2 * Copyright (c) 2000-2008, 2010 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
;
76 int sc_status
= kSCStatusFailed
;
77 SCNetworkSetRef set
= NULL
;
78 CFStringRef setName
= NULL
;
79 Boolean updated
= FALSE
;
82 ok
= SCPreferencesLock(prefs
, TRUE
);
87 sc_status
= SCError();
88 if (sc_status
== kSCStatusStale
) {
89 SCPreferencesSynchronize(prefs
);
92 CFSTR("Could not acquire network configuration lock: %s"),
93 SCErrorString(sc_status
));
98 current
= SCNetworkSetCopyCurrent(prefs
);
99 if (current
!= NULL
) {
104 set
= SCNetworkSetCreate(prefs
);
107 sc_status
= SCError();
111 bundle
= _SC_CFBundleGet();
112 if (bundle
!= NULL
) {
113 setName
= CFBundleCopyLocalizedString(bundle
,
114 CFSTR("DEFAULT_SET_NAME"),
119 ok
= SCNetworkSetSetName(set
, (setName
!= NULL
) ? setName
: CFSTR("Automatic"));
121 sc_status
= SCError();
125 ok
= SCNetworkSetSetCurrent(set
);
127 sc_status
= SCError();
132 ok
= SCNetworkSetEstablishDefaultConfiguration(set
);
134 sc_status
= SCError();
141 ok
= SCPreferencesCommitChanges(prefs
);
143 SCLog(TRUE
, LOG_NOTICE
, CFSTR("New network configuration saved"));
146 sc_status
= SCError();
147 if (sc_status
== EROFS
) {
148 /* a read-only fileysstem is OK */
151 /* ... but we don't want to synchronize */
156 /* apply (committed or temporary/read-only) changes */
157 (void) SCPreferencesApplyChanges(prefs
);
158 } else if ((current
== NULL
) && (set
!= NULL
)) {
159 (void) SCNetworkSetRemove(set
);
164 CFSTR("Could not establish network configuration: %s"),
165 SCErrorString(sc_status
));
168 (void)SCPreferencesUnlock(prefs
);
169 if (setName
!= NULL
) CFRelease(setName
);
170 if (set
!= NULL
) CFRelease(set
);
176 quiet(Boolean
*timeout
)
178 CFDictionaryRef dict
;
179 Boolean _quiet
= FALSE
;
180 Boolean _timeout
= FALSE
;
183 dict
= SCDynamicStoreCopyValue(store
, initKey
);
185 if (isA_CFDictionary(dict
)) {
186 if (CFDictionaryContainsKey(dict
, CFSTR("*QUIET*"))) {
189 if (CFDictionaryContainsKey(dict
, CFSTR("*TIMEOUT*"))) {
196 if (timeout
!= NULL
) {
206 if ((initKey
== NULL
) || (initRls
== NULL
)) {
210 (void) SCDynamicStoreSetNotificationKeys(store
, NULL
, NULL
);
212 CFRunLoopSourceInvalidate(initRls
);
229 initKey
= SCDynamicStoreKeyCreate(NULL
,
230 CFSTR("%@" "InterfaceNamer"),
231 kSCDynamicStoreDomainPlugin
);
233 initRls
= SCDynamicStoreCreateRunLoopSource(NULL
, store
, 0);
234 CFRunLoopAddSource(CFRunLoopGetCurrent(), initRls
, kCFRunLoopDefaultMode
);
236 keys
= CFArrayCreate(NULL
, (const void **)&initKey
, 1, &kCFTypeArrayCallBacks
);
237 ok
= SCDynamicStoreSetNotificationKeys(store
, keys
, NULL
);
241 CFSTR("SCDynamicStoreSetNotificationKeys() failed: %s\n"), SCErrorString(SCError()));
249 watchQuietCallback(SCDynamicStoreRef store
, CFArrayRef changedKeys
, void *info
)
252 Boolean _timeout
= FALSE
;
254 _quiet
= quiet(&_timeout
);
256 #if !TARGET_OS_IPHONE
258 #endif /* !TARGET_OS_IPHONE */
263 if (_quiet
|| _timeout
) {
264 static int logged
= 0;
266 (void) establishNewPreferences();
267 if (_timeout
&& (logged
++ == 0)) {
268 SCLog(TRUE
, LOG_NOTICE
,
269 CFSTR("Network configuration creation timed out waiting for IORegistry"));
278 updateCache(const void *key
, const void *value
, void *context
)
280 CFStringRef configKey
= (CFStringRef
)key
;
281 CFPropertyListRef configData
= (CFPropertyListRef
)value
;
282 CFPropertyListRef cacheData
;
285 cacheData
= CFDictionaryGetValue(currentPrefs
, configKey
);
288 if (CFEqual(cacheData
, configData
)) {
290 * if the old & new property list values have
291 * not changed then we don't need to update
294 CFArrayAppendValue(unchangedPrefsKeys
, configKey
);
298 /* in any case, this key should not be removed */
299 i
= CFArrayGetFirstIndexOfValue(removedPrefsKeys
,
300 CFRangeMake(0, CFArrayGetCount(removedPrefsKeys
)),
302 if (i
!= kCFNotFound
) {
303 CFArrayRemoveValueAtIndex(removedPrefsKeys
, i
);
311 flatten(SCPreferencesRef prefs
,
313 CFDictionaryRef base
)
315 CFDictionaryRef subset
;
317 CFMutableDictionaryRef myDict
;
324 if (!CFDictionaryGetValueIfPresent(base
, kSCResvLink
, (const void **)&link
)) {
325 /* if this dictionary is not linked */
328 /* if __LINK__ key is present */
329 subset
= SCPreferencesPathGetValue(prefs
, link
);
331 /* if error with link */
333 CFSTR("SCPreferencesPathGetValue(,%@,) failed: %s"),
335 SCErrorString(SCError()));
340 if (CFDictionaryContainsKey(subset
, kSCResvInactive
)) {
341 /* if __INACTIVE__ key is present */
345 myKey
= CFStringCreateWithFormat(NULL
,
348 kSCDynamicStoreDomainSetup
,
351 myDict
= (CFMutableDictionaryRef
)CFDictionaryGetValue(newPrefs
, myKey
);
353 myDict
= CFDictionaryCreateMutableCopy(NULL
,
355 (CFDictionaryRef
)myDict
);
357 myDict
= CFDictionaryCreateMutable(NULL
,
359 &kCFTypeDictionaryKeyCallBacks
,
360 &kCFTypeDictionaryValueCallBacks
);
363 nKeys
= CFDictionaryGetCount(subset
);
365 keys
= CFAllocatorAllocate(NULL
, nKeys
* sizeof(CFStringRef
) , 0);
366 vals
= CFAllocatorAllocate(NULL
, nKeys
* sizeof(CFPropertyListRef
), 0);
367 CFDictionaryGetKeysAndValues(subset
, keys
, vals
);
368 for (i
= 0; i
< nKeys
; i
++) {
369 if (CFGetTypeID((CFTypeRef
)vals
[i
]) != CFDictionaryGetTypeID()) {
370 /* add this key/value to the current dictionary */
371 CFDictionarySetValue(myDict
, keys
[i
], vals
[i
]);
375 /* flatten [sub]dictionaries */
376 subKey
= CFStringCreateWithFormat(NULL
,
380 CFEqual(key
, CFSTR("/")) ? "" : "/",
382 flatten(prefs
, subKey
, vals
[i
]);
386 CFAllocatorDeallocate(NULL
, keys
);
387 CFAllocatorDeallocate(NULL
, vals
);
390 if (CFDictionaryGetCount(myDict
) > 0) {
391 /* add this dictionary to the new preferences */
392 CFDictionarySetValue(newPrefs
, myKey
, myDict
);
403 updateSCDynamicStore(SCPreferencesRef prefs
)
405 CFStringRef current
= NULL
;
406 CFDateRef date
= NULL
;
407 CFMutableDictionaryRef dict
= NULL
;
408 CFDictionaryRef global
= NULL
;
413 CFMutableArrayRef patterns
;
414 CFDictionaryRef set
= NULL
;
417 * initialize old preferences, new preferences, an array
418 * of keys which have not changed, and an array of keys
419 * to be removed (cleaned up).
422 patterns
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
423 pattern
= CFStringCreateWithFormat(NULL
,
426 kSCDynamicStoreDomainSetup
);
427 CFArrayAppendValue(patterns
, pattern
);
428 dict
= (CFMutableDictionaryRef
)SCDynamicStoreCopyMultiple(store
, NULL
, patterns
);
432 currentPrefs
= CFDictionaryCreateMutableCopy(NULL
, 0, dict
);
435 currentPrefs
= CFDictionaryCreateMutable(NULL
,
437 &kCFTypeDictionaryKeyCallBacks
,
438 &kCFTypeDictionaryValueCallBacks
);
441 unchangedPrefsKeys
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
443 i
= CFDictionaryGetCount(currentPrefs
);
445 const void **currentKeys
;
448 currentKeys
= CFAllocatorAllocate(NULL
, i
* sizeof(CFStringRef
), 0);
449 CFDictionaryGetKeysAndValues(currentPrefs
, currentKeys
, NULL
);
450 array
= CFArrayCreate(NULL
, currentKeys
, i
, &kCFTypeArrayCallBacks
);
451 removedPrefsKeys
= CFArrayCreateMutableCopy(NULL
, 0, array
);
453 CFAllocatorDeallocate(NULL
, currentKeys
);
455 removedPrefsKeys
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
459 * The "newPrefs" dictionary will contain the new / updated
460 * configuration which will be written to the configuration cache.
462 newPrefs
= CFDictionaryCreateMutable(NULL
,
464 &kCFTypeDictionaryKeyCallBacks
,
465 &kCFTypeDictionaryValueCallBacks
);
468 * create status dictionary associated with current configuration
469 * information including:
470 * - current set "name" to cache
471 * - time stamp indicating when the cache preferences were
474 dict
= CFDictionaryCreateMutable(NULL
,
476 &kCFTypeDictionaryKeyCallBacks
,
477 &kCFTypeDictionaryValueCallBacks
);
478 date
= CFDateCreate(NULL
, CFAbsoluteTimeGetCurrent());
483 keys
= SCPreferencesCopyKeyList(prefs
);
484 if ((keys
== NULL
) || (CFArrayGetCount(keys
) == 0)) {
485 SCLog(TRUE
, LOG_NOTICE
, CFSTR("updateConfiguration(): no preferences."));
490 * get "global" system preferences
492 global
= SCPreferencesGetValue(prefs
, kSCPrefSystem
);
494 /* if no global preferences are defined */
498 if (!isA_CFDictionary(global
)) {
500 CFSTR("updateConfiguration(): %@ is not a dictionary."),
505 /* flatten property list */
506 flatten(prefs
, CFSTR("/"), global
);
511 * get current set name
513 current
= SCPreferencesGetValue(prefs
, kSCPrefCurrentSet
);
515 /* if current set not defined */
519 if (!isA_CFString(current
)) {
521 CFSTR("updateConfiguration(): %@ is not a string."),
529 set
= SCPreferencesPathGetValue(prefs
, current
);
531 /* if error with path */
533 CFSTR("%@ value (%@) not valid"),
539 if (!isA_CFDictionary(set
)) {
541 CFSTR("updateConfiguration(): %@ is not a dictionary."),
546 /* flatten property list */
547 flatten(prefs
, CFSTR("/"), set
);
549 CFDictionarySetValue(dict
, kSCDynamicStorePropSetupCurrentSet
, current
);
553 /* add last updated time stamp */
554 CFDictionarySetValue(dict
, kSCDynamicStorePropSetupLastUpdated
, date
);
557 CFDictionarySetValue(newPrefs
, kSCDynamicStoreDomainSetup
, dict
);
559 /* compare current and new preferences */
560 CFDictionaryApplyFunction(newPrefs
, updateCache
, NULL
);
562 /* remove those keys which have not changed from the update */
563 n
= CFArrayGetCount(unchangedPrefsKeys
);
564 for (i
= 0; i
< n
; i
++) {
567 key
= CFArrayGetValueAtIndex(unchangedPrefsKeys
, i
);
568 CFDictionaryRemoveValue(newPrefs
, key
);
571 /* Update the dynamic store */
572 if (!SCDynamicStoreSetMultiple(store
, newPrefs
, removedPrefsKeys
, NULL
)) {
574 CFSTR("SCDynamicStoreSetMultiple() failed: %s"),
575 SCErrorString(SCError()));
578 CFRelease(currentPrefs
);
580 CFRelease(unchangedPrefsKeys
);
581 CFRelease(removedPrefsKeys
);
582 if (dict
) CFRelease(dict
);
583 if (date
) CFRelease(date
);
584 if (keys
) CFRelease(keys
);
590 updateConfiguration(SCPreferencesRef prefs
,
591 SCPreferencesNotification notificationType
,
596 #if !TARGET_OS_IPHONE
597 if ((notificationType
& kSCPreferencesNotificationCommit
) == kSCPreferencesNotificationCommit
) {
598 SCNetworkSetRef current
;
600 current
= SCNetworkSetCopyCurrent(prefs
);
601 if (current
!= NULL
) {
602 /* network configuration available, disable template creation */
607 #endif /* !TARGET_OS_IPHONE */
609 if ((notificationType
& kSCPreferencesNotificationApply
) != kSCPreferencesNotificationApply
) {
613 SCLog(_verbose
, LOG_DEBUG
, CFSTR("updating configuration"));
615 /* update SCDynamicStore (Setup:) */
616 updateSCDynamicStore(prefs
);
618 /* finished with current prefs, wait for changes */
620 SCPreferencesSynchronize(prefs
);
629 prime_PreferencesMonitor()
631 SCLog(_verbose
, LOG_DEBUG
, CFSTR("prime() called"));
633 /* load the initial configuration from the database */
634 updateConfiguration(prefs
, kSCPreferencesNotificationApply
, (void *)store
);
642 load_PreferencesMonitor(CFBundleRef bundle
, Boolean bundleVerbose
)
644 Boolean initPrefs
= TRUE
;
650 SCLog(_verbose
, LOG_DEBUG
, CFSTR("load() called"));
651 SCLog(_verbose
, LOG_DEBUG
, CFSTR(" bundle ID = %@"), CFBundleGetIdentifier(bundle
));
653 /* open a SCDynamicStore session to allow cache updates */
654 store
= SCDynamicStoreCreate(NULL
,
655 CFSTR("PreferencesMonitor.bundle"),
660 CFSTR("SCDynamicStoreCreate() failed: %s"),
661 SCErrorString(SCError()));
665 /* open a SCPreferences session */
666 prefs
= SCPreferencesCreate(NULL
, CFSTR("PreferencesMonitor.bundle"), NULL
);
668 SCNetworkSetRef current
;
670 current
= SCNetworkSetCopyCurrent(prefs
);
671 if (current
!= NULL
) {
672 /* network configuration available, disable template creation */
678 CFSTR("SCPreferencesCreate() failed: %s"),
679 SCErrorString(SCError()));
684 * register for change notifications.
686 if (!SCPreferencesSetCallback(prefs
, updateConfiguration
, NULL
)) {
688 CFSTR("SCPreferencesSetCallBack() failed: %s"),
689 SCErrorString(SCError()));
693 if (!SCPreferencesScheduleWithRunLoop(prefs
, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode
)) {
695 CFSTR("SCPreferencesScheduleWithRunLoop() failed: %s"),
696 SCErrorString(SCError()));
701 * if no preferences, initialize with a template (now or
702 * when IOKit has quiesced).
706 watchQuietCallback(store
, NULL
, NULL
);
714 if (store
!= NULL
) CFRelease(store
);
715 if (prefs
!= NULL
) CFRelease(prefs
);
723 main(int argc
, char **argv
)
726 _sc_verbose
= (argc
> 1) ? TRUE
: FALSE
;
728 load_PreferencesMonitor(CFBundleGetMainBundle(), (argc
> 1) ? TRUE
: FALSE
);
729 prime_PreferencesMonitor();