OSStatus DoStatPaths(COMMAND_PROC_ARGUMENTS) { OSStatus retval = noErr; // Pre-conditions // userData may be NULL assert(request != NULL); assert(response != NULL); // asl may be NULL // aslMsg may be NULL // Get Info from arguments and assert that it's a CFArrayRef CFArrayRef infos = CFDictionaryGetValue(request, CFSTR(kInfos)) ; assert(infos != NULL) ; assert(CFGetTypeID(infos) == CFArrayGetTypeID()) ; CFIndex nFiles = CFArrayGetCount(infos) ; CFIndex i ; int nSucceeded = 0 ; CFMutableDictionaryRef statDatas = CFDictionaryCreateMutable( NULL, nFiles, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks ) ; CFMutableDictionaryRef errorCodes = CFDictionaryCreateMutable( NULL, nFiles, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks ) ; for (i=0; i<nFiles; i++) { CFStringRef path = CFArrayGetValueAtIndex(infos, i) ; assert(CFGetTypeID(path) == CFStringGetTypeID()) ; int errorCode = 0 ; char pathC[SSY_UNIX_PATH_UTILS_MAX_PATH_CHARS] ; if (errorCode == 0) { Boolean ok = CFStringGetCString( path, pathC, SSY_UNIX_PATH_UTILS_MAX_PATH_CHARS, kCFStringEncodingASCII ) ; if (!ok) { errorCode = SSYAuthorizedTasksPathTooLong ; } } if (errorCode == 0) { struct stat aStat ; int result = stat(pathC, &aStat) ; if (result == 0) { CFDataRef statData = CFDataCreate ( kCFAllocatorDefault, (UInt8*)&aStat, sizeof(aStat) ) ; CFDictionaryAddValue(statDatas, path, statData) ; CFQRelease(statData) ; } else { errorCode = errno ; } } if (errorCode == 0) { nSucceeded++ ; } else { CFNumberRef errorNumber = CFNumberCreate( kCFAllocatorDefault, kCFNumberIntType, &errorCode ) ; CFDictionaryAddValue(errorCodes, path, errorNumber) ; CFQRelease(errorNumber) ; } } CFDictionaryAddValue(response, CFSTR(kStatDatas), statDatas) ; CFRelease(statDatas) ; CFDictionaryAddValue(response, CFSTR(kErrorCodes), errorCodes) ; CFRelease(errorCodes) ; asl_log( asl, aslMsg, ASL_LEVEL_DEBUG, "DoStatPaths did good %d/%d requested files", nSucceeded, (int)nFiles ) ; // Return the number of file copy operations that failed retval = nFiles - nSucceeded ; return retval ; }
bool ScaledFontMac::GetFontFileData(FontFileDataOutput aDataCallback, void *aBaton) { // We'll reconstruct a TTF font from the tables we can get from the CGFont CFArrayRef tags = CGFontCopyTableTags(mFont); CFIndex count = CFArrayGetCount(tags); TableRecord *records = new TableRecord[count]; uint32_t offset = 0; offset += sizeof(uint32_t)*3; offset += sizeof(uint32_t)*4*count; bool CFF = false; for (CFIndex i = 0; i<count; i++) { uint32_t tag = (uint32_t)(uintptr_t)CFArrayGetValueAtIndex(tags, i); if (tag == 0x43464620) // 'CFF ' CFF = true; CFDataRef data = CGFontCopyTableForTag(mFont, tag); records[i].tag = tag; records[i].offset = offset; records[i].data = data; records[i].length = CFDataGetLength(data); bool skipChecksumAdjust = (tag == 0x68656164); // 'head' records[i].checkSum = CalcTableChecksum(reinterpret_cast<const uint32_t*>(CFDataGetBytePtr(data)), records[i].length, skipChecksumAdjust); offset += records[i].length; // 32 bit align the tables offset = (offset + 3) & ~3; } CFRelease(tags); struct writeBuf buf(offset); // write header/offset table if (CFF) { buf.writeElement(CFSwapInt32HostToBig(0x4f54544f)); } else { buf.writeElement(CFSwapInt32HostToBig(0x00010000)); } buf.writeElement(CFSwapInt16HostToBig(count)); buf.writeElement(CFSwapInt16HostToBig((1<<maxPow2LessThan(count))*16)); buf.writeElement(CFSwapInt16HostToBig(maxPow2LessThan(count))); buf.writeElement(CFSwapInt16HostToBig(count*16-((1<<maxPow2LessThan(count))*16))); // write table record entries for (CFIndex i = 0; i<count; i++) { buf.writeElement(CFSwapInt32HostToBig(records[i].tag)); buf.writeElement(CFSwapInt32HostToBig(records[i].checkSum)); buf.writeElement(CFSwapInt32HostToBig(records[i].offset)); buf.writeElement(CFSwapInt32HostToBig(records[i].length)); } // write tables int checkSumAdjustmentOffset = 0; for (CFIndex i = 0; i<count; i++) { if (records[i].tag == 0x68656164) { checkSumAdjustmentOffset = buf.offset + 2*4; } buf.writeMem(CFDataGetBytePtr(records[i].data), CFDataGetLength(records[i].data)); buf.align(); CFRelease(records[i].data); } delete[] records; // clear the checksumAdjust field before checksumming the whole font memset(&buf.data[checkSumAdjustmentOffset], 0, sizeof(uint32_t)); uint32_t fontChecksum = CFSwapInt32HostToBig(0xb1b0afba - CalcTableChecksum(reinterpret_cast<const uint32_t*>(buf.data), offset)); // set checkSumAdjust to the computed checksum memcpy(&buf.data[checkSumAdjustmentOffset], &fontChecksum, sizeof(fontChecksum)); // we always use an index of 0 aDataCallback(buf.data, buf.offset, 0, mSize, aBaton); return true; }
bool mongoc_secure_transport_setup_certificate ( mongoc_stream_tls_secure_transport_t *secure_transport, mongoc_ssl_opt_t *opt) { bool success; CFArrayRef items; SecIdentityRef id; SecKeyRef key = NULL; SecCertificateRef cert = NULL; SecExternalItemType type = kSecItemTypeCertificate; if (!opt->pem_file) { TRACE ("%s", "No private key provided, the server won't be able to verify us"); return false; } success = _mongoc_secure_transport_import_pem ( opt->pem_file, opt->pem_pwd, &items, &type); if (!success) { MONGOC_ERROR ("Can't find certificate in: '%s'", opt->pem_file); return false; } if (type != kSecItemTypeAggregate) { MONGOC_ERROR ("Cannot work with keys of type \"%d\". Please file a JIRA", type); CFRelease (items); return false; } for (CFIndex i = 0; i < CFArrayGetCount (items); ++i) { CFTypeID item_id = CFGetTypeID (CFArrayGetValueAtIndex (items, i)); if (item_id == SecCertificateGetTypeID ()) { cert = (SecCertificateRef) CFArrayGetValueAtIndex (items, i); } else if (item_id == SecKeyGetTypeID ()) { key = (SecKeyRef) CFArrayGetValueAtIndex (items, i); } } if (!cert || !key) { MONGOC_ERROR ("Couldn't find valid private key"); CFRelease (items); return false; } id = SecIdentityCreate (kCFAllocatorDefault, cert, key); secure_transport->my_cert = CFArrayCreateMutable (kCFAllocatorDefault, 2, &kCFTypeArrayCallBacks); CFArrayAppendValue (secure_transport->my_cert, id); CFArrayAppendValue (secure_transport->my_cert, cert); CFRelease (id); /* * Secure Transport assumes the following: * * The certificate references remain valid for the lifetime of the * session. * * The identity specified in certRefs[0] is capable of signing. */ success = !SSLSetCertificate (secure_transport->ssl_ctx_ref, secure_transport->my_cert); TRACE ("Setting client certificate %s", success ? "succeeded" : "failed"); CFRelease (items); return true; }
static void pango_core_text_family_list_faces (PangoFontFamily *family, PangoFontFace ***faces, int *n_faces) { PangoCoreTextFamily *ctfamily = PANGO_CORE_TEXT_FAMILY (family); if (ctfamily->n_faces < 0) { GList *l; GList *faces = NULL; GList *synthetic_faces = NULL; GHashTable *italic_faces; const char *real_family = get_real_family (ctfamily->family_name); CTFontCollectionRef collection; CFArrayRef ctfaces; CFArrayRef font_descriptors; CFDictionaryRef attributes; CFIndex i, count; CFTypeRef keys[] = { (CFTypeRef) kCTFontFamilyNameAttribute }; CFStringRef values[] = { CFStringCreateWithCString (kCFAllocatorDefault, real_family, kCFStringEncodingUTF8) }; CTFontDescriptorRef descriptors[1]; attributes = CFDictionaryCreate (kCFAllocatorDefault, (const void **)keys, (const void **)values, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); descriptors[0] = CTFontDescriptorCreateWithAttributes (attributes); font_descriptors = CFArrayCreate (kCFAllocatorDefault, (const void **)descriptors, 1, &kCFTypeArrayCallBacks); collection = CTFontCollectionCreateWithFontDescriptors (font_descriptors, NULL); ctfaces = CTFontCollectionCreateMatchingFontDescriptors (collection); italic_faces = g_hash_table_new (g_direct_hash, g_direct_equal); count = CFArrayGetCount (ctfaces); for (i = 0; i < count; i++) { PangoCoreTextFace *face; CTFontDescriptorRef desc = CFArrayGetValueAtIndex (ctfaces, i); face = pango_core_text_face_from_ct_font_descriptor (desc); face->family = ctfamily; faces = g_list_prepend (faces, face); if (face->traits & kCTFontItalicTrait || pango_core_text_face_is_oblique (face)) g_hash_table_insert (italic_faces, GINT_TO_POINTER ((gint)face->weight), face); } CFRelease (font_descriptors); CFRelease (attributes); CFRelease (ctfaces); /* For all fonts for which a non-synthetic italic variant does * not exist on the system, we create synthesized versions here. */ for (l = faces; l; l = l->next) { PangoCoreTextFace *face = l->data; if (!g_hash_table_lookup (italic_faces, GINT_TO_POINTER ((gint)face->weight))) { PangoCoreTextFace *italic_face; italic_face = g_object_new (PANGO_TYPE_CORE_TEXT_FACE, NULL); italic_face->family = ctfamily; italic_face->postscript_name = g_strdup (face->postscript_name); italic_face->weight = face->weight; italic_face->traits = face->traits | kCTFontItalicTrait; italic_face->synthetic_italic = TRUE; italic_face->coverage = pango_coverage_ref (face->coverage); /* Try to create a sensible face name. */ if (strcasecmp (face->style_name, "regular") == 0) italic_face->style_name = g_strdup ("Oblique"); else italic_face->style_name = g_strdup_printf ("%s Oblique", face->style_name); synthetic_faces = g_list_prepend (synthetic_faces, italic_face); } } faces = g_list_concat (faces, synthetic_faces); ctfamily->n_faces = g_list_length (faces); ctfamily->faces = g_new (PangoFontFace *, ctfamily->n_faces); for (l = faces, i = 0; l; l = l->next, i++) ctfamily->faces[i] = l->data; g_list_free (faces); g_hash_table_destroy (italic_faces); }
CF_INLINE void __CFArrayValidateRange(CFArrayRef array, CFRange range, const char *func) { CFAssert3(0 <= range.location && range.location <= CFArrayGetCount(array), __kCFLogAssertion, "%s(): range.location index (%ld) out of bounds (0, %ld)", func, range.location, CFArrayGetCount(array)); CFAssert2(0 <= range.length, __kCFLogAssertion, "%s(): range.length (%ld) cannot be less than zero", func, range.length); CFAssert3(range.location + range.length <= CFArrayGetCount(array), __kCFLogAssertion, "%s(): ending index (%ld) out of bounds (0, %ld)", func, range.location + range.length, CFArrayGetCount(array)); }
PsychError SCREENReadNormalizedGammaTable(void) { int i, screenNumber, numEntries, reallutsize, physicalDisplay, outputId; float *redTable, *greenTable, *blueTable; double *gammaTable; //all subfunctions should have these two lines PsychPushHelp(useString, synopsisString, seeAlsoString); if(PsychIsGiveHelp()){PsychGiveHelp();return(PsychError_none);}; PsychErrorExit(PsychCapNumOutputArgs(3)); PsychErrorExit(PsychCapNumInputArgs(2)); // Get optional physicalDisplay argument - It defaults to zero: physicalDisplay = -1; PsychCopyInIntegerArg(2, FALSE, &physicalDisplay); // Read in the screen number: // On OS/X we also accept screen indices for physical displays (as opposed to active dispays). // This only makes a difference in mirror-mode, where there is only 1 active display, but that // corresponds to two physical displays which can have different gamma setting requirements: if ((PSYCH_SYSTEM == PSYCH_OSX) && (physicalDisplay > 0)) { PsychCopyInIntegerArg(1, TRUE, &screenNumber); if (screenNumber < 1) PsychErrorExitMsg(PsychError_user, "A 'screenNumber' that is smaller than one provided, although 'physicalDisplay' flag set. This is not allowed!"); // Invert screenNumber as a sign its a physical display, not an active display: screenNumber = -1 * screenNumber; } else { PsychCopyInScreenNumberArg(1, TRUE, &screenNumber); } if ((PSYCH_SYSTEM == PSYCH_LINUX) && (physicalDisplay > -1)) { // Affect one specific display output for given screen: outputId = physicalDisplay; } else { // Other OS'es, and Linux with default setting: Affect all outputs // for a screen. outputId = -1; } // Retrieve gamma table: PsychReadNormalizedGammaTable(screenNumber, outputId, &numEntries, &redTable, &greenTable, &blueTable); // Copy it out to runtime: PsychAllocOutDoubleMatArg(1, FALSE, numEntries, 3, 0, &gammaTable); for(i=0;i<numEntries;i++){ gammaTable[PsychIndexElementFrom3DArray(numEntries, 3, 0, i, 0, 0)]=(double)redTable[i]; gammaTable[PsychIndexElementFrom3DArray(numEntries, 3, 0, i, 1, 0)]=(double)greenTable[i]; gammaTable[PsychIndexElementFrom3DArray(numEntries, 3, 0, i, 2, 0)]=(double)blueTable[i]; } // Copy out optional DAC resolution value: PsychCopyOutDoubleArg(2, FALSE, (double) PsychGetDacBitsFromDisplay(screenNumber)); // We default to the assumption that the real size of the hardware LUT is identical to // the size of the returned LUT: reallutsize = numEntries; #if PSYCH_SYSTEM == PSYCH_OSX // On OS-X we query the real LUT size from the OS and return that value: CGDirectDisplayID displayID; CFMutableDictionaryRef properties; CFNumberRef cfGammaLength; SInt32 lutslotcount; io_service_t displayService; kern_return_t kr; CFMutableArrayRef framebufferTimings0 = 0; CFDataRef framebufferTimings1 = 0; IODetailedTimingInformationV2 *framebufferTiming = NULL; // Retrieve display handle for screen: PsychGetCGDisplayIDFromScreenNumber(&displayID, screenNumber); // Retrieve low-level IOKit service port for this display: displayService = CGDisplayIOServicePort(displayID); // Obtain the properties from that service kr = IORegistryEntryCreateCFProperties(displayService, &properties, NULL, 0); if((kr == kIOReturnSuccess) && ((cfGammaLength = (CFNumberRef) CFDictionaryGetValue(properties, CFSTR(kIOFBGammaCountKey)))!=NULL)) { CFNumberGetValue(cfGammaLength, kCFNumberSInt32Type, &lutslotcount); CFRelease(properties); reallutsize = (int) lutslotcount; } else { // Failed! if (PsychPrefStateGet_Verbosity()>1) printf("PTB-WARNING: Failed to query real size of video LUT for screen %i! Will return safe default of %i slots.\n", screenNumber, reallutsize); } if (PsychPrefStateGet_Verbosity()>9) { CGDisplayModeRef currentMode; CFNumberRef n; int modeId; currentMode = CGDisplayCopyDisplayMode(displayID); modeId = (int) CGDisplayModeGetIODisplayModeID(currentMode); CGDisplayModeRelease(currentMode); printf("Current mode has id %i\n\n", modeId); kr = IORegistryEntryCreateCFProperties(displayService, &properties, NULL, 0); if((kr == kIOReturnSuccess) && ((framebufferTimings0 = (CFMutableArrayRef) CFDictionaryGetValue(properties, CFSTR(kIOFBDetailedTimingsKey) ) )!=NULL)) { for (i=0; i<CFArrayGetCount(framebufferTimings0); i++) { if ((framebufferTimings1 = CFArrayGetValueAtIndex(framebufferTimings0, i)) != NULL) { if ((framebufferTiming = (IODetailedTimingInformationV2*) CFDataGetBytePtr(framebufferTimings1)) != NULL) { printf("[%i] : VActive = %li, VBL = %li, VSYNC = %li, VSYNCWIDTH = %li , VBORDERBOT = %li, VTOTAL = %li \n", i, framebufferTiming->verticalActive, framebufferTiming->verticalBlanking, framebufferTiming->verticalSyncOffset, framebufferTiming->verticalSyncPulseWidth, framebufferTiming->verticalBorderBottom, framebufferTiming->verticalActive + framebufferTiming->verticalBlanking); } } } CFRelease(properties); } else { // Failed! if (PsychPrefStateGet_Verbosity()>1) printf("PTB-WARNING: Failed to query STUFF for screen %i --> %p!\n", screenNumber, properties); } } #endif // Copy out optional real LUT size (number of slots): PsychCopyOutDoubleArg(3, FALSE, (double) reallutsize); return(PsychError_none); }
OSStatus sslCreateSecTrust( SSLContext *ctx, CFArrayRef certChain, bool arePeerCerts, SecTrustRef *pTrust) /* RETURNED */ { OSStatus status = errSecAllocate; CFStringRef peerDomainName = NULL; CFTypeRef policies = NULL; SecTrustRef trust = NULL; const char *peerDomainNameData = NULL; size_t peerDomainNameLen = 0; if(ctx->protocolSide==kSSLClientSide) { tls_handshake_get_peer_hostname(ctx->hdsk, &peerDomainNameData, &peerDomainNameLen); } if (CFArrayGetCount(certChain) == 0) { status = errSSLBadCert; goto errOut; } if (arePeerCerts) { if (peerDomainNameLen && peerDomainNameData) { CFIndex len = peerDomainNameLen; if (peerDomainNameData[len - 1] == 0) { len--; //secwarning("peerDomainName is zero terminated!"); } /* @@@ Double check that this is the correct encoding. */ require(peerDomainName = CFStringCreateWithBytes(kCFAllocatorDefault, (const UInt8 *)peerDomainNameData, len, kCFStringEncodingUTF8, false), errOut); } } /* If we are the client, our peer certificates must satisfy the ssl server policy. */ bool server = ctx->protocolSide == kSSLClientSide; require(policies = SecPolicyCreateSSL(server, peerDomainName), errOut); require_noerr(status = SecTrustCreateWithCertificates(certChain, policies, &trust), errOut); /* If we have trustedAnchors we set them here. */ if (ctx->trustedCerts) { require_noerr(status = SecTrustSetAnchorCertificates(trust, ctx->trustedCerts), errOut); require_noerr(status = SecTrustSetAnchorCertificatesOnly(trust, ctx->trustedCertsOnly), errOut); } status = errSecSuccess; errOut: CFReleaseSafe(peerDomainName); CFReleaseSafe(policies); *pTrust = trust; return status; }
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()); } }
bool SetFallbackFont(FreeTypeSettings *settings, const char *language_isocode, int winlangid, MissingGlyphSearcher *callback) { const char *str; bool result = false; callback->FindMissingGlyphs(&str); #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5) if (MacOSVersionIsAtLeast(10, 5, 0)) { /* Determine fallback font using CoreText. This uses the language isocode * to find a suitable font. CoreText is available from 10.5 onwards. */ char lang[16]; if (strcmp(language_isocode, "zh_TW") == 0) { /* Traditional Chinese */ strecpy(lang, "zh-Hant", lastof(lang)); } else if (strcmp(language_isocode, "zh_CN") == 0) { /* Simplified Chinese */ strecpy(lang, "zh-Hans", lastof(lang)); } else if (strncmp(language_isocode, "ur", 2) == 0) { /* The urdu alphabet is variant of persian. As OS X has no default * font that advertises an urdu language code, search for persian * support instead. */ strecpy(lang, "fa", lastof(lang)); } else { /* Just copy the first part of the isocode. */ strecpy(lang, language_isocode, lastof(lang)); char *sep = strchr(lang, '_'); if (sep != NULL) *sep = '\0'; } CFStringRef lang_code; lang_code = CFStringCreateWithCString(kCFAllocatorDefault, lang, kCFStringEncodingUTF8); /* Create a font iterator and iterate over all fonts that * are available to the application. */ ATSFontIterator itr; ATSFontRef font; ATSFontIteratorCreate(kATSFontContextLocal, NULL, NULL, kATSOptionFlagsUnRestrictedScope, &itr); while (!result && ATSFontIteratorNext(itr, &font) == noErr) { /* Get CoreText font handle. */ CTFontRef font_ref = CTFontCreateWithPlatformFont(font, 0.0, NULL, NULL); CFArrayRef langs = CTFontCopySupportedLanguages(font_ref); if (langs != NULL) { /* Font has a list of supported languages. */ for (CFIndex i = 0; i < CFArrayGetCount(langs); i++) { CFStringRef lang = (CFStringRef)CFArrayGetValueAtIndex(langs, i); if (CFStringCompare(lang, lang_code, kCFCompareAnchored) == kCFCompareEqualTo) { /* Lang code is supported by font, get full font name. */ CFStringRef font_name = CTFontCopyFullName(font_ref); char name[128]; CFStringGetCString(font_name, name, lengthof(name), kCFStringEncodingUTF8); CFRelease(font_name); /* Skip some inappropriate or ugly looking fonts that have better alternatives. */ if (strncmp(name, "Courier", 7) == 0 || strncmp(name, "Apple Symbols", 13) == 0 || strncmp(name, ".Aqua", 5) == 0 || strncmp(name, "LastResort", 10) == 0 || strncmp(name, "GB18030 Bitmap", 14) == 0) continue; /* Save result. */ callback->SetFontNames(settings, name); DEBUG(freetype, 2, "CT-Font for %s: %s", language_isocode, name); result = true; break; } } CFRelease(langs); } CFRelease(font_ref); } ATSFontIteratorRelease(&itr); CFRelease(lang_code); } else #endif { #if (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5) && !__LP64__ /* Determine fallback font using ATSUI. This uses a string sample with * missing characters. This is not failure-proof, but a better way like * using the isocode as in the CoreText code path is not available. * ATSUI was deprecated with 10.6 and is only partially available in * 64-bit mode. */ /* Remove all control characters in the range from SCC_CONTROL_START to * SCC_CONTROL_END as well as all ASCII < 0x20 from the string as it will * mess with the automatic font detection */ char buff[256]; // This length is enough to find a suitable replacement font strecpy(buff, str, lastof(buff)); str_validate(buff, lastof(buff), SVS_ALLOW_NEWLINE); /* Extract a UniChar representation of the sample string. */ CFStringRef cf_str = CFStringCreateWithCString(kCFAllocatorDefault, buff, kCFStringEncodingUTF8); if (cf_str == NULL) { /* Something went wrong. Corrupt/invalid sample string? */ return false; } CFIndex str_len = CFStringGetLength(cf_str); UniChar string[str_len]; CFStringGetCharacters(cf_str, CFRangeMake(0, str_len), string); /* Create a default text style with the default font. */ ATSUStyle style; ATSUCreateStyle(&style); /* Create a text layout object from the sample string using the text style. */ UniCharCount run_len = kATSUToTextEnd; ATSUTextLayout text_layout; ATSUCreateTextLayoutWithTextPtr(string, kATSUFromTextBeginning, kATSUToTextEnd, str_len, 1, &run_len, &style, &text_layout); /* Try to match a font for the sample text. ATSUMatchFontsToText stops after * it finds the first continuous character run not renderable with the currently * selected font starting at offset. The matching needs to be repeated until * the end of the string is reached to make sure the fallback font matches for * all characters in the string and not only the first run. */ UniCharArrayOffset offset = kATSUFromTextBeginning; OSStatus os_err; do { ATSUFontID font; UniCharCount run_len; os_err = ATSUMatchFontsToText(text_layout, offset, kATSUToTextEnd, &font, &offset, &run_len); if (os_err == kATSUFontsMatched) { /* Found a better fallback font. Update the text layout * object with the new font. */ ATSUAttributeTag tag = kATSUFontTag; ByteCount size = sizeof(font); ATSUAttributeValuePtr val = &font; ATSUSetAttributes(style, 1, &tag, &size, &val); offset += run_len; } /* Exit if the end of the string is reached or some other error occurred. */ } while (os_err == kATSUFontsMatched && offset < (UniCharArrayOffset)str_len); if (os_err == noErr || os_err == kATSUFontsMatched) { /* ATSUMatchFontsToText exited normally. Extract font * out of the text layout object. */ ATSUFontID font; ByteCount act_len; ATSUGetAttribute(style, kATSUFontTag, sizeof(font), &font, &act_len); /* Get unique font name. The result is not a c-string, we have * to leave space for a \0 and terminate it ourselves. */ char name[128]; ATSUFindFontName(font, kFontUniqueName, kFontNoPlatformCode, kFontNoScriptCode, kFontNoLanguageCode, 127, name, &act_len, NULL); name[act_len > 127 ? 127 : act_len] = '\0'; /* Save Result. */ callback->SetFontNames(settings, name); DEBUG(freetype, 2, "ATSUI-Font for %s: %s", language_isocode, name); result = true; } ATSUDisposeTextLayout(text_layout); ATSUDisposeStyle(style); CFRelease(cf_str); #endif } if (result && strncmp(settings->medium.font, "Geeza Pro", 9) == 0) { /* The font 'Geeza Pro' is often found for arabic characters, but * it has the 'tiny' problem of not having any latin characters. * 'Arial Unicode MS' on the other hand has arabic and latin glyphs, * but seems to 'forget' to inform the OS about this fact. Manually * substitute the latter for the former if it is loadable. */ bool ft_init = _library != NULL; FT_Face face; /* Init FreeType if needed. */ if ((ft_init || FT_Init_FreeType(&_library) == FT_Err_Ok) && GetFontByFaceName("Arial Unicode MS", &face) == FT_Err_Ok) { FT_Done_Face(face); callback->SetFontNames(settings, "Arial Unicode MS"); DEBUG(freetype, 1, "Replacing font 'Geeza Pro' with 'Arial Unicode MS'"); } if (!ft_init) { /* Uninit FreeType if we did the init. */ FT_Done_FreeType(_library); _library = NULL; } } callback->FindMissingGlyphs(NULL); return result; }
static int keychain_iter_start(hx509_context context, hx509_certs certs, void *data, void **cursor) { #ifndef __APPLE_TARGET_EMBEDDED__ struct ks_keychain *ctx = data; #endif struct iter *iter; iter = calloc(1, sizeof(*iter)); if (iter == NULL) { hx509_set_error_string(context, 0, ENOMEM, "out of memory"); return ENOMEM; } #ifndef __APPLE_TARGET_EMBEDDED__ if (ctx->anchors) { CFArrayRef anchors; int ret; int i; ret = hx509_certs_init(context, "MEMORY:ks-file-create", 0, NULL, &iter->certs); if (ret) { free(iter); return ret; } ret = SecTrustCopyAnchorCertificates(&anchors); if (ret != 0) { hx509_certs_free(&iter->certs); free(iter); hx509_set_error_string(context, 0, ENOMEM, "Can't get trust anchors from Keychain"); return ENOMEM; } for (i = 0; i < CFArrayGetCount(anchors); i++) { SecCertificateRef cr; hx509_cert cert; CFDataRef dataref; cr = (SecCertificateRef)CFArrayGetValueAtIndex(anchors, i); dataref = SecCertificateCopyData(cr); if (dataref == NULL) continue; ret = hx509_cert_init_data(context, CFDataGetBytePtr(dataref), CFDataGetLength(dataref), &cert); CFRelease(dataref); if (ret) continue; ret = hx509_certs_add(context, iter->certs, cert); hx509_cert_free(cert); } CFRelease(anchors); if (ret != 0) { hx509_certs_free(&iter->certs); free(iter); hx509_set_error_string(context, 0, ret, "Failed to add cert"); return ret; } } if (iter->certs) { int ret; ret = hx509_certs_start_seq(context, iter->certs, &iter->cursor); if (ret) { hx509_certs_free(&iter->certs); free(iter); return ret; } } else #endif { OSStatus ret; const void *keys[] = { kSecClass, kSecReturnRef, kSecMatchLimit }; const void *values[] = { kSecClassCertificate, kCFBooleanTrue, kSecMatchLimitAll }; CFDictionaryRef secQuery; secQuery = CFDictionaryCreate(NULL, keys, values, sizeof(keys) / sizeof(*keys), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); ret = SecItemCopyMatching(secQuery, (CFTypeRef *)&iter->search); CFRelease(secQuery); if (ret) { free(iter); return ENOMEM; } } *cursor = iter; return 0; }
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 int keychain_query(hx509_context context, hx509_certs certs, void *data, const hx509_query *query, hx509_cert *retcert) { CFArrayRef identities = NULL; hx509_cert cert = NULL; CFIndex n, count; int ret; int kdcLookupHack = 0; /* * First to course filtering using security framework .... */ #define FASTER_FLAGS (HX509_QUERY_MATCH_PERSISTENT|HX509_QUERY_PRIVATE_KEY) if ((query->match & FASTER_FLAGS) == 0) return HX509_UNIMPLEMENTED_OPERATION; CFMutableDictionaryRef secQuery = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); /* * XXX this is so broken, SecItem doesn't find the kdc certificte, * and kdc certificates happend to be searched by friendly name, * so find that and mundge on the structure. */ if ((query->match & HX509_QUERY_MATCH_FRIENDLY_NAME) && (query->match & HX509_QUERY_PRIVATE_KEY) && strcmp(query->friendlyname, "O=System Identity,CN=com.apple.kerberos.kdc") == 0) { ((hx509_query *)query)->match &= ~HX509_QUERY_PRIVATE_KEY; kdcLookupHack = 1; } if (kdcLookupHack || (query->match & HX509_QUERY_MATCH_PERSISTENT)) { CFDictionaryAddValue(secQuery, kSecClass, kSecClassCertificate); } else CFDictionaryAddValue(secQuery, kSecClass, kSecClassIdentity); CFDictionaryAddValue(secQuery, kSecReturnRef, kCFBooleanTrue); CFDictionaryAddValue(secQuery, kSecMatchLimit, kSecMatchLimitAll); if (query->match & HX509_QUERY_MATCH_PERSISTENT) { CFDataRef refdata = CFDataCreateWithBytesNoCopy(NULL, query->persistent->data, query->persistent->length, kCFAllocatorNull); CFDictionaryAddValue(secQuery, kSecValuePersistentRef, refdata); CFRelease(refdata); } OSStatus status = SecItemCopyMatching(secQuery, (CFTypeRef *)&identities); CFRelease(secQuery); if (status || identities == NULL) { hx509_clear_error_string(context); return HX509_CERT_NOT_FOUND; } heim_assert(CFArrayGetTypeID() == CFGetTypeID(identities), "return value not an array"); /* * ... now do hx509 filtering */ count = CFArrayGetCount(identities); for (n = 0; n < count; n++) { CFTypeRef secitem = (CFTypeRef)CFArrayGetValueAtIndex(identities, n); #ifndef __APPLE_TARGET_EMBEDDED__ if (query->match & HX509_QUERY_MATCH_PERSISTENT) { SecIdentityRef other = NULL; OSStatus osret; osret = SecIdentityCreateWithCertificate(NULL, (SecCertificateRef)secitem, &other); if (osret == noErr) { ret = hx509_cert_init_SecFramework(context, (void *)other, &cert); CFRelease(other); if (ret) continue; } else { ret = hx509_cert_init_SecFramework(context, (void *)secitem, &cert); if (ret) continue; } } else #endif { ret = hx509_cert_init_SecFramework(context, (void *)secitem, &cert); if (ret) continue; } if (_hx509_query_match_cert(context, query, cert)) { #ifndef __APPLE_TARGET_EMBEDDED__ /* certtool/keychain doesn't glue togheter the cert with keys for system keys */ if (kdcLookupHack) { SecIdentityRef other = NULL; OSStatus osret; osret = SecIdentityCreateWithCertificate(NULL, (SecCertificateRef)secitem, &other); if (osret == noErr) { hx509_cert_free(cert); ret = hx509_cert_init_SecFramework(context, other, &cert); CFRelease(other); if (ret) continue; } } #endif *retcert = cert; break; } hx509_cert_free(cert); } if (kdcLookupHack) ((hx509_query *)query)->match |= HX509_QUERY_PRIVATE_KEY; CFRelease(identities); if (*retcert == NULL) { hx509_clear_error_string(context); return HX509_CERT_NOT_FOUND; } return 0; }
static QVariant qtValue(CFPropertyListRef cfvalue) { if (!cfvalue) return QVariant(); CFTypeID typeId = CFGetTypeID(cfvalue); /* Sorted grossly from most to least frequent type. */ if (typeId == CFStringGetTypeID()) { return QSettingsPrivate::stringToVariant(QCFString::toQString(static_cast<CFStringRef>(cfvalue))); } else if (typeId == CFNumberGetTypeID()) { CFNumberRef cfnumber = static_cast<CFNumberRef>(cfvalue); if (CFNumberIsFloatType(cfnumber)) { double d; CFNumberGetValue(cfnumber, kCFNumberDoubleType, &d); return d; } else { int i; qint64 ll; if (CFNumberGetValue(cfnumber, kCFNumberIntType, &i)) return i; CFNumberGetValue(cfnumber, kCFNumberLongLongType, &ll); return ll; } } else if (typeId == CFArrayGetTypeID()) { CFArrayRef cfarray = static_cast<CFArrayRef>(cfvalue); QList<QVariant> list; CFIndex size = CFArrayGetCount(cfarray); bool metNonString = false; for (CFIndex i = 0; i < size; ++i) { QVariant value = qtValue(CFArrayGetValueAtIndex(cfarray, i)); if (value.type() != QVariant::String) metNonString = true; list << value; } if (metNonString) return list; else return QVariant(list).toStringList(); } else if (typeId == CFBooleanGetTypeID()) { return (bool)CFBooleanGetValue(static_cast<CFBooleanRef>(cfvalue)); } else if (typeId == CFDataGetTypeID()) { CFDataRef cfdata = static_cast<CFDataRef>(cfvalue); return QByteArray(reinterpret_cast<const char *>(CFDataGetBytePtr(cfdata)), CFDataGetLength(cfdata)); } else if (typeId == CFDictionaryGetTypeID()) { CFDictionaryRef cfdict = static_cast<CFDictionaryRef>(cfvalue); CFTypeID arrayTypeId = CFArrayGetTypeID(); int size = (int)CFDictionaryGetCount(cfdict); QVarLengthArray<CFPropertyListRef> keys(size); QVarLengthArray<CFPropertyListRef> values(size); CFDictionaryGetKeysAndValues(cfdict, keys.data(), values.data()); QMultiMap<QString, QVariant> map; for (int i = 0; i < size; ++i) { QString key = QCFString::toQString(static_cast<CFStringRef>(keys[i])); if (CFGetTypeID(values[i]) == arrayTypeId) { CFArrayRef cfarray = static_cast<CFArrayRef>(values[i]); CFIndex arraySize = CFArrayGetCount(cfarray); for (CFIndex j = arraySize - 1; j >= 0; --j) map.insert(key, qtValue(CFArrayGetValueAtIndex(cfarray, j))); } else { map.insert(key, qtValue(values[i])); } } return map; } else if (typeId == CFDateGetTypeID()) { QDateTime dt; dt.setTime_t((uint)kCFAbsoluteTimeIntervalSince1970); return dt.addSecs((int)CFDateGetAbsoluteTime(static_cast<CFDateRef>(cfvalue))); } return QVariant(); }
// Sorry for the very long code, all nicer OS X APIs are coded in Objective C and not C! // Also it does very thorough error handling bool GetDataFromPasteboard( PasteboardRef inPasteboard, char* flavorText /* out */, const int bufSize ) { OSStatus err = noErr; PasteboardSyncFlags syncFlags; ItemCount itemCount; syncFlags = PasteboardSynchronize( inPasteboard ); //require_action( syncFlags & kPasteboardModified, PasteboardOutOfSync, // err = badPasteboardSyncErr ); err = PasteboardGetItemCount( inPasteboard, &itemCount ); require_noerr( err, CantGetPasteboardItemCount ); for (UInt32 itemIndex = 1; itemIndex <= itemCount; itemIndex++) { PasteboardItemID itemID; CFArrayRef flavorTypeArray; CFIndex flavorCount; err = PasteboardGetItemIdentifier( inPasteboard, itemIndex, &itemID ); require_noerr( err, CantGetPasteboardItemIdentifier ); err = PasteboardCopyItemFlavors( inPasteboard, itemID, &flavorTypeArray ); require_noerr( err, CantCopyPasteboardItemFlavors ); flavorCount = CFArrayGetCount( flavorTypeArray ); for (CFIndex flavorIndex = 0; flavorIndex < flavorCount; flavorIndex++) { CFStringRef flavorType; CFDataRef flavorData; CFIndex flavorDataSize; flavorType = (CFStringRef)CFArrayGetValueAtIndex(flavorTypeArray, flavorIndex); // we're only interested by text... if (UTTypeConformsTo(flavorType, CFSTR("public.utf8-plain-text"))) { err = PasteboardCopyItemFlavorData( inPasteboard, itemID, flavorType, &flavorData ); require_noerr( err, CantCopyFlavorData ); flavorDataSize = CFDataGetLength( flavorData ); flavorDataSize = (flavorDataSize<254) ? flavorDataSize : 254; if (flavorDataSize+2 > bufSize) { fprintf(stderr, "Cannot copy clipboard, contents is too big!\n"); return false; } for (short dataIndex = 0; dataIndex <= flavorDataSize; dataIndex++) { char byte = *(CFDataGetBytePtr( flavorData ) + dataIndex); flavorText[dataIndex] = byte; } flavorText[flavorDataSize] = '\0'; flavorText[flavorDataSize+1] = '\n'; CFRelease (flavorData); return true; } continue; CantCopyFlavorData: fprintf(stderr, "Cannot copy clipboard, CantCopyFlavorData!\n"); } CFRelease (flavorTypeArray); continue; CantCopyPasteboardItemFlavors: fprintf(stderr, "Cannot copy clipboard, CantCopyPasteboardItemFlavors!\n"); continue; CantGetPasteboardItemIdentifier: fprintf(stderr, "Cannot copy clipboard, CantGetPasteboardItemIdentifier!\n"); continue; } fprintf(stderr, "Cannot copy clipboard, found no acceptable flavour!\n"); return false; CantGetPasteboardItemCount: fprintf(stderr, "Cannot copy clipboard, CantGetPasteboardItemCount!\n"); return false; //PasteboardOutOfSync: fprintf(stderr, "Cannot copy clipboard, PasteboardOutOfSync!\n"); return false; }
// utility routine to dump device info void HIDDumpDeviceInfo( IOHIDDeviceRef inIOHIDDeviceRef ) { char cstring[256]; printf( "Device: %p = { ", inIOHIDDeviceRef ); char manufacturer[256] = ""; // name of manufacturer CFStringRef tCFStringRef = IOHIDDevice_GetManufacturer( inIOHIDDeviceRef ); if ( tCFStringRef ) { verify( CFStringGetCString( tCFStringRef, manufacturer, sizeof( manufacturer ), kCFStringEncodingUTF8 ) ); } char product[256] = ""; // name of product tCFStringRef = IOHIDDevice_GetProduct( inIOHIDDeviceRef ); if ( tCFStringRef ) { verify( CFStringGetCString( tCFStringRef, product, sizeof( product ), kCFStringEncodingUTF8 ) ); } printf( "%s - %s, ", manufacturer, product ); long vendorID = IOHIDDevice_GetVendorID( inIOHIDDeviceRef ); if ( vendorID ) { #if 1 printf( " vendorID: 0x%04lX, ", vendorID ); #else if ( HIDGetVendorNameFromVendorID( vendorID, cstring ) ) { printf( " vendorID: 0x%04lX (\"%s\"), ", vendorID, cstring ); } else { printf( " vendorID: 0x%04lX, ", vendorID ); } #endif } long productID = IOHIDDevice_GetProductID( inIOHIDDeviceRef ); if ( productID ) { #if 1 printf( " productID: 0x%04lX, ", productID ); #else if ( HIDGetProductNameFromVendorProductID( vendorID, productID, cstring ) ) { printf( " productID: 0x%04lX (\"%s\"), ", productID, cstring ); } else { printf( " productID: 0x%04lX, ", productID ); } #endif } uint32_t usagePage = IOHIDDevice_GetUsagePage( inIOHIDDeviceRef ); uint32_t usage = IOHIDDevice_GetUsage( inIOHIDDeviceRef ); if ( !usagePage || !usage ) { usagePage = IOHIDDevice_GetPrimaryUsagePage( inIOHIDDeviceRef ); usage = IOHIDDevice_GetPrimaryUsage( inIOHIDDeviceRef ); } printf( "usage: 0x%04lX:0x%04lX, ", (long unsigned int) usagePage, (long unsigned int) usage ); #if 1 tCFStringRef = HIDCopyUsageName( usagePage, usage ); if ( tCFStringRef ) { verify( CFStringGetCString( tCFStringRef, cstring, sizeof( cstring ), kCFStringEncodingUTF8 ) ); printf( "\"%s\", ", cstring ); CFRelease( tCFStringRef ); } #endif #if 1 tCFStringRef = IOHIDDevice_GetTransport( inIOHIDDeviceRef ); if ( tCFStringRef ) { verify( CFStringGetCString( tCFStringRef, cstring, sizeof( cstring ), kCFStringEncodingUTF8 ) ); printf( "Transport: \"%s\", ", cstring ); } long vendorIDSource = IOHIDDevice_GetVendorIDSource( inIOHIDDeviceRef ); if ( vendorIDSource ) { printf( "VendorIDSource: %ld, ", vendorIDSource ); } long version = IOHIDDevice_GetVersionNumber( inIOHIDDeviceRef ); if ( version ) { printf( "version: %ld, ", version ); } tCFStringRef = IOHIDDevice_GetSerialNumber( inIOHIDDeviceRef ); if ( tCFStringRef ) { verify( CFStringGetCString( tCFStringRef, cstring, sizeof( cstring ), kCFStringEncodingUTF8 ) ); printf( "SerialNumber: \"%s\", ", cstring ); } long country = IOHIDDevice_GetCountryCode( inIOHIDDeviceRef ); if ( country ) { printf( "CountryCode: %ld, ", country ); } long locationID = IOHIDDevice_GetLocationID( inIOHIDDeviceRef ); if ( locationID ) { printf( "locationID: 0x%08lX, ", locationID ); } #if 0 CFArrayRef pairs = IOHIDDevice_GetUsagePairs( inIOHIDDeviceRef ); if ( pairs ) { CFIndex idx, cnt = CFArrayGetCount(pairs); for ( idx = 0; idx < cnt; idx++ ) { const void * pair = CFArrayGetValueAtIndex(pairs, idx); CFShow( pair ); } } #endif long maxInputReportSize = IOHIDDevice_GetMaxInputReportSize( inIOHIDDeviceRef ); if ( maxInputReportSize ) { printf( "MaxInputReportSize: %ld, ", maxInputReportSize ); } long maxOutputReportSize = IOHIDDevice_GetMaxOutputReportSize( inIOHIDDeviceRef ); if ( maxOutputReportSize ) { printf( "MaxOutputReportSize: %ld, ", maxOutputReportSize ); } long maxFeatureReportSize = IOHIDDevice_GetMaxFeatureReportSize( inIOHIDDeviceRef ); if ( maxFeatureReportSize ) { printf( "MaxFeatureReportSize: %ld, ", maxOutputReportSize ); } long reportInterval = IOHIDDevice_GetReportInterval( inIOHIDDeviceRef ); if ( reportInterval ) { printf( "ReportInterval: %ld, ", reportInterval ); } IOHIDQueueRef queueRef = IOHIDDevice_GetQueue( inIOHIDDeviceRef ); if ( queueRef ) { printf( "queue: %p, ", queueRef); } IOHIDTransactionRef transactionRef = IOHIDDevice_GetTransaction( inIOHIDDeviceRef ); if ( transactionRef ) { printf( "transaction: %p, ", transactionRef); } #endif printf( "}\n" ); fflush( stdout ); } // HIDDumpDeviceInfo
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 *)osd_malloc_array (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; }
// Because language preferences are set on a per-user basis, we // must get the preferred languages while set to the current // user, before the Apple Installer switches us to root. // So we get the preferred languages here and write them to a // temporary file to be retrieved by our PostInstall app. static void GetPreferredLanguages() { DIR *dirp; struct dirent *dp; char searchPath[MAXPATHLEN]; char savedWD[MAXPATHLEN]; struct stat sbuf; CFMutableArrayRef supportedLanguages; CFStringRef aLanguage; char shortLanguage[32]; CFArrayRef preferredLanguages; int i, j, k; char * language; char *uscore; FILE *f; getcwd(savedWD, sizeof(savedWD)); system("rm -dfR /tmp/BOINC_payload"); mkdir("/tmp/BOINC_payload", 0777); chdir("/tmp/BOINC_payload"); system("cpio -i < /tmp/expanded_BOINC.pkg/BOINC.pkg/Payload"); chdir(savedWD); // Create an array of all our supported languages supportedLanguages = CFArrayCreateMutable(kCFAllocatorDefault, 100, &kCFTypeArrayCallBacks); aLanguage = CFStringCreateWithCString(NULL, "en", kCFStringEncodingMacRoman); CFArrayAppendValue(supportedLanguages, aLanguage); CFRelease(aLanguage); aLanguage = NULL; dirp = opendir(Catalogs_Dir); if (!dirp) goto cleanup; while (true) { dp = readdir(dirp); if (dp == NULL) break; // End of list if (dp->d_name[0] == '.') continue; // Ignore names beginning with '.' strlcpy(searchPath, Catalogs_Dir, sizeof(searchPath)); strlcat(searchPath, dp->d_name, sizeof(searchPath)); strlcat(searchPath, "/", sizeof(searchPath)); strlcat(searchPath, Catalog_Name, sizeof(searchPath)); strlcat(searchPath, ".mo", sizeof(searchPath)); if (stat(searchPath, &sbuf) != 0) continue; // printf("Adding %s to supportedLanguages array\n", dp->d_name); aLanguage = CFStringCreateWithCString(NULL, dp->d_name, kCFStringEncodingMacRoman); CFArrayAppendValue(supportedLanguages, aLanguage); CFRelease(aLanguage); aLanguage = NULL; // If it has a region code ("it_IT") also try without region code ("it") // TODO: Find a more general solution strlcpy(shortLanguage, dp->d_name, sizeof(shortLanguage)); uscore = strchr(shortLanguage, '_'); if (uscore) { *uscore = '\0'; aLanguage = CFStringCreateWithCString(NULL, shortLanguage, kCFStringEncodingMacRoman); CFArrayAppendValue(supportedLanguages, aLanguage); CFRelease(aLanguage); aLanguage = NULL; } } closedir(dirp); // Write a temp file to tell our PostInstall.app our preferred languages f = fopen("/tmp/BOINC_preferred_languages", "w"); for (i=0; i<MAX_LANGUAGES_TO_TRY; ++i) { preferredLanguages = CFBundleCopyLocalizationsForPreferences(supportedLanguages, NULL ); #if 0 // For testing int c = CFArrayGetCount(preferredLanguages); for (k=0; k<c; ++k) { CFStringRef s = (CFStringRef)CFArrayGetValueAtIndex(preferredLanguages, k); printf("Preferred language %u is %s\n", k, CFStringGetCStringPtr(s, kCFStringEncodingMacRoman)); } #endif for (j=0; j<CFArrayGetCount(preferredLanguages); ++j) { aLanguage = (CFStringRef)CFArrayGetValueAtIndex(preferredLanguages, j); language = (char *)CFStringGetCStringPtr(aLanguage, kCFStringEncodingMacRoman); if (f) { fprintf(f, "%s\n", language); } // Remove all copies of this language from our list of supported languages // so we can get the next preferred language in order of priority for (k=CFArrayGetCount(supportedLanguages)-1; k>=0; --k) { if (CFStringCompare(aLanguage, (CFStringRef)CFArrayGetValueAtIndex(supportedLanguages, k), 0) == kCFCompareEqualTo) { CFArrayRemoveValueAtIndex(supportedLanguages, k); } } // Since the original strings are English, no // further translation is needed for language en. if (!strcmp(language, "en")) { fclose(f); CFRelease(preferredLanguages); preferredLanguages = NULL; goto cleanup; } } CFRelease(preferredLanguages); preferredLanguages = NULL; } fclose(f); cleanup: CFArrayRemoveAllValues(supportedLanguages); CFRelease(supportedLanguages); supportedLanguages = NULL; }
bool macosxSetScreenResolution(QSize resolution, QPoint screenPoint) { CGDirectDisplayID display = displayAtPoint(screenPoint); if (display == kCGNullDirectDisplay) { return false; } #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 1060 if (CGDisplayCopyAllDisplayModes != NULL) { bool ok = false; CGDisplayModeRef currentMainDisplayMode = CGDisplayCopyDisplayMode(display); CFStringRef currentPixelEncoding = CGDisplayModeCopyPixelEncoding(currentMainDisplayMode); CFArrayRef displayModes = CGDisplayCopyAllDisplayModes(display, NULL); for (CFIndex i = 0, c = CFArrayGetCount(displayModes); i < c; i++) { bool isEqual = false; CGDisplayModeRef mode = (CGDisplayModeRef)CFArrayGetValueAtIndex(displayModes, i); CFStringRef pixelEncoding = CGDisplayModeCopyPixelEncoding(mode); if (CFStringCompare(pixelEncoding, currentPixelEncoding, 0) == kCFCompareEqualTo && CGDisplayModeGetWidth(mode) == (size_t)resolution.width() && CGDisplayModeGetHeight(mode) == (size_t)resolution.height()) { isEqual = true; } CFRelease(pixelEncoding); if (isEqual) { CGDisplaySetDisplayMode(display, mode, NULL); ok = true; break; } } CFRelease(currentPixelEncoding); CFRelease(displayModes); return ok; } else #endif { CFDictionaryRef currentMainDisplayMode = CGDisplayCurrentMode(display); int bpp; dictget(currentMainDisplayMode, Int, kCGDisplayBitsPerPixel, &bpp); boolean_t exactMatch = false; CFDictionaryRef bestMode = CGDisplayBestModeForParameters(display, bpp, resolution.width(), resolution.height(), &exactMatch); if (bestMode != NULL) { if (!exactMatch) { qWarning("No optimal display mode for requested parameters."); } CGDisplaySwitchToMode(display, bestMode); return true; } else { qWarning("Bad resolution change: Invalid display."); return false; } } }
int wxFileDialog::ShowModal() { m_paths.Empty(); m_fileNames.Empty(); OSErr err; NavDialogCreationOptions dialogCreateOptions; // set default options ::NavGetDefaultDialogCreationOptions(&dialogCreateOptions); // this was always unset in the old code dialogCreateOptions.optionFlags &= ~kNavSelectDefaultLocation; wxCFStringRef message(m_message, GetFont().GetEncoding()); dialogCreateOptions.windowTitle = message; wxCFStringRef defaultFileName(m_fileName, GetFont().GetEncoding()); dialogCreateOptions.saveFileName = defaultFileName; NavDialogRef dialog; NavObjectFilterUPP navFilterUPP = NULL; OpenUserDataRec myData( this ); dialogCreateOptions.popupExtension = myData.GetMenuItems(); if (HasFdFlag(wxFD_SAVE)) { dialogCreateOptions.optionFlags |= kNavDontAutoTranslate; dialogCreateOptions.optionFlags |= kNavDontAddTranslateItems; if (dialogCreateOptions.popupExtension == NULL) dialogCreateOptions.optionFlags |= kNavNoTypePopup; // The extension is important if ( dialogCreateOptions.popupExtension == NULL || CFArrayGetCount(dialogCreateOptions.popupExtension)<2) dialogCreateOptions.optionFlags |= kNavPreserveSaveFileExtension; if (!(m_windowStyle & wxFD_OVERWRITE_PROMPT)) dialogCreateOptions.optionFlags |= kNavDontConfirmReplacement; err = ::NavCreatePutFileDialog( &dialogCreateOptions, kNavGenericSignature, // Suppresses the 'Default' (top) menu item kNavGenericSignature, sStandardNavEventFilter, &myData, // for defaultLocation &dialog ); } else { // let the user select bundles/programs in dialogs dialogCreateOptions.optionFlags |= kNavSupportPackages; navFilterUPP = NewNavObjectFilterUPP(CrossPlatformFilterCallback); err = ::NavCreateGetFileDialog( &dialogCreateOptions, NULL, // NavTypeListHandle sStandardNavEventFilter, NULL, // NavPreviewUPP navFilterUPP, (void *) &myData, // inClientData &dialog ); } SetupExtraControls(NavDialogGetWindow(dialog)); if (err == noErr) { wxDialog::OSXBeginModalDialog(); err = ::NavDialogRun(dialog); wxDialog::OSXEndModalDialog(); } // clean up filter related data, etc. if (navFilterUPP) ::DisposeNavObjectFilterUPP(navFilterUPP); if (err != noErr) { ::NavDialogDispose(dialog); return wxID_CANCEL; } NavReplyRecord navReply; err = ::NavDialogGetReply(dialog, &navReply); if (err == noErr && navReply.validRecord) { AEKeyword theKeyword; DescType actualType; Size actualSize; FSRef theFSRef; wxString thePath ; long count; m_filterIndex = myData.GetCurrentFilter(); ::AECountItems( &navReply.selection, &count ); for (long i = 1; i <= count; ++i) { err = ::AEGetNthPtr( &(navReply.selection), i, typeFSRef, &theKeyword, &actualType, &theFSRef, sizeof(theFSRef), &actualSize ); if (err != noErr) break; if (HasFdFlag(wxFD_SAVE)) thePath = wxMacFSRefToPath( &theFSRef, navReply.saveFileName ); else thePath = wxMacFSRefToPath( &theFSRef ); if (!thePath) { ::NavDisposeReply(&navReply); ::NavDialogDispose(dialog); return wxID_CANCEL; } m_path = thePath; m_paths.Add(m_path); m_fileName = wxFileNameFromPath(m_path); m_fileNames.Add(m_fileName); } // set these to the first hit m_path = m_paths[0]; m_fileName = wxFileNameFromPath(m_path); m_dir = wxPathOnly(m_path); } ::NavDisposeReply(&navReply); ::NavDialogDispose(dialog); return (err == noErr) ? wxID_OK : wxID_CANCEL; }
bool macosxAppendAvailableScreenResolutions(QList<QSize> &resolutions, QSize minSize, QPoint screenPoint) { CGDirectDisplayID display = displayAtPoint(screenPoint); if (display == kCGNullDirectDisplay) { return false; } #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 1060 bool modern = (CGDisplayCopyAllDisplayModes != NULL); // where 'modern' means >= 10.6 #endif CFArrayRef displayModes; #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 1060 if (modern) { displayModes = CGDisplayCopyAllDisplayModes(display, NULL); } else #endif { displayModes = CGDisplayAvailableModes(display); } #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 1060 CFStringRef currentPixelEncoding = NULL; #endif double currentRefreshRate; int curBPP, curBPS, curSPP; #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 1060 if (modern) { CGDisplayModeRef currentDisplayMode = CGDisplayCopyDisplayMode(display); currentRefreshRate = CGDisplayModeGetRefreshRate(currentDisplayMode); currentPixelEncoding = CGDisplayModeCopyPixelEncoding(currentDisplayMode); CFRelease(currentDisplayMode); } else #endif { CFDictionaryRef currentDisplayMode = CGDisplayCurrentMode(display); dictget(currentDisplayMode, Double, kCGDisplayRefreshRate, ¤tRefreshRate); dictget(currentDisplayMode, Int, kCGDisplayBitsPerPixel, &curBPP); dictget(currentDisplayMode, Int, kCGDisplayBitsPerSample, &curBPS); dictget(currentDisplayMode, Int, kCGDisplaySamplesPerPixel, &curSPP); } for (CFIndex j = 0, c = CFArrayGetCount(displayModes); j < c; j++) { int width, height; double refreshRate; bool pixelEncodingsEqual; #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 1060 if (modern) { CGDisplayModeRef displayMode = (CGDisplayModeRef)CFArrayGetValueAtIndex(displayModes, j); width = (int)CGDisplayModeGetWidth(displayMode); height = (int)CGDisplayModeGetHeight(displayMode); refreshRate = CGDisplayModeGetRefreshRate(displayMode); CFStringRef pixelEncoding = CGDisplayModeCopyPixelEncoding(displayMode); pixelEncodingsEqual = (CFStringCompare(pixelEncoding, currentPixelEncoding, 0) == kCFCompareEqualTo); CFRelease(pixelEncoding); } else #endif { CFDictionaryRef displayMode = (CFDictionaryRef)CFArrayGetValueAtIndex(displayModes, j); dictget(displayMode, Int, kCGDisplayWidth, &width); dictget(displayMode, Int, kCGDisplayHeight, &height); dictget(displayMode, Double, kCGDisplayRefreshRate, &refreshRate); int bpp, bps, spp; dictget(displayMode, Int, kCGDisplayBitsPerPixel, &bpp); dictget(displayMode, Int, kCGDisplayBitsPerSample, &bps); dictget(displayMode, Int, kCGDisplaySamplesPerPixel, &spp); pixelEncodingsEqual = (bpp == curBPP && bps == curBPS && spp == curSPP); } QSize res(width, height); if (!resolutions.contains(res) && width >= minSize.width() && height >= minSize.height() && refreshRate == currentRefreshRate && pixelEncodingsEqual) { resolutions += res; } } #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 1060 if (modern) { CFRelease(currentPixelEncoding); CFRelease(displayModes); } #endif return true; }
void PrintCFTypeInternalFormat(CFTypeRef value, uint32_t depth) { bool foundType = false; CFStringRef valueType = CFCopyTypeIDDescription(CFGetTypeID(value)); CFStringRef dictionaryType = CFCopyTypeIDDescription(CFDictionaryGetTypeID()); if (CFStringCompare(valueType, dictionaryType, 0x0) == kCFCompareEqualTo) { foundType = true; printf("{\n"); PrintCFDictionaryInternalFormatting(value, depth+0x1); PrintDepth(depth,"}\n"); } CFSafeRelease(dictionaryType); CFStringRef booleanType = CFCopyTypeIDDescription(CFBooleanGetTypeID()); if (CFStringCompare(valueType, booleanType, 0x0) == kCFCompareEqualTo) { foundType = true; printf("%s\n",(CFBooleanGetValue(value) ? "True" : "False")); } CFSafeRelease(booleanType); CFStringRef stringType = CFCopyTypeIDDescription(CFStringGetTypeID()); if (CFStringCompare(valueType, stringType, 0x0) == kCFCompareEqualTo) { foundType = true; printf("%s\n",(char*)CFStringGetCStringPtr(value,kCFStringEncodingUTF8)); } CFSafeRelease(stringType); CFStringRef numberType = CFCopyTypeIDDescription(CFNumberGetTypeID()); if (CFStringCompare(valueType, numberType, 0x0) == kCFCompareEqualTo) { foundType = true; CFIndex numberType = CFNumberGetType(value); switch (numberType) { case kCFNumberSInt8Type: { SInt8 number; CFNumberGetValue(value, numberType, &number); printf("%hhd\n",number); break; }; case kCFNumberSInt16Type: { SInt16 number; CFNumberGetValue(value, numberType, &number); printf("%hd\n",number); break; }; case kCFNumberSInt32Type: { SInt32 number; CFNumberGetValue(value, numberType, &number); printf("%d\n",(int32_t)number); break; }; case kCFNumberSInt64Type: { SInt64 number; CFNumberGetValue(value, numberType, &number); printf("%lld\n",number); break; }; case kCFNumberFloat32Type: { Float32 number; CFNumberGetValue(value, numberType, &number); printf("%.f\n",number); break; }; case kCFNumberFloat64Type: { Float64 number; CFNumberGetValue(value, numberType, &number); printf("%.f\n",number); break; }; case kCFNumberCharType: { char number; CFNumberGetValue(value, numberType, &number); printf("%c\n",number); break; }; case kCFNumberShortType: { short number; CFNumberGetValue(value, numberType, &number); printf("%hd\n",number); break; }; case kCFNumberIntType: { int number; CFNumberGetValue(value, numberType, &number); printf("%d\n",number); break; }; case kCFNumberLongType: { long number; CFNumberGetValue(value, numberType, &number); printf("%ld\n",number); break; }; case kCFNumberLongLongType: { long long number; CFNumberGetValue(value, numberType, &number); printf("%qd\n",number); break; }; case kCFNumberFloatType: { float number; CFNumberGetValue(value, numberType, &number); printf("%.f\n",number); break; }; case kCFNumberDoubleType: { double number; CFNumberGetValue(value, numberType, &number); printf("%.f\n",number); break; }; case kCFNumberCFIndexType: { CFIndex number; CFNumberGetValue(value, numberType, &number); printf("%ld\n",number); break; }; case kCFNumberNSIntegerType: { NSInteger number; CFNumberGetValue(value, numberType, &number); printf("%ld\n",(long)number); break; }; case kCFNumberCGFloatType: { CGFloat number; CFNumberGetValue(value, numberType, &number); printf("%.f\n",number); break; }; default: { break; }; } } CFSafeRelease(numberType); CFStringRef arrayType = CFCopyTypeIDDescription(CFArrayGetTypeID()); if (CFStringCompare(valueType, arrayType, 0x0) == kCFCompareEqualTo) { foundType = true; CFIndex count = CFArrayGetCount(value); printf("[\n"); for (CFIndex i = 0x0; i < count; i++) { CFTypeRef item = CFArrayGetValueAtIndex(value, i); PrintDepth(depth+0x1,""); PrintCFTypeInternalFormat(item, depth+0x1); } PrintDepth(depth,"]\n"); } CFSafeRelease(arrayType); if (!foundType) { CFStringRef description = CFCopyDescription(value); printf("%s\n",(char*)CFStringGetCStringPtr(description,kCFStringEncodingUTF8)); CFSafeRelease(description); } CFSafeRelease(valueType); }
void InbandTextTrackPrivateAVF::processCue(CFArrayRef attributedStrings, double time) { if (!client()) return; LOG(Media, "InbandTextTrackPrivateAVF::processCue - %li cues at time %.2f\n", attributedStrings ? CFArrayGetCount(attributedStrings) : 0, time); if (m_pendingCueStatus != None) { // Cues do not have an explicit duration, they are displayed until the next "cue" (which might be empty) is emitted. m_currentCueEndTime = time; if (m_currentCueEndTime >= m_currentCueStartTime) { for (size_t i = 0; i < m_cues.size(); i++) { GenericCueData* cueData = m_cues[i].get(); if (m_pendingCueStatus == Valid) { cueData->setEndTime(m_currentCueEndTime); cueData->setStatus(GenericCueData::Complete); LOG(Media, "InbandTextTrackPrivateAVF::processCue(%p) - updating cue: start=%.2f, end=%.2f, content=\"%s\"", this, cueData->startTime(), m_currentCueEndTime, cueData->content().utf8().data()); client()->updateGenericCue(this, cueData); } else { // We have to assume that the implicit duration is invalid for cues delivered during a seek because the AVF decode pipeline may not // see every cue, so DO NOT update cue duration while seeking. LOG(Media, "InbandTextTrackPrivateAVF::processCue(%p) - ignoring cue delivered during seek: start=%.2f, end=%.2f, content=\"%s\"", this, cueData->startTime(), m_currentCueEndTime, cueData->content().utf8().data()); } } } else LOG(Media, "InbandTextTrackPrivateAVF::processCue negative length cue(s) ignored: start=%.2f, end=%.2f\n", m_currentCueStartTime, m_currentCueEndTime); resetCueValues(); } if (!attributedStrings) return; CFIndex count = CFArrayGetCount(attributedStrings); if (!count) return; for (CFIndex i = 0; i < count; i++) { CFAttributedStringRef attributedString = static_cast<CFAttributedStringRef>(CFArrayGetValueAtIndex(attributedStrings, i)); if (!attributedString || !CFAttributedStringGetLength(attributedString)) continue; RefPtr<GenericCueData> cueData = GenericCueData::create(); processCueAttributes(attributedString, cueData.get()); if (!cueData->content().length()) continue; m_cues.append(cueData); m_currentCueStartTime = time; cueData->setStartTime(m_currentCueStartTime); cueData->setEndTime(numeric_limits<double>::infinity()); // AVFoundation cue "position" is to the center of the text so adjust relative to the edge because we will use it to // set CSS "left". if (cueData->position() >= 0 && cueData->size() > 0) cueData->setPosition(cueData->position() - cueData->size() / 2); LOG(Media, "InbandTextTrackPrivateAVF::processCue(%p) - adding cue for time = %.2f, position = %.2f, line = %.2f", this, cueData->startTime(), cueData->position(), cueData->line()); cueData->setStatus(GenericCueData::Partial); client()->addGenericCue(this, cueData.release()); m_pendingCueStatus = seeking() ? DeliveredDuringSeek : Valid; } }
void configSet(CFMutableArrayRef config, CFStringRef key, CFStringRef value) { CFMutableStringRef pref; CFIndex configLen = CFArrayGetCount(config); CFIndex i; CFIndex n; CFMutableStringRef newValue; CFRange range; CFStringRef specialChars = CFSTR(" \"'$!|\\<>`{}[]"); boolean_t mustQuote = FALSE; /* create search prefix */ pref = CFStringCreateMutableCopy(NULL, 0, key); CFStringAppend(pref, CFSTR("=")); /* * create new / replacement value * * Note: Since the configuration file may be processed by a * shell script we need to ensure that, if needed, the * string is properly quoted. */ newValue = CFStringCreateMutableCopy(NULL, 0, value); n = CFStringGetLength(specialChars); for (i = 0; i < n; i++) { CFStringRef specialChar; specialChar = CFStringCreateWithSubstring(NULL, specialChars, CFRangeMake(i, 1)); range = CFStringFind(newValue, specialChar, 0); CFRelease(specialChar); if (range.location != kCFNotFound) { /* this string has at least one special character */ mustQuote = TRUE; break; } } if (mustQuote) { CFStringRef charsToQuote = CFSTR("\\\"$`"); /* * in addition to quoting the entire string we also need to escape the * space " " and backslash "\" characters */ n = CFStringGetLength(charsToQuote); for (i = 0; i < n; i++) { CFStringRef quoteChar; CFArrayRef matches; quoteChar = CFStringCreateWithSubstring(NULL, charsToQuote, CFRangeMake(i, 1)); range = CFRangeMake(0, CFStringGetLength(newValue)); matches = CFStringCreateArrayWithFindResults(NULL, newValue, quoteChar, range, 0); CFRelease(quoteChar); if (matches) { CFIndex j = CFArrayGetCount(matches); while (--j >= 0) { const CFRange *range; range = CFArrayGetValueAtIndex(matches, j); CFStringInsert(newValue, range->location, CFSTR("\\")); } CFRelease(matches); } } CFStringInsert(newValue, 0, CFSTR("\"")); CFStringAppend(newValue, CFSTR("\"")); } /* locate existing key */ for (i = 0; i < configLen; i++) { if (CFStringHasPrefix(CFArrayGetValueAtIndex(config, i), pref)) { break; } } CFStringAppend(pref, newValue); CFRelease(newValue); if (i < configLen) { /* if replacing an existing entry */ CFArraySetValueAtIndex(config, i, pref); } else { /* * if new entry, insert it just prior to the last (emtpy) * array element. */ CFArrayInsertValueAtIndex(config, configLen-1, pref); } CFRelease(pref); return; }
/* * SecCmsSignedDataEncodeAfterData - do all the necessary things to a SignedData * after all the encapsulated data was passed through the encoder. * * In detail: * - create the signatures in all the SignerInfos * * Please note that nothing is done to the Certificates and CRLs in the message - this * is entirely the responsibility of our callers. */ OSStatus SecCmsSignedDataEncodeAfterData(SecCmsSignedDataRef sigd) { SecCmsSignerInfoRef *signerinfos, signerinfo; SecCmsContentInfoRef cinfo; SECOidTag digestalgtag; OSStatus ret = SECFailure; OSStatus rv; CSSM_DATA_PTR contentType; int certcount; int i, ci, n, rci, si; PLArenaPool *poolp; CFArrayRef certlist; extern const SecAsn1Template SecCmsSignerInfoTemplate[]; poolp = sigd->cmsg->poolp; cinfo = &(sigd->contentInfo); /* did we have digest calculation going on? */ if (cinfo->digcx) { rv = SecCmsDigestContextFinishMultiple(cinfo->digcx, (SecArenaPoolRef)poolp, &(sigd->digests)); if (rv != SECSuccess) goto loser; /* error has been set by SecCmsDigestContextFinishMultiple */ cinfo->digcx = NULL; } signerinfos = sigd->signerInfos; certcount = 0; /* prepare all the SignerInfos (there may be none) */ for (i=0; i < SecCmsSignedDataSignerInfoCount(sigd); i++) { signerinfo = SecCmsSignedDataGetSignerInfo(sigd, i); /* find correct digest for this signerinfo */ digestalgtag = SecCmsSignerInfoGetDigestAlgTag(signerinfo); n = SecCmsAlgArrayGetIndexByAlgTag(sigd->digestAlgorithms, digestalgtag); if (n < 0 || sigd->digests == NULL || sigd->digests[n] == NULL) { /* oops - digest not found */ PORT_SetError(SEC_ERROR_DIGEST_NOT_FOUND); goto loser; } /* XXX if our content is anything else but data, we need to force the * presence of signed attributes (RFC2630 5.3 "signedAttributes is a * collection...") */ /* pass contentType here as we want a contentType attribute */ if ((contentType = SecCmsContentInfoGetContentTypeOID(cinfo)) == NULL) goto loser; /* sign the thing */ rv = SecCmsSignerInfoSign(signerinfo, sigd->digests[n], contentType); if (rv != SECSuccess) goto loser; /* while we're at it, count number of certs in certLists */ certlist = SecCmsSignerInfoGetCertList(signerinfo); if (certlist) certcount += CFArrayGetCount(certlist); } /* Now we can get a timestamp, since we have all the digests */ // We force the setting of a callback, since this is the most usual case if (!sigd->cmsg->tsaCallback) SecCmsMessageSetTSACallback(sigd->cmsg, (SecCmsTSACallback)SecCmsTSADefaultCallback); if (sigd->cmsg->tsaCallback && sigd->cmsg->tsaContext) { CSSM_DATA tsaResponse = {0,}; SecAsn1TSAMessageImprint messageImprint = {{{0},},{0,}}; // <rdar://problem/11073466> Add nonce support for timestamping client uint64_t nonce = 0; require_noerr(getRandomNonce(&nonce), tsxit); dprintf("SecCmsSignedDataSignerInfoCount: %d\n", SecCmsSignedDataSignerInfoCount(sigd)); // Calculate hash of encDigest and put in messageImprint.hashedMessage SecCmsSignerInfoRef signerinfo = SecCmsSignedDataGetSignerInfo(sigd, 0); // NB - assume 1 signer only! CSSM_DATA *encDigest = SecCmsSignerInfoGetEncDigest(signerinfo); require_noerr(createTSAMessageImprint(sigd, encDigest, &messageImprint), tsxit); // Callback to fire up XPC service to talk to TimeStamping server, etc. require_noerr(rv =(*sigd->cmsg->tsaCallback)(sigd->cmsg->tsaContext, &messageImprint, nonce, &tsaResponse), tsxit); require_noerr(rv = validateTSAResponseAndAddTimeStamp(signerinfo, &tsaResponse, nonce), tsxit); /* It is likely that every occurrence of "goto loser" in this file should also do a PORT_SetError. Since it is not clear what might depend on this behavior, we just do this in the timestamping case. */ tsxit: if (rv) { dprintf("Original timestamp error: %d\n", (int)rv); rv = remapTimestampError(rv); PORT_SetError(rv); goto loser; } } /* this is a SET OF, so we need to sort them guys */ rv = SecCmsArraySortByDER((void **)signerinfos, SecCmsSignerInfoTemplate, NULL); if (rv != SECSuccess) goto loser; /* * now prepare certs & crls */ /* count the rest of the certs */ if (sigd->certs != NULL) certcount += CFArrayGetCount(sigd->certs); if (certcount == 0) { sigd->rawCerts = NULL; } else { /* * Combine all of the certs and cert chains into rawcerts. * Note: certcount is an upper bound; we may not need that many slots * but we will allocate anyway to avoid having to do another pass. * (The temporary space saving is not worth it.) * * XXX ARGH - this NEEDS to be fixed. need to come up with a decent * SetOfDERcertficates implementation */ sigd->rawCerts = (CSSM_DATA_PTR *)PORT_ArenaAlloc(poolp, (certcount + 1) * sizeof(CSSM_DATA_PTR)); if (sigd->rawCerts == NULL) return SECFailure; /* * XXX Want to check for duplicates and not add *any* cert that is * already in the set. This will be more important when we start * dealing with larger sets of certs, dual-key certs (signing and * encryption), etc. For the time being we can slide by... * * XXX ARGH - this NEEDS to be fixed. need to come up with a decent * SetOfDERcertficates implementation */ rci = 0; if (signerinfos != NULL) { for (si = 0; signerinfos[si] != NULL; si++) { signerinfo = signerinfos[si]; for (ci = 0; ci < CFArrayGetCount(signerinfo->certList); ci++) { sigd->rawCerts[rci] = PORT_ArenaZAlloc(poolp, sizeof(CSSM_DATA)); SecCertificateRef cert = (SecCertificateRef)CFArrayGetValueAtIndex(signerinfo->certList, ci); SecCertificateGetData(cert, sigd->rawCerts[rci++]); } } } if (sigd->certs != NULL) { for (ci = 0; ci < CFArrayGetCount(sigd->certs); ci++) { sigd->rawCerts[rci] = PORT_ArenaZAlloc(poolp, sizeof(CSSM_DATA)); SecCertificateRef cert = (SecCertificateRef)CFArrayGetValueAtIndex(sigd->certs, ci); SecCertificateGetData(cert, sigd->rawCerts[rci++]); } } sigd->rawCerts[rci] = NULL; /* this is a SET OF, so we need to sort them guys - we have the DER already, though */ SecCmsArraySort((void **)sigd->rawCerts, SecCmsUtilDERCompare, NULL, NULL); } ret = SECSuccess; loser: dprintf("SecCmsSignedDataEncodeAfterData: ret: %ld, rv: %ld\n", (long)ret, (long)rv); return ret; }
__private_extern__ CFArrayRef _CFPreferencesCreateDomainList(CFStringRef userName, CFStringRef hostName) { CFAllocatorRef prefAlloc = __CFPreferencesAllocator(); CFArrayRef domains; CFMutableArrayRef marray; CFStringRef *cachedDomainKeys; CFPreferencesDomainRef *cachedDomains; SInt32 idx, cnt; CFStringRef suffix; UInt32 suffixLen; CFURLRef prefDir = _preferencesDirectoryForUserHost(userName, hostName); if (!prefDir) { return NULL; } if (hostName == kCFPreferencesAnyHost) { suffix = CFStringCreateWithCString(prefAlloc, ".plist", kCFStringEncodingASCII); } else if (hostName == kCFPreferencesCurrentHost) { CFStringRef hostID = _CFPreferencesGetByHostIdentifierString(); suffix = CFStringCreateWithFormat(prefAlloc, NULL, CFSTR(".%@.plist"), hostID); } else { suffix = CFStringCreateWithFormat(prefAlloc, NULL, CFSTR(".%@.plist"), hostName); // sketchy - this allows someone to create a domain list for an arbitrary hostname. } suffixLen = CFStringGetLength(suffix); domains = (CFArrayRef)CFURLCreatePropertyFromResource(prefAlloc, prefDir, kCFURLFileDirectoryContents, NULL); CFRelease(prefDir); if (domains){ marray = CFArrayCreateMutableCopy(prefAlloc, 0, domains); CFRelease(domains); } else { marray = CFArrayCreateMutable(prefAlloc, 0, & kCFTypeArrayCallBacks); } for (idx = CFArrayGetCount(marray)-1; idx >= 0; idx --) { CFURLRef url = (CFURLRef)CFArrayGetValueAtIndex(marray, idx); CFStringRef string = CFURLCopyFileSystemPath(url, kCFURLPOSIXPathStyle); if (!CFStringHasSuffix(string, suffix)) { CFArrayRemoveValueAtIndex(marray, idx); } else { CFStringRef dom = CFStringCreateWithSubstring(prefAlloc, string, CFRangeMake(0, CFStringGetLength(string) - suffixLen)); if (CFEqual(dom, CFSTR(".GlobalPreferences"))) { CFArraySetValueAtIndex(marray, idx, kCFPreferencesAnyApplication); } else { CFArraySetValueAtIndex(marray, idx, dom); } CFRelease(dom); } CFRelease(string); } CFRelease(suffix); // Now add any domains added in the cache; delete any that have been deleted in the cache __CFSpinLock(&domainCacheLock); if (!domainCache) { __CFSpinUnlock(&domainCacheLock); return marray; } cnt = CFDictionaryGetCount(domainCache); cachedDomainKeys = (CFStringRef *)CFAllocatorAllocate(prefAlloc, 2 * cnt * sizeof(CFStringRef), 0); cachedDomains = (CFPreferencesDomainRef *)(cachedDomainKeys + cnt); CFDictionaryGetKeysAndValues(domainCache, (const void **)cachedDomainKeys, (const void **)cachedDomains); __CFSpinUnlock(&domainCacheLock); suffix = _CFPreferencesCachePrefixForUserHost(userName, hostName); suffixLen = CFStringGetLength(suffix); for (idx = 0; idx < cnt; idx ++) { CFStringRef domainKey = cachedDomainKeys[idx]; CFPreferencesDomainRef domain = cachedDomains[idx]; CFStringRef domainName; CFIndex keyCount = 0; if (!CFStringHasPrefix(domainKey, suffix)) continue; domainName = CFStringCreateWithSubstring(prefAlloc, domainKey, CFRangeMake(suffixLen, CFStringGetLength(domainKey) - suffixLen)); if (CFEqual(domainName, CFSTR("*"))) { CFRelease(domainName); domainName = (CFStringRef)CFRetain(kCFPreferencesAnyApplication); } else if (CFEqual(domainName, kCFPreferencesCurrentApplication)) { CFRelease(domainName); domainName = (CFStringRef)CFRetain(_CFProcessNameString()); } CFDictionaryRef d = _CFPreferencesDomainDeepCopyDictionary(domain); keyCount = d ? CFDictionaryGetCount(d) : 0; if (keyCount) CFRelease(d); if (keyCount == 0) { // Domain was deleted SInt32 firstIndexOfValue = CFArrayGetFirstIndexOfValue(marray, CFRangeMake(0, CFArrayGetCount(marray)), domainName); if (0 <= firstIndexOfValue) { CFArrayRemoveValueAtIndex(marray, firstIndexOfValue); } } else if (!CFArrayContainsValue(marray, CFRangeMake(0, CFArrayGetCount(marray)), domainName)) { CFArrayAppendValue(marray, domainName); } CFRelease(domainName); } CFRelease(suffix); CFAllocatorDeallocate(prefAlloc, cachedDomainKeys); return marray; }
// get the first element of device passed in as parameter // returns NULL if no list exists or device does not exists or is NULL IOHIDElementRef HIDGetFirstDeviceElement( IOHIDDeviceRef inIOHIDDeviceRef, HIDElementTypeMask typeMask ) { IOHIDElementRef result = NULL; if ( inIOHIDDeviceRef ) { assert( IOHIDDeviceGetTypeID() == CFGetTypeID( inIOHIDDeviceRef ) ); gElementCFArrayRef = IOHIDDeviceCopyMatchingElements( inIOHIDDeviceRef, NULL, kIOHIDOptionsTypeNone ); if ( gElementCFArrayRef ) { CFIndex idx, cnt = CFArrayGetCount( gElementCFArrayRef ); for ( idx = 0; idx < cnt; idx++ ) { IOHIDElementRef tIOHIDElementRef = ( IOHIDElementRef ) CFArrayGetValueAtIndex( gElementCFArrayRef, idx ); if ( !tIOHIDElementRef ) { continue; } IOHIDElementType type = IOHIDElementGetType( tIOHIDElementRef ); switch ( type ) { case kIOHIDElementTypeInput_Misc: case kIOHIDElementTypeInput_Button: case kIOHIDElementTypeInput_Axis: case kIOHIDElementTypeInput_ScanCodes: { if ( typeMask & kHIDElementTypeInput ) { result = tIOHIDElementRef; } break; } case kIOHIDElementTypeOutput: { if ( typeMask & kHIDElementTypeOutput ) { result = tIOHIDElementRef; } break; } case kIOHIDElementTypeFeature: { if ( typeMask & kHIDElementTypeFeature ) { result = tIOHIDElementRef; } break; } case kIOHIDElementTypeCollection: { if ( typeMask & kHIDElementTypeCollection ) { result = tIOHIDElementRef; } break; } } // switch ( type ) if ( result ) { break; // DONE! } } // next idx CFRelease( gElementCFArrayRef ); gElementCFArrayRef = NULL; } // if ( gElementCFArrayRef ) } // if ( inIOHIDDeviceRef ) return result; } /* HIDGetFirstDeviceElement */
char * _mongoc_secure_transport_RFC2253_from_cert (SecCertificateRef cert) { CFTypeRef value; bson_string_t *retval; CFTypeRef subject_name; CFDictionaryRef cert_dict; cert_dict = SecCertificateCopyValues (cert, NULL, NULL); if (!cert_dict) { return NULL; } subject_name = CFDictionaryGetValue (cert_dict, kSecOIDX509V1SubjectName); if (!subject_name) { CFRelease (cert_dict); return NULL; } subject_name = CFDictionaryGetValue (subject_name, kSecPropertyKeyValue); if (!subject_name) { CFRelease (cert_dict); return NULL; } retval = bson_string_new (""); ; value = _mongoc_secure_transport_dict_get (subject_name, kSecOIDCountryName); _bson_append_cftyperef (retval, "C=", value); value = _mongoc_secure_transport_dict_get (subject_name, kSecOIDStateProvinceName); _bson_append_cftyperef (retval, ",ST=", value); value = _mongoc_secure_transport_dict_get (subject_name, kSecOIDLocalityName); _bson_append_cftyperef (retval, ",L=", value); value = _mongoc_secure_transport_dict_get (subject_name, kSecOIDOrganizationName); _bson_append_cftyperef (retval, ",O=", value); value = _mongoc_secure_transport_dict_get (subject_name, kSecOIDOrganizationalUnitName); if (value) { /* Can be either one unit name, or array of unit names */ if (CFGetTypeID (value) == CFStringGetTypeID ()) { _bson_append_cftyperef (retval, ",OU=", value); } else if (CFGetTypeID (value) == CFArrayGetTypeID ()) { CFIndex len = CFArrayGetCount (value); if (len > 0) { _bson_append_cftyperef ( retval, ",OU=", CFArrayGetValueAtIndex (value, 0)); } if (len > 1) { _bson_append_cftyperef ( retval, ",", CFArrayGetValueAtIndex (value, 1)); } if (len > 2) { _bson_append_cftyperef ( retval, ",", CFArrayGetValueAtIndex (value, 2)); } } } value = _mongoc_secure_transport_dict_get (subject_name, kSecOIDCommonName); _bson_append_cftyperef (retval, ",CN=", value); value = _mongoc_secure_transport_dict_get (subject_name, kSecOIDStreetAddress); _bson_append_cftyperef (retval, ",STREET", value); CFRelease (cert_dict); return bson_string_free (retval, false); }
// get next element of given device in list given current element as parameter // will walk down each collection then to next element or collection (depthwise traverse) // returns NULL if end of list // uses mask of HIDElementTypeMask to restrict element found // use kHIDElementTypeIO to get previous HIDGetNextDeviceElement functionality IOHIDElementRef HIDGetNextDeviceElement( IOHIDElementRef inIOHIDElementRef, HIDElementTypeMask typeMask ) { IOHIDElementRef result = NULL; if ( inIOHIDElementRef ) { assert( IOHIDElementGetTypeID() == CFGetTypeID( inIOHIDElementRef ) ); IOHIDDeviceRef tIOHIDDeviceRef = IOHIDElementGetDevice( inIOHIDElementRef ); if ( tIOHIDDeviceRef ) { Boolean found = FALSE; gElementCFArrayRef = IOHIDDeviceCopyMatchingElements( tIOHIDDeviceRef, NULL, kIOHIDOptionsTypeNone ); if ( gElementCFArrayRef ) { CFIndex idx, cnt = CFArrayGetCount( gElementCFArrayRef ); for ( idx = 0; idx < cnt; idx++ ) { IOHIDElementRef tIOHIDElementRef = ( IOHIDElementRef ) CFArrayGetValueAtIndex( gElementCFArrayRef, idx ); if ( !tIOHIDElementRef ) { continue; } if ( !found ) { if ( inIOHIDElementRef == tIOHIDElementRef ) { found = TRUE; } continue; // next element } else { // we've found the current element; now find the next one of the right type IOHIDElementType type = IOHIDElementGetType( tIOHIDElementRef ); switch ( type ) { case kIOHIDElementTypeInput_Misc: case kIOHIDElementTypeInput_Button: case kIOHIDElementTypeInput_Axis: case kIOHIDElementTypeInput_ScanCodes: { if ( typeMask & kHIDElementTypeInput ) { result = tIOHIDElementRef; } break; } case kIOHIDElementTypeOutput: { if ( typeMask & kHIDElementTypeOutput ) { result = tIOHIDElementRef; } break; } case kIOHIDElementTypeFeature: { if ( typeMask & kHIDElementTypeFeature ) { result = tIOHIDElementRef; } break; } case kIOHIDElementTypeCollection: { if ( typeMask & kHIDElementTypeCollection ) { result = tIOHIDElementRef; } break; } } // switch ( type ) if ( result ) { break; // DONE! } } // if ( !found ) } // next idx CFRelease( gElementCFArrayRef ); gElementCFArrayRef = NULL; } // if ( gElementCFArrayRef ) } // if ( inIOHIDDeviceRef ) } // if ( inIOHIDElementRef ) return result; } /* HIDGetNextDeviceElement */
static int keychain_iter_start(hx509_context context, hx509_certs certs, void *data, void **cursor) { struct ks_keychain *ctx = data; struct iter *iter; iter = calloc(1, sizeof(*iter)); if (iter == NULL) { hx509_set_error_string(context, 0, ENOMEM, "out of memory"); return ENOMEM; } if (ctx->anchors) { CFArrayRef anchors; int ret; int i; ret = hx509_certs_init(context, "MEMORY:ks-file-create", 0, NULL, &iter->certs); if (ret) { free(iter); return ret; } ret = SecTrustCopyAnchorCertificates(&anchors); if (ret != 0) { hx509_certs_free(&iter->certs); free(iter); hx509_set_error_string(context, 0, ENOMEM, "Can't get trust anchors from Keychain"); return ENOMEM; } for (i = 0; i < CFArrayGetCount(anchors); i++) { SecCertificateRef cr; hx509_cert cert; CSSM_DATA cssm; cr = (SecCertificateRef)CFArrayGetValueAtIndex(anchors, i); SecCertificateGetData(cr, &cssm); ret = hx509_cert_init_data(context, cssm.Data, cssm.Length, &cert); if (ret) continue; ret = hx509_certs_add(context, iter->certs, cert); hx509_cert_free(cert); } CFRelease(anchors); } if (iter->certs) { int ret; ret = hx509_certs_start_seq(context, iter->certs, &iter->cursor); if (ret) { hx509_certs_free(&iter->certs); free(iter); return ret; } } else { OSStatus ret; ret = SecKeychainSearchCreateFromAttributes(ctx->keychain, kSecCertificateItemClass, NULL, &iter->searchRef); if (ret) { free(iter); hx509_set_error_string(context, 0, ret, "Failed to start search for attributes"); return ENOMEM; } } *cursor = iter; return 0; }
/* Call AddHIDElement() on all elements in an array of IOHIDElementRefs */ static void AddHIDElements(CFArrayRef array, recDevice *pDevice) { const CFRange range = { 0, CFArrayGetCount(array) }; CFArrayApplyFunction(array, range, AddHIDElement, pDevice); }