static CFStringRef decryptString(SecKeyRef wrapKey, CFDataRef iv, CFDataRef wrappedPassword) { CFStringRef retval = NULL; CFDataRef retData = NULL; CFErrorRef error = NULL; SecTransformRef decryptTrans = SecDecryptTransformCreate(wrapKey, &error); if(error == NULL) { SecTransformRef group = SecTransformCreateGroupTransform(); SecTransformRef decodeTrans = SecDecodeTransformCreate(kSecBase64Encoding, &error); if(error == NULL) SecTransformSetAttribute(decodeTrans, kSecTransformInputAttributeName, wrappedPassword, &error); if(error == NULL) SecTransformSetAttribute(decryptTrans, kSecEncryptionMode, kSecModeCBCKey, &error); if(error == NULL) SecTransformSetAttribute(decryptTrans, kSecPaddingKey, kSecPaddingPKCS7Key, &error); if(error == NULL) SecTransformSetAttribute(decryptTrans, kSecIVKey, iv, &error); SecTransformConnectTransforms(decodeTrans, kSecTransformOutputAttributeName, decryptTrans, kSecTransformInputAttributeName, group, &error); CFRelease(decodeTrans); CFRelease(decryptTrans); if(error == NULL) retData = SecTransformExecute(group, &error); if(error == NULL) retval = CFStringCreateFromExternalRepresentation(kCFAllocatorDefault, retData, kCFStringEncodingMacRoman); else secDebug(ASL_LEVEL_ERR, "Failed to decrypt recovery password\n", NULL); CFRelease(group); } return retval; }
static inline CFStringRef TSICTStringCreateStringFromIntermediateRepresentation(TStringIRep* rep) { CFDataRef data = TSICTStringCreateDataFromIntermediateRepresentation(rep); CFStringRef string = CFStringCreateFromExternalRepresentation(kCFAllocatorDefault, data, kCFStringEncodingUTF8); CFRelease(data); return string; }
static void __DAFileSystemProbeCallbackStage2( int status, CFDataRef output, void * parameter ) { /* * Process the "get UUID" command's completion. */ __DAFileSystemProbeContext * context = parameter; if ( status == FSUR_IO_SUCCESS ) { /* * Obtain the volume UUID. The "get UUID" command returns a unique 64-bit number, which * we must map into the official, structured 128-bit UUID format. One would expect that * the "get UUID" interface return the official UUID format, when it is revised later on, * and we take that into account here. */ if ( output ) { CFStringRef string; string = CFStringCreateFromExternalRepresentation( kCFAllocatorDefault, output, kCFStringEncodingUTF8 ); if ( string ) { context->volumeUUID = ___CFUUIDCreateFromString( kCFAllocatorDefault, string ); CFRelease( string ); } } } if ( context->repairCommand ) { /* * Execute the "is clean" command. */ DACommandExecute( context->repairCommand, kDACommandExecuteOptionDefault, ___UID_ROOT, ___GID_WHEEL, __DAFileSystemProbeCallbackStage3, context, CFSTR( "-q" ), context->devicePath, NULL ); } else { /* * Skip the "is clean" command, as it is not applicable. */ __DAFileSystemProbeCallbackStage3( 0, NULL, context ); } }
static void __DAFileSystemProbeCallbackStage1( int status, CFDataRef output, void * parameter ) { /* * Process the probe command's completion. */ __DAFileSystemProbeContext * context = parameter; if ( status == FSUR_RECOGNIZED ) { /* * Obtain the volume name. */ if ( output ) { CFStringRef string; string = CFStringCreateFromExternalRepresentation( kCFAllocatorDefault, output, kCFStringEncodingUTF8 ); if ( string ) { if ( CFStringGetLength( string ) ) { context->volumeName = CFStringCreateMutableCopy( kCFAllocatorDefault, 0, string ); if ( context->volumeName ) { CFStringTrim( ( CFMutableStringRef ) context->volumeName, CFSTR( "\n" ) ); } } CFRelease( string ); } } /* * Execute the "get UUID" command. */ DACommandExecute( context->probeCommand, kDACommandExecuteOptionCaptureOutput, ___UID_ROOT, ___GID_WHEEL, __DAFileSystemProbeCallbackStage2, context, CFSTR( "-k" ), context->deviceName, NULL ); } else { __DAFileSystemProbeCallback( status, context, NULL ); } }
CRESTRequestRef CRESTRequestCreateWithBytes(UInt8 const *bytes, ssize_t len) { CFURLRef url; CRESTRequestRef request; CFHTTPMessageRef message; message = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, true); request = calloc(1, sizeof(struct CRESTRequest)); assert(request); bool isAppended = CFHTTPMessageAppendBytes(message, bytes, (CFIndex) len); bool isComplete = CFHTTPMessageIsHeaderComplete(message); if( ! ( isAppended && isComplete ) ) { CFRelease(message); CRESTRequestDealloc(request); return NULL; } url = CFHTTPMessageCopyRequestURL(message); CFMutableDictionaryRef params = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFStringRef query = CFURLCopyQueryString(url, NULL); if( query ) { parseParams(params, query); CFRelease(query); } CFDataRef bodyData = CFHTTPMessageCopyBody(message); if( CFDataGetLength(bodyData) ) { CFStringRef bodyString = CFStringCreateFromExternalRepresentation(kCFAllocatorDefault, bodyData, kCFStringEncodingUTF8); parseParams(params, bodyString); CFRelease(bodyString); } CFRelease(bodyData); request->method = CFHTTPMessageCopyRequestMethod(message); request->path = CFURLCopyPath(url); request->params = (CFDictionaryRef) params; CFRelease(url); CFRelease(message); return request; }
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 }
/* * Opens a configuration file and returns a CFArrayRef consisting * of a CFStringRef for each line. */ CFArrayRef configRead(const char *path) { int fd; struct stat statBuf; CFMutableDataRef data; CFStringRef str; CFArrayRef config = NULL; fd = open(path, O_RDONLY, 0644); if (fd < 0) { goto done; } if (fstat(fd, &statBuf) < 0) { goto done; } if ((statBuf.st_mode & S_IFMT) != S_IFREG) { goto done; } data = CFDataCreateMutable(NULL, statBuf.st_size); CFDataSetLength(data, statBuf.st_size); if(read(fd, (void *)CFDataGetMutableBytePtr(data), statBuf.st_size) != statBuf.st_size) { CFRelease(data); goto done; } str = CFStringCreateFromExternalRepresentation(NULL, data, kCFStringEncodingMacRoman); CFRelease(data); config = CFStringCreateArrayBySeparatingStrings(NULL, str, CFSTR("\n")); CFRelease(str); done: if (fd >= 0) { close(fd); } if (config == NULL) { CFMutableArrayRef emptyConfig; /* pretend that we found an empty file */ emptyConfig = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); CFArrayAppendValue(emptyConfig, CFSTR("")); config = (CFArrayRef)emptyConfig; } return config; }
static void convertWebResourceDataToString(CFMutableDictionaryRef resource) { CFMutableStringRef mimeType = (CFMutableStringRef)CFDictionaryGetValue(resource, CFSTR("WebResourceMIMEType")); CFStringLowercase(mimeType, CFLocaleGetSystem()); convertMIMEType(mimeType); CFArrayRef supportedMIMETypes = supportedNonImageMIMETypes(); if (CFStringHasPrefix(mimeType, CFSTR("text/")) || CFArrayContainsValue(supportedMIMETypes, CFRangeMake(0, CFArrayGetCount(supportedMIMETypes)), mimeType)) { CFStringRef textEncodingName = static_cast<CFStringRef>(CFDictionaryGetValue(resource, CFSTR("WebResourceTextEncodingName"))); CFStringEncoding stringEncoding; if (textEncodingName && CFStringGetLength(textEncodingName)) stringEncoding = CFStringConvertIANACharSetNameToEncoding(textEncodingName); else stringEncoding = kCFStringEncodingUTF8; CFDataRef data = static_cast<CFDataRef>(CFDictionaryGetValue(resource, CFSTR("WebResourceData"))); RetainPtr<CFStringRef> dataAsString = adoptCF(CFStringCreateFromExternalRepresentation(kCFAllocatorDefault, data, stringEncoding)); if (dataAsString) CFDictionarySetValue(resource, CFSTR("WebResourceData"), dataAsString.get()); } }
CFStringRef SecCreateRecoveryPassword(void) { CFStringRef result = NULL; CFErrorRef error = NULL; CFDataRef encodedData = NULL; CFDataRef randData = getRandomBytes(16); int i; // base32FDE is a "private" base32 encoding, it has no 0/O or L/l/1 in it (it uses 8 and 9). SecTransformRef encodeTrans = SecEncodeTransformCreate(CFSTR("base32FDE"), &error); if(error == NULL) { SecTransformSetAttribute(encodeTrans, kSecTransformInputAttributeName, randData, &error); if(error == NULL) encodedData = SecTransformExecute(encodeTrans, &error); CFRelease(encodeTrans); } CFRelease(randData); if(encodedData != NULL && error == NULL) { CFStringRef b32string = CFStringCreateFromExternalRepresentation(kCFAllocatorDefault, encodedData, kCFStringEncodingMacRoman); CFMutableStringRef encodedString = CFStringCreateMutableCopy(kCFAllocatorDefault, 64, b32string); // Add some hyphens to make the generated password easier to use for(i = 4; i < 34; i += 5) CFStringInsert(encodedString, i, CFSTR("-")); // Trim so the last section is 4 characters long CFStringDelete(encodedString, CFRangeMake(29,CFStringGetLength(encodedString)-29)); result = CFStringCreateCopy(kCFAllocatorDefault, encodedString); CFRelease(encodedString); CFRelease(b32string); CFRelease(encodedData); } else { secDebug(ASL_LEVEL_ERR, "Failed to base32 encode random data for recovery password\n", NULL); } return result; }
CFDataRef SecOTRSessionCreateRemote_internal(CFDataRef publicAccountData, CFDataRef publicPeerId, CFDataRef privateAccountData, CFErrorRef *error) { SOSDataSourceFactoryRef ds = SecItemDataSourceFactoryGetDefault(); SOSAccountRef privateAccount = NULL; SOSAccountRef publicAccount = NULL; CFStringRef publicKeyString = NULL; SecKeyRef privateKeyRef = NULL; SecKeyRef publicKeyRef = NULL; SecOTRFullIdentityRef privateIdentity = NULL; SecOTRPublicIdentityRef publicIdentity = NULL; CFDataRef result = NULL; SecOTRSessionRef ourSession = NULL; require_quiet(ds, fail); require_quiet(publicPeerId, fail); privateAccount = (privateAccountData == NULL) ? CFRetainSafe(SOSKeychainAccountGetSharedAccount()) : SOSAccountCreateFromData(kCFAllocatorDefault, privateAccountData, ds, error); require_quiet(privateAccount, fail); privateKeyRef = SOSAccountCopyDeviceKey(privateAccount, error); require_quiet(privateKeyRef, fail); CFReleaseNull(privateAccount); privateIdentity = SecOTRFullIdentityCreateFromSecKeyRef(kCFAllocatorDefault, privateKeyRef, error); require_quiet(privateIdentity, fail); CFReleaseNull(privateKeyRef); publicKeyString = CFStringCreateFromExternalRepresentation(kCFAllocatorDefault, publicPeerId, kCFStringEncodingUTF8); require_quiet(publicKeyString, fail); publicAccount = (publicAccountData == NULL) ? CFRetainSafe(SOSKeychainAccountGetSharedAccount()) : SOSAccountCreateFromData(kCFAllocatorDefault, publicAccountData, ds, error); require_quiet(publicAccount, fail); publicKeyRef = SOSAccountCopyPublicKeyForPeer(publicAccount, publicKeyString, error); require_quiet(publicKeyRef, fail); CFReleaseNull(publicAccount); publicIdentity = SecOTRPublicIdentityCreateFromSecKeyRef(kCFAllocatorDefault, publicKeyRef, error); require_quiet(publicIdentity, fail); CFReleaseNull(publicKeyRef); ourSession = SecOTRSessionCreateFromID(kCFAllocatorDefault, privateIdentity, publicIdentity); CFMutableDataRef exportSession = CFDataCreateMutable(kCFAllocatorDefault, 0); SecOTRSAppendSerialization(ourSession, exportSession); result = exportSession; exportSession = NULL; fail: CFReleaseNull(ourSession); CFReleaseNull(publicKeyString); CFReleaseNull(privateAccount); CFReleaseNull(publicAccount); CFReleaseNull(privateKeyRef); CFReleaseNull(publicKeyRef); CFReleaseNull(publicIdentity); CFReleaseNull(privateIdentity); return result; }
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; }
QList<QNetworkProxy> macQueryInternal(const QNetworkProxyQuery &query) { QList<QNetworkProxy> result; // obtain a dictionary to the proxy settings: CFDictionaryRef dict = SCDynamicStoreCopyProxies(NULL); if (!dict) { qWarning("QNetworkProxyFactory::systemProxyForQuery: SCDynamicStoreCopyProxies returned NULL"); return result; // failed } if (isHostExcluded(dict, query.peerHostName())) { CFRelease(dict); return result; // no proxy for this host } // is there a PAC enabled? If so, use it first. CFNumberRef pacEnabled; if ((pacEnabled = (CFNumberRef)CFDictionaryGetValue(dict, kSCPropNetProxiesProxyAutoConfigEnable))) { int enabled; if (CFNumberGetValue(pacEnabled, kCFNumberIntType, &enabled) && enabled) { // PAC is enabled CFStringRef cfPacLocation = (CFStringRef)CFDictionaryGetValue(dict, kSCPropNetProxiesProxyAutoConfigURLString); #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5) if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5) { QCFType<CFDataRef> pacData; QCFType<CFURLRef> pacUrl = CFURLCreateWithString(kCFAllocatorDefault, cfPacLocation, NULL); SInt32 errorCode; if (!CFURLCreateDataAndPropertiesFromResource(kCFAllocatorDefault, pacUrl, &pacData, NULL, NULL, &errorCode)) { QString pacLocation = QCFString::toQString(cfPacLocation); qWarning("Unable to get the PAC script at \"%s\" (%s)", qPrintable(pacLocation), cfurlErrorDescription(errorCode)); return result; } QCFType<CFStringRef> pacScript = CFStringCreateFromExternalRepresentation(kCFAllocatorDefault, pacData, kCFStringEncodingISOLatin1); if (!pacScript) { // This should never happen, but the documentation says it may return NULL if there was a problem creating the object. QString pacLocation = QCFString::toQString(cfPacLocation); qWarning("Unable to read the PAC script at \"%s\"", qPrintable(pacLocation)); return result; } QByteArray encodedURL = query.url().toEncoded(); // converted to UTF-8 if (encodedURL.isEmpty()) { return result; // Invalid URL, abort } QCFType<CFURLRef> targetURL = CFURLCreateWithBytes(kCFAllocatorDefault, (UInt8*)encodedURL.data(), encodedURL.size(), kCFStringEncodingUTF8, NULL); if (!targetURL) { return result; // URL creation problem, abort } QCFType<CFErrorRef> pacError; QCFType<CFArrayRef> proxies = CFNetworkCopyProxiesForAutoConfigurationScript(pacScript, targetURL, &pacError); if (!proxies) { QString pacLocation = QCFString::toQString(cfPacLocation); QCFType<CFStringRef> pacErrorDescription = CFErrorCopyDescription(pacError); qWarning("Execution of PAC script at \"%s\" failed: %s", qPrintable(pacLocation), qPrintable(QCFString::toQString(pacErrorDescription))); return result; } CFIndex size = CFArrayGetCount(proxies); for (CFIndex i = 0; i < size; ++i) { CFDictionaryRef proxy = (CFDictionaryRef)CFArrayGetValueAtIndex(proxies, i); result << proxyFromDictionary(proxy); } return result; } else #endif { QString pacLocation = QCFString::toQString(cfPacLocation); qWarning("Mac system proxy: PAC script at \"%s\" not handled", qPrintable(pacLocation)); } } } // no PAC, decide which proxy we're looking for based on the query bool isHttps = false; QString protocol = query.protocolTag().toLower(); // try the protocol-specific proxy QNetworkProxy protocolSpecificProxy; if (protocol == QLatin1String("ftp")) { protocolSpecificProxy = proxyFromDictionary(dict, QNetworkProxy::FtpCachingProxy, kSCPropNetProxiesFTPEnable, kSCPropNetProxiesFTPProxy, kSCPropNetProxiesFTPPort); } else if (protocol == QLatin1String("http")) { protocolSpecificProxy = proxyFromDictionary(dict, QNetworkProxy::HttpProxy, kSCPropNetProxiesHTTPEnable, kSCPropNetProxiesHTTPProxy, kSCPropNetProxiesHTTPPort); } else if (protocol == QLatin1String("https")) { isHttps = true; protocolSpecificProxy = proxyFromDictionary(dict, QNetworkProxy::HttpProxy, kSCPropNetProxiesHTTPSEnable, kSCPropNetProxiesHTTPSProxy, kSCPropNetProxiesHTTPSPort); } if (protocolSpecificProxy.type() != QNetworkProxy::DefaultProxy) result << protocolSpecificProxy; // let's add SOCKSv5 if present too QNetworkProxy socks5 = proxyFromDictionary(dict, QNetworkProxy::Socks5Proxy, kSCPropNetProxiesSOCKSEnable, kSCPropNetProxiesSOCKSProxy, kSCPropNetProxiesSOCKSPort); if (socks5.type() != QNetworkProxy::DefaultProxy) result << socks5; // let's add the HTTPS proxy if present (and if we haven't added // yet) if (!isHttps) { QNetworkProxy https = proxyFromDictionary(dict, QNetworkProxy::HttpProxy, kSCPropNetProxiesHTTPSEnable, kSCPropNetProxiesHTTPSProxy, kSCPropNetProxiesHTTPSPort); if (https.type() != QNetworkProxy::DefaultProxy && https != protocolSpecificProxy) result << https; } CFRelease(dict); return result; }
void propertyListExample(void) { CFMutableDictionaryRef dict; CFNumberRef num; CFArrayRef array; CFDataRef data; #define NumKids 2 CFStringRef kidsNames[] = {CFSTR("John"), CFSTR("Kyra")}; #define NumPets 0 int yearOfBirth = 1965; #define NumBytesInPic 10 const unsigned char pic[NumBytesInPic] = {0x3c, 0x42, 0x81, 0xa5, 0x81, 0xa5, 0x99, 0x81, 0x42, 0x3c}; CFDataRef xmlPropertyListData; CFStringRef xmlAsString; // Create and populate a pretty standard mutable dictionary: CFString keys, CF type values. // To be written out as a "propertyList", the tree of CF types can contain only: // CFDictionary, CFArray, CFString, CFData, CFNumber, and CFDate. // In addition, the keys of the dictionaries should be CFStrings. dict = CFDictionaryCreateMutable(NULL, 0, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFDictionarySetValue(dict, CFSTR("Name"), CFSTR("John Doe")); CFDictionarySetValue(dict, CFSTR("City of Birth"), CFSTR("Springfield")); num = CFNumberCreate(NULL, kCFNumberIntType, &yearOfBirth); CFDictionarySetValue(dict, CFSTR("Year Of Birth"), num); CFRelease(num); array = CFArrayCreate(NULL, (const void **)kidsNames, 2, &kCFTypeArrayCallBacks); CFDictionarySetValue(dict, CFSTR("Kids Names"), array); CFRelease(array); array = CFArrayCreate(NULL, NULL, 0, &kCFTypeArrayCallBacks); CFDictionarySetValue(dict, CFSTR("Pets Names"), array); CFRelease(array); data = CFDataCreate(NULL, pic, NumBytesInPic); CFDictionarySetValue(dict, CFSTR("Picture"), data); CFRelease(data); // We now have a dictionary which contains everything we want to know about // John Doe; let's show it first: show(CFSTR("John Doe info dictionary: %@"), dict); // Now create a "property list", which is a flattened, XML version of the // dictionary: xmlPropertyListData = CFPropertyListCreateXMLData(NULL, dict); // The return value is a CFData containing the XML file; show the data show(CFSTR("Shown as XML property list (bytes): %@"), xmlPropertyListData); // Given CFDatas are shown as ASCII versions of their hex contents, we can also // attempt to show the contents of the XML, assuming it was encoded in UTF8 // (This is the case for XML property lists generated by CoreFoundation currently) xmlAsString = CFStringCreateFromExternalRepresentation(NULL, xmlPropertyListData, kCFStringEncodingUTF8); show(CFSTR("The XML property list contents: %@"), xmlAsString); CFRelease(dict); CFRelease(xmlAsString); CFRelease(xmlPropertyListData); }
/** * Get proxy information from a proxy script. * @param dict : Dictionary to search through. * @param targetURLString : Target remote URL * @param logger : Log object * @return Collection of proxy information. */ ProxyInfoVec proxyInformationFromPac(CFDictionaryRef dict, const std::string &targetURLString, Logger &logger) { ProxyInfoVec proxyInfoVec; // is there a PAC enabled? If so, use it first. CFNumberRef pacEnabled; if ((pacEnabled = reinterpret_cast<CFNumberRef>(CFDictionaryGetValue( dict, kSCPropNetProxiesProxyAutoConfigEnable)))) { int enabled; if (CFNumberGetValue(pacEnabled, kCFNumberIntType, &enabled) && enabled) { // PAC is enabled CFStringRef cfPacLocation = reinterpret_cast<CFStringRef>(CFDictionaryGetValue( dict, kSCPropNetProxiesProxyAutoConfigURLString)); CFDataRef pacData; CFURLRef pacURL = CFURLCreateWithString(kCFAllocatorDefault, cfPacLocation, nullptr); SInt32 errorCode; if (!CFURLCreateDataAndPropertiesFromResource(kCFAllocatorDefault, pacURL, &pacData, nullptr, nullptr, &errorCode)) { logger.debug() << "Unable to get the PAC script at " << toString(cfPacLocation) << "Error code: " << errorCode << std::endl; return proxyInfoVec; } CFStringRef pacScript = CFStringCreateFromExternalRepresentation( kCFAllocatorDefault, pacData, kCFStringEncodingISOLatin1); CFURLRef targetURL = CFURLCreateWithBytes( kCFAllocatorDefault, (UInt8 *)targetURLString.c_str(), targetURLString.size(), kCFStringEncodingUTF8, nullptr); if (!targetURL) { logger.debug("Problem with Target URI for proxy script"); return proxyInfoVec; } CFErrorRef pacError; CFArrayRef proxies = CFNetworkCopyProxiesForAutoConfigurationScript( pacScript, targetURL, &pacError); if (!proxies) { std::string pacLocation = toString(cfPacLocation); CFStringRef pacErrorDescription = CFErrorCopyDescription(pacError); logger.debug() << "Execution of PAC script at \"%s\" failed: %s" << pacLocation << toString(pacErrorDescription) << std::endl; } CFIndex size = CFArrayGetCount(proxies); for (CFIndex i = 0; i < size; ++i) { CFDictionaryRef proxy = reinterpret_cast<CFDictionaryRef>( CFArrayGetValueAtIndex(proxies, i)); proxyInfoVec.push_back(proxyFromDictionary(proxy)); } } } return proxyInfoVec; }
int ValidateAsset(const char* asset_dir_path, unsigned long current_version) { const char* files[] = { "certs.plist", "distrusted.plist", "EVRoots.plist", "Manifest.plist", "revoked.plist", "roots.plist" }; int num_files = (sizeof(files) / sizeof(const char*)); int iCnt = 0; const char* file_name = NULL; char wd_buf[1024]; const char* current_working_directory_path = getcwd(wd_buf, 1024); CFDataRef file_data = NULL; CFDataRef hash_data = NULL; CFDataRef encoded_hash_data = NULL; CFStringRef manifest_hash_data_str = NULL; CFDataRef signature_data = NULL; CFStringRef key_name = NULL; CFDictionaryRef manifest_dict = NULL; CFNumberRef manifest_version = NULL; CFStringRef encoded_hash_str = NULL; CFDataRef manifest_data = NULL; unsigned long manifest_verson_number; int iResult = -1; // parameter check if (NULL == asset_dir_path) { return iResult; } if (ValidateFilesInDirectory(asset_dir_path, num_files, files)) { return iResult; } if (chdir(asset_dir_path)) { return iResult; } if (ReadFileIntoCFDataRef("Manifest.plist", &file_data)) { (void)chdir(current_working_directory_path); return iResult; } if (CreatePropertyListFromData(file_data, CFDictionaryGetTypeID(), (CFTypeRef *)&manifest_dict)) { CFRelease(file_data); (void)chdir(current_working_directory_path); return iResult; } CFRelease(file_data); // Validate the hash for the files in the manifest for (iCnt = 0; iCnt < num_files; iCnt++) { file_name = files[iCnt]; // bypass the manifest file for now if (!strcmp("Manifest.plist", file_name)) { continue; } if (ReadFileIntoCFDataRef(file_name, &file_data)) { CFRelease(manifest_dict); (void)chdir(current_working_directory_path); return iResult; } if (CreateHashForData(file_data, 0, &hash_data)) { CFRelease(file_data); CFRelease(manifest_dict); (void)chdir(current_working_directory_path); return iResult; } CFRelease(file_data); if (Base64Data(hash_data, 1, &encoded_hash_data)) { CFRelease(hash_data); CFRelease(manifest_dict); (void)chdir(current_working_directory_path); return iResult; } CFRelease(hash_data); encoded_hash_str = CFStringCreateFromExternalRepresentation(kCFAllocatorDefault, encoded_hash_data, kCFStringEncodingUTF8); if (NULL == encoded_hash_str) { CFRelease(encoded_hash_data); CFRelease(manifest_dict); (void)chdir(current_working_directory_path); return iResult; } CFRelease(encoded_hash_data); key_name = CFStringCreateWithCString(kCFAllocatorDefault, file_name, kCFStringEncodingUTF8); if (NULL == key_name) { CFRelease(encoded_hash_str); CFRelease(manifest_dict); (void)chdir(current_working_directory_path); return iResult; } manifest_hash_data_str = (CFStringRef)CFDictionaryGetValue(manifest_dict, key_name); if (NULL == manifest_hash_data_str) { CFRelease(key_name); CFRelease(encoded_hash_str); CFRelease(manifest_dict); (void)chdir(current_working_directory_path); return iResult; } CFRelease(key_name); if (!CFEqual(encoded_hash_str, manifest_hash_data_str)) { CFRelease(encoded_hash_str); CFRelease(manifest_dict); (void)chdir(current_working_directory_path); return iResult; } CFRelease(encoded_hash_str); } // Get the version manifest_version = (CFNumberRef)CFDictionaryGetValue(manifest_dict, CFSTR("Version")); if (NULL == manifest_version) { CFRelease(manifest_dict); (void)chdir(current_working_directory_path); return iResult; } if (!CFNumberGetValue(manifest_version, kCFNumberLongType, &manifest_verson_number)) { CFRelease(manifest_version); CFRelease(manifest_dict); (void)chdir(current_working_directory_path); return iResult; } CFRelease(manifest_version); if (manifest_verson_number < current_version) { CFRelease(manifest_dict); (void)chdir(current_working_directory_path); return iResult; } // Deal with the signature if (TearOffSignatureAndHashManifest(manifest_dict, &signature_data, &manifest_data)) { CFRelease(manifest_dict); (void)chdir(current_working_directory_path); return iResult; } iResult = ValidateSignature(signature_data, manifest_data); CFRelease(signature_data); CFRelease(manifest_data); CFRelease(manifest_dict); (void)chdir(current_working_directory_path); return iResult; }
char *osd_get_clipboard_text(void) { char *result = NULL; /* core expects a malloced C string of uft8 data */ PasteboardRef pasteboard_ref; OSStatus err; PasteboardSyncFlags sync_flags; PasteboardItemID item_id; CFIndex flavor_count; CFArrayRef flavor_type_array; CFIndex flavor_index; ItemCount item_count; UInt32 item_index; Boolean success = false; err = PasteboardCreate(kPasteboardClipboard, &pasteboard_ref); if (!err) { sync_flags = PasteboardSynchronize( pasteboard_ref ); err = PasteboardGetItemCount(pasteboard_ref, &item_count ); for (item_index=1; item_index<=item_count; item_index++) { err = PasteboardGetItemIdentifier(pasteboard_ref, item_index, &item_id); if (!err) { err = PasteboardCopyItemFlavors(pasteboard_ref, item_id, &flavor_type_array); if (!err) { flavor_count = CFArrayGetCount(flavor_type_array); for (flavor_index = 0; flavor_index < flavor_count; flavor_index++) { CFStringRef flavor_type; CFDataRef flavor_data; CFStringEncoding encoding; CFStringRef string_ref; CFDataRef data_ref; CFIndex length; CFRange range; flavor_type = (CFStringRef)CFArrayGetValueAtIndex(flavor_type_array, flavor_index); 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; err = PasteboardCopyItemFlavorData(pasteboard_ref, item_id, flavor_type, &flavor_data); if( !err ) { string_ref = CFStringCreateFromExternalRepresentation (kCFAllocatorDefault, flavor_data, encoding); data_ref = CFStringCreateExternalRepresentation (kCFAllocatorDefault, string_ref, kCFStringEncodingUTF8, '?'); length = CFDataGetLength (data_ref); range = CFRangeMake (0,length); result = (char *)malloc (length+1); if (result != NULL) { CFDataGetBytes (data_ref, range, (unsigned char *)result); result[length] = 0; success = true; break; } CFRelease(data_ref); CFRelease(string_ref); CFRelease(flavor_data); } } CFRelease(flavor_type_array); } } if (success) break; } CFRelease(pasteboard_ref); } return result; }
CFStringRef createXMLStringFromWebArchiveData(CFDataRef webArchiveData) { CFErrorRef error = 0; CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0; RetainPtr<CFMutableDictionaryRef> propertyList = adoptCF((CFMutableDictionaryRef)CFPropertyListCreateWithData(kCFAllocatorDefault, webArchiveData, kCFPropertyListMutableContainersAndLeaves, &format, &error)); if (!propertyList) { if (error) return CFErrorCopyDescription(error); return static_cast<CFStringRef>(CFRetain(CFSTR("An unknown error occurred converting data to property list."))); } RetainPtr<CFMutableArrayRef> resources = adoptCF(CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks)); CFArrayAppendValue(resources.get(), propertyList.get()); while (CFArrayGetCount(resources.get())) { RetainPtr<CFMutableDictionaryRef> resourcePropertyList = (CFMutableDictionaryRef)CFArrayGetValueAtIndex(resources.get(), 0); CFArrayRemoveValueAtIndex(resources.get(), 0); CFMutableDictionaryRef mainResource = (CFMutableDictionaryRef)CFDictionaryGetValue(resourcePropertyList.get(), CFSTR("WebMainResource")); normalizeWebResourceURL((CFMutableStringRef)CFDictionaryGetValue(mainResource, CFSTR("WebResourceURL"))); convertWebResourceDataToString(mainResource); // Add subframeArchives to list for processing CFMutableArrayRef subframeArchives = (CFMutableArrayRef)CFDictionaryGetValue(resourcePropertyList.get(), CFSTR("WebSubframeArchives")); // WebSubframeArchivesKey in WebArchive.m if (subframeArchives) CFArrayAppendArray(resources.get(), subframeArchives, CFRangeMake(0, CFArrayGetCount(subframeArchives))); CFMutableArrayRef subresources = (CFMutableArrayRef)CFDictionaryGetValue(resourcePropertyList.get(), CFSTR("WebSubresources")); // WebSubresourcesKey in WebArchive.m if (!subresources) continue; CFIndex subresourcesCount = CFArrayGetCount(subresources); for (CFIndex i = 0; i < subresourcesCount; ++i) { CFMutableDictionaryRef subresourcePropertyList = (CFMutableDictionaryRef)CFArrayGetValueAtIndex(subresources, i); normalizeWebResourceURL((CFMutableStringRef)CFDictionaryGetValue(subresourcePropertyList, CFSTR("WebResourceURL"))); convertWebResourceResponseToDictionary(subresourcePropertyList); convertWebResourceDataToString(subresourcePropertyList); } // Sort the subresources so they're always in a predictable order for the dump CFArraySortValues(subresources, CFRangeMake(0, CFArrayGetCount(subresources)), compareResourceURLs, 0); } error = 0; RetainPtr<CFDataRef> xmlData = adoptCF(CFPropertyListCreateData(kCFAllocatorDefault, propertyList.get(), kCFPropertyListXMLFormat_v1_0, 0, &error)); if (!xmlData) { if (error) return CFErrorCopyDescription(error); return static_cast<CFStringRef>(CFRetain(CFSTR("An unknown error occurred converting property list to data."))); } RetainPtr<CFStringRef> xmlString = adoptCF(CFStringCreateFromExternalRepresentation(kCFAllocatorDefault, xmlData.get(), kCFStringEncodingUTF8)); RetainPtr<CFMutableStringRef> string = adoptCF(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, xmlString.get())); // Replace "Apple Computer" with "Apple" in the DTD declaration. CFStringFindAndReplace(string.get(), CFSTR("-//Apple Computer//"), CFSTR("-//Apple//"), CFRangeMake(0, CFStringGetLength(string.get())), 0); return string.leakRef(); }