Пример #1
0
extern pascal OSStatus CFQDictionaryMerge(CFMutableDictionaryRef dst, CFDictionaryRef src)
{
	OSStatus err;
	
	assert(dst != NULL);
	assert(src != NULL);
	
	err = noErr;
	CFDictionaryApplyFunction(src, MergeOne, dst);
	
	return err;
}
Пример #2
0
static void
CFRunLoopFinalize (CFTypeRef cf)
{
  CFRunLoopRef rl = (CFRunLoopRef)cf;
  CFAllocatorRef alloc = CFGetAllocator (rl);

  CFRelease (rl->_commonModes);
  CFRelease (rl->_commonObjects);
  CFDictionaryApplyFunction (rl->_contexts, GSRunLoopContextDeallocFunc,
                             (void*)alloc);
  CFRelease (rl->_contexts);
}
Пример #3
0
__private_extern__ void _CFBundleInitPlugIn(CFBundleRef bundle) {
    CFArrayCallBacks _pluginFactoryArrayCallbacks = {0, NULL, NULL, NULL, NULL};
    Boolean doDynamicReg = false;
    CFDictionaryRef infoDict;
    CFDictionaryRef factoryDict;
    CFDictionaryRef typeDict;
    CFStringRef tempStr;

    infoDict = CFBundleGetInfoDictionary(bundle);
    if (!infoDict) return;
    
    factoryDict = (CFDictionaryRef)CFDictionaryGetValue(infoDict, kCFPlugInFactoriesKey);
    if (factoryDict && CFGetTypeID(factoryDict) != CFDictionaryGetTypeID()) factoryDict = NULL;
    tempStr = (CFStringRef)CFDictionaryGetValue(infoDict, kCFPlugInDynamicRegistrationKey);
    if (tempStr && CFGetTypeID(tempStr) == CFStringGetTypeID() && CFStringCompare(tempStr, CFSTR("YES"), kCFCompareCaseInsensitive) == kCFCompareEqualTo) doDynamicReg = true;
    if (!factoryDict && !doDynamicReg) return;  // This is not a plug-in.

    /* loadOnDemand is true by default if the plugIn does not do dynamic registration.  It is false, by default if it does do dynamic registration.  The dynamic register function can set this. */
    __CFBundleGetPlugInData(bundle)->_isPlugIn = true;
    __CFBundleGetPlugInData(bundle)->_loadOnDemand = true;
    __CFBundleGetPlugInData(bundle)->_isDoingDynamicRegistration = false;
    __CFBundleGetPlugInData(bundle)->_instanceCount = 0;

    __CFBundleGetPlugInData(bundle)->_factories = CFArrayCreateMutable(CFGetAllocator(bundle), 0, &_pluginFactoryArrayCallbacks);

    /* Now do the registration */

    /* First do static registrations, if any. */
    if (factoryDict) CFDictionaryApplyFunction(factoryDict, _registerFactory, bundle);
    typeDict = (CFDictionaryRef)CFDictionaryGetValue(infoDict, kCFPlugInTypesKey);
    if (typeDict && CFGetTypeID(typeDict) != CFDictionaryGetTypeID()) typeDict = NULL;
    if (typeDict) CFDictionaryApplyFunction(typeDict, _registerType, bundle);

    /* Now set key for dynamic registration if necessary */
    if (doDynamicReg) {
        CFDictionarySetValue((CFMutableDictionaryRef)infoDict, CFSTR("CFPlugInNeedsDynamicRegistration"), CFSTR("YES"));
        if (CFBundleIsExecutableLoaded(bundle)) _CFBundlePlugInLoaded(bundle);
    }
}
Пример #4
0
VMKXMLPathProcessorRef VMKXMLPathProcessorCreate(CFDictionaryRef namespaces, VMKXMLDocumentRef document)
{
    VMKXMLPathProcessorRef processor = _VMKCreateInstance2(VMKXMLDocumentGetTypeID(), processor);
    
    processor->_rawXMLPathContext = xmlXPathNewContext(VMKXMLDocumentGetRawDocument(document));
    
    if (namespaces)
    {
        CFDictionaryApplyFunction(namespaces, __registerNamespace, processor);
    }

    return processor;
}
Пример #5
0
void xpcEngineAssess(CFURLRef path, uint flags, CFDictionaryRef context, CFMutableDictionaryRef result)
{
	Message msg("assess");
	xpc_dictionary_set_string(msg, "path", cfString(path).c_str());
	xpc_dictionary_set_int64(msg, "flags", flags);
	CFRef<CFMutableDictionaryRef> ctx = makeCFMutableDictionary();
	if (context)
		CFDictionaryApplyFunction(context, copyCFDictionary, ctx);
	CFRef<CFDataRef> contextData = makeCFData(CFDictionaryRef(ctx));
	xpc_dictionary_set_data(msg, "context", CFDataGetBytePtr(contextData), CFDataGetLength(contextData));
	
	msg.send();
	
	if (int64_t error = xpc_dictionary_get_int64(msg, "error"))
		MacOSError::throwMe(error);

	size_t resultLength;
	const void *resultData = xpc_dictionary_get_data(msg, "result", &resultLength);
	CFRef<CFDictionaryRef> resultDict = makeCFDictionaryFrom(resultData, resultLength);
	CFDictionaryApplyFunction(resultDict, copyCFDictionary, result);
	CFDictionaryAddValue(result, CFSTR("assessment:remote"), kCFBooleanTrue);
}
Пример #6
0
void list_installed_apps(struct am_device *device)
{
  connect_to_device(device);

  CFDictionaryRef apps;
  ASSERT_OR_EXIT(!AMDeviceLookupApplications(device, 0, &apps),
                 "!AMDeviceLookupApplications\n");

  CFDictionaryApplyFunction(apps, print_installed_app, NULL);
  CFRelease(apps);

  unregister_device_notification(0);
}
Пример #7
0
QueryData genKernelExtensions(QueryContext &context) {
  QueryData results;

  // Populate dict of kernel extensions.
  CFDictionaryRef dict = KextManagerCopyLoadedKextInfo(nullptr, nullptr);
  if (dict == nullptr) {
    return {};
  }

  CFDictionaryApplyFunction(dict, &genExtension, &results);
  CFRelease(dict);
  return results;
}
static __inline__ void
my_CFDictionaryApplyFunction(CFDictionaryRef			theDict,
			     CFDictionaryApplierFunction	applier,
			     void				*context)
{
	CFAllocatorRef	myAllocator;
	CFDictionaryRef	myDict;

	myAllocator = CFGetAllocator(theDict);
	myDict      = CFDictionaryCreateCopy(myAllocator, theDict);
	CFDictionaryApplyFunction(myDict, applier, context);
	CFRelease(myDict);
	return;
}
Пример #9
0
TStringIRep* TSICTStringCreateWithDictionaryAndFormat(CFDictionaryRef dictionary, TSITStringFormat format)
{
    CFRetain(dictionary);

    CFMutableDataRef buffer = CFDataCreateMutable(kCFAllocatorDefault, 0);

    TStringCollectionCallbackContext cx = {buffer, format};
    CFDictionaryApplyFunction(dictionary, DictionaryBufferAppendCallback, &cx);

    TStringIRep* rep = TSICTStringCreateWithDataOfTypeAndFormat(buffer, kTSITStringTagDict, format);
    CFRelease(buffer);
    CFRelease(dictionary);
    return rep;
}
Пример #10
0
 void build_id3tag(CFDictionaryRef dict,
                   const AudioFilePacketTableInfo *packet_info,
                   uint32_t prefetch_point,
                   std::vector<uint8_t> *result)
 {
     std::vector<uint8_t> vec(10);
     std::memcpy(&vec[0], "ID3\x03", 4);
     struct dict_callback {
         static void f(const void *k, const void *v, void *c)
         {
             std::vector<uint8_t> *vp =
                 static_cast<std::vector<uint8_t>*>(c);
             std::wstring wkey =
                 cautil::CF2W(static_cast<CFStringRef>(k));
             std::wstring wvalue =
                 cautil::CF2W(static_cast<CFStringRef>(v));
             std::string skey = strutil::w2us(wkey);
             std::vector<uint8_t> frame;
             build_text_frame(skey.c_str(), wvalue.c_str(), &frame);
             if (frame.size())
                 std::copy(frame.begin(), frame.end(),
                           std::back_inserter(*vp));
         }
     };
     if (dict)
         CFDictionaryApplyFunction(dict, &dict_callback::f, &vec);
     if (packet_info &&
         (packet_info->mPrimingFrames || packet_info->mRemainderFrames)) {
         const char *tmpl =
             " 00000000 %08X %08X %016llX 00000000 %08X 00000000 00000000"
             " 00000000 00000000 00000000 00000000";
         char buf[256];
         std::sprintf(buf, tmpl, packet_info->mPrimingFrames,
                      packet_info->mRemainderFrames,
                      packet_info->mNumberValidFrames,
                      prefetch_point);
         std::wstring ws = strutil::us2w(buf);
         std::vector<uint8_t> frame;
         build_comment_frame("eng", L"iTunPGAP", L"0", &frame);
         std::copy(frame.begin(), frame.end(), std::back_inserter(vec));
         build_comment_frame("eng", L"iTunSMPB", ws.c_str(), &frame);
         std::copy(frame.begin(), frame.end(), std::back_inserter(vec));
     }
     uint32_t size = 512;
     while (size < vec.size())
         size <<= 1;
     vec.resize(size);
     get_sync_value(size - 10, &vec[6]);
     result->swap(vec);
 }
Пример #11
0
void cli_show_plist (void)
{
  CFBundleRef mainBundle = CFBundleGetMainBundle();
  CFRetain(mainBundle);
  CFDictionaryRef mainBundleDict = CFBundleGetInfoDictionary(mainBundle);
  if (mainBundleDict) {
    CFRetain(mainBundleDict);
    printf("Embedded Info.plist metadata:\n\n");
    CFDictionaryApplyFunction(mainBundleDict, cli_print_info_dict, NULL);
    CFRelease(mainBundleDict);
  }
  CFRelease(mainBundle);
  printf("\n");
}
Пример #12
0
/* Callback function which will recieve the 'mounted' notification
 * from FUSE. It is full with debug code... but I'll let it stay
 * that way. */
static void NotificationCallback(CFNotificationCenterRef center,
				 void *observer,
				 CFStringRef name,
				 const void *object,
				 CFDictionaryRef userInfo) {
  if(DEBUGMODE) {
    char buffer[512];
    LOG_DEBUG("Received notification:\n");
    if(CFStringGetCString(name, buffer, 512, kCFStringEncodingUTF8) == true)
      LOG_DEBUG("  Name: %s\n", buffer);
    else
      LOG_DEBUG("  <Cound not get name>\n");
    
    LOG_DEBUG("  userInfo:\n");
    if(userInfo != NULL)
      CFDictionaryApplyFunction(userInfo, PrintDictEntry, NULL);
    else
      LOG_DEBUG("    <null>\n");
  }
  
  if(userInfo != NULL) { // It's only null when testing
    const void *value = NULL;
    LOG_DEBUG("CFDictionaryGetValueIfPresent(%p, \"%s\", %p)\n",
	      userInfo, FUSE_MOUNT_PATH_KEY, &value);

    if(CFDictionaryGetValueIfPresent(userInfo, CFSTR(FUSE_MOUNT_PATH_KEY),
				     &value) == true) {
      LOG_DEBUG("CFStringGetTypeID(%p) == %lu ?\n", value,
		CFStringGetTypeID());
      if(CFGetTypeID((CFStringRef)value) == CFStringGetTypeID()) {
	LOG_DEBUG("  yes.\n");
	LOG_DEBUG("mountPath=%p\n", mountPath);
	if(mountPath != NULL)
	  CFRelease(mountPath); // No memory leaks please.
	LOG_DEBUG("assigning mountpath the value %p\n", value);

	mountPath = (CFStringRef)value;
	CFRetain(mountPath);

	LOG_DEBUG("done with assigning.\n");
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
	CFRunLoopStop(CFRunLoopGetCurrent());
#endif
      }
      else
	LOG_DEBUG("  no.");
    }
  }
}
Пример #13
0
void detect_window_below_cursor()
{
        window_lst.clear();

        CFArrayRef osx_window_list = CGWindowListCopyWindowInfo(kCGWindowListOptionOnScreenOnly | kCGWindowListExcludeDesktopElements, kCGNullWindowID);
        if(osx_window_list)
        {
                CFIndex osx_window_count = CFArrayGetCount(osx_window_list);
                for(CFIndex i = 0; i < osx_window_count; ++i)
                {
                        CFDictionaryRef elem = (CFDictionaryRef)CFArrayGetValueAtIndex(osx_window_list, i);
                        window_lst.push_back(app_info());
                        CFDictionaryApplyFunction(elem, print_keys, NULL);
                }

                CGEventRef event = CGEventCreate(NULL);
                CGPoint cursor = CGEventGetLocation(event);
                CFRelease(event);

                std::cout << "Mouse Pos: " << cursor.x << ", " << cursor.y << std::endl;
                for(int i = 0; i < window_lst.size(); ++i)
                {
                        if(window_lst[i].layer == 0)
                        {
                                if(cursor.x >= window_lst[i].x && cursor.x <= window_lst[i].x + window_lst[i].width
                                                && cursor.y >= window_lst[i].y && cursor.y <= window_lst[i].y + window_lst[i].height)
                                {
                                        window_lst_focus_index = i;
                                        pid = window_lst[i].pid;
                                        GetProcessForPID(pid, &psn);
                                        SetFrontProcessWithOptions(&psn, kSetFrontProcessFrontWindowOnly);
                                        break;
                                }

                                std::cout << "Owner: " << window_lst[i].owner << std::endl;
                                std::cout << "Name: " << window_lst[i].name << std::endl;
                                std::cout << "PID: " << window_lst[i].pid << std::endl;
                                std::cout << "Layer: " << window_lst[i].layer << std::endl;
                                std::cout << "X: " << window_lst[i].x << std::endl;
                                std::cout << "Y: " << window_lst[i].y << std::endl;
                                std::cout << "Width: " << window_lst[i].width << std::endl;
                                std::cout << "Height: " << window_lst[i].height << std::endl;

                        }
                }
                std::cout << "Keyboard focus: " << pid << std::endl;
        }
}
Пример #14
0
void ResourceResponse::platformLazyInit(InitLevel initLevel)
{
    if (m_initLevel > initLevel)
        return;

    if (m_isNull || !m_cfResponse.get())
        return;

    if (m_initLevel < CommonFieldsOnly && initLevel >= CommonFieldsOnly) {
        m_url = CFURLResponseGetURL(m_cfResponse.get());
        m_mimeType = CFURLResponseGetMIMEType(m_cfResponse.get());
        m_expectedContentLength = CFURLResponseGetExpectedContentLength(m_cfResponse.get());
        m_textEncodingName = CFURLResponseGetTextEncodingName(m_cfResponse.get());

        // Workaround for <rdar://problem/8757088>, can be removed once that is fixed.
        unsigned textEncodingNameLength = m_textEncodingName.length();
        if (textEncodingNameLength >= 2 && m_textEncodingName[0U] == '"' && m_textEncodingName[textEncodingNameLength - 1] == '"')
            m_textEncodingName = m_textEncodingName.string().substring(1, textEncodingNameLength - 2);

        CFHTTPMessageRef httpResponse = CFURLResponseGetHTTPResponse(m_cfResponse.get());
        if (httpResponse) {
            m_httpStatusCode = CFHTTPMessageGetResponseStatusCode(httpResponse);
            
            if (initLevel < AllFields) {
                RetainPtr<CFDictionaryRef> headers = adoptCF(CFHTTPMessageCopyAllHeaderFields(httpResponse));
                for (auto& commonHeader : commonHeaderFields) {
                    CFStringRef value;
                    if (CFDictionaryGetValueIfPresent(headers.get(), commonHeader, (const void **)&value))
                        m_httpHeaderFields.set(commonHeader, value);
                }
            }
        } else
            m_httpStatusCode = 0;
    }

    if (m_initLevel < AllFields && initLevel == AllFields) {
        CFHTTPMessageRef httpResponse = CFURLResponseGetHTTPResponse(m_cfResponse.get());
        if (httpResponse) {
            RetainPtr<CFStringRef> statusLine = adoptCF(CFHTTPMessageCopyResponseStatusLine(httpResponse));
            m_httpStatusText = extractReasonPhraseFromHTTPStatusLine(statusLine.get());

            RetainPtr<CFDictionaryRef> headers = adoptCF(CFHTTPMessageCopyAllHeaderFields(httpResponse));
            CFDictionaryApplyFunction(headers.get(), addToHTTPHeaderMap, &m_httpHeaderFields);
        }
    }

    m_initLevel = initLevel;
}
Пример #15
0
/// the call remove all kelled process from process list
static int remove_killed_process()
{
     int ret, i;
     struct pid_builder_struct pid_builder = {};
     task_record_t **killed_list[MAX_TASKS];
     pid_builder.array = &killed_list;

     CFDictionaryApplyFunction(tasks_dict, build_killed_array, (void*)&pid_builder);
    
     for (i = 0; i < pid_builder.pos; i++)
     {
          CFDictionaryRemoveValue(tasks_dict, killed_list[i]);
     }

     return ret;
}
Пример #16
0
static CFDictionaryRef _CFUserNotificationModifiedDictionary(CFAllocatorRef allocator, CFDictionaryRef dictionary, SInt32 token, SInt32 timeout, CFStringRef source) {
    CFMutableDictionaryRef md = CFDictionaryCreateMutable(allocator, 0, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
    CFNumberRef tokenNumber = CFNumberCreate(allocator, kCFNumberSInt32Type, &token);
    CFNumberRef timeoutNumber = CFNumberCreate(allocator, kCFNumberSInt32Type, &timeout);
    CFURLRef url = NULL;
    CFStringRef path = NULL;

    if (dictionary) CFDictionaryApplyFunction(dictionary, _CFUserNotificationAddToDictionary, md);
    if (source) CFDictionaryAddValue(md, kCFUserNotificationAlertSourceKey, source);
    if (tokenNumber) {
        CFDictionaryAddValue(md, kCFUserNotificationTokenKey, tokenNumber);
        CFRelease(tokenNumber);
    }
    if (timeoutNumber) {
        CFDictionaryAddValue(md, kCFUserNotificationTimeoutKey, timeoutNumber);
        CFRelease(timeoutNumber);
    }
    
    url = CFDictionaryGetValue(md, kCFUserNotificationIconURLKey);
    if (url && CFGetTypeID((CFTypeRef)url) == CFURLGetTypeID()) {
        url = CFURLCopyAbsoluteURL(url);
        CFDictionaryRemoveValue(md, kCFUserNotificationIconURLKey);
        path = CFURLCopyFileSystemPath(url, kCFURLPOSIXPathStyle);
        CFDictionaryAddValue(md, kCFUserNotificationIconPathKey, path);
        CFRelease(url);
        CFRelease(path);
    }
    url = CFDictionaryGetValue(md, kCFUserNotificationSoundURLKey);
    if (url && CFGetTypeID((CFTypeRef)url) == CFURLGetTypeID()) {
        url = CFURLCopyAbsoluteURL(url);
        CFDictionaryRemoveValue(md, kCFUserNotificationSoundURLKey);
        path = CFURLCopyFileSystemPath(url, kCFURLPOSIXPathStyle);
        CFDictionaryAddValue(md, kCFUserNotificationSoundPathKey, path);
        CFRelease(url);
        CFRelease(path);
    }
    url = CFDictionaryGetValue(md, kCFUserNotificationLocalizationURLKey);
    if (url && CFGetTypeID((CFTypeRef)url) == CFURLGetTypeID()) {
        url = CFURLCopyAbsoluteURL(url);
        CFDictionaryRemoveValue(md, kCFUserNotificationLocalizationURLKey);
        path = CFURLCopyFileSystemPath(url, kCFURLPOSIXPathStyle);
        CFDictionaryAddValue(md, kCFUserNotificationLocalizationPathKey, path);
        CFRelease(url);
        CFRelease(path);
    }
    return md;
}
Пример #17
0
void print_keys(const void *key, const void *value, void *context)
{
        CFStringRef k = (CFStringRef)key;
        std::string key_str = CFStringGetCStringPtr(k, kCFStringEncodingMacRoman);
        std::string value_str;

        CFTypeID id = CFGetTypeID(value);
        if(id == CFStringGetTypeID())
        {
                CFStringRef v = (CFStringRef)value;
                if(CFStringGetCStringPtr(v, kCFStringEncodingMacRoman))
                {
                        value_str = CFStringGetCStringPtr(v, kCFStringEncodingMacRoman);
                        if(key_str == "kCGWindowName")
                                window_lst[window_lst.size()-1].name = value_str;
                        else if(key_str == "kCGWindowOwnerName")
                                window_lst[window_lst.size()-1].owner = value_str;
                }
        }
        else if(id == CFNumberGetTypeID())
        {
                CFNumberRef v = (CFNumberRef)value;
                int myint;
                CFNumberGetValue(v, kCFNumberSInt64Type, &myint);
                value_str = std::to_string(myint);
                if(key_str == "kCGWindowLayer")
                        window_lst[window_lst.size()-1].layer = myint;
                else if(key_str == "kCGWindowOwnerPID")
                        window_lst[window_lst.size()-1].pid = myint;
                else if(key_str == "X")
                        window_lst[window_lst.size()-1].x = myint;
                else if(key_str == "Y")
                        window_lst[window_lst.size()-1].y = myint;
                else if(key_str == "Width")
                        window_lst[window_lst.size()-1].width = myint;
                else if(key_str == "Height")
                        window_lst[window_lst.size()-1].height = myint;
        }
        else if(id == CFDictionaryGetTypeID())
        {
                CFDictionaryRef elem = (CFDictionaryRef)value;
                CFDictionaryApplyFunction(elem, print_keys, NULL);
                CFRelease(elem);
        } 
}
Пример #18
0
CFStringRef _CFErrorCreateDebugDescription(CFErrorRef err) {
    CFStringRef desc = CFErrorCopyDescription(err);
    CFStringRef debugDesc = _CFErrorCopyUserInfoKey(err, kCFErrorDebugDescriptionKey);
    CFDictionaryRef userInfo = _CFErrorGetUserInfo(err);
    CFMutableStringRef result = CFStringCreateMutable(kCFAllocatorSystemDefault, 0);
    CFStringAppendFormat(result, NULL, CFSTR("Error Domain=%@ Code=%d"), CFErrorGetDomain(err), (long)CFErrorGetCode(err));
    CFStringAppendFormat(result, NULL, CFSTR(" \"%@\""), desc);
    if (debugDesc && CFStringGetLength(debugDesc) > 0) CFStringAppendFormat(result, NULL, CFSTR(" (%@)"), debugDesc);
    if (userInfo) {
        CFStringAppendFormat(result, NULL, CFSTR(" UserInfo=%p {"), userInfo);
	CFDictionaryApplyFunction(userInfo, userInfoKeyValueShow, (void *)result);
	CFIndex commaLength = (CFStringHasSuffix(result, CFSTR(", "))) ? 2 : 0;
	CFStringReplace(result, CFRangeMake(CFStringGetLength(result)-commaLength, commaLength), CFSTR("}"));
    }
    if (debugDesc) CFRelease(debugDesc);
    if (desc) CFRelease(desc);
    return result;
}
Пример #19
0
    void fetchTags(AudioFileX &af, FILE *fp,
                   std::map<std::string, std::string> *result)
    {
        std::map<std::string, std::string> tags;

        if (af.getFileFormat() == 'caff') {
            std::vector<uint8_t> data;
            af.getUserData('info', 0, &data);
            CAF::fetchTags(data, &tags);
        } else {
            CFDictionaryPtr dict;
            af.getInfoDictionary(&dict);
            if (dict.get())
                CFDictionaryApplyFunction(dict.get(), fetchTagDictCallback,
                                          &tags);
        }
        TextBasedTag::normalizeTags(tags, result);
    }
Пример #20
0
//============================================================================
//		NCFDictionary::SetObject : Set the object.
//----------------------------------------------------------------------------
bool NCFDictionary::SetObject(CFDictionaryRef cfObject, bool takeOwnership)
{	NCFObject		theObject(cfObject, takeOwnership);
	bool			isValid;



	// Get the state we need
	isValid = (cfObject != NULL);
	Clear();



	// Set the object
	if (isValid)
		CFDictionaryApplyFunction(cfObject, InsertValue, this);

	return(isValid);
}
Пример #21
0
void genOSXPrefValues(const CFTypeRef& value,
                      const Row& base,
                      QueryData& results,
                      size_t depth) {
  if (value == nullptr) {
    return;
  }

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

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

  results.push_back(std::move(r));
}
Пример #22
0
// Apple don't use a simple callback to NP_GetMIMEDescription, as on Linux, but
// we still need to implement it as we can dynamically open other plugins.
//
// XXX: For the initial release, I'm not going to support external MIME types. I
//      will add it on request.
char * platform_getmimedescription(struct plugin *plugin)
{
    CFDictionaryRef     cf_pluginplist   = NULL;
    CFDictionaryRef     cf_mimetypes     = NULL;
    CFBundleRef         cf_plugin        = plugin->handle;
    char               *mime_description = strdup("");

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

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

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

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

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

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

finished:
    // Return the final string.
    return mime_description;
}
Пример #23
0
CFDictionaryRef xpcEngineUpdate(CFTypeRef target, uint flags, CFDictionaryRef context)
{
	Message msg("update");
	// target can be NULL, a CFURLRef, a SecRequirementRef, or a CFNumberRef
	if (target) {
		if (CFGetTypeID(target) == CFNumberGetTypeID())
			xpc_dictionary_set_uint64(msg, "rule", cfNumber<int64_t>(CFNumberRef(target)));
		else if (CFGetTypeID(target) == CFURLGetTypeID())
			xpc_dictionary_set_string(msg, "url", cfString(CFURLRef(target)).c_str());
		else if (CFGetTypeID(target) == SecRequirementGetTypeID()) {
			CFRef<CFDataRef> data;
			MacOSError::check(SecRequirementCopyData(SecRequirementRef(target), kSecCSDefaultFlags, &data.aref()));
			xpc_dictionary_set_data(msg, "requirement", CFDataGetBytePtr(data), CFDataGetLength(data));
		} else
			MacOSError::throwMe(errSecCSInvalidObjectRef);
	}
	xpc_dictionary_set_int64(msg, "flags", flags);
	CFRef<CFMutableDictionaryRef> ctx = makeCFMutableDictionary();
	if (context)
		CFDictionaryApplyFunction(context, copyCFDictionary, ctx);
	AuthorizationRef localAuthorization = NULL;
	if (CFDictionaryGetValue(ctx, kSecAssessmentUpdateKeyAuthorization) == NULL) {	// no caller-provided authorization
		MacOSError::check(AuthorizationCreate(NULL, NULL, kAuthorizationFlagDefaults, &localAuthorization));
		AuthorizationExternalForm extForm;
		MacOSError::check(AuthorizationMakeExternalForm(localAuthorization, &extForm));
		CFDictionaryAddValue(ctx, kSecAssessmentUpdateKeyAuthorization, CFTempData(&extForm, sizeof(extForm)));
	}
	CFRef<CFDataRef> contextData = makeCFData(CFDictionaryRef(ctx));
	xpc_dictionary_set_data(msg, "context", CFDataGetBytePtr(contextData), CFDataGetLength(contextData));
	
	msg.send();

	if (localAuthorization)
		AuthorizationFree(localAuthorization, kAuthorizationFlagDefaults);
	
	if (int64_t error = xpc_dictionary_get_int64(msg, "error"))
		MacOSError::throwMe(error);
	
	size_t resultLength;
	const void *resultData = xpc_dictionary_get_data(msg, "result", &resultLength);
	return makeCFDictionaryFrom(resultData, resultLength);
}
Пример #24
0
static krb5_error_code
parse_plist_config(krb5_context context, const char *path, krb5_config_section **parent)
{
    CFReadStreamRef s;
    CFDictionaryRef d;
    CFURLRef url;

    url = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, (UInt8 *)path, strlen(path), FALSE);
    if (url == NULL) {
        krb5_clear_error_message(context);
        return ENOMEM;
    }

    s = CFReadStreamCreateWithFile(kCFAllocatorDefault, url);
    CFRelease(url);
    if (s == NULL) {
        krb5_clear_error_message(context);
        return ENOMEM;
    }

    if (!CFReadStreamOpen(s)) {
        CFRelease(s);
        krb5_clear_error_message(context);
        return ENOENT;
    }

#ifdef HAVE_CFPROPERTYLISTCREATEWITHSTREAM
    d = (CFDictionaryRef)CFPropertyListCreateWithStream(NULL, s, 0, kCFPropertyListImmutable, NULL, NULL);
#else
    d = (CFDictionaryRef)CFPropertyListCreateFromStream(NULL, s, 0, kCFPropertyListImmutable, NULL, NULL);
#endif
    CFRelease(s);
    if (d == NULL) {
        krb5_clear_error_message(context);
        return ENOENT;
    }

    CFDictionaryApplyFunction(d, convert_content, parent);
    CFRelease(d);

    return 0;
}
Пример #25
0
static void
gst_vtenc_session_dump_properties (GstVTEnc * self,
    VTCompressionSessionRef session)
{
  GstVTDumpPropCtx dpc = { self, self->ctx->vt, session };
  CFDictionaryRef dict;
  VTStatus status;

  status = self->ctx->vt->VTCompressionSessionCopySupportedPropertyDictionary
      (session, &dict);
  if (status != kVTSuccess)
    goto error;
  CFDictionaryApplyFunction (dict,
      (CFDictionaryApplierFunction) gst_vtenc_session_dump_property, &dpc);
  CFRelease (dict);

  return;

error:
  GST_WARNING_OBJECT (self, "failed to dump properties");
}
Пример #26
0
/* Create a mutable dictionary that is based on the subdictionary for key
 with any attributes from the top level dict merged in. */
static CFMutableDictionaryRef merge_params(CFDictionaryRef dict,
                                           CFStringRef key) {
	CFDictionaryRef subdict = CFDictionaryGetValue(dict, key);
	CFMutableDictionaryRef result;
    
	if (subdict) {
		result = CFDictionaryCreateMutableCopy(NULL, 0, subdict);
		/* Add everything in dict not already in result to result. */
		CFDictionaryApplyFunction(dict, merge_params_applier, result);
	} else {
		result = CFDictionaryCreateMutableCopy(NULL, 0, dict);
	}
    
	/* Remove values that only belong in the top level dict. */
	CFDictionaryRemoveValue(result, kSecPublicKeyAttrs);
	CFDictionaryRemoveValue(result, kSecPrivateKeyAttrs);
	CFDictionaryRemoveValue(result, kSecAttrKeyType);
	CFDictionaryRemoveValue(result, kSecAttrKeySizeInBits);
    
	return result;
}
Пример #27
0
static VALUE rb_keychain_item_reload(VALUE self){
  SecKeychainItemRef keychainItem=NULL;
  Data_Get_Struct(self, struct OpaqueSecKeychainItemRef, keychainItem);

  CFMutableDictionaryRef query = sec_query_identifying_item(keychainItem);

  CFDictionarySetValue(query, kSecReturnAttributes, kCFBooleanTrue);
  CFStringRef cfclass = rb_copy_item_class(keychainItem);
  CFDictionarySetValue(query, kSecClass, cfclass);
  CFRelease(cfclass);

  CFDictionaryRef attributes;
  OSStatus result = SecItemCopyMatching(query, (CFTypeRef*)&attributes);
  CFRelease(query);
  CheckOSStatusOrRaise(result);
  VALUE new_attributes = rb_hash_new();
  CFDictionaryApplyFunction(attributes, cf_hash_to_rb_hash, (void*)new_attributes);
  rb_ivar_set(self, rb_intern("@attributes"), new_attributes);
  rb_ivar_set(self, rb_intern("unsaved_password"), Qnil);
  CFRelease(attributes);

  return self;
}
Пример #28
0
/* Callback function which will recieve the 'mounted' notification
 * from FUSE. It is full with debug code... but I'll let it stay
 * that way. */
static void NotificationCallback(CFNotificationCenterRef center,
				 void *observer,
				 CFStringRef name,
				 const void *object,
				 CFDictionaryRef userInfo) {
  if(DEBUGMODE) {
    char buffer[512];
    DEBUG("Received notification:\n");
    if(CFStringGetCString(name, buffer, 512, kCFStringEncodingUTF8) == true)
      DEBUG("  Name: %s\n", buffer);
    else
      DEBUG("  <Cound not get name>\n");
  }
  if(userInfo != NULL) { // It's only null when testing
    DEBUG("  userInfo:\n");
    if(DEBUGMODE) CFDictionaryApplyFunction(userInfo, PrintDictEntry, NULL);
    
    const void *value = NULL;
    DEBUG("CFDictionaryGetValueIfPresent(%X, \"%s\", %X\n",
	    (int)userInfo, FUSE_MOUNT_PATH_KEY, (int)&value);

    if(CFDictionaryGetValueIfPresent(userInfo, CFSTR(FUSE_MOUNT_PATH_KEY), &value) == true) {
      DEBUG("CFGetTypeID(%X) == %X ?\n", (int)value, (int)CFStringGetTypeID());
      if(CFGetTypeID((CFStringRef)value) == CFStringGetTypeID()) {
	DEBUG("mountPath=%X\n", (int)mountPath);
	if(mountPath != NULL)
	  CFRelease(mountPath); // No memory leaks please.
	DEBUG("assigning mountpath the value %X\n", (int)value);

	mountPath = (CFStringRef)value;
	CFRetain(mountPath);

	DEBUG("done with assigning.\n");
      }
    }
  }
}
Пример #29
0
static void
convert_content(const void *key, const void *value, void *context)
{
    krb5_config_section *tmp, **parent = context;
    char *k;

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

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

    if (CFGetTypeID(value) == CFStringGetTypeID()) {
        tmp = get_entry(parent, k, krb5_config_string);
        tmp->u.string = cfstring2cstring(value);
    } else if (CFGetTypeID(value) == CFDictionaryGetTypeID()) {
        tmp = get_entry(parent, k, krb5_config_list);
        CFDictionaryApplyFunction(value, convert_content, &tmp->u.list);
    } else {
        /* log */
    }
    free(k);
}
Пример #30
0
static kern_return_t
IOFindPlugIns( io_service_t service,
               CFUUIDRef pluginType,
               CFArrayRef * factories, CFArrayRef * plists )
{
    CFURLRef		url;
    CFPlugInRef		onePlugin;
    CFBundleRef		bundle;
    CFDictionaryRef	plist;
    CFDictionaryRef	matching;
    CFDictionaryRef	pluginTypes;
    CFMutableStringRef	path;
    LookUUIDContext	context;
    CFStringRef		pluginName;
    boolean_t		matches;
    kern_return_t	kr = kIOReturnSuccess;
    
    // -- loadables
    onePlugin 		= NULL;
    pluginName		= NULL;
    path 		= NULL;
    url 		= NULL;

    do {

        pluginTypes = IORegistryEntryCreateCFProperty( service, CFSTR(kIOCFPlugInTypesKey),
                                            kCFAllocatorDefault, kNilOptions );
        if( !pluginTypes )
            continue;

        // look up UUID key this way - otherwise string case matters
//        CFShow( pluginTypes );
        context.key = pluginType;
        context.result = 0;
        CFDictionaryApplyFunction( pluginTypes, &_IOGetWithUUIDKey, &context);
        pluginName = (CFStringRef) context.result;
        if( !pluginName)
            continue;

        path = CFStringCreateMutable( kCFAllocatorDefault, 0 );
        if( !path)
            continue;
        CFStringAppendCString(path,
                            "/System/Library/Extensions/",
                            kCFStringEncodingMacRoman);
        CFStringAppend(path, pluginName);
        url = CFURLCreateWithFileSystemPath(NULL, path,
                        kCFURLPOSIXPathStyle, TRUE);
        if( !url)
            continue;

        onePlugin = CFPlugInCreate(NULL, url);

    } while( false );

//    if (pluginName && (!onePlugin))
//        printf("Could not create CFPluginRef.\n");

    if( url)
        CFRelease( url );
    if( path)
        CFRelease( path );
    if( pluginTypes )
        CFRelease( pluginTypes );
    // --

    if( onePlugin
        && (bundle = CFPlugInGetBundle(onePlugin))
        && (plist = CFBundleGetInfoDictionary(bundle))
        && (matching = (CFDictionaryRef)
            CFDictionaryGetValue(plist, CFSTR("Personality")))) {

        kr = IOServiceMatchPropertyTable( service, matching, &matches);
        if( kr != kIOReturnSuccess)
            matches = FALSE;
    } else
        matches = TRUE;

    if( matches) {
        if( onePlugin)
            *factories = CFPlugInFindFactoriesForPlugInTypeInPlugIn(pluginType, onePlugin);
        else
            *factories = 0;//CFPlugInFindFactoriesForPlugInType(pluginType);
    } else
        *factories = 0;

    *plists = 0;

    return( kr );
}