bool FileManager::mkdir(const URL &sDir) { if (!sDir.isAbsolutePath()) { SCError("cannot mkdir: %s", sDir.c_str()); return false; } URL dir(sDir); dir.trim(); if (dir.empty() || isExists(dir)) { return true; } // create upper directory if (!mkdir(URL(dir).deleteLastPathComponent())) { SCError("failed to create upper dir: %s", sDir.c_str()); return false; } if (mkdir_(dir)) { return true; } else { SCError("failed to mkdir: %s", dir.c_str()); return false; } }
bool FileManager::move(const URL &sSourcePath, const URL &sTargetPath) { if (!isExists(sSourcePath) || !isWritable(URL(sTargetPath).deleteLastPathComponent())) { SCError("cannot move file %s to %s", sSourcePath.c_str(), sTargetPath.c_str()); return false; } if (rename(sSourcePath.c_str(), sTargetPath.c_str()) == 0) { return true; } SCLog("cannot rename %s to %s, try copying...", sSourcePath.c_str(), sTargetPath.c_str()); // cannot rename, try copy if (!copy(sSourcePath, sTargetPath)) { SCError("failed to copy file %s to %s", sSourcePath.c_str(), sTargetPath.c_str()); return false; } if (!remove(sSourcePath)) { SCWarning("cannot remove old file: %s", sSourcePath.c_str()); return false; } return true; }
static Boolean ensure_unique_service_name(SCNetworkServiceRef service) { SCNetworkInterfaceRef interface; CFStringRef name; Boolean ok = TRUE; interface = SCNetworkServiceGetInterface(service); name = SCNetworkServiceGetName(service); if (name != NULL) { CFRetain(name); } while (TRUE) { CFStringRef newName; ok = SCNetworkServiceSetName(service, name); if (ok) { break; } if (SCError() != kSCStatusKeyExists) { SC_log(LOG_INFO, "could not update service name for \"%@\": %s", SCNetworkInterfaceGetLocalizedDisplayName(interface), SCErrorString(SCError())); break; } newName = copy_next_name(name); if (newName == NULL) { SC_log(LOG_INFO, "could not create unique name for \"%@\": %s", SCNetworkInterfaceGetLocalizedDisplayName(interface), SCErrorString(SCError())); break; } // try again with the "new" name if (name != NULL) { CFRelease(name); } name = newName; } if (name != NULL) { CFRelease(name); } return ok; }
__private_extern__ void enable_service(int argc, char **argv) { SCNetworkServiceRef service; if (argc == 1) { service = _find_service(argv[0]); } else { if (net_service != NULL) { service = net_service; } else { SCPrint(TRUE, stdout, CFSTR("service not selected\n")); return; } } if (service == NULL) { return; } if (!SCNetworkServiceSetEnabled(service, TRUE)) { SCPrint(TRUE, stdout, CFSTR("%s\n"), SCErrorString(SCError())); return; } _prefs_changed = TRUE; return; }
bool FileManager::remove(const URL &sFilePath) { if (!isExists(sFilePath) || !isWritable(URL(sFilePath).deleteLastPathComponent())) { SCError("cannot remove file: %s", sFilePath.c_str()); return false; } if (unlink(sFilePath.c_str()) == 0) { return true; } else { SCError("failed to remove file: %s", sFilePath.c_str()); return false; } }
/* ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- */ static void nc_select(int argc, char **argv) { SCNetworkSetRef current_set; int exit_code = 1; SCNetworkServiceRef service = NULL; Boolean status; do_prefs_init(); /* initialization */ do_prefs_open(0, NULL); /* open default prefs */ current_set = SCNetworkSetCopyCurrent(prefs); if (current_set == NULL) { SCPrint(TRUE, stderr, CFSTR("No current location\n"), SCErrorString(SCError())); goto done; } service = nc_copy_service_from_arguments(argc, argv, current_set); if (service == NULL) { SCPrint(TRUE, stderr, CFSTR("No service\n")); goto done; } #if !TARGET_OS_IPHONE status = SCNetworkServiceSetEnabled(service, TRUE); if (!status) { SCPrint(TRUE, stderr, CFSTR("Unable to enable service: %s\n"), SCErrorString(SCError())); goto done; } #else status = SCNetworkSetSetSelectedVPNService(current_set, service); if (!status) { SCPrint(TRUE, stderr, CFSTR("Unable to select service: %s\n"), SCErrorString(SCError())); goto done; } #endif _prefs_save(); exit_code = 0; done: my_CFRelease(&service); my_CFRelease(¤t_set); _prefs_close(); exit(exit_code); }
Boolean SCNetworkSetRemoveService(SCNetworkSetRef set, SCNetworkServiceRef service) { SCNetworkInterfaceRef interface; CFArrayRef interface_config = NULL; Boolean ok; CFStringRef path; int sc_status = kSCStatusOK; SCNetworkServicePrivateRef servicePrivate = (SCNetworkServicePrivateRef)service; SCNetworkSetPrivateRef setPrivate = (SCNetworkSetPrivateRef)set; if (!isA_SCNetworkSet(set)) { _SCErrorSet(kSCStatusInvalidArgument); return FALSE; } if (!isA_SCNetworkService(service) || (servicePrivate->prefs == NULL)) { _SCErrorSet(kSCStatusInvalidArgument); return FALSE; } // remove service from ServiceOrder _serviceOrder_remove(set, service); // get the [deep] interface configuration settings interface = SCNetworkServiceGetInterface(service); if (interface != NULL) { interface_config = __SCNetworkInterfaceCopyDeepConfiguration(set, interface); if (interface_config != NULL) { // remove the interface configuration from all sets which contain this service. __SCNetworkInterfaceSetDeepConfiguration(set, interface, NULL); } } // remove the link between "set" and the "service" path = SCPreferencesPathKeyCreateSetNetworkServiceEntity(NULL, setPrivate->setID, servicePrivate->serviceID, NULL); ok = SCPreferencesPathRemoveValue(setPrivate->prefs, path); if (!ok) { sc_status = SCError(); // preserve the error } CFRelease(path); // push the [deep] interface configuration [back] into all sets which contain the service. if (interface_config != NULL) { __SCNetworkInterfaceSetDeepConfiguration(set, interface, interface_config); } if (interface_config != NULL) CFRelease(interface_config); if (!ok) { _SCErrorSet(sc_status); } return ok; }
__private_extern__ Boolean __setPrefsConfiguration(SCPreferencesRef prefs, CFStringRef path, CFDictionaryRef config, Boolean keepInactive) { CFDictionaryRef curConfig; CFMutableDictionaryRef newConfig = NULL; Boolean ok; if ((config != NULL) && !isA_CFDictionary(config)) { _SCErrorSet(kSCStatusInvalidArgument); return FALSE; } curConfig = SCPreferencesPathGetValue(prefs, path); if (config != NULL) { newConfig = CFDictionaryCreateMutableCopy(NULL, 0, config); } if (keepInactive) { if (config == NULL) { newConfig = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); } if (isA_CFDictionary(curConfig) && CFDictionaryContainsKey(curConfig, kSCResvInactive)) { // if currently disabled CFDictionarySetValue(newConfig, kSCResvInactive, kCFBooleanTrue); } else { // if currently enabled CFDictionaryRemoveValue(newConfig, kSCResvInactive); } } // set new configuration if (_SC_CFEqual(curConfig, newConfig)) { // if no change if (newConfig != NULL) CFRelease(newConfig); ok = TRUE; } else if (newConfig != NULL) { // if new configuration (or we are preserving a disabled state) ok = SCPreferencesPathSetValue(prefs, path, newConfig); CFRelease(newConfig); } else { ok = SCPreferencesPathRemoveValue(prefs, path); if (!ok && (SCError() == kSCStatusNoKey)) { ok = TRUE; } } return ok; }
bool Client::isConnected(void) const { SCLog("checking network..."); int fd = socket(AF_INET, SOCK_DGRAM, 0); if (fd < 0) { SCError("not connect"); return false; } return false; }
/* ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- */ static void checkOnDemandHost(SCDynamicStoreRef store, CFStringRef nodeName, Boolean retry) { Boolean ok; CFStringRef connectionServiceID = NULL; SCNetworkConnectionStatus connectionStatus = 0; CFStringRef vpnRemoteAddress = NULL; SCPrint(TRUE, stdout, CFSTR("OnDemand host/domain check (%sretry)\n"), retry ? "" : "no "); ok = __SCNetworkConnectionCopyOnDemandInfoWithName(&store, nodeName, retry, &connectionServiceID, &connectionStatus, &vpnRemoteAddress); if (ok) { SCPrint(TRUE, stdout, CFSTR(" serviceID = %@\n"), connectionServiceID); SCPrint(TRUE, stdout, CFSTR(" remote address = %@\n"), vpnRemoteAddress); } else if (SCError() != kSCStatusOK) { SCPrint(TRUE, stdout, CFSTR("%sretry\n"), retry ? "" : "no "); SCPrint(TRUE, stdout, CFSTR(" Unable to copy OnDemand information for connection: %s\n"), SCErrorString(SCError())); } else { SCPrint(TRUE, stdout, CFSTR(" no match\n")); } if (connectionServiceID != NULL) { CFRelease(connectionServiceID); connectionServiceID = NULL; } if (vpnRemoteAddress != NULL) { CFRelease(vpnRemoteAddress); vpnRemoteAddress = NULL; } return; }
/* ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- */ static void nc_stop(int argc, char **argv) { nc_create_connection(argc, argv, TRUE); if (!SCNetworkConnectionStop(connection, TRUE)) { SCPrint(TRUE, stderr, CFSTR("Could not stop connection: %s\n"), SCErrorString(SCError())); exit(1); }; nc_release_connection(); exit(0); }
bool FileManager::copy(const URL &sSourcePath, const URL &sTargetPath) { if (!isExists(sSourcePath) || !isWritable(URL(sTargetPath).deleteLastPathComponent())) { SCError("failed to copy file %s to %s", sSourcePath.c_str(), sTargetPath.c_str()); return false; } File file; if (!file.read(sSourcePath.c_str())) { SCError("failed to read file: %s", sSourcePath.c_str()); return false; } if (!file.write(sTargetPath.c_str())) { SCError("failed to write file: %s", sTargetPath.c_str()); return false; } return true; }
STATIC SCPreferencesRef get_sc_prefs(EAPOLClientConfigurationRef cfg) { if (cfg->sc_prefs == NULL) { cfg->sc_prefs = SCPreferencesCreate(NULL, kPrefsName, NULL); if (cfg->sc_prefs == NULL) { EAPLOG(LOG_NOTICE, "EAPOLClientConfiguration: SCPreferencesCreate failed, %s", SCErrorString(SCError())); } } return (cfg->sc_prefs); }
__private_extern__ Boolean __setPrefsEnabled(SCPreferencesRef prefs, CFStringRef path, Boolean enabled) { CFDictionaryRef curConfig; CFMutableDictionaryRef newConfig = NULL; Boolean ok = FALSE; // preserve current configuration curConfig = SCPreferencesPathGetValue(prefs, path); if (curConfig != NULL) { if (!isA_CFDictionary(curConfig)) { _SCErrorSet(kSCStatusFailed); return FALSE; } newConfig = CFDictionaryCreateMutableCopy(NULL, 0, curConfig); if (enabled) { // enable CFDictionaryRemoveValue(newConfig, kSCResvInactive); } else { // disable CFDictionarySetValue(newConfig, kSCResvInactive, kCFBooleanTrue); } } else { if (!enabled) { // disable newConfig = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFDictionarySetValue(newConfig, kSCResvInactive, kCFBooleanTrue); } } // set new configuration if (_SC_CFEqual(curConfig, newConfig)) { // if no change if (newConfig != NULL) CFRelease(newConfig); ok = TRUE; } else if (newConfig != NULL) { // if updated configuration (or we are establishing as disabled) ok = SCPreferencesPathSetValue(prefs, path, newConfig); CFRelease(newConfig); } else { ok = SCPreferencesPathRemoveValue(prefs, path); if (!ok && (SCError() == kSCStatusNoKey)) { ok = TRUE; } } return ok; }
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); }
bool FileManager::init(void) { bool ok0 = SCFileManager_makeDirectory(0, m_sResourceDirectory); bool ok1 = SCFileManager_makeDirectory(1, m_sDocumentDirectory); bool ok2 = SCFileManager_makeDirectory(2, m_sCachesDirectory); bool ok4 = SCFileManager_makeDirectory(4, m_sTemporaryDirectory); if (ok0 && ok1 && ok2 && ok4) { return true; } else { SCError("error"); return false; } }
FileManager::FileManager(void) : m_sResourceDirectory("") , m_sDocumentDirectory("") , m_sCachesDirectory("") , m_sTemporaryDirectory("") { bool ok0 = SCFileManager_makeDirectory(0, m_sResourceDirectory); bool ok1 = SCFileManager_makeDirectory(1, m_sDocumentDirectory); bool ok2 = SCFileManager_makeDirectory(2, m_sCachesDirectory); bool ok4 = SCFileManager_makeDirectory(4, m_sTemporaryDirectory); if (!ok0 || !ok1 || !ok2 || !ok4) { SCError("error"); SCAssert(false, "error"); } }
void Client::setInfo(const std::string & name, const std::string & value) { if (name.empty()) { SCError("key is empty"); } // screen else if (strcasecmp(name.c_str(), "ScreenWidth") == 0) { m_uiScreenWidth = atoi(value.c_str()); } else if (strcasecmp(name.c_str(), "ScreenHeight") == 0) { m_uiScreenHeight = atoi(value.c_str()); } // client info else if (strcasecmp(name.c_str(), "Hardware") == 0) { m_sHardware = value; } else if (strcasecmp(name.c_str(), "IMEI") == 0) { m_sDeviceIdentifier = value; } else if (strcasecmp(name.c_str(), "Model") == 0) { m_sDeviceModel = value; } else if (strcasecmp(name.c_str(), "SystemName") == 0) { m_sSystemName = value; } else if (strcasecmp(name.c_str(), "SystemVersion") == 0) { m_sSystemVersion = value; } // bundle version else if (strcasecmp(name.c_str(), "Version") == 0) { m_sVersion = value; } updateClientParameters(); }
/* ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- */ static Boolean nc_enable_vpntype(CFStringRef vpnType) { Boolean is_enabled = FALSE; Boolean success = FALSE; if (vpnType == NULL) { SCPrint(TRUE, stderr, CFSTR("No VPN type provided\n")); goto done; } is_enabled = VPNConfigurationIsVPNTypeEnabled(vpnType); if (is_enabled) { SCPrint(TRUE, stdout, CFSTR("VPN is already enabled\n")); } else { #if !TARGET_OS_IPHONE AuthorizationRef authorization; authorization = _prefs_AuthorizationCreate(); if ((authorization == NULL) || !VPNConfigurationSetAuthorization(authorization)) { SCPrint(TRUE, stderr, CFSTR("VPNConfigurationSetAuthorization failed: %s\n"), SCErrorString(SCError())); goto done; } #endif // !TARGET_OS_IPHONE if (!VPNConfigurationEnableVPNType(vpnType)) { SCPrint(TRUE, stderr, CFSTR("VPN could not be enabled: %s\n"), SCErrorString(SCError())); goto done; } #if !TARGET_OS_IPHONE _prefs_AuthorizationFree(authorization); #endif // !TARGET_OS_IPHONE SCPrint(TRUE, stdout, CFSTR("VPN enabled\n")); } success = TRUE; done: return success; }
__private_extern__ void cache_write(SCDynamicStoreRef store) { if ((CFDictionaryGetCount(cached_set) > 0) || (CFArrayGetCount(cached_removals) > 0) || (CFArrayGetCount(cached_notifys) > 0)) { if (!SCDynamicStoreSetMultiple(store, cached_set, cached_removals, cached_notifys)) { SCLog(TRUE, LOG_ERR, CFSTR("SCDynamicStoreSetMultiple() failed: %s"), SCErrorString(SCError())); } } return; }
__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; }
bool FileManager::isWritable(const URL &sFilePath) { if (sFilePath.empty()) { SCError("%s", sFilePath.c_str()); return false; } if (!m_sDocumentDirectory.empty() && sFilePath.hasPrefix(m_sDocumentDirectory)) { return true; } if (!m_sCachesDirectory.empty() && sFilePath.hasPrefix(m_sCachesDirectory)) { return true; } if (!m_sTemporaryDirectory.empty() && sFilePath.hasPrefix(m_sTemporaryDirectory)) { return true; } return false; }
static void nc_callback(SCNetworkConnectionRef connection, SCNetworkConnectionStatus status, void *info) { int *n = (int *)info; CFDictionaryRef status_dict; // report status if (n != NULL) { if (*n == 0) { SCPrint(TRUE, stdout, CFSTR("Current status = ")); } else { struct tm tm_now; struct timeval tv_now; (void)gettimeofday(&tv_now, NULL); (void)localtime_r(&tv_now.tv_sec, &tm_now); SCPrint(TRUE, stdout, CFSTR("\n*** %2d:%02d:%02d.%03d\n\n"), tm_now.tm_hour, tm_now.tm_min, tm_now.tm_sec, tv_now.tv_usec / 1000); SCPrint(TRUE, stdout, CFSTR("Callback (%d) status = "), *n); } *n = *n + 1; } SCPrint(TRUE, stdout, CFSTR("%s%s%s\n"), nc_status_string(status), (status == kSCNetworkConnectionInvalid) ? ": " : "", (status == kSCNetworkConnectionInvalid) ? SCErrorString(SCError()) : ""); // report extended status status_dict = SCNetworkConnectionCopyExtendedStatus(connection); if (status_dict) { SCPrint(TRUE, stdout, CFSTR("Extended Status %@\n"), status_dict); CFRelease(status_dict); } return; }
void Java_com_slanissue_bevatingx_bevatingx_nativeSetClientInfo(JNIEnv* env, jobject thiz, jstring clientInfo) { const char * str = env->GetStringUTFChars(clientInfo, NULL); std::string string = str ? str : ""; env->ReleaseStringUTFChars(clientInfo, str); SCLog("clientInfo: %s", string.c_str()); std::size_t pos = string.find("="); if (pos == std::string::npos) { SCError("error"); return; } std::string key = string.substr(0, pos); std::string value = string.substr(pos + 1); StringUtils::trim(key); StringUtils::trim(value); SCLog("key: %s, value: %s", key.c_str(), value.c_str()); Client::currentClient()->setInfo(key, value); }
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); }
/* Initialise a Preferences object from the given pspec. This might be an * SCPreferences AppID or it might be the path to a plist file. */ Preferences::Preferences(const char * pspec) : m_pspec(pspec), m_plist(NULL), m_scpref(NULL) { /* Try to load this as a plist file first. The SCPreferences API does a * bunch of work if it can't find the file, and we should avoid that unless * we have a good idea that it's necessary. */ this->m_plist = load_plist_from_path(this->m_pspec.c_str()); if (this->m_plist) { /* Loading a plist should always give you back a dictionary. */ ASSERT(CFDictionaryGetTypeID() == CFGetTypeID(this->m_plist)); VERBOSE("loaded plist %s\n", pspec); return; } cf_typeref<CFStringRef> appname(cfstring_wrap(getprogname())); cf_typeref<CFStringRef> appid(cfstring_wrap(this->m_pspec.c_str())); this->m_scpref = SCPreferencesCreate(kCFAllocatorDefault, appname, appid); if (this->m_scpref == NULL) { return; } /* If there was no existing preferences file, SCError() should return * kSCStatusNoConfigFile. We are only interested in reading preferences, so * we want to fail if there's no existing config. */ if (SCError() != kSCStatusOK) { safe_release(this->m_scpref); } if (this->m_scpref) { VERBOSE("loaded SC preferences %s\n", pspec); } }
static void nc_create_connection(int argc, char **argv, Boolean exit_on_failure) { SCNetworkConnectionContext context = { 0, &n_callback, NULL, NULL, NULL }; SCNetworkServiceRef service; service = nc_copy_service_from_arguments(argc, argv, NULL); if (service == NULL) { SCPrint(TRUE, stderr, CFSTR("No service\n")); if (exit_on_failure) exit(1); return; } connection = SCNetworkConnectionCreateWithService(NULL, service, nc_callback, &context); CFRelease(service); if (connection == NULL) { SCPrint(TRUE, stderr, CFSTR("Could not create connection: %s\n"), SCErrorString(SCError())); if (exit_on_failure) exit(1); return; } }
static void watchQuietEnable() { CFArrayRef keys; Boolean ok; initKey = SCDynamicStoreKeyCreate(NULL, CFSTR("%@" "InterfaceNamer"), kSCDynamicStoreDomainPlugin); initRls = SCDynamicStoreCreateRunLoopSource(NULL, store, 0); CFRunLoopAddSource(CFRunLoopGetCurrent(), initRls, kCFRunLoopDefaultMode); keys = CFArrayCreate(NULL, (const void **)&initKey, 1, &kCFTypeArrayCallBacks); ok = SCDynamicStoreSetNotificationKeys(store, keys, NULL); CFRelease(keys); if (!ok) { SCLog(TRUE, LOG_ERR, CFSTR("SCDynamicStoreSetNotificationKeys() failed: %s\n"), SCErrorString(SCError())); watchQuietDisable(); } return; }
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; }
/* * 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; }