2 * Copyright (c) 2001-2019 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 "plugin_shared.h"
90 #include "InterfaceNamerControlPrefs.h"
91 #endif // !TARGET_OS_IPHONE
93 #include <IOKit/IOKitLib.h>
94 #include <IOKit/IOKitLibPrivate.h>
95 #include <IOKit/IOKitKeysPrivate.h>
96 #include <IOKit/IOBSD.h>
97 #include <IOKit/IOMessage.h>
98 #include <IOKit/network/IONetworkController.h>
99 #include <IOKit/network/IONetworkInterface.h>
100 #include <IOKit/network/IONetworkStack.h>
101 #include <IOKit/usb/USB.h>
103 #ifdef kIONetworkStackUserCommandKey
104 #define USE_REGISTRY_ENTRY_ID
107 #ifndef USE_REGISTRY_ENTRY_ID
108 // from <IOKit/network/IONetworkStack.h>
109 #define kIONetworkStackUserCommandKey "IONetworkStackUserCommand"
111 kRegisterInterfaceWithFixedUnit
= 0,
113 kRegisterAllInterfaces
115 #endif // !USE_REGISTRY_ENTRY_ID
117 #define kSCNetworkInterfaceActive "Active"
118 #define kSCNetworkInterfaceInfo "SCNetworkInterfaceInfo"
119 #define kSCNetworkInterfaceType "SCNetworkInterfaceType"
120 #define kSCNetworkInterfaceMatchingMACs "MatchingMACs"
122 #define MY_PLUGIN_NAME "InterfaceNamer"
123 #define MY_PLUGIN_ID CFSTR("com.apple.SystemConfiguration." MY_PLUGIN_NAME)
125 #define WAIT_STACK_TIMEOUT_KEY "WaitStackTimeout"
126 #define WAIT_STACK_TIMEOUT_DEFAULT 300.0
128 #define WAIT_QUIET_TIMEOUT_KEY "WaitQuietTimeout"
129 #define WAIT_QUIET_TIMEOUT_DEFAULT 240.0
133 * "IONetworkStack" connect object used to "name" an interface.
135 static io_connect_t S_connect
= MACH_PORT_NULL
;
139 * An array of CFDictionary's representing the interfaces
140 * that have been identified and [need to be] named.
142 static CFMutableArrayRef S_dblist
= NULL
;
146 * An array of SCNetworkInterface's representing the
147 * interfaces that have been identified.
149 static CFMutableArrayRef S_iflist
= NULL
;
153 * IOServiceAddMatchingNotification object used to watch for
154 * new network interfaces.
156 static io_iterator_t S_iter
= MACH_PORT_NULL
;
158 #if !TARGET_OS_IPHONE
161 * An array of CFData(WatchedInfo) objects representing those
162 * interfaces that have been connected to the system while
165 static CFMutableArrayRef S_locked
= NULL
;
166 #endif // !TARGET_OS_IPHONE
170 * notification object for receiving IOKit notifications of
171 * new devices or state changes.
173 static IONotificationPortRef S_notify
= NULL
;
177 * An array of CFData(WatchedInfo) objects representing those
178 * pre-configured interfaces that have been connected to the
181 static CFMutableArrayRef S_preconfigured
= NULL
;
183 /* S_prev_active_list
184 * An array of CFDictionary's representing the previously
187 static CFMutableArrayRef S_prev_active_list
= NULL
;
191 * IOServiceAddInterestNotification object used to watch for
192 * IOKit matching to quiesce.
194 static io_object_t S_quiet
= MACH_PORT_NULL
;
198 * IOServiceAddMatchingNotification object used to watch for
199 * the availability of the "IONetworkStack" object.
201 static io_iterator_t S_stack
= MACH_PORT_NULL
;
205 * A dictionary containing Information about each network
206 * interface. For now, the key is the BSD name and the
207 * value is a CFNumber noting how long (in milliseconds)
208 * it took for the interface to be recognized/named.
210 static CFMutableDictionaryRef S_state
= NULL
;
214 * S_trustedHostAttached
216 * Note: this global must only be updated on trustRequired_queue()
218 static Boolean S_trustedHostAttached
= FALSE
;
222 * Note: this global must only be updated on trustRequired_queue()
224 static CFIndex S_trustedHostCount
= 0;
228 * An array of CFData(WatchedInfo) objects representing those
229 * interfaces that require [lockdownd] trust.
231 static CFMutableArrayRef S_trustRequired
= NULL
;
232 #endif // TARGET_OS_IPHONE
236 * CFRunLoopTimer tracking how long we are willing to wait
237 * for IOKit matching to quiesce (IOKitWaitQuiet).
240 * time to wait for the IONetworkStack object to appear before timeout
243 * time to wait for the IOKit to quiesce (after the IONetworkStack is
246 static CFRunLoopTimerRef S_timer
= NULL
;
247 static double S_stack_timeout
= WAIT_STACK_TIMEOUT_DEFAULT
;
248 static double S_quiet_timeout
= WAIT_QUIET_TIMEOUT_DEFAULT
;
251 * Virtual network interface configuration
252 * S_prefs : SCPreferences to configuration
253 * S_bonds : most recently actived Bond configuration
254 * S_bridges : most recently actived Bridge configuration
255 * S_vlans : most recently actived VLAN configuration
257 static SCPreferencesRef S_prefs
= NULL
;
258 static CFArrayRef S_bonds
= NULL
;
259 static CFArrayRef S_bridges
= NULL
;
260 static CFArrayRef S_vlans
= NULL
;
267 __log_InterfaceNamer(void)
269 static os_log_t log
= NULL
;
272 log
= os_log_create("com.apple.SystemConfiguration", "InterfaceNamer");
280 addTimestamp(CFMutableDictionaryRef dict
, CFStringRef key
)
285 now
= CFAbsoluteTimeGetCurrent();
286 val
= CFNumberCreate(NULL
, kCFNumberDoubleType
, &now
);
287 CFDictionaryAddValue(dict
, key
, val
);
292 #define INTERFACES CFSTR("Interfaces")
293 #define NETWORK_INTERFACES_PREFS CFSTR("NetworkInterfaces.plist")
295 static CFComparisonResult
296 if_unit_compare(const void *val1
, const void *val2
, void *context
)
298 #pragma unused(context)
299 CFComparisonResult res
;
305 type1
= CFDictionaryGetValue((CFDictionaryRef
)val1
,
306 CFSTR(kIOInterfaceType
));
307 type2
= CFDictionaryGetValue((CFDictionaryRef
)val2
,
308 CFSTR(kIOInterfaceType
));
309 res
= CFNumberCompare(type1
, type2
, NULL
);
310 if (res
!= kCFCompareEqualTo
) {
313 unit1
= CFDictionaryGetValue((CFDictionaryRef
)val1
,
314 CFSTR(kIOInterfaceUnit
));
315 unit2
= CFDictionaryGetValue((CFDictionaryRef
)val2
,
316 CFSTR(kIOInterfaceUnit
));
317 return (CFNumberCompare(unit1
, unit2
, NULL
));
321 writeInterfaceList(CFArrayRef if_list
)
324 CFStringRef new_model
;
325 CFStringRef old_model
;
326 SCPreferencesRef prefs
;
328 if (isA_CFArray(if_list
) == NULL
) {
332 prefs
= SCPreferencesCreate(NULL
, CFSTR(MY_PLUGIN_NAME
":writeInterfaceList"), NETWORK_INTERFACES_PREFS
);
334 SC_log(LOG_NOTICE
, "SCPreferencesCreate() failed: %s", SCErrorString(SCError()));
338 cur_list
= SCPreferencesGetValue(prefs
, INTERFACES
);
339 if (_SC_CFEqual(cur_list
, if_list
)) {
343 old_model
= SCPreferencesGetValue(prefs
, MODEL
);
344 new_model
= _SC_hw_model(FALSE
);
345 if ((new_model
!= NULL
) && !_SC_CFEqual(old_model
, new_model
)) {
347 if ((old_model
!= NULL
) && (cur_list
!= NULL
)) {
350 // if interface list was created on other hardware
351 history
= CFStringCreateWithFormat(NULL
, NULL
,
355 SCPreferencesSetValue(prefs
, history
, cur_list
);
358 SC_log(LOG_NOTICE
, "Hardware model changed\n"
359 " created on \"%@\"\n"
365 SCPreferencesSetValue(prefs
, MODEL
, new_model
);
368 SCPreferencesSetValue(prefs
, INTERFACES
, if_list
);
370 if (!SCPreferencesCommitChanges(prefs
)) {
371 if (SCError() != EROFS
) {
372 SC_log(LOG_NOTICE
, "SCPreferencesCommitChanges() failed: %s", SCErrorString(SCError()));
383 static CFPropertyListRef
384 restoreNIPrefsFromBackup(SCPreferencesRef prefs
, CFStringRef current_model
)
386 CFPropertyListRef if_list
;
389 key
= CFStringCreateWithFormat(NULL
, 0, CFSTR("%@:%@"), INTERFACES
, current_model
);
390 if_list
= SCPreferencesGetValue(prefs
, key
);
391 if_list
= isA_CFArray(if_list
);
392 if (if_list
!= NULL
) {
393 /* Write the previously backed up Interface list for this hardware */
394 writeInterfaceList(if_list
);
396 /* Synchronize the prefs */
397 SCPreferencesSynchronize(prefs
);
399 /* Re-fetch the interface list */
400 if_list
= SCPreferencesGetValue(prefs
, INTERFACES
);
401 if_list
= isA_CFArray(if_list
);
402 if (if_list
!= NULL
) {
403 /* We do not need the old interface list any more */
404 SCPreferencesRemoveValue(prefs
, key
);
405 if (!SCPreferencesCommitChanges(prefs
)) {
406 if (SCError() != EROFS
) {
407 SC_log(LOG_NOTICE
, "SCPreferencesCommitChanges() failed: %s", SCErrorString(SCError()));
418 static CF_RETURNS_RETAINED CFMutableArrayRef
422 CFStringRef old_model
;
423 CFMutableArrayRef plist
= NULL
;
424 SCPreferencesRef prefs
= NULL
;
426 prefs
= SCPreferencesCreate(NULL
, CFSTR(MY_PLUGIN_NAME
":readInterfaceList"), NETWORK_INTERFACES_PREFS
);
428 SC_log(LOG_NOTICE
, "SCPreferencesCreate() failed: %s", SCErrorString(SCError()));
432 if_list
= SCPreferencesGetValue(prefs
, INTERFACES
);
433 if_list
= isA_CFArray(if_list
);
435 old_model
= SCPreferencesGetValue(prefs
, MODEL
);
436 if (old_model
!= NULL
) {
437 CFStringRef new_model
;
439 new_model
= _SC_hw_model(FALSE
);
440 if (!_SC_CFEqual(old_model
, new_model
)) {
441 /* if interface list was created on other hardware,
442 Restore if a backup interface list is present */
443 if_list
= restoreNIPrefsFromBackup(prefs
, new_model
);
447 if (if_list
!= NULL
) {
449 CFIndex n
= CFArrayGetCount(if_list
);
451 plist
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
452 for (i
= 0; i
< n
; i
++) {
453 CFDictionaryRef dict
;
455 dict
= CFArrayGetValueAtIndex(if_list
, i
);
456 if (isA_CFDictionary(dict
) &&
457 CFDictionaryContainsKey(dict
, CFSTR(kIOInterfaceType
)) &&
458 CFDictionaryContainsKey(dict
, CFSTR(kIOInterfaceUnit
)) &&
459 CFDictionaryContainsKey(dict
, CFSTR(kIOMACAddress
))) {
460 CFArrayAppendValue(plist
, dict
);
471 static CF_RETURNS_RETAINED CFMutableArrayRef
472 previouslyActiveInterfaces()
474 CFMutableArrayRef active
;
478 if (S_dblist
== NULL
) {
482 active
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
484 n
= CFArrayGetCount(S_dblist
);
485 for (i
= 0; i
< n
; i
++) {
486 CFDictionaryRef if_dict
;
488 if_dict
= CFArrayGetValueAtIndex(S_dblist
, i
);
489 if (CFDictionaryContainsKey(if_dict
, CFSTR(kSCNetworkInterfaceActive
))) {
490 CFMutableDictionaryRef new_dict
;
492 new_dict
= CFDictionaryCreateMutableCopy(NULL
, 0, if_dict
);
493 CFDictionaryRemoveValue(new_dict
, CFSTR(kSCNetworkInterfaceActive
));
494 CFArraySetValueAtIndex(S_dblist
, i
, new_dict
);
495 CFArrayAppendValue(active
, new_dict
);
504 updateInterfaces(void);
511 key
= SCDynamicStoreKeyCreate(NULL
, CFSTR("%@" MY_PLUGIN_NAME
), kSCDynamicStoreDomainPlugin
);
512 (void)SCDynamicStoreSetValue(NULL
, key
, S_state
);
518 #if !TARGET_OS_IPHONE
520 updateBondInterfaceConfiguration(SCPreferencesRef prefs
)
522 CFArrayRef interfaces
;
524 interfaces
= SCBondInterfaceCopyAll(prefs
);
525 if ((interfaces
!= NULL
) && (CFArrayGetCount(interfaces
) == 0)) {
526 CFRelease(interfaces
);
530 if (_SC_CFEqual(S_bonds
, interfaces
)) {
532 if (interfaces
!= NULL
) CFRelease(interfaces
);
536 if (S_bonds
!= NULL
) CFRelease(S_bonds
);
537 S_bonds
= interfaces
;
539 if (!_SCBondInterfaceUpdateConfiguration(prefs
)) {
540 SC_log(LOG_NOTICE
, "_SCBondInterfaceUpdateConfiguration() failed: %s",
541 SCErrorString(SCError()));
546 #endif // !TARGET_OS_IPHONE
549 updateBridgeInterfaceConfiguration(SCPreferencesRef prefs
)
551 CFArrayRef interfaces
;
553 interfaces
= SCBridgeInterfaceCopyAll(prefs
);
554 if ((interfaces
!= NULL
) && (CFArrayGetCount(interfaces
) == 0)) {
555 CFRelease(interfaces
);
559 if (_SC_CFEqual(S_bridges
, interfaces
)) {
561 if (interfaces
!= NULL
) CFRelease(interfaces
);
565 if (S_bridges
!= NULL
) CFRelease(S_bridges
);
566 S_bridges
= interfaces
;
568 if (!_SCBridgeInterfaceUpdateConfiguration(prefs
)) {
569 SC_log(LOG_NOTICE
, "_SCBridgeInterfaceUpdateConfiguration() failed: %s",
570 SCErrorString(SCError()));
577 updateVLANInterfaceConfiguration(SCPreferencesRef prefs
)
579 CFArrayRef interfaces
;
581 interfaces
= SCVLANInterfaceCopyAll(prefs
);
582 if ((interfaces
!= NULL
) && (CFArrayGetCount(interfaces
) == 0)) {
583 CFRelease(interfaces
);
587 if (_SC_CFEqual(S_vlans
, interfaces
)) {
589 if (interfaces
!= NULL
) CFRelease(interfaces
);
593 if (S_vlans
!= NULL
) CFRelease(S_vlans
);
594 S_vlans
= interfaces
;
596 if (!_SCVLANInterfaceUpdateConfiguration(prefs
)) {
597 SC_log(LOG_NOTICE
, "_SCVLANInterfaceUpdateConfiguration() failed: %s",
598 SCErrorString(SCError()));
605 updateVirtualNetworkInterfaceConfiguration(SCPreferencesRef prefs
,
606 SCPreferencesNotification notificationType
,
610 if ((notificationType
& kSCPreferencesNotificationApply
) != kSCPreferencesNotificationApply
) {
615 // if a new interface has been "named"
617 if (S_bonds
!= NULL
) {
621 if (S_bridges
!= NULL
) {
622 CFRelease(S_bridges
);
625 if (S_vlans
!= NULL
) {
631 #if !TARGET_OS_IPHONE
632 updateBondInterfaceConfiguration (prefs
);
633 #endif // !TARGET_OS_IPHONE
634 updateBridgeInterfaceConfiguration(prefs
);
635 updateVLANInterfaceConfiguration (prefs
);
637 // we are finished with current prefs, wait for changes
638 SCPreferencesSynchronize(prefs
);
646 updateBTPANInformation(const void *value
, void *context
)
648 #pragma unused(context)
650 CFDictionaryRef dict
= (CFDictionaryRef
)value
;
652 CFDictionaryRef info
;
655 if_name
= CFDictionaryGetValue(dict
, CFSTR(kIOBSDNameKey
));
656 if (!isA_CFString(if_name
)) {
661 info
= CFDictionaryGetValue(dict
, CFSTR(kSCNetworkInterfaceInfo
));
662 if (!isA_CFDictionary(info
)) {
663 // if no SCNetworkInterface info
667 name
= CFDictionaryGetValue(info
, kSCPropUserDefinedName
);
668 if (!isA_CFString(name
) || !CFEqual(name
, CFSTR(BT_PAN_NAME
))) {
669 // if not BT-PAN interface
673 CFDictionaryAddValue(S_state
, kInterfaceNamerKey_BT_PAN_Name
, if_name
);
675 addr
= CFDictionaryGetValue(dict
, CFSTR(kIOMACAddress
));
676 if (isA_CFData(addr
)) {
677 CFDictionaryAddValue(S_state
, kInterfaceNamerKey_BT_PAN_Mac
, addr
);
682 #endif // TARGET_OS_OSX
684 static CFDictionaryRef
685 createInterfaceDict(SCNetworkInterfaceRef interface
, CFArrayRef matchingMACs
)
687 CFMutableDictionaryRef new_if
;
690 new_if
= CFDictionaryCreateMutable(NULL
,
692 &kCFTypeDictionaryKeyCallBacks
,
693 &kCFTypeDictionaryValueCallBacks
);
695 val
= _SCNetworkInterfaceCopyInterfaceInfo(interface
);
697 CFDictionarySetValue(new_if
, CFSTR(kSCNetworkInterfaceInfo
), val
);
701 val
= _SCNetworkInterfaceGetIOPath(interface
);
703 CFDictionarySetValue(new_if
, CFSTR(kIOPathMatchKey
), val
);
706 val
= _SCNetworkInterfaceGetIOInterfaceNamePrefix(interface
);
708 CFDictionarySetValue(new_if
, CFSTR(kIOInterfaceNamePrefix
), val
);
711 val
= _SCNetworkInterfaceGetIOInterfaceType(interface
);
713 CFDictionarySetValue(new_if
, CFSTR(kIOInterfaceType
), val
);
716 val
= _SCNetworkInterfaceGetIOInterfaceUnit(interface
);
718 CFDictionarySetValue(new_if
, CFSTR(kIOInterfaceUnit
), val
);
721 val
= _SCNetworkInterfaceGetHardwareAddress(interface
);
723 CFDictionarySetValue(new_if
, CFSTR(kIOMACAddress
), val
);
726 val
= SCNetworkInterfaceGetBSDName(interface
);
728 CFDictionarySetValue(new_if
, CFSTR(kIOBSDNameKey
), val
);
731 val
= SCNetworkInterfaceGetInterfaceType(interface
);
733 CFDictionarySetValue(new_if
, CFSTR(kSCNetworkInterfaceType
), val
);
736 CFDictionarySetValue(new_if
,
738 _SCNetworkInterfaceIsBuiltin(interface
) ? kCFBooleanTrue
: kCFBooleanFalse
);
740 CFDictionarySetValue(new_if
, CFSTR(kSCNetworkInterfaceActive
), kCFBooleanTrue
);
742 if (matchingMACs
!= NULL
) {
743 CFDictionarySetValue(new_if
, CFSTR(kSCNetworkInterfaceMatchingMACs
), matchingMACs
);
749 static CFDictionaryRef
750 lookupInterfaceByAddress(CFArrayRef db_list
, SCNetworkInterfaceRef interface
, CFIndex
* where
)
757 if (db_list
== NULL
) {
760 type
= _SCNetworkInterfaceGetIOInterfaceType(interface
);
761 addr
= _SCNetworkInterfaceGetHardwareAddress(interface
);
762 if (type
== NULL
|| addr
== NULL
) {
766 n
= CFArrayGetCount(db_list
);
767 for (i
= 0; i
< n
; i
++) {
769 CFDictionaryRef dict
= CFArrayGetValueAtIndex(db_list
, i
);
772 t
= CFDictionaryGetValue(dict
, CFSTR(kIOInterfaceType
));
773 a
= CFDictionaryGetValue(dict
, CFSTR(kIOMACAddress
));
774 if (t
== NULL
|| a
== NULL
)
777 if (CFEqual(type
, t
) && CFEqual(addr
, a
)) {
787 static CFDictionaryRef
788 lookupInterfaceByUnit(CFArrayRef db_list
, SCNetworkInterfaceRef interface
, CFIndex
* where
)
795 if (db_list
== NULL
) {
798 type
= _SCNetworkInterfaceGetIOInterfaceType(interface
);
799 unit
= _SCNetworkInterfaceGetIOInterfaceUnit(interface
);
800 if (type
== NULL
|| unit
== NULL
) {
804 n
= CFArrayGetCount(db_list
);
805 for (i
= 0; i
< n
; i
++) {
806 CFDictionaryRef dict
= CFArrayGetValueAtIndex(db_list
, i
);
810 t
= CFDictionaryGetValue(dict
, CFSTR(kIOInterfaceType
));
811 u
= CFDictionaryGetValue(dict
, CFSTR(kIOInterfaceUnit
));
812 if (t
== NULL
|| u
== NULL
) {
816 if (CFEqual(type
, t
) && CFEqual(unit
, u
)) {
826 CFDictionaryRef match_info
;
827 CFStringRef match_type
;
828 CFBooleanRef match_builtin
;
829 CFMutableArrayRef matches
;
830 } matchContext
, *matchContextRef
;
832 static CF_RETURNS_RETAINED CFDictionaryRef
833 thinInterfaceInfo(CFDictionaryRef info
)
838 if (CFDictionaryGetValueIfPresent(info
, CFSTR(kUSBVendorID
), (const void **)&num
)
840 && CFNumberGetValue(num
, kCFNumberIntType
, &vid
)
841 && (vid
== kIOUSBVendorIDAppleComputer
)) {
842 CFMutableDictionaryRef thin
;
844 // if this is an Apple USB device than we trust that
845 // the non-localized name will be correct.
846 thin
= CFDictionaryCreateMutableCopy(NULL
, 0, info
);
847 CFDictionaryRemoveValue(thin
, CFSTR(kUSBProductString
));
848 CFDictionaryRemoveValue(thin
, CFSTR(kUSBVendorID
));
849 CFDictionaryRemoveValue(thin
, CFSTR(kUSBProductID
));
853 return CFRetain(info
);
857 matchInterfaceInfo(CFDictionaryRef known_info
, CFDictionaryRef match_info
)
861 match
= _SC_CFEqual(known_info
, match_info
);
863 isA_CFDictionary(known_info
) &&
864 isA_CFDictionary(match_info
)) {
866 // if not an exact match, try thinning
867 known_info
= thinInterfaceInfo(known_info
);
868 match_info
= thinInterfaceInfo(match_info
);
869 match
= _SC_CFEqual(known_info
, match_info
);
870 if (known_info
!= NULL
) CFRelease(known_info
);
871 if (match_info
!= NULL
) CFRelease(match_info
);
878 matchKnown(const void *value
, void *context
)
880 CFDictionaryRef known_dict
= (CFDictionaryRef
)value
;
881 matchContextRef match_context
= (matchContextRef
)context
;
883 // match interface type
885 CFStringRef known_type
;
887 known_type
= CFDictionaryGetValue(known_dict
, CFSTR(kSCNetworkInterfaceType
));
888 if (!_SC_CFEqual(known_type
, match_context
->match_type
)) {
893 // match SCNetworkInterfaceInfo
895 CFDictionaryRef known_info
;
897 known_info
= CFDictionaryGetValue(known_dict
, CFSTR(kSCNetworkInterfaceInfo
));
898 if (!matchInterfaceInfo(known_info
, match_context
->match_info
)) {
903 // if requested, match [non-]builtin
904 if (match_context
->match_builtin
!= NULL
) {
905 CFBooleanRef known_builtin
;
907 known_builtin
= CFDictionaryGetValue(known_dict
, CFSTR(kIOBuiltin
));
908 if (!isA_CFBoolean(known_builtin
)) {
909 known_builtin
= kCFBooleanFalse
;
911 if (!_SC_CFEqual(known_builtin
, match_context
->match_builtin
)) {
916 // if we have a match
917 if (match_context
->matches
== NULL
) {
918 match_context
->matches
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
920 CFArrayAppendValue(match_context
->matches
, known_dict
);
926 matchUnnamed(const void *value
, void *context
)
928 SCNetworkInterfaceRef known_if
= (SCNetworkInterfaceRef
)value
;
929 matchContextRef match_context
= (matchContextRef
)context
;
931 if (match_context
->matches
== NULL
) {
935 // match interface type
937 CFStringRef known_type
;
939 known_type
= SCNetworkInterfaceGetInterfaceType(known_if
);
940 if (!_SC_CFEqual(known_type
, match_context
->match_type
)) {
945 // match SCNetworkInterfaceInfo
947 CFDictionaryRef known_info
;
950 known_info
= _SCNetworkInterfaceCopyInterfaceInfo(known_if
);
951 match
= matchInterfaceInfo(known_info
, match_context
->match_info
);
952 if (known_info
!= NULL
) CFRelease(known_info
);
958 // if requested, match [non-]builtin
959 if (match_context
->match_builtin
!= NULL
) {
960 CFBooleanRef known_builtin
;
962 known_builtin
= _SCNetworkInterfaceIsBuiltin(known_if
) ? kCFBooleanTrue
964 if (!_SC_CFEqual(known_builtin
, match_context
->match_builtin
)) {
969 // if we have a match
970 CFRelease(match_context
->matches
);
971 match_context
->matches
= NULL
;
977 interfaceExists(CFStringRef prefix
, CFNumberRef unit
)
979 Boolean found
= FALSE
;
980 CFDictionaryRef match_dict
;
981 CFStringRef match_keys
[2];
982 CFTypeRef match_vals
[2];
983 CFDictionaryRef matching
;
987 io_registry_entry_t entry
= MACH_PORT_NULL
;
988 io_iterator_t iterator
= MACH_PORT_NULL
;
990 mach_port_t masterPort
= MACH_PORT_NULL
;
992 kr
= IOMasterPort(bootstrap_port
, &masterPort
);
993 if (kr
!= KERN_SUCCESS
) {
994 SC_log(LOG_ERR
, "IOMasterPort returned 0x%x", kr
);
998 // look for kIONetworkInterface with matching prefix and unit
999 match_keys
[0] = CFSTR(kIOInterfaceNamePrefix
);
1000 match_vals
[0] = prefix
;
1001 match_keys
[1] = CFSTR(kIOInterfaceUnit
);
1002 match_vals
[1] = unit
;
1003 match_dict
= CFDictionaryCreate(NULL
,
1004 (const void **)match_keys
,
1005 (const void **)match_vals
,
1007 &kCFTypeDictionaryKeyCallBacks
,
1008 &kCFTypeDictionaryValueCallBacks
);
1010 match_keys
[0] = CFSTR(kIOProviderClassKey
);
1011 match_vals
[0] = CFSTR(kIONetworkInterfaceClass
);
1012 match_keys
[1] = CFSTR(kIOPropertyMatchKey
);
1013 match_vals
[1] = match_dict
;
1014 matching
= CFDictionaryCreate(NULL
,
1015 (const void **)match_keys
,
1016 (const void **)match_vals
,
1017 sizeof(match_keys
)/sizeof(match_keys
[0]),
1018 &kCFTypeDictionaryKeyCallBacks
,
1019 &kCFTypeDictionaryValueCallBacks
);
1020 CFRelease(match_dict
);
1022 // note: the "matching" dictionary will be consumed by the following
1023 kr
= IOServiceGetMatchingServices(masterPort
, matching
, &iterator
);
1024 if ((kr
!= kIOReturnSuccess
) || (iterator
== MACH_PORT_NULL
)) {
1029 entry
= IOIteratorNext(iterator
);
1030 if (entry
== MACH_PORT_NULL
) {
1038 if (masterPort
!= MACH_PORT_NULL
) {
1039 mach_port_deallocate(mach_task_self(), masterPort
);
1041 if (entry
!= MACH_PORT_NULL
) {
1042 IOObjectRelease(entry
);
1044 if (iterator
!= MACH_PORT_NULL
) {
1045 IOObjectRelease(iterator
);
1052 * lookupMatchingInterface
1054 * Looks at the interfaces that have already been [or need to be] named with
1055 * the goal of allowing a system using a single network interface/adaptor of
1056 * a given type (vendor, model, ...) to not care about the specific adaptor
1057 * that is used (i.e. swapping dongle's is OK). Once a system has had more
1058 * than one interface/adaptor connected at the same time than we assume that
1059 * the network configuration is being setup for multi-homing that should be
1062 * If no matches are found or if more than one match is found, return NULL.
1063 * If a single match is found, return the match.
1065 static CFDictionaryRef
1066 lookupMatchingInterface(SCNetworkInterfaceRef interface
,
1067 CFArrayRef db_list
, // already named
1068 CFArrayRef if_list
, // to be named
1069 CFIndex if_list_index
,
1070 CFBooleanRef builtin
)
1072 CFStringRef if_type
;
1073 CFDictionaryRef match
= NULL
;
1074 matchContext match_context
;
1076 if_type
= SCNetworkInterfaceGetInterfaceType(interface
);
1077 if (if_type
== NULL
) {
1081 match_context
.match_type
= if_type
;
1082 match_context
.match_info
= _SCNetworkInterfaceCopyInterfaceInfo(interface
);
1083 match_context
.match_builtin
= builtin
;
1084 match_context
.matches
= NULL
;
1086 // check for matches to interfaces that have already been named
1087 // ... and append each match that we find to match_context.matches
1088 if (db_list
!= NULL
) {
1089 CFArrayApplyFunction(db_list
,
1090 CFRangeMake(0, CFArrayGetCount(db_list
)),
1095 // check for matches to interfaces that will be named
1096 // ... and CFRelease match_context.matches if we find another network
1097 // interface of the same type that also needs to be named
1098 if (if_list
!= NULL
) {
1099 CFIndex if_list_count
;
1101 if_list_count
= CFArrayGetCount(if_list
);
1102 if (if_list_index
< if_list_count
) {
1103 CFArrayApplyFunction(if_list
,
1104 CFRangeMake(if_list_index
, if_list_count
- if_list_index
),
1110 // check if we have a single match
1111 if (match_context
.matches
!= NULL
) {
1112 if (CFArrayGetCount(match_context
.matches
) == 1) {
1113 match
= CFArrayGetValueAtIndex(match_context
.matches
, 0);
1115 CFRelease(match_context
.matches
);
1118 if (match
!= NULL
) {
1119 Boolean active
= TRUE
;
1122 name
= CFDictionaryGetValue(match
, CFSTR(kIOBSDNameKey
));
1123 if (isA_CFString(name
)) {
1127 prefix
= CFDictionaryGetValue(match
, CFSTR(kIOInterfaceNamePrefix
));
1128 unit
= CFDictionaryGetValue(match
, CFSTR(kIOInterfaceUnit
));
1129 if (isA_CFString(prefix
) && isA_CFNumber(unit
)) {
1130 if (!interfaceExists(prefix
, unit
)) {
1141 if (match_context
.match_info
!= NULL
) CFRelease(match_context
.match_info
);
1146 insertInterface(CFMutableArrayRef db_list
, SCNetworkInterfaceRef interface
, CFDictionaryRef db_dict_match
)
1149 CFDictionaryRef if_dict
;
1150 CFStringRef if_name
;
1151 CFNumberRef if_type
;
1152 CFNumberRef if_unit
;
1153 CFArrayRef matchingMACs
= NULL
;
1154 CFIndex n
= CFArrayGetCount(db_list
);
1155 CFComparisonResult res
;
1157 if_name
= SCNetworkInterfaceGetBSDName(interface
);
1158 if (if_name
!= NULL
) {
1159 addTimestamp(S_state
, if_name
);
1162 if (!_SCNetworkInterfaceIsBuiltin(interface
) && (db_dict_match
!= NULL
)) {
1166 matchingMACs
= CFDictionaryGetValue(db_dict_match
, CFSTR(kSCNetworkInterfaceMatchingMACs
));
1167 if (matchingMACs
!= NULL
) {
1168 CFRetain(matchingMACs
);
1171 addr_old
= CFDictionaryGetValue(db_dict_match
, CFSTR(kIOMACAddress
));
1172 addr_cur
= _SCNetworkInterfaceGetHardwareAddress(interface
);
1173 if ((addr_old
!= NULL
) && (addr_cur
!= NULL
) && !CFEqual(addr_old
, addr_cur
)) {
1174 CFMutableArrayRef matching_new
;
1176 // if MAC address changed, add previous MAC to history
1177 if (matchingMACs
!= NULL
) {
1178 matching_new
= CFArrayCreateMutableCopy(NULL
, 0, matchingMACs
);
1179 CFRelease(matchingMACs
);
1181 // remove duplicates of the now current MAC from history
1182 i
= CFArrayGetFirstIndexOfValue(matching_new
, CFRangeMake(0, CFArrayGetCount(matching_new
)), addr_cur
);
1183 if (i
!= kCFNotFound
) {
1184 CFArrayRemoveValueAtIndex(matching_new
, i
);
1187 // remove duplicates of the previous MAC from history before re-inserting
1188 i
= CFArrayGetFirstIndexOfValue(matching_new
, CFRangeMake(0, CFArrayGetCount(matching_new
)), addr_old
);
1189 if (i
!= kCFNotFound
) {
1190 CFArrayRemoveValueAtIndex(matching_new
, i
);
1193 matching_new
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
1195 CFArrayInsertValueAtIndex(matching_new
, 0, addr_old
);
1197 // limit history size
1198 #define MATCHING_HISTORY_MAXLEN 32
1199 for (i
= CFArrayGetCount(matching_new
); i
> MATCHING_HISTORY_MAXLEN
; i
--) {
1200 CFArrayRemoveValueAtIndex(matching_new
, i
- 1);
1203 matchingMACs
= matching_new
;
1207 if_dict
= createInterfaceDict(interface
, matchingMACs
);
1208 if (matchingMACs
!= NULL
) {
1209 CFRelease(matchingMACs
);
1212 if_type
= _SCNetworkInterfaceGetIOInterfaceType(interface
);
1213 if_unit
= _SCNetworkInterfaceGetIOInterfaceUnit(interface
);
1214 if ((if_type
== NULL
) || (if_unit
== NULL
)) {
1219 for (i
= 0; i
< n
; i
++) {
1220 CFNumberRef db_type
;
1221 CFNumberRef db_unit
;
1222 CFDictionaryRef dict
= CFArrayGetValueAtIndex(db_list
, i
);
1224 db_type
= CFDictionaryGetValue(dict
, CFSTR(kIOInterfaceType
));
1225 db_unit
= CFDictionaryGetValue(dict
, CFSTR(kIOInterfaceUnit
));
1226 res
= CFNumberCompare(if_type
, db_type
, NULL
);
1227 if (res
== kCFCompareLessThan
1228 || (res
== kCFCompareEqualTo
1229 && (CFNumberCompare(if_unit
, db_unit
, NULL
)
1230 == kCFCompareLessThan
))) {
1231 CFArrayInsertValueAtIndex(db_list
, i
, if_dict
);
1237 CFArrayAppendValue(S_dblist
, if_dict
);
1240 updateBTPANInformation(if_dict
, NULL
);
1241 #endif // TARGET_OS_OSX
1248 replaceInterface(SCNetworkInterfaceRef interface
)
1250 CFDictionaryRef db_dict
;
1251 CFDictionaryRef db_dict_match
= NULL
;
1255 if (S_dblist
== NULL
) {
1256 S_dblist
= CFArrayCreateMutable(NULL
, 0,
1257 &kCFTypeArrayCallBacks
);
1260 // remove any dict that has our type/addr
1262 db_dict
= lookupInterfaceByAddress(S_dblist
, interface
, &where
);
1263 if (db_dict
== NULL
) {
1266 if (db_dict_match
== NULL
) {
1267 db_dict_match
= CFRetain(db_dict
);
1269 CFArrayRemoveValueAtIndex(S_dblist
, where
);
1273 // remove any dict that has the same type/unit
1275 db_dict
= lookupInterfaceByUnit(S_dblist
, interface
, &where
);
1276 if (db_dict
== NULL
) {
1279 if (db_dict_match
== NULL
) {
1280 db_dict_match
= CFRetain(db_dict
);
1282 CFArrayRemoveValueAtIndex(S_dblist
, where
);
1286 insertInterface(S_dblist
, interface
, db_dict_match
);
1287 if (db_dict_match
!= NULL
) {
1288 CFRelease(db_dict_match
);
1292 SC_log(LOG_ERR
, "Multiple interfaces updated (n = %d, %@)", n
, interface
);
1299 getHighestUnitForType(CFNumberRef if_type
)
1303 CFNumberRef ret_unit
= NULL
;
1305 if (S_dblist
== NULL
) {
1309 n
= CFArrayGetCount(S_dblist
);
1310 for (i
= 0; i
< n
; i
++) {
1311 CFDictionaryRef dict
= CFArrayGetValueAtIndex(S_dblist
, i
);
1314 type
= CFDictionaryGetValue(dict
, CFSTR(kIOInterfaceType
));
1315 if (CFEqual(type
, if_type
)) {
1318 unit
= CFDictionaryGetValue(dict
, CFSTR(kIOInterfaceUnit
));
1319 if (ret_unit
== NULL
1320 || (CFNumberCompare(unit
, ret_unit
, NULL
)
1321 == kCFCompareGreaterThan
)) {
1331 * Function: ensureInterfaceHasUnit
1333 * Ensure that the SCNetworkInterfaceRef has a unit number. If it doesn't,
1334 * release the interface and return NULL.
1336 static SCNetworkInterfaceRef
1337 ensureInterfaceHasUnit(SCNetworkInterfaceRef net_if
)
1340 && _SCNetworkInterfaceGetIOInterfaceUnit(net_if
) == NULL
) {
1347 #ifdef USE_REGISTRY_ENTRY_ID
1348 static kern_return_t
1349 registerInterfaceWithIORegistryEntryID(io_connect_t connect
,
1355 CFMutableDictionaryRef dict
;
1359 dict
= CFDictionaryCreateMutable(NULL
, 0,
1360 &kCFTypeDictionaryKeyCallBacks
,
1361 &kCFTypeDictionaryValueCallBacks
);
1362 num
= CFNumberCreate(NULL
, kCFNumberIntType
, &command
);
1363 CFDictionarySetValue(dict
, CFSTR(kIONetworkStackUserCommandKey
), num
);
1365 data
= CFDataCreate(NULL
, (void *) &entryID
, sizeof(entryID
));
1366 CFDictionarySetValue(dict
, CFSTR(kIORegistryEntryIDKey
), data
);
1368 CFDictionarySetValue(dict
, CFSTR(kIOInterfaceUnit
), unit
);
1369 kr
= IOConnectSetCFProperties(connect
, dict
);
1374 static SCNetworkInterfaceRef
1375 copyInterfaceForIORegistryEntryID(uint64_t entryID
)
1377 io_registry_entry_t entry
= MACH_PORT_NULL
;
1378 SCNetworkInterfaceRef interface
= NULL
;
1379 io_iterator_t iterator
= MACH_PORT_NULL
;
1381 mach_port_t masterPort
= MACH_PORT_NULL
;
1383 kr
= IOMasterPort(bootstrap_port
, &masterPort
);
1384 if (kr
!= KERN_SUCCESS
) {
1385 SC_log(LOG_ERR
, "IOMasterPort returned 0x%x", kr
);
1389 kr
= IOServiceGetMatchingServices(masterPort
,
1390 IORegistryEntryIDMatching(entryID
),
1392 if ((kr
!= KERN_SUCCESS
) || (iterator
== MACH_PORT_NULL
)) {
1393 SC_log(LOG_NOTICE
, "IOServiceGetMatchingServices(0x%llx) returned 0x%x/%d",
1400 entry
= IOIteratorNext(iterator
);
1401 if (entry
== MACH_PORT_NULL
) {
1402 SC_log(LOG_NOTICE
, "IORegistryEntryIDMatching(0x%llx) failed", entryID
);
1406 interface
= _SCNetworkInterfaceCreateWithIONetworkInterfaceObject(entry
);
1409 if (masterPort
!= MACH_PORT_NULL
) {
1410 mach_port_deallocate(mach_task_self(), masterPort
);
1412 if (entry
!= MACH_PORT_NULL
) {
1413 IOObjectRelease(entry
);
1415 if (iterator
!= MACH_PORT_NULL
) {
1416 IOObjectRelease(iterator
);
1421 static SCNetworkInterfaceRef
1422 copyNamedInterfaceForIORegistryEntryID(uint64_t entryID
)
1424 SCNetworkInterfaceRef net_if
;
1426 net_if
= copyInterfaceForIORegistryEntryID(entryID
);
1427 return (ensureInterfaceHasUnit(net_if
));
1430 #else // USE_REGISTRY_ENTRY_ID
1432 * Function: registerInterface
1434 * Register a single interface with the given service path to the
1435 * data link layer (BSD), using the specified unit number.
1437 static kern_return_t
1438 registerInterfaceWithIOServicePath(io_connect_t connect
,
1443 CFMutableDictionaryRef dict
;
1447 dict
= CFDictionaryCreateMutable(NULL
, 0,
1448 &kCFTypeDictionaryKeyCallBacks
,
1449 &kCFTypeDictionaryValueCallBacks
);
1450 num
= CFNumberCreate(NULL
, kCFNumberIntType
, &command
);
1451 CFDictionarySetValue(dict
, CFSTR(kIONetworkStackUserCommandKey
), num
);
1453 CFDictionarySetValue(dict
, CFSTR(kIOPathMatchKey
), path
);
1454 CFDictionarySetValue(dict
, CFSTR(kIOInterfaceUnit
), unit
);
1455 kr
= IOConnectSetCFProperties(connect
, dict
);
1460 static SCNetworkInterfaceRef
1461 copyInterfaceForIOKitPath(CFStringRef if_path
)
1463 io_registry_entry_t entry
= MACH_PORT_NULL
;
1464 SCNetworkInterfaceRef interface
= NULL
;
1466 mach_port_t masterPort
= MACH_PORT_NULL
;
1469 kr
= IOMasterPort(bootstrap_port
, &masterPort
);
1470 if (kr
!= KERN_SUCCESS
) {
1471 SC_log(LOG_ERR
, "IOMasterPort returned 0x%x", kr
);
1474 _SC_cfstring_to_cstring(if_path
, path
, sizeof(path
), kCFStringEncodingASCII
);
1475 entry
= IORegistryEntryFromPath(masterPort
, path
);
1476 if (entry
== MACH_PORT_NULL
) {
1477 SC_log(LOG_NOTICE
, "IORegistryEntryFromPath(%@) failed", if_path
);
1481 interface
= _SCNetworkInterfaceCreateWithIONetworkInterfaceObject(entry
);
1484 if (masterPort
!= MACH_PORT_NULL
) {
1485 mach_port_deallocate(mach_task_self(), masterPort
);
1487 if (entry
!= MACH_PORT_NULL
) {
1488 IOObjectRelease(entry
);
1494 static SCNetworkInterfaceRef
1495 copyNamedInterfaceForIOKitPath(CFStringRef if_path
)
1497 SCNetworkInterfaceRef net_if
;
1499 net_if
= copyInterfaceForIOKitPath(if_path
);
1500 return (ensureInterfaceHasUnit(net_if
));
1503 #endif // USE_REGISTRY_ENTRY_ID
1506 displayInterface(SCNetworkInterfaceRef interface
)
1513 name
= SCNetworkInterfaceGetBSDName(interface
);
1514 unit
= _SCNetworkInterfaceGetIOInterfaceUnit(interface
);
1515 type
= _SCNetworkInterfaceGetIOInterfaceType(interface
);
1516 addr
= SCNetworkInterfaceGetHardwareAddressString(interface
);
1518 SC_log(LOG_INFO
, " %s%@%sType: %@, %s%@%sMAC address: %@",
1519 (name
!= NULL
) ? "BSD Name: " : "",
1520 (name
!= NULL
) ? name
: CFSTR(""),
1521 (name
!= NULL
) ? ", " : "",
1523 (unit
!= NULL
) ? "Unit: " : "",
1524 (unit
!= NULL
) ? (CFTypeRef
)unit
: (CFTypeRef
)CFSTR(""),
1525 (unit
!= NULL
) ? ", " : "",
1526 (addr
!= NULL
) ? addr
: CFSTR("?"));
1530 builtinAvailable(SCNetworkInterfaceRef interface
, // new interface
1531 CFNumberRef if_unit
) // desired unit
1534 CFNumberRef if_type
= _SCNetworkInterfaceGetIOInterfaceType(interface
);
1537 n
= (S_dblist
!= NULL
) ? CFArrayGetCount(S_dblist
) : 0;
1538 for (i
= 0; i
< n
; i
++) {
1539 CFStringRef if_path
;
1540 CFDictionaryRef known_dict
= CFArrayGetValueAtIndex(S_dblist
, i
);
1541 CFStringRef known_path
;
1542 CFNumberRef known_type
;
1543 CFNumberRef known_unit
;
1545 known_type
= CFDictionaryGetValue(known_dict
, CFSTR(kIOInterfaceType
));
1546 if (!_SC_CFEqual(if_type
, known_type
)) {
1547 continue; // if not the same interface type
1550 known_unit
= CFDictionaryGetValue(known_dict
, CFSTR(kIOInterfaceUnit
));
1551 if (!_SC_CFEqual(if_unit
, known_unit
)) {
1552 continue; // if not the same interface unit
1555 if_path
= _SCNetworkInterfaceGetIOPath(interface
);
1556 known_path
= CFDictionaryGetValue(known_dict
, CFSTR(kIOPathMatchKey
));
1557 if (!_SC_CFEqual(if_path
, known_path
)) {
1558 // if different IORegistry path
1562 // if same type, same unit, same path
1566 // if interface type/unit not found
1571 builtinCount(CFArrayRef if_list
, CFIndex last
, CFNumberRef if_type
)
1576 for (i
= 0; i
< last
; i
++) {
1577 SCNetworkInterfaceRef builtin_if
;
1578 CFNumberRef builtin_type
;
1580 builtin_if
= CFArrayGetValueAtIndex(if_list
, i
);
1581 builtin_type
= _SCNetworkInterfaceGetIOInterfaceType(builtin_if
);
1582 if (CFEqual(if_type
, builtin_type
)) {
1583 if (_SCNetworkInterfaceIsBuiltin(builtin_if
)) {
1584 n
++; // if built-in interface
1594 #pragma mark Interface monitoring (e.g. watch for "detach")
1597 typedef struct WatchedInfo
*WatchedInfoRef
;
1599 typedef void (*InterfaceUpdateCallBack
) (
1601 natural_t messageType
,
1602 void *messageArgument
1606 SCNetworkInterfaceRef interface
;
1607 io_service_t interface_node
;
1608 io_object_t notification
;
1609 InterfaceUpdateCallBack callback
;
1613 watcherRelease(CFDataRef watched
);
1616 updateWatchedInterface(void *refCon
, io_service_t service
, natural_t messageType
, void *messageArgument
)
1618 #pragma unused(service)
1619 #pragma unused(messageArgument)
1620 switch (messageType
) {
1621 case kIOMessageServiceIsTerminated
: { // if [watched] interface yanked
1622 CFDataRef watched
= (CFDataRef
)refCon
;
1623 WatchedInfo
*watchedInfo
= (WatchedInfo
*)(void *)CFDataGetBytePtr(watched
);
1626 watchedInfo
->callback(watched
, messageType
, messageArgument
);
1627 watcherRelease(watched
);
1640 watcherCreate(SCNetworkInterfaceRef interface
, InterfaceUpdateCallBack callback
)
1643 io_service_t interface_node
;
1645 CFDictionaryRef matching
;
1646 CFMutableDataRef watched
;
1647 WatchedInfo
*watchedInfo
;
1649 // get the IORegistry node
1650 entryID
= _SCNetworkInterfaceGetIORegistryEntryID(interface
);
1651 matching
= IORegistryEntryIDMatching(entryID
);
1652 interface_node
= IOServiceGetMatchingService(kIOMasterPortDefault
, matching
);
1653 if (interface_node
== MACH_PORT_NULL
) {
1654 // interface no longer present
1658 // create [locked/trusted] interface watcher
1659 watched
= CFDataCreateMutable(NULL
, sizeof(WatchedInfo
));
1660 CFDataSetLength(watched
, sizeof(WatchedInfo
));
1661 watchedInfo
= (WatchedInfo
*)(void *)CFDataGetBytePtr(watched
);
1662 memset(watchedInfo
, 0, sizeof(*watchedInfo
));
1665 watchedInfo
->interface
= CFRetain(interface
);
1667 // ... and the interface node
1668 watchedInfo
->interface_node
= interface_node
;
1670 // ... and set the callback
1671 watchedInfo
->callback
= callback
;
1673 kr
= IOServiceAddInterestNotification(S_notify
, // IONotificationPortRef
1674 watchedInfo
->interface_node
, // io_service_t
1675 kIOGeneralInterest
, // interestType
1676 updateWatchedInterface
, // IOServiceInterestCallback
1677 (void *)watched
, // refCon
1678 &watchedInfo
->notification
); // notification
1679 if (kr
!= KERN_SUCCESS
) {
1681 "IOServiceAddInterestNotification() failed, kr = 0x%x",
1683 watcherRelease(watched
);
1692 watcherRelease(CFDataRef watched
)
1694 WatchedInfo
*watchedInfo
= (WatchedInfo
*)(void *)CFDataGetBytePtr(watched
);
1697 if (watchedInfo
->notification
!= IO_OBJECT_NULL
) {
1698 IOObjectRelease(watchedInfo
->notification
);
1699 watchedInfo
->notification
= IO_OBJECT_NULL
;
1702 // release interface node
1703 if (watchedInfo
->interface_node
!= IO_OBJECT_NULL
) {
1704 IOObjectRelease(watchedInfo
->interface_node
);
1705 watchedInfo
->interface_node
= IO_OBJECT_NULL
;
1708 // release interface
1709 if (watchedInfo
->interface
!= NULL
) {
1710 CFRelease(watchedInfo
->interface
);
1711 watchedInfo
->interface
= NULL
;
1719 #pragma mark Locked device support [macOS]
1722 #if !TARGET_OS_IPHONE
1728 n
= (S_locked
!= NULL
) ? CFArrayGetCount(S_locked
) : 0;
1730 CFMutableArrayRef locked
;
1732 locked
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
1734 for (CFIndex i
= 0; i
< n
; i
++) {
1739 CFDataRef watched
= CFArrayGetValueAtIndex(S_locked
, i
);
1740 WatchedInfo
*watchedInfo
= (WatchedInfo
*)(void *)CFDataGetBytePtr(watched
);
1742 name
= SCNetworkInterfaceGetLocalizedDisplayName(watchedInfo
->interface
);
1743 addr
= SCNetworkInterfaceGetHardwareAddressString(watchedInfo
->interface
);
1744 path
= _SCNetworkInterfaceGetIOPath(watchedInfo
->interface
);
1745 str
= CFStringCreateWithFormat(NULL
, NULL
, CFSTR("%@: %@: %@"),
1746 (name
!= NULL
) ? name
: CFSTR("?"),
1747 (addr
!= NULL
) ? addr
: CFSTR("?"),
1749 CFArrayAppendValue(locked
, str
);
1753 CFDictionarySetValue(S_state
, kInterfaceNamerKey_LockedInterfaces
, locked
);
1756 CFDictionaryRemoveValue(S_state
, kInterfaceNamerKey_LockedInterfaces
);
1765 blockNewInterfaces()
1767 static boolean_t allow
= TRUE
;
1768 static dispatch_once_t once
;
1770 dispatch_once(&once
, ^{
1771 allow
= InterfaceNamerControlPrefsAllowNewInterfaces();
1780 CFArrayRef console_sessions
;
1781 boolean_t locked
= FALSE
;
1782 io_registry_entry_t root
;
1784 root
= IORegistryGetRootEntry(kIOMasterPortDefault
);
1785 console_sessions
= IORegistryEntryCreateCFProperty(root
,
1786 CFSTR(kIOConsoleUsersKey
),
1789 if (isA_CFArray(console_sessions
)) {
1792 n
= CFArrayGetCount(console_sessions
);
1793 for (CFIndex i
= 0; i
< n
; i
++) {
1794 CFBooleanRef isLocked
;
1795 CFBooleanRef isLoginDone
;
1796 CFBooleanRef onConsole
;
1797 CFDictionaryRef session
;
1799 session
= CFArrayGetValueAtIndex(console_sessions
, i
);
1800 if (!isA_CFDictionary(session
)) {
1801 // if not dictionary
1805 if (!CFDictionaryGetValueIfPresent(session
,
1806 CFSTR(kIOConsoleSessionOnConsoleKey
),
1807 (const void **)&onConsole
) ||
1808 !isA_CFBoolean(onConsole
) ||
1809 !CFBooleanGetValue(onConsole
)) {
1810 // if not "on console" session
1815 CFDictionaryGetValueIfPresent(session
,
1816 CFSTR(kIOConsoleSessionLoginDoneKey
),
1817 (const void **)&isLoginDone
) &&
1818 isA_CFBoolean(isLoginDone
) &&
1819 !CFBooleanGetValue(isLoginDone
)) {
1821 SC_log(LOG_INFO
, "multiple sessions, console @ loginwindow");
1826 if (CFDictionaryGetValueIfPresent(session
,
1827 CFSTR(kIOConsoleSessionScreenIsLockedKey
),
1828 (const void **)&isLocked
) &&
1829 isA_CFBoolean(isLocked
) &&
1830 CFBooleanGetValue(isLocked
)) {
1832 SC_log(LOG_INFO
, "console screen locked");
1839 SC_log(LOG_INFO
, "console not locked");
1843 if (console_sessions
!= NULL
) {
1844 CFRelease(console_sessions
);
1846 IOObjectRelease(root
);
1851 //#define ENABLE_LOCKED_CONSOLE_INTERFACE_NOTIFICATIONS
1852 #ifdef ENABLE_LOCKED_CONSOLE_INTERFACE_NOTIFICATIONS
1854 static CFUserNotificationRef userNotification
;
1855 static CFRunLoopSourceRef userRls
;
1858 lockedNotification_remove(void)
1860 if (userRls
!= NULL
) {
1861 CFRunLoopSourceInvalidate(userRls
);
1865 if (userNotification
!= NULL
) {
1868 status
= CFUserNotificationCancel(userNotification
);
1871 "CFUserNotificationCancel() failed, status=%d",
1874 CFRelease(userNotification
);
1875 userNotification
= NULL
;
1881 #define MY_ICON_PATH "/System/Library/PreferencePanes/Network.prefPane/Contents/Resources/Network.icns"
1884 lockedNotification_reply(CFUserNotificationRef userNotification
, CFOptionFlags response_flags
)
1886 #pragma unused(userNotification)
1890 n
= (S_locked
!= NULL
) ? CFArrayGetCount(S_locked
) : 0;
1891 for (CFIndex i
= 0; i
< n
; i
++) {
1892 CFDataRef watched
= CFArrayGetValueAtIndex(S_locked
, i
);
1893 WatchedInfo
*watchedInfo
= (WatchedInfo
*)(void *)CFDataGetBytePtr(watched
);
1895 // process user response
1896 switch (response_flags
& 0x3) {
1897 case kCFUserNotificationDefaultResponse
: {
1898 // if OK'd, [re-]process new interfaces
1900 SC_log(LOG_INFO
, "Reprocessing %ld [locked] interface%s", n
, n
== 1 ? "" : "s");
1902 if (S_iflist
== NULL
) {
1903 S_iflist
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
1907 // add the interface to those newly discovered
1908 CFArrayAppendValue(S_iflist
, watchedInfo
->interface
);
1912 // if cancelled, ignore [remaining] new interfaces
1913 SC_log(LOG_INFO
, "[locked] interface ignored");
1914 SC_log(LOG_INFO
, " path = %@", _SCNetworkInterfaceGetIOPath(watchedInfo
->interface
));
1920 watcherRelease(watched
);
1923 if (S_locked
!= NULL
) {
1924 CFRelease(S_locked
);
1928 lockedNotification_remove();
1930 if (S_iflist
!= NULL
) {
1938 lockedNotification_add(void)
1941 CFMutableDictionaryRef dict
;
1943 CFMutableArrayRef message
;
1945 CFURLRef url
= NULL
;
1947 n
= (S_locked
!= NULL
) ? CFArrayGetCount(S_locked
) : 0;
1949 // no locked interfaces, no notification needed
1953 dict
= CFDictionaryCreateMutable(NULL
,
1955 &kCFTypeDictionaryKeyCallBacks
,
1956 &kCFTypeDictionaryValueCallBacks
);
1958 // set localization URL
1959 bundle
= _SC_CFBundleGet();
1960 if (bundle
!= NULL
) {
1961 url
= CFBundleCopyBundleURL(bundle
);
1965 CFDictionarySetValue(dict
, kCFUserNotificationLocalizationURLKey
, url
);
1968 SC_log(LOG_ERR
, "can't find bundle");
1973 url
= CFURLCreateFromFileSystemRepresentation(NULL
,
1974 (const UInt8
*)MY_ICON_PATH
,
1975 sizeof(MY_ICON_PATH
) - 1,
1978 CFDictionarySetValue(dict
, kCFUserNotificationIconURLKey
, url
);
1983 CFDictionarySetValue(dict
,
1984 kCFUserNotificationAlertHeaderKey
,
1985 (n
== 1) ? CFSTR("LOCKED_SINGLE_INTERFACE_HEADER")
1986 : CFSTR("LOCKED_MULTIPLE_INTERFACES_HEADER"));
1989 message
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
1990 CFArrayAppendValue(message
,
1991 (n
== 1) ? CFSTR("LOCKED_SINGLE_INTERFACE_MESSAGE")
1992 : CFSTR("LOCKED_MULTIPLE_INTERFACES_MESSAGE"));
1993 for (CFIndex i
= 0; i
< n
; i
++) {
1996 CFDataRef watched
= CFArrayGetValueAtIndex(S_locked
, i
);
1997 WatchedInfo
*watchedInfo
= (WatchedInfo
*)(void *)CFDataGetBytePtr(watched
);
1999 name
= SCNetworkInterfaceGetLocalizedDisplayName(watchedInfo
->interface
);
2000 str
= CFStringCreateWithFormat(NULL
, NULL
, CFSTR("\r\t%@"), name
);
2001 CFArrayAppendValue(message
, str
);
2004 CFDictionarySetValue(dict
, kCFUserNotificationAlertMessageKey
, message
);
2008 CFDictionarySetValue(dict
,
2009 kCFUserNotificationDefaultButtonTitleKey
,
2010 CFSTR("LOCKED_INTERFACES_IGNORE"));
2011 CFDictionarySetValue(dict
,
2012 kCFUserNotificationAlternateButtonTitleKey
,
2013 (n
== 1) ? CFSTR("LOCKED_SINGLE_INTERFACE_ADD")
2014 : CFSTR("LOCKED_MULTIPLE_INTERFACES_ADD"));
2016 // create and post notification
2017 userNotification
= CFUserNotificationCreate(NULL
,
2019 kCFUserNotificationNoteAlertLevel
,
2022 if (userNotification
== NULL
) {
2023 SC_log(LOG_ERR
, "CFUserNotificationCreate() failed: %d", (int)error
);
2027 // establish callback
2028 userRls
= CFUserNotificationCreateRunLoopSource(NULL
,
2030 lockedNotification_reply
,
2032 if (userRls
== NULL
) {
2033 SC_log(LOG_ERR
, "CFUserNotificationCreateRunLoopSource() failed");
2034 CFRelease(userNotification
);
2035 userNotification
= NULL
;
2038 CFRunLoopAddSource(CFRunLoopGetCurrent(), userRls
, kCFRunLoopDefaultMode
);
2042 if (dict
!= NULL
) CFRelease(dict
);
2047 lockedNotification_update(void)
2049 // if present, remove current notification
2050 lockedNotification_remove();
2052 // post notification (if needed)
2053 lockedNotification_add();
2058 #endif // ENABLE_LOCKED_CONSOLE_INTERFACE_NOTIFICATIONS
2061 lockedInterfaceUpdated(CFDataRef watched
, natural_t messageType
, void *messageArgument
)
2063 #pragma unused(messageArgument)
2064 Boolean updated
= FALSE
;
2065 WatchedInfo
*watchedInfo
= (WatchedInfo
*)(void *)CFDataGetBytePtr(watched
);
2067 switch (messageType
) {
2068 case kIOMessageServiceIsTerminated
: { // if [locked] interface yanked
2069 SC_log(LOG_INFO
, "[locked] interface removed");
2070 SC_log(LOG_INFO
, " path = %@", _SCNetworkInterfaceGetIOPath(watchedInfo
->interface
));
2072 if (S_locked
!= NULL
) {
2074 CFIndex n
= CFArrayGetCount(S_locked
);
2076 i
= CFArrayGetFirstIndexOfValue(S_locked
, CFRangeMake(0, n
), watched
);
2077 if (i
!= kCFNotFound
) {
2078 CFArrayRemoveValueAtIndex(S_locked
, i
);
2079 if (CFArrayGetCount(S_locked
) == 0) {
2080 CFRelease(S_locked
);
2095 #ifdef ENABLE_LOCKED_CONSOLE_INTERFACE_NOTIFICATIONS
2096 // update user notification after interface removed
2097 lockedNotification_update();
2098 #endif // ENABLE_LOCKED_CONSOLE_INTERFACE_NOTIFICATIONS
2100 // post info about interfaces not added because the console is locked
2108 watchLockedInterface(SCNetworkInterfaceRef interface
)
2110 Boolean updated
= FALSE
;
2113 watched
= watcherCreate(interface
, lockedInterfaceUpdated
);
2114 if (watched
!= NULL
) {
2115 SC_log(LOG_INFO
, "watching [locked] interface");
2116 SC_log(LOG_INFO
, " path = %@", _SCNetworkInterfaceGetIOPath(interface
));
2118 if (S_locked
== NULL
) {
2119 S_locked
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
2121 CFArrayAppendValue(S_locked
, watched
);
2126 // post info about interfaces not added because the console is locked
2129 #ifdef ENABLE_LOCKED_CONSOLE_INTERFACE_NOTIFICATIONS
2130 // post/update user notification with new interface
2131 lockedNotification_update();
2132 #endif // ENABLE_LOCKED_CONSOLE_INTERFACE_NOTIFICATIONS
2137 #endif // !TARGET_OS_IPHONE
2141 #pragma mark Trust required support [iOS]
2144 #if TARGET_OS_IPHONE
2148 void * volatile fn_WeakFunction
= (void *)&(lockdown_is_host_trusted
);
2149 Boolean haveLibrary
;
2151 haveLibrary
= (fn_WeakFunction
!= NULL
) ? TRUE
: FALSE
;
2160 n
= (S_trustRequired
!= NULL
) ? CFArrayGetCount(S_trustRequired
) : 0;
2161 if ((n
> 0) && !S_trustedHostAttached
) {
2162 CFMutableArrayRef excluded
;
2164 // if we have interfaces that require not [yet] granted "trust".
2166 excluded
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
2168 for (CFIndex i
= 0; i
< n
; i
++) {
2169 CFStringRef bsdName
;
2170 CFDataRef watched
= CFArrayGetValueAtIndex(S_trustRequired
, i
);
2171 WatchedInfo
*watchedInfo
= (WatchedInfo
*)(void *)CFDataGetBytePtr(watched
);
2173 bsdName
= SCNetworkInterfaceGetBSDName(watchedInfo
->interface
);
2174 if (bsdName
== NULL
) {
2175 SC_log(LOG_NOTICE
, "[trust required] excluded interface w/no BSD name");
2176 SC_log(LOG_NOTICE
, " interface = %@", watchedInfo
->interface
);
2179 CFArrayAppendValue(excluded
, bsdName
);
2182 CFDictionarySetValue(S_state
, kInterfaceNamerKey_ExcludedInterfaces
, excluded
);
2183 CFRelease(excluded
);
2185 CFDictionaryRemoveValue(S_state
, kInterfaceNamerKey_ExcludedInterfaces
);
2193 static dispatch_queue_t
2194 trustRequired_queue()
2196 static dispatch_once_t once
;
2197 static dispatch_queue_t q
;
2199 dispatch_once(&once
, ^{
2200 q
= dispatch_queue_create("Trust Required queue", NULL
);
2207 // runs on "Trust Required" dispatch queue
2209 trustRequiredNotification_update(CFRunLoopRef rl
, CFStringRef reason
)
2211 Boolean changed
= FALSE
;
2212 CFStringRef error
= NULL
;
2217 * determine whether the device has "trusted" the host (or other device)
2219 trusted
= lockdown_is_host_trusted(MY_PLUGIN_ID
, NULL
, &error
);
2220 n
= (S_trustRequired
!= NULL
) ? CFArrayGetCount(S_trustRequired
) : 0;
2221 if ((S_trustedHostCount
!= n
) || (S_trustedHostAttached
!= trusted
)) {
2225 SC_log(LOG_INFO
, "%@, trusted = %s%s%@, %ld interface%s)%s",
2227 trusted
? "Yes" : "No",
2228 (error
!= NULL
) ? ", error = " : "",
2229 (error
!= NULL
) ? error
: CFSTR(""),
2231 (n
== 1) ? "" : "s",
2232 changed
? " *" : "");
2235 S_trustedHostAttached
= trusted
;
2236 S_trustedHostCount
= n
;
2237 CFRunLoopPerformBlock(rl
, kCFRunLoopDefaultMode
, ^{
2240 CFRunLoopWakeUp(rl
);
2243 if (error
!= NULL
) {
2251 trustRequiredInterfaceUpdated(CFDataRef watched
, natural_t messageType
, void *messageArgument
)
2253 #pragma unused(messageArgument)
2254 Boolean updated
= FALSE
;
2255 WatchedInfo
*watchedInfo
= (WatchedInfo
*)(void *)CFDataGetBytePtr(watched
);
2257 switch (messageType
) {
2258 case kIOMessageServiceIsTerminated
: { // if [locked] interface yanked
2259 SC_log(LOG_INFO
, "[trust required] interface removed");
2260 SC_log(LOG_INFO
, " path = %@", _SCNetworkInterfaceGetIOPath(watchedInfo
->interface
));
2262 if (S_trustRequired
!= NULL
) {
2264 CFIndex n
= CFArrayGetCount(S_trustRequired
);
2266 i
= CFArrayGetFirstIndexOfValue(S_trustRequired
, CFRangeMake(0, n
), watched
);
2267 if (i
!= kCFNotFound
) {
2268 CFArrayRemoveValueAtIndex(S_trustRequired
, i
);
2269 if (CFArrayGetCount(S_trustRequired
) == 0) {
2270 CFRelease(S_trustRequired
);
2271 S_trustRequired
= NULL
;
2285 CFRunLoopRef rl
= CFRunLoopGetCurrent();
2288 dispatch_async(trustRequired_queue(), ^{
2289 trustRequiredNotification_update(rl
, CFSTR("TrustRequired interface removed"));
2298 watchTrustedStatus(CFStringRef notification
, CFStringRef reason
)
2301 int notify_token
= -1;
2303 CFRunLoopRef rl
= CFRunLoopGetCurrent();
2305 key
= CFStringGetCStringPtr(notification
, kCFStringEncodingUTF8
);
2306 assert(key
!= NULL
);
2310 ret
= notify_register_dispatch(key
,
2312 trustRequired_queue(),
2314 #pragma unused(token)
2315 trustRequiredNotification_update(rl
, reason
);
2317 if (ret
!= NOTIFY_STATUS_OK
) {
2318 SC_log(LOG_ERR
, "notify_register_dispatch(%@) failed: %u", notification
, ret
);
2327 isWatchedInterface(SCNetworkInterfaceRef interface
)
2329 Boolean found
= FALSE
;
2332 n
= (S_trustRequired
!= NULL
) ? CFArrayGetCount(S_trustRequired
) : 0;
2333 for (CFIndex i
= 0; i
< n
; i
++) {
2334 CFDataRef watched
= CFArrayGetValueAtIndex(S_trustRequired
, i
);
2335 WatchedInfo
*watchedInfo
= (WatchedInfo
*)(void *)CFDataGetBytePtr(watched
);
2337 if (CFEqual((watchedInfo
->interface
), interface
)) {
2347 updateTrustRequiredInterfaces(CFArrayRef interfaces
)
2350 Boolean updated
= FALSE
;
2352 n
= (interfaces
!= NULL
) ? CFArrayGetCount(interfaces
) : 0;
2353 for (CFIndex i
= 0; i
< n
; i
++) {
2354 SCNetworkInterfaceRef interface
;
2356 interface
= CFArrayGetValueAtIndex(interfaces
, i
);
2357 if (_SCNetworkInterfaceIsTrustRequired(interface
) && !isWatchedInterface(interface
)) {
2360 watched
= watcherCreate(interface
, trustRequiredInterfaceUpdated
);
2361 if (watched
!= NULL
) {
2362 SC_log(LOG_INFO
, "watching [trust required] interface: %@",
2363 SCNetworkInterfaceGetBSDName(interface
));
2365 if (S_trustRequired
== NULL
) {
2366 S_trustRequired
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
2368 CFArrayAppendValue(S_trustRequired
, watched
);
2375 static dispatch_once_t once
;
2376 CFRunLoopRef rl
= CFRunLoopGetCurrent();
2378 dispatch_once(&once
, ^{
2379 // watch for "Host attached"
2380 watchTrustedStatus(kLockdownNotificationHostAttached
,
2381 CFSTR("Host attached"));
2383 // watch for "Host detached"
2384 watchTrustedStatus(kLockdownNotificationHostDetached
,
2385 CFSTR("Host detached"));
2387 // watch for "Trusted host attached"
2388 watchTrustedStatus(kLockdownNotificationTrustedHostAttached
,
2389 CFSTR("Trusted Host attached"));
2391 // watch for "Trusted PDP attached"
2392 watchTrustedStatus(kLockdownNotificationTrustedPTPAttached
,
2393 CFSTR("Trusted PTP attached"));
2397 dispatch_async(trustRequired_queue(), ^{
2398 trustRequiredNotification_update(rl
, CFSTR("TrustRequired interface added"));
2405 #endif // TARGET_OS_IPHONE
2409 #pragma mark Pre-configured interface support
2413 sharePreconfigured()
2417 n
= (S_preconfigured
!= NULL
) ? CFArrayGetCount(S_preconfigured
) : 0;
2419 CFMutableArrayRef preconfigured
;
2421 preconfigured
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
2423 for (CFIndex i
= 0; i
< n
; i
++) {
2424 CFStringRef bsdName
;
2425 CFDataRef watched
= CFArrayGetValueAtIndex(S_preconfigured
, i
);
2426 WatchedInfo
*watchedInfo
= (WatchedInfo
*)(void *)CFDataGetBytePtr(watched
);
2428 bsdName
= SCNetworkInterfaceGetBSDName(watchedInfo
->interface
);
2429 CFArrayAppendValue(preconfigured
, bsdName
);
2432 CFDictionarySetValue(S_state
, kInterfaceNamerKey_PreConfiguredInterfaces
, preconfigured
);
2433 CFRelease(preconfigured
);
2435 CFDictionaryRemoveValue(S_state
, kInterfaceNamerKey_PreConfiguredInterfaces
);
2444 preconfiguredInterfaceUpdated(CFDataRef watched
, natural_t messageType
, void *messageArgument
)
2446 Boolean updated
= FALSE
;
2447 WatchedInfo
*watchedInfo
= (WatchedInfo
*)(void *)CFDataGetBytePtr(watched
);
2449 #pragma unused(messageArgument)
2450 switch (messageType
) {
2451 case kIOMessageServiceIsTerminated
: { // if [locked] interface yanked
2452 SC_log(LOG_INFO
, "[pre-configured] interface removed: %@",
2453 SCNetworkInterfaceGetBSDName(watchedInfo
->interface
));
2455 if (S_preconfigured
!= NULL
) {
2457 CFIndex n
= CFArrayGetCount(S_preconfigured
);
2459 i
= CFArrayGetFirstIndexOfValue(S_preconfigured
, CFRangeMake(0, n
), watched
);
2460 if (i
!= kCFNotFound
) {
2461 CFArrayRemoveValueAtIndex(S_preconfigured
, i
);
2462 if (CFArrayGetCount(S_preconfigured
) == 0) {
2463 CFRelease(S_preconfigured
);
2464 S_preconfigured
= NULL
;
2478 sharePreconfigured();
2485 updatePreConfiguredInterfaces(CFArrayRef interfaces
)
2488 Boolean updated
= FALSE
;
2490 n
= (interfaces
!= NULL
) ? CFArrayGetCount(interfaces
) : 0;
2491 for (CFIndex i
= 0; i
< n
; i
++) {
2492 SCNetworkInterfaceRef interface
;
2494 interface
= CFArrayGetValueAtIndex(interfaces
, i
);
2495 if (_SCNetworkInterfaceIsApplePreconfigured(interface
)) {
2498 watched
= watcherCreate(interface
, preconfiguredInterfaceUpdated
);
2499 if (watched
!= NULL
) {
2500 SC_log(LOG_INFO
, "watching [pre-configured] interface: %@",
2501 SCNetworkInterfaceGetBSDName(interface
));
2503 if (S_preconfigured
== NULL
) {
2504 S_preconfigured
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
2506 CFArrayAppendValue(S_preconfigured
, watched
);
2513 sharePreconfigured();
2521 #pragma mark Interface naming
2524 static __inline__ boolean_t
2527 return (S_quiet
== MACH_PORT_NULL
);
2531 wasPreviouslyUsedInterface(CFDictionaryRef dbdict
, SCNetworkInterfaceRef interface
)
2533 CFArrayRef matchingMACs
;
2535 matchingMACs
= CFDictionaryGetValue(dbdict
, CFSTR(kSCNetworkInterfaceMatchingMACs
));
2536 if (matchingMACs
!= NULL
) {
2539 addr
= _SCNetworkInterfaceGetHardwareAddress(interface
);
2541 if (CFArrayContainsValue(matchingMACs
,
2542 CFRangeMake(0, CFArrayGetCount(matchingMACs
)),
2553 nameInterfaces(CFMutableArrayRef if_list
)
2556 CFIndex n
= CFArrayGetCount(if_list
);
2558 for (i
= 0; i
< n
; i
++) {
2560 SCNetworkInterfaceRef interface
;
2561 SCNetworkInterfaceRef new_interface
;
2567 interface
= CFArrayGetValueAtIndex(if_list
, i
);
2568 path
= _SCNetworkInterfaceGetIOPath(interface
);
2569 type
= _SCNetworkInterfaceGetIOInterfaceType(interface
);
2570 unit
= _SCNetworkInterfaceGetIOInterfaceUnit(interface
);
2571 entryID
= _SCNetworkInterfaceGetIORegistryEntryID(interface
);
2574 CFStringRef if_name
;
2576 if_name
= SCNetworkInterfaceGetBSDName(interface
);
2577 if ((if_name
== NULL
) || !CFDictionaryContainsKey(S_state
, if_name
)) {
2578 SC_log(LOG_INFO
, "Interface already has a unit number");
2579 displayInterface(interface
);
2582 // update the list of interfaces that were previously named
2583 if ((S_prev_active_list
!= NULL
)
2584 && lookupInterfaceByAddress(S_prev_active_list
, interface
, &where
) != NULL
) {
2585 CFArrayRemoveValueAtIndex(S_prev_active_list
, where
);
2588 replaceInterface(interface
);
2590 CFDictionaryRef dbdict
;
2591 boolean_t is_builtin
;
2595 dbdict
= lookupInterfaceByAddress(S_dblist
, interface
, NULL
);
2596 if (dbdict
!= NULL
) {
2597 unit
= CFDictionaryGetValue(dbdict
, CFSTR(kIOInterfaceUnit
));
2600 SC_log(LOG_INFO
, "Interface assigned unit %@ (from database)", unit
);
2603 if ((dbdict
== NULL
) && !isQuiet()) {
2604 // if new interface, wait until quiet before naming
2605 addTimestamp(S_state
, path
);
2609 is_builtin
= _SCNetworkInterfaceIsBuiltin(interface
);
2611 if (dbdict
== NULL
) {
2612 dbdict
= lookupMatchingInterface(interface
,
2616 is_builtin
? kCFBooleanTrue
: kCFBooleanFalse
);
2618 if ((dbdict
!= NULL
) && wasPreviouslyUsedInterface(dbdict
, interface
)) {
2619 unit
= CFDictionaryGetValue(dbdict
, CFSTR(kIOInterfaceUnit
));
2622 SC_log(LOG_INFO
, "Interface assigned unit %@ (updating database w/previously used interface)", unit
);
2625 #if !TARGET_OS_IPHONE
2626 if ((unit
== NULL
) &&
2629 blockNewInterfaces() &&
2630 !_SCNetworkInterfaceIsApplePreconfigured(interface
) &&
2631 isConsoleLocked()) {
2634 // if new (but matching) interface and console locked, ignore
2635 addr
= SCNetworkInterfaceGetHardwareAddressString(interface
);
2636 SC_log(LOG_NOTICE
, "Console locked, network interface* ignored");
2637 SC_log(LOG_INFO
, " path = %@, addr = %@",
2639 (addr
!= NULL
) ? addr
: CFSTR("?"));
2640 watchLockedInterface(interface
);
2643 #endif // !TARGET_OS_IPHONE
2645 if ((unit
== NULL
) && (dbdict
!= NULL
)) {
2646 unit
= CFDictionaryGetValue(dbdict
, CFSTR(kIOInterfaceUnit
));
2649 SC_log(LOG_INFO
, "Interface assigned unit %@ (updating database w/new interface)", unit
);
2653 if ((dbdict
!= NULL
) && (S_prev_active_list
!= NULL
)) {
2654 // update the list of interfaces that were previously named
2655 where
= CFArrayGetFirstIndexOfValue(S_prev_active_list
,
2656 CFRangeMake(0, CFArrayGetCount(S_prev_active_list
)),
2658 if (where
!= kCFNotFound
) {
2659 CFArrayRemoveValueAtIndex(S_prev_active_list
, where
);
2663 if (dbdict
== NULL
) {
2667 // built-in interface, try to use the reserved slots
2668 next_unit
= builtinCount(if_list
, i
, type
);
2670 // But, before claiming a reserved slot we check to see if the
2671 // slot had previously been used. If so, and if the slot had been
2672 // assigned to the same type of interface, then we will perform a
2673 // replacement (e.g. assume that this was a board swap). But, if
2674 // the new interface is a different type then we assume that the
2675 // built-in configuration has changed and allocate a new unit from
2676 // the non-reserved slots.
2678 unit
= CFNumberCreate(NULL
, kCFNumberIntType
, &next_unit
);
2679 if (!builtinAvailable(interface
, unit
)) {
2680 // if [built-in] unit not available
2681 SC_log(LOG_INFO
, "Interface not assigned [built-in] unit %@", unit
);
2687 #if !TARGET_OS_IPHONE
2690 blockNewInterfaces() &&
2691 !_SCNetworkInterfaceIsApplePreconfigured(interface
) &&
2692 isConsoleLocked()) {
2695 // if new interface and console locked, ignore
2696 addr
= SCNetworkInterfaceGetHardwareAddressString(interface
);
2697 SC_log(LOG_NOTICE
, "Console locked, network interface ignored");
2698 SC_log(LOG_INFO
, " path = %@, addr = %@",
2700 (addr
!= NULL
) ? addr
: CFSTR("?"));
2701 watchLockedInterface(interface
);
2704 #endif // !TARGET_OS_IPHONE
2707 // not built-in (or built-in unit not available), allocate from
2708 // the non-reserved slots
2709 next_unit
= builtinCount(if_list
, n
, type
);
2711 unit
= getHighestUnitForType(type
);
2715 CFNumberGetValue(unit
, kCFNumberIntType
, &high_unit
);
2716 if (high_unit
>= next_unit
) {
2717 next_unit
= high_unit
+ 1;
2721 unit
= CFNumberCreate(NULL
, kCFNumberIntType
, &next_unit
);
2724 SC_log(LOG_INFO
, "Interface assigned unit %@ (%s)",
2726 is_builtin
? "built-in" : "next available");
2731 #ifdef USE_REGISTRY_ENTRY_ID
2732 kr
= registerInterfaceWithIORegistryEntryID(S_connect
,
2735 (dbdict
== NULL
) ? kIONetworkStackRegisterInterfaceWithLowestUnit
2736 : kIONetworkStackRegisterInterfaceWithUnit
);
2737 new_interface
= copyNamedInterfaceForIORegistryEntryID(entryID
);
2738 #else // USE_REGISTRY_ENTRY_ID
2739 kr
= registerInterfaceWithIOServicePath(S_connect
,
2742 (dbdict
== NULL
) ? kRegisterInterface
2743 : kRegisterInterfaceWithFixedUnit
);
2744 new_interface
= copyNamedInterfaceForIOKitPath(path
);
2745 #endif // USE_REGISTRY_ENTRY_ID
2746 if (new_interface
== NULL
) {
2747 const char *signature
;
2749 signature
= (dbdict
== NULL
) ? "failed to name new interface"
2750 : "failed to name known interface";
2752 SC_log(LOG_NOTICE
, "%s, kr=0x%x\n"
2762 displayInterface(interface
);
2764 if ((dbdict
!= NULL
) && (retries
++ < 5)) {
2765 usleep(50 * 1000); // sleep 50ms between attempts
2770 CFNumberRef new_unit
;
2773 SC_log(LOG_INFO
, "%s interface named after %d %s\n"
2776 (dbdict
== NULL
) ? "New" : "Known",
2778 (retries
== 1) ? "try" : "tries",
2782 #ifdef SHOW_NAMING_FAILURE
2783 str
= CFStringCreateWithFormat(NULL
,
2785 CFSTR("\"%s\" interface named after %d %s, unit = %@"),
2786 (dbdict
== NULL
) ? "New" : "Known",
2788 (retries
== 1) ? "try" : "tries",
2790 CFUserNotificationDisplayNotice(0,
2791 kCFUserNotificationStopAlertLevel
,
2796 CFSTR("Please report repeated failures."),
2799 #endif // SHOW_NAMING_FAILURE
2802 new_unit
= _SCNetworkInterfaceGetIOInterfaceUnit(new_interface
);
2803 if (!CFEqual(unit
, new_unit
)) {
2804 SC_log(LOG_INFO
, "interface type %@ assigned unit %@ instead of %@",
2805 type
, new_unit
, unit
);
2808 displayInterface(new_interface
);
2810 // update if_list (with the interface name & unit)
2811 CFArraySetValueAtIndex(if_list
, i
, new_interface
);
2812 CFRelease(new_interface
);
2813 interface
= new_interface
; // if_list holds the reference
2815 if (is_builtin
&& (S_prev_active_list
!= NULL
)) {
2818 // update the list of [built-in] interfaces that were previously named
2819 if (lookupInterfaceByUnit(S_prev_active_list
, interface
, &where
) != NULL
) {
2820 SC_log(LOG_DEBUG
, " and updated database (new address)");
2821 CFArrayRemoveValueAtIndex(S_prev_active_list
, where
);
2824 replaceInterface(interface
);
2832 #if !TARGET_OS_IPHONE
2834 #define INSTALL_ENVIRONMENT "__OSINSTALL_ENVIRONMENT"
2839 static Boolean isRecovery
= FALSE
;
2840 static dispatch_once_t once
;
2843 * We check to see if the __OSINSTALL_ENVIRONMENT env var is present. If
2844 * so, then we are most likely booted into the Recovery OS with no [Aqua]
2845 * "SCMonitor" [UserEventAgent] plugin.
2847 dispatch_once(&once
, ^{
2848 if (getenv(INSTALL_ENVIRONMENT
) != NULL
) {
2858 updateNetworkConfiguration(CFArrayRef if_list
)
2860 Boolean do_commit
= FALSE
;
2863 SCPreferencesRef prefs
= NULL
;
2864 SCNetworkSetRef set
= NULL
;
2866 prefs
= SCPreferencesCreate(NULL
, CFSTR(MY_PLUGIN_NAME
":updateNetworkConfiguration"), NULL
);
2867 if (prefs
== NULL
) {
2868 SC_log(LOG_NOTICE
, "SCPreferencesCreate() failed: %s", SCErrorString(SCError()));
2872 set
= SCNetworkSetCopyCurrent(prefs
);
2874 SC_log(LOG_INFO
, "No current set, adding default");
2875 set
= _SCNetworkSetCreateDefault(prefs
);
2877 SC_log(LOG_NOTICE
, "_SCNetworkSetCreateDefault() failed: %s", SCErrorString(SCError()));
2882 n
= (if_list
!= NULL
) ? CFArrayGetCount(if_list
) : 0;
2883 for (i
= 0; i
< n
; i
++) {
2884 SCNetworkInterfaceRef interface
;
2886 interface
= CFArrayGetValueAtIndex(if_list
, i
);
2887 if (SCNetworkSetEstablishDefaultInterfaceConfiguration(set
, interface
)) {
2888 SC_log(LOG_INFO
, "adding default configuration for %@",
2889 SCNetworkInterfaceGetBSDName(interface
));
2897 ok
= SCPreferencesCommitChanges(prefs
);
2899 SC_log(LOG_NOTICE
, "SCPreferencesCommitChanges() failed: %s", SCErrorString(SCError()));
2903 ok
= SCPreferencesApplyChanges(prefs
);
2905 SC_log(LOG_NOTICE
, "SCPreferencesApplyChanges() failed: %s", SCErrorString(SCError()));
2917 if (prefs
!= NULL
) {
2924 #endif // !TARGET_OS_IPHONE
2929 if (S_connect
== MACH_PORT_NULL
) {
2930 // if we don't have the "IONetworkStack" connect object
2934 if (S_iflist
!= NULL
) {
2937 n
= CFArrayGetCount(S_iflist
);
2939 CFArraySortValues(S_iflist
, CFRangeMake(0, n
), _SCNetworkInterfaceCompare
, NULL
);
2941 nameInterfaces(S_iflist
);
2945 * Update the list of [Apple] pre-configured interfaces
2947 updatePreConfiguredInterfaces(S_iflist
);
2949 #if TARGET_OS_IPHONE
2951 * Update the list of "trust required" interfaces
2953 if (haveLockdown()) {
2954 updateTrustRequiredInterfaces(S_iflist
);
2956 #endif // TARGET_OS_IPHONE
2960 * The registry [matching] has quiesced so let's
2961 * - save the DB with the interfaces that have been named
2962 * - update the VLAN/BOND configuration
2963 * - tell everyone that we've finished (at least for now)
2964 * - log those interfaces which are no longer present
2965 * in the HW config (or have yet to show up).
2967 writeInterfaceList(S_dblist
);
2968 updateVirtualNetworkInterfaceConfiguration(NULL
, kSCPreferencesNotificationApply
, NULL
);
2970 #if !TARGET_OS_IPHONE
2971 if (isRecoveryOS()) {
2973 * We are most likely booted into the Recovery OS with no "SCMonitor"
2974 * UserEventAgent plugin running so let's make sure we update the
2975 * network configuration for new interfaces.
2977 updateNetworkConfiguration(S_iflist
);
2979 #endif // !TARGET_OS_IPHONE
2983 if (S_iflist
!= NULL
) {
2984 CFRelease(S_iflist
);
2988 if (S_prev_active_list
!= NULL
) {
2992 n
= CFArrayGetCount(S_prev_active_list
);
2994 SC_log(LOG_INFO
, "Interface%s not [yet] active",
2995 (n
> 1) ? "s" : "");
2997 for (i
= 0; i
< n
; i
++) {
2998 CFDictionaryRef if_dict
;
3003 if_dict
= CFArrayGetValueAtIndex(S_prev_active_list
, i
);
3004 name
= CFDictionaryGetValue(if_dict
, CFSTR(kIOBSDNameKey
));
3005 type
= CFDictionaryGetValue(if_dict
, CFSTR(kIOInterfaceType
));
3006 unit
= CFDictionaryGetValue(if_dict
, CFSTR(kIOInterfaceUnit
));
3007 SC_log(LOG_INFO
, " %s%@%sType: %@, Unit: %@",
3008 (name
!= NULL
) ? "BSD Name: " : "",
3009 (name
!= NULL
) ? name
: CFSTR(""),
3010 (name
!= NULL
) ? ", " : "",
3015 CFRelease(S_prev_active_list
);
3016 S_prev_active_list
= NULL
;
3019 if ((S_prev_active_list
!= NULL
) && (CFArrayGetCount(S_prev_active_list
) == 0)) {
3021 * if we've named all of the interfaces that
3022 * were used during the previous boot.
3024 addTimestamp(S_state
, CFSTR("*RELEASE*"));
3025 SC_log(LOG_INFO
, "last boot interfaces have been named");
3027 CFRelease(S_prev_active_list
);
3028 S_prev_active_list
= NULL
;
3036 interfaceArrivalCallback(void *refcon
, io_iterator_t iter
)
3038 #pragma unused(refcon)
3041 while ((obj
= IOIteratorNext(iter
)) != MACH_PORT_NULL
) {
3042 SCNetworkInterfaceRef interface
;
3044 interface
= _SCNetworkInterfaceCreateWithIONetworkInterfaceObject(obj
);
3045 if (interface
!= NULL
) {
3046 if (S_iflist
== NULL
) {
3047 S_iflist
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
3049 CFArrayAppendValue(S_iflist
, interface
);
3050 CFRelease(interface
);
3052 IOObjectRelease(obj
);
3061 * Function: stackCallback
3063 * Get a reference to the single IONetworkStack object instance in
3064 * the kernel. Naming requests must be sent to this object, which is
3065 * attached as a client to all network interface objects in the system.
3067 * Call IOObjectRelease on the returned object.
3070 stackCallback(void *refcon
, io_iterator_t iter
)
3072 #pragma unused(refcon)
3076 stack
= IOIteratorNext(iter
);
3077 if (stack
== MACH_PORT_NULL
) {
3081 kr
= IOServiceOpen(stack
, mach_task_self(), 0, &S_connect
);
3082 if (kr
!= KERN_SUCCESS
) {
3083 SC_log(LOG_ERR
, "IOServiceOpen returned 0x%x", kr
);
3087 addTimestamp(S_state
, CFSTR("*STACK*"));
3088 SC_log(LOG_INFO
, "IONetworkStack found");
3090 if (S_stack
!= MACH_PORT_NULL
) {
3091 IOObjectRelease(S_stack
);
3092 S_stack
= MACH_PORT_NULL
;
3095 if ((S_timer
!= NULL
) && CFRunLoopTimerIsValid(S_timer
)) {
3096 // With the IONetworkStack object now available we can
3097 // reset (shorten?) the time we are willing to wait for
3098 // IOKit to quiesce.
3099 CFRunLoopTimerSetNextFireDate(S_timer
,
3100 CFAbsoluteTimeGetCurrent() + S_quiet_timeout
);
3107 if (stack
!= MACH_PORT_NULL
) {
3108 IOObjectRelease(stack
);
3115 quietCallback(void *refcon
,
3116 io_service_t service
,
3117 natural_t messageType
,
3118 void *messageArgument
)
3120 #pragma unused(refcon)
3121 #pragma unused(service)
3122 if (messageArgument
!= NULL
) {
3127 if (messageType
== kIOMessageServiceBusyStateChange
) {
3128 addTimestamp(S_state
, kInterfaceNamerKey_Quiet
);
3129 SC_log(LOG_INFO
, "IOKit quiet");
3132 if (S_connect
== MACH_PORT_NULL
) {
3133 SC_log(LOG_ERR
, "No network stack object");
3137 if (S_quiet
!= MACH_PORT_NULL
) {
3138 IOObjectRelease(S_quiet
);
3139 S_quiet
= MACH_PORT_NULL
;
3142 if (S_timer
!= NULL
) {
3143 CFRunLoopTimerInvalidate(S_timer
);
3148 // grab (and name) any additional interfaces.
3149 interfaceArrivalCallback((void *)S_notify
, S_iter
);
3151 if (messageType
== kIOMessageServiceBusyStateChange
) {
3152 addTimestamp(S_state
, CFSTR("*QUIET&NAMED*"));
3160 iterateRegistryBusy(io_iterator_t iterator
, CFArrayRef nodes
, int *count
)
3162 kern_return_t kr
= kIOReturnSuccess
;;
3165 while ((kr
== kIOReturnSuccess
) &&
3166 ((obj
= IOIteratorNext(iterator
)) != MACH_PORT_NULL
)) {
3167 uint64_t accumulated_busy_time
;
3168 uint32_t busy_state
;
3171 CFMutableArrayRef newNodes
;
3173 CFMutableStringRef str
= NULL
;
3175 if (nodes
== NULL
) {
3176 newNodes
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
3178 newNodes
= CFArrayCreateMutableCopy(NULL
, 0, nodes
);
3180 assert(newNodes
!= NULL
);
3182 kr
= IORegistryEntryGetName(obj
, name
);
3183 if (kr
!= kIOReturnSuccess
) {
3184 SC_log(LOG_NOTICE
, "IORegistryEntryGetName() returned 0x%x", kr
);
3188 str
= CFStringCreateMutable(NULL
, 0);
3189 CFStringAppendCString(str
, name
, kCFStringEncodingUTF8
);
3191 kr
= IORegistryEntryGetLocationInPlane(obj
, kIOServicePlane
, location
);
3193 case kIOReturnSuccess
:
3194 CFStringAppendCString(str
, "@", kCFStringEncodingUTF8
);
3195 CFStringAppendCString(str
, location
, kCFStringEncodingUTF8
);
3197 case kIOReturnNotFound
:
3200 SC_log(LOG_NOTICE
, "IORegistryEntryGetLocationInPlane() returned 0x%x", kr
);
3205 CFArrayAppendValue(newNodes
, str
);
3208 kr
= IOServiceGetBusyStateAndTime(obj
, &state
, &busy_state
, &accumulated_busy_time
);
3209 if (kr
!= kIOReturnSuccess
) {
3210 SC_log(LOG_NOTICE
, "IOServiceGetBusyStateAndTime() returned 0x%x", kr
);
3214 #ifdef TEST_SNAPSHOT
3217 #endif // TEST_SNAPSHOT
3219 if (busy_state
!= 0) {
3222 if ((*count
)++ == 0) {
3223 SC_log(LOG_ERR
, "Busy services :");
3226 path
= CFStringCreateByCombiningStrings(NULL
, newNodes
, CFSTR("/"));
3227 SC_log(LOG_ERR
, " %@ [%s%s%s%d, %lld ms]",
3229 (state
& kIOServiceRegisteredState
) ? "" : "!registered, ",
3230 (state
& kIOServiceMatchedState
) ? "" : "!matched, ",
3231 (state
& kIOServiceInactiveState
) ? "inactive, " : "",
3233 accumulated_busy_time
/ kMillisecondScale
);
3237 kr
= IORegistryIteratorEnterEntry(iterator
);
3238 if (kr
!= kIOReturnSuccess
) {
3239 SC_log(LOG_NOTICE
, "IORegistryIteratorEnterEntry() returned 0x%x", kr
);
3243 iterateRegistryBusy(iterator
, newNodes
, count
);
3245 kr
= IORegistryIteratorExitEntry(iterator
);
3246 if (kr
!= kIOReturnSuccess
) {
3247 SC_log(LOG_NOTICE
, "IORegistryIteratorExitEntry() returned 0x%x", kr
);
3252 CFRelease(newNodes
);
3253 IOObjectRelease(obj
);
3263 io_iterator_t iterator
= MACH_PORT_NULL
;
3266 kr
= IORegistryCreateIterator(kIOMasterPortDefault
,
3270 if (kr
!= kIOReturnSuccess
) {
3271 SC_log(LOG_NOTICE
, "IORegistryCreateIterator() returned 0x%x", kr
);
3275 iterateRegistryBusy(iterator
, NULL
, &count
);
3277 SC_log(LOG_ERR
, "w/no busy services");
3280 IOObjectRelease(iterator
);
3284 timerCallback(CFRunLoopTimerRef timer
, void *info
)
3286 #pragma unused(timer)
3287 #pragma unused(info)
3288 // We've been waiting for IOKit to quiesce and it just
3289 // hasn't happenned. Time to just move on!
3290 addTimestamp(S_state
, kInterfaceNamerKey_Timeout
);
3293 SC_log(LOG_ERR
, "timed out waiting for IOKit to quiesce");
3296 quietCallback((void *)S_notify
, MACH_PORT_NULL
, 0, NULL
);
3298 addTimestamp(S_state
, CFSTR("*TIMEOUT&NAMED*"));
3305 setup_IOKit(CFBundleRef bundle
)
3307 #pragma unused(bundle)
3310 mach_port_t masterPort
= MACH_PORT_NULL
;
3312 io_object_t root
= MACH_PORT_NULL
;
3314 // read DB of previously named network interfaces
3315 S_dblist
= readInterfaceList();
3316 if (S_dblist
!= NULL
) {
3319 n
= CFArrayGetCount(S_dblist
);
3321 CFArraySortValues(S_dblist
, CFRangeMake(0, n
), if_unit_compare
, NULL
);
3325 // get interfaces that were named during the last boot
3326 S_prev_active_list
= previouslyActiveInterfaces();
3328 // track how long we've waited to see each interface.
3329 S_state
= CFDictionaryCreateMutable(NULL
,
3331 &kCFTypeDictionaryKeyCallBacks
,
3332 &kCFTypeDictionaryValueCallBacks
);
3333 addTimestamp(S_state
, CFSTR("*START*"));
3335 // Creates and returns a notification object for receiving IOKit
3336 // notifications of new devices or state changes.
3337 kr
= IOMasterPort(bootstrap_port
, &masterPort
);
3338 if (kr
!= KERN_SUCCESS
) {
3339 SC_log(LOG_ERR
, "IOMasterPort returned 0x%x", kr
);
3343 S_notify
= IONotificationPortCreate(masterPort
);
3344 if (S_notify
== NULL
) {
3345 SC_log(LOG_ERR
, "IONotificationPortCreate failed");
3349 // watch IOKit matching activity
3350 root
= IORegistryEntryFromPath(masterPort
, kIOServicePlane
":/");
3351 if (root
== MACH_PORT_NULL
) {
3352 SC_log(LOG_ERR
, "IORegistryEntryFromPath failed");
3356 kr
= IOServiceAddInterestNotification(S_notify
,
3360 (void *)S_notify
, // refCon
3361 &S_quiet
); // notification
3362 if (kr
!= KERN_SUCCESS
) {
3363 SC_log(LOG_ERR
, "IOServiceAddInterestNotification returned 0x%x", kr
);
3367 kr
= IOServiceGetBusyState(root
, &busy
);
3368 if (kr
!= KERN_SUCCESS
) {
3369 SC_log(LOG_ERR
, "IOServiceGetBusyState returned 0x%x", kr
);
3373 // add a timer so we don't wait forever for IOKit to quiesce
3374 S_timer
= CFRunLoopTimerCreate(NULL
,
3375 CFAbsoluteTimeGetCurrent() + S_stack_timeout
,
3381 if (S_timer
== NULL
) {
3382 SC_log(LOG_ERR
, "CFRunLoopTimerCreate failed");
3386 CFRunLoopAddTimer(CFRunLoopGetCurrent(), S_timer
, kCFRunLoopDefaultMode
);
3388 // watch for the introduction of the IONetworkStack
3389 kr
= IOServiceAddMatchingNotification(S_notify
,
3390 kIOFirstMatchNotification
,
3391 IOServiceMatching("IONetworkStack"),
3393 (void *)S_notify
, // refCon
3394 &S_stack
); // notification
3395 if (kr
!= KERN_SUCCESS
) {
3396 SC_log(LOG_ERR
, "IOServiceAddMatchingNotification returned 0x%x", kr
);
3400 // check and see if the stack is already available and arm the
3401 // notification for its introduction.
3402 stackCallback((void *)S_notify
, S_stack
);
3404 // watch for the introduction of new network interfaces
3405 kr
= IOServiceAddMatchingNotification(S_notify
,
3406 kIOFirstMatchNotification
,
3407 IOServiceMatching("IONetworkInterface"),
3408 &interfaceArrivalCallback
,
3409 (void *)S_notify
, // refCon
3410 &S_iter
); // notification
3411 if (kr
!= KERN_SUCCESS
) {
3412 SC_log(LOG_ERR
, "IOServiceAddMatchingNotification returned 0x%x", kr
);
3416 // Get the current list of matches and arm the notification for
3417 // future interface arrivals.
3418 interfaceArrivalCallback((void *)S_notify
, S_iter
);
3420 // Check if IOKit has already quiesced.
3421 quietCallback((void *)S_notify
,
3423 kIOMessageServiceBusyStateChange
,
3424 (void *)(uintptr_t)busy
);
3426 CFRunLoopAddSource(CFRunLoopGetCurrent(),
3427 IONotificationPortGetRunLoopSource(S_notify
),
3428 kCFRunLoopDefaultMode
);
3430 #ifdef WAIT_PREVIOUS_BOOT_INTERFACES_OR_QUIET
3432 * Start the wheels turning until we've named all of
3433 * the interfaces that were used during the previous
3434 * boot, until IOKit [matching] has quiesced, or
3435 * until we've waited long enough.
3437 CFRunLoopAddTimer(CFRunLoopGetCurrent(), S_timer
, MY_PLUGIN_ID
);
3438 CFRunLoopAddSource(CFRunLoopGetCurrent(),
3439 IONotificationPortGetRunLoopSource(S_notify
),
3441 while (S_prev_active_list
!= NULL
) {
3444 rlStatus
= CFRunLoopRunInMode(MY_PLUGIN_ID
, 1.0e10
, TRUE
);
3446 #endif /* WAIT_PREVIOUS_BOOT_INTERFACES_OR_QUIET */
3449 if (S_dblist
!= NULL
) {
3450 // apply special handling for the BT-PAN interface (if present)
3451 CFArrayApplyFunction(S_dblist
,
3452 CFRangeMake(0, CFArrayGetCount(S_dblist
)),
3453 updateBTPANInformation
,
3456 #endif // TARGET_OS_OSX
3461 if (root
!= MACH_PORT_NULL
) {
3462 IOObjectRelease(root
);
3464 if (masterPort
!= MACH_PORT_NULL
) {
3465 mach_port_deallocate(mach_task_self(), masterPort
);
3472 setup_Virtual(CFBundleRef bundle
)
3474 #pragma unused(bundle)
3475 // open a SCPreferences session
3476 S_prefs
= SCPreferencesCreate(NULL
, CFSTR(MY_PLUGIN_NAME
":setup_Virtual"), NULL
);
3477 if (S_prefs
== NULL
) {
3478 SC_log(LOG_ERR
, "SCPreferencesCreate() failed: %s",
3479 SCErrorString(SCError()));
3483 // register for change notifications.
3484 if (!SCPreferencesSetCallback(S_prefs
, updateVirtualNetworkInterfaceConfiguration
, NULL
)) {
3485 SC_log(LOG_ERR
, "SCPreferencesSetCallBack() failed: %s", SCErrorString(SCError()));
3491 if (!SCPreferencesScheduleWithRunLoop(S_prefs
, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode
)) {
3492 if (SCError() != kSCStatusNoStoreServer
) {
3493 SC_log(LOG_ERR
, "SCPreferencesScheduleWithRunLoop() failed: %s", SCErrorString(SCError()));
3503 exec_InterfaceNamer(void *arg
)
3505 CFBundleRef bundle
= (CFBundleRef
)arg
;
3506 CFDictionaryRef dict
;
3508 pthread_setname_np(MY_PLUGIN_NAME
" thread");
3510 dict
= CFBundleGetInfoDictionary(bundle
);
3511 if (isA_CFDictionary(dict
)) {
3514 num
= CFDictionaryGetValue(dict
, CFSTR(WAIT_STACK_TIMEOUT_KEY
));
3516 if (!isA_CFNumber(num
) ||
3517 !CFNumberGetValue(num
, kCFNumberDoubleType
, &S_stack_timeout
) ||
3518 (S_stack_timeout
<= 0.0)) {
3519 SC_log(LOG_NOTICE
, WAIT_STACK_TIMEOUT_KEY
" value error");
3520 S_stack_timeout
= WAIT_STACK_TIMEOUT_DEFAULT
;
3524 num
= CFDictionaryGetValue(dict
, CFSTR(WAIT_QUIET_TIMEOUT_KEY
));
3526 if (!isA_CFNumber(num
) ||
3527 !CFNumberGetValue(num
, kCFNumberDoubleType
, &S_quiet_timeout
) ||
3528 (S_quiet_timeout
<= 0.0)) {
3529 SC_log(LOG_NOTICE
, WAIT_QUIET_TIMEOUT_KEY
" value error");
3530 S_quiet_timeout
= WAIT_QUIET_TIMEOUT_DEFAULT
;
3535 // setup virtual network interface monitoring
3536 if (!setup_Virtual(bundle
)) {
3540 // setup [IOKit] network interface monitoring
3541 if (!setup_IOKit(bundle
)) {
3548 if (S_connect
!= MACH_PORT_NULL
) {
3549 IOServiceClose(S_connect
);
3550 S_connect
= MACH_PORT_NULL
;
3552 if (S_dblist
!= NULL
) {
3553 CFRelease(S_dblist
);
3556 if (S_iter
!= MACH_PORT_NULL
) {
3557 IOObjectRelease(S_iter
);
3558 S_iter
= MACH_PORT_NULL
;
3560 if (S_notify
!= MACH_PORT_NULL
) {
3561 IONotificationPortDestroy(S_notify
);
3563 if (S_quiet
!= MACH_PORT_NULL
) {
3564 IOObjectRelease(S_quiet
);
3565 S_quiet
= MACH_PORT_NULL
;
3567 if (S_stack
!= MACH_PORT_NULL
) {
3568 IOObjectRelease(S_stack
);
3569 S_stack
= MACH_PORT_NULL
;
3571 if (S_state
!= NULL
) {
3575 if (S_timer
!= NULL
) {
3576 CFRunLoopTimerInvalidate(S_timer
);
3590 load_InterfaceNamer(CFBundleRef bundle
, Boolean bundleVerbose
)
3592 #pragma unused(bundleVerbose)
3593 pthread_attr_t tattr
;
3596 CFRetain(bundle
); // released in exec_InterfaceNamer
3598 pthread_attr_init(&tattr
);
3599 pthread_attr_setscope(&tattr
, PTHREAD_SCOPE_SYSTEM
);
3600 pthread_attr_setdetachstate(&tattr
, PTHREAD_CREATE_DETACHED
);
3601 // pthread_attr_setstacksize(&tattr, 96 * 1024); // each thread gets a 96K stack
3602 pthread_create(&tid
, &tattr
, exec_InterfaceNamer
, bundle
);
3603 pthread_attr_destroy(&tattr
);
3608 //------------------------------------------------------------------------
3612 main(int argc
, char ** argv
)
3617 _sc_verbose
= (argc
> 1) ? TRUE
: FALSE
;
3619 bundle
= CFBundleGetMainBundle();
3620 CFRetain(bundle
); // released in exec_InterfaceNamer
3622 (void)exec_InterfaceNamer();
3630 #ifdef TEST_SNAPSHOT
3632 main(int argc
, char ** argv
)
3634 CFStringRef snapshot
;
3637 _sc_verbose
= (argc
> 1) ? TRUE
: FALSE
;
3639 snapshot
= captureBusy();
3640 SCPrint(TRUE
, stdout
, CFSTR("%@\n"), snapshot
);
3641 CFRelease(snapshot
);
3646 #endif /* TEST_SNAPSHOT */