/* IOCopyLoadAdvisoryLevelDetailed * In case of error, or inability to find system load advisory level, * returns NULL. */ CFDictionaryRef IOCopySystemLoadAdvisoryDetailed(void) { CFDictionaryRef gtDetailed = NULL; SCDynamicStoreRef storage = NULL; CFStringRef gtDetailedKey = SCDynamicStoreKeyCreate( kCFAllocatorDefault, CFSTR("%@%@"), _io_kSCDynamicStoreDomainState, kSLADetailedPath); storage = SCDynamicStoreCreate( kCFAllocatorDefault, CFSTR("IOKit IOGetSystemLoadAdvisoryDetailed"), NULL, NULL); if (!storage || !gtDetailedKey) { goto exit; } gtDetailed = SCDynamicStoreCopyValue(storage, gtDetailedKey); if(gtDetailed) { if(!isA_CFDictionary(gtDetailed)) { CFRelease(gtDetailed); gtDetailed = NULL; } } exit: if (gtDetailedKey) CFRelease(gtDetailedKey); if (storage) CFRelease(storage); return gtDetailed; }
NetworkStateNotifier::NetworkStateNotifier() : m_isOnLine(false) , m_networkStateChangeTimer(*this, &NetworkStateNotifier::networkStateChangeTimerFired) { SCDynamicStoreContext context = { 0, this, 0, 0, 0 }; m_store = adoptCF(SCDynamicStoreCreate(0, CFSTR("com.apple.WebCore"), dynamicStoreCallback, &context)); if (!m_store) return; RetainPtr<CFRunLoopSourceRef> configSource = adoptCF(SCDynamicStoreCreateRunLoopSource(0, m_store.get(), 0)); if (!configSource) return; CFRunLoopAddSource(CFRunLoopGetMain(), configSource.get(), kCFRunLoopCommonModes); RetainPtr<CFMutableArrayRef> keys = adoptCF(CFArrayCreateMutable(0, 0, &kCFTypeArrayCallBacks)); RetainPtr<CFMutableArrayRef> patterns = adoptCF(CFArrayCreateMutable(0, 0, &kCFTypeArrayCallBacks)); RetainPtr<CFStringRef> key; RetainPtr<CFStringRef> pattern; key = adoptCF(SCDynamicStoreKeyCreateNetworkGlobalEntity(0, kSCDynamicStoreDomainState, kSCEntNetIPv4)); CFArrayAppendValue(keys.get(), key.get()); pattern = adoptCF(SCDynamicStoreKeyCreateNetworkInterfaceEntity(0, kSCDynamicStoreDomainState, kSCCompAnyRegex, kSCEntNetIPv4)); CFArrayAppendValue(patterns.get(), pattern.get()); key = adoptCF(SCDynamicStoreKeyCreateNetworkGlobalEntity(0, kSCDynamicStoreDomainState, kSCEntNetDNS)); CFArrayAppendValue(keys.get(), key.get()); SCDynamicStoreSetNotificationKeys(m_store.get(), keys.get(), patterns.get()); updateState(); }
static Boolean InitDynamicStore() { Boolean success = TRUE; write_log(LOG_NOTICE, "Creating DynamicStore session."); dsSession = SCDynamicStoreCreate(NULL, CFSTR(kProgramName), ConsoleUserChangedCallbackFunction, &dsContext); if(dsSession == NULL) { write_log(LOG_ERR, "Couldn't create DynamicStore session!"); success = FALSE; goto EXIT; } write_log(LOG_NOTICE, "Creating DynamicStore RunLoop source."); dsRunLoopSource = SCDynamicStoreCreateRunLoopSource(NULL, dsSession, (CFIndex)0); if(dsRunLoopSource == NULL) { write_log(LOG_ERR, "Couldn't create DynamicStore RunLoop source!"); success = FALSE; goto EXIT; } CFRunLoopAddSource(CFRunLoopGetCurrent(), dsRunLoopSource, kCFRunLoopDefaultMode); EXIT: return success; }
HRESULT HostDnsServiceDarwin::init() { SCDynamicStoreContext ctx; RT_ZERO(ctx); ctx.info = this; m->m_store = SCDynamicStoreCreate(NULL, CFSTR("org.virtualbox.VBoxSVC"), (SCDynamicStoreCallBack)HostDnsServiceDarwin::hostDnsServiceStoreCallback, &ctx); AssertReturn(m->m_store, E_FAIL); m->m_DnsWatcher = SCDynamicStoreCreateRunLoopSource(NULL, m->m_store, 0); if (!m->m_DnsWatcher) return E_OUTOFMEMORY; int rc = RTSemEventCreate(&m->m_evtStop); AssertRCReturn(rc, E_FAIL); CFRunLoopSourceContext sctx; RT_ZERO(sctx); sctx.perform = HostDnsServiceDarwin::Data::performShutdownCallback; m->m_Stopper = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &sctx); AssertReturn(m->m_Stopper, E_FAIL); HRESULT hrc = HostDnsMonitor::init(); AssertComRCReturn(hrc, hrc); return updateInfo(); }
__private_extern__ Boolean __SCPreferencesAddSession(SCPreferencesRef prefs) { CFAllocatorRef allocator = CFGetAllocator(prefs); SCDynamicStoreContext context = { 0 , (void *)prefs , NULL , NULL , NULL }; SCPreferencesPrivateRef prefsPrivate = (SCPreferencesPrivateRef)prefs; /* establish a dynamic store session */ prefsPrivate->session = SCDynamicStoreCreate(allocator, prefsPrivate->name, prefsNotify, &context); if (prefsPrivate->session == NULL) { SCLog(_sc_verbose, LOG_INFO, CFSTR("__SCPreferencesAddSession SCDynamicStoreCreate() failed")); return FALSE; } /* create the session "commit" key */ prefsPrivate->sessionKeyCommit = _SCPNotificationKey(NULL, prefsPrivate->prefsID, kSCPreferencesKeyCommit); /* create the session "apply" key */ prefsPrivate->sessionKeyApply = _SCPNotificationKey(NULL, prefsPrivate->prefsID, kSCPreferencesKeyApply); return TRUE; }
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; }
/* * Wait until a console user logs in (or don't wait if one is already logged in). */ static bool wait_for_console_user(char *devname) { CFStringRef key; CFMutableArrayRef keys; Boolean ok; SCDynamicStoreRef store = NULL; CFRunLoopSourceRef rls; CFStringRef user; uid_t uid; gid_t gid; bool ret = false; store = SCDynamicStoreCreate(NULL, CFSTR("com.apple.nofs"), console_user_changed_cb, NULL); if (store == NULL) { return ret; } /* check if a console user is already logged in */ user = SCDynamicStoreCopyConsoleUser(store, &uid, &gid); if (user != NULL) { CFRelease(user); ret = true; goto out; } /* wait for a notification that a console user logged in */ keys = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); key = SCDynamicStoreKeyCreateConsoleUser(NULL); CFArrayAppendValue(keys, key); CFRelease(key); ok = SCDynamicStoreSetNotificationKeys(store, keys, NULL); CFRelease(keys); if (!ok) { syslog(LOG_ERR, "nofs: SCDynamicStoreSetNotificationKeys() failed"); goto out; } rls = SCDynamicStoreCreateRunLoopSource(NULL, store, -1); if (rls == NULL) { syslog(LOG_ERR, "nofs: SCDynamicStoreCreateRunLoopSource() failed"); goto out; } CFRunLoopAddSource(CFRunLoopGetCurrent(), rls, kCFRunLoopDefaultMode); CFRunLoopRun(); CFRunLoopSourceInvalidate(rls); CFRelease(rls); ret = true; out: if (store) { CFRelease(store); } return ret; }
void KprNetworkInterfaceSetup() { #if TARGET_OS_IPHONE struct sockaddr_in localWifiAddress; SCNetworkReachabilityContext context = {0, NULL, NULL, NULL, NULL}; SCNetworkReachabilityFlags flags; bzero(&localWifiAddress, sizeof(localWifiAddress)); localWifiAddress.sin_len = sizeof(localWifiAddress); localWifiAddress.sin_family = AF_INET; localWifiAddress.sin_addr.s_addr = htonl(IN_LINKLOCALNETNUM); // IN_LINKLOCALNETNUM is defined in <netinet/in.h> as 169.254.0.0 gNetworkInterfaceReachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)&localWifiAddress); SCNetworkReachabilitySetCallback(gNetworkInterfaceReachability, KprNetworkInterfaceReachabilityCallback, &context); SCNetworkReachabilityScheduleWithRunLoop(gNetworkInterfaceReachability, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode); SCNetworkReachabilityGetFlags(gNetworkInterfaceReachability, &flags); KprNetworkInterfaceReachabilityCallback(gNetworkInterfaceReachability, flags, NULL); #elif TARGET_OS_MAC FskErr err = kFskErrNone; SCDynamicStoreContext context = {0, NULL, NULL, NULL, NULL}; CFStringRef pattern = NULL; CFArrayRef patternList = NULL; pattern = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL, kSCDynamicStoreDomainState, kSCCompAnyRegex, kSCEntNetIPv4); if (!pattern) { err = kFskErrOperationFailed; goto bail; } patternList = CFArrayCreate(NULL, (const void **)&pattern, 1, &kCFTypeArrayCallBacks); if (!patternList) { err = kFskErrOperationFailed; goto bail; } gNetworkInterfaceStore = SCDynamicStoreCreate(NULL, CFSTR("KprNetWorkInterface"), KprNetworkInterfaceStoreCallback, &context); if (!gNetworkInterfaceStore) { err = kFskErrOperationFailed; goto bail; } if (!SCDynamicStoreSetNotificationKeys(gNetworkInterfaceStore, NULL, patternList)) { err = kFskErrOperationFailed; goto bail; } gNetworkInterfaceSource = SCDynamicStoreCreateRunLoopSource(NULL, gNetworkInterfaceStore, 0); if (!gNetworkInterfaceSource) { err = kFskErrOperationFailed; goto bail; } CFRunLoopAddSource(CFRunLoopGetCurrent(), gNetworkInterfaceSource, kCFRunLoopCommonModes); KprNetworkInterfaceStoreCallback(gNetworkInterfaceStore, NULL, NULL); bail: if (err != noErr) { if (gNetworkInterfaceSource) { CFRelease(gNetworkInterfaceSource); gNetworkInterfaceSource = NULL; } if (gNetworkInterfaceStore) { CFRelease(gNetworkInterfaceStore); gNetworkInterfaceStore = NULL; } } if (patternList) CFRelease(patternList); if (pattern) CFRelease(pattern); #elif TARGET_OS_WIN32 NETIOAPI_API status = NotifyIpInterfaceChange(AF_INET, &KprNetworkInterfaceCallback, NULL, TRUE, &gNetworkInterfaceHandle); #elif TARGET_OS_KPL #ifdef KPR_CONFIG KplNetInterfaceInitialize(); KplNetInterfaceSetChangedCallback(KprNetworkInterfaceCallback, 0L); KprNetworkInterfaceCallback(0); #endif #endif }
static int S_wait_all(mach_port_t server, int argc, char * argv[]) { CFMutableArrayRef keys; SCDynamicStoreRef session; CFRunLoopSourceRef rls; unsigned long t = WAIT_ALL_DEFAULT_TIMEOUT; CFPropertyListRef value; struct itimerval v; if (argc > 0) { t = strtoul(argv[0], 0, 0); if (t > WAIT_ALL_MAX_TIMEOUT) { t = WAIT_ALL_MAX_TIMEOUT; } } session = SCDynamicStoreCreate(NULL, CFSTR("ipconfig command"), key_appeared, NULL); if (session == NULL) { fprintf(stderr, "SCDynamicStoreCreate failed: %s\n", SCErrorString(SCError())); return (0); } keys = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); CFArrayAppendValue(keys, STARTUP_KEY); SCDynamicStoreSetNotificationKeys(session, keys, NULL); CFRelease(keys); rls = SCDynamicStoreCreateRunLoopSource(NULL, session, 0); CFRunLoopAddSource(CFRunLoopGetCurrent(), rls, kCFRunLoopDefaultMode); CFRelease(rls); signal(SIGALRM, on_alarm); bzero(&v, sizeof(v)); v.it_value.tv_sec = t; if (setitimer(ITIMER_REAL, &v, NULL) < 0) { perror("setitimer"); return (0); } value = SCDynamicStoreCopyValue(session, STARTUP_KEY); if (value == NULL) { CFRunLoopRun(); return (0); } CFRelease(value); CFRelease(session); return (0); }
int InstallLoginLogoutNotifiers(CFRunLoopSourceRef* RunloopSourceReturned) { SCDynamicStoreContext DynamicStoreContext = { 0, NULL, NULL, NULL, NULL }; SCDynamicStoreRef DynamicStoreCommunicationMechanism = NULL; CFStringRef KeyRepresentingConsoleUserNameChange = NULL; CFMutableArrayRef ArrayOfNotificationKeys; Boolean Result; *RunloopSourceReturned = NULL; DynamicStoreCommunicationMechanism = SCDynamicStoreCreate(NULL, CFSTR("logKext"), LoginLogoutCallBackFunction, &DynamicStoreContext); if (DynamicStoreCommunicationMechanism == NULL) return(-1); //unable to create dynamic store. KeyRepresentingConsoleUserNameChange = SCDynamicStoreKeyCreateConsoleUser(NULL); if (KeyRepresentingConsoleUserNameChange == NULL) { CFRelease(DynamicStoreCommunicationMechanism); return(-2); } ArrayOfNotificationKeys = CFArrayCreateMutable(NULL, (CFIndex)1, &kCFTypeArrayCallBacks); if (ArrayOfNotificationKeys == NULL) { CFRelease(DynamicStoreCommunicationMechanism); CFRelease(KeyRepresentingConsoleUserNameChange); return(-3); } CFArrayAppendValue(ArrayOfNotificationKeys, KeyRepresentingConsoleUserNameChange); Result = SCDynamicStoreSetNotificationKeys(DynamicStoreCommunicationMechanism, ArrayOfNotificationKeys, NULL); CFRelease(ArrayOfNotificationKeys); CFRelease(KeyRepresentingConsoleUserNameChange); if (Result == FALSE) //unable to add keys to dynamic store. { CFRelease(DynamicStoreCommunicationMechanism); return(-4); } *RunloopSourceReturned = SCDynamicStoreCreateRunLoopSource(NULL, DynamicStoreCommunicationMechanism, (CFIndex) 0); return(0); }
static CFArrayRef copyCurrentDNSServers(void) { SCDynamicStoreRef store; CFPropertyListRef propList; CFStringRef scdsRegexp; CFArrayRef retval = NULL; CFStringRef serviceID; serviceID = copyCurrentPrimaryService(); if(serviceID) { scdsRegexp = SCDynamicStoreKeyCreateNetworkServiceEntity ( kCFAllocatorDefault, kSCDynamicStoreDomainState, serviceID, kSCEntNetDNS); if(scdsRegexp) { store = SCDynamicStoreCreate(kCFAllocatorDefault, CFSTR("Network Diagnostics"), NULL, NULL); if(store) { propList = SCDynamicStoreCopyValue(store, scdsRegexp); if(propList) { retval = CFDictionaryGetValue(propList, CFSTR("ServerAddresses")); if (retval) { CFRetain(retval); } CFRelease(propList); } CFRelease(store); } CFRelease(scdsRegexp); } CFRelease(serviceID); } return retval; }
__private_extern__ void do_open(int argc, char **argv) { if (store) { CFRelease(store); CFRelease(watchedKeys); CFRelease(watchedPatterns); } if (argc < 1) { store = SCDynamicStoreCreate(NULL, CFSTR("scutil"), storeCallback, NULL); } else { CFMutableDictionaryRef options; options = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFDictionarySetValue(options, kSCDynamicStoreUseSessionKeys, kCFBooleanTrue); store = SCDynamicStoreCreateWithOptions(NULL, CFSTR("scutil"), options, storeCallback, NULL); CFRelease(options); } if (store == NULL) { SCPrint(TRUE, stdout, CFSTR(" %s\n"), SCErrorString(SCError())); return; } (void) SCDynamicStoreSetDisconnectCallBack(store, reconnected); watchedKeys = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); watchedPatterns = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); cache_close(); return; }
static CFStringRef copyCurrentPrimaryService(void) { SCDynamicStoreRef store; CFPropertyListRef propList; CFStringRef retval = NULL; store = SCDynamicStoreCreate(kCFAllocatorDefault, CFSTR("Network Diagnostics"), NULL, NULL); if(store) { propList = SCDynamicStoreCopyValue(store, CFSTR("State:/Network/Global/IPv4")); if(propList) { retval = CFDictionaryGetValue(propList, CFSTR("PrimaryService")); if (retval) { CFRetain(retval); } CFRelease(propList); } CFRelease(store); } return retval; }
static SCDynamicStoreRef config_session_start(SCDynamicStoreCallBack func, void * arg, const char * ifname) { SCDynamicStoreContext context; CFStringRef key; SCDynamicStoreRef store; bzero(&context, sizeof(context)); context.info = arg; store = SCDynamicStoreCreate(NULL, CFSTR("/usr/local/bin/eapoltest"), func, &context); if (store == NULL) { fprintf(stderr, "SCDynamicStoreCreate() failed, %s", SCErrorString(SCError())); return (NULL); } /* EAPClient status notifications */ if (ifname == NULL) { /* watch all interfaces */ CFArrayRef patterns; key = EAPOLControlAnyInterfaceKeyCreate(); patterns = CFArrayCreate(NULL, (const void **)&key, 1, &kCFTypeArrayCallBacks); CFRelease(key); SCDynamicStoreSetNotificationKeys(store, NULL, patterns); CFRelease(patterns); } else { /* watch just one interface */ CFArrayRef keys = NULL; key = EAPOLControlKeyCreate(ifname); keys = CFArrayCreate(NULL, (const void **)&key, 1, &kCFTypeArrayCallBacks); CFRelease(key); SCDynamicStoreSetNotificationKeys(store, keys, NULL); CFRelease(keys); } return (store); }
/* return AD realm if it exists */ const char *get_ad_realm ( struct auth_request *auth_request ) { const char *out_realm = NULL; SCDynamicStoreRef store = SCDynamicStoreCreate(kCFAllocatorDefault, CFSTR("dovecot.digest.auth"), NULL, NULL); if ( store ) { CFDictionaryRef dict = SCDynamicStoreCopyValue(store, CFSTR("com.apple.opendirectoryd.ActiveDirectory")); if (dict) { CFStringRef domain = CFDictionaryGetValue(dict, CFSTR("DomainNameFlat")); if (domain) { const char *ad_realm = CFStringGetCStringPtr(domain, kCFStringEncodingUTF8); if (ad_realm) { auth_request_log_info(auth_request, "digest-md5", "ad realm: %s", ad_realm); out_realm = t_strdup(ad_realm); } } CFRelease(dict); } CFRelease(store); } return( out_realm ); }
static CFRunLoopSourceRef InstallComputerNameMonitor(void) { CFRunLoopSourceRef runLoopSource = NULL; SCDynamicStoreContext context = { 0, NULL, NULL, NULL, NULL }; SCDynamicStoreRef store = SCDynamicStoreCreate(NULL, CFSTR("DirectoryService"), ComputerNameChangedCallBack, &context); if (store) { CFStringRef computerNameKey = SCDynamicStoreKeyCreateComputerName(NULL); CFMutableArrayRef keys = CFArrayCreateMutable(NULL, 1, &kCFTypeArrayCallBacks); CFArrayAppendValue(keys, computerNameKey); if (SCDynamicStoreSetNotificationKeys(store, keys, NULL)) { runLoopSource = SCDynamicStoreCreateRunLoopSource(NULL, store, 0); if (runLoopSource) { CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopCommonModes); } } CFRelease(computerNameKey); CFRelease(keys); CFRelease(store); } return runLoopSource; }
HRESULT HostDnsServiceDarwin::init(const VirtualBox *aParent) { SCDynamicStoreContext ctx; RT_ZERO(ctx); ctx.info = this; g_store = SCDynamicStoreCreate(NULL, CFSTR("org.virtualbox.VBoxSVC"), (SCDynamicStoreCallBack)HostDnsServiceDarwin::hostDnsServiceStoreCallback, &ctx); AssertReturn(g_store, E_FAIL); g_DnsWatcher = SCDynamicStoreCreateRunLoopSource(NULL, g_store, 0); if (!g_DnsWatcher) return E_OUTOFMEMORY; HRESULT hrc = HostDnsService::init(aParent); AssertComRCReturn(hrc, hrc); int rc = RTSemEventCreate(&g_DnsInitEvent); AssertRCReturn(rc, E_FAIL); return update(); }
IOReturn CreatePowerManagerUPSEntry(UPSDataRef upsDataRef, CFDictionaryRef properties, CFSetRef capabilities) { CFMutableDictionaryRef upsStoreDict = NULL; CFStringRef upsName = NULL; CFStringRef transport = NULL; CFStringRef upsStoreKey = NULL; CFNumberRef number = NULL; SCDynamicStoreRef upsStore = NULL; IOReturn status = kIOReturnSuccess; int elementValue = 0; char upsLabelString[kInternalUPSLabelLength]; if ( !upsDataRef || !properties || !capabilities) return kIOReturnError; upsStoreDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); // Set some Store values if ( upsStoreDict ) { // We need to save a name for this device. First, try to see if we have a USB Product Name. If // that fails then use the manufacturer and if that fails, then use a generic name. Couldn't we use // a serial # here? // upsName = (CFStringRef) CFDictionaryGetValue( properties, CFSTR( kIOPSNameKey ) ); if ( !upsName ) upsName = CFSTR(kDefaultUPSName); transport = (CFStringRef) CFDictionaryGetValue( properties, CFSTR( kIOPSTransportTypeKey ) ); CFDictionarySetValue(upsStoreDict, CFSTR(kIOPSNameKey), upsName); CFDictionarySetValue(upsStoreDict, CFSTR(kIOPSTransportTypeKey), transport); CFDictionarySetValue(upsStoreDict, CFSTR(kIOPSIsPresentKey), kCFBooleanTrue); CFDictionarySetValue(upsStoreDict, CFSTR(kIOPSIsChargingKey), kCFBooleanTrue); CFDictionarySetValue(upsStoreDict, CFSTR(kIOPSPowerSourceStateKey), CFSTR(kIOPSACPowerValue)); number = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &upsDataRef->upsID); CFDictionarySetValue(upsStoreDict, CFSTR(kIOPSPowerSourceIDKey), number); CFRelease(number); elementValue = 100; number = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &elementValue); CFDictionarySetValue(upsStoreDict, CFSTR(kIOPSMaxCapacityKey), number); CFRelease(number); if (CFSetContainsValue(capabilities, CFSTR(kIOPSCurrentCapacityKey))) { // Initialize kIOPSCurrentCapacityKey // // For Power Manager, we will be sharing capacity with Power Book battery capacities, so // we want a consistent measure. For now we have settled on percentage of full capacity. // elementValue = 100; number = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &elementValue); CFDictionarySetValue(upsStoreDict, CFSTR(kIOPSCurrentCapacityKey), number); CFRelease(number); } if (CFSetContainsValue(capabilities, CFSTR(kIOPSTimeToEmptyKey))) { // Initialize kIOPSTimeToEmptyKey (OS 9 PowerClass.c assumed 100 milliwatt-hours) // elementValue = 100; number = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &elementValue); CFDictionarySetValue(upsStoreDict, CFSTR(kIOPSTimeToEmptyKey), number); CFRelease(number); } if (CFSetContainsValue(capabilities, CFSTR(kIOPSVoltageKey))) { // Initialize kIOPSVoltageKey (OS 9 PowerClass.c assumed millivolts. // (Shouldn't that be 130,000 millivolts for AC?)) // Actually, Power Devices Usage Tables say units will be in Volts. // However we have to check what exponent is used because that may // make the value we get in centiVolts (exp = -2). So it looks like // OS 9 sources said millivolts, but used centivolts. Our final // answer should device by proper exponent to get back to Volts. // elementValue = 13 * 1000 / 100; number = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &elementValue); CFDictionarySetValue(upsStoreDict, CFSTR(kIOPSVoltageKey), number); CFRelease(number); } if (CFSetContainsValue(capabilities, CFSTR(kIOPSCurrentKey))) { // Initialize kIOPSCurrentKey (What would be a good amperage to // initialize to?) Same discussion as for Volts, where the unit // for current is Amps. But with typical exponents (-2), we get // centiAmps. Hmm... typical current for USB may be 500 milliAmps, // which would be .5 A. Since that is not an integer, that may be // why our displays get larger numbers // elementValue = 1; // Just a guess! number = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &elementValue); CFDictionarySetValue(upsStoreDict, CFSTR(kIOPSCurrentKey), number); CFRelease(number); } } upsStore = SCDynamicStoreCreate(kCFAllocatorDefault, CFSTR("UPS Power Manager"), NULL, NULL); // Uniquely name each Sys Config key // snprintf(upsLabelString, kInternalUPSLabelLength, "/UPS%d", upsDataRef->upsID); #if 0 SCLog(TRUE, LOG_NOTICE, CFSTR("What does CreatePowerManagerUPSEntry think our key name is?")); SCLog(TRUE, LOG_NOTICE, CFSTR(" %@%@%@"), kSCDynamicStoreDomainState, CFSTR(kIOPSDynamicStorePath), CFStringCreateWithCStringNoCopy(NULL, upsLabelString, kCFStringEncodingMacRoman, kCFAllocatorNull)); #endif CFStringRef upsLabelCF = NULL; upsLabelCF = CFStringCreateWithCStringNoCopy(NULL, upsLabelString, kCFStringEncodingMacRoman, kCFAllocatorNull); if (upsLabelCF) { upsStoreKey = SCDynamicStoreKeyCreate(kCFAllocatorDefault, CFSTR("%@%@%@"), kSCDynamicStoreDomainState, CFSTR(kIOPSDynamicStorePath), upsLabelCF); CFRelease(upsLabelCF); } if(!upsStoreKey || !SCDynamicStoreSetValue(upsStore, upsStoreKey, upsStoreDict)) { status = SCError(); #if UPS_DEBUG SCLog(TRUE, LOG_NOTICE, CFSTR("UPSSupport: Encountered SCDynamicStoreSetValue error 0x%x"), status); #endif } if (kIOReturnSuccess == status) { // Store our SystemConfiguration variables in our private data // upsDataRef->upsStoreDict = upsStoreDict; upsDataRef->upsStore = upsStore; upsDataRef->upsStoreKey = upsStoreKey; } else { if (upsStoreDict) CFRelease(upsStoreDict); if (upsStore) CFRelease(upsStore); if (upsStoreKey) CFRelease(upsStoreKey); } return status; }
static void SetInterfaceChangedObserver_MacDesktop(OsContext* aContext, InterfaceListChanged aCallback, void* aArg) { SCDynamicStoreContext context = {0, NULL, NULL, NULL, NULL}; CFStringRef pattern = NULL; CFArrayRef patternList = NULL; CFRunLoopRef runLoop = NULL; if (NULL != aContext->iInterfaceChangedObserver) { return; } aContext->iInterfaceChangedObserver = (InterfaceChangedObserver*)malloc(sizeof(*(aContext->iInterfaceChangedObserver))); if (NULL == aContext->iInterfaceChangedObserver) { goto Error; } aContext->iInterfaceChangedObserver->iCallback = aCallback; aContext->iInterfaceChangedObserver->iArg = aArg; aContext->iInterfaceChangedObserver->iStore = NULL; aContext->iInterfaceChangedObserver->iRunLoopSource = NULL; context.info = aContext->iInterfaceChangedObserver; aContext->iInterfaceChangedObserver->iStore = SCDynamicStoreCreate(NULL, CFSTR("AddIPAddressListChangeCallbackSCF"), &InterfaceChangedDynamicStoreCallback, &context); if (NULL == aContext->iInterfaceChangedObserver->iStore) { goto Error; } pattern = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL, kSCDynamicStoreDomainState, kSCCompAnyRegex, kSCEntNetIPv4); if (NULL == pattern) { goto Error; } patternList = CFArrayCreate(NULL, (const void **)&pattern, 1, &kCFTypeArrayCallBacks); if (NULL == patternList) { goto Error; } if (false == SCDynamicStoreSetNotificationKeys(aContext->iInterfaceChangedObserver->iStore, NULL, patternList)) { goto Error; } aContext->iInterfaceChangedObserver->iRunLoopSource = SCDynamicStoreCreateRunLoopSource(NULL, aContext->iInterfaceChangedObserver->iStore, 0); if (NULL == aContext->iInterfaceChangedObserver->iRunLoopSource) { goto Error; } runLoop = CFRunLoopGetMain(); if (NULL == runLoop) { goto Error; } CFRunLoopAddSource(runLoop, aContext->iInterfaceChangedObserver->iRunLoopSource, kCFRunLoopCommonModes); CFRelease(pattern); CFRelease(patternList); return; Error: if (NULL != pattern) { CFRelease(pattern); } if (NULL != patternList) { CFRelease(patternList); } if (NULL != aContext->iInterfaceChangedObserver) { if (aContext->iInterfaceChangedObserver->iStore != NULL) { CFRelease(aContext->iInterfaceChangedObserver->iStore); } if (aContext->iInterfaceChangedObserver->iRunLoopSource != NULL) { CFRelease(aContext->iInterfaceChangedObserver->iRunLoopSource); } free(aContext->iInterfaceChangedObserver); aContext->iInterfaceChangedObserver = NULL; } }
void load(CFBundleRef bundle, Boolean bundleVerbose) { int so; int status; struct kev_request kev_req; CFSocketRef es; CFSocketContext context = { 0, NULL, NULL, NULL, NULL }; CFRunLoopSourceRef rls; if (bundleVerbose) { _verbose = TRUE; } SCLog(_verbose, LOG_DEBUG, CFSTR("load() called")); SCLog(_verbose, LOG_DEBUG, CFSTR(" bundle ID = %@"), CFBundleGetIdentifier(bundle)); /* open a "configd" session to allow cache updates */ store = SCDynamicStoreCreate(NULL, CFSTR("Kernel Event Monitor plug-in"), NULL, NULL); if (!store) { SCLog(TRUE, LOG_ERR, CFSTR("SCDnamicStoreCreate() failed: %s"), SCErrorString(SCError())); SCLog(TRUE, LOG_ERR, CFSTR("kernel event monitor disabled.")); return; } /* Open an event socket */ so = socket(PF_SYSTEM, SOCK_RAW, SYSPROTO_EVENT); if (so != -1) { /* establish filter to return all events */ kev_req.vendor_code = 0; kev_req.kev_class = 0; /* Not used if vendor_code is 0 */ kev_req.kev_subclass = 0; /* Not used if either kev_class OR vendor_code are 0 */ status = ioctl(so, SIOCSKEVFILT, &kev_req); if (status) { SCLog(TRUE, LOG_ERR, CFSTR("could not establish event filter, ioctl() failed: %s"), strerror(errno)); (void) close(so); so = -1; } } else { SCLog(TRUE, LOG_ERR, CFSTR("could not open event socket, socket() failed: %s"), strerror(errno)); } if (so != -1) { int yes = 1; status = ioctl(so, FIONBIO, &yes); if (status) { SCLog(TRUE, LOG_ERR, CFSTR("could not set non-blocking io, ioctl() failed: %s"), strerror(errno)); (void) close(so); so = -1; } } if (so == -1) { SCLog(TRUE, LOG_ERR, CFSTR("kernel event monitor disabled.")); CFRelease(store); return; } /* Create a CFSocketRef for the PF_SYSTEM kernel event socket */ es = CFSocketCreateWithNative(NULL, so, kCFSocketReadCallBack, eventCallback, &context); /* Create and add a run loop source for the event socket */ rls = CFSocketCreateRunLoopSource(NULL, es, 0); CFRunLoopAddSource(CFRunLoopGetCurrent(), rls, kCFRunLoopDefaultMode); CFRelease(rls); CFRelease(es); return; }
static void dnssdUpdateDNSSDName(int from_callback) /* I - Called from callback? */ { char webif[1024]; /* Web interface share name */ # ifdef __APPLE__ SCDynamicStoreRef sc; /* Context for dynamic store */ CFDictionaryRef btmm; /* Back-to-My-Mac domains */ CFStringEncoding nameEncoding; /* Encoding of computer name */ CFStringRef nameRef; /* Host name CFString */ char nameBuffer[1024]; /* C-string buffer */ # endif /* __APPLE__ */ /* * Only share the web interface and printers when non-local listening is * enabled... */ if (!DNSSDPort) { /* * Get the port we use for registrations. If we are not listening on any * non-local ports, there is no sense sharing local printers via Bonjour... */ cupsd_listener_t *lis; /* Current listening socket */ for (lis = (cupsd_listener_t *)cupsArrayFirst(Listeners); lis; lis = (cupsd_listener_t *)cupsArrayNext(Listeners)) { if (httpAddrLocalhost(&(lis->address))) continue; DNSSDPort = httpAddrPort(&(lis->address)); break; } } if (!DNSSDPort) return; /* * Get the computer name as a c-string... */ # ifdef __APPLE__ sc = SCDynamicStoreCreate(kCFAllocatorDefault, CFSTR("cupsd"), NULL, NULL); if (sc) { /* * Get the computer name from the dynamic store... */ cupsdClearString(&DNSSDComputerName); if ((nameRef = SCDynamicStoreCopyComputerName(sc, &nameEncoding)) != NULL) { if (CFStringGetCString(nameRef, nameBuffer, sizeof(nameBuffer), kCFStringEncodingUTF8)) { cupsdLogMessage(CUPSD_LOG_DEBUG, "Dynamic store computer name is \"%s\".", nameBuffer); cupsdSetString(&DNSSDComputerName, nameBuffer); } CFRelease(nameRef); } if (!DNSSDComputerName) { /* * Use the ServerName instead... */ cupsdLogMessage(CUPSD_LOG_DEBUG, "Using ServerName \"%s\" as computer name.", ServerName); cupsdSetString(&DNSSDComputerName, ServerName); } /* * Get the local hostname from the dynamic store... */ cupsdClearString(&DNSSDHostName); if ((nameRef = SCDynamicStoreCopyLocalHostName(sc)) != NULL) { if (CFStringGetCString(nameRef, nameBuffer, sizeof(nameBuffer), kCFStringEncodingUTF8)) { cupsdLogMessage(CUPSD_LOG_DEBUG, "Dynamic store host name is \"%s\".", nameBuffer); cupsdSetString(&DNSSDHostName, nameBuffer); } CFRelease(nameRef); } if (!DNSSDHostName) { /* * Use the ServerName instead... */ cupsdLogMessage(CUPSD_LOG_DEBUG, "Using ServerName \"%s\" as host name.", ServerName); cupsdSetString(&DNSSDHostName, ServerName); } /* * Get any Back-to-My-Mac domains and add them as aliases... */ cupsdFreeAliases(DNSSDAlias); DNSSDAlias = NULL; btmm = SCDynamicStoreCopyValue(sc, CFSTR("Setup:/Network/BackToMyMac")); if (btmm && CFGetTypeID(btmm) == CFDictionaryGetTypeID()) { cupsdLogMessage(CUPSD_LOG_DEBUG, "%d Back to My Mac aliases to add.", (int)CFDictionaryGetCount(btmm)); CFDictionaryApplyFunction(btmm, dnssdAddAlias, NULL); } else if (btmm) cupsdLogMessage(CUPSD_LOG_ERROR, "Bad Back to My Mac data in dynamic store!"); else cupsdLogMessage(CUPSD_LOG_DEBUG, "No Back to My Mac aliases to add."); if (btmm) CFRelease(btmm); CFRelease(sc); } else # endif /* __APPLE__ */ # ifdef HAVE_AVAHI if (DNSSDClient) { const char *host_name = avahi_client_get_host_name(DNSSDClient); const char *host_fqdn = avahi_client_get_host_name_fqdn(DNSSDClient); cupsdSetString(&DNSSDComputerName, host_name ? host_name : ServerName); if (host_fqdn) cupsdSetString(&DNSSDHostName, host_fqdn); else if (strchr(ServerName, '.')) cupsdSetString(&DNSSDHostName, ServerName); else cupsdSetStringf(&DNSSDHostName, "%s.local", ServerName); } else # endif /* HAVE_AVAHI */ { cupsdSetString(&DNSSDComputerName, ServerName); if (strchr(ServerName, '.')) cupsdSetString(&DNSSDHostName, ServerName); else cupsdSetStringf(&DNSSDHostName, "%s.local", ServerName); } /* * Then (re)register the web interface if enabled... */ if (BrowseWebIF) { if (DNSSDComputerName) snprintf(webif, sizeof(webif), "CUPS @ %s", DNSSDComputerName); else strlcpy(webif, "CUPS", sizeof(webif)); dnssdDeregisterInstance(&WebIFSrv, from_callback); dnssdRegisterInstance(&WebIFSrv, NULL, webif, "_http._tcp", "_printer", DNSSDPort, NULL, 1, from_callback); } }
/* * startKicker() * * The first argument is a dictionary representing the keys * which need to be monitored for a given "target" and what * action should be taken if a change in one of those keys * is detected. */ static void startKicker(const void *value, void *context) { CFMutableStringRef name; CFArrayRef keys; CFArrayRef patterns; kickeeRef target = CFAllocatorAllocate(NULL, sizeof(kickee), 0); SCDynamicStoreContext targetContext = { 0, (void *)target, NULL, NULL, NULL }; target->active = FALSE; target->needsKick = FALSE; target->dict = CFRetain((CFDictionaryRef)value); target->store = NULL; target->rl = NULL; target->rls = NULL; target->changedKeys = NULL; name = CFStringCreateMutableCopy(NULL, 0, CFDictionaryGetValue(target->dict, CFSTR("name"))); SCLog(TRUE, LOG_DEBUG, CFSTR("Starting kicker for %@"), name); CFStringAppend(name, CFSTR(" \"Kicker\"")); target->store = SCDynamicStoreCreate(NULL, name, kicker, &targetContext); CFRelease(name); if (!target->store) { SCLog(TRUE, LOG_NOTICE, CFSTR("SCDynamicStoreCreate() failed: %s"), SCErrorString(SCError())); goto error; } keys = isA_CFArray(CFDictionaryGetValue(target->dict, CFSTR("keys"))); patterns = isA_CFArray(CFDictionaryGetValue(target->dict, CFSTR("regexKeys"))); if (!SCDynamicStoreSetNotificationKeys(target->store, keys, patterns)) { SCLog(TRUE, LOG_NOTICE, CFSTR("SCDynamicStoreSetNotifications() failed: %s"), SCErrorString(SCError())); goto error; } target->rl = CFRunLoopGetCurrent(); target->rls = SCDynamicStoreCreateRunLoopSource(NULL, target->store, 0); if (!target->rls) { SCLog(TRUE, LOG_NOTICE, CFSTR("SCDynamicStoreCreateRunLoopSource() failed: %s"), SCErrorString(SCError())); goto error; } CFRunLoopAddSource(target->rl, target->rls, kCFRunLoopDefaultMode); return; error : CFRelease(target->dict); if (target->store) CFRelease(target->store); CFAllocatorDeallocate(NULL, target); return; }
int main(int argc, char **argv) { CFDictionaryRef entities; CFStringRef key; CFDictionaryRef newProxy = NULL; CFStringRef pattern; CFMutableArrayRef patterns; CFStringRef primary = NULL; CFMutableDictionaryRef primary_proxy = NULL; CFArrayRef service_order = NULL; CFMutableDictionaryRef service_state_dict; CFDictionaryRef setup_global_ipv4; CFDictionaryRef state_global_ipv4; SCDynamicStoreRef store; _sc_log = FALSE; _sc_verbose = (argc > 1) ? TRUE : FALSE; store = SCDynamicStoreCreate(NULL, CFSTR("TEST"), NULL, NULL); // get IPv4, IPv6, and Proxies entities patterns = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); pattern = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL, kSCDynamicStoreDomainState, kSCCompAnyRegex, kSCEntNetIPv4); CFArrayAppendValue(patterns, pattern); CFRelease(pattern); pattern = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL, kSCDynamicStoreDomainState, kSCCompAnyRegex, kSCEntNetIPv6); CFArrayAppendValue(patterns, pattern); CFRelease(pattern); pattern = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL, kSCDynamicStoreDomainSetup, kSCCompAnyRegex, kSCEntNetProxies); CFArrayAppendValue(patterns, pattern); CFRelease(pattern); pattern = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL, kSCDynamicStoreDomainState, kSCCompAnyRegex, kSCEntNetProxies); CFArrayAppendValue(patterns, pattern); CFRelease(pattern); entities = SCDynamicStoreCopyMultiple(store, NULL, patterns); CFRelease(patterns); service_state_dict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFDictionaryApplyFunction(entities, split, service_state_dict); CFRelease(entities); // get primary service ID key = SCDynamicStoreKeyCreateNetworkGlobalEntity(NULL, kSCDynamicStoreDomainState, kSCEntNetIPv4); state_global_ipv4 = SCDynamicStoreCopyValue(store, key); CFRelease(key); if (state_global_ipv4 != NULL) { primary = CFDictionaryGetValue(state_global_ipv4, kSCDynamicStorePropNetPrimaryService); if (primary != NULL) { CFDictionaryRef service_dict; // get proxy configuration for primary service service_dict = CFDictionaryGetValue(service_state_dict, primary); if (service_dict != NULL) { CFDictionaryRef service_proxy; service_proxy = CFDictionaryGetValue(service_dict, kSCEntNetProxies); if (service_proxy != NULL) { primary_proxy = CFDictionaryCreateMutableCopy(NULL, 0, service_proxy); CFDictionaryRemoveValue(primary_proxy, kSCPropInterfaceName); } } } } // get serviceOrder key = SCDynamicStoreKeyCreateNetworkGlobalEntity(NULL, kSCDynamicStoreDomainSetup, kSCEntNetIPv4); setup_global_ipv4 = SCDynamicStoreCopyValue(store, key); CFRelease(key); if (setup_global_ipv4 != NULL) { service_order = CFDictionaryGetValue(setup_global_ipv4, kSCPropNetServiceOrder); } // update proxy configuration proxy_configuration_init(CFBundleGetMainBundle()); newProxy = proxy_configuration_update(primary_proxy, service_state_dict, service_order, NULL); if (newProxy != NULL) { SCPrint(TRUE, stdout, CFSTR("%@\n"), newProxy); CFRelease(newProxy); } // cleanup if (setup_global_ipv4 != NULL) CFRelease(setup_global_ipv4); if (state_global_ipv4 != NULL) CFRelease(state_global_ipv4); CFRelease(service_state_dict); CFRelease(store); /* not reached */ exit(0); return 0; }
void PcapLiveDeviceList::setDnsServers() { #ifdef WIN32 FIXED_INFO * fixedInfo; ULONG ulOutBufLen; DWORD dwRetVal; IP_ADDR_STRING * pIPAddr; uint8_t buf1[sizeof(FIXED_INFO)]; fixedInfo = (FIXED_INFO *) buf1; ulOutBufLen = sizeof( FIXED_INFO ); dwRetVal = GetNetworkParams( fixedInfo, &ulOutBufLen ); uint8_t buf2[ulOutBufLen]; if(ERROR_BUFFER_OVERFLOW == dwRetVal) { fixedInfo = (FIXED_INFO *)buf2; } if ((dwRetVal = GetNetworkParams( fixedInfo, &ulOutBufLen )) != 0) LOG_ERROR("Call to GetNetworkParams failed. Return Value: %08lx\n", dwRetVal); else { m_DnsServers.push_back(IPv4Address(fixedInfo->DnsServerList.IpAddress.String)); int i = 1; LOG_DEBUG("Default DNS server IP #%d: %s\n", i++, fixedInfo->DnsServerList.IpAddress.String ); pIPAddr = fixedInfo->DnsServerList.Next; while ( pIPAddr ) { m_DnsServers.push_back(IPv4Address(pIPAddr->IpAddress.String)); LOG_DEBUG("Default DNS server IP #%d: %s\n", i++, pIPAddr->IpAddress.String); pIPAddr = pIPAddr -> Next; } } #elif LINUX std::string command = "nmcli dev list | grep IP4.DNS"; std::string dnsServersInfo = executeShellCommand(command); if (dnsServersInfo == "") { LOG_DEBUG("Error retrieving DNS server list: call to nmcli gave no output"); return; } std::istringstream stream(dnsServersInfo); std::string line; int i = 1; while(std::getline(stream, line)) { std::istringstream lineStream(line); std::string headline; std::string dnsIP; lineStream >> headline; lineStream >> dnsIP; IPv4Address dnsIPAddr(dnsIP); if (!dnsIPAddr.isValid()) continue; if (std::find(m_DnsServers.begin(), m_DnsServers.end(), dnsIPAddr) == m_DnsServers.end()) { m_DnsServers.push_back(dnsIPAddr); LOG_DEBUG("Default DNS server IP #%d: %s\n", i++, dnsIPAddr.toString().c_str()); } } #elif MAC_OS_X SCDynamicStoreRef dynRef = SCDynamicStoreCreate(kCFAllocatorSystemDefault, CFSTR("iked"), NULL, NULL); if (dynRef == NULL) { LOG_DEBUG("Couldn't set DNS server list: failed to retrieve SCDynamicStore"); return; } CFDictionaryRef dnsDict = (CFDictionaryRef)SCDynamicStoreCopyValue(dynRef,CFSTR("State:/Network/Global/DNS")); if (dnsDict == NULL) { LOG_DEBUG("Couldn't set DNS server list: failed to get DNS dictionary"); CFRelease(dynRef); return; } CFArrayRef serverAddresses = (CFArrayRef)CFDictionaryGetValue(dnsDict, CFSTR("ServerAddresses")); if (serverAddresses == NULL) { LOG_DEBUG("Couldn't set DNS server list: server addresses array is null"); CFRelease(dynRef); CFRelease(dnsDict); return; } CFIndex count = CFArrayGetCount(serverAddresses); for (CFIndex i = 0; i < count; i++) { CFStringRef serverAddress = (CFStringRef)CFArrayGetValueAtIndex(serverAddresses, i); if (serverAddress == NULL) continue; uint8_t buf[20]; char* serverAddressCString = (char*)buf; CFStringGetCString(serverAddress, serverAddressCString, 20, kCFStringEncodingUTF8); m_DnsServers.push_back(IPv4Address(serverAddressCString)); LOG_DEBUG("Default DNS server IP #%d: %s\n", (int)(i+1), serverAddressCString); } CFRelease(dynRef); CFRelease(dnsDict); #endif }
static OSStatus CreateIPAddressListChangeCallbackSCF(SCDynamicStoreCallBack callback, void *contextPtr, SCDynamicStoreRef *storeRef, CFRunLoopSourceRef *sourceRef) // Create a SCF dynamic store reference and a // corresponding CFRunLoop source. If you add the // run loop source to your run loop then the supplied // callback function will be called when local IP // address list changes. { OSStatus err = 0; SCDynamicStoreContext context = {0, NULL, NULL, NULL, NULL}; SCDynamicStoreRef ref; CFStringRef pattern; CFArrayRef patternList; CFRunLoopSourceRef rls; assert(callback != NULL); assert( storeRef != NULL); assert(*storeRef == NULL); assert( sourceRef != NULL); assert(*sourceRef == NULL); ref = NULL; pattern = NULL; patternList = NULL; rls = NULL; // Create a connection to the dynamic store, then create // a search pattern that finds all IPv4 entities. // The pattern is "State:/Network/Service/[^/]+/IPv4". context.info = contextPtr; ref = SCDynamicStoreCreate( NULL, CFSTR("AddIPAddressListChangeCallbackSCF"), callback, &context); //err = MoreSCError(ref); if (err == noErr) { pattern = SCDynamicStoreKeyCreateNetworkServiceEntity( NULL, kSCDynamicStoreDomainState, kSCCompAnyRegex, kSCEntNetIPv4); //err = MoreSCError(pattern); } // Create a pattern list containing just one pattern, // then tell SCF that we want to watch changes in keys // that match that pattern list, then create our run loop // source. if (err == noErr) { patternList = CFArrayCreate(NULL, (const void **) &pattern, 1, &kCFTypeArrayCallBacks); //err = CFQError(patternList); } if (err == noErr) { //err = MoreSCErrorBoolean( SCDynamicStoreSetNotificationKeys( ref, NULL, patternList); // ); } if (err == noErr) { rls = SCDynamicStoreCreateRunLoopSource(NULL, ref, 0); //err = MoreSCError(rls); } CFRunLoopAddSource(CFRunLoopGetCurrent(), rls, kCFRunLoopDefaultMode); // Clean up. //CFQRelease(pattern); //CFQRelease(patternList); if (err != noErr) { //CFQRelease(ref); ref = NULL; } *storeRef = ref; *sourceRef = rls; assert( (err == noErr) == (*storeRef != NULL) ); assert( (err == noErr) == (*sourceRef != NULL) ); return err; }
//----------------------------------------------------------------------------- // open_dynamic_store //----------------------------------------------------------------------------- void open_dynamic_store(struct vpn_params* params) { params->storeRef = SCDynamicStoreCreate(0, CFSTR("vpnd"), 0, 0); }
/* Main program */ int main (int argc, const char * argv[]) { enum suspend_type {soft, dump, hard}; int vmmib[2] = {CTL_VM, VM_SWAPUSAGE}; int osmib[2] = {CTL_KERN, KERN_OSRELEASE}; int original_mode; int target_mode; int default_mode; int original_profile; int target_profile = -1; void *refCon; struct xsw_usage swap; size_t swlen = sizeof(swap); size_t oslen; char *kernel_version; int major_version = 0; int minor_version = 0; struct stat sleepimage; /* By default, */ int do_sleep = 1; /* send the sleep call, */ int repair = 0; /* do not check the validity of the original hibernation mode, */ int check_hibernation = 1; /* check if the hibernation file is present, */ int check_os = 1; /* check if the operating system is supported, */ enum suspend_type target_suspend = soft; /* send computer to software suspend mode, */ int restore = 1; /* restore the original mode, */ if (argc >= 2) { if (!strcmp(argv[1], "-v")) { /* Display version number if invoked with -v */ printf("deepsleep build %s\n", VERSION); return 0; } else if (!strcmp(argv[1], "-h")) { printf("deepsleep usage: deepsleep [-bdhrvsu] [hard|dump|soft]\n"); printf(" -b : bypass the hibernation file check\n"); printf(" -d : debug mode - be verbose\n"); printf(" -h : display this help screen\n"); printf(" -m : mute - be silent\n"); printf(" -o : do not restore the original hibernation mode\n"); printf(" -r : repair the default hibernation mode if needed\n"); printf(" -s : simulation - do not send the computer to sleep\n"); printf(" -v : display version number\n"); printf(" -u : perform operations even on unsupported OS revisions\n"); printf(" hard : send computer to hardware suspend mode\n"); printf(" dump : send computer to safe hardware suspend mode\n"); printf(" soft : send computer to software suspend mode (by default)\n"); return 0; } else { if (argc >= 3) { if (strstr(argv[1], "b")) /* Do not check the existence of the hibernation file if invoked with -b */ check_hibernation = 0; if (strstr(argv[1], "d")) /* Print debug information if invoked with -d */ debug = 1; if (strstr(argv[1], "o")) /* Do not restore the original hibernation mode if invoked with -o */ restore = 0; if (strstr(argv[1], "r")) /* Check for the validity of the original hibernation mode if invoked with -r*/ repair = 1; if (strstr(argv[1], "s")) /* Do not send the sleep call if invoked with -s */ do_sleep = 0; if (strstr(argv[1], "u")) /* Do not care about OS revision if invoked with -u */ check_os = 0; if (strstr(argv[1], "m")) mute = 1; } if (strstr(argv[argc-1], "hard")) /* Send computer to hardware suspend mode instead of software suspend mode if the hard argument is present */ target_suspend = hard; else if (strstr(argv[argc-1], "dump")) /* Send computer to safe hardware suspend mode instead of software suspend mode if the safe argument is present */ target_suspend = dump; } } if (sysctl(osmib, 2, NULL, &oslen, NULL, 0) == -1) { /* Get the operating system revision length */ printf("Failed to get the operating system revision\n"); /* On failure: quit */ return 1; } else { kernel_version = malloc(oslen * sizeof(char)); sysctl(osmib, 2, kernel_version, &oslen, NULL, 0); /* Get the operating system revision length */ sscanf(kernel_version, "%d.%d", &major_version, &minor_version); free(kernel_version); } if (debug) { printf("OS revision: %d.%d", major_version, minor_version); if (!check_os) printf(" (ignored)"); printf("\n"); } if (check_os && (major_version != 8 || minor_version < 3) && (major_version <= 8)) { /* If needed, check if major version is 8 (Mac OS X 10.4) and minor version is greater or equal than 3. Mac OS X 10.5 is also supported.*/ printf("This operating system is not supported\n"); /* On failure: quit */ return 1; } if (check_hibernation && stat("/private/var/vm/sleepimage", &sleepimage)) { /* If needed, check if the hibernation file (/private/var/vm/sleepimage) exists */ printf("Hibernation file is missing\n"); /* On failure: quit */ return 1; } if (sysctl(vmmib, 2, &swap, &swlen, NULL, 0) == -1) { /* Get the current virtual memory parameters */ printf("Failed to get the virtual memory information\n"); /* On failure: quit */ return 1; } else { default_mode = 3; if (target_suspend == dump) { target_mode = default_mode; /* we will use the regular mode 3 for safe hardware suspsend */ } else /*if (target_suspend == soft)*/ { target_mode = 25; /* or the regular mode 25 for software suspsend */ } if (target_suspend == hard) /* If we only want to perform basic hardware suspend */ target_mode = 0; /* we will sleep with hibernate mode 0 */ if (debug) printf("target mode: %d\n", target_mode); } ps_info = IOPSCopyPowerSourcesInfo(); /* Get the power source information */ if (ps_info) { current_ps = IOPSGetProvidingPowerSourceType(ps_info); /* On success, store the active power source */ } else { printf("Failed to get the power source information\n"); /* On failure: quit */ return 1; } if (debug) printf("target power source: %s\n", CFStringGetCStringPtr(current_ps, kCFStringEncodingMacRoman)); active_prof = IOPMCopyActivePowerProfiles(); /* Get the power profiles */ if (!active_prof) { printf("Failed to get the active profile\n"); CFCleanup(); return 1; } if (CFDictionaryContainsKey(active_prof, current_ps)) { /* Get the active profile corresponding to the current power source */ profile_ref = (CFNumberRef) CFDictionaryGetValue(active_prof, current_ps); profile_type = CFNumberGetType(profile_ref); CFNumberGetValue(profile_ref, profile_type, &original_profile); /* On succes, store its value */ if (debug) printf("original profile: %d\n", original_profile); } else { printf("Failed to get the power management settings\n"); /* On failure: quit */ CFCleanup(); return 1; } ds = SCDynamicStoreCreate(NULL, CFSTR("deepsleep"), NULL, NULL); /* Create a new dynamic store */ live_settings = SCDynamicStoreCopyValue(ds, CFSTR(kIOPMDynamicStoreSettingsKey)); /* Read current settings */ if(!isA_CFDictionary(live_settings)) { /* We did not get the settings: quit */ printf("Failed to get the power management settings\n"); CFCleanup(); return 1; } if (CFDictionaryContainsKey(live_settings, CFSTR("Hibernate Mode"))) { /* Check if the hibernate mode key exists */ hm_ref = (CFNumberRef) CFDictionaryGetValue(live_settings, CFSTR("Hibernate Mode")); /* On success, get its value */ hm_type = CFNumberGetType(hm_ref); CFNumberGetValue(hm_ref, hm_type, &original_mode); if (debug) printf("original mode: %d\n", original_mode); } else { /* On failure, cleanup and quit */ printf("Failed to get the hibernation mode\n"); CFCleanup(); return 1; } if (repair && original_mode == target_mode) { /* If the original mode is the same as the target mode */ original_mode = default_mode; /* A crash has probably happened during hibernation: we will set back the hibernation mode to its default value after wakeup */ if (debug) printf("repair mode to: %d\n", default_mode); } root_power_port = IORegisterForSystemPower(refCon, ¬ifyPortRef, PowerCallBack, ¬ifierObject); /* Register to the Root Power Domain IOService: notifications will be handled by the PowerCallBack functions */ if (!root_power_port) { /* Registering failed: quit */ printf("Failed to register to the Root Power Domain IOService\n"); CFCleanup(); return 1; } CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(notifyPortRef), kCFRunLoopCommonModes); /* Add the notification port to the run loop */ if (SetActiveProfile(target_profile, current_ps, active_prof)) { /* Set the active power profile to custom (-1) */ printf("Failed to set the active profile\n"); PortsCleanup(); CFCleanup(); return 1; } if (SetHibernateMode(target_mode, current_ps)) { /* Set the hibernate mode to target mode */ printf("Failed to set the hibernation mode\n"); SetActiveProfile(original_profile, current_ps, active_prof); PortsCleanup(); CFCleanup(); return 1; } if (do_sleep) { /* If we are not in simulation mode */ sleep(3); /* Wait for 3s to allow settings to settle down */ if (IOPMSleepSystem(root_power_port) == kIOReturnSuccess) /* Request the system to sleep */ CFRunLoopRun(); /* On success, start the run loop */ else perror("Failed to send the sleep request\n"); /* On failure, do not start it */ } /* The run loop has stopped: system has woken up */ if (restore) { /* If we are asked to restore the original hibernate mode */ if (SetHibernateMode(original_mode, current_ps)) { /* Restore the original hibernate mode */ printf("Failed to set the hibernation mode\n"); SetActiveProfile(original_profile, current_ps, active_prof); PortsCleanup(); CFCleanup(); return 1; } if (SetActiveProfile(original_profile, current_ps, active_prof)) { /* Restore the original power profile */ printf("Failed to set the active profile\n"); PortsCleanup(); CFCleanup(); return 1; } } PortsCleanup(); /* Cleanup */ CFCleanup(); return 0; }
CFNetDiagnosticStatus CFNetDiagnosticCopyNetworkStatusPassively(CFNetDiagnosticRef details, CFStringRef *description) { CFMutableDictionaryRef detailsDict = (CFMutableDictionaryRef)details; CFNetDiagnosticStatus retval = kCFNetDiagnosticConnectionIndeterminate; CFStringRef serviceID; SCDynamicStoreRef store; store = SCDynamicStoreCreate(kCFAllocatorDefault, CFSTR("CFNetDiagnostics"), NULL, NULL); if(store) { serviceID = CFDictionaryGetValue(detailsDict, _CFNetDiagnosticServiceIDKey); if(serviceID) { //If there is a specific ServiceID we only scan on it. We can only get in this position through SPIs retval = _CFNetDiagnosticCopyNetworkStatusPassivelyInterfaceSpecific(store, serviceID, description); } else { //Iterate through all serviceIDs. If any are good, then we return it CFStringRef pattern = NULL; CFDictionaryRef dict = NULL; CFArrayRef serviceOrder = NULL; CFIndex i, count; CFNetDiagnosticStatus serviceState = kCFNetDiagnosticConnectionDown; pattern = SCDynamicStoreKeyCreateNetworkGlobalEntity( NULL, (CFStringRef) kSCDynamicStoreDomainSetup, (CFStringRef) kSCEntNetIPv4 ); if(pattern) { dict = SCDynamicStoreCopyValue( store, pattern ); CFRelease( pattern ); } if(dict) { serviceOrder = CFDictionaryGetValue(dict, CFSTR("ServiceOrder")); CFRetain(serviceOrder); CFRelease(dict); } if(serviceOrder) { count = CFArrayGetCount(serviceOrder); retval = kCFNetDiagnosticConnectionDown; for ( i = 0; i < count; i++ ) { serviceID = CFArrayGetValueAtIndex(serviceOrder, i); serviceState = _CFNetDiagnosticCopyNetworkStatusPassivelyInterfaceSpecific(store, serviceID, description); if(serviceState == kCFNetDiagnosticConnectionDown) { retval = kCFNetDiagnosticConnectionDown; if (description) { *description = CFCopyLocalizedStringFromTableInBundle( CFSTR("CONNECTION_DOWN"), NULL, CFBundleGetBundleWithIdentifier(CFSTR("com.apple.CFNetwork")), "This computer's Internet connect appears to be offline."); } } else if (serviceState == kCFNetDiagnosticConnectionIndeterminate) { retval = kCFNetDiagnosticConnectionIndeterminate; if (description) { *description = CFCopyLocalizedStringFromTableInBundle( CFSTR("CONNECTION_INDETERMINATE"), NULL, CFBundleGetBundleWithIdentifier(CFSTR("com.apple.CFNetwork")), "This computer's Internet may be offline."); } } else if (serviceState == kCFNetDiagnosticConnectionUp) { retval = kCFNetDiagnosticConnectionUp; if (description) { *description = CFCopyLocalizedStringFromTableInBundle( CFSTR("CONNECTION_UP"), NULL, CFBundleGetBundleWithIdentifier(CFSTR("com.apple.CFNetwork")), "This computer's Internet may be online."); } break; } else { //FIXME //NOT REACHED log an error } } CFRelease(serviceOrder); } } CFRelease(store); } return retval; }
__private_extern__ void load_smb_configuration(Boolean verbose) { CFStringRef key; CFMutableArrayRef keys = NULL; dispatch_block_t notify_block; Boolean ok; CFMutableArrayRef patterns = NULL; uint32_t status; /* initialize a few globals */ store = SCDynamicStoreCreate(NULL, CFSTR("smb-configuration"), configuration_changed, NULL); if (store == NULL) { my_log(LOG_ERR, "SCDynamicStoreCreate() failed: %s", SCErrorString(SCError())); goto error; } /* establish notification keys and patterns */ keys = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); patterns = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); /* ...watch for SMB configuration changes */ key = SCDynamicStoreKeyCreateNetworkGlobalEntity(NULL, kSCDynamicStoreDomainState, kSCEntNetSMB); CFArrayAppendValue(keys, key); CFRelease(key); /* ...watch for ComputerName changes */ key = SCDynamicStoreKeyCreateComputerName(NULL); CFArrayAppendValue(keys, key); CFRelease(key); /* ...watch for local (multicast DNS) hostname changes */ key = SCDynamicStoreKeyCreateHostNames(NULL); CFArrayAppendValue(keys, key); CFRelease(key); /* register the keys/patterns */ ok = SCDynamicStoreSetNotificationKeys(store, keys, patterns); CFRelease(keys); CFRelease(patterns); if (!ok) { my_log(LOG_ERR, "SCDynamicStoreSetNotificationKeys() failed: %s", SCErrorString(SCError())); goto error; } rl = CFRunLoopGetCurrent(); rls = SCDynamicStoreCreateRunLoopSource(NULL, store, 0); if (rls == NULL) { my_log(LOG_ERR, "SCDynamicStoreCreateRunLoopSource() failed: %s", SCErrorString(SCError())); goto error; } CFRunLoopAddSource(rl, rls, kCFRunLoopDefaultMode); /* ...watch for primary service/interface and DNS configuration changes */ notify_block = ^{ CFArrayRef changes; CFStringRef key; key = SCDynamicStoreKeyCreateNetworkGlobalEntity(NULL, kSCDynamicStoreDomainState, kSCEntNetDNS); changes = CFArrayCreate(NULL, (const void **)&key, 1, &kCFTypeArrayCallBacks); (*configuration_changed)(store, changes, NULL); CFRelease(changes); CFRelease(key); return; }; status = notify_register_dispatch(_SC_NOTIFY_NETWORK_CHANGE, ¬ify_token, dispatch_get_main_queue(), ^(int token){ CFRunLoopPerformBlock(rl, kCFRunLoopDefaultMode, notify_block); CFRunLoopWakeUp(rl); });
static void * /* O - Return status/value */ sysEventThreadEntry(void) { io_object_t powerNotifierObj; /* Power notifier object */ IONotificationPortRef powerNotifierPort; /* Power notifier port */ SCDynamicStoreRef store = NULL;/* System Config dynamic store */ CFRunLoopSourceRef powerRLS = NULL,/* Power runloop source */ storeRLS = NULL;/* System Config runloop source */ CFStringRef key[6], /* System Config keys */ pattern[2]; /* System Config patterns */ CFArrayRef keys = NULL, /* System Config key array*/ patterns = NULL;/* System Config pattern array */ SCDynamicStoreContext storeContext; /* Dynamic store context */ CFRunLoopTimerContext timerContext; /* Timer context */ cupsd_thread_data_t threadData; /* Thread context data for the * * runloop notifiers */ /* * Register for power state change notifications */ bzero(&threadData, sizeof(threadData)); threadData.sysevent.powerKernelPort = IORegisterForSystemPower(&threadData, &powerNotifierPort, sysEventPowerNotifier, &powerNotifierObj); if (threadData.sysevent.powerKernelPort) { powerRLS = IONotificationPortGetRunLoopSource(powerNotifierPort); CFRunLoopAddSource(CFRunLoopGetCurrent(), powerRLS, kCFRunLoopDefaultMode); } else DEBUG_puts("sysEventThreadEntry: error registering for system power " "notifications"); /* * Register for system configuration change notifications */ bzero(&storeContext, sizeof(storeContext)); storeContext.info = &threadData; store = SCDynamicStoreCreate(kCFAllocatorDefault, CFSTR("cupsd"), sysEventConfigurationNotifier, &storeContext); if (!ComputerNameKey) ComputerNameKey = SCDynamicStoreKeyCreateComputerName(kCFAllocatorDefault); if (!BTMMKey) BTMMKey = SCDynamicStoreKeyCreate(kCFAllocatorDefault, CFSTR("Setup:/Network/BackToMyMac")); if (!NetworkGlobalKeyIPv4) NetworkGlobalKeyIPv4 = SCDynamicStoreKeyCreateNetworkGlobalEntity(kCFAllocatorDefault, kSCDynamicStoreDomainState, kSCEntNetIPv4); if (!NetworkGlobalKeyIPv6) NetworkGlobalKeyIPv6 = SCDynamicStoreKeyCreateNetworkGlobalEntity(kCFAllocatorDefault, kSCDynamicStoreDomainState, kSCEntNetIPv6); if (!NetworkGlobalKeyDNS) NetworkGlobalKeyDNS = SCDynamicStoreKeyCreateNetworkGlobalEntity(kCFAllocatorDefault, kSCDynamicStoreDomainState, kSCEntNetDNS); if (!HostNamesKey) HostNamesKey = SCDynamicStoreKeyCreateHostNames(kCFAllocatorDefault); if (!NetworkInterfaceKeyIPv4) NetworkInterfaceKeyIPv4 = SCDynamicStoreKeyCreateNetworkInterfaceEntity(kCFAllocatorDefault, kSCDynamicStoreDomainState, kSCCompAnyRegex, kSCEntNetIPv4); if (!NetworkInterfaceKeyIPv6) NetworkInterfaceKeyIPv6 = SCDynamicStoreKeyCreateNetworkInterfaceEntity(kCFAllocatorDefault, kSCDynamicStoreDomainState, kSCCompAnyRegex, kSCEntNetIPv6); if (store && ComputerNameKey && HostNamesKey && NetworkGlobalKeyIPv4 && NetworkGlobalKeyIPv6 && NetworkGlobalKeyDNS && NetworkInterfaceKeyIPv4 && NetworkInterfaceKeyIPv6) { key[0] = ComputerNameKey; key[1] = BTMMKey; key[2] = NetworkGlobalKeyIPv4; key[3] = NetworkGlobalKeyIPv6; key[4] = NetworkGlobalKeyDNS; key[5] = HostNamesKey; pattern[0] = NetworkInterfaceKeyIPv4; pattern[1] = NetworkInterfaceKeyIPv6; keys = CFArrayCreate(kCFAllocatorDefault, (const void **)key, sizeof(key) / sizeof(key[0]), &kCFTypeArrayCallBacks); patterns = CFArrayCreate(kCFAllocatorDefault, (const void **)pattern, sizeof(pattern) / sizeof(pattern[0]), &kCFTypeArrayCallBacks); if (keys && patterns && SCDynamicStoreSetNotificationKeys(store, keys, patterns)) { if ((storeRLS = SCDynamicStoreCreateRunLoopSource(kCFAllocatorDefault, store, 0)) != NULL) { CFRunLoopAddSource(CFRunLoopGetCurrent(), storeRLS, kCFRunLoopDefaultMode); } else DEBUG_printf(("sysEventThreadEntry: SCDynamicStoreCreateRunLoopSource " "failed: %s\n", SCErrorString(SCError()))); } else DEBUG_printf(("sysEventThreadEntry: SCDynamicStoreSetNotificationKeys " "failed: %s\n", SCErrorString(SCError()))); } else DEBUG_printf(("sysEventThreadEntry: SCDynamicStoreCreate failed: %s\n", SCErrorString(SCError()))); if (keys) CFRelease(keys); if (patterns) CFRelease(patterns); /* * Set up a timer to delay the wake change notifications. * * The initial time is set a decade or so into the future, we'll adjust * this later. */ bzero(&timerContext, sizeof(timerContext)); timerContext.info = &threadData; threadData.timerRef = CFRunLoopTimerCreate(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + (86400L * 365L * 10L), 86400L * 365L * 10L, 0, 0, sysEventTimerNotifier, &timerContext); CFRunLoopAddTimer(CFRunLoopGetCurrent(), threadData.timerRef, kCFRunLoopDefaultMode); /* * Store our runloop in a global so the main thread can use it to stop us. */ pthread_mutex_lock(&SysEventThreadMutex); SysEventRunloop = CFRunLoopGetCurrent(); pthread_cond_signal(&SysEventThreadCond); pthread_mutex_unlock(&SysEventThreadMutex); /* * Disappear into the runloop until it's stopped by the main thread. */ CFRunLoopRun(); /* * Clean up before exiting. */ if (threadData.timerRef) { CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), threadData.timerRef, kCFRunLoopDefaultMode); CFRelease(threadData.timerRef); } if (threadData.sysevent.powerKernelPort) { CFRunLoopRemoveSource(CFRunLoopGetCurrent(), powerRLS, kCFRunLoopDefaultMode); IODeregisterForSystemPower(&powerNotifierObj); IOServiceClose(threadData.sysevent.powerKernelPort); IONotificationPortDestroy(powerNotifierPort); } if (storeRLS) { CFRunLoopRemoveSource(CFRunLoopGetCurrent(), storeRLS, kCFRunLoopDefaultMode); CFRunLoopSourceInvalidate(storeRLS); CFRelease(storeRLS); } if (store) CFRelease(store); pthread_exit(NULL); }