2 * Copyright (c) 2000-2008, 2010, 2012-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 * April 2, 2004 Allan Nathanson <ajn@apple.com>
28 * - use SCPreference notification APIs
30 * June 24, 2001 Allan Nathanson <ajn@apple.com>
31 * - update to public SystemConfiguration.framework APIs
33 * November 10, 2000 Allan Nathanson <ajn@apple.com>
38 #include <TargetConditionals.h>
41 #include <sys/types.h>
46 #define SC_LOG_HANDLE __log_PreferencesMonitor
47 #define SC_LOG_HANDLE_TYPE static
48 #include <SystemConfiguration/SystemConfiguration.h>
49 #include <SystemConfiguration/SCPrivate.h>
50 #include <SystemConfiguration/SCValidation.h>
51 #include "plugin_shared.h"
54 #include <CommonCrypto/CommonDigest.h>
58 static SCPreferencesRef prefs
= NULL
;
59 static SCDynamicStoreRef store
= NULL
;
61 /* InterfaceNamer[.plugin] monitoring globals */
62 static CFMutableArrayRef excluded_interfaces
= NULL
; // of SCNetworkInterfaceRef
63 static CFMutableArrayRef excluded_names
= NULL
; // of CFStringRef (BSD name)
64 Boolean haveConfiguration
= FALSE
;
65 static CFStringRef namerKey
= NULL
;
66 static CFMutableArrayRef preconfigured_interfaces
= NULL
; // of SCNetworkInterfaceRef
67 static CFMutableArrayRef preconfigured_names
= NULL
; // of CFStringRef (BSD name)
69 /* KernelEventMonitor[.plugin] monitoring globals */
70 static CFStringRef interfacesKey
= NULL
;
72 /* SCDynamicStore (Setup:) */
73 static CFMutableDictionaryRef currentPrefs
; /* current prefs */
74 static CFMutableDictionaryRef newPrefs
; /* new prefs */
75 static CFMutableArrayRef unchangedPrefsKeys
; /* new prefs keys which match current */
76 static CFMutableArrayRef removedPrefsKeys
; /* old prefs keys to be removed */
78 static Boolean rofs
= FALSE
;
79 static Boolean restorePrefs
= FALSE
;
81 #define MY_PLUGIN_NAME "PreferencesMonitor"
82 #define MY_PLUGIN_ID CFSTR("com.apple.SystemConfiguration." MY_PLUGIN_NAME)
86 updateConfiguration(SCPreferencesRef prefs
,
87 SCPreferencesNotification notificationType
,
92 __log_PreferencesMonitor(void)
94 static os_log_t log
= NULL
;
97 log
= os_log_create("com.apple.SystemConfiguration", "PreferencesMonitor");
108 CFStringRef currentModel
= NULL
;
109 CFMutableStringRef modelPrefixStr
= NULL
;
110 CFArrayRef keyList
= NULL
;
111 CFIndex keyListCount
;
113 Boolean modified
= FALSE
;
114 int sc_status
= kSCStatusFailed
;
117 ok
= SCPreferencesLock(prefs
, TRUE
);
122 sc_status
= SCError();
123 if (sc_status
== kSCStatusStale
) {
124 SCPreferencesSynchronize(prefs
);
126 SC_log(LOG_NOTICE
, "Could not acquire network configuration lock: %s",
127 SCErrorString(sc_status
));
132 keyList
= SCPreferencesCopyKeyList(prefs
);
133 if (keyList
== NULL
) {
137 currentModel
= _SC_hw_model(FALSE
);
138 if (currentModel
== NULL
) {
142 /* Create "model:" string for prefix-check */
143 modelPrefixStr
= CFStringCreateMutableCopy(NULL
, 0, currentModel
);
144 CFStringAppend(modelPrefixStr
, CFSTR(":"));
146 keyListCount
= CFArrayGetCount(keyList
);
147 for (idx
= 0; idx
< keyListCount
; idx
++) {
148 CFStringRef existingKey
= CFArrayGetValueAtIndex(keyList
, idx
);
150 CFArrayRef splitKey
= NULL
;
151 CFPropertyListRef value
;
153 if (isA_CFString(existingKey
) == NULL
) {
157 if (!CFStringHasPrefix(existingKey
, modelPrefixStr
)) {
161 splitKey
= CFStringCreateArrayBySeparatingStrings(NULL
, existingKey
, CFSTR(":"));
162 key
= CFArrayGetValueAtIndex(splitKey
, 1);
163 value
= SCPreferencesGetValue(prefs
, existingKey
);
164 SCPreferencesSetValue(prefs
, key
, value
);
165 SCPreferencesRemoveValue(prefs
, existingKey
);
171 SCPreferencesRef ni_prefs
= NULL
;
172 ni_prefs
= SCPreferencesCreate(NULL
, MY_PLUGIN_ID
, CFSTR("NetworkInterfaces.plist"));
173 if (ni_prefs
== NULL
) {
177 ok
= _SCNetworkConfigurationCheckValidityWithPreferences(prefs
, ni_prefs
, NULL
);
180 //Commit the changes only if prefs files valid
182 if (!SCPreferencesCommitChanges(prefs
)) {
183 if (SCError() != EROFS
) {
184 SC_log(LOG_NOTICE
, "SCPreferencesCommitChanges() failed: %s",
185 SCErrorString(SCError()));
191 (void) SCPreferencesApplyChanges(prefs
);
196 (void) SCPreferencesUnlock(prefs
);
198 if (keyList
!= NULL
) {
201 if (modelPrefixStr
!= NULL
) {
202 CFRelease(modelPrefixStr
);
209 establishNewPreferences()
211 SCNetworkSetRef current
= NULL
;
212 CFStringRef new_model
;
214 int sc_status
= kSCStatusFailed
;
215 SCNetworkSetRef set
= NULL
;
216 Boolean updated
= FALSE
;
219 ok
= SCPreferencesLock(prefs
, TRUE
);
224 sc_status
= SCError();
225 if (sc_status
== kSCStatusStale
) {
226 SCPreferencesSynchronize(prefs
);
228 SC_log(LOG_NOTICE
, "Could not acquire network configuration lock: %s",
229 SCErrorString(sc_status
));
234 /* Ensure that the preferences has the new model */
235 new_model
= _SC_hw_model(FALSE
);
237 /* Need to regenerate the new configuration for new model */
238 if (new_model
!= NULL
) {
239 CFStringRef old_model
;
241 old_model
= SCPreferencesGetValue(prefs
, MODEL
);
242 if ((old_model
!= NULL
) && !_SC_CFEqual(old_model
, new_model
)) {
247 keys
= SCPreferencesCopyKeyList(prefs
);
248 count
= (keys
!= NULL
) ? CFArrayGetCount(keys
) : 0;
250 for (index
= 0; index
< count
; index
++) {
251 CFStringRef existing_key
;
253 existing_key
= CFArrayGetValueAtIndex(keys
, index
);
254 if (isA_CFString(existing_key
) != NULL
) {
256 CFPropertyListRef value
;
258 /* If it already contains a Model
259 or if it already contains a MODEL:KEY key skip it*/
260 if (CFEqual(existing_key
, MODEL
)
261 || CFStringFind(existing_key
, CFSTR(":"), 0).location
266 value
= SCPreferencesGetValue(prefs
, existing_key
);
268 /* Create a new key as OLD_MODEL:OLD_KEY */
269 new_key
= CFStringCreateWithFormat(NULL
, NULL
, CFSTR("%@:%@"),
270 old_model
, existing_key
);
271 SCPreferencesSetValue(prefs
, new_key
, value
);
272 if (!CFEqual(existing_key
, kSCPrefSystem
)) {
273 /* preserve existing host names */
274 SCPreferencesRemoveValue(prefs
, existing_key
);
284 /* Set the new model */
285 SCPreferencesSetValue(prefs
, MODEL
, new_model
);
288 current
= SCNetworkSetCopyCurrent(prefs
);
289 if (current
!= NULL
) {
294 set
= _SCNetworkSetCreateDefault(prefs
);
297 sc_status
= SCError();
302 ok
= SCNetworkSetEstablishDefaultConfiguration(set
);
304 sc_status
= SCError();
311 ok
= SCPreferencesCommitChanges(prefs
);
313 SC_log(LOG_NOTICE
, "New network configuration saved");
316 sc_status
= SCError();
317 if (sc_status
== EROFS
) {
318 /* a read-only fileysstem is OK */
321 /* ... but we don't want to synchronize */
326 /* apply (committed or temporary/read-only) changes */
327 (void) SCPreferencesApplyChanges(prefs
);
328 } else if ((current
== NULL
) && (set
!= NULL
)) {
329 (void) SCNetworkSetRemove(set
);
333 if (sc_status
== kSCStatusOK
) {
334 SC_log(LOG_NOTICE
, "Network configuration not updated");
336 SC_log(LOG_NOTICE
, "Could not establish network configuration: %s",
337 SCErrorString(sc_status
));
341 (void)SCPreferencesUnlock(prefs
);
342 if (set
!= NULL
) CFRelease(set
);
348 watchSCDynamicStore()
350 CFMutableArrayRef keys
;
352 CFRunLoopSourceRef rls
;
355 * watch for KernelEventMonitor[.bundle] changes (the list of
356 * active network interfaces)
358 interfacesKey
= SCDynamicStoreKeyCreateNetworkInterface(NULL
,
359 kSCDynamicStoreDomainState
);
362 * watch for InterfaceNamer[.bundle] changes (quiet, timeout,
363 * and the list of pre-configured interfaces)
365 namerKey
= SCDynamicStoreKeyCreate(NULL
,
366 CFSTR("%@" "InterfaceNamer"),
367 kSCDynamicStoreDomainPlugin
);
369 rls
= SCDynamicStoreCreateRunLoopSource(NULL
, store
, 0);
371 SC_log(LOG_NOTICE
, "SCDynamicStoreCreateRunLoopSource() failed: %s", SCErrorString(SCError()));
372 haveConfiguration
= TRUE
;
375 CFRunLoopAddSource(CFRunLoopGetCurrent(), rls
, kCFRunLoopDefaultMode
);
378 keys
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
379 CFArrayAppendValue(keys
, interfacesKey
);
380 CFArrayAppendValue(keys
, namerKey
);
381 ok
= SCDynamicStoreSetNotificationKeys(store
, keys
, NULL
);
384 SC_log(LOG_NOTICE
, "SCDynamicStoreSetNotificationKeys() failed: %s", SCErrorString(SCError()));
385 haveConfiguration
= TRUE
;
393 previousConfigurationAvailable()
395 CFStringRef backupKey
= NULL
;
396 CFStringRef currentModel
= NULL
;
397 CFPropertyListRef properties
= NULL
;
399 currentModel
= _SC_hw_model(FALSE
);
400 if (currentModel
== NULL
) {
404 /* Currently relying only if a backup of "Sets" is present */
405 backupKey
= CFStringCreateWithFormat(NULL
, NULL
, CFSTR("%@:Sets"), currentModel
);
406 properties
= SCPreferencesGetValue(prefs
, backupKey
);
407 CFRelease(backupKey
);
409 return (properties
!= NULL
);
414 findInterfaces(CFArrayRef interfaces
, CFMutableArrayRef
*matched_interfaces
, CFMutableArrayRef
*matched_names
)
418 Boolean updated
= FALSE
;
421 if (*matched_interfaces
!= NULL
) {
422 CFRelease(*matched_interfaces
);
423 *matched_interfaces
= NULL
;
425 if (*matched_names
!= NULL
) {
426 nx
= CFArrayGetCount(*matched_names
);
427 CFRelease(*matched_names
);
428 *matched_names
= NULL
;
431 n
= (interfaces
!= NULL
) ? CFArrayGetCount(interfaces
) : 0;
432 for (CFIndex i
= 0; i
< n
; i
++) {
433 CFStringRef bsdName
= CFArrayGetValueAtIndex(interfaces
, i
);
434 SCNetworkInterfaceRef interface
;
436 for (int retry
= 0; retry
< 10; retry
++) {
438 // add short delay (before retry)
439 usleep(20 * 1000); // 20ms
442 interface
= _SCNetworkInterfaceCreateWithBSDName(NULL
, bsdName
, kIncludeNoVirtualInterfaces
);
443 if (interface
== NULL
) {
444 SC_log(LOG_ERR
, "could not create network interface for %@", bsdName
);
445 } else if (_SCNetworkInterfaceGetIOPath(interface
) == NULL
) {
446 SC_log(LOG_ERR
, "could not get IOPath for %@", bsdName
);
447 CFRelease(interface
);
451 if (interface
== NULL
) {
452 // if SCNetworkInterface not [currently] available
456 // keep track of the interface name (quicker than having to iterate the list
457 // of SCNetworkInterfaces, extract the name, and compare).
458 if (*matched_names
== NULL
) {
459 *matched_names
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
461 CFArrayAppendValue(*matched_names
, bsdName
);
463 if (*matched_interfaces
== NULL
) {
464 *matched_interfaces
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
466 CFArrayAppendValue(*matched_interfaces
, interface
);
467 CFRelease(interface
);
474 // check if all interfaces were detached
475 n
= (*matched_names
!= NULL
) ? CFArrayGetCount(*matched_names
) : 0;
476 if ((nx
> 0) && (n
== 0)) {
485 storeCallback(SCDynamicStoreRef store
, CFArrayRef changedKeys
, void *info
)
488 CFDictionaryRef dict
;
489 Boolean quiet
= FALSE
;
490 Boolean timeout
= FALSE
;
491 Boolean updated
= FALSE
;
494 * Capture/process InterfaceNamer[.bundle] info
495 * 1. check if IORegistry "quiet", "timeout"
496 * 2. update list of excluded interfaces (e.g. those requiring that
497 * the attached host be trusted)
498 * 3. update list of named pre-configured interfaces
500 dict
= SCDynamicStoreCopyValue(store
, namerKey
);
502 if (isA_CFDictionary(dict
)) {
504 CFArrayRef preconfigured
;
506 if (CFDictionaryContainsKey(dict
, kInterfaceNamerKey_Quiet
)) {
509 if (CFDictionaryContainsKey(dict
, kInterfaceNamerKey_Timeout
)) {
513 excluded
= CFDictionaryGetValue(dict
, kInterfaceNamerKey_ExcludedInterfaces
);
514 excluded
= isA_CFArray(excluded
);
515 if (!_SC_CFEqual(excluded
, excluded_names
)) {
516 Boolean excluded_updated
;
518 excluded_updated
= findInterfaces(excluded
, &excluded_interfaces
, &excluded_names
);
519 if (excluded_updated
) {
520 CFStringRef interfaces
= CFSTR("<empty>");
522 // report [updated] pre-configured interfaces
523 if (excluded_names
!= NULL
) {
524 interfaces
= CFStringCreateByCombiningStrings(NULL
, excluded_names
, CFSTR(","));
526 CFRetain(interfaces
);
528 SC_log(LOG_INFO
, "excluded interface list changed: %@", interfaces
);
529 CFRelease(interfaces
);
535 preconfigured
= CFDictionaryGetValue(dict
, kInterfaceNamerKey_PreConfiguredInterfaces
);
536 preconfigured
= isA_CFArray(preconfigured
);
537 if (!_SC_CFEqual(preconfigured
, preconfigured_names
)) {
538 Boolean preconfigured_updated
;
540 preconfigured_updated
= findInterfaces(preconfigured
, &preconfigured_interfaces
, &preconfigured_names
);
541 if (preconfigured_updated
) {
542 CFStringRef interfaces
= CFSTR("<empty>");
544 // report [updated] pre-configured interfaces
545 if (preconfigured_names
!= NULL
) {
546 interfaces
= CFStringCreateByCombiningStrings(NULL
, preconfigured_names
, CFSTR(","));
548 CFRetain(interfaces
);
550 SC_log(LOG_INFO
, "pre-configured interface list changed: %@", interfaces
);
551 CFRelease(interfaces
);
561 if (!haveConfiguration
&& (quiet
|| timeout
)) {
562 static int logged
= 0;
565 #if !TARGET_OS_IPHONE
567 #endif /* !TARGET_OS_IPHONE */
569 haveConfiguration
= TRUE
;
572 (void) establishNewPreferences();
575 (void) restorePreferences();
576 restorePrefs
= FALSE
;
579 if (timeout
&& (logged
++ == 0)) {
580 SC_log(LOG_ERR
, "Network configuration creation timed out waiting for IORegistry");
584 if (updated
&& (changedKeys
!= NULL
)) {
585 // if pre-configured interface list changed
586 updateConfiguration(prefs
, kSCPreferencesNotificationApply
, (void *)store
);
594 updateCache(const void *key
, const void *value
, void *context
)
596 #pragma unused(context)
597 CFStringRef configKey
= (CFStringRef
)key
;
598 CFPropertyListRef configData
= (CFPropertyListRef
)value
;
599 CFPropertyListRef cacheData
;
602 cacheData
= CFDictionaryGetValue(currentPrefs
, configKey
);
605 if (CFEqual(cacheData
, configData
)) {
607 * if the old & new property list values have
608 * not changed then we don't need to update
611 CFArrayAppendValue(unchangedPrefsKeys
, configKey
);
615 /* in any case, this key should not be removed */
616 i
= CFArrayGetFirstIndexOfValue(removedPrefsKeys
,
617 CFRangeMake(0, CFArrayGetCount(removedPrefsKeys
)),
619 if (i
!= kCFNotFound
) {
620 CFArrayRemoveValueAtIndex(removedPrefsKeys
, i
);
628 flatten(SCPreferencesRef prefs
,
630 CFDictionaryRef base
)
632 CFDictionaryRef subset
;
634 CFMutableDictionaryRef myDict
;
641 if (!CFDictionaryGetValueIfPresent(base
, kSCResvLink
, (const void **)&link
)) {
642 /* if this dictionary is not linked */
645 /* if __LINK__ key is present */
646 subset
= SCPreferencesPathGetValue(prefs
, link
);
648 /* if error with link */
649 SC_log(LOG_NOTICE
, "SCPreferencesPathGetValue(,%@,) failed: %s",
651 SCErrorString(SCError()));
656 if (CFDictionaryContainsKey(subset
, kSCResvInactive
)) {
657 /* if __INACTIVE__ key is present */
661 myKey
= CFStringCreateWithFormat(NULL
,
664 kSCDynamicStoreDomainSetup
,
667 myDict
= (CFMutableDictionaryRef
)CFDictionaryGetValue(newPrefs
, myKey
);
669 myDict
= CFDictionaryCreateMutableCopy(NULL
,
671 (CFDictionaryRef
)myDict
);
673 myDict
= CFDictionaryCreateMutable(NULL
,
675 &kCFTypeDictionaryKeyCallBacks
,
676 &kCFTypeDictionaryValueCallBacks
);
679 nKeys
= CFDictionaryGetCount(subset
);
681 keys
= CFAllocatorAllocate(NULL
, nKeys
* sizeof(CFStringRef
) , 0);
682 vals
= CFAllocatorAllocate(NULL
, nKeys
* sizeof(CFPropertyListRef
), 0);
683 CFDictionaryGetKeysAndValues(subset
, keys
, vals
);
684 for (i
= 0; i
< nKeys
; i
++) {
685 if (CFGetTypeID((CFTypeRef
)vals
[i
]) != CFDictionaryGetTypeID()) {
686 /* add this key/value to the current dictionary */
687 CFDictionarySetValue(myDict
, keys
[i
], vals
[i
]);
691 /* flatten [sub]dictionaries */
692 subKey
= CFStringCreateWithFormat(NULL
,
696 CFEqual(key
, CFSTR("/")) ? "" : "/",
698 flatten(prefs
, subKey
, vals
[i
]);
702 CFAllocatorDeallocate(NULL
, keys
);
703 CFAllocatorDeallocate(NULL
, vals
);
706 if (CFDictionaryGetCount(myDict
) > 0) {
707 /* add this dictionary to the new preferences */
708 CFDictionarySetValue(newPrefs
, myKey
, myDict
);
718 static CF_RETURNS_RETAINED CFStringRef
719 copyInterfaceUUID(CFStringRef bsdName
)
722 unsigned char sha256_bytes
[CC_SHA256_DIGEST_LENGTH
];
723 CFUUIDBytes uuid_bytes
;
726 char if_name
[IF_NAMESIZE
];
728 CFStringRef uuid_str
;
730 // start with interface name
731 memset(&if_name
, 0, sizeof(if_name
));
732 (void) _SC_cfstring_to_cstring(bsdName
,
735 kCFStringEncodingASCII
);
737 // create SHA256 hash
738 memset(&bytes
, 0, sizeof(bytes
));
739 CC_SHA256_Init(&ctx
);
740 CC_SHA256_Update(&ctx
,
743 CC_SHA256_Final(bytes
.sha256_bytes
, &ctx
);
745 // create UUID string
746 uuid
= CFUUIDCreateFromUUIDBytes(NULL
, bytes
.uuid_bytes
);
747 uuid_str
= CFUUIDCreateString(NULL
, uuid
);
755 excludeConfigurations(SCPreferencesRef prefs
)
762 range
= CFRangeMake(0,
763 (excluded_names
!= NULL
) ? CFArrayGetCount(excluded_names
) : 0);
764 if (range
.length
== 0) {
765 // if no [excluded] interfaces
769 set
= SCNetworkSetCopyCurrent(prefs
);
776 * Check for (and remove) any network services associated with
777 * an excluded interface from the prefs.
779 services
= SCNetworkSetCopyServices(set
);
780 if (services
!= NULL
) {
783 n
= CFArrayGetCount(services
);
784 for (CFIndex i
= 0; i
< n
; i
++) {
786 SCNetworkInterfaceRef interface
;
787 SCNetworkServiceRef service
;
789 service
= CFArrayGetValueAtIndex(services
, i
);
791 interface
= SCNetworkServiceGetInterface(service
);
792 if (interface
== NULL
) {
797 bsdName
= SCNetworkInterfaceGetBSDName(interface
);
798 if (bsdName
== NULL
) {
799 // if no interface name
803 if (!CFArrayContainsValue(excluded_names
, range
, bsdName
)) {
808 // remove [excluded] network service from the prefs
809 SC_log(LOG_NOTICE
, "excluding network service for %@", bsdName
);
810 ok
= SCNetworkSetRemoveService(set
, service
);
812 SC_log(LOG_ERR
, "SCNetworkSetRemoveService() failed: %s",
813 SCErrorString(SCError()));
826 updatePreConfiguredConfiguration(SCPreferencesRef prefs
)
832 Boolean updated
= FALSE
;
834 range
= CFRangeMake(0,
835 (preconfigured_names
!= NULL
) ? CFArrayGetCount(preconfigured_names
) : 0);
836 if (range
.length
== 0) {
837 // if no [pre-configured] interfaces
841 set
= SCNetworkSetCopyCurrent(prefs
);
848 * Check for (and remove) any network services associated with
849 * a pre-configured interface from the prefs.
851 services
= SCNetworkServiceCopyAll(prefs
);
852 if (services
!= NULL
) {
855 n
= CFArrayGetCount(services
);
856 for (CFIndex i
= 0; i
< n
; i
++) {
858 SCNetworkInterfaceRef interface
;
859 SCNetworkServiceRef service
;
861 service
= CFArrayGetValueAtIndex(services
, i
);
863 interface
= SCNetworkServiceGetInterface(service
);
864 if (interface
== NULL
) {
869 bsdName
= SCNetworkInterfaceGetBSDName(interface
);
870 if (bsdName
== NULL
) {
871 // if no interface name
875 if (!CFArrayContainsValue(preconfigured_names
, range
, bsdName
)) {
876 // if not preconfigured
880 // remove [preconfigured] network service from the prefs
881 SC_log(LOG_NOTICE
, "removing network service for %@", bsdName
);
882 ok
= SCNetworkServiceRemove(service
);
884 SC_log(LOG_ERR
, "SCNetworkServiceRemove() failed: %s",
885 SCErrorString(SCError()));
894 // commit the updated prefs ... but don't apply
895 ok
= SCPreferencesCommitChanges(prefs
);
897 if (SCError() != EROFS
) {
898 SC_log(LOG_ERR
, "SCPreferencesCommitChanges() failed: %s",
899 SCErrorString(SCError()));
905 * Now, add a new network service for each pre-configured interface
907 for (CFIndex i
= 0; i
< range
.length
; i
++) {
909 SCNetworkInterfaceRef interface
= CFArrayGetValueAtIndex(preconfigured_interfaces
, i
);
910 SCNetworkServiceRef service
;
911 CFStringRef serviceID
;
913 bsdName
= SCNetworkInterfaceGetBSDName(interface
);
915 // create network service
916 service
= SCNetworkServiceCreate(prefs
, interface
);
917 if (service
== NULL
) {
918 SC_log(LOG_ERR
, "could not create network service for \"%@\": %s",
920 SCErrorString(SCError()));
924 // update network service to use a consistent serviceID
925 serviceID
= copyInterfaceUUID(bsdName
);
926 if (serviceID
!= NULL
) {
927 ok
= _SCNetworkServiceSetServiceID(service
, serviceID
);
928 CFRelease(serviceID
);
930 SC_log(LOG_ERR
, "_SCNetworkServiceSetServiceID() failed: %s",
931 SCErrorString(SCError()));
932 // ... and keep whatever random UUID was created for the service
935 SC_log(LOG_ERR
, "could not create serviceID for \"%@\"", bsdName
);
936 // ... and we'll use whatever random UUID was created for the service
939 // establish [template] configuration
940 ok
= SCNetworkServiceEstablishDefaultConfiguration(service
);
942 SC_log(LOG_ERR
, "could not establish network service for \"%@\": %s",
944 SCErrorString(SCError()));
945 SCNetworkServiceRemove(service
);
950 // add network service to the current set
951 ok
= SCNetworkSetAddService(set
, service
);
953 SC_log(LOG_ERR
, "could not add service for \"%@\": %s",
955 SCErrorString(SCError()));
956 SCNetworkServiceRemove(service
);
961 SC_log(LOG_INFO
, "network service %@ added for \"%@\"",
962 SCNetworkServiceGetServiceID(service
),
974 updateSCDynamicStore(SCPreferencesRef prefs
)
976 CFStringRef current
= NULL
;
977 CFDateRef date
= NULL
;
978 CFMutableDictionaryRef dict
= NULL
;
979 CFDictionaryRef global
= NULL
;
984 CFMutableArrayRef patterns
;
985 CFDictionaryRef set
= NULL
;
988 * initialize old preferences, new preferences, an array
989 * of keys which have not changed, and an array of keys
990 * to be removed (cleaned up).
993 patterns
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
994 pattern
= CFStringCreateWithFormat(NULL
,
997 kSCDynamicStoreDomainSetup
);
998 CFArrayAppendValue(patterns
, pattern
);
999 dict
= (CFMutableDictionaryRef
)SCDynamicStoreCopyMultiple(store
, NULL
, patterns
);
1000 CFRelease(patterns
);
1003 currentPrefs
= CFDictionaryCreateMutableCopy(NULL
, 0, dict
);
1006 currentPrefs
= CFDictionaryCreateMutable(NULL
,
1008 &kCFTypeDictionaryKeyCallBacks
,
1009 &kCFTypeDictionaryValueCallBacks
);
1012 unchangedPrefsKeys
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
1014 i
= CFDictionaryGetCount(currentPrefs
);
1016 const void **currentKeys
;
1019 currentKeys
= CFAllocatorAllocate(NULL
, i
* sizeof(CFStringRef
), 0);
1020 CFDictionaryGetKeysAndValues(currentPrefs
, currentKeys
, NULL
);
1021 array
= CFArrayCreate(NULL
, currentKeys
, i
, &kCFTypeArrayCallBacks
);
1022 removedPrefsKeys
= CFArrayCreateMutableCopy(NULL
, 0, array
);
1024 CFAllocatorDeallocate(NULL
, currentKeys
);
1026 removedPrefsKeys
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
1030 * The "newPrefs" dictionary will contain the new / updated
1031 * configuration which will be written to the configuration cache.
1033 newPrefs
= CFDictionaryCreateMutable(NULL
,
1035 &kCFTypeDictionaryKeyCallBacks
,
1036 &kCFTypeDictionaryValueCallBacks
);
1039 * create status dictionary associated with current configuration
1040 * information including:
1041 * - current set "name" to cache
1042 * - time stamp indicating when the cache preferences were
1045 dict
= CFDictionaryCreateMutable(NULL
,
1047 &kCFTypeDictionaryKeyCallBacks
,
1048 &kCFTypeDictionaryValueCallBacks
);
1049 date
= CFDateCreate(NULL
, CFAbsoluteTimeGetCurrent());
1054 keys
= SCPreferencesCopyKeyList(prefs
);
1055 if ((keys
== NULL
) || (CFArrayGetCount(keys
) == 0)) {
1056 SC_log(LOG_NOTICE
, "updateConfiguration(): no preferences");
1061 * get "global" system preferences
1063 global
= SCPreferencesGetValue(prefs
, kSCPrefSystem
);
1065 /* if no global preferences are defined */
1069 if (!isA_CFDictionary(global
)) {
1070 SC_log(LOG_NOTICE
, "updateConfiguration(): %@ is not a dictionary",
1075 /* flatten property list */
1076 flatten(prefs
, CFSTR("/"), global
);
1081 * get current set name
1083 current
= SCPreferencesGetValue(prefs
, kSCPrefCurrentSet
);
1085 /* if current set not defined */
1089 if (!isA_CFString(current
)) {
1090 SC_log(LOG_NOTICE
, "updateConfiguration(): %@ is not a string",
1098 set
= SCPreferencesPathGetValue(prefs
, current
);
1100 /* if error with path */
1101 SC_log(LOG_NOTICE
, "%@ value (%@) not valid",
1107 if (!isA_CFDictionary(set
)) {
1108 SC_log(LOG_NOTICE
, "updateConfiguration(): %@ is not a dictionary",
1113 /* flatten property list */
1114 flatten(prefs
, CFSTR("/"), set
);
1116 CFDictionarySetValue(dict
, kSCDynamicStorePropSetupCurrentSet
, current
);
1120 /* add last updated time stamp */
1121 CFDictionarySetValue(dict
, kSCDynamicStorePropSetupLastUpdated
, date
);
1123 /* add Setup: key */
1124 CFDictionarySetValue(newPrefs
, kSCDynamicStoreDomainSetup
, dict
);
1126 /* compare current and new preferences */
1127 CFDictionaryApplyFunction(newPrefs
, updateCache
, NULL
);
1129 /* remove those keys which have not changed from the update */
1130 n
= CFArrayGetCount(unchangedPrefsKeys
);
1131 for (i
= 0; i
< n
; i
++) {
1134 key
= CFArrayGetValueAtIndex(unchangedPrefsKeys
, i
);
1135 CFDictionaryRemoveValue(newPrefs
, key
);
1138 /* Update the dynamic store */
1140 if (!SCDynamicStoreSetMultiple(store
, newPrefs
, removedPrefsKeys
, NULL
)) {
1141 SC_log(LOG_NOTICE
, "SCDynamicStoreSetMultiple() failed: %s", SCErrorString(SCError()));
1144 SC_log(LOG_DEBUG
, "SCDynamicStore\nset: %@\nremove: %@",
1149 CFRelease(currentPrefs
);
1150 CFRelease(newPrefs
);
1151 CFRelease(unchangedPrefsKeys
);
1152 CFRelease(removedPrefsKeys
);
1153 if (dict
) CFRelease(dict
);
1154 if (date
) CFRelease(date
);
1155 if (keys
) CFRelease(keys
);
1161 updateConfiguration(SCPreferencesRef prefs
,
1162 SCPreferencesNotification notificationType
,
1165 #pragma unused(info)
1166 #if !TARGET_OS_IPHONE
1167 if ((notificationType
& kSCPreferencesNotificationCommit
) == kSCPreferencesNotificationCommit
) {
1168 SCNetworkSetRef current
;
1170 current
= SCNetworkSetCopyCurrent(prefs
);
1171 if (current
!= NULL
) {
1172 /* network configuration available, disable template creation */
1173 haveConfiguration
= TRUE
;
1177 #endif /* !TARGET_OS_IPHONE */
1179 if ((notificationType
& kSCPreferencesNotificationApply
) != kSCPreferencesNotificationApply
) {
1183 SC_log(LOG_INFO
, "updating configuration");
1185 /* add any [Apple] pre-configured network services */
1186 updatePreConfiguredConfiguration(prefs
);
1188 /* remove any excluded network services */
1189 excludeConfigurations(prefs
);
1191 /* update SCDynamicStore (Setup:) */
1192 updateSCDynamicStore(prefs
);
1194 /* finished with current prefs, wait for changes */
1196 SCPreferencesSynchronize(prefs
);
1207 prime_PreferencesMonitor()
1209 SC_log(LOG_DEBUG
, "prime() called");
1211 /* load the initial configuration from the database */
1212 updateConfiguration(prefs
, kSCPreferencesNotificationApply
, (void *)store
);
1220 load_PreferencesMonitor(CFBundleRef bundle
, Boolean bundleVerbose
)
1222 #pragma unused(bundle)
1223 #pragma unused(bundleVerbose)
1224 SC_log(LOG_DEBUG
, "load() called");
1225 SC_log(LOG_DEBUG
, " bundle ID = %@", CFBundleGetIdentifier(bundle
));
1227 /* open a SCDynamicStore session to allow cache updates */
1228 store
= SCDynamicStoreCreate(NULL
,
1229 CFSTR("PreferencesMonitor.bundle"),
1232 if (store
== NULL
) {
1233 SC_log(LOG_NOTICE
, "SCDynamicStoreCreate() failed: %s", SCErrorString(SCError()));
1237 /* open a SCPreferences session */
1239 prefs
= SCPreferencesCreate(NULL
, CFSTR("PreferencesMonitor.bundle"), NULL
);
1241 prefs
= SCPreferencesCreate(NULL
, CFSTR("PreferencesMonitor.bundle"), CFSTR("/tmp/preferences.plist"));
1243 if (prefs
!= NULL
) {
1244 Boolean need_update
= FALSE
;
1245 CFStringRef new_model
;
1247 new_model
= _SC_hw_model(FALSE
);
1249 /* Need to regenerate the new configuration for new model */
1250 if (new_model
!= NULL
) {
1251 CFStringRef old_model
;
1253 old_model
= SCPreferencesGetValue(prefs
, MODEL
);
1254 if (old_model
!= NULL
&& !_SC_CFEqual(old_model
, new_model
)) {
1257 restorePrefs
= previousConfigurationAvailable();
1262 SCNetworkSetRef current
;
1264 current
= SCNetworkSetCopyCurrent(prefs
);
1265 if (current
!= NULL
) {
1266 /* network configuration available, disable template creation */
1267 haveConfiguration
= TRUE
;
1272 SC_log(LOG_NOTICE
, "SCPreferencesCreate() failed: %s", SCErrorString(SCError()));
1277 * register for change notifications.
1279 if (!SCPreferencesSetCallback(prefs
, updateConfiguration
, NULL
)) {
1280 SC_log(LOG_NOTICE
, "SCPreferencesSetCallBack() failed: %s", SCErrorString(SCError()));
1284 if (!SCPreferencesScheduleWithRunLoop(prefs
, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode
)) {
1285 SC_log(LOG_NOTICE
, "SCPreferencesScheduleWithRunLoop() failed: %s", SCErrorString(SCError()));
1290 * watch InterfaceNamer and KernelEventMonitor changes to know when
1291 * the IORegistry has quiesced (to create the initial configuration
1292 * template), to track any pre-configured interfaces, and to ensure
1293 * that we create a network service for any active interfaces.
1295 watchSCDynamicStore();
1296 storeCallback(store
, NULL
, NULL
);
1302 if (store
!= NULL
) CFRelease(store
);
1303 if (prefs
!= NULL
) CFRelease(prefs
);
1304 haveConfiguration
= TRUE
;
1312 main(int argc
, char **argv
)
1315 _sc_verbose
= (argc
> 1) ? TRUE
: FALSE
;
1317 load_PreferencesMonitor(CFBundleGetMainBundle(), (argc
> 1) ? TRUE
: FALSE
);
1318 prime_PreferencesMonitor();