sdmmd_return_t SDMMD_AMDeviceSecureInstallApplication(SDMMD_AMConnectionRef conn, SDMMD_AMDeviceRef device, CFURLRef path, CFDictionaryRef options, CallBack installCallback, void *unknown)
{
	sdmmd_return_t result = kAMDSuccess;
	SDMMD_AMConnectionRef connection = NULL;
	bool hasConnection = (conn ? true : false);
	if (device) {
		result = SDMMD_AMDeviceSecureStartService(device, CFSTR(AMSVC_INSTALLATION_PROXY), NULL, &connection);
		if (result == 0) {
			hasConnection = true;
		}
		else {
			printf("%s: Was unable to start the install service on the device 0x%x.\n", __FUNCTION__, result);
		}
	}
	if (hasConnection) {
		CFStringRef lastComp = CFURLCopyLastPathComponent(path);
		if (CFStringGetLength(lastComp) == 0) {
			CFSafeRelease(lastComp);
			CFURLRef pathURL = CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorDefault, path);
			lastComp = CFURLCopyLastPathComponent(pathURL);
			CFSafeRelease(pathURL);
		}
		if (lastComp) {
			CFStringRef format = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("PublicStaging/%@"), lastComp);
			if (format) {
				char *appName = SDMCFStringGetString(format);
				printf("%s: Attempting install of %s.\n", __FUNCTION__, appName);
				result = SDMMD_perform_command(connection, CFSTR("Install"), 0, installCallback, 4, unknown, CFSTR("PackagePath"), format, CFSTR("ClientOptions"), options);
				if (result) {
					printf("%s: Old style of install failed for (%s).\n", __FUNCTION__, appName);
				}
				Safe(free, appName);
			}
			else {
				printf("%s: Unable to create CFString!\n", __FUNCTION__);
			}
			CFSafeRelease(format);
		}
		else {
			char *lastCompString = SDMCFStringGetString(lastComp);
			printf("%s: Could not copy last path component from url %s.\n", __FUNCTION__, lastCompString);
			Safe(free, lastCompString);
		}
		CFSafeRelease(lastComp);
	}
	CFSafeRelease(connection);
	char *pathString = SDMCFURLGetString(path);
	printf("%s: Installation of package %s returned 0x%x.\n", __FUNCTION__, pathString, result);
	Safe(free, pathString);
	return result;
}
Esempio n. 2
0
OSStatus	PosixPathToParentFSRefAndName(const char *path, FSRef &outParentDir, CFStringRef &outFileName)
{
	// convert C string to CFString
#if !TARGET_OS_WIN32
	CFStringRef cfFullPath = CFStringCreateWithCString(NULL, path, kCFStringEncodingUTF8);
#else
	CFStringRef cfFullPath = CFStringCreateWithCString(NULL, path, kCFStringEncodingWindowsLatin1);
#endif
	// convert CF string to URL
	CFURLRef fullurl = CFURLCreateWithFileSystemPath(NULL, cfFullPath, TARGET_OS_WIN32 ? kCFURLWindowsPathStyle : kCFURLPOSIXPathStyle, false);
	CFRelease(cfFullPath);
	// get the directory portion of the URL
	CFURLRef dirurl = CFURLCreateCopyDeletingLastPathComponent(NULL, fullurl);
	// get the directory's FSSpec
	OSStatus err = CFURLGetFSRef(dirurl, &outParentDir) ? OSStatus(noErr) : OSStatus(fnfErr);
	CFRelease(dirurl);
	
	CFStringRef lastPathComponent = CFURLCopyLastPathComponent(fullurl);
	CFRelease(fullurl);
	CFMutableStringRef filename = CFStringCreateMutableCopy(NULL, 0, lastPathComponent);
	CFRelease(lastPathComponent);
	// convert colons (legal in POSIX paths, illegal in File Manager) to slashes
	CFStringFindAndReplace(filename, CFSTR(":"), CFSTR("/"), CFRangeMake(0, CFStringGetLength(filename)), 0);
	
	outFileName = filename;
	
	return err;
}
Esempio n. 3
0
void _glfwChangeToResourcesDirectory( void )
{
    CFBundleRef mainBundle = CFBundleGetMainBundle();
    CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL( mainBundle );
    char resourcesPath[ _GLFW_MAX_PATH_LENGTH ];
    
    CFStringRef lastComponent = CFURLCopyLastPathComponent( resourcesURL );
    if ( kCFCompareEqualTo != CFStringCompare(
            CFSTR( "Resources" ),
            lastComponent,
            0 ) )
    {
        UNBUNDLED;
    }
    
    CFRelease( lastComponent );

    if( !CFURLGetFileSystemRepresentation( resourcesURL,
                                           TRUE,
                                           (UInt8*)resourcesPath,
                                           _GLFW_MAX_PATH_LENGTH ) )
    {
        CFRelease( resourcesURL );
        UNBUNDLED;
    }

    CFRelease( resourcesURL );

    if( chdir( resourcesPath ) != 0 )
    {
        UNBUNDLED;
    }
}
Esempio n. 4
0
int makeHFSFromPosixPath(char *pathString, int pathStringLength,char *dst,char *lastpart) {
		CFStringRef filePath;
        CFURLRef 	sillyThing;
        CFStringRef	filePath2,lastPathPart;
		
        dst[0] = 0x00;
		if (lastpart)
			lastpart[0] = 0x00;
		filePath   = CFStringCreateWithBytes(kCFAllocatorDefault,
                    (UInt8 *)pathString,pathStringLength,gCurrentVMEncoding,false);
        if (filePath == nil)
            return -1;
			
		// HFS+ imposes Unicode2.1 decomposed UTF-8 encoding on all path elements
		CFMutableStringRef str= CFStringCreateMutableCopy(NULL, 0, filePath);
		if (gCurrentVMEncoding == kCFStringEncodingUTF8) 
			CFStringNormalize(str, kCFStringNormalizationFormKC); // canonical decomposition

		sillyThing = CFURLCreateWithFileSystemPath (kCFAllocatorDefault, str, kCFURLPOSIXPathStyle,false);
		CFRelease(str);
		if (sillyThing == NULL) 
			return -2;
		
		filePath2 = CFURLCopyFileSystemPath (sillyThing, kCFURLHFSPathStyle);
		CFStringGetCString (filePath2,dst,1000, gCurrentVMEncoding);
		if (lastpart) {
			lastPathPart = CFURLCopyLastPathComponent(sillyThing);
			CFStringGetCString(lastPathPart,lastpart,256, gCurrentVMEncoding);
			CFRelease(lastPathPart);
		}
        CFRelease(filePath);
        CFRelease(sillyThing);
        CFRelease(filePath2);
        return 0;
}
Esempio n. 5
0
char* SDMDaodanFindTargetBundleIdentifier(char *targetPath) {
	CFStringRef targetExecutablePath = CFStringCreateWithCString(kCFAllocatorDefault, targetPath, kCFStringEncodingUTF8);
	CFURLRef executableURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, targetExecutablePath, kCFURLPOSIXPathStyle, false);
	CFRelease(targetExecutablePath);
	CFURLRef macOSURL = CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorDefault, executableURL);
	CFURLRef contentsURL = CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorDefault, macOSURL);
	CFRelease(macOSURL);
	CFURLRef appURL = CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorDefault, contentsURL);
	CFRelease(contentsURL);
	CFArrayRef bundles = CFBundleCreateBundlesFromDirectory(kCFAllocatorDefault, appURL, NULL);
	CFRelease(appURL);
	CFStringRef targetIdentifier = NULL;
	for (uint32_t i = 0x0; i < CFArrayGetCount(bundles); i++) {
		CFBundleRef bundleItem = (CFBundleRef)CFArrayGetValueAtIndex(bundles, i);
		targetIdentifier = CFBundleGetIdentifier(bundleItem);
		if (targetIdentifier) {
			break;
		}
	}
	CFRelease(bundles);
	char *bundle;
	if (!targetIdentifier) {
		CFStringRef executableIdentifier = CFURLCopyLastPathComponent(executableURL);
		bundle = SDMCFStringGetString(executableIdentifier);
		CFRelease(executableIdentifier);
	} else {
		bundle = SDMCFStringGetString(targetIdentifier);
	}
	CFRelease(executableURL);
	return bundle;
}
Esempio n. 6
0
/********************************************************************
*	 MoveFile
*		 lpFromFileName: old file path
*		 lpToFileName: new file path
********************************************************************/
BOOL MoveFile(const char * lpFromFileName, const char * lpToFileName)
{
	OSErr theErr;
	FSRef fromFileRef;
	FSRef toFileRef;
	FSRef parentFolderRef;
	
	// Get the path to the old file
	theErr = FSPathMakeRef((const UInt8 *)lpFromFileName, &fromFileRef, NULL);
	if (theErr != noErr)
	{
		SetLastError(theErr);
		return false;
	}
	
	// Get the path to the new folder for the file
	char folderName[strlen(lpToFileName)];
	CFStringRef folderPathCFString = CFStringCreateWithCString(NULL, lpToFileName, kCFStringEncodingUTF8);
	CFURLRef fileURL = CFURLCreateWithFileSystemPath(NULL, folderPathCFString, kCFURLPOSIXPathStyle, FALSE);
	CFURLRef folderURL = CFURLCreateCopyDeletingLastPathComponent(NULL, fileURL);
	CFURLGetFileSystemRepresentation(folderURL, TRUE, (UInt8 *)folderName, strlen(lpToFileName));
	theErr = FSPathMakeRef((UInt8 *)folderName, &parentFolderRef, NULL);
	CFRelease(fileURL);
	CFRelease(folderURL);
	CFRelease(folderPathCFString);
	
	// Move the old file
	theErr = FSMoveObject(&fromFileRef, &parentFolderRef, &toFileRef);
	if (theErr != noErr)
	{
		SetLastError(theErr);
		return false;
	}
	
	// Get a CFString for the new file name
	CFStringRef newFileNameCFString = CFStringCreateWithCString(NULL, lpToFileName, kCFStringEncodingUTF8);
	fileURL = CFURLCreateWithFileSystemPath(NULL, newFileNameCFString, kCFURLPOSIXPathStyle, FALSE);
	CFRelease(newFileNameCFString);
	newFileNameCFString = CFURLCopyLastPathComponent(fileURL);
	CFRelease(fileURL);
	
	// Convert CFString to Unicode and rename the file
	UniChar unicodeFileName[256];
	CFStringGetCharacters(newFileNameCFString, CFRangeMake(0, CFStringGetLength(newFileNameCFString)), 
						  unicodeFileName);
	theErr = FSRenameUnicode(&toFileRef, CFStringGetLength(newFileNameCFString), unicodeFileName, 
							 kTextEncodingUnknown, NULL);
	if (theErr != noErr)
	{
		SetLastError(theErr);
		CFRelease(newFileNameCFString);
		return false;
	}
	
	CFRelease(newFileNameCFString);
	
	SetLastError(theErr);
	return true;
}
Esempio n. 7
0
char* SDMDaodanFindTargetName(char *targetPath) {
	CFStringRef targetExecutablePath = CFStringCreateWithCString(kCFAllocatorDefault, targetPath, kCFStringEncodingUTF8);
	CFURLRef executableURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, targetExecutablePath, kCFURLPOSIXPathStyle, false);
	CFRelease(targetExecutablePath);
	CFStringRef targetIdentifier = CFURLCopyLastPathComponent(executableURL);
	char *targetName = SDMCFStringGetString(targetIdentifier);
	CFRelease(targetIdentifier);
	CFRelease(executableURL);
	return targetName;
}
int dir_Create(char *pathString, int pathStringLength) {
	/* Create a new directory with the given path. By default, this
	   directory is created in the current directory. Use
	   a full path name such as "MyDisk:Working:New Folder" to
	   create folders elsewhere. */

    char cFileName[1001];

    if (pathStringLength >= 1000) {
        return false;
    }

    /* copy the file name into a null-terminated C string */
    sqFilenameFromString((char *) cFileName, (int) pathString, pathStringLength);
    
#if defined(__MWERKS__)
	{
        CFStringRef 	filePath,lastFilePath;
        CFURLRef 	    sillyThing,sillyThing2;
        FSRef	        parentFSRef;
        UniChar         buffer[1024];
        long            tokenLength;
		int err;
        
        filePath   = CFStringCreateWithBytes(kCFAllocatorDefault,(UInt8 *)cFileName,strlen(cFileName),gCurrentVMEncoding,false);
        if (filePath == nil) 
            return false;
        sillyThing = CFURLCreateWithFileSystemPath (kCFAllocatorDefault,filePath,kCFURLHFSPathStyle,true);
        CFRelease(filePath);

        lastFilePath = CFURLCopyLastPathComponent(sillyThing);
        tokenLength = CFStringGetLength(lastFilePath);
        if (tokenLength > 1024)
            return false;
        CFStringGetCharacters(lastFilePath,CFRangeMake(0,tokenLength),buffer);
        CFRelease(lastFilePath);

        sillyThing2 = CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorDefault,sillyThing);

        err = CFURLGetFSRef(sillyThing2,&parentFSRef);
        CFRelease(sillyThing);
        CFRelease(sillyThing2);
        if (err == 0) {
            return false;  
        }
		err = FSCreateDirectoryUnicode(&parentFSRef,tokenLength,buffer,kFSCatInfoNone,NULL,NULL,NULL,NULL);
		
    	return (err == noErr ? 1 : 0);
    }
#else
    return mkdir(cFileName, 0777) == 0;
#endif
}
void MDSAttrParser::parseAttrs(CFStringRef subdir)
{
	/* get all *.mdsinfo files */
	CFArrayRef bundleInfoFiles = CFBundleCopyResourceURLsOfType(mBundle,
		CFSTR(MDS_INFO_TYPE),
		subdir);
	if(bundleInfoFiles == NULL) {
		Syslog::alert("MDSAttrParser: no mdsattr files for %s", mPath);
		return;
	}
	assert(CFGetTypeID(bundleInfoFiles) == CFArrayGetTypeID());
	
	/* process each .mdsinfo file */
	CFIndex numFiles = CFArrayGetCount(bundleInfoFiles);
	for(CFIndex i=0; i<numFiles; i++) {
		/* get filename as CFURL */
		CFURLRef infoUrl = NULL;
		
		infoUrl = reinterpret_cast<CFURLRef>(
			CFArrayGetValueAtIndex(bundleInfoFiles, i));
		if(infoUrl == NULL) {
			MPDebug("MDSAttrParser: CFBundleCopyResourceURLsOfType screwup 1");
			continue;
		}
		if(CFGetTypeID(infoUrl) != CFURLGetTypeID()) {
			MPDebug("MDSAttrParser: CFBundleCopyResourceURLsOfType screwup 2");
			continue;
		}
		
		// @@@  Workaround for 4234967: skip any filename beginning with "._"
		CFStringRef lastComponent = CFURLCopyLastPathComponent(infoUrl);
		if (lastComponent) {
			CFStringRef resFilePfx = CFSTR("._");
			// setting the search length and location like this permits, 
			// e.g., ".foo.mdsinfo" to be valid
			CFIndex resFilePfxLen = CFStringGetMaximumSizeForEncoding(CFStringGetLength(resFilePfx), kCFStringEncodingUTF8);
			CFRange range = CFRangeMake(0, resFilePfxLen);
			Boolean skip = CFStringFindWithOptions(lastComponent, 
												   resFilePfx, 
												   range,
												   0/*options*/,
												   NULL/*returned substr*/);
			CFRelease(lastComponent);
			if (skip == true) {
				Syslog::warning("MDSAttrParser: ignoring resource file");
				continue;
			}
		}
		
		parseFile(infoUrl, subdir);
	} /* for each mdsinfo */
	CF_RELEASE(bundleInfoFiles);
}
//---------------------------------------------------------------------
// Sets up the window's title and proxy icon based on the given file.
//
void SetWindowTitleAndProxyFromCFURL(WindowRef window, CFURLRef file)
{
	CFStringRef title;
	FSRef fileAsFSRef;
	
	require( (CFURLGetFSRef(file, &fileAsFSRef) != false), CantGetFSRef );
	verify_noerr( HIWindowSetProxyFSRef(window, &fileAsFSRef) );

	title = CFURLCopyLastPathComponent(file);
	verify_noerr( SetWindowTitleWithCFString(window, title) );
	CFRelease(title);

CantGetFSRef:
	return;
}
Esempio n. 11
0
//
// set our static text control to be the name of the movie
//
static OSStatus SetControlTextToMovieName()
{
	CFStringRef stringRef = CFURLCopyLastPathComponent (mMovieFileURLref);

	CFIndex size = CFStringGetLength (stringRef);
	CFRange range = CFRangeMake(0, size);
	UniChar *buffer = (UniChar *)malloc(range.length  * sizeof(UniChar));
	if (buffer)
	{
		CFStringGetCharacters(stringRef, range, buffer);
		
		SetControlData (mMovNameRef, kControlNoPart, kControlStaticTextTextTag, size * 2, buffer);
        
		free((void *)buffer);
		CFRelease(stringRef);
	}

}
Esempio n. 12
0
int getLastPathComponentInCurrentEncoding(char *pathString,char * lastPathPart,CFStringEncoding encoding) {
    CFURLRef    sillyThing;
    CFStringRef tmpStrRef;

	sillyThing = makeFileSystemURLFromString(pathString,strlen(pathString),encoding);
	if (sillyThing == NULL) 
		return -2000;
	tmpStrRef = CFURLCopyLastPathComponent(sillyThing);
    CFRelease(sillyThing);
	CFMutableStringRef mutableStr= CFStringCreateMutableCopy(NULL, 0, tmpStrRef);
	CFRelease(tmpStrRef);
	// HFS+ imposes Unicode2.1 decomposed UTF-8 encoding on all path elements
	if (gCurrentVMEncoding == kCFStringEncodingUTF8) 
		CFStringNormalize(mutableStr, kCFStringNormalizationFormC); // pre-combined
  
	CFStringGetCString (mutableStr, lastPathPart,256, gCurrentVMEncoding);
	CFRelease(mutableStr);
	return 0;
}
Esempio n. 13
0
OSStatus GeneratePreviewForURL(void *thisInterface, QLPreviewRequestRef preview, CFURLRef url, CFStringRef contentTypeUTI, CFDictionaryRef options)
{
	CGDataProviderRef dataProvider = CGDataProviderCreateWithURL(url);
	if (!dataProvider) return -1;
	CFDataRef data = CGDataProviderCopyData(dataProvider);
	CGDataProviderRelease(dataProvider);
	if (!data) return -1;
	
	int width, height, channels;
	unsigned char* rgbadata = SOIL_load_image_from_memory(CFDataGetBytePtr(data), CFDataGetLength(data), &width, &height, &channels, SOIL_LOAD_RGBA);
	CFStringRef format=CFStringCreateWithBytes(NULL, CFDataGetBytePtr(data) + 0x54, 4, kCFStringEncodingASCII, false);
    CFRelease(data);
	if (!rgbadata) return -1;
	
	CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB();
	CGContextRef context = CGBitmapContextCreate(rgbadata, width, height, 8, width * 4, rgb, kCGImageAlphaPremultipliedLast);
	SOIL_free_image_data(rgbadata);
	CGColorSpaceRelease(rgb);
	if (!context) return -1;

	CGImageRef image = CGBitmapContextCreateImage(context);
	CGContextRelease(context);
	if (!image) return -1;

	/* Add basic metadata to title */
	CFStringRef name = CFURLCopyLastPathComponent(url);
	CFTypeRef keys[1] = {kQLPreviewPropertyDisplayNameKey};
	CFTypeRef values[1] = {CFStringCreateWithFormat(NULL, NULL, CFSTR("%@ (%dx%d %@)"), name, width, height, format)};
 	CFDictionaryRef properties = CFDictionaryCreate(NULL, (const void**)keys, (const void**)values, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
	CFRelease(name);

	context = QLPreviewRequestCreateContext(preview, CGSizeMake(width, height), true, properties);
	CGContextDrawImage(context, CGRectMake(0, 0, width, height), image);
	QLPreviewRequestFlushContext(preview, context);
	
	CGContextRelease(context);
	CFRelease(format);
	CFRelease(properties);
	
	return noErr;
}
Esempio n. 14
0
 CF::String URL::GetLastPathComponent( void )
 {
     CF::String  str;
     CFStringRef cfStr;
     
     if( this->_cfObject == NULL )
     {
         return str;
     }
     
     cfStr = CFURLCopyLastPathComponent( this->_cfObject );
     
     if( cfStr != NULL )
     {
         str = cfStr;
         
         CFRelease( cfStr );
     }
     
     return str;
 }
CFStringRef
CreateDisplayNameForURL(CFURLRef url)
{
    assert(nullptr != url);

    CFStringRef displayName = nullptr;

#if !TARGET_OS_IPHONE
    CFStringRef scheme = CFURLCopyScheme(url);
    if(scheme) {
        bool isFileURL = (kCFCompareEqualTo == CFStringCompare(CFSTR("file"), scheme, kCFCompareCaseInsensitive));
        CFRelease(scheme), scheme = nullptr;

        if(isFileURL) {
            OSStatus result = LSCopyDisplayNameForURL(url, &displayName);

            if(noErr != result) {
                LOGGER_WARNING("org.sbooth.AudioEngine", "LSCopyDisplayNameForURL failed: " << result);
                displayName = CFURLCopyLastPathComponent(url);
            }
        }
        else {
            displayName = CFURLGetString(url);
            CFRetain(displayName);
        }
    }
    // If scheme is nullptr the URL is probably invalid, but can still be logged
    else {
        displayName = CFURLGetString(url);
        CFRetain(displayName);
    }
#else
    displayName = CFURLGetString(url);
    CFRetain(displayName);
#endif

    return displayName;
}
Esempio n. 16
0
sqInt	ioFilenamefromStringofLengthresolveAliases(char* dst, char* src, sqInt num, sqInt resolveAlias) {
        FSRef		theFSRef;
        FSSpec		convertFileNameSpec,failureRetry;
        OSErr		err;
        Boolean		isFolder=false,isAlias=false;
        CFURLRef 	sillyThing,appendedSillyThing;
        CFStringRef 	lastPartOfPath,filePath2;
		CFMutableStringRef filePath;
        
        *dst = 0x00;
        err = quicklyMakePath((char *) src,num,dst,resolveAlias);
        if (err == noErr) 
            return;
            
        err = lookupPath((char *) src,num,&convertFileNameSpec,true,false);
        if ((err == noErr) && resolveAlias) {
            err = ResolveAliasFile(&convertFileNameSpec,true,&isFolder,&isAlias);
            if (err == fnfErr) {
				err = lookupPath((char *) src,num,&convertFileNameSpec,false,false);
	            err = ResolveAliasFile(&convertFileNameSpec,true,&isFolder,&isAlias);
            }
        }
        
        if (err == fnfErr) {
            failureRetry = convertFileNameSpec;
            CopyCStringToPascal("::",failureRetry.name);
            err = FSpMakeFSRef(&failureRetry,&theFSRef);
            if (err != noErr) 
                return;
//            filePath   = CFStringCreateWithBytes(kCFAllocatorDefault,(UInt8 *)src,num,gCurrentVMEncoding,false);
			CFStringRef tmpStrRef = CFStringCreateWithBytes(kCFAllocatorDefault,(UInt8 *)src,num,gCurrentVMEncoding,false);
            if (tmpStrRef == nil) 
                return;
			filePath = CFStringCreateMutableCopy(NULL, 0, tmpStrRef);
			if (gCurrentVMEncoding == kCFStringEncodingUTF8) 
				CFStringNormalize(filePath, kCFStringNormalizationFormKD); // canonical decomposition

            sillyThing = CFURLCreateWithFileSystemPath (kCFAllocatorDefault,filePath,kCFURLHFSPathStyle,false);
            CFRelease(filePath);
			if (sillyThing == NULL) 
					return;

            lastPartOfPath = CFURLCopyLastPathComponent(sillyThing);
            CFRelease(sillyThing);
            sillyThing = CFURLCreateFromFSRef(kCFAllocatorDefault,&theFSRef);
            appendedSillyThing = CFURLCreateCopyAppendingPathComponent(kCFAllocatorDefault,sillyThing,lastPartOfPath,false);
#if defined(__MWERKS__) && !defined(__APPLE__) && !defined(__MACH__)
            filePath2 = CFURLCopyFileSystemPath (appendedSillyThing, kCFURLHFSPathStyle);
#else
            filePath2 = CFURLCopyFileSystemPath (appendedSillyThing, kCFURLPOSIXPathStyle);
#endif
            CFStringGetCString (filePath2,dst,1000, gCurrentVMEncoding);
            CFRelease(sillyThing);
            CFRelease(appendedSillyThing);
            CFRelease(lastPartOfPath);
            CFRelease(filePath2);        
            return; 
        }
        	
        err = FSpMakeFSRef(&convertFileNameSpec,&theFSRef);
#if defined(__MWERKS__) && !defined(__APPLE__) && !defined(__MACH__)
		sillyThing = CFURLCreateFromFSRef(kCFAllocatorDefault,&theFSRef);
        filePath = CFURLCopyFileSystemPath (sillyThing, kCFURLHFSPathStyle);
        CFStringGetCString (filePath,dst,1000, gCurrentVMEncoding);
		CFRelease(sillyThing);
        CFRelease(filePath);        
        return;
 #else
        err = FSRefMakePath(&theFSRef,(UInt8 *)dst,1000); 
 #endif
}
Esempio n. 17
0
static int quicklyMakePath(char *pathString, int pathStringLength,char *dst, Boolean resolveAlias) {
	CFStringRef 	filePath;
        CFURLRef 	sillyThing,firstPartOfPath;
        FSRef		theFSRef;   
        Boolean		isFolder,isAlias;
        OSErr		err;
        
        filePath   = CFStringCreateWithBytes(kCFAllocatorDefault,
                    (UInt8 *)pathString,pathStringLength,gCurrentVMEncoding,false);
        if (filePath == nil)
            return -1;
		CFMutableStringRef str= CFStringCreateMutableCopy(NULL, 0, filePath);
		// HFS+ imposes Unicode2.1 decomposed UTF-8 encoding on all path elements
		if (gCurrentVMEncoding == kCFStringEncodingUTF8) 
			CFStringNormalize(str, kCFStringNormalizationFormKC); // canonical decomposition

		sillyThing = CFURLCreateWithFileSystemPath (kCFAllocatorDefault, str, kCFURLHFSPathStyle,false);
		if (sillyThing == NULL) {
			CFRelease(filePath);
			return -2;
		}
		CFRelease(str);
        
        if (!CFURLGetFSRef(sillyThing,&theFSRef)) {
            firstPartOfPath = CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorDefault,sillyThing);
            if (!CFURLGetFSRef(firstPartOfPath,&theFSRef)) {
                CFRelease(firstPartOfPath);
                CFRelease(filePath);
                CFRelease(sillyThing);
                return -1;
            } else {
                CFStringRef lastPathPart;
                char	 lastpart[256];
                
                CFRelease(filePath);
                CFRelease(firstPartOfPath);
                lastPathPart = CFURLCopyLastPathComponent(sillyThing);
                CFRelease(sillyThing);
                
                err = noErr;
                if (resolveAlias) 
                    err = FSResolveAliasFile (&theFSRef,true,&isFolder,&isAlias);

                if (err) 
                    return 2;
                
                err = FSRefMakePath(&theFSRef,(UInt8 *)dst,1000); 
                CFStringGetCString(lastPathPart,lastpart,256, kCFStringEncodingUTF8);
                CFRelease(lastPathPart);
                if (strlen(dst)+1+strlen(lastpart) < 1000) {
                    strcat(dst,"/");
                    strcat(dst,lastpart);
                    
#if defined(__MWERKS__) && !defined(__APPLE__) && !defined(__MACH__)
        filePath   = CFStringCreateWithBytes(kCFAllocatorDefault,(UInt8 *)dst,strlen(dst),gCurrentVMEncoding,false);
        if (filePath == nil) 
            return 2;
        sillyThing = CFURLCreateWithFileSystemPath (kCFAllocatorDefault,filePath,kCFURLPOSIXPathStyle,true);
		CFRelease(filePath);
        filePath = CFURLCopyFileSystemPath (sillyThing, kCFURLHFSPathStyle);
        CFStringGetCString (filePath,dst,1000, gCurrentVMEncoding);
		CFRelease(sillyThing);
        CFRelease(filePath);        
#endif

                    return 0;
                } else
                    return 2;
            }
        }
        
        CFRelease(filePath);
        CFRelease(sillyThing);
        
        if (resolveAlias) 
            err = FSResolveAliasFile (&theFSRef,true,&isFolder,&isAlias);

#if defined(__MWERKS__) && !defined(__APPLE__) && !defined(__MACH__)
		sillyThing = CFURLCreateFromFSRef(kCFAllocatorDefault,&theFSRef);
        filePath = CFURLCopyFileSystemPath (sillyThing, kCFURLHFSPathStyle);
        CFStringGetCString (filePath,dst,1000, gCurrentVMEncoding);
		CFRelease(sillyThing);
        CFRelease(filePath);        
        return 0;
#else
        err = FSRefMakePath(&theFSRef,(UInt8 *)dst,1000); 
        return err;
#endif 
}
Esempio n. 18
0
mDNSlocal void FetchRootTA(mDNS *const m)
{
    CFStringRef urlString = CFSTR("https://data.iana.org/root-anchors/root-anchors.xml");
    CFDataRef xmlData;
    CFStringRef fileRef = NULL;
    const char *xmlFileName = NULL;
    char buf[512];
    CFURLRef url = NULL;
    static unsigned int RootTAFetchInterval = InitialTAFetchInterval;

    (void) m;

    TrustAnchor *ta = (TrustAnchor *)mDNSPlatformMemAllocate(sizeof(TrustAnchor));
    if (!ta)
    {
        LogMsg("FetchRootTA: TrustAnchor alloc failed");
        return;
    }
    memset(ta, 0, sizeof(TrustAnchor));

    url = CFURLCreateWithString(NULL, urlString, NULL);
    if (!url)
    {
        LogMsg("FetchRootTA: CFURLCreateWithString error");
        mDNSPlatformMemFree(ta);
        return;
    }

    // If we can't fetch the XML file e.g., network problems, trigger a timer. All other failures
    // should hardly happen in practice for which schedule the normal interval to refetch the TA.
    if (!CFURLCreateDataAndPropertiesFromResource(kCFAllocatorDefault, url, &xmlData, NULL, NULL, NULL))
    {
        LogInfo("FetchRootTA: CFURLCreateDataAndPropertiesFromResource error");
        CFRelease(url);
        mDNSPlatformMemFree(ta);
        RegisterNotification(m, RootTAFetchInterval);
        RootTAFetchInterval *= 2 + 1;
        return;
    }

    // get the name of the last component from the url, libxml will use it if
    // it has to report an error
    fileRef = CFURLCopyLastPathComponent(url);
    if (fileRef)
    {
        xmlFileName = CFStringGetCStringPtr(fileRef, kCFStringEncodingUTF8);
        if (!xmlFileName)
        {
            if (!CFStringGetCString(fileRef, buf, sizeof(buf), kCFStringEncodingUTF8) )
                strlcpy(buf, "nofile.xml", sizeof(buf));
            xmlFileName = (const char *)buf;
        }
    }

    // Parse the XML and get the CFXMLTree.
    xmlDocPtr tadoc = xmlReadMemory((const char*)CFDataGetBytePtr(xmlData),
        (int)CFDataGetLength(xmlData), xmlFileName, NULL, 0);        

    CFRelease(fileRef);
    CFRelease(url);
    CFRelease(xmlData);

    if (!tadoc)
    {
        LogMsg("FetchRootTA: xmlReadMemory failed");
        goto done;
    }

    xmlNodePtr root = xmlDocGetRootElement(tadoc);
    if (!root)
    {
        LogMsg("FetchRootTA: Cannot get root element");
        goto done;
    }

    if (ParseElement(tadoc, root, ta) && ValidateTrustAnchor(ta))
    {
        // Do the actual addition of TA on the main queue.
        mDNSPlatformDispatchAsync(m, ta, TAComplete);
    }
    else
    {
        if (ta->rds.digest)
            mDNSPlatformMemFree(ta->rds.digest);
        mDNSPlatformMemFree(ta);
    }
done:
    if (tadoc)
        xmlFreeDoc(tadoc);
    RegisterNotification(m, ROOT_TA_UPDATE_INTERVAL);
    RootTAFetchInterval = InitialTAFetchInterval;
    return;
}
Esempio n. 19
0
static pascal OSStatus MultiCartPaneEventHandler (EventHandlerCallRef inHandlerRef, EventRef inEvent, void *inUserData)
{
	OSStatus			err, result = eventNotHandledErr;
	HIViewRef			view;
	DragRef				drag;
	PasteboardRef		pasteboard;
	PasteboardItemID	itemID;
	CFArrayRef			array;
	CFStringRef			flavorType;
	CFIndex				numFlavors;
	ItemCount			numItems;
	int					index = *((int *) inUserData);

	switch (GetEventClass(inEvent))
	{
		case kEventClassControl:
		{
			switch (GetEventKind(inEvent))
			{
				case kEventControlDraw:
				{
					err = GetEventParameter(inEvent, kEventParamDirectObject, typeControlRef, NULL, sizeof(ControlRef), NULL, &view);
					if (err == noErr)
					{
						CGContextRef	ctx;

						err = GetEventParameter(inEvent, kEventParamCGContextRef, typeCGContextRef, NULL, sizeof(CGContextRef), NULL, &ctx);
						if (err == noErr)
						{
							HIThemeFrameDrawInfo	info;
							HIRect					bounds, frame;

							HIViewGetBounds(view, &bounds);

							CGContextSetRGBFillColor(ctx, 1.0f, 1.0f, 1.0f, 1.0f);
							CGContextFillRect(ctx, bounds);

							info.version   = 0;
							info.kind      = kHIThemeFrameTextFieldSquare;
							info.state     = kThemeStateInactive;
							info.isFocused = false;
							err = HIThemeDrawFrame(&bounds, &info, ctx, kHIThemeOrientationNormal);

							if (multiCartDragHilite == index && systemVersion >= 0x1040)
							{
								err = HIThemeSetStroke(kThemeBrushDragHilite, NULL, ctx, kHIThemeOrientationNormal);
								frame = CGRectInset(bounds, 1, 1);
								CGContextBeginPath(ctx);
								CGContextAddRect(ctx, frame);
								CGContextStrokePath(ctx);
							}
						}
					}

					result = noErr;
					break;
				}

				case kEventControlDragEnter:
				{
					err = GetEventParameter(inEvent, kEventParamDirectObject, typeControlRef, NULL, sizeof(ControlRef), NULL, &view);
					if (err == noErr)
					{
						err = GetEventParameter(inEvent, kEventParamDragRef, typeDragRef, NULL, sizeof(DragRef), NULL, &drag);
						if (err == noErr)
						{
							err = GetDragPasteboard(drag, &pasteboard);
							if (err == noErr)
							{
								err = PasteboardGetItemCount(pasteboard, &numItems);
								if (err == noErr && numItems == 1)
								{
									err = PasteboardGetItemIdentifier(pasteboard, 1, &itemID);
									if (err == noErr)
									{
										err = PasteboardCopyItemFlavors(pasteboard, itemID, &array);
										if (err == noErr)
										{
											numFlavors = CFArrayGetCount(array);
											for (CFIndex i = 0; i < numFlavors; i++)
											{
												flavorType = (CFStringRef) CFArrayGetValueAtIndex(array, i);
												if (UTTypeConformsTo(flavorType, CFSTR("public.file-url")))
												{
													Boolean	accept = true;

													err = SetEventParameter(inEvent, kEventParamControlWouldAcceptDrop, typeBoolean, sizeof(Boolean), &accept);
													if (err == noErr)
													{
														multiCartDragHilite = index;
														HIViewSetNeedsDisplay(view, true);
														result = noErr;
													}
												}
											}

											CFRelease(array);
										}
									}
								}
							}
						}
					}

					break;
				}

				case kEventControlDragWithin:
				{
					result = noErr;
					break;
				}

				case kEventControlDragLeave:
				{
					err = GetEventParameter(inEvent, kEventParamDirectObject, typeControlRef, NULL, sizeof(ControlRef), NULL, &view);
					if (err == noErr)
					{
						multiCartDragHilite = -1;
						HIViewSetNeedsDisplay(view, true);
					}

					result = noErr;
					break;
				}

				case kEventControlDragReceive:
				{
					err = GetEventParameter(inEvent, kEventParamDirectObject, typeControlRef, NULL, sizeof(ControlRef), NULL, &view);
					if (err == noErr)
					{
						err = GetEventParameter(inEvent, kEventParamDragRef, typeDragRef, NULL, sizeof(DragRef), NULL, &drag);
						if (err == noErr)
						{
							multiCartDragHilite = -1;
							HIViewSetNeedsDisplay(view, true);

							err = GetDragPasteboard(drag, &pasteboard);
							if (err == noErr)
							{
								err = PasteboardGetItemIdentifier(pasteboard, 1, &itemID);
								if (err == noErr)
								{
									err = PasteboardCopyItemFlavors(pasteboard, itemID, &array);
									if (err == noErr)
									{
										numFlavors = CFArrayGetCount(array);
										for (CFIndex i = 0; i < numFlavors; i++)
										{
											flavorType = (CFStringRef) CFArrayGetValueAtIndex(array, i);
											if (UTTypeConformsTo(flavorType, CFSTR("public.file-url")))
											{
												CFDataRef	flavorData;

												err = PasteboardCopyItemFlavorData(pasteboard, itemID, flavorType, &flavorData);
												if (err == noErr)
												{
													CFIndex	dataSize;
													UInt8	*data;

													dataSize = CFDataGetLength(flavorData);
													data = (UInt8 *) malloc(dataSize);
													if (data)
													{
														CFDataGetBytes(flavorData, CFRangeMake(0, dataSize), data);

														HIViewRef	ctl;
														HIViewID	cid;
														CFStringRef	str;
														CFURLRef	url;

														GetControlID(view, &cid);
														cid.signature = 'MNAM';
														HIViewFindByID(view, cid, &ctl);

														url = CFURLCreateWithBytes(kCFAllocatorDefault, data, dataSize, kCFStringEncodingUTF8, NULL);
														str = CFURLCopyLastPathComponent(url);
														SetStaticTextCFString(ctl, str, true);
														CFRelease(str);
														str = CFURLCopyFileSystemPath(url, kCFURLPOSIXPathStyle);
														if (multiCartPath[cid.id])
															CFRelease(multiCartPath[cid.id]);
														multiCartPath[cid.id] = str;
														CFRelease(url);

														result = noErr;

														free(data);
													}

													CFRelease(flavorData);
												}
											}
										}

										CFRelease(array);
									}
								}
							}
						}
					}
				}
			}
		}
	}

	return (result);
}
int
keychain_import(int argc, char * const *argv)
{
	int ch, result = 0;

	char *inFile = NULL;
	char *kcName = NULL;
	SecKeychainRef kcRef = NULL;
	SecExternalFormat externFormat = kSecFormatUnknown;
	SecExternalItemType itemType = kSecItemTypeUnknown;
	Boolean wrapped = FALSE;
	Boolean nonExtractable = FALSE;
	const char *passphrase = NULL;
	unsigned char *inFileData = NULL;
	unsigned inFileLen = 0;
	CFDataRef inData = NULL;
	unsigned numExtendedAttributes = 0;
	char **attrNames = NULL;
	char **attrValues = NULL;
	Boolean access_specified = FALSE;
	Boolean always_allow = FALSE;
	SecAccessRef access = NULL;
	CFMutableArrayRef trusted_list = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);

	if(argc < 2) {
		result = 2; /* @@@ Return 2 triggers usage message. */
		goto cleanup;
	}
	inFile = argv[1];
	if((argc == 2) && (inFile[0] == '-')) {
		result = 2;
		goto cleanup;
	}
	optind = 2;

    while ((ch = getopt(argc, argv, "k:t:f:P:wxa:hAT:")) != -1)
	{
		switch  (ch)
		{
		case 'k':
			kcName = optarg;
			break;
		case 't':
			if(!strcmp("pub", optarg)) {
				itemType = kSecItemTypePublicKey;
			}
			else if(!strcmp("priv", optarg)) {
				itemType = kSecItemTypePrivateKey;
			}
			else if(!strcmp("session", optarg)) {
				itemType = kSecItemTypeSessionKey;
			}
			else if(!strcmp("cert", optarg)) {
				itemType = kSecItemTypeCertificate;
			}
			else if(!strcmp("agg", optarg)) {
				itemType = kSecItemTypeAggregate;
			}
			else {
				result = 2; /* @@@ Return 2 triggers usage message. */
				goto cleanup;
			}
			break;
		case 'f':
			if(!strcmp("openssl", optarg)) {
				externFormat = kSecFormatOpenSSL;
			}
			else if(!strcmp("openssh1", optarg)) {
				externFormat = kSecFormatSSH;
			}
			else if(!strcmp("openssh2", optarg)) {
				externFormat = kSecFormatSSHv2;
			}
			else if(!strcmp("bsafe", optarg)) {
				externFormat = kSecFormatBSAFE;
			}
			else if(!strcmp("raw", optarg)) {
				externFormat = kSecFormatRawKey;
			}
			else if(!strcmp("pkcs7", optarg)) {
				externFormat = kSecFormatPKCS7;
			}
			else if(!strcmp("pkcs8", optarg)) {
				externFormat = kSecFormatWrappedPKCS8;
			}
			else if(!strcmp("pkcs12", optarg)) {
				externFormat = kSecFormatPKCS12;
			}
			else if(!strcmp("netscape", optarg)) {
				externFormat = kSecFormatNetscapeCertSequence;
			}
			else if(!strcmp("x509", optarg)) {
				externFormat = kSecFormatX509Cert;
			}
			else if(!strcmp("pemseq", optarg)) {
				externFormat = kSecFormatPEMSequence;
			}
			else {
				result = 2; /* @@@ Return 2 triggers usage message. */
				goto cleanup;
			}
			break;
		case 'w':
			wrapped = TRUE;
			break;
		case 'x':
			nonExtractable = TRUE;
			break;
		case 'P':
			passphrase = optarg;
			break;
		case 'a':
			/* this takes an additional argument */
			if(optind > (argc - 1)) {
				result = 2; /* @@@ Return 2 triggers usage message. */
				goto cleanup;
			}
			attrNames  = (char **)realloc(attrNames, numExtendedAttributes * sizeof(char *));
			attrValues = (char **)realloc(attrValues, numExtendedAttributes * sizeof(char *));
			attrNames[numExtendedAttributes]  = optarg;
			attrValues[numExtendedAttributes] = argv[optind];
			numExtendedAttributes++;
			optind++;
			break;
		case 'A':
			always_allow = TRUE;
			access_specified = TRUE;
			break;
		case 'T':
			if (optarg[0])
			{
				SecTrustedApplicationRef app = NULL;
				OSStatus status = noErr;
				/* check whether the argument specifies an application group */
				const char *groupPrefix = "group://";
				size_t prefixLen = strlen(groupPrefix);
				if (strlen(optarg) > prefixLen && !memcmp(optarg, groupPrefix, prefixLen)) {
					const char *groupName = &optarg[prefixLen];
					if ((status = SecTrustedApplicationCreateApplicationGroup(groupName, NULL, &app)) != noErr) {
						sec_error("SecTrustedApplicationCreateApplicationGroup %s: %s", optarg, sec_errstr(status));
					}
				} else {
					if ((status = SecTrustedApplicationCreateFromPath(optarg, &app)) != noErr) {
						sec_error("SecTrustedApplicationCreateFromPath %s: %s", optarg, sec_errstr(status));
					}
				}

				if (status) {
					result = 1;
					goto cleanup;
				}

				CFArrayAppendValue(trusted_list, app);
				CFRelease(app);
			}
			access_specified = TRUE;
			break;
		case '?':
		default:
			result = 2; /* @@@ Return 2 triggers usage message. */
			goto cleanup;
		}
	}

	if(wrapped) {
		switch(externFormat) {
			case kSecFormatOpenSSL:
			case kSecFormatUnknown:		// i.e., use default
				externFormat = kSecFormatWrappedOpenSSL;
				break;
			case kSecFormatSSH:
				externFormat = kSecFormatWrappedSSH;
				break;
			case kSecFormatSSHv2:
				/* there is no wrappedSSHv2 */
				externFormat = kSecFormatWrappedOpenSSL;
				break;
			case kSecFormatWrappedPKCS8:
				/* proceed */
				break;
			default:
				fprintf(stderr, "Don't know how to wrap in specified format/type\n");
				result = 2; /* @@@ Return 2 triggers usage message. */
				goto cleanup;
		}
	}

	if(kcName) {
		kcRef = keychain_open(kcName);
		if(kcRef == NULL) {
			return 1;
		}
	}
	if(readFile(inFile, &inFileData, &inFileLen)) {
		sec_error("Error reading infile %s: %s", inFile, strerror(errno));
		result = 1;
		goto cleanup;
	}
	inData = CFDataCreate(NULL, inFileData, inFileLen);
	if(inData == NULL) {
		result = 1;
		goto cleanup;
	}
	free(inFileData);

	if(access_specified)
	{
		char *accessName = NULL;
		CFStringRef fileStr = CFStringCreateWithCString(NULL, inFile, kCFStringEncodingUTF8);
		if (fileStr) {
			CFURLRef fileURL = CFURLCreateWithFileSystemPath(NULL, fileStr, kCFURLPOSIXPathStyle, FALSE);
			if (fileURL) {
				CFStringRef nameStr = CFURLCopyLastPathComponent(fileURL);
				if (nameStr) {
					CFIndex nameLen = CFStringGetLength(nameStr);
					CFIndex bufLen = 1 + CFStringGetMaximumSizeForEncoding(nameLen, kCFStringEncodingUTF8);
					accessName = (char *)malloc(bufLen);
					if (!CFStringGetCString(nameStr, accessName, bufLen-1, kCFStringEncodingUTF8))
						accessName[0]=0;
					nameLen = strlen(accessName);
					char *p = &accessName[nameLen]; // initially points to terminating null
					while (--nameLen > 0) {
						if (*p == '.') { // strip extension, if any
							*p = '\0';
							break;
						}
						p--;
					}
					safe_CFRelease(&nameStr);
				}
				safe_CFRelease(&fileURL);
			}
			safe_CFRelease(&fileStr);
		}

		result = create_access(accessName, always_allow, trusted_list, &access);

		if (accessName) {
			free(accessName);
		}
		if (result != 0) {
			goto cleanup;
		}
	}

	result = do_keychain_import(kcRef, inData, externFormat, itemType, access,
								nonExtractable, passphrase, inFile, attrNames,
								attrValues, numExtendedAttributes);

cleanup:
	safe_CFRelease(&trusted_list);
	safe_CFRelease(&access);
	safe_CFRelease(&kcRef);
	safe_CFRelease(&inData);

	return result;
}
Esempio n. 21
0
LLDir_Mac::LLDir_Mac()
{
	mDirDelimiter = "/";
	mCurrentDirIndex = -1;
	mCurrentDirCount = -1;
	
	CFBundleRef		mainBundleRef = NULL;
	CFURLRef		executableURLRef = NULL;
	CFStringRef		stringRef = NULL;
	OSStatus		error = noErr;
	FSRef			fileRef;
	CFStringRef		secondLifeString = CFSTR("SecondLife");
	
	mainBundleRef = CFBundleGetMainBundle();
		
	executableURLRef = CFBundleCopyExecutableURL(mainBundleRef);
	
	if (executableURLRef != NULL)
	{
		// mExecutablePathAndName
		CFURLRefToLLString(executableURLRef, mExecutablePathAndName, false);
		
		// mExecutableFilename
		stringRef = CFURLCopyLastPathComponent(executableURLRef);
		CFStringRefToLLString(stringRef, mExecutableFilename, true);
		
		// mExecutableDir
		CFURLRef	executableParentURLRef = CFURLCreateCopyDeletingLastPathComponent(NULL, executableURLRef);
		CFURLRefToLLString(executableParentURLRef, mExecutableDir, true);
		
		// mAppRODataDir
		CFURLRef	resourcesURLRef = CFBundleCopyResourcesDirectoryURL(mainBundleRef);
		CFURLRefToLLString(resourcesURLRef, mAppRODataDir, true);
		
		// mOSUserDir
		error = FSFindFolder(kUserDomain, kApplicationSupportFolderType, true, &fileRef);
		if (error == noErr)
		{
			FSRef	newFileRef;
			
			// Create the directory
			error = CFCreateDirectory(&fileRef, secondLifeString, &newFileRef);
			if (error == noErr)
			{
				// Save the full path to the folder
				FSRefToLLString(&newFileRef, mOSUserDir);
				
				// Create our sub-dirs
				(void) CFCreateDirectory(&newFileRef, CFSTR("data"), NULL);
				//(void) CFCreateDirectory(&newFileRef, CFSTR("cache"), NULL);
				(void) CFCreateDirectory(&newFileRef, CFSTR("logs"), NULL);
				(void) CFCreateDirectory(&newFileRef, CFSTR("user_settings"), NULL);
				(void) CFCreateDirectory(&newFileRef, CFSTR("browser_profile"), NULL);
			}
		}
		
		//mOSCacheDir
		FSRef cacheDirRef;
		error = FSFindFolder(kUserDomain, kCachedDataFolderType, true, &cacheDirRef);
		if (error == noErr)
		{
			FSRefToLLString(&cacheDirRef, mOSCacheDir);
			(void)CFCreateDirectory(&cacheDirRef, CFSTR("SecondLife"),NULL);
		}
		
		// mOSUserAppDir
		mOSUserAppDir = mOSUserDir;
		
		// mTempDir
		error = FSFindFolder(kOnAppropriateDisk, kTemporaryFolderType, true, &fileRef);
		if (error == noErr)
		{
			FSRef	tempRef;
			error = CFCreateDirectory(&fileRef, secondLifeString, &tempRef);
			if (error == noErr)
				FSRefToLLString(&tempRef, mTempDir);
		}
		
		mWorkingDir = getCurPath();

		mLLPluginDir = mAppRODataDir + mDirDelimiter + "llplugin";
				
		CFRelease(executableURLRef);
		executableURLRef = NULL;
	}
}
Esempio n. 22
0
string URL::basename() const
{
    return mkstr(CFURLCopyLastPathComponent(ref));
}
int	__open_file(const char * name, __file_modes mode, __file_handle * handle)
{
	FSSpec					spec;
	OSErr						ioResult;
	HParamBlockRec	pb;
	
	ioResult = __path2fss(name, &spec);
	
	if (ioResult) 
		gSqueakFileLastError = ioResult;
		
	if (__system7present())												/* mm 980424 */
	{																	/* mm 980424 */
		Boolean targetIsFolder, wasAliased;								/* mm 980424 */
		ResolveAliasFile(&spec, true, &targetIsFolder, &wasAliased);	/* mm 980424 */
	}																	/* mm 980424 */
	
	if (ioResult && (ioResult != fnfErr || mode.open_mode == __must_exist))
		return(__io_error);
	
	
#if TARGET_API_MAC_CARBON
	if (ioResult) {
        CFStringRef 	filePath;
        CFURLRef 	    sillyThing, sillyThing2;
        FSRef	        parentFSRef;
    	short int       fileRefNum;
        OSErr           err;
        UniChar         buffer[1024];
        long            tokenLength;
        
		
        filePath   = CFStringCreateWithBytes(kCFAllocatorDefault,(UInt8 *)name,strlen(name),gCurrentVMEncoding,false);
        if (filePath == nil) 
            return __io_error;
        sillyThing = CFURLCreateWithFileSystemPath (kCFAllocatorDefault,filePath,kCFURLHFSPathStyle,false);
        CFRelease(filePath);
        sillyThing2 = CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorDefault,sillyThing);
        err = CFURLGetFSRef(sillyThing2,&parentFSRef);
        if (err == 0) {
            CFRelease(sillyThing);
            CFRelease(sillyThing2);
            return fnfErr;  
        }
        filePath = CFURLCopyLastPathComponent(sillyThing);
        tokenLength = CFStringGetLength(filePath);
        if (tokenLength > 1024) {
            CFRelease(filePath);
            CFRelease(sillyThing);
            CFRelease(sillyThing2);
            return(__io_error);
        }
            
        CFStringGetCharacters(filePath,CFRangeMake(0,tokenLength),buffer);

        CFRelease(filePath);
        CFRelease(sillyThing);
        CFRelease(sillyThing2);

		ioResult = FSCreateFileUnicode(&parentFSRef,tokenLength,buffer,kFSCatInfoNone,NULL,NULL,&spec);  
    	if (ioResult)
			gSqueakFileLastError = ioResult;
    	if (ioResult)
	    	return(__io_error);
	    	
        pb.ioParam.ioNamePtr    = spec.name;
    	pb.ioParam.ioVRefNum    = spec.vRefNum;
    	pb.ioParam.ioPermssn    = (mode.io_mode == __read) ? fsRdPerm : fsRdWrPerm;
    	pb.ioParam.ioMisc       = 0;
    	pb.fileParam.ioFVersNum = 0;
    	pb.fileParam.ioDirID    = spec.parID;
		set_file_type(&spec, mode.binary_io);
		ioResult = PBHOpenDFSync(&pb);  /* HH 10/25/97  was PBHOpenSync */
    	    	
    	if (ioResult)
    		return(__io_error);
    	
    	*handle = pb.ioParam.ioRefNum;
	
	    return(__no_io_error);
	}
#endif
    pb.ioParam.ioNamePtr    = spec.name;
	pb.ioParam.ioVRefNum    = spec.vRefNum;
	pb.ioParam.ioPermssn    = (mode.io_mode == __read) ? fsRdPerm : fsRdWrPerm;
	pb.ioParam.ioMisc       = 0;
	pb.fileParam.ioFVersNum = 0;
	pb.fileParam.ioDirID    = spec.parID;
	
	if (ioResult)
	{
		if (!(ioResult = PBHCreateSync(&pb)))
		{
			if (ioResult) 
				gSqueakFileLastError = ioResult;
			set_file_type(&spec, mode.binary_io);
			ioResult = PBHOpenDFSync(&pb);  /* HH 10/25/97  was PBHOpenSync */
			if (ioResult) 
				gSqueakFileLastError = ioResult;
		}
	}
	else
	{
		if (!(ioResult = PBHOpenDFSync(&pb)) && mode.open_mode == __create_or_truncate)  
		                                  /* HH 10/25/97  was PBHOpenSync */
		{
			pb.ioParam.ioMisc = 0;
			
			ioResult = PBSetEOFSync((ParmBlkPtr) &pb);
			
			if (ioResult)
				gSqueakFileLastError = ioResult;

			if (ioResult)
				PBCloseSync((ParmBlkPtr) &pb);
		} else {
			if (ioResult) 
				gSqueakFileLastError = ioResult;

		}
	}
	
	if (ioResult)
		return(__io_error);
	
	*handle = pb.ioParam.ioRefNum;
	
	return(__no_io_error);
}
Esempio n. 24
0
kim_error kim_os_library_get_caller_name (kim_string *out_application_name)
{
    kim_error err = KIM_NO_ERROR;
    kim_string name = NULL;
    CFBundleRef bundle = CFBundleGetMainBundle ();
    CFStringRef cfname = NULL;

    if (!err && !out_application_name) { err = check_error (KIM_NULL_PARAMETER_ERR); }

    if (!err && bundle) {
        cfname = CFBundleGetValueForInfoDictionaryKey (bundle,
                                                       kCFBundleNameKey);

        if (!cfname || CFGetTypeID (cfname) != CFStringGetTypeID ()) {
            cfname = CFBundleGetValueForInfoDictionaryKey (bundle,
                                                           kCFBundleExecutableKey);
        }

        if (cfname) {
            cfname = CFStringCreateCopy (kCFAllocatorDefault, cfname);
        }
    }

    if (!err && !cfname) {
        kim_string path = NULL;
        CFURLRef cfpath = NULL;
        CFURLRef cfpathnoext = NULL;

        err = kim_os_library_get_application_path (&path);

        if (!err) {
            cfpath = CFURLCreateFromFileSystemRepresentation (kCFAllocatorDefault,
                                                              (const UInt8 *) path,
                                                              strlen (path),
                                                              0);

            if (cfpath) {
                cfpathnoext = CFURLCreateCopyDeletingPathExtension (kCFAllocatorDefault,
                                                                    cfpath);
            }

            if (cfpathnoext) {
                cfname = CFURLCopyLastPathComponent (cfpathnoext);
            } else {
                cfname = CFURLCopyLastPathComponent (cfpath);
            }
        }

        if (cfpathnoext) { CFRelease (cfpathnoext); }
        if (cfpath     ) { CFRelease (cfpath); }
        kim_string_free (&path);
    }

    if (!err && cfname) {
        err = kim_os_string_create_from_cfstring (&name, cfname);
    }

    if (!err) {
        *out_application_name = name;
        name = NULL;

    }

    if (cfname) { CFRelease (cfname); }
    kim_string_free (&name);

    return check_error (err);
}
Esempio n. 25
0
AudioDecoder * AudioDecoder::CreateDecoderForInputSource(InputSource *inputSource, CFStringRef mimeType, CFErrorRef *error)
{
	if(NULL == inputSource)
		return NULL;

	AudioDecoder *decoder = NULL;

	// Open the input source if it isn't already
	if(AutomaticallyOpenDecoders() && !inputSource->IsOpen() && !inputSource->Open(error))
		return NULL;

	// As a factory this class has knowledge of its subclasses
	// It would be possible (and perhaps preferable) to switch to a generic
	// plugin interface at a later date

#if 0
	// If the input is an instance of HTTPInputSource, use the MIME type from the server
	// This code is disabled because most HTTP servers don't send the correct MIME types
	HTTPInputSource *httpInputSource = dynamic_cast<HTTPInputSource *>(inputSource);
	bool releaseMIMEType = false;
	if(!mimeType && httpInputSource && httpInputSource->IsOpen()) {
		mimeType = httpInputSource->CopyContentMIMEType();
		if(mimeType)
			releaseMIMEType = true;
	}
#endif

	// The MIME type takes precedence over the file extension
	if(mimeType) {
#if BUILD_FOR_MAC_OSX
		if(FLACDecoder::HandlesMIMEType(mimeType)) {
			decoder = new FLACDecoder(inputSource);
			if(AutomaticallyOpenDecoders() && !decoder->Open(error)) {
				decoder->mInputSource = NULL;
				delete decoder, decoder = NULL;
			}
		}
		if(NULL == decoder && WavPackDecoder::HandlesMIMEType(mimeType)) {
			decoder = new WavPackDecoder(inputSource);
			if(AutomaticallyOpenDecoders() && !decoder->Open(error)) {
				decoder->mInputSource = NULL;
				delete decoder, decoder = NULL;
			}
		}
		if(NULL == decoder && MPEGDecoder::HandlesMIMEType(mimeType)) {
			decoder = new MPEGDecoder(inputSource);
			if(AutomaticallyOpenDecoders() && !decoder->Open(error)) {
				decoder->mInputSource = NULL;
				delete decoder, decoder = NULL;
			}
		}
		if(NULL == decoder && OggVorbisDecoder::HandlesMIMEType(mimeType)) {
			decoder = new OggVorbisDecoder(inputSource);
			if(AutomaticallyOpenDecoders() && !decoder->Open(error)) {
				decoder->mInputSource = NULL;
				delete decoder, decoder = NULL;
			}
		}
		if(NULL == decoder && MusepackDecoder::HandlesMIMEType(mimeType)) {
			decoder = new MusepackDecoder(inputSource);
			if(AutomaticallyOpenDecoders() && !decoder->Open(error)) {
				decoder->mInputSource = NULL;
				delete decoder, decoder = NULL;
			}
		}
		if(NULL == decoder && MonkeysAudioDecoder::HandlesMIMEType(mimeType)) {
			decoder = new MonkeysAudioDecoder(inputSource);
			if(AutomaticallyOpenDecoders() && !decoder->Open(error)) {
				decoder->mInputSource = NULL;
				delete decoder, decoder = NULL;
			}
		}
		if(NULL == decoder && OggSpeexDecoder::HandlesMIMEType(mimeType)) {
			decoder = new OggSpeexDecoder(inputSource);
			if(AutomaticallyOpenDecoders() && !decoder->Open(error)) {
				decoder->mInputSource = NULL;
				delete decoder, decoder = NULL;
			}
		}
		if(NULL == decoder && MODDecoder::HandlesMIMEType(mimeType)) {
			decoder = new MODDecoder(inputSource);
			if(AutomaticallyOpenDecoders() && !decoder->Open(error)) {
				decoder->mInputSource = NULL;
				delete decoder, decoder = NULL;
			}
		}
		if(NULL == decoder && LibsndfileDecoder::HandlesMIMEType(mimeType)) {
			decoder = new LibsndfileDecoder(inputSource);
			if(AutomaticallyOpenDecoders() && !decoder->Open(error)) {
				decoder->mInputSource = NULL;
				delete decoder, decoder = NULL;
			}
		}
#endif
		if(NULL == decoder && CoreAudioDecoder::HandlesMIMEType(mimeType)) {
			decoder = new CoreAudioDecoder(inputSource);
			if(AutomaticallyOpenDecoders() && !decoder->Open(error)) {
				decoder->mInputSource = NULL;
				delete decoder, decoder = NULL;
			}
		}

#if 0
		if(releaseMIMEType)
			CFRelease(mimeType), mimeType = NULL;
#endif

		if(decoder)
			return decoder;
	}

	// If no MIME type was specified, use the extension-based resolvers

	CFURLRef inputURL = inputSource->GetURL();
	if(!inputURL)
		return NULL;

	CFStringRef pathExtension = CFURLCopyPathExtension(inputURL);
	if(!pathExtension) {
		if(error) {
			CFMutableDictionaryRef errorDictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, 
																			   32,
																			   &kCFTypeDictionaryKeyCallBacks,
																			   &kCFTypeDictionaryValueCallBacks);

			CFStringRef displayName = CFURLCopyLastPathComponent(inputURL);
			CFStringRef errorString = CFStringCreateWithFormat(kCFAllocatorDefault, 
															   NULL, 
															   CFCopyLocalizedString(CFSTR("The type of the file “%@” could not be determined."), ""), 
															   displayName);

			CFDictionarySetValue(errorDictionary, 
								 kCFErrorLocalizedDescriptionKey, 
								 errorString);

			CFDictionarySetValue(errorDictionary, 
								 kCFErrorLocalizedFailureReasonKey, 
								 CFCopyLocalizedString(CFSTR("Unknown file type"), ""));

			CFDictionarySetValue(errorDictionary, 
								 kCFErrorLocalizedRecoverySuggestionKey, 
								 CFCopyLocalizedString(CFSTR("The file's extension may be missing or may not match the file's type."), ""));

			CFRelease(errorString), errorString = NULL;
			CFRelease(displayName), displayName = NULL;

			*error = CFErrorCreate(kCFAllocatorDefault, 
								   InputSourceErrorDomain, 
								   InputSourceFileNotFoundError,
								   errorDictionary);
			
			CFRelease(errorDictionary), errorDictionary = NULL;				
		}

		return NULL;
	}

	// TODO: Some extensions (.oga for example) support multiple audio codecs (Vorbis, FLAC, Speex)
	// and if openDecoder is false the wrong decoder type may be returned, since the file isn't analyzed
	// until Open() is called
	
#if BUILD_FOR_MAC_OSX
	if(FLACDecoder::HandlesFilesWithExtension(pathExtension)) {
		decoder = new FLACDecoder(inputSource);
		if(AutomaticallyOpenDecoders() && !decoder->Open(error)) {
			decoder->mInputSource = NULL;
			delete decoder, decoder = NULL;
		}
	}
	if(NULL == decoder && WavPackDecoder::HandlesFilesWithExtension(pathExtension)) {
		decoder = new WavPackDecoder(inputSource);
		if(AutomaticallyOpenDecoders() && !decoder->Open(error)) {
			decoder->mInputSource = NULL;
			delete decoder, decoder = NULL;
		}
	}
	if(NULL == decoder && MPEGDecoder::HandlesFilesWithExtension(pathExtension)) {
		decoder = new MPEGDecoder(inputSource);
		if(AutomaticallyOpenDecoders() && !decoder->Open(error)) {
			decoder->mInputSource = NULL;
			delete decoder, decoder = NULL;
		}
	}
	if(NULL == decoder && OggVorbisDecoder::HandlesFilesWithExtension(pathExtension)) {
		decoder = new OggVorbisDecoder(inputSource);
		if(AutomaticallyOpenDecoders() && !decoder->Open(error)) {
			decoder->mInputSource = NULL;
			delete decoder, decoder = NULL;
		}
	}
	if(NULL == decoder && MusepackDecoder::HandlesFilesWithExtension(pathExtension)) {
		decoder = new MusepackDecoder(inputSource);
		if(AutomaticallyOpenDecoders() && !decoder->Open(error)) {
			decoder->mInputSource = NULL;
			delete decoder, decoder = NULL;
		}
	}
	if(NULL == decoder && MonkeysAudioDecoder::HandlesFilesWithExtension(pathExtension)) {
		decoder = new MonkeysAudioDecoder(inputSource);
		if(AutomaticallyOpenDecoders() && !decoder->Open(error)) {
			decoder->mInputSource = NULL;
			delete decoder, decoder = NULL;
		}
	}
	if(NULL == decoder && OggSpeexDecoder::HandlesFilesWithExtension(pathExtension)) {
		decoder = new OggSpeexDecoder(inputSource);
		if(AutomaticallyOpenDecoders() && !decoder->Open(error)) {
			decoder->mInputSource = NULL;
			delete decoder, decoder = NULL;
		}
	}
	if(NULL == decoder && MODDecoder::HandlesFilesWithExtension(pathExtension)) {
		decoder = new MODDecoder(inputSource);
		if(AutomaticallyOpenDecoders() && !decoder->Open(error)) {
			decoder->mInputSource = NULL;
			delete decoder, decoder = NULL;
		}
	}
	if(NULL == decoder && LibsndfileDecoder::HandlesFilesWithExtension(pathExtension)) {
		decoder = new LibsndfileDecoder(inputSource);
		if(AutomaticallyOpenDecoders() && !decoder->Open(error)) {
			decoder->mInputSource = NULL;
			delete decoder, decoder = NULL;
		}
	}
#endif
	if(NULL == decoder && CoreAudioDecoder::HandlesFilesWithExtension(pathExtension)) {
		decoder = new CoreAudioDecoder(inputSource);
		if(AutomaticallyOpenDecoders() && !decoder->Open(error)) {
			decoder->mInputSource = NULL;
			delete decoder, decoder = NULL;
		}
	}

	CFRelease(pathExtension), pathExtension = NULL;

	return decoder;
}
Esempio n. 26
0
int
Tcl_MacOSXOpenVersionedBundleResources(
    Tcl_Interp *interp,
    const char *bundleName,
    const char *bundleVersion,
    int hasResourceFile,
    int maxPathLen,
    char *libraryPath)
{
#ifdef HAVE_COREFOUNDATION
    CFBundleRef bundleRef, versionedBundleRef = NULL;
    CFStringRef bundleNameRef;
    CFURLRef libURL;

    libraryPath[0] = '\0';

    bundleNameRef = CFStringCreateWithCString(NULL, bundleName,
	    kCFStringEncodingUTF8);

    bundleRef = CFBundleGetBundleWithIdentifier(bundleNameRef);
    CFRelease(bundleNameRef);

    if (bundleVersion && bundleRef) {
	/*
	 * Create bundle from bundleVersion subdirectory of 'Versions'.
	 */

	CFURLRef bundleURL = CFBundleCopyBundleURL(bundleRef);

	if (bundleURL) {
	    CFStringRef bundleVersionRef = CFStringCreateWithCString(NULL,
		    bundleVersion, kCFStringEncodingUTF8);

	    if (bundleVersionRef) {
		CFStringRef bundleTailRef = CFURLCopyLastPathComponent(
			bundleURL);

		if (bundleTailRef) {
		    if (CFStringCompare(bundleTailRef, bundleVersionRef, 0) ==
			    kCFCompareEqualTo) {
			versionedBundleRef = (CFBundleRef) CFRetain(bundleRef);
		    }
		    CFRelease(bundleTailRef);
		}
		if (!versionedBundleRef) {
		    CFURLRef versURL = CFURLCreateCopyAppendingPathComponent(
			    NULL, bundleURL, CFSTR("Versions"), TRUE);

		    if (versURL) {
			CFURLRef versionedBundleURL =
				CFURLCreateCopyAppendingPathComponent(
				NULL, versURL, bundleVersionRef, TRUE);
			if (versionedBundleURL) {
			    versionedBundleRef = CFBundleCreate(NULL,
				    versionedBundleURL);
			    CFRelease(versionedBundleURL);
			}
			CFRelease(versURL);
		    }
		}
		CFRelease(bundleVersionRef);
	    }
	    CFRelease(bundleURL);
	}
	if (versionedBundleRef) {
	    bundleRef = versionedBundleRef;
	}
    }

    if (bundleRef) {
	if (hasResourceFile) {
	    /*
	     * Dynamically acquire address for CFBundleOpenBundleResourceMap
	     * symbol, since it is only present in full CoreFoundation on Mac
	     * OS X and not in CFLite on pure Darwin.
	     */

	    static int initialized = FALSE;
	    static short (*openresourcemap)(CFBundleRef) = NULL;

	    if (!initialized) {
#if TCL_DYLD_USE_DLFCN
#if MAC_OS_X_VERSION_MIN_REQUIRED < 1040
		if (tclMacOSXDarwinRelease >= 8)
#endif
		{
		    const char *errMsg = nil;
		    openresourcemap = dlsym(RTLD_NEXT,
			    "CFBundleOpenBundleResourceMap");
		    if (!openresourcemap) {
			errMsg = dlerror();
			TclLoadDbgMsg("dlsym() failed: %s", errMsg);
		    }
		}
		if (!openresourcemap)
#endif
		{
#if TCL_DYLD_USE_NSMODULE
		    NSSymbol nsSymbol = NULL;
		    if (NSIsSymbolNameDefinedWithHint(
			    "_CFBundleOpenBundleResourceMap",
			    "CoreFoundation")) {
			nsSymbol = NSLookupAndBindSymbolWithHint(
				"_CFBundleOpenBundleResourceMap",
				"CoreFoundation");
			if (nsSymbol) {
			    openresourcemap = NSAddressOfSymbol(nsSymbol);
			}
		    }
#endif
		}
		initialized = TRUE;
	    }

	    if (openresourcemap) {
		short refNum;

		refNum = openresourcemap(bundleRef);
	    }
	}

	libURL = CFBundleCopyResourceURL(bundleRef, CFSTR("Scripts"),
		NULL, NULL);

	if (libURL) {
	    /*
	     * FIXME: This is a quick fix, it is probably not right for
	     * internationalization.
	     */

	    CFURLGetFileSystemRepresentation(libURL, TRUE,
		    (unsigned char*) libraryPath, maxPathLen);
	    CFRelease(libURL);
	}
	if (versionedBundleRef) {
	    CFRelease(versionedBundleRef);
	}
    }

    if (libraryPath[0]) {
	return TCL_OK;
    } else {
	return TCL_ERROR;
    }
#else  /* HAVE_COREFOUNDATION */
    return TCL_ERROR;
#endif /* HAVE_COREFOUNDATION */
}
Esempio n. 27
0
URL_TYPE createURLByMakingDirectoryAtURLWithName(URL_TYPE parent, STRING_TYPE name) {
	CFURLRef newDirectory = NULL;

	CFAllocatorRef allocator = parent ? CFGetAllocator(parent) : name ? CFGetAllocator(name) : kCFAllocatorDefault;

	if (parent) parent = CFRetain(parent);
	else {
		char *cwdBytes = alloca(PATH_MAX);
		getcwd(cwdBytes, PATH_MAX);
		parent = CFURLCreateFromFileSystemRepresentation(allocator, (const unsigned char *)cwdBytes, strlen(cwdBytes), /*isDirectory*/ true);
		if (!name) {
			newDirectory = parent;
			goto end;
		}
	}
	if (!parent)
		NSLog(CFSTR("in createURLByMakingDirectoryAtURLWithName in CFGrowlAdditions: parent directory URL is NULL (please tell the Growl developers)\n"), parent);
	else {
		if (name)
			name = CFRetain(name);
		else {
			name = CFURLCopyLastPathComponent(parent);
			CFURLRef newParent = CFURLCreateCopyDeletingLastPathComponent(allocator, parent);
			CFRelease(parent);
			parent = newParent;
		}

		if (!name)
			NSLog(CFSTR("in createURLByMakingDirectoryAtURLWithName in CFGrowlAdditions: name of directory to create is NULL (please tell the Growl developers)\n"), parent);
		else {
			FSRef parentRef;
			if (!CFURLGetFSRef(parent, &parentRef))
				NSLog(CFSTR("in createURLByMakingDirectoryAtURLWithName in CFGrowlAdditions: could not create FSRef for parent directory at %@ (please tell the Growl developers)\n"), parent);
			else {
				FSRef newDirectoryRef;

				struct HFSUniStr255 nameUnicode;
				CFRange range = { 0, MIN(CFStringGetLength(name), USHRT_MAX) };
				CFStringGetCharacters(name, range, nameUnicode.unicode);
				nameUnicode.length = range.length;

				struct FSRefParam refPB = {
					.ref              = &parentRef,
					.nameLength       = nameUnicode.length,
					.name             = nameUnicode.unicode,
					.whichInfo        = kFSCatInfoNone,
					.catInfo          = NULL,
					.textEncodingHint = kTextEncodingUnknown,
					.newRef           = &newDirectoryRef,
				};
				
				OSStatus err = PBCreateDirectoryUnicodeSync(&refPB);
				if (err == dupFNErr) {
					//dupFNErr == file (or folder) exists already. this is fine.
					err = PBMakeFSRefUnicodeSync(&refPB);
				}
				if (err == noErr) {
					NSLog(CFSTR("PBCreateDirectoryUnicodeSync or PBMakeFSRefUnicodeSync returned %li; calling CFURLCreateFromFSRef"), (long)err); //XXX
					newDirectory = CFURLCreateFromFSRef(allocator, &newDirectoryRef);
					NSLog(CFSTR("CFURLCreateFromFSRef returned %@"), newDirectory); //XXX
				} else
					NSLog(CFSTR("in createURLByMakingDirectoryAtURLWithName in CFGrowlAdditions: could not create directory '%@' in parent directory at %@: FSCreateDirectoryUnicode returned %li (please tell the Growl developers)"), name, parent, (long)err);
			}

			CFRelease(parent);
		} //if (name)
		CFRelease(name);
	} //if (parent)

end:
	return newDirectory;
}

#ifndef COPYFORK_BUFSIZE
#	define COPYFORK_BUFSIZE 5242880U /*5 MiB*/
#endif

static OSStatus copyFork(const struct HFSUniStr255 *forkName, const FSRef *srcFile, const FSRef *destDir, const struct HFSUniStr255 *destName, FSRef *outDestFile) {
	OSStatus err, closeErr;
	struct FSForkIOParam srcPB = {
		.ref = srcFile,
		.forkNameLength = forkName->length,
		.forkName = forkName->unicode,
		.permissions = fsRdPerm,
	};
	unsigned char debuggingPathBuf[PATH_MAX] = "";
	OSStatus debuggingPathErr;

	err = PBOpenForkSync(&srcPB);
	if (err != noErr) {
		debuggingPathErr = FSRefMakePath(srcFile, debuggingPathBuf, PATH_MAX);
		if (debuggingPathErr != noErr)
			snprintf((char *)debuggingPathBuf, PATH_MAX, "(could not get path for source file: FSRefMakePath returned %li)", (long)debuggingPathErr);
		NSLog(CFSTR("in copyFork in CFGrowlAdditions: PBOpenForkSync (source: %s) returned %li"), debuggingPathBuf, (long)err);
	} else {
		FSRef destFile;

		/*the first thing to do is get the name of the destination file, if one
		 *	wasn't provided.
		 *and while we're at it, we get the catalogue info as well.
		 */
		struct FSCatalogInfo catInfo;
		struct FSRefParam refPB = {
			.ref       = srcFile,
			.whichInfo = kFSCatInfoGettableInfo & kFSCatInfoSettableInfo,
			.catInfo   = &catInfo,
			.spec      = NULL,
			.parentRef = NULL,
			.outName   = destName ? NULL : (struct HFSUniStr255 *)(destName = alloca(sizeof(struct HFSUniStr255))),
		};

		err = PBGetCatalogInfoSync(&refPB);
		if (err != noErr) {
			debuggingPathErr = FSRefMakePath(srcFile, debuggingPathBuf, PATH_MAX);
			if (debuggingPathErr != noErr)
				snprintf((char *)debuggingPathBuf, PATH_MAX, "(could not get path for source file: FSRefMakePath returned %li)", (long)debuggingPathErr);
			NSLog(CFSTR("in copyFork in CFGrowlAdditions: PBGetCatalogInfoSync (source: %s) returned %li"), debuggingPathBuf, (long)err);
		} else {
			refPB.ref              = destDir;
			refPB.nameLength       = destName->length;
			refPB.name             = destName->unicode;
			refPB.textEncodingHint = kTextEncodingUnknown;
			refPB.newRef           = &destFile;

			const char *functionName = "PBMakeFSRefUnicodeSync"; //for error-reporting message

			err = PBMakeFSRefUnicodeSync(&refPB);
			if ((err != noErr) && (err != fnfErr)) {
			handleMakeFSRefError:
				debuggingPathErr = FSRefMakePath(destDir, debuggingPathBuf, PATH_MAX);
				if (debuggingPathErr != noErr)
					snprintf((char *)debuggingPathBuf, PATH_MAX, "(could not get path for destination directory: FSRefMakePath returned %li)", (long)debuggingPathErr);

				//get filename too
				CFStringRef debuggingFilename = CFStringCreateWithCharactersNoCopy(kCFAllocatorDefault,
																				   destName->unicode,
																				   destName->length,
																				   /*contentsDeallocator*/ kCFAllocatorNull);
				if (!debuggingFilename)
					debuggingFilename = CFStringCreateWithCStringNoCopy(kCFAllocatorDefault, "(could not get filename for destination file: CFStringCreateWithCharactersNoCopy returned NULL)", kCFStringEncodingASCII, /*contentsDeallocator*/ kCFAllocatorNull);

				NSLog(CFSTR("in copyFork in CFGrowlAdditions: %s (destination: %s/%@) returned %li"), functionName, debuggingPathBuf, debuggingFilename, (long)err);

				if (debuggingFilename) CFRelease(debuggingFilename);
			} else {
				//that file doesn't exist in that folder; create it.
				err = PBCreateFileUnicodeSync(&refPB);
				if (err == noErr) {
					/*make sure the Finder knows about the new file.
					 *FNNotify returns a status code too, but this isn't an
					 *	essential step, so we just ignore it.
					 */
					FNNotify(destDir, kFNDirectoryModifiedMessage, kNilOptions);
				} else if (err == dupFNErr) {
					/*dupFNErr: the file already exists.
					 *we can safely ignore this error.
					 */
					err = noErr;
				} else {
					functionName = "PBCreateFileUnicodeSync";
					goto handleMakeFSRefError;
				}
			}
		}
		if (err == noErr) {
			if (outDestFile)
				memcpy(outDestFile, &destFile, sizeof(destFile));

			struct FSForkIOParam destPB = {
				.ref            = &destFile,
				.forkNameLength = forkName->length,
				.forkName       = forkName->unicode,
				.permissions    = fsWrPerm,
			};
			err = PBOpenForkSync(&destPB);
			NSLog(CFSTR("in copyFork in CFGrowlAdditions: PBOpenForkSync (dest) returned %li"), (long)err);
			if (err != noErr) {
				debuggingPathErr = FSRefMakePath(&destFile, debuggingPathBuf, PATH_MAX);
				if (debuggingPathErr != noErr)
					snprintf((char *)debuggingPathBuf, PATH_MAX, "(could not get path for dest file: FSRefMakePath returned %li)", (long)debuggingPathErr);
				NSLog(CFSTR("in copyFork in CFGrowlAdditions: PBOpenForkSync (destination: %s) returned %li"), debuggingPathBuf, (long)err);
			} else {
				void *buf = malloc(COPYFORK_BUFSIZE);
				if (buf) {
					srcPB.buffer = destPB.buffer = buf;
					srcPB.requestCount = COPYFORK_BUFSIZE;
					while (err == noErr) {
						err = PBReadForkSync(&srcPB);
						if (err == eofErr) {
							err = noErr;
							if (srcPB.actualCount == 0)
								break;
						}
						if (err != noErr) {
							debuggingPathErr = FSRefMakePath(&destFile, debuggingPathBuf, PATH_MAX);
							if (debuggingPathErr != noErr)
								snprintf((char *)debuggingPathBuf, PATH_MAX, "(could not get path for source file: FSRefMakePath returned %li)", (long)debuggingPathErr);
							NSLog(CFSTR("in copyFork in CFGrowlAdditions: PBReadForkSync (source: %s) returned %li"), debuggingPathBuf, (long)err);
						} else {
							destPB.requestCount = srcPB.actualCount;
							err = PBWriteForkSync(&destPB);
							if (err != noErr) {
								debuggingPathErr = FSRefMakePath(&destFile, debuggingPathBuf, PATH_MAX);
								if (debuggingPathErr != noErr)
									snprintf((char *)debuggingPathBuf, PATH_MAX, "(could not get path for dest file: FSRefMakePath returned %li)", (long)debuggingPathErr);
								NSLog(CFSTR("in copyFork in CFGrowlAdditions: PBWriteForkSync (destination: %s) returned %li"), debuggingPathBuf, (long)err);
							}
						}
					}

					free(buf);
				}

				closeErr = PBCloseForkSync(&destPB);
				if (closeErr != noErr) {
					debuggingPathErr = FSRefMakePath(&destFile, debuggingPathBuf, PATH_MAX);
					if (debuggingPathErr != noErr)
						snprintf((char *)debuggingPathBuf, PATH_MAX, "(could not get path for dest file: FSRefMakePath returned %li)", (long)debuggingPathErr);
					NSLog(CFSTR("in copyFork in CFGrowlAdditions: PBCloseForkSync (destination: %s) returned %li"), debuggingPathBuf, (long)err);
				}
				if (err == noErr) err = closeErr;
			}
		}

		closeErr = PBCloseForkSync(&srcPB);
		if (closeErr != noErr) {
			debuggingPathErr = FSRefMakePath(&destFile, debuggingPathBuf, PATH_MAX);
			if (debuggingPathErr != noErr)
				snprintf((char *)debuggingPathBuf, PATH_MAX, "(could not get path for source file: FSRefMakePath returned %li)", (long)debuggingPathErr);
			NSLog(CFSTR("in copyFork in CFGrowlAdditions: PBCloseForkSync (source: %s) returned %li"), debuggingPathBuf, (long)err);
		}
		if (err == noErr) err = closeErr;
	}

	return err;
}

static OSStatus GrowlCopyObjectSync(const FSRef *fileRef, const FSRef *destRef, FSRef *destFileRef) {
	OSStatus err;
	struct HFSUniStr255 forkName;
	struct FSForkIOParam forkPB = {
		.ref = fileRef,
		.forkIterator = {
			.initialize = 0L
		},
		.outForkName = &forkName,
	};
	
	do {
		err = PBIterateForksSync(&forkPB);
		NSLog(CFSTR("PBIterateForksSync returned %li"), (long)err);
		if (err != noErr) {
			if (err != errFSNoMoreItems)
				NSLog(CFSTR("in GrowlCopyObjectSync in CFGrowlAdditions: PBIterateForksSync returned %li"), (long)err);
		} else {
			err = copyFork(&forkName, fileRef, destRef, /*destName*/ NULL, /*outDestFile*/ destFileRef);
			//copyFork prints its own error messages
		}
	} while (err == noErr);
	if (err == errFSNoMoreItems) err = noErr;

	return err;
}

CFURLRef createURLByCopyingFileFromURLToDirectoryURL(CFURLRef file, CFURLRef dest) {
	CFURLRef destFileURL = NULL;

	FSRef fileRef, destRef, destFileRef;
	Boolean gotFileRef = CFURLGetFSRef(file, &fileRef);
	Boolean gotDestRef = CFURLGetFSRef(dest, &destRef);
	if (!gotFileRef)
		NSLog(CFSTR("in createURLByCopyingFileFromURLToDirectoryURL in CFGrowlAdditions: CFURLGetFSRef failed with source URL %@"), file);
	else if (!gotDestRef)
		NSLog(CFSTR("in createURLByCopyingFileFromURLToDirectoryURL in CFGrowlAdditions: CFURLGetFSRef failed with destination URL %@"), dest);
	else {
		OSStatus err;

		/*
		 * 10.2 has a problem with weak symbols in frameworks so we use
		 * MAC_OS_X_VERSION_MIN_REQUIRED >= 10.3.
		 */
#if defined(NSAppKitVersionNumber10_3) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4 && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_3
		if (FSCopyObjectSync) {
			err = FSCopyObjectSync(&fileRef, &destRef, /*destName*/ NULL, &destFileRef, kFSFileOperationOverwrite);
		} else {
#endif
			err = GrowlCopyObjectSync(&fileRef, &destRef, &destFileRef);
#if defined(NSAppKitVersionNumber10_3) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4 && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_3
		}
#endif

		if (err == noErr)
			destFileURL = CFURLCreateFromFSRef(kCFAllocatorDefault, &destFileRef);
		else
			NSLog(CFSTR("in createURLByCopyingFileFromURLToDirectoryURL in CFGrowlAdditions: CopyObjectSync returned %li for source URL %@"), (long)err, file);
	}

	return destFileURL;
}
Esempio n. 28
0
Boolean MultiCartDialog (void)
{
	OSStatus	err;
	IBNibRef	nibRef;

	multiCartDragHilite = -1;
	multiCartDialogResult = false;

	err = CreateNibReference(kMacS9XCFString, &nibRef);
	if (err == noErr)
	{
		WindowRef	window;

		err = CreateWindowFromNib(nibRef, CFSTR("MultiCart"), &window);
		if (err == noErr)
		{
			static int	index[2] = { 0, 1 };

			EventHandlerRef	wRef, cRef[2];
			EventHandlerUPP	wUPP, cUPP[2];
			EventTypeSpec	wEvent[] = { { kEventClassCommand, kEventCommandProcess      },
										 { kEventClassCommand, kEventCommandUpdateStatus } },
							cEvent[] = { { kEventClassControl, kEventControlDraw         },
										 { kEventClassControl, kEventControlDragEnter    },
										 { kEventClassControl, kEventControlDragWithin   },
										 { kEventClassControl, kEventControlDragLeave    },
										 { kEventClassControl, kEventControlDragReceive  } };
			HIViewRef		ctl, root, pane[2];
			HIViewID		cid;

			root = HIViewGetRoot(window);

			wUPP = NewEventHandlerUPP(MultiCartEventHandler);
			err = InstallWindowEventHandler(window, wUPP, GetEventTypeCount(wEvent), wEvent, (void *) window, &wRef);
			err = SetAutomaticControlDragTrackingEnabledForWindow(window, true);

			for (int i = 0; i < 2; i++)
			{
				cid.id = i;

				cid.signature = 'MPan';
				HIViewFindByID(root, cid, &pane[i]);
				cUPP[i] = NewEventHandlerUPP(MultiCartPaneEventHandler);
				err = InstallControlEventHandler(pane[i], cUPP[i], GetEventTypeCount(cEvent), cEvent, (void *) &index[i], &cRef[i]);
				err = SetControlDragTrackingEnabled(pane[i], true);

				cid.signature = 'MNAM';
				HIViewFindByID(root, cid, &ctl);
				SetStaticTextTrunc(ctl, truncEnd, false);
				if (multiCartPath[i])
				{
					CFStringRef	str;
					CFURLRef	url;

					url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, multiCartPath[i], kCFURLPOSIXPathStyle, false);
					str = CFURLCopyLastPathComponent(url);
					SetStaticTextCFString(ctl, str, false);
					CFRelease(str);
					CFRelease(url);
				}
				else
					SetStaticTextCFString(ctl, CFSTR(""), false);
			}

			MoveWindowPosition(window, kWindowMultiCart, false);
			ShowWindow(window);
			err = RunAppModalLoopForWindow(window);
			HideWindow(window);
			SaveWindowPosition(window, kWindowMultiCart);

			for (int i = 0; i < 2; i++)
			{
				err = RemoveEventHandler(cRef[i]);
				DisposeEventHandlerUPP(cUPP[i]);
			}

			err = RemoveEventHandler(wRef);
			DisposeEventHandlerUPP(wUPP);

			CFRelease(window);
		}

		DisposeNibReference(nibRef);
	}

	return (multiCartDialogResult);
}
static int do_keychain_import(
	SecKeychainRef		kcRef,
	CFDataRef			inData,
	SecExternalFormat   externFormat,
	SecExternalItemType itemType,
	SecAccessRef		access,
	Boolean				nonExtractable,
	const char			*passphrase,
	const char			*fileName,
	char				**attrNames,
	char				**attrValues,
	unsigned			numExtendedAttributes)
{
	SecKeyImportExportParameters	keyParams;
	OSStatus		ortn;
	CFStringRef		fileStr;
	CFArrayRef		outArray = NULL;
	int				result = 0;
	int				numCerts = 0;
	int				numKeys = 0;
	int				numIdentities = 0;
	int				tryCount = 0;
	CFIndex			dex;
	CFIndex			numItems = 0;
	CFStringRef		passStr = NULL;
	CFStringRef		promptStr = NULL;
	CFStringRef		retryStr = NULL;

	/*
	 * Specify some kind of passphrase in case caller doesn't know this
	 * is a wrapped object
	 */
	memset(&keyParams, 0, sizeof(SecKeyImportExportParameters));
	keyParams.version = SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION;
	if(passphrase != NULL) {
		passStr = CFStringCreateWithCString(NULL, passphrase, kCFStringEncodingASCII);
		keyParams.passphrase = passStr;
	}
	else {
		keyParams.flags = kSecKeySecurePassphrase;
	}
	if(nonExtractable) {
        // explicitly set the key attributes, omitting the CSSM_KEYATTR_EXTRACTABLE bit
        keyParams.keyAttributes = CSSM_KEYATTR_PERMANENT | CSSM_KEYATTR_SENSITIVE;
    }
	keyParams.accessRef = access;

	fileStr = CFStringCreateWithCString(NULL, fileName, kCFStringEncodingUTF8);
	if (fileStr) {
		CFURLRef fileURL = CFURLCreateWithFileSystemPath(NULL, fileStr, kCFURLPOSIXPathStyle, FALSE);
		if (fileURL) {
			CFStringRef nameStr = CFURLCopyLastPathComponent(fileURL);
			if (nameStr) {
				safe_CFRelease(&fileStr);
				fileStr = nameStr;
			}
			safe_CFRelease(&fileURL);
		}
	}
	promptStr = CFStringCreateWithFormat(NULL, NULL, KC_IMPORT_KEY_PASSWORD_MESSAGE, fileStr);
	retryStr = CFStringCreateWithFormat(NULL, NULL, KC_IMPORT_KEY_PASSWORD_RETRYMESSAGE, fileStr);

	while (TRUE)
	{
		keyParams.alertPrompt = (tryCount == 0) ? promptStr : retryStr;

		ortn = SecKeychainItemImport(inData,
									 fileStr,
									 &externFormat,
									 &itemType,
									 0,		/* flags not used (yet) */
									 &keyParams,
									 kcRef,
									 &outArray);

		if(ortn) {
			if (ortn == errSecPkcs12VerifyFailure && ++tryCount < 3) {
				continue;
			}
			sec_perror("SecKeychainItemImport", ortn);
			result = 1;
			goto cleanup;
		}
		break;
	}

	/*
	 * Parse returned items & report to user
	 */
	if(outArray == NULL) {
		sec_error("No keychain items found");
		result = 1;
		goto cleanup;
	}
	numItems = CFArrayGetCount(outArray);
	for(dex=0; dex<numItems; dex++) {
		CFTypeRef item = CFArrayGetValueAtIndex(outArray, dex);
		CFTypeID itemType = CFGetTypeID(item);
		if(itemType == SecIdentityGetTypeID()) {
			numIdentities++;
		}
		else if(itemType == SecCertificateGetTypeID()) {
			numCerts++;
		}
		else if(itemType == SecKeyGetTypeID()) {
			numKeys++;
		}
		else {
			sec_error("Unexpected item type returned from SecKeychainItemImport");
			result = 1;
			goto cleanup;
		}
	}
	if(numIdentities) {
		char *str;
		if(numIdentities > 1) {
			str = "identities";
		}
		else {
			str = "identity";
		}
		fprintf(stdout, "%d %s imported.\n", numIdentities, str);
	}
	if(numKeys) {
		char *str;
		if(numKeys > 1) {
			str = "keys";
		}
		else {
			str = "key";
		}
		fprintf(stdout, "%d %s imported.\n", numKeys, str);
	}
	if(numCerts) {
		char *str;
		if(numCerts > 1) {
			str = "certificates";
		}
		else {
			str = "certificate";
		}
		fprintf(stdout, "%d %s imported.\n", numCerts, str);
	}

	/* optionally apply extended attributes */
	if(numExtendedAttributes) {
		unsigned attrDex;
		for(attrDex=0; attrDex<numExtendedAttributes; attrDex++) {
			CFStringRef attrNameStr = CFStringCreateWithCString(NULL, attrNames[attrDex],
				kCFStringEncodingASCII);
			CFDataRef attrValueData = CFDataCreate(NULL, (const UInt8 *)attrValues[attrDex],
				strlen(attrValues[attrDex]));
			for(dex=0; dex<numItems; dex++) {
				SecKeychainItemRef itemRef =
					(SecKeychainItemRef)CFArrayGetValueAtIndex(outArray, dex);
				ortn = SecKeychainItemSetExtendedAttribute(itemRef, attrNameStr, attrValueData);
				if(ortn) {
					cssmPerror("SecKeychainItemSetExtendedAttribute", ortn);
					result = 1;
					break;
				}
			}	/* for each imported item */
			CFRelease(attrNameStr);
			CFRelease(attrValueData);
			if(result) {
				break;
			}
		}	/* for each extended attribute */
	}

cleanup:
	safe_CFRelease(&fileStr);
	safe_CFRelease(&outArray);
	safe_CFRelease(&passStr);
	safe_CFRelease(&promptStr);
	safe_CFRelease(&retryStr);

	return result;
}
Esempio n. 30
0
static pascal OSStatus MultiCartEventHandler (EventHandlerCallRef inHandlerRef, EventRef inEvent, void *inUserData)
{
	OSStatus	err, result = eventNotHandledErr;
	WindowRef	window = (WindowRef) inUserData;
	static int	index = -1;

	switch (GetEventClass(inEvent))
	{
		case kEventClassCommand:
		{
			switch (GetEventKind(inEvent))
			{
				HICommand	tHICommand;

				case kEventCommandUpdateStatus:
				{
					err = GetEventParameter(inEvent, kEventParamDirectObject, typeHICommand, NULL, sizeof(HICommand), NULL, &tHICommand);
					if (err == noErr && tHICommand.commandID == 'clos')
					{
						UpdateMenuCommandStatus(false);
						result = noErr;
					}

					break;
				}

				case kEventCommandProcess:
				{
					err = GetEventParameter(inEvent, kEventParamDirectObject, typeHICommand, NULL, sizeof(HICommand), NULL, &tHICommand);
					if (err == noErr)
					{
						HIViewRef	ctl, root;
						HIViewID	cid;
						FSRef		ref;
						bool8		r;

						root = HIViewGetRoot(window);

						switch (tHICommand.commandID)
						{
							case 'Cho0':
							case 'Cho1':
							{
								index = (tHICommand.commandID & 0xFF) - '0';
								r = NavBeginOpenROMImageSheet(window, NULL);
								result = noErr;
								break;
							}

							case 'NvDn':
							{
								r = NavEndOpenROMImageSheet(&ref);
								if (r)
								{
									CFStringRef	str;
									CFURLRef	url;

									url = CFURLCreateFromFSRef(kCFAllocatorDefault, &ref);
									str = CFURLCopyLastPathComponent(url);
									cid.signature = 'MNAM';
									cid.id = index;
									HIViewFindByID(root, cid, &ctl);
									SetStaticTextCFString(ctl, str, true);
									CFRelease(str);
									str = CFURLCopyFileSystemPath(url, kCFURLPOSIXPathStyle);
									if (multiCartPath[index])
										CFRelease(multiCartPath[index]);
									multiCartPath[index] = str;
									CFRelease(url);
								}

								index = -1;
								result = noErr;
								break;
							}

							case 'Cle0':
							case 'Cle1':
							{
								index = (tHICommand.commandID & 0xFF) - '0';
								cid.signature = 'MNAM';
								cid.id = index;
								HIViewFindByID(root, cid, &ctl);
								SetStaticTextCFString(ctl, CFSTR(""), true);
								if (multiCartPath[index])
								{
									CFRelease(multiCartPath[index]);
									multiCartPath[index] = NULL;
								}

								index = -1;
								result = noErr;
								break;
							}

							case 'SWAP':
							{
								CFStringRef	str;
								CFURLRef	url;

								str = multiCartPath[0];
								multiCartPath[0] = multiCartPath[1];
								multiCartPath[1] = str;

								cid.signature = 'MNAM';

								for (int i = 0; i < 2; i++)
								{
									cid.id = i;
									HIViewFindByID(root, cid, &ctl);

									if (multiCartPath[i])
									{
										url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, multiCartPath[i], kCFURLPOSIXPathStyle, false);
										str = CFURLCopyLastPathComponent(url);
										SetStaticTextCFString(ctl, str, true);
										CFRelease(str);
										CFRelease(url);
									}
									else
										SetStaticTextCFString(ctl, CFSTR(""), true);
								}

								result = noErr;
								break;
							}

							case 'ok  ':
							{
								QuitAppModalLoopForWindow(window);
								multiCartDialogResult = true;
								result = noErr;
								break;
							}

							case 'not!':
							{
								QuitAppModalLoopForWindow(window);
								multiCartDialogResult = false;
								result = noErr;
								break;
							}
						}
					}
				}
			}
		}
	}

	return (result);
}