void SDMMD_USBMuxListenerSend(SDMMD_USBMuxListenerRef listener, struct USBMuxPacket **packet) { listener->ivars.semaphore = dispatch_semaphore_create(0x0); SDMMD_USBMuxSend(listener->ivars.socket, *packet); dispatch_semaphore_wait(listener->ivars.semaphore, (*packet)->timeout); CFMutableArrayRef updateWithRemove = CFArrayCreateMutableCopy(kCFAllocatorDefault, 0x0, listener->ivars.responses); struct USBMuxPacket *responsePacket = NULL; uint32_t removeCounter = 0x0; for (uint32_t i = 0x0; i < CFArrayGetCount(listener->ivars.responses); i++) { struct USBMuxPacket *response = (struct USBMuxPacket *)CFArrayGetValueAtIndex(listener->ivars.responses, i); if ((*packet)->body.tag == response->body.tag) { responsePacket = response; CFArrayRemoveValueAtIndex(updateWithRemove, i-removeCounter); removeCounter++; } } CFSafeRelease(listener->ivars.responses); listener->ivars.responses = CFArrayCreateMutableCopy(kCFAllocatorDefault, 0x0, updateWithRemove); CFSafeRelease(updateWithRemove); USBMuxPacketRelease(*packet); if (!responsePacket) { responsePacket = (struct USBMuxPacket *)calloc(0x1, sizeof(struct USBMuxPacket)); } *packet = responsePacket; dispatch_release(listener->ivars.semaphore); }
void SDMMD_USBMuxListenerSend(SDMMD_USBMuxListenerRef listener, struct USBMuxPacket **packet) { __block struct USBMuxPacket *block_packet = *packet; dispatch_sync(listener->ivars.operationQueue, ^{ // This semaphore will be signaled when a response is received listener->ivars.semaphore = dispatch_semaphore_create(0); // Send the outgoing packet SDMMD_USBMuxSend(listener->ivars.socket, block_packet); // Wait for a response-type packet to be received dispatch_semaphore_wait(listener->ivars.semaphore, block_packet->timeout); CFMutableArrayRef updateWithRemove = CFArrayCreateMutableCopy(kCFAllocatorDefault, 0, listener->ivars.responses); // Search responses for a packet that matches the one sent struct USBMuxPacket *responsePacket = NULL; uint32_t removeCounter = 0; for (uint32_t i = 0; i < CFArrayGetCount(listener->ivars.responses); i++) { struct USBMuxPacket *response = (struct USBMuxPacket *)CFArrayGetValueAtIndex(listener->ivars.responses, i); if ((*packet)->body.tag == response->body.tag) { // Equal tags indicate response to request if (responsePacket) { // Found additional response, destroy old one USBMuxPacketRelease(responsePacket); } // Each matching packet is removed from the responses list responsePacket = response; CFArrayRemoveValueAtIndex(updateWithRemove, i - removeCounter); removeCounter++; } } if (responsePacket == NULL) { // Didn't find an appropriate response, initialize an empty packet to return responsePacket = (struct USBMuxPacket *)calloc(1, sizeof(struct USBMuxPacket)); } CFSafeRelease(listener->ivars.responses); listener->ivars.responses = CFArrayCreateMutableCopy(kCFAllocatorDefault, 0, updateWithRemove); CFSafeRelease(updateWithRemove); // Destroy sent packet USBMuxPacketRelease(block_packet); // Return response packet to caller block_packet = responsePacket; // Discard "waiting for response" semaphore dispatch_release(listener->ivars.semaphore); });
static void _serviceOrder_remove(SCNetworkSetRef set, SCNetworkServiceRef service) { CFMutableArrayRef newOrder; CFArrayRef order; CFStringRef serviceID; order = SCNetworkSetGetServiceOrder(set); if (order == NULL) { return; } serviceID = SCNetworkServiceGetServiceID(service); newOrder = CFArrayCreateMutableCopy(NULL, 0, order); while (TRUE) { CFIndex i; i = CFArrayGetFirstIndexOfValue(newOrder, CFRangeMake(0, CFArrayGetCount(newOrder)), serviceID); if (i == kCFNotFound) { break; } CFArrayRemoveValueAtIndex(newOrder, i); } (void) SCNetworkSetSetServiceOrder(set, newOrder); CFRelease(newOrder); return; }
static CFArrayRef SecTaskCopyAccessGroups(SecTaskRef task) { #if CHECK_ENTITLEMENTS CFStringRef appID = SecTaskCopyStringForEntitlement(task, kSecEntitlementApplicationIdentifier); CFArrayRef groups = SecTaskCopyArrayOfStringsForEntitlement(task, kSecEntitlementKeychainAccessGroups); if (appID) { if (groups) { CFMutableArrayRef nGroups = CFArrayCreateMutableCopy( CFGetAllocator(groups), CFArrayGetCount(groups) + 1, groups); CFArrayAppendValue(nGroups, appID); CFRelease(groups); groups = nGroups; } else { groups = CFArrayCreate(CFGetAllocator(task), (const void **)&appID, 1, &kCFTypeArrayCallBacks); } CFRelease(appID); } #else CFArrayRef groups = SecAccessGroupsGetCurrent(); if (groups) CFRetain(groups); #endif return groups; }
static void appendPrefixLen(CFMutableDictionaryRef dict, struct sockaddr_in6 *sin6) { register u_int8_t *name = &sin6->sin6_addr.s6_addr[0]; CFNumberRef prefixLen; CFArrayRef prefixLens; CFMutableArrayRef newPrefixLens; register int byte; register int bit; int plen = 0; for (byte = 0; byte < sizeof(struct in6_addr); byte++, plen += 8) { if (name[byte] != 0xff) { break; } } if (byte == sizeof(struct in6_addr)) { goto append; } for (bit = 7; bit != 0; bit--, plen++) { if (!(name[byte] & (1 << bit))) { break; } } for (; bit != 0; bit--) { if (name[byte] & (1 << bit)) { plen = 0; goto append; } } byte++; for (; byte < sizeof(struct in6_addr); byte++) { if (name[byte]) { plen = 0; goto append; } } append : prefixLens = CFDictionaryGetValue(dict, kSCPropNetIPv6PrefixLength); if (prefixLens) { newPrefixLens = CFArrayCreateMutableCopy(NULL, 0, prefixLens); } else { newPrefixLens = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); } prefixLen = CFNumberCreate(NULL, kCFNumberIntType, &plen); CFArrayAppendValue(newPrefixLens, prefixLen); CFRelease(prefixLen); CFDictionarySetValue(dict, kSCPropNetIPv6PrefixLength, newPrefixLens); CFRelease(newPrefixLens); return; }
static void appendAddress(CFMutableDictionaryRef dict, CFStringRef key, struct sockaddr_in6 *sin6) { CFStringRef addr; CFArrayRef addrs; CFMutableArrayRef newAddrs; char str[64]; addrs = CFDictionaryGetValue(dict, key); if (addrs) { newAddrs = CFArrayCreateMutableCopy(NULL, 0, addrs); } else { newAddrs = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); } if (inet_ntop(AF_INET6, (const void *)&sin6->sin6_addr, str, sizeof(str)) == NULL) { SCLog(TRUE, LOG_ERR, CFSTR("inet_ntop() failed: %s"), strerror(errno)); str[0] = '\0'; } addr = CFStringCreateWithFormat(NULL, NULL, CFSTR("%s"), str); CFArrayAppendValue(newAddrs, addr); CFRelease(addr); CFDictionarySetValue(dict, key, newAddrs); CFRelease(newAddrs); return; }
CFMutableArrayRef get_device_product_version_parts(AMDeviceRef device) { CFStringRef version = AMDeviceCopyValue(device, 0, CFSTR("ProductVersion")); CFArrayRef parts = CFStringCreateArrayBySeparatingStrings(NULL, version, CFSTR(".")); CFMutableArrayRef result = CFArrayCreateMutableCopy(NULL, CFArrayGetCount(parts), parts); CFRelease(version); CFRelease(parts); return result; }
/* * Obtain an array of the certificates in a timestamp response. Elements of the * returned array are SecCertificateRefs. The caller must CFRelease the returned * array. This timestamp is an authenticated timestamp provided by * a timestamping authority. * * Returns errSecParam if the CMS message was not signed or if signerIndex * is greater than the number of signers of the message minus one. It returns * errSecItemNotFound if no certificates were found. * * This cannot be called until after CMSDecoderFinalizeMessage() is called. */ OSStatus CMSDecoderCopySignerTimestampCertificates( CMSDecoderRef cmsDecoder, size_t signerIndex, /* usually 0 */ CFArrayRef *certificateRefs) /* RETURNED */ { OSStatus status = errSecParam; SecCmsMessageRef cmsg = NULL; SecCmsSignedDataRef signedData = NULL; int numContentInfos = 0; CFIndex tsn = 0; bool good = false; require(cmsDecoder && certificateRefs, xit); require_noerr(CMSDecoderGetCmsMessage(cmsDecoder, &cmsg), xit); numContentInfos = SecCmsMessageContentLevelCount(cmsg); for (int dex = 0; !signedData && dex < numContentInfos; dex++) { SecCmsContentInfoRef ci = SecCmsMessageContentLevel(cmsg, dex); SECOidTag tag = SecCmsContentInfoGetContentTypeTag(ci); if (tag == SEC_OID_PKCS7_SIGNED_DATA) if ((signedData = SecCmsSignedDataRef(SecCmsContentInfoGetContent(ci)))) if (SecCmsSignerInfoRef signerInfo = SecCmsSignedDataGetSignerInfo(signedData, (int)signerIndex)) { CFArrayRef certList = SecCmsSignerInfoGetTimestampCertList(signerInfo); require_action(certList, xit, status = errSecItemNotFound); CFMutableArrayRef certs = CFArrayCreateMutableCopy(kCFAllocatorDefault, CFArrayGetCount(certList), certList); if(certs){ //reorder certificates: tsn = CFArrayGetCount(certs); good = tsn > 0 && Security::CodeSigning::isAppleCA(SecCertificateRef(CFArrayGetValueAtIndex(certs, tsn-1))); if ( good == false ) { //change TS certificate ordering. for (CFIndex n = 0; n < tsn; n++) { if (SecCertificateRef tsRoot = SecCertificateRef(CFArrayGetValueAtIndex(certs, n))) if ((good = Security::CodeSigning::isAppleCA(tsRoot))) { CFArrayExchangeValuesAtIndices(certs, n, tsn-1); break; } } } *certificateRefs = CFArrayCreateCopy(kCFAllocatorDefault, certs); CFRelease(certs); status = errSecSuccess; } break; } } xit: return status; }
kim_error kim_os_selection_hints_forget_identity (kim_selection_hints in_selection_hints) { kim_error err = KIM_NO_ERROR; CFArrayRef old_hints_array = NULL; CFMutableArrayRef new_hints_array = NULL; CFIndex count = 0; CFIndex i = 0; if (!err && !in_selection_hints) { err = check_error (KIM_NULL_PARAMETER_ERR); } if (!err) { err = kim_os_selection_hints_get_selection_hints_array (&old_hints_array); } if (!err) { new_hints_array = CFArrayCreateMutableCopy (kCFAllocatorDefault, 0, old_hints_array); if (!new_hints_array) { err = KIM_OUT_OF_MEMORY_ERR; } } if (!err) { count = CFArrayGetCount (new_hints_array); } for (i = 0; !err && i < count; i++) { CFDictionaryRef dictionary = NULL; kim_boolean hints_equal = 0; dictionary = CFArrayGetValueAtIndex (new_hints_array, i); if (!dictionary) { err = KIM_OUT_OF_MEMORY_ERR; } if (!err && CFGetTypeID (dictionary) != CFDictionaryGetTypeID ()) { kim_debug_printf ("%s: Malformed entry in hints array.", __FUNCTION__); continue; /* skip entries which aren't dictionaries */ } if (!err) { err = kim_os_selection_hints_compare_to_dictionary (in_selection_hints, dictionary, &hints_equal); } if (!err && hints_equal) { CFArrayRemoveValueAtIndex (new_hints_array, i); i--; /* back up one index so we don't skip */ count = CFArrayGetCount (new_hints_array); /* count changed */ } } if (!err) { err = kim_os_selection_hints_set_selection_hints_array (new_hints_array); } if (new_hints_array) { CFRelease (new_hints_array); } return check_error (err); }
__private_extern__ void link_add(const char *if_name) { CFStringRef interface; CFStringRef cacheKey; CFDictionaryRef dict; CFMutableDictionaryRef newDict = NULL; CFArrayRef ifList; CFMutableArrayRef newIFList = NULL; interface = CFStringCreateWithCString(NULL, if_name, kCFStringEncodingMacRoman); cacheKey = SCDynamicStoreKeyCreateNetworkInterface(NULL, kSCDynamicStoreDomainState); dict = cache_SCDynamicStoreCopyValue(store, cacheKey); if (dict) { if (isA_CFDictionary(dict)) { newDict = CFDictionaryCreateMutableCopy(NULL, 0, dict); ifList = CFDictionaryGetValue(newDict, kSCPropNetInterfaces); if (isA_CFArray(ifList)) { newIFList = CFArrayCreateMutableCopy(NULL, 0, ifList); } } CFRelease(dict); } if (!newDict) { newDict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); } if (!newIFList) { newIFList = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); } if (CFArrayContainsValue(newIFList, CFRangeMake(0, CFArrayGetCount(newIFList)), interface) == FALSE) { CFArrayAppendValue(newIFList, interface); CFDictionarySetValue(newDict, kSCPropNetInterfaces, newIFList); } cache_SCDynamicStoreSetValue(store, cacheKey, newDict); link_update_status(if_name, TRUE); #ifdef KEV_DL_LINK_QUALITY_METRIC_CHANGED link_update_quality_metric(if_name); #endif /* KEV_DL_LINK_QUALITY_METRIC_CHANGED */ CFRelease(cacheKey); CFRelease(interface); if (newDict) CFRelease(newDict); if (newIFList) CFRelease(newIFList); return; }
/** * Do the two texts share a Substring which is at least half the length of * the longer text? * This speedup can produce non-minimal diffs. * @param text1 First CFStringRef. * @param text2 Second CFStringRef. * @param diffTimeout Time limit for diff. * @return Five element String array, containing the prefix of text1, the * suffix of text1, the prefix of text2, the suffix of text2 and the * common middle. Or NULL if there was no match. */ CFArrayRef diff_halfMatchCreate(CFStringRef text1, CFStringRef text2, const float diffTimeout) { if (diffTimeout <= 0) { // Don't risk returning a non-optimal diff if we have unlimited time. return NULL; } CFStringRef longtext = CFStringGetLength(text1) > CFStringGetLength(text2) ? text1 : text2; CFStringRef shorttext = CFStringGetLength(text1) > CFStringGetLength(text2) ? text2 : text1; if (CFStringGetLength(longtext) < 4 || CFStringGetLength(shorttext) * 2 < CFStringGetLength(longtext)) { return NULL; // Pointless. } // First check if the second quarter is the seed for a half-match. CFArrayRef hm1 = diff_halfMatchICreate(longtext, shorttext, (CFStringGetLength(longtext) + 3) / 4); // Check again based on the third quarter. CFArrayRef hm2 = diff_halfMatchICreate(longtext, shorttext, (CFStringGetLength(longtext) + 1) / 2); CFArrayRef hm; if (hm1 == NULL && hm2 == NULL) { return NULL; } else if (hm2 == NULL) { hm = CFRetain(hm1); } else if (hm1 == NULL) { hm = CFRetain(hm2); } else { // Both matched. Select the longest. hm = CFStringGetLength(CFArrayGetValueAtIndex(hm1, 4)) > CFStringGetLength(CFArrayGetValueAtIndex(hm2, 4)) ? CFRetain(hm1) : CFRetain(hm2); } if (hm1 != NULL) { CFRelease(hm1); } if (hm2 != NULL) { CFRelease(hm2); } // A half-match was found, sort out the return data. if (CFStringGetLength(text1) > CFStringGetLength(text2)) { return hm; //return new CFStringRef[]{hm[0], hm[1], hm[2], hm[3], hm[4]}; } else { // { hm[0], hm[1], hm[2], hm[3], hm[4] } // => { hm[2], hm[3], hm[0], hm[1], hm[4] } CFMutableArrayRef hm_mutable = CFArrayCreateMutableCopy(kCFAllocatorDefault, CFArrayGetCount(hm), hm); CFRelease(hm); CFArrayExchangeValuesAtIndices(hm_mutable, 0, 2); CFArrayExchangeValuesAtIndices(hm_mutable, 1, 3); return hm_mutable; } }
STATIC bool load_DUID_info(void) { CFDataRef duid; CFDictionaryRef duid_ia; CFDataRef host_uuid; CFArrayRef ia_list; duid_ia = my_CFPropertyListCreateFromFile(DUID_IA_FILE); if (isA_CFDictionary(duid_ia) == NULL) { goto done; } duid = CFDictionaryGetValue(duid_ia, kDUIDKey); if (isA_CFData(duid) == NULL) { goto done; } ia_list = CFDictionaryGetValue(duid_ia, kIAIDListKey); ia_list = isA_CFArray(ia_list); if (ia_list != NULL) { int count; int i; count = CFArrayGetCount(ia_list); for (i = 0; i < count; i++) { CFStringRef name = CFArrayGetValueAtIndex(ia_list, i); if (isA_CFString(name) == NULL) { /* invalid property */ ia_list = NULL; break; } } } host_uuid = CFDictionaryGetValue(duid_ia, kHostUUIDKey); if (isA_CFData(host_uuid) != NULL && CFDataGetLength(host_uuid) == sizeof(uuid_t)) { CFDataRef our_UUID; our_UUID = HostUUIDGet(); if (our_UUID != NULL && CFEqual(host_uuid, our_UUID) == FALSE) { syslog(LOG_NOTICE, "DHCPDUID: ignoring DUID - host UUID doesn't match"); goto done; } } S_DUID = CFRetain(duid); if (ia_list != NULL) { S_IAIDList = CFArrayCreateMutableCopy(NULL, 0, ia_list); } done: my_CFRelease(&duid_ia); return (S_DUID != NULL); }
__private_extern__ void link_remove(const char *if_name) { CFStringRef interface; CFStringRef cacheKey; CFDictionaryRef dict; CFMutableDictionaryRef newDict = NULL; CFArrayRef ifList; CFMutableArrayRef newIFList = NULL; CFIndex i; interface = CFStringCreateWithCString(NULL, if_name, kCFStringEncodingMacRoman); cacheKey = SCDynamicStoreKeyCreateNetworkInterface(NULL, kSCDynamicStoreDomainState); dict = cache_SCDynamicStoreCopyValue(store, cacheKey); if (dict) { if (isA_CFDictionary(dict)) { newDict = CFDictionaryCreateMutableCopy(NULL, 0, dict); ifList = CFDictionaryGetValue(newDict, kSCPropNetInterfaces); if (isA_CFArray(ifList)) { newIFList = CFArrayCreateMutableCopy(NULL, 0, ifList); } } CFRelease(dict); } if (!newIFList || ((i = CFArrayGetFirstIndexOfValue(newIFList, CFRangeMake(0, CFArrayGetCount(newIFList)), interface)) == kCFNotFound) ) { /* we're not tracking this interface */ goto done; } CFArrayRemoveValueAtIndex(newIFList, i); CFDictionarySetValue(newDict, kSCPropNetInterfaces, newIFList); cache_SCDynamicStoreSetValue(store, cacheKey, newDict); interface_remove(if_name); done: CFRelease(cacheKey); CFRelease(interface); if (newDict) CFRelease(newDict); if (newIFList) CFRelease(newIFList); return; }
static void __DAStageProbe( DADiskRef disk ) { /* * We commence the "probe" stage if the conditions are right. */ if ( DAUnitGetState( disk, kDAUnitStateCommandActive ) == FALSE ) { CFMutableArrayRef candidates; candidates = CFArrayCreateMutableCopy( kCFAllocatorDefault, 0, gDAFileSystemProbeList ); if ( candidates ) { CFNumberRef size; /* * Determine whether the disk is formatted. */ size = DADiskGetDescription( disk, kDADiskDescriptionMediaSizeKey ); if ( size ) { if ( ___CFNumberGetIntegerValue( size ) == 0 ) { CFArrayRemoveAllValues( candidates ); } } /* * Commence the probe. */ CFRetain( disk ); DADiskSetFileSystem( disk, NULL ); DADiskSetContext( disk, candidates ); DADiskSetState( disk, kDADiskStateStagedProbe, TRUE ); DADiskSetState( disk, kDADiskStateCommandActive, TRUE ); DAUnitSetState( disk, kDAUnitStateCommandActive, TRUE ); __DAStageProbeCallback( -1, NULL, NULL, NULL, disk ); CFRelease( candidates ); } } }
static void __show_service_protocols(SCNetworkServiceRef service, const char *prefix, Boolean skipEmpty) { CFIndex i; CFIndex n; CFArrayRef protocols; protocols = SCNetworkServiceCopyProtocols(service); if (protocols == NULL) { return; } n = CFArrayGetCount(protocols); if (n > 1) { CFMutableArrayRef sorted; sorted = CFArrayCreateMutableCopy(NULL, 0, protocols); CFArraySortValues(sorted, CFRangeMake(0, n), _compare_protocols, NULL); CFRelease(protocols); protocols = sorted; } for (i = 0; i < n; i++) { CFStringRef description; SCNetworkProtocolRef protocol; protocol = CFArrayGetValueAtIndex(protocols, i); description = _protocol_description(protocol, skipEmpty); if (description != NULL) { CFStringRef protocolType; protocolType = SCNetworkProtocolGetProtocolType(protocol); SCPrint(TRUE, stdout, CFSTR("%s%@%*s : %@\n"), prefix, protocolType, (int)(sizeof("Interface") - CFStringGetLength(protocolType) - 1), "", description); CFRelease(description); } } CFRelease(protocols); return; }
OSStatus SecCmsSignedDataAddCertList(SecCmsSignedDataRef sigd, CFArrayRef certlist) { PORT_Assert(certlist != NULL); if (certlist == NULL) return SECFailure; if (!sigd->certs) sigd->certs = CFArrayCreateMutableCopy(NULL, 0, certlist); else { CFRange certlistRange = { 0, CFArrayGetCount(certlist) }; CFArrayAppendArray(sigd->certs, certlist, certlistRange); } return SECSuccess; }
static CFArrayRef service_order_copy_all(CFDictionaryRef services, CFArrayRef service_order) { const void * keys_q[N_QUICK]; const void ** keys = keys_q; CFIndex i; CFIndex n_order; CFIndex n_services; CFMutableArrayRef order; // ensure that we process all services in order n_services = isA_CFDictionary(services) ? CFDictionaryGetCount(services) : 0; if (n_services == 0) { // if no services return NULL; } // ensure that we process all services in order n_order = isA_CFArray(service_order) ? CFArrayGetCount(service_order) : 0; if (n_order > 0) { order = CFArrayCreateMutableCopy(NULL, 0, service_order); } else { order = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); } if (n_services > (CFIndex)(sizeof(keys_q) / sizeof(CFTypeRef))) { keys = CFAllocatorAllocate(NULL, n_services * sizeof(CFTypeRef), 0); } CFDictionaryGetKeysAndValues(services, keys, NULL); for (i = 0; i < n_services; i++) { CFStringRef serviceID = (CFStringRef)keys[i]; if (!CFArrayContainsValue(order, CFRangeMake(0, n_order), serviceID)) { CFArrayAppendValue(order, serviceID); n_order++; } } if (keys != keys_q) { CFAllocatorDeallocate(NULL, keys); } return order; }
static CFStringRef copy_next_name(CFStringRef name) { CFArrayRef components; CFIndex n; CFMutableArrayRef newComponents; SInt32 suffix = 2; if (name == NULL) { return NULL; } components = CFStringCreateArrayBySeparatingStrings(NULL, name, CFSTR(" ")); if (components != NULL) { newComponents = CFArrayCreateMutableCopy(NULL, 0, components); CFRelease(components); } else { newComponents = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); CFArrayAppendValue(newComponents, name); } n = CFArrayGetCount(newComponents); if (n > 1) { CFStringRef str; str = CFArrayGetValueAtIndex(newComponents, n - 1); suffix = CFStringGetIntValue(str); if (suffix++ > 0) { CFArrayRemoveValueAtIndex(newComponents, n - 1); } else { suffix = 2; } } name = CFStringCreateWithFormat(NULL, NULL, CFSTR("%d"), (int)suffix); CFArrayAppendValue(newComponents, name); CFRelease(name); name = CFStringCreateByCombiningStrings(NULL, newComponents, CFSTR(" ")); CFRelease(newComponents); return name; }
static int load_cert(URLContext *h) { TLSContext *c = h->priv_data; int ret = 0; CFArrayRef certArray = NULL; CFArrayRef keyArray = NULL; SecIdentityRef id = NULL; CFMutableArrayRef outArray = NULL; if ((ret = import_pem(h, c->tls_shared.cert_file, &certArray)) < 0) goto end; if ((ret = import_pem(h, c->tls_shared.key_file, &keyArray)) < 0) goto end; if (!(id = SecIdentityCreate(kCFAllocatorDefault, (SecCertificateRef)CFArrayGetValueAtIndex(certArray, 0), (SecKeyRef)CFArrayGetValueAtIndex(keyArray, 0)))) { ret = AVERROR_UNKNOWN; goto end; } if (!(outArray = CFArrayCreateMutableCopy(kCFAllocatorDefault, 0, certArray))) { ret = AVERROR(ENOMEM); goto end; } CFArraySetValueAtIndex(outArray, 0, id); SSLSetCertificate(c->ssl_context, outArray); end: if (certArray) CFRelease(certArray); if (keyArray) CFRelease(keyArray); if (outArray) CFRelease(outArray); if (id) CFRelease(id); return ret; }
/* * * copySchedulePowerChangeArrays * */ static void copyScheduledPowerChangeArrays(void) { #if !TARGET_OS_EMBEDDED CFArrayRef tmp; SCPreferencesRef prefs; PowerEventBehavior *this_behavior; int i; prefs = SCPreferencesCreate(0, CFSTR("PM-configd-AutoWake"), CFSTR(kIOPMAutoWakePrefsPath)); if(!prefs) return; activeEventCnt = 0; // Loop through all sleep, wake, shutdown powerbehaviors for(i=0; i<kBehaviorsCount; i++) { this_behavior = behaviors[i]; if(this_behavior->array) { CFRelease(this_behavior->array); this_behavior->array = NULL; } tmp = isA_CFArray(SCPreferencesGetValue(prefs, this_behavior->title)); if(tmp && (0 < CFArrayGetCount(tmp))) { this_behavior->array = CFArrayCreateMutableCopy(0, 0, tmp); activeEventCnt += CFArrayGetCount(tmp); } else { this_behavior->array = NULL; } } CFRelease(prefs); #endif }
static void appendScopeID(CFMutableDictionaryRef dict, struct sockaddr_in6 *sin6) { CFNumberRef scope; CFArrayRef scopes; CFMutableArrayRef newScopes; scopes = CFDictionaryGetValue(dict, kSCPropNetIPv6ScopeID); if (scopes) { newScopes = CFArrayCreateMutableCopy(NULL, 0, scopes); } else { newScopes = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); } scope = CFNumberCreate(NULL, kCFNumberSInt32Type, &sin6->sin6_scope_id); CFArrayAppendValue(newScopes, scope); CFRelease(scope); CFDictionarySetValue(dict, kSCPropNetIPv6ScopeID, newScopes); CFRelease(newScopes); return; }
static void appendFlags(CFMutableDictionaryRef dict, int flags6) { CFArrayRef flags; CFMutableArrayRef newFlags; CFNumberRef v6Flags; flags = CFDictionaryGetValue(dict, kSCPropNetIPv6Flags); if (flags) { newFlags = CFArrayCreateMutableCopy(NULL, 0, flags); } else { newFlags = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); } v6Flags = CFNumberCreate(NULL, kCFNumberIntType, &flags6); CFArrayAppendValue(newFlags, v6Flags); CFRelease(v6Flags); CFDictionarySetValue(dict, kSCPropNetIPv6Flags, newFlags); CFRelease(newFlags); return; }
static bool SecPathBuilderComputeDetails(SecPathBuilderRef builder) { SecPVCRef pvc = &builder->path; #if 0 if (!builder->caller_wants_details) { SecPVCSetPath(pvc, builder->bestPath, NULL); pvc->result = builder->rejectScore == INTPTR_MAX; builder->state = SecPathBuilderReportResult; return true; } #endif CFIndex ix, pathLength = SecCertificatePathGetCount(builder->bestPath); CFMutableArrayRef details = CFArrayCreateMutableCopy(kCFAllocatorDefault, pathLength, builder->leafDetails); SecPVCSetPath(pvc, builder->bestPath, details); /* Only report on EV stuff if the bestPath actually was valid for EV. */ pvc->optionally_ev = builder->bestPathIsEV; pvc->info = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); for (ix = 1; ix < pathLength; ++ix) { CFMutableDictionaryRef certDetail = CFDictionaryCreateMutable( kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFArrayAppendValue(details, certDetail); CFRelease(certDetail); SecPVCParentCertificateChecks(pvc, ix); SecPVCBlackListedKeyChecks(pvc, ix); } builder->state = SecPathBuilderReportResult; bool completed = SecPVCPathChecks(pvc); /* Reject the certificate if it was accepted before but we failed it now. */ if (builder->rejectScore == INTPTR_MAX && !pvc->result) { builder->rejectScore = 0; } return completed; }
std::string getKextLinked(const void *value, const CFStringRef key) { std::string result; auto links = (CFArrayRef)CFDictionaryGetValue((CFDictionaryRef)value, key); if (links == nullptr) { // Very core. return result; } CFIndex count = CFArrayGetCount(links); if (count == 0) { // Odd error case, there was a linked value, but an empty list. return result; } auto link_indexes = CFArrayCreateMutableCopy(NULL, count, links); CFArraySortValues(link_indexes, CFRangeMake(0, count), (CFComparatorFunction)CFNumberCompare, NULL); for (int i = 0; i < count; i++) { int link; CFNumberGetValue((CFNumberRef)CFArrayGetValueAtIndex(link_indexes, i), kCFNumberSInt32Type, (void *)&link); if (i > 0) { result += " "; } result += TEXT(link); } CFRelease(link_indexes); // Return in kextstat format for linked extensions. return "<" + result + ">"; }
__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; }
/* druPromptForDevice Interactively asks the user to select a device from the devices which are currently attached. If only one device is connected, the device is automatically chosen and nothing is printed. The optional filter function is called to filter devices. If you wish to suppress a device, the filter function should return 0. The returned device is retained by this routine. */ DRDeviceRef druPromptForDevice(char *promptString, druDeviceFilterProc filter) { CFArrayRef deviceList = DRCopyDeviceArray(); CFIndex deviceCount = CFArrayGetCount(deviceList); DRDeviceRef device; CFIndex selection; char userInput[10]; /* Can't proceed without at least one drive. */ if (deviceCount == 0) { printf("Sorry, no CD/DVD drives were found.\n"); exit(1); } /* Filter the list. */ if (filter != NULL) { CFMutableArrayRef filteredList = CFArrayCreateMutableCopy(NULL,0,deviceList); for (selection=deviceCount-1; selection>=0; --selection) if ((*filter)((DRDeviceRef)CFArrayGetValueAtIndex(filteredList,selection)) == 0) CFArrayRemoveValueAtIndex(filteredList,selection); CFRelease(deviceList); deviceList = filteredList; deviceCount = CFArrayGetCount(deviceList); } /* Can't proceed without at least one drive. */ if (deviceCount == 0) { printf("Sorry, no eligible drives were found.\n"); exit(1); } /* If there's only one device, which is actually true for many machines (those with an internal CD burner and no external burners attached) then the choice is obvious, and we don't need to display a menu. */ if (deviceCount == 1) { device = (DRDeviceRef)CFArrayGetValueAtIndex(deviceList,0); CFRetain(device); CFRelease(deviceList); return device; } /* Display a menu of devices. */ printf("Available devices:\n"); druDisplayDeviceList(deviceList); /* Display the prompt. */ if (promptString == NULL) promptString = "Please select a device:"; printf("%s ", promptString); fflush(stdout); /* Get user input. */ userInput[0] = 0; selection = atoi(fgets(userInput,sizeof(userInput),stdin)) - 1; if (selection < 0 || selection >= deviceCount) { printf("Aborted.\n"); exit(1); } /* Return the selected device. */ device = (DRDeviceRef)CFArrayGetValueAtIndex(deviceList,selection); CFRetain(device); CFRelease(deviceList); return device; }
/* * We need to separate the share name and any path component from the URL. * URL "smb://*****:*****@server" no share name or path. * URL "smb://*****:*****@server/"no share name or path. * URL "smb://*****:*****@server/share" just a share name. * URL "smb://*****:*****@server/share/path" share name and path. * * The Share name and Path name will not begin with a slash. * smb://server/ntfs share = ntfs path = NULL * smb://ntfs/dir1/dir2 share = ntfs path = dir1/dir2 * smb://server/OPEN%2fSPACE/dir1 share = OPEN%2fSPACE path = dir1 */ static int GetShareAndPathFromURL(CFURLRef url, CFStringRef *out_share, CFStringRef *out_path) { Boolean isAbsolute; CFArrayRef userArray = NULL; CFMutableArrayRef userArrayM = NULL; CFStringRef share = CFURLCopyStrictPath(url, &isAbsolute); CFStringRef path = NULL; *out_share = NULL; *out_path = NULL; /* We have an empty share treat it like no share */ if (share && (CFStringGetLength(share) == 0)) { CFRelease(share); share = NULL; } /* Since there is no share name we have nothing left to do. */ if (!share) return 0; userArray = CFStringCreateArrayBySeparatingStrings(NULL, share, CFSTR("/")); if (userArray && (CFArrayGetCount(userArray) > 1)) userArrayM = CFArrayCreateMutableCopy(NULL, CFArrayGetCount(userArray), userArray); if (userArray) CFRelease(userArray); if (userArrayM) { CFMutableStringRef newshare; /* Just in case something goes wrong */ newshare = CFStringCreateMutableCopy(NULL, 0, (CFStringRef)CFArrayGetValueAtIndex(userArrayM, 0)); if (newshare) { CFStringTrim(newshare, CFSTR("/")); /* Remove any trailing slashes */ CreateStringByReplacingPercentEscapesUTF8((CFStringRef *) &newshare, CFSTR("/")); } CFArrayRemoveValueAtIndex(userArrayM, 0); /* Now remove any trailing slashes */ path = CFStringCreateByCombiningStrings(NULL, userArrayM, CFSTR("/")); if (path && (CFStringGetLength(path) == 0)) { CFRelease(path); /* Empty path remove it */ path = NULL; } if (path) { CFMutableStringRef newpath = CFStringCreateMutableCopy(NULL, 0, path); if (newpath) { CFStringTrim(newpath, CFSTR("/")); /* Remove any trailing slashes */ CFRelease(path); path = newpath; } } if (path) { CreateStringByReplacingPercentEscapesUTF8(&path, CFSTR("/")); LogCFString(path, "Path", __FUNCTION__, __LINE__); } CFRelease(userArrayM); /* Something went wrong use the original value */ if (newshare) { CFRelease(share); share = newshare; } } else CreateStringByReplacingPercentEscapesUTF8(&share, CFSTR("/")); /* * The above routines will not un-precent escape out slashes. We only allow for the cases * where the share name is a single slash. Slashes are treated as delemiters in the path name. * So if the share name has a single 0x2f then make it a slash. This means you can't have * a share name whos name is 0x2f, not likley to happen. */ if (share && ( kCFCompareEqualTo == CFStringCompare (share, CFSTR("0x2f"), kCFCompareCaseInsensitive) )) { CFRelease(share); share = CFStringCreateCopy(NULL, CFSTR("/")); } if (share && (CFStringGetLength(share) >= SMB_MAXSHARENAMELEN)) { CFRelease(share); if (path) CFRelease(path); return ENAMETOOLONG; } *out_share = share; *out_path = path; return 0; }
// Set the entire blacklist array, removing any existing entries void APSetBlacklist(CFArrayRef hashArray) { if (blacklist != NULL) CFRelease(blacklist); blacklist = CFArrayCreateMutableCopy(kCFAllocatorDefault, 0, hashArray); }
static void _serviceOrder_add(SCNetworkSetRef set, SCNetworkServiceRef service) { CFIndex i; CFIndex n; CFMutableArrayRef newOrder; CFArrayRef order; CFStringRef serviceID; CFIndex serviceOrder; SCNetworkSetPrivateRef setPrivate = (SCNetworkSetPrivateRef)set; CFIndex slot; order = SCNetworkSetGetServiceOrder(set); if (order != NULL) { newOrder = CFArrayCreateMutableCopy(NULL, 0, order); } else { newOrder = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); } assert(newOrder != NULL); n = CFArrayGetCount(newOrder); serviceID = SCNetworkServiceGetServiceID(service); if (CFArrayContainsValue(newOrder, CFRangeMake(0, n), serviceID)) { // if serviceID already present goto done; } serviceOrder = _serviceOrder(service); slot = 0; for (i = 0; i < n; i++) { int slotOrder; SCNetworkServiceRef slotService; CFStringRef slotServiceID; slotServiceID = CFArrayGetValueAtIndex(newOrder, i); if (!isA_CFString(slotServiceID)) { // if bad prefs continue; } slotService = SCNetworkServiceCopy(setPrivate->prefs, slotServiceID); if (slotService == NULL) { // if serviceID not valid continue; } slotOrder = _serviceOrder(slotService); if (serviceOrder >= slotOrder) { // add the service *after* this one slot = i + 1; } CFRelease(slotService); } CFArrayInsertValueAtIndex(newOrder, slot, serviceID); (void) SCNetworkSetSetServiceOrder(set, newOrder); done : CFRelease(newOrder); return; }
SCNetworkServiceRef SCNetworkSetCopySelectedVPNService(SCNetworkSetRef set) { CFIndex i; CFIndex n; SCNetworkServiceRef selected = NULL; CFArrayRef services; CFMutableArrayRef services_vpn = NULL; if (!isA_SCNetworkSet(set)) { _SCErrorSet(kSCStatusInvalidArgument); return NULL; } services = SCNetworkSetCopyServices(set); if (services != NULL) { n = CFArrayGetCount(services); for (i = 0; i < n; i++) { SCNetworkServiceRef service; service = CFArrayGetValueAtIndex(services, i); if (!SCNetworkServiceGetEnabled(service)) { // if not enabled continue; } if (!_SCNetworkServiceIsVPN(service)) { // if not VPN service continue; } if (services_vpn == NULL) { services_vpn = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); } CFArrayAppendValue(services_vpn, service); } CFRelease(services); } if (services_vpn == NULL) { // if no VPN services return NULL; } n = CFArrayGetCount(services_vpn); if (n > 1) { CFArrayRef order; CFMutableArrayRef sorted; order = SCNetworkSetGetServiceOrder(set); sorted = CFArrayCreateMutableCopy(NULL, 0, services_vpn); CFArraySortValues(sorted, CFRangeMake(0, CFArrayGetCount(sorted)), _SCNetworkServiceCompare, (void *)order); CFRelease(services_vpn); services_vpn = sorted; } #if TARGET_OS_IPHONE if (n > 1) { CFStringRef serviceID_prefs; #define VPN_PREFERENCES CFSTR("com.apple.mobilevpn") #define VPN_SERVICE_ID CFSTR("activeVPNID") CFPreferencesAppSynchronize(VPN_PREFERENCES); serviceID_prefs = CFPreferencesCopyAppValue(VPN_SERVICE_ID, VPN_PREFERENCES); if (serviceID_prefs != NULL) { for (i = 0; i < n; i++) { SCNetworkServiceRef service; CFStringRef serviceID; service = CFArrayGetValueAtIndex(services_vpn, i); serviceID = SCNetworkServiceGetServiceID(service); if (CFEqual(serviceID, serviceID_prefs)) { selected = service; CFRetain(selected); break; } } CFRelease(serviceID_prefs); } } #endif // TARGET_OS_IPHONE if (selected == NULL) { selected = CFArrayGetValueAtIndex(services_vpn, 0); CFRetain(selected); } CFRelease(services_vpn); return selected; }