Compare commits

...
57 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
Kornel 545b8f2416 Merge pull request #653 from artillery/artillery-seamless2
Fire didFindValidUpdate even if automatically installing updates
2015-10-08 23:45:44 +01:00
Ian Langworth ☠ d1a62bba89 Fire didFindValidUpdate even if automatically installing updates 2015-10-08 15:33:00 -07:00
Kornel Lesiński 7ccf706a1d Synthesize automaticallyInstallUpdates 2015-10-08 23:25:21 +01:00
Kornel ef61691b34 Merge pull request #620 from artillery/artillery-seamless
Add automatically-install-updates option
2015-10-08 23:17:21 +01:00
Ian Langworth ☠ a92c23bb26 Add automatically install updates option 2015-10-08 14:45:05 -07:00
Zorg 21e4cc42cc Fix segfault when patch path has insufficient write permissions 2015-10-07 18:44:14 -04:00
Kornel abc307dc35 Merge pull request #647 from kainjow/patch-1
Fix readme headings
2015-10-05 11:10:02 +01:00
Kevin Wojniak 49e262e718 Fix readme headings 2015-10-04 16:36:57 -07:00
Jake Petroules 25be040bfc Merge pull request #643 from sparkle-project/maxcdn
MaxCDN
2015-10-03 05:56:59 -07:00
Kornel 46c677ea57 Merge pull request #641 from sparkle-project/charconv
Char conversions
2015-09-30 19:00:16 +01:00
Kornel Lesiński 165b772f8f MaxCDN 2015-09-29 00:39:35 +01:00
Kornel Lesiński bac2463ff2 Use a C formatting function for a C string 2015-09-28 10:54:30 +01:00
Kornel Lesiński c61b5d99a2 Avoid conversion from NSString to char[] 2015-09-28 10:46:36 +01:00
Jake Petroules e54498dd35 Merge pull request #640 from sparkle-project/fix-warnings
Fix warnings.
2015-09-27 16:21:28 -07:00
Jake Petroules 9ca70a5157 Fix warnings. 2015-09-27 16:16:37 -07:00
Jake Petroules f9b9184a39 Merge pull request #639 from sparkle-project/at-least-version
Use proper version checking.
2015-09-27 16:00:32 -07:00
Jake Petroules b943af3b59 Use proper version checking. 2015-09-27 15:55:26 -07:00
Jake Petroules 5afdc4f20e Implement isOperatingSystemAtLeastVersion: 2015-09-27 15:41:23 -07:00
Kornel f85ac88595 Merge pull request #635 from zorgiepoo/update-mod-time
Update modification & access time for new update
2015-09-27 23:02:29 +01:00
Zorg e9e04e2cb4 Merge branch 'master' into update-mod-time 2015-09-27 17:05:07 -04:00
Jake Petroules 114252dd09 Merge pull request #637 from kainjow/test-app-urls
Test app cleanup
2015-09-27 13:35:31 -07:00
Zorg 2f41dec805 Log any installation error that may occur 2015-09-27 16:19:35 -04:00
Kevin Wojniak 2ad01ad672 Reuse file manager variable 2015-09-27 12:33:14 -07:00
Kevin Wojniak 079666643d Set the task working directories instead of changing the process working directory 2015-09-27 12:31:45 -07:00
Kevin Wojniak da370c0f2b Avoid converting URLs to paths to check for existence 2015-09-27 12:24:47 -07:00
Zorg b98026040f Merge branch 'master' into update-mod-time 2015-09-27 11:19:36 -04:00
Zorg 83578c1f38 Merge branch 'master' into update-mod-time 2015-09-27 11:05:22 -04:00
Zorg 6af2fbfb6e Update modification & access time for new update
If we don't do this, Finder may not report the correct file size for the new update.
The system also may not register the new app in its database if we don't do this.

We may have been able to get away with not doing this before because we used to perform a copy
to install the update. However, now updates in some cases can be done with only move operations.

This should also be an alternative way of addressing issue #508
2015-09-27 10:53:22 -04:00
28 changed files with 857 additions and 150 deletions

No files matched your search

+8 -3
View File
@@ -1,4 +1,4 @@
# Sparkle [![Build Status](https://travis-ci.org/sparkle-project/Sparkle.svg?branch=master)](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> [![Coverage Status](https://coveralls.io/repos/sparkle-project/Sparkle/badge.svg?branch=master&service=github)](https://coveralls.io/github/sparkle-project/Sparkle?branch=master)
# Sparkle [![Build Status](https://travis-ci.org/sparkle-project/Sparkle.svg?branch=master)](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> [![Coverage Status](https://coveralls.io/repos/sparkle-project/Sparkle/badge.svg?branch=master&service=github)](https://coveralls.io/github/sparkle-project/Sparkle?branch=master) <a href="https://www.bandwidthhog.com/?utm_source=sparkle-github&amp;utm_medium=badge&amp;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.
+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 */,
+1
View File
@@ -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 = @"";
+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);
+35 -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.
@@ -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
+252 -57
View File
@@ -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];
-3
View File
@@ -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;
-27
View File
@@ -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
+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
+7 -2
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];
@@ -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) {
+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]];
}
+37 -12
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"
@@ -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];
+1
View File
@@ -24,6 +24,7 @@ extern NSString *const SUUpdateDriverFinishedNotification;
- (void)abortUpdate;
@property (getter=isInterruptible, readonly) BOOL interruptible;
@property (readonly) BOOL finished;
@property BOOL automaticallyInstallUpdates;
@end
+1
View File
@@ -26,6 +26,7 @@ NSString *const SUUpdateDriverFinishedNotification = @"SUUpdateDriverFinished";
@synthesize interruptible;
@synthesize finished;
@synthesize appcastURL;
@synthesize automaticallyInstallUpdates;
- (instancetype)initWithUpdater:(SUUpdater *)anUpdater
{
+17
View File
@@ -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.
+13 -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;
@@ -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; }
+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>
+22 -14
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);
@@ -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
+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
+1 -1
View File
@@ -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];
}
+55 -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))
@@ -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())
}
}
+2 -1
View File
@@ -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)