mirror of
https://github.com/sparkle-project/Sparkle
synced 2026-11-22 04:30:47 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a19dfb2be0 | ||
|
|
7394593743 | ||
|
|
4973c0143f | ||
|
|
c171f381d4 | ||
|
|
dde4a0aae2 | ||
|
|
d5a1ba44ff | ||
|
|
0d03b4006d | ||
|
|
25993d0776 | ||
|
|
276707b3da | ||
|
|
23e88737ec | ||
|
|
d400a53ebd | ||
|
|
f39b07fd59 | ||
|
|
5bc8f3e535 | ||
|
|
503a292084 | ||
|
|
d60b16f633 | ||
|
|
de3e73b589 | ||
|
|
ad863775db | ||
|
|
79511c982a | ||
|
|
189ed9d315 | ||
|
|
ea94969188 | ||
|
|
57731f44d7 | ||
|
|
2a0514c93b | ||
|
|
467e1495c0 | ||
|
|
8ac254951a | ||
|
|
c83c9221f7 | ||
|
|
b46315df9c | ||
|
|
9c505dee2f | ||
|
|
2ed7402367 | ||
|
|
3afa47b092 | ||
|
|
874d6bce36 | ||
|
|
51a335b3fd | ||
|
|
578bb9ecb8 | ||
|
|
76e8838eb3 | ||
|
|
0a101b7902 | ||
|
|
865dd2e187 | ||
|
|
083bd9b453 | ||
|
|
b48bc4dcac | ||
|
|
bb6203f40a | ||
|
|
25204a66e0 | ||
|
|
c886947f55 | ||
|
|
f0460033ba | ||
|
|
1a71456ed9 | ||
|
|
e7cdbfc45e | ||
|
|
8b5c8b5cdf | ||
|
|
a7af48f0d1 | ||
|
|
03e28780d9 | ||
|
|
5b1c76db26 | ||
|
|
703e611eb5 | ||
|
|
6ee88124ad | ||
|
|
1cc5f230a5 | ||
|
|
429f950434 | ||
|
|
7df50ccfd3 | ||
|
|
9c301bfbf3 | ||
|
|
8a0474d644 | ||
|
|
dc85d63861 | ||
|
|
dc8e8b775a | ||
|
|
ecb608bb40 | ||
|
|
c3e546d7f8 | ||
|
|
2477a92b0f | ||
|
|
7f0bc6a244 | ||
|
|
68f62e5955 | ||
|
|
0cb0b2f2c7 | ||
|
|
b590722aad | ||
|
|
10f831fce8 | ||
|
|
a2ecdd2744 | ||
|
|
ec7f55d173 | ||
|
|
ddfc4089d2 | ||
|
|
80c34526e8 | ||
|
|
0c3994c571 | ||
|
|
fbda90ad64 | ||
|
|
40750b6f24 | ||
|
|
a7ba0bea6e | ||
|
|
558cfd2153 | ||
|
|
94074e2bdc | ||
|
|
56065fcf95 | ||
|
|
f24189e848 | ||
|
|
65b12a2be1 | ||
|
|
900de556a8 | ||
|
|
7c8ff2b969 | ||
|
|
43b4472d3c | ||
|
|
260170f372 | ||
|
|
ea85fc6442 | ||
|
|
a52604a264 | ||
|
|
39d6c616b0 | ||
|
|
043ad0464a | ||
|
|
d99339cf08 | ||
|
|
c541f95036 | ||
|
|
e678ffb3ca | ||
|
|
070ea362a2 | ||
|
|
c4db636d0b | ||
|
|
7e9f05865a | ||
|
|
3c14c950ef | ||
|
|
4438b69b50 | ||
|
|
6d0c734c26 | ||
|
|
e8805e0563 | ||
|
|
193036b2c4 | ||
|
|
33bf6732ea | ||
|
|
e94fb63ff0 | ||
|
|
84e5925578 | ||
|
|
bb83e9a0da | ||
|
|
26d4d75c36 | ||
|
|
fe5737f0b6 | ||
|
|
ac49a3b5b6 | ||
|
|
cbeaeb29ec | ||
|
|
d0a6c699da | ||
|
|
84b7e5e22f | ||
|
|
61774b3f7d | ||
|
|
55be13ca6f | ||
|
|
fc48e5e4df | ||
|
|
bfada07a2c | ||
|
|
4f965660f3 | ||
|
|
a2764158d6 | ||
|
|
60727bffa5 | ||
|
|
715163fe0d | ||
|
|
629c42d62d | ||
|
|
3e45211bbe | ||
|
|
89acca1318 | ||
|
|
4bc2e6e891 | ||
|
|
405c9fd9a1 | ||
|
|
9232316b19 | ||
|
|
0569c73391 | ||
|
|
423ee5a9d6 | ||
|
|
ac042821d8 | ||
|
|
36139c57bc | ||
|
|
662e84400a | ||
|
|
b6b5c6d927 | ||
|
|
1683d2de34 | ||
|
|
615a08bc32 | ||
|
|
c7bf998913 | ||
|
|
1dd9d93090 | ||
|
|
ac8c37096e | ||
|
|
c86e825a5f | ||
|
|
40a777f5d9 | ||
|
|
3098afc90b | ||
|
|
3809da20bf | ||
|
|
c623480f72 | ||
|
|
72ee4aa2c6 | ||
|
|
e160f994b4 | ||
|
|
e7810c970b | ||
|
|
0a94a6ce88 | ||
|
|
e54748ac87 | ||
|
|
3b04c45ee9 | ||
|
|
792e13a067 | ||
|
|
83195a802e | ||
|
|
46d2a6aeab | ||
|
|
40347c0d43 | ||
|
|
e1f67cf8db | ||
|
|
5210e1d3ac | ||
|
|
f43c83688d | ||
|
|
83709f4b30 | ||
|
|
c0d4640508 | ||
|
|
c6fb841868 | ||
|
|
9a07c5125e | ||
|
|
fb6fe6d6da | ||
|
|
9318b9f896 | ||
|
|
d27c12f1fc | ||
|
|
016dad176e | ||
|
|
1f98f9eb36 | ||
|
|
6e51231966 | ||
|
|
dc1d83e904 | ||
|
|
9d966e68f0 | ||
|
|
03abfe2739 | ||
|
|
155816b609 | ||
|
|
313352fe26 | ||
|
|
67b1e08a45 | ||
|
|
21214e8623 | ||
|
|
ed16c5c2a0 | ||
|
|
0a869e87bf | ||
|
|
14c543ccb3 | ||
|
|
0fd0331464 | ||
|
|
0cba214f07 | ||
|
|
2a644672ca | ||
|
|
81e71844d6 | ||
|
|
e4821e0454 | ||
|
|
a97538f931 | ||
|
|
c61767f501 | ||
|
|
c0d45952a9 | ||
|
|
06629310e2 | ||
|
|
7e99561d9c | ||
|
|
5c71eebf59 | ||
|
|
5368dbfb41 | ||
|
|
0e978e3faf | ||
|
|
f9dfa3dd9d | ||
|
|
c104c1b27e | ||
|
|
7e7c97a09f | ||
|
|
a75ad96719 | ||
|
|
22f5d1f0f8 | ||
|
|
b9753cbd81 | ||
|
|
548ae6e2b6 | ||
|
|
db7f4acc83 | ||
|
|
942d70d3aa | ||
|
|
2ccac610f6 | ||
|
|
7a0d402a01 | ||
|
|
d070bca0b0 | ||
|
|
682f8f32c6 | ||
|
|
56db200f06 | ||
|
|
34179edd6d | ||
|
|
530f3a4a63 | ||
|
|
135d05b8b8 | ||
|
|
c56694382e | ||
|
|
a39023e95b | ||
|
|
282f0ae58e | ||
|
|
55e1a24431 | ||
|
|
9fa0519811 | ||
|
|
ecc72f834d | ||
|
|
c1488b0515 | ||
|
|
aa29a754e6 | ||
|
|
65bd11df8a | ||
|
|
397eb8a379 | ||
|
|
27c560b7d5 | ||
|
|
5121d74ad9 | ||
|
|
fbb040926e | ||
|
|
e2426784ac | ||
|
|
118c72e61c | ||
|
|
6f11c1ce02 | ||
|
|
d5f4c312ee | ||
|
|
9b3753f5d7 | ||
|
|
5dda7462c1 | ||
|
|
c059dc8ae8 | ||
|
|
6ca4b05cad | ||
|
|
d95f420360 | ||
|
|
7ae0e71b02 | ||
|
|
548908628f | ||
|
|
d40bdb615a | ||
|
|
b16d881808 | ||
|
|
392cb65716 | ||
|
|
6e01dd272f | ||
|
|
762d527463 | ||
|
|
07599c2ffd | ||
|
|
f795802d60 | ||
|
|
073ce22015 | ||
|
|
7ef468e8ea | ||
|
|
fc9b2b38fa | ||
|
|
717921cfa1 | ||
|
|
e621622c8b | ||
|
|
6902b80ab6 | ||
|
|
d44a122a21 | ||
|
|
0b6b6fe4ca | ||
|
|
f43b9f7f02 | ||
|
|
eafbb2cfad | ||
|
|
5c408f5019 | ||
|
|
9d35c819fd | ||
|
|
b9d113924e | ||
|
|
ee80a66896 | ||
|
|
187ae4fe57 | ||
|
|
ca4d51561e | ||
|
|
915c2047bf | ||
|
|
f172cd32a8 | ||
|
|
8481035fb9 | ||
|
|
7238c2aeb6 | ||
|
|
d9d62299be | ||
|
|
478bbf303b | ||
|
|
ee16e5ae55 | ||
|
|
d50e823b3d | ||
|
|
4636588e76 | ||
|
|
2be4dc11a0 | ||
|
|
6181c9276a | ||
|
|
49845d8246 | ||
|
|
8fa136c0a3 | ||
|
|
dc1151a5ff | ||
|
|
a920ecc197 | ||
|
|
271d504f6d | ||
|
|
9c0ccd4a57 | ||
|
|
266be254d2 | ||
|
|
efe93c492f | ||
|
|
74b09ad904 | ||
|
|
b9012aa8dc | ||
|
|
ae41185267 | ||
|
|
6634ed7d69 | ||
|
|
799ebdcf7d | ||
|
|
d911db7357 | ||
|
|
d2e1987ce3 | ||
|
|
2d1688c063 | ||
|
|
b56910f455 | ||
|
|
a3e96581b4 | ||
|
|
94423a10c9 | ||
|
|
b14c00136e | ||
|
|
ebf8d2105b | ||
|
|
14ac885ea0 | ||
|
|
355e239df9 | ||
|
|
e7ae7d5330 | ||
|
|
daaadf1c44 | ||
|
|
87064c9304 | ||
|
|
0af392f808 | ||
|
|
fb8ad9f75d | ||
|
|
b4210a85b9 | ||
|
|
091986b12f | ||
|
|
1ecb620986 | ||
|
|
21f3c8a157 | ||
|
|
468bcb9640 | ||
|
|
d38b29c858 | ||
|
|
e2b9fc7ffd | ||
|
|
f016cd8086 | ||
|
|
796967cf24 | ||
|
|
578e78876c | ||
|
|
2f438186d6 | ||
|
|
2c1820f2a9 | ||
|
|
a30eff3680 | ||
|
|
1a09baf0ed | ||
|
|
a1095ff29c | ||
|
|
51b3931485 | ||
|
|
1e3f5482d0 | ||
|
|
0a45be54c4 | ||
|
|
b5bc2a7374 | ||
|
|
3666b89add | ||
|
|
23f9e747c1 | ||
|
|
c77895066a | ||
|
|
c98017dbe2 | ||
|
|
657e3d47d0 | ||
|
|
4d34e4358a | ||
|
|
6fcd6beb84 | ||
|
|
98b3a9828a | ||
|
|
137b73af4e | ||
|
|
dd1bda5066 | ||
|
|
7bc7a90a09 | ||
|
|
91d13c7239 | ||
|
|
fd6ba1820a | ||
|
|
fb61777024 | ||
|
|
2519eb573f | ||
|
|
8a3338b078 | ||
|
|
b03ae0d765 | ||
|
|
97c652e3b0 | ||
|
|
301af71228 | ||
|
|
60d4f05743 | ||
|
|
464972126c | ||
|
|
c1392bc190 | ||
|
|
921aed0fae | ||
|
|
59d90e0bb1 | ||
|
|
e3fb6bb1a8 | ||
|
|
8103f5fd43 | ||
|
|
70f5681797 | ||
|
|
5ee02e954e | ||
|
|
23b2b49663 | ||
|
|
311ed493b4 | ||
|
|
9d8b3c0c36 | ||
|
|
f3f268388b | ||
|
|
8d0effe327 | ||
|
|
19455099ff | ||
|
|
6e754d7e4f | ||
|
|
ab6fa76303 | ||
|
|
93fc4b0151 |
No files matched your search
+1
-1
@@ -1,5 +1,5 @@
|
||||
language: objective-c
|
||||
osx_image: xcode8
|
||||
osx_image: xcode9
|
||||
before_install:
|
||||
- brew update
|
||||
script: make ci
|
||||
@@ -1,3 +1,77 @@
|
||||
# 1.19.0
|
||||
|
||||
* Refactoring of downloader code to avoid deprecated methods (Deadpikle)
|
||||
* Changes to which methods run on the main thread.
|
||||
Note: some delegate methods may be called on non-main thread now. (Kornel)
|
||||
* Update Japanese localization (1024jp)
|
||||
* Update Sparkle.strings (Stefan Paychère)
|
||||
* Fix Sparkle clients polling too frequently (Jonathan Bullard)
|
||||
* Handle SecTransformExecute errors (Kornel)
|
||||
* Silence Touch Bar availability warnings on Xcode 9 by using API_AVAILABLE. Disable gnu-zero-variadic-macro-arguments to prevent warnings from use of API_AVAILABLE. (Kent Sutherland)
|
||||
* 10.11 SDK compatibility (David Fuhrmann)
|
||||
|
||||
# 1.18.1
|
||||
|
||||
* Add optional updaterDidRelaunchApplication: method on SUUpdaterDelegate (#1115) (App Tyrant)
|
||||
* Implemented sparkle:os attribute as documented (Memphiz)
|
||||
* Additional termination detection in case kpoll fails. (fujisoft)
|
||||
* Included bin files in CocoaPods installation (Keith Smiley)
|
||||
* Updated Dutch localization (Eitot)
|
||||
* Updated German localization (Eitot)
|
||||
* Updated Japanese translation (1024jp)
|
||||
* Updated Portuguese translation (Victor)
|
||||
* Updated to Xcode 9/Swift 4
|
||||
|
||||
# 1.18.0
|
||||
|
||||
* Name of the host app is used in authorization prompt (the `SPARKLE_RELAUNCH_TOOL_NAME` setting is now obsolete)
|
||||
* More detailed progress bar for package installers (Kornel Lesiński)
|
||||
* Disabled the keyboard shortcut for the install button for scheduled updates to avoid accidental installs. (George Nachman)
|
||||
* generate_appcast tool adds release notes if there's an .html file with the same base name as the archive (Brett Walker)
|
||||
* Added `sparkle:shortVersionString` to the enclosure, #1032 (Brett Walker)
|
||||
* Fixed Japanese localization (1024jp)
|
||||
* Fixed escaping of system profile URLs
|
||||
* Added more logging in various failure cases (Kornel Lesiński)
|
||||
* Better error message for quarantined apps that can't be updated
|
||||
|
||||
# 1.17.0
|
||||
|
||||
* Added Touch Bar support (Bi11)
|
||||
* Upgraded SULog to use logging APIs that Apple provides built-in (Zorg)
|
||||
* Skip buttons are disabled if the update is marked as critical (Kornel Lesiński)
|
||||
* Background updates ask OS for lower-priority networking (Kornel Lesiński)
|
||||
* Refactorings to sync with upcoming 2.0
|
||||
* Added kqueue based termination listener (Zorg)
|
||||
* Added AppKit prevention guards to modules that shouldn't import it (Zorg)
|
||||
* Added Obj-C generics where applicable (Zorg)
|
||||
* Made SUBundleIcon & SUApplicationInfo take SUHost, not NSBundle (Zorg)
|
||||
* Improved -[SUHost objectForInfoDictionaryKey:] (Zorg)
|
||||
* Detect and fail if any two-way dependencies exist in the project (Zorg)
|
||||
* generate_appcast:
|
||||
* fixed handling of multiple directories in an archive
|
||||
* percent encode the filename used in the delta url (Brett Walker)
|
||||
* Update Sparkle.strings (BR Lingo)
|
||||
* Improved handling of non-ASCII names in delta archives (Kornel Lesiński)
|
||||
* Don't touch Info.plist unless git version changes (Václav Slavík)
|
||||
|
||||
# 1.16.0
|
||||
|
||||
* Guided package installs are now the default for updating packages (Zorg)
|
||||
- `pkg` installers won't show any UI. If you require the old behavior of showing a full installer window, rename the `*.pkg` file to `*.sparkle_interactive.pkg`
|
||||
* Previous version of the app is now deleted instead of staying in the trash (Zorg)
|
||||
* Added `generate_appcast` helper tool (Kornel Lesiński)
|
||||
* Made manual check resume pending automatic updates instead of starting a new update (Kornel Lesiński)
|
||||
* Started using `length` value from RSS if HTTP doesn't give one (Zorg)
|
||||
* Hidden automatic updates checkbox for information only updates (Bi11)
|
||||
* Added progressbar for DMG and binary delta extraction (Kornel Lesiński)
|
||||
* Fixed showing of download status if we attempt a 2nd download (Zorg)
|
||||
* Refactorings to sync with upcoming 2.0
|
||||
* Decoupled and simplified installation code using protocols (Zorg)
|
||||
* Added nullability annotations (Zorg)
|
||||
* Allowed delegate methods that return an object to return nil (Zorg)
|
||||
* Decreased responsibility of SUHost and moved code into other components (Zorg)
|
||||
* Removed Sparkle.pch and many file #includes (Zorg)
|
||||
|
||||
# 1.15.0
|
||||
|
||||
* A new icon! Thanks to 1024jp
|
||||
|
||||
@@ -16,15 +16,13 @@ SPARKLE_AUTOMATED_DOWNGRADES = 0
|
||||
SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME = 0
|
||||
|
||||
SPARKLE_VERSION_MAJOR = 1
|
||||
SPARKLE_VERSION_MINOR = 15
|
||||
SPARKLE_VERSION_MINOR = 19
|
||||
SPARKLE_VERSION_PATCH = 1
|
||||
SPARKLE_VERSION = $(SPARKLE_VERSION_MAJOR).$(SPARKLE_VERSION_MINOR).$(SPARKLE_VERSION_PATCH)
|
||||
|
||||
CURRENT_PROJECT_VERSION = $(SPARKLE_VERSION)
|
||||
ALWAYS_SEARCH_USER_PATHS = NO
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES
|
||||
GCC_PRECOMPILE_PREFIX_HEADER = YES
|
||||
GCC_PREFIX_HEADER = Sparkle/Sparkle.pch
|
||||
GCC_SYMBOLS_PRIVATE_EXTERN = YES
|
||||
GCC_INLINES_ARE_PRIVATE_EXTERN = YES
|
||||
ARCHS = $(ARCHS_STANDARD)
|
||||
@@ -90,4 +88,4 @@ CLANG_ENABLE_MODULES[sdk=macosx10.8] = NO
|
||||
WARNING_CFLAGS_EXTRA = -Wno-custom-atomic-properties -Wno-implicit-atomic-properties
|
||||
|
||||
// Turn on all warnings, then disable a few which are almost impossible to avoid
|
||||
WARNING_CFLAGS = -Wall -Weverything -Wno-unused-macros -Wno-gnu-statement-expression -Wno-arc-repeated-use-of-weak -Wno-auto-import $(WARNING_CFLAGS_EXTRA)
|
||||
WARNING_CFLAGS = -Wall -Weverything -Wno-unused-macros -Wno-gnu-statement-expression -Wno-arc-repeated-use-of-weak -Wno-auto-import -Wno-gnu-zero-variadic-macro-arguments $(WARNING_CFLAGS_EXTRA)
|
||||
@@ -1,4 +1,10 @@
|
||||
#include "ConfigCommonDebug.xcconfig"
|
||||
|
||||
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
|
||||
CLANG_WARN_COMMA = YES;
|
||||
CLANG_WARN_INFINITE_RECURSION = YES;
|
||||
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
|
||||
CLANG_WARN_STRICT_PROTOTYPES = YES;
|
||||
CLANG_WARN_SUSPICIOUS_MOVE = YES;
|
||||
GCC_GENERATE_TEST_COVERAGE_FILES = YES
|
||||
GCC_INSTRUMENT_PROGRAM_FLOW_ARCS = YES
|
||||
@@ -2,8 +2,13 @@
|
||||
|
||||
// Debug only
|
||||
|
||||
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
|
||||
CLANG_WARN_COMMA = YES;
|
||||
CLANG_WARN_INFINITE_RECURSION = YES;
|
||||
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
|
||||
CLANG_WARN_STRICT_PROTOTYPES = YES;
|
||||
CLANG_WARN_SUSPICIOUS_MOVE = YES;
|
||||
GCC_OPTIMIZATION_LEVEL = 0
|
||||
SWIFT_OPTIMIZATION_LEVEL = -Onone
|
||||
DEBUG_INFORMATION_FORMAT = dwarf
|
||||
ENABLE_TESTABILITY = YES
|
||||
GCC_GENERATE_DEBUGGING_SYMBOLS = YES
|
||||
|
||||
@@ -2,8 +2,13 @@
|
||||
|
||||
// Release only
|
||||
|
||||
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
|
||||
CLANG_WARN_COMMA = YES;
|
||||
CLANG_WARN_INFINITE_RECURSION = YES;
|
||||
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
|
||||
CLANG_WARN_STRICT_PROTOTYPES = YES;
|
||||
CLANG_WARN_SUSPICIOUS_MOVE = YES;
|
||||
GCC_OPTIMIZATION_LEVEL = s
|
||||
SWIFT_OPTIMIZATION_LEVEL = -Ofast
|
||||
DEBUG_INFORMATION_FORMAT = dwarf-with-dsym
|
||||
GCC_GENERATE_DEBUGGING_SYMBOLS = YES
|
||||
GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS_COMMON)
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
// Generate Appcast only
|
||||
|
||||
#include "ConfigSwift.xcconfig"
|
||||
|
||||
SWIFT_OBJC_BRIDGING_HEADER = generate_appcast/Appcast-Bridging-Header.h
|
||||
MACOSX_DEPLOYMENT_TARGET = 10.11
|
||||
PRODUCT_NAME = generate_appcast
|
||||
@@ -0,0 +1,4 @@
|
||||
// Generate Appcast Debug
|
||||
|
||||
#include "ConfigGenerateAppcast.xcconfig"
|
||||
#include "ConfigSwiftDebug.xcconfig"
|
||||
@@ -0,0 +1,4 @@
|
||||
// Generate Appcast Release
|
||||
|
||||
#include "ConfigGenerateAppcast.xcconfig"
|
||||
#include "ConfigSwiftRelease.xcconfig"
|
||||
@@ -1 +1,2 @@
|
||||
SWIFT_VERSION = 3.0
|
||||
SWIFT_VERSION = 4.0
|
||||
SWIFT_SWIFT3_OBJC_INFERENCE = Off;
|
||||
@@ -1 +1 @@
|
||||
SWIFT_OPTIMIZATION_LEVEL = -Ofast
|
||||
SWIFT_OPTIMIZATION_LEVEL = -Owholemodule
|
||||
@@ -2,11 +2,13 @@
|
||||
set -e
|
||||
|
||||
if [ "$ACTION" = "" ] ; then
|
||||
# Sanity check that the Podspec version matches the Sparkle version
|
||||
spec_version=$(printf "require 'cocoapods'\nspec = %s\nprint spec.version" "$(cat "$SRCROOT/Sparkle.podspec")" | LANG=en_US.UTF-8 ruby)
|
||||
if [ "$spec_version" != "$CURRENT_PROJECT_VERSION" ] ; then
|
||||
echo "podspec version '$spec_version' does not match the current project version '$CURRENT_PROJECT_VERSION'" >&2
|
||||
exit 1
|
||||
# If using cocoapods, sanity check that the Podspec version matches the Sparkle version
|
||||
if [ -x "$(command -v pod)" ]; then
|
||||
spec_version=$(printf "require 'cocoapods'\nspec = %s\nprint spec.version" "$(cat "$SRCROOT/Sparkle.podspec")" | LANG=en_US.UTF-8 ruby)
|
||||
if [ "$spec_version" != "$CURRENT_PROJECT_VERSION" ] ; then
|
||||
echo "podspec version '$spec_version' does not match the current project version '$CURRENT_PROJECT_VERSION'" >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
rm -rf "$CONFIGURATION_BUILD_DIR/staging"
|
||||
@@ -16,6 +18,7 @@ if [ "$ACTION" = "" ] ; then
|
||||
cp "$SRCROOT/CHANGELOG" "$SRCROOT/LICENSE" "$SRCROOT/Resources/SampleAppcast.xml" "$CONFIGURATION_BUILD_DIR/staging"
|
||||
cp -R "$SRCROOT/bin" "$CONFIGURATION_BUILD_DIR/staging"
|
||||
cp "$CONFIGURATION_BUILD_DIR/BinaryDelta" "$CONFIGURATION_BUILD_DIR/staging/bin"
|
||||
cp "$CONFIGURATION_BUILD_DIR/generate_appcast" "$CONFIGURATION_BUILD_DIR/staging/bin"
|
||||
cp -R "$CONFIGURATION_BUILD_DIR/Sparkle Test App.app" "$CONFIGURATION_BUILD_DIR/staging"
|
||||
cp -R "$CONFIGURATION_BUILD_DIR/Sparkle.framework" "$CONFIGURATION_BUILD_DIR/staging"
|
||||
|
||||
@@ -23,6 +26,7 @@ if [ "$ACTION" = "" ] ; then
|
||||
# because missing dSYMs in a release build SHOULD trigger a build failure
|
||||
if [ "$CONFIGURATION" = "Release" ] ; then
|
||||
cp -R "$CONFIGURATION_BUILD_DIR/BinaryDelta.dSYM" "$CONFIGURATION_BUILD_DIR/staging/bin"
|
||||
cp -R "$CONFIGURATION_BUILD_DIR/generate_appcast.dSYM" "$CONFIGURATION_BUILD_DIR/staging/bin"
|
||||
cp -R "$CONFIGURATION_BUILD_DIR/Sparkle Test App.app.dSYM" "$CONFIGURATION_BUILD_DIR/staging"
|
||||
cp -R "$CONFIGURATION_BUILD_DIR/Sparkle.framework.dSYM" "$CONFIGURATION_BUILD_DIR/staging"
|
||||
fi
|
||||
|
||||
@@ -30,5 +30,11 @@ fi
|
||||
|
||||
# and use it to set the CFBundleShortVersionString value
|
||||
export PATH="$PATH:/usr/libexec"
|
||||
PlistBuddy -c "Set :CFBundleShortVersionString '$version'" \
|
||||
"$BUILT_PRODUCTS_DIR/$INFOPLIST_PATH"
|
||||
|
||||
if [ -f "$BUILT_PRODUCTS_DIR/$INFOPLIST_PATH" ] ; then
|
||||
oldversion=$(PlistBuddy -c "Print :CFBundleShortVersionString" "$BUILT_PRODUCTS_DIR/$INFOPLIST_PATH")
|
||||
fi
|
||||
if [ "$version" != "$oldversion" ] ; then
|
||||
PlistBuddy -c "Set :CFBundleShortVersionString '$version'" \
|
||||
"$BUILT_PRODUCTS_DIR/$INFOPLIST_PATH"
|
||||
fi
|
||||
@@ -1,6 +1,7 @@
|
||||
Copyright (c) 2006-2013 Andy Matuschak.
|
||||
Copyright (c) 2009-2013 Elgato Systems GmbH.
|
||||
Copyright (c) 2011-2014 Kornel Lesiński.
|
||||
Copyright (c) 2015-2017 Mayur Pawashe.
|
||||
Copyright (c) 2014 C.W. Betts.
|
||||
Copyright (c) 2014 Petroules Corporation.
|
||||
Copyright (c) 2014 Big Nerd Ranch.
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
.PHONY: all localizable-strings release build test ci
|
||||
|
||||
all: build
|
||||
|
||||
ifndef BUILDDIR
|
||||
BUILDDIR := $(shell mktemp -d "$(TMPDIR)/Sparkle.XXXXXX")
|
||||
endif
|
||||
@@ -21,6 +23,7 @@ build:
|
||||
|
||||
test:
|
||||
xcodebuild -scheme Distribution -configuration Debug test
|
||||
./objc_dep/objc_dep.py -t .
|
||||
|
||||
uitest:
|
||||
xcodebuild -scheme UITests -configuration Debug test
|
||||
@@ -31,7 +34,7 @@ ci:
|
||||
( rm -rf build && xcodebuild -sdk "macosx10.$$i" -scheme Distribution -configuration Coverage -derivedDataPath build ) || exit 1 ; \
|
||||
fi ; \
|
||||
done
|
||||
for i in {10..11} ; do \
|
||||
for i in {10..12} ; do \
|
||||
if xcrun --sdk "macosx10.$$i" --show-sdk-path 2> /dev/null ; then \
|
||||
( rm -rf build && xcodebuild -sdk "macosx10.$$i" -scheme Distribution -configuration Coverage -derivedDataPath build test ) || exit 1 ; \
|
||||
fi ; \
|
||||
|
||||
+26
-24
@@ -1,54 +1,56 @@
|
||||
# Sparkle [](https://travis-ci.org/sparkle-project/Sparkle) [](https://github.com/Carthage/Carthage) []() <a href="https://www.stackpath.com/?utm_source=sparkle-github&utm_medium=badge&utm_campaign=readme"><img src="https://img.shields.io/badge/sponsored%20by-StackPath-orange.svg" alt="sponsored by: StackPath"></a>
|
||||
|
||||
An easy-to-use software update framework for Cocoa developers.
|
||||
Secure and reliable software update framework for Cocoa developers.
|
||||
|
||||
<img src="Resources/Screenshot.png" width="732" alt="Sparkle shows familiar update window with release notes">
|
||||
|
||||
## Features
|
||||
|
||||
* Seamless. There's no mention of Sparkle; your icons and app name are used.
|
||||
* Secure. Updates are verified using DSA signatures and Apple Code Signing.
|
||||
* Fast. Supports delta updates which only patch files that have changed.
|
||||
* Easy to install. Sparkle requires no code in your app, and only needs static files on a web server.
|
||||
* Supports bundles, preference panes, plugins, and other non-.app software. Can install .pkg files for more complicated products.
|
||||
* Handles permissions, quarantine and automatically asks for authentication if needed.
|
||||
* Uses RSS-based appcasts for release information. Appcasts are a de-facto standard supported by 3rd party update-tracking programs and websites.
|
||||
* Sparkle stays hidden until second launch for better first impressions.
|
||||
* Truly self-updating — the user can choose to automatically download and install all updates in the background.
|
||||
|
||||
## Changes since 1.5b
|
||||
|
||||
* Up-to-date with 10.11 SDK and Xcode 7. Supports macOS 10.7+.
|
||||
* Compatibilty with macOS Sierra.
|
||||
* Up-to-date with 10.12 SDK and Xcode 8 (supports macOS 10.7+).
|
||||
* Important security fixes.
|
||||
* Cleaned up and modernized code, using ARC and Autolayout.
|
||||
* Truly automatic background updates (no UI at all) when user agreed to "Automatically download and install updates in the future."
|
||||
* Upgraded and more reliable binary delta and code signing verification.
|
||||
* Ability to mark updates as critical.
|
||||
* Progress and status notifications for the host app.
|
||||
* Name of finish_installation.app can be configured to match your app's name.
|
||||
* Upgraded and more reliable binary delta and code signing verification.
|
||||
|
||||
## Features
|
||||
|
||||
* Seamless integration—there's no mention of Sparkle; your icons and app name are used.
|
||||
* True self-updating—the user can choose to automatically download and install all updates.
|
||||
* Displays a detailed progress window to the user.
|
||||
* Supports authentication for installing in secure locations.
|
||||
* Supports Apple Code Signing and DSA signatures for ultra-secure updates.
|
||||
* Easy to install. Sparkle requires no code in your app, so it's trivial to upgrade or remove the framework.
|
||||
* Uses RSS-based appcasts for release information. Appcasts are supported by 3rd party update-tracking programs and websites.
|
||||
* Displays release notes to the user via WebKit.
|
||||
* Sparkle doesn't bug the user until second launch for better first impressions.
|
||||
* Deep delegate support to make Sparkle work exactly as you need.
|
||||
* Optionally sends system information to the server when checking for updates.
|
||||
* Supports bundles, preference panes, plugins, and other non-.app software. Can install .pkg files for more complicated products.
|
||||
* Supports branches due to minimum OS version requirements.
|
||||
|
||||
## Requirements
|
||||
|
||||
* Runtime: macOS 10.7 or greater
|
||||
* Build: Xcode 5 and 10.8 SDK or greater
|
||||
* Build: Xcode 7 and 10.8 SDK or greater
|
||||
* HTTPS server for serving updates (see [App Transport Security](http://sparkle-project.org/documentation/app-transport-security/))
|
||||
|
||||
## API
|
||||
## Usage
|
||||
|
||||
See [getting started guide](https://sparkle-project.org/documentation/). No code is necessary, but a bit of Xcode configuration is required.
|
||||
|
||||
## Development
|
||||
|
||||
### API symbols
|
||||
|
||||
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.
|
||||
|
||||
## Code of Conduct
|
||||
### Code of Conduct
|
||||
|
||||
We pledge to have an open and welcoming environment. See our [Code of Conduct](CODE_OF_CONDUCT.md).
|
||||
|
||||
|
||||
+2
-1
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = "Sparkle"
|
||||
s.version = "1.15.1"
|
||||
s.version = "1.19.1"
|
||||
s.summary = "A software update framework for macOS"
|
||||
s.description = "Sparkle is an easy-to-use software update framework for Cocoa developers."
|
||||
s.homepage = "http://sparkle-project.org"
|
||||
@@ -22,6 +22,7 @@ Pod::Spec.new do |s|
|
||||
s.source = { :http => "https://github.com/sparkle-project/Sparkle/releases/download/#{s.version}/Sparkle-#{s.version}.tar.bz2" }
|
||||
s.source_files = 'Sparkle.framework/Versions/A/Headers/*.h'
|
||||
|
||||
s.preserve_paths = 'bin/*'
|
||||
s.public_header_files = 'Sparkle.framework/Versions/A/Headers/*.h'
|
||||
s.vendored_frameworks = 'Sparkle.framework'
|
||||
s.xcconfig = {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0800"
|
||||
LastUpgradeVersion = "0920"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
@@ -26,6 +26,7 @@
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
language = ""
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
@@ -55,6 +56,7 @@
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = ""
|
||||
selectedLauncherIdentifier = "Xcode.IDEFoundation.Launcher.PosixSpawn"
|
||||
language = ""
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0800"
|
||||
LastUpgradeVersion = "0920"
|
||||
version = "2.0">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
@@ -26,6 +26,7 @@
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
language = ""
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
@@ -55,6 +56,7 @@
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = ""
|
||||
selectedLauncherIdentifier = "Xcode.IDEFoundation.Launcher.PosixSpawn"
|
||||
language = ""
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0800"
|
||||
LastUpgradeVersion = "0920"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
@@ -10,6 +10,7 @@
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
language = ""
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
@@ -30,6 +31,7 @@
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
language = ""
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0920"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "5AA96C541E0AE0DB00CA4346"
|
||||
BuildableName = "generate_appcast"
|
||||
BlueprintName = "generate_appcast"
|
||||
ReferencedContainer = "container:Sparkle.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
language = ""
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
</Testables>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "5AA96C541E0AE0DB00CA4346"
|
||||
BuildableName = "generate_appcast"
|
||||
BlueprintName = "generate_appcast"
|
||||
ReferencedContainer = "container:Sparkle.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Release"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
language = ""
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "5AA96C541E0AE0DB00CA4346"
|
||||
BuildableName = "generate_appcast"
|
||||
BlueprintName = "generate_appcast"
|
||||
ReferencedContainer = "container:Sparkle.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "5AA96C541E0AE0DB00CA4346"
|
||||
BuildableName = "generate_appcast"
|
||||
BlueprintName = "generate_appcast"
|
||||
ReferencedContainer = "container:Sparkle.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
Vendored
+20
@@ -0,0 +1,20 @@
|
||||
//
|
||||
// AppKitPrevention.h
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Mayur Pawashe on 1/17/17.
|
||||
// Copyright © 2017 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
// #include (not #import) this header to prevent AppKit from being imported
|
||||
// Note this should be your LAST #include in your implementation file
|
||||
|
||||
// If this error is triggered, you can have Xcode indicate to you which source file including this header caused the issue
|
||||
|
||||
// One may wonder for certain targets where AppKit is banned completely, why just not link AppKit instead.
|
||||
// Well, Xcode has thing called auto-linking that I don't trust very much.
|
||||
// Even after trying to disable the setting, I've had targets able to link to AppKit without AppKit being specified in the list of linked libraries.
|
||||
|
||||
#ifdef _APPKITDEFINES_H
|
||||
#error This is a core or daemon-safe module and should NOT import AppKit
|
||||
#endif
|
||||
Vendored
+85
-103
@@ -1,70 +1,16 @@
|
||||
#import <AppKit/AppKit.h>
|
||||
#import <Cocoa/Cocoa.h>
|
||||
#import "SULocalizations.h"
|
||||
#import "SUErrors.h"
|
||||
#import "SUInstaller.h"
|
||||
#import "SUHost.h"
|
||||
#import "SUStandardVersionComparator.h"
|
||||
#import "SUStatusController.h"
|
||||
#import "SULog.h"
|
||||
#import "SUInstallerProtocol.h"
|
||||
#import "TerminationListener.h"
|
||||
|
||||
#include <unistd.h>
|
||||
|
||||
/*!
|
||||
* Time this app uses to recheck if the parent has already died.
|
||||
*/
|
||||
static const NSTimeInterval SUParentQuitCheckInterval = .25;
|
||||
|
||||
@interface TerminationListener : NSObject
|
||||
|
||||
- (instancetype)initWithProcessId:(pid_t)pid;
|
||||
|
||||
@end
|
||||
|
||||
@interface TerminationListener ()
|
||||
|
||||
@property (nonatomic, assign) pid_t processIdentifier;
|
||||
@property (nonatomic, strong) NSTimer *watchdogTimer;
|
||||
|
||||
@end
|
||||
|
||||
@implementation TerminationListener
|
||||
|
||||
@synthesize processIdentifier = _processIdentifier;
|
||||
@synthesize watchdogTimer = _watchdogTimer;
|
||||
|
||||
- (instancetype)initWithProcessId:(pid_t)pid
|
||||
{
|
||||
if (!(self = [super init])) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
self.processIdentifier = pid;
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)cleanupWithCompletion:(void (^)(void))completionBlock
|
||||
{
|
||||
[self.watchdogTimer invalidate];
|
||||
completionBlock();
|
||||
}
|
||||
|
||||
- (void)startListeningWithCompletion:(void (^)(void))completionBlock
|
||||
{
|
||||
BOOL alreadyTerminated = (getppid() == 1); // ppid is launchd (1) => parent terminated already
|
||||
if (alreadyTerminated)
|
||||
[self cleanupWithCompletion:completionBlock];
|
||||
else
|
||||
self.watchdogTimer = [NSTimer scheduledTimerWithTimeInterval:SUParentQuitCheckInterval target:self selector:@selector(watchdog:) userInfo:completionBlock repeats:YES];
|
||||
}
|
||||
|
||||
- (void)watchdog:(NSTimer *)timer
|
||||
{
|
||||
if (![NSRunningApplication runningApplicationWithProcessIdentifier:self.processIdentifier]) {
|
||||
[self cleanupWithCompletion:timer.userInfo];
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
/*!
|
||||
* If the Installation takes longer than this time the Application Icon is shown in the Dock so that the user has some feedback.
|
||||
*/
|
||||
@@ -125,7 +71,8 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.5;
|
||||
|
||||
self.hostPath = hostPath;
|
||||
self.relaunchPath = relaunchPath;
|
||||
self.terminationListener = [[TerminationListener alloc] initWithProcessId:parentProcessId];
|
||||
SULog(SULogLevelDefault, @"PID to listen: %d", parentProcessId);
|
||||
self.terminationListener = [[TerminationListener alloc] initWithProcessIdentifier:@(parentProcessId)];
|
||||
self.updateFolderPath = updateFolderPath;
|
||||
self.shouldRelaunch = shouldRelaunch;
|
||||
self.shouldShowUI = shouldShowUI;
|
||||
@@ -135,8 +82,13 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.5;
|
||||
|
||||
- (void)applicationDidFinishLaunching:(NSNotification __unused *)notification
|
||||
{
|
||||
[self.terminationListener startListeningWithCompletion:^{
|
||||
[self.terminationListener startListeningWithCompletion:^(BOOL terminationSuccess) {
|
||||
self.terminationListener = nil;
|
||||
|
||||
if (!terminationSuccess) {
|
||||
SULog(SULogLevelError, @"Failed to listen for application termination");
|
||||
// Continue on with the installation anyway?
|
||||
}
|
||||
|
||||
if (self.shouldShowUI) {
|
||||
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(SUInstallationTimeLimit * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
|
||||
@@ -152,56 +104,86 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.5;
|
||||
}];
|
||||
}
|
||||
|
||||
- (void)showError:(NSError *)error
|
||||
{
|
||||
if (self.shouldShowUI) {
|
||||
NSAlert *alert = [[NSAlert alloc] init];
|
||||
alert.messageText = @"";
|
||||
alert.informativeText = [NSString stringWithFormat:@"%@", [error localizedDescription]];
|
||||
[alert runModal];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)install
|
||||
{
|
||||
NSBundle *theBundle = [NSBundle bundleWithPath:self.hostPath];
|
||||
SUHost *host = [[SUHost alloc] initWithBundle:theBundle];
|
||||
NSString *installationPath = [[host installationPath] copy];
|
||||
|
||||
if (self.shouldShowUI) {
|
||||
self.statusController = [[SUStatusController alloc] initWithHost:host];
|
||||
[self.statusController setButtonTitle:SULocalizedString(@"Cancel Update", @"") target:nil action:Nil isDefault:NO];
|
||||
[self.statusController beginActionWithTitle:SULocalizedString(@"Installing update...", @"")
|
||||
maxProgressValue: 0 statusText: @""];
|
||||
[self.statusController showWindow:self];
|
||||
}
|
||||
|
||||
NSString *fileOperationToolPath = [[[[NSBundle mainBundle] executablePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@""SPARKLE_FILEOP_TOOL_NAME];
|
||||
|
||||
if (![[NSFileManager defaultManager] fileExistsAtPath:fileOperationToolPath]) {
|
||||
SULog(@"Potential Installation Error: File operation tool path %@ is not found", fileOperationToolPath);
|
||||
SULog(SULogLevelError, @"Potential Installation Error: File operation tool path %@ is not found", fileOperationToolPath);
|
||||
}
|
||||
|
||||
[SUInstaller installFromUpdateFolder:self.updateFolderPath
|
||||
overHost:host
|
||||
installationPath:installationPath
|
||||
fileOperationToolPath:fileOperationToolPath
|
||||
versionComparator:[SUStandardVersionComparator defaultComparator]
|
||||
completionHandler:^(NSError *error) {
|
||||
if (error) {
|
||||
NSError *underlyingError = [error.userInfo objectForKey:NSUnderlyingErrorKey];
|
||||
if (underlyingError == nil || underlyingError.code != SUInstallationCancelledError) {
|
||||
SULog(@"Installation Error: %@", error);
|
||||
if (self.shouldShowUI) {
|
||||
NSAlert *alert = [[NSAlert alloc] init];
|
||||
alert.messageText = @"";
|
||||
alert.informativeText = [NSString stringWithFormat:@"%@", [error localizedDescription]];
|
||||
[alert runModal];
|
||||
}
|
||||
}
|
||||
exit(EXIT_FAILURE);
|
||||
} else {
|
||||
NSString *pathToRelaunch = nil;
|
||||
// If the installation path differs from the host path, we give higher precedence for it than
|
||||
// if the desired relaunch path differs from the host path
|
||||
if (![installationPath.pathComponents isEqualToArray:self.hostPath.pathComponents] || [self.relaunchPath.pathComponents isEqualToArray:self.hostPath.pathComponents]) {
|
||||
pathToRelaunch = installationPath;
|
||||
} else {
|
||||
pathToRelaunch = self.relaunchPath;
|
||||
}
|
||||
[self cleanupAndTerminateWithPathToRelaunch:pathToRelaunch];
|
||||
}
|
||||
}];
|
||||
NSError *retrieveInstallerError = nil;
|
||||
id<SUInstallerProtocol> installer = [SUInstaller installerForHost:host fileOperationToolPath:fileOperationToolPath updateDirectory:self.updateFolderPath error:&retrieveInstallerError];
|
||||
if (installer == nil) {
|
||||
SULog(SULogLevelError, @"Retrieved Installer Error: %@", retrieveInstallerError);
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
if (self.shouldShowUI && [installer canInstallSilently]) {
|
||||
self.statusController = [[SUStatusController alloc] initWithHost:host];
|
||||
[self.statusController setButtonTitle:SULocalizedString(@"Cancel Update", @"") target:nil action:Nil isDefault:NO];
|
||||
[self.statusController beginActionWithTitle:SULocalizedString(@"Installing update...", @"")
|
||||
maxProgressValue:100 statusText: @""];
|
||||
[self.statusController showWindow:self];
|
||||
}
|
||||
|
||||
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
|
||||
NSError *initialInstallationError = nil;
|
||||
if (![installer performInitialInstallation:&initialInstallationError]) {
|
||||
SULog(SULogLevelError, @"Failed to perform initial installation with error: %@", initialInstallationError);
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[self showError:initialInstallationError];
|
||||
exit(EXIT_FAILURE);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
void(^progressBlock)(double) = ^(double progress){
|
||||
dispatch_async(dispatch_get_main_queue(), ^(){
|
||||
self.statusController.progressValue = progress * 100.0;
|
||||
});
|
||||
};
|
||||
|
||||
NSError *finalInstallationError = nil;
|
||||
if (![installer performFinalInstallationProgressBlock:progressBlock error:&finalInstallationError]) {
|
||||
NSError *underlyingError = [finalInstallationError.userInfo objectForKey:NSUnderlyingErrorKey];
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
if (underlyingError == nil || underlyingError.code != SUInstallationCancelledError) {
|
||||
SULog(SULogLevelError, @"Failed to perform final installation Error: %@", finalInstallationError);
|
||||
[self showError:finalInstallationError];
|
||||
}
|
||||
exit(EXIT_FAILURE);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
NSString *installationPath = [installer installationPath];
|
||||
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
NSString *pathToRelaunch = nil;
|
||||
// If the relaunch path is the same as the host bundle path, use the installation path from the installer which may be normalized
|
||||
// Otherwise use the requested relaunch path in all other cases
|
||||
if ([self.relaunchPath.pathComponents isEqualToArray:host.bundlePath.pathComponents]) {
|
||||
pathToRelaunch = installationPath;
|
||||
} else {
|
||||
pathToRelaunch = self.relaunchPath;
|
||||
}
|
||||
[self cleanupAndTerminateWithPathToRelaunch:pathToRelaunch];
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
- (void)cleanupAndTerminateWithPathToRelaunch:(NSString *)relaunchPath
|
||||
@@ -211,7 +193,7 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.5;
|
||||
dispatch_block_t cleanupAndExit = ^{
|
||||
NSError *theError = nil;
|
||||
if (![[NSFileManager defaultManager] removeItemAtPath:self.updateFolderPath error:&theError]) {
|
||||
SULog(@"Couldn't remove update folder: %@.", theError);
|
||||
SULog(SULogLevelError, @"Couldn't remove update folder: %@.", theError);
|
||||
}
|
||||
|
||||
[[NSFileManager defaultManager] removeItemAtPath:[[NSBundle mainBundle] bundlePath] error:NULL];
|
||||
@@ -227,7 +209,7 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.5;
|
||||
|
||||
// Don't use -launchApplication: because we may not be launching an application. Eg: it could be a system prefpane
|
||||
if (![[NSWorkspace sharedWorkspace] openFile:relaunchPath]) {
|
||||
SULog(@"Failed to launch %@", relaunchPath);
|
||||
SULog(SULogLevelError, @"Failed to launch %@", relaunchPath);
|
||||
}
|
||||
|
||||
[self.statusController close];
|
||||
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
//
|
||||
// TerminationListener.h
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Mayur Pawashe on 3/7/16.
|
||||
// Copyright © 2016 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface TerminationListener : NSObject
|
||||
|
||||
- (instancetype)initWithProcessIdentifier:(NSNumber * _Nullable)processIdentifier;
|
||||
|
||||
@property (nonatomic, readonly) BOOL terminated;
|
||||
|
||||
// If the process identifier provided was nil, then the completion block will invoke immediately with a YES success
|
||||
- (void)startListeningWithCompletion:(void (^)(BOOL success))completionBlock;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
//
|
||||
// TerminationListener.m
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Mayur Pawashe on 3/7/16.
|
||||
// Copyright © 2016 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#import "TerminationListener.h"
|
||||
#import "SULog.h"
|
||||
|
||||
#include <sys/types.h>
|
||||
#include <sys/event.h>
|
||||
#include <sys/time.h>
|
||||
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
|
||||
@interface TerminationListener ()
|
||||
|
||||
@property (nonatomic, readonly, nullable) NSNumber *processIdentifier;
|
||||
@property (nonatomic) BOOL watchedTermination;
|
||||
@property (nonatomic, copy) void (^completionBlock)(BOOL);
|
||||
|
||||
@end
|
||||
|
||||
@implementation TerminationListener
|
||||
|
||||
@synthesize completionBlock = _completionBlock;
|
||||
@synthesize processIdentifier = _processIdentifier;
|
||||
@synthesize watchedTermination = _watchedTermination;
|
||||
|
||||
- (instancetype)initWithProcessIdentifier:(NSNumber * _Nullable)processIdentifier
|
||||
{
|
||||
self = [super init];
|
||||
if (self != nil) {
|
||||
_processIdentifier = processIdentifier;
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (BOOL)terminated
|
||||
{
|
||||
return (self.watchedTermination || self.processIdentifier == nil) ? YES : (kill(self.processIdentifier.intValue, 0) != 0);
|
||||
}
|
||||
|
||||
- (void)invokeCompletionWithSuccess:(BOOL)success
|
||||
{
|
||||
if (self.completionBlock != nil) {
|
||||
self.completionBlock(success);
|
||||
self.completionBlock = nil;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)startListeningWithCompletion:(void (^)(BOOL))completionBlock
|
||||
{
|
||||
self.completionBlock = completionBlock;
|
||||
|
||||
if (self.processIdentifier == nil) {
|
||||
[self invokeCompletionWithSuccess:YES];
|
||||
return;
|
||||
}
|
||||
|
||||
// Use kqueues to determine when the process will terminate
|
||||
// As described in https://developer.apple.com/library/mac/technotes/tn2050/_index.html#//apple_ref/doc/uid/DTS10003081-CH1-SUBSECTION10
|
||||
// By using kqueues, we can stay away from using AppKit in case we ever decide to abandon it
|
||||
|
||||
pid_t processIdentifier = self.processIdentifier.intValue;
|
||||
int queue = kqueue();
|
||||
if (queue == -1) {
|
||||
SULog(SULogLevelError, @"Failed to create kqueue() due to error %d: %@", errno, @(strerror(errno)));
|
||||
[self invokeCompletionWithSuccess:NO];
|
||||
return;
|
||||
}
|
||||
|
||||
struct kevent changes;
|
||||
EV_SET(&changes, processIdentifier, EVFILT_PROC, EV_ADD | EV_RECEIPT, NOTE_EXIT, 0, NULL);
|
||||
|
||||
if (kevent(queue, &changes, 1, &changes, 1, NULL) == -1) {
|
||||
SULog(SULogLevelError, @"Failed to invoke kevent() due to error %d: %@", errno, @(strerror(errno)));
|
||||
[self invokeCompletionWithSuccess:NO];
|
||||
return;
|
||||
}
|
||||
|
||||
// We will assume this terminationListener will never be deallocated
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wcast-qual"
|
||||
CFFileDescriptorContext context = { 0, (void *)CFBridgingRetain(self), NULL, NULL, NULL };
|
||||
#pragma clang diagnostic pop
|
||||
CFFileDescriptorRef noteExitKQueueRef = CFFileDescriptorCreate(NULL, queue, true, noteExitKQueueCallback, &context);
|
||||
if (noteExitKQueueRef == NULL) {
|
||||
SULog(SULogLevelError, @"Failed to create file descriptor via CFFileDescriptorCreate()");
|
||||
CFRelease((__bridge CFTypeRef)(self));
|
||||
[self invokeCompletionWithSuccess:NO];
|
||||
return;
|
||||
}
|
||||
|
||||
CFRunLoopSourceRef runLoopSource = CFFileDescriptorCreateRunLoopSource(NULL, noteExitKQueueRef, 0);
|
||||
if (runLoopSource == NULL) {
|
||||
SULog(SULogLevelError, @"Failed to create runLoopSource via CFFileDescriptorCreateRunLoopSource()");
|
||||
CFRelease((__bridge CFTypeRef)(self));
|
||||
[self invokeCompletionWithSuccess:NO];
|
||||
return;
|
||||
}
|
||||
|
||||
CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopDefaultMode);
|
||||
CFRelease(runLoopSource);
|
||||
|
||||
CFFileDescriptorEnableCallBacks(noteExitKQueueRef, kCFFileDescriptorReadCallBack);
|
||||
|
||||
// Make sure we didn't set the listener callback to a dead PID
|
||||
// If we did, we could hang forever. To avoid this, we check if the process has terminated *after* we set up the callback
|
||||
// If we tried to do this check before setting the callback, we could run into an issue where the process can terminate after our check
|
||||
// but before setting the callback
|
||||
if ([self terminated]) {
|
||||
[self invokeCompletionWithSuccess:YES];
|
||||
}
|
||||
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
|
||||
if ([self terminated]) {
|
||||
[self invokeCompletionWithSuccess:YES];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
static void noteExitKQueueCallback(CFFileDescriptorRef file, CFOptionFlags __unused callBackTypes, void *info)
|
||||
{
|
||||
struct kevent event;
|
||||
kevent(CFFileDescriptorGetNativeDescriptor(file), NULL, 0, &event, 1, NULL);
|
||||
|
||||
TerminationListener *self = CFBridgingRelease(info);
|
||||
self.watchedTermination = YES;
|
||||
[self invokeCompletionWithSuccess:YES];
|
||||
}
|
||||
|
||||
@end
|
||||
Vendored
+29
-29
@@ -2,21 +2,21 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
func die(msg: String) {
|
||||
func die(_ msg: String) {
|
||||
print("ERROR: \(msg)")
|
||||
exit(1)
|
||||
}
|
||||
|
||||
extension NSXMLElement {
|
||||
extension XMLElement {
|
||||
convenience init(name: String, attributes: [String: String], stringValue string: String? = nil) {
|
||||
self.init(name: name, stringValue: string)
|
||||
setAttributesWithDictionary(attributes)
|
||||
setAttributesWith(attributes)
|
||||
}
|
||||
}
|
||||
|
||||
let ud = NSUserDefaults.standardUserDefaults()
|
||||
let sparkleRoot = ud.objectForKey("root") as? String
|
||||
let htmlPath = ud.objectForKey("htmlPath") as? String
|
||||
let ud = UserDefaults.standard
|
||||
let sparkleRoot = ud.object(forKey: "root") as? String
|
||||
let htmlPath = ud.object(forKey: "htmlPath") as? String
|
||||
if sparkleRoot == nil || htmlPath == nil {
|
||||
die("Missing arguments")
|
||||
}
|
||||
@@ -29,36 +29,36 @@ if enStringsDict == nil {
|
||||
let enStringsDictKeys = enStringsDict!.allKeys
|
||||
|
||||
let dirPath = NSString(string: sparkleRoot! + "/Sparkle")
|
||||
let dirContents = try! NSFileManager.defaultManager().contentsOfDirectoryAtPath(dirPath as String)
|
||||
let dirContents = try! FileManager.default.contentsOfDirectory(atPath: dirPath as String)
|
||||
let css =
|
||||
"body { font-family: sans-serif; font-size: 10pt; }" +
|
||||
"h1 { font-size: 12pt; }" +
|
||||
".missing { background-color: #FFBABA; color: #D6010E; white-space: pre; }" +
|
||||
".unused { background-color: #BDE5F8; color: #00529B; white-space: pre; }" +
|
||||
".unlocalized { background-color: #FEEFB3; color: #9F6000; white-space: pre; }"
|
||||
var html = NSXMLDocument(rootElement: NSXMLElement(name: "html"))
|
||||
html.DTD = NSXMLDTD()
|
||||
html.DTD!.name = html.rootElement()!.name
|
||||
var html = XMLDocument(rootElement: XMLElement(name: "html"))
|
||||
html.dtd = XMLDTD()
|
||||
html.dtd!.name = html.rootElement()!.name
|
||||
html.characterEncoding = "UTF-8"
|
||||
html.documentContentKind = NSXMLDocumentContentKind.XHTMLKind
|
||||
var body = NSXMLElement(name: "body")
|
||||
var head = NSXMLElement(name: "head")
|
||||
html.documentContentKind = XMLDocument.ContentKind.xhtml
|
||||
var body = XMLElement(name: "body")
|
||||
var head = XMLElement(name: "head")
|
||||
html.rootElement()!.addChild(head)
|
||||
html.rootElement()!.addChild(body)
|
||||
head.addChild(NSXMLElement(name: "meta", attributes: ["charset": html.characterEncoding!]))
|
||||
head.addChild(NSXMLElement(name: "title", stringValue: "Sparkle Localizations Report"))
|
||||
head.addChild(NSXMLElement(name: "style", stringValue: css))
|
||||
head.addChild(XMLElement(name: "meta", attributes: ["charset": html.characterEncoding!]))
|
||||
head.addChild(XMLElement(name: "title", stringValue: "Sparkle Localizations Report"))
|
||||
head.addChild(XMLElement(name: "style", stringValue: css))
|
||||
|
||||
let locale = NSLocale.currentLocale()
|
||||
let locale = Locale.current
|
||||
for dirEntry in dirContents {
|
||||
if NSString(string: dirEntry).pathExtension != "lproj" || dirEntry == "en.lproj" {
|
||||
continue
|
||||
}
|
||||
|
||||
let lang = locale.displayNameForKey(NSLocaleLanguageCode, value: NSString(string: dirEntry).stringByDeletingPathExtension)
|
||||
body.addChild(NSXMLElement(name: "h1", stringValue: "\(dirEntry) (\(lang!))"))
|
||||
let lang = (locale as NSLocale).displayName(forKey: NSLocale.Key.languageCode, value: NSString(string: dirEntry).deletingPathExtension)
|
||||
body.addChild(XMLElement(name: "h1", stringValue: "\(dirEntry) (\(lang!))"))
|
||||
|
||||
let stringsPath = NSString(string: dirPath.stringByAppendingPathComponent(dirEntry)).stringByAppendingPathComponent("Sparkle.strings")
|
||||
let stringsPath = NSString(string: dirPath.appendingPathComponent(dirEntry)).appendingPathComponent("Sparkle.strings")
|
||||
let stringsDict = NSDictionary(contentsOfFile: stringsPath)
|
||||
if stringsDict == nil {
|
||||
die("Invalid strings file \(dirEntry)")
|
||||
@@ -70,10 +70,10 @@ for dirEntry in dirContents {
|
||||
var unused: [String] = []
|
||||
|
||||
for key in enStringsDictKeys {
|
||||
let str = stringsDict?.objectForKey(key) as? String
|
||||
let str = stringsDict?.object(forKey: key) as? String
|
||||
if str == nil {
|
||||
missing.append(key as! String)
|
||||
} else if let enStr = enStringsDict?.objectForKey(key) as? String {
|
||||
} else if let enStr = enStringsDict?.object(forKey: key) as? String {
|
||||
if enStr == str {
|
||||
unlocalized.append(key as! String)
|
||||
}
|
||||
@@ -82,7 +82,7 @@ for dirEntry in dirContents {
|
||||
|
||||
let stringsDictKeys = stringsDict!.allKeys
|
||||
for key in stringsDictKeys {
|
||||
if enStringsDict?.objectForKey(key) == nil {
|
||||
if enStringsDict?.object(forKey: key) == nil {
|
||||
unused.append(key as! String)
|
||||
}
|
||||
}
|
||||
@@ -90,12 +90,12 @@ for dirEntry in dirContents {
|
||||
let sorter = { (s1: String, s2: String) -> Bool in
|
||||
return s1 < s2
|
||||
}
|
||||
missing.sortInPlace(sorter)
|
||||
unlocalized.sortInPlace(sorter)
|
||||
unused.sortInPlace(sorter)
|
||||
missing.sort(by: sorter)
|
||||
unlocalized.sort(by: sorter)
|
||||
unused.sort(by: sorter)
|
||||
|
||||
let addRow = { (prefix: String, cssClass: String, key: String) -> Void in
|
||||
body.addChild(NSXMLElement(name: "span", attributes: ["class": cssClass], stringValue: [prefix, key].joinWithSeparator(" ") + "\n"))
|
||||
body.addChild(XMLElement(name: "span", attributes: ["class": cssClass], stringValue: [prefix, key].joined(separator: " ") + "\n"))
|
||||
}
|
||||
|
||||
for key in missing {
|
||||
@@ -110,6 +110,6 @@ for dirEntry in dirContents {
|
||||
}
|
||||
|
||||
var err: NSError?
|
||||
if !html.XMLData.writeToFile(htmlPath!, atomically: true) {
|
||||
die("Can't write report: \(err)")
|
||||
if !((try? html.xmlData.write(to: URL(fileURLWithPath: htmlPath!), options: [.atomic])) != nil) {
|
||||
die("Can't write report: \(err!)")
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
//
|
||||
// SPUDownloadData.h
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Mayur Pawashe on 8/10/16.
|
||||
// Copyright © 2016 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#if __has_feature(modules)
|
||||
@import Foundation;
|
||||
#else
|
||||
#import <Foundation/Foundation.h>
|
||||
#endif
|
||||
|
||||
#import "SUExport.h"
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
/*!
|
||||
* A class for containing downloaded data along with some information about it.
|
||||
*/
|
||||
SU_EXPORT @interface SPUDownloadData : NSObject <NSSecureCoding>
|
||||
|
||||
- (instancetype)initWithData:(NSData *)data textEncodingName:(NSString * _Nullable)textEncodingName MIMEType:(NSString * _Nullable)MIMEType;
|
||||
|
||||
/*!
|
||||
* The raw data that was downloaded.
|
||||
*/
|
||||
@property (nonatomic, readonly) NSData *data;
|
||||
|
||||
/*!
|
||||
* The IANA charset encoding name if available. Eg: "utf-8"
|
||||
*/
|
||||
@property (nonatomic, readonly, nullable, copy) NSString *textEncodingName;
|
||||
|
||||
/*!
|
||||
* The MIME type if available. Eg: "text/plain"
|
||||
*/
|
||||
@property (nonatomic, readonly, nullable, copy) NSString *MIMEType;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
//
|
||||
// SPUDownloadData.m
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Mayur Pawashe on 8/10/16.
|
||||
// Copyright © 2016 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#import "SPUDownloadData.h"
|
||||
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
|
||||
static NSString *SPUDownloadDataKey = @"SPUDownloadData";
|
||||
static NSString *SPUDownloadTextEncodingKey = @"SPUDownloadTextEncoding";
|
||||
static NSString *SPUDownloadMIMETypeKey = @"SPUDownloadMIMEType";
|
||||
|
||||
@implementation SPUDownloadData
|
||||
|
||||
@synthesize data = _data;
|
||||
@synthesize textEncodingName = _textEncodingName;
|
||||
@synthesize MIMEType = _MIMEType;
|
||||
|
||||
+ (BOOL)supportsSecureCoding
|
||||
{
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (instancetype)initWithData:(NSData *)data textEncodingName:(NSString * _Nullable)textEncodingName MIMEType:(NSString *)MIMEType
|
||||
{
|
||||
self = [super init];
|
||||
if (self != nil) {
|
||||
_data = data;
|
||||
_textEncodingName = textEncodingName;
|
||||
_MIMEType = MIMEType;
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)encodeWithCoder:(NSCoder *)coder
|
||||
{
|
||||
[coder encodeObject:self.data forKey:SPUDownloadDataKey];
|
||||
|
||||
if (self.textEncodingName != nil) {
|
||||
[coder encodeObject:self.textEncodingName forKey:SPUDownloadTextEncodingKey];
|
||||
}
|
||||
|
||||
if (self.MIMEType != nil) {
|
||||
[coder encodeObject:self.MIMEType forKey:SPUDownloadMIMETypeKey];
|
||||
}
|
||||
}
|
||||
|
||||
- (nullable instancetype)initWithCoder:(NSCoder *)decoder
|
||||
{
|
||||
if (@available(macOS 10.8, *)) {
|
||||
NSData *data = [decoder decodeObjectOfClass:[NSData class] forKey:SPUDownloadDataKey];
|
||||
if (data == nil) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
NSString *textEncodingName = [decoder decodeObjectOfClass:[NSString class] forKey:SPUDownloadTextEncodingKey];
|
||||
|
||||
NSString *MIMEType = [decoder decodeObjectOfClass:[NSString class] forKey:SPUDownloadMIMETypeKey];
|
||||
|
||||
return [self initWithData:data textEncodingName:textEncodingName MIMEType:MIMEType];
|
||||
} else {
|
||||
abort(); // Not used on 10.7
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
//
|
||||
// SPUDownloader.h
|
||||
// Downloader
|
||||
//
|
||||
// Created by Mayur Pawashe on 4/1/16.
|
||||
// Copyright © 2016 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#if __has_feature(modules)
|
||||
@import Foundation;
|
||||
#else
|
||||
#import <Foundation/Foundation.h>
|
||||
#endif
|
||||
#import "SPUDownloaderProtocol.h"
|
||||
|
||||
@protocol SPUDownloaderDelegate;
|
||||
|
||||
// This object implements the protocol which we have defined. It provides the actual behavior for the service. It is 'exported' by the service to make it available to the process hosting the service over an NSXPCConnection.
|
||||
@interface SPUDownloader : NSObject <SPUDownloaderProtocol>
|
||||
|
||||
// Due to XPC remote object reasons, this delegate is strongly referenced
|
||||
// Invoke cleanup when done with this instance
|
||||
- (instancetype)initWithDelegate:(id <SPUDownloaderDelegate>)delegate;
|
||||
|
||||
@end
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
//
|
||||
// SPUDownloader.m
|
||||
// Downloader
|
||||
//
|
||||
// Created by Mayur Pawashe on 4/1/16.
|
||||
// Copyright © 2016 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#import "SPUDownloader.h"
|
||||
#import "SPUDownloaderDelegate.h"
|
||||
#import "SPULocalCacheDirectory.h"
|
||||
#import "SPUURLRequest.h"
|
||||
#import "SPUDownloadData.h"
|
||||
#import "SUErrors.h"
|
||||
#import "SPUDownloader_Private.h"
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
|
||||
@interface SPUDownloader ()
|
||||
|
||||
@end
|
||||
|
||||
@implementation SPUDownloader
|
||||
|
||||
@synthesize delegate = _delegate;
|
||||
@synthesize bundleIdentifier = _bundleIdentifier;
|
||||
@synthesize desiredFilename = _desiredFilename;
|
||||
@synthesize downloadFilename = _downloadFilename;
|
||||
@synthesize disabledAutomaticTermination = _disabledAutomaticTermination;
|
||||
@synthesize mode = _mode;
|
||||
@synthesize receivedExpectedBytes = _receivedExpectedBytes;
|
||||
|
||||
- (instancetype)initWithDelegate:(id <SPUDownloaderDelegate>)delegate
|
||||
{
|
||||
self = [super init];
|
||||
if (self != nil) {
|
||||
_delegate = delegate;
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
// Don't implement dealloc - make the client call cleanup, which is the only way to remove the reference cycle from the delegate anyway
|
||||
|
||||
- (void)startPersistentDownloadWithRequest:(SPUURLRequest *)__unused request bundleIdentifier:(NSString *)__unused bundleIdentifier desiredFilename:(NSString *)__unused desiredFilename
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
- (void)startTemporaryDownloadWithRequest:(SPUURLRequest *)__unused request
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
- (void)enableAutomaticTermination
|
||||
{
|
||||
if (self.disabledAutomaticTermination) {
|
||||
[[NSProcessInfo processInfo] enableAutomaticTermination:SUDownloadingReason];
|
||||
self.disabledAutomaticTermination = NO;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)cleanup
|
||||
{
|
||||
[self enableAutomaticTermination];
|
||||
self.delegate = nil;
|
||||
|
||||
if (self.mode == SPUDownloadModeTemporary && self.downloadFilename != nil)
|
||||
{
|
||||
[[NSFileManager defaultManager] removeItemAtPath:self.downloadFilename error:NULL];
|
||||
self.downloadFilename = nil;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)cancel
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
- (void)downloadDidFinish
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
-(void)downloadDidFinishWithData:(SPUDownloadData*)data
|
||||
{
|
||||
switch (self.mode) {
|
||||
case SPUDownloadModeTemporary:
|
||||
if (data != nil) {
|
||||
[self.delegate downloaderDidFinishWithTemporaryDownloadData:data];
|
||||
} else {
|
||||
[self.delegate downloaderDidFailWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUDownloadError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to read temporary downloaded data from %@", self.downloadFilename]}]];
|
||||
}
|
||||
break;
|
||||
case SPUDownloadModePersistent:
|
||||
[self.delegate downloaderDidFinishWithTemporaryDownloadData:nil];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
-(NSString*)getAndCleanTempDirectory
|
||||
{
|
||||
NSString *rootPersistentDownloadCachePath = [[SPULocalCacheDirectory cachePathForBundleIdentifier:self.bundleIdentifier] stringByAppendingPathComponent:@"PersistentDownloads"];
|
||||
|
||||
[SPULocalCacheDirectory removeOldItemsInDirectory:rootPersistentDownloadCachePath];
|
||||
|
||||
NSString *tempDir = [SPULocalCacheDirectory createUniqueDirectoryInDirectory:rootPersistentDownloadCachePath];
|
||||
if (tempDir == nil) {
|
||||
// Okay, something's really broken with this user's file structure.
|
||||
NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUTemporaryDirectoryError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Can't make a temporary directory for the update download at %@.", tempDir] }];
|
||||
|
||||
[self.delegate downloaderDidFailWithError:error];
|
||||
|
||||
[self cancel];
|
||||
}
|
||||
return tempDir;
|
||||
}
|
||||
|
||||
@end
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
//
|
||||
// SPUDownloaderDelegate.h
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Mayur Pawashe on 4/1/16.
|
||||
// Copyright © 2016 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#if __has_feature(modules)
|
||||
@import Foundation;
|
||||
#else
|
||||
#import <Foundation/Foundation.h>
|
||||
#endif
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@class SPUDownloadData;
|
||||
|
||||
@protocol SPUDownloaderDelegate <NSObject>
|
||||
|
||||
// This is only invoked for persistent downloads
|
||||
- (void)downloaderDidSetDestinationName:(NSString *)destinationName temporaryDirectory:(NSString *)temporaryDirectory;
|
||||
|
||||
// Under rare cases, this may be called more than once, in which case the current progress should be reset back to 0
|
||||
// This is only invoked for persistent downloads
|
||||
- (void)downloaderDidReceiveExpectedContentLength:(int64_t)expectedContentLength;
|
||||
|
||||
// This is only invoked for persistent downloads
|
||||
- (void)downloaderDidReceiveDataOfLength:(uint64_t)length;
|
||||
|
||||
// downloadData is nil if this is a persisent download, otherwise it's non-nil if it's a temporary download
|
||||
- (void)downloaderDidFinishWithTemporaryDownloadData:(SPUDownloadData * _Nullable)downloadData;
|
||||
|
||||
- (void)downloaderDidFailWithError:(NSError *)error;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
Vendored
+13
@@ -0,0 +1,13 @@
|
||||
//
|
||||
// SPUDownloaderDeprecated.h
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Deadpikle on 12/20/17.
|
||||
// Copyright © 2017 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#import "SPUDownloader.h"
|
||||
|
||||
@interface SPUDownloaderDeprecated : SPUDownloader <SPUDownloaderProtocol>
|
||||
|
||||
@end
|
||||
Vendored
+167
@@ -0,0 +1,167 @@
|
||||
//
|
||||
// SPUDownloaderDeprecated.m
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Deadpikle on 12/20/17.
|
||||
// Copyright © 2017 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#import "SPUDownloaderDeprecated.h"
|
||||
#import "SPUURLRequest.h"
|
||||
#import "SPUDownloader_Private.h"
|
||||
#import "SPUDownloadData.h"
|
||||
#import "SPULocalCacheDirectory.h"
|
||||
#import "SUErrors.h"
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
|
||||
@interface SPUDownloaderDeprecated () <NSURLDownloadDelegate>
|
||||
|
||||
@property (nonatomic) NSURLDownload *download;
|
||||
@property (nonatomic) NSURLResponse *response;
|
||||
|
||||
@end
|
||||
|
||||
@implementation SPUDownloaderDeprecated
|
||||
|
||||
@synthesize download = _download;
|
||||
@synthesize response = _response;
|
||||
|
||||
- (void)startPersistentDownloadWithRequest:(SPUURLRequest *)request bundleIdentifier:(NSString *)bundleIdentifier desiredFilename:(NSString *)desiredFilename
|
||||
{
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
if (self.download == nil && self.delegate != nil) {
|
||||
// Prevent service from automatically terminating while downloading the update asynchronously without any reply blocks
|
||||
[[NSProcessInfo processInfo] disableAutomaticTermination:SUDownloadingReason];
|
||||
self.disabledAutomaticTermination = YES;
|
||||
|
||||
self.mode = SPUDownloadModePersistent;
|
||||
self.desiredFilename = desiredFilename;
|
||||
self.bundleIdentifier = bundleIdentifier;
|
||||
|
||||
self.download = [[NSURLDownload alloc] initWithRequest:request.request delegate:self];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
- (void)startTemporaryDownloadWithRequest:(SPUURLRequest *)request
|
||||
{
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
if (self.download == nil && self.delegate != nil) {
|
||||
// Prevent service from automatically terminating while downloading the update asynchronously without any reply blocks
|
||||
[[NSProcessInfo processInfo] disableAutomaticTermination:SUDownloadingReason];
|
||||
self.disabledAutomaticTermination = YES;
|
||||
|
||||
self.mode = SPUDownloadModeTemporary;
|
||||
self.download = [[NSURLDownload alloc] initWithRequest:request.request delegate:self];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
- (void)download:(NSURLDownload *)__unused d decideDestinationWithSuggestedFilename:(NSString *)name
|
||||
{
|
||||
if (self.mode == SPUDownloadModeTemporary) {
|
||||
// Files downloaded in temporary mode should not last for very long,
|
||||
// so it's ideal to place them in a system temporary directory
|
||||
NSString *destinationFilename = NSTemporaryDirectory();
|
||||
if (destinationFilename) {
|
||||
destinationFilename = [destinationFilename stringByAppendingPathComponent:name];
|
||||
|
||||
[self.download setDestination:destinationFilename allowOverwrite:NO];
|
||||
}
|
||||
} else {
|
||||
NSString *tempDir = [super getAndCleanTempDirectory];
|
||||
|
||||
if (tempDir != nil) {
|
||||
NSString *downloadFileName = self.desiredFilename;
|
||||
NSString *downloadFileNameDirectory = [tempDir stringByAppendingPathComponent:downloadFileName];
|
||||
|
||||
NSError *createError = nil;
|
||||
if (![[NSFileManager defaultManager] createDirectoryAtPath:downloadFileNameDirectory withIntermediateDirectories:NO attributes:nil error:&createError]) {
|
||||
NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUTemporaryDirectoryError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Can't make a download file name %@ directory inside temporary directory for the update download at %@.", downloadFileName, downloadFileNameDirectory] }];
|
||||
|
||||
[self.delegate downloaderDidFailWithError:error];
|
||||
} else {
|
||||
[self.download setDestination:[downloadFileNameDirectory stringByAppendingPathComponent:name] allowOverwrite:YES];
|
||||
|
||||
[self.delegate downloaderDidSetDestinationName:name temporaryDirectory:downloadFileNameDirectory];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
- (void)download:(NSURLDownload *)__unused aDownload didCreateDestination:(NSString *)path
|
||||
{
|
||||
self.downloadFilename = path;
|
||||
}
|
||||
|
||||
- (void)download:(NSURLDownload *)__unused download didReceiveResponse:(NSURLResponse *)response
|
||||
{
|
||||
self.response = response;
|
||||
|
||||
if (self.mode == SPUDownloadModePersistent) {
|
||||
// It might be tempting to send over the response object instead of the expected content length but this isn't a good idea
|
||||
// For one, we are only ever concerned about the expected content length
|
||||
// Another reason is that NSURLResponse doesn't support NSSecureCoding in older OS releases (eg: 10.8), which cause issues with XPC
|
||||
[self.delegate downloaderDidReceiveExpectedContentLength:response.expectedContentLength];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)download:(NSURLDownload *)__unused download didReceiveDataOfLength:(NSUInteger)length
|
||||
{
|
||||
if (self.mode == SPUDownloadModePersistent) {
|
||||
[self.delegate downloaderDidReceiveDataOfLength:length];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)downloadDidFinish:(NSURLDownload *)__unused d
|
||||
{
|
||||
[self downloadDidFinish];
|
||||
}
|
||||
|
||||
- (void)download:(NSURLDownload *)__unused download didFailWithError:(NSError *)error
|
||||
{
|
||||
self.download = nil;
|
||||
[self.delegate downloaderDidFailWithError:error];
|
||||
[self cleanup];
|
||||
}
|
||||
|
||||
- (BOOL)download:(NSURLDownload *)__unused download shouldDecodeSourceDataOfMIMEType:(NSString *)encodingType
|
||||
{
|
||||
// We don't want the download system to extract our gzips for persistent downloads
|
||||
// Note that we use a substring matching here instead of direct comparison because the docs say "application/gzip" but the system *uses* "application/x-gzip". This is a documentation bug.
|
||||
return (self.mode == SPUDownloadModeTemporary || [encodingType rangeOfString:@"gzip"].location == NSNotFound);
|
||||
}
|
||||
|
||||
- (void)downloadDidFinish
|
||||
{
|
||||
assert(self.response != nil);
|
||||
assert(self.downloadFilename != nil);
|
||||
|
||||
SPUDownloadData *downloadData = nil;
|
||||
if (self.mode == SPUDownloadModeTemporary) {
|
||||
NSData *data = [NSData dataWithContentsOfFile:self.downloadFilename];
|
||||
if (data != nil) {
|
||||
downloadData = [[SPUDownloadData alloc] initWithData:data textEncodingName:self.response.textEncodingName MIMEType:self.response.MIMEType];
|
||||
}
|
||||
}
|
||||
|
||||
self.download = nil;
|
||||
|
||||
[super downloadDidFinishWithData:downloadData];
|
||||
}
|
||||
|
||||
-(void)cleanup
|
||||
{
|
||||
[self.download cancel];
|
||||
self.download = nil;
|
||||
self.response = nil;
|
||||
[super cleanup];
|
||||
}
|
||||
|
||||
- (void)cancel
|
||||
{
|
||||
[self cleanup];
|
||||
}
|
||||
|
||||
@end
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
//
|
||||
// SPUDownloaderProtocol.h
|
||||
// PersistentDownloader
|
||||
//
|
||||
// Created by Mayur Pawashe on 4/1/16.
|
||||
// Copyright © 2016 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#if __has_feature(modules)
|
||||
@import Foundation;
|
||||
#else
|
||||
#import <Foundation/Foundation.h>
|
||||
#endif
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@class SPUURLRequest;
|
||||
|
||||
// The protocol that this service will vend as its API. This header file will also need to be visible to the process hosting the service.
|
||||
@protocol SPUDownloaderProtocol
|
||||
|
||||
- (void)startPersistentDownloadWithRequest:(SPUURLRequest *)request bundleIdentifier:(NSString *)bundleIdentifier desiredFilename:(NSString *)desiredFilename;
|
||||
|
||||
- (void)startTemporaryDownloadWithRequest:(SPUURLRequest *)request;
|
||||
|
||||
- (void)downloadDidFinish;
|
||||
|
||||
- (void)cleanup;
|
||||
|
||||
- (void)cancel;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
Vendored
+20
@@ -0,0 +1,20 @@
|
||||
//
|
||||
// SPUDownloaderSession.h
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Deadpikle on 12/20/17.
|
||||
// Copyright © 2017 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#if __has_feature(modules)
|
||||
@import Foundation;
|
||||
#else
|
||||
#import <Foundation/Foundation.h>
|
||||
#endif
|
||||
#import "SPUDownloader.h"
|
||||
#import "SPUDownloaderProtocol.h"
|
||||
|
||||
NS_CLASS_AVAILABLE(NSURLSESSION_AVAILABLE, 7_0)
|
||||
@interface SPUDownloaderSession : SPUDownloader <SPUDownloaderProtocol>
|
||||
|
||||
@end
|
||||
Vendored
+167
@@ -0,0 +1,167 @@
|
||||
//
|
||||
// SPUDownloaderSession.m
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Deadpikle on 12/20/17.
|
||||
// Copyright © 2017 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#import "SPUDownloaderSession.h"
|
||||
#import "SPUURLRequest.h"
|
||||
#import "SPUDownloader_Private.h"
|
||||
#import "SPULocalCacheDirectory.h"
|
||||
#import "SUErrors.h"
|
||||
#import "SPUDownloadData.h"
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
|
||||
@interface SPUDownloaderSession () <NSURLSessionDelegate>
|
||||
|
||||
@property (nonatomic) NSURLSession *downloadSession;
|
||||
@property (nonatomic) NSURLSessionDownloadTask *download;
|
||||
|
||||
@end
|
||||
|
||||
@implementation SPUDownloaderSession
|
||||
|
||||
@synthesize downloadSession = _downloadSession;
|
||||
@synthesize download = _download;
|
||||
|
||||
- (void)startDownloadWithRequest:(SPUURLRequest *)request
|
||||
{
|
||||
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
|
||||
queue.maxConcurrentOperationCount = 1;
|
||||
self.downloadSession = [NSURLSession
|
||||
sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]
|
||||
delegate:self
|
||||
delegateQueue:queue];
|
||||
self.download = [self.downloadSession downloadTaskWithRequest:request.request];
|
||||
[self.download resume];
|
||||
}
|
||||
|
||||
- (void)startPersistentDownloadWithRequest:(SPUURLRequest *)request bundleIdentifier:(NSString *)bundleIdentifier desiredFilename:(NSString *)desiredFilename
|
||||
{
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
if (self.download == nil && self.delegate != nil) {
|
||||
// Prevent service from automatically terminating while downloading the update asynchronously without any reply blocks
|
||||
[[NSProcessInfo processInfo] disableAutomaticTermination:SUDownloadingReason];
|
||||
self.disabledAutomaticTermination = YES;
|
||||
|
||||
self.mode = SPUDownloadModePersistent;
|
||||
self.desiredFilename = desiredFilename;
|
||||
self.bundleIdentifier = bundleIdentifier;
|
||||
|
||||
[self startDownloadWithRequest:request];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
- (void)startTemporaryDownloadWithRequest:(SPUURLRequest *)request
|
||||
{
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
if (self.download == nil && self.delegate != nil) {
|
||||
// Prevent service from automatically terminating while downloading the update asynchronously without any reply blocks
|
||||
[[NSProcessInfo processInfo] disableAutomaticTermination:SUDownloadingReason];
|
||||
self.disabledAutomaticTermination = YES;
|
||||
|
||||
self.mode = SPUDownloadModeTemporary;
|
||||
[self startDownloadWithRequest:request];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
- (void)URLSession:(NSURLSession *)__unused session downloadTask:(NSURLSessionDownloadTask *)__unused downloadTask didFinishDownloadingToURL:(NSURL *)location
|
||||
{
|
||||
if (self.mode == SPUDownloadModeTemporary) {
|
||||
self.downloadFilename = location.path;
|
||||
[self downloadDidFinish]; // file is already in a system temp dir
|
||||
} else {
|
||||
NSString *tempDir = [super getAndCleanTempDirectory];
|
||||
|
||||
if (tempDir != nil) {
|
||||
NSString *downloadFileName = self.desiredFilename;
|
||||
NSString *downloadFileNameDirectory = [tempDir stringByAppendingPathComponent:downloadFileName];
|
||||
|
||||
NSError *createError = nil;
|
||||
if (![[NSFileManager defaultManager] createDirectoryAtPath:downloadFileNameDirectory withIntermediateDirectories:NO attributes:nil error:&createError]) {
|
||||
NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUTemporaryDirectoryError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Can't make a download file name %@ directory inside temporary directory for the update download at %@.", downloadFileName, downloadFileNameDirectory] }];
|
||||
|
||||
[self.delegate downloaderDidFailWithError:error];
|
||||
} else {
|
||||
NSString *name = self.download.response.suggestedFilename;
|
||||
if (!name) {
|
||||
name = location.lastPathComponent; // This likely contains nothing useful to identify the file (e.g. CFNetworkDownload_87LVIz.tmp)
|
||||
}
|
||||
NSString *toPath = [downloadFileNameDirectory stringByAppendingPathComponent:name];
|
||||
NSString *fromPath = location.path; // suppress moveItemAtPath: non-null warning
|
||||
NSError *error = nil;
|
||||
if ([[NSFileManager defaultManager] moveItemAtPath:fromPath toPath:toPath error:&error]) {
|
||||
self.downloadFilename = toPath;
|
||||
[self.delegate downloaderDidSetDestinationName:name temporaryDirectory:downloadFileNameDirectory];
|
||||
[self downloadDidFinish];
|
||||
} else {
|
||||
[self.delegate downloaderDidFailWithError:error];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
- (void)URLSession:(NSURLSession *)__unused session downloadTask:(NSURLSessionDownloadTask *)__unused downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)__unused totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
|
||||
{
|
||||
|
||||
if (self.mode == SPUDownloadModePersistent && totalBytesExpectedToWrite > 0 && !self.receivedExpectedBytes) {
|
||||
self.receivedExpectedBytes = YES;
|
||||
[self.delegate downloaderDidReceiveExpectedContentLength:totalBytesExpectedToWrite];
|
||||
}
|
||||
|
||||
if (self.mode == SPUDownloadModePersistent && bytesWritten >= 0) {
|
||||
[self.delegate downloaderDidReceiveDataOfLength:(uint64_t)bytesWritten];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)URLSession:(NSURLSession *)__unused session task:(NSURLSessionTask *)__unused task didCompleteWithError:(NSError *)error
|
||||
{
|
||||
self.download = nil;
|
||||
if (error) {
|
||||
[self.delegate downloaderDidFailWithError:error];
|
||||
}
|
||||
[self cleanup];
|
||||
}
|
||||
|
||||
- (void)downloadDidFinish
|
||||
{
|
||||
assert(self.downloadFilename != nil);
|
||||
|
||||
SPUDownloadData *downloadData = nil;
|
||||
if (self.mode == SPUDownloadModeTemporary) {
|
||||
NSData *data = [NSData dataWithContentsOfFile:self.downloadFilename];
|
||||
if (data != nil) {
|
||||
NSURLResponse *response = self.download.response;
|
||||
assert(response != nil);
|
||||
downloadData = [[SPUDownloadData alloc] initWithData:data textEncodingName:response.textEncodingName MIMEType:response.MIMEType];
|
||||
}
|
||||
}
|
||||
|
||||
self.download = nil;
|
||||
|
||||
[super downloadDidFinishWithData:downloadData];
|
||||
}
|
||||
|
||||
-(void)cleanup
|
||||
{
|
||||
[self.download cancel];
|
||||
self.download = nil;
|
||||
self.downloadSession = nil;
|
||||
[super cleanup];
|
||||
}
|
||||
|
||||
- (void)cancel
|
||||
{
|
||||
[self cleanup];
|
||||
}
|
||||
|
||||
// NSURLDownload has a [downlaod:shouldDecodeSourceDataOfMIMEType:] to determine if the data should be decoded.
|
||||
// This does not exist for NSURLSessionDownloadTask and appears unnecessary. Data tasks will decode data, but not download tasks.
|
||||
|
||||
@end
|
||||
Vendored
+41
@@ -0,0 +1,41 @@
|
||||
//
|
||||
// SPUDownloader_Private.h
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Deadpikle on 12/20/17.
|
||||
// Copyright © 2017 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#ifndef SPUDownloader_Private_h
|
||||
#define SPUDownloader_Private_h
|
||||
|
||||
#import "SPUDownloaderDelegate.h"
|
||||
|
||||
typedef NS_ENUM(NSUInteger, SPUDownloadMode)
|
||||
{
|
||||
SPUDownloadModePersistent,
|
||||
SPUDownloadModeTemporary
|
||||
};
|
||||
|
||||
static NSString *SUDownloadingReason = @"Downloading update related file";
|
||||
|
||||
@interface SPUDownloader ()
|
||||
|
||||
// Delegate is intentionally strongly referenced; see header
|
||||
@property (nonatomic) id <SPUDownloaderDelegate> delegate;
|
||||
@property (nonatomic, copy) NSString *bundleIdentifier;
|
||||
@property (nonatomic, copy) NSString *desiredFilename;
|
||||
@property (nonatomic, copy) NSString *downloadFilename;
|
||||
@property (nonatomic) BOOL disabledAutomaticTermination;
|
||||
@property (nonatomic) SPUDownloadMode mode;
|
||||
@property (nonatomic) BOOL receivedExpectedBytes;
|
||||
|
||||
// returns temp directory location if successful; if not successful,
|
||||
// returns nil after sending error message to client and canceling download
|
||||
-(NSString*)getAndCleanTempDirectory;
|
||||
|
||||
-(void)downloadDidFinishWithData:(SPUDownloadData*)data;
|
||||
|
||||
@end
|
||||
|
||||
#endif /* SPUDownloader_Private_h */
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
//
|
||||
// SULocalCacheDirectory.h
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Mayur Pawashe on 6/23/16.
|
||||
// Copyright © 2016 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface SPULocalCacheDirectory : NSObject
|
||||
|
||||
// Returns a path to a suitable cache directory to create specifically for Sparkle
|
||||
// Intermediate directories to this path may not exist yet
|
||||
// This path may depend on the type of running process,
|
||||
// such that sandboxed vs non-sandboxed processes could yield different paths
|
||||
// The caller should create a subdirectory from the path that is returned here so they don't have files that
|
||||
// conflict with other callers. Once that subdirectory name is decided, the caller can remove old items inside it (using +removeOldItemsInDirectory:)
|
||||
// and then create a unique temporary directory inside it (using +createUniqueDirectoryInDirectory:)
|
||||
+ (NSString *)cachePathForBundleIdentifier:(NSString *)bundleIdentifier;
|
||||
|
||||
// Remove old files inside a directory
|
||||
// A caller may want to invoke this on a directory they own rather than remove and re-create an entire directory
|
||||
// This does nothing if the supplied directory does not exist yet
|
||||
+ (void)removeOldItemsInDirectory:(NSString *)directory;
|
||||
|
||||
// Create a unique directory inside a parent directory
|
||||
// The parent directory doesn't have to exist yet. If it doesn't exist, intermediate directories will be created.
|
||||
+ (NSString * _Nullable)createUniqueDirectoryInDirectory:(NSString *)directory;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
//
|
||||
// SULocalCacheDirectory.m
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Mayur Pawashe on 6/23/16.
|
||||
// Copyright © 2016 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#import "SPULocalCacheDirectory.h"
|
||||
#import "SULog.h"
|
||||
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
|
||||
static NSTimeInterval OLD_ITEM_DELETION_INTERVAL = 86400 * 10; // 10 days
|
||||
|
||||
@implementation SPULocalCacheDirectory
|
||||
|
||||
// It is important to note this may return a different path whether invoked from a sanboxed vs non-sandboxed process, or from a different user
|
||||
// For this reason, this method should not be a part of SUHost because its behavior depends on what kind of process it's being invoked from
|
||||
+ (NSString *)cachePathForBundleIdentifier:(NSString *)bundleIdentifier
|
||||
{
|
||||
NSURL *cacheURL = [[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:NULL];
|
||||
assert(cacheURL != nil);
|
||||
|
||||
NSString *resultPath = [[[cacheURL URLByAppendingPathComponent:bundleIdentifier] URLByAppendingPathComponent:@SPARKLE_BUNDLE_IDENTIFIER] path];
|
||||
assert(resultPath != nil);
|
||||
|
||||
return resultPath;
|
||||
}
|
||||
|
||||
+ (void)removeOldItemsInDirectory:(NSString *)directory
|
||||
{
|
||||
NSMutableArray<NSString *> *filePathsToRemove = [NSMutableArray array];
|
||||
NSFileManager *fileManager = [NSFileManager defaultManager];
|
||||
if ([fileManager fileExistsAtPath:directory]) {
|
||||
NSDirectoryEnumerator *directoryEnumerator = [fileManager enumeratorAtPath:directory];
|
||||
NSDate *currentDate = [NSDate date];
|
||||
for (NSString *filename in directoryEnumerator)
|
||||
{
|
||||
NSDictionary<NSString *, id> *fileAttributes = [fileManager attributesOfItemAtPath:[directory stringByAppendingPathComponent:filename] error:NULL];
|
||||
if (fileAttributes != nil)
|
||||
{
|
||||
NSDate *lastModificationDate = [fileAttributes objectForKey:NSFileModificationDate];
|
||||
if ([currentDate timeIntervalSinceDate:lastModificationDate] >= OLD_ITEM_DELETION_INTERVAL)
|
||||
{
|
||||
[filePathsToRemove addObject:[directory stringByAppendingPathComponent:filename]];
|
||||
}
|
||||
}
|
||||
|
||||
[directoryEnumerator skipDescendants];
|
||||
}
|
||||
|
||||
for (NSString *filename in filePathsToRemove)
|
||||
{
|
||||
[fileManager removeItemAtPath:filename error:NULL];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+ (NSString * _Nullable)createUniqueDirectoryInDirectory:(NSString *)directory
|
||||
{
|
||||
NSFileManager *fileManager = [NSFileManager defaultManager];
|
||||
NSError *createError = nil;
|
||||
if (![fileManager createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:nil error:&createError]) {
|
||||
SULog(SULogLevelError, @"Failed to create directory with intermediate components at %@ with error %@", directory, createError);
|
||||
return nil;
|
||||
}
|
||||
|
||||
NSString *templateString = [directory stringByAppendingPathComponent:@"XXXXXXXXX"];
|
||||
char buffer[PATH_MAX] = {0};
|
||||
if ([templateString getFileSystemRepresentation:buffer maxLength:sizeof(buffer)]) {
|
||||
if (mkdtemp(buffer) != NULL) {
|
||||
return [[NSString alloc] initWithUTF8String:buffer];
|
||||
}
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
@end
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
//
|
||||
// SPUURLRequest.h
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Mayur Pawashe on 5/19/16.
|
||||
// Copyright © 2016 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#if __has_feature(modules)
|
||||
@import Foundation;
|
||||
#else
|
||||
#import <Foundation/Foundation.h>
|
||||
#endif
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
// A class that wraps NSURLRequest and implements NSSecureCoding
|
||||
// This class exists because NSURLRequest did not support NSSecureCoding in macOS 10.8
|
||||
// I have not verified if NSURLRequest in 10.9 implements NSSecureCoding or not
|
||||
@interface SPUURLRequest : NSObject <NSSecureCoding>
|
||||
|
||||
// Creates a new URL request
|
||||
// Only these properties are currently tracked:
|
||||
// * URL
|
||||
// * Cache policy
|
||||
// * Timeout interval
|
||||
// * HTTP header fields
|
||||
// * networkServiceType
|
||||
+ (instancetype)URLRequestWithRequest:(NSURLRequest *)request;
|
||||
|
||||
@property (nonatomic, readonly) NSURLRequest *request;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
//
|
||||
// SPUURLRequest.m
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Mayur Pawashe on 5/19/16.
|
||||
// Copyright © 2016 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#import "SPUURLRequest.h"
|
||||
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
|
||||
static NSString *SPUURLRequestURLKey = @"SPUURLRequestURL";
|
||||
static NSString *SPUURLRequestCachePolicyKey = @"SPUURLRequestCachePolicy";
|
||||
static NSString *SPUURLRequestTimeoutIntervalKey = @"SPUURLRequestTimeoutInterval";
|
||||
static NSString *SPUURLRequestHttpHeaderFieldsKey = @"SPUURLRequestHttpHeaderFields";
|
||||
static NSString *SPUURLRequestNetworkServiceTypeKey = @"SPUURLRequestNetworkServiceType";
|
||||
|
||||
@interface SPUURLRequest ()
|
||||
|
||||
@property (nonatomic, readonly) NSURL *url;
|
||||
@property (nonatomic, readonly) NSURLRequestCachePolicy cachePolicy;
|
||||
@property (nonatomic, readonly) NSTimeInterval timeoutInterval;
|
||||
@property (nonatomic, readonly, nullable) NSDictionary<NSString *, NSString *> *httpHeaderFields;
|
||||
@property (nonatomic, readonly) NSURLRequestNetworkServiceType networkServiceType;
|
||||
|
||||
@end
|
||||
|
||||
@implementation SPUURLRequest
|
||||
|
||||
@synthesize url = _url;
|
||||
@synthesize cachePolicy = _cachePolicy;
|
||||
@synthesize timeoutInterval = _timeoutInterval;
|
||||
@synthesize httpHeaderFields = _httpHeaderFields;
|
||||
@synthesize networkServiceType = _networkServiceType;
|
||||
|
||||
- (instancetype)initWithURL:(NSURL *)url cachePolicy:(NSURLRequestCachePolicy)cachePolicy timeoutInterval:(NSTimeInterval)timeoutInterval httpHeaderFields:(NSDictionary<NSString *, NSString *> *)httpHeaderFields networkServiceType:(NSURLRequestNetworkServiceType)networkServiceType
|
||||
{
|
||||
self = [super init];
|
||||
if (self != nil) {
|
||||
_url = url;
|
||||
_cachePolicy = cachePolicy;
|
||||
_timeoutInterval = timeoutInterval;
|
||||
_httpHeaderFields = httpHeaderFields;
|
||||
_networkServiceType = networkServiceType;
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
+ (instancetype)URLRequestWithRequest:(NSURLRequest *)request
|
||||
{
|
||||
return [[[self class] alloc] initWithURL:request.URL cachePolicy:request.cachePolicy timeoutInterval:request.timeoutInterval httpHeaderFields:request.allHTTPHeaderFields networkServiceType:request.networkServiceType];
|
||||
}
|
||||
|
||||
+ (BOOL)supportsSecureCoding
|
||||
{
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (void)encodeWithCoder:(NSCoder *)coder
|
||||
{
|
||||
[coder encodeObject:self.url forKey:SPUURLRequestURLKey];
|
||||
[coder encodeInteger:self.cachePolicy forKey:SPUURLRequestCachePolicyKey];
|
||||
[coder encodeDouble:self.timeoutInterval forKey:SPUURLRequestTimeoutIntervalKey];
|
||||
[coder encodeInteger:self.networkServiceType forKey:SPUURLRequestNetworkServiceTypeKey];
|
||||
|
||||
if (self.httpHeaderFields != nil) {
|
||||
[coder encodeObject:self.httpHeaderFields forKey:SPUURLRequestHttpHeaderFieldsKey];
|
||||
}
|
||||
}
|
||||
|
||||
- (instancetype)initWithCoder:(NSCoder *)decoder
|
||||
{
|
||||
if (@available(macOS 10.8, *)) {
|
||||
NSURL *url = [decoder decodeObjectOfClass:[NSURL class] forKey:SPUURLRequestURLKey];
|
||||
NSURLRequestCachePolicy cachePolicy = (NSURLRequestCachePolicy)[decoder decodeIntegerForKey:SPUURLRequestCachePolicyKey];
|
||||
NSTimeInterval timeoutInterval = [decoder decodeDoubleForKey:SPUURLRequestTimeoutIntervalKey];
|
||||
NSDictionary<NSString *, NSString *> *httpHeaderFields = [decoder decodeObjectOfClasses:[NSSet setWithArray:@[[NSDictionary class], [NSString class]]] forKey:SPUURLRequestHttpHeaderFieldsKey];
|
||||
NSURLRequestNetworkServiceType networkServiceType = (NSURLRequestNetworkServiceType)[decoder decodeIntegerForKey:SPUURLRequestNetworkServiceTypeKey];
|
||||
|
||||
return [self initWithURL:url cachePolicy:cachePolicy timeoutInterval:timeoutInterval httpHeaderFields:httpHeaderFields networkServiceType:networkServiceType];
|
||||
} else {
|
||||
abort(); // Not used on 10.7
|
||||
}
|
||||
}
|
||||
|
||||
- (NSURLRequest *)request
|
||||
{
|
||||
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:self.url cachePolicy:self.cachePolicy timeoutInterval:self.timeoutInterval];
|
||||
if (self.httpHeaderFields != nil) {
|
||||
request.allHTTPHeaderFields = self.httpHeaderFields;
|
||||
}
|
||||
request.networkServiceType = self.networkServiceType;
|
||||
return [request copy];
|
||||
}
|
||||
|
||||
@end
|
||||
Vendored
+14
-5
@@ -16,16 +16,25 @@
|
||||
#endif
|
||||
#import "SUExport.h"
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@class SUAppcastItem;
|
||||
SU_EXPORT @interface SUAppcast : NSObject<NSURLDownloadDelegate>
|
||||
SU_EXPORT @interface SUAppcast : NSObject
|
||||
|
||||
@property (copy) NSString *userAgentString;
|
||||
@property (copy) NSDictionary *httpHeaders;
|
||||
@property (copy, nullable) NSString *userAgentString;
|
||||
|
||||
- (void)fetchAppcastFromURL:(NSURL *)url completionBlock:(void (^)(NSError *))err;
|
||||
#if __has_feature(objc_generics)
|
||||
@property (copy, nullable) NSDictionary<NSString *, NSString *> *httpHeaders;
|
||||
#else
|
||||
@property (copy, nullable) NSDictionary *httpHeaders;
|
||||
#endif
|
||||
|
||||
- (void)fetchAppcastFromURL:(NSURL *)url inBackground:(BOOL)bg completionBlock:(void (^)(NSError *_Nullable))err;
|
||||
- (SUAppcast *)copyWithoutDeltaUpdates;
|
||||
|
||||
@property (readonly, copy) NSArray *items;
|
||||
@property (readonly, copy, nullable) NSArray *items;
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
#endif
|
||||
Vendored
+83
-58
@@ -6,14 +6,20 @@
|
||||
// Copyright 2006 Andy Matuschak. All rights reserved.
|
||||
//
|
||||
|
||||
#import "SUUpdater.h"
|
||||
|
||||
#import "SUAppcast.h"
|
||||
#import "SUAppcastItem.h"
|
||||
#import "SUVersionComparisonProtocol.h"
|
||||
#import "SUAppcast.h"
|
||||
#import "SUConstants.h"
|
||||
#import "SULog.h"
|
||||
#import "SULocalizations.h"
|
||||
#import "SUErrors.h"
|
||||
|
||||
#import "SPUURLRequest.h"
|
||||
#import "SUOperatingSystem.h"
|
||||
#import "SPUDownloadData.h"
|
||||
#import "SPUDownloaderDelegate.h"
|
||||
#import "SPUDownloaderDeprecated.h"
|
||||
#import "SPUDownloaderSession.h"
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
|
||||
@interface NSXMLElement (SUAppcastExtensions)
|
||||
@property (readonly, copy) NSDictionary *attributesAsDictionary;
|
||||
@@ -39,85 +45,114 @@
|
||||
}
|
||||
@end
|
||||
|
||||
@interface SUAppcast () <NSURLDownloadDelegate>
|
||||
@interface SUAppcast () <SPUDownloaderDelegate>
|
||||
|
||||
@property (strong) void (^completionBlock)(NSError *);
|
||||
@property (copy) NSString *downloadFilename;
|
||||
@property (strong) NSURLDownload *download;
|
||||
@property (strong) SPUDownloader *download;
|
||||
@property (copy) NSArray *items;
|
||||
- (void)reportError:(NSError *)error;
|
||||
- (NSXMLNode *)bestNodeInNodes:(NSArray *)nodes;
|
||||
|
||||
@end
|
||||
|
||||
@implementation SUAppcast
|
||||
|
||||
@synthesize downloadFilename;
|
||||
@synthesize completionBlock;
|
||||
@synthesize userAgentString;
|
||||
@synthesize httpHeaders;
|
||||
@synthesize download;
|
||||
@synthesize items;
|
||||
|
||||
- (void)fetchAppcastFromURL:(NSURL *)url completionBlock:(void (^)(NSError *))block
|
||||
- (void)fetchAppcastFromURL:(NSURL *)url inBackground:(BOOL)background completionBlock:(void (^)(NSError *))block
|
||||
{
|
||||
self.completionBlock = block;
|
||||
|
||||
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30.0];
|
||||
if (background) {
|
||||
request.networkServiceType = NSURLNetworkServiceTypeBackground;
|
||||
}
|
||||
|
||||
if (self.userAgentString) {
|
||||
[request setValue:self.userAgentString forHTTPHeaderField:@"User-Agent"];
|
||||
}
|
||||
|
||||
if (self.httpHeaders) {
|
||||
for (NSString *key in self.httpHeaders) {
|
||||
id value = [self.httpHeaders objectForKey:key];
|
||||
NSString *value = [self.httpHeaders objectForKey:key];
|
||||
[request setValue:value forHTTPHeaderField:key];
|
||||
}
|
||||
}
|
||||
|
||||
[request setValue:@"application/rss+xml,*/*;q=0.1" forHTTPHeaderField:@"Accept"];
|
||||
|
||||
self.download = [[NSURLDownload alloc] initWithRequest:request delegate:self];
|
||||
}
|
||||
|
||||
- (void)download:(NSURLDownload *)__unused aDownload decideDestinationWithSuggestedFilename:(NSString *)filename
|
||||
{
|
||||
NSString *destinationFilename = NSTemporaryDirectory();
|
||||
if (destinationFilename)
|
||||
{
|
||||
destinationFilename = [destinationFilename stringByAppendingPathComponent:filename];
|
||||
[self.download setDestination:destinationFilename allowOverwrite:NO];
|
||||
|
||||
if ([SUOperatingSystem isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){10, 9, 0}]) {
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wunguarded-availability"
|
||||
self.download = [[SPUDownloaderSession alloc] initWithDelegate:self];
|
||||
#pragma clang diagnostic pop
|
||||
}
|
||||
else {
|
||||
self.download = [[SPUDownloaderDeprecated alloc] initWithDelegate:self];
|
||||
}
|
||||
|
||||
SPUURLRequest *urlRequest = [SPUURLRequest URLRequestWithRequest:request];
|
||||
[self.download startTemporaryDownloadWithRequest:urlRequest];
|
||||
}
|
||||
|
||||
- (void)download:(NSURLDownload *)__unused aDownload didCreateDestination:(NSString *)path
|
||||
- (void)downloaderDidSetDestinationName:(NSString *)__unused destinationName temporaryDirectory:(NSString *)__unused temporaryDirectory
|
||||
{
|
||||
self.downloadFilename = path;
|
||||
}
|
||||
|
||||
- (void)downloadDidFinish:(NSURLDownload *)__unused aDownload
|
||||
- (void)downloaderDidReceiveExpectedContentLength:(int64_t)__unused expectedContentLength
|
||||
{
|
||||
NSError *error = nil;
|
||||
NSArray *appcastItems = [self parseAppcastItemsFromXMLFile:[NSURL fileURLWithPath:self.downloadFilename] error:&error];
|
||||
}
|
||||
|
||||
[[NSFileManager defaultManager] removeItemAtPath:self.downloadFilename error:nil];
|
||||
self.downloadFilename = nil;
|
||||
- (void)downloaderDidReceiveDataOfLength:(uint64_t)__unused length
|
||||
{
|
||||
}
|
||||
|
||||
if (appcastItems) {
|
||||
self.items = appcastItems;
|
||||
self.completionBlock(nil);
|
||||
self.completionBlock = nil;
|
||||
} else {
|
||||
NSMutableDictionary *userInfo = [NSMutableDictionary
|
||||
dictionaryWithObject: SULocalizedString(@"An error occurred while parsing the update feed.", nil)
|
||||
forKey: NSLocalizedDescriptionKey];
|
||||
if (error) {
|
||||
[userInfo setObject:error forKey:NSUnderlyingErrorKey];
|
||||
- (void)downloaderDidFinishWithTemporaryDownloadData:(SPUDownloadData * _Nullable)downloadData
|
||||
{
|
||||
if (downloadData != nil) {
|
||||
NSError *parseError = nil;
|
||||
NSArray *appcastItems = [self parseAppcastItemsFromXMLData:downloadData.data error:&parseError];
|
||||
|
||||
if (appcastItems != nil) {
|
||||
self.items = appcastItems;
|
||||
self.completionBlock(nil);
|
||||
self.completionBlock = nil;
|
||||
} else {
|
||||
NSMutableDictionary *userInfo = [NSMutableDictionary
|
||||
dictionaryWithObject: SULocalizedString(@"An error occurred while parsing the update feed.", nil)
|
||||
forKey: NSLocalizedDescriptionKey];
|
||||
if (parseError != nil) {
|
||||
[userInfo setObject:parseError forKey:NSUnderlyingErrorKey];
|
||||
}
|
||||
[self reportError:[NSError errorWithDomain:SUSparkleErrorDomain
|
||||
code:SUAppcastParseError
|
||||
userInfo:userInfo]];
|
||||
}
|
||||
} else {
|
||||
SULog(SULogLevelError, @"Temp data download is null in SUAppcast");
|
||||
|
||||
NSDictionary *userInfo = [NSDictionary
|
||||
dictionaryWithObject: SULocalizedString(@"An error occurred while downloading the update feed.", nil)
|
||||
forKey: NSLocalizedDescriptionKey];
|
||||
|
||||
[self reportError:[NSError errorWithDomain:SUSparkleErrorDomain
|
||||
code:SUAppcastParseError
|
||||
code:SUDownloadError
|
||||
userInfo:userInfo]];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)downloaderDidFailWithError:(NSError *)error
|
||||
{
|
||||
SULog(SULogLevelError, @"Encountered download feed error: %@", error);
|
||||
|
||||
[self reportError:error];
|
||||
}
|
||||
|
||||
- (NSDictionary *)attributesOfNode:(NSXMLElement *)node
|
||||
{
|
||||
NSEnumerator *attributeEnum = [[node attributes] objectEnumerator];
|
||||
@@ -148,17 +183,22 @@
|
||||
}
|
||||
}
|
||||
|
||||
-(NSArray *)parseAppcastItemsFromXMLFile:(NSURL *)appcastFile error:(NSError *__autoreleasing*)errorp {
|
||||
-(NSArray *)parseAppcastItemsFromXMLFile:(NSURL *)appcastURL error:(NSError *__autoreleasing*)errorp {
|
||||
NSData *data = [NSData dataWithContentsOfURL:appcastURL];
|
||||
return [self parseAppcastItemsFromXMLData:data error:errorp];
|
||||
}
|
||||
|
||||
-(NSArray *)parseAppcastItemsFromXMLData:(NSData *)appcastData error:(NSError *__autoreleasing*)errorp {
|
||||
if (errorp) {
|
||||
*errorp = nil;
|
||||
}
|
||||
|
||||
if (!appcastFile) {
|
||||
if (!appcastData) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
NSUInteger options = NSXMLNodeLoadExternalEntitiesNever; // Prevent inclusion from file://
|
||||
NSXMLDocument *document = [[NSXMLDocument alloc] initWithContentsOfURL:appcastFile options:options error:errorp];
|
||||
NSXMLDocument *document = [[NSXMLDocument alloc] initWithData:appcastData options:options error:errorp];
|
||||
if (nil == document) {
|
||||
return nil;
|
||||
}
|
||||
@@ -245,7 +285,7 @@
|
||||
[appcastItems addObject:anItem];
|
||||
}
|
||||
else {
|
||||
SULog(@"Sparkle Updater: Failed to parse appcast item: %@.\nAppcast dictionary was: %@", errString, dict);
|
||||
SULog(SULogLevelError, @"Sparkle Updater: Failed to parse appcast item: %@.\nAppcast dictionary was: %@", errString, dict);
|
||||
if (errorp) *errorp = [NSError errorWithDomain:SUSparkleErrorDomain
|
||||
code:SUAppcastParseError
|
||||
userInfo:@{NSLocalizedDescriptionKey: errString}];
|
||||
@@ -258,21 +298,6 @@
|
||||
return appcastItems;
|
||||
}
|
||||
|
||||
- (void)download:(NSURLDownload *)__unused aDownload didFailWithError:(NSError *)error
|
||||
{
|
||||
if (self.downloadFilename) {
|
||||
[[NSFileManager defaultManager] removeItemAtPath:self.downloadFilename error:nil];
|
||||
}
|
||||
self.downloadFilename = nil;
|
||||
|
||||
[self reportError:error];
|
||||
}
|
||||
|
||||
- (NSURLRequest *)download:(NSURLDownload *)__unused aDownload willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)__unused redirectResponse
|
||||
{
|
||||
return request;
|
||||
}
|
||||
|
||||
- (void)reportError:(NSError *)error
|
||||
{
|
||||
NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:@{
|
||||
|
||||
Vendored
+3
@@ -25,7 +25,9 @@ SU_EXPORT @interface SUAppcastItem : NSObject
|
||||
@property (copy, readonly) NSString *minimumSystemVersion;
|
||||
@property (copy, readonly) NSString *maximumSystemVersion;
|
||||
@property (strong, readonly) NSURL *fileURL;
|
||||
@property (nonatomic, readonly) uint64_t contentLength;
|
||||
@property (copy, readonly) NSString *versionString;
|
||||
@property (copy, readonly) NSString *osString;
|
||||
@property (copy, readonly) NSString *displayVersionString;
|
||||
@property (copy, readonly) NSDictionary *deltaUpdates;
|
||||
@property (strong, readonly) NSURL *infoURL;
|
||||
@@ -36,6 +38,7 @@ SU_EXPORT @interface SUAppcastItem : NSObject
|
||||
|
||||
@property (getter=isDeltaUpdate, readonly) BOOL deltaUpdate;
|
||||
@property (getter=isCriticalUpdate, readonly) BOOL criticalUpdate;
|
||||
@property (getter=isMacOsUpdate, readonly) BOOL macOsUpdate;
|
||||
@property (getter=isInformationOnlyUpdate, readonly) BOOL informationOnlyUpdate;
|
||||
|
||||
// Returns the dictionary provided in initWithDictionary; this might be useful later for extensions.
|
||||
|
||||
Vendored
+26
-9
@@ -6,13 +6,12 @@
|
||||
// Copyright 2006 Andy Matuschak. All rights reserved.
|
||||
//
|
||||
|
||||
#import "SUUpdater.h"
|
||||
|
||||
#import "SUAppcast.h"
|
||||
#import "SUAppcastItem.h"
|
||||
#import "SUVersionComparisonProtocol.h"
|
||||
#import "SUAppcastItem.h"
|
||||
#import "SULog.h"
|
||||
#import "SUConstants.h"
|
||||
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
|
||||
@interface SUAppcastItem ()
|
||||
@property (copy, readwrite) NSString *title;
|
||||
@@ -24,6 +23,7 @@
|
||||
@property (copy, readwrite) NSString *maximumSystemVersion;
|
||||
@property (strong, readwrite) NSURL *fileURL;
|
||||
@property (copy, readwrite) NSString *versionString;
|
||||
@property (copy, readwrite) NSString *osString;
|
||||
@property (copy, readwrite) NSString *displayVersionString;
|
||||
@property (copy, readwrite) NSDictionary *deltaUpdates;
|
||||
@property (strong, readwrite) NSURL *infoURL;
|
||||
@@ -36,6 +36,7 @@
|
||||
@synthesize displayVersionString;
|
||||
@synthesize DSASignature;
|
||||
@synthesize fileURL;
|
||||
@synthesize contentLength = _contentLength;
|
||||
@synthesize infoURL;
|
||||
@synthesize itemDescription;
|
||||
@synthesize maximumSystemVersion;
|
||||
@@ -43,6 +44,7 @@
|
||||
@synthesize releaseNotesURL;
|
||||
@synthesize title;
|
||||
@synthesize versionString;
|
||||
@synthesize osString;
|
||||
@synthesize propertiesDictionary;
|
||||
|
||||
- (BOOL)isDeltaUpdate
|
||||
@@ -56,6 +58,11 @@
|
||||
return [[self.propertiesDictionary objectForKey:SUAppcastElementTags] containsObject:SUAppcastElementCriticalUpdate];
|
||||
}
|
||||
|
||||
- (BOOL)isMacOsUpdate
|
||||
{
|
||||
return self.osString == nil || [self.osString isEqualToString:SUAppcastAttributeValueMacOS];
|
||||
}
|
||||
|
||||
- (BOOL)isInformationOnlyUpdate
|
||||
{
|
||||
return self.infoURL && !self.fileURL;
|
||||
@@ -86,7 +93,7 @@
|
||||
}
|
||||
if (newVersion == nil) // no sparkle:version attribute anywhere?
|
||||
{
|
||||
SULog(@"warning: <%@> for URL '%@' is missing %@ attribute. Version comparison may be unreliable. Please always specify %@", SURSSElementEnclosure, [enclosure objectForKey:SURSSAttributeURL], SUAppcastAttributeVersion, SUAppcastAttributeVersion);
|
||||
SULog(SULogLevelError, @"warning: <%@> for URL '%@' is missing %@ attribute. Version comparison may be unreliable. Please always specify %@", SURSSElementEnclosure, [enclosure objectForKey:SURSSAttributeURL], SUAppcastAttributeVersion, SUAppcastAttributeVersion);
|
||||
|
||||
// Separate the url by underscores and take the last component, as that'll be closest to the end,
|
||||
// then we remove the extension. Hopefully, this will be the version.
|
||||
@@ -111,7 +118,7 @@
|
||||
NSString *theInfoURL = [dict objectForKey:SURSSElementLink];
|
||||
if (theInfoURL) {
|
||||
if (![theInfoURL isKindOfClass:[NSString class]]) {
|
||||
SULog(@"%@ -%@ Info URL is not of valid type.", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
|
||||
SULog(SULogLevelError, @"%@ -%@ Info URL is not of valid type.", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
|
||||
} else {
|
||||
self.infoURL = [NSURL URLWithString:theInfoURL];
|
||||
}
|
||||
@@ -133,6 +140,15 @@
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
if (enclosureURLString) {
|
||||
NSString *enclosureLengthString = [enclosure objectForKey:SURSSAttributeLength];
|
||||
long long contentLength = 0;
|
||||
if (enclosureLengthString != nil) {
|
||||
contentLength = [enclosureLengthString longLongValue];
|
||||
}
|
||||
_contentLength = (contentLength > 0) ? (uint64_t)contentLength : 0;
|
||||
}
|
||||
|
||||
if (enclosureURLString) {
|
||||
// Sparkle used to always URL-encode, so for backwards compatibility spaces in URLs must be forgiven.
|
||||
@@ -141,8 +157,9 @@
|
||||
}
|
||||
if (enclosure) {
|
||||
self.DSASignature = [enclosure objectForKey:SUAppcastAttributeDSASignature];
|
||||
self.osString = [enclosure objectForKey:SUAppcastAttributeOsType];
|
||||
}
|
||||
|
||||
|
||||
self.versionString = newVersion;
|
||||
self.minimumSystemVersion = [dict objectForKey:SUAppcastElementMinimumSystemVersion];
|
||||
self.maximumSystemVersion = [dict objectForKey:SUAppcastElementMaximumSystemVersion];
|
||||
@@ -163,7 +180,7 @@
|
||||
if (releaseNotesString) {
|
||||
NSURL *url = [NSURL URLWithString:releaseNotesString];
|
||||
if ([url isFileURL]) {
|
||||
SULog(@"Release notes with file:// URLs are not supported");
|
||||
SULog(SULogLevelError, @"Release notes with file:// URLs are not supported");
|
||||
} else {
|
||||
self.releaseNotesURL = url;
|
||||
}
|
||||
|
||||
Vendored
+23
@@ -0,0 +1,23 @@
|
||||
//
|
||||
// SUApplicationInfo.h
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Mayur Pawashe on 2/28/16.
|
||||
// Copyright © 2016 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@class SUHost;
|
||||
|
||||
@interface SUApplicationInfo : NSObject
|
||||
|
||||
+ (BOOL)isBackgroundApplication:(NSApplication *)application;
|
||||
|
||||
+ (NSImage *)bestIconForHost:(SUHost *)host;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
Vendored
+37
@@ -0,0 +1,37 @@
|
||||
//
|
||||
// SUApplicationInfo.m
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Mayur Pawashe on 2/28/16.
|
||||
// Copyright © 2016 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#import "SUApplicationInfo.h"
|
||||
#import "SUBundleIcon.h"
|
||||
#import "SUHost.h"
|
||||
|
||||
@implementation SUApplicationInfo
|
||||
|
||||
+ (BOOL)isBackgroundApplication:(NSApplication *)application
|
||||
{
|
||||
return (application.activationPolicy == NSApplicationActivationPolicyAccessory);
|
||||
}
|
||||
|
||||
+ (NSImage *)bestIconForHost:(SUHost *)host
|
||||
{
|
||||
NSURL *iconURL = [SUBundleIcon iconURLForHost:host];
|
||||
|
||||
NSImage *icon = (iconURL == nil) ? nil : [[NSImage alloc] initWithContentsOfURL:iconURL];
|
||||
// Use a default icon if none is defined.
|
||||
if (!icon) {
|
||||
// this asumption may not be correct (eg. even though we're not the main bundle, it could be still be a regular app)
|
||||
// but still better than nothing if no icon was included
|
||||
BOOL isMainBundle = [host.bundle isEqualTo:[NSBundle mainBundle]];
|
||||
|
||||
NSString *fileType = isMainBundle ? (__bridge NSString *)kUTTypeApplication : (__bridge NSString *)kUTTypeBundle;
|
||||
icon = [[NSWorkspace sharedWorkspace] iconForFileType:fileType];
|
||||
}
|
||||
return icon;
|
||||
}
|
||||
|
||||
@end
|
||||
Vendored
+2
-2
@@ -9,7 +9,7 @@
|
||||
#ifndef SUAUTOMATICUPDATEALERT_H
|
||||
#define SUAUTOMATICUPDATEALERT_H
|
||||
|
||||
#import "SUWindowController.h"
|
||||
#import <Cocoa/Cocoa.h>
|
||||
|
||||
typedef NS_ENUM(NSInteger, SUAutomaticInstallationChoice) {
|
||||
SUInstallNowChoice,
|
||||
@@ -18,7 +18,7 @@ typedef NS_ENUM(NSInteger, SUAutomaticInstallationChoice) {
|
||||
};
|
||||
|
||||
@class SUAppcastItem, SUHost;
|
||||
@interface SUAutomaticUpdateAlert : SUWindowController
|
||||
@interface SUAutomaticUpdateAlert : NSWindowController
|
||||
|
||||
- (instancetype)initWithAppcastItem:(SUAppcastItem *)item host:(SUHost *)hostBundle completionBlock:(void (^)(SUAutomaticInstallationChoice))c;
|
||||
- (IBAction)installNow:sender;
|
||||
|
||||
Vendored
+45
-4
@@ -7,19 +7,32 @@
|
||||
//
|
||||
|
||||
#import "SUAutomaticUpdateAlert.h"
|
||||
|
||||
#import "SULocalizations.h"
|
||||
#import "SUAppcastItem.h"
|
||||
#import "SUApplicationInfo.h"
|
||||
#import "SUHost.h"
|
||||
#import "SUTouchBarForwardDeclarations.h"
|
||||
#import "SUTouchBarButtonGroup.h"
|
||||
|
||||
@interface SUAutomaticUpdateAlert ()
|
||||
static NSString *const SUAutomaticUpdateAlertTouchBarIndentifier = @"" SPARKLE_BUNDLE_IDENTIFIER ".SUAutomaticUpdateAlert";
|
||||
|
||||
@interface SUAutomaticUpdateAlert () <NSTouchBarDelegate>
|
||||
@property (strong) void(^completionBlock)(SUAutomaticInstallationChoice);
|
||||
@property (strong) SUAppcastItem *updateItem;
|
||||
@property (strong) SUHost *host;
|
||||
|
||||
@property (weak) IBOutlet NSButton *skipButton;
|
||||
@property (weak) IBOutlet NSButton *laterButton;
|
||||
@property (weak) IBOutlet NSButton *installButton;
|
||||
@end
|
||||
|
||||
@implementation SUAutomaticUpdateAlert
|
||||
@synthesize host;
|
||||
@synthesize updateItem;
|
||||
@synthesize completionBlock;
|
||||
@synthesize skipButton;
|
||||
@synthesize laterButton;
|
||||
@synthesize installButton;
|
||||
|
||||
- (instancetype)initWithAppcastItem:(SUAppcastItem *)item host:(SUHost *)aHost completionBlock:(void (^)(SUAutomaticInstallationChoice))block
|
||||
{
|
||||
@@ -29,12 +42,13 @@
|
||||
self.completionBlock = block;
|
||||
self.host = aHost;
|
||||
[self setShouldCascadeWindows:NO];
|
||||
|
||||
[[self window] center];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (NSString *__nonnull)description { return [NSString stringWithFormat:@"%@ <%@, %@>", [self class], [self.host bundlePath], [self.host installationPath]]; }
|
||||
- (NSString *__nonnull)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], [self.host bundlePath]]; }
|
||||
|
||||
- (IBAction)installNow:(id)__unused sender
|
||||
{
|
||||
@@ -57,9 +71,17 @@
|
||||
self.completionBlock = nil;
|
||||
}
|
||||
|
||||
- (void)windowDidLoad
|
||||
{
|
||||
if ([self.updateItem isCriticalUpdate]) {
|
||||
self.skipButton.enabled = NO;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
- (NSImage *__nonnull)applicationIcon
|
||||
{
|
||||
return [self.host icon];
|
||||
return [SUApplicationInfo bestIconForHost:self.host];
|
||||
}
|
||||
|
||||
- (NSString *__nonnull)titleText
|
||||
@@ -86,4 +108,23 @@
|
||||
}
|
||||
}
|
||||
|
||||
- (NSTouchBar *)makeTouchBar
|
||||
{
|
||||
NSTouchBar *touchBar = [[NSClassFromString(@"NSTouchBar") alloc] init];
|
||||
touchBar.defaultItemIdentifiers = @[SUAutomaticUpdateAlertTouchBarIndentifier,];
|
||||
touchBar.principalItemIdentifier = SUAutomaticUpdateAlertTouchBarIndentifier;
|
||||
touchBar.delegate = self;
|
||||
return touchBar;
|
||||
}
|
||||
|
||||
- (NSTouchBarItem *)touchBar:(NSTouchBar * __unused)touchBar makeItemForIdentifier:(NSTouchBarItemIdentifier)identifier API_AVAILABLE(macos(10.12.2))
|
||||
{
|
||||
if ([identifier isEqualToString:SUAutomaticUpdateAlertTouchBarIndentifier]) {
|
||||
NSCustomTouchBarItem* item = [(NSCustomTouchBarItem *)[NSClassFromString(@"NSCustomTouchBarItem") alloc] initWithIdentifier:identifier];
|
||||
item.viewController = [[SUTouchBarButtonGroup alloc] initByReferencingButtons:@[self.installButton, self.laterButton, self.skipButton]];
|
||||
return item;
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
@end
|
||||
Vendored
+1
-3
@@ -9,11 +9,9 @@
|
||||
#ifndef SUAUTOMATICUPDATEDRIVER_H
|
||||
#define SUAUTOMATICUPDATEDRIVER_H
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
#import "SUBasicUpdateDriver.h"
|
||||
#import "SUAutomaticUpdateAlert.h"
|
||||
|
||||
@interface SUAutomaticUpdateDriver : SUBasicUpdateDriver <SUUnarchiverDelegate>
|
||||
@interface SUAutomaticUpdateDriver : SUBasicUpdateDriver
|
||||
|
||||
@end
|
||||
|
||||
|
||||
Vendored
+34
-25
@@ -7,10 +7,15 @@
|
||||
//
|
||||
|
||||
#import "SUAutomaticUpdateDriver.h"
|
||||
|
||||
#import "SUUpdaterPrivate.h"
|
||||
#import "SUUpdaterDelegate.h"
|
||||
#import "SULocalizations.h"
|
||||
#import "SUErrors.h"
|
||||
#import "SUAutomaticUpdateAlert.h"
|
||||
#import "SUHost.h"
|
||||
#import "SUConstants.h"
|
||||
#import "SUAppcastItem.h"
|
||||
#import "SUApplicationInfo.h"
|
||||
|
||||
// If the user hasn't quit in a week, ask them if they want to relaunch to get the latest bits. It doesn't matter that this measure of "one day" is imprecise.
|
||||
static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 24 * 7;
|
||||
@@ -24,7 +29,6 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
|
||||
@interface SUAutomaticUpdateDriver ()
|
||||
|
||||
@property (assign) BOOL postponingInstallation;
|
||||
@property (assign) BOOL showErrors;
|
||||
@property (assign) BOOL willUpdateOnTermination;
|
||||
@property (assign) BOOL isTerminating;
|
||||
@property (strong) SUAutomaticUpdateAlert *alert;
|
||||
@@ -35,7 +39,6 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
|
||||
@implementation SUAutomaticUpdateDriver
|
||||
|
||||
@synthesize postponingInstallation;
|
||||
@synthesize showErrors;
|
||||
@synthesize willUpdateOnTermination;
|
||||
@synthesize isTerminating;
|
||||
@synthesize alert;
|
||||
@@ -44,6 +47,12 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
|
||||
- (void)showUpdateAlert
|
||||
{
|
||||
self.interruptible = NO;
|
||||
[self invalidateShowUpdateAlertTimer];
|
||||
|
||||
if (self.alert) {
|
||||
[self.alert close];
|
||||
}
|
||||
|
||||
self.alert = [[SUAutomaticUpdateAlert alloc] initWithAppcastItem:self.updateItem host:self.host completionBlock:^(SUAutomaticInstallationChoice choice) {
|
||||
[self automaticUpdateAlertFinishedWithChoice:choice];
|
||||
}];
|
||||
@@ -51,7 +60,7 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
|
||||
// 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.
|
||||
if ([self.host isBackgroundApplication]) {
|
||||
if ([SUApplicationInfo isBackgroundApplication:[NSApplication sharedApplication]]) {
|
||||
[[self.alert window] setHidesOnDeactivate:NO];
|
||||
[NSApp activateIgnoringOtherApps:YES];
|
||||
}
|
||||
@@ -62,7 +71,7 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
|
||||
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:) name:NSApplicationDidBecomeActiveNotification object:NSApp];
|
||||
}
|
||||
|
||||
- (void)unarchiverDidFinish:(SUUnarchiver *)__unused ua
|
||||
- (void)unarchiverDidFinish:(id)__unused ua
|
||||
{
|
||||
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:) name:NSApplicationWillTerminateNotification object:nil];
|
||||
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(systemWillPowerOff:) name:NSWorkspaceWillPowerOffNotification object:nil];
|
||||
@@ -73,7 +82,8 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
|
||||
|
||||
self.willUpdateOnTermination = YES;
|
||||
|
||||
id<SUUpdaterDelegate> updaterDelegate = [self.updater delegate];
|
||||
id<SUUpdaterPrivate> updater = self.updater;
|
||||
id<SUUpdaterDelegate> updaterDelegate = [updater delegate];
|
||||
if ([updaterDelegate respondsToSelector:@selector(updater:willInstallUpdateOnQuit:immediateInstallationInvocation:)])
|
||||
{
|
||||
BOOL relaunch = YES;
|
||||
@@ -83,7 +93,7 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
|
||||
[invocation setArgument:&relaunch atIndex:2];
|
||||
[invocation setArgument:&showUI atIndex:3];
|
||||
[invocation setTarget:self];
|
||||
|
||||
|
||||
[updaterDelegate updater:self.updater willInstallUpdateOnQuit:self.updateItem immediateInstallationInvocation:invocation];
|
||||
}
|
||||
|
||||
@@ -101,6 +111,18 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
|
||||
}
|
||||
}
|
||||
|
||||
-(BOOL)resumeUpdateInteractively {
|
||||
if ([self isInterruptible]) {
|
||||
[self showUpdateAlert];
|
||||
return YES;
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
-(BOOL)downloadsUpdatesInBackground {
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (void)stopUpdatingOnTermination
|
||||
{
|
||||
if (self.willUpdateOnTermination)
|
||||
@@ -113,7 +135,8 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
|
||||
|
||||
self.willUpdateOnTermination = NO;
|
||||
|
||||
id<SUUpdaterDelegate> updaterDelegate = [self.updater delegate];
|
||||
id<SUUpdaterPrivate> updater = self.updater;
|
||||
id<SUUpdaterDelegate> updaterDelegate = [updater delegate];
|
||||
if ([updaterDelegate respondsToSelector:@selector(updater:didCancelInstallUpdateOnQuit:)])
|
||||
[updaterDelegate updater:self.updater didCancelInstallUpdateOnQuit:self.updateItem];
|
||||
}
|
||||
@@ -133,6 +156,8 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
|
||||
|
||||
- (void)abortUpdate
|
||||
{
|
||||
[self.alert close];
|
||||
|
||||
self.isTerminating = NO;
|
||||
[self stopUpdatingOnTermination];
|
||||
[self invalidateShowUpdateAlertTimer];
|
||||
@@ -147,6 +172,7 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
|
||||
|
||||
- (void)automaticUpdateAlertFinishedWithChoice:(SUAutomaticInstallationChoice)choice
|
||||
{
|
||||
self.alert = nil;
|
||||
switch (choice)
|
||||
{
|
||||
case SUInstallNowChoice:
|
||||
@@ -174,7 +200,6 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
|
||||
[self stopUpdatingOnTermination];
|
||||
}
|
||||
|
||||
self.showErrors = YES;
|
||||
[super installWithToolAndRelaunch:relaunch displayingUserInterface:showUI];
|
||||
}
|
||||
|
||||
@@ -203,20 +228,4 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
|
||||
}
|
||||
}
|
||||
|
||||
- (void)abortUpdateWithError:(NSError *)error
|
||||
{
|
||||
if (self.showErrors) {
|
||||
[super abortUpdateWithError:error];
|
||||
} else {
|
||||
// Call delegate separately here because otherwise it won't know we stopped.
|
||||
// Normally this gets called by the superclass
|
||||
id<SUUpdaterDelegate> updaterDelegate = [self.updater delegate];
|
||||
if ([updaterDelegate respondsToSelector:@selector(updater:didAbortWithError:)]) {
|
||||
[updaterDelegate updater:self.updater didAbortWithError:error];
|
||||
}
|
||||
|
||||
[self abortUpdate];
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
Vendored
+15
-11
@@ -9,16 +9,15 @@
|
||||
#ifndef SUBASICUPDATEDRIVER_H
|
||||
#define SUBASICUPDATEDRIVER_H
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
#import "SUUpdateDriver.h"
|
||||
#import "SUUnarchiver.h"
|
||||
#import "SUAppcast.h"
|
||||
#import "SPUDownloader.h"
|
||||
#import "SPUDownloaderDelegate.h"
|
||||
|
||||
@class SUAppcastItem, SUHost;
|
||||
@interface SUBasicUpdateDriver : SUUpdateDriver <NSURLDownloadDelegate, SUUnarchiverDelegate>
|
||||
@class SUAppcast, SUAppcastItem, SUHost, SPUDownloadData;
|
||||
@interface SUBasicUpdateDriver : SUUpdateDriver <SPUDownloaderDelegate>
|
||||
|
||||
@property (strong, readonly) SUAppcastItem *updateItem;
|
||||
@property (strong, readonly) NSURLDownload *download;
|
||||
@property (strong, readonly) SPUDownloader *download;
|
||||
@property (copy, readonly) NSString *downloadPath;
|
||||
|
||||
- (void)checkForUpdatesAtURL:(NSURL *)URL host:(SUHost *)host;
|
||||
@@ -32,15 +31,20 @@
|
||||
- (void)didNotFindUpdate;
|
||||
|
||||
- (void)downloadUpdate;
|
||||
- (void)download:(NSURLDownload *)d decideDestinationWithSuggestedFilename:(NSString *)name;
|
||||
- (void)downloadDidFinish:(NSURLDownload *)d;
|
||||
- (void)download:(NSURLDownload *)download didFailWithError:(NSError *)error;
|
||||
// SPUDownloaderDelegate
|
||||
- (void)downloaderDidSetDestinationName:(NSString *)destinationName temporaryDirectory:(NSString *)temporaryDirectory;
|
||||
- (void)downloaderDidReceiveExpectedContentLength:(int64_t)expectedContentLength;
|
||||
- (void)downloaderDidReceiveDataOfLength:(uint64_t)length;
|
||||
- (void)downloaderDidFinishWithTemporaryDownloadData:(SPUDownloadData *)downloadData;
|
||||
- (void)downloaderDidFailWithError:(NSError *)error;
|
||||
|
||||
- (void)extractUpdate;
|
||||
- (void)unarchiverDidFinish:(SUUnarchiver *)ua;
|
||||
- (void)unarchiverDidFail:(SUUnarchiver *)ua;
|
||||
- (void)failedToApplyDeltaUpdate;
|
||||
|
||||
// Needed to preserve compatibility to subclasses, even though our unarchiver code uses blocks now
|
||||
- (void)unarchiver:(id)ua extractedProgress:(double)progress;
|
||||
- (void)unarchiverDidFinish:(id)ua;
|
||||
|
||||
- (void)installWithToolAndRelaunch:(BOOL)relaunch;
|
||||
- (void)installWithToolAndRelaunch:(BOOL)relaunch displayingUserInterface:(BOOL)showUI;
|
||||
- (void)installerForHost:(SUHost *)host failedWithError:(NSError *)error;
|
||||
|
||||
Vendored
+180
-97
@@ -8,6 +8,7 @@
|
||||
|
||||
#import "SUBasicUpdateDriver.h"
|
||||
|
||||
#import "SUUnarchiverProtocol.h"
|
||||
#import "SUHost.h"
|
||||
#import "SUOperatingSystem.h"
|
||||
#import "SUStandardVersionComparator.h"
|
||||
@@ -15,14 +16,23 @@
|
||||
#import "SUConstants.h"
|
||||
#import "SULog.h"
|
||||
#import "SUBinaryDeltaCommon.h"
|
||||
#import "SUUpdater_Private.h"
|
||||
#import "SUUpdaterPrivate.h"
|
||||
#import "SUUpdaterDelegate.h"
|
||||
#import "SUFileManager.h"
|
||||
#import "SUUpdateValidator.h"
|
||||
#import "SULocalizations.h"
|
||||
#import "SUErrors.h"
|
||||
#import "SUAppcast.h"
|
||||
#import "SUAppcastItem.h"
|
||||
|
||||
#import "SPUURLRequest.h"
|
||||
#import "SPUDownloaderDeprecated.h"
|
||||
#import "SPUDownloaderSession.h"
|
||||
|
||||
@interface SUBasicUpdateDriver ()
|
||||
|
||||
@property (strong) SUAppcastItem *updateItem;
|
||||
@property (strong) NSURLDownload *download;
|
||||
@property (strong) SPUDownloader *download;
|
||||
@property (copy) NSString *downloadPath;
|
||||
|
||||
@property (strong) SUAppcastItem *nonDeltaUpdateItem;
|
||||
@@ -50,15 +60,16 @@
|
||||
[super checkForUpdatesAtURL:URL host:aHost];
|
||||
if ([aHost isRunningOnReadOnlyVolume])
|
||||
{
|
||||
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SURunningFromDiskImageError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:SULocalizedString(@"%1$@ can't be updated when it's running from a read-only volume like a disk image or an optical drive. Move %1$@ to your Applications folder, relaunch it from there, and try again.", nil), [aHost name]] }]];
|
||||
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SURunningFromDiskImageError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:SULocalizedString(@"%1$@ can't be updated, because it was opened from a read-only or a temporary location. Use Finder to copy %1$@ to the Applications folder, relaunch it from there, and try again.", nil), [aHost name]] }]];
|
||||
return;
|
||||
}
|
||||
|
||||
SUAppcast *appcast = [[SUAppcast alloc] init];
|
||||
|
||||
[appcast setUserAgentString:[self.updater userAgentString]];
|
||||
[appcast setHttpHeaders:[self.updater httpHeaders]];
|
||||
[appcast fetchAppcastFromURL:URL completionBlock:^(NSError *error) {
|
||||
id<SUUpdaterPrivate> updater = self.updater;
|
||||
[appcast setUserAgentString:[updater userAgentString]];
|
||||
[appcast setHttpHeaders:[updater httpHeaders]];
|
||||
[appcast fetchAppcastFromURL:URL inBackground:self.downloadsAppcastInBackground completionBlock:^(NSError *error) {
|
||||
if (error) {
|
||||
[self abortUpdateWithError:error];
|
||||
} else {
|
||||
@@ -70,15 +81,16 @@
|
||||
- (id<SUVersionComparison>)versionComparator
|
||||
{
|
||||
id<SUVersionComparison> comparator = nil;
|
||||
|
||||
id<SUUpdaterPrivate> updater = self.updater;
|
||||
|
||||
// Give the delegate a chance to provide a custom version comparator
|
||||
if ([[self.updater delegate] respondsToSelector:@selector(versionComparatorForUpdater:)]) {
|
||||
comparator = [[self.updater delegate] versionComparatorForUpdater:self.updater];
|
||||
if ([[updater delegate] respondsToSelector:@selector(versionComparatorForUpdater:)]) {
|
||||
comparator = [[updater delegate] versionComparatorForUpdater:self.updater];
|
||||
}
|
||||
|
||||
// If we don't get a comparator from the delegate, use the default comparator
|
||||
if (!comparator) {
|
||||
comparator = [SUStandardVersionComparator defaultComparator];
|
||||
comparator = [[SUStandardVersionComparator alloc] init];
|
||||
}
|
||||
|
||||
return comparator;
|
||||
@@ -107,21 +119,26 @@
|
||||
|
||||
+ (BOOL)hostSupportsItem:(SUAppcastItem *)ui
|
||||
{
|
||||
BOOL osOK = [ui isMacOsUpdate];
|
||||
if (([ui minimumSystemVersion] == nil || [[ui minimumSystemVersion] isEqualToString:@""]) &&
|
||||
([ui maximumSystemVersion] == nil || [[ui maximumSystemVersion] isEqualToString:@""])) { return YES; }
|
||||
([ui maximumSystemVersion] == nil || [[ui maximumSystemVersion] isEqualToString:@""])) {
|
||||
return osOK;
|
||||
}
|
||||
|
||||
BOOL minimumVersionOK = TRUE;
|
||||
BOOL maximumVersionOK = TRUE;
|
||||
|
||||
id<SUVersionComparison> versionComparator = [[SUStandardVersionComparator alloc] init];
|
||||
|
||||
// Check minimum and maximum System Version
|
||||
if ([ui minimumSystemVersion] != nil && ![[ui minimumSystemVersion] isEqualToString:@""]) {
|
||||
minimumVersionOK = [[SUStandardVersionComparator defaultComparator] compareVersion:[ui minimumSystemVersion] toVersion:[SUOperatingSystem systemVersionString]] != NSOrderedDescending;
|
||||
minimumVersionOK = [versionComparator compareVersion:[ui minimumSystemVersion] toVersion:[SUOperatingSystem systemVersionString]] != NSOrderedDescending;
|
||||
}
|
||||
if ([ui maximumSystemVersion] != nil && ![[ui maximumSystemVersion] isEqualToString:@""]) {
|
||||
maximumVersionOK = [[SUStandardVersionComparator defaultComparator] compareVersion:[ui maximumSystemVersion] toVersion:[SUOperatingSystem systemVersionString]] != NSOrderedAscending;
|
||||
maximumVersionOK = [versionComparator compareVersion:[ui maximumSystemVersion] toVersion:[SUOperatingSystem systemVersionString]] != NSOrderedAscending;
|
||||
}
|
||||
|
||||
return minimumVersionOK && maximumVersionOK;
|
||||
return minimumVersionOK && maximumVersionOK && osOK;
|
||||
}
|
||||
|
||||
- (BOOL)isItemNewer:(SUAppcastItem *)ui
|
||||
@@ -143,24 +160,29 @@
|
||||
|
||||
- (void)appcastDidFinishLoading:(SUAppcast *)ac
|
||||
{
|
||||
if ([[self.updater delegate] respondsToSelector:@selector(updater:didFinishLoadingAppcast:)]) {
|
||||
[[self.updater delegate] updater:self.updater didFinishLoadingAppcast:ac];
|
||||
id<SUUpdaterPrivate> updater = self.updater;
|
||||
if ([[updater delegate] respondsToSelector:@selector(updater:didFinishLoadingAppcast:)]) {
|
||||
[[updater delegate] updater:self.updater didFinishLoadingAppcast:ac];
|
||||
}
|
||||
|
||||
NSDictionary *userInfo = (ac != nil) ? @{ SUUpdaterAppcastNotificationKey: ac } : nil;
|
||||
NSDictionary *userInfo = @{ SUUpdaterAppcastNotificationKey: ac };
|
||||
[[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterDidFinishLoadingAppCastNotification object:self.updater userInfo:userInfo];
|
||||
|
||||
SUAppcastItem *item = nil;
|
||||
|
||||
// Now we have to find the best valid update in the appcast.
|
||||
if ([[self.updater delegate] respondsToSelector:@selector(bestValidUpdateInAppcast:forUpdater:)]) // Does the delegate want to handle it?
|
||||
if ([[updater delegate] respondsToSelector:@selector(bestValidUpdateInAppcast:forUpdater:)]) // Does the delegate want to handle it?
|
||||
{
|
||||
item = [[updater delegate] bestValidUpdateInAppcast:ac forUpdater:self.updater];
|
||||
}
|
||||
|
||||
if (item != nil) // Does the delegate want to handle it?
|
||||
{
|
||||
item = [[self.updater delegate] bestValidUpdateInAppcast:ac forUpdater:self.updater];
|
||||
if ([item isDeltaUpdate]) {
|
||||
self.nonDeltaUpdateItem = [[self.updater delegate] bestValidUpdateInAppcast:[ac copyWithoutDeltaUpdates] forUpdater:self.updater];
|
||||
self.nonDeltaUpdateItem = [[updater delegate] bestValidUpdateInAppcast:[ac copyWithoutDeltaUpdates] forUpdater:self.updater];
|
||||
}
|
||||
}
|
||||
else // If not, we'll take care of it ourselves.
|
||||
}
|
||||
else // If not, we'll take care of it ourselves.
|
||||
{
|
||||
// Find the best supported update
|
||||
SUAppcastItem *deltaUpdateItem = nil;
|
||||
@@ -174,19 +196,21 @@
|
||||
|
||||
if ([self itemContainsValidUpdate:item]) {
|
||||
self.updateItem = item;
|
||||
[self didFindValidUpdate];
|
||||
[self performSelectorOnMainThread:@selector(didFindValidUpdate) withObject:nil waitUntilDone:NO];
|
||||
} else {
|
||||
self.updateItem = nil;
|
||||
[self didNotFindUpdate];
|
||||
[self performSelectorOnMainThread:@selector(didNotFindUpdate) withObject:nil waitUntilDone:NO];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)didFindValidUpdate
|
||||
{
|
||||
assert(self.updateItem);
|
||||
|
||||
id<SUUpdaterPrivate> updater = self.updater;
|
||||
|
||||
if ([[self.updater delegate] respondsToSelector:@selector(updater:didFindValidUpdate:)]) {
|
||||
[[self.updater delegate] updater:self.updater didFindValidUpdate:self.updateItem];
|
||||
if ([[updater delegate] respondsToSelector:@selector(updater:didFindValidUpdate:)]) {
|
||||
[[updater delegate] updater:self.updater didFindValidUpdate:self.updateItem];
|
||||
}
|
||||
|
||||
[[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterDidFindValidUpdateNotification
|
||||
@@ -197,8 +221,10 @@
|
||||
|
||||
- (void)didNotFindUpdate
|
||||
{
|
||||
if ([[self.updater delegate] respondsToSelector:@selector(updaterDidNotFindUpdate:)]) {
|
||||
[[self.updater delegate] updaterDidNotFindUpdate:self.updater];
|
||||
id<SUUpdaterPrivate> updater = self.updater;
|
||||
|
||||
if ([[updater delegate] respondsToSelector:@selector(updaterDidNotFindUpdate:)]) {
|
||||
[[updater delegate] updaterDidNotFindUpdate:self.updater];
|
||||
}
|
||||
|
||||
[[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterDidNotFindUpdateNotification object:self.updater];
|
||||
@@ -218,7 +244,7 @@
|
||||
cachePath = [cachePaths objectAtIndex:0];
|
||||
}
|
||||
if (!cachePath) {
|
||||
SULog(@"Failed to find user's cache directory! Using system default");
|
||||
SULog(SULogLevelError, @"Failed to find user's cache directory! Using system default");
|
||||
cachePath = NSTemporaryDirectory();
|
||||
}
|
||||
|
||||
@@ -234,93 +260,102 @@
|
||||
|
||||
- (void)downloadUpdate
|
||||
{
|
||||
NSString *bundleIdentifier = self.host.bundle.bundleIdentifier;
|
||||
assert(bundleIdentifier != nil);
|
||||
|
||||
// Clear cache directory so that downloads can't possibly accumulate inside
|
||||
NSString *appCachePath = [self appCachePath];
|
||||
if ([[NSFileManager defaultManager] fileExistsAtPath:appCachePath]) {
|
||||
[[NSFileManager defaultManager] removeItemAtPath:appCachePath error:NULL];
|
||||
}
|
||||
|
||||
|
||||
id<SUUpdaterPrivate> updater = self.updater;
|
||||
|
||||
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[self.updateItem fileURL]];
|
||||
[request setValue:[self.updater userAgentString] forHTTPHeaderField:@"User-Agent"];
|
||||
if ([[self.updater delegate] respondsToSelector:@selector(updater:willDownloadUpdate:withRequest:)]) {
|
||||
[[self.updater delegate] updater:self.updater
|
||||
if (self.downloadsUpdatesInBackground) {
|
||||
request.networkServiceType = NSURLNetworkServiceTypeBackground;
|
||||
}
|
||||
|
||||
[request setValue:[updater userAgentString] forHTTPHeaderField:@"User-Agent"];
|
||||
if ([[updater delegate] respondsToSelector:@selector(updater:willDownloadUpdate:withRequest:)]) {
|
||||
[[updater delegate] updater:self.updater
|
||||
willDownloadUpdate:self.updateItem
|
||||
withRequest:request];
|
||||
}
|
||||
self.download = [[NSURLDownload alloc] initWithRequest:request delegate:self];
|
||||
|
||||
if ([SUOperatingSystem isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){10, 9, 0}]) {
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wunguarded-availability"
|
||||
self.download = [[SPUDownloaderSession alloc] initWithDelegate:self];
|
||||
#pragma clang diagnostic pop
|
||||
}
|
||||
else {
|
||||
self.download = [[SPUDownloaderDeprecated alloc] initWithDelegate:self];
|
||||
}
|
||||
SPUURLRequest *urlRequest = [SPUURLRequest URLRequestWithRequest:request];
|
||||
NSString *desiredFilename = [NSString stringWithFormat:@"%@ %@", [self.host name], [self.updateItem versionString]];
|
||||
[self.download startPersistentDownloadWithRequest:urlRequest bundleIdentifier:bundleIdentifier desiredFilename:desiredFilename];
|
||||
}
|
||||
|
||||
- (void)download:(NSURLDownload *)__unused d decideDestinationWithSuggestedFilename:(NSString *)name
|
||||
|
||||
- (void)downloaderDidSetDestinationName:(NSString *)destinationName temporaryDirectory:(NSString *)temporaryDirectory
|
||||
{
|
||||
NSString *downloadFileName = [NSString stringWithFormat:@"%@ %@", [self.host name], [self.updateItem versionString]];
|
||||
|
||||
NSString *appCachePath = [self appCachePath];
|
||||
|
||||
self.tempDir = [appCachePath stringByAppendingPathComponent:downloadFileName];
|
||||
int cnt = 1;
|
||||
while ([[NSFileManager defaultManager] fileExistsAtPath:self.tempDir] && cnt <= 999)
|
||||
{
|
||||
self.tempDir = [appCachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@ %d", downloadFileName, cnt++]];
|
||||
}
|
||||
|
||||
// Create the temporary directory if necessary.
|
||||
BOOL success = [[NSFileManager defaultManager] createDirectoryAtPath:self.tempDir withIntermediateDirectories:YES attributes:nil error:NULL];
|
||||
if (!success)
|
||||
{
|
||||
// Okay, something's really broken with this user's file structure.
|
||||
[self.download cancel];
|
||||
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUTemporaryDirectoryError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Can't make a temporary directory for the update download at %@.", self.tempDir] }]];
|
||||
}
|
||||
|
||||
self.downloadPath = [self.tempDir stringByAppendingPathComponent:name];
|
||||
[self.download setDestination:self.downloadPath allowOverwrite:YES];
|
||||
self.tempDir = temporaryDirectory;
|
||||
self.downloadPath = [temporaryDirectory stringByAppendingPathComponent:destinationName];
|
||||
}
|
||||
|
||||
- (void)downloadDidFinish:(NSURLDownload *)__unused d
|
||||
- (void)downloaderDidReceiveExpectedContentLength:(int64_t)__unused expectedContentLength
|
||||
{
|
||||
// don't need to do anything here as there's no GUI with this driver (there can be with child classes)
|
||||
}
|
||||
|
||||
- (void)downloaderDidReceiveDataOfLength:(uint64_t)__unused length
|
||||
{
|
||||
// don't need do anything here as there's no GUI with this driver (there can be with child classes)
|
||||
}
|
||||
|
||||
- (void)downloaderDidFinishWithTemporaryDownloadData:(SPUDownloadData * _Nullable)__unused downloadData
|
||||
{
|
||||
// finished. downloadData should be nil as this was a permanent download
|
||||
assert(self.updateItem);
|
||||
|
||||
|
||||
[self extractUpdate];
|
||||
}
|
||||
|
||||
- (void)download:(NSURLDownload *)__unused download didFailWithError:(NSError *)error
|
||||
- (void)downloaderDidFailWithError:(NSError *)error
|
||||
{
|
||||
NSURL *failingUrl = [error.userInfo objectForKey:NSURLErrorFailingURLErrorKey];
|
||||
if (!failingUrl) {
|
||||
failingUrl = [self.updateItem fileURL];
|
||||
}
|
||||
|
||||
if ([[self.updater delegate] respondsToSelector:@selector(updater:failedToDownloadUpdate:error:)]) {
|
||||
[[self.updater delegate] updater:self.updater
|
||||
failedToDownloadUpdate:self.updateItem
|
||||
error:error];
|
||||
|
||||
id<SUUpdaterPrivate> updater = self.updater;
|
||||
|
||||
if ([[updater delegate] respondsToSelector:@selector(updater:failedToDownloadUpdate:error:)]) {
|
||||
[[updater delegate] updater:self.updater
|
||||
failedToDownloadUpdate:self.updateItem
|
||||
error:error];
|
||||
}
|
||||
|
||||
|
||||
NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:@{
|
||||
NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while downloading the update. Please try again later.", nil),
|
||||
NSUnderlyingErrorKey: error,
|
||||
}];
|
||||
NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while downloading the update. Please try again later.", nil),
|
||||
NSUnderlyingErrorKey: error,
|
||||
}];
|
||||
if (failingUrl) {
|
||||
[userInfo setObject:failingUrl forKey:NSURLErrorFailingURLErrorKey];
|
||||
}
|
||||
|
||||
|
||||
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUDownloadError userInfo:userInfo]];
|
||||
}
|
||||
|
||||
- (BOOL)download:(NSURLDownload *)__unused download shouldDecodeSourceDataOfMIMEType:(NSString *)encodingType
|
||||
{
|
||||
// We don't want the download system to extract our gzips.
|
||||
// Note that we use a substring matching here instead of direct comparison because the docs say "application/gzip" but the system *uses* "application/x-gzip". This is a documentation bug.
|
||||
return ([encodingType rangeOfString:@"gzip"].location == NSNotFound);
|
||||
}
|
||||
|
||||
- (void)extractUpdate
|
||||
{
|
||||
SUUnarchiver *unarchiver = [SUUnarchiver unarchiverForPath:self.downloadPath updatingHostBundlePath:self.host.bundlePath withPassword:self.updater.decryptionPassword];
|
||||
id<SUUpdaterPrivate> updater = self.updater;
|
||||
id<SUUnarchiverProtocol> unarchiver = [SUUnarchiver unarchiverForPath:self.downloadPath updatingHostBundlePath:self.host.bundlePath decryptionPassword:updater.decryptionPassword];
|
||||
|
||||
BOOL success;
|
||||
if (!unarchiver) {
|
||||
SULog(@"Error: No valid unarchiver for %@!", self.downloadPath);
|
||||
SULog(SULogLevelError, @"Error: No valid unarchiver for %@!", self.downloadPath);
|
||||
|
||||
success = NO;
|
||||
} else {
|
||||
@@ -333,10 +368,19 @@
|
||||
}
|
||||
|
||||
if (!success) {
|
||||
[self unarchiverDidFail:nil];
|
||||
NSError *reason = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{NSLocalizedDescriptionKey: @"Failed to extract update."}];
|
||||
[self unarchiverDidFailWithError:reason];
|
||||
} else {
|
||||
unarchiver.delegate = self;
|
||||
[unarchiver start];
|
||||
[unarchiver unarchiveWithCompletionBlock:^(NSError *err){
|
||||
if (err) {
|
||||
[self unarchiverDidFailWithError:err];
|
||||
return;
|
||||
}
|
||||
|
||||
[self performSelectorOnMainThread:@selector(unarchiverDidFinish:) withObject:nil waitUntilDone:NO];
|
||||
} progressBlock:^(double progress) {
|
||||
[self unarchiver:nil extractedProgress:progress];
|
||||
}];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -349,14 +393,20 @@
|
||||
[self downloadUpdate];
|
||||
}
|
||||
|
||||
- (void)unarchiverDidFinish:(SUUnarchiver *)__unused ua
|
||||
// By default does nothing, can be overridden
|
||||
- (void)unarchiver:(id)__unused ua extractedProgress:(double)__unused progress
|
||||
{
|
||||
}
|
||||
|
||||
// Note this method can be overridden (and is)
|
||||
- (void)unarchiverDidFinish:(id)__unused ua
|
||||
{
|
||||
assert(self.updateItem);
|
||||
|
||||
|
||||
[self installWithToolAndRelaunch:YES];
|
||||
}
|
||||
|
||||
- (void)unarchiverDidFail:(SUUnarchiver *)__unused ua
|
||||
- (void)unarchiverDidFailWithError:(NSError *)err
|
||||
{
|
||||
// No longer needed
|
||||
self.updateValidator = nil;
|
||||
@@ -365,8 +415,8 @@
|
||||
[self failedToApplyDeltaUpdate];
|
||||
return;
|
||||
}
|
||||
|
||||
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while extracting the archive. Please try again later.", nil) }]];
|
||||
|
||||
[self abortUpdateWithError:err];
|
||||
}
|
||||
|
||||
- (void)installWithToolAndRelaunch:(BOOL)relaunch
|
||||
@@ -400,6 +450,12 @@
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (BOOL)mayUpdateAndRestart
|
||||
{
|
||||
id<SUUpdaterPrivate> updater = self.updater;
|
||||
return (!updater.delegate || ![updater.delegate respondsToSelector:@selector(updaterShouldRelaunchApplication:)] || [updater.delegate updaterShouldRelaunchApplication:self.updater]);
|
||||
}
|
||||
|
||||
- (void)installWithToolAndRelaunch:(BOOL)relaunch displayingUserInterface:(BOOL)showUI
|
||||
{
|
||||
assert(self.updateItem);
|
||||
@@ -415,15 +471,16 @@
|
||||
return;
|
||||
}
|
||||
|
||||
if (![self.updater mayUpdateAndRestart])
|
||||
if (![self mayUpdateAndRestart])
|
||||
{
|
||||
[self abortUpdate];
|
||||
return;
|
||||
}
|
||||
|
||||
// Give the host app an opportunity to postpone the install and relaunch.
|
||||
id<SUUpdaterPrivate> updater = self.updater;
|
||||
static BOOL postponedOnce = NO;
|
||||
id<SUUpdaterDelegate> updaterDelegate = [self.updater delegate];
|
||||
id<SUUpdaterDelegate> updaterDelegate = [updater delegate];
|
||||
if (!postponedOnce && [updaterDelegate respondsToSelector:@selector(updater:shouldPostponeRelaunchForUpdate:untilInvoking:)])
|
||||
{
|
||||
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[[self class] instanceMethodSignatureForSelector:@selector(installWithToolAndRelaunch:)]];
|
||||
@@ -441,18 +498,37 @@
|
||||
[updaterDelegate updater:self.updater willInstallUpdate:self.updateItem];
|
||||
}
|
||||
|
||||
NSBundle *sparkleBundle = self.updater.sparkleBundle;
|
||||
NSBundle *sparkleBundle = updater.sparkleBundle;
|
||||
if (!sparkleBundle) {
|
||||
SULog(SULogLevelError, @"Sparkle bundle is gone?");
|
||||
return;
|
||||
}
|
||||
|
||||
// Copy the relauncher into a temporary directory so we can get to it after the new version's installed.
|
||||
// Only the paranoid survive: if there's already a stray copy of relaunch there, we would have problems.
|
||||
NSString *const relaunchToolName = @"" SPARKLE_RELAUNCH_TOOL_NAME;
|
||||
NSString *const relaunchToolSourcePath = [sparkleBundle pathForResource:relaunchToolName ofType:@"app"];
|
||||
NSString *const relaunchToolSourceName = @"" SPARKLE_RELAUNCH_TOOL_NAME;
|
||||
NSString *const relaunchToolSourcePath = [sparkleBundle pathForResource:relaunchToolSourceName ofType:@"app"];
|
||||
NSString *relaunchCopyTargetPath = nil;
|
||||
NSError *error = nil;
|
||||
BOOL copiedRelaunchPath = NO;
|
||||
|
||||
if (!relaunchToolSourceName || ![relaunchToolSourceName length]) {
|
||||
SULog(SULogLevelError, @"SPARKLE_RELAUNCH_TOOL_NAME not configued");
|
||||
}
|
||||
|
||||
if (!relaunchToolSourcePath) {
|
||||
SULog(SULogLevelError, @"Sparkle.framework is damaged. %@ is missing", relaunchToolSourceName);
|
||||
}
|
||||
|
||||
if (relaunchToolSourcePath) {
|
||||
relaunchCopyTargetPath = [[self appCachePath] stringByAppendingPathComponent:[relaunchToolSourcePath lastPathComponent]];
|
||||
NSString *hostBundleBaseName = [[self.host.bundlePath lastPathComponent] stringByDeletingPathExtension];
|
||||
if (!hostBundleBaseName) {
|
||||
SULog(SULogLevelError, @"Unable to get bundlePath");
|
||||
hostBundleBaseName = @"Sparkle";
|
||||
}
|
||||
NSString *relaunchCopyBaseName = [NSString stringWithFormat:@"%@ (Autoupdate).app", hostBundleBaseName];
|
||||
|
||||
relaunchCopyTargetPath = [[self appCachePath] stringByAppendingPathComponent:relaunchCopyBaseName];
|
||||
|
||||
SUFileManager *fileManager = [SUFileManager defaultManager];
|
||||
|
||||
@@ -468,7 +544,7 @@
|
||||
// Perhaps in a sandboxed environment this matters more. Note that this may not be a fatal error.
|
||||
NSError *quarantineError = nil;
|
||||
if (![fileManager releaseItemFromQuarantineAtRootURL:relaunchCopyTargetURL error:&quarantineError]) {
|
||||
SULog(@"Failed to release quarantine on %@ with error %@", relaunchCopyTargetPath, quarantineError);
|
||||
SULog(SULogLevelError, @"Failed to release quarantine on %@ with error %@", relaunchCopyTargetPath, quarantineError);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -499,9 +575,15 @@
|
||||
|
||||
NSString *pathToRelaunch = [self.host bundlePath];
|
||||
if ([updaterDelegate respondsToSelector:@selector(pathToRelaunchForUpdater:)]) {
|
||||
pathToRelaunch = [updaterDelegate pathToRelaunchForUpdater:self.updater];
|
||||
NSString *delegateRelaunchPath = [updaterDelegate pathToRelaunchForUpdater:self.updater];
|
||||
if (delegateRelaunchPath != nil) {
|
||||
pathToRelaunch = delegateRelaunchPath;
|
||||
}
|
||||
}
|
||||
|
||||
//Set relaunching flag.
|
||||
[self.host setBool:YES forUserDefaultsKey:SUUpdateRelaunchingMarkerKey];
|
||||
|
||||
[NSTask launchedTaskWithLaunchPath:relaunchToolPath arguments:@[[self.host bundlePath],
|
||||
pathToRelaunch,
|
||||
[NSString stringWithFormat:@"%d", [[NSProcessInfo processInfo] processIdentifier]],
|
||||
@@ -557,7 +639,7 @@
|
||||
NSError *errorToDisplay = error;
|
||||
int finiteRecursion=5;
|
||||
do {
|
||||
SULog(@"Error: %@ %@ (URL %@)", errorToDisplay.localizedDescription, errorToDisplay.localizedFailureReason, [errorToDisplay.userInfo objectForKey:NSURLErrorFailingURLErrorKey]);
|
||||
SULog(SULogLevelError, @"Error: %@ %@ (URL %@)", errorToDisplay.localizedDescription, errorToDisplay.localizedFailureReason, [errorToDisplay.userInfo objectForKey:NSURLErrorFailingURLErrorKey]);
|
||||
errorToDisplay = [errorToDisplay.userInfo objectForKey:NSUnderlyingErrorKey];
|
||||
} while(--finiteRecursion && errorToDisplay);
|
||||
}
|
||||
@@ -566,7 +648,8 @@
|
||||
}
|
||||
|
||||
// Notify host app that update has aborted
|
||||
id<SUUpdaterDelegate> updaterDelegate = [self.updater delegate];
|
||||
id<SUUpdaterPrivate> updater = self.updater;
|
||||
id<SUUpdaterDelegate> updaterDelegate = [updater delegate];
|
||||
if ([updaterDelegate respondsToSelector:@selector(updater:didAbortWithError:)]) {
|
||||
[updaterDelegate updater:self.updater didAbortWithError:error];
|
||||
}
|
||||
|
||||
Vendored
+3
-1
@@ -9,7 +9,9 @@
|
||||
#ifndef SUBINARYDELTAAPPLY_H
|
||||
#define SUBINARYDELTAAPPLY_H
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
@class NSString;
|
||||
BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFile, BOOL verbose, NSError * __autoreleasing *error);
|
||||
BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFile, BOOL verbose, void (^progressCallback)(double), NSError * __autoreleasing *error);
|
||||
|
||||
#endif
|
||||
Vendored
+46
-31
@@ -15,17 +15,19 @@
|
||||
#include <stdlib.h>
|
||||
#include <xar/xar.h>
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
|
||||
static BOOL applyBinaryDeltaToFile(xar_t x, xar_file_t file, NSString *sourceFilePath, NSString *destinationFilePath)
|
||||
{
|
||||
NSString *patchFile = temporaryFilename(@"apply-binary-delta");
|
||||
xar_extract_tofile(x, file, [patchFile fileSystemRepresentation]);
|
||||
const char *argv[] = {"/usr/bin/bspatch", [sourceFilePath fileSystemRepresentation], [destinationFilePath fileSystemRepresentation], [patchFile fileSystemRepresentation]};
|
||||
const char *argv[] = { "/usr/bin/bspatch", [sourceFilePath fileSystemRepresentation], [destinationFilePath fileSystemRepresentation], [patchFile fileSystemRepresentation] };
|
||||
BOOL success = (bspatch(4, argv) == 0);
|
||||
unlink([patchFile fileSystemRepresentation]);
|
||||
return success;
|
||||
}
|
||||
|
||||
BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFile, BOOL verbose, NSError * __autoreleasing *error)
|
||||
BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFile, BOOL verbose, void (^progressCallback)(double progress), NSError *__autoreleasing *error)
|
||||
{
|
||||
xar_t x = xar_open([patchFile fileSystemRepresentation], READ);
|
||||
if (!x) {
|
||||
@@ -34,69 +36,71 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
SUBinaryDeltaMajorVersion majorDiffVersion = FIRST_DELTA_DIFF_MAJOR_VERSION;
|
||||
SUBinaryDeltaMinorVersion minorDiffVersion = FIRST_DELTA_DIFF_MINOR_VERSION;
|
||||
int minorDiffVersion = 0;
|
||||
|
||||
NSString *expectedBeforeHashv1 = nil;
|
||||
NSString *expectedAfterHashv1 = nil;
|
||||
|
||||
|
||||
NSString *expectedNewBeforeHash = nil;
|
||||
NSString *expectedNewAfterHash = nil;
|
||||
|
||||
|
||||
progressCallback(0/6.0);
|
||||
|
||||
xar_subdoc_t subdoc;
|
||||
for (subdoc = xar_subdoc_first(x); subdoc; subdoc = xar_subdoc_next(subdoc)) {
|
||||
if (!strcmp(xar_subdoc_name(subdoc), BINARY_DELTA_ATTRIBUTES_KEY)) {
|
||||
const char *value = 0;
|
||||
|
||||
|
||||
// available in version 2.0 or later
|
||||
xar_subdoc_prop_get(subdoc, MAJOR_DIFF_VERSION_KEY, &value);
|
||||
if (value)
|
||||
majorDiffVersion = (SUBinaryDeltaMajorVersion)[@(value) intValue];
|
||||
|
||||
|
||||
// available in version 2.0 or later
|
||||
xar_subdoc_prop_get(subdoc, MINOR_DIFF_VERSION_KEY, &value);
|
||||
if (value)
|
||||
minorDiffVersion = (SUBinaryDeltaMinorVersion)[@(value) intValue];
|
||||
|
||||
minorDiffVersion = [@(value) intValue];
|
||||
|
||||
// available in version 2.0 or later
|
||||
xar_subdoc_prop_get(subdoc, BEFORE_TREE_SHA1_KEY, &value);
|
||||
if (value)
|
||||
expectedNewBeforeHash = @(value);
|
||||
|
||||
|
||||
// available in version 2.0 or later
|
||||
xar_subdoc_prop_get(subdoc, AFTER_TREE_SHA1_KEY, &value);
|
||||
if (value)
|
||||
expectedNewAfterHash = @(value);
|
||||
|
||||
|
||||
// only available in version 1.0
|
||||
xar_subdoc_prop_get(subdoc, BEFORE_TREE_SHA1_OLD_KEY, &value);
|
||||
if (value)
|
||||
expectedBeforeHashv1 = @(value);
|
||||
|
||||
|
||||
// only available in version 1.0
|
||||
xar_subdoc_prop_get(subdoc, AFTER_TREE_SHA1_OLD_KEY, &value);
|
||||
if (value)
|
||||
expectedAfterHashv1 = @(value);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (majorDiffVersion < FIRST_DELTA_DIFF_MAJOR_VERSION) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadCorruptFileError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Unable to identify diff-version %u in delta. Giving up.", majorDiffVersion] }];
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
if (majorDiffVersion > LATEST_DELTA_DIFF_MAJOR_VERSION) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"A later version is needed to apply this patch (on major version %u, but patch requests version %u).", LATEST_DELTA_DIFF_MAJOR_VERSION, majorDiffVersion] }];
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
BOOL usesNewTreeHash = MAJOR_VERSION_IS_AT_LEAST(majorDiffVersion, SUBeigeMajorVersion);
|
||||
|
||||
|
||||
NSString *expectedBeforeHash = usesNewTreeHash ? expectedNewBeforeHash : expectedBeforeHashv1;
|
||||
NSString *expectedAfterHash = usesNewTreeHash ? expectedNewAfterHash : expectedAfterHashv1;
|
||||
|
||||
@@ -111,7 +115,9 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi
|
||||
fprintf(stderr, "Applying version %u.%u patch...\n", majorDiffVersion, minorDiffVersion);
|
||||
fprintf(stderr, "Verifying source...");
|
||||
}
|
||||
|
||||
|
||||
progressCallback(1/6.0);
|
||||
|
||||
NSString *beforeHash = hashOfTreeWithVersion(source, majorDiffVersion);
|
||||
if (!beforeHash) {
|
||||
if (verbose) {
|
||||
@@ -136,7 +142,9 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi
|
||||
if (verbose) {
|
||||
fprintf(stderr, "\nCopying files...");
|
||||
}
|
||||
|
||||
|
||||
progressCallback(2/6.0);
|
||||
|
||||
if (!removeTree(destination)) {
|
||||
if (verbose) {
|
||||
fprintf(stderr, "\n");
|
||||
@@ -146,6 +154,9 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
progressCallback(3/6.0);
|
||||
|
||||
if (!copyTree(source, destination)) {
|
||||
if (verbose) {
|
||||
fprintf(stderr, "\n");
|
||||
@@ -155,7 +166,9 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
progressCallback(4/6.0);
|
||||
|
||||
BOOL hasExtractKeyAvailable = MAJOR_VERSION_IS_AT_LEAST(majorDiffVersion, SUBeigeMajorVersion);
|
||||
|
||||
if (verbose) {
|
||||
@@ -172,10 +185,9 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi
|
||||
// Don't use -[NSFileManager fileExistsAtPath:] because it will follow symbolic links
|
||||
BOOL fileExisted = verbose && [fileManager attributesOfItemAtPath:destinationFilePath error:nil];
|
||||
BOOL removedFile = NO;
|
||||
|
||||
|
||||
const char *value;
|
||||
if (!xar_prop_get(file, DELETE_KEY, &value) ||
|
||||
(!hasExtractKeyAvailable && !xar_prop_get(file, DELETE_THEN_EXTRACT_OLD_KEY, &value))) {
|
||||
if (!xar_prop_get(file, DELETE_KEY, &value) || (!hasExtractKeyAvailable && !xar_prop_get(file, DELETE_THEN_EXTRACT_OLD_KEY, &value))) {
|
||||
if (!removeTree(destinationFilePath)) {
|
||||
if (verbose) {
|
||||
fprintf(stderr, "\n");
|
||||
@@ -191,7 +203,7 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
removedFile = YES;
|
||||
}
|
||||
|
||||
@@ -205,13 +217,12 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
if (verbose) {
|
||||
fprintf(stderr, "\n🔨 %s %s", VERBOSE_PATCHED, [path fileSystemRepresentation]);
|
||||
}
|
||||
} else if ((hasExtractKeyAvailable && !xar_prop_get(file, EXTRACT_KEY, &value)) ||
|
||||
(!hasExtractKeyAvailable && xar_prop_get(file, MODIFY_PERMISSIONS_KEY, &value))) { // extract and permission modifications don't coexist
|
||||
|
||||
} else if ((hasExtractKeyAvailable && !xar_prop_get(file, EXTRACT_KEY, &value)) || (!hasExtractKeyAvailable && xar_prop_get(file, MODIFY_PERMISSIONS_KEY, &value))) { // extract and permission modifications don't coexist
|
||||
|
||||
if (xar_extract_tofile(x, file, [destinationFilePath fileSystemRepresentation]) != 0) {
|
||||
if (verbose) {
|
||||
fprintf(stderr, "\n");
|
||||
@@ -221,7 +232,7 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
if (verbose) {
|
||||
if (fileExisted) {
|
||||
fprintf(stderr, "\n✏️ %s %s", VERBOSE_UPDATED, [path fileSystemRepresentation]);
|
||||
@@ -232,7 +243,7 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi
|
||||
} else if (verbose && removedFile) {
|
||||
fprintf(stderr, "\n❌ %s %s", VERBOSE_DELETED, [path fileSystemRepresentation]);
|
||||
}
|
||||
|
||||
|
||||
if (!xar_prop_get(file, MODIFY_PERMISSIONS_KEY, &value)) {
|
||||
mode_t mode = (mode_t)[[NSString stringWithUTF8String:value] intValue];
|
||||
if (!modifyPermissions(destinationFilePath, mode)) {
|
||||
@@ -244,7 +255,7 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
if (verbose) {
|
||||
fprintf(stderr, "\n👮 %s %s (0%o)", VERBOSE_MODIFIED, [path fileSystemRepresentation], mode);
|
||||
}
|
||||
@@ -252,6 +263,8 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi
|
||||
}
|
||||
xar_close(x);
|
||||
|
||||
progressCallback(5/6.0);
|
||||
|
||||
if (verbose) {
|
||||
fprintf(stderr, "\nVerifying destination...");
|
||||
}
|
||||
@@ -277,6 +290,8 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi
|
||||
return NO;
|
||||
}
|
||||
|
||||
progressCallback(6/6.0);
|
||||
|
||||
if (verbose) {
|
||||
fprintf(stderr, "\nDone!\n");
|
||||
}
|
||||
|
||||
Vendored
+1
-10
@@ -57,16 +57,7 @@ typedef NS_ENUM(uint16_t, SUBinaryDeltaMajorVersion)
|
||||
SUBeigeMajorVersion = 2
|
||||
};
|
||||
|
||||
// Only keep track of the latest minor version for each major version
|
||||
typedef NS_ENUM(uint16_t, SUBinaryDeltaMinorVersion)
|
||||
{
|
||||
SUAzureMinorVersion = 1,
|
||||
SUBeigeMinorVersion = 1,
|
||||
};
|
||||
|
||||
#define FIRST_DELTA_DIFF_MAJOR_VERSION SUAzureMajorVersion
|
||||
#define FIRST_DELTA_DIFF_MINOR_VERSION ((SUBinaryDeltaMinorVersion)0)
|
||||
|
||||
#define LATEST_DELTA_DIFF_MAJOR_VERSION SUBeigeMajorVersion
|
||||
|
||||
extern int compareFiles(const FTSENT **a, const FTSENT **b);
|
||||
@@ -80,5 +71,5 @@ extern NSString *pathRelativeToDirectory(NSString *directory, NSString *path);
|
||||
NSString *temporaryFilename(NSString *base);
|
||||
NSString *temporaryDirectory(NSString *base);
|
||||
NSString *stringWithFileSystemRepresentation(const char*);
|
||||
SUBinaryDeltaMinorVersion latestMinorVersionForMajorVersion(SUBinaryDeltaMajorVersion majorVersion);
|
||||
int latestMinorVersionForMajorVersion(SUBinaryDeltaMajorVersion majorVersion);
|
||||
#endif
|
||||
Vendored
+24
-18
@@ -18,6 +18,8 @@
|
||||
#include <sys/stat.h>
|
||||
#include <xar/xar.h>
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
|
||||
int compareFiles(const FTSENT **a, const FTSENT **b)
|
||||
{
|
||||
return strcoll((*a)->fts_name, (*b)->fts_name);
|
||||
@@ -32,19 +34,20 @@ NSString *pathRelativeToDirectory(NSString *directory, NSString *path)
|
||||
return path;
|
||||
}
|
||||
|
||||
NSString *stringWithFileSystemRepresentation(const char *input) {
|
||||
NSString *stringWithFileSystemRepresentation(const char *input)
|
||||
{
|
||||
return [[NSFileManager defaultManager] stringWithFileSystemRepresentation:input length:strlen(input)];
|
||||
}
|
||||
|
||||
SUBinaryDeltaMinorVersion latestMinorVersionForMajorVersion(SUBinaryDeltaMajorVersion majorVersion)
|
||||
int latestMinorVersionForMajorVersion(SUBinaryDeltaMajorVersion majorVersion)
|
||||
{
|
||||
switch (majorVersion) {
|
||||
case SUAzureMajorVersion:
|
||||
return SUAzureMinorVersion;
|
||||
return 1;
|
||||
case SUBeigeMajorVersion:
|
||||
return SUBeigeMinorVersion;
|
||||
return 2;
|
||||
}
|
||||
return (SUBinaryDeltaMinorVersion)0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
NSString *temporaryFilename(NSString *base)
|
||||
@@ -73,18 +76,18 @@ NSString *temporaryDirectory(NSString *base)
|
||||
NSString *template = [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.XXXXXXXXXX", base]];
|
||||
NSMutableData *data = [NSMutableData data];
|
||||
[data appendBytes:template.fileSystemRepresentation length:strlen(template.fileSystemRepresentation) + 1];
|
||||
|
||||
|
||||
char *buffer = data.mutableBytes;
|
||||
char *templateResult = mkdtemp(buffer);
|
||||
if (templateResult == NULL) {
|
||||
perror("mkdtemp");
|
||||
return nil;
|
||||
}
|
||||
|
||||
|
||||
return stringWithFileSystemRepresentation(templateResult);
|
||||
}
|
||||
|
||||
static void _hashOfBuffer(unsigned char *hash, const char* buffer, ssize_t bufferLength)
|
||||
static void _hashOfBuffer(unsigned char *hash, const char *buffer, ssize_t bufferLength)
|
||||
{
|
||||
assert(bufferLength >= 0 && bufferLength <= UINT32_MAX);
|
||||
CC_SHA1_CTX hashContext;
|
||||
@@ -93,7 +96,7 @@ static void _hashOfBuffer(unsigned char *hash, const char* buffer, ssize_t buffe
|
||||
CC_SHA1_Final(hash, &hashContext);
|
||||
}
|
||||
|
||||
static BOOL _hashOfFileContents(unsigned char* hash, FTSENT *ent)
|
||||
static BOOL _hashOfFileContents(unsigned char *hash, FTSENT *ent)
|
||||
{
|
||||
if (ent->fts_info == FTS_SL) {
|
||||
char linkDestination[MAXPATHLEN + 1];
|
||||
@@ -116,12 +119,12 @@ static BOOL _hashOfFileContents(unsigned char* hash, FTSENT *ent)
|
||||
_hashOfBuffer(hash, NULL, 0);
|
||||
} else {
|
||||
void *buffer = mmap(0, (size_t)fileSize, PROT_READ, MAP_FILE | MAP_PRIVATE, fileDescriptor, 0);
|
||||
if (buffer == (void*)-1) {
|
||||
if (buffer == (void *)-1) {
|
||||
close(fileDescriptor);
|
||||
perror("mmap");
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
_hashOfBuffer(hash, buffer, fileSize);
|
||||
munmap(buffer, (size_t)fileSize);
|
||||
}
|
||||
@@ -145,12 +148,12 @@ NSData *hashOfFileContents(FTSENT *ent)
|
||||
|
||||
NSString *hashOfTreeWithVersion(NSString *path, uint16_t majorVersion)
|
||||
{
|
||||
char pathBuffer[PATH_MAX] = {0};
|
||||
char pathBuffer[PATH_MAX] = { 0 };
|
||||
if (![path getFileSystemRepresentation:pathBuffer maxLength:sizeof(pathBuffer)]) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
char * const sourcePaths[] = {pathBuffer, 0};
|
||||
char *const sourcePaths[] = { pathBuffer, 0 };
|
||||
FTS *fts = fts_open(sourcePaths, FTS_PHYSICAL | FTS_NOCHDIR, compareFiles);
|
||||
if (!fts) {
|
||||
perror("fts_open");
|
||||
@@ -160,16 +163,19 @@ NSString *hashOfTreeWithVersion(NSString *path, uint16_t majorVersion)
|
||||
CC_SHA1_CTX hashContext;
|
||||
CC_SHA1_Init(&hashContext);
|
||||
|
||||
// Ensure the path uses filesystem-specific Unicode normalization #1017
|
||||
NSString *normalizedPath = stringWithFileSystemRepresentation(pathBuffer);
|
||||
|
||||
FTSENT *ent = 0;
|
||||
while ((ent = fts_read(fts))) {
|
||||
if (ent->fts_info != FTS_F && ent->fts_info != FTS_SL && ent->fts_info != FTS_D)
|
||||
continue;
|
||||
|
||||
|
||||
if (ent->fts_info == FTS_D && !MAJOR_VERSION_IS_AT_LEAST(majorVersion, SUBeigeMajorVersion)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
NSString *relativePath = pathRelativeToDirectory(path, stringWithFileSystemRepresentation(ent->fts_path));
|
||||
|
||||
NSString *relativePath = pathRelativeToDirectory(normalizedPath, stringWithFileSystemRepresentation(ent->fts_path));
|
||||
if (relativePath.length == 0)
|
||||
continue;
|
||||
|
||||
@@ -181,12 +187,12 @@ NSString *hashOfTreeWithVersion(NSString *path, uint16_t majorVersion)
|
||||
|
||||
const char *relativePathBytes = [relativePath fileSystemRepresentation];
|
||||
CC_SHA1_Update(&hashContext, relativePathBytes, (CC_LONG)strlen(relativePathBytes));
|
||||
|
||||
|
||||
if (MAJOR_VERSION_IS_AT_LEAST(majorVersion, SUBeigeMajorVersion)) {
|
||||
uint16_t mode = ent->fts_statp->st_mode;
|
||||
uint16_t type = ent->fts_info;
|
||||
uint16_t permissions = mode & PERMISSION_FLAGS;
|
||||
|
||||
|
||||
CC_SHA1_Update(&hashContext, &type, sizeof(type));
|
||||
CC_SHA1_Update(&hashContext, &permissions, sizeof(permissions));
|
||||
}
|
||||
|
||||
Vendored
+70
-71
@@ -21,6 +21,8 @@
|
||||
#include <sys/xattr.h>
|
||||
#include <xar/xar.h>
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
|
||||
extern int bsdiff(int argc, const char **argv);
|
||||
|
||||
@interface CreateBinaryDeltaOperation : NSOperation
|
||||
@@ -56,7 +58,7 @@ extern int bsdiff(int argc, const char **argv);
|
||||
- (void)main
|
||||
{
|
||||
NSString *temporaryFile = temporaryFilename(@"BinaryDelta");
|
||||
const char *argv[] = {"/usr/bin/bsdiff", [self._fromPath fileSystemRepresentation], [self._toPath fileSystemRepresentation], [temporaryFile fileSystemRepresentation]};
|
||||
const char *argv[] = { "/usr/bin/bsdiff", [self._fromPath fileSystemRepresentation], [self._toPath fileSystemRepresentation], [temporaryFile fileSystemRepresentation] };
|
||||
int result = bsdiff(4, argv);
|
||||
if (!result)
|
||||
self.resultPath = temporaryFile;
|
||||
@@ -75,14 +77,17 @@ static NSDictionary *infoForFile(FTSENT *ent)
|
||||
if (!hash) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
|
||||
off_t size = (ent->fts_info != FTS_D) ? ent->fts_statp->st_size : 0;
|
||||
|
||||
|
||||
assert(ent->fts_statp != NULL);
|
||||
|
||||
|
||||
mode_t permissions = ent->fts_statp->st_mode & PERMISSION_FLAGS;
|
||||
|
||||
return @{INFO_HASH_KEY: hash, INFO_TYPE_KEY: @(ent->fts_info), INFO_PERMISSIONS_KEY : @(permissions), INFO_SIZE_KEY: @(size)};
|
||||
|
||||
return @{ INFO_HASH_KEY: hash,
|
||||
INFO_TYPE_KEY: @(ent->fts_info),
|
||||
INFO_PERMISSIONS_KEY: @(permissions),
|
||||
INFO_SIZE_KEY: @(size) };
|
||||
}
|
||||
|
||||
static bool aclExists(const FTSENT *ent)
|
||||
@@ -91,7 +96,7 @@ static bool aclExists(const FTSENT *ent)
|
||||
if (ent->fts_info == FTS_SL) {
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
acl_t acl = acl_get_link_np(ent->fts_path, ACL_TYPE_EXTENDED);
|
||||
if (acl != NULL) {
|
||||
acl_entry_t entry;
|
||||
@@ -109,28 +114,26 @@ static bool codeSignatureExtendedAttributeExists(const FTSENT *ent)
|
||||
if (listSize == -1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
char *buffer = malloc((size_t)listSize);
|
||||
assert(buffer != NULL);
|
||||
|
||||
|
||||
ssize_t sizeBack = listxattr(ent->fts_path, buffer, (size_t)listSize, options);
|
||||
assert(sizeBack == listSize);
|
||||
|
||||
|
||||
size_t startCharacterIndex = 0;
|
||||
for (size_t characterIndex = 0; characterIndex < (size_t)listSize; characterIndex++) {
|
||||
if (buffer[characterIndex] == '\0') {
|
||||
char *attribute = &buffer[startCharacterIndex];
|
||||
size_t length = characterIndex - startCharacterIndex;
|
||||
if (strncmp(APPLE_CODE_SIGN_XATTR_CODE_DIRECTORY_KEY, attribute, length) == 0 ||
|
||||
strncmp(APPLE_CODE_SIGN_XATTR_CODE_REQUIREMENTS_KEY, attribute, length) == 0 ||
|
||||
strncmp(APPLE_CODE_SIGN_XATTR_CODE_SIGNATURE_KEY, attribute, length) == 0) {
|
||||
if (strncmp(APPLE_CODE_SIGN_XATTR_CODE_DIRECTORY_KEY, attribute, length) == 0 || strncmp(APPLE_CODE_SIGN_XATTR_CODE_REQUIREMENTS_KEY, attribute, length) == 0 || strncmp(APPLE_CODE_SIGN_XATTR_CODE_SIGNATURE_KEY, attribute, length) == 0) {
|
||||
free(buffer);
|
||||
return true;
|
||||
}
|
||||
startCharacterIndex = characterIndex + 1;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
free(buffer);
|
||||
return false;
|
||||
}
|
||||
@@ -138,7 +141,7 @@ static bool codeSignatureExtendedAttributeExists(const FTSENT *ent)
|
||||
static NSString *absolutePath(NSString *path)
|
||||
{
|
||||
NSURL *url = [[NSURL alloc] initFileURLWithPath:path];
|
||||
return [[url absoluteURL] path];
|
||||
return [[url absoluteURL] path];
|
||||
}
|
||||
|
||||
static NSString *temporaryPatchFile(NSString *patchFile)
|
||||
@@ -151,7 +154,7 @@ static NSString *temporaryPatchFile(NSString *patchFile)
|
||||
|
||||
#define MIN_FILE_SIZE_FOR_CREATING_DELTA 4096
|
||||
|
||||
static BOOL shouldSkipDeltaCompression(NSDictionary* originalInfo, NSDictionary *newInfo)
|
||||
static BOOL shouldSkipDeltaCompression(NSDictionary *originalInfo, NSDictionary *newInfo)
|
||||
{
|
||||
unsigned long long fileSize = [newInfo[INFO_SIZE_KEY] unsignedLongLongValue];
|
||||
if (fileSize < MIN_FILE_SIZE_FOR_CREATING_DELTA) {
|
||||
@@ -165,7 +168,7 @@ static BOOL shouldSkipDeltaCompression(NSDictionary* originalInfo, NSDictionary
|
||||
if ([originalInfo[INFO_TYPE_KEY] unsignedShortValue] != [newInfo[INFO_TYPE_KEY] unsignedShortValue]) {
|
||||
return YES;
|
||||
}
|
||||
|
||||
|
||||
if ([originalInfo[INFO_HASH_KEY] isEqual:newInfo[INFO_HASH_KEY]]) {
|
||||
// this is possible if just the permissions have changed
|
||||
return YES;
|
||||
@@ -174,7 +177,7 @@ static BOOL shouldSkipDeltaCompression(NSDictionary* originalInfo, NSDictionary
|
||||
return NO;
|
||||
}
|
||||
|
||||
static BOOL shouldDeleteThenExtract(NSDictionary* originalInfo, NSDictionary *newInfo)
|
||||
static BOOL shouldDeleteThenExtract(NSDictionary *originalInfo, NSDictionary *newInfo)
|
||||
{
|
||||
if (!originalInfo) {
|
||||
return NO;
|
||||
@@ -192,15 +195,15 @@ static BOOL shouldSkipExtracting(NSDictionary *originalInfo, NSDictionary *newIn
|
||||
if (!originalInfo) {
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
if ([originalInfo[INFO_TYPE_KEY] unsignedShortValue] != [newInfo[INFO_TYPE_KEY] unsignedShortValue]) {
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
if (![originalInfo[INFO_HASH_KEY] isEqual:newInfo[INFO_HASH_KEY]]) {
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
@@ -209,30 +212,30 @@ static BOOL shouldChangePermissions(NSDictionary *originalInfo, NSDictionary *ne
|
||||
if (!originalInfo) {
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
if ([originalInfo[INFO_TYPE_KEY] unsignedShortValue] != [newInfo[INFO_TYPE_KEY] unsignedShortValue]) {
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
if ([originalInfo[INFO_PERMISSIONS_KEY] unsignedShortValue] == [newInfo[INFO_PERMISSIONS_KEY] unsignedShortValue]) {
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchFile, SUBinaryDeltaMajorVersion majorVersion, BOOL verbose, NSError * __autoreleasing *error)
|
||||
BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchFile, SUBinaryDeltaMajorVersion majorVersion, BOOL verbose, NSError *__autoreleasing *error)
|
||||
{
|
||||
assert(source);
|
||||
assert(destination);
|
||||
assert(patchFile);
|
||||
assert(majorVersion >= FIRST_DELTA_DIFF_MAJOR_VERSION && majorVersion <= LATEST_DELTA_DIFF_MAJOR_VERSION);
|
||||
|
||||
SUBinaryDeltaMinorVersion minorVersion = latestMinorVersionForMajorVersion(majorVersion);
|
||||
|
||||
|
||||
int minorVersion = latestMinorVersionForMajorVersion(majorVersion);
|
||||
|
||||
NSMutableDictionary *originalTreeState = [NSMutableDictionary dictionary];
|
||||
|
||||
char pathBuffer[PATH_MAX] = {0};
|
||||
char pathBuffer[PATH_MAX] = { 0 };
|
||||
if (![source getFileSystemRepresentation:pathBuffer maxLength:sizeof(pathBuffer)]) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to retrieve file system path representation from source %@", source] }];
|
||||
@@ -240,7 +243,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
|
||||
return NO;
|
||||
}
|
||||
|
||||
char *sourcePaths[] = {pathBuffer, 0};
|
||||
char *sourcePaths[] = { pathBuffer, 0 };
|
||||
FTS *fts = fts_open(sourcePaths, FTS_PHYSICAL | FTS_NOCHDIR, compareFiles);
|
||||
if (!fts) {
|
||||
if (error != NULL) {
|
||||
@@ -253,7 +256,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
|
||||
fprintf(stderr, "Creating version %u.%u patch...\n", majorVersion, minorVersion);
|
||||
fprintf(stderr, "Processing %s...", [source fileSystemRepresentation]);
|
||||
}
|
||||
|
||||
|
||||
FTSENT *ent = 0;
|
||||
while ((ent = fts_read(fts))) {
|
||||
if (ent->fts_info != FTS_F && ent->fts_info != FTS_SL && ent->fts_info != FTS_D) {
|
||||
@@ -276,7 +279,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
|
||||
return NO;
|
||||
}
|
||||
originalTreeState[key] = info;
|
||||
|
||||
|
||||
if (aclExists(ent)) {
|
||||
if (verbose) {
|
||||
fprintf(stderr, "\n");
|
||||
@@ -286,7 +289,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
if (codeSignatureExtendedAttributeExists(ent)) {
|
||||
if (verbose) {
|
||||
fprintf(stderr, "\n");
|
||||
@@ -298,7 +301,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
|
||||
}
|
||||
}
|
||||
fts_close(fts);
|
||||
|
||||
|
||||
NSString *beforeHash = hashOfTreeWithVersion(source, majorVersion);
|
||||
|
||||
if (!beforeHash) {
|
||||
@@ -312,8 +315,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
|
||||
}
|
||||
|
||||
NSMutableDictionary *newTreeState = [NSMutableDictionary dictionary];
|
||||
for (NSString *key in originalTreeState)
|
||||
{
|
||||
for (NSString *key in originalTreeState) {
|
||||
newTreeState[key] = [NSNull null];
|
||||
}
|
||||
|
||||
@@ -331,7 +333,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
sourcePaths[0] = pathBuffer;
|
||||
fts = fts_open(sourcePaths, FTS_PHYSICAL | FTS_NOCHDIR, compareFiles);
|
||||
if (!fts) {
|
||||
@@ -341,7 +343,6 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
while ((ent = fts_read(fts))) {
|
||||
if (ent->fts_info != FTS_F && ent->fts_info != FTS_SL && ent->fts_info != FTS_D) {
|
||||
continue;
|
||||
@@ -362,13 +363,13 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
// We should validate permissions and ACLs even if we don't store the info in the diff in the case of ACLs,
|
||||
// or in the case of permissions if the patch version is 1
|
||||
|
||||
|
||||
// We should also not allow files with code signed extended attributes since Apple doesn't recommend inserting these
|
||||
// inside an application, and since we don't preserve extended attribitutes anyway
|
||||
|
||||
|
||||
mode_t permissions = [info[INFO_PERMISSIONS_KEY] unsignedShortValue];
|
||||
if (!IS_VALID_PERMISSIONS(permissions)) {
|
||||
if (verbose) {
|
||||
@@ -379,7 +380,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
if (aclExists(ent)) {
|
||||
if (verbose) {
|
||||
fprintf(stderr, "\n");
|
||||
@@ -389,7 +390,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
if (codeSignatureExtendedAttributeExists(ent)) {
|
||||
if (verbose) {
|
||||
fprintf(stderr, "\n");
|
||||
@@ -399,14 +400,14 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
NSDictionary *oldInfo = originalTreeState[key];
|
||||
|
||||
if ([info isEqual:oldInfo]) {
|
||||
[newTreeState removeObjectForKey:key];
|
||||
} else {
|
||||
newTreeState[key] = info;
|
||||
|
||||
|
||||
if (oldInfo && [oldInfo[INFO_TYPE_KEY] unsignedShortValue] == FTS_D && [info[INFO_TYPE_KEY] unsignedShortValue] != FTS_D) {
|
||||
NSArray *parentPathComponents = key.pathComponents;
|
||||
|
||||
@@ -432,7 +433,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
if (verbose) {
|
||||
fprintf(stderr, "\nGenerating delta...");
|
||||
}
|
||||
@@ -448,20 +449,18 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
xar_opt_set(x, XAR_OPT_COMPRESSION, "bzip2");
|
||||
|
||||
|
||||
xar_subdoc_t attributes = xar_subdoc_new(x, BINARY_DELTA_ATTRIBUTES_KEY);
|
||||
|
||||
|
||||
xar_subdoc_prop_set(attributes, MAJOR_DIFF_VERSION_KEY, [[NSString stringWithFormat:@"%u", majorVersion] UTF8String]);
|
||||
xar_subdoc_prop_set(attributes, MINOR_DIFF_VERSION_KEY, [[NSString stringWithFormat:@"%u", minorVersion] UTF8String]);
|
||||
|
||||
|
||||
// Version 1 patches don't have a major or minor version field, so we need to differentiate between the hash keys
|
||||
const char *beforeHashKey =
|
||||
MAJOR_VERSION_IS_AT_LEAST(majorVersion, SUBeigeMajorVersion) ? BEFORE_TREE_SHA1_KEY : BEFORE_TREE_SHA1_OLD_KEY;
|
||||
const char *afterHashKey =
|
||||
MAJOR_VERSION_IS_AT_LEAST(majorVersion, SUBeigeMajorVersion) ? AFTER_TREE_SHA1_KEY : AFTER_TREE_SHA1_OLD_KEY;
|
||||
|
||||
const char *beforeHashKey = MAJOR_VERSION_IS_AT_LEAST(majorVersion, SUBeigeMajorVersion) ? BEFORE_TREE_SHA1_KEY : BEFORE_TREE_SHA1_OLD_KEY;
|
||||
const char *afterHashKey = MAJOR_VERSION_IS_AT_LEAST(majorVersion, SUBeigeMajorVersion) ? AFTER_TREE_SHA1_KEY : AFTER_TREE_SHA1_OLD_KEY;
|
||||
|
||||
xar_subdoc_prop_set(attributes, beforeHashKey, [beforeHash UTF8String]);
|
||||
xar_subdoc_prop_set(attributes, afterHashKey, [afterHash UTF8String]);
|
||||
|
||||
@@ -471,21 +470,21 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
|
||||
// Sort the keys by preferring the ones from the original tree to appear first
|
||||
// We want to enforce deleting before extracting in the case paths differ only by case
|
||||
NSArray *keys = [[newTreeState allKeys] sortedArrayUsingComparator:^NSComparisonResult(NSString *key1, NSString *key2) {
|
||||
NSComparisonResult insensitiveCompareResult = [key1 caseInsensitiveCompare:key2];
|
||||
if (insensitiveCompareResult != NSOrderedSame) {
|
||||
return insensitiveCompareResult;
|
||||
}
|
||||
NSComparisonResult insensitiveCompareResult = [key1 caseInsensitiveCompare:key2];
|
||||
if (insensitiveCompareResult != NSOrderedSame) {
|
||||
return insensitiveCompareResult;
|
||||
}
|
||||
|
||||
return originalTreeState[key1] ? NSOrderedAscending : NSOrderedDescending;
|
||||
return originalTreeState[key1] ? NSOrderedAscending : NSOrderedDescending;
|
||||
}];
|
||||
for (NSString* key in keys) {
|
||||
for (NSString *key in keys) {
|
||||
id value = [newTreeState valueForKey:key];
|
||||
|
||||
if ([value isEqual:[NSNull null]]) {
|
||||
xar_file_t newFile = xar_add_frombuffer(x, 0, [key fileSystemRepresentation], (char *)"", 1);
|
||||
assert(newFile);
|
||||
xar_prop_set(newFile, DELETE_KEY, "true");
|
||||
|
||||
|
||||
if (verbose) {
|
||||
fprintf(stderr, "\n❌ %s %s", VERBOSE_REMOVED, [key fileSystemRepresentation]);
|
||||
}
|
||||
@@ -500,7 +499,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
|
||||
xar_file_t newFile = xar_add_frombuffer(x, 0, [key fileSystemRepresentation], (char *)"", 1);
|
||||
assert(newFile);
|
||||
xar_prop_set(newFile, MODIFY_PERMISSIONS_KEY, [[NSString stringWithFormat:@"%u", [newInfo[INFO_PERMISSIONS_KEY] unsignedShortValue]] UTF8String]);
|
||||
|
||||
|
||||
if (verbose) {
|
||||
fprintf(stderr, "\n👮 %s %s (0%o -> 0%o)", VERBOSE_MODIFIED, [key fileSystemRepresentation], [originalInfo[INFO_PERMISSIONS_KEY] unsignedShortValue], [newInfo[INFO_PERMISSIONS_KEY] unsignedShortValue]);
|
||||
}
|
||||
@@ -509,7 +508,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
|
||||
NSString *path = [destination stringByAppendingPathComponent:key];
|
||||
xar_file_t newFile = xar_add_frompath(x, 0, [key fileSystemRepresentation], [path fileSystemRepresentation]);
|
||||
assert(newFile);
|
||||
|
||||
|
||||
if (shouldDeleteThenExtract(originalInfo, newInfo)) {
|
||||
if (MAJOR_VERSION_IS_AT_LEAST(majorVersion, SUBeigeMajorVersion)) {
|
||||
xar_prop_set(newFile, DELETE_KEY, "true");
|
||||
@@ -517,11 +516,11 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
|
||||
xar_prop_set(newFile, DELETE_THEN_EXTRACT_OLD_KEY, "true");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (MAJOR_VERSION_IS_AT_LEAST(majorVersion, SUBeigeMajorVersion)) {
|
||||
xar_prop_set(newFile, EXTRACT_KEY, "true");
|
||||
}
|
||||
|
||||
|
||||
if (verbose) {
|
||||
if (originalInfo) {
|
||||
fprintf(stderr, "\n✏️ %s %s", VERBOSE_UPDATED, [key fileSystemRepresentation]);
|
||||
@@ -554,19 +553,19 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
if (verbose) {
|
||||
fprintf(stderr, "\n🔨 %s %s", VERBOSE_DIFFED, [[operation relativePath] fileSystemRepresentation]);
|
||||
}
|
||||
|
||||
|
||||
xar_file_t newFile = xar_add_frompath(x, 0, [[operation relativePath] fileSystemRepresentation], [resultPath fileSystemRepresentation]);
|
||||
assert(newFile);
|
||||
xar_prop_set(newFile, BINARY_DELTA_KEY, "true");
|
||||
unlink([resultPath fileSystemRepresentation]);
|
||||
|
||||
|
||||
if (operation.permissions) {
|
||||
xar_prop_set(newFile, MODIFY_PERMISSIONS_KEY, [[NSString stringWithFormat:@"%u", [operation.permissions unsignedShortValue]] UTF8String]);
|
||||
|
||||
|
||||
if (verbose) {
|
||||
fprintf(stderr, "\n👮 %s %s (0%o -> 0%o)", VERBOSE_MODIFIED, [[operation relativePath] fileSystemRepresentation], operation.oldPermissions.unsignedShortValue, operation.permissions.unsignedShortValue);
|
||||
}
|
||||
@@ -578,7 +577,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
|
||||
unlink([patchFile fileSystemRepresentation]);
|
||||
link([temporaryFile fileSystemRepresentation], [patchFile fileSystemRepresentation]);
|
||||
unlink([temporaryFile fileSystemRepresentation]);
|
||||
|
||||
|
||||
if (verbose) {
|
||||
fprintf(stderr, "\nDone!\n");
|
||||
}
|
||||
|
||||
Vendored
+43
-37
@@ -20,6 +20,8 @@
|
||||
#define VERSION_COMMAND @"version"
|
||||
#define VERSION_ALTERNATE_COMMAND @"--version"
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
|
||||
static void printUsage(NSString *programName)
|
||||
{
|
||||
fprintf(stderr, "Usage:\n");
|
||||
@@ -34,7 +36,7 @@ static BOOL runCreateCommand(NSString *programName, NSArray *args)
|
||||
printUsage(programName);
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
NSUInteger numberOflagsFound = 0;
|
||||
NSUInteger verboseIndex = [args indexOfObject:VERBOSE_FLAG];
|
||||
NSUInteger versionIndex = NSNotFound;
|
||||
@@ -44,22 +46,22 @@ static BOOL runCreateCommand(NSString *programName, NSArray *args)
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (verboseIndex != NSNotFound) {
|
||||
++numberOflagsFound;
|
||||
}
|
||||
if (versionIndex != NSNotFound) {
|
||||
++numberOflagsFound;
|
||||
}
|
||||
|
||||
|
||||
if (args.count - numberOflagsFound < 3) {
|
||||
printUsage(programName);
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
BOOL verbose = (verboseIndex != NSNotFound);
|
||||
NSString *versionField = (versionIndex != NSNotFound) ? args[versionIndex] : nil;
|
||||
|
||||
|
||||
NSArray *versionComponents = nil;
|
||||
if (versionField) {
|
||||
versionComponents = [versionField componentsSeparatedByString:@"="];
|
||||
@@ -68,17 +70,17 @@ static BOOL runCreateCommand(NSString *programName, NSArray *args)
|
||||
return NO;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
SUBinaryDeltaMajorVersion patchVersion =
|
||||
!versionComponents ?
|
||||
LATEST_DELTA_DIFF_MAJOR_VERSION :
|
||||
(SUBinaryDeltaMajorVersion)[[versionComponents[1] componentsSeparatedByString:@"."][0] intValue]; // ignore minor version if provided
|
||||
|
||||
|
||||
if (patchVersion < FIRST_DELTA_DIFF_MAJOR_VERSION) {
|
||||
fprintf(stderr, "Version provided (%u) is not valid\n", patchVersion);
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
if (patchVersion > LATEST_DELTA_DIFF_MAJOR_VERSION) {
|
||||
fprintf(stderr, "This program is too old to create a version %u patch, or the version number provided is invalid\n", patchVersion);
|
||||
return NO;
|
||||
@@ -90,31 +92,35 @@ static BOOL runCreateCommand(NSString *programName, NSArray *args)
|
||||
[fileArgs addObject:argument];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (fileArgs.count != 3) {
|
||||
printUsage(programName);
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
NSString *sourcePath = fileArgs[0];
|
||||
NSString *destPath = fileArgs[1];
|
||||
NSString *patchPath = fileArgs[2];
|
||||
|
||||
BOOL isDirectory;
|
||||
if (![[NSFileManager defaultManager] fileExistsAtPath:fileArgs[0] isDirectory:&isDirectory] || !isDirectory) {
|
||||
if (![[NSFileManager defaultManager] fileExistsAtPath:sourcePath isDirectory:&isDirectory] || !isDirectory) {
|
||||
printUsage(programName);
|
||||
fprintf(stderr, "Error: before-tree must be a directory\n");
|
||||
return NO;
|
||||
}
|
||||
|
||||
if (![[NSFileManager defaultManager] fileExistsAtPath:fileArgs[1] isDirectory:&isDirectory] || !isDirectory) {
|
||||
|
||||
if (![[NSFileManager defaultManager] fileExistsAtPath:destPath isDirectory:&isDirectory] || !isDirectory) {
|
||||
printUsage(programName);
|
||||
fprintf(stderr, "Error: after-tree must be a directory\n");
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
NSError *createDiffError = nil;
|
||||
if (!createBinaryDelta(fileArgs[0], fileArgs[1], fileArgs[2], patchVersion, verbose, &createDiffError)) {
|
||||
if (!createBinaryDelta(sourcePath, destPath, patchPath, patchVersion, verbose, &createDiffError)) {
|
||||
fprintf(stderr, "%s\n", [createDiffError.localizedDescription UTF8String]);
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
@@ -124,45 +130,45 @@ static BOOL runApplyCommand(NSString *programName, NSArray *args)
|
||||
printUsage(programName);
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
BOOL verbose = [args containsObject:VERBOSE_FLAG];
|
||||
|
||||
|
||||
if (args.count == 4 && !verbose) {
|
||||
printUsage(programName);
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
NSMutableArray *fileArgs = [NSMutableArray array];
|
||||
for (NSString *argument in args) {
|
||||
if (![argument isEqualToString:VERBOSE_FLAG]) {
|
||||
[fileArgs addObject:argument];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (fileArgs.count != 3) {
|
||||
printUsage(programName);
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
BOOL isDirectory;
|
||||
if (![[NSFileManager defaultManager] fileExistsAtPath:fileArgs[0] isDirectory:&isDirectory] || !isDirectory) {
|
||||
printUsage(programName);
|
||||
fprintf(stderr, "Error: before-tree must be a directory\n");
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
if (![[NSFileManager defaultManager] fileExistsAtPath:fileArgs[2] isDirectory:&isDirectory] || isDirectory) {
|
||||
printUsage(programName);
|
||||
fprintf(stderr, "Error: patch-file must be a file %d\n", isDirectory);
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
NSError *applyDiffError = nil;
|
||||
if (!applyBinaryDelta(fileArgs[0], fileArgs[1], fileArgs[2], verbose, &applyDiffError)) {
|
||||
if (!applyBinaryDelta(fileArgs[0], fileArgs[1], fileArgs[2], verbose, ^(__unused double x){}, &applyDiffError)) {
|
||||
fprintf(stderr, "%s\n", [applyDiffError.localizedDescription UTF8String]);
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
@@ -172,7 +178,7 @@ static BOOL runVersionCommand(NSString *programName, NSArray *args)
|
||||
printUsage(programName);
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
if (args.count == 0) {
|
||||
fprintf(stdout, "%u.%u\n", LATEST_DELTA_DIFF_MAJOR_VERSION, latestMinorVersionForMajorVersion(LATEST_DELTA_DIFF_MAJOR_VERSION));
|
||||
} else {
|
||||
@@ -182,30 +188,30 @@ static BOOL runVersionCommand(NSString *programName, NSArray *args)
|
||||
fprintf(stderr, "Unable to open patch %s\n", [patchFile fileSystemRepresentation]);
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
SUBinaryDeltaMajorVersion majorDiffVersion = FIRST_DELTA_DIFF_MAJOR_VERSION;
|
||||
SUBinaryDeltaMinorVersion minorDiffVersion = FIRST_DELTA_DIFF_MINOR_VERSION;
|
||||
|
||||
int minorDiffVersion = 0;
|
||||
|
||||
xar_subdoc_t subdoc;
|
||||
for (subdoc = xar_subdoc_first(x); subdoc; subdoc = xar_subdoc_next(subdoc)) {
|
||||
if (!strcmp(xar_subdoc_name(subdoc), BINARY_DELTA_ATTRIBUTES_KEY)) {
|
||||
const char *value = 0;
|
||||
|
||||
|
||||
// available in version 2.0 or later
|
||||
xar_subdoc_prop_get(subdoc, MAJOR_DIFF_VERSION_KEY, &value);
|
||||
if (value)
|
||||
majorDiffVersion = (SUBinaryDeltaMajorVersion)[@(value) intValue];
|
||||
|
||||
|
||||
// available in version 2.0 or later
|
||||
xar_subdoc_prop_get(subdoc, MINOR_DIFF_VERSION_KEY, &value);
|
||||
if (value)
|
||||
minorDiffVersion = (SUBinaryDeltaMinorVersion)[@(value) intValue];
|
||||
minorDiffVersion = [@(value) intValue];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
fprintf(stdout, "%u.%u\n", majorDiffVersion, minorDiffVersion);
|
||||
}
|
||||
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
@@ -214,7 +220,7 @@ int main(int __unused argc, char __unused *argv[])
|
||||
@autoreleasepool {
|
||||
NSArray *args = [[NSProcessInfo processInfo] arguments];
|
||||
NSString *programName = [args[0] lastPathComponent];
|
||||
|
||||
|
||||
if (args.count < 2) {
|
||||
printUsage(programName);
|
||||
return 1;
|
||||
@@ -222,7 +228,7 @@ int main(int __unused argc, char __unused *argv[])
|
||||
|
||||
NSString *command = args[1];
|
||||
NSArray *commandArguments = [args subarrayWithRange:NSMakeRange(2, args.count - 2)];
|
||||
|
||||
|
||||
BOOL result;
|
||||
if ([command isEqualToString:CREATE_COMMAND]) {
|
||||
result = runCreateCommand(programName, commandArguments);
|
||||
@@ -234,7 +240,7 @@ int main(int __unused argc, char __unused *argv[])
|
||||
result = NO;
|
||||
printUsage(programName);
|
||||
}
|
||||
|
||||
|
||||
return result ? 0 : 1;
|
||||
}
|
||||
}
|
||||
Vendored
+9
-3
@@ -9,11 +9,17 @@
|
||||
#ifndef SUBINARYDELTAUNARCHIVER_H
|
||||
#define SUBINARYDELTAUNARCHIVER_H
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
#import "SUUnarchiver.h"
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "SUUnarchiverProtocol.h"
|
||||
|
||||
@interface SUBinaryDeltaUnarchiver : SUUnarchiver
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface SUBinaryDeltaUnarchiver : NSObject <SUUnarchiverProtocol>
|
||||
|
||||
- (instancetype)initWithArchivePath:(NSString *)archivePath updateHostBundlePath:(NSString *)updateHostBundlePath;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
#endif
|
||||
Vendored
+47
-29
@@ -6,16 +6,28 @@
|
||||
// Copyright 2009 Mark Rowe. All rights reserved.
|
||||
//
|
||||
|
||||
#import "SUBinaryDeltaCommon.h"
|
||||
#import "SUBinaryDeltaUnarchiver.h"
|
||||
#import "SUUnarchiverNotifier.h"
|
||||
#import "SUBinaryDeltaCommon.h"
|
||||
#import "SUBinaryDeltaApply.h"
|
||||
#import "SUUnarchiver_Private.h"
|
||||
#import "SUFileManager.h"
|
||||
#import "SUHost.h"
|
||||
#import "SULog.h"
|
||||
#import "SUFileManager.h"
|
||||
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
|
||||
@interface SUBinaryDeltaUnarchiver ()
|
||||
|
||||
@property (nonatomic, copy, readonly) NSString *archivePath;
|
||||
@property (nonatomic, copy, readonly) NSString *updateHostBundlePath;
|
||||
|
||||
@end
|
||||
|
||||
@implementation SUBinaryDeltaUnarchiver
|
||||
|
||||
@synthesize archivePath = _archivePath;
|
||||
@synthesize updateHostBundlePath = _updateHostBundlePath;
|
||||
|
||||
+ (BOOL)canUnarchivePath:(NSString *)path
|
||||
{
|
||||
return [[path pathExtension] isEqualToString:@"delta"];
|
||||
@@ -55,46 +67,52 @@
|
||||
for (NSURL *file in filesToUpdate) {
|
||||
NSError *error = nil;
|
||||
if (![fileManager updateModificationAndAccessTimeOfItemAtURL:file error:&error]) {
|
||||
SULog(@"Error: During delta unarchiving, failed to touch %@", error);
|
||||
SULog(SULogLevelError, @"Error: During delta unarchiving, failed to touch %@", error);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
- (void)applyBinaryDelta
|
||||
- (instancetype)initWithArchivePath:(NSString *)archivePath updateHostBundlePath:(NSString *)updateHostBundlePath
|
||||
{
|
||||
@autoreleasepool {
|
||||
NSString *sourcePath = self.updateHostBundlePath;
|
||||
NSString *targetPath = [[self.archivePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:[sourcePath lastPathComponent]];
|
||||
|
||||
NSError *applyDiffError = nil;
|
||||
BOOL success = applyBinaryDelta(sourcePath, targetPath, self.archivePath, NO, &applyDiffError);
|
||||
if (success) {
|
||||
[[self class] updateSpotlightImportersAtBundlePath:targetPath];
|
||||
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[self notifyDelegateOfSuccess];
|
||||
});
|
||||
}
|
||||
else {
|
||||
SULog(@"Applying delta patch failed with error: %@", applyDiffError);
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[self notifyDelegateOfFailure];
|
||||
});
|
||||
}
|
||||
self = [super init];
|
||||
if (self != nil) {
|
||||
_archivePath = [archivePath copy];
|
||||
_updateHostBundlePath = [updateHostBundlePath copy];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)start
|
||||
- (void)unarchiveWithCompletionBlock:(void (^)(NSError * _Nullable))completionBlock progressBlock:(void (^ _Nullable)(double))progressBlock
|
||||
{
|
||||
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
|
||||
[self applyBinaryDelta];
|
||||
@autoreleasepool {
|
||||
SUUnarchiverNotifier *notifier = [[SUUnarchiverNotifier alloc] initWithCompletionBlock:completionBlock progressBlock:progressBlock];
|
||||
[self extractDeltaWithNotifier:notifier];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
+ (void)load
|
||||
- (void)extractDeltaWithNotifier:(SUUnarchiverNotifier *)notifier
|
||||
{
|
||||
[self registerImplementation:self];
|
||||
NSString *sourcePath = self.updateHostBundlePath;
|
||||
NSString *targetPath = [[self.archivePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:[sourcePath lastPathComponent]];
|
||||
|
||||
NSError *applyDiffError = nil;
|
||||
BOOL success = applyBinaryDelta(sourcePath, targetPath, self.archivePath, NO, ^(double progress){
|
||||
[notifier notifyProgress:progress];
|
||||
|
||||
}, &applyDiffError);
|
||||
|
||||
if (success) {
|
||||
[[self class] updateSpotlightImportersAtBundlePath:targetPath];
|
||||
[notifier notifySuccess];
|
||||
}
|
||||
else {
|
||||
[notifier notifyFailureWithError:applyDiffError];
|
||||
}
|
||||
}
|
||||
|
||||
- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], self.archivePath]; }
|
||||
|
||||
@end
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
//
|
||||
// SUBundleIcon.h
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Mayur Pawashe on 7/24/16.
|
||||
// Copyright © 2016 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@class SUHost;
|
||||
|
||||
@interface SUBundleIcon : NSObject
|
||||
|
||||
+ (NSURL * _Nullable)iconURLForHost:(SUHost *)host;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
Vendored
+34
@@ -0,0 +1,34 @@
|
||||
//
|
||||
// SUBundleIcon.m
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Mayur Pawashe on 7/24/16.
|
||||
// Copyright © 2016 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#import "SUBundleIcon.h"
|
||||
#import "SUHost.h"
|
||||
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
|
||||
@implementation SUBundleIcon
|
||||
|
||||
// Note: To obtain the most current bundle icon file from the Info dictionary, this should take a SUHost, not a NSBundle
|
||||
+ (NSURL *)iconURLForHost:(SUHost *)host
|
||||
{
|
||||
NSString *resource = [host objectForInfoDictionaryKey:@"CFBundleIconFile"];
|
||||
if (resource == nil || ![resource isKindOfClass:[NSString class]]) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
NSURL *iconURL = [host.bundle URLForResource:resource withExtension:@"icns"];
|
||||
|
||||
// The resource could already be containing the path extension, so try again without the extra extension
|
||||
if (iconURL == nil) {
|
||||
iconURL = [host.bundle URLForResource:resource withExtension:nil];
|
||||
}
|
||||
return iconURL;
|
||||
}
|
||||
|
||||
@end
|
||||
Vendored
+3
-1
@@ -10,11 +10,13 @@
|
||||
#define SUCODESIGNINGVERIFIER_H
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "SUExport.h"
|
||||
|
||||
@interface SUCodeSigningVerifier : NSObject
|
||||
SU_EXPORT @interface SUCodeSigningVerifier : NSObject
|
||||
+ (BOOL)codeSignatureAtBundleURL:(NSURL *)oldBundlePath matchesSignatureAtBundleURL:(NSURL *)newBundlePath error:(NSError **)error;
|
||||
+ (BOOL)codeSignatureIsValidAtBundleURL:(NSURL *)bundlePath error:(NSError **)error;
|
||||
+ (BOOL)bundleAtURLIsCodeSigned:(NSURL *)bundlePath;
|
||||
+ (NSDictionary *)codeSignatureInfoAtBundleURL:(NSURL *)bundlePath;
|
||||
@end
|
||||
|
||||
#endif
|
||||
Vendored
+32
-8
@@ -11,6 +11,9 @@
|
||||
#import "SUCodeSigningVerifier.h"
|
||||
#import "SULog.h"
|
||||
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
|
||||
@implementation SUCodeSigningVerifier
|
||||
|
||||
+ (BOOL)codeSignatureAtBundleURL:(NSURL *)oldBundleURL matchesSignatureAtBundleURL:(NSURL *)newBundleURL error:(NSError *__autoreleasing *)error
|
||||
@@ -31,13 +34,13 @@
|
||||
|
||||
result = SecCodeCopyDesignatedRequirement(oldCode, kSecCSDefaultFlags, &requirement);
|
||||
if (result != noErr) {
|
||||
SULog(@"Failed to copy designated requirement. Code Signing OSStatus code: %d", result);
|
||||
SULog(SULogLevelError, @"Failed to copy designated requirement. Code Signing OSStatus code: %d", result);
|
||||
goto finally;
|
||||
}
|
||||
|
||||
result = SecStaticCodeCreateWithPath((__bridge CFURLRef)newBundleURL, kSecCSDefaultFlags, &staticCode);
|
||||
if (result != noErr) {
|
||||
SULog(@"Failed to get static code %d", result);
|
||||
SULog(SULogLevelError, @"Failed to get static code %d", result);
|
||||
goto finally;
|
||||
}
|
||||
|
||||
@@ -55,12 +58,12 @@
|
||||
|
||||
if (result != noErr) {
|
||||
if (result == errSecCSUnsigned) {
|
||||
SULog(@"The host app is signed, but the new version of the app is not signed using Apple Code Signing. Please ensure that the new app is signed and that archiving did not corrupt the signature.");
|
||||
SULog(SULogLevelError, @"The host app is signed, but the new version of the app is not signed using Apple Code Signing. Please ensure that the new app is signed and that archiving did not corrupt the signature.");
|
||||
}
|
||||
if (result == errSecCSReqFailed) {
|
||||
CFStringRef requirementString = nil;
|
||||
if (SecRequirementCopyString(requirement, kSecCSDefaultFlags, &requirementString) == noErr) {
|
||||
SULog(@"Code signature of the new version doesn't match the old version: %@. Please ensure that old and new app is signed using exactly the same certificate.", requirementString);
|
||||
SULog(SULogLevelError, @"Code signature of the new version doesn't match the old version: %@. Please ensure that old and new app is signed using exactly the same certificate.", requirementString);
|
||||
CFRelease(requirementString);
|
||||
}
|
||||
|
||||
@@ -87,7 +90,7 @@ finally:
|
||||
|
||||
result = SecStaticCodeCreateWithPath((__bridge CFURLRef)bundleURL, kSecCSDefaultFlags, &staticCode);
|
||||
if (result != noErr) {
|
||||
SULog(@"Failed to get static code %d", result);
|
||||
SULog(SULogLevelError, @"Failed to get static code %d", result);
|
||||
goto finally;
|
||||
}
|
||||
|
||||
@@ -102,7 +105,7 @@ finally:
|
||||
|
||||
if (result != noErr) {
|
||||
if (result == errSecCSUnsigned) {
|
||||
SULog(@"Error: The app is not signed using Apple Code Signing. %@", bundleURL);
|
||||
SULog(SULogLevelError, @"Error: The app is not signed using Apple Code Signing. %@", bundleURL);
|
||||
}
|
||||
if (result == errSecCSReqFailed) {
|
||||
[self logSigningInfoForCode:staticCode label:@"new info"];
|
||||
@@ -118,7 +121,22 @@ static id valueOrNSNull(id value) {
|
||||
return value ? value : [NSNull null];
|
||||
}
|
||||
|
||||
+ (void)logSigningInfoForCode:(SecStaticCodeRef)code label:(NSString*)label {
|
||||
+ (NSDictionary *)codeSignatureInfoAtBundleURL:(NSURL *)bundlePath {
|
||||
NSDictionary *info = nil;
|
||||
SecStaticCodeRef code = NULL;
|
||||
OSStatus result = SecStaticCodeCreateWithPath((__bridge CFURLRef)bundlePath, kSecCSDefaultFlags, &code);
|
||||
if (result != noErr) {
|
||||
SULog(SULogLevelError, @"Failed to get static code %d", result);
|
||||
goto finally;
|
||||
}
|
||||
info = [self codeSignatureInfoForCode:code];
|
||||
|
||||
finally:
|
||||
if (code) CFRelease(code);
|
||||
return info;
|
||||
}
|
||||
|
||||
+ (NSDictionary *)codeSignatureInfoForCode:(SecStaticCodeRef)code {
|
||||
CFDictionaryRef signingInfo = nil;
|
||||
const SecCSFlags flags = (SecCSFlags) (kSecCSSigningInformation | kSecCSRequirementInformation | kSecCSDynamicInformation | kSecCSContentInformation);
|
||||
if (SecCodeCopySigningInformation(code, flags, &signingInfo) == noErr) {
|
||||
@@ -130,8 +148,14 @@ static id valueOrNSNull(id value) {
|
||||
NSDictionary *infoPlist = [signingDict objectForKey:@"info-plist"];
|
||||
[relevantInfo setObject:valueOrNSNull([infoPlist objectForKey:@"CFBundleShortVersionString"]) forKey:@"version"];
|
||||
[relevantInfo setObject:valueOrNSNull([infoPlist objectForKey:(__bridge NSString *)kCFBundleVersionKey]) forKey:@"build"];
|
||||
SULog(@"%@: %@", label, relevantInfo);
|
||||
return [relevantInfo copy];
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
+ (void)logSigningInfoForCode:(SecStaticCodeRef)code label:(NSString*)label {
|
||||
NSDictionary *relevantInfo = [self codeSignatureInfoForCode:code];
|
||||
SULog(SULogLevelDefault, @"%@: %@", label, relevantInfo);
|
||||
}
|
||||
|
||||
+ (BOOL)bundleAtURLIsCodeSigned:(NSURL *)bundleURL
|
||||
|
||||
Vendored
+7
-1
@@ -21,6 +21,8 @@ extern const NSTimeInterval SUDefaultUpdateCheckInterval;
|
||||
|
||||
extern NSString *const SUBundleIdentifier;
|
||||
|
||||
extern NSString *const SUAppcastAttributeValueMacOS;
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// Notifications:
|
||||
// -----------------------------------------------------------------------------
|
||||
@@ -33,6 +35,7 @@ extern NSString *const SUTechnicalErrorInformationKey;
|
||||
|
||||
extern NSString *const SUFeedURLKey;
|
||||
extern NSString *const SUHasLaunchedBeforeKey;
|
||||
extern NSString *const SUUpdateRelaunchingMarkerKey;
|
||||
extern NSString *const SUShowReleaseNotesKey;
|
||||
extern NSString *const SUSkippedVersionKey;
|
||||
extern NSString *const SUScheduledCheckIntervalKey;
|
||||
@@ -47,7 +50,6 @@ extern NSString *const SUEnableSystemProfilingKey;
|
||||
extern NSString *const SUSendProfileInfoKey;
|
||||
extern NSString *const SULastProfileSubmitDateKey;
|
||||
extern NSString *const SUPromptUserOnFirstLaunchKey;
|
||||
extern NSString *const SUKeepDownloadOnFailedInstallKey;
|
||||
extern NSString *const SUDefaultsDomainKey;
|
||||
extern NSString *const SUEnableJavaScriptKey;
|
||||
extern NSString *const SUFixedHTMLDisplaySizeKey __attribute__((deprecated("This key is obsolete and has no effect.")));
|
||||
@@ -64,6 +66,9 @@ extern NSString *const SUAppcastAttributeDeltaFrom;
|
||||
extern NSString *const SUAppcastAttributeDSASignature;
|
||||
extern NSString *const SUAppcastAttributeShortVersionString;
|
||||
extern NSString *const SUAppcastAttributeVersion;
|
||||
extern NSString *const SUAppcastAttributeOsType;
|
||||
|
||||
|
||||
|
||||
extern NSString *const SUAppcastElementCriticalUpdate;
|
||||
extern NSString *const SUAppcastElementDeltas;
|
||||
@@ -73,6 +78,7 @@ extern NSString *const SUAppcastElementReleaseNotesLink;
|
||||
extern NSString *const SUAppcastElementTags;
|
||||
|
||||
extern NSString *const SURSSAttributeURL;
|
||||
extern NSString *const SURSSAttributeLength;
|
||||
|
||||
extern NSString *const SURSSElementDescription;
|
||||
extern NSString *const SURSSElementEnclosure;
|
||||
|
||||
Vendored
+8
-6
@@ -6,26 +6,27 @@
|
||||
// Copyright 2006 Andy Matuschak. All rights reserved.
|
||||
//
|
||||
|
||||
#import "SUUpdater.h"
|
||||
|
||||
#import "SUAppcast.h"
|
||||
#import "SUAppcastItem.h"
|
||||
#import "SUVersionComparisonProtocol.h"
|
||||
#import "SUConstants.h"
|
||||
#import "SUErrors.h"
|
||||
|
||||
#ifndef DEBUG
|
||||
#define DEBUG 0
|
||||
#endif
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
|
||||
// Define some minimum intervals to avoid DoS-like checking attacks
|
||||
const NSTimeInterval SUMinimumUpdateCheckInterval = DEBUG ? 60 : (60 * 60);
|
||||
const NSTimeInterval SUDefaultUpdateCheckInterval = DEBUG ? 60 : (60 * 60 * 24);
|
||||
|
||||
NSString *const SUBundleIdentifier = @SPARKLE_BUNDLE_IDENTIFIER;
|
||||
|
||||
NSString *const SUAppcastAttributeValueMacOS = @"macos";
|
||||
|
||||
NSString *const SUTechnicalErrorInformationKey = @"SUTechnicalErrorInformation";
|
||||
|
||||
NSString *const SUHasLaunchedBeforeKey = @"SUHasLaunchedBefore";
|
||||
NSString *const SUUpdateRelaunchingMarkerKey = @"SUUpdateRelaunchingMarker";
|
||||
NSString *const SUFeedURLKey = @"SUFeedURL";
|
||||
NSString *const SUShowReleaseNotesKey = @"SUShowReleaseNotes";
|
||||
NSString *const SUSkippedVersionKey = @"SUSkippedVersion";
|
||||
@@ -43,7 +44,6 @@ NSString *const SULastProfileSubmitDateKey = @"SULastProfileSubmissionDate";
|
||||
NSString *const SUPromptUserOnFirstLaunchKey = @"SUPromptUserOnFirstLaunch";
|
||||
NSString *const SUEnableJavaScriptKey = @"SUEnableJavaScript";
|
||||
NSString *const SUFixedHTMLDisplaySizeKey = @"SUFixedHTMLDisplaySize";
|
||||
NSString *const SUKeepDownloadOnFailedInstallKey = @"SUKeepDownloadOnFailedInstall";
|
||||
NSString *const SUDefaultsDomainKey = @"SUDefaultsDomain";
|
||||
NSString *const SUSparkleErrorDomain = @"SUSparkleErrorDomain";
|
||||
|
||||
@@ -56,6 +56,7 @@ NSString *const SUAppcastAttributeDeltaFrom = @"sparkle:deltaFrom";
|
||||
NSString *const SUAppcastAttributeDSASignature = @"sparkle:dsaSignature";
|
||||
NSString *const SUAppcastAttributeShortVersionString = @"sparkle:shortVersionString";
|
||||
NSString *const SUAppcastAttributeVersion = @"sparkle:version";
|
||||
NSString *const SUAppcastAttributeOsType = @"sparkle:os";
|
||||
|
||||
NSString *const SUAppcastElementCriticalUpdate = @"sparkle:criticalUpdate";
|
||||
NSString *const SUAppcastElementDeltas = @"sparkle:deltas";
|
||||
@@ -65,6 +66,7 @@ NSString *const SUAppcastElementReleaseNotesLink = @"sparkle:releaseNotesLink";
|
||||
NSString *const SUAppcastElementTags = @"sparkle:tags";
|
||||
|
||||
NSString *const SURSSAttributeURL = @"url";
|
||||
NSString *const SURSSAttributeLength = @"length";
|
||||
|
||||
NSString *const SURSSElementDescription = @"description";
|
||||
NSString *const SURSSElementEnclosure = @"enclosure";
|
||||
|
||||
Vendored
+12
-9
@@ -16,6 +16,9 @@
|
||||
#import "SULog.h"
|
||||
#include <CommonCrypto/CommonDigest.h>
|
||||
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
|
||||
@implementation SUDSAVerifier {
|
||||
SecKeyRef _secKey;
|
||||
}
|
||||
@@ -23,7 +26,7 @@
|
||||
+ (BOOL)validatePath:(NSString *)path withEncodedDSASignature:(NSString *)encodedSignature withPublicDSAKey:(NSString *)pkeyString
|
||||
{
|
||||
if (!encodedSignature) {
|
||||
SULog(@"There is no DSA signature to check");
|
||||
SULog(SULogLevelError, @"There is no DSA signature to check");
|
||||
return NO;
|
||||
}
|
||||
|
||||
@@ -47,7 +50,7 @@
|
||||
self = [super init];
|
||||
|
||||
if (!self || !data.length) {
|
||||
SULog(@"Could not read public DSA key");
|
||||
SULog(SULogLevelError, @"Could not read public DSA key");
|
||||
return nil;
|
||||
}
|
||||
|
||||
@@ -60,7 +63,7 @@
|
||||
if (items) {
|
||||
CFRelease(items);
|
||||
}
|
||||
SULog(@"Public DSA key could not be imported: %d", status);
|
||||
SULog(SULogLevelError, @"Public DSA key could not be imported: %d", status);
|
||||
return nil;
|
||||
}
|
||||
|
||||
@@ -118,7 +121,7 @@
|
||||
|
||||
dataReadTransform = SecTransformCreateReadTransformWithReadStream((__bridge CFReadStreamRef)stream);
|
||||
if (!dataReadTransform) {
|
||||
SULog(@"File containing update archive could not be read (failed to create SecTransform for input stream)");
|
||||
SULog(SULogLevelError, @"File containing update archive could not be read (failed to create SecTransform for input stream)");
|
||||
return cleanup();
|
||||
}
|
||||
|
||||
@@ -132,30 +135,30 @@
|
||||
dataVerifyTransform = SecVerifyTransformCreate(_secKey, (__bridge CFDataRef)signature, &error);
|
||||
#pragma clang diagnostic pop
|
||||
if (!dataVerifyTransform || error) {
|
||||
SULog(@"Could not understand format of the signature: %@; Signature data: %@", error, signature);
|
||||
SULog(SULogLevelError, @"Could not understand format of the signature: %@; Signature data: %@", error, signature);
|
||||
return cleanup();
|
||||
}
|
||||
|
||||
SecTransformConnectTransforms(dataReadTransform, kSecTransformOutputAttributeName, dataDigestTransform, kSecTransformInputAttributeName, group, &error);
|
||||
if (error) {
|
||||
SULog(@"%@", error);
|
||||
SULog(SULogLevelError, @"%@", error);
|
||||
return cleanup();
|
||||
}
|
||||
|
||||
SecTransformConnectTransforms(dataDigestTransform, kSecTransformOutputAttributeName, dataVerifyTransform, kSecTransformInputAttributeName, group, &error);
|
||||
if (error) {
|
||||
SULog(@"%@", error);
|
||||
SULog(SULogLevelError, @"%@", error);
|
||||
return cleanup();
|
||||
}
|
||||
|
||||
NSNumber *result = CFBridgingRelease(SecTransformExecute(group, &error));
|
||||
if (error) {
|
||||
SULog(@"DSA signature verification failed: %@", error);
|
||||
SULog(SULogLevelError, @"DSA signature verification failed: %@", error);
|
||||
return cleanup();
|
||||
}
|
||||
|
||||
if (!result.boolValue) {
|
||||
SULog(@"DSA signature does not match. Data of the update file being checked is different than data that has been signed, or the public key and the private key are not from the same set.");
|
||||
SULog(SULogLevelError, @"DSA signature does not match. Data of the update file being checked is different than data that has been signed, or the public key and the private key are not from the same set.");
|
||||
}
|
||||
|
||||
cleanup();
|
||||
|
||||
Vendored
+9
-3
@@ -9,11 +9,17 @@
|
||||
#ifndef SUDISKIMAGEUNARCHIVER_H
|
||||
#define SUDISKIMAGEUNARCHIVER_H
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
#import "SUUnarchiver.h"
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "SUUnarchiverProtocol.h"
|
||||
|
||||
@interface SUDiskImageUnarchiver : SUUnarchiver
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface SUDiskImageUnarchiver : NSObject <SUUnarchiverProtocol>
|
||||
|
||||
- (instancetype)initWithArchivePath:(NSString *)archivePath decryptionPassword:(nullable NSString *)decryptionPassword;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
#endif
|
||||
Vendored
+77
-77
@@ -7,12 +7,24 @@
|
||||
//
|
||||
|
||||
#import "SUDiskImageUnarchiver.h"
|
||||
#import "SUUnarchiver_Private.h"
|
||||
#import "SUUnarchiverNotifier.h"
|
||||
#import "SULog.h"
|
||||
#include <CoreServices/CoreServices.h>
|
||||
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
|
||||
@interface SUDiskImageUnarchiver ()
|
||||
|
||||
@property (nonatomic, copy, readonly) NSString *archivePath;
|
||||
@property (nullable, nonatomic, copy, readonly) NSString *decryptionPassword;
|
||||
|
||||
@end
|
||||
|
||||
@implementation SUDiskImageUnarchiver
|
||||
|
||||
@synthesize archivePath = _archivePath;
|
||||
@synthesize decryptionPassword = _decryptionPassword;
|
||||
|
||||
+ (BOOL)canUnarchivePath:(NSString *)path
|
||||
{
|
||||
return [[path pathExtension] isEqualToString:@"dmg"];
|
||||
@@ -23,59 +35,58 @@
|
||||
return NO;
|
||||
}
|
||||
|
||||
// Called on a non-main thread.
|
||||
- (void)extractDMG
|
||||
- (instancetype)initWithArchivePath:(NSString *)archivePath decryptionPassword:(nullable NSString *)decryptionPassword
|
||||
{
|
||||
@autoreleasepool {
|
||||
[self extractDMGWithPassword:nil];
|
||||
self = [super init];
|
||||
if (self != nil) {
|
||||
_archivePath = [archivePath copy];
|
||||
_decryptionPassword = [decryptionPassword copy];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)unarchiveWithCompletionBlock:(void (^)(NSError * _Nullable))completionBlock progressBlock:(void (^ _Nullable)(double))progressBlock
|
||||
{
|
||||
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
|
||||
SUUnarchiverNotifier *notifier = [[SUUnarchiverNotifier alloc] initWithCompletionBlock:completionBlock progressBlock:progressBlock];
|
||||
[self extractDMGWithNotifier:notifier];
|
||||
});
|
||||
}
|
||||
|
||||
// Called on a non-main thread.
|
||||
- (void)extractDMGWithPassword:(NSString *)__unused password
|
||||
- (void)extractDMGWithNotifier:(SUUnarchiverNotifier *)notifier
|
||||
{
|
||||
@autoreleasepool {
|
||||
BOOL mountedSuccessfully = NO;
|
||||
|
||||
SULog(@"Extracting %@ as a DMG", self.archivePath);
|
||||
|
||||
|
||||
// get a unique mount point path
|
||||
NSString *mountPoint = nil;
|
||||
FSRef tmpRef;
|
||||
NSFileManager *manager;
|
||||
NSError *error;
|
||||
NSArray *contents;
|
||||
// We have to declare these before a goto to prevent an error under ARC.
|
||||
// No, we cannot have them in the dispatch_async calls, as the goto "jump enters
|
||||
// lifetime of block which strongly captures a variable"
|
||||
dispatch_block_t delegateFailure = ^{
|
||||
[self notifyDelegateOfFailure];
|
||||
};
|
||||
dispatch_block_t delegateSuccess = ^{
|
||||
[self notifyDelegateOfSuccess];
|
||||
};
|
||||
do
|
||||
do
|
||||
{
|
||||
// Using NSUUID would make creating UUIDs be done in Cocoa,
|
||||
// and thus managed under ARC. Sadly, the class is in 10.8 and later.
|
||||
CFUUIDRef uuid = CFUUIDCreate(NULL);
|
||||
if (uuid)
|
||||
{
|
||||
if (uuid)
|
||||
{
|
||||
NSString *uuidString = CFBridgingRelease(CFUUIDCreateString(NULL, uuid));
|
||||
if (uuidString)
|
||||
{
|
||||
if (uuidString)
|
||||
{
|
||||
mountPoint = [@"/Volumes" stringByAppendingPathComponent:uuidString];
|
||||
}
|
||||
CFRelease(uuid);
|
||||
}
|
||||
}
|
||||
while (noErr == FSPathMakeRefWithOptions((const UInt8 *)[mountPoint fileSystemRepresentation], kFSPathMakeRefDoNotFollowLeafSymlink, &tmpRef, NULL));
|
||||
|
||||
}
|
||||
// Note: this check does not follow symbolic links, which is what we want
|
||||
while ([[NSURL fileURLWithPath:mountPoint] checkResourceIsReachableAndReturnError:NULL]);
|
||||
|
||||
NSData *promptData = nil;
|
||||
promptData = [NSData dataWithBytes:"yes\n" length:4];
|
||||
|
||||
|
||||
NSMutableArray *arguments = [@[@"attach", self.archivePath, @"-mountpoint", mountPoint, /*@"-noverify",*/ @"-nobrowse", @"-noautoopen"] mutableCopy];
|
||||
|
||||
|
||||
if (self.decryptionPassword) {
|
||||
NSMutableData *passwordData = [[self.decryptionPassword dataUsingEncoding:NSUTF8StringEncoding] mutableCopy];
|
||||
// From the hdiutil docs:
|
||||
@@ -85,14 +96,14 @@
|
||||
[passwordData appendData:[NSData dataWithBytes:"\0" length:1]];
|
||||
[passwordData appendData:promptData];
|
||||
promptData = passwordData;
|
||||
|
||||
|
||||
[arguments addObject:@"-stdinpass"];
|
||||
}
|
||||
|
||||
|
||||
NSData *output = nil;
|
||||
NSInteger taskResult = -1;
|
||||
@try
|
||||
{
|
||||
@try
|
||||
{
|
||||
NSTask *task = [[NSTask alloc] init];
|
||||
task.launchPath = @"/usr/bin/hdiutil";
|
||||
task.currentDirectoryPath = @"/";
|
||||
@@ -106,6 +117,8 @@
|
||||
|
||||
[task launch];
|
||||
|
||||
[notifier notifyProgress:0.125];
|
||||
|
||||
[inputPipe.fileHandleForWriting writeData:promptData];
|
||||
[inputPipe.fileHandleForWriting closeFile];
|
||||
|
||||
@@ -119,88 +132,75 @@
|
||||
{
|
||||
goto reportError;
|
||||
}
|
||||
|
||||
[notifier notifyProgress:0.5];
|
||||
|
||||
if (taskResult != 0)
|
||||
{
|
||||
NSString *resultStr = output ? [[NSString alloc] initWithData:output encoding:NSUTF8StringEncoding] : nil;
|
||||
SULog(@"hdiutil failed with code: %ld data: <<%@>>", (long)taskResult, resultStr);
|
||||
SULog(SULogLevelError, @"hdiutil failed with code: %ld data: <<%@>>", (long)taskResult, resultStr);
|
||||
goto reportError;
|
||||
}
|
||||
mountedSuccessfully = YES;
|
||||
|
||||
|
||||
// Now that we've mounted it, we need to copy out its contents.
|
||||
manager = [[NSFileManager alloc] init];
|
||||
contents = [manager contentsOfDirectoryAtPath:mountPoint error:&error];
|
||||
if (error)
|
||||
{
|
||||
SULog(@"Couldn't enumerate contents of archive mounted at %@: %@", mountPoint, error);
|
||||
if (error)
|
||||
{
|
||||
SULog(SULogLevelError, @"Couldn't enumerate contents of archive mounted at %@: %@", mountPoint, error);
|
||||
goto reportError;
|
||||
}
|
||||
|
||||
double itemsCopied = 0;
|
||||
double totalItems = [contents count];
|
||||
|
||||
for (NSString *item in contents)
|
||||
{
|
||||
NSString *fromPath = [mountPoint stringByAppendingPathComponent:item];
|
||||
NSString *toPath = [[self.archivePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:item];
|
||||
|
||||
|
||||
// We skip any files in the DMG which are not readable.
|
||||
if (![manager isReadableFileAtPath:fromPath]) {
|
||||
continue;
|
||||
}
|
||||
|
||||
SULog(@"copyItemAtPath:%@ toPath:%@", fromPath, toPath);
|
||||
|
||||
itemsCopied += 1.0;
|
||||
[notifier notifyProgress:0.5 + itemsCopied/(totalItems*2.0)];
|
||||
SULog(SULogLevelDefault, @"copyItemAtPath:%@ toPath:%@", fromPath, toPath);
|
||||
|
||||
if (![manager copyItemAtPath:fromPath toPath:toPath error:&error])
|
||||
{
|
||||
SULog(@"Couldn't copy item: %@ : %@", error, error.userInfo ? error.userInfo : @"");
|
||||
goto reportError;
|
||||
}
|
||||
}
|
||||
|
||||
dispatch_async(dispatch_get_main_queue(), delegateSuccess);
|
||||
|
||||
[notifier notifySuccess];
|
||||
goto finally;
|
||||
|
||||
|
||||
reportError:
|
||||
dispatch_async(dispatch_get_main_queue(), delegateFailure);
|
||||
[notifier notifyFailureWithError:error];
|
||||
|
||||
finally:
|
||||
if (mountedSuccessfully) {
|
||||
NSTask *task = [[NSTask alloc] init];
|
||||
task.launchPath = @"/usr/bin/hdiutil";
|
||||
task.arguments = @[@"detach", mountPoint, @"-force"];
|
||||
task.standardOutput = [NSPipe pipe];
|
||||
task.standardError = [NSPipe pipe];
|
||||
|
||||
@try {
|
||||
[NSTask launchedTaskWithLaunchPath:@"/usr/bin/hdiutil" arguments:@[@"detach", mountPoint, @"-force"]];
|
||||
[task launch];
|
||||
} @catch (NSException *exception) {
|
||||
SULog(@"Failed to unmount %@", mountPoint);
|
||||
SULog(@"Exception: %@", exception);
|
||||
SULog(SULogLevelError, @"Failed to unmount %@", mountPoint);
|
||||
SULog(SULogLevelError, @"Exception: %@", exception);
|
||||
}
|
||||
} else {
|
||||
SULog(@"Can't mount DMG %@", self.archivePath);
|
||||
SULog(SULogLevelError, @"Can't mount DMG %@", self.archivePath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
- (void)start
|
||||
{
|
||||
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
|
||||
[self extractDMG];
|
||||
});
|
||||
}
|
||||
|
||||
+ (void)load
|
||||
{
|
||||
[self registerImplementation:self];
|
||||
}
|
||||
|
||||
- (BOOL)isEncrypted:(NSData *)resultData
|
||||
{
|
||||
BOOL result = NO;
|
||||
if(resultData)
|
||||
{
|
||||
NSString *data = [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding];
|
||||
|
||||
if ((data != nil) && !NSEqualRanges([data rangeOfString:@"passphrase-count"], NSMakeRange(NSNotFound, 0)))
|
||||
{
|
||||
result = YES;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], self.archivePath]; }
|
||||
|
||||
@end
|
||||
Vendored
+3
@@ -21,6 +21,8 @@
|
||||
*/
|
||||
SU_EXPORT extern NSString *const SUSparkleErrorDomain;
|
||||
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wc++98-compat"
|
||||
typedef NS_ENUM(OSStatus, SUError) {
|
||||
// Appcast phase errors.
|
||||
SUAppcastParseError = 1000,
|
||||
@@ -49,5 +51,6 @@ typedef NS_ENUM(OSStatus, SUError) {
|
||||
// System phase errors
|
||||
SUSystemPowerOffError = 5000
|
||||
};
|
||||
#pragma clang diagnostic pop
|
||||
|
||||
#endif
|
||||
Vendored
+15
-25
@@ -8,6 +8,8 @@
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
/**
|
||||
* A class used for performing file operations that may also perform authorization 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.
|
||||
@@ -50,7 +52,7 @@
|
||||
* When moving an item from a source to a destination, it is desirable to create a temporary intermediate destination on the same volume as the destination to ensure
|
||||
* that the item will be moved, and not copied, from the intermediate point to the final destination. This ensures file atomicity.
|
||||
*/
|
||||
- (NSURL *)makeTemporaryDirectoryWithPreferredName:(NSString *)preferredName appropriateForDirectoryURL:(NSURL *)appropriateURL error:(NSError **)error;
|
||||
- (nullable NSURL *)makeTemporaryDirectoryWithPreferredName:(NSString *)preferredName appropriateForDirectoryURL:(NSURL *)appropriateURL error:(NSError *_Nullable*_Nullable)error;
|
||||
|
||||
/**
|
||||
* Creates a directory at the target URL
|
||||
@@ -60,7 +62,7 @@
|
||||
*
|
||||
* This is an atomic operation.
|
||||
*/
|
||||
- (BOOL)makeDirectoryAtURL:(NSURL *)targetURL error:(NSError **)error;
|
||||
- (BOOL)makeDirectoryAtURL:(NSURL *)targetURL error:(NSError *_Nullable*_Nullable)error;
|
||||
|
||||
/**
|
||||
* Moves an item from a source to a destination
|
||||
@@ -68,11 +70,11 @@
|
||||
* @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 moved successfully, otherwise NO along with a populated error object
|
||||
*
|
||||
*
|
||||
* If sourceURL and destinationURL reside on the same volume, this operation will be an atomic move operation.
|
||||
* Otherwise this will be equivalent to a copy & remove which will be a nonatomic operation.
|
||||
*/
|
||||
- (BOOL)moveItemAtURL:(NSURL *)sourceURL toURL:(NSURL *)destinationURL error:(NSError **)error;
|
||||
- (BOOL)moveItemAtURL:(NSURL *)sourceURL toURL:(NSURL *)destinationURL error:(NSError *_Nullable*_Nullable)error;
|
||||
|
||||
/**
|
||||
* Copies an item from a source to a destination
|
||||
@@ -83,22 +85,7 @@
|
||||
*
|
||||
* 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.
|
||||
* @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 moved to the trash successfully, otherwise NO along with a populated error object
|
||||
*
|
||||
*
|
||||
* This method has to locate the trash directory and uses an intermediate temporary directory before trashing the item.
|
||||
* A copy may have to be done if the url is not on the same volume as the running user's trash directory.
|
||||
* If a failure occurs in the middle of this operation, the item to remove may be lost forever or stuck in a temporary location.
|
||||
*
|
||||
* This is not an atomic operation, nor intended to be a recoverable operation if the worst comes to worst.
|
||||
*/
|
||||
- (BOOL)moveItemAtURLToTrash:(NSURL *)url error:(NSError **)error;
|
||||
- (BOOL)copyItemAtURL:(NSURL *)sourceURL toURL:(NSURL *)destinationURL error:(NSError *_Nullable*_Nullable)error;
|
||||
|
||||
/**
|
||||
* Removes an item at a URL
|
||||
@@ -108,7 +95,7 @@
|
||||
*
|
||||
* This is not an atomic operation.
|
||||
*/
|
||||
- (BOOL)removeItemAtURL:(NSURL *)url error:(NSError **)error;
|
||||
- (BOOL)removeItemAtURL:(NSURL *)url error:(NSError *_Nullable*_Nullable)error;
|
||||
|
||||
/**
|
||||
* Changes the owner and group IDs of an item at a specified target URL to match another URL
|
||||
@@ -123,7 +110,7 @@
|
||||
*
|
||||
* This is not an atomic operation.
|
||||
*/
|
||||
- (BOOL)changeOwnerAndGroupOfItemAtRootURL:(NSURL *)targetURL toMatchURL:(NSURL *)matchURL error:(NSError **)error;
|
||||
- (BOOL)changeOwnerAndGroupOfItemAtRootURL:(NSURL *)targetURL toMatchURL:(NSURL *)matchURL error:(NSError *_Nullable*_Nullable)error;
|
||||
|
||||
/**
|
||||
* Updates the modification and access time of an item at a specified target URL to the current time
|
||||
@@ -136,7 +123,7 @@
|
||||
*
|
||||
* This is not an atomic operation.
|
||||
*/
|
||||
- (BOOL)updateModificationAndAccessTimeOfItemAtURL:(NSURL *)targetURL error:(NSError **)error;
|
||||
- (BOOL)updateModificationAndAccessTimeOfItemAtURL:(NSURL *)targetURL error:(NSError *_Nullable*_Nullable)error;
|
||||
|
||||
/**
|
||||
* Releases Apple's quarantine extended attribute from the item at the specified root URL
|
||||
@@ -154,11 +141,12 @@
|
||||
*
|
||||
* This is not an atomic operation.
|
||||
*/
|
||||
- (BOOL)releaseItemFromQuarantineAtRootURL:(NSURL *)rootURL error:(NSError **)error;
|
||||
- (BOOL)releaseItemFromQuarantineAtRootURL:(NSURL *)rootURL error:(NSError *_Nullable*_Nullable)error;
|
||||
|
||||
/**
|
||||
* Runs an installer package (pkg) in a headless mode using /usr/sbin/installer
|
||||
* @param packageURL A URL pointing to the package to execute. The item at this URL must exist.
|
||||
* @param progressBlock Callback that takes double value (0..1 range) notifying how far the installation has progressed
|
||||
* @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 installer ran the package successfully, otherwise NO with a populated error object
|
||||
*
|
||||
@@ -166,6 +154,8 @@
|
||||
* an initial authorization prompt if the calling process does not have root privileges. In other words, root privileges are required to use this method, and the file manager instance must have been created by allowing authorization.
|
||||
* An error can occur if the package is unable to be ran by the installer, or if the installer reports a non-zero exit status code.
|
||||
*/
|
||||
- (BOOL)executePackageAtURL:(NSURL *)packageURL error:(NSError **)error;
|
||||
- (BOOL)executePackageAtURL:(NSURL *)packageURL progressBlock:(nullable void(^)(double))progressBlock error:(NSError *_Nullable*_Nullable)error;
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
@end
|
||||
Vendored
+96
-122
@@ -7,6 +7,7 @@
|
||||
//
|
||||
|
||||
#import "SUFileManager.h"
|
||||
#import "SUErrors.h"
|
||||
#import "SUOperatingSystem.h"
|
||||
#import "SUFileOperationConstants.h"
|
||||
|
||||
@@ -14,6 +15,9 @@
|
||||
#include <sys/errno.h>
|
||||
#include <sys/time.h>
|
||||
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
|
||||
static char SUAppleQuarantineIdentifier[] = "com.apple.quarantine";
|
||||
|
||||
static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
|
||||
@@ -105,20 +109,20 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
|
||||
_auth = NULL;
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
AuthorizationItem rightItems[] = {
|
||||
// The right that allows us to run tools as root user
|
||||
{.name = kAuthorizationRightExecute, .valueLength = 0, .value = NULL, .flags = 0}
|
||||
};
|
||||
|
||||
|
||||
AuthorizationRights rights = {
|
||||
.count = sizeof(rightItems) / sizeof(*rightItems),
|
||||
.items = rightItems
|
||||
};
|
||||
|
||||
|
||||
AuthorizationFlags flags =
|
||||
(AuthorizationFlags)(kAuthorizationFlagDefaults | kAuthorizationFlagInteractionAllowed | kAuthorizationFlagExtendRights | kAuthorizationFlagPreAuthorize);
|
||||
|
||||
|
||||
// This will test if we can gain authorization for running utlities as root
|
||||
OSStatus copyStatus = AuthorizationCopyRights(_auth, &rights, kAuthorizationEmptyEnvironment, flags, NULL);
|
||||
if (copyStatus != errAuthorizationSuccess) {
|
||||
@@ -129,17 +133,21 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed granting authorization rights with status code %d.", copyStatus] }];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
AuthorizationFree(_auth, kAuthorizationFlagDefaults);
|
||||
_auth = NULL;
|
||||
|
||||
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (BOOL)_authorizeAndExecuteCommand:(char *)command sourcePath:(char *)sourcePath destinationPath:(char *)destinationPath error:(NSError * __autoreleasing *)error
|
||||
- (BOOL)_authorizeAndExecuteCommand:(char *)command sourcePath:(char *)sourcePath destinationPath:(char *)destinationPath error:(NSError * __autoreleasing *)error {
|
||||
return [self _authorizeAndExecuteCommand:command sourcePath:sourcePath destinationPath:destinationPath lineCallback:nil error:error];
|
||||
}
|
||||
|
||||
- (BOOL)_authorizeAndExecuteCommand:(char *)command sourcePath:(char *)sourcePath destinationPath:(char *)destinationPath lineCallback:(void(^)(NSString*))lineCallback error:(NSError * __autoreleasing *)error
|
||||
{
|
||||
NSError *acquireError = nil;
|
||||
if (![self _acquireAuthorizationWithError:&acquireError]) {
|
||||
@@ -148,9 +156,9 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
char *arguments[] = { command, sourcePath, destinationPath, NULL };
|
||||
|
||||
|
||||
char toolPath[PATH_MAX] = {0};
|
||||
if (![_authorizationToolPath getFileSystemRepresentation:toolPath maxLength:sizeof(toolPath)]) {
|
||||
if (error != NULL) {
|
||||
@@ -158,18 +166,22 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
FILE *pipe = NULL;
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
|
||||
if (AuthorizationExecuteWithPrivileges(_auth, toolPath, kAuthorizationFlagDefaults, arguments, &pipe) != errAuthorizationSuccess) {
|
||||
OSStatus runStatus = AuthorizationExecuteWithPrivileges(_auth, toolPath, kAuthorizationFlagDefaults, arguments, &pipe);
|
||||
if (runStatus != errAuthorizationSuccess) {
|
||||
#pragma clang diagnostic pop
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:@"Failed to run authorization tool." }];
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wcstring-format-directive"
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Failed to run authorization tool %s (error code %d).", toolPath, (int)runStatus] }];
|
||||
#pragma clang diagnostic pop
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
uint32_t pidData = 0;
|
||||
if (fread(&pidData, sizeof(pidData), 1, pipe) < 1) {
|
||||
if (error != NULL) {
|
||||
@@ -178,27 +190,54 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
|
||||
fclose(pipe);
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
if (lineCallback) {
|
||||
NSFileHandle *pipeHandle = [[NSFileHandle alloc] initWithFileDescriptor:fileno(pipe) closeOnDealloc:NO];
|
||||
[self parseLines:pipeHandle lineCallback:lineCallback];
|
||||
}
|
||||
|
||||
pid_t childPid = (int32_t)CFSwapInt32LittleToHost(pidData);
|
||||
int status = 0;
|
||||
|
||||
|
||||
pid_t waitResult;
|
||||
do {
|
||||
waitResult = waitpid(childPid, &status, 0);
|
||||
} while (waitResult == -1 && errno == EINTR);
|
||||
|
||||
|
||||
fclose(pipe);
|
||||
|
||||
|
||||
if (waitResult == -1 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Failed to execute authorized executable with result %d and status (%d, %d, %d).", waitResult, status, WIFEXITED(status), WEXITSTATUS(status)] }];
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (void)parseLines:(NSFileHandle *)pipeHandle lineCallback:(void(^)(NSString *))lineCallback {
|
||||
__block NSMutableData *line = [NSMutableData new];
|
||||
pipeHandle.readabilityHandler = ^(NSFileHandle *handle){
|
||||
NSData *data = handle.availableData;
|
||||
NSUInteger length = data.length;
|
||||
if (!length) {
|
||||
return;
|
||||
}
|
||||
const char *bytes = data.bytes;
|
||||
for(NSUInteger i = 0; i < length; i++) {
|
||||
if (bytes[i] == '\n') {
|
||||
NSData *dataToEOL = [data subdataWithRange:NSMakeRange(0, i)];
|
||||
[line appendData:dataToEOL];
|
||||
NSString *fullLine = [[NSString alloc] initWithData:line encoding:NSUTF8StringEncoding];
|
||||
lineCallback(fullLine);
|
||||
line = [[data subdataWithRange:NSMakeRange(i+1, length-i-1)] mutableCopy];
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
- (void)dealloc
|
||||
{
|
||||
if (_auth != NULL) {
|
||||
@@ -279,7 +318,9 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
NSLog(@"Sparkle: Authorization required to remove quarantine %@", rootURL);
|
||||
|
||||
NSError *executeError = nil;
|
||||
BOOL success = [self _authorizeAndExecuteCommand:SUFileOpRemoveQuarantineCommand sourcePath:path destinationPath:NULL error:&executeError];
|
||||
if (!success && error != NULL) {
|
||||
@@ -477,7 +518,9 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
NSLog(@"Sparkle: Authorization required to copy %@ to %@", sourceURL, destinationURL);
|
||||
|
||||
NSError *executeError = nil;
|
||||
if (![self _authorizeAndExecuteCommand:SUFileOpCopyCommand sourcePath:sourcePath destinationPath:destinationPath error:&executeError]) {
|
||||
if (error != NULL) {
|
||||
@@ -570,6 +613,8 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
|
||||
return NO;
|
||||
}
|
||||
|
||||
NSLog(@"Sparkle: Authorization required to move %@ to %@", sourceURL, destinationURL);
|
||||
|
||||
char sourcePath[PATH_MAX] = {0};
|
||||
if (![sourceURL.path getFileSystemRepresentation:sourcePath maxLength:sizeof(sourcePath)]) {
|
||||
if (error != NULL) {
|
||||
@@ -585,7 +630,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
NSError *executeError = nil;
|
||||
if (![self _authorizeAndExecuteCommand:SUFileOpMoveCommand sourcePath:sourcePath destinationPath:destinationPath error:&executeError]) {
|
||||
if (error != NULL) {
|
||||
@@ -615,11 +660,11 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
// We use fchown instead of chown because the latter can follow symbolic links
|
||||
BOOL success = fchown(fileDescriptor, ownerID.unsignedIntValue, groupID.unsignedIntValue) == 0;
|
||||
close(fileDescriptor);
|
||||
|
||||
|
||||
if (!success) {
|
||||
if (errno == EPERM) {
|
||||
if (needsAuth != NULL) {
|
||||
@@ -730,7 +775,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
char matchPath[PATH_MAX] = {0};
|
||||
if (![matchURLPath getFileSystemRepresentation:matchPath maxLength:sizeof(matchPath)]) {
|
||||
if (error != NULL) {
|
||||
@@ -739,6 +784,8 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
|
||||
return NO;
|
||||
}
|
||||
|
||||
NSLog(@"Sparkle: Authorization required to change permissions of %@ to match %@", targetURL, matchURL);
|
||||
|
||||
NSError *executeError = nil;
|
||||
BOOL success = [self _authorizeAndExecuteCommand:SUFileOpChangeOwnerAndGroupCommand sourcePath:targetPath destinationPath:matchPath error:&executeError];
|
||||
if (!success && error != NULL) {
|
||||
@@ -779,12 +826,12 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
// Using futimes() because utimes() follows symbolic links
|
||||
BOOL updatedTime = (futimes(fileDescriptor, NULL) == 0);
|
||||
|
||||
|
||||
close(fileDescriptor);
|
||||
|
||||
|
||||
if (updatedTime) {
|
||||
return YES;
|
||||
}
|
||||
@@ -795,7 +842,9 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
NSLog(@"Sparkle: Authorization required to update timestamp of %@", targetURL);
|
||||
|
||||
NSError *executeError = nil;
|
||||
BOOL success = [self _authorizeAndExecuteCommand:SUFileOpUpdateModificationAndAccessTimeCommand sourcePath:path destinationPath:NULL error:&executeError];
|
||||
if (!success && error != NULL) {
|
||||
@@ -838,6 +887,8 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
|
||||
return NO;
|
||||
}
|
||||
|
||||
NSLog(@"Sparkle: Authorization required to make directory %@", url);
|
||||
|
||||
char path[PATH_MAX] = {0};
|
||||
if (![url.path getFileSystemRepresentation:path maxLength:sizeof(path)]) {
|
||||
if (error != NULL) {
|
||||
@@ -845,7 +896,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
NSError *executeError = nil;
|
||||
BOOL success = [self _authorizeAndExecuteCommand:SUFileOpMakeDirectoryCommand sourcePath:path destinationPath:NULL error:&executeError];
|
||||
if (!success) {
|
||||
@@ -854,7 +905,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: errorMessage, NSUnderlyingErrorKey: executeError }];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return success;
|
||||
}
|
||||
|
||||
@@ -900,6 +951,8 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
|
||||
return NO;
|
||||
}
|
||||
|
||||
NSLog(@"Sparkle: Authorization required to delete %@", url);
|
||||
|
||||
char path[PATH_MAX] = {0};
|
||||
if (![url.path getFileSystemRepresentation:path maxLength:sizeof(path)]) {
|
||||
if (error != NULL) {
|
||||
@@ -907,104 +960,19 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
NSError *executeError = nil;
|
||||
BOOL success = [self _authorizeAndExecuteCommand:SUFileOpRemoveCommand sourcePath:path destinationPath:NULL error:&executeError];
|
||||
|
||||
if (!success && error != NULL) {
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to remove %@ with authentication.", url.path.lastPathComponent], NSUnderlyingErrorKey: executeError }];
|
||||
}
|
||||
|
||||
return success;
|
||||
}
|
||||
|
||||
- (BOOL)moveItemAtURLToTrash:(NSURL *)url error:(NSError *__autoreleasing *)error
|
||||
{
|
||||
if (![self _itemExistsAtURL:url]) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileNoSuchFileError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to move %@ to the trash because the file does not exist.", url.path.lastPathComponent] }];
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
NSURL *trashURL = nil;
|
||||
BOOL canUseNewTrashAPI = YES;
|
||||
#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) {
|
||||
trashURL = CFBridgingRelease(CFURLCreateFromFSRef(kCFAllocatorDefault, &trashRef));
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
if (canUseNewTrashAPI) {
|
||||
trashURL = [_fileManager URLForDirectory:NSTrashDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
|
||||
}
|
||||
|
||||
if (trashURL == nil) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileNoSuchFileError userInfo:@{ NSLocalizedDescriptionKey: @"Failed to locate the user's trash folder." }];
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
// In the rare worst case scenario, our temporary directory will be labeled incomplete and be in the user's trash directory,
|
||||
// indicating that whatever inside of there is not yet completely moved.
|
||||
// Regardless, we want the item to be in our Volume before we try moving it to the trash
|
||||
NSString *preferredName = [url.lastPathComponent.stringByDeletingPathExtension stringByAppendingString:@" (Incomplete Files)"];
|
||||
NSURL *tempDirectory = [self makeTemporaryDirectoryWithPreferredName:preferredName appropriateForDirectoryURL:trashURL error:error];
|
||||
if (tempDirectory == nil) {
|
||||
return NO;
|
||||
}
|
||||
|
||||
NSString *urlLastPathComponent = url.lastPathComponent;
|
||||
NSURL *tempItemURL = [tempDirectory URLByAppendingPathComponent:urlLastPathComponent];
|
||||
if (![self moveItemAtURL:url toURL:tempItemURL error:error]) {
|
||||
// If we can't move the item at url, just remove it completely; chances are it's not going to be missed
|
||||
[self removeItemAtURL:url error:NULL];
|
||||
[self removeItemAtURL:tempDirectory error:NULL];
|
||||
return NO;
|
||||
}
|
||||
|
||||
if (![self changeOwnerAndGroupOfItemAtRootURL:tempItemURL toMatchURL:trashURL error:error]) {
|
||||
// Removing the item inside of the temp directory is better than trying to move the item to the trash with incorrect ownership
|
||||
[self removeItemAtURL:tempDirectory error:NULL];
|
||||
return NO;
|
||||
}
|
||||
|
||||
// If we get here, we should be able to trash the item normally without authentication
|
||||
|
||||
BOOL success = NO;
|
||||
#if __MAC_OS_X_VERSION_MIN_REQUIRED < 1080
|
||||
if (!canUseNewTrashAPI) {
|
||||
NSString *tempParentPath = tempItemURL.URLByDeletingLastPathComponent.path;
|
||||
success = [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:tempParentPath destination:@"" files:@[tempItemURL.lastPathComponent] tag:NULL];
|
||||
if (!success && error != NULL) {
|
||||
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileNoSuchFileError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to move file %@ into the trash.", tempItemURL.lastPathComponent] }];
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
if (canUseNewTrashAPI) {
|
||||
NSError *trashError = nil;
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wpartial-availability"
|
||||
success = [_fileManager trashItemAtURL:tempItemURL resultingItemURL:NULL error:&trashError];
|
||||
#pragma clang diagnostic pop
|
||||
if (!success && error != NULL) {
|
||||
*error = trashError;
|
||||
}
|
||||
}
|
||||
|
||||
[self removeItemAtURL:tempDirectory error:NULL];
|
||||
|
||||
return success;
|
||||
}
|
||||
|
||||
// Unlike other methods, authorization is required to execute this method successfully
|
||||
- (BOOL)executePackageAtURL:(NSURL *)packageURL error:(NSError * __autoreleasing *)error
|
||||
- (BOOL)executePackageAtURL:(NSURL *)packageURL progressBlock:(void(^)(double))progressBlock error:(NSError * __autoreleasing *)error
|
||||
{
|
||||
if (![self _itemExistsAtURL:packageURL]) {
|
||||
if (error != NULL) {
|
||||
@@ -1012,7 +980,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
char path[PATH_MAX] = {0};
|
||||
if (![packageURL.path getFileSystemRepresentation:path maxLength:sizeof(path)]) {
|
||||
if (error != NULL) {
|
||||
@@ -1020,10 +988,16 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
NSLog(@"Sparkle: Authorization required to run pkg installer %@", packageURL);
|
||||
|
||||
NSError *executeError = nil;
|
||||
BOOL success = [self _authorizeAndExecuteCommand:SUFileOpInstallCommand sourcePath:path destinationPath:NULL error:&executeError];
|
||||
|
||||
BOOL success = [self _authorizeAndExecuteCommand:SUFileOpInstallCommand sourcePath:path destinationPath:NULL lineCallback:^(NSString *line){
|
||||
if ([line hasPrefix:@"installer:%"]) {
|
||||
progressBlock([[line substringFromIndex:11] doubleValue]/100.0);
|
||||
}
|
||||
} error:&executeError];
|
||||
|
||||
if (!success && error != NULL) {
|
||||
NSString* errorMessage = @"Failed to execute package installer.";
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{NSLocalizedDescriptionKey: errorMessage, NSUnderlyingErrorKey: executeError}];
|
||||
|
||||
Vendored
+7
-9
@@ -19,17 +19,15 @@ A guided installation can be started by applications other than the application
|
||||
- Replace the use of `AuthorizationExecuteWithPrivilegesAndWait`. This method remains because it is well supported and tested. Ideally a helper tool or XPC would be used.
|
||||
*/
|
||||
|
||||
#ifndef SUGUIDEDPACKAGEINSTALLER_H
|
||||
#define SUGUIDEDPACKAGEINSTALLER_H
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "Sparkle.h"
|
||||
#import "SUInstaller.h"
|
||||
#import "SUInstallerProtocol.h"
|
||||
|
||||
@interface SUGuidedPackageInstaller : SUInstaller
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface SUGuidedPackageInstaller : NSObject <SUInstallerProtocol>
|
||||
|
||||
- (instancetype)initWithPackagePath:(NSString *)packagePath installationPath:(NSString *)installationPath fileOperationToolPath:(NSString *)fileOperationToolPath;
|
||||
|
||||
/*! Perform the guided installation */
|
||||
+ (void)performInstallationToPath:(NSString *)path fromPath:(NSString *)installerGuide host:(SUHost *)host fileOperationToolPath:(NSString *)fileOperationToolPath versionComparator:(id<SUVersionComparison>)comparator completionHandler:(void (^)(NSError *))completionHandler;
|
||||
@end
|
||||
|
||||
#endif
|
||||
NS_ASSUME_NONNULL_END
|
||||
Vendored
+39
-16
@@ -9,26 +9,49 @@
|
||||
#import "SUGuidedPackageInstaller.h"
|
||||
#import "SUFileManager.h"
|
||||
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
|
||||
@interface SUGuidedPackageInstaller ()
|
||||
|
||||
@property (nonatomic, readonly, copy) NSString *packagePath;
|
||||
@property (nonatomic, readonly, copy) NSString *installationPath;
|
||||
@property (nonatomic, readonly, copy) NSString *fileOperationToolPath;
|
||||
|
||||
@end
|
||||
|
||||
@implementation SUGuidedPackageInstaller
|
||||
|
||||
+ (void)performInstallationToPath:(NSString *)destinationPath fromPath:(NSString *)packagePath host:(SUHost *)__unused host fileOperationToolPath:(NSString *)fileOperationToolPath versionComparator:(id<SUVersionComparison>)__unused comparator completionHandler:(void (^)(NSError *))completionHandler
|
||||
@synthesize packagePath = _packagePath;
|
||||
@synthesize installationPath = _installationPath;
|
||||
@synthesize fileOperationToolPath = _fileOperationToolPath;
|
||||
|
||||
- (instancetype)initWithPackagePath:(NSString *)packagePath installationPath:(NSString *)installationPath fileOperationToolPath:(NSString *)fileOperationToolPath
|
||||
{
|
||||
SUParameterAssert(packagePath);
|
||||
self = [super init];
|
||||
if (self != nil) {
|
||||
_packagePath = [packagePath copy];
|
||||
_installationPath = [installationPath copy];
|
||||
_fileOperationToolPath = [fileOperationToolPath copy];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (BOOL)performInitialInstallation:(NSError * __autoreleasing *)__unused error
|
||||
{
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (BOOL)performFinalInstallationProgressBlock:(nullable void(^)(double))progressBlock error:(NSError * __autoreleasing *)error
|
||||
{
|
||||
SUFileManager *fileManager = [SUFileManager fileManagerWithAuthorizationToolPath:self.fileOperationToolPath];
|
||||
|
||||
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
|
||||
SUFileManager *fileManager = [SUFileManager fileManagerWithAuthorizationToolPath:fileOperationToolPath];
|
||||
|
||||
NSError *error = nil;
|
||||
BOOL validInstallation = [fileManager executePackageAtURL:[NSURL fileURLWithPath:packagePath] error:&error];
|
||||
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[self finishInstallationToPath:destinationPath
|
||||
withResult:validInstallation
|
||||
error:error
|
||||
completionHandler:completionHandler];
|
||||
|
||||
});
|
||||
});
|
||||
return [fileManager executePackageAtURL:[NSURL fileURLWithPath:self.packagePath] progressBlock:progressBlock error:error];
|
||||
}
|
||||
|
||||
- (BOOL)canInstallSilently
|
||||
{
|
||||
return YES;
|
||||
}
|
||||
|
||||
@end
|
||||
-17
@@ -6,18 +6,6 @@
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "SUUpdater.h"
|
||||
#import "SUAppcast.h"
|
||||
#import "SUAppcastItem.h"
|
||||
#import "SUVersionComparisonProtocol.h"
|
||||
|
||||
#if __MAC_OS_X_VERSION_MAX_ALLOWED < 101000
|
||||
typedef struct {
|
||||
NSInteger majorVersion;
|
||||
NSInteger minorVersion;
|
||||
NSInteger patchVersion;
|
||||
} NSOperatingSystemVersion;
|
||||
#endif
|
||||
|
||||
@interface SUHost : NSObject
|
||||
|
||||
@@ -25,17 +13,12 @@ typedef struct {
|
||||
|
||||
- (instancetype)initWithBundle:(NSBundle *)aBundle;
|
||||
@property (readonly, copy) NSString *bundlePath;
|
||||
@property (readonly) BOOL allowsAutomaticUpdates;
|
||||
@property (readonly, copy) NSString *installationPath;
|
||||
@property (readonly, copy) NSString *name;
|
||||
@property (readonly, copy) NSString *version;
|
||||
@property (readonly, copy) NSString *displayVersion;
|
||||
@property (readonly, copy) NSImage *icon;
|
||||
@property (getter=isRunningOnReadOnlyVolume, readonly) BOOL runningOnReadOnlyVolume;
|
||||
@property (getter=isBackgroundApplication, readonly) BOOL backgroundApplication;
|
||||
@property (readonly, copy) NSString *publicDSAKey;
|
||||
@property (readonly, nonatomic, copy) NSString *publicDSAKeyFileKey;
|
||||
@property (readonly, copy) NSArray *systemProfile;
|
||||
|
||||
- (id)objectForInfoDictionaryKey:(NSString *)key;
|
||||
- (BOOL)boolForInfoDictionaryKey:(NSString *)key;
|
||||
|
||||
+43
-106
@@ -8,20 +8,22 @@
|
||||
#import "SUHost.h"
|
||||
|
||||
#import "SUConstants.h"
|
||||
#import "SUSystemProfiler.h"
|
||||
#include <sys/mount.h> // For statfs for isRunningOnReadOnlyVolume
|
||||
#import "SULog.h"
|
||||
#import "SUFileManager.h"
|
||||
|
||||
#if __MAC_OS_X_VERSION_MAX_ALLOWED < 101000
|
||||
@interface NSProcessInfo ()
|
||||
- (NSOperatingSystemVersion)operatingSystemVersion;
|
||||
@end
|
||||
#endif
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
|
||||
// This class should not rely on AppKit and should also be process independent
|
||||
// For example, it should not have code that tests writabilty to somewhere on disk,
|
||||
// as that may depend on the privileges of the process owner. Or code that depends on
|
||||
// if the process is sandboxed or not; eg: finding the user's caches directory. Or code that depends
|
||||
// on compilation flags and if other files exist relative to the host bundle.
|
||||
|
||||
@interface SUHost ()
|
||||
|
||||
@property (strong, readwrite) NSBundle *bundle;
|
||||
@property (nonatomic, readonly) BOOL isMainBundle;
|
||||
@property (copy) NSString *defaultsDomain;
|
||||
@property (assign) BOOL usesStandardUserDefaults;
|
||||
|
||||
@@ -30,6 +32,7 @@
|
||||
@implementation SUHost
|
||||
|
||||
@synthesize bundle;
|
||||
@synthesize isMainBundle = _isMainBundle;
|
||||
@synthesize defaultsDomain;
|
||||
@synthesize usesStandardUserDefaults;
|
||||
|
||||
@@ -37,13 +40,15 @@
|
||||
{
|
||||
if ((self = [super init]))
|
||||
{
|
||||
SUParameterAssert(aBundle);
|
||||
NSParameterAssert(aBundle);
|
||||
self.bundle = aBundle;
|
||||
if (![self.bundle bundleIdentifier]) {
|
||||
SULog(@"Error: the bundle being updated at %@ has no %@! This will cause preference read/write to not work properly.", self.bundle, kCFBundleIdentifierKey);
|
||||
SULog(SULogLevelError, @"Error: the bundle being updated at %@ has no %@! This will cause preference read/write to not work properly.", self.bundle, kCFBundleIdentifierKey);
|
||||
}
|
||||
|
||||
_isMainBundle = [aBundle isEqualTo:[NSBundle mainBundle]];
|
||||
|
||||
self.defaultsDomain = [self.bundle objectForInfoDictionaryKey:SUDefaultsDomainKey];
|
||||
self.defaultsDomain = [self objectForInfoDictionaryKey:SUDefaultsDomainKey];
|
||||
if (!self.defaultsDomain) {
|
||||
self.defaultsDomain = [self.bundle bundleIdentifier];
|
||||
}
|
||||
@@ -56,68 +61,13 @@
|
||||
}
|
||||
|
||||
|
||||
- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@, %@>", [self class], [self bundlePath], [self installationPath]]; }
|
||||
- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], [self bundlePath]]; }
|
||||
|
||||
- (NSString *)bundlePath
|
||||
{
|
||||
return [self.bundle bundlePath];
|
||||
}
|
||||
|
||||
- (BOOL)allowsAutomaticUpdates
|
||||
{
|
||||
// Does the developer want us to disable automatic updates?
|
||||
NSNumber *developerAllowsAutomaticUpdates = [self objectForInfoDictionaryKey:SUAllowsAutomaticUpdatesKey];
|
||||
if (developerAllowsAutomaticUpdates != nil && !developerAllowsAutomaticUpdates.boolValue) {
|
||||
return NO;
|
||||
}
|
||||
|
||||
// Can we automatically update in the background without bugging the user (e.g, with a administrator password prompt)?
|
||||
// Note it's very well possible to have the bundle be writable but not be able to write into the parent directory
|
||||
// And if the bundle isn't writable, but we can write into the parent directory, we will still need to authorize to replace it
|
||||
NSString *bundlePath = [self bundlePath];
|
||||
if (![[NSFileManager defaultManager] isWritableFileAtPath:bundlePath.stringByDeletingLastPathComponent] || ![[NSFileManager defaultManager] isWritableFileAtPath:bundlePath]) {
|
||||
return NO;
|
||||
}
|
||||
|
||||
// Just because we have writability access does not mean we can set the correct owner/group silently
|
||||
// Test if we can set the owner/group on a temporarily created file
|
||||
// If we can, then we can probably perform an update without authorization
|
||||
// One place where this matters is if you copy and run an app from /tmp/
|
||||
|
||||
NSString *tempFilename = @"permission_test" ;
|
||||
|
||||
SUFileManager *suFileManager = [SUFileManager defaultManager];
|
||||
NSURL *tempDirectoryURL = [suFileManager makeTemporaryDirectoryWithPreferredName:tempFilename appropriateForDirectoryURL:[NSURL fileURLWithPath:NSTemporaryDirectory()] error:NULL];
|
||||
|
||||
if (tempDirectoryURL == nil) {
|
||||
// I don't imagine this ever happening but in case it does, requesting authorization may be the better option
|
||||
return NO;
|
||||
}
|
||||
|
||||
NSURL *tempFileURL = [tempDirectoryURL URLByAppendingPathComponent:tempFilename];
|
||||
|
||||
BOOL changeOwnerAndGroupSuccess =
|
||||
[[NSData data] writeToURL:tempFileURL atomically:NO] &&
|
||||
[suFileManager changeOwnerAndGroupOfItemAtRootURL:tempFileURL toMatchURL:self.bundle.bundleURL error:NULL];
|
||||
|
||||
[suFileManager removeItemAtURL:tempDirectoryURL error:NULL];
|
||||
|
||||
return changeOwnerAndGroupSuccess;
|
||||
}
|
||||
|
||||
- (NSString *)installationPath
|
||||
{
|
||||
if (SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME) {
|
||||
// We'll install to "#{CFBundleName}.app", but only if that path doesn't already exist. If we're "Foo 4.2.app," and there's a "Foo.app" in this directory, we don't want to overwrite it! But if there's no "Foo.app," we'll take that name.
|
||||
NSString *normalizedAppPath = [[[self.bundle bundlePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", [self.bundle objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleNameKey], [[self.bundle bundlePath] pathExtension]]];
|
||||
|
||||
if (![[NSFileManager defaultManager] fileExistsAtPath:normalizedAppPath]) {
|
||||
return normalizedAppPath;
|
||||
}
|
||||
}
|
||||
return [self.bundle bundlePath];
|
||||
}
|
||||
|
||||
- (NSString *__nonnull)name
|
||||
{
|
||||
NSString *name;
|
||||
@@ -126,18 +76,18 @@
|
||||
name = [self objectForInfoDictionaryKey:@"SUBundleName"];
|
||||
if (name && name.length > 0) return name;
|
||||
|
||||
name = [self.bundle objectForInfoDictionaryKey:@"CFBundleDisplayName"];
|
||||
name = [self objectForInfoDictionaryKey:@"CFBundleDisplayName"];
|
||||
if (name && name.length > 0) return name;
|
||||
|
||||
name = [self objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleNameKey];
|
||||
if (name && name.length > 0) return name;
|
||||
|
||||
return [[[NSFileManager defaultManager] displayNameAtPath:[self.bundle bundlePath]] stringByDeletingPathExtension];
|
||||
return [[[NSFileManager defaultManager] displayNameAtPath:[self bundlePath]] stringByDeletingPathExtension];
|
||||
}
|
||||
|
||||
- (NSString *__nonnull)version
|
||||
{
|
||||
NSString *version = [self.bundle objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleVersionKey];
|
||||
NSString *version = [self objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleVersionKey];
|
||||
if (!version || [version isEqualToString:@""])
|
||||
[NSException raise:@"SUNoVersionException" format:@"This host (%@) has no %@! This attribute is required.", [self bundlePath], (__bridge NSString *)kCFBundleVersionKey];
|
||||
return version;
|
||||
@@ -145,36 +95,13 @@
|
||||
|
||||
- (NSString *__nonnull)displayVersion
|
||||
{
|
||||
NSString *shortVersionString = [self.bundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
|
||||
NSString *shortVersionString = [self objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
|
||||
if (shortVersionString)
|
||||
return shortVersionString;
|
||||
else
|
||||
return [self version]; // Fall back on the normal version string.
|
||||
}
|
||||
|
||||
- (NSImage *__nonnull)icon
|
||||
{
|
||||
// Cache the application icon.
|
||||
NSString *iconPath = [self.bundle pathForResource:[self.bundle objectForInfoDictionaryKey:@"CFBundleIconFile"] ofType:@"icns"];
|
||||
// According to the macOS docs, "CFBundleIconFile - This key identifies the file containing
|
||||
// the icon for the bundle. The filename you specify does not need to include the .icns
|
||||
// extension, although it may."
|
||||
//
|
||||
// However, if it *does* include the '.icns' the above method fails (tested on macOS 10.3.9) so we'll also try:
|
||||
if (!iconPath) {
|
||||
iconPath = [self.bundle pathForResource:[self.bundle objectForInfoDictionaryKey:@"CFBundleIconFile"] ofType:nil];
|
||||
}
|
||||
NSImage *icon = [[NSImage alloc] initWithContentsOfFile:iconPath];
|
||||
// Use a default icon if none is defined.
|
||||
if (!icon) {
|
||||
BOOL isMainBundle = (self.bundle == [NSBundle mainBundle]);
|
||||
|
||||
NSString *fileType = isMainBundle ? (__bridge NSString *)kUTTypeApplication : (__bridge NSString *)kUTTypeBundle;
|
||||
icon = [[NSWorkspace sharedWorkspace] iconForFileType:fileType];
|
||||
}
|
||||
return icon;
|
||||
}
|
||||
|
||||
- (BOOL)isRunningOnReadOnlyVolume
|
||||
{
|
||||
struct statfs statfs_info;
|
||||
@@ -182,15 +109,10 @@
|
||||
return (statfs_info.f_flags & MNT_RDONLY) != 0;
|
||||
}
|
||||
|
||||
- (BOOL)isBackgroundApplication
|
||||
{
|
||||
return ([[NSApplication sharedApplication] activationPolicy] == NSApplicationActivationPolicyAccessory);
|
||||
}
|
||||
|
||||
- (NSString *__nullable)publicDSAKey
|
||||
{
|
||||
// Maybe the key is just a string in the Info.plist.
|
||||
NSString *key = [self.bundle objectForInfoDictionaryKey:SUPublicDSAKeyKey];
|
||||
NSString *key = [self objectForInfoDictionaryKey:SUPublicDSAKeyKey];
|
||||
if (key) {
|
||||
return key;
|
||||
}
|
||||
@@ -205,7 +127,12 @@
|
||||
if (!keyPath) {
|
||||
return nil;
|
||||
}
|
||||
return [NSString stringWithContentsOfFile:keyPath encoding:NSASCIIStringEncoding error:nil];
|
||||
NSError *error = nil;
|
||||
key = [NSString stringWithContentsOfFile:keyPath encoding:NSASCIIStringEncoding error:&error];
|
||||
if (error) {
|
||||
SULog(SULogLevelError, @"Error loading %@: %@", keyPath, error);
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
- (NSString * __nullable)publicDSAKeyFileKey
|
||||
@@ -213,14 +140,23 @@
|
||||
return [self objectForInfoDictionaryKey:SUPublicDSAKeyFileKey];
|
||||
}
|
||||
|
||||
- (NSArray *)systemProfile
|
||||
{
|
||||
return [[SUSystemProfiler sharedSystemProfiler] systemProfileArrayForHost:self];
|
||||
}
|
||||
|
||||
- (id)objectForInfoDictionaryKey:(NSString *)key
|
||||
{
|
||||
return [self.bundle objectForInfoDictionaryKey:key];
|
||||
if (self.isMainBundle) {
|
||||
// Common fast path - if we're updating the main bundle, that means our updater and host bundle's lifetime is the same
|
||||
// If the bundle happens to be updated or change, that means our updater process needs to be terminated first to do it safely
|
||||
// Thus we can rely on the cached Info dictionary
|
||||
return [self.bundle objectForInfoDictionaryKey:key];
|
||||
} else {
|
||||
// Slow path - if we're updating another bundle, we should read in the most up to date Info dictionary because
|
||||
// the bundle can be replaced externally or even by us.
|
||||
// This is the easiest way to read the Info dictionary values *correctly* despite some performance loss.
|
||||
// A mutable method to reload the Info dictionary at certain points and have it cached at other points is challenging to do correctly.
|
||||
CFDictionaryRef cfInfoDictionary = CFBundleCopyInfoDictionaryInDirectory((CFURLRef)self.bundle.bundleURL);
|
||||
NSDictionary *infoDictionary = CFBridgingRelease(cfInfoDictionary);
|
||||
|
||||
return [infoDictionary objectForKey:key];
|
||||
}
|
||||
}
|
||||
|
||||
- (BOOL)boolForInfoDictionaryKey:(NSString *)key
|
||||
@@ -245,6 +181,7 @@
|
||||
return CFBridgingRelease(obj);
|
||||
}
|
||||
|
||||
// Note this handles nil being passed for defaultName, in which case the user default will be removed
|
||||
- (void)setObject:(id)value forUserDefaultsKey:(NSString *)defaultName
|
||||
{
|
||||
if (self.usesStandardUserDefaults)
|
||||
|
||||
Vendored
+10
-8
@@ -6,19 +6,21 @@
|
||||
// Copyright 2008 Andy Matuschak. All rights reserved.
|
||||
//
|
||||
|
||||
#ifndef SUINSTALLER_H
|
||||
#define SUINSTALLER_H
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "SUVersionComparisonProtocol.h"
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@class SUHost;
|
||||
|
||||
@protocol SUInstallerProtocol;
|
||||
|
||||
@interface SUInstaller : NSObject
|
||||
|
||||
+ (NSString *)installSourcePathInUpdateFolder:(NSString *)inUpdateFolder forHost:(SUHost *)host isPackage:(BOOL *)isPackagePtr isGuided:(BOOL *)isGuidedPtr;
|
||||
+ (void)installFromUpdateFolder:(NSString *)inUpdateFolder overHost:(SUHost *)host installationPath:(NSString *)installationPath fileOperationToolPath:(NSString *)fileOperationToolPath versionComparator:(id<SUVersionComparison>)comparator completionHandler:(void (^)(NSError *))completionHandler;
|
||||
+ (void)finishInstallationToPath:(NSString *)installationPath withResult:(BOOL)result error:(NSError *)error completionHandler:(void (^)(NSError *))completionHandler;
|
||||
+ (nullable id<SUInstallerProtocol>)installerForHost:(SUHost *)host fileOperationToolPath:(NSString *)fileOperationToolPath updateDirectory:(NSString *)updateDirectory error:(NSError **)error;
|
||||
|
||||
+ (nullable NSString *)installSourcePathInUpdateFolder:(NSString *)inUpdateFolder forHost:(SUHost *)host isPackage:(BOOL *)isPackagePtr isGuided:(nullable BOOL *)isGuidedPtr;
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
NS_ASSUME_NONNULL_END
|
||||
Vendored
+56
-34
@@ -7,12 +7,16 @@
|
||||
//
|
||||
|
||||
#import "SUInstaller.h"
|
||||
#import "SUInstallerProtocol.h"
|
||||
#import "SUPlainInstaller.h"
|
||||
#import "SUPackageInstaller.h"
|
||||
#import "SUGuidedPackageInstaller.h"
|
||||
#import "SUHost.h"
|
||||
#import "SUConstants.h"
|
||||
#import "SULog.h"
|
||||
#import "SUErrors.h"
|
||||
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
|
||||
@implementation SUInstaller
|
||||
|
||||
@@ -25,10 +29,10 @@
|
||||
return aliasFlag.boolValue && directoryFlag.boolValue;
|
||||
}
|
||||
|
||||
+ (NSString *)installSourcePathInUpdateFolder:(NSString *)inUpdateFolder forHost:(SUHost *)host isPackage:(BOOL *)isPackagePtr isGuided:(BOOL *)isGuidedPtr
|
||||
+ (nullable NSString *)installSourcePathInUpdateFolder:(NSString *)inUpdateFolder forHost:(SUHost *)host isPackage:(BOOL *)isPackagePtr isGuided:(nullable BOOL *)isGuidedPtr
|
||||
{
|
||||
SUParameterAssert(inUpdateFolder);
|
||||
SUParameterAssert(host);
|
||||
NSParameterAssert(inUpdateFolder);
|
||||
NSParameterAssert(host);
|
||||
|
||||
// Search subdirectories for the application
|
||||
NSString *currentFile,
|
||||
@@ -36,7 +40,7 @@
|
||||
*bundleFileName = [[host bundlePath] lastPathComponent],
|
||||
*alternateBundleFileName = [[host name] stringByAppendingPathExtension:[[host bundlePath] pathExtension]];
|
||||
BOOL isPackage = NO;
|
||||
BOOL isGuided = NO;
|
||||
BOOL isGuided = YES;
|
||||
NSString *fallbackPackagePath = nil;
|
||||
NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath:inUpdateFolder];
|
||||
NSString *bundleFileNameNoExtension = [bundleFileName stringByDeletingPathExtension];
|
||||
@@ -86,9 +90,12 @@
|
||||
}
|
||||
|
||||
if (isPackage) {
|
||||
// foo.app -> foo.sparkle_guided.pkg or foo.sparkle_guided.mpkg
|
||||
if ([[[newAppDownloadPath stringByDeletingPathExtension] pathExtension] isEqualToString:@"sparkle_guided"]) {
|
||||
isGuided = YES;
|
||||
// Guided (or now "normal") installs used to be opt-in (i.e, Sparkle would detect foo.sparkle_guided.pkg or foo.sparkle_guided.mpkg),
|
||||
// but to get an interactive (or "unguided") install, the developer now must opt-out of guided installations.
|
||||
|
||||
// foo.app -> foo.sparkle_interactive.pkg or foo.sparkle_interactive.mpkg
|
||||
if ([[[newAppDownloadPath stringByDeletingPathExtension] pathExtension] isEqualToString:@"sparkle_interactive"]) {
|
||||
isGuided = NO;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,44 +105,59 @@
|
||||
*isGuidedPtr = isGuided;
|
||||
|
||||
if (!newAppDownloadPath) {
|
||||
SULog(@"Searched %@ for %@.(app|pkg)", inUpdateFolder, bundleFileNameNoExtension);
|
||||
SULog(SULogLevelError, @"Searched %@ for %@.(app|pkg)", inUpdateFolder, bundleFileNameNoExtension);
|
||||
}
|
||||
return newAppDownloadPath;
|
||||
}
|
||||
|
||||
+ (void)installFromUpdateFolder:(NSString *)inUpdateFolder overHost:(SUHost *)host installationPath:(NSString *)installationPath fileOperationToolPath:(NSString *)fileOperationToolPath versionComparator:(id<SUVersionComparison>)comparator completionHandler:(void (^)(NSError *))completionHandler
|
||||
+ (nullable id<SUInstallerProtocol>)installerForHost:(SUHost *)host fileOperationToolPath:(NSString *)fileOperationToolPath updateDirectory:(NSString *)updateDirectory error:(NSError * __autoreleasing *)error
|
||||
{
|
||||
BOOL isPackage = NO;
|
||||
BOOL isGuided = NO;
|
||||
NSString *newAppDownloadPath = [self installSourcePathInUpdateFolder:inUpdateFolder forHost:host isPackage:&isPackage isGuided:&isGuided];
|
||||
|
||||
if (newAppDownloadPath == nil) {
|
||||
[self finishInstallationToPath:installationPath withResult:NO error:[NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingUpdateError userInfo:@{ NSLocalizedDescriptionKey: @"Couldn't find an appropriate update in the downloaded package." }] completionHandler:completionHandler];
|
||||
} else {
|
||||
if (isPackage && isGuided) {
|
||||
[SUGuidedPackageInstaller performInstallationToPath:installationPath fromPath:newAppDownloadPath host:host fileOperationToolPath:fileOperationToolPath versionComparator:comparator completionHandler:completionHandler];
|
||||
} else if (isPackage) {
|
||||
[SUPackageInstaller performInstallationToPath:installationPath fromPath:newAppDownloadPath host:host fileOperationToolPath:fileOperationToolPath versionComparator:comparator completionHandler:completionHandler];
|
||||
} else {
|
||||
[SUPlainInstaller performInstallationToPath:installationPath fromPath:newAppDownloadPath host:host fileOperationToolPath:fileOperationToolPath versionComparator:comparator completionHandler:completionHandler];
|
||||
NSString *newDownloadPath = [self installSourcePathInUpdateFolder:updateDirectory forHost:host isPackage:&isPackage isGuided:&isGuided];
|
||||
|
||||
if (newDownloadPath == nil) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingUpdateError userInfo:@{ NSLocalizedDescriptionKey: @"Couldn't find an appropriate update in the downloaded package." }];
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
id <SUInstallerProtocol> installer;
|
||||
if (isPackage && isGuided) {
|
||||
installer = [[SUGuidedPackageInstaller alloc] initWithPackagePath:newDownloadPath installationPath:host.bundlePath fileOperationToolPath:fileOperationToolPath];
|
||||
} else if (isPackage) {
|
||||
installer = [[SUPackageInstaller alloc] initWithPackagePath:newDownloadPath installationPath:host.bundlePath];
|
||||
} else {
|
||||
NSString *normalizedInstallationPath = nil;
|
||||
if (SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME) {
|
||||
normalizedInstallationPath = [self normalizedInstallationPathForHost:host];
|
||||
}
|
||||
|
||||
// If we have a normalized path, we'll install to "#{CFBundleName}.app", but only if that path doesn't already exist. If we're "Foo 4.2.app," and there's a "Foo.app" in this directory, we don't want to overwrite it! But if there's no "Foo.app," we'll take that name.
|
||||
// Otherwise if there's no normalized path (the more likely case), we'll just use the host bundle's path
|
||||
NSString *installationPath;
|
||||
if (normalizedInstallationPath != nil && ![[NSFileManager defaultManager] fileExistsAtPath:normalizedInstallationPath]) {
|
||||
installationPath = normalizedInstallationPath;
|
||||
} else {
|
||||
installationPath = host.bundlePath;
|
||||
}
|
||||
|
||||
installer = [[SUPlainInstaller alloc] initWithHost:host bundlePath:newDownloadPath installationPath:installationPath fileOperationToolPath:fileOperationToolPath];
|
||||
}
|
||||
return installer;
|
||||
}
|
||||
|
||||
+ (void)finishInstallationToPath:(NSString *)__unused installationPath withResult:(BOOL)result error:(NSError *)error completionHandler:(void (^)(NSError *))completionHandler
|
||||
+ (NSString *)normalizedInstallationPathForHost:(SUHost *)host
|
||||
{
|
||||
if (result) {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
completionHandler(nil);
|
||||
});
|
||||
} else {
|
||||
if (!error) {
|
||||
error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:nil];
|
||||
}
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
completionHandler(error);
|
||||
});
|
||||
}
|
||||
NSBundle *bundle = host.bundle;
|
||||
assert(bundle != nil);
|
||||
|
||||
NSString *normalizedAppPath = [[[bundle bundlePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", [host objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleNameKey], [[bundle bundlePath] pathExtension]]];
|
||||
|
||||
// Roundtrip string through fileSystemRepresentation to ensure it uses filesystem's Unicode normalization
|
||||
// rather than arbitrary Unicode form from Info.plist - #1017
|
||||
return [NSString stringWithUTF8String:[normalizedAppPath fileSystemRepresentation]];
|
||||
}
|
||||
|
||||
@end
|
||||
Vendored
+36
@@ -0,0 +1,36 @@
|
||||
//
|
||||
// SUInstallerProtocol.h
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Mayur Pawashe on 12/26/16.
|
||||
// Copyright © 2016 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@protocol SUInstallerProtocol <NSObject>
|
||||
|
||||
// Any installation work can be done prior to user application being terminated and relaunched
|
||||
// Currently this is invoked after the user application is terminated, but this may change in the future.
|
||||
// No UI should occur during this stage (i.e, do not show package installer apps, etc..)
|
||||
// Should be able to be called from non-main thread
|
||||
- (BOOL)performInitialInstallation:(NSError **)error;
|
||||
|
||||
// Any installation work after the user application has been terminated. This is where the final installation work can be done.
|
||||
// After this stage is done, the user application may be relaunched.
|
||||
// Should be able to be called from non-main thread
|
||||
- (BOOL)performFinalInstallationProgressBlock:(nullable void(^)(double))cb error:(NSError **)error;
|
||||
|
||||
// Indicates whether or not this installer can install the update silently in the background, without hindering the user
|
||||
// Should be thread safe
|
||||
- (BOOL)canInstallSilently;
|
||||
|
||||
// The destination and installation path of the bundle being updated
|
||||
// Should be thread safe
|
||||
- (NSString *)installationPath;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
Vendored
+16
@@ -0,0 +1,16 @@
|
||||
//
|
||||
// SULocalizations.h
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Mayur Pawashe on 2/28/16.
|
||||
// Copyright © 2016 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#ifndef SULocalizations_h
|
||||
#define SULocalizations_h
|
||||
|
||||
#import "SUConstants.h"
|
||||
|
||||
#define SULocalizedString(key, comment) NSLocalizedStringFromTableInBundle(key, @"Sparkle", (NSBundle * _Nonnull)([NSBundle bundleWithIdentifier:SUBundleIdentifier] ? [NSBundle bundleWithIdentifier:SUBundleIdentifier] : [NSBundle mainBundle]), comment)
|
||||
|
||||
#endif /* SULocalizations_h */
|
||||
Vendored
+20
-23
@@ -1,32 +1,29 @@
|
||||
/*
|
||||
* SULog.h
|
||||
* EyeTV
|
||||
*
|
||||
* Created by Uli Kusterer on 12/03/2009.
|
||||
* Copyright 2008 Elgato Systems GmbH. All rights reserved.
|
||||
*
|
||||
*/
|
||||
|
||||
/*
|
||||
Log output for troubleshooting Sparkle failures on end-user machines.
|
||||
Your tech support will hug you if you tell them about this.
|
||||
*/
|
||||
//
|
||||
// SULog.h
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Mayur Pawashe on 5/18/16.
|
||||
// Copyright © 2016 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#ifndef SULOG_H
|
||||
#define SULOG_H
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// Headers:
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
#include <Foundation/Foundation.h>
|
||||
|
||||
typedef NS_ENUM(uint8_t, SULogLevel) {
|
||||
// This level is for information that *might* result a failure
|
||||
// For now until other levels are added, this may serve as a level for other information as well
|
||||
SULogLevelDefault,
|
||||
// This level is for errors that occurred
|
||||
SULogLevelError
|
||||
};
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// Prototypes:
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
void SUClearLog(void);
|
||||
void SULog(NSString *format, ...) NS_FORMAT_FUNCTION(1, 2);
|
||||
// Logging utlity function that is thread-safe
|
||||
// On 10.12 or later this uses os_log
|
||||
// Otherwise on older systems this uses ASL
|
||||
// For debugging command line tools, you may have to use Console.app or log(1) to view log messages
|
||||
// Try to keep log messages as compact/short as possible
|
||||
void SULog(SULogLevel level, NSString *format, ...) NS_FORMAT_FUNCTION(2, 3);
|
||||
|
||||
#endif
|
||||
Vendored
+113
-61
@@ -1,78 +1,130 @@
|
||||
/*
|
||||
* SULog.m
|
||||
* EyeTV
|
||||
*
|
||||
* Created by Uli Kusterer on 12/03/2009.
|
||||
* Copyright 2009 Elgato Systems GmbH. All rights reserved.
|
||||
*
|
||||
*/
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// Headers:
|
||||
// -----------------------------------------------------------------------------
|
||||
//
|
||||
// SULog.m
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Mayur Pawashe on 5/18/16.
|
||||
// Copyright © 2016 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#include "SULog.h"
|
||||
|
||||
#include <asl.h>
|
||||
#include <Availability.h>
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// Constants:
|
||||
// -----------------------------------------------------------------------------
|
||||
#if __MAC_OS_X_VERSION_MAX_ALLOWED >= 101200
|
||||
#include <os/log.h>
|
||||
#else
|
||||
|
||||
static NSString *const SULogFilePath = @"~/Library/Logs/SparkleUpdateLog.log";
|
||||
typedef struct os_log_s *os_log_t;
|
||||
#define os_log_create(subsystem, category) nil
|
||||
|
||||
#define os_log(log, format, ...)
|
||||
#define os_log_error(log, format, ...)
|
||||
|
||||
#endif
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
#import "SUOperatingSystem.h"
|
||||
|
||||
// For converting constants to string literals using the preprocessor
|
||||
#define STRINGIFY(x) #x
|
||||
#define TO_STRING(x) STRINGIFY(x)
|
||||
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// SUClearLog:
|
||||
// Erase the log at the start of an update. We don't want to litter the
|
||||
// user's hard disk with logging data that's mostly unused, so each app
|
||||
// should clear the log before it starts updating, so only the most recent
|
||||
// update is kept around.
|
||||
//
|
||||
// TAKES:
|
||||
// sender - Object that sent this message, typically of type X.
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
void SUClearLog(void)
|
||||
void SULog(SULogLevel level, NSString *format, ...)
|
||||
{
|
||||
FILE *logfile = fopen([[SULogFilePath stringByExpandingTildeInPath] fileSystemRepresentation], "w");
|
||||
if (logfile) {
|
||||
fclose(logfile);
|
||||
SULog(@"===== %@ =====", [[NSFileManager defaultManager] displayNameAtPath:[[NSBundle mainBundle] bundlePath]]);
|
||||
}
|
||||
}
|
||||
static aslclient client;
|
||||
static dispatch_queue_t queue;
|
||||
static dispatch_once_t onceToken;
|
||||
|
||||
static os_log_t logger;
|
||||
static BOOL hasOSLogging;
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// SULog:
|
||||
// Like NSLog, but logs to one specific log file. Each line is prefixed
|
||||
// with the current date and time, to help in regressing issues.
|
||||
//
|
||||
// TAKES:
|
||||
// format - NSLog/printf-style format string.
|
||||
// ... - More parameters depending on format string's contents.
|
||||
// -----------------------------------------------------------------------------
|
||||
dispatch_once(&onceToken, ^{
|
||||
NSBundle *mainBundle = [NSBundle mainBundle];
|
||||
|
||||
void SULog(NSString *format, ...)
|
||||
{
|
||||
static BOOL loggedYet = NO;
|
||||
if (!loggedYet) {
|
||||
loggedYet = YES;
|
||||
SUClearLog();
|
||||
hasOSLogging = [SUOperatingSystem isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){10, 12, 0}];
|
||||
#if __MAC_OS_X_VERSION_MAX_ALLOWED < 101200
|
||||
hasOSLogging = NO;
|
||||
#endif
|
||||
|
||||
if (hasOSLogging) {
|
||||
const char *subsystem = SPARKLE_BUNDLE_IDENTIFIER;
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wpartial-availability"
|
||||
// This creates a thread-safe object
|
||||
logger = os_log_create(subsystem, "Sparkle");
|
||||
#pragma clang diagnostic pop
|
||||
} else {
|
||||
uint32_t options = ASL_OPT_NO_DELAY;
|
||||
// Act the same way os_log() does; don't log to stderr if a terminal device is attached
|
||||
if (!isatty(STDERR_FILENO)) {
|
||||
options |= ASL_OPT_STDERR;
|
||||
}
|
||||
|
||||
NSString *displayName = [[NSFileManager defaultManager] displayNameAtPath:mainBundle.bundlePath];
|
||||
client = asl_open([displayName stringByAppendingString:@" [Sparkle]"].UTF8String, SPARKLE_BUNDLE_IDENTIFIER, options);
|
||||
queue = dispatch_queue_create(NULL, DISPATCH_QUEUE_SERIAL);
|
||||
}
|
||||
});
|
||||
|
||||
if (!hasOSLogging && client == NULL) {
|
||||
return;
|
||||
}
|
||||
|
||||
va_list ap;
|
||||
va_start(ap, format);
|
||||
NSString *theStr = [[NSString alloc] initWithFormat:format arguments:ap];
|
||||
NSLog(@"Sparkle: %@", theStr);
|
||||
|
||||
FILE *logfile = fopen([[SULogFilePath stringByExpandingTildeInPath] fileSystemRepresentation], "a");
|
||||
if (logfile) {
|
||||
theStr = [NSString stringWithFormat:@"%@: %@\n", [NSDate date], theStr];
|
||||
NSData *theData = [theStr dataUsingEncoding:NSUTF8StringEncoding];
|
||||
fwrite([theData bytes], 1, [theData length], logfile);
|
||||
fclose(logfile);
|
||||
}
|
||||
NSString *logMessage = [[NSString alloc] initWithFormat:format arguments:ap];
|
||||
va_end(ap);
|
||||
|
||||
// Use os_log if available (on 10.12+)
|
||||
if (hasOSLogging) {
|
||||
// We'll make all of our messages formatted as public; just don't log sensitive information.
|
||||
// Note we don't take advantage of info like the source line number because we wrap this macro inside our own function
|
||||
// And we don't really leverage of os_log's deferred formatting processing because we format the string before passing it in
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wpartial-availability"
|
||||
switch (level) {
|
||||
case SULogLevelDefault:
|
||||
// See docs for OS_LOG_TYPE_DEFAULT
|
||||
// By default, OS_LOG_TYPE_DEFAULT seems to be more noticable than OS_LOG_TYPE_INFO
|
||||
os_log(logger, "%{public}@", logMessage);
|
||||
break;
|
||||
case SULogLevelError:
|
||||
// See docs for OS_LOG_TYPE_ERROR
|
||||
os_log_error(logger, "%{public}@", logMessage);
|
||||
break;
|
||||
}
|
||||
#pragma clang diagnostic pop
|
||||
return;
|
||||
}
|
||||
|
||||
// Otherwise use ASL
|
||||
// Make sure we do not async, because if we async, the log may not be delivered deterministically
|
||||
dispatch_sync(queue, ^{
|
||||
aslmsg message = asl_new(ASL_TYPE_MSG);
|
||||
if (message == NULL) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (asl_set(message, ASL_KEY_MSG, logMessage.UTF8String) != 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
int levelSetResult;
|
||||
switch (level) {
|
||||
case SULogLevelDefault:
|
||||
// Just use one level below the error level
|
||||
levelSetResult = asl_set(message, ASL_KEY_LEVEL, TO_STRING(ASL_LEVEL_WARNING));
|
||||
break;
|
||||
case SULogLevelError:
|
||||
levelSetResult = asl_set(message, ASL_KEY_LEVEL, TO_STRING(ASL_LEVEL_ERR));
|
||||
break;
|
||||
}
|
||||
if (levelSetResult != 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
asl_send(client, message);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
Vendored
+8
@@ -7,6 +7,14 @@
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
#if __MAC_OS_X_VERSION_MAX_ALLOWED < 101000
|
||||
typedef struct {
|
||||
NSInteger majorVersion;
|
||||
NSInteger minorVersion;
|
||||
NSInteger patchVersion;
|
||||
} NSOperatingSystemVersion;
|
||||
#endif
|
||||
|
||||
@interface SUOperatingSystem : NSObject
|
||||
|
||||
+ (NSOperatingSystemVersion)operatingSystemVersion;
|
||||
|
||||
Vendored
+9
@@ -7,6 +7,15 @@
|
||||
|
||||
#import "SUOperatingSystem.h"
|
||||
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
|
||||
#if __MAC_OS_X_VERSION_MAX_ALLOWED < 101000
|
||||
@interface NSProcessInfo ()
|
||||
- (NSOperatingSystemVersion)operatingSystemVersion;
|
||||
@end
|
||||
#endif
|
||||
|
||||
@implementation SUOperatingSystem
|
||||
|
||||
+ (NSOperatingSystemVersion)operatingSystemVersion
|
||||
|
||||
Vendored
+6
-10
@@ -6,19 +6,15 @@
|
||||
// Copyright 2008 Andy Matuschak. All rights reserved.
|
||||
//
|
||||
|
||||
#ifndef SUPACKAGEINSTALLER_H
|
||||
#define SUPACKAGEINSTALLER_H
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "SUInstallerProtocol.h"
|
||||
|
||||
#import "SUUpdater.h"
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
#import "SUAppcast.h"
|
||||
#import "SUAppcastItem.h"
|
||||
#import "SUVersionComparisonProtocol.h"
|
||||
#import "SUPlainInstaller.h"
|
||||
@interface SUPackageInstaller : NSObject <SUInstallerProtocol>
|
||||
|
||||
- (instancetype)initWithPackagePath:(NSString *)packagePath installationPath:(NSString *)installationPath;
|
||||
|
||||
@interface SUPackageInstaller : SUPlainInstaller
|
||||
@end
|
||||
|
||||
#endif
|
||||
NS_ASSUME_NONNULL_END
|
||||
Vendored
+58
-18
@@ -7,35 +7,75 @@
|
||||
//
|
||||
|
||||
#import "SUPackageInstaller.h"
|
||||
#import <Cocoa/Cocoa.h>
|
||||
#import "SUConstants.h"
|
||||
#import "SUErrors.h"
|
||||
#import "SULog.h"
|
||||
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
|
||||
@interface SUPackageInstaller ()
|
||||
|
||||
@property (nonatomic, readonly, copy) NSString *packagePath;
|
||||
@property (nonatomic, readonly, copy) NSString *installationPath;
|
||||
|
||||
@end
|
||||
|
||||
@implementation SUPackageInstaller
|
||||
|
||||
+ (void)performInstallationToPath:(NSString *)installationPath fromPath:(NSString *)path host:(SUHost *)__unused host fileOperationToolPath:(NSString *)__unused fileOperationToolPath versionComparator:(id<SUVersionComparison>)__unused comparator completionHandler:(void (^)(NSError *))completionHandler
|
||||
static NSString *SUOpenUtilityPath = @"/usr/bin/open";
|
||||
|
||||
@synthesize packagePath = _packagePath;
|
||||
@synthesize installationPath = _installationPath;
|
||||
|
||||
- (instancetype)initWithPackagePath:(NSString *)packagePath installationPath:(NSString *)installationPath
|
||||
{
|
||||
self = [super init];
|
||||
if (self != nil) {
|
||||
_packagePath = [packagePath copy];
|
||||
_installationPath = [installationPath copy];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (BOOL)performInitialInstallation:(NSError * __autoreleasing *)error
|
||||
{
|
||||
if (![[NSFileManager defaultManager] fileExistsAtPath:SUOpenUtilityPath]) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingInstallerToolError userInfo:@{ NSLocalizedDescriptionKey: @"Couldn't find Apple's installer tool!" }];
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (BOOL)performFinalInstallationProgressBlock:(nullable void(^)(double))__unused cb error:(NSError *__autoreleasing*)error
|
||||
{
|
||||
// Run installer using the "open" command to ensure it is launched in front of current application.
|
||||
// -W = wait until the app has quit.
|
||||
// -n = Open another instance if already open.
|
||||
// -b = app bundle identifier
|
||||
NSString *command = @"/usr/bin/open";
|
||||
NSArray *args = @[@"-W", @"-n", @"-b", @"com.apple.installer", path];
|
||||
|
||||
if (![[NSFileManager defaultManager] fileExistsAtPath:command]) {
|
||||
NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingInstallerToolError userInfo:@{ NSLocalizedDescriptionKey: @"Couldn't find Apple's installer tool!" }];
|
||||
[self finishInstallationToPath:installationPath withResult:NO error:error completionHandler:completionHandler];
|
||||
return;
|
||||
}
|
||||
|
||||
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
|
||||
NSTask *installer = [NSTask launchedTaskWithLaunchPath:command arguments:args];
|
||||
NSArray *args = @[@"-W", @"-n", @"-b", @"com.apple.installer", self.packagePath];
|
||||
|
||||
// Known bug: if the installation fails or is canceled, Sparkle goes ahead and restarts, thinking everything is fine.
|
||||
@try {
|
||||
NSTask *installer = [NSTask launchedTaskWithLaunchPath:SUOpenUtilityPath arguments:args];
|
||||
[installer waitUntilExit];
|
||||
}
|
||||
@catch (NSException *exception) {
|
||||
SULog(SULogLevelError, @"Error: Failed to launch package installer: %@", exception);
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: @"Package installer failed to launch." }];
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
// Known bug: if the installation fails or is canceled, Sparkle goes ahead and restarts, thinking everything is fine.
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[self finishInstallationToPath:installationPath withResult:YES error:nil completionHandler:completionHandler];
|
||||
});
|
||||
});
|
||||
- (BOOL)canInstallSilently
|
||||
{
|
||||
return NO;
|
||||
}
|
||||
|
||||
@end
|
||||
Vendored
+9
-3
@@ -9,11 +9,17 @@
|
||||
#ifndef SUPIPEDUNARCHIVER_H
|
||||
#define SUPIPEDUNARCHIVER_H
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
#import "SUUnarchiver.h"
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "SUUnarchiverProtocol.h"
|
||||
|
||||
@interface SUPipedUnarchiver : SUUnarchiver
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface SUPipedUnarchiver : NSObject <SUUnarchiverProtocol>
|
||||
|
||||
- (instancetype)initWithArchivePath:(NSString *)archivePath;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
#endif
|
||||
Vendored
+75
-87
@@ -7,38 +7,55 @@
|
||||
//
|
||||
|
||||
#import "SUPipedUnarchiver.h"
|
||||
#import "SUUnarchiver_Private.h"
|
||||
#import "SUUnarchiverNotifier.h"
|
||||
#import "SULog.h"
|
||||
#import "SUErrors.h"
|
||||
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
|
||||
@interface SUPipedUnarchiver ()
|
||||
|
||||
@property (nonatomic, copy, readonly) NSString *archivePath;
|
||||
|
||||
@end
|
||||
|
||||
@implementation SUPipedUnarchiver
|
||||
|
||||
+ (SEL)selectorConformingToTypeOfPath:(NSString *)path
|
||||
@synthesize archivePath = _archivePath;
|
||||
|
||||
+ (nullable NSArray <NSString *> *)commandAndArgumentsConformingToTypeOfPath:(NSString *)path
|
||||
{
|
||||
static NSDictionary *typeSelectorDictionary;
|
||||
if (!typeSelectorDictionary)
|
||||
typeSelectorDictionary = @{ @".zip": @"extractZIP",
|
||||
@".tar": @"extractTAR",
|
||||
@".tar.gz": @"extractTGZ",
|
||||
@".tgz": @"extractTGZ",
|
||||
@".tar.bz2": @"extractTBZ",
|
||||
@".tbz": @"extractTBZ",
|
||||
@".tar.xz": @"extractTXZ",
|
||||
@".txz": @"extractTXZ",
|
||||
@".tar.lzma": @"extractTXZ"};
|
||||
|
||||
NSArray <NSString *> *extractTGZ = @[@"/usr/bin/tar", @"-zxC"];
|
||||
NSArray <NSString *> *extractTBZ = @[@"/usr/bin/tar", @"-jxC"];
|
||||
NSArray <NSString *> *extractTXZ = extractTGZ;
|
||||
|
||||
NSDictionary <NSString *, NSArray<NSString *> *> *extractCommandDictionary =
|
||||
@{
|
||||
@".zip" : @[@"/usr/bin/ditto", @"-x",@"-k",@"-"],
|
||||
@".tar" : @[@"/usr/bin/tar", @"-xC"],
|
||||
@".tar.gz" : extractTGZ,
|
||||
@".tgz" : extractTGZ,
|
||||
@".tar.bz2" : extractTBZ,
|
||||
@".tbz" : extractTBZ,
|
||||
@".tar.xz" : extractTXZ,
|
||||
@".txz" : extractTXZ,
|
||||
@".tar.lzma" : extractTXZ
|
||||
};
|
||||
|
||||
NSString *lastPathComponent = [path lastPathComponent];
|
||||
for (NSString *currentType in typeSelectorDictionary)
|
||||
{
|
||||
NSString *value = [typeSelectorDictionary objectForKey:currentType];
|
||||
assert(value);
|
||||
|
||||
if ([currentType length] > [lastPathComponent length]) continue;
|
||||
if ([[lastPathComponent substringFromIndex:[lastPathComponent length] - [currentType length]] isEqualToString:currentType]) {
|
||||
return NSSelectorFromString(value);
|
||||
for (NSString *currentType in extractCommandDictionary)
|
||||
{
|
||||
if ([lastPathComponent hasSuffix:currentType]) {
|
||||
return [extractCommandDictionary objectForKey:currentType];
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
return nil;
|
||||
}
|
||||
|
||||
+ (BOOL)canUnarchivePath:(NSString *)path
|
||||
{
|
||||
return ([self commandAndArgumentsConformingToTypeOfPath:path] != nil);
|
||||
}
|
||||
|
||||
+ (BOOL)unsafeIfArchiveIsNotValidated
|
||||
@@ -46,35 +63,50 @@
|
||||
return NO;
|
||||
}
|
||||
|
||||
- (void)start
|
||||
- (instancetype)initWithArchivePath:(NSString *)archivePath
|
||||
{
|
||||
[NSThread detachNewThreadSelector:[[self class] selectorConformingToTypeOfPath:self.archivePath] toTarget:self withObject:nil];
|
||||
self = [super init];
|
||||
if (self != nil) {
|
||||
_archivePath = [archivePath copy];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
+ (BOOL)canUnarchivePath:(NSString *)path
|
||||
- (void)unarchiveWithCompletionBlock:(void (^)(NSError * _Nullable))completionBlock progressBlock:(void (^ _Nullable)(double))progressBlock
|
||||
{
|
||||
return ([self selectorConformingToTypeOfPath:path] != nil);
|
||||
NSArray <NSString *> *commandAndArguments = [[self class] commandAndArgumentsConformingToTypeOfPath:self.archivePath];
|
||||
assert(commandAndArguments != nil);
|
||||
|
||||
NSString *command = commandAndArguments.firstObject;
|
||||
assert(command != nil);
|
||||
|
||||
NSArray <NSString *> *arguments = [commandAndArguments subarrayWithRange:NSMakeRange(1, commandAndArguments.count - 1)];
|
||||
|
||||
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
|
||||
SUUnarchiverNotifier *notifier = [[SUUnarchiverNotifier alloc] initWithCompletionBlock:completionBlock progressBlock:progressBlock];
|
||||
[self extractArchivePipingDataToCommand:command arguments:arguments notifier:notifier];
|
||||
});
|
||||
}
|
||||
|
||||
// This method abstracts the types that use a command line tool piping data from stdin.
|
||||
- (void)extractArchivePipingDataToCommand:(NSString *)command args:(NSArray*)args
|
||||
- (void)extractArchivePipingDataToCommand:(NSString *)command arguments:(NSArray*)args notifier:(SUUnarchiverNotifier *)notifier
|
||||
{
|
||||
// *** GETS CALLED ON NON-MAIN THREAD!!!
|
||||
@autoreleasepool {
|
||||
|
||||
NSError *error = nil;
|
||||
NSString *destination = [self.archivePath stringByDeletingLastPathComponent];
|
||||
|
||||
SULog(@"Extracting using '%@' '%@' < '%@' '%@'", command, [args componentsJoinedByString:@"' '"], self.archivePath, destination);
|
||||
|
||||
SULog(SULogLevelDefault, @"Extracting using '%@' '%@' < '%@' '%@'", command, [args componentsJoinedByString:@"' '"], self.archivePath, destination);
|
||||
|
||||
// Get the file size.
|
||||
NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:self.archivePath error:nil];
|
||||
NSUInteger expectedLength = [[attributes objectForKey:NSFileSize] unsignedIntegerValue];
|
||||
if (expectedLength > 0) {
|
||||
NSFileHandle *archiveInput = [NSFileHandle fileHandleForReadingAtPath:self.archivePath];
|
||||
|
||||
|
||||
NSPipe *pipe = [NSPipe pipe];
|
||||
NSFileHandle *archiveOutput = [pipe fileHandleForWriting];
|
||||
|
||||
|
||||
NSTask *task = [[NSTask alloc] init];
|
||||
[task setStandardInput:[pipe fileHandleForReading]];
|
||||
[task setStandardError:[NSFileHandle fileHandleWithStandardError]];
|
||||
@@ -82,7 +114,7 @@
|
||||
[task setLaunchPath:command];
|
||||
[task setArguments:[args arrayByAddingObject:destination]];
|
||||
[task launch];
|
||||
|
||||
|
||||
NSUInteger bytesRead = 0;
|
||||
do {
|
||||
NSData *data = [archiveInput readDataOfLength:256*1024];
|
||||
@@ -92,76 +124,32 @@
|
||||
}
|
||||
bytesRead += len;
|
||||
[archiveOutput writeData:data];
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[self notifyDelegateOfProgress:(double)bytesRead / (double)expectedLength];
|
||||
});
|
||||
[notifier notifyProgress:(double)bytesRead / (double)expectedLength];
|
||||
}
|
||||
while(bytesRead < expectedLength);
|
||||
|
||||
[archiveOutput closeFile];
|
||||
|
||||
|
||||
[task waitUntilExit];
|
||||
|
||||
if ([task terminationStatus] == 0) {
|
||||
if (bytesRead == expectedLength) {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[self notifyDelegateOfSuccess];
|
||||
});
|
||||
[notifier notifySuccess];
|
||||
return;
|
||||
} else {
|
||||
SULog(@"Extraction failed, command '%@' got only %ld of %ld bytes", command, (long)bytesRead, (long)expectedLength);
|
||||
error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Extraction failed, command '%@' got only %ld of %ld bytes", command, (long)bytesRead, (long)expectedLength]}];
|
||||
|
||||
}
|
||||
} else {
|
||||
SULog(@"Extraction failed, command '%@' returned %d", command, [task terminationStatus]);
|
||||
error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Extraction failed, command '%@' returned %d", command, [task terminationStatus]]}];
|
||||
}
|
||||
} else {
|
||||
SULog(@"Extraction failed, archive '%@' is empty", self.archivePath);
|
||||
error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Extraction failed, archive '%@' is empty", self.archivePath]}];
|
||||
}
|
||||
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[self notifyDelegateOfFailure];
|
||||
});
|
||||
[notifier notifyFailureWithError:error];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)extractTAR
|
||||
{
|
||||
// *** GETS CALLED ON NON-MAIN THREAD!!!
|
||||
|
||||
[self extractArchivePipingDataToCommand:@"/usr/bin/tar" args:@[@"-xC"]];
|
||||
}
|
||||
|
||||
- (void)extractTGZ
|
||||
{
|
||||
// *** GETS CALLED ON NON-MAIN THREAD!!!
|
||||
|
||||
[self extractArchivePipingDataToCommand:@"/usr/bin/tar" args:@[@"-zxC"]];
|
||||
}
|
||||
|
||||
- (void)extractTBZ
|
||||
{
|
||||
// *** GETS CALLED ON NON-MAIN THREAD!!!
|
||||
|
||||
[self extractArchivePipingDataToCommand:@"/usr/bin/tar" args:@[@"-jxC"]];
|
||||
}
|
||||
|
||||
- (void)extractZIP
|
||||
{
|
||||
// *** GETS CALLED ON NON-MAIN THREAD!!!
|
||||
|
||||
[self extractArchivePipingDataToCommand:@"/usr/bin/ditto" args:@[@"-x",@"-k",@"-"]];
|
||||
}
|
||||
|
||||
- (void)extractTXZ
|
||||
{
|
||||
// *** GETS CALLED ON NON-MAIN THREAD!!!
|
||||
|
||||
[self extractArchivePipingDataToCommand:@"/usr/bin/tar" args:@[@"-zxC"]];
|
||||
}
|
||||
|
||||
+ (void)load
|
||||
{
|
||||
[self registerImplementation:self];
|
||||
}
|
||||
- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], self.archivePath]; }
|
||||
|
||||
@end
|
||||
Vendored
+11
-13
@@ -6,25 +6,23 @@
|
||||
// Copyright 2008 Andy Matuschak. All rights reserved.
|
||||
//
|
||||
|
||||
#ifndef SUPLAININSTALLER_H
|
||||
#define SUPLAININSTALLER_H
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "SUInstallerProtocol.h"
|
||||
|
||||
#import "SUUpdater.h"
|
||||
|
||||
#import "SUAppcast.h"
|
||||
#import "SUAppcastItem.h"
|
||||
#import "SUVersionComparisonProtocol.h"
|
||||
#import "SUInstaller.h"
|
||||
#import "SUVersionComparisonProtocol.h"
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@class SUHost;
|
||||
|
||||
@interface SUPlainInstaller : SUInstaller
|
||||
@interface SUPlainInstaller : NSObject <SUInstallerProtocol>
|
||||
|
||||
+ (void)performInstallationToPath:(NSString *)installationPath fromPath:(NSString *)path host:(SUHost *)host fileOperationToolPath:(NSString *)fileOperationToolPath versionComparator:(id<SUVersionComparison>)comparator completionHandler:(void (^)(NSError *))completionHandler;
|
||||
/*!
|
||||
@param host The current (old) bundle host
|
||||
@param bundlePath The path to the new bundle that will be installed.
|
||||
@param installationPath The path the new bundlePath will be installed to.
|
||||
@param fileOperationToolPath The path to the file operation tool for authorized operations.
|
||||
*/
|
||||
- (instancetype)initWithHost:(SUHost *)host bundlePath:(NSString *)bundlePath installationPath:(NSString *)installationPath fileOperationToolPath:(NSString *)fileOperationToolPath;
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
NS_ASSUME_NONNULL_END
|
||||
Vendored
+139
-63
@@ -7,178 +7,254 @@
|
||||
//
|
||||
|
||||
#import "SUPlainInstaller.h"
|
||||
#import "SUVersionComparisonProtocol.h"
|
||||
#import "SUStandardVersionComparator.h"
|
||||
#import "SUFileManager.h"
|
||||
#import "SUCodeSigningVerifier.h"
|
||||
#import "SUConstants.h"
|
||||
#import "SUHost.h"
|
||||
#import "SULog.h"
|
||||
#import "SUErrors.h"
|
||||
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
|
||||
@interface SUPlainInstaller ()
|
||||
|
||||
@property (nonatomic, readonly) SUHost *host;
|
||||
@property (nonatomic, copy, readonly) NSString *bundlePath;
|
||||
@property (nonatomic, copy, readonly) NSString *installationPath;
|
||||
@property (nonatomic, copy, readonly) NSString *fileOperationToolPath;
|
||||
|
||||
@end
|
||||
|
||||
@implementation SUPlainInstaller
|
||||
|
||||
@synthesize host = _host;
|
||||
@synthesize bundlePath = _bundlePath;
|
||||
@synthesize installationPath = _installationPath;
|
||||
@synthesize fileOperationToolPath = _fileOperationToolPath;
|
||||
|
||||
- (instancetype)initWithHost:(SUHost *)host bundlePath:(NSString *)bundlePath installationPath:(NSString *)installationPath fileOperationToolPath:(NSString *)fileOperationToolPath
|
||||
{
|
||||
self = [super init];
|
||||
if (self != nil) {
|
||||
_host = host;
|
||||
_bundlePath = [bundlePath copy];
|
||||
_installationPath = [installationPath copy];
|
||||
_fileOperationToolPath = [fileOperationToolPath copy];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
// Returns the bundle version from the specified host that is appropriate to use as a filename, or nil if we're unable to retrieve one
|
||||
+ (NSString *)bundleVersionAppropriateForFilenameFromHost:(SUHost *)host
|
||||
- (NSString *)bundleVersionAppropriateForFilenameFromHost:(SUHost *)host
|
||||
{
|
||||
NSString *bundleVersion = [host objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleVersionKey];
|
||||
NSString *trimmedVersion = @"";
|
||||
|
||||
|
||||
if (bundleVersion != nil) {
|
||||
NSMutableCharacterSet *validCharacters = [NSMutableCharacterSet alphanumericCharacterSet];
|
||||
[validCharacters formUnionWithCharacterSet:[NSCharacterSet characterSetWithCharactersInString:@".-()"]];
|
||||
|
||||
|
||||
trimmedVersion = [bundleVersion stringByTrimmingCharactersInSet:[validCharacters invertedSet]];
|
||||
}
|
||||
|
||||
|
||||
return trimmedVersion.length > 0 ? trimmedVersion : nil;
|
||||
}
|
||||
|
||||
+ (BOOL)performInstallationToURL:(NSURL *)installationURL fromUpdateAtURL:(NSURL *)newURL withHost:(SUHost *)host fileOperationToolPath:(NSString *)fileOperationToolPath error:(NSError * __autoreleasing *)error
|
||||
- (BOOL)performInstallationToURL:(NSURL *)installationURL fromUpdateAtURL:(NSURL *)newURL withHost:(SUHost *)host fileOperationToolPath:(NSString *)fileOperationToolPath progressBlock:(nullable void(^)(double))progress error:(NSError * __autoreleasing *)error
|
||||
{
|
||||
if (installationURL == nil || newURL == nil) {
|
||||
// this really shouldn't happen but just in case
|
||||
SULog(@"Failed to perform installation because either installation URL (%@) or new URL (%@) is nil", installationURL, newURL);
|
||||
SULog(SULogLevelError, @"Failed to perform installation because either installation URL (%@) or new URL (%@) is nil", installationURL, newURL);
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: @"Failed to perform installation because the paths to install at and from are not valid" }];
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
if (progress) {
|
||||
progress(1/10.0);
|
||||
}
|
||||
|
||||
SUFileManager *fileManager = [SUFileManager fileManagerWithAuthorizationToolPath:fileOperationToolPath];
|
||||
|
||||
|
||||
// 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];
|
||||
NSString *preferredName = [installationURL.lastPathComponent.stringByDeletingPathExtension stringByAppendingString:@" (Incomplete Update)"];
|
||||
NSURL *installationDirectory = installationURL.URLByDeletingLastPathComponent;
|
||||
NSURL *tempNewDirectoryURL = [fileManager makeTemporaryDirectoryWithPreferredName:preferredName appropriateForDirectoryURL:installationDirectory error:error];
|
||||
if (tempNewDirectoryURL == nil) {
|
||||
SULog(@"Failed to make new temp directory");
|
||||
SULog(SULogLevelError, @"Failed to make new temp directory");
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
if (progress) {
|
||||
progress(2/10.0);
|
||||
}
|
||||
|
||||
// Move the new app to our temporary directory
|
||||
NSString *newURLLastPathComponent = newURL.lastPathComponent;
|
||||
NSURL *newTempURL = [tempNewDirectoryURL URLByAppendingPathComponent:newURLLastPathComponent];
|
||||
if (![fileManager moveItemAtURL:newURL toURL:newTempURL error:error]) {
|
||||
SULog(@"Failed to move the new app from %@ to its temp directory at %@", newURL.path, newTempURL.path);
|
||||
SULog(SULogLevelError, @"Failed to move the new app from %@ to its temp directory at %@", newURL.path, newTempURL.path);
|
||||
[fileManager removeItemAtURL:tempNewDirectoryURL error:NULL];
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
if (progress) {
|
||||
progress(3/10.0);
|
||||
}
|
||||
|
||||
// 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
|
||||
|
||||
|
||||
NSError *quarantineError = nil;
|
||||
if (![fileManager releaseItemFromQuarantineAtRootURL:newTempURL error:&quarantineError]) {
|
||||
// Not big enough of a deal to fail the entire installation
|
||||
SULog(@"Failed to release quarantine at %@ with error %@", newTempURL.path, quarantineError);
|
||||
SULog(SULogLevelError, @"Failed to release quarantine at %@ with error %@", newTempURL.path, quarantineError);
|
||||
}
|
||||
|
||||
|
||||
if (progress) {
|
||||
progress(4/10.0);
|
||||
}
|
||||
|
||||
NSURL *oldURL = [NSURL fileURLWithPath:host.bundlePath];
|
||||
if (oldURL == nil) {
|
||||
// this really shouldn't happen but just in case
|
||||
SULog(@"Failed to construct URL from bundle path: %@", host.bundlePath);
|
||||
SULog(SULogLevelError, @"Failed to construct URL from bundle path: %@", host.bundlePath);
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: @"Failed to perform installation because a path could not be constructed for the old installation" }];
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
if (![fileManager changeOwnerAndGroupOfItemAtRootURL:newTempURL toMatchURL:oldURL error:error]) {
|
||||
// But this is big enough of a deal to fail
|
||||
SULog(@"Failed to change owner and group of new app at %@ to match old app at %@", newTempURL.path, oldURL.path);
|
||||
SULog(SULogLevelError, @"Failed to change owner and group of new app at %@ to match old app at %@", newTempURL.path, oldURL.path);
|
||||
[fileManager removeItemAtURL:tempNewDirectoryURL error:NULL];
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
if (progress) {
|
||||
progress(5/10.0);
|
||||
}
|
||||
|
||||
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);
|
||||
SULog(SULogLevelError, @"Failed to update modification and access time of new app at %@", newTempURL.path);
|
||||
}
|
||||
|
||||
|
||||
if (progress) {
|
||||
progress(6/10.0);
|
||||
}
|
||||
|
||||
// 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) {
|
||||
NSString *oldBundleVersion = [self bundleVersionAppropriateForFilenameFromHost:host];
|
||||
|
||||
|
||||
oldDestinationName = [oldURL.lastPathComponent.stringByDeletingPathExtension stringByAppendingFormat:@" (%@)", oldBundleVersion != nil ? oldBundleVersion : @"old"];
|
||||
} else {
|
||||
oldDestinationName = oldURL.lastPathComponent.stringByDeletingPathExtension;
|
||||
}
|
||||
|
||||
|
||||
NSString *oldURLExtension = oldURL.pathExtension;
|
||||
NSString *oldDestinationNameWithPathExtension = [oldDestinationName stringByAppendingPathExtension:oldURLExtension];
|
||||
|
||||
NSURL *oldURLDirectory = oldURL.URLByDeletingLastPathComponent;
|
||||
|
||||
// Create a temporary directory for our old app that resides on its volume
|
||||
NSURL *tempOldDirectoryURL = [fileManager makeTemporaryDirectoryWithPreferredName:oldDestinationName appropriateForDirectoryURL:oldURL.URLByDeletingLastPathComponent error:error];
|
||||
NSURL *tempOldDirectoryURL = [fileManager makeTemporaryDirectoryWithPreferredName:oldDestinationName appropriateForDirectoryURL:oldURLDirectory error:error];
|
||||
if (tempOldDirectoryURL == nil) {
|
||||
SULog(@"Failed to create temporary directory for old app at %@", oldURL.path);
|
||||
SULog(SULogLevelError, @"Failed to create temporary directory for old app at %@", oldURL.path);
|
||||
[fileManager removeItemAtURL:tempNewDirectoryURL error:NULL];
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
if (progress) {
|
||||
progress(7/10.0);
|
||||
}
|
||||
|
||||
// Move the old app to the temporary directory
|
||||
NSURL *oldTempURL = [tempOldDirectoryURL URLByAppendingPathComponent:oldDestinationNameWithPathExtension];
|
||||
if (![fileManager moveItemAtURL:oldURL toURL:oldTempURL error:error]) {
|
||||
SULog(@"Failed to move the old app at %@ to a temporary location at %@", oldURL.path, oldTempURL.path);
|
||||
|
||||
SULog(SULogLevelError, @"Failed to move the old app at %@ to a temporary location at %@", oldURL.path, oldTempURL.path);
|
||||
|
||||
// Just forget about our updated app on failure
|
||||
[fileManager removeItemAtURL:tempNewDirectoryURL error:NULL];
|
||||
[fileManager removeItemAtURL:tempOldDirectoryURL error:NULL];
|
||||
|
||||
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
if (progress) {
|
||||
progress(8/10.0);
|
||||
}
|
||||
|
||||
// Move the new app to its final destination
|
||||
if (![fileManager moveItemAtURL:newTempURL toURL:installationURL error:error]) {
|
||||
SULog(@"Failed to move new app at %@ to final destination %@", newTempURL.path, installationURL.path);
|
||||
|
||||
SULog(SULogLevelError, @"Failed to move new app at %@ to final destination %@", newTempURL.path, installationURL.path);
|
||||
|
||||
// Forget about our updated app on failure
|
||||
[fileManager removeItemAtURL:tempNewDirectoryURL error:NULL];
|
||||
|
||||
|
||||
// Attempt to restore our old app back the way it was on failure
|
||||
[fileManager moveItemAtURL:oldTempURL toURL:oldURL error:NULL];
|
||||
[fileManager removeItemAtURL:tempOldDirectoryURL error:NULL];
|
||||
|
||||
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
if (progress) {
|
||||
progress(9/10.0);
|
||||
}
|
||||
|
||||
// From here on out, we don't really need to bring up authorization if we haven't done so prior
|
||||
SUFileManager *constrainedFileManager = [fileManager fileManagerByPreservingAuthorizationRights];
|
||||
|
||||
// Cleanup: move the old app to the trash
|
||||
NSError *trashError = nil;
|
||||
if (![constrainedFileManager moveItemAtURLToTrash:oldTempURL error:&trashError]) {
|
||||
SULog(@"Failed to move %@ to trash with error %@", oldTempURL, trashError);
|
||||
}
|
||||
|
||||
|
||||
// Cleanup
|
||||
[constrainedFileManager removeItemAtURL:tempOldDirectoryURL error:NULL];
|
||||
|
||||
[constrainedFileManager removeItemAtURL:tempNewDirectoryURL error:NULL];
|
||||
|
||||
|
||||
if (progress) {
|
||||
progress(10/10.0);
|
||||
}
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
+ (void)performInstallationToPath:(NSString *)installationPath fromPath:(NSString *)path host:(SUHost *)host fileOperationToolPath:(NSString *)fileOperationToolPath versionComparator:(id<SUVersionComparison>)comparator completionHandler:(void (^)(NSError *))completionHandler
|
||||
- (BOOL)performInitialInstallation:(NSError * __autoreleasing *)error
|
||||
{
|
||||
SUParameterAssert(host);
|
||||
|
||||
BOOL allowDowngrades = SPARKLE_AUTOMATED_DOWNGRADES;
|
||||
|
||||
// Prevent malicious downgrades
|
||||
if (!allowDowngrades) {
|
||||
if ([comparator compareVersion:[host version] toVersion:[[NSBundle bundleWithPath:path] objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleVersionKey]] == NSOrderedDescending) {
|
||||
NSString *errorMessage = [NSString stringWithFormat:@"For security reasons, updates that downgrade version of the application are not allowed. Refusing to downgrade app from version %@ to %@. Aborting update.", [host version], [[NSBundle bundleWithPath:path] objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleVersionKey]];
|
||||
NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUDowngradeError userInfo:@{ NSLocalizedDescriptionKey: errorMessage }];
|
||||
[self finishInstallationToPath:installationPath withResult:NO error:error completionHandler:completionHandler];
|
||||
return;
|
||||
NSString *hostVersion = [self.host version];
|
||||
|
||||
NSBundle *bundle = [NSBundle bundleWithPath:self.bundlePath];
|
||||
SUHost *updateHost = [[SUHost alloc] initWithBundle:bundle];
|
||||
NSString *updateVersion = [updateHost objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleVersionKey];
|
||||
|
||||
id<SUVersionComparison> comparator = [[SUStandardVersionComparator alloc] init];
|
||||
if (!updateVersion || [comparator compareVersion:hostVersion toVersion:updateVersion] == NSOrderedDescending) {
|
||||
if (error != NULL) {
|
||||
NSString *errorMessage = [NSString stringWithFormat:@"For security reasons, updates that downgrade version of the application are not allowed. Refusing to downgrade app from version %@ to %@. Aborting update.", hostVersion, updateVersion];
|
||||
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUDowngradeError userInfo:@{ NSLocalizedDescriptionKey: errorMessage }];
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
}
|
||||
return YES;
|
||||
}
|
||||
|
||||
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
|
||||
NSError *error = nil;
|
||||
BOOL result = [self performInstallationToURL:[NSURL fileURLWithPath:installationPath] fromUpdateAtURL:[NSURL fileURLWithPath:path] withHost:host fileOperationToolPath:fileOperationToolPath error:&error];
|
||||
- (BOOL)performFinalInstallationProgressBlock:(nullable void(^)(double))cb error:(NSError *__autoreleasing*)error
|
||||
{
|
||||
return [self performInstallationToURL:[NSURL fileURLWithPath:self.installationPath] fromUpdateAtURL:[NSURL fileURLWithPath:self.bundlePath] withHost:self.host fileOperationToolPath:self.fileOperationToolPath progressBlock:cb error:error];
|
||||
}
|
||||
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[self finishInstallationToPath:installationPath withResult:result error:error completionHandler:completionHandler];
|
||||
});
|
||||
});
|
||||
- (BOOL)canInstallSilently
|
||||
{
|
||||
return YES;
|
||||
}
|
||||
|
||||
@end
|
||||
Vendored
-1
@@ -9,7 +9,6 @@
|
||||
#ifndef SUPROBINGUPDATEDRIVER_H
|
||||
#define SUPROBINGUPDATEDRIVER_H
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
#import "SUBasicUpdateDriver.h"
|
||||
|
||||
// This replaces the old SUStatusChecker.
|
||||
|
||||
Vendored
+6
-3
@@ -7,7 +7,8 @@
|
||||
//
|
||||
|
||||
#import "SUProbingUpdateDriver.h"
|
||||
#import "SUUpdater.h"
|
||||
#import "SUUpdaterPrivate.h"
|
||||
#import "SUUpdaterDelegate.h"
|
||||
|
||||
@implementation SUProbingUpdateDriver
|
||||
|
||||
@@ -15,7 +16,8 @@
|
||||
|
||||
- (void)didFindValidUpdate
|
||||
{
|
||||
id<SUUpdaterDelegate> updaterDelegate = [self.updater delegate];
|
||||
id<SUUpdaterPrivate> updater = self.updater;
|
||||
id<SUUpdaterDelegate> updaterDelegate = [updater delegate];
|
||||
|
||||
if ([updaterDelegate respondsToSelector:@selector(updater:didFindValidUpdate:)])
|
||||
[updaterDelegate updater:self.updater didFindValidUpdate:self.updateItem];
|
||||
@@ -26,7 +28,8 @@
|
||||
|
||||
- (void)didNotFindUpdate
|
||||
{
|
||||
id<SUUpdaterDelegate> updaterDelegate = [self.updater delegate];
|
||||
id<SUUpdaterPrivate> updater = self.updater;
|
||||
id<SUUpdaterDelegate> updaterDelegate = [updater delegate];
|
||||
|
||||
if ([updaterDelegate respondsToSelector:@selector(updaterDidNotFindUpdate:)]) {
|
||||
[updaterDelegate updaterDidNotFindUpdate:self.updater];
|
||||
|
||||
Vendored
-1
@@ -9,7 +9,6 @@
|
||||
#ifndef SUSCHEDULEDUPDATEDRIVER_H
|
||||
#define SUSCHEDULEDUPDATEDRIVER_H
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
#import "SUUIBasedUpdateDriver.h"
|
||||
|
||||
@interface SUScheduledUpdateDriver : SUUIBasedUpdateDriver
|
||||
|
||||
Vendored
+13
-23
@@ -7,21 +7,22 @@
|
||||
//
|
||||
|
||||
#import "SUScheduledUpdateDriver.h"
|
||||
#import "SUUpdater.h"
|
||||
|
||||
#import "SUAppcast.h"
|
||||
#import "SUAppcastItem.h"
|
||||
#import "SUVersionComparisonProtocol.h"
|
||||
#import "SUUpdaterPrivate.h"
|
||||
#import "SUUpdaterDelegate.h"
|
||||
|
||||
@interface SUScheduledUpdateDriver ()
|
||||
|
||||
@property (assign) BOOL showErrors;
|
||||
|
||||
@end
|
||||
|
||||
@implementation SUScheduledUpdateDriver
|
||||
|
||||
@synthesize showErrors;
|
||||
- (instancetype)initWithUpdater:(id<SUUpdaterPrivate>)anUpdater
|
||||
{
|
||||
if ((self = [super initWithUpdater:anUpdater])) {
|
||||
self.showErrors = NO;
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)didFindValidUpdate
|
||||
{
|
||||
@@ -31,7 +32,8 @@
|
||||
|
||||
- (void)didNotFindUpdate
|
||||
{
|
||||
id<SUUpdaterDelegate> updaterDelegate = [self.updater delegate];
|
||||
id<SUUpdaterPrivate> updater = self.updater;
|
||||
id<SUUpdaterDelegate> updaterDelegate = [updater delegate];
|
||||
|
||||
if ([updaterDelegate respondsToSelector:@selector(updaterDidNotFindUpdate:)]) {
|
||||
[updaterDelegate updaterDidNotFindUpdate:self.updater];
|
||||
@@ -41,20 +43,8 @@
|
||||
[self abortUpdate]; // Don't tell the user that no update was found; this was a scheduled update.
|
||||
}
|
||||
|
||||
- (void)abortUpdateWithError:(NSError *)error
|
||||
{
|
||||
if (self.showErrors) {
|
||||
[super abortUpdateWithError:error];
|
||||
} else {
|
||||
// Call delegate separately here because otherwise it won't know we stopped.
|
||||
// Normally this gets called by the superclass
|
||||
id<SUUpdaterDelegate> updaterDelegate = [self.updater delegate];
|
||||
if ([updaterDelegate respondsToSelector:@selector(updater:didAbortWithError:)]) {
|
||||
[updaterDelegate updater:self.updater didAbortWithError:error];
|
||||
}
|
||||
|
||||
[self abortUpdate];
|
||||
}
|
||||
- (BOOL)shouldDisableKeyboardShortcutForInstallButton {
|
||||
return YES;
|
||||
}
|
||||
|
||||
@end
|
||||
+10
@@ -17,6 +17,8 @@
|
||||
#import "SUExport.h"
|
||||
#import "SUVersionComparisonProtocol.h"
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
/*!
|
||||
Sparkle's default version comparator.
|
||||
|
||||
@@ -26,8 +28,15 @@
|
||||
*/
|
||||
SU_EXPORT @interface SUStandardVersionComparator : NSObject <SUVersionComparison>
|
||||
|
||||
/*!
|
||||
Initializes a new instance of the standard version comparator.
|
||||
*/
|
||||
- (instancetype)init;
|
||||
|
||||
/*!
|
||||
Returns a singleton instance of the comparator.
|
||||
|
||||
It is usually preferred to alloc/init new a comparator instead.
|
||||
*/
|
||||
+ (SUStandardVersionComparator *)defaultComparator;
|
||||
|
||||
@@ -39,4 +48,5 @@ SU_EXPORT @interface SUStandardVersionComparator : NSObject <SUVersionComparison
|
||||
- (NSComparisonResult)compareVersion:(NSString *)versionA toVersion:(NSString *)versionB;
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
#endif
|
||||
+11
-6
@@ -6,21 +6,26 @@
|
||||
// Copyright 2007 Andy Matuschak. All rights reserved.
|
||||
//
|
||||
|
||||
#import "SUUpdater.h"
|
||||
|
||||
#import "SUAppcast.h"
|
||||
#import "SUAppcastItem.h"
|
||||
#import "SUVersionComparisonProtocol.h"
|
||||
#import "SUStandardVersionComparator.h"
|
||||
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
|
||||
@implementation SUStandardVersionComparator
|
||||
|
||||
- (instancetype)init
|
||||
{
|
||||
return [super init];
|
||||
}
|
||||
|
||||
+ (SUStandardVersionComparator *)defaultComparator
|
||||
{
|
||||
static SUStandardVersionComparator *defaultComparator = nil;
|
||||
if (defaultComparator == nil) {
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
defaultComparator = [[SUStandardVersionComparator alloc] init];
|
||||
}
|
||||
});
|
||||
return defaultComparator;
|
||||
}
|
||||
|
||||
|
||||
Vendored
+9
-9
@@ -1,9 +1,9 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="5056" systemVersion="13D65" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none">
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="11542" systemVersion="16G29" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none">
|
||||
<dependencies>
|
||||
<deployment defaultVersion="1070" identifier="macosx"/>
|
||||
<development version="5100" identifier="xcode"/>
|
||||
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="5056"/>
|
||||
<deployment identifier="macosx"/>
|
||||
<development version="7000" identifier="xcode"/>
|
||||
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="11542"/>
|
||||
</dependencies>
|
||||
<objects>
|
||||
<customObject id="-2" userLabel="File's Owner" customClass="SUStatusController">
|
||||
@@ -15,8 +15,8 @@
|
||||
</connections>
|
||||
</customObject>
|
||||
<customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/>
|
||||
<customObject id="-3" userLabel="Application"/>
|
||||
<window title="Set in Code" allowsToolTipsWhenApplicationIsInactive="NO" autorecalculatesKeyViewLoop="NO" releasedWhenClosed="NO" visibleAtLaunch="NO" animationBehavior="default" id="5" userLabel="Window">
|
||||
<customObject id="-3" userLabel="Application" customClass="NSObject"/>
|
||||
<window identifier="SUStatus" title="Set in Code" allowsToolTipsWhenApplicationIsInactive="NO" autorecalculatesKeyViewLoop="NO" releasedWhenClosed="NO" visibleAtLaunch="NO" animationBehavior="default" id="5" userLabel="Window">
|
||||
<windowStyleMask key="styleMask" titled="YES"/>
|
||||
<windowPositionMask key="initialPositionMask" leftStrut="YES" rightStrut="YES" topStrut="YES" bottomStrut="YES"/>
|
||||
<rect key="contentRect" x="200" y="222" width="400" height="107"/>
|
||||
@@ -55,7 +55,7 @@
|
||||
</connections>
|
||||
</progressIndicator>
|
||||
<button verticalHuggingPriority="750" id="12">
|
||||
<rect key="frame" x="272.00000009349748" y="12" width="114" height="32"/>
|
||||
<rect key="frame" x="272" y="12" width="114" height="32"/>
|
||||
<autoresizingMask key="autoresizingMask" flexibleMinX="YES" widthSizable="YES"/>
|
||||
<buttonCell key="cell" type="push" title="Button" bezelStyle="rounded" alignment="center" borderStyle="border" inset="2" id="55">
|
||||
<behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/>
|
||||
@@ -74,12 +74,12 @@
|
||||
<color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/>
|
||||
</textFieldCell>
|
||||
<connections>
|
||||
<binding destination="-2" name="value" keyPath="statusText" id="17"/>
|
||||
<binding destination="-2" name="hidden" keyPath="statusText" id="33">
|
||||
<dictionary key="options">
|
||||
<string key="NSValueTransformerName">NSIsNil</string>
|
||||
</dictionary>
|
||||
</binding>
|
||||
<binding destination="-2" name="value" keyPath="statusText" id="17"/>
|
||||
</connections>
|
||||
</textField>
|
||||
</subviews>
|
||||
|
||||
Vendored
+2
-2
@@ -9,10 +9,10 @@
|
||||
#ifndef SUSTATUSCONTROLLER_H
|
||||
#define SUSTATUSCONTROLLER_H
|
||||
|
||||
#import "SUWindowController.h"
|
||||
#import <Cocoa/Cocoa.h>
|
||||
|
||||
@class SUHost;
|
||||
@interface SUStatusController : SUWindowController
|
||||
@interface SUStatusController : NSWindowController
|
||||
@property (weak) IBOutlet NSButton *actionButton;
|
||||
@property (weak) IBOutlet NSProgressIndicator *progressBar;
|
||||
@property (weak) IBOutlet NSTextField *statusTextField;
|
||||
|
||||
Loaded 100 of 283 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user