Пример #1
0
bool	CACFArray::InsertCFType(UInt32 inIndex, const CFTypeRef inItem)
{
	bool theAnswer = false;
	
	if((mCFArray != NULL) && mMutable)
	{
		if(inIndex < GetNumberItems())
		{
			CFArrayInsertValueAtIndex(mCFArray, inIndex, inItem);
		}
		else
		{
			CFArrayAppendValue(mCFArray, inItem);
		}
		theAnswer = true;
	}
	
	return theAnswer;
}
Пример #2
0
int InstallLoginLogoutNotifiers(CFRunLoopSourceRef* RunloopSourceReturned)
{
    SCDynamicStoreContext DynamicStoreContext = { 0, NULL, NULL, NULL, NULL };
    SCDynamicStoreRef DynamicStoreCommunicationMechanism = NULL;
    CFStringRef KeyRepresentingConsoleUserNameChange = NULL;
    CFMutableArrayRef ArrayOfNotificationKeys;
    Boolean Result;

    *RunloopSourceReturned = NULL;
    DynamicStoreCommunicationMechanism = SCDynamicStoreCreate(NULL, CFSTR("logKext"), LoginLogoutCallBackFunction, &DynamicStoreContext);

    if (DynamicStoreCommunicationMechanism == NULL)
        return(-1); //unable to create dynamic store.

    KeyRepresentingConsoleUserNameChange = SCDynamicStoreKeyCreateConsoleUser(NULL);
    if (KeyRepresentingConsoleUserNameChange == NULL)
    {
        CFRelease(DynamicStoreCommunicationMechanism);
        return(-2);
    }

    ArrayOfNotificationKeys = CFArrayCreateMutable(NULL, (CFIndex)1, &kCFTypeArrayCallBacks);
    if (ArrayOfNotificationKeys == NULL)
    {
        CFRelease(DynamicStoreCommunicationMechanism);
        CFRelease(KeyRepresentingConsoleUserNameChange);
        return(-3);
    }
    CFArrayAppendValue(ArrayOfNotificationKeys, KeyRepresentingConsoleUserNameChange);

     Result = SCDynamicStoreSetNotificationKeys(DynamicStoreCommunicationMechanism, ArrayOfNotificationKeys, NULL);
     CFRelease(ArrayOfNotificationKeys);
     CFRelease(KeyRepresentingConsoleUserNameChange);

     if (Result == FALSE) //unable to add keys to dynamic store.
     {
        CFRelease(DynamicStoreCommunicationMechanism);
        return(-4);
     }

	*RunloopSourceReturned = SCDynamicStoreCreateRunLoopSource(NULL, DynamicStoreCommunicationMechanism, (CFIndex) 0);
    return(0);
}
Пример #3
0
CUI_EXPORT int
pam_select_credential(pam_handle_t *pamh, int flags)
{
    int rc;
    CUIControllerRef controller = NULL;
    CFDictionaryRef attributes = NULL;
    CFDictionaryRef credAttributes = NULL;
    CFMutableArrayRef creds = NULL;
    CUICredentialRef selectedCred = NULL;
    char *user = NULL, *pass = NULL;
    __block CFIndex defaultCredentialIndex = kCFNotFound;

    controller = CUIControllerCreate(kCFAllocatorDefault, kCUIUsageScenarioLogin, kCUIUsageFlagsConsole);
    if (controller == NULL) {
        rc = PAM_SERVICE_ERR;
        goto cleanup;
    }
   
    CUIControllerSetContext(controller, pamh);
 
    creds = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
    if (creds == NULL) {
        rc = PAM_BUF_ERR;
        goto cleanup;
    }

    rc = _PAMSetTargetNameWithService(pamh, controller);
    if (rc != PAM_SUCCESS)
        goto cleanup;
    
    rc = _PAMCreateAttributesFromHandle(pamh, &attributes);
    if (rc == PAM_BUF_ERR)
        goto cleanup;
    else if (attributes)
        CUIControllerSetAttributes(controller, attributes);
    
    CUIControllerEnumerateCredentials(controller, ^(CUICredentialRef cred, Boolean isDefault, CFErrorRef err) {
        if (cred) {
            if (isDefault)
                defaultCredentialIndex = CFArrayGetCount(creds);
            CFArrayAppendValue(creds, cred);
        }
    });
Пример #4
0
static void iohidmanager_hid_append_matching_dictionary(
      CFMutableArrayRef array,
      uint32_t page, uint32_t use)
{
   CFMutableDictionaryRef matcher = CFDictionaryCreateMutable(
         kCFAllocatorDefault, 0,
         &kCFTypeDictionaryKeyCallBacks,
         &kCFTypeDictionaryValueCallBacks);
   CFNumberRef pagen = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &page);
   CFNumberRef usen  = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &use);

   CFDictionarySetValue(matcher, CFSTR(kIOHIDDeviceUsagePageKey), pagen);
   CFDictionarySetValue(matcher, CFSTR(kIOHIDDeviceUsageKey), usen);
   CFArrayAppendValue(array, matcher);

   CFRelease(pagen);
   CFRelease(usen);
   CFRelease(matcher);
}
int main(int argc, char **argv)
{
	bool quiet = false;
	
	int arg;
	while ((arg = getopt(argc, argv, "qh")) != -1) {
		switch (arg) {
			case 'q':
				quiet = true;
				break;
			case 'h':
				usage(argv);
		}
	}
	
	unsigned numCerts = argc - optind;
	if(numCerts == 0) {
		usage(argv);
	}
	CFMutableArrayRef certArray = CFArrayCreateMutable(NULL, 0, 
		&kCFTypeArrayCallBacks);
	for(int dex=optind; dex<argc; dex++) {
		SecCertificateRef certRef = certFromFile(argv[dex]);
		if(certRef == NULL) {
			exit(1);
		}
		CFArrayAppendValue(certArray, certRef);
		CFRelease(certRef);
	}
	
	OSStatus ortn;
	SecPolicyRef policyRef = NULL;
	ortn = SecPolicyCopy(CSSM_CERT_X_509v3, &CSSMOID_APPLE_TP_SSL, &policyRef);
	if(ortn) {
		cssmPerror("SecPolicyCopy", ortn);
		exit(1);
	}
	
	int ourRtn = doTest(certArray, policyRef, quiet);
	CFRelease(policyRef);
	CFRelease(certArray);
	return ourRtn;
}
void diff_mungeHelper(CFStringRef token, CFMutableArrayRef tokenArray, CFMutableDictionaryRef tokenHash, CFMutableStringRef chars) {
  #define diff_UniCharMax (~(UniChar)0x00)
  
  CFIndex hash;
  
  if (CFDictionaryGetValueIfPresent(tokenHash, token, (const void **)&hash)) {
    const UniChar hashChar = (UniChar)hash;
    CFStringAppendCharacters(chars, &hashChar, 1);
  } else {
    CFArrayAppendValue(tokenArray, token);
    hash = CFArrayGetCount(tokenArray) - 1;
    check_string(hash <= diff_UniCharMax, "Hash value has exceeded UniCharMax!");
    CFDictionaryAddValue(tokenHash, token, (void *)hash);
    const UniChar hashChar = (UniChar)hash;
    CFStringAppendCharacters(chars, &hashChar, 1);
  }
  
  #undef diff_UniCharMax
}
void AddEventDictionary(CFDictionaryRef eventDict, CFMutableDictionaryRef allEventsDictionary, NetBrowserInfo* key)
{
    CFMutableArrayRef eventsForBrowser = (CFMutableArrayRef)CFDictionaryGetValue(allEventsDictionary, key);

    if (!eventsForBrowser) // We have no events for this browser yet, lets add him.
    {
        eventsForBrowser = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
        CFDictionarySetValue(allEventsDictionary, key, eventsForBrowser);
        asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s creating a new array", sPluginIdentifier, __FUNCTION__);
    }
    else
    {
        asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s Incrementing refcount", sPluginIdentifier, __FUNCTION__);
        CFRetain(eventsForBrowser);
    }

    CFArrayAppendValue(eventsForBrowser, eventDict);
    CFRelease(eventsForBrowser);
}
Пример #8
0
/*
 * Function: EAPOLClientConfigurationCopyLoginWindowProfiles
 *
 * Purpose:
 *   Return the list of profiles configured for LoginWindow mode on the
 *   specified BSD network interface (e.g. "en0", "en1").
 *
 * Returns:
 *   NULL if no profiles are defined, non-NULL non-empty array of profiles
 *   otherwise.
 */
CFArrayRef /* of EAPOLClientProfileRef */
EAPOLClientConfigurationCopyLoginWindowProfiles(EAPOLClientConfigurationRef cfg,
						CFStringRef if_name)
{
    int				count;
    int				i;
    CFDictionaryRef		dict;
    CFArrayRef			profile_ids;
    CFMutableArrayRef		ret_profiles = NULL;

    dict = get_eapol_configuration(get_sc_prefs(cfg), if_name, NULL);
    if (dict == NULL) {
	goto done;
    }
    profile_ids = CFDictionaryGetValue(dict, kLoginWindowProfileIDs);
    if (isA_CFArray(profile_ids) == NULL) {
	goto done;
    }
    count = CFArrayGetCount(profile_ids);
    if (count == 0) {
	goto done;
    }
    ret_profiles = CFArrayCreateMutable(NULL, count, &kCFTypeArrayCallBacks);
    for (i = 0; i < count; i++) {
	CFStringRef		profileID;
	EAPOLClientProfileRef	profile;

	profileID = (CFStringRef)CFArrayGetValueAtIndex(profile_ids, i);
	if (isA_CFString(profileID) == NULL) {
	    continue;
	}
	profile = EAPOLClientConfigurationGetProfileWithID(cfg, profileID);
	if (profile != NULL) {
	    CFArrayAppendValue(ret_profiles, profile);
	}
    }
    if (CFArrayGetCount(ret_profiles) == 0) {
	my_CFRelease(&ret_profiles);
    }

 done:
    return (ret_profiles);
}
Пример #9
0
bool
CAuthAuthority::AddValue( const char *inAuthAuthorityStr )
{
	bool added = false;
	CFMutableDictionaryRef aaDict = dsConvertAuthAuthorityToCFDict( inAuthAuthorityStr );
	if ( aaDict != NULL )
	{
		if ( mValueArray == NULL )
			mValueArray = CFArrayCreateMutable( kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks );
		
		if ( mValueArray != NULL ) {
			CFArrayAppendValue( mValueArray, aaDict );
			added = true;
		}
		CFRelease( aaDict );
	}
	
	return added;
}
Пример #10
0
// The callback function that we'll eventually supply to MIDIInputPortCreate
static void RbMIDIReadProc(const MIDIPacketList* packetList, void* readProcRefCon, void* srcConnRefCon)
{
    if( pthread_mutex_lock(&mutex) != 0 )
    {
        // uh oh
        // Not much we can do
        return;
    }
    
    MIDIPacket* current_packet = (MIDIPacket*) packetList->packet;

    unsigned int j;
    for( j = 0; j < packetList->numPackets; ++j )
    {
        RbMIDIPacket* rb_packet = (RbMIDIPacket*) malloc( sizeof(RbMIDIPacket) );
        
        if( rb_packet == NULL )
        {
            fprintf(stderr, "Failed to allocate memory for RbMIDIPacket!\n");
            abort();
        }
        
        rb_packet->timeStamp = current_packet->timeStamp;
        rb_packet->length = current_packet->length;
        
        size_t size = sizeof(Byte) * rb_packet->length;
        rb_packet->data = (Byte*) malloc( size );
        
        if( rb_packet->data == NULL )
        {
            fprintf(stderr, "Failed to allocate memory for RbMIDIPacket data!\n");
            abort();
        }
        
        memcpy(rb_packet->data, current_packet->data, size);
        
        CFArrayAppendValue(midi_data, rb_packet);
        
        current_packet = MIDIPacketNext(current_packet);
    }
    
    pthread_mutex_unlock(&mutex);
}
Пример #11
0
bool decode(ArgumentDecoder* decoder, RetainPtr<CFArrayRef>& result)
{
    uint64_t size;
    if (!decoder->decodeUInt64(size))
        return false;

    RetainPtr<CFMutableArrayRef> array(AdoptCF, CFArrayCreateMutable(0, 0, &kCFTypeArrayCallBacks));

    for (size_t i = 0; i < size; ++i) {
        RetainPtr<CFTypeRef> element;
        if (!decode(decoder, element))
            return false;

        CFArrayAppendValue(array.get(), element.get());
    }

    result.adoptCF(array.leakRef());
    return true;
}
void ResourceRequest::doUpdatePlatformRequest()
{
    CFMutableURLRequestRef cfRequest;

    RetainPtr<CFURLRef> url(AdoptCF, ResourceRequest::url().createCFURL());
    RetainPtr<CFURLRef> firstPartyForCookies(AdoptCF, ResourceRequest::firstPartyForCookies().createCFURL());
    if (m_cfRequest) {
        cfRequest = CFURLRequestCreateMutableCopy(0, m_cfRequest.get());
        CFURLRequestSetURL(cfRequest, url.get());
        CFURLRequestSetMainDocumentURL(cfRequest, firstPartyForCookies.get());
        CFURLRequestSetCachePolicy(cfRequest, (CFURLRequestCachePolicy)cachePolicy());
        CFURLRequestSetTimeoutInterval(cfRequest, timeoutInterval());
    } else {
        cfRequest = CFURLRequestCreateMutable(0, url.get(), (CFURLRequestCachePolicy)cachePolicy(), timeoutInterval(), firstPartyForCookies.get());
    }

    RetainPtr<CFStringRef> requestMethod(AdoptCF, httpMethod().createCFString());
    CFURLRequestSetHTTPRequestMethod(cfRequest, requestMethod.get());

    addHeadersFromHashMap(cfRequest, httpHeaderFields());
    WebCore::setHTTPBody(cfRequest, httpBody());
    CFURLRequestSetShouldHandleHTTPCookies(cfRequest, allowHTTPCookies());

    unsigned fallbackCount = m_responseContentDispositionEncodingFallbackArray.size();
    RetainPtr<CFMutableArrayRef> encodingFallbacks(AdoptCF, CFArrayCreateMutable(kCFAllocatorDefault, fallbackCount, 0));
    for (unsigned i = 0; i != fallbackCount; ++i) {
        RetainPtr<CFStringRef> encodingName(AdoptCF, m_responseContentDispositionEncodingFallbackArray[i].createCFString());
        CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding(encodingName.get());
        if (encoding != kCFStringEncodingInvalidId)
            CFArrayAppendValue(encodingFallbacks.get(), reinterpret_cast<const void*>(encoding));
    }
    setContentDispositionEncodingFallbackArray(cfRequest, encodingFallbacks.get());

    if (m_cfRequest) {
        RetainPtr<CFHTTPCookieStorageRef> cookieStorage(AdoptCF, CFURLRequestCopyHTTPCookieStorage(m_cfRequest.get()));
        if (cookieStorage)
            CFURLRequestSetHTTPCookieStorage(cfRequest, cookieStorage.get());
        CFURLRequestSetHTTPCookieStorageAcceptPolicy(cfRequest, CFURLRequestGetHTTPCookieStorageAcceptPolicy(m_cfRequest.get()));
        CFURLRequestSetSSLProperties(cfRequest, CFURLRequestGetSSLProperties(m_cfRequest.get()));
    }

    m_cfRequest.adoptCF(cfRequest);
}
Пример #13
0
/**************************************************************************
 *                              find_top_level
 */
static CFIndex find_top_level(IOHIDDeviceRef hid_device, CFMutableArrayRef main_elements)
{
    CFArrayRef      elements;
    CFIndex         total = 0;

    TRACE("hid_device %s\n", debugstr_device(hid_device));

    if (!hid_device)
        return 0;

    elements = IOHIDDeviceCopyMatchingElements(hid_device, NULL, 0);

    if (elements)
    {
        CFIndex i, count = CFArrayGetCount(elements);
        for (i = 0; i < count; i++)
        {
            IOHIDElementRef element = (IOHIDElementRef)CFArrayGetValueAtIndex(elements, i);
            int type = IOHIDElementGetType(element);

            TRACE("element %s\n", debugstr_element(element));

            /* Check for top-level gaming device collections */
            if (type == kIOHIDElementTypeCollection && IOHIDElementGetParent(element) == 0)
            {
                int usage_page = IOHIDElementGetUsagePage(element);
                int usage = IOHIDElementGetUsage(element);

                if (usage_page == kHIDPage_GenericDesktop &&
                    (usage == kHIDUsage_GD_Joystick || usage == kHIDUsage_GD_GamePad))
                {
                    CFArrayAppendValue(main_elements, element);
                    total++;
                }
            }
        }
        CFRelease(elements);
    }

    TRACE("-> total %d\n", (int)total);
    return total;
}
/*
 * Obtain an array of all of the certificates in a message. Elements of the
 * returned array are SecCertificateRefs. The caller must CFRelease the returned
 * array.
 * This cannot be called until after CMSDecoderFinalizeMessage() is called.
 */
OSStatus CMSDecoderCopyAllCerts(
                                CMSDecoderRef		cmsDecoder,
                                CFArrayRef			*certs)					/* RETURNED */
{
	if((cmsDecoder == NULL) || (certs == NULL)) {
		return errSecParam;
	}
	if(cmsDecoder->decState != DS_Final) {
		return errSecParam;
	}
	if(cmsDecoder->signedData == NULL) {
		/* message wasn't signed */
		*certs = NULL;
		return errSecSuccess;
	}
	
	/* NULL_terminated array of CSSM_DATA ptrs */
	CSSM_DATA_PTR *cssmCerts = SecCmsSignedDataGetCertificateList(cmsDecoder->signedData);
	if((cssmCerts == NULL) || (*cssmCerts == NULL)) {
		*certs = NULL;
		return errSecSuccess;
	}
	
	CFMutableArrayRef allCerts = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
	CSSM_DATA_PTR *cssmCert;
	for(cssmCert=cssmCerts; *cssmCert!=NULL; cssmCert++) {
		OSStatus ortn;
		SecCertificateRef cfCert;
		ortn = SecCertificateCreateFromData(*cssmCert,
                                            CSSM_CERT_X_509v3, CSSM_CERT_ENCODING_DER,
                                            &cfCert);
		if(ortn) {
			CFRelease(allCerts);
			return ortn;
		}
		CFArrayAppendValue(allCerts, cfCert);
		/* the array holds the only needed refcount */
		CFRelease(cfCert);
	}
	*certs = allCerts;
	return errSecSuccess;
}
static bool decodeCertificateChain(Decoder& decoder, RetainPtr<CFArrayRef>& certificateChain)
{
    uint64_t size;
    if (!decoder.decode(size))
        return false;

    auto array = adoptCF(CFArrayCreateMutable(0, 0, &kCFTypeArrayCallBacks));

    for (size_t i = 0; i < size; ++i) {
        RetainPtr<CFDataRef> data;
        if (!decodeCFData(decoder, data))
            return false;

        auto certificate = adoptCF(SecCertificateCreateWithData(0, data.get()));
        CFArrayAppendValue(array.get(), certificate.get());
    }

    certificateChain = WTFMove(array);
    return true;
}
  // [
  //   {directory, [file, file, ...]}
  //   {directory, [file, file, ...]}
  //   ...
  // ]
  file_monitor(spdlog::logger& logger,
               const std::vector<std::pair<std::string, std::vector<std::string>>>& targets,
               const callback& callback) : logger_(logger),
                                           callback_(callback),
                                           directories_(CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks)),
                                           stream_(nullptr) {
    if (directories_) {
      for (const auto& target : targets) {
        if (auto directory = CFStringCreateWithCString(kCFAllocatorDefault,
                                                       target.first.c_str(),
                                                       kCFStringEncodingUTF8)) {
          CFArrayAppendValue(directories_, directory);
          CFRelease(directory);

          files_ = target.second;
        }
      }
      register_stream();
    }
  }
CFErrorRef accumulate_data(CFMutableArrayRef *a, CFDataRef d) {
	if (!*a) {
		*a = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
		if (!*a) {
			return GetNoMemoryError();
		}
	}
	CFDataRef dc = CFDataCreateCopy(NULL, d);
	if (!dc) {
		return GetNoMemoryError();
	}
	CFIndex c = CFArrayGetCount(*a);
	CFArrayAppendValue(*a, dc);
	CFRelease(dc);
	if (CFArrayGetCount(*a) != c+1) {
		return GetNoMemoryError();
	}
	
	return NULL;
}
__private_extern__ CFMutableArrayRef __CFArrayCreateMutableCopy0(CFAllocatorRef allocator, CFIndex capacity, CFArrayRef array) {
    CFMutableArrayRef result;
    const CFArrayCallBacks *cb;
    CFIndex idx, numValues = CFArrayGetCount(array);
    UInt32 flags;
    if (CF_IS_OBJC(__kCFArrayTypeID, array)) {
	cb = &kCFTypeArrayCallBacks;
    }
    else {
	cb = __CFArrayGetCallBacks(array);
    }
    flags = __kCFArrayDeque;
    result = (CFMutableArrayRef)__CFArrayInit(allocator, flags, capacity, cb);
    if (0 == capacity) _CFArraySetCapacity(result, numValues);
    for (idx = 0; idx < numValues; idx++) {
	const void *value = CFArrayGetValueAtIndex(array, idx);
	CFArrayAppendValue(result, value);
    }
    return result;
}
Пример #19
0
void SecPathBuilderSetCanAccessNetwork(SecPathBuilderRef builder, bool allow) {
    if (builder->canAccessNetwork != allow) {
        builder->canAccessNetwork = allow;
        if (allow) {
            secdebug("http", "network access re-enabled by policy");
            /* re-enabling network_access re-adds kSecCAIssuerSource as
               a parent source. */
            CFArrayAppendValue(builder->parentSources, &kSecCAIssuerSource);
        } else {
            secdebug("http", "network access disabled by policy");
            /* disabling network_access removes kSecCAIssuerSource from
               the list of parent sources. */
            CFIndex ix = CFArrayGetFirstIndexOfValue(builder->parentSources,
                CFRangeMake(0, CFArrayGetCount(builder->parentSources)),
                &kSecCAIssuerSource);
            if (ix >= 0)
                CFArrayRemoveValueAtIndex(builder->parentSources, ix);
        }
    }
}
Пример #20
0
CF_EXPORT CFArrayRef CFPlugInFindFactoriesForPlugInTypeInPlugIn(CFUUIDRef typeID, CFPlugInRef plugIn) {
    CFArrayRef array = _CFPFactoryFindForType(typeID);
    CFMutableArrayRef result = NULL;

    if (array) {
        SInt32 i, c = CFArrayGetCount(array);
        _CFPFactory *factory;
        
        // Use default allocator
        result = CFArrayCreateMutable(kCFAllocatorSystemDefault, 0, &kCFTypeArrayCallBacks);

        for (i=0; i<c; i++) {
            factory = (_CFPFactory *)CFArrayGetValueAtIndex(array, i);
            if (_CFPFactoryGetPlugIn(factory) == plugIn) {
                CFArrayAppendValue(result, _CFPFactoryGetFactoryID(factory));
            }
        }
    }
    return result;
}
Пример #21
0
static OSStatus
_EAPSecIdentityCreateCertificateTrustChain(SecIdentityRef identity,
					   CFArrayRef * ret_chain)
{
    SecCertificateRef		cert = NULL;
    CFArrayRef 			certs;
    SecPolicyRef		policy = NULL;
    OSStatus			status;
    SecTrustRef 		trust = NULL;
    SecTrustResultType 		trust_result;

    *ret_chain = NULL;
    ok(policy = SecPolicyCreateBasicX509(), "SecPolicyCreateBasicX509");
    ok_status(status = SecIdentityCopyCertificate(identity, &cert), "SecIdentityCopyCertificate");
    certs = CFArrayCreate(NULL, (const void **)&cert,
			  1, &kCFTypeArrayCallBacks);
    CFReleaseNull(cert);
    ok_status(status = SecTrustCreateWithCertificates(certs, policy, &trust),
        "SecTrustCreateWithCertificates");
    CFReleaseNull(certs);
    ok_status(status = SecTrustEvaluate(trust, &trust_result), "SecTrustEvaluate");
    {
	CFMutableArrayRef	array;
	CFIndex			count = SecTrustGetCertificateCount(trust);
	CFIndex			i;

	isnt(count, 0, "SecTrustGetCertificateCount is nonzero");
	array = CFArrayCreateMutable(NULL, count, &kCFTypeArrayCallBacks);
	for (i = 0; i < count; i++) {
	    SecCertificateRef	s;

	    s = SecTrustGetCertificateAtIndex(trust, i);
	    CFArrayAppendValue(array, s);
	}
	*ret_chain = array;
    }

    CFReleaseNull(trust);
    CFReleaseNull(policy);
    return (status);
}
Пример #22
0
/* Extract public SecKeyRef from Certificate Chain */
static
int sslCopyPeerPubKey(const SSLCertificate *certchain,
                      SecKeyRef            *pubKey)
{
    int err;
    check(pubKey);
    SecTrustRef trust = NULL;
    const SSLCertificate *cert;
    CFMutableArrayRef certArray = NULL;
    CFDataRef certData = NULL;
    SecCertificateRef cfCert = NULL;

    err = errSSLInternal;

    certArray = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
    cert = certchain;
    while(cert) {
        require((certData = CFDataCreate(kCFAllocatorDefault, cert->derCert.data, cert->derCert.length)), out);
        require((cfCert = SecCertificateCreateWithData(kCFAllocatorDefault, certData)), out);
        CFArrayAppendValue(certArray, cfCert);
        CFReleaseNull(cfCert);
        CFReleaseNull(certData);
        cert=cert->next;
    }

    require_noerr((err=SecTrustCreateWithCertificates(certArray, NULL, &trust)), out);
    SecKeyRef key = SecTrustCopyPublicKey(trust);
    require_action(key, out, err=-9808); // errSSLBadCert

    *pubKey = key;

    err = errSecSuccess;

out:
    CFReleaseSafe(certData);
    CFReleaseSafe(cfCert);
    CFReleaseSafe(trust);
    CFReleaseSafe(certArray);

    return err;
}
static void writeXMLValue(CFTypeRef context, void *xmlDomain, CFStringRef key, CFTypeRef value) {
    _CFXMLPreferencesDomain *domain = (_CFXMLPreferencesDomain *)xmlDomain;
    const void *existing = NULL;

    __CFLock(&domain->_lock);
    if (domain->_domainDict == NULL) {
        _loadXMLDomainIfStale((CFURLRef )context, domain);
    }

	// check to see if the value is the same
	// if (1) the key is present AND value is !NULL and equal to existing, do nothing, or
	// if (2) the key is not present AND value is NULL, do nothing
	// these things are no-ops, and should not dirty the domain
    if (CFDictionaryGetValueIfPresent(domain->_domainDict, key, &existing)) {
	if (NULL != value && (existing == value || CFEqual(existing, value))) {
	    __CFUnlock(&domain->_lock);
	    return;
	}
    } else {
	if (NULL == value) {
	    __CFUnlock(&domain->_lock);
	    return;
	}
    }

	// We must append first so key gets another retain (in case we're
	// about to remove it from the dictionary, and that's the sole reference)
    // This should be a set not an array.
    if (!CFArrayContainsValue(domain->_dirtyKeys, CFRangeMake(0, CFArrayGetCount(domain->_dirtyKeys)), key)) {
	CFArrayAppendValue(domain->_dirtyKeys, key);
    }
    if (value) {
        // Must copy for two reasons - we don't want mutable objects in the cache, and we don't want objects allocated from a different allocator in the cache.
        CFTypeRef newValue = CFPropertyListCreateDeepCopy(__CFPreferencesAllocator(), value, kCFPropertyListImmutable);
        CFDictionarySetValue(domain->_domainDict, key, newValue);
        CFRelease(newValue);
    } else {
        CFDictionaryRemoveValue(domain->_domainDict, key);
    }
    __CFUnlock(&domain->_lock);
}
Пример #24
0
CFDictionaryRef PolicyEngine::find(CFTypeRef target, AuthorityType type, SecAssessmentFlags flags, CFDictionaryRef context)
{
	SQLite::Statement query(*this);
	selectRules(query, "SELECT scan_authority.id, scan_authority.type, scan_authority.requirement, scan_authority.allow, scan_authority.label, scan_authority.priority, scan_authority.remarks, scan_authority.expires, scan_authority.disabled, bookmarkhints.bookmark FROM scan_authority LEFT OUTER JOIN bookmarkhints ON scan_authority.id = bookmarkhints.authority",
		"scan_authority", target, type, flags, context,
		" ORDER BY priority DESC");
	CFRef<CFMutableArrayRef> found = makeCFMutableArray(0);
	while (query.nextRow()) {
		SQLite::int64 id = query[0];
		int type = int(query[1]);
		const char *requirement = query[2];
		int allow = int(query[3]);
		const char *label = query[4];
		double priority = query[5];
		const char *remarks = query[6];
		double expires = query[7];
		int disabled = int(query[8]);
		CFRef<CFDataRef> bookmark = query[9].data();
		CFRef<CFMutableDictionaryRef> rule = makeCFMutableDictionary(5,
			kSecAssessmentRuleKeyID, CFTempNumber(id).get(),
			kSecAssessmentRuleKeyType, CFRef<CFStringRef>(typeNameFor(type)).get(),
			kSecAssessmentRuleKeyRequirement, CFTempString(requirement).get(),
			kSecAssessmentRuleKeyAllow, allow ? kCFBooleanTrue : kCFBooleanFalse,
			kSecAssessmentRuleKeyPriority, CFTempNumber(priority).get()
			);
		if (label)
			CFDictionaryAddValue(rule, kSecAssessmentRuleKeyLabel, CFTempString(label));
		if (remarks)
			CFDictionaryAddValue(rule, kSecAssessmentRuleKeyRemarks, CFTempString(remarks));
		if (expires != never)
			CFDictionaryAddValue(rule, kSecAssessmentRuleKeyExpires, CFRef<CFDateRef>(julianToDate(expires)));
		if (disabled)
			CFDictionaryAddValue(rule, kSecAssessmentRuleKeyDisabled, CFTempNumber(disabled));
		if (bookmark)
			CFDictionaryAddValue(rule, kSecAssessmentRuleKeyBookmark, bookmark);
		CFArrayAppendValue(found, rule);
	}
	if (CFArrayGetCount(found) == 0)
		MacOSError::throwMe(errSecCSNoMatches);
	return cfmake<CFDictionaryRef>("{%O=%O}", kSecAssessmentUpdateKeyFound, found.get());
}
/* IOPSCopyUPSArray
 *
 * Argument: 
 *	CFTypeRef power_sources: The return value from IOPSCoyPowerSourcesInfo()
 * Return value:
 * 	CFArrayRef: all the UPS's we found
 *			NULL if none are found
 */
 CFArrayRef
IOPSCopyUPSArray(CFTypeRef power_sources)
{
    CFArrayRef			array = isA_CFArray(IOPSCopyPowerSourcesList(power_sources));
    CFMutableArrayRef   ret_arr;
    CFTypeRef			name = NULL;
    CFDictionaryRef		ps;
    CFStringRef			transport_type;
    int				    i, count;

    if(!array) return NULL;
    count = CFArrayGetCount(array);
    name = NULL;

    ret_arr = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
    if(!ret_arr) goto exit;

    // Iterate through power_sources
    for(i=0; i<count; i++) {
        name = CFArrayGetValueAtIndex(array, i);
        ps = isA_CFDictionary(IOPSGetPowerSourceDescription(power_sources, name));
        if(ps) {
            transport_type = isA_CFString(CFDictionaryGetValue(ps, CFSTR(kIOPSTransportTypeKey)));
            if(transport_type && ( CFEqual(transport_type, CFSTR(kIOPSSerialTransportType)) ||
                CFEqual(transport_type, CFSTR(kIOPSUSBTransportType)) ||
                CFEqual(transport_type, CFSTR(kIOPSNetworkTransportType)) ) )
            {
                CFArrayAppendValue(ret_arr, name);
            }
        }
    }

    if(0 == CFArrayGetCount(ret_arr)) {
        CFRelease(ret_arr);
        ret_arr = NULL;
    }

exit:
    CFRelease(array);
    return ret_arr;
}
Пример #26
0
static int
dictionary_set(st_data_t key, st_data_t value, CFMutableDictionaryRef dict) {
  CFStringRef keyRef = str_to_cfstr(key);

  CFTypeRef valueRef = NULL;
  if (TYPE(value) == T_HASH) {
    valueRef = CFDictionaryCreateMutable(NULL,
                                         0,
                                         &kCFTypeDictionaryKeyCallBacks,
                                         &kCFTypeDictionaryValueCallBacks);
    rb_hash_foreach(value, dictionary_set, (st_data_t)valueRef);

  } else if (TYPE(value) == T_ARRAY) {
    long i, count = RARRAY_LEN(value);
    valueRef = CFArrayCreateMutable(NULL, count, &kCFTypeArrayCallBacks);
    for (i = 0; i < count; i++) {
      VALUE element = RARRAY_PTR(value)[i];
      CFTypeRef elementRef = NULL;
      if (TYPE(element) == T_HASH) {
        elementRef = CFDictionaryCreateMutable(NULL,
                                               0,
                                               &kCFTypeDictionaryKeyCallBacks,
                                               &kCFTypeDictionaryValueCallBacks);
        rb_hash_foreach(element, dictionary_set, (st_data_t)elementRef);
      } else {
        // otherwise coerce to string
        elementRef = str_to_cfstr(element);
      }
      CFArrayAppendValue((CFMutableArrayRef)valueRef, elementRef);
      CFRelease(elementRef);
    }

  } else {
    valueRef = str_to_cfstr(value);
  }

  CFDictionaryAddValue(dict, keyRef, valueRef);
  CFRelease(keyRef);
  CFRelease(valueRef);
  return ST_CONTINUE;
}
void SearchPopupMenuWin::saveRecentSearches(const AtomicString& name, const Vector<String>& searchItems)
{
    if (name.isEmpty())
        return;

#if USE(CF)
    RetainPtr<CFMutableArrayRef> items;

    size_t size = searchItems.size();
    if (size) {
        items.adoptCF(CFArrayCreateMutable(0, size, &kCFTypeArrayCallBacks));
        for (size_t i = 0; i < size; ++i) {
            RetainPtr<CFStringRef> item(AdoptCF, searchItems[i].createCFString());
            CFArrayAppendValue(items.get(), item.get());
        }
    }

    CFPreferencesSetAppValue(autosaveKey(name).get(), items.get(), kCFPreferencesCurrentApplication);
    CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication);
#endif
}
Пример #28
0
static OSStatus
EAPSecIdentityCreateIdentityTrustChain(SecIdentityRef identity,
				       CFArrayRef * ret_array)
{
    CFMutableArrayRef		array = NULL;
    CFIndex                 count;
    OSStatus			status;
    CFArrayRef			trust_chain = NULL;

    *ret_array = NULL;
    ok_status(status = _EAPSecIdentityCreateCertificateTrustChain(identity,
        &trust_chain), "_EAPSecIdentityCreateCertificateTrustChain");
    count = CFArrayGetCount(trust_chain);
    array = CFArrayCreateMutable(NULL, count + 1, &kCFTypeArrayCallBacks);
    CFArrayAppendValue(array, identity); /* identity into [0] */
    CFArrayAppendArray(array, trust_chain, CFRangeMake(0, count));
    *ret_array = array;

    CFReleaseNull(trust_chain);
    return (status);
}
Пример #29
0
static RetainPtr<CFArrayRef> filterCookies(CFArrayRef unfilteredCookies)
{
    CFIndex count = CFArrayGetCount(unfilteredCookies);
    RetainPtr<CFMutableArrayRef> filteredCookies = adoptCF(CFArrayCreateMutable(0, count, &kCFTypeArrayCallBacks));
    for (CFIndex i = 0; i < count; ++i) {
        CFHTTPCookieRef cookie = (CFHTTPCookieRef)CFArrayGetValueAtIndex(unfilteredCookies, i);

        // <rdar://problem/5632883> CFHTTPCookieStorage would store an empty cookie,
        // which would be sent as "Cookie: =". We have a workaround in setCookies() to prevent
        // that, but we also need to avoid sending cookies that were previously stored, and
        // there's no harm to doing this check because such a cookie is never valid.
        if (!CFStringGetLength(cookieName(cookie).get()))
            continue;

        if (CFHTTPCookieIsHTTPOnly(cookie))
            continue;

        CFArrayAppendValue(filteredCookies.get(), cookie);
    }
    return filteredCookies;
}
Пример #30
0
static void get_element_children(IOHIDElementRef tElement, CFArrayRef childElements)
{
    CFIndex    idx, cnt;
    CFArrayRef tElementChildrenArray = IOHIDElementGetChildren(tElement);

    cnt = CFArrayGetCount(tElementChildrenArray);
    if (cnt < 1)
        return;

    /* Either add the element to the array or grab its children */
    for (idx=0; idx<cnt; idx++)
    {
        IOHIDElementRef tChildElementRef;

        tChildElementRef = (IOHIDElementRef)CFArrayGetValueAtIndex(tElementChildrenArray, idx);
        if (IOHIDElementGetType(tChildElementRef) == kIOHIDElementTypeCollection)
            get_element_children(tChildElementRef, childElements);
        else
            CFArrayAppendValue((CFMutableArrayRef)childElements, tChildElementRef);
    }
}