コード例 #1
0
ファイル: ID3v1.c プロジェクト: ljsebald/SonatinaTag
ST_FUNC CFArrayRef ST_ID3v1_copyGenres(void) {
    CFMutableArrayRef rv = CFArrayCreateMutable(kCFAllocatorDefault,
                                                ID3v1GenreMax + 1,
                                                &kCFTypeArrayCallBacks);
    CFStringRef tmp;
    int i;

    if(rv) {
        for(i = 0; i <= ID3v1GenreMax; ++i) {
            tmp = CFStringCreateWithCString(kCFAllocatorDefault, id3_genres[i],
                                            kCFStringEncodingISOLatin1);
            if(tmp) {
                CFArrayAppendValue(rv, tmp);
                CFRelease(tmp);
            }
            else {
                CFRelease(rv);
                return NULL;
            }
        }
    }

    return (CFArrayRef)rv;
}
コード例 #2
0
/*****************************************************************************
 * Alloc
 * - 
 * Functionas as both +[alloc] and -[init] for the plugin. Add any 
 * initalization of member variables here.
 *****************************************************************************/
static BonjourUserEventsPlugin* Alloc(CFUUIDRef factoryID)
{
	BonjourUserEventsPlugin* plugin = malloc(sizeof(BonjourUserEventsPlugin));
	
	plugin->_UserEventAgentInterface = &UserEventAgentInterfaceFtbl;
	plugin->_pluginContext = NULL;
		
	if (factoryID) 
	{
		plugin->_factoryID = (CFUUIDRef)CFRetain(factoryID);
		CFPlugInAddInstanceForFactory(factoryID);
	}
	
	plugin->_refCount = 1;
	plugin->_tokenToBrowserMap = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kNetBrowserInfoDictionaryValueCallbacks);
	plugin->_browsers = CFDictionaryCreateMutable(NULL, 0, &kNetBrowserInfoDictionaryKeyCallbacks, &kCFTypeDictionaryValueCallBacks);
	plugin->_onAddEvents = CFDictionaryCreateMutable(NULL, 0, &kNetBrowserInfoDictionaryKeyCallbacks, &kCFTypeDictionaryValueCallBacks);
	plugin->_onRemoveEvents = CFDictionaryCreateMutable(NULL, 0, &kNetBrowserInfoDictionaryKeyCallbacks, &kCFTypeDictionaryValueCallBacks);
	plugin->_whileServiceExist = CFDictionaryCreateMutable(NULL, 0, &kNetBrowserInfoDictionaryKeyCallbacks, &kCFTypeDictionaryValueCallBacks);
	
	plugin->_timers = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
	
	return plugin;
}
コード例 #3
0
ファイル: NCFArray.cpp プロジェクト: refnum/nano
//============================================================================
//		NCFArray::GetObject : Get the object.
//----------------------------------------------------------------------------
NCFObject NCFArray::GetObject(void) const
{	NCFObject		theObject, theValue;
	NIndex			n, numItems;



	// Get the state we need
	numItems = GetSize();
	
	if (!theObject.SetObject(CFArrayCreateMutable(kCFAllocatorNano, numItems, &kCFTypeArrayCallBacks)))
		return(theObject);



	// Get the object
	for (n = 0; n < numItems; n++)
		{
		theValue = NMacTarget::ConvertObjectToCF(GetValue(n));
		if (theValue.IsValid())
			CFArrayAppendValue(theObject, (CFTypeRef) theValue);
		}

	return(theObject);
}
コード例 #4
0
ファイル: apple_joypad.c プロジェクト: DerrrekWang/RetroArch
// RetroArch joypad driver:
static bool apple_joypad_init(void)
{
#ifdef OSX
    CFMutableArrayRef matcher;
    
    if (!g_hid_manager)
    {
        g_hid_manager = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);
        
        matcher = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
        append_matching_dictionary(matcher, kHIDPage_GenericDesktop, kHIDUsage_GD_Joystick);
        append_matching_dictionary(matcher, kHIDPage_GenericDesktop, kHIDUsage_GD_GamePad);
        
        IOHIDManagerSetDeviceMatchingMultiple(g_hid_manager, matcher);
        CFRelease(matcher);
        
        IOHIDManagerRegisterDeviceMatchingCallback(g_hid_manager, hid_manager_device_attached, 0);
        IOHIDManagerScheduleWithRunLoop(g_hid_manager, CFRunLoopGetMain(), kCFRunLoopCommonModes);
        
        IOHIDManagerOpen(g_hid_manager, kIOHIDOptionsTypeNone);
    }
#endif
   return true;
}
コード例 #5
0
JSValue UserObjectImp::callAsFunction(ExecState *exec, JSObject *thisObj, const ArgList &args)
{
    JSValue result = jsUndefined();
    JSUserObject* jsThisObj = KJSValueToJSObject(thisObj, exec);
    if (jsThisObj) {
        CFIndex argCount = args.size();
        CFArrayCallBacks arrayCallBacks;
        JSTypeGetCFArrayCallBacks(&arrayCallBacks);
        CFMutableArrayRef jsArgs = CFArrayCreateMutable(0, 0, &arrayCallBacks);
        if (jsArgs) {
            for (CFIndex i = 0; i < argCount; i++) {
                JSUserObject* jsArg = KJSValueToJSObject(args.at(i), exec);
                CFArrayAppendValue(jsArgs, (void*)jsArg);
                jsArg->Release();
            }
        }

        JSUserObject* jsResult;
        {   // scope
            JSLock::DropAllLocks dropLocks(exec);

            // getCallData should have guarded against a NULL fJSUserObject.
            assert(fJSUserObject);
            jsResult = fJSUserObject->CallFunction(jsThisObj, jsArgs);
        }

        if (jsResult) {
            result = JSObjectKJSValue(jsResult);
            jsResult->Release();
        }

        ReleaseCFType(jsArgs);
        jsThisObj->Release();
    }
    return result;
}
コード例 #6
0
ファイル: CFLocale.c プロジェクト: AbhinavBansal/opencflite
static CFArrayRef __CFLocaleCopyUEnumerationAsArray(UEnumeration *enumer, UErrorCode *icuErr) {
    const UChar *next = NULL;
    int32_t len = 0;
    CFMutableArrayRef working = NULL;
    if (U_SUCCESS(*icuErr)) {
        working = CFArrayCreateMutable(kCFAllocatorSystemDefault, 0, &kCFTypeArrayCallBacks);
    }
    while ((next = uenum_unext(enumer, &len, icuErr)) && U_SUCCESS(*icuErr)) {
        CFStringRef string = CFStringCreateWithCharacters(kCFAllocatorSystemDefault, (const UniChar *)next, (CFIndex) len);
        CFArrayAppendValue(working, string);
        CFRelease(string);
    }
    if (*icuErr == U_INDEX_OUTOFBOUNDS_ERROR) {
        *icuErr = U_ZERO_ERROR;      // Temp: Work around bug (ICU 5220) in ucurr enumerator
    }
    CFArrayRef result = NULL;
    if (U_SUCCESS(*icuErr)) {
        result = CFArrayCreateCopy(kCFAllocatorSystemDefault, working);
    }
    if (working != NULL) {
        CFRelease(working);
    }
    return result;
}
コード例 #7
0
ファイル: filedlg.cpp プロジェクト: 0ryuO/dolphin-avsync
OpenUserDataRec::OpenUserDataRec( wxFileDialog* d)
{
    m_dialog = d;
    m_controlAdded = false;
    m_saveMode = m_dialog->HasFdFlag(wxFD_SAVE);

    m_defaultLocation = m_dialog->GetDirectory();
    MakeUserDataRec(m_dialog->GetWildcard());
    m_currentfilter = m_dialog->GetFilterIndex();

    m_menuitems = NULL;

    size_t numFilters = m_extensions.GetCount();
    if (numFilters)
    {
        m_menuitems = CFArrayCreateMutable( kCFAllocatorDefault ,
                                         numFilters , &kCFTypeArrayCallBacks ) ;
        for ( size_t i = 0 ; i < numFilters ; ++i )
        {
            CFArrayAppendValue( m_menuitems , (CFStringRef) wxCFStringRef( m_name[i] ) ) ;
        }
    }
    m_lastRight = m_lastBottom = 0;
}
コード例 #8
0
JSValue UserObjectImp::callAsFunction(ExecState *exec)
{
    JSValue result = jsUndefined();
    JSUserObject* jsThisObj = KJSValueToJSObject(exec->hostThisValue().toThisObject(exec), exec);
    if (jsThisObj) {
        CFIndex argCount = exec->argumentCount();
        CFArrayCallBacks arrayCallBacks;
        JSTypeGetCFArrayCallBacks(&arrayCallBacks);
        CFMutableArrayRef jsArgs = CFArrayCreateMutable(0, 0, &arrayCallBacks);
        if (jsArgs) {
            for (CFIndex i = 0; i < argCount; i++) {
                JSUserObject* jsArg = KJSValueToJSObject(exec->argument(i), exec);
                CFArrayAppendValue(jsArgs, (void*)jsArg);
                jsArg->Release();
            }
        }

        JSUserObject* jsResult;
        { // scope
            JSGlueAPICallback apiCallback(exec);

            // getCallData should have guarded against a NULL fJSUserObject.
            assert(fJSUserObject);
            jsResult = fJSUserObject->CallFunction(jsThisObj, jsArgs);
        }

        if (jsResult) {
            result = JSObjectKJSValue(jsResult);
            jsResult->Release();
        }

        ReleaseCFType(jsArgs);
        jsThisObj->Release();
    }
    return result;
}
コード例 #9
0
/*
 * Function: setInterfaceEAPOLConfiguration
 * Purpose:
 *   Set the EAPOL configuration for the particular interface in the
 *   cfg->sc_prefs and add the SCNetworkInterfaceRef to cfg->sc_changed_if.
 *   That allows saveInterfaceEAPOLConfiguration() to know which interfaces
 *   were changed when it commits the changes to the writable prefs.
 */
STATIC Boolean
setInterfaceEAPOLConfiguration(EAPOLClientConfigurationRef cfg, 
			       SCNetworkInterfaceRef net_if,
			       CFDictionaryRef dict)
{
    CFRange	r;
    Boolean	ret;

    ret = SCNetworkInterfaceSetExtendedConfiguration(net_if, kEAPOL, dict);
    if (ret == FALSE) {
	return (ret);
    }
    /* keep track of which SCNetworkInterfaceRef's were changed */
    if (cfg->sc_changed_if == NULL) {
	cfg->sc_changed_if = CFArrayCreateMutable(NULL, 0, 
						  &kCFTypeArrayCallBacks);
    }
    r.location = 0;
    r.length = CFArrayGetCount(cfg->sc_changed_if);
    if (CFArrayContainsValue(cfg->sc_changed_if, r, net_if) == FALSE) {
	CFArrayAppendValue(cfg->sc_changed_if, net_if);
    }
    return (TRUE);
}
コード例 #10
0
ファイル: iohidmanager_hid.c プロジェクト: Monroe88/RetroArch
static int iohidmanager_hid_manager_set_device_matching(
      iohidmanager_hid_t *hid)
{
   CFMutableArrayRef matcher = CFArrayCreateMutable(kCFAllocatorDefault, 0,
         &kCFTypeArrayCallBacks);

   if (!matcher)
      return -1;

   iohidmanager_hid_append_matching_dictionary(matcher,
         kHIDPage_GenericDesktop,
         kHIDUsage_GD_Joystick);
   iohidmanager_hid_append_matching_dictionary(matcher,
         kHIDPage_GenericDesktop,
         kHIDUsage_GD_GamePad);

   IOHIDManagerSetDeviceMatchingMultiple(hid->ptr, matcher);
   IOHIDManagerRegisterDeviceMatchingCallback(hid->ptr,
         iohidmanager_hid_device_add, 0);

   CFRelease(matcher);

   return 0;
}
コード例 #11
0
ファイル: PageSetupPDE.c プロジェクト: fruitsamples/App
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	Name:	MyPDEGetSummaryText

	Input Parameters:
		context			:	The plugins context
		titleArray 		:	an array to store the title of the summary text
		summaryArray		:	an array to store the summary text
		
	Output Parameters:
		titleArray 		:	updated with this plugins summary text title
		summaryArray		:	updated with this plugins summary text
		err			:	returns the error status

	Description:
		Returns the status/state of the plugin in textual form

	Change History (most recent first):

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
static 
OSStatus MyPDEGetSummaryText(PMPDEContext	context, 
                        CFArrayRef 		*titleArray,
                        CFArrayRef		*summaryArray)
{
	OSStatus err = noErr;
        CFMutableArrayRef theTitleArray = NULL;		// Init CF strings
        CFMutableArrayRef theSummaryArray = NULL;
        CFStringRef titleStringRef = NULL;
        CFStringRef summaryStringRef = NULL;
	PageSetupPDEOnlyContextPtr myContext = NULL;	// Pointer to global data block.

        DebugMessage("PageSetupPDE MyPDEGetSummaryText called\n");
    
        myContext = (PageSetupPDEOnlyContextPtr) context;
	*titleArray = NULL;
        *summaryArray = NULL;

	if (myContext != NULL)
        {
		//  NOTE: if the second parameter to CFArrayCreateMutable 
		//		  is not 0 then the array is a FIXED size
		theTitleArray = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
		theSummaryArray = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
    
		if ((theTitleArray != NULL) && (theSummaryArray != NULL))
		{
		    SInt16	theControlValue = -1;
		    titleStringRef = CopyLocalizedStringFromPlugin(
					    CFSTR(" Print Title Text"),
					    CFSTR("Summary Title"),
					    myContext->theBundleRef);
		    theControlValue = GetControlValue(myContext->thePrintTitleControlRef);
		    switch (theControlValue)
		    {
			    case 0:
				    summaryStringRef = CopyLocalizedStringFromPlugin(
					    CFSTR(" No"),
					    CFSTR("Summary Text"),
					    myContext->theBundleRef);
				    break;
    
			    case 1:
				    summaryStringRef = CopyLocalizedStringFromPlugin(
					    CFSTR(" Yes"),
					    CFSTR("Summary Text"),
					    myContext->theBundleRef);
				    break;
		    }
		    if(titleStringRef && summaryStringRef){
			CFArrayAppendValue(theTitleArray, titleStringRef);
			CFArrayAppendValue(theSummaryArray, summaryStringRef);
		    }else
			err = memFullErr;
		}else{
			err = memFullErr;
		}
	}else
            err = kPMInvalidPDEContext;

        // we release these because we've added them already to the title and summary array
        // or we don't need them because there was an error
        if (titleStringRef)
                CFRelease(titleStringRef);
        if (summaryStringRef)
                CFRelease(summaryStringRef);
        
        // update the data passed in.
        if(!err){
            *titleArray = theTitleArray;
            *summaryArray = theSummaryArray;

        }else{
            if (theTitleArray)
                    CFRelease(theTitleArray);
            if (theSummaryArray)
                    CFRelease(theSummaryArray);
        }
        
	DebugPrintErr(err, "PageSetupPDE Error from MyPDEGetSummaryText returned %d\n");
	return (err);
}
コード例 #12
0
static OSStatus CreateCFArrayFromAEDescList(
	const AEDescList *	descList, 
	CFArrayRef *		itemsPtr
)
	// This routine's input is an AEDescList that contains replies 
	// from the "properties of every login item" event.  Each element 
	// of the list is an AERecord with two important properties, 
	// "path" and "hidden".  This routine creates a CFArray that 
	// corresponds to this list.  Each element of the CFArray 
	// contains two properties, kLIAEURL and 
	// kLIAEHidden, that are derived from the corresponding 
	// AERecord properties.
	//
	// On entry, descList must not be NULL
	// On entry,  itemsPtr must not be NULL
	// On entry, *itemsPtr must be NULL
	// On success, *itemsPtr will be a valid CFArray
	// On error, *itemsPtr will be NULL
{
	OSStatus			err;
	CFMutableArrayRef	result;
	long				itemCount;
	long				itemIndex;
	AEKeyword			junkKeyword;
	DescType			junkType;
	Size				junkSize;
	
	assert( itemsPtr != NULL);
	assert(*itemsPtr == NULL);

	result = NULL;
	
	// Create a place for the result.
	
    err = noErr;
    result = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
    if (result == NULL) {
        err = coreFoundationUnknownErr;
    }
	
	// For each element in the descriptor list...
	
	if (err == noErr) {
		err = AECountItems(descList, &itemCount);
	}
	if (err == noErr) {
		for (itemIndex = 1; itemIndex <= itemCount; itemIndex++) {
		  if (itemIndex == 4) {
			  int notused = 0;
				notused++;
			}
			AERecord 			thisItem;
			UInt8 				thisPath[1024];
			Size				thisPathSize;
			FSRef				thisItemRef;
			CFURLRef			thisItemURL;
			Boolean				thisItemHidden;
			CFDictionaryRef		thisItemDict;
			
			thisItem = kAENull;
			thisItemURL = NULL;
			thisItemDict = NULL;
			
			// Get this element's AERecord.
			
			err = AEGetNthDesc(descList, itemIndex, typeAERecord, &junkKeyword, &thisItem);

			if (err != noErr) {
			  err = noErr;
				continue;
			}

			// Extract the path and create a CFURL.

			if (err == noErr) {
				err = AEGetKeyPtr(
					&thisItem, 
					propPath, 
					typeUTF8Text, 
					&junkType, 
					thisPath, 
					sizeof(thisPath) - 1, 		// to ensure that we can always add null terminator
					&thisPathSize
				);
			}
			
			if (err == noErr) {
				thisPath[thisPathSize] = 0;
				
				err = FSPathMakeRef(thisPath, &thisItemRef, NULL);
				
				if (err == noErr) {
					thisItemURL = CFURLCreateFromFSRef(NULL, &thisItemRef);
				} else {
					err = noErr;			// swallow error and create an imprecise URL
					
					thisItemURL = CFURLCreateFromFileSystemRepresentation(
						NULL,
						thisPath,
						thisPathSize,
						false
					);
				}
				if (thisItemURL == NULL) {
					err = coreFoundationUnknownErr;
				}
			}
			
			// Extract the hidden flag.
			
			if (err == noErr) {
				err = AEGetKeyPtr(
					&thisItem, 
					propHidden, 
					typeBoolean, 
					&junkType, 
					&thisItemHidden, 
					sizeof(thisItemHidden),
					&junkSize
				);
                
                // Work around <rdar://problem/4052117> by assuming that hidden 
                // is false if we can't get its value.
                
                if (err != noErr) {
                    thisItemHidden = false;
                    err = noErr;
                }
			}

			// Create the CFDictionary for this item.
			
			if (err == noErr) {
				CFStringRef keys[2];
				CFTypeRef	values[2];
				
				keys[0] = kLIAEURL;
				keys[1] = kLIAEHidden;
				
				values[0] = thisItemURL;
				values[1] = (thisItemHidden ? kCFBooleanTrue : kCFBooleanFalse);

				thisItemDict = CFDictionaryCreate(
					NULL,
					(const void **) keys,
					values,
					2,
					&kCFTypeDictionaryKeyCallBacks,
					&kCFTypeDictionaryValueCallBacks
				);
				if (thisItemDict == NULL) {
					err = coreFoundationUnknownErr;
				}
			}
			
			// Add it to the results array.
			
			if (err == noErr) {
				CFArrayAppendValue(result, thisItemDict);
			}
						
			AEDisposeDescQ(&thisItem);
			CFQRelease(thisItemURL);
			CFQRelease(thisItemDict);
						
			if (err != noErr) {
				break;
			}
		}
	}

	// Clean up.
	
	if (err != noErr) {
		CFQRelease(result);
		result = NULL;
	}
	*itemsPtr = result;
	assert( (err == noErr) == (*itemsPtr != NULL) );

	return err;
}
コード例 #13
0
ファイル: IOCFPlugIn.c プロジェクト: StrongZhu/IOKitUser
kern_return_t
IOCreatePlugInInterfaceForService(io_service_t service,
                CFUUIDRef pluginType, CFUUIDRef interfaceType,
                IOCFPlugInInterface *** theInterface, SInt32 * theScore)
{
    CFDictionaryRef	plist = 0;
    CFArrayRef		plists;
    CFArrayRef		factories;
    CFMutableArrayRef	candidates;
    CFMutableArrayRef	scores;
    CFIndex		index;
    CFIndex		insert;
    CFUUIDRef		factoryID;
    kern_return_t	kr;
    SInt32		score;
    IOCFPlugInInterface **	interface;
    Boolean		haveOne;


    kr = IOFindPlugIns( service, pluginType,
                        &factories, &plists );
    if( KERN_SUCCESS != kr) {
        if (factories) CFRelease(factories);
        if (plists) CFRelease(plists);
        return( kr );
    }
    if ((KERN_SUCCESS != kr)
        || (factories == NULL)
        || (0 == CFArrayGetCount(factories))) {
//        printf("No factories for type\n");
        if (factories) CFRelease(factories);
        if (plists) CFRelease(plists);
        return( kIOReturnUnsupported );
    }
    candidates = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
    scores = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);

    // allocate and Probe all
    if (candidates && scores) {
        CFIndex numfactories = CFArrayGetCount(factories);
        for ( index = 0; index < numfactories; index++ ) {
            IUnknownVTbl **				iunknown;
    
            factoryID = (CFUUIDRef) CFArrayGetValueAtIndex(factories, index);
            iunknown = (IUnknownVTbl **)
                CFPlugInInstanceCreate(NULL, factoryID, pluginType);
            if (!iunknown) {
    //            printf("Failed to create instance (link error?)\n");
                continue;
            }
            (*iunknown)->QueryInterface(iunknown, CFUUIDGetUUIDBytes(interfaceType),
                                (LPVOID *)&interface);
    
            // Now we are done with IUnknown interface
            (*iunknown)->Release(iunknown);
    
            if (!interface) {
    //            printf("Failed to get interface.\n");
                continue;
            }
            if (plists)
                plist = (CFDictionaryRef) CFArrayGetValueAtIndex( plists, index );
            score = 0;   // from property table
            kr = (*interface)->Probe(interface, plist, service, &score);
    
            if (kIOReturnSuccess == kr) {
                CFIndex numscores = CFArrayGetCount(scores);
                for (insert = 0; insert < numscores; insert++) {
                    if (score > (SInt32) ((intptr_t) CFArrayGetValueAtIndex(scores, insert)))
                        break;
                }
                CFArrayInsertValueAtIndex(candidates, insert, (void *) interface);
                CFArrayInsertValueAtIndex(scores, insert, (void *) (intptr_t) score);
            } else
                (*interface)->Release(interface);
        }
    }


    // Start in score order
    CFIndex candidatecount = CFArrayGetCount(candidates);
    for (haveOne = false, index = 0;
         index < candidatecount;
         index++) {

        Boolean freeIt;

        if (plists)
            plist = (CFDictionaryRef) CFArrayGetValueAtIndex(plists, index );
        interface = (IOCFPlugInInterface **)
            CFArrayGetValueAtIndex(candidates, index );
        if (!haveOne) {
            haveOne = (kIOReturnSuccess == (*interface)->Start(interface, plist, service));
            freeIt = !haveOne;
            if (haveOne) {
                *theInterface = interface;
                *theScore = (SInt32) (intptr_t)
		    CFArrayGetValueAtIndex(scores, index );
            }
        } else
            freeIt = true;
        if (freeIt)
            (*interface)->Release(interface);
    }

    if (factories)
        CFRelease(factories);
    if (plists)
        CFRelease(plists);
    if (candidates)
        CFRelease(candidates);
    if (scores)
        CFRelease(scores);
    //    CFRelease(plugin);

    return (haveOne ? kIOReturnSuccess : kIOReturnNoResources);
}
コード例 #14
0
ファイル: JSUtils.cpp プロジェクト: achellies/WinCEWebKit
//--------------------------------------------------------------------------
// KJSValueToCFTypeInternal
//--------------------------------------------------------------------------
// Caller is responsible for releasing the returned CFTypeRef
CFTypeRef KJSValueToCFTypeInternal(JSValue inValue, ExecState *exec, ObjectImpList* inImps)
{
    if (!inValue)
        return 0;

    CFTypeRef result = 0;

    JSGlueAPIEntry entry;

        if (inValue.isBoolean())
            {
                result = inValue.toBoolean(exec) ? kCFBooleanTrue : kCFBooleanFalse;
                RetainCFType(result);
                return result;
            }

        if (inValue.isString())
            {
                UString uString = inValue.toString(exec);
                result = UStringToCFString(uString);
                return result;
            }

        if (inValue.isNumber())
            {
                double number1 = inValue.toNumber(exec);
                double number2 = (double)inValue.toInteger(exec);
                if (number1 ==  number2)
                {
                    int intValue = (int)number2;
                    result = CFNumberCreate(0, kCFNumberIntType, &intValue);
                }
                else
                {
                    result = CFNumberCreate(0, kCFNumberDoubleType, &number1);
                }
                return result;
            }

        if (inValue.isObject())
            {
                if (inValue.inherits(&UserObjectImp::info)) {
                    UserObjectImp* userObjectImp = static_cast<UserObjectImp *>(asObject(inValue));
                    JSUserObject* ptr = userObjectImp->GetJSUserObject();
                    if (ptr)
                    {
                        result = ptr->CopyCFValue();
                    }
                }
                else
                {
                    JSObject *object = inValue.toObject(exec);
                    UInt8 isArray = false;

                    // if two objects reference each
                    JSObject* imp = object;
                    ObjectImpList* temp = inImps;
                    while (temp) {
                        if (imp == temp->imp) {
                            return CFRetain(GetCFNull());
                        }
                        temp = temp->next;
                    }

                    ObjectImpList imps;
                    imps.next = inImps;
                    imps.imp = imp;


//[...] HACK since we do not have access to the class info we use class name instead
#if 0
                    if (object->inherits(&ArrayInstanceImp::info))
#else
                    if (object->className() == "Array")
#endif
                    {
                        isArray = true;
                        JSGlueGlobalObject* globalObject = static_cast<JSGlueGlobalObject*>(exec->dynamicGlobalObject());
                        if (globalObject && (globalObject->Flags() & kJSFlagConvertAssociativeArray)) {
                            PropertyNameArray propNames(exec);
                            object->getPropertyNames(exec, propNames);
                            PropertyNameArray::const_iterator iter = propNames.begin();
                            PropertyNameArray::const_iterator end = propNames.end();
                            while(iter != end && isArray)
                            {
                                Identifier propName = *iter;
                                UString ustr = propName.ustring();
                                const UniChar* uniChars = (const UniChar*)ustr.characters();
                                int size = ustr.length();
                                while (size--) {
                                    if (uniChars[size] < '0' || uniChars[size] > '9') {
                                        isArray = false;
                                        break;
                                    }
                                }
                                iter++;
                            }
                        }
                    }

                    if (isArray)
                    {
                        // This is an KJS array
                        unsigned int length = object->get(exec, Identifier(exec, "length")).toUInt32(exec);
                        result = CFArrayCreateMutable(0, 0, &kCFTypeArrayCallBacks);
                        if (result)
                        {
                            for (unsigned i = 0; i < length; i++)
                            {
                                CFTypeRef cfValue = KJSValueToCFTypeInternal(object->get(exec, i), exec, &imps);
                                CFArrayAppendValue((CFMutableArrayRef)result, cfValue);
                                ReleaseCFType(cfValue);
                            }
                        }
                    }
                    else
                    {
                        // Not an array, just treat it like a dictionary which contains (property name, property value) pairs
                        PropertyNameArray propNames(exec);
                        object->getPropertyNames(exec, propNames);
                        {
                            result = CFDictionaryCreateMutable(0,
                                                               0,
                                                               &kCFTypeDictionaryKeyCallBacks,
                                                               &kCFTypeDictionaryValueCallBacks);
                            if (result)
                            {
                                PropertyNameArray::const_iterator iter = propNames.begin();
                                PropertyNameArray::const_iterator end = propNames.end();
                                while(iter != end)
                                {
                                    Identifier propName = *iter;
                                    if (object->hasProperty(exec, propName))
                                    {
                                        CFStringRef cfKey = IdentifierToCFString(propName);
                                        CFTypeRef cfValue = KJSValueToCFTypeInternal(object->get(exec, propName), exec, &imps);
                                        if (cfKey && cfValue)
                                        {
                                            CFDictionaryAddValue((CFMutableDictionaryRef)result, cfKey, cfValue);
                                        }
                                        ReleaseCFType(cfKey);
                                        ReleaseCFType(cfValue);
                                    }
                                    iter++;
                                }
                            }
                        }
                    }
                }
                return result;
            }

    if (inValue.isUndefinedOrNull())
        {
            result = RetainCFType(GetCFNull());
            return result;
        }

    ASSERT_NOT_REACHED();
    return 0;
}
コード例 #15
0
__private_extern__ CFArrayRef  _CFPreferencesCreateDomainList(CFStringRef  userName, CFStringRef  hostName) {
    CFAllocatorRef prefAlloc = __CFPreferencesAllocator();
    CFArrayRef  domains;
    CFMutableArrayRef  marray;
    CFStringRef  *cachedDomainKeys;
    CFPreferencesDomainRef *cachedDomains;
    SInt32 idx, cnt;
    CFStringRef  suffix;
    UInt32 suffixLen;
    CFURLRef prefDir = _preferencesDirectoryForUserHost(userName, hostName);
    
    if (!prefDir) {
        return NULL;
    }
    if (hostName == kCFPreferencesAnyHost) {
        suffix = CFStringCreateWithCString(prefAlloc, ".plist", kCFStringEncodingASCII);
    } else if (hostName == kCFPreferencesCurrentHost) {
        CFStringRef hostID = _CFPreferencesGetByHostIdentifierString();
        suffix = CFStringCreateWithFormat(prefAlloc, NULL, CFSTR(".%@.plist"), hostID);
    } else {
        suffix = CFStringCreateWithFormat(prefAlloc, NULL, CFSTR(".%@.plist"), hostName);   // sketchy - this allows someone to create a domain list for an arbitrary hostname.
    }
    suffixLen = CFStringGetLength(suffix);
    
    domains = (CFArrayRef)CFURLCreatePropertyFromResource(prefAlloc, prefDir, kCFURLFileDirectoryContents, NULL);
    CFRelease(prefDir);
    if (domains){
        marray = CFArrayCreateMutableCopy(prefAlloc, 0, domains);
        CFRelease(domains);
    } else {
        marray = CFArrayCreateMutable(prefAlloc, 0, & kCFTypeArrayCallBacks);
    }
    for (idx = CFArrayGetCount(marray)-1; idx >= 0; idx --) {
        CFURLRef  url = (CFURLRef)CFArrayGetValueAtIndex(marray, idx);
        CFStringRef string = CFURLCopyFileSystemPath(url, kCFURLPOSIXPathStyle);
        if (!CFStringHasSuffix(string, suffix)) {
            CFArrayRemoveValueAtIndex(marray, idx);
        } else {
            CFStringRef  dom = CFStringCreateWithSubstring(prefAlloc, string, CFRangeMake(0, CFStringGetLength(string) - suffixLen));
            if (CFEqual(dom, CFSTR(".GlobalPreferences"))) {
                CFArraySetValueAtIndex(marray, idx, kCFPreferencesAnyApplication);
            } else {
                CFArraySetValueAtIndex(marray, idx, dom);
            }
            CFRelease(dom);
        }
        CFRelease(string);
    }
    CFRelease(suffix);
    
    // Now add any domains added in the cache; delete any that have been deleted in the cache
    __CFSpinLock(&domainCacheLock);
    if (!domainCache) {
        __CFSpinUnlock(&domainCacheLock);
        return marray;
    }
    cnt = CFDictionaryGetCount(domainCache);
    cachedDomainKeys = (CFStringRef *)CFAllocatorAllocate(prefAlloc, 2 * cnt * sizeof(CFStringRef), 0);
    cachedDomains = (CFPreferencesDomainRef *)(cachedDomainKeys + cnt);
    CFDictionaryGetKeysAndValues(domainCache, (const void **)cachedDomainKeys, (const void **)cachedDomains);
    __CFSpinUnlock(&domainCacheLock);
    suffix = _CFPreferencesCachePrefixForUserHost(userName, hostName);
    suffixLen = CFStringGetLength(suffix);
    
    for (idx = 0; idx < cnt; idx ++) {
        CFStringRef  domainKey = cachedDomainKeys[idx];
        CFPreferencesDomainRef domain = cachedDomains[idx];
        CFStringRef  domainName;
        CFIndex keyCount = 0;
        
        if (!CFStringHasPrefix(domainKey, suffix)) continue;
        domainName = CFStringCreateWithSubstring(prefAlloc, domainKey, CFRangeMake(suffixLen, CFStringGetLength(domainKey) - suffixLen));
        if (CFEqual(domainName, CFSTR("*"))) {
            CFRelease(domainName);
            domainName = (CFStringRef)CFRetain(kCFPreferencesAnyApplication);
        } else if (CFEqual(domainName, kCFPreferencesCurrentApplication)) {
            CFRelease(domainName);
            domainName = (CFStringRef)CFRetain(_CFProcessNameString());
        }
        CFDictionaryRef d = _CFPreferencesDomainDeepCopyDictionary(domain);
        keyCount = d ? CFDictionaryGetCount(d) : 0;
        if (keyCount) CFRelease(d);
        if (keyCount == 0) {
            // Domain was deleted
            SInt32 firstIndexOfValue = CFArrayGetFirstIndexOfValue(marray, CFRangeMake(0, CFArrayGetCount(marray)), domainName);
            if (0 <= firstIndexOfValue) {
                CFArrayRemoveValueAtIndex(marray, firstIndexOfValue);
            }
        } else if (!CFArrayContainsValue(marray, CFRangeMake(0, CFArrayGetCount(marray)), domainName)) {
            CFArrayAppendValue(marray, domainName);
        }
        CFRelease(domainName);
    }
    CFRelease(suffix);
    CFAllocatorDeallocate(prefAlloc, cachedDomainKeys);
    return marray;
}
コード例 #16
0
__private_extern__
CF_RETURNS_RETAINED CFDictionaryRef
proxy_configuration_update(CFDictionaryRef	defaultProxy,
			   CFDictionaryRef	services,
			   CFArrayRef		serviceOrder,
			   CFDictionaryRef	servicesInfo)
{
	CFIndex			i;
	CFMutableDictionaryRef	myDefault;
	Boolean			myOrderAdded	= FALSE;
	CFMutableDictionaryRef	newProxy	= NULL;
	CFIndex			n_proxies;
	CFDictionaryRef		proxy;
	CFMutableArrayRef	proxies;

	// establish full list of proxies

	proxies = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);

	// collect (and add) any "supplemental" proxy configurations

	add_supplemental_proxies(proxies, services, serviceOrder);

	// add the "default" proxy

	add_default_proxy(proxies, defaultProxy, &myOrderAdded);

	// sort proxies, cleanup

	n_proxies = CFArrayGetCount(proxies);
	if (n_proxies > 1) {
		CFArraySortValues(proxies, CFRangeMake(0, n_proxies), compareDomain, NULL);
	}

	// cleanup

	for (i = n_proxies - 1; i >= 0; i--) {
		proxy = CFArrayGetValueAtIndex(proxies, i);

		if ((i > 0) &&
		    !CFDictionaryContainsKey(proxy, kSCPropNetProxiesSupplementalMatchDomain)) {
			// remove non-supplemental proxy
			CFArrayRemoveValueAtIndex(proxies, i);
			n_proxies--;
			continue;
		}

		newProxy = CFDictionaryCreateMutableCopy(NULL, 0, proxy);
		CFDictionaryRemoveValue(newProxy, PROXY_MATCH_ORDER_KEY);
		CFDictionaryRemoveValue(newProxy, ORDER_KEY);
		CFArraySetValueAtIndex(proxies, i, newProxy);
		CFRelease(newProxy);
	}

	// update the default proxy

	myDefault = CFDictionaryCreateMutableCopy(NULL,
						  0,
						  CFArrayGetValueAtIndex(proxies, 0));
	if (myOrderAdded && (n_proxies > 1)) {
		CFDictionaryRef	proxy;

		proxy = CFArrayGetValueAtIndex(proxies, 1);
		if (CFDictionaryContainsKey(proxy, kSCPropNetProxiesSupplementalMatchDomain)) {
			// if not a supplemental "default" proxy (a match domain name is
			// present)
			CFDictionaryRemoveValue(myDefault, PROXY_MATCH_ORDER_KEY);
		}
	}
	CFArraySetValueAtIndex(proxies, 0, myDefault);
	CFRelease(myDefault);

	// establish proxy configuration

	if (n_proxies > 0) {
		CFDictionaryRef		app_layer;
		CFDictionaryRef		scoped;
		CFArrayRef		serviceOrderAll;
		Boolean			skip		= FALSE;
		CFArrayRef		supplemental;

		proxy = CFArrayGetValueAtIndex(proxies, 0);
		if (!CFDictionaryContainsKey(proxy, kSCPropNetProxiesSupplementalMatchDomain)) {
			// if we have "a" default (non-supplemental) proxy
			newProxy = CFDictionaryCreateMutableCopy(NULL, 0, proxy);
			CFDictionaryRemoveValue(newProxy, kSCPropNetProxiesSupplementalMatchDomains);
			CFDictionaryRemoveValue(newProxy, kSCPropNetProxiesSupplementalMatchOrders);
			skip = TRUE;
		} else {
			newProxy = CFDictionaryCreateMutable(NULL,
							     0,
							     &kCFTypeDictionaryKeyCallBacks,
							     &kCFTypeDictionaryValueCallBacks);
		}

		serviceOrderAll = service_order_copy_all(services, serviceOrder);

		// collect (and add) any "supplemental" proxy configurations

		supplemental = copy_supplemental_proxies(proxies, skip);
		if (supplemental != NULL) {
			CFDictionarySetValue(newProxy, kSCPropNetProxiesSupplemental, supplemental);
			CFRelease(supplemental);
		}

		// collect (and add) any "scoped" proxy configurations

		scoped = copy_scoped_proxies(services, serviceOrderAll);
		if (scoped != NULL) {
			CFDictionarySetValue(newProxy, kSCPropNetProxiesScoped, scoped);
			CFRelease(scoped);
		}

		// collect (and add) any "services" based proxy configurations

		app_layer = copy_app_layer_vpn_proxies(services, serviceOrderAll, servicesInfo);
		if (app_layer != NULL) {
			CFDictionarySetValue(newProxy, kSCPropNetProxiesServices, app_layer);
			CFRelease(app_layer);
		}

		if (serviceOrderAll != NULL) {
			CFRelease(serviceOrderAll);
		}
	} else {
		newProxy = NULL;
	}

	CFRelease(proxies);
	return newProxy;
}
コード例 #17
0
ファイル: keychain.c プロジェクト: fcheung/keychain_c
static VALUE rb_keychain_find(int argc, VALUE *argv, VALUE self){

  VALUE kind;
  VALUE attributes;
  VALUE first_or_all;
  rb_scan_args(argc, argv, "2:", &first_or_all, &kind, &attributes);

  Check_Type(first_or_all, T_SYMBOL);
  Check_Type(kind, T_STRING);
  
  CFMutableDictionaryRef query = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);

  CFDictionarySetValue(query, kSecReturnAttributes, kCFBooleanTrue);
  CFDictionarySetValue(query, kSecReturnRef, kCFBooleanTrue);
  

  if(rb_to_id(first_or_all) == rb_intern("all")){
    CFDictionarySetValue(query, kSecMatchLimit, kSecMatchLimitAll);
  }

  rb_add_value_to_cf_dictionary(query, kSecClass, kind);


  if(!NIL_P(attributes)){
    Check_Type(attributes, T_HASH);
    VALUE rb_keychains = rb_hash_aref(attributes, ID2SYM(rb_intern("keychains")));
    if(!NIL_P(rb_keychains)){
      Check_Type(rb_keychains, T_ARRAY);
      CFMutableArrayRef searchArray = CFArrayCreateMutable(NULL, RARRAY_LEN(rb_keychains), &kCFTypeArrayCallBacks);
      for(int index=0; index < RARRAY_LEN(rb_keychains); index++){
        SecKeychainRef keychain = NULL;
        Data_Get_Struct(RARRAY_PTR(rb_keychains)[index], struct OpaqueSecKeychainRef, keychain);
        CFArrayAppendValue(searchArray, keychain);
      }
      CFDictionarySetValue(query, kSecMatchSearchList,searchArray);
      CFRelease(searchArray);
    }  

    VALUE limit = rb_hash_aref(attributes, ID2SYM(rb_intern("limit")));
    if(!NIL_P(limit)){
      Check_Type(limit, T_FIXNUM);
      long c_limit = FIX2LONG(limit);
      CFNumberRef cf_limit = CFNumberCreate(NULL, kCFNumberLongType, &c_limit);
      CFDictionarySetValue(query, kSecMatchLimit, cf_limit);
      CFRelease(cf_limit);
    }

    VALUE conditions = rb_hash_aref(attributes, ID2SYM(rb_intern("conditions")));
    
    if(!NIL_P(conditions)){
      Check_Type(conditions, T_HASH);
      VALUE rQuery = Data_Wrap_Struct(rb_cPointerWrapper, NULL, NULL, query);
      rb_block_call(conditions, rb_intern("each"), 0, NULL, RUBY_METHOD_FUNC(add_conditions_to_query), rQuery);
    }
  }

  CFDictionaryRef result;

  OSStatus status = SecItemCopyMatching(query, (CFTypeRef*)&result);
  CFRelease(query);

  VALUE rb_item = rb_ary_new2(0);

  switch(status){
    case errSecItemNotFound: 
      break;
    default:
    CheckOSStatusOrRaise(status);
    if(CFArrayGetTypeID() == CFGetTypeID(result)){
      CFArrayRef result_array = (CFArrayRef)result;
      for(CFIndex i = 0; i < CFArrayGetCount(result_array); i++){
        rb_ary_push(rb_item,rb_keychain_item_from_sec_dictionary(CFArrayGetValueAtIndex(result_array,i)));
      }
    }
    else{
      rb_ary_push(rb_item, rb_keychain_item_from_sec_dictionary(result));
    }
    CFRelease(result);
  }

  if(rb_to_id(first_or_all) == rb_intern("first")){
    return rb_ary_entry(rb_item,0);
  }
  else{
    return rb_item;
  }
}
コード例 #18
0
ファイル: SpeechRoutines.c プロジェクト: arnelh/Examples
Boolean AddCommands( SRRecognizer inSpeechRecognizer, SRLanguageModel inCommandsLangaugeModel, CFArrayRef inCommandNamesArray )
{

    // Dictionary keys for Commands Data property list
    #define	kCommandsDataPlacementHintKey			"PlacementHint"			// value type is: CFNumberRef
        #define	kPlacementHintWhereverNumValue			0
        #define	kPlacementHintProcessNumValue			1					// you must also provide the PSN using kCommandsDataProcessPSNHighKey & kCommandsDataProcessPSNLowKey
        #define	kPlacementHintFirstNumValue				2
        #define	kPlacementHintMiddleNumValue			3
        #define	kPlacementHintLastNumValue				4
    #define	kCommandsDataProcessPSNHighKey			"ProcessPSNHigh"		// value type is: CFNumberRef
    #define	kCommandsDataProcessPSNLowKey			"ProcessPSNLow"			// value type is: CFNumberRef
    #define	kCommandsDataDisplayOrderKey				"DisplayOrder"			// value type is: CFNumberRef  - the order in which recognizers from the same client process should be displayed.
    #define	kCommandsDataCmdInfoArrayKey				"CommandInfoArray"		// value type is: CFArrayRef of CFDictionaryRef values
        #define	kCommandInfoNameKey						"Text"
        #define	kCommandInfoChildrenKey					"Children"

    Boolean	successfullyAddCommands = false;
    
    if (inCommandNamesArray) {
    
        CFIndex	numOfCommands = CFArrayGetCount( inCommandNamesArray );
        CFMutableArrayRef	theSectionArray = CFArrayCreateMutable( NULL, 0, &kCFTypeArrayCallBacks );
        
        // Erase any existing commands in the language model before we begin adding the given list of commands
        if (SREmptyLanguageObject( inCommandsLangaugeModel ) == noErr && theSectionArray) {
        
            CFIndex	i;
            char 	theCSringBuffer[100];

            successfullyAddCommands = true;
            for (i = 0; i < numOfCommands; i++) {
               
                 CFStringRef	theCommandName = CFArrayGetValueAtIndex(inCommandNamesArray, i);
                if (theCommandName && CFStringGetCString( theCommandName, theCSringBuffer, 100, kCFStringEncodingMacRoman )) {
                    
                    if (SRAddText( inCommandsLangaugeModel, theCSringBuffer, strlen(theCSringBuffer), i) == noErr) {
    
                        CFStringRef 	keys[1];
                        CFTypeRef		values[1];
                        CFDictionaryRef theItemDict;
                        
                        keys[0] 	= CFSTR( kCommandInfoNameKey );
                        values[0] 	= theCommandName;
                        
                        // Make CDDictionary our keys and values.
                        theItemDict = CFDictionaryCreate(NULL, (const void **)keys, (const void **)values, 1, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
                        
                        // Add to command array
                        if (theItemDict) {
                            CFArrayAppendValue( theSectionArray, theItemDict );
                            CFRelease( theItemDict );  // We release our hold on the dictionary object and let the array own it now.
                        }
                        else
                            successfullyAddCommands = false;
                    }
                    else
                        successfullyAddCommands = false;
                    
                    if (! successfullyAddCommands)
                        break;
                }
            }
    
            //
            // Create the XML data that contains the commands to display and give this data to the
            // recognizer object to display in the Speech Commands window.
            //
            {
                CFIndex				numOfParams = 4;
                CFStringRef 		keys[numOfParams];
                CFTypeRef			values[numOfParams];
                CFDictionaryRef 	theItemDict;
                SInt32				placementHint = 1;	// 1 = show only when this app is front process
                ProcessSerialNumber	thisAppsPSN;
                
                thisAppsPSN.highLongOfPSN = 0;
                thisAppsPSN.lowLongOfPSN = 0;
        
                GetCurrentProcess( &thisAppsPSN );
            
                keys[0] 	= CFSTR( kCommandsDataPlacementHintKey );
                keys[1] 	= CFSTR( kCommandsDataCmdInfoArrayKey );
                keys[2] 	= CFSTR( kCommandsDataProcessPSNHighKey );
                keys[3] 	= CFSTR( kCommandsDataProcessPSNLowKey );
                values[0] 	= CFNumberCreate(NULL, kCFNumberSInt32Type, &placementHint);
                values[1] 	= theSectionArray;
                values[2] 	= CFNumberCreate(NULL, kCFNumberSInt32Type, &(thisAppsPSN.highLongOfPSN));
                values[3] 	= CFNumberCreate(NULL, kCFNumberSInt32Type, &(thisAppsPSN.lowLongOfPSN));
                    
                // Make CDDictionary of our keys and values.
                theItemDict = CFDictionaryCreate(NULL, (const void **)keys, (const void **)values, numOfParams, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
                if (theItemDict) {
                
                    // Convert CFDictionary object to XML representation
                    CFDataRef dictData = CFPropertyListCreateXMLData(NULL, theItemDict);
                    if (dictData) {

                    	// Set command list in our SRRecognizer object, causing the Speech Commands window to update.
                        (void)SRSetProperty (inSpeechRecognizer, 'cdpl', CFDataGetBytePtr(dictData), CFDataGetLength(dictData));
                        CFRelease( dictData );
                    }
                }
                
                // Release our hold on the dictionary object and let the array own it now.
                if (theItemDict)
                    CFRelease( theItemDict );
                
                // Release our values
                if (values[0])
                    CFRelease( values[0] );
                
                if (values[2])
                    CFRelease( values[2] );
                    
                if (values[3])
                    CFRelease( values[3] );
                    
                CFRelease( theSectionArray );
            }
        }

    }
    
    return successfullyAddCommands;
}
コード例 #19
0
__private_extern__
void
do_dictSetKey(int argc, char **argv)
{
	CFMutableArrayRef	array		= NULL;
	Boolean			doArray		= FALSE;
	Boolean			doBoolean	= FALSE;
	Boolean			doData		= FALSE;
	Boolean			doNumeric	= FALSE;
	CFStringRef		key;
	CFMutableDictionaryRef	newValue;
	CFTypeRef		val		= NULL;

	if (value == NULL) {
		SCPrint(TRUE, stdout, CFSTR("d.add: dictionary must be initialized.\n"));
		return;
	}

	if (!isA_CFDictionary(value)) {
		SCPrint(TRUE, stdout, CFSTR("d.add: data (fetched from configuration server) is not a dictionary.\n"));
		return;
	}

	key = CFStringCreateWithCString(NULL, argv[0], kCFStringEncodingUTF8);
	argv++; argc--;

	while (argc > 0) {
		if (strcmp(argv[0], "*") == 0) {
			/* if array requested */
			doArray = TRUE;
		} else if (strcmp(argv[0], "-") == 0) {
			/* if string values requested */
		} else if (strcmp(argv[0], "?") == 0) {
			/* if boolean values requested */
			doBoolean = TRUE;
		} else if (strcmp(argv[0], "%") == 0) {
			/* if [hex] data values requested */
			doData = TRUE;
		} else if (strcmp(argv[0], "#") == 0) {
			/* if numeric values requested */
			doNumeric = TRUE;
		} else {
			/* it's not a special flag */
			break;
		}
		argv++; argc--;
	}

	if (argc > 1) {
		doArray = TRUE;
	} else if (!doArray && (argc == 0)) {
		SCPrint(TRUE, stdout, CFSTR("d.add: no values.\n"));
		CFRelease(key);
		return;
	}

	if (doArray) {
		array = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
	}

	while (argc > 0) {
		if (doBoolean) {
			if         ((strcasecmp(argv[0], "true") == 0) ||
				    (strcasecmp(argv[0], "t"   ) == 0) ||
				    (strcasecmp(argv[0], "yes" ) == 0) ||
				    (strcasecmp(argv[0], "y"   ) == 0) ||
				    (strcmp    (argv[0], "1"   ) == 0)) {
				val = CFRetain(kCFBooleanTrue);
			} else if ((strcasecmp(argv[0], "false") == 0) ||
				   (strcasecmp(argv[0], "f"    ) == 0) ||
				   (strcasecmp(argv[0], "no"   ) == 0) ||
				   (strcasecmp(argv[0], "n"    ) == 0) ||
				   (strcmp    (argv[0], "0"    ) == 0)) {
				val = CFRetain(kCFBooleanFalse);
			} else {
				SCPrint(TRUE, stdout, CFSTR("d.add: invalid data.\n"));
				if (doArray) CFRelease(array);
				CFRelease(key);
				return;
			}
		} else if (doData) {
			uint8_t			*bytes;
			CFMutableDataRef	data;
			int			i;
			int			j;
			int			n;

			n = strlen(argv[0]);
			if ((n % 2) == 1) {
				SCPrint(TRUE, stdout, CFSTR("d.add: not enough bytes.\n"));
				if (doArray) CFRelease(array);
				CFRelease(key);
				return;
			}

			data = CFDataCreateMutable(NULL, (n / 2));
			CFDataSetLength(data, (n / 2));

			bytes = (uint8_t *)CFDataGetBytePtr(data);
			for (i = 0, j = 0; i < n; i += 2, j++) {
				unsigned long	byte;
				char		*end;
				char		str[3]	= { 0 };

				str[0] = argv[0][i];
				str[1] = argv[0][i + 1];
				errno = 0;
				byte = strtoul(str, &end, 16);
				if ((*end != '\0') || (errno != 0)) {
					CFRelease(data);
					data = NULL;
					break;
				}

				bytes[j] = byte;
			}

			if (data == NULL) {
				SCPrint(TRUE, stdout, CFSTR("d.add: invalid data.\n"));
				if (doArray) CFRelease(array);
				CFRelease(key);
				return;
			}

			val = data;
		} else if (doNumeric) {
			int	intValue;

			if (sscanf(argv[0], "%d", &intValue) == 1) {
				val = CFNumberCreate(NULL, kCFNumberIntType, &intValue);
			} else {
				SCPrint(TRUE, stdout, CFSTR("d.add: invalid data.\n"));
				if (doArray) CFRelease(array);
				CFRelease(key);
				return;
			}
		} else {
			val = (CFPropertyListRef)CFStringCreateWithCString(NULL, argv[0], kCFStringEncodingUTF8);
		}

		if (doArray) {
			CFArrayAppendValue(array, val);
			CFRelease(val);
			argv++; argc--;
		} else {
			break;
		}
	}

	newValue = CFDictionaryCreateMutableCopy(NULL, 0, value);
	if (doArray) {
		CFDictionarySetValue(newValue, key, array);
		CFRelease(array);
	} else if (val != NULL) {
		CFDictionarySetValue(newValue, key, val);
		CFRelease(val);
	}
	CFRelease(key);
	CFRelease(value);
	value = newValue;

	return;
}
コード例 #20
0
ファイル: AquaticPrime.c プロジェクト: samdeane/AquaticPrime
CFDictionaryRef APCreateDictionaryForLicenseData(CFDataRef data)
{
    if (!rsaKey->n || !rsaKey->e)
        return NULL;
    
    // Make the property list from the data
    CFStringRef errorString = NULL;
    CFPropertyListRef propertyList;
    propertyList = CFPropertyListCreateFromXMLData(kCFAllocatorDefault, data, kCFPropertyListMutableContainers, &errorString);
    if (errorString || CFDictionaryGetTypeID() != CFGetTypeID(propertyList) || !CFPropertyListIsValid(propertyList, kCFPropertyListXMLFormat_v1_0)) {
        if (propertyList)
            CFRelease(propertyList);
        return NULL;
    }
    
    // Load the signature
    CFMutableDictionaryRef licenseDictionary = (CFMutableDictionaryRef)propertyList;
    if (!CFDictionaryContainsKey(licenseDictionary, CFSTR("Signature"))) {
        CFRelease(licenseDictionary);
        return NULL;
    }
    
    CFDataRef sigData = CFDictionaryGetValue(licenseDictionary, CFSTR("Signature"));
	CFIndex sigDataLength = CFDataGetLength(sigData);
	UInt8 sigBytes[sigDataLength];
    CFDataGetBytes(sigData, CFRangeMake(0, sigDataLength), sigBytes);
    CFDictionaryRemoveValue(licenseDictionary, CFSTR("Signature"));
    
    // Decrypt the signature
	int checkDigestMaxSize = RSA_size(rsaKey)-11;
    unsigned char checkDigest[checkDigestMaxSize];
    if (RSA_public_decrypt((int) sigDataLength, sigBytes, checkDigest, rsaKey, RSA_PKCS1_PADDING) != SHA_DIGEST_LENGTH) {
        CFRelease(licenseDictionary);
        return NULL;
    }
    
    // Get the license hash
    CFMutableStringRef hashCheck = CFStringCreateMutable(kCFAllocatorDefault,0);
    int hashIndex;
    for (hashIndex = 0; hashIndex < SHA_DIGEST_LENGTH; hashIndex++)
        CFStringAppendFormat(hashCheck, nil, CFSTR("%02x"), checkDigest[hashIndex]);
    APSetHash(hashCheck);
    CFRelease(hashCheck);
    
    if (blacklist && (CFArrayContainsValue(blacklist, CFRangeMake(0, CFArrayGetCount(blacklist)), hash) == true))
        return NULL;
    
    // Get the number of elements
    CFIndex count = CFDictionaryGetCount(licenseDictionary);
    // Load the keys and build up the key array
    CFMutableArrayRef keyArray = CFArrayCreateMutable(kCFAllocatorDefault, count, NULL);
    CFStringRef keys[count];
    CFDictionaryGetKeysAndValues(licenseDictionary, (const void**)&keys, NULL);
    int i;
    for (i = 0; i < count; i++)
        CFArrayAppendValue(keyArray, keys[i]);
    
    // Sort the array
    int context = kCFCompareCaseInsensitive;
    CFArraySortValues(keyArray, CFRangeMake(0, count), (CFComparatorFunction)CFStringCompare, &context);
    
    // Setup up the hash context
    SHA_CTX ctx;
    SHA1_Init(&ctx);
    // Convert into UTF8 strings
    for (i = 0; i < count; i++)
    {
        char *valueBytes;
        CFIndex valueLengthAsUTF8;
        CFStringRef key = CFArrayGetValueAtIndex(keyArray, i);
        CFStringRef value = CFDictionaryGetValue(licenseDictionary, key);
        
        // Account for the null terminator
        valueLengthAsUTF8 = CFStringGetMaximumSizeForEncoding(CFStringGetLength(value), kCFStringEncodingUTF8) + 1;
        valueBytes = (char *)malloc(valueLengthAsUTF8);
        CFStringGetCString(value, valueBytes, valueLengthAsUTF8, kCFStringEncodingUTF8);
        SHA1_Update(&ctx, valueBytes, strlen(valueBytes));
        free(valueBytes);
    }
    unsigned char digest[SHA_DIGEST_LENGTH];
    SHA1_Final(digest, &ctx);
    
    if (keyArray != NULL)
        CFRelease(keyArray);
    
    // Check if the signature is a match    
    for (i = 0; i < SHA_DIGEST_LENGTH; i++) {
        if (checkDigest[i] ^ digest[i]) {
            CFRelease(licenseDictionary);
            return NULL;
        }
    }
    
    // If it's a match, we return the dictionary; otherwise, we never reach this
    return licenseDictionary;
}
コード例 #21
0
void *_ykusb_open_device(int vendor_id, int *product_ids, size_t pids_len)
{
	void *yk = NULL;

	int rc = YK_ENOKEY;

	size_t i;

	IOHIDManagerSetDeviceMatchingMultiple( ykosxManager, NULL );

	CFSetRef devSet = IOHIDManagerCopyDevices( ykosxManager );

	if ( devSet ) {
		CFMutableArrayRef array = CFArrayCreateMutable( kCFAllocatorDefault, 0, NULL );

		CFSetApplyFunction( devSet, _ykosx_CopyToCFArray, array );

		CFIndex cnt = CFArrayGetCount( array );

		CFIndex i;

		for(i = 0; i < cnt; i++) {
			IOHIDDeviceRef dev = (IOHIDDeviceRef)CFArrayGetValueAtIndex( array, i );
			long devVendorId = _ykosx_getIntProperty( dev, CFSTR( kIOHIDVendorIDKey ));
			if(devVendorId == vendor_id) {
				long devProductId = _ykosx_getIntProperty( dev, CFSTR( kIOHIDProductIDKey ));
				size_t j;
				for(j = 0; j < pids_len; j++) {
					if(product_ids[j] == devProductId) {
						if(yk == NULL) {
							yk = dev;
							break;
						} else {
							rc = YK_EMORETHANONE;
							break;
						}
					}
				}
			}
			if(rc == YK_EMORETHANONE) {
				yk = NULL;
				break;
			}
		}

		if(rc != YK_EMORETHANONE) {
			rc = YK_ENOKEY;
		}

		/* this is a workaround for a memory leak in IOHIDManagerCopyDevices() in 10.8 */
		IOHIDManagerScheduleWithRunLoop( ykosxManager, CFRunLoopGetCurrent( ), kCFRunLoopDefaultMode );
		IOHIDManagerUnscheduleFromRunLoop( ykosxManager, CFRunLoopGetCurrent( ), kCFRunLoopDefaultMode );

		CFRelease( array );
		CFRelease( devSet );
	}

	if (yk) {
		CFRetain(yk);
		_ykusb_IOReturn = IOHIDDeviceOpen( yk, 0L );

		if ( _ykusb_IOReturn != kIOReturnSuccess ) {
			CFRelease(yk);
			rc = YK_EUSBERR;
			goto error;
		}

		return yk;
	}

error:
	yk_errno = rc;
	return 0;
}
コード例 #22
0
static void SecPathBuilderInit(SecPathBuilderRef builder,
	CFArrayRef certificates, CFArrayRef anchors, bool anchorsOnly,
    CFArrayRef policies, CFAbsoluteTime verifyTime,
    SecPathBuilderCompleted completed, const void *context) {
    secdebug("alloc", "%p", builder);
	CFAllocatorRef allocator = kCFAllocatorDefault;

	builder->nextParentSource = 1;
	builder->considerPartials = false;
    builder->canAccessNetwork = true;

    builder->anchorSources = CFArrayCreateMutable(allocator, 0, NULL);
    builder->parentSources = CFArrayCreateMutable(allocator, 0, NULL);
    builder->allPaths = CFSetCreateMutable(allocator, 0,
		&kCFTypeSetCallBacks);

    builder->partialPaths = CFArrayCreateMutable(allocator, 0, NULL);
    builder->rejectedPaths = CFArrayCreateMutable(allocator, 0, NULL);
    builder->candidatePaths = CFArrayCreateMutable(allocator, 0, NULL);
    builder->partialIX = 0;

    /* Init the policy verification context. */
    SecPVCInit(&builder->path, builder, policies, verifyTime);
	builder->bestPath = NULL;
	builder->bestPathIsEV = false;
	builder->rejectScore = 0;

	/* Let's create all the certificate sources we might want to use. */
	builder->certificateSource =
		SecMemoryCertificateSourceCreate(certificates);
	if (anchors)
		builder->anchorSource = SecMemoryCertificateSourceCreate(anchors);
	else
		builder->anchorSource = NULL;

	/* We always search certificateSource for parents since it includes the
	   leaf itself and it might be self signed. */
	CFArrayAppendValue(builder->parentSources, builder->certificateSource);
	if (builder->anchorSource) {
		CFArrayAppendValue(builder->anchorSources, builder->anchorSource);
	}
	CFArrayAppendValue(builder->parentSources, &kSecItemCertificateSource);
    if (anchorsOnly) {
        /* Add the system and user anchor certificate db to the search list
           if we don't explicitly trust them. */
        CFArrayAppendValue(builder->parentSources, &kSecSystemAnchorSource);
        CFArrayAppendValue(builder->parentSources, &kSecUserAnchorSource);
    } else {
        /* Only add the system and user anchor certificate db to the
           anchorSources if we are supposed to trust them. */
        CFArrayAppendValue(builder->anchorSources, &kSecSystemAnchorSource);
        CFArrayAppendValue(builder->anchorSources, &kSecUserAnchorSource);
    }
    CFArrayAppendValue(builder->parentSources, &kSecCAIssuerSource);

	/* Now let's get the leaf cert and turn it into a path. */
	SecCertificateRef leaf =
		(SecCertificateRef)CFArrayGetValueAtIndex(certificates, 0);
	SecCertificatePathRef path = SecCertificatePathCreate(NULL, leaf);
	CFSetAddValue(builder->allPaths, path);
	CFArrayAppendValue(builder->partialPaths, path);
    if (SecPathBuilderIsAnchor(builder, leaf)) {
        SecCertificatePathSetIsAnchored(path);
        CFArrayAppendValue(builder->candidatePaths, path);
    }
    SecPathBuilderLeafCertificateChecks(builder, path);
	CFRelease(path);

    builder->activations = 0;
    builder->state = SecPathBuilderGetNext;
    builder->completed = completed;
    builder->context = context;
}
コード例 #23
0
int
main(int argc, char **argv)
{
	CFDictionaryRef		entities;
	CFStringRef		key;
	CFDictionaryRef		newProxy	= NULL;
	CFStringRef		pattern;
	CFMutableArrayRef	patterns;
	CFStringRef		primary		= NULL;
	CFMutableDictionaryRef	primary_proxy	= NULL;
	CFArrayRef		service_order	= NULL;
	CFMutableDictionaryRef	service_state_dict;
	CFDictionaryRef		setup_global_ipv4;
	CFDictionaryRef		state_global_ipv4;
	SCDynamicStoreRef	store;

	_sc_log     = FALSE;
	_sc_verbose = (argc > 1) ? TRUE : FALSE;

	store = SCDynamicStoreCreate(NULL, CFSTR("TEST"), NULL, NULL);

	// get IPv4, IPv6, and Proxies entities
	patterns = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
	pattern = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL,
							      kSCDynamicStoreDomainState,
							      kSCCompAnyRegex,
							      kSCEntNetIPv4);
	CFArrayAppendValue(patterns, pattern);
	CFRelease(pattern);
	pattern = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL,
							      kSCDynamicStoreDomainState,
							      kSCCompAnyRegex,
							      kSCEntNetIPv6);
	CFArrayAppendValue(patterns, pattern);
	CFRelease(pattern);
	pattern = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL,
							      kSCDynamicStoreDomainSetup,
							      kSCCompAnyRegex,
							      kSCEntNetProxies);
	CFArrayAppendValue(patterns, pattern);
	CFRelease(pattern);
	pattern = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL,
							      kSCDynamicStoreDomainState,
							      kSCCompAnyRegex,
							      kSCEntNetProxies);
	CFArrayAppendValue(patterns, pattern);
	CFRelease(pattern);
	entities = SCDynamicStoreCopyMultiple(store, NULL, patterns);
	CFRelease(patterns);

	service_state_dict = CFDictionaryCreateMutable(NULL,
						       0,
						       &kCFTypeDictionaryKeyCallBacks,
						       &kCFTypeDictionaryValueCallBacks);
	CFDictionaryApplyFunction(entities, split, service_state_dict);
	CFRelease(entities);

	// get primary service ID
	key = SCDynamicStoreKeyCreateNetworkGlobalEntity(NULL,
							 kSCDynamicStoreDomainState,
							 kSCEntNetIPv4);
	state_global_ipv4 = SCDynamicStoreCopyValue(store, key);
	CFRelease(key);
	if (state_global_ipv4 != NULL) {
		primary = CFDictionaryGetValue(state_global_ipv4, kSCDynamicStorePropNetPrimaryService);
		if (primary != NULL) {
			CFDictionaryRef	service_dict;

			// get proxy configuration for primary service
			service_dict = CFDictionaryGetValue(service_state_dict, primary);
			if (service_dict != NULL) {
				CFDictionaryRef	service_proxy;

				service_proxy = CFDictionaryGetValue(service_dict, kSCEntNetProxies);
				if (service_proxy != NULL) {
					primary_proxy = CFDictionaryCreateMutableCopy(NULL, 0, service_proxy);
					CFDictionaryRemoveValue(primary_proxy, kSCPropInterfaceName);
				}
			}
		}
	}

	// get serviceOrder
	key = SCDynamicStoreKeyCreateNetworkGlobalEntity(NULL,
							 kSCDynamicStoreDomainSetup,
							 kSCEntNetIPv4);
	setup_global_ipv4 = SCDynamicStoreCopyValue(store, key);
	CFRelease(key);
	if (setup_global_ipv4 != NULL) {
		service_order = CFDictionaryGetValue(setup_global_ipv4, kSCPropNetServiceOrder);
	}

	// update proxy configuration
	proxy_configuration_init(CFBundleGetMainBundle());
	newProxy = proxy_configuration_update(primary_proxy,
					      service_state_dict,
					      service_order,
					      NULL);
	if (newProxy != NULL) {
		SCPrint(TRUE, stdout, CFSTR("%@\n"), newProxy);
		CFRelease(newProxy);
	}

	// cleanup
	if (setup_global_ipv4 != NULL)	CFRelease(setup_global_ipv4);
	if (state_global_ipv4 != NULL)	CFRelease(state_global_ipv4);
	CFRelease(service_state_dict);
	CFRelease(store);

	/* not reached */
	exit(0);
	return 0;
}
コード例 #24
0
ファイル: abquery.c プロジェクト: theiostream/utilities
int main(int argc, char **argv) {
	int i;
	
	if (argc <= 1) {
		// TODO: Man page?
		fprintf(stderr, "Usage: abquery <name>\n"
						"The <name> parameter accepts similarities: \"dan fer\" matches \"Däniel Ferrêira\".\n"
						"Details on /usr/share/tiutils/abquery-ex.txt\n");
		return 1;
	}
	
	CFMutableArrayRef args = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
	for (i=1; i<argc; i++) {
		CFStringRef str = CFStringCreateWithCString(NULL, argv[i], kCFStringEncodingUTF8);
		CFArrayAppendValue(args, str);
		CFRelease(str);
	}
	
	ABAddressBookRef ab = ABAddressBookCreate();
	CFIndex count = ABAddressBookGetPersonCount(ab);
	if (count == 0) {
		CFRelease(ab);
		
		puts("No entries on the address book database.");
		return 0;
	}
	else
		printf("Total name matches: %lu\n", count);
	
	CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(ab);
	if (!people || CFArrayGetCount(people)==0) {
		if (people) CFRelease(people);
		CFRelease(ab);
		
		fprintf(stderr, "[Error] Inconsistency: ABAddressBookCopyArrayOfAllPeople returned NULL or contains no people, but address book people count is bigger than zero.\n");
		return 2;
	}
	
	for (i=0; i<count; i++) {
		ABRecordRef dude = (ABRecordRef)CFArrayGetValueAtIndex(people, i);
		if (!dude) {
			fprintf(stderr, "[Error] Null entry at index %d. Skipping.\n", i);
			continue;
		}
		
		CFStringRef name = ABRecordCopyCompositeName(dude);
		if (!name || CFStringGetLength(name)==0)
			continue;
		
		Boolean found = false;
		CFIndex j, cnt=CFArrayGetCount(args);
		for (j=0; j<cnt; j++) {
			CFStringRef str = (CFStringRef)CFArrayGetValueAtIndex(args, j);
			found = CFStringFindWithOptions(name, str, CFRangeMake(0, CFStringGetLength(name)), kCFCompareCaseInsensitive|kCFCompareDiacriticInsensitive, NULL);
			
			if (!found) break;
		}
		
		if (found) {
			// NOTE: We can have a lot more here.
			// But for now let's stick with what Erica did originally
			char nm[1024];
			CFStringGetCString(name, nm, sizeof(nm), kCFStringEncodingUTF8);
			printf("%s\n", nm);
			printmv(dude, kABPersonPhoneProperty);
			printmv(dude, kABPersonEmailProperty);
		}
	}
	
	CFRelease(people);
	CFRelease(ab);
	
	return 0;
}
コード例 #25
0
/* Lately, dirSpec appears to be (rightfully) unused. */
__private_extern__ CFMutableArrayRef _CFContentsOfDirectory(CFAllocatorRef alloc, char *dirPath, void *dirSpec, CFURLRef dirURL, CFStringRef matchingAbstractType) {
    CFMutableArrayRef files = NULL;
    Boolean releaseBase = false;
    CFIndex pathLength = dirPath ? strlen(dirPath) : 0;
    // MF:!!! Need to use four-letter type codes where appropriate.
    CFStringRef extension = (matchingAbstractType ? _CFCopyExtensionForAbstractType(matchingAbstractType) : NULL);
    CFIndex targetExtLen = (extension ? CFStringGetLength(extension) : 0);

#if DEPLOYMENT_TARGET_WINDOWS
    // This is a replacement for 'dirent' below, and also uses wchar_t to support unicode paths
    wchar_t extBuff[CFMaxPathSize];
    int extBuffInteriorDotCount = 0; //people insist on using extensions like ".trace.plist", so we need to know how many dots back to look :(
    
    if (targetExtLen > 0) {
        CFIndex usedBytes = 0;
        CFStringGetBytes(extension, CFRangeMake(0, targetExtLen), kCFStringEncodingUTF16, 0, false, (uint8_t *)extBuff, CFMaxPathLength, &usedBytes);
        targetExtLen = usedBytes / sizeof(wchar_t);
        extBuff[targetExtLen] = '\0';
        wchar_t *extBuffStr = (wchar_t *)extBuff;
        if (extBuffStr[0] == '.')
            extBuffStr++; //skip the first dot, it's legitimate to have ".plist" for example
        
        wchar_t *extBuffDotPtr = extBuffStr;
        while ((extBuffDotPtr = wcschr(extBuffStr, '.'))) { //find the next . in the extension...
            extBuffInteriorDotCount++;
            extBuffStr = extBuffDotPtr + 1;
        }
    }
    
    wchar_t pathBuf[CFMaxPathSize];
    
    if (!dirPath) {
        if (!_CFURLGetWideFileSystemRepresentation(dirURL, true, pathBuf, CFMaxPathLength)) {
            if (extension) CFRelease(extension);
            return NULL;
        }
        
        pathLength = wcslen(pathBuf);

    } else {
        // Convert dirPath to a wide representation and put it into our pathBuf
        // Get the real length of the string in UTF16 characters
        CFStringRef dirPathStr = CFStringCreateWithCString(kCFAllocatorSystemDefault, dirPath, kCFStringEncodingUTF8);
        CFIndex strLen = CFStringGetLength(dirPathStr);
        
        // Copy the string into the buffer and terminate
        CFStringGetCharacters(dirPathStr, CFRangeMake(0, strLen), (UniChar *)pathBuf);
        pathBuf[strLen] = 0;
        
        CFRelease(dirPathStr);
    }
    
    WIN32_FIND_DATAW  file;
    HANDLE handle;
    
    if (pathLength + 2 >= CFMaxPathLength) {
        if (extension) {
            CFRelease(extension);
        }
        return NULL;
    }

    pathBuf[pathLength] = '\\';
    pathBuf[pathLength + 1] = '*';
    pathBuf[pathLength + 2] = '\0';
    handle = FindFirstFileW(pathBuf, (LPWIN32_FIND_DATAW)&file);
    if (INVALID_HANDLE_VALUE == handle) {
        pathBuf[pathLength] = '\0';
        if (extension) {
            CFRelease(extension);
        }
        return NULL;
    }

    files = CFArrayCreateMutable(alloc, 0, &kCFTypeArrayCallBacks);

    do {
        CFURLRef fileURL;
        CFIndex namelen = wcslen(file.cFileName);
        if (file.cFileName[0] == '.' && (namelen == 1 || (namelen == 2  && file.cFileName[1] == '.'))) {
            continue;
        }

        if (targetExtLen > namelen) continue;    // if the extension is the same length or longer than the name, it can't possibly match.

        if (targetExtLen > 0) {
	    if (file.cFileName[namelen - 1] == '.') continue; //filename ends with a dot, no extension
	    
	    wchar_t *fileExt = NULL;
            
            if (extBuffInteriorDotCount == 0) {
                fileExt = wcsrchr(file.cFileName, '.');
            } else { //find the Nth occurrence of . from the end of the string, to handle ".foo.bar"
                wchar_t *save = file.cFileName;
                while ((save = wcschr(save, '.')) && !fileExt) {
                    wchar_t *temp = save;
                    int moreDots = 0;
                    while ((temp = wcschr(temp, '.'))) {
                        if (++moreDots == extBuffInteriorDotCount) break;
                    }
                    if (moreDots == extBuffInteriorDotCount) {
                        fileExt = save;
                    }
                }
            }
	    
	    if (!fileExt) continue; //no extension
	    
	    if (((const wchar_t *)extBuff)[0] != '.')
		fileExt++; //omit the dot if the target file extension omits the dot
	    
	    CFIndex fileExtLen = wcslen(fileExt);
	    
	    //if the extensions are different lengths, they can't possibly match
	    if (fileExtLen != targetExtLen) continue;
	    
            // Check to see if it matches the extension we're looking for.
            if (_wcsicmp(fileExt, (const wchar_t *)extBuff) != 0) {
                continue;
            }
        }
	if (dirURL == NULL) {
	    CFStringRef dirURLStr = CFStringCreateWithBytes(alloc, (const uint8_t *)pathBuf, pathLength * sizeof(wchar_t), kCFStringEncodingUTF16, NO);
	    dirURL = CFURLCreateWithFileSystemPath(alloc, dirURLStr, kCFURLWindowsPathStyle, true);
	    CFRelease(dirURLStr);
            releaseBase = true;
        }
        // MF:!!! What about the trailing slash?
        CFStringRef fileURLStr = CFStringCreateWithBytes(alloc, (const uint8_t *)file.cFileName, namelen * sizeof(wchar_t), kCFStringEncodingUTF16, NO);
        fileURL = CFURLCreateWithFileSystemPathRelativeToBase(alloc, fileURLStr, kCFURLWindowsPathStyle, (file.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? true : false, dirURL);
        CFArrayAppendValue(files, fileURL);
        CFRelease(fileURL);
        CFRelease(fileURLStr);
    } while (FindNextFileW(handle, &file));
    FindClose(handle);
    pathBuf[pathLength] = '\0';

#elif DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI || DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD
    uint8_t extBuff[CFMaxPathSize];
    int extBuffInteriorDotCount = 0; //people insist on using extensions like ".trace.plist", so we need to know how many dots back to look :(
    
    if (targetExtLen > 0) {
        CFStringGetBytes(extension, CFRangeMake(0, targetExtLen), CFStringFileSystemEncoding(), 0, false, extBuff, CFMaxPathLength, &targetExtLen);
        extBuff[targetExtLen] = '\0';
        char *extBuffStr = (char *)extBuff;
        if (extBuffStr[0] == '.')
            extBuffStr++; //skip the first dot, it's legitimate to have ".plist" for example
        
        char *extBuffDotPtr = extBuffStr;
        while ((extBuffDotPtr = strchr(extBuffStr, '.'))) { //find the next . in the extension...
            extBuffInteriorDotCount++;
            extBuffStr = extBuffDotPtr + 1;
        }
    }
    
    uint8_t pathBuf[CFMaxPathSize];
    
    if (!dirPath) {
        if (!CFURLGetFileSystemRepresentation(dirURL, true, pathBuf, CFMaxPathLength)) {
            if (extension) CFRelease(extension);
            return NULL;
        } else {
            dirPath = (char *)pathBuf;
            pathLength = strlen(dirPath);
        }
    }
    
    struct dirent buffer;
    struct dirent *dp;
    int err;
   
    int no_hang_fd = __CFProphylacticAutofsAccess ? open("/dev/autofs_nowait", 0) : -1;
 
    DIR *dirp = opendir(dirPath);
    if (!dirp) {
        if (extension) {
            CFRelease(extension);
        }
	if (-1 != no_hang_fd) close(no_hang_fd);
        return NULL;
        // raiseErrno("opendir", path);
    }
    files = CFArrayCreateMutable(alloc, 0, & kCFTypeArrayCallBacks);

    while((0 == readdir_r(dirp, &buffer, &dp)) && dp) {
        CFURLRef fileURL;
	unsigned namelen = strlen(dp->d_name);

        // skip . & ..; they cause descenders to go berserk
	if (dp->d_name[0] == '.' && (namelen == 1 || (namelen == 2 && dp->d_name[1] == '.'))) {
            continue;
        }
        
        if (targetExtLen > namelen) continue;    // if the extension is the same length or longer than the name, it can't possibly match.
                
        if (targetExtLen > 0) {
	    if (dp->d_name[namelen - 1] == '.') continue; //filename ends with a dot, no extension
	      
            char *fileExt = NULL;
            if (extBuffInteriorDotCount == 0) {
                fileExt = strrchr(dp->d_name, '.'); 
            } else { //find the Nth occurrence of . from the end of the string, to handle ".foo.bar"
                char *save = dp->d_name;
                while ((save = strchr(save, '.')) && !fileExt) {
                    char *temp = save;
                    int moreDots = 0;
                    while ((temp = strchr(temp, '.'))) {
                        if (++moreDots == extBuffInteriorDotCount) break;
                    }
                    if (moreDots == extBuffInteriorDotCount) {
                        fileExt = save;
                    }
                }
            }
	    
	    if (!fileExt) continue; //no extension
	    
	    if (((char *)extBuff)[0] != '.')
		fileExt++; //omit the dot if the target extension omits the dot; safe, because we checked to make sure it isn't the last character just before
	    
	    size_t fileExtLen = strlen(fileExt);
	    
	    //if the extensions are different lengths, they can't possibly match
	    if (fileExtLen != targetExtLen) continue;
	    
	    // Check to see if it matches the extension we're looking for.
            if (strncmp(fileExt, (char *)extBuff, fileExtLen) != 0) {
                continue;
            }
        }
        if (dirURL == NULL) {
            dirURL = CFURLCreateFromFileSystemRepresentation(alloc, (uint8_t *)dirPath, pathLength, true);
            releaseBase = true;
        }
        if (dp->d_type == DT_DIR || dp->d_type == DT_UNKNOWN || dp->d_type == DT_LNK || dp->d_type == DT_WHT) {
            Boolean isDir = (dp->d_type == DT_DIR);
            if (!isDir) {
                // Ugh; must stat.
                char subdirPath[CFMaxPathLength];
                struct statinfo statBuf;
                strlcpy(subdirPath, dirPath, sizeof(subdirPath));
                strlcat(subdirPath, "/", sizeof(subdirPath));
                strlcat(subdirPath, dp->d_name, sizeof(subdirPath));
                if (stat(subdirPath, &statBuf) == 0) {
                    isDir = ((statBuf.st_mode & S_IFMT) == S_IFDIR);
                }
            }
#if DEPLOYMENT_TARGET_LINUX
            fileURL = CFURLCreateFromFileSystemRepresentationRelativeToBase(alloc, (uint8_t *)dp->d_name, namelen, isDir, dirURL);
#else
            fileURL = CFURLCreateFromFileSystemRepresentationRelativeToBase(alloc, (uint8_t *)dp->d_name, dp->d_namlen, isDir, dirURL);
#endif
        } else {
#if DEPLOYMENT_TARGET_LINUX
            fileURL = CFURLCreateFromFileSystemRepresentationRelativeToBase (alloc, (uint8_t *)dp->d_name, namelen, false, dirURL);
#else
            fileURL = CFURLCreateFromFileSystemRepresentationRelativeToBase (alloc, (uint8_t *)dp->d_name, dp->d_namlen, false, dirURL);
#endif
        }
        CFArrayAppendValue(files, fileURL);
        CFRelease(fileURL);
    }
    err = closedir(dirp);
    if (-1 != no_hang_fd) close(no_hang_fd);
    if (err != 0) {
        CFRelease(files);
        if (releaseBase) {
            CFRelease(dirURL);
        }
        if (extension) {
            CFRelease(extension);
        }
        return NULL;
    }
    
#else
    
#error _CFContentsOfDirectory() unknown architecture, not implemented
    
#endif

    if (extension) {
        CFRelease(extension);
    }
    if (releaseBase) {
        CFRelease(dirURL);
    }
    return files;
}
コード例 #26
0
ファイル: Joystick.cpp プロジェクト: bhuman/BHumanCodeRelease
bool Joystick::init()
{
  SYNC;
  if(!p->hidManager)
  {
    VERIFY(p->hidManager = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone));
    IOHIDManagerSetDeviceMatching((IOHIDManagerRef) p->hidManager, 0);
    IOHIDManagerOpen((IOHIDManagerRef) p->hidManager, kIOHIDOptionsTypeNone);
    p->nextDevice = 0;
  }

  CFSetRef copyOfDevices = IOHIDManagerCopyDevices((IOHIDManagerRef) p->hidManager);
  CFMutableArrayRef devArray = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
  CFSetApplyFunction(copyOfDevices, Joystick::Private::copyCallBack, (void*) devArray);
  CFRelease(copyOfDevices);

  while(!p->deviceId && p->nextDevice < (unsigned) CFArrayGetCount(devArray))
  {
    p->deviceId = CFArrayGetValueAtIndex(devArray, p->nextDevice++);
    if(p->deviceId)
    {
      CFArrayRef elemAry = IOHIDDeviceCopyMatchingElements((IOHIDDeviceRef) p->deviceId, 0, 0);
      bool isJoystick = false;
      for(int i = 0; !isJoystick && i < (int) CFArrayGetCount(elemAry); ++i)
      {
        IOHIDElementRef elem = (IOHIDElementRef) CFArrayGetValueAtIndex(elemAry, i);
        isJoystick = IOHIDElementGetUsagePage(elem) == kHIDPage_GenericDesktop &&
                     (IOHIDElementGetUsage(elem) == kHIDUsage_GD_Joystick ||
                      IOHIDElementGetUsage(elem) == kHIDUsage_GD_GamePad);
      }
      if(isJoystick)
      {
        CFRetain((IOHIDDeviceRef) p->deviceId);
        ++(p->usedJoysticks);
        for(int i = 0; i < (int) CFArrayGetCount(elemAry); ++i)
        {
          IOHIDElementRef elem = (IOHIDElementRef) CFArrayGetValueAtIndex(elemAry, i);
          IOHIDElementType elemType = IOHIDElementGetType(elem);

          if(elemType == kIOHIDElementTypeInput_Misc ||
             elemType == kIOHIDElementTypeInput_Button ||
             elemType == kIOHIDElementTypeInput_Axis ||
             elemType == kIOHIDElementTypeInput_ScanCodes)
          {
            if(IOHIDElementGetUsagePage(elem) == kHIDPage_GenericDesktop)
              switch(IOHIDElementGetUsage(elem))
              {
                case kHIDUsage_GD_X:
                case kHIDUsage_GD_Y:
                case kHIDUsage_GD_Z:
                case kHIDUsage_GD_Rx:
                case kHIDUsage_GD_Ry:
                case kHIDUsage_GD_Rz:
                {
                  CFRetain(elem);
                  int axis = IOHIDElementGetUsage(elem) - kHIDUsage_GD_X;
                  p->axisIds[axis] = elem;
                  p->axisMin[axis] = (int) IOHIDElementGetLogicalMin(elem);
                  p->axisMax[axis] = (int) IOHIDElementGetLogicalMax(elem);
                  break;
                }
                case kHIDUsage_GD_Hatswitch:
                  CFRetain(elem);
                  p->hatId = elem;
                  p->axisMin[6] = p->axisMin[7] = -1;
                  p->axisMax[6] = p->axisMax[7] = 1;
                  break;
              }
            else if(IOHIDElementGetUsagePage(elem) == kHIDPage_Button)
            {
              int button = IOHIDElementGetUsage(elem) - 1;
              if(button >= 0 && button < numOfButtons)
              {
                CFRetain(elem);
                p->buttonIds[button] = elem;
              }
            }
          }
        }
      }
      else
        p->deviceId = 0;
      CFRelease(elemAry);
    }
  }

  CFRelease(devArray);

  return p->deviceId != 0;
}
コード例 #27
0
ファイル: curtains.c プロジェクト: JeremyAgost/curtains
CGError lockScreen(CFStringRef lockMessage, CGSSessionID *outSession)
{
	CFDictionaryRef dict;
	CFNumberRef number;
	CGSSessionID currentSession, lockSession;
	CFStringRef lockCmd, currentSessionStr;
	size_t lockMsgLen;
	char *lockMsgC;
	CFMutableStringRef lockMsgHex;
	CFMutableArrayRef lockCmdArgs;

	if (lockMessage == NULL)
		lockMessage = CFSTR("");

	lockMsgLen = CFStringGetLength(lockMessage);
	lockMsgC = malloc(sizeof(char) * (lockMsgLen + 1));
	CFStringGetCString(lockMessage,
	                   lockMsgC,
	                   lockMsgLen + 1,
	                   kCFStringEncodingUTF8);
	lockMsgHex = CFStringCreateMutable(NULL, lockMsgLen * 2);
	for (int i = 0; i < lockMsgLen; i++) {
		CFStringAppendFormat(lockMsgHex,
		                     NULL,
		                     CFSTR("%02x"),
		                     lockMsgC[i]);
	}
	free(lockMsgC);

	dict = CGSCopyCurrentSessionDictionary();
	number = (CFNumberRef)
	         CFDictionaryGetValue(dict, CFSTR("kCGSSessionIDKey"));
	CFNumberGetValue(number, kCFNumberIntType, &currentSession);

	lockCmd = CFSTR("/System/Library/CoreServices/RemoteManagement"
	                "/AppleVNCServer.bundle/Contents/Support"
	                "/LockScreen.app/Contents/MacOS/LockScreen");
	lockCmdArgs = CFArrayCreateMutable(NULL, 0, NULL);
	CFArrayAppendValue(lockCmdArgs, lockCmd);
	CFArrayAppendValue(lockCmdArgs, CFSTR("-session"));
	currentSessionStr =
		CFStringCreateWithFormat(NULL,
		                         NULL,
		                         CFSTR("%i"),
		                         currentSession);
	CFArrayAppendValue(lockCmdArgs, currentSessionStr);
	CFArrayAppendValue(lockCmdArgs, CFSTR("-msgHex"));
	CFArrayAppendValue(lockCmdArgs, lockMsgHex);

	CGSSessionCreateSessionIDWithOptions(lockCmd,
	                                     lockCmdArgs,
	                                     3,
	                                     &lockSession);
	
	if (outSession)
		*outSession = lockSession;

	CFRelease(currentSessionStr);
	CFRelease(lockCmdArgs);
	CFRelease(lockCmd);
	CFRelease(dict);
	CFRelease(lockMsgHex);

	return 0;
}
コード例 #28
0
ファイル: smb-configuration.c プロジェクト: carriercomm/osx-2
__private_extern__
void
load_smb_configuration(Boolean verbose)
{
	CFStringRef		key;
	CFMutableArrayRef	keys		= NULL;
	dispatch_block_t	notify_block;
	Boolean			ok;
	CFMutableArrayRef	patterns	= NULL;
	uint32_t		status;

	/* initialize a few globals */

	store = SCDynamicStoreCreate(NULL, CFSTR("smb-configuration"), configuration_changed, NULL);
	if (store == NULL) {
		my_log(LOG_ERR,
		       "SCDynamicStoreCreate() failed: %s",
		       SCErrorString(SCError()));
		goto error;
	}

	/* establish notification keys and patterns */

	keys     = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
	patterns = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);

	/* ...watch for SMB configuration changes */
	key = SCDynamicStoreKeyCreateNetworkGlobalEntity(NULL,
							 kSCDynamicStoreDomainState,
							 kSCEntNetSMB);
	CFArrayAppendValue(keys, key);
	CFRelease(key);

	/* ...watch for ComputerName changes */
	key = SCDynamicStoreKeyCreateComputerName(NULL);
	CFArrayAppendValue(keys, key);
	CFRelease(key);

	/* ...watch for local (multicast DNS) hostname changes */
	key = SCDynamicStoreKeyCreateHostNames(NULL);
	CFArrayAppendValue(keys, key);
	CFRelease(key);

	/* register the keys/patterns */
	ok = SCDynamicStoreSetNotificationKeys(store, keys, patterns);
	CFRelease(keys);
	CFRelease(patterns);
	if (!ok) {
		my_log(LOG_ERR,
		       "SCDynamicStoreSetNotificationKeys() failed: %s",
		       SCErrorString(SCError()));
		goto error;
	}

	rl = CFRunLoopGetCurrent();
	rls = SCDynamicStoreCreateRunLoopSource(NULL, store, 0);
	if (rls == NULL) {
		my_log(LOG_ERR,
		       "SCDynamicStoreCreateRunLoopSource() failed: %s",
		       SCErrorString(SCError()));
		goto error;
	}
	CFRunLoopAddSource(rl, rls, kCFRunLoopDefaultMode);

	/* ...watch for primary service/interface and DNS configuration changes */
	notify_block = ^{
		CFArrayRef      changes;
		CFStringRef     key;

		key = SCDynamicStoreKeyCreateNetworkGlobalEntity(NULL,
								 kSCDynamicStoreDomainState,
								 kSCEntNetDNS);
		changes = CFArrayCreate(NULL, (const void **)&key, 1, &kCFTypeArrayCallBacks);
		(*configuration_changed)(store, changes, NULL);
		CFRelease(changes);
		CFRelease(key);

		return;
	};
	status = notify_register_dispatch(_SC_NOTIFY_NETWORK_CHANGE,
					  &notify_token,
					  dispatch_get_main_queue(),
					  ^(int token){
						  CFRunLoopPerformBlock(rl,
									kCFRunLoopDefaultMode,
									notify_block);
						  CFRunLoopWakeUp(rl);
					  });
コード例 #29
0
int
keychain_import(int argc, char * const *argv)
{
	int ch, result = 0;

	char *inFile = NULL;
	char *kcName = NULL;
	SecKeychainRef kcRef = NULL;
	SecExternalFormat externFormat = kSecFormatUnknown;
	SecExternalItemType itemType = kSecItemTypeUnknown;
	Boolean wrapped = FALSE;
	Boolean nonExtractable = FALSE;
	const char *passphrase = NULL;
	unsigned char *inFileData = NULL;
	unsigned inFileLen = 0;
	CFDataRef inData = NULL;
	unsigned numExtendedAttributes = 0;
	char **attrNames = NULL;
	char **attrValues = NULL;
	Boolean access_specified = FALSE;
	Boolean always_allow = FALSE;
	SecAccessRef access = NULL;
	CFMutableArrayRef trusted_list = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);

	if(argc < 2) {
		result = 2; /* @@@ Return 2 triggers usage message. */
		goto cleanup;
	}
	inFile = argv[1];
	if((argc == 2) && (inFile[0] == '-')) {
		result = 2;
		goto cleanup;
	}
	optind = 2;

    while ((ch = getopt(argc, argv, "k:t:f:P:wxa:hAT:")) != -1)
	{
		switch  (ch)
		{
		case 'k':
			kcName = optarg;
			break;
		case 't':
			if(!strcmp("pub", optarg)) {
				itemType = kSecItemTypePublicKey;
			}
			else if(!strcmp("priv", optarg)) {
				itemType = kSecItemTypePrivateKey;
			}
			else if(!strcmp("session", optarg)) {
				itemType = kSecItemTypeSessionKey;
			}
			else if(!strcmp("cert", optarg)) {
				itemType = kSecItemTypeCertificate;
			}
			else if(!strcmp("agg", optarg)) {
				itemType = kSecItemTypeAggregate;
			}
			else {
				result = 2; /* @@@ Return 2 triggers usage message. */
				goto cleanup;
			}
			break;
		case 'f':
			if(!strcmp("openssl", optarg)) {
				externFormat = kSecFormatOpenSSL;
			}
			else if(!strcmp("openssh1", optarg)) {
				externFormat = kSecFormatSSH;
			}
			else if(!strcmp("openssh2", optarg)) {
				externFormat = kSecFormatSSHv2;
			}
			else if(!strcmp("bsafe", optarg)) {
				externFormat = kSecFormatBSAFE;
			}
			else if(!strcmp("raw", optarg)) {
				externFormat = kSecFormatRawKey;
			}
			else if(!strcmp("pkcs7", optarg)) {
				externFormat = kSecFormatPKCS7;
			}
			else if(!strcmp("pkcs8", optarg)) {
				externFormat = kSecFormatWrappedPKCS8;
			}
			else if(!strcmp("pkcs12", optarg)) {
				externFormat = kSecFormatPKCS12;
			}
			else if(!strcmp("netscape", optarg)) {
				externFormat = kSecFormatNetscapeCertSequence;
			}
			else if(!strcmp("x509", optarg)) {
				externFormat = kSecFormatX509Cert;
			}
			else if(!strcmp("pemseq", optarg)) {
				externFormat = kSecFormatPEMSequence;
			}
			else {
				result = 2; /* @@@ Return 2 triggers usage message. */
				goto cleanup;
			}
			break;
		case 'w':
			wrapped = TRUE;
			break;
		case 'x':
			nonExtractable = TRUE;
			break;
		case 'P':
			passphrase = optarg;
			break;
		case 'a':
			/* this takes an additional argument */
			if(optind > (argc - 1)) {
				result = 2; /* @@@ Return 2 triggers usage message. */
				goto cleanup;
			}
			attrNames  = (char **)realloc(attrNames, numExtendedAttributes * sizeof(char *));
			attrValues = (char **)realloc(attrValues, numExtendedAttributes * sizeof(char *));
			attrNames[numExtendedAttributes]  = optarg;
			attrValues[numExtendedAttributes] = argv[optind];
			numExtendedAttributes++;
			optind++;
			break;
		case 'A':
			always_allow = TRUE;
			access_specified = TRUE;
			break;
		case 'T':
			if (optarg[0])
			{
				SecTrustedApplicationRef app = NULL;
				OSStatus status = noErr;
				/* check whether the argument specifies an application group */
				const char *groupPrefix = "group://";
				size_t prefixLen = strlen(groupPrefix);
				if (strlen(optarg) > prefixLen && !memcmp(optarg, groupPrefix, prefixLen)) {
					const char *groupName = &optarg[prefixLen];
					if ((status = SecTrustedApplicationCreateApplicationGroup(groupName, NULL, &app)) != noErr) {
						sec_error("SecTrustedApplicationCreateApplicationGroup %s: %s", optarg, sec_errstr(status));
					}
				} else {
					if ((status = SecTrustedApplicationCreateFromPath(optarg, &app)) != noErr) {
						sec_error("SecTrustedApplicationCreateFromPath %s: %s", optarg, sec_errstr(status));
					}
				}

				if (status) {
					result = 1;
					goto cleanup;
				}

				CFArrayAppendValue(trusted_list, app);
				CFRelease(app);
			}
			access_specified = TRUE;
			break;
		case '?':
		default:
			result = 2; /* @@@ Return 2 triggers usage message. */
			goto cleanup;
		}
	}

	if(wrapped) {
		switch(externFormat) {
			case kSecFormatOpenSSL:
			case kSecFormatUnknown:		// i.e., use default
				externFormat = kSecFormatWrappedOpenSSL;
				break;
			case kSecFormatSSH:
				externFormat = kSecFormatWrappedSSH;
				break;
			case kSecFormatSSHv2:
				/* there is no wrappedSSHv2 */
				externFormat = kSecFormatWrappedOpenSSL;
				break;
			case kSecFormatWrappedPKCS8:
				/* proceed */
				break;
			default:
				fprintf(stderr, "Don't know how to wrap in specified format/type\n");
				result = 2; /* @@@ Return 2 triggers usage message. */
				goto cleanup;
		}
	}

	if(kcName) {
		kcRef = keychain_open(kcName);
		if(kcRef == NULL) {
			return 1;
		}
	}
	if(readFile(inFile, &inFileData, &inFileLen)) {
		sec_error("Error reading infile %s: %s", inFile, strerror(errno));
		result = 1;
		goto cleanup;
	}
	inData = CFDataCreate(NULL, inFileData, inFileLen);
	if(inData == NULL) {
		result = 1;
		goto cleanup;
	}
	free(inFileData);

	if(access_specified)
	{
		char *accessName = NULL;
		CFStringRef fileStr = CFStringCreateWithCString(NULL, inFile, kCFStringEncodingUTF8);
		if (fileStr) {
			CFURLRef fileURL = CFURLCreateWithFileSystemPath(NULL, fileStr, kCFURLPOSIXPathStyle, FALSE);
			if (fileURL) {
				CFStringRef nameStr = CFURLCopyLastPathComponent(fileURL);
				if (nameStr) {
					CFIndex nameLen = CFStringGetLength(nameStr);
					CFIndex bufLen = 1 + CFStringGetMaximumSizeForEncoding(nameLen, kCFStringEncodingUTF8);
					accessName = (char *)malloc(bufLen);
					if (!CFStringGetCString(nameStr, accessName, bufLen-1, kCFStringEncodingUTF8))
						accessName[0]=0;
					nameLen = strlen(accessName);
					char *p = &accessName[nameLen]; // initially points to terminating null
					while (--nameLen > 0) {
						if (*p == '.') { // strip extension, if any
							*p = '\0';
							break;
						}
						p--;
					}
					safe_CFRelease(&nameStr);
				}
				safe_CFRelease(&fileURL);
			}
			safe_CFRelease(&fileStr);
		}

		result = create_access(accessName, always_allow, trusted_list, &access);

		if (accessName) {
			free(accessName);
		}
		if (result != 0) {
			goto cleanup;
		}
	}

	result = do_keychain_import(kcRef, inData, externFormat, itemType, access,
								nonExtractable, passphrase, inFile, attrNames,
								attrValues, numExtendedAttributes);

cleanup:
	safe_CFRelease(&trusted_list);
	safe_CFRelease(&access);
	safe_CFRelease(&kcRef);
	safe_CFRelease(&inData);

	return result;
}
コード例 #30
0
// Create a dictionary that describes the kinds of pixel buffers that we want to receive.
// The important keys to add are kCVPixelBufferPixelFormatTypeKey,
// kCVPixelBufferWidthKey and kCVPixelBufferHeightKey.
// Many compressors will also want to set kCVPixelBufferExtendedPixels,
// kCVPixelBufferBytesPerRowAlignmentKey, kCVImageBufferGammaLevelKey and kCVImageBufferYCbCrMatrixKey.
static OSStatus
createPixelBufferAttributesDictionary(SInt32 width, SInt32 height,
                                      const OSType *pixelFormatList, int pixelFormatCount,
                                      CFMutableDictionaryRef *pixelBufferAttributesOut)
{
  OSStatus err = memFullErr;
  int i;
  CFMutableDictionaryRef pixelBufferAttributes = NULL;
  CFNumberRef number = NULL;
  CFMutableArrayRef array = NULL;
  SInt32 widthRoundedUp, heightRoundedUp, extendRight, extendBottom;

  pixelBufferAttributes = CFDictionaryCreateMutable(
                                                    NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);

  if (! pixelBufferAttributes) goto bail;

  array = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);

  if (! array) goto bail;

  // Under kCVPixelBufferPixelFormatTypeKey, add the list of source pixel formats.
  // This can be a CFNumber or a CFArray of CFNumbers.
  for (i = 0; i < pixelFormatCount; i++)
  {
    number = CFNumberCreate(NULL, kCFNumberSInt32Type, &pixelFormatList[i]);

    if (! number) goto bail;

    CFArrayAppendValue(array, number);

    CFRelease(number);
    number = NULL;
  }

  CFDictionaryAddValue(pixelBufferAttributes, kCVPixelBufferPixelFormatTypeKey, array);
  CFRelease(array);
  array = NULL;

  // Add kCVPixelBufferWidthKey and kCVPixelBufferHeightKey to specify the dimensions
  // of the source pixel buffers.  Normally this is the same as the compression target dimensions.
  addNumberToDictionary(pixelBufferAttributes, kCVPixelBufferWidthKey, width);
  addNumberToDictionary(pixelBufferAttributes, kCVPixelBufferHeightKey, height);

  // If you want to require that extra scratch pixels be allocated on the edges of source pixel buffers,
  // add the kCVPixelBufferExtendedPixels{Left,Top,Right,Bottom}Keys to indicate how much.
  // Internally our encoded can only support multiples of 16x16 macroblocks;
  // we will round the compression dimensions up to a multiple of 16x16 and encode that size.
  // (Note that if your compressor needs to copy the pixels anyhow (eg, in order to convert to a different
  // format) you may get better performance if your copy routine does not require extended pixels.)
  widthRoundedUp = roundUpToMultipleOf16(width);
  heightRoundedUp = roundUpToMultipleOf16(height);
  extendRight = widthRoundedUp - width;
  extendBottom = heightRoundedUp - height;

  if (extendRight || extendBottom)
  {
    addNumberToDictionary(pixelBufferAttributes, kCVPixelBufferExtendedPixelsRightKey, extendRight);
    addNumberToDictionary(pixelBufferAttributes, kCVPixelBufferExtendedPixelsBottomKey, extendBottom);
  }

  // Altivec code is most efficient reading data aligned at addresses that are multiples of 16.
  // Pretending that we have some altivec code, we set kCVPixelBufferBytesPerRowAlignmentKey to
  // ensure that each row of pixels starts at a 16-byte-aligned address.
  addNumberToDictionary(pixelBufferAttributes, kCVPixelBufferBytesPerRowAlignmentKey, 16);

  // This codec accepts YCbCr input in the form of '2vuy' format pixel buffers.
  // We recommend explicitly defining the gamma level and YCbCr matrix that should be used.
  addDoubleToDictionary(pixelBufferAttributes, kCVImageBufferGammaLevelKey, 2.2);
  CFDictionaryAddValue(pixelBufferAttributes, kCVImageBufferYCbCrMatrixKey, kCVImageBufferYCbCrMatrix_ITU_R_601_4);

  err = noErr;
  *pixelBufferAttributesOut = pixelBufferAttributes;
  pixelBufferAttributes = NULL;

bail:

  if (pixelBufferAttributes) CFRelease(pixelBufferAttributes);

  if (number) CFRelease(number);

  if (array) CFRelease(array);

  return err;
}