コード例 #1
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;
}
コード例 #2
0
__private_extern__ kern_return_t _io_pm_hid_event_copy_history(
            mach_port_t     server,
            vm_offset_t     *array_data,
            mach_msg_type_number_t  *array_dataLen,
            int             *return_val)
{
    CFDataRef   sendData = NULL;

    sendData = CFPropertyListCreateData(0, gHIDEventHistory, kCFPropertyListXMLFormat_v1_0, 0, NULL);
    if (!sendData) {
        *return_val = kIOReturnError;
        goto exit;
    }

    *array_data = (vm_offset_t)CFDataGetBytePtr(sendData);
    *array_dataLen = (size_t)CFDataGetLength(sendData);
    vm_allocate(mach_task_self(), (vm_address_t *)array_data, *array_dataLen, TRUE);
    if (*array_data) {
        memcpy((void *)*array_data, CFDataGetBytePtr(sendData), *array_dataLen);
        *return_val = kIOReturnSuccess;
    }

    CFRelease(sendData);

    *return_val = kIOReturnSuccess;
exit:
    return KERN_SUCCESS;
}
コード例 #3
0
ファイル: client.c プロジェクト: aosm/bootp
static int
S_find_service(mach_port_t server, int argc, char * argv[])
{
    CFDataRef			data = NULL;
    CFDictionaryRef		dict;
    boolean_t			exact = FALSE;
    char *			method_name;
    if_name_t			if_name;
    kern_return_t		kret;
    inline_data_t 		service_id;
    unsigned int 		service_id_len = sizeof(service_id);
    ipconfig_status_t		status = ipconfig_status_success_e;
    void *			xml_data_ptr = NULL;
    int				xml_data_len = 0;

    strlcpy(if_name, argv[0], sizeof(if_name));
    argv++;
    argc--;
    if (argc > 1 && strcasecmp(argv[0], "exact") == 0) {
	exact = TRUE;
	argc--;
	argv++;
    }
    method_name = argv[0];
    argc--;
    argv++;
    dict = ConfigDictCreate(if_name, argc, argv, command_name, method_name,
			    FALSE);
    if (dict == NULL) {
	return (1);
    }
    data = CFPropertyListCreateData(NULL,
				    dict,
				    kCFPropertyListBinaryFormat_v1_0,
				    0,
				    NULL);
    if (data == NULL) {
	CFRelease(dict);
	fprintf(stderr, "failed to allocate memory\n");
	return (1);
    }
    xml_data_ptr = (void *)CFDataGetBytePtr(data);
    xml_data_len = (int)CFDataGetLength(data);
    kret = ipconfig_find_service(server, if_name, exact,
				 xml_data_ptr, xml_data_len,
				 service_id, &service_id_len, &status);
    my_CFRelease(&dict);
    my_CFRelease(&data);
    if (kret != KERN_SUCCESS) {
	mach_error("ipconfig_find_service failed", kret);
	return (1);
    }
    if (status != ipconfig_status_success_e) {
	fprintf(stderr, "ipconfig_find_service %s %s failed: %s\n",
		if_name, method_name, ipconfig_status_string(status));
	return (1);
    }
    printf("%.*s\n", service_id_len, service_id);
    return (0);
}
コード例 #4
0
ファイル: qsettings_mac.cpp プロジェクト: xjohncz/qt5
bool QConfFileSettingsPrivate::writePlistFile(const QString &fileName,
        const ParsedSettingsMap &map) const
{
    QVarLengthArray<QCFType<CFStringRef> > cfkeys(map.size());
    QVarLengthArray<QCFType<CFPropertyListRef> > cfvalues(map.size());
    int i = 0;
    ParsedSettingsMap::const_iterator j;
    for (j = map.constBegin(); j != map.constEnd(); ++j) {
        cfkeys[i] = macKey(j.key());
        cfvalues[i] = macValue(j.value());
        ++i;
    }

    QCFType<CFDictionaryRef> propertyList =
        CFDictionaryCreate(kCFAllocatorDefault,
                           reinterpret_cast<const void **>(cfkeys.data()),
                           reinterpret_cast<const void **>(cfvalues.data()),
                           CFIndex(map.size()),
                           &kCFTypeDictionaryKeyCallBacks,
                           &kCFTypeDictionaryValueCallBacks);

    QCFType<CFDataRef> xmlData = CFPropertyListCreateData(
                                     kCFAllocatorDefault, propertyList, kCFPropertyListXMLFormat_v1_0, 0, 0);

    SInt32 code;
    return CFURLWriteDataAndPropertiesToResource(urlFromFileName(fileName), xmlData, 0, &code);
}
コード例 #5
0
ファイル: cfutil.c プロジェクト: aosm/bootp
PRIVATE_EXTERN int
my_CFPropertyListWriteFile(CFPropertyListRef plist, const char * filename,
			   mode_t permissions)
{
    CFDataRef	data;
    int		ret;

    if (plist == NULL)
	return (0);

    data = CFPropertyListCreateData(NULL,
				    plist,
				    kCFPropertyListXMLFormat_v1_0,
				    0,
				    NULL);
    if (data == NULL) {
	return (0);
    }
    ret = write_file(filename, 
		     (const void *)CFDataGetBytePtr(data),
		     CFDataGetLength(data),
		     permissions);
    CFRelease(data);
    return (ret);
}
コード例 #6
0
sdmmd_return_t SDMMD_ServiceSendMessage(SocketConnection handle, CFPropertyListRef data, CFPropertyListFormat format) {
	CFErrorRef error;
	CFDataRef xmlData = CFPropertyListCreateData(kCFAllocatorDefault, data, format, 0, &error);
	sdmmd_return_t result = ((data) ? SDMMD_ServiceSend(handle, xmlData) : kAMDInvalidArgumentError);
	if (xmlData)
		CFRelease(xmlData);
	return result;
}
コード例 #7
0
PassRefPtr<SharedBuffer> KeyedEncoder::finishEncoding()
{
    RetainPtr<CFDataRef> data = adoptCF(CFPropertyListCreateData(kCFAllocatorDefault, m_rootDictionary.get(), kCFPropertyListBinaryFormat_v1_0, 0, nullptr));
    if (!data)
        return nullptr;

    return SharedBuffer::wrapCFData(data.get());
}
コード例 #8
0
inline SQLite3Status SQLite3StatementBindPropertyList(SQLite3StatementRef statement, CFIndex index, CFPropertyListRef value, CFPropertyListFormat format) {
  SQLite3Status status = kSQLite3StatusError;
  CFDataRef data = CFPropertyListCreateData(statement->allocator, value, format, 0, NULL);
  if (data) {
    status = SQLite3StatementBindData(statement, index, data);
    CFRelease(data);
  }
  return status;
}
コード例 #9
0
ファイル: iSCSIDaemon.c プロジェクト: bafomet/iSCSIInitiator
errno_t iSCSIDCreateArrayofActivePortalsForTarget(int fd,struct iSCSIDCmdCreateArrayOfActivePortalsForTarget * cmd)
{
    CFArrayRef sessionIds = iSCSICreateArrayOfSessionIds();
    CFIndex sessionCount = CFArrayGetCount(sessionIds);

    // Prepare an array to hold our targets
    CFMutableArrayRef activeTargets = CFArrayCreateMutable(kCFAllocatorDefault,
                                      sessionCount,
                                      &kCFTypeArrayCallBacks);

    // Get target object for each active session and add to array
    for(CFIndex idx = 0; idx < sessionCount; idx++)
    {
        iSCSITargetRef target = iSCSICreateTargetForSessionId((SID)CFArrayGetValueAtIndex(sessionIds,idx));
        CFArrayAppendValue(activeTargets,target);
        iSCSITargetRelease(target);
    }

    // Serialize and send array
    CFDataRef data = CFPropertyListCreateData(kCFAllocatorDefault,
                     (CFPropertyListRef) activeTargets,
                     kCFPropertyListBinaryFormat_v1_0,0,NULL);
    CFRelease(activeTargets);

    // Send response header
    struct iSCSIDRspCreateArrayOfActiveTargets rsp = iSCSIDRspCreateArrayOfActiveTargetsInit;
    if(data)
        rsp.dataLength = (UInt32)CFDataGetLength(data);
    else
        rsp.dataLength = 0;

    if(send(fd,&rsp,sizeof(rsp),0) != sizeof(rsp))
    {
        if(data)
            CFRelease(data);
        return EAGAIN;
    }

    if(data)
    {
        if(send(fd,CFDataGetBytePtr(data),rsp.dataLength,0) != rsp.dataLength)
        {
            CFRelease(data);
            return EAGAIN;
        }

        CFRelease(data);
    }
    return 0;
}
コード例 #10
0
ファイル: client.c プロジェクト: aosm/bootp
static int
S_remove_service(mach_port_t server, int argc, char * argv[])
{
    CFDataRef			data = NULL;
    CFDictionaryRef		dict;
    char *			method_name;
    if_name_t			if_name;
    kern_return_t		kret;
    ipconfig_status_t		status = ipconfig_status_success_e;
    void *			xml_data_ptr = NULL;
    int				xml_data_len = 0;

    strlcpy(if_name, argv[0], sizeof(if_name));
    method_name = argv[1];
    argv += 2;
    argc -= 2;

    dict = ConfigDictCreate(if_name, argc, argv, command_name, method_name,
			    FALSE);
    if (dict == NULL) {
	return (1);
    }
    data = CFPropertyListCreateData(NULL,
				    dict,
				    kCFPropertyListBinaryFormat_v1_0,
				    0,
				    NULL);
    if (data == NULL) {
	CFRelease(dict);
	fprintf(stderr, "failed to allocate memory\n");
	return (1);
    }
    xml_data_ptr = (void *)CFDataGetBytePtr(data);
    xml_data_len = (int)CFDataGetLength(data);
    kret = ipconfig_remove_service(server, if_name, xml_data_ptr, xml_data_len,
				   &status);
    my_CFRelease(&dict);
    my_CFRelease(&data);
    if (kret != KERN_SUCCESS) {
	mach_error("ipconfig_remove_service failed", kret);
	return (1);
    }
    if (status != ipconfig_status_success_e) {
	fprintf(stderr, "ipconfig_remove_service %s %s failed: %s\n",
		if_name, method_name, ipconfig_status_string(status));
	return (1);
    }
    return (0);
}
コード例 #11
0
ファイル: main.c プロジェクト: Frederikus/eid-mw
void StoreDictionaryInPlist(CFPropertyListRef propListRef, CFStringRef stringPlist, SInt32 *errorCode)
{
    CFErrorRef errorRef;
    CFURLRef fileURLRef = CFURLCreateWithFileSystemPath(kCFAllocatorDefault,stringPlist,kCFURLPOSIXPathStyle,false);
    
    CFDataRef dataRef = CFPropertyListCreateData(kCFAllocatorDefault, propListRef, kCFPropertyListXMLFormat_v1_0, 0, &errorRef);
    // Write the plist to the file.
    Boolean status = CFURLWriteDataAndPropertiesToResource(fileURLRef, dataRef, NULL, errorCode);
    if (!status) {
        //error
    }
    
    CFRelease(fileURLRef);
    CFRelease(dataRef);
}
コード例 #12
0
void	CASettingsStorage::SaveSettings()
{
	if(mSettingsCache != NULL)
	{
		//	make a CFData that contains the new settings
		CACFData theNewRawPrefsCFData(CFPropertyListCreateData(NULL, mSettingsCache, mSettingsCacheFormat, 0, NULL), true);
		
		//	open the file for writing
		FILE* theFile = fopen(mSettingsFilePath, "w+");
		if(theFile != NULL)
		{
			//	lock the file (this call blocks until the lock is taken)
			int theError = flock(fileno(theFile), LOCK_EX);
			if(theError == 0)
			{
				//	set the file access mode if necessary
				if(mSettingsFileAccessMode != 0)
				{
					fchmod(fileno(theFile), mSettingsFileAccessMode);
				}
				
				//	write the data
				fwrite(theNewRawPrefsCFData.GetDataPtr(), theNewRawPrefsCFData.GetSize(), 1, theFile);
				
				//	flush the file to be sure it is all on disk
				fflush(theFile);
				
				//	release the lock
				flock(fileno(theFile), LOCK_UN);
			
				//	close the file
				fclose(theFile);
				
				//	stat the file to get the mod date
				struct stat theFileInfo;
				stat(mSettingsFilePath, &theFileInfo);
				
				//	save the mod date
				mSettingsCacheTime = theFileInfo.st_mtimespec;
			}
			else
			{
				//	close the file
				fclose(theFile);
			}
		}
	}
}
コード例 #13
0
ファイル: plist.c プロジェクト: aburgh/usbmuxd
/**
 * Export the #plist_t structure to binary format.
 *
 * @param plist the root node to export
 * @param plist_bin a pointer to a char* buffer. This function allocates the memory,
 *            caller is responsible for freeing it.
 * @param length a pointer to an uint32_t variable. Represents the length of the allocated buffer.
 */
void plist_to_bin(plist_t plist, char **plist_bin, uint32_t * length)
{
	*plist_bin = NULL;
	*length = 0;

	CFDataRef data = CFPropertyListCreateData(kCFAllocatorDefault, plist, kCFPropertyListBinaryFormat_v1_0, 0, NULL);
	if (data) {
		*length = CFDataGetLength(data);
		*plist_bin = malloc(*length);
		if (*plist_bin)
			CFDataGetBytes(data, CFRangeMake(0, *length), (UInt8 *) *plist_bin);
		else
			*length = 0;
		
		CFRelease(data);
	}
}
コード例 #14
0
BOOL write_property_list( const char *path, CFPropertyListRef propertyList, CFPropertyListFormat format)
{
    CFDataRef data = NULL;
    CFStringRef pathstr = NULL;
    CFURLRef fileURL = NULL;
    CFErrorRef err = NULL;
    BOOL ret = FALSE;
    SInt32 errorCode;

    pathstr = CFStringCreateWithFileSystemRepresentation(NULL, path);
    if (!pathstr)
        goto cleanup;

    fileURL = CFURLCreateWithFileSystemPath( kCFAllocatorDefault,
            pathstr,
            kCFURLPOSIXPathStyle,
            false );
    if (!fileURL)
        goto cleanup;

    data = CFPropertyListCreateData(NULL, propertyList, format, 0, &err);
    if (!data)
        goto cleanup;

    ret = CFURLWriteDataAndPropertiesToResource (
            fileURL,
            data,
            NULL,
            &errorCode);

cleanup:
    if (pathstr)
        CFRelease(pathstr);
    if (fileURL)
        CFRelease(fileURL);
    if (data)
        CFRelease(data);
    if (err)
        CFRelease(err);

    return ret;
}
コード例 #15
0
ファイル: plconvert.c プロジェクト: 0oneo/CF-855.11
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);
        }
    }
}
コード例 #16
0
ファイル: iSCSIDaemon.c プロジェクト: bafomet/iSCSIInitiator
errno_t iSCSIDCreateCFPropertiesForConnection(int fd,struct iSCSIDCmdCreateCFPropertiesForConnection * cmd)
{
    // Grab objects from stream
    iSCSITargetRef target = iSCSIDCreateObjectFromSocket(fd,cmd->targetLength,
                            (void *(* )(CFDataRef))&iSCSITargetCreateWithData);
    iSCSIPortalRef portal = iSCSIDCreateObjectFromSocket(fd,cmd->portalLength,
                            (void *(* )(CFDataRef))&iSCSIPortalCreateWithData);

    if(!target || !portal)
        return EINVAL;

    errno_t error = 0;
    CFDictionaryRef properties = iSCSICreateCFPropertiesForConnection(target,portal);

    // Send back response
    iSCSIDRspCreateCFPropertiesForConnection rsp = iSCSIDRspCreateCFPropertiesForConnectionInit;

    CFDataRef data = NULL;
    if(properties) {
        data = CFPropertyListCreateData(kCFAllocatorDefault,
                                        (CFPropertyListRef)properties,
                                        kCFPropertyListBinaryFormat_v1_0,0,NULL);

        rsp.dataLength = (UInt32)CFDataGetLength(data);
        CFRelease(properties);
    }
    else
        rsp.dataLength = 0;

    if(send(fd,&rsp,sizeof(rsp),0) != sizeof(rsp))
        error = EAGAIN;

    // Send data if any
    if(data && !error) {
        if(send(fd,CFDataGetBytePtr(data),CFDataGetLength(data),0) != CFDataGetLength(data))
            error =  EAGAIN;

        CFRelease(data);
    }

    return error;
}
コード例 #17
0
IOReturn IOPMScheduleRepeatingPowerEvent(CFDictionaryRef events)
{
    IOReturn                    ret = kIOReturnError;
    CFDataRef                   flatPackage = NULL;
    kern_return_t               rc = KERN_SUCCESS;
    mach_port_t                 pm_server = MACH_PORT_NULL;
    
    // Validate our inputs
    if(!isA_CFDictionary(events)) return kIOReturnBadArgument;

    
    if(kIOReturnSuccess != _pm_connect(&pm_server)) {
        ret = kIOReturnInternalError;
        goto exit;
    }

    flatPackage = CFPropertyListCreateData(0, events,
                          kCFPropertyListBinaryFormat_v1_0, 0, NULL );

    if ( !flatPackage ) {
        ret = kIOReturnBadArgument;
        goto exit;
    }

    rc = io_pm_schedule_repeat_event(pm_server, (vm_offset_t)CFDataGetBytePtr(flatPackage),
            CFDataGetLength(flatPackage), 1, &ret);

    if (rc != KERN_SUCCESS)
        ret = kIOReturnInternalError;
 
exit:

    if (MACH_PORT_NULL != pm_server) {
        _pm_disconnect(pm_server);
    }
    if(flatPackage) CFRelease(flatPackage);

    return ret;
}
コード例 #18
0
ファイル: server.c プロジェクト: Apple-FOSS-Mirror/Security
/* AUDIT[securityd](done):
   reply (checked by mig) is a caller provided mach_port.
   request_id (checked by mig) is caller provided value, that matches the
       mig entry for the server function.
 */
kern_return_t securityd_server_send_reply(mach_port_t reply,
    uint32_t request_id, OSStatus status, CFTypeRef args_out) {
    CFDataRef data_out = NULL;
    if (args_out) {
#ifndef NDEBUG
        CFDataRef query_debug = CFPropertyListCreateXMLData(kCFAllocatorDefault,
            args_out);
        secdebug("client", "securityd response: %.*s\n",
            CFDataGetLength(query_debug), CFDataGetBytePtr(query_debug));
        CFReleaseSafe(query_debug);
#endif
        CFErrorRef error = NULL;
        data_out = CFPropertyListCreateData(kCFAllocatorDefault, args_out,
                                           kCFPropertyListBinaryFormat_v1_0,
                                           0, &error);
		CFRelease(args_out);
        if (error) {
            secdebug("server", "failed to encode return data: %@", error);
             CFReleaseSafe(error);
        }
    }

    void *p = (data_out ? (void *)CFDataGetBytePtr(data_out) : NULL);
    CFIndex l = (data_out ? CFDataGetLength(data_out) : 0);
    /* 64 bits cast: securityd should never generate replies bigger than 2^32 bytes.
       Worst case is we are truncating the reply we send to the client. This would only
       cause the client side to not be able to decode the response. */
    assert((unsigned long)l<UINT_MAX); /* Debug check */
    kern_return_t err = securityd_client_reply(reply, request_id, status,
        p, (unsigned int)l);

    CFReleaseSafe(data_out);

    request_end();

    return err;
}
コード例 #19
0
// domain should already be locked.
static Boolean _writeXMLFile(CFURLRef url, CFMutableDictionaryRef dict, Boolean isWorldReadable, Boolean *tryAgain) {
    Boolean success = false;
    CFAllocatorRef alloc = __CFPreferencesAllocator();
    *tryAgain = false;
    if (CFDictionaryGetCount(dict) == 0) {
        // Destroy the file
        CFBooleanRef val = (CFBooleanRef) CFURLCreatePropertyFromResource(alloc, url, kCFURLFileExists, NULL);
        if (val && CFBooleanGetValue(val)) {
            success = CFURLDestroyResource(url, NULL);
        } else {
            success = true;
        }
        if (val) CFRelease(val);
    } else {
        CFPropertyListFormat desiredFormat = __CFPreferencesShouldWriteXML() ? kCFPropertyListXMLFormat_v1_0 : kCFPropertyListBinaryFormat_v1_0;
        CFDataRef data = CFPropertyListCreateData(alloc, dict, desiredFormat, 0, NULL);
        if (data) {
            SInt32 mode;
#if TARGET_OS_OSX || TARGET_OS_LINUX
            mode = isWorldReadable ? S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH : S_IRUSR|S_IWUSR;
#else
	    mode = 0666;
#endif
#if TARGET_OS_OSX
            {	// Try quick atomic way first, then fallback to slower ways and error cases
                CFStringRef scheme = CFURLCopyScheme(url);
                if (!scheme) {
                    *tryAgain = false;
                    CFRelease(data);
                    return false;
                } else if (CFStringCompare(scheme, CFSTR("file"), 0) == kCFCompareEqualTo) {
                    SInt32 length = CFDataGetLength(data);
                    const void *bytes = (0 == length) ? (const void *)"" : CFDataGetBytePtr(data);
                    Boolean atomicWriteSuccess = __CFWriteBytesToFileWithAtomicity(url, bytes, length, mode, true);
                    if (atomicWriteSuccess) {
                        CFRelease(scheme);
                        *tryAgain = false;
                        CFRelease(data);
                        return true;
                    }
                    if (!atomicWriteSuccess && thread_errno() == ENOSPC) {
                        CFRelease(scheme);
                        *tryAgain = false;
                        CFRelease(data);
                        return false;
                    }
                }
                CFRelease(scheme);
            }
#endif
            success = CFURLWriteDataAndPropertiesToResource(url, data, URLPropertyDictForPOSIXMode(mode), NULL);
            URLPropertyDictRelease();
            if (success) {
                CFDataRef readData;
                if (!CFURLCreateDataAndPropertiesFromResource(alloc, url, &readData, NULL, NULL, NULL) || !CFEqual(readData, data)) {
                    success = false;
                    *tryAgain = true;
                }
                if (readData) CFRelease(readData);
            } else {
                CFBooleanRef val = (CFBooleanRef) CFURLCreatePropertyFromResource(alloc, url, kCFURLFileExists, NULL);
                if (!val || !CFBooleanGetValue(val)) {
                    CFURLRef tmpURL = CFURLCreateWithFileSystemPathRelativeToBase(alloc, CFSTR("."), kCFURLPOSIXPathStyle, true, url); // Just "." because url is not a directory URL
                    CFURLRef parentURL = tmpURL ? CFURLCopyAbsoluteURL(tmpURL) : NULL;
                    if (tmpURL) CFRelease(tmpURL);
                    if (val) CFRelease(val);
                    val = (CFBooleanRef) CFURLCreatePropertyFromResource(alloc, parentURL, kCFURLFileExists, NULL);
                    if ((!val || !CFBooleanGetValue(val)) && _createDirectory(parentURL, isWorldReadable)) {
                        // parent directory didn't exist; now it does; try again to write
                        success = CFURLWriteDataAndPropertiesToResource(url, data, URLPropertyDictForPOSIXMode(mode), NULL);
                        URLPropertyDictRelease();
                        if (success) {
                            CFDataRef rdData;
                            if (!CFURLCreateDataAndPropertiesFromResource(alloc, url, &rdData, NULL, NULL, NULL) || !CFEqual(rdData, data)) {
                                success = false;
                                *tryAgain = true;
                            }
                            if (rdData) CFRelease(rdData);
                        }
                        
                    }
                    if (parentURL) CFRelease(parentURL);
                }
                if (val) CFRelease(val);
            }
            CFRelease(data);
        } else {
            // ???  This should never happen
            CFLog(__kCFLogAssertion, CFSTR("Could not generate XML data for property list"));
            success = false;
        }
    }
    return success;
}
コード例 #20
0
ファイル: iSCSITypes.c プロジェクト: anvena/iSCSIInitiator
/*! Copies the authentication object to a byte array representation. */
CFDataRef iSCSIAuthCreateData(iSCSIAuthRef auth)
{
    return CFPropertyListCreateData(kCFAllocatorDefault,auth,kCFPropertyListBinaryFormat_v1_0,0,NULL);
}
コード例 #21
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;
}
コード例 #22
0
ファイル: iSCSITypes.c プロジェクト: anvena/iSCSIInitiator
/*! Copies the discovery record object to a byte array representation.
 *  @param auth an iSCSI discovery record object.
 *  @return data representing the discovery record object
 *  or NULL if the discovery record object is invalid. */
CFDataRef iSCSIDiscoveryRecCreateData(iSCSIMutableDiscoveryRecRef discoveryRec)
{
    return CFPropertyListCreateData(kCFAllocatorDefault,discoveryRec,kCFPropertyListBinaryFormat_v1_0,0,NULL);
}
コード例 #23
0
ファイル: dump.c プロジェクト: aosm/Heimdal
static krb5_error_code
od_dump_entry(krb5_context kcontext, HDB *db, hdb_entry_ex *entry, void *data)
{
    CFErrorRef error = NULL;
    CFDictionaryRef dict;
    CFStringRef fn, uuidstr;
    CFUUIDRef uuid;
    CFURLRef url;

    dict = HeimODDumpHdbEntry(&entry->entry, &error);
    if (dict == NULL) {
	if (error)
	    CFRelease(error);
	return 0;
    }

    uuid = CFUUIDCreate(NULL);
    if (uuid == NULL) {
	krb5_warnx(kcontext, "out of memory");
        CFRelease(dict);
	return 0;
    }
    
    uuidstr = CFUUIDCreateString(NULL, uuid);
    CFRelease(uuid);
    if (uuidstr == NULL) {
	krb5_warnx(kcontext, "out of memory");
        CFRelease(dict);
	return 0;
    }

    fn = CFStringCreateWithFormat(NULL, NULL, CFSTR("%s/%@.plist"), (char *)data, uuidstr);
    CFRelease(uuidstr);
    if (fn == NULL) {
	krb5_warnx(kcontext, "out of memory");
        CFRelease(dict);
	return 0;
    }

    url = CFURLCreateWithFileSystemPath(NULL, fn,  kCFURLPOSIXPathStyle, false);
    CFRelease(fn);
    if (url == NULL) {
	krb5_warnx(kcontext, "out of memory");
        CFRelease(dict);
	return 0;
    }

    CFDataRef xmldata = CFPropertyListCreateData(NULL, dict, kCFPropertyListXMLFormat_v1_0, 0, NULL);
    CFRelease(dict);
    if (xmldata == NULL) {
	CFRelease(url);
	krb5_warnx(kcontext, "out of memory");
	return 0;
    }

    CFWriteStreamRef stream = CFWriteStreamCreateWithFile(NULL, url);
    if (stream) {
	if (CFWriteStreamOpen(stream))
	    CFWriteStreamWrite(stream, CFDataGetBytePtr(xmldata), CFDataGetLength(xmldata));
	CFWriteStreamClose(stream);
	CFRelease(stream);
    }

    CFRelease(url);
    CFRelease(xmldata);

    return 0;
}
コード例 #24
0
void ReceiptsDb::putInstalledPackageInfo(const char* identifier, const ReceiptsDb::InstalledPackageInfo& info)
{
	CFDictionaryRef plist;
	CFTypeRef keys[6], values[6];
	CFDataRef plistData;
	std::string path;
	int fd, wr;
	
	mkdirs(RECEIPTS_DIR);
	
	keys[0] = CFSTR("PackageIdentifier");
	keys[1] = CFSTR("PackageVersion");
	keys[2] = CFSTR("InstallPrefixPath");
	keys[3] = CFSTR("InstallProcessName");
	keys[4] = CFSTR("PackageFileName");
	keys[5] = CFSTR("InstallDate");
	
	values[0] = string2cfstring(info.identifier.c_str());
	values[1] = string2cfstring(info.version.c_str());
	values[2] = string2cfstring(info.prefixPath.c_str());
	values[3] = string2cfstring(info.installProcessName.c_str());
	values[4] = string2cfstring(info.packageFileName.c_str());
	values[5] = CFDateCreate(nullptr, info.installDate);
	
	plist = CFDictionaryCreate(nullptr, keys, values, 6,
			&kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
	
	for (CFTypeRef v : values)
		CFRelease(v);
	
	plistData = CFPropertyListCreateData(nullptr, plist,
			kCFPropertyListBinaryFormat_v1_0, 0, nullptr);
	CFRelease(plist);
	
	if (plistData == nullptr)
		throw std::runtime_error("Cannot generate .plist");
	
	path = getReceiptsPath(identifier, ".plist");
	fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0644);
	
	if (fd == -1)
	{
		std::stringstream ss;
		ss << "Cannot write plist file: " << strerror(errno) << std::endl;
		throw std::runtime_error(ss.str());
	}
	
	wr = ::write(fd, CFDataGetBytePtr(plistData), CFDataGetLength(plistData));
	CFRelease(plistData);
	
	if (wr == -1)
	{
		std::stringstream ss;
		ss << "Cannot write plist file: " << strerror(errno) << std::endl;
		
		::close(fd);
		throw std::runtime_error(ss.str());
	}
	
	::close(fd);
}
コード例 #25
0
ファイル: KEXTManager.c プロジェクト: StrongZhu/IOKitUser
/*********************************************************************
* Internal function for use by KextManagerLoadKextWithIdentifier()
* and KextManagerLoadKextWithURL().
*********************************************************************/
OSReturn __KextManagerSendLoadKextRequest(
    CFMutableDictionaryRef  requestDict,
    CFArrayRef              dependencyKextAndFolderURLs)
{
    OSReturn           result           = kOSReturnError;
    mach_port_t        kextd_port       = MACH_PORT_NULL;
    CFDataRef          requestData      = NULL;  // must release
    CFMutableArrayRef  dependencyPaths  = NULL;  // must release
    CFURLRef           dependencyAbsURL = NULL;  // must release
    CFStringRef        dependencyPath   = NULL;  // must release
    CFErrorRef         error            = NULL;  // must release

    if (!requestDict) {
        result = kOSKextReturnInvalidArgument;
        goto finish;
    }

    result = get_kextd_port(&kextd_port);
    if (result != kOSReturnSuccess) {
        goto finish;
    }

    if (dependencyKextAndFolderURLs &&
        CFArrayGetCount(dependencyKextAndFolderURLs)) {

        CFIndex count, index;
        
        dependencyPaths = CFArrayCreateMutable(kCFAllocatorDefault,
            /* capacity */ 0, &kCFTypeArrayCallBacks);
        if (!dependencyPaths) {
            result = kOSKextReturnNoMemory;
            goto finish;
        }
        CFDictionarySetValue(requestDict, kKextLoadDependenciesKey,
            dependencyPaths);

        count = CFArrayGetCount(dependencyKextAndFolderURLs);
        for (index = 0; index < count; index++) {
            CFURLRef thisURL = (CFURLRef)CFArrayGetValueAtIndex(
                dependencyKextAndFolderURLs, index);

            SAFE_RELEASE_NULL(dependencyPath);
            SAFE_RELEASE_NULL(dependencyAbsURL);

            dependencyAbsURL = CFURLCopyAbsoluteURL(thisURL);
            if (!dependencyAbsURL) {
                result = kOSKextReturnNoMemory;
                goto finish;
            }
            dependencyPath = CFURLCopyFileSystemPath(dependencyAbsURL,
                kCFURLPOSIXPathStyle);
            if (!dependencyPath) {
                result = kOSKextReturnNoMemory;
                goto finish;
            }

            CFArrayAppendValue(dependencyPaths, dependencyPath);
        }
    }

    requestData = CFPropertyListCreateData(kCFAllocatorDefault,
         requestDict, kCFPropertyListBinaryFormat_v1_0,
         /* options */ 0,
         &error);
    if (!requestData) {
        // any point in logging error reason here? nothing caller can do....
        result = kOSKextReturnSerialization;
        goto finish;
    }

    result = kextmanager_load_kext(kextd_port,
        (char *)CFDataGetBytePtr(requestData),
        CFDataGetLength(requestData));

finish:
    SAFE_RELEASE(requestData);
    SAFE_RELEASE(dependencyPaths);
    SAFE_RELEASE(dependencyPath);
    SAFE_RELEASE(dependencyAbsURL);
    SAFE_RELEASE(error);

    return result;
}
コード例 #26
0
ファイル: client.c プロジェクト: aosm/bootp
static int
S_add_or_set_service(mach_port_t server, int argc, char * argv[], bool add)
{
    CFDataRef			data = NULL;
    CFDictionaryRef		dict;
    char *			method_name;
    if_name_t			if_name;
    kern_return_t		kret;
    inline_data_t 		service_id;
    unsigned int 		service_id_len;
    ipconfig_status_t		status = ipconfig_status_success_e;
    void *			xml_data_ptr = NULL;
    int				xml_data_len = 0;

    strlcpy(if_name, argv[0], sizeof(if_name));
    method_name = argv[1];
    argv += 2;
    argc -= 2;

    dict = ConfigDictCreate(if_name, argc, argv, command_name, method_name,
			    FALSE);
    if (dict == NULL) {
	return (1);
    }
    data = CFPropertyListCreateData(NULL,
				    dict,
				    kCFPropertyListBinaryFormat_v1_0,
				    0,
				    NULL);
    if (data == NULL) {
	CFRelease(dict);
	fprintf(stderr, "failed to allocate memory\n");
	return (1);
    }
    xml_data_ptr = (void *)CFDataGetBytePtr(data);
    xml_data_len = (int)CFDataGetLength(data);
    if (add) {
	kret = ipconfig_add_service(server, if_name, xml_data_ptr, xml_data_len,
				    service_id, &service_id_len, &status);
    }
    else {
	kret = ipconfig_set_service(server, if_name, xml_data_ptr, xml_data_len,
				    service_id, &service_id_len, &status);
    }
    CFRelease(dict);
    CFRelease(data);
    
    if (kret != KERN_SUCCESS) {
	fprintf(stderr, "ipconfig_%s_service failed, %s\n", add ? "add" : "set",
		mach_error_string(kret));
	return (1);
    }
    if (status != ipconfig_status_success_e) {
	fprintf(stderr, "ipconfig_%s_service %s %s failed: %s\n",
		add ? "add" : "set",
		if_name, method_name, ipconfig_status_string(status));
	return (1);
    }
    printf("%.*s\n", service_id_len, service_id);
    return (0);
}
コード例 #27
0
ファイル: client.c プロジェクト: aosm/bootp
static int
S_set(mach_port_t server, int argc, char * argv[])
{
    CFDataRef			data = NULL;
    CFDictionaryRef		dict = NULL;
    const char *		method_name;
    if_name_t			if_name;
    kern_return_t		kret;
    ipconfig_status_t		status = ipconfig_status_success_e;
    void *			xml_data_ptr = NULL;
    int				xml_data_len = 0;

    strlcpy(if_name, argv[0], sizeof(if_name));
    method_name = argv[1];
    argv += 2;
    argc -= 2;

    if (strcasecmp(method_name, "NONE") == 0) {
	/* nothing to do, NONE implies NULL method data */
    }
    else if (strcasecmp(method_name, "NONE-V6") == 0
	     || strcasecmp(method_name, "NONE-V4") == 0) {

	CFDictionaryRef		empty_dict;
	CFStringRef		ip_key;

	/* NONE-V{4,6} is represented as an empty IPv{4,6} dictionary */
	empty_dict = CFDictionaryCreate(NULL,
					NULL, NULL, 0,
					&kCFTypeDictionaryKeyCallBacks,
					&kCFTypeDictionaryValueCallBacks);
	if (strcasecmp(method_name, "NONE-V6") == 0) {
	    ip_key = kSCEntNetIPv6;
	}
	else {
	    ip_key = kSCEntNetIPv4;
	}
	dict = CFDictionaryCreate(NULL,
				  (const void * *)&ip_key,
				  (const void * *)&empty_dict, 1,
				  &kCFTypeDictionaryKeyCallBacks,
				  &kCFTypeDictionaryValueCallBacks);
	CFRelease(empty_dict);
    }
    else {
	dict = ConfigDictCreate(if_name, argc, argv, command_name, method_name,
				TRUE);
	if (dict == NULL) {
	    return (1);
	}
    }
    if (dict != NULL) {
	data = CFPropertyListCreateData(NULL,
					dict,
					kCFPropertyListBinaryFormat_v1_0,
					0,
					NULL);
	if (data == NULL) {
	    CFRelease(dict);
	    fprintf(stderr, "failed to allocate memory\n");
	    return (1);
	}
	xml_data_ptr = (void *)CFDataGetBytePtr(data);
	xml_data_len = (int)CFDataGetLength(data);
    }
    kret = ipconfig_set(server, if_name, xml_data_ptr, xml_data_len, &status);
    my_CFRelease(&dict);
    my_CFRelease(&data);
    if (kret != KERN_SUCCESS) {
	mach_error("ipconfig_set failed", kret);
	return (1);
    }
    if (status != ipconfig_status_success_e) {
	fprintf(stderr, "ipconfig_set %s %s failed: %s\n",
		if_name, method_name, ipconfig_status_string(status));
	return (1);
    }
    return (0);
}
コード例 #28
0
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();
}
コード例 #29
0
ファイル: iSCSITypes.c プロジェクト: anvena/iSCSIInitiator
/*! Copies the configuration object to a byte array representation.
 *  @param config an iSCSI configuration object.
 *  @return data representing the configuration object
 *  or NULL if the configuration object is invalid. */
CFDataRef iSCSIConnectionConfigCreateData(iSCSIConnectionConfigRef config)
{
    return CFPropertyListCreateData(kCFAllocatorDefault,config,kCFPropertyListBinaryFormat_v1_0,0,NULL);
}
コード例 #30
0
ファイル: exportProject.c プロジェクト: rafirafi/darwinbuild
static int run(CFArrayRef argv) {
	ssize_t res = 0;
	CFIndex count = CFArrayGetCount(argv);
	if (count > 2)  return -1;
	int xml = 0, i;
	CFMutableDictionaryRef dict, preplist;
	CFDictionaryRef project = NULL;
	CFStringRef projname;
	CFArrayRef builds;
	const void *ssites, *bsites;
	CFStringRef build = DBGetCurrentBuild();

	if (count == 2) {
		CFStringRef arg = CFArrayGetValueAtIndex(argv, 0);
		xml = CFEqual(arg, CFSTR("-xml"));
		// -xml is the only supported option
		if (!xml) return -1;
		projname = CFArrayGetValueAtIndex(argv, 1);
	} else if (count == 1 ) {
		projname = CFArrayGetValueAtIndex(argv, 0);
	} else
		return -1;

	builds = DBCopyBuildInheritance(build);
	dict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks,&kCFTypeDictionaryValueCallBacks);

	preplist = (CFMutableDictionaryRef)DBCopyProjectPlist(build, NULL);
	ssites = CFDictionaryGetValue(preplist, CFSTR("source_sites"));
	bsites = CFDictionaryGetValue(preplist, CFSTR("binary_sites"));

	preplist = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks,&kCFTypeDictionaryValueCallBacks);
	for( i = 0; i < CFArrayGetCount(builds); i++ ) {
		build = CFArrayGetValueAtIndex(builds, i);
		project = DBCopyProjectPlist(build, projname);
		if( CFDictionaryGetCount(project) > 0 )
			break;
	}
	if( CFDictionaryGetCount(project) < 1 )
		return -1;
	CFDictionaryAddValue(dict, projname, project);
	CFRelease(project);
	CFDictionarySetValue(preplist, CFSTR("build"), build);
	CFDictionarySetValue(preplist, CFSTR("projects"), dict);
	if(ssites) CFDictionarySetValue(preplist, CFSTR("source_sites"), ssites);
	if(bsites) CFDictionarySetValue(preplist, CFSTR("binary_sites"), bsites);

	CFPropertyListRef plist = preplist;
	if (xml) {
#if __MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
	    CFDataRef data = CFPropertyListCreateData(kCFAllocatorDefault, 
			  				  plist, 
							  kCFPropertyListXMLFormat_v1_0,
							  0,
							  NULL);
#else
		CFDataRef data = CFPropertyListCreateXMLData(NULL, plist);
#endif
		res = write(STDOUT_FILENO, CFDataGetBytePtr(data), (ssize_t)CFDataGetLength(data));
	} else {
		res = writePlist(stdout, plist, 0);
	}
	return (int)res;
}