2 * Copyright (c) 2000-2008 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 _verbose
= FALSE
;
70 establishNewPreferences()
73 SCNetworkSetRef current
= NULL
;
75 int sc_status
= kSCStatusFailed
;
76 SCNetworkSetRef set
= NULL
;
77 CFStringRef setName
= NULL
;
78 Boolean updated
= FALSE
;
81 ok
= SCPreferencesLock(prefs
, TRUE
);
86 sc_status
= SCError();
87 if (sc_status
== kSCStatusStale
) {
88 SCPreferencesSynchronize(prefs
);
91 CFSTR("Could not acquire network configuration lock: %s"),
92 SCErrorString(sc_status
));
97 current
= SCNetworkSetCopyCurrent(prefs
);
98 if (current
!= NULL
) {
103 set
= SCNetworkSetCreate(prefs
);
106 sc_status
= SCError();
110 bundle
= _SC_CFBundleGet();
111 if (bundle
!= NULL
) {
112 setName
= CFBundleCopyLocalizedString(bundle
,
113 CFSTR("DEFAULT_SET_NAME"),
118 ok
= SCNetworkSetSetName(set
, (setName
!= NULL
) ? setName
: CFSTR("Automatic"));
120 sc_status
= SCError();
124 ok
= SCNetworkSetSetCurrent(set
);
126 sc_status
= SCError();
131 ok
= SCNetworkSetEstablishDefaultConfiguration(set
);
133 sc_status
= SCError();
140 ok
= SCPreferencesCommitChanges(prefs
);
142 SCLog(TRUE
, LOG_NOTICE
, CFSTR("New network configuration saved"));
145 sc_status
= SCError();
146 if (sc_status
== EROFS
) {
147 /* a read-only fileysstem is OK */
152 /* apply (committed or temporary/read-only) changes */
153 (void) SCPreferencesApplyChanges(prefs
);
154 } else if ((current
== NULL
) && (set
!= NULL
)) {
155 (void) SCNetworkSetRemove(set
);
160 CFSTR("Could not establish network configuration: %s"),
161 SCErrorString(sc_status
));
164 (void)SCPreferencesUnlock(prefs
);
165 if (setName
!= NULL
) CFRelease(setName
);
166 if (set
!= NULL
) CFRelease(set
);
172 quiet(Boolean
*timeout
)
174 CFDictionaryRef dict
;
175 Boolean _quiet
= FALSE
;
176 Boolean _timeout
= FALSE
;
179 dict
= SCDynamicStoreCopyValue(store
, initKey
);
181 if (isA_CFDictionary(dict
)) {
182 if (CFDictionaryContainsKey(dict
, CFSTR("*QUIET*"))) {
185 if (CFDictionaryContainsKey(dict
, CFSTR("*TIMEOUT*"))) {
192 if (timeout
!= NULL
) {
202 if ((initKey
== NULL
) && (initRls
== NULL
)) {
206 (void) SCDynamicStoreSetNotificationKeys(store
, NULL
, NULL
);
208 CFRunLoopSourceInvalidate(initRls
);
225 initKey
= SCDynamicStoreKeyCreate(NULL
,
226 CFSTR("%@" "InterfaceNamer"),
227 kSCDynamicStoreDomainPlugin
);
229 initRls
= SCDynamicStoreCreateRunLoopSource(NULL
, store
, 0);
230 CFRunLoopAddSource(CFRunLoopGetCurrent(), initRls
, kCFRunLoopDefaultMode
);
232 keys
= CFArrayCreate(NULL
, (const void **)&initKey
, 1, &kCFTypeArrayCallBacks
);
233 ok
= SCDynamicStoreSetNotificationKeys(store
, keys
, NULL
);
237 CFSTR("SCDynamicStoreSetNotificationKeys() failed: %s\n"), SCErrorString(SCError()));
245 watchQuietCallback(SCDynamicStoreRef store
, CFArrayRef changedKeys
, void *info
)
248 Boolean _timeout
= FALSE
;
250 _quiet
= quiet(&_timeout
);
252 #if !TARGET_OS_IPHONE
254 #endif /* !TARGET_OS_IPHONE */
259 if (_quiet
|| _timeout
) {
260 static int logged
= 0;
262 (void) establishNewPreferences();
263 if (_timeout
&& (logged
++ == 0)) {
264 SCLog(TRUE
, LOG_NOTICE
,
265 CFSTR("Network configuration creation timed out waiting for IORegistry"));
274 updateCache(const void *key
, const void *value
, void *context
)
276 CFStringRef configKey
= (CFStringRef
)key
;
277 CFPropertyListRef configData
= (CFPropertyListRef
)value
;
278 CFPropertyListRef cacheData
;
281 cacheData
= CFDictionaryGetValue(currentPrefs
, configKey
);
284 if (CFEqual(cacheData
, configData
)) {
286 * if the old & new property list values have
287 * not changed then we don't need to update
290 CFArrayAppendValue(unchangedPrefsKeys
, configKey
);
294 /* in any case, this key should not be removed */
295 i
= CFArrayGetFirstIndexOfValue(removedPrefsKeys
,
296 CFRangeMake(0, CFArrayGetCount(removedPrefsKeys
)),
298 if (i
!= kCFNotFound
) {
299 CFArrayRemoveValueAtIndex(removedPrefsKeys
, i
);
307 flatten(SCPreferencesRef prefs
,
309 CFDictionaryRef base
)
311 CFDictionaryRef subset
;
313 CFMutableDictionaryRef myDict
;
320 if (!CFDictionaryGetValueIfPresent(base
, kSCResvLink
, (const void **)&link
)) {
321 /* if this dictionary is not linked */
324 /* if __LINK__ key is present */
325 subset
= SCPreferencesPathGetValue(prefs
, link
);
327 /* if error with link */
329 CFSTR("SCPreferencesPathGetValue(,%@,) failed: %s"),
331 SCErrorString(SCError()));
336 if (CFDictionaryContainsKey(subset
, kSCResvInactive
)) {
337 /* if __INACTIVE__ key is present */
341 myKey
= CFStringCreateWithFormat(NULL
,
344 kSCDynamicStoreDomainSetup
,
347 myDict
= (CFMutableDictionaryRef
)CFDictionaryGetValue(newPrefs
, myKey
);
349 myDict
= CFDictionaryCreateMutableCopy(NULL
,
351 (CFDictionaryRef
)myDict
);
353 myDict
= CFDictionaryCreateMutable(NULL
,
355 &kCFTypeDictionaryKeyCallBacks
,
356 &kCFTypeDictionaryValueCallBacks
);
359 nKeys
= CFDictionaryGetCount(subset
);
361 keys
= CFAllocatorAllocate(NULL
, nKeys
* sizeof(CFStringRef
) , 0);
362 vals
= CFAllocatorAllocate(NULL
, nKeys
* sizeof(CFPropertyListRef
), 0);
363 CFDictionaryGetKeysAndValues(subset
, keys
, vals
);
364 for (i
= 0; i
< nKeys
; i
++) {
365 if (CFGetTypeID((CFTypeRef
)vals
[i
]) != CFDictionaryGetTypeID()) {
366 /* add this key/value to the current dictionary */
367 CFDictionarySetValue(myDict
, keys
[i
], vals
[i
]);
371 /* flatten [sub]dictionaries */
372 subKey
= CFStringCreateWithFormat(NULL
,
376 CFEqual(key
, CFSTR("/")) ? "" : "/",
378 flatten(prefs
, subKey
, vals
[i
]);
382 CFAllocatorDeallocate(NULL
, keys
);
383 CFAllocatorDeallocate(NULL
, vals
);
386 if (CFDictionaryGetCount(myDict
) > 0) {
387 /* add this dictionary to the new preferences */
388 CFDictionarySetValue(newPrefs
, myKey
, myDict
);
399 updateSCDynamicStore(SCPreferencesRef prefs
)
401 CFStringRef current
= NULL
;
402 CFDateRef date
= NULL
;
403 CFMutableDictionaryRef dict
= NULL
;
404 CFDictionaryRef global
= NULL
;
409 CFMutableArrayRef patterns
;
410 CFDictionaryRef set
= NULL
;
413 * initialize old preferences, new preferences, an array
414 * of keys which have not changed, and an array of keys
415 * to be removed (cleaned up).
418 patterns
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
419 pattern
= CFStringCreateWithFormat(NULL
,
422 kSCDynamicStoreDomainSetup
);
423 CFArrayAppendValue(patterns
, pattern
);
424 dict
= (CFMutableDictionaryRef
)SCDynamicStoreCopyMultiple(store
, NULL
, patterns
);
428 currentPrefs
= CFDictionaryCreateMutableCopy(NULL
, 0, dict
);
431 currentPrefs
= CFDictionaryCreateMutable(NULL
,
433 &kCFTypeDictionaryKeyCallBacks
,
434 &kCFTypeDictionaryValueCallBacks
);
437 unchangedPrefsKeys
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
439 i
= CFDictionaryGetCount(currentPrefs
);
441 const void **currentKeys
;
444 currentKeys
= CFAllocatorAllocate(NULL
, i
* sizeof(CFStringRef
), 0);
445 CFDictionaryGetKeysAndValues(currentPrefs
, currentKeys
, NULL
);
446 array
= CFArrayCreate(NULL
, currentKeys
, i
, &kCFTypeArrayCallBacks
);
447 removedPrefsKeys
= CFArrayCreateMutableCopy(NULL
, 0, array
);
449 CFAllocatorDeallocate(NULL
, currentKeys
);
451 removedPrefsKeys
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
455 * The "newPrefs" dictionary will contain the new / updated
456 * configuration which will be written to the configuration cache.
458 newPrefs
= CFDictionaryCreateMutable(NULL
,
460 &kCFTypeDictionaryKeyCallBacks
,
461 &kCFTypeDictionaryValueCallBacks
);
464 * create status dictionary associated with current configuration
465 * information including:
466 * - current set "name" to cache
467 * - time stamp indicating when the cache preferences were
470 dict
= CFDictionaryCreateMutable(NULL
,
472 &kCFTypeDictionaryKeyCallBacks
,
473 &kCFTypeDictionaryValueCallBacks
);
474 date
= CFDateCreate(NULL
, CFAbsoluteTimeGetCurrent());
479 keys
= SCPreferencesCopyKeyList(prefs
);
480 if ((keys
== NULL
) || (CFArrayGetCount(keys
) == 0)) {
481 SCLog(TRUE
, LOG_NOTICE
, CFSTR("updateConfiguration(): no preferences."));
486 * get "global" system preferences
488 global
= SCPreferencesGetValue(prefs
, kSCPrefSystem
);
490 /* if no global preferences are defined */
494 if (!isA_CFDictionary(global
)) {
496 CFSTR("updateConfiguration(): %@ is not a dictionary."),
501 /* flatten property list */
502 flatten(prefs
, CFSTR("/"), global
);
507 * get current set name
509 current
= SCPreferencesGetValue(prefs
, kSCPrefCurrentSet
);
511 /* if current set not defined */
515 if (!isA_CFString(current
)) {
517 CFSTR("updateConfiguration(): %@ is not a string."),
525 set
= SCPreferencesPathGetValue(prefs
, current
);
527 /* if error with path */
529 CFSTR("%@ value (%@) not valid"),
535 if (!isA_CFDictionary(set
)) {
537 CFSTR("updateConfiguration(): %@ is not a dictionary."),
542 /* flatten property list */
543 flatten(prefs
, CFSTR("/"), set
);
545 CFDictionarySetValue(dict
, kSCDynamicStorePropSetupCurrentSet
, current
);
549 /* add last updated time stamp */
550 CFDictionarySetValue(dict
, kSCDynamicStorePropSetupLastUpdated
, date
);
553 CFDictionarySetValue(newPrefs
, kSCDynamicStoreDomainSetup
, dict
);
555 /* compare current and new preferences */
556 CFDictionaryApplyFunction(newPrefs
, updateCache
, NULL
);
558 /* remove those keys which have not changed from the update */
559 n
= CFArrayGetCount(unchangedPrefsKeys
);
560 for (i
= 0; i
< n
; i
++) {
563 key
= CFArrayGetValueAtIndex(unchangedPrefsKeys
, i
);
564 CFDictionaryRemoveValue(newPrefs
, key
);
567 /* Update the dynamic store */
568 if (!SCDynamicStoreSetMultiple(store
, newPrefs
, removedPrefsKeys
, NULL
)) {
570 CFSTR("SCDynamicStoreSetMultiple() failed: %s"),
571 SCErrorString(SCError()));
574 CFRelease(currentPrefs
);
576 CFRelease(unchangedPrefsKeys
);
577 CFRelease(removedPrefsKeys
);
578 if (dict
) CFRelease(dict
);
579 if (date
) CFRelease(date
);
580 if (keys
) CFRelease(keys
);
586 updateConfiguration(SCPreferencesRef prefs
,
587 SCPreferencesNotification notificationType
,
592 #if !TARGET_OS_IPHONE
593 if ((notificationType
& kSCPreferencesNotificationCommit
) == kSCPreferencesNotificationCommit
) {
594 SCNetworkSetRef current
;
596 current
= SCNetworkSetCopyCurrent(prefs
);
597 if (current
!= NULL
) {
598 /* network configuration available, disable template creation */
603 #endif /* !TARGET_OS_IPHONE */
605 if ((notificationType
& kSCPreferencesNotificationApply
) != kSCPreferencesNotificationApply
) {
609 SCLog(_verbose
, LOG_DEBUG
, CFSTR("updating configuration"));
611 /* update SCDynamicStore (Setup:) */
612 updateSCDynamicStore(prefs
);
614 /* finished with current prefs, wait for changes */
615 SCPreferencesSynchronize(prefs
);
623 prime_PreferencesMonitor()
625 SCLog(_verbose
, LOG_DEBUG
, CFSTR("prime() called"));
627 /* load the initial configuration from the database */
628 updateConfiguration(prefs
, kSCPreferencesNotificationApply
, (void *)store
);
636 load_PreferencesMonitor(CFBundleRef bundle
, Boolean bundleVerbose
)
638 Boolean initPrefs
= TRUE
;
644 SCLog(_verbose
, LOG_DEBUG
, CFSTR("load() called"));
645 SCLog(_verbose
, LOG_DEBUG
, CFSTR(" bundle ID = %@"), CFBundleGetIdentifier(bundle
));
647 /* open a SCDynamicStore session to allow cache updates */
648 store
= SCDynamicStoreCreate(NULL
,
649 CFSTR("PreferencesMonitor.bundle"),
654 CFSTR("SCDynamicStoreCreate() failed: %s"),
655 SCErrorString(SCError()));
659 /* open a SCPreferences session */
660 prefs
= SCPreferencesCreate(NULL
, CFSTR("PreferencesMonitor.bundle"), NULL
);
662 SCNetworkSetRef current
;
664 current
= SCNetworkSetCopyCurrent(prefs
);
665 if (current
!= NULL
) {
666 /* network configuration available, disable template creation */
672 CFSTR("SCPreferencesCreate() failed: %s"),
673 SCErrorString(SCError()));
678 * register for change notifications.
680 if (!SCPreferencesSetCallback(prefs
, updateConfiguration
, NULL
)) {
682 CFSTR("SCPreferencesSetCallBack() failed: %s"),
683 SCErrorString(SCError()));
687 if (!SCPreferencesScheduleWithRunLoop(prefs
, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode
)) {
689 CFSTR("SCPreferencesScheduleWithRunLoop() failed: %s"),
690 SCErrorString(SCError()));
695 * if no preferences, initialize with a template (now or
696 * when IOKit has quiesced).
700 watchQuietCallback(store
, NULL
, NULL
);
708 if (store
!= NULL
) CFRelease(store
);
709 if (prefs
!= NULL
) CFRelease(prefs
);
717 main(int argc
, char **argv
)
720 _sc_verbose
= (argc
> 1) ? TRUE
: FALSE
;
722 load_PreferencesMonitor(CFBundleGetMainBundle(), (argc
> 1) ? TRUE
: FALSE
);
723 prime_PreferencesMonitor();