From 155782708bdbcb3dafe93b91d3b97b3f7fb47870 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kornel=20Lesin=CC=81ski?= Date: Sun, 8 Nov 2015 23:37:28 +0000 Subject: [PATCH 1/4] Helper function for FSRef --- Sparkle/SUFileManager.m | 285 ++++++++++++++++++++-------------------- 1 file changed, 140 insertions(+), 145 deletions(-) diff --git a/Sparkle/SUFileManager.m b/Sparkle/SUFileManager.m index b89365e2..ca7452ca 100644 --- a/Sparkle/SUFileManager.m +++ b/Sparkle/SUFileManager.m @@ -20,7 +20,7 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza { sig_t oldSigChildHandler = signal(SIGCHLD, SIG_DFL); BOOL returnValue = YES; - + #pragma clang diagnostic push // In the future, we may have to look at SMJobBless API to avoid deprecation. See issue #558 #pragma clang diagnostic ignored "-Wdeprecated-declarations" @@ -34,11 +34,34 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza } else returnValue = NO; - + signal(SIGCHLD, oldSigChildHandler); return returnValue; } +static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { + + char sourcePath[PATH_MAX] = {0}; + if (![url.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.", url.lastPathComponent] }]; + } + return NO; + } + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + OSStatus makeResult = FSPathMakeRefWithOptions((const UInt8 *)sourcePath, kFSPathMakeRefDoNotFollowLeafSymlink, ref, NULL); +#pragma clang diagnostic pop + if (makeResult != noErr) { + if (error != NULL) { + *error = [NSError errorWithDomain:NSOSStatusErrorDomain code:makeResult userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to create file system reference for source %@.", url.lastPathComponent] }]; + } + return NO; + } + return YES; +} + // Used to indicate if the type of NSError requires us to attempt to peform the same operation again except with authentication // To be safe, both read and write permission denied's are included because Cocoa's error methods are not very well documented // and at least one case is caused from lack of read permissions (-[NSURL setResourceValue:forKey:error:]) @@ -78,14 +101,14 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza if (_auth != NULL) { return YES; } - + if (!_allowsAuthorization) { if (error != NULL) { *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: @"Unable to grant authorization to perform action because it is explicitly turned off" }]; } return NO; } - + OSStatus status = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &_auth); if (status != errAuthorizationSuccess) { if (error != NULL) { @@ -121,16 +144,16 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza if (path == nil) { return NO; } - + NSDictionary *attributes = [_fileManager attributesOfItemAtPath:path error:NULL]; if (attributes == nil) { return NO; } - + if (isDirectory != NULL) { *isDirectory = [attributes[NSFileType] isEqualToString:NSFileTypeDirectory]; } - + return YES; } @@ -142,7 +165,7 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza errno = 0; return -1; } - + return getxattr(path, name, NULL, 0, 0, options); } @@ -154,7 +177,7 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza errno = 0; return -1; } - + return removexattr(path, attr, options); } @@ -169,7 +192,7 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza } return NO; } - + char path[PATH_MAX] = {0}; if (![rootURL.path getFileSystemRepresentation:path maxLength:sizeof(path)]) { if (error != NULL) { @@ -177,18 +200,18 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza } return NO; } - + if (![self _acquireAuthorizationWithError:error]) { return NO; } - + BOOL success = AuthorizationExecuteWithPrivilegesAndWait(_auth, XATTR_UTILITY_PATH, kAuthorizationFlagDefaults, (char *[]){ "-s", "-r", "-d", xattrName, path, NULL }); - + if (!success && error != NULL) { NSString *errorMessage = [NSString stringWithFormat:@"Authenticated extended attribute deletion for %@ failed on %@.", [NSString stringWithUTF8String:xattrName], rootURL.path.lastPathComponent]; *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:errorMessage }]; } - + return success; } @@ -200,11 +223,11 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza } return NO; } - + BOOL (^releasingQuarantineRequiredAuthentication)(NSURL *, BOOL *, BOOL *) = ^(NSURL *fileURL, BOOL *didReleaseQuarantine, BOOL *success) { BOOL removedQuarantine = NO; BOOL attemptedAuthentication = NO; - + if (quarantineRetrieval(fileURL)) { NSError *removalError = nil; if (quarantineRemoval(fileURL, &removalError)) { @@ -225,32 +248,32 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza } } } - + if (didReleaseQuarantine != NULL) { *didReleaseQuarantine = removedQuarantine; } - + return attemptedAuthentication; }; - + BOOL success = YES; - + BOOL releasedRootQuarantine = NO; if (releasingQuarantineRequiredAuthentication(rootURL, &releasedRootQuarantine, &success)) { return releasedRootQuarantine; } - + // Only recurse if it's actually a directory. Don't recurse into a // root-level symbolic link. NSString *rootURLPath = rootURL.path; NSDictionary *rootAttributes = [_fileManager attributesOfItemAtPath:rootURLPath error:nil]; NSString *rootType = rootAttributes[NSFileType]; - + if ([rootType isEqualToString:NSFileTypeDirectory]) { // The NSDirectoryEnumerator will avoid recursing into any contained // symbolic links, so no further type checks are needed. NSDirectoryEnumerator *directoryEnumerator = [_fileManager enumeratorAtURL:rootURL includingPropertiesForKeys:nil options:(NSDirectoryEnumerationOptions)0 errorHandler:nil]; - + for (NSURL *file in directoryEnumerator) { BOOL releasedQuarantine = NO; if (releasingQuarantineRequiredAuthentication(file, &releasedQuarantine, &success)) { @@ -258,7 +281,7 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza } } } - + return success; } @@ -287,7 +310,7 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza - (BOOL)releaseItemFromQuarantineAtRootURL:(NSURL *)rootURL error:(NSError *__autoreleasing *)error { static const int removeXAttrOptions = XATTR_NOFOLLOW; - + return [self _releaseItemFromQuarantineAtRootURL:rootURL @@ -323,61 +346,31 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza } return NO; } - + if (![self _itemExistsAtURL:destinationURL.URLByDeletingLastPathComponent]) { if (error != NULL) { *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileNoSuchFileError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Destination parent directory to copy into (%@) does not exist.", destinationURL.URLByDeletingLastPathComponent.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] }]; - } + if (!SUMakeRefFromURL(sourceURL, &sourceRef, error)) { 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] }]; - } + if (!SUMakeRefFromURL(destinationURL.URLByDeletingLastPathComponent, &destinationParentRef, error)) { return NO; } - + #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" OSStatus copyResult = FSCopyObjectSync(&sourceRef, &destinationParentRef, (__bridge CFStringRef)(destinationURL.lastPathComponent), NULL, kFSFileOperationDefaultOptions); @@ -385,7 +378,7 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza if (copyResult == noErr) { return YES; } - + // Note: I have received afpAccessDenied error in testing even when not copying from/to an AFP mount, // when the error should have been a normal permission denied one if (copyResult != permErr && copyResult != afpAccessDenied) { @@ -394,10 +387,19 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza } return NO; } - + if (![self _acquireAuthorizationWithError:error]) { 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:@"Destination to copy file to (%@) cannot be represented as a valid file name.", sourceURL.lastPathComponent] }]; + } + return NO; + } char destinationPath[PATH_MAX] = {0}; if (![destinationURL.path getFileSystemRepresentation:destinationPath maxLength:sizeof(destinationPath)]) { @@ -406,7 +408,7 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza } 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]; @@ -414,7 +416,7 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza } return NO; } - + return YES; } @@ -427,19 +429,11 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza */ - (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 + if (!SUMakeRefFromURL(url, &pathRef, NULL)) { return NO; } - + FSCatalogInfo catalogInfo; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" @@ -448,11 +442,11 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza if (catalogError != noErr) { return NO; } - + if (volumeID != NULL) { *volumeID = catalogInfo.volume; } - + return YES; } @@ -464,52 +458,53 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza } return NO; } - - if (![self _itemExistsAtURL:destinationURL.URLByDeletingLastPathComponent]) { + + NSURL *destinationURLParent = destinationURL.URLByDeletingLastPathComponent; + if (![self _itemExistsAtURL:destinationURLParent]) { if (error != NULL) { - *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileNoSuchFileError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Destination parent directory to move into (%@) does not exist.", destinationURL.URLByDeletingLastPathComponent.lastPathComponent] }]; + *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileNoSuchFileError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Destination parent directory to move into (%@) does not exist.", destinationURLParent.lastPathComponent] }]; } return NO; } - + if ([self _itemExistsAtURL:destinationURL]) { if (error != NULL) { *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileWriteFileExistsError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Destination file to move (%@) already exists.", destinationURL.lastPathComponent] }]; } 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]; - + BOOL foundDestinationVolume = [self _getVolumeID:&destinationVolume ofItemAtURL:destinationURLParent]; + 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; } - + if (!NS_HAS_PERMISSION_ERROR(moveError)) { if (error != NULL) { *error = moveError; } return NO; } - + if (![self _acquireAuthorizationWithError:error]) { return NO; } - + char sourcePath[PATH_MAX] = {0}; if (![sourceURL.path getFileSystemRepresentation:sourcePath maxLength:sizeof(sourcePath)]) { if (error != NULL) { @@ -517,7 +512,7 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza } return NO; } - + char destinationPath[PATH_MAX] = {0}; if (![destinationURL.path getFileSystemRepresentation:destinationPath maxLength:sizeof(destinationPath)]) { if (error != NULL) { @@ -525,7 +520,7 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza } return NO; } - + if (!AuthorizationExecuteWithPrivilegesAndWait(_auth, "/bin/mv", kAuthorizationFlagDefaults, (char *[]){ "-f", sourcePath, destinationPath, NULL })) { if (error != NULL) { NSString *errorMessage = [NSString stringWithFormat:@"Failed to perform authenticated file move for %@.", sourceURL.lastPathComponent]; @@ -533,7 +528,7 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza } return NO; } - + return YES; } @@ -546,7 +541,7 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza } return NO; } - + if (chown(path, ownerID.unsignedIntValue, groupID.unsignedIntValue) != 0) { if (errno == EPERM) { if (needsAuth != NULL) { @@ -559,7 +554,7 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza return NO; } } - + return YES; } @@ -572,14 +567,14 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza } return NO; } - + 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] }]; } return NO; } - + NSError *matchFileAttributesError = nil; NSString *matchURLPath = matchURL.path; NSDictionary *matchFileAttributes = [_fileManager attributesOfItemAtPath:matchURLPath error:&matchFileAttributesError]; @@ -589,7 +584,7 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza } return NO; } - + NSError *targetFileAttributesError = nil; NSString *targetURLPath = targetURL.path; NSDictionary *targetFileAttributes = [_fileManager attributesOfItemAtPath:targetURLPath error:&targetFileAttributesError]; @@ -599,7 +594,7 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza } return NO; } - + NSNumber *ownerID = matchFileAttributes[NSFileOwnerAccountID]; if (ownerID == nil) { // shouldn't be possible to error here, but just in case @@ -608,7 +603,7 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza } return NO; } - + NSNumber *groupID = matchFileAttributes[NSFileGroupOwnerAccountID]; if (groupID == nil) { // shouldn't be possible to error here, but just in case @@ -617,39 +612,39 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza } return NO; } - + 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; } - + BOOL needsAuth = NO; - + 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; } } } - + if (!needsAuth) { return YES; } - + char targetPath[PATH_MAX] = {0}; if (![targetURL.path getFileSystemRepresentation:targetPath maxLength:sizeof(targetPath)]) { if (error != NULL) { @@ -657,23 +652,23 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza } return NO; } - + char userAndGroup[100]; int written = snprintf(userAndGroup, sizeof(userAndGroup), "%u:%u", ownerID.unsignedIntValue, groupID.unsignedIntValue); if (written < 0 || written >= 100) { return NO; // No custom error, because it's too unlikely to ever happen } - + if (![self _acquireAuthorizationWithError:error]) { return NO; } - + BOOL success = AuthorizationExecuteWithPrivilegesAndWait(_auth, "/usr/sbin/chown", kAuthorizationFlagDefaults, (char *[]){ "-R", userAndGroup, targetPath, NULL }); if (!success && error != NULL) { NSString *errorMessage = [NSString stringWithFormat:@"Failed to change owner:group %@ on %@ with authentication.", [NSString stringWithUTF8String:userAndGroup], targetURL.path.lastPathComponent]; *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: errorMessage }]; } - + return success; } @@ -691,7 +686,7 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza } return NO; } - + char path[PATH_MAX] = {0}; if (![targetURL.path getFileSystemRepresentation:path maxLength:sizeof(path)]) { if (error != NULL) { @@ -699,28 +694,28 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza } return NO; } - + if (utimes(path, NULL) == 0) { return YES; } - + if (errno != EACCES) { if (error != NULL) { *error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to update modification & access time for %@", targetURL.path.lastPathComponent] }]; } return NO; } - + if (![self _acquireAuthorizationWithError:error]) { return NO; } - + BOOL success = AuthorizationExecuteWithPrivilegesAndWait(_auth, "/usr/bin/touch", kAuthorizationFlagDefaults, (char *[]){ path, NULL }); if (!success && error != NULL) { NSString *errorMessage = [NSString stringWithFormat:@"Failed to update modification & access time on %@ with authentication.", targetURL.path.lastPathComponent]; *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: errorMessage }]; } - + return success; } @@ -734,7 +729,7 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza } return NO; } - + NSURL *parentURL = [url URLByDeletingLastPathComponent]; BOOL isParentADirectory = NO; if (![self _itemExistsAtURL:parentURL isDirectory:&isParentADirectory] || !isParentADirectory) { @@ -743,19 +738,19 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza } return NO; } - + NSError *createDirectoryError = nil; if ([_fileManager createDirectoryAtURL:url withIntermediateDirectories:NO attributes:nil error:&createDirectoryError]) { return YES; } - + if (!NS_HAS_PERMISSION_ERROR(createDirectoryError)) { if (error != NULL) { *error = createDirectoryError; } return NO; } - + char path[PATH_MAX] = {0}; if (![url.path getFileSystemRepresentation:path maxLength:sizeof(path)]) { if (error != NULL) { @@ -763,11 +758,11 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza } return NO; } - + if (![self _acquireAuthorizationWithError:error]) { return NO; } - + BOOL success = AuthorizationExecuteWithPrivilegesAndWait(_auth, "/bin/mkdir", kAuthorizationFlagDefaults, (char *[]){ path, NULL }); if (!success && error != NULL) { NSString *errorMessage = [NSString stringWithFormat:@"Failed to make directory %@ with authentication.", url.path.lastPathComponent]; @@ -780,20 +775,20 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza { NSError *tempError = nil; NSURL *tempURL = [_fileManager URLForDirectory:NSItemReplacementDirectory inDomain:NSUserDomainMask appropriateForURL:directoryURL create:YES error:&tempError]; - + if (tempURL != nil) { return tempURL; } - + // It is pretty unlikely in my testing we will get here, but just in case we do, we should create a directory inside // the directory pointed by directoryURL, using the preferredName - + NSURL *desiredURL = [directoryURL URLByAppendingPathComponent:preferredName]; NSUInteger tagIndex = 1; while ([self _itemExistsAtURL:desiredURL] && tagIndex <= 9999) { desiredURL = [directoryURL URLByAppendingPathComponent:[preferredName stringByAppendingFormat:@" (%lu)", (unsigned long)++tagIndex]]; } - + return [self _makeDirectoryAtURL:desiredURL error:error] ? desiredURL : nil; } @@ -805,23 +800,23 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza } return NO; } - + NSError *removeError = nil; if ([_fileManager removeItemAtURL:url error:&removeError]) { return YES; } - + if (!NS_HAS_PERMISSION_ERROR(removeError)) { if (error != NULL) { *error = removeError; } return NO; } - + if (![self _acquireAuthorizationWithError:error]) { return NO; } - + char path[PATH_MAX] = {0}; if (![url.path getFileSystemRepresentation:path maxLength:sizeof(path)]) { if (error != NULL) { @@ -829,7 +824,7 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza } return NO; } - + BOOL success = AuthorizationExecuteWithPrivilegesAndWait(_auth, "/bin/rm", kAuthorizationFlagDefaults, (char *[]){ "-rf", path, NULL }); if (!success && error != NULL) { *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to remove %@ with authentication.", url.path.lastPathComponent] }]; @@ -845,7 +840,7 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza } return NO; } - + NSURL *trashURL = nil; BOOL canUseNewTrashAPI = YES; #if __MAC_OS_X_VERSION_MIN_REQUIRED < 1080 @@ -857,18 +852,18 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza } } #endif - + if (canUseNewTrashAPI) { trashURL = [_fileManager URLForDirectory:NSTrashDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil]; } - + if (trashURL == nil) { if (error != NULL) { *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileNoSuchFileError userInfo:@{ NSLocalizedDescriptionKey: @"Failed to locate the user's trash folder." }]; } return NO; } - + // In the rare worst case scenario, our temporary directory will be labeled incomplete and be in the user's trash directory, // indicating that whatever inside of there is not yet completely moved. // Regardless, we want the item to be in our Volume before we try moving it to the trash @@ -877,7 +872,7 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza if (tempDirectory == nil) { return NO; } - + NSString *urlLastPathComponent = url.lastPathComponent; NSURL *tempItemURL = [tempDirectory URLByAppendingPathComponent:urlLastPathComponent]; if (![self moveItemAtURL:url toURL:tempItemURL error:error]) { @@ -886,15 +881,15 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza [self removeItemAtURL:tempDirectory error:NULL]; return NO; } - + if (![self changeOwnerAndGroupOfItemAtRootURL:tempItemURL toMatchURL:trashURL error:error]) { // Removing the item inside of the temp directory is better than trying to move the item to the trash with incorrect ownership [self removeItemAtURL:tempDirectory error:NULL]; return NO; } - + // If we get here, we should be able to trash the item normally without authentication - + BOOL success = NO; #if __MAC_OS_X_VERSION_MIN_REQUIRED < 1080 if (!canUseNewTrashAPI) { @@ -905,7 +900,7 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza } } #endif - + if (canUseNewTrashAPI) { NSError *trashError = nil; success = [_fileManager trashItemAtURL:tempItemURL resultingItemURL:NULL error:&trashError]; @@ -913,9 +908,9 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza *error = trashError; } } - + [self removeItemAtURL:tempDirectory error:NULL]; - + return success; } From 533a0ecf17bcfaa6fd39023da0953982fb84b23e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kornel=20Lesin=CC=81ski?= Date: Sun, 8 Nov 2015 23:37:44 +0000 Subject: [PATCH 2/4] cp -- to stop argument parsing --- Sparkle/SUFileManager.m | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sparkle/SUFileManager.m b/Sparkle/SUFileManager.m index ca7452ca..75654360 100644 --- a/Sparkle/SUFileManager.m +++ b/Sparkle/SUFileManager.m @@ -409,7 +409,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { return NO; } - if (!AuthorizationExecuteWithPrivilegesAndWait(_auth, "/bin/cp", kAuthorizationFlagDefaults, (char *[]){ "-Rf", sourcePath, destinationPath, NULL })) { + 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 }]; From c78a314385e7622e22e234aa426848f5c430d77e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kornel=20Lesin=CC=81ski?= Date: Mon, 9 Nov 2015 09:57:55 +0000 Subject: [PATCH 3/4] Wording --- Sparkle/SUFileManager.m | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Sparkle/SUFileManager.m b/Sparkle/SUFileManager.m index 75654360..12820928 100644 --- a/Sparkle/SUFileManager.m +++ b/Sparkle/SUFileManager.m @@ -41,21 +41,21 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { - char sourcePath[PATH_MAX] = {0}; - if (![url.path getFileSystemRepresentation:sourcePath maxLength:sizeof(sourcePath)]) { + 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 copy (%@) cannot be represented as a valid file name.", url.lastPathComponent] }]; + *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"URL of the file (%@) cannot be represented as a file path", url.lastPathComponent] }]; } return NO; } #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" - OSStatus makeResult = FSPathMakeRefWithOptions((const UInt8 *)sourcePath, kFSPathMakeRefDoNotFollowLeafSymlink, ref, NULL); + OSStatus makeResult = FSPathMakeRefWithOptions((const UInt8 *)path, kFSPathMakeRefDoNotFollowLeafSymlink, ref, NULL); #pragma clang diagnostic pop if (makeResult != noErr) { if (error != NULL) { - *error = [NSError errorWithDomain:NSOSStatusErrorDomain code:makeResult userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to create file system reference for source %@.", url.lastPathComponent] }]; + *error = [NSError errorWithDomain:NSOSStatusErrorDomain code:makeResult userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to create file system reference for %@", url.lastPathComponent] }]; } return NO; } From 373a3b422795c9e1acd2424b2238158fee7b7f93 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kornel=20Lesin=CC=81ski?= Date: Mon, 9 Nov 2015 10:01:51 +0000 Subject: [PATCH 4/4] Protect shell commands from filenames starting with - --- Sparkle/SUFileManager.m | 212 ++++++++++++++++++++-------------------- 1 file changed, 106 insertions(+), 106 deletions(-) diff --git a/Sparkle/SUFileManager.m b/Sparkle/SUFileManager.m index 12820928..be5ef09b 100644 --- a/Sparkle/SUFileManager.m +++ b/Sparkle/SUFileManager.m @@ -20,7 +20,7 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza { sig_t oldSigChildHandler = signal(SIGCHLD, SIG_DFL); BOOL returnValue = YES; - + #pragma clang diagnostic push // In the future, we may have to look at SMJobBless API to avoid deprecation. See issue #558 #pragma clang diagnostic ignored "-Wdeprecated-declarations" @@ -34,7 +34,7 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza } else returnValue = NO; - + signal(SIGCHLD, oldSigChildHandler); return returnValue; } @@ -101,14 +101,14 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { if (_auth != NULL) { return YES; } - + if (!_allowsAuthorization) { if (error != NULL) { *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: @"Unable to grant authorization to perform action because it is explicitly turned off" }]; } return NO; } - + OSStatus status = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &_auth); if (status != errAuthorizationSuccess) { if (error != NULL) { @@ -144,16 +144,16 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { if (path == nil) { return NO; } - + NSDictionary *attributes = [_fileManager attributesOfItemAtPath:path error:NULL]; if (attributes == nil) { return NO; } - + if (isDirectory != NULL) { *isDirectory = [attributes[NSFileType] isEqualToString:NSFileTypeDirectory]; } - + return YES; } @@ -165,7 +165,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { errno = 0; return -1; } - + return getxattr(path, name, NULL, 0, 0, options); } @@ -177,7 +177,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { errno = 0; return -1; } - + return removexattr(path, attr, options); } @@ -192,7 +192,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } return NO; } - + char path[PATH_MAX] = {0}; if (![rootURL.path getFileSystemRepresentation:path maxLength:sizeof(path)]) { if (error != NULL) { @@ -200,18 +200,18 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } return NO; } - + if (![self _acquireAuthorizationWithError:error]) { return NO; } - + BOOL success = AuthorizationExecuteWithPrivilegesAndWait(_auth, XATTR_UTILITY_PATH, kAuthorizationFlagDefaults, (char *[]){ "-s", "-r", "-d", xattrName, path, NULL }); - + if (!success && error != NULL) { NSString *errorMessage = [NSString stringWithFormat:@"Authenticated extended attribute deletion for %@ failed on %@.", [NSString stringWithUTF8String:xattrName], rootURL.path.lastPathComponent]; *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:errorMessage }]; } - + return success; } @@ -223,11 +223,11 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } return NO; } - + BOOL (^releasingQuarantineRequiredAuthentication)(NSURL *, BOOL *, BOOL *) = ^(NSURL *fileURL, BOOL *didReleaseQuarantine, BOOL *success) { BOOL removedQuarantine = NO; BOOL attemptedAuthentication = NO; - + if (quarantineRetrieval(fileURL)) { NSError *removalError = nil; if (quarantineRemoval(fileURL, &removalError)) { @@ -248,32 +248,32 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } } } - + if (didReleaseQuarantine != NULL) { *didReleaseQuarantine = removedQuarantine; } - + return attemptedAuthentication; }; - + BOOL success = YES; - + BOOL releasedRootQuarantine = NO; if (releasingQuarantineRequiredAuthentication(rootURL, &releasedRootQuarantine, &success)) { return releasedRootQuarantine; } - + // Only recurse if it's actually a directory. Don't recurse into a // root-level symbolic link. NSString *rootURLPath = rootURL.path; NSDictionary *rootAttributes = [_fileManager attributesOfItemAtPath:rootURLPath error:nil]; NSString *rootType = rootAttributes[NSFileType]; - + if ([rootType isEqualToString:NSFileTypeDirectory]) { // The NSDirectoryEnumerator will avoid recursing into any contained // symbolic links, so no further type checks are needed. NSDirectoryEnumerator *directoryEnumerator = [_fileManager enumeratorAtURL:rootURL includingPropertiesForKeys:nil options:(NSDirectoryEnumerationOptions)0 errorHandler:nil]; - + for (NSURL *file in directoryEnumerator) { BOOL releasedQuarantine = NO; if (releasingQuarantineRequiredAuthentication(file, &releasedQuarantine, &success)) { @@ -281,7 +281,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } } } - + return success; } @@ -310,7 +310,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { - (BOOL)releaseItemFromQuarantineAtRootURL:(NSURL *)rootURL error:(NSError *__autoreleasing *)error { static const int removeXAttrOptions = XATTR_NOFOLLOW; - + return [self _releaseItemFromQuarantineAtRootURL:rootURL @@ -346,31 +346,31 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } return NO; } - + if (![self _itemExistsAtURL:destinationURL.URLByDeletingLastPathComponent]) { if (error != NULL) { *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileNoSuchFileError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Destination parent directory to copy into (%@) does not exist.", destinationURL.URLByDeletingLastPathComponent.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; } - + FSRef sourceRef; if (!SUMakeRefFromURL(sourceURL, &sourceRef, error)) { return NO; } - + FSRef destinationParentRef; if (!SUMakeRefFromURL(destinationURL.URLByDeletingLastPathComponent, &destinationParentRef, error)) { return NO; } - + #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" OSStatus copyResult = FSCopyObjectSync(&sourceRef, &destinationParentRef, (__bridge CFStringRef)(destinationURL.lastPathComponent), NULL, kFSFileOperationDefaultOptions); @@ -378,7 +378,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { if (copyResult == noErr) { return YES; } - + // Note: I have received afpAccessDenied error in testing even when not copying from/to an AFP mount, // when the error should have been a normal permission denied one if (copyResult != permErr && copyResult != afpAccessDenied) { @@ -387,11 +387,11 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } return NO; } - + if (![self _acquireAuthorizationWithError:error]) { return NO; } - + char sourcePath[PATH_MAX] = {0}; if (![sourceURL.path getFileSystemRepresentation:sourcePath maxLength:sizeof(sourcePath)]) { @@ -408,7 +408,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } 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]; @@ -416,7 +416,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } return NO; } - + return YES; } @@ -433,7 +433,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { if (!SUMakeRefFromURL(url, &pathRef, NULL)) { return NO; } - + FSCatalogInfo catalogInfo; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" @@ -442,11 +442,11 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { if (catalogError != noErr) { return NO; } - + if (volumeID != NULL) { *volumeID = catalogInfo.volume; } - + return YES; } @@ -458,7 +458,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } return NO; } - + NSURL *destinationURLParent = destinationURL.URLByDeletingLastPathComponent; if (![self _itemExistsAtURL:destinationURLParent]) { if (error != NULL) { @@ -466,45 +466,45 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } return NO; } - + if ([self _itemExistsAtURL:destinationURL]) { if (error != NULL) { *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileWriteFileExistsError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Destination file to move (%@) already exists.", destinationURL.lastPathComponent] }]; } 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:destinationURLParent]; - + 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; } - + if (!NS_HAS_PERMISSION_ERROR(moveError)) { if (error != NULL) { *error = moveError; } return NO; } - + if (![self _acquireAuthorizationWithError:error]) { return NO; } - + char sourcePath[PATH_MAX] = {0}; if (![sourceURL.path getFileSystemRepresentation:sourcePath maxLength:sizeof(sourcePath)]) { if (error != NULL) { @@ -512,7 +512,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } return NO; } - + char destinationPath[PATH_MAX] = {0}; if (![destinationURL.path getFileSystemRepresentation:destinationPath maxLength:sizeof(destinationPath)]) { if (error != NULL) { @@ -520,15 +520,15 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } return NO; } - - if (!AuthorizationExecuteWithPrivilegesAndWait(_auth, "/bin/mv", kAuthorizationFlagDefaults, (char *[]){ "-f", sourcePath, destinationPath, NULL })) { + + if (!AuthorizationExecuteWithPrivilegesAndWait(_auth, "/bin/mv", kAuthorizationFlagDefaults, (char *[]){ "-f", "--", sourcePath, destinationPath, NULL })) { if (error != NULL) { NSString *errorMessage = [NSString stringWithFormat:@"Failed to perform authenticated file move for %@.", sourceURL.lastPathComponent]; *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:errorMessage }]; } return NO; } - + return YES; } @@ -541,7 +541,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } return NO; } - + if (chown(path, ownerID.unsignedIntValue, groupID.unsignedIntValue) != 0) { if (errno == EPERM) { if (needsAuth != NULL) { @@ -554,7 +554,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { return NO; } } - + return YES; } @@ -567,14 +567,14 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } return NO; } - + 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] }]; } return NO; } - + NSError *matchFileAttributesError = nil; NSString *matchURLPath = matchURL.path; NSDictionary *matchFileAttributes = [_fileManager attributesOfItemAtPath:matchURLPath error:&matchFileAttributesError]; @@ -584,7 +584,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } return NO; } - + NSError *targetFileAttributesError = nil; NSString *targetURLPath = targetURL.path; NSDictionary *targetFileAttributes = [_fileManager attributesOfItemAtPath:targetURLPath error:&targetFileAttributesError]; @@ -594,7 +594,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } return NO; } - + NSNumber *ownerID = matchFileAttributes[NSFileOwnerAccountID]; if (ownerID == nil) { // shouldn't be possible to error here, but just in case @@ -603,7 +603,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } return NO; } - + NSNumber *groupID = matchFileAttributes[NSFileGroupOwnerAccountID]; if (groupID == nil) { // shouldn't be possible to error here, but just in case @@ -612,39 +612,39 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } return NO; } - + 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; } - + BOOL needsAuth = NO; - + 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; } } } - + if (!needsAuth) { return YES; } - + char targetPath[PATH_MAX] = {0}; if (![targetURL.path getFileSystemRepresentation:targetPath maxLength:sizeof(targetPath)]) { if (error != NULL) { @@ -652,23 +652,23 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } return NO; } - + char userAndGroup[100]; int written = snprintf(userAndGroup, sizeof(userAndGroup), "%u:%u", ownerID.unsignedIntValue, groupID.unsignedIntValue); if (written < 0 || written >= 100) { return NO; // No custom error, because it's too unlikely to ever happen } - + if (![self _acquireAuthorizationWithError:error]) { return NO; } - + BOOL success = AuthorizationExecuteWithPrivilegesAndWait(_auth, "/usr/sbin/chown", kAuthorizationFlagDefaults, (char *[]){ "-R", userAndGroup, targetPath, NULL }); if (!success && error != NULL) { NSString *errorMessage = [NSString stringWithFormat:@"Failed to change owner:group %@ on %@ with authentication.", [NSString stringWithUTF8String:userAndGroup], targetURL.path.lastPathComponent]; *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: errorMessage }]; } - + return success; } @@ -686,7 +686,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } return NO; } - + char path[PATH_MAX] = {0}; if (![targetURL.path getFileSystemRepresentation:path maxLength:sizeof(path)]) { if (error != NULL) { @@ -694,28 +694,28 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } return NO; } - + if (utimes(path, NULL) == 0) { return YES; } - + if (errno != EACCES) { if (error != NULL) { *error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to update modification & access time for %@", targetURL.path.lastPathComponent] }]; } return NO; } - + if (![self _acquireAuthorizationWithError:error]) { return NO; } - - BOOL success = AuthorizationExecuteWithPrivilegesAndWait(_auth, "/usr/bin/touch", kAuthorizationFlagDefaults, (char *[]){ path, NULL }); + + BOOL success = AuthorizationExecuteWithPrivilegesAndWait(_auth, "/usr/bin/touch", kAuthorizationFlagDefaults, (char *[]){ "--", path, NULL }); if (!success && error != NULL) { NSString *errorMessage = [NSString stringWithFormat:@"Failed to update modification & access time on %@ with authentication.", targetURL.path.lastPathComponent]; *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: errorMessage }]; } - + return success; } @@ -729,7 +729,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } return NO; } - + NSURL *parentURL = [url URLByDeletingLastPathComponent]; BOOL isParentADirectory = NO; if (![self _itemExistsAtURL:parentURL isDirectory:&isParentADirectory] || !isParentADirectory) { @@ -738,19 +738,19 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } return NO; } - + NSError *createDirectoryError = nil; if ([_fileManager createDirectoryAtURL:url withIntermediateDirectories:NO attributes:nil error:&createDirectoryError]) { return YES; } - + if (!NS_HAS_PERMISSION_ERROR(createDirectoryError)) { if (error != NULL) { *error = createDirectoryError; } return NO; } - + char path[PATH_MAX] = {0}; if (![url.path getFileSystemRepresentation:path maxLength:sizeof(path)]) { if (error != NULL) { @@ -758,12 +758,12 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } return NO; } - + if (![self _acquireAuthorizationWithError:error]) { return NO; } - - BOOL success = AuthorizationExecuteWithPrivilegesAndWait(_auth, "/bin/mkdir", kAuthorizationFlagDefaults, (char *[]){ path, NULL }); + + BOOL success = AuthorizationExecuteWithPrivilegesAndWait(_auth, "/bin/mkdir", kAuthorizationFlagDefaults, (char *[]){ "--", path, NULL }); if (!success && error != NULL) { NSString *errorMessage = [NSString stringWithFormat:@"Failed to make directory %@ with authentication.", url.path.lastPathComponent]; *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: errorMessage }]; @@ -775,20 +775,20 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { { NSError *tempError = nil; NSURL *tempURL = [_fileManager URLForDirectory:NSItemReplacementDirectory inDomain:NSUserDomainMask appropriateForURL:directoryURL create:YES error:&tempError]; - + if (tempURL != nil) { return tempURL; } - + // It is pretty unlikely in my testing we will get here, but just in case we do, we should create a directory inside // the directory pointed by directoryURL, using the preferredName - + NSURL *desiredURL = [directoryURL URLByAppendingPathComponent:preferredName]; NSUInteger tagIndex = 1; while ([self _itemExistsAtURL:desiredURL] && tagIndex <= 9999) { desiredURL = [directoryURL URLByAppendingPathComponent:[preferredName stringByAppendingFormat:@" (%lu)", (unsigned long)++tagIndex]]; } - + return [self _makeDirectoryAtURL:desiredURL error:error] ? desiredURL : nil; } @@ -800,23 +800,23 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } return NO; } - + NSError *removeError = nil; if ([_fileManager removeItemAtURL:url error:&removeError]) { return YES; } - + if (!NS_HAS_PERMISSION_ERROR(removeError)) { if (error != NULL) { *error = removeError; } return NO; } - + if (![self _acquireAuthorizationWithError:error]) { return NO; } - + char path[PATH_MAX] = {0}; if (![url.path getFileSystemRepresentation:path maxLength:sizeof(path)]) { if (error != NULL) { @@ -824,8 +824,8 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } return NO; } - - BOOL success = AuthorizationExecuteWithPrivilegesAndWait(_auth, "/bin/rm", kAuthorizationFlagDefaults, (char *[]){ "-rf", path, NULL }); + + BOOL success = AuthorizationExecuteWithPrivilegesAndWait(_auth, "/bin/rm", kAuthorizationFlagDefaults, (char *[]){ "-rf", "--", path, NULL }); if (!success && error != NULL) { *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to remove %@ with authentication.", url.path.lastPathComponent] }]; } @@ -840,7 +840,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } return NO; } - + NSURL *trashURL = nil; BOOL canUseNewTrashAPI = YES; #if __MAC_OS_X_VERSION_MIN_REQUIRED < 1080 @@ -852,18 +852,18 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } } #endif - + if (canUseNewTrashAPI) { trashURL = [_fileManager URLForDirectory:NSTrashDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil]; } - + if (trashURL == nil) { if (error != NULL) { *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileNoSuchFileError userInfo:@{ NSLocalizedDescriptionKey: @"Failed to locate the user's trash folder." }]; } return NO; } - + // In the rare worst case scenario, our temporary directory will be labeled incomplete and be in the user's trash directory, // indicating that whatever inside of there is not yet completely moved. // Regardless, we want the item to be in our Volume before we try moving it to the trash @@ -872,7 +872,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { if (tempDirectory == nil) { return NO; } - + NSString *urlLastPathComponent = url.lastPathComponent; NSURL *tempItemURL = [tempDirectory URLByAppendingPathComponent:urlLastPathComponent]; if (![self moveItemAtURL:url toURL:tempItemURL error:error]) { @@ -881,15 +881,15 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { [self removeItemAtURL:tempDirectory error:NULL]; return NO; } - + if (![self changeOwnerAndGroupOfItemAtRootURL:tempItemURL toMatchURL:trashURL error:error]) { // Removing the item inside of the temp directory is better than trying to move the item to the trash with incorrect ownership [self removeItemAtURL:tempDirectory error:NULL]; return NO; } - + // If we get here, we should be able to trash the item normally without authentication - + BOOL success = NO; #if __MAC_OS_X_VERSION_MIN_REQUIRED < 1080 if (!canUseNewTrashAPI) { @@ -900,7 +900,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } } #endif - + if (canUseNewTrashAPI) { NSError *trashError = nil; success = [_fileManager trashItemAtURL:tempItemURL resultingItemURL:NULL error:&trashError]; @@ -908,9 +908,9 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { *error = trashError; } } - + [self removeItemAtURL:tempDirectory error:NULL]; - + return success; }