mirror of
https://github.com/sparkle-project/Sparkle
synced 2026-11-23 04:34:27 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0bc66ab011 | ||
|
|
c98ef7c614 | ||
|
|
896a01cd40 | ||
|
|
93a5228f5b | ||
|
|
124d9a901f | ||
|
|
c848882778 | ||
|
|
374b8d6195 | ||
|
|
27c1b0f045 | ||
|
|
154aa1b0db | ||
|
|
658e5fcb9f | ||
|
|
292ba01dbf | ||
|
|
ff7966d96a | ||
|
|
9cf7437392 | ||
|
|
9f1884f100 | ||
|
|
8a208ce520 | ||
|
|
c850146ef6 | ||
|
|
ccf4f81ea0 | ||
|
|
3c957096c6 | ||
|
|
bc5ad0d919 | ||
|
|
9d06f5bc4d | ||
|
|
6818d1f180 | ||
|
|
ee72ec3dab | ||
|
|
9b74309eb5 | ||
|
|
948eccb169 | ||
|
|
ff342f1e5b | ||
|
|
a7af6fb82d | ||
|
|
d7e3b01bd6 | ||
|
|
117716da9e | ||
|
|
17da7b5fb8 | ||
|
|
545b8f2416 | ||
|
|
d1a62bba89 | ||
|
|
7ccf706a1d | ||
|
|
ef61691b34 | ||
|
|
a92c23bb26 | ||
|
|
21e4cc42cc | ||
|
|
abc307dc35 | ||
|
|
49e262e718 | ||
|
|
25be040bfc | ||
|
|
46c677ea57 | ||
|
|
165b772f8f | ||
|
|
bac2463ff2 | ||
|
|
c61b5d99a2 | ||
|
|
e54498dd35 | ||
|
|
9ca70a5157 | ||
|
|
f9b9184a39 | ||
|
|
b943af3b59 | ||
|
|
5afdc4f20e | ||
|
|
f85ac88595 | ||
|
|
e9e04e2cb4 | ||
|
|
114252dd09 | ||
|
|
2f41dec805 | ||
|
|
2ad01ad672 | ||
|
|
079666643d | ||
|
|
da370c0f2b | ||
|
|
b98026040f | ||
|
|
83578c1f38 | ||
|
|
6af2fbfb6e |
No files matched your search
+8
-3
@@ -1,4 +1,4 @@
|
||||
# Sparkle [](https://travis-ci.org/sparkle-project/Sparkle) <a href='https://app.ship.io/dashboard#/jobs/8814/history' target='_blank'><img src='https://app.ship.io/jobs/V3PoCLcN5ft5Pnq0/build_status.png' height='20' /></a> [](https://coveralls.io/github/sparkle-project/Sparkle?branch=master)
|
||||
# Sparkle [](https://travis-ci.org/sparkle-project/Sparkle) <a href='https://app.ship.io/dashboard#/jobs/8814/history' target='_blank'><img src='https://app.ship.io/jobs/V3PoCLcN5ft5Pnq0/build_status.png' height='20' /></a> [](https://coveralls.io/github/sparkle-project/Sparkle?branch=master) <a href="https://www.bandwidthhog.com/?utm_source=sparkle-github&utm_medium=badge&utm_campaign=readme"><img src="https://img.shields.io/badge/sponsored%20by-Bandwidth%20Hog-orange.svg" alt="sponsored by: bandwidth hog"></a>
|
||||
|
||||
An easy-to-use software update framework for Cocoa developers.
|
||||
|
||||
@@ -36,13 +36,18 @@ An easy-to-use software update framework for Cocoa developers.
|
||||
* Runtime: OS X 10.7 or greater
|
||||
* Build: Xcode 5 and 10.8 SDK or greater
|
||||
|
||||
### API
|
||||
## API
|
||||
|
||||
Sparkle is built with `-fvisibility=hidden -fvisibility-inlines-hidden` which means no symbols are exported by default.
|
||||
If you are adding a symbol to the public API you must decorate the declaration with the `SU_EXPORT` macro (grep the source code for examples).
|
||||
|
||||
### Building the distribution package
|
||||
## Building the distribution package
|
||||
|
||||
`cd` to the root of the Sparkle source tree and run `make release`. Sparkle-*VERSION*.tar.bz2 will be created in a temporary directory and revealed in Finder after the build has completed.
|
||||
|
||||
Alternatively, build the Distribution scheme in the Xcode UI.
|
||||
|
||||
## Project Sponsor
|
||||
|
||||
[Bandwidth Hog](https://www.bandwidthhog.com/?utm_source=sparkle-github&utm_medium=link&utm_campaign=readme-footer) is a service from MaxCDN
|
||||
that allows you to push software updates to your customers for only 1¢ a gigabyte. Best part is there are no contracts, it is all Pay-as-you-Go.
|
||||
@@ -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 */,
|
||||
|
||||
Vendored
+1
@@ -172,6 +172,7 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.5;
|
||||
versionComparator:[SUStandardVersionComparator defaultComparator]
|
||||
completionHandler:^(NSError *error) {
|
||||
if (error) {
|
||||
SULog(@"Installation Error: %@", error);
|
||||
if (self.shouldShowUI) {
|
||||
NSAlert *alert = [[NSAlert alloc] init];
|
||||
alert.messageText = @"";
|
||||
|
||||
Vendored
+9
-5
@@ -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;
|
||||
|
||||
Vendored
+2
-1
@@ -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)
|
||||
|
||||
Vendored
+10
@@ -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);
|
||||
|
||||
Vendored
+35
-6
@@ -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.
|
||||
@@ -79,6 +100,19 @@
|
||||
*/
|
||||
- (BOOL)changeOwnerAndGroupOfItemAtRootURL:(NSURL *)targetURL toMatchURL:(NSURL *)matchURL error:(NSError **)error;
|
||||
|
||||
/**
|
||||
* Updates the modification and access time of an item at a specified target URL to the current time
|
||||
* @param targetURL A URL pointing to the target item whose modification and access time to update. The item at this URL must exist.
|
||||
* @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 target item's modification and access times have been updated, otherwise NO along with a populated error object
|
||||
*
|
||||
* This method updates the modification and access time of an item to the current time, ideal for letting the system know we installed a new file or
|
||||
* application.
|
||||
*
|
||||
* This is not an atomic operation.
|
||||
*/
|
||||
- (BOOL)updateModificationAndAccessTimeOfItemAtURL:(NSURL *)targetURL error:(NSError **)error;
|
||||
|
||||
/**
|
||||
* Releases Apple's quarantine extended attribute from the item at the specified root URL
|
||||
* @param rootURL A URL pointing to the item to release from Apple's quarantine. This will be applied recursively if the item is a directory. The item at this URL must exist.
|
||||
@@ -97,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
|
||||
Vendored
+252
-57
@@ -7,15 +7,13 @@
|
||||
//
|
||||
|
||||
#import "SUFileManager.h"
|
||||
#import "SUOperatingSystem.h"
|
||||
|
||||
#include <sys/xattr.h>
|
||||
#include <sys/errno.h>
|
||||
#include <sys/time.h>
|
||||
|
||||
#pragma clang diagnostic push
|
||||
// This is a private constant but it's referenced from our unit tests
|
||||
#pragma clang diagnostic ignored "-Wmissing-variable-declarations"
|
||||
NSString *SUAppleQuarantineIdentifier = @"com.apple.quarantine";
|
||||
#pragma clang diagnostic pop
|
||||
static char SUAppleQuarantineIdentifier[] = "com.apple.quarantine";
|
||||
|
||||
// Authorization code based on generous contribution from Allan Odgaard. Thanks, Allan!
|
||||
static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authorization, const char *executablePath, AuthorizationFlags options, char *const *arguments)
|
||||
@@ -54,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
|
||||
{
|
||||
@@ -73,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) {
|
||||
@@ -122,7 +135,7 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza
|
||||
}
|
||||
|
||||
// Wrapper around getxattr()
|
||||
- (ssize_t)_getXAttr:(NSString *)nameString fromFile:(NSString *)file options:(int)options
|
||||
- (ssize_t)_getXAttr:(const char *)name fromFile:(NSString *)file options:(int)options
|
||||
{
|
||||
char path[PATH_MAX] = {0};
|
||||
if (![file getFileSystemRepresentation:path maxLength:sizeof(path)]) {
|
||||
@@ -130,17 +143,11 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza
|
||||
return -1;
|
||||
}
|
||||
|
||||
const char *name = [nameString cStringUsingEncoding:NSASCIIStringEncoding];
|
||||
if (name == NULL) {
|
||||
errno = 0;
|
||||
return -1;
|
||||
}
|
||||
|
||||
return getxattr(path, name, NULL, 0, 0, options);
|
||||
}
|
||||
|
||||
// Wrapper around removexattr()
|
||||
- (int)_removeXAttr:(NSString *)name fromFile:(NSString *)file options:(int)options
|
||||
- (int)_removeXAttr:(const char *)attr fromFile:(NSString *)file options:(int)options
|
||||
{
|
||||
char path[PATH_MAX] = {0};
|
||||
if (![file getFileSystemRepresentation:path maxLength:sizeof(path)]) {
|
||||
@@ -148,18 +155,12 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza
|
||||
return -1;
|
||||
}
|
||||
|
||||
const char *attr = [name cStringUsingEncoding:NSASCIIStringEncoding];
|
||||
if (attr == NULL) {
|
||||
errno = 0;
|
||||
return -1;
|
||||
}
|
||||
|
||||
return removexattr(path, attr, options);
|
||||
}
|
||||
|
||||
#define XATTR_UTILITY_PATH "/usr/bin/xattr"
|
||||
// Recursively remove an xattr at a specified root URL with authentication
|
||||
- (BOOL)_removeXAttrWithAuthentication:(NSString *)name fromRootURL:(NSURL *)rootURL error:(NSError *__autoreleasing *)error
|
||||
- (BOOL)_removeXAttrWithAuthentication:(char *__nonnull)xattrName fromRootURL:(NSURL *)rootURL error:(NSError *__autoreleasing *)error
|
||||
{
|
||||
// Because this is a system utility, it's fine to follow the symbolic link if one exists
|
||||
if (![_fileManager fileExistsAtPath:@(XATTR_UTILITY_PATH)]) {
|
||||
@@ -177,29 +178,21 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza
|
||||
return NO;
|
||||
}
|
||||
|
||||
const char *xattrName = [name cStringUsingEncoding:NSASCIIStringEncoding];
|
||||
if (xattrName == NULL) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileWriteInapplicableStringEncodingError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Extended attribute %@ is not a valid ASCII convertible string.", name] }];
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
if (![self _acquireAuthorizationWithError:error]) {
|
||||
return NO;
|
||||
}
|
||||
|
||||
BOOL success = AuthorizationExecuteWithPrivilegesAndWait(_auth, XATTR_UTILITY_PATH, kAuthorizationFlagDefaults, (char *[]){ "-s", "-r", "-d", (char *)xattrName, path, NULL });
|
||||
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 %@.", name, rootURL.path.lastPathComponent];
|
||||
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;
|
||||
}
|
||||
|
||||
- (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) {
|
||||
@@ -217,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 {
|
||||
@@ -291,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);
|
||||
}
|
||||
@@ -315,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;
|
||||
@@ -505,11 +656,55 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza
|
||||
return NO;
|
||||
}
|
||||
|
||||
NSString *formattedUserAndGroupIDs = [NSString stringWithFormat:@"%u:%u", ownerID.unsignedIntValue, groupID.unsignedIntValue];
|
||||
const char *userAndGroup = [formattedUserAndGroupIDs cStringUsingEncoding:NSASCIIStringEncoding];
|
||||
if (userAndGroup == NULL) {
|
||||
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;
|
||||
}
|
||||
|
||||
// /usr/bin/touch can be used to update an application, as described in:
|
||||
// https://developer.apple.com/library/mac/documentation/Carbon/Conceptual/LaunchServicesConcepts/LSCConcepts/LSCConcepts.html
|
||||
// The document says LSRegisterURL() can be used as well but this hasn't worked out well for me in practice
|
||||
// Anyway, updating the modification time of the application is important because the system will be aware a new version of your app is available,
|
||||
// Finder will report the correct file size and other metadata for it, URL schemes your app may register will be updated, etc.
|
||||
// Behind the scenes, touch calls to utimes() which is what we use here - unless we need to authenticate
|
||||
- (BOOL)updateModificationAndAccessTimeOfItemAtURL:(NSURL *)targetURL error:(NSError * __autoreleasing *)error
|
||||
{
|
||||
if (![self _itemExistsAtURL:targetURL]) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFormattingError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Owner ID %u and Group ID %u could not be formatted.", ownerID.unsignedIntValue, groupID.unsignedIntValue] }];
|
||||
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileNoSuchFileError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to update modification & access time because %@ does not exist.", targetURL.path.lastPathComponent] }];
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
char path[PATH_MAX] = {0};
|
||||
if (![targetURL.path getFileSystemRepresentation:path maxLength:sizeof(path)]) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"File to update modification & access time (%@) cannot be represented as a valid file name.", targetURL.path.lastPathComponent] }];
|
||||
}
|
||||
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;
|
||||
}
|
||||
@@ -518,9 +713,9 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza
|
||||
return NO;
|
||||
}
|
||||
|
||||
BOOL success = AuthorizationExecuteWithPrivilegesAndWait(_auth, "/usr/sbin/chown", kAuthorizationFlagDefaults, (char *[]){ "-R", (char *)userAndGroup, targetPath, NULL });
|
||||
BOOL success = AuthorizationExecuteWithPrivilegesAndWait(_auth, "/usr/bin/touch", kAuthorizationFlagDefaults, (char *[]){ path, NULL });
|
||||
if (!success && error != NULL) {
|
||||
NSString *errorMessage = [NSString stringWithFormat:@"Failed to change owner:group %@ on %@ with authentication.", formattedUserAndGroupIDs, targetURL.path.lastPathComponent];
|
||||
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 }];
|
||||
}
|
||||
|
||||
@@ -651,8 +846,8 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza
|
||||
|
||||
NSURL *trashURL = nil;
|
||||
BOOL canUseNewTrashAPI = YES;
|
||||
#if __MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_8
|
||||
canUseNewTrashAPI = [_fileManager respondsToSelector:@selector(trashItemAtURL:resultingItemURL:error:)];
|
||||
#if __MAC_OS_X_VERSION_MIN_REQUIRED < 1080
|
||||
canUseNewTrashAPI = [SUOperatingSystem isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){10, 8, 0}];
|
||||
if (!canUseNewTrashAPI) {
|
||||
FSRef trashRef;
|
||||
if (FSFindFolder(kUserDomain, kTrashFolderType, kDontCreateFolder, &trashRef) == noErr) {
|
||||
@@ -699,7 +894,7 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza
|
||||
// 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 < MAC_OS_X_VERSION_10_8
|
||||
#if __MAC_OS_X_VERSION_MIN_REQUIRED < 1080
|
||||
if (!canUseNewTrashAPI) {
|
||||
NSString *tempParentPath = tempItemURL.URLByDeletingLastPathComponent.path;
|
||||
success = [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:tempParentPath destination:@"" files:@[tempItemURL.lastPathComponent] tag:NULL];
|
||||
|
||||
Vendored
-3
@@ -23,9 +23,6 @@ typedef struct {
|
||||
|
||||
@property (strong, readonly) NSBundle *bundle;
|
||||
|
||||
+ (NSOperatingSystemVersion)operatingSystemVersion;
|
||||
+ (NSString *)systemVersionString;
|
||||
|
||||
- (instancetype)initWithBundle:(NSBundle *)aBundle;
|
||||
@property (readonly, copy) NSString *bundlePath;
|
||||
@property (readonly) BOOL allowsAutomaticUpdates;
|
||||
|
||||
Vendored
-27
@@ -284,31 +284,4 @@
|
||||
return [self objectForUserDefaultsKey:key] ? [self boolForUserDefaultsKey:key] : [self boolForInfoDictionaryKey:key];
|
||||
}
|
||||
|
||||
+ (NSOperatingSystemVersion)operatingSystemVersion
|
||||
{
|
||||
#if __MAC_OS_X_VERSION_MIN_REQUIRED < 1090 // Present in 10.9 despite NS_AVAILABLE's claims
|
||||
#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];
|
||||
}
|
||||
|
||||
+ (NSString *)systemVersionString
|
||||
{
|
||||
NSOperatingSystemVersion version = self.operatingSystemVersion;
|
||||
return [NSString stringWithFormat:@"%ld.%ld.%ld", (long)version.majorVersion, (long)version.minorVersion, (long)version.patchVersion];
|
||||
}
|
||||
|
||||
@end
|
||||
Vendored
+16
@@ -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
|
||||
Vendored
+51
@@ -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
|
||||
Vendored
+7
-2
@@ -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];
|
||||
@@ -60,7 +60,7 @@
|
||||
return NO;
|
||||
}
|
||||
|
||||
// Release our new app from quarantine and fix its owner and group IDs while it's at our temporary destination
|
||||
// Release our new app from quarantine, fix its owner and group IDs, and update its modification time while it's at our temporary destination
|
||||
// We must leave moving the app to its destination as the final step in installing it, so that
|
||||
// it's not possible our new app can be left in an incomplete state at the final destination
|
||||
|
||||
@@ -87,6 +87,11 @@
|
||||
return NO;
|
||||
}
|
||||
|
||||
if (![fileManager updateModificationAndAccessTimeOfItemAtURL:newTempURL error:error]) {
|
||||
// Not a fatal error, but a pretty unfortunate one
|
||||
SULog(@"Failed to update modification and access time of new app at %@", newTempURL.path);
|
||||
}
|
||||
|
||||
// Decide on a destination name we should use for the older app when we move it around the file system
|
||||
NSString *oldDestinationName = nil;
|
||||
if (SPARKLE_APPEND_VERSION_NUMBER) {
|
||||
|
||||
Vendored
+4
-2
@@ -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]];
|
||||
}
|
||||
|
||||
Vendored
+37
-12
@@ -11,6 +11,7 @@
|
||||
#import "SUUpdateAlert.h"
|
||||
#import "SUUpdater_Private.h"
|
||||
#import "SUHost.h"
|
||||
#import "SUOperatingSystem.h"
|
||||
#import "SUStatusController.h"
|
||||
#import "SUConstants.h"
|
||||
|
||||
@@ -41,8 +42,25 @@
|
||||
@synthesize statusController;
|
||||
@synthesize updateAlert;
|
||||
|
||||
- (instancetype)initWithUpdater:(SUUpdater *)anUpdater
|
||||
{
|
||||
if ((self = [super initWithUpdater:anUpdater])) {
|
||||
self.automaticallyInstallUpdates = NO;
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)didFindValidUpdate
|
||||
{
|
||||
if ([[self.updater delegate] respondsToSelector:@selector(updater:didFindValidUpdate:)]) {
|
||||
[[self.updater delegate] updater:self.updater didFindValidUpdate:self.updateItem];
|
||||
}
|
||||
|
||||
if (self.automaticallyInstallUpdates) {
|
||||
[self updateAlertFinishedWithChoice:SUInstallUpdateChoice];
|
||||
return;
|
||||
}
|
||||
|
||||
self.updateAlert = [[SUUpdateAlert alloc] initWithAppcastItem:self.updateItem host:self.host completionBlock:^(SUUpdateAlertChoice choice) {
|
||||
[self updateAlertFinishedWithChoice:choice];
|
||||
}];
|
||||
@@ -53,10 +71,6 @@
|
||||
}
|
||||
[self.updateAlert setVersionDisplayer:versDisp];
|
||||
|
||||
if ([[self.updater delegate] respondsToSelector:@selector(updater:didFindValidUpdate:)]) {
|
||||
[[self.updater delegate] updater:self.updater didFindValidUpdate:self.updateItem];
|
||||
}
|
||||
|
||||
// If the app is a menubar app or the like, we need to focus it first and alter the
|
||||
// update prompt to behave like a normal window. Otherwise if the window were hidden
|
||||
// there may be no way for the application to be activated to make it visible again.
|
||||
@@ -78,12 +92,14 @@
|
||||
[[self.updater delegate] updaterDidNotFindUpdate:self.updater];
|
||||
[[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterDidNotFindUpdateNotification object:self.updater];
|
||||
|
||||
NSAlert *alert = [[NSAlert alloc] init];
|
||||
alert.messageText = SULocalizedString(@"You're up-to-date!", "Status message shown when the user checks for updates but is already current or the feed doesn't contain any updates.");
|
||||
alert.informativeText = [NSString stringWithFormat:SULocalizedString(@"%@ %@ is currently the newest version available.", nil), [self.host name], [self.host displayVersion]];
|
||||
[alert addButtonWithTitle:SULocalizedString(@"OK", nil)];
|
||||
[self showModalAlert:alert];
|
||||
[self abortUpdate];
|
||||
if (!self.automaticallyInstallUpdates) {
|
||||
NSAlert *alert = [[NSAlert alloc] init];
|
||||
alert.messageText = SULocalizedString(@"You're up-to-date!", "Status message shown when the user checks for updates but is already current or the feed doesn't contain any updates.");
|
||||
alert.informativeText = [NSString stringWithFormat:SULocalizedString(@"%@ %@ is currently the newest version available.", nil), [self.host name], [self.host displayVersion]];
|
||||
[alert addButtonWithTitle:SULocalizedString(@"OK", nil)];
|
||||
[self showModalAlert:alert];
|
||||
[self abortUpdate];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)applicationDidBecomeActive:(NSNotification *)__unused aNotification
|
||||
@@ -128,7 +144,7 @@
|
||||
|
||||
- (NSString *)localizedStringFromByteCount:(long long)value
|
||||
{
|
||||
if (SUHost.operatingSystemVersion.minorVersion < 8) {
|
||||
if (![SUOperatingSystem isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){10, 8, 0}]) {
|
||||
if (value < 1000) {
|
||||
return [NSString stringWithFormat:@"%.0lf %@", value / 1.0,
|
||||
SULocalizedString(@"B", @"the unit for bytes")];
|
||||
@@ -163,8 +179,12 @@
|
||||
|
||||
- (IBAction)cancelDownload:(id)__unused sender
|
||||
{
|
||||
if (self.download)
|
||||
if (self.download) {
|
||||
[self.download cancel];
|
||||
if ([[self.updater delegate] respondsToSelector:@selector(userDidCancelDownload:)]) {
|
||||
[[self.updater delegate] userDidCancelDownload:self.updater];
|
||||
}
|
||||
}
|
||||
[self abortUpdate];
|
||||
}
|
||||
|
||||
@@ -187,6 +207,11 @@
|
||||
|
||||
- (void)unarchiverDidFinish:(SUUnarchiver *)__unused ua
|
||||
{
|
||||
if (self.automaticallyInstallUpdates) {
|
||||
[self installWithToolAndRelaunch:YES];
|
||||
return;
|
||||
}
|
||||
|
||||
[self.statusController beginActionWithTitle:SULocalizedString(@"Ready to Install", nil) maxProgressValue:1.0 statusText:nil];
|
||||
[self.statusController setProgressValue:1.0]; // Fill the bar.
|
||||
[self.statusController setButtonEnabled:YES];
|
||||
|
||||
Vendored
+1
@@ -24,6 +24,7 @@ extern NSString *const SUUpdateDriverFinishedNotification;
|
||||
- (void)abortUpdate;
|
||||
@property (getter=isInterruptible, readonly) BOOL interruptible;
|
||||
@property (readonly) BOOL finished;
|
||||
@property BOOL automaticallyInstallUpdates;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
Vendored
+1
@@ -26,6 +26,7 @@ NSString *const SUUpdateDriverFinishedNotification = @"SUUpdateDriverFinished";
|
||||
@synthesize interruptible;
|
||||
@synthesize finished;
|
||||
@synthesize appcastURL;
|
||||
@synthesize automaticallyInstallUpdates;
|
||||
|
||||
- (instancetype)initWithUpdater:(SUUpdater *)anUpdater
|
||||
{
|
||||
|
||||
Vendored
+17
@@ -77,6 +77,16 @@ SU_EXPORT @interface SUUpdater : NSObject
|
||||
*/
|
||||
- (void)checkForUpdatesInBackground;
|
||||
|
||||
/*!
|
||||
Checks for updates and, if available, immediately downloads and installs them.
|
||||
A progress dialog is shown but the user will never be prompted to read the
|
||||
release notes.
|
||||
|
||||
You may want to respond to the userDidCancelDownload delegate method in case
|
||||
the user clicks the "Cancel" button while the update is downloading.
|
||||
*/
|
||||
- (void)installUpdatesIfAvailable;
|
||||
|
||||
/*!
|
||||
Returns the date of last update check.
|
||||
|
||||
@@ -228,6 +238,13 @@ SU_EXPORT extern NSString *const SUUpdaterAppcastNotificationKey;
|
||||
*/
|
||||
- (void)updater:(SUUpdater *)updater failedToDownloadUpdate:(SUAppcastItem *)item error:(NSError *)error;
|
||||
|
||||
/*!
|
||||
Called when the user clicks the cancel button while and update is being downloaded.
|
||||
|
||||
\param updater The SUUpdater instance.
|
||||
*/
|
||||
- (void)userDidCancelDownload:(SUUpdater *)updater;
|
||||
|
||||
/*!
|
||||
Called immediately before installing the specified update.
|
||||
|
||||
|
||||
Vendored
+13
-1
@@ -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;
|
||||
@@ -333,6 +334,17 @@ static NSString *const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefaults
|
||||
[self checkForUpdatesWithDriver:[[SUProbingUpdateDriver alloc] initWithUpdater:self]];
|
||||
}
|
||||
|
||||
- (void)installUpdatesIfAvailable
|
||||
{
|
||||
if (self.driver && [self.driver isInterruptible]) {
|
||||
[self.driver abortUpdate];
|
||||
}
|
||||
|
||||
SUUIBasedUpdateDriver *theUpdateDriver = [[SUUserInitiatedUpdateDriver alloc] initWithUpdater:self];
|
||||
theUpdateDriver.automaticallyInstallUpdates = YES;
|
||||
[self checkForUpdatesWithDriver:theUpdateDriver];
|
||||
}
|
||||
|
||||
- (void)checkForUpdatesWithDriver:(SUUpdateDriver *)d
|
||||
{
|
||||
if ([self updateInProgress]) { return; }
|
||||
|
||||
Vendored
+7
-7
@@ -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
@@ -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
@@ -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>
|
||||
|
||||
@@ -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);
|
||||
@@ -53,7 +55,7 @@ static NSString * const UPDATED_VERSION = @"2.0";
|
||||
|
||||
// Create a directory that'll be used for our web server listing
|
||||
NSURL *serverDirectoryURL = [cacheDirectoryURL URLByAppendingPathComponent:bundleIdentifier];
|
||||
if ([fileManager fileExistsAtPath:serverDirectoryURL.path]) {
|
||||
if ([serverDirectoryURL checkResourceIsReachableAndReturnError:nil]) {
|
||||
NSError *removeServerDirectoryError = nil;
|
||||
|
||||
if (![fileManager removeItemAtURL:serverDirectoryURL error:&removeServerDirectoryError]) {
|
||||
@@ -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);
|
||||
}
|
||||
@@ -81,7 +83,7 @@ static NSString * const UPDATED_VERSION = @"2.0";
|
||||
// Update bundle's version keys to latest version
|
||||
NSURL *infoURL = [[destinationBundleURL URLByAppendingPathComponent:@"Contents"] URLByAppendingPathComponent:@"Info.plist"];
|
||||
|
||||
BOOL infoFileExists = [fileManager fileExistsAtPath:infoURL.path];
|
||||
BOOL infoFileExists = [infoURL checkResourceIsReachableAndReturnError:nil];
|
||||
assert(infoFileExists);
|
||||
|
||||
NSMutableDictionary *infoDictionary = [[NSMutableDictionary alloc] initWithContentsOfURL:infoURL];
|
||||
@@ -92,20 +94,21 @@ static NSString * const UPDATED_VERSION = @"2.0";
|
||||
assert(wroteInfoFile);
|
||||
|
||||
// Change current working directory so web server knows where to list files
|
||||
BOOL changedCurrentWorkingDirectory = [fileManager changeCurrentDirectoryPath:serverDirectoryURL.path];
|
||||
assert(changedCurrentWorkingDirectory);
|
||||
NSString *serverDirectoryPath = serverDirectoryURL.path;
|
||||
assert(serverDirectoryPath != nil);
|
||||
|
||||
// Create the archive for our update
|
||||
NSString *zipName = @"Sparkle_Test_App.zip";
|
||||
NSTask *dittoTask = [[NSTask alloc] init];
|
||||
dittoTask.launchPath = @"/usr/bin/ditto";
|
||||
dittoTask.arguments = @[@"-c", @"-k", @"--sequesterRsrc", @"--keepParent", destinationBundleURL.lastPathComponent, zipName];
|
||||
dittoTask.currentDirectoryPath = serverDirectoryPath;
|
||||
[dittoTask launch];
|
||||
[dittoTask waitUntilExit];
|
||||
|
||||
assert(dittoTask.terminationStatus == 0);
|
||||
|
||||
[[NSFileManager defaultManager] removeItemAtURL:destinationBundleURL error:NULL];
|
||||
[fileManager removeItemAtURL:destinationBundleURL error:NULL];
|
||||
|
||||
// Don't ever do this at home, kids (seriously)
|
||||
// (that is, including the private key inside of your application)
|
||||
@@ -119,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;
|
||||
@@ -136,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);
|
||||
@@ -175,7 +178,12 @@ static NSString * const UPDATED_VERSION = @"2.0";
|
||||
}
|
||||
|
||||
// Finally start the server
|
||||
self.serverTask = [NSTask launchedTaskWithLaunchPath:@"/usr/bin/python" arguments:@[@"-m", @"SimpleHTTPServer", @"1337"]];
|
||||
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];
|
||||
@@ -184,7 +192,7 @@ static NSString * const UPDATED_VERSION = @"2.0";
|
||||
|
||||
- (void)applicationWillTerminate:(NSNotification * __unused)notification
|
||||
{
|
||||
[self.serverTask terminate];
|
||||
[self.webServer close];
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -67,7 +67,7 @@
|
||||
{
|
||||
SUDSAVerifier *v = [[SUDSAVerifier alloc] initWithPublicKeyData:pubKey];
|
||||
|
||||
NSData *sig = [[NSData alloc] initWithBase64Encoding:sigString];
|
||||
NSData *sig = [[NSData alloc] initWithBase64EncodedString:sigString options:(NSDataBase64DecodingOptions)0];
|
||||
|
||||
return [v verifyFileAtPath:aFile signature:sig];
|
||||
}
|
||||
|
||||
@@ -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))
|
||||
@@ -169,6 +191,27 @@ class SUFileManagerTest: XCTestCase
|
||||
}
|
||||
}
|
||||
|
||||
func testUpdateFileModificationTime()
|
||||
{
|
||||
makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL in
|
||||
XCTAssertNil(try? fileManager.updateModificationAndAccessTimeOfItemAtURL(rootURL.URLByAppendingPathComponent("does not exist")))
|
||||
|
||||
let oldOrdinaryFileAttributes = try! NSFileManager.defaultManager().attributesOfItemAtPath(ordinaryFileURL.path!)
|
||||
let oldDirectoryAttributes = try! NSFileManager.defaultManager().attributesOfItemAtPath(directoryURL.path!)
|
||||
|
||||
sleep(1); // wait for clock to advance
|
||||
|
||||
try! fileManager.updateModificationAndAccessTimeOfItemAtURL(ordinaryFileURL)
|
||||
try! fileManager.updateModificationAndAccessTimeOfItemAtURL(directoryURL)
|
||||
|
||||
let newOrdinaryFileAttributes = try! NSFileManager.defaultManager().attributesOfItemAtPath(ordinaryFileURL.path!)
|
||||
XCTAssertGreaterThan((newOrdinaryFileAttributes[NSFileModificationDate] as! NSDate).timeIntervalSinceDate(oldOrdinaryFileAttributes[NSFileModificationDate] as! NSDate), 0)
|
||||
|
||||
let newDirectoryAttributes = try! NSFileManager.defaultManager().attributesOfItemAtPath(directoryURL.path!)
|
||||
XCTAssertGreaterThan((newDirectoryAttributes[NSFileModificationDate] as! NSDate).timeIntervalSinceDate(oldDirectoryAttributes[NSFileModificationDate] as! NSDate), 0)
|
||||
}
|
||||
}
|
||||
|
||||
func testFileExists()
|
||||
{
|
||||
makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL in
|
||||
@@ -223,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())
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,8 @@
|
||||
#import "SUBinaryDeltaCommon.h"
|
||||
#import "SUFileManager.h"
|
||||
|
||||
extern NSString *SUAppleQuarantineIdentifier;
|
||||
// Duplicated to avoid exporting a private symbol from SUFileManager
|
||||
static const char *SUAppleQuarantineIdentifier = "com.apple.quarantine";
|
||||
|
||||
@interface SUFileManager (Private)
|
||||
|
||||
|
||||
Reference in new issue
Block a user