/*
 * Writes a new configuration file with the contents of a CFArrayRef. Each
 * element of the array is a CFStringRef.
 */
void
configWrite(const char *path, CFArrayRef config)
{
	CFStringRef	str;
	CFDataRef	data;
	int		fd = -1;
	int		len;

	str  = CFStringCreateByCombiningStrings(NULL, config, CFSTR("\n"));
	data = CFStringCreateExternalRepresentation(NULL, str, kCFStringEncodingMacRoman, '.');
	CFRelease(str);

	fd = open(path, O_WRONLY|O_CREAT|O_TRUNC, 0644);
	if (fd < 0) {
		goto done;
	}

	len = CFDataGetLength(data);
	if (len) {
		(void)write(fd, CFDataGetBytePtr(data), len);
	}

    done:

	if (fd >= 0)
		close(fd);
	CFRelease(data);
	return;
}
/* do a [NSString stringByDeletingPathExtension] equivalent */
CFStringRef impExpImportDeleteExtension(
	CFStringRef			fileStr)
{
	CFDataRef fileStrData = CFStringCreateExternalRepresentation(NULL, fileStr,
		kCFStringEncodingUTF8, 0);
	if(fileStrData == NULL) {
		return NULL;
	}

	CFURLRef urlRef = CFURLCreateFromFileSystemRepresentation(NULL,
		CFDataGetBytePtr(fileStrData), CFDataGetLength(fileStrData), false);
	if(urlRef == NULL) {
		CFRelease(fileStrData);
		return NULL;
	}
	CFURLRef rtnUrl = CFURLCreateCopyDeletingPathExtension(NULL, urlRef);
	CFStringRef rtnStr = NULL;
	CFRelease(urlRef);
	if(rtnUrl) {
		rtnStr = CFURLGetString(rtnUrl);
		CFRetain(rtnStr);
		CFRelease(rtnUrl);
	}
	CFRelease(fileStrData);
	return rtnStr;
}
std::wstring MacUtils::CFStringRefToWString(CFStringRef aString)
{
    if (aString == NULL) {
        return L"";
    }
    
    if (!aString)
        return false;
    CFDataRef cfData = CFStringCreateExternalRepresentation(kCFAllocatorDefault,
                                                            aString, kCFStringEncodingUTF32, 0);
    CFRelease(aString);
    if (!cfData)
        return false;
    int out_byte_len = CFDataGetLength(cfData);
    out_byte_len -= sizeof(wchar_t); // don't count the 32 bit BOM char at start
    int out_len = out_byte_len / sizeof(wchar_t);
    wchar_t *tmp = new wchar_t[out_len + 1];
    // start after the BOM, hence sizeof(wchar_t)
    CFDataGetBytes(cfData, CFRangeMake(sizeof(wchar_t), out_byte_len),
                   (UInt8*)tmp);
    CFRelease(cfData);
    tmp[out_len] = 0;
    std::wstring result = tmp;
    delete[] tmp;
    
    return result;
}
Exemple #4
0
inline bool __JSONParseWithString(__JSONRef json, CFStringRef string, CFErrorRef *error) {
  bool success = 1;
  json->yajlParser = yajl_alloc(&json->yajlParserCallbacks, &json->yajlAllocFuncs, (void *)json);
  if (json->yajlParser) {
//  yajl_config(json->yajlParser, yajl_allow_comments, kJSONReadOptionAllowComments | options ? 1 : 0);
//  yajl_config(json->yajlParser, yajl_dont_validate_strings, kJSONReadOptionCheckUTF8 | options ? 1 : 0);
  
    CFDataRef data = CFStringCreateExternalRepresentation(json->allocator, string, kCFStringEncodingUTF8, 0);
    if (data) {
      if ((json->yajlParserStatus = yajl_parse(json->yajlParser, CFDataGetBytePtr(data), CFDataGetLength(data))) != yajl_status_ok) {
        if (error) {
          success = 0;
          
          unsigned char * str = yajl_get_error(json->yajlParser, 1, CFDataGetBytePtr(data), CFDataGetLength(data));
          fprintf(stderr, "%s", (const char *) str);
          yajl_free_error(json->yajlParser, str);
          
          *error = CFErrorCreateWithUserInfoKeysAndValues(json->allocator, CFSTR("com.github.mirek.CoreJSON"), (CFIndex)json->yajlParserStatus, (const void *) { kCFErrorDescriptionKey }, (const void *) { CFSTR("Test") }, 1);
        }
        // TODO: Error stuff
        //printf("ERROR: %s\n", yajl_get_error(json->yajlParser, 1, __JSONUTF8StringGetBuffer(utf8), __JSONUTF8StringGetMaximumSize(utf8)));
      }
    
      json->yajlParserStatus = yajl_complete_parse(json->yajlParser);
      CFRelease(data);
    } else {
Exemple #5
0
static CFDataRef IPCCallback(__unused CFMessagePortRef port, SInt32 messageID, __unused CFDataRef data, __unused void *info)
{
	switch(messageID)
	{
		case ServerCommandGetIP:
		{
			if(publicIPState == IPStateInvalid)
			{
				SCNetworkReachabilityFlags flags;
				SCNetworkReachabilityGetFlags(reachability, &flags);

				ReachabilityCallback(reachability, flags, NULL);
			}

			if(publicIPData)
				return publicIPData;

			return CFStringCreateExternalRepresentation(kCFAllocatorDefault, CFSTR(""), kCFStringEncodingUTF8, 0);
		}
		case ServerCommandStop:
		{
			CFRunLoopStop(CFRunLoopGetMain());
			return NULL;
		}
		case ServerCommandReload:
		{
			FetchIPAddress();
			return NULL;
		}

		default:
			return NULL;
	}
}
static CFDataRef
encryptString(SecKeyRef wrapKey, CFDataRef iv, CFStringRef str)
{
	CFDataRef retval = NULL;
 	CFErrorRef error = NULL;
    CFDataRef inputString = CFStringCreateExternalRepresentation(kCFAllocatorDefault, str, kCFStringEncodingMacRoman, 0xff);

 	SecTransformRef encryptTrans = SecEncryptTransformCreate(wrapKey, &error);
    if(error == NULL) {
		SecTransformRef group = SecTransformCreateGroupTransform();
		
        SecTransformSetAttribute(encryptTrans, kSecEncryptionMode, kSecModeCBCKey, &error);
        if(error == NULL) SecTransformSetAttribute(encryptTrans, kSecPaddingKey, kSecPaddingPKCS7Key, &error);
        if(error == NULL) SecTransformSetAttribute(encryptTrans, kSecTransformInputAttributeName, inputString, &error);
        if(error == NULL) SecTransformSetAttribute(encryptTrans, kSecIVKey, iv, &error);
		SecTransformRef encodeTrans = SecEncodeTransformCreate(kSecBase64Encoding, &error);
		SecTransformConnectTransforms(encryptTrans, kSecTransformOutputAttributeName, encodeTrans, kSecTransformInputAttributeName, group, &error);
		CFRelease(encodeTrans);  
		CFRelease(encryptTrans);
		if(error == NULL) retval = SecTransformExecute(group, &error);
        if(error != NULL) secDebug(ASL_LEVEL_ERR, "Failed to encrypt recovery password\n", NULL);
        CFRelease(group);
    }
    return retval;
}
Exemple #7
0
int main (int argc, const char * argv[]) {
    
	if (argv[1] != NULL)
	{
		CFDataRef data;
		CFStringRef searchterm = CFStringCreateWithCString(NULL, argv[1],
														   kCFStringEncodingMacRoman);
		CFRange searchRange = CFRangeMake(0, CFStringGetLength(searchterm));
		CFStringRef dictResult = DCSCopyTextDefinition(NULL, searchterm, searchRange);
		CFRelease(searchterm);

		if (dictResult != NULL) {
			data = CFStringCreateExternalRepresentation(NULL, dictResult, CFStringGetSystemEncoding(), '?');
			CFRelease(dictResult);

		}
		if (data != NULL) {
			printf ("%.*s\n\n", (int)CFDataGetLength(data), CFDataGetBytePtr(data));
			CFRelease(data);
		}
		else {
			printf("Could not find word in Dictionary.app.\n");
		}

		return 0;
	}
	else {
		printf("Usage: dictlookup \"word\"\n");
		return 1;
	}

}
/*
* Add a CFString to a crypto context handle.
*/
static CSSM_RETURN impExpAddStringAttr(
	CSSM_CC_HANDLE ccHand,
	CFStringRef str,
	CSSM_ATTRIBUTE_TYPE attrType)
{
	/* CFStrings are passed as external rep in UTF8 encoding by convention */
	CFDataRef outData;
	outData = CFStringCreateExternalRepresentation(NULL,
		str, kCFStringEncodingUTF8,	0);		// lossByte 0 ==> no loss allowed
	if(outData == NULL) {
		SecImpExpDbg("impExpAddStringAttr: bad string format");
		return errSecParam;
	}

	CSSM_DATA attrData;
	attrData.Data = (uint8 *)CFDataGetBytePtr(outData);
	attrData.Length = CFDataGetLength(outData);
	CSSM_RETURN crtn = impExpAddContextAttribute(ccHand, attrType, sizeof(CSSM_DATA),
		&attrData);
	CFRelease(outData);
	if(crtn) {
		SecImpExpDbg("impExpAddStringAttr: CSSM_UpdateContextAttributes error");
	}
	return crtn;
}
inline SQLite3StatementRef _SQLite3StatementCreate(CFAllocatorRef allocator, SQLite3ConnectionRef connection, CFStringRef sql, CFErrorRef *error) {
  SQLite3StatementRef statement = NULL;
  if (connection && sql) {
    statement = CFAllocatorAllocate(allocator, sizeof(__SQLite3Statement), 0);
    if (statement) {
      statement->connection = SQLite3ConnectionRetain(connection);   // Let's retain connection
      statement->allocator = allocator ? CFRetain(allocator) : NULL; // ...and allocator if not null
      statement->retainCount = 1;
      statement->stmt = NULL;
      CFDataRef sqlData = CFStringCreateExternalRepresentation(statement->allocator, sql, kCFStringEncodingUTF8, 0);
      if (sqlData) {
        SQLite3Status status = sqlite3_prepare_v2(connection->db, (const char *)CFDataGetBytePtr(sqlData), -1, &statement->stmt, NULL);
        if (kSQLite3StatusOK != status) {
          if (error) {
            *error = CFErrorCreate(allocator, CFSTR("com.github.mirek.SQLite3"), status, NULL);
          }
          printf("ERROR: %s\n", sqlite3_errmsg(connection->db));
          statement = SQLite3StatementRelease(statement); // ...will be set to NULL
        }
        CFRelease(sqlData);
      }
    }
  }
  return statement;
}
/*! Sets or updates a shared secret.
 *  @param handle a handle to a daemon connection.
 *  @param authorization an authorization for the right kiSCSIAuthModifyRights.
 *  @param nodeIQN the node iSCSI qualified name.
 *  @param sharedSecret the secret to set.
 *  @return an error code indicating whether the operating was successful. */
errno_t iSCSIDaemonSetSharedSecret(iSCSIDaemonHandle handle,
                                   AuthorizationRef authorization,
                                   CFStringRef nodeIQN,
                                   CFStringRef sharedSecret)
{
    // Validate inputs
    if(handle < 0 || !authorization || !nodeIQN || !sharedSecret)
        return EINVAL;
    
    AuthorizationExternalForm authExtForm;
    AuthorizationMakeExternalForm(authorization,&authExtForm);
    
    CFDataRef authData = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault,
                                                     (UInt8*)&authExtForm.bytes,
                                                     kAuthorizationExternalFormLength,
                                                     kCFAllocatorDefault);
    
    CFDataRef nodeIQNData = CFStringCreateExternalRepresentation(kCFAllocatorDefault,nodeIQN,kCFStringEncodingASCII,0);
    CFDataRef sharedSecretData = CFStringCreateExternalRepresentation(kCFAllocatorDefault,sharedSecret,kCFStringEncodingASCII,0);
    
    iSCSIDMsgSetSharedSecretCmd cmd = iSCSIDMsgSetSharedSecretCmdInit;
    cmd.authorizationLength = (UInt32)CFDataGetLength(authData);
    cmd.nodeIQNLength = (UInt32)CFDataGetLength(nodeIQNData);
    cmd.secretLength = (UInt32)CFDataGetLength(sharedSecretData);
    
    errno_t error = iSCSIDaemonSendMsg(handle,(iSCSIDMsgGeneric *)&cmd,
                                       authData,nodeIQNData,sharedSecretData,NULL);
    
    if(nodeIQNData)
        CFRelease(nodeIQNData);
    
    if(sharedSecretData)
        CFRelease(sharedSecretData);

    if(error)
        return error;
    
    iSCSIDMsgSetSharedSecretRsp rsp;
    
    if(recv(handle,&rsp,sizeof(rsp),0) != sizeof(rsp))
        return EIO;
    
    if(rsp.funcCode != kiSCSIDSetSharedSecret)
        return EIO;

    return rsp.errorCode;
}
Exemple #11
0
void stringGettingContentsAsCStringExample(void) {

    CFStringRef str;
    CFDataRef data;
    CFRange rangeToProcess;
    const char *bytes;

    show(CFSTR("------------------C String Manipulations---------------"));

    // Create some test CFString
    // Note that in general the string might contain Unicode characters which cannot
    // be converted to a 8-bit character encoding
    str = CFStringCreateWithCString(NULL, "Hello World", kCFStringEncodingASCII);

    show(CFSTR("Original String : %@"), str);
   
    // First, the fast but unpredictable way to get at the C String contents...
    // This is O(1), meaning it takes constant time.
    // This might return NULL!
    bytes = CFStringGetCStringPtr(str, kCFStringEncodingASCII);
   
    // If that fails, you can try to get the contents by copying it out
    if (bytes == NULL) {
        char localBuffer[10];
        Boolean success;

        // This might also fail, either if you provide a buffer that is too small, 
        // or the string cannot be converted into the specified encoding
        success = CFStringGetCString(str, localBuffer, 10, kCFStringEncodingASCII);
    }
    else
        show(CFSTR("From CStringPtr : %@"), bytes);   
    
    // A pretty simple solution is to use a CFData; this frees you from guessing at the buffer size
    // But it does allocate a CFData...
    data = CFStringCreateExternalRepresentation(NULL, str, kCFStringEncodingASCII, 0);
    if (data) {
        show(CFSTR("External Rep: %@"), data);   
        bytes = (const char *)CFDataGetBytePtr(data);
    }

    // More complicated but efficient solution is to use a fixed size buffer, and put a loop in
    rangeToProcess = CFRangeMake(0, CFStringGetLength(str));

    while (rangeToProcess.length > 0) {
        UInt8 localBuffer[100];
        CFIndex usedBufferLength;
        CFIndex numChars = CFStringGetBytes(str, rangeToProcess, kCFStringEncodingASCII, 0, FALSE, (UInt8 *)localBuffer, 100, &usedBufferLength);

        if (numChars == 0) break;	// Means we failed to convert anything...

        // Otherwise we converted some stuff; process localBuffer containing usedBufferLength bytes
        // Note that the bytes in localBuffer are not NULL terminated
		
        // Update the remaining range to continue looping
        rangeToProcess.location += numChars;
        rangeToProcess.length -= numChars;
    }
}
CFDataRef TLProjectionGeoidCreateDataRepresentation(TLProjectionGeoidRef projGeoid) {
	CFStringRef ellipseValue = TLProjectionGeoidCreateEllipseValue(projGeoid);
	CFStringRef geoidArgs = TLProjectionParametersCreateStringWithKeyAndValue(TLProjectionParametersEllipseNameKey, ellipseValue);
	CFRelease(ellipseValue);
	CFDataRef geoidAsData = CFStringCreateExternalRepresentation(kCFAllocatorDefault, geoidArgs, kCFStringEncodingASCII, 0);
	CFRelease(geoidArgs);
	return geoidAsData;
}
Exemple #13
0
void write_gdb_prep_cmds(AMDeviceRef device, CFURLRef disk_app_url) {
    CFMutableStringRef cmds = CFStringCreateMutableCopy(NULL, 0, GDB_PREP_CMDS);
    CFRange range = { 0, CFStringGetLength(cmds) };

    CFStringRef ds_path = copy_device_support_path(device);
    CFStringFindAndReplace(cmds, CFSTR("{ds_path}"), ds_path, range, 0);
    range.length = CFStringGetLength(cmds);

    if (args) {
        CFStringRef cf_args = CFStringCreateWithCString(NULL, args, kCFStringEncodingASCII);
        CFStringFindAndReplace(cmds, CFSTR("{args}"), cf_args, range, 0);
        CFRelease(cf_args);
    } else {
        CFStringFindAndReplace(cmds, CFSTR(" {args}"), CFSTR(""), range, 0);
    }
    range.length = CFStringGetLength(cmds);

    CFStringRef bundle_identifier = copy_disk_app_identifier(disk_app_url);
    CFURLRef device_app_url = copy_device_app_url(device, bundle_identifier);
    CFStringRef device_app_path = CFURLCopyFileSystemPath(device_app_url, kCFURLPOSIXPathStyle);
    CFStringFindAndReplace(cmds, CFSTR("{device_app}"), device_app_path, range, 0);
    range.length = CFStringGetLength(cmds);

    CFStringRef disk_app_path = CFURLCopyFileSystemPath(disk_app_url, kCFURLPOSIXPathStyle);
    CFStringFindAndReplace(cmds, CFSTR("{disk_app}"), disk_app_path, range, 0);
    range.length = CFStringGetLength(cmds);

    CFURLRef device_container_url = CFURLCreateCopyDeletingLastPathComponent(NULL, device_app_url);
    CFStringRef device_container_path = CFURLCopyFileSystemPath(device_container_url, kCFURLPOSIXPathStyle);
    CFMutableStringRef dcp_noprivate = CFStringCreateMutableCopy(NULL, 0, device_container_path);
    range.length = CFStringGetLength(dcp_noprivate);
    CFStringFindAndReplace(dcp_noprivate, CFSTR("/private/var/"), CFSTR("/var/"), range, 0);
    range.length = CFStringGetLength(cmds);
    CFStringFindAndReplace(cmds, CFSTR("{device_container}"), dcp_noprivate, range, 0);
    range.length = CFStringGetLength(cmds);

    CFURLRef disk_container_url = CFURLCreateCopyDeletingLastPathComponent(NULL, disk_app_url);
    CFStringRef disk_container_path = CFURLCopyFileSystemPath(disk_container_url, kCFURLPOSIXPathStyle);
    CFStringFindAndReplace(cmds, CFSTR("{disk_container}"), disk_container_path, range, 0);

    CFDataRef cmds_data = CFStringCreateExternalRepresentation(NULL, cmds, kCFStringEncodingASCII, 0);
    FILE *out = fopen(PREP_CMDS_PATH, "w");
    fwrite(CFDataGetBytePtr(cmds_data), CFDataGetLength(cmds_data), 1, out);
    fclose(out);

    CFRelease(cmds);
    if (ds_path != NULL) CFRelease(ds_path);
    CFRelease(bundle_identifier);
    CFRelease(device_app_url);
    CFRelease(device_app_path);
    CFRelease(disk_app_path);
    CFRelease(device_container_url);
    CFRelease(device_container_path);
    CFRelease(dcp_noprivate);
    CFRelease(disk_container_url);
    CFRelease(disk_container_path);
    CFRelease(cmds_data);
}
static CFDataRef
__copy_legacy_password(CFTypeRef password)
{
	if (password == NULL) {
		return NULL;
	}

	if (isA_CFData(password)) {
		CFIndex	n;

		n = CFDataGetLength(password);
		if ((n % sizeof(UniChar)) == 0) {
			CFStringEncoding	encoding;
			CFStringRef		str;

#if	__BIG_ENDIAN__
			encoding = (*(CFDataGetBytePtr(password) + 1) == 0x00) ? kCFStringEncodingUTF16LE : kCFStringEncodingUTF16BE;
#else	// __LITTLE_ENDIAN__
			encoding = (*(CFDataGetBytePtr(password)    ) == 0x00) ? kCFStringEncodingUTF16BE : kCFStringEncodingUTF16LE;
#endif
			str = CFStringCreateWithBytes(NULL,
						      (const UInt8 *)CFDataGetBytePtr(password),
						      n,
						      encoding,
						      FALSE);
			password = CFStringCreateExternalRepresentation(NULL,
									str,
									kCFStringEncodingUTF8,
									0);
			CFRelease(str);
		} else {
			password = NULL;
		}
	} else if (isA_CFString(password) && (CFStringGetLength(password) > 0)) {
		// convert password to CFData
		password = CFStringCreateExternalRepresentation(NULL,
								password,
								kCFStringEncodingUTF8,
								0);
	} else {
		password = NULL;
	}

	return password;
}
Exemple #15
0
bool unwrap(const String& cfvalue, sfz::String& value) {
    if (!cfvalue.c_obj()) {
        return false;
    }
    Data encoded(CFStringCreateExternalRepresentation(
            NULL, cfvalue.c_obj(), kCFStringEncodingUTF8, '?'));
    print(value, utf8::decode(encoded.data()));
    return true;
}
Exemple #16
0
TStringIRep* TSICTStringCreateWithStringAndFormat(CFStringRef string, TSITStringFormat format)
{
    CFRetain(string);
    CFDataRef data = CFStringCreateExternalRepresentation(kCFAllocatorDefault, string, kCFStringEncodingUTF8, '?');
    TStringIRep* rep = TSICTStringCreateWithDataOfTypeAndFormat(data, kTSITStringTagString, format);
    CFRelease(data);
    CFRelease(string);
    return rep;
}
CFDataRef WebApiClientMD5DigestCreateWithString(CFStringRef string) {
	CFDataRef result = NULL;
	CFDataRef data = CFStringCreateExternalRepresentation(kCFAllocatorDefault, string, kCFStringEncodingUTF8, 0);
	if ( data ) {
		result = WebApiClientMD5DigestCreateWithData(data);
		CFRelease(data);
	}
	return result;
}
Exemple #18
0
extern CFPropertyListRef INXCreateDictionaryWithString(CFStringRef s) {
	if (s == NULL)
		return NULL;
	CFDataRef data = CFStringCreateExternalRepresentation(NULL, s, kCFStringEncodingUTF8, 0);
	if (data == NULL)
		return NULL;
	CFPropertyListRef retval = CFPropertyListCreateFromXMLData(NULL, data, kCFPropertyListImmutable, NULL);
	CFRelease(data);
	return retval;
}
Exemple #19
0
WebSocketFrameRef
WebSocketFrameCreateWithPayloadString (CFAllocatorRef allocator, Boolean isMasked, UInt8 *maskingKey, CFStringRef payload) {
    WebSocketFrameRef self = NULL;
    CFDataRef data = CFStringCreateExternalRepresentation(allocator, payload, kCFStringEncodingUTF8, 0);
    if (data != NULL) {
        self = WebSocketFrameCreateWithPayloadData(allocator, kWebSocketFrameOpCodeText, isMasked, maskingKey, data);
        CFRelease(data);
    }
    return self;
}
static int TearOffSignatureAndHashManifest(CFDictionaryRef manifestDict, CFDataRef* signature, CFDataRef* manifest_data)
{
	int result = -1;
	CFMutableDictionaryRef new_manifest_dict = NULL;
    CFStringRef sig_data_str = NULL;
	CFDataRef sig_data = NULL;
	CFDataRef prop_list = NULL;
    CFDataRef decoded_sig_data = NULL;
	
	if (NULL == manifestDict || NULL == signature || NULL == manifest_data)
	{
		return result;
	}
	*signature = NULL;
	*manifest_data = NULL;
	
	new_manifest_dict = CFDictionaryCreateMutableCopy(kCFAllocatorDefault, CFDictionaryGetCount(manifestDict), manifestDict);
	sig_data_str = (CFStringRef)CFDictionaryGetValue(new_manifest_dict, CFSTR("Signature"));
	if (NULL == sig_data_str)
	{
		CFRelease(new_manifest_dict);
		return result; 
	}
    
    sig_data = CFStringCreateExternalRepresentation(kCFAllocatorDefault, sig_data_str, kCFStringEncodingUTF8, 0);
    if (NULL == sig_data)
    {
        CFRelease(sig_data_str);
        CFRelease(new_manifest_dict);
		return result;
    }
    
    if (Base64Data(sig_data, 0, &decoded_sig_data))
    {
        CFRelease(sig_data);
        CFRelease(new_manifest_dict);
		return result;
    }
        
	*signature = decoded_sig_data;
	
	CFDictionaryRemoveValue(new_manifest_dict, CFSTR("Signature"));
	prop_list = CFPropertyListCreateXMLData (kCFAllocatorDefault, new_manifest_dict);
	CFRelease(new_manifest_dict);
	if (NULL == prop_list)
	{
		return result; 
	}
    
    (void)CreateHashForData(prop_list, 1, manifest_data);
	
    result = (NULL == *manifest_data) ? -1 : 0;
	return result;	
}
inline CFIndex SQLite3StatementGetBindParameterIndexWithName(SQLite3StatementRef statement, CFStringRef name) {
  int index = 0;
  if (name) {
    CFDataRef nameData = CFStringCreateExternalRepresentation(statement->allocator, name, kCFStringEncodingUTF8, 0);
    if (nameData) {
      index = sqlite3_bind_parameter_index(statement->stmt, (const char *)CFDataGetBytePtr(nameData));
      CFRelease(nameData);
    }
  }
  return index;
}
Exemple #22
0
static VALUE cfstring2rbstr(CFStringRef str) {
    const char *result;
    VALUE rb_result = Qnil;
    CFDataRef data = CFStringCreateExternalRepresentation(kCFAllocatorDefault, str, kCFStringEncodingUTF8, 0);
    if (data) {
        result = (const char *)CFDataGetBytePtr(data);
        rb_result = rb_str_new2(result);
    }
    RELEASE_IF_NOT_NULL(data)
    return rb_result;
}
__private_extern__
void CFPlatformLog(const char* prefix, CFLogLevel level, CFStringRef message) {
    CFDataRef chars = CFStringCreateExternalRepresentation(
        kCFAllocatorDefault,
        message,
        CFStringGetSystemEncoding(),
        '?');
    printf("[%s / %s] %.*s\n",
		prefix, CFLogFormatLevel(level),
        (int)CFDataGetLength(chars), CFDataGetBytePtr(chars));
    CFRelease(chars);
}
Exemple #24
0
void
__NCPrint(
  FILE*       stream,
  CFStringRef format,
  va_list     argv,
  Boolean     addNewline
)
{
  CFDataRef     externalRep;
  CFStringRef   string;
  CFRange       range = CFStringFind(format,CFSTR("%!"),0);
  
  //  Look for ANSI formatting directives:
  if (range.location != kCFNotFound) {
    format = __NCParseExtendedFormatString(format);
    string = CFStringCreateWithFormatAndArguments(
                kCFAllocatorDefault,
                NULL,
                format,
                argv);
    CFRelease(format);
  } else {
    string = CFStringCreateWithFormatAndArguments(
                kCFAllocatorDefault,
                NULL,
                format,
                argv);
  }
  
  if (string) {
    externalRep = CFStringCreateExternalRepresentation(
                  kCFAllocatorDefault,
                  string,
                  CFCStringGetDefaultEncoding(),
                  '?');
    CFRelease(string);
    if (externalRep) {
      if ( addNewline )
        fprintf(stream,"%.*s\n",
            (int)CFDataGetLength(externalRep),
            (char*)CFDataGetBytePtr(externalRep)
          );
      else
        fprintf(stream,"%.*s",
            (int)CFDataGetLength(externalRep),
            (char*)CFDataGetBytePtr(externalRep)
          );
      CFRelease(externalRep);
      fflush(stream);
    }
  }  
}
inline SQLite3Status SQLite3StatementBindString(SQLite3StatementRef statement, CFIndex index, CFStringRef value) {
  SQLite3Status status = kSQLite3StatusError;
  if (value) {
    CFDataRef valueData = CFStringCreateExternalRepresentation(statement->allocator, value, kCFStringEncodingUTF8, 0);
    if (valueData) {
      status = sqlite3_bind_text(statement->stmt, (int)index, (const char *)CFDataGetBytePtr(valueData), -1, SQLITE_TRANSIENT);
      CFRelease(valueData);
    }
  } else {
    status = SQLite3StatementBindNULL(statement, index);
  }
  return status;
}
Exemple #26
0
static void OnData(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
    switch (type) {
        case kCFSocketDataCallBack:
            CFDataRef data(reinterpret_cast<CFDataRef>(value));
            Client *client(reinterpret_cast<Client *>(info));

            if (client->message_ == NULL)
                client->message_ = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, TRUE);

            if (!CFHTTPMessageAppendBytes(client->message_, CFDataGetBytePtr(data), CFDataGetLength(data)))
                CFLog(kCFLogLevelError, CFSTR("CFHTTPMessageAppendBytes()"));
            else if (CFHTTPMessageIsHeaderComplete(client->message_)) {
                CFURLRef url(CFHTTPMessageCopyRequestURL(client->message_));
                Boolean absolute;
                CFStringRef path(CFURLCopyStrictPath(url, &absolute));
                CFRelease(client->message_);

                CFStringRef code(CFURLCreateStringByReplacingPercentEscapes(kCFAllocatorDefault, path, CFSTR("")));
                CFRelease(path);

                JSStringRef script(JSStringCreateWithCFString(code));
                CFRelease(code);

                JSValueRef result(JSEvaluateScript(CYGetJSContext(), script, NULL, NULL, 0, NULL));
                JSStringRelease(script);

                CFHTTPMessageRef response(CFHTTPMessageCreateResponse(kCFAllocatorDefault, 200, NULL, kCFHTTPVersion1_1));
                CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Type"), CFSTR("application/json; charset=utf-8"));

                CFStringRef json(CYCopyJSONString(CYGetJSContext(), result, NULL));
                CFDataRef body(CFStringCreateExternalRepresentation(kCFAllocatorDefault, json, kCFStringEncodingUTF8, NULL));
                CFRelease(json);

                CFStringRef length(CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%u"), CFDataGetLength(body)));
                CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Length"), length);
                CFRelease(length);

                CFHTTPMessageSetBody(response, body);
                CFRelease(body);

                CFDataRef serialized(CFHTTPMessageCopySerializedMessage(response));
                CFRelease(response);

                CFSocketSendData(socket, NULL, serialized, 0);
                CFRelease(serialized);

                CFRelease(url);
            }
        break;
    }
}
/*
 * Given a CFTypeRef passphrase which may be a CFDataRef or a CFStringRef,
 * return a refcounted CFDataRef whose bytes are suitable for use with
 * PKCS5 (v1.5 and v2.0) key derivation.
 */
OSStatus impExpPassphraseToCFData(
	CFTypeRef   passin,
	CFDataRef   *passout)	// may be the same as passin, but refcounted
{
	if(CFGetTypeID(passin) == CFDataGetTypeID()) {
		CFDataRef passInData = (CFDataRef)passin;
		CFRetain(passInData);
		*passout = passInData;
		return errSecSuccess;
	}
	else if(CFGetTypeID(passin) == CFStringGetTypeID()) {
		CFStringRef passInStr = (CFStringRef)passin;
		CFDataRef outData;
		outData = CFStringCreateExternalRepresentation(NULL,
			passInStr,
			kCFStringEncodingUTF8,
			0);		// lossByte 0 ==> no loss allowed
		if(outData == NULL) {
			/* Well try with lossy conversion */
			SecImpExpDbg("Trying lossy conversion of CFString passphrase to UTF8");
			outData = CFStringCreateExternalRepresentation(NULL,
				passInStr,
				kCFStringEncodingUTF8,
				1);
			if(outData == NULL) {
				SecImpExpDbg("Failure on conversion of CFString passphrase to UTF8");
				/* what do we do now, Batman? */
				return errSecParam;
			}
		}
		*passout = outData;
		return errSecSuccess;
	}
	else {
		SecImpExpDbg("Passphrase not CFData or CFString");
		return errSecParam;
	}
}
static int GetPublicManifestKey(CCRSACryptorRef* key_ref)
{
	int result = -1;
	
	CFStringRef encoded_key_data_str = NULL;
	CFDataRef encoded_key_data_str_data = NULL;
	CFDataRef decoded_key_data = NULL;
	CCCryptorStatus ccStatus = kCCSuccess;
	
	if (NULL == key_ref)
	{
		return result;
	}
	*key_ref = NULL;
		
	encoded_key_data_str = CFStringCreateWithCString(kCFAllocatorDefault, kPublicManifestKeyData, kCFStringEncodingUTF8);
	if (NULL == encoded_key_data_str)
	{
		return result;
	}
	
	encoded_key_data_str_data = CFStringCreateExternalRepresentation(kCFAllocatorDefault, encoded_key_data_str, kCFStringEncodingUTF8, 0);
	if (NULL == encoded_key_data_str_data)
	{
		CFRelease(encoded_key_data_str);
		return result;
	}
	CFRelease(encoded_key_data_str);
	
	if (Base64Data(encoded_key_data_str_data, 0, &decoded_key_data))
    {
		CFRelease(encoded_key_data_str_data);
        return result;
    }
	CFRelease(encoded_key_data_str_data);
	
	ccStatus = CCRSACryptorImport(CFDataGetBytePtr(decoded_key_data), CFDataGetLength(decoded_key_data), key_ref);
	CFRelease(decoded_key_data);
	
	if (kCCSuccess != ccStatus)
	{
		*key_ref = NULL;
	}
	else
	{
		result = 0;
	}
	return result;	
}
Exemple #29
0
void simpleStringExample(void) {

    CFStringRef str;
    CFDataRef data;
    char *bytes;

    show(CFSTR("------------------Simple Strings---------------"));

    // Create a simple immutable string from a Pascal string and convert it to Unicode
#if defined(__APPLE__)
    str = CFStringCreateWithPascalString(NULL, "\pFoo Bar", kCFStringEncodingASCII);
#else
    str = CFStringCreateWithCString(NULL, "Hello World", kCFStringEncodingASCII);
#endif

    // Create the Unicode representation of the string
    // "0", lossByte, indicates that if there's a conversion error, fail (and return NULL)
    data = CFStringCreateExternalRepresentation(NULL, str, kCFStringEncodingUnicode, 0);

    show(CFSTR("String          : %@"), str);
    show(CFSTR("Unicode data    : %@"), data);

    CFRelease(str);
 
    // Create a string from the Unicode data...
    str = CFStringCreateFromExternalRepresentation(NULL, data, kCFStringEncodingUnicode);

    show(CFSTR("String Out      : %@"), str);

    CFRelease(str);

    // Create a string for which you already have some allocated contents which you want to 
    // pass ownership of to the CFString. The last argument, "NULL," indicates that the default allocator
    // should be used to free the contents when the CFString is freed (or you can pass in CFAllocatorGetDefault()).

    bytes = (char*)CFAllocatorAllocate(CFAllocatorGetDefault(), 6, 0);
    strcpy(bytes, "Hello");

    str = CFStringCreateWithCStringNoCopy(NULL, bytes, kCFStringEncodingASCII, NULL);
    CFRelease(str);

#if defined(__APPLE__)
    // Now create a string with a Pascal string which is not copied, and not freed when the string is
    // This is an advanced usage; obviously you need to guarantee that the string bytes do not go away
    // before the CFString does. 
    str = CFStringCreateWithPascalStringNoCopy(NULL, "\pFoo Bar", kCFStringEncodingASCII, kCFAllocatorNull);
    CFRelease(str);
#endif
}
/* print the contents of a CFString */
void printCfStr(
	CFStringRef cfstr)
{
	CFDataRef strData = CFStringCreateExternalRepresentation(NULL, cfstr,
		kCFStringEncodingUTF8, true);
	if(strData == NULL) {
		printf("<<string decode error>>");
		return;
	}
	const char *cp = (const char *)CFDataGetBytePtr(strData);
	CFIndex len = CFDataGetLength(strData);
	for(CFIndex dex=0; dex<len; dex++) {
		putchar(*cp++);
	}
	CFRelease(strData);
}