Example #1
0
// Given a data structure representing document type data, or a list of such
// structures, find the one which matches a particular file extension
// The result will be a CFDictionary containining document type data
// if a match is found, or null otherwise
CFDictionaryRef GetDocTypeForExt( CFTypeRef docTypeData, CFStringRef requiredExt )
{
    if( !docTypeData )
        return NULL;

    if( CFGetTypeID( docTypeData ) == CFArrayGetTypeID() )
    {
        CFTypeRef item;
        CFArrayRef docTypes;
        docTypes = reinterpret_cast< CFArrayRef >( docTypeData );

        for( CFIndex i = 0, n = CFArrayGetCount( docTypes ); i < n; i++ )
        {
            item = CFArrayGetValueAtIndex( docTypes, i );

            if( CFGetTypeID( item ) == CFDictionaryGetTypeID() )
            {
                CFDictionaryRef docType;
                docType = reinterpret_cast< CFDictionaryRef >( item );

                if( CheckDocTypeMatchesExt( docType, requiredExt ) )
                    return docType;
            }
        }
    }

    if( CFGetTypeID( docTypeData ) == CFDictionaryGetTypeID() )
    {
        CFDictionaryRef docType = reinterpret_cast< CFDictionaryRef >( docTypeData );

        if( CheckDocTypeMatchesExt( docType, requiredExt ) )
            return docType;
    }

    return NULL;
}
static void
HIDTopLevelElementHandler(const void *value, void *parameter)
{
    CFTypeRef refCF = 0;
    if (CFGetTypeID(value) != CFDictionaryGetTypeID())
        return;
    refCF = CFDictionaryGetValue(value, CFSTR(kIOHIDElementUsagePageKey));
    if (!CFNumberGetValue
        (refCF, kCFNumberLongType, &((recDevice *) parameter)->usagePage))
        SDL_SetError("CFNumberGetValue error retrieving pDevice->usagePage.");
    refCF = CFDictionaryGetValue(value, CFSTR(kIOHIDElementUsageKey));
    if (!CFNumberGetValue
        (refCF, kCFNumberLongType, &((recDevice *) parameter)->usage))
        SDL_SetError("CFNumberGetValue error retrieving pDevice->usage.");
}
		// Given a CFData object generated by the save command, this will re-establish
		// the CAStreamBasicDescription
OSStatus	CAStreamBasicDescription::Restore (CFPropertyListRef& inData)
{
	if (CFGetTypeID (inData) != CFDictionaryGetTypeID()) return -1;
	CACFDictionary dict(static_cast<CFDictionaryRef>(inData), false);
	
	if (!dict.GetFloat64 (kSampleRate, mSampleRate)) return -1;
	if (!dict.GetUInt32 (kFormat, mFormatID)) return -1;
	if (!dict.GetUInt32 (kFormatFlags, mFormatFlags)) return -1;
	if (!dict.GetUInt32 (kPacketBytes, mBytesPerPacket)) return -1;
	if (!dict.GetUInt32 (kFramePackets, mFramesPerPacket)) return -1;
	if (!dict.GetUInt32 (kFrameBytes, mBytesPerFrame)) return -1;
	if (!dict.GetUInt32 (kFrameChannels, mChannelsPerFrame)) return -1;
	if (!dict.GetUInt32 (kChannelBits, mBitsPerChannel)) return -1;

	return noErr;
}
Example #4
0
void mUSBHID::registerHIDProperties(CFTypeRef object){
	CFTypeID type = CFGetTypeID(object);
	if (type == CFArrayGetTypeID()){
		registerHID_CFArray((const __CFArray*)object);
	} else if (type == CFDictionaryGetTypeID()){
		registerHID_CFDictionary((const __CFDictionary*)object);
	} else if (type == CFBooleanGetTypeID()){
		//MyCFBoolean(object);
	} else if (type == CFNumberGetTypeID()){
		//MyCFNumberShow(object);
	} else if (type == CFStringGetTypeID()){
		//MyCFStringShow(object);
	} else{
		//mprintf("<unknown hid object>");
	}
}
Example #5
0
bool KeyedDecoder::beginArray(const String& key)
{
    auto array = dynamic_cf_cast<CFArrayRef>(CFDictionaryGetValue(m_dictionaryStack.last(), key.createCFString().get()));
    if (!array)
        return false;

    for (CFIndex i = 0; i < CFArrayGetCount(array); ++i) {
        CFTypeRef object = CFArrayGetValueAtIndex(array, i);
        if (CFGetTypeID(object) != CFDictionaryGetTypeID())
            return false;
    }

    m_arrayStack.append(array);
    m_arrayIndexStack.append(0);
    return true;
}
bool	CACFDictionary::GetDictionary(const CFStringRef inKey, CFDictionaryRef& outValue) const
{
	bool theAnswer = false;
	
	CFTypeRef theValue = NULL;
	if(GetCFType(inKey, theValue))
	{
		if((theValue != NULL) && (CFGetTypeID(theValue) == CFDictionaryGetTypeID()))
		{
			outValue = static_cast<CFDictionaryRef>(theValue);
			theAnswer = true;
		}
	}
	
	return theAnswer;
}
Example #7
0
bool	CACFArray::GetDictionary(UInt32 inIndex, CFDictionaryRef& outItem) const
{
	bool theAnswer = false;
	
	CFTypeRef theItem = NULL;
	if(GetCFType(inIndex, theItem))
	{
		if((theItem != NULL) && (CFGetTypeID(theItem) == CFDictionaryGetTypeID()))
		{
			outItem = static_cast<CFDictionaryRef>(theItem);
			theAnswer = true;
		}
	}
	
	return theAnswer;
}
Example #8
0
static void
_rd_prefs_load_recent_files(rd_recent_file_t *r, int num_files, CFStringRef app)
{
    assert(r != NULL);
    assert(app != NULL);

    CFArrayRef the_array = CFPreferencesCopyAppValue(CFSTR("recent_files"), app);
    if (the_array == NULL) {
        return;
    }
    
    CFIndex array_count = CFArrayGetCount(the_array);        
    int i;
    for (i = 0; i < num_files; i++) {
        rd_recent_file_t *f = &r[i];
        if (i >= array_count) {
            bzero(f, sizeof(*f));
        } else {
            const void *f_val    = CFArrayGetValueAtIndex(the_array, i);
            if (CFGetTypeID(f_val) == CFStringGetTypeID()) {
                // string.  set the time to now.
                if (CFStringGetCString(f_val, f->path, sizeof(f->path), kCFStringEncodingUTF8)) {
                    // success 
                    f->path[sizeof(f->path) - 1] = '\0';
                    f->last_atime = (unsigned long) time(NULL);
                }
            } else if (CFGetTypeID(f_val) == CFDictionaryGetTypeID()) {
                CFStringRef f_name  = CFDictionaryGetValue(f_val, CFSTR("name"));
                CFNumberRef f_atime = CFDictionaryGetValue(f_val, CFSTR("atime"));
                
                if (CFStringGetCString(f_name, f->path, sizeof(f->path), kCFStringEncodingUTF8)) {
                    // success
                    f->path[sizeof(f->path) - 1] = '\0';
                
                    if (CFNumberGetValue(f_atime, kCFNumberLongType, (long*) &f->last_atime)) {
                        // success
                    } else {
                        f->last_atime = (unsigned long) time(NULL);
                    }
                }
            }
        }
    }
    
    CFRelease(the_array);
}
Example #9
0
static Boolean
MyBurnSessionDeviceCheckCallBack(DRBurnSessionRef burnSession, DRDeviceRef device)
{
    #pragma unused(burnSession)
    
    CFDictionaryRef deviceDict;
    CFDictionaryRef writeCapDict;
    CFBooleanRef canWriteDVDRAM;
    CFStringRef vendorName;
    CFStringRef productName;
    char vendor[256];
    char product[256];
    Boolean showDeviceInList;
    
    /* DRDeviceCopyInfo will return information that identifies the device and describes its
    capabilities. The information includes the vendor's name, the product identifier, whether 
    the device can burn CDs or DVDs, and so on. */
    deviceDict = DRDeviceCopyInfo(device);
    assert(deviceDict != NULL);
        
    vendorName = CFDictionaryGetValue(deviceDict, kDRDeviceVendorNameKey);
    assert((vendorName != NULL) && (CFGetTypeID(vendorName) == CFStringGetTypeID()));
    
    productName = CFDictionaryGetValue(deviceDict, kDRDeviceProductNameKey);
    assert((productName != NULL) && (CFGetTypeID(productName) == CFStringGetTypeID()));
        
    if (CFStringGetCString(vendorName, vendor, sizeof(vendor), kCFStringEncodingASCII)) {
        if (CFStringGetCString(productName, product, sizeof(product), kCFStringEncodingASCII)) {
        
            fprintf(stderr, "%s ", vendor);
            fprintf(stderr, "%s Checked.\n", product);
        }
    }
    
    writeCapDict = CFDictionaryGetValue(deviceDict, kDRDeviceWriteCapabilitiesKey);
    assert((writeCapDict != NULL) && (CFGetTypeID(writeCapDict) == CFDictionaryGetTypeID()));
    
    canWriteDVDRAM = CFDictionaryGetValue(writeCapDict, kDRDeviceCanWriteDVDRAMKey);
    assert((canWriteDVDRAM != NULL) && (CFGetTypeID(canWriteDVDRAM) == CFBooleanGetTypeID()));

    // Don't show DVD-RAM drives in the list.
    showDeviceInList = !CFBooleanGetValue(canWriteDVDRAM);
    CFRelease(deviceDict);
    
    return showDeviceInList;
}
Example #10
0
//
// Process % scan forms.
// This delivers the object value, scanf-style, somehow.
//
bool CFScan::scanformat(CFTypeRef obj)
{
	switch (*++format) {
	case F_OBJECT:
		store<CFTypeRef>(obj);
		return true;
	case F_ARRAY:	// %a*
		return typescan(obj, CFArrayGetTypeID()) == done;
	case F_BOOLEAN:
		if (Typescan rc = typescan(obj, CFBooleanGetTypeID()))
			return rc == done;
		switch (*format) {
		case 'f':	// %Bf - two arguments (value, &variable)
			{
				unsigned flag = va_arg(args, unsigned);
				unsigned *value = va_arg(args, unsigned *);
				if (obj == kCFBooleanTrue && !suppress)
					*value |= flag;
				return true;
			}
		default:	// %b - CFBoolean as int boolean
			store<int>(obj == kCFBooleanTrue);
			return true;
		}
	case F_DICTIONARY:
		return typescan(obj, CFDictionaryGetTypeID()) == done;
	case 'd':	// %d - int
		return scannumber<int>(obj);
	case F_NUMBER:
		return typescan(obj, CFNumberGetTypeID()) == done;
	case F_STRING:
	case 's':
		if (Typescan rc = typescan(obj, CFStringGetTypeID()))
			return rc == done;
		// %s
		store<std::string>(cfString(CFStringRef(obj)));
		return true;
	case 'u':
		return scannumber<unsigned int>(obj);
	case F_DATA:
		return typescan(obj, CFDataGetTypeID()) == done;
	default:
		assert(false);
		return false;
	}
}
Example #11
0
void print_keys(const void *key, const void *value, void *context)
{
        CFStringRef k = (CFStringRef)key;
        std::string key_str = CFStringGetCStringPtr(k, kCFStringEncodingMacRoman);
        std::string value_str;

        CFTypeID id = CFGetTypeID(value);
        if(id == CFStringGetTypeID())
        {
                CFStringRef v = (CFStringRef)value;
                if(CFStringGetCStringPtr(v, kCFStringEncodingMacRoman))
                {
                        value_str = CFStringGetCStringPtr(v, kCFStringEncodingMacRoman);
                        if(key_str == "kCGWindowName")
                                window_lst[window_lst.size()-1].name = value_str;
                        else if(key_str == "kCGWindowOwnerName")
                                window_lst[window_lst.size()-1].owner = value_str;
                }
        }
        else if(id == CFNumberGetTypeID())
        {
                CFNumberRef v = (CFNumberRef)value;
                int myint;
                CFNumberGetValue(v, kCFNumberSInt64Type, &myint);
                value_str = std::to_string(myint);
                if(key_str == "kCGWindowLayer")
                        window_lst[window_lst.size()-1].layer = myint;
                else if(key_str == "kCGWindowOwnerPID")
                        window_lst[window_lst.size()-1].pid = myint;
                else if(key_str == "X")
                        window_lst[window_lst.size()-1].x = myint;
                else if(key_str == "Y")
                        window_lst[window_lst.size()-1].y = myint;
                else if(key_str == "Width")
                        window_lst[window_lst.size()-1].width = myint;
                else if(key_str == "Height")
                        window_lst[window_lst.size()-1].height = myint;
        }
        else if(id == CFDictionaryGetTypeID())
        {
                CFDictionaryRef elem = (CFDictionaryRef)value;
                CFDictionaryApplyFunction(elem, print_keys, NULL);
                CFRelease(elem);
        } 
}
Example #12
0
static CFTypeRef
CopyKeyFromFile(CFStringRef domain, CFStringRef key)
{
    CFReadStreamRef s;
    CFDictionaryRef d;
    CFStringRef file;
    CFErrorRef e;
    CFURLRef url;
    CFTypeRef val;
    
    file = CFStringCreateWithFormat(NULL, 0, CFSTR("/Library/Preferences/%@.plist"), domain);
    if (file == NULL)
	return NULL;
    
    url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, domain, kCFURLPOSIXPathStyle, false);
    CFRelease(file);
    if (url == NULL)
	return NULL;
    
    s = CFReadStreamCreateWithFile(kCFAllocatorDefault, url);
    CFRelease(url);
    if (s == NULL)
	return NULL;
    
    if (!CFReadStreamOpen(s)) {
	CFRelease(s);
	return NULL;
    }
    
    d = (CFDictionaryRef)CFPropertyListCreateWithStream (kCFAllocatorDefault, s, 0, kCFPropertyListImmutable, NULL, &e);
    CFRelease(s);
    if (d == NULL)
	return NULL;
    
    if (CFGetTypeID(d) != CFDictionaryGetTypeID()) {
	CFRelease(d);
	return NULL;
    }
    
    val = CFDictionaryGetValue(d, key);
    if (val)
	CFRetain(val);
    CFRelease(d);
    return val;
}
Example #13
0
/*
 * Obtain the CFDictionary representing this user's PKINIT client cert prefs, if it
 * exists. Returns noErr or errSecItemNotFound as appropriate.
 */
static OSStatus pkinit_get_pref_dict(
    CFDictionaryRef *dict)
{
    CFDictionaryRef theDict;
    theDict = (CFDictionaryRef)CFPreferencesCopyValue(CFSTR(kPkinitClientCertKey),
                                                      CFSTR(kPkinitClientCertApp), kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
    if(theDict == NULL) {
        pkiDebug("pkinit_get_pref_dict: no kPkinitClientCertKey\n");
        return errSecItemNotFound;
    }
    if(CFGetTypeID(theDict) != CFDictionaryGetTypeID()) {
        pkiDebug("pkinit_get_pref_dict: bad kPkinitClientCertKey pref\n");
        CFRelease(theDict);
        return errSecItemNotFound;
    }
    *dict = theDict;
    return noErr;
}
static bool testPostGet(CFStringRef key, CFTypeRef cfobj, dispatch_queue_t processQueue, dispatch_group_t dgroup)
{
    CFErrorRef error = NULL;
    bool result = false;
    CFTypeRef cfv = NULL;
    
    testPutObjectInCloud(key, cfobj, &error, dgroup, processQueue);
    CFTypeRef cfvalue = testGetObjectFromCloud(key, processQueue, dgroup);
    printTimeNow("finished getObjectFromCloud");
    if (!cfvalue)
        return false;
    if (CFGetTypeID(cfvalue)==CFDictionaryGetTypeID())
        cfv = CFDictionaryGetValue(cfvalue, key);
    else
        cfv = cfvalue;
    result = CFEqual(cfobj, cfv);
    return result;
}
Example #15
0
void genOSXPrefValues(const CFTypeRef& value,
                      const Row& base,
                      QueryData& results,
                      size_t depth) {
  if (value == nullptr) {
    return;
  }

  // Since we recurse when parsing Arrays/Dicts, monitor stack limits.
  if (++depth > kPreferenceDepthLimit) {
    TLOG << "The macOS preference: " << base.at("domain")
         << " exceeded subkey depth limit: " << kPreferenceDepthLimit;
    return;
  }

  // Emit a string representation for each preference type.
  Row r = base;
  if (CFGetTypeID(value) == CFNumberGetTypeID()) {
    r["value"] = stringFromCFNumber(static_cast<CFDataRef>(value));
  } else if (CFGetTypeID(value) == CFStringGetTypeID()) {
    r["value"] = stringFromCFString(static_cast<CFStringRef>(value));
  } else if (CFGetTypeID(value) == CFDateGetTypeID()) {
    auto unix_time = CFDateGetAbsoluteTime(static_cast<CFDateRef>(value)) +
                     kCFAbsoluteTimeIntervalSince1970;
    r["value"] = boost::lexical_cast<std::string>(std::llround(unix_time));
  } else if (CFGetTypeID(value) == CFBooleanGetTypeID()) {
    r["value"] = (CFBooleanGetValue(static_cast<CFBooleanRef>(value)) == TRUE)
                     ? "true"
                     : "false";
  } else if (CFGetTypeID(value) == CFDataGetTypeID()) {
    // Do not include data preferences.
  } else if (CFGetTypeID(value) == CFArrayGetTypeID()) {
    genOSXListPref(static_cast<CFArrayRef>(value), base, results, depth);
    return;
  } else if (CFGetTypeID(value) == CFDictionaryGetTypeID()) {
    // Generate a row for each hash key.
    TRowResults trow(base, results, depth);
    CFDictionaryApplyFunction(
        static_cast<CFDictionaryRef>(value), &genOSXHashPref, &trow);
    return;
  }

  results.push_back(std::move(r));
}
Example #16
0
extern pascal void CFQPropertyListDeepApplyFunction(CFPropertyListRef propList, 
													CFQPropertyListDeepApplierFunction func,
													void *context)
	// See comment in header.
{
	assert(propList != NULL);
	assert(func     != NULL);
	
	// Call "func" for this node.
	
	func(propList, context);
	
	// If this node is a dictionary or an array, call func for 
	// each element.
	
	if ( CFGetTypeID(propList) == CFDictionaryGetTypeID() ) {
		CFIndex count;
		CFIndex index;
		
		count = CFDictionaryGetCount( (CFDictionaryRef) propList);
		if (count > 0) {
			const void **keys;

			keys = (const void **) malloc( count * sizeof(const void *));
			if (keys != NULL) {
				CFDictionaryGetKeysAndValues( (CFDictionaryRef) propList, keys, NULL);
				
				for (index = 0; index < count; index++) {
					CFQPropertyListDeepApplyFunction(CFDictionaryGetValue( (CFDictionaryRef) propList, keys[index]), func, context);
				}
				free(keys);
			}
		}
	} else if ( CFGetTypeID(propList) == CFArrayGetTypeID() ) {
		CFIndex count;
		long    index;
		
		count = CFArrayGetCount( (CFArrayRef) propList);
		for (index = 0; index < count; index++) {
			CFQPropertyListDeepApplyFunction(CFArrayGetValueAtIndex( (CFArrayRef) propList, index), func, context);
		}
	}
}
Example #17
0
// Apple don't use a simple callback to NP_GetMIMEDescription, as on Linux, but
// we still need to implement it as we can dynamically open other plugins.
//
// XXX: For the initial release, I'm not going to support external MIME types. I
//      will add it on request.
char * platform_getmimedescription(struct plugin *plugin)
{
    CFDictionaryRef     cf_pluginplist   = NULL;
    CFDictionaryRef     cf_mimetypes     = NULL;
    CFBundleRef         cf_plugin        = plugin->handle;
    char               *mime_description = strdup("");

    // If we don't have a valid handle, we return an empty MIME description.
    // This is jsut for convenience so that I don't have to special case
    // invalid plugins on shutdown.
    if (plugin->handle == NULL) {
        goto finished;
    }

    // We should already have a CFBundleRef in plugin->handle.
    cf_pluginplist = CFBundleGetInfoDictionary(cf_plugin);

    // Find the WebPluginMIMETypes key.
    if (CFDictionaryGetValueIfPresent(cf_pluginplist,
                                      CFSTR("WebPluginMIMETypes"),
                                      (const void **) &cf_mimetypes) == false) {
        // The plugin is invalid, malformed, or using external MIME Types. This
        // is not currently supported, so return an empty string.
        goto finished;
    }

    if (CFGetTypeID(cf_mimetypes) != CFDictionaryGetTypeID()) {
        goto finished;
    }

    l_debug("found %u keys in WebPluginMIMETypes dictionary from plugin %s",
            CFDictionaryGetCount(cf_mimetypes),
            plugin->section);

    // Enumerate each key in the dictionary, adding them to the description.
    CFDictionaryApplyFunction(cf_mimetypes,
                              mimetype_dictionary_applier,
                              &mime_description);

finished:
    // Return the final string.
    return mime_description;
}
void CFPreferencesSetMultiple(CFDictionaryRef keysToSet, CFArrayRef keysToRemove, CFStringRef appName, CFStringRef user, CFStringRef host) {
    CFPreferencesDomainRef domain;
    CFIndex idx, count;
    CFAssert1(appName != NULL && user != NULL && host != NULL, __kCFLogAssertion, "%s(): Cannot access preferences for a NULL application name, user, or host", __PRETTY_FUNCTION__);
    if (keysToSet) __CFGenericValidateType(keysToSet, CFDictionaryGetTypeID());
    if (keysToRemove) __CFGenericValidateType(keysToRemove, CFArrayGetTypeID());
    __CFGenericValidateType(appName, CFStringGetTypeID());
    __CFGenericValidateType(user, CFStringGetTypeID());
    __CFGenericValidateType(host, CFStringGetTypeID());

    CFTypeRef *keys = NULL;
    CFTypeRef *values;
    CFIndex numOfKeysToSet = 0;
    
    domain = _CFPreferencesStandardDomain(appName, user, host);
    if (!domain) return;

    CFAllocatorRef alloc = CFGetAllocator(domain);
    
    if (keysToSet && (count = CFDictionaryGetCount(keysToSet))) {
        numOfKeysToSet = count;
        keys = (CFTypeRef *)CFAllocatorAllocate(alloc, 2*count*sizeof(CFTypeRef), 0);
        if (keys) {
            values = &(keys[count]);
            CFDictionaryGetKeysAndValues(keysToSet, keys, values);
            for (idx = 0; idx < count; idx ++) {
                _CFPreferencesDomainSet(domain, (CFStringRef)keys[idx], values[idx]);
            }
        }
    }
    if (keysToRemove && (count = CFArrayGetCount(keysToRemove))) {
        for (idx = 0; idx < count; idx ++) {
            CFStringRef removedKey = (CFStringRef)CFArrayGetValueAtIndex(keysToRemove, idx);
            _CFPreferencesDomainSet(domain, removedKey, NULL);
        }
    }


    _CFApplicationPreferencesDomainHasChanged(domain);
    
    if(keys) CFAllocatorDeallocate(alloc, keys);
}
Example #19
0
static void writeFontDatabaseToPlist(CFPropertyListRef cgFontDBPropertyList, CFPropertyListRef filenamesFromRegistry)
{
    if (!cgFontDBPropertyList)
        return;

    RetainPtr<CFDataRef> data;

    if (!filenamesFromRegistry || CFGetTypeID(cgFontDBPropertyList) != CFDictionaryGetTypeID())
        data.adoptCF(CFPropertyListCreateXMLData(kCFAllocatorDefault, cgFontDBPropertyList));
    else {
        RetainPtr<CFMutableDictionaryRef> dictionary(AdoptCF, CFDictionaryCreateMutableCopy(kCFAllocatorDefault, 2, static_cast<CFDictionaryRef>(cgFontDBPropertyList)));
        CFDictionarySetValue(dictionary.get(), fontFilenamesFromRegistryKey(), filenamesFromRegistry);
        data.adoptCF(CFPropertyListCreateXMLData(kCFAllocatorDefault, dictionary.get()));
    }

    if (!data)
        return;

    safeCreateFile(fontsPlistPath(), data.get());
}
OSStatus		CAComponentDescription::Restore (CFPropertyListRef &inData)
{
	if (CFGetTypeID (inData) != CFDictionaryGetTypeID()) return -1;
	CACFDictionary dict(static_cast<CFDictionaryRef>(inData), false);
	
	CFStringRef value;
	
	if (!dict.GetString (kType, value)) return -1;
	CFStrToNum (value, componentType);

	if (!dict.GetString (kSubType, value)) return -1;
	CFStrToNum (value, componentSubType);

	if (!dict.GetString (kManu, value)) return -1;
	CFStrToNum (value, componentManufacturer);

	componentFlags = 0;
	componentFlagsMask = 0;
	
	return 0;
}
void NetworkStateNotifier::updateState()
{
    // Assume that we're offline until proven otherwise.
    m_isOnLine = false;
    
    RetainPtr<CFStringRef> str = adoptCF(SCDynamicStoreKeyCreateNetworkInterface(0, kSCDynamicStoreDomainState));
    
    RetainPtr<CFPropertyListRef> propertyList = adoptCF(SCDynamicStoreCopyValue(m_store.get(), str.get()));
    
    if (!propertyList)
        return;
    
    if (CFGetTypeID(propertyList.get()) != CFDictionaryGetTypeID())
        return;
    
    CFArrayRef netInterfaces = (CFArrayRef)CFDictionaryGetValue((CFDictionaryRef)propertyList.get(), kSCDynamicStorePropNetInterfaces);
    if (CFGetTypeID(netInterfaces) != CFArrayGetTypeID())
        return;
    
    for (CFIndex i = 0; i < CFArrayGetCount(netInterfaces); i++) {
        CFStringRef interface = (CFStringRef)CFArrayGetValueAtIndex(netInterfaces, i);
        if (CFGetTypeID(interface) != CFStringGetTypeID())
            continue;
        
        // Ignore the loopback interface.
        if (CFStringFind(interface, CFSTR("lo"), kCFCompareAnchored).location != kCFNotFound)
            continue;

        RetainPtr<CFStringRef> key = adoptCF(SCDynamicStoreKeyCreateNetworkInterfaceEntity(0, kSCDynamicStoreDomainState, interface, kSCEntNetIPv4));

        RetainPtr<CFArrayRef> keyList = adoptCF(SCDynamicStoreCopyKeyList(m_store.get(), key.get()));
    
        if (keyList && CFArrayGetCount(keyList.get())) {
            m_isOnLine = true;
            break;
        }
    }
}
Example #22
0
File: plist.cpp Project: aosm/samba
/* Initialise a Preferences object from the given pspec. This might be an
 * SCPreferences AppID or it might be the path to a plist file.
 */
Preferences::Preferences(const char * pspec)
    : m_pspec(pspec), m_plist(NULL), m_scpref(NULL)
{

    /* Try to load this as a plist file first. The SCPreferences API does a
     * bunch of work if it can't find the file, and we should avoid that unless
     * we have a good idea that it's necessary.
     */
    this->m_plist = load_plist_from_path(this->m_pspec.c_str());
    if (this->m_plist) {
	/* Loading a plist should always give you back a dictionary. */
	ASSERT(CFDictionaryGetTypeID() == CFGetTypeID(this->m_plist));
	VERBOSE("loaded plist %s\n", pspec);
	return;
    }

    cf_typeref<CFStringRef> appname(cfstring_wrap(getprogname()));
    cf_typeref<CFStringRef> appid(cfstring_wrap(this->m_pspec.c_str()));

    this->m_scpref = SCPreferencesCreate(kCFAllocatorDefault, appname, appid);
    if (this->m_scpref == NULL) {
	return;
    }

    /* If there was no existing preferences file, SCError() should return
     * kSCStatusNoConfigFile. We are only interested in reading preferences, so
     * we want to fail if there's no existing config.
     */

    if (SCError() != kSCStatusOK) {
	safe_release(this->m_scpref);
    }

    if (this->m_scpref) {
	VERBOSE("loaded SC preferences %s\n", pspec);
    }

}
CFTypeRef
_mongoc_secure_transport_dict_get (CFArrayRef values, CFStringRef label)
{
   if (!values || CFGetTypeID (values) != CFArrayGetTypeID ()) {
      return NULL;
   }

   for (CFIndex i = 0; i < CFArrayGetCount (values); ++i) {
      CFStringRef item_label;
      CFDictionaryRef item = CFArrayGetValueAtIndex (values, i);

      if (CFGetTypeID (item) != CFDictionaryGetTypeID ()) {
         continue;
      }

      item_label = CFDictionaryGetValue (item, kSecPropertyKeyLabel);
      if (item_label && CFStringCompare (item_label, label, 0) == kCFCompareEqualTo) {
         return CFDictionaryGetValue (item, kSecPropertyKeyValue);
      }
   }

   return NULL;
}
PassRefPtr<LegacyWebArchive> LegacyWebArchive::create(SharedBuffer* data)
{
    LOG(Archives, "LegacyWebArchive - Creating from raw data");
    
    RefPtr<LegacyWebArchive> archive = create();
        
    ASSERT(data);
    if (!data)
        return 0;
        
    RetainPtr<CFDataRef> cfData(AdoptCF, data->createCFData());
    if (!cfData)
        return 0;
        
    CFStringRef errorString = 0;
    
    RetainPtr<CFDictionaryRef> plist(AdoptCF, static_cast<CFDictionaryRef>(CFPropertyListCreateFromXMLData(0, cfData.get(), kCFPropertyListImmutable, &errorString)));
    if (!plist) {
#ifndef NDEBUG
        const char* cError = errorString ? CFStringGetCStringPtr(errorString, kCFStringEncodingUTF8) : "unknown error";
        LOG(Archives, "LegacyWebArchive - Error parsing PropertyList from archive data - %s", cError);
#endif
        if (errorString)
            CFRelease(errorString);
        return 0;
    }
    
    if (CFGetTypeID(plist.get()) != CFDictionaryGetTypeID()) {
        LOG(Archives, "LegacyWebArchive - Archive property list is not the expected CFDictionary, aborting invalid WebArchive");
        return 0;
    }
    
    if (!archive->extract(plist.get()))
        return 0;

    return archive.release();
}
Example #25
0
/*************************************************************************
 *
 * hu_XMLSearchForVendorNameByVendorID( inVendorID, outCStr )
 *
 * Purpose: Find a vendor string in the <HID_device_usage_strings.plist> resource ( XML ) file
 *
 * Inputs: inVendorID - the elements vendor ID
 *			inProductID - the elements product ID
 *			outCStr		- address where result will be returned
 *
 * Returns: Boolean		- if successful
 */
static Boolean hu_XMLSearchForVendorNameByVendorID(long inVendorID, char *outCStr) {
	Boolean results = FALSE;
	if ( !gUsageCFPropertyListRef ) {
		gUsageCFPropertyListRef =
		hu_XMLLoad(                                 CFSTR(
														  "HID_device_usage_strings"), CFSTR("plist") );
	}
	if ( gUsageCFPropertyListRef ) {
		if (
		    CFDictionaryGetTypeID() == CFGetTypeID(gUsageCFPropertyListRef) )
		{
			CFDictionaryRef vendorCFDictionaryRef;
			CFStringRef vendorKeyCFStringRef = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%ld"), inVendorID);
			if ( vendorKeyCFStringRef ) {
				if (     CFDictionaryGetValueIfPresent(gUsageCFPropertyListRef, vendorKeyCFStringRef,
				                                       (const void **) &vendorCFDictionaryRef) )
				{
					CFStringRef vendorCFStringRef = NULL;
					if ( CFDictionaryGetValueIfPresent(vendorCFDictionaryRef, kNameKeyCFStringRef,
					                                   (const void **) &vendorCFStringRef) && vendorCFStringRef )
					{
						// CFShow( vendorCFStringRef );
						results =
						CFStringGetCString(vendorCFStringRef, outCStr, CFStringGetLength(
																						 vendorCFStringRef) * sizeof(UniChar) + 1, kCFStringEncodingUTF8);
					}
				}
				
				CFRelease(vendorKeyCFStringRef);
			}
		}
		
		// ++ CFRelease( gUsageCFPropertyListRef );	// Leak this !
	}
	
	return (results);
}   // hu_XMLSearchForVendorNameByVendorID
Example #26
0
/*****************************************************************************
 * ManageEventsCallback
 * - 
 * This is invoked when launchd loads a event dictionary and needs to inform 
 * us what a daemon / agent is looking for.
 *****************************************************************************/
static void ManageEventsCallback(UserEventAgentLaunchdAction action, CFNumberRef token, CFTypeRef eventMatchDict, void* vContext)
{
	
	if (!eventMatchDict || CFGetTypeID(eventMatchDict) != CFDictionaryGetTypeID())
	{
		fprintf(stderr, "%s given non-dictionary for event dictionary\n", sPluginIdentifier);
		return;
	}
	
	if (action == kUserEventAgentLaunchdAdd)
	{
		// Launchd wants us to add a launch event for this token and matching dictionary.
		AddEventToPlugin((BonjourUserEventsPlugin*)vContext, token, (CFDictionaryRef)eventMatchDict);
	}
	else if (action == kUserEventAgentLaunchdRemove)
	{
		// Launchd wants us to remove the event hook we setup for this token / matching dictionary.
		RemoveEventFromPlugin((BonjourUserEventsPlugin*)vContext, token);
	}
	else
	{
		fprintf(stderr, "%s got unknown UserEventAction: %d\n", sPluginIdentifier, action);
	}
}
Example #27
0
static void
convert_content(const void *key, const void *value, void *context)
{
    krb5_config_section *tmp, **parent = context;
    char *k;

    if (CFGetTypeID(key) != CFStringGetTypeID())
        return;

    k = cfstring2cstring(key);
    if (k == NULL)
        return;

    if (CFGetTypeID(value) == CFStringGetTypeID()) {
        tmp = get_entry(parent, k, krb5_config_string);
        tmp->u.string = cfstring2cstring(value);
    } else if (CFGetTypeID(value) == CFDictionaryGetTypeID()) {
        tmp = get_entry(parent, k, krb5_config_list);
        CFDictionaryApplyFunction(value, convert_content, &tmp->u.list);
    } else {
        /* log */
    }
    free(k);
}
Example #28
0
static CFType typeFromCFTypeRef(CFTypeRef type)
{
    ASSERT(type);

    if (type == tokenNullTypeRef())
        return Null;

    CFTypeID typeID = CFGetTypeID(type);
    if (typeID == CFArrayGetTypeID())
        return CFArray;
    if (typeID == CFBooleanGetTypeID())
        return CFBoolean;
    if (typeID == CFDataGetTypeID())
        return CFData;
    if (typeID == CFDateGetTypeID())
        return CFDate;
    if (typeID == CFDictionaryGetTypeID())
        return CFDictionary;
    if (typeID == CFNullGetTypeID())
        return CFNull;
    if (typeID == CFNumberGetTypeID())
        return CFNumber;
    if (typeID == CFStringGetTypeID())
        return CFString;
    if (typeID == CFURLGetTypeID())
        return CFURL;
#if PLATFORM(MAC)
    if (typeID == SecCertificateGetTypeID())
        return SecCertificate;
    if (typeID == SecKeychainItemGetTypeID())
        return SecKeychainItem;
#endif

    ASSERT_NOT_REACHED();
    return Unknown;
}
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;
}
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;
}