/* * Display a Trust Settings array as obtained from * SecTrustSettingsCopyTrustSettings(). */ static int displayTrustSettings( CFArrayRef trustSettings) { /* must always be there though it may be empty */ if(trustSettings == NULL) { fprintf(stderr, "***displayTrustSettings: missing trust settings array"); return -1; } if(CFGetTypeID(trustSettings) != CFArrayGetTypeID()) { fprintf(stderr, "***displayTrustSettings: malformed trust settings array"); return -1; } int ourRtn = 0; CFIndex numUseConstraints = CFArrayGetCount(trustSettings); indentIncr(); indent(); printf("Number of trust settings : %ld\n", (long)numUseConstraints); OSStatus ortn; SecPolicyRef certPolicy; SecTrustedApplicationRef certApp; CFDictionaryRef ucDict; CFStringRef policyStr; CFNumberRef cfNum; CFIndex ucDex; /* grind thru the trust settings dictionaries */ for(ucDex=0; ucDex<numUseConstraints; ucDex++) { indent(); printf("Trust Setting %ld:\n", (long)ucDex); indentIncr(); ucDict = (CFDictionaryRef)CFArrayGetValueAtIndex(trustSettings, ucDex); if(CFGetTypeID(ucDict) != CFDictionaryGetTypeID()) { fprintf(stderr, "***displayTrustSettings: malformed usage constraints dictionary"); ourRtn = -1; goto nextAp; } /* policy - optional */ certPolicy = (SecPolicyRef)CFDictionaryGetValue(ucDict, kSecTrustSettingsPolicy); if(certPolicy != NULL) { if(CFGetTypeID(certPolicy) != SecPolicyGetTypeID()) { fprintf(stderr, "***displayTrustSettings: malformed certPolicy"); ourRtn = -1; goto nextAp; } CSSM_OID policyOid; ortn = SecPolicyGetOID(certPolicy, &policyOid); if(ortn) { cssmPerror("SecPolicyGetOID", ortn); ourRtn = -1; goto nextAp; } indent(); printf("Policy OID : %s\n", oidToOidString(&policyOid)); } /* app - optional */ certApp = (SecTrustedApplicationRef)CFDictionaryGetValue(ucDict, kSecTrustSettingsApplication); if(certApp != NULL) { if(CFGetTypeID(certApp) != SecTrustedApplicationGetTypeID()) { fprintf(stderr, "***displayTrustSettings: malformed certApp"); ourRtn = -1; goto nextAp; } CFDataRef appPath = NULL; ortn = SecTrustedApplicationCopyData(certApp, &appPath); if(ortn) { cssmPerror("SecTrustedApplicationCopyData", ortn); ourRtn = -1; goto nextAp; } indent(); printf("Application : %s", CFDataGetBytePtr(appPath)); printf("\n"); CFRelease(appPath); } /* policy string */ policyStr = (CFStringRef)CFDictionaryGetValue(ucDict, kSecTrustSettingsPolicyString); if(policyStr != NULL) { if(CFGetTypeID(policyStr) != CFStringGetTypeID()) { fprintf(stderr, "***displayTrustSettings: malformed policyStr"); ourRtn = -1; goto nextAp; } indent(); printf("Policy String : "); printCfStr(policyStr); printf("\n"); } /* Allowed error */ cfNum = (CFNumberRef)CFDictionaryGetValue(ucDict, kSecTrustSettingsAllowedError); if(cfNum != NULL) { if(CFGetTypeID(cfNum) != CFNumberGetTypeID()) { fprintf(stderr, "***displayTrustSettings: malformed allowedError"); ourRtn = -1; goto nextAp; } indent(); printf("Allowed Error : "); printCssmErr(cfNum); printf("\n"); } /* ResultType */ cfNum = (CFNumberRef)CFDictionaryGetValue(ucDict, kSecTrustSettingsResult); if(cfNum != NULL) { if(CFGetTypeID(cfNum) != CFNumberGetTypeID()) { fprintf(stderr, "***displayTrustSettings: malformed ResultType"); ourRtn = -1; goto nextAp; } indent(); printf("Result Type : "); printResultType(cfNum); printf("\n"); } /* key usage */ cfNum = (CFNumberRef)CFDictionaryGetValue(ucDict, kSecTrustSettingsKeyUsage); if(cfNum != NULL) { if(CFGetTypeID(cfNum) != CFNumberGetTypeID()) { fprintf(stderr, "***displayTrustSettings: malformed keyUsage"); ourRtn = -1; goto nextAp; } indent(); printf("Key Usage : "); printKeyUsage(cfNum); printf("\n"); } nextAp: indentDecr(); } indentDecr(); return ourRtn; }
/*********************************************************************** * copy_display_modes * * Wrapper around CGDisplayCopyAllDisplayModes() to include additional * modes on Retina-capable systems, but filter those which would confuse * Windows apps (basically duplicates at different DPIs). * * For example, some Retina Macs support a 1920x1200 mode, but it's not * returned from CGDisplayCopyAllDisplayModes() without special options. * This is especially bad if that's the user's default mode, since then * no "available" mode matches the initial settings. */ static CFArrayRef copy_display_modes(CGDirectDisplayID display) { CFArrayRef modes = NULL; #if defined(MAC_OS_X_VERSION_10_8) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_8 if (&kCGDisplayShowDuplicateLowResolutionModes != NULL && CGDisplayModeGetPixelWidth != NULL && CGDisplayModeGetPixelHeight != NULL) { CFDictionaryRef options; CFMutableDictionaryRef modes_by_size; CFIndex i, count; CGDisplayModeRef* mode_array; options = CFDictionaryCreate(NULL, (const void**)&kCGDisplayShowDuplicateLowResolutionModes, (const void**)&kCFBooleanTrue, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); modes = CGDisplayCopyAllDisplayModes(display, options); if (options) CFRelease(options); if (!modes) return NULL; modes_by_size = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); count = CFArrayGetCount(modes); for (i = 0; i < count; i++) { BOOL better = TRUE; CGDisplayModeRef new_mode = (CGDisplayModeRef)CFArrayGetValueAtIndex(modes, i); uint32_t new_flags = CGDisplayModeGetIOFlags(new_mode); CFStringRef pixel_encoding; size_t width_points; size_t height_points; CFDictionaryRef key; CGDisplayModeRef old_mode; if (!(new_flags & kDisplayModeDefaultFlag) && (pixel_encoding = CGDisplayModeCopyPixelEncoding(new_mode))) { BOOL bpp30 = CFEqual(pixel_encoding, CFSTR(kIO30BitDirectPixels)); CFRelease(pixel_encoding); if (bpp30) { /* This is an odd pixel encoding. It seems it's only returned when using kCGDisplayShowDuplicateLowResolutionModes. It's 32bpp in terms of the actual raster layout, but it's 10 bits per component. I think that no Windows program is likely to need it and they will probably be confused by it. Skip it. */ continue; } } width_points = CGDisplayModeGetWidth(new_mode); height_points = CGDisplayModeGetHeight(new_mode); key = create_mode_dict(new_mode); old_mode = (CGDisplayModeRef)CFDictionaryGetValue(modes_by_size, key); if (old_mode) { uint32_t old_flags = CGDisplayModeGetIOFlags(old_mode); /* If a given mode is the user's default, then always list it in preference to any similar modes that may exist. */ if ((new_flags & kDisplayModeDefaultFlag) && !(old_flags & kDisplayModeDefaultFlag)) better = TRUE; else if (!(new_flags & kDisplayModeDefaultFlag) && (old_flags & kDisplayModeDefaultFlag)) better = FALSE; else { /* Otherwise, prefer a mode whose pixel size equals its point size over one which is scaled. */ size_t new_width_pixels = CGDisplayModeGetPixelWidth(new_mode); size_t new_height_pixels = CGDisplayModeGetPixelHeight(new_mode); size_t old_width_pixels = CGDisplayModeGetPixelWidth(old_mode); size_t old_height_pixels = CGDisplayModeGetPixelHeight(old_mode); BOOL new_size_same = (new_width_pixels == width_points && new_height_pixels == height_points); BOOL old_size_same = (old_width_pixels == width_points && old_height_pixels == height_points); if (new_size_same && !old_size_same) better = TRUE; else if (!new_size_same && old_size_same) better = FALSE; else { /* Otherwise, prefer the mode with the smaller pixel size. */ if (old_width_pixels < new_width_pixels || old_height_pixels < new_height_pixels) better = FALSE; } } } if (better) CFDictionarySetValue(modes_by_size, key, new_mode); CFRelease(key); } CFRelease(modes); count = CFDictionaryGetCount(modes_by_size); mode_array = HeapAlloc(GetProcessHeap(), 0, count * sizeof(mode_array[0])); CFDictionaryGetKeysAndValues(modes_by_size, NULL, (const void **)mode_array); modes = CFArrayCreate(NULL, (const void **)mode_array, count, &kCFTypeArrayCallBacks); HeapFree(GetProcessHeap(), 0, mode_array); CFRelease(modes_by_size); } else #endif modes = CGDisplayCopyAllDisplayModes(display, NULL); return modes; }
/*********************************************************************** * EnumDisplaySettingsEx (MACDRV.@) * */ BOOL CDECL macdrv_EnumDisplaySettingsEx(LPCWSTR devname, DWORD mode, LPDEVMODEW devmode, DWORD flags) { static const WCHAR dev_name[CCHDEVICENAME] = { 'W','i','n','e',' ','M','a','c',' ','d','r','i','v','e','r',0 }; struct macdrv_display *displays = NULL; int num_displays; CGDisplayModeRef display_mode; int display_mode_bpp; BOOL synthesized = FALSE; double rotation; uint32_t io_flags; TRACE("%s, %u, %p + %hu, %08x\n", debugstr_w(devname), mode, devmode, devmode->dmSize, flags); memcpy(devmode->dmDeviceName, dev_name, sizeof(dev_name)); devmode->dmSpecVersion = DM_SPECVERSION; devmode->dmDriverVersion = DM_SPECVERSION; devmode->dmSize = FIELD_OFFSET(DEVMODEW, dmICMMethod); devmode->dmDriverExtra = 0; memset(&devmode->dmFields, 0, devmode->dmSize - FIELD_OFFSET(DEVMODEW, dmFields)); if (mode == ENUM_REGISTRY_SETTINGS) { TRACE("mode %d (registry) -- getting default mode\n", mode); return read_registry_settings(devmode); } if (macdrv_get_displays(&displays, &num_displays)) goto failed; if (mode == ENUM_CURRENT_SETTINGS) { TRACE("mode %d (current) -- getting current mode\n", mode); display_mode = CGDisplayCopyDisplayMode(displays[0].displayID); display_mode_bpp = display_mode_bits_per_pixel(display_mode); } else { DWORD count, i; EnterCriticalSection(&modes_section); if (mode == 0 || !modes) { if (modes) CFRelease(modes); modes = copy_display_modes(displays[0].displayID); modes_has_8bpp = modes_has_16bpp = FALSE; if (modes) { count = CFArrayGetCount(modes); for (i = 0; i < count && !(modes_has_8bpp && modes_has_16bpp); i++) { CGDisplayModeRef mode = (CGDisplayModeRef)CFArrayGetValueAtIndex(modes, i); int bpp = display_mode_bits_per_pixel(mode); if (bpp == 8) modes_has_8bpp = TRUE; else if (bpp == 16) modes_has_16bpp = TRUE; } } } display_mode = NULL; if (modes) { int default_bpp = get_default_bpp(); DWORD seen_modes = 0; count = CFArrayGetCount(modes); for (i = 0; i < count; i++) { CGDisplayModeRef candidate = (CGDisplayModeRef)CFArrayGetValueAtIndex(modes, i); io_flags = CGDisplayModeGetIOFlags(candidate); if (!(flags & EDS_RAWMODE) && (!(io_flags & kDisplayModeValidFlag) || !(io_flags & kDisplayModeSafeFlag))) continue; seen_modes++; if (seen_modes > mode) { display_mode = (CGDisplayModeRef)CFRetain(candidate); display_mode_bpp = display_mode_bits_per_pixel(display_mode); break; } /* We only synthesize modes from those having the default bpp. */ if (display_mode_bits_per_pixel(candidate) != default_bpp) continue; if (!modes_has_8bpp) { seen_modes++; if (seen_modes > mode) { display_mode = (CGDisplayModeRef)CFRetain(candidate); display_mode_bpp = 8; synthesized = TRUE; break; } } if (!modes_has_16bpp) { seen_modes++; if (seen_modes > mode) { display_mode = (CGDisplayModeRef)CFRetain(candidate); display_mode_bpp = 16; synthesized = TRUE; break; } } } } LeaveCriticalSection(&modes_section); } if (!display_mode) goto failed; /* We currently only report modes for the primary display, so it's at (0, 0). */ devmode->dmPosition.x = 0; devmode->dmPosition.y = 0; devmode->dmFields |= DM_POSITION; rotation = CGDisplayRotation(displays[0].displayID); devmode->dmDisplayOrientation = ((int)((rotation / 90) + 0.5)) % 4; devmode->dmFields |= DM_DISPLAYORIENTATION; io_flags = CGDisplayModeGetIOFlags(display_mode); if (io_flags & kDisplayModeStretchedFlag) devmode->dmDisplayFixedOutput = DMDFO_STRETCH; else devmode->dmDisplayFixedOutput = DMDFO_CENTER; devmode->dmFields |= DM_DISPLAYFIXEDOUTPUT; devmode->dmBitsPerPel = display_mode_bpp; if (devmode->dmBitsPerPel) devmode->dmFields |= DM_BITSPERPEL; devmode->dmPelsWidth = CGDisplayModeGetWidth(display_mode); devmode->dmPelsHeight = CGDisplayModeGetHeight(display_mode); devmode->dmFields |= DM_PELSWIDTH | DM_PELSHEIGHT; devmode->dmDisplayFlags = 0; if (io_flags & kDisplayModeInterlacedFlag) devmode->dmDisplayFlags |= DM_INTERLACED; devmode->dmFields |= DM_DISPLAYFLAGS; devmode->dmDisplayFrequency = CGDisplayModeGetRefreshRate(display_mode); if (!devmode->dmDisplayFrequency) devmode->dmDisplayFrequency = 60; devmode->dmFields |= DM_DISPLAYFREQUENCY; CFRelease(display_mode); macdrv_free_displays(displays); TRACE("mode %d -- %dx%dx%dbpp @%d Hz", mode, devmode->dmPelsWidth, devmode->dmPelsHeight, devmode->dmBitsPerPel, devmode->dmDisplayFrequency); if (devmode->dmDisplayOrientation) TRACE(" rotated %u degrees", devmode->dmDisplayOrientation * 90); if (devmode->dmDisplayFixedOutput == DMDFO_STRETCH) TRACE(" stretched"); if (devmode->dmDisplayFlags & DM_INTERLACED) TRACE(" interlaced"); if (synthesized) TRACE(" (synthesized)"); TRACE("\n"); return TRUE; failed: TRACE("mode %d -- not present\n", mode); if (displays) macdrv_free_displays(displays); SetLastError(ERROR_NO_MORE_FILES); 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
/* * Creates a vector of driver bundle info structures from the hot-plug driver * directory. * * Returns NULL on error and a pointer to an allocated HPDriver vector on * success. The caller must free the HPDriver with a call to * HPDriversRelease(). */ static HPDriverVector HPDriversGetFromDirectory(const char *driverBundlePath) { int i; #ifdef DEBUG_HOTPLUG Log2(PCSC_LOG_DEBUG, "Entering HPDriversGetFromDirectory: %s", driverBundlePath); #endif int readersNumber = 0; HPDriverVector bundleVector = NULL; CFArrayRef bundleArray; CFStringRef driverBundlePathString = CFStringCreateWithCString(kCFAllocatorDefault, driverBundlePath, kCFStringEncodingMacRoman); CFURLRef pluginUrl = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, driverBundlePathString, kCFURLPOSIXPathStyle, TRUE); CFRelease(driverBundlePathString); if (!pluginUrl) { Log1(PCSC_LOG_ERROR, "error getting plugin directory URL"); return NULL; } bundleArray = CFBundleCreateBundlesFromDirectory(kCFAllocatorDefault, pluginUrl, NULL); if (!bundleArray) { Log1(PCSC_LOG_ERROR, "error getting plugin directory bundles"); return NULL; } CFRelease(pluginUrl); size_t bundleArraySize = CFArrayGetCount(bundleArray); /* get the number of readers (including aliases) */ for (i = 0; i < bundleArraySize; i++) { CFBundleRef currBundle = (CFBundleRef) CFArrayGetValueAtIndex(bundleArray, i); CFDictionaryRef dict = CFBundleGetInfoDictionary(currBundle); const void * blobValue = CFDictionaryGetValue(dict, CFSTR(PCSCLITE_HP_MANUKEY_NAME)); if (!blobValue) { Log1(PCSC_LOG_ERROR, "error getting vendor ID from bundle"); return NULL; } if (CFGetTypeID(blobValue) == CFArrayGetTypeID()) { /* alias found, each reader count as 1 */ CFArrayRef propertyArray = blobValue; readersNumber += CFArrayGetCount(propertyArray); } else /* No alias, only one reader supported */ readersNumber++; } #ifdef DEBUG_HOTPLUG Log2(PCSC_LOG_DEBUG, "Total of %d readers supported", readersNumber); #endif /* The last entry is an end marker (m_vendorId = 0) * see checks in HPDriversMatchUSBDevices:503 * and HPDriverVectorRelease:376 */ readersNumber++; bundleVector = (HPDriver *) calloc(readersNumber, sizeof(HPDriver)); if (!bundleVector) { Log1(PCSC_LOG_ERROR, "memory allocation failure"); return NULL; } HPDriver *driverBundle = bundleVector; for (i = 0; i < bundleArraySize; i++) { CFBundleRef currBundle = (CFBundleRef) CFArrayGetValueAtIndex(bundleArray, i); CFDictionaryRef dict = CFBundleGetInfoDictionary(currBundle); CFURLRef bundleUrl = CFBundleCopyBundleURL(currBundle); CFStringRef bundlePath = CFURLCopyPath(bundleUrl); driverBundle->m_libPath = strdup(CFStringGetCStringPtr(bundlePath, CFStringGetSystemEncoding())); const void * blobValue = CFDictionaryGetValue(dict, CFSTR(PCSCLITE_HP_MANUKEY_NAME)); if (!blobValue) { Log1(PCSC_LOG_ERROR, "error getting vendor ID from bundle"); return bundleVector; } if (CFGetTypeID(blobValue) == CFArrayGetTypeID()) { CFArrayRef vendorArray = blobValue; CFArrayRef productArray; CFArrayRef friendlyNameArray; char *libPath = driverBundle->m_libPath; #ifdef DEBUG_HOTPLUG Log2(PCSC_LOG_DEBUG, "Driver with aliases: %s", libPath); #endif /* get list of ProductID */ productArray = CFDictionaryGetValue(dict, CFSTR(PCSCLITE_HP_PRODKEY_NAME)); if (!productArray) { Log1(PCSC_LOG_ERROR, "error getting product ID from bundle"); return bundleVector; } /* get list of FriendlyName */ friendlyNameArray = CFDictionaryGetValue(dict, CFSTR(PCSCLITE_HP_NAMEKEY_NAME)); if (!friendlyNameArray) { Log1(PCSC_LOG_ERROR, "error getting product ID from bundle"); return bundleVector; } int reader_nb = CFArrayGetCount(vendorArray); if (reader_nb != CFArrayGetCount(productArray)) { Log3(PCSC_LOG_ERROR, "Malformed Info.plist: %d vendors and %d products", reader_nb, CFArrayGetCount(productArray)); return bundleVector; } if (reader_nb != CFArrayGetCount(friendlyNameArray)) { Log3(PCSC_LOG_ERROR, "Malformed Info.plist: %d vendors and %d friendlynames", reader_nb, CFArrayGetCount(friendlyNameArray)); return bundleVector; } int j; for (j=0; j<reader_nb; j++) { CFStringRef strValue = CFArrayGetValueAtIndex(vendorArray, j); driverBundle->m_vendorId = strtoul(CFStringGetCStringPtr(strValue, CFStringGetSystemEncoding()), NULL, 16); strValue = CFArrayGetValueAtIndex(productArray, j); driverBundle->m_productId = strtoul(CFStringGetCStringPtr(strValue, CFStringGetSystemEncoding()), NULL, 16); strValue = CFArrayGetValueAtIndex(friendlyNameArray, j); const char *cstr = CFStringGetCStringPtr(strValue, CFStringGetSystemEncoding()); driverBundle->m_friendlyName = strdup(cstr); if (!driverBundle->m_libPath) driverBundle->m_libPath = strdup(libPath); #ifdef DEBUG_HOTPLUG Log2(PCSC_LOG_DEBUG, "VendorID: 0x%04X", driverBundle->m_vendorId); Log2(PCSC_LOG_DEBUG, "ProductID: 0x%04X", driverBundle->m_productId); Log2(PCSC_LOG_DEBUG, "Friendly name: %s", driverBundle->m_friendlyName); Log2(PCSC_LOG_DEBUG, "Driver: %s", driverBundle->m_libPath); #endif /* go to next bundle in the vector */ driverBundle++; } } else { CFStringRef strValue = blobValue; #ifdef DEBUG_HOTPLUG Log3(PCSC_LOG_DEBUG, "Driver without alias: %s", driverBundle, driverBundle->m_libPath); #endif driverBundle->m_vendorId = strtoul(CFStringGetCStringPtr(strValue, CFStringGetSystemEncoding()), NULL, 16); strValue = (CFStringRef) CFDictionaryGetValue(dict, CFSTR(PCSCLITE_HP_PRODKEY_NAME)); if (!strValue) { Log1(PCSC_LOG_ERROR, "error getting product ID from bundle"); return bundleVector; } driverBundle->m_productId = strtoul(CFStringGetCStringPtr(strValue, CFStringGetSystemEncoding()), NULL, 16); strValue = (CFStringRef) CFDictionaryGetValue(dict, CFSTR(PCSCLITE_HP_NAMEKEY_NAME)); if (!strValue) { Log1(PCSC_LOG_ERROR, "error getting product friendly name from bundle"); driverBundle->m_friendlyName = strdup("unnamed device"); } else { const char *cstr = CFStringGetCStringPtr(strValue, CFStringGetSystemEncoding()); driverBundle->m_friendlyName = strdup(cstr); } #ifdef DEBUG_HOTPLUG Log2(PCSC_LOG_DEBUG, "VendorID: 0x%04X", driverBundle->m_vendorId); Log2(PCSC_LOG_DEBUG, "ProductID: 0x%04X", driverBundle->m_productId); Log2(PCSC_LOG_DEBUG, "Friendly name: %s", driverBundle->m_friendlyName); Log2(PCSC_LOG_DEBUG, "Driver: %s", driverBundle->m_libPath); #endif /* go to next bundle in the vector */ driverBundle++; } } CFRelease(bundleArray); return bundleVector; }
__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 */
void wxHIDJoystick::MakeCookies(CFArrayRef Array) { int i, nUsage, nPage; for (i = 0; i < CFArrayGetCount(Array); ++i) { const void* ref = CFDictionaryGetValue( (CFDictionaryRef)CFArrayGetValueAtIndex(Array, i), CFSTR(kIOHIDElementKey) ); if (ref != NULL) { MakeCookies((CFArrayRef) ref); } else { CFNumberGetValue( (CFNumberRef) CFDictionaryGetValue( (CFDictionaryRef) CFArrayGetValueAtIndex(Array, i), CFSTR(kIOHIDElementUsageKey) ), kCFNumberIntType, &nUsage ); CFNumberGetValue( (CFNumberRef) CFDictionaryGetValue( (CFDictionaryRef) CFArrayGetValueAtIndex(Array, i), CFSTR(kIOHIDElementUsagePageKey) ), kCFNumberIntType, &nPage ); #if 0 wxLogSysError(wxT("[%i][%i]"), nUsage, nPage); #endif if (nPage == kHIDPage_Button && nUsage <= 40) AddCookieInQueue(CFArrayGetValueAtIndex(Array, i), nUsage-1 ); else if (nPage == kHIDPage_GenericDesktop) { //axis... switch(nUsage) { case kHIDUsage_GD_X: AddCookieInQueue(CFArrayGetValueAtIndex(Array, i), wxJS_AXIS_X); wxGetIntFromCFDictionary(CFArrayGetValueAtIndex(Array, i), CFSTR(kIOHIDElementMaxKey), &m_nXMax); wxGetIntFromCFDictionary(CFArrayGetValueAtIndex(Array, i), CFSTR(kIOHIDElementMinKey), &m_nXMin); break; case kHIDUsage_GD_Y: AddCookieInQueue(CFArrayGetValueAtIndex(Array, i), wxJS_AXIS_Y); wxGetIntFromCFDictionary(CFArrayGetValueAtIndex(Array, i), CFSTR(kIOHIDElementMaxKey), &m_nYMax); wxGetIntFromCFDictionary(CFArrayGetValueAtIndex(Array, i), CFSTR(kIOHIDElementMinKey), &m_nYMin); break; case kHIDUsage_GD_Z: AddCookieInQueue(CFArrayGetValueAtIndex(Array, i), wxJS_AXIS_Z); wxGetIntFromCFDictionary(CFArrayGetValueAtIndex(Array, i), CFSTR(kIOHIDElementMaxKey), &m_nZMax); wxGetIntFromCFDictionary(CFArrayGetValueAtIndex(Array, i), CFSTR(kIOHIDElementMinKey), &m_nZMin); break; default: break; } } else if (nPage == kHIDPage_Simulation && nUsage == kHIDUsage_Sim_Rudder) { //rudder... AddCookieInQueue(CFArrayGetValueAtIndex(Array, i), wxJS_AXIS_RUDDER ); wxGetIntFromCFDictionary(CFArrayGetValueAtIndex(Array, i), CFSTR(kIOHIDElementMaxKey), &m_nRudderMax); wxGetIntFromCFDictionary(CFArrayGetValueAtIndex(Array, i), CFSTR(kIOHIDElementMinKey), &m_nRudderMin); } } } }
int OnBattery (void) { #if defined (__APPLE__) /* The following copyright applies to the battery detection code below. I did modify */ /* substantially as it did far more than I needed. */ /* Copyright (c) 2003 Thomas Runge ([email protected]) * Mach and Darwin specific code is Copyright (c) 2006 Eric Pooch ([email protected]) * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the author nor the names of its contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ CFTypeRef blob = IOPSCopyPowerSourcesInfo(); CFArrayRef sources = IOPSCopyPowerSourcesList(blob); int i, acstat; CFDictionaryRef pSource = NULL; const void *psValue; acstat = TRUE; for(i = 0; i < CFArrayGetCount(sources); i++) { pSource = IOPSGetPowerSourceDescription(blob, CFArrayGetValueAtIndex(sources, i)); if(!pSource) break; psValue = (CFStringRef)CFDictionaryGetValue(pSource, CFSTR(kIOPSNameKey)); if (CFDictionaryGetValueIfPresent(pSource, CFSTR(kIOPSIsPresentKey), &psValue) && (CFBooleanGetValue(psValue) > 0)) { psValue = (CFStringRef)CFDictionaryGetValue(pSource, CFSTR(kIOPSPowerSourceStateKey)); if (CFStringCompare(psValue,CFSTR(kIOPSBatteryPowerValue),0)==kCFCompareEqualTo) { /* We are running on a battery power source. */ acstat = FALSE; } } } CFRelease(blob); CFRelease(sources); return(!acstat); #elif defined (__linux__) FILE *fd; char buf[180]; int ac_state; ac_state = -1; fd = fopen ("/sys/class/power_supply/AC/online", "r"); if (fd != NULL) { fscanf (fd, "%d", &ac_state); fclose (fd); return (ac_state == 0); } fd = fopen ("/proc/acpi/battery/BAT0/state", "r"); if (fd != NULL) { while (fgets (buf, sizeof (buf), fd) != NULL) { char *p; p = strstr (buf, "charging state:"); if (p == NULL) continue; if (strstr (p+14, "discharging") != NULL) ac_state = 0; else if (strstr (p+14, "charging") != NULL) ac_state = 1; else if (strstr (p+14, "charged") != NULL) ac_state = 1; } fclose (fd); } return (ac_state == 0); #else return (FALSE); /* Assume we're on AC power */ #endif }
CFDataRef APCreateHashFromDictionary(CFDictionaryRef dict) { __block CFErrorRef error = NULL; __block SecTransformRef hashFunction = NULL; void(^cleanup)(void) = ^(void) { if (error != NULL) { CFShow(error); CFRelease(error); error = NULL; } if (hashFunction != NULL) { CFRelease(hashFunction); hashFunction = NULL; } }; // Get the number of elements CFIndex count = CFDictionaryGetCount(dict); // Load the keys and build up the key array CFMutableArrayRef keyArray = CFArrayCreateMutable(kCFAllocatorDefault, count, NULL); CFStringRef keys[count]; CFDictionaryGetKeysAndValues(dict, (const void**)&keys, NULL); for (int idx = 0; idx < count; idx++) { // Skip the signature key if (CFStringCompare(keys[idx], CFSTR("Signature"), 0) == kCFCompareEqualTo) { continue; } CFArrayAppendValue(keyArray, keys[idx]); } // Sort the array CFStringCompareFlags context = kCFCompareCaseInsensitive; CFArraySortValues(keyArray, CFRangeMake(0, count-1), (CFComparatorFunction)CFStringCompare, (void*)context); // Build the data CFMutableDataRef dictData = CFDataCreateMutable(kCFAllocatorDefault, 0); int keyCount = CFArrayGetCount(keyArray); for (int keyIndex = 0; keyIndex < keyCount; keyIndex++) { CFStringRef key = CFArrayGetValueAtIndex(keyArray, keyIndex); CFStringRef value = CFDictionaryGetValue(dict, key); CFDataRef valueData = CFStringCreateExternalRepresentation(kCFAllocatorDefault, value, kCFStringEncodingUTF8, 0); const UInt8 *valueBuffer = CFDataGetBytePtr(valueData); CFDataAppendBytes(dictData, valueBuffer, CFDataGetLength(valueData)); CFRelease(valueData); } // Hash the data hashFunction = SecDigestTransformCreate(kSecDigestSHA1, 0, &error); if (error != NULL) { CFRelease(dictData); cleanup(); return NULL; } SecTransformSetAttribute(hashFunction, kSecTransformInputAttributeName, dictData, &error); CFDataRef hashData = SecTransformExecute(hashFunction, &error); CFRelease(dictData); if (error != NULL) { cleanup(); if (hashData) { CFRelease(hashData); } return NULL; } cleanup(); return hashData; }
Boolean APSetKey(CFStringRef key) { hash = CFSTR(""); blacklist = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks); CFMutableStringRef mutableKey = CFStringCreateMutableCopy(kCFAllocatorDefault, 0, key); CFStringRef preparedKey = CFStringCreateMutableCopy(kCFAllocatorDefault, 0, key); CFLocaleRef currentLocale = CFLocaleCopyCurrent(); CFStringLowercase(mutableKey, currentLocale); CFRelease(currentLocale); if (CFStringHasPrefix(mutableKey, CFSTR("0x")) && CFStringGetLength(mutableKey) > 2) { CFStringDelete(mutableKey, CFRangeMake(0, 2)); } if (CFStringGetLength(mutableKey) == 1024/8*2) { CFRelease(preparedKey); preparedKey = APPEMKeyCreateFromHexKey(mutableKey); } CFRelease(mutableKey); SecItemImportExportKeyParameters params = {0}; params.version = SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION; params.flags = kSecKeyNoAccessControl; SecExternalItemType itemType = kSecItemTypePublicKey; SecExternalFormat externalFormat = kSecFormatPEMSequence; CFArrayRef tempArray = NULL; OSStatus oserr = noErr; // Set the key as extractable. Looking through the source code in SecImportExportUtils.cpp // it looks like this isn't handled, yet it seems to be documented to me. One day the code // may catch up, so I'm leaving this here to show the intention. CFNumberRef attributeFlags[1]; uint32 flag0value = CSSM_KEYATTR_EXTRACTABLE; CFNumberRef flag0 = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &flag0value); attributeFlags[0] = flag0; CFArrayRef keyAttributes = CFArrayCreate(kCFAllocatorDefault, (const void **)attributeFlags, 1, &kCFTypeArrayCallBacks); CFRelease(flag0); params.keyAttributes = keyAttributes; CFDataRef keyData = CFStringCreateExternalRepresentation(kCFAllocatorDefault, preparedKey, kCFStringEncodingUTF8, 0); CFRelease(preparedKey); oserr = SecItemImport(keyData, NULL, &externalFormat, &itemType, 0, ¶ms, NULL, &tempArray); CFRelease(keyAttributes); CFRelease(keyData); if (oserr != noErr) { CFStringRef errorString = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("Unable to import key. Error %d"), oserr); CFShow(errorString); CFRelease(errorString); return FALSE; } publicKeyRef = (SecKeyRef)CFArrayGetValueAtIndex(tempArray, 0); CFRetain(publicKeyRef); CFRelease(tempArray); return TRUE; }
int Printer_print (void (*draw) (void *boss, Graphics g), void *boss) { #if defined (UNIX) structMelderFile tempFile = { 0 }; char tempPath_utf8 [] = "/tmp/picXXXXXX"; close (mkstemp (tempPath_utf8)); Melder_pathToFile (Melder_peekUtf8ToWcs (tempPath_utf8), & tempFile); thePrinter. graphics = Graphics_create_postscriptjob (& tempFile, thePrinter. resolution, thePrinter. spots, thePrinter. paperSize, thePrinter. orientation, thePrinter. magnification); if (! thePrinter. graphics) return Melder_error1 (L"Cannot create temporary PostScript file for printing."); draw (boss, thePrinter. graphics); forget (thePrinter. graphics); char command [500]; sprintf (command, Melder_peekWcsToUtf8 (Site_getPrintCommand ()), tempPath_utf8); system (command); MelderFile_delete (& tempFile); #elif defined (_WIN32) int postScriptCode = POSTSCRIPT_PASSTHROUGH; DOCINFO docInfo; DEVMODE *devMode; initPrinter (); if (! theWinPrint. hDevMode) { memset (& theWinPrint, 0, sizeof (PRINTDLG)); theWinPrint. lStructSize = sizeof (PRINTDLG); theWinPrint. Flags = PD_RETURNDEFAULT; if (! PrintDlg (& theWinPrint)) return Melder_error1 (L"Cannot initialize printer."); } if (Melder_backgrounding) { theWinPrint. Flags = PD_RETURNDEFAULT | PD_RETURNDC; if (! PrintDlg (& theWinPrint) || theWinPrint. hDC == NULL) { return Melder_error1 (L"Cannot print from a script on this computer."); } } else { theWinPrint. Flags &= ~ PD_RETURNDEFAULT; theWinPrint. Flags |= PD_RETURNDC; if (! PrintDlg (& theWinPrint)) return 1; } theWinDC = theWinPrint. hDC; thePrinter. postScript = thePrinter. allowDirectPostScript && Escape (theWinDC, QUERYESCSUPPORT, sizeof (int), (LPSTR) & postScriptCode, NULL); /* * The HP colour inkjet printer returns in dmFields: * 0, 1, 8, 9, 10, 11, 12, 13, 14, 15, 23, 24, 25, 26 = DM_ORIENTATION | * DM_PAPERSIZE | DM_COPIES | DM_DEFAULTSOURCE | DM_PRINTQUALITY | * DM_COLOR | DM_DUPLEX | DM_YRESOLUTION | DM_TTOPTION | DM_COLLATE | * DM_ICMMETHOD | DM_ICMINTENT | DM_MEDIATYPE | DM_DITHERTYPE */ devMode = * (DEVMODE **) theWinPrint. hDevMode; thePrinter. resolution = devMode -> dmFields & DM_YRESOLUTION ? devMode -> dmYResolution : devMode -> dmFields & DM_PRINTQUALITY ? ( devMode -> dmPrintQuality > 0 ? devMode -> dmPrintQuality : 300 ) : 300; if (devMode -> dmFields & DM_PAPERWIDTH) { thePrinter. paperWidth = devMode -> dmPaperWidth * thePrinter. resolution / 254; thePrinter. paperHeight = devMode -> dmPaperLength * thePrinter. resolution / 254; } else if (devMode -> dmFields & DM_PAPERSIZE) { static struct { float width, height; } sizes [] = { { 0, 0 }, { 8.5, 11 }, { 8.5, 11 }, { 11, 17 }, { 17, 11 }, { 8.5, 14 }, { 5.5, 8.5 }, { 7.25, 10.5 }, { 297/25.4, 420/25.4 }, { 210/25.4, 297/25.4 }, { 210/25.4, 297/25.4 }, { 148.5/25.4, 210/25.4 }, { 250/25.4, 354/25.4 }, { 182/25.4, 257/25.4 }, { 8.5, 13 }, { 215/25.4, 275/25.4 }, { 10, 14 }, { 11, 17 }, { 8.5, 11 }, { 3.875, 8.875 }, { 4.125, 9.5 }, { 4.5, 10.375 } }; int paperSize = devMode -> dmPaperSize; if (paperSize <= 0 || paperSize > 21) paperSize = 1; thePrinter. paperWidth = sizes [paperSize]. width * thePrinter. resolution; thePrinter. paperHeight = sizes [paperSize]. height * thePrinter. resolution; if (devMode -> dmOrientation == DMORIENT_LANDSCAPE) { long dummy = thePrinter. paperWidth; thePrinter. paperWidth = thePrinter. paperHeight; thePrinter. paperHeight = dummy; } } else { thePrinter. paperWidth = 1000; thePrinter. paperHeight = 1000; } EnableWindow ((HWND) XtWindow (theCurrentPraatApplication -> topShell), FALSE); SetAbortProc (theWinDC, AbortFunc); memset (& docInfo, 0, sizeof (DOCINFO)); docInfo. cbSize = sizeof (DOCINFO); docInfo. lpszDocName = L"Praatjes"; docInfo. lpszOutput = NULL; if (thePrinter. postScript) { StartDoc (theWinDC, & docInfo); StartPage (theWinDC); initPostScriptPage (); thePrinter. graphics = Graphics_create_postscriptprinter (); if (! thePrinter. graphics) return Melder_error1 (L"Cannot open printer."); draw (boss, thePrinter. graphics); forget (thePrinter. graphics); exitPostScriptPage (); EndPage (theWinDC); EndDoc (theWinDC); } else { StartDoc (theWinDC, & docInfo); StartPage (theWinDC); thePrinter. graphics = Graphics_create_screenPrinter (NULL, (unsigned long) theWinDC); if (! thePrinter. graphics) return Melder_error1 (L"Cannot open printer."); draw (boss, thePrinter. graphics); forget (thePrinter. graphics); if (EndPage (theWinDC) < 0) { Melder_error1 (L"Cannot print page."); } else { EndDoc (theWinDC); } } EnableWindow ((HWND) XtWindow (theCurrentPraatApplication -> topShell), TRUE); DeleteDC (theWinDC), theWinDC = NULL; #elif defined (macintosh) Boolean result; initPrinter (); if (Melder_backgrounding) { PMSessionValidatePageFormat (theMacPrintSession, theMacPageFormat, & result); PMSessionValidatePrintSettings (theMacPrintSession, theMacPrintSettings, & result); } else { Boolean accepted; PMSessionPrintDialog (theMacPrintSession, theMacPrintSettings, theMacPageFormat, & accepted); if (! accepted) return 1; /* Normal cancelled return. */ } PMSessionValidatePageFormat (theMacPrintSession, theMacPageFormat, & result); PMSessionValidatePrintSettings (theMacPrintSession, theMacPrintSettings, & result); PMResolution res; PMGetResolution (theMacPageFormat, & res); thePrinter. resolution = res. hRes; PMGetAdjustedPaperRect (theMacPageFormat, & paperSize); thePrinter. paperWidth = paperSize. right - paperSize. left; thePrinter. paperHeight = paperSize. bottom - paperSize. top; Boolean isPostScriptDriver = FALSE; //PMSessionIsDocumentFormatSupported (theMacPrintSession, // kPMDocumentFormatPICTPS, & isPostScriptDriver); CFArrayRef supportedFormats; PMSessionGetDocumentFormatGeneration (theMacPrintSession, & supportedFormats); CFIndex numberOfSupportedFormats = CFArrayGetCount (supportedFormats); if (Melder_debug == 21) { MelderInfo_open (); MelderInfo_writeLine1 (L"Supported document formats:"); } for (CFIndex i = 0; i < numberOfSupportedFormats; i ++) { CFStringRef supportedFormat = CFArrayGetValueAtIndex (supportedFormats, i); if (CFStringCompare (supportedFormat, kPMDocumentFormatPICTPS, 0) == 0) { isPostScriptDriver = TRUE; } if (Melder_debug == 21) { MelderInfo_writeLine3 (Melder_integer (i), L": ", Melder_peekUtf8ToWcs (CFStringGetCStringPtr (supportedFormat, kCFStringEncodingUTF8))); } } if (Melder_debug == 21) { MelderInfo_close (); } CFRelease (supportedFormats); isPostScriptDriver = FALSE; // OVERRIDE, because from 10.4 on we have something better: we'll be sending PDF thePrinter. postScript = thePrinter. allowDirectPostScript && isPostScriptDriver; if (thePrinter. postScript) { CFStringRef strings [1]; strings [0] = kPMGraphicsContextQuickdraw; CFArrayRef array = CFArrayCreate (kCFAllocatorDefault, (const void **) strings, 1, & kCFTypeArrayCallBacks); OSStatus err = PMSessionSetDocumentFormatGeneration (theMacPrintSession, kPMDocumentFormatPICTPS, array, NULL); CFRelease (array); if (err != 0) { return Melder_error2 (L"PMSessionSetDocumentFormatGeneration: error ", Melder_integer (err)); } } PMOrientation orientation; PMGetOrientation (theMacPageFormat, & orientation); thePrinter. orientation = orientation == kPMLandscape || orientation == kPMReverseLandscape ? kGraphicsPostscript_orientation_LANDSCAPE : kGraphicsPostscript_orientation_PORTRAIT; PMSessionBeginDocument (theMacPrintSession, theMacPrintSettings, theMacPageFormat); PMSessionBeginPage (theMacPrintSession, theMacPageFormat, NULL); PMSessionGetGraphicsContext (theMacPrintSession, kPMGraphicsContextQuickdraw, (void **) & theMacPort); /* * On PostScript, the point (0, 0) is the bottom left corner of the paper, which is fine. * On the screen, however, the point (0, 0) is the top left corner of the writable page. * Since we want paper-related margins, not writable-page-related margins, * we require that this point gets the coordinates (250, 258) or so, * so that the top left corner of the paper gets coordinates (0, 0). * The "left" and "top" attributes of rPaper are negative values (e.g. -250 and -258), * so multiply them by -1. * * Under Carbon, the port has to be set inside the page. */ SetPort (theMacPort); if (! thePrinter. postScript) SetOrigin (- paperSize. left, - paperSize. top); if (thePrinter. postScript) { if (! openPostScript ()) error1 (L"Cannot print PostScript.") thePrinter. graphics = Graphics_create_postscriptprinter (); if (! thePrinter. graphics) goto end; draw (boss, thePrinter. graphics); forget (thePrinter. graphics); closePostScript (); } else { thePrinter. graphics = Graphics_create_screenPrinter (NULL, (unsigned long) theMacPort); draw (boss, thePrinter. graphics); forget (thePrinter. graphics); } end: if (theMacPort) { PMSessionEndPage (theMacPrintSession); PMSessionEndDocument (theMacPrintSession); theMacPort = NULL; } #endif iferror return 0; return 1; }
CFStringRef CFUserNotificationGetResponseValue(CFUserNotificationRef userNotification, CFStringRef key, CFIndex idx) { CHECK_FOR_FORK(); CFStringRef retval = NULL; CFTypeRef value = NULL; if (userNotification && userNotification->_responseDictionary) { value = CFDictionaryGetValue(userNotification->_responseDictionary, key); if (CFGetTypeID(value) == CFStringGetTypeID()) { if (0 == idx) retval = (CFStringRef)value; } else if (CFGetTypeID(value) == CFArrayGetTypeID()) { if (0 <= idx && idx < CFArrayGetCount((CFArrayRef)value)) retval = (CFStringRef)CFArrayGetValueAtIndex((CFArrayRef)value, idx); } } return retval; }
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 // kSCPropNetProxiesProxyAutoConfigURLString returns the URL string // as entered in the system proxy configuration dialog CFStringRef pacLocationSetting = (CFStringRef)CFDictionaryGetValue(dict, kSCPropNetProxiesProxyAutoConfigURLString); QCFType<CFStringRef> cfPacLocation = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, pacLocationSetting, NULL, NULL, kCFStringEncodingUTF8); if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5) { QCFType<CFDataRef> pacData; QCFType<CFURLRef> pacUrl = CFURLCreateWithString(kCFAllocatorDefault, cfPacLocation, NULL); if (!pacUrl) { qWarning("Invalid PAC URL \"%s\"", qPrintable(QCFString::toQString(cfPacLocation))); return result; } 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; } if (!pacData) { qWarning("\"%s\" returned an empty PAC script", qPrintable(QCFString::toQString(cfPacLocation))); 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 { 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; }
static bool switchPartition(char * diskName, char * partitionType) { char wholeDevicePath[256]; sprintf(wholeDevicePath, "/dev/%s", diskName); unsigned int partitionNumber = 0; char * c = wholeDevicePath + 5 + 4; // skip over "/dev/disk" while (*c != 's' && *c++); // look for 's' if (*c == 's') { *c = 0; // clip off remainder sscanf(c+1, "%u", &partitionNumber); // get partition number } if (!partitionNumber) return true; // just assume it is a raid disk #define LIVERAID #ifdef LIVERAID char * optionString = "<dict> <key>Writable</key> <true/> <key>Shared Writer</key> <true/></dict>"; #else char * optionString = "<dict> <key>Writable</key> <true/> </dict>"; #endif CFDictionaryRef options = IOCFUnserialize(optionString, kCFAllocatorDefault, 0, NULL); if (!options) exit(1); int32_t err; MKMediaRef device = MKMediaCreateWithPath(nil, wholeDevicePath, options, &err); CFRelease(options); if (!device || err) return false; options = NULL; MKStatus err2; CFMutableDictionaryRef media = MKCFReadMedia(options, device, &err2); if (!media || err2) goto Failure; // find and extract the 'Schemes' array CFMutableArrayRef Schemes = (CFMutableArrayRef) CFDictionaryGetValue(media, CFSTR("Schemes")); if (!Schemes) goto Failure; // DMTool just grabs the first "default" scheme, so do the same CFMutableDictionaryRef Scheme = (CFMutableDictionaryRef) CFArrayGetValueAtIndex(Schemes, 0); if (!Scheme) goto Failure; // Then find and extract the 'Sections' array of that scheme: CFMutableArrayRef Sections = (CFMutableArrayRef) CFDictionaryGetValue(Scheme, CFSTR("Sections")); if (!Sections) goto Failure; // Every scheme can have multiple sections to it, we need to find the 'MAP' section: CFMutableDictionaryRef Section = (CFMutableDictionaryRef) CFArrayDictionarySearch(Sections, CFSTR("ID"), CFSTR("MAP")); if (!Section) goto Failure; // Then find and extract the 'Partitions' array of that section: CFMutableArrayRef Partitions = (CFMutableArrayRef) CFDictionaryGetValue(Section, CFSTR("Partitions")); if (!Partitions) goto Failure; CFNumberRef partitionIndex = CFNumberCreate(nil, kCFNumberSInt32Type, &partitionNumber); if (!partitionIndex) goto Failure; CFMutableDictionaryRef Partition = (CFMutableDictionaryRef) CFArrayDictionarySearch(Partitions, CFSTR("Partition ID"), partitionIndex); if (!Partition) goto Failure; // change the partition type (finally!) CFStringRef Type = CFStringCreateWithCString(nil, partitionType, kCFStringEncodingUTF8); if (!Type) goto Failure; CFDictionarySetValue(Partition, CFSTR("Type"), Type); CFMutableDictionaryRef woptions = CFDictionaryCreateMutable(kCFAllocatorDefault, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); if (!woptions) goto Failure; CFDictionarySetValue(woptions, CFSTR("Retain existing content"), kCFBooleanTrue); CFDictionarySetValue(woptions, CFSTR("Direct Mode"), kCFBooleanTrue); err2 = MKCFWriteMedia(media, nil, nil, woptions, device); MKCFDisposeMedia(media); CFRelease(woptions); CFRelease(device); return !err2; Failure: if (media) MKCFDisposeMedia(media); if (device) CFRelease(device); return false; }
/* Reads certificates from the list of known locations into store. Stops when * any location contains any certificates, to prevent spending unnecessary time * adding redundant certificates, e.g. when both a certificate bundle and * individual certificates exist in the same directory. */ static void read_trusted_roots_from_known_locations(HCERTSTORE store) { HCERTSTORE from = CertOpenStore(CERT_STORE_PROV_MEMORY, X509_ASN_ENCODING, 0, CERT_STORE_CREATE_NEW_FLAG, NULL); if (from) { DWORD i; BOOL ret = FALSE; #ifdef __APPLE__ OSStatus status; CFArrayRef rootCerts; KeychainExportFunc exportFunc = NULL; #ifdef HAVE_DLFCN_H /* SecKeychainItemExport is deprecated on OS X 10.7, replaced by SecItemExport. * Since their parameters match, we can simply get the function pointer. */ exportFunc = dlsym(RTLD_DEFAULT, "SecItemExport"); if (exportFunc == NULL) { exportFunc = dlsym(RTLD_DEFAULT, "SecKeychainItemExport"); if (exportFunc == NULL) WARN("unable to load a keychain export function: root certificates not loaded from Keychain\n"); else TRACE("using SecKeychainItemExport()\n"); } else TRACE("using SecItemExport()\n"); #else exportFunc = SecKeychainItemExport; #endif status = SecTrustCopyAnchorCertificates(&rootCerts); if (status == noErr && exportFunc != NULL) { int i; for (i = 0; i < CFArrayGetCount(rootCerts); i++) { SecCertificateRef cert = (SecCertificateRef)CFArrayGetValueAtIndex(rootCerts, i); CFDataRef certData; if ((status = exportFunc(cert, kSecFormatX509Cert, 0, NULL, &certData)) == noErr) { if (CertAddEncodedCertificateToStore(store, X509_ASN_ENCODING, CFDataGetBytePtr(certData), CFDataGetLength(certData), CERT_STORE_ADD_NEW, NULL)) ret = TRUE; else WARN("adding root cert %d failed: %08x\n", i, GetLastError()); CFRelease(certData); } else WARN("could not export certificate %d to X509 format: 0x%08x\n", i, (unsigned int)status); } CFRelease(rootCerts); } #endif for (i = 0; !ret && i < sizeof(CRYPT_knownLocations) / sizeof(CRYPT_knownLocations[0]); i++) ret = import_certs_from_path(CRYPT_knownLocations[i], from, TRUE); check_and_store_certs(from, store); } CertCloseStore(from, 0); }
static void createSet(char * levelCString, char * nameCString, int argc, char* argv[]) { if (!levelCString || !nameCString || argc < 2) { usage(); exit(1); } CFStringRef level = CFStringCreateWithCString(kCFAllocatorDefault, levelCString, kCFStringEncodingUTF8); CFStringRef name = CFStringCreateWithCString(kCFAllocatorDefault, nameCString, kCFStringEncodingUTF8); if (!level || !name) exit(1); // get list of available raid set descriptions CFMutableArrayRef descriptionArray = AppleRAIDGetSetDescriptions(); CFIndex dCount = CFArrayGetCount(descriptionArray); CFIndex dIndex = 0; CFStringRef dLevel = 0; for (dIndex = 0; dIndex < dCount; dIndex++) { CFMutableDictionaryRef setDescription = (CFMutableDictionaryRef)CFArrayGetValueAtIndex(descriptionArray, dIndex); dLevel = (CFStringRef)CFDictionaryGetValue(setDescription, CFSTR(kAppleRAIDLevelNameKey)); if (!dLevel) break; if (CFStringCompare(dLevel, level, kCFCompareCaseInsensitive) == kCFCompareEqualTo) break; dLevel = 0; } if (dLevel == 0) { printf("raid level \"%s\" is not valid?.\n", levelCString); exit(1); } CFMutableDictionaryRef setInfo = AppleRAIDCreateSet(dLevel, name); if (!setInfo) exit(1); char **firstPartition = argv; int partitionCount = argc; while (argc--) { printf("adding partition \"%s\"\n", *argv); CFStringRef partitionName = CFStringCreateWithCString(kCFAllocatorDefault, *argv, kCFStringEncodingUTF8); AppleRAIDMemberRef member = AppleRAIDAddMember(setInfo, partitionName, CFSTR(kAppleRAIDMembersKey)); if (!member) { printf("there was problem adding partition \"%s\"\n", *argv); exit(1); } CFShow(member); bool success = switchPartition(*argv, kRAID_OFFLINE); if (!success) { printf("switching the partition on \"%s\" to %s FAILED.\n", *argv, kRAID_OFFLINE); exit(1); } argv++; } if (autoRebuild == AUTO_YES) AppleRAIDModifySet(setInfo, CFSTR(kAppleRAIDSetAutoRebuildKey), (void *)kCFBooleanTrue); if (quickRebuild == AUTO_YES) AppleRAIDModifySet(setInfo, CFSTR(kAppleRAIDSetQuickRebuildKey), (void *)kCFBooleanTrue); if (blockSize) { CFNumberRef blockSizeCF = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt64Type, &blockSize); if (blockSizeCF) AppleRAIDModifySet(setInfo, CFSTR(kAppleRAIDChunkSizeKey), (void *)blockSizeCF); } if (hint) { CFStringRef hintCF = CFStringCreateWithCString(kCFAllocatorDefault, hint, kCFStringEncodingUTF8); if (hintCF) AppleRAIDModifySet(setInfo, CFSTR(kAppleRAIDSetContentHintKey), (void *)hintCF); } if (timeout) { CFNumberRef timeoutCF = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt64Type, &timeout); if (timeoutCF) AppleRAIDModifySet(setInfo, CFSTR(kAppleRAIDSetTimeoutKey), (void *)timeoutCF); } printf("creating the set \"%s\".\n", nameCString); AppleRAIDSetRef set = AppleRAIDUpdateSet(setInfo); CFPrintf(CFSTR("created set %@\n"), set); CFRelease(setInfo); if (!set) { printf("something went wrong creating the set\n"); exit(0); } while (partitionCount--) { printf("switching the partition on \"%s\" to %s.\n", *firstPartition, kRAID_ONLINE); bool success = switchPartition(*firstPartition, kRAID_ONLINE); if (!success) { printf("switching the partition on \"%s\" to %s FAILED.\n", *firstPartition, kRAID_ONLINE); exit(1); } firstPartition++; } // at this point the code should wait for notifications that members and the set are available }
launch_data_t GTMLaunchDataCreateFromCFType(CFTypeRef cf_type_ref, CFErrorRef *error) { launch_data_t result = NULL; CFErrorRef local_error = NULL; if (cf_type_ref == NULL) { local_error = GTMCFLaunchCreateUnlocalizedError(EINVAL, CFSTR("NULL CFType")); goto exit; } CFTypeID cf_type = CFGetTypeID(cf_type_ref); if (cf_type == CFStringGetTypeID()) { CFIndex length = CFStringGetLength(cf_type_ref); CFIndex max_length = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8) + 1; char *buffer = calloc(max_length, sizeof(char)); size_t buffer_size = max_length * sizeof(char); if (buffer) { if (CFStringGetCString(cf_type_ref, buffer, buffer_size, kCFStringEncodingUTF8)) { result = launch_data_alloc(LAUNCH_DATA_STRING); launch_data_set_string(result, buffer); } else { local_error = GTMCFLaunchCreateUnlocalizedError(EINVAL, CFSTR("CFStringGetCString failed %@"), cf_type_ref); } free(buffer); } else { local_error = GTMCFLaunchCreateUnlocalizedError(ENOMEM, CFSTR("calloc of %lu failed"), (unsigned long)buffer_size); } } else if (cf_type == CFBooleanGetTypeID()) { result = launch_data_alloc(LAUNCH_DATA_BOOL); launch_data_set_bool(result, CFBooleanGetValue(cf_type_ref)); } else if (cf_type == CFArrayGetTypeID()) { CFIndex count = CFArrayGetCount(cf_type_ref); result = launch_data_alloc(LAUNCH_DATA_ARRAY); for (CFIndex i = 0; i < count; i++) { CFTypeRef array_value = CFArrayGetValueAtIndex(cf_type_ref, i); if (array_value) { launch_data_t launch_value = GTMLaunchDataCreateFromCFType(array_value, &local_error); if (local_error) break; launch_data_array_set_index(result, launch_value, i); } } } else if (cf_type == CFDictionaryGetTypeID()) { result = launch_data_alloc(LAUNCH_DATA_DICTIONARY); GTMCFToLDictContext context = { result, &local_error }; CFDictionaryApplyFunction(cf_type_ref, GTMConvertCFDictEntryToLaunchDataDictEntry, &context); } else if (cf_type == CFDataGetTypeID()) { result = launch_data_alloc(LAUNCH_DATA_OPAQUE); launch_data_set_opaque(result, CFDataGetBytePtr(cf_type_ref), CFDataGetLength(cf_type_ref)); } else if (cf_type == CFNumberGetTypeID()) { CFNumberType cf_number_type = CFNumberGetType(cf_type_ref); switch (cf_number_type) { case kCFNumberSInt8Type: case kCFNumberSInt16Type: case kCFNumberSInt32Type: case kCFNumberSInt64Type: case kCFNumberCharType: case kCFNumberShortType: case kCFNumberIntType: case kCFNumberLongType: case kCFNumberLongLongType: case kCFNumberCFIndexType: case kCFNumberNSIntegerType:{ long long value; if (CFNumberGetValue(cf_type_ref, kCFNumberLongLongType, &value)) { result = launch_data_alloc(LAUNCH_DATA_INTEGER); launch_data_set_integer(result, value); } else { local_error = GTMCFLaunchCreateUnlocalizedError(EINVAL, CFSTR("Unknown to convert: %@"), cf_type_ref); } break; } case kCFNumberFloat32Type: case kCFNumberFloat64Type: case kCFNumberFloatType: case kCFNumberDoubleType: case kCFNumberCGFloatType: { double value; if (CFNumberGetValue(cf_type_ref, kCFNumberDoubleType, &value)) { result = launch_data_alloc(LAUNCH_DATA_REAL); launch_data_set_real(result, value); } else { local_error = GTMCFLaunchCreateUnlocalizedError(EINVAL, CFSTR("Unknown to convert: %@"), cf_type_ref); } break; } default: local_error = GTMCFLaunchCreateUnlocalizedError(EINVAL, CFSTR("Unknown CFNumberType %lld"), (long long)cf_number_type); break; } } else { local_error = GTMCFLaunchCreateUnlocalizedError(EINVAL, CFSTR("Unknown CFTypeID %lu"), (unsigned long)cf_type); } exit: if (error) { *error = local_error; } else if (local_error) { #ifdef DEBUG CFShow(local_error); #endif // DEBUG CFRelease(local_error); } return result; }
QVariant QMacPasteboard::retrieveData(const QString &format, QVariant::Type) const { if (!paste) return QVariant(); sync(); ItemCount cnt = 0; if(PasteboardGetItemCount(paste, &cnt) || !cnt) return QByteArray(); #ifdef DEBUG_PASTEBOARD qDebug("Pasteboard: retrieveData [%s]", qPrintable(format)); #endif const QList<QMacPasteboardMime *> mimes = QMacPasteboardMime::all(mime_type); for(int mime = 0; mime < mimes.size(); ++mime) { QMacPasteboardMime *c = mimes.at(mime); QString c_flavor = c->flavorFor(format); if(!c_flavor.isEmpty()) { // Handle text/plain a little differently. Try handling Unicode first. bool checkForUtf16 = (c_flavor == QLatin1String("com.apple.traditional-mac-plain-text") || c_flavor == QLatin1String("public.utf8-plain-text")); if (checkForUtf16 || c_flavor == QLatin1String("public.utf16-plain-text")) { // Try to get the NSStringPboardType from NSPasteboard, newlines are mapped // correctly (as '\n') in this data. The 'public.utf16-plain-text' type // usually maps newlines to '\r' instead. QString str = qt_mac_get_pasteboardString(paste); if (!str.isEmpty()) return str; } if (checkForUtf16 && hasFlavor(QLatin1String("public.utf16-plain-text"))) c_flavor = QLatin1String("public.utf16-plain-text"); QVariant ret; QList<QByteArray> retList; for(uint index = 1; index <= cnt; ++index) { PasteboardItemID id; if(PasteboardGetItemIdentifier(paste, index, &id) != noErr) continue; QCFType<CFArrayRef> types; if(PasteboardCopyItemFlavors(paste, id, &types ) != noErr) continue; const int type_count = CFArrayGetCount(types); for(int i = 0; i < type_count; ++i) { CFStringRef flavor = static_cast<CFStringRef>(CFArrayGetValueAtIndex(types, i)); if(c_flavor == QCFString::toQString(flavor)) { QCFType<CFDataRef> macBuffer; if(PasteboardCopyItemFlavorData(paste, id, flavor, &macBuffer) == noErr) { QByteArray buffer((const char *)CFDataGetBytePtr(macBuffer), CFDataGetLength(macBuffer)); if(!buffer.isEmpty()) { #ifdef DEBUG_PASTEBOARD qDebug(" - %s [%s] (%s)", qPrintable(format), qPrintable(QCFString::toQString(flavor)), qPrintable(c->convertorName())); #endif buffer.detach(); //detach since we release the macBuffer retList.append(buffer); break; //skip to next element } } } else { #ifdef DEBUG_PASTEBOARD qDebug(" - NoMatch %s [%s] (%s)", qPrintable(c_flavor), qPrintable(QCFString::toQString(flavor)), qPrintable(c->convertorName())); #endif } } } if (!retList.isEmpty()) { ret = c->convertToMime(format, retList, c_flavor); return ret; } } } return QVariant(); }
extern pascal OSStatus MoreSCCreateCCLArray(CFArrayRef *result, CFIndex *indexOfDefaultCCL) // See comment in header. { OSStatus err; CFMutableArrayRef localResult; UInt32 domainIndex; FSRef folderRef; static const SInt16 kFolderDomains[] = {kUserDomain, kNetworkDomain, kLocalDomain, kSystemDomain, 0}; assert( result != NULL); assert(*result == NULL); // Create an array containing the names of the CCLs from the Modem Scripts // folder in each domain. localResult = NULL; err = CFQArrayCreateMutable(&localResult); if (err == noErr) { UInt32 scannedFolders; scannedFolders = 0; domainIndex = 0; do { err = FSFindFolder(kFolderDomains[domainIndex], kModemScriptsFolderType, false, &folderRef); if (err != noErr) { // If we can't find the folder in this domain, just ignore the domain. err = noErr; } else { scannedFolders += 1; // If we found the folder, add each CCL in it to the array. err = AddCCLsInFolderToArray(&folderRef, localResult); } domainIndex += 1; } while (err == noErr && kFolderDomains[domainIndex] != 0); // Testing reveals that under certain circumstances, the above loop // will never find any folders. The specific case I saw was on // Mac OS 9.1 with CarbonLib 1.6 when running the application off // the non-boot volume. So, if FSFindFolder never returns any // folders in the domains we looped over above, let's do it the old // way and call FSFindFolder with kOnSystemDisk. // // I didn't file a bug against FSFindFolder because traditional Mac OS // bugs are no longer being fixed at this time. // -- Quinn, 10 Dec 2002 if ( (err == noErr) && (scannedFolders == 0) ) { if (FSFindFolder(kOnSystemDisk, kModemScriptsFolderType, false, &folderRef) == noErr) { err = AddCCLsInFolderToArray(&folderRef, localResult); } } } // Sort the resulting array and delete any duplicates. if (err == noErr) { CFIndex cursor; CFArraySortValues(localResult, CFRangeMake(0, CFArrayGetCount(localResult)), (CFComparatorFunction) CFStringCompare, (void *) kMyStringCompareOptions); cursor = 1; while (cursor < CFArrayGetCount(localResult)) { if ( CFEqual(CFArrayGetValueAtIndex(localResult, cursor), CFArrayGetValueAtIndex(localResult, cursor - 1)) ) { CFArrayRemoveValueAtIndex(localResult, cursor); } else { cursor += 1; } } } // Find the index of the default CCL (or use the first CCL if the default // isn't found). The array is already sorted for user presentation, so // we can use CFArrayBSearchValues rather than searching by hand. This // might even be a relevant speed increase because the number of CCLs can // range into the hundreds. if (err == noErr && indexOfDefaultCCL != NULL) { CFStringRef defaultCCLName; CFIndex itemIndex; if (gDefaultCCL == NULL) { defaultCCLName = CFSTR("Apple Internal 56K Modem (v.90)"); } else { defaultCCLName = gDefaultCCL; } itemIndex = CFArrayBSearchValues(localResult, CFRangeMake(0, CFArrayGetCount(localResult)), defaultCCLName, (CFComparatorFunction) CFStringCompare, (void *) kMyStringCompareOptions); // itemIndex is either: // // o pointing directly at the correct element, if an exact match is found, or // // o if no exact match is found, pointing after the element that's immediately // less than defaultCCLName // // So, to confirm that we have the default script we check that the item is in // bounds and that its value matches defaultCCLName. If either of these // checks fails, we return the index of the first CCL. if ( (itemIndex < CFArrayGetCount(localResult)) && (CFStringCompare(defaultCCLName, (CFStringRef) CFArrayGetValueAtIndex(localResult, itemIndex), kMyStringCompareOptions) == kCFCompareEqualTo)) { *indexOfDefaultCCL = itemIndex; } else { *indexOfDefaultCCL = 0; } } // Clean up. if (err != noErr) { CFQRelease(localResult); localResult = NULL; } *result = localResult; assert( (err == noErr) == (*result != NULL) ); assert( (err != noErr) // either we got an error || (indexOfDefaultCCL == NULL) // or the user didn't ask for the default CCL || (CFArrayGetCount(*result) == 0) // or there are no CCLs || (*indexOfDefaultCCL >= 0 && *indexOfDefaultCCL < CFArrayGetCount(*result)) ); // or the default CCL we're returning is in bounds return err; }
// 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 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(); }
/* Resolve IPv4/IPv6 address */ PJ_DEF(pj_status_t) pj_getaddrinfo(int af, const pj_str_t *nodename, unsigned *count, pj_addrinfo ai[]) { #if defined(PJ_SOCK_HAS_GETADDRINFO) && PJ_SOCK_HAS_GETADDRINFO!=0 char nodecopy[PJ_MAX_HOSTNAME]; pj_bool_t has_addr = PJ_FALSE; unsigned i; #if defined(PJ_GETADDRINFO_USE_CFHOST) && PJ_GETADDRINFO_USE_CFHOST!=0 CFStringRef hostname; CFHostRef hostRef; pj_status_t status = PJ_SUCCESS; #else int rc; struct addrinfo hint, *res, *orig_res; #endif PJ_ASSERT_RETURN(nodename && count && *count && ai, PJ_EINVAL); PJ_ASSERT_RETURN(nodename->ptr && nodename->slen, PJ_EINVAL); PJ_ASSERT_RETURN(af==PJ_AF_INET || af==PJ_AF_INET6 || af==PJ_AF_UNSPEC, PJ_EINVAL); /* Check if nodename is IP address */ pj_bzero(&ai[0], sizeof(ai[0])); if ((af==PJ_AF_INET || af==PJ_AF_UNSPEC) && pj_inet_pton(PJ_AF_INET, nodename, &ai[0].ai_addr.ipv4.sin_addr) == PJ_SUCCESS) { af = PJ_AF_INET; has_addr = PJ_TRUE; } else if ((af==PJ_AF_INET6 || af==PJ_AF_UNSPEC) && pj_inet_pton(PJ_AF_INET6, nodename, &ai[0].ai_addr.ipv6.sin6_addr) == PJ_SUCCESS) { af = PJ_AF_INET6; has_addr = PJ_TRUE; } if (has_addr) { pj_str_t tmp; tmp.ptr = ai[0].ai_canonname; pj_strncpy_with_null(&tmp, nodename, PJ_MAX_HOSTNAME); ai[0].ai_addr.addr.sa_family = (pj_uint16_t)af; *count = 1; return PJ_SUCCESS; } /* Copy node name to null terminated string. */ if (nodename->slen >= PJ_MAX_HOSTNAME) return PJ_ENAMETOOLONG; pj_memcpy(nodecopy, nodename->ptr, nodename->slen); nodecopy[nodename->slen] = '\0'; #if defined(PJ_GETADDRINFO_USE_CFHOST) && PJ_GETADDRINFO_USE_CFHOST!=0 hostname = CFStringCreateWithCStringNoCopy(kCFAllocatorDefault, nodecopy, kCFStringEncodingASCII, kCFAllocatorNull); hostRef = CFHostCreateWithName(kCFAllocatorDefault, hostname); if (CFHostStartInfoResolution(hostRef, kCFHostAddresses, nil)) { CFArrayRef addrRef = CFHostGetAddressing(hostRef, nil); i = 0; if (addrRef != nil) { CFIndex idx, naddr; naddr = CFArrayGetCount(addrRef); for (idx = 0; idx < naddr && i < *count; idx++) { struct sockaddr *addr; addr = (struct sockaddr *) CFDataGetBytePtr(CFArrayGetValueAtIndex(addrRef, idx)); /* This should not happen. */ pj_assert(addr); /* Ignore unwanted address families */ if (af!=PJ_AF_UNSPEC && addr->sa_family != af) continue; /* Store canonical name */ pj_ansi_strcpy(ai[i].ai_canonname, nodecopy); /* Store address */ PJ_ASSERT_ON_FAIL(sizeof(*addr) <= sizeof(pj_sockaddr), continue); pj_memcpy(&ai[i].ai_addr, addr, sizeof(*addr)); PJ_SOCKADDR_RESET_LEN(&ai[i].ai_addr); i++; } } *count = i; } else {
void printKextInfo(CFDictionaryRef kextInfo, KextstatArgs * toolArgs) { CFBooleanRef isKernelComponent = NULL; // do not release CFNumberRef loadTag = NULL; // do not release CFNumberRef retainCount = NULL; // do not release CFNumberRef loadAddress = NULL; // do not release CFNumberRef loadSize = NULL; // do not release CFNumberRef wiredSize = NULL; // do not release CFStringRef bundleID = NULL; // do not release CFStringRef bundleVersion = NULL; // do not release CFArrayRef dependencyLoadTags = NULL; // do not release CFMutableArrayRef sortedLoadTags = NULL; // must release uint32_t loadTagValue = kOSKextInvalidLoadTag; uint32_t retainCountValue = (uint32_t)-1; uint64_t loadAddressValue = (uint64_t)-1; uint32_t loadSizeValue = (uint32_t)-1; uint32_t wiredSizeValue = (uint32_t)-1; uint32_t cpuTypeValue = (uint32_t)-1; uint32_t cpuSubTypeValue = (uint32_t)-1; char * bundleIDCString = NULL; // must free char * bundleVersionCString = NULL; // must free CFIndex count, i; loadTag = (CFNumberRef)CFDictionaryGetValue(kextInfo, CFSTR(kOSBundleLoadTagKey)); retainCount = (CFNumberRef)CFDictionaryGetValue(kextInfo, CFSTR(kOSBundleRetainCountKey)); loadAddress = (CFNumberRef)CFDictionaryGetValue(kextInfo, CFSTR(kOSBundleLoadAddressKey)); loadSize = (CFNumberRef)CFDictionaryGetValue(kextInfo, CFSTR(kOSBundleLoadSizeKey)); wiredSize = (CFNumberRef)CFDictionaryGetValue(kextInfo, CFSTR(kOSBundleWiredSizeKey)); bundleID = (CFStringRef)CFDictionaryGetValue(kextInfo, kCFBundleIdentifierKey); bundleVersion = (CFStringRef)CFDictionaryGetValue(kextInfo, kCFBundleVersionKey); dependencyLoadTags = (CFArrayRef)CFDictionaryGetValue(kextInfo, CFSTR(kOSBundleDependenciesKey)); /* If the -k flag was given, skip any kernel components unless * they are explicitly requested. */ if (toolArgs->flagNoKernelComponents) { isKernelComponent = (CFBooleanRef)CFDictionaryGetValue(kextInfo, CFSTR(kOSKernelResourceKey)); if (isKernelComponent && CFBooleanGetValue(isKernelComponent)) { if (bundleID && kCFNotFound == CFArrayGetFirstIndexOfValue(toolArgs->bundleIDs, RANGE_ALL(toolArgs->bundleIDs), bundleID)) { goto finish; } } } if (!getNumValue(loadTag, kCFNumberSInt32Type, &loadTagValue)) { loadTagValue = kOSKextInvalidLoadTag; } /* Never print the info for the kernel (loadTag 0, id __kernel__). */ if (loadTagValue == 0) { goto finish; } if (!getNumValue(retainCount, kCFNumberSInt32Type, &retainCountValue)) { retainCountValue = (uint32_t)-1; } if (!getNumValue(loadAddress, kCFNumberSInt64Type, &loadAddressValue)) { loadAddressValue = (uint64_t)-1; } if (!getNumValue(loadSize, kCFNumberSInt32Type, &loadSizeValue)) { loadSizeValue = (uint32_t)-1; } if (!getNumValue(wiredSize, kCFNumberSInt32Type, &wiredSizeValue)) { wiredSizeValue = (uint32_t)-1; } if (!getNumValue(((CFNumberRef)CFDictionaryGetValue(kextInfo, CFSTR(kOSBundleCPUTypeKey))), kCFNumberSInt32Type, &cpuTypeValue)) { cpuTypeValue = (uint32_t)-1; } if (!getNumValue(((CFNumberRef)CFDictionaryGetValue(kextInfo, CFSTR(kOSBundleCPUSubtypeKey))), kCFNumberSInt32Type, &cpuSubTypeValue)) { cpuSubTypeValue = (uint32_t)-1; } bundleIDCString = createUTF8CStringForCFString(bundleID); bundleVersionCString = createUTF8CStringForCFString(bundleVersion); /* First column has no leading space. * * These field widths are from the old kextstat, may want to change them. */ if (loadTagValue == kOSKextInvalidLoadTag) { fprintf(stdout, "%5s", kStringInvalidShort); } else { fprintf(stdout, "%5d", loadTagValue); } if (retainCountValue == (uint32_t)-1) { fprintf(stdout, " %4s", kStringInvalidShort); } else { fprintf(stdout, " %4d", retainCountValue); } if (toolArgs->runningKernelArch->cputype & CPU_ARCH_ABI64) { if (loadAddressValue == (uint64_t)-1) { fprintf(stdout, " %-18s", kStringInvalidLong); } else { fprintf(stdout, " %#-18llx", (uint64_t)loadAddressValue); } } else { if (loadAddressValue == (uint64_t)-1) { fprintf(stdout, " %-10s", kStringInvalidLong); } else { fprintf(stdout, " %#-10x", (uint32_t)loadAddressValue); } } if (loadSizeValue == (uint32_t)-1) { fprintf(stdout, " %-10s", kStringInvalidLong); } else { fprintf(stdout, " %#-10x", loadSizeValue); } if (wiredSizeValue == (uint32_t)-1) { fprintf(stdout, " %-10s", kStringInvalidLong); } else { fprintf(stdout, " %#-10x", wiredSizeValue); } if (toolArgs->flagShowArchitecture) { // include kext cputype/cpusubtype info if (cpuTypeValue == (uint32_t) -1) { fprintf(stdout, " %10s/%-7s", kStringInvalidLong, kStringInvalidLong); } else { const NXArchInfo * archName = NXGetArchInfoFromCpuType(cpuTypeValue, cpuSubTypeValue); if (archName != NULL) { fprintf(stdout, " %-18s", archName->name); } else { fprintf(stdout, " %#010x/%#-7x", cpuTypeValue, cpuSubTypeValue); } } } fprintf(stdout, " %s", bundleIDCString ? bundleIDCString : kStringInvalidLong); fprintf(stdout, " (%s)", bundleVersionCString ? bundleVersionCString : kStringInvalidLong); if (dependencyLoadTags && CFArrayGetCount(dependencyLoadTags)) { sortedLoadTags = CFArrayCreateMutableCopy(kCFAllocatorDefault, 0, dependencyLoadTags); if (!sortedLoadTags) { OSKextLogMemError(); goto finish; } CFArraySortValues(sortedLoadTags, RANGE_ALL(sortedLoadTags), &compareNumbers, /* context */ NULL); fprintf(stdout, " <"); count = CFArrayGetCount(sortedLoadTags); for (i = 0; i < count; i++) { loadTag = (CFNumberRef)CFArrayGetValueAtIndex(sortedLoadTags, i); if (!getNumValue(loadTag, kCFNumberSInt32Type, &loadTagValue)) { loadTagValue = kOSKextInvalidLoadTag; } if (loadTagValue == kOSKextInvalidLoadTag) { fprintf(stdout, "%s%s", i == 0 ? "" : " ", kStringInvalidShort); } else { fprintf(stdout, "%s%d", i == 0 ? "" : " ", loadTagValue); } } fprintf(stdout, ">"); } fprintf(stdout, "\n"); finish: SAFE_RELEASE(sortedLoadTags); SAFE_FREE(bundleIDCString); SAFE_FREE(bundleVersionCString); return; }
void wxOSXPrintData::TransferPaperInfoFrom( const wxPrintData &data ) { PMPrinter printer; PMSessionGetCurrentPrinter(m_macPrintSession, &printer); wxSize papersize = wxDefaultSize; const wxPaperSize paperId = data.GetPaperId(); if ( paperId != wxPAPER_NONE && wxThePrintPaperDatabase ) { papersize = wxThePrintPaperDatabase->GetSize(paperId); if ( papersize != wxDefaultSize ) { papersize.x /= 10; papersize.y /= 10; } } else { papersize = data.GetPaperSize(); } if ( papersize != wxDefaultSize ) { papersize.x = (wxInt32) (papersize.x * mm2pt); papersize.y = (wxInt32) (papersize.y * mm2pt); double height, width; PMPaperGetHeight(m_macPaper, &height); PMPaperGetWidth(m_macPaper, &width); if ( fabs( width - papersize.x ) >= 5 || fabs( height - papersize.y ) >= 5 ) { // we have to change the current paper CFArrayRef paperlist = 0 ; if ( PMPrinterGetPaperList( printer, &paperlist ) == noErr ) { PMPaper bestPaper = kPMNoData ; CFIndex top = CFArrayGetCount(paperlist); for ( CFIndex i = 0 ; i < top ; ++ i ) { PMPaper paper = (PMPaper) CFArrayGetValueAtIndex( paperlist, i ); PMPaperGetHeight(paper, &height); PMPaperGetWidth(paper, &width); if ( fabs( width - papersize.x ) < 5 && fabs( height - papersize.y ) < 5 ) { // TODO test for duplicate hits and use additional // criteria for best match bestPaper = paper; } } PMPaper paper = kPMNoData; if ( bestPaper == kPMNoData ) { const PMPaperMargins margins = { 0.0, 0.0, 0.0, 0.0 }; wxString id, name(wxT("Custom paper")); id.Printf(wxT("wxPaperCustom%dx%d"), papersize.x, papersize.y); if ( PMPaperCreateCustom ( printer, wxCFStringRef(id, wxFont::GetDefaultEncoding()), wxCFStringRef(name, wxFont::GetDefaultEncoding()), papersize.x, papersize.y, &margins, &paper ) ) { bestPaper = paper; } } if ( bestPaper != kPMNoData ) { PMPageFormat pageFormat; PMCreatePageFormatWithPMPaper(&pageFormat, bestPaper); PMCopyPageFormat( pageFormat, m_macPageFormat ); PMRelease(pageFormat); PMGetPageFormatPaper(m_macPageFormat, &m_macPaper); } PMRelease(paper); } } } PMSetCopies( m_macPrintSettings , data.GetNoCopies() , false ) ; PMSetCollate(m_macPrintSettings, data.GetCollate()); if ( data.IsOrientationReversed() ) PMSetOrientation( m_macPageFormat , ( data.GetOrientation() == wxLANDSCAPE ) ? kPMReverseLandscape : kPMReversePortrait , false ) ; else PMSetOrientation( m_macPageFormat , ( data.GetOrientation() == wxLANDSCAPE ) ? kPMLandscape : kPMPortrait , false ) ; PMDuplexMode mode = 0 ; switch( data.GetDuplex() ) { case wxDUPLEX_HORIZONTAL : mode = kPMDuplexNoTumble ; break ; case wxDUPLEX_VERTICAL : mode = kPMDuplexTumble ; break ; case wxDUPLEX_SIMPLEX : default : mode = kPMDuplexNone ; break ; } PMSetDuplex( m_macPrintSettings, mode ) ; if ( data.IsOrientationReversed() ) PMSetOrientation( m_macPageFormat , ( data.GetOrientation() == wxLANDSCAPE ) ? kPMReverseLandscape : kPMReversePortrait , false ) ; else PMSetOrientation( m_macPageFormat , ( data.GetOrientation() == wxLANDSCAPE ) ? kPMLandscape : kPMPortrait , false ) ; }
nsresult nsWifiMonitor::DoScanOld() { void *apple_80211_library = dlopen( "/System/Library/PrivateFrameworks/Apple80211.framework/Apple80211", RTLD_LAZY); if (!apple_80211_library) return NS_ERROR_NOT_AVAILABLE; WirelessContextPtr wifi_context_; WirelessAttachFunction WirelessAttach_function_ = reinterpret_cast<WirelessAttachFunction>(dlsym(apple_80211_library, "WirelessAttach")); WirelessScanSplitFunction WirelessScanSplit_function_ = reinterpret_cast<WirelessScanSplitFunction>(dlsym(apple_80211_library, "WirelessScanSplit")); WirelessDetachFunction WirelessDetach_function_ = reinterpret_cast<WirelessDetachFunction>(dlsym(apple_80211_library, "WirelessDetach")); if (!WirelessAttach_function_ || !WirelessScanSplit_function_ || !WirelessDetach_function_) { dlclose(apple_80211_library); return NS_ERROR_NOT_AVAILABLE; } WIErr err = 0; err = (*WirelessAttach_function_)(&wifi_context_, 0); if (err != noErr) { printf("Error: WirelessAttach: %d\n", (int) err); dlclose(apple_80211_library); return NS_ERROR_FAILURE; } // Regularly get the access point data. nsCOMArray<nsWifiAccessPoint> lastAccessPoints; nsCOMArray<nsWifiAccessPoint> accessPoints; do { accessPoints.Clear(); CFArrayRef managed_access_points = NULL; CFArrayRef adhoc_access_points = NULL; if ((*WirelessScanSplit_function_)(wifi_context_, &managed_access_points, &adhoc_access_points, 0) != noErr) { return NS_ERROR_FAILURE; } if (managed_access_points == NULL) { return NS_ERROR_FAILURE; } int accessPointsCount = CFArrayGetCount(managed_access_points); for (int i = 0; i < accessPointsCount; ++i) { nsWifiAccessPoint* ap = new nsWifiAccessPoint(); if (!ap) continue; const WirelessNetworkInfo *access_point_info = reinterpret_cast<const WirelessNetworkInfo*>(CFDataGetBytePtr(reinterpret_cast<const CFDataRef>(CFArrayGetValueAtIndex(managed_access_points, i)))); ap->setMac(access_point_info->macAddress); // WirelessNetworkInfo::signal appears to be signal strength in dBm. ap->setSignal(access_point_info->signal); ap->setSSID(reinterpret_cast<const char*>(access_point_info->name), access_point_info->nameLen); accessPoints.AppendObject(ap); } PRBool accessPointsChanged = !AccessPointsEqual(accessPoints, lastAccessPoints); nsCOMArray<nsIWifiListener> currentListeners; { nsAutoMonitor mon(mMonitor); for (PRUint32 i = 0; i < mListeners.Length(); i++) { if (!mListeners[i].mHasSentData || accessPointsChanged) { mListeners[i].mHasSentData = PR_TRUE; currentListeners.AppendObject(mListeners[i].mListener); } } } ReplaceArray(lastAccessPoints, accessPoints); if (currentListeners.Count() > 0) { PRUint32 resultCount = lastAccessPoints.Count(); nsIWifiAccessPoint** result = static_cast<nsIWifiAccessPoint**> (nsMemory::Alloc(sizeof(nsIWifiAccessPoint*) * resultCount)); if (!result) { dlclose(apple_80211_library); return NS_ERROR_OUT_OF_MEMORY; } for (PRUint32 i = 0; i < resultCount; i++) result[i] = lastAccessPoints[i]; for (PRInt32 i = 0; i < currentListeners.Count(); i++) { LOG(("About to send data to the wifi listeners\n")); nsCOMPtr<nsIWifiListener> proxy; nsCOMPtr<nsIProxyObjectManager> proxyObjMgr = do_GetService("@mozilla.org/xpcomproxy;1"); proxyObjMgr->GetProxyForObject(NS_PROXY_TO_MAIN_THREAD, NS_GET_IID(nsIWifiListener), currentListeners[i], NS_PROXY_SYNC | NS_PROXY_ALWAYS, getter_AddRefs(proxy)); if (!proxy) { LOG(("There is no proxy available. this should never happen\n")); } else { nsresult rv = proxy->OnChange(result, resultCount); LOG( ("... sent %d\n", rv)); } } nsMemory::Free(result); } // wait for some reasonable amount of time. pref? LOG(("waiting on monitor\n")); nsAutoMonitor mon(mMonitor); mon.Wait(PR_SecondsToInterval(60)); } while (mKeepGoing); (*WirelessDetach_function_)(wifi_context_); dlclose(apple_80211_library); return NS_OK; }
/*********************************************************************** * ChangeDisplaySettingsEx (MACDRV.@) * */ LONG CDECL macdrv_ChangeDisplaySettingsEx(LPCWSTR devname, LPDEVMODEW devmode, HWND hwnd, DWORD flags, LPVOID lpvoid) { LONG ret = DISP_CHANGE_BADMODE; int bpp; DEVMODEW dm; BOOL def_mode = TRUE; struct macdrv_display *displays; int num_displays; CFArrayRef display_modes; CFIndex count, i, safe, best; CGDisplayModeRef best_display_mode; uint32_t best_io_flags; TRACE("%s %p %p 0x%08x %p\n", debugstr_w(devname), devmode, hwnd, flags, lpvoid); if (devmode) { /* this is the minimal dmSize that XP accepts */ if (devmode->dmSize < FIELD_OFFSET(DEVMODEW, dmFields)) return DISP_CHANGE_FAILED; if (devmode->dmSize >= FIELD_OFFSET(DEVMODEW, dmFields) + sizeof(devmode->dmFields)) { if (((devmode->dmFields & DM_BITSPERPEL) && devmode->dmBitsPerPel) || ((devmode->dmFields & DM_PELSWIDTH) && devmode->dmPelsWidth) || ((devmode->dmFields & DM_PELSHEIGHT) && devmode->dmPelsHeight) || ((devmode->dmFields & DM_DISPLAYFREQUENCY) && devmode->dmDisplayFrequency)) def_mode = FALSE; } } if (def_mode) { if (!macdrv_EnumDisplaySettingsEx(devname, ENUM_REGISTRY_SETTINGS, &dm, 0)) { ERR("Default mode not found!\n"); return DISP_CHANGE_BADMODE; } TRACE("Return to original display mode\n"); devmode = &dm; } if ((devmode->dmFields & (DM_PELSWIDTH | DM_PELSHEIGHT)) != (DM_PELSWIDTH | DM_PELSHEIGHT)) { WARN("devmode doesn't specify the resolution: %04x\n", devmode->dmFields); return DISP_CHANGE_BADMODE; } if (macdrv_get_displays(&displays, &num_displays)) return DISP_CHANGE_FAILED; display_modes = copy_display_modes(displays[0].displayID); if (!display_modes) { macdrv_free_displays(displays); return DISP_CHANGE_FAILED; } bpp = get_default_bpp(); if ((devmode->dmFields & DM_BITSPERPEL) && devmode->dmBitsPerPel != bpp) TRACE("using default %d bpp instead of caller's request %d bpp\n", bpp, devmode->dmBitsPerPel); TRACE("looking for %dx%dx%dbpp @%d Hz", (devmode->dmFields & DM_PELSWIDTH ? devmode->dmPelsWidth : 0), (devmode->dmFields & DM_PELSHEIGHT ? devmode->dmPelsHeight : 0), bpp, (devmode->dmFields & DM_DISPLAYFREQUENCY ? devmode->dmDisplayFrequency : 0)); if (devmode->dmFields & DM_DISPLAYFIXEDOUTPUT) TRACE(" %sstretched", devmode->dmDisplayFixedOutput == DMDFO_STRETCH ? "" : "un"); if (devmode->dmFields & DM_DISPLAYFLAGS) TRACE(" %sinterlaced", devmode->dmDisplayFlags & DM_INTERLACED ? "" : "non-"); TRACE("\n"); safe = -1; best_display_mode = NULL; count = CFArrayGetCount(display_modes); for (i = 0; i < count; i++) { CGDisplayModeRef display_mode = (CGDisplayModeRef)CFArrayGetValueAtIndex(display_modes, i); uint32_t io_flags = CGDisplayModeGetIOFlags(display_mode); int mode_bpp = display_mode_bits_per_pixel(display_mode); size_t width = CGDisplayModeGetWidth(display_mode); size_t height = CGDisplayModeGetHeight(display_mode); if (!(io_flags & kDisplayModeValidFlag) || !(io_flags & kDisplayModeSafeFlag)) continue; safe++; if (bpp != mode_bpp) continue; if (devmode->dmFields & DM_PELSWIDTH) { if (devmode->dmPelsWidth != width) continue; } if (devmode->dmFields & DM_PELSHEIGHT) { if (devmode->dmPelsHeight != height) continue; } if ((devmode->dmFields & DM_DISPLAYFREQUENCY) && devmode->dmDisplayFrequency != 0) { double refresh_rate = CGDisplayModeGetRefreshRate(display_mode); if (!refresh_rate) refresh_rate = 60; if (devmode->dmDisplayFrequency != (DWORD)refresh_rate) continue; } if (devmode->dmFields & DM_DISPLAYFLAGS) { if (!(devmode->dmDisplayFlags & DM_INTERLACED) != !(io_flags & kDisplayModeInterlacedFlag)) continue; } else if (best_display_mode) { if (io_flags & kDisplayModeInterlacedFlag && !(best_io_flags & kDisplayModeInterlacedFlag)) continue; else if (!(io_flags & kDisplayModeInterlacedFlag) && best_io_flags & kDisplayModeInterlacedFlag) goto better; } if (devmode->dmFields & DM_DISPLAYFIXEDOUTPUT) { if (!(devmode->dmDisplayFixedOutput == DMDFO_STRETCH) != !(io_flags & kDisplayModeStretchedFlag)) continue; } else if (best_display_mode) { if (io_flags & kDisplayModeStretchedFlag && !(best_io_flags & kDisplayModeStretchedFlag)) continue; else if (!(io_flags & kDisplayModeStretchedFlag) && best_io_flags & kDisplayModeStretchedFlag) goto better; } if (best_display_mode) continue; better: best_display_mode = display_mode; best = safe; best_io_flags = io_flags; } if (best_display_mode) { /* we have a valid mode */ TRACE("Requested display settings match mode %ld\n", best); if ((flags & CDS_UPDATEREGISTRY) && !write_registry_settings(devmode)) { WARN("Failed to update registry\n"); ret = DISP_CHANGE_NOTUPDATED; } else if (flags & (CDS_TEST | CDS_NORESET)) ret = DISP_CHANGE_SUCCESSFUL; else if (macdrv_set_display_mode(&displays[0], best_display_mode)) { int mode_bpp = display_mode_bits_per_pixel(best_display_mode); size_t width = CGDisplayModeGetWidth(best_display_mode); size_t height = CGDisplayModeGetHeight(best_display_mode); SendMessageW(GetDesktopWindow(), WM_MACDRV_UPDATE_DESKTOP_RECT, mode_bpp, MAKELPARAM(width, height)); ret = DISP_CHANGE_SUCCESSFUL; } else { WARN("Failed to set display mode\n"); ret = DISP_CHANGE_FAILED; } } else { /* no valid modes found */ ERR("No matching mode found %ux%ux%d @%u!\n", devmode->dmPelsWidth, devmode->dmPelsHeight, bpp, devmode->dmDisplayFrequency); } CFRelease(display_modes); macdrv_free_displays(displays); return ret; }
__private_extern__ kern_return_t _io_pm_hid_event_report_activity( mach_port_t server, audit_token_t token, int _action) { pid_t callerPID; CFNumberRef appPID = NULL; int _app_pid_; CFMutableDictionaryRef foundDictionary = NULL; CFMutableArrayRef bucketsArray = NULL; CFDataRef dataEvent = NULL; IOPMHIDPostEventActivityWindow *ev = NULL; CFAbsoluteTime timeNow = CFAbsoluteTimeGetCurrent(); int arrayCount = 0; int i = 0; // Unwrapping big data structure... if (!gHIDEventHistory) { gHIDEventHistory = CFArrayCreateMutable(0, 1, &kCFTypeArrayCallBacks); } if (!gHIDEventHistory) { goto exit; } audit_token_to_au32(token, NULL, NULL, NULL, NULL, NULL, &callerPID, NULL, NULL); if (0 !=(arrayCount = CFArrayGetCount(gHIDEventHistory))) { // Scan through the array to find an existing dictionary for the given pid for (i=0; i<arrayCount; i++) { CFMutableDictionaryRef dictionaryForApp = NULL; dictionaryForApp = (CFMutableDictionaryRef)CFArrayGetValueAtIndex(gHIDEventHistory, i); if (!dictionaryForApp) { break; } appPID = CFDictionaryGetValue(dictionaryForApp, kIOPMHIDAppPIDKey); if (appPID) { CFNumberGetValue(appPID, kCFNumberIntType, &_app_pid_); if (callerPID == _app_pid_) { foundDictionary = dictionaryForApp; break; } } } } // Unwrapping big data structure... if (!foundDictionary) { foundDictionary = CFDictionaryCreateMutable(0, 3, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFArrayAppendValue(gHIDEventHistory, foundDictionary); CFRelease(foundDictionary); /* Tag our pid */ appPID = CFNumberCreate(0, kCFNumberIntType, &callerPID); if (appPID) { CFDictionarySetValue(foundDictionary, kIOPMHIDAppPIDKey, appPID); CFRelease(appPID); } /* Tag the process name */ CFStringRef appName = NULL; char appBuf[MAXPATHLEN]; int len = proc_name(callerPID, appBuf, MAXPATHLEN); if (0 != len) { appName = CFStringCreateWithCString(0, appBuf, kCFStringEncodingMacRoman); if (appName) { CFDictionarySetValue(foundDictionary, kIOPMHIDAppPathKey, appName); CFRelease(appName); } } } if (!foundDictionary) goto exit; // Unwrapping big data structure... bucketsArray = (CFMutableArrayRef)CFDictionaryGetValue(foundDictionary, kIOPMHIDHistoryArrayKey); if (!bucketsArray) { bucketsArray = CFArrayCreateMutable(0, 1, &kCFTypeArrayCallBacks); CFDictionarySetValue(foundDictionary, kIOPMHIDHistoryArrayKey, bucketsArray); CFRelease(bucketsArray); } if (!bucketsArray) goto exit; // Check last HID event bucket timestamp - is it more than 5 minutes old? bool foundWindowForEvent = false; if (0 < CFArrayGetCount(bucketsArray)) { dataEvent = (CFDataRef)CFArrayGetValueAtIndex(bucketsArray, 0); } if (dataEvent) { ev = (IOPMHIDPostEventActivityWindow *)CFDataGetBytePtr(dataEvent); if (timeNow < (ev->eventWindowStart + kFiveMinutesInSeconds)) { // This HID event gets dropped into this existing 5 minute bucket. // We bump the count for HID activity! if (__NX_NULL_EVENT == _action) { ev->nullEventCount++; } else { ev->hidEventCount++; } foundWindowForEvent = true; } } if (!foundWindowForEvent) { IOPMHIDPostEventActivityWindow newv; // We align the starts of our windows with 5 minute intervals newv.eventWindowStart = ((int)timeNow / (int)kFiveMinutesInSeconds) * kFiveMinutesInSeconds; newv.nullEventCount = newv.hidEventCount = 0; if (__NX_NULL_EVENT == _action) { newv.nullEventCount++; } else { newv.hidEventCount++; } dataEvent = CFDataCreate(0, (const UInt8 *)&newv, sizeof(IOPMHIDPostEventActivityWindow)); if (dataEvent) { CFArrayInsertValueAtIndex(bucketsArray, 0, dataEvent); CFRelease(dataEvent); } // If we've recorded more than kMaxFiveMinutesWindowsCount activity windows for this process, delete the old ones. while (kMaxFiveMinutesWindowsCount < CFArrayGetCount(bucketsArray)) { CFArrayRemoveValueAtIndex(bucketsArray, CFArrayGetCount(bucketsArray) - 1); } } exit: return KERN_SUCCESS; }
static SCNetworkServiceRef _find_service(char *match) { Boolean allowIndex = TRUE; CFIndex i; CFIndex n; CFStringRef select_name = NULL; SCNetworkServiceRef selected = NULL; if (services == NULL) { if (net_set == NULL) { SCPrint(TRUE, stdout, CFSTR("set not selected\n")); return NULL; } services = SCNetworkSetCopyServices(net_set); if (services == NULL) { SCPrint(TRUE, stdout, CFSTR("%s\n"), SCErrorString(SCError())); return NULL; } allowIndex = FALSE; } // try to select the service by its serviceID select_name = CFStringCreateWithCString(NULL, match, kCFStringEncodingUTF8); n = CFArrayGetCount(services); for (i = 0; i < n; i++) { SCNetworkServiceRef service; CFStringRef serviceID; service = CFArrayGetValueAtIndex(services, i); serviceID = SCNetworkServiceGetServiceID(service); if (CFEqual(select_name, serviceID)) { selected = service; goto done; } } // try to select the service by its name for (i = 0; i < n; i++) { SCNetworkServiceRef service; CFStringRef serviceName; service = CFArrayGetValueAtIndex(services, i); serviceName = SCNetworkServiceGetName(service); if ((serviceName != NULL) && CFEqual(select_name, serviceName)) { if (selected == NULL) { selected = service; } else { // if multiple services match selected = NULL; SCPrint(TRUE, stdout, CFSTR("multiple services match\n")); goto done; } } } if (selected != NULL) { goto done; } // try to select the service by its name (case insensitive) for (i = 0; i < n; i++) { SCNetworkServiceRef service; CFStringRef serviceName; service = CFArrayGetValueAtIndex(services, i); serviceName = SCNetworkServiceGetName(service); if ((serviceName != NULL) && CFStringCompare(select_name, serviceName, kCFCompareCaseInsensitive) == kCFCompareEqualTo) { if (selected == NULL) { selected = service; } else { // if multiple services match selected = NULL; SCPrint(TRUE, stdout, CFSTR("multiple services match\n")); goto done; } } } if (selected != NULL) { goto done; } // try to select the service by its [BSD] interface name for (i = 0; i < n; i++) { SCNetworkInterfaceRef interface; CFStringRef interfaceName = NULL; SCNetworkServiceRef service; service = CFArrayGetValueAtIndex(services, i); interface = SCNetworkServiceGetInterface(service); while ((interface != NULL) && (interfaceName == NULL)) { interfaceName = SCNetworkInterfaceGetBSDName(interface); if (interfaceName == NULL) { interface = SCNetworkInterfaceGetInterface(interface); } } if (interfaceName == NULL) { continue; } if (CFStringCompare(select_name, interfaceName, kCFCompareCaseInsensitive) == kCFCompareEqualTo) { if (selected == NULL) { selected = service; } else { // if multiple services match selected = NULL; SCPrint(TRUE, stdout, CFSTR("multiple services match\n")); goto done; } } } if (selected != NULL) { goto done; } // try to select the service by its index if (allowIndex) { char *end; char *str = match; long val; errno = 0; val = strtol(str, &end, 10); if ((*str != '\0') && (*end == '\0') && (errno == 0)) { if ((val > 0) && (val <= n)) { selected = CFArrayGetValueAtIndex(services, val - 1); } } } if (selected != NULL) { goto done; } SCPrint(TRUE, stdout, CFSTR("no match, which service?\n")); done : if (select_name != NULL) CFRelease(select_name); return selected; }
int trusted_cert_dump(int argc, char * const *argv) { CFArrayRef certArray = NULL; OSStatus ortn = noErr; CFIndex numCerts; CFIndex dex; CFArrayRef trustSettings; int ourRtn = 0; SecTrustSettingsDomain domain = kSecTrustSettingsDomainUser; extern char *optarg; extern int optind; int arg; optind = 1; while ((arg = getopt(argc, argv, "sdh")) != -1) { switch (arg) { case 's': domain = kSecTrustSettingsDomainSystem; break; case 'd': domain = kSecTrustSettingsDomainAdmin; break; default: case 'h': return 2; /* @@@ Return 2 triggers usage message. */ } } if(optind != argc) { return 2; /* @@@ Return 2 triggers usage message. */ } ortn = SecTrustSettingsCopyCertificates(domain, &certArray); if(ortn) { cssmPerror("SecTrustSettingsCopyCertificates", ortn); return 1; } numCerts = CFArrayGetCount(certArray); printf("Number of trusted certs = %ld\n", (long)numCerts); for(dex=0; dex<numCerts; dex++) { SecCertificateRef certRef = (SecCertificateRef)CFArrayGetValueAtIndex(certArray, dex); if(CFGetTypeID(certRef) != SecCertificateGetTypeID()) { fprintf(stderr, "***Bad CFGetTypeID for cert %ld\n", (long)dex); ourRtn = -1; break; } /* always print the cert's label */ printf("Cert %ld: ", dex); printCertLabel(certRef); printf("\n"); /* see if the cert has any usage constraints (it should!) */ ortn = SecTrustSettingsCopyTrustSettings(certRef, domain, &trustSettings); if(ortn) { cssmPerror("SecTrustSettingsCopyTrustSettings", ortn); ourRtn = -1; continue; } if(displayTrustSettings(trustSettings)) { ourRtn = -1; } } CFRelease(certArray); return ourRtn; }