OSErr getURLFromUTextDesc(const AEDesc *utdesc_p, CFURLRef *urlRef_p) { OSErr err; Size theLength = AEGetDescDataSize(utdesc_p); UInt8 *theData = malloc(theLength); err = AEGetDescData(utdesc_p, theData, theLength); if (err != noErr) goto bail; CFStringRef pathStr = CFStringCreateWithBytes(NULL, theData, theLength, kCFStringEncodingUnicode, false); CFURLPathStyle pathStyle; if (CFStringHasPrefix(pathStr, CFSTR("/"))) { pathStyle = kCFURLPOSIXPathStyle; } else { pathStyle = kCFURLHFSPathStyle; } *urlRef_p = CFURLCreateWithFileSystemPath(NULL, pathStr, pathStyle, true); CFRelease(pathStr); bail: free(theData); return err; }
__private_extern__ CFStringRef _CFPreferencesGetByHostIdentifierString(void) { static CFStringRef __byHostIdentifierString = NULL; if (!__byHostIdentifierString) { CFStringRef hostID = _CFGetHostUUIDString(); if (hostID) { if (CFStringHasPrefix(hostID, CFSTR("00000000-0000-1000-8000-"))) { // If the host UUID is prefixed by "00000000-0000-1000-8000-" then the UUID returned is the "compatible" type. The last field of the string will be the MAC address of the primary ethernet interface of the computer. We use this for compatibility with existing by-host preferences. CFStringRef lastField = CFStringCreateWithSubstring(kCFAllocatorSystemDefault, hostID, CFRangeMake(24, 12)); CFMutableStringRef tmpstr = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, 0, lastField); CFStringLowercase(tmpstr, NULL); CFStringRef downcasedField = CFStringCreateCopy(kCFAllocatorSystemDefault, tmpstr); if (!OSAtomicCompareAndSwapPtrBarrier(NULL, (void *)downcasedField, (void *)&__byHostIdentifierString)) { CFRelease(downcasedField); } CFRelease(tmpstr); CFRelease(lastField); } else { // The host UUID is a full UUID, and we should just use that. This doesn't involve any additional string creation, so we should just be able to do the assignment. __byHostIdentifierString = hostID; } } else { __byHostIdentifierString = CFSTR("UnknownHostID"); } } return __byHostIdentifierString; }
Boolean APSetKey(CFStringRef key) { hash = CFSTR(""); blacklist = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks); // Create a new key rsaKey = RSA_new(); // Public exponent is always 3 BN_hex2bn(&rsaKey->e, "3"); CFMutableStringRef mutableKey = CFStringCreateMutableCopy(kCFAllocatorDefault, 0, key); if (!mutableKey) return FALSE; CFIndex maximumCStringLength = CFStringGetMaximumSizeForEncoding(CFStringGetLength(mutableKey), kCFStringEncodingMacRoman) + 1; char *keyCStringBuffer = malloc(maximumCStringLength); // Determine if we have a hex or decimal key CFStringLowercase(mutableKey, NULL); if (CFStringHasPrefix(mutableKey, CFSTR("0x"))) { CFStringTrim(mutableKey, CFSTR("0x")); CFStringGetCString(mutableKey, keyCStringBuffer, maximumCStringLength, kCFStringEncodingMacRoman); BN_hex2bn(&rsaKey->n, keyCStringBuffer); } else { CFStringGetCString(mutableKey, keyCStringBuffer, maximumCStringLength, kCFStringEncodingMacRoman); BN_dec2bn(&rsaKey->n, keyCStringBuffer); } CFRelease(mutableKey); free(keyCStringBuffer); return TRUE; }
std::ostream& operator<<(std::ostream& out, CFURLRef u) { if(nullptr == u) { out << "(null)"; return out; } CFStringRef s = CFURLGetString(u); #if !TARGET_OS_IPHONE if(CFStringHasPrefix(s, CFSTR("file:"))) { CFStringRef displayName = nullptr; OSStatus result = LSCopyDisplayNameForURL(u, &displayName); if(noErr == result && nullptr != displayName) { out << displayName; CFRelease(displayName); displayName = nullptr; } } else #endif out << s; return out; }
uint8_t AMAuthInstallCryptoGetKeyIdType(CFStringRef key) { Boolean has_suffix, has_prefix = CFStringHasPrefix(key, @"ap."); uint8_t flag = 1; if (has_prefix == false) { has_prefix = CFStringHasPrefix(key, @"bb."); } has_suffix = CFStringHasSuffix(key, @".private"); if (has_suffix == true) { flag = (flag | 0x8); } else { flag = (flag | 0x4); if (CFStringHasSuffix(key, @".public")) { flag = 1; } } return flag; }
static void ShowErrorVa(const wchar_t *de, const wchar_t *en, va_list args) { // Get current language const wchar_t *stringToUse = en; #ifdef _WIN32 if ((GetUserDefaultLangID() & 0xFF) == LANG_GERMAN) stringToUse = de; #elif defined(__APPLE_CC__) CFStringRef localisations[2] = { CFSTR("en"), CFSTR("de") }; CFArrayRef allLocalisations = CFArrayCreate(kCFAllocatorDefault, (const void **) localisations, 2, &kCFTypeArrayCallBacks); CFArrayRef preferredLocalisations = CFBundleCopyPreferredLocalizationsFromArray(allLocalisations); CFStringRef oldStyleLang = (CFStringRef) CFArrayGetValueAtIndex(preferredLocalisations, 0); CFStringRef newStyleLang = CFLocaleCreateCanonicalLanguageIdentifierFromString(kCFAllocatorDefault, oldStyleLang); if (CFStringHasPrefix(newStyleLang, CFSTR("de"))) stringToUse = de; CFRelease(allLocalisations); CFRelease(preferredLocalisations); CFRelease(newStyleLang); #else // TODO: Implement something here for android. #endif // Create output string wchar_t text[1024]; vswprintf(text, 1024, stringToUse, args); // Show message #ifdef _WIN32 MessageBoxW(NULL, text, L"Mindstorms Simulator", MB_TASKMODAL & MB_ICONWARNING); #elif defined(IPHONE) // Ignore it #elif defined(__APPLE_CC__) CFStringRef messageString = CFStringCreateWithBytes(kCFAllocatorDefault, (const UInt8 *) text, sizeof(wchar_t) * wcslen(text), (CFByteOrderGetCurrent() == CFByteOrderBigEndian) ? kCFStringEncodingUTF32BE : kCFStringEncodingUTF32LE, false); CFUserNotificationDisplayAlert(0.0, kCFUserNotificationStopAlertLevel, NULL, NULL, NULL, messageString, NULL, NULL, NULL, NULL, NULL); CFRelease(messageString); #else // TODO: Implement something here for android. size_t length = wcslen(text)+1; char *englishMangledASCII = new char[length]; for (unsigned i = 0; i < length; i++) englishMangledASCII[i] = (char) en[i]; __android_log_print(ANDROID_LOG_FATAL, "librobosim.so", "Error: %s", englishMangledASCII); delete englishMangledASCII; #endif }
/* * Function: parse_component * Purpose: * Given a string 'key' and a string prefix 'prefix', * return the next component in the slash '/' separated * key. * * Examples: * 1. key = "a/b/c" prefix = "a/" * returns "b" * 2. key = "a/b/c" prefix = "a/b/" * returns "c" */ static CFStringRef parse_component(CFStringRef key, CFStringRef prefix) { CFMutableStringRef comp; CFRange range; if (CFStringHasPrefix(key, prefix) == FALSE) { return NULL; } comp = CFStringCreateMutableCopy(NULL, 0, key); CFStringDelete(comp, CFRangeMake(0, CFStringGetLength(prefix))); range = CFStringFind(comp, CFSTR("/"), 0); if (range.location == kCFNotFound) { return comp; } range.length = CFStringGetLength(comp) - range.location; CFStringDelete(comp, range); return comp; }
static void convertWebResourceDataToString(CFMutableDictionaryRef resource) { CFMutableStringRef mimeType = (CFMutableStringRef)CFDictionaryGetValue(resource, CFSTR("WebResourceMIMEType")); CFStringLowercase(mimeType, CFLocaleGetSystem()); convertMIMEType(mimeType); CFArrayRef supportedMIMETypes = supportedNonImageMIMETypes(); if (CFStringHasPrefix(mimeType, CFSTR("text/")) || CFArrayContainsValue(supportedMIMETypes, CFRangeMake(0, CFArrayGetCount(supportedMIMETypes)), mimeType)) { CFStringRef textEncodingName = static_cast<CFStringRef>(CFDictionaryGetValue(resource, CFSTR("WebResourceTextEncodingName"))); CFStringEncoding stringEncoding; if (textEncodingName && CFStringGetLength(textEncodingName)) stringEncoding = CFStringConvertIANACharSetNameToEncoding(textEncodingName); else stringEncoding = kCFStringEncodingUTF8; CFDataRef data = static_cast<CFDataRef>(CFDictionaryGetValue(resource, CFSTR("WebResourceData"))); RetainPtr<CFStringRef> dataAsString = adoptCF(CFStringCreateFromExternalRepresentation(kCFAllocatorDefault, data, stringEncoding)); if (dataAsString) CFDictionarySetValue(resource, CFSTR("WebResourceData"), dataAsString.get()); } }
void configRemove(CFMutableArrayRef config, CFStringRef key) { CFMutableStringRef pref; CFIndex configLen = CFArrayGetCount(config); CFIndex i; /* create search prefix */ pref = CFStringCreateMutableCopy(NULL, 0, key); CFStringAppend(pref, CFSTR("=")); /* locate existing key */ for (i = 0; i < configLen; i++) { if (CFStringHasPrefix(CFArrayGetValueAtIndex(config, i), pref)) { /* entry found, remove it */ CFArrayRemoveValueAtIndex(config, i); break; } } CFRelease(pref); return; }
static CFStringRef copyCurrentNIDFromStore (struct service *serv) { CFStringRef result = NULL; struct sockaddr_in addr; SCLog(TRUE, LOG_INFO, CFSTR("%s:"), __FUNCTION__); // only one NID for now bzero(&addr, sizeof(addr)); ((struct sockaddr *)&addr)->sa_len = sizeof(addr); ((struct sockaddr *)&addr)->sa_family = AF_INET; result = SCNetworkSignatureCopyActiveIdentifierForAddress(NULL, (struct sockaddr *)&addr); if (!result) { return NULL; } else if (CFStringHasPrefix(result, VPN_INTERFACE_NID_PREFIX)) { SCLog(TRUE, LOG_NOTICE, CFSTR("%s: ignoring nid %@"), __FUNCTION__, result); CFRelease(result); return NULL; } SCLog(TRUE, LOG_INFO, CFSTR("%s: nid %@"), __FUNCTION__, result); return result; }
int od_record_check_authauthority(ODRecordRef record) { int retval = PAM_PERM_DENIED; CFStringRef authauth = NULL; if (NULL == record) { openpam_log(PAM_LOG_DEBUG, "NULL argument passed"); retval = PAM_SERVICE_ERR; goto cleanup; } retval = od_record_attribute_create_cfstring(record, kODAttributeTypeAuthenticationAuthority, &authauth); if (PAM_SUCCESS != retval) { openpam_log(PAM_LOG_DEBUG, "od_record_attribute_create_cfstring() failed"); goto cleanup; } if (NULL == authauth) { retval = PAM_SUCCESS; goto cleanup; } if (!CFStringHasPrefix(authauth, CFSTR(kDSValueAuthAuthorityDisabledUser))) { retval = PAM_SUCCESS; } cleanup: if (PAM_SUCCESS != retval) { openpam_log(PAM_LOG_ERROR, "failed: %d", retval); } if (authauth) { CFRelease(authauth); } return retval; }
/* * Given a c-style string create a CFURL. We assume the c-style string is in * URL or UNC format. Anything else will give unexpected behavior. * NOTE: The library code doesn't care if the scheme exist or not in the URL, * but we attempt to create a URL with a scheme, just for correctness sake. * * Note: If its a URL, then do not escape it out again since it should already * be escaped out properly. */ CFURLRef CreateSMBURL(const char *url) { CFURLRef ct_url = NULL; CFStringRef urlString = CFStringCreateWithCString(NULL, url, kCFStringEncodingUTF8); CFStringRef escapedUrlString; int UNCformat = 0; escapedUrlString = NULL; /* * We have a UNC path that we need to convert into a SMB URL. Currently we * just replace the backslashes with slashes */ if (urlString && (*url == '\\') && (*(url + 1) == '\\')) { CFArrayRef urlArray = CFStringCreateArrayBySeparatingStrings(NULL, urlString, CFSTR("\\")); CFRelease(urlString); urlString = NULL; if (urlArray) { urlString = CFStringCreateByCombiningStrings(NULL, urlArray, CFSTR("/")); CFRelease(urlArray); } UNCformat = 1; } /* Something failed just get out */ if (!urlString) { return NULL; } DebugLogCFString(urlString, "urlString ", __FUNCTION__, __LINE__); /* * No scheme, add one if we can, but not required by the library code. * NOTE: If no scheme, then expect the string to start with double slashes. */ if ((!CFStringHasPrefix(urlString, CFSTR("smb://"))) && (!CFStringHasPrefix(urlString, CFSTR("cifs://")))) { CFMutableStringRef urlStringM = CFStringCreateMutableCopy(NULL, 1024, CFSTR("smb:")); if (urlStringM) { CFStringAppend(urlStringM, urlString); CFRelease(urlString); urlString = urlStringM; } } /* Something failed just get out */ if (urlString == NULL) { return (NULL); } if (UNCformat == 1) { /* For UNC format strings, escape out any non-URL characters */ escapedUrlString = CFURLCreateStringByAddingPercentEscapes(NULL, urlString, NULL, NULL, kCFStringEncodingUTF8); CFRelease(urlString); /* Can release it now */ /* Something failed just get out */ if (escapedUrlString == NULL) { return (NULL); } /* now create the URL */ ct_url = CFURLCreateWithString(kCFAllocatorDefault, escapedUrlString, NULL); CFRelease(escapedUrlString); /* We create it now release it */ } else { /* * For URL format strings, it should already be escaped. * Just create the URL. */ ct_url = CFURLCreateWithString(kCFAllocatorDefault, urlString, NULL); CFRelease(urlString); /* Can release it now */ } return ct_url; }
Boolean _DAUnitIsUnreadable( DADiskRef disk ) { CFIndex count; CFIndex index; count = CFArrayGetCount( gDADiskList ); for ( index = 0; index < count; index++ ) { DADiskRef item; item = ( void * ) CFArrayGetValueAtIndex( gDADiskList, index ); if ( DADiskGetBSDUnit( disk ) == DADiskGetBSDUnit( item ) ) { CFStringRef name; name = DADiskGetDescription( item, kDADiskDescriptionMediaBSDNameKey ); if ( DADiskGetBusy( item ) ) { return FALSE; } if ( DADiskGetClaim( item ) ) { return FALSE; } if ( DADiskGetState( item, _kDADiskStateMountAutomatic ) == FALSE ) { return FALSE; } if ( DADiskGetDescription( item, kDADiskDescriptionVolumeMountableKey ) == kCFBooleanTrue ) { return FALSE; } if ( DADiskGetDescription( item, kDADiskDescriptionMediaLeafKey ) == kCFBooleanFalse ) { CFIndex subcount; CFIndex subindex; subcount = CFArrayGetCount( gDADiskList ); for ( subindex = 0; subindex < subcount; subindex++ ) { DADiskRef subitem; subitem = ( void * ) CFArrayGetValueAtIndex( gDADiskList, subindex ); if ( item != subitem ) { CFStringRef subname; subname = DADiskGetDescription( subitem, kDADiskDescriptionMediaBSDNameKey ); if ( subname ) { if ( CFStringHasPrefix( subname, name ) ) { break; } } } } if ( subindex == subcount ) { return FALSE; } } } } return TRUE; }
static SCPreferencesPrivateRef __SCPreferencesCreate(CFAllocatorRef allocator, CFStringRef name, CFStringRef prefsID, CFDataRef authorizationData, CFDictionaryRef options) { SCPreferencesPrivateRef prefsPrivate; int sc_status = kSCStatusOK; /* * allocate and initialize a new prefs session */ prefsPrivate = __SCPreferencesCreatePrivate(allocator); if (prefsPrivate == NULL) { return NULL; } prefsPrivate->name = CFStringCreateCopy(allocator, name); if (prefsID != NULL) { prefsPrivate->prefsID = CFStringCreateCopy(allocator, prefsID); } if (authorizationData != NULL) { prefsPrivate->authorizationData = CFRetain(authorizationData); } if (options != NULL) { prefsPrivate->options = CFDictionaryCreateCopy(allocator, options); } retry : /* * convert prefsID to path */ prefsPrivate->path = __SCPreferencesPath(allocator, prefsID, (prefsPrivate->newPath == NULL)); if (prefsPrivate->path == NULL) { sc_status = kSCStatusFailed; goto error; } if (access(prefsPrivate->path, R_OK) == 0) { goto done; } switch (errno) { case ENOENT : /* no prefs file */ if ((prefsID == NULL) || !CFStringHasPrefix(prefsID, CFSTR("/"))) { /* if default preference ID or relative path */ if (prefsPrivate->newPath == NULL) { /* * we've looked in the "new" prefs directory * without success. Save the "new" path and * look in the "old" prefs directory. */ prefsPrivate->newPath = prefsPrivate->path; goto retry; } else { /* * we've looked in both the "new" and "old" * prefs directories without success. Use * the "new" path. */ CFAllocatorDeallocate(NULL, prefsPrivate->path); prefsPrivate->path = prefsPrivate->newPath; prefsPrivate->newPath = NULL; } } /* no preference data, start fresh */ sc_status = kSCStatusNoConfigFile; goto done; case EPERM : case EACCES : if (prefsPrivate->authorizationData != NULL) { /* no problem, we'll be using the helper */ goto done; } SCLog(_sc_verbose, LOG_DEBUG, CFSTR("__SCPreferencesCreate open() failed: %s"), strerror(errno)); sc_status = kSCStatusAccessError; break; default : SCLog(TRUE, LOG_ERR, CFSTR("__SCPreferencesCreate open() failed: %s"), strerror(errno)); sc_status = kSCStatusFailed; break; } error: CFRelease(prefsPrivate); _SCErrorSet(sc_status); return NULL; done : /* all OK */ _SCErrorSet(sc_status); return prefsPrivate; }
static CFArrayRef _SecIdentityCopyPossiblePaths( CFStringRef name) { // utility function to build and return an array of possible paths for the given name. // if name is not a URL, this returns a single-element array. // if name is a URL, the array may contain 1..N elements, one for each level of the path hierarchy. CFMutableArrayRef names = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); if (!name) { return names; } CFIndex oldLength = CFStringGetLength(name); CFArrayAppendValue(names, name); CFURLRef url = CFURLCreateWithString(NULL, name, NULL); if (url) { if (CFURLCanBeDecomposed(url)) { // first, remove the query portion of this URL, if any CFStringRef qs = CFURLCopyQueryString(url, NULL); if (qs) { CFMutableStringRef newName = CFStringCreateMutableCopy(NULL, oldLength, name); if (newName) { CFIndex qsLength = CFStringGetLength(qs) + 1; // include the '?' CFStringDelete(newName, CFRangeMake(oldLength-qsLength, qsLength)); CFRelease(url); url = CFURLCreateWithString(NULL, newName, NULL); CFArraySetValueAtIndex(names, 0, newName); CFRelease(newName); } CFRelease(qs); } // now add an entry for each level of the path while (url) { CFURLRef parent = CFURLCreateCopyDeletingLastPathComponent(NULL, url); if (parent) { CFStringRef parentURLString = CFURLGetString(parent); if (parentURLString) { CFIndex newLength = CFStringGetLength(parentURLString); // check that string length has decreased as expected; for file URLs, // CFURLCreateCopyDeletingLastPathComponent can insert './' or '../' if ((newLength >= oldLength) || (!CFStringHasPrefix(name, parentURLString))) { CFRelease(parent); CFRelease(url); break; } oldLength = newLength; CFArrayAppendValue(names, parentURLString); } } CFRelease(url); url = parent; } } else { CFRelease(url); } } // finally, add wildcard entries for each subdomain url = CFURLCreateWithString(NULL, name, NULL); if (url) { if (CFURLCanBeDecomposed(url)) { CFStringRef netLocString = CFURLCopyNetLocation(url); if (netLocString) { // first strip off port number, if present CFStringRef tmpLocString = netLocString; CFArrayRef hostnameArray = CFStringCreateArrayBySeparatingStrings(NULL, netLocString, CFSTR(":")); tmpLocString = (CFStringRef)CFRetain((CFStringRef)CFArrayGetValueAtIndex(hostnameArray, 0)); CFRelease(netLocString); CFRelease(hostnameArray); netLocString = tmpLocString; // split remaining string into domain components hostnameArray = CFStringCreateArrayBySeparatingStrings(NULL, netLocString, CFSTR(".")); CFIndex subdomainCount = CFArrayGetCount(hostnameArray); CFIndex i = 0; while (++i < subdomainCount) { CFIndex j = i; CFMutableStringRef wildcardString = CFStringCreateMutable(NULL, 0); if (wildcardString) { CFStringAppendCString(wildcardString, "*", kCFStringEncodingUTF8); while (j < subdomainCount) { CFStringRef domainString = (CFStringRef)CFArrayGetValueAtIndex(hostnameArray, j++); if (CFStringGetLength(domainString) > 0) { CFStringAppendCString(wildcardString, ".", kCFStringEncodingUTF8); CFStringAppend(wildcardString, domainString); } } if (CFStringGetLength(wildcardString) > 1) { CFArrayAppendValue(names, wildcardString); } CFRelease(wildcardString); } } CFRelease(hostnameArray); CFRelease(netLocString); } } CFRelease(url); } return names; }
Boolean APSetKey(CFStringRef key) { hash = CFSTR(""); blacklist = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks); CFMutableStringRef mutableKey = CFStringCreateMutableCopy(kCFAllocatorDefault, 0, key); CFStringRef preparedKey = CFStringCreateMutableCopy(kCFAllocatorDefault, 0, key); CFLocaleRef currentLocale = CFLocaleCopyCurrent(); CFStringLowercase(mutableKey, currentLocale); CFRelease(currentLocale); if (CFStringHasPrefix(mutableKey, CFSTR("0x")) && CFStringGetLength(mutableKey) > 2) { CFStringDelete(mutableKey, CFRangeMake(0, 2)); } if (CFStringGetLength(mutableKey) == 1024/8*2) { CFRelease(preparedKey); preparedKey = APPEMKeyCreateFromHexKey(mutableKey); } CFRelease(mutableKey); SecItemImportExportKeyParameters params = {0}; params.version = SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION; params.flags = kSecKeyNoAccessControl; SecExternalItemType itemType = kSecItemTypePublicKey; SecExternalFormat externalFormat = kSecFormatPEMSequence; CFArrayRef tempArray = NULL; OSStatus oserr = noErr; // Set the key as extractable. Looking through the source code in SecImportExportUtils.cpp // it looks like this isn't handled, yet it seems to be documented to me. One day the code // may catch up, so I'm leaving this here to show the intention. CFNumberRef attributeFlags[1]; uint32 flag0value = CSSM_KEYATTR_EXTRACTABLE; CFNumberRef flag0 = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &flag0value); attributeFlags[0] = flag0; CFArrayRef keyAttributes = CFArrayCreate(kCFAllocatorDefault, (const void **)attributeFlags, 1, &kCFTypeArrayCallBacks); CFRelease(flag0); params.keyAttributes = keyAttributes; CFDataRef keyData = CFStringCreateExternalRepresentation(kCFAllocatorDefault, preparedKey, kCFStringEncodingUTF8, 0); CFRelease(preparedKey); oserr = SecItemImport(keyData, NULL, &externalFormat, &itemType, 0, ¶ms, NULL, &tempArray); CFRelease(keyAttributes); CFRelease(keyData); if (oserr != noErr) { CFStringRef errorString = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("Unable to import key. Error %d"), oserr); CFShow(errorString); CFRelease(errorString); return FALSE; } publicKeyRef = (SecKeyRef)CFArrayGetValueAtIndex(tempArray, 0); CFRetain(publicKeyRef); CFRelease(tempArray); return TRUE; }
static kern_return_t ModemOrSerialDeviceToDictProc(void *contextPtr, io_object_t interface, CFMutableDictionaryRef interfaceInfo) // This routine is called (via function pointer) by AddMatchingDevicesToArray // to add modem/serial-specific information for the modem/serial-like device // (which includes internal modems, built-in serial ports, USB serial adapters, // USB modems, and IrDA) specified by interface to the interfaceInfo dictionary. { #pragma unused(contextPtr) kern_return_t err; kern_return_t junk; CFMutableDictionaryRef interfaceDict; CFStringRef baseName; CFNumberRef supportsHold; assert(interface != 0 ); assert(interfaceInfo != NULL); interfaceDict = NULL; supportsHold = false; err = IORegistryEntryCreateCFProperties(interface, &interfaceDict, NULL, kNilOptions ); // Get IOTTYBaseName // Yetch. We specifically exclude ports named "irda" because otherwise the IrDA // ports on the original iMac (rev's A through D) show up as serial ports. Given // that only the rev A actually had an IrDA port, and Mac OS X doesn't even support // it, these ports definitely shouldn't be listed. if (err == 0 && CFDictionaryGetValueIfPresent(interfaceDict, CFSTR(kIOTTYBaseNameKey), (const void **) &baseName ) && ! CFEqual(baseName, CFSTR("irda")) ) { junk = CFQDictionarySetNumber(interfaceInfo, kSortOrderKey, kSerialSortOrder); assert(junk == 0); // kSCPropNetInterfaceDeviceName CFDictionarySetValue(interfaceInfo, kSCPropNetInterfaceDeviceName, CFDictionaryGetValue(interfaceDict, CFSTR(kIOTTYDeviceKey))); // kSCPropNetInterfaceHardware CFDictionarySetValue(interfaceInfo, kSCPropNetInterfaceHardware, kSCEntNetModem); // kSCPropNetInterfaceType CFDictionarySetValue(interfaceInfo, kSCPropNetInterfaceType, kSCValNetInterfaceTypePPP); // kSCPropNetInterfaceSubType CFDictionarySetValue(interfaceInfo, kSCPropNetInterfaceSubType, kSCValNetInterfaceSubTypePPPSerial); // "HardwareVariant" // A special hack for IrDA, modelled directly on the code from the // control panel. if ( CFStringHasPrefix(baseName, kMoreSCValNetInterfaceHardwareVariantIrDACOMM) ) { junk = CFQDictionarySetNumber(interfaceInfo, kSortOrderKey, kIrDASerialSortOrder); assert(junk == 0); CFDictionarySetValue(interfaceInfo, kMoreSCPropNetInterfaceHardwareVariant, kMoreSCValNetInterfaceHardwareVariantIrDACOMM); } // kSCPropNetInterfaceSupportsModemOnHold supportsHold = (CFNumberRef) IORegistryEntrySearchCFProperty(interface, kIOServicePlane, CFSTR("V92Modem"), NULL, kIORegistryIterateRecursively | kIORegistryIterateParents); if (supportsHold != NULL) { assert( CFGetTypeID(supportsHold) == CFNumberGetTypeID() ); CFDictionarySetValue(interfaceInfo, kSCPropNetInterfaceSupportsModemOnHold, supportsHold); } // kSCPropUserDefinedName set up by caller. } CFQRelease(interfaceDict); CFQRelease(supportsHold); return err; }
static CFStringRef CopyUserVisibleSlotName(CFStringRef slotName) // Translate the PCI card slot name into a user friendly number. // // Machine Slot Name (in numeric order, starting at 1) // --------- --------- // Beige G3 A1, B1, C1 // B&W G3, G4 (PCI Graphics) J12, J11, J10, J9 // G4 (AGP Graphics) A, B, C, D // G4 (Digital Audio)... 1, 2, 3, 4, 5 // ... and later ditto { CFStringRef result; CFStringRef slotPrefix; CFStringRef trimmedSlotName; UInt32 sysVer; Boolean tenTwoOrLater; assert(slotName != NULL); result = NULL; // not really necessary, but used for post-condition debug assert slotPrefix = NULL; trimmedSlotName = NULL; slotPrefix = CFSTR("SLOT-"); if ( CFStringHasPrefix(slotName, slotPrefix) ) { trimmedSlotName = CFStringCreateWithSubstring(NULL, slotName, CFRangeMake(CFStringGetLength(slotPrefix), CFStringGetLength(slotName) - CFStringGetLength(slotPrefix)) ); } if (trimmedSlotName == NULL) { trimmedSlotName = (CFStringRef) CFRetain(slotName); } // The Network preferences panel on 10.2 and later will translate // slot names into slot numbers. We replicate it's behaviour here. tenTwoOrLater = (Gestalt(gestaltSystemVersion, (SInt32 *) &sysVer) == noErr) && (sysVer >= 0x01020); if (tenTwoOrLater) { // Beige G3 if ( CFEqual(trimmedSlotName, CFSTR("A1")) ) { result = CFSTR("1"); } else if ( CFEqual(trimmedSlotName, CFSTR("B1")) ) { result = CFSTR("2"); } else if ( CFEqual(trimmedSlotName, CFSTR("C1")) ) { result = CFSTR("3"); // Blue and White G3, G4 (PCI Graphics) } else if ( CFEqual(trimmedSlotName, CFSTR("J12")) ) { result = CFSTR("1"); } else if ( CFEqual(trimmedSlotName, CFSTR("J11")) ) { result = CFSTR("2"); } else if ( CFEqual(trimmedSlotName, CFSTR("J10")) ) { result = CFSTR("3"); } else if ( CFEqual(trimmedSlotName, CFSTR("J9")) ) { result = CFSTR("4"); // G4 (AGP Graphics) } else if ( CFEqual(trimmedSlotName, CFSTR("A")) ) { result = CFSTR("1"); } else if ( CFEqual(trimmedSlotName, CFSTR("B")) ) { result = CFSTR("2"); } else if ( CFEqual(trimmedSlotName, CFSTR("C")) ) { result = CFSTR("3"); } else if ( CFEqual(trimmedSlotName, CFSTR("D")) ) { result = CFSTR("4"); // all later models } else { result = trimmedSlotName; } } else { result = trimmedSlotName; } CFRetain(result); CFQRelease(trimmedSlotName); assert(result != NULL); return result; }
Boolean DAMountContainsArgument( CFStringRef arguments, CFStringRef argument ) { CFBooleanRef argumentValue; CFBooleanRef argumentsValue; argumentsValue = NULL; if ( CFStringHasPrefix( argument, CFSTR( "no" ) ) ) { argument = CFStringCreateWithSubstring( kCFAllocatorDefault, argument, CFRangeMake( 2, CFStringGetLength( argument ) - 2 ) ); argumentValue = kCFBooleanFalse; } else { argument = CFRetain( argument ); argumentValue = kCFBooleanTrue; } if ( argument ) { CFArrayRef argumentList; CFIndex argumentListCount; CFIndex argumentListIndex; argumentList = CFStringCreateArrayBySeparatingStrings( kCFAllocatorDefault, arguments, CFSTR( "," ) ); if ( argumentList ) { argumentListCount = CFArrayGetCount( argumentList ); for ( argumentListIndex = 0; argumentListIndex < argumentListCount; argumentListIndex++ ) { CFStringRef compare; compare = CFArrayGetValueAtIndex( argumentList, argumentListIndex ); if ( compare ) { CFBooleanRef compareValue; if ( CFStringHasPrefix( compare, CFSTR( "no" ) ) ) { compare = CFStringCreateWithSubstring( kCFAllocatorDefault, compare, CFRangeMake( 2, CFStringGetLength( compare ) - 2 ) ); compareValue = kCFBooleanFalse; } else { compare = CFRetain( compare ); compareValue = kCFBooleanTrue; } if ( compare ) { if ( CFEqual( compare, CFSTR( FSTAB_RO ) ) ) { CFRelease( compare ); compare = CFRetain( kDAFileSystemMountArgumentNoWrite ); compareValue = compareValue; } if ( CFEqual( compare, CFSTR( FSTAB_RW ) ) ) { CFRelease( compare ); compare = CFRetain( kDAFileSystemMountArgumentNoWrite ); compareValue = ( compareValue == kCFBooleanTrue ) ? kCFBooleanFalse : kCFBooleanTrue; } } if ( compare ) { if ( CFEqual( argument, compare ) ) { argumentsValue = compareValue; } CFRelease( compare ); } } } CFRelease( argumentList ); } CFRelease( argument ); } return ( argumentValue == argumentsValue ) ? TRUE : FALSE; }
void configSet(CFMutableArrayRef config, CFStringRef key, CFStringRef value) { CFMutableStringRef pref; CFIndex configLen = CFArrayGetCount(config); CFIndex i; CFIndex n; CFMutableStringRef newValue; CFRange range; CFStringRef specialChars = CFSTR(" \"'$!|\\<>`{}[]"); boolean_t mustQuote = FALSE; /* create search prefix */ pref = CFStringCreateMutableCopy(NULL, 0, key); CFStringAppend(pref, CFSTR("=")); /* * create new / replacement value * * Note: Since the configuration file may be processed by a * shell script we need to ensure that, if needed, the * string is properly quoted. */ newValue = CFStringCreateMutableCopy(NULL, 0, value); n = CFStringGetLength(specialChars); for (i = 0; i < n; i++) { CFStringRef specialChar; specialChar = CFStringCreateWithSubstring(NULL, specialChars, CFRangeMake(i, 1)); range = CFStringFind(newValue, specialChar, 0); CFRelease(specialChar); if (range.location != kCFNotFound) { /* this string has at least one special character */ mustQuote = TRUE; break; } } if (mustQuote) { CFStringRef charsToQuote = CFSTR("\\\"$`"); /* * in addition to quoting the entire string we also need to escape the * space " " and backslash "\" characters */ n = CFStringGetLength(charsToQuote); for (i = 0; i < n; i++) { CFStringRef quoteChar; CFArrayRef matches; quoteChar = CFStringCreateWithSubstring(NULL, charsToQuote, CFRangeMake(i, 1)); range = CFRangeMake(0, CFStringGetLength(newValue)); matches = CFStringCreateArrayWithFindResults(NULL, newValue, quoteChar, range, 0); CFRelease(quoteChar); if (matches) { CFIndex j = CFArrayGetCount(matches); while (--j >= 0) { const CFRange *range; range = CFArrayGetValueAtIndex(matches, j); CFStringInsert(newValue, range->location, CFSTR("\\")); } CFRelease(matches); } } CFStringInsert(newValue, 0, CFSTR("\"")); CFStringAppend(newValue, CFSTR("\"")); } /* locate existing key */ for (i = 0; i < configLen; i++) { if (CFStringHasPrefix(CFArrayGetValueAtIndex(config, i), pref)) { break; } } CFStringAppend(pref, newValue); CFRelease(newValue); if (i < configLen) { /* if replacing an existing entry */ CFArraySetValueAtIndex(config, i, pref); } else { /* * if new entry, insert it just prior to the last (emtpy) * array element. */ CFArrayInsertValueAtIndex(config, configLen-1, pref); } CFRelease(pref); return; }
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; }
/* extract the principal from OpenDirectory */ int od_principal_for_user(pam_handle_t *pamh, const char *user, char **od_principal) { int retval = PAM_SERVICE_ERR; ODRecordRef record = NULL; CFStringRef principal = NULL; CFArrayRef authparts = NULL, vals = NULL; CFIndex i = 0, count = 0; if (NULL == user || NULL == od_principal) { openpam_log(PAM_LOG_DEBUG, "NULL argument passed"); retval = PAM_SERVICE_ERR; goto cleanup; } retval = od_record_create_cstring(pamh, &record, user); if (PAM_SUCCESS != retval) { openpam_log(PAM_LOG_DEBUG, "od_record_attribute_create_cfstring() failed"); goto cleanup; } retval = od_record_attribute_create_cfarray(record, kODAttributeTypeAuthenticationAuthority, &vals); if (PAM_SUCCESS != retval) { openpam_log(PAM_LOG_DEBUG, "od_record_attribute_create_cfarray() failed"); goto cleanup; } if (NULL == vals) { openpam_log(PAM_LOG_DEBUG, "no authauth availale for user."); retval = PAM_PERM_DENIED; goto cleanup; } count = CFArrayGetCount(vals); for (i = 0; i < count; i++) { const void *val = CFArrayGetValueAtIndex(vals, i); if (NULL == val || CFGetTypeID(val) != CFStringGetTypeID()) break; authparts = CFStringCreateArrayBySeparatingStrings(kCFAllocatorDefault, val, CFSTR(";")); if (NULL == authparts) continue; if ((CFArrayGetCount(authparts) < 5) || (CFStringCompare(CFArrayGetValueAtIndex(authparts, 1), CFSTR("Kerberosv5"), kCFCompareEqualTo)) || (CFStringHasPrefix(CFArrayGetValueAtIndex(authparts, 4), CFSTR("LKDC:")))) { if (NULL != authparts) { CFRelease(authparts); authparts = NULL; } continue; } else { break; } } if (NULL == authparts) { openpam_log(PAM_LOG_DEBUG, "No authentication authority returned"); retval = PAM_PERM_DENIED; goto cleanup; } principal = CFArrayGetValueAtIndex(authparts, 3); if (NULL == principal) { openpam_log(PAM_LOG_DEBUG, "no principal found in authentication authority"); retval = PAM_PERM_DENIED; goto cleanup; } retval = cfstring_to_cstring(principal, od_principal); if (PAM_SUCCESS != retval) { openpam_log(PAM_LOG_DEBUG, "cfstring_to_cstring() failed"); goto cleanup; } cleanup: if (PAM_SUCCESS != retval) { openpam_log(PAM_LOG_DEBUG, "failed: %d", retval); } if (NULL != record) { CFRelease(record); } if (NULL != authparts) { CFRelease(authparts); } if (NULL != vals) { CFRelease(vals); } return retval; }
__private_extern__ CFArrayRef _CFPreferencesCreateDomainList(CFStringRef userName, CFStringRef hostName) { CFAllocatorRef prefAlloc = __CFPreferencesAllocator(); CFArrayRef domains; CFMutableArrayRef marray; CFStringRef *cachedDomainKeys; CFPreferencesDomainRef *cachedDomains; SInt32 idx, cnt; CFStringRef suffix; UInt32 suffixLen; CFURLRef prefDir = _preferencesDirectoryForUserHost(userName, hostName); if (!prefDir) { return NULL; } if (hostName == kCFPreferencesAnyHost) { suffix = CFStringCreateWithCString(prefAlloc, ".plist", kCFStringEncodingASCII); } else if (hostName == kCFPreferencesCurrentHost) { CFStringRef hostID = _CFPreferencesGetByHostIdentifierString(); suffix = CFStringCreateWithFormat(prefAlloc, NULL, CFSTR(".%@.plist"), hostID); } else { suffix = CFStringCreateWithFormat(prefAlloc, NULL, CFSTR(".%@.plist"), hostName); // sketchy - this allows someone to create a domain list for an arbitrary hostname. } suffixLen = CFStringGetLength(suffix); domains = (CFArrayRef)CFURLCreatePropertyFromResource(prefAlloc, prefDir, kCFURLFileDirectoryContents, NULL); CFRelease(prefDir); if (domains){ marray = CFArrayCreateMutableCopy(prefAlloc, 0, domains); CFRelease(domains); } else { marray = CFArrayCreateMutable(prefAlloc, 0, & kCFTypeArrayCallBacks); } for (idx = CFArrayGetCount(marray)-1; idx >= 0; idx --) { CFURLRef url = (CFURLRef)CFArrayGetValueAtIndex(marray, idx); CFStringRef string = CFURLCopyFileSystemPath(url, kCFURLPOSIXPathStyle); if (!CFStringHasSuffix(string, suffix)) { CFArrayRemoveValueAtIndex(marray, idx); } else { CFStringRef dom = CFStringCreateWithSubstring(prefAlloc, string, CFRangeMake(0, CFStringGetLength(string) - suffixLen)); if (CFEqual(dom, CFSTR(".GlobalPreferences"))) { CFArraySetValueAtIndex(marray, idx, kCFPreferencesAnyApplication); } else { CFArraySetValueAtIndex(marray, idx, dom); } CFRelease(dom); } CFRelease(string); } CFRelease(suffix); // Now add any domains added in the cache; delete any that have been deleted in the cache __CFSpinLock(&domainCacheLock); if (!domainCache) { __CFSpinUnlock(&domainCacheLock); return marray; } cnt = CFDictionaryGetCount(domainCache); cachedDomainKeys = (CFStringRef *)CFAllocatorAllocate(prefAlloc, 2 * cnt * sizeof(CFStringRef), 0); cachedDomains = (CFPreferencesDomainRef *)(cachedDomainKeys + cnt); CFDictionaryGetKeysAndValues(domainCache, (const void **)cachedDomainKeys, (const void **)cachedDomains); __CFSpinUnlock(&domainCacheLock); suffix = _CFPreferencesCachePrefixForUserHost(userName, hostName); suffixLen = CFStringGetLength(suffix); for (idx = 0; idx < cnt; idx ++) { CFStringRef domainKey = cachedDomainKeys[idx]; CFPreferencesDomainRef domain = cachedDomains[idx]; CFStringRef domainName; CFIndex keyCount = 0; if (!CFStringHasPrefix(domainKey, suffix)) continue; domainName = CFStringCreateWithSubstring(prefAlloc, domainKey, CFRangeMake(suffixLen, CFStringGetLength(domainKey) - suffixLen)); if (CFEqual(domainName, CFSTR("*"))) { CFRelease(domainName); domainName = (CFStringRef)CFRetain(kCFPreferencesAnyApplication); } else if (CFEqual(domainName, kCFPreferencesCurrentApplication)) { CFRelease(domainName); domainName = (CFStringRef)CFRetain(_CFProcessNameString()); } CFDictionaryRef d = _CFPreferencesDomainDeepCopyDictionary(domain); keyCount = d ? CFDictionaryGetCount(d) : 0; if (keyCount) CFRelease(d); if (keyCount == 0) { // Domain was deleted SInt32 firstIndexOfValue = CFArrayGetFirstIndexOfValue(marray, CFRangeMake(0, CFArrayGetCount(marray)), domainName); if (0 <= firstIndexOfValue) { CFArrayRemoveValueAtIndex(marray, firstIndexOfValue); } } else if (!CFArrayContainsValue(marray, CFRangeMake(0, CFArrayGetCount(marray)), domainName)) { CFArrayAppendValue(marray, domainName); } CFRelease(domainName); } CFRelease(suffix); CFAllocatorDeallocate(prefAlloc, cachedDomainKeys); return marray; }
int checkVPNInterfaceOrServiceBlocked (const char *location, char *interface_buf) { // check to see if interface is captive: if so, bail if the interface is not ready. if (check_interface_captive_and_not_ready(gDynamicStore, interface_buf)) { // TODO: perhaps we should wait for a few seconds? return true; } // return 1, if this is a delete event, and; // TODO: add support for IPv6 <rdar://problem/5920237> // walk Setup:/Network/Service/* and check if there are service entries referencing this interface. e.g. Setup:/Network/Service/44DB8790-0177-4F17-8D4E-37F9413D1D87/Interface:DeviceName == interface, other_serv_found = 1 // Setup:/Network/Interface/"interface"/AirPort:'PowerEnable' == 0 || Setup:/Network/Interface/"interface"/IPv4 is missing, interf_down = 1 if (gDynamicStore) { CFStringRef interf_key; CFMutableArrayRef interf_keys; CFStringRef pattern; CFMutableArrayRef patterns; CFDictionaryRef dict = NULL; CFIndex i; const void * keys_q[128]; const void ** keys = keys_q; const void * values_q[128]; const void ** values = values_q; CFIndex n; CFStringRef vpn_if; int other_serv_found = 0, interf_down = 0; vpn_if = CFStringCreateWithCStringNoCopy(NULL, interface_buf, kCFStringEncodingASCII, kCFAllocatorNull); if (!vpn_if) { // if we could not initialize interface CFString syslog(LOG_NOTICE, "%s: failed to initialize interface CFString", location); goto done; } interf_keys = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); patterns = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); // get Setup:/Network/Interface/<vpn_if>/Airport interf_key = SCDynamicStoreKeyCreateNetworkInterfaceEntity(NULL, kSCDynamicStoreDomainSetup, vpn_if, kSCEntNetAirPort); CFArrayAppendValue(interf_keys, interf_key); CFRelease(interf_key); // get State:/Network/Interface/<vpn_if>/Airport interf_key = SCDynamicStoreKeyCreateNetworkInterfaceEntity(NULL, kSCDynamicStoreDomainState, vpn_if, kSCEntNetAirPort); CFArrayAppendValue(interf_keys, interf_key); CFRelease(interf_key); // get Setup:/Network/Service/*/Interface pattern = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL, kSCDynamicStoreDomainSetup, kSCCompAnyRegex, kSCEntNetInterface); CFArrayAppendValue(patterns, pattern); CFRelease(pattern); // get Setup:/Network/Service/*/IPv4 pattern = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL, kSCDynamicStoreDomainSetup, kSCCompAnyRegex, kSCEntNetIPv4); CFArrayAppendValue(patterns, pattern); CFRelease(pattern); dict = SCDynamicStoreCopyMultiple(gDynamicStore, interf_keys, patterns); CFRelease(interf_keys); CFRelease(patterns); if (!dict) { // if we could not access the SCDynamicStore syslog(LOG_NOTICE, "%s: failed to initialize SCDynamicStore dictionary", location); CFRelease(vpn_if); goto done; } // look for the service which matches the provided prefixes n = CFDictionaryGetCount(dict); if (n <= 0) { syslog(LOG_NOTICE, "%s: empty SCDynamicStore dictionary", location); CFRelease(vpn_if); goto done; } if (n > (CFIndex)(sizeof(keys_q) / sizeof(CFTypeRef))) { keys = CFAllocatorAllocate(NULL, n * sizeof(CFTypeRef), 0); values = CFAllocatorAllocate(NULL, n * sizeof(CFTypeRef), 0); } CFDictionaryGetKeysAndValues(dict, keys, values); for (i=0; i < n; i++) { CFStringRef s_key = (CFStringRef)keys[i]; CFDictionaryRef s_dict = (CFDictionaryRef)values[i]; CFStringRef s_if; if (!isA_CFString(s_key) || !isA_CFDictionary(s_dict)) { continue; } if (CFStringHasSuffix(s_key, kSCEntNetInterface)) { // is a Service Interface entity s_if = CFDictionaryGetValue(s_dict, kSCPropNetInterfaceDeviceName); if (isA_CFString(s_if) && CFEqual(vpn_if, s_if)) { CFArrayRef components; CFStringRef serviceIDRef = NULL, serviceKey = NULL; other_serv_found = 1; // extract service ID components = CFStringCreateArrayBySeparatingStrings(NULL, s_key, CFSTR("/")); if (CFArrayGetCount(components) > 3) { serviceIDRef = CFArrayGetValueAtIndex(components, 3); //if (new key) Setup:/Network/Service/service_id/IPv4 is missing, then interf_down = 1 serviceKey = SCDynamicStoreKeyCreateNetworkServiceEntity(0, kSCDynamicStoreDomainSetup, serviceIDRef, kSCEntNetIPv4); if (!serviceKey || !CFDictionaryGetValue(dict, serviceKey)) { syslog(LOG_NOTICE, "%s: detected disabled IPv4 Config", location); interf_down = 1; } if (serviceKey) CFRelease(serviceKey); } if (components) CFRelease(components); if (interf_down) break; } continue; } else if (CFStringHasSuffix(s_key, kSCEntNetAirPort)) { // Interface/<vpn_if>/Airport entity if (CFStringHasPrefix(s_key, kSCDynamicStoreDomainSetup)) { CFBooleanRef powerEnable = CFDictionaryGetValue(s_dict, kSCPropNetAirPortPowerEnabled); if (isA_CFBoolean(powerEnable) && CFEqual(powerEnable, kCFBooleanFalse)) { syslog(LOG_NOTICE, "%s: detected AirPort, PowerEnable == FALSE", location); interf_down = 1; break; } } else if (CFStringHasPrefix(s_key, kSCDynamicStoreDomainState)) { UInt16 temp; CFNumberRef airStatus = CFDictionaryGetValue(s_dict, CFSTR("Power Status")); if (isA_CFNumber(airStatus) && CFNumberGetValue(airStatus, kCFNumberShortType, &temp)) { if (temp ==0) { syslog(LOG_NOTICE, "%s: detected AirPort, PowerStatus == 0", location); } } } continue; } } if (vpn_if) CFRelease(vpn_if); if (keys != keys_q) { CFAllocatorDeallocate(NULL, keys); CFAllocatorDeallocate(NULL, values); } done : if (dict) CFRelease(dict); return (other_serv_found == 0 || interf_down == 1); } return 0; }