static void printEntry(const void *key, const void *value, void *context)
{
    struct indent_ctxt * ctxt = context;

#if 1
    // IOKit pretty
    CFDataRef	data;

    indent(false, ctxt->depth, ctxt->stackOfBits);
    printf("  ");
    printCFString( (CFStringRef)key );
    printf(" = ");

    data = IOCFSerialize((CFStringRef)value, kNilOptions);
    if( data) {
        if( 10000 > CFDataGetLength(data))
            printf(CFDataGetBytePtr(data));
        else
            printf("<is BIG>");
        CFRelease(data);
    } else
        printf("<IOCFSerialize failed>");
    printf("\n");

#else
    // CF ugly
    CFStringRef 	 keyStr = (CFStringRef) key;
    CFStringRef 	 valueStr = CFCopyDescription((CFTypeRef) val);
    CFStringRef 	 outStr;

    indent(false, ctxt->depth, ctxt->stackOfBits);
    outStr = CFStringCreateWithFormat(kCFAllocatorDefault, 0,
                CFSTR("  %@ = %@\n"), keyStr, valueStr);
    assert(outStr);
    printCFString(outStr);
    CFRelease(valueStr);
    CFRelease(outStr);
#endif
}
Example #2
0
SECURITY_STATUS schan_imp_get_session_peer_certificate(schan_imp_session session,
                                                       PCCERT_CONTEXT *cert)
{
    struct mac_session* s = (struct mac_session*)session;
    SECURITY_STATUS ret = SEC_E_INTERNAL_ERROR;
    CFArrayRef certs;
    OSStatus status;

    TRACE("(%p/%p, %p)\n", s, s->context, cert);

    status = SSLCopyPeerCertificates(s->context, &certs);
    if (status == noErr && certs)
    {
        SecCertificateRef mac_cert;
        CFDataRef data;
        if (CFArrayGetCount(certs) &&
            (mac_cert = (SecCertificateRef)CFArrayGetValueAtIndex(certs, 0)) &&
            (SecKeychainItemExport(mac_cert, kSecFormatX509Cert, 0, NULL, &data) == noErr))
        {
            *cert = CertCreateCertificateContext(X509_ASN_ENCODING,
                    CFDataGetBytePtr(data), CFDataGetLength(data));
            if (*cert)
                ret = SEC_E_OK;
            else
            {
                ret = GetLastError();
                WARN("CertCreateCertificateContext failed: %x\n", ret);
            }
            CFRelease(data);
        }
        else
            WARN("Couldn't extract certificate data\n");
        CFRelease(certs);
    }
    else
        WARN("SSLCopyPeerCertificates failed: %ld\n", (long)status);

    return ret;
}
static CFIndex dataRead(CFReadStreamRef stream, UInt8 *buffer, CFIndex bufferLength, CFStreamError *error, Boolean *atEOF, void *info) {
    _CFReadDataStreamContext *dataCtxt = (_CFReadDataStreamContext *)info;
    const UInt8 *bytePtr = CFDataGetBytePtr(dataCtxt->data);
    CFIndex length = CFDataGetLength(dataCtxt->data);
    CFIndex bytesToCopy = bytePtr + length - dataCtxt->loc;
    if (bytesToCopy > bufferLength) {
        bytesToCopy = bufferLength;
    }
    if (bytesToCopy < 0) {
        bytesToCopy = 0;
    }
    if (bytesToCopy != 0) {
        memmove(buffer, dataCtxt->loc, bytesToCopy);
        dataCtxt->loc += bytesToCopy;
    }
    error->error = 0;
    *atEOF = (dataCtxt->loc < bytePtr + length) ? FALSE : TRUE;
    if (dataCtxt->scheduled && !*atEOF) {
        CFReadStreamSignalEvent(stream, kCFStreamEventHasBytesAvailable, NULL);
    }
    return bytesToCopy;
}
Example #4
0
GHOST_TUns8* GHOST_SystemCarbon::getClipboard(bool selection) const
{
	PasteboardRef inPasteboard;
	PasteboardItemID itemID;
	CFDataRef flavorData;
	OSStatus err = noErr;
	GHOST_TUns8 * temp_buff;
	CFRange range;
	OSStatus syncFlags;
	
	err = PasteboardCreate(kPasteboardClipboard, &inPasteboard);
	if(err != noErr) { return NULL;}

	syncFlags = PasteboardSynchronize( inPasteboard );
		/* as we always get in a new string, we can safely ignore sync flags if not an error*/
	if(syncFlags <0) { return NULL;}


	err = PasteboardGetItemIdentifier( inPasteboard, 1, &itemID );
	if(err != noErr) { return NULL;}

	err = PasteboardCopyItemFlavorData( inPasteboard, itemID, CFSTR("public.utf8-plain-text"), &flavorData);
	if(err != noErr) { return NULL;}

	range = CFRangeMake(0, CFDataGetLength(flavorData));
	
	temp_buff = (GHOST_TUns8*) malloc(range.length+1); 

	CFDataGetBytes(flavorData, range, (UInt8*)temp_buff);
	
	temp_buff[range.length] = '\0';
	
	if(temp_buff) {
		return temp_buff;
	} else {
		return NULL;
	}
}
Example #5
0
std::vector<char> metadata_realm_encryption_key()
{
    const size_t key_size = 64;
    const std::string service = "io.realm.sync.keychain";
    const std::string account = "metadata";

    auto search_dictionary = build_search_dictionary(account, service, none);
    CFDataRef retained_key_data;
    if (OSStatus status = SecItemCopyMatching(search_dictionary.get(), (CFTypeRef *)&retained_key_data)) {
        if (status != errSecItemNotFound) {
            throw KeychainAccessException(status);
        }

        // Key was not found. Generate a new key, store it, and return it.
        std::vector<char> key(key_size);
        arc4random_buf(key.data(), key_size);
        auto key_data = adoptCF(CFDataCreate(nullptr, reinterpret_cast<const UInt8 *>(key.data()), key_size));
        if (!key_data) {
            throw std::bad_alloc();
        }

        CFDictionaryAddValue(search_dictionary.get(), kSecValueData, key_data.get());
        if (OSStatus status = SecItemAdd(search_dictionary.get(), nullptr)) {
            throw KeychainAccessException(status);
        }

        return key;
    }
    CFPtr<CFDataRef> key_data = adoptCF(retained_key_data);

    // Key was previously stored. Extract it.
    if (key_size != CFDataGetLength(key_data.get())) {
        throw std::runtime_error("Password stored in keychain was not expected size.");
    }

    auto key_bytes = reinterpret_cast<const char *>(CFDataGetBytePtr(key_data.get()));
    return std::vector<char>(key_bytes, key_bytes + key_size);
}
Example #6
0
static void __DAQueueResponse( DASessionRef    session,
                               void *          address,
                               void *          context,
                               _DACallbackKind kind,
                               DADiskRef       disk,
                               CFTypeRef       response,
                               SInt32          responseID )
{
    CFDataRef _response = NULL;

    if ( response )  _response = _DASerialize( kCFAllocatorDefault, response );

    _DAServerSessionQueueResponse( _DASessionGetID( session ),
                                   ( uintptr_t              ) address,
                                   ( uintptr_t              ) context,
                                   ( int32_t                ) kind,
                                   ( caddr_t                ) _DADiskGetID( disk ),
                                   ( vm_address_t           ) ( _response ? CFDataGetBytePtr( _response ) : 0 ),
                                   ( mach_msg_type_number_t ) ( _response ? CFDataGetLength(  _response ) : 0 ),
                                   ( int32_t                ) responseID );

    if ( _response )  CFRelease( _response );
}
Example #7
0
int img3_flash_NOR_image(io_connect_t norServiceConnection, CFDataRef imageData, int isLLB) {
	restored_log("%s: flashing %s data\n", "img3_flash_NOR_image", (isLLB ? "LLB" : "NOR"));
	
	size_t imgLen = CFDataGetLength(imageData);
	void *mappedImage = mmap(NULL, imgLen, PROT_READ | PROT_WRITE, MAP_SHARED, -1, 0);
	if(mappedImage == MAP_FAILED) {
		int err = errno;
		restored_log("mmap (size = %d) failed: %s\n", imgLen, strerror(err));
		return err;
	}
	
	const void *imageDataPtr = CFDataGetBytePtr(imageData);
	bcopy(imageDataPtr, mappedImage, imgLen);
	
	kern_return_t result;
	if((result = IOConnectCallStructMethod(norServiceConnection, 0, mappedImage, imgLen, NULL, 0)) != KERN_SUCCESS) {
		restored_log("IOConnectCallStructMethod failed: 0x%x\n", result);
	}
	
	munmap(mappedImage, imgLen);
	
	return result;
}
Example #8
0
static void
dumpLogicalVolumeExtents(CFMutableDictionaryRef lv)
{
    CFStringRef lvUUID = CFDictionaryGetValue(lv, CFSTR(kAppleLVMVolumeUUIDKey));
    if (!lvUUID) { printf("\ninternal error, no uuid in lv dict\n"); return; };
    
    CFDataRef extentData = (CFDataRef)AppleLVMGetVolumeExtents(lvUUID);
    if (!extentData) { printf("\nno extent data found?\n"); return; };

    AppleRAIDExtentOnDisk * extentList = (AppleRAIDExtentOnDisk *)CFDataGetBytePtr(extentData);
    UInt64 extentCount = CFDataGetLength(extentData) / sizeof(AppleRAIDExtentOnDisk);
    if (!extentCount || !extentList) { printf("\nextent data empty?\n"); return; };

    printf("\textent list:\n");
	       
    UInt32 i;
    for (i = 0; i < extentCount; i++) {
	printf("  %20llu - %12llu (%llu)\n",
	       extentList[i].extentByteOffset,
	       extentList[i].extentByteOffset + extentList[i].extentByteCount - 1,
	       extentList[i].extentByteCount);
    }
}
Example #9
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;
}
static int mailstream_low_cfstream_get_fd(mailstream_low * s)
{
#if HAVE_CFNETWORK
  struct mailstream_cfstream_data * cfstream_data = NULL;
  CFDataRef native_handle_data = NULL;
  CFSocketNativeHandle native_handle_value = -1;
  CFIndex native_data_len  = 0;
  CFIndex native_value_len = 0;

  if (!s)
    return -1;

  cfstream_data = (struct mailstream_cfstream_data *) s->data;

  if (!cfstream_data->readStream)
    return -1;

  native_handle_data = (CFDataRef)CFReadStreamCopyProperty(cfstream_data->readStream, kCFStreamPropertySocketNativeHandle);
  if (!native_handle_data)
    return -1;

  native_data_len  = CFDataGetLength(native_handle_data);
  native_value_len = (CFIndex)sizeof(native_handle_value);

  if (native_data_len != native_value_len) {
    CFRelease(native_handle_data);
    return -1;
  }

  CFDataGetBytes(native_handle_data, CFRangeMake(0, MIN(native_data_len, native_value_len)), (UInt8 *)&native_handle_value);
  CFRelease(native_handle_data);

  return native_handle_value;
#else
  return -1;
#endif
}
Example #11
0
void start_paste(widget_list *widget)
{
	OSStatus err = noErr;
	PasteboardRef gClipboard;
	PasteboardItemID  itemID;
	CFDataRef        flavorData;
	char*          flavorText;

	err = PasteboardCreate( kPasteboardClipboard, &gClipboard );
	//require_noerr( err, CantCreateClipboard );

  	err = PasteboardGetItemIdentifier( gClipboard, 1, &itemID );
	err = PasteboardCopyItemFlavorData( gClipboard, itemID, CFSTR("com.apple.traditional-mac-plain-text"), &flavorData );

	int flavorDataSize = CFDataGetLength(flavorData);
	flavorText=(char*)malloc(flavorDataSize+1);

	short dataIndex;
	for(dataIndex = 0; dataIndex <= flavorDataSize; dataIndex++ )
	{
		char byte = *(CFDataGetBytePtr( flavorData ) + dataIndex);
		flavorText[dataIndex] = (byte>32) ? byte : ' ';
	}
	flavorText[flavorDataSize] = '\0';
	CFRelease(flavorData);
	if (widget == NULL)
	{
		do_paste (flavorText);
	}
	else
	{
		do_paste_to_text_field(widget, flavorText);
	}

	free(flavorText);
	CFRelease( gClipboard );
}
/*! Creates a dictionary of session parameters for the session associated with
 *  the specified target, if one exists.
 *  @param handle a handle to a daemon connection.
 *  @param target the target to check for associated sessions to generate
 *  a dictionary of session parameters.
 *  @return a dictionary of session properties. */
CFDictionaryRef iSCSIDaemonCreateCFPropertiesForSession(iSCSIDaemonHandle handle,
                                                        iSCSITargetRef target)
{
    // Validate inputs
    if(handle < 0 || !target)
        return NULL;

    CFDictionaryRef properties = NULL;
    CFDataRef targetData = iSCSITargetCreateData(target);

    // Send command to daemon
    iSCSIDMsgCreateCFPropertiesForSessionCmd cmd = iSCSIDMsgCreateCFPropertiesForSessionCmdInit;

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

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

    iSCSIDMsgCreateCFPropertiesForSessionRsp rsp;

    if(!error)
        error = iSCSIDaemonRecvMsg(handle,(iSCSIDMsgGeneric*)&rsp,NULL);
    
    if(!error) {
        CFDataRef data = NULL;
        error = iSCSIDaemonRecvMsg(handle,0,&data,rsp.dataLength,NULL);
        
        if(!error && data) {
            CFPropertyListFormat format;
            properties = CFPropertyListCreateWithData(kCFAllocatorDefault,data,0,&format,NULL);
            CFRelease(data);
        }
    }

    return properties;
}
Example #13
0
/* Private call for Apple Internal use only */
IOReturn IOPMSleepSystemWithOptions ( io_connect_t fb, CFDictionaryRef options )
{
    uint64_t rtn = 0;
    size_t len = sizeof(uint32_t);
    kern_return_t err;
    CFDataRef serializedOptions = NULL;
    
    if( !options ) {
        return IOPMSleepSystem( fb );
    }
    
    serializedOptions = IOCFSerialize( options, 0 );

    if (!serializedOptions) 
    {
        return kIOReturnInternalError;
    }
    
    /* kPMSleepSystemOptions
     * in: serialized CFDictionary of options
     * out: IOReturn code returned from sleepSystem
     */
    err = IOConnectCallStructMethod(
                fb, 
                kPMSleepSystemOptions,
                CFDataGetBytePtr(serializedOptions), /* inputStruct */
                CFDataGetLength(serializedOptions), /* inputStructCnt */
                &rtn, /* outputStruct */
                &len); /* outputStructCnt */

    CFRelease(serializedOptions);
                
    if (kIOReturnSuccess != err)
        return err;
    else
        return (IOReturn) rtn;
}
Example #14
0
CFNetDiagnosticStatus CFNetDiagnosticDiagnoseProblemInteractively(CFNetDiagnosticRef details) {
	SInt32 retval = 0;
	mach_port_t port = MACH_PORT_NULL;
	CFDataRef msgData = NULL;
	kern_return_t err;
	
	//build message
	CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers(kCFAllocatorDefault, kCFAllocatorDefault);
	CFWriteStreamOpen(stream);
	CFIndex len = CFPropertyListWriteToStream(details, stream, kCFPropertyListBinaryFormat_v1_0, NULL);
	CFWriteStreamClose(stream);
	if(len > 0) {
		msgData = CFWriteStreamCopyProperty(stream, kCFStreamPropertyDataWritten);
	}
	CFRelease(stream);
	

	if(msgData) {
		err = bootstrap_look_up(bootstrap_port, *((name_t*)(&_CFNetDiagnosticMachPortName)), &port);
		
		if (err == KERN_SUCCESS) {
			err = _CFNetDiagnosticClient_passDescriptor(	port,
                                                                        _CFNetDiagnosticMachProtocolVersion,
									(vm_address_t)CFDataGetBytePtr(msgData),
									CFDataGetLength(msgData));
			if (err == KERN_SUCCESS) {
				//FIXME Yay!!!
			}
			
		}
		
		CFRelease(msgData);
	}
	
	return (CFNetDiagnosticStatus)retval;
}
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);
	CheckErrorAndReturn(result);
	
	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);
	CheckErrorAndReturn(result);
	
	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);
	CheckErrorAndReturn(result);
	
	ExitLabelAndReturn(result);
}
CFDataRef SC_MachMessagePort::messagePortCallBack(CFMessagePortRef local, SInt32 msgid, CFDataRef data, void *info)
{
    // CFShow(data);
    SC_MachMessagePort *port = (SC_MachMessagePort *) info;
    OSC_Packet* packet = (OSC_Packet *) malloc(sizeof(OSC_Packet));
    bzero(&packet->mReplyAddr, sizeof(ReplyAddress));
    packet->mReplyAddr.mReplyFunc = port->mReplyPort ? mach_reply_func : null_reply_func;
	packet->mReplyAddr.mReplyData = 0;
    packet->mReplyAddr.mSocket = (int)(int64)port->mReplyPort;
    packet->mSize = CFDataGetLength(data);
    packet->mData = (char*) memcpy(malloc(packet->mSize), CFDataGetBytePtr(data), packet->mSize);

    World *world = port->mWorld;
    if (world->mDumpOSC) dumpOSC(world->mDumpOSC, packet->mSize, packet->mData);

    if (!ProcessOSCPacket(world, packet)) {
        scprintf("command FIFO full\n");
        free(packet->mData);
        free(packet);
    }

    // how can we send a reply? we could block here until the message is processed...
    return NULL;
}
Example #17
0
static int convertOid(
	CFTypeRef inRef,
	CSSM_OID *outOid)
{
	if (!inRef || !outOid)
		return errSecParam;
	
	unsigned char *oidData = NULL;
	unsigned int oidLen = 0;

	if (CFGetTypeID(inRef) == CFStringGetTypeID()) {
		// CFStringRef: OID representation is a dotted-decimal string
		CFStringRef inStr = (CFStringRef)inRef;
		CFIndex max = CFStringGetLength(inStr) * 3;
		char buf[max];
		if (!CFStringGetCString(inStr, buf, max-1, kCFStringEncodingASCII))
			return errSecParam;

		if(encodeOid((unsigned char *)buf, &oidData, &oidLen) != 0)
			return errSecParam;
	}
	else if (CFGetTypeID(inRef) == CFDataGetTypeID()) {
		// CFDataRef: OID representation is in binary DER format
		CFDataRef inData = (CFDataRef)inRef;
		oidLen = (unsigned int) CFDataGetLength(inData);
		oidData = (unsigned char *) malloc(oidLen);
		memcpy(oidData, CFDataGetBytePtr(inData), oidLen);
	}
	else {
		// Not in a format we understand
		return errSecParam;
	}
	outOid->Length = oidLen;
	outOid->Data = (uint8 *)oidData;
	return 0;
}
Boolean IOURLWriteDataAndPropertiesToResource(CFURLRef url, CFDataRef data, CFDictionaryRef propertyDict, SInt32 *errorCode) {
    CFStringRef scheme = CFURLCopyScheme(url);
    if (!scheme) {
        if (errorCode) *errorCode = kIOURLImproperArgumentsError;
        return FALSE;
    } else if (CFStringCompare(scheme, CFSTR("file"), 0) == kCFCompareEqualTo) {
        Boolean success = TRUE;
        CFRelease(scheme);
        if (errorCode) *errorCode = 0;
        if (data) {
            char cPath[CFMaxPathSize];
            if (!CFURLGetFileSystemRepresentation(url, TRUE, cPath, CFMaxPathSize)) {
                if (errorCode) *errorCode = kIOURLImproperArgumentsError;
                success = FALSE;
            } else if (CFURLHasDirectoryPath(url)) {
                // Create a directory
                success = !mkdir(cPath, 0777);
                if (!success && errorCode) *errorCode = kIOURLUnknownError;
            } else {
               // Write data
                SInt32 length = CFDataGetLength(data);
                const void *bytes = (0 == length) ? (const void *)"" : CFDataGetBytePtr(data);
                success = _IOWriteBytesToFile(cPath, bytes, length);
                if (!success && errorCode) *errorCode = kIOURLUnknownError;
            }
        }
        if (propertyDict) {
            if (!_IOFileURLWritePropertiesToResource(url, propertyDict, errorCode))
                success = FALSE;
        }
        return success;
    } else {
        if (errorCode) *errorCode = kIOURLUnknownSchemeError;
        return FALSE;
    }
}
static int Base64Data(CFDataRef cfData, int for_encoding, CFDataRef* encoded_data)
{
	int result = -1; // Guilty until proven
	CNEncodings encoding = kCNEncodingBase64;
	CNStatus status = kCCSuccess;
	CNEncodingDirection direction = (for_encoding) ? kCNEncode : kCNDecode;
	unsigned char buffer[1024];
	size_t encoded_data_length = 1024;
	
	if (NULL == cfData || NULL == encoded_data)
	{
		return result;
	}
	memset(buffer, 0, 1024);
	*encoded_data = NULL;
	
	status = CNEncode(encoding, direction, CFDataGetBytePtr(cfData), CFDataGetLength(cfData), buffer, &encoded_data_length);
	if (kCCSuccess == status)
	{
		*encoded_data = CFDataCreate(kCFAllocatorDefault, (const UInt8 *)buffer, encoded_data_length);
		result = (NULL == *encoded_data) ? -1 : 0;
	}
	return result;	
}
Example #20
0
sdmmd_return_t SDMMD_DirectServiceReceive(SocketConnection handle, CFDataRef *data) {
	uint32_t size = (data && *data ? (uint32_t)CFDataGetLength(*data) : 0);
	if (size) {
		if (CheckIfExpectingResponse(handle, 1000)) {
			unsigned char *buffer = malloc(size);
			uint32_t remainder = size;
			size_t recieved;
			while (remainder) {
				if (handle.isSSL) {
					recieved = SSL_read(handle.socket.ssl, &buffer[size-remainder], remainder);
				} else {
					recieved = recv(handle.socket.conn, &buffer[size-remainder], remainder, 0);
				}
				if (!recieved)
					break;
				remainder -= recieved;
			}
			*data = CFDataCreate(kCFAllocatorDefault, buffer, size);
			free(buffer);
		}
		return kAMDSuccess;
	}
	return kAMDSuccess;
}
Example #21
0
static String CGImageToDataURL(CGImageRef image, const String& mimeType, const double* quality)
{
    if (!image)
        return "data:,";

    RetainPtr<CFMutableDataRef> data(AdoptCF, CFDataCreateMutable(kCFAllocatorDefault, 0));
    if (!data)
        return "data:,";

    RetainPtr<CFStringRef> uti = utiFromMIMEType(mimeType);
    ASSERT(uti);

    RetainPtr<CGImageDestinationRef> destination(AdoptCF, CGImageDestinationCreateWithData(data.get(), uti.get(), 1, 0));
    if (!destination)
        return "data:,";

    RetainPtr<CFDictionaryRef> imageProperties = 0;
    if (CFEqual(uti.get(), jpegUTI()) && quality && *quality >= 0.0 && *quality <= 1.0) {
        // Apply the compression quality to the JPEG image destination.
        RetainPtr<CFNumberRef> compressionQuality(AdoptCF, CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, quality));
        const void* key = kCGImageDestinationLossyCompressionQuality;
        const void* value = compressionQuality.get();
        imageProperties.adoptCF(CFDictionaryCreate(0, &key, &value, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
    }

    // Setting kCGImageDestinationBackgroundColor to black for JPEG images in imageProperties would save some math
    // in the calling functions, but it doesn't seem to work.

    CGImageDestinationAddImage(destination.get(), image, imageProperties.get());
    CGImageDestinationFinalize(destination.get());

    Vector<char> base64Data;
    base64Encode(reinterpret_cast<const char*>(CFDataGetBytePtr(data.get())), CFDataGetLength(data.get()), base64Data);

    return "data:" + mimeType + ";base64," + base64Data;
}
Example #22
0
sdmmd_return_t SDMMD_ServiceSend(SocketConnection handle, CFDataRef data) {
	CFIndex msgLen = (data ? CFDataGetLength(data) : 0);
	if (msgLen) {
	    msgLen = htonl((uint32_t)msgLen);
		uint64_t result;
		// Send 32-bit data length header
		if (handle.isSSL) {
			if (SSL_is_init_finished(handle.socket.ssl)) {
				result = SSL_write(handle.socket.ssl, &msgLen, sizeof(uint32_t));
			}
			else {
				return kAMDNotConnectedError;
			}
		}
		else {
			result = send(handle.socket.conn, &msgLen, sizeof(uint32_t), 0);
		}
		// Send data body
		if (result == sizeof(uint32_t)) {
			msgLen = ntohl(msgLen);
			if (handle.isSSL) {
				result = SSL_write(handle.socket.ssl, CFDataGetBytePtr(data), (uint32_t)msgLen);
			}
			else {
				result = send(handle.socket.conn, CFDataGetBytePtr(data), msgLen, 0);
			}
			return (result == msgLen ? kAMDSuccess : kAMDInvalidResponseError);
		}
		else {
			return kAMDNotConnectedError;
		}
	}
	else {
		return kAMDInvalidArgumentError;
	}
}
Example #23
0
TagLib::ByteVector TagLib::DecodeBase64(const TagLib::ByteVector& input)
{
	SFB::CFError error;
	SFB::SecTransform decoder(SecDecodeTransformCreate(kSecBase64Encoding, &error));
    if(!decoder) {
		LOGGER_WARNING("org.sbooth.AudioEngine", "SecDecodeTransformCreate failed: " << error);
		return {};
	}

	SFB::CFData sourceData(CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, (const UInt8 *)input.data(), (CFIndex)input.size(), kCFAllocatorNull));
	if(!sourceData)
		return {};

    if(!SecTransformSetAttribute(decoder, kSecTransformInputAttributeName, sourceData, &error)) {
		LOGGER_WARNING("org.sbooth.AudioEngine", "SecTransformSetAttribute failed: " << error);
		return {};
	}

	SFB::CFData decodedData((CFDataRef)SecTransformExecute(decoder, &error));
	if(!decodedData)
		return {};

	return {(const char *)CFDataGetBytePtr((CFDataRef)decodedData), (size_t)CFDataGetLength((CFDataRef)decodedData)};
}
/*! Synchronizes cached preference changes to disk and releases the locked
 *  semaphore, allowing other clients to make changes. If the prefereneces
 *  parameter is NULL, then no changes are made to disk and the semaphore is
 *  unlocked.
 *  @param handle a handle to a daemon connection.
 *  @param preferences the preferences to be synchronized
 *  @return an error code indicating whether the operating was successful. */
errno_t iSCSIDaemonPreferencesIOUnlockAndSync(iSCSIDaemonHandle handle,
                                              iSCSIPreferencesRef preferences)
{
    // Validate inputs
    if(handle < 0)
        return EINVAL;
    
    CFDataRef preferencesData = NULL;
    
    iSCSIDMsgPreferencesIOUnlockAndSyncCmd cmd = iSCSIDMsgPreferencesIOUnlockAndSyncCmdInit;
    
    if(preferences) {
        preferencesData = iSCSIPreferencesCreateData(preferences);
        cmd.preferencesLength = (UInt32)CFDataGetLength(preferencesData);
    }
    else
        cmd.preferencesLength = 0;
    
    errno_t error = iSCSIDaemonSendMsg(handle,(iSCSIDMsgGeneric *)&cmd,preferencesData,NULL);
    
    if(preferencesData)
        CFRelease(preferencesData);
    
    if(error)
        return error;
    
    iSCSIDMsgPreferencesIOUnlockAndSyncRsp rsp;
    
    if(recv(handle,&rsp,sizeof(rsp),0) != sizeof(rsp))
        return EIO;
    
    if(rsp.funcCode != kiSCSIDPreferencesIOUnlockAndSync)
        return EIO;
    
    return rsp.errorCode;
}
Example #25
0
CFDataRef createHTMLData(CFDataRef nfo) {
    // Load HTML constants (UCS2)
    CFDataRef preNfo = createUCS2FromConst(PRE_NFO_HTML, sizeof(PRE_NFO_HTML));
    CFDataRef postNfo = createUCS2FromConst(POST_NFO_HTML, sizeof(POST_NFO_HTML));
    CFDataRef preBlock = createUCS2FromConst(PRE_BLOCK_HTML, sizeof(PRE_BLOCK_HTML));
    CFDataRef postBlock = createUCS2FromConst(POST_BLOCK_HTML, sizeof(POST_BLOCK_HTML));
    
    
    CFMutableDataRef result = CFDataCreateMutable(NULL, 0);
    
    appendCFData(result, preNfo);
    CFRelease(preNfo);
    
    const UInt8* inPtr = CFDataGetBytePtr(nfo);
	size_t inCharsLeft = CFDataGetLength(nfo) / sizeof(UInt16);
    
    const UInt8* bsPtr = inPtr;
    bool inRun = false;
    
    while (inCharsLeft-- > 0) {
        UInt16 chr = *((const UInt16*)inPtr);
        
        // Look ahead for new state
        bool newState = inRun;
        
        if(!inRun) {
            if(ISBLOCKORBOX(chr)) {
                newState = true;
            }
        } else {
            if(!ISBLOCKORBOX(chr) && !ISWHITESPACE(chr)) {
                newState = false;
            }
        }
        
        // Process change of state, append data
        if(inRun != newState) {
            if(inPtr != bsPtr) {
                if(inRun) {
                    appendCFData(result, preBlock);
                    CFDataAppendBytes(result, (const UInt8*)bsPtr, (inPtr - bsPtr));
                    appendCFData(result, postBlock);
                } else {
                    CFDataAppendBytes(result, (const UInt8*)bsPtr, (inPtr - bsPtr));
                }
                
                bsPtr = inPtr;
            }
            
            inRun = newState;
        }
        
        inPtr += sizeof(UInt16);
    }
    
    // Append trailing data
    if(inPtr > bsPtr) {
        if(inRun) {
            appendCFData(result, preBlock);
            CFDataAppendBytes(result, (const UInt8*)bsPtr, (inPtr - bsPtr));
            appendCFData(result, postBlock);
        } else {
            CFDataAppendBytes(result, (const UInt8*)bsPtr, (inPtr - bsPtr));
        }
    }
    
    CFRelease(preBlock);
    CFRelease(postBlock);
    
    appendCFData(result, postNfo);
    CFRelease(postNfo);
    
    return result;
}
Example #26
0
void appendCFData(CFMutableDataRef dst, CFDataRef src) {
    CFDataAppendBytes(dst, CFDataGetBytePtr(src), CFDataGetLength(src));
}
CFMutableDataRef CFDataCreateMutableCopy(CFAllocatorRef allocator, CFIndex capacity, CFDataRef data) {
    // Do not allow magic allocator for now for mutable datas, because it
    // isn't remembered for proper handling later when growth of the buffer
    // has to occur.
    Boolean wasMagic = _CFAllocatorIsGCRefZero(allocator);
    if (0 == capacity) allocator = _CFConvertAllocatorToNonGCRefZeroEquivalent(allocator);
    CFMutableDataRef r = (CFMutableDataRef) __CFDataInit(allocator, (0 == capacity) ? kCFMutable : kCFFixedMutable, capacity, CFDataGetBytePtr(data), CFDataGetLength(data), NULL);
    if (wasMagic) CFMakeCollectable(r);
    return r;
}
CFDataRef CFDataCreateCopy(CFAllocatorRef allocator, CFDataRef data) {
    CFIndex length = CFDataGetLength(data);
    return __CFDataInit(allocator, kCFImmutable, length, CFDataGetBytePtr(data), length, NULL);
}
Example #29
0
bool CDVDVideoCodecVDA::Open(CDVDStreamInfo &hints, CDVDCodecOptions &options)
{
  if (CSettings::GetInstance().GetBool(CSettings::SETTING_VIDEOPLAYER_USEVDA) && !hints.software)
  {
    CCocoaAutoPool pool;

    //
    int width  = hints.width;
    int height = hints.height;
    int level  = hints.level;
    int profile = hints.profile;
    
    switch(profile)
    {
      case FF_PROFILE_H264_HIGH_10:
      case FF_PROFILE_H264_HIGH_10_INTRA:
      case FF_PROFILE_H264_HIGH_422:
      case FF_PROFILE_H264_HIGH_422_INTRA:
      case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
      case FF_PROFILE_H264_HIGH_444_INTRA:
      case FF_PROFILE_H264_CAVLC_444:
        CLog::Log(LOGNOTICE, "%s - unsupported h264 profile(%d)", __FUNCTION__, hints.profile);
        return false;
        break;
    }

    if (width <= 0 || height <= 0)
    {
      CLog::Log(LOGNOTICE, "%s - bailing with bogus hints, width(%d), height(%d)",
        __FUNCTION__, width, height);
      return false;
    }
    
    if (Cocoa_GPUForDisplayIsNvidiaPureVideo3() && !CDVDCodecUtils::IsVP3CompatibleWidth(width))
    {
      CLog::Log(LOGNOTICE, "%s - Nvidia 9400 GPU hardware limitation, cannot decode a width of %d", __FUNCTION__, width);
      return false;
    }

    CFDataRef avcCData;
    switch (hints.codec)
    {
      case AV_CODEC_ID_H264:
        m_bitstream = new CBitstreamConverter;
        if (!m_bitstream->Open(hints.codec, (uint8_t*)hints.extradata, hints.extrasize, false))
          return false;

        avcCData = CFDataCreate(kCFAllocatorDefault,
          (const uint8_t*)m_bitstream->GetExtraData(), m_bitstream->GetExtraSize());

        m_format = 'avc1';
        m_pFormatName = "vda-h264";
      break;
      default:
        return false;
      break;
    }

    // check the avcC atom's sps for number of reference frames and
    // bail if interlaced, VDA does not handle interlaced h264.
    uint32_t avcc_len = CFDataGetLength(avcCData);
    if (avcc_len < 8)
    {
      // avcc atoms with length less than 8 are borked.
      CFRelease(avcCData);
      delete m_bitstream, m_bitstream = NULL;
      return false;
    }
    else
    {
      bool interlaced = true;
      uint8_t *spc = (uint8_t*)CFDataGetBytePtr(avcCData) + 6;
      uint32_t sps_size = BS_RB16(spc);
      if (sps_size)
        m_bitstream->parseh264_sps(spc+3, sps_size-1, &interlaced, &m_max_ref_frames);
      if (interlaced)
      {
        CLog::Log(LOGNOTICE, "%s - possible interlaced content.", __FUNCTION__);
        CFRelease(avcCData);
        return false;
      }
    }

    if (profile == FF_PROFILE_H264_MAIN && level == 32 && m_max_ref_frames > 4)
    {
      // [email protected], VDA cannot handle greater than 4 reference frames
      CLog::Log(LOGNOTICE, "%s - [email protected] detected, VDA cannot decode.", __FUNCTION__);
      CFRelease(avcCData);
      return false;
    }

    std::string rendervendor = g_Windowing.GetRenderVendor();
    StringUtils::ToLower(rendervendor);
    if (rendervendor.find("nvidia") != std::string::npos)
    {
      // Nvidia gpu's are all powerful and work the way god intended
      m_decode_async = true;
      // The gods are liars, ignore the sirens for now.
      m_use_cvBufferRef = false;
    }
    else if (rendervendor.find("intel") != std::string::npos)
    {
      // Intel gpu are borked when using cvBufferRef
      m_decode_async = true;
      m_use_cvBufferRef = false;
    }
    else
    {
      // ATI gpu's are borked when using async decode
      m_decode_async = false;
      // They lie here too.
      m_use_cvBufferRef = false;
    }

    if (!m_use_cvBufferRef)
    {
      // allocate a YV12 DVDVideoPicture buffer.
      // first make sure all properties are reset.
      memset(&m_videobuffer, 0, sizeof(DVDVideoPicture));
      unsigned int iPixels = width * height;
      unsigned int iChromaPixels = iPixels/4;

      m_videobuffer.dts = DVD_NOPTS_VALUE;
      m_videobuffer.pts = DVD_NOPTS_VALUE;
      m_videobuffer.iFlags = DVP_FLAG_ALLOCATED;
      m_videobuffer.format = RENDER_FMT_YUV420P;
      m_videobuffer.color_range  = 0;
      m_videobuffer.color_matrix = 4;
      m_videobuffer.iWidth  = width;
      m_videobuffer.iHeight = height;
      m_videobuffer.iDisplayWidth  = width;
      m_videobuffer.iDisplayHeight = height;

      m_videobuffer.iLineSize[0] = width;   //Y
      m_videobuffer.iLineSize[1] = width/2; //U
      m_videobuffer.iLineSize[2] = width/2; //V
      m_videobuffer.iLineSize[3] = 0;

      m_videobuffer.data[0] = (uint8_t*)malloc(16 + iPixels);
      m_videobuffer.data[1] = (uint8_t*)malloc(16 + iChromaPixels);
      m_videobuffer.data[2] = (uint8_t*)malloc(16 + iChromaPixels);
      m_videobuffer.data[3] = NULL;

      // set all data to 0 for less artifacts.. hmm.. what is black in YUV??
      memset(m_videobuffer.data[0], 0, iPixels);
      memset(m_videobuffer.data[1], 0, iChromaPixels);
      memset(m_videobuffer.data[2], 0, iChromaPixels);
    }

    // setup the decoder configuration dict
    CFMutableDictionaryRef decoderConfiguration = CFDictionaryCreateMutable(
      kCFAllocatorDefault, 4, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);

    CFNumberRef avcWidth  = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &width);
    CFNumberRef avcHeight = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &height);
    CFNumberRef avcFormat = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &m_format);

    CFDictionarySetValue(decoderConfiguration, kVDADecoderConfiguration_Height, avcHeight);
    CFDictionarySetValue(decoderConfiguration, kVDADecoderConfiguration_Width,  avcWidth);
    CFDictionarySetValue(decoderConfiguration, kVDADecoderConfiguration_SourceFormat, avcFormat);
    CFDictionarySetValue(decoderConfiguration, kVDADecoderConfiguration_avcCData, avcCData);

    // release the retained object refs, decoderConfiguration owns them now
    CFRelease(avcWidth);
    CFRelease(avcHeight);
    CFRelease(avcFormat);
    CFRelease(avcCData);

    // setup the destination image buffer dict, vda will output this pict format
    CFMutableDictionaryRef destinationImageBufferAttributes = CFDictionaryCreateMutable(
      kCFAllocatorDefault, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
    OSType cvPixelFormatType = kCVPixelFormatType_422YpCbCr8;
    CFNumberRef pixelFormat  = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &cvPixelFormatType);

    // an IOSurface properties dictionary
    CFDictionaryRef iosurfaceDictionary = CFDictionaryCreate(kCFAllocatorDefault,
      NULL, NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);

    CFDictionarySetValue(destinationImageBufferAttributes,
      kCVPixelBufferPixelFormatTypeKey, pixelFormat);
    CFDictionarySetValue(destinationImageBufferAttributes,
      kCVPixelBufferIOSurfacePropertiesKey, iosurfaceDictionary);
    // release the retained object refs, destinationImageBufferAttributes owns them now
    CFRelease(pixelFormat);
    CFRelease(iosurfaceDictionary);

    // create the VDADecoder object
    OSStatus status;
    try
    {
      status = VDADecoderCreate(decoderConfiguration, destinationImageBufferAttributes,
        (VDADecoderOutputCallback*)VDADecoderCallback, this, (VDADecoder*)&m_vda_decoder);
    }
    catch (...)
    {
      CLog::Log(LOGERROR, "%s - exception",__FUNCTION__);
      status = kVDADecoderDecoderFailedErr;
    }
    CFRelease(decoderConfiguration);
    CFRelease(destinationImageBufferAttributes);
    if (CDarwinUtils::DeviceHasLeakyVDA())
      CFRelease(pixelFormat);
    if (status != kVDADecoderNoErr)
    {
      if (status == kVDADecoderDecoderFailedErr)
          CLog::Log(LOGNOTICE, "%s - VDADecoder Codec failed to open, currently in use by another process",
            __FUNCTION__);
      else
          CLog::Log(LOGNOTICE, "%s - VDADecoder Codec failed to open, status(%d), profile(%d), level(%d)",
            __FUNCTION__, (int)status, profile, level);
      return false;
    }

    m_DropPictures = false;
    m_max_ref_frames = std::max(m_max_ref_frames + 1, 5);
    m_sort_time = 0;
    return true;
  }

  return false;
}
Example #30
0
char *osd_get_clipboard_text(void)
{
	OSStatus err;

	PasteboardRef pasteboard_ref;
	err = PasteboardCreate(kPasteboardClipboard, &pasteboard_ref);
	if (err)
		return nullptr;

	PasteboardSynchronize(pasteboard_ref);

	ItemCount item_count;
	err = PasteboardGetItemCount(pasteboard_ref, &item_count);

	char *result = nullptr; // core expects a malloced C string of uft8 data
	for (UInt32 item_index = 1; (item_index <= item_count) && !result; item_index++)
	{
		PasteboardItemID item_id;
		err = PasteboardGetItemIdentifier(pasteboard_ref, item_index, &item_id);
		if (err)
			continue;

		CFArrayRef flavor_type_array;
		err = PasteboardCopyItemFlavors(pasteboard_ref, item_id, &flavor_type_array);
		if (err)
			continue;

		CFIndex const flavor_count = CFArrayGetCount(flavor_type_array);
		for (CFIndex flavor_index = 0; (flavor_index < flavor_count) && !result; flavor_index++)
		{
			CFStringRef const flavor_type = (CFStringRef)CFArrayGetValueAtIndex(flavor_type_array, flavor_index);

			CFStringEncoding encoding;
			if (UTTypeConformsTo(flavor_type, kUTTypeUTF16PlainText))
				encoding = kCFStringEncodingUTF16;
			else if (UTTypeConformsTo (flavor_type, kUTTypeUTF8PlainText))
				encoding = kCFStringEncodingUTF8;
			else if (UTTypeConformsTo (flavor_type, kUTTypePlainText))
				encoding = kCFStringEncodingMacRoman;
			else
				continue;

			CFDataRef flavor_data;
			err = PasteboardCopyItemFlavorData(pasteboard_ref, item_id, flavor_type, &flavor_data);

			if (!err)
			{
				CFStringRef string_ref = CFStringCreateFromExternalRepresentation(kCFAllocatorDefault, flavor_data, encoding);
				CFDataRef data_ref = CFStringCreateExternalRepresentation (kCFAllocatorDefault, string_ref, kCFStringEncodingUTF8, '?');
				CFRelease(string_ref);
				CFRelease(flavor_data);

				CFIndex const length = CFDataGetLength(data_ref);
				CFRange const range = CFRangeMake(0, length);

				result = reinterpret_cast<char *>(malloc(length + 1));
				if (result)
				{
					CFDataGetBytes(data_ref, range, reinterpret_cast<unsigned char *>(result));
					result[length] = 0;
				}

				CFRelease(data_ref);
			}
		}

		CFRelease(flavor_type_array);
	}

	CFRelease(pasteboard_ref);

	return result;
}