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
);
138 SCPreferencesRemoveValue(prefs
, existing_key
);
148 /* Set the new model */
149 SCPreferencesSetValue(prefs
, MODEL
, new_model
);
152 current
= SCNetworkSetCopyCurrent(prefs
);
153 if (current
!= NULL
) {
158 set
= SCNetworkSetCreate(prefs
);
161 sc_status
= SCError();
165 bundle
= _SC_CFBundleGet();
166 if (bundle
!= NULL
) {
167 setName
= CFBundleCopyLocalizedString(bundle
,
168 CFSTR("DEFAULT_SET_NAME"),
173 ok
= SCNetworkSetSetName(set
, (setName
!= NULL
) ? setName
: CFSTR("Automatic"));
175 sc_status
= SCError();
179 ok
= SCNetworkSetSetCurrent(set
);
181 sc_status
= SCError();
186 ok
= SCNetworkSetEstablishDefaultConfiguration(set
);
188 sc_status
= SCError();
195 ok
= SCPreferencesCommitChanges(prefs
);
197 SCLog(TRUE
, LOG_NOTICE
, CFSTR("New network configuration saved"));
200 sc_status
= SCError();
201 if (sc_status
== EROFS
) {
202 /* a read-only fileysstem is OK */
205 /* ... but we don't want to synchronize */
210 /* apply (committed or temporary/read-only) changes */
211 (void) SCPreferencesApplyChanges(prefs
);
212 } else if ((current
== NULL
) && (set
!= NULL
)) {
213 (void) SCNetworkSetRemove(set
);
218 CFSTR("Could not establish network configuration: %s"),
219 SCErrorString(sc_status
));
222 (void)SCPreferencesUnlock(prefs
);
223 if (setName
!= NULL
) CFRelease(setName
);
224 if (set
!= NULL
) CFRelease(set
);
230 quiet(Boolean
*timeout
)
232 CFDictionaryRef dict
;
233 Boolean _quiet
= FALSE
;
234 Boolean _timeout
= FALSE
;
237 dict
= SCDynamicStoreCopyValue(store
, initKey
);
239 if (isA_CFDictionary(dict
)) {
240 if (CFDictionaryContainsKey(dict
, CFSTR("*QUIET*"))) {
243 if (CFDictionaryContainsKey(dict
, CFSTR("*TIMEOUT*"))) {
250 if (timeout
!= NULL
) {
260 if ((initKey
== NULL
) || (initRls
== NULL
)) {
264 (void) SCDynamicStoreSetNotificationKeys(store
, NULL
, NULL
);
266 CFRunLoopSourceInvalidate(initRls
);
283 initKey
= SCDynamicStoreKeyCreate(NULL
,
284 CFSTR("%@" "InterfaceNamer"),
285 kSCDynamicStoreDomainPlugin
);
287 initRls
= SCDynamicStoreCreateRunLoopSource(NULL
, store
, 0);
288 CFRunLoopAddSource(CFRunLoopGetCurrent(), initRls
, kCFRunLoopDefaultMode
);
290 keys
= CFArrayCreate(NULL
, (const void **)&initKey
, 1, &kCFTypeArrayCallBacks
);
291 ok
= SCDynamicStoreSetNotificationKeys(store
, keys
, NULL
);
295 CFSTR("SCDynamicStoreSetNotificationKeys() failed: %s\n"), SCErrorString(SCError()));
303 watchQuietCallback(SCDynamicStoreRef store
, CFArrayRef changedKeys
, void *info
)
306 Boolean _timeout
= FALSE
;
308 _quiet
= quiet(&_timeout
);
310 #if !TARGET_OS_IPHONE
312 #endif /* !TARGET_OS_IPHONE */
317 if (_quiet
|| _timeout
) {
318 static int logged
= 0;
320 (void) establishNewPreferences();
321 if (_timeout
&& (logged
++ == 0)) {
322 SCLog(TRUE
, LOG_NOTICE
,
323 CFSTR("Network configuration creation timed out waiting for IORegistry"));
332 updateCache(const void *key
, const void *value
, void *context
)
334 CFStringRef configKey
= (CFStringRef
)key
;
335 CFPropertyListRef configData
= (CFPropertyListRef
)value
;
336 CFPropertyListRef cacheData
;
339 cacheData
= CFDictionaryGetValue(currentPrefs
, configKey
);
342 if (CFEqual(cacheData
, configData
)) {
344 * if the old & new property list values have
345 * not changed then we don't need to update
348 CFArrayAppendValue(unchangedPrefsKeys
, configKey
);
352 /* in any case, this key should not be removed */
353 i
= CFArrayGetFirstIndexOfValue(removedPrefsKeys
,
354 CFRangeMake(0, CFArrayGetCount(removedPrefsKeys
)),
356 if (i
!= kCFNotFound
) {
357 CFArrayRemoveValueAtIndex(removedPrefsKeys
, i
);
365 flatten(SCPreferencesRef prefs
,
367 CFDictionaryRef base
)
369 CFDictionaryRef subset
;
371 CFMutableDictionaryRef myDict
;
378 if (!CFDictionaryGetValueIfPresent(base
, kSCResvLink
, (const void **)&link
)) {
379 /* if this dictionary is not linked */
382 /* if __LINK__ key is present */
383 subset
= SCPreferencesPathGetValue(prefs
, link
);
385 /* if error with link */
387 CFSTR("SCPreferencesPathGetValue(,%@,) failed: %s"),
389 SCErrorString(SCError()));
394 if (CFDictionaryContainsKey(subset
, kSCResvInactive
)) {
395 /* if __INACTIVE__ key is present */
399 myKey
= CFStringCreateWithFormat(NULL
,
402 kSCDynamicStoreDomainSetup
,
405 myDict
= (CFMutableDictionaryRef
)CFDictionaryGetValue(newPrefs
, myKey
);
407 myDict
= CFDictionaryCreateMutableCopy(NULL
,
409 (CFDictionaryRef
)myDict
);
411 myDict
= CFDictionaryCreateMutable(NULL
,
413 &kCFTypeDictionaryKeyCallBacks
,
414 &kCFTypeDictionaryValueCallBacks
);
417 nKeys
= CFDictionaryGetCount(subset
);
419 keys
= CFAllocatorAllocate(NULL
, nKeys
* sizeof(CFStringRef
) , 0);
420 vals
= CFAllocatorAllocate(NULL
, nKeys
* sizeof(CFPropertyListRef
), 0);
421 CFDictionaryGetKeysAndValues(subset
, keys
, vals
);
422 for (i
= 0; i
< nKeys
; i
++) {
423 if (CFGetTypeID((CFTypeRef
)vals
[i
]) != CFDictionaryGetTypeID()) {
424 /* add this key/value to the current dictionary */
425 CFDictionarySetValue(myDict
, keys
[i
], vals
[i
]);
429 /* flatten [sub]dictionaries */
430 subKey
= CFStringCreateWithFormat(NULL
,
434 CFEqual(key
, CFSTR("/")) ? "" : "/",
436 flatten(prefs
, subKey
, vals
[i
]);
440 CFAllocatorDeallocate(NULL
, keys
);
441 CFAllocatorDeallocate(NULL
, vals
);
444 if (CFDictionaryGetCount(myDict
) > 0) {
445 /* add this dictionary to the new preferences */
446 CFDictionarySetValue(newPrefs
, myKey
, myDict
);
457 updateSCDynamicStore(SCPreferencesRef prefs
)
459 CFStringRef current
= NULL
;
460 CFDateRef date
= NULL
;
461 CFMutableDictionaryRef dict
= NULL
;
462 CFDictionaryRef global
= NULL
;
467 CFMutableArrayRef patterns
;
468 CFDictionaryRef set
= NULL
;
471 * initialize old preferences, new preferences, an array
472 * of keys which have not changed, and an array of keys
473 * to be removed (cleaned up).
476 patterns
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
477 pattern
= CFStringCreateWithFormat(NULL
,
480 kSCDynamicStoreDomainSetup
);
481 CFArrayAppendValue(patterns
, pattern
);
482 dict
= (CFMutableDictionaryRef
)SCDynamicStoreCopyMultiple(store
, NULL
, patterns
);
486 currentPrefs
= CFDictionaryCreateMutableCopy(NULL
, 0, dict
);
489 currentPrefs
= CFDictionaryCreateMutable(NULL
,
491 &kCFTypeDictionaryKeyCallBacks
,
492 &kCFTypeDictionaryValueCallBacks
);
495 unchangedPrefsKeys
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
497 i
= CFDictionaryGetCount(currentPrefs
);
499 const void **currentKeys
;
502 currentKeys
= CFAllocatorAllocate(NULL
, i
* sizeof(CFStringRef
), 0);
503 CFDictionaryGetKeysAndValues(currentPrefs
, currentKeys
, NULL
);
504 array
= CFArrayCreate(NULL
, currentKeys
, i
, &kCFTypeArrayCallBacks
);
505 removedPrefsKeys
= CFArrayCreateMutableCopy(NULL
, 0, array
);
507 CFAllocatorDeallocate(NULL
, currentKeys
);
509 removedPrefsKeys
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
513 * The "newPrefs" dictionary will contain the new / updated
514 * configuration which will be written to the configuration cache.
516 newPrefs
= CFDictionaryCreateMutable(NULL
,
518 &kCFTypeDictionaryKeyCallBacks
,
519 &kCFTypeDictionaryValueCallBacks
);
522 * create status dictionary associated with current configuration
523 * information including:
524 * - current set "name" to cache
525 * - time stamp indicating when the cache preferences were
528 dict
= CFDictionaryCreateMutable(NULL
,
530 &kCFTypeDictionaryKeyCallBacks
,
531 &kCFTypeDictionaryValueCallBacks
);
532 date
= CFDateCreate(NULL
, CFAbsoluteTimeGetCurrent());
537 keys
= SCPreferencesCopyKeyList(prefs
);
538 if ((keys
== NULL
) || (CFArrayGetCount(keys
) == 0)) {
539 SCLog(TRUE
, LOG_NOTICE
, CFSTR("updateConfiguration(): no preferences."));
544 * get "global" system preferences
546 global
= SCPreferencesGetValue(prefs
, kSCPrefSystem
);
548 /* if no global preferences are defined */
552 if (!isA_CFDictionary(global
)) {
554 CFSTR("updateConfiguration(): %@ is not a dictionary."),
559 /* flatten property list */
560 flatten(prefs
, CFSTR("/"), global
);
565 * get current set name
567 current
= SCPreferencesGetValue(prefs
, kSCPrefCurrentSet
);
569 /* if current set not defined */
573 if (!isA_CFString(current
)) {
575 CFSTR("updateConfiguration(): %@ is not a string."),
583 set
= SCPreferencesPathGetValue(prefs
, current
);
585 /* if error with path */
587 CFSTR("%@ value (%@) not valid"),
593 if (!isA_CFDictionary(set
)) {
595 CFSTR("updateConfiguration(): %@ is not a dictionary."),
600 /* flatten property list */
601 flatten(prefs
, CFSTR("/"), set
);
603 CFDictionarySetValue(dict
, kSCDynamicStorePropSetupCurrentSet
, current
);
607 /* add last updated time stamp */
608 CFDictionarySetValue(dict
, kSCDynamicStorePropSetupLastUpdated
, date
);
611 CFDictionarySetValue(newPrefs
, kSCDynamicStoreDomainSetup
, dict
);
613 /* compare current and new preferences */
614 CFDictionaryApplyFunction(newPrefs
, updateCache
, NULL
);
616 /* remove those keys which have not changed from the update */
617 n
= CFArrayGetCount(unchangedPrefsKeys
);
618 for (i
= 0; i
< n
; i
++) {
621 key
= CFArrayGetValueAtIndex(unchangedPrefsKeys
, i
);
622 CFDictionaryRemoveValue(newPrefs
, key
);
625 /* Update the dynamic store */
627 if (!SCDynamicStoreSetMultiple(store
, newPrefs
, removedPrefsKeys
, NULL
)) {
629 CFSTR("SCDynamicStoreSetMultiple() failed: %s"),
630 SCErrorString(SCError()));
633 SCLog(TRUE
, LOG_NOTICE
,
634 CFSTR("SCDynamicStore\nset: %@\nremove: %@\n"),
639 CFRelease(currentPrefs
);
641 CFRelease(unchangedPrefsKeys
);
642 CFRelease(removedPrefsKeys
);
643 if (dict
) CFRelease(dict
);
644 if (date
) CFRelease(date
);
645 if (keys
) CFRelease(keys
);
651 updateConfiguration(SCPreferencesRef prefs
,
652 SCPreferencesNotification notificationType
,
657 #if !TARGET_OS_IPHONE
658 if ((notificationType
& kSCPreferencesNotificationCommit
) == kSCPreferencesNotificationCommit
) {
659 SCNetworkSetRef current
;
661 current
= SCNetworkSetCopyCurrent(prefs
);
662 if (current
!= NULL
) {
663 /* network configuration available, disable template creation */
668 #endif /* !TARGET_OS_IPHONE */
670 if ((notificationType
& kSCPreferencesNotificationApply
) != kSCPreferencesNotificationApply
) {
674 SCLog(_verbose
, LOG_DEBUG
, CFSTR("updating configuration"));
676 /* update SCDynamicStore (Setup:) */
677 updateSCDynamicStore(prefs
);
679 /* finished with current prefs, wait for changes */
681 SCPreferencesSynchronize(prefs
);
690 prime_PreferencesMonitor()
692 SCLog(_verbose
, LOG_DEBUG
, CFSTR("prime() called"));
694 /* load the initial configuration from the database */
695 updateConfiguration(prefs
, kSCPreferencesNotificationApply
, (void *)store
);
703 load_PreferencesMonitor(CFBundleRef bundle
, Boolean bundleVerbose
)
705 Boolean initPrefs
= TRUE
;
711 SCLog(_verbose
, LOG_DEBUG
, CFSTR("load() called"));
712 SCLog(_verbose
, LOG_DEBUG
, CFSTR(" bundle ID = %@"), CFBundleGetIdentifier(bundle
));
714 /* open a SCDynamicStore session to allow cache updates */
715 store
= SCDynamicStoreCreate(NULL
,
716 CFSTR("PreferencesMonitor.bundle"),
721 CFSTR("SCDynamicStoreCreate() failed: %s"),
722 SCErrorString(SCError()));
726 /* open a SCPreferences session */
728 prefs
= SCPreferencesCreate(NULL
, CFSTR("PreferencesMonitor.bundle"), NULL
);
730 prefs
= SCPreferencesCreate(NULL
, CFSTR("PreferencesMonitor.bundle"), CFSTR("/tmp/preferences.plist"));
733 Boolean need_update
= FALSE
;
734 CFStringRef new_model
;
736 new_model
= _SC_hw_model();
738 /* Need to regenerate the new configuration for new model */
739 if (new_model
!= NULL
) {
740 CFStringRef old_model
;
742 old_model
= SCPreferencesGetValue(prefs
, MODEL
);
743 if (old_model
!= NULL
&& !_SC_CFEqual(old_model
, new_model
)) {
749 if (need_update
== FALSE
) {
750 SCNetworkSetRef current
;
752 current
= SCNetworkSetCopyCurrent(prefs
);
753 if (current
!= NULL
) {
754 /* network configuration available, disable template creation */
761 CFSTR("SCPreferencesCreate() failed: %s"),
762 SCErrorString(SCError()));
767 * register for change notifications.
769 if (!SCPreferencesSetCallback(prefs
, updateConfiguration
, NULL
)) {
771 CFSTR("SCPreferencesSetCallBack() failed: %s"),
772 SCErrorString(SCError()));
776 if (!SCPreferencesScheduleWithRunLoop(prefs
, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode
)) {
778 CFSTR("SCPreferencesScheduleWithRunLoop() failed: %s"),
779 SCErrorString(SCError()));
784 * if no preferences, initialize with a template (now or
785 * when IOKit has quiesced).
789 watchQuietCallback(store
, NULL
, NULL
);
797 if (store
!= NULL
) CFRelease(store
);
798 if (prefs
!= NULL
) CFRelease(prefs
);
806 main(int argc
, char **argv
)
809 _sc_verbose
= (argc
> 1) ? TRUE
: FALSE
;
811 load_PreferencesMonitor(CFBundleGetMainBundle(), (argc
> 1) ? TRUE
: FALSE
);
812 prime_PreferencesMonitor();