Esempio n. 1
0
static Boolean IOHIDDevice_GetUInt32Property(IOHIDDeviceRef inIOHIDDeviceRef, CFStringRef inKey, uint32_t *outValue) {
	Boolean result = FALSE;
	if ( inIOHIDDeviceRef ) {
		assert( IOHIDDeviceGetTypeID() == CFGetTypeID(inIOHIDDeviceRef) );
		
		CFTypeRef tCFTypeRef = IOHIDDeviceGetProperty(inIOHIDDeviceRef, inKey);
		if ( tCFTypeRef ) {
			// if this is a number
			if ( CFNumberGetTypeID() == CFGetTypeID(tCFTypeRef) ) {
				// get it's value
				result = CFNumberGetValue( (CFNumberRef) tCFTypeRef, kCFNumberSInt32Type, outValue );
			}
		}
	}
	
	return (result);
}   // IOHIDDevice_GetUInt32Property
Esempio n. 2
0
static PyObject *pyidle_get(PyIdle *self,
                            PyObject *args,
                            PyObject *kwargs)
{
    CFMutableDictionaryRef props;
    CFTypeRef obj;
    uint64_t idleTime;
    CFTypeID type;
    int ret;

    if ((ret = IORegistryEntryCreateCFProperties(self->regEntry, &props, kCFAllocatorDefault, 0)) != kIOReturnSuccess)
    {
      PyErr_Format(PyExc_RuntimeError, "IORegistryEntryCreateCFProperties failed: %d", ret);
        return NULL;
    }

    obj = CFDictionaryGetValue(props, CFSTR("HIDIdleTime"));
    CFRetain(obj);

    type = CFGetTypeID(obj);
    if (type == CFDataGetTypeID())
    {
        CFDataGetBytes((CFDataRef)obj,
                       CFRangeMake(0, sizeof(idleTime)),
                       (UInt8*)&idleTime);
    }
    else if (type == CFNumberGetTypeID())
    {
        CFNumberGetValue((CFNumberRef)obj,
                         kCFNumberSInt64Type,
                         &idleTime);
    }
    else
    {
        PyErr_Format(PyExc_RuntimeError, "Unsupported type: %d", (int)type);
        CFRelease(obj);
        CFRelease((CFTypeRef)props);
        return NULL;
    }

    CFRelease(obj);
    CFRelease(props);

    return Py_BuildValue("L", idleTime >> 30);
}
Esempio n. 3
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);
        } 
}
Esempio n. 4
0
File: unimotion.c Progetto: ADTSH/io
static Boolean getPrefDouble(CFStringRef key, CFStringRef app, double *val)
{
    CFPropertyListRef prefRef;
    Boolean ok;
    double ret;

    ok = false;
    prefRef = CFPreferencesCopyAppValue(key, app);
    if ( prefRef ) {
        if ( CFGetTypeID(prefRef) == CFNumberGetTypeID() && CFNumberIsFloatType(prefRef) ) {
            ok = CFNumberGetValue(prefRef, kCFNumberDoubleType, &ret);
            if ( ok && val )
                *val = ret;
        }
        CFRelease(prefRef);
    }
    return ok;
}
static bool
GetNumericProperty (io_service_t ioDeviceObj, CFStringRef propName, SInt32& value)
{
	// Get the property:
	CFTypeRef prop  = IORegistryEntryCreateCFProperty (ioDeviceObj,
											propName,
											kCFAllocatorDefault, 0);
	if (prop == NULL)
		return false;
	
	// Make sure it's a number, and get the value:
	bool success = false;
	if (CFGetTypeID (prop) == CFNumberGetTypeID ())
		success = CFNumberGetValue ((CFNumberRef) prop, kCFNumberSInt32Type, &value);

	CFRelease (prop);
	return success;
}
static int GetIntProperty( io_registry_entry_t entry, CFStringRef key )
{
	CFTypeRef t = IORegistryEntryCreateCFProperty( entry, key, NULL, 0 );
	
	if( !t )
		return -1;
	if( CFGetTypeID( t ) != CFNumberGetTypeID() )
	{
		CFRelease( t );
		return -1;
	}
	int num;
	
	if( !CFNumberGetValue(CFNumberRef(t), kCFNumberIntType, &num) )
		num = -1;
	CFRelease( t );
	return num;
}
Esempio n. 7
0
static int getHIDCookies(IOHIDDeviceInterface122 **handle,
                         IOHIDElementCookie **cookies,
                         int *nr_cookies)
{
    CFTypeRef object;
    long number;
    CFArrayRef elements;
    CFDictionaryRef element;
    CFIndex i;

    *nr_cookies = 0;

    if (!handle || !(*handle))
        return -1;

    // Copy all elements, since we're grabbing most of the elements
    // for this device anyway, and thus, it's faster to iterate them
    // ourselves. When grabbing only one or two elements, a matching
    // dictionary should be passed in here instead of NULL.
    if (((*handle)->copyMatchingElements(handle, NULL, &elements)) != kIOReturnSuccess)
        return -1;

    // No elements, still a valid result.
    if (CFArrayGetCount(elements)==0)
        return 0;

    *cookies = calloc(CFArrayGetCount(elements), sizeof(IOHIDElementCookie));
    if (*cookies == NULL)
        return -1;

    for (i=0; i<CFArrayGetCount(elements); i++) {
        element = CFArrayGetValueAtIndex(elements, i);

        // Get cookie.
        object = CFDictionaryGetValue(element, CFSTR(kIOHIDElementCookieKey));
        if (object == 0 || CFGetTypeID(object) != CFNumberGetTypeID())
            continue;
        if (!CFNumberGetValue((CFNumberRef)object, kCFNumberLongType, &number))
            continue;
        (*cookies)[(*nr_cookies)++] = (IOHIDElementCookie)number;
    }

    return 0;
}
Esempio n. 8
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));
}
Esempio n. 9
0
static pascal void PrintPropertyListCallback(CFTypeRef key, CFTypeRef node, void *context)
	// A callback routine used by PrintPropertyList to print 
	// a property list in a nicely formatted way.
{
	#pragma unused(key)
	int i;
	int depth;
	
	depth = (int)context;
	
	for (i = 0; i < depth; i++) {
		fprintf(stderr, "  ");
	}

	{
		CFStringRef fullDesc;
		CFStringRef typeDesc;
		CFStringRef valueDesc;

		fullDesc = NULL;		
		typeDesc = CFCopyTypeIDDescription(CFGetTypeID(node));
		valueDesc = NULL;
		if ( CFQPropertyListIsLeaf(node) ) {
			if ( CFGetTypeID(node) == CFStringGetTypeID() ) {
				valueDesc = (CFStringRef) CFRetain(node);
			} else if ( CFGetTypeID(node) == CFNumberGetTypeID() ) {
				valueDesc = (CFStringRef) CFRetain(node);
			} else {
				valueDesc = CFCopyDescription(node);
			}
			fullDesc = CFStringCreateWithFormat(NULL, NULL, CFSTR("%@ : %@ [%d] = %@"), key, typeDesc, CFGetRetainCount(node), valueDesc);
		} else {
			fullDesc = CFStringCreateWithFormat(NULL, NULL, CFSTR("%@ : %@ [%d]"), key, typeDesc, CFGetRetainCount(node));
		}
		CFShow(fullDesc);
		CFQRelease(fullDesc);
		CFQRelease(valueDesc);
		CFQRelease(typeDesc);
	}

	if ( ! CFQPropertyListIsLeaf(node) ) {
		CFQPropertyListShallowApplyFunction(node, PrintPropertyListCallback, (void *) (depth + 1) );
	}
}
static bool makeRGBA32FromARGBCFArray(CFArrayRef colorArray, RGBA32& color)
{
    if (CFArrayGetCount(colorArray) < 4)
        return false;

    float componentArray[4];
    for (int i = 0; i < 4; i++) {
        CFNumberRef value = static_cast<CFNumberRef>(CFArrayGetValueAtIndex(colorArray, i));
        if (CFGetTypeID(value) != CFNumberGetTypeID())
            return false;

        float component;
        CFNumberGetValue(value, kCFNumberFloatType, &component);
        componentArray[i] = component;
    }

    color = makeRGBA32FromFloats(componentArray[1], componentArray[2], componentArray[3], componentArray[0]);
    return true;
}
Esempio n. 11
0
static void cf_hash_to_rb_hash(const void *raw_key, const void * raw_value, void *ctx){
  CFTypeRef value = (CFTypeRef)raw_value;
  CFStringRef key = (CFStringRef)raw_key;

  VALUE rubyValue = Qnil;
  VALUE hash = (VALUE)ctx;

  if(CFStringGetTypeID() == CFGetTypeID(value)){
    rubyValue = cfstring_to_rb_string((CFStringRef)value);
  }
  else if(CFDataGetTypeID() == CFGetTypeID(value)){
    CFDataRef data = (CFDataRef)value;
    rubyValue = rb_enc_str_new((const char*)CFDataGetBytePtr(data),CFDataGetLength(data), rb_ascii8bit_encoding());
  }
  else if(CFBooleanGetTypeID() == CFGetTypeID(value)){
    Boolean booleanValue = CFBooleanGetValue(value);
    rubyValue = booleanValue ? Qtrue : Qfalse;
  }
  else if(CFNumberGetTypeID() == CFGetTypeID(value)){
    if(CFNumberIsFloatType(value))
    {
      double doubleValue;
      CFNumberGetValue(value, kCFNumberDoubleType, &doubleValue);
      rubyValue = rb_float_new(doubleValue);
    }else{
      long long longValue;
      CFNumberGetValue(value, kCFNumberLongLongType, &longValue);
      rubyValue = LL2NUM(longValue);
    }
  }
  else if (CFDateGetTypeID() == CFGetTypeID(value)){
    CFDateRef date = (CFDateRef) value;
    CFAbsoluteTime abs_time = CFDateGetAbsoluteTime(date);
    double secondsSinceUnixEpoch = abs_time + kCFAbsoluteTimeIntervalSince1970;
    time_t seconds = (time_t)secondsSinceUnixEpoch;
    long usec = (secondsSinceUnixEpoch - seconds) * 1000000;
    rubyValue = rb_time_new((time_t)secondsSinceUnixEpoch, usec);
  }

  if(!NIL_P(rubyValue)){
    rb_hash_aset(hash, cfstring_to_rb_string(key), rubyValue);
  }
}
Esempio n. 12
0
//
// Construct and prepare an SQL query on the authority table, operating on some set of existing authority records.
// In essence, this appends a suitable WHERE clause to the stanza passed and prepares it on the statement given.
//
void PolicyEngine::selectRules(SQLite::Statement &action, std::string phrase, std::string table,
	CFTypeRef inTarget, AuthorityType type, SecAssessmentFlags flags, CFDictionaryRef context, std::string suffix /* = "" */)
{
	CFDictionary ctx(context, errSecCSInvalidAttributeValues);
	CFCopyRef<CFTypeRef> target = inTarget;
	std::string filter_unsigned;	// ignored; used just to trigger ad-hoc signing
	normalizeTarget(target, ctx, &filter_unsigned);

	string label;
	if (CFStringRef lab = ctx.get<CFStringRef>(kSecAssessmentUpdateKeyLabel))
		label = cfString(CFStringRef(lab));

	if (!target) {
		if (label.empty()) {
			if (type == kAuthorityInvalid) {
				action.query(phrase + suffix);
			} else {
				action.query(phrase + " WHERE " + table + ".type = :type" + suffix);
				action.bind(":type").integer(type);
			}
		} else {	// have label
			if (type == kAuthorityInvalid) {
				action.query(phrase + " WHERE " + table + ".label = :label" + suffix);
			} else {
				action.query(phrase + " WHERE " + table + ".type = :type AND " + table + ".label = :label" + suffix);
				action.bind(":type").integer(type);
			}
			action.bind(":label") = label;
		}
	} else if (CFGetTypeID(target) == CFNumberGetTypeID()) {
		action.query(phrase + " WHERE " + table + ".id = :id" + suffix);
		action.bind(":id").integer(cfNumber<uint64_t>(target.as<CFNumberRef>()));
	} else if (CFGetTypeID(target) == SecRequirementGetTypeID()) {
		if (type == kAuthorityInvalid)
			type = kAuthorityExecute;
		CFRef<CFStringRef> requirementText;
		MacOSError::check(SecRequirementCopyString(target.as<SecRequirementRef>(), kSecCSDefaultFlags, &requirementText.aref()));
		action.query(phrase + " WHERE " + table + ".type = :type AND " + table + ".requirement = :requirement" + suffix);
		action.bind(":type").integer(type);
		action.bind(":requirement") = requirementText.get();
	} else
		MacOSError::throwMe(errSecCSInvalidObjectRef);
}
Esempio n. 13
0
CFDictionaryRef xpcEngineUpdate(CFTypeRef target, uint flags, CFDictionaryRef context)
{
	Message msg("update");
	// target can be NULL, a CFURLRef, a SecRequirementRef, or a CFNumberRef
	if (target) {
		if (CFGetTypeID(target) == CFNumberGetTypeID())
			xpc_dictionary_set_uint64(msg, "rule", cfNumber<int64_t>(CFNumberRef(target)));
		else if (CFGetTypeID(target) == CFURLGetTypeID())
			xpc_dictionary_set_string(msg, "url", cfString(CFURLRef(target)).c_str());
		else if (CFGetTypeID(target) == SecRequirementGetTypeID()) {
			CFRef<CFDataRef> data;
			MacOSError::check(SecRequirementCopyData(SecRequirementRef(target), kSecCSDefaultFlags, &data.aref()));
			xpc_dictionary_set_data(msg, "requirement", CFDataGetBytePtr(data), CFDataGetLength(data));
		} else
			MacOSError::throwMe(errSecCSInvalidObjectRef);
	}
	xpc_dictionary_set_int64(msg, "flags", flags);
	CFRef<CFMutableDictionaryRef> ctx = makeCFMutableDictionary();
	if (context)
		CFDictionaryApplyFunction(context, copyCFDictionary, ctx);
	AuthorizationRef localAuthorization = NULL;
	if (CFDictionaryGetValue(ctx, kSecAssessmentUpdateKeyAuthorization) == NULL) {	// no caller-provided authorization
		MacOSError::check(AuthorizationCreate(NULL, NULL, kAuthorizationFlagDefaults, &localAuthorization));
		AuthorizationExternalForm extForm;
		MacOSError::check(AuthorizationMakeExternalForm(localAuthorization, &extForm));
		CFDictionaryAddValue(ctx, kSecAssessmentUpdateKeyAuthorization, CFTempData(&extForm, sizeof(extForm)));
	}
	CFRef<CFDataRef> contextData = makeCFData(CFDictionaryRef(ctx));
	xpc_dictionary_set_data(msg, "context", CFDataGetBytePtr(contextData), CFDataGetLength(contextData));
	
	msg.send();

	if (localAuthorization)
		AuthorizationFree(localAuthorization, kAuthorizationFlagDefaults);
	
	if (int64_t error = xpc_dictionary_get_int64(msg, "error"))
		MacOSError::throwMe(error);
	
	size_t resultLength;
	const void *resultData = xpc_dictionary_get_data(msg, "result", &resultLength);
	return makeCFDictionaryFrom(resultData, resultLength);
}
__private_extern__ CFIndex CFPreferencesAppIntegerValue(CFStringRef key, CFStringRef appName, Boolean *keyExistsAndHasValidFormat) {
    CFPropertyListRef value;
    CFIndex result;
    CFTypeID typeID = 0;
    Boolean valid;
    CFAssert1(appName != NULL, __kCFLogAssertion, "%s(): Cannot access application preferences with a NULL application name", __PRETTY_FUNCTION__);
    CFAssert1(key != NULL, __kCFLogAssertion, "%s(): Cannot access preferences with a NULL key", __PRETTY_FUNCTION__);

    value = CFPreferencesCopyAppValue(key, appName);
    if (!keyExistsAndHasValidFormat) {
        keyExistsAndHasValidFormat = &valid;
    }
    if (!value) {
        *keyExistsAndHasValidFormat = false;
        return 0;
    }
    typeID = CFGetTypeID(value);
    if (typeID == CFStringGetTypeID()) {
        SInt32 charIndex = 0;
        SInt32 intVal;
        CFStringInlineBuffer buf;
        Boolean success;
        CFStringInitInlineBuffer((CFStringRef)value, &buf, CFRangeMake(0, CFStringGetLength((CFStringRef)value)));
        success = __CFStringScanInteger(&buf, NULL, &charIndex, false, &intVal);
        *keyExistsAndHasValidFormat = (success && charIndex == CFStringGetLength((CFStringRef)value));
        result = (*keyExistsAndHasValidFormat) ? intVal : 0;
    } else if (typeID == CFNumberGetTypeID()) {
        *keyExistsAndHasValidFormat = !CFNumberIsFloatType((CFNumberRef)value);
        if (*keyExistsAndHasValidFormat) {
            CFNumberGetValue((CFNumberRef)value, kCFNumberCFIndexType, &result);
        } else {
            result = 0;
        }
    } else {
        // Unknown type
        result = 0;
        *keyExistsAndHasValidFormat = false;
    }
    CFRelease(value);
    return result;
}
Esempio n. 15
0
inline SQLite3Status SQLite3StatementBindCFType(SQLite3StatementRef statement, CFIndex index, CFTypeRef value) {
  SQLite3Status status = kSQLite3StatusError;
  if (value) {
    CFTypeID valueTypeID = CFGetTypeID(value);
    if (CFStringGetTypeID() == valueTypeID)
      status = SQLite3StatementBindString(statement, index, (CFStringRef)value);
    else if (CFDataGetTypeID() == valueTypeID)
      status = SQLite3StatementBindData(statement, index, (CFDataRef)value);
//  else if (CGImageGetTypeID() == valueTypeID)
//    status = SQLite3StatementBindImage(statement, index, (CGImageRef)value);
    else if (CFDateGetTypeID() == valueTypeID)
      status = SQLite3StatementBindDate(statement, index, (CFDateRef)value);
    else if (CFNumberGetTypeID() == valueTypeID)
      status = SQLite3StatementBindNumber(statement, index, (CFNumberRef)value);
    else
      status = kSQLite3StatusError;
  } else {
    status = SQLite3StatementBindNULL(statement, index);
  }
  return status;
}
Esempio n. 16
0
long int GetPointerAccelerationThreshold() {
	#if defined COREFOUNDATION
	bool successful = false;
	SInt32 threshold;
	#endif

	long int value = -1;

	#ifdef COREFOUNDATION
	if (!successful) {
		CFTypeRef pref_val = CFPreferencesCopyValue(CFSTR("mouseDriverMaxSpeed"), CFSTR("com.apple.universalaccess"), kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
		if (pref_val != NULL && CFGetTypeID(pref_val) == CFNumberGetTypeID()) {
			if (CFNumberGetValue((CFNumberRef) pref_val, kCFNumberSInt32Type, &threshold)) {
				value = (long) threshold;
			}
		}
	}
	#endif

	return value;
}
Esempio n. 17
0
static Boolean IOHIDDevice_GetPtrProperty(IOHIDDeviceRef inIOHIDDeviceRef, CFStringRef inKey, void **outValue) {
	Boolean result = false;
	if (inIOHIDDeviceRef) {
		assert(IOHIDDeviceGetTypeID() == CFGetTypeID(inIOHIDDeviceRef));

		CFTypeRef tCFTypeRef = IOHIDDeviceGetProperty(inIOHIDDeviceRef, inKey);
		if (tCFTypeRef) {
			// if this is a number
			if (CFNumberGetTypeID() == CFGetTypeID(tCFTypeRef)) {
				// get it's value
#ifdef __LP64__
				result = CFNumberGetValue((CFNumberRef) tCFTypeRef, kCFNumberSInt64Type, outValue);
#else
				result = CFNumberGetValue((CFNumberRef) tCFTypeRef, kCFNumberSInt32Type, outValue);
#endif // ifdef __LP64__
			}
		}
	}

	return (result);
} // IOHIDDevice_GetPtrProperty
Esempio n. 18
0
/*
 * Do dictionary lookup, convert possible CFNumber to uint32.
 * Does not alter val if valid number is not found.
 */
static void rsaLookupVal(
    Dictionary &prefs,
    CFStringRef key,
    uint32 &val)
{
    CFNumberRef cfVal = (CFNumberRef)prefs.getValue(key);
    if(cfVal == NULL) {
        return;
    }
    if(CFGetTypeID(cfVal) != CFNumberGetTypeID()) {
        return;
    }

    /* ensure the number is positive, not relying on gcc 64-bit arithmetic */
    SInt32 s32 = 0;
    CFNumberRef cfLimit = CFNumberCreate(NULL, kCFNumberSInt32Type, &s32);
    CFComparisonResult result = CFNumberCompare(cfVal, cfLimit, NULL);
    CFRelease(cfLimit);
    if(result == kCFCompareLessThan) {
        /* negative value in preference */
        return;
    }

    /* ensure the number fits in 31 bits (the useful size of a SInt32 for us) */
    s32 = 0x7fffffff;
    cfLimit = CFNumberCreate(NULL, kCFNumberSInt32Type, &s32);
    result = CFNumberCompare(cfVal, cfLimit, NULL);
    CFRelease(cfLimit);
    if(result == kCFCompareGreaterThan) {
        /* too large; discard it */
        return;
    }
    SInt64 s64;
    if(!CFNumberGetValue(cfVal, kCFNumberSInt64Type, &s64)) {
        /* impossible, right? We already range checked */
        return;
    }
    val = (uint32)s64;
}
bool	CACFDictionary::GetFixed32(const CFStringRef inKey, Float32& outValue) const
{
	bool theAnswer = false;
	
	CFTypeRef theValue = NULL;
	if(GetCFType(inKey, theValue))
	{
		if((theValue != NULL) && (CFGetTypeID(theValue) == CFNumberGetTypeID()))
		{
			SInt32 theFixed32 = 0;
			CFNumberGetValue(static_cast<CFNumberRef>(theValue), kCFNumberSInt32Type, &theFixed32);
			
			//	this is a 16.16 value so convert it to a float
			Float32 theSign = theFixed32 < 0 ? -1.0f : 1.0f;
			theFixed32 *= (SInt32)theSign;
			Float32 theWholePart = (theFixed32 & 0x7FFF0000) >> 16;
			Float32 theFractPart = theFixed32 & 0x0000FFFF;
			theFractPart /= 65536.0f;
			outValue = theSign * (theWholePart + theFractPart);
			theAnswer = true;
		}
	}
Esempio n. 20
0
bool AppleRemote::_initCookies()
{
    IOHIDDeviceInterface122** handle;
    CFArrayRef                elements;
    IOReturn                  success;

    handle  = (IOHIDDeviceInterface122**)hidDeviceInterface;
    success = (*handle)->copyMatchingElements(handle,
                                              NULL,
                                              (CFArrayRef*)&elements);

    if (success == kIOReturnSuccess)
    {
        for (CFIndex i = 0; i < CFArrayGetCount(elements); ++i)
        {
            CFDictionaryRef    element;
            CFTypeRef          object;
            long               number;
            IOHIDElementCookie cookie;

            element = (CFDictionaryRef)CFArrayGetValueAtIndex(elements, i);
            object  = CFDictionaryGetValue(element,
                                           CFSTR(kIOHIDElementCookieKey));

            if (object == 0 || CFGetTypeID(object) != CFNumberGetTypeID())
                continue;

            if (!CFNumberGetValue((CFNumberRef)object,
                                  kCFNumberLongType, &number))
                continue;

            cookie = (IOHIDElementCookie)number;

            cookies.push_back((int)cookie);
        }
        return true;
    }
    return false;
}
static OSStatus GetKeySize(CFDictionaryRef parameters, CSSM_ALGORITHMS algorithms, uint32 &keySizeInBits)
{

    // get the key size and check it for validity
    CFTypeRef ref = CFDictionaryGetValue(parameters, kSecAttrKeySizeInBits);

    keySizeInBits = kSecDefaultKeySize;

    CFTypeID bitSizeType = CFGetTypeID(ref);
    if (bitSizeType == CFStringGetTypeID())
        keySizeInBits = ConvertCFStringToInteger((CFStringRef) ref);
    else if (bitSizeType == CFNumberGetTypeID())
        CFNumberGetValue((CFNumberRef) ref, kCFNumberSInt32Type, &keySizeInBits);
    else return errSecParam;


    switch (algorithms) {
    case CSSM_ALGID_ECDSA:
        if(keySizeInBits == kSecDefaultKeySize) keySizeInBits = kSecp256r1;
        if(keySizeInBits == kSecp192r1 || keySizeInBits == kSecp256r1 || keySizeInBits == kSecp384r1 || keySizeInBits == kSecp521r1 ) return noErr;
        break;
    case CSSM_ALGID_RSA:
			  if(keySizeInBits % 8) return errSecParam;
        if(keySizeInBits == kSecDefaultKeySize) keySizeInBits = 2048;
        if(keySizeInBits >= kSecRSAMin && keySizeInBits <= kSecRSAMax) return noErr;
        break;
    case CSSM_ALGID_AES:
        if(keySizeInBits == kSecDefaultKeySize) keySizeInBits = kSecAES128;
        if(keySizeInBits == kSecAES128 || keySizeInBits == kSecAES192 || keySizeInBits == kSecAES256) return noErr;
        break;
    case CSSM_ALGID_3DES:
        if(keySizeInBits == kSecDefaultKeySize) keySizeInBits = kSec3DES192;
        if(keySizeInBits == kSec3DES192) return noErr;
        break;
    default:
        break;
    }
    return errSecParam;
}
Esempio n. 22
0
void	CASettingsStorage::CopyFloat64Value(CFStringRef inKey, Float64& outValue, Float64 inDefaultValue) const
{
	//	initialize the return value
	outValue = inDefaultValue;
	
	//	get the raw value
	CFTypeRef theValue = NULL;
	CopyCFTypeValue(inKey, theValue, NULL);
	
	//	for this type, NULL is an invalid value
	if(theValue != NULL)
	{
		//	make sure we are dealing with the right kind of CF object
		if(CFGetTypeID(theValue) == CFNumberGetTypeID())
		{
			//	get the return value from the CF object
			CFNumberGetValue(static_cast<CFNumberRef>(theValue), kCFNumberFloat64Type, &outValue);
		}
		
		//	release the value since we aren't returning it
		CFRelease(theValue);
	}
}
Esempio n. 23
0
bool	CACFArray::GetBool(UInt32 inIndex, bool& outValue) const
{
	bool theAnswer = false;
	
	CFTypeRef theValue = NULL;
	if(GetCFType(inIndex, theValue))
	{
		if((theValue != NULL) && (CFGetTypeID(theValue) == CFBooleanGetTypeID()))
		{
			outValue = CFBooleanGetValue(static_cast<CFBooleanRef>(theValue));
			theAnswer = true;
		}
		else if((theValue != NULL) && (CFGetTypeID(theValue) == CFNumberGetTypeID()))
		{
			SInt32 theNumericValue = 0;
			CFNumberGetValue(static_cast<CFNumberRef>(theValue), kCFNumberSInt32Type, &theNumericValue);
			outValue = theNumericValue != 0;
			theAnswer = true;
		}
	}
	
	return theAnswer;
}
Esempio n. 24
0
int
cfboolean_get_value(CFTypeRef p)
{
	int value = 0;
	int retval = 0;
	
	if (NULL == p) {
		goto cleanup;
	}
	
	if (CFBooleanGetTypeID() == CFGetTypeID(p))
		retval = CFBooleanGetValue(p);
	else if (CFNumberGetTypeID() == CFGetTypeID(p) && CFNumberGetValue(p, kCFNumberIntType, &value))
		retval = value;
	else
		retval = 0;
	
cleanup:
	if (PAM_SUCCESS != retval)
		openpam_log(PAM_LOG_ERROR, "failed: %d", retval);
	
	return retval;
}
Esempio n. 25
0
CFDataRef CreatePropertyFromCertificate(const SecCertificateRef& cert,
                                        const CFTypeRef& oid) {
  // Set the list of attributes.
  auto keys = CFArrayCreateMutable(nullptr, 0, &kCFTypeArrayCallBacks);
  CFArrayAppendValue(keys, oid); // SecCertificateOIDs.h

  // Request dictionary of dictionaries (one for each attribute).
  auto certificate_values = SecCertificateCopyValues(cert, keys, nullptr);
  CFRelease(keys);

  if (!CFDictionaryContainsKey(certificate_values, oid)) {
    // Certificate does not have the requested property.
    CFRelease(certificate_values);
    return nullptr;
  }

  auto values = (CFDictionaryRef)CFDictionaryGetValue(certificate_values, oid);
  if (!CFDictionaryContainsKey(values, kSecPropertyKeyValue)) {
    // Odd, there was not value in the property result.
    CFRelease(certificate_values);
    return nullptr;
  }

  // Create copy of the property value, which is an index to owned dict.
  auto property = (CFDataRef)CFDictionaryGetValue(values, kSecPropertyKeyValue);
  if (CFGetTypeID(property) == CFArrayGetTypeID()) {
    property = (CFDataRef)CFArrayCreateCopy(nullptr, (CFArrayRef)property);
  } else if (CFGetTypeID(property) == CFNumberGetTypeID()) {
    property = (CFDataRef)CFNumberCreateCopy((CFNumberRef)property);
  } else {
    property = nullptr;
  }

  // Release and give the caller control of the property.
  CFRelease(certificate_values);
  return property;
}
Esempio n. 26
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;
}
Esempio n. 27
0
int GetIntPreference(const char * name, int defaut)
{
    int retour = defaut;

    CFStringRef nom = CFStringCreateWithCString (NULL,name,CFStringGetSystemEncoding());

    if (nom != NULL)
    {
        CFNumberRef value = (CFNumberRef)CFPreferencesCopyAppValue(nom,kCFPreferencesCurrentApplication);

        if (value != NULL)
        {
           if (CFGetTypeID(value) == CFNumberGetTypeID ())
           {
            if (CFNumberGetValue (value, kCFNumberIntType,&retour) == false)
                retour = defaut;
           }
            CFRelease(value);
        }
        CFRelease(nom);
    }

    return retour;
}
Esempio n. 28
0
UIOHOOK_API long int hook_get_pointer_acceleration_threshold() {
	#if defined USE_COREFOUNDATION
	bool successful = false;
	SInt32 threshold;
	#endif

	long int value = -1;

	#ifdef USE_COREFOUNDATION
	if (!successful) {
		CFTypeRef pref_val = CFPreferencesCopyValue(CFSTR("mouseDriverMaxSpeed"), CFSTR("com.apple.universalaccess"), kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
		if (pref_val != NULL && CFGetTypeID(pref_val) == CFNumberGetTypeID()) {
			if (CFNumberGetValue((CFNumberRef) pref_val, kCFNumberSInt32Type, &threshold)) {
				value = (long) threshold;

				logger(LOG_LEVEL_INFO,	"%s [%u]: CFPreferencesCopyValue: %li.\n",
						__FUNCTION__, __LINE__, value);
			}
		}
	}
	#endif

	return value;
}
Esempio n. 29
0
static double dict_get_double(CFDictionaryRef dict,
                              const char *key_string) /* {{{ */
{
  double val_double;
  long long val_int;
  CFNumberRef val_obj;
  CFStringRef key_obj;

  key_obj = CFStringCreateWithCString(kCFAllocatorDefault, key_string,
                                      kCFStringEncodingASCII);
  if (key_obj == NULL) {
    DEBUG("CFStringCreateWithCString (%s) failed.\n", key_string);
    return (NAN);
  }

  if ((val_obj = CFDictionaryGetValue(dict, key_obj)) == NULL) {
    DEBUG("CFDictionaryGetValue (%s) failed.", key_string);
    CFRelease(key_obj);
    return (NAN);
  }
  CFRelease(key_obj);

  if (CFGetTypeID(val_obj) == CFNumberGetTypeID()) {
    if (CFNumberIsFloatType(val_obj)) {
      CFNumberGetValue(val_obj, kCFNumberDoubleType, &val_double);
    } else {
      CFNumberGetValue(val_obj, kCFNumberLongLongType, &val_int);
      val_double = val_int;
    }
  } else {
    DEBUG("CFGetTypeID (val_obj) = %i", (int)CFGetTypeID(val_obj));
    return (NAN);
  }

  return (val_double);
} /* }}} double dict_get_double */
Esempio n. 30
0
File: IPC.c Progetto: aosm/Startup
/**
 * Returns a reference to an item based on tokens passed in an IPC message.
 * This is useful for figuring out which item the message came from.
 * 
 * Currently two tokens are supported:
 * kIPCProcessIDKey - the pid of the running startup script
 * kIPCServiceNameKey - a name of a service that the item provides.  This
 *	takes precedence over the pid key when both are present.
 **/
static CFMutableDictionaryRef itemFromIPCMessage (StartupContext aStartupContext, CFDictionaryRef anIPCMessage)
{
    CFMutableDictionaryRef anItem = NULL;
    
    if (aStartupContext && anIPCMessage)
      {        
        CFStringRef     aServiceName = CFDictionaryGetValue(anIPCMessage, kIPCServiceNameKey);
        CFIndex         aPID         = 0;
        CFNumberRef     aPIDNumber   = CFDictionaryGetValue(anIPCMessage, kIPCProcessIDKey);
    
        if (aServiceName && CFGetTypeID(aServiceName) == CFStringGetTypeID())
          {
            anItem = StartupItemListGetProvider(aStartupContext->aWaitingList, aServiceName);
          }
        else if (aPIDNumber							&& 
                CFGetTypeID(aPIDNumber) == CFNumberGetTypeID()		&&
                CFNumberGetValue(aPIDNumber, kCFNumberCFIndexType, &aPID)	)
          {
            anItem = StartupItemWithPID(aStartupContext->aWaitingList, aPID);
          }
      }
      
    return anItem;
}