mirror of
https://github.com/sparkle-project/Sparkle
synced 2026-11-22 04:30:47 +00:00
Compare commits
272
Commits
2.2.1
...
2.8.0-beta.3
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
488fd7d8bd | ||
|
|
86d11fd407 | ||
|
|
167db6f80c | ||
|
|
f1ecf8e445 | ||
|
|
ba41d1b7b1 | ||
|
|
f52d989151 | ||
|
|
ee00f4f63c | ||
|
|
4dac8e3ce8 | ||
|
|
4d7ad5613b | ||
|
|
366e8a0bf9 | ||
|
|
1603296a50 | ||
|
|
fa4176fdb6 | ||
|
|
782e2bf5d7 | ||
|
|
97bea2fcd4 | ||
|
|
b4a1b46fe1 | ||
|
|
8702e2dd11 | ||
|
|
d491aafeb7 | ||
|
|
2cfb1e6fe2 | ||
|
|
0c0317c09a | ||
|
|
43b3b03886 | ||
|
|
21e34394d0 | ||
|
|
e67dcb0fd2 | ||
|
|
5f9ee13796 | ||
|
|
eadcc179d0 | ||
|
|
f3dc1a4b9c | ||
|
|
4274e096fe | ||
|
|
341c8b2c17 | ||
|
|
8e30a08291 | ||
|
|
fea50c33c8 | ||
|
|
afc4179c0d | ||
|
|
f3cd2b9ff9 | ||
|
|
3b39b400e1 | ||
|
|
1dec7ddce9 | ||
|
|
3e3d573d08 | ||
|
|
057702e757 | ||
|
|
997778dd2d | ||
|
|
16819179a0 | ||
|
|
0ca3004e98 | ||
|
|
edacb83e50 | ||
|
|
62a1908333 | ||
|
|
19ff91d93d | ||
|
|
587aa028e6 | ||
|
|
f9a3d95ce0 | ||
|
|
4ad4255672 | ||
|
|
92c78f3c27 | ||
|
|
73695f6913 | ||
|
|
e13e63c85e | ||
|
|
9902f2fb05 | ||
|
|
1ca60d5ab6 | ||
|
|
597825d111 | ||
|
|
2c95fa406a | ||
|
|
8fcdac1e6c | ||
|
|
d04faabe7d | ||
|
|
ebf75782f8 | ||
|
|
14ba9efc51 | ||
|
|
f3dc125d8c | ||
|
|
544c642483 | ||
|
|
ad3c8b5dc7 | ||
|
|
ef9bc6ef58 | ||
|
|
6848a88abc | ||
|
|
8de8db001e | ||
|
|
8f8842214b | ||
|
|
661540d088 | ||
|
|
a5c26b5cdf | ||
|
|
8f86cad4a2 | ||
|
|
8bc4976a2c | ||
|
|
ed987512f6 | ||
|
|
04ad482d59 | ||
|
|
fa4eaa977c | ||
|
|
e9726ff718 | ||
|
|
0ef1ee0220 | ||
|
|
6aa15e9933 | ||
|
|
b8986f608a | ||
|
|
a4badefff2 | ||
|
|
3a9734538a | ||
|
|
1b6565ded5 | ||
|
|
dd9374356b | ||
|
|
97a8f5a6ba | ||
|
|
3f93bf0150 | ||
|
|
007e9aee61 | ||
|
|
37d1fee019 | ||
|
|
2a48c17b03 | ||
|
|
cd6c61d47f | ||
|
|
3c180effcb | ||
|
|
0ad8d83066 | ||
|
|
b456fd4049 | ||
|
|
5af89de393 | ||
|
|
3a87581af2 | ||
|
|
6e2366255b | ||
|
|
c648665724 | ||
|
|
27cf3b3650 | ||
|
|
444a537365 | ||
|
|
61054c7a9a | ||
|
|
2247105ff3 | ||
|
|
f904466d35 | ||
|
|
9d6e8c24b5 | ||
|
|
dd76d0063d | ||
|
|
be8247efbd | ||
|
|
41847a58cd | ||
|
|
f948fafe16 | ||
|
|
946c583910 | ||
|
|
026cf54a76 | ||
|
|
b328c499a3 | ||
|
|
00e6259c9d | ||
|
|
31b462f860 | ||
|
|
5264c01d37 | ||
|
|
0cff81740f | ||
|
|
e9989a8ae7 | ||
|
|
2e1bdb98f1 | ||
|
|
d30adc8407 | ||
|
|
0183bf2b3f | ||
|
|
2b7615fe5b | ||
|
|
9aece0259c | ||
|
|
8c7476f93d | ||
|
|
0a4caaf7a8 | ||
|
|
a603047fd5 | ||
|
|
2bd33682d1 | ||
|
|
dfab64efdf | ||
|
|
51ce7108c9 | ||
|
|
56e365d050 | ||
|
|
c983fa1548 | ||
|
|
ef1f03cf1e | ||
|
|
4d164ba4ab | ||
|
|
66c198932d | ||
|
|
24f0f3952d | ||
|
|
7e5ebca735 | ||
|
|
001d6d6a69 | ||
|
|
9e9830eb0f | ||
|
|
615043da2b | ||
|
|
485f0e661d | ||
|
|
f1daff840f | ||
|
|
47d3d90aee | ||
|
|
9a29d14b7b | ||
|
|
7a7fb9ecd9 | ||
|
|
4ad2b0d945 | ||
|
|
2afa08405c | ||
|
|
ed1bc2fdc8 | ||
|
|
b84c1b14ce | ||
|
|
0a92e049eb | ||
|
|
1a0b023e1c | ||
|
|
1e419c8c16 | ||
|
|
ac6c897dd5 | ||
|
|
5a708be2a5 | ||
|
|
82209831c0 | ||
|
|
70a9ad52ae | ||
|
|
a00fd1d323 | ||
|
|
1f07f4096e | ||
|
|
679d3568c2 | ||
|
|
bd90fb7b18 | ||
|
|
9684a433ee | ||
|
|
ff4d4f53a8 | ||
|
|
469f423e28 | ||
|
|
846838c90b | ||
|
|
f6a86f52b3 | ||
|
|
f0ceaf5cc9 | ||
|
|
569f69b463 | ||
|
|
7cc751ff4f | ||
|
|
d005af3e03 | ||
|
|
4cdfffa8e9 | ||
|
|
0e865f07c5 | ||
|
|
a6e22a0667 | ||
|
|
8125490931 | ||
|
|
4abbb2b4f1 | ||
|
|
28e85abe88 | ||
|
|
5675086860 | ||
|
|
e59cf0e101 | ||
|
|
b5a9c0a1f1 | ||
|
|
57c3732f7d | ||
|
|
0155c78a99 | ||
|
|
d41b8652ee | ||
|
|
821b0ff37f | ||
|
|
c9c08b7f42 | ||
|
|
7c8fe1d427 | ||
|
|
5528d7f9ec | ||
|
|
419552a7d3 | ||
|
|
c23d74d8e0 | ||
|
|
456a3d4275 | ||
|
|
87e4fcbac3 | ||
|
|
2af0fa916c | ||
|
|
8039288f64 | ||
|
|
4ca2e2eb21 | ||
|
|
f7567e5a69 | ||
|
|
7907f058bc | ||
|
|
4a322e0ab4 | ||
|
|
270582b2e7 | ||
|
|
91a2c1c100 | ||
|
|
53d58921ef | ||
|
|
e15324773f | ||
|
|
b7b858dbf3 | ||
|
|
8e2107a57d | ||
|
|
631846cc82 | ||
|
|
3a99b31f37 | ||
|
|
151c256721 | ||
|
|
82b94a131d | ||
|
|
4ac6ea827a | ||
|
|
b5199e7a05 | ||
|
|
39495fd562 | ||
|
|
60568b82ba | ||
|
|
9ab2c0d58c | ||
|
|
665bba36cc | ||
|
|
1e8308116e | ||
|
|
245c6821aa | ||
|
|
ad936155fa | ||
|
|
d220346206 | ||
|
|
95f8e7e0cf | ||
|
|
362f50a8a1 | ||
|
|
87697ce10f | ||
|
|
da75bb432e | ||
|
|
fde8f0a35e | ||
|
|
06edf5695d | ||
|
|
ffc203b89a | ||
|
|
348c3a9658 | ||
|
|
077d7228ba | ||
|
|
be7f6952c2 | ||
|
|
91b8f4eaa0 | ||
|
|
cc90026ade | ||
|
|
68d539ce83 | ||
|
|
8154b1eab3 | ||
|
|
14e4a98b69 | ||
|
|
f36c34f2f4 | ||
|
|
bdc095bf3a | ||
|
|
8cd13b0cfd | ||
|
|
89e2f94872 | ||
|
|
a6536ea8f1 | ||
|
|
df313f7f59 | ||
|
|
f06ccf2711 | ||
|
|
ef9398ab32 | ||
|
|
8ac92e3ffa | ||
|
|
2a98381dfe | ||
|
|
9b4c91bc58 | ||
|
|
a7855eabe6 | ||
|
|
f86907c13c | ||
|
|
028e4c2bec | ||
|
|
891cd38eba | ||
|
|
a208bd5cf9 | ||
|
|
005392963f | ||
|
|
83cc66b988 | ||
|
|
a93317fb08 | ||
|
|
1b1a7db1ac | ||
|
|
d9c0cc7f53 | ||
|
|
7d68f8f7ae | ||
|
|
03f2452379 | ||
|
|
fc8000471b | ||
|
|
6c0e685063 | ||
|
|
c7c8b719cb | ||
|
|
4fa7b23f09 | ||
|
|
f1fe9e45f6 | ||
|
|
679cbc8652 | ||
|
|
6ef1f7fc7f | ||
|
|
6831a35e28 | ||
|
|
1c560652e7 | ||
|
|
863f85b5f5 | ||
|
|
f46ea87380 | ||
|
|
f5d4ad52ca | ||
|
|
926c47d48e | ||
|
|
fbfcec3453 | ||
|
|
8f77f066c1 | ||
|
|
47f335614a | ||
|
|
80a5b80ade | ||
|
|
e81ccbd891 | ||
|
|
dc2e1ff534 | ||
|
|
37ef179284 | ||
|
|
6a69f26dcc | ||
|
|
4cb6719c6b | ||
|
|
2c81393ec2 | ||
|
|
983d19580b | ||
|
|
6cbe8444a0 | ||
|
|
45a9099082 | ||
|
|
aa72b3f639 | ||
|
|
372f0504a5 | ||
|
|
470296a90e | ||
|
|
242ae2c392 |
No files matched your search
@@ -29,4 +29,4 @@ https://github.com/sparkle-project/Sparkle#troubleshooting
|
||||
|
||||
## Version
|
||||
|
||||
[please specify versions of Sparkle this is applicable to; note the old 1.x (master) branch is only taking fixes to regressions and security fixes now.]
|
||||
[please specify versions of Sparkle this is applicable to]
|
||||
@@ -1,36 +0,0 @@
|
||||
---
|
||||
name: Sparkle 1.x doesn't work in my app
|
||||
about: Problems with integration, unexpected errors using Sparkle 1
|
||||
title: ''
|
||||
labels: '1.x'
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
<!--
|
||||
|
||||
The answer to your issue is probably already in Console.app on your computer.
|
||||
Please use Console.app and search for Sparkle.
|
||||
|
||||
Please try troubleshooting steps:
|
||||
https://github.com/sparkle-project/Sparkle#troubleshooting
|
||||
|
||||
-->
|
||||
|
||||
### Description of the problem
|
||||
|
||||
|
||||
### Do you use Sandboxing in your app?
|
||||
|
||||
### Version of `Sparkle.framework` in the latest version of your app
|
||||
|
||||
### Version of `Sparkle.framework` in the old version of app that your users have (or N/A)
|
||||
|
||||
### Sparkle's output from Console.app
|
||||
```
|
||||
|
||||
```
|
||||
|
||||
### Steps to reproduce the behavior
|
||||
|
||||
[The more information provided and pasted verbatim, the easier it will be to diagnose an issue. If you can provide the affected application/binary and XML feed to reproduce an issue, share them]
|
||||
+2
-3
@@ -1,8 +1,7 @@
|
||||
---
|
||||
name: Sparkle 2.x doesn't work in my app
|
||||
about: Problems with integration, unexpected errors using Sparkle 2
|
||||
name: Sparkle doesn't work in my app
|
||||
about: Problems with integration, unexpected errors using Sparkle
|
||||
title: ''
|
||||
labels: '2.x'
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
@@ -7,8 +7,6 @@ Fixes # (issue)
|
||||
- [ ] My change requires a documentation update on [Sparkle's website repository](https://github.com/sparkle-project/sparkle-project.github.io)
|
||||
- [ ] My change requires changes to generate_appcast, generate_keys, or sign_update
|
||||
|
||||
Only bug fixes to regressions or security fixes are being backported to the 1.x (master) branch now. If you believe your change is significant enough to backport, please also create a separate pull request against the master branch.
|
||||
|
||||
## Testing
|
||||
|
||||
I tested and verified my change by using one or multiple of these methods:
|
||||
|
||||
+24
-19
@@ -10,25 +10,28 @@ jobs:
|
||||
build:
|
||||
strategy:
|
||||
matrix:
|
||||
xcode: ['xcode12.5.1', 'xcode13.3.1']
|
||||
xcode: ['xcode26', 'xcode16.4']
|
||||
include:
|
||||
- xcode: 'xcode13.3.1'
|
||||
xcode-path: '/Applications/Xcode_13.3.1.app/Contents/Developer'
|
||||
- xcode: 'xcode16.4'
|
||||
xcode-path: '/Applications/Xcode_16.4.app/Contents/Developer'
|
||||
upload-dist: true
|
||||
run-analyzer: true
|
||||
macos: 'macos-12'
|
||||
- xcode: 'xcode12.5.1'
|
||||
xcode-path: '/Applications/Xcode_12.5.1.app/Contents/Developer'
|
||||
macos: 'macos-15'
|
||||
- xcode: 'xcode26'
|
||||
xcode-path: '/Applications/Xcode_26.0.app'
|
||||
upload-dist: false
|
||||
run-analyzer: false
|
||||
macos: 'macos-11'
|
||||
macos: 'macos-15'
|
||||
|
||||
name: Build and Test Sparkle
|
||||
runs-on: ${{ matrix.macos }}
|
||||
|
||||
permissions:
|
||||
pull-requests: write
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v2
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
fetch-depth: 0
|
||||
@@ -58,7 +61,7 @@ jobs:
|
||||
env:
|
||||
DEVELOPER_DIR: ${{ matrix.xcode-path }}
|
||||
run: |
|
||||
xcodebuild analyze -project Sparkle.xcodeproj -quiet -scheme Sparkle -configuration Release -derivedDataPath analyze > anaylze_output.txt
|
||||
xcodebuild analyze -project Sparkle.xcodeproj -quiet -scheme Sparkle -configuration Release -derivedDataPath analyze > analyze_output.txt
|
||||
|
||||
- name: Find Analyzed Warnings
|
||||
if: ${{ success() && matrix.run-analyzer && github.event_name == 'pull_request' }}
|
||||
@@ -66,25 +69,27 @@ jobs:
|
||||
env:
|
||||
DEVELOPER_DIR: ${{ matrix.xcode-path }}
|
||||
run: |
|
||||
if grep -q "warning:" anaylze_output.txt; then
|
||||
echo '::set-output name=analyzestatus::0'
|
||||
if grep "warning:" analyze_output.txt | grep -q -v "dependency scan of"; then
|
||||
echo "analyzestatus=0" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo '::set-output name=analyzestatus::1'
|
||||
echo "analyzestatus=1" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Extract Analyzed Warnings
|
||||
if: ${{ success() && matrix.run-analyzer && github.event_name == 'pull_request' && steps.findwarnings.outputs.analyzestatus == '0' }}
|
||||
id: warnings
|
||||
run: |
|
||||
echo ::set-output name=content::$(cat anaylze_output.txt)
|
||||
{
|
||||
echo 'content<<EOF'
|
||||
cat analyze_output.txt
|
||||
echo 'EOF'
|
||||
} >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Post Analyzed Warnings
|
||||
if: ${{ success() && matrix.run-analyzer && github.event_name == 'pull_request' && steps.findwarnings.outputs.analyzestatus == '0' }}
|
||||
uses: mshick/add-pr-comment@v1
|
||||
uses: mshick/add-pr-comment@v2
|
||||
with:
|
||||
allow-repeats: false
|
||||
repo-token: ${{ secrets.BOT_PERSONAL_ACCESS_TOKEN }}
|
||||
repo-token-user-login: 'Sparkle-Bot'
|
||||
message: "``` ${{ steps.warnings.outputs.content }} ```"
|
||||
|
||||
- name: Build Release Distribution
|
||||
@@ -94,13 +99,13 @@ jobs:
|
||||
xcodebuild build -project Sparkle.xcodeproj -scheme Distribution -configuration Release -derivedDataPath build
|
||||
- name: Archive Test Results
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v2
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: build-logs
|
||||
path: build/Logs
|
||||
- name: Upload Distribution
|
||||
if: ${{ success() && matrix.upload-dist }}
|
||||
uses: actions/upload-artifact@v2
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: Sparkle-distribution-${{ matrix.xcode }}.tar.xz
|
||||
path: build/Build/Products/Release/sparkle-dist.tar.xz
|
||||
path: build/Build/Products/Release/sparkle_dist.tar.xz
|
||||
@@ -2,7 +2,7 @@ name: "Create Draft Release"
|
||||
|
||||
env:
|
||||
BUILDDIR: "build"
|
||||
DEVELOPER_DIR: "/Applications/Xcode_13.3.1.app/Contents/Developer"
|
||||
DEVELOPER_DIR: "/Applications/Xcode_16.4.app/Contents/Developer"
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
@@ -29,11 +29,11 @@ concurrency:
|
||||
jobs:
|
||||
release:
|
||||
name: "Publish binaries for release"
|
||||
runs-on: macos-12
|
||||
runs-on: macos-15
|
||||
|
||||
steps:
|
||||
- name: "Checkout sources"
|
||||
uses: actions/checkout@v2
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
token: ${{ secrets.BOT_PERSONAL_ACCESS_TOKEN }}
|
||||
submodules: true
|
||||
@@ -86,10 +86,11 @@ jobs:
|
||||
run: git push
|
||||
|
||||
- name: "Draft a release"
|
||||
uses: softprops/action-gh-release@v1
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
draft: true
|
||||
prerelease: ${{ env.PRERELEASE_VERSION }}
|
||||
target_commitish: ${{ github.ref_name }}
|
||||
name: "${{ github.event.inputs.marketingVersion }}${{ github.event.inputs.prereleaseSuffix }}"
|
||||
tag_name: "${{ github.event.inputs.marketingVersion }}${{ github.event.inputs.prereleaseSuffix }}"
|
||||
fail_on_unmatched_files: true
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
[submodule "Vendor/ed25519"]
|
||||
path = Vendor/ed25519
|
||||
url = https://github.com/orlp/ed25519
|
||||
@@ -19,7 +19,7 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@protocol SPUInstallerAgentProtocol;
|
||||
|
||||
@interface AgentConnection : NSObject
|
||||
SPU_OBJC_DIRECT_MEMBERS @interface AgentConnection : NSObject
|
||||
|
||||
- (instancetype)initWithHostBundleIdentifier:(NSString *)bundleIdentifier delegate:(id<AgentConnectionDelegate>)delegate;
|
||||
|
||||
|
||||
@@ -10,26 +10,24 @@
|
||||
#import "SPUMessageTypes.h"
|
||||
#import "SPUInstallerAgentProtocol.h"
|
||||
#import "SUInstallerAgentInitiationProtocol.h"
|
||||
#import "SUCodeSigningVerifier.h"
|
||||
#import "SULog.h"
|
||||
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
|
||||
@interface AgentConnection () <NSXPCListenerDelegate, SUInstallerAgentInitiationProtocol>
|
||||
|
||||
@property (nonatomic) NSXPCListener *xpcListener;
|
||||
@property (nonatomic, nullable) NSXPCConnection *activeConnection;
|
||||
@property (nonatomic, nullable) id<SPUInstallerAgentProtocol> agent;
|
||||
@property (nonatomic, weak) id<AgentConnectionDelegate> delegate;
|
||||
@property (nonatomic) BOOL connected;
|
||||
|
||||
@end
|
||||
|
||||
@implementation AgentConnection
|
||||
{
|
||||
NSXPCListener *_xpcListener;
|
||||
NSXPCConnection *_activeConnection;
|
||||
__weak id<AgentConnectionDelegate> _delegate;
|
||||
}
|
||||
|
||||
@synthesize xpcListener = _xpcListener;
|
||||
@synthesize activeConnection = _activeConnection;
|
||||
@synthesize agent = _agent;
|
||||
@synthesize delegate = _delegate;
|
||||
@synthesize connected = _connected;
|
||||
@synthesize invalidationError = _invalidationError;
|
||||
|
||||
@@ -48,70 +46,95 @@
|
||||
|
||||
- (void)startListener
|
||||
{
|
||||
[self.xpcListener resume];
|
||||
[_xpcListener resume];
|
||||
}
|
||||
|
||||
- (void)invalidate
|
||||
{
|
||||
self.delegate = nil;
|
||||
_delegate = nil;
|
||||
|
||||
[self.activeConnection invalidate];
|
||||
self.activeConnection = nil;
|
||||
[_activeConnection invalidate];
|
||||
// Don't need to set _activeConnection to nil, we don't expect new connections
|
||||
|
||||
[self.xpcListener invalidate];
|
||||
self.xpcListener = nil;
|
||||
[_xpcListener invalidate];
|
||||
_xpcListener = nil;
|
||||
}
|
||||
|
||||
- (BOOL)listener:(NSXPCListener *)__unused listener shouldAcceptNewConnection:(NSXPCConnection *)newConnection
|
||||
{
|
||||
if (self.activeConnection != nil) {
|
||||
if (_activeConnection != nil) {
|
||||
SULog(SULogLevelError, @"Error: Rejecting new connection for agent due already having an active connection");
|
||||
|
||||
[newConnection invalidate];
|
||||
return NO;
|
||||
}
|
||||
|
||||
// Hardening but not critical for security
|
||||
NSError *validationError = nil;
|
||||
SUValidateConnectionStatus validationStatus = [SUCodeSigningVerifier validateConnection:newConnection options:SUValidateConnectionOptionDefault error:&validationError];
|
||||
switch (validationStatus) {
|
||||
case SUValidateConnectionStatusSetCodeSigningRequirementSuccess:
|
||||
break;
|
||||
case SUValidateConnectionStatusSetNoRequirementSuccess:
|
||||
break;
|
||||
case SUValidateConnectionStatusAPIFailure:
|
||||
case SUValidateConnectionStatusCodeSigningRequirementFailure:
|
||||
case SUValidateConectionNoSupportedValidationMethodFailure:
|
||||
SULog(SULogLevelError, @"Error: Rejecting new connection for agent due to failing validation of XPC connection with status %lu and error: %@", validationStatus, validationError.localizedDescription);
|
||||
|
||||
[newConnection invalidate];
|
||||
return NO;
|
||||
}
|
||||
|
||||
newConnection.exportedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUInstallerAgentInitiationProtocol)];
|
||||
newConnection.exportedObject = self;
|
||||
|
||||
newConnection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SPUInstallerAgentProtocol)];
|
||||
|
||||
self.activeConnection = newConnection;
|
||||
_activeConnection = newConnection;
|
||||
|
||||
__weak AgentConnection *weakSelf = self;
|
||||
__weak __typeof__(self) weakSelf = self;
|
||||
newConnection.interruptionHandler = ^{
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[weakSelf.activeConnection invalidate];
|
||||
__typeof__(self) strongSelf = weakSelf;
|
||||
if (strongSelf != nil) {
|
||||
[strongSelf->_activeConnection invalidate];
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
newConnection.invalidationHandler = ^{
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[weakSelf.delegate agentConnectionDidInvalidate];
|
||||
__typeof__(self) strongSelf = weakSelf;
|
||||
if (strongSelf != nil) {
|
||||
[strongSelf->_delegate agentConnectionDidInvalidate];
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
_agent = newConnection.remoteObjectProxy;
|
||||
[newConnection resume];
|
||||
|
||||
self.agent = newConnection.remoteObjectProxy;
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (void)connectionDidInitiateWithReply:(void (^)(void))acknowledgement
|
||||
{
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
self.connected = YES;
|
||||
self->_connected = YES;
|
||||
|
||||
[self.delegate agentConnectionDidInitiate];
|
||||
self.delegate = nil;
|
||||
[self->_delegate agentConnectionDidInitiate];
|
||||
});
|
||||
|
||||
acknowledgement();
|
||||
if (acknowledgement != NULL) {
|
||||
acknowledgement();
|
||||
}
|
||||
}
|
||||
|
||||
- (void)connectionWillInvalidateWithError:(NSError *)error
|
||||
{
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
self.invalidationError = error;
|
||||
self->_invalidationError = error;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface AppInstaller : NSObject
|
||||
SPU_OBJC_DIRECT_MEMBERS @interface AppInstaller : NSObject
|
||||
|
||||
- (instancetype)initWithHostBundleIdentifier:(NSString *)hostBundleIdentifier homeDirectory:(NSString *)homeDirectory userName:(NSString *)userName;
|
||||
|
||||
|
||||
+445
-247
@@ -7,7 +7,6 @@
|
||||
//
|
||||
|
||||
#import "AppInstaller.h"
|
||||
#import "TerminationListener.h"
|
||||
#import "SUInstaller.h"
|
||||
#import "SUUpdateValidator.h"
|
||||
#import "SULog.h"
|
||||
@@ -28,6 +27,10 @@
|
||||
#import "SPUInstallerAgentProtocol.h"
|
||||
#import "SPUInstallationType.h"
|
||||
#import "SPULocalCacheDirectory.h"
|
||||
#import "SPUVerifierInformation.h"
|
||||
#import "SUConstants.h"
|
||||
#import "SUCodeSigningVerifier.h"
|
||||
#import <os/lock.h>
|
||||
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
@@ -43,73 +46,63 @@
|
||||
static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
|
||||
|
||||
@interface AppInstaller () <NSXPCListenerDelegate, SUInstallerCommunicationProtocol, AgentConnectionDelegate>
|
||||
|
||||
@property (nonatomic) NSXPCListener* xpcListener;
|
||||
@property (nonatomic) NSXPCConnection *activeConnection;
|
||||
@property (nonatomic) id<SUInstallerCommunicationProtocol> communicator;
|
||||
@property (nonatomic) AgentConnection *agentConnection;
|
||||
@property (nonatomic) BOOL receivedUpdaterPong;
|
||||
|
||||
@property (nonatomic, strong) TerminationListener *terminationListener;
|
||||
|
||||
@property (nonatomic) SUUpdateValidator *updateValidator;
|
||||
|
||||
@property (nonatomic, readonly, copy) NSString *hostBundleIdentifier;
|
||||
@property (nonatomic, readonly) NSString *homeDirectory;
|
||||
@property (nonatomic, readonly) NSString *userName;
|
||||
@property (nonatomic) SUHost *host;
|
||||
@property (nonatomic, copy) NSString *updateDirectoryPath;
|
||||
@property (nonatomic, copy) NSString *downloadName;
|
||||
@property (nonatomic, copy) NSString *decryptionPassword;
|
||||
@property (nonatomic, strong) SUSignatures *signatures;
|
||||
@property (nonatomic, copy) NSString *relaunchPath;
|
||||
@property (nonatomic, copy) NSString *installationType;
|
||||
@property (nonatomic, assign) BOOL shouldRelaunch;
|
||||
@property (nonatomic, assign) BOOL shouldShowUI;
|
||||
|
||||
@property (nonatomic) id<SUInstallerProtocol> installer;
|
||||
@property (nonatomic) BOOL willCompleteInstallation;
|
||||
@property (nonatomic) BOOL receivedInstallationData;
|
||||
@property (nonatomic) BOOL finishedValidation;
|
||||
@property (nonatomic) BOOL agentInitiatedConnection;
|
||||
|
||||
@property (nonatomic) dispatch_queue_t installerQueue;
|
||||
@property (nonatomic) BOOL performedStage1Installation;
|
||||
@property (nonatomic) BOOL performedStage2Installation;
|
||||
@property (nonatomic) BOOL performedStage3Installation;
|
||||
|
||||
@end
|
||||
|
||||
@implementation AppInstaller
|
||||
{
|
||||
NSXPCListener* _xpcListener;
|
||||
// Must be synchronized with _newConnectionLock
|
||||
// Set from new connection handler, and also set/read from main thread
|
||||
NSXPCConnection *_activeConnection;
|
||||
|
||||
id<SUInstallerCommunicationProtocol> _communicator;
|
||||
AgentConnection *_agentConnection;
|
||||
|
||||
@synthesize xpcListener = _xpcListener;
|
||||
@synthesize activeConnection = _activeConnection;
|
||||
@synthesize communicator = _communicator;
|
||||
@synthesize agentConnection = _agentConnection;
|
||||
@synthesize receivedUpdaterPong = _receivedUpdaterPong;
|
||||
@synthesize hostBundleIdentifier = _hostBundleIdentifier;
|
||||
@synthesize homeDirectory = _homeDirectory;
|
||||
@synthesize userName = _userName;
|
||||
@synthesize terminationListener = _terminationListener;
|
||||
@synthesize updateValidator = _updateValidator;
|
||||
@synthesize host = _host;
|
||||
@synthesize updateDirectoryPath = _updateDirectoryPath;
|
||||
@synthesize downloadName = _downloadName;
|
||||
@synthesize decryptionPassword = _decryptionPassword;
|
||||
@synthesize signatures = _signatures;
|
||||
@synthesize relaunchPath = _relaunchPath;
|
||||
@synthesize installationType = _installationType;
|
||||
@synthesize shouldRelaunch = _shouldRelaunch;
|
||||
@synthesize shouldShowUI = _shouldShowUI;
|
||||
@synthesize installer = _installer;
|
||||
@synthesize willCompleteInstallation = _willCompleteInstallation;
|
||||
@synthesize receivedInstallationData = _receivedInstallationData;
|
||||
@synthesize installerQueue = _installerQueue;
|
||||
@synthesize performedStage1Installation = _performedStage1Installation;
|
||||
@synthesize performedStage2Installation = _performedStage2Installation;
|
||||
@synthesize performedStage3Installation = _performedStage3Installation;
|
||||
@synthesize finishedValidation = _finishedValidation;
|
||||
@synthesize agentInitiatedConnection = _agentInitiatedConnection;
|
||||
SUUpdateValidator *_updateValidator;
|
||||
|
||||
NSString *_hostBundleIdentifier;
|
||||
NSString *_homeDirectory;
|
||||
NSString *_userName;
|
||||
SUHost *_host;
|
||||
NSString *_updateDirectoryPath;
|
||||
NSString *_extractionDirectory;
|
||||
NSString *_downloadName;
|
||||
NSString *_decryptionPassword;
|
||||
SUSignatures *_signatures;
|
||||
NSString *_relaunchPath;
|
||||
NSString *_installationType;
|
||||
SPUVerifierInformation *_verifierInformation;
|
||||
|
||||
id<SUInstallerProtocol> _installer;
|
||||
|
||||
dispatch_queue_t _installerQueue;
|
||||
|
||||
os_unfair_lock _newConnectionLock;
|
||||
|
||||
#if SPARKLE_BUILD_PACKAGE_SUPPORT
|
||||
// Must be synchronized with _newConnectionLock
|
||||
// Set from new connection handler, read from main thread
|
||||
BOOL _connectionCodeSigningValidationSkipped;
|
||||
#endif
|
||||
|
||||
BOOL _shouldRelaunch;
|
||||
BOOL _shouldShowUI;
|
||||
|
||||
BOOL _receivedUpdaterPong;
|
||||
|
||||
BOOL _willCompleteInstallation;
|
||||
BOOL _receivedInstallationData;
|
||||
BOOL _finishedValidation;
|
||||
BOOL _agentInitiatedConnection;
|
||||
|
||||
// Setting _performedStage1Installation on main thread must be synchronzied with reading it from new connection handler
|
||||
BOOL _performedStage1Installation;
|
||||
|
||||
BOOL _performedStage2Installation;
|
||||
BOOL _performedStage3Installation;
|
||||
|
||||
BOOL _targetTerminated;
|
||||
}
|
||||
|
||||
- (instancetype)initWithHostBundleIdentifier:(NSString *)hostBundleIdentifier homeDirectory:(NSString *)homeDirectory userName:(NSString *)userName
|
||||
{
|
||||
@@ -117,6 +110,8 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
|
||||
return nil;
|
||||
}
|
||||
|
||||
_newConnectionLock = OS_UNFAIR_LOCK_INIT;
|
||||
|
||||
_hostBundleIdentifier = [hostBundleIdentifier copy];
|
||||
|
||||
_homeDirectory = [homeDirectory copy];
|
||||
@@ -132,109 +127,194 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
|
||||
|
||||
- (BOOL)listener:(NSXPCListener *)__unused listener shouldAcceptNewConnection:(NSXPCConnection *)newConnection
|
||||
{
|
||||
if (self.activeConnection != nil) {
|
||||
SULog(SULogLevelDefault, @"Rejecting multiple connections...");
|
||||
[newConnection invalidate];
|
||||
return NO;
|
||||
os_unfair_lock_lock(&_newConnectionLock);
|
||||
{
|
||||
if (_activeConnection != nil) {
|
||||
os_unfair_lock_unlock(&_newConnectionLock);
|
||||
|
||||
SULog(SULogLevelError, @"Error: Rejecting multiple XPC connections for installer...");
|
||||
|
||||
[newConnection invalidate];
|
||||
return NO;
|
||||
}
|
||||
|
||||
#if SPARKLE_BUILD_PACKAGE_SUPPORT
|
||||
BOOL connectionCodeSigningValidationSkipped = NO;
|
||||
#endif
|
||||
|
||||
// It's safe to allow any connections once stage 1 installation is complete
|
||||
// This is to allow general updaters to resume the installation.
|
||||
if (!_performedStage1Installation) {
|
||||
BOOL passesValidation;
|
||||
NSError *validationError = nil;
|
||||
SUValidateConnectionStatus status = [SUCodeSigningVerifier validateConnection:newConnection options:SUValidateConnectionOptionDefault error:&validationError];
|
||||
switch (status) {
|
||||
case SUValidateConnectionStatusSetCodeSigningRequirementSuccess:
|
||||
passesValidation = YES;
|
||||
break;
|
||||
case SUValidateConnectionStatusSetNoRequirementSuccess:
|
||||
passesValidation = YES;
|
||||
#if SPARKLE_BUILD_PACKAGE_SUPPORT
|
||||
connectionCodeSigningValidationSkipped = YES;
|
||||
#endif
|
||||
break;
|
||||
case SUValidateConnectionStatusAPIFailure:
|
||||
case SUValidateConnectionStatusCodeSigningRequirementFailure:
|
||||
case SUValidateConectionNoSupportedValidationMethodFailure:
|
||||
passesValidation = NO;
|
||||
break;
|
||||
}
|
||||
|
||||
if (!passesValidation) {
|
||||
os_unfair_lock_unlock(&_newConnectionLock);
|
||||
|
||||
SULog(SULogLevelError, @"Error: Rejecting new connection for installer due to failing validation of XPC connection with status %lu and error: %@", status, validationError.localizedDescription);
|
||||
[newConnection invalidate];
|
||||
return NO;
|
||||
}
|
||||
}
|
||||
|
||||
#if SPARKLE_BUILD_PACKAGE_SUPPORT
|
||||
_connectionCodeSigningValidationSkipped = connectionCodeSigningValidationSkipped;
|
||||
#endif
|
||||
_activeConnection = newConnection;
|
||||
}
|
||||
|
||||
self.activeConnection = newConnection;
|
||||
os_unfair_lock_unlock(&_newConnectionLock);
|
||||
|
||||
newConnection.exportedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUInstallerCommunicationProtocol)];
|
||||
newConnection.exportedObject = self;
|
||||
|
||||
newConnection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUInstallerCommunicationProtocol)];
|
||||
|
||||
__weak AppInstaller *weakSelf = self;
|
||||
__weak __typeof__(self) weakSelf = self;
|
||||
newConnection.interruptionHandler = ^{
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[weakSelf.activeConnection invalidate];
|
||||
__typeof__(self) strongSelf = weakSelf;
|
||||
if (strongSelf != nil) {
|
||||
os_unfair_lock_lock(&strongSelf->_newConnectionLock);
|
||||
NSXPCConnection *activeConnection = strongSelf->_activeConnection;
|
||||
os_unfair_lock_unlock(&strongSelf->_newConnectionLock);
|
||||
|
||||
[activeConnection invalidate];
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
newConnection.invalidationHandler = ^{
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
AppInstaller *strongSelf = weakSelf;
|
||||
__typeof__(self) strongSelf = weakSelf;
|
||||
if (strongSelf != nil) {
|
||||
if (strongSelf.activeConnection != nil && !strongSelf.willCompleteInstallation) {
|
||||
if (strongSelf->_activeConnection != nil && !strongSelf->_willCompleteInstallation) {
|
||||
[strongSelf cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Invalidation on remote port being called, and installation is not close enough to completion!" }]];
|
||||
}
|
||||
strongSelf.communicator = nil;
|
||||
strongSelf.activeConnection = nil;
|
||||
strongSelf->_communicator = nil;
|
||||
|
||||
os_unfair_lock_lock(&strongSelf->_newConnectionLock);
|
||||
strongSelf->_activeConnection = nil;
|
||||
os_unfair_lock_unlock(&strongSelf->_newConnectionLock);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
[newConnection resume];
|
||||
|
||||
self.communicator = newConnection.remoteObjectProxy;
|
||||
// _communicator is used only on main thread
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
self->_communicator = newConnection.remoteObjectProxy;
|
||||
[newConnection resume];
|
||||
});
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (void)start
|
||||
{
|
||||
[self.xpcListener resume];
|
||||
[self.agentConnection startListener];
|
||||
[_xpcListener resume];
|
||||
[_agentConnection startListener];
|
||||
|
||||
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(FIRST_UPDATER_MESSAGE_TIMEOUT * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
|
||||
if (!self.receivedInstallationData) {
|
||||
if (!self->_receivedInstallationData) {
|
||||
[self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Timeout: installation data was never received" }]];
|
||||
}
|
||||
|
||||
if (!self.agentConnection.connected) {
|
||||
if (!self->_agentConnection.connected) {
|
||||
[self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Timeout: agent connection was never initiated" }]];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
- (void)extractAndInstallUpdate
|
||||
- (void)extractAndInstallUpdate SPU_OBJC_DIRECT
|
||||
{
|
||||
[self.communicator handleMessageWithIdentifier:SPUExtractionStarted data:[NSData data]];
|
||||
[_communicator handleMessageWithIdentifier:SPUExtractionStarted data:[NSData data]];
|
||||
|
||||
NSString *archivePath = [self.updateDirectoryPath stringByAppendingPathComponent:self.downloadName];
|
||||
id<SUUnarchiverProtocol> unarchiver = [SUUnarchiver unarchiverForPath:archivePath updatingHostBundlePath:self.host.bundlePath decryptionPassword:self.decryptionPassword expectingInstallationType:self.installationType];
|
||||
NSString *archivePath = [_updateDirectoryPath stringByAppendingPathComponent:_downloadName];
|
||||
|
||||
NSError *unarchiverError = nil;
|
||||
id<SUUnarchiverProtocol> unarchiver = [SUUnarchiver unarchiverForPath:archivePath extractionDirectory:_extractionDirectory updatingHostBundlePath:_host.bundlePath decryptionPassword:_decryptionPassword expectingInstallationType:_installationType];
|
||||
|
||||
NSError *prevalidationError = nil;
|
||||
BOOL success = NO;
|
||||
if (!unarchiver) {
|
||||
unarchiverError = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"No valid unarchiver was found for %@", archivePath] }];
|
||||
prevalidationError = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"No valid unarchiver was found for %@", archivePath] }];
|
||||
|
||||
success = NO;
|
||||
} else {
|
||||
self.updateValidator = [[SUUpdateValidator alloc] initWithDownloadPath:archivePath signatures:self.signatures host:self.host];
|
||||
|
||||
// Delta & package updates will require validation before extraction
|
||||
// Normal application updates are a bit more lenient allowing developers to change one of apple dev ID or EdDSA keys
|
||||
BOOL needsPrevalidation = [[unarchiver class] mustValidateBeforeExtraction] || ![self.installationType isEqualToString:SPUInstallationTypeApplication];
|
||||
|
||||
if (needsPrevalidation) {
|
||||
success = [self.updateValidator validateDownloadPathWithError:&unarchiverError];
|
||||
NSError *fileAttributesError = nil;
|
||||
NSDictionary<NSFileAttributeKey, id> *archiveFileAttributes = [NSFileManager.defaultManager attributesOfItemAtPath:archivePath error:&fileAttributesError];
|
||||
if (archiveFileAttributes == nil) {
|
||||
SULog(SULogLevelError, @"Failed to retrieve file attributes from archive: %@.", fileAttributesError);
|
||||
} else {
|
||||
success = YES;
|
||||
_verifierInformation.actualContentLength = (uint64_t)(archiveFileAttributes.fileSize);
|
||||
}
|
||||
|
||||
_updateValidator = [[SUUpdateValidator alloc] initWithDownloadPath:archivePath signatures:_signatures host:_host verifierInformation:_verifierInformation];
|
||||
|
||||
// More uncommon archives types (.aar, .yaa) need SUVerifyUpdateBeforeExtraction
|
||||
BOOL verifyBeforeExtraction = [_host boolForInfoDictionaryKey:SUVerifyUpdateBeforeExtractionKey];
|
||||
if (!verifyBeforeExtraction && unarchiver.needsVerifyBeforeExtractionKey) {
|
||||
prevalidationError = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Extracting %@ archives require setting %@ to YES in the old app. Please visit https://sparkle-project.org/documentation/customization/ for more information.", archivePath.pathExtension, SUVerifyUpdateBeforeExtractionKey] }];
|
||||
|
||||
success = NO;
|
||||
} else {
|
||||
// Delta, package updates, and apps with SUVerifyUpdateBeforeExtraction will require validation before extraction
|
||||
// Otherwise normal application updates are a bit more lenient allowing developers to change one of apple dev ID or EdDSA keys after extraction
|
||||
BOOL archiveTypeMustValidateBeforeExtraction = [[unarchiver class] mustValidateBeforeExtraction];
|
||||
BOOL needsPrevalidation = verifyBeforeExtraction || archiveTypeMustValidateBeforeExtraction || ![_installationType isEqualToString:SPUInstallationTypeApplication];
|
||||
|
||||
if (needsPrevalidation) {
|
||||
// EdDSA signing is required, so host must have public keys
|
||||
if (![_updateValidator validateHostHasPublicKeys:&prevalidationError]) {
|
||||
success = NO;
|
||||
} else {
|
||||
// Falling back on code signing for prevalidation requires SUVerifyUpdateBeforeExtraction
|
||||
// and that update is a regular app update, and not a delta update
|
||||
BOOL fallbackOnCodeSigning = (verifyBeforeExtraction && !archiveTypeMustValidateBeforeExtraction && [_installationType isEqualToString:SPUInstallationTypeApplication]);
|
||||
|
||||
success = [_updateValidator validateDownloadPathWithFallbackOnCodeSigning:fallbackOnCodeSigning error:&prevalidationError];
|
||||
}
|
||||
} else {
|
||||
success = YES;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!success) {
|
||||
[self unarchiverDidFailWithError:unarchiverError];
|
||||
[self unarchiverDidFailWithError:prevalidationError];
|
||||
} else {
|
||||
[unarchiver
|
||||
unarchiveWithCompletionBlock:^(NSError * _Nullable error) {
|
||||
if (error != nil) {
|
||||
[self unarchiverDidFailWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to unarchive %@", archivePath], NSUnderlyingErrorKey: (NSError * _Nonnull)error }]];
|
||||
} else {
|
||||
[self.communicator handleMessageWithIdentifier:SPUValidationStarted data:[NSData data]];
|
||||
[self->_communicator handleMessageWithIdentifier:SPUValidationStarted data:[NSData data]];
|
||||
|
||||
NSError *validationError = nil;
|
||||
BOOL validationSuccess = [self.updateValidator validateWithUpdateDirectory:self.updateDirectoryPath error:&validationError];
|
||||
BOOL validationSuccess = [self->_updateValidator validateWithUpdateDirectory:self->_extractionDirectory error:&validationError];
|
||||
|
||||
if (!validationSuccess) {
|
||||
[self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Update validation was a failure", NSUnderlyingErrorKey: validationError }]];
|
||||
} else {
|
||||
[self.communicator handleMessageWithIdentifier:SPUInstallationStartedStage1 data:[NSData data]];
|
||||
[self->_communicator handleMessageWithIdentifier:SPUInstallationStartedStage1 data:[NSData data]];
|
||||
|
||||
self.finishedValidation = YES;
|
||||
if (self.agentInitiatedConnection) {
|
||||
self->_finishedValidation = YES;
|
||||
if (self->_agentInitiatedConnection) {
|
||||
[self retrieveProcessIdentifierAndStartInstallation];
|
||||
}
|
||||
}
|
||||
@@ -245,60 +325,61 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
|
||||
uint64_t progressValue = CFSwapInt64HostToLittle(*(uint64_t *)&progress);
|
||||
NSData *data = [NSData dataWithBytes:&progressValue length:sizeof(progressValue)];
|
||||
|
||||
[self.communicator handleMessageWithIdentifier:SPUExtractedArchiveWithProgress data:data];
|
||||
[self->_communicator handleMessageWithIdentifier:SPUExtractedArchiveWithProgress data:data];
|
||||
}
|
||||
}];
|
||||
} waitForCleanup:NO];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)clearUpdateDirectory
|
||||
- (void)clearUpdateDirectory SPU_OBJC_DIRECT
|
||||
{
|
||||
if (self.updateDirectoryPath != nil) {
|
||||
if (_updateDirectoryPath != nil) {
|
||||
NSError *theError = nil;
|
||||
if (![[[SUFileManager alloc] init] removeItemAtURL:[NSURL fileURLWithPath:self.updateDirectoryPath] error:&theError]) {
|
||||
if (![[[SUFileManager alloc] init] removeItemAtURL:[NSURL fileURLWithPath:_updateDirectoryPath] error:&theError]) {
|
||||
SULog(SULogLevelError, @"Couldn't remove update folder: %@.", theError);
|
||||
}
|
||||
self.updateDirectoryPath = nil;
|
||||
_updateDirectoryPath = nil;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)unarchiverDidFailWithError:(NSError *)error
|
||||
- (void)unarchiverDidFailWithError:(NSError *)error SPU_OBJC_DIRECT
|
||||
{
|
||||
SULog(SULogLevelError, @"Failed to unarchive file");
|
||||
SULogError(error);
|
||||
|
||||
// No longer need update validator until next possible extraction (eg: if initial delta update fails)
|
||||
self.updateValidator = nil;
|
||||
_updateValidator = nil;
|
||||
|
||||
// Client could try update again with different inputs
|
||||
// Eg: one common case is if a delta update fails, client may want to fall back to regular update
|
||||
// We really only need to set updateDirectoryPath to nil since that's the field we check if we've received installation data,
|
||||
// but may as well set other fields to nil too
|
||||
[self clearUpdateDirectory];
|
||||
self.downloadName = nil;
|
||||
self.decryptionPassword = nil;
|
||||
self.signatures = nil;
|
||||
self.relaunchPath = nil;
|
||||
self.host = nil;
|
||||
_downloadName = nil;
|
||||
_extractionDirectory = nil;
|
||||
_decryptionPassword = nil;
|
||||
_signatures = nil;
|
||||
_relaunchPath = nil;
|
||||
_host = nil;
|
||||
|
||||
NSData *archivedError = SPUArchiveRootObjectSecurely(error);
|
||||
[self.communicator handleMessageWithIdentifier:SPUArchiveExtractionFailed data:archivedError != nil ? archivedError : [NSData data]];
|
||||
[_communicator handleMessageWithIdentifier:SPUArchiveExtractionFailed data:archivedError != nil ? archivedError : [NSData data]];
|
||||
}
|
||||
|
||||
- (void)agentConnectionDidInitiate
|
||||
{
|
||||
self.agentInitiatedConnection = YES;
|
||||
if (self.finishedValidation) {
|
||||
_agentInitiatedConnection = YES;
|
||||
if (_finishedValidation) {
|
||||
[self retrieveProcessIdentifierAndStartInstallation];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)agentConnectionDidInvalidate
|
||||
{
|
||||
if (!self.finishedValidation || !self.agentInitiatedConnection) {
|
||||
if (!_finishedValidation || !_agentInitiatedConnection || !_targetTerminated) {
|
||||
NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:@{ NSLocalizedDescriptionKey: @"Error: Agent connection invalidated before installation began" }];
|
||||
|
||||
NSError *agentError = self.agentConnection.invalidationError;
|
||||
NSError *agentError = _agentConnection.invalidationError;
|
||||
if (agentError != nil) {
|
||||
userInfo[NSUnderlyingErrorKey] = agentError;
|
||||
}
|
||||
@@ -307,35 +388,51 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)retrieveProcessIdentifierAndStartInstallation
|
||||
- (void)retrieveProcessIdentifierAndStartInstallation SPU_OBJC_DIRECT
|
||||
{
|
||||
// We use the relaunch path for the bundle to listen for termination instead of the host path
|
||||
// For a plug-in this makes a big difference; we want to wait until the app hosting the plug-in terminates
|
||||
// Otherwise for an app, the relaunch path and host path should be identical
|
||||
|
||||
[self.agentConnection.agent registerApplicationBundlePath:self.relaunchPath reply:^(NSNumber * _Nullable processIdentifier) {
|
||||
__block BOOL receivedResponse = NO;
|
||||
[_agentConnection.agent registerApplicationBundlePath:_relaunchPath reply:^(BOOL targetTerminated) {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
self.terminationListener = [[TerminationListener alloc] initWithProcessIdentifier:processIdentifier];
|
||||
receivedResponse = YES;
|
||||
|
||||
if (!targetTerminated) {
|
||||
[self->_agentConnection.agent listenForTerminationWithCompletion:^{
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
self->_targetTerminated = YES;
|
||||
|
||||
if (self->_performedStage1Installation) {
|
||||
[self finishInstallationAfterHostTermination];
|
||||
}
|
||||
});
|
||||
}];
|
||||
} else {
|
||||
self->_targetTerminated = YES;
|
||||
}
|
||||
|
||||
[self startInstallation];
|
||||
});
|
||||
}];
|
||||
|
||||
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(RETRIEVE_PROCESS_IDENTIFIER_TIMEOUT * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
|
||||
if (self.terminationListener == nil) {
|
||||
[self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Timeout error: failed to retreive process identifier from agent" }]];
|
||||
if (!receivedResponse) {
|
||||
[self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Timeout error: failed to retrieve process identifier from agent" }]];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
- (void)handleMessageWithIdentifier:(int32_t)identifier data:(NSData *)data
|
||||
{
|
||||
if (identifier == SPUInstallationData && self.updateDirectoryPath == nil) {
|
||||
if (identifier == SPUInstallationData && _updateDirectoryPath == nil) {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
// Mark that we have received the installation data
|
||||
// Do not rely on eg: self.updateDirectoryPath != nil because we may set it to nil again if an early stage fails (i.e, archive extraction)
|
||||
self.receivedInstallationData = YES;
|
||||
// Do not rely on eg: self->_updateDirectoryPath != nil because we may set it to nil again if an early stage fails (i.e, archive extraction)
|
||||
self->_receivedInstallationData = YES;
|
||||
|
||||
SPUInstallationInputData *installationData = (SPUInstallationInputData *)SPUUnarchiveRootObjectSecurely(data, [SPUInstallationInputData class]);
|
||||
SPUInstallationInputData *installationData = (data != nil) ? (SPUInstallationInputData *)SPUUnarchiveRootObjectSecurely(data, [SPUInstallationInputData class]) : nil;
|
||||
if (installationData == nil) {
|
||||
[self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Error: Failed to unarchive input installation data" }]];
|
||||
return;
|
||||
@@ -350,8 +447,8 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
|
||||
NSBundle *hostBundle = [NSBundle bundleWithPath:installationData.hostBundlePath];
|
||||
|
||||
NSString *bundleIdentifier = hostBundle.bundleIdentifier;
|
||||
if (bundleIdentifier == nil || ![bundleIdentifier isEqualToString:self.hostBundleIdentifier]) {
|
||||
[self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Error: Failed to match host bundle identifiers %@ and %@", self.hostBundleIdentifier, bundleIdentifier] }]];
|
||||
if (bundleIdentifier == nil || ![bundleIdentifier isEqualToString:self->_hostBundleIdentifier]) {
|
||||
[self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Error: Failed to match host bundle identifiers %@ and %@", self->_hostBundleIdentifier, bundleIdentifier] }]];
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -372,12 +469,83 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
|
||||
return;
|
||||
}
|
||||
|
||||
// Resolve the bookmark data for the downloaded update
|
||||
// See "Share file access between processes with URL bookmarks" in https://developer.apple.com/documentation/security/app_sandbox/accessing_files_from_the_macos_app_sandbox
|
||||
BOOL isStale = NO;
|
||||
NSError *bookmarkError = nil;
|
||||
NSURL *downloadURL = [NSURL URLByResolvingBookmarkData:installationData.updateURLBookmarkData options:NSURLBookmarkResolutionWithoutUI relativeToURL:nil bookmarkDataIsStale:&isStale error:&bookmarkError];
|
||||
if (downloadURL == nil) {
|
||||
[self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Error: Failed to resolve bookmark data from downloaded update", NSUnderlyingErrorKey: bookmarkError }]];
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate the download URL before moving it
|
||||
{
|
||||
NSArray<NSString *> *downloadURLPathComponents = downloadURL.URLByResolvingSymlinksInPath.pathComponents;
|
||||
if (downloadURLPathComponents == nil) {
|
||||
[self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Error: Failed to retrieve path components from download URL" }]];
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ([downloadURLPathComponents containsObject:@".."]) {
|
||||
[self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Error: download URL path components contains '..' which is unsafe" }]];
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (![downloadURLPathComponents containsObject:@SPARKLE_BUNDLE_IDENTIFIER] || ![downloadURLPathComponents containsObject:@"PersistentDownloads"]) {
|
||||
[self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Error: download URL path components does not contain PersistentDownloads or "@SPARKLE_BUNDLE_IDENTIFIER }]];
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (!isStale) {
|
||||
SULog(SULogLevelError, @"Error: bookmark data for update download is stale.. but still continuing.");
|
||||
}
|
||||
|
||||
NSString *originalDownloadName = downloadURL.lastPathComponent;
|
||||
if (originalDownloadName == nil) {
|
||||
[self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Error: Failed to retrieve download name from download URL" }]];
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Randomize the download name if possible
|
||||
// This adds better security if there are any vulnerabilities in extracting/executing archives
|
||||
// which allow writing in unexpected locations. For zip/tar/dmg archives we may also extract them before
|
||||
// performing signing validation (due to key rotation).
|
||||
NSString *downloadName;
|
||||
NSString *randomizedUUIDString = [[NSUUID UUID] UUIDString];
|
||||
if (randomizedUUIDString != nil) {
|
||||
// Find the real path extension of the download name
|
||||
// We cannot use -[NSString pathExtension] because it may not give us the full path extension
|
||||
// E.g. for "foo.tar.xz" we need "tar.xz", not "xz"
|
||||
NSString *downloadPathExtension;
|
||||
NSRange pathExtensionDelimiterRange = [originalDownloadName rangeOfString:@"."];
|
||||
if (pathExtensionDelimiterRange.location == NSNotFound) {
|
||||
downloadPathExtension = @"";
|
||||
} else {
|
||||
downloadPathExtension = [originalDownloadName substringFromIndex:pathExtensionDelimiterRange.location + 1];
|
||||
}
|
||||
|
||||
NSString *randomizedDownloadName = [randomizedUUIDString stringByAppendingPathExtension:downloadPathExtension];
|
||||
if (randomizedDownloadName != nil) {
|
||||
downloadName = randomizedDownloadName;
|
||||
} else {
|
||||
downloadName = originalDownloadName;
|
||||
}
|
||||
} else {
|
||||
downloadName = originalDownloadName;
|
||||
}
|
||||
|
||||
// Move the download archive to somewhere where probably only we will be touching it
|
||||
// This prevents eg: if a bug exists in the updater that removes files we are trying to install
|
||||
// When this tool is ran as root, we are moving it into a directory that only root will have access to
|
||||
NSURL *downloadURL = [[NSURL fileURLWithPath:installationData.updateDirectoryPath] URLByAppendingPathComponent:installationData.downloadName];
|
||||
|
||||
NSURL *downloadDestinationURL = [[NSURL fileURLWithPath:cacheInstallationPath] URLByAppendingPathComponent:installationData.downloadName];
|
||||
NSURL *downloadDestinationURL = [[NSURL fileURLWithPath:cacheInstallationPath] URLByAppendingPathComponent:downloadName];
|
||||
|
||||
NSError *moveError = nil;
|
||||
if (![[[SUFileManager alloc] init] moveItemAtURL:downloadURL toURL:downloadDestinationURL error:&moveError]) {
|
||||
@@ -407,25 +575,35 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
|
||||
return;
|
||||
}
|
||||
|
||||
// Carry these properities separately rather than using the SUInstallationInputData object
|
||||
NSString *extractionDirectory = [SPULocalCacheDirectory createUniqueDirectoryInDirectory:cacheInstallationPath];
|
||||
if (extractionDirectory == nil) {
|
||||
[self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Error: Failed to create installation extraction directory in %@", cacheInstallationPath] }]];
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Carry these properties separately rather than using the SUInstallationInputData object
|
||||
// Some of our properties may slightly differ than our input and we don't want to make the mistake of using one of those
|
||||
self.installationType = installationType;
|
||||
self.relaunchPath = installationData.relaunchPath;
|
||||
self.downloadName = installationData.downloadName;
|
||||
self.signatures = installationData.signatures;
|
||||
self.updateDirectoryPath = cacheInstallationPath;
|
||||
self.host = [[SUHost alloc] initWithBundle:hostBundle];
|
||||
self->_installationType = installationType;
|
||||
self->_relaunchPath = installationData.relaunchPath;
|
||||
self->_downloadName = downloadName;
|
||||
self->_signatures = installationData.signatures;
|
||||
self->_updateDirectoryPath = cacheInstallationPath;
|
||||
self->_extractionDirectory = extractionDirectory;
|
||||
self->_decryptionPassword = installationData.decryptionPassword;
|
||||
self->_host = [[SUHost alloc] initWithBundle:hostBundle];
|
||||
self->_verifierInformation = [[SPUVerifierInformation alloc] initWithExpectedVersion:installationData.expectedVersion expectedContentLength:installationData.expectedContentLength];
|
||||
|
||||
[self extractAndInstallUpdate];
|
||||
});
|
||||
} else if (identifier == SPUSentUpdateAppcastItemData) {
|
||||
SUAppcastItem *updateItem = (SUAppcastItem *)SPUUnarchiveRootObjectSecurely(data, [SUAppcastItem class]);
|
||||
SUAppcastItem *updateItem = (data != nil) ? (SUAppcastItem *)SPUUnarchiveRootObjectSecurely(data, [SUAppcastItem class]) : nil;
|
||||
if (updateItem != nil) {
|
||||
SPUInstallationInfo *installationInfo = [[SPUInstallationInfo alloc] initWithAppcastItem:updateItem canSilentlyInstall:[self.installer canInstallSilently]];
|
||||
SPUInstallationInfo *installationInfo = [[SPUInstallationInfo alloc] initWithAppcastItem:updateItem canSilentlyInstall:[_installer canInstallSilently]];
|
||||
|
||||
NSData *archivedData = SPUArchiveRootObjectSecurely(installationInfo);
|
||||
if (archivedData != nil) {
|
||||
[self.agentConnection.agent registerInstallationInfoData:archivedData];
|
||||
[_agentConnection.agent registerInstallationInfoData:archivedData];
|
||||
}
|
||||
}
|
||||
} else if (identifier == SPUResumeInstallationToStage2 && data.length == sizeof(uint8_t) * 2) {
|
||||
@@ -435,14 +613,23 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
|
||||
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
// This flag has an impact on interactive type installations and showing UI progress during non-interactive installations
|
||||
self.shouldShowUI = (BOOL)showsUI;
|
||||
self->_shouldShowUI = (BOOL)showsUI;
|
||||
// Don't test if the application was alive initially, leave that to the progress agent if we decide to relaunch
|
||||
self.shouldRelaunch = (BOOL)relaunch;
|
||||
self->_shouldRelaunch = (BOOL)relaunch;
|
||||
|
||||
if (self.performedStage1Installation) {
|
||||
if (self->_performedStage1Installation) {
|
||||
// Resume the installation if we aren't done with stage 2 yet, and remind the client we are prepared to relaunch
|
||||
dispatch_async(self.installerQueue, ^{
|
||||
[self performStage2InstallationIfNeeded];
|
||||
dispatch_async(self->_installerQueue, ^{
|
||||
if (!self->_performedStage2Installation) {
|
||||
[self performStage2Installation];
|
||||
} else if (!self->_performedStage3Installation) {
|
||||
// If we already performed the 2nd stage, re-purpose this request to re-try sending another termination signal
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
// Don't check if the target is already terminated, leave that to the progress agent
|
||||
// We could be slightly off if there were multiple instances running
|
||||
[self->_agentConnection.agent sendTerminationSignal];
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -451,19 +638,29 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
|
||||
[self cleanupAndExitWithStatus:0 error:nil];
|
||||
});
|
||||
} else if (identifier == SPUUpdaterAlivePong) {
|
||||
self.receivedUpdaterPong = YES;
|
||||
_receivedUpdaterPong = YES;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)startInstallation
|
||||
- (void)startInstallation SPU_OBJC_DIRECT
|
||||
{
|
||||
self.willCompleteInstallation = YES;
|
||||
_willCompleteInstallation = YES;
|
||||
|
||||
self.installerQueue = dispatch_queue_create("org.sparkle-project.sparkle.installer", DISPATCH_QUEUE_SERIAL);
|
||||
dispatch_queue_attr_t queuePriority = dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_USER_INITIATED, 0);
|
||||
|
||||
dispatch_async(self.installerQueue, ^{
|
||||
_installerQueue = dispatch_queue_create("org.sparkle-project.sparkle.installer", queuePriority);
|
||||
|
||||
#if SPARKLE_BUILD_PACKAGE_SUPPORT
|
||||
os_unfair_lock_lock(&_newConnectionLock);
|
||||
BOOL connectionCodeSigningValidationSkipped = self->_connectionCodeSigningValidationSkipped;
|
||||
os_unfair_lock_unlock(&_newConnectionLock);
|
||||
#else
|
||||
BOOL connectionCodeSigningValidationSkipped = NO;
|
||||
#endif
|
||||
|
||||
dispatch_async(_installerQueue, ^{
|
||||
NSError *installerError = nil;
|
||||
id <SUInstallerProtocol> installer = [SUInstaller installerForHost:self.host expectedInstallationType:self.installationType updateDirectory:self.updateDirectoryPath homeDirectory:self.homeDirectory userName:self.userName error:&installerError];
|
||||
id <SUInstallerProtocol> installer = [SUInstaller installerForHost:self->_host expectedInstallationType:self->_installationType updateDirectory:self->_extractionDirectory connectionCodeSigningValidationSkipped:connectionCodeSigningValidationSkipped homeDirectory:self->_homeDirectory userName:self->_userName error:&installerError];
|
||||
|
||||
if (installer == nil) {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
@@ -474,7 +671,7 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
|
||||
|
||||
NSError *firstStageError = nil;
|
||||
if (![installer performInitialInstallation:&firstStageError]) {
|
||||
self.installer = nil;
|
||||
self->_installer = nil;
|
||||
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Error: Failed to start installer", NSUnderlyingErrorKey: firstStageError }]];
|
||||
@@ -485,47 +682,45 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
|
||||
uint8_t canPerformSilentInstall = (uint8_t)[installer canInstallSilently];
|
||||
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
self.installer = installer;
|
||||
self->_installer = installer;
|
||||
|
||||
uint8_t targetTerminated = (uint8_t)self.terminationListener.terminated;
|
||||
os_unfair_lock_lock(&self->_newConnectionLock);
|
||||
self->_performedStage1Installation = YES;
|
||||
os_unfair_lock_unlock(&self->_newConnectionLock);
|
||||
|
||||
uint8_t sendInformation[] = {canPerformSilentInstall, targetTerminated};
|
||||
uint8_t sendInformation[] = {canPerformSilentInstall, (uint8_t)self->_targetTerminated};
|
||||
|
||||
NSData *sendData = [NSData dataWithBytes:sendInformation length:sizeof(sendInformation)];
|
||||
|
||||
[self.communicator handleMessageWithIdentifier:SPUInstallationFinishedStage1 data:sendData];
|
||||
[self->_communicator handleMessageWithIdentifier:SPUInstallationFinishedStage1 data:sendData];
|
||||
|
||||
self.performedStage1Installation = YES;
|
||||
|
||||
// Stage 2 can still be run before we finish installation
|
||||
// if the updater requests for it before the app is terminated
|
||||
[self finishInstallationAfterHostTermination];
|
||||
if (self->_targetTerminated) {
|
||||
// Stage 2 can still be run before we finish installation
|
||||
// if the updater requests for it before the app is terminated
|
||||
[self finishInstallationAfterHostTermination];
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
- (void)performStage2InstallationIfNeeded
|
||||
- (void)performStage2Installation SPU_OBJC_DIRECT
|
||||
{
|
||||
if (self.performedStage2Installation) {
|
||||
return;
|
||||
}
|
||||
|
||||
BOOL performedSecondStage = self.shouldShowUI || [self.installer canInstallSilently];
|
||||
if (performedSecondStage) {
|
||||
self.performedStage2Installation = YES;
|
||||
BOOL canPerformSecondStage = _shouldShowUI || [_installer canInstallSilently];
|
||||
if (canPerformSecondStage) {
|
||||
_performedStage2Installation = YES;
|
||||
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
uint8_t targetTerminated = (uint8_t)self.terminationListener.terminated;
|
||||
uint8_t targetTerminated = (uint8_t)self->_targetTerminated;
|
||||
|
||||
NSData *sendData = [NSData dataWithBytes:&targetTerminated length:sizeof(targetTerminated)];
|
||||
[self.communicator handleMessageWithIdentifier:SPUInstallationFinishedStage2 data:sendData];
|
||||
[self->_communicator handleMessageWithIdentifier:SPUInstallationFinishedStage2 data:sendData];
|
||||
|
||||
// Don't check if the target is already terminated, leave that to the progress agent
|
||||
// We could be slightly off if there were multiple instances running
|
||||
[self.agentConnection.agent sendTerminationSignal];
|
||||
[self->_agentConnection.agent sendTerminationSignal];
|
||||
});
|
||||
} else {
|
||||
self.installer = nil;
|
||||
_installer = nil;
|
||||
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Error: Failed to resume installer on stage 2 because installation cannot be installed silently" }]];
|
||||
@@ -533,76 +728,73 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)finishInstallationAfterHostTermination
|
||||
- (void)finishInstallationAfterHostTermination SPU_OBJC_DIRECT
|
||||
{
|
||||
[self.terminationListener startListeningWithCompletion:^(BOOL success) {
|
||||
if (!success) {
|
||||
[self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Failed to listen for application termination" }]];
|
||||
assert(self->_targetTerminated);
|
||||
|
||||
// Show our installer progress UI tool if only after a certain amount of time passes,
|
||||
// and if our installer is silent (i.e, doesn't show progress on its own)
|
||||
__block BOOL shouldShowUIProgress = YES;
|
||||
if (self->_shouldShowUI && [self->_installer canInstallSilently]) {
|
||||
// Ask the updater if it is still alive
|
||||
// If they are, we will receive a pong response back
|
||||
// Reset if we received a pong just to be on the safe side
|
||||
self->_receivedUpdaterPong = NO;
|
||||
[self->_communicator handleMessageWithIdentifier:SPUUpdaterAlivePing data:[NSData data]];
|
||||
|
||||
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(SUDisplayProgressTimeDelay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
|
||||
// Make sure we're still eligible for showing the installer progress
|
||||
// Also if the updater process is still alive, showing the progress should not be our duty
|
||||
// if the communicator object is nil, the updater definitely isn't alive. However, if it is not nil,
|
||||
// this does not necessarily mean the updater is alive, so we should also check if we got a recent response back from the updater
|
||||
if (shouldShowUIProgress && (!self->_receivedUpdaterPong || self->_communicator == nil)) {
|
||||
[self->_agentConnection.agent showProgress];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
dispatch_async(self->_installerQueue, ^{
|
||||
if (!self->_performedStage2Installation) {
|
||||
[self performStage2Installation];
|
||||
}
|
||||
|
||||
if (!self->_performedStage2Installation) {
|
||||
// We failed and we're going to exit shortly
|
||||
return;
|
||||
}
|
||||
|
||||
// Show our installer progress UI tool if only after a certain amount of time passes,
|
||||
// and if our installer is silent (i.e, doesn't show progress on its own)
|
||||
__block BOOL shouldShowUIProgress = YES;
|
||||
if (self.shouldShowUI && [self.installer canInstallSilently]) {
|
||||
// Ask the updater if it is still alive
|
||||
// If they are, we will receive a pong response back
|
||||
// Reset if we received a pong just to be on the safe side
|
||||
self.receivedUpdaterPong = NO;
|
||||
[self.communicator handleMessageWithIdentifier:SPUUpdaterAlivePing data:[NSData data]];
|
||||
|
||||
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(SUDisplayProgressTimeDelay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
|
||||
// Make sure we're still eligible for showing the installer progress
|
||||
// Also if the updater process is still alive, showing the progress should not be our duty
|
||||
// if the communicator object is nil, the updater definitely isn't alive. However, if it is not nil,
|
||||
// this does not necessarily mean the updater is alive, so we should also check if we got a recent response back from the updater
|
||||
if (shouldShowUIProgress && (!self.receivedUpdaterPong || self.communicator == nil)) {
|
||||
[self.agentConnection.agent showProgress];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
dispatch_async(self.installerQueue, ^{
|
||||
[self performStage2InstallationIfNeeded];
|
||||
|
||||
if (!self.performedStage2Installation) {
|
||||
// We failed and we're going to exit shortly
|
||||
return;
|
||||
}
|
||||
|
||||
NSError *thirdStageError = nil;
|
||||
if (![self.installer performFinalInstallationProgressBlock:nil error:&thirdStageError]) {
|
||||
[self.installer performCleanup];
|
||||
self.installer = nil;
|
||||
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Failed to finalize installation", NSUnderlyingErrorKey: thirdStageError }]];
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
self.performedStage3Installation = YES;
|
||||
NSError *thirdStageError = nil;
|
||||
if (![self->_installer performFinalInstallationProgressBlock:nil error:&thirdStageError]) {
|
||||
[self->_installer performCleanup];
|
||||
self->_installer = nil;
|
||||
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
// Make sure to stop our displayed progress before we move onto cleanup & relaunch
|
||||
// This will also stop the agent from broadcasting the status info service, which we want to do before
|
||||
// we relaunch the app because the relaunched app could check the service upon launch..
|
||||
[self.agentConnection.agent stopProgress];
|
||||
shouldShowUIProgress = NO;
|
||||
|
||||
[self.communicator handleMessageWithIdentifier:SPUInstallationFinishedStage3 data:[NSData data]];
|
||||
|
||||
if (self.shouldRelaunch) {
|
||||
// This will also signal to the agent that it will terminate soon
|
||||
[self.agentConnection.agent relaunchApplication];
|
||||
}
|
||||
|
||||
[self.installer performCleanup];
|
||||
|
||||
[self cleanupAndExitWithStatus:EXIT_SUCCESS error:nil];
|
||||
[self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Failed to finalize installation", NSUnderlyingErrorKey: thirdStageError }]];
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
self->_performedStage3Installation = YES;
|
||||
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
// Make sure to stop our displayed progress before we move onto cleanup & relaunch
|
||||
// This will also stop the agent from broadcasting the status info service, which we want to do before
|
||||
// we relaunch the app because the relaunched app could check the service upon launch..
|
||||
[self->_agentConnection.agent stopProgress];
|
||||
shouldShowUIProgress = NO;
|
||||
|
||||
[self->_communicator handleMessageWithIdentifier:SPUInstallationFinishedStage3 data:[NSData data]];
|
||||
|
||||
if (self->_shouldRelaunch) {
|
||||
// This will also signal to the agent that it will terminate soon
|
||||
[self->_agentConnection.agent relaunchApplication];
|
||||
}
|
||||
|
||||
[self->_installer performCleanup];
|
||||
|
||||
[self cleanupAndExitWithStatus:EXIT_SUCCESS error:nil];
|
||||
});
|
||||
}];
|
||||
});
|
||||
}
|
||||
|
||||
- (void)cleanupAndExitWithStatus:(int)status error:(NSError * _Nullable)error __attribute__((noreturn))
|
||||
@@ -612,20 +804,26 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
|
||||
|
||||
NSData *errorData = SPUArchiveRootObjectSecurely((NSError * _Nonnull)error);
|
||||
if (errorData != nil) {
|
||||
[self.communicator handleMessageWithIdentifier:SPUInstallerError data:errorData];
|
||||
[_communicator handleMessageWithIdentifier:SPUInstallerError data:errorData];
|
||||
}
|
||||
}
|
||||
|
||||
// It's nice to tell the other end we're invalidating
|
||||
|
||||
[self.activeConnection invalidate];
|
||||
self.activeConnection = nil;
|
||||
os_unfair_lock_lock(&_newConnectionLock);
|
||||
|
||||
[self.xpcListener invalidate];
|
||||
self.xpcListener = nil;
|
||||
NSXPCConnection *activeConnection = _activeConnection;
|
||||
_activeConnection = nil;
|
||||
|
||||
[self.agentConnection invalidate];
|
||||
self.agentConnection = nil;
|
||||
os_unfair_lock_unlock(&_newConnectionLock);
|
||||
|
||||
[activeConnection invalidate];
|
||||
|
||||
[_xpcListener invalidate];
|
||||
_xpcListener = nil;
|
||||
|
||||
[_agentConnection invalidate];
|
||||
_agentConnection = nil;
|
||||
|
||||
[self clearUpdateDirectory];
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
#import "SPUDeltaArchiveProtocol.h"
|
||||
#import "SPUSparkleDeltaArchive.h"
|
||||
#import "SPUXarDeltaArchive.h"
|
||||
#import <CommonCrypto/CommonDigest.h>
|
||||
#import "SUBinaryDeltaCommon.h"
|
||||
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
@@ -23,6 +23,7 @@ id<SPUDeltaArchiveProtocol> SPUDeltaArchiveReadPatchAndHeader(NSString *patchFil
|
||||
|
||||
SPUDeltaArchiveHeader *header = [sparkleArchive readHeader];
|
||||
if (header == nil) {
|
||||
#if SPARKLE_BUILD_LEGACY_DELTA_SUPPORT
|
||||
NSError *archiveError = sparkleArchive.error;
|
||||
if (archiveError != nil && [archiveError.domain isEqualToString:SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN] && archiveError.code == SPARKLE_DELTA_ARCHIVE_ERROR_CODE_BAD_MAGIC) {
|
||||
// Retry with XAR archive if the magic value is unexpected
|
||||
@@ -35,7 +36,9 @@ id<SPUDeltaArchiveProtocol> SPUDeltaArchiveReadPatchAndHeader(NSString *patchFil
|
||||
*outHeader = xarHeader;
|
||||
}
|
||||
return xarArchive;
|
||||
} else {
|
||||
} else
|
||||
#endif
|
||||
{
|
||||
if (outHeader != NULL) {
|
||||
*outHeader = nil;
|
||||
}
|
||||
@@ -56,7 +59,9 @@ id<SPUDeltaArchiveProtocol> SPUDeltaArchiveReadPatchAndHeader(NSString *patchFil
|
||||
@synthesize clonedRelativePath = _clonedRelativePath;
|
||||
@synthesize sourcePath = _sourcePath;
|
||||
@synthesize commands = _commands;
|
||||
#if SPARKLE_BUILD_LEGACY_DELTA_SUPPORT
|
||||
@synthesize xarContext = _xarContext;
|
||||
#endif
|
||||
@synthesize mode = _mode;
|
||||
@synthesize codedDataLength = _codedDataLength;
|
||||
|
||||
@@ -75,8 +80,8 @@ id<SPUDeltaArchiveProtocol> SPUDeltaArchiveReadPatchAndHeader(NSString *patchFil
|
||||
|
||||
@implementation SPUDeltaArchiveHeader
|
||||
{
|
||||
unsigned char _beforeTreeHash[CC_SHA1_DIGEST_LENGTH];
|
||||
unsigned char _afterTreeHash[CC_SHA1_DIGEST_LENGTH];
|
||||
unsigned char _beforeTreeHash[BINARY_DELTA_HASH_LENGTH];
|
||||
unsigned char _afterTreeHash[BINARY_DELTA_HASH_LENGTH];
|
||||
}
|
||||
|
||||
@synthesize compression = _compression;
|
||||
@@ -84,8 +89,9 @@ id<SPUDeltaArchiveProtocol> SPUDeltaArchiveReadPatchAndHeader(NSString *patchFil
|
||||
@synthesize fileSystemCompression = _fileSystemCompression;
|
||||
@synthesize majorVersion = _majorVersion;
|
||||
@synthesize minorVersion = _minorVersion;
|
||||
@synthesize bundleCreationDate = _bundleCreationDate;
|
||||
|
||||
- (instancetype)initWithCompression:(SPUDeltaCompressionMode)compression compressionLevel:(uint8_t)compressionLevel fileSystemCompression:(bool)fileSystemCompression majorVersion:(uint16_t)majorVersion minorVersion:(uint16_t)minorVersion beforeTreeHash:(const unsigned char *)beforeTreeHash afterTreeHash:(const unsigned char *)afterTreeHash
|
||||
- (instancetype)initWithCompression:(SPUDeltaCompressionMode)compression compressionLevel:(uint8_t)compressionLevel fileSystemCompression:(bool)fileSystemCompression majorVersion:(uint16_t)majorVersion minorVersion:(uint16_t)minorVersion beforeTreeHash:(const unsigned char *)beforeTreeHash afterTreeHash:(const unsigned char *)afterTreeHash bundleCreationDate:(nullable NSDate *)bundleCreationDate
|
||||
{
|
||||
self = [super init];
|
||||
if (self != nil)
|
||||
@@ -99,13 +105,12 @@ id<SPUDeltaArchiveProtocol> SPUDeltaArchiveReadPatchAndHeader(NSString *patchFil
|
||||
|
||||
memcpy(_beforeTreeHash, beforeTreeHash, sizeof(_beforeTreeHash));
|
||||
memcpy(_afterTreeHash, afterTreeHash, sizeof(_afterTreeHash));
|
||||
|
||||
_bundleCreationDate = bundleCreationDate;
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wdirect-ivar-access"
|
||||
|
||||
- (unsigned char *)beforeTreeHash
|
||||
{
|
||||
return _beforeTreeHash;
|
||||
@@ -116,6 +121,4 @@ id<SPUDeltaArchiveProtocol> SPUDeltaArchiveReadPatchAndHeader(NSString *patchFil
|
||||
return _afterTreeHash;
|
||||
}
|
||||
|
||||
#pragma clang diagnostic pop
|
||||
|
||||
@end
|
||||
@@ -24,9 +24,9 @@ typedef NS_ENUM(uint8_t, SPUDeltaItemCommands) {
|
||||
};
|
||||
|
||||
// Represents header for our archive
|
||||
@interface SPUDeltaArchiveHeader : NSObject
|
||||
SPU_OBJC_DIRECT_MEMBERS @interface SPUDeltaArchiveHeader : NSObject
|
||||
|
||||
- (instancetype)initWithCompression:(SPUDeltaCompressionMode)compression compressionLevel:(uint8_t)compressionLevel fileSystemCompression:(bool)fileSystemCompression majorVersion:(uint16_t)majorVersion minorVersion:(uint16_t)minorVersion beforeTreeHash:(const unsigned char *)beforeTreeHash afterTreeHash:(const unsigned char *)afterTreeHash;
|
||||
- (instancetype)initWithCompression:(SPUDeltaCompressionMode)compression compressionLevel:(uint8_t)compressionLevel fileSystemCompression:(bool)fileSystemCompression majorVersion:(uint16_t)majorVersion minorVersion:(uint16_t)minorVersion beforeTreeHash:(const unsigned char *)beforeTreeHash afterTreeHash:(const unsigned char *)afterTreeHash bundleCreationDate:(nullable NSDate *)bundleCreationDate;
|
||||
|
||||
@property (nonatomic, readonly) SPUDeltaCompressionMode compression;
|
||||
@property (nonatomic, readonly) uint8_t compressionLevel;
|
||||
@@ -35,11 +35,12 @@ typedef NS_ENUM(uint8_t, SPUDeltaItemCommands) {
|
||||
@property (nonatomic, readonly) uint16_t minorVersion;
|
||||
@property (nonatomic, readonly) unsigned char *beforeTreeHash;
|
||||
@property (nonatomic, readonly) unsigned char *afterTreeHash;
|
||||
@property (nonatomic, readonly, nullable) NSDate *bundleCreationDate;
|
||||
|
||||
@end
|
||||
|
||||
// Represents an item we read or write to in our delta archive
|
||||
@interface SPUDeltaArchiveItem : NSObject
|
||||
SPU_OBJC_DIRECT_MEMBERS @interface SPUDeltaArchiveItem : NSObject
|
||||
|
||||
- (instancetype)initWithRelativeFilePath:(NSString *)relativeFilePath commands:(SPUDeltaItemCommands)commands mode:(uint16_t)mode;
|
||||
|
||||
@@ -58,8 +59,10 @@ typedef NS_ENUM(uint8_t, SPUDeltaItemCommands) {
|
||||
@property (nonatomic) uint16_t mode;
|
||||
|
||||
// Private properties
|
||||
#if SPARKLE_BUILD_LEGACY_DELTA_SUPPORT
|
||||
// xar_file context for Xar delta archiver
|
||||
@property (nonatomic, nullable) const void *xarContext;
|
||||
#endif
|
||||
// Tracking length of item's data in data section, when encoding items and when extracting items
|
||||
@property (nonatomic) uint64_t codedDataLength;
|
||||
|
||||
|
||||
@@ -12,9 +12,9 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@class SUAppcastItem;
|
||||
|
||||
@interface SPUInstallationInfo : NSObject <NSSecureCoding>
|
||||
SPU_OBJC_DIRECT_MEMBERS @interface SPUInstallationInfo : NSObject <NSSecureCoding>
|
||||
|
||||
- (instancetype)initWithAppcastItem:(SUAppcastItem *)appcastItem canSilentlyInstall:(BOOL)canSilentyInstall;
|
||||
- (instancetype)initWithAppcastItem:(SUAppcastItem *)appcastItem canSilentlyInstall:(BOOL)canSilentlyInstall;
|
||||
|
||||
@property (nonatomic, readonly) SUAppcastItem *appcastItem;
|
||||
@property (nonatomic, readonly) BOOL canSilentlyInstall;
|
||||
|
||||
@@ -52,9 +52,9 @@ static NSString *SUSystemDomainKey = @"SUSystemDomain";
|
||||
|
||||
- (void)encodeWithCoder:(NSCoder *)coder
|
||||
{
|
||||
[coder encodeObject:self.appcastItem forKey:SUAppcastItemKey];
|
||||
[coder encodeBool:self.canSilentlyInstall forKey:SUCanSilentlyInstallKey];
|
||||
[coder encodeBool:self.systemDomain forKey:SUSystemDomainKey];
|
||||
[coder encodeObject:_appcastItem forKey:SUAppcastItemKey];
|
||||
[coder encodeBool:_canSilentlyInstall forKey:SUCanSilentlyInstallKey];
|
||||
[coder encodeBool:_systemDomain forKey:SUSystemDomainKey];
|
||||
}
|
||||
|
||||
+ (BOOL)supportsSecureCoding
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface SPUInstallationInputData : NSObject <NSSecureCoding>
|
||||
SPU_OBJC_DIRECT_MEMBERS @interface SPUInstallationInputData : NSObject <NSSecureCoding>
|
||||
|
||||
/*
|
||||
* relaunchPath - path to application bundle to relaunch and listen for termination
|
||||
@@ -21,16 +21,19 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
* downloadName - name of update archive in update directory
|
||||
* signatures - signatures for the update that came from the appcast item
|
||||
* decryptionPassword - optional decryption password for dmg archives
|
||||
* expectedVersion - optional expected version of the new update
|
||||
* expectedContentLength - optional expected content length of the new download archive
|
||||
*/
|
||||
- (instancetype)initWithRelaunchPath:(NSString *)relaunchPath hostBundlePath:(NSString *)hostBundlePath updateDirectoryPath:(NSString *)updateDirectoryPath downloadName:(NSString *)downloadName installationType:(NSString *)installationType signatures:(SUSignatures * _Nullable)signatures decryptionPassword:(nullable NSString *)decryptionPassword;
|
||||
- (instancetype)initWithRelaunchPath:(NSString *)relaunchPath hostBundlePath:(NSString *)hostBundlePath updateURLBookmarkData:(NSData *)updateURLBookmarkData installationType:(NSString *)installationType signatures:(SUSignatures * _Nullable)signatures decryptionPassword:(nullable NSString *)decryptionPassword expectedVersion:(NSString *)expectedVersion expectedContentLength:(uint64_t)expectedContentLength;
|
||||
|
||||
@property (nonatomic, copy, readonly) NSString *relaunchPath;
|
||||
@property (nonatomic, copy, readonly) NSString *hostBundlePath;
|
||||
@property (nonatomic, copy, readonly) NSString *updateDirectoryPath;
|
||||
@property (nonatomic, copy, readonly) NSString *downloadName;
|
||||
@property (nonatomic, copy, readonly) NSData *updateURLBookmarkData;
|
||||
@property (nonatomic, copy, readonly) NSString *installationType;
|
||||
@property (nonatomic, readonly, nullable) SUSignatures *signatures; // nullable because although not using signatures is deprecated, it's still supported
|
||||
@property (nonatomic, copy, readonly, nullable) NSString *decryptionPassword;
|
||||
@property (nonatomic, copy, readonly, nullable) NSString *expectedVersion;
|
||||
@property (nonatomic, readonly) uint64_t expectedContentLength;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
@@ -14,36 +14,40 @@
|
||||
|
||||
static NSString *SURelaunchPathKey = @"SURelaunchPath";
|
||||
static NSString *SUHostBundlePathKey = @"SUHostBundlePath";
|
||||
static NSString *SUUpdateDirectoryPathKey = @"SUUpdateDirectoryPath";
|
||||
static NSString *SUDownloadNameKey = @"SUDownloadName";
|
||||
static NSString *SUUpdateURLBookmarkDataKey = @"SUUpdateURLBookmarkData";
|
||||
static NSString *SUSignaturesKey = @"SUSignatures";
|
||||
static NSString *SUDecryptionPasswordKey = @"SUDecryptionPassword";
|
||||
static NSString *SUInstallationTypeKey = @"SUInstallationType";
|
||||
static NSString *SUExpectedVersionKey = @"SUExpectedVersion";
|
||||
static NSString *SUExpectedContentLength = @"SUExpectedContentLength";
|
||||
|
||||
@implementation SPUInstallationInputData
|
||||
|
||||
@synthesize relaunchPath = _relaunchPath;
|
||||
@synthesize hostBundlePath = _hostBundlePath;
|
||||
@synthesize updateDirectoryPath = _updateDirectoryPath;
|
||||
@synthesize downloadName = _downloadName;
|
||||
@synthesize updateURLBookmarkData = _updateURLBookmarkData;
|
||||
@synthesize signatures = _signatures;
|
||||
@synthesize decryptionPassword = _decryptionPassword;
|
||||
@synthesize installationType = _installationType;
|
||||
@synthesize expectedVersion = _expectedVersion;
|
||||
@synthesize expectedContentLength = _expectedContentLength;
|
||||
|
||||
- (instancetype)initWithRelaunchPath:(NSString *)relaunchPath hostBundlePath:(NSString *)hostBundlePath updateDirectoryPath:(NSString *)updateDirectoryPath downloadName:(NSString *)downloadName installationType:(NSString *)installationType signatures:(SUSignatures * _Nullable)signatures decryptionPassword:(nullable NSString *)decryptionPassword
|
||||
- (instancetype)initWithRelaunchPath:(NSString *)relaunchPath hostBundlePath:(NSString *)hostBundlePath updateURLBookmarkData:(NSData *)updateURLBookmarkData installationType:(NSString *)installationType signatures:(SUSignatures * _Nullable)signatures decryptionPassword:(nullable NSString *)decryptionPassword expectedVersion:(nonnull NSString *)expectedVersion expectedContentLength:(uint64_t)expectedContentLength
|
||||
{
|
||||
self = [super init];
|
||||
if (self != nil) {
|
||||
_relaunchPath = [relaunchPath copy];
|
||||
_hostBundlePath = [hostBundlePath copy];
|
||||
_updateDirectoryPath = [updateDirectoryPath copy];
|
||||
_downloadName = [downloadName copy];
|
||||
_updateURLBookmarkData = updateURLBookmarkData;
|
||||
|
||||
_installationType = [installationType copy];
|
||||
assert(SPUValidInstallationType(_installationType));
|
||||
|
||||
_signatures = signatures;
|
||||
_decryptionPassword = [decryptionPassword copy];
|
||||
|
||||
_expectedVersion = [expectedVersion copy];
|
||||
_expectedContentLength = expectedContentLength;
|
||||
}
|
||||
return self;
|
||||
}
|
||||
@@ -60,13 +64,8 @@ static NSString *SUInstallationTypeKey = @"SUInstallationType";
|
||||
return nil;
|
||||
}
|
||||
|
||||
NSString *updateDirectoryPath = [decoder decodeObjectOfClass:[NSString class] forKey:SUUpdateDirectoryPathKey];
|
||||
if (updateDirectoryPath == nil) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
NSString *downloadName = [decoder decodeObjectOfClass:[NSString class] forKey:SUDownloadNameKey];
|
||||
if (downloadName == nil) {
|
||||
NSData *updateURLBookmarkData = [decoder decodeObjectOfClass:[NSData class] forKey:SUUpdateURLBookmarkDataKey];
|
||||
if (updateURLBookmarkData == nil) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
@@ -82,20 +81,26 @@ static NSString *SUInstallationTypeKey = @"SUInstallationType";
|
||||
|
||||
NSString *decryptionPassword = [decoder decodeObjectOfClass:[NSString class] forKey:SUDecryptionPasswordKey];
|
||||
|
||||
return [self initWithRelaunchPath:relaunchPath hostBundlePath:hostBundlePath updateDirectoryPath:updateDirectoryPath downloadName:downloadName installationType:installationType signatures:signatures decryptionPassword:decryptionPassword];
|
||||
NSString *expectedVersion = [decoder decodeObjectOfClass:[NSString class] forKey:SUExpectedVersionKey];
|
||||
uint64_t expectedContentLength = (uint64_t)[decoder decodeInt64ForKey:SUExpectedContentLength];
|
||||
|
||||
return [self initWithRelaunchPath:relaunchPath hostBundlePath:hostBundlePath updateURLBookmarkData:updateURLBookmarkData installationType:installationType signatures:signatures decryptionPassword:decryptionPassword expectedVersion:expectedVersion expectedContentLength:expectedContentLength];
|
||||
}
|
||||
|
||||
- (void)encodeWithCoder:(NSCoder *)coder
|
||||
{
|
||||
[coder encodeObject:self.relaunchPath forKey:SURelaunchPathKey];
|
||||
[coder encodeObject:self.hostBundlePath forKey:SUHostBundlePathKey];
|
||||
[coder encodeObject:self.updateDirectoryPath forKey:SUUpdateDirectoryPathKey];
|
||||
[coder encodeObject:self.installationType forKey:SUInstallationTypeKey];
|
||||
[coder encodeObject:self.downloadName forKey:SUDownloadNameKey];
|
||||
[coder encodeObject:self.signatures forKey:SUSignaturesKey];
|
||||
if (self.decryptionPassword != nil) {
|
||||
[coder encodeObject:self.decryptionPassword forKey:SUDecryptionPasswordKey];
|
||||
[coder encodeObject:_relaunchPath forKey:SURelaunchPathKey];
|
||||
[coder encodeObject:_hostBundlePath forKey:SUHostBundlePathKey];
|
||||
[coder encodeObject:_updateURLBookmarkData forKey:SUUpdateURLBookmarkDataKey];
|
||||
[coder encodeObject:_installationType forKey:SUInstallationTypeKey];
|
||||
[coder encodeObject:_signatures forKey:SUSignaturesKey];
|
||||
if (_decryptionPassword != nil) {
|
||||
[coder encodeObject:_decryptionPassword forKey:SUDecryptionPasswordKey];
|
||||
}
|
||||
if (_expectedVersion != nil) {
|
||||
[coder encodeObject:_expectedVersion forKey:SUExpectedVersionKey];
|
||||
}
|
||||
[coder encodeInt64:(int64_t)_expectedContentLength forKey:SUExpectedContentLength];
|
||||
}
|
||||
|
||||
+ (BOOL)supportsSecureCoding
|
||||
|
||||
@@ -97,7 +97,7 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
(P number of blobs where P <= M commands)
|
||||
(Indexes for data blobs correspond to indexes for a filtered list of applicable commands (EXTRACT_FILE, BINARY_DIFF_FILE) that have data content)
|
||||
*/
|
||||
@interface SPUSparkleDeltaArchive : NSObject <SPUDeltaArchiveProtocol>
|
||||
SPU_OBJC_DIRECT_MEMBERS @interface SPUSparkleDeltaArchive : NSObject <SPUDeltaArchiveProtocol>
|
||||
|
||||
- (instancetype)initWithPatchFileForWriting:(NSString *)patchFile;
|
||||
- (instancetype)initWithPatchFileForReading:(NSString *)patchFile;
|
||||
|
||||
+213
-174
@@ -7,12 +7,15 @@
|
||||
//
|
||||
|
||||
#import "SPUSparkleDeltaArchive.h"
|
||||
#import <bzlib.h>
|
||||
#import <sys/stat.h>
|
||||
#import <CommonCrypto/CommonDigest.h>
|
||||
#import "SUBinaryDeltaCommon.h"
|
||||
#import <compression.h>
|
||||
|
||||
#if SPARKLE_BUILD_BZIP2_DELTA_SUPPORT
|
||||
#import <bzlib.h>
|
||||
#endif
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
|
||||
#define SPARKLE_DELTA_FORMAT_MAGIC "spk!"
|
||||
@@ -28,39 +31,26 @@ typedef struct
|
||||
bool fileSystemCompression : 1;
|
||||
} SparkleDeltaArchiveMetadata;
|
||||
|
||||
@interface SPUSparkleDeltaArchive ()
|
||||
|
||||
@property (nonatomic) FILE *file;
|
||||
@property (nonatomic) BZFILE *bzipFile;
|
||||
@property (nonatomic) compression_stream compressionStream;
|
||||
@property (nonatomic) BOOL initializedCompressionStream;
|
||||
@property (nonatomic, readonly) NSString *patchFile;
|
||||
@property (nonatomic) SPUDeltaCompressionMode compression;
|
||||
@property (nonatomic, readonly) BOOL writeMode;
|
||||
@property (nonatomic) NSError *error;
|
||||
@property (nonatomic) void *partialChunkBuffer;
|
||||
@property (nonatomic) void *compressionBuffer;
|
||||
|
||||
@property (nonatomic) NSMutableArray<SPUDeltaArchiveItem *> *writableItems;
|
||||
|
||||
@end
|
||||
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wdirect-ivar-access"
|
||||
|
||||
@implementation SPUSparkleDeltaArchive
|
||||
{
|
||||
FILE *_file;
|
||||
#if SPARKLE_BUILD_BZIP2_DELTA_SUPPORT
|
||||
BZFILE *_bzipFile;
|
||||
#endif
|
||||
NSString *_patchFile;
|
||||
NSError *_error;
|
||||
void *_partialChunkBuffer;
|
||||
void *_compressionBuffer;
|
||||
NSMutableArray<SPUDeltaArchiveItem *> *_writableItems;
|
||||
|
||||
compression_stream _compressionStream;
|
||||
SPUDeltaCompressionMode _compression;
|
||||
|
||||
BOOL _initializedCompressionStream;
|
||||
BOOL _writeMode;
|
||||
}
|
||||
|
||||
@synthesize file = _file;
|
||||
@synthesize bzipFile = _bzipFile;
|
||||
@synthesize compressionStream = _compressionStream;
|
||||
@synthesize initializedCompressionStream = _initializedCompressionStream;
|
||||
@synthesize patchFile = _patchFile;
|
||||
@synthesize compression = _compression;
|
||||
@synthesize writeMode = _writeMode;
|
||||
@synthesize writableItems = _writableItems;
|
||||
@synthesize error = _error;
|
||||
@synthesize partialChunkBuffer = _partialChunkBuffer;
|
||||
@synthesize compressionBuffer = _compressionBuffer;
|
||||
|
||||
+ (BOOL)maySupportSafeExtraction
|
||||
{
|
||||
@@ -94,42 +84,45 @@ typedef struct
|
||||
|
||||
- (void)close
|
||||
{
|
||||
if (self.bzipFile != NULL) {
|
||||
if (!self.writeMode) {
|
||||
#if SPARKLE_BUILD_BZIP2_DELTA_SUPPORT
|
||||
if (_bzipFile != NULL) {
|
||||
if (!_writeMode) {
|
||||
int bzerror = 0;
|
||||
BZ2_bzReadClose(&bzerror, self.bzipFile);
|
||||
BZ2_bzReadClose(&bzerror, _bzipFile);
|
||||
}
|
||||
|
||||
self.bzipFile = NULL;
|
||||
} else if (self.initializedCompressionStream) {
|
||||
_bzipFile = NULL;
|
||||
} else
|
||||
#endif
|
||||
if (_initializedCompressionStream) {
|
||||
compression_stream_destroy(&_compressionStream);
|
||||
self.initializedCompressionStream = NO;
|
||||
_initializedCompressionStream = NO;
|
||||
}
|
||||
|
||||
if (self.file != NULL) {
|
||||
fclose(self.file);
|
||||
self.file = NULL;
|
||||
if (_file != NULL) {
|
||||
fclose(_file);
|
||||
_file = NULL;
|
||||
}
|
||||
|
||||
free(self.partialChunkBuffer);
|
||||
self.partialChunkBuffer = NULL;
|
||||
free(_partialChunkBuffer);
|
||||
_partialChunkBuffer = NULL;
|
||||
|
||||
free(self.compressionBuffer);
|
||||
self.compressionBuffer = NULL;
|
||||
free(_compressionBuffer);
|
||||
_compressionBuffer = NULL;
|
||||
}
|
||||
|
||||
- (BOOL)createBuffers
|
||||
- (BOOL)createBuffers SPU_OBJC_DIRECT
|
||||
{
|
||||
self.partialChunkBuffer = calloc(1, PARTIAL_IO_CHUNK_SIZE);
|
||||
if (self.partialChunkBuffer == NULL) {
|
||||
self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to calloc() %d bytes for partial chunk buffer.", PARTIAL_IO_CHUNK_SIZE] }];
|
||||
_partialChunkBuffer = calloc(1, PARTIAL_IO_CHUNK_SIZE);
|
||||
if (_partialChunkBuffer == NULL) {
|
||||
_error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to calloc() %d bytes for partial chunk buffer.", PARTIAL_IO_CHUNK_SIZE] }];
|
||||
return NO;
|
||||
}
|
||||
|
||||
if (self.initializedCompressionStream) {
|
||||
self.compressionBuffer = calloc(1, COMPRESSION_BUFFER_SIZE);
|
||||
if (self.compressionBuffer == NULL) {
|
||||
self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to calloc() %d bytes for compression buffer.", COMPRESSION_BUFFER_SIZE] }];
|
||||
if (_initializedCompressionStream) {
|
||||
_compressionBuffer = calloc(1, COMPRESSION_BUFFER_SIZE);
|
||||
if (_compressionBuffer == NULL) {
|
||||
_error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to calloc() %d bytes for compression buffer.", COMPRESSION_BUFFER_SIZE] }];
|
||||
return NO;
|
||||
}
|
||||
}
|
||||
@@ -137,48 +130,53 @@ typedef struct
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (BOOL)_readBuffer:(void *)buffer length:(int32_t)length
|
||||
- (BOOL)_readBuffer:(void *)buffer length:(int32_t)length SPU_OBJC_DIRECT
|
||||
{
|
||||
if (self.error != nil) {
|
||||
if (_error != nil) {
|
||||
return NO;
|
||||
}
|
||||
|
||||
switch (self.compression) {
|
||||
switch (_compression) {
|
||||
case SPUDeltaCompressionModeNone: {
|
||||
if (fread(buffer, (size_t)length, 1, self.file) < 1) {
|
||||
self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to read %d uncompressed bytes from archive.", length] }];
|
||||
if (fread(buffer, (size_t)length, 1, _file) < 1) {
|
||||
_error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to read %d uncompressed bytes from archive.", length] }];
|
||||
return NO;
|
||||
} else {
|
||||
return YES;
|
||||
}
|
||||
}
|
||||
case SPUDeltaCompressionModeBzip2: {
|
||||
case SPUDeltaCompressionModeBzip2:
|
||||
{
|
||||
#if SPARKLE_BUILD_BZIP2_DELTA_SUPPORT
|
||||
int bzerror = 0;
|
||||
int bytesRead = BZ2_bzRead(&bzerror, self.bzipFile, buffer, length);
|
||||
int bytesRead = BZ2_bzRead(&bzerror, _bzipFile, buffer, length);
|
||||
|
||||
switch (bzerror) {
|
||||
case BZ_OK:
|
||||
case BZ_STREAM_END:
|
||||
if (bytesRead < length) {
|
||||
self.error = [NSError errorWithDomain:SPARKLE_BZIP2_ERROR_DOMAIN code:0 userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Only %d out of %d expected bytes were read from the bz2 archive.", bytesRead, length] }];
|
||||
_error = [NSError errorWithDomain:SPARKLE_BZIP2_ERROR_DOMAIN code:0 userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Only %d out of %d expected bytes were read from the bz2 archive.", bytesRead, length] }];
|
||||
return NO;
|
||||
} else {
|
||||
return YES;
|
||||
}
|
||||
case BZ_IO_ERROR:
|
||||
self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: @"Encountered unexpected IO error when reading compressed bytes from bz2 archive." }];
|
||||
_error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: @"Encountered unexpected IO error when reading compressed bytes from bz2 archive." }];
|
||||
return NO;
|
||||
default:
|
||||
self.error = [NSError errorWithDomain:SPARKLE_BZIP2_ERROR_DOMAIN code:bzerror userInfo:@{ NSLocalizedDescriptionKey: @"Encountered unexpected error when reading compressed bytes from bz2 archive." }];
|
||||
_error = [NSError errorWithDomain:SPARKLE_BZIP2_ERROR_DOMAIN code:bzerror userInfo:@{ NSLocalizedDescriptionKey: @"Encountered unexpected error when reading compressed bytes from bz2 archive." }];
|
||||
return NO;
|
||||
}
|
||||
#else
|
||||
return NO;
|
||||
#endif
|
||||
}
|
||||
case SPUDeltaCompressionModeLZMA:
|
||||
case SPUDeltaCompressionModeLZFSE:
|
||||
case SPUDeltaCompressionModeLZ4:
|
||||
case SPUDeltaCompressionModeZLIB: {
|
||||
FILE *file = self.file;
|
||||
void *compressionBuffer = self.compressionBuffer;
|
||||
FILE *file = _file;
|
||||
void *compressionBuffer = _compressionBuffer;
|
||||
|
||||
_compressionStream.dst_ptr = buffer;
|
||||
_compressionStream.dst_size = (size_t)length;
|
||||
@@ -190,7 +188,7 @@ typedef struct
|
||||
size_t bytesRead = fread(compressionBuffer, 1, COMPRESSION_BUFFER_SIZE, file);
|
||||
if (bytesRead < COMPRESSION_BUFFER_SIZE) {
|
||||
if (feof(file) == 0) {
|
||||
self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to read %d compressed raw bytes from archive.", length] }];
|
||||
_error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to read %d compressed raw bytes from archive.", length] }];
|
||||
return NO;
|
||||
}
|
||||
}
|
||||
@@ -202,13 +200,13 @@ typedef struct
|
||||
|
||||
compression_status status = compression_stream_process(&_compressionStream, feof(file) != 0 ? COMPRESSION_STREAM_FINALIZE : 0);
|
||||
if (status == COMPRESSION_STATUS_ERROR) {
|
||||
self.error = [NSError errorWithDomain:SPARKLE_COMPRESSION_ERROR_DOMAIN code:COMPRESSION_STATUS_ERROR userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to read %d compressed bytes.", length] }];
|
||||
_error = [NSError errorWithDomain:SPARKLE_COMPRESSION_ERROR_DOMAIN code:COMPRESSION_STATUS_ERROR userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to read %d compressed bytes.", length] }];
|
||||
return NO;
|
||||
}
|
||||
|
||||
if (status == COMPRESSION_STATUS_END && _compressionStream.dst_size > 0) {
|
||||
// We're expecting more bytes but we can't read any more bytes
|
||||
self.error = [NSError errorWithDomain:SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN code:-1 userInfo:@{ NSLocalizedDescriptionKey: @"Failed to decompress and read bytes because we reached EOF" }];
|
||||
_error = [NSError errorWithDomain:SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN code:-1 userInfo:@{ NSLocalizedDescriptionKey: @"Failed to decompress and read bytes because we reached EOF" }];
|
||||
return NO;
|
||||
}
|
||||
}
|
||||
@@ -218,7 +216,7 @@ typedef struct
|
||||
}
|
||||
}
|
||||
|
||||
static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMode compressionMode)
|
||||
static compression_algorithm compressionAlgorithmForMode(SPUDeltaCompressionMode compressionMode)
|
||||
{
|
||||
switch (compressionMode) {
|
||||
case SPUDeltaCompressionModeLZMA:
|
||||
@@ -239,44 +237,44 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
|
||||
- (nullable SPUDeltaArchiveHeader *)readHeader
|
||||
{
|
||||
NSString *patchFile = self.patchFile;
|
||||
NSString *patchFile = _patchFile;
|
||||
|
||||
char patchFilePath[PATH_MAX + 1] = {0};
|
||||
if (![patchFile getFileSystemRepresentation:patchFilePath maxLength:sizeof(patchFilePath) - 1]) {
|
||||
self.error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to open and represent as a file system representation: %@", patchFile] }];
|
||||
_error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to open and represent as a file system representation: %@", patchFile] }];
|
||||
return nil;
|
||||
}
|
||||
|
||||
FILE *file = fopen(patchFilePath, "rb");
|
||||
if (file == NULL) {
|
||||
self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to open patch file for writing value due to io error: %@", patchFile] }];
|
||||
_error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to open patch file for writing value due to io error: %@", patchFile] }];
|
||||
return nil;
|
||||
}
|
||||
|
||||
self.file = file;
|
||||
_file = file;
|
||||
|
||||
char magic[5] = {0};
|
||||
if (fread(magic, sizeof(magic) - 1, 1, file) < 1) {
|
||||
self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to read magic value from patch file: %@", patchFile] }];
|
||||
_error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to read magic value from patch file: %@", patchFile] }];
|
||||
return nil;
|
||||
}
|
||||
|
||||
if (strncmp(magic, SPARKLE_DELTA_FORMAT_MAGIC, sizeof(magic) - 1) != 0) {
|
||||
self.error = [NSError errorWithDomain:SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_ARCHIVE_ERROR_CODE_BAD_MAGIC userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Patch file does not have '%@' magic value", @SPARKLE_DELTA_FORMAT_MAGIC] }];
|
||||
_error = [NSError errorWithDomain:SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_ARCHIVE_ERROR_CODE_BAD_MAGIC userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Patch file does not have '%@' magic value", @SPARKLE_DELTA_FORMAT_MAGIC] }];
|
||||
return nil;
|
||||
}
|
||||
|
||||
SPUDeltaCompressionMode compression = 0;
|
||||
if (fread(&compression, sizeof(compression), 1, file) < 1) {
|
||||
self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to read compression value from patch file: %@", patchFile] }];
|
||||
_error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to read compression value from patch file: %@", patchFile] }];
|
||||
return nil;
|
||||
}
|
||||
|
||||
self.compression = compression;
|
||||
_compression = compression;
|
||||
|
||||
SparkleDeltaArchiveMetadata metadata = {0};
|
||||
if (fread(&metadata, sizeof(metadata), 1, file) < 1) {
|
||||
self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to read compression level value from patch file: %@", patchFile] }];
|
||||
_error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to read compression level value from patch file: %@", patchFile] }];
|
||||
return nil;
|
||||
}
|
||||
|
||||
@@ -284,40 +282,45 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
case SPUDeltaCompressionModeNone:
|
||||
break;
|
||||
case SPUDeltaCompressionModeBzip2: {
|
||||
#if SPARKLE_BUILD_BZIP2_DELTA_SUPPORT
|
||||
int bzerror = 0;
|
||||
|
||||
BZFILE *bzipFile = BZ2_bzReadOpen(&bzerror, file, 0, 0, NULL, 0);
|
||||
if (bzipFile == NULL) {
|
||||
switch (bzerror) {
|
||||
case BZ_IO_ERROR:
|
||||
self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to open patch as bz2 file due to io error: %@", patchFile] }];
|
||||
_error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to open patch as bz2 file due to io error: %@", patchFile] }];
|
||||
break;
|
||||
default:
|
||||
self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:bzerror userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to open patch as bz2 file: %@", patchFile] }];
|
||||
_error = [NSError errorWithDomain:NSPOSIXErrorDomain code:bzerror userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to open patch as bz2 file: %@", patchFile] }];
|
||||
break;
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
self.bzipFile = bzipFile;
|
||||
_bzipFile = bzipFile;
|
||||
|
||||
break;
|
||||
#else
|
||||
_error = [NSError errorWithDomain:SPARKLE_BZIP2_ERROR_DOMAIN code:-1 userInfo:@{ NSLocalizedDescriptionKey: @"Failed to open patch as bz2 file because bzip2 support is disabled" }];
|
||||
return nil;
|
||||
#endif
|
||||
}
|
||||
case SPUDeltaCompressionModeLZMA:
|
||||
case SPUDeltaCompressionModeLZFSE:
|
||||
case SPUDeltaCompressionModeLZ4:
|
||||
case SPUDeltaCompressionModeZLIB: {
|
||||
if (compression_stream_init(&_compressionStream, COMPRESSION_STREAM_DECODE, _compressionAlgorithmForMode(compression)) != COMPRESSION_STATUS_OK) {
|
||||
self.error = [NSError errorWithDomain:SPARKLE_COMPRESSION_ERROR_DOMAIN code:COMPRESSION_STATUS_ERROR userInfo:@{ NSLocalizedDescriptionKey: @"Failed to open compression stream for reading" }];
|
||||
if (compression_stream_init(&_compressionStream, COMPRESSION_STREAM_DECODE, compressionAlgorithmForMode(compression)) != COMPRESSION_STATUS_OK) {
|
||||
_error = [NSError errorWithDomain:SPARKLE_COMPRESSION_ERROR_DOMAIN code:COMPRESSION_STATUS_ERROR userInfo:@{ NSLocalizedDescriptionKey: @"Failed to open compression stream for reading" }];
|
||||
return nil;
|
||||
}
|
||||
|
||||
self.initializedCompressionStream = YES;
|
||||
_initializedCompressionStream = YES;
|
||||
|
||||
break;
|
||||
}
|
||||
default:
|
||||
self.error = [NSError errorWithDomain:SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_ARCHIVE_ERROR_CODE_BAD_COMPRESSION_VALUE userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Compression value read %d is not recognized.", compression] }];
|
||||
_error = [NSError errorWithDomain:SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_ARCHIVE_ERROR_CODE_BAD_COMPRESSION_VALUE userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Compression value read %d is not recognized.", compression] }];
|
||||
return nil;
|
||||
}
|
||||
|
||||
@@ -335,22 +338,34 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
return nil;
|
||||
}
|
||||
|
||||
unsigned char beforeTreeHash[CC_SHA1_DIGEST_LENGTH] = {0};
|
||||
unsigned char beforeTreeHash[BINARY_DELTA_HASH_LENGTH] = {0};
|
||||
if (![self _readBuffer:beforeTreeHash length:sizeof(beforeTreeHash)]) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
unsigned char afterTreeHash[CC_SHA1_DIGEST_LENGTH] = {0};
|
||||
unsigned char afterTreeHash[BINARY_DELTA_HASH_LENGTH] = {0};
|
||||
if (![self _readBuffer:afterTreeHash length:sizeof(afterTreeHash)]) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
return [[SPUDeltaArchiveHeader alloc] initWithCompression:compression compressionLevel:metadata.compressionLevel fileSystemCompression:metadata.fileSystemCompression majorVersion:majorVersion minorVersion:minorVersion beforeTreeHash:beforeTreeHash afterTreeHash:afterTreeHash];
|
||||
NSDate *bundleCreationDate;
|
||||
if (majorVersion >= SUBinaryDeltaMajorVersion4) {
|
||||
double bundleCreationTimeInterval = 0;
|
||||
if (![self _readBuffer:&bundleCreationTimeInterval length:sizeof(bundleCreationTimeInterval)]) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
bundleCreationDate = (bundleCreationTimeInterval != 0.0) ? [NSDate dateWithTimeIntervalSinceReferenceDate:bundleCreationTimeInterval] : nil;
|
||||
} else {
|
||||
bundleCreationDate = nil;
|
||||
}
|
||||
|
||||
return [[SPUDeltaArchiveHeader alloc] initWithCompression:compression compressionLevel:metadata.compressionLevel fileSystemCompression:metadata.fileSystemCompression majorVersion:majorVersion minorVersion:minorVersion beforeTreeHash:beforeTreeHash afterTreeHash:afterTreeHash bundleCreationDate:bundleCreationDate];
|
||||
}
|
||||
|
||||
- (NSArray<NSString *> *)_readRelativeFilePaths
|
||||
- (NSArray<NSString *> *)_readRelativeFilePaths SPU_OBJC_DIRECT
|
||||
{
|
||||
if (self.error != nil) {
|
||||
if (_error != nil) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
@@ -366,7 +381,7 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
|
||||
char *fileTableData = calloc(1, filePathSectionSize);
|
||||
if (fileTableData == NULL) {
|
||||
self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to calloc() %llu bytes for relative file paths.", filePathSectionSize] }];
|
||||
_error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to calloc() %llu bytes for relative file paths.", filePathSectionSize] }];
|
||||
return nil;
|
||||
}
|
||||
|
||||
@@ -393,7 +408,7 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
if (fileTableData[index] == '\0') {
|
||||
NSString *relativePath = [fileManager stringWithFileSystemRepresentation:&fileTableData[currentStartIndex] length:index - currentStartIndex];
|
||||
if (relativePath == nil) {
|
||||
self.error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Relative path cannot be decoded as a file system representation: %@", relativePath] }];
|
||||
_error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Relative path cannot be decoded as a file system representation: %@", relativePath] }];
|
||||
|
||||
free(fileTableData);
|
||||
return nil;
|
||||
@@ -425,7 +440,7 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
if (relativeFilePaths.count > UINT32_MAX) {
|
||||
// Very unlikely but we should guard against this
|
||||
// Clones rely on 32-bit indexes
|
||||
self.error = [NSError errorWithDomain:SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_ARCHIVE_ERROR_CODE_TOO_MANY_FILES userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"There are too many file entries to apply a patch for (more than %u)", UINT32_MAX] }];
|
||||
_error = [NSError errorWithDomain:SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_ARCHIVE_ERROR_CODE_TOO_MANY_FILES userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"There are too many file entries to apply a patch for (more than %u)", UINT32_MAX] }];
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -464,7 +479,7 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
}
|
||||
|
||||
if ((NSUInteger)cloneRelativePathIndex >= relativeFilePaths.count) {
|
||||
self.error = [NSError errorWithDomain:SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_ARCHIVE_ERROR_CODE_BAD_CLONE_LOOKUP userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Index %u is past relative path table bounds of length %lu", cloneRelativePathIndex, (unsigned long)relativeFilePaths.count] }];
|
||||
_error = [NSError errorWithDomain:SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_ARCHIVE_ERROR_CODE_BAD_CLONE_LOOKUP userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Index %u is past relative path table bounds of length %lu", cloneRelativePathIndex, (unsigned long)relativeFilePaths.count] }];
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -525,7 +540,7 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
}
|
||||
}
|
||||
|
||||
if (self.error != nil) {
|
||||
if (_error != nil) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -559,15 +574,17 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
if ((commands & SPUDeltaItemCommandBinaryDiff) != 0 || S_ISREG(mode)) {
|
||||
// Regular files
|
||||
|
||||
[fileManager removeItemAtPath:itemFilePath error:NULL];
|
||||
|
||||
char itemFilePathString[PATH_MAX + 1] = {0};
|
||||
if (![itemFilePath getFileSystemRepresentation:itemFilePathString maxLength:sizeof(itemFilePathString) - 1]) {
|
||||
self.error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Path to extract cannot be decoded and expressed as a file system representation: %@", itemFilePath] }];
|
||||
_error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Path to extract cannot be decoded and expressed as a file system representation: %@", itemFilePath] }];
|
||||
return NO;
|
||||
}
|
||||
|
||||
FILE *outputFile = fopen(itemFilePathString, "wb");
|
||||
if (outputFile == NULL) {
|
||||
self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to fopen() %@", itemFilePath] }];
|
||||
_error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to fopen() %@", itemFilePath] }];
|
||||
return NO;
|
||||
}
|
||||
|
||||
@@ -578,14 +595,14 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
while (bytesLeftoverToCopy > 0) {
|
||||
uint64_t currentBlockSize = (bytesLeftoverToCopy >= PARTIAL_IO_CHUNK_SIZE) ? PARTIAL_IO_CHUNK_SIZE : bytesLeftoverToCopy;
|
||||
|
||||
void *tempBuffer = self.partialChunkBuffer;
|
||||
void *tempBuffer = _partialChunkBuffer;
|
||||
|
||||
if (![self _readBuffer:tempBuffer length:(int32_t)currentBlockSize]) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (fwrite(tempBuffer, currentBlockSize, 1, outputFile) < 1) {
|
||||
self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to fwrite() %llu bytes during extraction.", currentBlockSize] }];
|
||||
_error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to fwrite() %llu bytes during extraction.", currentBlockSize] }];
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -595,12 +612,12 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
|
||||
fclose(outputFile);
|
||||
|
||||
if (self.error != nil) {
|
||||
if (_error != nil) {
|
||||
return NO;
|
||||
}
|
||||
|
||||
if ((commands & SPUDeltaItemCommandExtract) != 0 && chmod(itemFilePathString, mode) != 0) {
|
||||
self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to chmod() mode %d on %@", mode, itemFilePath] }];
|
||||
_error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to chmod() mode %d on %@", mode, itemFilePath] }];
|
||||
return NO;
|
||||
}
|
||||
} else {
|
||||
@@ -608,13 +625,13 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
|
||||
if (PARTIAL_IO_CHUNK_SIZE < decodedLength) {
|
||||
// Something is seriously wrong
|
||||
self.error = [NSError errorWithDomain:SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_ARCHIVE_ERROR_CODE_BAD_CHUNK_SIZE userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"PARTIAL_IO_CHUNK_SIZE (%d) < decodedLength (%llu)", PARTIAL_IO_CHUNK_SIZE, decodedLength] }];
|
||||
_error = [NSError errorWithDomain:SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_ARCHIVE_ERROR_CODE_BAD_CHUNK_SIZE userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"PARTIAL_IO_CHUNK_SIZE (%d) < decodedLength (%llu)", PARTIAL_IO_CHUNK_SIZE, decodedLength] }];
|
||||
return NO;
|
||||
}
|
||||
|
||||
if (decodedLength > PATH_MAX) {
|
||||
// Link is too long
|
||||
self.error = [NSError errorWithDomain:SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_ARCHIVE_ERROR_CODE_LINK_TOO_LONG userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Decoded length for link (%llu) is too long.", decodedLength] }];
|
||||
_error = [NSError errorWithDomain:SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_ARCHIVE_ERROR_CODE_LINK_TOO_LONG userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Decoded length for link (%llu) is too long.", decodedLength] }];
|
||||
return NO;
|
||||
}
|
||||
|
||||
@@ -626,7 +643,7 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
NSString *destinationPath = [fileManager stringWithFileSystemRepresentation:buffer length:decodedLength];
|
||||
|
||||
if (destinationPath == nil) {
|
||||
self.error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Destination path for link %@ cannot be created in a file system representation: %@",itemFilePath, destinationPath] }];
|
||||
_error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Destination path for link %@ cannot be created in a file system representation: %@",itemFilePath, destinationPath] }];
|
||||
return NO;
|
||||
}
|
||||
|
||||
@@ -634,13 +651,13 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
|
||||
NSError *createLinkError = nil;
|
||||
if (![fileManager createSymbolicLinkAtPath:itemFilePath withDestinationPath:destinationPath error:&createLinkError]) {
|
||||
self.error = createLinkError;
|
||||
_error = createLinkError;
|
||||
return NO;
|
||||
}
|
||||
|
||||
char itemFilePathString[PATH_MAX + 1] = {0};
|
||||
if (![itemFilePath getFileSystemRepresentation:itemFilePathString maxLength:sizeof(itemFilePathString) - 1]) {
|
||||
self.error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Link path to extract cannot be decoded and expressed as a file system representation: %@", itemFilePath] }];
|
||||
_error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Link path to extract cannot be decoded and expressed as a file system representation: %@", itemFilePath] }];
|
||||
return NO;
|
||||
}
|
||||
|
||||
@@ -652,7 +669,7 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
} else if (S_ISDIR(mode)) {
|
||||
NSError *createDirectoryError = nil;
|
||||
if (![fileManager createDirectoryAtPath:itemFilePath withIntermediateDirectories:NO attributes:@{NSFilePosixPermissions: @(mode)} error:&createDirectoryError]) {
|
||||
self.error = createDirectoryError;
|
||||
_error = createDirectoryError;
|
||||
return NO;
|
||||
}
|
||||
}
|
||||
@@ -660,34 +677,39 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (BOOL)_writeBuffer:(void *)buffer length:(int32_t)length
|
||||
- (BOOL)_writeBuffer:(void *)buffer length:(int32_t)length SPU_OBJC_DIRECT
|
||||
{
|
||||
if (self.error != nil) {
|
||||
if (_error != nil) {
|
||||
return NO;
|
||||
}
|
||||
|
||||
switch (self.compression) {
|
||||
switch (_compression) {
|
||||
case SPUDeltaCompressionModeNone: {
|
||||
BOOL success = (fwrite(buffer, (size_t)length, 1, self.file) == 1);
|
||||
BOOL success = (fwrite(buffer, (size_t)length, 1, _file) == 1);
|
||||
if (!success) {
|
||||
self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to write %d uncompressed bytes.", length] }];
|
||||
_error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to write %d uncompressed bytes.", length] }];
|
||||
}
|
||||
|
||||
return success;
|
||||
}
|
||||
case SPUDeltaCompressionModeBzip2: {
|
||||
case SPUDeltaCompressionModeBzip2:
|
||||
{
|
||||
#if SPARKLE_BUILD_BZIP2_DELTA_SUPPORT
|
||||
int bzerror = 0;
|
||||
BZ2_bzWrite(&bzerror, self.bzipFile, buffer, length);
|
||||
BZ2_bzWrite(&bzerror, _bzipFile, buffer, length);
|
||||
switch (bzerror) {
|
||||
case BZ_OK:
|
||||
return YES;
|
||||
case BZ_IO_ERROR:
|
||||
self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to write %d compressed bz2 bytes due to io error.", length] }];
|
||||
_error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to write %d compressed bz2 bytes due to io error.", length] }];
|
||||
return NO;
|
||||
default:
|
||||
self.error = [NSError errorWithDomain:SPARKLE_BZIP2_ERROR_DOMAIN code:bzerror userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to write %d compressed bz2 bytes.", length] }];
|
||||
_error = [NSError errorWithDomain:SPARKLE_BZIP2_ERROR_DOMAIN code:bzerror userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to write %d compressed bz2 bytes.", length] }];
|
||||
return NO;
|
||||
}
|
||||
#else
|
||||
return NO;
|
||||
#endif
|
||||
}
|
||||
case SPUDeltaCompressionModeLZMA:
|
||||
case SPUDeltaCompressionModeLZFSE:
|
||||
@@ -696,21 +718,21 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
_compressionStream.src_ptr = buffer;
|
||||
_compressionStream.src_size = (size_t)length;
|
||||
|
||||
FILE *file = self.file;
|
||||
void *compressionBuffer = self.compressionBuffer;
|
||||
FILE *file = _file;
|
||||
void *compressionBuffer = _compressionBuffer;
|
||||
while (_compressionStream.src_size > 0) {
|
||||
// Reset destination buffer
|
||||
_compressionStream.dst_ptr = compressionBuffer;
|
||||
_compressionStream.dst_size = COMPRESSION_BUFFER_SIZE;
|
||||
|
||||
if (compression_stream_process(&_compressionStream, 0) == COMPRESSION_STATUS_ERROR) {
|
||||
self.error = [NSError errorWithDomain:SPARKLE_COMPRESSION_ERROR_DOMAIN code:COMPRESSION_STATUS_ERROR userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to write %d compressed bytes.", length] }];
|
||||
_error = [NSError errorWithDomain:SPARKLE_COMPRESSION_ERROR_DOMAIN code:COMPRESSION_STATUS_ERROR userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to write %d compressed bytes.", length] }];
|
||||
return NO;
|
||||
}
|
||||
|
||||
size_t compressedBytesWritten = (size_t)(_compressionStream.dst_ptr - (uint8_t *)compressionBuffer);
|
||||
if (compressedBytesWritten > 0 && fwrite(compressionBuffer, compressedBytesWritten, 1, file) < 1) {
|
||||
self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to write %zu compressed bytes.", compressedBytesWritten] }];
|
||||
_error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to write %zu compressed bytes.", compressedBytesWritten] }];
|
||||
return NO;
|
||||
}
|
||||
}
|
||||
@@ -723,31 +745,31 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
- (void)writeHeader:(SPUDeltaArchiveHeader *)header
|
||||
{
|
||||
char patchFilePath[PATH_MAX + 1] = {0};
|
||||
if (![self.patchFile getFileSystemRepresentation:patchFilePath maxLength:sizeof(patchFilePath) - 1]) {
|
||||
self.error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to open header and represent as a file system representation: %@", self.patchFile] }];
|
||||
if (![_patchFile getFileSystemRepresentation:patchFilePath maxLength:sizeof(patchFilePath) - 1]) {
|
||||
_error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to open header and represent as a file system representation: %@", _patchFile] }];
|
||||
return;
|
||||
}
|
||||
|
||||
FILE *file = fopen(patchFilePath, "wb");
|
||||
if (file == NULL) {
|
||||
self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to open patch file for writing: %@", self.patchFile] }];
|
||||
_error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to open patch file for writing: %@", _patchFile] }];
|
||||
return;
|
||||
}
|
||||
|
||||
self.file = file;
|
||||
_file = file;
|
||||
|
||||
char magic[] = SPARKLE_DELTA_FORMAT_MAGIC;
|
||||
if (fwrite(magic, sizeof(magic) - 1, 1, file) < 1) {
|
||||
self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: @"Failed to write magic value due to io error" }];
|
||||
_error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: @"Failed to write magic value due to io error" }];
|
||||
return;
|
||||
}
|
||||
|
||||
SPUDeltaCompressionMode compression = (header.compression == SPUDeltaCompressionModeDefault) ? SPUDeltaCompressionModeLZMA : header.compression;
|
||||
|
||||
self.compression = compression;
|
||||
_compression = compression;
|
||||
|
||||
if (fwrite(&compression, sizeof(compression), 1, file) < 1) {
|
||||
self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: @"Failed to write compression value due to io error" }];
|
||||
_error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: @"Failed to write compression value due to io error" }];
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -755,13 +777,19 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
uint8_t compressionLevel = 0;
|
||||
switch (compression) {
|
||||
case SPUDeltaCompressionModeBzip2:
|
||||
#if SPARKLE_BUILD_BZIP2_DELTA_SUPPORT
|
||||
// Only 1 - 9 are valid, 0 is a special case for using default 9
|
||||
if (header.compressionLevel <= 0 || header.compressionLevel > 9) {
|
||||
compressionLevel = 9;
|
||||
} else {
|
||||
compressionLevel = header.compressionLevel;
|
||||
}
|
||||
|
||||
break;
|
||||
#else
|
||||
_error = [NSError errorWithDomain:SPARKLE_BZIP2_ERROR_DOMAIN code:-1 userInfo:@{ NSLocalizedDescriptionKey: @"Failed to write bzip2 patch because bzip2 support is disabled" }];
|
||||
return;
|
||||
#endif
|
||||
// Some supported formats below have a documented level even though it's not customizable
|
||||
// Let's record them in the archive
|
||||
case SPUDeltaCompressionModeLZMA:
|
||||
@@ -780,7 +808,7 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
SparkleDeltaArchiveMetadata metadata = {.compressionLevel = compressionLevel, .fileSystemCompression = header.fileSystemCompression};
|
||||
|
||||
if (fwrite(&metadata, sizeof(metadata), 1, file) < 1) {
|
||||
self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: @"Failed to write metadata value due to io error" }];
|
||||
_error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: @"Failed to write metadata value due to io error" }];
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -788,6 +816,7 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
case SPUDeltaCompressionModeNone:
|
||||
break;
|
||||
case SPUDeltaCompressionModeBzip2: {
|
||||
#if SPARKLE_BUILD_BZIP2_DELTA_SUPPORT
|
||||
int bzerror = 0;
|
||||
// Compression level can be 1 - 9
|
||||
int blockSize100k = (int)compressionLevel;
|
||||
@@ -796,17 +825,18 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
if (bzipFile == NULL) {
|
||||
switch (bzerror) {
|
||||
case BZ_IO_ERROR:
|
||||
self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: @"Failed to open bz2 stream for writing due to io error" }];
|
||||
_error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: @"Failed to open bz2 stream for writing due to io error" }];
|
||||
break;
|
||||
default:
|
||||
self.error = [NSError errorWithDomain:SPARKLE_BZIP2_ERROR_DOMAIN code:bzerror userInfo:@{ NSLocalizedDescriptionKey: @"Failed to open bz2 stream for writing" }];
|
||||
_error = [NSError errorWithDomain:SPARKLE_BZIP2_ERROR_DOMAIN code:bzerror userInfo:@{ NSLocalizedDescriptionKey: @"Failed to open bz2 stream for writing" }];
|
||||
break;
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
self.bzipFile = bzipFile;
|
||||
_bzipFile = bzipFile;
|
||||
#endif
|
||||
|
||||
break;
|
||||
}
|
||||
@@ -814,13 +844,13 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
case SPUDeltaCompressionModeLZFSE:
|
||||
case SPUDeltaCompressionModeLZ4:
|
||||
case SPUDeltaCompressionModeZLIB: {
|
||||
if (compression_stream_init(&_compressionStream, COMPRESSION_STREAM_ENCODE, _compressionAlgorithmForMode(compression)) != COMPRESSION_STATUS_OK) {
|
||||
self.error = [NSError errorWithDomain:SPARKLE_COMPRESSION_ERROR_DOMAIN code:COMPRESSION_STATUS_ERROR userInfo:@{ NSLocalizedDescriptionKey: @"Failed to open compression stream for writing" }];
|
||||
if (compression_stream_init(&_compressionStream, COMPRESSION_STREAM_ENCODE, compressionAlgorithmForMode(compression)) != COMPRESSION_STATUS_OK) {
|
||||
_error = [NSError errorWithDomain:SPARKLE_COMPRESSION_ERROR_DOMAIN code:COMPRESSION_STATUS_ERROR userInfo:@{ NSLocalizedDescriptionKey: @"Failed to open compression stream for writing" }];
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
self.initializedCompressionStream = YES;
|
||||
_initializedCompressionStream = YES;
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -835,22 +865,30 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
uint16_t minorVersion = header.minorVersion;
|
||||
[self _writeBuffer:&minorVersion length:sizeof(minorVersion)];
|
||||
|
||||
[self _writeBuffer:header.beforeTreeHash length:CC_SHA1_DIGEST_LENGTH];
|
||||
[self _writeBuffer:header.afterTreeHash length:CC_SHA1_DIGEST_LENGTH];
|
||||
[self _writeBuffer:header.beforeTreeHash length:BINARY_DELTA_HASH_LENGTH];
|
||||
[self _writeBuffer:header.afterTreeHash length:BINARY_DELTA_HASH_LENGTH];
|
||||
|
||||
if (majorVersion >= SUBinaryDeltaMajorVersion4) {
|
||||
NSDate *bundleCreationDate = header.bundleCreationDate;
|
||||
|
||||
// If bundleCreationDate == nil, we will write out a 0 time interval
|
||||
double timeInterval = bundleCreationDate.timeIntervalSinceReferenceDate;
|
||||
[self _writeBuffer:&timeInterval length:sizeof(timeInterval)];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)addItem:(SPUDeltaArchiveItem *)item
|
||||
{
|
||||
[self.writableItems addObject:item];
|
||||
[_writableItems addObject:item];
|
||||
}
|
||||
|
||||
- (void)finishEncodingItems
|
||||
{
|
||||
if (self.error != nil) {
|
||||
if (_error != nil) {
|
||||
return;
|
||||
}
|
||||
|
||||
NSMutableArray<SPUDeltaArchiveItem *> *writableItems = self.writableItems;
|
||||
NSMutableArray<SPUDeltaArchiveItem *> *writableItems = _writableItems;
|
||||
|
||||
// Build relative path table for tracking file clones
|
||||
NSMutableDictionary<NSString *, NSNumber *> *relativePathToIndexTable = [NSMutableDictionary dictionary];
|
||||
@@ -865,7 +903,7 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
|
||||
// Clone commands reference relative file paths in this table but sometimes there may not
|
||||
// be an entry if extraction for an original item was skipped. Fill out any missing file path entries.
|
||||
// For example, if A.app has Contents/A and B.app has Contents/A and Contents/A and Contents/B,
|
||||
// For example, if A.app has Contents/A and B.app has Contents/A and Contents/B,
|
||||
// where A and B's contents are the same and A is the same in both apps, normally we would not record Contents/A because its extraction was skipped. However now B is a clone of A so we need a record for A.
|
||||
NSMutableArray<NSString *> *newClonedPathEntries = [NSMutableArray array];
|
||||
for (SPUDeltaArchiveItem *item in writableItems) {
|
||||
@@ -882,7 +920,7 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
if (relativePathToIndexTable.count > UINT32_MAX) {
|
||||
// Very unlikely but we should guard against this
|
||||
// Clones rely on 32-bit indexes
|
||||
self.error = [NSError errorWithDomain:SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_ARCHIVE_ERROR_CODE_TOO_MANY_FILES userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"There are too many file entries to create a patch for (more than %u)", UINT32_MAX] }];
|
||||
_error = [NSError errorWithDomain:SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_ARCHIVE_ERROR_CODE_TOO_MANY_FILES userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"There are too many file entries to create a patch for (more than %u)", UINT32_MAX] }];
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -893,7 +931,7 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
|
||||
char relativePathString[PATH_MAX + 1] = {0};
|
||||
if (![relativePath getFileSystemRepresentation:relativePathString maxLength:sizeof(relativePathString) - 1]) {
|
||||
self.error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Relative path cannot be retrieved and expressed as a file system representation: %@", relativePath] }];
|
||||
_error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Relative path cannot be retrieved and expressed as a file system representation: %@", relativePath] }];
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -902,14 +940,14 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
for (NSString *clonedPathEntry in newClonedPathEntries) {
|
||||
char relativePathString[PATH_MAX + 1] = {0};
|
||||
if (![clonedPathEntry getFileSystemRepresentation:relativePathString maxLength:sizeof(relativePathString) - 1]) {
|
||||
self.error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Relative path for clone cannot be retrieved and expressed as a file system representation: %@", clonedPathEntry] }];
|
||||
_error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Relative path for clone cannot be retrieved and expressed as a file system representation: %@", clonedPathEntry] }];
|
||||
break;
|
||||
}
|
||||
|
||||
totalPathLength += strlen(relativePathString) + 1;
|
||||
}
|
||||
|
||||
if (self.error != nil) {
|
||||
if (_error != nil) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -924,7 +962,7 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
|
||||
char pathBuffer[PATH_MAX + 1] = {0};
|
||||
if (![relativePath getFileSystemRepresentation:pathBuffer maxLength:PATH_MAX]) {
|
||||
self.error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Relative path cannot be encoded and expressed as a file system representation: %@", relativePath] }];
|
||||
_error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Relative path cannot be encoded and expressed as a file system representation: %@", relativePath] }];
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -935,7 +973,7 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
for (NSString *clonedPathEntry in newClonedPathEntries) {
|
||||
char pathBuffer[PATH_MAX + 1] = {0};
|
||||
if (![clonedPathEntry getFileSystemRepresentation:pathBuffer maxLength:PATH_MAX]) {
|
||||
self.error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Relative path for clone cannot be encoded and expressed as a file system representation: %@", clonedPathEntry] }];
|
||||
_error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Relative path for clone cannot be encoded and expressed as a file system representation: %@", clonedPathEntry] }];
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -944,7 +982,7 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
}
|
||||
}
|
||||
|
||||
if (self.error != nil) {
|
||||
if (_error != nil) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -967,13 +1005,13 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
|
||||
char sourcePathString[PATH_MAX + 1] = {0};
|
||||
if (![sourcePath getFileSystemRepresentation:sourcePathString maxLength:sizeof(sourcePathString) - 1]) {
|
||||
self.error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Path cannot be decoded and expressed as a file system representation while encoding cloned binary diff item: %@", sourcePath] }];
|
||||
_error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Path cannot be decoded and expressed as a file system representation while encoding cloned binary diff item: %@", sourcePath] }];
|
||||
break;
|
||||
}
|
||||
|
||||
struct stat fileInfo = {0};
|
||||
if (lstat(sourcePathString, &fileInfo) != 0) {
|
||||
self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to lstat() on %@", sourcePath] }];
|
||||
_error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to lstat() on %@", sourcePath] }];
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -1000,7 +1038,7 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
NSNumber *relativePathIndex = relativePathToIndexTable[clonedRelativePath];
|
||||
if (relativePathIndex == nil) {
|
||||
// We have quite a problem here
|
||||
self.error = [NSError errorWithDomain:SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_ARCHIVE_ERROR_CODE_BAD_CLONE_LOOKUP userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Relative file path index for %@ could not be located", clonedRelativePath] }];
|
||||
_error = [NSError errorWithDomain:SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_ARCHIVE_ERROR_CODE_BAD_CLONE_LOOKUP userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Relative file path index for %@ could not be located", clonedRelativePath] }];
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -1015,13 +1053,13 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
|
||||
char itemFilePathString[PATH_MAX + 1] = {0};
|
||||
if (![itemPath getFileSystemRepresentation:itemFilePathString maxLength:sizeof(itemFilePathString) - 1]) {
|
||||
self.error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Path cannot be decoded and expressed as a file system representation while encoding cloned binary diff item: %@", itemPath] }];
|
||||
_error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Path cannot be decoded and expressed as a file system representation while encoding cloned binary diff item: %@", itemPath] }];
|
||||
break;
|
||||
}
|
||||
|
||||
struct stat fileInfo = {0};
|
||||
if (lstat(itemFilePathString, &fileInfo) != 0) {
|
||||
self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to lstat() on %@", itemPath] }];
|
||||
_error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to lstat() on %@", itemPath] }];
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -1041,13 +1079,13 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
|
||||
char sourceFilePathString[PATH_MAX + 1] = {0};
|
||||
if (![sourcePath getFileSystemRepresentation:sourceFilePathString maxLength:sizeof(sourceFilePathString) - 1]) {
|
||||
self.error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Path cannot be decoded and expressed as a file system representation while encoding items: %@", sourcePath] }];
|
||||
_error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Path cannot be decoded and expressed as a file system representation while encoding items: %@", sourcePath] }];
|
||||
break;
|
||||
}
|
||||
|
||||
struct stat sourceFileInfo = {0};
|
||||
if (lstat(sourceFilePathString, &sourceFileInfo) != 0) {
|
||||
self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to lstat() on %@", sourcePath] }];
|
||||
_error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to lstat() on %@", sourcePath] }];
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -1083,13 +1121,13 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
|
||||
char itemFilePathString[PATH_MAX + 1] = {0};
|
||||
if (![itemPath getFileSystemRepresentation:itemFilePathString maxLength:sizeof(itemFilePathString) - 1]) {
|
||||
self.error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Path cannot be decoded and expressed as a file system representation while encoding items: %@", itemPath] }];
|
||||
_error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Path cannot be decoded and expressed as a file system representation while encoding items: %@", itemPath] }];
|
||||
break;
|
||||
}
|
||||
|
||||
struct stat itemFileInfo = {0};
|
||||
if (lstat(itemFilePathString, &itemFileInfo) != 0) {
|
||||
self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to lstat() on %@", itemPath] }];
|
||||
_error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to lstat() on %@", itemPath] }];
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -1103,7 +1141,7 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
} else if (S_ISLNK(extractMode)) {
|
||||
off_t fileSize = itemFileInfo.st_size;
|
||||
if (fileSize > UINT16_MAX) {
|
||||
self.error = [NSError errorWithDomain:SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_ARCHIVE_ERROR_CODE_LINK_TOO_LONG userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Link path has a destination that is too long: %llu bytes", fileSize] }];
|
||||
_error = [NSError errorWithDomain:SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_ARCHIVE_ERROR_CODE_LINK_TOO_LONG userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Link path has a destination that is too long: %lld bytes", fileSize] }];
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -1123,7 +1161,7 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
}
|
||||
}
|
||||
|
||||
if (self.error != nil) {
|
||||
if (_error != nil) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1134,7 +1172,7 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
}
|
||||
|
||||
// Encode all of our file contents
|
||||
void *tempBuffer = self.partialChunkBuffer;
|
||||
void *tempBuffer = _partialChunkBuffer;
|
||||
for (SPUDeltaArchiveItem *item in writableItems) {
|
||||
SPUDeltaItemCommands commands = item.commands;
|
||||
if ((commands & SPUDeltaItemCommandExtract) != 0 || (commands & SPUDeltaItemCommandBinaryDiff) != 0) {
|
||||
@@ -1149,13 +1187,13 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
if (totalItemSize > 0) {
|
||||
char itemFilePathString[PATH_MAX + 1] = {0};
|
||||
if (![itemPath getFileSystemRepresentation:itemFilePathString maxLength:sizeof(itemFilePathString) - 1]) {
|
||||
self.error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Path to finish encoding cannot be decoded and expressed as a file system representation: %@", itemPath] }];
|
||||
_error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Path to finish encoding cannot be decoded and expressed as a file system representation: %@", itemPath] }];
|
||||
break;
|
||||
}
|
||||
|
||||
FILE *inputFile = fopen(itemFilePathString, "rb");
|
||||
if (inputFile == NULL) {
|
||||
self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to open file for reading while encoding items: %@", itemPath] }];
|
||||
_error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to open file for reading while encoding items: %@", itemPath] }];
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -1164,7 +1202,7 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
uint64_t currentBlockSize = (bytesLeftoverToCopy >= PARTIAL_IO_CHUNK_SIZE) ? PARTIAL_IO_CHUNK_SIZE : bytesLeftoverToCopy;
|
||||
|
||||
if (fread(tempBuffer, currentBlockSize, 1, inputFile) < 1) {
|
||||
self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to read %llu chunk bytes while encoding items", currentBlockSize] }];
|
||||
_error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to read %llu chunk bytes while encoding items", currentBlockSize] }];
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -1177,21 +1215,21 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
|
||||
fclose(inputFile);
|
||||
|
||||
if (self.error != nil) {
|
||||
if (_error != nil) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else if (S_ISLNK(extractMode)) {
|
||||
char itemFilePathString[PATH_MAX + 1] = {0};
|
||||
if (![itemPath getFileSystemRepresentation:itemFilePathString maxLength:sizeof(itemFilePathString) - 1]) {
|
||||
self.error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Link path to finish encoding cannot be decoded and expressed as a file system representation: %@", itemPath] }];
|
||||
_error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Link path to finish encoding cannot be decoded and expressed as a file system representation: %@", itemPath] }];
|
||||
break;
|
||||
}
|
||||
|
||||
char linkDestination[PATH_MAX + 1] = {0};
|
||||
ssize_t linkDestinationLength = readlink(itemFilePathString, linkDestination, PATH_MAX);
|
||||
if (linkDestinationLength < 0) {
|
||||
self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to readlink() file at %@", itemPath] }];
|
||||
_error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to readlink() file at %@", itemPath] }];
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -1204,16 +1242,19 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
|
||||
// Close up and write final data to compressed streams
|
||||
|
||||
if (self.bzipFile != NULL) {
|
||||
#if SPARKLE_BUILD_BZIP2_DELTA_SUPPORT
|
||||
if (_bzipFile != NULL) {
|
||||
int bzerror = 0;
|
||||
BZ2_bzWriteClose64(&bzerror, self.bzipFile, 0, NULL, NULL, NULL, NULL);
|
||||
BZ2_bzWriteClose64(&bzerror, _bzipFile, 0, NULL, NULL, NULL, NULL);
|
||||
if (bzerror == BZ_IO_ERROR) {
|
||||
self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: @"Failed to write and close bzip2 file due to IO error" }];
|
||||
_error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: @"Failed to write and close bzip2 file due to IO error" }];
|
||||
return;
|
||||
}
|
||||
} else if (self.initializedCompressionStream) {
|
||||
void *compressionBuffer = self.compressionBuffer;
|
||||
FILE *file = self.file;
|
||||
} else
|
||||
#endif
|
||||
if (_initializedCompressionStream) {
|
||||
void *compressionBuffer = _compressionBuffer;
|
||||
FILE *file = _file;
|
||||
|
||||
_compressionStream.src_size = 0;
|
||||
|
||||
@@ -1223,14 +1264,14 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
|
||||
compression_status status = compression_stream_process(&_compressionStream, COMPRESSION_STREAM_FINALIZE);
|
||||
if (status == COMPRESSION_STATUS_ERROR) {
|
||||
self.error = [NSError errorWithDomain:SPARKLE_COMPRESSION_ERROR_DOMAIN code:COMPRESSION_STATUS_ERROR userInfo:@{ NSLocalizedDescriptionKey: @"Failed to write final bits of Compression based file" }];
|
||||
_error = [NSError errorWithDomain:SPARKLE_COMPRESSION_ERROR_DOMAIN code:COMPRESSION_STATUS_ERROR userInfo:@{ NSLocalizedDescriptionKey: @"Failed to write final bits of Compression based file" }];
|
||||
return;
|
||||
}
|
||||
|
||||
size_t compressedBytesToWrite = (size_t)(_compressionStream.dst_ptr - (uint8_t *)compressionBuffer);
|
||||
if (compressedBytesToWrite > 0) {
|
||||
if (fwrite(compressionBuffer, compressedBytesToWrite, 1, file) < 1) {
|
||||
self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: @"Failed to write and close Compression based file due to io error" }];
|
||||
_error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: @"Failed to write and close Compression based file due to io error" }];
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -1244,5 +1285,3 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma clang diagnostic pop
|
||||
@@ -6,6 +6,8 @@
|
||||
// Copyright © 2021 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#if SPARKLE_BUILD_LEGACY_DELTA_SUPPORT
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
#import "SPUDeltaArchiveProtocol.h"
|
||||
@@ -14,11 +16,13 @@
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
// Legacy container format for binary delta archives
|
||||
@interface SPUXarDeltaArchive : NSObject <SPUDeltaArchiveProtocol>
|
||||
SPU_OBJC_DIRECT_MEMBERS @interface SPUXarDeltaArchive : NSObject <SPUDeltaArchiveProtocol>
|
||||
|
||||
- (instancetype)initWithPatchFileForWriting:(NSString *)patchFile;
|
||||
- (instancetype)initWithPatchFileForReading:(NSString *)patchFile;
|
||||
- (instancetype)initWithPatchFileForWriting:(NSString *)patchFile SPU_OBJC_DIRECT;
|
||||
- (instancetype)initWithPatchFileForReading:(NSString *)patchFile SPU_OBJC_DIRECT;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
#endif
|
||||
@@ -6,6 +6,8 @@
|
||||
// Copyright © 2021 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#if SPARKLE_BUILD_LEGACY_DELTA_SUPPORT
|
||||
|
||||
#import "SPUXarDeltaArchive.h"
|
||||
#include <xar/xar.h>
|
||||
#include "SUBinaryDeltaCommon.h"
|
||||
@@ -45,22 +47,15 @@ extern char *xar_get_safe_path(xar_file_t f) __attribute__((weak_import));
|
||||
#define SPARKLE_DELTA_XAR_ARCHIVE_ERROR_CODE_EXTRACT_FAILURE 3
|
||||
#define SPARKLE_DELTA_XAR_ARCHIVE_ERROR_CODE_UNSUPPORTED_COMPRESSION_FAILURE 4
|
||||
|
||||
@interface SPUXarDeltaArchive ()
|
||||
|
||||
@property (nonatomic) xar_t x;
|
||||
@property (nonatomic, readonly) int32_t xarMode;
|
||||
@property (nonatomic, readonly) NSMutableDictionary<NSString *, NSValue *> *fileTable;
|
||||
@property (nonatomic, readonly) NSString *patchFile;
|
||||
@property (nonatomic) NSError *error;
|
||||
|
||||
@end
|
||||
|
||||
@implementation SPUXarDeltaArchive
|
||||
{
|
||||
NSMutableDictionary<NSString *, NSValue *> *_fileTable;
|
||||
NSString *_patchFile;
|
||||
|
||||
xar_t _x;
|
||||
int32_t _xarMode;
|
||||
}
|
||||
|
||||
@synthesize x = _x;
|
||||
@synthesize xarMode = _xarMode;
|
||||
@synthesize patchFile = _patchFile;
|
||||
@synthesize fileTable = _fileTable;
|
||||
@synthesize error = _error;
|
||||
|
||||
- (instancetype)initWithPatchFileForWriting:(NSString *)patchFile
|
||||
@@ -91,9 +86,9 @@ extern char *xar_get_safe_path(xar_file_t f) __attribute__((weak_import));
|
||||
|
||||
- (void)close
|
||||
{
|
||||
if (self.x != NULL) {
|
||||
xar_close(self.x);
|
||||
self.x = NULL;
|
||||
if (_x != NULL) {
|
||||
xar_close(_x);
|
||||
_x = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,18 +100,18 @@ extern char *xar_get_safe_path(xar_file_t f) __attribute__((weak_import));
|
||||
|
||||
- (nullable SPUDeltaArchiveHeader *)readHeader
|
||||
{
|
||||
NSString *patchFile = self.patchFile;
|
||||
NSString *patchFile = _patchFile;
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
|
||||
// Sparkle's XAR delta archives have been superceded by Sparkle's own format
|
||||
// Sparkle's XAR delta archives have been superseded by Sparkle's own format
|
||||
xar_t x = xar_open(patchFile.fileSystemRepresentation, READ);
|
||||
#pragma clang diagnostic pop
|
||||
if (x == NULL) {
|
||||
self.error = [NSError errorWithDomain:SPARKLE_DELTA_XAR_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_XAR_ARCHIVE_ERROR_CODE_OPEN_FAILURE userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to xar_open() file for reading: %@", patchFile] }];
|
||||
_error = [NSError errorWithDomain:SPARKLE_DELTA_XAR_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_XAR_ARCHIVE_ERROR_CODE_OPEN_FAILURE userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to xar_open() file for reading: %@", patchFile] }];
|
||||
return nil;
|
||||
}
|
||||
|
||||
self.x = x;
|
||||
_x = x;
|
||||
|
||||
uint16_t majorDiffVersion = SUBinaryDeltaMajorVersionFirst;
|
||||
uint16_t minorDiffVersion = 0;
|
||||
@@ -124,7 +119,7 @@ extern char *xar_get_safe_path(xar_file_t f) __attribute__((weak_import));
|
||||
NSString *expectedAfterHash = nil;
|
||||
|
||||
xar_subdoc_t subdoc;
|
||||
for (subdoc = xar_subdoc_first(self.x); subdoc; subdoc = xar_subdoc_next(subdoc)) {
|
||||
for (subdoc = xar_subdoc_first(_x); subdoc; subdoc = xar_subdoc_next(subdoc)) {
|
||||
if (strcmp(xar_subdoc_name(subdoc), BINARY_DELTA_ATTRIBUTES_KEY) == 0) {
|
||||
{
|
||||
// available in version 2.0 or later
|
||||
@@ -164,32 +159,32 @@ extern char *xar_get_safe_path(xar_file_t f) __attribute__((weak_import));
|
||||
}
|
||||
}
|
||||
|
||||
unsigned char rawExpectedBeforeHash[CC_SHA1_DIGEST_LENGTH] = {0};
|
||||
unsigned char rawExpectedBeforeHash[BINARY_DELTA_HASH_LENGTH] = {0};
|
||||
getRawHashFromDisplayHash(rawExpectedBeforeHash, expectedBeforeHash);
|
||||
|
||||
unsigned char rawExpectedAfterHash[CC_SHA1_DIGEST_LENGTH] = {0};
|
||||
unsigned char rawExpectedAfterHash[BINARY_DELTA_HASH_LENGTH] = {0};
|
||||
getRawHashFromDisplayHash(rawExpectedAfterHash, expectedAfterHash);
|
||||
|
||||
// I wasn't able to figure out how to retrieve the compression options from xar,
|
||||
// so we will use default flags to indicate the info isn't available
|
||||
return [[SPUDeltaArchiveHeader alloc] initWithCompression:SPUDeltaCompressionModeDefault compressionLevel:0 fileSystemCompression:false majorVersion:majorDiffVersion minorVersion:minorDiffVersion beforeTreeHash:rawExpectedBeforeHash afterTreeHash:rawExpectedAfterHash];
|
||||
return [[SPUDeltaArchiveHeader alloc] initWithCompression:SPUDeltaCompressionModeDefault compressionLevel:0 fileSystemCompression:false majorVersion:majorDiffVersion minorVersion:minorDiffVersion beforeTreeHash:rawExpectedBeforeHash afterTreeHash:rawExpectedAfterHash bundleCreationDate:nil];
|
||||
}
|
||||
|
||||
- (void)writeHeader:(SPUDeltaArchiveHeader *)header
|
||||
{
|
||||
NSString *patchFile = self.patchFile;
|
||||
NSString *patchFile = _patchFile;
|
||||
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
|
||||
// Sparkle's XAR delta archives have been superceded by Sparkle's own format
|
||||
// Sparkle's XAR delta archives have been superseded by Sparkle's own format
|
||||
xar_t x = xar_open(patchFile.fileSystemRepresentation, WRITE);
|
||||
#pragma clang diagnostic pop
|
||||
if (x == NULL) {
|
||||
self.error = [NSError errorWithDomain:SPARKLE_DELTA_XAR_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_XAR_ARCHIVE_ERROR_CODE_OPEN_FAILURE userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to xar_open() file for writing: %@", patchFile] }];
|
||||
_error = [NSError errorWithDomain:SPARKLE_DELTA_XAR_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_XAR_ARCHIVE_ERROR_CODE_OPEN_FAILURE userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to xar_open() file for writing: %@", patchFile] }];
|
||||
return;
|
||||
}
|
||||
|
||||
self.x = x;
|
||||
_x = x;
|
||||
|
||||
SPUDeltaCompressionMode compression = (header.compression == SPUDeltaCompressionModeDefault ? SPUDeltaCompressionModeBzip2 : header.compression);
|
||||
|
||||
@@ -218,7 +213,7 @@ extern char *xar_get_safe_path(xar_file_t f) __attribute__((weak_import));
|
||||
case SPUDeltaCompressionModeLZFSE:
|
||||
case SPUDeltaCompressionModeLZ4:
|
||||
case SPUDeltaCompressionModeZLIB: {
|
||||
self.error = [NSError errorWithDomain:SPARKLE_DELTA_XAR_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_XAR_ARCHIVE_ERROR_CODE_UNSUPPORTED_COMPRESSION_FAILURE userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Version 2 patches only support bzip2 compression."] }];
|
||||
_error = [NSError errorWithDomain:SPARKLE_DELTA_XAR_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_XAR_ARCHIVE_ERROR_CODE_UNSUPPORTED_COMPRESSION_FAILURE userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Version 2 patches only support bzip2 compression."] }];
|
||||
|
||||
return;
|
||||
}
|
||||
@@ -233,7 +228,7 @@ extern char *xar_get_safe_path(xar_file_t f) __attribute__((weak_import));
|
||||
xar_subdoc_prop_set(attributes, AFTER_TREE_SHA1_KEY, [displayHashFromRawHash(header.afterTreeHash) UTF8String]);
|
||||
}
|
||||
|
||||
static xar_file_t _xarAddFile(NSMutableDictionary<NSString *, NSValue *> *fileTable, xar_t x, NSString *relativePath, NSString *filePath)
|
||||
static xar_file_t xarAddFile(NSMutableDictionary<NSString *, NSValue *> *fileTable, xar_t x, NSString *relativePath, NSString *filePath)
|
||||
{
|
||||
NSArray<NSString *> *rootRelativePathComponents = relativePath.pathComponents;
|
||||
// Relative path must at least have starting "/" component and one more path component
|
||||
@@ -251,7 +246,7 @@ static xar_file_t _xarAddFile(NSMutableDictionary<NSString *, NSValue *> *fileTa
|
||||
// We store every file we add into a fileTable for easy referencing
|
||||
// Note if a diff has Contents/Resources/foo/ and Contents/Resources/foo/bar.txt,
|
||||
// due to sorting order we will add the foo directory first and won't end up with
|
||||
// mis-ordering bugs
|
||||
// misordering bugs
|
||||
xar_file_t lastParent = NULL;
|
||||
for (NSUInteger componentIndex = 0; componentIndex < relativePathComponentsCount; componentIndex++) {
|
||||
NSArray<NSString *> *subpathComponents = [relativePathComponents subarrayWithRange:NSMakeRange(0, componentIndex + 1)];
|
||||
@@ -281,7 +276,7 @@ static xar_file_t _xarAddFile(NSMutableDictionary<NSString *, NSValue *> *fileTa
|
||||
|
||||
- (void)addItem:(SPUDeltaArchiveItem *)item
|
||||
{
|
||||
if (self.error != nil) {
|
||||
if (_error != nil) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -290,9 +285,9 @@ static xar_file_t _xarAddFile(NSMutableDictionary<NSString *, NSValue *> *fileTa
|
||||
SPUDeltaItemCommands commands = item.commands;
|
||||
uint16_t mode = item.mode;
|
||||
|
||||
xar_file_t newFile = _xarAddFile(self.fileTable, self.x, relativeFilePath, filePath);
|
||||
xar_file_t newFile = xarAddFile(_fileTable, _x, relativeFilePath, filePath);
|
||||
if (newFile == NULL) {
|
||||
self.error = [NSError errorWithDomain:SPARKLE_DELTA_XAR_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_XAR_ARCHIVE_ERROR_CODE_ADD_FAILURE userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to add xar file entry: %@", relativeFilePath] }];
|
||||
_error = [NSError errorWithDomain:SPARKLE_DELTA_XAR_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_XAR_ARCHIVE_ERROR_CODE_ADD_FAILURE userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to add xar file entry: %@", relativeFilePath] }];
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -320,13 +315,13 @@ static xar_file_t _xarAddFile(NSMutableDictionary<NSString *, NSValue *> *fileTa
|
||||
|
||||
- (void)enumerateItems:(void (^)(SPUDeltaArchiveItem *, BOOL *))itemHandler
|
||||
{
|
||||
if (self.error != nil) {
|
||||
if (_error != nil) {
|
||||
return;
|
||||
}
|
||||
|
||||
BOOL exitedEarly = NO;
|
||||
xar_iter_t iter = xar_iter_new();
|
||||
for (xar_file_t file = xar_file_first(self.x, iter); file; file = xar_file_next(iter)) {
|
||||
for (xar_file_t file = xar_file_first(_x, iter); file; file = xar_file_next(iter)) {
|
||||
char *pathCString;
|
||||
#if HAS_XAR_GET_SAFE_PATH
|
||||
#pragma clang diagnostic push
|
||||
@@ -397,7 +392,7 @@ static xar_file_t _xarAddFile(NSMutableDictionary<NSString *, NSValue *> *fileTa
|
||||
|
||||
- (BOOL)extractItem:(SPUDeltaArchiveItem *)item
|
||||
{
|
||||
if (self.error != nil) {
|
||||
if (_error != nil) {
|
||||
return NO;
|
||||
}
|
||||
|
||||
@@ -405,8 +400,8 @@ static xar_file_t _xarAddFile(NSMutableDictionary<NSString *, NSValue *> *fileTa
|
||||
assert(item.xarContext != NULL);
|
||||
|
||||
xar_file_t file = item.xarContext;
|
||||
if (xar_extract_tofile(self.x, file, item.itemFilePath.fileSystemRepresentation) != 0) {
|
||||
self.error = [NSError errorWithDomain:SPARKLE_DELTA_XAR_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_XAR_ARCHIVE_ERROR_CODE_EXTRACT_FAILURE userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to extract xar file entry to %@", item.itemFilePath] }];
|
||||
if (xar_extract_tofile(_x, file, item.itemFilePath.fileSystemRepresentation) != 0) {
|
||||
_error = [NSError errorWithDomain:SPARKLE_DELTA_XAR_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_XAR_ARCHIVE_ERROR_CODE_EXTRACT_FAILURE userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to extract xar file entry to %@", item.itemFilePath] }];
|
||||
return NO;
|
||||
}
|
||||
|
||||
@@ -414,3 +409,5 @@ static xar_file_t _xarAddFile(NSMutableDictionary<NSString *, NSValue *> *fileTa
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
@@ -92,7 +92,7 @@ BOOL applyBinaryDelta(NSString *source, NSString *finalDestination, NSString *pa
|
||||
|
||||
progressCallback(1/7.0);
|
||||
|
||||
unsigned char beforeHash[CC_SHA1_DIGEST_LENGTH] = {0};
|
||||
unsigned char beforeHash[BINARY_DELTA_HASH_LENGTH] = {0};
|
||||
if (!getRawHashOfTreeWithVersion(beforeHash, source, majorDiffVersion)) {
|
||||
if (verbose) {
|
||||
fprintf(stderr, "\n");
|
||||
@@ -102,8 +102,8 @@ BOOL applyBinaryDelta(NSString *source, NSString *finalDestination, NSString *pa
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
if (memcmp(beforeHash, expectedBeforeHash, CC_SHA1_DIGEST_LENGTH) != 0) {
|
||||
|
||||
if (memcmp(beforeHash, expectedBeforeHash, BINARY_DELTA_HASH_LENGTH) != 0) {
|
||||
if (verbose) {
|
||||
fprintf(stderr, "\n");
|
||||
}
|
||||
@@ -141,7 +141,9 @@ BOOL applyBinaryDelta(NSString *source, NSString *finalDestination, NSString *pa
|
||||
|
||||
progressCallback(3/7.0);
|
||||
|
||||
if (!copyTree(source, destination)) {
|
||||
NSFileManager *fileManager = [[NSFileManager alloc] init];
|
||||
|
||||
if (!copyTree(fileManager, source, destination)) {
|
||||
if (verbose) {
|
||||
fprintf(stderr, "\n");
|
||||
}
|
||||
@@ -150,13 +152,22 @@ BOOL applyBinaryDelta(NSString *source, NSString *finalDestination, NSString *pa
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
// Preserve file creation date only for the root item if the date is recorded
|
||||
// (requires major version 4 or later)
|
||||
NSDate *bundleCreationDate = header.bundleCreationDate;
|
||||
if (bundleCreationDate != nil) {
|
||||
NSError *setFileCreationDateError = nil;
|
||||
if (![fileManager setAttributes:@{NSFileCreationDate: bundleCreationDate} ofItemAtPath:destination error:&setFileCreationDateError]) {
|
||||
fprintf(stderr, "\nWarning: failed to set file creation date: %s", setFileCreationDateError.localizedDescription.UTF8String);
|
||||
}
|
||||
}
|
||||
|
||||
progressCallback(4/7.0);
|
||||
|
||||
if (verbose) {
|
||||
fprintf(stderr, "\nPatching...");
|
||||
}
|
||||
NSFileManager *fileManager = [[NSFileManager alloc] init];
|
||||
|
||||
// Ensure error is cleared out in advance
|
||||
if (error != NULL) {
|
||||
@@ -282,6 +293,21 @@ BOOL applyBinaryDelta(NSString *source, NSString *finalDestination, NSString *pa
|
||||
clonedRelativePath = nil;
|
||||
}
|
||||
|
||||
// Decide if we need to preserve original file permissions from the original file
|
||||
// applyBinaryDeltaToFile() normally preserves file permissions on the file it's replacing.
|
||||
// However this is not possible if the destination file we're patching is not writable.
|
||||
// We also need to preserve permissions for clones except when we'll be changing permissions later anyway.
|
||||
BOOL needsToCopyFilePermissions;
|
||||
if (![fileManager isWritableFileAtPath:destinationFilePath]) {
|
||||
// Remove the file non-writable we're patching that may cause issues
|
||||
[fileManager removeItemAtPath:destinationFilePath error:NULL];
|
||||
|
||||
// We will need to preserve permissions if there is no need to make permission changes later on
|
||||
needsToCopyFilePermissions = (commands & SPUDeltaItemCommandModifyPermissions) == 0;
|
||||
} else {
|
||||
needsToCopyFilePermissions = ((commands & SPUDeltaItemCommandClone) != 0) && ((commands & SPUDeltaItemCommandModifyPermissions) == 0);
|
||||
}
|
||||
|
||||
if (!applyBinaryDeltaToFile(tempDiffFile, sourceDiffFilePath, destinationFilePath)) {
|
||||
if (verbose) {
|
||||
fprintf(stderr, "\n");
|
||||
@@ -293,12 +319,7 @@ BOOL applyBinaryDelta(NSString *source, NSString *finalDestination, NSString *pa
|
||||
return;
|
||||
}
|
||||
|
||||
// Preserve original file permissions from the original file
|
||||
// Only necessary for clones because applyBinaryDeltaToFile() otherwise preserves
|
||||
// file permissions on the file it's replacing. Also not necessary if we're going to
|
||||
// change permissions later
|
||||
if ((commands & SPUDeltaItemCommandClone) != 0 && (commands & SPUDeltaItemCommandModifyPermissions) == 0) {
|
||||
|
||||
if (needsToCopyFilePermissions) {
|
||||
struct stat sourceFileInfo = {0};
|
||||
if (lstat(sourceDiffFilePath.fileSystemRepresentation, &sourceFileInfo) != 0) {
|
||||
if (verbose) {
|
||||
@@ -368,7 +389,7 @@ BOOL applyBinaryDelta(NSString *source, NSString *finalDestination, NSString *pa
|
||||
}
|
||||
|
||||
if (verbose) {
|
||||
fprintf(stderr, "\n👮 %s %s (0%o)", VERBOSE_MODIFIED, [relativePath fileSystemRepresentation], mode & PERMISSION_FLAGS);
|
||||
fprintf(stderr, "\n👮 %s %s (0%o)", VERBOSE_MODIFIED, [relativePath fileSystemRepresentation], (unsigned int)(mode & PERMISSION_FLAGS));
|
||||
}
|
||||
}
|
||||
}];
|
||||
@@ -398,32 +419,17 @@ BOOL applyBinaryDelta(NSString *source, NSString *finalDestination, NSString *pa
|
||||
|
||||
NSTask *dittoTask = [[NSTask alloc] init];
|
||||
|
||||
if (@available(macOS 10.13, *)) {
|
||||
dittoTask.executableURL = [NSURL fileURLWithPath:@"/usr/bin/ditto" isDirectory:NO];
|
||||
} else {
|
||||
dittoTask.launchPath = @"/usr/bin/ditto";
|
||||
}
|
||||
|
||||
dittoTask.executableURL = [NSURL fileURLWithPath:@"/usr/bin/ditto" isDirectory:NO];
|
||||
dittoTask.arguments = @[@"--hfsCompression", destination, finalDestination];
|
||||
|
||||
// If we fail to apply file system compression, we will try falling back to not doing this
|
||||
BOOL failedToApplyFileSystemCompression = NO;
|
||||
|
||||
if (@available(macOS 10.13, *)) {
|
||||
NSError *launchError = nil;
|
||||
if (![dittoTask launchAndReturnError:&launchError]) {
|
||||
failedToApplyFileSystemCompression = YES;
|
||||
|
||||
fprintf(stderr, "\nWarning: failed to launch ditto task for file compression: %s", launchError.localizedDescription.UTF8String);
|
||||
}
|
||||
} else {
|
||||
@try {
|
||||
[dittoTask launch];
|
||||
} @catch (NSException *exception) {
|
||||
failedToApplyFileSystemCompression = YES;
|
||||
|
||||
fprintf(stderr, "\nWarning: failed to launch ditto task for file compression: %s", exception.reason.UTF8String);
|
||||
}
|
||||
NSError *launchError = nil;
|
||||
if (![dittoTask launchAndReturnError:&launchError]) {
|
||||
failedToApplyFileSystemCompression = YES;
|
||||
|
||||
fprintf(stderr, "\nWarning: failed to launch ditto task for file compression: %s", launchError.localizedDescription.UTF8String);
|
||||
}
|
||||
|
||||
if (!failedToApplyFileSystemCompression) {
|
||||
@@ -454,7 +460,7 @@ BOOL applyBinaryDelta(NSString *source, NSString *finalDestination, NSString *pa
|
||||
fprintf(stderr, "\nVerifying destination...");
|
||||
}
|
||||
|
||||
unsigned char afterHash[CC_SHA1_DIGEST_LENGTH] = {0};
|
||||
unsigned char afterHash[BINARY_DELTA_HASH_LENGTH] = {0};
|
||||
if (!getRawHashOfTreeWithVersion(afterHash, finalDestination, majorDiffVersion)) {
|
||||
if (verbose) {
|
||||
fprintf(stderr, "\n");
|
||||
@@ -465,8 +471,8 @@ BOOL applyBinaryDelta(NSString *source, NSString *finalDestination, NSString *pa
|
||||
removeTree(finalDestination);
|
||||
return NO;
|
||||
}
|
||||
|
||||
if (memcmp(afterHash, expectedAfterHash, CC_SHA1_DIGEST_LENGTH) != 0) {
|
||||
|
||||
if (memcmp(afterHash, expectedAfterHash, BINARY_DELTA_HASH_LENGTH) != 0) {
|
||||
if (verbose) {
|
||||
fprintf(stderr, "\n");
|
||||
}
|
||||
|
||||
@@ -32,8 +32,6 @@
|
||||
#define VERBOSE_MODIFIED "Modified" // file's metadata is modified
|
||||
#define VERBOSE_CLONED "Cloned" // file is cloned in content from a differently named file
|
||||
|
||||
#define MAJOR_VERSION_IS_AT_LEAST(actualMajor, expectedMajor) (actualMajor >= expectedMajor)
|
||||
|
||||
// Relative path of custom icon data that may be set on a bundle via a resource fork
|
||||
#define CUSTOM_ICON_PATH @"/Icon\r"
|
||||
|
||||
@@ -44,7 +42,8 @@ typedef NS_ENUM(uint16_t, SUBinaryDeltaMajorVersion)
|
||||
// Note: support for creating or applying version 1 deltas have been removed
|
||||
SUBinaryDeltaMajorVersion1 = 1,
|
||||
SUBinaryDeltaMajorVersion2 = 2,
|
||||
SUBinaryDeltaMajorVersion3 = 3
|
||||
SUBinaryDeltaMajorVersion3 = 3,
|
||||
SUBinaryDeltaMajorVersion4 = 4,
|
||||
};
|
||||
|
||||
extern SUBinaryDeltaMajorVersion SUBinaryDeltaMajorVersionDefault;
|
||||
@@ -52,22 +51,27 @@ extern SUBinaryDeltaMajorVersion SUBinaryDeltaMajorVersionLatest;
|
||||
extern SUBinaryDeltaMajorVersion SUBinaryDeltaMajorVersionFirst;
|
||||
extern SUBinaryDeltaMajorVersion SUBinaryDeltaMajorVersionFirstSupported;
|
||||
|
||||
#define COMPRESSION_METHOD_ARGUMENT_DESCRIPTION @"The compression method to use for generating delta updates. Supported methods for version 3 delta files are 'lzma', 'bzip2', 'zlib', 'lzfse', 'lz4', 'none', and 'default'. Note that version 2 delta files only support 'bzip2', 'none', and 'default' so other methods will be ignored if version 2 files are being generated. The 'default' compression for version 3 delta files is currently lzma."
|
||||
// Additional compression methods for version 3 or 4 patches that we have for debugging are zlib, bzip2, none
|
||||
#define COMPRESSION_METHOD_ARGUMENT_DESCRIPTION @"The compression method to use for generating delta updates. Supported methods for version 3 delta files are 'lzma' (best compression, slowest), 'lzfse' (good compression, fast), 'lz4' (worse compression, fastest), and 'default'. Note that version 2 delta files only support 'bzip2', and 'default' so other methods will be ignored if version 2 files are being generated. The 'default' compression for version 3 or 4 delta files is currently lzma."
|
||||
|
||||
#define COMPRESSION_LEVEL_ARGUMENT_DESCRIPTION @"The compression level to use for generating delta updates. This only applies if the compression method used is bzip2 which accepts values from 1 - 9. A special value of 0 will use the default compression level."
|
||||
//#define COMPRESSION_LEVEL_ARGUMENT_DESCRIPTION @"The compression level to use for generating delta updates. This only applies if the compression method used is bzip2 which accepts values from 1 - 9. A special value of 0 will use the default compression level."
|
||||
|
||||
// This is the same as CC_SHA1_DIGEST_LENGTH
|
||||
// Major versions >= 4 use a crc32 hash (using a subset of these bytes) while older versions use a sha1 hash
|
||||
#define BINARY_DELTA_HASH_LENGTH 20
|
||||
|
||||
SPUDeltaCompressionMode deltaCompressionModeFromDescription(NSString *description, BOOL *requestValid);
|
||||
NSString *deltaCompressionStringFromMode(SPUDeltaCompressionMode mode);
|
||||
|
||||
extern int compareFiles(const FTSENT **a, const FTSENT **b);
|
||||
BOOL getRawHashOfTreeWithVersion(unsigned char *hashBuffer, NSString *path, uint16_t majorVersion);
|
||||
BOOL getRawHashOfTreeAndFileTablesWithVersion(unsigned char *hashBuffer, NSString *path, uint16_t majorVersion, NSMutableDictionary<NSData *, NSMutableArray<NSString *> *> *hashToFileKeyDictionary, NSMutableDictionary<NSString *, NSData *> *fileKeyToHashDictionary);
|
||||
BOOL getRawHashOfTreeWithVersion(void *hashBuffer, NSString *path, uint16_t majorVersion);
|
||||
BOOL getRawHashOfTreeAndFileTablesWithVersion(void *hashBuffer, NSString *path, uint16_t majorVersion, NSMutableDictionary<NSData *, NSMutableArray<NSString *> *> *hashToFileKeyDictionary, NSMutableDictionary<NSString *, NSData *> *fileKeyToHashDictionary);
|
||||
NSString *displayHashFromRawHash(const unsigned char *hash);
|
||||
void getRawHashFromDisplayHash(unsigned char *hash, NSString *hexHash);
|
||||
extern NSString *hashOfTreeWithVersion(NSString *path, uint16_t majorVersion);
|
||||
extern NSString *hashOfTree(NSString *path);
|
||||
extern BOOL removeTree(NSString *path);
|
||||
extern BOOL copyTree(NSString *source, NSString *dest);
|
||||
extern BOOL copyTree(NSFileManager *fileManager, NSString *source, NSString *dest);
|
||||
extern BOOL modifyPermissions(NSString *path, mode_t desiredPermissions);
|
||||
extern NSString *pathRelativeToDirectory(NSString *directory, NSString *path);
|
||||
NSString *temporaryFilename(NSString *base);
|
||||
|
||||
@@ -7,8 +7,8 @@
|
||||
//
|
||||
|
||||
#include "SUBinaryDeltaCommon.h"
|
||||
#import "SUFileManager.h"
|
||||
#include <CommonCrypto/CommonDigest.h>
|
||||
#include <zlib.h> // for crc32()
|
||||
#include <Foundation/Foundation.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdio.h>
|
||||
@@ -22,8 +22,8 @@
|
||||
|
||||
// Note: the framework bundle version must be bumped, and generate_appcast must be updated to compare it,
|
||||
// when we add/change new major versions and defaults. Unit tests need to be updated to use new versions too.
|
||||
SUBinaryDeltaMajorVersion SUBinaryDeltaMajorVersionDefault = SUBinaryDeltaMajorVersion3;
|
||||
SUBinaryDeltaMajorVersion SUBinaryDeltaMajorVersionLatest = SUBinaryDeltaMajorVersion3;
|
||||
SUBinaryDeltaMajorVersion SUBinaryDeltaMajorVersionDefault = SUBinaryDeltaMajorVersion4;
|
||||
SUBinaryDeltaMajorVersion SUBinaryDeltaMajorVersionLatest = SUBinaryDeltaMajorVersion4;
|
||||
SUBinaryDeltaMajorVersion SUBinaryDeltaMajorVersionFirst = SUBinaryDeltaMajorVersion1;
|
||||
SUBinaryDeltaMajorVersion SUBinaryDeltaMajorVersionFirstSupported = SUBinaryDeltaMajorVersion2;
|
||||
|
||||
@@ -113,9 +113,11 @@ uint16_t latestMinorVersionForMajorVersion(SUBinaryDeltaMajorVersion majorVersio
|
||||
case SUBinaryDeltaMajorVersion1:
|
||||
return 2;
|
||||
case SUBinaryDeltaMajorVersion2:
|
||||
return 4;
|
||||
return 5;
|
||||
case SUBinaryDeltaMajorVersion3:
|
||||
return 1;
|
||||
return 3;
|
||||
case SUBinaryDeltaMajorVersion4:
|
||||
return 2;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -157,7 +159,7 @@ NSString *temporaryDirectory(NSString *base)
|
||||
return stringWithFileSystemRepresentation(templateResult);
|
||||
}
|
||||
|
||||
static void _hashOfBuffer(unsigned char *hash, const char *buffer, ssize_t bufferLength)
|
||||
static void sha1HashOfBuffer(unsigned char *hash, const char *buffer, ssize_t bufferLength)
|
||||
{
|
||||
assert(bufferLength >= 0 && bufferLength <= UINT32_MAX);
|
||||
CC_SHA1_CTX hashContext;
|
||||
@@ -166,7 +168,59 @@ 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, void *tempBuffer, size_t tempBufferSize)
|
||||
static BOOL crc32HashOfFileContents(uLong *outChecksum, FTSENT *ent, void *tempBuffer, size_t tempBufferSize)
|
||||
{
|
||||
uLong checksum = *outChecksum;
|
||||
|
||||
if (ent->fts_info == FTS_SL) {
|
||||
char linkDestination[MAXPATHLEN + 1];
|
||||
ssize_t linkDestinationLength = readlink(ent->fts_path, linkDestination, MAXPATHLEN);
|
||||
if (linkDestinationLength < 0) {
|
||||
perror("readlink");
|
||||
return NO;
|
||||
}
|
||||
|
||||
checksum = crc32(checksum, (const void *)linkDestination, (unsigned int)linkDestinationLength);
|
||||
} else if (ent->fts_info == FTS_F) {
|
||||
ssize_t fileSize = ent->fts_statp->st_size;
|
||||
|
||||
uint64_t encodedFileSize = (uint64_t)fileSize;
|
||||
checksum = crc32(checksum, (const void *)&encodedFileSize, sizeof(encodedFileSize));
|
||||
|
||||
if (fileSize > 0) {
|
||||
FILE *file = fopen(ent->fts_path, "rb");
|
||||
if (file == NULL) {
|
||||
perror("fopen");
|
||||
return NO;
|
||||
}
|
||||
|
||||
size_t bytesLeft = (size_t)fileSize;
|
||||
while (bytesLeft > 0) {
|
||||
size_t bytesToConsume = (bytesLeft >= tempBufferSize) ? tempBufferSize : bytesLeft;
|
||||
|
||||
if (fread(tempBuffer, bytesToConsume, 1, file) < 1) {
|
||||
perror("fread");
|
||||
fclose(file);
|
||||
return NO;
|
||||
}
|
||||
|
||||
checksum = crc32(checksum, tempBuffer, (uInt)bytesToConsume);
|
||||
|
||||
bytesLeft -= bytesToConsume;
|
||||
}
|
||||
|
||||
fclose(file);
|
||||
}
|
||||
} else {
|
||||
return NO;
|
||||
}
|
||||
|
||||
*outChecksum = checksum;
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
static BOOL sha1HashOfFileContents(unsigned char *hash, FTSENT *ent, void *tempBuffer, size_t tempBufferSize)
|
||||
{
|
||||
if (ent->fts_info == FTS_SL) {
|
||||
char linkDestination[MAXPATHLEN + 1];
|
||||
@@ -176,11 +230,11 @@ static BOOL _hashOfFileContents(unsigned char *hash, FTSENT *ent, void *tempBuff
|
||||
return NO;
|
||||
}
|
||||
|
||||
_hashOfBuffer(hash, linkDestination, linkDestinationLength);
|
||||
sha1HashOfBuffer(hash, linkDestination, linkDestinationLength);
|
||||
} else if (ent->fts_info == FTS_F) {
|
||||
ssize_t fileSize = ent->fts_statp->st_size;
|
||||
if (fileSize <= 0) {
|
||||
_hashOfBuffer(hash, NULL, 0);
|
||||
sha1HashOfBuffer(hash, NULL, 0);
|
||||
} else {
|
||||
FILE *file = fopen(ent->fts_path, "rb");
|
||||
if (file == NULL) {
|
||||
@@ -217,12 +271,12 @@ static BOOL _hashOfFileContents(unsigned char *hash, FTSENT *ent, void *tempBuff
|
||||
return YES;
|
||||
}
|
||||
|
||||
BOOL getRawHashOfTreeWithVersion(unsigned char *hashBuffer, NSString *path, uint16_t majorVersion)
|
||||
BOOL getRawHashOfTreeWithVersion(void *hashBuffer, NSString *path, uint16_t majorVersion)
|
||||
{
|
||||
return getRawHashOfTreeAndFileTablesWithVersion(hashBuffer, path, majorVersion, nil, nil);
|
||||
}
|
||||
|
||||
BOOL getRawHashOfTreeAndFileTablesWithVersion(unsigned char *hashBuffer, NSString *path, uint16_t __unused majorVersion, NSMutableDictionary<NSData *, NSMutableArray<NSString *> *> *hashToFileKeyDictionary, NSMutableDictionary<NSString *, NSData *> *fileKeyToHashDictionary)
|
||||
BOOL getRawHashOfTreeAndFileTablesWithVersion(void *hashBuffer, NSString *path, uint16_t majorVersion, NSMutableDictionary<NSData *, NSMutableArray<NSString *> *> *hashToFileKeyDictionary, NSMutableDictionary<NSString *, NSData *> *fileKeyToHashDictionary)
|
||||
{
|
||||
char pathBuffer[PATH_MAX] = { 0 };
|
||||
if (![path getFileSystemRepresentation:pathBuffer maxLength:sizeof(pathBuffer)]) {
|
||||
@@ -245,7 +299,12 @@ BOOL getRawHashOfTreeAndFileTablesWithVersion(unsigned char *hashBuffer, NSStrin
|
||||
}
|
||||
|
||||
CC_SHA1_CTX hashContext;
|
||||
CC_SHA1_Init(&hashContext);
|
||||
const uLong initialCrc32Value = crc32(0L, Z_NULL, 0);
|
||||
uLong crc32ChecksumValue = initialCrc32Value;
|
||||
|
||||
if (majorVersion < SUBinaryDeltaMajorVersion4) {
|
||||
CC_SHA1_Init(&hashContext);
|
||||
}
|
||||
|
||||
// Ensure the path uses filesystem-specific Unicode normalization #1017
|
||||
NSString *normalizedPath = stringWithFileSystemRepresentation(pathBuffer);
|
||||
@@ -262,32 +321,67 @@ BOOL getRawHashOfTreeAndFileTablesWithVersion(unsigned char *hashBuffer, NSStrin
|
||||
continue;
|
||||
}
|
||||
|
||||
unsigned char fileHash[CC_SHA1_DIGEST_LENGTH];
|
||||
if (!_hashOfFileContents(fileHash, ent, tempBuffer, tempBufferSize)) {
|
||||
fts_close(fts);
|
||||
free(tempBuffer);
|
||||
return NO;
|
||||
NSData *fileHashKey;
|
||||
if (majorVersion >= SUBinaryDeltaMajorVersion4) {
|
||||
if (ent->fts_info == FTS_D) {
|
||||
// No need to hash any further values for directories
|
||||
// We hash relative file path and file type later
|
||||
fileHashKey = nil;
|
||||
} else {
|
||||
uLong fileContentsChecksum = initialCrc32Value;
|
||||
if (!crc32HashOfFileContents(&fileContentsChecksum, ent, tempBuffer, tempBufferSize)) {
|
||||
fts_close(fts);
|
||||
free(tempBuffer);
|
||||
return NO;
|
||||
}
|
||||
|
||||
uint64_t encodedFileContentsChecksum = fileContentsChecksum;
|
||||
|
||||
crc32ChecksumValue = crc32(crc32ChecksumValue, (const void *)&encodedFileContentsChecksum, sizeof(encodedFileContentsChecksum));
|
||||
|
||||
if (ent->fts_info == FTS_F) {
|
||||
fileHashKey = [NSData dataWithBytes:&encodedFileContentsChecksum length:sizeof(encodedFileContentsChecksum)];
|
||||
} else {
|
||||
fileHashKey = nil;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
unsigned char fileHash[CC_SHA1_DIGEST_LENGTH];
|
||||
if (!sha1HashOfFileContents(fileHash, ent, tempBuffer, tempBufferSize)) {
|
||||
fts_close(fts);
|
||||
free(tempBuffer);
|
||||
return NO;
|
||||
}
|
||||
CC_SHA1_Update(&hashContext, fileHash, sizeof(fileHash));
|
||||
|
||||
if (ent->fts_info == FTS_F) {
|
||||
fileHashKey = [NSData dataWithBytes:fileHash length:sizeof(fileHash)];
|
||||
} else {
|
||||
fileHashKey = nil;
|
||||
}
|
||||
}
|
||||
CC_SHA1_Update(&hashContext, fileHash, sizeof(fileHash));
|
||||
|
||||
// For file hash tables we only track regular files
|
||||
if (ent->fts_info == FTS_F) {
|
||||
NSData *hashKey = [NSData dataWithBytes:fileHash length:sizeof(fileHash)];
|
||||
|
||||
if (fileHashKey != nil) {
|
||||
if (hashToFileKeyDictionary != nil) {
|
||||
if (hashToFileKeyDictionary[hashKey] == nil) {
|
||||
hashToFileKeyDictionary[hashKey] = [NSMutableArray array];
|
||||
if (hashToFileKeyDictionary[fileHashKey] == nil) {
|
||||
hashToFileKeyDictionary[fileHashKey] = [NSMutableArray array];
|
||||
}
|
||||
[hashToFileKeyDictionary[hashKey] addObject:relativePath];
|
||||
[hashToFileKeyDictionary[fileHashKey] addObject:relativePath];
|
||||
}
|
||||
|
||||
if (fileKeyToHashDictionary != nil) {
|
||||
fileKeyToHashDictionary[relativePath] = hashKey;
|
||||
fileKeyToHashDictionary[relativePath] = fileHashKey;
|
||||
}
|
||||
}
|
||||
|
||||
const char *relativePathBytes = [relativePath fileSystemRepresentation];
|
||||
CC_SHA1_Update(&hashContext, relativePathBytes, (CC_LONG)strlen(relativePathBytes));
|
||||
|
||||
if (majorVersion >= SUBinaryDeltaMajorVersion4) {
|
||||
crc32ChecksumValue = crc32(crc32ChecksumValue, (const void *)relativePathBytes, (uInt)strlen(relativePathBytes));
|
||||
} else {
|
||||
CC_SHA1_Update(&hashContext, relativePathBytes, (CC_LONG)strlen(relativePathBytes));
|
||||
}
|
||||
|
||||
uint16_t mode = ent->fts_statp->st_mode;
|
||||
uint16_t type = ent->fts_info;
|
||||
@@ -298,15 +392,26 @@ BOOL getRawHashOfTreeAndFileTablesWithVersion(unsigned char *hashBuffer, NSStrin
|
||||
// hardcoding a value helps avoid differences between filesystems.
|
||||
uint16_t hashedPermissions = (ent->fts_info == FTS_SL) ? VALID_SYMBOLIC_LINK_PERMISSIONS : permissions;
|
||||
|
||||
CC_SHA1_Update(&hashContext, &type, sizeof(type));
|
||||
CC_SHA1_Update(&hashContext, &hashedPermissions, sizeof(hashedPermissions));
|
||||
if (majorVersion >= SUBinaryDeltaMajorVersion4) {
|
||||
crc32ChecksumValue = crc32(crc32ChecksumValue, (const void *)&type, sizeof(type));
|
||||
crc32ChecksumValue = crc32(crc32ChecksumValue, (const void *)&hashedPermissions, sizeof(hashedPermissions));
|
||||
} else {
|
||||
CC_SHA1_Update(&hashContext, &type, sizeof(type));
|
||||
CC_SHA1_Update(&hashContext, &hashedPermissions, sizeof(hashedPermissions));
|
||||
}
|
||||
}
|
||||
|
||||
free(tempBuffer);
|
||||
|
||||
fts_close(fts);
|
||||
|
||||
CC_SHA1_Final(hashBuffer, &hashContext);
|
||||
if (majorVersion >= SUBinaryDeltaMajorVersion4) {
|
||||
uint64_t encodedCrc32ChecksumValue = crc32ChecksumValue;
|
||||
memset(hashBuffer, 0, BINARY_DELTA_HASH_LENGTH);
|
||||
memcpy(hashBuffer, &encodedCrc32ChecksumValue, sizeof(encodedCrc32ChecksumValue));
|
||||
} else {
|
||||
CC_SHA1_Final(hashBuffer, &hashContext);
|
||||
}
|
||||
|
||||
return YES;
|
||||
}
|
||||
@@ -318,7 +423,7 @@ void getRawHashFromDisplayHash(unsigned char *hash, NSString *hexHash)
|
||||
return;
|
||||
}
|
||||
|
||||
for (size_t blockIndex = 0; blockIndex < CC_SHA1_DIGEST_LENGTH; blockIndex++) {
|
||||
for (size_t blockIndex = 0; blockIndex < BINARY_DELTA_HASH_LENGTH; blockIndex++) {
|
||||
const char *currentBlock = hexString + blockIndex * 2;
|
||||
char convertedBlock[3] = {currentBlock[0], currentBlock[1], '\0'};
|
||||
hash[blockIndex] = (unsigned char)strtol(convertedBlock, NULL, 16);
|
||||
@@ -327,8 +432,8 @@ void getRawHashFromDisplayHash(unsigned char *hash, NSString *hexHash)
|
||||
|
||||
NSString *displayHashFromRawHash(const unsigned char *hash)
|
||||
{
|
||||
char hexHash[CC_SHA1_DIGEST_LENGTH * 2 + 1] = {0};
|
||||
for (size_t i = 0; i < CC_SHA1_DIGEST_LENGTH; i++) {
|
||||
char hexHash[BINARY_DELTA_HASH_LENGTH * 2 + 1] = {0};
|
||||
for (size_t i = 0; i < BINARY_DELTA_HASH_LENGTH; i++) {
|
||||
snprintf(hexHash + i * 2, 3, "%02x", hash[i]);
|
||||
}
|
||||
return @(hexHash);
|
||||
@@ -336,7 +441,7 @@ NSString *displayHashFromRawHash(const unsigned char *hash)
|
||||
|
||||
NSString *hashOfTreeWithVersion(NSString *path, uint16_t majorVersion)
|
||||
{
|
||||
unsigned char hash[CC_SHA1_DIGEST_LENGTH];
|
||||
unsigned char hash[BINARY_DELTA_HASH_LENGTH] = {0};
|
||||
if (!getRawHashOfTreeWithVersion(hash, path, majorVersion)) {
|
||||
return nil;
|
||||
}
|
||||
@@ -358,10 +463,9 @@ BOOL removeTree(NSString *path)
|
||||
return [fileManager removeItemAtPath:path error:nil];
|
||||
}
|
||||
|
||||
BOOL copyTree(NSString *source, NSString *dest)
|
||||
BOOL copyTree(NSFileManager *fileManager, NSString *source, NSString *dest)
|
||||
{
|
||||
// SUFileManager will be more reliable for copying items especially across network mounts
|
||||
return [[[SUFileManager alloc] init] copyItemAtURL:[NSURL fileURLWithPath:source] toURL:[NSURL fileURLWithPath:dest] error:NULL];
|
||||
return [fileManager copyItemAtURL:[NSURL fileURLWithPath:source] toURL:[NSURL fileURLWithPath:dest] error:NULL];
|
||||
}
|
||||
|
||||
BOOL modifyPermissions(NSString *path, mode_t desiredPermissions)
|
||||
|
||||
@@ -29,42 +29,47 @@
|
||||
extern int bsdiff(int argc, const char **argv);
|
||||
|
||||
@interface CreateBinaryDeltaOperation : NSOperation
|
||||
@property (copy) NSString *relativePath;
|
||||
@property (copy) NSString *clonedRelativePath;
|
||||
@property (strong) NSString *resultPath;
|
||||
@property (strong) NSNumber *oldPermissions;
|
||||
@property (strong) NSNumber *permissions;
|
||||
@property (nonatomic) BOOL changingPermissions;
|
||||
@property (strong) NSString *_fromPath;
|
||||
@property (strong) NSString *_toPath;
|
||||
- (id)initWithRelativePath:(NSString *)relativePath clonedRelativePath:(NSString *)clonedRelativePath oldTree:(NSString *)oldTree newTree:(NSString *)newTree oldPermissions:(NSNumber *)oldPermissions newPermissions:(NSNumber *)permissions changingPermissions:(BOOL)changingPermissions;
|
||||
|
||||
@property (nonatomic, copy, readonly) NSString *relativePath;
|
||||
@property (nonatomic, copy, readonly) NSString *clonedRelativePath;
|
||||
@property (nonatomic, readonly) NSString *resultPath;
|
||||
@property (nonatomic, readonly) NSNumber *oldPermissions;
|
||||
@property (nonatomic, readonly) NSNumber *permissions;
|
||||
@property (nonatomic, readonly) NSString *fromPath;
|
||||
@property (nonatomic, readonly) BOOL changingPermissions;
|
||||
|
||||
- (id)initWithRelativePath:(NSString *)relativePath clonedRelativePath:(NSString *)clonedRelativePath oldTree:(NSString *)oldTree newTree:(NSString *)newTree oldPermissions:(NSNumber *)oldPermissions newPermissions:(NSNumber *)permissions changingPermissions:(BOOL)changingPermissions SPU_OBJC_DIRECT;
|
||||
|
||||
@end
|
||||
|
||||
@implementation CreateBinaryDeltaOperation
|
||||
{
|
||||
NSString *_toPath;
|
||||
}
|
||||
|
||||
@synthesize relativePath = _relativePath;
|
||||
@synthesize clonedRelativePath = _clonedRelativePath;
|
||||
@synthesize resultPath = _resultPath;
|
||||
@synthesize oldPermissions = _oldPermissions;
|
||||
@synthesize permissions = _permissions;
|
||||
@synthesize fromPath = _fromPath;
|
||||
@synthesize changingPermissions = _changingPermissions;
|
||||
@synthesize _fromPath = _fromPath;
|
||||
@synthesize _toPath = _toPath;
|
||||
|
||||
- (id)initWithRelativePath:(NSString *)relativePath clonedRelativePath:(NSString *)clonedRelativePath oldTree:(NSString *)oldTree newTree:(NSString *)newTree oldPermissions:(NSNumber *)oldPermissions newPermissions:(NSNumber *)permissions changingPermissions:(BOOL)changingPermissions
|
||||
{
|
||||
if ((self = [super init])) {
|
||||
self.relativePath = relativePath;
|
||||
self.clonedRelativePath = clonedRelativePath;
|
||||
self.oldPermissions = oldPermissions;
|
||||
self.permissions = permissions;
|
||||
self.changingPermissions = changingPermissions;
|
||||
_relativePath = [relativePath copy];
|
||||
_clonedRelativePath = [clonedRelativePath copy];
|
||||
_oldPermissions = oldPermissions;
|
||||
_permissions = permissions;
|
||||
_changingPermissions = changingPermissions;
|
||||
|
||||
if (clonedRelativePath == nil) {
|
||||
self._fromPath = [oldTree stringByAppendingPathComponent:relativePath];
|
||||
_fromPath = [oldTree stringByAppendingPathComponent:relativePath];
|
||||
} else {
|
||||
self._fromPath = [oldTree stringByAppendingPathComponent:clonedRelativePath];
|
||||
_fromPath = [oldTree stringByAppendingPathComponent:clonedRelativePath];
|
||||
}
|
||||
self._toPath = [newTree stringByAppendingPathComponent:relativePath];
|
||||
_toPath = [newTree stringByAppendingPathComponent:relativePath];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
@@ -72,10 +77,11 @@ 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", [_fromPath fileSystemRepresentation], [_toPath fileSystemRepresentation], [temporaryFile fileSystemRepresentation] };
|
||||
int result = bsdiff(4, argv);
|
||||
if (!result)
|
||||
self.resultPath = temporaryFile;
|
||||
if (result == 0) {
|
||||
_resultPath = temporaryFile;
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -339,7 +345,12 @@ static NSString *cloneableRelativePath(NSDictionary<NSString *, NSData *> *after
|
||||
if (oldCloneInfo == nil) {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
// The old file must have the same type as the new one
|
||||
if ([(NSNumber *)oldCloneInfo[INFO_TYPE_KEY] unsignedShortValue] != FTS_F) {
|
||||
continue;
|
||||
}
|
||||
|
||||
NSNumber *newPermissions = newInfo[INFO_PERMISSIONS_KEY];
|
||||
if (outNewPermissions != NULL) {
|
||||
*outNewPermissions = newPermissions;
|
||||
@@ -471,7 +482,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
|
||||
fprintf(stderr, "\n");
|
||||
}
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Permissions for Sparkle executable must be 0%o (found 0%o) on file %@", VALID_SPARKLE_EXECUTABLE_PERMISSIONS, permissions, @(ent->fts_path)] }];
|
||||
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Permissions for Sparkle executable must be 0%o (found 0%o) on file %@", (unsigned int)VALID_SPARKLE_EXECUTABLE_PERMISSIONS, permissions, @(ent->fts_path)] }];
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
@@ -492,7 +503,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
|
||||
fprintf(stderr, "\n");
|
||||
}
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Diffing code signed extended attributes are not supported. Detected extended attribute in before-tree on file %@", @(ent->fts_path)] }];
|
||||
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Diffing code signed extended attributes are not supported. Detected extended attribute in before-tree on file %@. For removing code signed extended attributes and improving your bundle's structure, please see https://developer.apple.com/documentation/bundleresources/placing_content_in_a_bundle", @(ent->fts_path)] }];
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
@@ -500,9 +511,9 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
|
||||
fts_close(fts);
|
||||
|
||||
// This dictionary will help us keep track of clones
|
||||
NSMutableDictionary<NSData *, NSMutableArray<NSString *> *> *beforeHashToFileKeyDictionary = MAJOR_VERSION_IS_AT_LEAST(majorVersion, SUBinaryDeltaMajorVersion3) ? [NSMutableDictionary dictionary] : nil;
|
||||
NSMutableDictionary<NSData *, NSMutableArray<NSString *> *> *beforeHashToFileKeyDictionary = (majorVersion >= SUBinaryDeltaMajorVersion3) ? [NSMutableDictionary dictionary] : nil;
|
||||
|
||||
unsigned char beforeHash[CC_SHA1_DIGEST_LENGTH] = {0};
|
||||
unsigned char beforeHash[BINARY_DELTA_HASH_LENGTH] = {0};
|
||||
if (!getRawHashOfTreeAndFileTablesWithVersion(beforeHash, source, majorVersion, beforeHashToFileKeyDictionary, nil)) {
|
||||
if (verbose) {
|
||||
fprintf(stderr, "\n");
|
||||
@@ -585,7 +596,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
|
||||
fprintf(stderr, "\n");
|
||||
}
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Permissions for Sparkle executable must be 0%o (found 0%o) on file %@", VALID_SPARKLE_EXECUTABLE_PERMISSIONS, permissions, @(ent->fts_path)] }];
|
||||
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Permissions for Sparkle executable must be 0%o (found 0%o) on file %@", (unsigned int)VALID_SPARKLE_EXECUTABLE_PERMISSIONS, permissions, @(ent->fts_path)] }];
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
@@ -610,7 +621,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
|
||||
fprintf(stderr, "\n");
|
||||
}
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Diffing code signed extended attributes are not supported. Detected extended attribute in after-tree on file %@", @(ent->fts_path)] }];
|
||||
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Diffing code signed extended attributes are not supported. Detected extended attribute in after-tree on file %@. For removing code signed extended attributes and improving your bundle's structure, please see https://developer.apple.com/documentation/bundleresources/placing_content_in_a_bundle", @(ent->fts_path)] }];
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
@@ -638,7 +649,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
|
||||
// If we find any executable files that are using file system compression, that is sufficient
|
||||
// for recording that the applier should re-apply file system compression.
|
||||
// We check for executable files because they are likely candidates to be compressed.
|
||||
if (!foundFilesystemCompression && MAJOR_VERSION_IS_AT_LEAST(majorVersion, SUBinaryDeltaMajorVersion3) && ent->fts_info == FTS_F && (ent->fts_statp->st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0 && (ent->fts_statp->st_flags & UF_COMPRESSED) != 0) {
|
||||
if (!foundFilesystemCompression && (majorVersion >= SUBinaryDeltaMajorVersion3) && ent->fts_info == FTS_F && (ent->fts_statp->st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0 && (ent->fts_statp->st_flags & UF_COMPRESSED) != 0) {
|
||||
foundFilesystemCompression = true;
|
||||
|
||||
if (verbose) {
|
||||
@@ -678,9 +689,9 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
|
||||
fts_close(fts);
|
||||
|
||||
// This dictionary will help us keep track of clones
|
||||
NSMutableDictionary<NSString *, NSData *> *afterFileKeyToHashDictionary = MAJOR_VERSION_IS_AT_LEAST(majorVersion, SUBinaryDeltaMajorVersion3) ? [NSMutableDictionary dictionary] : nil;
|
||||
NSMutableDictionary<NSString *, NSData *> *afterFileKeyToHashDictionary = (majorVersion >= SUBinaryDeltaMajorVersion3) ? [NSMutableDictionary dictionary] : nil;
|
||||
|
||||
unsigned char afterHash[CC_SHA1_DIGEST_LENGTH] = {0};
|
||||
unsigned char afterHash[BINARY_DELTA_HASH_LENGTH] = {0};
|
||||
if (!getRawHashOfTreeAndFileTablesWithVersion(afterHash, destination, majorVersion, nil, afterFileKeyToHashDictionary)) {
|
||||
if (verbose) {
|
||||
fprintf(stderr, "\n");
|
||||
@@ -704,10 +715,36 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
|
||||
if (majorVersion >= SUBinaryDeltaMajorVersion3) {
|
||||
archive = [[SPUSparkleDeltaArchive alloc] initWithPatchFileForWriting:temporaryFile];
|
||||
} else {
|
||||
#if SPARKLE_BUILD_LEGACY_DELTA_SUPPORT
|
||||
archive = [[SPUXarDeltaArchive alloc] initWithPatchFileForWriting:temporaryFile];
|
||||
#else
|
||||
if (verbose) {
|
||||
fprintf(stderr, "\n");
|
||||
}
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadUnknownError userInfo:@{ NSLocalizedDescriptionKey: @"Support for creating legacy delta updates is disabled" }];
|
||||
}
|
||||
return NO;
|
||||
#endif
|
||||
}
|
||||
|
||||
SPUDeltaArchiveHeader *header = [[SPUDeltaArchiveHeader alloc] initWithCompression:compression compressionLevel:compressionLevel fileSystemCompression:foundFilesystemCompression majorVersion:majorVersion minorVersion:minorVersion beforeTreeHash:beforeHash afterTreeHash:afterHash];
|
||||
// Record creation date of root bundle item
|
||||
NSDate *bundleCreationDate;
|
||||
if (majorVersion >= SUBinaryDeltaMajorVersion4) {
|
||||
NSError *fileAttributesError = nil;
|
||||
NSDictionary<NSFileAttributeKey, id> *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:destination error:&fileAttributesError];
|
||||
|
||||
if (fileAttributes != nil) {
|
||||
bundleCreationDate = fileAttributes[NSFileCreationDate];
|
||||
} else {
|
||||
bundleCreationDate = nil;
|
||||
fprintf(stderr, "\nWarning: unable to retrieve file creation date of new bundle: %s", fileAttributesError.localizedDescription.UTF8String);
|
||||
}
|
||||
} else {
|
||||
bundleCreationDate = nil;
|
||||
}
|
||||
|
||||
SPUDeltaArchiveHeader *header = [[SPUDeltaArchiveHeader alloc] initWithCompression:compression compressionLevel:compressionLevel fileSystemCompression:foundFilesystemCompression majorVersion:majorVersion minorVersion:minorVersion beforeTreeHash:beforeHash afterTreeHash:afterHash bundleCreationDate:bundleCreationDate];
|
||||
|
||||
[archive writeHeader:header];
|
||||
if (archive.error != nil) {
|
||||
@@ -734,10 +771,10 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
|
||||
return originalTreeState[key1] ? NSOrderedAscending : NSOrderedDescending;
|
||||
}];
|
||||
|
||||
// Using a couple of heursitics we track if files have been moved to other locations within the app bundle
|
||||
// Using a couple of heuristics we track if files have been moved to other locations within the app bundle
|
||||
NSMutableDictionary<NSString *, NSString *> *frameworkVersionsSubstitutes = [NSMutableDictionary dictionary];
|
||||
NSMutableDictionary<NSString *, NSString *> *fileSubstitutes = [NSMutableDictionary dictionary];
|
||||
if (MAJOR_VERSION_IS_AT_LEAST(majorVersion, SUBinaryDeltaMajorVersion3)) {
|
||||
if (majorVersion >= SUBinaryDeltaMajorVersion3) {
|
||||
// Heuristic #1: track if an old framework version was removed and a new framework version was added
|
||||
// Keep track of these prefixes in a dictionary
|
||||
// Eg: /Contents/Frameworks/Foo.framework/Versions/B/ (new) -> /Contents/Frameworks/Foo.framework/Versions/A/ (old)
|
||||
@@ -855,7 +892,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
|
||||
NSNumber *newPermissions = nil;
|
||||
BOOL clonePermissionsChanged = NO;
|
||||
BOOL clonedBinaryDiff = NO;
|
||||
NSString *clonedRelativePath = MAJOR_VERSION_IS_AT_LEAST(majorVersion, SUBinaryDeltaMajorVersion3) ? cloneableRelativePath(afterFileKeyToHashDictionary, beforeHashToFileKeyDictionary, frameworkVersionsSubstitutes, fileSubstitutes, originalTreeState, newInfo, key, &newPermissions, &clonePermissionsChanged, &clonedBinaryDiff) : nil;
|
||||
NSString *clonedRelativePath = (majorVersion >= SUBinaryDeltaMajorVersion3) ? cloneableRelativePath(afterFileKeyToHashDictionary, beforeHashToFileKeyDictionary, frameworkVersionsSubstitutes, fileSubstitutes, originalTreeState, newInfo, key, &newPermissions, &clonePermissionsChanged, &clonedBinaryDiff) : nil;
|
||||
if (clonedRelativePath != nil) {
|
||||
if (clonedBinaryDiff) {
|
||||
NSDictionary *cloneInfo = originalTreeState[clonedRelativePath];
|
||||
@@ -918,7 +955,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
|
||||
|
||||
BOOL deltaOperationsFailed = NO;
|
||||
for (CreateBinaryDeltaOperation *operation in deltaOperations) {
|
||||
NSString *resultPath = [operation resultPath];
|
||||
NSString *resultPath = operation.resultPath;
|
||||
if (resultPath == nil) {
|
||||
if (verbose) {
|
||||
fprintf(stderr, "\n");
|
||||
@@ -952,7 +989,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
|
||||
|
||||
SPUDeltaArchiveItem *item = [[SPUDeltaArchiveItem alloc] initWithRelativeFilePath:relativePath commands:commands mode:mode.unsignedShortValue];
|
||||
item.itemFilePath = resultPath;
|
||||
item.sourcePath = operation._fromPath;
|
||||
item.sourcePath = operation.fromPath;
|
||||
item.clonedRelativePath = clonedRelativePath;
|
||||
|
||||
[archive addItem:item];
|
||||
@@ -972,7 +1009,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
|
||||
|
||||
// Clean up operations after the archive has finished encoding
|
||||
for (CreateBinaryDeltaOperation *operation in deltaOperations) {
|
||||
NSString *resultPath = [operation resultPath];
|
||||
NSString *resultPath = operation.resultPath;
|
||||
if (resultPath != nil) {
|
||||
unlink(resultPath.fileSystemRepresentation);
|
||||
}
|
||||
|
||||
@@ -14,9 +14,14 @@
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
#ifndef BUILDING_SPARKLE_TESTS
|
||||
SPU_OBJC_DIRECT_MEMBERS
|
||||
#endif
|
||||
@interface SUBinaryDeltaUnarchiver : NSObject <SUUnarchiverProtocol>
|
||||
|
||||
- (instancetype)initWithArchivePath:(NSString *)archivePath updateHostBundlePath:(NSString *)updateHostBundlePath;
|
||||
- (instancetype)initWithArchivePath:(NSString *)archivePath extractionDirectory:(NSString *)extractionDirectory updateHostBundlePath:(NSString *)updateHostBundlePath;
|
||||
|
||||
+ (BOOL)canUnarchivePath:(NSString *)path;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
@@ -16,17 +16,12 @@
|
||||
|
||||
#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;
|
||||
{
|
||||
NSString *_archivePath;
|
||||
NSString *_updateHostBundlePath;
|
||||
NSString *_extractionDirectory;
|
||||
}
|
||||
|
||||
+ (BOOL)canUnarchivePath:(NSString *)path
|
||||
{
|
||||
@@ -43,7 +38,11 @@
|
||||
// We used to invoke mdimport on the bundle but this is not a very good approach.
|
||||
// There's no need to do that for non-delta updates and for updates that contain no mdimporters.
|
||||
// Moreover, updating the timestamp on the mdimporter bundles is what developers have to do anyway when shipping their new update outside of Sparkle
|
||||
// Note: this is used from unit tests
|
||||
+ (void)updateSpotlightImportersAtBundlePath:(NSString *)targetPath
|
||||
#ifndef BUILDING_SPARKLE_TESTS
|
||||
SPU_OBJC_DIRECT
|
||||
#endif
|
||||
{
|
||||
NSURL *targetURL = [NSURL fileURLWithPath:targetPath];
|
||||
// Only recurse if it's actually a directory. Don't recurse into a
|
||||
@@ -73,17 +72,23 @@
|
||||
}
|
||||
}
|
||||
|
||||
- (instancetype)initWithArchivePath:(NSString *)archivePath updateHostBundlePath:(NSString *)updateHostBundlePath
|
||||
- (instancetype)initWithArchivePath:(NSString *)archivePath extractionDirectory:(NSString *)extractionDirectory updateHostBundlePath:(NSString *)updateHostBundlePath
|
||||
{
|
||||
self = [super init];
|
||||
if (self != nil) {
|
||||
_archivePath = [archivePath copy];
|
||||
_updateHostBundlePath = [updateHostBundlePath copy];
|
||||
_extractionDirectory = [extractionDirectory copy];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)unarchiveWithCompletionBlock:(void (^)(NSError * _Nullable))completionBlock progressBlock:(void (^ _Nullable)(double))progressBlock
|
||||
- (BOOL)needsVerifyBeforeExtractionKey
|
||||
{
|
||||
return NO;
|
||||
}
|
||||
|
||||
- (void)unarchiveWithCompletionBlock:(void (^)(NSError * _Nullable))completionBlock progressBlock:(void (^ _Nullable)(double))progressBlock waitForCleanup:(BOOL)__unused waitForCleanup
|
||||
{
|
||||
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
|
||||
@autoreleasepool {
|
||||
@@ -95,17 +100,17 @@
|
||||
|
||||
- (void)extractDeltaWithNotifier:(SUUnarchiverNotifier *)notifier
|
||||
{
|
||||
NSString *sourcePath = self.updateHostBundlePath;
|
||||
NSString *targetPath = [[self.archivePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:[sourcePath lastPathComponent]];
|
||||
NSString *sourcePath = _updateHostBundlePath;
|
||||
NSString *targetPath = [_extractionDirectory stringByAppendingPathComponent:[sourcePath lastPathComponent]];
|
||||
|
||||
NSError *applyDiffError = nil;
|
||||
BOOL success = applyBinaryDelta(sourcePath, targetPath, self.archivePath, NO, ^(double progress){
|
||||
BOOL success = applyBinaryDelta(sourcePath, targetPath, _archivePath, NO, ^(double progress){
|
||||
[notifier notifyProgress:progress];
|
||||
|
||||
}, &applyDiffError);
|
||||
|
||||
if (success) {
|
||||
[[self class] updateSpotlightImportersAtBundlePath:targetPath];
|
||||
[SUBinaryDeltaUnarchiver updateSpotlightImportersAtBundlePath:targetPath];
|
||||
[notifier notifySuccess];
|
||||
}
|
||||
else {
|
||||
@@ -113,6 +118,6 @@
|
||||
}
|
||||
}
|
||||
|
||||
- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], self.archivePath]; }
|
||||
- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], _archivePath]; }
|
||||
|
||||
@end
|
||||
@@ -11,16 +11,51 @@
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
#ifndef BUILDING_SPARKLE_TESTS
|
||||
#define SUCodeSigningVerifierDefinitionAttribute SPU_OBJC_DIRECT_MEMBERS
|
||||
#else
|
||||
#define SUCodeSigningVerifierDefinitionAttribute __attribute__((objc_runtime_name("SUTestCodeSigningVerifier")))
|
||||
#endif
|
||||
|
||||
typedef NS_ENUM(NSUInteger, SUValidateConnectionStatus) {
|
||||
SUValidateConnectionStatusSetCodeSigningRequirementSuccess = 0,
|
||||
SUValidateConnectionStatusSetNoRequirementSuccess,
|
||||
SUValidateConnectionStatusAPIFailure,
|
||||
SUValidateConnectionStatusCodeSigningRequirementFailure,
|
||||
SUValidateConectionNoSupportedValidationMethodFailure,
|
||||
};
|
||||
|
||||
typedef NS_OPTIONS(NSUInteger, SUValidateConnectionOptions) {
|
||||
// Default validation behavior (matches against Team ID from main executable if available)
|
||||
SUValidateConnectionOptionDefault = 0,
|
||||
|
||||
// Require that the connecting client has the app sandbox entitlement
|
||||
SUValidateConnectionOptionRequireSandboxEntitlement = 1 << 0,
|
||||
};
|
||||
|
||||
SUCodeSigningVerifierDefinitionAttribute
|
||||
@interface SUCodeSigningVerifier : NSObject
|
||||
|
||||
+ (BOOL)codeSignatureAtBundleURL:(NSURL *)oldBundleURL matchesSignatureAtBundleURL:(NSURL *)newBundleURL error:(NSError **)error;
|
||||
+ (BOOL)codeSignatureIsValidAtBundleURL:(NSURL *)newBundleURL andMatchesSignatureAtBundleURL:(NSURL *)oldBundleURL error:(NSError **)error;
|
||||
|
||||
+ (BOOL)codeSignatureIsValidAtBundleURL:(NSURL *)bundleURL checkNestedCode:(BOOL)checkNestedCode error:(NSError **)error;
|
||||
|
||||
// Same as above except does not check for nested code. This method should be used by the framework.
|
||||
+ (BOOL)codeSignatureIsValidAtBundleURL:(NSURL *)bundleURL error:(NSError *__autoreleasing *)error;
|
||||
|
||||
+ (BOOL)codeSignatureIsValidAtDownloadURL:(NSURL *)downloadURL andMatchesDeveloperIDTeamFromOldBundleURL:(NSURL *)oldBundleURL error:(NSError * __autoreleasing *)error;
|
||||
|
||||
+ (BOOL)bundleAtURLIsCodeSigned:(NSURL *)bundleURL;
|
||||
|
||||
+ (NSString * _Nullable)teamIdentifierAtURL:(NSURL *)url;
|
||||
+ (NSString * _Nullable)teamIdentifierFromMainExecutable;
|
||||
|
||||
+ (SUValidateConnectionStatus)validateConnection:(NSXPCConnection *)connection options:(SUValidateConnectionOptions)options error:(NSError * __autoreleasing *)error;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
#endif
|
||||
@@ -15,9 +15,15 @@
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
|
||||
@interface NSXPCConnection (Private)
|
||||
|
||||
@property (nonatomic, readonly) audit_token_t auditToken;
|
||||
|
||||
@end
|
||||
|
||||
@implementation SUCodeSigningVerifier
|
||||
|
||||
+ (BOOL)codeSignatureAtBundleURL:(NSURL *)oldBundleURL matchesSignatureAtBundleURL:(NSURL *)newBundleURL error:(NSError * __autoreleasing *)error
|
||||
+ (BOOL)codeSignatureIsValidAtBundleURL:(NSURL *)newBundleURL andMatchesSignatureAtBundleURL:(NSURL *)oldBundleURL error:(NSError * __autoreleasing *)error
|
||||
{
|
||||
OSStatus result;
|
||||
SecRequirementRef requirement = NULL;
|
||||
@@ -26,12 +32,17 @@
|
||||
CFErrorRef cfError = NULL;
|
||||
|
||||
result = SecStaticCodeCreateWithPath((__bridge CFURLRef)oldBundleURL, kSecCSDefaultFlags, &oldCode);
|
||||
if (result == errSecCSUnsigned) {
|
||||
if (result != noErr) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInsufficientSigningError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Bundle is not code signed: %@", newBundleURL] }];
|
||||
NSString *errorMessage =
|
||||
(result == errSecCSUnsigned) ?
|
||||
[NSString stringWithFormat:@"Bundle is not code signed: %@", oldBundleURL.path] :
|
||||
[NSString stringWithFormat:@"Failed to get static code (%d): %@", result, oldBundleURL.path];
|
||||
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInsufficientSigningError userInfo:@{ NSLocalizedDescriptionKey: errorMessage }];
|
||||
}
|
||||
|
||||
return NO;
|
||||
goto finally;
|
||||
}
|
||||
|
||||
result = SecCodeCopyDesignatedRequirement(oldCode, kSecCSDefaultFlags, &requirement);
|
||||
@@ -61,9 +72,9 @@
|
||||
|
||||
// Note that kSecCSCheckNestedCode may not work with pre-Mavericks code signing.
|
||||
// See https://github.com/sparkle-project/Sparkle/issues/376#issuecomment-48824267 and https://developer.apple.com/library/mac/technotes/tn2206
|
||||
// Aditionally, there are several reasons to stay away from deep verification and to prefer EdDSA signing the download archive instead.
|
||||
// Additionally, there are several reasons to stay away from deep verification and to prefer EdDSA signing the download archive instead.
|
||||
// See https://github.com/sparkle-project/Sparkle/pull/523#commitcomment-17549302 and https://github.com/sparkle-project/Sparkle/issues/543
|
||||
SecCSFlags flags = (SecCSFlags) (kSecCSDefaultFlags | kSecCSCheckAllArchitectures);
|
||||
SecCSFlags flags = kSecCSCheckAllArchitectures;
|
||||
result = SecStaticCodeCheckValidityWithErrors(staticCode, flags, requirement, &cfError);
|
||||
|
||||
if (result != errSecSuccess) {
|
||||
@@ -148,8 +159,8 @@ finally:
|
||||
goto finally;
|
||||
}
|
||||
|
||||
// See in -codeSignatureAtBundleURL:matchesSignatureAtBundleURL:error: for why kSecCSCheckNestedCode is not always passed
|
||||
SecCSFlags flags = (SecCSFlags) (kSecCSDefaultFlags | kSecCSCheckAllArchitectures);
|
||||
// See in -codeSignatureIsValidAtBundleURL:andMatchesSignatureAtBundleURL:error: for why kSecCSCheckNestedCode is not always passed
|
||||
SecCSFlags flags = kSecCSCheckAllArchitectures;
|
||||
if (checkNestedCode) {
|
||||
flags |= kSecCSCheckNestedCode;
|
||||
}
|
||||
@@ -209,22 +220,8 @@ static id valueOrNSNull(id value) {
|
||||
return value ? value : [NSNull null];
|
||||
}
|
||||
|
||||
+ (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 {
|
||||
+ (NSDictionary *)codeSignatureInfoForCode:(SecStaticCodeRef)code SPU_OBJC_DIRECT
|
||||
{
|
||||
CFDictionaryRef signingInfo = nil;
|
||||
const SecCSFlags flags = (SecCSFlags) (kSecCSSigningInformation | kSecCSRequirementInformation | kSecCSDynamicInformation | kSecCSContentInformation);
|
||||
if (SecCodeCopySigningInformation(code, flags, &signingInfo) == noErr) {
|
||||
@@ -241,7 +238,8 @@ finally:
|
||||
return nil;
|
||||
}
|
||||
|
||||
+ (NSDictionary *)logSigningInfoForCode:(SecStaticCodeRef)code label:(NSString*)label {
|
||||
+ (NSDictionary *)logSigningInfoForCode:(SecStaticCodeRef)code label:(NSString*)label SPU_OBJC_DIRECT
|
||||
{
|
||||
NSDictionary *relevantInfo = [self codeSignatureInfoForCode:code];
|
||||
SULog(SULogLevelDefault, @"%@: %@", label, relevantInfo);
|
||||
return relevantInfo;
|
||||
@@ -271,4 +269,274 @@ finally:
|
||||
return (result == 0);
|
||||
}
|
||||
|
||||
static NSString * _Nullable SUTeamIdentifierFromCode(SecStaticCodeRef staticCode)
|
||||
{
|
||||
CFDictionaryRef cfSigningInformation = NULL;
|
||||
OSStatus copySigningInfoCode = SecCodeCopySigningInformation(staticCode, kSecCSSigningInformation,
|
||||
&cfSigningInformation);
|
||||
|
||||
NSDictionary *signingInformation = CFBridgingRelease(cfSigningInformation);
|
||||
|
||||
if (copySigningInfoCode != noErr) {
|
||||
SULog(SULogLevelError, @"Failed to get signing information for retrieving team identifier: %d", copySigningInfoCode);
|
||||
return nil;
|
||||
}
|
||||
|
||||
// Note this will return nil for ad-hoc or unsigned binaries
|
||||
return signingInformation[(NSString *)kSecCodeInfoTeamIdentifier];
|
||||
}
|
||||
|
||||
+ (NSString * _Nullable)teamIdentifierAtURL:(NSURL *)url
|
||||
{
|
||||
SecStaticCodeRef staticCode = NULL;
|
||||
OSStatus staticCodeResult = SecStaticCodeCreateWithPath((__bridge CFURLRef)url, kSecCSDefaultFlags, &staticCode);
|
||||
if (staticCodeResult != errSecSuccess) {
|
||||
SULog(SULogLevelError, @"Failed to get static code for retrieving team identifier: %d", staticCodeResult);
|
||||
return nil;
|
||||
}
|
||||
|
||||
NSString *teamIdentifier = SUTeamIdentifierFromCode(staticCode);
|
||||
|
||||
if (staticCode != NULL) {
|
||||
CFRelease(staticCode);
|
||||
}
|
||||
|
||||
return teamIdentifier;
|
||||
}
|
||||
|
||||
+ (NSString * _Nullable)teamIdentifierFromMainExecutable
|
||||
{
|
||||
SecCodeRef code = NULL;
|
||||
OSStatus result = SecCodeCopySelf(kSecCSDefaultFlags, &code);
|
||||
if (result != errSecSuccess) {
|
||||
SULog(SULogLevelError, @"Failed to get code for retrieving team identifier of main executable: %d", result);
|
||||
return nil;
|
||||
}
|
||||
|
||||
NSString *teamIdentifier = SUTeamIdentifierFromCode(code);
|
||||
|
||||
CFRelease(code);
|
||||
|
||||
return teamIdentifier;
|
||||
}
|
||||
|
||||
+ (BOOL)codeSignatureIsValidAtDownloadURL:(NSURL *)downloadURL andMatchesDeveloperIDTeamFromOldBundleURL:(NSURL *)oldBundleURL error:(NSError * __autoreleasing *)error
|
||||
{
|
||||
NSString *teamIdentifier = nil;
|
||||
NSString *requirementString = nil;
|
||||
SecRequirementRef requirement = NULL;
|
||||
SecStaticCodeRef oldStaticCode = NULL;
|
||||
SecStaticCodeRef downloadStaticCode = NULL;
|
||||
OSStatus result;
|
||||
|
||||
NSError *resultError = nil;
|
||||
|
||||
NSString *commonErrorMessage = @"The download archive cannot be validated with Apple Developer ID code signing as fallback (after (Ed)DSA verification has failed)";
|
||||
|
||||
result = SecStaticCodeCreateWithPath((__bridge CFURLRef)oldBundleURL, kSecCSDefaultFlags, &oldStaticCode);
|
||||
if (result != errSecSuccess) {
|
||||
NSString *errorMessage =
|
||||
(result == errSecCSUnsigned) ?
|
||||
[NSString stringWithFormat:@"%@. The original app is not code signed: %@", commonErrorMessage, oldBundleURL.path] :
|
||||
[NSString stringWithFormat:@"%@. The static code could not be retrieved from the original app (%d): %@", commonErrorMessage, result, oldBundleURL.path];
|
||||
|
||||
resultError = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInsufficientSigningError userInfo:@{ NSLocalizedDescriptionKey: errorMessage }];
|
||||
|
||||
goto finally;
|
||||
}
|
||||
|
||||
teamIdentifier = SUTeamIdentifierFromCode(oldStaticCode);
|
||||
if (teamIdentifier == nil) {
|
||||
resultError = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInsufficientSigningError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"%@. The team identifier could not be retrieved from the original app: %@", commonErrorMessage, oldBundleURL.path] }];
|
||||
|
||||
goto finally;
|
||||
}
|
||||
|
||||
// Create a designated requirement with developer ID signing with this team ID
|
||||
// Validate it against code signing check of this archive
|
||||
// CertificateIssuedByApple = anchor apple generic
|
||||
// IssuerIsDeveloperID = certificate 1[field.1.2.840.113635.100.6.2.6]
|
||||
// LeafIsDeveloperIDApp = certificate leaf[field.1.2.840.113635.100.6.1.13]
|
||||
// DeveloperIDTeamID = certificate leaf[subject.OU]
|
||||
// https://developer.apple.com/documentation/technotes/tn3127-inside-code-signing-requirements#Xcode-designated-requirement-for-Developer-ID-code
|
||||
requirementString = [NSString stringWithFormat:@"anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] and certificate leaf[field.1.2.840.113635.100.6.1.13] and certificate leaf[subject.OU] = \"%@\"", teamIdentifier];
|
||||
|
||||
result = SecRequirementCreateWithString((__bridge CFStringRef)requirementString, kSecCSDefaultFlags, &requirement);
|
||||
if (result != errSecSuccess) {
|
||||
resultError = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInsufficientSigningError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"%@. The designated requirement string with a Developer ID requirement with team identifier '%@' could not be created with error %d", commonErrorMessage, teamIdentifier, result] }];
|
||||
|
||||
goto finally;
|
||||
}
|
||||
|
||||
result = SecStaticCodeCreateWithPath((__bridge CFURLRef)downloadURL, kSecCSDefaultFlags, &downloadStaticCode);
|
||||
if (result != errSecSuccess) {
|
||||
NSString *message = [NSString stringWithFormat:@"%@. The static code could not be retrieved from the download archive with error %d. The download archive may not be Apple code signed.", commonErrorMessage, result];
|
||||
|
||||
SULog(SULogLevelError, @"%@", message);
|
||||
|
||||
resultError = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInsufficientSigningError userInfo:@{ NSLocalizedDescriptionKey: message }];
|
||||
|
||||
goto finally;
|
||||
}
|
||||
|
||||
SecCSFlags flags = (SecCSFlags)kSecCSDefaultFlags;
|
||||
CFErrorRef cfError = NULL;
|
||||
result = SecStaticCodeCheckValidityWithErrors(downloadStaticCode, flags, requirement, &cfError);
|
||||
if (result != errSecSuccess) {
|
||||
NSError *underlyingError;
|
||||
if (cfError != NULL) {
|
||||
NSError *tmpError = CFBridgingRelease(cfError);
|
||||
underlyingError = tmpError;
|
||||
} else {
|
||||
underlyingError = nil;
|
||||
}
|
||||
|
||||
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
|
||||
if (underlyingError != nil) {
|
||||
userInfo[NSUnderlyingErrorKey] = underlyingError;
|
||||
}
|
||||
|
||||
if (result == errSecCSUnsigned) {
|
||||
NSString *message = [NSString stringWithFormat:@"%@. The download archive is not Apple code signed.", commonErrorMessage];
|
||||
|
||||
SULog(SULogLevelError, @"%@", message);
|
||||
|
||||
userInfo[NSLocalizedDescriptionKey] = message;
|
||||
|
||||
resultError = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInsufficientSigningError userInfo:[userInfo copy]];
|
||||
} else if (result == errSecCSReqFailed) {
|
||||
NSString *initialMessage = [NSString stringWithFormat:@"%@. The Apple code signature of new downloaded archive is either not Developer ID code signed, or doesn't have a Team ID that matches the old app version (%@). Please ensure that the archive and app are signed using the same Developer ID certificate.", commonErrorMessage, teamIdentifier];
|
||||
|
||||
NSDictionary *oldInfo = [self logSigningInfoForCode:oldStaticCode label:@"old info"];
|
||||
NSDictionary *newInfo = [self logSigningInfoForCode:downloadStaticCode label:@"new info"];
|
||||
|
||||
userInfo[NSLocalizedDescriptionKey] = [NSString stringWithFormat:@"%@ old info: %@. new info: %@", initialMessage, oldInfo, newInfo];
|
||||
|
||||
resultError = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInsufficientSigningError userInfo:[userInfo copy]];
|
||||
} else {
|
||||
userInfo[NSLocalizedDescriptionKey] = [NSString stringWithFormat:@"%@. The downloaded archive code signing signature failed to validate with an unknown error (%d).", commonErrorMessage, result];
|
||||
|
||||
resultError = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInsufficientSigningError userInfo:[userInfo copy]];
|
||||
}
|
||||
|
||||
goto finally;
|
||||
}
|
||||
|
||||
finally:
|
||||
|
||||
if (oldStaticCode != NULL) {
|
||||
CFRelease(oldStaticCode);
|
||||
}
|
||||
|
||||
if (requirement != NULL) {
|
||||
CFRelease(requirement);
|
||||
}
|
||||
|
||||
if (downloadStaticCode != NULL) {
|
||||
CFRelease(downloadStaticCode);
|
||||
}
|
||||
|
||||
if (resultError != nil && error != NULL) {
|
||||
*error = resultError;
|
||||
}
|
||||
|
||||
return (resultError == nil);
|
||||
}
|
||||
|
||||
+ (SUValidateConnectionStatus)validateConnection:(NSXPCConnection *)connection options:(SUValidateConnectionOptions)options error:(NSError * __autoreleasing *)error
|
||||
{
|
||||
NSMutableArray<NSString *> *codeSigningRequirementComponents = [NSMutableArray array];
|
||||
|
||||
// Build the default team ID signing requirement
|
||||
NSString *hostTeamIdentifier = [self teamIdentifierFromMainExecutable];
|
||||
if (hostTeamIdentifier != nil) {
|
||||
NSString *teamIdentifierRequirement = [NSString stringWithFormat:@"(anchor apple generic and certificate leaf[subject.OU] = \"%@\")", hostTeamIdentifier];
|
||||
[codeSigningRequirementComponents addObject:teamIdentifierRequirement];
|
||||
}
|
||||
|
||||
// Build the sandboxing requirement
|
||||
if ((options & SUValidateConnectionOptionRequireSandboxEntitlement) != 0) {
|
||||
// This ensures the entitlement is set to true too
|
||||
NSString *sandboxingRequirement = @"(entitlement [\"com.apple.security.app-sandbox\"] exists)";
|
||||
[codeSigningRequirementComponents addObject:sandboxingRequirement];
|
||||
}
|
||||
|
||||
// Check if no requirement is required
|
||||
if (codeSigningRequirementComponents.count == 0) {
|
||||
return SUValidateConnectionStatusSetNoRequirementSuccess;
|
||||
}
|
||||
|
||||
NSString *codeSigningRequirement = [codeSigningRequirementComponents componentsJoinedByString:@" and "];
|
||||
|
||||
if (@available(macOS 13.0, *)) {
|
||||
[connection setCodeSigningRequirement:codeSigningRequirement];
|
||||
|
||||
return SUValidateConnectionStatusSetCodeSigningRequirementSuccess;
|
||||
}
|
||||
|
||||
// Fall back to audit token on older OS's
|
||||
if ([connection respondsToSelector:@selector(auditToken)]) {
|
||||
audit_token_t auditToken = [connection auditToken];
|
||||
NSData *auditTokenData = [NSData dataWithBytes:&auditToken length:sizeof(auditToken)];
|
||||
|
||||
NSDictionary *attributes = @{
|
||||
(NSString *)kSecGuestAttributeAudit: auditTokenData
|
||||
};
|
||||
|
||||
SecCodeRef code = NULL;
|
||||
OSStatus result = SecCodeCopyGuestWithAttributes(NULL, (__bridge CFDictionaryRef _Nullable)(attributes), kSecCSDefaultFlags, &code);
|
||||
if (result != errSecSuccess) {
|
||||
CFRelease(code);
|
||||
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInsufficientSigningError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"The client connection could not be validated because SecCodeCopyGuestWithAttributes() failed with error %d", result] }];
|
||||
}
|
||||
|
||||
return SUValidateConnectionStatusAPIFailure;
|
||||
}
|
||||
|
||||
// Check if the client is code signed with our signing requirement
|
||||
|
||||
SecRequirementRef requirement = NULL;
|
||||
result = SecRequirementCreateWithString((__bridge CFStringRef)codeSigningRequirement, kSecCSDefaultFlags, &requirement);
|
||||
|
||||
if (result != errSecSuccess) {
|
||||
CFRelease(code);
|
||||
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInsufficientSigningError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"The client connection could not be validated because SecRequirementCreateWithString() failed with error %d", result] }];
|
||||
}
|
||||
|
||||
return SUValidateConnectionStatusAPIFailure;
|
||||
}
|
||||
|
||||
CFErrorRef cfError = NULL;
|
||||
// This is not a static code, so we don't pass kSecCSCheckAllArchitectures
|
||||
result = SecCodeCheckValidityWithErrors(code, kSecCSDefaultFlags, requirement, &cfError);
|
||||
|
||||
CFRelease(requirement);
|
||||
requirement = NULL;
|
||||
|
||||
if (result != errSecSuccess) {
|
||||
NSError *cfBridgedError = (NSError *)CFBridgingRelease(cfError);
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInsufficientSigningError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"The client connection could not be validated because validating the code signature failed with error %d (%@). Does the app meet the designated requirement: %@", result, cfBridgedError.localizedDescription, codeSigningRequirement] }];
|
||||
}
|
||||
|
||||
[self logSigningInfoForCode:code label:@"Client"];
|
||||
|
||||
CFRelease(code);
|
||||
|
||||
return SUValidateConnectionStatusCodeSigningRequirementFailure;
|
||||
}
|
||||
|
||||
CFRelease(code);
|
||||
|
||||
return SUValidateConnectionStatusSetCodeSigningRequirementSuccess;
|
||||
}
|
||||
|
||||
// Not much we can do if auditToken is not supported. This code should not be reached though.
|
||||
return SUValidateConectionNoSupportedValidationMethodFailure;
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -14,9 +14,11 @@
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface SUDiskImageUnarchiver : NSObject <SUUnarchiverProtocol>
|
||||
SPU_OBJC_DIRECT_MEMBERS @interface SUDiskImageUnarchiver : NSObject <SUUnarchiverProtocol>
|
||||
|
||||
- (instancetype)initWithArchivePath:(NSString *)archivePath decryptionPassword:(nullable NSString *)decryptionPassword;
|
||||
- (instancetype)initWithArchivePath:(NSString *)archivePath extractionDirectory:(NSString *)extractionDirectory decryptionPassword:(nullable NSString *)decryptionPassword;
|
||||
|
||||
+ (BOOL)canUnarchivePath:(NSString *)path;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
@@ -9,21 +9,24 @@
|
||||
#import "SUDiskImageUnarchiver.h"
|
||||
#import "SUUnarchiverNotifier.h"
|
||||
#import "SULog.h"
|
||||
#import "SUErrors.h"
|
||||
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
|
||||
@interface SUDiskImageUnarchiver ()
|
||||
|
||||
@property (nonatomic, copy, readonly) NSString *archivePath;
|
||||
@property (nullable, nonatomic, copy, readonly) NSString *decryptionPassword;
|
||||
|
||||
@interface SUDiskImageUnarchiver () <NSFileManagerDelegate>
|
||||
@end
|
||||
|
||||
@implementation SUDiskImageUnarchiver
|
||||
|
||||
@synthesize archivePath = _archivePath;
|
||||
@synthesize decryptionPassword = _decryptionPassword;
|
||||
{
|
||||
NSString *_archivePath;
|
||||
NSString *_decryptionPassword;
|
||||
NSString *_extractionDirectory;
|
||||
|
||||
SUUnarchiverNotifier *_notifier;
|
||||
double _currentExtractionProgress;
|
||||
double _fileProgressIncrement;
|
||||
}
|
||||
|
||||
+ (BOOL)canUnarchivePath:(NSString *)path
|
||||
{
|
||||
@@ -35,26 +38,51 @@
|
||||
return NO;
|
||||
}
|
||||
|
||||
- (instancetype)initWithArchivePath:(NSString *)archivePath decryptionPassword:(nullable NSString *)decryptionPassword
|
||||
- (instancetype)initWithArchivePath:(NSString *)archivePath extractionDirectory:(NSString *)extractionDirectory decryptionPassword:(nullable NSString *)decryptionPassword
|
||||
{
|
||||
self = [super init];
|
||||
if (self != nil) {
|
||||
_archivePath = [archivePath copy];
|
||||
_decryptionPassword = [decryptionPassword copy];
|
||||
_extractionDirectory = [extractionDirectory copy];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)unarchiveWithCompletionBlock:(void (^)(NSError * _Nullable))completionBlock progressBlock:(void (^ _Nullable)(double))progressBlock
|
||||
- (BOOL)needsVerifyBeforeExtractionKey
|
||||
{
|
||||
return NO;
|
||||
}
|
||||
|
||||
- (void)unarchiveWithCompletionBlock:(void (^)(NSError * _Nullable))completionBlock progressBlock:(void (^ _Nullable)(double))progressBlock waitForCleanup:(BOOL)waitForCleanup
|
||||
{
|
||||
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
|
||||
SUUnarchiverNotifier *notifier = [[SUUnarchiverNotifier alloc] initWithCompletionBlock:completionBlock progressBlock:progressBlock];
|
||||
[self extractDMGWithNotifier:notifier];
|
||||
[self extractDMGWithNotifier:notifier waitForCleanup:waitForCleanup];
|
||||
});
|
||||
}
|
||||
|
||||
static NSUInteger fileCountForDirectory(NSFileManager *fileManager, NSString *itemPath)
|
||||
{
|
||||
NSUInteger fileCount = 0;
|
||||
NSDirectoryEnumerator *dirEnum = [fileManager enumeratorAtPath:itemPath];
|
||||
for (NSString * __unused currentFile in dirEnum) {
|
||||
fileCount++;
|
||||
}
|
||||
|
||||
return fileCount;
|
||||
}
|
||||
|
||||
- (BOOL)fileManager:(NSFileManager *)fileManager shouldCopyItemAtURL:(NSURL *)srcURL toURL:(NSURL *)dstURL
|
||||
{
|
||||
_currentExtractionProgress += _fileProgressIncrement;
|
||||
[_notifier notifyProgress:_currentExtractionProgress];
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
// Called on a non-main thread.
|
||||
- (void)extractDMGWithNotifier:(SUUnarchiverNotifier *)notifier
|
||||
- (void)extractDMGWithNotifier:(SUUnarchiverNotifier *)notifier waitForCleanup:(BOOL)waitForCleanup SPU_OBJC_DIRECT
|
||||
{
|
||||
@autoreleasepool {
|
||||
BOOL mountedSuccessfully = NO;
|
||||
@@ -64,44 +92,47 @@
|
||||
NSFileManager *manager;
|
||||
NSError *error = nil;
|
||||
NSArray *contents = nil;
|
||||
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)
|
||||
{
|
||||
NSString *uuidString = CFBridgingRelease(CFUUIDCreateString(NULL, uuid));
|
||||
if (uuidString)
|
||||
{
|
||||
mountPoint = [@"/Volumes" stringByAppendingPathComponent:uuidString];
|
||||
}
|
||||
CFRelease(uuid);
|
||||
}
|
||||
}
|
||||
do {
|
||||
NSString *uuidString = [[NSUUID UUID] UUIDString];
|
||||
mountPoint = [@"/Volumes" stringByAppendingPathComponent:uuidString];
|
||||
}
|
||||
// Note: this check does not follow symbolic links, which is what we want
|
||||
while ([[NSURL fileURLWithPath:mountPoint] checkResourceIsReachableAndReturnError:NULL]);
|
||||
while ([[NSURL fileURLWithPath:mountPoint] checkResourceIsReachableAndReturnError:NULL]);
|
||||
|
||||
NSData *promptData = [NSData dataWithBytes:"yes\n" length:4];
|
||||
NSMutableData *inputData = [NSMutableData data];
|
||||
|
||||
NSMutableArray *arguments = [@[@"attach", self.archivePath, @"-mountpoint", mountPoint, /*@"-noverify",*/ @"-nobrowse", @"-noautoopen"] mutableCopy];
|
||||
|
||||
if (self.decryptionPassword) {
|
||||
NSMutableData *passwordData = [[self.decryptionPassword dataUsingEncoding:NSUTF8StringEncoding] mutableCopy];
|
||||
// Prepare stdin data for passwords and license agreements
|
||||
{
|
||||
// If no password is supplied, we will still be asked a password.
|
||||
// In that case we respond with an empty password.
|
||||
NSData *decryptionPasswordData = [_decryptionPassword dataUsingEncoding:NSUTF8StringEncoding];
|
||||
if (decryptionPasswordData != nil) {
|
||||
[inputData appendData:decryptionPasswordData];
|
||||
}
|
||||
|
||||
// From the hdiutil docs:
|
||||
// read a null-terminated passphrase from standard input
|
||||
//
|
||||
// Add the null terminator, then the newline
|
||||
[passwordData appendData:[NSData dataWithBytes:"\0" length:1]];
|
||||
[passwordData appendData:promptData];
|
||||
promptData = passwordData;
|
||||
// Add the null terminator
|
||||
[inputData appendBytes:"\0" length:1];
|
||||
|
||||
[arguments addObject:@"-stdinpass"];
|
||||
// Append prompt data for license agreements
|
||||
[inputData appendBytes:"yes\n" length:4];
|
||||
}
|
||||
|
||||
// Finder doesn't verify disk images anymore beyond the code signing signature (if available)
|
||||
// Opt out of the old CRC checksum checks
|
||||
// Also always pass -stdinpass so we gracefully handle password protected disk images even if we aren't expecting them
|
||||
NSArray *arguments = @[@"attach", _archivePath, @"-mountpoint", mountPoint, @"-noverify", @"-nobrowse", @"-noautoopen", @"-stdinpass"];
|
||||
|
||||
NSData *output = nil;
|
||||
NSInteger taskResult = -1;
|
||||
|
||||
NSURL *mountPointURL = [NSURL fileURLWithPath:mountPoint isDirectory:YES];
|
||||
NSURL *extractionDirectoryURL = [NSURL fileURLWithPath:_extractionDirectory isDirectory:YES];
|
||||
NSMutableArray<NSString *> *itemsToExtract = [NSMutableArray array];
|
||||
NSUInteger totalFileExtractionCount = 0;
|
||||
|
||||
{
|
||||
NSTask *task = [[NSTask alloc] init];
|
||||
task.launchPath = @"/usr/bin/hdiutil";
|
||||
@@ -128,33 +159,25 @@
|
||||
dispatch_semaphore_signal(terminationSemaphore);
|
||||
};
|
||||
|
||||
if (@available(macOS 10.13, *)) {
|
||||
if (![task launchAndReturnError:&error]) {
|
||||
goto reportError;
|
||||
}
|
||||
} else {
|
||||
@try {
|
||||
[task launch];
|
||||
} @catch (NSException *) {
|
||||
goto reportError;
|
||||
}
|
||||
if (![task launchAndReturnError:&error]) {
|
||||
goto reportError;
|
||||
}
|
||||
|
||||
[notifier notifyProgress:0.125];
|
||||
|
||||
[inputPipe.fileHandleForWriting writeData:promptData];
|
||||
|
||||
if (@available(macOS 10.15, *)) {
|
||||
if (![inputPipe.fileHandleForWriting writeData:promptData error:&error]) {
|
||||
if (![inputPipe.fileHandleForWriting writeData:inputData error:&error]) {
|
||||
goto reportError;
|
||||
}
|
||||
} else {
|
||||
}
|
||||
#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_15
|
||||
else
|
||||
{
|
||||
@try {
|
||||
[inputPipe.fileHandleForWriting writeData:promptData];
|
||||
[inputPipe.fileHandleForWriting writeData:inputData];
|
||||
} @catch (NSException *) {
|
||||
goto reportError;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
[inputPipe.fileHandleForWriting closeFile];
|
||||
|
||||
@@ -164,54 +187,110 @@
|
||||
taskResult = task.terminationStatus;
|
||||
}
|
||||
|
||||
[notifier notifyProgress:0.5];
|
||||
|
||||
if (taskResult != 0)
|
||||
{
|
||||
if (taskResult != 0) {
|
||||
NSString *resultStr = output ? [[NSString alloc] initWithData:output encoding:NSUTF8StringEncoding] : nil;
|
||||
SULog(SULogLevelError, @"hdiutil failed with code: %ld data: <<%@>>", (long)taskResult, resultStr);
|
||||
|
||||
error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Extraction failed due to hdiutil returning %ld status: %@", (long)taskResult, resultStr]}];
|
||||
|
||||
goto reportError;
|
||||
}
|
||||
|
||||
mountedSuccessfully = YES;
|
||||
|
||||
// Mounting can take some time, so increment progress
|
||||
_currentExtractionProgress = 0.1;
|
||||
[notifier notifyProgress:_currentExtractionProgress];
|
||||
|
||||
// Now that we've mounted it, we need to copy out its contents.
|
||||
manager = [[NSFileManager alloc] init];
|
||||
contents = [manager contentsOfDirectoryAtPath:mountPoint error:&error];
|
||||
if (contents == nil)
|
||||
{
|
||||
if (contents == nil) {
|
||||
SULog(SULogLevelError, @"Couldn't enumerate contents of archive mounted at %@: %@", mountPoint, error);
|
||||
goto reportError;
|
||||
}
|
||||
|
||||
double itemsCopied = 0;
|
||||
double totalItems = (double)[contents count];
|
||||
|
||||
for (NSString *item in contents)
|
||||
{
|
||||
NSString *fromPath = [mountPoint stringByAppendingPathComponent:item];
|
||||
NSString *toPath = [[self.archivePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:item];
|
||||
|
||||
// Sparkle can support installing pkg files, app bundles, and other bundle types for plug-ins
|
||||
// We must not filter any of those out
|
||||
for (NSString *item in contents) {
|
||||
NSURL *fromPathURL = [mountPointURL URLByAppendingPathComponent:item];
|
||||
|
||||
itemsCopied += 1.0;
|
||||
[notifier notifyProgress:0.5 + itemsCopied/(totalItems*2.0)];
|
||||
NSString *lastPathComponent = fromPathURL.lastPathComponent;
|
||||
|
||||
// We skip any files in the DMG which are not readable but include the item in the progress
|
||||
if (![manager isReadableFileAtPath:fromPath]) {
|
||||
// Ignore hidden files
|
||||
if ([lastPathComponent hasPrefix:@"."]) {
|
||||
continue;
|
||||
}
|
||||
|
||||
SULog(SULogLevelDefault, @"copyItemAtPath:%@ toPath:%@", fromPath, toPath);
|
||||
|
||||
if (![manager copyItemAtPath:fromPath toPath:toPath error:&error])
|
||||
{
|
||||
|
||||
// Ignore aliases
|
||||
NSNumber *aliasFlag = nil;
|
||||
if ([fromPathURL getResourceValue:&aliasFlag forKey:NSURLIsAliasFileKey error:NULL] && aliasFlag.boolValue) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Ignore symbolic links
|
||||
NSNumber *symbolicFlag = nil;
|
||||
if ([fromPathURL getResourceValue:&symbolicFlag forKey:NSURLIsSymbolicLinkKey error:NULL] && symbolicFlag.boolValue) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Ensure file is readable
|
||||
NSNumber *isReadableFlag = nil;
|
||||
if ([fromPathURL getResourceValue:&isReadableFlag forKey:NSURLIsReadableKey error:NULL] && !isReadableFlag.boolValue) {
|
||||
continue;
|
||||
}
|
||||
|
||||
NSNumber *isDirectoryFlag = nil;
|
||||
if (![fromPathURL getResourceValue:&isDirectoryFlag forKey:NSURLIsDirectoryKey error:NULL]) {
|
||||
continue;
|
||||
}
|
||||
|
||||
BOOL isDirectory = isDirectoryFlag.boolValue;
|
||||
NSString *pathExtension = fromPathURL.pathExtension;
|
||||
|
||||
if (isDirectory) {
|
||||
// Skip directory types that aren't bundles or regular directories
|
||||
if ([pathExtension isEqualToString:@"rtfd"]) {
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
// The only non-directory files we care about are (m)pkg files
|
||||
if (![pathExtension isEqualToString:@"pkg"] && ![pathExtension isEqualToString:@"mpkg"]) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (isDirectory) {
|
||||
totalFileExtractionCount += fileCountForDirectory(manager, fromPathURL.path);
|
||||
} else {
|
||||
totalFileExtractionCount++;
|
||||
}
|
||||
|
||||
[itemsToExtract addObject:item];
|
||||
}
|
||||
|
||||
_fileProgressIncrement = (0.99 - _currentExtractionProgress) / totalFileExtractionCount;
|
||||
_notifier = notifier;
|
||||
|
||||
// Copy all items we want to extract and notify of progress
|
||||
manager.delegate = self;
|
||||
for (NSString *item in itemsToExtract) {
|
||||
NSURL *fromURL = [mountPointURL URLByAppendingPathComponent:item];
|
||||
NSURL *toURL = [extractionDirectoryURL URLByAppendingPathComponent:item];
|
||||
|
||||
if (![manager copyItemAtURL:fromURL toURL:toURL error:&error]) {
|
||||
SULog(SULogLevelError, @"Failed to copy '%@' to '%@' with error: %@", fromURL.path, toURL.path, error);
|
||||
goto reportError;
|
||||
}
|
||||
}
|
||||
|
||||
[notifier notifySuccess];
|
||||
[notifier notifyProgress:1.0];
|
||||
|
||||
BOOL success = YES;
|
||||
goto finally;
|
||||
|
||||
reportError:
|
||||
[notifier notifyFailureWithError:error];
|
||||
success = NO;
|
||||
|
||||
finally:
|
||||
if (mountedSuccessfully) {
|
||||
@@ -221,27 +300,25 @@
|
||||
task.standardOutput = [NSPipe pipe];
|
||||
task.standardError = [NSPipe pipe];
|
||||
|
||||
|
||||
if (@available(macOS 10.13, *)) {
|
||||
NSError *launchCleanupError = nil;
|
||||
if (![task launchAndReturnError:&launchCleanupError]) {
|
||||
SULog(SULogLevelError, @"Failed to unmount %@", mountPoint);
|
||||
SULog(SULogLevelError, @"Error: %@", launchCleanupError);
|
||||
}
|
||||
} else {
|
||||
@try {
|
||||
[task launch];
|
||||
} @catch (NSException *exception) {
|
||||
SULog(SULogLevelError, @"Failed to unmount %@", mountPoint);
|
||||
SULog(SULogLevelError, @"Exception: %@", exception);
|
||||
}
|
||||
NSError *launchCleanupError = nil;
|
||||
if (![task launchAndReturnError:&launchCleanupError]) {
|
||||
SULog(SULogLevelError, @"Failed to unmount %@", mountPoint);
|
||||
SULog(SULogLevelError, @"Error: %@", launchCleanupError);
|
||||
} else if (waitForCleanup) {
|
||||
[task waitUntilExit];
|
||||
}
|
||||
} else {
|
||||
SULog(SULogLevelError, @"Can't mount DMG %@", self.archivePath);
|
||||
SULog(SULogLevelError, @"Can't mount DMG %@", _archivePath);
|
||||
}
|
||||
|
||||
if (success) {
|
||||
[notifier notifySuccess];
|
||||
} else {
|
||||
[notifier notifyFailureWithError:error];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], self.archivePath]; }
|
||||
- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], _archivePath]; }
|
||||
|
||||
@end
|
||||
@@ -6,16 +6,22 @@
|
||||
// Copyright © 2021 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#if SPARKLE_BUILD_PACKAGE_SUPPORT
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "SUUnarchiverProtocol.h"
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
// An unarchiver for flat packages that doesn't really do any unarchiving
|
||||
@interface SUFlatPackageUnarchiver : NSObject <SUUnarchiverProtocol>
|
||||
SPU_OBJC_DIRECT_MEMBERS @interface SUFlatPackageUnarchiver : NSObject <SUUnarchiverProtocol>
|
||||
|
||||
- (instancetype)initWithFlatPackagePath:(NSString *)flatPackagePath expectingInstallationType:(NSString *)installationType;
|
||||
- (instancetype)initWithFlatPackagePath:(NSString *)flatPackagePath extractionDirectory:(NSString *)extractionDirectory expectingInstallationType:(NSString *)installationType;
|
||||
|
||||
+ (BOOL)canUnarchivePath:(NSString *)path;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
#endif
|
||||
@@ -6,6 +6,8 @@
|
||||
// Copyright © 2021 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#if SPARKLE_BUILD_PACKAGE_SUPPORT
|
||||
|
||||
#import "SUFlatPackageUnarchiver.h"
|
||||
#import "SUUnarchiverNotifier.h"
|
||||
#import "SPUInstallationType.h"
|
||||
@@ -14,17 +16,12 @@
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
|
||||
@interface SUFlatPackageUnarchiver ()
|
||||
|
||||
@property (nonatomic, readonly) NSString *flatPackagePath;
|
||||
@property (nonatomic, readonly) NSString *expectedInstallationType;
|
||||
|
||||
@end
|
||||
|
||||
@implementation SUFlatPackageUnarchiver
|
||||
|
||||
@synthesize flatPackagePath = _flatPackagePath;
|
||||
@synthesize expectedInstallationType = _expectedInstallationType;
|
||||
{
|
||||
NSString *_flatPackagePath;
|
||||
NSString *_expectedInstallationType;
|
||||
NSString *_extractionDirectory;
|
||||
}
|
||||
|
||||
+ (BOOL)canUnarchivePath:(NSString *)path
|
||||
{
|
||||
@@ -36,32 +33,52 @@
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (instancetype)initWithFlatPackagePath:(NSString *)flatPackagePath expectingInstallationType:(NSString *)installationType
|
||||
- (instancetype)initWithFlatPackagePath:(NSString *)flatPackagePath extractionDirectory:(NSString *)extractionDirectory expectingInstallationType:(NSString *)installationType
|
||||
{
|
||||
self = [super init];
|
||||
if (self != nil) {
|
||||
_flatPackagePath = [flatPackagePath copy];
|
||||
_expectedInstallationType = [installationType copy];
|
||||
_extractionDirectory = [extractionDirectory copy];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)unarchiveWithCompletionBlock:(void (^)(NSError * _Nullable))completionBlock progressBlock:(void (^ _Nullable)(double))progressBlock
|
||||
- (BOOL)needsVerifyBeforeExtractionKey
|
||||
{
|
||||
return NO;
|
||||
}
|
||||
|
||||
- (void)unarchiveWithCompletionBlock:(void (^)(NSError * _Nullable))completionBlock progressBlock:(void (^ _Nullable)(double))progressBlock waitForCleanup:(BOOL)__unused waitForCleanup
|
||||
{
|
||||
SUUnarchiverNotifier *notifier = [[SUUnarchiverNotifier alloc] initWithCompletionBlock:completionBlock progressBlock:progressBlock];
|
||||
|
||||
// Flat packages must use guided package installs, not interactive
|
||||
BOOL isDirectory = NO;
|
||||
if (![self.expectedInstallationType isEqualToString:SPUInstallationTypeGuidedPackage]) {
|
||||
[notifier notifyFailureWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Flat package does not have guided installation type but %@ instead", self.expectedInstallationType]}]];
|
||||
} else if (![[NSFileManager defaultManager] fileExistsAtPath:self.flatPackagePath isDirectory:&isDirectory] || isDirectory) {
|
||||
[notifier notifyFailureWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Flat package does not exist at %@", self.flatPackagePath]}]];
|
||||
if (![_expectedInstallationType isEqualToString:SPUInstallationTypeGuidedPackage]) {
|
||||
[notifier notifyFailureWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Flat package does not have guided installation type but %@ instead", _expectedInstallationType]}]];
|
||||
} else if (![[NSFileManager defaultManager] fileExistsAtPath:_flatPackagePath isDirectory:&isDirectory] || isDirectory) {
|
||||
[notifier notifyFailureWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Flat package does not exist at %@", _flatPackagePath]}]];
|
||||
} else {
|
||||
[notifier notifyProgress:1.0];
|
||||
[notifier notifySuccess];
|
||||
// Copying the flat package should be very fast, especially on APFS
|
||||
NSError *copyError = nil;
|
||||
if (![[NSFileManager defaultManager] copyItemAtPath:_flatPackagePath toPath:[_extractionDirectory stringByAppendingPathComponent:_flatPackagePath.lastPathComponent] error:©Error]) {
|
||||
NSMutableDictionary *userInfoDictionary = [NSMutableDictionary dictionaryWithDictionary:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Flat package (%@) cannot be copied to extraction directory (%@)", _flatPackagePath, _extractionDirectory]}];
|
||||
|
||||
if (copyError != nil) {
|
||||
userInfoDictionary[NSUnderlyingErrorKey] = copyError;
|
||||
}
|
||||
|
||||
[notifier notifyFailureWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:userInfoDictionary]];
|
||||
} else {
|
||||
[notifier notifyProgress:1.0];
|
||||
[notifier notifySuccess];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], self.flatPackagePath]; }
|
||||
- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], _flatPackagePath]; }
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
@@ -16,11 +16,15 @@ The installer package is installed using macOS's built-in command line installer
|
||||
A guided installation can be started by applications other than the application being replaced. This is particularly useful where helper applications or agents are used.
|
||||
*/
|
||||
|
||||
#if SPARKLE_BUILD_PACKAGE_SUPPORT
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "SUInstallerProtocol.h"
|
||||
|
||||
@interface SUGuidedPackageInstaller : NSObject <SUInstallerProtocol>
|
||||
SPU_OBJC_DIRECT_MEMBERS @interface SUGuidedPackageInstaller : NSObject <SUInstallerProtocol>
|
||||
|
||||
- (instancetype)initWithPackagePath:(NSString *)packagePath homeDirectory:(NSString *)homeDirectory userName:(NSString *)userName;
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
@@ -6,6 +6,8 @@
|
||||
// Copyright 2010 Dragon Systems Software Limited. All rights reserved.
|
||||
//
|
||||
|
||||
#if SPARKLE_BUILD_PACKAGE_SUPPORT
|
||||
|
||||
#import <sys/stat.h>
|
||||
#import "SUGuidedPackageInstaller.h"
|
||||
#import "SUErrors.h"
|
||||
@@ -13,19 +15,12 @@
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
|
||||
@interface SUGuidedPackageInstaller ()
|
||||
|
||||
@property (nonatomic, readonly, copy) NSString *packagePath;
|
||||
@property (nonatomic, readonly, copy) NSString *homeDirectory;
|
||||
@property (nonatomic, readonly, copy) NSString *userName;
|
||||
|
||||
@end
|
||||
|
||||
@implementation SUGuidedPackageInstaller
|
||||
|
||||
@synthesize packagePath = _packagePath;
|
||||
@synthesize homeDirectory = _homeDirectory;
|
||||
@synthesize userName = _userName;
|
||||
{
|
||||
NSString *_packagePath;
|
||||
NSString *_homeDirectory;
|
||||
NSString *_userName;
|
||||
}
|
||||
|
||||
- (instancetype)initWithPackagePath:(NSString *)packagePath homeDirectory:(NSString *)homeDirectory userName:(NSString *)userName
|
||||
{
|
||||
@@ -50,36 +45,24 @@
|
||||
|
||||
NSTask *task = [[NSTask alloc] init];
|
||||
task.launchPath = installerPath;
|
||||
task.arguments = @[@"-pkg", self.packagePath, @"-target", @"/"];
|
||||
task.arguments = @[@"-pkg", _packagePath, @"-target", @"/"];
|
||||
// Set the $HOME and $USER variables so pre/post install scripts reference the correct user environment
|
||||
task.environment = @{@"HOME": self.homeDirectory, @"USER": self.userName};
|
||||
task.environment = @{@"HOME": _homeDirectory, @"USER": _userName};
|
||||
task.standardError = nil;
|
||||
task.standardOutput = nil;
|
||||
|
||||
if (@available(macOS 10.13, *)) {
|
||||
NSError *launchError = nil;
|
||||
if (![task launchAndReturnError:&launchError]) {
|
||||
if (error != NULL) {
|
||||
NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:@{ NSLocalizedDescriptionKey: @"Guided package installer failed to launch" }];
|
||||
|
||||
if (launchError != nil) {
|
||||
userInfo[NSUnderlyingErrorKey] = launchError;
|
||||
}
|
||||
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:userInfo];
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
} else {
|
||||
@try {
|
||||
[task launch];
|
||||
} @catch (NSException *) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: @"Guided package installer task threw an exception" }];
|
||||
NSError *launchError = nil;
|
||||
if (![task launchAndReturnError:&launchError]) {
|
||||
if (error != NULL) {
|
||||
NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:@{ NSLocalizedDescriptionKey: @"Guided package installer failed to launch" }];
|
||||
|
||||
if (launchError != nil) {
|
||||
userInfo[NSUnderlyingErrorKey] = launchError;
|
||||
}
|
||||
|
||||
return NO;
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:userInfo];
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
[task waitUntilExit];
|
||||
@@ -105,3 +88,5 @@
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
@@ -13,11 +13,15 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@class SUHost;
|
||||
|
||||
@interface SUInstaller : NSObject
|
||||
SPU_OBJC_DIRECT_MEMBERS @interface SUInstaller : NSObject
|
||||
|
||||
+ (nullable id<SUInstallerProtocol>)installerForHost:(SUHost *)host expectedInstallationType:(NSString *)expectedInstallationType updateDirectory:(NSString *)updateDirectory homeDirectory:(NSString *)homeDirectory userName:(NSString *)userName error:(NSError **)error;
|
||||
+ (nullable id<SUInstallerProtocol>)installerForHost:(SUHost *)host expectedInstallationType:(NSString *)expectedInstallationType updateDirectory:(NSString *)updateDirectory connectionCodeSigningValidationSkipped:(BOOL)connectionCodeSigningValidationSkipped homeDirectory:(NSString *)homeDirectory userName:(NSString *)userName error:(NSError **)error;
|
||||
|
||||
+ (nullable NSString *)installSourcePathInUpdateFolder:(NSString *)inUpdateFolder forHost:(SUHost *)host isPackage:(BOOL *)isPackagePtr isGuided:(nullable BOOL *)isGuidedPtr;
|
||||
+ (nullable NSString *)installSourcePathInUpdateFolder:(NSString *)inUpdateFolder forHost:(SUHost *)host
|
||||
#if SPARKLE_BUILD_PACKAGE_SUPPORT
|
||||
isPackage:(BOOL *)isPackagePtr isGuided:(nullable BOOL *)isGuidedPtr
|
||||
#endif
|
||||
;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
+144
-19
@@ -22,16 +22,10 @@
|
||||
|
||||
@implementation SUInstaller
|
||||
|
||||
+ (BOOL)isAliasFolderAtPath:(NSString *)path
|
||||
{
|
||||
NSNumber *aliasFlag = nil;
|
||||
[[NSURL fileURLWithPath:path] getResourceValue:&aliasFlag forKey:NSURLIsAliasFileKey error:nil];
|
||||
NSNumber *directoryFlag = nil;
|
||||
[[NSURL fileURLWithPath:path] getResourceValue:&directoryFlag forKey:NSURLIsDirectoryKey error:nil];
|
||||
return aliasFlag.boolValue && directoryFlag.boolValue;
|
||||
}
|
||||
|
||||
+ (nullable NSString *)installSourcePathInUpdateFolder:(NSString *)inUpdateFolder forHost:(SUHost *)host isPackage:(BOOL *)isPackagePtr isGuided:(BOOL *)isGuidedPtr
|
||||
+ (nullable NSString *)installSourcePathInUpdateFolder:(NSString *)inUpdateFolder forHost:(SUHost *)host
|
||||
#if SPARKLE_BUILD_PACKAGE_SUPPORT
|
||||
isPackage:(BOOL *)isPackagePtr isGuided:(BOOL *)isGuidedPtr
|
||||
#endif
|
||||
{
|
||||
NSParameterAssert(inUpdateFolder);
|
||||
NSParameterAssert(host);
|
||||
@@ -41,23 +35,59 @@
|
||||
*newAppDownloadPath = nil,
|
||||
*bundleFileName = [[host bundlePath] lastPathComponent],
|
||||
*alternateBundleFileName = [[host name] stringByAppendingPathExtension:[[host bundlePath] pathExtension]];
|
||||
#if SPARKLE_BUILD_PACKAGE_SUPPORT
|
||||
NSString *fallbackPackagePath = nil;
|
||||
|
||||
BOOL isPackage = NO;
|
||||
BOOL isGuided = YES;
|
||||
NSString *fallbackPackagePath = nil;
|
||||
#endif
|
||||
NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath:inUpdateFolder];
|
||||
NSString *bundleFileNameNoExtension = [bundleFileName stringByDeletingPathExtension];
|
||||
|
||||
while ((currentFile = [dirEnum nextObject])) {
|
||||
NSString *currentPath = [inUpdateFolder stringByAppendingPathComponent:currentFile];
|
||||
|
||||
// Ignore all symbolic links and aliases
|
||||
{
|
||||
NSURL *currentPathURL = [NSURL fileURLWithPath:currentPath];
|
||||
|
||||
NSNumber *symbolicLinkFlag = nil;
|
||||
[currentPathURL getResourceValue:&symbolicLinkFlag forKey:NSURLIsSymbolicLinkKey error:NULL];
|
||||
if (symbolicLinkFlag.boolValue) {
|
||||
// NSDirectoryEnumerator won't recurse into symlinked directories
|
||||
continue;
|
||||
}
|
||||
|
||||
NSNumber *aliasFlag = nil;
|
||||
[currentPathURL getResourceValue:&aliasFlag forKey:NSURLIsAliasFileKey error:NULL];
|
||||
|
||||
if (aliasFlag.boolValue) {
|
||||
NSNumber *directoryFlag = nil;
|
||||
[currentPathURL getResourceValue:&directoryFlag forKey:NSURLIsDirectoryKey error:NULL];
|
||||
|
||||
// Some DMGs have symlinks into /Applications! That's no good!
|
||||
if (directoryFlag.boolValue) {
|
||||
[dirEnum skipDescendents];
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
NSString *currentFilename = [currentFile lastPathComponent];
|
||||
#if SPARKLE_BUILD_PACKAGE_SUPPORT
|
||||
NSString *currentExtension = [currentFile pathExtension];
|
||||
NSString *currentFilenameNoExtension = [currentFilename stringByDeletingPathExtension];
|
||||
#endif
|
||||
if ([currentFilename isEqualToString:bundleFileName] ||
|
||||
[currentFilename isEqualToString:alternateBundleFileName]) // We found one!
|
||||
{
|
||||
#if SPARKLE_BUILD_PACKAGE_SUPPORT
|
||||
isPackage = NO;
|
||||
#endif
|
||||
newAppDownloadPath = currentPath;
|
||||
break;
|
||||
#if SPARKLE_BUILD_PACKAGE_SUPPORT
|
||||
} else if ([currentExtension isEqualToString:@"pkg"] ||
|
||||
[currentExtension isEqualToString:@"mpkg"]) {
|
||||
if ([currentFilenameNoExtension isEqualToString:bundleFileNameNoExtension]) {
|
||||
@@ -68,22 +98,22 @@
|
||||
// Remember any other non-matching packages we have seen should we need to use one of them as a fallback.
|
||||
fallbackPackagePath = currentPath;
|
||||
}
|
||||
#endif
|
||||
} else {
|
||||
// Try matching on bundle identifiers in case the user has changed the name of the host app
|
||||
NSBundle *incomingBundle = [NSBundle bundleWithPath:currentPath];
|
||||
NSString *hostBundleIdentifier = host.bundle.bundleIdentifier;
|
||||
if (incomingBundle && [incomingBundle.bundleIdentifier isEqualToString:hostBundleIdentifier]) {
|
||||
#if SPARKLE_BUILD_PACKAGE_SUPPORT
|
||||
isPackage = NO;
|
||||
#endif
|
||||
newAppDownloadPath = currentPath;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Some DMGs have symlinks into /Applications! That's no good!
|
||||
if ([self isAliasFolderAtPath:currentPath])
|
||||
[dirEnum skipDescendents];
|
||||
}
|
||||
|
||||
#if SPARKLE_BUILD_PACKAGE_SUPPORT
|
||||
// We don't have a valid path. Try to use the fallback package.
|
||||
|
||||
if (newAppDownloadPath == nil && fallbackPackagePath != nil) {
|
||||
@@ -105,18 +135,33 @@
|
||||
*isPackagePtr = isPackage;
|
||||
if (isGuidedPtr)
|
||||
*isGuidedPtr = isGuided;
|
||||
|
||||
#endif
|
||||
|
||||
if (!newAppDownloadPath) {
|
||||
SULog(SULogLevelError, @"Searched %@ for %@.(app|pkg)", inUpdateFolder, bundleFileNameNoExtension);
|
||||
SULog(SULogLevelError, @"Searched %@ for %@.(app%@)", inUpdateFolder, bundleFileNameNoExtension,
|
||||
#if SPARKLE_BUILD_PACKAGE_SUPPORT
|
||||
@"|pkg"
|
||||
#else
|
||||
@""
|
||||
#endif
|
||||
);
|
||||
}
|
||||
return newAppDownloadPath;
|
||||
}
|
||||
|
||||
+ (nullable id<SUInstallerProtocol>)installerForHost:(SUHost *)host expectedInstallationType:(NSString *)expectedInstallationType updateDirectory:(NSString *)updateDirectory homeDirectory:(NSString *)homeDirectory userName:(NSString *)userName error:(NSError * __autoreleasing *)error
|
||||
+ (nullable id<SUInstallerProtocol>)installerForHost:(SUHost *)host expectedInstallationType:(NSString *)expectedInstallationType updateDirectory:(NSString *)updateDirectory connectionCodeSigningValidationSkipped:(BOOL)connectionCodeSigningValidationSkipped homeDirectory:(NSString *)homeDirectory userName:(NSString *)userName error:(NSError * __autoreleasing *)error
|
||||
{
|
||||
#if SPARKLE_BUILD_PACKAGE_SUPPORT
|
||||
BOOL isPackage = NO;
|
||||
BOOL isGuided = NO;
|
||||
NSString *newDownloadPath = [self installSourcePathInUpdateFolder:updateDirectory forHost:host isPackage:&isPackage isGuided:&isGuided];
|
||||
#endif
|
||||
|
||||
NSString *newDownloadPath = [self installSourcePathInUpdateFolder:updateDirectory forHost:host
|
||||
#if SPARKLE_BUILD_PACKAGE_SUPPORT
|
||||
isPackage:&isPackage isGuided:&isGuided
|
||||
#endif
|
||||
];
|
||||
|
||||
if (newDownloadPath == nil) {
|
||||
if (error != NULL) {
|
||||
@@ -125,10 +170,88 @@
|
||||
return nil;
|
||||
}
|
||||
|
||||
#if SPARKLE_BUILD_PACKAGE_SUPPORT
|
||||
if (isPackage && connectionCodeSigningValidationSkipped) {
|
||||
// Package updates cannot update arbitrary bundles if code signing validation on the connection was skipped
|
||||
// (This means our helper is not code signed with an Apple issued certificate).
|
||||
// In this case, the main executable must be owned by root and the host must contain our installer tool
|
||||
|
||||
NSString *installerExecutablePath = NSBundle.mainBundle.executableURL.URLByResolvingSymlinksInPath.path;
|
||||
if (installerExecutablePath == nil) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingUpdateError userInfo:@{ NSLocalizedDescriptionKey: @"The "@SPARKLE_RELAUNCH_TOOL_NAME" executable path failed to be retrieved, which is an internal error that shouldn't happen. Please try to update using a production build of your app." }];
|
||||
}
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
NSString *hostBundlePath = host.bundle.bundleURL.URLByResolvingSymlinksInPath.path;
|
||||
if (hostBundlePath == nil) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingUpdateError userInfo:@{ NSLocalizedDescriptionKey: @"The host bundle path to update to be retrieved, which is an internal error that shouldn't happen. Please try to update using a production build of your app." }];
|
||||
}
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
NSError *attributesError = nil;
|
||||
NSDictionary<NSFileAttributeKey, id> *fileAttributes = [NSFileManager.defaultManager attributesOfItemAtPath:installerExecutablePath error:&attributesError];
|
||||
|
||||
if (fileAttributes == nil) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingUpdateError userInfo:@{ NSLocalizedDescriptionKey: @"File attributes failed to be retrieved from the "@SPARKLE_RELAUNCH_TOOL_NAME" executable, which is an internal error that shouldn't happen. Please try to update using a production build of your app." }];
|
||||
}
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
NSNumber *installerOwnerID = fileAttributes[NSFileOwnerAccountID];
|
||||
if (installerOwnerID == nil) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingUpdateError userInfo:@{ NSLocalizedDescriptionKey: @"File owner ID failed to be retrieved from the "@SPARKLE_RELAUNCH_TOOL_NAME" executable, which is an internal error that shouldn't happen. Please try to update using a production build of your app." }];
|
||||
}
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
// Check our helper is owned by root
|
||||
if (![installerOwnerID isEqual:@(0)]) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingUpdateError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Due to security, updating apps with package installers is disabled when '%@' is not signed with the same Team ID as your app, and "@SPARKLE_RELAUNCH_TOOL_NAME" is not owned by root (this specific case) or not residing in '%@'. Please either test an exported & production build of your app, or for development, code sign your app and Sparkle's embedded helpers with the same team: https://sparkle-project.org/documentation/sandboxing#code-signing", installerExecutablePath, hostBundlePath] }];
|
||||
}
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
NSArray<NSString *> *installerExecutablePathComponents = installerExecutablePath.pathComponents;
|
||||
NSArray<NSString *> *hostBundlePathComponents = hostBundlePath.pathComponents;
|
||||
|
||||
if (installerExecutablePathComponents.count <= hostBundlePathComponents.count) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingUpdateError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Due to security, updating apps with package installers is disabled when '%@' is not signed with the same Team ID as your app, and "@SPARKLE_RELAUNCH_TOOL_NAME" is not owned by root or not residing in '%@' (this specific case). Please either test an exported & production build of your app, or for development, code sign your app and Sparkle's embedded helpers with the same team: https://sparkle-project.org/documentation/sandboxing#code-signing", installerExecutablePath, hostBundlePath] }];
|
||||
}
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
// Check out helper resides inside the host app to be updated
|
||||
if (![[installerExecutablePathComponents subarrayWithRange:NSMakeRange(0, hostBundlePathComponents.count)] isEqualToArray:hostBundlePathComponents]) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingUpdateError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Due to security, updating apps with package installers is disabled when '%@' is not signed with the same Team ID as your app, and "@SPARKLE_RELAUNCH_TOOL_NAME" is not owned by root or not residing in '%@' (this specific case). Please either test an exported & production build of your app, or for development, code sign your app and Sparkle's embedded helpers with the same team: https://sparkle-project.org/documentation/sandboxing#code-signing", installerExecutablePath, hostBundlePath] }];
|
||||
}
|
||||
|
||||
return nil;
|
||||
}
|
||||
}
|
||||
#else
|
||||
(void)connectionCodeSigningValidationSkipped;
|
||||
#endif
|
||||
|
||||
// Make sure we find the type of installer that we were expecting to find
|
||||
// We shouldn't implicitly trust the installation type fed into here from the appcast because the installation type helps us determine
|
||||
// ahead of time whether or not this installer tool should be ran as root or not
|
||||
id <SUInstallerProtocol> installer = nil;
|
||||
#if SPARKLE_BUILD_PACKAGE_SUPPORT
|
||||
if (isPackage && isGuided) {
|
||||
if (![expectedInstallationType isEqualToString:SPUInstallationTypeGuidedPackage]) {
|
||||
if (error != NULL) {
|
||||
@@ -145,7 +268,9 @@
|
||||
} else {
|
||||
installer = [[SUPackageInstaller alloc] initWithPackagePath:newDownloadPath];
|
||||
}
|
||||
} else {
|
||||
} else
|
||||
#endif
|
||||
{
|
||||
if (![expectedInstallationType isEqualToString:SPUInstallationTypeApplication]) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Found regular application update but expected '%@=%@' from the appcast item enclosure instead", SUAppcastAttributeInstallationType, expectedInstallationType] }];
|
||||
|
||||
@@ -6,14 +6,18 @@
|
||||
// Copyright 2008 Andy Matuschak. All rights reserved.
|
||||
//
|
||||
|
||||
#if SPARKLE_BUILD_PACKAGE_SUPPORT
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "SUInstallerProtocol.h"
|
||||
|
||||
// This is the deprecated package installation type, aka the "interactive" package installer
|
||||
// For a more supported package installation, see SUGuidedPackageInstaller
|
||||
|
||||
@interface SUPackageInstaller : NSObject <SUInstallerProtocol>
|
||||
SPU_OBJC_DIRECT_MEMBERS @interface SUPackageInstaller : NSObject <SUInstallerProtocol>
|
||||
|
||||
- (instancetype)initWithPackagePath:(NSString *)packagePath;
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
@@ -6,6 +6,8 @@
|
||||
// Copyright 2008 Andy Matuschak. All rights reserved.
|
||||
//
|
||||
|
||||
#if SPARKLE_BUILD_PACKAGE_SUPPORT
|
||||
|
||||
#import "SUPackageInstaller.h"
|
||||
#import "SUConstants.h"
|
||||
#import "SUErrors.h"
|
||||
@@ -14,18 +16,13 @@
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
|
||||
@interface SUPackageInstaller ()
|
||||
|
||||
@property (nonatomic, readonly, copy) NSString *packagePath;
|
||||
|
||||
@end
|
||||
|
||||
@implementation SUPackageInstaller
|
||||
{
|
||||
NSString *_packagePath;
|
||||
}
|
||||
|
||||
static NSString *SUOpenUtilityPath = @"/usr/bin/open";
|
||||
|
||||
@synthesize packagePath = _packagePath;
|
||||
|
||||
- (instancetype)initWithPackagePath:(NSString *)packagePath
|
||||
{
|
||||
self = [super init];
|
||||
@@ -52,7 +49,7 @@ static NSString *SUOpenUtilityPath = @"/usr/bin/open";
|
||||
// -W = wait until the app has quit.
|
||||
// -n = Open another instance if already open.
|
||||
// -b = app bundle identifier
|
||||
NSArray *args = @[@"-W", @"-n", @"-b", @"com.apple.installer", self.packagePath];
|
||||
NSArray *args = @[@"-W", @"-n", @"-b", @"com.apple.installer", _packagePath];
|
||||
|
||||
// Known bug: if the installation fails or is canceled, Sparkle goes ahead and restarts, thinking everything is fine.
|
||||
@try {
|
||||
@@ -80,3 +77,5 @@ static NSString *SUOpenUtilityPath = @"/usr/bin/open";
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
@@ -14,9 +14,11 @@
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface SUPipedUnarchiver : NSObject <SUUnarchiverProtocol>
|
||||
SPU_OBJC_DIRECT_MEMBERS @interface SUPipedUnarchiver : NSObject <SUUnarchiverProtocol>
|
||||
|
||||
- (instancetype)initWithArchivePath:(NSString *)archivePath;
|
||||
- (instancetype)initWithArchivePath:(NSString *)archivePath extractionDirectory:(NSString *)extractionDirectory;
|
||||
|
||||
+ (BOOL)canUnarchivePath:(NSString *)path;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
+245
-100
@@ -14,25 +14,23 @@
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
|
||||
@interface SUPipedUnarchiver ()
|
||||
|
||||
@property (nonatomic, copy, readonly) NSString *archivePath;
|
||||
|
||||
@end
|
||||
|
||||
@implementation SUPipedUnarchiver
|
||||
{
|
||||
NSString *_archivePath;
|
||||
NSString *_extractionDirectory;
|
||||
}
|
||||
|
||||
@synthesize archivePath = _archivePath;
|
||||
|
||||
+ (nullable NSArray <NSString *> *)commandAndArgumentsConformingToTypeOfPath:(NSString *)path
|
||||
// pipingData == NO is only supported for zip archives
|
||||
static NSArray<NSString *> * _Nullable argumentsConformingToTypeOfPath(NSString *path, BOOL pipingData, NSString * __autoreleasing *outCommand)
|
||||
{
|
||||
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",@"-"],
|
||||
// Note: keep this list in sync with generate_appcast's unarchiveUpdates()
|
||||
NSMutableDictionary <NSString *, NSArray<NSString *> *> *extractCommandDictionary =
|
||||
[@{
|
||||
@".zip" : (pipingData ? @[@"/usr/bin/ditto", @"-x", @"-k", @"-"] : @[@"/usr/bin/ditto", @"-x", @"-k", path]),
|
||||
@".tar" : @[@"/usr/bin/tar", @"-xC"],
|
||||
@".tar.gz" : extractTGZ,
|
||||
@".tgz" : extractTGZ,
|
||||
@@ -40,14 +38,39 @@
|
||||
@".tbz" : extractTBZ,
|
||||
@".tar.xz" : extractTXZ,
|
||||
@".txz" : extractTXZ,
|
||||
@".tar.lzma" : extractTXZ
|
||||
};
|
||||
@".tar.lzma" : extractTXZ,
|
||||
} mutableCopy];
|
||||
|
||||
// At least the latest versions of 10.15 understand how to extract aar files
|
||||
// Versions before 10.15 do not understand extracting newly created aar files
|
||||
// Note encrypted aea files are supported in macOS 12 onwards, if we ever want to support those one day
|
||||
if (@available(macOS 10.15.7, *)) {
|
||||
NSString *appleArchiveCommand;
|
||||
if (@available(macOS 11, *)) {
|
||||
appleArchiveCommand = @"/usr/bin/aa";
|
||||
} else {
|
||||
// In 10.15 the utility was named yaa, which was later renamed to aar
|
||||
appleArchiveCommand = @"/usr/bin/yaa";
|
||||
}
|
||||
|
||||
NSArray <NSString *> *extractAppleArchive = @[appleArchiveCommand, @"extract", @"-d"];
|
||||
|
||||
[extractCommandDictionary addEntriesFromDictionary:@{
|
||||
@".aar" : extractAppleArchive,
|
||||
@".yaa" : extractAppleArchive,
|
||||
}];
|
||||
}
|
||||
|
||||
NSString *lastPathComponent = [path lastPathComponent];
|
||||
for (NSString *currentType in extractCommandDictionary)
|
||||
{
|
||||
if ([lastPathComponent hasSuffix:currentType]) {
|
||||
return [extractCommandDictionary objectForKey:currentType];
|
||||
NSArray<NSString *> *commandAndArguments = [extractCommandDictionary objectForKey:currentType];
|
||||
if (outCommand != NULL) {
|
||||
*outCommand = commandAndArguments.firstObject;
|
||||
}
|
||||
|
||||
return [commandAndArguments subarrayWithRange:NSMakeRange(1, commandAndArguments.count - 1)];
|
||||
}
|
||||
}
|
||||
return nil;
|
||||
@@ -55,7 +78,7 @@
|
||||
|
||||
+ (BOOL)canUnarchivePath:(NSString *)path
|
||||
{
|
||||
return ([self commandAndArgumentsConformingToTypeOfPath:path] != nil);
|
||||
return argumentsConformingToTypeOfPath(path, YES, NULL) != nil;
|
||||
}
|
||||
|
||||
+ (BOOL)mustValidateBeforeExtraction
|
||||
@@ -63,90 +86,177 @@
|
||||
return NO;
|
||||
}
|
||||
|
||||
- (instancetype)initWithArchivePath:(NSString *)archivePath
|
||||
- (instancetype)initWithArchivePath:(NSString *)archivePath extractionDirectory:(NSString *)extractionDirectory
|
||||
{
|
||||
self = [super init];
|
||||
if (self != nil) {
|
||||
_archivePath = [archivePath copy];
|
||||
_extractionDirectory = [extractionDirectory copy];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)unarchiveWithCompletionBlock:(void (^)(NSError * _Nullable))completionBlock progressBlock:(void (^ _Nullable)(double))progressBlock
|
||||
- (BOOL)needsVerifyBeforeExtractionKey
|
||||
{
|
||||
NSArray <NSString *> *commandAndArguments = [[self class] commandAndArgumentsConformingToTypeOfPath:self.archivePath];
|
||||
assert(commandAndArguments != nil);
|
||||
|
||||
NSString *command = commandAndArguments.firstObject;
|
||||
return ([_archivePath hasSuffix:@".aar"] || [_archivePath hasSuffix:@".yaa"]);
|
||||
}
|
||||
|
||||
- (void)unarchiveWithCompletionBlock:(void (^)(NSError * _Nullable))completionBlock progressBlock:(void (^ _Nullable)(double))progressBlock waitForCleanup:(BOOL)__unused waitForCleanup
|
||||
{
|
||||
NSString *command = nil;
|
||||
NSArray<NSString *> *arguments = argumentsConformingToTypeOfPath(_archivePath, YES, &command);
|
||||
assert(arguments != nil);
|
||||
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];
|
||||
@autoreleasepool {
|
||||
SUUnarchiverNotifier *notifier = [[SUUnarchiverNotifier alloc] initWithCompletionBlock:completionBlock progressBlock:progressBlock];
|
||||
NSError *extractError = nil;
|
||||
if ([self extractArchivePipingData:YES command:command arguments:arguments notifier:notifier error:&extractError]) {
|
||||
[notifier notifySuccess];
|
||||
} else {
|
||||
// If we fail due to an IO PIPE write failure for zip files,
|
||||
// we may re-attempt extracting the archive without piping archive data
|
||||
// (and without fine grained progress reporting).
|
||||
// This is to workaround a bug in ditto which causes extraction to fail when piping data for
|
||||
// some types of constructed zip files.
|
||||
// Note this bug is fixed on macOS 15+, so this workaround is not needed there.
|
||||
// https://github.com/sparkle-project/Sparkle/issues/2544
|
||||
BOOL useNonPipingWorkaround;
|
||||
if (@available(macOS 15, *)) {
|
||||
useNonPipingWorkaround = NO;
|
||||
} else {
|
||||
NSError *underlyingError = extractError.userInfo[NSUnderlyingErrorKey];
|
||||
|
||||
useNonPipingWorkaround = [self->_archivePath.pathExtension isEqualToString:@"zip"] && ([extractError.domain isEqualToString:SUSparkleErrorDomain] && extractError.code == SUUnarchivingError && [underlyingError.domain isEqualToString:NSPOSIXErrorDomain] && underlyingError.code == EPIPE);
|
||||
}
|
||||
|
||||
if (!useNonPipingWorkaround) {
|
||||
[notifier notifyFailureWithError:extractError];
|
||||
} else {
|
||||
// Re-create the extraction directory, then try extracting without piping
|
||||
|
||||
NSFileManager *fileManager = [NSFileManager defaultManager];
|
||||
|
||||
NSURL *extractionDirectoryURL = [NSURL fileURLWithPath:self->_extractionDirectory isDirectory:YES];
|
||||
|
||||
NSError *removeError = nil;
|
||||
if (![fileManager removeItemAtURL:extractionDirectoryURL error:&removeError]) {
|
||||
SULog(SULogLevelError, @"Failed to remove extraction directory path for non-piping workaround with error: %@", removeError);
|
||||
|
||||
[notifier notifyFailureWithError:extractError];
|
||||
} else {
|
||||
NSError *createError = nil;
|
||||
if (![fileManager createDirectoryAtPath:self->_extractionDirectory withIntermediateDirectories:NO attributes:nil error:&createError]) {
|
||||
SULog(SULogLevelError, @"Failed to create new extraction directory path for non-piping workaround with error: %@", createError);
|
||||
|
||||
[notifier notifyFailureWithError:extractError];
|
||||
} else {
|
||||
// The ditto command will be the same so no need to fetch it again
|
||||
NSArray<NSString *> *nonPipingArguments = argumentsConformingToTypeOfPath(self->_archivePath, NO, NULL);
|
||||
assert(nonPipingArguments != nil);
|
||||
|
||||
NSError *nonPipingExtractError = nil;
|
||||
if ([self extractArchivePipingData:NO command:command arguments:nonPipingArguments notifier:notifier error:&nonPipingExtractError]) {
|
||||
[notifier notifySuccess];
|
||||
} else {
|
||||
[notifier notifyFailureWithError:nonPipingExtractError];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// This method abstracts the types that use a command line tool piping data from stdin.
|
||||
- (void)extractArchivePipingDataToCommand:(NSString *)command arguments:(NSArray*)args notifier:(SUUnarchiverNotifier *)notifier
|
||||
- (BOOL)extractArchivePipingData:(BOOL)pipingData command:(NSString *)command arguments:(NSArray*)args notifier:(SUUnarchiverNotifier *)notifier error:(NSError * __autoreleasing *)outError SPU_OBJC_DIRECT
|
||||
{
|
||||
// *** GETS CALLED ON NON-MAIN THREAD!!!
|
||||
@autoreleasepool {
|
||||
NSString *destination = [self.archivePath stringByDeletingLastPathComponent];
|
||||
|
||||
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 = [(NSNumber *)[attributes objectForKey:NSFileSize] unsignedIntegerValue];
|
||||
NSString *destination = _extractionDirectory;
|
||||
|
||||
NSFileManager *fileManager = [NSFileManager defaultManager];
|
||||
|
||||
if (pipingData) {
|
||||
SULog(SULogLevelDefault, @"Extracting using '%@' '%@' < '%@' '%@'", command, [args componentsJoinedByString:@"' '"], _archivePath, destination);
|
||||
} else {
|
||||
SULog(SULogLevelDefault, @"Extracting using '%@' '%@' '%@'", command, [args componentsJoinedByString:@"' '"], destination);
|
||||
}
|
||||
|
||||
// Get expected file size for piping the archive
|
||||
NSUInteger expectedLength;
|
||||
if (pipingData) {
|
||||
NSDictionary *attributes = [fileManager attributesOfItemAtPath:_archivePath error:nil];
|
||||
expectedLength = [(NSNumber *)[attributes objectForKey:NSFileSize] unsignedIntegerValue];
|
||||
|
||||
if (expectedLength == 0) {
|
||||
NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Extraction failed, archive '%@' is empty", self.archivePath]}];
|
||||
NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Extraction failed, archive '%@' is empty", _archivePath]}];
|
||||
|
||||
[notifier notifyFailureWithError:error];
|
||||
return;
|
||||
if (outError != NULL) {
|
||||
*outError = error;
|
||||
}
|
||||
|
||||
return NO;
|
||||
}
|
||||
|
||||
NSFileHandle *archiveInput = [NSFileHandle fileHandleForReadingAtPath:self.archivePath];
|
||||
|
||||
NSPipe *pipe = [NSPipe pipe];
|
||||
NSTask *task = [[NSTask alloc] init];
|
||||
} else {
|
||||
expectedLength = 0;
|
||||
}
|
||||
|
||||
NSTask *task = [[NSTask alloc] init];
|
||||
|
||||
NSPipe *pipe;
|
||||
if (pipingData) {
|
||||
pipe = [NSPipe pipe];
|
||||
[task setStandardInput:pipe];
|
||||
[task setStandardError:[NSFileHandle fileHandleWithStandardError]];
|
||||
[task setStandardOutput:[NSFileHandle fileHandleWithStandardOutput]];
|
||||
[task setLaunchPath:command];
|
||||
[task setArguments:[args arrayByAddingObject:destination]];
|
||||
|
||||
NSError *launchError = nil;
|
||||
if (@available(macOS 10.13, *)) {
|
||||
if (![task launchAndReturnError:&launchError]) {
|
||||
[notifier notifyFailureWithError:launchError];
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
@try {
|
||||
[task launch];
|
||||
} @catch (NSException *e) {
|
||||
NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Extraction failed, -[NSTask launch] threw exception '%@'", e.description]}];
|
||||
[notifier notifyFailureWithError:error];
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
pipe = nil;
|
||||
}
|
||||
|
||||
[task setStandardError:[NSFileHandle fileHandleWithStandardError]];
|
||||
[task setStandardOutput:[NSFileHandle fileHandleWithStandardOutput]];
|
||||
[task setLaunchPath:command];
|
||||
[task setArguments:[args arrayByAddingObject:destination]];
|
||||
|
||||
NSError *launchError = nil;
|
||||
if (![task launchAndReturnError:&launchError]) {
|
||||
if (outError != NULL) {
|
||||
*outError = launchError;
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
NSError *underlyingOutError = nil;
|
||||
NSUInteger bytesWritten = 0;
|
||||
|
||||
if (pipingData) {
|
||||
NSFileHandle *archiveInput = [NSFileHandle fileHandleForReadingAtPath:_archivePath];
|
||||
|
||||
NSFileHandle *archiveOutput = [pipe fileHandleForWriting];
|
||||
NSUInteger bytesWritten = 0;
|
||||
|
||||
#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_15
|
||||
BOOL hasIOErrorMethods;
|
||||
if (@available(macOS 10.15, *)) {
|
||||
hasIOErrorMethods = YES;
|
||||
} else {
|
||||
hasIOErrorMethods = NO;
|
||||
}
|
||||
#endif
|
||||
|
||||
do {
|
||||
NSData *data;
|
||||
if (hasIOErrorMethods) {
|
||||
#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_15
|
||||
if (!hasIOErrorMethods) {
|
||||
@try {
|
||||
data = [archiveInput readDataOfLength:256*1024];
|
||||
} @catch (NSException *exception) {
|
||||
SULog(SULogLevelError, @"Failed to read data from archive with exception reason %@", exception.reason);
|
||||
data = nil;
|
||||
}
|
||||
}
|
||||
else
|
||||
#endif
|
||||
{
|
||||
NSError *readError = nil;
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wpartial-availability"
|
||||
@@ -154,13 +264,7 @@
|
||||
#pragma clang diagnostic pop
|
||||
if (data == nil) {
|
||||
SULog(SULogLevelError, @"Failed to read data from archive with error %@", readError);
|
||||
}
|
||||
} else {
|
||||
@try {
|
||||
data = [archiveInput readDataOfLength:256*1024];
|
||||
} @catch (NSException *exception) {
|
||||
SULog(SULogLevelError, @"Failed to read data from archive with exception reason %@", exception.reason);
|
||||
data = nil;
|
||||
underlyingOutError = readError;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -170,19 +274,35 @@
|
||||
}
|
||||
|
||||
NSError *writeError = nil;
|
||||
if (hasIOErrorMethods) {
|
||||
#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_15
|
||||
if (!hasIOErrorMethods) {
|
||||
@try {
|
||||
[archiveOutput writeData:data];
|
||||
} @catch (NSException *exception) {
|
||||
SULog(SULogLevelError, @"Failed to write data to pipe with exception reason %@", exception.reason);
|
||||
|
||||
if ([exception.name isEqualToString:NSFileHandleOperationException]) {
|
||||
NSError *underlyingFileHandleError = exception.userInfo[@"NSFileHandleOperationExceptionUnderlyingError"];
|
||||
NSError *underlyingPOSIXError = underlyingFileHandleError.userInfo[NSUnderlyingErrorKey];
|
||||
|
||||
underlyingOutError = underlyingPOSIXError;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
else
|
||||
#endif
|
||||
{
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wpartial-availability"
|
||||
if (![archiveOutput writeData:data error:&writeError]) {
|
||||
#pragma clang diagnostic pop
|
||||
SULog(SULogLevelError, @"Failed to write data to pipe with error %@", writeError);
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
@try {
|
||||
[archiveOutput writeData:data];
|
||||
} @catch (NSException *exception) {
|
||||
SULog(SULogLevelError, @"Failed to write data to pipe with exception reason %@", exception.reason);
|
||||
|
||||
NSError *underlyingPOSIXError = writeError.userInfo[NSUnderlyingErrorKey];
|
||||
|
||||
underlyingOutError = underlyingPOSIXError;
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -198,39 +318,64 @@
|
||||
if (![archiveOutput closeAndReturnError:&archiveOutputCloseError]) {
|
||||
SULog(SULogLevelError, @"Failed to close pipe with error %@", archiveOutputCloseError);
|
||||
}
|
||||
} else {
|
||||
}
|
||||
#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_15
|
||||
else
|
||||
{
|
||||
[archiveOutput closeFile];
|
||||
}
|
||||
#endif
|
||||
|
||||
if (@available(macOS 10.15, *)) {
|
||||
NSError *archiveInputCloseError = nil;
|
||||
if (![archiveInput closeAndReturnError:&archiveInputCloseError]) {
|
||||
SULog(SULogLevelError, @"Failed to close archive input with error %@", archiveInputCloseError);
|
||||
}
|
||||
} else {
|
||||
}
|
||||
#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_15
|
||||
else
|
||||
{
|
||||
[archiveInput closeFile];
|
||||
}
|
||||
|
||||
[task waitUntilExit];
|
||||
|
||||
if ([task terminationStatus] != 0) {
|
||||
NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Extraction failed, command '%@' returned %d", command, [task terminationStatus]]}];
|
||||
|
||||
[notifier notifyFailureWithError:error];
|
||||
return;
|
||||
}
|
||||
|
||||
if (bytesWritten != expectedLength) {
|
||||
NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Extraction failed, command '%@' got only %ld of %ld bytes", command, (long)bytesWritten, (long)expectedLength]}];
|
||||
|
||||
[notifier notifyFailureWithError:error];
|
||||
return;
|
||||
}
|
||||
|
||||
[notifier notifySuccess];
|
||||
#endif
|
||||
}
|
||||
|
||||
[task waitUntilExit];
|
||||
|
||||
if ([task terminationStatus] != 0) {
|
||||
NSMutableDictionary *userInfo = [@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Extraction failed, command '%@' returned %d", command, [task terminationStatus]]} mutableCopy];
|
||||
|
||||
if (underlyingOutError != nil) {
|
||||
userInfo[NSUnderlyingErrorKey] = underlyingOutError;
|
||||
}
|
||||
|
||||
NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:[userInfo copy]];
|
||||
|
||||
if (outError != NULL) {
|
||||
*outError = error;
|
||||
}
|
||||
|
||||
return NO;
|
||||
}
|
||||
|
||||
if (!pipingData) {
|
||||
[notifier notifyProgress:1.0];
|
||||
} else if (bytesWritten != expectedLength) {
|
||||
// Don't set underlying error in this case
|
||||
// This may fail due to a write PIPE error but we don't currently support extracting archives that have
|
||||
// extraneous data leftover because these may be corrupt.
|
||||
// We don't want to later workaround extraction by not piping the data.
|
||||
NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Extraction failed, command '%@' got only %ld of %ld bytes", command, (long)bytesWritten, (long)expectedLength]}];
|
||||
|
||||
if (outError != NULL) {
|
||||
*outError = error;
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], self.archivePath]; }
|
||||
- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], _archivePath]; }
|
||||
|
||||
@end
|
||||
@@ -12,7 +12,7 @@
|
||||
@class SUHost;
|
||||
@protocol SUVersionComparison;
|
||||
|
||||
@interface SUPlainInstaller : NSObject <SUInstallerProtocol>
|
||||
SPU_OBJC_DIRECT_MEMBERS @interface SUPlainInstaller : NSObject <SUInstallerProtocol>
|
||||
|
||||
/**
|
||||
@param host The current (old) bundle host
|
||||
|
||||
+203
-131
@@ -14,29 +14,23 @@
|
||||
#import "SUErrors.h"
|
||||
#import "SUVersionComparisonProtocol.h"
|
||||
#import "SUStandardVersionComparator.h"
|
||||
#import "SUCodeSigningVerifier.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) NSURL *temporaryOldDirectory;
|
||||
// We get an obj-c warning if we use 'newTemporaryDirectory' name about new + ownership stuff, so use 'temporaryNewDirectory' instead
|
||||
@property (nonatomic) NSURL *temporaryNewDirectory;
|
||||
|
||||
@end
|
||||
|
||||
@implementation SUPlainInstaller
|
||||
|
||||
@synthesize host = _host;
|
||||
@synthesize bundlePath = _bundlePath;
|
||||
@synthesize installationPath = _installationPath;
|
||||
@synthesize temporaryOldDirectory = _temporaryOldDirectory;
|
||||
@synthesize temporaryNewDirectory = _temporaryNewDirectory;
|
||||
{
|
||||
SUHost *_host;
|
||||
NSString *_bundlePath;
|
||||
NSString *_installationPath;
|
||||
NSURL *_temporaryOldDirectory;
|
||||
// We get an obj-c warning if we use 'newTemporaryDirectory' name about new + ownership stuff, so use 'temporaryNewDirectory' instead
|
||||
NSURL *_temporaryNewDirectory;
|
||||
|
||||
BOOL _newAndOldBundlesOnSameVolume;
|
||||
BOOL _canPerformSafeAtomicSwap;
|
||||
}
|
||||
|
||||
- (instancetype)initWithHost:(SUHost *)host bundlePath:(NSString *)bundlePath installationPath:(NSString *)installationPath
|
||||
{
|
||||
@@ -49,23 +43,89 @@
|
||||
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
|
||||
- (void)_performInitialInstallationWithFileManager:(SUFileManager *)fileManager oldBundleURL:(NSURL *)oldBundleURL newBundleURL:(NSURL *)newBundleURL performGatekeeperScan:(BOOL)performGatekeeperScan progressBlock:(nullable void(^)(double))progress SPU_OBJC_DIRECT
|
||||
{
|
||||
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]];
|
||||
// Release our new app from quarantine
|
||||
NSError *quarantineError = nil;
|
||||
if (![fileManager releaseItemFromQuarantineAtRootURL:newBundleURL error:&quarantineError]) {
|
||||
// Not big enough of a deal to fail the entire installation
|
||||
SULog(SULogLevelError, @"Failed to release quarantine at %@ with error %@", newBundleURL.path, quarantineError);
|
||||
}
|
||||
|
||||
return trimmedVersion.length > 0 ? trimmedVersion : nil;
|
||||
if (progress) {
|
||||
progress(5/11.0);
|
||||
}
|
||||
|
||||
// Try to preserve Finder Tags
|
||||
NSArray *resourceTags = nil;
|
||||
BOOL retrievedResourceTags = [oldBundleURL getResourceValue:&resourceTags forKey:NSURLTagNamesKey error:NULL];
|
||||
if (retrievedResourceTags && resourceTags.count > 0) {
|
||||
[newBundleURL setResourceValue:resourceTags forKey:NSURLTagNamesKey error:NULL];
|
||||
}
|
||||
|
||||
if (progress) {
|
||||
progress(6/11.0);
|
||||
}
|
||||
|
||||
// Update owner and group (if possible)
|
||||
NSError *changeOwnerAndGroupError = nil;
|
||||
if (![fileManager changeOwnerAndGroupOfItemAtRootURL:newBundleURL toMatchURL:oldBundleURL error:&changeOwnerAndGroupError]) {
|
||||
// Not a fatal error
|
||||
SULog(SULogLevelError, @"Failed to change owner and group of new app at %@ to match old app at %@", newBundleURL.path, oldBundleURL.path);
|
||||
SULog(SULogLevelError, @"Error: %@", changeOwnerAndGroupError);
|
||||
}
|
||||
|
||||
if (progress) {
|
||||
progress(7/11.0);
|
||||
}
|
||||
|
||||
// Register the new bundle with LaunchServices and the system
|
||||
NSError *touchError = nil;
|
||||
if (![fileManager updateModificationAndAccessTimeOfItemAtURL:newBundleURL error:&touchError]) {
|
||||
// Not a fatal error, but a pretty unfortunate one
|
||||
SULog(SULogLevelError, @"Failed to update modification and access time of new app at %@", newBundleURL.path);
|
||||
SULog(SULogLevelError, @"Error: %@", touchError);
|
||||
}
|
||||
|
||||
if (progress) {
|
||||
progress(8/11.0);
|
||||
}
|
||||
|
||||
if (performGatekeeperScan) {
|
||||
// Perform a Gatekeeper scan to pre-warm the app launch
|
||||
// This avoids users seeing a "Verifying..." dialog when the installed update is launched
|
||||
// Note the tool we use to perform the Gatekeeper scan (gktool) is technically available on macOS 14.0,
|
||||
// however there are some potential bugs/issues with performing a Gatekeeper scan on versions before 14.4:
|
||||
// https://github.com/sparkle-project/Sparkle/issues/2491
|
||||
if (@available(macOS 14.4, *)) {
|
||||
// Only perform Gatekeeper scan if we're updating an app bundle
|
||||
NSString *newBundlePath = newBundleURL.path;
|
||||
if ([newBundlePath.pathExtension caseInsensitiveCompare:@"app"] == NSOrderedSame) {
|
||||
NSURL *gktoolURL = [NSURL fileURLWithPath:@"/usr/bin/gktool" isDirectory:NO];
|
||||
if ([gktoolURL checkResourceIsReachableAndReturnError:NULL]) {
|
||||
NSTask *gatekeeperScanTask = [[NSTask alloc] init];
|
||||
gatekeeperScanTask.executableURL = gktoolURL;
|
||||
gatekeeperScanTask.arguments = @[@"scan", newBundlePath];
|
||||
|
||||
NSError *taskError;
|
||||
if (![gatekeeperScanTask launchAndReturnError:&taskError]) {
|
||||
// Not a fatal error
|
||||
SULog(SULogLevelError, @"Failed to perform GateKeeper scan on '%@' with error %@", newBundlePath, taskError);
|
||||
} else {
|
||||
[gatekeeperScanTask waitUntilExit];
|
||||
|
||||
if (gatekeeperScanTask.terminationStatus != 0) {
|
||||
SULog(SULogLevelError, @"gktool failed and returned exit status %d", gatekeeperScanTask.terminationStatus);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
- (BOOL)startInstallationToURL:(NSURL *)installationURL fromUpdateAtURL:(NSURL *)newURL withHost:(SUHost *)host progressBlock:(nullable void(^)(double))progress error:(NSError * __autoreleasing *)error
|
||||
|
||||
- (BOOL)startInstallationToURL:(NSURL *)installationURL fromUpdateAtURL:(NSURL *)newURL withHost:(SUHost *)host progressBlock:(nullable void(^)(double))progress error:(NSError * __autoreleasing *)error SPU_OBJC_DIRECT
|
||||
{
|
||||
if (installationURL == nil || newURL == nil) {
|
||||
// this really shouldn't happen but just in case
|
||||
@@ -77,7 +137,7 @@
|
||||
}
|
||||
|
||||
if (progress) {
|
||||
progress(1/10.0);
|
||||
progress(1/11.0);
|
||||
}
|
||||
|
||||
SUFileManager *fileManager = [[SUFileManager alloc] init];
|
||||
@@ -86,19 +146,21 @@
|
||||
// The system periodically cleans up files by looking at the mod & access times, so we have to make sure they're up to date
|
||||
// They could be potentially be preserved when archiving an application, but also an update could just be sitting on the system for a long time
|
||||
// before being installed
|
||||
NSError *accessTimeError = nil;
|
||||
if (![fileManager updateAccessTimeOfItemAtRootURL:newURL error:&accessTimeError]) {
|
||||
if (error != NULL) {
|
||||
NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:@{ NSLocalizedDescriptionKey: @"Failed to recursively update new application's modification time before moving into temporary directory" }];
|
||||
|
||||
if (accessTimeError != nil) {
|
||||
userInfo[NSUnderlyingErrorKey] = accessTimeError;
|
||||
if (!_newAndOldBundlesOnSameVolume) {
|
||||
NSError *accessTimeError = nil;
|
||||
if (![fileManager updateAccessTimeOfItemAtRootURL:newURL error:&accessTimeError]) {
|
||||
if (error != NULL) {
|
||||
NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:@{ NSLocalizedDescriptionKey: @"Failed to recursively update new application's modification time before moving into temporary directory" }];
|
||||
|
||||
if (accessTimeError != nil) {
|
||||
userInfo[NSUnderlyingErrorKey] = accessTimeError;
|
||||
}
|
||||
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:userInfo];
|
||||
}
|
||||
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:userInfo];
|
||||
return NO;
|
||||
}
|
||||
|
||||
return NO;
|
||||
}
|
||||
|
||||
NSURL *oldURL = [NSURL fileURLWithPath:host.bundlePath];
|
||||
@@ -112,105 +174,74 @@
|
||||
}
|
||||
|
||||
if (progress) {
|
||||
progress(2/10.0);
|
||||
progress(2/11.0);
|
||||
}
|
||||
|
||||
// Create a temporary directory for our new app that resides on our destination's volume
|
||||
// We use oldURL here instead of installationURL because in the case of normalization, installationURL may not exist
|
||||
// And we don't want to use either of the URL's parent directories because the parent directory could be on a different volume
|
||||
NSURL *tempNewDirectoryURL = [fileManager makeTemporaryDirectoryAppropriateForDirectoryURL:oldURL error:error];
|
||||
if (tempNewDirectoryURL == nil) {
|
||||
return NO;
|
||||
}
|
||||
|
||||
self.temporaryNewDirectory = tempNewDirectoryURL;
|
||||
|
||||
if (progress) {
|
||||
progress(3/10.0);
|
||||
}
|
||||
|
||||
// Move the new app to our temporary directory
|
||||
NSString *newURLLastPathComponent = newURL.lastPathComponent;
|
||||
NSURL *newTempURL = [tempNewDirectoryURL URLByAppendingPathComponent:newURLLastPathComponent];
|
||||
NSError *newTempMoveError = nil;
|
||||
if (![fileManager moveItemAtURL:newURL toURL:newTempURL error:&newTempMoveError]) {
|
||||
if (error != NULL) {
|
||||
NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to move the new app from %@ to its temp directory at %@", newURL.path, newTempURL.path] }];
|
||||
|
||||
if (newTempMoveError != nil) {
|
||||
userInfo[NSUnderlyingErrorKey] = newTempMoveError;
|
||||
}
|
||||
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:userInfo];
|
||||
NSURL *tempNewDirectoryURL;
|
||||
if (!_newAndOldBundlesOnSameVolume) {
|
||||
// Create a temporary directory for our new app that resides on our destination's volume
|
||||
// We use oldURL here instead of installationURL because in the case of normalization, installationURL may not exist
|
||||
// And we don't want to use either of the URL's parent directories because the parent directory could be on a different volume
|
||||
tempNewDirectoryURL = [fileManager makeTemporaryDirectoryAppropriateForDirectoryURL:oldURL error:error];
|
||||
if (tempNewDirectoryURL == nil) {
|
||||
return NO;
|
||||
}
|
||||
return NO;
|
||||
|
||||
_temporaryNewDirectory = tempNewDirectoryURL;
|
||||
} else {
|
||||
tempNewDirectoryURL = nil;
|
||||
}
|
||||
|
||||
if (progress) {
|
||||
progress(4/10.0);
|
||||
progress(3/11.0);
|
||||
}
|
||||
|
||||
// Release our new app from quarantine
|
||||
NSError *quarantineError = nil;
|
||||
if (![fileManager releaseItemFromQuarantineAtRootURL:newTempURL error:&quarantineError]) {
|
||||
// Not big enough of a deal to fail the entire installation
|
||||
SULog(SULogLevelError, @"Failed to release quarantine at %@ with error %@", newTempURL.path, quarantineError);
|
||||
// Move the new app to our temporary directory if needed
|
||||
NSURL *newFinalURL;
|
||||
if (!_newAndOldBundlesOnSameVolume) {
|
||||
NSString *newURLLastPathComponent = newURL.lastPathComponent;
|
||||
newFinalURL = [tempNewDirectoryURL URLByAppendingPathComponent:newURLLastPathComponent];
|
||||
NSError *newTempMoveError = nil;
|
||||
if (![fileManager moveItemAtURL:newURL toURL:newFinalURL error:&newTempMoveError]) {
|
||||
if (error != NULL) {
|
||||
NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to move the new app from %@ to its temp directory at %@", newURL.path, newFinalURL.path] }];
|
||||
|
||||
if (newTempMoveError != nil) {
|
||||
userInfo[NSUnderlyingErrorKey] = newTempMoveError;
|
||||
}
|
||||
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:userInfo];
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
} else {
|
||||
newFinalURL = newURL;
|
||||
}
|
||||
|
||||
if (progress) {
|
||||
progress(5/10.0);
|
||||
progress(4/11.0);
|
||||
}
|
||||
|
||||
// Try to preserve Finder Tags
|
||||
NSArray *resourceTags = nil;
|
||||
BOOL retrievedResourceTags = [oldURL getResourceValue:&resourceTags forKey:NSURLTagNamesKey error:NULL];
|
||||
if (retrievedResourceTags && resourceTags.count > 0) {
|
||||
[newTempURL setResourceValue:resourceTags forKey:NSURLTagNamesKey error:NULL];
|
||||
}
|
||||
|
||||
if (progress) {
|
||||
progress(6/10.0);
|
||||
}
|
||||
|
||||
// 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 *changeOwnerAndGroupError = nil;
|
||||
if (![fileManager changeOwnerAndGroupOfItemAtRootURL:newTempURL toMatchURL:oldURL error:&changeOwnerAndGroupError]) {
|
||||
// Not a fatal error
|
||||
SULog(SULogLevelError, @"Failed to change owner and group of new app at %@ to match old app at %@", newTempURL.path, oldURL.path);
|
||||
SULog(SULogLevelError, @"Error: %@", changeOwnerAndGroupError);
|
||||
if (!_newAndOldBundlesOnSameVolume) {
|
||||
// If we're updating a bundle on another volume, the install process can be pretty slow.
|
||||
// In this case let's get out of the way and skip the Gatekeeper scan
|
||||
[self _performInitialInstallationWithFileManager:fileManager oldBundleURL:oldURL newBundleURL:newFinalURL performGatekeeperScan:NO progressBlock:progress];
|
||||
}
|
||||
|
||||
if (progress) {
|
||||
progress(7/10.0);
|
||||
}
|
||||
|
||||
NSError *touchError = nil;
|
||||
if (![fileManager updateModificationAndAccessTimeOfItemAtURL:newTempURL error:&touchError]) {
|
||||
// Not a fatal error, but a pretty unfortunate one
|
||||
SULog(SULogLevelError, @"Failed to update modification and access time of new app at %@", newTempURL.path);
|
||||
SULog(SULogLevelError, @"Error: %@", touchError);
|
||||
}
|
||||
|
||||
if (progress) {
|
||||
progress(8/10.0);
|
||||
progress(9/11.0);
|
||||
}
|
||||
|
||||
// First try swapping the application atomically
|
||||
NSError *swapError = nil;
|
||||
BOOL swappedApp;
|
||||
if (@available(macOS 10.13, *)) {
|
||||
// If the app is normalized and the installation path differs, go through the old swap path
|
||||
if (SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME && ![oldURL.path isEqual:installationURL.path]) {
|
||||
swappedApp = NO;
|
||||
} else {
|
||||
// We will be cleaning up the temporary directory later in -performCleanup:
|
||||
// We don't want to clean it up now because it can take some time
|
||||
swappedApp = [fileManager swapItemAtURL:installationURL withItemAtURL:newTempURL error:&swapError];
|
||||
}
|
||||
} else {
|
||||
// If we can not safely perform an atomic swap, or if the app is normalized and the installation path differs, go through the old swap path
|
||||
if (!_canPerformSafeAtomicSwap || (SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME && ![oldURL.path isEqual:installationURL.path])) {
|
||||
swappedApp = NO;
|
||||
} else {
|
||||
// We will be cleaning up the temporary directory later in -performCleanup:
|
||||
// We don't want to clean it up now because it can take some time
|
||||
swappedApp = [fileManager swapItemAtURL:installationURL withItemAtURL:newFinalURL error:&swapError];
|
||||
}
|
||||
|
||||
if (!swappedApp) {
|
||||
@@ -226,10 +257,10 @@
|
||||
return NO;
|
||||
}
|
||||
|
||||
self.temporaryOldDirectory = tempOldDirectoryURL;
|
||||
_temporaryOldDirectory = tempOldDirectoryURL;
|
||||
|
||||
if (progress) {
|
||||
progress(9/10.0);
|
||||
progress(10/11.0);
|
||||
}
|
||||
|
||||
NSString *oldURLFilename = oldURL.lastPathComponent;
|
||||
@@ -259,14 +290,14 @@
|
||||
}
|
||||
|
||||
if (progress) {
|
||||
progress(9.5/10.0);
|
||||
progress(10.5/11.0);
|
||||
}
|
||||
|
||||
// Move the new app to its final destination
|
||||
NSError *installMoveError = nil;
|
||||
if (![fileManager moveItemAtURL:newTempURL toURL:installationURL error:&installMoveError]) {
|
||||
if (![fileManager moveItemAtURL:newFinalURL toURL:installationURL error:&installMoveError]) {
|
||||
if (error != NULL) {
|
||||
NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to move new app at %@ to final destination %@", newTempURL.path, installationURL.path] }];
|
||||
NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to move new app at %@ to final destination %@", newFinalURL.path, installationURL.path] }];
|
||||
|
||||
if (installMoveError != nil) {
|
||||
userInfo[NSUnderlyingErrorKey] = installMoveError;
|
||||
@@ -283,7 +314,7 @@
|
||||
}
|
||||
|
||||
if (progress) {
|
||||
progress(10/10.0);
|
||||
progress(11/11.0);
|
||||
}
|
||||
|
||||
return YES;
|
||||
@@ -293,9 +324,9 @@
|
||||
{
|
||||
// Prevent malicious downgrades
|
||||
// Note that we may not be able to do this for package installations, hence this code being done here
|
||||
NSString *hostVersion = [self.host version];
|
||||
NSString *hostVersion = [_host version];
|
||||
|
||||
NSBundle *bundle = [NSBundle bundleWithPath:self.bundlePath];
|
||||
NSBundle *bundle = [NSBundle bundleWithPath:_bundlePath];
|
||||
SUHost *updateHost = [[SUHost alloc] initWithBundle:bundle];
|
||||
NSString *updateVersion = [updateHost objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleVersionKey];
|
||||
|
||||
@@ -311,6 +342,47 @@
|
||||
return NO;
|
||||
}
|
||||
|
||||
SUFileManager *fileManager = [[SUFileManager alloc] init];
|
||||
|
||||
BOOL updateHasCustomUpdateSecurityPolicy = NO;
|
||||
if (@available(macOS 13.0, *)) {
|
||||
// If the new update is notarized / developer ID code signed and Autoupdate is not signed with the same Team ID as the new update,
|
||||
// then we may run into Privacy & Security prompt issues from the OS
|
||||
// which think we are modifying the update (but we're not)
|
||||
// To avoid these, we skip the gatekeeper scan and skip performing an atomic swap during install
|
||||
// If the update has a custom update security policy, the same team ID policy may not apply,
|
||||
// so in that case we will also skip performing an atomic swap
|
||||
|
||||
updateHasCustomUpdateSecurityPolicy = updateHost.hasUpdateSecurityPolicy;
|
||||
if (updateHasCustomUpdateSecurityPolicy) {
|
||||
// We don't handle working around a custom update security policy
|
||||
_canPerformSafeAtomicSwap = NO;
|
||||
} else {
|
||||
NSString *installerTeamIdentifier = [SUCodeSigningVerifier teamIdentifierFromMainExecutable];
|
||||
NSString *bundleTeamIdentifier = [SUCodeSigningVerifier teamIdentifierAtURL:bundle.bundleURL];
|
||||
|
||||
// If bundleTeamIdentifier is nil, then the update isn't code signed so atomic swap is okay
|
||||
_canPerformSafeAtomicSwap = (bundleTeamIdentifier == nil || (installerTeamIdentifier != nil && [installerTeamIdentifier isEqualToString:bundleTeamIdentifier]));
|
||||
}
|
||||
} else {
|
||||
_canPerformSafeAtomicSwap = YES;
|
||||
}
|
||||
|
||||
if (!_canPerformSafeAtomicSwap) {
|
||||
if (updateHasCustomUpdateSecurityPolicy) {
|
||||
SULog(SULogLevelDefault, @"Skipping atomic rename/swap and gatekeeper scan because new update %@ has a custom NSUpdateSecurityPolicy", bundle.bundleURL.lastPathComponent);
|
||||
} else {
|
||||
SULog(SULogLevelDefault, @"Skipping atomic rename/swap and gatekeeper scan because Autoupdate is not signed with same identity as the new update %@", bundle.bundleURL.lastPathComponent);
|
||||
}
|
||||
}
|
||||
|
||||
_newAndOldBundlesOnSameVolume = [fileManager itemAtURL:bundle.bundleURL isOnSameVolumeItemAsURL:_host.bundle.bundleURL];
|
||||
|
||||
// We can do a lot of the installation work ahead of time if the new app update does not need to be copied to another volume
|
||||
if (_newAndOldBundlesOnSameVolume) {
|
||||
[self _performInitialInstallationWithFileManager:fileManager oldBundleURL:_host.bundle.bundleURL newBundleURL:bundle.bundleURL performGatekeeperScan:_canPerformSafeAtomicSwap progressBlock:NULL];
|
||||
}
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
@@ -318,19 +390,19 @@
|
||||
{
|
||||
// Note: we must do most installation work in the third stage due to relying on our application sitting in temporary directories.
|
||||
// It must not be possible for our update to sit in temporary directories for a very long time.
|
||||
return [self startInstallationToURL:[NSURL fileURLWithPath:self.installationPath] fromUpdateAtURL:[NSURL fileURLWithPath:self.bundlePath] withHost:self.host progressBlock:cb error:error];
|
||||
return [self startInstallationToURL:[NSURL fileURLWithPath:_installationPath] fromUpdateAtURL:[NSURL fileURLWithPath:_bundlePath] withHost:_host progressBlock:cb error:error];
|
||||
}
|
||||
|
||||
- (void)performCleanup
|
||||
{
|
||||
SUFileManager *fileManager = [[SUFileManager alloc] init];
|
||||
|
||||
if (self.temporaryNewDirectory != nil) {
|
||||
[fileManager removeItemAtURL:self.temporaryNewDirectory error:NULL];
|
||||
if (_temporaryNewDirectory != nil) {
|
||||
[fileManager removeItemAtURL:_temporaryNewDirectory error:NULL];
|
||||
}
|
||||
|
||||
if (self.temporaryOldDirectory != nil) {
|
||||
[fileManager removeItemAtURL:self.temporaryOldDirectory error:NULL];
|
||||
if (_temporaryOldDirectory != nil) {
|
||||
[fileManager removeItemAtURL:_temporaryOldDirectory error:NULL];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -18,15 +18,22 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
@class SUSignatures;
|
||||
@class SUPublicKeys;
|
||||
@class SPUVerifierInformation;
|
||||
|
||||
@interface SUSignatureVerifier : NSObject
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
+ (BOOL)validatePath:(NSString *)path withSignatures:(SUSignatures *)signatures withPublicKeys:(SUPublicKeys *)pkeys error:(NSError * __autoreleasing *)error;
|
||||
SPU_OBJC_DIRECT_MEMBERS @interface SUSignatureVerifier : NSObject
|
||||
|
||||
+ (BOOL)validatePath:(NSString *)path withSignatures:(SUSignatures *)signatures withPublicKeys:(SUPublicKeys *)pkeys verifierInformation:(SPUVerifierInformation * _Nullable)verifierInformation error:(NSError * __autoreleasing *)error;
|
||||
|
||||
- (instancetype)init NS_UNAVAILABLE;
|
||||
|
||||
- (instancetype)initWithPublicKeys:(SUPublicKeys *)pkeys;
|
||||
|
||||
- (BOOL)verifyFileAtPath:(NSString *)path signatures:(SUSignatures *)signatures error:(NSError * __autoreleasing *)error;
|
||||
- (BOOL)verifyFileAtPath:(NSString *)path signatures:(SUSignatures *)signatures verifierInformation:(SPUVerifierInformation * _Nullable)verifierInformation error:(NSError * __autoreleasing *)error;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
#endif
|
||||
@@ -16,22 +16,22 @@
|
||||
#import "SULog.h"
|
||||
#import "SUSignatures.h"
|
||||
#import "SUErrors.h"
|
||||
#import "SPUVerifierInformation.h"
|
||||
#import "SUConstants.h"
|
||||
#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT
|
||||
#include <CommonCrypto/CommonDigest.h>
|
||||
#import "ed25519.h" // Run `git submodule update --init` if you get an error here
|
||||
#endif
|
||||
#import "ed25519.h"
|
||||
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
|
||||
@interface SUSignatureVerifier ()
|
||||
@property (readonly) SUPublicKeys *pubKeys;
|
||||
@end
|
||||
|
||||
@implementation SUSignatureVerifier {
|
||||
@implementation SUSignatureVerifier
|
||||
{
|
||||
SUPublicKeys *_pubKeys;
|
||||
}
|
||||
|
||||
@synthesize pubKeys = _pubKeys;
|
||||
|
||||
+ (BOOL)validatePath:(NSString *)path withSignatures:(SUSignatures *)signatures withPublicKeys:(SUPublicKeys *)pkeys error:(NSError * __autoreleasing *)error
|
||||
+ (BOOL)validatePath:(NSString *)path withSignatures:(SUSignatures *)signatures withPublicKeys:(SUPublicKeys *)pkeys verifierInformation:(SPUVerifierInformation * _Nullable)verifierInformation error:(NSError * __autoreleasing *)error
|
||||
{
|
||||
SUSignatureVerifier *verifier = [(SUSignatureVerifier *)[self alloc] initWithPublicKeys:pkeys];
|
||||
|
||||
@@ -42,7 +42,7 @@
|
||||
return NO;
|
||||
}
|
||||
|
||||
return [verifier verifyFileAtPath:path signatures:signatures error:error];
|
||||
return [verifier verifyFileAtPath:path signatures:signatures verifierInformation:verifierInformation error:error];
|
||||
}
|
||||
|
||||
- (instancetype)initWithPublicKeys:(SUPublicKeys *)pubkeys
|
||||
@@ -54,9 +54,10 @@
|
||||
return self;
|
||||
}
|
||||
|
||||
- (SecKeyRef)dsaSecKeyRef {
|
||||
|
||||
NSData *data = [self.pubKeys.dsaPubKey dataUsingEncoding:NSASCIIStringEncoding];
|
||||
#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT
|
||||
- (SecKeyRef)dsaSecKeyRef SPU_OBJC_DIRECT
|
||||
{
|
||||
NSData *data = [_pubKeys.dsaPubKey dataUsingEncoding:NSASCIIStringEncoding];
|
||||
if (!self || !data.length) {
|
||||
SULog(SULogLevelError, @"Could not read public DSA key");
|
||||
return nil;
|
||||
@@ -89,8 +90,9 @@
|
||||
CFRelease(items);
|
||||
return dsaPubKeySecKey;
|
||||
}
|
||||
#endif
|
||||
|
||||
- (BOOL)verifyFileAtPath:(NSString *)path signatures:(SUSignatures *)signatures error:(NSError * __autoreleasing *)error
|
||||
- (BOOL)verifyFileAtPath:(NSString *)path signatures:(SUSignatures *)signatures verifierInformation:(SPUVerifierInformation * _Nullable)verifierInformation error:(NSError * __autoreleasing *)error
|
||||
{
|
||||
if (!path || !path.length) {
|
||||
if (error != NULL) {
|
||||
@@ -106,7 +108,7 @@
|
||||
return NO;
|
||||
}
|
||||
|
||||
switch (self.pubKeys.ed25519PubKeyStatus) {
|
||||
switch (_pubKeys.ed25519PubKeyStatus) {
|
||||
case SUSigningInputStatusAbsent:
|
||||
if (signatures.ed25519SignatureStatus != SUSigningInputStatusAbsent) {
|
||||
SULog(SULogLevelDefault, @"The update has an EdDSA signature, but it won't be used, because the old app doesn't have an EdDSA public key");
|
||||
@@ -165,21 +167,48 @@
|
||||
|
||||
return NO;
|
||||
}
|
||||
if (ed25519_verify(signatures.ed25519Signature, data.bytes, data.length, self.pubKeys.ed25519PubKey)) {
|
||||
if (ed25519_verify(signatures.ed25519Signature, data.bytes, data.length, _pubKeys.ed25519PubKey)) {
|
||||
SULog(SULogLevelDefault, @"OK: EdDSA signature is correct");
|
||||
#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT
|
||||
// No need to check DSA when EdDSA verification succeeded, unless a DSA signature is provided and it's
|
||||
// erroneously invalid
|
||||
if (signatures.dsaSignatureStatus != SUSigningInputStatusInvalid) {
|
||||
if (signatures.dsaSignatureStatus != SUSigningInputStatusInvalid)
|
||||
#endif
|
||||
{
|
||||
return YES;
|
||||
}
|
||||
} else {
|
||||
NSString *message = @"EdDSA 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.";
|
||||
NSMutableString *message = [NSMutableString stringWithString:@"EdDSA 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, @"%@", message);
|
||||
// Elaborate on the error message if we have more information about the download archive
|
||||
if (verifierInformation != nil) {
|
||||
BOOL reportedDiscrepancy = NO;
|
||||
|
||||
if (verifierInformation.expectedContentLength > 0 && verifierInformation.actualContentLength > 0) {
|
||||
if (verifierInformation.expectedContentLength != verifierInformation.actualContentLength) {
|
||||
[message appendFormat:@" The downloaded update (%@) is likely different than the signed archive because the expected content length from the appcast item (%llu bytes) differs from the downloaded archive length (%llu bytes).", path.lastPathComponent, verifierInformation.expectedContentLength, verifierInformation.actualContentLength];
|
||||
reportedDiscrepancy = YES;
|
||||
}
|
||||
}
|
||||
|
||||
NSString *actualVersion = verifierInformation.actualVersion;
|
||||
if (actualVersion != nil && ![verifierInformation.expectedVersion isEqualToString:actualVersion]) {
|
||||
[message appendFormat:@" The downloaded update (%@) also has a CFBundleVersion (%@) which differs from the %@ in the appcast item (%@).", path.lastPathComponent, actualVersion, SUAppcastAttributeVersion, verifierInformation.expectedVersion];
|
||||
reportedDiscrepancy = YES;
|
||||
}
|
||||
|
||||
if (!reportedDiscrepancy && verifierInformation.expectedContentLength > 0) {
|
||||
[message appendFormat:@" The downloaded update (%@) is likely not signed correctly because the archive has the expected content length (%llu bytes)%@ which matches the appcast item.", path.lastPathComponent, verifierInformation.actualContentLength, (actualVersion == nil ? @"" : [NSString stringWithFormat:@" and CFBundleVersion (%@)", actualVersion])];
|
||||
}
|
||||
}
|
||||
|
||||
SULog(SULogLevelError, @"%@", [message copy]);
|
||||
|
||||
#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT
|
||||
if (signatures.dsaSignatureStatus != SUSigningInputStatusAbsent) {
|
||||
SULog(SULogLevelDefault, @"DSA signature won't be checked, because EdDSA verification has already failed");
|
||||
}
|
||||
#endif
|
||||
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:@{ NSLocalizedDescriptionKey: message }];
|
||||
@@ -192,7 +221,8 @@
|
||||
break;
|
||||
}
|
||||
|
||||
switch (self.pubKeys.dsaPubKeyStatus) {
|
||||
#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT
|
||||
switch (_pubKeys.dsaPubKeyStatus) {
|
||||
case SUSigningInputStatusAbsent:
|
||||
if (signatures.dsaSignatureStatus != SUSigningInputStatusAbsent) {
|
||||
SULog(SULogLevelDefault, @"The update has a DSA signature, but it can't be used, because the old app doesn't have a DSA public key");
|
||||
@@ -235,6 +265,21 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
#else
|
||||
switch (_pubKeys.dsaPubKeyStatus) {
|
||||
case SUSigningInputStatusAbsent:
|
||||
break;
|
||||
case SUSigningInputStatusInvalid:
|
||||
// We don't keep track of DSA signatures, so we will ignore this mistake and treat it as if it were absent
|
||||
break;
|
||||
case SUSigningInputStatusPresent:
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:@{ NSLocalizedDescriptionKey: @"The old app has a DSA public key but DSA support is disabled, and the old app does not have an EdDSA public key." }];
|
||||
}
|
||||
|
||||
return NO;
|
||||
}
|
||||
#endif
|
||||
|
||||
if (error != NULL) {
|
||||
// Use generic failure
|
||||
@@ -244,7 +289,8 @@
|
||||
return NO;
|
||||
}
|
||||
|
||||
- (BOOL)verifyDSASignatureOfStream:(NSInputStream *)stream dsaSignature:(NSData *)dsaSignature error:(NSError * __autoreleasing *)outError
|
||||
#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT
|
||||
- (BOOL)verifyDSASignatureOfStream:(NSInputStream *)stream dsaSignature:(NSData *)dsaSignature error:(NSError * __autoreleasing *)outError SPU_OBJC_DIRECT
|
||||
{
|
||||
if (!stream || !dsaSignature) {
|
||||
SULog(SULogLevelError, @"Invalid arguments to verifyStream");
|
||||
@@ -301,10 +347,7 @@
|
||||
return cleanup();
|
||||
}
|
||||
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wdirect-ivar-access"
|
||||
dataVerifyTransform = SecVerifyTransformCreate(dsaPubKeySecKey, (__bridge CFDataRef)dsaSignature, &error);
|
||||
#pragma clang diagnostic pop
|
||||
if (!dataVerifyTransform) {
|
||||
SULog(SULogLevelError, @"Could not understand format of the signature: %@; Signature data: %@", error, dsaSignature);
|
||||
if (outError != NULL) {
|
||||
@@ -368,5 +411,6 @@
|
||||
cleanup();
|
||||
return result.boolValue;
|
||||
}
|
||||
#endif
|
||||
|
||||
@end
|
||||
@@ -12,9 +12,9 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@protocol SUUnarchiverProtocol;
|
||||
|
||||
@interface SUUnarchiver : NSObject
|
||||
SPU_OBJC_DIRECT_MEMBERS @interface SUUnarchiver : NSObject
|
||||
|
||||
+ (nullable id <SUUnarchiverProtocol>)unarchiverForPath:(NSString *)path updatingHostBundlePath:(nullable NSString *)hostPath decryptionPassword:(nullable NSString *)decryptionPassword expectingInstallationType:(NSString *)installationType;
|
||||
+ (nullable id <SUUnarchiverProtocol>)unarchiverForPath:(NSString *)path extractionDirectory:(NSString *)extractionDirectory updatingHostBundlePath:(nullable NSString *)hostPath decryptionPassword:(nullable NSString *)decryptionPassword expectingInstallationType:(NSString *)installationType;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
+14
-11
@@ -18,22 +18,25 @@
|
||||
|
||||
@implementation SUUnarchiver
|
||||
|
||||
+ (nullable id <SUUnarchiverProtocol>)unarchiverForPath:(NSString *)path updatingHostBundlePath:(nullable NSString *)hostPath decryptionPassword:(nullable NSString *)decryptionPassword expectingInstallationType:(NSString *)installationType
|
||||
+ (nullable id <SUUnarchiverProtocol>)unarchiverForPath:(NSString *)path extractionDirectory:(NSString *)extractionDirectory updatingHostBundlePath:(nullable NSString *)hostPath decryptionPassword:(nullable NSString *)decryptionPassword expectingInstallationType:(NSString *)installationType
|
||||
{
|
||||
if ([SUPipedUnarchiver canUnarchivePath:path]) {
|
||||
return [[SUPipedUnarchiver alloc] initWithArchivePath:path];
|
||||
|
||||
} else if ([SUDiskImageUnarchiver canUnarchivePath:path]) {
|
||||
return [[SUDiskImageUnarchiver alloc] initWithArchivePath:path decryptionPassword:decryptionPassword];
|
||||
|
||||
} else if ([SUBinaryDeltaUnarchiver canUnarchivePath:path]) {
|
||||
return [[SUPipedUnarchiver alloc] initWithArchivePath:path extractionDirectory:extractionDirectory];
|
||||
}
|
||||
else if ([SUDiskImageUnarchiver canUnarchivePath:path]) {
|
||||
return [[SUDiskImageUnarchiver alloc] initWithArchivePath:path extractionDirectory:extractionDirectory decryptionPassword:decryptionPassword];
|
||||
}
|
||||
else if ([SUBinaryDeltaUnarchiver canUnarchivePath:path]) {
|
||||
assert(hostPath != nil);
|
||||
NSString *nonNullHostPath = hostPath;
|
||||
return [[SUBinaryDeltaUnarchiver alloc] initWithArchivePath:path updateHostBundlePath:nonNullHostPath];
|
||||
} else if ([SUFlatPackageUnarchiver canUnarchivePath:path]) {
|
||||
// Flat packages are only supported for guided packaage installs
|
||||
return [[SUFlatPackageUnarchiver alloc] initWithFlatPackagePath:path expectingInstallationType:installationType];
|
||||
return [[SUBinaryDeltaUnarchiver alloc] initWithArchivePath:path extractionDirectory:extractionDirectory updateHostBundlePath:nonNullHostPath];
|
||||
}
|
||||
#if SPARKLE_BUILD_PACKAGE_SUPPORT
|
||||
else if ([SUFlatPackageUnarchiver canUnarchivePath:path]) {
|
||||
// Flat packages are only supported for guided packaage installs
|
||||
return [[SUFlatPackageUnarchiver alloc] initWithFlatPackagePath:path extractionDirectory:extractionDirectory expectingInstallationType:installationType];
|
||||
}
|
||||
#endif
|
||||
return nil;
|
||||
}
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface SUUnarchiverNotifier : NSObject
|
||||
SPU_OBJC_DIRECT_MEMBERS @interface SUUnarchiverNotifier : NSObject
|
||||
|
||||
- (instancetype)initWithCompletionBlock:(void (^)(NSError * _Nullable))completionBlock progressBlock:(void (^ _Nullable)(double))progressBlock;
|
||||
|
||||
|
||||
@@ -13,17 +13,11 @@
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
|
||||
@interface SUUnarchiverNotifier ()
|
||||
|
||||
@property (nonatomic, readonly, copy) void (^completionBlock)(NSError * _Nullable);
|
||||
@property (nonatomic, readonly, copy) void (^ _Nullable progressBlock)(double);
|
||||
|
||||
@end
|
||||
|
||||
@implementation SUUnarchiverNotifier
|
||||
|
||||
@synthesize completionBlock = _completionBlock;
|
||||
@synthesize progressBlock = _progressBlock;
|
||||
{
|
||||
void (^_completionBlock)(NSError * _Nullable);
|
||||
void (^ _Nullable _progressBlock)(double);
|
||||
}
|
||||
|
||||
- (instancetype)initWithCompletionBlock:(void (^)(NSError * _Nullable))completionBlock progressBlock:(void (^ _Nullable)(double))progressBlock
|
||||
{
|
||||
@@ -40,13 +34,13 @@
|
||||
- (void)notifySuccess
|
||||
{
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
self.completionBlock(nil);
|
||||
self->_completionBlock(nil);
|
||||
});
|
||||
}
|
||||
|
||||
- (void)notifyFailureWithError:(NSError * _Nullable)reason
|
||||
{
|
||||
NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithObject:SULocalizedString(@"An error occurred while extracting the archive. Please try again later.", nil) forKey:NSLocalizedDescriptionKey];
|
||||
NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithObject:@"An error occurred while extracting the archive. Please try again later." forKey:NSLocalizedDescriptionKey];
|
||||
if (reason) {
|
||||
[userInfo setObject:(NSError * _Nonnull)reason forKey:NSUnderlyingErrorKey];
|
||||
}
|
||||
@@ -54,15 +48,15 @@
|
||||
NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:userInfo];
|
||||
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
self.completionBlock(error);
|
||||
self->_completionBlock(error);
|
||||
});
|
||||
}
|
||||
|
||||
- (void)notifyProgress:(double)progress
|
||||
{
|
||||
if (self.progressBlock != nil) {
|
||||
if (_progressBlock != nil) {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
self.progressBlock(progress);
|
||||
self->_progressBlock(progress);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,11 +12,11 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@protocol SUUnarchiverProtocol <NSObject>
|
||||
|
||||
+ (BOOL)canUnarchivePath:(NSString *)path;
|
||||
|
||||
+ (BOOL)mustValidateBeforeExtraction;
|
||||
|
||||
- (void)unarchiveWithCompletionBlock:(void (^)(NSError * _Nullable))completionBlock progressBlock:(void (^ _Nullable)(double))progressBlock;
|
||||
- (void)unarchiveWithCompletionBlock:(void (^)(NSError * _Nullable))completionBlock progressBlock:(void (^ _Nullable)(double))progressBlock waitForCleanup:(BOOL)waitForCleanup;
|
||||
|
||||
@property (nonatomic, readonly) BOOL needsVerifyBeforeExtractionKey;
|
||||
|
||||
- (NSString *)description;
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface StatusInfo : NSObject <SUStatusInfoProtocol>
|
||||
SPU_OBJC_DIRECT_MEMBERS @interface StatusInfo : NSObject <SUStatusInfoProtocol>
|
||||
|
||||
- (instancetype)initWithHostBundleIdentifier:(NSString *)bundleIdentifier;
|
||||
|
||||
|
||||
+44
-8
@@ -12,15 +12,19 @@
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
|
||||
#define REPLY_STATUS_INFO_TIMEOUT 2
|
||||
|
||||
@interface StatusInfo () <NSXPCListenerDelegate>
|
||||
|
||||
@property (nonatomic) NSXPCListener *xpcListener;
|
||||
|
||||
@end
|
||||
|
||||
@implementation StatusInfo
|
||||
{
|
||||
NSXPCListener *_xpcListener;
|
||||
NSMutableDictionary *_pendingReplies;
|
||||
|
||||
NSUInteger _pendingReplyCounter;
|
||||
}
|
||||
|
||||
@synthesize xpcListener = _xpcListener;
|
||||
@synthesize installationInfoData = _installationInfoData;
|
||||
|
||||
- (instancetype)initWithHostBundleIdentifier:(NSString *)bundleIdentifier
|
||||
@@ -29,19 +33,20 @@
|
||||
if (self != nil) {
|
||||
_xpcListener = [[NSXPCListener alloc] initWithMachServiceName:SPUStatusInfoServiceNameForBundleIdentifier(bundleIdentifier)];
|
||||
_xpcListener.delegate = self;
|
||||
_pendingReplies = [NSMutableDictionary dictionary];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)startListener
|
||||
{
|
||||
[self.xpcListener resume];
|
||||
[_xpcListener resume];
|
||||
}
|
||||
|
||||
- (void)invalidate
|
||||
{
|
||||
[self.xpcListener invalidate];
|
||||
self.xpcListener = nil;
|
||||
[_xpcListener invalidate];
|
||||
_xpcListener = nil;
|
||||
}
|
||||
|
||||
- (BOOL)listener:(NSXPCListener *)__unused listener shouldAcceptNewConnection:(NSXPCConnection *)newConnection
|
||||
@@ -54,10 +59,41 @@
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (void)setInstallationInfoData:(NSData *)installationInfoData
|
||||
{
|
||||
_installationInfoData = installationInfoData;
|
||||
|
||||
// Respond to all of our pending replies
|
||||
for (NSNumber *replyKey in _pendingReplies) {
|
||||
void (^replyBlock)(NSData * _Nullable) = self->_pendingReplies[replyKey];
|
||||
replyBlock(_installationInfoData);
|
||||
}
|
||||
|
||||
[_pendingReplies removeAllObjects];
|
||||
}
|
||||
|
||||
- (void)probeStatusInfoWithReply:(void (^)(NSData * _Nullable))reply
|
||||
{
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
reply(self.installationInfoData);
|
||||
if (self->_installationInfoData != nil) {
|
||||
reply(self->_installationInfoData);
|
||||
} else {
|
||||
// If we don't have the installation info data currently, we may receive it in a very short window afterwards
|
||||
// In this case wait a bit for the reply. If we receive the data it will be in -setInstallationInfoData:
|
||||
NSUInteger currentReplyCounter = self->_pendingReplyCounter;
|
||||
self->_pendingReplyCounter++;
|
||||
|
||||
NSNumber *currentReplyCounterKey = @(currentReplyCounter);
|
||||
self->_pendingReplies[currentReplyCounterKey] = [reply copy];
|
||||
|
||||
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(REPLY_STATUS_INFO_TIMEOUT * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
|
||||
void (^replyBlock)(NSData * _Nullable) = self->_pendingReplies[currentReplyCounterKey];
|
||||
if (replyBlock != nil) {
|
||||
replyBlock(self->_installationInfoData);
|
||||
[self->_pendingReplies removeObjectForKey:currentReplyCounterKey];
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
//
|
||||
// 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
|
||||
@@ -1,131 +0,0 @@
|
||||
//
|
||||
// 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];
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
+5
-1
@@ -28,7 +28,11 @@ int main(int __unused argc, const char __unused *argv[])
|
||||
|
||||
dispatch_source_t sigtermSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, SIGTERM, 0, dispatch_get_main_queue());
|
||||
dispatch_source_set_event_handler(sigtermSource, ^{
|
||||
[appInstaller cleanupAndExitWithStatus:SIGTERM error:nil];
|
||||
// Don't clear the update directory because the installer may be in middle of installing an update
|
||||
// We still need to set an event handler for receiving SIGTERM though, otherwise our job may not terminate
|
||||
// (This is also recommended from the developer documentation).
|
||||
// Simply exit with SIGTERM if we receive this signal
|
||||
exit(SIGTERM);
|
||||
});
|
||||
dispatch_resume(sigtermSource);
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ struct Create: ParsableCommand {
|
||||
@Option(name: .long, help: ArgumentHelp(COMPRESSION_METHOD_ARGUMENT_DESCRIPTION, valueName: "compression"))
|
||||
var compression: String = "default"
|
||||
|
||||
@Option(name: .long, help: ArgumentHelp(COMPRESSION_LEVEL_ARGUMENT_DESCRIPTION, valueName: "compression-level"))
|
||||
@Option(name: .long, help: .hidden)
|
||||
var compressionLevel: UInt8 = 0
|
||||
|
||||
@Argument(help: ArgumentHelp("Path to original bundle to create a patch from."))
|
||||
|
||||
@@ -1,3 +1,225 @@
|
||||
# 2.8.0
|
||||
|
||||
* UI modernization and macOS Tahoe support
|
||||
* Modernize update alert and release notes UI (#2737) (Zorg, Noah Nuebling, Cykelero, Daniel Jalkut, Peter Nowell)
|
||||
* Update retrieving app icon to work better in Tahoe (#2742) (Zorg)
|
||||
* Improve retrieval of main app icon for authorization dialog (#2743) (Zorg)
|
||||
* Delta updates
|
||||
* Improve bsdiff performance by preventing excessive iterations when processing similar data blocks (#2693) (Will Fairclough)
|
||||
* Fix an issue while searching a cloneable file for delta updates (#2748, #2753) (Vincent Bénony, Zorg)
|
||||
* Add support for relative URLs for delta updates (#2741) (jj)
|
||||
* Localization
|
||||
* Set STRINGS_FILE_OUTPUT_ENCODING build setting to "binary" (#2712) (Nicolas Kick)
|
||||
* Move all localizations to main Sparkle.strings (#2760) (Zorg)
|
||||
* Synchronize updater settings with user defaults to fix out-of-sync UI state (#2728) (Zorg)
|
||||
* Document and better enforce main thread only requirement for using Sparkle methods (#2746, #2754) (Sebastien Marchand, Zorg)
|
||||
* Make -[SPUUserDriver showUpdateInFocus] optional (#2717) (Zorg)
|
||||
* Add private module map for framework (#2722) (Zorg)
|
||||
* Workaround a corner case in which the bundle path of a running application contains Contents/MacOS/Executable (#2726, #2747) (Jeremy Huddleston Sequoia, Zorg)
|
||||
* Disable false dependency scan analysis warnings when building Sparkle from source (#2762) (Daniel Jalkut)
|
||||
* Refactor the logic for avoiding re-sending the system profile more frequently than once a week (#2720) (Daniel Jalkut)
|
||||
|
||||
# 2.7.3
|
||||
|
||||
* Double quote team identifiers in requirement strings to fix crash if Team ID starts with number (#2766) (Zorg)
|
||||
|
||||
# 2.7.2
|
||||
|
||||
* Harden policy on what operations clients are allowed to take (#2763) (Zorg)
|
||||
|
||||
# 2.7.1
|
||||
|
||||
* Fix typo in NN localisation (#2694) (Sjur N Moshagen)
|
||||
* Fix compiler warnings for Xcode 16.3 (#2709) (Zorg)
|
||||
* Fix Sparkle not building when SPARKLE_COPY_LOCALIZATIONS=0 (#2707) (Zorg)
|
||||
* Fix release notes constraints when compiled with macOS 26 SDK (#2730) (Zorg)
|
||||
* Fix reserved identifier warnings for Xcode 26 (#2729) (Zorg)
|
||||
|
||||
# 2.7.0
|
||||
|
||||
* Unarchiver / validation improvements (Zorg)
|
||||
* Remove old checksum verification checks for dmg archives to improve extraction speed (#2568) (Zorg)
|
||||
* Skip extracting auxiliary files and improve extraction progress for disk images (#2569) (Zorg)
|
||||
* Improve robustness around extracting dmg's with passwords (#2627, #2571) (Zorg)
|
||||
* Randomize the download archive name the installer extracts/executes (#2584) (Zorg)
|
||||
* Retry extracting zip file without piping if extraction fails to workaround bug prior to macOS 15 (#2616) (Zorg)
|
||||
* Add opt-in SUVerifyUpdateBeforeExtraction option to force verification of updates before extraction (#2667) (Zorg)
|
||||
* Add support for extracting Apple Archives (.aar files; requires SUVerifyUpdateBeforeExtraction, macOS 10.15+) (#2586, #2588, #2590) (Zorg)
|
||||
* Don't allow removal of signing keys more strictly (#2647) (Zorg)
|
||||
* Remove SPARKLE_BUILD_DMG_SUPPORT option (#2690) (Zorg)
|
||||
* Add new BinaryDelta format (version 4) (Zorg)
|
||||
* Preserve bundle creation date when creating and applying delta updates (#2583) (Zorg)
|
||||
* Use faster crc32 hashes for binary delta version 4 (#2638) (Zorg)
|
||||
* Make binary delta version 4 the default (#2668) (Zorg)
|
||||
* Language / layout improvements
|
||||
* Fix recovery error suggestion not shown when app is translocated or on read-only mount (#2689) (Zorg)
|
||||
* Fix typo in Dutch localisation (#2642) (Eitot)
|
||||
* Add baseline alignment to status text in SUStatus dialog (#2587) (Eitot)
|
||||
* Make horizontal hugging priority required for status text field (#2614) (Zorg)
|
||||
* Adjust the layout of anonymous system profile info to align better with the rest of the panel's UI (#2564) (Daniel Jalkut)
|
||||
* Fix typo in Dutch localisation (#2642) (Eitot)
|
||||
* Internationalize system profile display keys (#2577) (Zorg)
|
||||
* Update hebrew locale and add right-to-left characters (#2573, #2576, #2578, #2579) (Shlomo)
|
||||
* Update localisations for Dutch and German (#2582) (Eitot)
|
||||
* Add unlocalized strings in Japanese (#2589) (1024jp)
|
||||
* Fix typo in LICENSE (#2648) (fujisoft)
|
||||
* Deprecate custom version comparators (#2639) (Zorg)
|
||||
* Skip preflight update check in sparkle-cli if user is root (#2645) (Zorg)
|
||||
* Avoid assert/crash when app is moved before update alert shows (#2658) (Zorg)
|
||||
* Use default NSURLRequest timeoutInterval for the downloader (currently 60s) (#2673) (Zorg)
|
||||
* Fix process substitution failing to work for providing the private key as file argument (#2615) (Zorg)
|
||||
* Improve unable decode private key error messages in generate_appcast (#2675) (Zorg)
|
||||
* Clarify that default channel must be in allowed channels set in API documentation (#2676) (Zorg)
|
||||
* Call update permission prompt delegate method only when needed (#2622) (Zorg)
|
||||
* Resolve duplicate class definitions from BinaryDelta, Sparkle Test App, and unit tests (#2570, #2629) (Zorg)
|
||||
|
||||
# 2.6.4
|
||||
|
||||
* Fix app modification prompt from appearing when downloaded update overrides NSUpdateSecurityPolicy (#2593)
|
||||
|
||||
# 2.6.3
|
||||
|
||||
* Guard update timer update check against sessionInProgress to fix rare crash when checking for updates (#2561)
|
||||
* Remove extra writeData: call when unarchiving disk images (#2562)
|
||||
* Ignore crashes due to SIGPIPE in generate_appcast when failing to extract zip files (#2563)
|
||||
|
||||
# 2.6.2
|
||||
|
||||
* Create and use temp extraction directory in generate_appcast again (#2555) (Zorg)
|
||||
|
||||
# 2.6.1
|
||||
|
||||
* Extract archives in a separate directory from the input archive (#2550) (Zorg)
|
||||
* Fix the release notes WebKit view not updating background when transitioning from light to dark mode (#2542) (Zorg)
|
||||
* Add NN (Norwegian Nynorsk) locale (#2532) (Sjur N Moshagen, Zorg)
|
||||
* Create tar.xz files with built-in tar and remove bzip2 fallback for creating a release distribution (#2535) (Zorg)
|
||||
* Add fallback in case SULocalizedStringFromTableInBundle() fails (#2533) (Zorg)
|
||||
* Remove assert on download response being available fixing rare crash (#2547) (Zorg)
|
||||
* Clarify when authoriation prompt may show in SPUUserDriver documentation (#2531, #2534) (Zorg)
|
||||
* Fix typos in codebase (#2537) (Viktor Szépe)
|
||||
|
||||
# 2.6.0
|
||||
|
||||
* Perform Gatekeeper scan to pre-warm app launch (#2505) (Zorg)
|
||||
* Disable sandboxing for the Downloader XPC service by default to fix downloader prompt warnings (#2511) (Zorg)
|
||||
* Store private seed as the secret for newly generated keys (#2472) (Zorg)
|
||||
* Improve signing error message to developers if they serve the wrong update file (#2471) (Zorg)
|
||||
* Prevent app modification warnings from external updaters (like sparkli-cli) by improving installation (#2516) (Zorg)
|
||||
* Update Korean localization (#2504) (CheolHyun Mun)
|
||||
* Use $PROJECT_DIR instead of $SRCROOT (#2489) (Zorg)
|
||||
* Set Package.swift minimum deployment to macOS 10.13 (#2481) (Eitot)
|
||||
* Fix false positive analyzer warning about resumableUpdate type (#2454) (Zorg)
|
||||
|
||||
# 2.5.2
|
||||
|
||||
* Don't clean up update directory when Autoupdate receives SIGTERM (#2479) (Zorg)
|
||||
* Update Japanese localization (#2475) (1024jp)
|
||||
* Improve Turkish translations (#2464) (Emir SARI)
|
||||
* Update Spanish translation for 'You are currently running version %@.' and 'Version History' (#2463) (Billy Gray)
|
||||
|
||||
# 2.5.1
|
||||
|
||||
* Default to English for XML nodes when no xml:lang is present (#2440) (Zorg)
|
||||
* Filter for archive files in generate_appcast more intelligently (#2448) (Zorg)
|
||||
* Use correct entitlements and dsym files when using custom bundle id and XPC names in ConfigCommon (#2446) (floorish)
|
||||
|
||||
# 2.5.0
|
||||
|
||||
* Add ability to adapt release notes based on the currently installed version (#2373) (Nathan Manceaux-Panot)
|
||||
* Allow developers to use custom URL schemes in the release notes view (#2393) (Zorg)
|
||||
* Adopt cooperative app activation APIs in macOS 14 Sonoma (#2409) (Zorg)
|
||||
* Improve permission prompt layout (#2420) (Zorg)
|
||||
* Remove hyphenation in "You're up to date" message (#2425) (Zorg, Dom Neill)
|
||||
* Pre-warm installs before relaunch and resolve sporadic failures in CI (#2421) (Zorg)
|
||||
* Fix make release not building distribution successfully (#2430) (Zorg)
|
||||
* Fix Updater app not starting when running Sparkle as root (e.g. from CLI with sudo or a daemon) on macOS 14 Sonoma (#2432) (Zorg)
|
||||
* Fix KVO usage for updaterController.updater.* (#2404) (Zorg)
|
||||
* Replace CFUUID* with NSUUID (#2395) (Eitot)
|
||||
* Report an error when detecting duplicate updates in generate_appcast (#2407) (Zorg)
|
||||
* Improve error for rejecting xattr based code signing for delta updates (#2408) (Zorg)
|
||||
* Fail gracefully when auxiliary tool cannot be located (#2436) (Zorg)
|
||||
|
||||
# 2.4.2
|
||||
|
||||
* Ignore release notes download when we shouldn't show release notes (#2381) (Zorg)
|
||||
* Fix NSKeyedUnarchiver warning for not specifying keyed NSString class (#2381) (Zorg)
|
||||
* Harden verification of Sparkle update download (#2392) (Zorg)
|
||||
|
||||
# 2.4.1
|
||||
|
||||
* Remove auxiliary apps and relocate symbols in SPM package to resolve missing AvailableLibraries warnings (#2356) (Zorg)
|
||||
* Add -Wno-declaration-after-statement to silence warnings that only apply to pre-C99 (#2345) (Kent Sutherland)
|
||||
* Fix compile error when setting SPARKLE_EMBED_DOWNLOADER_XPC_SERVICE=0 (#2346) (Zorg)
|
||||
* Improve how downloaded update is passed to the installer (#2359) (Zorg)
|
||||
|
||||
# 2.4.0
|
||||
|
||||
* Reduce code size
|
||||
* Enable deployment postprocessing in Release to properly strip debug symbols and strip all non-global symbols (#2286, #2305) (Zorg)
|
||||
* Remove duplicate Sparkle localization strings in Updater app (#2288) (Zorg)
|
||||
* Optimize codebase for generated code size (less properties, direct methods, etc) (#2305) (Zorg)
|
||||
* Add additional settings to `ConfigCommon.xcconfig` for disabling features
|
||||
* Ask permission for automatically downloading and installing new updates (#2285) (Zorg)
|
||||
* Add support for plain text release notes view that does not use web view (#2315) (Zorg)
|
||||
* Update `SUVersionDisplay` to better customize and display how versions are shown (#2321) (Zorg)
|
||||
* Add deprecations/warnings for incorrect background update checking usage (#2295) (Zorg)
|
||||
* Deprecate `-[SPUUpdater setFeedURL:]` API and add `-[SPUUpdater clearFeedURLFromUserDefaults]` for migrating away from `-[SPUUpdater setFeedURL:]` (#2295)
|
||||
* Trigger a new update check in `-[SPUUpdater resetUpdateCycle]` if the updater's feed or allowed channels have changed (#2324) (Zorg)
|
||||
* Exit with an error if generate_appcast cannot sign an update that must be signed (#2322) (Zorg)
|
||||
* Remove a redundant Apple code signing check when verifying new updates (#2341) (Zorg)
|
||||
* Turn off auto-linking for XPC targets to alleviate circular dependency issues (#2332) (Daniel Jalkut)
|
||||
|
||||
# 2.3.2
|
||||
|
||||
* Fix potential crash during download if appcast item includes invalid enclosure URL (#2317) (Zorg)
|
||||
* Add delegate method to hide showing version history option (#2303) (Zorg)
|
||||
* Finnish localization grammar fixes (#2311) (Lauri-Matti Parppei)
|
||||
|
||||
# 2.3.1
|
||||
|
||||
* Fix update permission alert title text overlapping with question text in some languages (#2284) (Zorg)
|
||||
* Log the URL that failed to download correctly (#2296) (Zorg)
|
||||
* Update Czech translation (#2275) (Sam)
|
||||
* Add zh_HK (Chinese, Hong Kong) localization (#2273) (Bing Zheung)
|
||||
|
||||
# 2.3.0
|
||||
|
||||
* Bump minimum deployment target to macOS 10.13 (#2196) (Zorg)
|
||||
* Remove and preserve necessary updates in generate_appcast (#2218) (Zorg)
|
||||
* Move old update files no longer needed to old_updates/ in archive directory in generate_appcast (#2228) (Zorg)
|
||||
* Expose maximum-versions option (per branch) in generate_appcast to preserve in the feed (#2259) (Zorg)
|
||||
* Add -p option to sign_update to only print the signed signature (#2268) (Zorg)
|
||||
* Hide automatic install check box when allowsAutomaticUpdates is disabled (#2202) (Jie)
|
||||
* Allow developer to always force allowing automatic updates (#2266) (Zorg)
|
||||
* Fix update window going haywire during resize when release notes are hidden by disabling resizing (#2200) (Zorg)
|
||||
* Allow user to re-try installing/relaunching application when quit is delayed/cancelled (#2234) (Zorg)
|
||||
* Add delta update attributes for validating an app hasn't been stripped from removed localizations or architectures (#2219) (Zorg)
|
||||
* Fix delta patches not applying edge case if files from source that need to be diffed are not writeable (#2211) (Zorg)
|
||||
* Add delegate callback when user makes choice to install, dismiss, or skip an update (#2250) (Zorg)
|
||||
* Reject serving updates with DSA only and no EdDSA (#2167) (Zorg)
|
||||
* Find potential matching running apps that are translocated in the updater agent (#2233) (Zorg)
|
||||
* Expose -[SPUStandardUserDriver activeUpdateAlert] as private API (#2255) (Zorg)
|
||||
* Add zh_CN l10n for "Version History" (#2247) (kakaiikaka)
|
||||
* Update zh_TW localization (#2271) (Chiahong)
|
||||
* Remove ed25519 git submodule in favor of including the dependency directly (#2244) (Zorg)
|
||||
* Clean up left-over code (#2243) (Eitot)
|
||||
* Update Package.resolved (#2245) (Zorg)
|
||||
* Remove model translation table for system profiling (#2188) (Zorg)
|
||||
* Improve documentation usage for SPUUpdater properties (#2256) (Zorg)
|
||||
|
||||
This release improves generate_appcast by automatically removing updates that are no longer needed in the generated appcast, and moving old update files to old_updates/ in the archives directory. New delta update attributes are also added to let Sparkle know when to skip downloading delta updates if the application has been stripped.
|
||||
|
||||
macOS 10.13 or later is now required (due to Xcode 14 dropping support for deploying to older OS versions).
|
||||
|
||||
If you're not generating appcasts automatically, remember to add `<sparkle:minimumSystemVersion>10.13</sparkle:minimumSystemVersion>` element to `<item>`s in your appcast.
|
||||
|
||||
# 2.2.2
|
||||
|
||||
* Critical update alerts may not show up as promptly as they should when they are being automatically installed (#2230) (Zorg)
|
||||
* Remove module imports from framework headers (#2217) (Zorg)
|
||||
* Update Portuguese localization (#2224) (Kent Sutherland)
|
||||
* Update zh_TW localization (#2246) (Chiahong)
|
||||
|
||||
# 2.2.1
|
||||
|
||||
* Make scroll bar dark in dark theme for Release Notes by default (#2187) (Pavel Moiseenko)
|
||||
@@ -120,6 +342,15 @@ Please visit [Sparkle's website](http://sparkle-project.org) for more informatio
|
||||
|
||||
If you are migrating from earlier beta versions of Sparkle 2 and use sandboxing, please re-familiarize yourself with the [Sandboxing guide](https://sparkle-project.org/documentation/sandboxing/). Some of the XPC Services are now optional and integration with XPC Services and code signing have been simplified. The SPUUserDriver protocol for custom user interfaces has been greatly simplified too.
|
||||
|
||||
# 1.27.3
|
||||
|
||||
* Create and use temp extraction directory in generate_appcast again (#2556) (Zorg)
|
||||
|
||||
# 1.27.2
|
||||
|
||||
* Extract archives in a separate directory from the input archive (#2552) (Zorg)
|
||||
* Fix incorrect xz log warning in make release (#2044) (trss)
|
||||
|
||||
# 1.27.1
|
||||
|
||||
* Use px instead of pt when specifying font size to fix default font size in WebView from #1962 (regressed in 1.25.0 with WKWebView adoption) (Daniel Jalkut)
|
||||
@@ -278,7 +509,7 @@ If you are migrating from earlier beta versions of Sparkle 2 and use sandboxing,
|
||||
# 1.20.0
|
||||
|
||||
* `generate_appcast` option to read private key directly from the keychain (Tamás Lustyik)
|
||||
* Add delegate callbacks for fininshed download and extraction related events (Csaba Horony)
|
||||
* Add delegate callbacks for finished download and extraction related events (Csaba Horony)
|
||||
* Don't check for updates if Do Not Disturb is on (Kornel)
|
||||
* Expose `CodesigningVerifier`, add codesign info API (sunuslee)
|
||||
* Threading fixes:
|
||||
@@ -628,7 +859,7 @@ Important security fixes:
|
||||
* All the user defaults keys are now private; instead, SUUpdater is KVC-compliant for automaticallyChecksForUpdates, updateCheckInterval, and feedURL.
|
||||
* Reduced the size of the English-only framework by 25%.
|
||||
* System profiling information is now only submitted to the server once per week; this will help normalize your statistics across users with different interval preferences.
|
||||
* The feedParamatersForUpdater: delegate method now requires "displayKey" and "displayVersion" keys so that it can inform the user what's being sent.
|
||||
* The feedParametersForUpdater: delegate method now requires "displayKey" and "displayVersion" keys so that it can inform the user what's being sent.
|
||||
* Added a delegate method called pathToRelaunchForUpdater: which can be used for plugins to provide the path which should be used when relaunching the client after installing an update.
|
||||
* Added support for xml:lang to pick localized nodes in appcasts (for release notes, etc).
|
||||
* Fixed a bug which would cause the "checking for updates" window to not disappear in certain extraordinary error conditions.
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"1.27.1": "https://github.com/sparkle-project/Sparkle/releases/download/1.27.1/Sparkle-1.27.1.tar.xz", "2.0.0-beta.6": "https://github.com/sparkle-project/Sparkle/releases/download/2.0.0-beta.6/Sparkle-2.0.0-beta.6.tar.xz", "2.0.0-rc.1": "https://github.com/sparkle-project/Sparkle/releases/download/2.0.0-rc.1/Sparkle-2.0.0-rc.1.tar.xz", "2.0.0": "https://github.com/sparkle-project/Sparkle/releases/download/2.0.0/Sparkle-2.0.0.tar.xz", "2.1.0-beta.1": "https://github.com/sparkle-project/Sparkle/releases/download/2.1.0-beta.1/Sparkle-2.1.0-beta.1.tar.xz", "2.1.0-beta.2": "https://github.com/sparkle-project/Sparkle/releases/download/2.1.0-beta.2/Sparkle-2.1.0-beta.2.tar.xz", "2.1.0": "https://github.com/sparkle-project/Sparkle/releases/download/2.1.0/Sparkle-2.1.0.tar.xz", "2.2.0-beta.1": "https://github.com/sparkle-project/Sparkle/releases/download/2.2.0-beta.1/Sparkle-2.2.0-beta.1.tar.xz", "2.2.0-beta.2": "https://github.com/sparkle-project/Sparkle/releases/download/2.2.0-beta.2/Sparkle-2.2.0-beta.2.tar.xz", "2.2.0": "https://github.com/sparkle-project/Sparkle/releases/download/2.2.0/Sparkle-2.2.0.tar.xz", "2.2.1": "https://github.com/sparkle-project/Sparkle/releases/download/2.2.1/Sparkle-2.2.1.tar.xz"}
|
||||
{"1.27.1": "https://github.com/sparkle-project/Sparkle/releases/download/1.27.1/Sparkle-1.27.1.tar.xz", "2.0.0-beta.6": "https://github.com/sparkle-project/Sparkle/releases/download/2.0.0-beta.6/Sparkle-2.0.0-beta.6.tar.xz", "2.0.0-rc.1": "https://github.com/sparkle-project/Sparkle/releases/download/2.0.0-rc.1/Sparkle-2.0.0-rc.1.tar.xz", "2.0.0": "https://github.com/sparkle-project/Sparkle/releases/download/2.0.0/Sparkle-2.0.0.tar.xz", "2.1.0-beta.1": "https://github.com/sparkle-project/Sparkle/releases/download/2.1.0-beta.1/Sparkle-2.1.0-beta.1.tar.xz", "2.1.0-beta.2": "https://github.com/sparkle-project/Sparkle/releases/download/2.1.0-beta.2/Sparkle-2.1.0-beta.2.tar.xz", "2.1.0": "https://github.com/sparkle-project/Sparkle/releases/download/2.1.0/Sparkle-2.1.0.tar.xz", "2.2.0-beta.1": "https://github.com/sparkle-project/Sparkle/releases/download/2.2.0-beta.1/Sparkle-2.2.0-beta.1.tar.xz", "2.2.0-beta.2": "https://github.com/sparkle-project/Sparkle/releases/download/2.2.0-beta.2/Sparkle-2.2.0-beta.2.tar.xz", "2.2.0": "https://github.com/sparkle-project/Sparkle/releases/download/2.2.0/Sparkle-2.2.0.tar.xz", "2.2.1": "https://github.com/sparkle-project/Sparkle/releases/download/2.2.1/Sparkle-2.2.1.tar.xz", "2.2.2": "https://github.com/sparkle-project/Sparkle/releases/download/2.2.2/Sparkle-2.2.2.tar.xz", "2.3.0-beta.1": "https://github.com/sparkle-project/Sparkle/releases/download/2.3.0-beta.1/Sparkle-2.3.0-beta.1.tar.xz", "2.3.0-beta.2": "https://github.com/sparkle-project/Sparkle/releases/download/2.3.0-beta.2/Sparkle-2.3.0-beta.2.tar.xz", "2.3.0": "https://github.com/sparkle-project/Sparkle/releases/download/2.3.0/Sparkle-2.3.0.tar.xz", "2.3.1": "https://github.com/sparkle-project/Sparkle/releases/download/2.3.1/Sparkle-2.3.1.tar.xz", "2.3.2": "https://github.com/sparkle-project/Sparkle/releases/download/2.3.2/Sparkle-2.3.2.tar.xz", "2.4.0-beta.1": "https://github.com/sparkle-project/Sparkle/releases/download/2.4.0-beta.1/Sparkle-2.4.0-beta.1.tar.xz", "2.4.0-beta.2": "https://github.com/sparkle-project/Sparkle/releases/download/2.4.0-beta.2/Sparkle-2.4.0-beta.2.tar.xz", "2.4.0": "https://github.com/sparkle-project/Sparkle/releases/download/2.4.0/Sparkle-2.4.0.tar.xz", "2.4.1-beta.1": "https://github.com/sparkle-project/Sparkle/releases/download/2.4.1-beta.1/Sparkle-2.4.1-beta.1.tar.xz", "2.4.1": "https://github.com/sparkle-project/Sparkle/releases/download/2.4.1/Sparkle-2.4.1.tar.xz", "2.4.2": "https://github.com/sparkle-project/Sparkle/releases/download/2.4.2/Sparkle-2.4.2.tar.xz", "2.5.0-beta.1": "https://github.com/sparkle-project/Sparkle/releases/download/2.5.0-beta.1/Sparkle-2.5.0-beta.1.tar.xz", "2.5.0-beta.2": "https://github.com/sparkle-project/Sparkle/releases/download/2.5.0-beta.2/Sparkle-2.5.0-beta.2.tar.xz", "2.5.0": "https://github.com/sparkle-project/Sparkle/releases/download/2.5.0/Sparkle-2.5.0.tar.xz", "2.5.1": "https://github.com/sparkle-project/Sparkle/releases/download/2.5.1/Sparkle-2.5.1.tar.xz", "2.5.2": "https://github.com/sparkle-project/Sparkle/releases/download/2.5.2/Sparkle-2.5.2.tar.xz", "2.6.0-beta.1": "https://github.com/sparkle-project/Sparkle/releases/download/2.6.0-beta.1/Sparkle-2.6.0-beta.1.tar.xz", "2.6.0-beta.2": "https://github.com/sparkle-project/Sparkle/releases/download/2.6.0-beta.2/Sparkle-2.6.0-beta.2.tar.xz", "2.6.0": "https://github.com/sparkle-project/Sparkle/releases/download/2.6.0/Sparkle-2.6.0.tar.xz", "2.6.1": "https://github.com/sparkle-project/Sparkle/releases/download/2.6.1/Sparkle-2.6.1.tar.xz", "1.27.2": "https://github.com/sparkle-project/Sparkle/releases/download/1.27.2/Sparkle-1.27.2.tar.xz", "2.6.2": "https://github.com/sparkle-project/Sparkle/releases/download/2.6.2/Sparkle-2.6.2.tar.xz", "1.27.3": "https://github.com/sparkle-project/Sparkle/releases/download/1.27.3/Sparkle-1.27.3.tar.xz", "2.6.3": "https://github.com/sparkle-project/Sparkle/releases/download/2.6.3/Sparkle-2.6.3.tar.xz", "2.6.4": "https://github.com/sparkle-project/Sparkle/releases/download/2.6.4/Sparkle-2.6.4.tar.xz", "2.7.0-beta.1": "https://github.com/sparkle-project/Sparkle/releases/download/2.7.0-beta.1/Sparkle-2.7.0-beta.1.tar.xz", "2.7.0": "https://github.com/sparkle-project/Sparkle/releases/download/2.7.0/Sparkle-2.7.0.tar.xz", "2.7.1": "https://github.com/sparkle-project/Sparkle/releases/download/2.7.1/Sparkle-2.7.1.tar.xz", "2.7.2": "https://github.com/sparkle-project/Sparkle/releases/download/2.7.2/Sparkle-2.7.2.tar.xz", "2.7.3": "https://github.com/sparkle-project/Sparkle/releases/download/2.7.3/Sparkle-2.7.3.tar.xz", "2.8.0-beta.1": "https://github.com/sparkle-project/Sparkle/releases/download/2.8.0-beta.1/Sparkle-2.8.0-beta.1.tar.xz", "2.8.0-beta.2": "https://github.com/sparkle-project/Sparkle/releases/download/2.8.0-beta.2/Sparkle-2.8.0-beta.2.tar.xz", "2.8.0-beta.3": "https://github.com/sparkle-project/Sparkle/releases/download/2.8.0-beta.3/Sparkle-2.8.0-beta.3.tar.xz"}
|
||||
@@ -3,4 +3,4 @@
|
||||
#include "ConfigSwift.xcconfig"
|
||||
|
||||
SWIFT_OBJC_BRIDGING_HEADER = $(PRODUCT_NAME)/Bridging-Header.h
|
||||
GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS) BUILDING_SPARKLE_TOOL=1
|
||||
GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS) BUILDING_EXTERNALLY=1
|
||||
@@ -1,15 +1,62 @@
|
||||
// Common
|
||||
|
||||
SPARKLE_BUNDLE_IDENTIFIER = org.sparkle-project.Sparkle
|
||||
SPARKLE_RELAUNCH_TOOL_NAME = Autoupdate
|
||||
SPARKLE_INSTALLER_PROGRESS_TOOL_NAME = Updater
|
||||
|
||||
// Set to 1 or 0 to bundle or not bundle provided XPC Services in Sparkle framework
|
||||
// Set to 1 or 0 to build and bundle the provided XPC Services in Sparkle framework
|
||||
// (Note for testing purposes for sandboxed apps, disabling all XPC services and then re-enabling them
|
||||
// may not work on the same login session due to a system caching issue. See comments for setting FRAMEWORK_VERSION for more info)
|
||||
SPARKLE_EMBED_INSTALLER_LAUNCHER_XPC_SERVICE = 1
|
||||
// Embedding the downloader service also enables building legacy WebKit1 support
|
||||
SPARKLE_EMBED_DOWNLOADER_XPC_SERVICE = 1
|
||||
SPARKLE_EMBED_INSTALLER_STATUS_XPC_SERVICE = 0
|
||||
SPARKLE_EMBED_INSTALLER_CONNECTION_XPC_SERVICE = 0
|
||||
|
||||
// Set to 0 to disable building legacy 1.x SUUpdater stub
|
||||
SPARKLE_BUILD_LEGACY_SUUPDATER = 1
|
||||
|
||||
// Set to 0 to not build legacy DSA signing support
|
||||
// Don't disable this if you haven't migrated to EdDSA yet or if you support updating
|
||||
// other developer's applications that haven't migrated to EdDSA yet
|
||||
// If this is disabled, this requires an update to OTHER_SWIFT_FLAGS_COMMON below
|
||||
SPARKLE_BUILD_LEGACY_DSA_SUPPORT = 1
|
||||
|
||||
// Set to 0 to not build legacy DSA signing support for generate_appcast
|
||||
// Don't disable this if you still have items in your appcast feed that still need DSA signatures
|
||||
// If this is disabled, this requires an update to OTHER_SWIFT_FLAGS_COMMON below
|
||||
GENERATE_APPCAST_BUILD_LEGACY_DSA_SUPPORT = 1
|
||||
|
||||
// Set to 0 to not build legacy / xar based delta update support
|
||||
SPARKLE_BUILD_LEGACY_DELTA_SUPPORT = 1
|
||||
|
||||
// Set to 0 to not build bzip2 support for version 3 delta based updates
|
||||
SPARKLE_BUILD_BZIP2_DELTA_SUPPORT = 1
|
||||
|
||||
// Set to 0 to not build support for package (pkg) based installations
|
||||
// If this is disabled, this requires an update to OTHER_SWIFT_FLAGS_COMMON below
|
||||
SPARKLE_BUILD_PACKAGE_SUPPORT = 1
|
||||
|
||||
// Set to 0 to only build all non-UI bits (which means client uses a custom SPUUserDriver)
|
||||
SPARKLE_BUILD_UI_BITS = 1
|
||||
|
||||
// Set to 0 to not use and copy localization / string files to framework
|
||||
SPARKLE_COPY_LOCALIZATIONS = 1
|
||||
|
||||
// Compilation flags for Swift tools and unit tests
|
||||
// If SPARKLE_BUILD_LEGACY_DELTA_SUPPORT is set to 0, remove -DSPARKLE_BUILD_LEGACY_DSA_SUPPORT
|
||||
// If GENERATE_APPCAST_BUILD_LEGACY_DSA_SUPPORT is set to 0, remove -DGENERATE_APPCAST_BUILD_LEGACY_DSA_SUPPORT
|
||||
// If SPARKLE_BUILD_PACKAGE_SUPPORT is set to 0, remove -DSPARKLE_BUILD_PACKAGE_SUPPORT
|
||||
OTHER_SWIFT_FLAGS_COMMON = -DSPARKLE_BUILD_LEGACY_DSA_SUPPORT -DGENERATE_APPCAST_BUILD_LEGACY_DSA_SUPPORT -DSPARKLE_BUILD_PACKAGE_SUPPORT
|
||||
|
||||
// Minimum supported macOS version
|
||||
MACOSX_DEPLOYMENT_TARGET = 10.13
|
||||
|
||||
// Supported architectures
|
||||
ARCHS = $(ARCHS_STANDARD)
|
||||
|
||||
// Default Sparkle names
|
||||
SPARKLE_BUNDLE_IDENTIFIER = org.sparkle-project.Sparkle
|
||||
SPARKLE_RELAUNCH_TOOL_NAME = Autoupdate
|
||||
SPARKLE_INSTALLER_PROGRESS_TOOL_NAME = Updater
|
||||
SPARKLE_INSTALLER_PROGRESS_TOOL_BUNDLE_ID = $(SPARKLE_BUNDLE_IDENTIFIER).$(SPARKLE_INSTALLER_PROGRESS_TOOL_NAME)
|
||||
|
||||
// Set these if you want to use custom name for the XPC Services
|
||||
// For the Installer one in particular, this name may show up in an authorization prompt
|
||||
// when installing an update that requires authorization.
|
||||
@@ -24,10 +71,14 @@ XPC_SERVICE_BUNDLE_ID_PREFIX = org.sparkle-project
|
||||
INSTALLER_CONNECTION_BUNDLE_ID = ${XPC_SERVICE_BUNDLE_ID_PREFIX}.InstallerConnection
|
||||
INSTALLER_STATUS_BUNDLE_ID = ${XPC_SERVICE_BUNDLE_ID_PREFIX}.InstallerStatus
|
||||
INSTALLER_LAUNCHER_BUNDLE_ID = ${XPC_SERVICE_BUNDLE_ID_PREFIX}.InstallerLauncher
|
||||
DOWNLOADER_BUNDLE_ID = ${XPC_SERVICE_BUNDLE_ID_PREFIX}.Downloader
|
||||
DOWNLOADER_BUNDLE_ID = ${XPC_SERVICE_BUNDLE_ID_PREFIX}.DownloaderService
|
||||
|
||||
// The Downloader XPC Service is not sandboxed by default.
|
||||
// Uncomment line to enable Sandboxing for this service.
|
||||
// If this is done, you *must* set a custom XPC_SERVICE_BUNDLE_ID_PREFIX for your app above.
|
||||
// Otherwise sandboxed apps that use the same sandboxed Downloader Service may conflict with each other.
|
||||
//DOWNLOADER_SANDBOXED_ENTITLEMENTS = Downloader/Downloader.entitlements
|
||||
|
||||
// Set to 0 to only build all non-UI bits
|
||||
SPARKLE_BUILD_UI_BITS = 1
|
||||
|
||||
// If your app file on disk is named "MyApp 1.1b4", Sparkle usually updates it
|
||||
// in place, giving you an app named 1.1b4 that is actually 1.2. Turn the
|
||||
@@ -42,25 +93,23 @@ SPARKLE_ICON_NAME = AppIcon
|
||||
// If you change any of these version details, you must increase CURRENT_PROJECT_VERSION
|
||||
// These variables must have a space after the '=' too
|
||||
SPARKLE_VERSION_MAJOR = 2
|
||||
SPARKLE_VERSION_MINOR = 2
|
||||
SPARKLE_VERSION_PATCH = 1
|
||||
SPARKLE_VERSION_MINOR = 8
|
||||
SPARKLE_VERSION_PATCH = 0
|
||||
|
||||
// This should be in SemVer format or empty, ie. "-beta.1"
|
||||
// These variables must have a space after the '=' too
|
||||
SPARKLE_VERSION_SUFFIX =
|
||||
CURRENT_PROJECT_VERSION = 2017
|
||||
SPARKLE_VERSION_SUFFIX = -beta.3
|
||||
CURRENT_PROJECT_VERSION = 2048
|
||||
|
||||
MARKETING_VERSION = $(SPARKLE_VERSION_MAJOR).$(SPARKLE_VERSION_MINOR).$(SPARKLE_VERSION_PATCH)$(SPARKLE_VERSION_SUFFIX)
|
||||
ALWAYS_SEARCH_USER_PATHS = NO
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES
|
||||
GCC_SYMBOLS_PRIVATE_EXTERN = YES
|
||||
GCC_INLINES_ARE_PRIVATE_EXTERN = YES
|
||||
ARCHS = $(ARCHS_STANDARD)
|
||||
MACOSX_DEPLOYMENT_TARGET = 10.11
|
||||
PRODUCT_NAME = ${TARGET_NAME}
|
||||
PRODUCT_BUNDLE_IDENTIFIER = org.sparkle-project.Sparkle.${PRODUCT_NAME:rfc1034identifier}
|
||||
|
||||
GCC_PREPROCESSOR_DEFINITIONS_COMMON = SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME=$(SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME) SPARKLE_BUILD_UI_BITS=$(SPARKLE_BUILD_UI_BITS) SPARKLE_BUNDLE_IDENTIFIER=\"$(SPARKLE_BUNDLE_IDENTIFIER)\" CURRENT_PROJECT_VERSION=\"$(CURRENT_PROJECT_VERSION)\" MARKETING_VERSION=\"$(MARKETING_VERSION)\" SPARKLE_RELAUNCH_TOOL_NAME=\"$(SPARKLE_RELAUNCH_TOOL_NAME)\" SPARKLE_INSTALLER_PROGRESS_TOOL_NAME=\"$(SPARKLE_INSTALLER_PROGRESS_TOOL_NAME)\" SPARKLE_ICON_NAME=\"$(SPARKLE_ICON_NAME)\" INSTALLER_LAUNCHER_NAME=\"${INSTALLER_LAUNCHER_NAME}\" INSTALLER_LAUNCHER_BUNDLE_ID=\"${INSTALLER_LAUNCHER_BUNDLE_ID}\" INSTALLER_CONNECTION_NAME=\"${INSTALLER_CONNECTION_NAME}\" INSTALLER_CONNECTION_BUNDLE_ID=\"${INSTALLER_CONNECTION_BUNDLE_ID}\" INSTALLER_STATUS_NAME=\"${INSTALLER_STATUS_NAME}\" INSTALLER_STATUS_BUNDLE_ID=\"${INSTALLER_STATUS_BUNDLE_ID}\" DOWNLOADER_NAME=\"${DOWNLOADER_NAME}\" DOWNLOADER_BUNDLE_ID=\"${DOWNLOADER_BUNDLE_ID}\"
|
||||
GCC_PREPROCESSOR_DEFINITIONS_COMMON = SPU_OBJC_DIRECT=__attribute__((objc_direct)) SPU_OBJC_DIRECT_MEMBERS=__attribute__((objc_direct_members)) SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME=$(SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME) SPARKLE_BUILD_UI_BITS=$(SPARKLE_BUILD_UI_BITS) SPARKLE_COPY_LOCALIZATIONS=$(SPARKLE_COPY_LOCALIZATIONS) SPARKLE_BUILD_LEGACY_SUUPDATER=$(SPARKLE_BUILD_LEGACY_SUUPDATER) SPARKLE_BUILD_PACKAGE_SUPPORT=$(SPARKLE_BUILD_PACKAGE_SUPPORT) SPARKLE_BUILD_LEGACY_DELTA_SUPPORT=$(SPARKLE_BUILD_LEGACY_DELTA_SUPPORT) SPARKLE_BUILD_BZIP2_DELTA_SUPPORT=$(SPARKLE_BUILD_BZIP2_DELTA_SUPPORT) SPARKLE_BUILD_LEGACY_DSA_SUPPORT=$(SPARKLE_BUILD_LEGACY_DSA_SUPPORT) GENERATE_APPCAST_BUILD_LEGACY_DSA_SUPPORT=$(GENERATE_APPCAST_BUILD_LEGACY_DSA_SUPPORT) SPARKLE_BUNDLE_IDENTIFIER=\"$(SPARKLE_BUNDLE_IDENTIFIER)\" CURRENT_PROJECT_VERSION=\"$(CURRENT_PROJECT_VERSION)\" MARKETING_VERSION=\"$(MARKETING_VERSION)\" SPARKLE_RELAUNCH_TOOL_NAME=\"$(SPARKLE_RELAUNCH_TOOL_NAME)\" SPARKLE_INSTALLER_PROGRESS_TOOL_NAME=\"$(SPARKLE_INSTALLER_PROGRESS_TOOL_NAME)\" SPARKLE_INSTALLER_PROGRESS_TOOL_BUNDLE_ID=\"$(SPARKLE_INSTALLER_PROGRESS_TOOL_BUNDLE_ID)\" SPARKLE_ICON_NAME=\"$(SPARKLE_ICON_NAME)\" INSTALLER_LAUNCHER_NAME=\"${INSTALLER_LAUNCHER_NAME}\" INSTALLER_LAUNCHER_BUNDLE_ID=\"${INSTALLER_LAUNCHER_BUNDLE_ID}\" INSTALLER_LAUNCHER_XPC_SERVICE_EMBEDDED=$(SPARKLE_EMBED_INSTALLER_LAUNCHER_XPC_SERVICE) INSTALLER_CONNECTION_NAME=\"${INSTALLER_CONNECTION_NAME}\" INSTALLER_CONNECTION_BUNDLE_ID=\"${INSTALLER_CONNECTION_BUNDLE_ID}\" INSTALLER_CONNECTION_XPC_SERVICE_EMBEDDED=$(SPARKLE_EMBED_INSTALLER_CONNECTION_XPC_SERVICE) INSTALLER_STATUS_NAME=\"${INSTALLER_STATUS_NAME}\" INSTALLER_STATUS_BUNDLE_ID=\"${INSTALLER_STATUS_BUNDLE_ID}\" INSTALLER_STATUS_XPC_SERVICE_EMBEDDED=$(SPARKLE_EMBED_INSTALLER_STATUS_XPC_SERVICE) DOWNLOADER_NAME=\"${DOWNLOADER_NAME}\" DOWNLOADER_BUNDLE_ID=\"${DOWNLOADER_BUNDLE_ID}\" DOWNLOADER_XPC_SERVICE_EMBEDDED=$(SPARKLE_EMBED_DOWNLOADER_XPC_SERVICE)
|
||||
|
||||
CODE_SIGN_IDENTITY = -
|
||||
SDKROOT = macosx
|
||||
@@ -114,8 +163,8 @@ GCC_WARN_UNUSED_LABEL = YES
|
||||
GCC_WARN_UNUSED_PARAMETER = YES
|
||||
GCC_WARN_UNUSED_VARIABLE = YES
|
||||
|
||||
// These should be removed once the conversion to ARC is complete
|
||||
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 -Wno-gnu-zero-variadic-macro-arguments -Wno-format-non-iso -Wno-direct-ivar-access $(WARNING_CFLAGS_EXTRA)
|
||||
WARNING_CFLAGS = -Wall -Weverything -Wno-unused-macros -Wno-gnu-statement-expression -Wno-auto-import -Wno-gnu-zero-variadic-macro-arguments -Wno-format-non-iso -Wno-direct-ivar-access -Wno-declaration-after-statement -Wno-gnu-conditional-omitted-operand -Wno-switch-default -Wno-missing-include-dirs -Werror=undef
|
||||
|
||||
// Prevents spurious warnings based on dependency scan considering Sparkle itself a dependency
|
||||
DIAGNOSE_MISSING_TARGET_DEPENDENCIES = NO
|
||||
@@ -1,6 +1,7 @@
|
||||
#include "ConfigCommonDebug.xcconfig"
|
||||
|
||||
GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS_COMMON)
|
||||
OTHER_SWIFT_FLAGS = $(OTHER_SWIFT_FLAGS_COMMON)
|
||||
|
||||
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
|
||||
CLANG_WARN_COMMA = YES;
|
||||
|
||||
@@ -13,5 +13,6 @@ DEBUG_INFORMATION_FORMAT = dwarf
|
||||
ENABLE_TESTABILITY = YES
|
||||
GCC_GENERATE_DEBUGGING_SYMBOLS = YES
|
||||
GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS_COMMON) DEBUG=1
|
||||
OTHER_SWIFT_FLAGS = $(OTHER_SWIFT_FLAGS_COMMON)
|
||||
ONLY_ACTIVE_ARCH = YES
|
||||
COPY_PHASE_STRIP = NO
|
||||
@@ -12,7 +12,9 @@ GCC_OPTIMIZATION_LEVEL = s
|
||||
DEBUG_INFORMATION_FORMAT = dwarf-with-dsym
|
||||
GCC_GENERATE_DEBUGGING_SYMBOLS = YES
|
||||
GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS_COMMON) DEBUG=0
|
||||
OTHER_SWIFT_FLAGS = $(OTHER_SWIFT_FLAGS_COMMON)
|
||||
DEAD_CODE_STRIPPING = YES
|
||||
GCC_TREAT_WARNINGS_AS_ERRORS = NO
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES
|
||||
COPY_PHASE_STRIP = NO
|
||||
DEPLOYMENT_POSTPROCESSING = YES
|
||||
@@ -4,5 +4,6 @@ INFOPLIST_FILE = Downloader/Info.plist
|
||||
WRAPPER_EXTENSION = xpc
|
||||
PRODUCT_BUNDLE_IDENTIFIER = ${DOWNLOADER_BUNDLE_ID}
|
||||
PRODUCT_NAME = ${DOWNLOADER_NAME}
|
||||
CODE_SIGN_ENTITLEMENTS = Downloader/${DOWNLOADER_BUNDLE_ID}.entitlements
|
||||
GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS) BUILDING_SPARKLE_DOWNLOADER_SERVICE=1
|
||||
CODE_SIGN_ENTITLEMENTS = $(DOWNLOADER_SANDBOXED_ENTITLEMENTS)
|
||||
GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS) BUILDING_SPARKLE_SOURCES_EXTERNALLY=1
|
||||
CLANG_MODULES_AUTOLINK = NO
|
||||
@@ -18,8 +18,12 @@ GCC_PREPROCESSOR_DEFINITIONS = $(inherited) BUILDING_SPARKLE=1
|
||||
SKIP_INSTALL = YES
|
||||
DEFINES_MODULE = YES
|
||||
PRODUCT_BUNDLE_IDENTIFIER = ${SPARKLE_BUNDLE_IDENTIFIER}
|
||||
STRINGS_FILE_OUTPUT_ENCODING = binary
|
||||
|
||||
// As long as we don't ourselves depend upon any Frameworks that are incompatible
|
||||
// with Application Extensions, then we should allow frameworks that require
|
||||
// compatibility to be able to link with us.
|
||||
APPLICATION_EXTENSION_API_ONLY = YES
|
||||
|
||||
ENABLE_MODULE_VERIFIER = YES
|
||||
MODULEMAP_PRIVATE_FILE = Sparkle/Sparkle.private.modulemap
|
||||
@@ -0,0 +1,4 @@
|
||||
#include "ConfigFramework.xcconfig"
|
||||
|
||||
// Strip all non-global symbols (including debug symbols)
|
||||
STRIP_STYLE = non-global
|
||||
@@ -4,3 +4,5 @@ INFOPLIST_FILE = InstallerConnection/Info.plist
|
||||
WRAPPER_EXTENSION = xpc
|
||||
PRODUCT_BUNDLE_IDENTIFIER = ${INSTALLER_CONNECTION_BUNDLE_ID}
|
||||
PRODUCT_NAME = ${INSTALLER_CONNECTION_NAME}
|
||||
GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS) BUILDING_SPARKLE_SOURCES_EXTERNALLY=1
|
||||
CLANG_MODULES_AUTOLINK = NO
|
||||
@@ -4,3 +4,5 @@ INFOPLIST_FILE = InstallerLauncher/Info.plist
|
||||
WRAPPER_EXTENSION = xpc
|
||||
PRODUCT_BUNDLE_IDENTIFIER = ${INSTALLER_LAUNCHER_BUNDLE_ID}
|
||||
PRODUCT_NAME = ${INSTALLER_LAUNCHER_NAME}
|
||||
GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS) BUILDING_SPARKLE_SOURCES_EXTERNALLY=1
|
||||
CLANG_MODULES_AUTOLINK = NO
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
INFOPLIST_FILE = Sparkle/InstallerProgress/InstallerProgress-Info.plist
|
||||
PRODUCT_NAME = $(SPARKLE_INSTALLER_PROGRESS_TOOL_NAME)
|
||||
GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS) BUILDING_SPARKLE=0
|
||||
PRODUCT_BUNDLE_IDENTIFIER = $(SPARKLE_INSTALLER_PROGRESS_TOOL_BUNDLE_ID)
|
||||
GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS) BUILDING_SPARKLE=0 BUILDING_SPARKLE_SOURCES_EXTERNALLY=1
|
||||
SKIP_INSTALL = YES
|
||||
CLANG_ENABLE_MODULES = NO
|
||||
@@ -4,3 +4,5 @@ INFOPLIST_FILE = InstallerStatus/Info.plist
|
||||
WRAPPER_EXTENSION = xpc
|
||||
PRODUCT_BUNDLE_IDENTIFIER = ${INSTALLER_STATUS_BUNDLE_ID}
|
||||
PRODUCT_NAME = ${INSTALLER_STATUS_NAME}
|
||||
GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS) BUILDING_SPARKLE=0 BUILDING_SPARKLE_SOURCES_EXTERNALLY=1
|
||||
CLANG_MODULES_AUTOLINK = NO
|
||||
@@ -3,3 +3,4 @@
|
||||
PRODUCT_NAME = $(SPARKLE_RELAUNCH_TOOL_NAME)
|
||||
SKIP_INSTALL = YES
|
||||
CLANG_ENABLE_MODULES = NO
|
||||
GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS) BUILDING_SPARKLE_SOURCES_EXTERNALLY=1
|
||||
@@ -11,4 +11,4 @@ FRAMEWORK_SEARCH_PATHS = $(inherited) $(DEVELOPER_FRAMEWORKS_DIR)
|
||||
LD_RUNPATH_SEARCH_PATHS = @loader_path/../Frameworks
|
||||
CLANG_ENABLE_MODULES = YES
|
||||
SWIFT_OBJC_BRIDGING_HEADER = Tests/Sparkle Unit Tests-Bridging-Header.h
|
||||
GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS) BUILDING_SPARKLE_TESTS=1
|
||||
GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS) BUILDING_SPARKLE_TESTS=1 BUILDING_SPARKLE_SOURCES_EXTERNALLY=1
|
||||
@@ -5,6 +5,7 @@ set -e
|
||||
# This guards against our archives being corrupt / created incorrectly.
|
||||
function verify_code_signatures() {
|
||||
verification_directory="$1"
|
||||
check_aux_apps="$2"
|
||||
|
||||
if [[ -z "$verification_directory" ]]; then
|
||||
echo "Provided verification directory does not exist" >&2
|
||||
@@ -13,8 +14,11 @@ function verify_code_signatures() {
|
||||
|
||||
# Search the current directory for all instances of the framework to verify them (XCFrameworks can have multiple copies of a framework for different platforms).
|
||||
find "${verification_directory}" -name "Sparkle.framework" -type d -exec codesign --verify -vvv --deep {} \;
|
||||
codesign --verify -vvv --deep "${verification_directory}/sparkle.app"
|
||||
codesign --verify -vvv --deep "${verification_directory}/Sparkle Test App.app"
|
||||
|
||||
if [ "$check_aux_apps" = true ] ; then
|
||||
codesign --verify -vvv --deep "${verification_directory}/sparkle.app"
|
||||
codesign --verify -vvv --deep "${verification_directory}/Sparkle Test App.app"
|
||||
fi
|
||||
codesign --verify -vvv --deep "${verification_directory}/bin/BinaryDelta"
|
||||
codesign --verify -vvv --deep "${verification_directory}/bin/generate_appcast"
|
||||
codesign --verify -vvv --deep "${verification_directory}/bin/sign_update"
|
||||
@@ -30,27 +34,17 @@ if [ "$ACTION" = "" ] ; then
|
||||
|
||||
mkdir -p "$CONFIGURATION_BUILD_DIR/staging"
|
||||
mkdir -p "$CONFIGURATION_BUILD_DIR/staging-spm"
|
||||
cp "$SRCROOT/CHANGELOG" "$SRCROOT/LICENSE" "$SRCROOT/INSTALL" "$SRCROOT/Resources/SampleAppcast.xml" "$CONFIGURATION_BUILD_DIR/staging"
|
||||
cp "$SRCROOT/CHANGELOG" "$SRCROOT/LICENSE" "$SRCROOT/INSTALL" "$SRCROOT/Resources/SampleAppcast.xml" "$CONFIGURATION_BUILD_DIR/staging-spm"
|
||||
cp -R "$SRCROOT/bin" "$CONFIGURATION_BUILD_DIR/staging"
|
||||
cp "$PROJECT_DIR/CHANGELOG" "$PROJECT_DIR/LICENSE" "$PROJECT_DIR/INSTALL" "$PROJECT_DIR/Resources/SampleAppcast.xml" "$CONFIGURATION_BUILD_DIR/staging"
|
||||
cp "$PROJECT_DIR/CHANGELOG" "$PROJECT_DIR/LICENSE" "$PROJECT_DIR/INSTALL" "$PROJECT_DIR/Resources/SampleAppcast.xml" "$CONFIGURATION_BUILD_DIR/staging-spm"
|
||||
cp -R "$PROJECT_DIR/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 "$CONFIGURATION_BUILD_DIR/generate_keys" "$CONFIGURATION_BUILD_DIR/staging/bin"
|
||||
cp "$CONFIGURATION_BUILD_DIR/sign_update" "$CONFIGURATION_BUILD_DIR/staging/bin"
|
||||
cp -R "$CONFIGURATION_BUILD_DIR/Sparkle Test App.app" "$CONFIGURATION_BUILD_DIR/staging"
|
||||
cp -R "$CONFIGURATION_BUILD_DIR/Sparkle Test App.app" "$CONFIGURATION_BUILD_DIR/staging-spm"
|
||||
cp -R "$CONFIGURATION_BUILD_DIR/sparkle.app" "$CONFIGURATION_BUILD_DIR/staging"
|
||||
cp -R "$CONFIGURATION_BUILD_DIR/sparkle.app" "$CONFIGURATION_BUILD_DIR/staging-spm"
|
||||
cp -R "$CONFIGURATION_BUILD_DIR/Sparkle.framework" "$CONFIGURATION_BUILD_DIR/staging"
|
||||
cp -R "$CONFIGURATION_BUILD_DIR/Sparkle.xcframework" "$CONFIGURATION_BUILD_DIR/staging-spm"
|
||||
|
||||
if [[ "$SPARKLE_EMBED_DOWNLOADER_XPC_SERVICE" -eq 1 ]]; then
|
||||
mkdir -p "$CONFIGURATION_BUILD_DIR/staging/Entitlements"
|
||||
mkdir -p "$CONFIGURATION_BUILD_DIR/staging-spm/Entitlements"
|
||||
|
||||
cp -R "$SRCROOT/Downloader/org.sparkle-project.Downloader.entitlements" "$CONFIGURATION_BUILD_DIR/staging/Entitlements/$DOWNLOADER_NAME.entitlements"
|
||||
cp -R "$SRCROOT/Downloader/org.sparkle-project.Downloader.entitlements" "$CONFIGURATION_BUILD_DIR/staging-spm/Entitlements/$DOWNLOADER_NAME.entitlements"
|
||||
fi
|
||||
|
||||
mkdir -p "$CONFIGURATION_BUILD_DIR/staging/Symbols"
|
||||
|
||||
@@ -58,94 +52,95 @@ 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/Symbols"
|
||||
|
||||
cp -R "$CONFIGURATION_BUILD_DIR/generate_appcast.dSYM" "$CONFIGURATION_BUILD_DIR/staging/Symbols"
|
||||
|
||||
cp -R "$CONFIGURATION_BUILD_DIR/generate_keys.dSYM" "$CONFIGURATION_BUILD_DIR/staging/Symbols"
|
||||
|
||||
cp -R "$CONFIGURATION_BUILD_DIR/sign_update.dSYM" "$CONFIGURATION_BUILD_DIR/staging/Symbols"
|
||||
|
||||
cp -R "$CONFIGURATION_BUILD_DIR/Sparkle Test App.app.dSYM" "$CONFIGURATION_BUILD_DIR/staging/Symbols"
|
||||
|
||||
cp -R "$CONFIGURATION_BUILD_DIR/sparkle.app.dSYM" "$CONFIGURATION_BUILD_DIR/staging/Symbols"
|
||||
|
||||
cp -R "$CONFIGURATION_BUILD_DIR/Sparkle.framework.dSYM" "$CONFIGURATION_BUILD_DIR/staging/Symbols"
|
||||
|
||||
cp -R "$CONFIGURATION_BUILD_DIR/Autoupdate.dSYM" "$CONFIGURATION_BUILD_DIR/staging/Symbols"
|
||||
|
||||
cp -R "$CONFIGURATION_BUILD_DIR/Updater.app.dSYM" "$CONFIGURATION_BUILD_DIR/staging/Symbols"
|
||||
|
||||
cp -R "$CONFIGURATION_BUILD_DIR/${INSTALLER_LAUNCHER_NAME}.xpc.dSYM" "$CONFIGURATION_BUILD_DIR/staging/Symbols"
|
||||
|
||||
cp -R "$CONFIGURATION_BUILD_DIR/${DOWNLOADER_NAME}.xpc.dSYM" "$CONFIGURATION_BUILD_DIR/staging/Symbols"
|
||||
fi
|
||||
cp -R "$CONFIGURATION_BUILD_DIR/staging/bin" "$CONFIGURATION_BUILD_DIR/staging-spm"
|
||||
cp -R "$CONFIGURATION_BUILD_DIR/staging/Symbols" "$CONFIGURATION_BUILD_DIR/staging-spm"
|
||||
|
||||
cd "$CONFIGURATION_BUILD_DIR/staging"
|
||||
|
||||
if [ -x "$(command -v xz)" ]; then
|
||||
XZ_EXISTS=1
|
||||
else
|
||||
XZ_EXISTS=0
|
||||
fi
|
||||
|
||||
rm -rf "/tmp/sparkle-extract"
|
||||
mkdir -p "/tmp/sparkle-extract"
|
||||
|
||||
# Sorted file list groups similar files together, which improves tar compression
|
||||
if [ "$XZ_EXISTS" -eq 1 ] ; then
|
||||
find . \! -type d | rev | sort | rev | tar cv --files-from=- | xz -9 > "../Sparkle-$MARKETING_VERSION.tar.xz"
|
||||
find . \! -type d | rev | sort | rev | tar --no-xattrs -cJvf "../Sparkle-$MARKETING_VERSION.tar.xz" --files-from=-
|
||||
|
||||
# Copy archived distribution for CI
|
||||
cp -f "../Sparkle-$MARKETING_VERSION.tar.xz" "../sparkle_dist.tar.xz"
|
||||
|
||||
# Copy archived distribution for CI
|
||||
cp -f "../Sparkle-$MARKETING_VERSION.tar.xz" "../sparkle-dist.tar.xz"
|
||||
|
||||
# Extract archive for testing binary validity
|
||||
tar -xf "../Sparkle-$MARKETING_VERSION.tar.xz" -C "/tmp/sparkle-extract"
|
||||
else
|
||||
# Fallback to bz2 compression if xz utility is not available
|
||||
find . \! -type d | rev | sort | rev | tar cjvf "../Sparkle-$MARKETING_VERSION.tar.bz2" --files-from=-
|
||||
|
||||
# Extract archive for testing binary validity
|
||||
tar -xf "../Sparkle-$MARKETING_VERSION.tar.bz2" -C "/tmp/sparkle-extract"
|
||||
fi
|
||||
# Extract archive for testing binary validity
|
||||
tar -xf "../Sparkle-$MARKETING_VERSION.tar.xz" -C "/tmp/sparkle-extract"
|
||||
|
||||
# Test code signing validity of the extracted products
|
||||
# This guards against our archives being corrupt / created incorrectly
|
||||
verify_code_signatures "/tmp/sparkle-extract"
|
||||
verify_code_signatures "/tmp/sparkle-extract" true
|
||||
|
||||
rm -rf "/tmp/sparkle-extract"
|
||||
rm -rf "$CONFIGURATION_BUILD_DIR/staging"
|
||||
|
||||
# Generate zip containing the xcframework for SPM
|
||||
rm -rf "/tmp/sparkle-spm-extract"
|
||||
mkdir -p "/tmp/sparkle-spm-extract"
|
||||
cd "$CONFIGURATION_BUILD_DIR/staging-spm"
|
||||
# rm -rf "$CONFIGURATION_BUILD_DIR/Sparkle.xcarchive"
|
||||
ditto -c -k --zlibCompressionLevel 9 --rsrc . "../Sparkle-for-Swift-Package-Manager.zip"
|
||||
|
||||
# Test code signing validity of the extracted Swift package
|
||||
# This guards against our archives being corrupt / created incorrectly
|
||||
ditto -x -k "../Sparkle-for-Swift-Package-Manager.zip" "/tmp/sparkle-spm-extract"
|
||||
verify_code_signatures "/tmp/sparkle-spm-extract"
|
||||
|
||||
rm -rf "/tmp/sparkle-spm-extract"
|
||||
rm -rf "$CONFIGURATION_BUILD_DIR/staging-spm"
|
||||
|
||||
# Get latest git tag
|
||||
cd "$SRCROOT"
|
||||
latest_git_tag=$(git describe --tags --abbrev=0)
|
||||
cd "$PROJECT_DIR"
|
||||
latest_git_tag=$( git describe --tags --abbrev=0 || true )
|
||||
|
||||
# Check semantic versioning
|
||||
if [[ $latest_git_tag =~ ^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-((0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*))*))?(\\+([0-9a-zA-Z-]+(\.[0-9a-zA-Z-]+)*))?$ ]]; then
|
||||
echo "Tag $latest_git_tag follows semantic versioning"
|
||||
else
|
||||
echo "ERROR: Tag $latest_git_tag does not follow semantic versioning! SPM will not be able to resolve the repository" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [ -n "$latest_git_tag" ] ; then
|
||||
# Generate zip containing the xcframework for SPM
|
||||
rm -rf "/tmp/sparkle-spm-extract"
|
||||
mkdir -p "/tmp/sparkle-spm-extract"
|
||||
cd "$CONFIGURATION_BUILD_DIR/staging-spm"
|
||||
# rm -rf "$CONFIGURATION_BUILD_DIR/Sparkle.xcarchive"
|
||||
ditto -c -k --zlibCompressionLevel 9 --rsrc . "../Sparkle-for-Swift-Package-Manager.zip"
|
||||
|
||||
# Generate new Package manifest, podspec, and carthage files
|
||||
cd "$CONFIGURATION_BUILD_DIR"
|
||||
cp "$SRCROOT/Package.swift" "$CONFIGURATION_BUILD_DIR"
|
||||
cp "$SRCROOT/Sparkle.podspec" "$CONFIGURATION_BUILD_DIR"
|
||||
cp "$SRCROOT/Carthage-dev.json" "$CONFIGURATION_BUILD_DIR"
|
||||
# Test code signing validity of the extracted Swift package
|
||||
# This guards against our archives being corrupt / created incorrectly
|
||||
ditto -x -k "../Sparkle-for-Swift-Package-Manager.zip" "/tmp/sparkle-spm-extract"
|
||||
verify_code_signatures "/tmp/sparkle-spm-extract" false
|
||||
|
||||
rm -rf "/tmp/sparkle-spm-extract"
|
||||
rm -rf "$CONFIGURATION_BUILD_DIR/staging-spm"
|
||||
|
||||
cd "$PROJECT_DIR"
|
||||
|
||||
if [ "$XCODE_VERSION_MAJOR" -ge "1200" ]; then
|
||||
# Check semantic versioning
|
||||
if [[ $latest_git_tag =~ ^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-((0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*))*))?(\\+([0-9a-zA-Z-]+(\.[0-9a-zA-Z-]+)*))?$ ]]; then
|
||||
echo "Tag $latest_git_tag follows semantic versioning"
|
||||
else
|
||||
echo "ERROR: Tag $latest_git_tag does not follow semantic versioning! SPM will not be able to resolve the repository" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Generate new Package manifest, podspec, and carthage files
|
||||
cd "$CONFIGURATION_BUILD_DIR"
|
||||
cp "$PROJECT_DIR/Package.swift" "$CONFIGURATION_BUILD_DIR"
|
||||
cp "$PROJECT_DIR/Sparkle.podspec" "$CONFIGURATION_BUILD_DIR"
|
||||
cp "$PROJECT_DIR/Carthage-dev.json" "$CONFIGURATION_BUILD_DIR"
|
||||
fi
|
||||
|
||||
if [ -z "$latest_git_tag" ] ; then
|
||||
echo "warning: No git repository found so skipping updating package management files"
|
||||
elif [ "$XCODE_VERSION_MAJOR" -ge "1200" ]; then
|
||||
# is equivalent to shasum -a 256 FILE
|
||||
spm_checksum=$(swift package compute-checksum "Sparkle-for-Swift-Package-Manager.zip")
|
||||
rm -rf ".build"
|
||||
sed -E -i '' -e "/let tag/ s/\".+\"/\"$latest_git_tag\"/" -e "/let version/ s/\".+\"/\"$MARKETING_VERSION\"/" -e "/let checksum/ s/[[:xdigit:]]{64}/$spm_checksum/" "Package.swift"
|
||||
cp "Package.swift" "$SRCROOT"
|
||||
cp "Package.swift" "$PROJECT_DIR"
|
||||
echo "Package.swift updated with the following values:"
|
||||
echo "Version: $MARKETING_VERSION"
|
||||
echo "Tag: $latest_git_tag"
|
||||
@@ -153,19 +148,15 @@ if [ "$ACTION" = "" ] ; then
|
||||
|
||||
sed -E -i '' -e "/s\.version.+=/ s/\".+\"/\"$MARKETING_VERSION\"/" "Sparkle.podspec"
|
||||
|
||||
"$SRCROOT/Configurations/update-carthage.py" "Carthage-dev.json" "$MARKETING_VERSION"
|
||||
cp "Sparkle.podspec" "$SRCROOT"
|
||||
"$PROJECT_DIR/Configurations/update-carthage.py" "Carthage-dev.json" "$MARKETING_VERSION"
|
||||
cp "Sparkle.podspec" "$PROJECT_DIR"
|
||||
# Note the Carthage-dev.json file will finally be copied to the website repo in Carthage/Sparkle.json in the end
|
||||
cp "Carthage-dev.json" "$SRCROOT"
|
||||
cp "Carthage-dev.json" "$PROJECT_DIR"
|
||||
echo "Sparkle.podspec and Carthage-dev.json updated with following values:"
|
||||
echo "Version: $MARKETING_VERSION"
|
||||
else
|
||||
echo "warning: Xcode version $XCODE_VERSION_ACTUAL does not support computing checksums for Swift Packages. Please update the Package manifest manually."
|
||||
fi
|
||||
|
||||
if [ "$XZ_EXISTS" -ne 1 ] ; then
|
||||
echo "WARNING: xz compression is used for official releases but bz2 is being used instead because xz tool is not installed on your system."
|
||||
fi
|
||||
|
||||
rm -rf "$CONFIGURATION_BUILD_DIR/staging-spm"
|
||||
fi
|
||||
Executable
+15
@@ -0,0 +1,15 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Deleting old products
|
||||
rm -rd "$BUILT_PRODUCTS_DIR/Sparkle.xcarchive"
|
||||
rm -rd "$BUILT_PRODUCTS_DIR/Sparkle.xcframework"
|
||||
|
||||
xcodebuild archive -scheme Sparkle -archivePath "$BUILT_PRODUCTS_DIR/Sparkle.xcarchive" BUILD_LIBRARY_FOR_DISTRIBUTION=YES SKIP_INSTALL=NO
|
||||
|
||||
if [ $XCODE_VERSION_MAJOR -ge "1200" ]; then
|
||||
xcodebuild -create-xcframework -framework "$BUILT_PRODUCTS_DIR/Sparkle.xcarchive/Products/Library/Frameworks/Sparkle.framework" -debug-symbols "$BUILT_PRODUCTS_DIR/Sparkle.xcarchive/dSYMs/Sparkle.framework.dSYM" -debug-symbols "$BUILT_PRODUCTS_DIR/Sparkle.xcarchive/dSYMs/Autoupdate.dSYM" -debug-symbols "$BUILT_PRODUCTS_DIR/Sparkle.xcarchive/dSYMs/Updater.app.dSYM" -debug-symbols "$BUILT_PRODUCTS_DIR/Sparkle.xcarchive/dSYMs/$INSTALLER_LAUNCHER_NAME.xpc.dSYM" -debug-symbols "$BUILT_PRODUCTS_DIR/Sparkle.xcarchive/dSYMs/$DOWNLOADER_NAME.xpc.dSYM" -output "$BUILT_PRODUCTS_DIR/Sparkle.xcframework"
|
||||
else
|
||||
echo "warning: Your Xcode version does not support bundling dSYMs in XCFrameworks directly. You should copy them manually into the XCFramework."
|
||||
echo "note: cp '$BUILT_PRODUCTS_DIR/Sparkle.xcarchive/dSYMs/Sparkle.framework.dSYM' '$BUILT_PRODUCTS_DIR/Sparkle.xcframework/your_architecture/dSYMs'"
|
||||
xcodebuild -create-xcframework -framework "$BUILT_PRODUCTS_DIR/Sparkle.xcarchive/Products/Library/Frameworks/Sparkle.framework" -output "$BUILT_PRODUCTS_DIR/Sparkle.xcframework"
|
||||
fi
|
||||
@@ -2,7 +2,11 @@
|
||||
set -e
|
||||
|
||||
# Convenience script to automatically commit Package.swift after updating the checksum and move the latest tag
|
||||
latest_git_tag=$(git describe --tags --abbrev=0) # gets the latest tag name
|
||||
latest_git_tag=$( git describe --tags --abbrev=0 || true ) # gets the latest tag name
|
||||
if [ -z "$latest_git_tag" ] ; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
commits_since_tag=$(git rev-list ${latest_git_tag}.. --count)
|
||||
|
||||
function move_tag() {
|
||||
|
||||
@@ -5,7 +5,7 @@ if ! which -s git ; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [ -z "$SRCROOT" ] || \
|
||||
if [ -z "$PROJECT_DIR" ] || \
|
||||
[ -z "$BUILT_PRODUCTS_DIR" ] || \
|
||||
[ -z "$INFOPLIST_PATH" ] || \
|
||||
[ -z "$MARKETING_VERSION" ]; then
|
||||
@@ -16,7 +16,7 @@ fi
|
||||
version="$MARKETING_VERSION"
|
||||
|
||||
# Get version in format 1.x.x-commits-hash
|
||||
gitversion=$( cd "$SRCROOT"; git describe --tags --match '[12].*' || true )
|
||||
gitversion=$( cd "$PROJECT_DIR"; git describe --tags --match '[12].*' || true )
|
||||
if [ -z "$gitversion" ] ; then
|
||||
echo "$0: Can't find a Git hash!" 1>&2
|
||||
exit 0
|
||||
|
||||
Executable
+58
@@ -0,0 +1,58 @@
|
||||
#!/bin/sh
|
||||
|
||||
FRAMEWORK_PATH="${TARGET_BUILD_DIR}"/"${FULL_PRODUCT_NAME}"
|
||||
|
||||
# Remove any unused XPC Services
|
||||
|
||||
removedservices=0
|
||||
|
||||
if [[ "$SPARKLE_EMBED_INSTALLER_LAUNCHER_XPC_SERVICE" -eq 0 ]]; then
|
||||
rm -rf "${FRAMEWORK_PATH}"/"Versions/"${FRAMEWORK_VERSION}"/XPCServices"/"${INSTALLER_LAUNCHER_NAME}.xpc"
|
||||
removedservices=$((removedservices+1))
|
||||
fi
|
||||
|
||||
if [[ "$SPARKLE_EMBED_DOWNLOADER_XPC_SERVICE" -eq 0 ]]; then
|
||||
rm -rf "${FRAMEWORK_PATH}"/"Versions/"${FRAMEWORK_VERSION}"/XPCServices"/"${DOWNLOADER_NAME}.xpc"
|
||||
removedservices=$((removedservices+1))
|
||||
fi
|
||||
|
||||
if [[ "$SPARKLE_EMBED_INSTALLER_STATUS_XPC_SERVICE" -eq 0 ]]; then
|
||||
rm -rf "${FRAMEWORK_PATH}"/"Versions/"${FRAMEWORK_VERSION}"/XPCServices"/"${INSTALLER_STATUS_NAME}.xpc"
|
||||
removedservices=$((removedservices+1))
|
||||
fi
|
||||
|
||||
if [[ "$SPARKLE_EMBED_INSTALLER_CONNECTION_XPC_SERVICE" -eq 0 ]]; then
|
||||
rm -rf "${FRAMEWORK_PATH}"/"Versions/"${FRAMEWORK_VERSION}"/XPCServices"/"${INSTALLER_CONNECTION_NAME}.xpc"
|
||||
removedservices=$((removedservices+1))
|
||||
fi
|
||||
|
||||
if [[ "$removedservices" -eq 4 ]]; then
|
||||
rm -rf "${FRAMEWORK_PATH}"/"Versions/"${FRAMEWORK_VERSION}"/XPCServices"
|
||||
rm -rf "${FRAMEWORK_PATH}"/"XPCServices"
|
||||
fi
|
||||
|
||||
# Remove any unused nibs
|
||||
|
||||
if [[ "$SPARKLE_BUILD_UI_BITS" -eq 0 ]]; then
|
||||
rm -rf "${FRAMEWORK_PATH}"/"Versions/"${FRAMEWORK_VERSION}"/Resources"/"SUStatus.nib"
|
||||
rm -rf "${FRAMEWORK_PATH}"/"Versions/"${FRAMEWORK_VERSION}"/Resources"/"Base.lproj/SUUpdateAlert.nib"
|
||||
rm -rf "${FRAMEWORK_PATH}"/"Versions/"${FRAMEWORK_VERSION}"/Resources"/"Base.lproj/SUUpdatePermissionPrompt.nib"
|
||||
rm -rf "${FRAMEWORK_PATH}"/"Versions/"${FRAMEWORK_VERSION}"/Resources"/"ReleaseNotesColorStyle.css"
|
||||
fi
|
||||
|
||||
# Remove localization files if requested
|
||||
|
||||
if [[ "$SPARKLE_COPY_LOCALIZATIONS" -eq 0 ]]; then
|
||||
for dir in "${FRAMEWORK_PATH}"/"Versions/"${FRAMEWORK_VERSION}"/Resources"/*; do
|
||||
base=$(basename "$dir")
|
||||
if [[ "$base" =~ .*".lproj" ]]; then
|
||||
if [[ "$base" = "Base.lproj" ]]; then
|
||||
rm -rf "$dir/Sparkle.strings"
|
||||
# Remove Base.lproj if it's empty and the nibs have been stripped out already
|
||||
rmdir "$dir"
|
||||
else
|
||||
rm -rf "$dir"
|
||||
fi
|
||||
fi
|
||||
done
|
||||
fi
|
||||
@@ -1,30 +0,0 @@
|
||||
#!/bin/sh
|
||||
|
||||
FRAMEWORK_PATH="${TARGET_BUILD_DIR}"/"${FULL_PRODUCT_NAME}"
|
||||
|
||||
removedservices=0
|
||||
|
||||
if [[ "$SPARKLE_EMBED_INSTALLER_LAUNCHER_XPC_SERVICE" -eq 0 ]]; then
|
||||
rm -rf "${FRAMEWORK_PATH}"/"Versions/"${FRAMEWORK_VERSION}"/XPCServices"/"${INSTALLER_LAUNCHER_NAME}.xpc"
|
||||
removedservices=$((removedservices+1))
|
||||
fi
|
||||
|
||||
if [[ "$SPARKLE_EMBED_DOWNLOADER_XPC_SERVICE" -eq 0 ]]; then
|
||||
rm -rf "${FRAMEWORK_PATH}"/"Versions/"${FRAMEWORK_VERSION}"/XPCServices"/"${DOWNLOADER_NAME}.xpc"
|
||||
removedservices=$((removedservices+1))
|
||||
fi
|
||||
|
||||
if [[ "$SPARKLE_EMBED_INSTALLER_STATUS_XPC_SERVICE" -eq 0 ]]; then
|
||||
rm -rf "${FRAMEWORK_PATH}"/"Versions/"${FRAMEWORK_VERSION}"/XPCServices"/"${INSTALLER_STATUS_NAME}.xpc"
|
||||
removedservices=$((removedservices+1))
|
||||
fi
|
||||
|
||||
if [[ "$SPARKLE_EMBED_INSTALLER_CONNECTION_XPC_SERVICE" -eq 0 ]]; then
|
||||
rm -rf "${FRAMEWORK_PATH}"/"Versions/"${FRAMEWORK_VERSION}"/XPCServices"/"${INSTALLER_CONNECTION_NAME}.xpc"
|
||||
removedservices=$((removedservices+1))
|
||||
fi
|
||||
|
||||
if [[ "$removedservices" -eq 4 ]]; then
|
||||
rm -rf "${FRAMEWORK_PATH}"/"Versions/"${FRAMEWORK_VERSION}"/XPCServices"
|
||||
rm -rf "${FRAMEWORK_PATH}"/"XPCServices"
|
||||
fi
|
||||
@@ -10,15 +10,15 @@ The protocols used in XPC services must also not adopt other protocols (i.e, one
|
||||
|
||||
Singletons and other global mutable variables have been either removed entirely or completely avoided with an exception to backwards compatibility. They have no place in a well architectured framework.
|
||||
|
||||
`SPUUpdater` doesn't maintain singleton instances and can now be properly deconstructed. Note because a caller is not expected to explicitly invalidate an updater, this means that the updater needs to avoid geting into a retain cycle. Intermediate clasess were created for the update cycle and schedule timer to avoid just this.
|
||||
`SPUUpdater` doesn't maintain singleton instances and can now be properly deconstructed. Note because a caller is not expected to explicitly invalidate an updater, this means that the updater needs to avoid getting into a retain cycle. Intermediate clasess were created for the update cycle and schedule timer to avoid just this.
|
||||
|
||||
One may argue that we shouldn't allow multiple live updaters running at the same bundle simutaneously, but I disagree and I think that is missing the point. It also does not account for updaters running external to the process. For example, it may be perfectly reasonable to start an update from `sparkle-cli` that defers the installation until quit, and have the application that is being updated be able to resume that installation and relaunch immediately.
|
||||
One may argue that we shouldn't allow multiple live updaters running at the same bundle simultaneously, but I disagree and I think that is missing the point. It also does not account for updaters running external to the process. For example, it may be perfectly reasonable to start an update from `sparkle-cli` that defers the installation until quit, and have the application that is being updated be able to resume that installation and relaunch immediately.
|
||||
|
||||
The original `SUUpdater` may have also been created to assist plug-ins and other non-app bundles. My advice there is in order to be truely safe, you must not inject a framework like Sparkle into the host application anyway. An external tool that is bundled like `sparkle-cli` may be more appropriate to use here.
|
||||
The original `SUUpdater` may have also been created to assist plug-ins and other non-app bundles. My advice there is in order to be truly safe, you must not inject a framework like Sparkle into the host application anyway. An external tool that is bundled like `sparkle-cli` may be more appropriate to use here.
|
||||
|
||||
## Extensibility
|
||||
|
||||
Sparkle 2.0 does not support subclassing classes internal (not exported) to Sparkle anymore. Doing so would be almost impossible to maintain into the future. Subclassing in general has been banned. Composition is prefered everywhere, even amongst the internal update drivers which were rewritten to follow a protocol oriented approach. The reason why composition is preferred is because it's easier to follow the flow of logic.
|
||||
Sparkle 2.0 does not support subclassing classes internal (not exported) to Sparkle anymore. Doing so would be almost impossible to maintain into the future. Subclassing in general has been banned. Composition is preferred everywhere, even amongst the internal update drivers which were rewritten to follow a protocol oriented approach. The reason why composition is preferred is because it's easier to follow the flow of logic.
|
||||
|
||||
I hope the user driver API gives enough extensibility without someone wanting to create another fork.
|
||||
|
||||
@@ -32,10 +32,16 @@ You may notice that the delegate and user driver are not accessible as propertie
|
||||
|
||||
## Decoupling
|
||||
|
||||
Two software components should not directly know about each other. Preferrably they wouldn't know about each other at all, but if they must, they can use the delegation pattern with a declared protocol.
|
||||
Two software components should not directly know about each other. Preferably they wouldn't know about each other at all, but if they must, they can use the delegation pattern with a declared protocol.
|
||||
|
||||
See `Documentation/graph-of-sparkle.png` for a graph of how the code looks like currently. This was generated via [objc_dep](https://github.com/nst/objc_dep) (great tool). Note that there are no red edges which would mean that two nodes know of each other.
|
||||
|
||||
## Attributes
|
||||
## Attributes & Code Size
|
||||
|
||||
`nonatomic` should really be used wherever possible with regards to obj-c properties (`atomic` is a bad default). `readonly` should be used wherever possible as well, which also implies that only ivar access should be used in initializers. `NS_ASSUME_NONNULL_BEGIN` and `NS_ASSUME_NONNULL_END` should be used around new headers whenever possible. AppKit prevention guards should be used for any non-UI class whenever possible.
|
||||
Instance variables and instance variable access should be used for private members (declared in `@implementation` block) whenever possible over properties. Preferring instance variables over properties for internal usage can significantly reduce code size. Instance variables should also be ordered by having the larger sized data members declared first.
|
||||
|
||||
`SPU_OBJC_DIRECT_MEMBERS` should be used for any internal class in Sparkle and `SPU_OBJC_DIRECT` should be used for any other internal methods to Sparkle that doesn't need to utilize the Obj-C runtime to reduce code size. Note these attributes should not be used for *any* class or method that is exported to the developer (this includes private headers / APIs we carefully decided to expose too). For internal methods and classes that are also used by our Swift tools or unit tests, we may not expose them as direct specifically when building for those targets.
|
||||
|
||||
`nonatomic` should really be used wherever possible with regards to obj-c properties (`atomic` is a bad default). `readonly` should be used wherever possible as well, which also implies that only ivar access should be used in initializers. `NS_ASSUME_NONNULL_BEGIN` and `NS_ASSUME_NONNULL_END` should be used around new headers whenever possible. AppKit prevention guards should be used for any non-UI class whenever possible.
|
||||
|
||||
Sparkle has several feature flags in ConfigCommon.xcconfig (e.g. `SPARKLE_BUILD_LEGACY_SUUPDATER`, `SPARKLE_BUILD_LEGACY_DSA_SUPPORT`, `SPARKLE_BUILD_UI_BITS`, etc). This allows disabling any combination of these features and building Sparkle with a more minimal feature set. These flags (with the exception for stripping UI bits, localizations, or XPC Services) are for disabling features that are legacy or not recommended to use for most applications. Note when altering these flags, `OTHER_SWIFT_FLAGS_COMMON` may need to be updated appropriately too.
|
||||
@@ -57,7 +57,7 @@ After extraction starts, one or more `SPUExtractedArchiveWithProgress` messages
|
||||
### Post Validation
|
||||
If the unarchiving succeeds, a `SPUValidationStarted` message is sent back to the updater, and the installer begins post validating the update.
|
||||
|
||||
If validation was already done before extraction, just the code signature is checked on the extracted bundle to make sure it's valid (if there's a code signature on the bundle). This is just a consistency check to make sure the developer didn't make a careless erorr.
|
||||
If validation was already done before extraction, just the code signature is checked on the extracted bundle to make sure it's valid (if there's a code signature on the bundle). This is just a consistency check to make sure the developer didn't make a careless error.
|
||||
|
||||
If validation fails, the installer aborts, causing the updater to abort the update as well. Otherwise, the installer sends a message `SPUInstallationStartedStage1` to the updater and begins the installation.
|
||||
|
||||
@@ -73,7 +73,7 @@ The installer figures out what kind of installer to use (regular, guided pkg, in
|
||||
|
||||
Once the type of installer is found, the first stage of installation is performed:
|
||||
|
||||
* Regular application installer 1st stage: Makes sure this update is not a downgrade.
|
||||
* Regular application installer 1st stage: Makes sure this update is not a downgrade and do all initial installation work if possible (such as clearing quarantine, changing owner/group, updating modification date, invoking GateKeeper scan). This initial work is not done if the bundle has to transfer to another volume; in this case, this work will be done in a later stage.
|
||||
* Guided Package installer 1st stage: Does nothing.
|
||||
* Interactive Package installer (deprecated) 1st stage: Makes sure /usr/bin/open utility is available.
|
||||
|
||||
@@ -92,7 +92,7 @@ For automatic based drivers, if the update is not going to be installed immediat
|
||||
|
||||
Otherwise if the updater delegate doesn't handle immediate installation for automatic based drivers (assuming still the update is not going to be installed immediately), the update driver is aborted; the installer will still wait for the target to terminate however. If the update cannot be silently installed or if the update is marked as critical from the appcast, the update procedure is actually 'resumed' as a scheduled UI based update driver immediately. The update driver can also be 'resumed' later when the user initiates for an update manually or when a long duration (I think a week) has passed by without the user terminating the application. Note automatic based drivers are unable to do a resume, so only UI based ones can.
|
||||
|
||||
If an update driver is resumed (which cannot happen if the target applicaton is already terminated by the way), then the updater first requests the installer for the appcast item data that the installer received before. The updater does this by creating a temporary distinct connection for the purpose of querying for the installation status. The connection will give up if a short timeout passes. If the updater fails to retrieve resume data, it assumes that there's no update to resume and will start back from the beginning. The updater can use this data for showing release notes, etc. Note the updater and target application don't have to live in the same process, and the updater could choose to terminate and resume later as a new process - so having the installer keep the appcast item data is nice.
|
||||
If an update driver is resumed (which cannot happen if the target application is already terminated by the way), then the updater first requests the installer for the appcast item data that the installer received before. The updater does this by creating a temporary distinct connection for the purpose of querying for the installation status. The connection will give up if a short timeout passes. If the updater fails to retrieve resume data, it assumes that there's no update to resume and will start back from the beginning. The updater can use this data for showing release notes, etc. Note the updater and target application don't have to live in the same process, and the updater could choose to terminate and resume later as a new process - so having the installer keep the appcast item data is nice.
|
||||
|
||||
Afterwards the resumed update driver then allows the user driver to decide whether to a) install the update now, b) install & relaunch the update, or to c) delay the update installation and abort the update driver. Note we are now back to the same options discussed earlier.
|
||||
|
||||
@@ -105,11 +105,13 @@ If the 2nd stage succeeds, the installer sends a `SPUInstallationFinishedStage2`
|
||||
|
||||
The updater receives a `SPUInstallationFinishedStage2` message, and reads if the target application had already been terminated. If the target application has not already terminated, the updater tells the user driver to show that the application is being sent a termination request.
|
||||
|
||||
In the case termination of the application is delayed or canceled, the user driver may re-try sending a `SPUResumeInstallationToStage2` message to the installer. This time the installer will recognize it already completed stage 2. If it hasn't proceeded onto stage 3 it will send another quit event to the application. This re-try can be done multiple times.
|
||||
|
||||
### Showing Progress
|
||||
|
||||
When the target application is terminated, if the updater allowed the installer to show UI progress and the installation type doesn't show progress on its own (only interactive package installer shows progress on its own), then the installer sends a `SPUUpdaterAlivePing` message to the updater. If the updater is still alive by now and receives the message, the updater will then send back a `SPUUpdaterAlivePong` message. This lets the installer know that the updater is still active after the target application is terminated, and whether the installer should later be responsible for displaying updater progress or not if a short time passes by, and the installation is still not finished. If the updater is still not alive, then the installer should be responsible for showing progress if otherwise allowed.
|
||||
|
||||
If the installer decides to show progress, it sends a message to the progress agent to show progress UI. Under most circumstances, the installation will finish faster than this point is reached however (exceptions may be potentially large updates with many scattered files, guided package installers, and updates over a remote network mount). If the connection to the updater is still connected after this short time passes (eg: like with sparkle-cli), then it's the updater's job to show progress instead.
|
||||
If the installer decides to show progress, it sends a message to the progress agent to show progress UI. Under most circumstances, the installation will finish faster than this point is reached however (exceptions may be guided package installers and updates over a remote network mount). If the connection to the updater is still connected after this short time passes (eg: like with sparkle-cli), then it's the updater's job to show progress instead.
|
||||
|
||||
### Finishing the Installation
|
||||
The installer starts stage 3 of the installation after the target application is terminated as well. The third stage does the final installation for updating and replacing the new updated bundle.
|
||||
@@ -132,4 +134,4 @@ When the progress agent exits, it cleans up by removing itself from disk. The in
|
||||
|
||||
* When we terminate the application before doing final installation work, we send an Apple quit event to all running application instances we find under the agent's GUI login session. This does not include running instances from other logged in sessions -- that may require authenticating all the time, so trade off is not worthwhile. Also currently the installer only handles a single process identifier to watch for until termination, and certainly doesn't handle the case if more instances are launched afterwards. Note all of this only applies to instances being launched from the same bundle path, and the consequence may rarely be updating a bundle when a running instance is still left alive.
|
||||
|
||||
* SMJobBless() would be interesting to explore and perhaps more suitable for sparkle-cli than ordinary application updaters because using this API is less approriate for one-off installations. Furthermore, the installer would have to change to persist rather than be a one-time install, and may have to handle mutliple connections for installing multiple bundles simutaneously.
|
||||
* SMJobBless() would be interesting to explore and perhaps more suitable for sparkle-cli than ordinary application updaters because using this API is less appropriate for one-off installations. Furthermore, the installer would have to change to persist rather than be a one-time install, and may have to handle multiple connections for installing multiple bundles simultaneously.
|
||||
@@ -20,7 +20,7 @@ For XPC Services, it's significant to understand they can be used independent of
|
||||
|
||||
We have code that detects whether or not XPC services are available and enabled by the main application bundle. This is simpler and more efficient than attempting to create a connection and wait for a timeout. We don't have *any* checks for seeing if the "current process" is sandboxed; doing so is a rather broken behavior. The XPC Services are important, not the sandboxing.
|
||||
|
||||
I said above that XPC services are looked up in the main bundle. One may think this assumption doesn't hold for helpers or plug-ins inside applications. My response to that is they probably don't need the services, and they probably shoudn't be injecting Sparkle inside the host application anyway due to unintended conflicts and other consequences. A more appropriate approach may be to bundle a separate tool such as the sparkle command line utility.
|
||||
I said above that XPC services are looked up in the main bundle. One may think this assumption doesn't hold for helpers or plug-ins inside applications. My response to that is they probably don't need the services, and they probably shouldn't be injecting Sparkle inside the host application anyway due to unintended conflicts and other consequences. A more appropriate approach may be to bundle a separate tool such as the sparkle command line utility.
|
||||
|
||||
The `InstallerLauncher` XPC service needs a `JoinExistingSession` key set to `YES` otherwise authorization will not work properly, and even less so on older systems. It took me forever to debug this, so it's worth mentioning.
|
||||
|
||||
|
||||
File renamed without changes.
@@ -12,7 +12,7 @@
|
||||
@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>
|
||||
SPU_OBJC_DIRECT_MEMBERS @interface SPUDownloader : NSObject <SPUDownloaderProtocol>
|
||||
|
||||
// Due to XPC remote object reasons, this delegate is strongly referenced
|
||||
// Invoke cleanup when done with this instance
|
||||
|
||||
+131
-93
@@ -25,31 +25,24 @@ typedef NS_ENUM(NSUInteger, SPUDownloadMode)
|
||||
static NSString *SUDownloadingReason = @"Downloading update related file";
|
||||
|
||||
@interface SPUDownloader () <NSURLSessionDownloadDelegate>
|
||||
|
||||
// Delegate is intentionally strongly referenced; see header
|
||||
@property (nonatomic) id <SPUDownloaderDelegate> delegate;
|
||||
@property (nonatomic) NSURLSessionDownloadTask *download;
|
||||
@property (nonatomic) NSURLSession *downloadSession;
|
||||
@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;
|
||||
|
||||
@end
|
||||
|
||||
@implementation SPUDownloader
|
||||
|
||||
@synthesize delegate = _delegate;
|
||||
@synthesize download = _download;
|
||||
@synthesize downloadSession = _downloadSession;
|
||||
@synthesize bundleIdentifier = _bundleIdentifier;
|
||||
@synthesize desiredFilename = _desiredFilename;
|
||||
@synthesize downloadFilename = _downloadFilename;
|
||||
@synthesize disabledAutomaticTermination = _disabledAutomaticTermination;
|
||||
@synthesize mode = _mode;
|
||||
@synthesize receivedExpectedBytes = _receivedExpectedBytes;
|
||||
{
|
||||
NSURLSessionDownloadTask *_download;
|
||||
NSURLSession *_downloadSession;
|
||||
NSString *_bundleIdentifier;
|
||||
NSString *_desiredFilename;
|
||||
NSString *_downloadFilename;
|
||||
|
||||
// Delegate is intentionally strongly referenced; see header
|
||||
id <SPUDownloaderDelegate> _delegate;
|
||||
|
||||
SPUDownloadMode _mode;
|
||||
|
||||
BOOL _disabledAutomaticTermination;
|
||||
BOOL _receivedExpectedBytes;
|
||||
}
|
||||
|
||||
- (instancetype)initWithDelegate:(id <SPUDownloaderDelegate>)delegate
|
||||
{
|
||||
@@ -60,14 +53,40 @@ static NSString *SUDownloadingReason = @"Downloading update related file";
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)startDownloadWithRequest:(NSURLRequest *)request
|
||||
- (void)startDownloadWithRequest:(NSURLRequest *)request SPU_OBJC_DIRECT
|
||||
{
|
||||
self.downloadSession = [NSURLSession
|
||||
if (request == nil) {
|
||||
NSString *message = @"The download request must not be nil";
|
||||
NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUDownloadError userInfo:@{ NSLocalizedDescriptionKey: message }];
|
||||
[_delegate downloaderDidFailWithError:error];
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Prevent any unwanted URL schemes (e.g. file://)
|
||||
NSString *scheme = request.URL.scheme;
|
||||
if (scheme == nil) {
|
||||
NSString *message = @"The download request scheme must not be nil";
|
||||
NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUDownloadError userInfo:@{ NSLocalizedDescriptionKey: message }];
|
||||
[_delegate downloaderDidFailWithError:error];
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ([scheme caseInsensitiveCompare:@"http"] != NSOrderedSame && [scheme caseInsensitiveCompare:@"https"] != NSOrderedSame) {
|
||||
NSString *message = [NSString stringWithFormat:@"The download request URL must use http or https (%@)", request.URL];
|
||||
NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUDownloadError userInfo:@{ NSLocalizedDescriptionKey: message }];
|
||||
[_delegate downloaderDidFailWithError:error];
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
_downloadSession = [NSURLSession
|
||||
sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]
|
||||
delegate:self
|
||||
delegateQueue:[NSOperationQueue mainQueue]];
|
||||
self.download = [self.downloadSession downloadTaskWithRequest:request];
|
||||
[self.download resume];
|
||||
_download = [_downloadSession downloadTaskWithRequest:request];
|
||||
[_download resume];
|
||||
}
|
||||
|
||||
// Don't implement dealloc - make the client call cleanup, which is the only way to remove the reference cycle from the delegate anyway
|
||||
@@ -75,14 +94,14 @@ static NSString *SUDownloadingReason = @"Downloading update related file";
|
||||
- (void)startPersistentDownloadWithRequest:(NSURLRequest *)request bundleIdentifier:(NSString *)bundleIdentifier desiredFilename:(NSString *)desiredFilename
|
||||
{
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
if (self.download == nil && self.delegate != nil) {
|
||||
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->_disabledAutomaticTermination = YES;
|
||||
|
||||
self.mode = SPUDownloadModePersistent;
|
||||
self.desiredFilename = desiredFilename;
|
||||
self.bundleIdentifier = bundleIdentifier;
|
||||
self->_mode = SPUDownloadModePersistent;
|
||||
self->_desiredFilename = desiredFilename;
|
||||
self->_bundleIdentifier = [bundleIdentifier copy];
|
||||
|
||||
[self startDownloadWithRequest:request];
|
||||
}
|
||||
@@ -92,60 +111,63 @@ static NSString *SUDownloadingReason = @"Downloading update related file";
|
||||
- (void)startTemporaryDownloadWithRequest:(NSURLRequest *)request
|
||||
{
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
if (self.download == nil && self.delegate != nil) {
|
||||
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->_disabledAutomaticTermination = YES;
|
||||
|
||||
self.mode = SPUDownloadModeTemporary;
|
||||
self->_mode = SPUDownloadModeTemporary;
|
||||
[self startDownloadWithRequest:request];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
- (void)enableAutomaticTermination
|
||||
- (void)enableAutomaticTermination SPU_OBJC_DIRECT
|
||||
{
|
||||
if (self.disabledAutomaticTermination) {
|
||||
if (_disabledAutomaticTermination) {
|
||||
[[NSProcessInfo processInfo] enableAutomaticTermination:SUDownloadingReason];
|
||||
self.disabledAutomaticTermination = NO;
|
||||
_disabledAutomaticTermination = NO;
|
||||
}
|
||||
}
|
||||
|
||||
- (NSString *)rootPersistentDownloadCachePathForBundleIdentifier:(NSString *)bundleIdentifier
|
||||
- (NSString *)rootPersistentDownloadCachePathForBundleIdentifier:(NSString *)bundleIdentifier SPU_OBJC_DIRECT
|
||||
{
|
||||
// Note: The installer verifies this "PersistentDownloads" path component
|
||||
return [[SPULocalCacheDirectory cachePathForBundleIdentifier:bundleIdentifier] stringByAppendingPathComponent:@"PersistentDownloads"];
|
||||
}
|
||||
|
||||
- (void)removeDownloadDirectory:(NSString *)directoryName bundleIdentifier:(NSString *)bundleIdentifier
|
||||
- (void)removeDownloadDirectoryWithDownloadToken:(NSString *)downloadToken bundleIdentifier:(NSString *)bundleIdentifier
|
||||
{
|
||||
// Only take the directory name and compute most of the base path ourselves
|
||||
// Only take the directory name (from the download token) and compute most of the base path ourselves
|
||||
// This way we do not have to send/trust an absolute path
|
||||
// The downloader instance that creates this temp directory isn't necessarily the same as the one
|
||||
// that clears it (eg upon skipping an already downloaded update), so we can't just preserve it here too
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
NSString *rootPersistentDownloadCachePath = [self rootPersistentDownloadCachePathForBundleIdentifier:bundleIdentifier];
|
||||
if (rootPersistentDownloadCachePath != nil) {
|
||||
NSString *sanitizedDirectoryName = directoryName.lastPathComponent;
|
||||
NSString *tempDir = [rootPersistentDownloadCachePath stringByAppendingPathComponent:sanitizedDirectoryName];
|
||||
|
||||
[[NSFileManager defaultManager] removeItemAtPath:tempDir error:NULL];
|
||||
if (bundleIdentifier != nil && downloadToken != nil) {
|
||||
NSString *rootPersistentDownloadCachePath = [self rootPersistentDownloadCachePathForBundleIdentifier:bundleIdentifier];
|
||||
if (rootPersistentDownloadCachePath != nil) {
|
||||
NSString *sanitizedDownloadToken = downloadToken.lastPathComponent;
|
||||
NSString *tempDir = [rootPersistentDownloadCachePath stringByAppendingPathComponent:sanitizedDownloadToken];
|
||||
|
||||
[[NSFileManager defaultManager] removeItemAtPath:tempDir error:NULL];
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
- (void)_cleanup
|
||||
- (void)_cleanup SPU_OBJC_DIRECT
|
||||
{
|
||||
[self enableAutomaticTermination];
|
||||
[self.download cancel];
|
||||
[self.downloadSession finishTasksAndInvalidate];
|
||||
self.download = nil;
|
||||
self.downloadSession = nil;
|
||||
self.delegate = nil;
|
||||
[_download cancel];
|
||||
[_downloadSession finishTasksAndInvalidate];
|
||||
_download = nil;
|
||||
_downloadSession = nil;
|
||||
_delegate = nil;
|
||||
|
||||
if (self.mode == SPUDownloadModeTemporary && self.downloadFilename != nil)
|
||||
if (_mode == SPUDownloadModeTemporary && _downloadFilename != nil)
|
||||
{
|
||||
[[NSFileManager defaultManager] removeItemAtPath:self.downloadFilename error:NULL];
|
||||
self.downloadFilename = nil;
|
||||
[[NSFileManager defaultManager] removeItemAtPath:_downloadFilename error:NULL];
|
||||
_downloadFilename = nil;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -154,28 +176,30 @@ static NSString *SUDownloadingReason = @"Downloading update related file";
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[self _cleanup];
|
||||
|
||||
completionHandler();
|
||||
if (completionHandler != NULL) {
|
||||
completionHandler();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
- (void)URLSession:(NSURLSession *)__unused session downloadTask:(NSURLSessionDownloadTask *) downloadTask didFinishDownloadingToURL:(NSURL *)location
|
||||
- (void)URLSession:(NSURLSession *)__unused session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
|
||||
{
|
||||
NSInteger statusCode = [downloadTask.response isKindOfClass:[NSHTTPURLResponse class]] ? ((NSHTTPURLResponse *)downloadTask.response).statusCode : 200;
|
||||
if ((statusCode < 200) || (statusCode >= 400))
|
||||
{
|
||||
NSString *message = [NSString stringWithFormat:@"A network error occurred while downloading the update. %@ (%ld)", [NSHTTPURLResponse localizedStringForStatusCode:statusCode], (long)statusCode];
|
||||
NSString *message = [NSString stringWithFormat:@"A network error occurred while downloading %@. %@ (%ld)", downloadTask.originalRequest.URL.absoluteString, [NSHTTPURLResponse localizedStringForStatusCode:statusCode], (long)statusCode];
|
||||
NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUDownloadError userInfo:@{ NSLocalizedDescriptionKey: message }];
|
||||
[self.delegate downloaderDidFailWithError:error];
|
||||
[_delegate downloaderDidFailWithError:error];
|
||||
}
|
||||
else if (self.mode == SPUDownloadModeTemporary)
|
||||
else if (_mode == SPUDownloadModeTemporary)
|
||||
{
|
||||
self.downloadFilename = location.path;
|
||||
_downloadFilename = location.path;
|
||||
[self downloadDidFinish]; // file is already in a system temp dir
|
||||
}
|
||||
else
|
||||
{
|
||||
// Remove our old caches path so we don't start accumulating files in there
|
||||
NSString *rootPersistentDownloadCachePath = [self rootPersistentDownloadCachePathForBundleIdentifier:self.bundleIdentifier];
|
||||
NSString *rootPersistentDownloadCachePath = [self rootPersistentDownloadCachePathForBundleIdentifier:_bundleIdentifier];
|
||||
|
||||
[SPULocalCacheDirectory removeOldItemsInDirectory:rootPersistentDownloadCachePath];
|
||||
|
||||
@@ -183,23 +207,23 @@ static NSString *SUDownloadingReason = @"Downloading update related file";
|
||||
if (tempDir == nil)
|
||||
{
|
||||
// Okay, something's really broken with this user's file structure.
|
||||
[self.download cancel];
|
||||
self.download = nil;
|
||||
[_download cancel];
|
||||
_download = nil;
|
||||
|
||||
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];
|
||||
[_delegate downloaderDidFailWithError:error];
|
||||
} else {
|
||||
NSString *downloadFileName = self.desiredFilename;
|
||||
NSString *downloadFileName = _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];
|
||||
[_delegate downloaderDidFailWithError:error];
|
||||
} else {
|
||||
NSString *name = self.download.response.suggestedFilename;
|
||||
NSString *name = _download.response.suggestedFilename;
|
||||
if (!name) {
|
||||
name = location.lastPathComponent; // This likely contains nothing useful to identify the file (e.g. CFNetworkDownload_87LVIz.tmp)
|
||||
}
|
||||
@@ -207,11 +231,26 @@ static NSString *SUDownloadingReason = @"Downloading update related file";
|
||||
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];
|
||||
_downloadFilename = toPath;
|
||||
|
||||
// Create a bookmark for the download
|
||||
// Don't pass any options (we don't want a persistent security scoped bookmark)
|
||||
|
||||
NSURL *downloadURL = [NSURL fileURLWithPath:toPath isDirectory:NO];
|
||||
|
||||
NSError *bookmarkError = nil;
|
||||
NSData *bookmarkData = [downloadURL bookmarkDataWithOptions:0 includingResourceValuesForKeys:@[] relativeToURL:nil error:&bookmarkError];
|
||||
if (bookmarkData == nil) {
|
||||
[_delegate downloaderDidFailWithError:bookmarkError];
|
||||
} else {
|
||||
// The download token may be provided later to the downloader for removing a download
|
||||
// and its temporary directory
|
||||
NSString *downloadToken = tempDir.lastPathComponent;
|
||||
[_delegate downloaderDidSetDownloadBookmarkData:bookmarkData downloadToken:downloadToken];
|
||||
[self downloadDidFinish];
|
||||
}
|
||||
} else {
|
||||
[self.delegate downloaderDidFailWithError:error];
|
||||
[_delegate downloaderDidFailWithError:error];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -221,33 +260,32 @@ static NSString *SUDownloadingReason = @"Downloading update related file";
|
||||
- (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 (_mode == SPUDownloadModePersistent && totalBytesExpectedToWrite > 0 && !_receivedExpectedBytes) {
|
||||
_receivedExpectedBytes = YES;
|
||||
[_delegate downloaderDidReceiveExpectedContentLength:totalBytesExpectedToWrite];
|
||||
}
|
||||
|
||||
if (self.mode == SPUDownloadModePersistent && bytesWritten >= 0) {
|
||||
[self.delegate downloaderDidReceiveDataOfLength:(uint64_t)bytesWritten];
|
||||
if (_mode == SPUDownloadModePersistent && bytesWritten >= 0) {
|
||||
[_delegate downloaderDidReceiveDataOfLength:(uint64_t)bytesWritten];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)downloadDidFinish
|
||||
- (void)downloadDidFinish SPU_OBJC_DIRECT
|
||||
{
|
||||
assert(self.downloadFilename != nil);
|
||||
assert(_downloadFilename != nil);
|
||||
|
||||
SPUDownloadData *downloadData = nil;
|
||||
if (self.mode == SPUDownloadModeTemporary) {
|
||||
NSData *data = [NSData dataWithContentsOfFile:self.downloadFilename];
|
||||
if (_mode == SPUDownloadModeTemporary) {
|
||||
NSData *data = [NSData dataWithContentsOfFile:_downloadFilename];
|
||||
if (data != nil) {
|
||||
NSURLResponse *response = self.download.response;
|
||||
assert(response != nil);
|
||||
NSURLResponse *response = _download.response;
|
||||
|
||||
NSURL *responseURL = response.URL;
|
||||
if (responseURL == nil) {
|
||||
responseURL = self.download.currentRequest.URL;
|
||||
responseURL = _download.currentRequest.URL;
|
||||
}
|
||||
if (responseURL == nil) {
|
||||
responseURL = self.download.originalRequest.URL;
|
||||
responseURL = _download.originalRequest.URL;
|
||||
}
|
||||
assert(responseURL != nil);
|
||||
|
||||
@@ -255,33 +293,33 @@ static NSString *SUDownloadingReason = @"Downloading update related file";
|
||||
}
|
||||
}
|
||||
|
||||
self.download = nil;
|
||||
_download = nil;
|
||||
|
||||
switch (self.mode) {
|
||||
switch (_mode) {
|
||||
case SPUDownloadModeTemporary:
|
||||
if (downloadData != nil) {
|
||||
[self.delegate downloaderDidFinishWithTemporaryDownloadData:downloadData];
|
||||
[_delegate downloaderDidFinishWithTemporaryDownloadData:downloadData];
|
||||
} else {
|
||||
[self.delegate downloaderDidFailWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUDownloadError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to read temporary downloaded data from %@", self.downloadFilename]}]];
|
||||
[_delegate downloaderDidFailWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUDownloadError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to read temporary downloaded data from %@", _downloadFilename]}]];
|
||||
}
|
||||
|
||||
[self _cleanup];
|
||||
break;
|
||||
case SPUDownloadModePersistent:
|
||||
[self.delegate downloaderDidFinishWithTemporaryDownloadData:nil];
|
||||
[_delegate downloaderDidFinishWithTemporaryDownloadData:nil];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)URLSession:(NSURLSession *)__unused session task:(NSURLSessionTask *)__unused task didCompleteWithError:(NSError *)error
|
||||
{
|
||||
self.download = nil;
|
||||
_download = nil;
|
||||
if (error != nil) {
|
||||
[self.delegate downloaderDidFailWithError:error];
|
||||
[_delegate downloaderDidFailWithError:error];
|
||||
}
|
||||
}
|
||||
|
||||
// NSURLDownload has a [downlaod:shouldDecodeSourceDataOfMIMEType:] to determine if the data should be decoded.
|
||||
// NSURLDownload has a [download: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
|
||||
@@ -15,7 +15,7 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
@protocol SPUDownloaderDelegate <NSObject>
|
||||
|
||||
// This is only invoked for persistent downloads
|
||||
- (void)downloaderDidSetDestinationName:(NSString *)destinationName temporaryDirectory:(NSString *)temporaryDirectory;
|
||||
- (void)downloaderDidSetDownloadBookmarkData:(NSData *)downloadBookmarkData downloadToken:(NSString *)downloadToken;
|
||||
|
||||
// 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
|
||||
|
||||
@@ -17,7 +17,7 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
- (void)startTemporaryDownloadWithRequest:(NSURLRequest *)request;
|
||||
|
||||
- (void)removeDownloadDirectory:(NSString *)directoryName bundleIdentifier:(NSString *)bundleIdentifier;
|
||||
- (void)removeDownloadDirectoryWithDownloadToken:(NSString *)downloadToken bundleIdentifier:(NSString *)bundleIdentifier;
|
||||
|
||||
- (void)cleanup:(void (^)(void))completionHandler;
|
||||
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "SPUDownloader.h"
|
||||
#import "SPUDownloaderDelegate.h"
|
||||
#import "SULog.h"
|
||||
#import "SUCodeSigningVerifier.h"
|
||||
|
||||
@interface ServiceDelegate : NSObject <NSXPCListenerDelegate>
|
||||
@end
|
||||
@@ -18,6 +20,29 @@
|
||||
- (BOOL)listener:(NSXPCListener *)__unused listener shouldAcceptNewConnection:(NSXPCConnection *)newConnection {
|
||||
// This method is where the NSXPCListener configures, accepts, and resumes a new incoming NSXPCConnection.
|
||||
|
||||
// Validate connection of clients to avoid any client from using the service.
|
||||
// Ideally we would also prevent clients connecting that have an outgoing network connection enabled,
|
||||
// but this is not easy to enforce.
|
||||
// This is a policy, not a security critical enforcement.
|
||||
{
|
||||
NSError *validationError = nil;
|
||||
SUValidateConnectionStatus validationStatus = [SUCodeSigningVerifier validateConnection:newConnection options:SUValidateConnectionOptionDefault error:&validationError];
|
||||
switch (validationStatus) {
|
||||
case SUValidateConnectionStatusSetCodeSigningRequirementSuccess:
|
||||
break;
|
||||
case SUValidateConnectionStatusSetNoRequirementSuccess:
|
||||
break;
|
||||
case SUValidateConnectionStatusAPIFailure:
|
||||
case SUValidateConnectionStatusCodeSigningRequirementFailure:
|
||||
case SUValidateConectionNoSupportedValidationMethodFailure:
|
||||
SULog(SULogLevelError, @"Error: Downloader XPC Service is rejecting new connection due to failing validation of XPC connection with status %lu and error: %@", validationStatus, validationError.localizedDescription);
|
||||
|
||||
[newConnection invalidate];
|
||||
|
||||
return NO;
|
||||
}
|
||||
}
|
||||
|
||||
// Configure the connection.
|
||||
// First, set the interface that the exported object implements.
|
||||
newConnection.exportedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SPUDownloaderProtocol)];
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
// 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 SUInstallerConnection : NSObject <SUInstallerConnectionProtocol>
|
||||
SPU_OBJC_DIRECT_MEMBERS @interface SUInstallerConnection : NSObject <SUInstallerConnectionProtocol>
|
||||
|
||||
// Due to XPC reasons, this delegate is strongly referenced, until it's invalidated
|
||||
- (instancetype)initWithDelegate:(id<SUInstallerCommunicationProtocol>)delegate remote:(BOOL)remote;
|
||||
|
||||
@@ -14,26 +14,20 @@
|
||||
static NSString *SUInstallerConnectionKeepAliveReason = @"Installer Connection Keep Alive";
|
||||
|
||||
@interface SUInstallerConnection () <SUInstallerCommunicationProtocol>
|
||||
|
||||
// Intentionally not weak for XPC reasons
|
||||
@property (nonatomic) id<SUInstallerCommunicationProtocol> delegate;
|
||||
|
||||
@property (nonatomic) BOOL disabledAutomaticTermination;
|
||||
@property (nonatomic, copy) void (^invalidationBlock)(void);
|
||||
@property (nonatomic) NSXPCConnection *connection;
|
||||
|
||||
@end
|
||||
|
||||
@implementation SUInstallerConnection
|
||||
{
|
||||
NSXPCConnection *_connection;
|
||||
// Intentionally not weak for XPC reasons
|
||||
id<SUInstallerCommunicationProtocol> _delegate;
|
||||
|
||||
void (^_invalidationBlock)(void);
|
||||
|
||||
BOOL _disabledAutomaticTermination;
|
||||
BOOL _remote;
|
||||
}
|
||||
|
||||
@synthesize delegate = _delegate;
|
||||
@synthesize disabledAutomaticTermination = _disabledAutomaticTermination;
|
||||
@synthesize invalidationBlock = _invalidationBlock;
|
||||
@synthesize connection = _connection;
|
||||
|
||||
- (instancetype)initWithDelegate:(id<SUInstallerCommunicationProtocol>)delegate remote:(BOOL)remote
|
||||
{
|
||||
self = [super init];
|
||||
@@ -50,17 +44,17 @@ static NSString *SUInstallerConnectionKeepAliveReason = @"Installer Connection K
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)enableAutomaticTermination
|
||||
- (void)enableAutomaticTermination SPU_OBJC_DIRECT
|
||||
{
|
||||
if (self.disabledAutomaticTermination) {
|
||||
if (_disabledAutomaticTermination) {
|
||||
[[NSProcessInfo processInfo] enableAutomaticTermination:SUInstallerConnectionKeepAliveReason];
|
||||
self.disabledAutomaticTermination = NO;
|
||||
_disabledAutomaticTermination = NO;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)_setInvalidationHandler:(void (^)(void))invalidationHandler
|
||||
- (void)_setInvalidationHandler:(void (^)(void))invalidationHandler SPU_OBJC_DIRECT
|
||||
{
|
||||
self.invalidationBlock = invalidationHandler;
|
||||
_invalidationBlock = [invalidationHandler copy];
|
||||
|
||||
// No longer needed because of invalidation callback
|
||||
[self enableAutomaticTermination];
|
||||
@@ -77,36 +71,39 @@ static NSString *SUInstallerConnectionKeepAliveReason = @"Installer Connection K
|
||||
}
|
||||
}
|
||||
|
||||
- (void)_setServiceName:(NSString *)serviceName systemDomain:(BOOL)systemDomain
|
||||
- (void)_setServiceName:(NSString *)serviceName systemDomain:(BOOL)systemDomain SPU_OBJC_DIRECT
|
||||
{
|
||||
NSXPCConnectionOptions options = systemDomain ? NSXPCConnectionPrivileged : 0;
|
||||
NSXPCConnection *connection = [[NSXPCConnection alloc] initWithMachServiceName:serviceName options:options];
|
||||
|
||||
connection.exportedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUInstallerCommunicationProtocol)];
|
||||
connection.exportedObject = self.delegate;
|
||||
connection.exportedObject = _delegate;
|
||||
|
||||
connection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUInstallerCommunicationProtocol)];
|
||||
|
||||
self.connection = connection;
|
||||
_connection = connection;
|
||||
|
||||
__weak SUInstallerConnection *weakSelf = self;
|
||||
self.connection.interruptionHandler = ^{
|
||||
__weak __typeof__(self) weakSelf = self;
|
||||
_connection.interruptionHandler = ^{
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[weakSelf.connection invalidate];
|
||||
__typeof__(self) strongSelf = weakSelf;
|
||||
if (strongSelf != nil) {
|
||||
[strongSelf->_connection invalidate];
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
self.connection.invalidationHandler = ^{
|
||||
_connection.invalidationHandler = ^{
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
SUInstallerConnection *strongSelf = weakSelf;
|
||||
__typeof__(self) strongSelf = weakSelf;
|
||||
if (strongSelf != nil) {
|
||||
strongSelf.connection = nil;
|
||||
strongSelf->_connection = nil;
|
||||
[strongSelf _invalidate];
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
[self.connection resume];
|
||||
[_connection resume];
|
||||
}
|
||||
|
||||
- (void)setServiceName:(NSString *)serviceName systemDomain:(BOOL)systemDomain
|
||||
@@ -124,22 +121,22 @@ static NSString *SUInstallerConnectionKeepAliveReason = @"Installer Connection K
|
||||
{
|
||||
if (_remote) {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[(id<SUInstallerCommunicationProtocol>)self.connection.remoteObjectProxy handleMessageWithIdentifier:identifier data:data];
|
||||
[(id<SUInstallerCommunicationProtocol>)self->_connection.remoteObjectProxy handleMessageWithIdentifier:identifier data:data];
|
||||
});
|
||||
} else {
|
||||
[(id<SUInstallerCommunicationProtocol>)self.connection.remoteObjectProxy handleMessageWithIdentifier:identifier data:data];
|
||||
[(id<SUInstallerCommunicationProtocol>)_connection.remoteObjectProxy handleMessageWithIdentifier:identifier data:data];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)_invalidate
|
||||
- (void)_invalidate SPU_OBJC_DIRECT
|
||||
{
|
||||
if (self.invalidationBlock != nil) {
|
||||
self.invalidationBlock();
|
||||
self.invalidationBlock = nil;
|
||||
if (_invalidationBlock != nil) {
|
||||
_invalidationBlock();
|
||||
_invalidationBlock = nil;
|
||||
}
|
||||
|
||||
// Break the retain cycle
|
||||
self.delegate = nil;
|
||||
_delegate = nil;
|
||||
|
||||
[self enableAutomaticTermination];
|
||||
}
|
||||
@@ -148,8 +145,8 @@ static NSString *SUInstallerConnectionKeepAliveReason = @"Installer Connection K
|
||||
- (void)invalidate
|
||||
{
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[self.connection invalidate];
|
||||
self.connection = nil;
|
||||
[self->_connection invalidate];
|
||||
self->_connection = nil;
|
||||
|
||||
[self _invalidate];
|
||||
});
|
||||
|
||||
@@ -6,12 +6,14 @@
|
||||
// Copyright © 2016 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#if INSTALLER_CONNECTION_XPC_SERVICE_EMBEDDED
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "SUInstallerConnectionProtocol.h"
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface SUXPCInstallerConnection : NSObject <SUInstallerConnectionProtocol>
|
||||
SPU_OBJC_DIRECT_MEMBERS @interface SUXPCInstallerConnection : NSObject <SUInstallerConnectionProtocol>
|
||||
|
||||
// Due to XPC reasons, this delegate is strongly referenced, until it's invalidated
|
||||
- (instancetype)initWithDelegate:(id<SUInstallerCommunicationProtocol>)delegate;
|
||||
@@ -19,3 +21,5 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
#endif
|
||||
@@ -6,24 +6,21 @@
|
||||
// Copyright © 2016 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#if INSTALLER_CONNECTION_XPC_SERVICE_EMBEDDED
|
||||
|
||||
#import "SUXPCInstallerConnection.h"
|
||||
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
|
||||
@interface SUXPCInstallerConnection ()
|
||||
|
||||
@property (nonatomic) NSXPCConnection *connection;
|
||||
@property (nonatomic) id<SUInstallerCommunicationProtocol> delegate; // intentionally not weak for XPC reasons
|
||||
@property (nonatomic, copy) void (^invalidationBlock)(void);
|
||||
|
||||
@end
|
||||
|
||||
@implementation SUXPCInstallerConnection
|
||||
|
||||
@synthesize connection = _connection;
|
||||
@synthesize delegate = _delegate;
|
||||
@synthesize invalidationBlock = _invalidationBlock;
|
||||
{
|
||||
NSXPCConnection *_connection;
|
||||
// Intentionally not weak for XPC reasons
|
||||
id<SUInstallerCommunicationProtocol> _delegate;
|
||||
|
||||
void (^_invalidationBlock)(void);
|
||||
}
|
||||
|
||||
- (instancetype)initWithDelegate:(id<SUInstallerCommunicationProtocol>)delegate
|
||||
{
|
||||
@@ -32,14 +29,17 @@
|
||||
_connection = [[NSXPCConnection alloc] initWithServiceName:@INSTALLER_CONNECTION_BUNDLE_ID];
|
||||
_connection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUInstallerConnectionProtocol)];
|
||||
|
||||
__weak SUXPCInstallerConnection *weakSelf = self;
|
||||
__weak __typeof__(self) weakSelf = self;
|
||||
_connection.invalidationHandler = ^{
|
||||
[weakSelf invokeInvalidation];
|
||||
};
|
||||
|
||||
_connection.interruptionHandler = ^{
|
||||
[weakSelf invokeInvalidation];
|
||||
[weakSelf.connection invalidate];
|
||||
__typeof__(self) strongSelf = weakSelf;
|
||||
if (strongSelf != nil) {
|
||||
[strongSelf invokeInvalidation];
|
||||
[strongSelf->_connection invalidate];
|
||||
}
|
||||
};
|
||||
|
||||
_delegate = delegate;
|
||||
@@ -54,39 +54,41 @@
|
||||
|
||||
- (void)setInvalidationHandler:(void (^)(void))invalidationHandler
|
||||
{
|
||||
self.invalidationBlock = invalidationHandler;
|
||||
_invalidationBlock = [invalidationHandler copy];
|
||||
|
||||
__weak SUXPCInstallerConnection *weakSelf = self;
|
||||
[(id<SUInstallerConnectionProtocol>)self.connection.remoteObjectProxy setInvalidationHandler:^{
|
||||
__weak __typeof__(self) weakSelf = self;
|
||||
[(id<SUInstallerConnectionProtocol>)_connection.remoteObjectProxy setInvalidationHandler:^{
|
||||
[weakSelf invokeInvalidation];
|
||||
}];
|
||||
}
|
||||
|
||||
- (void)setServiceName:(NSString *)serviceName systemDomain:(BOOL)systemDomain
|
||||
{
|
||||
[(id<SUInstallerConnectionProtocol>)self.connection.remoteObjectProxy setServiceName:serviceName systemDomain:systemDomain];
|
||||
[(id<SUInstallerConnectionProtocol>)_connection.remoteObjectProxy setServiceName:serviceName systemDomain:systemDomain];
|
||||
}
|
||||
|
||||
- (void)handleMessageWithIdentifier:(int32_t)identifier data:(NSData *)data
|
||||
{
|
||||
[(id<SUInstallerConnectionProtocol>)self.connection.remoteObjectProxy handleMessageWithIdentifier:identifier data:data];
|
||||
[(id<SUInstallerConnectionProtocol>)_connection.remoteObjectProxy handleMessageWithIdentifier:identifier data:data];
|
||||
}
|
||||
|
||||
- (void)invalidate
|
||||
{
|
||||
[(id<SUInstallerConnectionProtocol>)self.connection.remoteObjectProxy invalidate];
|
||||
[self.connection invalidate];
|
||||
self.connection = nil;
|
||||
[(id<SUInstallerConnectionProtocol>)_connection.remoteObjectProxy invalidate];
|
||||
[_connection invalidate];
|
||||
_connection = nil;
|
||||
}
|
||||
|
||||
- (void)invokeInvalidation
|
||||
- (void)invokeInvalidation SPU_OBJC_DIRECT
|
||||
{
|
||||
if (self.invalidationBlock != nil) {
|
||||
self.invalidationBlock();
|
||||
self.invalidationBlock = nil;
|
||||
if (_invalidationBlock != nil) {
|
||||
_invalidationBlock();
|
||||
_invalidationBlock = nil;
|
||||
}
|
||||
// Break our retain cycle
|
||||
self.delegate = nil;
|
||||
_delegate = nil;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
@@ -1,12 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>com.apple.security.app-sandbox</key>
|
||||
<true/>
|
||||
<key>com.apple.security.temporary-exception.mach-lookup.global-name</key>
|
||||
<array>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)-spki</string>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -9,10 +9,18 @@
|
||||
#ifndef SUInstallerLauncher_Private_h
|
||||
#define SUInstallerLauncher_Private_h
|
||||
|
||||
#if defined(BUILDING_SPARKLE_SOURCES_EXTERNALLY)
|
||||
// Ignore incorrect warning
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wquoted-include-in-framework-header"
|
||||
#import "SUExport.h"
|
||||
#import "SPUInstallationType.h"
|
||||
#pragma clang diagnostic pop
|
||||
#else
|
||||
#import <Sparkle/SUExport.h>
|
||||
|
||||
// Chances are clients will need this too
|
||||
#import <Sparkle/SPUInstallationType.h>
|
||||
#endif
|
||||
|
||||
@class NSString;
|
||||
|
||||
|
||||
@@ -11,21 +11,28 @@
|
||||
#import "SUFileManager.h"
|
||||
#import "SULog.h"
|
||||
#import "SPUMessageTypes.h"
|
||||
#import "SUBundleIcon.h"
|
||||
#import "SPULocalCacheDirectory.h"
|
||||
#import "SPUInstallationType.h"
|
||||
#import "SUHost.h"
|
||||
#import <ImageIO/ImageIO.h>
|
||||
#import <ServiceManagement/ServiceManagement.h>
|
||||
#import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>
|
||||
#import <SystemConfiguration/SystemConfiguration.h>
|
||||
|
||||
// We only fetch bundle icon for Installer Launcher XPC Service
|
||||
#if defined(BUILDING_SPARKLE_SOURCES_EXTERNALLY) && BUILDING_SPARKLE_SOURCES_EXTERNALLY
|
||||
#define FETCH_BUNDLE_ICON_FOR_AUTH 1
|
||||
#else
|
||||
#define FETCH_BUNDLE_ICON_FOR_AUTH 0
|
||||
#endif
|
||||
|
||||
#if FETCH_BUNDLE_ICON_FOR_AUTH
|
||||
#import <AppKit/AppKit.h>
|
||||
#else
|
||||
#include "AppKitPrevention.h"
|
||||
#endif
|
||||
|
||||
@implementation SUInstallerLauncher
|
||||
|
||||
- (BOOL)submitProgressToolAtPath:(NSString *)progressToolPath withHostBundle:(NSBundle *)hostBundle inSystemDomainForInstaller:(BOOL)inSystemDomainForInstaller
|
||||
- (BOOL)submitProgressToolAtPath:(NSString *)progressToolPath withHostBundle:(NSBundle *)hostBundle inSystemDomainForInstaller:(BOOL)inSystemDomainForInstaller SPU_OBJC_DIRECT
|
||||
{
|
||||
SUFileManager *fileManager = [[SUFileManager alloc] init];
|
||||
|
||||
@@ -106,10 +113,8 @@
|
||||
return (submittedJob == true);
|
||||
}
|
||||
|
||||
- (SUInstallerLauncherStatus)submitInstallerAtPath:(NSString *)installerPath withHostBundle:(NSBundle *)hostBundle updaterIdentifier:(NSString *)updaterIdentifier userName:(NSString *)userName homeDirectory:(NSString *)homeDirectory authorizationPrompt:(NSString *)authorizationPrompt inSystemDomain:(BOOL)systemDomain rootUser:(BOOL)rootUser
|
||||
- (SUInstallerLauncherStatus)submitInstallerAtPath:(NSString *)installerPath withHostBundle:(NSBundle *)hostBundle iconBundlePath:(NSString *)iconBundlePath updaterIdentifier:(NSString *)updaterIdentifier userName:(NSString *)userName homeDirectory:(NSString *)homeDirectory mainBundleName:(NSString *)mainBundleName inSystemDomain:(BOOL)systemDomain rootUser:(BOOL)rootUser SPU_OBJC_DIRECT
|
||||
{
|
||||
SUFileManager *fileManager = [[SUFileManager alloc] init];
|
||||
|
||||
// No need to release the quarantine for this utility
|
||||
// In fact, we shouldn't because the tool may be located at a path we should not be writing too.
|
||||
|
||||
@@ -140,14 +145,25 @@
|
||||
// Using this right rather than using something like kSMRightModifySystemDaemons allows us to present a better worded prompt
|
||||
// Note the right name is cached, so if we want to change the authorization
|
||||
// prompt, we may need to change the right name. I have found no good way around this :|
|
||||
|
||||
SUHost *host = [[SUHost alloc] initWithBundle:hostBundle];
|
||||
NSString *hostName = host.name;
|
||||
|
||||
// Figure out the authorization prompt and right name
|
||||
// We create the authorization prompt here so that a bad client cannot pass in a completely arbitrary prompt message
|
||||
// We also forgo localization for this prompt at the moment because with the right name being cached, updating localizations will be undesirable.
|
||||
// Furthermore, we can avoid adding localization files to the Installer XPC Service (if that one is being used).
|
||||
NSString *sparkleAuthTag = @"sparkle2-auth"; // this needs to change if auth wording changes
|
||||
NSString *rightNameString;
|
||||
NSString *authorizationPrompt;
|
||||
if ([hostBundleIdentifier isEqualToString:updaterIdentifier]) {
|
||||
// Application bundle is likely updating itself
|
||||
rightNameString = [NSString stringWithFormat:@"%@.%@", hostBundleIdentifier, sparkleAuthTag];
|
||||
authorizationPrompt = [NSString stringWithFormat:@"%1$@ wants permission to update.", hostName];
|
||||
} else {
|
||||
// Updater is likely updating a bundle that is not itself
|
||||
rightNameString = [NSString stringWithFormat:@"%@.%@.%@", updaterIdentifier, hostBundleIdentifier, sparkleAuthTag];
|
||||
authorizationPrompt = [NSString stringWithFormat:@"%1$@ wants permission to update %2$@.", mainBundleName, hostName];
|
||||
}
|
||||
|
||||
const char *rightName = rightNameString.UTF8String;
|
||||
@@ -164,80 +180,68 @@
|
||||
AuthorizationRights rights = { .count = 1, .items = &right };
|
||||
|
||||
AuthorizationFlags flags = (AuthorizationFlags)(kAuthorizationFlagExtendRights | kAuthorizationFlagInteractionAllowed);
|
||||
|
||||
AuthorizationItem iconAuthorizationItem = {.name = kAuthorizationEnvironmentIcon, .valueLength = 0, .value = NULL, .flags = 0};
|
||||
AuthorizationEnvironment authorizationEnvironment = {.count = 0, .items = NULL};
|
||||
|
||||
// Find a 32x32 image representation of the icon, and write out a PNG version of it to a temporary location
|
||||
// Then use the icon (if one is available) for the authorization prompt
|
||||
// NSImage is not used because it relies on AppKit
|
||||
NSURL *tempIconDestinationURL = nil;
|
||||
NSURL *iconURL = [SUBundleIcon iconURLForHost:[[SUHost alloc] initWithBundle:hostBundle]];
|
||||
if (iconURL != nil) {
|
||||
CGImageSourceRef imageSource = CGImageSourceCreateWithURL((CFURLRef)iconURL, (CFDictionaryRef)@{});
|
||||
if (imageSource != NULL) {
|
||||
size_t imageCount = CGImageSourceGetCount(imageSource);
|
||||
for (size_t imageIndex = 0; imageIndex < imageCount; imageIndex++) {
|
||||
CFDictionaryRef cfProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, imageIndex, (CFDictionaryRef)@{});
|
||||
NSDictionary *properties = CFBridgingRelease(cfProperties);
|
||||
#if FETCH_BUNDLE_ICON_FOR_AUTH
|
||||
NSString *tempIconDestinationPath = nil;
|
||||
AuthorizationItem iconAuthorizationItem = {.name = kAuthorizationEnvironmentIcon, .valueLength = 0, .value = NULL, .flags = 0};
|
||||
char iconPathBuffer[] = "/tmp/XXXXXX.png";
|
||||
|
||||
// If an icon bundle path is specified, write out a representation of the icon's data to a temporary file.
|
||||
// Then use that image data for the authorization prompt
|
||||
if (iconBundlePath != nil) {
|
||||
NSImage *icon = [[NSWorkspace sharedWorkspace] iconForFile:iconBundlePath];
|
||||
|
||||
// Creating a bitmap representation at a specific size is much cheaper than asking for icon's TIFFRepresentation
|
||||
// On older OS's we must create a 32x32 image otherwise it won't be scaled correctly in the dialog
|
||||
// On newer OS's we can use a slightly higher resolution image
|
||||
NSInteger imageDimensions;
|
||||
if (@available(macOS 10.15, *)) {
|
||||
imageDimensions = 64;
|
||||
} else {
|
||||
imageDimensions = 32;
|
||||
}
|
||||
|
||||
NSBitmapImageRep *iconBitmapRep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL pixelsWide:imageDimensions pixelsHigh:imageDimensions bitsPerSample:8 samplesPerPixel:4 hasAlpha:YES isPlanar:NO colorSpaceName:NSCalibratedRGBColorSpace bytesPerRow:0 bitsPerPixel:0];
|
||||
|
||||
[NSGraphicsContext saveGraphicsState];
|
||||
|
||||
NSGraphicsContext.currentContext = [NSGraphicsContext graphicsContextWithBitmapImageRep:iconBitmapRep];
|
||||
[icon drawInRect:NSMakeRect(0, 0, imageDimensions, imageDimensions)];
|
||||
|
||||
[NSGraphicsContext restoreGraphicsState];
|
||||
|
||||
NSData *pngData = [iconBitmapRep representationUsingType:NSBitmapImageFileTypePNG properties:@{}];
|
||||
|
||||
if (pngData != nil) {
|
||||
// Use /tmp rather than NSTemporaryDirectory() or SUFileManager's temp directory function because we want:
|
||||
// a) no spaces in the path (SU/NSFileManager fails here)
|
||||
// b) short file path that does not exceed a small threshold (NSTemporaryDirectory() fails here) only apply to older systems (eg: macOS 10.8)
|
||||
// The file also needs to be placed in a system readable place such as /tmp
|
||||
// See https://github.com/sparkle-project/Sparkle/issues/347#issuecomment-149523848 for more info
|
||||
int tempIconFile = mkstemps(iconPathBuffer, strlen(".png"));
|
||||
if (tempIconFile == -1) {
|
||||
SULog(SULogLevelError, @"Failed to open temp icon from path buffer with error: %d", errno);
|
||||
} else {
|
||||
close(tempIconFile);
|
||||
|
||||
NSNumber *pixelWidth = properties[(const NSString *)kCGImagePropertyPixelWidth];
|
||||
NSNumber *pixelHeight = properties[(const NSString *)kCGImagePropertyPixelHeight];
|
||||
tempIconDestinationPath = [[NSFileManager defaultManager] stringWithFileSystemRepresentation:iconPathBuffer length:strlen(iconPathBuffer)];
|
||||
|
||||
// If we don't find a 32x32 image representation, then we don't provide an icon
|
||||
// Don't try to make up with it by eg: converting an image representation to this size
|
||||
// The app developer should be providing the icon representation.
|
||||
// The authorization API may not take other size dimensions.
|
||||
NSNumber *targetDimension = @32;
|
||||
if ([pixelWidth isKindOfClass:[NSNumber class]] && [pixelHeight isKindOfClass:[NSNumber class]] && [pixelWidth isEqualToNumber:targetDimension] && [pixelHeight isEqualToNumber:targetDimension]) {
|
||||
|
||||
// Use /tmp rather than NSTemporaryDirectory() or SUFileManager's temp directory function because we want:
|
||||
// a) no spaces in the path (SU/NSFileManager fails here)
|
||||
// b) short file path that does not exceed a small threshold (NSTemporaryDirectory() fails here)
|
||||
// These limitations only apply to older systems (eg: macOS 10.8)
|
||||
// The file also needs to be placed in a system readable place such as /tmp
|
||||
// See https://github.com/sparkle-project/Sparkle/issues/347#issuecomment-149523848 for more info
|
||||
char pathBuffer[] = "/tmp/XXXXXX.png";
|
||||
int tempIconFile = mkstemps(pathBuffer, strlen(".png"));
|
||||
if (tempIconFile == -1) {
|
||||
SULog(SULogLevelError, @"Failed to open temp icon from path buffer with error: %d", errno);
|
||||
if (tempIconDestinationPath != nil) {
|
||||
if (![pngData writeToFile:tempIconDestinationPath atomically:NO]) {
|
||||
SULog(SULogLevelError, @"Failed to write icon image data to %@", tempIconDestinationPath);
|
||||
} else {
|
||||
close(tempIconFile);
|
||||
iconAuthorizationItem.valueLength = strlen(iconPathBuffer);
|
||||
iconAuthorizationItem.value = iconPathBuffer;
|
||||
|
||||
NSString *path = [[NSString alloc] initWithUTF8String:pathBuffer];
|
||||
tempIconDestinationURL = [NSURL fileURLWithPath:path];
|
||||
|
||||
CGImageDestinationRef imageDestination = NULL;
|
||||
if (@available(macOS 11, *)) {
|
||||
CFStringRef uti = (__bridge CFStringRef)[UTTypePNG identifier];
|
||||
imageDestination = CGImageDestinationCreateWithURL((CFURLRef)tempIconDestinationURL, uti, 1, NULL);
|
||||
} else {
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
|
||||
imageDestination = CGImageDestinationCreateWithURL((CFURLRef)tempIconDestinationURL, kUTTypePNG, 1, NULL);
|
||||
#pragma clang diagnostic pop
|
||||
}
|
||||
if (imageDestination != NULL) {
|
||||
CGImageDestinationAddImageFromSource(imageDestination, imageSource, imageIndex, (CFDictionaryRef)@{});
|
||||
if (CGImageDestinationFinalize(imageDestination)) {
|
||||
iconAuthorizationItem.valueLength = strlen(pathBuffer);
|
||||
iconAuthorizationItem.value = pathBuffer;
|
||||
|
||||
authorizationEnvironment.count = 1;
|
||||
authorizationEnvironment.items = &iconAuthorizationItem;
|
||||
}
|
||||
|
||||
CFRelease(imageDestination);
|
||||
}
|
||||
authorizationEnvironment.count = 1;
|
||||
authorizationEnvironment.items = &iconAuthorizationItem;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
CFRelease(imageSource);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
// This should prompt up the authorization dialog if necessary
|
||||
OSStatus copyStatus = AuthorizationCopyRights(auth, &rights, &authorizationEnvironment, flags, NULL);
|
||||
@@ -251,9 +255,11 @@
|
||||
}
|
||||
}
|
||||
|
||||
if (tempIconDestinationURL != nil) {
|
||||
[fileManager removeItemAtURL:tempIconDestinationURL error:NULL];
|
||||
#if FETCH_BUNDLE_ICON_FOR_AUTH
|
||||
if (tempIconDestinationPath != nil) {
|
||||
[[NSFileManager defaultManager] removeItemAtPath:tempIconDestinationPath error:NULL];
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
Boolean submittedJob = false;
|
||||
@@ -310,7 +316,7 @@
|
||||
return status;
|
||||
}
|
||||
|
||||
- (NSString *)pathForBundledTool:(NSString *)toolName extension:(NSString *)extension fromBundle:(NSBundle *)bundle
|
||||
- (NSString *)pathForBundledTool:(NSString *)toolName extension:(NSString *)extension fromBundle:(NSBundle *)bundle SPU_OBJC_DIRECT
|
||||
{
|
||||
// If the path extension is empty, we don't want to add a "." at the end
|
||||
NSString *nameWithExtension = (extension.length > 0) ? [toolName stringByAppendingPathExtension:extension] : toolName;
|
||||
@@ -325,10 +331,17 @@
|
||||
} else {
|
||||
auxiliaryToolURL = [bundle URLForAuxiliaryExecutable:nameWithExtension];
|
||||
}
|
||||
assert(auxiliaryToolURL != nil);
|
||||
|
||||
if (auxiliaryToolURL == nil) {
|
||||
SULog(SULogLevelError, @"Error: Cannot retrieve path for auxiliary tool: %@", nameWithExtension);
|
||||
return nil;
|
||||
}
|
||||
|
||||
NSURL *resolvedAuxiliaryToolURL = [auxiliaryToolURL URLByResolvingSymlinksInPath];
|
||||
assert(resolvedAuxiliaryToolURL != nil);
|
||||
if (resolvedAuxiliaryToolURL == nil) {
|
||||
SULog(SULogLevelError, @"Error: Cannot retrieve resolved path for auxiliary tool path: %@", auxiliaryToolURL.path);
|
||||
return nil;
|
||||
}
|
||||
|
||||
return resolvedAuxiliaryToolURL.path;
|
||||
}
|
||||
@@ -370,14 +383,21 @@ BOOL SPUSystemNeedsAuthorizationAccessForBundlePath(NSString *bundlePath)
|
||||
return needsAuthorization;
|
||||
}
|
||||
|
||||
static BOOL SPUUsesSystemDomainForBundlePath(NSString *path, NSString *installationType, BOOL rootUser)
|
||||
static BOOL SPUUsesSystemDomainForBundlePath(NSString *path, BOOL rootUser
|
||||
#if SPARKLE_BUILD_PACKAGE_SUPPORT
|
||||
, NSString *installationType
|
||||
#endif
|
||||
)
|
||||
{
|
||||
if (!rootUser) {
|
||||
#if SPARKLE_BUILD_PACKAGE_SUPPORT
|
||||
if ([installationType isEqualToString:SPUInstallationTypeGuidedPackage]) {
|
||||
return YES;
|
||||
} else if ([installationType isEqualToString:SPUInstallationTypeInteractivePackage]) {
|
||||
return NO;
|
||||
} else {
|
||||
} else
|
||||
#endif
|
||||
{
|
||||
return SPUSystemNeedsAuthorizationAccessForBundlePath(path);
|
||||
}
|
||||
} else {
|
||||
@@ -387,16 +407,66 @@ static BOOL SPUUsesSystemDomainForBundlePath(NSString *path, NSString *installat
|
||||
}
|
||||
}
|
||||
|
||||
// Note: do not pass untrusted information such as paths to the installer and progress agent tools, when we can find them ourselves here
|
||||
- (void)launchInstallerWithHostBundlePath:(NSString *)hostBundlePath updaterIdentifier:(NSString *)updaterIdentifier authorizationPrompt:(NSString *)authorizationPrompt installationType:(NSString *)installationType allowingDriverInteraction:(BOOL)allowingDriverInteraction completion:(void (^)(SUInstallerLauncherStatus, BOOL))completionHandler
|
||||
// Note: do not pass information which can we compute ourselves here, such as paths to the installer and progress agent tools
|
||||
- (void)launchInstallerWithHostBundlePath:(NSString *)hostBundlePath mainBundlePath:(NSString *)mainBundlePath installationType:(NSString *)installationType allowingDriverInteraction:(BOOL)allowingDriverInteraction completion:(void (^)(SUInstallerLauncherStatus, BOOL))completionHandler
|
||||
{
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
if (completionHandler == NULL) {
|
||||
SULog(SULogLevelError, @"Error: Failed to retrieve completionHandler (nil)");
|
||||
return;
|
||||
}
|
||||
|
||||
if (hostBundlePath == nil) {
|
||||
SULog(SULogLevelError, @"Error: Failed to retrieve hostBundlePath (nil)");
|
||||
completionHandler(SUInstallerLauncherFailure, NO);
|
||||
return;
|
||||
}
|
||||
|
||||
if (mainBundlePath == nil) {
|
||||
SULog(SULogLevelError, @"Error: Failed to retrieve mainBundlePath (nil)");
|
||||
completionHandler(SUInstallerLauncherFailure, NO);
|
||||
return;
|
||||
}
|
||||
|
||||
NSBundle *mainBundle = [NSBundle bundleWithPath:mainBundlePath];
|
||||
if (mainBundle == nil) {
|
||||
SULog(SULogLevelError, @"Error: Failed to retrieve mainBundle from path: %@", mainBundlePath);
|
||||
completionHandler(SUInstallerLauncherFailure, NO);
|
||||
return;
|
||||
}
|
||||
|
||||
SUHost *mainBundleHost = [[SUHost alloc] initWithBundle:mainBundle];
|
||||
|
||||
// We use SUHost.name property, so an application
|
||||
// or Sparkle helper application can override its name with SUBundleName key
|
||||
NSString *mainBundleName = mainBundleHost.name;
|
||||
|
||||
// This updaterIdentifier is just used for authorization prompt
|
||||
NSString *updaterIdentifier;
|
||||
NSString *mainBundleIdentifier = mainBundle.bundleIdentifier;
|
||||
if (mainBundleIdentifier != nil) {
|
||||
updaterIdentifier = mainBundleIdentifier;
|
||||
} else {
|
||||
// Should be unlikely
|
||||
updaterIdentifier = mainBundleHost.name;
|
||||
}
|
||||
|
||||
if (installationType == nil) {
|
||||
SULog(SULogLevelError, @"Error: Failed to retrieve installationType (nil)");
|
||||
completionHandler(SUInstallerLauncherFailure, NO);
|
||||
return;
|
||||
}
|
||||
|
||||
// We could do a sort of preflight Authorization test instead of testing if we are running as root,
|
||||
// but I think this is not necessarily a better approach. We have to chown() the launcher cache directory later on,
|
||||
// and that is not necessarily related to a preflight test. It's more related to being ran under a root / different user from the active GUI session
|
||||
BOOL rootUser = (geteuid() == 0);
|
||||
|
||||
BOOL inSystemDomain = SPUUsesSystemDomainForBundlePath(hostBundlePath, installationType, rootUser);
|
||||
BOOL inSystemDomain = SPUUsesSystemDomainForBundlePath(hostBundlePath, rootUser
|
||||
#if SPARKLE_BUILD_PACKAGE_SUPPORT
|
||||
, installationType
|
||||
#endif
|
||||
);
|
||||
|
||||
NSBundle *hostBundle = [NSBundle bundleWithPath:hostBundlePath];
|
||||
if (hostBundle == nil) {
|
||||
@@ -428,7 +498,7 @@ static BOOL SPUUsesSystemDomainForBundlePath(NSString *path, NSString *installat
|
||||
return;
|
||||
}
|
||||
|
||||
// We do however have to copy the progress tool app somewhere safe due to its external depedencies
|
||||
// We do however have to copy the progress tool app somewhere safe due to its external dependencies
|
||||
NSString *progressToolResourcePath = [self pathForBundledTool:@""SPARKLE_INSTALLER_PROGRESS_TOOL_NAME extension:@"app" fromBundle:ourBundle];
|
||||
|
||||
if (progressToolResourcePath == nil) {
|
||||
@@ -437,26 +507,10 @@ static BOOL SPUUsesSystemDomainForBundlePath(NSString *path, NSString *installat
|
||||
return;
|
||||
}
|
||||
|
||||
// It may be tempting here to validate/match the signature of the installer and progress tool, however this is not very reliable
|
||||
// We can't compare the signature of this framework/XPC service (depending how it's run) to the host bundle because
|
||||
// they could be different (eg: take a look at sparkle-cli). We also can't easily tell if the signature of the service/framework is the same as the bundle it's inside.
|
||||
// The service/framework also need not even be signed in the first place. We'll just assume for now the original bundle hasn't been tampered with
|
||||
|
||||
NSString *rootLauncherCachePath = [[SPULocalCacheDirectory cachePathForBundleIdentifier:hostBundleIdentifier] stringByAppendingPathComponent:@"Launcher"];
|
||||
|
||||
[SPULocalCacheDirectory removeOldItemsInDirectory:rootLauncherCachePath];
|
||||
|
||||
NSString *launcherCachePath = [SPULocalCacheDirectory createUniqueDirectoryInDirectory:rootLauncherCachePath];
|
||||
if (launcherCachePath == nil) {
|
||||
SULog(SULogLevelError, @"Failed to create cache directory for progress tool in %@", rootLauncherCachePath);
|
||||
completionHandler(SUInstallerLauncherFailure, inSystemDomain);
|
||||
return;
|
||||
}
|
||||
|
||||
SUFileManager *fileManager = [[SUFileManager alloc] init];
|
||||
|
||||
NSString *userName;
|
||||
NSString *homeDirectory;
|
||||
uid_t uid = 0;
|
||||
gid_t gid = 0;
|
||||
if (!rootUser) {
|
||||
// Normal path
|
||||
homeDirectory = NSHomeDirectory();
|
||||
@@ -467,9 +521,6 @@ static BOOL SPUUsesSystemDomainForBundlePath(NSString *path, NSString *installat
|
||||
} else {
|
||||
// As the root user we need to obtain the user name and home directory reflecting
|
||||
// the user's console session.
|
||||
|
||||
uid_t uid = 0;
|
||||
gid_t gid = 0;
|
||||
CFStringRef userNameRef = SCDynamicStoreCopyConsoleUser(NULL, &uid, &gid);
|
||||
if (userNameRef == NULL) {
|
||||
SULog(SULogLevelError, @"Failed to retrieve user name from the console user");
|
||||
@@ -485,7 +536,35 @@ static BOOL SPUUsesSystemDomainForBundlePath(NSString *path, NSString *installat
|
||||
completionHandler(SUInstallerLauncherFailure, inSystemDomain);
|
||||
return;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// It may be tempting here to validate/match the signature of the installer and progress tool, however this is not very reliable
|
||||
// We can't compare the signature of this framework/XPC service (depending how it's run) to the host bundle because
|
||||
// they could be different (eg: take a look at sparkle-cli). We also can't easily tell if the signature of the service/framework is the same as the bundle it's inside.
|
||||
// The service/framework also need not even be signed in the first place. We'll just assume for now the original bundle hasn't been tampered with
|
||||
NSString *cachePath = rootUser ?
|
||||
[SPULocalCacheDirectory cachePathForBundleIdentifier:hostBundleIdentifier userName:userName] :
|
||||
[SPULocalCacheDirectory cachePathForBundleIdentifier:hostBundleIdentifier];
|
||||
|
||||
NSString *rootLauncherCachePath = [cachePath stringByAppendingPathComponent:@"Launcher"];
|
||||
|
||||
[SPULocalCacheDirectory removeOldItemsInDirectory:rootLauncherCachePath];
|
||||
|
||||
NSDictionary<NSFileAttributeKey, id> *fileAttributes = rootUser ?
|
||||
@{NSFileOwnerAccountID: @(uid), NSFileGroupOwnerAccountID: @(gid)} :
|
||||
nil;
|
||||
|
||||
NSString *launcherCachePath = [SPULocalCacheDirectory createUniqueDirectoryInDirectory:rootLauncherCachePath intermediateDirectoryFileAttributes:fileAttributes];
|
||||
|
||||
if (launcherCachePath == nil) {
|
||||
SULog(SULogLevelError, @"Failed to create cache directory for progress tool in %@", rootLauncherCachePath);
|
||||
completionHandler(SUInstallerLauncherFailure, inSystemDomain);
|
||||
return;
|
||||
}
|
||||
|
||||
SUFileManager *fileManager = [[SUFileManager alloc] init];
|
||||
|
||||
if (rootUser) {
|
||||
// Ensure the console user has ownership of the launcher cache directory
|
||||
// Otherwise the updater may not launch and not be able to clean up itself
|
||||
NSError *changeOwnerAndGroupError = nil;
|
||||
@@ -507,7 +586,7 @@ static BOOL SPUUsesSystemDomainForBundlePath(NSString *path, NSString *installat
|
||||
return;
|
||||
}
|
||||
|
||||
SUInstallerLauncherStatus installerStatus = [self submitInstallerAtPath:installerPath withHostBundle:hostBundle updaterIdentifier:updaterIdentifier userName:userName homeDirectory:homeDirectory authorizationPrompt:authorizationPrompt inSystemDomain:inSystemDomain rootUser:rootUser];
|
||||
SUInstallerLauncherStatus installerStatus = [self submitInstallerAtPath:installerPath withHostBundle:hostBundle iconBundlePath:mainBundle.bundlePath updaterIdentifier:updaterIdentifier userName:userName homeDirectory:homeDirectory mainBundleName:mainBundleName inSystemDomain:inSystemDomain rootUser:rootUser];
|
||||
|
||||
BOOL submittedProgressTool = NO;
|
||||
if (installerStatus == SUInstallerLauncherSuccess) {
|
||||
|
||||
@@ -11,6 +11,6 @@
|
||||
|
||||
@protocol SUInstallerLauncherProtocol
|
||||
|
||||
- (void)launchInstallerWithHostBundlePath:(NSString *)hostBundlePath updaterIdentifier:(NSString *)updaterBundleIdentifier authorizationPrompt:(NSString *)authorizationPrompt installationType:(NSString *)installationType allowingDriverInteraction:(BOOL)allowingDriverInteraction completion:(void (^)(SUInstallerLauncherStatus, BOOL))completionHandler;
|
||||
- (void)launchInstallerWithHostBundlePath:(NSString *)hostBundlePath mainBundlePath:(NSString *)mainBundlePath installationType:(NSString *)installationType allowingDriverInteraction:(BOOL)allowingDriverInteraction completion:(void (^)(SUInstallerLauncherStatus, BOOL))completionHandler;
|
||||
|
||||
@end
|
||||
@@ -8,6 +8,8 @@
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "SUInstallerLauncher.h"
|
||||
#import "SULog.h"
|
||||
#import "SUCodeSigningVerifier.h"
|
||||
|
||||
@interface ServiceDelegate : NSObject <NSXPCListenerDelegate>
|
||||
@end
|
||||
@@ -17,6 +19,27 @@
|
||||
- (BOOL)listener:(NSXPCListener *)__unused listener shouldAcceptNewConnection:(NSXPCConnection *)newConnection {
|
||||
// This method is where the NSXPCListener configures, accepts, and resumes a new incoming NSXPCConnection.
|
||||
|
||||
// Validate connection of clients to avoid any client from using the service.
|
||||
// This is a policy, not a security critical enforcement.
|
||||
{
|
||||
NSError *validationError = nil;
|
||||
SUValidateConnectionStatus validationStatus = [SUCodeSigningVerifier validateConnection:newConnection options: SUValidateConnectionOptionDefault error:&validationError];
|
||||
switch (validationStatus) {
|
||||
case SUValidateConnectionStatusSetCodeSigningRequirementSuccess:
|
||||
break;
|
||||
case SUValidateConnectionStatusSetNoRequirementSuccess:
|
||||
break;
|
||||
case SUValidateConnectionStatusAPIFailure:
|
||||
case SUValidateConnectionStatusCodeSigningRequirementFailure:
|
||||
case SUValidateConectionNoSupportedValidationMethodFailure:
|
||||
SULog(SULogLevelError, @"Error: Installer XPC Service is rejecting new connection due to failing validation of XPC connection with status %lu and error: %@", validationStatus, validationError.localizedDescription);
|
||||
|
||||
[newConnection invalidate];
|
||||
|
||||
return NO;
|
||||
}
|
||||
}
|
||||
|
||||
// Configure the connection.
|
||||
// First, set the interface that the exported object implements.
|
||||
newConnection.exportedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUInstallerLauncherProtocol)];
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
#import "SUInstallerStatusProtocol.h"
|
||||
|
||||
// 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 SUInstallerStatus : NSObject <SUInstallerStatusProtocol>
|
||||
SPU_OBJC_DIRECT_MEMBERS @interface SUInstallerStatus : NSObject <SUInstallerStatusProtocol>
|
||||
|
||||
- (instancetype)initWithRemote:(BOOL)remote;
|
||||
|
||||
|
||||
@@ -11,21 +11,15 @@
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
|
||||
@interface SUInstallerStatus ()
|
||||
|
||||
@property (nonatomic, copy) void (^invalidationBlock)(void);
|
||||
@property (nonatomic) NSXPCConnection *connection;
|
||||
|
||||
@end
|
||||
|
||||
@implementation SUInstallerStatus
|
||||
{
|
||||
NSXPCConnection *_connection;
|
||||
|
||||
void (^_invalidationBlock)(void);
|
||||
|
||||
BOOL _remote;
|
||||
}
|
||||
|
||||
@synthesize invalidationBlock = _invalidationBlock;
|
||||
@synthesize connection = _connection;
|
||||
|
||||
- (instancetype)initWithRemote:(BOOL)remote
|
||||
{
|
||||
self = [super init];
|
||||
@@ -39,39 +33,42 @@
|
||||
{
|
||||
if (_remote) {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
self.invalidationBlock = invalidationHandler;
|
||||
self->_invalidationBlock = [invalidationHandler copy];
|
||||
});
|
||||
} else {
|
||||
self.invalidationBlock = invalidationHandler;
|
||||
_invalidationBlock = [invalidationHandler copy];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)_setServiceName:(NSString *)serviceName
|
||||
- (void)_setServiceName:(NSString *)serviceName SPU_OBJC_DIRECT
|
||||
{
|
||||
NSXPCConnection *connection = [[NSXPCConnection alloc] initWithMachServiceName:serviceName options:(NSXPCConnectionOptions)0];
|
||||
|
||||
connection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUStatusInfoProtocol)];
|
||||
|
||||
self.connection = connection;
|
||||
_connection = connection;
|
||||
|
||||
__weak SUInstallerStatus *weakSelf = self;
|
||||
self.connection.interruptionHandler = ^{
|
||||
__weak __typeof__(self) weakSelf = self;
|
||||
_connection.interruptionHandler = ^{
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[weakSelf.connection invalidate];
|
||||
__typeof__(self) strongSelf = weakSelf;
|
||||
if (strongSelf != nil) {
|
||||
[strongSelf->_connection invalidate];
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
self.connection.invalidationHandler = ^{
|
||||
_connection.invalidationHandler = ^{
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
SUInstallerStatus *strongSelf = weakSelf;
|
||||
__typeof__(self) strongSelf = weakSelf;
|
||||
if (strongSelf != nil) {
|
||||
strongSelf.connection = nil;
|
||||
strongSelf->_connection = nil;
|
||||
[strongSelf _invokeInvalidationBlock];
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
[self.connection resume];
|
||||
[_connection resume];
|
||||
}
|
||||
|
||||
- (void)setServiceName:(NSString *)serviceName
|
||||
@@ -89,10 +86,10 @@
|
||||
{
|
||||
if (_remote) {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[(id<SUStatusInfoProtocol>)self.connection.remoteObjectProxy probeStatusInfoWithReply:reply];
|
||||
[(id<SUStatusInfoProtocol>)self->_connection.remoteObjectProxy probeStatusInfoWithReply:reply];
|
||||
});
|
||||
} else {
|
||||
[(id<SUStatusInfoProtocol>)self.connection.remoteObjectProxy probeStatusInfoWithReply:reply];
|
||||
[(id<SUStatusInfoProtocol>)_connection.remoteObjectProxy probeStatusInfoWithReply:reply];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -100,18 +97,18 @@
|
||||
{
|
||||
if (_remote) {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[(id<SUStatusInfoProtocol>)self.connection.remoteObjectProxy probeStatusConnectivityWithReply:reply];
|
||||
[(id<SUStatusInfoProtocol>)self->_connection.remoteObjectProxy probeStatusConnectivityWithReply:reply];
|
||||
});
|
||||
} else {
|
||||
[(id<SUStatusInfoProtocol>)self.connection.remoteObjectProxy probeStatusConnectivityWithReply:reply];
|
||||
[(id<SUStatusInfoProtocol>)_connection.remoteObjectProxy probeStatusConnectivityWithReply:reply];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)_invokeInvalidationBlock
|
||||
- (void)_invokeInvalidationBlock SPU_OBJC_DIRECT
|
||||
{
|
||||
if (self.invalidationBlock != nil) {
|
||||
self.invalidationBlock();
|
||||
self.invalidationBlock = nil;
|
||||
if (_invalidationBlock != nil) {
|
||||
_invalidationBlock();
|
||||
_invalidationBlock = nil;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -119,8 +116,8 @@
|
||||
- (void)invalidate
|
||||
{
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[self.connection invalidate];
|
||||
self.connection = nil;
|
||||
[self->_connection invalidate];
|
||||
self->_connection = nil;
|
||||
|
||||
[self _invokeInvalidationBlock];
|
||||
});
|
||||
|
||||
@@ -6,9 +6,13 @@
|
||||
// Copyright © 2016 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#if INSTALLER_STATUS_XPC_SERVICE_EMBEDDED
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "SUInstallerStatusProtocol.h"
|
||||
|
||||
@interface SUXPCInstallerStatus : NSObject <SUInstallerStatusProtocol>
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
@@ -6,22 +6,19 @@
|
||||
// Copyright © 2016 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#if INSTALLER_STATUS_XPC_SERVICE_EMBEDDED
|
||||
|
||||
#import "SUXPCInstallerStatus.h"
|
||||
|
||||
|
||||
#include "AppKitPrevention.h"
|
||||
|
||||
@interface SUXPCInstallerStatus ()
|
||||
|
||||
@property (nonatomic) NSXPCConnection *connection;
|
||||
@property (nonatomic, copy) void (^invalidationBlock)(void);
|
||||
|
||||
@end
|
||||
|
||||
@implementation SUXPCInstallerStatus
|
||||
|
||||
@synthesize connection = _connection;
|
||||
@synthesize invalidationBlock = _invalidationBlock;
|
||||
{
|
||||
NSXPCConnection *_connection;
|
||||
|
||||
void (^_invalidationBlock)(void);
|
||||
}
|
||||
|
||||
- (instancetype)init
|
||||
{
|
||||
@@ -30,14 +27,17 @@
|
||||
_connection = [[NSXPCConnection alloc] initWithServiceName:@INSTALLER_STATUS_BUNDLE_ID];
|
||||
_connection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUInstallerStatusProtocol)];
|
||||
|
||||
__weak SUXPCInstallerStatus *weakSelf = self;
|
||||
__weak __typeof__(self) weakSelf = self;
|
||||
_connection.invalidationHandler = ^{
|
||||
[weakSelf invokeInvalidation];
|
||||
};
|
||||
|
||||
_connection.interruptionHandler = ^{
|
||||
[weakSelf invokeInvalidation];
|
||||
[weakSelf.connection invalidate];
|
||||
__typeof__(self) strongSelf = weakSelf;
|
||||
if (strongSelf != nil) {
|
||||
[strongSelf invokeInvalidation];
|
||||
[strongSelf->_connection invalidate];
|
||||
}
|
||||
};
|
||||
|
||||
[_connection resume];
|
||||
@@ -47,42 +47,44 @@
|
||||
|
||||
- (void)setInvalidationHandler:(void (^)(void))invalidationHandler
|
||||
{
|
||||
self.invalidationBlock = invalidationHandler;
|
||||
_invalidationBlock = [invalidationHandler copy];
|
||||
|
||||
__weak SUXPCInstallerStatus *weakSelf = self;
|
||||
[(id<SUInstallerStatusProtocol>)self.connection.remoteObjectProxy setInvalidationHandler:^{
|
||||
__weak __typeof__(self) weakSelf = self;
|
||||
[(id<SUInstallerStatusProtocol>)_connection.remoteObjectProxy setInvalidationHandler:^{
|
||||
[weakSelf invokeInvalidation];
|
||||
}];
|
||||
}
|
||||
|
||||
- (void)setServiceName:(NSString *)serviceName
|
||||
{
|
||||
[(id<SUInstallerStatusProtocol>)self.connection.remoteObjectProxy setServiceName:serviceName];
|
||||
[(id<SUInstallerStatusProtocol>)_connection.remoteObjectProxy setServiceName:serviceName];
|
||||
}
|
||||
|
||||
- (void)probeStatusInfoWithReply:(void (^)(NSData * _Nullable installationInfoData))reply
|
||||
{
|
||||
[(id<SUInstallerStatusProtocol>)self.connection.remoteObjectProxy probeStatusInfoWithReply:reply];
|
||||
[(id<SUInstallerStatusProtocol>)_connection.remoteObjectProxy probeStatusInfoWithReply:reply];
|
||||
}
|
||||
|
||||
- (void)probeStatusConnectivityWithReply:(void (^)(void))reply
|
||||
{
|
||||
[(id<SUInstallerStatusProtocol>)self.connection.remoteObjectProxy probeStatusConnectivityWithReply:reply];
|
||||
[(id<SUInstallerStatusProtocol>)_connection.remoteObjectProxy probeStatusConnectivityWithReply:reply];
|
||||
}
|
||||
|
||||
- (void)invalidate
|
||||
{
|
||||
[(id<SUInstallerStatusProtocol>)self.connection.remoteObjectProxy invalidate];
|
||||
[self.connection invalidate];
|
||||
self.connection = nil;
|
||||
[(id<SUInstallerStatusProtocol>)_connection.remoteObjectProxy invalidate];
|
||||
[_connection invalidate];
|
||||
_connection = nil;
|
||||
}
|
||||
|
||||
- (void)invokeInvalidation
|
||||
{
|
||||
if (self.invalidationBlock != nil) {
|
||||
self.invalidationBlock();
|
||||
self.invalidationBlock = nil;
|
||||
if (_invalidationBlock != nil) {
|
||||
_invalidationBlock();
|
||||
_invalidationBlock = nil;
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
Loaded 100 of 430 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user