2 * Copyright (c) 2000-2008, 2010, 2012 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>
40 #include <sys/types.h>
45 #include <SystemConfiguration/SystemConfiguration.h>
46 #include <SystemConfiguration/SCPrivate.h>
47 #include <SystemConfiguration/SCValidation.h>
53 static SCPreferencesRef prefs
= NULL
;
54 static SCDynamicStoreRef store
= NULL
;
56 /* preferences "initialization" globals */
57 static CFStringRef initKey
= NULL
;
58 static CFRunLoopSourceRef initRls
= NULL
;
60 /* SCDynamicStore (Setup:) */
61 static CFMutableDictionaryRef currentPrefs
; /* current prefs */
62 static CFMutableDictionaryRef newPrefs
; /* new prefs */
63 static CFMutableArrayRef unchangedPrefsKeys
; /* new prefs keys which match current */
64 static CFMutableArrayRef removedPrefsKeys
; /* old prefs keys to be removed */
66 static Boolean rofs
= FALSE
;
67 static Boolean _verbose
= FALSE
;
71 establishNewPreferences()
74 SCNetworkSetRef current
= NULL
;
75 CFStringRef new_model
;
77 int sc_status
= kSCStatusFailed
;
78 SCNetworkSetRef set
= NULL
;
79 CFStringRef setName
= NULL
;
80 Boolean updated
= FALSE
;
83 ok
= SCPreferencesLock(prefs
, TRUE
);
88 sc_status
= SCError();
89 if (sc_status
== kSCStatusStale
) {
90 SCPreferencesSynchronize(prefs
);
93 CFSTR("Could not acquire network configuration lock: %s"),
94 SCErrorString(sc_status
));
99 /* Ensure that the preferences has the new model */
100 new_model
= _SC_hw_model();
102 /* Need to regenerate the new configuration for new model */
103 if (new_model
!= NULL
) {
104 CFStringRef old_model
;
106 old_model
= SCPreferencesGetValue(prefs
, MODEL
);
107 if ((old_model
!= NULL
) && !_SC_CFEqual(old_model
, new_model
)) {
112 keys
= SCPreferencesCopyKeyList(prefs
);
113 count
= (keys
!= NULL
) ? CFArrayGetCount(keys
) : 0;
115 for (index
= 0; index
< count
; index
++) {
116 CFStringRef existing_key
;
118 existing_key
= CFArrayGetValueAtIndex(keys
, index
);
120 if (isA_CFString(existing_key
) != NULL
) {
122 CFPropertyListRef value
;
124 /* If it already contains a Model
125 or if it already contains a MODEL:KEY key skip it*/
126 if (CFEqual(existing_key
, MODEL
)
127 || CFStringFind(existing_key
, CFSTR(":"), 0).location
132 value
= SCPreferencesGetValue(prefs
, existing_key
);
134 /* Create a new key as OLD_MODEL:OLD_KEY */
135 new_key
= CFStringCreateWithFormat(NULL
, NULL
, CFSTR("%@:%@"),
136 old_model
, existing_key
);
137 SCPreferencesSetValue(prefs
, new_key
, value
);
139 /* Let's preserve existing host names */
140 if (!CFEqual(existing_key
, kSCPrefSystem
)) {
141 SCPreferencesRemoveValue(prefs
, existing_key
);
151 /* Set the new model */
152 SCPreferencesSetValue(prefs
, MODEL
, new_model
);
155 current
= SCNetworkSetCopyCurrent(prefs
);
156 if (current
!= NULL
) {
161 set
= SCNetworkSetCreate(prefs
);
164 sc_status
= SCError();
168 bundle
= _SC_CFBundleGet();
169 if (bundle
!= NULL
) {
170 setName
= CFBundleCopyLocalizedString(bundle
,
171 CFSTR("DEFAULT_SET_NAME"),
176 ok
= SCNetworkSetSetName(set
, (setName
!= NULL
) ? setName
: CFSTR("Automatic"));
178 sc_status
= SCError();
182 ok
= SCNetworkSetSetCurrent(set
);
184 sc_status
= SCError();
189 ok
= SCNetworkSetEstablishDefaultConfiguration(set
);
191 sc_status
= SCError();
198 ok
= SCPreferencesCommitChanges(prefs
);
200 SCLog(TRUE
, LOG_NOTICE
, CFSTR("New network configuration saved"));
203 sc_status
= SCError();
204 if (sc_status
== EROFS
) {
205 /* a read-only fileysstem is OK */
208 /* ... but we don't want to synchronize */
213 /* apply (committed or temporary/read-only) changes */
214 (void) SCPreferencesApplyChanges(prefs
);
215 } else if ((current
== NULL
) && (set
!= NULL
)) {
216 (void) SCNetworkSetRemove(set
);
221 CFSTR("Could not establish network configuration: %s"),
222 SCErrorString(sc_status
));
225 (void)SCPreferencesUnlock(prefs
);
226 if (setName
!= NULL
) CFRelease(setName
);
227 if (set
!= NULL
) CFRelease(set
);
233 quiet(Boolean
*timeout
)
235 CFDictionaryRef dict
;
236 Boolean _quiet
= FALSE
;
237 Boolean _timeout
= FALSE
;
240 dict
= SCDynamicStoreCopyValue(store
, initKey
);
242 if (isA_CFDictionary(dict
)) {
243 if (CFDictionaryContainsKey(dict
, CFSTR("*QUIET*"))) {
246 if (CFDictionaryContainsKey(dict
, CFSTR("*TIMEOUT*"))) {
253 if (timeout
!= NULL
) {
263 if ((initKey
== NULL
) || (initRls
== NULL
)) {
267 (void) SCDynamicStoreSetNotificationKeys(store
, NULL
, NULL
);
269 CFRunLoopSourceInvalidate(initRls
);
286 initKey
= SCDynamicStoreKeyCreate(NULL
,
287 CFSTR("%@" "InterfaceNamer"),
288 kSCDynamicStoreDomainPlugin
);
290 initRls
= SCDynamicStoreCreateRunLoopSource(NULL
, store
, 0);
291 CFRunLoopAddSource(CFRunLoopGetCurrent(), initRls
, kCFRunLoopDefaultMode
);
293 keys
= CFArrayCreate(NULL
, (const void **)&initKey
, 1, &kCFTypeArrayCallBacks
);
294 ok
= SCDynamicStoreSetNotificationKeys(store
, keys
, NULL
);
298 CFSTR("SCDynamicStoreSetNotificationKeys() failed: %s\n"), SCErrorString(SCError()));
309 watchQuietCallback(SCDynamicStoreRef store
, CFArrayRef changedKeys
, void *info
)
312 Boolean _timeout
= FALSE
;
314 _quiet
= quiet(&_timeout
);
316 #if !TARGET_OS_IPHONE
318 #endif /* !TARGET_OS_IPHONE */
323 if (_quiet
|| _timeout
) {
324 static int logged
= 0;
326 (void) establishNewPreferences();
327 if (_timeout
&& (logged
++ == 0)) {
328 SCLog(TRUE
, LOG_NOTICE
,
329 CFSTR("Network configuration creation timed out waiting for IORegistry"));
338 updateCache(const void *key
, const void *value
, void *context
)
340 CFStringRef configKey
= (CFStringRef
)key
;
341 CFPropertyListRef configData
= (CFPropertyListRef
)value
;
342 CFPropertyListRef cacheData
;
345 cacheData
= CFDictionaryGetValue(currentPrefs
, configKey
);
348 if (CFEqual(cacheData
, configData
)) {
350 * if the old & new property list values have
351 * not changed then we don't need to update
354 CFArrayAppendValue(unchangedPrefsKeys
, configKey
);
358 /* in any case, this key should not be removed */
359 i
= CFArrayGetFirstIndexOfValue(removedPrefsKeys
,
360 CFRangeMake(0, CFArrayGetCount(removedPrefsKeys
)),
362 if (i
!= kCFNotFound
) {
363 CFArrayRemoveValueAtIndex(removedPrefsKeys
, i
);
371 flatten(SCPreferencesRef prefs
,
373 CFDictionaryRef base
)
375 CFDictionaryRef subset
;
377 CFMutableDictionaryRef myDict
;
384 if (!CFDictionaryGetValueIfPresent(base
, kSCResvLink
, (const void **)&link
)) {
385 /* if this dictionary is not linked */
388 /* if __LINK__ key is present */
389 subset
= SCPreferencesPathGetValue(prefs
, link
);
391 /* if error with link */
393 CFSTR("SCPreferencesPathGetValue(,%@,) failed: %s"),
395 SCErrorString(SCError()));
400 if (CFDictionaryContainsKey(subset
, kSCResvInactive
)) {
401 /* if __INACTIVE__ key is present */
405 myKey
= CFStringCreateWithFormat(NULL
,
408 kSCDynamicStoreDomainSetup
,
411 myDict
= (CFMutableDictionaryRef
)CFDictionaryGetValue(newPrefs
, myKey
);
413 myDict
= CFDictionaryCreateMutableCopy(NULL
,
415 (CFDictionaryRef
)myDict
);
417 myDict
= CFDictionaryCreateMutable(NULL
,
419 &kCFTypeDictionaryKeyCallBacks
,
420 &kCFTypeDictionaryValueCallBacks
);
423 nKeys
= CFDictionaryGetCount(subset
);
425 keys
= CFAllocatorAllocate(NULL
, nKeys
* sizeof(CFStringRef
) , 0);
426 vals
= CFAllocatorAllocate(NULL
, nKeys
* sizeof(CFPropertyListRef
), 0);
427 CFDictionaryGetKeysAndValues(subset
, keys
, vals
);
428 for (i
= 0; i
< nKeys
; i
++) {
429 if (CFGetTypeID((CFTypeRef
)vals
[i
]) != CFDictionaryGetTypeID()) {
430 /* add this key/value to the current dictionary */
431 CFDictionarySetValue(myDict
, keys
[i
], vals
[i
]);
435 /* flatten [sub]dictionaries */
436 subKey
= CFStringCreateWithFormat(NULL
,
440 CFEqual(key
, CFSTR("/")) ? "" : "/",
442 flatten(prefs
, subKey
, vals
[i
]);
446 CFAllocatorDeallocate(NULL
, keys
);
447 CFAllocatorDeallocate(NULL
, vals
);
450 if (CFDictionaryGetCount(myDict
) > 0) {
451 /* add this dictionary to the new preferences */
452 CFDictionarySetValue(newPrefs
, myKey
, myDict
);
463 updateSCDynamicStore(SCPreferencesRef prefs
)
465 CFStringRef current
= NULL
;
466 CFDateRef date
= NULL
;
467 CFMutableDictionaryRef dict
= NULL
;
468 CFDictionaryRef global
= NULL
;
473 CFMutableArrayRef patterns
;
474 CFDictionaryRef set
= NULL
;
477 * initialize old preferences, new preferences, an array
478 * of keys which have not changed, and an array of keys
479 * to be removed (cleaned up).
482 patterns
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
483 pattern
= CFStringCreateWithFormat(NULL
,
486 kSCDynamicStoreDomainSetup
);
487 CFArrayAppendValue(patterns
, pattern
);
488 dict
= (CFMutableDictionaryRef
)SCDynamicStoreCopyMultiple(store
, NULL
, patterns
);
492 currentPrefs
= CFDictionaryCreateMutableCopy(NULL
, 0, dict
);
495 currentPrefs
= CFDictionaryCreateMutable(NULL
,
497 &kCFTypeDictionaryKeyCallBacks
,
498 &kCFTypeDictionaryValueCallBacks
);
501 unchangedPrefsKeys
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
503 i
= CFDictionaryGetCount(currentPrefs
);
505 const void **currentKeys
;
508 currentKeys
= CFAllocatorAllocate(NULL
, i
* sizeof(CFStringRef
), 0);
509 CFDictionaryGetKeysAndValues(currentPrefs
, currentKeys
, NULL
);
510 array
= CFArrayCreate(NULL
, currentKeys
, i
, &kCFTypeArrayCallBacks
);
511 removedPrefsKeys
= CFArrayCreateMutableCopy(NULL
, 0, array
);
513 CFAllocatorDeallocate(NULL
, currentKeys
);
515 removedPrefsKeys
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
519 * The "newPrefs" dictionary will contain the new / updated
520 * configuration which will be written to the configuration cache.
522 newPrefs
= CFDictionaryCreateMutable(NULL
,
524 &kCFTypeDictionaryKeyCallBacks
,
525 &kCFTypeDictionaryValueCallBacks
);
528 * create status dictionary associated with current configuration
529 * information including:
530 * - current set "name" to cache
531 * - time stamp indicating when the cache preferences were
534 dict
= CFDictionaryCreateMutable(NULL
,
536 &kCFTypeDictionaryKeyCallBacks
,
537 &kCFTypeDictionaryValueCallBacks
);
538 date
= CFDateCreate(NULL
, CFAbsoluteTimeGetCurrent());
543 keys
= SCPreferencesCopyKeyList(prefs
);
544 if ((keys
== NULL
) || (CFArrayGetCount(keys
) == 0)) {
545 SCLog(TRUE
, LOG_NOTICE
, CFSTR("updateConfiguration(): no preferences."));
550 * get "global" system preferences
552 global
= SCPreferencesGetValue(prefs
, kSCPrefSystem
);
554 /* if no global preferences are defined */
558 if (!isA_CFDictionary(global
)) {
560 CFSTR("updateConfiguration(): %@ is not a dictionary."),
565 /* flatten property list */
566 flatten(prefs
, CFSTR("/"), global
);
571 * get current set name
573 current
= SCPreferencesGetValue(prefs
, kSCPrefCurrentSet
);
575 /* if current set not defined */
579 if (!isA_CFString(current
)) {
581 CFSTR("updateConfiguration(): %@ is not a string."),
589 set
= SCPreferencesPathGetValue(prefs
, current
);
591 /* if error with path */
593 CFSTR("%@ value (%@) not valid"),
599 if (!isA_CFDictionary(set
)) {
601 CFSTR("updateConfiguration(): %@ is not a dictionary."),
606 /* flatten property list */
607 flatten(prefs
, CFSTR("/"), set
);
609 CFDictionarySetValue(dict
, kSCDynamicStorePropSetupCurrentSet
, current
);
613 /* add last updated time stamp */
614 CFDictionarySetValue(dict
, kSCDynamicStorePropSetupLastUpdated
, date
);
617 CFDictionarySetValue(newPrefs
, kSCDynamicStoreDomainSetup
, dict
);
619 /* compare current and new preferences */
620 CFDictionaryApplyFunction(newPrefs
, updateCache
, NULL
);
622 /* remove those keys which have not changed from the update */
623 n
= CFArrayGetCount(unchangedPrefsKeys
);
624 for (i
= 0; i
< n
; i
++) {
627 key
= CFArrayGetValueAtIndex(unchangedPrefsKeys
, i
);
628 CFDictionaryRemoveValue(newPrefs
, key
);
631 /* Update the dynamic store */
633 if (!SCDynamicStoreSetMultiple(store
, newPrefs
, removedPrefsKeys
, NULL
)) {
635 CFSTR("SCDynamicStoreSetMultiple() failed: %s"),
636 SCErrorString(SCError()));
639 SCLog(TRUE
, LOG_NOTICE
,
640 CFSTR("SCDynamicStore\nset: %@\nremove: %@\n"),
645 CFRelease(currentPrefs
);
647 CFRelease(unchangedPrefsKeys
);
648 CFRelease(removedPrefsKeys
);
649 if (dict
) CFRelease(dict
);
650 if (date
) CFRelease(date
);
651 if (keys
) CFRelease(keys
);
657 updateConfiguration(SCPreferencesRef prefs
,
658 SCPreferencesNotification notificationType
,
663 #if !TARGET_OS_IPHONE
664 if ((notificationType
& kSCPreferencesNotificationCommit
) == kSCPreferencesNotificationCommit
) {
665 SCNetworkSetRef current
;
667 current
= SCNetworkSetCopyCurrent(prefs
);
668 if (current
!= NULL
) {
669 /* network configuration available, disable template creation */
674 #endif /* !TARGET_OS_IPHONE */
676 if ((notificationType
& kSCPreferencesNotificationApply
) != kSCPreferencesNotificationApply
) {
680 SCLog(_verbose
, LOG_DEBUG
, CFSTR("updating configuration"));
682 /* update SCDynamicStore (Setup:) */
683 updateSCDynamicStore(prefs
);
685 /* finished with current prefs, wait for changes */
687 SCPreferencesSynchronize(prefs
);
696 prime_PreferencesMonitor()
698 SCLog(_verbose
, LOG_DEBUG
, CFSTR("prime() called"));
700 /* load the initial configuration from the database */
701 updateConfiguration(prefs
, kSCPreferencesNotificationApply
, (void *)store
);
709 load_PreferencesMonitor(CFBundleRef bundle
, Boolean bundleVerbose
)
711 Boolean initPrefs
= TRUE
;
717 SCLog(_verbose
, LOG_DEBUG
, CFSTR("load() called"));
718 SCLog(_verbose
, LOG_DEBUG
, CFSTR(" bundle ID = %@"), CFBundleGetIdentifier(bundle
));
720 /* open a SCDynamicStore session to allow cache updates */
721 store
= SCDynamicStoreCreate(NULL
,
722 CFSTR("PreferencesMonitor.bundle"),
727 CFSTR("SCDynamicStoreCreate() failed: %s"),
728 SCErrorString(SCError()));
732 /* open a SCPreferences session */
734 prefs
= SCPreferencesCreate(NULL
, CFSTR("PreferencesMonitor.bundle"), NULL
);
736 prefs
= SCPreferencesCreate(NULL
, CFSTR("PreferencesMonitor.bundle"), CFSTR("/tmp/preferences.plist"));
739 Boolean need_update
= FALSE
;
740 CFStringRef new_model
;
742 new_model
= _SC_hw_model();
744 /* Need to regenerate the new configuration for new model */
745 if (new_model
!= NULL
) {
746 CFStringRef old_model
;
748 old_model
= SCPreferencesGetValue(prefs
, MODEL
);
749 if (old_model
!= NULL
&& !_SC_CFEqual(old_model
, new_model
)) {
755 if (need_update
== FALSE
) {
756 SCNetworkSetRef current
;
758 current
= SCNetworkSetCopyCurrent(prefs
);
759 if (current
!= NULL
) {
760 /* network configuration available, disable template creation */
767 CFSTR("SCPreferencesCreate() failed: %s"),
768 SCErrorString(SCError()));
773 * register for change notifications.
775 if (!SCPreferencesSetCallback(prefs
, updateConfiguration
, NULL
)) {
777 CFSTR("SCPreferencesSetCallBack() failed: %s"),
778 SCErrorString(SCError()));
782 if (!SCPreferencesScheduleWithRunLoop(prefs
, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode
)) {
784 CFSTR("SCPreferencesScheduleWithRunLoop() failed: %s"),
785 SCErrorString(SCError()));
790 * if no preferences, initialize with a template (now or
791 * when IOKit has quiesced).
795 watchQuietCallback(store
, NULL
, NULL
);
803 if (store
!= NULL
) CFRelease(store
);
804 if (prefs
!= NULL
) CFRelease(prefs
);
812 main(int argc
, char **argv
)
815 _sc_verbose
= (argc
> 1) ? TRUE
: FALSE
;
817 load_PreferencesMonitor(CFBundleGetMainBundle(), (argc
> 1) ? TRUE
: FALSE
);
818 prime_PreferencesMonitor();