Ejemplo n.º 1
0
static CFDictionaryRef _CFCopyVersionDictionary(CFStringRef path)
{
  CFURLRef url;
  CFDataRef resourceData;
  Boolean status;
  SInt32 errorCode;
  CFErrorRef err;
  CFPropertyListRef plist;

  url = CFURLCreateWithFileSystemPath(NULL, path, kCFURLPOSIXPathStyle, 0);
  status = CFURLCreateDataAndPropertiesFromResource(NULL, url, &resourceData,
		  NULL, NULL, &errorCode);

  if (!status)
  {
	  CFRelease(url);
	  return NULL;
  }

  plist = CFPropertyListCreateWithData(NULL, resourceData, kCFPropertyListImmutable,
		  NULL, &err);

  CFRelease(resourceData);
  CFRelease(url);

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

    return WTFMove(archive);
}
Ejemplo n.º 3
0
bool ReceiptsDb::getInstalledPackageInfo(const char* identifier, std::string& plistXml)
{
	std::string path;
	std::unique_ptr<Reader> fileReader;
	std::unique_ptr<UInt8[]> fileData;
	CFDataRef data;
	CFDictionaryRef plist;
	
	path = getReceiptsPath(identifier, ".plist");
	
	if (::access(path.c_str(), F_OK) != 0)
		return false;
	
	fileReader.reset(new FileReader(path));
	fileData.reset(new UInt8[fileReader->length()]);
	
	if (fileReader->read(fileData.get(), fileReader->length(), 0) != fileReader->length())
		throw std::runtime_error("Short read in getInstalledPackageInfo()");
	
	data = CFDataCreate(nullptr, fileData.get(), fileReader->length());
	fileData.reset(nullptr);
	
	plist = (CFDictionaryRef) CFPropertyListCreateWithData(nullptr, data,
			kCFPropertyListImmutable, nullptr, nullptr);
	CFRelease(data);
	
	data = CFPropertyListCreateData(nullptr, plist,
			kCFPropertyListXMLFormat_v1_0, 0, nullptr);
	CFRelease(plist);
	
	plistXml.assign((const char*) CFDataGetBytePtr(data), CFDataGetLength(data));
	CFRelease(data);
	
	return true;
}
Ejemplo n.º 4
0
Archivo: cfutil.c Proyecto: aosm/bootp
PRIVATE_EXTERN CFPropertyListRef 
my_CFPropertyListCreateFromFile(const char * filename)
{
    void *		buf;
    size_t		bufsize;
    CFDataRef		data = NULL;
    CFPropertyListRef	plist = NULL;

    buf = read_file(filename, &bufsize);
    if (buf == NULL) {
	return (NULL);
    }
    data = CFDataCreateWithBytesNoCopy(NULL, buf, bufsize, kCFAllocatorNull);
    if (data == NULL) {
	goto done;
    }
    plist = CFPropertyListCreateWithData(NULL,
					 data, 
					 kCFPropertyListImmutable,
					 NULL,
					 NULL);
 done:
    if (data)
	CFRelease(data);
    if (buf)
	free(buf);
    return (plist);
}
Ejemplo n.º 5
0
sdmmd_return_t SDMMD_ServiceReceiveMessage(SocketConnection handle, CFPropertyListRef *data) {
	CFDataRef dataBuffer = NULL;
	sdmmd_return_t result;
	*data = NULL;
	CFErrorRef error = NULL;

	result = SDMMD_ServiceReceive(handle, &dataBuffer);
	if (result == kAMDSuccess) {
		
		// ServiceReceive success does not guarantee that valid data is available
		if (dataBuffer) {
			// CFPropertyListCreateWithData will return NULL if data is invalid format
			*data = CFPropertyListCreateWithData(kCFAllocatorDefault, dataBuffer, kCFPropertyListImmutable, NULL, &error);
		}
		
		if (*data == NULL) {
			// Could not parse received data
			result = kAMDInvalidResponseError;
		}
	}
	CFSafeRelease(dataBuffer);
	
	// Return an empty dictionary if a receive OR parse failure occurred
	if (result != kAMDSuccess) {
		*data = CFDictionaryCreateMutable(kCFAllocatorDefault, 0x0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
	}
	
	return result;
}
static int CreatePropertyListFromData(CFDataRef prop_data,  CFTypeID output_type, CFTypeRef* plistRef)
{
	int result = -1; // Guilt until proven
	CFPropertyListRef aPlistRef = NULL;
	CFPropertyListFormat list_format = kCFPropertyListXMLFormat_v1_0;
	CFErrorRef error = NULL;
	
	if (NULL == prop_data || NULL == plistRef)
	{
		return result;
	}
	
	*plistRef = NULL;
	
	aPlistRef = CFPropertyListCreateWithData(kCFAllocatorDefault, prop_data, 0, &list_format, &error);
	if (NULL != error || NULL == aPlistRef)
	{
		if (NULL != error)
		{
			CFRelease(error);
		}
		return result;
	}
	
	if (CFGetTypeID(aPlistRef) != output_type)
	{
		CFRelease(aPlistRef);
		return result;
	}
	
	*plistRef = aPlistRef;
    result = (NULL == *plistRef) ? -1 : 0;
	return result;
}
Ejemplo n.º 7
0
Status parseApplicationAliasData(const std::string& data, std::string& result) {
  std::string decoded_data = base64Decode(data);
  if (decoded_data.empty()) {
    return Status(1, "Failed to base64 decode data");
  }

  CFDataRef resourceData = CFDataCreate(
      nullptr,
      static_cast<const UInt8*>(static_cast<const void*>(decoded_data.c_str())),
      decoded_data.length());
  if (resourceData == nullptr) {
    return Status(1, "Failed to allocate resource data");
  }

  auto alias = (CFDataRef)CFPropertyListCreateWithData(kCFAllocatorDefault,
                                                       resourceData,
                                                       kCFPropertyListImmutable,
                                                       nullptr,
                                                       nullptr);
  CFRelease(resourceData);
  if (alias == nullptr) {
    return Status(1, "Failed to allocate alias data");
  }

  auto bookmark =
      CFURLCreateBookmarkDataFromAliasRecord(kCFAllocatorDefault, alias);
  CFRelease(alias);
  if (bookmark == nullptr) {
    return Status(1, "Alias data is not a bookmark");
  }

  auto url = CFURLCreateByResolvingBookmarkData(
      kCFAllocatorDefault, bookmark, 0, nullptr, nullptr, nullptr, nullptr);
  CFRelease(bookmark);
  if (url == nullptr) {
    return Status(1, "Alias data is not a URL bookmark");
  }

  auto replaced = CFURLCreateStringByReplacingPercentEscapes(
      kCFAllocatorDefault, CFURLGetString(url), CFSTR(""));
  CFRelease(url);
  if (replaced == nullptr) {
    return Status(1, "Failed to replace percent escapes.");
  }

  // Get the URL-formatted path.
  result = stringFromCFString(replaced);
  CFRelease(replaced);
  if (result.empty()) {
    return Status(1, "Return result is zero size");
  }
  if (result.length() > 6 && result.substr(0, 7) == "file://") {
    result = result.substr(7);
  }

  return Status(0, "OK");
}
Ejemplo n.º 8
0
inline CFPropertyListRef SQLite3StatementCreatePropertyListWithColumn(SQLite3StatementRef statement, CFIndex index, CFOptionFlags options, CFPropertyListFormat *format) {
  CFPropertyListRef result = NULL;
  CFDataRef data = SQLite3StatementCreateDataWithColumn(statement, index);
  if (data) {
    result = CFPropertyListCreateWithData(statement->allocator, data, options, format, NULL);
    CFRelease(data);
  }
  return result;
}
Ejemplo n.º 9
0
/**
 * Import the #plist_t structure from binary format.
 *
 * @param plist_bin a pointer to the xml buffer.
 * @param length length of the buffer to read.
 * @param plist a pointer to the imported plist.
 */
void plist_from_bin(const char *plist_bin, uint32_t length, plist_t * plist)
{
	*plist = NULL;
	
	CFDataRef data = CFDataCreate(kCFAllocatorDefault, (UInt8 *)plist_bin, length);
	if (data) {
		*plist = CFPropertyListCreateWithData(kCFAllocatorDefault, data, kCFPropertyListMutableContainers, NULL, NULL);
		CFRelease(data);
	}
}
Ejemplo n.º 10
0
KeyedDecoder::KeyedDecoder(const uint8_t* data, size_t size)
{
    auto cfData = adoptCF(CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, data, size, kCFAllocatorNull));

    if (auto rootDictionary = adoptCF(dynamic_cf_cast<CFDictionaryRef>(CFPropertyListCreateWithData(kCFAllocatorDefault, cfData.get(), kCFPropertyListImmutable, nullptr, nullptr))))
        m_rootDictionary = std::move(rootDictionary);
    else
        m_rootDictionary = adoptCF(CFDictionaryCreate(kCFAllocatorDefault, nullptr, nullptr, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
    m_dictionaryStack.append(m_rootDictionary.get());
}
Ejemplo n.º 11
0
/*! Creates a new target object from byte representation. */
iSCSISessionConfigRef iSCSITargetCreateWithData(CFDataRef data)
{
    CFPropertyListFormat format;
    
    iSCSITargetRef target = CFPropertyListCreateWithData(kCFAllocatorDefault,data,0,&format,NULL);

    if(format == kCFPropertyListBinaryFormat_v1_0)
        return target;

    CFRelease(target);
    return NULL;
}
Ejemplo n.º 12
0
/*! Creates a new connection config object from an external data representation.
 *  @param data data used to construct an iSCSI connection config object.
 *  @return an iSCSI connection configuration object
 *  or NULL if object creation failed */
iSCSIConnectionConfigRef iSCSIConnectionConfigCreateWithData(CFDataRef data)
{
    CFPropertyListFormat format;
    
    iSCSIConnectionConfigRef connCfg = CFPropertyListCreateWithData(kCFAllocatorDefault,data,0,&format,NULL);
    
    if(format == kCFPropertyListBinaryFormat_v1_0)
        return connCfg;
    
    CFRelease(connCfg);
    return NULL;
}
Ejemplo n.º 13
0
/*! Creates a new portal object from byte representation. */
iSCSIPortalRef iSCSIPortalCreateWithData(CFDataRef data)
{
    CFPropertyListFormat format;
    iSCSIPortalRef portal = CFPropertyListCreateWithData(
            kCFAllocatorDefault,data,kCFPropertyListImmutable,&format,NULL);
    
    if(format == kCFPropertyListBinaryFormat_v1_0)
        return portal;

    CFRelease(portal);
    return NULL;
}
Ejemplo n.º 14
0
/*! Creates a new authentication object from byte representation. */
iSCSIAuthRef iSCSIAuthCreateWithData(CFDataRef data)
{
    CFPropertyListFormat format;
    
    iSCSIAuthRef auth = CFPropertyListCreateWithData(kCFAllocatorDefault,data,0,&format,NULL);

    if(format == kCFPropertyListBinaryFormat_v1_0)
        return auth;
    
    CFRelease(auth);
    return NULL;
}
Ejemplo n.º 15
0
sdmmd_return_t SDMMD_ServiceReceiveMessage(SocketConnection handle, CFPropertyListRef *data) {
	CFDataRef dataBuffer = NULL;
	if (SDM_MD_CallSuccessful(SDMMD_ServiceReceive(handle, &dataBuffer))) {
		if (dataBuffer && CFDataGetLength(dataBuffer)) {
			*data = CFPropertyListCreateWithData(0, dataBuffer, kCFPropertyListImmutable, NULL, NULL);
		} else {
			*data = CFDictionaryCreateMutable(kCFAllocatorDefault, 0x0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
		}
		return kAMDSuccess;
	} else {
		return kAMDNotConnectedError;
	}
}
Ejemplo n.º 16
0
/*! Creates a discovery record from an external data representation.
 * @param data data used to construct an iSCSI discovery object.
 * @return an iSCSI discovery object or NULL if object creation failed */
iSCSIMutableDiscoveryRecRef iSCSIDiscoveryRecCreateMutableWithData(CFDataRef data)
{
    CFPropertyListFormat format;
    iSCSIMutableDiscoveryRecRef discoveryRec = (iSCSIMutableDiscoveryRecRef)
        CFPropertyListCreateWithData(kCFAllocatorDefault,data,kCFPropertyListImmutable,&format,NULL);
    
    if(format == kCFPropertyListBinaryFormat_v1_0)
        return discoveryRec;
    
    if(discoveryRec)
        CFRelease(discoveryRec);
    
    return NULL;
}
static CFDictionaryRef
__copyTemplates()
{
	CFBundleRef     bundle;
	CFErrorRef	error		= NULL;
	Boolean		ok;
	CFDictionaryRef templates;
	CFURLRef	url;
	CFDataRef       xmlTemplates    = NULL;

	bundle = _SC_CFBundleGet();
	if (bundle == NULL) {
		return NULL;
	}

	url = CFBundleCopyResourceURL(bundle, CFSTR("NetworkConfiguration"), CFSTR("plist"), NULL);
	if (url == NULL) {
		return NULL;
	}

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated"
	ok = CFURLCreateDataAndPropertiesFromResource(NULL, url, &xmlTemplates, NULL, NULL, NULL);
#pragma GCC diagnostic pop
	CFRelease(url);
	if (!ok || (xmlTemplates == NULL)) {
		return NULL;
	}

	// convert the XML data into a property list
	templates = CFPropertyListCreateWithData(NULL, xmlTemplates, kCFPropertyListImmutable, NULL, &error);
	CFRelease(xmlTemplates);
	if (templates == NULL) {
		if (error != NULL) {
			SCLog(TRUE, LOG_DEBUG, CFSTR("could not load SCNetworkConfiguration templates: %@"), error);
			CFRelease(error);
		}
		return NULL;
	}

	if (!isA_CFDictionary(templates)) {
		CFRelease(templates);
		return NULL;
	}

	return templates;
}
Ejemplo n.º 18
0
sdmmd_return_t SDMMD_ServiceReceiveMessage(SocketConnection handle, CFPropertyListRef *data) {
	CFDataRef dataBuffer = NULL;
	sdmmd_return_t result;
	
	result = SDMMD_ServiceReceive(handle, &dataBuffer);
	if (result == kAMDSuccess) {
		if (dataBuffer && CFDataGetLength(dataBuffer)) {
			*data = CFPropertyListCreateWithData(kCFAllocatorDefault, dataBuffer, kCFPropertyListImmutable, NULL, NULL);
		}
		else {
			*data = CFDictionaryCreateMutable(kCFAllocatorDefault, 0x0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
			result = kAMDInvalidResponseError;
		}
	}
	
	return result;
}
Ejemplo n.º 19
0
int main(int argc, char **argv) {
    
    if (argc != 3) {
        printf("Usage: plconvert <in file> <out file>\nIf the in file is an XML property list, convert to binary property list in out file. If the in file is a binary property list, convert to XML property list in out file.\n");
    } else {
        CFMutableDataRef plistData = createDataFromFile(argv[1]);
        if (!plistData) {
            printf("Unable to create data from file name: %s", argv[1]);
        } else {
            CFPropertyListFormat fmt;
            CFErrorRef err;
            CFPropertyListRef plist = CFPropertyListCreateWithData(kCFAllocatorSystemDefault, (CFDataRef)plistData, 0, &fmt, &err);
            if (!plist) {
                logIt(CFSTR("Unable to create property list from data: %@"), err);
            } else {
                logIt(CFSTR("Property list contents:\n%@"), plist);
                if (fmt == kCFPropertyListBinaryFormat_v1_0) {
                    logIt(CFSTR("Converting to XML property list at: %s"), argv[2]);
                    fmt = kCFPropertyListXMLFormat_v1_0;
                } else if (fmt == kCFPropertyListXMLFormat_v1_0) {
                    logIt(CFSTR("Converting to binary property list at: %s"), argv[2]);
                    fmt = kCFPropertyListBinaryFormat_v1_0;
                } else {
                    logIt(CFSTR("Unknown property list format! Not converting output format."));
                }
                
                CFDataRef outputData = CFPropertyListCreateData(kCFAllocatorSystemDefault, plist, fmt, 0, &err);
                if (!outputData) {
                    logIt(CFSTR("Unable to write property list to data: %@"), err);
                } else {
                    bool success = writeDataToFile(outputData, argv[2]);
                    if (!success) {
                        logIt(CFSTR("Unable to write data to file"));
                    }
                    CFRelease(outputData);
                }
                CFRelease(plist);
            }
            CFRelease(plistData);
        }
    }
}
Ejemplo n.º 20
0
bool ReceiptsDb::getInstalledPackageInfo(const char* identifier, ReceiptsDb::InstalledPackageInfo& info)
{
	std::string path;
	CFDataRef data;
	CFDateRef date;
	CFDictionaryRef plist;
	std::unique_ptr<Reader> fileReader;
	std::unique_ptr<UInt8[]> fileData;
	
	path = getReceiptsPath(identifier, ".plist");
	
	if (::access(path.c_str(), F_OK) != 0)
		return false;
	
	fileReader.reset(new FileReader(path));
	fileData.reset(new UInt8[fileReader->length()]);
	
	if (fileReader->read(fileData.get(), fileReader->length(), 0) != fileReader->length())
		throw std::runtime_error("Short read in getInstalledPackageInfo()");
	
	data = CFDataCreate(nullptr, fileData.get(), fileReader->length());
	fileData.reset(nullptr);
	
	plist = (CFDictionaryRef) CFPropertyListCreateWithData(nullptr, data,
			kCFPropertyListImmutable, nullptr, nullptr);
	CFRelease(data);
	
	if (plist == nullptr)
		throw std::runtime_error("Failed to parse plist in getInstalledPackageInfo()");
	
	info.identifier = cfstring2stdstring((CFStringRef) CFDictionaryGetValue(plist, CFSTR("PackageIdentifier")));
	info.version = cfstring2stdstring((CFStringRef) CFDictionaryGetValue(plist, CFSTR("PackageVersion")));
	info.prefixPath = cfstring2stdstring((CFStringRef) CFDictionaryGetValue(plist, CFSTR("InstallPrefixPath")));
	info.installProcessName = cfstring2stdstring((CFStringRef) CFDictionaryGetValue(plist, CFSTR("InstallProcessName")));
	info.packageFileName = cfstring2stdstring((CFStringRef) CFDictionaryGetValue(plist, CFSTR("PackageFileName")));
	
	date = (CFDateRef) CFDictionaryGetValue(plist, CFSTR("InstallDate"));
	info.installDate = CFDateGetAbsoluteTime(date);
	
	CFRelease(plist);
	return true;
}
/*! Creates a dictionary of connection parameters for the connection associated
 *  with the specified target and portal, if one exists.
 *  @param handle a handle to a daemon connection.
 *  @param target the target associated with the the specified portal.
 *  @param portal the portal to check for active connections to generate
 *  a dictionary of connection parameters.
 *  @return a dictionary of connection properties. */
CFDictionaryRef iSCSIDaemonCreateCFPropertiesForConnection(iSCSIDaemonHandle handle,
                                                           iSCSITargetRef target,
                                                           iSCSIPortalRef portal)
{
    // Validate inputs
    if(handle < 0 || !target || !portal)
        return NULL;

    CFDictionaryRef properties = NULL;
    CFDataRef targetData = iSCSITargetCreateData(target);
    CFDataRef portalData = iSCSIPortalCreateData(portal);

    // Send command to daemon
    iSCSIDMsgCreateCFPropertiesForConnectionCmd cmd = iSCSIDMsgCreateCFPropertiesForConnectionCmdInit;

    cmd.targetLength = (UInt32)CFDataGetLength(targetData);
    cmd.portalLength = (UInt32)CFDataGetLength(portalData);

    errno_t error = iSCSIDaemonSendMsg(handle,(iSCSIDMsgGeneric *)&cmd,
                                       targetData,portalData,NULL);
    CFRelease(targetData);
    CFRelease(portalData);

    iSCSIDMsgCreateCFPropertiesForConnectionRsp rsp;
    
    if(!error)
        error = iSCSIDaemonRecvMsg(handle,(iSCSIDMsgGeneric*)&rsp,NULL);
    
    if(!error) {
        CFDataRef data = NULL;
        error = iSCSIDaemonRecvMsg(handle,0,&data,rsp.dataLength,NULL);
        
        if(!error && data) {
            CFPropertyListFormat format;
            properties = CFPropertyListCreateWithData(kCFAllocatorDefault,data,0,&format,NULL);
            CFRelease(data);
        }
    }
    return properties;
}
/*! Creates an array of active portal objects.
 *  @param target the target to retrieve active portals.
 *  @param handle a handle to a daemon connection.
 *  @return an array of active target objects or NULL if no targets are active. */
CFArrayRef iSCSIDaemonCreateArrayOfActivePortalsForTarget(iSCSIDaemonHandle handle,
                                                          iSCSITargetRef target)
{
    // Validate inputs
    if(handle < 0)
        return NULL;

    CFArrayRef activePortals = NULL;
    errno_t error = 0;

    // Send command to daemon
    iSCSIDMsgCreateArrayOfActivePortalsForTargetCmd cmd = iSCSIDMsgCreateArrayOfActivePortalsForTargetCmdInit;

    if(send(handle,&cmd,sizeof(cmd),0) != sizeof(cmd))
        error = EIO;
    
    iSCSIDMsgCreateArrayOfActivePortalsForTargetRsp rsp;
    
    if(!error)
        error = iSCSIDaemonRecvMsg(handle,(iSCSIDMsgGeneric*)&rsp,NULL);

    if(!error) {
        CFDataRef data = NULL;
        error = iSCSIDaemonRecvMsg(handle,0,&data,rsp.dataLength,NULL);

        if(!error && data) {
            CFPropertyListFormat format;
            activePortals = CFPropertyListCreateWithData(kCFAllocatorDefault,data,0,&format,NULL);
            CFRelease(data);

            if(format != kCFPropertyListBinaryFormat_v1_0) {
                if(activePortals) {
                    CFRelease(activePortals);
                    activePortals = NULL;
                }
            }
        }
    }
    return activePortals;
}
CFStringRef createXMLStringFromWebArchiveData(CFDataRef webArchiveData)
{
    CFErrorRef error = 0;
    CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
    RetainPtr<CFMutableDictionaryRef> propertyList = adoptCF((CFMutableDictionaryRef)CFPropertyListCreateWithData(kCFAllocatorDefault, webArchiveData, kCFPropertyListMutableContainersAndLeaves, &format, &error));

    if (!propertyList) {
        if (error)
            return CFErrorCopyDescription(error);
        return static_cast<CFStringRef>(CFRetain(CFSTR("An unknown error occurred converting data to property list.")));
    }

    RetainPtr<CFMutableArrayRef> resources = adoptCF(CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks));
    CFArrayAppendValue(resources.get(), propertyList.get());

    while (CFArrayGetCount(resources.get())) {
        RetainPtr<CFMutableDictionaryRef> resourcePropertyList = (CFMutableDictionaryRef)CFArrayGetValueAtIndex(resources.get(), 0);
        CFArrayRemoveValueAtIndex(resources.get(), 0);

        CFMutableDictionaryRef mainResource = (CFMutableDictionaryRef)CFDictionaryGetValue(resourcePropertyList.get(), CFSTR("WebMainResource"));
        normalizeWebResourceURL((CFMutableStringRef)CFDictionaryGetValue(mainResource, CFSTR("WebResourceURL")));
        convertWebResourceDataToString(mainResource);

        // Add subframeArchives to list for processing
        CFMutableArrayRef subframeArchives = (CFMutableArrayRef)CFDictionaryGetValue(resourcePropertyList.get(), CFSTR("WebSubframeArchives")); // WebSubframeArchivesKey in WebArchive.m
        if (subframeArchives)
            CFArrayAppendArray(resources.get(), subframeArchives, CFRangeMake(0, CFArrayGetCount(subframeArchives)));

        CFMutableArrayRef subresources = (CFMutableArrayRef)CFDictionaryGetValue(resourcePropertyList.get(), CFSTR("WebSubresources")); // WebSubresourcesKey in WebArchive.m
        if (!subresources)
            continue;

        CFIndex subresourcesCount = CFArrayGetCount(subresources);
        for (CFIndex i = 0; i < subresourcesCount; ++i) {
            CFMutableDictionaryRef subresourcePropertyList = (CFMutableDictionaryRef)CFArrayGetValueAtIndex(subresources, i);
            normalizeWebResourceURL((CFMutableStringRef)CFDictionaryGetValue(subresourcePropertyList, CFSTR("WebResourceURL")));
            convertWebResourceResponseToDictionary(subresourcePropertyList);
            convertWebResourceDataToString(subresourcePropertyList);
        }

        // Sort the subresources so they're always in a predictable order for the dump
        CFArraySortValues(subresources, CFRangeMake(0, CFArrayGetCount(subresources)), compareResourceURLs, 0);
    }

    error = 0;

    RetainPtr<CFDataRef> xmlData = adoptCF(CFPropertyListCreateData(kCFAllocatorDefault, propertyList.get(), kCFPropertyListXMLFormat_v1_0, 0, &error));

    if (!xmlData) {
        if (error)
            return CFErrorCopyDescription(error);
        return static_cast<CFStringRef>(CFRetain(CFSTR("An unknown error occurred converting property list to data.")));
    }

    RetainPtr<CFStringRef> xmlString = adoptCF(CFStringCreateFromExternalRepresentation(kCFAllocatorDefault, xmlData.get(), kCFStringEncodingUTF8));
    RetainPtr<CFMutableStringRef> string = adoptCF(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, xmlString.get()));

    // Replace "Apple Computer" with "Apple" in the DTD declaration.
    CFStringFindAndReplace(string.get(), CFSTR("-//Apple Computer//"), CFSTR("-//Apple//"), CFRangeMake(0, CFStringGetLength(string.get())), 0);

    return string.leakRef();
}
Ejemplo n.º 24
0
void	CASettingsStorage::RefreshSettings()
{
	//	if this storage is only supporting a single file, there is no need to hit the disk unless
	//	required to by it being the first time or if the refresh is specifically forced for some reason
	if(!mIsSingleProcessOnly || (mSettingsCache == NULL) || ((mSettingsCacheTime.tv_sec == 0) && (mSettingsCacheTime.tv_nsec == 0)) || mSettingsCacheForceRefresh)
	{
		//	first, we need to stat the file to check the mod date, this has the side effect of also
		//	telling us if the file exisits
		struct stat theFileInfo;
		int theStatError = stat(mSettingsFilePath, &theFileInfo);
		
		//	we use this boolean to make error recovery easier since we need a case for when there's no file anyway
		bool theSettingsWereCached = false;
		bool theSettingsNeedSaving = true;
		
		if(theStatError == 0)
		{
			//	stat says there is something there, only have to do work if we either don't have a cache or the cache is out of date
			if((mSettingsCache == NULL) || (mSettingsCacheTime < theFileInfo.st_mtimespec) || mSettingsCacheForceRefresh)
			{
				//	open the file
				FILE* theFile = fopen(mSettingsFilePath, "r");
				if(theFile != NULL)
				{
					//	lock the file (this call blocks until the lock is taken)
					int theError = flock(fileno(theFile), LOCK_EX);
					if(theError == 0)
					{
						//	get the length of the file
						fseek(theFile, 0, SEEK_END);
						size_t theFileLength = ftell(theFile);
						fseek(theFile, 0, SEEK_SET);
						
						if(theFileLength > 0)
						{
							//	allocate a block of memory to hold the data in the file
							CAAutoFree<Byte> theRawFileData(theFileLength);
							
							//	read all the data in
							fread(static_cast<Byte*>(theRawFileData), theFileLength, 1, theFile);
							
							//	release the lock
							flock(fileno(theFile), LOCK_UN);
							
							//	put it into a CFData object
							CACFData theRawFileDataCFData(static_cast<Byte*>(theRawFileData), static_cast<UInt32>(theFileLength));
							
							//	get rid of the existing cache
							if(mSettingsCache != NULL)
							{
								CFRelease(mSettingsCache);
								mSettingsCache = NULL;
							}
							
							//	parse the data as a property list
							mSettingsCache = (CFMutableDictionaryRef)CFPropertyListCreateWithData(NULL, theRawFileDataCFData.GetCFData(), kCFPropertyListMutableContainersAndLeaves, NULL, NULL);
							
							//	check to be sure we parsed a plist out of the file
							if(mSettingsCache != NULL)
							{
								//	save the date of the cache
								mSettingsCacheTime = theFileInfo.st_mtimespec;
								
								//	mark that we're done
								theSettingsWereCached = true;
								theSettingsNeedSaving = false;
							}
						}
					}
					
					//	close the file
					fclose(theFile);
					mSettingsCacheForceRefresh = false;
				}
			}
			else
			{
				//	nothing to do since the file was older than the cached data
				theSettingsNeedSaving = false;
				theSettingsWereCached = true;
			}
		}
		
		//	if there was a failure, we need to clean up 
		if((theStatError != 0) || theSettingsNeedSaving || !theSettingsWereCached)
		{
			//	we get here if either there isn't a file or something wacky happenned while parsing it
			//	all we do here is make sure that the member variables are set to their initial values
			if(mSettingsCache != NULL)
			{
				CFRelease(mSettingsCache);
				mSettingsCache = NULL;
			}
			mSettingsCache = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
			
			mSettingsCacheTime.tv_sec = 0;
			mSettingsCacheTime.tv_nsec = 0;
			
			if((theStatError != 0) || theSettingsNeedSaving)
			{
				SaveSettings();
			}
		}
	}
}
void setupAUGraph(MyMIDIPlayer *player) {
	
	CheckError(NewAUGraph(&player->graph),
			   "Couldn't open AU Graph");
	
	// generate description that will match our output device (speakers)
	AudioComponentDescription outputcd = {0};
	outputcd.componentType = kAudioUnitType_Output;
	outputcd.componentSubType = kAudioUnitSubType_DefaultOutput;
	outputcd.componentManufacturer = kAudioUnitManufacturer_Apple;
	
	// adds a node with above description to the graph
	AUNode outputNode;
	CheckError(AUGraphAddNode(player->graph, &outputcd, &outputNode),
			   "AUGraphAddNode[kAudioUnitSubType_DefaultOutput] failed");
	
	
	AudioComponentDescription instrumentcd = {0};
	instrumentcd.componentManufacturer = kAudioUnitManufacturer_Apple;
	instrumentcd.componentType = kAudioUnitType_MusicDevice;
	instrumentcd.componentSubType = kAudioUnitSubType_Sampler;  // changed!
	
	AUNode instrumentNode;
	CheckError(AUGraphAddNode(player->graph, &instrumentcd, &instrumentNode),
			   "AUGraphAddNode[kAudioUnitSubType_DLSSynth] failed");
	
	// opening the graph opens all contained audio units but does not allocate any resources yet
	CheckError(AUGraphOpen(player->graph),
			   "AUGraphOpen failed");
	
	// get the reference to the AudioUnit object for the instrument graph node
	CheckError(AUGraphNodeInfo(player->graph, instrumentNode, NULL, &player->instrumentUnit),
			   "AUGraphNodeInfo failed");
	
	// connect the output source of the instrument AU to the input source of the output node
	CheckError(AUGraphConnectNodeInput(player->graph, instrumentNode, 0, outputNode, 0),
			   "AUGraphConnectNodeInput");
	
	// now initialize the graph (causes resources to be allocated)
	CheckError(AUGraphInitialize(player->graph),
			   "AUGraphInitialize failed");
	
	
	// configure the AUSampler
	// 2nd parameter obviously needs to be a full path on your system, and 3rd param is its length in characters
	CFURLRef presetURL = CFURLCreateFromFileSystemRepresentation(
						    kCFAllocatorDefault,
							"/Users/cadamson/Library/Audio/Presets/Apple/AUSampler/ch12-aupreset.aupreset",
							77,
							false);
	
	// load preset file into a CFDataRef
	CFDataRef presetData = NULL;
	SInt32 errorCode = noErr;
	Boolean gotPresetData =
	CFURLCreateDataAndPropertiesFromResource(kCFAllocatorSystemDefault,
											 presetURL,
											 &presetData,
											 NULL,
											 NULL,
											 &errorCode);
	CheckError(errorCode, "couldn't load .aupreset data");
	CheckError(!gotPresetData, "couldn't load .aupreset data");
	
	// convert this into a property list
	CFPropertyListFormat presetPlistFormat = {0};
	CFErrorRef presetPlistError = NULL;
	CFPropertyListRef presetPlist = CFPropertyListCreateWithData(kCFAllocatorSystemDefault,
																 presetData,
																 kCFPropertyListImmutable,
																 &presetPlistFormat, 
																 &presetPlistError);
	if (presetPlistError) {
		printf ("Couldn't create plist object for .aupreset");
		return;
	}
	
	// set this plist as the kAudioUnitProperty_ClassInfo on _auSampler
	if (presetPlist) {
		CheckError(AudioUnitSetProperty(player->instrumentUnit,
										kAudioUnitProperty_ClassInfo,
										kAudioUnitScope_Global,
										0,
										&presetPlist, 
										sizeof(presetPlist)),
				   "Couldn't set aupreset plist as sampler's class info");
	}

	
	
}
Ejemplo n.º 26
0
__private_extern__ void
__SCPreferencesAccess(SCPreferencesRef	prefs)
{
	CFAllocatorRef		allocator	= CFGetAllocator(prefs);
	int			fd		= -1;
	SCPreferencesPrivateRef	prefsPrivate	= (SCPreferencesPrivateRef)prefs;
	struct stat		statBuf;

	if (prefsPrivate->accessed) {
		// if preference data has already been accessed
		return;
	}

	if (!prefsPrivate->authorizationRequired) {
		if (access(prefsPrivate->path, R_OK) == 0) {
			fd = open(prefsPrivate->path, O_RDONLY, 0644);
		} else {
			fd = -1;
		}
	} else {
		errno = EACCES;
	}
	if (fd != -1) {
		// create signature
		if (fstat(fd, &statBuf) == -1) {
			SCLog(TRUE, LOG_ERR, CFSTR("__SCPreferencesAccess fstat() failed: %s"), strerror(errno));
			bzero(&statBuf, sizeof(statBuf));
		}
	} else {
		switch (errno) {
			case ENOENT :
				/* no preference data, start fresh */
				break;
			case EPERM  :
			case EACCES :
				if (prefsPrivate->authorizationData != NULL) {
					if (__SCPreferencesAccess_helper(prefs)) {
						goto done;
					} else {
						SCLog(TRUE, LOG_ERR,
						      CFSTR("__SCPreferencesAccess_helper() failed: %s"),
						      SCErrorString(SCError()));
					}
					break;
				}
				// fall through
			default :
				SCLog(TRUE, LOG_ERR, CFSTR("__SCPreferencesAccess open() failed: %s"), strerror(errno));
				break;
		}
		bzero(&statBuf, sizeof(statBuf));
	}

	if (prefsPrivate->signature != NULL) CFRelease(prefsPrivate->signature);
	prefsPrivate->signature = __SCPSignatureFromStatbuf(&statBuf);

	if (statBuf.st_size > 0) {
		CFDictionaryRef		dict;
		CFErrorRef		error	= NULL;
		CFMutableDataRef	xmlData;

		/*
		 * extract property list
		 */
		xmlData = CFDataCreateMutable(allocator, (CFIndex)statBuf.st_size);
		CFDataSetLength(xmlData, (CFIndex)statBuf.st_size);
		if (read(fd, (void *)CFDataGetBytePtr(xmlData), (CFIndex)statBuf.st_size) != (CFIndex)statBuf.st_size) {
			/* corrupt prefs file, start fresh */
			SCLog(_sc_verbose, LOG_DEBUG, CFSTR("__SCPreferencesAccess read(): could not load preference data."));
			CFRelease(xmlData);
			xmlData = NULL;
			goto done;
		}

		/*
		 * load preferences
		 */
		dict = CFPropertyListCreateWithData(allocator, xmlData, kCFPropertyListImmutable, NULL, &error);
		CFRelease(xmlData);
		if (dict == NULL) {
			/* corrupt prefs file, start fresh */
			if (error != NULL) {
				SCLog(TRUE, LOG_ERR,
				      CFSTR("__SCPreferencesAccess CFPropertyListCreateWithData(): %@"),
				      error);
				CFRelease(error);
			}
			goto done;
		}

		/*
		 * make sure that we've got a dictionary
		 */
		if (!isA_CFDictionary(dict)) {
			/* corrupt prefs file, start fresh */
			SCLog(_sc_verbose, LOG_DEBUG, CFSTR("__SCPreferencesAccess CFGetTypeID(): not a dictionary."));
			CFRelease(dict);
			goto done;
		}

		prefsPrivate->prefs = CFDictionaryCreateMutableCopy(allocator, 0, dict);
		CFRelease(dict);
	}

    done :

	if (fd != -1) {
		(void) close(fd);
	}

	if (prefsPrivate->prefs == NULL) {
		/*
		 * new file, create empty preferences
		 */
//		SCLog(_sc_verbose, LOG_DEBUG, CFSTR("__SCPreferencesAccess(): creating new preferences file."));
		prefsPrivate->prefs = CFDictionaryCreateMutable(allocator,
								0,
								&kCFTypeDictionaryKeyCallBacks,
								&kCFTypeDictionaryValueCallBacks);
		prefsPrivate->changed = TRUE;
	}

	prefsPrivate->accessed = TRUE;
	return;
}
Ejemplo n.º 27
0
/* OS X only: __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA) */
OSStatus
SecTrustSetOptions(SecTrustRef trustRef, SecTrustOptionFlags options)
{
	/* bridge to support API functionality for legacy callers */
	OSStatus status = errSecSuccess;
	CFDataRef encodedExceptions = SecTrustCopyExceptions(trustRef);
	CFArrayRef exceptions = NULL,
            oldExceptions = SecTrustGetTrustExceptionsArray(trustRef);

	if (encodedExceptions) {
		exceptions = (CFArrayRef)CFPropertyListCreateWithData(kCFAllocatorDefault,
			encodedExceptions, kCFPropertyListImmutable, NULL, NULL);
		CFRelease(encodedExceptions);
		encodedExceptions = NULL;
	}

	if (exceptions && CFGetTypeID(exceptions) != CFArrayGetTypeID()) {
		CFRelease(exceptions);
		exceptions = NULL;
	}

	if (oldExceptions && exceptions &&
		CFArrayGetCount(oldExceptions) > CFArrayGetCount(exceptions)) {
		oldExceptions = NULL;
	}

	/* verify both exceptions are for the same leaf */
	if (oldExceptions && exceptions && CFArrayGetCount(oldExceptions) > 0) {
		CFDictionaryRef oldLeafExceptions = (CFDictionaryRef)CFArrayGetValueAtIndex(oldExceptions, 0);
		CFDictionaryRef leafExceptions = (CFDictionaryRef)CFArrayGetValueAtIndex(exceptions, 0);
		CFDataRef oldDigest = (CFDataRef)CFDictionaryGetValue(oldLeafExceptions, CFSTR("SHA1Digest"));
		CFDataRef digest = (CFDataRef)CFDictionaryGetValue(leafExceptions, CFSTR("SHA1Digest"));
		if (!oldDigest || !digest || !CFEqual(oldDigest, digest)) {
			oldExceptions = NULL;
		}
	}

	/* add only those exceptions which are allowed by the supplied options */
	if (exceptions) {
		CFMutableArrayRef filteredExceptions = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
		CFIndex i, exceptionCount = (filteredExceptions) ? CFArrayGetCount(exceptions) : 0;

		for (i = 0; i < exceptionCount; ++i) {
			CFDictionaryRef exception = (CFDictionaryRef)CFArrayGetValueAtIndex(exceptions, i);
			CFDictionaryRef oldException = NULL;
			if (oldExceptions && i < CFArrayGetCount(oldExceptions)) {
				oldException = (CFDictionaryRef)CFArrayGetValueAtIndex(oldExceptions, i);
			}
			CFMutableDictionaryRef filteredException = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks,
																				 &kCFTypeDictionaryValueCallBacks);
			if (exception && filteredException) {
				SecExceptionFilterContext filterContext = { options, i, trustRef, filteredException, oldException };
				CFDictionaryApplyFunction(exception, filter_exception, &filterContext);
				CFArrayAppendValue(filteredExceptions, filteredException);
				CFRelease(filteredException);
			}
		}

		if (filteredExceptions) {
			CFIndex filteredCount = CFArrayGetCount(filteredExceptions);
			/* remove empty trailing entries to match iOS behavior */
			for (i = filteredCount; i-- > 1;) {
				CFDictionaryRef exception = (CFDictionaryRef)CFArrayGetValueAtIndex(filteredExceptions, i);
				if (CFDictionaryGetCount(exception) == 0) {
					CFArrayRemoveValueAtIndex(filteredExceptions, i);
				} else {
					break;
				}
			}
			encodedExceptions = CFPropertyListCreateData(kCFAllocatorDefault,
				filteredExceptions, kCFPropertyListBinaryFormat_v1_0, 0, NULL);
			CFRelease(filteredExceptions);

			SecTrustSetExceptions(trustRef, encodedExceptions);
			CFRelease(encodedExceptions);
		}
		CFRelease(exceptions);
	}

#if SECTRUST_DEPRECATION_WARNINGS
	bool displayModifyMsg = false;
	bool displayNetworkMsg = false;
	bool displayPolicyMsg = false;
	const char *baseMsg = "WARNING: SecTrustSetOptions called with";
	const char *modifyMsg = "Use SecTrustSetExceptions and SecTrustCopyExceptions to modify default trust results.";
	const char *networkMsg = "Use SecTrustSetNetworkFetchAllowed to specify whether missing certificates can be fetched from the network.";
	const char *policyMsg = "Use SecPolicyCreateRevocation to specify revocation policy requirements.";

	if (options & kSecTrustOptionAllowExpired) {
		syslog(LOG_ERR, "%s %s.", baseMsg, "kSecTrustOptionAllowExpired");
		displayModifyMsg = true;
	}
	if (options & kSecTrustOptionAllowExpiredRoot) {
		syslog(LOG_ERR, "%s %s.", baseMsg, "kSecTrustOptionAllowExpiredRoot");
		displayModifyMsg = true;
	}
	if (options & kSecTrustOptionFetchIssuerFromNet) {
		syslog(LOG_ERR, "%s %s.", baseMsg, "kSecTrustOptionFetchIssuerFromNet");
		displayNetworkMsg = true;
	}
	if (options & kSecTrustOptionRequireRevPerCert) {
		syslog(LOG_ERR, "%s %s.", baseMsg, "kSecTrustOptionRequireRevPerCert");
		displayPolicyMsg = true;
	}
	if (displayModifyMsg || displayNetworkMsg || displayPolicyMsg) {
		syslog(LOG_ERR, "%s %s %s",
			(displayModifyMsg) ? modifyMsg : "",
			(displayNetworkMsg) ? networkMsg : "",
			(displayPolicyMsg) ? policyMsg : "");
	}
#endif

	return status;
}
Ejemplo n.º 28
0
//-----------------------------------------------------------------------------
bool LoadAsioLibInfo(CFURLRef asioLibUrl, AsioLibInfo & buffer)
{
    CFDataRef           resourceData;
    SInt32              errorCode;
    Boolean             status;
    CFErrorRef          errorRef;
    CFPropertyListRef   propertyList;
    Boolean             ok;
    const void        * val;

    buffer.Number = 0;
	memset(buffer.Id,            '\0', ASIO_LIB_ID_CAPACITY);
	memset(buffer.DisplayName,   '\0', ASIO_LIB_DISPLAYNAME_CAPACITY);
    memset(buffer.Company,       '\0', ASIO_LIB_COMPANY_CAPACITY);
	memset(buffer.InstallFolder, '\0', ASIO_LIB_FOLDER_CAPACITY);
	memset(buffer.Architectures, '\0', ASIO_LIB_ARCHITECTURES_CAPACITY);

    status = CFURLCreateDataAndPropertiesFromResource(kCFAllocatorDefault, asioLibUrl, &resourceData, NULL, NULL, &errorCode);
    if ( ! status ) {
        return false;
    }

    errorRef     = NULL;
    propertyList = CFPropertyListCreateWithData(kCFAllocatorDefault, resourceData, kCFPropertyListImmutable, NULL, &errorRef);

    if (propertyList) {
        // name
        ok = CFDictionaryGetValueIfPresent((CFDictionaryRef)propertyList, CFSTR("Name"), &val);
        if (ok) {
            if (val) {
                /*ok =*/ CFStringGetCString((CFStringRef)val, buffer.Id, ASIO_LIB_ID_CAPACITY, kCFStringEncodingASCII);
            }
        }
        ok = CFDictionaryGetValueIfPresent((CFDictionaryRef)propertyList, CFSTR("Number"), &val);
        if (ok) {
            if (val) {
                /*ok =*/ CFNumberGetValue((CFNumberRef)val, kCFNumberSInt32Type, &buffer.Number);
            }
        }
        // number
        // display name
        ok = CFDictionaryGetValueIfPresent((CFDictionaryRef)propertyList, CFSTR("DisplayName"), &val);
        if (ok) {
            if (val) {
                /*ok =*/ CFStringGetCString((CFStringRef)val, buffer.DisplayName, ASIO_LIB_DISPLAYNAME_CAPACITY, kCFStringEncodingASCII);
            }
        }
        // company
        ok = CFDictionaryGetValueIfPresent((CFDictionaryRef)propertyList, CFSTR("Company"), &val);
        if (ok) {
            if (val) {
                /*ok =*/ CFStringGetCString((CFStringRef)val, buffer.Company, ASIO_LIB_COMPANY_CAPACITY, kCFStringEncodingASCII);
            }
        }
        // installation folder
        ok = CFDictionaryGetValueIfPresent((CFDictionaryRef)propertyList, CFSTR("InstallationFolder"), &val);
        if (ok) {
            if (val) {
                /*ok =*/ CFStringGetCString((CFStringRef)val, buffer.InstallFolder, ASIO_LIB_FOLDER_CAPACITY, kCFStringEncodingASCII);
            }
        }
        // build architectures
        ok = CFDictionaryGetValueIfPresent((CFDictionaryRef)propertyList, CFSTR("Architectures"), &val);
        if (ok) {
            if (val) {
                /*ok =*/ CFStringGetCString((CFStringRef)val, buffer.Architectures, ASIO_LIB_ARCHITECTURES_CAPACITY, kCFStringEncodingASCII);
            }
        }
    }

    // cleanup
    CFRelease(resourceData);
    if (errorRef) {
        CFRelease(errorRef);
    }
    if (propertyList) {
        CFRelease(propertyList);
    }

    // Id and DisplayName are mandatory, other fields are optional
    return (strlen(buffer.Id) > 0) && (strlen(buffer.DisplayName) > 0);
}
static CFStringRef _copyStringFromTable(CFBundleRef bundle, CFStringRef tableName, CFStringRef key, CFStringRef localizationName) {
    // Check the cache first. If it's not there, populate the cache and check again.
    
    __CFLock(&bundle->_lock);
    // Only consult the cache when a specific localization has not been requested. We only cache results for the preferred language as determined by normal bundle lookup rules.
    if (!localizationName && bundle->_stringTable) {
        CFDictionaryRef stringTable = (CFDictionaryRef)CFDictionaryGetValue(bundle->_stringTable, tableName);
        if (stringTable) {
            CFStringRef result = CFDictionaryGetValue(stringTable, key);
            if (result) {
                CFRetain(result);
            }
            __CFUnlock(&bundle->_lock);
            return result;
        }
    }

    // Not in the local cache, so load the table. Unlock so we don't hold the lock across file system access.
    __CFUnlock(&bundle->_lock);

    CFDictionaryRef stringsTable = NULL;
    CFURLRef stringsTableURL = NULL;
    CFURLRef stringsDictTableURL = NULL;
    
    // Find the resource URL.
    if (localizationName) {
        stringsTableURL = CFBundleCopyResourceURLForLocalization(bundle, tableName, _CFBundleStringTableType, NULL, localizationName);
        stringsDictTableURL = CFBundleCopyResourceURLForLocalization(bundle, tableName, _CFBundleStringDictTableType, NULL, localizationName);
    } else {
        stringsTableURL = CFBundleCopyResourceURL(bundle, tableName, _CFBundleStringTableType, NULL);
        stringsDictTableURL = CFBundleCopyResourceURL(bundle, tableName, _CFBundleStringDictTableType, NULL);
    }
    
    
    // Next, look on disk for the regular strings file.
    if (!stringsTable && stringsTableURL) {
        CFDataRef tableData = _CFDataCreateFromURL(stringsTableURL, NULL);
        if (tableData) {
            CFErrorRef error = NULL;
            stringsTable = (CFDictionaryRef)CFPropertyListCreateWithData(CFGetAllocator(bundle), tableData, kCFPropertyListImmutable, NULL, &error);
            CFRelease(tableData);
            
            if (stringsTable && CFDictionaryGetTypeID() != CFGetTypeID(stringsTable)) {
                os_log_error(_CFBundleLocalizedStringLogger(), "Unable to load .strings file: %@ / %@: Top-level object was not a dictionary", bundle, tableName);
                CFRelease(stringsTable);
                stringsTable = NULL;
            } else if (!stringsTable && error) {
                os_log_error(_CFBundleLocalizedStringLogger(), "Unable to load .strings file: %@ / %@: %@", bundle, tableName, error);
                CFRelease(error);
                error = NULL;
            }
        }
        
    }
    
    // Check for a .stringsdict file.
    if (stringsDictTableURL) {
        CFDataRef tableData = _CFDataCreateFromURL(stringsDictTableURL, NULL);
        if (tableData) {
            CFErrorRef error = NULL;
            CFDictionaryRef stringsDictTable = (CFDictionaryRef)CFPropertyListCreateWithData(CFGetAllocator(bundle), tableData, kCFPropertyListImmutable, NULL, &error);
            CFRelease(tableData);
            
            if (!stringsDictTable && error) {
                os_log_error(_CFBundleLocalizedStringLogger(), "Unable to load .stringsdict file: %@ / %@: %@", bundle, tableName, error);
                CFRelease(error);
                error = NULL;
            } else if (stringsDictTable && CFDictionaryGetTypeID() != CFGetTypeID(stringsDictTable)) {
                os_log_error(_CFBundleLocalizedStringLogger(), "Unable to load .stringsdict file: %@ / %@: Top-level object was not a dictionary", bundle, tableName);
                CFRelease(stringsDictTable);
                stringsDictTable = NULL;
            } else if (stringsDictTable) {
                // Post-process the strings table.
                CFMutableDictionaryRef mutableStringsDictTable;
                if (stringsTable) {
                    // Any strings that are in the stringsTable that are not in the stringsDict must be added to the stringsDict.
                    // However, any entry in the stringsDictTable must override the content from stringsTable.
                    
                    // Start by copying the stringsTable.
                    mutableStringsDictTable = CFDictionaryCreateMutableCopy(NULL, 0, stringsTable);
                    
                    // Replace any stringsTable entries with entries from stringsDictTable. This will override any entries from the original stringsTable if they existed.
                    CFDictionaryApplyFunction(stringsDictTable, __CFStringsDictMergeApplyFunction, mutableStringsDictTable);
                } else {
                    // Start with a copy of the stringsDictTable on its own.
                    mutableStringsDictTable = CFDictionaryCreateMutableCopy(NULL, 0, stringsDictTable);
                }
                
                CFRelease(stringsDictTable);

                if (stringsTable) CFRelease(stringsTable);
                // The new strings table is the result of all the transforms above.
                stringsTable = mutableStringsDictTable;
            }
        }
    }
    
    if (stringsTableURL) CFRelease(stringsTableURL);
    if (stringsDictTableURL) CFRelease(stringsDictTableURL);
    
    // Last resort: create an empty table
    if (!stringsTable) {
        os_log_debug(_CFBundleLocalizedStringLogger(), "Hit last resort and creating empty strings table");
        stringsTable = CFDictionaryCreate(CFGetAllocator(bundle), NULL, NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
    }
    
    // Insert the result into our local cache
    if ((!CFStringHasSuffix(tableName, CFSTR(".nocache")) || !_CFExecutableLinkedOnOrAfter(CFSystemVersionLeopard)) && localizationName == NULL) {
        // Take lock again, because this we will unlock after getting the value out of the table.
        __CFLock(&bundle->_lock);
        if (!bundle->_stringTable) bundle->_stringTable = CFDictionaryCreateMutable(CFGetAllocator(bundle), 0, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
        
        // If another thread beat us to setting this tableName, then we'll just replace it here.
        CFDictionarySetValue(bundle->_stringTable, tableName, stringsTable);
    } else {
        // Take lock again, because this we will unlock after getting the value out of the table.
        __CFLock(&bundle->_lock);
    }
    
    // Finally, fetch the result from the table
    CFStringRef result = CFDictionaryGetValue(stringsTable, key);
    if (result) {
        CFRetain(result);
    }
    __CFUnlock(&bundle->_lock);

    CFRelease(stringsTable);
    
    return result;
}
Ejemplo n.º 30
0
kern_return_t
_io_pm_schedule_repeat_event
(
    mach_port_t             server __unused,
    audit_token_t           token,
    vm_offset_t             flatPackage,
    mach_msg_type_number_t  packageLen,
    int                     action,
    int                     *return_code
)
{
    CFDictionaryRef     events = NULL;
    CFDictionaryRef     offEvents = NULL;
    CFDictionaryRef     onEvents = NULL;
    CFDataRef           dataRef = NULL;
    uid_t               callerEUID;
    SCPreferencesRef    prefs = 0;
    CFStringRef         prevOffType = NULL;
    CFStringRef         prevOnType = NULL;
    CFStringRef         newOffType = NULL;
    CFStringRef         newOnType = NULL;


    *return_code = kIOReturnSuccess;

    audit_token_to_au32(token, NULL, &callerEUID, NULL, NULL, NULL, NULL, NULL, NULL);

    dataRef = CFDataCreate(0, (const UInt8 *)flatPackage, packageLen);
    if (dataRef) {
        events = (CFDictionaryRef)CFPropertyListCreateWithData(0, dataRef, 0, NULL, NULL); 
    }

    if (!events) {
        *return_code = kIOReturnBadArgument;
        goto exit;
    }
    offEvents = isA_CFDictionary(CFDictionaryGetValue(
                                events, 
                                CFSTR(kIOPMRepeatingPowerOffKey)));
    onEvents = isA_CFDictionary(CFDictionaryGetValue(
                                events, 
                                CFSTR(kIOPMRepeatingPowerOnKey)));

    if( !is_valid_repeating_dictionary(offEvents) 
     || !is_valid_repeating_dictionary(onEvents) )
    {
        syslog(LOG_INFO, "PMCFGD: Invalid formatted repeating power event dictionary\n");
        *return_code = kIOReturnBadArgument;
        goto exit;
    }

    if((*return_code = createSCSession(&prefs, callerEUID, 1)) != kIOReturnSuccess)
        goto exit;


    /* Need to take a retain on these strings as these dictionaries get released below */
    prevOffType =  getRepeatingDictionaryType(repeatingPowerOff); CFRetain(prevOffType);
    prevOnType = getRepeatingDictionaryType(repeatingPowerOn); CFRetain(prevOnType);

    /*
     * Remove both off & on events first. If off or on event is not set thru this request,
     * then it is assumed that user is requesting to delete it.
     */
    if (repeatingPowerOff && isA_CFDictionary(repeatingPowerOff))
        CFRelease(repeatingPowerOff); 
    if (repeatingPowerOn && isA_CFDictionary(repeatingPowerOn))
        CFRelease(repeatingPowerOn); 

    repeatingPowerOff = repeatingPowerOn = NULL;


    if (offEvents) {
        repeatingPowerOff = CFDictionaryCreateMutableCopy(0,0,offEvents);
    }
    if (onEvents) {
        repeatingPowerOn = CFDictionaryCreateMutableCopy(0,0,onEvents);
    }


    if ((*return_code = updateRepeatEventsOnDisk(prefs)) != kIOReturnSuccess)
        goto exit;

    newOffType = getRepeatingDictionaryType(repeatingPowerOff);
    newOnType = getRepeatingDictionaryType(repeatingPowerOn);


    /* 
     * Re-schedule the modified event types in case these new events are earlier
     * than previously scheduled ones
     */
    schedulePowerEventType(prevOffType);
    schedulePowerEventType(prevOnType);

    if (!CFEqual(prevOffType, newOffType))
        schedulePowerEventType(newOffType);

    if (!CFEqual(prevOnType, newOnType))
        schedulePowerEventType(newOnType);


exit:
    if (prevOffType)
        CFRelease(prevOffType);
    if (prevOnType)
        CFRelease(prevOnType);

    if (dataRef)
        CFRelease(dataRef);
    if (events)
        CFRelease(events);
    destroySCSession(prefs, 1);

    vm_deallocate(mach_task_self(), flatPackage, packageLen);

    return KERN_SUCCESS;
}