Compare commits

...
30 Commits
Author SHA1 Message Date
Kornel 0bc66ab011 Merge pull request #657 from zorgiepoo/fileop-copy
File Operations Copy Fixes
2015-11-08 23:18:51 +00:00
Zorg c98ef7c614 Merge branch 'master' into fileop-copy 2015-11-08 17:03:19 -05:00
Zorg 896a01cd40 Remove compiled classes in the Test App that exist in the framework
This removes run-time warnings that SUFileManager and SUOperatingSystem are
defined in both the test app and the framework, and which one
is used is undefined.
2015-11-08 17:00:27 -05:00
Kornel 93a5228f5b Merge pull request #669 from AutoScout24/x2on-patch-1
Fix framework imports
2015-10-27 11:10:38 +00:00
Felix Schulze 124d9a901f Fix framework imports
Fixes #668
2015-10-27 11:26:25 +01:00
Zorg c848882778 Merge branch 'master' into fileop-copy 2015-10-24 21:57:07 -04:00
Kornel 374b8d6195 Merge pull request #655 from kainjow/webserver
Replace use of Python with built-in web server
2015-10-23 16:25:35 +01:00
Kornel 27c1b0f045 Merge pull request #650 from zorgiepoo/binarydelta-no-write-perm
Fix segfault when patch path has insufficient write permissions
2015-10-23 00:35:06 +01:00
Kornel Lesiński 154aa1b0db Subclassing fixes #661 2015-10-22 13:55:01 +01:00
Kornel 658e5fcb9f Merge pull request #661 from osolo/misc-fixes
Misc fixes
2015-10-21 16:41:16 +02:00
Oz Solomon 292ba01dbf Removed invalid deployment target version 2015-10-21 09:39:26 -04:00
Oz Solomon ff7966d96a Fix: sparkleBundle not calculated correctly when SUUpdater is subclassed by a class in a different bundle. 2015-10-21 09:39:14 -04:00
Zorg 9cf7437392 Update explanation of why copyfile() is insufficient 2015-10-17 14:47:16 -04:00
Zorg 9f1884f100 Add compile sources to Test App to fix building issues 2015-10-10 18:23:45 -04:00
Zorg 8a208ce520 Move OS methods from SUHost to SUOperatingSystem
This reduces the bloat that BinaryDelta and SUFileManager need to include
2015-10-10 18:14:06 -04:00
Zorg c850146ef6 Forgot to update SUFileManager constuctor in Test App 2015-10-10 18:10:24 -04:00
Zorg ccf4f81ea0 Use SUFileManager for copyTree in BinaryDelta
Fixes app not being able to be patched because the original app
was on a network mounted volume
2015-10-10 17:58:44 -04:00
Zorg 3c957096c6 Use class constructor instead of an init method for SUFileManager
I think it's more natural this way
2015-10-10 17:42:27 -04:00
Zorg bc5ad0d919 Merge branch 'master' into binarydelta-no-write-perm 2015-10-10 00:38:38 -04:00
Zorg 9d06f5bc4d Meant to use NSFileNoSuchFileError here 2015-10-10 00:28:12 -04:00
Zorg 6818d1f180 Verify existence of destination parent directory for moving/copying 2015-10-10 00:12:58 -04:00
Zorg ee72ec3dab Fix issues with copying files from different mounted drives
The move operation now does an explict copy & remove.

We also copy items using FSCopyObjectSync due to issues
existing in copyfile (and NSFileManager).

Both of these fix bugs in some cases where items cannot be moved
from one network drive to another. In my testing before this patch,
I was unable to get the test application to launch and was unable
to move the old installation to the trash.
2015-10-09 23:58:23 -04:00
Zorg 9b74309eb5 Make allowsAuthorization apply to all of SUFileManager's methods 2015-10-09 17:49:46 -04:00
Kevin Wojniak 948eccb169 Use properties to avoid having to disable warning for entire file 2015-10-09 09:37:25 -07:00
Kevin Wojniak ff342f1e5b Use nil instead of 0. Fix pointer style. 2015-10-09 09:22:20 -07:00
Kornel a7af6fb82d Merge pull request #654 from zorgiepoo/nstask-string
Fix Test App crashing on systems earlier than 10.9
2015-10-09 16:02:48 +01:00
Zorg d7e3b01bd6 Merge branch 'master' into binarydelta-no-write-perm 2015-10-09 08:26:22 -04:00
Kevin Wojniak 117716da9e Replace use of Python with built-in web server
See issue #637
2015-10-08 20:41:26 -07:00
Zorg 17da7b5fb8 Fix Test App crashing on systems earlier than 10.9
Passing a NSURL instance to a NSTask's arguments calls
-[NSURL fileSystemRepresentation] which is only available on 10.9+
2015-10-08 22:49:03 -04:00
Zorg 21e4cc42cc Fix segfault when patch path has insufficient write permissions 2015-10-07 18:44:14 -04:00
21 changed files with 675 additions and 110 deletions

No files matched your search

+24
View File
@@ -170,6 +170,13 @@
721CF1AB1AD764EB00D9AC09 /* libbz2.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 5D06E8FB0FD68D61005AE3F6 /* libbz2.dylib */; };
7223E7631AD1AEFF008E3161 /* sais.c in Sources */ = {isa = PBXBuildFile; fileRef = 7223E7611AD1AEFF008E3161 /* sais.c */; };
7268AC631AD634C200C3E0C1 /* SUBinaryDeltaCreate.m in Sources */ = {isa = PBXBuildFile; fileRef = 7268AC621AD634C200C3E0C1 /* SUBinaryDeltaCreate.m */; };
726F2CDE1BC9BE5B001971A4 /* SUFileManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 7275F9C01B5F1F2900B1D19E /* SUFileManager.m */; };
726F2CE51BC9C33D001971A4 /* SUOperatingSystem.h in Headers */ = {isa = PBXBuildFile; fileRef = 726F2CE31BC9C33D001971A4 /* SUOperatingSystem.h */; };
726F2CE61BC9C33D001971A4 /* SUOperatingSystem.m in Sources */ = {isa = PBXBuildFile; fileRef = 726F2CE41BC9C33D001971A4 /* SUOperatingSystem.m */; };
726F2CE71BC9C3E2001971A4 /* SUOperatingSystem.m in Sources */ = {isa = PBXBuildFile; fileRef = 726F2CE41BC9C33D001971A4 /* SUOperatingSystem.m */; };
726F2CE81BC9C48F001971A4 /* SUConstants.m in Sources */ = {isa = PBXBuildFile; fileRef = 61299A5F09CA6EB100B7442F /* SUConstants.m */; };
726F2CE91BC9C499001971A4 /* SUOperatingSystem.m in Sources */ = {isa = PBXBuildFile; fileRef = 726F2CE41BC9C33D001971A4 /* SUOperatingSystem.m */; };
726F2CEB1BC9C733001971A4 /* SUConstants.m in Sources */ = {isa = PBXBuildFile; fileRef = 61299A5F09CA6EB100B7442F /* SUConstants.m */; };
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 */; };
@@ -190,6 +197,7 @@
767B61AC1972D488004E0C3C /* SUGuidedPackageInstaller.h in Headers */ = {isa = PBXBuildFile; fileRef = 767B61AA1972D488004E0C3C /* SUGuidedPackageInstaller.h */; };
767B61AD1972D488004E0C3C /* SUGuidedPackageInstaller.m in Sources */ = {isa = PBXBuildFile; fileRef = 767B61AB1972D488004E0C3C /* SUGuidedPackageInstaller.m */; };
767B61AE1972D488004E0C3C /* SUGuidedPackageInstaller.m in Sources */ = {isa = PBXBuildFile; fileRef = 767B61AB1972D488004E0C3C /* SUGuidedPackageInstaller.m */; };
A5BF4F1D1BC7668B007A052A /* SUTestWebServer.m in Sources */ = {isa = PBXBuildFile; fileRef = A5BF4F1C1BC7668B007A052A /* SUTestWebServer.m */; };
F8761EB11ADC5068000C9034 /* SUCodeSigningVerifierTest.m in Sources */ = {isa = PBXBuildFile; fileRef = F8761EB01ADC5068000C9034 /* SUCodeSigningVerifierTest.m */; };
F8761EB31ADC50EB000C9034 /* SparkleTestCodeSignApp.zip in Resources */ = {isa = PBXBuildFile; fileRef = F8761EB21ADC50EB000C9034 /* SparkleTestCodeSignApp.zip */; };
F8761EB61ADC5E7A000C9034 /* SUCodeSigningVerifier.m in Sources */ = {isa = PBXBuildFile; fileRef = 61B078CD15A5FB6100600039 /* SUCodeSigningVerifier.m */; };
@@ -569,6 +577,8 @@
7223E7621AD1AEFF008E3161 /* sais.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = sais.h; sourceTree = "<group>"; };
7268AC621AD634C200C3E0C1 /* SUBinaryDeltaCreate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SUBinaryDeltaCreate.m; sourceTree = "<group>"; };
7268AC641AD634E400C3E0C1 /* SUBinaryDeltaCreate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUBinaryDeltaCreate.h; sourceTree = "<group>"; };
726F2CE31BC9C33D001971A4 /* SUOperatingSystem.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUOperatingSystem.h; sourceTree = "<group>"; };
726F2CE41BC9C33D001971A4 /* SUOperatingSystem.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SUOperatingSystem.m; sourceTree = "<group>"; };
7275F9BF1B5F1F2900B1D19E /* SUFileManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUFileManager.h; sourceTree = "<group>"; };
7275F9C01B5F1F2900B1D19E /* SUFileManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SUFileManager.m; sourceTree = "<group>"; };
72A4A23F1BB6567D00E7820D /* SUFileManagerTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SUFileManagerTest.swift; sourceTree = "<group>"; };
@@ -590,6 +600,8 @@
767B61AB1972D488004E0C3C /* SUGuidedPackageInstaller.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SUGuidedPackageInstaller.m; sourceTree = "<group>"; };
8DC2EF5A0486A6940098B216 /* Sparkle-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "Sparkle-Info.plist"; sourceTree = "<group>"; };
8DC2EF5B0486A6940098B216 /* Sparkle.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Sparkle.framework; sourceTree = BUILT_PRODUCTS_DIR; };
A5BF4F1B1BC7668B007A052A /* SUTestWebServer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUTestWebServer.h; sourceTree = "<group>"; };
A5BF4F1C1BC7668B007A052A /* SUTestWebServer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SUTestWebServer.m; sourceTree = "<group>"; };
F8761EB01ADC5068000C9034 /* SUCodeSigningVerifierTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SUCodeSigningVerifierTest.m; sourceTree = "<group>"; };
F8761EB21ADC50EB000C9034 /* SparkleTestCodeSignApp.zip */ = {isa = PBXFileReference; lastKnownFileType = archive.zip; path = SparkleTestCodeSignApp.zip; sourceTree = "<group>"; };
FA1941CA0D94A70100DD942E /* ConfigFrameworkDebug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = ConfigFrameworkDebug.xcconfig; sourceTree = "<group>"; };
@@ -954,6 +966,8 @@
14652F8319A9759F00959E44 /* SUExport.h */,
61EF67580E25C5B400F754E0 /* SUHost.h */,
61EF67550E25B58D00F754E0 /* SUHost.m */,
726F2CE31BC9C33D001971A4 /* SUOperatingSystem.h */,
726F2CE41BC9C33D001971A4 /* SUOperatingSystem.m */,
55C14F04136EF6DB00649790 /* SULog.h */,
55C14F05136EF6DB00649790 /* SULog.m */,
);
@@ -973,6 +987,8 @@
72E45CF21B640CDD005C701A /* SUTestApplicationDelegate.m */,
72E45CF41B640DAE005C701A /* SUUpdateSettingsWindowController.h */,
72E45CF51B640DAE005C701A /* SUUpdateSettingsWindowController.m */,
A5BF4F1B1BC7668B007A052A /* SUTestWebServer.h */,
A5BF4F1C1BC7668B007A052A /* SUTestWebServer.m */,
72E45CF61B640DAE005C701A /* SUUpdateSettingsWindowController.xib */,
72E45CFD1B641D0D005C701A /* test_app_only_dsa_priv_dont_ever_do_this_for_real.pem */,
14732BBF1960F0AC00593899 /* test_app_only_dsa_pub.pem */,
@@ -1085,6 +1101,7 @@
61EF67590E25C5B400F754E0 /* SUHost.h in Headers */,
618FA5010DAE88B40026945C /* SUInstaller.h in Headers */,
55C14F06136EF6DB00649790 /* SULog.h in Headers */,
726F2CE51BC9C33D001971A4 /* SUOperatingSystem.h in Headers */,
618FA5220DAE8E8A0026945C /* SUPackageInstaller.h in Headers */,
6102FE460E077FCE00F85D09 /* SUPipedUnarchiver.h in Headers */,
618FA5050DAE8AB80026945C /* SUPlainInstaller.h in Headers */,
@@ -1452,6 +1469,7 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
726F2CE71BC9C3E2001971A4 /* SUOperatingSystem.m in Sources */,
55C14BD4136EEFCE00649790 /* Autoupdate.m in Sources */,
F8761EB61ADC5E7A000C9034 /* SUCodeSigningVerifier.m in Sources */,
55C14F00136EF6B700649790 /* SUConstants.m in Sources */,
@@ -1473,6 +1491,9 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
726F2CE91BC9C499001971A4 /* SUOperatingSystem.m in Sources */,
726F2CE81BC9C48F001971A4 /* SUConstants.m in Sources */,
726F2CDE1BC9BE5B001971A4 /* SUFileManager.m in Sources */,
5D06E8E90FD68CDB005AE3F6 /* bsdiff.c in Sources */,
14652F7E19A9728A00959E44 /* bspatch.c in Sources */,
7223E7631AD1AEFF008E3161 /* sais.c in Sources */,
@@ -1506,7 +1527,9 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
726F2CEB1BC9C733001971A4 /* SUConstants.m in Sources */,
61B5F93009C4CFDC00B25A18 /* main.m in Sources */,
A5BF4F1D1BC7668B007A052A /* SUTestWebServer.m in Sources */,
72E45CF31B640CDD005C701A /* SUTestApplicationDelegate.m in Sources */,
72E45CF71B640DAE005C701A /* SUUpdateSettingsWindowController.m in Sources */,
);
@@ -1540,6 +1563,7 @@
618FA5060DAE8AB80026945C /* SUPlainInstaller.m in Sources */,
6101347C0DD2541A0049ACDF /* SUProbingUpdateDriver.m in Sources */,
61B93C0A0DD112FF00DCD2F8 /* SUScheduledUpdateDriver.m in Sources */,
726F2CE61BC9C33D001971A4 /* SUOperatingSystem.m in Sources */,
61A225A50D1C4AC000430CCD /* SUStandardVersionComparator.m in Sources */,
6196CFFA09C72149000DC222 /* SUStatusController.m in Sources */,
61A2279D0D1CEE7600430CCD /* SUSystemProfiler.m in Sources */,
+9 -5
View File
@@ -9,6 +9,7 @@
#import "SUBasicUpdateDriver.h"
#import "SUHost.h"
#import "SUOperatingSystem.h"
#import "SUDSAVerifier.h"
#import "SUInstaller.h"
#import "SUStandardVersionComparator.h"
@@ -96,10 +97,10 @@
// Check minimum and maximum System Version
if ([ui minimumSystemVersion] != nil && ![[ui minimumSystemVersion] isEqualToString:@""]) {
minimumVersionOK = [[SUStandardVersionComparator defaultComparator] compareVersion:[ui minimumSystemVersion] toVersion:[SUHost systemVersionString]] != NSOrderedDescending;
minimumVersionOK = [[SUStandardVersionComparator defaultComparator] compareVersion:[ui minimumSystemVersion] toVersion:[SUOperatingSystem systemVersionString]] != NSOrderedDescending;
}
if ([ui maximumSystemVersion] != nil && ![[ui maximumSystemVersion] isEqualToString:@""]) {
maximumVersionOK = [[SUStandardVersionComparator defaultComparator] compareVersion:[ui maximumSystemVersion] toVersion:[SUHost systemVersionString]] != NSOrderedAscending;
maximumVersionOK = [[SUStandardVersionComparator defaultComparator] compareVersion:[ui maximumSystemVersion] toVersion:[SUOperatingSystem systemVersionString]] != NSOrderedAscending;
}
return minimumVersionOK && maximumVersionOK;
@@ -452,16 +453,19 @@
if (relaunchPathToCopy != nil) {
NSString *targetPath = [self.host.appCachePath stringByAppendingPathComponent:[relaunchPathToCopy lastPathComponent]];
NSFileManager *fileManager = [[NSFileManager alloc] init];
SUFileManager *fileManager = [SUFileManager fileManagerAllowingAuthorization:NO];
NSError *error = nil;
NSURL *relaunchURLToCopy = [NSURL fileURLWithPath:relaunchPathToCopy];
NSURL *targetURL = [NSURL fileURLWithPath:targetPath];
// We only need to run our copy of the app by spawning a task
// Since we are copying the app to a directory that is write-accessible, we don't need to muck with owner/group IDs
if ([self preparePathForRelaunchTool:targetPath error:&error] && [fileManager copyItemAtPath:relaunchPathToCopy toPath:targetPath error:&error]) {
if ([self preparePathForRelaunchTool:targetPath error:&error] && [fileManager copyItemAtURL:relaunchURLToCopy toURL:targetURL error:&error]) {
// We probably don't need to release the quarantine, but we'll do it just in case it's necessary.
// Perhaps in a sandboxed environment this matters more. Note that this may not be a fatal error.
NSError *quarantineError = nil;
if (![[[SUFileManager alloc] init] releaseItemFromQuarantineWithoutAuthenticationAtRootURL:[NSURL fileURLWithPath:targetPath] error:&quarantineError]) {
if (![fileManager releaseItemFromQuarantineAtRootURL:targetURL error:&quarantineError]) {
SULog(@"Failed to release quarantine on %@ with error %@", targetPath, quarantineError);
}
self.relaunchPath = targetPath;
+2 -1
View File
@@ -7,6 +7,7 @@
//
#include "SUBinaryDeltaCommon.h"
#import "SUFileManager.h"
#include <CommonCrypto/CommonDigest.h>
#include <Foundation/Foundation.h>
#include <fcntl.h>
@@ -220,7 +221,7 @@ BOOL removeTree(NSString *path)
BOOL copyTree(NSString *source, NSString *dest)
{
return [[NSFileManager defaultManager] copyItemAtPath:source toPath:dest error:nil];
return [[SUFileManager fileManagerAllowingAuthorization:NO] copyItemAtURL:[NSURL fileURLWithPath:source] toURL:[NSURL fileURLWithPath:dest] error:NULL];
}
BOOL modifyPermissions(NSString *path, mode_t desiredPermissions)
+10
View File
@@ -439,6 +439,16 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
NSString *temporaryFile = temporaryPatchFile(patchFile);
xar_t x = xar_open([temporaryFile fileSystemRepresentation], WRITE);
if (!x) {
if (verbose) {
fprintf(stderr, "\n");
}
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileWriteUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to write to %@", temporaryFile] }];
}
return NO;
}
xar_opt_set(x, XAR_OPT_COMPRESSION, "bzip2");
xar_subdoc_t attributes = xar_subdoc_new(x, BINARY_DELTA_ATTRIBUTES_KEY);
+22 -6
View File
@@ -9,12 +9,22 @@
#import <Foundation/Foundation.h>
/**
* A class used for performing file operations that may also perform authentication if permission is denied when trying to
* A class used for performing file operations that may also perform authentication if allowed and if permission is denied when trying to
* perform them normally as the running user. All operations on this class may be used on thread other than the main thread.
* This class provides basic file operations and stays away from including much application-level logic.
*/
@interface SUFileManager : NSObject
/**
* Creates a file manager that allows or disallows authorizing for file operations
* @param allowsAuthorization Specifies whether operations invoked on this instance are allowed to acquire authorization in order
* to perform file operations when read or write access is denied
* @return A new file manager instance
*
* This method just creates the file manager. It doesn't acquire authorization immediately if allowsAuthorization is YES
*/
+ (instancetype)fileManagerAllowingAuthorization:(BOOL)allowsAuthorization;
/**
* Creates a temporary directory on the same volume as a provided URL
* @param preferredName A name that may be used when creating the temporary directory. Note that in the uncommon case this name is used, the temporary directory will be created inside the directory pointed by appropriateURL
@@ -39,6 +49,17 @@
*/
- (BOOL)moveItemAtURL:(NSURL *)sourceURL toURL:(NSURL *)destinationURL error:(NSError **)error;
/**
* Copies an item from a source to a destination
* @param sourceURL A URL pointing to the item to move. The item at this URL must exist.
* @param destinationURL A URL pointing to the destination the item will be moved at. An item must not already exist at this URL.
* @param error If an error occurs, upon returns contains an NSError object that describes the problem. If you are not interested in possible errors, you may pass in NULL.
* @return YES if the item was copied successfully, otherwise NO along with a populated error object
*
* This is not an atomic operation.
*/
- (BOOL)copyItemAtURL:(NSURL *)sourceURL toURL:(NSURL *)destinationURL error:(NSError **)error;
/**
* Moves an item at a specified URL to the running user's trash directory
* @param url A URL pointing to the item to move to the trash. The item at this URL must exist.
@@ -110,9 +131,4 @@
*/
- (BOOL)releaseItemFromQuarantineAtRootURL:(NSURL *)rootURL error:(NSError **)error;
/**
* Behaves as -releaseItemFromQuarantineAtRootURL:error: does, except without the capability of authenticating when permission is denied
*/
- (BOOL)releaseItemFromQuarantineWithoutAuthenticationAtRootURL:(NSURL *)rootURL error:(NSError **)error;
@end
+193 -20
View File
@@ -7,7 +7,7 @@
//
#import "SUFileManager.h"
#import "SUHost.h"
#import "SUOperatingSystem.h"
#include <sys/xattr.h>
#include <sys/errno.h>
@@ -52,17 +52,25 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza
{
AuthorizationRef _auth;
NSFileManager *_fileManager;
BOOL _allowsAuthorization;
}
- (id)init
- (instancetype)initAllowingAuthorization:(BOOL)allowsAuthorization
{
self = [super init];
if (self != nil) {
_fileManager = [[NSFileManager alloc] init];
_allowsAuthorization = allowsAuthorization;
}
return self;
}
+ (instancetype)fileManagerAllowingAuthorization:(BOOL)allowsAuthorization
{
return [[self alloc] initAllowingAuthorization:allowsAuthorization];
}
// Acquires an authorization reference which is intended to be used for future authorized file operations
- (BOOL)_acquireAuthorizationWithError:(NSError *__autoreleasing *)error
{
@@ -71,6 +79,13 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza
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) {
@@ -177,7 +192,7 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza
return success;
}
- (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 withQuarantineRetrieval:(BOOL (^)(NSURL *))quarantineRetrieval quarantineRemoval:(BOOL (^)(NSURL *, NSError * __autoreleasing *))quarantineRemoval isAccessError:(BOOL (^)(NSError *))isAccessError error:(NSError * __autoreleasing *)error
{
if (![self _itemExistsAtURL:rootURL]) {
if (error != NULL) {
@@ -195,7 +210,7 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza
if (quarantineRemoval(fileURL, &removalError)) {
removedQuarantine = YES;
} else {
if (allowsAuthentication && isAccessError(removalError)) {
if (isAccessError(removalError)) {
removedQuarantine = [self _removeXAttrWithAuthentication:SUAppleQuarantineIdentifier fromRootURL:rootURL error:error];
attemptedAuthentication = YES;
} else {
@@ -269,14 +284,13 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza
// 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
- (BOOL)releaseItemFromQuarantineAtRootURL:(NSURL *)rootURL error:(NSError *__autoreleasing *)error
{
static const int removeXAttrOptions = XATTR_NOFOLLOW;
return
[self
_releaseItemFromQuarantineAtRootURL:rootURL
allowingAuthentication:allowsAuthentication
withQuarantineRetrieval:^BOOL(NSURL *fileURL) {
return ([self _getXAttr:SUAppleQuarantineIdentifier fromFile:fileURL.path options:removeXAttrOptions] >= 0);
}
@@ -293,32 +307,191 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza
error:error];
}
- (BOOL)releaseItemFromQuarantineAtRootURL:(NSURL *)rootURL error:(NSError * __autoreleasing *)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];
}
- (BOOL)moveItemAtURL:(NSURL *)sourceURL toURL:(NSURL *)destinationURL error:(NSError *__autoreleasing *)error
/*
* Copies an item from one location to another
* This intentionally does *not* use copyfile() or any API that uses it such as NSFileManager's copy item method
* This is because copyfile() can fail to copy symbolic links from one network mount to another, which will affect copying apps
* This failure occurs because the system may think symbolic links on a SMB mount are zero bytes in size
* For more info, see bug reports at http://openradar.appspot.com/radar?id=4925873463492608
* and http://openradar.appspot.com/radar?id=5024037222744064
*/
- (BOOL)copyItemAtURL:(NSURL *)sourceURL toURL:(NSURL *)destinationURL error:(NSError * __autoreleasing *)error
{
if (![self _itemExistsAtURL:sourceURL]) {
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileNoSuchFileError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Source file to move (%@) does not exist.", sourceURL.path.lastPathComponent] }];
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileNoSuchFileError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Source file to copy (%@) does not exist.", sourceURL.lastPathComponent] }];
}
return NO;
}
if (![self _itemExistsAtURL:destinationURL.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 move (%@) already exists.", destinationURL.path.lastPathComponent] }];
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileWriteFileExistsError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Destination file to copy to (%@) already exists.", destinationURL.lastPathComponent] }];
}
return NO;
}
char sourcePath[PATH_MAX] = {0};
if (![sourceURL.path getFileSystemRepresentation:sourcePath maxLength:sizeof(sourcePath)]) {
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"File to copy (%@) cannot be represented as a valid file name.", sourceURL.lastPathComponent] }];
}
return NO;
}
FSRef sourceRef;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
OSStatus makeSourceResult = FSPathMakeRefWithOptions((const UInt8 *)sourcePath, kFSPathMakeRefDoNotFollowLeafSymlink, &sourceRef, NULL);
#pragma clang diagnostic pop
if (makeSourceResult != noErr) {
if (error != NULL) {
*error = [NSError errorWithDomain:NSOSStatusErrorDomain code:makeSourceResult userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to create file system reference for source %@.", sourceURL.lastPathComponent] }];
}
return NO;
}
char destinationParentPath[PATH_MAX] = {0};
if (![destinationURL.URLByDeletingLastPathComponent.path getFileSystemRepresentation:destinationParentPath maxLength:sizeof(destinationParentPath)]) {
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Destination parent directory to copy file into (%@) cannot be represented as a valid file name.", destinationURL.URLByDeletingLastPathComponent.lastPathComponent] }];
}
return NO;
}
FSRef destinationParentRef;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
OSStatus makeDestinationParentResult = FSPathMakeRefWithOptions((const UInt8 *)destinationParentPath, kFSPathMakeRefDoNotFollowLeafSymlink, &destinationParentRef, NULL);
#pragma clang diagnostic pop
if (makeDestinationParentResult != noErr) {
if (error != NULL) {
*error = [NSError errorWithDomain:NSOSStatusErrorDomain code:makeDestinationParentResult userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to create file system reference for parent directory %@.", destinationURL.URLByDeletingLastPathComponent.lastPathComponent] }];
}
return NO;
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
OSStatus copyResult = FSCopyObjectSync(&sourceRef, &destinationParentRef, (__bridge CFStringRef)(destinationURL.lastPathComponent), NULL, kFSFileOperationDefaultOptions);
#pragma clang diagnostic pop
if (copyResult == noErr) {
return YES;
}
if (copyResult != permErr) {
if (error != NULL) {
*error = [NSError errorWithDomain:NSOSStatusErrorDomain code:copyResult userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to copy file (%@)", sourceURL.lastPathComponent] }];
}
return NO;
}
if (![self _acquireAuthorizationWithError:error]) {
return NO;
}
char destinationPath[PATH_MAX] = {0};
if (![destinationURL.path getFileSystemRepresentation:destinationPath maxLength:sizeof(destinationPath)]) {
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Destination to copy file to (%@) cannot be represented as a valid file name.", destinationURL.lastPathComponent] }];
}
return NO;
}
if (!AuthorizationExecuteWithPrivilegesAndWait(_auth, "/bin/cp", kAuthorizationFlagDefaults, (char *[]){ "-Rf", sourcePath, destinationPath, NULL })) {
if (error != NULL) {
NSString *errorMessage = [NSString stringWithFormat:@"Failed to perform authenticated file copy for %@.", sourceURL.lastPathComponent];
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:errorMessage }];
}
return NO;
}
return YES;
}
/*
* Retrieves the volume ID that a particular url resides on
* The url must point to a file that exists
* There is no cocoa equivalent for obtaining the volume ID
* Although NSURLVolumeURLForRemountingKey exists as a resource key for NSURL,
* that will not return a URL if the mount is not re-mountable and I otherwise don't trust the API
*/
- (BOOL)_getVolumeID:(FSVolumeRefNum *)volumeID ofItemAtURL:(NSURL *)url
{
char path[PATH_MAX] = {0};
if (![url.path getFileSystemRepresentation:path maxLength:sizeof(path)]) {
return NO;
}
FSRef pathRef;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
if (FSPathMakeRefWithOptions((const UInt8*)path, kFSPathMakeRefDoNotFollowLeafSymlink, &pathRef, NULL) != noErr) {
#pragma clang diagnostic pop
return NO;
}
FSCatalogInfo catalogInfo;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
OSErr catalogError = FSGetCatalogInfo(&pathRef, kFSCatInfoVolume, &catalogInfo, NULL, NULL, NULL);
#pragma clang diagnostic pop
if (catalogError != noErr) {
return NO;
}
if (volumeID != NULL) {
*volumeID = catalogInfo.volume;
}
return YES;
}
- (BOOL)moveItemAtURL:(NSURL *)sourceURL toURL:(NSURL *)destinationURL error:(NSError *__autoreleasing *)error
{
if (![self _itemExistsAtURL:sourceURL]) {
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileNoSuchFileError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Source file to move (%@) does not exist.", sourceURL.lastPathComponent] }];
}
return NO;
}
if (![self _itemExistsAtURL:destinationURL.URLByDeletingLastPathComponent]) {
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] }];
}
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];
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;
@@ -674,7 +847,7 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza
NSURL *trashURL = nil;
BOOL canUseNewTrashAPI = YES;
#if __MAC_OS_X_VERSION_MIN_REQUIRED < 1080
canUseNewTrashAPI = [SUHost isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){10, 8, 0}];
canUseNewTrashAPI = [SUOperatingSystem isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){10, 8, 0}];
if (!canUseNewTrashAPI) {
FSRef trashRef;
if (FSFindFolder(kUserDomain, kTrashFolderType, kDontCreateFolder, &trashRef) == noErr) {
-4
View File
@@ -23,10 +23,6 @@ typedef struct {
@property (strong, readonly) NSBundle *bundle;
+ (NSOperatingSystemVersion)operatingSystemVersion;
+ (BOOL)isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion)version;
+ (NSString *)systemVersionString;
- (instancetype)initWithBundle:(NSBundle *)aBundle;
@property (readonly, copy) NSString *bundlePath;
@property (readonly) BOOL allowsAutomaticUpdates;
-39
View File
@@ -284,43 +284,4 @@
return [self objectForUserDefaultsKey:key] ? [self boolForUserDefaultsKey:key] : [self boolForInfoDictionaryKey:key];
}
+ (NSOperatingSystemVersion)operatingSystemVersion
{
#if __MAC_OS_X_VERSION_MIN_REQUIRED < 101000
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wselector"
// Xcode 5.1.1: operatingSystemVersion is clearly declared, must warn due to a compiler bug?
if (![NSProcessInfo instancesRespondToSelector:@selector(operatingSystemVersion)])
#pragma clang diagnostic pop
{
NSOperatingSystemVersion version = { 0, 0, 0 };
NSURL *coreServices = [[NSFileManager defaultManager] URLForDirectory:NSCoreServiceDirectory inDomain:NSSystemDomainMask appropriateForURL:nil create:NO error:nil];
NSArray *components = [[NSDictionary dictionaryWithContentsOfURL:[coreServices URLByAppendingPathComponent:@"SystemVersion.plist"]][@"ProductVersion"] componentsSeparatedByString:@"."];
version.majorVersion = components.count > 0 ? [components[0] integerValue] : 0;
version.minorVersion = components.count > 1 ? [components[1] integerValue] : 0;
version.patchVersion = components.count > 2 ? [components[2] integerValue] : 0;
return version;
}
#endif
return [[NSProcessInfo processInfo] operatingSystemVersion];
}
+ (BOOL)isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion)version
{
const NSOperatingSystemVersion systemVersion = self.operatingSystemVersion;
if (systemVersion.majorVersion == version.majorVersion) {
if (systemVersion.minorVersion == version.minorVersion) {
return systemVersion.patchVersion >= version.patchVersion;
}
return systemVersion.minorVersion >= version.minorVersion;
}
return systemVersion.majorVersion >= version.majorVersion;
}
+ (NSString *)systemVersionString
{
NSOperatingSystemVersion version = self.operatingSystemVersion;
return [NSString stringWithFormat:@"%ld.%ld.%ld", (long)version.majorVersion, (long)version.minorVersion, (long)version.patchVersion];
}
@end
+16
View File
@@ -0,0 +1,16 @@
//
// SUOperatingSystem.h
// Sparkle
//
// Copyright © 2015 Sparkle Project. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface SUOperatingSystem : NSObject
+ (NSOperatingSystemVersion)operatingSystemVersion;
+ (BOOL)isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion)version;
+ (NSString *)systemVersionString;
@end
+51
View File
@@ -0,0 +1,51 @@
//
// SUOperatingSystem.m
// Sparkle
//
// Copyright © 2015 Sparkle Project. All rights reserved.
//
#import "SUOperatingSystem.h"
@implementation SUOperatingSystem
+ (NSOperatingSystemVersion)operatingSystemVersion
{
#if __MAC_OS_X_VERSION_MIN_REQUIRED < 101000
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wselector"
// Xcode 5.1.1: operatingSystemVersion is clearly declared, must warn due to a compiler bug?
if (![NSProcessInfo instancesRespondToSelector:@selector(operatingSystemVersion)])
#pragma clang diagnostic pop
{
NSOperatingSystemVersion version = { 0, 0, 0 };
NSURL *coreServices = [[NSFileManager defaultManager] URLForDirectory:NSCoreServiceDirectory inDomain:NSSystemDomainMask appropriateForURL:nil create:NO error:nil];
NSArray *components = [[NSDictionary dictionaryWithContentsOfURL:[coreServices URLByAppendingPathComponent:@"SystemVersion.plist"]][@"ProductVersion"] componentsSeparatedByString:@"."];
version.majorVersion = components.count > 0 ? [components[0] integerValue] : 0;
version.minorVersion = components.count > 1 ? [components[1] integerValue] : 0;
version.patchVersion = components.count > 2 ? [components[2] integerValue] : 0;
return version;
}
#endif
return [[NSProcessInfo processInfo] operatingSystemVersion];
}
+ (BOOL)isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion)version
{
const NSOperatingSystemVersion systemVersion = self.operatingSystemVersion;
if (systemVersion.majorVersion == version.majorVersion) {
if (systemVersion.minorVersion == version.minorVersion) {
return systemVersion.patchVersion >= version.patchVersion;
}
return systemVersion.minorVersion >= version.minorVersion;
}
return systemVersion.majorVersion >= version.majorVersion;
}
+ (NSString *)systemVersionString
{
NSOperatingSystemVersion version = self.operatingSystemVersion;
return [NSString stringWithFormat:@"%ld.%ld.%ld", (long)version.majorVersion, (long)version.minorVersion, (long)version.patchVersion];
}
@end
+1 -1
View File
@@ -42,7 +42,7 @@
return NO;
}
SUFileManager *fileManager = [[SUFileManager alloc] init];
SUFileManager *fileManager = [SUFileManager fileManagerAllowingAuthorization:YES];
// Create a temporary directory for our new app that resides on our destination's volume
NSURL *tempNewDirectoryURL = [fileManager makeTemporaryDirectoryWithPreferredName:[installationURL.lastPathComponent.stringByDeletingPathExtension stringByAppendingString:@" (Incomplete Update)"] appropriateForDirectoryURL:installationURL.URLByDeletingLastPathComponent error:error];
+4 -2
View File
@@ -11,6 +11,7 @@
#import "SUSystemProfiler.h"
#import "SUHost.h"
#import "SUOperatingSystem.h"
#include <sys/sysctl.h>
static NSString *const SUSystemProfilerApplicationNameKey = @"appName";
@@ -37,7 +38,8 @@ static NSString *const SUSystemProfilerPreferredLanguageKey = @"lang";
- (NSDictionary *)modelTranslationTable
{
NSString *path = [[NSBundle bundleForClass:[self class]] pathForResource:@"SUModelTranslation" ofType:@"plist"];
// Use explicit class to use the correct bundle even when subclassed
NSString *path = [[NSBundle bundleForClass:[SUSystemProfiler class]] pathForResource:@"SUModelTranslation" ofType:@"plist"];
return [[NSDictionary alloc] initWithContentsOfFile:path];
}
@@ -53,7 +55,7 @@ static NSString *const SUSystemProfilerPreferredLanguageKey = @"lang";
size_t length = sizeof(value);
// OS version
NSString *currentSystemVersion = [SUHost systemVersionString];
NSString *currentSystemVersion = [SUOperatingSystem systemVersionString];
if (currentSystemVersion != nil) {
[profileArray addObject:[NSDictionary dictionaryWithObjects:@[SUSystemProfilerOperatingSystemVersionKey, @"OS Version", currentSystemVersion, currentSystemVersion] forKeys:profileDictKeys]];
}
+2 -1
View File
@@ -11,6 +11,7 @@
#import "SUUpdateAlert.h"
#import "SUUpdater_Private.h"
#import "SUHost.h"
#import "SUOperatingSystem.h"
#import "SUStatusController.h"
#import "SUConstants.h"
@@ -143,7 +144,7 @@
- (NSString *)localizedStringFromByteCount:(long long)value
{
if (![SUHost isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){10, 8, 0}]) {
if (![SUOperatingSystem isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){10, 8, 0}]) {
if (value < 1000) {
return [NSString stringWithFormat:@"%.0lf %@", value / 1.0,
SULocalizedString(@"B", @"the unit for bytes")];
+2 -1
View File
@@ -83,7 +83,8 @@ static NSString *const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefaults
self = [super init];
if (bundle == nil) bundle = [NSBundle mainBundle];
self.sparkleBundle = [NSBundle bundleForClass:[self class]];
// Use explicit class to use the correct bundle even when subclassed
self.sparkleBundle = [NSBundle bundleForClass:[SUUpdater class]];
if (!self.sparkleBundle) {
SULog(@"Error: SUUpdater can't find Sparkle.framework it belongs to");
return nil;
+7 -7
View File
@@ -14,12 +14,12 @@
// This list should include the shared headers. It doesn't matter if some of them aren't shared (unless
// there are name-space collisions) so we can list all of them to start with:
#import <Sparkle/SUAppcast.h>
#import <Sparkle/SUAppcastItem.h>
#import <Sparkle/SUStandardVersionComparator.h>
#import <Sparkle/SUUpdater.h>
#import <Sparkle/SUVersionComparisonProtocol.h>
#import <Sparkle/SUVersionDisplayProtocol.h>
#import <Sparkle/SUErrors.h>
#import "SUAppcast.h"
#import "SUAppcastItem.h"
#import "SUStandardVersionComparator.h"
#import "SUUpdater.h"
#import "SUVersionComparisonProtocol.h"
#import "SUVersionDisplayProtocol.h"
#import "SUErrors.h"
#endif
+1 -1
View File
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="5037.3" systemVersion="13C44" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none">
<dependencies>
<deployment version="1060" identifier="macosx"/>
<deployment identifier="macosx"/>
<development version="5000" identifier="xcode"/>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="5037.3"/>
</dependencies>
+1 -1
View File
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="5037.3" systemVersion="13C44" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none">
<dependencies>
<deployment version="1060" identifier="macosx"/>
<deployment identifier="macosx"/>
<development version="5000" identifier="xcode"/>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="5037.3"/>
</dependencies>
+16 -15
View File
@@ -8,18 +8,20 @@
#import "SUTestApplicationDelegate.h"
#import "SUUpdateSettingsWindowController.h"
#import "SUFileManager.h"
#import "SUTestWebServer.h"
@interface SUTestApplicationDelegate ()
@property (nonatomic) SUUpdateSettingsWindowController *updateSettingsWindowController;
@property (nonatomic) NSTask *serverTask;
@property (nonatomic) SUTestWebServer *webServer;
@end
@implementation SUTestApplicationDelegate
@synthesize updateSettingsWindowController = _updateSettingsWindowController;
@synthesize serverTask = _serverTask;
@synthesize webServer = _webServer;
static NSString * const UPDATED_VERSION = @"2.0";
@@ -37,11 +39,11 @@ static NSString * const UPDATED_VERSION = @"2.0";
[[NSApplication sharedApplication] terminate:nil];
}
NSFileManager *fileManager = [NSFileManager defaultManager];
SUFileManager *fileManager = [SUFileManager fileManagerAllowingAuthorization:NO];
// Locate user's cache directory
NSError *cacheError = nil;
NSURL *cacheDirectoryURL = [fileManager URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:&cacheError];
NSURL *cacheDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:&cacheError];
if (cacheDirectoryURL == nil) {
NSLog(@"Failed to locate cache directory with error: %@", cacheError);
@@ -62,7 +64,7 @@ static NSString * const UPDATED_VERSION = @"2.0";
}
NSError *createDirectoryError = nil;
if (![fileManager createDirectoryAtURL:serverDirectoryURL withIntermediateDirectories:YES attributes:nil error:&createDirectoryError]) {
if (![[NSFileManager defaultManager] createDirectoryAtURL:serverDirectoryURL withIntermediateDirectories:YES attributes:nil error:&createDirectoryError]) {
NSLog(@"Failed creating directory at %@ with error %@", serverDirectoryURL.path, createDirectoryError);
assert(NO);
}
@@ -120,7 +122,7 @@ static NSString * const UPDATED_VERSION = @"2.0";
signUpdateTask.launchPath = signUpdatePath;
NSURL *archiveURL = [serverDirectoryURL URLByAppendingPathComponent:zipName];
signUpdateTask.arguments = @[archiveURL, privateKeyPath];
signUpdateTask.arguments = @[archiveURL.path, privateKeyPath];
NSPipe *outputPipe = [NSPipe pipe];
signUpdateTask.standardOutput = outputPipe;
@@ -137,7 +139,7 @@ static NSString * const UPDATED_VERSION = @"2.0";
// Obtain the file attributes to get the file size of our update later
NSError *fileAttributesError = nil;
NSDictionary *archiveFileAttributes = [fileManager attributesOfItemAtPath:archiveURL.path error:&fileAttributesError];
NSDictionary *archiveFileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:archiveURL.path error:&fileAttributesError];
if (archiveFileAttributes == nil) {
NSLog(@"Failed to retrieve file attributes from archive with error %@", fileAttributesError);
assert(NO);
@@ -176,13 +178,12 @@ static NSString * const UPDATED_VERSION = @"2.0";
}
// Finally start the server
NSTask *serverTask = [[NSTask alloc] init];
serverTask.launchPath = @"/usr/bin/python";
assert([fileManager fileExistsAtPath:serverTask.launchPath]);
serverTask.arguments = @[@"-m", @"SimpleHTTPServer", @"1337"];
serverTask.currentDirectoryPath = serverDirectoryPath;
[serverTask launch];
self.serverTask = serverTask;
SUTestWebServer *webServer = [[SUTestWebServer alloc] initWithPort:1337 workingDirectory:serverDirectoryPath];
if (!webServer) {
NSLog(@"Failed to create the web server");
assert(NO);
}
self.webServer = webServer;
// Show the Settings window
self.updateSettingsWindowController = [[SUUpdateSettingsWindowController alloc] init];
@@ -191,7 +192,7 @@ static NSString * const UPDATED_VERSION = @"2.0";
- (void)applicationWillTerminate:(NSNotification * __unused)notification
{
[self.serverTask terminate];
[self.webServer close];
}
@end
+17
View File
@@ -0,0 +1,17 @@
//
// SUTestWebServer.h
// Sparkle
//
// Created by Kevin Wojniak on 10/8/15.
// Copyright © 2015 Sparkle Project. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface SUTestWebServer : NSObject
- (instancetype)initWithPort:(int)port workingDirectory:(NSString*)workingDirectory;
- (void)close;
@end
+263
View File
@@ -0,0 +1,263 @@
//
// SUTestWebServer.m
// Sparkle
//
// Created by Kevin Wojniak on 10/8/15.
// Copyright © 2015 Sparkle Project. All rights reserved.
//
#import "SUTestWebServer.h"
#import <sys/socket.h>
#import <netinet/in.h>
@class SUTestWebServerConnection;
@protocol SUTestWebServerConnectionDelegate <NSObject>
@required
- (void)connectionDidClose:(SUTestWebServerConnection*)sender;
@end
@interface SUTestWebServerConnection : NSObject <NSStreamDelegate>
@property (nonatomic) NSString* workingDirectory;
@property (nonatomic, weak) id<SUTestWebServerConnectionDelegate> delegate;
@property (nonatomic) NSInputStream *inputStream;
@property (nonatomic) NSOutputStream *outputStream;
@property (nonatomic) NSData *dataToWrite;
@property (nonatomic) NSInteger numBytesToWrite;
@end
@implementation SUTestWebServerConnection
@synthesize workingDirectory = _workingDirectory;
@synthesize delegate = _delegate;
@synthesize inputStream = _inputStream;
@synthesize outputStream = _outputStream;
@synthesize dataToWrite = _dataToWrite;
@synthesize numBytesToWrite = _numBytesToWrite;
- (instancetype)initWithNativeHandle:(CFSocketNativeHandle)handle workingDirectory:(NSString*)workingDirectory delegate:(id<SUTestWebServerConnectionDelegate>)delegate {
self = [super init];
assert(self != nil);
_workingDirectory = workingDirectory;
_delegate = delegate;
CFReadStreamRef readStream = NULL;
CFWriteStreamRef writeStream = NULL;
CFStreamCreatePairWithSocket(NULL, handle, &readStream, &writeStream);
assert(readStream != NULL);
assert(writeStream != NULL);
_inputStream = (__bridge NSInputStream*)readStream;
assert(_inputStream != nil);
_inputStream.delegate = self;
_outputStream = (__bridge NSOutputStream*)writeStream;
assert(_outputStream != nil);
_outputStream.delegate = self;
[_inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[_outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[_inputStream open];
[_outputStream open];
return self;
}
- (void)close {
NSInputStream *inputStream = self.inputStream;
NSOutputStream *outputStream = self.outputStream;
if (inputStream == nil) {
assert(outputStream == nil);
return;
}
[inputStream close];
[outputStream close];
[inputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
self.inputStream = nil;
self.outputStream = nil;
[self.delegate connectionDidClose:self];
}
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode {
if (eventCode == NSStreamEventEndEncountered) {
[self close];
return;
}
if (aStream == self.inputStream && eventCode == NSStreamEventHasBytesAvailable) {
uint8_t buffer[8096];
const NSInteger numBytes = [self.inputStream read:buffer maxLength:sizeof(buffer)];
if (numBytes > 0) {
NSString *request = [[NSString alloc] initWithBytes:buffer length:(NSUInteger)numBytes encoding:NSUTF8StringEncoding];
NSArray *lines = [request componentsSeparatedByString:@"\r\n"];
NSString *requestLine = lines.count >= 3 ? lines[0] : nil;
NSArray *parts = requestLine ? [requestLine componentsSeparatedByString:@" "] : nil;
// Only process GET requests for existing files
if ([parts[0] isEqualToString:@"GET"]) {
// Use NSURL to strip out query parameters
NSString *path = [NSURL URLWithString:parts[1] relativeToURL:nil].path;
NSString *filePath = [self.workingDirectory stringByAppendingString:path];
BOOL isDir = NO;
if (![[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:&isDir] || isDir) {
NSLog(@"%@ - 404", requestLine);
[self write404];
} else {
NSLog(@"%@ - 200", requestLine);
[self write:[NSData dataWithContentsOfFile:filePath] status:YES];
}
} else {
NSLog(@"%@ - 404", requestLine);
[self write404];
}
}
} else if (aStream == self.outputStream && eventCode == NSStreamEventHasSpaceAvailable && self.dataToWrite != nil) {
[self checkIfCanWriteNow];
}
}
- (void)write404 {
NSString *body = @"<html><head><title>404 Not Found</title></head><body><h1>Not Found</h1></body></html>";
[self write:[body dataUsingEncoding:NSUTF8StringEncoding] status:NO];
}
- (void)write:(NSData*)body status:(BOOL)status {
NSString *state = status ? @"200 OK" : @"404 Not Found";
NSString *header = [NSString stringWithFormat:@"HTTP/1.0 %@\r\nContent-Length: %lu\r\n\r\n", state, body.length];
NSMutableData *response = [[header dataUsingEncoding:NSUTF8StringEncoding] mutableCopy];
[response appendData:body];
[self queueWrite:response];
}
- (void)queueWrite:(NSData*)data {
assert(self.dataToWrite == nil);
assert(data != nil);
assert(data.length > 0);
self.dataToWrite = data;
self.numBytesToWrite = (NSInteger)data.length;
[self checkIfCanWriteNow];
}
- (void)checkIfCanWriteNow {
assert(self.dataToWrite != nil);
if (self.numBytesToWrite == 0) {
// nothing more to write, we're done.
self.dataToWrite = nil;
self.numBytesToWrite = -1;
} else if (self.outputStream.hasSpaceAvailable) {
[self writeNow];
}
// otherwise wait for space available event
}
- (void)writeNow {
assert(self.outputStream != nil);
assert(self.outputStream.hasSpaceAvailable);
assert(self.dataToWrite != nil);
NSData *dataToWrite = self.dataToWrite;
const uint8_t *bytesOffset = (const uint8_t*)dataToWrite.bytes + ((NSInteger)dataToWrite.length - self.numBytesToWrite);
const NSInteger bytesWritten = [self.outputStream write:bytesOffset maxLength:(NSUInteger)self.numBytesToWrite];
if (bytesWritten > 0) {
self.numBytesToWrite = self.numBytesToWrite - bytesWritten;
assert(self.numBytesToWrite >= 0);
// wait for next space available event to write more
} else {
NSLog(@"Error: bytes written = %ld (%@)", bytesWritten, [NSString stringWithUTF8String:strerror(errno)]);
}
}
@end
@interface SUTestWebServer () <SUTestWebServerConnectionDelegate> {
CFSocketRef _socket;
}
@property (nonatomic) NSMutableArray *connections;
@property (nonatomic) NSString *workingDirectory;
- (void)accept:(CFSocketNativeHandle)address;
@end
static void connectCallback(CFSocketRef __unused s, CFSocketCallBackType type, CFDataRef __unused address, const void *data, void *info) {
if (type == kCFSocketAcceptCallBack) {
assert(data != NULL);
assert(info != NULL);
SUTestWebServer *server = (__bridge SUTestWebServer*)info;
assert(server != nil);
[server accept:*(const CFSocketNativeHandle*)data];
}
}
@implementation SUTestWebServer
@synthesize connections = _connections;
@synthesize workingDirectory = _workingDirectory;
- (instancetype)initWithPort:(int)port workingDirectory:(NSString*)workingDirectory {
self = [super init];
assert(self != nil);
CFSocketContext ctx;
memset(&ctx, 0, sizeof(ctx));
ctx.info = (__bridge void*)self;
_socket = CFSocketCreate(NULL, 0, 0, 0, kCFSocketAcceptCallBack, connectCallback, &ctx);
assert(_socket != NULL);
struct sockaddr_in address;
memset(&address, 0, sizeof(address));
address.sin_len = sizeof(address);
address.sin_family = AF_INET;
address.sin_port = htons(port);
address.sin_addr.s_addr = INADDR_ANY;
// will fail if port is in use.
CFSocketError socketErr = CFSocketSetAddress(_socket, (CFDataRef)[NSData dataWithBytes:&address length:sizeof(address)]);
if (socketErr != kCFSocketSuccess) {
NSLog(@"Socket error: %@", [NSString stringWithUTF8String:strerror(errno)]);
return nil;
}
_connections = [[NSMutableArray alloc] init];
_workingDirectory = workingDirectory;
CFRunLoopSourceRef source = CFSocketCreateRunLoopSource(NULL, _socket, 0);
assert(source != NULL);
CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
CFRelease(source);
return self;
}
- (void)connectionDidClose:(SUTestWebServerConnection *)sender {
assert(self.connections != nil);
assert([self.connections containsObject:sender]);
[self.connections removeObject:sender];
}
- (void)accept:(CFSocketNativeHandle)address {
SUTestWebServerConnection *conn = [[SUTestWebServerConnection alloc] initWithNativeHandle:address workingDirectory:self.workingDirectory delegate:self];
assert(conn != nil);
if (conn) {
assert(self.connections != nil);
[self.connections addObject:conn];
}
}
- (void)close {
for (SUTestWebServerConnection *conn in self.connections) {
[conn close];
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdirect-ivar-access"
if (_socket) {
CFSocketInvalidate(_socket);
CFRelease(_socket);
_socket = NULL;
}
#pragma clang diagnostic pop
}
@end
+34 -6
View File
@@ -12,7 +12,7 @@ class SUFileManagerTest: XCTestCase
{
func makeTempFiles(testBlock: (SUFileManager, NSURL, NSURL, NSURL, NSURL) -> Void)
{
let fileManager = SUFileManager()
let fileManager = SUFileManager(allowingAuthorization: false)
let tempDirectoryURL = try! fileManager.makeTemporaryDirectoryWithPreferredName("Sparkle Unit Test Data", appropriateForDirectoryURL: NSURL(fileURLWithPath: NSHomeDirectory()))
@@ -36,6 +36,7 @@ class SUFileManagerTest: XCTestCase
{
makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL in
XCTAssertNil(try? fileManager.moveItemAtURL(ordinaryFileURL, toURL: directoryURL))
XCTAssertNil(try? fileManager.moveItemAtURL(ordinaryFileURL, toURL: directoryURL.URLByAppendingPathComponent("foo").URLByAppendingPathComponent("bar")))
XCTAssertNil(try? fileManager.moveItemAtURL(rootURL.URLByAppendingPathComponent("does not exist"), toURL: directoryURL))
let newFileURL = (ordinaryFileURL.URLByDeletingLastPathComponent?.URLByAppendingPathComponent("new file"))!
@@ -77,6 +78,27 @@ class SUFileManagerTest: XCTestCase
try! fileManager.removeItemAtURL(directoryTrashURL)
}
}
func testCopyFiles()
{
makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL in
XCTAssertNil(try? fileManager.copyItemAtURL(ordinaryFileURL, toURL: directoryURL))
XCTAssertNil(try? fileManager.copyItemAtURL(ordinaryFileURL, toURL: directoryURL.URLByAppendingPathComponent("foo").URLByAppendingPathComponent("bar")))
XCTAssertNil(try? fileManager.copyItemAtURL(rootURL.URLByAppendingPathComponent("does not exist"), toURL: directoryURL))
let newFileURL = (ordinaryFileURL.URLByDeletingLastPathComponent?.URLByAppendingPathComponent("new file"))!
try! fileManager.copyItemAtURL(ordinaryFileURL, toURL: newFileURL)
XCTAssertTrue(fileManager._itemExistsAtURL(ordinaryFileURL))
XCTAssertTrue(fileManager._itemExistsAtURL(newFileURL))
let newDirectoryURL = (ordinaryFileURL.URLByDeletingLastPathComponent?.URLByAppendingPathComponent("new directory"))!
try! fileManager.copyItemAtURL(directoryURL, toURL: newDirectoryURL)
XCTAssertTrue(fileManager._itemExistsAtURL(directoryURL))
XCTAssertTrue(fileManager._itemExistsAtURL(newDirectoryURL))
XCTAssertTrue(fileManager._itemExistsAtURL(fileInDirectoryURL))
XCTAssertTrue(fileManager._itemExistsAtURL(newDirectoryURL.URLByAppendingPathComponent(fileInDirectoryURL.lastPathComponent!)))
}
}
func testRemoveFiles()
{
@@ -95,8 +117,8 @@ class SUFileManagerTest: XCTestCase
func testReleaseFilesFromQuarantine()
{
makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL in
try! fileManager.releaseItemFromQuarantineWithoutAuthenticationAtRootURL(ordinaryFileURL)
try! fileManager.releaseItemFromQuarantineWithoutAuthenticationAtRootURL(directoryURL)
try! fileManager.releaseItemFromQuarantineAtRootURL(ordinaryFileURL)
try! fileManager.releaseItemFromQuarantineAtRootURL(directoryURL)
let quarantineData = "does not really matter what is here".cStringUsingEncoding(NSUTF8StringEncoding)!
let quarantineDataLength = Int(strlen(quarantineData))
@@ -104,7 +126,7 @@ class SUFileManagerTest: XCTestCase
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)
try! fileManager.releaseItemFromQuarantineAtRootURL(ordinaryFileURL)
XCTAssertEqual(-1, getxattr(ordinaryFileURL.path!, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW))
XCTAssertEqual(0, setxattr(directoryURL.path!, SUAppleQuarantineIdentifier, quarantineData, quarantineDataLength, 0, XATTR_CREATE))
@@ -113,7 +135,7 @@ class SUFileManagerTest: XCTestCase
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)
try! fileManager.releaseItemFromQuarantineAtRootURL(directoryURL)
XCTAssertEqual(-1, getxattr(directoryURL.path!, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW))
XCTAssertEqual(-1, getxattr(fileInDirectoryURL.path!, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW))
@@ -244,7 +266,13 @@ class SUFileManagerTest: XCTestCase
// This alone shouldn't prompt a password dialog and should always succeed
func testAcquireAuthorization()
{
let fileManager = SUFileManager()
let fileManager = SUFileManager(allowingAuthorization: true)
try! fileManager._acquireAuthorization()
}
func testAcquireBadAuthorization()
{
let fileManager = SUFileManager(allowingAuthorization: false)
XCTAssertNil(try? fileManager._acquireAuthorization())
}
}