From ee72ec3dab88b09dd9281d5d63245c876c0a2c01 Mon Sep 17 00:00:00 2001 From: Zorg Date: Fri, 9 Oct 2015 23:58:23 -0400 Subject: [PATCH] Fix issues with copying files from different mounted drives The move operation now does an explict copy & remove. We also copy items using FSCopyObjectSync due to issues existing in copyfile (and NSFileManager). Both of these fix bugs in some cases where items cannot be moved from one network drive to another. In my testing before this patch, I was unable to get the test application to launch and was unable to move the old installation to the trash. --- Sparkle/SUBasicUpdateDriver.m | 9 +- Sparkle/SUFileManager.h | 11 ++ Sparkle/SUFileManager.m | 154 ++++++++++++++++++++ TestApplication/SUTestApplicationDelegate.m | 11 +- Tests/SUFileManagerTest.swift | 20 +++ 5 files changed, 197 insertions(+), 8 deletions(-) diff --git a/Sparkle/SUBasicUpdateDriver.m b/Sparkle/SUBasicUpdateDriver.m index 1a01436f..2b52ea8a 100644 --- a/Sparkle/SUBasicUpdateDriver.m +++ b/Sparkle/SUBasicUpdateDriver.m @@ -452,16 +452,19 @@ if (relaunchPathToCopy != nil) { NSString *targetPath = [self.host.appCachePath stringByAppendingPathComponent:[relaunchPathToCopy lastPathComponent]]; - NSFileManager *fileManager = [[NSFileManager alloc] init]; + SUFileManager *fileManager = [[SUFileManager alloc] initAllowingAuthorization:NO]; NSError *error = nil; + NSURL *relaunchURLToCopy = [NSURL fileURLWithPath:relaunchPathToCopy]; + NSURL *targetURL = [NSURL fileURLWithPath:targetPath]; + // We only need to run our copy of the app by spawning a task // Since we are copying the app to a directory that is write-accessible, we don't need to muck with owner/group IDs - if ([self preparePathForRelaunchTool:targetPath error:&error] && [fileManager copyItemAtPath:relaunchPathToCopy toPath:targetPath error:&error]) { + if ([self preparePathForRelaunchTool:targetPath error:&error] && [fileManager copyItemAtURL:relaunchURLToCopy toURL:targetURL error:&error]) { // We probably don't need to release the quarantine, but we'll do it just in case it's necessary. // Perhaps in a sandboxed environment this matters more. Note that this may not be a fatal error. NSError *quarantineError = nil; - if (![[[SUFileManager alloc] initAllowingAuthorization:NO] releaseItemFromQuarantineAtRootURL:[NSURL fileURLWithPath:targetPath] error:&quarantineError]) { + if (![fileManager releaseItemFromQuarantineAtRootURL:targetURL error:&quarantineError]) { SULog(@"Failed to release quarantine on %@ with error %@", targetPath, quarantineError); } self.relaunchPath = targetPath; diff --git a/Sparkle/SUFileManager.h b/Sparkle/SUFileManager.h index 5a390d89..7dde8cab 100644 --- a/Sparkle/SUFileManager.h +++ b/Sparkle/SUFileManager.h @@ -49,6 +49,17 @@ */ - (BOOL)moveItemAtURL:(NSURL *)sourceURL toURL:(NSURL *)destinationURL error:(NSError **)error; +/** + * Copies an item from a source to a destination + * @param sourceURL A URL pointing to the item to move. The item at this URL must exist. + * @param destinationURL A URL pointing to the destination the item will be moved at. An item must not already exist at this URL. + * @param error If an error occurs, upon returns contains an NSError object that describes the problem. If you are not interested in possible errors, you may pass in NULL. + * @return YES if the item was copied successfully, otherwise NO along with a populated error object + * + * This is not an atomic operation. + */ +- (BOOL)copyItemAtURL:(NSURL *)sourceURL toURL:(NSURL *)destinationURL error:(NSError **)error; + /** * Moves an item at a specified URL to the running user's trash directory * @param url A URL pointing to the item to move to the trash. The item at this URL must exist. diff --git a/Sparkle/SUFileManager.m b/Sparkle/SUFileManager.m index db25a782..3a57f827 100644 --- a/Sparkle/SUFileManager.m +++ b/Sparkle/SUFileManager.m @@ -301,6 +301,145 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza error:error]; } +/* + * Copies an item from one location to another + * This intentionally does *not* use copyfile() or any API that uses it such as NSFileManager's copy item method + * This is because copyfile() fails to copy symbolic links from one network mount to another, which will affect copying apps + * This failure has been reproduced on 10.11.0 and a VM running 10.8, so the issue has existed for a while. + * For more info, see the bug report at http://openradar.appspot.com/radar?id=4925873463492608 + */ +- (BOOL)copyItemAtURL:(NSURL *)sourceURL toURL:(NSURL *)destinationURL error:(NSError * __autoreleasing *)error +{ + if (![self _itemExistsAtURL:sourceURL]) { + if (error != NULL) { + *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileNoSuchFileError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Source file to copy (%@) does not exist.", sourceURL.lastPathComponent] }]; + } + return NO; + } + + if ([self _itemExistsAtURL:destinationURL]) { + if (error != NULL) { + *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileWriteFileExistsError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Destination file to copy to (%@) already exists.", destinationURL.lastPathComponent] }]; + } + return NO; + } + + char sourcePath[PATH_MAX] = {0}; + if (![sourceURL.path getFileSystemRepresentation:sourcePath maxLength:sizeof(sourcePath)]) { + if (error != NULL) { + *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"File to copy (%@) cannot be represented as a valid file name.", sourceURL.lastPathComponent] }]; + } + return NO; + } + + FSRef sourceRef; +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + OSStatus makeSourceResult = FSPathMakeRefWithOptions((const UInt8 *)sourcePath, kFSPathMakeRefDoNotFollowLeafSymlink, &sourceRef, NULL); +#pragma clang diagnostic pop + if (makeSourceResult != noErr) { + if (error != NULL) { + *error = [NSError errorWithDomain:NSOSStatusErrorDomain code:makeSourceResult userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to create file system reference for source %@.", sourceURL.lastPathComponent] }]; + } + return NO; + } + + char destinationParentPath[PATH_MAX] = {0}; + if (![destinationURL.URLByDeletingLastPathComponent.path getFileSystemRepresentation:destinationParentPath maxLength:sizeof(destinationParentPath)]) { + if (error != NULL) { + *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Destination parent directory to copy file into (%@) cannot be represented as a valid file name.", destinationURL.URLByDeletingLastPathComponent.lastPathComponent] }]; + } + return NO; + } + + FSRef destinationParentRef; +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + OSStatus makeDestinationParentResult = FSPathMakeRefWithOptions((const UInt8 *)destinationParentPath, kFSPathMakeRefDoNotFollowLeafSymlink, &destinationParentRef, NULL); +#pragma clang diagnostic pop + if (makeDestinationParentResult != noErr) { + if (error != NULL) { + *error = [NSError errorWithDomain:NSOSStatusErrorDomain code:makeDestinationParentResult userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to create file system reference for parent directory %@.", destinationURL.URLByDeletingLastPathComponent.lastPathComponent] }]; + } + return NO; + } + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + OSStatus copyResult = FSCopyObjectSync(&sourceRef, &destinationParentRef, (__bridge CFStringRef)(destinationURL.lastPathComponent), NULL, kFSFileOperationDefaultOptions); +#pragma clang diagnostic pop + if (copyResult == noErr) { + return YES; + } + + if (copyResult != permErr) { + if (error != NULL) { + *error = [NSError errorWithDomain:NSOSStatusErrorDomain code:copyResult userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to copy file (%@)", sourceURL.lastPathComponent] }]; + } + return NO; + } + + if (![self _acquireAuthorizationWithError:error]) { + return NO; + } + + char destinationPath[PATH_MAX] = {0}; + if (![destinationURL.path getFileSystemRepresentation:destinationPath maxLength:sizeof(destinationPath)]) { + if (error != NULL) { + *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Destination to copy file to (%@) cannot be represented as a valid file name.", destinationURL.lastPathComponent] }]; + } + return NO; + } + + if (!AuthorizationExecuteWithPrivilegesAndWait(_auth, "/bin/cp", kAuthorizationFlagDefaults, (char *[]){ "-Rf", sourcePath, destinationPath, NULL })) { + if (error != NULL) { + NSString *errorMessage = [NSString stringWithFormat:@"Failed to perform authenticated file copy for %@.", sourceURL.lastPathComponent]; + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:errorMessage }]; + } + return NO; + } + + return YES; +} + +/* + * Retrieves the volume ID that a particular url resides on + * The url must point to a file that exists + * There is no cocoa equivalent for obtaining the volume ID + * Although NSURLVolumeURLForRemountingKey exists as a resource key for NSURL, + * that will not return a URL if the mount is not re-mountable and I otherwise don't trust the API + */ +- (BOOL)_getVolumeID:(FSVolumeRefNum *)volumeID ofItemAtURL:(NSURL *)url +{ + char path[PATH_MAX] = {0}; + if (![url.path getFileSystemRepresentation:path maxLength:sizeof(path)]) { + return NO; + } + + FSRef pathRef; +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + if (FSPathMakeRefWithOptions((const UInt8*)path, kFSPathMakeRefDoNotFollowLeafSymlink, &pathRef, NULL) != noErr) { +#pragma clang diagnostic pop + return NO; + } + + FSCatalogInfo catalogInfo; +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + OSErr catalogError = FSGetCatalogInfo(&pathRef, kFSCatInfoVolume, &catalogInfo, NULL, NULL, NULL); +#pragma clang diagnostic pop + if (catalogError != noErr) { + return NO; + } + + if (volumeID != NULL) { + *volumeID = catalogInfo.volume; + } + + return YES; +} + - (BOOL)moveItemAtURL:(NSURL *)sourceURL toURL:(NSURL *)destinationURL error:(NSError *__autoreleasing *)error { if (![self _itemExistsAtURL:sourceURL]) { @@ -317,6 +456,21 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza return NO; } + // If the source and destination are on different volumes, we should not do a move; + // from my experience a move may fail when moving particular files from + // one network mount to another one. This is possibly related to the fact that + // moving a file will try to preserve ownership but copying won't + + FSVolumeRefNum sourceVolume = 0; + BOOL foundSourceVolume = [self _getVolumeID:&sourceVolume ofItemAtURL:sourceURL]; + + FSVolumeRefNum destinationVolume = 0; + BOOL foundDestinationVolume = [self _getVolumeID:&destinationVolume ofItemAtURL:destinationURL.URLByDeletingLastPathComponent]; + + if (foundSourceVolume && foundDestinationVolume && sourceVolume != destinationVolume) { + return ([self copyItemAtURL:sourceURL toURL:destinationURL error:error] && [self removeItemAtURL:sourceURL error:error]); + } + NSError *moveError = nil; if ([_fileManager moveItemAtURL:sourceURL toURL:destinationURL error:&moveError]) { return YES; diff --git a/TestApplication/SUTestApplicationDelegate.m b/TestApplication/SUTestApplicationDelegate.m index 9296073f..a4c83e16 100644 --- a/TestApplication/SUTestApplicationDelegate.m +++ b/TestApplication/SUTestApplicationDelegate.m @@ -8,6 +8,7 @@ #import "SUTestApplicationDelegate.h" #import "SUUpdateSettingsWindowController.h" +#import "SUFileManager.h" @interface SUTestApplicationDelegate () @@ -37,11 +38,11 @@ static NSString * const UPDATED_VERSION = @"2.0"; [[NSApplication sharedApplication] terminate:nil]; } - NSFileManager *fileManager = [NSFileManager defaultManager]; + SUFileManager *fileManager = [[SUFileManager alloc] initAllowingAuthorization:NO]; // Locate user's cache directory NSError *cacheError = nil; - NSURL *cacheDirectoryURL = [fileManager URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:&cacheError]; + NSURL *cacheDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:&cacheError]; if (cacheDirectoryURL == nil) { NSLog(@"Failed to locate cache directory with error: %@", cacheError); @@ -62,7 +63,7 @@ static NSString * const UPDATED_VERSION = @"2.0"; } NSError *createDirectoryError = nil; - if (![fileManager createDirectoryAtURL:serverDirectoryURL withIntermediateDirectories:YES attributes:nil error:&createDirectoryError]) { + if (![[NSFileManager defaultManager] createDirectoryAtURL:serverDirectoryURL withIntermediateDirectories:YES attributes:nil error:&createDirectoryError]) { NSLog(@"Failed creating directory at %@ with error %@", serverDirectoryURL.path, createDirectoryError); assert(NO); } @@ -137,7 +138,7 @@ static NSString * const UPDATED_VERSION = @"2.0"; // Obtain the file attributes to get the file size of our update later NSError *fileAttributesError = nil; - NSDictionary *archiveFileAttributes = [fileManager attributesOfItemAtPath:archiveURL.path error:&fileAttributesError]; + NSDictionary *archiveFileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:archiveURL.path error:&fileAttributesError]; if (archiveFileAttributes == nil) { NSLog(@"Failed to retrieve file attributes from archive with error %@", fileAttributesError); assert(NO); @@ -178,7 +179,7 @@ static NSString * const UPDATED_VERSION = @"2.0"; // Finally start the server NSTask *serverTask = [[NSTask alloc] init]; serverTask.launchPath = @"/usr/bin/python"; - assert([fileManager fileExistsAtPath:serverTask.launchPath]); + assert([[NSFileManager defaultManager] fileExistsAtPath:serverTask.launchPath]); serverTask.arguments = @[@"-m", @"SimpleHTTPServer", @"1337"]; serverTask.currentDirectoryPath = serverDirectoryPath; [serverTask launch]; diff --git a/Tests/SUFileManagerTest.swift b/Tests/SUFileManagerTest.swift index ecc38bd0..75553278 100644 --- a/Tests/SUFileManagerTest.swift +++ b/Tests/SUFileManagerTest.swift @@ -77,6 +77,26 @@ class SUFileManagerTest: XCTestCase try! fileManager.removeItemAtURL(directoryTrashURL) } } + + func testCopyFiles() + { + makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL in + XCTAssertNil(try? fileManager.copyItemAtURL(ordinaryFileURL, toURL: directoryURL)) + XCTAssertNil(try? fileManager.copyItemAtURL(rootURL.URLByAppendingPathComponent("does not exist"), toURL: directoryURL)) + + let newFileURL = (ordinaryFileURL.URLByDeletingLastPathComponent?.URLByAppendingPathComponent("new file"))! + try! fileManager.copyItemAtURL(ordinaryFileURL, toURL: newFileURL) + XCTAssertTrue(fileManager._itemExistsAtURL(ordinaryFileURL)) + XCTAssertTrue(fileManager._itemExistsAtURL(newFileURL)) + + let newDirectoryURL = (ordinaryFileURL.URLByDeletingLastPathComponent?.URLByAppendingPathComponent("new directory"))! + try! fileManager.copyItemAtURL(directoryURL, toURL: newDirectoryURL) + XCTAssertTrue(fileManager._itemExistsAtURL(directoryURL)) + XCTAssertTrue(fileManager._itemExistsAtURL(newDirectoryURL)) + XCTAssertTrue(fileManager._itemExistsAtURL(fileInDirectoryURL)) + XCTAssertTrue(fileManager._itemExistsAtURL(newDirectoryURL.URLByAppendingPathComponent(fileInDirectoryURL.lastPathComponent!))) + } + } func testRemoveFiles() {