static char * od_get_error_string(CFErrorRef err) { CFStringRef errstringref; char *errstring; if (err != NULL) { errstringref = CFErrorCopyDescription(err); errstring = od_CFStringtoCString(errstringref); CFRelease(errstringref); } else errstring = strdup("Unknown error"); return (errstring); }
std::ostream& operator<<(std::ostream& out, CFErrorRef e) { if(NULL == e) { out << "(null)"; return out; } CFStringRef r = CFErrorCopyDescription(e); if(r) { out << r; CFRelease(r), r = NULL; } return out; }
SecurityTokenPointer Sandbox::openTokenFromBookmark(const QString& canonicalPath, const QString& bookmarkBase64) { #ifdef Q_OS_MAC #if __MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7 QByteArray bookmarkBA = QByteArray::fromBase64(bookmarkBase64.toLatin1()); if (!bookmarkBA.isEmpty()) { CFDataRef bookmarkData = CFDataCreate( kCFAllocatorDefault, reinterpret_cast<const UInt8*>(bookmarkBA.constData()), bookmarkBA.length()); Boolean stale; CFErrorRef error = NULL; CFURLRef url = CFURLCreateByResolvingBookmarkData( kCFAllocatorDefault, bookmarkData, kCFURLBookmarkResolutionWithSecurityScope, NULL, NULL, &stale, &error); if (error != NULL) { if (sDebug) { qDebug() << "Error creating URL from bookmark data:" << CFStringToQString(CFErrorCopyDescription(error)); } } CFRelease(bookmarkData); if (url != NULL) { if (!CFURLStartAccessingSecurityScopedResource(url)) { if (sDebug) { qDebug() << "CFURLStartAccessingSecurityScopedResource failed for" << canonicalPath; } } else { SecurityTokenPointer pToken = SecurityTokenPointer( new SandboxSecurityToken(canonicalPath, url)); s_activeTokens[canonicalPath] = pToken; return pToken; } } else { if (sDebug) { qDebug() << "Cannot resolve security-scoped bookmark for" << canonicalPath; } } } #endif #else Q_UNUSED(canonicalPath); Q_UNUSED(bookmarkBase64); #endif return SecurityTokenPointer(); }
static void proxyAutoConfigurationResultCallback(void *context, CFArrayRef proxies, CFErrorRef error) { // We only expect a single result callback per invocation. Stop our runloop to unblock our caller. CFRunLoopStop(CFRunLoopGetCurrent()); Vector<ProxyServer>* proxyServers = (Vector<ProxyServer>*)context; if (!proxies) { ASSERT(error); RetainPtr<CFStringRef> errorDescriptionCF(AdoptCF, CFErrorCopyDescription(error)); String errorDescription(errorDescriptionCF.get()); LOG(Network, "Failed to process proxy auto-configuration file with error: %s", errorDescription.utf8().data()); return; } processProxyServers(*proxyServers, proxies, 0); }
CFStringRef _CFErrorCreateDebugDescription(CFErrorRef err) { CFStringRef desc = CFErrorCopyDescription(err); CFStringRef debugDesc = _CFErrorCopyUserInfoKey(err, kCFErrorDebugDescriptionKey); CFDictionaryRef userInfo = _CFErrorGetUserInfo(err); CFMutableStringRef result = CFStringCreateMutable(kCFAllocatorSystemDefault, 0); CFStringAppendFormat(result, NULL, CFSTR("Error Domain=%@ Code=%d"), CFErrorGetDomain(err), (long)CFErrorGetCode(err)); CFStringAppendFormat(result, NULL, CFSTR(" \"%@\""), desc); if (debugDesc && CFStringGetLength(debugDesc) > 0) CFStringAppendFormat(result, NULL, CFSTR(" (%@)"), debugDesc); if (userInfo) { CFStringAppendFormat(result, NULL, CFSTR(" UserInfo=%p {"), userInfo); CFDictionaryApplyFunction(userInfo, userInfoKeyValueShow, (void *)result); CFIndex commaLength = (CFStringHasSuffix(result, CFSTR(", "))) ? 2 : 0; CFStringReplace(result, CFRangeMake(CFStringGetLength(result)-commaLength, commaLength), CFSTR("}")); } if (debugDesc) CFRelease(debugDesc); if (desc) CFRelease(desc); return result; }
bool Error(CFErrorRef error) { if (gSession) { CFErrorRef unused = NULL; DTPerformanceSessionStop(gSession, NULL, &unused); CFRelease(gSession); gSession = NULL; } #ifdef DEBUG AutoReleased<CFDataRef> data = CFStringCreateExternalRepresentation(NULL, CFErrorCopyDescription(error), kCFStringEncodingUTF8, '?'); if (data != NULL) { printf("%.*s\n\n", (int)CFDataGetLength(data), CFDataGetBytePtr(data)); } #endif return false; }
CFDictionaryRef download_file(int socket, CFDictionaryRef dict) { UInt8 buffer[8192]; CFIndex bytesRead; CFStringRef path = CFDictionaryGetValue(dict, CFSTR("Path")); if(path == NULL || CFGetTypeID(path) != CFStringGetTypeID()) return NULL; CFMutableDictionaryRef out = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFURLRef fileURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, path, kCFURLPOSIXPathStyle, FALSE); CFReadStreamRef stream = CFReadStreamCreateWithFile(kCFAllocatorDefault, fileURL); CFRelease(fileURL); if(!CFReadStreamOpen(stream)) { CFErrorRef error = CFReadStreamCopyError(stream); if (error != NULL) { CFStringRef errorDesc = CFErrorCopyDescription(error); CFDictionaryAddValue(out, CFSTR("Error"), errorDesc); CFRelease(errorDesc); CFRelease(error); } CFRelease(stream); return out; } CFMutableDataRef data = CFDataCreateMutable(kCFAllocatorDefault, 0); while(CFReadStreamHasBytesAvailable(stream)) { if((bytesRead = CFReadStreamRead(stream, buffer, 8192)) <= 0) break; CFDataAppendBytes(data, buffer, bytesRead); } CFReadStreamClose(stream); CFRelease(stream); CFDictionaryAddValue(out, CFSTR("Data"), data); CFRelease(data); return out; }
void SocketStreamHandle::reportErrorToClient(CFErrorRef error) { CFIndex errorCode = CFErrorGetCode(error); String description; #if PLATFORM(MAC) if (CFEqual(CFErrorGetDomain(error), kCFErrorDomainOSStatus)) { const char* descriptionOSStatus = GetMacOSStatusCommentString(static_cast<OSStatus>(errorCode)); if (descriptionOSStatus && descriptionOSStatus[0] != '\0') description = makeString("OSStatus Error ", String::number(errorCode), ": ", descriptionOSStatus); } #endif if (description.isNull()) { RetainPtr<CFStringRef> descriptionCF(AdoptCF, CFErrorCopyDescription(error)); description = String(descriptionCF.get()); } m_client->didFail(this, SocketStreamError(static_cast<int>(errorCode), m_url.string(), description)); }
static SInt32 printErrorOrMessage( CFErrorRef *inError, const char *errorString, bool inVerbose ) { SInt32 errorCode = EX_USAGE; if ( inError == NULL || (*inError) == NULL || (inVerbose == false && errorString != NULL) ) { CFStringRef cfString = CFStringCreateWithCString( kCFAllocatorDefault, errorString, kCFStringEncodingUTF8 ); if ( cfString != NULL ) { CFShow( cfString ); CFRelease( cfString ); } } else if ( inError != NULL && (*inError) != NULL ) { if ( inVerbose == true ) { CFStringRef cfString = CFErrorCopyDescription( *inError ); if ( cfString != NULL ) { CFShow( cfString ); CFRelease( cfString ); } } CFIndex errorCode = CFErrorGetCode( *inError ); // this is temporary until ODFramework has some kind of ranges for error types if ( errorCode >= kODErrorCredentialsInvalid && errorCode < kODErrorCredentialsInvalid+999 ) { errorCode = EX_NOPERM; } // we null the pointer *inError = NULL; } return errorCode; }
/* This is the description you get for %@; * we tone it down a bit from what you get in * __CFErrorCopyDescription(). */ static CFStringRef __CFErrorCopyFormattingDescription(CFTypeRef cf, CFDictionaryRef formatOptions) { CFErrorRef err = (CFErrorRef)cf; return CFErrorCopyDescription(err); }
void printErrorMsg(const char *func, CFErrorRef error) { CFStringRef desc = CFErrorCopyDescription(error); warnx("%s failed: %s", func, CFStringGetCStringPtr(desc, kCFStringEncodingUTF8)); CFRelease(desc); }
/** * 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; }
void HTTP_Stream::readCallBack(CFReadStreamRef stream, CFStreamEventType eventType, void *clientCallBackInfo) { HTTP_Stream *THIS = static_cast<HTTP_Stream*>(clientCallBackInfo); Stream_Configuration *config = Stream_Configuration::configuration(); switch (eventType) { case kCFStreamEventHasBytesAvailable: { if (!THIS->m_httpReadBuffer) { THIS->m_httpReadBuffer = new UInt8[config->httpConnectionBufferSize]; } while (CFReadStreamHasBytesAvailable(stream)) { if (!THIS->m_scheduledInRunLoop) { /* * This is critical - though the stream has data available, * do not try to feed the audio queue with data, if it has * indicated that it doesn't want more data due to buffers * full. */ THIS->m_readPending = true; break; } CFIndex bytesRead = CFReadStreamRead(stream, THIS->m_httpReadBuffer, config->httpConnectionBufferSize); if (CFReadStreamGetStatus(stream) == kCFStreamStatusError || bytesRead < 0) { #if defined (HS_DEBUG) CFErrorRef streamError = CFReadStreamCopyError(stream); if (streamError) { CFStringRef errorDesc = CFErrorCopyDescription(streamError); if (errorDesc) { HS_TRACE_CFSTRING(errorDesc); CFRelease(errorDesc); } CFRelease(streamError); } #endif /* HS_DEBUG */ if (THIS->m_delegate) { THIS->m_delegate->streamErrorOccurred(); } break; } if (bytesRead > 0) { HS_TRACE("Read %li bytes\n", bytesRead); THIS->parseHttpHeadersIfNeeded(THIS->m_httpReadBuffer, bytesRead); #ifdef INCLUDE_ID3TAG_SUPPORT if (!THIS->m_icyStream && THIS->m_id3Parser->wantData()) { THIS->m_id3Parser->feedData(THIS->m_httpReadBuffer, (UInt32)bytesRead); } #endif if (THIS->m_icyStream) { HS_TRACE("Parsing ICY stream\n"); THIS->parseICYStream(THIS->m_httpReadBuffer, bytesRead); } else { if (THIS->m_delegate) { HS_TRACE("Not an ICY stream; calling the delegate back\n"); THIS->m_delegate->streamHasBytesAvailable(THIS->m_httpReadBuffer, (UInt32)bytesRead); } } } } break; } case kCFStreamEventEndEncountered: { if (THIS->m_delegate) { THIS->m_delegate->streamEndEncountered(); } break; } case kCFStreamEventErrorOccurred: { if (THIS->m_delegate) { THIS->m_delegate->streamErrorOccurred(); } break; } } }
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; }
bool _mongoc_secure_transport_import_pem (const char *filename, const char *passphrase, CFArrayRef *items, SecExternalItemType *type) { SecExternalFormat format = kSecFormatPEMSequence; SecItemImportExportKeyParameters params; SecTransformRef sec_transform; CFReadStreamRef read_stream; CFDataRef dataref; CFErrorRef error; CFURLRef url; OSStatus res; if (!filename) { MONGOC_INFO ("%s", "No certificate provided"); return false; } params.version = SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION; params.flags = 0; params.passphrase = NULL; params.alertTitle = NULL; params.alertPrompt = NULL; params.accessRef = NULL; params.keyUsage = NULL; params.keyAttributes = NULL; if (passphrase) { params.passphrase = CFStringCreateWithCString (kCFAllocatorDefault, passphrase, kCFStringEncodingUTF8); } url = CFURLCreateFromFileSystemRepresentation (kCFAllocatorDefault, (const UInt8 *)filename, strlen (filename), false); read_stream = CFReadStreamCreateWithFile (kCFAllocatorDefault, url); sec_transform = SecTransformCreateReadTransformWithReadStream (read_stream); dataref = SecTransformExecute (sec_transform, &error); if (error) { CFStringRef str = CFErrorCopyDescription (error); MONGOC_ERROR ("Failed importing PEM '%s': %s", filename, CFStringGetCStringPtr (str, CFStringGetFastestEncoding(str))); CFRelease (str); CFRelease (sec_transform); CFRelease (read_stream); CFRelease (url); if (passphrase) { CFRelease (params.passphrase); } return false; } res = SecItemImport (dataref, CFSTR(".pem"), &format, type, 0, ¶ms, NULL, items); CFRelease (dataref); CFRelease (sec_transform); CFRelease (read_stream); CFRelease (url); if (passphrase) { CFRelease (params.passphrase); } if (res) { MONGOC_ERROR ("Failed importing PEM '%s' (code: %d)", filename, res); return false; } return true; }
/* This is the description you get for %@; we tone it down a bit from what you get in __CFErrorCopyDescription(). */ static CFStringRef __CFErrorCopyFormattingDescription(CFTypeRef cf, CFDictionaryRef formatOptions) { CFErrorRef err = (CFErrorRef)cf; return CFErrorCopyDescription(err); // No need to release, since we are returning from a Copy function }
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(); }
static cups_array_t * /* O - Message catalog */ appleMessageLoad(const char *locale) /* I - Locale ID */ { char filename[1024], /* Path to cups.strings file */ applelang[256], /* Apple language ID */ baselang[3]; /* Base language */ CFURLRef url; /* URL to cups.strings file */ CFReadStreamRef stream = NULL; /* File stream */ CFPropertyListRef plist = NULL; /* Localization file */ #ifdef DEBUG CFErrorRef error = NULL; /* Error when opening file */ #endif /* DEBUG */ DEBUG_printf(("appleMessageLoad(locale=\"%s\")", locale)); /* * Load the cups.strings file... */ snprintf(filename, sizeof(filename), CUPS_BUNDLEDIR "/Resources/%s.lproj/cups.strings", _cupsAppleLanguage(locale, applelang, sizeof(applelang))); if (access(filename, 0)) { /* * <rdar://problem/22086642> * * Try with original locale string... */ snprintf(filename, sizeof(filename), CUPS_BUNDLEDIR "/Resources/%s.lproj/cups.strings", locale); } DEBUG_printf(("1appleMessageLoad: filename=\"%s\"", filename)); if (access(filename, 0)) { /* * Try alternate lproj directory names... */ if (!strncmp(locale, "en", 2)) locale = "English"; else if (!strncmp(locale, "nb", 2) || !strncmp(locale, "nl", 2)) locale = "Dutch"; else if (!strncmp(locale, "fr", 2)) locale = "French"; else if (!strncmp(locale, "de", 2)) locale = "German"; else if (!strncmp(locale, "it", 2)) locale = "Italian"; else if (!strncmp(locale, "ja", 2)) locale = "Japanese"; else if (!strncmp(locale, "es", 2)) locale = "Spanish"; else if (!strcmp(locale, "zh_HK")) { /* * <rdar://problem/22130168> * * Try zh_TW first, then zh... Sigh... */ if (!access(CUPS_BUNDLEDIR "/Resources/zh_TW.lproj/cups.strings", 0)) locale = "zh_TW"; else locale = "zh"; } else if (strstr(locale, "_") != NULL || strstr(locale, "-") != NULL) { /* * Drop country code, just try language... */ strlcpy(baselang, locale, sizeof(baselang)); locale = baselang; } snprintf(filename, sizeof(filename), CUPS_BUNDLEDIR "/Resources/%s.lproj/cups.strings", locale); DEBUG_printf(("1appleMessageLoad: alternate filename=\"%s\"", filename)); } url = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, (UInt8 *)filename, (CFIndex)strlen(filename), false); if (url) { stream = CFReadStreamCreateWithFile(kCFAllocatorDefault, url); if (stream) { /* * Read the property list containing the localization data. * * NOTE: This code currently generates a clang "potential leak" * warning, but the object is released in _cupsMessageFree(). */ CFReadStreamOpen(stream); #ifdef DEBUG plist = CFPropertyListCreateWithStream(kCFAllocatorDefault, stream, 0, kCFPropertyListImmutable, NULL, &error); if (error) { CFStringRef msg = CFErrorCopyDescription(error); /* Error message */ CFStringGetCString(msg, filename, sizeof(filename), kCFStringEncodingUTF8); DEBUG_printf(("1appleMessageLoad: %s", filename)); CFRelease(msg); CFRelease(error); } #else plist = CFPropertyListCreateWithStream(kCFAllocatorDefault, stream, 0, kCFPropertyListImmutable, NULL, NULL); #endif /* DEBUG */ if (plist && CFGetTypeID(plist) != CFDictionaryGetTypeID()) { CFRelease(plist); plist = NULL; } CFRelease(stream); } CFRelease(url); } DEBUG_printf(("1appleMessageLoad: url=%p, stream=%p, plist=%p", url, stream, plist)); /* * Create and return an empty array to act as a cache for messages, passing the * plist as the user data. */ return (_cupsMessageNew((void *)plist)); }
static DWORD CTGetPListVersion( PSTR* ppVersion ) { DWORD error = 0; CFURLRef pURL = NULL; CFDataRef pContents = NULL; // SInt32 urlError = 0; // Do not free. This is returned by a mac function following the "get" // rule. CFStringRef pVers = NULL; CFErrorRef pError = NULL; PSTR pVersionString = NULL; CFPropertyListRef pPList = NULL; PSTR pErrorString = NULL; pURL = CFURLCreateWithFileSystemPath( kCFAllocatorDefault, CFSTR("/System/Library/CoreServices/SystemVersion.plist"), kCFURLPOSIXPathStyle, false); if (!pURL) { error = ERROR_NOT_ENOUGH_MEMORY; GCE(error); } //// CFMutableDataRef fileContent = CFDataCreateMutable(kCFAllocatorDefault, 0); CFReadStreamRef stream = CFReadStreamCreateWithFile(kCFAllocatorDefault, pURL); if(stream) { if(CFReadStreamOpen(stream)) { UInt8 buffer[BUFFERSIZE]; CFIndex bytesRead; do { bytesRead = CFReadStreamRead(stream, buffer, sizeof(buffer)); if(bytesRead > 0) { CFDataAppendBytes(fileContent, buffer, bytesRead); } } while (bytesRead > 0); CFReadStreamClose(stream); } CFRelease(stream); } //// /* if (!CFURLCreateDataAndPropertiesFromResource( kCFAllocatorDefault, pURL, &pContents, NULL, NULL, &urlError)) { error = UrlErrorToLwError(urlError); GCE(error); } */ pPList = CFPropertyListCreateWithData( kCFAllocatorDefault, pContents, kCFPropertyListImmutable, NULL, &pError); if (!pPList) { CFStringRef pErrorDesc = CFErrorCopyDescription(pError); GetPstrFromStringRef(pErrorDesc, &pErrorString); // CT_LOG_ERROR("Error '%s' parsing OS X version file", // LW_SAFE_LOG_STRING(pErrorString)); error = ERROR_PRODUCT_VERSION; CFRelease(pErrorDesc); GCE(error); } pVers = (CFStringRef)CFDictionaryGetValue( (CFDictionaryRef)pPList, CFSTR("ProductVersion")); if (!pVers) { error = ERROR_PRODUCT_VERSION; GCE(error); } error = GetPstrFromStringRef( pVers, &pVersionString); GCE(error); *ppVersion = pVersionString; cleanup: if (error) { LW_SAFE_FREE_STRING(pVersionString); } if (pError) { CFRelease(pError); } LW_SAFE_FREE_STRING(pErrorString); if (pURL) { CFRelease(pURL); } if (pContents) { CFRelease(pContents); } if (pPList) { CFRelease(pPList); } return error; }