CFDataRef WebApiClientDataCreateWithHexEncodedString(CFStringRef string) {
	CFIndex len = CFStringGetLength(string);
	CFMutableDataRef result = CFDataCreateMutable(kCFAllocatorDefault, len / 2);
	bool allocated = false;
	char *str = (char *)CFStringGetCStringPtr(string, kCFStringEncodingUTF8);
	if ( str == NULL ) {
		CFIndex bufferSize = CFStringGetMaximumSizeForEncoding(len, kCFStringEncodingUTF8) + 1;
		str = malloc(bufferSize);
		if ( !str ) {
			return result;
		}
		if ( !CFStringGetCString(string, str, bufferSize, kCFStringEncodingUTF8) ) {
			free(str);
			return result;
		}
		allocated = true;
	}
	CFIndex i;
	unsigned char byte = 0;
	size_t slen = strnlen(str, len);
	slen -= (slen % 2); // if odd # of characters, truncate down
	for ( i = 0; i < slen; i += 2 ) {
		if ( sscanf(&str[i], "%2hhx", &byte) ) {
			CFDataAppendBytes(result, &byte, 1);
		} else {
			break;
		}
	}
	if ( allocated ) {
		free(str);
	}
	return result;
}
Пример #2
0
// Missing glyphs run constructor. Core Text will not generate a run of missing glyphs, instead falling back on
// glyphs from LastResort. We want to use the primary font's missing glyph in order to match the fast text code path.
CoreTextController::CoreTextRun::CoreTextRun(const SimpleFontData* fontData, const UChar* characters, unsigned stringLocation, size_t stringLength, bool ltr)
    : m_fontData(fontData)
    , m_characters(characters)
    , m_stringLocation(stringLocation)
    , m_stringLength(stringLength)
{
    Vector<CFIndex, 16> indices;
    unsigned r = 0;
    while (r < stringLength) {
        indices.append(r);
        if (U_IS_SURROGATE(characters[r])) {
            ASSERT(r + 1 < stringLength);
            ASSERT(U_IS_SURROGATE_LEAD(characters[r]));
            ASSERT(U_IS_TRAIL(characters[r + 1]));
            r += 2;
        } else
            r++;
    }
    m_glyphCount = indices.size();
    if (!ltr) {
        for (unsigned r = 0, end = m_glyphCount - 1; r < m_glyphCount / 2; ++r, --end)
            std::swap(indices[r], indices[end]);
    }
    m_indicesData.adoptCF(CFDataCreateMutable(kCFAllocatorDefault, m_glyphCount * sizeof(CFIndex)));
    CFDataAppendBytes(m_indicesData.get(), reinterpret_cast<const UInt8*>(indices.data()), m_glyphCount * sizeof(CFIndex));
    m_indices = reinterpret_cast<const CFIndex*>(CFDataGetBytePtr(m_indicesData.get()));
}
Пример #3
0
CFDataRef createConvertedString( CFDataRef text, char* srcEncoding, char* dstEncoding )
{
	iconv_t cd;
	cd = iconv_open (dstEncoding, srcEncoding);
	if (cd == (iconv_t) -1)
		return NULL;

	CFMutableDataRef result = CFDataCreateMutable(NULL, 0);
	
	char *inPtr = (char*) CFDataGetBytePtr(text);
	size_t inBytesLeft = CFDataGetLength(text);
	
	char buffer[BUFFERSIZE];
	do {
		size_t outBytesLeft = BUFFERSIZE;
		char *outPtr = (char*)buffer;
		iconv(cd, &inPtr, &inBytesLeft, &outPtr , &outBytesLeft);
		CFIndex converted = BUFFERSIZE - outBytesLeft;
		CFDataAppendBytes(result, (UInt8*) &buffer, converted);
	} while (inBytesLeft > 0);
	
	iconv_close( cd );
	
	return result;
}
Пример #4
0
/* static */ void
_HttpContextHandleHasBytesAvailable(HttpContextRef context) {

	UInt8 buffer[2048];
	
	// Try reading the bytes into the buffer.
	CFIndex bytesRead = CFReadStreamRead(context->_inStream, buffer, sizeof(buffer));
	
	// Reset the timeout.
	CFRunLoopTimerSetNextFireDate(context->_timer, CFAbsoluteTimeGetCurrent() + kTimeOutInSeconds);
	
	// If there wasn't an error (-1) and not end (0), process the data.
	if (bytesRead > 0) {
		
		// Add the bytes of data to the receive buffer.
		CFDataAppendBytes(context->_rcvdBytes, buffer, bytesRead);

		// Parse recieved data
        int result = HTTPParseRequest(context);      
        
        if ( result == 1 ) {
            // HTTP message is fully loaded, process it
            HTTPProcessMessage(context);
			
			// Reset the timeout.
			CFRunLoopTimerSetNextFireDate(context->_timer, CFAbsoluteTimeGetCurrent() + kTimeOutInSeconds);
        }
        
        // If the ouput stream can write, try sending the bytes.
		if (result != 0 && CFWriteStreamCanAcceptBytes(context->_outStream))
			_HttpContextHandleCanAcceptBytes(context);
	}
}
Пример #5
0
void ResourceHandle::handleDataArray(CFArrayRef dataArray)
{
    ASSERT(client());
    if (client()->supportsDataArray()) {
        client()->didReceiveDataArray(this, dataArray);
        return;
    }

    CFIndex count = CFArrayGetCount(dataArray);
    ASSERT(count);
    if (count == 1) {
        CFDataRef data = static_cast<CFDataRef>(CFArrayGetValueAtIndex(dataArray, 0));
        client()->didReceiveBuffer(this, SharedBuffer::wrapCFData(data), -1);
        return;
    }

    CFIndex totalSize = 0;
    CFIndex index;
    for (index = 0; index < count; index++)
        totalSize += CFDataGetLength(static_cast<CFDataRef>(CFArrayGetValueAtIndex(dataArray, index)));

    RetainPtr<CFMutableDataRef> mergedData = adoptCF(CFDataCreateMutable(kCFAllocatorDefault, totalSize));
    for (index = 0; index < count; index++) {
        CFDataRef data = static_cast<CFDataRef>(CFArrayGetValueAtIndex(dataArray, index));
        CFDataAppendBytes(mergedData.get(), CFDataGetBytePtr(data), CFDataGetLength(data));
    }

    client()->didReceiveBuffer(this, SharedBuffer::wrapCFData(mergedData.get()), -1);
}
Пример #6
0
void ResourceHandle::handleDataArray(CFArrayRef dataArray)
{
    ASSERT(client());
    if (client()->supportsDataArray()) {
        client()->didReceiveDataArray(this, dataArray);
        return;
    }

    CFIndex count = CFArrayGetCount(dataArray);
    ASSERT(count);
    if (count == 1) {
        CFDataRef data = static_cast<CFDataRef>(CFArrayGetValueAtIndex(dataArray, 0));
        CFIndex length = CFDataGetLength(data);
        client()->didReceiveData(this, reinterpret_cast<const char*>(CFDataGetBytePtr(data)), length, static_cast<int>(length));
        return;
    }

    CFIndex totalSize = 0;
    CFIndex index;
    for (index = 0; index < count; index++)
        totalSize += CFDataGetLength(static_cast<CFDataRef>(CFArrayGetValueAtIndex(dataArray, index)));

    RetainPtr<CFMutableDataRef> mergedData(AdoptCF, CFDataCreateMutable(kCFAllocatorDefault, totalSize));
    for (index = 0; index < count; index++) {
        CFDataRef data = static_cast<CFDataRef>(CFArrayGetValueAtIndex(dataArray, index));
        CFDataAppendBytes(mergedData.get(), CFDataGetBytePtr(data), CFDataGetLength(data));
    }

    client()->didReceiveData(this, reinterpret_cast<const char*>(CFDataGetBytePtr(mergedData.get())), totalSize, static_cast<int>(totalSize));
}
Пример #7
0
    CFDataRef Monitor::receive_request(CFMessagePortRef local, SInt32 msgid, CFDataRef data, void *info) {
        Monitor *monitor = (Monitor *)info;
        CFIndex length = CFDataGetLength(data);
        memcpy(monitor->_request, CFDataGetBytePtr(data), length);

        CFDataRef reply = monitor->_response_buffer = CFDataCreateMutable(kCFAllocatorMallocZone, 0);
        
        // sample the stack.
        monitor->_stack_bottom = (void*) auto_get_sp();
        
        // scan args
        monitor->tokenize_args();
        
        // prevent the collector from collecting until we've processed the request.
        Zone *zone = Zone::zone();
        if (zone) zone->block_collector();

        // process request generating report
        monitor->process_request();
        
        // unblock the collector.
        if (zone) zone->unblock_collector();

        // return the response.
        CFDataAppendBytes(monitor->_response_buffer, (const UInt8*)"\0", 1);
        monitor->_response_buffer = NULL;
        return reply;
    }
/* write a 16-bit word, little endian */
void appendUint16(
	CFMutableDataRef	buf,
	uint16_t			word)
{
	unsigned char cb[2];
	OSWriteLittleInt16(cb, 0, word);
	CFDataAppendBytes(buf, cb, 2);
}
OSStatus impExpWrappedOpenSSHExport(
	SecKeyRef							secKey,
	SecItemImportExportFlags			flags,		
	const SecKeyImportExportParameters	*keyParams,		// optional 
	const CssmData						&descData,
	CFMutableDataRef					outData)		// output appended here
{
	CSSM_CSP_HANDLE cspdlHand = 0;
	OSStatus ortn;
	bool releaseCspHand = false;
	CSSM_RETURN crtn;
	
	if(keyParams == NULL) {
		return errSecParam;
	}

	/* we need a CSPDL handle - try to get it from the key */	
	ortn = SecKeyGetCSPHandle(secKey, &cspdlHand);
	if(ortn) {
		cspdlHand = cuCspStartup(CSSM_FALSE);
		if(cspdlHand == 0) {
			return CSSMERR_CSSM_ADDIN_LOAD_FAILED;
		}
		releaseCspHand = true;
	}
	/* subsequent errors to errOut: */

	/* derive wrapping key */
	CSSM_KEY wrappingKey;
	crtn = openSSHv1DeriveKey(cspdlHand, keyParams, VP_Export, &wrappingKey);
	if(crtn) {
		goto errOut;
	}
	
	/* GO */
	CSSM_KEY wrappedKey;
	memset(&wrappedKey, 0, sizeof(CSSM_KEY));
	
	crtn = impExpExportKeyCommon(cspdlHand, secKey, &wrappingKey, &wrappedKey,
		CSSM_ALGID_OPENSSH1, CSSM_ALGMODE_NONE, CSSM_PADDING_NONE,
		CSSM_KEYBLOB_WRAPPED_FORMAT_OPENSSH1, CSSM_ATTRIBUTE_NONE, CSSM_KEYBLOB_RAW_FORMAT_NONE, 
		&descData,
		NULL);	// IV
	if(crtn) {
		goto errOut;
	}
	
	/* the wrappedKey's KeyData is out output */
	CFDataAppendBytes(outData, wrappedKey.KeyData.Data, wrappedKey.KeyData.Length);
	CSSM_FreeKey(cspdlHand, NULL, &wrappedKey, CSSM_FALSE);
	
errOut:
	if(releaseCspHand) {
		cuCspDetachUnload(cspdlHand, CSSM_FALSE);
	}
	return crtn;

}
Пример #10
0
//_____________________________________________________________________________
//
void			AUElement::SaveState(CFMutableDataRef data)
{
	if(mUseIndexedParameters)
	{
		UInt32 nparams = mIndexedParameters.size();
		UInt32 theData = CFSwapInt32HostToBig(nparams);
		CFDataAppendBytes(data, (UInt8 *)&theData, sizeof(nparams));
	
		for (UInt32 i = 0; i < nparams; i++)
		{
			struct {
				UInt32				paramID;
				//CFSwappedFloat32	value; crashes gcc3 PFE
				UInt32				value;	// really a big-endian float
			} entry;
			
			entry.paramID = CFSwapInt32HostToBig(i);
	
			AudioUnitParameterValue v = mIndexedParameters[i].GetValue();
			entry.value = CFSwapInt32HostToBig(*(UInt32 *)&v );
	
			CFDataAppendBytes(data, (UInt8 *)&entry, sizeof(entry));
		}
	}
	else
	{
		UInt32 nparams = CFSwapInt32HostToBig(mParameters.size());
		CFDataAppendBytes(data, (UInt8 *)&nparams, sizeof(nparams));
	
		for (ParameterMap::iterator i = mParameters.begin(); i != mParameters.end(); ++i) {
			struct {
				UInt32				paramID;
				//CFSwappedFloat32	value; crashes gcc3 PFE
				UInt32				value;	// really a big-endian float
			} entry;
			
			entry.paramID = CFSwapInt32HostToBig((*i).first);
	
			AudioUnitParameterValue v = (*i).second.GetValue();
			entry.value = CFSwapInt32HostToBig(*(UInt32 *)&v );
	
			CFDataAppendBytes(data, (UInt8 *)&entry, sizeof(entry));
		}
	}
}
Пример #11
0
sdmmd_return_t SDMMD_MB2SendFileStream(SDMMD_AMConnectionRef conn, CFStringRef path, CFDataRef file) {
	sdmmd_return_t result = kAMDSuccess;
	
	CFDataRef file_path = CFStringCreateExternalRepresentation(kCFAllocatorDefault, path, kCFStringEncodingUTF8, 0);
	result = SDMMD_ServiceSend(SDMMD_TranslateConnectionToSocket(conn), file_path);
	CFSafeRelease(file_path);
	
	char data_chunk[1] = { 0x0C };
	CFMutableDataRef data_separator = CFDataCreateMutable(kCFAllocatorDefault, 0);
	CFDataAppendBytes(data_separator, (const UInt8 *)data_chunk, sizeof(uint8_t));
	CFDataAppendBytes(data_separator, CFDataGetBytePtr(file), CFDataGetLength(file));
	result = SDMMD_ServiceSend(SDMMD_TranslateConnectionToSocket(conn), data_separator);
	CFSafeRelease(data_separator);
	
	char zero_chunk[1] = { 0x0 };
	CFDataRef data_end = CFDataCreate(kCFAllocatorDefault, (const UInt8 *)zero_chunk, sizeof(uint8_t));
	result = SDMMD_ServiceSend(SDMMD_TranslateConnectionToSocket(conn), data_end);
	CFSafeRelease(data_end);
	
	return result;
}
Пример #12
0
static CFMutableDataRef createDataFromFile(const char *fname) {
    int fd = open(fname, O_RDONLY);
    CFMutableDataRef res = CFDataCreateMutable(kCFAllocatorSystemDefault, 0);
    char buf[4096];
    
    ssize_t amountRead;
    while ((amountRead = read(fd, buf, 4096)) > 0) {
        CFDataAppendBytes(res, (const UInt8 *)buf, amountRead);
    }
    
    close(fd);
    return res;
}
Пример #13
0
 //
 // print
 //
 // Formatted print to response pipe.
 //
 void Monitor::print(const char *fmt, ...) {
     va_list ap;
     va_start(ap, fmt);
     //XXX_JML needs a lock
     // XXX_PCB not if it's run off the main runloop.
     char *buffer;
     int length = vasprintf(&buffer, fmt, ap);
     if (buffer) {
         CFDataAppendBytes(_response_buffer, (const UInt8*)buffer, length);
         free(buffer);
     }
     va_end(ap);
 }
Пример #14
0
void write_buffer(CFStringRef inData)
{
	#ifdef DEBUG
		syslog(LOG_ERR,"Writing buffer to file.");
	#endif

	if (CFWriteStreamGetStatus(logStream)!=kCFStreamStatusOpen)
	{
		CFWriteStreamSetProperty(logStream,kCFStreamPropertyAppendToFile,kCFBooleanTrue);
		CFWriteStreamOpen(logStream);
	}

	if (!CFBooleanGetValue(doEncrypt))
	{
		CFWriteStreamWrite(logStream,(const UInt8*)CFStringGetCStringPtr(inData,CFStringGetFastestEncoding(inData)),CFStringGetLength(inData));
		return;
	}

	int buff_pos = 0;
	while (1)
	{	
		int avail_space =	8-CFDataGetLength(encrypt_buffer);					//space rem in buffer
		int rem_to_copy =	CFStringGetLength(inData)-buff_pos;					//stuff in data that needs to be copied
		int to_copy =		rem_to_copy<avail_space?rem_to_copy:avail_space;	//amount left to encryp, or avail space
		
		if (avail_space)
		{	
			UInt8 tmp_buff[8];
			CFStringGetBytes(inData,CFRangeMake(buff_pos,to_copy),kCFStringEncodingNonLossyASCII,0,false,tmp_buff,8,NULL);
			CFDataAppendBytes(encrypt_buffer,tmp_buff,to_copy);
			
			avail_space -= to_copy;
			if (avail_space>0)			// small buffer? still space left?
				break;
			buff_pos += to_copy;			//move along the buffer
		}
		
		UInt8 enc_buff[8];
		BF_ecb_encrypt(CFDataGetBytePtr(encrypt_buffer),enc_buff,&encrypt_bf_key,BF_ENCRYPT);
		CFWriteStreamWrite(logStream,enc_buff,8);

		CFDataDeleteBytes(encrypt_buffer,CFRangeMake(0,8));
		
		if (buff_pos==CFStringGetLength(inData))				//just in case buffer happens to fit perfectly
			break;
	}
	
	return;

}
Пример #15
0
CFDataRef CMFormatDescriptionCopyFLVVideoStartData(CMFormatDescriptionRef formatDescription)
{
	const CMMediaType mediaType = CMFormatDescriptionGetMediaType(formatDescription);
	if(mediaType != kCMMediaType_Video)
	{
		return NULL;
	}
	
	const FourCharCode mediaSubType = CMFormatDescriptionGetMediaSubType(formatDescription);
	
	const uint8_t videoHeader = CMFormatDescriptionGetFLVVideoHeader(formatDescription, true);
	
	if(mediaSubType == kCMVideoCodecType_H264 || mediaSubType == kCMVideoCodecType_MPEG4Video)
	{
		CFDataRef extradata = NULL;
		CMPVideoFormatDescriptionCopyExtradata(NULL, formatDescription, &extradata);
		
		AVCHeader avcheader;
		avcheader.videoCodec = videoHeader;
		avcheader.nalu = 0x00;
		avcheader.time = 0; // TODO
		
		CFMutableDataRef data = CFDataCreateMutable(NULL, sizeof(avcheader) + CFDataGetLength(extradata));
		
		CFDataAppendBytes(data, (UInt8 *)&avcheader, sizeof(avcheader));
		CFDataAppendBytes(data, CFDataGetBytePtr(extradata), CFDataGetLength(extradata));
		
		CFRelease(extradata);
		
		return data;
	}
	else
	{
		return NULL;
	}
	
}
Пример #16
0
static inline void TSICTStringAppendObjectToMutableDataWithFormat(CFTypeRef object, CFMutableDataRef buffer, TSITStringFormat format)
{
    if (object == NULL) {
        object = kCFNull;
    }

    CFRetain(object);

    TStringIRep* objRep = TSICTStringCreateWithObjectAndFormat(object, format);
    CFDataRef objData = TSICTStringCreateDataFromIntermediateRepresentation(objRep);
    CFDataAppendBytes(buffer, (CFDataGetBytePtr(objData)), CFDataGetLength(objData));
    CFRelease(objData);
    TSICTStringDestroy(objRep);

    CFRelease(object);
}
/* write a 32-bit word, little endian */
void appendUint32(
	CFMutableDataRef	buf,
	uint32_t			word)
{
#if 1
	unsigned char cb[4];
	OSWriteLittleInt32(cb, 0, word);
	CFDataAppendBytes(buf, cb, 4);
#else
	/* This is an alternate implementation which may or may not be faster than
	   the above. */
	CFIndex offset = CFDataGetLength(buf);
	UInt8 *bytes = CFDataGetMutableBytePtr(buf);
	CFDataIncreaseLength(buf, 4);
	OSWriteLittleInt32(bytes, offset, word);
#endif
}
Пример #18
0
static void IPStreamCallback(CFReadStreamRef stream, CFStreamEventType eventType, void *clientCallBackInfo)
{
	CFMutableDataRef responseData = (CFMutableDataRef)clientCallBackInfo;

	if(eventType & kCFStreamEventHasBytesAvailable)
	{
		UInt8 buffer[1024];
		CFIndex read;

		do {
			read = CFReadStreamRead(stream, buffer, sizeof(buffer));
			if(read > 0)
				CFDataAppendBytes(responseData, buffer, read);

		} while(read > 0);
	}

	if(eventType & (kCFStreamEventEndEncountered | kCFStreamEventErrorOccurred))
	{
		if((eventType & kCFStreamEventEndEncountered) && publicIPState == IPStateFetching)
		{
			if(publicIPData)
				CFRelease(publicIPData);

			publicIPData = CFDataCreateCopy(kCFAllocatorDefault, responseData);
			publicIPState = IPStateFetched;
		}

		if(eventType & kCFStreamEventErrorOccurred)
		{
			if(publicIPData)
				CFRelease(publicIPData);

			publicIPData = NULL;
			publicIPState = IPStateInvalid;
		}

		CFReadStreamClose(stream);
		CFReadStreamSetClient(stream, 0, NULL, NULL);
		CFReadStreamUnscheduleFromRunLoop(stream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
		CFRelease(stream);

		CFRelease(responseData);
	}
}
CFErrorRef fetch_and_clear_accumulated_data(CFMutableArrayRef *a, CFDataRef *data_out) {
	if (!*a) {
		*data_out = CFDataCreate(NULL, NULL, 0);
		return (*data_out) ? NULL : GetNoMemoryError();
	}

	CFIndex i, c = CFArrayGetCount(*a);
	CFIndex total = 0, prev_total = 0;
	
	for(i = 0; i < c; i++) {
		total += CFDataGetLength((CFDataRef)CFArrayGetValueAtIndex(*a, i));
		if (total < prev_total) {
			return GetNoMemoryError();
		}
		prev_total = total;
	}
	
	CFMutableDataRef out = CFDataCreateMutable(NULL, total);
	if (!out) {
		return GetNoMemoryError();
	}
	
	for(i = 0; i < c; i++) {
		CFDataRef d = (CFDataRef)CFArrayGetValueAtIndex(*a, i);
		CFDataAppendBytes(out, CFDataGetBytePtr(d), CFDataGetLength(d));
	}
	
	if (CFDataGetLength(out) != total) {
		CFRelease(out);
		return GetNoMemoryError();
	}
	
	CFArrayRef accumulator = *a;
	CFRelease(accumulator);
	*a = NULL;
	
	// This might be nice:
	//   *data_out = CFDataCreateCopy(NULL, out);
	//   CFRelease(out);
	// but that is slow (for large values) AND isn't really all that important anyway
	
	*data_out = out;
	
	return NULL;
}
Пример #20
0
int ServeIndex(HttpContextRef context, char* index_name) {
	DBG(("Calling ruby framework to serve index\n"));
	
	char* res = callServeIndex(index_name);
	
	if (res) {
		DBG(("RESPONSE:\n"));
		_dbg_print_data((UInt8*)res, strlen(res));
		DBG(("-- eof --\n"));
		
		DBG(("Add response to the send buffer"))
		CFDataAppendBytes(context->_sendBytes, (UInt8*)res, (CFIndex)strlen(res));
		
		return 1;
	}
	
	return 0;	
}
Пример #21
0
int ServeIndex(HttpContextRef context, char* index_name) {
	RAWLOG_INFO("Calling ruby framework to serve index");
	
	VALUE val = callServeIndex(index_name);
	char* res = getStringFromValue(val);
	if (res) {
		RAWTRACE("RESPONSE:");
		RAWTRACE_DATA((UInt8*)res, strlen(res));
		RAWTRACE("RESPONSE -- eof --");
		
		RAWTRACE("Add response to the send buffer");
		CFDataAppendBytes(context->_sendBytes, (UInt8*)res, (CFIndex)strlen(res));
		
		releaseValue(val);
		return 1;
	}
	
	return 0;	
}
/* 
 * Write a security buffer, providing the index into the CFData at which 
 * this security buffer's offset is located. Just before the actual data is written,
 * go back and update the offset with the start of that data using secBufOffset().
 */
void appendSecBuf(
	CFMutableDataRef	buf,
	uint16_t			len,
	CFIndex				*offsetIndex)
{
#if 1
	unsigned char cb[8];
	OSWriteLittleInt16(cb, 0, len);           /* buffer length */
	OSWriteLittleInt16(cb, 2, len);           /* buffer allocated size */
	OSWriteLittleInt32(cb, 4, 0);             /* offset is empty for now */
	CFDataAppendBytes(buf, cb, 8);         
	*offsetIndex = CFDataGetLength(buf) - 4;  /* offset will go here */
#else
	appendUint16(buf, len);					/* buffer length */
	appendUint16(buf, len);					/* buffer allocated size */
	*offsetIndex = CFDataGetLength(buf);	/* offset will go here */
	appendUint32(buf, 0);					/* but it's empty for now */
#endif
}
Пример #23
0
static int 
_CallApplication(HttpContextRef context, RouteRef route) {
	DBG(("Calling ruby framework\n"));
		
	char* res = callFramework(_CreateRequestHash(context,route));
	
	if (res) {
		DBG(("RESPONSE:\n"));
		_dbg_print_data((UInt8*)res, strlen(res));
		DBG(("-- eof --\n"));
		
		DBG(("Add response to the send buffer"))
		CFDataAppendBytes(context->_sendBytes, (UInt8*)res, (CFIndex)strlen(res));
		
		return 1;
	}
	
	return 0;
}
CFDictionaryRef download_file(int socket, CFDictionaryRef dict)
{
    UInt8 buffer[8192];
    CFIndex bytesRead;

    CFStringRef path = CFDictionaryGetValue(dict, CFSTR("Path"));
    if(path == NULL || CFGetTypeID(path) != CFStringGetTypeID())
        return NULL;
    CFMutableDictionaryRef out  = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);	

    CFURLRef fileURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, path, kCFURLPOSIXPathStyle, FALSE);
    CFReadStreamRef stream = CFReadStreamCreateWithFile(kCFAllocatorDefault, fileURL);
    CFRelease(fileURL);
    if(!CFReadStreamOpen(stream))
    {
        CFErrorRef error = CFReadStreamCopyError(stream);
        if (error != NULL)
        {
            CFStringRef errorDesc = CFErrorCopyDescription(error);
            CFDictionaryAddValue(out, CFSTR("Error"), errorDesc);
            CFRelease(errorDesc);
            CFRelease(error);
        }
        CFRelease(stream);
        return out;
    }
    CFMutableDataRef data = CFDataCreateMutable(kCFAllocatorDefault, 0);

    while(CFReadStreamHasBytesAvailable(stream))
    {
        if((bytesRead = CFReadStreamRead(stream, buffer, 8192)) <= 0)
            break;
        CFDataAppendBytes(data, buffer, bytesRead);
    }
    CFReadStreamClose(stream);
    CFRelease(stream);

    CFDictionaryAddValue(out, CFSTR("Data"), data);
    CFRelease(data);

    return out;
}
Пример #25
0
static int 
_CallApplication(HttpContextRef context, RouteRef route) {
	RAWLOG_INFO("Calling ruby framework");
		
	VALUE val = callFramework(_CreateRequestHash(context,route));
	char* res = getStringFromValue(val);
	if (res) {
		RAWTRACE("RESPONSE:");
		RAWTRACE_DATA((UInt8*)res, strlen(res));
		RAWTRACE( "RESPONSE -- eof --");
		
		RAWTRACE("Add response to the send buffer");
		CFDataAppendBytes(context->_sendBytes, (UInt8*)res, (CFIndex)strlen(res));
		
		releaseValue(val);
		return 1;
	}
	
	return 0;
}
Пример #26
0
void Zirk2PortClient::SendPan(UInt32 channel, Float32 azimuth, Float32 zenith, Float32 azimuthSpan, Float32 zenithSpan, Float32 gain)
{
	if (!mRemoteMessagePort) return;
	
	ClearData();
	CFDataAppendBytes(mData, (const UInt8*) &channel, sizeof(channel));
	CFDataAppendBytes(mData, (const UInt8*) &azimuth, sizeof(azimuth));
	CFDataAppendBytes(mData, (const UInt8*) &zenith, sizeof(zenith));
	CFDataAppendBytes(mData, (const UInt8*) &azimuthSpan, sizeof(azimuthSpan));
	CFDataAppendBytes(mData, (const UInt8*) &zenithSpan, sizeof(zenithSpan));
	CFDataAppendBytes(mData, (const UInt8*) &gain, sizeof(gain));	
	
	CFDataRef returnData;
	SInt32 ans = CFMessagePortSendRequest(GetRemoteMessagePort(), kZirkPort_Pan, mData, 1., 1., NULL, &returnData);
	if (ans != 0) return;	
}
Пример #27
0
CFDataRef createDataFromURL( CFURLRef url )
{
	CFMutableDataRef fileContent = CFDataCreateMutable(kCFAllocatorDefault, 0);
    CFReadStreamRef stream = CFReadStreamCreateWithFile(kCFAllocatorDefault, url);

    if (stream) {
        if (CFReadStreamOpen(stream)) {
            UInt8 buffer[BUFFERSIZE];
            CFIndex bytesRead;
            do {
                bytesRead = CFReadStreamRead(stream, buffer, sizeof(buffer));
                if (bytesRead > 0) {
                    CFDataAppendBytes(fileContent, buffer, bytesRead);
                }
            } while (bytesRead > 0);
            CFReadStreamClose(stream);
        }
        CFRelease(stream);
    }
    
	return fileContent;
}
Пример #28
0
CryptoX_Result
CryptoMac_VerifyUpdate(CryptoX_SignatureHandle* aInputData, void* aBuf,
                       unsigned int aLen)
{
  if (aLen == 0) {
    return CryptoX_Success;
  }
  if (!aInputData || !*aInputData) {
    return CryptoX_Error;
  }

  CFMutableDataRef inputData;
  if (!OnLionOrLater()) {
    inputData = (CFMutableDataRef)((CSSM_DATA_PTR)*aInputData)->Data;
    ((CSSM_DATA_PTR)*aInputData)->Length += aLen;
  } else {
    inputData = (CFMutableDataRef)*aInputData;
  }

  CFDataAppendBytes(inputData, (const uint8*)aBuf, aLen);
  return CryptoX_Success;
}
Пример #29
0
static inline CFDataRef TSICTStringCreateDataFromIntermediateRepresentation(TStringIRep* rep)
{
    CFIndex len = CFDataGetLength(rep->data);
    CFMutableDataRef buffer = CFDataCreateMutableCopy(kCFAllocatorDefault, (len + 12), rep->data);
    UInt8* bufferBytes = CFDataGetMutableBytePtr(buffer);

    size_t prefixLength = strlen(rep->length) + 1;
    CFDataReplaceBytes(buffer, BeginningRange, (const UInt8*)rep->length, (CFIndex)prefixLength);

    if (rep->format == kTSITStringFormatTNetstring) {
        const UInt8 ftag = (UInt8)TNetstringTypes[rep->type];
        CFDataAppendBytes(buffer, &ftag, 1);
        bufferBytes[(prefixLength - 1)] = TNetstringSeparator;
    } else if (rep->format == kTSITStringFormatOTNetstring) {
        const UInt8 ftag = (UInt8)OTNetstringTypes[rep->type];
        bufferBytes[(prefixLength - 1)] = ftag;
    }

    CFDataRef dataRep = CFDataCreateCopy(kCFAllocatorDefault, buffer);
    CFRelease(buffer);

    return dataRep;
}
Пример #30
0
CryptoX_Result
CryptoMac_VerifyUpdate(CryptoX_SignatureHandle* aInputData, void* aBuf,
                       unsigned int aLen)
{
  if (!OnLionOrLater()) {
    return VFY_Update((VFYContext*)*aInputData,
                      (const unsigned char*)aBuf, aLen);
  }

  if (aLen == 0) {
    return CryptoX_Success;
  }
  if (!aInputData || !*aInputData) {
    return CryptoX_Error;
  }

  CryptoX_Result result = CryptoX_Error;
  CFDataAppendBytes((CFMutableDataRef)*aInputData, (const UInt8 *) aBuf, aLen);
  if (*aInputData) {
    result = CryptoX_Success;
  }

  return result;
}