Ejemplo n.º 1
0
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 = CFPropertyListCreateXMLData(kCFAllocatorDefault, propertyList);

    SInt32 code;
    return CFURLWriteDataAndPropertiesToResource(urlFromFileName(fileName), xmlData, 0, &code);
}
Ejemplo n.º 2
0
static SInt32 _CFUserNotificationSendRequest(CFAllocatorRef allocator, CFStringRef sessionID, mach_port_t replyPort, SInt32 token, CFTimeInterval timeout, CFOptionFlags flags, CFDictionaryRef dictionary) {
    CFDictionaryRef modifiedDictionary = NULL;
    SInt32 retval = ERR_SUCCESS, itimeout = (timeout > 0.0 && timeout < INT_MAX) ? (SInt32)timeout : 0;
    CFDataRef data;
    mach_msg_base_t *msg = NULL;
    mach_port_t bootstrapPort = MACH_PORT_NULL, serverPort = MACH_PORT_NULL;
    CFIndex size;
    char namebuffer[MAX_PORT_NAME_LENGTH + 1];
    
    strlcpy(namebuffer, NOTIFICATION_PORT_NAME, sizeof(namebuffer));
    if (sessionID) {
        char sessionid[MAX_PORT_NAME_LENGTH + 1];
        CFIndex len = MAX_PORT_NAME_LENGTH - sizeof(NOTIFICATION_PORT_NAME) - sizeof(NOTIFICATION_PORT_NAME_SUFFIX);
        CFStringGetBytes(sessionID, CFRangeMake(0, CFStringGetLength(sessionID)), kCFStringEncodingUTF8, 0, false, (uint8_t *)sessionid, len, &size);
        sessionid[len - 1] = '\0';
        strlcat(namebuffer, NOTIFICATION_PORT_NAME_SUFFIX, sizeof(namebuffer));
        strlcat(namebuffer, sessionid, sizeof(namebuffer));
    }

    retval = task_get_bootstrap_port(mach_task_self(), &bootstrapPort);
    if (ERR_SUCCESS == retval && MACH_PORT_NULL != bootstrapPort) retval = bootstrap_look_up2(bootstrapPort, namebuffer, &serverPort, 0, 0);
    if (ERR_SUCCESS == retval && MACH_PORT_NULL != serverPort) {
        modifiedDictionary = _CFUserNotificationModifiedDictionary(allocator, dictionary, token, itimeout, _CFProcessNameString());
        if (modifiedDictionary) {
            data = CFPropertyListCreateXMLData(allocator, modifiedDictionary);
            if (data) {
                size = sizeof(mach_msg_base_t) + ((CFDataGetLength(data) + 3) & (~0x3));
                msg = (mach_msg_base_t *)CFAllocatorAllocate(kCFAllocatorSystemDefault, size, 0);
                if (__CFOASafe) __CFSetLastAllocationEventName(msg, "CFUserNotification (temp)");
                if (msg) {
                    memset(msg, 0, size);
                    msg->header.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, MACH_MSG_TYPE_MAKE_SEND_ONCE);
                    msg->header.msgh_size = size;
                    msg->header.msgh_remote_port = serverPort;
                    msg->header.msgh_local_port = replyPort;
                    msg->header.msgh_id = flags;
                    msg->body.msgh_descriptor_count = 0;
                    CFDataGetBytes(data, CFRangeMake(0, CFDataGetLength(data)), (uint8_t *)msg + sizeof(mach_msg_base_t));
                    //CFShow(CFStringCreateWithBytes(kCFAllocatorSystemDefault, (UInt8 *)msg + sizeof(mach_msg_base_t), CFDataGetLength(data), kCFStringEncodingUTF8, false));
                    retval = mach_msg((mach_msg_header_t *)msg, MACH_SEND_MSG|MACH_SEND_TIMEOUT, size, 0, MACH_PORT_NULL, MESSAGE_TIMEOUT, MACH_PORT_NULL);
                    CFAllocatorDeallocate(kCFAllocatorSystemDefault, msg);
                } else {
                    retval = unix_err(ENOMEM);
                }
                CFRelease(data);
            } else {
                retval = unix_err(ENOMEM);
            }
            CFRelease(modifiedDictionary);
        } else {
            retval = unix_err(ENOMEM);
        }
    }
    return retval;
}
Ejemplo n.º 3
0
static void writeFontDatabaseToPlist(CFPropertyListRef cgFontDBPropertyList, CFPropertyListRef filenamesFromRegistry)
{
    if (!cgFontDBPropertyList)
        return;

    RetainPtr<CFDataRef> data;

    if (!filenamesFromRegistry || CFGetTypeID(cgFontDBPropertyList) != CFDictionaryGetTypeID())
        data.adoptCF(CFPropertyListCreateXMLData(kCFAllocatorDefault, cgFontDBPropertyList));
    else {
        RetainPtr<CFMutableDictionaryRef> dictionary(AdoptCF, CFDictionaryCreateMutableCopy(kCFAllocatorDefault, 2, static_cast<CFDictionaryRef>(cgFontDBPropertyList)));
        CFDictionarySetValue(dictionary.get(), fontFilenamesFromRegistryKey(), filenamesFromRegistry);
        data.adoptCF(CFPropertyListCreateXMLData(kCFAllocatorDefault, dictionary.get()));
    }

    if (!data)
        return;

    safeCreateFile(fontsPlistPath(), data.get());
}
Ejemplo n.º 4
0
Archivo: main.c Proyecto: Deanzou/ppp
/* -------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------- */
CFDataRef Serialize(CFPropertyListRef obj, void **data, u_int32_t *dataLen)
{
    CFDataRef           	xml;
    
    xml = CFPropertyListCreateXMLData(NULL, obj);
    if (xml) {
        *data = (void*)CFDataGetBytePtr(xml);
        *dataLen = CFDataGetLength(xml);
    }
    return xml;
}
static int TearOffSignatureAndHashManifest(CFDictionaryRef manifestDict, CFDataRef* signature, CFDataRef* manifest_data)
{
	int result = -1;
	CFMutableDictionaryRef new_manifest_dict = NULL;
    CFStringRef sig_data_str = NULL;
	CFDataRef sig_data = NULL;
	CFDataRef prop_list = NULL;
    CFDataRef decoded_sig_data = NULL;
	
	if (NULL == manifestDict || NULL == signature || NULL == manifest_data)
	{
		return result;
	}
	*signature = NULL;
	*manifest_data = NULL;
	
	new_manifest_dict = CFDictionaryCreateMutableCopy(kCFAllocatorDefault, CFDictionaryGetCount(manifestDict), manifestDict);
	sig_data_str = (CFStringRef)CFDictionaryGetValue(new_manifest_dict, CFSTR("Signature"));
	if (NULL == sig_data_str)
	{
		CFRelease(new_manifest_dict);
		return result; 
	}
    
    sig_data = CFStringCreateExternalRepresentation(kCFAllocatorDefault, sig_data_str, kCFStringEncodingUTF8, 0);
    if (NULL == sig_data)
    {
        CFRelease(sig_data_str);
        CFRelease(new_manifest_dict);
		return result;
    }
    
    if (Base64Data(sig_data, 0, &decoded_sig_data))
    {
        CFRelease(sig_data);
        CFRelease(new_manifest_dict);
		return result;
    }
        
	*signature = decoded_sig_data;
	
	CFDictionaryRemoveValue(new_manifest_dict, CFSTR("Signature"));
	prop_list = CFPropertyListCreateXMLData (kCFAllocatorDefault, new_manifest_dict);
	CFRelease(new_manifest_dict);
	if (NULL == prop_list)
	{
		return result; 
	}
    
    (void)CreateHashForData(prop_list, 1, manifest_data);
	
    result = (NULL == *manifest_data) ? -1 : 0;
	return result;	
}
Ejemplo n.º 6
0
static void
dump_plist(FILE * f, CFTypeRef p)
{
    CFDataRef	data;
    data = CFPropertyListCreateXMLData(NULL, p);
    if (data == NULL) {
	return;
    }
    fwrite(CFDataGetBytePtr(data), CFDataGetLength(data), 1, f);
    CFRelease(data);
    return;
}
Ejemplo n.º 7
0
void
printDictionaryAsXML(CFMutableDictionaryRef dict)
{
    CFDataRef xml = CFPropertyListCreateXMLData(kCFAllocatorDefault,
                                                (CFPropertyListRef)dict);
    if (xml) {
        write(1, CFDataGetBytePtr(xml), CFDataGetLength(xml));
	printf("done\n");
        CFRelease(xml);
    }
	printf("..\n");
}
Ejemplo n.º 8
0
static bool populateFontDatabaseFromPlist()
{
    RetainPtr<CFPropertyListRef> plist = readFontPlist();
    if (!plist)
        return false;

    RetainPtr<CFDataRef> data(AdoptCF, CFPropertyListCreateXMLData(0, plist.get()));
    if (!data)
        return false;

    wkAddFontsFromPlistRepresentation(data.get());
    return true;
}
Ejemplo n.º 9
0
STATIC CFDataRef
itemID_copy_data(EAPOLClientItemIDRef itemID)
{
    CFDataRef		data;
    CFDictionaryRef	dict;

    dict = EAPOLClientItemIDCopyDictionary(itemID);
    data = CFPropertyListCreateXMLData(NULL, dict);
    if (dict != NULL) {
        CFRelease(dict);
    }
    return (data);
}
Ejemplo n.º 10
0
int
printDictionaryAsXML(CFDictionaryRef dict)
{
    CFDataRef xml = CFPropertyListCreateXMLData(kCFAllocatorDefault,
                                                (CFPropertyListRef)dict);
    if (!xml)
        return -1;
   
    write(STDOUT_FILENO, CFDataGetBytePtr(xml), CFDataGetLength(xml));
    CFRelease(xml);
   
    return 0;
}
Ejemplo n.º 11
0
static void
dump_as_xml(CFPropertyListRef p)
{
    CFDataRef	xml;
    
    xml = CFPropertyListCreateXMLData(NULL, p);
    if (xml != NULL) {
	fwrite(CFDataGetBytePtr(xml), CFDataGetLength(xml), 1,
	       stdout);
	CFRelease(xml);
    }
    return;
}
Ejemplo n.º 12
0
void subsurface_close_conf(void)
{
	Boolean status;
	SInt32 errorCode;
	CFDataRef xmlData;

	propertyList = dict;
	dict = NULL;
	xmlData = CFPropertyListCreateXMLData(kCFAllocatorDefault, propertyList);
	status = CFURLWriteDataAndPropertiesToResource (fileURL, xmlData, NULL, &errorCode);
	// some error handling - but really, what can we do?
	CFRelease(xmlData);
	CFRelease(propertyList);
}
int
main(int argc, char * argv[])
{
    const void *	data;
    int			data_len;
    CFDataRef		cfdata;
    const char *	type;
    CFDataRef		xml_data;

    if (argc < 3) {
	usage(argv[0]);
    }
    type = argv[1];
    argv += 2;
    argc -= 2;
    if (strcmp(type, "ip") == 0) {
	data = data_from_ip(argc, argv, &data_len);
    }
    else if (strcmp(type, "uint8") == 0) {
	data = data_from_uint8(argc, argv, &data_len);
    }
    else if (strcmp(type, "uint16") == 0) {
	data = data_from_uint16(argc, argv, &data_len);
    }
    else if (strcmp(type, "uint32") == 0) {
	data = data_from_uint32(argc, argv, &data_len);
    }
    else if (strcmp(type, "string") == 0) {
	data = argv[0];
	data_len = strlen(data);
    }
    else {
	fprintf(stderr, "unrecognized type '%s'\n", type);
	exit(2);
    }
    if (data == NULL) {
	exit(2);
    }
    cfdata = CFDataCreateWithBytesNoCopy(NULL, data, data_len,
					 kCFAllocatorNull);
    xml_data = CFPropertyListCreateXMLData(NULL, cfdata);
    CFRelease(cfdata);
    fwrite(CFDataGetBytePtr(xml_data), CFDataGetLength(xml_data), 1,
	   stdout);
    CFRelease(xml_data);
    exit(0);
    return (0);
}
Ejemplo n.º 14
0
/*************************************************************************
 *
 * hu_SaveToXMLFile( inCFPRef, inCFURLRef )
 *
 * Purpose: save a property list into an XML file
 *
 * Inputs: inCFPRef		- the data
 *			inCFURLRef	- URL for the file
 *
 * Returns: SInt32		- error code ( if any )
 */
static SInt32 hu_SaveToXMLFile(CFPropertyListRef inCFPRef, CFURLRef inCFURLRef) {
	CFDataRef xmlCFDataRef;
	SInt32 error = coreFoundationUnknownErr;
	
	// Convert the property list into XML data.
	xmlCFDataRef = CFPropertyListCreateXMLData(kCFAllocatorDefault, inCFPRef);
	if ( xmlCFDataRef ) {
		// Write the XML data to the file.
		(void) CFURLWriteDataAndPropertiesToResource(inCFURLRef, xmlCFDataRef, NULL, &error);
		
		// Release the XML data
		CFRelease(xmlCFDataRef);
	}
	
	return (error);
}   // hu_SaveToXMLFile
Ejemplo n.º 15
0
// Translates an iPod binary Property-list into a text property list.
//
// Returns:
//		true	on success
//		false	on failure
//
bool CiPoTApi::TranslatePLIST(char *originalFile, char *newFile)
{
	CFPropertyListRef propertyList;
	CFURLRef fileURL;
	CFStringRef inputFile, errorString;
	CFDataRef resourceData;
	Boolean status;
	SInt32 errorCode;
	bool ok = false;

	// Create a URL that specifies the file we will create to hold the XML data.
	inputFile = CFStringCreateWithCString(kCFAllocatorDefault, originalFile, kStrEncoding);
	fileURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, inputFile, kPathStyle, false);
	if (!fileURL)
		return false;
	// Read the XML file.
	status = CFURLCreateDataAndPropertiesFromResource(
		kCFAllocatorDefault, fileURL, &resourceData, NULL, NULL, &errorCode);
	if (resourceData) {
		// Reconstitute the dictionary using the XML data.
		propertyList = CFPropertyListCreateFromXMLData(
			kCFAllocatorDefault, resourceData,kCFPropertyListImmutable, &errorString);
		if (propertyList != NULL) {
			CFStringRef outputFile;
			CFDataRef xmlData;
			Boolean status;
			SInt32 errorCode;
			
			CFRelease(fileURL);
			outputFile = CFStringCreateWithCString(kCFAllocatorDefault, newFile, kStrEncoding);
			fileURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, outputFile, kPathStyle, false);
			// Convert the property list into XML data.
			xmlData = CFPropertyListCreateXMLData(kCFAllocatorDefault, propertyList);
			// Write the XML data to the file.
			status = CFURLWriteDataAndPropertiesToResource(fileURL, xmlData, NULL, &errorCode);
			ok = status ? true : false;
			CFRelease(xmlData);
			CFRelease(outputFile);
			CFRelease(propertyList);
		}
	}
	CFRelease(inputFile);
	CFRelease(fileURL);
	return ok;
}
Ejemplo n.º 16
0
RetainPtr<CFDataRef> LegacyWebArchive::rawDataRepresentation()
{
    RetainPtr<CFDictionaryRef> propertyList = createPropertyListRep(this);
    if (!propertyList) {
        LOG(Archives, "LegacyWebArchive - Failed to create property list for archive, returning no data");
        return 0;
    }
    
    // FIXME: On Mac, WebArchives have been written out as Binary Property Lists until this change.
    // Unless we jump through CFWriteStream hoops, they'll now be textual XML data.  Is this okay?
    RetainPtr<CFDataRef> plistData(AdoptCF, CFPropertyListCreateXMLData(0, propertyList.get()));
    if (!plistData) {
        LOG(Archives, "LegacyWebArchive - Failed to convert property list into raw data, returning no data");
        return 0;
    }
    
    return plistData;
}
Ejemplo n.º 17
0
/* ------------------------------------------------------------------
 *	write_user_settings ()
 */
static void write_user_settings ( const char *in_file, CFPropertyListRef in_data )
{
	CFURLRef cf_url = CFURLCreateFromFileSystemRepresentation(NULL, (const UInt8 *)in_file, strlen(in_file), FALSE);
	if ( !cf_url ) {
		msg_error("aod: could not create URL from: %s", in_file);
		return;
	}

	CFDataRef cf_data = CFPropertyListCreateXMLData(NULL, in_data);
	if ( cf_data ) {
		SInt32 write_err = noErr;
		if ( !CFURLWriteDataAndPropertiesToResource(cf_url, cf_data, NULL, &write_err) )
			if ( msg_verbose )
				msg_warn("aod: could not write to %s (error: %d)", in_file, (int) write_err);
		CFRelease(cf_data);
	}
	CFRelease(cf_url);
} /* write_user_settings */
Ejemplo n.º 18
0
void USBMuxSend(uint32_t sock, struct USBMuxPacket *packet) {
	CFDataRef xmlData = CFPropertyListCreateXMLData(kCFAllocatorDefault, packet->payload);
	char *buffer = (char *)CFDataGetBytePtr(xmlData);
	ssize_t result = send(sock, &packet->body, sizeof(struct USBMuxPacketBody), 0x0);
	if (result == sizeof(struct USBMuxPacketBody)) {
		if (packet->body.length > result) {
			ssize_t payloadSize = packet->body.length - result;
			ssize_t remainder = payloadSize;
			while (remainder) {
				result = send(sock, &buffer[payloadSize-remainder], sizeof(char), 0x0);
				if (result != sizeof(char)) {
					break;
				}
				remainder -= result;
			}
		}
	}
	CFSafeRelease(xmlData);
}
Ejemplo n.º 19
0
extern OSStatus MySyncTicketFromPane (
    MyCustomContext context, 
    PMPrintSession session
)

{
    OSStatus result = noErr;
    PMTicketRef ticket = NULL;
    CFMutableDictionaryRef dict = NULL;
    CFDataRef xmlData = NULL;

    result = MyGetTicket (session, kPDE_PMPrintSettingsRef, &ticket);
    if (result == noErr)
    {
        // If our pane has never been shown, this will be a noop.
        SyncSettingsFromPane(context);
        
        dict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
                    (const CFDictionaryKeyCallBacks *)&kCFTypeDictionaryKeyCallBacks,
                    (const CFDictionaryValueCallBacks *)&kCFTypeDictionaryValueCallBacks);
        if (dict)
        {
            ExternSettings(&context->settings, dict);
            xmlData = CFPropertyListCreateXMLData(kCFAllocatorDefault, dict);
            if (xmlData)
            {
                result = PMTicketSetCFData (
                    ticket, 
                    kMyBundleIdentifier, 
                    kAppPrintDialogPDEOnlyKey, 
                    xmlData, 
                    kPMUnlocked
                );
                CFRelease(xmlData);
            }
            CFRelease(dict);
        }
    }

    MyDebugMessage("MySyncTicket", result);
    return result;
}
Ejemplo n.º 20
0
/**
 * Export the #plist_t structure to XML format.
 *
 * @param plist the root node to export
 * @param plist_xml a pointer to a C-string. This function allocates the memory,
 *            caller is responsible for freeing it. Data is UTF-8 encoded.
 * @param length a pointer to an uint32_t variable. Represents the length of the allocated buffer.
 */
void plist_to_xml(plist_t plist, char **plist_xml, uint32_t * length)
{
	UInt8 *data;
	CFIndex dataLen;

	*plist_xml = NULL;
	*length = 0;

	CFDataRef xmlData = CFPropertyListCreateXMLData(kCFAllocatorDefault, plist);
	if (xmlData) {
		dataLen = CFDataGetLength(xmlData);
		data = malloc(dataLen + 1);
		if (data) {
			CFDataGetBytes(xmlData, CFRangeMake(0, dataLen), data);
			data[dataLen] = 0;
			*plist_xml = (char *)data;
			*length = dataLen;
		}
		CFRelease(xmlData);
	}
}
Ejemplo n.º 21
0
/* 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;
}
Ejemplo n.º 22
0
void main () {
    CFStringRef names[kNumFamilyMembers];
    CFArrayRef  array;
    CFDataRef   xmlData;
    CFRange range = {0, kNumFamilyMembers};
    char name[100];
    const void *ret_val = NULL;
    // Define the family members.
    names[0] = CFSTR("Marge");
    names[1] = CFSTR("Homer");
    names[2] = CFSTR("Bart");
    names[3] = CFSTR("Lisa");
    names[4] = CFSTR("Maggie");
    // Create a property list using the string array of names.
    array = CFArrayCreate( kCFAllocatorDefault,
                (const void **)names,
                kNumFamilyMembers,
                &kCFTypeArrayCallBacks );
    printf("Array size = %d\n", CFArrayGetCount(array));
    printf("Array has %s %d times\n", "Marge", CFArrayGetCountOfValue(array, range, CFSTR("Marge")));

    printf("\nCFShow:\n");
    CFShow((CFTypeRef)CFArrayGetValueAtIndex(array, 3));
    printf("\n\nCFShowStr:");
    CFShowStr(CFArrayGetValueAtIndex(array, 3));
    printf("\n");

    ret_val = CFArrayGetValueAtIndex(array, 3);
    CFStringGetCString(ret_val, name, sizeof(name), 0);
    printf("Value at index %d is 0x%x %s\n", 3, ret_val, name);
    // Convert the plist into XML data.
    xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, array );
    // Clean up CF types.
    CFRelease( array );
    CFRelease( xmlData );
}
Ejemplo n.º 23
0
void propertyListExample(void) {

    CFMutableDictionaryRef dict;
    CFNumberRef num;
    CFArrayRef array;
    CFDataRef data;
    #define NumKids 2
    CFStringRef kidsNames[] = {CFSTR("John"), CFSTR("Kyra")};
    #define NumPets 0
    int yearOfBirth = 1965;
    #define NumBytesInPic 10
    const unsigned char pic[NumBytesInPic] = {0x3c, 0x42, 0x81, 0xa5, 0x81, 0xa5, 0x99, 0x81, 0x42, 0x3c};
    CFDataRef xmlPropertyListData;
    CFStringRef xmlAsString;

    // Create and populate a pretty standard mutable dictionary: CFString keys, CF type values.
    // To be written out as a "propertyList", the tree of CF types can contain only:
    //   CFDictionary, CFArray, CFString, CFData, CFNumber, and CFDate.
    // In addition, the keys of the dictionaries should be CFStrings.

    dict = CFDictionaryCreateMutable(NULL, 0, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);

    CFDictionarySetValue(dict, CFSTR("Name"), CFSTR("John Doe"));

    CFDictionarySetValue(dict, CFSTR("City of Birth"), CFSTR("Springfield"));

    num = CFNumberCreate(NULL, kCFNumberIntType, &yearOfBirth);
    CFDictionarySetValue(dict, CFSTR("Year Of Birth"), num);
    CFRelease(num);

    array = CFArrayCreate(NULL, (const void **)kidsNames, 2, &kCFTypeArrayCallBacks); 
    CFDictionarySetValue(dict, CFSTR("Kids Names"), array);
    CFRelease(array);

    array = CFArrayCreate(NULL, NULL, 0, &kCFTypeArrayCallBacks);
    CFDictionarySetValue(dict, CFSTR("Pets Names"), array);
    CFRelease(array);

    data = CFDataCreate(NULL, pic, NumBytesInPic);
    CFDictionarySetValue(dict, CFSTR("Picture"), data);
    CFRelease(data);

    // We now have a dictionary which contains everything we want to know about
    // John Doe; let's show it first:

    show(CFSTR("John Doe info dictionary: %@"), dict);

    // Now create a "property list", which is a flattened, XML version of the
    // dictionary:

    xmlPropertyListData = CFPropertyListCreateXMLData(NULL, dict);

   // The return value is a CFData containing the XML file; show the data

    show(CFSTR("Shown as XML property list (bytes): %@"), xmlPropertyListData);

    // Given CFDatas are shown as ASCII versions of their hex contents, we can also
    // attempt to show the contents of the XML, assuming it was encoded in UTF8
    // (This is the case for XML property lists generated by CoreFoundation currently)

    xmlAsString = CFStringCreateFromExternalRepresentation(NULL, xmlPropertyListData, kCFStringEncodingUTF8);

    show(CFSTR("The XML property list contents: %@"), xmlAsString);

    CFRelease(dict);
    CFRelease(xmlAsString);
    CFRelease(xmlPropertyListData);
}
	//-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	// SaveToPrefs()
	//	The settings for each device are stored in CFPreferences on a per-user basis. 
	//-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	void DeviceSettings::SaveToPrefs(const Device& device, const DeviceSettings::ControlInfo* controlsToSave, UInt32 numberControlsToSave)
	{
		// Until further implementation, make this a NOP
		return;
		
		#if	Log_SaveRestoreFromPrefs
			CACFString deviceName(device.CopyDeviceName());
			char name[256];
			UInt32 nameSize = 256;
			deviceName.GetCString(name, nameSize);
			DebugMessage("CMIO::DP::DeviceSettings::SaveToPrefs: %s", name);
		#endif
		
		// Get the current prefs Data
		CFMutableDictionaryRef currentPrefsCFDictionary = NULL;

		// Open the prefs file for reading
		FILE* prefsFile = fopen(kDALDeviceSettingsFilePath, "r");
		if (prefsFile != NULL)
		{
			// Get the length of the file
			fseek(prefsFile, 0, SEEK_END);
			UInt32 fileLength = ftell(prefsFile);
			fseek(prefsFile, 0, SEEK_SET);
			
			if (fileLength > 0)
			{
				// Allocate a block of memory to hold the data in the file
				CAAutoFree<Byte> rawPrefsData(fileLength);
				
				// Read all the data in
				fread(static_cast<Byte*>(rawPrefsData), fileLength, 1, prefsFile);
				
				// Close the file
				fclose(prefsFile);
				
				// Put it into a CFData object
				CACFData rawPrefsCFData(static_cast<Byte*>(rawPrefsData), fileLength);
				
				// Parse the data as a property list
				currentPrefsCFDictionary = (CFMutableDictionaryRef)CFPropertyListCreateFromXMLData(NULL, rawPrefsCFData.GetCFData(), kCFPropertyListMutableContainersAndLeaves, NULL);
			}
			else
			{
				// No data, so close the file
				fclose(prefsFile);
				
				// Create a new, mutable dictionary
				currentPrefsCFDictionary = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
			}
		}
		else
		{
			// No file, or a bad file, so just create a new, mutable dictionary
			currentPrefsCFDictionary = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
		}
		
		// Just skip things if we still don't have a current prefs dictionary
		if (currentPrefsCFDictionary != NULL)
		{
			// Make a CACFDictionary for convenience and to be sure it gets released
			CACFDictionary currentPrefsDictionary(currentPrefsCFDictionary, true);
			
			// Make the dictionary key for this device
			CACFString uid(device.CopyDeviceUID());
			CACFString prefsKey(CFStringCreateWithFormat(NULL, NULL, CFSTR("com.apple.cmio.CMIO.DeviceSettings.%@"), uid.GetCFString()));
			
			// Save the device's settings into a dictionary
			CACFDictionary settingsDictionary(SaveToDictionary(device, controlsToSave, numberControlsToSave), true);
			
			// Put the settings into the prefs
			currentPrefsDictionary.AddDictionary(prefsKey.GetCFString(), settingsDictionary.GetCFDictionary());
			
			// Make a CFData that contains the new prefs
			CACFData newRawPrefsCFData(CFPropertyListCreateXMLData(NULL, (CFPropertyListRef)currentPrefsDictionary.GetCFMutableDictionary()), true);
			
			if (newRawPrefsCFData.IsValid())
			{
				// Open the prefs file for writing
				prefsFile = fopen(kDALDeviceSettingsFilePath, "w+");
				if (prefsFile != NULL)
				{
					// Write the data
					fwrite(newRawPrefsCFData.GetDataPtr(), newRawPrefsCFData.GetSize(), 1, prefsFile);
					
					// Close the file
					fclose(prefsFile);
				}
			}
		}
		
		#if	Log_SaveRestoreFromPrefs
			DebugMessage("CMIO::DP::DeviceSettings::SaveToPrefs: %s finished", name);
		#endif
	}
Ejemplo n.º 25
0
static void cb(am_device_notification_callback_info * info, void *foo)
{
	struct am_device *dev;

	if (info->msg == ADNCI_MSG_CONNECTED) {
		dev = info->dev;

		AMDeviceConnect(dev);
		assert(AMDeviceIsPaired(dev));
		assert(!AMDeviceValidatePairing(dev));
		assert(!AMDeviceStartSession(dev));

		CFStringRef product =
		    AMDeviceCopyValue(dev, 0, CFSTR("ProductVersion"));
		assert(product);
		UniChar first = CFStringGetCharacterAtIndex(product, 0);
		int epoch = first - '0';
Retry:	{}
		printf("Attempting to mount image...\n");

		service_conn_t afc_socket = 0;
		struct afc_connection *afc = NULL;
		assert(!AMDeviceStartService(dev, CFSTR("com.apple.afc"), &afc_socket, NULL));
		assert(!AFCConnectionOpen(afc_socket, 0, &afc));
		assert(!AFCDirectoryCreate(afc, "PublicStaging"));

		AFCRemovePath(afc, "PublicStaging/staging.dimage");
		qwrite(afc, real_dmg, "PublicStaging/staging.dimage");
		qwrite(afc, ddi_dmg, "PublicStaging/ddi.dimage");

		service_conn_t mim_socket1 = 0;
		service_conn_t mim_socket2 = 0;
		assert(!AMDeviceStartService(dev, CFSTR("com.apple.mobile.mobile_image_mounter"), &mim_socket1, NULL));
		assert(mim_socket1);

		CFPropertyListRef result = NULL;
		CFMutableDictionaryRef dict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
		CFDictionarySetValue(dict, CFSTR("Command"), CFSTR("MountImage"));
		CFDictionarySetValue(dict, CFSTR("ImageType"), CFSTR("Developer"));

		CFDictionarySetValue(dict, CFSTR("ImagePath"), CFSTR("/var/mobile/Media/PublicStaging/staging.dimage"));

		int fd = open(real_dmg_signature, O_RDONLY);
		assert(fd != -1);
		uint8_t sig[128];
		assert(read(fd, sig, sizeof(sig)) == sizeof(sig));
		close(fd);

		CFDictionarySetValue(dict, CFSTR("ImageSignature"), CFDataCreateWithBytesNoCopy(NULL, sig, sizeof(sig), kCFAllocatorNull));
		send_message(mim_socket1, dict);

		usleep(timesl);
		assert(!AFCRenamePath(afc, "PublicStaging/ddi.dimage", "PublicStaging/staging.dimage"));

		result = receive_message(mim_socket1);

		int len = CFDataGetLength(CFPropertyListCreateXMLData(NULL, result));
		char* bytes = CFDataGetBytePtr(CFPropertyListCreateXMLData(NULL, result));

		if(strstr(bytes, "Complete")) {
			char* the_service = "CopyIt";
			service_conn_t socket = 0;
			sleep(2);
			printf("Image mounted, running helper...\n");
			assert(!AMDeviceStartService(dev, CFStringCreateWithCStringNoCopy(NULL, the_service, kCFStringEncodingUTF8, kCFAllocatorNull),
				&socket, NULL));
			assert(!fcntl(socket, F_SETFL, O_NONBLOCK));
			assert(!fcntl(0, F_SETFL, O_NONBLOCK));
		} else {
			printf("Failed to inject image, trying again... (if it fails, try a different time), delay ... %dus\n", timesl);
			timesl += 1000;
			goto Retry;
		}

		exit(0);
	}
}
Boolean GTMSMJobSubmit(CFDictionaryRef cf_job, CFErrorRef *error) {
  // We launch our jobs using launchctl instead of doing it by hand
  // because launchctl does a whole pile of parsing of the job internally
  // to handle the sockets cases that we don't want to duplicate here.
  int fd = -1;
  CFDataRef xmlData = NULL;
  char fileName[] = _PATH_TMP "GTMServiceManagement.XXXXXX";
  CFErrorRef local_error = NULL;

  if (!cf_job) {
    local_error
      = GTMCFLaunchCreateUnlocalizedError(EINVAL,
                                          CFSTR("NULL Job."),
                                          NULL);
    goto exit;
  }

  CFStringRef jobLabel = CFDictionaryGetValue(cf_job,
                                              CFSTR(LAUNCH_JOBKEY_LABEL));
  if (!jobLabel) {
    local_error
      = GTMCFLaunchCreateUnlocalizedError(EINVAL,
                                          CFSTR("Job missing label."),
                                          NULL);
    goto exit;
  }

  CFDictionaryRef jobDict = GTMSMJobCopyDictionary(jobLabel);
  if (jobDict) {
    CFRelease(jobDict);
    local_error
      = GTMCFLaunchCreateUnlocalizedError(EEXIST,
                                          CFSTR("Job already exists %@."),
                                          jobLabel);
    goto exit;
  }

  xmlData = CFPropertyListCreateXMLData(NULL, cf_job);
  if (!xmlData) {
    local_error
      = GTMCFLaunchCreateUnlocalizedError(EINVAL,
                                          CFSTR("Invalid Job %@."),
                                          jobLabel);
    goto exit;
  }

  fd = mkstemp(fileName);
  if (fd == -1) {
    local_error
      = GTMCFLaunchCreateUnlocalizedError(errno,
                                          CFSTR("Unable to create %s."),
                                          fileName);
    goto exit;
  }
  write(fd, CFDataGetBytePtr(xmlData), CFDataGetLength(xmlData));
  close(fd);

  pid_t childpid = fork();
  if (childpid == -1) {
    local_error
      = GTMCFLaunchCreateUnlocalizedError(errno,
                                          CFSTR("Unable to fork."),
                                          NULL);
    goto exit;
  }
  if (childpid != 0) {
    // Parent process
    int status = 0;
    pid_t pid = -1;
    do {
      pid = waitpid(childpid, &status, 0);
    } while (pid == -1 && errno == EINTR);
    if (pid == -1) {
      local_error
        = GTMCFLaunchCreateUnlocalizedError(errno,
                                            CFSTR("waitpid failed."));
        goto exit;
    } else if (WEXITSTATUS(status)) {
      local_error
        = GTMCFLaunchCreateUnlocalizedError(ECHILD,
                                            CFSTR("Child exit status: %d "
                                                  "pid: %d"),
                                            WEXITSTATUS(status), childpid);
      goto exit;
    }
  } else {
    // Child Process
    spc_sanitize_files();
    spc_drop_privileges();
    const char *args[] = { "launchctl", "load", fileName, NULL };
    execve("/bin/launchctl", (char* const*)args, NULL);
    abort();
  }
exit:
  if (xmlData) {
    CFRelease(xmlData);
  }
  if (fd != -1) {
    unlink(fileName);
  }
  if (error) {
    *error = local_error;
  } else if (local_error) {
#ifdef DEBUG
    CFShow(local_error);
#endif //  DEBUG
    CFRelease(local_error);
  }
  return local_error == NULL;
}
Ejemplo n.º 27
0
Boolean AddCommands( SRRecognizer inSpeechRecognizer, SRLanguageModel inCommandsLangaugeModel, CFArrayRef inCommandNamesArray )
{

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

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

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

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

    }
    
    return successfullyAddCommands;
}
Ejemplo n.º 28
0
//
// Contemplate the object-to-be-signed and set up the Signer state accordingly.
//
void SecCodeSigner::Signer::prepare(SecCSFlags flags)
{
	// get the Info.plist out of the rep for some creative defaulting
	CFRef<CFDictionaryRef> infoDict;
	if (CFRef<CFDataRef> infoData = rep->component(cdInfoSlot))
		infoDict.take(makeCFDictionaryFrom(infoData));

	// work out the canonical identifier
	identifier = state.mIdentifier;
	if (identifier.empty()) {
		identifier = rep->recommendedIdentifier(state);
		if (identifier.find('.') == string::npos)
			identifier = state.mIdentifierPrefix + identifier;
		if (identifier.find('.') == string::npos && state.isAdhoc())
			identifier = identifier + "-" + uniqueName();
		secdebug("signer", "using default identifier=%s", identifier.c_str());
	} else
		secdebug("signer", "using explicit identifier=%s", identifier.c_str());
	
	// work out the CodeDirectory flags word
	if (state.mCdFlagsGiven) {
		cdFlags = state.mCdFlags;
		secdebug("signer", "using explicit cdFlags=0x%x", cdFlags);
	} else {
		cdFlags = 0;
		if (infoDict)
			if (CFTypeRef csflags = CFDictionaryGetValue(infoDict, CFSTR("CSFlags"))) {
				if (CFGetTypeID(csflags) == CFNumberGetTypeID()) {
					cdFlags = cfNumber<uint32_t>(CFNumberRef(csflags));
					secdebug("signer", "using numeric cdFlags=0x%x from Info.plist", cdFlags);
				} else if (CFGetTypeID(csflags) == CFStringGetTypeID()) {
					cdFlags = cdTextFlags(cfString(CFStringRef(csflags)));
					secdebug("signer", "using text cdFlags=0x%x from Info.plist", cdFlags);
				} else
					MacOSError::throwMe(errSecCSBadDictionaryFormat);
			}
	}
	if (state.mSigner == SecIdentityRef(kCFNull))	// ad-hoc signing requested...
		cdFlags |= kSecCodeSignatureAdhoc;	// ... so note that
	
	// prepare the resource directory, if any
	string rpath = rep->resourcesRootPath();
	if (!rpath.empty()) {
		// explicitly given resource rules always win
		CFCopyRef<CFDictionaryRef> resourceRules = state.mResourceRules;
		
		// embedded resource rules come next
		if (!resourceRules && infoDict)
			if (CFTypeRef spec = CFDictionaryGetValue(infoDict, _kCFBundleResourceSpecificationKey)) {
				if (CFGetTypeID(spec) == CFStringGetTypeID())
					if (CFRef<CFDataRef> data = cfLoadFile(rpath + "/" + cfString(CFStringRef(spec))))
						if (CFDictionaryRef dict = makeCFDictionaryFrom(data))
							resourceRules.take(dict);
				if (!resourceRules)	// embedded rules present but unacceptable
					MacOSError::throwMe(errSecCSResourceRulesInvalid);
			}

		// finally, ask the DiskRep for its default
		if (!resourceRules)
			resourceRules.take(rep->defaultResourceRules(state));
		
		// build the resource directory
		ResourceBuilder resources(rpath, cfget<CFDictionaryRef>(resourceRules, "rules"), digestAlgorithm());
		rep->adjustResources(resources);	// DiskRep-specific adjustments
		CFRef<CFDictionaryRef> rdir = resources.build();
		resourceDirectory.take(CFPropertyListCreateXMLData(NULL, rdir));
	}
	
	// screen and set the signing time
	CFAbsoluteTime now = CFAbsoluteTimeGetCurrent();
	if (state.mSigningTime == CFDateRef(kCFNull)) {
		signingTime = 0;		// no time at all
	} else if (!state.mSigningTime) {
		signingTime = now;		// default
	} else {
		CFAbsoluteTime time = CFDateGetAbsoluteTime(state.mSigningTime);
		if (time > now)	// not allowed to post-date a signature
			MacOSError::throwMe(errSecCSBadDictionaryFormat);
		signingTime = time;
	}
	
	pagesize = state.mPageSize ? cfNumber<size_t>(state.mPageSize) : rep->pageSize(state);
    
    // Timestamping setup
    CFRef<SecIdentityRef> mTSAuth;	// identity for client-side authentication to the Timestamp server
}
Ejemplo n.º 29
0
Boolean AddCommands( SRRecognizer inSpeechRecognizer, SRLanguageModel inCommandsLangaugeModel, CFArrayRef inCommandNamesArray )
{

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

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

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

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

    }
    
    return successfullyAddCommands;
}


/*
    ConvertAppleEventResultIntoCommandID
    
    This routine converts the Apple event data received from a speech done (kAESpeechSuite, kAESpeechDone) 
    Apple event into a command ID when using the AddCommands routine to add your commands to the top-level
    language model.
    
    This routine returns true if the spoken utterance was recognized as a valid command.
*/

Boolean ConvertAppleEventResultIntoCommandID( const AppleEvent *inAppleEvent, long * outCommandID )
{
    Boolean			successfullyFound = false;
    Size			actualSize;
    DescType		actualType;
    OSErr			recStatus = noErr;
    
    //	Get recognition status from AE, and check that it is equal to 0.
    if (AEGetParamPtr( inAppleEvent, keySRSpeechStatus, typeSInt16, &actualType, (Ptr)&recStatus, sizeof(recStatus), &actualSize) == noErr && recStatus == noErr) {
    
        // Get recognition result from AE, and continue if not NULL.
        SRRecognitionResult recResult = NULL;
        if (AEGetParamPtr( inAppleEvent, keySRSpeechResult, typeSRSpeechResult, &actualType, (Ptr)&recResult, sizeof(recResult), &actualSize) == noErr && recResult) {
    
            // Get language model result from recognition result
            Size				theLen = sizeof(SRLanguageModel);
            SRLanguageModel		resultLanguageModel	= 0;  
            if (SRGetProperty( recResult, kSRLanguageModelFormat, &resultLanguageModel, &theLen ) == noErr) {
            
                // Get the recognized command object from the language model
                // Since there will only be one object in the langauge model, we just grab the first one.
                SRLanguageObject	resultingCommandObj = 0;
                if (SRGetIndexedItem( resultLanguageModel, &resultingCommandObj, 0 ) == noErr) {
                
                    // Get the command ID from the refCon property of the recognized command object.
                    theLen = sizeof(long);
                    if (SRGetProperty( resultingCommandObj, kSRRefCon, outCommandID, &theLen ) == noErr)
                        successfullyFound = true;
                }
            }
        }
    }
    
    return successfullyFound;
}
Ejemplo n.º 30
0
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;
}