From 32591954bcb565a049b751e69e202f900c6ae4b3 Mon Sep 17 00:00:00 2001 From: Zorg Date: Sat, 26 Sep 2015 10:09:05 -0400 Subject: [PATCH 1/3] Add SUFileManager tests and fix issues along the way * Fix uid / gid not being applied to the root path or non-directory inputs * Remove the code that released quarantines using the NSURL way. It turned out not to be very reliable and didn't pass the tests. More explanation is given in the code. * Prefix private methods with _ and expose some of them to the tests --- Sparkle.xcodeproj/project.pbxproj | 6 + Sparkle/SUFileManager.m | 158 +++++++------- Tests/SUFileManagerTest.swift | 229 +++++++++++++++++++++ Tests/Sparkle Unit Tests-Bridging-Header.h | 14 ++ 4 files changed, 329 insertions(+), 78 deletions(-) create mode 100644 Tests/SUFileManagerTest.swift diff --git a/Sparkle.xcodeproj/project.pbxproj b/Sparkle.xcodeproj/project.pbxproj index b1f6dddb..25b05069 100644 --- a/Sparkle.xcodeproj/project.pbxproj +++ b/Sparkle.xcodeproj/project.pbxproj @@ -173,6 +173,8 @@ 7275F9C11B5F1F2900B1D19E /* SUFileManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 7275F9BF1B5F1F2900B1D19E /* SUFileManager.h */; }; 7275F9C21B5F1F2900B1D19E /* SUFileManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 7275F9C01B5F1F2900B1D19E /* SUFileManager.m */; }; 7275F9C31B5F1F2900B1D19E /* SUFileManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 7275F9C01B5F1F2900B1D19E /* SUFileManager.m */; }; + 72A4A2401BB6567D00E7820D /* SUFileManagerTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 72A4A23F1BB6567D00E7820D /* SUFileManagerTest.swift */; settings = {ASSET_TAGS = (); }; }; + 72A4A2411BB656FA00E7820D /* SUFileManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 7275F9C01B5F1F2900B1D19E /* SUFileManager.m */; }; 72AC6B261B9AAC8800F62325 /* SparkleTestCodeSignApp.tar.gz in Resources */ = {isa = PBXBuildFile; fileRef = 72AC6B251B9AAC8800F62325 /* SparkleTestCodeSignApp.tar.gz */; settings = {ASSET_TAGS = (); }; }; 72AC6B281B9AAD6700F62325 /* SparkleTestCodeSignApp.tar in Resources */ = {isa = PBXBuildFile; fileRef = 72AC6B271B9AAD6700F62325 /* SparkleTestCodeSignApp.tar */; settings = {ASSET_TAGS = (); }; }; 72AC6B2A1B9AAF3A00F62325 /* SparkleTestCodeSignApp.tar.bz2 in Resources */ = {isa = PBXBuildFile; fileRef = 72AC6B291B9AAF3A00F62325 /* SparkleTestCodeSignApp.tar.bz2 */; settings = {ASSET_TAGS = (); }; }; @@ -569,6 +571,7 @@ 7268AC641AD634E400C3E0C1 /* SUBinaryDeltaCreate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUBinaryDeltaCreate.h; sourceTree = ""; }; 7275F9BF1B5F1F2900B1D19E /* SUFileManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUFileManager.h; sourceTree = ""; }; 7275F9C01B5F1F2900B1D19E /* SUFileManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SUFileManager.m; sourceTree = ""; }; + 72A4A23F1BB6567D00E7820D /* SUFileManagerTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SUFileManagerTest.swift; sourceTree = ""; }; 72AC6B251B9AAC8800F62325 /* SparkleTestCodeSignApp.tar.gz */ = {isa = PBXFileReference; lastKnownFileType = archive.gzip; path = SparkleTestCodeSignApp.tar.gz; sourceTree = ""; }; 72AC6B271B9AAD6700F62325 /* SparkleTestCodeSignApp.tar */ = {isa = PBXFileReference; lastKnownFileType = archive.tar; path = SparkleTestCodeSignApp.tar; sourceTree = ""; }; 72AC6B291B9AAF3A00F62325 /* SparkleTestCodeSignApp.tar.bz2 */ = {isa = PBXFileReference; lastKnownFileType = file; path = SparkleTestCodeSignApp.tar.bz2; sourceTree = ""; }; @@ -883,6 +886,7 @@ 14950074195FDF5900BC5B5B /* SUUpdaterTest.m */, 61227A150DB548B800AB99EA /* SUVersionComparisonTest.m */, 7210C7671B9A9A1500EB90AC /* SUUnarchiverTest.swift */, + 72A4A23F1BB6567D00E7820D /* SUFileManagerTest.swift */, 72AFC6121B9A944200F6B565 /* Sparkle Unit Tests-Bridging-Header.h */, ); path = Tests; @@ -1483,6 +1487,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 72A4A2411BB656FA00E7820D /* SUFileManager.m in Sources */, 721CF1A71AD7643600D9AC09 /* bsdiff.c in Sources */, 721CF1A81AD7644100D9AC09 /* bspatch.c in Sources */, 721CF1A91AD7644C00D9AC09 /* sais.c in Sources */, @@ -1493,6 +1498,7 @@ 5AF9DC3C1981DBEE001EA135 /* SUDSAVerifierTest.m in Sources */, 5AF6C7541AEA49840014A3AB /* SUInstallerTest.m in Sources */, 14652F8219A9746000959E44 /* SULog.m in Sources */, + 72A4A2401BB6567D00E7820D /* SUFileManagerTest.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/Sparkle/SUFileManager.m b/Sparkle/SUFileManager.m index 4c987f43..122c8b56 100644 --- a/Sparkle/SUFileManager.m +++ b/Sparkle/SUFileManager.m @@ -11,9 +11,11 @@ #include #include -#if __MAC_OS_X_VERSION_MAX_ALLOWED < 101000 /* MAC_OS_X_VERSION_10_10 */ -extern NSString *const NSURLQuarantinePropertiesKey WEAK_IMPORT_ATTRIBUTE; -#endif +#pragma clang diagnostic push +// This is a private constant but it's referenced from our unit tests +#pragma clang diagnostic ignored "-Wmissing-variable-declarations" +NSString *SUAppleQuarantineIdentifier = @"com.apple.quarantine"; +#pragma clang diagnostic pop // Authorization code based on generous contribution from Allan Odgaard. Thanks, Allan! static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authorization, const char *executablePath, AuthorizationFlags options, char *const *arguments) @@ -64,7 +66,7 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza } // Acquires an authorization reference which is intended to be used for future authorized file operations -- (BOOL)acquireAuthorizationWithError:(NSError *__autoreleasing *)error +- (BOOL)_acquireAuthorizationWithError:(NSError *__autoreleasing *)error { // No need to continue if we already acquired an authorization reference if (_auth != NULL) { @@ -91,12 +93,12 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza // -[NSFileManager attributesOfItemAtPath:error:] won't follow symbolic links -- (BOOL)itemExistsAtURL:(NSURL *)fileURL +- (BOOL)_itemExistsAtURL:(NSURL *)fileURL { return [_fileManager attributesOfItemAtPath:fileURL.path error:NULL] != nil; } -- (BOOL)itemExistsAtURL:(NSURL *)fileURL isDirectory:(BOOL *)isDirectory +- (BOOL)_itemExistsAtURL:(NSURL *)fileURL isDirectory:(BOOL *)isDirectory { NSDictionary *attributes = [_fileManager attributesOfItemAtPath:fileURL.path error:NULL]; if (attributes == nil) { @@ -111,7 +113,7 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza } // Wrapper around getxattr() -- (ssize_t)getXAttr:(NSString *)nameString fromFile:(NSString *)file options:(int)options +- (ssize_t)_getXAttr:(NSString *)nameString fromFile:(NSString *)file options:(int)options { char path[PATH_MAX] = {0}; if (![file getFileSystemRepresentation:path maxLength:sizeof(path)]) { @@ -129,7 +131,7 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza } // Wrapper around removexattr() -- (int)removeXAttr:(NSString *)name fromFile:(NSString *)file options:(int)options +- (int)_removeXAttr:(NSString *)name fromFile:(NSString *)file options:(int)options { char path[PATH_MAX] = {0}; if (![file getFileSystemRepresentation:path maxLength:sizeof(path)]) { @@ -148,7 +150,7 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza #define XATTR_UTILITY_PATH "/usr/bin/xattr" // Recursively remove an xattr at a specified root URL with authentication -- (BOOL)removeXAttrWithAuthentication:(NSString *)name fromRootURL:(NSURL *)rootURL error:(NSError *__autoreleasing *)error +- (BOOL)_removeXAttrWithAuthentication:(NSString *)name fromRootURL:(NSURL *)rootURL error:(NSError *__autoreleasing *)error { // Because this is a system utility, it's fine to follow the symbolic link if one exists if (![_fileManager fileExistsAtPath:@(XATTR_UTILITY_PATH)]) { @@ -174,7 +176,7 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza return NO; } - if (![self acquireAuthorizationWithError:error]) { + if (![self _acquireAuthorizationWithError:error]) { return NO; } @@ -188,11 +190,9 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza return success; } -#define APPLE_QUARANTINE_IDENTIFIER @"com.apple.quarantine" - -- (BOOL)releaseItemFromQuarantineAtRootURL:(NSURL *)rootURL allowingAuthentication:(BOOL)allowsAuthentication withQuarantineRetrieval:(BOOL (^)(NSURL *))quarantineRetrieval quarantineRemoval:(BOOL (^)(NSURL *, NSError * __autoreleasing *))quarantineRemoval isAccessError:(BOOL (^)(NSError *))isAccessError error:(NSError * __autoreleasing *)error +- (BOOL)_releaseItemFromQuarantineAtRootURL:(NSURL *)rootURL allowingAuthentication:(BOOL)allowsAuthentication withQuarantineRetrieval:(BOOL (^)(NSURL *))quarantineRetrieval quarantineRemoval:(BOOL (^)(NSURL *, NSError * __autoreleasing *))quarantineRemoval isAccessError:(BOOL (^)(NSError *))isAccessError error:(NSError * __autoreleasing *)error { - if (![self itemExistsAtURL:rootURL]) { + if (![self _itemExistsAtURL:rootURL]) { if (error != NULL) { *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileNoSuchFileError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to remove quarantine because %@ does not exist.", rootURL.path.lastPathComponent] }]; } @@ -209,7 +209,7 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza removedQuarantine = YES; } else { if (allowsAuthentication && isAccessError(removalError)) { - removedQuarantine = [self removeXAttrWithAuthentication:APPLE_QUARANTINE_IDENTIFIER fromRootURL:rootURL error:error]; + removedQuarantine = [self _removeXAttrWithAuthentication:SUAppleQuarantineIdentifier fromRootURL:rootURL error:error]; attemptedAuthentication = YES; } else { if (success != NULL) { @@ -267,30 +267,6 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza // If |root| is not a directory, then it alone is removed from the quarantine. // Symbolic links, including |root| if it is a symbolic link, will not be // traversed. -- (BOOL)releaseItemFromQuarantineAtRootURL:(NSURL *)rootURL allowingAuthentication:(BOOL)allowsAuthentication error:(NSError * __autoreleasing *)error -{ -#if __MAC_OS_X_VERSION_MIN_REQUIRED < 101000 /* MAC_OS_X_VERSION_10_10 */ - if (!&NSURLQuarantinePropertiesKey) { - return [self releaseItemUsingOldMethodFromQuarantineAtRootURL:rootURL allowingAuthentication:allowsAuthentication error:error]; - } -#endif - - return - [self - releaseItemFromQuarantineAtRootURL:rootURL - allowingAuthentication:allowsAuthentication - withQuarantineRetrieval:^BOOL(NSURL *fileURL) { - id resourceValue = nil; - return ([fileURL getResourceValue:&resourceValue forKey:NSURLQuarantinePropertiesKey error:NULL] && resourceValue != nil); - } - quarantineRemoval:^BOOL(NSURL *fileURL, NSError *__autoreleasing *removalError) { - return [fileURL setResourceValue:[NSNull null] forKey:NSURLQuarantinePropertiesKey error:removalError]; - } - isAccessError:^BOOL(NSError *removalError) { - return NS_HAS_PERMISSION_ERROR(removalError); - } - error:error]; -} // Ordinarily, the quarantine is managed by calling LSSetItemAttribute // to set the kLSItemQuarantineProperties attribute to a dictionary specifying @@ -301,19 +277,23 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza // "com.apple.quarantine", on affected files. Removing this attribute is // sufficient to remove files from the quarantine. -- (BOOL)releaseItemUsingOldMethodFromQuarantineAtRootURL:(NSURL *)rootURL allowingAuthentication:(BOOL)allowsAuthentication error:(NSError *__autoreleasing *)error +// This works be removing the quarantine extended attribute for every file we come across. +// We used to have code similar to the method below that used -[NSURL getResourceValue:forKey:error:] and -[NSURL setResourceValue:forKey:error:] +// However, those methods *really suck* - you can't rely on the return value from getting the resource value and if you set the resource value +// when the key isn't present, errors are spewed out to the console +- (BOOL)_releaseItemFromQuarantineAtRootURL:(NSURL *)rootURL allowingAuthentication:(BOOL)allowsAuthentication error:(NSError *__autoreleasing *)error { static const int removeXAttrOptions = XATTR_NOFOLLOW; return [self - releaseItemFromQuarantineAtRootURL:rootURL + _releaseItemFromQuarantineAtRootURL:rootURL allowingAuthentication:allowsAuthentication withQuarantineRetrieval:^BOOL(NSURL *fileURL) { - return ([self getXAttr:APPLE_QUARANTINE_IDENTIFIER fromFile:fileURL.path options:removeXAttrOptions] >= 0); + return ([self _getXAttr:SUAppleQuarantineIdentifier fromFile:fileURL.path options:removeXAttrOptions] >= 0); } quarantineRemoval:^BOOL(NSURL *fileURL, NSError * __autoreleasing *removalError) { - BOOL removedQuarantine = ([self removeXAttr:APPLE_QUARANTINE_IDENTIFIER fromFile:fileURL.path options:removeXAttrOptions] == 0); + BOOL removedQuarantine = ([self _removeXAttr:SUAppleQuarantineIdentifier fromFile:fileURL.path options:removeXAttrOptions] == 0); if (!removedQuarantine && removalError != NULL) { *removalError = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to remove file quarantine on %@.", fileURL.lastPathComponent] }]; } @@ -327,24 +307,24 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza - (BOOL)releaseItemFromQuarantineAtRootURL:(NSURL *)rootURL error:(NSError * __autoreleasing *)error { - return [self releaseItemFromQuarantineAtRootURL:rootURL allowingAuthentication:YES error:error]; + return [self _releaseItemFromQuarantineAtRootURL:rootURL allowingAuthentication:YES error:error]; } - (BOOL)releaseItemFromQuarantineWithoutAuthenticationAtRootURL:(NSURL *)rootURL error:(NSError * __autoreleasing *)error { - return [self releaseItemFromQuarantineAtRootURL:rootURL allowingAuthentication:NO error:error]; + return [self _releaseItemFromQuarantineAtRootURL:rootURL allowingAuthentication:NO error:error]; } - (BOOL)moveItemAtURL:(NSURL *)sourceURL toURL:(NSURL *)destinationURL error:(NSError *__autoreleasing *)error { - if (![self itemExistsAtURL:sourceURL]) { + if (![self _itemExistsAtURL:sourceURL]) { if (error != NULL) { *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileNoSuchFileError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Source file to move (%@) does not exist.", sourceURL.path.lastPathComponent] }]; } return NO; } - if ([self itemExistsAtURL:destinationURL]) { + if ([self _itemExistsAtURL:destinationURL]) { if (error != NULL) { *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileWriteFileExistsError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Destination file to move (%@) already exists.", destinationURL.path.lastPathComponent] }]; } @@ -363,7 +343,7 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza return NO; } - if (![self acquireAuthorizationWithError:error]) { + if (![self _acquireAuthorizationWithError:error]) { return NO; } @@ -394,16 +374,43 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza return YES; } +- (BOOL)_changeOwnerAndGroupOfItemAtURL:(NSURL *)targetURL ownerID:(NSNumber *)ownerID groupID:(NSNumber *)groupID needsAuth:(BOOL *)needsAuth error:(NSError * __autoreleasing *)error +{ + char path[PATH_MAX] = {0}; + if (![targetURL.path getFileSystemRepresentation:path maxLength:sizeof(path)]) { + if (error != NULL) { + *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"File to change owner & group (%@) cannot be represented as a valid file name.", targetURL.path.lastPathComponent] }]; + } + return NO; + } + + if (chown(path, ownerID.unsignedIntValue, groupID.unsignedIntValue) != 0) { + if (errno == EPERM) { + if (needsAuth != NULL) { + *needsAuth = YES; + } + } else { + if (error != NULL) { + *error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to change owner & group for %@ with owner ID %u and group ID %u.", targetURL.path.lastPathComponent, ownerID.unsignedIntValue, groupID.unsignedIntValue] }]; + } + return NO; + } + } + + return YES; +} + - (BOOL)changeOwnerAndGroupOfItemAtRootURL:(NSURL *)targetURL toMatchURL:(NSURL *)matchURL error:(NSError * __autoreleasing *)error { - if (![self itemExistsAtURL:targetURL]) { + BOOL isTargetADirectory = NO; + if (![self _itemExistsAtURL:targetURL isDirectory:&isTargetADirectory]) { if (error != NULL) { *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileNoSuchFileError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to change owner & group IDs because %@ does not exist.", targetURL.path.lastPathComponent] }]; } return NO; } - if (![self itemExistsAtURL:matchURL]) { + if (![self _itemExistsAtURL:matchURL]) { if (error != NULL) { *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileNoSuchFileError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to match owner & group IDs because %@ does not exist.", matchURL.path.lastPathComponent] }]; } @@ -452,27 +459,22 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza return YES; } - NSDirectoryEnumerator *directoryEnumerator = [_fileManager enumeratorAtURL:targetURL includingPropertiesForKeys:nil options:(NSDirectoryEnumerationOptions)0 errorHandler:nil]; BOOL needsAuth = NO; - for (NSURL *url in directoryEnumerator) { - char path[PATH_MAX] = {0}; - if (![url.path getFileSystemRepresentation:path maxLength:sizeof(path)]) { - if (error != NULL) { - *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"File to change owner & group (%@) cannot be represented as a valid file name.", url.path.lastPathComponent] }]; - } - return NO; - } - - if (chown(path, ownerID.unsignedIntValue, groupID.unsignedIntValue) != 0) { - if (errno == EPERM) { - needsAuth = YES; - break; - } else { - if (error != NULL) { - *error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to change owner & group for %@ with owner ID %u and group ID %u.", url.path.lastPathComponent, ownerID.unsignedIntValue, groupID.unsignedIntValue] }]; - } + + if (![self _changeOwnerAndGroupOfItemAtURL:targetURL ownerID:ownerID groupID:groupID needsAuth:&needsAuth error:error]) { + return NO; + } + + if (isTargetADirectory) { + NSDirectoryEnumerator *directoryEnumerator = [_fileManager enumeratorAtURL:targetURL includingPropertiesForKeys:nil options:(NSDirectoryEnumerationOptions)0 errorHandler:nil]; + for (NSURL *url in directoryEnumerator) { + if (![self _changeOwnerAndGroupOfItemAtURL:url ownerID:ownerID groupID:groupID needsAuth:&needsAuth error:error]) { return NO; } + + if (needsAuth) { + break; + } } } @@ -497,7 +499,7 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza return NO; } - if (![self acquireAuthorizationWithError:error]) { + if (![self _acquireAuthorizationWithError:error]) { return NO; } @@ -512,9 +514,9 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza // Creates a directory at the item pointed by url // An item cannot already exist at the url, but the parent must be a directory that exists -- (BOOL)makeDirectoryAtURL:(NSURL *)url error:(NSError * __autoreleasing *)error +- (BOOL)_makeDirectoryAtURL:(NSURL *)url error:(NSError * __autoreleasing *)error { - if ([self itemExistsAtURL:url]) { + if ([self _itemExistsAtURL:url]) { if (error != NULL) { *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileWriteFileExistsError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to create directory because file %@ already exists.", url.path.lastPathComponent] }]; } @@ -523,7 +525,7 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza NSURL *parentURL = [url URLByDeletingLastPathComponent]; BOOL isParentADirectory = NO; - if (![self itemExistsAtURL:parentURL isDirectory:&isParentADirectory] || !isParentADirectory) { + if (![self _itemExistsAtURL:parentURL isDirectory:&isParentADirectory] || !isParentADirectory) { if (error != NULL) { *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileNoSuchFileError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to create directory because parent directory %@ does not exist.", parentURL.path.lastPathComponent] }]; } @@ -550,7 +552,7 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza return NO; } - if (![self acquireAuthorizationWithError:error]) { + if (![self _acquireAuthorizationWithError:error]) { return NO; } @@ -576,16 +578,16 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza NSURL *desiredURL = [directoryURL URLByAppendingPathComponent:preferredName]; NSUInteger tagIndex = 1; - while ([self itemExistsAtURL:desiredURL] && tagIndex <= 9999) { + while ([self _itemExistsAtURL:desiredURL] && tagIndex <= 9999) { desiredURL = [directoryURL URLByAppendingPathComponent:[preferredName stringByAppendingFormat:@" (%lu)", (unsigned long)++tagIndex]]; } - return [self makeDirectoryAtURL:desiredURL error:error] ? desiredURL : nil; + return [self _makeDirectoryAtURL:desiredURL error:error] ? desiredURL : nil; } - (BOOL)removeItemAtURL:(NSURL *)url error:(NSError * __autoreleasing *)error { - if (![self itemExistsAtURL:url]) { + if (![self _itemExistsAtURL:url]) { if (error != NULL) { *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileNoSuchFileError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to remove file %@ because it does not exist.", url.path.lastPathComponent] }]; } @@ -604,7 +606,7 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza return NO; } - if (![self acquireAuthorizationWithError:error]) { + if (![self _acquireAuthorizationWithError:error]) { return NO; } @@ -625,7 +627,7 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza - (BOOL)moveItemAtURLToTrash:(NSURL *)url error:(NSError *__autoreleasing *)error { - if (![self itemExistsAtURL:url]) { + if (![self _itemExistsAtURL:url]) { if (error != NULL) { *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileNoSuchFileError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to move %@ to the trash because the file does not exist.", url.path.lastPathComponent] }]; } diff --git a/Tests/SUFileManagerTest.swift b/Tests/SUFileManagerTest.swift new file mode 100644 index 00000000..20722abe --- /dev/null +++ b/Tests/SUFileManagerTest.swift @@ -0,0 +1,229 @@ +// +// SUFileManagerTest.swift +// Sparkle +// +// Created by Mayur Pawashe on 9/26/15. +// Copyright © 2015 Sparkle Project. All rights reserved. +// + +import XCTest + +class SUFileManagerTest: XCTestCase +{ + func makeTempFiles(testBlock: (SUFileManager, NSURL, NSURL, NSURL, NSURL) -> Void) + { + let fileManager = SUFileManager() + + let tempDirectoryURL = try! fileManager.makeTemporaryDirectoryWithPreferredName("Sparkle Unit Test Data", appropriateForDirectoryURL: NSURL(fileURLWithPath: NSHomeDirectory())) + + defer { + try! fileManager.removeItemAtURL(tempDirectoryURL) + } + + let ordinaryFileURL = tempDirectoryURL.URLByAppendingPathComponent("a file written by sparkles unit tests") + try! "foo".dataUsingEncoding(NSUTF8StringEncoding)!.writeToURL(ordinaryFileURL, options: .DataWritingAtomic) + + let directoryURL = tempDirectoryURL.URLByAppendingPathComponent("a directory written by sparkles unit tests") + try! NSFileManager.defaultManager().createDirectoryAtURL(directoryURL, withIntermediateDirectories: false, attributes: nil) + + let fileInDirectoryURL = directoryURL.URLByAppendingPathComponent("a file inside a directory written by sparkles unit tests") + try! "bar baz".dataUsingEncoding(NSUTF8StringEncoding)!.writeToURL(fileInDirectoryURL, options: .DataWritingAtomic) + + testBlock(fileManager, tempDirectoryURL, ordinaryFileURL, directoryURL, fileInDirectoryURL) + } + + func testMoveFiles() + { + makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL in + XCTAssertNil(try? fileManager.moveItemAtURL(ordinaryFileURL, toURL: directoryURL)) + XCTAssertNil(try? fileManager.moveItemAtURL(rootURL.URLByAppendingPathComponent("does not exist"), toURL: directoryURL)) + + let newFileURL = (ordinaryFileURL.URLByDeletingLastPathComponent?.URLByAppendingPathComponent("new file"))! + try! fileManager.moveItemAtURL(ordinaryFileURL, toURL: newFileURL) + XCTAssertFalse(fileManager._itemExistsAtURL(ordinaryFileURL)) + XCTAssertTrue(fileManager._itemExistsAtURL(newFileURL)) + + let newDirectoryURL = (ordinaryFileURL.URLByDeletingLastPathComponent?.URLByAppendingPathComponent("new directory"))! + try! fileManager.moveItemAtURL(directoryURL, toURL: newDirectoryURL) + XCTAssertFalse(fileManager._itemExistsAtURL(directoryURL)) + XCTAssertTrue(fileManager._itemExistsAtURL(newDirectoryURL)) + XCTAssertFalse(fileManager._itemExistsAtURL(fileInDirectoryURL)) + XCTAssertTrue(fileManager._itemExistsAtURL(newDirectoryURL.URLByAppendingPathComponent(fileInDirectoryURL.lastPathComponent!))) + } + } + + func testMoveFilesToTrash() + { + makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL in + XCTAssertNil(try? fileManager.moveItemAtURLToTrash(rootURL.URLByAppendingPathComponent("does not exist"))) + + let trashURL = try! NSFileManager.defaultManager().URLForDirectory(.TrashDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false) + + try! fileManager.moveItemAtURLToTrash(ordinaryFileURL) + XCTAssertFalse(fileManager._itemExistsAtURL(ordinaryFileURL)) + + let ordinaryFileTrashURL = trashURL.URLByAppendingPathComponent(ordinaryFileURL.lastPathComponent!) + XCTAssertTrue(fileManager._itemExistsAtURL(ordinaryFileTrashURL)) + try! fileManager.removeItemAtURL(ordinaryFileTrashURL) + + try! fileManager.moveItemAtURLToTrash(directoryURL) + XCTAssertFalse(fileManager._itemExistsAtURL(directoryURL)) + XCTAssertFalse(fileManager._itemExistsAtURL(fileInDirectoryURL)) + + let directoryTrashURL = trashURL.URLByAppendingPathComponent(directoryURL.lastPathComponent!) + XCTAssertTrue(fileManager._itemExistsAtURL(directoryTrashURL)) + XCTAssertTrue(fileManager._itemExistsAtURL(directoryTrashURL.URLByAppendingPathComponent(fileInDirectoryURL.lastPathComponent!))) + + try! fileManager.removeItemAtURL(directoryTrashURL) + } + } + + func testRemoveFiles() + { + makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL in + XCTAssertNil(try? fileManager.removeItemAtURL(rootURL.URLByAppendingPathComponent("does not exist"))) + + try! fileManager.removeItemAtURL(ordinaryFileURL) + XCTAssertFalse(fileManager._itemExistsAtURL(ordinaryFileURL)) + + try! fileManager.removeItemAtURL(directoryURL) + XCTAssertFalse(fileManager._itemExistsAtURL(directoryURL)) + XCTAssertFalse(fileManager._itemExistsAtURL(fileInDirectoryURL)) + } + } + + func testReleaseFilesFromQuarantine() + { + makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL in + try! fileManager.releaseItemFromQuarantineWithoutAuthenticationAtRootURL(ordinaryFileURL) + try! fileManager.releaseItemFromQuarantineWithoutAuthenticationAtRootURL(directoryURL) + + let quarantineData = "does not really matter what is here".cStringUsingEncoding(NSUTF8StringEncoding)! + let quarantineDataLength = Int(strlen(quarantineData)) + + XCTAssertEqual(0, setxattr(ordinaryFileURL.path!, SUAppleQuarantineIdentifier, quarantineData, quarantineDataLength, 0, XATTR_CREATE)) + XCTAssertGreaterThan(getxattr(ordinaryFileURL.path!, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW), 0) + + try! fileManager.releaseItemFromQuarantineWithoutAuthenticationAtRootURL(ordinaryFileURL) + XCTAssertEqual(-1, getxattr(ordinaryFileURL.path!, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW)) + + XCTAssertEqual(0, setxattr(directoryURL.path!, SUAppleQuarantineIdentifier, quarantineData, quarantineDataLength, 0, XATTR_CREATE)) + XCTAssertGreaterThan(getxattr(directoryURL.path!, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW), 0) + + XCTAssertEqual(0, setxattr(fileInDirectoryURL.path!, SUAppleQuarantineIdentifier, quarantineData, quarantineDataLength, 0, XATTR_CREATE)) + XCTAssertGreaterThan(getxattr(fileInDirectoryURL.path!, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW), 0) + + try! fileManager.releaseItemFromQuarantineWithoutAuthenticationAtRootURL(directoryURL) + + XCTAssertEqual(-1, getxattr(directoryURL.path!, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW)) + XCTAssertEqual(-1, getxattr(fileInDirectoryURL.path!, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW)) + } + } + + func groupIDAtPath(path: String) -> gid_t + { + let attributes = try! NSFileManager.defaultManager().attributesOfItemAtPath(path) + let groupID = attributes[NSFileGroupOwnerAccountID] as! NSNumber + return groupID.unsignedIntValue + } + + // Only the super user can alter user IDs, so changing user IDs is not tested here + // Instead we try to change the group ID - we just have to be a member of that group + func testAlterFilesGroupID() + { + makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL in + XCTAssertNil(try? fileManager.changeOwnerAndGroupOfItemAtRootURL(ordinaryFileURL, toMatchURL: rootURL.URLByAppendingPathComponent("does not exist"))) + + XCTAssertNil(try? fileManager.changeOwnerAndGroupOfItemAtRootURL(rootURL.URLByAppendingPathComponent("does not exist"), toMatchURL: ordinaryFileURL)) + + let everyoneGroup = getgrnam("everyone") + let everyoneGroupID = everyoneGroup.memory.gr_gid + + let staffGroup = getgrnam("staff") + let staffGroupID = staffGroup.memory.gr_gid + + XCTAssertNotEqual(staffGroupID, everyoneGroupID) + + XCTAssertEqual(staffGroupID, self.groupIDAtPath(ordinaryFileURL.path!)) + XCTAssertEqual(staffGroupID, self.groupIDAtPath(directoryURL.path!)) + XCTAssertEqual(staffGroupID, self.groupIDAtPath(fileInDirectoryURL.path!)) + + try! fileManager.changeOwnerAndGroupOfItemAtRootURL(fileInDirectoryURL, toMatchURL: ordinaryFileURL) + try! fileManager.changeOwnerAndGroupOfItemAtRootURL(ordinaryFileURL, toMatchURL: ordinaryFileURL) + + XCTAssertEqual(staffGroupID, self.groupIDAtPath(ordinaryFileURL.path!)) + XCTAssertEqual(staffGroupID, self.groupIDAtPath(directoryURL.path!)) + + XCTAssertEqual(0, chown(ordinaryFileURL.path!, getuid(), everyoneGroupID)) + XCTAssertEqual(everyoneGroupID, self.groupIDAtPath(ordinaryFileURL.path!)) + + try! fileManager.changeOwnerAndGroupOfItemAtRootURL(fileInDirectoryURL, toMatchURL: ordinaryFileURL) + XCTAssertEqual(everyoneGroupID, self.groupIDAtPath(fileInDirectoryURL.path!)) + + try! fileManager.changeOwnerAndGroupOfItemAtRootURL(fileInDirectoryURL, toMatchURL: directoryURL) + XCTAssertEqual(staffGroupID, self.groupIDAtPath(fileInDirectoryURL.path!)) + + try! fileManager.changeOwnerAndGroupOfItemAtRootURL(directoryURL, toMatchURL: ordinaryFileURL) + XCTAssertEqual(everyoneGroupID, self.groupIDAtPath(directoryURL.path!)) + XCTAssertEqual(everyoneGroupID, self.groupIDAtPath(fileInDirectoryURL.path!)) + } + } + + func testFileExists() + { + makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL in + XCTAssertTrue(fileManager._itemExistsAtURL(ordinaryFileURL)) + XCTAssertTrue(fileManager._itemExistsAtURL(directoryURL)) + XCTAssertFalse(fileManager._itemExistsAtURL(rootURL.URLByAppendingPathComponent("does not exist"))) + + var isOrdinaryFileDirectory: ObjCBool = false + XCTAssertTrue(fileManager._itemExistsAtURL(ordinaryFileURL, isDirectory: &isOrdinaryFileDirectory) && !isOrdinaryFileDirectory) + + var isDirectoryADirectory: ObjCBool = false + XCTAssertTrue(fileManager._itemExistsAtURL(directoryURL, isDirectory: &isDirectoryADirectory) && isDirectoryADirectory) + + XCTAssertFalse(fileManager._itemExistsAtURL(rootURL.URLByAppendingPathComponent("does not exist"), isDirectory: nil)) + + let validSymlinkURL = rootURL.URLByAppendingPathComponent("symlink test") + try! NSFileManager.defaultManager().createSymbolicLinkAtURL(validSymlinkURL, withDestinationURL: directoryURL) + + XCTAssertTrue(fileManager._itemExistsAtURL(validSymlinkURL)) + + var validSymlinkIsADirectory: ObjCBool = false + XCTAssertTrue(fileManager._itemExistsAtURL(validSymlinkURL, isDirectory: &validSymlinkIsADirectory) && !validSymlinkIsADirectory) + + let invalidSymlinkURL = rootURL.URLByAppendingPathComponent("symlink test 2") + try! NSFileManager.defaultManager().createSymbolicLinkAtURL(invalidSymlinkURL, withDestinationURL: rootURL.URLByAppendingPathComponent("does not exist")) + + // Symlink should still exist even if it doesn't point to a file that exists + XCTAssertTrue(fileManager._itemExistsAtURL(invalidSymlinkURL)) + + var invalidSymlinkIsADirectory: ObjCBool = false + XCTAssertTrue(fileManager._itemExistsAtURL(invalidSymlinkURL, isDirectory: &invalidSymlinkIsADirectory) && !invalidSymlinkIsADirectory) + } + } + + func testMakeDirectory() + { + makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL in + XCTAssertNil(try? fileManager._makeDirectoryAtURL(ordinaryFileURL)) + XCTAssertNil(try? fileManager._makeDirectoryAtURL(directoryURL)) + + XCTAssertNil(try? fileManager._makeDirectoryAtURL(rootURL.URLByAppendingPathComponent("this should").URLByAppendingPathComponent("be a failure"))) + + let newDirectoryURL = rootURL.URLByAppendingPathComponent("new test directory") + XCTAssertFalse(fileManager._itemExistsAtURL(newDirectoryURL)) + try! fileManager._makeDirectoryAtURL(newDirectoryURL) + + var isDirectory: ObjCBool = false + XCTAssertTrue(fileManager._itemExistsAtURL(newDirectoryURL, isDirectory: &isDirectory)) + } + } + + // This alone shouldn't prompt a password dialog and should always succeed + func testAcquireAuthorization() + { + let fileManager = SUFileManager() + try! fileManager._acquireAuthorization() + } +} diff --git a/Tests/Sparkle Unit Tests-Bridging-Header.h b/Tests/Sparkle Unit Tests-Bridging-Header.h index f5d76dcd..7f7cc44e 100644 --- a/Tests/Sparkle Unit Tests-Bridging-Header.h +++ b/Tests/Sparkle Unit Tests-Bridging-Header.h @@ -5,3 +5,17 @@ #import "SUUnarchiver.h" #import "SUPipedUnarchiver.h" #import "SUBinaryDeltaCommon.h" +#import "SUFileManager.h" + +extern NSString *SUAppleQuarantineIdentifier; + +@interface SUFileManager (Private) + +- (BOOL)_acquireAuthorizationWithError:(NSError *__autoreleasing *)error; + +- (BOOL)_itemExistsAtURL:(NSURL *)fileURL; +- (BOOL)_itemExistsAtURL:(NSURL *)fileURL isDirectory:(BOOL *)isDirectory; + +- (BOOL)_makeDirectoryAtURL:(NSURL *)url error:(NSError * __autoreleasing *)error; + +@end From 03655cf8b24fa2c3914999acf899e91f06485921 Mon Sep 17 00:00:00 2001 From: Zorg Date: Sat, 26 Sep 2015 15:11:23 -0400 Subject: [PATCH 2/3] Resolve nullability warnings --- Sparkle/SUFileManager.m | 33 +++++++++++++++++++++++++-------- Sparkle/SUPlainInstaller.m | 26 +++++++++++++++++++++++--- 2 files changed, 48 insertions(+), 11 deletions(-) diff --git a/Sparkle/SUFileManager.m b/Sparkle/SUFileManager.m index 122c8b56..506b149f 100644 --- a/Sparkle/SUFileManager.m +++ b/Sparkle/SUFileManager.m @@ -95,12 +95,21 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza - (BOOL)_itemExistsAtURL:(NSURL *)fileURL { - return [_fileManager attributesOfItemAtPath:fileURL.path error:NULL] != nil; + NSString *path = fileURL.path; + if (path == nil) { + return NO; + } + return [_fileManager attributesOfItemAtPath:path error:NULL] != nil; } - (BOOL)_itemExistsAtURL:(NSURL *)fileURL isDirectory:(BOOL *)isDirectory { - NSDictionary *attributes = [_fileManager attributesOfItemAtPath:fileURL.path error:NULL]; + NSString *path = fileURL.path; + if (path == nil) { + return NO; + } + + NSDictionary *attributes = [_fileManager attributesOfItemAtPath:path error:NULL]; if (attributes == nil) { return NO; } @@ -240,7 +249,8 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza // Only recurse if it's actually a directory. Don't recurse into a // root-level symbolic link. - NSDictionary *rootAttributes = [_fileManager attributesOfItemAtPath:rootURL.path error:nil]; + NSString *rootURLPath = rootURL.path; + NSDictionary *rootAttributes = [_fileManager attributesOfItemAtPath:rootURLPath error:nil]; NSString *rootType = rootAttributes[NSFileType]; if ([rootType isEqualToString:NSFileTypeDirectory]) { @@ -418,7 +428,8 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza } NSError *matchFileAttributesError = nil; - NSDictionary *matchFileAttributes = [_fileManager attributesOfItemAtPath:matchURL.path error:&matchFileAttributesError]; + NSString *matchURLPath = matchURL.path; + NSDictionary *matchFileAttributes = [_fileManager attributesOfItemAtPath:matchURLPath error:&matchFileAttributesError]; if (matchFileAttributes == nil) { if (error != NULL) { *error = matchFileAttributesError; @@ -427,7 +438,8 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza } NSError *targetFileAttributesError = nil; - NSDictionary *targetFileAttributes = [_fileManager attributesOfItemAtPath:targetURL.path error:&targetFileAttributesError]; + NSString *targetURLPath = targetURL.path; + NSDictionary *targetFileAttributes = [_fileManager attributesOfItemAtPath:targetURLPath error:&targetFileAttributesError]; if (targetFileAttributes == nil) { if (error != NULL) { *error = targetFileAttributesError; @@ -453,7 +465,10 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza return NO; } - if ([ownerID isEqualToNumber:targetFileAttributes[NSFileOwnerAccountID]] && [groupID isEqualToNumber:targetFileAttributes[NSFileGroupOwnerAccountID]]) { + NSNumber *targetOwnerID = targetFileAttributes[NSFileOwnerAccountID]; + NSNumber *targetGroupID = targetFileAttributes[NSFileGroupOwnerAccountID]; + + if ((targetOwnerID != nil && [ownerID isEqualToNumber:targetOwnerID]) && (targetGroupID != nil && [groupID isEqualToNumber:targetGroupID])) { // Assume they're the same even if we don't check every file recursively // Speeds up the common case return YES; @@ -666,7 +681,8 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza return NO; } - NSURL *tempItemURL = [tempDirectory URLByAppendingPathComponent:url.lastPathComponent]; + NSString *urlLastPathComponent = url.lastPathComponent; + NSURL *tempItemURL = [tempDirectory URLByAppendingPathComponent:urlLastPathComponent]; if (![self moveItemAtURL:url toURL:tempItemURL error:error]) { // If we can't move the item at url, just remove it completely; chances are it's not going to be missed [self removeItemAtURL:url error:NULL]; @@ -685,7 +701,8 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza BOOL success = NO; #if __MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_8 if (!canUseNewTrashAPI) { - success = [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:tempItemURL.URLByDeletingLastPathComponent.path destination:@"" files:@[tempItemURL.lastPathComponent] tag:NULL]; + NSString *tempParentPath = tempItemURL.URLByDeletingLastPathComponent.path; + success = [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:tempParentPath destination:@"" files:@[tempItemURL.lastPathComponent] tag:NULL]; if (!success && error != NULL) { *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileNoSuchFileError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to move file %@ into the trash.", tempItemURL.lastPathComponent] }]; } diff --git a/Sparkle/SUPlainInstaller.m b/Sparkle/SUPlainInstaller.m index b70be520..6a9e9307 100644 --- a/Sparkle/SUPlainInstaller.m +++ b/Sparkle/SUPlainInstaller.m @@ -18,7 +18,7 @@ // Returns the bundle version from the specified host that is appropriate to use as a filename, or nil if we're unable to retrieve one + (NSString *)bundleVersionAppropriateForFilenameFromHost:(SUHost *)host { - NSString *bundleVersion = [host objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey]; + NSString *bundleVersion = [host objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleVersionKey]; NSString *trimmedVersion = @""; if (bundleVersion != nil) { @@ -33,6 +33,15 @@ + (BOOL)performInstallationToURL:(NSURL *)installationURL fromUpdateAtURL:(NSURL *)newURL withHost:(SUHost *)host error:(NSError * __autoreleasing *)error { + if (installationURL == nil || newURL == nil) { + // this really shouldn't happen but just in case + SULog(@"Failed to perform installation because either installation URL (%@) or new URL (%@) is nil", installationURL, newURL); + if (error != NULL) { + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: @"Failed to perform installation because the paths to install at and from are not valid" }]; + } + return NO; + } + SUFileManager *fileManager = [[SUFileManager alloc] init]; // Create a temporary directory for our new app that resides on our destination's volume @@ -43,7 +52,8 @@ } // Move the new app to our temporary directory - NSURL *newTempURL = [tempNewDirectoryURL URLByAppendingPathComponent:newURL.lastPathComponent]; + NSString *newURLLastPathComponent = newURL.lastPathComponent; + NSURL *newTempURL = [tempNewDirectoryURL URLByAppendingPathComponent:newURLLastPathComponent]; if (![fileManager moveItemAtURL:newURL toURL:newTempURL error:error]) { SULog(@"Failed to move the new app from %@ to its temp directory at %@", newURL.path, newTempURL.path); [fileManager removeItemAtURL:tempNewDirectoryURL error:NULL]; @@ -61,6 +71,15 @@ } NSURL *oldURL = [NSURL fileURLWithPath:host.bundlePath]; + if (oldURL == nil) { + // this really shouldn't happen but just in case + SULog(@"Failed to construct URL from bundle path: %@", host.bundlePath); + if (error != NULL) { + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: @"Failed to perform installation because a path could not be constructed for the old installation" }]; + } + return NO; + } + if (![fileManager changeOwnerAndGroupOfItemAtRootURL:newTempURL toMatchURL:oldURL error:error]) { // But this is big enough of a deal to fail SULog(@"Failed to change owner and group of new app at %@ to match old app at %@", newTempURL.path, oldURL.path); @@ -78,7 +97,8 @@ oldDestinationName = oldURL.lastPathComponent.stringByDeletingPathExtension; } - NSString *oldDestinationNameWithPathExtension = [oldDestinationName stringByAppendingPathExtension:oldURL.pathExtension]; + NSString *oldURLExtension = oldURL.pathExtension; + NSString *oldDestinationNameWithPathExtension = [oldDestinationName stringByAppendingPathExtension:oldURLExtension]; // Create a temporary directory for our old app that resides on its volume NSURL *tempOldDirectoryURL = [fileManager makeTemporaryDirectoryWithPreferredName:oldDestinationName appropriateForDirectoryURL:oldURL.URLByDeletingLastPathComponent error:error]; From 9822b4d2a13f3bf7d33be624c3bb1b66fca56a37 Mon Sep 17 00:00:00 2001 From: Zorg Date: Sat, 26 Sep 2015 15:21:33 -0400 Subject: [PATCH 3/3] Fix typo --- Sparkle/SUFileManager.m | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sparkle/SUFileManager.m b/Sparkle/SUFileManager.m index 506b149f..cbf74c82 100644 --- a/Sparkle/SUFileManager.m +++ b/Sparkle/SUFileManager.m @@ -287,7 +287,7 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza // "com.apple.quarantine", on affected files. Removing this attribute is // sufficient to remove files from the quarantine. -// This works be removing the quarantine extended attribute for every file we come across. +// This works by removing the quarantine extended attribute for every file we come across. // We used to have code similar to the method below that used -[NSURL getResourceValue:forKey:error:] and -[NSURL setResourceValue:forKey:error:] // However, those methods *really suck* - you can't rely on the return value from getting the resource value and if you set the resource value // when the key isn't present, errors are spewed out to the console