Beispiel #1
0
long OSCollector::Collect(NVDataItem **ReturnItem) 
{

	auto_ptr<NVDataItem> DataItems (new NVDataItem(OSCL_TAG));
	auto_ptr<NVDataItem> OSItem (new NVDataItem(OSCI_TAG));
	
	OSItem->AddNVItem(OSCL_MFR, "Apple Computer, Inc.");
	
	CFAuto<CFStringRef> PrefCFStringVal;
	
	CFAuto<SCDynamicStoreRef> DSObj;
	
	DSObj.Attach(
		SCDynamicStoreCreate(
			kCFAllocatorDefault,
			kProgramID,
			NULL,
			NULL));
				
	std::string PrefStringVal;
	CFAuto<SCPreferencesRef> SysVersion;
	
	SysVersion.Attach(
		SCPreferencesCreate (
			kCFAllocatorDefault,
			kProgramID,
			CFSTR("/System/Library/CoreServices/SystemVersion.plist")));
	
	CFPropertyListRef SCPropVal;
	
	SCPropVal = 
		SCPreferencesGetValue(SysVersion, CFSTR("ProductName"));
	
	PrefCFStringVal = reinterpret_cast<CFStringRef>(SCPropVal);
	PrefCFStringVal.GetCString(PrefStringVal);
	OSItem->AddNVItem(OSCL_NAME, PrefStringVal.c_str());

	SCPropVal = 
		SCPreferencesGetValue(SysVersion, CFSTR("ProductUserVisibleVersion"));
	
	PrefCFStringVal = reinterpret_cast<CFStringRef>(SCPropVal);
	PrefCFStringVal.GetCString(PrefStringVal);
	OSItem->AddNVItem(OSCL_VERSION, PrefStringVal.c_str());
	
	SCPropVal =
		SCPreferencesGetValue(SysVersion, CFSTR("ProductBuildVersion"));
	
	PrefCFStringVal = reinterpret_cast<CFStringRef>(SCPropVal);
	PrefCFStringVal.GetCString(PrefStringVal);
	OSItem->AddNVItem(OSCL_BUILD, PrefStringVal.c_str());		
		
	DataItems->AddSubItem(OSItem.release());	
	*ReturnItem = DataItems.release();
#ifdef TRACE
	printf("OS Complete\n");
#endif
	return ERROR_SUCCESS;
}
Beispiel #2
0
/* Get the value for the given key. We don't allow NULL ad a value, so
 * returning NULL means failure (not present).
 */
CFPropertyListRef Preferences::get_value(CFStringRef key) const
{
    CFPropertyListRef prefval = NULL;

    if (!this->is_loaded()) {
	return NULL;
    }

    if (this->m_plist) {
	prefval = CFDictionaryGetValue((CFDictionaryRef)this->m_plist, key);
    } else if (this->m_scpref) {
	prefval = SCPreferencesGetValue(this->m_scpref, key);
    }

    /* Dump the raw keys for debugging. Useful for figuring out whether our
     * type conversion has gone awry.
     */
    if (Options::Debug) {
	DEBUGMSG("%s value for key %s:\n",
		this->m_pspec.c_str(), cfstring_convert(key).c_str());
	CFShow(prefval);
    }

    return prefval;
}
Beispiel #3
0
SCNetworkSetRef
SCNetworkSetCopyCurrent(SCPreferencesRef prefs)
{
	CFArrayRef		components;
	CFStringRef		currentID;
	SCNetworkSetPrivateRef	setPrivate	= NULL;

	currentID = SCPreferencesGetValue(prefs, kSCPrefCurrentSet);
	if (!isA_CFString(currentID)) {
		return NULL;
	}

	components = CFStringCreateArrayBySeparatingStrings(NULL, currentID, CFSTR("/"));
	if (CFArrayGetCount(components) == 3) {
		CFStringRef	setID;
		CFStringRef	path;

		setID = CFArrayGetValueAtIndex(components, 2);
		path = SCPreferencesPathKeyCreateSet(NULL, setID);
		if (CFEqual(path, currentID)) {
			setPrivate = __SCNetworkSetCreatePrivate(NULL, prefs, setID);
			assert(setPrivate != NULL);

			// mark set as "old" (already established)
			setPrivate->established = TRUE;
		} else {
			SC_log(LOG_NOTICE, "SCNetworkSetCopyCurrent(): preferences are non-conformant");
		}
		CFRelease(path);
	}
	CFRelease(components);

	return (SCNetworkSetRef)setPrivate;
}
static void PrintAllPreferences(SCPreferencesRef prefsRef, CFArrayRef allKeys)
	// This routine prints all of the preferences in the SCF preferences 
	// database.  I use it during debugging.
{
	CFIndex keyCount;
	CFIndex keyIndex;
	
	keyCount = CFArrayGetCount(allKeys);
	for (keyIndex = 0; keyIndex < keyCount; keyIndex++) {
		CFPropertyListRef thisPref;
		
		thisPref = SCPreferencesGetValue(prefsRef, (CFStringRef) CFArrayGetValueAtIndex(allKeys, keyIndex));	// C++ requires cast
		PrintPropertyList(thisPref);
	}
}
/* 
 * Copy Events from on-disk file. We should be doing this only
 * once, at start of the powerd.
 */
static void
copyScheduledRepeatPowerEvents(void)
{
    SCPreferencesRef        prefs;
    CFDictionaryRef         tmp;
   
    prefs = SCPreferencesCreate(0, 
                               CFSTR("PM-configd-AutoWake"),
                                CFSTR(kIOPMAutoWakePrefsPath));
    if(!prefs) return;

    if (repeatingPowerOff) CFRelease(repeatingPowerOff);
    if (repeatingPowerOn) CFRelease(repeatingPowerOn);

    tmp = (CFDictionaryRef)SCPreferencesGetValue(prefs, CFSTR(kIOPMRepeatingPowerOffKey));
    if (tmp && isA_CFDictionary(tmp))
        repeatingPowerOff = CFDictionaryCreateMutableCopy(0,0,tmp);

    tmp = (CFDictionaryRef)SCPreferencesGetValue(prefs, CFSTR(kIOPMRepeatingPowerOnKey));
    if (tmp && isA_CFDictionary(tmp))
        repeatingPowerOn = CFDictionaryCreateMutableCopy(0,0,tmp);

    CFRelease(prefs);
}
STATIC CFDictionaryRef
copy_def_auth_props(SCPreferencesRef eap_prefs)
{
    CFArrayRef			accept_types = NULL;
    CFMutableDictionaryRef	auth_props;
    int				list[] = { 
	kEAPTypePEAP,
	kEAPTypeTTLS,
	kEAPTypeEAPFAST,
	kEAPTypeTLS
    };
    int				list_count = sizeof(list) / sizeof(list[0]);
    CFDictionaryRef		pref_auth_props;

    pref_auth_props
	= SCPreferencesGetValue(eap_prefs,
				kConfigurationKeyDefaultAuthenticationProperties);
    if (pref_auth_props != NULL) {
	accept_types = CFDictionaryGetValue(pref_auth_props,
					    kEAPClientPropAcceptEAPTypes);
	if (accept_types_valid(accept_types)) {
	    CFRetain(pref_auth_props);
	    return (pref_auth_props);
	}
	if (accept_types != NULL) {
	    SCLog(TRUE, LOG_NOTICE, 
		  CFSTR("EAPOLClientConfiguration: default Authentication "
			"Properties invalid, %@ - ignoring"), pref_auth_props);
	}
    }
    accept_types = myCFArrayCreateWithIntegerList(list, list_count);
    auth_props = CFDictionaryCreateMutable(NULL, 0,
					   &kCFTypeDictionaryKeyCallBacks,
					   &kCFTypeDictionaryValueCallBacks);
    CFDictionarySetValue(auth_props,
			 kEAPClientPropAcceptEAPTypes,
			 accept_types);
    CFDictionarySetValue(auth_props, kEAPClientPropEAPFASTUsePAC,
			 kCFBooleanTrue);
    CFDictionarySetValue(auth_props, kEAPClientPropEAPFASTProvisionPAC,
			 kCFBooleanTrue);
    CFRelease(accept_types);
    return (auth_props);

}
Beispiel #7
0
static void
update_pref(SCPreferencesRef prefs, CFStringRef key, CFTypeRef newVal, Boolean *changed)
{
	CFTypeRef	curVal;

	curVal = SCPreferencesGetValue(prefs, key);
	if (!_SC_CFEqual(curVal, newVal)) {
		if (newVal != NULL) {
			SCPreferencesSetValue(prefs, key, newVal);
		} else {
			SCPreferencesRemoveValue(prefs, key);
		}

		*changed = TRUE;
	}

	return;
}
/*
 * For rdar://problem/4685223
 *
 * To keep MoreSCF happy we need to ensure that the first "Set" and
 * "NetworkService" have a [less than] unique identifier that can
 * be parsed as a numeric string.
 *
 * Note: this backwards compatibility code must be enabled using the
 *       following command:
 *
 *       sudo defaults write						\
 *       	/Library/Preferences/SystemConfiguration/preferences	\
 *       	MoreSCF							\
 *       	-bool true
 */
__private_extern__
CFStringRef
__SCPreferencesPathCreateUniqueChild_WithMoreSCFCompatibility(SCPreferencesRef prefs, CFStringRef prefix)
{
	static int	hack	= -1;
	CFStringRef	path	= NULL;

	if (hack < 0) {
		CFBooleanRef	enable;

		enable = SCPreferencesGetValue(prefs, CFSTR("MoreSCF"));
		hack = (isA_CFBoolean(enable) && CFBooleanGetValue(enable)) ? 1 : 0;
	}

	if (hack > 0) {
		CFDictionaryRef	dict;
		Boolean	ok;

		path = CFStringCreateWithFormat(NULL, NULL, CFSTR("%@/%@"), prefix, CFSTR("0"));
		dict = SCPreferencesPathGetValue(prefs, path);
		if (dict != NULL) {
			// if path "0" exists
			CFRelease(path);
			return NULL;
		}

		// unique child with path "0" does not exist, create
		dict = CFDictionaryCreate(NULL,
					  NULL, NULL, 0,
					  &kCFTypeDictionaryKeyCallBacks,
					  &kCFTypeDictionaryValueCallBacks);
		ok = SCPreferencesPathSetValue(prefs, path, dict);
		CFRelease(dict);
		if (!ok) {
			// if create failed
			CFRelease(path);
			return NULL;
		}
	}

	return path;
}
static SInt32 TotalAllRefCounts(SCPreferencesRef prefsRef, CFArrayRef allKeys)
	// Given a connection to the SCF preferences database and an array 
	// of preference keys, this routine calculates the total of all 
	// of the reference counts of all of the nodes in all of the SCF 
	// preferences.  I use this routine to check for reference count leaks 
	// in my use of the SCF preferences database.
{
	CFIndex keyCount;
	CFIndex keyIndex;
	SInt32	result;
	
	result = 0;
	keyCount = CFArrayGetCount(allKeys);
	for (keyIndex = 0; keyIndex < keyCount; keyIndex++) {
		CFPropertyListRef thisPref;
		
		thisPref = SCPreferencesGetValue(prefsRef, (CFStringRef) CFArrayGetValueAtIndex(allKeys, keyIndex));	// C++ requires cast
		CFQPropertyListDeepApplyFunction(thisPref, RefCounter, (void *) &result );
	}
	return result;
}
Beispiel #10
0
//----------------------------------------------------------------------
//	dsauth_get_admin_acct
//----------------------------------------------------------------------
static void dsauth_get_admin_acct(u_int32_t *acctNameSize, char** acctName, u_int32_t *passwordSize, char **password)
{

    SCPreferencesRef 	prefs;
    CFPropertyListRef	globals;
    CFStringRef			acctNameRef;
    char				namestr[256];
    u_int32_t			namelen;
       
    *passwordSize = 0;
    *password = 0;
    *acctNameSize = 0;
    *acctName = 0;

    //
    // get the acct name from the plist
    //
    if ((prefs = SCPreferencesCreate(0, CFSTR("pppd"), kRASServerPrefsFileName)) != 0) {
        // get globals dict from the plist
        if ((globals = SCPreferencesGetValue(prefs, kRASGlobals)) != 0) {
            // retrieve the password server account id
            if ((acctNameRef = CFDictionaryGetValue(globals, KRASGlobPSKeyAccount)) != 0) {
                namestr[0] = 0;
                CFStringGetCString(acctNameRef, namestr, 256, kCFStringEncodingMacRoman);
                if (namestr[0]) {
                    namelen = strlen(namestr);

                    if (dsauth_get_admin_password(namelen, namestr, passwordSize, password) == 0) {
                        *acctNameSize = namelen;
                        *acctName = malloc(namelen + 1);
                        if (acctName != 0)
                            memcpy(*acctName, namestr, namelen + 1);
                       }
                } else
					error("DSAuth plugin: Key access user name not valid.\n");
            }
        }
        CFRelease(prefs);
    }
}
/*
 *
 * copySchedulePowerChangeArrays
 *
 */
static void
copyScheduledPowerChangeArrays(void)
{
#if !TARGET_OS_EMBEDDED
    CFArrayRef              tmp;
    SCPreferencesRef        prefs;
    PowerEventBehavior      *this_behavior;
    int                     i;
   
    prefs = SCPreferencesCreate(0, 
                                CFSTR("PM-configd-AutoWake"),
                                CFSTR(kIOPMAutoWakePrefsPath));
    if(!prefs) return;

    activeEventCnt = 0;
    // Loop through all sleep, wake, shutdown powerbehaviors
    for(i=0; i<kBehaviorsCount; i++) 
    {
        this_behavior = behaviors[i];

        if(this_behavior->array) {
            CFRelease(this_behavior->array);
            this_behavior->array = NULL;
        }

        tmp = isA_CFArray(SCPreferencesGetValue(prefs, this_behavior->title));
        if(tmp && (0 < CFArrayGetCount(tmp))) {
            this_behavior->array = CFArrayCreateMutableCopy(0, 0, tmp);
            activeEventCnt += CFArrayGetCount(tmp);
        } else {
            this_behavior->array = NULL;
        }
    }



    CFRelease(prefs);

#endif
}
Beispiel #12
0
// ----------------------------------------------------------------------------
//	get_active_server
// ----------------------------------------------------------------------------
CFArrayRef get_active_servers(struct vpn_params *params)
{
    SCPreferencesRef 		prefs = 0;
    CFPropertyListRef		active_servers;
    CFArrayRef                  arrayCopy = 0;
    char 			pathStr[MAXPATHLEN];

    // open the prefs file
    prefs = SCPreferencesCreate(0, CFSTR("vpnd"), kRASServerPrefsFileName);
    if (prefs == NULL) {
        CFStringGetCString(kRASServerPrefsFileName, pathStr, MAXPATHLEN, kCFStringEncodingMacRoman);
        vpnlog(LOG_ERR, "Unable to read vpnd prefs file '%s'\n", pathStr);
        return 0;
    }
    // get active servers list from the plist
    active_servers = SCPreferencesGetValue(prefs, kRASActiveServers);
    if (active_servers && isArray(active_servers))
        if (CFArrayGetCount(active_servers) > 0)
            arrayCopy = CFArrayCreateCopy(0, active_servers);
    CFRelease(prefs);
    return arrayCopy;
}
Beispiel #13
0
Boolean
SCNetworkSetRemove(SCNetworkSetRef set)
{
	CFStringRef		currentPath;
	Boolean			ok		= FALSE;
	CFStringRef		path;
	SCNetworkSetPrivateRef	setPrivate	= (SCNetworkSetPrivateRef)set;

	if (!isA_SCNetworkSet(set)) {
		_SCErrorSet(kSCStatusInvalidArgument);
		return FALSE;
	}

	currentPath = SCPreferencesGetValue(setPrivate->prefs, kSCPrefCurrentSet);
	path = SCPreferencesPathKeyCreateSet(NULL, setPrivate->setID);
	if (!isA_CFString(currentPath) || !CFEqual(currentPath, path)) {
		ok = SCPreferencesPathRemoveValue(setPrivate->prefs, path);
	} else {
		_SCErrorSet(kSCStatusInvalidArgument);
	}
	CFRelease(path);

	return ok;
}
Beispiel #14
0
static void LeakTest(TestFunc tester)
	// Given a test name and a pointer to a test function, 
	// this routine calls the test function repeatedly to check 
	// for SCF preferences reference count leaks.
{
	OSStatus 			err;
	SCPreferencesRef 	prefsRef;
	CFArrayRef 			allKeys;
	int					i;
	SInt32				startCount;
	SInt32				endCount;
	
	// This is kinda cheesy.  We need to use the same SCPreferencesRef 
	// that MoreSCF uses because otherwise we can't see the reference 
	// count changes done by MoreSCF.  Ideally, we wouldn't want to run 
	// within a MoreSCOpen/MoreSCClose pair because then our changes 
	// aren't necessarily being committed to the database.  However, 
	// given the current MoreSCF architecture, where the SCPreferenceRef 
	// is only valid inside the MoreSCOpen/MoreSCClose pair, that's 
	// exactly what we have to do.

	allKeys = NULL;
	
	err = MoreSCOpen(false, false);
	if (err == noErr) {
		prefsRef = MoreSCGetSCPreferencesRef();
	}

	// Now get a copy of the array of all keys in the database.  
	// We make this copy using CFPropertyListCreateDeepCopy so we 
	// know that it's completely independent of the SCF.
	
	if (err == noErr) {
		CFArrayRef allKeysOrig;
		
		allKeysOrig = NULL;

		allKeysOrig = SCPreferencesCopyKeyList(prefsRef);
		if (allKeysOrig == NULL) {
			err = SCError();
		}
		if (err == noErr) {
			allKeys = (CFArrayRef) CFPropertyListCreateDeepCopy(NULL, allKeysOrig, kCFPropertyListMutableContainersAndLeaves);	// C++ requires cast
			if (allKeys == NULL) {
				err = coreFoundationUnknownErr;
			}
		}
		
		CFQRelease(allKeysOrig);
	}

	// Now do the reference counting test.  Call the tester function
	// a few times to allow the refcounts to stabilise.  Then get 
	// a summ of all the nodes in all of the keys in SCF.  Then 
	// run the test a 10 more times and get another count.  If 
	// the counts are different, we're in trouble.
	
	if (err == noErr) {
		for (i = 0; i < 3; i++) {
			tester();
		}
		
		startCount = TotalAllRefCounts(prefsRef, allKeys);
		
		for (i = 0; i < 10; i++) {
			tester();
		}
		
		endCount = TotalAllRefCounts(prefsRef, allKeys);
		
		if (startCount != endCount) {
			CFIndex keyCount;
			CFIndex keyIndex;
			
			fprintf(stderr, "*** Leaked %ld reference counts.\n", endCount - startCount);

			keyCount = CFArrayGetCount(allKeys);
			for (keyIndex = 0; keyIndex < keyCount; keyIndex++) {
				CFPropertyListRef thisPref;

				// The commented out code is only needed when you're actively 
				// trying to track down a leak.  Given that leaks are rare 
				// I decided against making a proper architecture for this. 
				// Just uncomment the code and modify it appropriately.
				
				startCount = 0;
				thisPref = SCPreferencesGetValue(prefsRef, (CFStringRef) CFArrayGetValueAtIndex(allKeys, keyIndex));	// C++ requires cast
				CFQPropertyListDeepApplyFunction(thisPref, RefCounter, (void *) &startCount );
//				if (keyIndex == 0) {
//					fprintf(stderr, "*** BEFORE ***\n");
//					PrintPropertyList(thisPref);
//				}

				tester();

				endCount = 0;
				thisPref = SCPreferencesGetValue(prefsRef, (CFStringRef) CFArrayGetValueAtIndex(allKeys, keyIndex));	// C++ requires cast
				CFQPropertyListDeepApplyFunction(thisPref, RefCounter, (void *) &endCount );
//				if (keyIndex == 0) {
//					fprintf(stderr, "*** AFTER ***\n");
//					PrintPropertyList(thisPref);
//				}
				
				if (startCount != endCount) {
					fprintf(stderr, "*** Leaked %ld reference counts in set number %ld\n", endCount - startCount, keyIndex);
					CFShow(CFArrayGetValueAtIndex(allKeys, keyIndex));
				}
			}
		}
	}

	MoreSCClose(&err, false);

	CFQRelease(allKeys);

    if (err != noErr) {
        fprintf(stderr, "*** Failed with error %ld!\n", err);
    }
}
/*
 * Function: EAPOLClientConfigurationSave
 * 
 * Purpose:
 *   Write the configuration to persistent storage.
 *
 * Returns:
 *   TRUE if successfully written, FALSE otherwise.
 */	
Boolean
EAPOLClientConfigurationSave(EAPOLClientConfigurationRef cfg)
{
    Boolean		changed = FALSE;
    CFDictionaryRef	existing_prefs_dict;
    CFDictionaryRef	prefs_dict;
    Boolean		ret = FALSE;

    /* save the 802.1X prefs */
    prefs_dict = export_profiles(cfg);
    if (prefs_dict == NULL) {
	EAPLOG(LOG_NOTICE,
	       "EAPOLClientConfigurationSave export_profiles() failed");
	goto done;
    }
    existing_prefs_dict = SCPreferencesGetValue(cfg->eap_prefs,
						kConfigurationKeyProfiles);
    if (cfg->def_auth_props_changed == FALSE
	&& my_CFEqual(existing_prefs_dict, prefs_dict)) {
	/* configuration is the same, no need to save */
    }
    else {
	if (cfg->def_auth_props_changed) {
	    ret = SCPreferencesSetValue(cfg->eap_prefs,
					kConfigurationKeyDefaultAuthenticationProperties,
					cfg->def_auth_props);
	    if (ret == FALSE) {
		EAPLOG(LOG_NOTICE,
		       "EAPOLClientConfigurationSave SCPreferencesSetValue"
		       " failed %s",
		       SCErrorString(SCError()));
		goto done;
	    }
	}
	ret = SCPreferencesSetValue(cfg->eap_prefs, kConfigurationKeyProfiles,
				    prefs_dict);
	if (ret == FALSE) {
	    EAPLOG(LOG_NOTICE,
		   "EAPOLClientConfigurationSave SCPreferencesSetValue"
		   " failed %s",
		   SCErrorString(SCError()));
	    goto done;
	}
	ret = SCPreferencesCommitChanges(cfg->eap_prefs);
	if (ret == FALSE) {
	    EAPLOG(LOG_NOTICE,
		   "EAPOLClientConfigurationSave SCPreferencesCommitChanges"
		   " failed %s", SCErrorString(SCError()));
	    return (FALSE);
	}
	cfg->def_auth_props_changed = FALSE;
	SCPreferencesApplyChanges(cfg->eap_prefs);
	changed = TRUE;
    }

    /* save the network prefs */
    {
	Boolean		this_changed = FALSE;

	ret = saveInterfaceEAPOLConfiguration(cfg, &this_changed);
	if (ret == FALSE) {
	    goto done;
	}
	if (this_changed) {
	    changed = TRUE;
	}
    }
    my_CFRelease(&cfg->sc_prefs); /* force a refresh */

 done:
    my_CFRelease(&prefs_dict);
    if (changed) {
	notify_post(kEAPOLClientConfigurationChangedNotifyKey);
    }
    return (ret);
}
Beispiel #16
0
void DAPreferenceListRefresh( void )
{
    struct stat status1;
    struct stat status2;

    /*
     * Determine whether the preference list is up-to-date.
     */

    if ( stat( ___PREFS_DEFAULT_DIR "/" "autodiskmount.plist", &status1 ) )
    {
        __gDAPreferenceListTime1.tv_sec  = 0;
        __gDAPreferenceListTime1.tv_nsec = 0;
    }

    if ( stat( ___PREFS_DEFAULT_DIR "/" _kDADaemonName ".plist", &status2 ) )
    {
        __gDAPreferenceListTime2.tv_sec  = 0;
        __gDAPreferenceListTime2.tv_nsec = 0;
    }

    if ( __gDAPreferenceListTime1.tv_sec  != status1.st_mtimespec.tv_sec  ||
         __gDAPreferenceListTime1.tv_nsec != status1.st_mtimespec.tv_nsec ||
         __gDAPreferenceListTime2.tv_sec  != status2.st_mtimespec.tv_sec  ||
         __gDAPreferenceListTime2.tv_nsec != status2.st_mtimespec.tv_nsec )
    {
        SCPreferencesRef preferences;

        __gDAPreferenceListTime1.tv_sec  = status1.st_mtimespec.tv_sec;
        __gDAPreferenceListTime1.tv_nsec = status1.st_mtimespec.tv_nsec;
        __gDAPreferenceListTime2.tv_sec  = status2.st_mtimespec.tv_sec;
        __gDAPreferenceListTime2.tv_nsec = status2.st_mtimespec.tv_nsec;

        /*
         * Clear the preference list.
         */

        CFDictionaryRemoveAllValues( gDAPreferenceList );

        /*
         * Build the preference list.
         */

        preferences = SCPreferencesCreate( kCFAllocatorDefault, CFSTR( "autodiskmount" ), CFSTR( "autodiskmount.plist" ) );

        if ( preferences )
        {
            CFTypeRef value;

            value = SCPreferencesGetValue( preferences, CFSTR( "AutomountDisksWithoutUserLogin" ) );

            if ( value == kCFBooleanTrue )
            {
                CFDictionarySetValue( gDAPreferenceList, kDAPreferenceMountDeferExternalKey,  kCFBooleanFalse );
                CFDictionarySetValue( gDAPreferenceList, kDAPreferenceMountDeferRemovableKey, kCFBooleanFalse );
                CFDictionarySetValue( gDAPreferenceList, kDAPreferenceMountTrustExternalKey,  kCFBooleanTrue  );
            }
            else if ( value == kCFBooleanFalse )
            {
                CFDictionarySetValue( gDAPreferenceList, kDAPreferenceMountDeferExternalKey,  kCFBooleanFalse );
                CFDictionarySetValue( gDAPreferenceList, kDAPreferenceMountDeferRemovableKey, kCFBooleanTrue  );
                CFDictionarySetValue( gDAPreferenceList, kDAPreferenceMountTrustExternalKey,  kCFBooleanTrue  );
            }

            CFRelease( preferences );
        }

        preferences = SCPreferencesCreate( kCFAllocatorDefault, CFSTR( _kDADaemonName ), CFSTR( _kDADaemonName ".plist" ) );

        if ( preferences )
        {
            CFTypeRef value;

            value = SCPreferencesGetValue( preferences, kDAPreferenceMountDeferExternalKey );

            if ( value )
            {
                if ( CFGetTypeID( value ) == CFBooleanGetTypeID( ) )
                {
                    CFDictionarySetValue( gDAPreferenceList, kDAPreferenceMountDeferExternalKey, value );
                }
            }

            value = SCPreferencesGetValue( preferences, kDAPreferenceMountDeferInternalKey );

            if ( value )
            {
                if ( CFGetTypeID( value ) == CFBooleanGetTypeID( ) )
                {
                    CFDictionarySetValue( gDAPreferenceList, kDAPreferenceMountDeferInternalKey, value );
                }
            }

            value = SCPreferencesGetValue( preferences, kDAPreferenceMountDeferRemovableKey );

            if ( value )
            {
                if ( CFGetTypeID( value ) == CFBooleanGetTypeID( ) )
                {
                    CFDictionarySetValue( gDAPreferenceList, kDAPreferenceMountDeferRemovableKey, value );
                }
            }

            value = SCPreferencesGetValue( preferences, kDAPreferenceMountTrustExternalKey );

            if ( value )
            {
                if ( CFGetTypeID( value ) == CFBooleanGetTypeID( ) )
                {
                    CFDictionarySetValue( gDAPreferenceList, kDAPreferenceMountTrustExternalKey, value );
                }
            }

            value = SCPreferencesGetValue( preferences, kDAPreferenceMountTrustInternalKey );

            if ( value )
            {
                if ( CFGetTypeID( value ) == CFBooleanGetTypeID( ) )
                {
                    CFDictionarySetValue( gDAPreferenceList, kDAPreferenceMountTrustInternalKey, value );
                }
            }

            value = SCPreferencesGetValue( preferences, kDAPreferenceMountTrustRemovableKey );

            if ( value )
            {
                if ( CFGetTypeID( value ) == CFBooleanGetTypeID( ) )
                {
                    CFDictionarySetValue( gDAPreferenceList, kDAPreferenceMountTrustRemovableKey, value );
                }
            }

            CFRelease( preferences );
        }
    }
}
STATIC void
import_profiles(EAPOLClientConfigurationRef cfg)
{
    int					count = 0;
    CFMutableDictionaryRef		domains_dict;
    int					i;
    const void * *			keys;
    CFDictionaryRef			prefs_dict;
    CFMutableDictionaryRef		profiles_dict;
    CFMutableDictionaryRef		ssids_dict;
    const void * *			values;

    profiles_dict = CFDictionaryCreateMutable(NULL, 0,
					      &kCFTypeDictionaryKeyCallBacks,
					      &kCFTypeDictionaryValueCallBacks);
    ssids_dict = CFDictionaryCreateMutable(NULL, 0,
					   &kCFTypeDictionaryKeyCallBacks,
					   &kCFTypeDictionaryValueCallBacks);
    domains_dict = CFDictionaryCreateMutable(NULL, 0,
					     &kCFTypeDictionaryKeyCallBacks,
					     &kCFTypeDictionaryValueCallBacks);
    prefs_dict = SCPreferencesGetValue(cfg->eap_prefs,
				       kConfigurationKeyProfiles);
    if (isA_CFDictionary(prefs_dict) != NULL) {
	count = CFDictionaryGetCount(prefs_dict);
    }
    if (count == 0) {
	goto done;
    }

    /* allocate a single array, half for keys, half for values */
    keys = (const void * *)malloc(sizeof(*keys) * count * 2);
    values = keys + count;
    CFDictionaryGetKeysAndValues(prefs_dict, keys, values);
    for (i = 0; i < count; i++) {
	EAPOLClientProfileRef	profile;
	CFDictionaryRef		profile_dict = values[i];
	CFStringRef		profileID = keys[i];
	CFDataRef		ssid;

	if (isA_CFDictionary(profile_dict) == NULL) {
	    SCLog(TRUE, LOG_NOTICE, 
		  CFSTR("EAPOLClientConfiguration: invalid profile with id %@"),
		  profileID);
	    continue;
	}
	profile = EAPOLClientProfileCreateWithDictAndProfileID(profile_dict,
							       profileID);
	if (profile == NULL) {
	    continue;
	}
	ssid = EAPOLClientProfileGetWLANSSIDAndSecurityType(profile, NULL);
	if (ssid != NULL) {
	    CFStringRef		conflicting_profileID;

	    conflicting_profileID = CFDictionaryGetValue(ssids_dict, ssid);
	    if (conflicting_profileID != NULL) {
		CFStringRef	ssid_str = my_CFStringCreateWithData(ssid);

		SCLog(TRUE, LOG_NOTICE, 
		      CFSTR("EAPOLClientConfiguration: ignoring profile %@:"
			    " SSID '%@' already used by %@"),
		      profileID, ssid_str, conflicting_profileID);
		CFRelease(ssid_str);
		CFRelease(profile);
		continue;
	    }
	    CFDictionarySetValue(ssids_dict, ssid, profileID);
	}
	else {
	    CFStringRef		domain;

	    domain = EAPOLClientProfileGetWLANDomain(profile);
	    if (domain != NULL) {
		CFStringRef		conflicting_profileID;

		conflicting_profileID 
		    = CFDictionaryGetValue(profiles_dict, domain);
		if (conflicting_profileID != NULL) {
		    SCLog(TRUE, LOG_NOTICE, 
			  CFSTR("EAPOLClientConfiguration: ignoring profile %@:"
				" WLAN domain '%@' already used by %@"),
			  profileID, domain, conflicting_profileID);
		    CFRelease(profile);
		    continue;
		}
		CFDictionarySetValue(domains_dict, domain, profileID);
	    }
	}
	CFDictionarySetValue(profiles_dict, profileID, profile);
	EAPOLClientProfileSetConfiguration(profile, cfg);
	CFRelease(profile);
    }
    free(keys);

 done:
    cfg->ssids = ssids_dict;
    cfg->profiles = profiles_dict;
    cfg->domains = domains_dict;
    return;
}
Beispiel #18
0
// ----------------------------------------------------------------------------
//	process_prefs
// ----------------------------------------------------------------------------
int process_prefs(struct vpn_params *params)
{

    char 			pathStr[MAXPATHLEN];
    SCPreferencesRef 		prefs = 0;
    CFPropertyListRef		servers_list;
    
    char 			text[512] = "";
  
    // open the prefs file
    prefs = SCPreferencesCreate(0, CFSTR("vpnd"), kRASServerPrefsFileName);
    if (prefs == NULL) {
        CFStringGetCString(kRASServerPrefsFileName, pathStr, MAXPATHLEN, kCFStringEncodingMacRoman);
        snprintf(text, sizeof(text), "Unable to read vpnd prefs file '%s'\n", pathStr);
        goto fail;
    }
    // get servers list from the plist
    servers_list = SCPreferencesGetValue(prefs, kRASServers);
    if (servers_list == NULL) {
        snprintf(text, sizeof(text), "Could not get servers dictionary\n");
        goto fail;
    }
    // retrieve the information for the given Server ID
    params->serverIDRef = CFStringCreateWithCString(0, params->server_id, kCFStringEncodingMacRoman);
    if (params->serverIDRef == NULL) {
        snprintf(text, sizeof(text), "Could not create CFString for server ID\n");
        goto fail;
    }
    params->serverRef = CFDictionaryGetValue(servers_list, params->serverIDRef);
    if (params->serverRef == NULL || isDictionary(params->serverRef) == 0) {
        snprintf(text, sizeof(text), "Server ID '%.64s' invalid\n", params->server_id);
        params->serverRef = 0;
        goto fail;
    }
    CFRetain(params->serverRef);
    CFRelease(prefs);
    prefs = 0;    
    
    // process the dictionaries
    if (process_server_prefs(params))
        goto fail;
    if (process_interface_prefs(params))
        goto fail;
	
	switch (params->server_type) {
		case SERVER_TYPE_PPP:
			if (ppp_process_prefs(params)) {
				snprintf(text, sizeof(text), "Error while reading PPP preferences\n");
				goto fail;
			}
			break;
		case SERVER_TYPE_IPSEC:
			if (ipsec_process_prefs(params)) {
				snprintf(text, sizeof(text), "Error while reading IPSec preferences\n");
				goto fail;
			}
			break;
	}

    return 0;

fail:
    vpnlog(LOG_ERR, text[0] ? text : "Error while reading preferences\n");
    if (params->serverIDRef) {
        CFRelease(params->serverIDRef);
        params->serverIDRef = 0;
    }
    if (params->serverRef) {
        CFRelease(params->serverRef);
        params->serverRef = 0;
    }
    if (prefs)
        CFRelease(prefs);
    return -1;
}
Beispiel #19
0
int
main(int argc, char **argv)
{
	const char		*command	= argv[0];
	extern int		optind;
	int			opt;
	CFStringRef		current		= NULL;
	int			currentMatched	= 0;
	CFStringRef		newSet		= NULL;	/* set key */
	CFStringRef		newSetUDN	= NULL;	/* user defined name */
	CFStringRef		prefix;
	SCPreferencesRef	prefs;
	CFDictionaryRef		sets;
	CFIndex			nSets;
	const void		**setKeys	= NULL;
	const void		**setVals	= NULL;
	CFIndex			i;

#if	!TARGET_OS_IPHONE
	AuthorizationRef	authorization	= NULL;
	AuthorizationFlags	flags		= kAuthorizationFlagDefaults;
	CFMutableDictionaryRef	options;
	OSStatus		status;
#endif	// !TARGET_OS_IPHONE

	/* process any arguments */

	while ((opt = getopt_long(argc, argv, "dvn", longopts, NULL)) != -1) {
		switch(opt) {
			case 'd':
				_sc_debug = TRUE;
				_sc_log   = FALSE;	/* enable framework logging */
				break;
			case 'v':
				_sc_verbose = TRUE;
				break;
			case 'n':
				apply = FALSE;
				break;
			case '?':
			default :
				usage(command);
		}
	}
	argc -= optind;
	argv += optind;

	prefix = CFStringCreateWithFormat(NULL, NULL, CFSTR("/%@/"), kSCPrefSets);

	if (argc == 1) {
		newSet = CFStringCreateWithCString(NULL, argv[0], kCFStringEncodingMacRoman);

		/* check if a full path to the new "set" was specified */
		if ((CFStringGetLength(newSet) > 0) && CFStringHasPrefix(newSet, prefix)) {
			CFRange			range;
			CFMutableStringRef	str;

			str = CFStringCreateMutableCopy(NULL, 0, newSet);
			CFRelease(newSet);

			CFStringDelete(str, CFRangeMake(0, CFStringGetLength(prefix)));
			newSet = CFStringCreateCopy(NULL, newSet);
			CFRelease(str);

			range = CFStringFind(newSet, CFSTR("/"), 0);
			if (range.location != kCFNotFound) {
				SCPrint(TRUE, stderr, CFSTR("Set \"%@\" not available\n."), newSet);
				exit (1);
			}
		}
	} else {
		newSet = CFRetain(CFSTR(""));
	}

#if	!TARGET_OS_IPHONE
	status = AuthorizationCreate(NULL,
				     kAuthorizationEmptyEnvironment,
				     flags,
				     &authorization);
	if (status != errAuthorizationSuccess) {
		SCPrint(TRUE,
			stderr,
			CFSTR("AuthorizationCreate() failed: status = %d\n"),
			(int)status);
		exit (1);
	}

	options = CFDictionaryCreateMutable(NULL,
					    0,
					    &kCFTypeDictionaryKeyCallBacks,
					    &kCFTypeDictionaryValueCallBacks);
	CFDictionarySetValue(options, kSCPreferencesOptionChangeNetworkSet, kCFBooleanTrue);
	prefs = SCPreferencesCreateWithOptions(NULL, CFSTR("scselect"), NULL, authorization, options);
	CFRelease(options);
	if (prefs == NULL) {
		SCPrint(TRUE, stderr, CFSTR("SCPreferencesCreate() failed\n"));
		exit (1);
	}
#else	// !TARGET_OS_IPHONE
	prefs = SCPreferencesCreate(NULL, CFSTR("scselect"), NULL);
	if (prefs == NULL) {
		SCPrint(TRUE, stderr, CFSTR("SCPreferencesCreate() failed\n"));
		exit (1);
	}
#endif	// !TARGET_OS_IPHONE

	sets = SCPreferencesGetValue(prefs, kSCPrefSets);
	if (sets == NULL) {
		SCPrint(TRUE, stderr, CFSTR("No network sets defined.\n"));
		exit (1);
	}

	current = SCPreferencesGetValue(prefs, kSCPrefCurrentSet);
	if (current != NULL) {
		if (CFStringHasPrefix(current, prefix)) {
			CFMutableStringRef	tmp;

			tmp = CFStringCreateMutableCopy(NULL, 0, current);
			CFStringDelete(tmp, CFRangeMake(0, CFStringGetLength(prefix)));
			current = tmp;
		} else {
			CFRetain(current);
			currentMatched = -1;	/* not prefixed */
		}
	} else {
		current = CFRetain(CFSTR(""));
		currentMatched = -2;	/* not defined */
	}

	nSets = CFDictionaryGetCount(sets);
	if (nSets > 0) {
		setKeys = CFAllocatorAllocate(NULL, nSets * sizeof(CFStringRef), 0);
		setVals = CFAllocatorAllocate(NULL, nSets * sizeof(CFDictionaryRef), 0);
		CFDictionaryGetKeysAndValues(sets, setKeys, setVals);
	}

	/* check for set with matching name */
	for (i = 0; i < nSets; i++) {
		CFStringRef	key  = (CFStringRef)    setKeys[i];
		CFDictionaryRef	dict = (CFDictionaryRef)setVals[i];

		if ((currentMatched >= 0) && CFEqual(key, current)) {
			currentMatched++;
		}

		if (CFEqual(newSet, key)) {
			newSetUDN = CFDictionaryGetValue(dict, kSCPropUserDefinedName);
			if (newSetUDN != NULL) CFRetain(newSetUDN);
			goto found;
		}
	}

	/* check for set with matching user-defined name */
	for (i = 0; i < nSets; i++) {
		CFStringRef	key  = (CFStringRef)    setKeys[i];
		CFDictionaryRef	dict = (CFDictionaryRef)setVals[i];

		newSetUDN = CFDictionaryGetValue(dict, kSCPropUserDefinedName);
		if ((newSetUDN != NULL) && CFEqual(newSet, newSetUDN)) {
			CFRelease(newSet);
			newSet = CFRetain(key);
			CFRetain(newSetUDN);
			goto found;
		}
	}

	if (argc == 1) {
		SCPrint(TRUE, stderr, CFSTR("Set \"%@\" not available.\n"), newSet);
		exit(1);
	}

	SCPrint(TRUE, stdout,
		CFSTR("Defined sets include:%s\n"),
		(currentMatched > 0) ? " (* == current set)" : "");

	for (i = 0; i < nSets; i++) {
		CFStringRef	key  = (CFStringRef)    setKeys[i];
		CFDictionaryRef	dict = (CFDictionaryRef)setVals[i];
		CFStringRef	udn  = CFDictionaryGetValue(dict, kSCPropUserDefinedName);

		SCPrint(TRUE, stdout,
			CFSTR(" %s %@\t(%@)\n"),
			((currentMatched > 0) && CFEqual(key, current)) ? "*" : " ",
			key,
			udn ? udn : CFSTR(""));
	}

	switch (currentMatched) {
		case -2 :
			SCPrint(TRUE, stdout, CFSTR("\nCurrent set not defined.\n"));
			break;
		case -1 :
			SCPrint(TRUE, stdout, CFSTR("\nCurrent set \"%@\" may not be valid\n"), current);
			break;
		case  0 :
			SCPrint(TRUE, stdout, CFSTR("\nCurrent set \"%@\" not valid\n"), current);
			break;
		default :
			break;
	}

	CFRelease(prefix);
	exit (0);

    found :

	CFRelease(current);
	current = CFStringCreateWithFormat(NULL, NULL, CFSTR("%@%@"), prefix, newSet);

	if (!SCPreferencesSetValue(prefs, kSCPrefCurrentSet, current)) {
		SCPrint(TRUE, stderr,
			CFSTR("SCPreferencesSetValue(...,%@,%@) failed: %s\n"),
			kSCPrefCurrentSet,
			current,
			SCErrorString(SCError()));
		exit (1);
	}

	if (!SCPreferencesCommitChanges(prefs)) {
		int	sc_status	= SCError();

		if (sc_status == kSCStatusAccessError) {
			SCPrint(TRUE, stderr,
				CFSTR("Only local console users and administrators can change locations\n"));
			exit (EX_NOPERM);
		} else {
			SCPrint(TRUE, stderr,
				CFSTR("SCPreferencesCommitChanges() failed: %s\n"),
				SCErrorString(sc_status));
			exit (1);
		}
	}

	if (apply) {
		if (!SCPreferencesApplyChanges(prefs)) {
			SCPrint(TRUE, stderr,
				CFSTR("SCPreferencesApplyChanges() failed %s\n"),
				SCErrorString(SCError()));
			exit (1);
		}
	}

	SCPrint(TRUE, stdout,
		CFSTR("%@ updated to %@ (%@)\n"),
		kSCPrefCurrentSet,
		newSet,
		newSetUDN ? newSetUDN : CFSTR(""));

	CFRelease(current);
	CFRelease(newSet);
	if (newSetUDN != NULL)	CFRelease(newSetUDN);
	CFRelease(prefix);
	CFRelease(prefs);

#if	!TARGET_OS_IPHONE
	AuthorizationFree(authorization, kAuthorizationFlagDefaults);
//	AuthorizationFree(authorization, kAuthorizationFlagDestroyRights);
#endif	/* !TARGET_OS_IPHONE */

	exit (0);
	return 0;
}
Beispiel #20
0
/* -----------------------------------------------------------------------------
----------------------------------------------------------------------------- */
static void
nc_show(int argc, char **argv)
{
	SCNetworkServiceRef	service			= NULL;
	SCDynamicStoreRef	store			= NULL;
	int			exit_code		= 1;
	CFStringRef		serviceID		= NULL;
	CFStringRef		iftype			= NULL;
	CFStringRef		ifsubtype		= NULL;
	CFStringRef		type_entity_key		= NULL;
	CFStringRef		subtype_entity_key	= NULL;
	CFDictionaryRef		type_entity_dict	= NULL;
	CFDictionaryRef		subtype_entity_dict	= NULL;
	CFStringRef		vpnprefpath		= NULL;
#if !TARGET_OS_IPHONE
	CFDataRef		bookmarkData		= NULL;
	CFURLRef		directory		= NULL;
	Boolean			isStale			= FALSE;
	char			*path			= NULL;
	CFIndex			path_len		= 0;
#endif

	service = nc_copy_service_from_arguments(argc, argv, NULL);
	if (service == NULL) {
		SCPrint(TRUE, stderr, CFSTR("No service\n"));
		exit(exit_code);
	}

	serviceID = SCNetworkServiceGetServiceID(service);

	nc_get_service_type_and_subtype(service, &iftype, &ifsubtype);

	if (!CFEqual(iftype, kSCEntNetPPP) &&
	    !CFEqual(iftype, kSCEntNetIPSec) &&
	    !CFEqual(iftype, kSCEntNetVPN)) {
		SCPrint(TRUE, stderr, CFSTR("Not a connection oriented service: %@\n"), serviceID);
		goto done;
	}

	type_entity_key = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL, kSCDynamicStoreDomainSetup, serviceID, iftype);

	nc_print_VPN_service(service);

#if !TARGET_OS_IPHONE
	vpnprefpath = CFStringCreateWithFormat(NULL, NULL, CFSTR("%@%@%@"), PREF_PREFIX, ifsubtype, PREF_SUFFIX);
	if (vpnprefpath == NULL) {
		goto skipURL;
	}

	path_len = CFStringGetLength(vpnprefpath) + 1;
	path = malloc(path_len);
	if (path == NULL) {
		goto skipURL;
	}

	if (!CFStringGetCString(vpnprefpath, path, path_len, kCFStringEncodingASCII)) {
		SCPrint(TRUE, stderr, CFSTR("CFStringGetCString failed\n"));
		goto done;
	}

	do_prefs_init();		/* initialization */
	do_prefs_open(1, &path);	/* open prefs */

	bookmarkData = SCPreferencesGetValue(prefs, CFSTR("ApplicationURL"));
	if (bookmarkData == NULL) {
		goto skipURL;
	}

	directory = CFURLCreateByResolvingBookmarkData(kCFAllocatorDefault, bookmarkData, 0, NULL, NULL, &isStale, NULL);
	if (directory == NULL) {
		goto skipURL;
	}

	SCPrint(TRUE, stdout, CFSTR("ApplicationURL: %@\n"), directory);
skipURL:
#endif

	store = SCDynamicStoreCreate(NULL, CFSTR("scutil --nc"), NULL, NULL);
	if (store == NULL) {
		SCPrint(TRUE, stderr, CFSTR("Unable to create dynamic store: %s\n"), SCErrorString(SCError()));
		goto done;
	}
	type_entity_dict = SCDynamicStoreCopyValue(store, type_entity_key);

	if (!type_entity_dict) {
		SCPrint(TRUE, stderr, CFSTR("No \"%@\" configuration available\n"), iftype);
	} else {
		SCPrint(TRUE, stdout, CFSTR("%@ %@\n"), iftype, type_entity_dict);
	}

	if (ifsubtype) {
		subtype_entity_key = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL, kSCDynamicStoreDomainSetup, serviceID, ifsubtype);
		subtype_entity_dict = SCDynamicStoreCopyValue(store, subtype_entity_key);
		if (!subtype_entity_dict) {
			//
		}
		else {
			SCPrint(TRUE, stdout, CFSTR("%@ %@\n"), ifsubtype, subtype_entity_dict);
		}
	}

	exit_code = 0;

done:
	my_CFRelease(&type_entity_key);
	my_CFRelease(&type_entity_dict);
	my_CFRelease(&subtype_entity_key);
	my_CFRelease(&subtype_entity_dict);
	my_CFRelease(&store);
	my_CFRelease(&service);
	my_CFRelease(&vpnprefpath);
	_prefs_close();
	exit(exit_code);
}
Beispiel #21
0
static void
updateSCDynamicStore(SCPreferencesRef prefs)
{
	CFStringRef		current		= NULL;
	CFDateRef		date		= NULL;
	CFMutableDictionaryRef	dict		= NULL;
	CFDictionaryRef		global		= NULL;
	CFIndex			i;
	CFArrayRef		keys;
	CFIndex			n;
	CFStringRef		pattern;
	CFMutableArrayRef	patterns;
	CFDictionaryRef		set		= NULL;

	/*
	 * initialize old preferences, new preferences, an array
	 * of keys which have not changed, and an array of keys
	 * to be removed (cleaned up).
	 */

	patterns = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
	pattern  = CFStringCreateWithFormat(NULL,
					    NULL,
					    CFSTR("^%@.*"),
					    kSCDynamicStoreDomainSetup);
	CFArrayAppendValue(patterns, pattern);
	dict = (CFMutableDictionaryRef)SCDynamicStoreCopyMultiple(store, NULL, patterns);
	CFRelease(patterns);
	CFRelease(pattern);
	if (dict) {
		currentPrefs = CFDictionaryCreateMutableCopy(NULL, 0, dict);
		CFRelease(dict);
	} else {
		currentPrefs = CFDictionaryCreateMutable(NULL,
							 0,
							 &kCFTypeDictionaryKeyCallBacks,
							 &kCFTypeDictionaryValueCallBacks);
	}

	unchangedPrefsKeys = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);

	i = CFDictionaryGetCount(currentPrefs);
	if (i > 0) {
		const void	**currentKeys;
		CFArrayRef	array;

		currentKeys = CFAllocatorAllocate(NULL, i * sizeof(CFStringRef), 0);
		CFDictionaryGetKeysAndValues(currentPrefs, currentKeys, NULL);
		array = CFArrayCreate(NULL, currentKeys, i, &kCFTypeArrayCallBacks);
		removedPrefsKeys = CFArrayCreateMutableCopy(NULL, 0, array);
		CFRelease(array);
		CFAllocatorDeallocate(NULL, currentKeys);
	} else {
		removedPrefsKeys = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
	}

	/*
	 * The "newPrefs" dictionary will contain the new / updated
	 * configuration which will be written to the configuration cache.
	 */
	newPrefs = CFDictionaryCreateMutable(NULL,
						 0,
						 &kCFTypeDictionaryKeyCallBacks,
						 &kCFTypeDictionaryValueCallBacks);

	/*
	 * create status dictionary associated with current configuration
	 * information including:
	 *   - current set "name" to cache
	 *   - time stamp indicating when the cache preferences were
	 *     last updated.
	 */
	dict = CFDictionaryCreateMutable(NULL,
					 0,
					 &kCFTypeDictionaryKeyCallBacks,
					 &kCFTypeDictionaryValueCallBacks);
	date = CFDateCreate(NULL, CFAbsoluteTimeGetCurrent());

	/*
	 * load preferences
	 */
	keys = SCPreferencesCopyKeyList(prefs);
	if ((keys == NULL) || (CFArrayGetCount(keys) == 0)) {
		SCLog(TRUE, LOG_NOTICE, CFSTR("updateConfiguration(): no preferences."));
		goto done;
	}

	/*
	 * get "global" system preferences
	 */
	global = SCPreferencesGetValue(prefs, kSCPrefSystem);
	if (!global) {
		/* if no global preferences are defined */
		goto getSet;
	}

	if (!isA_CFDictionary(global)) {
		SCLog(TRUE, LOG_ERR,
		      CFSTR("updateConfiguration(): %@ is not a dictionary."),
		      kSCPrefSystem);
		goto done;
	}

	/* flatten property list */
	flatten(prefs, CFSTR("/"), global);

    getSet :

	/*
	 * get current set name
	 */
	current = SCPreferencesGetValue(prefs, kSCPrefCurrentSet);
	if (!current) {
		/* if current set not defined */
		goto done;
	}

	if (!isA_CFString(current)) {
		SCLog(TRUE, LOG_ERR,
		      CFSTR("updateConfiguration(): %@ is not a string."),
		      kSCPrefCurrentSet);
		goto done;
	}

	/*
	 * get current set
	 */
	set = SCPreferencesPathGetValue(prefs, current);
	if (!set) {
		/* if error with path */
		SCLog(TRUE, LOG_ERR,
		      CFSTR("%@ value (%@) not valid"),
		      kSCPrefCurrentSet,
		      current);
		goto done;
	}

	if (!isA_CFDictionary(set)) {
		SCLog(TRUE, LOG_ERR,
		      CFSTR("updateConfiguration(): %@ is not a dictionary."),
		      current);
		goto done;
	}

	/* flatten property list */
	flatten(prefs, CFSTR("/"), set);

	CFDictionarySetValue(dict, kSCDynamicStorePropSetupCurrentSet, current);

    done :

	/* add last updated time stamp */
	CFDictionarySetValue(dict, kSCDynamicStorePropSetupLastUpdated, date);

	/* add Setup: key */
	CFDictionarySetValue(newPrefs, kSCDynamicStoreDomainSetup, dict);

	/* compare current and new preferences */
	CFDictionaryApplyFunction(newPrefs, updateCache, NULL);

	/* remove those keys which have not changed from the update */
	n = CFArrayGetCount(unchangedPrefsKeys);
	for (i = 0; i < n; i++) {
		CFStringRef	key;

		key = CFArrayGetValueAtIndex(unchangedPrefsKeys, i);
		CFDictionaryRemoveValue(newPrefs, key);
	}

	/* Update the dynamic store */
#ifndef MAIN
	if (!SCDynamicStoreSetMultiple(store, newPrefs, removedPrefsKeys, NULL)) {
		SCLog(TRUE, LOG_ERR,
		      CFSTR("SCDynamicStoreSetMultiple() failed: %s"),
		      SCErrorString(SCError()));
	}
#else	// !MAIN
	SCLog(TRUE, LOG_NOTICE,
	      CFSTR("SCDynamicStore\nset: %@\nremove: %@\n"),
	      newPrefs,
	      removedPrefsKeys);
#endif	// !MAIN

	CFRelease(currentPrefs);
	CFRelease(newPrefs);
	CFRelease(unchangedPrefsKeys);
	CFRelease(removedPrefsKeys);
	if (dict)	CFRelease(dict);
	if (date)	CFRelease(date);
	if (keys)	CFRelease(keys);
	return;
}
Beispiel #22
0
static Boolean
establishNewPreferences()
{
	CFBundleRef     bundle;
	SCNetworkSetRef	current		= NULL;
	CFStringRef	new_model;
	Boolean		ok		= FALSE;
	int		sc_status	= kSCStatusFailed;
	SCNetworkSetRef	set		= NULL;
	CFStringRef	setName		= NULL;
	Boolean		updated		= FALSE;

	while (TRUE) {
		ok = SCPreferencesLock(prefs, TRUE);
		if (ok) {
			break;
		}

		sc_status = SCError();
		if (sc_status == kSCStatusStale) {
			SCPreferencesSynchronize(prefs);
		} else {
			SCLog(TRUE, LOG_ERR,
			      CFSTR("Could not acquire network configuration lock: %s"),
			      SCErrorString(sc_status));
			return FALSE;
		}
	}

	/* Ensure that the preferences has the new model */
	new_model = _SC_hw_model(FALSE);

	/* Need to regenerate the new configuration for new model */
	if (new_model != NULL) {
		CFStringRef	old_model;

		old_model = SCPreferencesGetValue(prefs, MODEL);
		if ((old_model != NULL) && !_SC_CFEqual(old_model, new_model)) {
			CFIndex		count;
			CFIndex		index;
			CFArrayRef	keys;

			keys = SCPreferencesCopyKeyList(prefs);
			count = (keys != NULL) ? CFArrayGetCount(keys) : 0;
			// if new hardware
			for (index = 0; index < count; index++) {
				CFStringRef		existing_key;

				existing_key = CFArrayGetValueAtIndex(keys, index);
				if (isA_CFString(existing_key) != NULL) {
					CFStringRef		new_key;
					CFPropertyListRef	value;

					/* If it already contains a Model
					   or if it already contains a MODEL:KEY key skip it*/
					if (CFEqual(existing_key, MODEL)
					    || CFStringFind(existing_key, CFSTR(":"), 0).location
					    != kCFNotFound) {
						continue;
					}

					value = SCPreferencesGetValue(prefs, existing_key);

					/* Create a new key as OLD_MODEL:OLD_KEY */
					new_key = CFStringCreateWithFormat(NULL, NULL, CFSTR("%@:%@"),
									   old_model, existing_key);
					SCPreferencesSetValue(prefs, new_key, value);
					if (!CFEqual(existing_key, kSCPrefSystem)) {
						/* preserve existing host names */
						SCPreferencesRemoveValue(prefs, existing_key);
					}
					CFRelease(new_key);
				}
			}

			if (keys != NULL) {
				CFRelease(keys);
			}
		}
		/* Set the new model */
		SCPreferencesSetValue(prefs, MODEL, new_model);
	}

	current = SCNetworkSetCopyCurrent(prefs);
	if (current != NULL) {
		set = current;
	}

	if (set == NULL) {
		set = SCNetworkSetCreate(prefs);
		if (set == NULL) {
			ok = FALSE;
			sc_status = SCError();
			goto done;
		}

		bundle = _SC_CFBundleGet();
		if (bundle != NULL) {
			setName = CFBundleCopyLocalizedString(bundle,
							      CFSTR("DEFAULT_SET_NAME"),
							      CFSTR("Automatic"),
							      NULL);
		}

		ok = SCNetworkSetSetName(set, (setName != NULL) ? setName : CFSTR("Automatic"));
		if (!ok) {
			sc_status = SCError();
			goto done;
		}

		ok = SCNetworkSetSetCurrent(set);
		if (!ok) {
			sc_status = SCError();
			goto done;
		}
	}

	ok = SCNetworkSetEstablishDefaultConfiguration(set);
	if (!ok) {
		sc_status = SCError();
		goto done;
	}

    done :

	if (ok) {
		ok = SCPreferencesCommitChanges(prefs);
		if (ok) {
			SCLog(TRUE, LOG_NOTICE, CFSTR("New network configuration saved"));
			updated = TRUE;
		} else {
			sc_status = SCError();
			if (sc_status == EROFS) {
				/* a read-only fileysstem is OK */
				ok = TRUE;

				/* ... but we don't want to synchronize */
				rofs = TRUE;
			}
		}

		/* apply (committed or temporary/read-only) changes */
		(void) SCPreferencesApplyChanges(prefs);
	} else if ((current == NULL) && (set != NULL)) {
		(void) SCNetworkSetRemove(set);
	}

	if (!ok) {
		SCLog(TRUE, LOG_ERR,
		      CFSTR("Could not establish network configuration: %s"),
		      SCErrorString(sc_status));
	}

	(void)SCPreferencesUnlock(prefs);
	if (setName != NULL) CFRelease(setName);
	if (set != NULL) CFRelease(set);
	return updated;
}
Beispiel #23
0
__private_extern__
void
load_PreferencesMonitor(CFBundleRef bundle, Boolean bundleVerbose)
{
	Boolean	initPrefs	= TRUE;

	if (bundleVerbose) {
		_verbose = TRUE;
	}

	SCLog(_verbose, LOG_DEBUG, CFSTR("load() called"));
	SCLog(_verbose, LOG_DEBUG, CFSTR("  bundle ID = %@"), CFBundleGetIdentifier(bundle));

	/* open a SCDynamicStore session to allow cache updates */
	store = SCDynamicStoreCreate(NULL,
				     CFSTR("PreferencesMonitor.bundle"),
				     watchQuietCallback,
				     NULL);
	if (store == NULL) {
		SCLog(TRUE, LOG_ERR,
		      CFSTR("SCDynamicStoreCreate() failed: %s"),
		      SCErrorString(SCError()));
		goto error;
	}

	/* open a SCPreferences session */
#ifndef	MAIN
	prefs = SCPreferencesCreate(NULL, CFSTR("PreferencesMonitor.bundle"), NULL);
#else	// !MAIN
	prefs = SCPreferencesCreate(NULL, CFSTR("PreferencesMonitor.bundle"), CFSTR("/tmp/preferences.plist"));
#endif	// !MAIN
	if (prefs != NULL) {
		Boolean		need_update = FALSE;
		CFStringRef	new_model;

		new_model = _SC_hw_model(FALSE);

		/* Need to regenerate the new configuration for new model */
		if (new_model != NULL) {
			CFStringRef	old_model;

			old_model = SCPreferencesGetValue(prefs, MODEL);
			if (old_model != NULL && !_SC_CFEqual(old_model, new_model)) {
				// if new hardware
				need_update = TRUE;
			}
		}

		if (need_update == FALSE) {
			SCNetworkSetRef current;

			current = SCNetworkSetCopyCurrent(prefs);
			if (current != NULL) {
				/* network configuration available, disable template creation */
				initPrefs = FALSE;
				CFRelease(current);
			}
		}
	} else {
		SCLog(TRUE, LOG_ERR,
		      CFSTR("SCPreferencesCreate() failed: %s"),
		      SCErrorString(SCError()));
		goto error;
	}

	/*
	 * register for change notifications.
	 */
	if (!SCPreferencesSetCallback(prefs, updateConfiguration, NULL)) {
		SCLog(TRUE, LOG_ERR,
		      CFSTR("SCPreferencesSetCallBack() failed: %s"),
		      SCErrorString(SCError()));
		goto error;
	}

	if (!SCPreferencesScheduleWithRunLoop(prefs, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode)) {
		SCLog(TRUE, LOG_ERR,
		      CFSTR("SCPreferencesScheduleWithRunLoop() failed: %s"),
		      SCErrorString(SCError()));
		goto error;
	}

	/*
	 * if no preferences, initialize with a template (now or
	 * when IOKit has quiesced).
	 */
	if (initPrefs) {
		watchQuietEnable();
		watchQuietCallback(store, NULL, NULL);
	}

	return;

    error :

	watchQuietDisable();
	if (store != NULL)	CFRelease(store);
	if (prefs != NULL)	CFRelease(prefs);

	return;
}