Ejemplo n.º 1
0
// This is the helper function to extract the strings from WebPluginExtensions
// in mimetype_dictionary_applier.
//  value   CFString containing a single file extension
//  context char ** of the current extension list.
static void extension_array_applier(const void *value, void *context)
{
    CFIndex     ext_length;
    char      **extension_list;

    extension_list  = context;
    ext_length      = CFStringGetMaximumSizeForEncoding(CFStringGetLength(value),
                                                        kCFStringEncodingUTF8);
    *extension_list = realloc(*extension_list, strlen(*extension_list)
                                + ext_length
                                + 1
                                + 1);

    // If I'm not the first extension, append a comma delimiter.
    if (strlen(*extension_list)) {
        strcat(*extension_list, ",");
    }

    // Append this string to the list.
    CFStringGetCString(value,
                       *extension_list + strlen(*extension_list),
                       ext_length + 1,
                       kCFStringEncodingUTF8);

    return;
}
Ejemplo n.º 2
0
CFIndex
CFStringGetMaximumSizeOfFileSystemRepresentation (CFStringRef string)
{
  CFIndex length = CFStringGetLength (string);
  return
    CFStringGetMaximumSizeForEncoding (length, CFStringGetSystemEncoding ());
}
Ejemplo n.º 3
0
ST_FUNC ST_Error ST_ID3v2_TextFrame_setTextStr(ST_TextFrame *f, CFStringRef s) {
    CFIndex slen;
    CFIndex l;
    uint8_t *buf;
    void *tmp;

    if(!f || !s) 
        return ST_Error_InvalidArgument;

    /* Make space for it */
    slen = CFStringGetLength(s);
    l = CFStringGetMaximumSizeForEncoding(slen, encs[f->encoding]);

    if(!(buf = (uint8_t *)malloc(l)))
        return ST_Error_errno;

    CFStringGetBytes(s, CFRangeMake(0, slen), encs[f->encoding], 0,
                     f->encoding == ST_TextEncoding_UTF16, buf, l, &slen);

    /* Attempt to make it smaller */
    if(slen != l) {
        if((tmp = realloc(buf, slen)))
            buf = (uint8_t *)tmp;
    }

    free(f->string);
    f->size = slen;
    f->string = buf;

    return ST_Error_None;
}
Ejemplo n.º 4
0
/**
 * Increment iterator of a #PLIST_DICT node.
 *
 * @param node the node of type #PLIST_DICT
 * @param iter iterator of the dictionary
 * @param key a location to store the key, or NULL.
 * @param val a location to store the value, or NULL.
 */
void plist_dict_next_item(plist_t node, plist_dict_iter iter, char **key, plist_t *val)
{
	assert(CFGetTypeID(node) == CFDictionaryGetTypeID());

	struct {
		CFIndex index;
		CFIndex count;
		const void * pairs[][2];
	} * myiter;

	myiter = iter;

	if (myiter->index < myiter->count) {
		if (key) {
			CFStringRef keyRef = myiter->pairs[myiter->index][0];
			CFIndex maxSize = CFStringGetMaximumSizeForEncoding(CFStringGetLength(keyRef), kCFStringEncodingUTF8);
			char *keyData = malloc(++maxSize);
			CFStringGetCString(keyRef, keyData, maxSize, kCFStringEncodingUTF8);
			*key = keyData;
		}
		if (val)
			*val = myiter->pairs[myiter->index][1];

		myiter->index += 1;
	}
	else {
		if (key) *key = NULL;
		if (val) *val = NULL;
	}
}
SecPolicyRef SecPolicyCreateAppleSSLService(CFStringRef hostname)
{
	// SSL server, pinned to an Apple intermediate
	SecPolicyRef policy = SecPolicyCreateSSL(true, hostname);
	if (policy) {
		// change options for policy evaluation
		char *strbuf = NULL;
		const char *hostnamestr = NULL;
		if (hostname) {
			hostnamestr = CFStringGetCStringPtr(hostname, kCFStringEncodingUTF8);
			if (hostnamestr == NULL) {
				CFIndex maxLen = CFStringGetMaximumSizeForEncoding(CFStringGetLength(hostname), kCFStringEncodingUTF8) + 1;
				strbuf = (char *)malloc(maxLen);
				if (CFStringGetCString(hostname, strbuf, maxLen, kCFStringEncodingUTF8)) {
					hostnamestr = strbuf;
				}
			}
		}
		uint32 hostnamelen = (hostnamestr) ? (uint32)strlen(hostnamestr) : 0;
		uint32 flags = 0x00000002; // 2nd-lowest bit set to require Apple intermediate pin
		CSSM_APPLE_TP_SSL_OPTIONS opts = {CSSM_APPLE_TP_SSL_OPTS_VERSION, hostnamelen, hostnamestr, flags};
		CSSM_DATA data = {sizeof(opts), (uint8*)&opts};
		SecPolicySetValue(policy, &data);
	}
	return policy;
}
void ARRAY_TEXT::convertToUTF8(const CUTF16String* fromString, CUTF8String* toString)
{
#ifdef _WIN32
	int len = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, (LPCWSTR)fromString->c_str(), fromString->length(), NULL, 0, NULL, NULL);
	
	if(len){
		std::vector<uint8_t> buf(len + 1);
		if(WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, (LPCWSTR)fromString->c_str(), fromString->length(), (LPSTR)&buf[0], len, NULL, NULL)){
			*toString = CUTF8String((const uint8_t *)&buf[0]);
		}
	}
           
#else
           CFStringRef str = CFStringCreateWithCharacters(kCFAllocatorDefault, (const UniChar *)fromString->c_str(), fromString->length());
           if(str){
               
               size_t size = CFStringGetMaximumSizeForEncoding(CFStringGetLength(str), kCFStringEncodingUTF8) + sizeof(uint8_t);
               std::vector<uint8_t> buf(size);
               CFIndex len = 0;
               CFStringGetBytes(str, CFRangeMake(0, CFStringGetLength(str)), kCFStringEncodingUTF8, 0, true, (UInt8 *)&buf[0], size, &len);
               
               *toString = CUTF8String((const uint8_t *)&buf[0], len);	
               CFRelease(str);
           }	
           
#endif
}
Ejemplo n.º 7
0
char *
_mongoc_cfstringref_to_cstring (CFStringRef str)
{
   CFIndex length;
   CFStringEncoding encoding;
   CFIndex max_size;
   char *cs;

   if (!str) {
      return NULL;
   }

   if (CFGetTypeID (str) != CFStringGetTypeID ()) {
      return NULL;
   }

   length = CFStringGetLength (str);
   encoding = kCFStringEncodingASCII;
   max_size = CFStringGetMaximumSizeForEncoding (length, encoding) + 1;
   cs = bson_malloc ((size_t) max_size);

   if (CFStringGetCString (str, cs, max_size, encoding)) {
      return cs;
   }

   bson_free (cs);
   return NULL;
}
Ejemplo n.º 8
0
static OSStatus GetAudioPropertyString(AudioObjectID id,
                                       AudioObjectPropertySelector selector,
                                       char **outData)
{
    OSStatus err;
    AudioObjectPropertyAddress property_address;
    UInt32 i_param_size;
    CFStringRef string;
    CFIndex string_length;

    property_address.mSelector = selector;
    property_address.mScope    = kAudioObjectPropertyScopeGlobal;
    property_address.mElement  = kAudioObjectPropertyElementMaster;

    i_param_size = sizeof(CFStringRef);
    err = AudioObjectGetPropertyData(id, &property_address, 0, NULL, &i_param_size, &string);
    if (err != noErr)
        return err;

    string_length = CFStringGetMaximumSizeForEncoding(CFStringGetLength(string),
                                                      kCFStringEncodingASCII);
    *outData = malloc(string_length + 1);
    CFStringGetCString(string, *outData, string_length + 1, kCFStringEncodingASCII);

    CFRelease(string);

    return err;
}
Ejemplo n.º 9
0
int
cfstring_to_cstring(const CFStringRef val, char **buffer)
{
	CFIndex maxlen = 0;
	int retval = PAM_BUF_ERR;
	
	if (NULL == val || NULL == buffer) {
		openpam_log(PAM_LOG_DEBUG, "NULL argument passed");
		retval = PAM_SERVICE_ERR;
		goto cleanup;
	}
	
	maxlen = CFStringGetMaximumSizeForEncoding(CFStringGetLength(val), kCFStringEncodingUTF8);
	*buffer = calloc(maxlen + 1, sizeof(char));
	if (NULL == *buffer) {
		openpam_log(PAM_LOG_DEBUG, "malloc() failed");
		retval = PAM_BUF_ERR;
		goto cleanup;
	}
	
	if (CFStringGetCString(val, *buffer, maxlen + 1, kCFStringEncodingUTF8)) {
		retval =  PAM_SUCCESS;
	} else {
		openpam_log(PAM_LOG_DEBUG, "CFStringGetCString failed.");
		free(*buffer);
		*buffer = NULL;
	}
	
cleanup:
	if (PAM_SUCCESS != retval)
		openpam_log(PAM_LOG_ERROR, "failed: %d", retval);
	
	return retval;
}
Ejemplo n.º 10
0
OSG_BEGIN_NAMESPACE

/********************** OS X **************************/
#ifdef __APPLE__

std::string FSRef2String(const FSRef& foundRef)
{
    std::string Result("");

    CFURLRef tURL;
    tURL = CFURLCreateFromFSRef(kCFAllocatorDefault, &foundRef);

    CFStringRef tCFString = CFURLCopyFileSystemPath(tURL,
                                                    kCFURLPOSIXPathStyle);

    CFIndex buf_len = 1 + CFStringGetMaximumSizeForEncoding(CFStringGetLength(tCFString), 
                                                            kCFStringEncodingUTF8);
    char *buffer  = new char[buf_len];
    CFStringGetCString(tCFString, buffer, buf_len,
                       kCFStringEncodingUTF8);

    Result = std::string(buffer);

    delete[] buffer;
    CFRelease(tCFString);
    CFRelease(tURL);

    return Result;
}
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;
}
Ejemplo n.º 12
0
/* http://stackoverflow.com/a/12535482 */
static CFDataRef APCopyDataFromHexString(CFStringRef string)
{
    CFIndex length = CFStringGetLength(string);
    CFIndex maxSize =CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8);
    char *cString = (char *)malloc(maxSize);
    CFStringGetCString(string, cString, maxSize, kCFStringEncodingUTF8);
    
    
    /* allocate the buffer */
    UInt8 * buffer = malloc((strlen(cString) / 2));
    
    char *h = cString; /* this will walk through the hex string */
    UInt8 *b = buffer; /* point inside the buffer */
    
    /* offset into this string is the numeric value */
    char translate[] = "0123456789abcdef";
    
    for ( ; *h; h += 2, ++b) /* go by twos through the hex string */
        *b = ((strchr(translate, *h) - translate) * 16) /* multiply leading digit by 16 */
        + ((strchr(translate, *(h+1)) - translate));
    
    CFDataRef data = CFDataCreate(kCFAllocatorDefault, buffer, (strlen(cString) / 2));
    free(cString);
    free(buffer);
    
    return data;
}
Ejemplo n.º 13
0
	FILE* fopen (const char *filename, const char *mode) {
		
		#ifdef HX_MACOS
		FILE *result = ::fopen (filename, "rb");
		if (!result) {
			CFStringRef str = CFStringCreateWithCString (NULL, filename, kCFStringEncodingUTF8);
			CFURLRef path = CFBundleCopyResourceURL (CFBundleGetMainBundle (), str, NULL, NULL);
			CFRelease (str);
			if (path) {
				str = CFURLCopyPath (path);
				CFIndex maxSize = CFStringGetMaximumSizeForEncoding (CFStringGetLength (str), kCFStringEncodingUTF8);
				char *buffer = (char *)malloc (maxSize);
				if (CFStringGetCString (str, buffer, maxSize, kCFStringEncodingUTF8)) {
					result = ::fopen (buffer,"rb");
					free (buffer);
				}
				CFRelease (str);
				CFRelease (path);
			}
		}
		return result;
		#else
		return ::fopen (filename, mode);
		#endif
		
	}
Ejemplo n.º 14
0
char *create_cstr_from_cfstring(CFStringRef cfstring)
{
  CFIndex str_len = CFStringGetLength(cfstring);
  if (str_len < 0)
  {
    return NULL;
  }

  CFIndex buf_len = CFStringGetMaximumSizeForEncoding(str_len, kCFStringEncodingUTF8) + 1;
  if (buf_len < 1)
  {
    return NULL;
  }

  char *cstr = (char *)malloc(buf_len);
  if (cstr == NULL)
  {
    return NULL;
  }

  if (CFStringGetCString(cfstring, cstr, buf_len, kCFStringEncodingUTF8))
  {
    return cstr;
  }

  return NULL;
}
Ejemplo n.º 15
0
void MDSAttrParser::parseFile(CFURLRef infoUrl, CFStringRef subdir)
{
	CFStringRef infoType = NULL;
	
	/* Get contents of mdsinfo file as dictionary */
	MDSDictionary mdsDict(infoUrl, subdir, mPath);
	/* Make sure we set all possible MDS values before checking for GUID */
	mdsDict.setDefaults(mDefaults);
	if (mGuid == NULL) {
		CFStringRef guid = (CFStringRef)mdsDict.lookup("ModuleID", true, CFStringGetTypeID());
		if (guid) {
			CFIndex copylen = CFStringGetMaximumSizeForEncoding(CFStringGetLength(guid), kCFStringEncodingUTF8) + 1/*nul terminator*/;
			mGuid = new char[copylen];
			if (false == CFStringGetCString(guid, mGuid, copylen, kCFStringEncodingUTF8)) {
				logFileError("Error copying GUID", infoUrl, NULL, NULL);
				delete [] mGuid;
				mGuid = NULL;
				CssmError::throwMe(CSSM_ERRCODE_MDS_ERROR);
			}
		}
		else {
			logFileError("No GUID associated with plugin?", infoUrl, NULL, NULL);
			CssmError::throwMe(CSSM_ERRCODE_MDS_ERROR);
		}
	}
	
	MPDebug("Parsing mdsinfo file %s", mdsDict.fileDesc());
	
	/* Determine what kind of info file this is and dispatch accordingly */
	infoType = (CFStringRef)mdsDict.lookup(CFSTR(MDS_INFO_FILE_TYPE),
		true, CFStringGetTypeID());
	if(infoType == NULL) {
		logFileError("Malformed MDS Info file", infoUrl, NULL, NULL);
		CssmError::throwMe(CSSM_ERRCODE_MDS_ERROR);
	}
	
	/* be robust here, errors in these low-level routines do not affect
	 * the rest of our task */
	try {
		if(CFStringCompare(infoType, CFSTR(MDS_INFO_FILE_TYPE_CSSM), 0) 
				== kCFCompareEqualTo) {
			parseCssmInfo(&mdsDict);
		}
		else if(CFStringCompare(infoType, CFSTR(MDS_INFO_FILE_TYPE_PLUGIN), 0) 
				== kCFCompareEqualTo) {
			parsePluginCommon(&mdsDict);
		}
		else if(CFStringCompare(infoType, CFSTR(MDS_INFO_FILE_TYPE_RECORD), 0) 
				== kCFCompareEqualTo) {
			parsePluginSpecific(&mdsDict);
		}
		else {
			logFileError("Malformed MDS Info file", infoUrl, NULL, NULL);
		}
	}
	catch(...) {
	
	}
}
Ejemplo n.º 16
0
static void vprintf_stderr_common(const char* format, va_list args)
{
#if USE(CF) && !OS(WINDOWS)
    if (strstr(format, "%@")) {
        CFStringRef cfFormat = CFStringCreateWithCString(NULL, format, kCFStringEncodingUTF8);

#if COMPILER(CLANG)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wformat-nonliteral"
#endif
        CFStringRef str = CFStringCreateWithFormatAndArguments(NULL, NULL, cfFormat, args);
#if COMPILER(CLANG)
#pragma clang diagnostic pop
#endif
        CFIndex length = CFStringGetMaximumSizeForEncoding(CFStringGetLength(str), kCFStringEncodingUTF8);
        char* buffer = (char*)malloc(length + 1);

        CFStringGetCString(str, buffer, length, kCFStringEncodingUTF8);

        logToStderr(buffer);

        free(buffer);
        CFRelease(str);
        CFRelease(cfFormat);
        return;
    }

#if USE(APPLE_SYSTEM_LOG)
    va_list copyOfArgs;
    va_copy(copyOfArgs, args);
    asl_vlog(0, 0, ASL_LEVEL_NOTICE, format, copyOfArgs);
    va_end(copyOfArgs);
#endif

    // Fall through to write to stderr in the same manner as other platforms.

#elif HAVE(ISDEBUGGERPRESENT)
    if (IsDebuggerPresent()) {
        size_t size = 1024;

        do {
            char* buffer = (char*)malloc(size);

            if (buffer == NULL)
                break;

            if (vsnprintf(buffer, size, format, args) != -1) {
                OutputDebugStringA(buffer);
                free(buffer);
                break;
            }

            free(buffer);
            size *= 2;
        } while (size > 1024);
    }
#endif
    vfprintf(stderr, format, args);
}
Ejemplo n.º 17
0
Archivo: parse_url.c Proyecto: aosm/smb
/* 
 * Get the server name out of the URL. CFURLCopyHostName will escape out the 
 * server name for us. So just convert it to the correct code page encoding.
 *
 * Note: Currently we put the server name into a c-style string. In the future 
 * it would be nice to keep this as a CFString.
 */
static int SetServerFromURL(struct smb_ctx *ctx, CFURLRef url)
{
	CFIndex maxlen;
	CFStringRef serverNameRef = CFURLCopyHostName(url);
	char *ipV6Name = NULL;

	ipV6Name = CStringCreateWithCFString(serverNameRef);
	if (ipV6Name && isIPv6NumericName(ipV6Name)) {
        /* CFURLCopyHostName removed the [] so put them back in */
        CFMutableStringRef newServer = CFStringCreateMutableCopy(NULL, 1024, CFSTR("["));
        if (newServer) {
            CFStringAppend(newServer, serverNameRef);
            CFStringAppend(newServer, CFSTR("]"));
            CFRelease(serverNameRef);
            serverNameRef = newServer;
        }
    }

	/* Free up the buffer we allocated */
	if (ipV6Name) {
		free(ipV6Name);
    }
    
    /*
	 * Every time we parse the URL we end up replacing the server name. In the 
	 * future we should skip replacing the server name if we already have one and
	 * the one return CFURLCopyHostName matches it.
	 *
	 * Not going to make that big of a change in an update, so lets limit to the
	 * case were we are dealing with using a domain controller.
	 */
	if (serverNameRef && ctx->serverNameRef && ctx->serverName &&
		(ctx->serverIsDomainController) &&	
		(ctx->ct_flags & SMBCF_CONNECTED) && 
		(CFStringCompare(serverNameRef, ctx->serverNameRef, 0) == kCFCompareEqualTo)) {
		CFRelease(serverNameRef);
		return 0; /* Same name nothing to do here */
	}
	if (ctx->serverNameRef) {
		CFRelease(ctx->serverNameRef);
	}
		/* The serverNameRef should always contain the URL host name or the Bonjour Name */
	ctx->serverNameRef = serverNameRef;
	if (ctx->serverNameRef == NULL)
		return EINVAL;
	DebugLogCFString(ctx->serverNameRef, "Server", __FUNCTION__, __LINE__);
	
	maxlen = CFStringGetMaximumSizeForEncoding(CFStringGetLength(ctx->serverNameRef), kCFStringEncodingUTF8) + 1;
	if (ctx->serverName)
		free(ctx->serverName);
	ctx->serverName = malloc(maxlen);
	if (!ctx->serverName) {
		CFRelease(ctx->serverNameRef);
		ctx->serverNameRef = NULL;
		return ENOMEM;
	}
	CFStringGetCString(ctx->serverNameRef, ctx->serverName, maxlen, kCFStringEncodingUTF8);
	return 0;
}
Ejemplo n.º 18
0
char *cfstr_get_cstr(CFStringRef cfstr)
{
    CFIndex size =
        CFStringGetMaximumSizeForEncoding(
            CFStringGetLength(cfstr), CA_CFSTR_ENCODING) + 1;
    char *buffer = talloc_zero_size(NULL, size);
    CFStringGetCString(cfstr, buffer, size, CA_CFSTR_ENCODING);
    return buffer;
}
Ejemplo n.º 19
0
static void vprintf_stderr_common(const char* format, va_list args)
{
#if PLATFORM(MAC)
    if (strstr(format, "%@")) {
        CFStringRef cfFormat = CFStringCreateWithCString(NULL, format, kCFStringEncodingUTF8);
        CFStringRef str = CFStringCreateWithFormatAndArguments(NULL, NULL, cfFormat, args);

        int length = CFStringGetMaximumSizeForEncoding(CFStringGetLength(str), kCFStringEncodingUTF8);
        char* buffer = (char*)malloc(length + 1);

        CFStringGetCString(str, buffer, length, kCFStringEncodingUTF8);

        fputs(buffer, stderr);

        free(buffer);
        CFRelease(str);
        CFRelease(cfFormat);
        return;
    }
#elif PLATFORM(BLACKBERRY)
    BlackBerry::Platform::logV(BlackBerry::Platform::LogLevelInfo, format, args);
#elif HAVE(ISDEBUGGERPRESENT)
    if (IsDebuggerPresent()) {
        size_t size = 1024;

        do {
            char* buffer = (char*)malloc(size);

            if (buffer == NULL)
                break;

            if (_vsnprintf(buffer, size, format, args) != -1) {
#if OS(WINCE)
                // WinCE only supports wide chars
                wchar_t* wideBuffer = (wchar_t*)malloc(size * sizeof(wchar_t));
                if (wideBuffer == NULL)
                    break;
                for (unsigned int i = 0; i < size; ++i) {
                    if (!(wideBuffer[i] = buffer[i]))
                        break;
                }
                OutputDebugStringW(wideBuffer);
                free(wideBuffer);
#else
                OutputDebugStringA(buffer);
#endif
                free(buffer);
                break;
            }

            free(buffer);
            size *= 2;
        } while (size > 1024);
    }
#endif
    vfprintf(stderr, format, args);
}
Ejemplo n.º 20
0
Array AudioDriverCoreAudio::_get_device_list(bool capture) {

	Array list;

	list.push_back("Default");

	AudioObjectPropertyAddress prop;

	prop.mSelector = kAudioHardwarePropertyDevices;
	prop.mScope = kAudioObjectPropertyScopeGlobal;
	prop.mElement = kAudioObjectPropertyElementMaster;

	UInt32 size = 0;
	AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &prop, 0, NULL, &size);
	AudioDeviceID *audioDevices = (AudioDeviceID *)malloc(size);
	AudioObjectGetPropertyData(kAudioObjectSystemObject, &prop, 0, NULL, &size, audioDevices);

	UInt32 deviceCount = size / sizeof(AudioDeviceID);
	for (UInt32 i = 0; i < deviceCount; i++) {
		prop.mScope = capture ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
		prop.mSelector = kAudioDevicePropertyStreamConfiguration;

		AudioObjectGetPropertyDataSize(audioDevices[i], &prop, 0, NULL, &size);
		AudioBufferList *bufferList = (AudioBufferList *)malloc(size);
		AudioObjectGetPropertyData(audioDevices[i], &prop, 0, NULL, &size, bufferList);

		UInt32 channelCount = 0;
		for (UInt32 j = 0; j < bufferList->mNumberBuffers; j++)
			channelCount += bufferList->mBuffers[j].mNumberChannels;

		free(bufferList);

		if (channelCount >= 1) {
			CFStringRef cfname;

			size = sizeof(CFStringRef);
			prop.mSelector = kAudioObjectPropertyName;

			AudioObjectGetPropertyData(audioDevices[i], &prop, 0, NULL, &size, &cfname);

			CFIndex length = CFStringGetLength(cfname);
			CFIndex maxSize = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8) + 1;
			char *buffer = (char *)malloc(maxSize);
			if (CFStringGetCString(cfname, buffer, maxSize, kCFStringEncodingUTF8)) {
				// Append the ID to the name in case we have devices with duplicate name
				list.push_back(String(buffer) + " (" + itos(audioDevices[i]) + ")");
			}

			free(buffer);
		}
	}

	free(audioDevices);

	return list;
}
Ejemplo n.º 21
0
size_t der_sizeof_string(CFStringRef str, CFErrorRef *error)
{
    const CFIndex str_length    = CFStringGetLength(str);
    const CFIndex maximum       = CFStringGetMaximumSizeForEncoding(str_length, kCFStringEncodingUTF8);

    CFIndex encodedLen = 0;
    CFIndex converted = CFStringGetBytes(str, CFRangeMake(0, str_length), kCFStringEncodingUTF8, 0, false, NULL, maximum, &encodedLen);

    return ccder_sizeof(CCDER_UTF8_STRING, (converted == str_length) ? encodedLen : 0);
}
Ejemplo n.º 22
0
char *
CFStringToCString(CFStringRef input)
{
	if (input == NULL)
		return NULL;
	int strlen = CFStringGetMaximumSizeForEncoding(CFStringGetLength(input), kCFStringEncodingUTF8);
	char *output = NewPtr(strlen+1);
	CFStringGetCString(input, output, strlen+1, kCFStringEncodingUTF8);
	return output;
}
bool
SetXiphCommentFromMetadata(const AudioMetadata& metadata, TagLib::Ogg::XiphComment *tag)
{
	assert(NULL != tag);

	// Standard tags
	SetXiphComment(tag, "ALBUM", metadata.GetAlbumTitle());
	SetXiphComment(tag, "ARTIST", metadata.GetArtist());
	SetXiphComment(tag, "ALBUMARTIST", metadata.GetAlbumArtist());
	SetXiphComment(tag, "COMPOSER", metadata.GetComposer());
	SetXiphComment(tag, "GENRE", metadata.GetGenre());
	SetXiphComment(tag, "DATE", metadata.GetReleaseDate());
	SetXiphComment(tag, "DESCRIPTION", metadata.GetComment());
	SetXiphComment(tag, "TITLE", metadata.GetTitle());
	SetXiphCommentNumber(tag, "TRACKNUMBER", metadata.GetTrackNumber());
	SetXiphCommentNumber(tag, "TRACKTOTAL", metadata.GetTrackTotal());
	SetXiphCommentBoolean(tag, "COMPILATION", metadata.GetCompilation());
	SetXiphCommentNumber(tag, "DISCNUMBER", metadata.GetDiscNumber());
	SetXiphCommentNumber(tag, "DISCTOTAL", metadata.GetDiscTotal());
	SetXiphComment(tag, "ISRC", metadata.GetISRC());
	SetXiphComment(tag, "MCN", metadata.GetMCN());
	
	// Additional metadata
	CFDictionaryRef additionalMetadata = metadata.GetAdditionalMetadata();
	if(NULL != additionalMetadata) {
		CFIndex count = CFDictionaryGetCount(additionalMetadata);
		
		const void * keys [count];
		const void * values [count];
		
		CFDictionaryGetKeysAndValues(additionalMetadata, reinterpret_cast<const void **>(keys), reinterpret_cast<const void **>(values));
		
		for(CFIndex i = 0; i < count; ++i) {
			CFIndex keySize = CFStringGetMaximumSizeForEncoding(CFStringGetLength(reinterpret_cast<CFStringRef>(keys[i])), kCFStringEncodingASCII);
			char key [keySize + 1];
			
			if(!CFStringGetCString(reinterpret_cast<CFStringRef>(keys[i]), key, keySize + 1, kCFStringEncodingASCII)) {
				log4cxx::LoggerPtr logger = log4cxx::Logger::getLogger("org.sbooth.AudioEngine");
				LOG4CXX_ERROR(logger, "CFStringGetCString failed");
				continue;
			}
			
			SetXiphComment(tag, key, reinterpret_cast<CFStringRef>(values[i]));
		}
	}
	
	// ReplayGain info
	SetXiphCommentDouble(tag, "REPLAYGAIN_REFERENCE_LOUDNESS", metadata.GetReplayGainReferenceLoudness(), CFSTR("%2.1f dB"));
	SetXiphCommentDouble(tag, "REPLAYGAIN_TRACK_GAIN", metadata.GetReplayGainReferenceLoudness(), CFSTR("%+2.2f dB"));
	SetXiphCommentDouble(tag, "REPLAYGAIN_TRACK_PEAK", metadata.GetReplayGainTrackGain(), CFSTR("%1.8f"));
	SetXiphCommentDouble(tag, "REPLAYGAIN_ALBUM_GAIN", metadata.GetReplayGainAlbumGain(), CFSTR("%+2.2f dB"));
	SetXiphCommentDouble(tag, "REPLAYGAIN_ALBUM_PEAK", metadata.GetReplayGainAlbumPeak(), CFSTR("%1.8f"));

	return true;
}
Ejemplo n.º 24
0
Archivo: parse_url.c Proyecto: aosm/smb
/*
 * We need to separate the share name and any path component from the URL.
 *	URL "smb://*****:*****@server" no share name or path.
 *	URL "smb://*****:*****@server/"no share name or path.
 *	URL "smb://*****:*****@server/share" just a share name.
 *	URL "smb://*****:*****@server/share/path" share name and path.
 *
 * The Share name and Path name will not begin with a slash.
 *		smb://server/ntfs  share = ntfs path = NULL
 *		smb://ntfs/dir1/dir2  share = ntfs path = dir1/dir2
 */
static int SetShareAndPathFromURL(struct smb_ctx *ctx, CFURLRef url)
{
	CFStringRef share = NULL;
	CFStringRef path = NULL;
	CFIndex maxlen;
	int error;

	error = GetShareAndPathFromURL(url, &share, &path);
	if (error) {
		return error;
    }

	/* Since there is no share name we have nothing left to do. */
	if (share == NULL) {
        if (path != NULL) {
            CFRelease(path);
        }
        
		return 0;
    }
    
	DebugLogCFString(share, "Share", __FUNCTION__, __LINE__);
    
	CreateStringByReplacingPercentEscapesUTF8(&share, CFSTR(""));
	
	if (ctx->ct_origshare) {
		free(ctx->ct_origshare);
    }
	
	if (ctx->mountPath) {
		CFRelease(ctx->mountPath);
    }
	ctx->mountPath = NULL;
	
	maxlen = CFStringGetMaximumSizeForEncoding(CFStringGetLength(share), kCFStringEncodingUTF8) + 1;
	ctx->ct_origshare = malloc(maxlen);
	if (!ctx->ct_origshare) {
		CFRelease(share);
        
        if (path != NULL) {
            CFRelease(path);
        }
        
		return ENOMEM;
	}

	CFStringGetCString(share, ctx->ct_origshare, maxlen, kCFStringEncodingUTF8);
	str_upper(ctx->ct_sh.ioc_share, sizeof(ctx->ct_sh.ioc_share), share); 
	CFRelease(share);
	
	ctx->mountPath = path;

	return 0;
}
Ejemplo n.º 25
0
char *PortBurn_CStringFromCFString(CFStringRef cfname) {
   char *name;
   CFIndex len;

   len = CFStringGetMaximumSizeForEncoding(CFStringGetLength(cfname),
                                           kCFStringEncodingASCII);
   name = (char *)malloc(len + 1);
   name[0] = 0;
   CFStringGetCString(cfname, name, len + 1, kCFStringEncodingASCII);
   return name;
}
Ejemplo n.º 26
0
char * CFStringCopyUTF8String(CFStringRef aString) {
    if (aString == NULL) { return NULL; }

    CFIndex length = CFStringGetLength(aString);
    CFIndex maxSize = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8);
    char *buffer = (char *)malloc(maxSize);
    if (CFStringGetCString(aString, buffer, maxSize, kCFStringEncodingUTF8)) {
        return buffer;
    }
    return "";
}
Ejemplo n.º 27
0
char *secCopyCString(CFStringRef theString)
{
	CFIndex maxLength = CFStringGetMaximumSizeForEncoding(CFStringGetLength(theString), kCFStringEncodingUTF8) + 1;
	char* buffer = (char*) malloc(maxLength);
	Boolean converted = CFStringGetCString(theString, buffer, maxLength, kCFStringEncodingUTF8);
	if (!converted) {
       free(buffer);
       buffer = NULL;
	}
	return buffer;
}
Ejemplo n.º 28
0
Archivo: IPC.c Proyecto: aosm/Startup
CFRunLoopSourceRef CreateIPCRunLoopSource(CFStringRef aPortName, StartupContext aStartupContext)
{
    CFRunLoopSourceRef	aSource = NULL;
    CFMachPortRef	aMachPort = NULL;
    CFMachPortContext	aContext;
    kern_return_t       aKernReturn = KERN_FAILURE;

    aContext.version = 0;
    aContext.info = (void*) aStartupContext;
    aContext.retain = 0;
    aContext.release = 0;
    aContext.copyDescription = 0;
    aMachPort = CFMachPortCreate(NULL, NULL, &aContext, NULL);
    
    if (aMachPort && aPortName)
      {
        CFIndex aPortNameLength = CFStringGetLength(aPortName);
        CFIndex aPortNameSize = CFStringGetMaximumSizeForEncoding(aPortNameLength, kCFStringEncodingUTF8) + 1;
        uint8_t *aBuffer = CFAllocatorAllocate(NULL, aPortNameSize, 0);
        if (aBuffer && CFStringGetCString(aPortName,
                                        aBuffer,
                                        aPortNameSize,
                                        kCFStringEncodingUTF8))
          {
            mach_port_t   aBootstrapPort;
            task_get_bootstrap_port(mach_task_self(), &aBootstrapPort);
            aKernReturn = bootstrap_register(aBootstrapPort, aBuffer, CFMachPortGetPort(aMachPort));
          }
        if (aBuffer) CFAllocatorDeallocate(NULL, aBuffer);
      }

    if (aMachPort && aKernReturn == KERN_SUCCESS)
      {
        CFRunLoopSourceContext1 aSourceContext;
        aSourceContext.version = 1;
        aSourceContext.info = aMachPort;
        aSourceContext.retain = CFRetain;
        aSourceContext.release = CFRelease;
        aSourceContext.copyDescription = CFCopyDescription;
        aSourceContext.equal = CFEqual;
        aSourceContext.hash = CFHash;
        aSourceContext.getPort = getIPCPort;
        aSourceContext.perform = (void*)handleIPCMessage;
        aSource = CFRunLoopSourceCreate(NULL, 0, (CFRunLoopSourceContext*)&aSourceContext);
      }

    if (aMachPort && (!aSource || aKernReturn != KERN_SUCCESS))
      {
        CFMachPortInvalidate(aMachPort);
        CFRelease(aMachPort);
        aMachPort = NULL;
      }
    return aSource;
}
Ejemplo n.º 29
0
void MDSAttrParser::parseAttrs(CFStringRef subdir)
{
	/* get all *.mdsinfo files */
	CFArrayRef bundleInfoFiles = CFBundleCopyResourceURLsOfType(mBundle,
		CFSTR(MDS_INFO_TYPE),
		subdir);
	if(bundleInfoFiles == NULL) {
		Syslog::alert("MDSAttrParser: no mdsattr files for %s", mPath);
		return;
	}
	assert(CFGetTypeID(bundleInfoFiles) == CFArrayGetTypeID());
	
	/* process each .mdsinfo file */
	CFIndex numFiles = CFArrayGetCount(bundleInfoFiles);
	for(CFIndex i=0; i<numFiles; i++) {
		/* get filename as CFURL */
		CFURLRef infoUrl = NULL;
		
		infoUrl = reinterpret_cast<CFURLRef>(
			CFArrayGetValueAtIndex(bundleInfoFiles, i));
		if(infoUrl == NULL) {
			MPDebug("MDSAttrParser: CFBundleCopyResourceURLsOfType screwup 1");
			continue;
		}
		if(CFGetTypeID(infoUrl) != CFURLGetTypeID()) {
			MPDebug("MDSAttrParser: CFBundleCopyResourceURLsOfType screwup 2");
			continue;
		}
		
		// @@@  Workaround for 4234967: skip any filename beginning with "._"
		CFStringRef lastComponent = CFURLCopyLastPathComponent(infoUrl);
		if (lastComponent) {
			CFStringRef resFilePfx = CFSTR("._");
			// setting the search length and location like this permits, 
			// e.g., ".foo.mdsinfo" to be valid
			CFIndex resFilePfxLen = CFStringGetMaximumSizeForEncoding(CFStringGetLength(resFilePfx), kCFStringEncodingUTF8);
			CFRange range = CFRangeMake(0, resFilePfxLen);
			Boolean skip = CFStringFindWithOptions(lastComponent, 
												   resFilePfx, 
												   range,
												   0/*options*/,
												   NULL/*returned substr*/);
			CFRelease(lastComponent);
			if (skip == true) {
				Syslog::warning("MDSAttrParser: ignoring resource file");
				continue;
			}
		}
		
		parseFile(infoUrl, subdir);
	} /* for each mdsinfo */
	CF_RELEASE(bundleInfoFiles);
}
Ejemplo n.º 30
0
WB_INLINE
UTF8Char *__WBCFStringCopyUTF8Characters(CFStringRef string) {
  CFIndex length = CFStringGetMaximumSizeForEncoding(CFStringGetLength(string), kCFStringEncodingUTF8);
  UTF8Char *characters = calloc(length, sizeof(UTF8Char));
  if (!characters) return NULL;

  if (!CFStringGetCString(string, (char *)characters, length, kCFStringEncodingUTF8)) {
    free(characters);
    return NULL;
  }
  return characters;
}