/*
 * Parse file extension and attempt to map it to format and type. Returns true
 * on success.
 */
bool impExpImportParseFileExten(
	CFStringRef			fstr,
	SecExternalFormat   *inputFormat,   // RETURNED
	SecExternalItemType	*itemType)		// RETURNED
{
	if(fstr == NULL) {
		/* nothing to work with */
		return false;
	}
	if(CFStringHasSuffix(fstr, CFSTR(".cer")) ||
	   CFStringHasSuffix(fstr, CFSTR(".crt"))) {
		*inputFormat = kSecFormatX509Cert;
		*itemType = kSecItemTypeCertificate;
		SecImpInferDbg("Inferring kSecFormatX509Cert from file name");
		return true;
	}
	if(CFStringHasSuffix(fstr, CFSTR(".p12")) ||
	   CFStringHasSuffix(fstr, CFSTR(".pfx"))) {
		*inputFormat = kSecFormatPKCS12;
		*itemType = kSecItemTypeAggregate;
		SecImpInferDbg("Inferring kSecFormatPKCS12 from file name");
		return true;
	}

	/* Get extension, look for key indicators as substrings */
	CFURLRef url = CFURLCreateWithString(NULL, fstr, NULL);
	if(url == NULL) {
		SecImpInferDbg("impExpImportParseFileExten: error creating URL");
		return false;
	}
	CFStringRef exten = CFURLCopyPathExtension(url);
	CFRelease(url);
	if(exten == NULL) {
		/* no extension, app probably passed in only an extension */
		exten = fstr;
		CFRetain(exten);
	}
	bool ortn = false;
	CFRange cfr;
	cfr = CFStringFind(exten, CFSTR("p7"), kCFCompareCaseInsensitive);
	if(cfr.length != 0) {
		*inputFormat = kSecFormatPKCS7;
		*itemType = kSecItemTypeAggregate;
		SecImpInferDbg("Inferring kSecFormatPKCS7 from file name");
		ortn = true;
	}
	if(!ortn) {
		cfr = CFStringFind(exten, CFSTR("p8"), kCFCompareCaseInsensitive);
		if(cfr.length != 0) {
			*inputFormat = kSecFormatWrappedPKCS8;
			*itemType = kSecItemTypePrivateKey;
			SecImpInferDbg("Inferring kSecFormatPKCS8 from file name");
			ortn = true;
		}
	}
	CFRelease(exten);
	return ortn;
}
Beispiel #2
0
void _CFFSGetLastPathComponent(CFStringRef* result, CFStringRef path) {
    if (!result) {
        return;
    }
    if (!path) {
        *result = NULL;
        return;
    }

    CFRange slash = CFStringFind(path, CFSTR("/"), kCFCompareBackwards);
    if (slash.location == kCFNotFound) {
        *result = (CFStringRef)CFRetain(path);
        return;
    }

    CFIndex lastSlashLocation = CFStringGetLength(path);
    while (slash.location == lastSlashLocation - 1) {
        lastSlashLocation = slash.location;
        Boolean found = CFStringFindWithOptions(
            path,
            CFSTR("/"),
            CFRangeMake(0, lastSlashLocation),
            kCFCompareBackwards,
            &slash);
        if (!found) {
            slash.location = -1;
            break;
        }
    }
    slash.location += 1;
    *result = CFStringCreateWithSubstring(
        kCFAllocatorDefault,
        path,
        CFRangeMake(slash.location, lastSlashLocation - slash.location));
}
CFArrayRef copyTrustedAppListFromBundle(CFStringRef bundlePath, CFStringRef trustedAppListFileName)
{
	CFStringRef errorString = nil;
    CFURLRef bundleURL,trustedAppsURL = NULL;
    CFBundleRef secBundle = NULL;
	CFPropertyListRef trustedAppsPlist = NULL;
	CFDataRef xmlDataRef = NULL;
	SInt32 errorCode;
    CFArrayRef trustedAppList = NULL;
	CFMutableStringRef trustedAppListFileNameWithoutExtension = NULL;

    // Make a CFURLRef from the CFString representation of the bundleÕs path.
    bundleURL = CFURLCreateWithFileSystemPath(
        kCFAllocatorDefault,bundlePath,kCFURLPOSIXPathStyle,true);

	CFRange wholeStrRange;

	if (!bundleURL)
        goto xit;

    // Make a bundle instance using the URLRef.
    secBundle = CFBundleCreate(kCFAllocatorDefault,bundleURL);
    if (!secBundle)
        goto xit;

	trustedAppListFileNameWithoutExtension =
		CFStringCreateMutableCopy(NULL,CFStringGetLength(trustedAppListFileName),trustedAppListFileName);
	wholeStrRange = CFStringFind(trustedAppListFileName,CFSTR(".plist"),0);

	CFStringDelete(trustedAppListFileNameWithoutExtension,wholeStrRange);

    // Look for a resource in the bundle by name and type
    trustedAppsURL = CFBundleCopyResourceURL(secBundle,trustedAppListFileNameWithoutExtension,CFSTR("plist"),NULL);
    if (!trustedAppsURL)
        goto xit;

    if ( trustedAppListFileNameWithoutExtension )
		CFRelease(trustedAppListFileNameWithoutExtension);

	if (!CFURLCreateDataAndPropertiesFromResource(kCFAllocatorDefault,trustedAppsURL,&xmlDataRef,NULL,NULL,&errorCode))
        goto xit;

	trustedAppsPlist = CFPropertyListCreateFromXMLData(kCFAllocatorDefault,xmlDataRef,kCFPropertyListImmutable,&errorString);
    trustedAppList = (CFArrayRef)trustedAppsPlist;

xit:
    if (bundleURL)
        CFRelease(bundleURL);
    if (secBundle)
        CFRelease(secBundle);
    if (trustedAppsURL)
        CFRelease(trustedAppsURL);
    if (xmlDataRef)
        CFRelease(xmlDataRef);
    if (errorString)
        CFRelease(errorString);

    return trustedAppList;
}
static void normalizeWebResourceURL(CFMutableStringRef webResourceURL)
{
    static CFIndex fileUrlLength = CFStringGetLength(CFSTR("file://"));
    CFRange layoutTestsWebArchivePathRange = CFStringFind(webResourceURL, CFSTR("/LayoutTests/"), kCFCompareBackwards);
    if (layoutTestsWebArchivePathRange.location == kCFNotFound)
        return;
    CFRange currentWorkingDirectoryRange = CFRangeMake(fileUrlLength, layoutTestsWebArchivePathRange.location - fileUrlLength);
    CFStringReplace(webResourceURL, currentWorkingDirectoryRange, CFSTR(""));
}
int sectask_11_sectask_audittoken(int argc, char *const *argv)
{
    SecTaskRef task=NULL;
    CFStringRef appId=NULL;
    CFStringRef signingIdentifier=NULL;

    plan_tests(6);

    init_self_audittoken();

    ok(task=SecTaskCreateWithAuditToken(kCFAllocatorDefault, g_self_audittoken), "SecTaskCreateFromAuditToken");
    require(task, out);

    /* TODO: remove the todo once xcode signs simulator binaries */
SKIP: {
#if TARGET_IPHONE_SIMULATOR
    todo("no entitlements in the simulator binaries yet, until <rdar://problem/12194625>");
#endif
    ok(appId=SecTaskCopyValueForEntitlement(task, kSecEntitlementApplicationIdentifier, NULL), "SecTaskCopyValueForEntitlement");
    skip("appId is NULL", 1, appId);
    ok(CFEqual(appId, CFSTR("com.apple.security.regressions")), "Application Identifier match");
    ok(signingIdentifier=SecTaskCopySigningIdentifier(task, NULL), "SecTaskCopySigningIdentifier");
    ok(CFEqual(signingIdentifier, CFBundleGetIdentifier(CFBundleGetMainBundle())), "CodeSigning Identifier match");
}

    pid_t pid = getpid();
    CFStringRef name = copyProcName(pid);
    CFStringRef pidstr = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("[%d]"), pid);
    CFStringRef desc = CFCopyDescription(task);

    ok(CFStringFind(desc, name, 0).location != kCFNotFound, "didn't find name: %@ vs %@", desc, name);
    ok(CFStringFind(desc, pidstr, 0).location != kCFNotFound, "didn't find pidstr: %@ vs %@", desc, pidstr);

    CFReleaseSafe(name);
    CFReleaseSafe(desc);
    CFReleaseSafe(pidstr);

out:
    CFReleaseSafe(task);
    CFReleaseSafe(appId);
    CFReleaseSafe(signingIdentifier);

    return 0;
}
__private_extern__ CFDictionaryRef
__copyProtocolTemplate(CFStringRef      interfaceType,
		       CFStringRef      childInterfaceType,
		       CFStringRef      protocolType)
{
	CFDictionaryRef interface       = NULL;
	CFDictionaryRef protocol	= NULL;
	CFDictionaryRef protocols;
	CFDictionaryRef templates;

	templates = __copyTemplates();
	if (templates == NULL) {
		return NULL;
	}

	protocols = CFDictionaryGetValue(templates, CFSTR("Protocol"));
	if (!isA_CFDictionary(protocols)) {
		CFRelease(templates);
		return NULL;
	}

	if (childInterfaceType == NULL) {
		interface = CFDictionaryGetValue(protocols, interfaceType);
	} else {
		CFStringRef     expandedType;

		if (CFStringFind(childInterfaceType, CFSTR("."), 0).location != kCFNotFound) {
			// if "vendor" type
			childInterfaceType = CFSTR("*");
		}

		expandedType = CFStringCreateWithFormat(NULL,
							NULL,
							CFSTR("%@-%@"),
							interfaceType,
							childInterfaceType);
		interface = CFDictionaryGetValue(protocols, expandedType);
		CFRelease(expandedType);
	}

	if (isA_CFDictionary(interface)) {
		protocol = CFDictionaryGetValue(interface, protocolType);
		if (isA_CFDictionary(protocol)) {
			CFRetain(protocol);
		} else {
			protocol = NULL;
		}
	}

	CFRelease(templates);

	return protocol;
}
Beispiel #7
0
void
__NCPrint(
  FILE*       stream,
  CFStringRef format,
  va_list     argv,
  Boolean     addNewline
)
{
  CFDataRef     externalRep;
  CFStringRef   string;
  CFRange       range = CFStringFind(format,CFSTR("%!"),0);
  
  //  Look for ANSI formatting directives:
  if (range.location != kCFNotFound) {
    format = __NCParseExtendedFormatString(format);
    string = CFStringCreateWithFormatAndArguments(
                kCFAllocatorDefault,
                NULL,
                format,
                argv);
    CFRelease(format);
  } else {
    string = CFStringCreateWithFormatAndArguments(
                kCFAllocatorDefault,
                NULL,
                format,
                argv);
  }
  
  if (string) {
    externalRep = CFStringCreateExternalRepresentation(
                  kCFAllocatorDefault,
                  string,
                  CFCStringGetDefaultEncoding(),
                  '?');
    CFRelease(string);
    if (externalRep) {
      if ( addNewline )
        fprintf(stream,"%.*s\n",
            (int)CFDataGetLength(externalRep),
            (char*)CFDataGetBytePtr(externalRep)
          );
      else
        fprintf(stream,"%.*s",
            (int)CFDataGetLength(externalRep),
            (char*)CFDataGetBytePtr(externalRep)
          );
      CFRelease(externalRep);
      fflush(stream);
    }
  }  
}
Beispiel #8
0
void QuartzBitmap_Output(QuartzDesc_t dev, QuartzBitmapDevice *qbd)
{
    if(qbd->path && qbd->uti) {
        /* On 10.4+ we can employ the CGImageDestination API to create a
           variety of different bitmap formats */
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4
	char buf[PATH_MAX+1];
	snprintf(buf, PATH_MAX, qbd->path, qbd->page); buf[PATH_MAX] = '\0';
        CFStringRef pathString = CFStringCreateWithBytes(kCFAllocatorDefault, (UInt8*) buf, strlen(buf), kCFStringEncodingUTF8, FALSE);
        CFURLRef path;
        if(CFStringFind(pathString, CFSTR("://"), 0).location != kCFNotFound) {
            CFStringRef pathEscaped = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, pathString, NULL, NULL, kCFStringEncodingUTF8);
            path = CFURLCreateWithString(kCFAllocatorDefault, pathEscaped, NULL);
            CFRelease(pathEscaped);
        } else {
            path = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, (const UInt8*) buf, strlen(buf), FALSE);
        }
        CFRelease(pathString);

        CFStringRef scheme = CFURLCopyScheme(path);
       	CFStringRef type  = CFStringCreateWithBytes(kCFAllocatorDefault, (UInt8*) qbd->uti, strlen(qbd->uti), kCFStringEncodingUTF8, FALSE);
    	CGImageRef image = CGBitmapContextCreateImage(qbd->bitmap);
        if(CFStringCompare(scheme,CFSTR("file"), 0) == 0) { /* file output */
            CGImageDestinationRef dest = CGImageDestinationCreateWithURL(path, type, 1, NULL);
	    if(dest) {
		CGImageDestinationAddImage(dest, image, NULL);
		CGImageDestinationFinalize(dest);
		CFRelease(dest);
	    } else 
		error(_("QuartzBitmap_Output - unable to open file '%s'"), buf);
        } else if(CFStringCompare(scheme, CFSTR("clipboard"), 0) == 0) { /* clipboard output */
            CFMutableDataRef      data = CFDataCreateMutable(kCFAllocatorDefault, 0);
            CGImageDestinationRef dest = CGImageDestinationCreateWithData(data, type, 1, NULL);
            CGImageDestinationAddImage(dest, image, NULL);
            CGImageDestinationFinalize(dest);
            CFRelease(dest);
            PasteboardRef pb = NULL;
            if(PasteboardCreate(kPasteboardClipboard, &pb) == noErr) {
                PasteboardClear(pb);
                PasteboardSynchronize(pb);
                PasteboardPutItemFlavor(pb, (PasteboardItemID) 1, type, data, 0);
            }
            CFRelease(data);
        } else
            warning(_("not a supported scheme, no image data written"));
        CFRelease(scheme);
       	CFRelease(type);
        CFRelease(path);
        CFRelease(image);
#endif
    }
}
STATIC Boolean
applicationID_is_valid(CFStringRef applicationID)
{
    CFRange	r;

    if (CFStringGetLength(applicationID) < 3) {
	return (FALSE);
    }
    r = CFStringFind(applicationID, CFSTR("."), 0);
    if (r.location == kCFNotFound) {
	return (FALSE);
    }
    return (TRUE);
}
__private_extern__ CFDictionaryRef
__copyInterfaceTemplate(CFStringRef      interfaceType,
			CFStringRef      childInterfaceType)
{
	CFDictionaryRef interface       = NULL;
	CFDictionaryRef interfaces;
	CFDictionaryRef templates;

	templates = __copyTemplates();
	if (templates == NULL) {
		return NULL;
	}

	interfaces = CFDictionaryGetValue(templates, CFSTR("Interface"));
	if (!isA_CFDictionary(interfaces)) {
		CFRelease(templates);
		return NULL;
	}

	if (childInterfaceType == NULL) {
		interface = CFDictionaryGetValue(interfaces, interfaceType);
	} else {
		CFStringRef     expandedType;

		if (CFStringFind(childInterfaceType, CFSTR("."), 0).location != kCFNotFound) {
			// if "vendor" type
			childInterfaceType = CFSTR("*");
		}

		expandedType = CFStringCreateWithFormat(NULL,
							NULL,
							CFSTR("%@-%@"),
							interfaceType,
							childInterfaceType);
		interface = CFDictionaryGetValue(interfaces, expandedType);
		CFRelease(expandedType);
	}

	if (isA_CFDictionary(interface) && (CFDictionaryGetCount(interface) > 0)) {
		CFRetain(interface);
	} else {
		interface = NULL;
	}

	CFRelease(templates);

	return interface;
}
Beispiel #11
0
MIDIEndpointRef MIDIClient::getSource(CFStringRef name) {
    MIDIEndpointRef ret(0);
    
    for(int i=0;i<MIDIGetNumberOfSources();++i) {
        MIDIEndpointRef src = MIDIGetSource(i);
        
        CFStringRef n = getName(src);
        if(CFStringFind(name, name, kCFCompareCaseInsensitive).length == CFStringGetLength(name)) {
            CFRelease(n);
            return src;
        }
        CFRelease(n);
    }
    
    return ret;
}
Beispiel #12
0
// ____________________________________________________________________________________
// Infer an audio file type from a filename's extension.
static Boolean InferAudioFileFormatFromFilename(CFStringRef filename, AudioFileTypeID *outFiletype)
{
	OSStatus err;
	
	// find the extension in the filename.
	CFRange range = CFStringFind(filename, CFSTR("."), kCFCompareBackwards);
	if (range.location == kCFNotFound)
		return FALSE;
	range.location += 1;
	range.length = CFStringGetLength(filename) - range.location;
	CFStringRef extension = CFStringCreateWithSubstring(NULL, filename, range);
	
	UInt32 propertySize = sizeof(AudioFileTypeID);
	err = AudioFileGetGlobalInfo(kAudioFileGlobalInfo_TypesForExtension, sizeof(extension), &extension, &propertySize, outFiletype);
	CFRelease(extension);
	
	return (err == noErr && propertySize > 0);
}
Beispiel #13
0
bool	CAAudioFileFormats::InferFileFormatFromFilename(CFStringRef filename, AudioFileTypeID &filetype)
{
	bool result = false;
	CFRange range = CFStringFind(filename, CFSTR("."), kCFCompareBackwards);
	if (range.location == kCFNotFound) return false;
	range.location += 1;
	range.length = CFStringGetLength(filename) - range.location;
	CFStringRef ext = CFStringCreateWithSubstring(NULL, filename, range);
	for (int i = 0; i < mNumFileFormats; ++i) {
		FileFormatInfo *ffi = &mFileFormats[i];
		if (ffi->MatchExtension(ext)) {
			filetype = ffi->mFileTypeID;
			result = true;
			break;
		}
	}
	CFRelease(ext);
	return result;
}
/* ------------------------------------------------------------------------------------------------------

SetNumberValueFromHeader: read FITS header and set number value to attribute name.

------------------------------------------------------------------------------------------------------ */
void SetNumberValueFromFITSHeader(const char* filename, 
				CFMutableDictionaryRef attributes, 
				const char* importerAttrName, 
				char* keyword, 
				Boolean isCoordinates)
{
	CFStringRef headerValue = getCleanedHeaderValue(filename, keyword);
	
	if (headerValue != NULL) {
		double number;
		CFRange r = CFStringFind(headerValue, CFSTR(":"), 0);		
		
		if ((isCoordinates == true) && (r.location != kCFNotFound)) {
			double sign = 1.;
			CFArrayRef dmsArray = CFStringCreateArrayBySeparatingStrings(kCFAllocatorDefault, headerValue, CFSTR(":"));

			if (CFArrayGetCount(dmsArray) == 3) {			
				if (CFStringGetDoubleValue(CFArrayGetValueAtIndex(dmsArray, 0)) < 0) {
					sign = -1;
				}
									
				// Work for either DMS or HMS, since the input format is kept. It is not a transformation, just a flattening.
				number = sign * ( fabs(CFStringGetDoubleValue(CFArrayGetValueAtIndex(dmsArray, 0))) +
									   CFStringGetDoubleValue(CFArrayGetValueAtIndex(dmsArray, 1)) / 60 +
									   CFStringGetDoubleValue(CFArrayGetValueAtIndex(dmsArray, 2)) / 3600 );

			}

			CFRelease(dmsArray);
		}
		else {
			number = CFStringGetDoubleValue(headerValue);			
		}

		CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
		CFStringRef cfImporterAttrName = CFStringCreateWithCString(kCFAllocatorDefault, importerAttrName, kCFStringEncodingUTF8);
		CFDictionaryAddValue(attributes, cfImporterAttrName, value);
		CFRelease(value);
		CFRelease(cfImporterAttrName);

		CFRelease(headerValue);
	}
}
Beispiel #15
0
/*
 * Function: parse_component
 * Purpose:
 *   Given a string 'key' and a string prefix 'prefix',
 *   return the next component in the slash '/' separated
 *   key.
 *
 * Examples:
 * 1. key = "a/b/c" prefix = "a/"
 *    returns "b"
 * 2. key = "a/b/c" prefix = "a/b/"
 *    returns "c"
 */
static CFStringRef
parse_component(CFStringRef key, CFStringRef prefix)
{
	CFMutableStringRef	comp;
	CFRange			range;

	if (CFStringHasPrefix(key, prefix) == FALSE) {
		return NULL;
	}
	comp = CFStringCreateMutableCopy(NULL, 0, key);
	CFStringDelete(comp, CFRangeMake(0, CFStringGetLength(prefix)));
	range = CFStringFind(comp, CFSTR("/"), 0);
	if (range.location == kCFNotFound) {
		return comp;
	}
	range.length = CFStringGetLength(comp) - range.location;
	CFStringDelete(comp, range);
	return comp;
}
void NetworkStateNotifier::updateState()
{
    // Assume that we're offline until proven otherwise.
    m_isOnLine = false;
    
    RetainPtr<CFStringRef> str = adoptCF(SCDynamicStoreKeyCreateNetworkInterface(0, kSCDynamicStoreDomainState));
    
    RetainPtr<CFPropertyListRef> propertyList = adoptCF(SCDynamicStoreCopyValue(m_store.get(), str.get()));
    
    if (!propertyList)
        return;
    
    if (CFGetTypeID(propertyList.get()) != CFDictionaryGetTypeID())
        return;
    
    CFArrayRef netInterfaces = (CFArrayRef)CFDictionaryGetValue((CFDictionaryRef)propertyList.get(), kSCDynamicStorePropNetInterfaces);
    if (CFGetTypeID(netInterfaces) != CFArrayGetTypeID())
        return;
    
    for (CFIndex i = 0; i < CFArrayGetCount(netInterfaces); i++) {
        CFStringRef interface = (CFStringRef)CFArrayGetValueAtIndex(netInterfaces, i);
        if (CFGetTypeID(interface) != CFStringGetTypeID())
            continue;
        
        // Ignore the loopback interface.
        if (CFStringFind(interface, CFSTR("lo"), kCFCompareAnchored).location != kCFNotFound)
            continue;

        RetainPtr<CFStringRef> key = adoptCF(SCDynamicStoreKeyCreateNetworkInterfaceEntity(0, kSCDynamicStoreDomainState, interface, kSCEntNetIPv4));

        RetainPtr<CFArrayRef> keyList = adoptCF(SCDynamicStoreCopyKeyList(m_store.get(), key.get()));
    
        if (keyList && CFArrayGetCount(keyList.get())) {
            m_isOnLine = true;
            break;
        }
    }
}
boolean_t IOHIDEventSystemStatistics::open(IOHIDSessionRef session, IOOptionBits options)
{
    CFTypeRef            bootArgs = nil;
    io_registry_entry_t  entry    = IO_OBJECT_NULL;
    
    (void)session;
    (void)options;
    
    entry = IORegistryEntryFromPath(kIOMasterPortDefault, "IODeviceTree:/options");
    if(entry){
        bootArgs = IORegistryEntryCreateCFProperty(entry, CFSTR("boot-args"), nil, 0);
        if (bootArgs){
            if (CFGetTypeID(bootArgs) == CFStringGetTypeID()){
                CFRange         findRange;
                CFStringRef     bootArgsString = (CFStringRef)bootArgs;
                
                findRange = CFStringFind(bootArgsString, CFSTR("opposing-button-logging"), 0);
                
                if (findRange.length != 0)
                    _logButtonFiltering = true;
            }
            CFRelease(bootArgs);
            IOObjectRelease(entry);
        }
    }
    
    if (_logButtonFiltering) {
        _logStrings = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
        _asl = asl_open("ButtonLogging", "Button Filtering Information", 0);
        
        _logfd = ::open("/var/mobile/Library/Logs/button.log", O_CREAT | O_APPEND | O_RDWR, 0644);
        
        if ((_logfd != -1) && (_asl != NULL))
            asl_add_log_file(_asl, _logfd);
    }

    return true;
}
//	find_unique_certificate
//
//	Returns a SecKeychainItemRef for the certificate
//	in the specified keychain (or keychain list)
//	which is a unique match for either the specified name
//	or SHA-1 hash. If more than one match exists, the
//	certificate is not unique and none are returned. Caller is
//	responsible for releasing the item (with CFRelease).
//
SecKeychainItemRef
find_unique_certificate(CFTypeRef keychainOrArray,
	const char *name,
	const char *hash)
{
	OSStatus status = noErr;
	SecKeychainSearchRef searchRef = NULL;
	SecKeychainItemRef uniqueItemRef = NULL;

	status = SecKeychainSearchCreateFromAttributes(keychainOrArray, kSecCertificateItemClass, NULL, &searchRef);
	if (status) {
		return uniqueItemRef;
	}

	// check input hash string and convert to data
	CSSM_DATA hashData = { 0, NULL };
	if (hash) {
		CSSM_SIZE len = strlen(hash)/2;
		hashData.Length = len;
		hashData.Data = (uint8 *)malloc(hashData.Length);
		fromHex(hash, &hashData);
	}

	// filter candidates against the hash (or the name, if no hash provided)
	CFStringRef matchRef = (name) ? CFStringCreateWithCString(NULL, name, kCFStringEncodingUTF8) : NULL;
	Boolean exactMatch = FALSE;

	CSSM_DATA certData = { 0, NULL };
	SecKeychainItemRef candidate = NULL;

	while (SecKeychainSearchCopyNext(searchRef, &candidate) == noErr) {
		SecCertificateRef cert = (SecCertificateRef)candidate;
		if (SecCertificateGetData(cert, &certData) != noErr) {
			safe_CFRelease(&candidate);
			continue;
		}
		if (hash) {
			uint8 candidate_sha1_hash[20];
			CSSM_DATA digest;
			digest.Length = sizeof(candidate_sha1_hash);
			digest.Data = candidate_sha1_hash;
			if ((SecDigestGetData(CSSM_ALGID_SHA1, &digest, &certData) == CSSM_OK) &&
				(hashData.Length == digest.Length) &&
				(!memcmp(hashData.Data, digest.Data, digest.Length))) {
				exactMatch = TRUE;
				uniqueItemRef = candidate; // currently retained
				break; // we're done - can't get more exact than this
			}
		} else {
			// copy certificate name
			CFStringRef nameRef = NULL;
			if ((SecCertificateCopyCommonName(cert, &nameRef) != noErr) || nameRef == NULL) {
				safe_CFRelease(&candidate);
				continue; // no name, so no match is possible
			}
			CFIndex nameLen = CFStringGetLength(nameRef);
			CFIndex bufLen = 1 + CFStringGetMaximumSizeForEncoding(nameLen, kCFStringEncodingUTF8);
			char *nameBuf = (char *)malloc(bufLen);
			if (!CFStringGetCString(nameRef, nameBuf, bufLen-1, kCFStringEncodingUTF8))
				nameBuf[0]=0;

			CFRange find = { kCFNotFound, 0 };
			if (nameRef && matchRef)
				find = CFStringFind(nameRef, matchRef, kCFCompareCaseInsensitive | kCFCompareNonliteral);
			Boolean isExact = (find.location == 0 && find.length == nameLen);
			if (find.location == kCFNotFound) {
				free(nameBuf);
				safe_CFRelease(&nameRef);
				safe_CFRelease(&candidate);
				continue; // no match
			}
			if (uniqueItemRef) {	// got two matches
				if (exactMatch && !isExact)	{	// prior is better; ignore this one
					free(nameBuf);
					safe_CFRelease(&nameRef);
					safe_CFRelease(&candidate);
					continue;
				}
				if (exactMatch == isExact) {	// same class of match
					if (CFEqual(uniqueItemRef, candidate)) {	// same certificate
						free(nameBuf);
						safe_CFRelease(&nameRef);
						safe_CFRelease(&candidate);
						continue;
					}
					// ambiguity - must fail
					sec_error("\"%s\" is ambiguous, matches more than one certificate", name);
					free(nameBuf);
					safe_CFRelease(&nameRef);
					safe_CFRelease(&candidate);
					safe_CFRelease(&uniqueItemRef);
					break;
				}
				safe_CFRelease(&uniqueItemRef); // about to replace with this one
			}
			uniqueItemRef = candidate; // currently retained
			exactMatch = isExact;
			free(nameBuf);
			safe_CFRelease(&nameRef);
		}
	}

	safe_CFRelease(&searchRef);
	safe_CFRelease(&matchRef);
	if (hashData.Data) {
		free(hashData.Data);
	}

	return uniqueItemRef;
}
Beispiel #19
0
static void
booter(kickeeRef target)
{
	char			**argv		= NULL;
	char			*cmd		= NULL;
	CFStringRef		execCommand	= CFDictionaryGetValue(target->dict, CFSTR("execCommand"));
	int			i;
	CFArrayRef		keys		= NULL;
	CFStringRef		name		= CFDictionaryGetValue(target->dict, CFSTR("name"));
	int			nKeys		= 0;
	Boolean			ok		= FALSE;
	CFStringRef		postName	= CFDictionaryGetValue(target->dict, CFSTR("postName"));

	SCLog(_verbose, LOG_DEBUG, CFSTR("Kicker callback, target=%@"), name);

	if (!isA_CFString(postName) && !isA_CFString(execCommand)) {
		goto error;	/* if no notifications to post nor commands to execute */
	}

	if (isA_CFString(postName)) {
		uint32_t	status;

		/*
		 * post a notification
		 */
		cmd = _SC_cfstring_to_cstring(postName, NULL, 0, kCFStringEncodingASCII);
		if (!cmd) {
			SCLog(TRUE, LOG_DEBUG, CFSTR("  could not convert post name to C string"));
			goto error;
		}

		SCLog(TRUE, LOG_NOTICE, CFSTR("posting notification %s"), cmd);
		status = notify_post(cmd);
		if (status != NOTIFY_STATUS_OK) {
			SCLog(TRUE, LOG_DEBUG, CFSTR("  notify_post() failed: error=%ld"), status);
			goto error;
		}

		CFAllocatorDeallocate(NULL, cmd);	/* clean up */
		cmd = NULL;
	}

	/*
	 * get the arguments for the kickee
	 */
	keys = target->changedKeys;
	target->changedKeys = NULL;

	if (isA_CFString(execCommand)) {
		CFRange			bpr;
		CFNumberRef		execGID		= CFDictionaryGetValue(target->dict, CFSTR("execGID"));
		CFNumberRef		execUID		= CFDictionaryGetValue(target->dict, CFSTR("execUID"));
		CFBooleanRef		passKeys	= CFDictionaryGetValue(target->dict, CFSTR("changedKeysAsArguments"));
		gid_t			reqGID		= 0;
		uid_t			reqUID		= 0;
		CFMutableStringRef	str;

		/*
		 * build the kickee command
		 */
		str = CFStringCreateMutableCopy(NULL, 0, execCommand);
		bpr = CFStringFind(str, CFSTR("$BUNDLE"), 0);
		if (bpr.location != kCFNotFound) {
			CFStringRef	bundlePath;

			bundlePath = CFURLCopyFileSystemPath(myBundleURL, kCFURLPOSIXPathStyle);
			CFStringReplace(str, bpr, bundlePath);
			CFRelease(bundlePath);
		}

		cmd = _SC_cfstring_to_cstring(str, NULL, 0, kCFStringEncodingASCII);
		CFRelease(str);
		if (!cmd) {
			SCLog(TRUE, LOG_DEBUG, CFSTR("  could not convert command to C string"));
			goto error;
		}

		/*
		 * get the UID/GID for the kickee
		 */
		if (isA_CFNumber(execUID)) {
			CFNumberGetValue(execUID, kCFNumberIntType, &reqUID);
		}

		if (isA_CFNumber(execGID)) {
			CFNumberGetValue(execGID, kCFNumberIntType, &reqGID);
		}

		nKeys = CFArrayGetCount(keys);
		argv  = CFAllocatorAllocate(NULL, (nKeys + 2) * sizeof(char *), 0);
		for (i = 0; i < (nKeys + 2); i++) {
			argv[i] = NULL;
		}

		/* create command name argument */
		if ((argv[0] = rindex(cmd, '/')) != NULL) {
			argv[0]++;
		} else {
			argv[0] = cmd;
		}

		/* create changed key arguments */
		if (isA_CFBoolean(passKeys) && CFBooleanGetValue(passKeys)) {
			for (i = 0; i < nKeys; i++) {
				CFStringRef	key = CFArrayGetValueAtIndex(keys, i);

				argv[i+1] = _SC_cfstring_to_cstring(key, NULL, 0, kCFStringEncodingASCII);
				if (!argv[i+1]) {
					SCLog(TRUE, LOG_DEBUG, CFSTR("  could not convert argument to C string"));
					goto error;
				}
			}
		}

		SCLog(TRUE,     LOG_NOTICE, CFSTR("executing %s"), cmd);
		SCLog(_verbose, LOG_DEBUG,  CFSTR("  current uid = %d, requested = %d"), geteuid(), reqUID);

		/* this kicker is now "running" */
		target->active = TRUE;

		(void)_SCDPluginExecCommand(booterExit,
			      target,
			      reqUID,
			      reqGID,
			      cmd,
			      argv);

//		CFAllocatorDeallocate(NULL, cmd);	/* clean up */
//		cmd = NULL;
	} else {
		target->active = FALSE;
	}

	target->needsKick = FALSE;	/* allow additional requests to be queued */
	ok = TRUE;

    error :

	if (keys)	CFRelease(keys);
	if (cmd)	CFAllocatorDeallocate(NULL, cmd);
	if (argv) {
		for (i = 0; i < nKeys; i++) {
			if (argv[i+1]) {
				CFAllocatorDeallocate(NULL, argv[i+1]);
			}
		}
		CFAllocatorDeallocate(NULL, argv);
	}

	if (!ok) {
		/*
		 * If the target action can't be performed this time then
		 * there's not much point in trying again. As such, I close
		 * the session and the kickee target released.
		 */
		cleanupKicker(target);
	}

	return;
}
Beispiel #20
0
static uint32_t
fsbundle_find_fssubtype(const char *bundle_path_C,
                        const char *claimed_name_C,
                        uint32_t    claimed_fssubtype)
{
    uint32_t result = FUSE_FSSUBTYPE_UNKNOWN;

    CFStringRef bundle_path_string  = NULL;
    CFStringRef claimed_name_string = NULL;

    CFURLRef    bundleURL = NULL;
    CFBundleRef bundleRef = NULL;

    CFDictionaryRef fspersonalities = NULL;

    CFIndex idx   = 0;
    CFIndex count = 0;
    Boolean found = false;

    CFStringRef     *keys     = NULL;
    CFDictionaryRef *subdicts = NULL;

    bundle_path_string = CFStringCreateWithCString(kCFAllocatorDefault,
                                                   bundle_path_C,
                                                   kCFStringEncodingUTF8);
    if (!bundle_path_string) {
        goto out;
    }

    bundleURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault,
                                              bundle_path_string,
                                              kCFURLPOSIXPathStyle,
                                              true);
    if (!bundleURL) {
        goto out;
    }

    bundleRef = CFBundleCreate(kCFAllocatorDefault, bundleURL);
    if (!bundleRef) {
        goto out;
    }

    fspersonalities = CFBundleGetValueForInfoDictionaryKey(
                          bundleRef, CFSTR(kFSPersonalitiesKey));
    if (!fspersonalities) {
        goto out;
    }

    count = CFDictionaryGetCount(fspersonalities);
    if (count <= 0) {
        goto out;
    }

    keys = (CFStringRef *)malloc(count * sizeof(CFStringRef));
    subdicts = (CFDictionaryRef *)malloc(count * sizeof(CFDictionaryRef));

    if (!keys || !subdicts) {
        goto out;
    }

    CFDictionaryGetKeysAndValues(fspersonalities,
                                 (const void **)keys,
                                 (const void **)subdicts);

    if (claimed_fssubtype == (uint32_t)FUSE_FSSUBTYPE_INVALID) {
        goto lookupbyfsname;
    }

    for (idx = 0; idx < count; idx++) {
        CFNumberRef n = NULL;
        uint32_t candidate_fssubtype = (uint32_t)FUSE_FSSUBTYPE_INVALID;
        if (CFDictionaryGetValueIfPresent(subdicts[idx],
                                          (const void *)CFSTR(kFSSubTypeKey),
                                          (const void **)&n)) {
            if (CFNumberGetValue(n, kCFNumberIntType, &candidate_fssubtype)) {
                if (candidate_fssubtype == claimed_fssubtype) {
                    found = true;
                    result = candidate_fssubtype;
                    break;
                }
            }
        }
    }

    if (found) {
        goto out;
    }

lookupbyfsname:

    claimed_name_string = CFStringCreateWithCString(kCFAllocatorDefault,
                                                    claimed_name_C,
                                                    kCFStringEncodingUTF8);
    if (!claimed_name_string) {
        goto out;
    }

    for (idx = 0; idx < count; idx++) {
        CFRange where = CFStringFind(claimed_name_string, keys[idx],
                                     kCFCompareCaseInsensitive);
        if (where.location != kCFNotFound) {
            found = true;
        }
        if (found) {
            CFNumberRef n = NULL;
            uint32_t candidate_fssubtype = (uint32_t)FUSE_FSSUBTYPE_INVALID;
            if (CFDictionaryGetValueIfPresent(
                    subdicts[idx], (const void *)CFSTR(kFSSubTypeKey),
                    (const void **)&n)) {
                if (CFNumberGetValue(n, kCFNumberIntType,
                                     &candidate_fssubtype)) {
                    result = candidate_fssubtype;
                }
            }
            break;
        }
    }

out:
    if (keys) {
        free(keys);
    }

    if (subdicts) {
        free(subdicts);
    }

    if (bundle_path_string) {
        CFRelease(bundle_path_string);
    }

    if (bundleURL) {
        CFRelease(bundleURL);
    }

    if (claimed_name_string) {
        CFRelease(claimed_name_string);
    }

    if (bundleRef) {
        CFRelease(bundleRef);
    }

    return result;
}
Beispiel #21
0
static void addShareToDictionary(SMBHANDLE inConnection, 
								 CFMutableDictionaryRef shareDict, 
								 CFStringRef shareName,  CFStringRef comments, 
								 u_int16_t shareType, struct statfs *fs, int fs_cnt)
{
	CFMutableDictionaryRef currDict = NULL;
	CFRange foundSlash;
	CFRange	foundPercentSign;
    CFStringRef tempShareName1 = NULL;
    CFStringRef tempShareName2 = NULL;
	
	if (shareName == NULL) {
		return;
	}

	currDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, 
										 &kCFTypeDictionaryKeyCallBacks, 
										 &kCFTypeDictionaryValueCallBacks);
	if (currDict == NULL) {
		/* Log error here, but keep going */
		SMBLogInfo("addShareToDictionary: Couldn't create the dictionary!", ASL_LEVEL_DEBUG);
		return;
	}
	
	if (CFStringHasSuffix(shareName, CFSTR("$"))) {
		CFDictionarySetValue (currDict, kNetFSIsHiddenKey, kCFBooleanTrue);
	}
		
	if (comments) {
		CFDictionarySetValue (currDict, kNetCommentStrKey, comments);
	}

	switch (shareType) {
		case SMB_ST_DISK:
			CFDictionarySetValue (currDict, kNetShareTypeStrKey, CFSTR("Disk"));
			/* Now check to see if this share is already mounted */
			if (fs) {
				/* We only care if its already mounted ignore any other errors for now */
				if (SMBCheckForAlreadyMountedShare(inConnection, shareName, currDict, fs, fs_cnt) == EEXIST) {
					CFDictionarySetValue (currDict, kNetFSAlreadyMountedKey, kCFBooleanTrue);
				} else {
					CFDictionarySetValue (currDict, kNetFSAlreadyMountedKey, kCFBooleanFalse);
				}

			}
			break;
		case SMB_ST_PRINTER:
			CFDictionarySetValue (currDict, kNetShareTypeStrKey, CFSTR("Printer"));
			CFDictionarySetValue (currDict, kNetFSPrinterShareKey, kCFBooleanTrue);				
			CFDictionarySetValue (currDict, kNetFSAlreadyMountedKey, kCFBooleanFalse);
			break;
		case SMB_ST_PIPE:
			CFDictionarySetValue (currDict, kNetShareTypeStrKey, CFSTR("Pipe"));
			CFDictionarySetValue (currDict, kNetFSAlreadyMountedKey, kCFBooleanFalse);
			break;
		case SMB_ST_COMM:
			CFDictionarySetValue (currDict, kNetShareTypeStrKey, CFSTR("Comm"));
			CFDictionarySetValue (currDict, kNetFSAlreadyMountedKey, kCFBooleanFalse);
			break;
		default:
			CFDictionarySetValue (currDict, kNetShareTypeStrKey, CFSTR("Unknown"));
			CFDictionarySetValue (currDict, kNetFSAlreadyMountedKey, kCFBooleanFalse);
			break;
	}
	CFDictionarySetValue (currDict, kNetFSHasPasswordKey, kCFBooleanFalse);
    
    /* Check for a '/' or '%' in the share name */
    foundSlash = CFStringFind (shareName, CFSTR("/"), 0);
    foundPercentSign = CFStringFind (shareName, CFSTR("%"), 0);
    if ( (foundSlash.location != kCFNotFound) || (foundPercentSign.location != kCFNotFound) ) {
        /* found a '/' or '%' in the name, so set a disply name to be used */
        CFDictionarySetValue (currDict, kNetFSDisplayNameKey, shareName);
        
        /* escape the vol name to get '/' converted to %2f and '%' to %25 */
        tempShareName1 = CFURLCreateStringByAddingPercentEscapes(NULL, shareName, NULL, CFSTR("/%"), kCFStringEncodingUTF8);
        
        /* re-escape it leaving the '/' as %2f and '%' as %25 */
        tempShareName2 = CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, tempShareName1, CFSTR("/%"), kCFStringEncodingUTF8);
        
        CFDictionarySetValue (shareDict, tempShareName2, currDict);
        
        CFRelease (tempShareName1);
        CFRelease (tempShareName2);
    }
    else {
        CFDictionarySetValue (shareDict, shareName, currDict);
    }
    
	CFRelease (currDict);
}
Beispiel #22
0
void _lp_set_is_s(lp_device_t d) {
    CFStringRef name;
    MIDIObjectGetStringProperty(d->device, kMIDIPropertyName, &name);
    
    d->is_lps = CFStringFind(name, CFSTR("Launchpad S"), kCFCompareCaseInsensitive).length > 0;
}
static int
do_keychain_find_certificate(CFTypeRef keychainOrArray,
	const char *name,
	const char *emailAddress,
	Boolean print_hash,
	Boolean output_pem,
	Boolean find_all,
	Boolean print_email)
{
	OSStatus result = noErr;
    SecCertificateRef certificateRef = NULL;
	SecKeychainSearchRef searchRef = NULL;
	CFStringRef matchRef = (name) ? CFStringCreateWithCString(NULL, name, kCFStringEncodingUTF8) : NULL;

	if (find_all && emailAddress) {
		result = SecKeychainSearchCreateForCertificateByEmail(keychainOrArray, emailAddress, &searchRef);
		if (result) {
			sec_perror("SecKeychainSearchCreateForCertificateByEmail", result);
			goto cleanup;
		}
	} else {
		result = SecKeychainSearchCreateFromAttributes(keychainOrArray, kSecCertificateItemClass, NULL, &searchRef);
		if (result) {
			sec_perror("SecKeychainSearchCreateFromAttributes", result);
			goto cleanup;
		}
	}

	do
	{
		if (find_all) {
			SecKeychainItemRef itemRef = NULL;
			result = SecKeychainSearchCopyNext(searchRef, &itemRef);
			if (result == errSecItemNotFound) {
				result = 0;
				break;
			}
			else if (result) {
				sec_perror("SecKeychainSearchCopyNext", result);
				goto cleanup;
			}

			if (!emailAddress && name) {
				// match name in common name
				CFStringRef nameRef = NULL;
				if (SecCertificateCopyCommonName((SecCertificateRef)itemRef, &nameRef) != noErr) {
					safe_CFRelease(&itemRef);
					continue; // no name, so no match is possible
				}
				CFRange find = { kCFNotFound, 0 };
				if (nameRef && matchRef)
					find = CFStringFind(nameRef, matchRef, kCFCompareCaseInsensitive | kCFCompareNonliteral);
				if (find.location == kCFNotFound) {
					safe_CFRelease(&nameRef);
					safe_CFRelease(&itemRef);
					continue; // no match
				}
				safe_CFRelease(&nameRef);
			}
			safe_CFRelease(&certificateRef);
			certificateRef = (SecCertificateRef) itemRef;
		}
		else { // only want the first match
			if (emailAddress) {
				result = SecCertificateFindByEmail(keychainOrArray, emailAddress, &certificateRef);
				if (result) {
					sec_perror("SecCertificateFindByEmail", result);
					goto cleanup;
				}
			} else {
				SecKeychainItemRef itemRef = NULL;
				while ((result = SecKeychainSearchCopyNext(searchRef, &itemRef)) != errSecItemNotFound) {
					if (name) {
						// match name in common name
						CFStringRef nameRef = NULL;
						if (SecCertificateCopyCommonName((SecCertificateRef)itemRef, &nameRef) != noErr) {
							safe_CFRelease(&itemRef);
							continue; // no name, so no match is possible
						}
						CFRange find = { kCFNotFound, 0 };
						if (nameRef && matchRef)
							find = CFStringFind(nameRef, matchRef, kCFCompareCaseInsensitive | kCFCompareNonliteral);
						if (find.location == kCFNotFound) {
							safe_CFRelease(&nameRef);
							safe_CFRelease(&itemRef);
							continue; // no match
						}
						safe_CFRelease(&nameRef);
					}
					break; // we have a match!
				}
				if (result == errSecItemNotFound) {
					sec_perror("SecKeychainSearchCopyNext", result);
					goto cleanup;
				}
				certificateRef = (SecCertificateRef) itemRef;
			}
		}

		// process the found certificate

		if (print_hash) {
			uint8 sha1_hash[20];
			CSSM_DATA data;
			CSSM_DATA digest;
			digest.Length = sizeof(sha1_hash);
			digest.Data = sha1_hash;
			if ((SecCertificateGetData(certificateRef, &data) == noErr) &&
				(SecDigestGetData(CSSM_ALGID_SHA1, &digest, &data) == CSSM_OK)) {
				unsigned int i;
				uint32 len = digest.Length;
				uint8 *cp = digest.Data;
				fprintf(stdout, "SHA-1 hash: ");
				for(i=0; i<len; i++) {
					fprintf(stdout, "%02X", ((unsigned char *)cp)[i]);
				}
				fprintf(stdout, "\n");
			}
		}

		if (print_email)
		{
			CFArrayRef emailAddresses = NULL;
			CFIndex ix, count;
			result = SecCertificateCopyEmailAddresses(certificateRef, &emailAddresses);
			if (result)
			{
				sec_perror("SecCertificateCopyEmailAddresses", result);
				goto cleanup;
			}

			count = CFArrayGetCount(emailAddresses);
			fputs("email addresses: ", stdout);
			for (ix = 0; ix < count; ++ix)
			{
				CFStringRef emailAddress = (CFStringRef)CFArrayGetValueAtIndex(emailAddresses, ix);
				const char *addr;
				char buffer[256];

				if (ix)
					fputs(", ", stdout);

				addr = CFStringGetCStringPtr(emailAddress, kCFStringEncodingUTF8);
				if (!addr)
				{
					if (CFStringGetCString(emailAddress, buffer, sizeof(buffer), kCFStringEncodingUTF8))
						addr = buffer;
				}

				fprintf(stdout, "%s", addr);
			}
			fputc('\n', stdout);

			CFRelease(emailAddresses);
		}

		if (output_pem)
		{
			CSSM_DATA certData = {};
			result = SecCertificateGetData(certificateRef, &certData);
			if (result)
			{
				sec_perror("SecCertificateGetData", result);
				goto cleanup;
			}

			print_buffer_pem(stdout, "CERTIFICATE", certData.Length, certData.Data);
		}
		else
		{
			print_keychain_item_attributes(stdout, (SecKeychainItemRef)certificateRef, FALSE, FALSE, FALSE, FALSE);
		}
	} while (find_all);

cleanup:
	safe_CFRelease(&searchRef);
	safe_CFRelease(&certificateRef);
	safe_CFRelease(&matchRef);

	return result;
}
Beispiel #24
0
int
main(int argc, char **argv)
{
	const char		*command	= argv[0];
	extern int		optind;
	int			opt;
	CFStringRef		current		= NULL;
	int			currentMatched	= 0;
	CFStringRef		newSet		= NULL;	/* set key */
	CFStringRef		newSetUDN	= NULL;	/* user defined name */
	CFStringRef		prefix;
	SCPreferencesRef	prefs;
	CFDictionaryRef		sets;
	CFIndex			nSets;
	const void		**setKeys	= NULL;
	const void		**setVals	= NULL;
	CFIndex			i;

#if	!TARGET_OS_IPHONE
	AuthorizationRef	authorization	= NULL;
	AuthorizationFlags	flags		= kAuthorizationFlagDefaults;
	CFMutableDictionaryRef	options;
	OSStatus		status;
#endif	// !TARGET_OS_IPHONE

	/* process any arguments */

	while ((opt = getopt_long(argc, argv, "dvn", longopts, NULL)) != -1) {
		switch(opt) {
			case 'd':
				_sc_debug = TRUE;
				_sc_log   = FALSE;	/* enable framework logging */
				break;
			case 'v':
				_sc_verbose = TRUE;
				break;
			case 'n':
				apply = FALSE;
				break;
			case '?':
			default :
				usage(command);
		}
	}
	argc -= optind;
	argv += optind;

	prefix = CFStringCreateWithFormat(NULL, NULL, CFSTR("/%@/"), kSCPrefSets);

	if (argc == 1) {
		newSet = CFStringCreateWithCString(NULL, argv[0], kCFStringEncodingMacRoman);

		/* check if a full path to the new "set" was specified */
		if ((CFStringGetLength(newSet) > 0) && CFStringHasPrefix(newSet, prefix)) {
			CFRange			range;
			CFMutableStringRef	str;

			str = CFStringCreateMutableCopy(NULL, 0, newSet);
			CFRelease(newSet);

			CFStringDelete(str, CFRangeMake(0, CFStringGetLength(prefix)));
			newSet = CFStringCreateCopy(NULL, newSet);
			CFRelease(str);

			range = CFStringFind(newSet, CFSTR("/"), 0);
			if (range.location != kCFNotFound) {
				SCPrint(TRUE, stderr, CFSTR("Set \"%@\" not available\n."), newSet);
				exit (1);
			}
		}
	} else {
		newSet = CFRetain(CFSTR(""));
	}

#if	!TARGET_OS_IPHONE
	status = AuthorizationCreate(NULL,
				     kAuthorizationEmptyEnvironment,
				     flags,
				     &authorization);
	if (status != errAuthorizationSuccess) {
		SCPrint(TRUE,
			stderr,
			CFSTR("AuthorizationCreate() failed: status = %d\n"),
			(int)status);
		exit (1);
	}

	options = CFDictionaryCreateMutable(NULL,
					    0,
					    &kCFTypeDictionaryKeyCallBacks,
					    &kCFTypeDictionaryValueCallBacks);
	CFDictionarySetValue(options, kSCPreferencesOptionChangeNetworkSet, kCFBooleanTrue);
	prefs = SCPreferencesCreateWithOptions(NULL, CFSTR("scselect"), NULL, authorization, options);
	CFRelease(options);
	if (prefs == NULL) {
		SCPrint(TRUE, stderr, CFSTR("SCPreferencesCreate() failed\n"));
		exit (1);
	}
#else	// !TARGET_OS_IPHONE
	prefs = SCPreferencesCreate(NULL, CFSTR("scselect"), NULL);
	if (prefs == NULL) {
		SCPrint(TRUE, stderr, CFSTR("SCPreferencesCreate() failed\n"));
		exit (1);
	}
#endif	// !TARGET_OS_IPHONE

	sets = SCPreferencesGetValue(prefs, kSCPrefSets);
	if (sets == NULL) {
		SCPrint(TRUE, stderr, CFSTR("No network sets defined.\n"));
		exit (1);
	}

	current = SCPreferencesGetValue(prefs, kSCPrefCurrentSet);
	if (current != NULL) {
		if (CFStringHasPrefix(current, prefix)) {
			CFMutableStringRef	tmp;

			tmp = CFStringCreateMutableCopy(NULL, 0, current);
			CFStringDelete(tmp, CFRangeMake(0, CFStringGetLength(prefix)));
			current = tmp;
		} else {
			CFRetain(current);
			currentMatched = -1;	/* not prefixed */
		}
	} else {
		current = CFRetain(CFSTR(""));
		currentMatched = -2;	/* not defined */
	}

	nSets = CFDictionaryGetCount(sets);
	if (nSets > 0) {
		setKeys = CFAllocatorAllocate(NULL, nSets * sizeof(CFStringRef), 0);
		setVals = CFAllocatorAllocate(NULL, nSets * sizeof(CFDictionaryRef), 0);
		CFDictionaryGetKeysAndValues(sets, setKeys, setVals);
	}

	/* check for set with matching name */
	for (i = 0; i < nSets; i++) {
		CFStringRef	key  = (CFStringRef)    setKeys[i];
		CFDictionaryRef	dict = (CFDictionaryRef)setVals[i];

		if ((currentMatched >= 0) && CFEqual(key, current)) {
			currentMatched++;
		}

		if (CFEqual(newSet, key)) {
			newSetUDN = CFDictionaryGetValue(dict, kSCPropUserDefinedName);
			if (newSetUDN != NULL) CFRetain(newSetUDN);
			goto found;
		}
	}

	/* check for set with matching user-defined name */
	for (i = 0; i < nSets; i++) {
		CFStringRef	key  = (CFStringRef)    setKeys[i];
		CFDictionaryRef	dict = (CFDictionaryRef)setVals[i];

		newSetUDN = CFDictionaryGetValue(dict, kSCPropUserDefinedName);
		if ((newSetUDN != NULL) && CFEqual(newSet, newSetUDN)) {
			CFRelease(newSet);
			newSet = CFRetain(key);
			CFRetain(newSetUDN);
			goto found;
		}
	}

	if (argc == 1) {
		SCPrint(TRUE, stderr, CFSTR("Set \"%@\" not available.\n"), newSet);
		exit(1);
	}

	SCPrint(TRUE, stdout,
		CFSTR("Defined sets include:%s\n"),
		(currentMatched > 0) ? " (* == current set)" : "");

	for (i = 0; i < nSets; i++) {
		CFStringRef	key  = (CFStringRef)    setKeys[i];
		CFDictionaryRef	dict = (CFDictionaryRef)setVals[i];
		CFStringRef	udn  = CFDictionaryGetValue(dict, kSCPropUserDefinedName);

		SCPrint(TRUE, stdout,
			CFSTR(" %s %@\t(%@)\n"),
			((currentMatched > 0) && CFEqual(key, current)) ? "*" : " ",
			key,
			udn ? udn : CFSTR(""));
	}

	switch (currentMatched) {
		case -2 :
			SCPrint(TRUE, stdout, CFSTR("\nCurrent set not defined.\n"));
			break;
		case -1 :
			SCPrint(TRUE, stdout, CFSTR("\nCurrent set \"%@\" may not be valid\n"), current);
			break;
		case  0 :
			SCPrint(TRUE, stdout, CFSTR("\nCurrent set \"%@\" not valid\n"), current);
			break;
		default :
			break;
	}

	CFRelease(prefix);
	exit (0);

    found :

	CFRelease(current);
	current = CFStringCreateWithFormat(NULL, NULL, CFSTR("%@%@"), prefix, newSet);

	if (!SCPreferencesSetValue(prefs, kSCPrefCurrentSet, current)) {
		SCPrint(TRUE, stderr,
			CFSTR("SCPreferencesSetValue(...,%@,%@) failed: %s\n"),
			kSCPrefCurrentSet,
			current,
			SCErrorString(SCError()));
		exit (1);
	}

	if (!SCPreferencesCommitChanges(prefs)) {
		int	sc_status	= SCError();

		if (sc_status == kSCStatusAccessError) {
			SCPrint(TRUE, stderr,
				CFSTR("Only local console users and administrators can change locations\n"));
			exit (EX_NOPERM);
		} else {
			SCPrint(TRUE, stderr,
				CFSTR("SCPreferencesCommitChanges() failed: %s\n"),
				SCErrorString(sc_status));
			exit (1);
		}
	}

	if (apply) {
		if (!SCPreferencesApplyChanges(prefs)) {
			SCPrint(TRUE, stderr,
				CFSTR("SCPreferencesApplyChanges() failed %s\n"),
				SCErrorString(SCError()));
			exit (1);
		}
	}

	SCPrint(TRUE, stdout,
		CFSTR("%@ updated to %@ (%@)\n"),
		kSCPrefCurrentSet,
		newSet,
		newSetUDN ? newSetUDN : CFSTR(""));

	CFRelease(current);
	CFRelease(newSet);
	if (newSetUDN != NULL)	CFRelease(newSetUDN);
	CFRelease(prefix);
	CFRelease(prefs);

#if	!TARGET_OS_IPHONE
	AuthorizationFree(authorization, kAuthorizationFlagDefaults);
//	AuthorizationFree(authorization, kAuthorizationFlagDestroyRights);
#endif	/* !TARGET_OS_IPHONE */

	exit (0);
	return 0;
}
Beispiel #25
0
void Common::mailTo( const QUrl &url )
{
#if defined(Q_OS_WIN32)
	QString file = url.queryItemValue( "attachment" );
	QByteArray filePath = QDir::toNativeSeparators( file ).toLatin1();
	QByteArray fileName = QFileInfo( file ).fileName().toLatin1();
	QByteArray subject = url.queryItemValue( "subject" ).toLatin1();

	MapiFileDesc doc[1];
	doc[0].ulReserved = 0;
	doc[0].flFlags = 0;
	doc[0].nPosition = -1;
	doc[0].lpszPathName = const_cast<char*>(filePath.constData());
	doc[0].lpszFileName = const_cast<char*>(fileName.constData());
	doc[0].lpFileType = NULL;

	// Create message
	MapiMessage message;
	message.ulReserved = 0;
	message.lpszSubject = const_cast<char*>(subject.constData());
	message.lpszNoteText = "";
	message.lpszMessageType = NULL;
	message.lpszDateReceived = NULL;
	message.lpszConversationID = NULL;
	message.flFlags = 0;
	message.lpOriginator = NULL;
	message.nRecipCount = 0;
	message.lpRecips = NULL;
	message.nFileCount = 1;
	message.lpFiles = (lpMapiFileDesc)&doc;

	QLibrary lib("mapi32");
	typedef ULONG (PASCAL *SendMail)(ULONG,ULONG,MapiMessage*,FLAGS,ULONG);
	SendMail mapi = (SendMail)lib.resolve("MAPISendMail");
	if( mapi )
	{
		mapi( NULL, 0, &message, MAPI_LOGON_UI|MAPI_DIALOG, 0 );
		return;
	}
#elif defined(Q_OS_MAC)
	CFURLRef emailUrl = CFURLCreateWithString( kCFAllocatorDefault, CFSTR("mailto:"), 0 );
	CFURLRef appUrl = 0;
	CFStringRef appPath = 0;
	if( LSGetApplicationForURL( emailUrl, kLSRolesAll, NULL, &appUrl ) == noErr )
	{
		appPath = CFURLCopyFileSystemPath( appUrl, kCFURLPOSIXPathStyle );
		CFRelease( appUrl );
	}
	CFRelease( emailUrl );

	if( appPath )
	{
		QProcess p;
		p.start( "/usr/bin/osascript", QStringList() << "-" << url.queryItemValue("attachment") << url.queryItemValue("subject") );
		p.waitForStarted();
		QTextStream s( &p );
		if( CFStringCompare( appPath, CFSTR("/Applications/Mail.app"), 0 ) == kCFCompareEqualTo )
		{
			s << "on run argv" << endl
				<< "set vattachment to (item 1 of argv)" << endl
				<< "set vsubject to (item 2 of argv)" << endl
				<< "tell application \"Mail\"" << endl
				<< "set composeMessage to make new outgoing message at beginning with properties {visible:true}" << endl
				<< "tell composeMessage" << endl
				<< "set subject to vsubject" << endl
				<< "set content to \" \"" << endl
				<< "tell content" << endl
				<< "make new attachment with properties {file name: vattachment} at after the last word of the last paragraph" << endl
				<< "end tell" << endl
				<< "end tell" << endl
				<< "activate" << endl
				<< "end tell" << endl
				<< "end run" << endl;
		}
		else if( CFStringFind( appPath, CFSTR("Entourage"), 0 ).location != kCFNotFound )
		{
			s << "on run argv" << endl
				<< "set vattachment to (item 1 of argv)" << endl
				<< "set vsubject to (item 2 of argv)" << endl
				<< "tell application \"Microsoft Entourage\"" << endl
				<< "set vmessage to make new outgoing message with properties" << endl
				<< "{subject:vsubject, attachments:vattachment}" << endl
				<< "open vmessage" << endl
				<< "activate" << endl
				<< "end tell" << endl
				<< "end run" << endl;
		}
#if 0
		else if(CFStringCompare(appPath, CFSTR("/Applications/Thunderbird.app"), 0) == kCFCompareEqualTo)
		{
			// TODO: Handle Thunderbird here? Impossible?
		}
#endif
		CFRelease( appPath );
		p.closeWriteChannel();
		p.waitForFinished();
		if( p.exitCode() == 0 )
			return;
	}
#elif defined(Q_OS_LINUX)
	QByteArray thunderbird;
	QProcess p;
	QStringList env = QProcess::systemEnvironment();
	if( env.indexOf( QRegExp("KDE_FULL_SESSION.*") ) != -1 )
	{
		p.start( "kreadconfig", QStringList()
			<< "--file" << "emaildefaults"
			<< "--group" << "PROFILE_Default"
			<< "--key" << "EmailClient" );
		p.waitForFinished();
		QByteArray data = p.readAllStandardOutput().trimmed();
		if( data.contains("thunderbird") )
			thunderbird = data;
	}
	else if( env.indexOf( QRegExp("GNOME_DESKTOP_SESSION_ID.*") ) != -1 )
	{
		p.start( "gconftool-2", QStringList()
			<< "--get" << "/desktop/gnome/url-handlers/mailto/command" );
		p.waitForFinished();
		QByteArray data = p.readAllStandardOutput();
		if( data.contains("thunderbird") )
			thunderbird = data.split(' ').value(0);
	}
	/*
	else
	{
		p.start( "xprop", QStringList() << "-root" << "_DT_SAVE_MODE" );
		p.waitForFinished();
		if( p.readAllStandardOutput().contains("xfce4") )
		{}
	}*/

	if( !thunderbird.isEmpty() )
	{
		if( p.startDetached( thunderbird, QStringList() << "-compose"
			<< QString( "subject='%1',attachment='%2'" )
				.arg( url.queryItemValue( "subject" ) )
				.arg( QUrl::fromLocalFile( url.queryItemValue( "attachment" ) ).toString() ) ) );
			return;
	}
	else
	{
		if( p.startDetached( "xdg-email", QStringList()
				<< "--subject" << url.queryItemValue( "subject" )
				<< "--attach" << url.queryItemValue( "attachment" ) ) )
			return;
	}
#endif
	QDesktopServices::openUrl( url );
}
/* ------------------------------------------------------------------------------------------------------

SetDateValueFromFITSHeader: read FITS header and set striped string value to attribute name.

------------------------------------------------------------------------------------------------------ */
void SetDateValueFromFITSHeader(const char* filename, 
				CFMutableDictionaryRef attributes, 
				const char* importerAttrName, 
				char* mainKeyword, 
				char* secondaryKeyword1,
				char* secondaryKeyword2)
{
	CFMutableStringRef headerValue = CFStringCreateMutable(kCFAllocatorDefault, (CFIndex)80);

	CFStringRef value1 = getCleanedHeaderValue(filename, mainKeyword);
	if (value1 != NULL) {
		CFIndex valueLength1 = CFStringGetLength(value1);
		if ((valueLength1 >= 19) || (valueLength1 == 10)) {
			CFStringAppend(headerValue, value1); // value of mainKeyword looks OK.
		}
		CFRelease(value1);
	}

	CFStringRef value2 = getCleanedHeaderValue(filename, secondaryKeyword1);
	if (value2 != NULL) {
		CFIndex valueLength2 = CFStringGetLength(value2);
		CFIndex headerValueLength = CFStringGetLength(headerValue);
		if (headerValueLength == 0 && valueLength2 >= 10) {
			CFStringAppend(headerValueLength, value2); // Append value of secondaryKeyword1
		}
		else if (headerValueLength < 19 && valueLength2 >= 19) {
			CFRange range = CFRangeMake(0, headerValueLength);
			CFStringDelete(headerValue, range);
			CFStringAppend(headerValue, value2); // Replace value of current headerValue by value of secondaryKeyword1
		}
		CFRelease(value2);
	}

	CFStringRef value3 = getCleanedHeaderValue(filename, secondaryKeyword2);
	if (value3 != NULL) {
		CFRange r = CFStringFind(value3, CFSTR(":"), 0);
		CFIndex headerValueLength = CFStringGetLength(headerValue);
		if (headerValueLength == 10 && r.location != kCFNotFound) {
			CFStringAppend(headerValue, CFSTR("T"));
			CFStringAppend(headerValue, value3);
		}
		CFRelease(value3);
	}

	CFIndex headerValueLength = CFStringGetLength(headerValue);
	if (headerValueLength > 0) {
		
		CFArrayRef tArray   = CFStringCreateArrayBySeparatingStrings(kCFAllocatorDefault, headerValue, CFSTR("T"));
		CFArrayRef ymdArray = CFStringCreateArrayBySeparatingStrings(kCFAllocatorDefault, CFArrayGetValueAtIndex(tArray, 0), CFSTR("-"));

		CFGregorianDate gregDate;
		gregDate.year   = 0;
		gregDate.month  = 0;
		gregDate.day    = 0.;
		
		if (CFStringGetLength(CFArrayGetValueAtIndex(ymdArray, 0)) > 0) {
			gregDate.year   = CFStringGetIntValue(CFArrayGetValueAtIndex(ymdArray, 0));
		}
		if (CFStringGetLength(CFArrayGetValueAtIndex(ymdArray, 1)) > 0) {
			gregDate.month  = CFStringGetIntValue(CFArrayGetValueAtIndex(ymdArray, 1));
		}
		if (CFStringGetLength(CFArrayGetValueAtIndex(ymdArray, 2)) > 0) {
			gregDate.day    = CFStringGetIntValue(CFArrayGetValueAtIndex(ymdArray, 2));
		}
		CFRelease(ymdArray);

		gregDate.hour   = 0;
		gregDate.minute = 0;
		gregDate.second = 0.;
		
		CFIndex arraySize = CFArrayGetCount(tArray);
		if (arraySize == 2) {
			CFArrayRef hmsArray = CFStringCreateArrayBySeparatingStrings(kCFAllocatorDefault, CFArrayGetValueAtIndex(tArray, 1), CFSTR(":"));
			if (CFStringGetLength(CFArrayGetValueAtIndex(hmsArray, 0)) > 0) {
				gregDate.hour   = CFStringGetIntValue(CFArrayGetValueAtIndex(hmsArray, 0));
			}
			if (CFStringGetLength(CFArrayGetValueAtIndex(hmsArray, 1)) > 0) {
				gregDate.minute = CFStringGetIntValue(CFArrayGetValueAtIndex(hmsArray, 1));
			}
			if (CFStringGetLength(CFArrayGetValueAtIndex(hmsArray, 2)) > 0) {
				gregDate.second = CFStringGetDoubleValue(CFArrayGetValueAtIndex(hmsArray, 2));			
			}
			CFRelease(hmsArray);
		}

		CFRelease(tArray);

//		printf("%i %i %i %i %i %f\n\n", gregDate.year, gregDate.month, gregDate.day, gregDate.hour, gregDate.minute, gregDate.second);

		if ((gregDate.year > 0) && (gregDate.month > 0) && (gregDate.day > 0)) {
			CFTimeZoneRef timeZone = CFTimeZoneCreateWithName(kCFAllocatorDefault, CFSTR("GMT"), true);
			CFAbsoluteTime absTime = CFGregorianDateGetAbsoluteTime(gregDate, timeZone);
			CFDateRef date = CFDateCreate(kCFAllocatorDefault, absTime);

			if (timeZone != NULL) {
				CFRelease(timeZone);
			}

			CFStringRef cfImporterAttrName = CFStringCreateWithCString(kCFAllocatorDefault, importerAttrName, kCFStringEncodingUTF8);
			CFDictionaryAddValue(attributes, cfImporterAttrName, date);
			CFRelease(cfImporterAttrName);
			CFRelease(date);
		}
	}

	CFRelease(headerValue);
}
Beispiel #27
0
static Boolean
establishNewPreferences()
{
	CFBundleRef     bundle;
	SCNetworkSetRef	current		= NULL;
	CFStringRef	new_model;
	Boolean		ok		= FALSE;
	int		sc_status	= kSCStatusFailed;
	SCNetworkSetRef	set		= NULL;
	CFStringRef	setName		= NULL;
	Boolean		updated		= FALSE;

	while (TRUE) {
		ok = SCPreferencesLock(prefs, TRUE);
		if (ok) {
			break;
		}

		sc_status = SCError();
		if (sc_status == kSCStatusStale) {
			SCPreferencesSynchronize(prefs);
		} else {
			SCLog(TRUE, LOG_ERR,
			      CFSTR("Could not acquire network configuration lock: %s"),
			      SCErrorString(sc_status));
			return FALSE;
		}
	}

	/* Ensure that the preferences has the new model */
	new_model = _SC_hw_model(FALSE);

	/* Need to regenerate the new configuration for new model */
	if (new_model != NULL) {
		CFStringRef	old_model;

		old_model = SCPreferencesGetValue(prefs, MODEL);
		if ((old_model != NULL) && !_SC_CFEqual(old_model, new_model)) {
			CFIndex		count;
			CFIndex		index;
			CFArrayRef	keys;

			keys = SCPreferencesCopyKeyList(prefs);
			count = (keys != NULL) ? CFArrayGetCount(keys) : 0;
			// if new hardware
			for (index = 0; index < count; index++) {
				CFStringRef		existing_key;

				existing_key = CFArrayGetValueAtIndex(keys, index);
				if (isA_CFString(existing_key) != NULL) {
					CFStringRef		new_key;
					CFPropertyListRef	value;

					/* If it already contains a Model
					   or if it already contains a MODEL:KEY key skip it*/
					if (CFEqual(existing_key, MODEL)
					    || CFStringFind(existing_key, CFSTR(":"), 0).location
					    != kCFNotFound) {
						continue;
					}

					value = SCPreferencesGetValue(prefs, existing_key);

					/* Create a new key as OLD_MODEL:OLD_KEY */
					new_key = CFStringCreateWithFormat(NULL, NULL, CFSTR("%@:%@"),
									   old_model, existing_key);
					SCPreferencesSetValue(prefs, new_key, value);
					if (!CFEqual(existing_key, kSCPrefSystem)) {
						/* preserve existing host names */
						SCPreferencesRemoveValue(prefs, existing_key);
					}
					CFRelease(new_key);
				}
			}

			if (keys != NULL) {
				CFRelease(keys);
			}
		}
		/* Set the new model */
		SCPreferencesSetValue(prefs, MODEL, new_model);
	}

	current = SCNetworkSetCopyCurrent(prefs);
	if (current != NULL) {
		set = current;
	}

	if (set == NULL) {
		set = SCNetworkSetCreate(prefs);
		if (set == NULL) {
			ok = FALSE;
			sc_status = SCError();
			goto done;
		}

		bundle = _SC_CFBundleGet();
		if (bundle != NULL) {
			setName = CFBundleCopyLocalizedString(bundle,
							      CFSTR("DEFAULT_SET_NAME"),
							      CFSTR("Automatic"),
							      NULL);
		}

		ok = SCNetworkSetSetName(set, (setName != NULL) ? setName : CFSTR("Automatic"));
		if (!ok) {
			sc_status = SCError();
			goto done;
		}

		ok = SCNetworkSetSetCurrent(set);
		if (!ok) {
			sc_status = SCError();
			goto done;
		}
	}

	ok = SCNetworkSetEstablishDefaultConfiguration(set);
	if (!ok) {
		sc_status = SCError();
		goto done;
	}

    done :

	if (ok) {
		ok = SCPreferencesCommitChanges(prefs);
		if (ok) {
			SCLog(TRUE, LOG_NOTICE, CFSTR("New network configuration saved"));
			updated = TRUE;
		} else {
			sc_status = SCError();
			if (sc_status == EROFS) {
				/* a read-only fileysstem is OK */
				ok = TRUE;

				/* ... but we don't want to synchronize */
				rofs = TRUE;
			}
		}

		/* apply (committed or temporary/read-only) changes */
		(void) SCPreferencesApplyChanges(prefs);
	} else if ((current == NULL) && (set != NULL)) {
		(void) SCNetworkSetRemove(set);
	}

	if (!ok) {
		SCLog(TRUE, LOG_ERR,
		      CFSTR("Could not establish network configuration: %s"),
		      SCErrorString(sc_status));
	}

	(void)SCPreferencesUnlock(prefs);
	if (setName != NULL) CFRelease(setName);
	if (set != NULL) CFRelease(set);
	return updated;
}
void
configSet(CFMutableArrayRef config, CFStringRef key, CFStringRef value)
{
	CFMutableStringRef	pref;
	CFIndex			configLen	= CFArrayGetCount(config);
	CFIndex			i;
	CFIndex			n;
	CFMutableStringRef	newValue;
	CFRange			range;
	CFStringRef		specialChars	= CFSTR(" \"'$!|\\<>`{}[]");
	boolean_t		mustQuote	= FALSE;

	/* create search prefix */
	pref = CFStringCreateMutableCopy(NULL, 0, key);
	CFStringAppend(pref, CFSTR("="));

	/*
	 * create new / replacement value
	 *
	 * Note: Since the configuration file may be processed by a
	 *       shell script we need to ensure that, if needed, the
	 *       string is properly quoted.
	 */
	newValue = CFStringCreateMutableCopy(NULL, 0, value);

	n = CFStringGetLength(specialChars);
	for (i = 0; i < n; i++) {
		CFStringRef	specialChar;

		specialChar = CFStringCreateWithSubstring(NULL, specialChars, CFRangeMake(i, 1));
		range = CFStringFind(newValue, specialChar, 0);
		CFRelease(specialChar);
		if (range.location != kCFNotFound) {
			/* this string has at least one special character */
			mustQuote = TRUE;
			break;
		}
	}

	if (mustQuote) {
		CFStringRef	charsToQuote	= CFSTR("\\\"$`");

		/*
		 * in addition to quoting the entire string we also need to escape the
		 * space " " and backslash "\" characters
		 */
		n = CFStringGetLength(charsToQuote);
		for (i = 0; i < n; i++) {
			CFStringRef	quoteChar;
			CFArrayRef	matches;

			quoteChar = CFStringCreateWithSubstring(NULL, charsToQuote, CFRangeMake(i, 1));
			range     = CFRangeMake(0, CFStringGetLength(newValue));
			matches   = CFStringCreateArrayWithFindResults(NULL,
								       newValue,
								       quoteChar,
								       range,
								       0);
			CFRelease(quoteChar);

			if (matches) {
				CFIndex	j = CFArrayGetCount(matches);

				while (--j >= 0) {
					const CFRange	*range;

					range = CFArrayGetValueAtIndex(matches, j);
					CFStringInsert(newValue, range->location, CFSTR("\\"));
				}
				CFRelease(matches);
			}
		}

		CFStringInsert(newValue, 0, CFSTR("\""));
		CFStringAppend(newValue, CFSTR("\""));
	}

	/* locate existing key */
	for (i = 0; i < configLen; i++) {
		if (CFStringHasPrefix(CFArrayGetValueAtIndex(config, i), pref)) {
			break;
		}
	}

	CFStringAppend(pref, newValue);
	CFRelease(newValue);
	if (i < configLen) {
		/* if replacing an existing entry */
		CFArraySetValueAtIndex(config, i, pref);
	} else {
		/*
		 * if new entry, insert it just prior to the last (emtpy)
		 * array element.
		 */
		CFArrayInsertValueAtIndex(config, configLen-1, pref);
	}
	CFRelease(pref);

	return;
}
/**
 * Determine if the suffix of one CFStringRef is the prefix of another.
 * @param text1 First CFStringRef.
 * @param text2 Second CFStringRef.
 * @return The number of characters common to the end of the first
 *     CFStringRef and the start of the second CFStringRef.
 */
CFIndex diff_commonOverlap(CFStringRef text1, CFStringRef text2) {
  CFIndex common_overlap = 0;

  // Cache the text lengths to prevent multiple calls.
  CFIndex text1_length = CFStringGetLength(text1);
  CFIndex text2_length = CFStringGetLength(text2);

  // Eliminate the nil case.
  if (text1_length == 0 || text2_length == 0) {
    return 0;
  }

  // Truncate the longer CFStringRef.
  CFStringRef text1_trunc;
  CFStringRef text2_trunc;
  CFIndex text1_trunc_length;
  if (text1_length > text2_length) {
    text1_trunc_length = text2_length;
    text1_trunc = diff_CFStringCreateRightSubstring(text1, text1_length, text1_trunc_length);

    text2_trunc = CFRetain(text2);
  } else if (text1_length < text2_length) {
    text1_trunc_length = text1_length;
    text1_trunc = CFRetain(text1);

    CFIndex text2_trunc_length = text1_length;
    text2_trunc = diff_CFStringCreateLeftSubstring(text2, text2_trunc_length);
  } else {
    text1_trunc_length = text1_length;
    text1_trunc = CFRetain(text1);

    text2_trunc = CFRetain(text2);
  }

  CFIndex text_length = MIN(text1_length, text2_length);
  // Quick check for the worst case.
  if (text1_trunc == text2_trunc) {
    common_overlap = text_length;
  } else {
    // Start by looking for a single character match
    // and increase length until no match is found.
    // Performance analysis: http://neil.fraser.name/news/2010/11/04/
    CFIndex best = 0;
    CFIndex length = 1;
    while (true) {
      CFStringRef pattern = diff_CFStringCreateRightSubstring(text1_trunc, text1_trunc_length, length);
      CFRange foundRange = CFStringFind(text2_trunc, pattern, 0);
      CFRelease(pattern);

      CFIndex found =  foundRange.location;
      if (found == kCFNotFound) {
        common_overlap = best;
        break;
      }
      length += found;

      CFStringRef text1_sub = diff_CFStringCreateRightSubstring(text1_trunc, text1_trunc_length, length);
      CFStringRef text2_sub = diff_CFStringCreateLeftSubstring(text2_trunc, length);

      if (found == 0 || (CFStringCompare(text1_sub, text2_sub, 0) == kCFCompareEqualTo)) {
        best = length;
        length++;
      }

      CFRelease(text1_sub);
      CFRelease(text2_sub);
    }
  }

  CFRelease(text1_trunc);
  CFRelease(text2_trunc);
  return common_overlap;
}
Beispiel #30
0
int _lp_is_launchpad(MIDIDeviceRef d) {
    CFStringRef name;
    MIDIObjectGetStringProperty(d, kMIDIPropertyName, &name);

    return CFStringFind(name, CFSTR("Launchpad"), kCFCompareCaseInsensitive).length > 0;
}