コード例 #1
0
void InbandTextTrackPrivateAVF::processCueAttributes(CFAttributedStringRef attributedString, GenericCueData* cueData)
{
    // Some of the attributes we translate into per-cue WebVTT settings are are repeated on each part of an attributed string so only
    // process the first instance of each.
    enum AttributeFlags {
        Line = 1 << 0,
        Position = 1 << 1,
        Size = 1 << 2,
        Vertical = 1 << 3,
        Align = 1 << 4,
        FontName = 1 << 5
    };
    unsigned processed = 0;

    StringBuilder content;
    String attributedStringValue = CFAttributedStringGetString(attributedString);
    CFIndex length = attributedStringValue.length();
    if (!length)
        return;

    CFRange effectiveRange = CFRangeMake(0, 0);
    while ((effectiveRange.location + effectiveRange.length) < length) {

        CFDictionaryRef attributes = CFAttributedStringGetAttributes(attributedString, effectiveRange.location + effectiveRange.length, &effectiveRange);
        if (!attributes)
            continue;

        StringBuilder tagStart;
        CFStringRef valueString;
        String tagEnd;
        CFIndex attributeCount = CFDictionaryGetCount(attributes);
        Vector<const void*> keys(attributeCount);
        Vector<const void*> values(attributeCount);
        CFDictionaryGetKeysAndValues(attributes, keys.data(), values.data());

        for (CFIndex i = 0; i < attributeCount; ++i) {
            CFStringRef key = static_cast<CFStringRef>(keys[i]);
            CFTypeRef value = values[i];
            if (CFGetTypeID(key) != CFStringGetTypeID() || !CFStringGetLength(key))
                continue;

            if (CFStringCompare(key, kCMTextMarkupAttribute_Alignment, 0) == kCFCompareEqualTo) {
                valueString = static_cast<CFStringRef>(value);
                if (CFGetTypeID(valueString) != CFStringGetTypeID() || !CFStringGetLength(valueString))
                    continue;
                if (processed & Align)
                    continue;
                processed |= Align;

                if (CFStringCompare(valueString, kCMTextMarkupAlignmentType_Start, 0) == kCFCompareEqualTo)
                    cueData->setAlign(GenericCueData::Start);
                else if (CFStringCompare(valueString, kCMTextMarkupAlignmentType_Middle, 0) == kCFCompareEqualTo)
                    cueData->setAlign(GenericCueData::Middle);
                else if (CFStringCompare(valueString, kCMTextMarkupAlignmentType_End, 0) == kCFCompareEqualTo)
                    cueData->setAlign(GenericCueData::End);
                else
                    ASSERT_NOT_REACHED();

                continue;
            }

            if (CFStringCompare(key, kCMTextMarkupAttribute_BoldStyle, 0) == kCFCompareEqualTo) {
                if (static_cast<CFBooleanRef>(value) != kCFBooleanTrue)
                    continue;

                tagStart.append("<b>");
                tagEnd.insert("</b>", 0);
                continue;
            }

            if (CFStringCompare(key, kCMTextMarkupAttribute_ItalicStyle, 0) == kCFCompareEqualTo) {
                if (static_cast<CFBooleanRef>(value) != kCFBooleanTrue)
                    continue;

                tagStart.append("<i>");
                tagEnd.insert("</i>", 0);
                continue;
            }

            if (CFStringCompare(key, kCMTextMarkupAttribute_UnderlineStyle, 0) == kCFCompareEqualTo) {
                if (static_cast<CFBooleanRef>(value) != kCFBooleanTrue)
                    continue;

                tagStart.append("<u>");
                tagEnd.insert("</u>", 0);
                continue;
            }

            if (CFStringCompare(key, kCMTextMarkupAttribute_OrthogonalLinePositionPercentageRelativeToWritingDirection, 0) == kCFCompareEqualTo) {
                if (CFGetTypeID(value) != CFNumberGetTypeID())
                    continue;
                if (processed & Line)
                    continue;
                processed |= Line;

                CFNumberRef valueNumber = static_cast<CFNumberRef>(value);
                double line;
                CFNumberGetValue(valueNumber, kCFNumberFloat64Type, &line);
                cueData->setLine(line);
                continue;
            }

            if (CFStringCompare(key, kCMTextMarkupAttribute_TextPositionPercentageRelativeToWritingDirection, 0) == kCFCompareEqualTo) {
                if (CFGetTypeID(value) != CFNumberGetTypeID())
                    continue;
                if (processed & Position)
                    continue;
                processed |= Position;

                CFNumberRef valueNumber = static_cast<CFNumberRef>(value);
                double position;
                CFNumberGetValue(valueNumber, kCFNumberFloat64Type, &position);
                cueData->setPosition(position);
                continue;
            }

            if (CFStringCompare(key, kCMTextMarkupAttribute_WritingDirectionSizePercentage, 0) == kCFCompareEqualTo) {
                if (CFGetTypeID(value) != CFNumberGetTypeID())
                    continue;
                if (processed & Size)
                    continue;
                processed |= Size;

                CFNumberRef valueNumber = static_cast<CFNumberRef>(value);
                double size;
                CFNumberGetValue(valueNumber, kCFNumberFloat64Type, &size);
                cueData->setSize(size);
                continue;
            }

            if (CFStringCompare(key, kCMTextMarkupAttribute_VerticalLayout, 0) == kCFCompareEqualTo) {
                valueString = static_cast<CFStringRef>(value);
                if (CFGetTypeID(valueString) != CFStringGetTypeID() || !CFStringGetLength(valueString))
                    continue;
                
                if (CFStringCompare(valueString, kCMTextVerticalLayout_LeftToRight, 0) == kCFCompareEqualTo)
                    tagStart.append(leftToRightMark);
                else if (CFStringCompare(valueString, kCMTextVerticalLayout_RightToLeft, 0) == kCFCompareEqualTo)
                    tagStart.append(rightToLeftMark);
                continue;
            }

            if (CFStringCompare(key, kCMTextMarkupAttribute_BaseFontSizePercentageRelativeToVideoHeight, 0) == kCFCompareEqualTo) {
                if (CFGetTypeID(value) != CFNumberGetTypeID())
                    continue;
                
                CFNumberRef valueNumber = static_cast<CFNumberRef>(value);
                double baseFontSize;
                CFNumberGetValue(valueNumber, kCFNumberFloat64Type, &baseFontSize);
                cueData->setBaseFontSize(baseFontSize);
                continue;
            }

            if (CFStringCompare(key, kCMTextMarkupAttribute_RelativeFontSize, 0) == kCFCompareEqualTo) {
                if (CFGetTypeID(value) != CFNumberGetTypeID())
                    continue;
                
                CFNumberRef valueNumber = static_cast<CFNumberRef>(value);
                double relativeFontSize;
                CFNumberGetValue(valueNumber, kCFNumberFloat64Type, &relativeFontSize);
                cueData->setRelativeFontSize(relativeFontSize);
                continue;
            }

            if (CFStringCompare(key, kCMTextMarkupAttribute_FontFamilyName, 0) == kCFCompareEqualTo) {
                valueString = static_cast<CFStringRef>(value);
                if (CFGetTypeID(valueString) != CFStringGetTypeID() || !CFStringGetLength(valueString))
                    continue;
                if (processed & FontName)
                    continue;
                processed |= FontName;
                
                cueData->setFontName(valueString);
                continue;
            }

            if (CFStringCompare(key, kCMTextMarkupAttribute_ForegroundColorARGB, 0) == kCFCompareEqualTo) {
                CFArrayRef arrayValue = static_cast<CFArrayRef>(value);
                if (CFGetTypeID(arrayValue) != CFArrayGetTypeID())
                    continue;
                
                RGBA32 color;
                if (!makeRGBA32FromARGBCFArray(arrayValue, color))
                    continue;
                cueData->setForegroundColor(color);
            }
            
            if (CFStringCompare(key, kCMTextMarkupAttribute_BackgroundColorARGB, 0) == kCFCompareEqualTo) {
                CFArrayRef arrayValue = static_cast<CFArrayRef>(value);
                if (CFGetTypeID(arrayValue) != CFArrayGetTypeID())
                    continue;
                
                RGBA32 color;
                if (!makeRGBA32FromARGBCFArray(arrayValue, color))
                    continue;
                cueData->setBackgroundColor(color);
            }

            if (CFStringCompare(key, kCMTextMarkupAttribute_CharacterBackgroundColorARGB, 0) == kCFCompareEqualTo) {
                CFArrayRef arrayValue = static_cast<CFArrayRef>(value);
                if (CFGetTypeID(arrayValue) != CFArrayGetTypeID())
                    continue;
                
                RGBA32 color;
                if (!makeRGBA32FromARGBCFArray(arrayValue, color))
                    continue;
                cueData->setHighlightColor(color);
            }
        }

        content.append(tagStart);
        content.append(attributedStringValue.substring(effectiveRange.location, effectiveRange.length));
        content.append(tagEnd);
    }

    if (content.length())
        cueData->setContent(content.toString());
}
コード例 #2
0
static QVariant qtValue(CFPropertyListRef cfvalue)
{
    if (!cfvalue)
        return QVariant();

    CFTypeID typeId = CFGetTypeID(cfvalue);

    /*
        Sorted grossly from most to least frequent type.
    */
    if (typeId == CFStringGetTypeID()) {
        return QSettingsPrivate::stringToVariant(QCFString::toQString(static_cast<CFStringRef>(cfvalue)));
    } else if (typeId == CFNumberGetTypeID()) {
        CFNumberRef cfnumber = static_cast<CFNumberRef>(cfvalue);
        if (CFNumberIsFloatType(cfnumber)) {
            double d;
            CFNumberGetValue(cfnumber, kCFNumberDoubleType, &d);
            return d;
        } else {
            int i;
            qint64 ll;

            if (CFNumberGetValue(cfnumber, kCFNumberIntType, &i))
                return i;
            CFNumberGetValue(cfnumber, kCFNumberLongLongType, &ll);
            return ll;
        }
    } else if (typeId == CFArrayGetTypeID()) {
        CFArrayRef cfarray = static_cast<CFArrayRef>(cfvalue);
        QList<QVariant> list;
        CFIndex size = CFArrayGetCount(cfarray);
        bool metNonString = false;
        for (CFIndex i = 0; i < size; ++i) {
            QVariant value = qtValue(CFArrayGetValueAtIndex(cfarray, i));
            if (value.type() != QVariant::String)
                metNonString = true;
            list << value;
        }
        if (metNonString)
            return list;
        else
            return QVariant(list).toStringList();
    } else if (typeId == CFBooleanGetTypeID()) {
        return (bool)CFBooleanGetValue(static_cast<CFBooleanRef>(cfvalue));
    } else if (typeId == CFDataGetTypeID()) {
        CFDataRef cfdata = static_cast<CFDataRef>(cfvalue);
        return QByteArray(reinterpret_cast<const char *>(CFDataGetBytePtr(cfdata)),
                          CFDataGetLength(cfdata));
    } else if (typeId == CFDictionaryGetTypeID()) {
        CFDictionaryRef cfdict = static_cast<CFDictionaryRef>(cfvalue);
        CFTypeID arrayTypeId = CFArrayGetTypeID();
        int size = (int)CFDictionaryGetCount(cfdict);
        QVarLengthArray<CFPropertyListRef> keys(size);
        QVarLengthArray<CFPropertyListRef> values(size);
        CFDictionaryGetKeysAndValues(cfdict, keys.data(), values.data());

        QMultiMap<QString, QVariant> map;
        for (int i = 0; i < size; ++i) {
            QString key = QCFString::toQString(static_cast<CFStringRef>(keys[i]));

            if (CFGetTypeID(values[i]) == arrayTypeId) {
                CFArrayRef cfarray = static_cast<CFArrayRef>(values[i]);
                CFIndex arraySize = CFArrayGetCount(cfarray);
                for (CFIndex j = arraySize - 1; j >= 0; --j)
                    map.insert(key, qtValue(CFArrayGetValueAtIndex(cfarray, j)));
            } else {
                map.insert(key, qtValue(values[i]));
            }
        }
        return map;
    } else if (typeId == CFDateGetTypeID()) {
        QDateTime dt;
        dt.setTime_t((uint)kCFAbsoluteTimeIntervalSince1970);
        return dt.addSecs((int)CFDateGetAbsoluteTime(static_cast<CFDateRef>(cfvalue)));
    }
    return QVariant();
}
コード例 #3
0
ファイル: ks_keychain.c プロジェクト: aosm/Heimdal
static int
keychain_query(hx509_context context,
	       hx509_certs certs,
	       void *data,
	       const hx509_query *query,
	       hx509_cert *retcert)
{
    CFArrayRef identities = NULL;
    hx509_cert cert = NULL;
    CFIndex n, count;
    int ret;
    int kdcLookupHack = 0;

    /*
     * First to course filtering using security framework ....
     */

#define FASTER_FLAGS (HX509_QUERY_MATCH_PERSISTENT|HX509_QUERY_PRIVATE_KEY)

    if ((query->match & FASTER_FLAGS) == 0)
	return HX509_UNIMPLEMENTED_OPERATION;

    CFMutableDictionaryRef secQuery = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks,  &kCFTypeDictionaryValueCallBacks);

    /*
     * XXX this is so broken, SecItem doesn't find the kdc certificte,
     * and kdc certificates happend to be searched by friendly name,
     * so find that and mundge on the structure.
     */

    if ((query->match & HX509_QUERY_MATCH_FRIENDLY_NAME) &&
	(query->match & HX509_QUERY_PRIVATE_KEY) && 
	strcmp(query->friendlyname, "O=System Identity,CN=com.apple.kerberos.kdc") == 0)
    {
	((hx509_query *)query)->match &= ~HX509_QUERY_PRIVATE_KEY;
	kdcLookupHack = 1;
    }

    if (kdcLookupHack || (query->match & HX509_QUERY_MATCH_PERSISTENT)) {
	CFDictionaryAddValue(secQuery, kSecClass, kSecClassCertificate);
    } else
	CFDictionaryAddValue(secQuery, kSecClass, kSecClassIdentity);

    CFDictionaryAddValue(secQuery, kSecReturnRef, kCFBooleanTrue);
    CFDictionaryAddValue(secQuery, kSecMatchLimit, kSecMatchLimitAll);

    if (query->match & HX509_QUERY_MATCH_PERSISTENT) {
	CFDataRef refdata = CFDataCreateWithBytesNoCopy(NULL, query->persistent->data, query->persistent->length, kCFAllocatorNull);
	CFDictionaryAddValue(secQuery, kSecValuePersistentRef, refdata);
	CFRelease(refdata);
    }


    OSStatus status = SecItemCopyMatching(secQuery, (CFTypeRef *)&identities);
    CFRelease(secQuery);
    if (status || identities == NULL) {
	hx509_clear_error_string(context);
	return HX509_CERT_NOT_FOUND;
    }
    
    heim_assert(CFArrayGetTypeID() == CFGetTypeID(identities), "return value not an array");

    /*
     * ... now do hx509 filtering
     */

    count = CFArrayGetCount(identities);
    for (n = 0; n < count; n++) {
	CFTypeRef secitem = (CFTypeRef)CFArrayGetValueAtIndex(identities, n);

#ifndef __APPLE_TARGET_EMBEDDED__

	if (query->match & HX509_QUERY_MATCH_PERSISTENT) {
	    SecIdentityRef other = NULL;
	    OSStatus osret;

	    osret = SecIdentityCreateWithCertificate(NULL, (SecCertificateRef)secitem, &other);
	    if (osret == noErr) {
		ret = hx509_cert_init_SecFramework(context, (void *)other, &cert);
		CFRelease(other);
		if (ret)
		    continue;
	    } else {
		ret = hx509_cert_init_SecFramework(context, (void *)secitem, &cert);
		if (ret)
		    continue;
	    }
	} else
#endif
        {

	    ret = hx509_cert_init_SecFramework(context, (void *)secitem, &cert);
	    if (ret)
		continue;
	}

	if (_hx509_query_match_cert(context, query, cert)) {

#ifndef __APPLE_TARGET_EMBEDDED__
	    /* certtool/keychain doesn't glue togheter the cert with keys for system keys */
	    if (kdcLookupHack) {
		SecIdentityRef other = NULL;
		OSStatus osret;

		osret = SecIdentityCreateWithCertificate(NULL, (SecCertificateRef)secitem, &other);
		if (osret == noErr) {
		    hx509_cert_free(cert);
		    ret = hx509_cert_init_SecFramework(context, other, &cert);
		    CFRelease(other);
		    if (ret)
			continue;
		}
	    }	    
#endif
	    *retcert = cert;
	    break;
	}
	hx509_cert_free(cert);
    }

    if (kdcLookupHack)
	((hx509_query *)query)->match |= HX509_QUERY_PRIVATE_KEY;

    CFRelease(identities);

    if (*retcert == NULL) {
	hx509_clear_error_string(context);
	return HX509_CERT_NOT_FOUND;
    }

    return 0;
}
コード例 #4
0
bool LegacyWebArchive::extract(CFDictionaryRef dictionary)
{
    ASSERT(dictionary);
    if (!dictionary) {
        LOG(Archives, "LegacyWebArchive - Null root CFDictionary, aborting invalid WebArchive");
        return false;
    }
    
    CFDictionaryRef mainResourceDict = static_cast<CFDictionaryRef>(CFDictionaryGetValue(dictionary, LegacyWebArchiveMainResourceKey));
    if (!mainResourceDict) {
        LOG(Archives, "LegacyWebArchive - No main resource in archive, aborting invalid WebArchive");
        return false;
    }
    if (CFGetTypeID(mainResourceDict) != CFDictionaryGetTypeID()) {
        LOG(Archives, "LegacyWebArchive - Main resource is not the expected CFDictionary, aborting invalid WebArchive");
        return false;
    }
    
    setMainResource(createResource(mainResourceDict));
    if (!mainResource()) {
        LOG(Archives, "LegacyWebArchive - Failed to parse main resource from CFDictionary or main resource does not exist, aborting invalid WebArchive");
        return false;
    }
    
    CFArrayRef subresourceArray = static_cast<CFArrayRef>(CFDictionaryGetValue(dictionary, LegacyWebArchiveSubresourcesKey));
    if (subresourceArray && CFGetTypeID(subresourceArray) != CFArrayGetTypeID()) {
        LOG(Archives, "LegacyWebArchive - Subresources is not the expected Array, aborting invalid WebArchive");
        return false;
    }
    
    if (subresourceArray) {
        CFIndex count = CFArrayGetCount(subresourceArray);
        for (CFIndex i = 0; i < count; ++i) {
            CFDictionaryRef subresourceDict = static_cast<CFDictionaryRef>(CFArrayGetValueAtIndex(subresourceArray, i));
            if (CFGetTypeID(subresourceDict) != CFDictionaryGetTypeID()) {
                LOG(Archives, "LegacyWebArchive - Subresource is not expected CFDictionary, aborting invalid WebArchive");
                return false;
            }
            addSubresource(createResource(subresourceDict));
        }
    }
    
    CFArrayRef subframeArray = static_cast<CFArrayRef>(CFDictionaryGetValue(dictionary, LegacyWebArchiveSubframeArchivesKey));
    if (subframeArray && CFGetTypeID(subframeArray) != CFArrayGetTypeID()) {
        LOG(Archives, "LegacyWebArchive - Subframe archives is not the expected Array, aborting invalid WebArchive");
        return false;
    }
    
    if (subframeArray) {
        CFIndex count = CFArrayGetCount(subframeArray);
        for (CFIndex i = 0; i < count; ++i) {
            CFDictionaryRef subframeDict = static_cast<CFDictionaryRef>(CFArrayGetValueAtIndex(subframeArray, i));
            if (CFGetTypeID(subframeDict) != CFDictionaryGetTypeID()) {
                LOG(Archives, "LegacyWebArchive - Subframe array is not expected CFDictionary, aborting invalid WebArchive");
                return false;
            }
            
            RefPtr<LegacyWebArchive> subframeArchive = create();
            if (subframeArchive->extract(subframeDict))
                addSubframeArchive(subframeArchive.release());
            else
                LOG(Archives, "LegacyWebArchive - Invalid subframe archive skipped");
        }
    }
    
    return true;
}
コード例 #5
0
OSStatus DoStatPaths(COMMAND_PROC_ARGUMENTS) {
	OSStatus retval = noErr;
	
	// Pre-conditions
    
    // userData may be NULL
	assert(request != NULL);
	assert(response != NULL);
    // asl may be NULL
    // aslMsg may be NULL
	
	// Get Info from arguments and assert that it's a CFArrayRef
	CFArrayRef infos = CFDictionaryGetValue(request, CFSTR(kInfos)) ;
	assert(infos != NULL) ;
	assert(CFGetTypeID(infos) == CFArrayGetTypeID()) ;
	
	CFIndex nFiles = CFArrayGetCount(infos) ;
	CFIndex i ;
	int nSucceeded = 0 ;
	CFMutableDictionaryRef statDatas = CFDictionaryCreateMutable(
																NULL,
																nFiles,
																&kCFTypeDictionaryKeyCallBacks,
																&kCFTypeDictionaryValueCallBacks
	) ;
	CFMutableDictionaryRef errorCodes = CFDictionaryCreateMutable(
															   NULL,
															   nFiles,
															   &kCFTypeDictionaryKeyCallBacks,
															   &kCFTypeDictionaryValueCallBacks
															   ) ;
	for (i=0; i<nFiles; i++) {
		CFStringRef path = CFArrayGetValueAtIndex(infos, i) ;
		assert(CFGetTypeID(path) == CFStringGetTypeID()) ;
		
		int errorCode = 0 ;
		
		char pathC[SSY_UNIX_PATH_UTILS_MAX_PATH_CHARS] ;
		if (errorCode == 0) {
			Boolean ok = CFStringGetCString(
										 path,
										 pathC,
										 SSY_UNIX_PATH_UTILS_MAX_PATH_CHARS,
										 kCFStringEncodingASCII
										 ) ;
			if (!ok) {
				errorCode = SSYAuthorizedTasksPathTooLong ;
			}
		}
		
		if (errorCode == 0) {
			struct stat aStat ;
			int result = stat(pathC, &aStat) ;
			if (result == 0) {
				CFDataRef statData = CFDataCreate (
												   kCFAllocatorDefault,
												   (UInt8*)&aStat,
												   sizeof(aStat)
												   ) ;
				CFDictionaryAddValue(statDatas, path, statData) ;
				CFQRelease(statData) ;
			}
			else {
				errorCode = errno ;
			}
		}
				
		if (errorCode == 0) {
			nSucceeded++ ;
		}
		else {
			CFNumberRef errorNumber = CFNumberCreate(
													 kCFAllocatorDefault,
													 kCFNumberIntType,
													 &errorCode
													 ) ;
			CFDictionaryAddValue(errorCodes, path, errorNumber) ;
			CFQRelease(errorNumber) ;
		}
	}
		
	CFDictionaryAddValue(response, CFSTR(kStatDatas), statDatas) ;
	CFRelease(statDatas) ;
	CFDictionaryAddValue(response, CFSTR(kErrorCodes), errorCodes) ;
	CFRelease(errorCodes) ;
	
	asl_log(
			asl,
			aslMsg,
			ASL_LEVEL_DEBUG,
			"DoStatPaths did good %d/%d requested files",
			nSucceeded,
			(int)nFiles
			) ;
	
	// Return the number of file copy operations that failed
	retval = nFiles - nSucceeded ;
	
	return retval ;
}	
コード例 #6
0
bool UserObjectImp::toBoolean(ExecState *exec) const
{
    bool result = false;
    JSUserObject* jsObjPtr = KJSValueToJSObject(toObject(exec), exec);
    CFTypeRef cfValue = jsObjPtr ? jsObjPtr->CopyCFValue() : 0;
    if (cfValue)
    {
        CFTypeID cfType = CFGetTypeID(cfValue);  // toPrimitive
        if (cfValue == GetCFNull())
        {
            //
        }
        else if (cfType == CFBooleanGetTypeID())
        {
            if (cfValue == kCFBooleanTrue)
            {
                result = true;
            }
        }
        else if (cfType == CFStringGetTypeID())
        {
            if (CFStringGetLength((CFStringRef)cfValue))
            {
                result = true;
            }
        }
        else if (cfType == CFNumberGetTypeID())
        {
            if (cfValue != kCFNumberNaN)
            {
                double d;
                if (CFNumberGetValue((CFNumberRef)cfValue, kCFNumberDoubleType, &d))
                {
                    if (d != 0)
                    {
                        result = true;
                    }
                }
            }
        }
        else if (cfType == CFArrayGetTypeID())
        {
            if (CFArrayGetCount((CFArrayRef)cfValue))
            {
                result = true;
            }
        }
        else if (cfType == CFDictionaryGetTypeID())
        {
            if (CFDictionaryGetCount((CFDictionaryRef)cfValue))
            {
                result = true;
            }
        }
        else if (cfType == CFSetGetTypeID())
        {
            if (CFSetGetCount((CFSetRef)cfValue))
            {
                result = true;
            }
        }
        else if (cfType == CFURLGetTypeID())
        {
            CFURLRef absURL = CFURLCopyAbsoluteURL((CFURLRef)cfValue);
            if (absURL)
            {
                CFStringRef cfStr = CFURLGetString(absURL);
                if (cfStr && CFStringGetLength(cfStr))
                {
                    result = true;
                }
                ReleaseCFType(absURL);
            }
        }
    }
    if (jsObjPtr) jsObjPtr->Release();
    ReleaseCFType(cfValue);
    return result;
}
コード例 #7
0
ファイル: osxInput.cpp プロジェクト: HwakyoungLee/opentnl
static void HIDGetElementsCFArrayHandler (const void * value, void * parameter)
{
	if (CFGetTypeID (value) != CFDictionaryGetTypeID ())
      return;

   CFTypeRef refElement = CFTypeRef(value);
	long elementType, usagePage, usage;
	CFTypeRef refElementType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementTypeKey));
	CFTypeRef refUsagePage = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementUsagePageKey));
	CFTypeRef refUsage = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementUsageKey));
   bool isButton = false, isAxis = false;

   ControllerElement *theElement = NULL;
	if ((refElementType) && (CFNumberGetValue (refElementType, kCFNumberLongType, &elementType)))
	{
		/* look at types of interest */
		if ((elementType == kIOHIDElementTypeInput_Misc) || (elementType == kIOHIDElementTypeInput_Button) ||
			(elementType == kIOHIDElementTypeInput_Axis))
		{
			if (refUsagePage && CFNumberGetValue (refUsagePage, kCFNumberLongType, &usagePage) &&
				refUsage && CFNumberGetValue (refUsage, kCFNumberLongType, &usage))
			{
				switch (usagePage) /* only interested in kHIDPage_GenericDesktop and kHIDPage_Button */
				{
					case kHIDPage_GenericDesktop:
						{
							switch (usage) /* look at usage to determine function */
							{
								case kHIDUsage_GD_X:
                           theElement = gController.axes + AxisX;
                           break;
								case kHIDUsage_GD_Y:
                           theElement = gController.axes + AxisY;
                           break;
								case kHIDUsage_GD_Z:
                           theElement = gController.axes + AxisZ;
                           break;
								case kHIDUsage_GD_Rx:
                           theElement = gController.axes + AxisRx;
                           break;
								case kHIDUsage_GD_Ry:
                           theElement = gController.axes + AxisRy;
                           break;
								case kHIDUsage_GD_Rz:
                           theElement = gController.axes + AxisRz;
                           break;
								case kHIDUsage_GD_Slider:
                           theElement = gController.axes + AxisSlider0;
                           break;
								case kHIDUsage_GD_Dial:
								case kHIDUsage_GD_Wheel:
   								break;
							}							
						}
						break;
					case kHIDPage_Button:
                  {
                     ControllerElement e;
                     gController.buttons.push_back(e);
                     theElement = &gController.buttons.last();
                  }
						break;
					default:
						break;
				}
			}
		}
		else if (kIOHIDElementTypeCollection == elementType)
      {
         CFTypeRef refElementTop = CFDictionaryGetValue ((CFMutableDictionaryRef) refElement, CFSTR(kIOHIDElementKey));
         if (refElementTop)
         {
            CFTypeID type = CFGetTypeID (refElementTop);
            if (type == CFArrayGetTypeID()) /* if element is an array */
            {
               CFRange range = {0, CFArrayGetCount (refElementTop)};
               /* CountElementsCFArrayHandler called for each array member */
               CFArrayApplyFunction (refElementTop, range, HIDGetElementsCFArrayHandler, NULL);
            }
         }
      }
	}
	if (theElement) /* add to list */
	{
	   long number;
	   CFTypeRef refType;

	   refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementCookieKey));
	   if (refType && CFNumberGetValue (refType, kCFNumberLongType, &number))
		   theElement->cookie = (IOHIDElementCookie) number;
	   refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementMinKey));
	   if (refType && CFNumberGetValue (refType, kCFNumberLongType, &number))
		   theElement->minValue = number;

      refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementMaxKey));

	   if (refType && CFNumberGetValue (refType, kCFNumberLongType, &number))
		   theElement->maxValue = number;
	  logprintf("Cookie = %d min = %d max = %d", theElement->cookie, theElement->minValue, theElement->maxValue);
	}
}
コード例 #8
0
void printProperty(
    CFStringRef label,
    CFStringRef propKey,
    CFTypeRef value,
    char lineEnd)
{
    CFTypeID type = CFGetTypeID(value);
    CFStringRef propString = NULL;     // must release
    CFStringRef labeledString = NULL;  // must release
    CFStringRef outputString = NULL;   // do not release
    char * allocString = NULL;         // must free
    char * dataString = NULL;  // must free

    if (type == CFStringGetTypeID()) {
        propString = CFStringCreateWithFormat(
            kCFAllocatorDefault, NULL, CFSTR("%@ = \"%@\"%c"),
            propKey, value, lineEnd);
    } else if (type == CFNumberGetTypeID()) {
        propString = CFStringCreateWithFormat(
            kCFAllocatorDefault, NULL, CFSTR("%@ = %@%c"),
            propKey, value, lineEnd);
    } else if (type == CFBooleanGetTypeID()) {
        propString = CFStringCreateWithFormat(
            kCFAllocatorDefault, NULL, CFSTR("%@ = %@%c"),
            propKey, value, lineEnd);
    } else if (type == CFDataGetTypeID()) {
        CFIndex length = 0;
        length = CFDataGetLength(value);
        const UInt8 * data = CFDataGetBytePtr(value);
        if (!data) {
            propString = CFStringCreateWithFormat(
                kCFAllocatorDefault, NULL, CFSTR("%@[%zd] = <null data pointer>%c"),
                propKey, length, lineEnd);
        } else {
            int numBytes = (int)MIN(length, kMaxPrintableCFDataLength);
            dataString = stringForData(data, MIN(numBytes, kMaxPrintableCFDataLength));
            if (length > kMaxPrintableCFDataLength) {
                propString = CFStringCreateWithFormat(
                    kCFAllocatorDefault, NULL,
                    CFSTR("%@ = <data (%zd bytes): %s...>%c"),
                    propKey, length, dataString, lineEnd);
            } else {
                propString = CFStringCreateWithFormat(
                    kCFAllocatorDefault, NULL,
                    CFSTR("%@ = <data (%zd bytes): %s>%c"),
                    propKey, length, dataString, lineEnd);
            }
        }
    } else if (type == CFDictionaryGetTypeID()) {
        propString = CFStringCreateWithFormat(
            kCFAllocatorDefault, NULL, CFSTR("%@ = <dictionary of %zd items>%c"),
            propKey, CFDictionaryGetCount(value), lineEnd);
    } else if (type == CFArrayGetTypeID()) {
        propString = CFStringCreateWithFormat(
            kCFAllocatorDefault, NULL, CFSTR("%@ = <array of %zd items>%c"),
            propKey, CFArrayGetCount(value), lineEnd);
    } else {
        propString = CFStringCreateWithFormat(
            kCFAllocatorDefault, NULL, CFSTR("%@ = <value of unknown type>%c"),
            propKey, lineEnd);
    }

    if (!propString) {
        goto finish;
    }

    if (label) {
        labeledString = CFStringCreateWithFormat(
            kCFAllocatorDefault, NULL, CFSTR("%@: %@"), label, propString);
        outputString = labeledString;
    } else {
        labeledString = CFStringCreateWithFormat(
            kCFAllocatorDefault, NULL, CFSTR("%@"), propString);
        outputString = labeledString;
    }

    if (!outputString) {
        goto finish;
    }

    allocString = createUTF8CStringForCFString(outputString);
    if (!allocString) {
        goto finish;
    }

    fprintf(stdout, "%s", allocString);

finish:
    if (propString)     CFRelease(propString);
    if (labeledString)  CFRelease(labeledString);
    if (allocString)    free(allocString);
    if (dataString)     free(dataString);
    return;
}
コード例 #9
0
ファイル: kim_os_preferences.c プロジェクト: Brainiarc7/pbis
kim_error kim_os_preferences_get_favorites_for_key (kim_preference_key in_key,
                                                    kim_favorites      io_favorites)
{
    kim_error err = KIM_NO_ERROR;
    CFArrayRef value = NULL;

    if (!err && !io_favorites) { err = check_error (KIM_NULL_PARAMETER_ERR); }

    if (!err) {
        err = kim_os_preferences_copy_value (in_key, CFArrayGetTypeID (),
                                             (CFPropertyListRef *) &value);
    }

    if (!err && value) {
        if (!value || CFArrayGetCount (value) < 1) {
            err =  kim_favorites_remove_all_identities (io_favorites);

        } else {
            CFIndex count = CFArrayGetCount (value);
            CFIndex i;

            for (i = 0; !err && i < count; i++) {
                CFDictionaryRef dictionary = NULL;
                CFStringRef cfstring = NULL;

                dictionary = (CFDictionaryRef) CFArrayGetValueAtIndex (value, i);
                if (!dictionary || CFGetTypeID (dictionary) != CFDictionaryGetTypeID ()) {
                    err = check_error (KIM_PREFERENCES_READ_ERR);
                }

                if (!err) {
                    err = kim_os_preferences_copy_value_for_dict_key (dictionary,
                                                                      kim_preference_key_client_identity,
                                                                      CFStringGetTypeID (),
                                                                      (CFPropertyListRef *) &cfstring);
                }

                if (!err && cfstring) {
                    kim_string string = NULL;
                    kim_identity identity = NULL;
                    kim_options options = KIM_OPTIONS_DEFAULT;

                    err = kim_os_string_create_from_cfstring (&string, cfstring);

                    if (!err) {
                        err = kim_identity_create_from_string (&identity, string);
                    }

                    if (!err && (CFDictionaryGetCount (dictionary) > 1)) {
                        err = kim_os_preferences_dictionary_to_options (dictionary,
                                                                        &options);
                    }

                    if (!err) {
                        err = kim_favorites_add_identity (io_favorites, identity,
                                                          options);
                    }

                    kim_string_free (&string);
                    kim_options_free (&options);
                    kim_identity_free (&identity);
                }
            }

            if (err) {
                kim_favorites_remove_all_identities (io_favorites);
            }
        }
    }

    if (value) { CFRelease (value); }

    return check_error (err);
}
コード例 #10
0
ファイル: apple.c プロジェクト: noscripter/nssecurity
// Helper function to construct strings for CFDictionaryApplyFunction in
// platform_getmimedescription()
//  key     CFString containing a MIME type.
//  value   CFDictionary containing descriptions and extensions.
//  context char * where we want our NP_GetMIMETypeDescription compatible output.
static void mimetype_dictionary_applier(const void *key,
                                        const void *value,
                                        void *context)
{
    CFDictionaryRef cf_mimetype_dict    = value;
    CFStringRef     cf_mimetype         = key;
    CFIndex         cf_length;
    CFArrayRef      cf_extensions;
    CFStringRef     cf_description;
    CFBooleanRef    cf_enabled;
    char           *mimetype            = strdupa("");
    char           *description         = strdupa("");
    char           *extensions          = strdup("");
    char          **result              = context;

    // Here is an example of the output we want:
    //
    // "application/example:ext1,ext2:Example MIME Type"
    //

    // Verify that we received a CFDictionary object.
    if (CFGetTypeID(cf_mimetype_dict) != CFDictionaryGetTypeID()) {
        goto finished;
    }

    // Verify that the key is a CFString.
    if (CFGetTypeID(cf_mimetype) != CFStringGetTypeID()) {
        goto finished;
    }

    // Find the length of the MIME Type, and allocate stack space for it.
    cf_length = CFStringGetMaximumSizeForEncoding(CFStringGetLength(cf_mimetype),
                                                  kCFStringEncodingUTF8);
    mimetype = alloca(cf_length + 1);

    // Extract the string.
    if (CFStringGetCString(cf_mimetype,
                           mimetype,
                           cf_length + 1,
                           kCFStringEncodingUTF8) != true) {
        goto finished;
    }

    // First we need to check if this type is disabled via WebPluginTypeEnabled.
    if (CFDictionaryGetValueIfPresent(cf_mimetype_dict,
                                      CFSTR("WebPluginTypeEnabled"),
                                      (const void **) &cf_enabled)) {
        // Verify that is a CFBoolean
        if (CFGetTypeID(cf_enabled) != CFBooleanGetTypeID()) {
            goto finished;
        }

        // Test value.
        if (CFBooleanGetValue(cf_enabled) == false) {
            goto finished;
        }
    }


    // Verify we have an empty string.
    if (!extensions) {
        goto finished;
    }

    // Now we need to lookup the extensions requested by the plugin.
    if (CFDictionaryGetValueIfPresent(cf_mimetype_dict,
                                      CFSTR("WebPluginExtensions"),
                                      (const void **) &cf_extensions)) {
        if (CFGetTypeID(cf_extensions) != CFArrayGetTypeID()) {
            goto finished;
        }

        l_debug("discovered %u extensions defined for mimetype %s",
                CFArrayGetCount(cf_extensions),
                mimetype);

        // Apply a function to every extension listed to concatenate them.
        CFArrayApplyFunction(cf_extensions,
                             CFRangeMake(0, CFArrayGetCount(cf_extensions)),
                             extension_array_applier,
                             &extensions);
    }

    // Now we need the description which is a CFString
    if (CFDictionaryGetValueIfPresent(cf_mimetype_dict,
                                      CFSTR("WebPluginTypeDescription"),
                                      (const void **) &cf_description)) {
        if (CFGetTypeID(cf_description) != CFStringGetTypeID()) {
            goto finished;
        }

        // Find the length of the MIME Type, and allocate stack space for it.
        cf_length = CFStringGetMaximumSizeForEncoding(CFStringGetLength(cf_description),
                                                      kCFStringEncodingUTF8);
        description = alloca(cf_length + 1);

        // Extract the string.
        if (CFStringGetCString(cf_description,
                               description,
                               cf_length + 1,
                               kCFStringEncodingUTF8) != true) {
            goto finished;
        }
    }

    // So now we need to assemble the final string.
    *result = realloc(*result,
                      (*result ? strlen(*result) : 0)
                        + strlen(mimetype) + 1
                        + strlen(description) + 1
                        + strlen(extensions) + 1
                        + 1
                        + 1);

    // Verify that worked.
    if (!*result) {
        goto finished;
    }

    // Create the final string.
    sprintf(*result, "%s%s%s:%s:%s",
            *result,
            strlen(*result) ? ";" : "",
            mimetype,
            extensions,
            description);

    l_debug("successfully processed mimetype %s", mimetype);

finished:
    free(extensions);
    return;
}
コード例 #11
0
/*
 * Creates a vector of driver bundle info structures from the hot-plug driver
 * directory.
 *
 * Returns NULL on error and a pointer to an allocated HPDriver vector on
 * success.  The caller must free the HPDriver with a call to
 * HPDriversRelease().
 */
static HPDriverVector HPDriversGetFromDirectory(const char *driverBundlePath)
{
#ifdef DEBUG_HOTPLUG
	Log2(PCSC_LOG_DEBUG, "Entering HPDriversGetFromDirectory: %s",
		driverBundlePath);
#endif

	int readersNumber = 0;
	HPDriverVector bundleVector = NULL;
	CFArrayRef bundleArray;
	CFStringRef driverBundlePathString =
		CFStringCreateWithCString(kCFAllocatorDefault,
		driverBundlePath,
		kCFStringEncodingMacRoman);
	CFURLRef pluginUrl = CFURLCreateWithFileSystemPath(kCFAllocatorDefault,
		driverBundlePathString,
		kCFURLPOSIXPathStyle, TRUE);

	CFRelease(driverBundlePathString);
	if (!pluginUrl)
	{
		Log1(PCSC_LOG_ERROR, "error getting plugin directory URL");
		return NULL;
	}
	bundleArray = CFBundleCreateBundlesFromDirectory(kCFAllocatorDefault,
		pluginUrl, NULL);
	if (!bundleArray)
	{
		Log1(PCSC_LOG_ERROR, "error getting plugin directory bundles");
		return NULL;
	}
	CFRelease(pluginUrl);

	size_t bundleArraySize = CFArrayGetCount(bundleArray);
	size_t i;

	/* get the number of readers (including aliases) */
	for (i = 0; i < bundleArraySize; i++)
	{
		CFBundleRef currBundle =
			(CFBundleRef) CFArrayGetValueAtIndex(bundleArray, i);
		CFDictionaryRef dict = CFBundleGetInfoDictionary(currBundle);

		const void * blobValue = CFDictionaryGetValue(dict,
			CFSTR(PCSCLITE_HP_MANUKEY_NAME));

		if (!blobValue)
		{
			Log1(PCSC_LOG_ERROR, "error getting vendor ID from bundle");
			return NULL;
		}

		if (CFGetTypeID(blobValue) == CFArrayGetTypeID())
		{
			/* alias found, each reader count as 1 */
			CFArrayRef propertyArray = blobValue;
			readersNumber += CFArrayGetCount(propertyArray);
		}
		else
			/* No alias, only one reader supported */
			readersNumber++;
	}
#ifdef DEBUG_HOTPLUG
	Log2(PCSC_LOG_DEBUG, "Total of %d readers supported", readersNumber);
#endif

	/* The last entry is an end marker (m_vendorId = 0)
	 * see checks in HPDriversMatchUSBDevices:503
	 *  and HPDriverVectorRelease:376 */
	readersNumber++;

	bundleVector = calloc(readersNumber, sizeof(HPDriver));
	if (!bundleVector)
	{
		Log1(PCSC_LOG_ERROR, "memory allocation failure");
		return NULL;
	}

	HPDriver *driverBundle = bundleVector;
	for (i = 0; i < bundleArraySize; i++)
	{
		CFBundleRef currBundle =
			(CFBundleRef) CFArrayGetValueAtIndex(bundleArray, i);
		CFDictionaryRef dict = CFBundleGetInfoDictionary(currBundle);

		CFURLRef bundleUrl = CFBundleCopyBundleURL(currBundle);
		CFStringRef bundlePath = CFURLCopyPath(bundleUrl);

		driverBundle->m_libPath = strdup(CFStringGetCStringPtr(bundlePath,
				CFStringGetSystemEncoding()));

		const void * blobValue = CFDictionaryGetValue(dict,
			CFSTR(PCSCLITE_HP_MANUKEY_NAME));

		if (!blobValue)
		{
			Log1(PCSC_LOG_ERROR, "error getting vendor ID from bundle");
			return bundleVector;
		}

		if (CFGetTypeID(blobValue) == CFArrayGetTypeID())
		{
			CFArrayRef vendorArray = blobValue;
			CFArrayRef productArray;
			CFArrayRef friendlyNameArray;
			char *libPath = driverBundle->m_libPath;

#ifdef DEBUG_HOTPLUG
			Log2(PCSC_LOG_DEBUG, "Driver with aliases: %s", libPath);
#endif
			/* get list of ProductID */
			productArray = CFDictionaryGetValue(dict,
				 CFSTR(PCSCLITE_HP_PRODKEY_NAME));
			if (!productArray)
			{
				Log1(PCSC_LOG_ERROR, "error getting product ID from bundle");
				return bundleVector;
			}

			/* get list of FriendlyName */
			friendlyNameArray = CFDictionaryGetValue(dict,
				 CFSTR(PCSCLITE_HP_NAMEKEY_NAME));
			if (!friendlyNameArray)
			{
				Log1(PCSC_LOG_ERROR, "error getting product ID from bundle");
				return bundleVector;
			}

			int reader_nb = CFArrayGetCount(vendorArray);

			if (reader_nb != CFArrayGetCount(productArray))
			{
				Log3(PCSC_LOG_ERROR,
					"Malformed Info.plist: %d vendors and %ld products",
					reader_nb, CFArrayGetCount(productArray));
				return bundleVector;
			}

			if (reader_nb != CFArrayGetCount(friendlyNameArray))
			{
				Log3(PCSC_LOG_ERROR,
					"Malformed Info.plist: %d vendors and %ld friendlynames",
					reader_nb, CFArrayGetCount(friendlyNameArray));
				return bundleVector;
			}

			int j;
			for (j=0; j<reader_nb; j++)
			{
				CFStringRef strValue = CFArrayGetValueAtIndex(vendorArray, j);

				driverBundle->m_vendorId = strtoul(CFStringGetCStringPtr(strValue,
					CFStringGetSystemEncoding()), NULL, 16);

				strValue = CFArrayGetValueAtIndex(productArray, j);
				driverBundle->m_productId = strtoul(CFStringGetCStringPtr(strValue,
					CFStringGetSystemEncoding()), NULL, 16);

				strValue = CFArrayGetValueAtIndex(friendlyNameArray, j);
				const char *cstr = CFStringGetCStringPtr(strValue,
					CFStringGetSystemEncoding());

				driverBundle->m_friendlyName = strdup(cstr);
				if (!driverBundle->m_libPath)
					driverBundle->m_libPath = strdup(libPath);

#ifdef DEBUG_HOTPLUG
				Log2(PCSC_LOG_DEBUG, "VendorID: 0x%04X",
					driverBundle->m_vendorId);
				Log2(PCSC_LOG_DEBUG, "ProductID: 0x%04X",
					driverBundle->m_productId);
				Log2(PCSC_LOG_DEBUG, "Friendly name: %s",
					driverBundle->m_friendlyName);
				Log2(PCSC_LOG_DEBUG, "Driver: %s", driverBundle->m_libPath);
#endif

				/* go to next bundle in the vector */
				driverBundle++;
			}
		}
		else
		{
			CFStringRef strValue = blobValue;

#ifdef DEBUG_HOTPLUG
			Log3(PCSC_LOG_DEBUG, "Driver without alias: %s %s",
				driverBundle->m_friendlyName, driverBundle->m_libPath);
#endif

			driverBundle->m_vendorId = strtoul(CFStringGetCStringPtr(strValue,
					CFStringGetSystemEncoding()), NULL, 16);

			strValue = (CFStringRef) CFDictionaryGetValue(dict,
				CFSTR(PCSCLITE_HP_PRODKEY_NAME));
			if (!strValue)
			{
				Log1(PCSC_LOG_ERROR, "error getting product ID from bundle");
				return bundleVector;
			}
			driverBundle->m_productId = strtoul(CFStringGetCStringPtr(strValue,
				CFStringGetSystemEncoding()), NULL, 16);

			strValue = (CFStringRef) CFDictionaryGetValue(dict,
				CFSTR(PCSCLITE_HP_NAMEKEY_NAME));
			if (!strValue)
			{
				Log1(PCSC_LOG_ERROR, "error getting product friendly name from bundle");
				driverBundle->m_friendlyName = strdup("unnamed device");
			}
			else
			{
				const char *cstr = CFStringGetCStringPtr(strValue,
					CFStringGetSystemEncoding());

				driverBundle->m_friendlyName = strdup(cstr);
			}
#ifdef DEBUG_HOTPLUG
			Log2(PCSC_LOG_DEBUG, "VendorID: 0x%04X", driverBundle->m_vendorId);
			Log2(PCSC_LOG_DEBUG, "ProductID: 0x%04X", driverBundle->m_productId);
			Log2(PCSC_LOG_DEBUG, "Friendly name: %s", driverBundle->m_friendlyName);
			Log2(PCSC_LOG_DEBUG, "Driver: %s", driverBundle->m_libPath);
#endif

			/* go to next bundle in the vector */
			driverBundle++;
		}
	}
	CFRelease(bundleArray);
	return bundleVector;
}
コード例 #12
0
ファイル: MoreCFQ.c プロジェクト: paullalonde/B
extern pascal Boolean CFQPropertyListIsLeaf(CFTypeRef node)
	// See comment in header.
{
	return ! (	   (CFGetTypeID(node) == CFDictionaryGetTypeID())
				|| (CFGetTypeID(node) == CFArrayGetTypeID())      );
}
コード例 #13
0
launch_data_t GTMLaunchDataCreateFromCFType(CFTypeRef cf_type_ref,
                                            CFErrorRef *error) {
  launch_data_t result = NULL;
  CFErrorRef local_error = NULL;
  if (cf_type_ref == NULL) {
    local_error = GTMCFLaunchCreateUnlocalizedError(EINVAL,
                                                    CFSTR("NULL CFType"));
    goto exit;
  }

  CFTypeID cf_type = CFGetTypeID(cf_type_ref);
  if (cf_type == CFStringGetTypeID()) {
    CFIndex length = CFStringGetLength(cf_type_ref);
    CFIndex max_length
      = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8) + 1;
    char *buffer = calloc(max_length, sizeof(char));
    size_t buffer_size = max_length * sizeof(char);
    if (buffer) {
      if (CFStringGetCString(cf_type_ref,
                             buffer,
                             buffer_size,
                             kCFStringEncodingUTF8)) {
        result = launch_data_alloc(LAUNCH_DATA_STRING);
        launch_data_set_string(result, buffer);
      } else {
        local_error
          = GTMCFLaunchCreateUnlocalizedError(EINVAL,
                                              CFSTR("CFStringGetCString failed %@"),
                                              cf_type_ref);
      }
      free(buffer);
    } else {
      local_error = GTMCFLaunchCreateUnlocalizedError(ENOMEM,
                                                      CFSTR("calloc of %lu failed"),
                                                      (unsigned long)buffer_size);
    }
  } else if (cf_type == CFBooleanGetTypeID()) {
    result = launch_data_alloc(LAUNCH_DATA_BOOL);
    launch_data_set_bool(result, CFBooleanGetValue(cf_type_ref));
  } else if (cf_type == CFArrayGetTypeID()) {
    CFIndex count = CFArrayGetCount(cf_type_ref);
    result = launch_data_alloc(LAUNCH_DATA_ARRAY);
    for (CFIndex i = 0; i < count; i++) {
      CFTypeRef array_value = CFArrayGetValueAtIndex(cf_type_ref, i);
      if (array_value) {
        launch_data_t launch_value
          = GTMLaunchDataCreateFromCFType(array_value, &local_error);
        if (local_error) break;
        launch_data_array_set_index(result, launch_value, i);
      }
    }
  } else if (cf_type == CFDictionaryGetTypeID()) {
    result = launch_data_alloc(LAUNCH_DATA_DICTIONARY);
    GTMCFToLDictContext context = { result, &local_error };
    CFDictionaryApplyFunction(cf_type_ref,
                              GTMConvertCFDictEntryToLaunchDataDictEntry,
                              &context);
  } else if (cf_type == CFDataGetTypeID()) {
    result = launch_data_alloc(LAUNCH_DATA_OPAQUE);
    launch_data_set_opaque(result,
                           CFDataGetBytePtr(cf_type_ref),
                           CFDataGetLength(cf_type_ref));
  } else if (cf_type == CFNumberGetTypeID()) {
    CFNumberType cf_number_type = CFNumberGetType(cf_type_ref);
    switch (cf_number_type) {
      case kCFNumberSInt8Type:
      case kCFNumberSInt16Type:
      case kCFNumberSInt32Type:
      case kCFNumberSInt64Type:
      case kCFNumberCharType:
      case kCFNumberShortType:
      case kCFNumberIntType:
      case kCFNumberLongType:
      case kCFNumberLongLongType:
      case kCFNumberCFIndexType:
      case kCFNumberNSIntegerType:{
        long long value;
        if (CFNumberGetValue(cf_type_ref, kCFNumberLongLongType, &value)) {
          result = launch_data_alloc(LAUNCH_DATA_INTEGER);
          launch_data_set_integer(result, value);
        } else {
          local_error
            = GTMCFLaunchCreateUnlocalizedError(EINVAL,
                                                CFSTR("Unknown to convert: %@"),
                                                cf_type_ref);
        }
        break;
      }

      case kCFNumberFloat32Type:
      case kCFNumberFloat64Type:
      case kCFNumberFloatType:
      case kCFNumberDoubleType:
      case kCFNumberCGFloatType: {
        double value;
        if (CFNumberGetValue(cf_type_ref, kCFNumberDoubleType, &value)) {
          result = launch_data_alloc(LAUNCH_DATA_REAL);
          launch_data_set_real(result, value);
        } else {
          local_error
            = GTMCFLaunchCreateUnlocalizedError(EINVAL,
                                                CFSTR("Unknown to convert: %@"),
                                                cf_type_ref);
        }
        break;
      }

      default:
        local_error
          = GTMCFLaunchCreateUnlocalizedError(EINVAL,
                                              CFSTR("Unknown CFNumberType %lld"),
                                              (long long)cf_number_type);
        break;
    }
  } else {
    local_error
      = GTMCFLaunchCreateUnlocalizedError(EINVAL,
                                          CFSTR("Unknown CFTypeID %lu"),
                                          (unsigned long)cf_type);
  }

exit:
  if (error) {
    *error = local_error;
  } else if (local_error) {
#ifdef DEBUG
    CFShow(local_error);
#endif //  DEBUG
    CFRelease(local_error);
  }
  return result;
}
コード例 #14
0
ファイル: osxInput.cpp プロジェクト: HwakyoungLee/opentnl
void InitJoystick()
{
   mach_port_t masterPort = NULL;
	io_iterator_t hidObjectIterator = NULL;

	IOReturn result = IOMasterPort (bootstrap_port, &masterPort);
   if(result != kIOReturnSuccess)
      return;
   
   CFMutableDictionaryRef hidMatchDictionary = IOServiceMatching (kIOHIDDeviceKey);
   if(!hidMatchDictionary)
      return;
	result = IOServiceGetMatchingServices (masterPort, hidMatchDictionary, &hidObjectIterator);
   if(result != kIOReturnSuccess)
      return;

   // find the first joystick/gamepad on the USB
   for(;;)
   {
      IOHIDDeviceInterface **device;
      io_object_t ioHIDDeviceObject = IOIteratorNext(hidObjectIterator);
      if(!ioHIDDeviceObject)
         break;

      CFMutableDictionaryRef hidProperties = 0;
      long kresult = IORegistryEntryCreateCFProperties(ioHIDDeviceObject, &hidProperties, kCFAllocatorDefault, kNilOptions);
      if(kresult == KERN_SUCCESS && hidProperties)
      {
			CFTypeRef refCF = 0;
			refCF = CFDictionaryGetValue (hidProperties, CFSTR(kIOHIDProductKey));
			
			if(CFGetTypeID(refCF) == CFStringGetTypeID())
			{
				CFIndex bufferSize = CFStringGetLength (refCF) + 1;
				char * buffer = (char *)malloc (bufferSize);
				if (buffer)
				{
					if (CFStringGetCString (refCF, buffer, bufferSize, CFStringGetSystemEncoding ()))
						strncpy(gJoystickName, buffer, MaxJoystickNameLen);
					free(buffer);
				}
			}
			refCF = CFDictionaryGetValue (hidProperties, CFSTR(kIOHIDPrimaryUsagePageKey));
         long usage, usagePage;
			CFNumberGetValue (refCF, kCFNumberLongType, &usagePage);
         refCF = CFDictionaryGetValue (hidProperties, CFSTR(kIOHIDPrimaryUsageKey));
			CFNumberGetValue (refCF, kCFNumberLongType, &usage);

   		if ( (usagePage == kHIDPage_GenericDesktop) &&
		     ((usage == kHIDUsage_GD_Joystick ||
		      usage == kHIDUsage_GD_GamePad)) )
         {
	         CFTypeRef refElementTop = CFDictionaryGetValue (hidProperties, CFSTR(kIOHIDElementKey));
	         if (refElementTop)
            {
	            CFTypeID type = CFGetTypeID (refElementTop);
	            if (type == CFArrayGetTypeID()) /* if element is an array */
	            {
		            CFRange range = {0, CFArrayGetCount (refElementTop)};
		            /* CountElementsCFArrayHandler called for each array member */
		            CFArrayApplyFunction (refElementTop, range, HIDGetElementsCFArrayHandler, NULL);

                  IOCFPlugInInterface ** ppPlugInInterface = NULL;
					S32 score;
		            IOReturn result = IOCreatePlugInInterfaceForService (ioHIDDeviceObject, kIOHIDDeviceUserClientTypeID,
													            kIOCFPlugInInterfaceID, &ppPlugInInterface, &score);
		            if (result == kIOReturnSuccess)
		            {
			            // Call a method of the intermediate plug-in to create the device interface
			            (*ppPlugInInterface)->QueryInterface (ppPlugInInterface,
								            CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID), (void *) &device);
                     if(device)
                     {
                        result = (*device)->open(device, 0);
                        gController.device = device;
                        gJoystickInit = true;
                     }
                     (*ppPlugInInterface)->Release (ppPlugInInterface);
                  }
               }
            }
         }
         CFRelease(hidProperties);
      }
      IOObjectRelease(ioHIDDeviceObject);
      if(gJoystickInit)
         break;
   }
	IOObjectRelease (hidObjectIterator); /* release the iterator */
}
コード例 #15
0
ファイル: CFTypeAddition.c プロジェクト: darling0825/Core-Lib
void PrintCFTypeInternalFormat(CFTypeRef value, uint32_t depth) {
	bool foundType = false;
	CFStringRef valueType = CFCopyTypeIDDescription(CFGetTypeID(value));
	CFStringRef dictionaryType = CFCopyTypeIDDescription(CFDictionaryGetTypeID());
	if (CFStringCompare(valueType, dictionaryType, 0x0) == kCFCompareEqualTo) {
		foundType = true;
		printf("{\n");
		PrintCFDictionaryInternalFormatting(value, depth+0x1);
		PrintDepth(depth,"}\n");
	}
	CFSafeRelease(dictionaryType);
	
	CFStringRef booleanType = CFCopyTypeIDDescription(CFBooleanGetTypeID());
	if (CFStringCompare(valueType, booleanType, 0x0) == kCFCompareEqualTo) {
		foundType = true;
		printf("%s\n",(CFBooleanGetValue(value) ? "True" : "False"));
	}
	CFSafeRelease(booleanType);
	
	CFStringRef stringType = CFCopyTypeIDDescription(CFStringGetTypeID());
	if (CFStringCompare(valueType, stringType, 0x0) == kCFCompareEqualTo) {
		foundType = true;
		printf("%s\n",(char*)CFStringGetCStringPtr(value,kCFStringEncodingUTF8));
	}
	CFSafeRelease(stringType);
	
	CFStringRef numberType = CFCopyTypeIDDescription(CFNumberGetTypeID());
	if (CFStringCompare(valueType, numberType, 0x0) == kCFCompareEqualTo) {
		foundType = true;
		CFIndex numberType = CFNumberGetType(value);
		switch (numberType) {
			case kCFNumberSInt8Type: {
				SInt8 number;
				CFNumberGetValue(value, numberType, &number);
				printf("%hhd\n",number);
				break;
			};
			case kCFNumberSInt16Type: {
				SInt16 number;
				CFNumberGetValue(value, numberType, &number);
				printf("%hd\n",number);
				break;
			};
			case kCFNumberSInt32Type: {
				SInt32 number;
				CFNumberGetValue(value, numberType, &number);
				printf("%d\n",(int32_t)number);
				break;
			};
			case kCFNumberSInt64Type: {
				SInt64 number;
				CFNumberGetValue(value, numberType, &number);
				printf("%lld\n",number);
				break;
			};
			case kCFNumberFloat32Type: {
				Float32 number;
				CFNumberGetValue(value, numberType, &number);
				printf("%.f\n",number);
				break;
			};
			case kCFNumberFloat64Type: {
				Float64 number;
				CFNumberGetValue(value, numberType, &number);
				printf("%.f\n",number);
				break;
			};
			case kCFNumberCharType: {
				char number;
				CFNumberGetValue(value, numberType, &number);
				printf("%c\n",number);
				break;
			};
			case kCFNumberShortType: {
				short number;
				CFNumberGetValue(value, numberType, &number);
				printf("%hd\n",number);
				break;
			};
			case kCFNumberIntType: {
				int number;
				CFNumberGetValue(value, numberType, &number);
				printf("%d\n",number);
				break;
			};
			case kCFNumberLongType: {
				long number;
				CFNumberGetValue(value, numberType, &number);
				printf("%ld\n",number);
				break;
			};
			case kCFNumberLongLongType: {
				long long number;
				CFNumberGetValue(value, numberType, &number);
				printf("%qd\n",number);
				break;
			};
			case kCFNumberFloatType: {
				float number;
				CFNumberGetValue(value, numberType, &number);
				printf("%.f\n",number);
				break;
			};
			case kCFNumberDoubleType: {
				double number;
				CFNumberGetValue(value, numberType, &number);
				printf("%.f\n",number);
				break;
			};
			case kCFNumberCFIndexType: {
				CFIndex number;
				CFNumberGetValue(value, numberType, &number);
				printf("%ld\n",number);
				break;
			};
			case kCFNumberNSIntegerType: {
				NSInteger number;
				CFNumberGetValue(value, numberType, &number);
				printf("%ld\n",(long)number);
				break;
			};
			case kCFNumberCGFloatType: {
				CGFloat number;
				CFNumberGetValue(value, numberType, &number);
				printf("%.f\n",number);
				break;
			};
			default: {
				break;
			};
		}
	}
	CFSafeRelease(numberType);
	
	CFStringRef arrayType = CFCopyTypeIDDescription(CFArrayGetTypeID());
	if (CFStringCompare(valueType, arrayType, 0x0) == kCFCompareEqualTo) {
		foundType = true;
		CFIndex count = CFArrayGetCount(value);
		printf("[\n");
		for (CFIndex i = 0x0; i < count; i++) {
			CFTypeRef item = CFArrayGetValueAtIndex(value, i);
			PrintDepth(depth+0x1,"");
			PrintCFTypeInternalFormat(item, depth+0x1);
		}
		PrintDepth(depth,"]\n");
	}
	CFSafeRelease(arrayType);
	
	if (!foundType) {
		CFStringRef description = CFCopyDescription(value);
		printf("%s\n",(char*)CFStringGetCStringPtr(description,kCFStringEncodingUTF8));
		CFSafeRelease(description);
	}
	
	CFSafeRelease(valueType);
}
コード例 #16
0
static const char *			/* O - Locale string */
appleLangDefault(void)
{
  int			i;		/* Looping var */
  CFBundleRef		bundle;		/* Main bundle (if any) */
  CFArrayRef		bundleList;	/* List of localizations in bundle */
  CFPropertyListRef 	localizationList;
					/* List of localization data */
  CFStringRef		languageName;	/* Current name */
  CFStringRef		localeName;	/* Canonical from of name */
  char			*lang;		/* LANG environment variable */
  _cups_globals_t	*cg = _cupsGlobals();
  					/* Pointer to library globals */


  DEBUG_puts("2appleLangDefault()");

 /*
  * Only do the lookup and translation the first time.
  */

  if (!cg->language[0])
  {
    if (getenv("SOFTWARE") != NULL && (lang = getenv("LANG")) != NULL)
    {
      DEBUG_printf(("3appleLangDefault: Using LANG=%s", lang));
      strlcpy(cg->language, lang, sizeof(cg->language));
      return (cg->language);
    }
    else if ((bundle = CFBundleGetMainBundle()) != NULL &&
             (bundleList = CFBundleCopyBundleLocalizations(bundle)) != NULL)
    {
      DEBUG_puts("3appleLangDefault: Getting localizationList from bundle.");

      localizationList =
	  CFBundleCopyPreferredLocalizationsFromArray(bundleList);

      CFRelease(bundleList);
    }
    else
    {
      DEBUG_puts("3appleLangDefault: Getting localizationList from preferences.");

      localizationList =
	  CFPreferencesCopyAppValue(CFSTR("AppleLanguages"),
				    kCFPreferencesCurrentApplication);
    }

    if (localizationList)
    {

#ifdef DEBUG
      if (CFGetTypeID(localizationList) == CFArrayGetTypeID())
        DEBUG_printf(("3appleLangDefault: Got localizationList, %d entries.",
                      (int)CFArrayGetCount(localizationList)));
      else
        DEBUG_puts("3appleLangDefault: Got localizationList but not an array.");
#endif /* DEBUG */

      if (CFGetTypeID(localizationList) == CFArrayGetTypeID() &&
	  CFArrayGetCount(localizationList) > 0)
      {
	languageName = CFArrayGetValueAtIndex(localizationList, 0);

	if (languageName &&
	    CFGetTypeID(languageName) == CFStringGetTypeID())
	{
	  localeName = CFLocaleCreateCanonicalLocaleIdentifierFromString(
			   kCFAllocatorDefault, languageName);

	  if (localeName)
	  {
	    CFStringGetCString(localeName, cg->language, sizeof(cg->language),
			       kCFStringEncodingASCII);
	    CFRelease(localeName);

	    DEBUG_printf(("3appleLangDefault: cg->language=\"%s\"",
			  cg->language));

	   /*
	    * Map new language identifiers to locales...
	    */

	    for (i = 0;
		 i < (int)(sizeof(apple_language_locale) /
		           sizeof(apple_language_locale[0]));
		 i ++)
	    {
	      if (!strcmp(cg->language, apple_language_locale[i].language))
	      {
		DEBUG_printf(("3appleLangDefault: mapping \"%s\" to \"%s\"...",
			      cg->language, apple_language_locale[i].locale));
		strlcpy(cg->language, apple_language_locale[i].locale,
			sizeof(cg->language));
		break;
	      }
	    }

	   /*
	    * Convert language subtag into region subtag...
	    */

	    if (cg->language[2] == '-')
	      cg->language[2] = '_';

	    if (!strchr(cg->language, '.'))
	      strlcat(cg->language, ".UTF-8", sizeof(cg->language));
	  }
	  else
	    DEBUG_puts("3appleLangDefault: Unable to get localeName.");
	}
      }

      CFRelease(localizationList);
    }

   /*
    * If we didn't find the language, default to en_US...
    */

    if (!cg->language[0])
    {
      DEBUG_puts("3appleLangDefault: Defaulting to en_US.");
      strlcpy(cg->language, "en_US.UTF-8", sizeof(cg->language));
    }
  }

 /*
  * Return the cached locale...
  */

  return (cg->language);
}
コード例 #17
0
char *
_mongoc_secure_transport_RFC2253_from_cert (SecCertificateRef cert)
{
   CFTypeRef value;
   bson_string_t *retval;
   CFTypeRef subject_name;
   CFDictionaryRef cert_dict;

   cert_dict = SecCertificateCopyValues (cert, NULL, NULL);
   if (!cert_dict) {
      return NULL;
   }

   subject_name = CFDictionaryGetValue (cert_dict, kSecOIDX509V1SubjectName);
   if (!subject_name) {
      CFRelease (cert_dict);
      return NULL;
   }

   subject_name = CFDictionaryGetValue (subject_name, kSecPropertyKeyValue);
   if (!subject_name) {
      CFRelease (cert_dict);
      return NULL;
   }

   retval = bson_string_new ("");;

   value = _mongoc_secure_transport_dict_get (subject_name, kSecOIDCommonName);
   _bson_append_cftyperef (retval, "CN=", value);

   value = _mongoc_secure_transport_dict_get (subject_name, kSecOIDOrganizationalUnitName);
   if (value) {
      /* Can be either one unit name, or array of unit names */
      if (CFGetTypeID(value) == CFStringGetTypeID()) {
         _bson_append_cftyperef (retval, ",OU=", value);
      } else if (CFGetTypeID(value) == CFArrayGetTypeID()) {
         CFIndex len = CFArrayGetCount(value);

         if (len > 0) {
            _bson_append_cftyperef (retval, ",OU=", CFArrayGetValueAtIndex(value, 0));
         }
         if (len > 1) {
            _bson_append_cftyperef (retval, ",", CFArrayGetValueAtIndex(value, 1));
         }
         if (len > 2) {
            _bson_append_cftyperef (retval, ",", CFArrayGetValueAtIndex(value, 2));
         }
      }
   }

   value = _mongoc_secure_transport_dict_get (subject_name, kSecOIDOrganizationName);
   _bson_append_cftyperef (retval, ",O=", value);

   value = _mongoc_secure_transport_dict_get (subject_name, kSecOIDLocalityName);
   _bson_append_cftyperef (retval, ",L=", value);

   value = _mongoc_secure_transport_dict_get (subject_name, kSecOIDStateProvinceName);
   _bson_append_cftyperef (retval, ",ST=", value);

   value = _mongoc_secure_transport_dict_get (subject_name, kSecOIDCountryName);
   _bson_append_cftyperef (retval, ",C=", value);

   /* This seems rarely used */
   value = _mongoc_secure_transport_dict_get (subject_name, kSecOIDStreetAddress);
   _bson_append_cftyperef (retval, ",STREET", value);

   CFRelease (cert_dict);
   return bson_string_free (retval, false);
}
コード例 #18
0
ファイル: langprefs.c プロジェクト: 5py/hddtemp
const char *
_nl_language_preferences_default (void)
{
#if HAVE_CFPREFERENCESCOPYAPPVALUE /* MacOS X 10.2 or newer */
  {
    /* Cache the preferences list, since CoreFoundation calls are expensive.  */
    static const char *cached_languages;
    static int cache_initialized;

    if (!cache_initialized)
      {
	CFTypeRef preferences =
	  CFPreferencesCopyAppValue (CFSTR ("AppleLanguages"),
				     kCFPreferencesCurrentApplication);
	if (preferences != NULL
	    && CFGetTypeID (preferences) == CFArrayGetTypeID ())
	  {
	    CFArrayRef prefArray = (CFArrayRef)preferences;
	    int n = CFArrayGetCount (prefArray);
	    char buf[256];
	    size_t size = 0;
	    int i;

	    for (i = 0; i < n; i++)
	      {
		CFTypeRef element = CFArrayGetValueAtIndex (prefArray, i);
		if (element != NULL
		    && CFGetTypeID (element) == CFStringGetTypeID ()
		    && CFStringGetCString ((CFStringRef)element,
					   buf, sizeof (buf),
					   kCFStringEncodingASCII))
		  {
		    size += strlen (buf) + 1;
		    /* Most GNU programs use msgids in English and don't ship
		       an en.mo message catalog.  Therefore when we see "en"
		       in the preferences list, arrange for gettext() to
		       return the msgid, and ignore all further elements of
		       the preferences list.  */
		    if (strcmp (buf, "en") == 0)
		      break;
		  }
		else
		  break;
	      }
	    if (size > 0)
	      {
		char *languages = (char *) malloc (size);

		if (languages != NULL)
		  {
		    char *p = languages;

		    for (i = 0; i < n; i++)
		      {
			CFTypeRef element =
			  CFArrayGetValueAtIndex (prefArray, i);
			if (element != NULL
		            && CFGetTypeID (element) == CFStringGetTypeID ()
			    && CFStringGetCString ((CFStringRef)element,
						   buf, sizeof (buf),
						   kCFStringEncodingASCII))
			  {
			    strcpy (p, buf);
			    p += strlen (buf);
			    *p++ = ':';
			    if (strcmp (buf, "en") == 0)
			      break;
			  }
			else
			  break;
		      }
		    *--p = '\0';

		    cached_languages = languages;
		  }
	      }
	  }
	cache_initialized = 1;
      }
    if (cached_languages != NULL)
      return cached_languages;
  }
#endif

  return NULL;
}
コード例 #19
0
UString UserObjectImp::toString(ExecState *exec) const
{
    UString result;
    JSUserObject* jsObjPtr = KJSValueToJSObject(toObject(exec), exec);
    CFTypeRef cfValue = jsObjPtr ? jsObjPtr->CopyCFValue() : 0;
    if (cfValue)
    {
        CFTypeID cfType = CFGetTypeID(cfValue);
        if (cfValue == GetCFNull())
        {
            //
        }
        else if (cfType == CFBooleanGetTypeID())
        {
            if (cfValue == kCFBooleanTrue)
            {
                result = "true";
            }
            else
            {
                result = "false";
            }
        }
        else if (cfType == CFStringGetTypeID())
        {
            result = CFStringToUString((CFStringRef)cfValue);
        }
        else if (cfType == CFNumberGetTypeID())
        {
            if (cfValue == kCFNumberNaN)
            {
                result = "Nan";
            }
            else if (CFNumberCompare(kCFNumberPositiveInfinity, (CFNumberRef)cfValue, 0) == 0)
            {
                result = "Infinity";
            }
            else if (CFNumberCompare(kCFNumberNegativeInfinity, (CFNumberRef)cfValue, 0) == 0)
            {
                result = "-Infinity";
            }
            else
            {
                CFStringRef cfNumStr;
                double d = 0;
                CFNumberGetValue((CFNumberRef)cfValue, kCFNumberDoubleType, &d);
                if (CFNumberIsFloatType((CFNumberRef)cfValue))
                {
                    cfNumStr = CFStringCreateWithFormat(0, 0, CFSTR("%f"), d);
                }
                else
                {
                    cfNumStr = CFStringCreateWithFormat(0, 0, CFSTR("%.0f"), d);
                }
                result = CFStringToUString(cfNumStr);
                ReleaseCFType(cfNumStr);
            }
        }
        else if (cfType == CFArrayGetTypeID())
        {
            //
        }
        else if (cfType == CFDictionaryGetTypeID())
        {
            //
        }
        else if (cfType == CFSetGetTypeID())
        {
            //
        }
        else if (cfType == CFURLGetTypeID())
        {
            CFURLRef absURL = CFURLCopyAbsoluteURL((CFURLRef)cfValue);
            if (absURL)
            {
                CFStringRef cfStr = CFURLGetString(absURL);
                if (cfStr)
                {
                    result = CFStringToUString(cfStr);
                }
                ReleaseCFType(absURL);
            }
        }
    }
    ReleaseCFType(cfValue);
    if (jsObjPtr) jsObjPtr->Release();
    return result;
}
コード例 #20
0
/*
 * Display a Trust Settings array as obtained from
 * SecTrustSettingsCopyTrustSettings().
 */
static int displayTrustSettings(
	CFArrayRef	trustSettings)
{
	/* must always be there though it may be empty */
	if(trustSettings == NULL) {
		fprintf(stderr, "***displayTrustSettings: missing trust settings array");
		return -1;
	}
	if(CFGetTypeID(trustSettings) != CFArrayGetTypeID()) {
		fprintf(stderr, "***displayTrustSettings: malformed trust settings array");
		return -1;
	}

	int ourRtn = 0;
	CFIndex numUseConstraints = CFArrayGetCount(trustSettings);
	indentIncr();
	indent(); printf("Number of trust settings : %ld\n", (long)numUseConstraints);
	OSStatus ortn;
	SecPolicyRef certPolicy;
	SecTrustedApplicationRef certApp;
	CFDictionaryRef ucDict;
	CFStringRef policyStr;
	CFNumberRef cfNum;
	CFIndex ucDex;

	/* grind thru the trust settings dictionaries */
	for(ucDex=0; ucDex<numUseConstraints; ucDex++) {
		indent(); printf("Trust Setting %ld:\n", (long)ucDex);
		indentIncr();

		ucDict = (CFDictionaryRef)CFArrayGetValueAtIndex(trustSettings, ucDex);
		if(CFGetTypeID(ucDict) != CFDictionaryGetTypeID()) {
			fprintf(stderr, "***displayTrustSettings: malformed usage constraints dictionary");
			ourRtn = -1;
			goto nextAp;
		}

		/* policy - optional */
		certPolicy = (SecPolicyRef)CFDictionaryGetValue(ucDict, kSecTrustSettingsPolicy);
		if(certPolicy != NULL) {
			if(CFGetTypeID(certPolicy) != SecPolicyGetTypeID()) {
				fprintf(stderr, "***displayTrustSettings: malformed certPolicy");
				ourRtn = -1;
				goto nextAp;
			}
			CSSM_OID policyOid;
			ortn = SecPolicyGetOID(certPolicy, &policyOid);
			if(ortn) {
				cssmPerror("SecPolicyGetOID", ortn);
				ourRtn = -1;
				goto nextAp;
			}
			indent(); printf("Policy OID            : %s\n",
					oidToOidString(&policyOid));
		}

		/* app - optional  */
		certApp = (SecTrustedApplicationRef)CFDictionaryGetValue(ucDict,
			kSecTrustSettingsApplication);
		if(certApp != NULL) {
			if(CFGetTypeID(certApp) != SecTrustedApplicationGetTypeID()) {
				fprintf(stderr, "***displayTrustSettings: malformed certApp");
				ourRtn = -1;
				goto nextAp;
			}
			CFDataRef appPath = NULL;
			ortn = SecTrustedApplicationCopyData(certApp, &appPath);
			if(ortn) {
				cssmPerror("SecTrustedApplicationCopyData", ortn);
				ourRtn = -1;
				goto nextAp;
			}
			indent(); printf("Application           : %s", CFDataGetBytePtr(appPath));
			printf("\n");
			CFRelease(appPath);
		}

		/* policy string */
		policyStr = (CFStringRef)CFDictionaryGetValue(ucDict, kSecTrustSettingsPolicyString);
		if(policyStr != NULL) {
			if(CFGetTypeID(policyStr) != CFStringGetTypeID()) {
				fprintf(stderr, "***displayTrustSettings: malformed policyStr");
				ourRtn = -1;
				goto nextAp;
			}
			indent(); printf("Policy String         : ");
			printCfStr(policyStr); printf("\n");
		}

		/* Allowed error */
		cfNum = (CFNumberRef)CFDictionaryGetValue(ucDict, kSecTrustSettingsAllowedError);
		if(cfNum != NULL) {
			if(CFGetTypeID(cfNum) != CFNumberGetTypeID()) {
				fprintf(stderr, "***displayTrustSettings: malformed allowedError");
				ourRtn = -1;
				goto nextAp;
			}
			indent(); printf("Allowed Error         : ");
			printCssmErr(cfNum); printf("\n");
		}

		/* ResultType */
		cfNum = (CFNumberRef)CFDictionaryGetValue(ucDict, kSecTrustSettingsResult);
		if(cfNum != NULL) {
			if(CFGetTypeID(cfNum) != CFNumberGetTypeID()) {
				fprintf(stderr, "***displayTrustSettings: malformed ResultType");
				ourRtn = -1;
				goto nextAp;
			}
			indent(); printf("Result Type           : ");
			printResultType(cfNum); printf("\n");
		}

		/* key usage */
		cfNum = (CFNumberRef)CFDictionaryGetValue(ucDict, kSecTrustSettingsKeyUsage);
		if(cfNum != NULL) {
			if(CFGetTypeID(cfNum) != CFNumberGetTypeID()) {
				fprintf(stderr, "***displayTrustSettings: malformed keyUsage");
				ourRtn = -1;
				goto nextAp;
			}
			indent(); printf("Key Usage             : ");
			printKeyUsage(cfNum); printf("\n");
		}

	nextAp:
		indentDecr();
	}
	indentDecr();
	return ourRtn;
}