Compare commits

...
170 Commits
Author SHA1 Message Date
Sparkle-Bot 059ce91287 Update Package management files for version 2.2.1 2022-07-16 13:34:05 +00:00
Zorg cc0007de3a Update CHANGELOG 2022-07-16 06:25:46 -07:00
VinBoiSoft fe69cab530 Update Italian localization (#2192) 2022-07-09 12:43:10 -07:00
Zorg 14e511f901 Fix memory leaks when using generate_appcast (#2193)
We fix one memory leak when calculating sha's, one memory leak in the xar delta applying path, and avoid creating Bundles for reading the Sparkle framework version.

There are some other small leaks with the xar delta creation/applying code but since it's a legacy implementation and the APIs are undocumented I don't want to touch it too much.

The biggest culprit here is the leak when calculating sha's I believe, if you have many archive items.
2022-07-09 12:22:36 -07:00
Pavel Moiseenko 80e60279ee Make dark scroll bar in dark theme (#2187) 2022-07-04 09:40:44 -07:00
Sparkle-Bot c1bf68f91f Update Package management files for version 2.2.0 2022-07-02 18:55:40 +00:00
Zorg 4622061d8f Add deprecation of -s flag in CHANGELOG 2022-07-02 09:45:00 -07:00
Zorg a7e5320d6a Update CHANGELOG 2022-07-01 21:58:58 -07:00
basilTandaONe 90221e7a0f Update Greek localizations (#2185)
Co-authored-by: aONe
2022-07-01 21:47:16 -07:00
aONe 7c1cc5627b Updated Greek translation (#2184)
Fixes #2175, from @seitsme
2022-07-01 19:08:13 -07:00
Zorg bececc3738 Reset opportune time for showing new updates after preference changes (#2183)
Reset opportune time for showing update notice when updater starts as well.

Also update updater header API documentation and add private protocol for gentle scheduled reminder APIs that the updater uses.
2022-07-01 19:06:27 -07:00
1024jp a6984d3c02 Update Japanese localization (#2182)
* Add unlocalized strings to Japanese localization

* Remove unwanted spaces in Japanese localization
2022-06-30 21:54:01 -07:00
Zorg 102c4a4009 Fix Greek translation in "You are currently running version" string (#2181) 2022-06-28 22:26:20 -07:00
Zorg d2fd9a50e0 Use recovery suggestion key for update permission error (#2180) 2022-06-26 18:41:55 -07:00
Zorg d544d456e0 Synchronize usage of XPC connections to main queue (#2178) 2022-06-25 21:29:44 -07:00
Zorg b1f6c161d1 Use snprintf instead of sprintf to fix compile warning (#2179) 2022-06-25 16:41:32 -07:00
Zorg 06daa03196 Fix installer status xpc service bundle ID (#2177)
The bundle ID name broke after I was renaming the XPC Services for 2.2.
2022-06-25 15:00:33 -07:00
Zorg e64b7649f2 Deprecate -s flag and add --ed-key-file option to generate_appcast (#2170) 2022-06-24 21:19:10 -07:00
Sparkle-Bot 220c1edac1 Update Package management files for version 2.2.0-beta.2 2022-06-20 02:54:54 +00:00
Zorg e866f8d786 Update changelog for Sparkle 2.2 2022-06-19 18:18:31 -07:00
Zorg 2b6664cd8a Fix incorrect references in gentle reminder header documentation (#2165) 2022-06-19 17:39:52 -07:00
Zorg a913fe1355 Update external licenses text and add ed25519 (#2164) 2022-06-18 20:54:46 -07:00
Zorg 24b072c661 Update gentle reminder API documentation (#2163) 2022-06-18 12:59:13 -07:00
Zorg 2ddef5179e Bump initial installer message timeouts and declare daemon/agents as Interactive (#2162) 2022-06-18 11:40:45 -07:00
Sparkle-Bot 308ba94373 Update Package management files for version 2.2.0-beta.1 2022-06-13 02:31:58 +00:00
Zorg 9a1142a5b1 Fix pull request number in changelog 2022-06-12 19:23:40 -07:00
Zorg 4cb4974107 Update changelog to incorporate #2119 2022-06-12 18:59:27 -07:00
Zorg 5343305e3f Report friendly error if installation fails with no write permission (#2157)
On macOS 13 (Ventura) and later, installation could fail if Gatekeeper blocks app modifications. Note this is only applicable for external updaters like sparkle-cli where the updater and target bundle to update have different team identifiers.
2022-06-12 18:50:40 -07:00
Zorg 72c866f964 Update changelog with stage manager fix 2022-06-12 15:23:23 -07:00
Zorg 6808a94dbb Don't let status window make other active windows exit in stage manager (#2153)
We set the status window's collection behavior to full screen auxiliary. This is how the collection behavior for the update alerts and permission prompts are set up, but we never applied it to the status window.

With this change, bringing the status window up front (e.g, for downloading an update) does not push the other app's windows back into the stage manager tiles.
2022-06-12 15:19:55 -07:00
Zorg 38ed86dad0 Update Changelog for Sparkle 2.2 2022-06-11 19:33:13 -07:00
Zorg 15e8270291 Silence deprecation warnings when bumping deployment target (#2152) 2022-06-11 13:09:23 -07:00
Zorg d7942768b8 Validate permission bits of Sparkle executable for delta updates (#2151) 2022-06-11 11:21:52 -07:00
Zorg f126876d35 Show checking window back in focus and activate app if needed (#2150) 2022-06-10 21:53:58 -07:00
Zorg 9080bebc88 Fix Xcode 14 warnings (#2149)
* Upgrade project version

* Use +initialize instead of +load for debug warning
2022-06-10 21:30:42 -07:00
Zorg bf6dc6210f Update issue templates to reflect new discussions 2022-06-05 18:01:17 -07:00
Zorg 04d3c13043 Make displayVersionString non-null and update fallback documentation (#2139) 2022-06-05 16:35:04 -07:00
samschott a33bae7bad Use displayVersionString instead of versionString for OS version mismatch error message (#2138) 2022-06-05 16:34:37 -07:00
Zorg b3d31d254e Update create-draft-release CI action 2022-06-05 07:13:20 -07:00
Zorg 024eec0b09 Update Xcode in CI to 13.3.1 (#2137) 2022-06-04 23:16:33 -07:00
Zorg 9ba73525b0 Update last update check time when choosing to install update (#2136)
In the UI driver, this is when the user chooses to Install & Relaunch.

In the automatic download based driver, this is when Sparkle hands off responsibility to its delegate to install the update and they trigger the callback to relaunch the app.
2022-06-04 18:43:59 -07:00
Zorg 7ced6efba0 Remove SPUURLRequest class (#2134)
This class was only introduced because older OS versions we no longer support didn't have NSURLRequest implement NSSecureCoding.
2022-06-04 18:22:44 -07:00
Zorg fabd3e6c7b Schedule next update check if we're firing immediately (#2133)
Even if the updater is set to not automatically check for updates.

This fixes a bug where an update cycle may not complete if the automatic update driver first started, and the update should have been resumed but automatic update checks were disabled by the developer.

The developer would have had to disable automatic update checks, check updates in the background themselves, have updates set to download automatically/silently, and be in a situation where the update would be deferred to non-silent update (for example, user requiring authorization to install, critical update being presented, info-only update being presented).
2022-06-04 14:03:03 -07:00
Zorg 58fa11ce04 Add standard user driver APIs for gentle scheduled update reminders (#2122)
* Log warning if gentle reminders aren't implemented for background app
* Don't let background running app steal focus from other apps except at launch
* Don't set update alert window level to floating for background apps
* Show update alert in back for currently active background apps
* Disable warnings for direct ivar access
* Center update status window to last update alert window shown
* Activate app from user initiated checks if it's not active
* Set systemHasBeenIdle to YES only if the app isn't preventing display sleep
* Don't make status window key if update alert wasn't key window
2022-06-04 13:14:01 -07:00
Zorg 503830bf24 Refine minimizing state for download/extraction/installation status (#2121)
Don't allow status window to be minimizable for non-app bundle updates due to atomicity concerns.

Add delegate method to allow developer to configure if they want the status window to be minimizable.
2022-05-08 11:12:12 -04:00
Zorg 2bc9471ed1 Delay showing scheduled update alert if application is active (#2120)
We wait until a more opportune time when the app becomes re-activated, but if too much time 
has passed we will show the update anyway. A few exceptions are:

* App just launched
* User has been idle on their machine
* User initiates update check themselves
2022-05-08 10:32:14 -04:00
Zorg 339e26984e Add support for running framework and CLI as root (#2119)
When the framework or sparkle-cli is run as root, we always launch the installer (Autoupdate) in the system domain.

For the progress tool agent, we chown() the copied Updater.app so the Updater app has proper ownership of it (and clean it up later). The progress tool app may not be able to clean up the parent directory, but that's okay and will be garbage collected on a later run.

To get the username and home directory for the user session when running the framework as root, we use the SecurityConfiguration framework. Sparkle needs and depends on an active GUI user login session. If a user ssh's in to install an update, that user must be the same as the active logged in user.

Installing interactive based package updates as root is not supported. For sparkle-cli, we disallow using --interactive when running as root.

An additional error exit code is added for sparkle-cli when ran as root and trying to install a interactive based package update, which is unsupported.
2022-05-07 09:33:27 -04:00
Zorg 9042c8dbd9 Fall back to regular update if delta update fails to download (#2118)
Also log out the download failure when a delta update fails to download (such as a 404 error for example).

Additionally, add a check to make sure that top-level appcast items cannot be delta update items.
2022-05-01 22:58:29 -07:00
Eitot 180f8975cf Replace deprecated code with newer APIs (#2112)
* Use UniformTypeIdentifiers framework to replace deprecated types

kUTType* constants are deprecated since macOS 12. The UniformTypeIdentifiers framework is available since the macOS 11 SDK.

* Replace renamed constants

* Use API_AVAILABLE macro instead of __OSX_AVAILABLE
2022-04-24 16:51:48 -07:00
Zorg d5b650bae7 Skip delta updates on exFAT and FAT32 file systems (#2115)
We don't support applying delta updates on these systems (due to lack of permission support), so we shouldn't even try downloading delta updates in this case.
2022-04-24 00:39:40 -07:00
Zorg 94719edeb3 Ignore custom icons set via resource forks in delta updates (#2114)
For creation, we will disallow creating delta updates if a custom resource fork icon data is found in either the old or app bundles.

For applying, we will just ignore the icon data when performing hash verification and continue applying the patch.
2022-04-24 00:38:42 -07:00
Eitot c33a416b53 Update localisations (#2113)
* Remove duplicate localization identifiers

Some localizations have multiple identifiers, e.g. Canadian French has "fr-CA", "fr_ca" and "fr_CA" and Norwegian Bokmål has "nb" and "no" (though "no" can include Norwegian Nynorsk, Xcode seems to treat it as Bokmål and therefore a duplicate of "nb"). This commit removes superfluous identifiers and keeps the identifier that Xcode uses by default.

This also removes the no.lproj/ directory which contains either obsolete localized strings or strings that are present in nb.lproj/ too.

Furthermore, this renames the .lproj/ directories for "pt_PT"/"pt_BR" to "pt-PT"/"pt-BR" since the latter identifiers are the default in Xcode.

* Update localizable strings to match the current localizations

Replaces the following characters in the localizable strings:
- ellipses (... → …)
- curly apostrophe (' → ’)
- em dashes (-- → —)
- non-breaking spaces

These were already used in the .strings files.

* Regenerate Sparkle.strings

This applies the changes in the previous commit to the strings files of the base localization.

This also removes the following strings, which are no longer present in the source:
- "%1$@ wants permission to update %2$@."	
- "%1$@ wants permission to update."
- "An error occurred while downloading the update feed."
- "An error occurred while installing the update. Please try again later."
- "An error occurred while relaunching %1$@, but the new version will be available next time you run %1$@."
- "Are you sure you want to skip this upgrade?"
- "Don't Skip"
- "Skip Upgrade"
- "The update is improperly signed."
- "You already have the newest version of %@."
- "B", "GB", "KB" and "MB"

* Update localized Sparkle.strings

This applies the changes in the previous commits to the strings files of the localizations.

* Re-import localizations

This updates the .strings files using xcodebuild to:
- remove obsolete localizable strings,
- incorporate (changed) localization comments and
- replace UTF-16 encoded .strings files with UTF-8.

* Update Dutch localization

* Update French localization

This replaces single quotes and spaces with apostrophes and non-breaking spaces.
2022-04-24 00:36:29 -07:00
Eitot b0116ef31b Remove obsolete SDK checks (#2111)
Sparkle currently requires at least Xcode 12 (or the macOS 11 SDK), therefore fallbacks for older versions are no longer needed.

* Remove +isOperatingSystemAtLeastVersion: method

* Remove +operatingSystemVersion accessor method

* Remove SUTouchBarForwardDeclarations header
2022-04-23 23:34:20 -07:00
Eitot c0cf32c2b7 Remove obsolete fallbacks folder older OS versions (#2110)
* Remove fallback for NSByteCountFormatter

* Remove fallback for NSFont -monospacedDigitSystemFontOfSize:weight:
2022-04-21 20:00:33 -07:00
Zorg f250bead4b Update alert activation improvements (#2100)
* Don't activate app when bringing up update alert errors
* Don't set status window level to floating
* Make status window minimize-able after checking for updates
* Allow install button to have focus when app has just launched
* Reset install button focus when app becomes active again
2022-03-06 22:39:32 -08:00
Zorg 640e988a39 Change XPC Service product names to be more human readable (#2096)
They should not be bundle IDs because they may surface up in the UI.

Particularly, the Installer XPC Service may show up in the authorization prompt when authorization is required to install an update.
2022-03-06 21:26:56 -08:00
Zorg 183a930797 Ignore -Wobjc-interface-ivars warning (#2099) 2022-03-05 13:03:08 -08:00
BR Lingo 2f86c4f5fe Translation of new strings (#2094)
Adaptation of previously translated strings to use a more inclusive language
Translation consistency amendments
2022-02-26 19:52:28 -08:00
Sparkle-Bot 286edd1fa2 Update Package management files for version 2.1.0 2022-02-18 18:59:35 +00:00
Zorg 242ba4e5c4 Update changelog and documentation (#2089) 2022-02-12 14:06:39 -08:00
Dan Rigdon-Bel 8edc77fdb2 Use strcoll_l() for locale-independent comparisons (#2087)
The update code uses the compareFiles function to determine the sort order of file names in a directory, which is then compared with a list of files in the Sparkle update info. If the list of files of a directory from Sparkle's update is different than what is on disk, the Sparkle abandons the update and does a full download. This bug would prevent Sparkle from updating properly when the file lists are calculated on an English language system, but then checked on a destination Japanese system.

The fix is to use strcoll_l(), which is locale-independent, when comparing file names for sorting. This will ignore any locale changes the host application has made that could potentially affect Sparkle's sort order.
2022-02-08 20:38:55 -08:00
Sparkle-Bot eb938ad15a Update Package management files for version 2.1.0-beta.2 2022-02-05 07:02:18 +00:00
Zorg 18c751eaf9 Update CHANGELOG 2022-02-04 22:54:34 -08:00
Zorg 94b48c45e7 Preserve file system compression when applying delta updates (#2084) 2022-01-30 23:37:42 -08:00
Zorg e8fea3481a Add generate_appcast support for recent features (#2082)
We add support for:
* <sparkle:belowVersion> in <sparkle:informationalUpdate>
* <sparkle:ignoreSkippedUpgradesBelowVersion>
2022-01-30 15:20:55 -08:00
Zorg 8ea4d705f5 Add option to ignore skipped upgrades (#2081)
Normally when a major upgrade is skipped, subsequent updates for that major release are skipped. This element however allows publishing updates that ignore the user skipping the major version before a specific sub-release.
2022-01-29 23:02:45 -08:00
Zorg ac2ef612bc Don't let skipping a major version to skip subsequent major versions (#2079) 2022-01-29 10:37:09 -08:00
Zorg 84252a64f8 Add sparkle:belowVersion element for informational updates (#2080)
This allows marking all updates below a specific version as informational only.

A new element (sparkle:belowVersion) was introduced this over a new attribute for sparkle:version due to compatibility reasons.
2022-01-29 10:36:11 -08:00
Zorg 930ea303fd Add sparkle:belowVersion element for informational updates (#2080)
This allows marking all updates below a specific version as informational only.

A new element (sparkle:belowVersion) was introduced this over a new attribute for sparkle:version due to compatibility reasons.
2022-01-29 10:35:24 -08:00
Sparkle-Bot 452472ee3e Update Package management files for version 2.1.0-beta.1 2022-01-24 03:00:42 +00:00
Zorg d4499956e7 Update CHANGELOG for 2.1.0 2022-01-23 18:40:00 -08:00
Zorg 91bccdf0ad Verify code signing in generate_appcast (#2077)
In generate_appcast we:

* Validate code signing integrity of new updates
* Add hidden flag to disable checking for nested code during validation
* Warn if new and old apps have differing signing identities when generating deltas
2022-01-23 14:46:52 -08:00
Zorg 89e20a490d Add hidden option to generate_appcast to set max CDATA threshold (#2075) 2022-01-22 20:58:53 -08:00
Zorg 9e45a78e6f Verify applying delta patch in generate_appcast (#2076) 2022-01-22 20:14:45 -08:00
Zorg 92d8b2bee6 Add verify and account options for signing updates (#2074)
Accounts are intended to be used for when working on products that belong to different organizations. This way multiple keys related to Sparkle can be stored in the keychain.

We also add a --verify option to sign_update which allows verifying that updates are signed correctly.
2022-01-22 18:48:02 -08:00
ZorgandEric Shapiro 6bed29c481 Add check for http statusCode on file downloads (#2073)
Co-authored-by: Eric Shapiro
2022-01-22 13:03:01 -08:00
Zorg fa9bfc1fc4 Fix unsteady progress when installing updates (#2072)
Also add -showInstallingUpdateWithApplicationTerminated: to SPUUserDriver which replaces -showInstallingUpdate and -showSendingTerminationSignal
2022-01-22 12:07:45 -08:00
Zorg 05abb2f7e4 Fix version compare not treating '2.1.0' and '2.1' as being equal (#2065) 2022-01-18 00:07:56 -08:00
Zorg c029b98efb Fix progress bar and button alignment for checking updates (#2066) 2022-01-18 00:05:05 -08:00
Zorg c30f6fe7fb Calculate hash of file for delta updates without using mmap (#2067) 2022-01-18 00:04:40 -08:00
digitalMoksha 403209b818 Preserve the Entitlements directory in podspec (#2062)
In order to code sign Sparkle when installing via a Pod, the `Entitlements` directory needs to be available.
2022-01-16 12:53:09 -08:00
Zorg 1641371e83 Warn and validate against irregular permissions for delta patches (#2061)
* Only track 0755 permissions for symbolic links

Also warn the user when encountering symbolic links that have a non-standard permission mode.

* Warn users when bad or irregular permissions are encountered
2022-01-15 23:00:59 -08:00
Zorg 1f538981c3 Reference XPC Service names from build setting variables (#2060) 2022-01-13 19:25:47 -08:00
Zorg 0a152ed02d Update FileManager APIs (#2059) 2022-01-09 22:30:10 -08:00
Zorg b05c058219 Silence deprecations and use modern NSSecureCoding APIs (#2058) 2022-01-09 19:25:28 -08:00
Zorg 3bd1b25513 Simplify tracking of file permissions for deltas (#2057)
Also fixes minor issue where change in permissions wasn't printed in correct format when applying a patch in verbose mode.
2022-01-09 18:20:50 -08:00
Zorg 41f953d77b Fix minor binary delta issues and make version 3 the default (#2055) 2022-01-08 21:23:15 -08:00
Zorg 51ee14c3d3 Add UI tests for delta updates and automatic updates (#2054) 2022-01-08 18:05:07 -08:00
Zorg f6396aecfb Add heuristics for binary delta when files move to other directories (#2053)
We have one heuristic for when a .framework version changes, and another for when a file with the same name moves to another location.

To support this, we added a clone + binary diff command.

Also document and improve the format.
2022-01-08 11:48:27 -08:00
Zorg 71fc8d7b11 Add additional options to delta tools (#2052) 2022-01-04 00:14:45 -08:00
Zorg 23fc577184 Add new version 3 binary delta archive format (#2051)
This new format introduces:

* A new container format which stores metadata in a way that is more efficient for compression, decompression, and size. Creation time can be 2x faster, apply time can be a few seconds faster, size savings can be 500 KB - couple of MB due to metadata alone.
* An array of supported compression formats including lzma, bzip2, zlib and more. We now default to lzma which is as competitive as bzip2 (which we were using in version 2 format) in applying/creation times, but can save several MB on size.
* Tracking of files from an old app being replicated in different locations in the new app. This can track unchanged files being renamed and can result in significant savings if the files are large.

Version 2 format is still the default. To use version 3, pass --version=3 to BinaryDelta when creating a patch. We will switch the default to version 3 later. generate_appcast support is upcoming.
2022-01-02 11:35:51 -08:00
Zorg a1add127eb Update pull request templates and Xcode CI version to 13.2.1 (#2048) 2021-12-29 23:23:55 -08:00
Zorg fc44085602 Isolate xar usage in its own archive type for delta patches (#2047)
Also remove support for creating and applying version 1 delta files. Version 2 delta files have been supported by Sparkle 1.10 and later.
2021-12-29 22:41:08 -08:00
Sparkle-Bot 85d3fa2e0e Update Package management files for version 2.0.0 2021-12-26 22:59:45 +00:00
Zorg 81b281b596 Fix readme typo 2021-12-26 14:43:44 -08:00
Zorg ee3f8f3285 Update changelog and readme for Sparkle 2 (#2040) 2021-12-26 14:42:31 -08:00
Zorg 26f1209fe9 Fix incorrect xz log warning in make release (2.x) (#2045) 2021-12-25 00:52:56 -08:00
Sparkle-Bot 2195ee0883 Update Package management files for version 2.0.0-rc.1 2021-12-12 05:35:16 +00:00
Zorg 92c8142354 Fix Cocoapods badge URL 2021-12-11 19:57:32 -08:00
Zorg 1d04bd44ab Update README (#2038)
Add SPM compatible badge. Update for soon anticipated release of Sparkle 2.
2021-12-11 19:54:39 -08:00
Zorg 017f8f733e Add and update Carthage binary json distribution file on release (#2036) 2021-12-11 11:07:39 -08:00
Eitot b37fa239db Update Dutch and German localization (#2034) 2021-12-08 17:52:51 -08:00
Sparkle-Bot 831e9b4eb7 Update Package.swift and Sparkle.podspec for version 2.0.0-beta.6 2021-12-06 07:11:10 +00:00
Zorg 0a19f6f30d Document how to implement error based delegate methods in Swift (#2033) 2021-12-05 22:56:48 -08:00
Zorg 3a64116913 Update and review internal documentation (#2030) 2021-12-04 22:59:17 -08:00
Zorg 1ef42e9d1c Add apfs dmg unarchiving test (#2028) 2021-11-25 15:53:19 -05:00
Zorg c500487077 Improve pipe usage when unarchiving files (#2027) 2021-11-24 19:21:53 -05:00
Zorg acc4674c3e Fix volume detection being wrong in rare cases (#2026) 2021-11-24 11:33:04 -05:00
Zorg 39cedd4092 Fix unarchiving job being blocked when passed bad input (#2023) 2021-11-24 11:16:31 -05:00
Zorg 4517d61db5 Clarify signing error better (#2022) 2021-11-23 12:51:03 -05:00
Zorg 18fe269949 Update issue templates and minor capitalization issue (#2024) 2021-11-15 18:36:53 -08:00
Zorg 3a9c257691 Sync CHANGELOG with 1.x 2021-11-12 21:18:01 -08:00
Zorg 3fcc87086c Use user agent of updater bundle instead of the host bundle (#2020) 2021-11-12 21:09:31 -08:00
Zorg 4b6527424a Revert monotonic timer (#2018) 2021-11-12 15:14:01 -08:00
Sparkle-Bot 1adbbccf5e Update Package.swift and Sparkle.podspec for version 2.0.0-beta.5 2021-11-08 07:40:57 +00:00
Zorg d792a3a4a9 Fix create-draft-release not including pre-release suffix 2021-11-07 23:10:36 -08:00
Zorg 32bc43fa9b Update CHANGELOG to sync 1.27.1 changes 2021-11-07 20:13:49 -08:00
Zorg 4b9388d9aa Add full release notes link flag to generate_appcast (#2015) 2021-11-07 19:52:03 -08:00
Zorg c53ed49e5e Prevent potential rapid update checks using monotonic clock (2.x) (#2002) 2021-11-07 17:20:19 -08:00
Zorg 011a7dbb36 Revert "Use NSPanel for Sparkle windows to allow untitled windows form Dock (#2005)"
This reverts commit 52511a2b1c.

Reverting due to extended discussion in #2005
2021-11-07 16:28:02 -08:00
Ethan Wong fb1f5aafbe Launch test app in English for UI Tests for prevent local test failure. (#2014) 2021-11-07 15:08:43 -08:00
Ethan Wong 52511a2b1c Use NSPanel for Sparkle windows to allow untitled windows form Dock (#2005) 2021-11-07 09:03:55 -08:00
Zorg 5b312aa63e Fix null deference analyzer warnings (#2011) 2021-11-06 18:49:45 -07:00
Zorg 7cec9dbbe0 Ensure analyze step is only ran during pull requests 2021-11-06 18:07:37 -07:00
Zorg dde2b48af7 Post analyzer warnings in CI (#2010) 2021-11-06 17:59:30 -07:00
Zorg 9b6f962b31 Clarify documentation for canCheckForUpdates / sessionInProgress (#2009) 2021-11-06 15:38:25 -07:00
Zorg 1cba9f466d Whitelist about:srcdoc as a safe web URL (#2006)
The document I tested (after enabling javascript) was:

<description>
          <![CDATA[
              <p>Hello</p>
              <script>
              var iframe = document.createElement("iframe");
              iframe.srcdoc = `<!DOCTYPE html><p>Hello World!</p>`;
              document.body.appendChild(iframe);
              </script>
          ]]>
</description>
2021-11-06 14:52:09 -07:00
Zorg dbe1ae94f9 Update documentation, readme, changelog (#2004) 2021-11-06 02:17:49 -07:00
Zorg 45956ae5b0 Support relative links for fullReleaseNotesLink and enforce http(s) (#2003) 2021-11-06 01:56:50 -07:00
aONe 4c1bebedf9 fullReleaseNotesLink implemented (#2001) 2021-11-04 22:35:23 -07:00
Zorg 873a026627 Add project version inputs to create-draft-release workflow (#1998) 2021-10-30 22:55:27 -07:00
Zorg 9e54c5ca4d Sync 1.27.1 changelog (#1997) 2021-10-30 16:24:25 -07:00
Zorg 083790afa7 Don't use current date unless necessary when scheduling next update (2.x) (#1992) 2021-10-30 11:03:52 -07:00
Zorg c3030a6621 Revert "Set CODE_SIGN_INJECT_BASE_ENTITLEMENTS=NO for release (#1973)" (#1994)
For development we should include task-get-allow entitlements. For distribution if people use custom workflows, they need to properly re-sign the app without preserving this entitlement
2021-10-30 11:02:04 -07:00
Billy Gray e48edc6856 Adds standard user driver delegate method for responding to Version History button (#1989) 2021-10-29 16:59:48 -07:00
Zorg a81f8f3d2d Add safer handling for applying binary delta files (#1988) 2021-10-29 12:14:23 -07:00
Zorg 88c325a66f Bump default Xcode version to 13.1 (#1987) 2021-10-28 23:46:34 -07:00
Sparkle-Bot 0d43f88a83 Update Package.swift and Sparkle.podspec for version 2.0.0-beta.4 2021-10-24 04:04:45 +00:00
Zorg 2268b96c78 Bump project version to 2.0.0 beta 4 2021-10-23 20:56:35 -07:00
Zorg 3de3591d13 Fix order of inserting new appcast items in generate_appcast (#1982)
When we don't have any information for existing items, we have been appending new items below the existing ones. We should insert new items such that new items are inserted in order of version descending.
2021-10-23 20:21:54 -07:00
Zorg 7a9c1d76e6 Update Xcode 13 to 13.1 in CI (#1983) 2021-10-22 23:28:51 -07:00
Eitot fad6f1efe8 Update Dutch localisation (#1976) 2021-10-21 23:55:57 -07:00
Eitot 8045bf7af8 Update German localisation (#1977) 2021-10-21 23:54:39 -07:00
Zorg a436711133 Update CI to Xcode 12.5.1 2021-10-21 22:45:37 -07:00
Eitot ae7e7f12bc Update English localisation (#1978) 2021-10-21 22:40:34 -07:00
Zorg 80abad4477 Move XPC Services inside Sparkle framework (#1965)
Also bump FRAMEWORK_VERSION from A to B to work around system cache issues.
2021-10-17 23:35:09 -07:00
Zorg c9097ba42c Set CODE_SIGN_INJECT_BASE_ENTITLEMENTS=NO for release (#1973)
This removes the com.apple.security.get-task-allow entitlement on helper executable tools and XPC Services. While this is not a big deal, I don't think we should distribute executables with this entitlement which allows debugging them (with SIP / hardened runtime on). Note notarization ought to reject this entitlement with library validation enabled, so people must be getting around this anyway (either by using Xcode's Archive / Export which automatically strips this entitlement, or re-signing Sparkle tools without preserving entitlements).
2021-10-17 23:30:47 -07:00
Micah Moore 08f473fe82 Updates Version History French string translation. (#1975) 2021-10-11 20:11:45 -07:00
Zorg 6f8e8e4789 Make canCheckForUpdates property KVO compliant/observable (#1968)
* Make canCheckForUpdates property KVO compliant/observable

Also set updater session in progress when probing for update check interval to use.

* Add assert that driver must be nil in checkForUpdatesWithDriver:..
2021-10-03 12:58:00 -07:00
Daniel Jalkut a9d5a42768 When applying the system font size to the baseline CSS for the web view, use px instead of pt to specify the font size. This is consistent with best practices for web content, and alleviates a problem wherein the text in the web view, if not based on a full-fledged release notes HTML document, appears too large. (#1962) 2021-09-22 22:23:04 -07:00
Daniel Jalkut 9364c96336 Don't manipulate the default WebView preferences, which at least on Monterey beta returns a preferences instance with nil identifier and with autosaves set to YES. This has the unfortunate effect of causing Sparkle, when it uses SULegacyWebView, to pollute the host app's user defaults with high level WebKit defaults for user style sheet, font sizes, etc. Specifying a unique identifier as well as turning autosaves off should both ensure Sparkle doesn't impose app-wide defaults on the host app, and also avoid littering the host app's preference file with identifier-prefixed defaults. (#1961) 2021-09-22 19:14:13 -07:00
Sparkle-Bot ed9fa9bfed Update Package.swift and Sparkle.podspec for version 2.0.0-beta.3 2021-09-19 23:54:50 +00:00
Zorg 21b264543d Update version to 2.0.0-beta.3 (2003) (#1959) 2021-09-19 16:48:03 -07:00
Zorg eba1734f09 Fix issues with standard updater controller initialization (#1958)
* Fix init'ing updater delegates in standard updater controller in nibs

* Convert updaterDelegate/userDriverDelegate properties to ivars

This should allow connecting outlets in IB while disallowing setting them programmatically.
2021-09-19 16:32:43 -07:00
Zorg 1dea970512 Update changelog and documentation (#1956)
* Update author to Sparkle Project when generating documentation

* Sync change log from 1.27.0

* Add recommendation to not call checkForUpdatesInBackground directly

* Add testing documentation for latsUpdateCheckDate

* Fix formatting with user driver header documentation
2021-09-19 08:44:01 -07:00
Zorg 0f53f65241 Fix not being able to show resumed update in utmost focus (#1948)
This fixes a minor bug where canCheckForUpdates returned NO on a user initiated update check that shows an update that was already downloaded / begun installing. Now that it returns YES, the update can be shown in utmost focus by the user again.
2021-09-12 14:57:29 -07:00
Konstantin Zamyakin c60f12ab47 update some russian translates (#1947) 2021-09-11 13:14:38 -07:00
Mayur Pawashe 364e797676 Update cocoa pods badge to use shorter maxAge/cacheSeconds (#1945)
cacheSeconds has superseded maxAge.
2021-09-06 15:22:04 -07:00
Mayur Pawashe bf8216240c Add space 2021-09-06 12:05:37 -07:00
Mayur Pawashe f599a7a1a9 Update readme (#1944) 2021-09-06 12:04:50 -07:00
Vojtěch Koňařík 7096317766 Another localization update. (#1943) 2021-09-06 09:23:05 -07:00
Mayur Pawashe a8840953fe Fix podspec not using .xz (#1942) 2021-09-03 22:58:13 -07:00
Sparkle-Bot 76acd9cb5f Update Package.swift and Sparkle.podspec for version 2.0.0-beta.2 2021-09-04 05:11:08 +00:00
Mayur Pawashe e4b2d96faf Update Sparkle 2 build to beta 2 (#1941) 2021-09-03 22:04:43 -07:00
Mayur Pawashe 9229fc57b1 Add API reference homepage, fix formatting, and improve information (#1940) 2021-09-03 17:24:41 -07:00
Mayur Pawashe c396a53c6f Fix check to only validate XPC display versions in Debug (#1939) 2021-09-03 13:27:25 -07:00
Mayur Pawashe 2a67e2d732 Update podspec to include XPC Services and use https (#1935) 2021-09-03 10:16:37 -07:00
J-rg a135f1a1ee Fix German localization (#1931) 2021-09-03 08:39:28 -07:00
Mayur Pawashe 30361b0128 Use a custom bot personal access token (#1930)
This bot has owner access to the repo and should be able to push changes to protected branches, as long as the workflows are being ran from trusted branches / remotes.

Also extract changelog and use it for the draft.
2021-09-02 23:13:37 -07:00
Mayur Pawashe cce5edd78d Remove installer interaction delegate API / refactor finishing update cycle (#1925) 2021-09-02 23:12:26 -07:00
284 changed files with 11001 additions and 4586 deletions

No files matched your search

@@ -1,11 +1,24 @@
---
name: Enhancements and Bug Fixes
about: Found a bug? Want to implement a new feature?
about: Found a bug? Want to implement a new feature? Something else?
title: ''
assignees: ''
---
<!--
If this is a question or an idea, please consider posting in Discussions first:
https://github.com/sparkle-project/Sparkle/discussions
Otherwise the answer to your issue may already be 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
-->
## Summary
[provide general summary to the issue or enhancement and its rationale]
@@ -16,4 +29,4 @@ assignees: ''
## Version
[please specify versions of Sparkle this is applicable to; note new pull requests must be developed and landed in 2.x development branch first and the 1.x (master) branch is feature-frozen]
[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.]
@@ -1,6 +1,6 @@
---
name: Sparkle 2.x doesn't work in my app
about: Problems with using the beta version of Sparkle 2
about: Problems with integration, unexpected errors using Sparkle 2
title: ''
labels: '2.x'
assignees: ''
@@ -32,3 +32,5 @@ https://github.com/sparkle-project/Sparkle#troubleshooting
```
### 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]
@@ -1,6 +1,6 @@
---
name: Sparkle 1.x doesn't work in my app
about: Problems with integration, unexpected errors
about: Problems with integration, unexpected errors using Sparkle 1
title: ''
labels: '1.x'
assignees: ''
@@ -32,3 +32,5 @@ https://github.com/sparkle-project/Sparkle#troubleshooting
```
### 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]
+4 -10
View File
@@ -2,18 +2,12 @@
Fixes # (issue)
## Checklist:
## Misc Checklist
- [ ] My change is being tested and reviewed against the Sparkle 2.x branch. New changes must be developed on the 2.x development branch first.
- [ ] My change is being backported to master branch (Sparkle 1.x). Please create a separate pull request for 1.x, should it be backported. Note 1.x is feature frozen and is only taking bug fixes, localization updates, and critical OS adoption enhancements.
- [ ] I have reviewed and commented my code, particularly in hard-to-understand areas.
- [ ] 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
## Type of change
- [ ] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
- [ ] My change is or requires a documentation or localization 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
+46 -7
View File
@@ -10,17 +10,21 @@ jobs:
build:
strategy:
matrix:
xcode: ['xcode12.5', 'xcode13']
xcode: ['xcode12.5.1', 'xcode13.3.1']
include:
- xcode: 'xcode12.5'
xcode-path: '/Applications/Xcode_12.5.app/Contents/Developer'
- xcode: 'xcode13.3.1'
xcode-path: '/Applications/Xcode_13.3.1.app/Contents/Developer'
upload-dist: true
- xcode: 'xcode13'
xcode-path: '/Applications/Xcode_13.0.app/Contents/Developer'
upload-dist: false # In Beta, so no upload
run-analyzer: true
macos: 'macos-12'
- xcode: 'xcode12.5.1'
xcode-path: '/Applications/Xcode_12.5.1.app/Contents/Developer'
upload-dist: false
run-analyzer: false
macos: 'macos-11'
name: Build and Test Sparkle
runs-on: macos-11
runs-on: ${{ matrix.macos }}
steps:
- name: Checkout
@@ -48,6 +52,41 @@ jobs:
DEVELOPER_DIR: ${{ matrix.xcode-path }}
run: |
xcodebuild test-without-building -project Sparkle.xcodeproj -scheme UITests -configuration Debug -derivedDataPath build
- name: Analyze Sparkle
if: ${{ matrix.run-analyzer && github.event_name == 'pull_request' }}
env:
DEVELOPER_DIR: ${{ matrix.xcode-path }}
run: |
xcodebuild analyze -project Sparkle.xcodeproj -quiet -scheme Sparkle -configuration Release -derivedDataPath analyze > anaylze_output.txt
- name: Find Analyzed Warnings
if: ${{ success() && matrix.run-analyzer && github.event_name == 'pull_request' }}
id: findwarnings
env:
DEVELOPER_DIR: ${{ matrix.xcode-path }}
run: |
if grep -q "warning:" anaylze_output.txt; then
echo '::set-output name=analyzestatus::0'
else
echo '::set-output name=analyzestatus::1'
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)
- 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
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
env:
DEVELOPER_DIR: ${{ matrix.xcode-path }}
+52 -17
View File
@@ -2,10 +2,25 @@ name: "Create Draft Release"
env:
BUILDDIR: "build"
DEVELOPER_DIR: "/Applications/Xcode_12.5.1.app/Contents/Developer"
DEVELOPER_DIR: "/Applications/Xcode_13.3.1.app/Contents/Developer"
on:
workflow_dispatch
workflow_dispatch:
inputs:
marketingVersion:
description: "Marketing Version"
required: true
default: ""
prereleaseSuffix:
description: "Pre-release Suffix"
required: false
default: ""
buildVersion:
description: "Product Build"
required: true
default: ""
concurrency:
group: publish-release-${{ github.ref }}
@@ -14,42 +29,60 @@ concurrency:
jobs:
release:
name: "Publish binaries for release"
runs-on: macos-11
runs-on: macos-12
steps:
- name: "Checkout sources"
uses: actions/checkout@v2
with:
token: ${{ secrets.BOT_PERSONAL_ACCESS_TOKEN }}
submodules: true
fetch-depth: 0
- name: "Extract version information from project"
- name: "Extract latest changes from CHANGELOG"
run: |
MARKETING_VERSION=$(xcrun xcodebuild -showBuildSettings -project Sparkle.xcodeproj | grep -m 1 '^[[:space:]]*MARKETING_VERSION' | sed -E 's/.+=[[:space:]]+(.*)$/\1/')
echo "MARKETING_VERSION=${MARKETING_VERSION}" >> $GITHUB_ENV
./Configurations/generate_latest_changes.py > latest-changes.txt
- name: "Overwrite project versions in project"
run: |
IFS='.' read major minor patch <<< "${{ github.event.inputs.marketingVersion }}"
sed -E -i '' "s/SPARKLE_VERSION_MAJOR =.+/SPARKLE_VERSION_MAJOR = $major/g" ./Configurations/ConfigCommon.xcconfig
sed -E -i '' "s/SPARKLE_VERSION_MINOR =.+/SPARKLE_VERSION_MINOR = $minor/g" ./Configurations/ConfigCommon.xcconfig
sed -E -i '' "s/SPARKLE_VERSION_PATCH =.+/SPARKLE_VERSION_PATCH = $patch/g" ./Configurations/ConfigCommon.xcconfig
if [[ ! -z "${{ github.event.inputs.prereleaseSuffix }}" ]]; then
sed -E -i '' "s/SPARKLE_VERSION_SUFFIX =.*/SPARKLE_VERSION_SUFFIX = ${{ github.event.inputs.prereleaseSuffix }}/g" ./Configurations/ConfigCommon.xcconfig
else
sed -E -i '' "s/SPARKLE_VERSION_SUFFIX =.*/SPARKLE_VERSION_SUFFIX =/g" ./Configurations/ConfigCommon.xcconfig
fi
sed -E -i '' "s/CURRENT_PROJECT_VERSION =.+/CURRENT_PROJECT_VERSION = ${{ github.event.inputs.buildVersion }}/g" ./Configurations/ConfigCommon.xcconfig
git add ./Configurations/ConfigCommon.xcconfig
- name: "Determine if this is a pre-release version"
run: |
SPARKLE_VERSION_SUFFIX=$(xcrun xcodebuild -showBuildSettings -project Sparkle.xcodeproj | grep -m 1 '^[[:space:]]*SPARKLE_VERSION_SUFFIX' | sed -E 's/.+=[[:space:]]+(.*)$/\1/')
if [[ ! -z "$SPARKLE_VERSION_SUFFIX" ]]; then
if [[ ! -z "${{ github.event.inputs.prereleaseSuffix }}" ]]; then
echo "PRERELEASE_VERSION=true" >> $GITHUB_ENV
else
echo "PRERELEASE_VERSION=false" >> $GITHUB_ENV
fi
- name: "Create a temporary Git tag"
run: git tag "${{ env.MARKETING_VERSION }}"
- name: "Set up git and create tag"
run: |
git config user.name Sparkle-Bot
git config user.email sparkle.project.bot@gmail.com
git tag "${{ github.event.inputs.marketingVersion }}${{ github.event.inputs.prereleaseSuffix }}"
- name: "Build release distribution"
run: make release
env:
GITHUB_ACTOR: ${{ github.actor }}
GITHUB_REPOSITORY: ${{ github.repository }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
MARKETING_VERSION: ${{ env.MARKETING_VERSION }}
SPARKLE_VERSION_SUFFIX: ${{ env.SPARKLE_VERSION_SUFFIX }}
GITHUB_TOKEN: ${{ secrets.BOT_PERSONAL_ACCESS_TOKEN }}
- name: "Push the updated Swift package description"
- name: "Push the updated package description"
env:
GITHUB_TOKEN: ${{ secrets.BOT_PERSONAL_ACCESS_TOKEN }}
run: git push
- name: "Draft a release"
@@ -57,9 +90,11 @@ jobs:
with:
draft: true
prerelease: ${{ env.PRERELEASE_VERSION }}
name: "Sparkle ${{ env.MARKETING_VERSION }}"
tag_name: ${{ env.MARKETING_VERSION }}
name: "${{ github.event.inputs.marketingVersion }}${{ github.event.inputs.prereleaseSuffix }}"
tag_name: "${{ github.event.inputs.marketingVersion }}${{ github.event.inputs.prereleaseSuffix }}"
fail_on_unmatched_files: true
token: ${{ secrets.BOT_PERSONAL_ACCESS_TOKEN }}
body_path: latest-changes.txt
files: |
build/Build/Products/Release/Sparkle-*.tar.xz
build/Build/Products/Release/Sparkle-for-Swift-Package-Manager.zip
+3 -1
View File
@@ -78,7 +78,9 @@
__weak AgentConnection *weakSelf = self;
newConnection.interruptionHandler = ^{
[weakSelf.activeConnection invalidate];
dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf.activeConnection invalidate];
});
};
newConnection.invalidationHandler = ^{
+7 -5
View File
@@ -32,8 +32,8 @@
#include "AppKitPrevention.h"
#define FIRST_UPDATER_MESSAGE_TIMEOUT 7ull
#define RETRIEVE_PROCESS_IDENTIFIER_TIMEOUT 5ull
#define FIRST_UPDATER_MESSAGE_TIMEOUT 18ull
#define RETRIEVE_PROCESS_IDENTIFIER_TIMEOUT 8ull
/**
* Show display progress UI after a delay from starting the final part of the installation.
@@ -147,7 +147,9 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
__weak AppInstaller *weakSelf = self;
newConnection.interruptionHandler = ^{
[weakSelf.activeConnection invalidate];
dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf.activeConnection invalidate];
});
};
newConnection.invalidationHandler = ^{
@@ -203,7 +205,7 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
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 DSA keys
// 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) {
@@ -330,7 +332,7 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
if (identifier == SPUInstallationData && self.updateDirectoryPath == nil) {
dispatch_async(dispatch_get_main_queue(), ^{
// Mark that we have received the installation data
// Do not rely on eg: self.ipdateDirectoryPath != nil because we may set it to nil again if an early stage fails (i.e, archive extraction)
// 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]);
+19
View File
@@ -0,0 +1,19 @@
//
// SPUDeltaArchive.h
// Sparkle
//
// Created by Mayur Pawashe on 12/29/21.
// Copyright © 2021 Sparkle Project. All rights reserved.
//
#import <Foundation/Foundation.h>
@protocol SPUDeltaArchiveProtocol;
@class SPUDeltaArchiveHeader;
NS_ASSUME_NONNULL_BEGIN
// Opens patch file for reading and decodes the archive header
id<SPUDeltaArchiveProtocol> SPUDeltaArchiveReadPatchAndHeader(NSString *patchFile, SPUDeltaArchiveHeader * _Nullable __autoreleasing * _Nullable outHeader);
NS_ASSUME_NONNULL_END
+121
View File
@@ -0,0 +1,121 @@
//
// SPUDeltaArchive.m
// Sparkle
//
// Created by Mayur Pawashe on 12/29/21.
// Copyright © 2021 Sparkle Project. All rights reserved.
//
#import "SPUDeltaArchive.h"
#import "SPUDeltaArchiveProtocol.h"
#import "SPUSparkleDeltaArchive.h"
#import "SPUXarDeltaArchive.h"
#import <CommonCrypto/CommonDigest.h>
#include "AppKitPrevention.h"
SPUDeltaCompressionMode SPUDeltaCompressionModeDefault = (SPUDeltaCompressionMode)UINT8_MAX;
id<SPUDeltaArchiveProtocol> SPUDeltaArchiveReadPatchAndHeader(NSString *patchFile, SPUDeltaArchiveHeader * _Nullable __autoreleasing * _Nullable outHeader)
{
id<SPUDeltaArchiveProtocol> sparkleArchive = [[SPUSparkleDeltaArchive alloc] initWithPatchFileForReading:patchFile];
SPUDeltaArchiveHeader *header = [sparkleArchive readHeader];
if (header == nil) {
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
[sparkleArchive close];
id<SPUDeltaArchiveProtocol> xarArchive = [[SPUXarDeltaArchive alloc] initWithPatchFileForReading:patchFile];
SPUDeltaArchiveHeader *xarHeader = [xarArchive readHeader];
if (outHeader != NULL) {
*outHeader = xarHeader;
}
return xarArchive;
} else {
if (outHeader != NULL) {
*outHeader = nil;
}
return sparkleArchive;
}
} else {
if (outHeader != NULL) {
*outHeader = header;
}
return sparkleArchive;
}
}
@implementation SPUDeltaArchiveItem
@synthesize relativeFilePath = _relativeFilePath;
@synthesize itemFilePath = _itemFilePath;
@synthesize clonedRelativePath = _clonedRelativePath;
@synthesize sourcePath = _sourcePath;
@synthesize commands = _commands;
@synthesize xarContext = _xarContext;
@synthesize mode = _mode;
@synthesize codedDataLength = _codedDataLength;
- (instancetype)initWithRelativeFilePath:(NSString *)relativeFilePath commands:(SPUDeltaItemCommands)commands mode:(uint16_t)mode
{
self = [super init];
if (self != nil) {
_relativeFilePath = [relativeFilePath copy];
_commands = commands;
_mode = mode;
}
return self;
}
@end
@implementation SPUDeltaArchiveHeader
{
unsigned char _beforeTreeHash[CC_SHA1_DIGEST_LENGTH];
unsigned char _afterTreeHash[CC_SHA1_DIGEST_LENGTH];
}
@synthesize compression = _compression;
@synthesize compressionLevel = _compressionLevel;
@synthesize fileSystemCompression = _fileSystemCompression;
@synthesize majorVersion = _majorVersion;
@synthesize minorVersion = _minorVersion;
- (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
{
self = [super init];
if (self != nil)
{
_compression = compression;
_compressionLevel = compressionLevel;
_fileSystemCompression = fileSystemCompression;
_majorVersion = majorVersion;
_minorVersion = minorVersion;
memcpy(_beforeTreeHash, beforeTreeHash, sizeof(_beforeTreeHash));
memcpy(_afterTreeHash, afterTreeHash, sizeof(_afterTreeHash));
}
return self;
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdirect-ivar-access"
- (unsigned char *)beforeTreeHash
{
return _beforeTreeHash;
}
- (unsigned char *)afterTreeHash
{
return _afterTreeHash;
}
#pragma clang diagnostic pop
@end
+110
View File
@@ -0,0 +1,110 @@
//
// SPUDeltaArchiveProtocol.h
// Autoupdate
//
// Created by Mayur Pawashe on 12/28/21.
// Copyright © 2021 Sparkle Project. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "SPUDeltaCompressionMode.h"
NS_ASSUME_NONNULL_BEGIN
// Attributes for an item we extract/write to the archive
// Note: BinaryDiff cannot coexist together with Delete
typedef NS_ENUM(uint8_t, SPUDeltaItemCommands) {
SPUDeltaItemCommandEndMarker = 0,
SPUDeltaItemCommandDelete = (1u << 0),
SPUDeltaItemCommandExtract = (1u << 1),
SPUDeltaItemCommandModifyPermissions = (1u << 2),
SPUDeltaItemCommandBinaryDiff = (1u << 3),
SPUDeltaItemCommandClone = (1u << 4),
};
// Represents header for our archive
@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;
@property (nonatomic, readonly) SPUDeltaCompressionMode compression;
@property (nonatomic, readonly) uint8_t compressionLevel;
@property (nonatomic, readonly) bool fileSystemCompression;
@property (nonatomic, readonly) uint16_t majorVersion;
@property (nonatomic, readonly) uint16_t minorVersion;
@property (nonatomic, readonly) unsigned char *beforeTreeHash;
@property (nonatomic, readonly) unsigned char *afterTreeHash;
@end
// Represents an item we read or write to in our delta archive
@interface SPUDeltaArchiveItem : NSObject
- (instancetype)initWithRelativeFilePath:(NSString *)relativeFilePath commands:(SPUDeltaItemCommands)commands mode:(uint16_t)mode;
// The relative file path of the item, eg /Contents/MacOS/Foo
@property (nonatomic, readonly) NSString *relativeFilePath;
// For extraction, the path where the item will be extracted. For creation, the path to the item to add to the archive.
@property (nonatomic, nullable) NSString *itemFilePath;
// The relative file path of the originating item for clones. This may be null.
// For example, if /Contents/Resources/hello/foo.txt moves to /Contents/Resources/hello2/foo.txt, the former is the relative path
@property (nonatomic, nullable) NSString *clonedRelativePath;
// The source path of the item to extract file metadata from such as file size.
@property (nonatomic, nullable) NSString *sourcePath;
// The commands that describe the actions to take for this item.
@property (nonatomic, readonly) SPUDeltaItemCommands commands;
// Provided change in permissions for item or tracking file mode for the item
@property (nonatomic) uint16_t mode;
// Private properties
// xar_file context for Xar delta archiver
@property (nonatomic, nullable) const void *xarContext;
// Tracking length of item's data in data section, when encoding items and when extracting items
@property (nonatomic) uint64_t codedDataLength;
@end
// A protocol for reading and writing binary delta patches
// Operations must be done in order. The header must first be read or written before any other operations.
// For reading, file items cannot be extracted out of order.
@protocol SPUDeltaArchiveProtocol <NSObject>
@property (nonatomic, readonly, class) BOOL maySupportSafeExtraction;
// If non-nil, there was an error with reading or writing data from the archive
@property (nonatomic, readonly, nullable) NSError *error;
// Closes file for reading/writing, called in -dealloc if it's not called manually
- (void)close;
// For reading
// Retrieves metadata for the archive including major/minor version and expected bundle hashes
- (nullable SPUDeltaArchiveHeader *)readHeader;
// Enumerate through items in the patch file and read the path, attributes, permissions (if permission attribute is available), and way to stop enumeration
- (void)enumerateItems:(void (^)(SPUDeltaArchiveItem *item, BOOL *stop))itemHandler;
// Extract a file item from the patch file to a destination file
// The item's physical file path must be set as a destination
- (BOOL)extractItem:(SPUDeltaArchiveItem *)item;
// ------------
// For writing
// Set metadata for archive including major/minor version and expected bundle hashes
- (void)writeHeader:(SPUDeltaArchiveHeader *)header;
// Add item to patch file
// Physical file path must be provided if there is an extract or binary delta attribute
// Permissions are used only if there is a modify permissions attribute
- (void)addItem:(SPUDeltaArchiveItem *)item;
// Finishes encoding items after having added all of them
- (void)finishEncodingItems;
@end
NS_ASSUME_NONNULL_END
+22
View File
@@ -0,0 +1,22 @@
//
// SPUDeltaCompressionMode.h
// Sparkle
//
// Created by Mayur Pawashe on 1/3/22.
// Copyright © 2022 Sparkle Project. All rights reserved.
//
#import <Foundation/Foundation.h>
// Compression mode to use during patch creation
typedef NS_ENUM(uint8_t, SPUDeltaCompressionMode) {
SPUDeltaCompressionModeNone = 0,
SPUDeltaCompressionModeBzip2,
SPUDeltaCompressionModeLZMA,
SPUDeltaCompressionModeLZFSE,
SPUDeltaCompressionModeLZ4,
SPUDeltaCompressionModeZLIB
};
// For Swift access
extern SPUDeltaCompressionMode SPUDeltaCompressionModeDefault;
+107
View File
@@ -0,0 +1,107 @@
//
// SPUSparkleDeltaArchive.h
// Sparkle
//
// Created by Mayur Pawashe on 12/30/21.
// Copyright © 2021 Sparkle Project. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "SPUDeltaArchiveProtocol.h"
#import "SPUDeltaCompressionMode.h"
NS_ASSUME_NONNULL_BEGIN
#define SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN @"Sparkle Delta Archive"
#define SPARKLE_DELTA_ARCHIVE_ERROR_CODE_BAD_MAGIC 1
#define SPARKLE_DELTA_ARCHIVE_ERROR_CODE_BAD_COMPRESSION_VALUE 2
#define SPARKLE_DELTA_ARCHIVE_ERROR_CODE_BAD_CHUNK_SIZE 3
#define SPARKLE_DELTA_ARCHIVE_ERROR_CODE_BAD_CLONE_LOOKUP 4
#define SPARKLE_DELTA_ARCHIVE_ERROR_CODE_TOO_MANY_FILES 5
#define SPARKLE_DELTA_ARCHIVE_ERROR_CODE_LINK_TOO_LONG 6
/*
Modern container format for binary delta archives.
Delta archive format has four sections which are the header, the relative file path table, the commands, and the data blobs.
The relative file path table records all the file paths the archive needs to know about.
The commands are the operations to be recorded (eg: extract, clone, binary diff, delete).
The commands may additionally have more metadata such as file permission modes, relative path indexes in the case of clones, or file sizes for the data blobs.
The data blobs contain all file data from extract and binary diff outputs.
The implementation design of this archive is such that we do not seek backwards or skip ahead to fetch data.
We go through the archive when writing or reading from it in a single pass.
-- UNCOMPRESSED --
[ HEADER (part 1) ]
magic (length: 4)
compression (length: 1)
metadata (See format below. length: 1)
-- METADATA --
compressionLevel (bits [0, 4])
(bits [5, 6] reserved)
fileSystemCompression (bit 7)
-- COMPRESSED --
[ HEADER (part 2)]
majorVersion (length: 2)
minorVersion (length: 2)
beforeTreeHash (length: 40)
afterTreeHash (length: 40)
[ RELATIVE_FILE_PATH_TABLE ]
sizeOfRelativeFilePathTable (length: 8 bytes)
List of null terminated path strings joined together (N paths)
[ COMMANDS ]
[ Command ]
Set of command types for entry (length: 1 byte)
Additional metadata for command (see below section)
(M commands where M <= N paths)
(Indexes for commands refer to indexes to relative file path table, excluding extraneous trailing entries in relative path table used for clones)
(Last command must be a ZERO COMMAND (a null terminating command))
[COMMAND METADATA]
[COMMAND: DELETE]
N/A: no additional data
[COMMAND: MODIFY_PERMISSIONS]
fileMode (length: 2)
[COMMAND: CLONE_FILE]
sourceRelativePathIndex (length: 4)
[COMMAND: EXTRACT_FILE]
dataLength (length: 8 for regular files, 2 for symbolic links, 0 for directories)
[COMMAND: BINARY_DIFF_FILE]
dataLength (length: 8)
Note: These command types may be OR'd or combined. In those cases, different commands
that have the same attribute (eg dataLength) are not repeated. This list of metadata is also
in order in what will be encoded/decoded first.
EXTRACT_FILE and BINARY_DIFF_FILE cannot be combined.
CLONE_FILE and EXTRACT_FILE cannot be combined.
MODIFY_PERMISSIONS can be combined with either CLONE_FILE, EXTRACT_FILE, BINARY_DIFF_FILE, or just by itself.
CLONE_FILE can be combined with BINARY_DIFF_FILE or just by itself.
DELETE can be combined with EXTRACT_FILE, or just by itself. It is only combined with EXTRACT_FILE when the file type (regular, directory, or symlink) changes.
[ DATA_BLOBS ]
All raw binary data joined together
(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>
- (instancetype)initWithPatchFileForWriting:(NSString *)patchFile;
- (instancetype)initWithPatchFileForReading:(NSString *)patchFile;
@end
NS_ASSUME_NONNULL_END
File diff suppressed because it is too large. Load diff
+24
View File
@@ -0,0 +1,24 @@
//
// SPUXarDeltaArchive.h
// Autoupdate
//
// Created by Mayur Pawashe on 12/28/21.
// Copyright © 2021 Sparkle Project. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "SPUDeltaArchiveProtocol.h"
#import "SPUDeltaCompressionMode.h"
NS_ASSUME_NONNULL_BEGIN
// Legacy container format for binary delta archives
@interface SPUXarDeltaArchive : NSObject <SPUDeltaArchiveProtocol>
- (instancetype)initWithPatchFileForWriting:(NSString *)patchFile;
- (instancetype)initWithPatchFileForReading:(NSString *)patchFile;
@end
NS_ASSUME_NONNULL_END
+416
View File
@@ -0,0 +1,416 @@
//
// SPUXarDeltaArchive.m
// Autoupdate
//
// Created by Mayur Pawashe on 12/28/21.
// Copyright © 2021 Sparkle Project. All rights reserved.
//
#import "SPUXarDeltaArchive.h"
#include <xar/xar.h>
#include "SUBinaryDeltaCommon.h"
#import <Availability.h>
#import <CommonCrypto/CommonDigest.h>
#include "AppKitPrevention.h"
#if __MAC_OS_X_VERSION_MAX_ALLOWED >= 120000
#define HAS_XAR_GET_SAFE_PATH 1
#else
#define HAS_XAR_GET_SAFE_PATH 0
#endif
#if HAS_XAR_GET_SAFE_PATH
// This is preferred over xar_get_path (which is deprecated) when it's available
// Don't use OS availability for this API
extern char *xar_get_safe_path(xar_file_t f) __attribute__((weak_import));
#endif
// Xar attribute keys
#define BINARY_DELTA_ATTRIBUTES_KEY "binary-delta-attributes"
#define MAJOR_DIFF_VERSION_KEY "major-version"
#define MINOR_DIFF_VERSION_KEY "minor-version"
#define BEFORE_TREE_SHA1_KEY "before-tree-sha1"
#define AFTER_TREE_SHA1_KEY "after-tree-sha1"
#define DELETE_KEY "delete"
#define EXTRACT_KEY "extract"
#define BINARY_DELTA_KEY "binary-delta"
#define MODIFY_PERMISSIONS_KEY "mod-permissions"
// Errors
#define SPARKLE_DELTA_XAR_ARCHIVE_ERROR_DOMAIN @"Sparkle XAR Archive"
#define SPARKLE_DELTA_XAR_ARCHIVE_ERROR_CODE_OPEN_FAILURE 1
#define SPARKLE_DELTA_XAR_ARCHIVE_ERROR_CODE_ADD_FAILURE 2
#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
@synthesize x = _x;
@synthesize xarMode = _xarMode;
@synthesize patchFile = _patchFile;
@synthesize fileTable = _fileTable;
@synthesize error = _error;
- (instancetype)initWithPatchFileForWriting:(NSString *)patchFile
{
self = [super init];
if (self != nil) {
_patchFile = [patchFile copy];
_xarMode = WRITE;
_fileTable = [NSMutableDictionary dictionary];
}
return self;
}
- (instancetype)initWithPatchFileForReading:(NSString *)patchFile
{
self = [super init];
if (self != nil) {
_patchFile = [patchFile copy];
_xarMode = READ;
}
return self;
}
- (void)dealloc
{
[self close];
}
- (void)close
{
if (self.x != NULL) {
xar_close(self.x);
self.x = NULL;
}
}
// This indicates if safe extraction is available at compile time (SDK), but not if it's available at runtime.
+ (BOOL)maySupportSafeExtraction
{
return HAS_XAR_GET_SAFE_PATH;
}
- (nullable SPUDeltaArchiveHeader *)readHeader
{
NSString *patchFile = self.patchFile;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
// Sparkle's XAR delta archives have been superceded 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] }];
return nil;
}
self.x = x;
uint16_t majorDiffVersion = SUBinaryDeltaMajorVersionFirst;
uint16_t minorDiffVersion = 0;
NSString *expectedBeforeHash = nil;
NSString *expectedAfterHash = nil;
xar_subdoc_t subdoc;
for (subdoc = xar_subdoc_first(self.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
const char *value = NULL;
xar_subdoc_prop_get(subdoc, MAJOR_DIFF_VERSION_KEY, &value);
if (value != NULL) {
majorDiffVersion = (uint16_t)[@(value) intValue];
}
}
{
// available in version 2.0 or later
const char *value = NULL;
xar_subdoc_prop_get(subdoc, MINOR_DIFF_VERSION_KEY, &value);
if (value != NULL) {
minorDiffVersion = (uint16_t)[@(value) intValue];
}
}
// available in version 2.0 or later
{
const char *value = NULL;
xar_subdoc_prop_get(subdoc, BEFORE_TREE_SHA1_KEY, &value);
if (value != NULL) {
expectedBeforeHash = @(value);
}
}
// available in version 2.0 or later
{
const char *value = NULL;
xar_subdoc_prop_get(subdoc, AFTER_TREE_SHA1_KEY, &value);
if (value != NULL) {
expectedAfterHash = @(value);
}
}
}
}
unsigned char rawExpectedBeforeHash[CC_SHA1_DIGEST_LENGTH] = {0};
getRawHashFromDisplayHash(rawExpectedBeforeHash, expectedBeforeHash);
unsigned char rawExpectedAfterHash[CC_SHA1_DIGEST_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];
}
- (void)writeHeader:(SPUDeltaArchiveHeader *)header
{
NSString *patchFile = self.patchFile;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
// Sparkle's XAR delta archives have been superceded 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] }];
return;
}
self.x = x;
SPUDeltaCompressionMode compression = (header.compression == SPUDeltaCompressionModeDefault ? SPUDeltaCompressionModeBzip2 : header.compression);
uint8_t compressionLevel;
// Only 1 - 9 are valid, 0 is special case to use default level 9
if (header.compressionLevel <= 0 || header.compressionLevel > 9) {
compressionLevel = 9;
} else {
compressionLevel = header.compressionLevel;
}
switch (compression) {
case SPUDeltaCompressionModeNone:
xar_opt_set(x, XAR_OPT_COMPRESSION, XAR_OPT_VAL_NONE);
break;
case SPUDeltaCompressionModeBzip2: {
xar_opt_set(x, XAR_OPT_COMPRESSION, "bzip2");
char buffer[256] = {0};
snprintf(buffer, sizeof(buffer) - 1, "%d", compressionLevel);
xar_opt_set(x, XAR_OPT_COMPRESSIONARG, buffer);
break;
}
case SPUDeltaCompressionModeLZMA:
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."] }];
return;
}
}
xar_subdoc_t attributes = xar_subdoc_new(x, BINARY_DELTA_ATTRIBUTES_KEY);
xar_subdoc_prop_set(attributes, MAJOR_DIFF_VERSION_KEY, [[NSString stringWithFormat:@"%u", header.majorVersion] UTF8String]);
xar_subdoc_prop_set(attributes, MINOR_DIFF_VERSION_KEY, [[NSString stringWithFormat:@"%u", header.minorVersion] UTF8String]);
xar_subdoc_prop_set(attributes, BEFORE_TREE_SHA1_KEY, [displayHashFromRawHash(header.beforeTreeHash) UTF8String]);
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)
{
NSArray<NSString *> *rootRelativePathComponents = relativePath.pathComponents;
// Relative path must at least have starting "/" component and one more path component
if (rootRelativePathComponents.count < 2) {
return NULL;
}
NSArray<NSString *> *relativePathComponents = [rootRelativePathComponents subarrayWithRange:NSMakeRange(1, rootRelativePathComponents.count - 1)];
NSUInteger relativePathComponentsCount = relativePathComponents.count;
// Build parent files as needed until we get to our final file we want to add
// So if we get "Contents/Resources/foo.txt", we will first add "Contents" parent,
// then "Resources" parent, then "foo.txt" as the final entry we want to add
// 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
xar_file_t lastParent = NULL;
for (NSUInteger componentIndex = 0; componentIndex < relativePathComponentsCount; componentIndex++) {
NSArray<NSString *> *subpathComponents = [relativePathComponents subarrayWithRange:NSMakeRange(0, componentIndex + 1)];
NSString *subpathKey = [subpathComponents componentsJoinedByString:@"/"];
xar_file_t cachedFile = [fileTable[subpathKey] pointerValue];
if (cachedFile != NULL) {
lastParent = cachedFile;
} else {
xar_file_t newParent;
BOOL atLastIndex = (componentIndex == relativePathComponentsCount - 1);
NSString *lastPathComponent = subpathComponents.lastObject;
if (atLastIndex && filePath != nil) {
newParent = xar_add_frompath(x, lastParent, lastPathComponent.fileSystemRepresentation, filePath.fileSystemRepresentation);
} else {
newParent = xar_add_frombuffer(x, lastParent, lastPathComponent.fileSystemRepresentation, "", 1);
}
lastParent = newParent;
fileTable[subpathKey] = [NSValue valueWithPointer:newParent];
}
}
return lastParent;
}
- (void)addItem:(SPUDeltaArchiveItem *)item
{
if (self.error != nil) {
return;
}
NSString *relativeFilePath = item.relativeFilePath;
NSString *filePath = item.itemFilePath;
SPUDeltaItemCommands commands = item.commands;
uint16_t mode = item.mode;
xar_file_t newFile = _xarAddFile(self.fileTable, self.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] }];
return;
}
if ((commands & SPUDeltaItemCommandDelete) != 0) {
xar_prop_set(newFile, DELETE_KEY, "true");
}
if ((commands & SPUDeltaItemCommandExtract) != 0) {
xar_prop_set(newFile, EXTRACT_KEY, "true");
}
if ((commands & SPUDeltaItemCommandBinaryDiff) != 0) {
xar_prop_set(newFile, BINARY_DELTA_KEY, "true");
}
if ((commands & SPUDeltaItemCommandModifyPermissions) != 0) {
xar_prop_set(newFile, MODIFY_PERMISSIONS_KEY, [NSString stringWithFormat:@"%u", mode].UTF8String);
}
}
- (void)finishEncodingItems
{
// Items are already encoded when they are extracted prior
}
- (void)enumerateItems:(void (^)(SPUDeltaArchiveItem *, BOOL *))itemHandler
{
if (self.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)) {
char *pathCString;
#if HAS_XAR_GET_SAFE_PATH
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunguarded-availability-new"
if (xar_get_safe_path != NULL) {
pathCString = xar_get_safe_path(file);
}
#pragma clang diagnostic pop
else
#endif
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
pathCString = xar_get_path(file);
#pragma clang diagnostic pop
}
if (pathCString == NULL) {
continue;
}
NSString *relativePath = [[NSString alloc] initWithBytesNoCopy:pathCString length:strlen(pathCString) encoding:NSUTF8StringEncoding freeWhenDone:YES];
if (relativePath == nil) {
free(pathCString);
continue;
}
SPUDeltaItemCommands commands = 0;
{
const char *value = NULL;
if (xar_prop_get(file, DELETE_KEY, &value) == 0) {
commands |= SPUDeltaItemCommandDelete;
}
}
{
const char *value = NULL;
if (xar_prop_get(file, BINARY_DELTA_KEY, &value) == 0) {
commands |= SPUDeltaItemCommandBinaryDiff;
}
}
{
const char *value = NULL;
if (xar_prop_get(file, EXTRACT_KEY, &value) == 0) {
commands |= SPUDeltaItemCommandExtract;
}
}
uint16_t mode = 0;
{
const char *value = NULL;
if (xar_prop_get(file, MODIFY_PERMISSIONS_KEY, &value) == 0) {
commands |= SPUDeltaItemCommandModifyPermissions;
mode = (uint16_t)[@(value) intValue];
}
}
SPUDeltaArchiveItem *item = [[SPUDeltaArchiveItem alloc] initWithRelativeFilePath:relativePath commands:commands mode:mode];
item.xarContext = file;
itemHandler(item, &exitedEarly);
if (exitedEarly) {
break;
}
}
xar_iter_free(iter);
}
- (BOOL)extractItem:(SPUDeltaArchiveItem *)item
{
if (self.error != nil) {
return NO;
}
assert(item.itemFilePath != nil);
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] }];
return NO;
}
return YES;
}
@end
+315 -132
View File
@@ -8,104 +8,77 @@
#import "SUBinaryDeltaApply.h"
#import "SUBinaryDeltaCommon.h"
#include <CommonCrypto/CommonDigest.h>
#import "SPUDeltaArchiveProtocol.h"
#import "SPUDeltaArchive.h"
#import <CommonCrypto/CommonDigest.h>
#import <Foundation/Foundation.h>
#include "bspatch.h"
#include <stdio.h>
#include <stdlib.h>
#include <xar/xar.h>
#import <sys/stat.h>
#include "AppKitPrevention.h"
static BOOL applyBinaryDeltaToFile(xar_t x, xar_file_t file, NSString *sourceFilePath, NSString *destinationFilePath)
static BOOL applyBinaryDeltaToFile(NSString *patchFile, NSString *sourceFilePath, NSString *destinationFilePath)
{
NSString *patchFile = temporaryFilename(@"apply-binary-delta");
xar_extract_tofile(x, file, [patchFile fileSystemRepresentation]);
const char *argv[] = {"/usr/bin/bspatch", [sourceFilePath fileSystemRepresentation], [destinationFilePath fileSystemRepresentation], [patchFile fileSystemRepresentation]};
BOOL success = (bspatch(4, argv) == 0);
unlink([patchFile fileSystemRepresentation]);
return success;
}
BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFile, BOOL verbose, void (^progressCallback)(double progress), NSError *__autoreleasing *error)
BOOL applyBinaryDelta(NSString *source, NSString *finalDestination, NSString *patchFile, BOOL verbose, void (^progressCallback)(double progress), NSError *__autoreleasing *error)
{
xar_t x = xar_open([patchFile fileSystemRepresentation], READ);
if (!x) {
SPUDeltaArchiveHeader *header = nil;
id<SPUDeltaArchiveProtocol> archive = SPUDeltaArchiveReadPatchAndHeader(patchFile, &header);
if (archive.error != nil) {
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Unable to open %@. Giving up.", patchFile] }];
*error = archive.error;
}
return NO;
}
SUBinaryDeltaMajorVersion majorDiffVersion = FIRST_DELTA_DIFF_MAJOR_VERSION;
int minorDiffVersion = 0;
progressCallback(0/7.0);
NSString *expectedBeforeHashv1 = nil;
NSString *expectedAfterHashv1 = nil;
SUBinaryDeltaMajorVersion majorDiffVersion = header.majorVersion;
uint16_t minorDiffVersion = header.minorVersion;
NSString *expectedNewBeforeHash = nil;
NSString *expectedNewAfterHash = nil;
progressCallback(0/6.0);
xar_subdoc_t subdoc;
for (subdoc = xar_subdoc_first(x); subdoc; subdoc = xar_subdoc_next(subdoc)) {
if (!strcmp(xar_subdoc_name(subdoc), BINARY_DELTA_ATTRIBUTES_KEY)) {
const char *value = 0;
// available in version 2.0 or later
xar_subdoc_prop_get(subdoc, MAJOR_DIFF_VERSION_KEY, &value);
if (value)
majorDiffVersion = (SUBinaryDeltaMajorVersion)[@(value) intValue];
// available in version 2.0 or later
xar_subdoc_prop_get(subdoc, MINOR_DIFF_VERSION_KEY, &value);
if (value)
minorDiffVersion = [@(value) intValue];
// available in version 2.0 or later
xar_subdoc_prop_get(subdoc, BEFORE_TREE_SHA1_KEY, &value);
if (value)
expectedNewBeforeHash = @(value);
// available in version 2.0 or later
xar_subdoc_prop_get(subdoc, AFTER_TREE_SHA1_KEY, &value);
if (value)
expectedNewAfterHash = @(value);
// only available in version 1.0
xar_subdoc_prop_get(subdoc, BEFORE_TREE_SHA1_OLD_KEY, &value);
if (value)
expectedBeforeHashv1 = @(value);
// only available in version 1.0
xar_subdoc_prop_get(subdoc, AFTER_TREE_SHA1_OLD_KEY, &value);
if (value)
expectedAfterHashv1 = @(value);
}
}
if (majorDiffVersion < FIRST_DELTA_DIFF_MAJOR_VERSION) {
unsigned char *expectedBeforeHash = header.beforeTreeHash;
unsigned char *expectedAfterHash = header.afterTreeHash;
if (majorDiffVersion < SUBinaryDeltaMajorVersionFirst) {
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadCorruptFileError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Unable to identify diff-version %u in delta. Giving up.", majorDiffVersion] }];
}
return NO;
}
if (majorDiffVersion > LATEST_DELTA_DIFF_MAJOR_VERSION) {
if (majorDiffVersion < SUBinaryDeltaMajorVersionFirstSupported) {
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"A later version is needed to apply this patch (on major version %u, but patch requests version %u).", LATEST_DELTA_DIFF_MAJOR_VERSION, majorDiffVersion] }];
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadCorruptFileError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Applying version %u patches is no longer supported.", majorDiffVersion] }];
}
return NO;
}
BOOL usesNewTreeHash = MAJOR_VERSION_IS_AT_LEAST(majorDiffVersion, SUBeigeMajorVersion);
if (majorDiffVersion > SUBinaryDeltaMajorVersionLatest) {
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"A later version is needed to apply this patch (on major version %u, but patch requests version %u).", SUBinaryDeltaMajorVersionLatest, majorDiffVersion] }];
}
return NO;
}
// Reject patches that did not generate valid hierarchical xar container paths
// These will not succeed to patch using recent versions of BinaryDelta
if ([[archive class] maySupportSafeExtraction] && majorDiffVersion == SUBinaryDeltaMajorVersion2 && minorDiffVersion < 3) {
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadCorruptFileError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"This patch version (%u.%u) is too old and potentially unsafe to apply. Please re-generate the patch using the latest version of BinaryDelta or generate_appcast. New version %u.%u patches will still be compatible with older versions of Sparkle.", majorDiffVersion, minorDiffVersion, majorDiffVersion, latestMinorVersionForMajorVersion(majorDiffVersion)] }];
}
return NO;
}
NSString *expectedBeforeHash = usesNewTreeHash ? expectedNewBeforeHash : expectedBeforeHashv1;
NSString *expectedAfterHash = usesNewTreeHash ? expectedNewAfterHash : expectedAfterHashv1;
if (!expectedBeforeHash || !expectedAfterHash) {
if (expectedBeforeHash == nil || expectedAfterHash == nil) {
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadCorruptFileError userInfo:@{ NSLocalizedDescriptionKey: @"Unable to find before-sha1 or after-sha1 metadata in delta. Giving up." }];
}
@@ -117,10 +90,10 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi
fprintf(stderr, "Verifying source...");
}
progressCallback(1/6.0);
NSString *beforeHash = hashOfTreeWithVersion(source, majorDiffVersion);
if (!beforeHash) {
progressCallback(1/7.0);
unsigned char beforeHash[CC_SHA1_DIGEST_LENGTH] = {0};
if (!getRawHashOfTreeWithVersion(beforeHash, source, majorDiffVersion)) {
if (verbose) {
fprintf(stderr, "\n");
}
@@ -130,12 +103,12 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi
return NO;
}
if (![beforeHash isEqualToString:expectedBeforeHash]) {
if (memcmp(beforeHash, expectedBeforeHash, CC_SHA1_DIGEST_LENGTH) != 0) {
if (verbose) {
fprintf(stderr, "\n");
}
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Source doesn't have expected hash (%@ != %@). Giving up.", expectedBeforeHash, beforeHash] }];
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Source doesn't have expected hash (%@ != %@). Giving up.", displayHashFromRawHash(expectedBeforeHash), displayHashFromRawHash(beforeHash)] }];
}
return NO;
}
@@ -144,7 +117,17 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi
fprintf(stderr, "\nCopying files...");
}
progressCallback(2/6.0);
progressCallback(2/7.0);
// Make a temporary destination path if necessary
// If we want to apply file system compression after we're done applying, we'll need to use a different
// temporary path
NSString *destination;
if (header.fileSystemCompression) {
destination = [finalDestination.stringByDeletingLastPathComponent stringByAppendingPathComponent:[NSString stringWithFormat:@".tmp.%@", finalDestination.lastPathComponent]];
} else {
destination = finalDestination;
}
if (!removeTree(destination)) {
if (verbose) {
@@ -156,7 +139,7 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi
return NO;
}
progressCallback(3/6.0);
progressCallback(3/7.0);
if (!copyTree(source, destination)) {
if (verbose) {
@@ -168,20 +151,49 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi
return NO;
}
progressCallback(4/6.0);
BOOL hasExtractKeyAvailable = MAJOR_VERSION_IS_AT_LEAST(majorDiffVersion, SUBeigeMajorVersion);
progressCallback(4/7.0);
if (verbose) {
fprintf(stderr, "\nPatching...");
}
NSFileManager *fileManager = [[NSFileManager alloc] init];
xar_file_t file;
xar_iter_t iter = xar_iter_new();
for (file = xar_file_first(x, iter); file; file = xar_file_next(iter)) {
NSString *path = @(xar_get_path(file));
NSString *sourceFilePath = [source stringByAppendingPathComponent:path];
NSString *destinationFilePath = [destination stringByAppendingPathComponent:path];
// Ensure error is cleared out in advance
if (error != NULL) {
*error = nil;
}
[archive enumerateItems:^(SPUDeltaArchiveItem *item, BOOL *stop) {
NSString *relativePath = item.relativeFilePath;
if ([relativePath.pathComponents containsObject:@".."]) {
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileWriteUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Relative path '%@' contains '..' path component", relativePath] }];
}
*stop = YES;
return;
}
NSString *sourceFilePath = [source stringByAppendingPathComponent:relativePath];
NSString *destinationFilePath = [destination stringByAppendingPathComponent:relativePath];
{
NSString *destinationParentDirectory = destinationFilePath.stringByDeletingLastPathComponent;
NSDictionary<NSFileAttributeKey, id> *destinationParentDirectoryAttributes = [fileManager attributesOfItemAtPath:destinationParentDirectory error:NULL];
// It is OK for the directory parent to not exist if it has already been removed
if (destinationParentDirectoryAttributes != nil) {
// But if it does exist, make sure the entry in the parent directory we're looking at is good
// If it's inside a symlink, this is not good in any circumstance
NSString *fileType = destinationParentDirectoryAttributes[NSFileType];
if ([fileType isEqualToString:NSFileTypeSymbolicLink]) {
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileWriteUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to create patch because '%@' cannot be a symbolic link.", destinationParentDirectory] }];
}
*stop = YES;
return;
}
}
}
// Don't use -[NSFileManager fileExistsAtPath:] because it will follow symbolic links
BOOL fileExisted = verbose && [fileManager attributesOfItemAtPath:destinationFilePath error:nil];
@@ -189,112 +201,283 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi
// Files that have no property set that we check for will get ignored
// This is important because they aren't part of the delta, just part of the directory structure
const char *value;
if (!xar_prop_get(file, DELETE_KEY, &value) || (!hasExtractKeyAvailable && !xar_prop_get(file, DELETE_THEN_EXTRACT_OLD_KEY, &value))) {
SPUDeltaItemCommands commands = item.commands;
if ((commands & SPUDeltaItemCommandDelete) != 0) {
if (!removeTree(destinationFilePath)) {
if (verbose) {
fprintf(stderr, "\n");
}
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileWriteUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"%@ or %@: failed to remove %@", @DELETE_KEY, @DELETE_THEN_EXTRACT_OLD_KEY, destination] }];
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileWriteUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"delete: failed to remove %@", destination] }];
}
return NO;
}
if (!hasExtractKeyAvailable && !xar_prop_get(file, DELETE_KEY, &value)) {
if (verbose) {
fprintf(stderr, "\n❌ %s %s", VERBOSE_DELETED, [path fileSystemRepresentation]);
}
continue;
*stop = YES;
return;
}
removedFile = YES;
}
if (!xar_prop_get(file, BINARY_DELTA_KEY, &value)) {
if (!applyBinaryDeltaToFile(x, file, sourceFilePath, destinationFilePath)) {
if ((commands & SPUDeltaItemCommandClone) != 0 && (commands & SPUDeltaItemCommandBinaryDiff) == 0) {
NSString *clonedRelativePath = item.clonedRelativePath;
if ([clonedRelativePath.pathComponents containsObject:@".."]) {
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileWriteUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Relative path for clone '%@' contains '..' path component", clonedRelativePath] }];
}
*stop = YES;
return;
}
NSString *clonedOriginalPath = [source stringByAppendingPathComponent:clonedRelativePath];
// Ensure there isn't an item already at our destination
[fileManager removeItemAtPath:destinationFilePath error:NULL];
NSError *copyError = nil;
if (![fileManager copyItemAtPath:clonedOriginalPath toPath:destinationFilePath error:&copyError]) {
if (verbose) {
fprintf(stderr, "\n");
}
if (error != NULL) {
*error = copyError;
}
*stop = YES;
return;
}
if (verbose) {
fprintf(stderr, "\n✂️ %s %s -> %s", VERBOSE_CLONED, [clonedRelativePath fileSystemRepresentation], [relativePath fileSystemRepresentation]);
}
} else if ((commands & SPUDeltaItemCommandBinaryDiff) != 0) {
NSString *tempDiffFile = temporaryFilename(@"apply-binary-delta");
item.itemFilePath = tempDiffFile;
if (![archive extractItem:item]) {
if (verbose) {
fprintf(stderr, "\n");
}
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileWriteUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Unable to extract diffed file to %@", tempDiffFile], NSUnderlyingErrorKey: (NSError * _Nonnull)archive.error }];
}
*stop = YES;
return;
}
NSString *sourceDiffFilePath;
NSString *clonedRelativePath;
if ((commands & SPUDeltaItemCommandClone) != 0) {
clonedRelativePath = item.clonedRelativePath;
if ([clonedRelativePath.pathComponents containsObject:@".."]) {
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileWriteUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Relative path for clone '%@' contains '..' path component", clonedRelativePath] }];
}
*stop = YES;
return;
}
sourceDiffFilePath = [source stringByAppendingPathComponent:clonedRelativePath];
} else {
sourceDiffFilePath = sourceFilePath;
clonedRelativePath = nil;
}
if (!applyBinaryDeltaToFile(tempDiffFile, sourceDiffFilePath, destinationFilePath)) {
if (verbose) {
fprintf(stderr, "\n");
}
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileWriteUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Unable to patch %@ to destination %@", sourceFilePath, destinationFilePath] }];
}
return NO;
*stop = YES;
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) {
struct stat sourceFileInfo = {0};
if (lstat(sourceDiffFilePath.fileSystemRepresentation, &sourceFileInfo) != 0) {
if (verbose) {
fprintf(stderr, "\n");
}
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileWriteUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Unable to retrieve stat info from %@", sourceFilePath] }];
}
*stop = YES;
return;
}
if (chmod(destinationFilePath.fileSystemRepresentation, sourceFileInfo.st_mode) != 0) {
if (verbose) {
fprintf(stderr, "\n");
}
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileWriteNoPermissionError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Unable to modify permissions (%u) on file %@", sourceFileInfo.st_mode, destinationFilePath] }];
}
*stop = YES;
return;
}
}
if (verbose) {
fprintf(stderr, "\n🔨 %s %s", VERBOSE_PATCHED, [path fileSystemRepresentation]);
if ((commands & SPUDeltaItemCommandClone) != 0) {
fprintf(stderr, "\n🔨 %s %s -> %s", VERBOSE_PATCHED, [clonedRelativePath fileSystemRepresentation], [relativePath fileSystemRepresentation]);
} else {
fprintf(stderr, "\n🔨 %s %s", VERBOSE_PATCHED, [relativePath fileSystemRepresentation]);
}
}
} else if ((hasExtractKeyAvailable && !xar_prop_get(file, EXTRACT_KEY, &value)) || (!hasExtractKeyAvailable && xar_prop_get(file, MODIFY_PERMISSIONS_KEY, &value))) { // extract and permission modifications don't coexist
if (xar_extract_tofile(x, file, [destinationFilePath fileSystemRepresentation]) != 0) {
} else if ((commands & SPUDeltaItemCommandExtract) != 0) { // extract and permission modifications don't coexist
item.itemFilePath = destinationFilePath;
if (![archive extractItem:item]) {
if (verbose) {
fprintf(stderr, "\n");
}
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileWriteUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Unable to extract file to %@", destinationFilePath] }];
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileWriteUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Unable to extract file to %@", destinationFilePath], NSUnderlyingErrorKey: (NSError * _Nonnull)archive.error }];
}
return NO;
*stop = YES;
return;
}
if (verbose) {
if (fileExisted) {
fprintf(stderr, "\n✏️ %s %s", VERBOSE_UPDATED, [path fileSystemRepresentation]);
fprintf(stderr, "\n✏️ %s %s", VERBOSE_UPDATED, [relativePath fileSystemRepresentation]);
} else {
fprintf(stderr, "\n✅ %s %s", VERBOSE_ADDED, [path fileSystemRepresentation]);
fprintf(stderr, "\n✅ %s %s", VERBOSE_ADDED, [relativePath fileSystemRepresentation]);
}
}
} else if (verbose && removedFile) {
fprintf(stderr, "\n❌ %s %s", VERBOSE_DELETED, [path fileSystemRepresentation]);
fprintf(stderr, "\n❌ %s %s", VERBOSE_DELETED, [relativePath fileSystemRepresentation]);
}
if (!xar_prop_get(file, MODIFY_PERMISSIONS_KEY, &value)) {
mode_t mode = (mode_t)[[NSString stringWithUTF8String:value] intValue];
if ((commands & SPUDeltaItemCommandModifyPermissions) != 0) {
mode_t mode = (mode_t)item.mode;
if (!modifyPermissions(destinationFilePath, mode)) {
if (verbose) {
fprintf(stderr, "\n");
}
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileWriteNoPermissionError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Unable to modify permissions (%@) on file %@", @(value), destinationFilePath] }];
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileWriteNoPermissionError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Unable to modify permissions (%u) on file %@", mode, destinationFilePath] }];
}
return NO;
*stop = YES;
return;
}
if (verbose) {
fprintf(stderr, "\n👮 %s %s (0%o)", VERBOSE_MODIFIED, [path fileSystemRepresentation], mode);
fprintf(stderr, "\n👮 %s %s (0%o)", VERBOSE_MODIFIED, [relativePath fileSystemRepresentation], mode & PERMISSION_FLAGS);
}
}
}
xar_close(x);
progressCallback(5/6.0);
if (verbose) {
fprintf(stderr, "\nVerifying destination...");
}
NSString *afterHash = hashOfTreeWithVersion(destination, majorDiffVersion);
if (!afterHash) {
}];
[archive close];
// Set error from enumerating items if we have encountered an error and haven't set it yet
NSError *archiveError = archive.error;
if (archiveError != nil) {
if (verbose) {
fprintf(stderr, "\n");
}
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Unable to calculate hash of tree %@", destination] }];
}
return NO;
}
if (![afterHash isEqualToString:expectedAfterHash]) {
if (verbose) {
fprintf(stderr, "\n");
}
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Destination doesn't have expected hash (%@ != %@). Giving up.", expectedAfterHash, afterHash] }];
if (error != NULL && *error == nil) {
*error = archiveError;
}
removeTree(destination);
return NO;
}
progressCallback(6/6.0);
progressCallback(5/7.0);
// Re-apply file system compression is requested
if (header.fileSystemCompression) {
if (verbose) {
fprintf(stderr, "\nApplying file system compression...");
}
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.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);
}
}
if (!failedToApplyFileSystemCompression) {
[dittoTask waitUntilExit];
if (dittoTask.terminationStatus != 0) {
failedToApplyFileSystemCompression = YES;
fprintf(stderr, "\nWarning: ditto task for file compression returned exit status %d", dittoTask.terminationStatus);
}
}
if (failedToApplyFileSystemCompression) {
// Try to replace bundle normally
if (![fileManager replaceItemAtURL:[NSURL fileURLWithPath:finalDestination] withItemAtURL:[NSURL fileURLWithPath:destination isDirectory:YES] backupItemName:nil options:0 resultingItemURL:NULL error:error]) {
removeTree(destination);
return NO;
}
} else {
// Remove original copy
[fileManager removeItemAtURL:[NSURL fileURLWithPath:destination isDirectory:YES] error:NULL];
}
}
progressCallback(6/7.0);
if (verbose) {
fprintf(stderr, "\nVerifying destination...");
}
unsigned char afterHash[CC_SHA1_DIGEST_LENGTH] = {0};
if (!getRawHashOfTreeWithVersion(afterHash, finalDestination, majorDiffVersion)) {
if (verbose) {
fprintf(stderr, "\n");
}
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Unable to calculate hash of tree %@", finalDestination] }];
}
removeTree(finalDestination);
return NO;
}
if (memcmp(afterHash, expectedAfterHash, CC_SHA1_DIGEST_LENGTH) != 0) {
if (verbose) {
fprintf(stderr, "\n");
}
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Destination doesn't have expected hash (%@ != %@). Giving up.", displayHashFromRawHash(expectedAfterHash), displayHashFromRawHash(afterHash)] }];
}
removeTree(finalDestination);
return NO;
}
progressCallback(7/7.0);
if (verbose) {
fprintf(stderr, "\nDone!\n");
+29 -26
View File
@@ -10,33 +10,19 @@
#define SUBINARYDELTACOMMON_H
#import <Foundation/Foundation.h>
#import "SPUDeltaCompressionMode.h"
#include <fts.h>
#define PERMISSION_FLAGS (S_IRWXU | S_IRWXG | S_IRWXO | S_ISUID | S_ISGID | S_ISVTX)
#define IS_VALID_PERMISSIONS(mode) \
(((mode & PERMISSION_FLAGS) == 0755) || ((mode & PERMISSION_FLAGS) == 0644))
#define VALID_SYMBOLIC_LINK_PERMISSIONS 0755
// Enforcing Sparkle's executable permissions to be valid allows us to perform a preflight test before
// downloading delta items
#define VALID_SPARKLE_EXECUTABLE_PERMISSIONS 0755
#define APPLE_CODE_SIGN_XATTR_CODE_DIRECTORY_KEY "com.apple.cs.CodeDirectory"
#define APPLE_CODE_SIGN_XATTR_CODE_REQUIREMENTS_KEY "com.apple.cs.CodeRequirements"
#define APPLE_CODE_SIGN_XATTR_CODE_SIGNATURE_KEY "com.apple.cs.CodeSignature"
#define BINARY_DELTA_ATTRIBUTES_KEY "binary-delta-attributes"
#define MAJOR_DIFF_VERSION_KEY "major-version"
#define MINOR_DIFF_VERSION_KEY "minor-version"
#define BEFORE_TREE_SHA1_KEY "before-tree-sha1"
#define AFTER_TREE_SHA1_KEY "after-tree-sha1"
#define DELETE_KEY "delete"
#define EXTRACT_KEY "extract"
#define BINARY_DELTA_KEY "binary-delta"
#define MODIFY_PERMISSIONS_KEY "mod-permissions"
// Properties no longer used in new patches
#define DELETE_THEN_EXTRACT_OLD_KEY "delete-then-extract"
#define BEFORE_TREE_SHA1_OLD_KEY "before-sha1"
#define AFTER_TREE_SHA1_OLD_KEY "after-sha1"
#define VERBOSE_DELETED "Deleted" // file is deleted from the file system when applying a patch
#define VERBOSE_REMOVED "Removed" // file is set to be removed when creating a patch
#define VERBOSE_ADDED "Added" // file is added to the patch or file system
@@ -44,23 +30,40 @@
#define VERBOSE_PATCHED "Patched" // file is patched when applying a patch
#define VERBOSE_UPDATED "Updated" // file's contents are updated
#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)
// Each major version will be assigned a name of a color
// Relative path of custom icon data that may be set on a bundle via a resource fork
#define CUSTOM_ICON_PATH @"/Icon\r"
// Changes that break backwards compatibility will have different major versions
// Changes that affect creating but not applying patches will have different minor versions
typedef NS_ENUM(uint16_t, SUBinaryDeltaMajorVersion)
{
SUAzureMajorVersion = 1,
SUBeigeMajorVersion = 2
// Note: support for creating or applying version 1 deltas have been removed
SUBinaryDeltaMajorVersion1 = 1,
SUBinaryDeltaMajorVersion2 = 2,
SUBinaryDeltaMajorVersion3 = 3
};
#define FIRST_DELTA_DIFF_MAJOR_VERSION SUAzureMajorVersion
#define LATEST_DELTA_DIFF_MAJOR_VERSION SUBeigeMajorVersion
extern SUBinaryDeltaMajorVersion SUBinaryDeltaMajorVersionDefault;
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."
#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."
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);
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);
@@ -70,5 +73,5 @@ extern NSString *pathRelativeToDirectory(NSString *directory, NSString *path);
NSString *temporaryFilename(NSString *base);
NSString *temporaryDirectory(NSString *base);
NSString *stringWithFileSystemRepresentation(const char*);
int latestMinorVersionForMajorVersion(SUBinaryDeltaMajorVersion majorVersion);
uint16_t latestMinorVersionForMajorVersion(SUBinaryDeltaMajorVersion majorVersion);
#endif
+188 -51
View File
@@ -16,13 +16,81 @@
#include <sys/mman.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <xar/xar.h>
#include <xlocale.h>
#include "AppKitPrevention.h"
// 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 SUBinaryDeltaMajorVersionFirst = SUBinaryDeltaMajorVersion1;
SUBinaryDeltaMajorVersion SUBinaryDeltaMajorVersionFirstSupported = SUBinaryDeltaMajorVersion2;
SPUDeltaCompressionMode deltaCompressionModeFromDescription(NSString *requestedDescription, BOOL *requestValid)
{
// Set to NO later if request was not valid
if (requestValid != NULL) {
*requestValid = YES;
}
SPUDeltaCompressionMode compression;
NSString *description = requestedDescription.lowercaseString;
if ([description isEqualToString:@"default"]) {
compression = SPUDeltaCompressionModeDefault;
} else if ([description isEqualToString:@"none"]) {
compression = SPUDeltaCompressionModeNone;
} else if ([description isEqualToString:@"bzip2"]) {
compression = SPUDeltaCompressionModeBzip2;
} else if ([description isEqualToString:@"lzma"]) {
compression = SPUDeltaCompressionModeLZMA;
} else if ([description isEqualToString:@"lzfse"]) {
compression = SPUDeltaCompressionModeLZFSE;
} else if ([description isEqualToString:@"lz4"]) {
compression = SPUDeltaCompressionModeLZ4;
} else if ([description isEqualToString:@"zlib"]) {
compression = SPUDeltaCompressionModeZLIB;
} else {
compression = SPUDeltaCompressionModeDefault;
if (requestValid != NULL) {
*requestValid = NO;
}
}
return compression;
}
NSString *deltaCompressionStringFromMode(SPUDeltaCompressionMode mode)
{
switch (mode) {
case SPUDeltaCompressionModeBzip2:
return @"bzip2";
case SPUDeltaCompressionModeLZMA:
return @"LZMA";
case SPUDeltaCompressionModeNone:
return @"no";
case SPUDeltaCompressionModeLZ4:
return @"LZ4";
case SPUDeltaCompressionModeLZFSE:
return @"LZFSE";
case SPUDeltaCompressionModeZLIB:
return @"ZLIB";
default:
break;
}
if (mode == SPUDeltaCompressionModeDefault) {
return @"default";
}
return @"unknown";
}
int compareFiles(const FTSENT **a, const FTSENT **b)
{
return strcoll((*a)->fts_name, (*b)->fts_name);
return strcoll_l((*a)->fts_name, (*b)->fts_name, _c_locale);
}
NSString *pathRelativeToDirectory(NSString *directory, NSString *path)
@@ -39,13 +107,15 @@ NSString *stringWithFileSystemRepresentation(const char *input)
return [[NSFileManager defaultManager] stringWithFileSystemRepresentation:input length:strlen(input)];
}
int latestMinorVersionForMajorVersion(SUBinaryDeltaMajorVersion majorVersion)
uint16_t latestMinorVersionForMajorVersion(SUBinaryDeltaMajorVersion majorVersion)
{
switch (majorVersion) {
case SUAzureMajorVersion:
case SUBinaryDeltaMajorVersion1:
return 2;
case SUBinaryDeltaMajorVersion2:
return 4;
case SUBinaryDeltaMajorVersion3:
return 1;
case SUBeigeMajorVersion:
return 3;
}
return 0;
}
@@ -96,7 +166,7 @@ static void _hashOfBuffer(unsigned char *hash, const char *buffer, ssize_t buffe
CC_SHA1_Final(hash, &hashContext);
}
static BOOL _hashOfFileContents(unsigned char *hash, FTSENT *ent)
static BOOL _hashOfFileContents(unsigned char *hash, FTSENT *ent, void *tempBuffer, size_t tempBufferSize)
{
if (ent->fts_info == FTS_SL) {
char linkDestination[MAXPATHLEN + 1];
@@ -108,27 +178,37 @@ static BOOL _hashOfFileContents(unsigned char *hash, FTSENT *ent)
_hashOfBuffer(hash, linkDestination, linkDestinationLength);
} else if (ent->fts_info == FTS_F) {
int fileDescriptor = open(ent->fts_path, O_RDONLY);
if (fileDescriptor == -1) {
perror("open");
return NO;
}
ssize_t fileSize = ent->fts_statp->st_size;
if (fileSize == 0) {
if (fileSize <= 0) {
_hashOfBuffer(hash, NULL, 0);
} else {
void *buffer = mmap(0, (size_t)fileSize, PROT_READ, MAP_FILE | MAP_PRIVATE, fileDescriptor, 0);
if (buffer == (void *)-1) {
close(fileDescriptor);
perror("mmap");
FILE *file = fopen(ent->fts_path, "rb");
if (file == NULL) {
perror("fopen");
return NO;
}
_hashOfBuffer(hash, buffer, fileSize);
munmap(buffer, (size_t)fileSize);
CC_SHA1_CTX hashContext;
CC_SHA1_Init(&hashContext);
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;
}
CC_SHA1_Update(&hashContext, tempBuffer, (CC_LONG)bytesToConsume);
bytesLeft -= bytesToConsume;
}
CC_SHA1_Final(hash, &hashContext);
fclose(file);
}
close(fileDescriptor);
} else if (ent->fts_info == FTS_D) {
memset(hash, 0xdd, CC_SHA1_DIGEST_LENGTH);
} else {
@@ -137,18 +217,31 @@ static BOOL _hashOfFileContents(unsigned char *hash, FTSENT *ent)
return YES;
}
NSString *hashOfTreeWithVersion(NSString *path, uint16_t majorVersion)
BOOL getRawHashOfTreeWithVersion(unsigned char *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)
{
char pathBuffer[PATH_MAX] = { 0 };
if (![path getFileSystemRepresentation:pathBuffer maxLength:sizeof(pathBuffer)]) {
return nil;
return NO;
}
const size_t tempBufferSize = 16384;
void *tempBuffer = calloc(1, tempBufferSize);
if (tempBuffer == NULL) {
perror("calloc");
return NO;
}
char *const sourcePaths[] = { pathBuffer, 0 };
FTS *fts = fts_open(sourcePaths, FTS_PHYSICAL | FTS_NOCHDIR, compareFiles);
if (!fts) {
perror("fts_open");
return nil;
free(tempBuffer);
return NO;
}
CC_SHA1_CTX hashContext;
@@ -162,53 +255,97 @@ NSString *hashOfTreeWithVersion(NSString *path, uint16_t majorVersion)
if (ent->fts_info != FTS_F && ent->fts_info != FTS_SL && ent->fts_info != FTS_D)
continue;
if (ent->fts_info == FTS_D && !MAJOR_VERSION_IS_AT_LEAST(majorVersion, SUBeigeMajorVersion)) {
NSString *relativePath = pathRelativeToDirectory(normalizedPath, stringWithFileSystemRepresentation(ent->fts_path));
// Ignore icon resource fork data
if (relativePath.length == 0 || [relativePath isEqualToString:CUSTOM_ICON_PATH]) {
continue;
}
NSString *relativePath = pathRelativeToDirectory(normalizedPath, stringWithFileSystemRepresentation(ent->fts_path));
if (relativePath.length == 0)
continue;
unsigned char fileHash[CC_SHA1_DIGEST_LENGTH];
if (!_hashOfFileContents(fileHash, ent)) {
return nil;
if (!_hashOfFileContents(fileHash, ent, tempBuffer, tempBufferSize)) {
fts_close(fts);
free(tempBuffer);
return NO;
}
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 (hashToFileKeyDictionary != nil) {
if (hashToFileKeyDictionary[hashKey] == nil) {
hashToFileKeyDictionary[hashKey] = [NSMutableArray array];
}
[hashToFileKeyDictionary[hashKey] addObject:relativePath];
}
if (fileKeyToHashDictionary != nil) {
fileKeyToHashDictionary[relativePath] = hashKey;
}
}
const char *relativePathBytes = [relativePath fileSystemRepresentation];
CC_SHA1_Update(&hashContext, relativePathBytes, (CC_LONG)strlen(relativePathBytes));
if (MAJOR_VERSION_IS_AT_LEAST(majorVersion, SUBeigeMajorVersion)) {
uint16_t mode = ent->fts_statp->st_mode;
// permission of symlinks is irrelevant and can't be changed.
// hardcoding a value helps avoid differences between filesystems.
if (ent->fts_info == FTS_SL) {
mode = 0755;
}
uint16_t type = ent->fts_info;
uint16_t permissions = mode & PERMISSION_FLAGS;
uint16_t mode = ent->fts_statp->st_mode;
uint16_t type = ent->fts_info;
uint16_t permissions = mode & PERMISSION_FLAGS;
// permission of symlinks are 0777 on some linux file systems and can't be changed,
// differing from the 0755 macOS default.
// 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, &permissions, sizeof(permissions));
}
CC_SHA1_Update(&hashContext, &type, sizeof(type));
CC_SHA1_Update(&hashContext, &hashedPermissions, sizeof(hashedPermissions));
}
free(tempBuffer);
fts_close(fts);
unsigned char hash[CC_SHA1_DIGEST_LENGTH];
CC_SHA1_Final(hash, &hashContext);
CC_SHA1_Final(hashBuffer, &hashContext);
return YES;
}
char hexHash[CC_SHA1_DIGEST_LENGTH * 2 + 1];
size_t i;
for (i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
sprintf(hexHash + i * 2, "%02x", hash[i]);
void getRawHashFromDisplayHash(unsigned char *hash, NSString *hexHash)
{
const char *hexString = hexHash.UTF8String;
if (hexString == NULL) {
return;
}
for (size_t blockIndex = 0; blockIndex < CC_SHA1_DIGEST_LENGTH; blockIndex++) {
const char *currentBlock = hexString + blockIndex * 2;
char convertedBlock[3] = {currentBlock[0], currentBlock[1], '\0'};
hash[blockIndex] = (unsigned char)strtol(convertedBlock, NULL, 16);
}
}
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++) {
snprintf(hexHash + i * 2, 3, "%02x", hash[i]);
}
return @(hexHash);
}
NSString *hashOfTreeWithVersion(NSString *path, uint16_t majorVersion)
{
unsigned char hash[CC_SHA1_DIGEST_LENGTH];
if (!getRawHashOfTreeWithVersion(hash, path, majorVersion)) {
return nil;
}
return displayHashFromRawHash(hash);
}
extern NSString *hashOfTree(NSString *path)
{
return hashOfTreeWithVersion(path, LATEST_DELTA_DIFF_MAJOR_VERSION);
return hashOfTreeWithVersion(path, SUBinaryDeltaMajorVersionLatest);
}
BOOL removeTree(NSString *path)
+2 -1
View File
@@ -10,8 +10,9 @@
#define SUBINARYDELTACREATE_H
#import "SUBinaryDeltaCommon.h"
#import "SPUDeltaArchiveProtocol.h"
@class NSString;
BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchFile, SUBinaryDeltaMajorVersion majorVersion, BOOL verbose, NSError * __autoreleasing *error);
BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchFile, SUBinaryDeltaMajorVersion majorVersion, SPUDeltaCompressionMode compression, uint8_t compressionLevel, BOOL verbose, NSError * __autoreleasing *error);
#endif
+488 -144
View File
@@ -9,6 +9,9 @@
#import "SUBinaryDeltaCreate.h"
#import <Foundation/Foundation.h>
#include "SUBinaryDeltaCommon.h"
#import "SPUDeltaArchiveProtocol.h"
#import "SPUSparkleDeltaArchive.h"
#import "SPUXarDeltaArchive.h"
#import <CommonCrypto/CommonDigest.h>
#include <fcntl.h>
#include <fts.h>
@@ -19,7 +22,7 @@
#include <sys/stat.h>
#include <unistd.h>
#include <sys/xattr.h>
#include <xar/xar.h>
#include "AppKitPrevention.h"
@@ -27,29 +30,40 @@ 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 oldTree:(NSString *)oldTree newTree:(NSString *)newTree oldPermissions:(NSNumber *)oldPermissions newPermissions:(NSNumber *)permissions;
- (id)initWithRelativePath:(NSString *)relativePath clonedRelativePath:(NSString *)clonedRelativePath oldTree:(NSString *)oldTree newTree:(NSString *)newTree oldPermissions:(NSNumber *)oldPermissions newPermissions:(NSNumber *)permissions changingPermissions:(BOOL)changingPermissions;
@end
@implementation CreateBinaryDeltaOperation
@synthesize relativePath = _relativePath;
@synthesize clonedRelativePath = _clonedRelativePath;
@synthesize resultPath = _resultPath;
@synthesize oldPermissions = _oldPermissions;
@synthesize permissions = _permissions;
@synthesize changingPermissions = _changingPermissions;
@synthesize _fromPath = _fromPath;
@synthesize _toPath = _toPath;
- (id)initWithRelativePath:(NSString *)relativePath oldTree:(NSString *)oldTree newTree:(NSString *)newTree oldPermissions:(NSNumber *)oldPermissions newPermissions:(NSNumber *)permissions
- (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._fromPath = [oldTree stringByAppendingPathComponent:relativePath];
self.changingPermissions = changingPermissions;
if (clonedRelativePath == nil) {
self._fromPath = [oldTree stringByAppendingPathComponent:relativePath];
} else {
self._fromPath = [oldTree stringByAppendingPathComponent:clonedRelativePath];
}
self._toPath = [newTree stringByAppendingPathComponent:relativePath];
}
return self;
@@ -88,15 +102,6 @@ static NSDictionary *infoForFile(FTSENT *ent)
INFO_SIZE_KEY: @(size) };
}
static bool isSymLink(const FTSENT *ent)
{
if (ent->fts_info == FTS_SL)
{
return (true);
}
return false;
}
static bool aclExists(const FTSENT *ent)
{
// macOS does not currently support ACLs for symlinks
@@ -174,17 +179,16 @@ static BOOL shouldSkipDeltaCompression(NSDictionary *originalInfo, NSDictionary
unsigned short originalInfoType = [(NSNumber *)originalInfo[INFO_TYPE_KEY] unsignedShortValue];
unsigned short newInfoType = [(NSNumber *)newInfo[INFO_TYPE_KEY] unsignedShortValue];
if (originalInfoType != newInfoType) {
// File types are different
if (originalInfoType != newInfoType || originalInfoType != FTS_F) {
// File types are different or they're not regular files
return YES;
}
NSString *originalPath = originalInfo[INFO_PATH_KEY];
NSString *newPath = newInfo[INFO_PATH_KEY];
// Skip delta if both entries are directories, or if the files/symlinks are equal in content
if (originalInfoType == FTS_D || [[NSFileManager defaultManager] contentsEqualAtPath:originalPath andPath:newPath]) {
// this is possible if just the permissions have changed but contents have not
// Skip delta if the files are equal in content
if ([[NSFileManager defaultManager] contentsEqualAtPath:originalPath andPath:newPath]) {
return YES;
}
@@ -236,72 +240,171 @@ static BOOL shouldChangePermissions(NSDictionary *originalInfo, NSDictionary *ne
if (!originalInfo) {
return NO;
}
unsigned short originalInfoType = [(NSNumber *)originalInfo[INFO_TYPE_KEY] unsignedShortValue];
unsigned short newInfoType = [(NSNumber *)newInfo[INFO_TYPE_KEY] unsignedShortValue];
if ([(NSNumber *)originalInfo[INFO_TYPE_KEY] unsignedShortValue] != [(NSNumber *)newInfo[INFO_TYPE_KEY] unsignedShortValue]) {
if (originalInfoType != newInfoType) {
return NO;
}
unsigned short oldPermissions = [(NSNumber *)originalInfo[INFO_PERMISSIONS_KEY] unsignedShortValue];
unsigned short newPermissions = [(NSNumber *)newInfo[INFO_PERMISSIONS_KEY] unsignedShortValue];
if ([(NSNumber *)originalInfo[INFO_PERMISSIONS_KEY] unsignedShortValue] == [(NSNumber *)newInfo[INFO_PERMISSIONS_KEY] unsignedShortValue]) {
if (oldPermissions == newPermissions) {
return NO;
}
// We don't track new permissions on symbolic links that aren't the 0755 macOS default
// Some linux / remotely mounted filesystems may not track permissions on symlinks and use 0777
// We don't want to pick up bad permissions
if (newInfoType == FTS_SL && newPermissions != VALID_SYMBOLIC_LINK_PERMISSIONS) {
return NO;
}
return YES;
}
static xar_file_t _xarAddFile(NSMutableDictionary<NSString *, NSValue *> *fileTable, xar_t x, NSString *relativePath, NSString *filePath)
#define MIN_SIZE_FOR_CLONE 4096
#define MIN_SIZE_FOR_CLONE_DIFF (4096 * 4)
static NSString *cloneableRelativePath(NSDictionary<NSString *, NSData *> *afterFileKeyToHashDictionary, NSDictionary<NSData *, NSArray<NSString *> *> *beforeHashToFileKeyDictionary, NSDictionary<NSString *, NSString *> *frameworkVersionsSubstitutes, NSDictionary<NSString *, NSString *> *fileSubstitutes, NSDictionary *originalTreeState, NSDictionary *newInfo, NSString *key, NSNumber * __autoreleasing *outNewPermissions, BOOL *clonePermissionsChanged, BOOL *clonedBinaryDiff)
{
NSArray<NSString *> *rootRelativePathComponents = relativePath.pathComponents;
// Relative path must at least have starting "/" component and one more path component
if (rootRelativePathComponents.count < 2) {
return NULL;
// Avoid clones for small files. Small files can compress very well, sometimes better than tracking clones.
if ([(NSNumber *)newInfo[INFO_SIZE_KEY] unsignedLongLongValue] <= MIN_SIZE_FOR_CLONE) {
return nil;
}
NSArray<NSString *> *relativePathComponents = [rootRelativePathComponents subarrayWithRange:NSMakeRange(1, rootRelativePathComponents.count - 1)];
if ([(NSNumber *)newInfo[INFO_TYPE_KEY] unsignedShortValue] != FTS_F) {
return nil;
}
NSUInteger relativePathComponentsCount = relativePathComponents.count;
// Build parent files as needed until we get to our final file we want to add
// So if we get "Contents/Resources/foo.txt", we will first add "Contents" parent,
// then "Resources" parent, then "foo.txt" as the final entry we want to add
// 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
xar_file_t lastParent = NULL;
for (NSUInteger componentIndex = 0; componentIndex < relativePathComponentsCount; componentIndex++) {
NSArray<NSString *> *subpathComponents = [relativePathComponents subarrayWithRange:NSMakeRange(0, componentIndex + 1)];
NSString *subpathKey = [subpathComponents componentsJoinedByString:@"/"];
xar_file_t cachedFile = [fileTable[subpathKey] pointerValue];
if (cachedFile != NULL) {
lastParent = cachedFile;
} else {
xar_file_t newParent;
BOOL atLastIndex = (componentIndex == relativePathComponentsCount - 1);
NSString *lastPathComponent = subpathComponents.lastObject;
if (atLastIndex && filePath != nil) {
newParent = xar_add_frompath(x, lastParent, lastPathComponent.fileSystemRepresentation, filePath.fileSystemRepresentation);
} else {
newParent = xar_add_frombuffer(x, lastParent, lastPathComponent.fileSystemRepresentation, "", 1);
{
NSData *keyHash = afterFileKeyToHashDictionary[key];
if (keyHash != nil) {
// Check for identical clones first
for (NSString *oldRelativePath in beforeHashToFileKeyDictionary[keyHash]) {
NSDictionary *oldCloneInfo = originalTreeState[oldRelativePath];
if (oldCloneInfo == nil) {
continue;
}
if ([(NSNumber *)oldCloneInfo[INFO_TYPE_KEY] unsignedShortValue] != FTS_F) {
continue;
}
NSString *clonePath = oldCloneInfo[INFO_PATH_KEY];
NSString *newPath = newInfo[INFO_PATH_KEY];
if (![[NSFileManager defaultManager] contentsEqualAtPath:clonePath andPath:newPath]) {
continue;
}
NSNumber *newPermissions = newInfo[INFO_PERMISSIONS_KEY];
if (outNewPermissions != NULL) {
*outNewPermissions = newPermissions;
}
if (clonePermissionsChanged != NULL) {
*clonePermissionsChanged = ([(NSNumber *)oldCloneInfo[INFO_PERMISSIONS_KEY] unsignedShortValue] != [newPermissions unsignedShortValue]);
}
if (clonedBinaryDiff != NULL) {
*clonedBinaryDiff = NO;
}
return oldRelativePath;
}
lastParent = newParent;
fileTable[subpathKey] = [NSValue valueWithPointer:newParent];
}
}
return lastParent;
// For non-identical files where we do a binary diff, make sure file size matches a more strict file size test
if ([(NSNumber *)newInfo[INFO_SIZE_KEY] unsignedLongLongValue] <= MIN_SIZE_FOR_CLONE_DIFF) {
return nil;
}
// Look out for any .framework/Versions/{A -> B} changes
for (NSString *frameworkVersionPrefix in frameworkVersionsSubstitutes) {
if (![key hasPrefix:frameworkVersionPrefix]) {
continue;
}
NSString *cloneFrameworkSubstitutePrefix = frameworkVersionsSubstitutes[frameworkVersionPrefix];
if (cloneFrameworkSubstitutePrefix == nil) {
continue;
}
NSString *cloneRelativeKey = [key stringByReplacingCharactersInRange:NSMakeRange(0, frameworkVersionPrefix.length) withString:cloneFrameworkSubstitutePrefix];
NSDictionary *oldCloneInfo = originalTreeState[cloneRelativeKey];
if (oldCloneInfo == nil) {
continue;
}
NSNumber *newPermissions = newInfo[INFO_PERMISSIONS_KEY];
if (outNewPermissions != NULL) {
*outNewPermissions = newPermissions;
}
if (clonePermissionsChanged != NULL) {
*clonePermissionsChanged = ([(NSNumber *)oldCloneInfo[INFO_PERMISSIONS_KEY] unsignedShortValue] != [newPermissions unsignedShortValue]);
}
if (clonedBinaryDiff != NULL) {
*clonedBinaryDiff = YES;
}
return cloneRelativeKey;
}
// Look out for any changes that involve the same named file moving to another directory
do {
NSString *cloneRelativeKey = fileSubstitutes[key.lastPathComponent];
if (cloneRelativeKey == nil) {
break;
}
NSDictionary *oldCloneInfo = originalTreeState[cloneRelativeKey];
if (oldCloneInfo == nil) {
break;
}
uint64_t cloneSize = [(NSNumber *)oldCloneInfo[INFO_SIZE_KEY] unsignedLongValue];
uint64_t newSize = [(NSNumber *)newInfo[INFO_SIZE_KEY] unsignedLongValue];
uint64_t minSize = MIN(cloneSize, newSize);
uint64_t maxSize = MAX(cloneSize, newSize);
// Ensure file is at least 60% the same size
if (minSize == 0 || maxSize == 0 || (double)minSize / (double)maxSize < 0.60) {
break;
}
NSNumber *newPermissions = newInfo[INFO_PERMISSIONS_KEY];
if (outNewPermissions != NULL) {
*outNewPermissions = newPermissions;
}
if (clonePermissionsChanged != NULL) {
*clonePermissionsChanged = ([(NSNumber *)oldCloneInfo[INFO_PERMISSIONS_KEY] unsignedShortValue] != [newPermissions unsignedShortValue]);
}
if (clonedBinaryDiff != NULL) {
*clonedBinaryDiff = YES;
}
return cloneRelativeKey;
} while (NO);
return nil;
}
BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchFile, SUBinaryDeltaMajorVersion majorVersion, BOOL verbose, NSError *__autoreleasing *error)
BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchFile, SUBinaryDeltaMajorVersion majorVersion, SPUDeltaCompressionMode compression, uint8_t compressionLevel, BOOL verbose, NSError *__autoreleasing *error)
{
assert(source);
assert(destination);
assert(patchFile);
assert(majorVersion >= FIRST_DELTA_DIFF_MAJOR_VERSION && majorVersion <= LATEST_DELTA_DIFF_MAJOR_VERSION);
assert(majorVersion >= SUBinaryDeltaMajorVersionFirst && majorVersion <= SUBinaryDeltaMajorVersionLatest);
int minorVersion = latestMinorVersionForMajorVersion(majorVersion);
uint16_t minorVersion = latestMinorVersionForMajorVersion(majorVersion);
NSMutableDictionary *originalTreeState = [NSMutableDictionary dictionary];
@@ -323,7 +426,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
}
if (verbose) {
fprintf(stderr, "Creating version %u.%u patch...\n", majorVersion, minorVersion);
fprintf(stderr, "Creating version %u.%u patch using %s compression...\n", majorVersion, minorVersion, deltaCompressionStringFromMode(compression).UTF8String);
fprintf(stderr, "Processing source, %s...", [source fileSystemRepresentation]);
}
@@ -337,6 +440,16 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
if (![key length]) {
continue;
}
if ([key isEqualToString:CUSTOM_ICON_PATH]) {
if (verbose) {
fprintf(stderr, "\n");
}
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Diffing bundles with a custom icon set via a resource fork is not supported. Detected presence of %@", @(ent->fts_path)] }];
}
return NO;
}
NSDictionary *info = infoForFile(ent);
if (!info) {
@@ -350,6 +463,20 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
}
originalTreeState[key] = info;
// Ensure Sparkle executable permissions are valid
if (ent->fts_info == FTS_F && [key.lastPathComponent isEqualToString:@"Sparkle"] && [key.stringByDeletingLastPathComponent.stringByDeletingLastPathComponent.stringByDeletingLastPathComponent.lastPathComponent isEqualToString:@"Sparkle.framework"]) {
mode_t permissions = (mode_t)[(NSNumber *)info[INFO_PERMISSIONS_KEY] shortValue];
if (permissions != VALID_SPARKLE_EXECUTABLE_PERMISSIONS) {
if (verbose) {
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)] }];
}
return NO;
}
}
if (aclExists(ent)) {
if (verbose) {
fprintf(stderr, "\n");
@@ -372,9 +499,11 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
}
fts_close(fts);
NSString *beforeHash = hashOfTreeWithVersion(source, majorVersion);
if (!beforeHash) {
// This dictionary will help us keep track of clones
NSMutableDictionary<NSData *, NSMutableArray<NSString *> *> *beforeHashToFileKeyDictionary = MAJOR_VERSION_IS_AT_LEAST(majorVersion, SUBinaryDeltaMajorVersion3) ? [NSMutableDictionary dictionary] : nil;
unsigned char beforeHash[CC_SHA1_DIGEST_LENGTH] = {0};
if (!getRawHashOfTreeAndFileTablesWithVersion(beforeHash, source, majorVersion, beforeHashToFileKeyDictionary, nil)) {
if (verbose) {
fprintf(stderr, "\n");
}
@@ -412,7 +541,11 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
}
return NO;
}
bool foundFilesystemCompression = false;
uint32_t warningsCount = 0;
const uint32_t maxWarningsToPrint = 16;
while ((ent = fts_read(fts))) {
if (ent->fts_info != FTS_F && ent->fts_info != FTS_SL && ent->fts_info != FTS_D) {
continue;
@@ -422,6 +555,16 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
if (![key length]) {
continue;
}
if ([key isEqualToString:CUSTOM_ICON_PATH]) {
if (verbose) {
fprintf(stderr, "\n");
}
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Diffing bundles with a custom icon set via a resource fork is not supported. Detected presence of %@", @(ent->fts_path)] }];
}
return NO;
}
NSDictionary *info = infoForFile(ent);
if (!info) {
@@ -434,23 +577,24 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
return NO;
}
// We should validate permissions and ACLs even if we don't store the info in the diff in the case of ACLs,
// or in the case of permissions if the patch version is 1
// Ensure Sparkle executable permissions are valid
if (ent->fts_info == FTS_F && [key.lastPathComponent isEqualToString:@"Sparkle"] && [key.stringByDeletingLastPathComponent.stringByDeletingLastPathComponent.stringByDeletingLastPathComponent.lastPathComponent isEqualToString:@"Sparkle.framework"]) {
mode_t permissions = (mode_t)[(NSNumber *)info[INFO_PERMISSIONS_KEY] shortValue];
if (permissions != VALID_SPARKLE_EXECUTABLE_PERMISSIONS) {
if (verbose) {
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)] }];
}
return NO;
}
}
// We should validate ACLs even if we don't store the info in the diff in the case of ACLs
// We should also not allow files with code signed extended attributes since Apple doesn't recommend inserting these
// inside an application, and since we don't preserve extended attribitutes anyway
mode_t permissions = [(NSNumber*)info[INFO_PERMISSIONS_KEY] unsignedShortValue];
if (!isSymLink(ent) && !IS_VALID_PERMISSIONS(permissions)) {
if (verbose) {
fprintf(stderr, "\n");
}
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Invalid file permissions after-tree on file %@ (only permissions with modes 0755 and 0644 are supported)", @(ent->fts_path)] }];
}
return NO;
}
if (aclExists(ent)) {
if (verbose) {
fprintf(stderr, "\n");
@@ -470,10 +614,50 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
}
return NO;
}
if (warningsCount < maxWarningsToPrint) {
uint16_t permissions = (ent->fts_statp->st_mode & PERMISSION_FLAGS);
if (ent->fts_info == FTS_SL) {
if (permissions != VALID_SYMBOLIC_LINK_PERMISSIONS) {
fprintf(stderr, "\nWarning: file permissions 0%o of symbolic link '%s' won't be preserved in the delta update (only permissions with mode 0755 are supported for symbolic links).", permissions, ent->fts_path);
warningsCount++;
}
} else if (permissions != 0755 && permissions != 0644) {
// This could indicate something is wrong inside of the bundle so it's worth warning the user about
fprintf(stderr, "\nWarning: detected irregular file permissions 0%o for '%s'", permissions, ent->fts_path);
warningsCount++;
}
if (warningsCount == maxWarningsToPrint) {
fprintf(stderr, "\nWarning: encountered too many warnings.. Ignoring the rest..");
}
}
// 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) {
foundFilesystemCompression = true;
if (verbose) {
fprintf(stderr, " File system compression detected.");
}
}
NSDictionary *oldInfo = originalTreeState[key];
if ([info isEqual:oldInfo]) {
BOOL hasEqualInfo;
if (![info isEqual:oldInfo]) {
hasEqualInfo = NO;
} else {
NSString *originalPath = oldInfo[INFO_PATH_KEY];
NSString *newPath = info[INFO_PATH_KEY];
hasEqualInfo = [[NSFileManager defaultManager] contentsEqualAtPath:originalPath andPath:newPath];
}
if (hasEqualInfo) {
[newTreeState removeObjectForKey:key];
} else {
newTreeState[key] = info;
@@ -493,8 +677,11 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
}
fts_close(fts);
NSString *afterHash = hashOfTreeWithVersion(destination, majorVersion);
if (!afterHash) {
// This dictionary will help us keep track of clones
NSMutableDictionary<NSString *, NSData *> *afterFileKeyToHashDictionary = MAJOR_VERSION_IS_AT_LEAST(majorVersion, SUBinaryDeltaMajorVersion3) ? [NSMutableDictionary dictionary] : nil;
unsigned char afterHash[CC_SHA1_DIGEST_LENGTH] = {0};
if (!getRawHashOfTreeAndFileTablesWithVersion(afterHash, destination, majorVersion, nil, afterFileKeyToHashDictionary)) {
if (verbose) {
fprintf(stderr, "\n");
}
@@ -512,31 +699,27 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
if (verbose) {
fprintf(stderr, "\nWriting to temporary file %s...", [temporaryFile fileSystemRepresentation]);
}
xar_t x = xar_open([temporaryFile fileSystemRepresentation], WRITE);
if (!x) {
id<SPUDeltaArchiveProtocol> archive;
if (majorVersion >= SUBinaryDeltaMajorVersion3) {
archive = [[SPUSparkleDeltaArchive alloc] initWithPatchFileForWriting:temporaryFile];
} else {
archive = [[SPUXarDeltaArchive alloc] initWithPatchFileForWriting:temporaryFile];
}
SPUDeltaArchiveHeader *header = [[SPUDeltaArchiveHeader alloc] initWithCompression:compression compressionLevel:compressionLevel fileSystemCompression:foundFilesystemCompression majorVersion:majorVersion minorVersion:minorVersion beforeTreeHash:beforeHash afterTreeHash:afterHash];
[archive writeHeader:header];
if (archive.error != nil) {
if (verbose) {
fprintf(stderr, "\n");
}
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileWriteUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to write to %@", temporaryFile] }];
*error = archive.error;
}
return NO;
}
xar_opt_set(x, XAR_OPT_COMPRESSION, "bzip2");
xar_subdoc_t attributes = xar_subdoc_new(x, BINARY_DELTA_ATTRIBUTES_KEY);
xar_subdoc_prop_set(attributes, MAJOR_DIFF_VERSION_KEY, [[NSString stringWithFormat:@"%u", majorVersion] UTF8String]);
xar_subdoc_prop_set(attributes, MINOR_DIFF_VERSION_KEY, [[NSString stringWithFormat:@"%u", minorVersion] UTF8String]);
// Version 1 patches don't have a major or minor version field, so we need to differentiate between the hash keys
const char *beforeHashKey = MAJOR_VERSION_IS_AT_LEAST(majorVersion, SUBeigeMajorVersion) ? BEFORE_TREE_SHA1_KEY : BEFORE_TREE_SHA1_OLD_KEY;
const char *afterHashKey = MAJOR_VERSION_IS_AT_LEAST(majorVersion, SUBeigeMajorVersion) ? AFTER_TREE_SHA1_KEY : AFTER_TREE_SHA1_OLD_KEY;
xar_subdoc_prop_set(attributes, beforeHashKey, [beforeHash UTF8String]);
xar_subdoc_prop_set(attributes, afterHashKey, [afterHash UTF8String]);
NSOperationQueue *deltaQueue = [[NSOperationQueue alloc] init];
NSMutableArray *deltaOperations = [NSMutableArray array];
@@ -551,15 +734,104 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
return originalTreeState[key1] ? NSOrderedAscending : NSOrderedDescending;
}];
NSMutableDictionary<NSString *, NSValue *> *fileTable = [NSMutableDictionary dictionary];
// Using a couple of heursitics 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)) {
// 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)
NSMutableDictionary<NSString *, NSString *> *oldFrameworkVersions = [NSMutableDictionary dictionary];
for (NSString *key in keys) {
id value = [newTreeState valueForKey:key];
if (![(NSObject *)value isEqual:[NSNull null]]) {
continue;
}
NSDictionary *originalInfo = originalTreeState[key];
if ([(NSNumber *)originalInfo[INFO_TYPE_KEY] unsignedShortValue] != FTS_D) {
continue;
}
NSString *keyWithoutLastPathComponent = key.stringByDeletingLastPathComponent;
if (![keyWithoutLastPathComponent.lastPathComponent isEqualToString:@"Versions"]) {
continue;
}
NSString *keyWithoutLastLastPathComponent = keyWithoutLastPathComponent.stringByDeletingLastPathComponent;
if (![keyWithoutLastLastPathComponent.pathExtension isEqualToString:@"framework"]) {
continue;
}
oldFrameworkVersions[keyWithoutLastLastPathComponent] = key;
}
for (NSString *key in keys) {
id value = [newTreeState valueForKey:key];
if ([(NSObject *)value isEqual:[NSNull null]] || originalTreeState[key] != nil) {
continue;
}
NSDictionary *newInfo = value;
if ([(NSNumber *)newInfo[INFO_TYPE_KEY] unsignedShortValue] != FTS_D) {
continue;
}
NSString *keyWithoutLastPathComponent = key.stringByDeletingLastPathComponent;
if (![keyWithoutLastPathComponent.lastPathComponent isEqualToString:@"Versions"]) {
continue;
}
NSString *keyWithoutLastLastPathComponent = keyWithoutLastPathComponent.stringByDeletingLastPathComponent;
if (![keyWithoutLastLastPathComponent.pathExtension isEqualToString:@"framework"]) {
continue;
}
NSString *oldFrameworkVersionKey = oldFrameworkVersions[keyWithoutLastLastPathComponent];
if (oldFrameworkVersionKey == nil) {
continue;
}
frameworkVersionsSubstitutes[[key stringByAppendingString:@"/"]] = [oldFrameworkVersionKey stringByAppendingString:@"/"];
}
// Heuristic #2: Keep a table of removed filenames, collapsing them by the largest file per unique name
// This sees if a file has just been moved to another location
for (NSString *key in keys) {
id value = [newTreeState valueForKey:key];
if (![(NSObject *)value isEqual:[NSNull null]]) {
continue;
}
NSDictionary *keyInfo = originalTreeState[key];
if ([(NSNumber *)keyInfo[INFO_TYPE_KEY] unsignedShortValue] != FTS_F) {
continue;
}
NSString *lastPathComponent = key.lastPathComponent;
NSString *existingKey = fileSubstitutes[lastPathComponent];
if (existingKey == nil) {
fileSubstitutes[lastPathComponent] = key;
} else {
NSDictionary *existingKeyInfo = originalTreeState[existingKey];
if ([(NSNumber *)keyInfo[INFO_SIZE_KEY] unsignedLongValue] > [(NSNumber *)existingKeyInfo[INFO_SIZE_KEY] unsignedLongValue]) {
fileSubstitutes[lastPathComponent] = key;
}
}
}
}
for (NSString *key in keys) {
id value = [newTreeState valueForKey:key];
if ([(NSObject *)value isEqual:[NSNull null]]) {
xar_file_t newFile = _xarAddFile(fileTable, x, key, NULL);
assert(newFile);
xar_prop_set(newFile, DELETE_KEY, "true");
[archive addItem:[[SPUDeltaArchiveItem alloc] initWithRelativeFilePath:key commands:SPUDeltaItemCommandDelete mode:0]];
if (verbose) {
fprintf(stderr, "\n❌ %s %s", VERBOSE_REMOVED, [key fileSystemRepresentation]);
@@ -570,47 +842,73 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
NSDictionary *originalInfo = originalTreeState[key];
NSDictionary *newInfo = newTreeState[key];
if (shouldSkipDeltaCompression(originalInfo, newInfo)) {
if (MAJOR_VERSION_IS_AT_LEAST(majorVersion, SUBeigeMajorVersion) && shouldSkipExtracting(originalInfo, newInfo)) {
if (shouldSkipExtracting(originalInfo, newInfo)) {
if (shouldChangePermissions(originalInfo, newInfo)) {
xar_file_t newFile = _xarAddFile(fileTable, x, key, NULL);
assert(newFile);
xar_prop_set(newFile, MODIFY_PERMISSIONS_KEY, [[NSString stringWithFormat:@"%u", [(NSNumber *)newInfo[INFO_PERMISSIONS_KEY] unsignedShortValue]] UTF8String]);
[archive addItem:[[SPUDeltaArchiveItem alloc] initWithRelativeFilePath:key commands:SPUDeltaItemCommandModifyPermissions mode:[(NSNumber *)newInfo[INFO_PERMISSIONS_KEY] unsignedShortValue]]];
if (verbose) {
fprintf(stderr, "\n👮 %s %s (0%o -> 0%o)", VERBOSE_MODIFIED, [key fileSystemRepresentation], [(NSNumber *)originalInfo[INFO_PERMISSIONS_KEY] unsignedShortValue], [(NSNumber *)newInfo[INFO_PERMISSIONS_KEY] unsignedShortValue]);
}
}
} else {
NSString *path = [destination stringByAppendingPathComponent:key];
xar_file_t newFile = _xarAddFile(fileTable, x, key, path);
assert(newFile);
if (shouldDeleteThenExtract(originalInfo, newInfo)) {
if (MAJOR_VERSION_IS_AT_LEAST(majorVersion, SUBeigeMajorVersion)) {
xar_prop_set(newFile, DELETE_KEY, "true");
// Check if the new file can be cloned from an old existing one located at a different path
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;
if (clonedRelativePath != nil) {
if (clonedBinaryDiff) {
NSDictionary *cloneInfo = originalTreeState[clonedRelativePath];
CreateBinaryDeltaOperation *operation = [[CreateBinaryDeltaOperation alloc] initWithRelativePath:key clonedRelativePath:clonedRelativePath oldTree:source newTree:destination oldPermissions:cloneInfo[INFO_PERMISSIONS_KEY] newPermissions:newPermissions changingPermissions:clonePermissionsChanged];
[deltaQueue addOperation:operation];
[deltaOperations addObject:operation];
} else {
xar_prop_set(newFile, DELETE_THEN_EXTRACT_OLD_KEY, "true");
SPUDeltaItemCommands commands = SPUDeltaItemCommandClone;
if (clonePermissionsChanged) {
commands |= SPUDeltaItemCommandModifyPermissions;
}
SPUDeltaArchiveItem *item = [[SPUDeltaArchiveItem alloc] initWithRelativeFilePath:key commands:commands mode:(clonePermissionsChanged ? newPermissions.unsignedShortValue : 0)];
// Physical path for clones points to the old file
item.itemFilePath = [source stringByAppendingPathComponent:clonedRelativePath];
item.sourcePath = item.itemFilePath;
item.clonedRelativePath = clonedRelativePath;
[archive addItem:item];
if (verbose) {
fprintf(stderr, "\n✂️ %s %s -> %s", VERBOSE_CLONED, [clonedRelativePath fileSystemRepresentation], [key fileSystemRepresentation]);
}
}
}
} else {
// Otherwise add a new file
NSString *path = [destination stringByAppendingPathComponent:key];
SPUDeltaItemCommands commands = SPUDeltaItemCommandExtract;
if (shouldDeleteThenExtract(originalInfo, newInfo)) {
commands |= SPUDeltaItemCommandDelete;
}
SPUDeltaArchiveItem *item = [[SPUDeltaArchiveItem alloc] initWithRelativeFilePath:key commands:commands mode:0];
item.itemFilePath = path;
item.sourcePath = path;
[archive addItem:item];
if (MAJOR_VERSION_IS_AT_LEAST(majorVersion, SUBeigeMajorVersion)) {
xar_prop_set(newFile, EXTRACT_KEY, "true");
}
if (verbose) {
if (originalInfo) {
fprintf(stderr, "\n✏️ %s %s", VERBOSE_UPDATED, [key fileSystemRepresentation]);
} else {
fprintf(stderr, "\n✅ %s %s", VERBOSE_ADDED, [key fileSystemRepresentation]);
if (verbose) {
if (originalInfo) {
fprintf(stderr, "\n✏️ %s %s", VERBOSE_UPDATED, [key fileSystemRepresentation]);
} else {
fprintf(stderr, "\n✅ %s %s", VERBOSE_ADDED, [key fileSystemRepresentation]);
}
}
}
}
} else {
NSNumber *permissions =
(MAJOR_VERSION_IS_AT_LEAST(majorVersion, SUBeigeMajorVersion) && shouldChangePermissions(originalInfo, newInfo)) ?
newInfo[INFO_PERMISSIONS_KEY] :
nil;
CreateBinaryDeltaOperation *operation = [[CreateBinaryDeltaOperation alloc] initWithRelativePath:key oldTree:source newTree:destination oldPermissions:originalInfo[INFO_PERMISSIONS_KEY] newPermissions:permissions];
NSNumber *permissions = newInfo[INFO_PERMISSIONS_KEY];
CreateBinaryDeltaOperation *operation = [[CreateBinaryDeltaOperation alloc] initWithRelativePath:key clonedRelativePath:nil oldTree:source newTree:destination oldPermissions:originalInfo[INFO_PERMISSIONS_KEY] newPermissions:permissions changingPermissions:shouldChangePermissions(originalInfo, newInfo)];
[deltaQueue addOperation:operation];
[deltaOperations addObject:operation];
}
@@ -618,37 +916,83 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
[deltaQueue waitUntilAllOperationsAreFinished];
BOOL deltaOperationsFailed = NO;
for (CreateBinaryDeltaOperation *operation in deltaOperations) {
NSString *resultPath = [operation resultPath];
if (!resultPath) {
if (resultPath == nil) {
if (verbose) {
fprintf(stderr, "\n");
}
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileWriteUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to create patch from source %@ and destination %@", operation.relativePath, resultPath] }];
}
return NO;
deltaOperationsFailed = YES;
break;
}
NSString *clonedRelativePath = [operation clonedRelativePath];
if (verbose) {
fprintf(stderr, "\n🔨 %s %s", VERBOSE_DIFFED, [[operation relativePath] fileSystemRepresentation]);
if (clonedRelativePath == nil) {
fprintf(stderr, "\n🔨 %s %s", VERBOSE_DIFFED, [[operation relativePath] fileSystemRepresentation]);
} else {
fprintf(stderr, "\n🔨 %s %s -> %s", VERBOSE_DIFFED, [clonedRelativePath fileSystemRepresentation], [[operation relativePath] fileSystemRepresentation]);
}
}
NSNumber *mode = operation.permissions;
NSString *relativePath = operation.relativePath;
SPUDeltaItemCommands commands = SPUDeltaItemCommandBinaryDiff;
if (operation.changingPermissions) {
commands |= SPUDeltaItemCommandModifyPermissions;
}
if (clonedRelativePath != nil) {
commands |= SPUDeltaItemCommandClone;
}
SPUDeltaArchiveItem *item = [[SPUDeltaArchiveItem alloc] initWithRelativeFilePath:relativePath commands:commands mode:mode.unsignedShortValue];
item.itemFilePath = resultPath;
item.sourcePath = operation._fromPath;
item.clonedRelativePath = clonedRelativePath;
[archive addItem:item];
xar_file_t newFile = _xarAddFile(fileTable, x, [operation relativePath], resultPath);
assert(newFile);
xar_prop_set(newFile, BINARY_DELTA_KEY, "true");
unlink([resultPath fileSystemRepresentation]);
if (operation.permissions) {
xar_prop_set(newFile, MODIFY_PERMISSIONS_KEY, [[NSString stringWithFormat:@"%u", [operation.permissions unsignedShortValue]] UTF8String]);
if (operation.changingPermissions) {
if (verbose) {
fprintf(stderr, "\n👮 %s %s (0%o -> 0%o)", VERBOSE_MODIFIED, [[operation relativePath] fileSystemRepresentation], operation.oldPermissions.unsignedShortValue, operation.permissions.unsignedShortValue);
fprintf(stderr, "\n👮 %s %s (0%o -> 0%o)", VERBOSE_MODIFIED, relativePath.fileSystemRepresentation, operation.oldPermissions.unsignedShortValue, operation.permissions.unsignedShortValue);
}
}
}
xar_close(x);
if (!deltaOperationsFailed) {
[archive finishEncodingItems];
}
[archive close];
// Clean up operations after the archive has finished encoding
for (CreateBinaryDeltaOperation *operation in deltaOperations) {
NSString *resultPath = [operation resultPath];
if (resultPath != nil) {
unlink(resultPath.fileSystemRepresentation);
}
}
if (deltaOperationsFailed) {
// We already set an error so let's bail
return NO;
}
NSError *archiveError = archive.error;
if (archiveError != nil) {
if (verbose) {
fprintf(stderr, "\n");
}
if (error != NULL) {
*error = archiveError;
}
return NO;
}
NSFileManager *filemgr;
filemgr = [NSFileManager defaultManager];
-246
View File
@@ -1,246 +0,0 @@
//
// SUBinaryDeltaTool.m
// Sparkle
//
// Created by Mark Rowe on 2009-06-01.
// Copyright 2009 Mark Rowe. All rights reserved.
//
#include "SUBinaryDeltaApply.h"
#include "SUBinaryDeltaCreate.h"
#import "SUBinaryDeltaCommon.h"
#include <Foundation/Foundation.h>
#include <xar/xar.h>
#define VERBOSE_FLAG @"--verbose"
#define VERSION_FLAG @"--version"
#define CREATE_COMMAND @"create"
#define APPLY_COMMAND @"apply"
#define VERSION_COMMAND @"version"
#define VERSION_ALTERNATE_COMMAND @"--version"
#include "AppKitPrevention.h"
static void printUsage(NSString *programName)
{
fprintf(stderr, "Usage:\n");
fprintf(stderr, "%s create [--verbose] [--version=<version>] <before-tree> <after-tree> <patch-file>\n", [programName UTF8String]);
fprintf(stderr, "%s apply [--verbose] <before-tree> <after-tree> <patch-file>\n", [programName UTF8String]);
fprintf(stderr, "%s version [<patch-file>]\n", [programName UTF8String]);
}
static BOOL runCreateCommand(NSString *programName, NSArray<NSString *> *args)
{
if (args.count < 3 || args.count > 5) {
printUsage(programName);
return NO;
}
NSUInteger numberOflagsFound = 0;
NSUInteger verboseIndex = [args indexOfObject:VERBOSE_FLAG];
NSUInteger versionIndex = NSNotFound;
for (NSUInteger argumentIndex = 0; argumentIndex < args.count; ++argumentIndex) {
if ([args[argumentIndex] hasPrefix:VERSION_FLAG]) {
versionIndex = argumentIndex;
break;
}
}
if (verboseIndex != NSNotFound) {
++numberOflagsFound;
}
if (versionIndex != NSNotFound) {
++numberOflagsFound;
}
if (args.count - numberOflagsFound < 3) {
printUsage(programName);
return NO;
}
BOOL verbose = (verboseIndex != NSNotFound);
NSString *versionField = (versionIndex != NSNotFound) ? args[versionIndex] : nil;
NSArray<NSString *> *versionComponents = nil;
if (versionField) {
versionComponents = [versionField componentsSeparatedByString:@"="];
if (versionComponents.count != 2) {
printUsage(programName);
return NO;
}
}
SUBinaryDeltaMajorVersion patchVersion =
!versionComponents ?
LATEST_DELTA_DIFF_MAJOR_VERSION :
(SUBinaryDeltaMajorVersion)[[versionComponents[1] componentsSeparatedByString:@"."][0] intValue]; // ignore minor version if provided
if (patchVersion < FIRST_DELTA_DIFF_MAJOR_VERSION) {
fprintf(stderr, "Version provided (%u) is not valid\n", patchVersion);
return NO;
}
if (patchVersion > LATEST_DELTA_DIFF_MAJOR_VERSION) {
fprintf(stderr, "This program is too old to create a version %u patch, or the version number provided is invalid\n", patchVersion);
return NO;
}
NSMutableArray *fileArgs = [NSMutableArray array];
for (NSString *argument in args) {
if (![argument hasPrefix:VERSION_FLAG] && ![argument isEqualToString:VERBOSE_FLAG]) {
[fileArgs addObject:argument];
}
}
if (fileArgs.count != 3) {
printUsage(programName);
return NO;
}
NSString *sourcePath = fileArgs[0];
NSString *destPath = fileArgs[1];
NSString *patchPath = fileArgs[2];
BOOL isDirectory;
if (![[NSFileManager defaultManager] fileExistsAtPath:sourcePath isDirectory:&isDirectory] || !isDirectory) {
printUsage(programName);
fprintf(stderr, "Error: before-tree must be a directory\n");
return NO;
}
if (![[NSFileManager defaultManager] fileExistsAtPath:destPath isDirectory:&isDirectory] || !isDirectory) {
printUsage(programName);
fprintf(stderr, "Error: after-tree must be a directory\n");
return NO;
}
NSError *createDiffError = nil;
if (!createBinaryDelta(sourcePath, destPath, patchPath, patchVersion, verbose, &createDiffError)) {
fprintf(stderr, "%s\n", [createDiffError.localizedDescription UTF8String]);
return NO;
}
return YES;
}
static BOOL runApplyCommand(NSString *programName, NSArray *args)
{
if (args.count < 3 || args.count > 4) {
printUsage(programName);
return NO;
}
BOOL verbose = [args containsObject:VERBOSE_FLAG];
if (args.count == 4 && !verbose) {
printUsage(programName);
return NO;
}
NSMutableArray *fileArgs = [NSMutableArray array];
for (NSString *argument in args) {
if (![argument isEqualToString:VERBOSE_FLAG]) {
[fileArgs addObject:argument];
}
}
if (fileArgs.count != 3) {
printUsage(programName);
return NO;
}
BOOL isDirectory;
if (![[NSFileManager defaultManager] fileExistsAtPath:fileArgs[0] isDirectory:&isDirectory] || !isDirectory) {
printUsage(programName);
fprintf(stderr, "Error: before-tree must be a directory\n");
return NO;
}
if (![[NSFileManager defaultManager] fileExistsAtPath:fileArgs[2] isDirectory:&isDirectory] || isDirectory) {
printUsage(programName);
fprintf(stderr, "Error: patch-file must be a file %d\n", isDirectory);
return NO;
}
NSError *applyDiffError = nil;
if (!applyBinaryDelta(fileArgs[0], fileArgs[1], fileArgs[2], verbose, ^(__unused double x){}, &applyDiffError)) {
fprintf(stderr, "%s\n", [applyDiffError.localizedDescription UTF8String]);
return NO;
}
return YES;
}
static BOOL runVersionCommand(NSString *programName, NSArray *args)
{
if (args.count > 1) {
printUsage(programName);
return NO;
}
if (args.count == 0) {
fprintf(stdout, "%u.%u\n", LATEST_DELTA_DIFF_MAJOR_VERSION, latestMinorVersionForMajorVersion(LATEST_DELTA_DIFF_MAJOR_VERSION));
} else {
NSString *patchFile = args[0];
xar_t x = xar_open([patchFile fileSystemRepresentation], READ);
if (!x) {
fprintf(stderr, "Unable to open patch %s\n", [patchFile fileSystemRepresentation]);
return NO;
}
SUBinaryDeltaMajorVersion majorDiffVersion = FIRST_DELTA_DIFF_MAJOR_VERSION;
int minorDiffVersion = 0;
xar_subdoc_t subdoc;
for (subdoc = xar_subdoc_first(x); subdoc; subdoc = xar_subdoc_next(subdoc)) {
if (!strcmp(xar_subdoc_name(subdoc), BINARY_DELTA_ATTRIBUTES_KEY)) {
const char *value = 0;
// available in version 2.0 or later
xar_subdoc_prop_get(subdoc, MAJOR_DIFF_VERSION_KEY, &value);
if (value)
majorDiffVersion = (SUBinaryDeltaMajorVersion)[@(value) intValue];
// available in version 2.0 or later
xar_subdoc_prop_get(subdoc, MINOR_DIFF_VERSION_KEY, &value);
if (value)
minorDiffVersion = [@(value) intValue];
}
}
fprintf(stdout, "%u.%u\n", majorDiffVersion, minorDiffVersion);
}
return YES;
}
int main(int __unused argc, char __unused *argv[])
{
@autoreleasepool {
NSArray<NSString *> *args = [[NSProcessInfo processInfo] arguments];
NSString *programName = [args[0] lastPathComponent];
if (args.count < 2) {
printUsage(programName);
return 1;
}
NSString *command = args[1];
NSArray *commandArguments = [args subarrayWithRange:NSMakeRange(2, args.count - 2)];
BOOL result;
if ([command isEqualToString:CREATE_COMMAND]) {
result = runCreateCommand(programName, commandArguments);
} else if ([command isEqualToString:APPLY_COMMAND]) {
result = runApplyCommand(programName, commandArguments);
} else if ([command isEqualToString:VERSION_COMMAND] || [command isEqualToString:VERSION_ALTERNATE_COMMAND]) {
result = runVersionCommand(programName, commandArguments);
} else {
result = NO;
printUsage(programName);
}
return result ? 0 : 1;
}
}
+7 -1
View File
@@ -12,8 +12,14 @@
#import <Foundation/Foundation.h>
@interface SUCodeSigningVerifier : NSObject
+ (BOOL)codeSignatureAtBundleURL:(NSURL *)oldBundleURL matchesSignatureAtBundleURL:(NSURL *)newBundleURL error:(NSError **)error;
+ (BOOL)codeSignatureIsValidAtBundleURL:(NSURL *)bundleURL 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)bundleAtURLIsCodeSigned:(NSURL *)bundleURL;
@end
+11 -2
View File
@@ -61,7 +61,7 @@
// 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 DSA signing the download archive instead.
// Aditionally, 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);
result = SecStaticCodeCheckValidityWithErrors(staticCode, flags, requirement, &cfError);
@@ -127,6 +127,11 @@ finally:
}
+ (BOOL)codeSignatureIsValidAtBundleURL:(NSURL *)bundleURL error:(NSError *__autoreleasing *)error
{
return [self codeSignatureIsValidAtBundleURL:bundleURL checkNestedCode:NO error:error];
}
+ (BOOL)codeSignatureIsValidAtBundleURL:(NSURL *)bundleURL checkNestedCode:(BOOL)checkNestedCode error:(NSError *__autoreleasing *)error
{
OSStatus result;
SecStaticCodeRef staticCode = NULL;
@@ -143,8 +148,12 @@ finally:
goto finally;
}
// See in -codeSignatureAtBundleURL:matchesSignatureAtBundleURL:error: for why kSecCSCheckNestedCode is not passed
// See in -codeSignatureAtBundleURL:matchesSignatureAtBundleURL:error: for why kSecCSCheckNestedCode is not always passed
SecCSFlags flags = (SecCSFlags) (kSecCSDefaultFlags | kSecCSCheckAllArchitectures);
if (checkNestedCode) {
flags |= kSecCSCheckNestedCode;
}
result = SecStaticCodeCheckValidityWithErrors(staticCode, flags, NULL, &cfError);
if (result != errSecSuccess) {
+64 -24
View File
@@ -62,8 +62,8 @@
// get a unique mount point path
NSString *mountPoint = nil;
NSFileManager *manager;
NSError *error;
NSArray *contents;
NSError *error = nil;
NSArray *contents = nil;
do
{
// Using NSUUID would make creating UUIDs be done in Cocoa,
@@ -82,8 +82,7 @@
// Note: this check does not follow symbolic links, which is what we want
while ([[NSURL fileURLWithPath:mountPoint] checkResourceIsReachableAndReturnError:NULL]);
NSData *promptData = nil;
promptData = [NSData dataWithBytes:"yes\n" length:4];
NSData *promptData = [NSData dataWithBytes:"yes\n" length:4];
NSMutableArray *arguments = [@[@"attach", self.archivePath, @"-mountpoint", mountPoint, /*@"-noverify",*/ @"-nobrowse", @"-noautoopen"] mutableCopy];
@@ -102,7 +101,7 @@
NSData *output = nil;
NSInteger taskResult = -1;
@try
{
NSTask *task = [[NSTask alloc] init];
task.launchPath = @"/usr/bin/hdiutil";
@@ -115,23 +114,55 @@
task.standardInput = inputPipe;
task.standardOutput = outputPipe;
[task launch];
NSFileHandle *fileStdHandle = outputPipe.fileHandleForReading;
NSMutableData *currentOutput = [NSMutableData data];
fileStdHandle.readabilityHandler = ^(NSFileHandle *file) {
[currentOutput appendData:file.availableData];
};
dispatch_semaphore_t terminationSemaphore = dispatch_semaphore_create(0);
task.terminationHandler = ^(NSTask *__unused terminatingTask) {
fileStdHandle.readabilityHandler = nil;
dispatch_semaphore_signal(terminationSemaphore);
};
if (@available(macOS 10.13, *)) {
if (![task launchAndReturnError:&error]) {
goto reportError;
}
} else {
@try {
[task launch];
} @catch (NSException *) {
goto reportError;
}
}
[notifier notifyProgress:0.125];
[inputPipe.fileHandleForWriting writeData:promptData];
if (@available(macOS 10.15, *)) {
if (![inputPipe.fileHandleForWriting writeData:promptData error:&error]) {
goto reportError;
}
} else {
@try {
[inputPipe.fileHandleForWriting writeData:promptData];
} @catch (NSException *) {
goto reportError;
}
}
[inputPipe.fileHandleForWriting closeFile];
// Read data to end *before* waiting until the task ends so we don't deadlock if the stdout buffer becomes full if we haven't consumed from it
output = [outputPipe.fileHandleForReading readDataToEndOfFile];
dispatch_semaphore_wait(terminationSemaphore, DISPATCH_TIME_FOREVER);
output = [currentOutput copy];
[task waitUntilExit];
taskResult = task.terminationStatus;
}
@catch (NSException *)
{
goto reportError;
}
[notifier notifyProgress:0.5];
@@ -146,27 +177,27 @@
// Now that we've mounted it, we need to copy out its contents.
manager = [[NSFileManager alloc] init];
contents = [manager contentsOfDirectoryAtPath:mountPoint error:&error];
if (error)
if (contents == nil)
{
SULog(SULogLevelError, @"Couldn't enumerate contents of archive mounted at %@: %@", mountPoint, error);
goto reportError;
}
double itemsCopied = 0;
double totalItems = [contents count];
double totalItems = (double)[contents count];
for (NSString *item in contents)
{
NSString *fromPath = [mountPoint stringByAppendingPathComponent:item];
NSString *toPath = [[self.archivePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:item];
// We skip any files in the DMG which are not readable.
itemsCopied += 1.0;
[notifier notifyProgress:0.5 + itemsCopied/(totalItems*2.0)];
// We skip any files in the DMG which are not readable but include the item in the progress
if (![manager isReadableFileAtPath:fromPath]) {
continue;
}
itemsCopied += 1.0;
[notifier notifyProgress:0.5 + itemsCopied/(totalItems*2.0)];
SULog(SULogLevelDefault, @"copyItemAtPath:%@ toPath:%@", fromPath, toPath);
@@ -190,11 +221,20 @@
task.standardOutput = [NSPipe pipe];
task.standardError = [NSPipe pipe];
@try {
[task launch];
} @catch (NSException *exception) {
SULog(SULogLevelError, @"Failed to unmount %@", mountPoint);
SULog(SULogLevelError, @"Exception: %@", exception);
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);
}
}
} else {
SULog(SULogLevelError, @"Can't mount DMG %@", self.archivePath);
+34 -14
View File
@@ -53,26 +53,46 @@
task.arguments = @[@"-pkg", self.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.standardError = [NSPipe pipe];
task.standardOutput = [NSPipe pipe];
task.standardError = nil;
task.standardOutput = nil;
BOOL success = YES;
@try {
[task launch];
[task waitUntilExit];
if (task.terminationStatus != EXIT_SUCCESS) {
success = NO;
if (@available(macOS 10.13, *)) {
NSError *launchError = nil;
if (![task launchAndReturnError:&launchError]) {
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Guided package installer returned non-zero exit status (%d)", task.terminationStatus] }];
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;
}
} @catch (NSException *) {
success = NO;
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Guided package installer task threw an exception"] }];
} else {
@try {
[task launch];
} @catch (NSException *) {
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: @"Guided package installer task threw an exception" }];
}
return NO;
}
}
return success;
[task waitUntilExit];
if (task.terminationStatus != EXIT_SUCCESS) {
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Guided package installer returned non-zero exit status (%d)", task.terminationStatus] }];
}
return NO;
}
return YES;
}
- (void)performCleanup
+124 -49
View File
@@ -93,7 +93,6 @@
{
// *** GETS CALLED ON NON-MAIN THREAD!!!
@autoreleasepool {
NSError *error = nil;
NSString *destination = [self.archivePath stringByDeletingLastPathComponent];
SULog(SULogLevelDefault, @"Extracting using '%@' '%@' < '%@' '%@'", command, [args componentsJoinedByString:@"' '"], self.archivePath, destination);
@@ -101,58 +100,134 @@
// Get the file size.
NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:self.archivePath error:nil];
NSUInteger expectedLength = [(NSNumber *)[attributes objectForKey:NSFileSize] unsignedIntegerValue];
if (expectedLength > 0) {
NSFileHandle *archiveInput = [NSFileHandle fileHandleForReadingAtPath:self.archivePath];
if (expectedLength == 0) {
NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Extraction failed, archive '%@' is empty", self.archivePath]}];
NSPipe *pipe = [NSPipe pipe];
NSTask *task = [[NSTask alloc] init];
[task setStandardInput:[pipe fileHandleForReading]];
[task setStandardError:[NSFileHandle fileHandleWithStandardError]];
[task setStandardOutput:[NSFileHandle fileHandleWithStandardOutput]];
[task setLaunchPath:command];
[task setArguments:[args arrayByAddingObject:destination]];
@try {
[task launch];
}
@catch (NSException *e) {
error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Extraction failed, -[NSTask launch] threw exception '%@'", e.description]}];
}
if (!error) {
NSFileHandle *archiveOutput = [pipe fileHandleForWriting];
NSUInteger bytesRead = 0;
do {
NSData *data = [archiveInput readDataOfLength:256*1024];
NSUInteger len = [data length];
if (!len) {
break;
}
bytesRead += len;
[archiveOutput writeData:data];
[notifier notifyProgress:(double)bytesRead / (double)expectedLength];
}
while(bytesRead < expectedLength);
[archiveOutput closeFile];
[task waitUntilExit];
if ([task terminationStatus] == 0) {
if (bytesRead == expectedLength) {
[notifier notifySuccess];
return;
} else {
error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Extraction failed, command '%@' got only %ld of %ld bytes", command, (long)bytesRead, (long)expectedLength]}];
}
} else {
error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Extraction failed, command '%@' returned %d", command, [task terminationStatus]]}];
}
[notifier notifyFailureWithError:error];
return;
}
NSFileHandle *archiveInput = [NSFileHandle fileHandleForReadingAtPath:self.archivePath];
NSPipe *pipe = [NSPipe pipe];
NSTask *task = [[NSTask alloc] init];
[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 {
error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Extraction failed, archive '%@' is empty", self.archivePath]}];
@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;
}
}
[notifier notifyFailureWithError:error];
NSFileHandle *archiveOutput = [pipe fileHandleForWriting];
NSUInteger bytesWritten = 0;
BOOL hasIOErrorMethods;
if (@available(macOS 10.15, *)) {
hasIOErrorMethods = YES;
} else {
hasIOErrorMethods = NO;
}
do {
NSData *data;
if (hasIOErrorMethods) {
NSError *readError = nil;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpartial-availability"
data = [archiveInput readDataUpToLength:256*1024 error:&readError];
#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;
}
}
NSUInteger len = [data length];
if (len == 0) {
break;
}
NSError *writeError = nil;
if (hasIOErrorMethods) {
#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);
break;
}
}
bytesWritten += len;
[notifier notifyProgress:(double)bytesWritten / (double)expectedLength];
}
while(bytesWritten < expectedLength);
if (@available(macOS 10.15, *)) {
NSError *archiveOutputCloseError = nil;
if (![archiveOutput closeAndReturnError:&archiveOutputCloseError]) {
SULog(SULogLevelError, @"Failed to close pipe with error %@", archiveOutputCloseError);
}
} else {
[archiveOutput closeFile];
}
if (@available(macOS 10.15, *)) {
NSError *archiveInputCloseError = nil;
if (![archiveInput closeAndReturnError:&archiveInputCloseError]) {
SULog(SULogLevelError, @"Failed to close archive input with error %@", archiveInputCloseError);
}
} 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];
}
}
+108 -79
View File
@@ -86,58 +86,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
if (![fileManager updateAccessTimeOfItemAtRootURL:newURL error:error]) {
NSError *accessTimeError = nil;
if (![fileManager updateAccessTimeOfItemAtRootURL:newURL error:&accessTimeError]) {
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: @"Failed to recursively update new application's modification time before moving into temporary directory" }];
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];
}
return NO;
}
// Create a temporary directory for our new app that resides on our destination's volume
NSString *preferredName = [installationURL.lastPathComponent.stringByDeletingPathExtension stringByAppendingString:@" (Incomplete Update)"];
NSURL *installationDirectory = installationURL.URLByDeletingLastPathComponent;
NSURL *tempNewDirectoryURL = [fileManager makeTemporaryDirectoryWithPreferredName:preferredName appropriateForDirectoryURL:installationDirectory error:error];
if (tempNewDirectoryURL == nil) {
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: @"Failed to make new temporary directory" }];
}
return NO;
}
self.temporaryNewDirectory = tempNewDirectoryURL;
if (progress) {
progress(2/10.0);
}
// Move the new app to our temporary directory
NSString *newURLLastPathComponent = newURL.lastPathComponent;
NSURL *newTempURL = [tempNewDirectoryURL URLByAppendingPathComponent:newURLLastPathComponent];
if (![fileManager moveItemAtURL:newURL toURL:newTempURL error:error]) {
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to move the new app from %@ to its temp directory at %@", newURL.path, newTempURL.path] }];
}
return NO;
}
if (progress) {
progress(3/10.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);
}
if (progress) {
progress(4/10.0);
}
NSURL *oldURL = [NSURL fileURLWithPath:host.bundlePath];
if (oldURL == nil) {
// this really shouldn't happen but just in case
@@ -148,6 +111,56 @@
return NO;
}
if (progress) {
progress(2/10.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];
}
return NO;
}
if (progress) {
progress(4/10.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);
}
if (progress) {
progress(5/10.0);
}
// Try to preserve Finder Tags
NSArray *resourceTags = nil;
BOOL retrievedResourceTags = [oldURL getResourceValue:&resourceTags forKey:NSURLTagNamesKey error:NULL];
@@ -155,6 +168,10 @@
[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
@@ -166,7 +183,7 @@
}
if (progress) {
progress(5/10.0);
progress(7/10.0);
}
NSError *touchError = nil;
@@ -177,69 +194,85 @@
}
if (progress) {
progress(6/10.0);
progress(8/10.0);
}
// First try replacing the application atomically
NSError *replaceError = nil;
BOOL replacedApp;
// 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]) {
replacedApp = NO;
swappedApp = NO;
} else {
// Note: in my experience, a clone of the app may still be left at newTempURL
// This is OK though because we will be cleaning up the temporary directory later in -performCleanup:
replacedApp = [fileManager replaceItemAtURL:installationURL withItemAtURL:newTempURL error:&replaceError];
// 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 {
replacedApp = NO;
swappedApp = NO;
}
if (!replacedApp) {
if (!swappedApp) {
// Otherwise swap out the old and new applications using the legacy path
if (replaceError != nil) {
SULog(SULogLevelDefault, @"Invoking fallback from failing to replace original item with error: %@", replaceError);
if (swapError != nil) {
SULog(SULogLevelDefault, @"Invoking fallback from failing to replace original item with error: %@", swapError);
}
// Decide on a destination name we should use for the older app when we move it around the file system
NSString *oldDestinationName = oldURL.lastPathComponent.stringByDeletingPathExtension;
NSString *oldDestinationNameWithPathExtension = oldURL.lastPathComponent;
// Create a temporary directory for our old app that resides on its volume
NSURL *oldDirectoryURL = oldURL.URLByDeletingLastPathComponent;
NSURL *tempOldDirectoryURL = (oldDirectoryURL != nil) ? [fileManager makeTemporaryDirectoryWithPreferredName:oldDestinationName appropriateForDirectoryURL:oldDirectoryURL error:error] : nil;
NSURL *tempOldDirectoryURL = [fileManager makeTemporaryDirectoryAppropriateForDirectoryURL:oldURL error:error];
if (tempOldDirectoryURL == nil) {
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to create temporary directory for old app at %@", oldURL.path] }];
}
return NO;
}
self.temporaryOldDirectory = tempOldDirectoryURL;
if (progress) {
progress(7/10.0);
progress(9/10.0);
}
NSString *oldURLFilename = oldURL.lastPathComponent;
if (oldURLFilename == nil) {
// this really shouldn't happen..
SULog(SULogLevelError, @"Failed to retrieve last path component from old URL: %@", oldURL.path);
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: @"Failed to perform installation because the last path component of the old installation URL could not be constructed." }];
}
return NO;
}
// Move the old app to the temporary directory
NSURL *oldTempURL = [tempOldDirectoryURL URLByAppendingPathComponent:oldDestinationNameWithPathExtension];
if (![fileManager moveItemAtURL:oldURL toURL:oldTempURL error:error]) {
NSURL *oldTempURL = [tempOldDirectoryURL URLByAppendingPathComponent:oldURLFilename];
NSError *oldMoveError = nil;
if (![fileManager moveItemAtURL:oldURL toURL:oldTempURL error:&oldMoveError]) {
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to move the old app at %@ to a temporary location at %@", oldURL.path, oldTempURL.path] }];
NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to move the old app at %@ to a temporary location at %@", oldURL.path, oldTempURL.path] }];
if (oldMoveError != nil) {
userInfo[NSUnderlyingErrorKey] = oldMoveError;
}
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:userInfo];
}
return NO;
}
if (progress) {
progress(8/10.0);
progress(9.5/10.0);
}
// Move the new app to its final destination
if (![fileManager moveItemAtURL:newTempURL toURL:installationURL error:error]) {
NSError *installMoveError = nil;
if (![fileManager moveItemAtURL:newTempURL toURL:installationURL error:&installMoveError]) {
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ 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 %@", newTempURL.path, installationURL.path] }];
if (installMoveError != nil) {
userInfo[NSUnderlyingErrorKey] = installMoveError;
}
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:userInfo];
}
// Attempt to restore our old app back the way it was on failure
@@ -247,10 +280,6 @@
return NO;
}
if (progress) {
progress(9/10.0);
}
}
if (progress) {
+14 -1
View File
@@ -265,6 +265,9 @@
return NO;
}
// Sparkle's DSA support is deprecated
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
__block SecGroupTransformRef group = SecTransformCreateGroupTransform();
__block SecTransformRef dataReadTransform = NULL;
__block SecTransformRef dataDigestTransform = NULL;
@@ -297,7 +300,7 @@
return cleanup();
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdirect-ivar-access"
dataVerifyTransform = SecVerifyTransformCreate(dsaPubKeySecKey, (__bridge CFDataRef)dsaSignature, &error);
@@ -317,8 +320,12 @@
return cleanup();
}
#pragma clang diagnostic pop
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
SecTransformConnectTransforms(dataReadTransform, kSecTransformOutputAttributeName, dataDigestTransform, kSecTransformInputAttributeName, group, &error);
#pragma clang diagnostic pop
if (error) {
if (outError != NULL) {
*outError = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:@{NSLocalizedDescriptionKey : @"Failed to connect data read transform", NSUnderlyingErrorKey: (__bridge NSError *)error}];
@@ -327,7 +334,10 @@
return cleanup();
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
SecTransformConnectTransforms(dataDigestTransform, kSecTransformOutputAttributeName, dataVerifyTransform, kSecTransformInputAttributeName, group, &error);
#pragma clang diagnostic pop
if (error) {
if (outError != NULL) {
*outError = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:@{NSLocalizedDescriptionKey : @"Failed to connect data digest transform", NSUnderlyingErrorKey: (__bridge NSError *)error}];
@@ -336,7 +346,10 @@
return cleanup();
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
NSNumber *result = CFBridgingRelease(SecTransformExecute(group, &error));
#pragma clang diagnostic pop
if (error) {
SULog(SULogLevelError, @"DSA signature verification failed: %@", error);
if (outError != NULL) {
+3
View File
@@ -22,6 +22,9 @@ int main(int __unused argc, const char __unused *argv[])
// Ignore SIGTERM because we are going to catch it ourselves
signal(SIGTERM, SIG_IGN);
// Ignore SIGPIPE because we won't want read or write failures due to broken pipe to unexpectably
// terminate the process (e.g, when extracting archives or performing package installs).
signal(SIGPIPE, SIG_IGN);
dispatch_source_t sigtermSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, SIGTERM, 0, dispatch_get_main_queue());
dispatch_source_set_event_handler(sigtermSource, ^{
+8
View File
@@ -0,0 +1,8 @@
//
// Use this file to import your target's public headers that you would like to expose to Swift.
//
#import "SUBinaryDeltaApply.h"
#import "SUBinaryDeltaCreate.h"
#import "SPUDeltaArchive.h"
#import "SPUDeltaArchiveProtocol.h"
+228
View File
@@ -0,0 +1,228 @@
//
// main.swift
// BinaryDelta
//
// Created by Mayur Pawashe on 1/3/22.
// Copyright © 2022 Sparkle Project. All rights reserved.
//
import Foundation
import ArgumentParser
// Create a patch from an old and new bundle
struct Create: ParsableCommand {
@Option(name: .long, help: ArgumentHelp("The major version of the patch to generate. Defaults to the latest stable version. Older versions will need to be specified for updating from applications using older versions of Sparkle.", valueName: "version"))
var version: Int = Int(SUBinaryDeltaMajorVersionDefault.rawValue)
@Flag(name: .customLong("verbose"), help: ArgumentHelp("Enable logging of the changes being archived into the generated patch."))
var verbose: Bool = false
@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"))
var compressionLevel: UInt8 = 0
@Argument(help: ArgumentHelp("Path to original bundle to create a patch from."))
var beforeTree: String
@Argument(help: ArgumentHelp("Path to new bundle to create a patch from."))
var afterTree: String
@Argument(help: ArgumentHelp("Path to new patch file to create."))
var patchFile: String
func validate() throws {
var validCompression: ObjCBool = false
let compressionMode = deltaCompressionModeFromDescription(compression, &validCompression)
guard validCompression.boolValue else {
fputs("Error: unrecognized compression \(compression)\n", stderr)
throw ExitCode(1)
}
switch compressionMode {
case SPUDeltaCompressionModeDefault:
fallthrough
case .none:
guard compressionLevel == 0 else {
fputs("Error: compression level must be 0 for compression \(compression)\n", stderr)
throw ExitCode(1)
}
break
case .bzip2:
guard compressionLevel >= 0 && compressionLevel <= 9 else {
fputs("Error: compression level \(compressionLevel) is not valid.\n", stderr)
throw ExitCode(1)
}
break
case .LZMA:
fallthrough
case .LZFSE:
fallthrough
case .LZ4:
fallthrough
case .ZLIB:
guard version >= 3 else {
fputs("Error: version \(version) patch files do not support compression \(compression)\n", stderr)
throw ExitCode(1)
}
guard compressionLevel == 0 else {
fputs("Error: compression level provided must be 0 for compression \(compression)\n", stderr)
throw ExitCode(1)
}
break
@unknown default:
fputs("Error: unrecognized compression \(compression)\n", stderr)
throw ExitCode(1)
}
guard version >= SUBinaryDeltaMajorVersionFirst.rawValue else {
fputs("Error: version provided \(version) is not valid.\n", stderr)
throw ExitCode(1)
}
guard version >= SUBinaryDeltaMajorVersionFirstSupported.rawValue else {
fputs("Error: creating version \(version) patches is no longer supported.\n", stderr)
throw ExitCode(1)
}
guard version <= SUBinaryDeltaMajorVersionLatest.rawValue else {
fputs("Error: this program is too old to create a version \(version) patch, or the version number provided is invalid.\n", stderr)
throw ExitCode(1)
}
let fileManager = FileManager.default
var isDirectory: ObjCBool = false
if !fileManager.fileExists(atPath: beforeTree, isDirectory: &isDirectory) || !isDirectory.boolValue {
fputs("Error: before-tree must be a directory\n", stderr)
throw ExitCode(1)
}
if !fileManager.fileExists(atPath: afterTree, isDirectory: &isDirectory) || !isDirectory.boolValue {
fputs("Error: after-tree must be a directory\n", stderr)
throw ExitCode(1)
}
}
func run() throws {
let compressionMode = deltaCompressionModeFromDescription(compression, nil)
guard let majorDeltaVersion = SUBinaryDeltaMajorVersion(rawValue: UInt16(version)) else {
// We shouldn't reach here
fputs("Error: failed to retrieve major version from provided version: \(version)\n", stderr)
throw ExitCode(1)
}
var createDiffError: NSError? = nil
if !createBinaryDelta(beforeTree, afterTree, patchFile, majorDeltaVersion, compressionMode, compressionLevel, verbose, &createDiffError) {
if let error = createDiffError {
fputs("\(error.localizedDescription)\n", stderr)
} else {
fputs("Error: Failed to create patch due to unknown reason.\n", stderr)
}
throw ExitCode(1)
}
}
}
// Apply a patch from an old bundle to generate a new bundle
struct Apply: ParsableCommand {
static let configuration = CommandConfiguration(abstract: "Apply a patch against an original bundle to generate a new bundle.")
@Flag(name: .customLong("verbose"), help: ArgumentHelp("Enable logging of changes being applied from the patch."))
var verbose: Bool = false
@Argument(help: ArgumentHelp("Path to original bundle to patch."))
var beforeTree: String
@Argument(help: ArgumentHelp("Path to new bundle to create."))
var afterTree: String
@Argument(help: ArgumentHelp("Path to patch file to apply."))
var patchFile: String
func validate() throws {
let fileManager = FileManager.default
var isDirectory: ObjCBool = false
if !fileManager.fileExists(atPath: beforeTree, isDirectory: &isDirectory) || !isDirectory.boolValue {
fputs("Error: before-tree must be a directory\n", stderr)
throw ExitCode(1)
}
if !fileManager.fileExists(atPath: patchFile, isDirectory: &isDirectory) || isDirectory.boolValue {
fputs("Error: patch-file must be a file\n", stderr)
throw ExitCode(1)
}
}
func run() throws {
var applyDiffError: NSError?
if (!applyBinaryDelta(beforeTree, afterTree, patchFile, verbose, { _ in }, &applyDiffError)) {
if let error = applyDiffError {
fputs("\(error.localizedDescription)\n", stderr)
} else {
fputs("Error: patch failed to apply for unknown reason\n", stderr)
}
throw ExitCode(1)
}
}
}
// Output information for BinaryDelta or from a patch file
struct Info: ParsableCommand {
@Argument(help: ArgumentHelp("Path to patch file to extract information from."))
var patchFile : String?
func run() throws {
if let patchFile = patchFile {
// Print version of patch file
var header: SPUDeltaArchiveHeader? = nil
let archive = SPUDeltaArchiveReadPatchAndHeader(patchFile, &header)
if let error = archive.error {
fputs("Error: Unable to open patch \(patchFile): \(error.localizedDescription)\n", stderr)
throw ExitCode(1)
}
if let header = header {
if header.majorVersion < SUBinaryDeltaMajorVersionFirst.rawValue {
fputs("Error: major version \(header.majorVersion) is invalid.\n", stderr)
throw ExitCode(1)
}
fputs("Patch version \(header.majorVersion).\(header.minorVersion)", stdout)
// Print out compression info only if it's available
// We can't get compression info from version 2 files
if header.compression != SPUDeltaCompressionModeDefault, let compressionDescription = deltaCompressionStringFromMode(header.compression) {
fputs(" using \(compressionDescription) compression", stdout)
// Compression level isn't available or applicable for all formats
if header.compressionLevel != 0 {
fputs(" with level \(header.compressionLevel)", stdout)
}
}
fputs("\n", stdout)
} else {
fputs("Error: Failed to retrieve header due to unknown reason.\n", stderr)
throw ExitCode(1)
}
} else {
// Print version of program
fputs("BinaryDelta version \(SUBinaryDeltaMajorVersionLatest.rawValue).\(latestMinorVersionForMajorVersion(SUBinaryDeltaMajorVersionLatest))\n", stdout)
}
}
}
struct BinaryDelta: ParsableCommand {
static let configuration = CommandConfiguration(commandName: "BinaryDelta", abstract: "Create and apply small and efficient delta patches between an old and new version of a bundle.", subcommands: [Create.self, Apply.self, Info.self])
}
DispatchQueue.global().async(execute: {
BinaryDelta.main()
CFRunLoopStop(CFRunLoopGetMain())
})
CFRunLoopRun()
+111 -14
View File
@@ -1,18 +1,93 @@
# 2.2.1
* Make scroll bar dark in dark theme for Release Notes by default (#2187) (Pavel Moiseenko)
* Fix memory leaks when using generate_appcast (#2193) (Zorg)
* Update Italian localization (#2192) (VinBoiSoft)
# 2.2.0
* Update Focus Improvements (#924)
* Present new scheduled updates in utmost focus only at opportune times (Zorg)
* For regular apps opportune times are: app launch, app re-activation, and system being idle (without a power assertion being held to prevent display sleep).
* For background (dockless) apps opportune time is just app launch. Otherwise, the update is now shown behind other applications and windows, instead of previously stealing focus from other active apps.
* Add APIs and documentation for adding gentle update reminders to compliment Sparkle's standard user interface (Zorg) (#2122)
* Allow status window to be minimizable for regular app installs (Zorg) (#2100)
* Center status window and inherit key focus from the previously shown update alert window (Zorg)
* Activate app when checking for updates if the app is not currently active (e.g, from a menu bar extra menu item) (Zorg)
* Fix issue where bringing status window to front made other active windows exit in macOS Ventura's Stage Manager (#2153) (Zorg)
* Fix showing update in focus not bringing the "checking for updates" window in focus (Zorg) (#2150)
* Rename XPC Service filenames for Sandboxing to show more friendly human-readable name in authorization dialog (Zorg) (#2096)
* Add support for running the framework and sparkle-cli as root (Zorg) (#2119)
* Fix issue where update cycle may not complete in unusual configuration if automatic checks are disabled + automatic downloading is enabled + install requires user interaction (Zorg) (#2133)
* Synchronize usage of XPC connections to main queue to fix potential race conditions (Zorg) (#2178)
* Update last update check time when choosing to install an update & relaunch (Zorg) (#2136)
* Improve error reporting in the framework and sparkle-cli when installation fails with no write permission (Zorg) (#2157)
* Use displayVersionString instead of versionString for OS version mismatch error message (samschott) (#2138)
* Make displayVersionString non-null and update fallback documentation (Zorg) (#2139)
* Ignore custom icons set via resource forks when applying delta updates (Zorg) (#2114)
* Fall back to regular update if delta update fails to download (Zorg) (#2118)
* Skip downloading delta updates when application has been moved to a file system (like FAT) that doesn't support regular permission modes (Zorg) (#2148)
* Bump initial installer message timeouts and declare daemon/agents processes as Interactive (Zorg) (#2162)
* Add and improve translation strings and update pt-BR (BR Lingo) (#2094)
* Update localisations (Eitot) (#2113)
* Update Greek localizations (seitsme) (#2184, #2185)
* Update Japanese localization (1024jp) (#2182)
* Replace deprecated code with newer APIs (Eitot) (#2112)
* Remove obsolete fallbacks for older OS versions (Eitot) (#2110)
* Remove SPUURLRequest (Zorg) (#2124)
* Silence ivar deprecation warnings (Zorg) (#2099)
* Fix Xcode 14 project warnings (Zorg) (#2147, #2179)
* Deprecate -s flag and add --ed-key-file option to generate_appcast (Zorg) (#2170)
* Update text for external licenses (Zorg) (#2164)
This update renames the bundled XPC Services, brings improvements to notifying users of new updates without disrupting their focus, and adds [gentle update reminder APIs](https://sparkle-project.org/documentation/gentle-reminders/) to further customize how Sparkle's standard user interface delivers new update alerts.
The `-s` flag for passing a raw private EdDSA key to sign_update and generate_appcast is now deprecated. If you were using this option previously, please see the help pages of these tools for more information.
# 2.1.0
* New Binary Delta format (version 3)
* Features a custom and more efficient container format, migrating away from the deprecated xar format (Zorg) (#2051)
* Adds delta compression options for lzma, bzip2, zlib, lzfse, lz4, and no compression (Zorg) (#2051)
* Changes default delta format compression from bzip2 (in version 2) to lzma (in version 3) resulting in smaller deltas (Zorg) (#2051)
* Preserve file system (HFS+/apfs) level compression when applying delta updates (Zorg) (#2084)
* Tracks renames and binary diffs for files that have moved around to new locations using intelligent heuristics (Zorg) (#2051, #2053)
* Added more unit tests, UI tests, and generate_appcast/BinaryDelta tools support for the new format (Zorg) (#2052, #2054)
* Major upgrade improvements (#2070)
* Fix skipping a major version to not skip subsequent major versions (Zorg) (#2079)
* Add sparkle:belowVersion element for informational updates (Zorg) (#2080)
* Add option to allow developers to ignore/reset user skipped upgrades (Zorg) (#2081)
* Fix progress bar and button alignment for checking updates (Zorg) (#2066)
* This deprecates `-[SPUUserDriver showInstallingUpdate]` and `-[SPUUserDriver showSendingTerminationSignal]` in favor for `-[SPUUserDriver showInstallingUpdateWithApplicationTerminated:]`
* Fix unsteady progress when installing updates (Zorg) (#2072)
* Check http statusCode in didFinishDownloadingToURL (Eric Shapiro, Zorg) (#2049, #2073)
* Use strcoll_l() for locale-independent comparisons for delta updates (Dan Rigdon-Bel) (#2087)
* Fix version compare not treating '2.1.0' and '2.1' as being equal (Zorg) (#2065)
* Add verify and account options for signing updates (Zorg) (#2074)
* Add delta patch and Apple code signing verification in generate_appcast (Zorg) (#2076, #2077)
* Use more modern NSSecureCoding APIs when available (Zorg) (#2058)
* Use more modern FileManager APIs for copying files (Zorg) (#2059)
* Fix make release failing when customizing XPC_SERVICE_BUNDLE_ID_PREFIX (Zorg) (#2060)
* Preserve the Entitlements directory in podspec (digitalMoksha) (#2062)
* Add hidden option to generate_appcast to set max CDATA threshold (Zorg) (#2075)
This update introduces a new major format for [delta updates](https://sparkle-project.org/documentation/delta-updates/), which migrates away from deprecated APIs (xar) and creates smaller patches. If you don't use `generate_appcast`, please check the [compatibility notes for creating delta updates](https://sparkle-project.org/documentation/delta-updates/#compatibility).
# 2.0.0
* Support for Sandboxed Applications (Zorg)
* Support for writing custom user interfaces (Zorg)
* Support for updating external Sparkle-based bundles (Zorg)
* Added command line utility to update Sparkle-based bundles (Zorg)
* More modern architecture
* Modern architecture
* Moves extraction, validation, and installation into a submitted launchd agent/daemon with XPC communication (Zorg)
* Features faster installs with shorter update/relaunch times (#1802) (Zorg)
* Provides more robust installs that need to request user authorization (Zorg)
* Adoption of atomic-safe bundle replacing updates leveraging APFS (#1801) (Zorg)
* Provides more robust installs when user authorization is needed (Zorg)
* Adoption of improved atomic-safe updates leveraging APFS (#1801) (Zorg)
* API Changes
* Introduced new SPUStandardUpdaterController, SPUUpdater, SPUUserDriver classes/protocols (Zorg)
* Decoupled AppKit and UI logic in the framework from core functionality (Zorg)
* Ensure (most) API / ABI compatibility with Sparkle 1.x; you can likely test Sparkle 2 in an existing app without any changes (Zorg)
* Ensure (most) API compatibility with Sparkle 1; you can likely test Sparkle 2 in an existing app with little to no changes (Zorg)
* Deprecated SUUpdater, albeit it is still functional for testing and transitional purposes (Zorg)
* `-bestValidUpdateInAppcast:forUpdater:` delegate method behavior has been refined and discouraged for some cases. Please review its updated header documentation in `SPUUpdaterDelegate.h` if you use this method. (#1838, #1862, #1879, #1880) (Zorg)
* Delegation methods may have been removed or added to the newer updater API. Please review `SPUUpdaterDelegate` if using `SPUUpdater`. (Zorg)
@@ -24,26 +99,48 @@
* Sparkle uses the icon of the bundle to update for its authorization dialog. A 32x32 image representation of the icon is needed. (Zorg)
* Sudden termination for silent automatic updates isn't disabled anymore (Zorg)
* Policy Changes
* Distributing updates without EdDSA signing the archives is now deprecated (Zorg)
* Package based updates that are zipped or archived must add sparkle:installationType="package" to the appcast item enclosure (Zorg)
* Non-bare package based updates that are zipped or archived must add sparkle:installationType="package" to the appcast item enclosure (this doesn't apply to bare packages which aren't archived) (Zorg)
* We now recommend using sparkle:version and sparkle:shortVersionString top level elements instead of enclosure attributes (#1878) (Zorg)
* The link element in an appcast item is now used for directing users to the product's website if they don't meet minimum system requirements (#1877) (Zorg)
* Major/Paid Upgrades Enhancements
* Latest minor updates are preferred over major updates (specified by sparkle:minimumAutoupdateVersion) (#1850) Zorg
* Major updates can be skipped with a user confirmation (#1853) Zorg
* Informational only and critical updates can be specified selectively by app version (#1862)
* Expose why a new update is unavailable and direct user to prior release notes or website info (#1877, #1886) (Zorg)
* Add support for posting updates only on specific channels (#1879) (Zorg)
* Add <sparkle:fullReleaseNotesLink> element allowing Sparkle to show a better stylized and full changelog to the user (#2001) (aONe)
* Add delegate API allowing applications to show full in-app or offline version history to the user (#1989) (Billy Gray)
* Major/Paid Upgrades Enhancements
* Latest minor updates are preferred over major updates (specified by sparkle:minimumAutoupdateVersion) (#1850) (Zorg)
* Major updates can be skipped with a user confirmation (#1853) (Zorg)
* Informational only and critical updates can be specified selectively by app version (#1862)
* Add support for posting updates only on specific channels (eg for supporting beta updates) (#1879) (Zorg)
* System profiler privacy and transparency (#1690) (Martin Pilkington)
* Support getting app icon from asset catalog (#1694) (Charles Srstka)
* Don't hide update alert window now on deactivation (#1804) (Zorg)
* Don't bring up authorization just because group ID doesn't match (#1830) (Zorg)
* Raise minimum system version to 10.11 (Zorg)
* Raise minimum system version to macOS 10.11 (Zorg)
* Special thanks to developers using early builds of this release in production and contributors for keeping this running (Kornel, Jonas Zaugg, Gwynne Raskind, Jordan Rose, Tony Arnold, Bryan Jones, Christian Tietze, Jakob Egger, and many more)
Please visit [Sparkle's website](http://sparkle-project.org) for more information on documentation and migration.
If you are migrating from earlier alpha versions of Sparkle 2, 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 code signing has been simplified. The SPUUserDriver protocol for custom user interfaces has been greatly simplified too.
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.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)
* Fix to prevent Sparkle manipulating the host app's high level WebView defaults from #1961 (affecting only macOS versions before 10.11 in 1.x branch) (Daniel Jalkut)
* Add safer handling of applying binary delta files from #1990 (Zorg)
* Don't use current date unless necessary when scheduling next update from #1991 (Zorg)
* Whitelist about:srcdoc as a safe web URL from #1938, #2007 (Louis Pontoise, Zorg)
* Backport not hiding update window on deactivation from #2008 (Zorg)
# 1.27.0
* Deprecate not using EdDSA and skip DSA verification when possible in #1892 (Zorg)
* Pass http headers and user agent when downloading release notes from #1873 (Zorg)
* Fix project warnings from #1893 (Zorg)
* Update sample appcast from #1895 (Zorg)
* Fix appcast pubDate tag generation in different locales from #1898 (Sungbin Jo)
* Create valid xar archives for generating binary delta files from #1906 (Zorg)
* Fix a few issues with German localization from #1931 (J-rg)
* Fix issues with Russian localizations from #1947 (Konstantin Zamyakin)
* Fix issues with Czech localizations from #1943 (Vojtěch Koňařík)
* Add an automated workflow that builds and publishes official Sparkle releases (Tony Arnold, Zorg)
# 1.26.0
+1
View File
@@ -0,0 +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 +0,0 @@
// BinaryDelta tool only
+30 -12
View File
@@ -4,6 +4,28 @@ 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
SPARKLE_EMBED_INSTALLER_LAUNCHER_XPC_SERVICE = 1
SPARKLE_EMBED_DOWNLOADER_XPC_SERVICE = 1
SPARKLE_EMBED_INSTALLER_STATUS_XPC_SERVICE = 0
SPARKLE_EMBED_INSTALLER_CONNECTION_XPC_SERVICE = 0
// 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.
INSTALLER_CONNECTION_NAME = InstallerConnection
INSTALLER_STATUS_NAME = InstallerStatus
INSTALLER_LAUNCHER_NAME = Installer
DOWNLOADER_NAME = Downloader
// Set this to your own prefix if you want to use XPC Service bundle IDs with different prefix
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
// Set to 0 to only build all non-UI bits
SPARKLE_BUILD_UI_BITS = 1
@@ -18,13 +40,15 @@ SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME = 0
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 = 0
SPARKLE_VERSION_PATCH = 0
SPARKLE_VERSION_MINOR = 2
SPARKLE_VERSION_PATCH = 1
// This should be in SemVer format or empty, ie. "-beta.1"
SPARKLE_VERSION_SUFFIX = -beta.1
CURRENT_PROJECT_VERSION = 2001
// These variables must have a space after the '=' too
SPARKLE_VERSION_SUFFIX =
CURRENT_PROJECT_VERSION = 2017
MARKETING_VERSION = $(SPARKLE_VERSION_MAJOR).$(SPARKLE_VERSION_MINOR).$(SPARKLE_VERSION_PATCH)$(SPARKLE_VERSION_SUFFIX)
ALWAYS_SEARCH_USER_PATHS = NO
@@ -36,13 +60,7 @@ MACOSX_DEPLOYMENT_TARGET = 10.11
PRODUCT_NAME = ${TARGET_NAME}
PRODUCT_BUNDLE_IDENTIFIER = org.sparkle-project.Sparkle.${PRODUCT_NAME:rfc1034identifier}
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
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_BUNDLE_ID=\"${INSTALLER_LAUNCHER_BUNDLE_ID}\" INSTALLER_CONNECTION_BUNDLE_ID=\"${INSTALLER_CONNECTION_BUNDLE_ID}\" INSTALLER_STATUS_BUNDLE_ID=\"${INSTALLER_STATUS_BUNDLE_ID}\" DOWNLOADER_BUNDLE_ID=\"${DOWNLOADER_BUNDLE_ID}\"
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}\"
CODE_SIGN_IDENTITY = -
SDKROOT = macosx
@@ -100,4 +118,4 @@ GCC_WARN_UNUSED_VARIABLE = YES
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 $(WARNING_CFLAGS_EXTRA)
WARNING_CFLAGS = -Wall -Weverything -Wno-unused-macros -Wno-gnu-statement-expression -Wno-arc-repeated-use-of-weak -Wno-auto-import -Wno-gnu-zero-variadic-macro-arguments -Wno-format-non-iso -Wno-direct-ivar-access $(WARNING_CFLAGS_EXTRA)
+1 -1
View File
@@ -3,6 +3,6 @@
INFOPLIST_FILE = Downloader/Info.plist
WRAPPER_EXTENSION = xpc
PRODUCT_BUNDLE_IDENTIFIER = ${DOWNLOADER_BUNDLE_ID}
PRODUCT_NAME = ${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
+9 -1
View File
@@ -4,7 +4,15 @@ DYLIB_INSTALL_NAME_BASE = @rpath
DYLIB_COMPATIBILITY_VERSION = 1.6
DYLIB_CURRENT_VERSION = $(SPARKLE_VERSION_MAJOR).$(SPARKLE_VERSION_MINOR).$(SPARKLE_VERSION_PATCH)
WRAPPER_EXTENSION = framework
FRAMEWORK_VERSION = A
// Sparkle 2 used to support developers embedding XPC Services in their own app bundle
// However the Sparkle framework now bundles these XPC Services. Unfortunately this causes
// a cache conflict in the system from upgrading from previous to newer versions of Sparkle, and
// XPC Services inside Sparkle may not launch (a system reboot would fix this though).
// The system cache seems to depend on the Sparkle file path,
// so as a better workaround we have changed the FRAMEWORK_VERSION from A to B
FRAMEWORK_VERSION = B
INFOPLIST_FILE = Sparkle/Sparkle-Info.plist
GCC_PREPROCESSOR_DEFINITIONS = $(inherited) BUILDING_SPARKLE=1
SKIP_INSTALL = YES
@@ -3,4 +3,4 @@
INFOPLIST_FILE = InstallerConnection/Info.plist
WRAPPER_EXTENSION = xpc
PRODUCT_BUNDLE_IDENTIFIER = ${INSTALLER_CONNECTION_BUNDLE_ID}
PRODUCT_NAME = ${INSTALLER_CONNECTION_BUNDLE_ID}
PRODUCT_NAME = ${INSTALLER_CONNECTION_NAME}
@@ -3,4 +3,4 @@
INFOPLIST_FILE = InstallerLauncher/Info.plist
WRAPPER_EXTENSION = xpc
PRODUCT_BUNDLE_IDENTIFIER = ${INSTALLER_LAUNCHER_BUNDLE_ID}
PRODUCT_NAME = ${INSTALLER_LAUNCHER_BUNDLE_ID}
PRODUCT_NAME = ${INSTALLER_LAUNCHER_NAME}
@@ -3,4 +3,4 @@
INFOPLIST_FILE = InstallerStatus/Info.plist
WRAPPER_EXTENSION = xpc
PRODUCT_BUNDLE_IDENTIFIER = ${INSTALLER_STATUS_BUNDLE_ID}
PRODUCT_NAME = ${INSTALLER_STATUS_BUNDLE_ID}
PRODUCT_NAME = ${INSTALLER_STATUS_NAME}
+3
View File
@@ -1,3 +1,6 @@
// Copyright © 2019 Sparkle Project. All rights reserved.
#include "bsdiff-Shared.xcconfig"
// Disable asserts for performance
GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS) NDEBUG=1
-93
View File
@@ -1,93 +0,0 @@
#!/usr/bin/env python3
import os, sys, subprocess, tempfile, pathlib
PRODUCT_BUNDLE_ID_MACRO = "$(PRODUCT_BUNDLE_IDENTIFIER)"
def log_message(message):
sys.stderr.write(message + "\n")
#Surround a token with double quotes if it has a space in it
def sanitize(argument):
return ('"' + argument + '"' if ' ' in argument else argument)
def _codesign_service(identity, path, entitlements_path=None):
command = ["codesign", "-o", "runtime", "-fs", identity, path] + ([] if entitlements_path is None else ["--entitlements", entitlements_path])
log_message(" ".join(map(sanitize, command)))
process = subprocess.Popen(command, stdout=subprocess.PIPE)
process.communicate()
if process.returncode != 0:
log_message("Error: Failed to codesign %s" % (path))
sys.exit(1)
def codesign_service(service_name, identity, path, entitlements_path=None):
#Sign the auxiliary executables (if any)
executables_path = os.path.join(path, "Contents/MacOS/")
if os.path.exists(executables_path):
for executable in os.listdir(executables_path):
if executable != service_name:
_codesign_service(identity, os.path.join(executables_path, executable), entitlements_path)
#Sign the service bundle
_codesign_service(identity, path, entitlements_path)
# Returns entitlements back with a bundle id applied if needed
def applied_entitlements_path(entitlements_path, bundle_id, temp_dir):
entitlements_str = pathlib.Path(entitlements_path).read_text()
if PRODUCT_BUNDLE_ID_MACRO in entitlements_str:
if bundle_id is None:
return None
else:
new_entitlements_str = entitlements_str.replace(PRODUCT_BUNDLE_ID_MACRO, bundle_id)
new_entitlements_path = os.path.join(temp_dir, os.path.basename(entitlements_path))
pathlib.Path(new_entitlements_path).write_text(new_entitlements_str)
return new_entitlements_path
else:
return entitlements_path
def print_usage():
log_message("Usage:\n\t%s code-signing-identity [-b app-bundle-id] service1 service2 ..." % (sys.argv[0]))
log_message("Example:\n\t%s \"Developer ID Application\" ./XPCServices/org.sparkle-project.InstallerLauncher.xpc" % (sys.argv[0]))
log_message("")
log_message("Use this script to sign XPC Services to include in your Sandboxed application.")
log_message("")
log_message("bundle-id is optional and only needs to be provided when signing InstallerConnection and InstallerStatus services. Most applications do not need to use these services and can provide additional entitlements to their application instead.")
log_message("")
log_message("This script may not be needed for common development workflows. Please visit https://sparkle-project.org/documentation/sandboxing/ for more details and instructions.")
if __name__ == "__main__":
if len(sys.argv) < 3:
print_usage()
sys.exit(1)
signing_identity = sys.argv[1]
remaining_args = sys.argv[2:]
bundle_id = None
if remaining_args[0] == '-b':
if len(remaining_args) < 3:
# We need the bundle-id and at least one XPC Service to sign
print_usage()
sys.exit(1)
else:
bundle_id = remaining_args[1]
services = remaining_args[2:]
else:
services = remaining_args
with tempfile.TemporaryDirectory() as temp_dir:
for service in services:
parent, child = os.path.split(service)
service_name = os.path.splitext(child)[0]
entitlements_path = os.path.join(parent, service_name + ".entitlements")
if os.path.exists(entitlements_path):
service_entitlements_path = applied_entitlements_path(entitlements_path, bundle_id, temp_dir)
if service_entitlements_path is None:
print_usage()
log_message("")
log_message("Error: Bundle ID must be specified for signing %s. As noted in the usage above, you probably don't need to embed this service." % (service_name))
sys.exit(1)
else:
service_entitlements_path = None
codesign_service(service_name, signing_identity, service, service_entitlements_path)
+23
View File
@@ -0,0 +1,23 @@
#!/usr/bin/env python3
import os, sys
# Ignore the first version line starting with # x.y.z..
# and print everything until the second version line starting with # x.y.z..
hit_first_changelog_note = False
with open("CHANGELOG", "r") as changelog_file:
for line in changelog_file:
if line.startswith("#"):
if hit_first_changelog_note:
# We are done with printing changes
break
else:
# We haven't hit an important changelog line yet, so continue
continue
if not hit_first_changelog_note and len(line.strip()) == 0:
continue
hit_first_changelog_note = True
sys.stdout.write(line)
+8 -1
View File
@@ -1,6 +1,13 @@
#!/bin/sh
# Create symlinks to our helper tools in Sparkle and SparkleCore framework bundles
# If Carthage is trying to build us, it won't preserve code signing information from our bundled tools properly
# Building Sparkle from source with Carthage is thus not supported
if [ "$CARTHAGE" = "YES" ]; then
echo "Error: Building Sparkle from source using Carthage is not supported. Please visit https://sparkle-project.org/documentation/ for proper Carthage integration."
exit 1
fi
# Create symlinks to our helper tools in Sparkle framework bundle
# so URLForAuxiliaryExecutable: will pick up the tools. Doing this is supported in the Code Signing in Depth guide.
FRAMEWORK_PATH="${TARGET_BUILD_DIR}"/"${FULL_PRODUCT_NAME}"
+36 -40
View File
@@ -13,10 +13,6 @@ 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}/XPCServices/org.sparkle-project.Downloader.xpc"
codesign --verify -vvv --deep "${verification_directory}/XPCServices/org.sparkle-project.InstallerConnection.xpc"
codesign --verify -vvv --deep "${verification_directory}/XPCServices/org.sparkle-project.InstallerLauncher.xpc"
codesign --verify -vvv --deep "${verification_directory}/XPCServices/org.sparkle-project.InstallerStatus.xpc"
codesign --verify -vvv --deep "${verification_directory}/sparkle.app"
codesign --verify -vvv --deep "${verification_directory}/Sparkle Test App.app"
codesign --verify -vvv --deep "${verification_directory}/bin/BinaryDelta"
@@ -41,55 +37,49 @@ if [ "$ACTION" = "" ] ; then
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 "$SRCROOT/Configurations/codesign_xpc_service.py" "$CONFIGURATION_BUILD_DIR/staging/bin/codesign_xpc_service"
chmod 0755 "$CONFIGURATION_BUILD_DIR/staging/bin/codesign_xpc_service"
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/XPCServices"
cp -R "$CONFIGURATION_BUILD_DIR/$INSTALLER_LAUNCHER_BUNDLE_ID.xpc" "$CONFIGURATION_BUILD_DIR/staging/XPCServices"
cp -R "$CONFIGURATION_BUILD_DIR/$DOWNLOADER_BUNDLE_ID.xpc" "$CONFIGURATION_BUILD_DIR/staging/XPCServices"
cp -R "$CONFIGURATION_BUILD_DIR/$INSTALLER_CONNECTION_BUNDLE_ID.xpc" "$CONFIGURATION_BUILD_DIR/staging/XPCServices"
cp -R "$CONFIGURATION_BUILD_DIR/$INSTALLER_STATUS_BUNDLE_ID.xpc" "$CONFIGURATION_BUILD_DIR/staging/XPCServices"
cp "$SRCROOT/Downloader/$DOWNLOADER_BUNDLE_ID.entitlements" "$CONFIGURATION_BUILD_DIR/staging/XPCServices"
cp "$SRCROOT/InstallerConnection/$INSTALLER_CONNECTION_BUNDLE_ID.entitlements" "$CONFIGURATION_BUILD_DIR/staging/XPCServices"
cp "$SRCROOT/InstallerStatus/$INSTALLER_STATUS_BUNDLE_ID.entitlements" "$CONFIGURATION_BUILD_DIR/staging/XPCServices"
mkdir -p "$CONFIGURATION_BUILD_DIR/staging/Symbols"
# Only copy dSYMs for Release builds, but don't check for the presence of the actual files
# because missing dSYMs in a release build SHOULD trigger a build failure
if [ "$CONFIGURATION" = "Release" ] ; then
cp -R "$CONFIGURATION_BUILD_DIR/BinaryDelta.dSYM" "$CONFIGURATION_BUILD_DIR/staging/bin"
cp -R "$CONFIGURATION_BUILD_DIR/generate_appcast.dSYM" "$CONFIGURATION_BUILD_DIR/staging/bin"
cp -R "$CONFIGURATION_BUILD_DIR/generate_keys.dSYM" "$CONFIGURATION_BUILD_DIR/staging/bin"
cp -R "$CONFIGURATION_BUILD_DIR/sign_update.dSYM" "$CONFIGURATION_BUILD_DIR/staging/bin"
cp -R "$CONFIGURATION_BUILD_DIR/Sparkle Test App.app.dSYM" "$CONFIGURATION_BUILD_DIR/staging"
cp -R "$CONFIGURATION_BUILD_DIR/Sparkle Test App.app.dSYM" "$CONFIGURATION_BUILD_DIR/staging-spm"
cp -R "$CONFIGURATION_BUILD_DIR/sparkle.app.dSYM" "$CONFIGURATION_BUILD_DIR/staging"
cp -R "$CONFIGURATION_BUILD_DIR/sparkle.app.dSYM" "$CONFIGURATION_BUILD_DIR/staging-spm"
cp -R "$CONFIGURATION_BUILD_DIR/Sparkle.framework.dSYM" "$CONFIGURATION_BUILD_DIR/staging"
cp -R "$CONFIGURATION_BUILD_DIR/$INSTALLER_LAUNCHER_BUNDLE_ID.xpc.dSYM" "$CONFIGURATION_BUILD_DIR/staging/XPCServices"
cp -R "$CONFIGURATION_BUILD_DIR/$DOWNLOADER_BUNDLE_ID.xpc.dSYM" "$CONFIGURATION_BUILD_DIR/staging/XPCServices"
cp -R "$CONFIGURATION_BUILD_DIR/$INSTALLER_CONNECTION_BUNDLE_ID.xpc.dSYM" "$CONFIGURATION_BUILD_DIR/staging/XPCServices"
cp -R "$CONFIGURATION_BUILD_DIR/$INSTALLER_STATUS_BUNDLE_ID.xpc.dSYM" "$CONFIGURATION_BUILD_DIR/staging/XPCServices"
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/XPCServices" "$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"
@@ -116,7 +106,7 @@ if [ "$ACTION" = "" ] ; then
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"
@@ -128,7 +118,7 @@ if [ "$ACTION" = "" ] ; then
# 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"
@@ -144,10 +134,12 @@ if [ "$ACTION" = "" ] ; then
exit 1
fi
# Generate new Package manifest and podspec
# 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"
if [ "$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")
@@ -160,16 +152,20 @@ if [ "$ACTION" = "" ] ; then
echo "Checksum: $spm_checksum"
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"
echo "Sparkle.podspec updated with following values:"
# 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"
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" -eq 1 ] ; then
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
+5 -5
View File
@@ -9,8 +9,8 @@ function move_tag() {
long_message=$(git tag -n99 -l $latest_git_tag) # gets corresponding message
long_message=${long_message/$latest_git_tag} # trims tag name
long_message="$(echo -e "${long_message}" | sed -e 's/^[[:space:]]*//')" # trim leading whitespace
git add Package.swift Sparkle.podspec
git commit -m "Update Package.swift and Sparkle.podspec for version ${latest_git_tag}"
git add Package.swift Sparkle.podspec Carthage-dev.json
git commit -m "Update Package management files for version ${latest_git_tag}"
git tag -fa $latest_git_tag -m "${long_message}"
echo "Package.swift and Sparkle.podspec committed and tag '$latest_git_tag' moved."
}
@@ -18,16 +18,16 @@ function move_tag() {
if [ "$commits_since_tag" -gt 0 ]; then
# If there have been commits since the latest tag, it's highly likely that we did not intend to do a full release
echo "WARNING: $commits_since_tag commit(s) since tag '$latest_git_tag'. Did you tag a new version?"
echo "Package.swift has not been committed and tag has not been moved."
echo "Package management files have not been committed and tag has not been moved."
elif [ "$CI" == true ]; then
move_tag
else
# TODO: add sanity check to see if version is actually being updated or not?
read -p "Do you want to commit changes to Package.swift and Sparkle.podspec, and force move tag '$latest_git_tag'? (required for official release) [Y/n]" -n 1 -r
read -p "Do you want to commit changes to Package.swift, Sparkle.podspec, Carthage-dev.json and force move tag '$latest_git_tag'? (required for official release) [Y/n]" -n 1 -r
echo # (optional) move to a new line
if [[ $REPLY =~ ^[Yy]$ ]]; then
move_tag
else
echo "Package.swift and Sparkle.podspec have not been committed and tag has not been moved."
echo "Package.swift, Sparkle.podspec, and Carthage-dev.json have not been committed and tag has not been moved."
fi
fi
+30
View File
@@ -0,0 +1,30 @@
#!/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
+20
View File
@@ -0,0 +1,20 @@
#!/usr/bin/env python3
import os, sys, json
if len(sys.argv) < 3:
print("Usage: path-to-carthage-file release-tag")
sys.exit(1)
carthage_file = sys.argv[1]
release_tag = sys.argv[2]
with open(carthage_file, "r") as json_file:
data = json.load(json_file)
if release_tag in data:
sys.exit(0)
with open(carthage_file, "w") as json_file:
data[release_tag] = "https://github.com/sparkle-project/Sparkle/releases/download/" + release_tag + "/Sparkle-" + release_tag + ".tar.xz"
json.dump(data, json_file)
+12
View File
@@ -0,0 +1,12 @@
# Sparkle 2 API Reference
These are the primary classes and protocols in Sparkle 2 you may be interested in:
- `SPUStandardUpdaterController` for creating a standard updater (encapsulates a `SPUUpdater` and `SPUStandardUserDriver`)
- `SPUUpdater` for invoking update checks and retrieving updater properties.
- `SPUUpdaterDelegate` for delegation methods to control the behavior of `SPUUpdater`.
- `SPUUserDriver` for making custom user interfaces.
If you are migrating from Sparkle 1, please refer to `SPUStandardUpdaterController` and `SPUUpdater`.
Please also visit the [Basic Setup](https://sparkle-project.org/documentation/) guide which shows how to instantiate an updater in a nib or how to create one programmatically.
+2 -2
View File
@@ -2,7 +2,7 @@
## XPC Services
XPC services in Sparkle are all optional, so the code involved in the services needs to be usable directly from the framework as well. For this to work well, if the class used in the XPC service takes a delegate, it must not be weakly referenced, so the retain cycle will have to be broken explicitly (via an explicit added invalidate method). dealloc also must not be implemented (do cleanup in custom invalidate method). As one may tell, a couple of the services are simply proxies (InstallerConnection, InstallerStatus), and I wish that didn't have to be the case -- it would be a burden to require a developer to set up a temporary exception with a specific bundle ID, and unsure how long that approach would work for in the future.
XPC services in Sparkle are all optional, so the code involved in the services needs to be usable directly from the framework as well. For this to work well, if the class used in the XPC service takes a delegate, it must not be weakly referenced, so the retain cycle will have to be broken explicitly (via an explicit added invalidate method). dealloc also must not be implemented (do cleanup in custom invalidate method). As one may tell, two of the services are simply proxies (InstallerConnection, InstallerStatus) -- we now recommend most developers to set up a temporary exception with their bundle ID rather than use these two services.
The protocols used in XPC services must also not adopt other protocols (i.e, one protocol inheriting from another protocol). This is because the XPC protocol decoder on older supported systems doesn't properly handle this case, and won't be able to find that methods exist on a class.
@@ -18,7 +18,7 @@ The original `SUUpdater` may have also been created to assist plug-ins and other
## Extensibility
This fork 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 in this fork. 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 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.
I hope the user driver API gives enough extensibility without someone wanting to create another fork.
-20
View File
@@ -1,20 +0,0 @@
PROJECT_NAME = Sparkle
PROJECT_NUMBER = 1.14.0
PROJECT_BRIEF = "A software update framework for macOS"
PROJECT_LOGO = Resources/Images.xcassets/AppIcon.appiconset/icon_32x32@2x.png
RECURSIVE = YES
INPUT = Sparkle
OUTPUT_DIRECTORY = Documentation
GENERATE_HTML = YES
GENERATE_LATEX = NO
GENERATE_BUGLIST = YES
GENERATE_DEPRECATEDLIST = YES
GENERATE_TODOLIST = YES
ALPHABETICAL_INDEX = YES
QT_AUTOBRIEF = YES
WARN_IF_UNDOCUMENTED = NO
+9 -11
View File
@@ -11,23 +11,23 @@
## After downloading the update:
### Launching the Installer
SPUCoreBasedUpdateDriver invokes SPUInstallerDriver's extraction method which invokes SUInstallerLauncher's launch installer method. The launcher can be inside a XPC service or running inside the updater/sparkle framework itself. The launcher XPC bundle includes a copy of the installer and agent application in its bundle so it can compute the path to them itself (instead of relying on the updater to pass the paths), which is for security trust reasons.
SPUCoreBasedUpdateDriver invokes SPUInstallerDriver's extraction method which invokes SUInstallerLauncher's launch installer method. An XPC Service may be used to launch the installer if necessary for Sandboxed applications.
First, the launcher makes sure that if the updater delegate doesn't allow interaction, that installation can be done without interaction. If it can't, then the launcher fails. If the updater driver that invoked the launcher doesn't allow for interaction (in particular, the automatic/silent update driver does not allow interaction), then the launcher fails with a hint to try again with interaction enabled (in particular, with a UI based update driver). If this happens, the updater keeps a reference to the downloaded update and appcast item that is used for resuming with a UI based update driver later. The launcher in this case is telling that authorization can only be done if interaction is allowed from the driver, so the user can enter their password to start up the installer as root to install over a location that requires such privileges.
First, if the updater driver that invoked the launcher doesn't allow for interaction (in particular, the automatic/silent update driver does not allow interaction), then the launcher fails with a hint to try again with interaction enabled (in particular, with a UI based update driver). If this happens, the updater keeps a reference to the downloaded update and appcast item that is used for resuming with a UI based update driver later. The launcher in this case is telling that authorization can only be done if interaction is allowed from the driver, so the user can enter their password to start up the installer as root to install over a location that requires such privileges.
The launcher then looks for the installer and agent application first in its bundle's auxiliary directory path, and then its resources path. If the launcher is running inside a XPC service, the tools will be in the auxiliary path location, which allows the developer using the service to also code sign the tools. Once those paths are found, the launcher copies the progress agent application to a temporary cache location. The installer is not copied because it is a plain single executable that does not rely on external relative depedencies, whereas the agent application relies on bundle resources. This is important to consider because the old application may be moved around and removed when the installation process occurs. Leaving the installer inside its bundle also could leave it in a place the user doesn't necessarily have write privileges to.
The launcher then looks for the installer and agent application. If we are inside the XPC Service, a relative path back to the framework auxiliary directory is computed otherwise the bundle's auxiliary directory path is retrieved. Once those paths are found, the launcher copies the progress agent application to a temporary cache location. The installer is not copied because it is a plain single executable that does not rely on external relative dependencies, whereas the agent application relies on bundle resources. This is important to consider because the old application may be moved around and removed when the installation process occurs. Leaving the installer inside its bundle also could leave it in a place the user doesn't necessarily have write privileges to.
The installer is first submitted. If it requires root privileges, it will ask for an admin user name and password. How it determines if root privileges are necessary is based on:
* If the installation type from the appcast is an interactive package based installer, then no root privileges are necessary because the package installer will ask for them. Note this type of installation is deprecated however.
* If the installation type from the appcast is a guided or regular package based installer, then root privileges are necessary because the system installer utility has to run as root.
* Otherwise the installation type is a normal application update, and root privileges are only needed if write permission or changing the owner/group is currently insufficient.
* Otherwise the installation type is a normal application update, and root privileges are only needed if write permission or changing the owner is currently insufficient.
The installer makes sure, after extraction, that the expected installation type from the appcast matches the type of installation found within the archive. So this hint from the appcast is not just trusted implicitly.
If the user cancels submitting the installer on authorization (if it's required), the launcher aborts the installation process silently. If everything does alright, the progress agent application is submitted next. If either of the submissions fail, the installation fails and aborts, otherwise the launcher succeeds and its job is done. Note before the submissions are done, the jobs are removed from launchd, and the jobs are submitted in a way that act as "one-time" jobs. If they fail or succeed, the jobs aren't restarted, and the jobs aren't installed in a system location for launchd to attempt launching again.
If the user cancels submitting the installer on authorization (if it's required), the launcher aborts the installation process silently. If everything goes alright, the progress agent application is submitted next. If either of the submissions fail, the installation fails and aborts, otherwise the launcher succeeds and its job is done. Note before the submissions are done, the jobs are removed from launchd, and the jobs are submitted in a way that act as "one-time" jobs. If they fail or succeed, the jobs aren't restarted, and the jobs aren't installed in a system location for launchd to attempt launching again.
The only argument passed to the installer is the host bundle identifier of the bundle to update. This bundle identifier is used so that the installer and updater know what Mach service to connect to for IPC. Everything else to the installer is sent via a XPC connection. The host bundle path is passed to the progress agent, which is just used for obtaining the bundle identifier, and for UI purposes (eg: displaying app icon and name when the app needs to show progress). The type of domain the installer is running in (user vs system) is also passed to the progress agent application so it can know which domain to use to connect to the installer.
The most important argument passed to the installer is the host bundle identifier of the bundle to update. This bundle identifier is used so that the installer and updater know what Mach service to connect to for IPC. Mostly everything else to the installer is sent via a XPC connection. The host bundle path is passed to the progress agent, which is just used for obtaining the bundle identifier, and for UI purposes (eg: displaying app icon and name when the app needs to show progress). The type of domain the installer is running in (user vs system) is also passed to the progress agent application so it can know which domain to use to connect to the installer.
### Timeouts
@@ -37,10 +37,8 @@ If the installer doesn't receive the "hello" message from the agent in a certain
When the updater attempts to set up a connection to the installer, after a certain threshold, if the installation hasn't progressed from not beginning (i.e, extraction hasn't begun), then the updater aborts the installation.
Note, we don't have a "version tag" for the installer or agent because they are either bundled inside the framework or in the XPC service, and the XPC service already has a version check of its own.
### Installation Data
After the installer launches, the updater creates a connection to the installer and sends installation data to the installer using the `SPUInstallationData` message. This data includes the bundle application path to relaunch, the path to the bundle to update and replace, DSA signature from the appcast item, decryption password for dmg if available, the path to the downloaded directory and name of the downloaded item, and the type of expected installation.
After the installer launches, the updater creates a connection to the installer and sends installation data to the installer using the `SPUInstallationData` message. This data includes the bundle application path to relaunch, the path to the bundle to update and replace, Ed(DSA) signature from the appcast item, decryption password for dmg if available, the path to the downloaded directory and name of the downloaded item, and the type of expected installation.
The installer takes note of all this information, but it moves the downloaded item into a update directory it chooses for itself. This is for two reasons:
@@ -52,7 +50,7 @@ After the installer moves the downloaded item, it makes sure the item is not a s
### Update Extraction
After the installer receives the input installation data, it starts extracting the update. The installer first sends a `SPUExtractionStarted` message.
If the unarchiver requires DSA validation before extraction (binary delta archives do) or if the expected installation type is a package type, then before starting the unarchiver, validation is checked to make sure the signature for the archive is valid. If the signature is not valid, then a `SPUArchiveExtractionFailed` message is sent to the updater (see below on what happens after that). We can't require validation before extracting for normal application updates because they allow changes to DSA keys. Delta updates are fine however because if those fail, then a full update can be tried.
If the unarchiver requires EdDSA validation before extraction (binary delta archives do) or if the expected installation type is a package type, then before starting the unarchiver, validation is checked to make sure the signature for the archive is valid. If the signature is not valid, then a `SPUArchiveExtractionFailed` message is sent to the updater (see below on what happens after that). We can't require validation before extracting for normal application updates because they allow changes to EdDSA keys. Delta updates are fine however because if those fail, then a full update can be tried.
After extraction starts, one or more `SPUExtractedArchiveWithProgress` messages indicating the unarchival progress are sent back to the updater. On failure, the installer will send `SPUArchiveExtractionFailed`. In the updater, if the update is a delta update and extraction fails, then the full archive is downloaded and we go back to the "Sending Installation Data" section to re-send the data and begin extraction again. If the update is not a delta update and extraction fails on the other hand, then the updater aborts causing the installer to abort as well.
@@ -134,4 +132,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. There may be some issues to take account of though (eg: http://www.openradar.me/20446733). 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 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.
+5 -5
View File
@@ -6,7 +6,7 @@ First, some references I've found to be quite useful:
* [EvenBetterAuthorizationExample](https://developer.apple.com/library/mac/samplecode/EvenBetterAuthorizationSample/Introduction/Intro.html) sample code by Apple for showing off privileged authorization as well as in sandboxed applications.
* Apple's [Daemons and Agents Technote](https://developer.apple.com/library/mac/technotes/tn2083/_index.html). Outdated and before XPC existed, but insightful.
This fork puts a huge emphasis on splitting Sparkle into several components to achieve privilege separation.
Sparkle 2.0 puts a huge emphasis on splitting Sparkle into several components to achieve privilege separation.
* User Driver (Application; AppKit permitted)
* Updater Scheduler (Framework)
@@ -18,18 +18,18 @@ These achieve privilege separation, because at least theoretically, they can all
For XPC Services, it's significant to understand they can be used independent of sandboxing (although I wouldn't recommend this personally). Besides privilege separation, they also have an impact on fault tolerance and termination.
XPC Services also act inside an application bundle namespace, which is one of many reasons why they aren't bundled inside the framework. We have code that detects whether or not services are available inside the main 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.
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.
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.
When developing this fork, I still had a huge hole in the privilege separation even after supporting XPC Services and sandboxing. I fixed that by removing references to `AuthorizationExecuteWithPrivileges` and submitting a launchd agent/daemon for the installer. This is overlooked, but absolutely essential for our model to be secure.
When developing Sparkle 2.0, I still had a huge hole in the privilege separation even after supporting XPC Services and sandboxing. I fixed that by removing references to `AuthorizationExecuteWithPrivileges` and submitting a launchd agent/daemon for the installer. This is overlooked, but absolutely essential for our model to be secure.
When communicating to a launchd job, we've several options to use for IPC such as BSD Sockets, Mach ports, XPC (note: XPC is an IPC API and is != "XPC Services"), and file IO. The technote I linked above describes why Mach ports have user namespace issues and why BSD sockets may be preferred over them. However, now, XPC which allows you to choose which domain to look up is the simplest, best, and most modern choice. It's crucial in any event we don't have a daemon (running in system domain) try to *connect* to something in the user domain. Our launchd tasks should also be connected to rather than the other way around. As for communication via file IO, I just wouldn't go anywhere close to trusting such a model mixing in system and user running processes.
For sending Obj-C objects across the wire, we use `SPUSecureCoding` because Cocoa doesn't support sending objects securely out of the box unless working with XPC Services. It's very important the objects implement `NSSecureCoding` and whitelist types that are expected to be decoded, as well as whitelist types inside collections before decoding them.
The installer handles extraction, validation, and installation of the update. This was the main reason why other forks were rejected from being secure. The point to be stressed anyway is that these all need to be done in the same process; they can't be handed off by some other process. This is also why removing references to `AuthorizationExecuteWithPrivileges` is crucial as well.
The installer handles extraction, validation, and installation of the update. This was the main reason why other sandboxed-capable forks were rejected from being secure. The point to be stressed anyway is that these all need to be done in the same process; they can't be handed off by some other process. This is also why removing references to `AuthorizationExecuteWithPrivileges` is crucial as well.
Note that the installer does *not* handle downloading. That is handled by the updater framework. This is ideal because downloading can be done without disrupting the user, allowing it to be done silently without presenting an authorization dialog. The downloading portion of code can also be stuck into a XPC service with just an entitlement for allowing incoming connections. This also means for secure installations the installer cannot know (or trust) what protocol the update was downloaded from (i.e: http vs https). A good installer will not care, which is why applying updates without a DSA signature/key is now deprecated (reminder that Apple's code signature checks are not intended for complete integrity).
Note that the installer does *not* handle downloading. That is handled by the updater framework. This is ideal because downloading can be done without disrupting the user, allowing it to be done silently without presenting an authorization dialog. The downloading portion of code can also be stuck into a XPC service with just an entitlement for allowing incoming connections. This also means for secure installations the installer cannot know (or trust) what protocol the update was downloaded from (i.e: http vs https). A good installer will not care, which is why applying updates without a EdDSA signature/key is now deprecated (reminder that Apple's code signature checks are not intended for complete integrity).
+13 -7
View File
@@ -9,7 +9,6 @@
#import "SPUDownloader.h"
#import "SPUDownloaderDelegate.h"
#import "SPULocalCacheDirectory.h"
#import "SPUURLRequest.h"
#import "SPUDownloadData.h"
#import "SPUDownloadDataPrivate.h"
#import "SUErrors.h"
@@ -61,19 +60,19 @@ static NSString *SUDownloadingReason = @"Downloading update related file";
return self;
}
- (void)startDownloadWithRequest:(SPUURLRequest *)request
- (void)startDownloadWithRequest:(NSURLRequest *)request
{
self.downloadSession = [NSURLSession
sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]
delegate:self
delegateQueue:[NSOperationQueue mainQueue]];
self.download = [self.downloadSession downloadTaskWithRequest:request.request];
self.download = [self.downloadSession downloadTaskWithRequest:request];
[self.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
- (void)startPersistentDownloadWithRequest:(SPUURLRequest *)request bundleIdentifier:(NSString *)bundleIdentifier desiredFilename:(NSString *)desiredFilename
- (void)startPersistentDownloadWithRequest:(NSURLRequest *)request bundleIdentifier:(NSString *)bundleIdentifier desiredFilename:(NSString *)desiredFilename
{
dispatch_async(dispatch_get_main_queue(), ^{
if (self.download == nil && self.delegate != nil) {
@@ -90,7 +89,7 @@ static NSString *SUDownloadingReason = @"Downloading update related file";
});
}
- (void)startTemporaryDownloadWithRequest:(SPUURLRequest *)request
- (void)startTemporaryDownloadWithRequest:(NSURLRequest *)request
{
dispatch_async(dispatch_get_main_queue(), ^{
if (self.download == nil && self.delegate != nil) {
@@ -159,9 +158,16 @@ static NSString *SUDownloadingReason = @"Downloading update related file";
});
}
- (void)URLSession:(NSURLSession *)__unused session downloadTask:(NSURLSessionDownloadTask *)__unused downloadTask didFinishDownloadingToURL:(NSURL *)location
- (void)URLSession:(NSURLSession *)__unused session downloadTask:(NSURLSessionDownloadTask *) downloadTask didFinishDownloadingToURL:(NSURL *)location
{
if (self.mode == SPUDownloadModeTemporary)
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];
NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUDownloadError userInfo:@{ NSLocalizedDescriptionKey: message }];
[self.delegate downloaderDidFailWithError:error];
}
else if (self.mode == SPUDownloadModeTemporary)
{
self.downloadFilename = location.path;
[self downloadDidFinish]; // file is already in a system temp dir
+2 -4
View File
@@ -10,14 +10,12 @@
NS_ASSUME_NONNULL_BEGIN
@class SPUURLRequest;
// The protocol that this service will vend as its API. This header file will also need to be visible to the process hosting the service.
@protocol SPUDownloaderProtocol
- (void)startPersistentDownloadWithRequest:(SPUURLRequest *)request bundleIdentifier:(NSString *)bundleIdentifier desiredFilename:(NSString *)desiredFilename;
- (void)startPersistentDownloadWithRequest:(NSURLRequest *)request bundleIdentifier:(NSString *)bundleIdentifier desiredFilename:(NSString *)desiredFilename;
- (void)startTemporaryDownloadWithRequest:(SPUURLRequest *)request;
- (void)startTemporaryDownloadWithRequest:(NSURLRequest *)request;
- (void)removeDownloadDirectory:(NSString *)directoryName bundleIdentifier:(NSString *)bundleIdentifier;
+3 -1
View File
@@ -15,7 +15,9 @@ NS_ASSUME_NONNULL_BEGIN
@interface SUInstallerConnection : NSObject <SUInstallerConnectionProtocol>
// Due to XPC reasons, this delegate is strongly referenced, until it's invalidated
- (instancetype)initWithDelegate:(id<SUInstallerCommunicationProtocol>)delegate;
- (instancetype)initWithDelegate:(id<SUInstallerCommunicationProtocol>)delegate remote:(BOOL)remote;
- (instancetype)init NS_UNAVAILABLE;
@end
+67 -24
View File
@@ -25,21 +25,27 @@ static NSString *SUInstallerConnectionKeepAliveReason = @"Installer Connection K
@end
@implementation SUInstallerConnection
{
BOOL _remote;
}
@synthesize delegate = _delegate;
@synthesize disabledAutomaticTermination = _disabledAutomaticTermination;
@synthesize invalidationBlock = _invalidationBlock;
@synthesize connection = _connection;
- (instancetype)initWithDelegate:(id<SUInstallerCommunicationProtocol>)delegate
- (instancetype)initWithDelegate:(id<SUInstallerCommunicationProtocol>)delegate remote:(BOOL)remote
{
self = [super init];
if (self != nil) {
_delegate = delegate;
_remote = remote;
// If we are a XPC service, protect it from being terminated until the invalidation handler is set
_disabledAutomaticTermination = YES;
[[NSProcessInfo processInfo] disableAutomaticTermination:SUInstallerConnectionKeepAliveReason];
if (remote) {
// If we are a XPC service, protect it from being terminated until the invalidation handler is set
_disabledAutomaticTermination = YES;
[[NSProcessInfo processInfo] disableAutomaticTermination:SUInstallerConnectionKeepAliveReason];
}
}
return self;
}
@@ -52,7 +58,7 @@ static NSString *SUInstallerConnectionKeepAliveReason = @"Installer Connection K
}
}
- (void)setInvalidationHandler:(void (^)(void))invalidationHandler
- (void)_setInvalidationHandler:(void (^)(void))invalidationHandler
{
self.invalidationBlock = invalidationHandler;
@@ -60,7 +66,18 @@ static NSString *SUInstallerConnectionKeepAliveReason = @"Installer Connection K
[self enableAutomaticTermination];
}
- (void)setServiceName:(NSString *)serviceName systemDomain:(BOOL)systemDomain
- (void)setInvalidationHandler:(void (^)(void))invalidationHandler
{
if (_remote) {
dispatch_async(dispatch_get_main_queue(), ^{
[self _setInvalidationHandler:invalidationHandler];
});
} else {
[self _setInvalidationHandler:invalidationHandler];
}
}
- (void)_setServiceName:(NSString *)serviceName systemDomain:(BOOL)systemDomain
{
NSXPCConnectionOptions options = systemDomain ? NSXPCConnectionPrivileged : 0;
NSXPCConnection *connection = [[NSXPCConnection alloc] initWithMachServiceName:serviceName options:options];
@@ -74,41 +91,67 @@ static NSString *SUInstallerConnectionKeepAliveReason = @"Installer Connection K
__weak SUInstallerConnection *weakSelf = self;
self.connection.interruptionHandler = ^{
[weakSelf.connection invalidate];
dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf.connection invalidate];
});
};
self.connection.invalidationHandler = ^{
SUInstallerConnection *strongSelf = weakSelf;
if (strongSelf != nil) {
strongSelf.connection = nil;
[strongSelf invalidate];
}
dispatch_async(dispatch_get_main_queue(), ^{
SUInstallerConnection *strongSelf = weakSelf;
if (strongSelf != nil) {
strongSelf.connection = nil;
[strongSelf _invalidate];
}
});
};
[self.connection resume];
}
- (void)handleMessageWithIdentifier:(int32_t)identifier data:(NSData *)data
- (void)setServiceName:(NSString *)serviceName systemDomain:(BOOL)systemDomain
{
[(id<SUInstallerCommunicationProtocol>)self.connection.remoteObjectProxy handleMessageWithIdentifier:identifier data:data];
if (_remote) {
dispatch_async(dispatch_get_main_queue(), ^{
[self _setServiceName:serviceName systemDomain:systemDomain];
});
} else {
[self _setServiceName:serviceName systemDomain:systemDomain];
}
}
// This method can be called by us or from a remote
- (void)handleMessageWithIdentifier:(int32_t)identifier data:(NSData *)data
{
if (_remote) {
dispatch_async(dispatch_get_main_queue(), ^{
[(id<SUInstallerCommunicationProtocol>)self.connection.remoteObjectProxy handleMessageWithIdentifier:identifier data:data];
});
} else {
[(id<SUInstallerCommunicationProtocol>)self.connection.remoteObjectProxy handleMessageWithIdentifier:identifier data:data];
}
}
- (void)_invalidate
{
if (self.invalidationBlock != nil) {
self.invalidationBlock();
self.invalidationBlock = nil;
}
// Break the retain cycle
self.delegate = nil;
[self enableAutomaticTermination];
}
// This method can be called from us or a remote
- (void)invalidate
{
dispatch_async(dispatch_get_main_queue(), ^{
[self.connection invalidate];
self.connection = nil;
if (self.invalidationBlock != nil) {
self.invalidationBlock();
self.invalidationBlock = nil;
}
// Break the retain cycle
self.delegate = nil;
[self enableAutomaticTermination];
[self _invalidate];
});
}
+1 -1
View File
@@ -26,7 +26,7 @@
newConnection.exportedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUInstallerConnectionProtocol)];
newConnection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUInstallerCommunicationProtocol)];
SUInstallerConnection *exportedObject = [[SUInstallerConnection alloc] initWithDelegate:newConnection.remoteObjectProxy];
SUInstallerConnection *exportedObject = [[SUInstallerConnection alloc] initWithDelegate:newConnection.remoteObjectProxy remote:YES];
newConnection.exportedObject = exportedObject;
@@ -0,0 +1,29 @@
//
// SUInstallerLauncher+Private.h
// SUInstallerLauncher+Private
//
// Created by Mayur Pawashe on 8/21/21.
// Copyright © 2021 Sparkle Project. All rights reserved.
//
#ifndef SUInstallerLauncher_Private_h
#define SUInstallerLauncher_Private_h
#import <Sparkle/SUExport.h>
// Chances are clients will need this too
#import <Sparkle/SPUInstallationType.h>
@class NSString;
/**
Private API for determining if the system needs authorization access to update a bundle path
This API is not supported when used directly from a Sandboxed applications and will always return @c YES in that case.
@param bundlePath The bundle path to test if authorization is needed when performing an update that replaces this bundle.
@return @c YES if Sparkle thinks authorization is needed to update the @c bundlePath, otherwise @c NO.
*/
SU_EXPORT BOOL SPUSystemNeedsAuthorizationAccessForBundlePath(NSString *bundlePath);
#endif /* SUInstallerLauncher_Private_h */
+136 -75
View File
@@ -7,6 +7,7 @@
//
#import "SUInstallerLauncher.h"
#import "SUInstallerLauncher+Private.h"
#import "SUFileManager.h"
#import "SULog.h"
#import "SPUMessageTypes.h"
@@ -16,6 +17,9 @@
#import "SUHost.h"
#import <ImageIO/ImageIO.h>
#import <ServiceManagement/ServiceManagement.h>
#import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>
#import <SystemConfiguration/SystemConfiguration.h>
#include "AppKitPrevention.h"
@@ -69,13 +73,16 @@
}
}
// If we are running as the root user, there is no need to explicitly set the UserName / GroupName keys
// because we are submitting under the user domain, which should automatically use the the console user.
NSMutableDictionary *jobDictionary = [[NSMutableDictionary alloc] init];
jobDictionary[@"Label"] = label;
jobDictionary[@"ProgramArguments"] = arguments;
jobDictionary[@"EnableTransactions"] = @NO;
jobDictionary[@"KeepAlive"] = @{@"SuccessfulExit" : @NO};
jobDictionary[@"RunAtLoad"] = @NO;
jobDictionary[@"NICE"] = @0;
jobDictionary[@"Nice"] = @0;
jobDictionary[@"ProcessType"] = @"Interactive";
jobDictionary[@"LaunchOnlyOnce"] = @YES;
jobDictionary[@"MachServices"] = @{SPUStatusInfoServiceNameForBundleIdentifier(hostBundleIdentifier) : @YES};
@@ -99,7 +106,7 @@
return (submittedJob == true);
}
- (SUInstallerLauncherStatus)submitInstallerAtPath:(NSString *)installerPath withHostBundle:(NSBundle *)hostBundle updaterIdentifier:(NSString *)updaterIdentifier authorizationPrompt:(NSString *)authorizationPrompt inSystemDomain:(BOOL)systemDomain
- (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
{
SUFileManager *fileManager = [[SUFileManager alloc] init];
@@ -109,12 +116,6 @@
NSString *hostBundleIdentifier = hostBundle.bundleIdentifier;
assert(hostBundleIdentifier != nil);
NSString *homeDirectory = NSHomeDirectory();
assert(homeDirectory != nil);
NSString *userName = NSUserName();
assert(userName != nil);
// The first argument has to be the path to the program, and the second is a host identifier so that the installer knows what mach services to host
// The third and forth arguments are for home directory and user name which only pkg installer scripts may need
// We intentionally do not pass any more arguments. Anything else should be done via IPC.
@@ -132,7 +133,7 @@
BOOL canceledAuthorization = NO;
BOOL failedToUseSystemDomain = NO;
if (auth != NULL && systemDomain) {
if (auth != NULL && systemDomain && !rootUser) {
// See Apple's 'EvenBetterAuthorizationSample' sample code and
// https://developer.apple.com/library/mac/technotes/tn2095/_index.html#//apple_ref/doc/uid/DTS10003110-CH1-SECTION7
// We can set a custom right name for authenticating as an administrator
@@ -206,7 +207,16 @@
NSString *path = [[NSString alloc] initWithUTF8String:pathBuffer];
tempIconDestinationURL = [NSURL fileURLWithPath:path];
CGImageDestinationRef imageDestination = CGImageDestinationCreateWithURL((CFURLRef)tempIconDestinationURL, kUTTypePNG, 1, NULL);
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)) {
@@ -268,7 +278,7 @@
}
}
NSDictionary *jobDictionary = @{@"Label" : label, @"ProgramArguments" : arguments, @"EnableTransactions" : @NO, @"KeepAlive" : @{@"SuccessfulExit" : @NO}, @"RunAtLoad" : @NO, @"Nice" : @0, @"LaunchOnlyOnce": @YES, @"MachServices" : @{SPUInstallerServiceNameForBundleIdentifier(hostBundleIdentifier) : @YES, SPUProgressAgentServiceNameForBundleIdentifier(hostBundleIdentifier) : @YES}};
NSDictionary *jobDictionary = @{@"Label" : label, @"ProgramArguments" : arguments, @"EnableTransactions" : @NO, @"KeepAlive" : @{@"SuccessfulExit" : @NO}, @"RunAtLoad" : @NO, @"Nice" : @0, @"ProcessType": @"Interactive", @"LaunchOnlyOnce": @YES, @"MachServices" : @{SPUInstallerServiceNameForBundleIdentifier(hostBundleIdentifier) : @YES, SPUProgressAgentServiceNameForBundleIdentifier(hostBundleIdentifier) : @YES}};
CFErrorRef submitError = NULL;
#pragma clang diagnostic push
@@ -300,13 +310,21 @@
return status;
}
- (NSString *)pathForBundledTool:(NSString *)toolName extension:(NSString *)extension inBundle:(NSBundle *)bundle
- (NSString *)pathForBundledTool:(NSString *)toolName extension:(NSString *)extension fromBundle:(NSBundle *)bundle
{
// 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;
assert(nameWithExtension != nil);
NSURL *auxiliaryToolURL = [bundle URLForAuxiliaryExecutable:nameWithExtension];
NSURL *auxiliaryToolURL;
if ([bundle.bundleURL.pathExtension isEqualToString:@"xpc"]) {
// Paranoid check to get full bundle URL
NSURL *fullURL = bundle.bundleURL.URLByResolvingSymlinksInPath;
auxiliaryToolURL = [fullURL.URLByDeletingLastPathComponent.URLByDeletingLastPathComponent URLByAppendingPathComponent:nameWithExtension];
} else {
auxiliaryToolURL = [bundle URLForAuxiliaryExecutable:nameWithExtension];
}
assert(auxiliaryToolURL != nil);
NSURL *resolvedAuxiliaryToolURL = [auxiliaryToolURL URLByResolvingSymlinksInPath];
@@ -315,78 +333,83 @@
return resolvedAuxiliaryToolURL.path;
}
static BOOL SPUNeedsSystemAuthorizationAccess(NSString *path, NSString *installationType)
BOOL SPUSystemNeedsAuthorizationAccessForBundlePath(NSString *bundlePath)
{
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL hasWritability = [fileManager isWritableFileAtPath:bundlePath] && [fileManager isWritableFileAtPath:[bundlePath stringByDeletingLastPathComponent]];
BOOL needsAuthorization;
if ([installationType isEqualToString:SPUInstallationTypeGuidedPackage]) {
if (!hasWritability) {
needsAuthorization = YES;
} else if ([installationType isEqualToString:SPUInstallationTypeInteractivePackage]) {
needsAuthorization = NO;
} else {
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL hasWritability = [fileManager isWritableFileAtPath:path] && [fileManager isWritableFileAtPath:[path stringByDeletingLastPathComponent]];
if (!hasWritability) {
// Just because we have writability access does not mean we can set the correct owner/group
// Test if we can set the owner/group on a temporarily created file
// If we can, then we can probably perform an update without authorization
NSString *tempFilename = @"permission_test" ;
SUFileManager *suFileManager = [[SUFileManager alloc] init];
NSURL *tempDirectoryURL = [suFileManager makeTemporaryDirectoryAppropriateForDirectoryURL:[NSURL fileURLWithPath:NSTemporaryDirectory()] error:NULL];
if (tempDirectoryURL == nil) {
// I don't imagine this ever happening but in case it does, requesting authorization may be the better option
needsAuthorization = YES;
} else {
// Just because we have writability access does not mean we can set the correct owner/group
// Test if we can set the owner/group on a temporarily created file
// If we can, then we can probably perform an update without authorization
NSString *tempFilename = @"permission_test" ;
SUFileManager *suFileManager = [[SUFileManager alloc] init];
NSURL *tempDirectoryURL = [suFileManager makeTemporaryDirectoryWithPreferredName:tempFilename appropriateForDirectoryURL:[NSURL fileURLWithPath:NSTemporaryDirectory()] error:NULL];
if (tempDirectoryURL == nil) {
// I don't imagine this ever happening but in case it does, requesting authorization may be the better option
NSURL *tempFileURL = [tempDirectoryURL URLByAppendingPathComponent:tempFilename];
if (![[NSData data] writeToURL:tempFileURL atomically:NO]) {
// Obvious indicator we may need authorization
needsAuthorization = YES;
} else {
NSURL *tempFileURL = [tempDirectoryURL URLByAppendingPathComponent:tempFilename];
if (![[NSData data] writeToURL:tempFileURL atomically:NO]) {
// Obvious indicator we may need authorization
needsAuthorization = YES;
} else {
needsAuthorization = ![suFileManager changeOwnerAndGroupOfItemAtRootURL:tempFileURL toMatchURL:[NSURL fileURLWithPath:path] error:NULL];
}
[suFileManager removeItemAtURL:tempDirectoryURL error:NULL];
needsAuthorization = ![suFileManager changeOwnerAndGroupOfItemAtRootURL:tempFileURL toMatchURL:[NSURL fileURLWithPath:bundlePath] error:NULL];
}
[suFileManager removeItemAtURL:tempDirectoryURL error:NULL];
}
}
return needsAuthorization;
}
static BOOL SPUUsesSystemDomainForBundlePath(NSString *path, NSString *installationType, BOOL rootUser)
{
if (!rootUser) {
if ([installationType isEqualToString:SPUInstallationTypeGuidedPackage]) {
return YES;
} else if ([installationType isEqualToString:SPUInstallationTypeInteractivePackage]) {
return NO;
} else {
return SPUSystemNeedsAuthorizationAccessForBundlePath(path);
}
} else {
// If we are the root user we use the system domain even if we don't need escalated authorization.
// Note interactive package installations are not supported as root.
return YES;
}
}
// 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 allowingUpdaterInteraction:(BOOL)allowingUpdaterInteraction completion:(void (^)(SUInstallerLauncherStatus, BOOL))completionHandler
- (void)launchInstallerWithHostBundlePath:(NSString *)hostBundlePath updaterIdentifier:(NSString *)updaterIdentifier authorizationPrompt:(NSString *)authorizationPrompt installationType:(NSString *)installationType allowingDriverInteraction:(BOOL)allowingDriverInteraction completion:(void (^)(SUInstallerLauncherStatus, BOOL))completionHandler
{
dispatch_async(dispatch_get_main_queue(), ^{
BOOL needsSystemAuthorization = SPUNeedsSystemAuthorizationAccess(hostBundlePath, installationType);
// 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);
NSBundle *hostBundle = [NSBundle bundleWithPath:hostBundlePath];
if (hostBundle == nil) {
SULog(SULogLevelError, @"InstallerLauncher failed to create bundle at %@", hostBundlePath);
SULog(SULogLevelError, @"Please make sure InstallerLauncher is not sandboxed and do not sign your app by passing --deep. Check: codesign -d --entitlements :- \"%@\"", NSBundle.mainBundle.bundlePath);
SULog(SULogLevelError, @"More information regarding sandboxing: https://sparkle-project.org/documentation/sandboxing/");
completionHandler(SUInstallerLauncherFailure, needsSystemAuthorization);
completionHandler(SUInstallerLauncherFailure, inSystemDomain);
return;
}
if (needsSystemAuthorization && !allowingUpdaterInteraction) {
SULog(SULogLevelError, @"Updater is not allowing interaction to the launcher.");
completionHandler(SUInstallerLauncherFailure, needsSystemAuthorization);
return;
}
if (!allowingUpdaterInteraction && [installationType isEqualToString:SPUInstallationTypeInteractivePackage]) {
SULog(SULogLevelError, @"Updater is not allowing interaction to the launcher for performing an interactive type package installation.");
completionHandler(SUInstallerLauncherFailure, needsSystemAuthorization);
return;
}
// if we need to use the system domain and we aren't allowed interaction, then try sometime later when interaction is allowed
if (needsSystemAuthorization && !allowingDriverInteraction) {
completionHandler(SUInstallerLauncherAuthorizeLater, needsSystemAuthorization);
// if we need to use the system authorization from non-root and we aren't allowed interaction, then try sometime later when interaction is allowed
if (inSystemDomain && !rootUser && !allowingDriverInteraction) {
completionHandler(SUInstallerLauncherAuthorizeLater, inSystemDomain);
return;
}
@@ -398,19 +421,19 @@ static BOOL SPUNeedsSystemAuthorizationAccess(NSString *path, NSString *installa
// Note we do not have to copy this tool out of the bundle it's in because it's a utility with no dependencies.
// Furthermore, we can keep the tool at a place that may not necessarily be writable.
NSString *installerPath = [self pathForBundledTool:@""SPARKLE_RELAUNCH_TOOL_NAME extension:@"" inBundle:ourBundle];
NSString *installerPath = [self pathForBundledTool:@""SPARKLE_RELAUNCH_TOOL_NAME extension:@"" fromBundle:ourBundle];
if (installerPath == nil) {
SULog(SULogLevelError, @"Error: Cannot submit installer because the installer could not be located");
completionHandler(SUInstallerLauncherFailure, needsSystemAuthorization);
completionHandler(SUInstallerLauncherFailure, inSystemDomain);
return;
}
// We do however have to copy the progress tool app somewhere safe due to its external depedencies
NSString *progressToolResourcePath = [self pathForBundledTool:@""SPARKLE_INSTALLER_PROGRESS_TOOL_NAME extension:@"app" inBundle:ourBundle];
NSString *progressToolResourcePath = [self pathForBundledTool:@""SPARKLE_INSTALLER_PROGRESS_TOOL_NAME extension:@"app" fromBundle:ourBundle];
if (progressToolResourcePath == nil) {
SULog(SULogLevelError, @"Error: Cannot submit progress tool because the progress tool could not be located");
completionHandler(SUInstallerLauncherFailure, needsSystemAuthorization);
completionHandler(SUInstallerLauncherFailure, inSystemDomain);
return;
}
@@ -426,25 +449,69 @@ static BOOL SPUNeedsSystemAuthorizationAccess(NSString *path, NSString *installa
NSString *launcherCachePath = [SPULocalCacheDirectory createUniqueDirectoryInDirectory:rootLauncherCachePath];
if (launcherCachePath == nil) {
SULog(SULogLevelError, @"Failed to create cache directory for progress tool in %@", rootLauncherCachePath);
completionHandler(SUInstallerLauncherFailure, needsSystemAuthorization);
completionHandler(SUInstallerLauncherFailure, inSystemDomain);
return;
}
SUFileManager *fileManager = [[SUFileManager alloc] init];
NSString *userName;
NSString *homeDirectory;
if (!rootUser) {
// Normal path
homeDirectory = NSHomeDirectory();
assert(homeDirectory != nil);
userName = NSUserName();
assert(userName != nil);
} 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");
completionHandler(SUInstallerLauncherFailure, inSystemDomain);
return;
}
userName = (NSString *)CFBridgingRelease(userNameRef);
homeDirectory = NSHomeDirectoryForUser(userName);
if (homeDirectory == nil) {
SULog(SULogLevelError, @"Failed to retrieve home directory for user: %@", userName);
completionHandler(SUInstallerLauncherFailure, inSystemDomain);
return;
}
// 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;
if (![fileManager changeOwnerAndGroupOfItemAtURL:[NSURL fileURLWithPath:launcherCachePath] ownerID:uid groupID:gid error:&changeOwnerAndGroupError]) {
SULog(SULogLevelError, @"Failed to change owner and group for launcher cache directory: %@", changeOwnerAndGroupError);
completionHandler(SUInstallerLauncherFailure, inSystemDomain);
return;
}
}
NSString *progressToolPath = [launcherCachePath stringByAppendingPathComponent:@""SPARKLE_INSTALLER_PROGRESS_TOOL_NAME@".app"];
NSError *copyError = nil;
// SUFileManager is more reliable for copying files around
if (![[[SUFileManager alloc] init] copyItemAtURL:[NSURL fileURLWithPath:progressToolResourcePath] toURL:[NSURL fileURLWithPath:progressToolPath] error:&copyError]) {
if (![fileManager copyItemAtURL:[NSURL fileURLWithPath:progressToolResourcePath] toURL:[NSURL fileURLWithPath:progressToolPath] error:&copyError]) {
SULog(SULogLevelError, @"Failed to copy progress tool to cache: %@", copyError);
completionHandler(SUInstallerLauncherFailure, needsSystemAuthorization);
completionHandler(SUInstallerLauncherFailure, inSystemDomain);
return;
}
SUInstallerLauncherStatus installerStatus = [self submitInstallerAtPath:installerPath withHostBundle:hostBundle updaterIdentifier:updaterIdentifier authorizationPrompt:authorizationPrompt inSystemDomain:needsSystemAuthorization];
SUInstallerLauncherStatus installerStatus = [self submitInstallerAtPath:installerPath withHostBundle:hostBundle updaterIdentifier:updaterIdentifier userName:userName homeDirectory:homeDirectory authorizationPrompt:authorizationPrompt inSystemDomain:inSystemDomain rootUser:rootUser];
BOOL submittedProgressTool = NO;
if (installerStatus == SUInstallerLauncherSuccess) {
submittedProgressTool = [self submitProgressToolAtPath:progressToolPath withHostBundle:hostBundle inSystemDomainForInstaller:needsSystemAuthorization];
submittedProgressTool = [self submitProgressToolAtPath:progressToolPath withHostBundle:hostBundle inSystemDomainForInstaller:inSystemDomain];
if (!submittedProgressTool) {
SULog(SULogLevelError, @"Failed to submit progress tool job");
@@ -455,17 +522,11 @@ static BOOL SPUNeedsSystemAuthorizationAccess(NSString *path, NSString *installa
}
if (installerStatus == SUInstallerLauncherCanceled) {
completionHandler(installerStatus, needsSystemAuthorization);
completionHandler(installerStatus, inSystemDomain);
} else {
completionHandler(submittedProgressTool ? SUInstallerLauncherSuccess : SUInstallerLauncherFailure, needsSystemAuthorization);
completionHandler(submittedProgressTool ? SUInstallerLauncherSuccess : SUInstallerLauncherFailure, inSystemDomain);
}
});
}
- (void)checkIfApplicationInstallationRequiresAuthorizationWithHostBundlePath:(NSString *)hostBundlePath reply:(void(^)(BOOL))reply
{
// No need to execute on main queue
reply(SPUNeedsSystemAuthorizationAccess(hostBundlePath, SPUInstallationTypeApplication));
}
@end
@@ -11,8 +11,6 @@
@protocol SUInstallerLauncherProtocol
- (void)launchInstallerWithHostBundlePath:(NSString *)hostBundlePath updaterIdentifier:(NSString *)updaterBundleIdentifier authorizationPrompt:(NSString *)authorizationPrompt installationType:(NSString *)installationType allowingDriverInteraction:(BOOL)allowingDriverInteraction allowingUpdaterInteraction:(BOOL)allowingUpdaterInteraction completion:(void (^)(SUInstallerLauncherStatus, BOOL))completionHandler;
- (void)checkIfApplicationInstallationRequiresAuthorizationWithHostBundlePath:(NSString *)hostBundlePath reply:(void(^)(BOOL requiresAuthorization))reply;
- (void)launchInstallerWithHostBundlePath:(NSString *)hostBundlePath updaterIdentifier:(NSString *)updaterBundleIdentifier authorizationPrompt:(NSString *)authorizationPrompt installationType:(NSString *)installationType allowingDriverInteraction:(BOOL)allowingDriverInteraction completion:(void (^)(SUInstallerLauncherStatus, BOOL))completionHandler;
@end
+4
View File
@@ -12,4 +12,8 @@
// 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>
- (instancetype)initWithRemote:(BOOL)remote;
- (instancetype)init NS_UNAVAILABLE;
@end
+66 -16
View File
@@ -19,16 +19,34 @@
@end
@implementation SUInstallerStatus
{
BOOL _remote;
}
@synthesize invalidationBlock = _invalidationBlock;
@synthesize connection = _connection;
- (void)setInvalidationHandler:(void (^)(void))invalidationHandler
- (instancetype)initWithRemote:(BOOL)remote
{
self.invalidationBlock = invalidationHandler;
self = [super init];
if (self != nil) {
_remote = remote;
}
return self;
}
- (void)setServiceName:(NSString *)serviceName
- (void)setInvalidationHandler:(void (^)(void))invalidationHandler
{
if (_remote) {
dispatch_async(dispatch_get_main_queue(), ^{
self.invalidationBlock = invalidationHandler;
});
} else {
self.invalidationBlock = invalidationHandler;
}
}
- (void)_setServiceName:(NSString *)serviceName
{
NSXPCConnection *connection = [[NSXPCConnection alloc] initWithMachServiceName:serviceName options:(NSXPCConnectionOptions)0];
@@ -38,41 +56,73 @@
__weak SUInstallerStatus *weakSelf = self;
self.connection.interruptionHandler = ^{
[weakSelf.connection invalidate];
dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf.connection invalidate];
});
};
self.connection.invalidationHandler = ^{
SUInstallerStatus *strongSelf = weakSelf;
if (strongSelf != nil) {
strongSelf.connection = nil;
[strongSelf invalidate];
}
dispatch_async(dispatch_get_main_queue(), ^{
SUInstallerStatus *strongSelf = weakSelf;
if (strongSelf != nil) {
strongSelf.connection = nil;
[strongSelf _invokeInvalidationBlock];
}
});
};
[self.connection resume];
}
- (void)setServiceName:(NSString *)serviceName
{
if (_remote) {
dispatch_async(dispatch_get_main_queue(), ^{
[self _setServiceName:serviceName];
});
} else {
[self _setServiceName:serviceName];
}
}
- (void)probeStatusInfoWithReply:(void (^)(NSData * _Nullable installationInfoData))reply
{
[(id<SUStatusInfoProtocol>)self.connection.remoteObjectProxy probeStatusInfoWithReply:reply];
if (_remote) {
dispatch_async(dispatch_get_main_queue(), ^{
[(id<SUStatusInfoProtocol>)self.connection.remoteObjectProxy probeStatusInfoWithReply:reply];
});
} else {
[(id<SUStatusInfoProtocol>)self.connection.remoteObjectProxy probeStatusInfoWithReply:reply];
}
}
- (void)probeStatusConnectivityWithReply:(void (^)(void))reply
{
[(id<SUStatusInfoProtocol>)self.connection.remoteObjectProxy probeStatusConnectivityWithReply:reply];
if (_remote) {
dispatch_async(dispatch_get_main_queue(), ^{
[(id<SUStatusInfoProtocol>)self.connection.remoteObjectProxy probeStatusConnectivityWithReply:reply];
});
} else {
[(id<SUStatusInfoProtocol>)self.connection.remoteObjectProxy probeStatusConnectivityWithReply:reply];
}
}
// This method can be called by us or from a remote
- (void)_invokeInvalidationBlock
{
if (self.invalidationBlock != nil) {
self.invalidationBlock();
self.invalidationBlock = nil;
}
}
// This method can be called from us or a remote
- (void)invalidate
{
dispatch_async(dispatch_get_main_queue(), ^{
[self.connection invalidate];
self.connection = nil;
if (self.invalidationBlock != nil) {
self.invalidationBlock();
self.invalidationBlock = nil;
}
[self _invokeInvalidationBlock];
});
}
+1 -1
View File
@@ -25,7 +25,7 @@
newConnection.exportedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUInstallerStatusProtocol)];
// Next, set the object that the connection exports. All messages sent on the connection to this service will be sent to the exported object to handle. The connection retains the exported object.
SUInstallerStatus *exportedObject = [SUInstallerStatus new];
SUInstallerStatus *exportedObject = [[SUInstallerStatus alloc] initWithRemote:YES];
newConnection.exportedObject = exportedObject;
// Resuming the connection allows the system to deliver more incoming messages.
+76 -3
View File
@@ -29,13 +29,86 @@ EXTERNAL LICENSES
=================
bspatch.c and bsdiff.c, from bsdiff 4.3 <http://www.daemonology.net/bsdiff/>:
Copyright (c) 2003-2005 Colin Percival.
Copyright 2003-2005 Colin Percival
All rights reserved
Redistribution and use in source and binary forms, with or without
modification, are permitted providing that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
--
sais.c and sais.c, from sais-lite (2010/08/07) <https://sites.google.com/site/yuta256/sais>:
Copyright (c) 2008-2010 Yuta Mori.
The sais-lite copyright is as follows:
Copyright (c) 2008-2010 Yuta Mori All Rights Reserved.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
--
Portable C implementation of Ed25519, from https://github.com/orlp/ed25519
Copyright (c) 2015 Orson Peters <orsonpeters@gmail.com>
This software is provided 'as-is', without any express or implied warranty. In no event will the
authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose, including commercial
applications, and to alter it and redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the
original software. If you use this software in a product, an acknowledgment in the product
documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as
being the original software.
3. This notice may not be removed or altered from any source distribution.
--
SUSignatureVerifier.m:
Copyright (c) 2011 Mark Hamlin.
Copyright (c) 2011 Mark Hamlin.
All rights reserved.
+5 -5
View File
@@ -7,10 +7,10 @@ ifndef BUILDDIR
endif
localizable-strings:
rm -f Sparkle/en.lproj/Sparkle.strings
genstrings -o Sparkle/en.lproj -s SULocalizedString Sparkle/*.m Sparkle/*.h
iconv -f UTF-16 -t UTF-8 < Sparkle/en.lproj/Localizable.strings > Sparkle/en.lproj/Sparkle.strings
rm Sparkle/en.lproj/Localizable.strings
rm -f Sparkle/Base.lproj/Sparkle.strings
genstrings -o Sparkle/Base.lproj -s SULocalizedString Sparkle/*.m
iconv -f UTF-16 -t UTF-8 < Sparkle/Base.lproj/Localizable.strings > Sparkle/Base.lproj/Sparkle.strings
rm Sparkle/Base.lproj/Localizable.strings
release:
xcodebuild -scheme Distribution -configuration Release -derivedDataPath "$(BUILDDIR)" build
@@ -25,7 +25,7 @@ build:
# Need to first gem install jazzy to run this rule
docs:
jazzy --objc --umbrella-header Sparkle/Sparkle.h --framework-root . --output Documentation/html
jazzy --author "Sparkle Project" --objc --umbrella-header Sparkle/Sparkle.h --framework-root . --readme Documentation/API_README.markdown --theme jony --output Documentation/html
uitest:
xcodebuild -scheme UITests -configuration Debug test
+3 -3
View File
@@ -2,10 +2,10 @@
import PackageDescription
// Version is technically not required here, SPM doesn't check
let version = "2.0.0-beta.1"
let version = "2.2.1"
// Tag is required to point towards the right asset. SPM requires the tag to follow semantic versioning to be able to resolve it.
let tag = "2.0.0-beta.1"
let checksum = "389a58bc0b333d9d18c8fa2d72aacbf4905d5d59a9858ecd9a5b16ff769bb5c5"
let tag = "2.2.1"
let checksum = "ce1e73dccebfd06c638ea9fc37451a690ea3137e1333406ec5dddb9e11b4e1b5"
let url = "https://github.com/sparkle-project/Sparkle/releases/download/\(tag)/Sparkle-for-Swift-Package-Manager.zip"
let package = Package(
+14 -25
View File
@@ -1,40 +1,36 @@
# Sparkle 2 (Beta) ![Build Status](https://github.com/sparkle-project/Sparkle/workflows/Build%20%26%20Tests/badge.svg?branch=2.x) <a href="https://www.stackpath.com/?utm_source=sparkle-github&amp;utm_medium=badge&amp;utm_campaign=readme"><img src="https://img.shields.io/badge/sponsored%20by-StackPath-orange.svg" alt="sponsored by: StackPath"></a>
# Sparkle 2 ![Build Status](https://github.com/sparkle-project/Sparkle/workflows/Build%20%26%20Tests/badge.svg?branch=2.x) ![SwiftPM](https://img.shields.io/badge/SwiftPM-compatible-4BC51D.svg?style=flat) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) [![CocoaPods](https://img.shields.io/cocoapods/v/Sparkle.svg?cacheSeconds=86400)](https://cocoapods.org/pods/Sparkle)
Secure and reliable software update framework for Cocoa developers.
Secure and reliable software update framework for macOS.
<img src="Resources/Screenshot.png" width="732" alt="Sparkle shows familiar update window with release notes">
This is the upcoming new version of Sparkle.
Major new features are support for sandboxing, custom user interfaces, updating external bundles, and a more modern secure architecture which includes faster and more reliable installs.
Sparkle 2 adds support for application sandboxing, custom user interfaces, updating external bundles, and a more modern architecture which includes faster and more reliable installs.
For the production ready version of Sparkle, please see the [Sparkle 1.x (master) branch](https://github.com/sparkle-project/Sparkle/tree/master). Note development has shifted to Sparkle 2 and the 1.x branch is now only accepting bug fixes, localization updates, and adoption of critical upcoming OS features.
Pre-releases when available can be found on the [Sparkle's Releases](https://github.com/sparkle-project/Sparkle/releases) or on your favorite package manager. More nightly builds can be downloaded by selecting a recent [workflow run](https://github.com/sparkle-project/Sparkle/actions?query=event%3Apush+is%3Asuccess+branch%3A2.x) and downloading the corresponding Sparkle-distribution artifact.
Sparkle 2 is currently in beta. Applications, typically sandboxed, have already been using it in production, but some work including testing is still required before an official version can be released. In the meantime, a nightly build can be downloaded by selecting a recent [workflow run](https://github.com/sparkle-project/Sparkle/actions?query=event%3Apush+is%3Asuccess+branch%3A2.x) and downloading the corresponding Sparkle-distribution artifact. The current status of Sparkle 2 is tracked in issue [#1523](https://github.com/sparkle-project/Sparkle/issues/1523).
The current status for future versions of Sparkle is tracked by [its roadmap](https://github.com/sparkle-project/Sparkle/milestones).
If you can help with testing or reviewing over the new changes, please report issues or submit pull requests!
New issues should be [reported here](https://github.com/sparkle-project/Sparkle/issues). Internal design documents can be found in [Documentation](Documentation/).
Please visit [Sparkle's website](http://sparkle-project.org) for up to date documentation on using and migrating over to Sparkle 2. Refer to [Changelog](CHANGELOG) for a more detailed list of changes.
Please visit [Sparkle's website](http://sparkle-project.org) for up to date documentation on using and migrating over to Sparkle 2. Refer to [Changelog](CHANGELOG) for a more detailed list of changes. More internal design documents to the project can be found in the repository under [Documentation](Documentation/).
## Features
* Seamless. There's no mention of Sparkle; your icons and app name are used.
* Secure. Updates are verified using EdDSA signatures and Apple Code Signing.
* Fast. Supports delta updates which only patch files that have changed.
* Secure. Updates are verified using EdDSA signatures and Apple Code Signing. Supports Sandboxed applications in Sparkle 2.
* Fast. Supports delta updates which only patch files that have changed and atomic-safe installs.
* Easy to install. Sparkle requires no code in your app, and only needs static files on a web server.
* Supports bundles, preference panes, plugins, and other non-.app software. Can install .pkg files for more complicated products.
* Handles permissions, quarantine and automatically asks for authentication if needed.
* Customizable. Sparkle 2 supports plugging in a custom UI for updates.
* Flexible. Supports applications, package installers, preference panes, and other plug-ins. Sparkle 2 supports updating external bundles.
* Handles permissions, quarantine, and automatically asks for authentication if needed.
* Uses RSS-based appcasts for release information. Appcasts are a de-facto standard supported by 3rd party update-tracking programs and websites.
* Stays hidden until second launch for better first impressions.
* Truly self-updating — the user can choose to automatically download and install all updates in the background.
* Ability to mark updates as critical.
* Ability to use channels for beta updates (in Sparkle 2), add phased rollouts to users, and mark updates as critical or major.
* Progress and status notifications for the host app.
## Requirements
* Runtime: macOS 10.11 or greater
* Build: Latest major Xcode (stable or beta, whichever is latest) and one major version less; at least Xcode 12 if using Swift Package Manager.
* Build: Latest major Xcode (stable or beta, whichever is latest) and one major version less.
* HTTPS server for serving updates (see [App Transport Security](http://sparkle-project.org/documentation/app-transport-security/))
## Usage
@@ -46,19 +42,16 @@ See [getting started guide](https://sparkle-project.org/documentation/). No code
This repository uses git submodules, and will not build unless you clone recursively. Also, GitHub-provided ZIP/tar archives are broken due to GitHub not supporting git submodules properly.
git clone https://github.com/sparkle-project/Sparkle
git checkout 2.x
git submodule update --init --recursive
### Troubleshooting
* Please check **Console.app**. Sparkle prints detailed information there about all problems it encounters. It often also suggests solutions to the problems, so please read Sparkle's log messages carefully.
* Please check **Console.app** for logs under your application. Sparkle prints detailed information there about all problems it encounters. It often also suggests solutions to the problems, so please read Sparkle's log messages carefully.
* Use the `generate_appcast` tool which creates appcast files, correct signatures, and delta updates automatically.
* Make sure the URL specified in [`SUFeedURL`](https://sparkle-project.org/documentation/customization/) is valid (typos/404s are a common error!), and that it uses modern TLS ([test it](https://www.ssllabs.com/ssltest/)).
* Delete your app's preferences (in `~/Library/Preferences/<your bundle id>`) if you've set another feed URL programmatically via Sparkle's Objective-C interface.
### API symbols
Sparkle is built with `-fvisibility=hidden -fvisibility-inlines-hidden` which means no symbols are exported by default.
@@ -73,7 +66,3 @@ Alternatively, build the Distribution scheme in the Xcode UI.
### Code of Conduct
We pledge to have an open and welcoming environment. See our [Code of Conduct](CODE_OF_CONDUCT.md).
## Project Sponsor
[StackPath](https://www.stackpath.com/?utm_source=sparkle-github&utm_medium=link&utm_campaign=readme-footer)
+1
View File
@@ -1,5 +1,6 @@
@media (prefers-color-scheme: dark) {
html {
color-scheme: dark;
color: white;
background: transparent;
}
+9
View File
@@ -11,6 +11,9 @@
<sparkle:releaseNotesLink>
https://you.com/app/2.0.html
</sparkle:releaseNotesLink>
<sparkle:fullReleaseNotesLink>
https://you.com/app/changelog.php
</sparkle:fullReleaseNotesLink>
<pubDate>Wed, 09 Jan 2006 19:20:11 +0000</pubDate>
<enclosure url="https://you.com/app/Your%20Great%20App%202.0.zip" length="1623481" type="application/octet-stream" sparkle:edSignature="WVyVJpOx+a5+vNWJVY79TRjFKveNk+VhGJf2iti4CZtJsJewIUGvh/1AKKEAFbH1qUwx+vro1ECuzOsMmumoBA==" />
<sparkle:minimumSystemVersion>10.11</sparkle:minimumSystemVersion>
@@ -23,6 +26,9 @@
<sparkle:releaseNotesLink>
https://you.com/app/1.5.html
</sparkle:releaseNotesLink>
<sparkle:fullReleaseNotesLink>
https://you.com/app/changelog.php?up-to=1.5
</sparkle:fullReleaseNotesLink>
<pubDate>Wed, 01 Jan 2006 12:20:11 +0000</pubDate>
<enclosure url="https://you.com/app/Your%20Great%20App%201.5.zip" length="1472893" type="application/octet-stream" sparkle:edSignature="pNFd7KbcQSu+Mq7UYrbQXTPq82luht2ACXm/r2utp1u/Uv/5hWqctdT2jwQgMejW7DRoeV/hVr6J4VdZYdwWDw==" />
<sparkle:minimumSystemVersion>10.11</sparkle:minimumSystemVersion>
@@ -35,6 +41,9 @@
<sparkle:releaseNotesLink>
https://you.com/app/1.4.html
</sparkle:releaseNotesLink>
<sparkle:fullReleaseNotesLink>
https://you.com/app/changelog.php?up-to=1.4
</sparkle:fullReleaseNotesLink>
<sparkle:version>241</sparkle:version>
<sparkle:shortVersionString>1.4</sparkle:shortVersionString>
<pubDate>Wed, 25 Dec 2005 12:20:11 +0000</pubDate>
+10 -10
View File
@@ -1,17 +1,17 @@
Pod::Spec.new do |s|
s.name = "Sparkle"
s.version = "2.0.0-beta.1"
s.version = "2.2.1"
s.summary = "A software update framework for macOS"
s.description = "Sparkle is an easy-to-use software update framework for Cocoa developers."
s.homepage = "http://sparkle-project.org"
s.documentation_url = "http://sparkle-project.org/documentation/"
s.screenshot = "http://sparkle-project.org/images/screenshot-noshadow@2x.png"
s.description = "Sparkle is an easy-to-use software update framework for macOS."
s.homepage = "https://sparkle-project.org"
s.documentation_url = "https://sparkle-project.org/documentation/"
s.screenshot = "https://sparkle-project.org/images/screenshot-noshadow@2x.png"
s.license = {
:type => 'MIT',
:file => 'LICENSE'
}
s.authors = {
'Mayur Pawashe' => 'zorgiepoo@gmail.com',
'Zorg' => 'zorgiepoo@gmail.com',
'Kornel Lesiński' => 'pornel@pornel.net',
'Jake Petroules' => 'jake.petroules@petroules.com',
'C.W. Betts' => 'computers57@hotmail.com',
@@ -19,11 +19,11 @@ Pod::Spec.new do |s|
}
s.platform = :osx, '10.11'
s.source = { :http => "https://github.com/sparkle-project/Sparkle/releases/download/#{s.version}/Sparkle-#{s.version}.tar.bz2" }
s.source_files = 'Sparkle.framework/Versions/A/Headers/*.h'
s.source = { :http => "https://github.com/sparkle-project/Sparkle/releases/download/#{s.version}/Sparkle-#{s.version}.tar.xz" }
s.source_files = 'Sparkle.framework/Versions/B/Headers/*.h'
s.preserve_paths = 'bin/*'
s.public_header_files = 'Sparkle.framework/Versions/A/Headers/*.h'
s.preserve_paths = ['bin/*', 'Entitlements', 'Symbols']
s.public_header_files = 'Sparkle.framework/Versions/B/Headers/*.h'
s.vendored_frameworks = 'Sparkle.framework'
s.xcconfig = {
'FRAMEWORK_SEARCH_PATHS' => '"${PODS_ROOT}/Sparkle"',
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,78 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1400"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "5D06E8CF0FD68C7C005AE3F6"
BuildableName = "BinaryDelta"
BlueprintName = "BinaryDelta"
ReferencedContainer = "container:Sparkle.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "5D06E8CF0FD68C7C005AE3F6"
BuildableName = "BinaryDelta"
BlueprintName = "BinaryDelta"
ReferencedContainer = "container:Sparkle.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "5D06E8CF0FD68C7C005AE3F6"
BuildableName = "BinaryDelta"
BlueprintName = "BinaryDelta"
ReferencedContainer = "container:Sparkle.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1300"
LastUpgradeVersion = "1400"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1300"
LastUpgradeVersion = "1400"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -52,6 +52,13 @@
ReferencedContainer = "container:Sparkle.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<EnvironmentVariables>
<EnvironmentVariable
key = "TEST_MODE"
value = "DELTA"
isEnabled = "NO">
</EnvironmentVariable>
</EnvironmentVariables>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1300"
LastUpgradeVersion = "1400"
version = "2.0">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1300"
LastUpgradeVersion = "1400"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1300"
LastUpgradeVersion = "1400"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1300"
LastUpgradeVersion = "1400"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1300"
LastUpgradeVersion = "1400"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -0,0 +1,78 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1400"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "72D9549D1CBB415B006F28BD"
BuildableName = "sparkle.app"
BlueprintName = "sparkle-cli"
ReferencedContainer = "container:Sparkle.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "NO"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "72D9549D1CBB415B006F28BD"
BuildableName = "sparkle.app"
BlueprintName = "sparkle-cli"
ReferencedContainer = "container:Sparkle.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "72D9549D1CBB415B006F28BD"
BuildableName = "sparkle.app"
BlueprintName = "sparkle-cli"
ReferencedContainer = "container:Sparkle.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
+83 -84
View File
@@ -1,153 +1,152 @@
/* Description text for SUUpdateAlert when the critical update has already been downloaded and ready to install. */
"%1$@ %2$@ has been downloaded and is ready to use! This is an important update; would you like to install it and relaunch %1$@ now?" = "%1$@ %2$@ has been downloaded and is ready to use! This is an important update; would you like to install it and relaunch %1$@ now?";
/* Description text for SUUpdateAlert when the update has already been downloaded and ready to install. */
"%1$@ %2$@ has been downloaded and is ready to use! Would you like to install it and relaunch %1$@ now?" = "%1$@ %2$@ has been downloaded and is ready to use! Would you like to install it and relaunch %1$@ now?";
"%1$@ can't be updated, because it was opened from a read-only or a temporary location." = "%1$@ can't be updated, because it was opened from a read-only or a temporary location.";
/* No comment provided by engineer. */
"%1$@ %2$@ is available but your macOS version is too new for this update. This update only supports up to macOS %3$@." = "%1$@ %2$@ is available but your macOS version is too new for this update. This update only supports up to macOS %3$@.";
"Use Finder to copy %1$@ to the Applications folder, relaunch it from there, and try again." = "Use Finder to copy %1$@ to the Applications folder, relaunch it from there, and try again.";
"Quit %1$@, move it into your Applications folder, relaunch it from there and try again." = "Quit %1$@, move it into your Applications folder, relaunch it from there and try again.";
/* No comment provided by engineer. */
"%1$@ %2$@ is available but your macOS version is too old to install it. At least macOS %3$@ is required." = "%1$@ %2$@ is available but your macOS version is too old to install it. At least macOS %3$@ is required.";
/* No comment provided by engineer. */
"%1$@ can’t be updated if it’s running from the location it was downloaded to." = "%1$@ can’t be updated if it’s running from the location it was downloaded to.";
/* No comment provided by engineer. */
"%1$@ can’t be updated, because it was opened from a read-only or a temporary location." = "%1$@ can’t be updated, because it was opened from a read-only or a temporary location.";
/* No comment provided by engineer. */
"%@ %@ is currently the newest version available." = "%1$@ %2$@ is currently the newest version available.";
"%@ %@ is currently the newest version available.\n(You are currently running version %@.)" = "%1$@ %2$@ is currently the newest version available.\n(You are currently running version %3$@.)";
/* No comment provided by engineer. */
"%@ %@ is currently the newest version available.\n(You are currently running version %@.)" = "%1$@ %2$@ is currently the newest version available.\n(You are currently running version %3$@.)";
"An error occurred while running the updater. Please try again later." = "An error occurred while running the updater. Please try again later.";
"An error occurred while starting the installer. Please try again later." = "An error occurred while starting the installer. Please try again later.";
"An error occurred while connecting to the installer. Please try again later." = "An error occurred while connecting to the installer. Please try again later.";
"An error occurred while launching the installer. Please try again later." = "An error occurred while launching the installer. Please try again later.";
"Update Installed" = "Update Installed";
"%@ is now updated to version %@!" = "%@ is now updated to version %@!";
"%@ is now updated!" = "%@ is now updated!";
/* Description text for SUUpdateAlert when the critical update is downloadable. */
"%@ %@ is now available—you have %@. This is an important update; would you like to download it now?" = "%1$@ %2$@ is now available—you have %3$@. This is an important update; would you like to download it now?";
/* Description text for SUUpdateAlert when the update is downloadable. */
"%@ %@ is now available--you have %@. Would you like to download it now?" = "%1$@ %2$@ is now available—you have %3$@. Would you like to download it now?";
"%@ %@ is now available—you have %@. Would you like to download it now?" = "%1$@ %2$@ is now available—you have %3$@. Would you like to download it now?";
/* Description text for SUUpdateAlert when the update informational with no download. */
"%@ %@ is now available--you have %@. Would you like to learn more about this update on the web?" = "%1$@ %2$@ is now available—you have %3$@. Would you like to learn more about this update on the web?";
/* Critical downloadable update */
"%@ %@ is now available--you have %@. This is an important update; would you like to download it now?" = "%1$@ %2$@ is now available--you have %3$@. This is an important update; would you like to download it now?";
"%@ %@ is now available—you have %@. Would you like to learn more about this update on the web?" = "%1$@ %2$@ is now available—you have %3$@. Would you like to learn more about this update on the web?";
/* The download progress in a unit of bytes, e.g. 100 KB */
"%@ downloaded" = "%@ downloaded";
/* No comment provided by engineer. */
"%@ is now updated to version %@!" = "%1$@ is now updated to version %2$@!";
/* No comment provided by engineer. */
"%@ is now updated!" = "%@ is now updated!";
/* The download progress in units of bytes, e.g. 100 KB of 1,0 MB */
"%@ of %@" = "%1$@ of %2$@";
/* No comment provided by engineer. */
"A new version of %@ is available!" = "A new version of %@ is available!";
/* No comment provided by engineer. */
"A new version of %@ is ready to install!" = "A new version of %@ is ready to install!";
/* No comment provided by engineer. */
"An error occurred in retrieving update information. Please try again later." = "An error occurred in retrieving update information. Please try again later.";
/* No comment provided by engineer. */
"An error occurred while connecting to the installer. Please try again later." = "An error occurred while connecting to the installer. Please try again later.";
/* No comment provided by engineer. */
"An error occurred while downloading the update. Please try again later." = "An error occurred while downloading the update. Please try again later.";
/* No comment provided by engineer. */
"An error occurred while extracting the archive. Please try again later." = "An error occurred while extracting the archive. Please try again later.";
"An error occurred while installing the update. Please try again later." = "An error occurred while installing the update. Please try again later.";
/* No comment provided by engineer. */
"An error occurred while launching the installer. Please try again later." = "An error occurred while launching the installer. Please try again later.";
/* No comment provided by engineer. */
"An error occurred while parsing the update feed." = "An error occurred while parsing the update feed.";
"An error occurred while downloading the update feed." = "An error occurred while downloading the update feed.";
/* No comment provided by engineer. */
"An error occurred while running the updater. Please try again later." = "An error occurred while running the updater. Please try again later.";
"Failed to resume installing update." = "Failed to resume installing update.";
"An error occurred while relaunching %1$@, but the new version will be available next time you run %1$@." = "An error occurred while relaunching %1$@, but the new version will be available next time you run %1$@.";
/* No comment provided by engineer. */
"An error occurred while starting the installer. Please try again later." = "An error occurred while starting the installer. Please try again later.";
/* No comment provided by engineer. */
"An important update to %@ is ready to install" = "An important update to %@ is ready to install";
"Unable to Check For Updates" = "Unable to Check For Updates";
"The update checker failed to start correctly. You should contact the app developer to report this issue and verify that you have the latest version" = "The update checker failed to start correctly. You should contact the app developer to report this issue and verify that you have the latest version";
/* the unit for bytes */
"B" = "B";
/* No comment provided by engineer. */
"Cancel" = "Cancel";
/* No comment provided by engineer. */
"Cancel Update" = "Cancel Update";
"Checking for updates..." = "Checking for updates…";
/* No comment provided by engineer. */
"Checking for updates…" = "Checking for updates…";
/* Take care not to overflow the status window. */
"Downloading update..." = "Downloading update…";
"Downloading update…" = "Downloading update…";
/* Take care not to overflow the status window. */
"Extracting update..." = "Extracting update…";
"Extracting update…" = "Extracting update…";
/* the unit for gigabytes */
"GB" = "GB";
/* No comment provided by engineer. */
"Failed to resume installing update." = "Failed to resume installing update.";
/* No comment provided by engineer. */
"Install and Relaunch" = "Install and Relaunch";
/* Alternate title for 'Remind Me Later' button when downloaded updates can be resumed */
"Install on Quit" = "Install on Quit";
/* Take care not to overflow the status window. */
"Installing update..." = "Installing update…";
"Installing update…" = "Installing update…";
/* Title confirmation for skipping major upgrade and future updates */
"Are you sure you want to skip this upgrade?" = "Are you sure you want to skip this upgrade?";
/* Alternate title for 'Install Update' button when there's no download in RSS feed. */
"Learn More…" = "Learn More…";
/* Confirmation message for skipping major upgrade and future updates */
"Skipping this major upgrade will opt out of alerts for future updates." = "Skipping this major upgrade will opt out of alerts for future updates.";
/* Skipping major upgrade */
"Skip Upgrade" = "Skip Upgrade";
/* Not skipping a major upgrade */
"Don't Skip" = "Don't Skip";
/* the unit for kilobytes */
"KB" = "KB";
/* Alternative name for "Install" button if we have a paid update or other update
without a download but with a URL. */
"Learn More..." = "Learn More…";
/* the unit for megabytes */
"MB" = "MB";
/* OK button. */
/* No comment provided by engineer. */
"OK" = "OK";
/* Status message on progress window once download has finished. */
/* No comment provided by engineer. */
"Quit %1$@, move it into your Applications folder, relaunch it from there and try again." = "Quit %1$@, move it into your Applications folder, relaunch it from there and try again.";
/* No comment provided by engineer. */
"Ready to Install" = "Ready to Install";
/* Message that is optionally shown at startup to allow users to turn on/off update checks. */
/* No comment provided by engineer. */
"Should %1$@ automatically check for updates? You can always check for updates manually from the %1$@ menu." = "Should %1$@ automatically check for updates? You can always check for updates manually from the %1$@ menu.";
"The update is improperly signed." = "The update is improperly signed.";
/* No comment provided by engineer. */
"The update checker failed to start correctly. You should contact the app developer to report this issue and verify that you have the latest version." = "The update checker failed to start correctly. You should contact the app developer to report this issue and verify that you have the latest version.";
/* No comment provided by engineer. */
"The update is improperly signed and could not be validated. Please try again later or contact the app developer." = "The update is improperly signed and could not be validated. Please try again later or contact the app developer.";
/* No comment provided by engineer. */
"Unable to Check For Updates" = "Unable to Check For Updates";
/* No comment provided by engineer. */
"Update Error!" = "Update Error!";
/* No comment provided by engineer. */
"Update Installed" = "Update Installed";
/* No comment provided by engineer. */
"Updating %@" = "Updating %@";
/* 'Error' message when the user checks for updates but is already current or the feed doesn't contain any updates. (not necessarily shown in UI) */
"You already have the newest version of %@." = "You already have the newest version of %@.";
/* No comment provided by engineer. */
"Use Finder to copy %1$@ to the Applications folder, relaunch it from there, and try again." = "Use Finder to copy %1$@ to the Applications folder, relaunch it from there, and try again.";
/* Status message shown when the user checks for updates but is already current or the feed doesn't contain any updates. */
"You're up-to-date!" = "You’re up to date!";
"Your macOS version is too old" = "Your macOS version is too old";
"%1$@ %2$@ is available but your macOS version is too old to install it. At least macOS %3$@ is required." = "%1$@ %2$@ is available but your macOS version is too old to install it. At least macOS %3$@ is required.";
"Your macOS version is too new" = "Your macOS version is too new";
"%1$@ %2$@ is available but your macOS version is too new for this update. This update only supports up to macOS %3$@." = "%1$@ %2$@ is available but your macOS version is too new for this update. This update only supports up to macOS %3$@.";
/* Used when a new update is not found */
/* No comment provided by engineer. */
"Version History" = "Version History";
/* Authorization message shown when app wants permission to update itself. */
"%1$@ wants permission to update." = "%1$@ wants permission to update.";
/* No comment provided by engineer. */
"Your macOS version is too new" = "Your macOS version is too new";
/* Authorization message shown when app wants permission to update another app / bundle. */
"%1$@ wants permission to update %2$@." = "%1$@ wants permission to update %2$@.";
/* No comment provided by engineer. */
"Your macOS version is too old" = "Your macOS version is too old";
/* Status message shown when the user checks for updates but is already current or the feed doesn't contain any updates. */
"You’re up-to-date!" = "You’re up-to-date!";
+4 -2
View File
@@ -126,7 +126,9 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.3;
__weak InstallerProgressAppController *weakSelf = self;
_connection.interruptionHandler = ^{
[weakSelf.connection invalidate];
dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf.connection invalidate];
});
};
_connection.invalidationHandler = ^{
@@ -331,7 +333,7 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.3;
}
// Note: we can launch application bundles or open plug-in bundles
if (![[NSWorkspace sharedWorkspace] openFile:pathToRelaunch]) {
if (![[NSWorkspace sharedWorkspace] openURL:[NSURL fileURLWithPath:pathToRelaunch isDirectory:YES]]) {
SULog(SULogLevelError, @"Error: Failed to relaunch bundle at %@", pathToRelaunch);
}
+2 -2
View File
@@ -24,10 +24,10 @@
- (void)installerProgressShouldDisplayWithHost:(SUHost *)host
{
self.statusController = [[SUStatusController alloc] initWithHost:host];
self.statusController = [[SUStatusController alloc] initWithHost:host centerPointValue:nil minimizable:NO];
[self.statusController setButtonTitle:SULocalizedString(@"Cancel Update", @"") target:nil action:nil isDefault:NO];
[self.statusController beginActionWithTitle:SULocalizedString(@"Installing update...", @"") maxProgressValue:0 statusText:@""];
[self.statusController beginActionWithTitle:SULocalizedString(@"Installing update…", @"") maxProgressValue:0 statusText:@""];
[self.statusController showWindow:self];
}
+15 -1
View File
@@ -98,8 +98,22 @@
return YES;
}
NSString *hostVersion = self.hostVersion;
// Informational update only for a set of host versions we're updating from
return [informationalUpdateVersions containsObject:self.hostVersion];
if ([informationalUpdateVersions containsObject:hostVersion]) {
return YES;
}
// If an informational update version has a '<' prefix, this is an informational update if
// hostVersion < this info update version
for (NSString *informationalUpdateVersion in informationalUpdateVersions) {
if ([informationalUpdateVersion hasPrefix:@"<"] && [self.applicationVersionComparator compareVersion:hostVersion toVersion:[informationalUpdateVersion substringFromIndex:1]] == NSOrderedAscending) {
return YES;
}
}
return NO;
}
- (SPUAppcastItemState *)resolveStateWithInformationalUpdateVersions:(NSSet<NSString *> * _Nullable)informationalUpdateVersions minimumOperatingSystemVersion:(NSString * _Nullable)minimumOperatingSystemVersion maximumOperatingSystemVersion:(NSString * _Nullable)maximumOperatingSystemVersion minimumAutoupdateVersion:(NSString * _Nullable)minimumAutoupdateVersion criticalUpdateDictionary:(NSDictionary * _Nullable)criticalUpdateDictionary
+22 -26
View File
@@ -47,44 +47,40 @@
// The user driver is only used for a termination callback
_userDriver = userDriver;
_updaterDelegate = updaterDelegate;
_coreDriver = [[SPUCoreBasedUpdateDriver alloc] initWithHost:host applicationBundle:applicationBundle updater:updater updaterDelegate:updaterDelegate delegate:self];
_coreDriver = [[SPUCoreBasedUpdateDriver alloc] initWithHost:host applicationBundle:applicationBundle updateCheck:SPUUpdateCheckUpdatesInBackground updater:updater updaterDelegate:updaterDelegate delegate:self];
}
return self;
}
- (void)checkForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders preventingInstallerInteraction:(BOOL)preventsInstallerInteraction completion:(SPUUpdateDriverCompletion)completionBlock
- (void)setCompletionHandler:(SPUUpdateDriverCompletion)completionBlock
{
[self.coreDriver prepareCheckForUpdatesWithCompletion:completionBlock];
[self.coreDriver preflightForUpdatePermissionPreventingInstallerInteraction:preventsInstallerInteraction reply:^(NSError * _Nullable error) {
if (error != nil) {
[self abortUpdateWithError:error];
} else {
[self.coreDriver checkForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders inBackground:YES requiresSilentInstall:YES];
}
}];
[self.coreDriver setCompletionHandler:completionBlock];
}
#pragma clang diagnostic push
#if __has_warning("-Wcompletion-handler")
#pragma clang diagnostic ignored "-Wcompletion-handler"
#endif
- (void)resumeInstallingUpdateWithCompletion:(SPUUpdateDriverCompletion)__unused completionBlock
#pragma clang diagnostic pop
- (void)setUpdateShownHandler:(void (^)(void))updateShownHandler
{
// Nothing really to do here.. this shouldn't be called.
SULog(SULogLevelError, @"Error: resumeInstallingUpdateWithCompletion: called on SPUAutomaticUpdateDriver");
}
#pragma clang diagnostic push
#if __has_warning("-Wcompletion-handler")
#pragma clang diagnostic ignored "-Wcompletion-handler"
#endif
- (void)resumeUpdate:(id<SPUResumableUpdate>)__unused resumableUpdate completion:(SPUUpdateDriverCompletion)__unused completionBlock
#pragma clang diagnostic pop
- (void)setUpdateWillInstallHandler:(void (^)(void))updateWillInstallHandler
{
[self.coreDriver setUpdateWillInstallHandler:updateWillInstallHandler];
}
- (void)checkForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders
{
[self.coreDriver checkForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders inBackground:YES requiresSilentInstall:YES];
}
- (void)resumeInstallingUpdate
{
// Nothing really to do here.. this shouldn't be called.
SULog(SULogLevelError, @"Error: resumeDownloadedUpdate:completion: called on SPUAutomaticUpdateDriver");
SULog(SULogLevelError, @"Error: resumeInstallingUpdate: called on SPUAutomaticUpdateDriver");
}
- (void)resumeUpdate:(id<SPUResumableUpdate>)__unused resumableUpdate
{
// Nothing really to do here.. this shouldn't be called.
SULog(SULogLevelError, @"Error: resumeDownloadedUpdate: called on SPUAutomaticUpdateDriver");
}
- (void)basicDriverDidFindUpdateWithAppcastItem:(SUAppcastItem *)updateItem secondaryAppcastItem:(SUAppcastItem * _Nullable)secondaryUpdateItem
+5 -4
View File
@@ -8,6 +8,7 @@
#import <Foundation/Foundation.h>
#import "SPUUpdateDriver.h"
#import "SPUUpdateCheck.h"
NS_ASSUME_NONNULL_BEGIN
@@ -28,15 +29,15 @@ NS_ASSUME_NONNULL_BEGIN
@interface SPUBasicUpdateDriver : NSObject
- (instancetype)initWithHost:(SUHost *)host updater:(id)updater updaterDelegate:(nullable id <SPUUpdaterDelegate>)updaterDelegate delegate:(id <SPUBasicUpdateDriverDelegate>)delegate;
- (instancetype)initWithHost:(SUHost *)host updateCheck:(SPUUpdateCheck)updateCheck updater:(id)updater updaterDelegate:(nullable id <SPUUpdaterDelegate>)updaterDelegate delegate:(id <SPUBasicUpdateDriverDelegate>)delegate;
- (void)prepareCheckForUpdatesWithCompletion:(SPUUpdateDriverCompletion)completionBlock;
- (void)setCompletionHandler:(SPUUpdateDriverCompletion)completionBlock;
- (void)checkForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders inBackground:(BOOL)background;
- (void)resumeInstallingUpdateWithCompletion:(SPUUpdateDriverCompletion)completionBlock;
- (void)resumeInstallingUpdate;
- (void)resumeUpdate:(id<SPUResumableUpdate>)resumableUpdate completion:(SPUUpdateDriverCompletion)completionBlock;
- (void)resumeUpdate:(id<SPUResumableUpdate>)resumableUpdate;
- (void)abortUpdateAndShowNextUpdateImmediately:(BOOL)shouldSignalShowingUpdate resumableUpdate:(id<SPUResumableUpdate> _Nullable)resumableUpdate error:(nullable NSError *)error;
+36 -33
View File
@@ -10,8 +10,6 @@
#import "SUAppcastDriver.h"
#import "SPUUpdaterDelegate.h"
#import "SUErrors.h"
#import "SULog.h"
#import "SULog+NSError.h"
#import "SULocalizations.h"
#import "SUHost.h"
#import "SUAppcastItem.h"
@@ -20,6 +18,7 @@
#import "SPUResumableUpdate.h"
#import "SPUAppcastItemState.h"
#import "SUAppcastItem+Private.h"
#import "SPUInstallationType.h"
#include "AppKitPrevention.h"
@@ -31,6 +30,7 @@
@property (nonatomic, copy) SPUUpdateDriverCompletion completionBlock;
@property (nonatomic, readonly) SUHost *host;
@property (nonatomic, readonly) SPUUpdateCheck updateCheck;
@property (nonatomic, readonly, weak) id updater; // if we didn't have legacy support, I'd remove this..
@property (nullable, nonatomic, readonly, weak) id <SPUUpdaterDelegate>updaterDelegate;
@@ -41,6 +41,7 @@
@implementation SPUBasicUpdateDriver
@synthesize host = _host;
@synthesize updateCheck = _updateCheck;
@synthesize updater = _updater;
@synthesize updaterDelegate = _updaterDelegate;
@synthesize delegate = _delegate;
@@ -48,11 +49,12 @@
@synthesize completionBlock = _completionBlock;
@synthesize aborted = _aborted;
- (instancetype)initWithHost:(SUHost *)host updater:(id)updater updaterDelegate:(id <SPUUpdaterDelegate>)updaterDelegate delegate:(id <SPUBasicUpdateDriverDelegate>)delegate
- (instancetype)initWithHost:(SUHost *)host updateCheck:(SPUUpdateCheck)updateCheck updater:(id)updater updaterDelegate:(id <SPUUpdaterDelegate>)updaterDelegate delegate:(id <SPUBasicUpdateDriverDelegate>)delegate
{
self = [super init];
if (self != nil) {
_host = host;
_updateCheck = updateCheck;
_updater = updater;
_updaterDelegate = updaterDelegate;
_delegate = delegate;
@@ -62,7 +64,7 @@
return self;
}
- (void)prepareCheckForUpdatesWithCompletion:(SPUUpdateDriverCompletion)completionBlock
- (void)setCompletionHandler:(SPUUpdateDriverCompletion)completionBlock
{
self.completionBlock = completionBlock;
}
@@ -74,7 +76,7 @@
if ([self.host isRunningTranslocated]) {
[self.delegate basicDriverIsRequestingAbortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SURunningTranslocated userInfo:@{ NSLocalizedRecoverySuggestionErrorKey: [NSString stringWithFormat:SULocalizedString(@"Quit %1$@, move it into your Applications folder, relaunch it from there and try again.", nil), hostName], NSLocalizedDescriptionKey: [NSString stringWithFormat:SULocalizedString(@"%1$@ can’t be updated if it’s running from the location it was downloaded to.", nil), hostName], }]];
} else {
[self.delegate basicDriverIsRequestingAbortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SURunningFromDiskImageError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:SULocalizedString(@"%1$@ can't be updated, because it was opened from a read-only or a temporary location.", nil), hostName], NSLocalizedRecoverySuggestionErrorKey: [NSString stringWithFormat:SULocalizedString(@"Use Finder to copy %1$@ to the Applications folder, relaunch it from there, and try again.", nil), hostName] }]];
[self.delegate basicDriverIsRequestingAbortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SURunningFromDiskImageError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:SULocalizedString(@"%1$@ can’t be updated, because it was opened from a read-only or a temporary location.", nil), hostName], NSLocalizedRecoverySuggestionErrorKey: [NSString stringWithFormat:SULocalizedString(@"Use Finder to copy %1$@ to the Applications folder, relaunch it from there, and try again.", nil), hostName] }]];
}
} else {
[self.appcastDriver loadAppcastFromURL:appcastURL userAgent:userAgent httpHeaders:httpHeaders inBackground:background];
@@ -90,14 +92,12 @@
[self notifyFinishLoadingAppcast];
SUAppcastItem *nonNullUpdateItem = updateItem;
[self notifyFoundValidUpdateWithAppcastItem:nonNullUpdateItem secondaryAppcastItem:secondaryUpdateItem systemDomain:systemDomain];
[self notifyFoundValidUpdateWithAppcastItem:nonNullUpdateItem secondaryAppcastItem:secondaryUpdateItem systemDomain:systemDomain resuming:YES];
}
}
- (void)resumeInstallingUpdateWithCompletion:(SPUUpdateDriverCompletion)completionBlock
- (void)resumeInstallingUpdate
{
self.completionBlock = completionBlock;
NSString *hostBundleIdentifier = self.host.bundle.bundleIdentifier;
assert(hostBundleIdentifier != nil);
[SPUProbeInstallStatus probeInstallerUpdateItemForHostBundleIdentifier:hostBundleIdentifier completion:^(SPUInstallationInfo * _Nullable installationInfo) {
@@ -107,10 +107,8 @@
}];
}
- (void)resumeUpdate:(id<SPUResumableUpdate>)resumableUpdate completion:(SPUUpdateDriverCompletion)completionBlock
- (void)resumeUpdate:(id<SPUResumableUpdate>)resumableUpdate
{
self.completionBlock = completionBlock;
[self notifyResumableUpdateItem:resumableUpdate.updateItem secondaryUpdateItem:resumableUpdate.secondaryUpdateItem systemDomain:nil];
}
@@ -139,9 +137,25 @@
}
}
- (void)notifyFoundValidUpdateWithAppcastItem:(SUAppcastItem *)updateItem secondaryAppcastItem:(SUAppcastItem * _Nullable)secondaryUpdateItem systemDomain:(NSNumber * _Nullable)systemDomain
- (void)notifyFoundValidUpdateWithAppcastItem:(SUAppcastItem *)updateItem secondaryAppcastItem:(SUAppcastItem * _Nullable)secondaryUpdateItem systemDomain:(NSNumber * _Nullable)systemDomain resuming:(BOOL)resuming
{
if (!self.aborted) {
if (!resuming) {
// interactive pkg based updates are not supported under root user
if ([updateItem.installationType isEqualToString:SPUInstallationTypeInteractivePackage] && geteuid() == 0) {
[self.delegate basicDriverIsRequestingAbortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationRootInteractiveError userInfo:@{ NSLocalizedDescriptionKey: SULocalizedString(@"Interactive based packages cannot be installed as the root user.", nil) }]];
return;
} else {
// Give the delegate a chance to bail
NSError *shouldNotProceedError = nil;
if ([self.updaterDelegate respondsToSelector:@selector(updater:shouldProceedWithUpdate:updateCheck:error:)] && ![self.updaterDelegate updater:self.updater shouldProceedWithUpdate:updateItem updateCheck:self.updateCheck error:&shouldNotProceedError]) {
[self.delegate basicDriverIsRequestingAbortUpdateWithError:shouldNotProceedError];
return;
}
}
}
[[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterDidFindValidUpdateNotification
object:self.updater
userInfo:@{ SUUpdaterAppcastItemNotificationKey: updateItem }];
@@ -156,7 +170,7 @@
- (void)didFindValidUpdateWithAppcastItem:(SUAppcastItem *)updateItem secondaryAppcastItem:(SUAppcastItem * _Nullable)secondaryAppcastItem
{
[self notifyFoundValidUpdateWithAppcastItem:updateItem secondaryAppcastItem:secondaryAppcastItem systemDomain:nil];
[self notifyFoundValidUpdateWithAppcastItem:updateItem secondaryAppcastItem:secondaryAppcastItem systemDomain:nil resuming:NO];
}
- (void)didNotFindUpdateWithLatestAppcastItem:(nullable SUAppcastItem *)latestAppcastItem hostToLatestAppcastItemComparisonResult:(NSComparisonResult)hostToLatestAppcastItemComparisonResult background:(BOOL)background
@@ -170,15 +184,15 @@
switch (hostToLatestAppcastItemComparisonResult) {
case NSOrderedDescending:
// This means the user is a 'newer than latest' version. give a slight hint to the user instead of wrongly claiming this version is identical to the latest feed version.
localizedDescription = SULocalizedString(@"You're up-to-date!", "Status message shown when the user checks for updates but is already current or the feed doesn't contain any updates.");
localizedDescription = SULocalizedString(@"You’re up-to-date!", "Status message shown when the user checks for updates but is already current or the feed doesn't contain any updates.");
recoverySuggestion = [NSString stringWithFormat:SULocalizedString(@"%@ %@ is currently the newest version available.\n(You are currently running version %@.)", nil), [self.host name], latestAppcastItem.displayVersionString, [self.host displayVersion]];
recoverySuggestion = [NSString stringWithFormat:SULocalizedString(@"%@ %@ is currently the newest version available.\n(You are currently running version %@.)", nil), [self.host name], latestAppcastItem.displayVersionString, [self.host displayVersion]];
reason = SPUNoUpdateFoundReasonOnNewerThanLatestVersion;
break;
case NSOrderedSame:
// No new update is available and we're on the latest
localizedDescription = SULocalizedString(@"You're up-to-date!", "Status message shown when the user checks for updates but is already current or the feed doesn't contain any updates.");
localizedDescription = SULocalizedString(@"You’re up-to-date!", "Status message shown when the user checks for updates but is already current or the feed doesn't contain any updates.");
recoverySuggestion = [NSString stringWithFormat:SULocalizedString(@"%@ %@ is currently the newest version available.", nil), [self.host name], [self.host displayVersion]];
@@ -190,18 +204,18 @@
if (!latestAppcastItem.minimumOperatingSystemVersionIsOK) {
localizedDescription = SULocalizedString(@"Your macOS version is too old", nil);
recoverySuggestion = [NSString stringWithFormat:SULocalizedString(@"%1$@ %2$@ is available but your macOS version is too old to install it. At least macOS %3$@ is required.", nil), [self.host name], latestAppcastItem.versionString, latestAppcastItem.minimumSystemVersion];
recoverySuggestion = [NSString stringWithFormat:SULocalizedString(@"%1$@ %2$@ is available but your macOS version is too old to install it. At least macOS %3$@ is required.", nil), [self.host name], latestAppcastItem.displayVersionString, latestAppcastItem.minimumSystemVersion];
reason = SPUNoUpdateFoundReasonSystemIsTooOld;
} else if (!latestAppcastItem.maximumOperatingSystemVersionIsOK) {
localizedDescription = SULocalizedString(@"Your macOS version is too new", nil);
recoverySuggestion = [NSString stringWithFormat:SULocalizedString(@"%1$@ %2$@ is available but your macOS version is too new for this update. This update only supports up to macOS %3$@.", nil), [self.host name], latestAppcastItem.versionString, latestAppcastItem.maximumSystemVersion];
recoverySuggestion = [NSString stringWithFormat:SULocalizedString(@"%1$@ %2$@ is available but your macOS version is too new for this update. This update only supports up to macOS %3$@.", nil), [self.host name], latestAppcastItem.displayVersionString, latestAppcastItem.maximumSystemVersion];
reason = SPUNoUpdateFoundReasonSystemIsTooNew;
} else {
// We shouldn't realistically get here
localizedDescription = SULocalizedString(@"You're up-to-date!", "Status message shown when the user checks for updates but is already current or the feed doesn't contain any updates.");
localizedDescription = SULocalizedString(@"You’re up-to-date!", "Status message shown when the user checks for updates but is already current or the feed doesn't contain any updates.");
recoverySuggestion = [NSString stringWithFormat:SULocalizedString(@"%@ %@ is currently the newest version available.", nil), [self.host name], [self.host displayVersion]];
@@ -214,7 +228,7 @@
// We will need to assume the user is up to date if the feed doen't have any applicable update items
// There could be update items on channels the updater is not subscribed to for example. But we can't tell the user about them.
// There could also only be update items available for other platforms or none at all.
localizedDescription = SULocalizedString(@"You're up-to-date!", "Status message shown when the user checks for updates but is already current or the feed doesn't contain any updates.");
localizedDescription = SULocalizedString(@"You’re up-to-date!", "Status message shown when the user checks for updates but is already current or the feed doesn't contain any updates.");
recoverySuggestion = [NSString stringWithFormat:SULocalizedString(@"%@ %@ is currently the newest version available.", nil), [self.host name], [self.host displayVersion]];
reason = SPUNoUpdateFoundReasonOnLatestVersion;
@@ -258,19 +272,8 @@
self.aborted = YES;
[self.appcastDriver cleanup:^{
if (error != nil) {
if (error.code != SUNoUpdateError && error.code != SUInstallationCanceledError && error.code != SUInstallationAuthorizeLaterError) { // Let's not bother logging this.
SULogError(error);
}
// Notify host app that updater has aborted
if ([self.updaterDelegate respondsToSelector:@selector((updater:didAbortWithError:))]) {
[self.updaterDelegate updater:self.updater didAbortWithError:(NSError * _Nonnull)error];
}
}
if (self.completionBlock != nil) {
self.completionBlock(shouldShowUpdateImmediately, resumableUpdate);
self.completionBlock(shouldShowUpdateImmediately, resumableUpdate, error);
self.completionBlock = nil;
}
}];
+7 -8
View File
@@ -9,6 +9,7 @@
#import <Foundation/Foundation.h>
#import "SPUUpdateDriver.h"
#import "SPUUserUpdateState.h"
#import "SPUUpdateCheck.h"
NS_ASSUME_NONNULL_BEGIN
@@ -37,29 +38,27 @@ NS_ASSUME_NONNULL_BEGIN
- (void)coreDriverDidStartExtractingUpdate;
- (void)installerDidStartInstalling;
- (void)installerDidStartInstallingWithApplicationTerminated:(BOOL)applicationTerminated;
- (void)installerDidExtractUpdateWithProgress:(double)progress;
- (void)installerIsSendingAppTerminationSignal;
- (void)installerDidFinishInstallationAndRelaunched:(BOOL)relaunched acknowledgement:(void(^)(void))acknowledgement;
@end
@interface SPUCoreBasedUpdateDriver : NSObject
- (instancetype)initWithHost:(SUHost *)host applicationBundle:(NSBundle *)applicationBundle updater:(id)updater updaterDelegate:(nullable id <SPUUpdaterDelegate>)updaterDelegate delegate:(id<SPUCoreBasedUpdateDriverDelegate>)delegate;
- (instancetype)initWithHost:(SUHost *)host applicationBundle:(NSBundle *)applicationBundle updateCheck:(SPUUpdateCheck)updateCheck updater:(id)updater updaterDelegate:(nullable id <SPUUpdaterDelegate>)updaterDelegate delegate:(id<SPUCoreBasedUpdateDriverDelegate>)delegate;
- (void)prepareCheckForUpdatesWithCompletion:(SPUUpdateDriverCompletion)completionBlock;
- (void)setCompletionHandler:(SPUUpdateDriverCompletion)completionBlock;
- (void)preflightForUpdatePermissionPreventingInstallerInteraction:(BOOL)preventsInstallerInteraction reply:(void (^)(NSError * _Nullable))reply;
- (void)setUpdateWillInstallHandler:(void (^)(void))updateWillInstallHandler;
- (void)checkForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders inBackground:(BOOL)background requiresSilentInstall:(BOOL)silentInstall;
- (void)resumeInstallingUpdateWithCompletion:(SPUUpdateDriverCompletion)completionBlock;
- (void)resumeInstallingUpdate;
- (void)resumeUpdate:(id<SPUResumableUpdate>)resumableUpdate completion:(SPUUpdateDriverCompletion)completionBlock;
- (void)resumeUpdate:(id<SPUResumableUpdate>)resumableUpdate;
- (void)downloadUpdateFromAppcastItem:(SUAppcastItem *)updateItem secondaryAppcastItem:(SUAppcastItem * _Nullable)secondaryUpdateItem inBackground:(BOOL)background;
+41 -72
View File
@@ -13,6 +13,7 @@
#import "SPUInstallerDriver.h"
#import "SPUDownloadDriver.h"
#import "SULog.h"
#import "SULog+NSError.h"
#import "SUErrors.h"
#import "SPUResumableUpdate.h"
#import "SPUDownloadedUpdate.h"
@@ -39,7 +40,6 @@
@property (nonatomic, readonly) SUHost *host;
@property (nonatomic) BOOL resumingInstallingUpdate;
@property (nonatomic) BOOL silentInstall;
@property (nonatomic) BOOL preventsInstallerInteraction;
@property (nonatomic, readonly, weak) id updater; // if we didn't have legacy support, I'd remove this..
@property (nullable, nonatomic, readonly, weak) id <SPUUpdaterDelegate>updaterDelegate;
@property (nonatomic) NSString *userAgent;
@@ -58,7 +58,6 @@
@synthesize host = _host;
@synthesize resumingInstallingUpdate = _resumingInstallingUpdate;
@synthesize silentInstall = _silentInstall;
@synthesize preventsInstallerInteraction = _preventsInstallerInteraction;
@synthesize updater = _updater;
@synthesize updaterDelegate = _updaterDelegate;
@synthesize userAgent = _userAgent;
@@ -66,7 +65,7 @@
@synthesize resumableUpdate = _resumableUpdate;
@synthesize downloadedUpdateForRemoval = _downloadedUpdateForRemoval;
- (instancetype)initWithHost:(SUHost *)host applicationBundle:(NSBundle *)applicationBundle updater:(id)updater updaterDelegate:(nullable id <SPUUpdaterDelegate>)updaterDelegate delegate:(id<SPUCoreBasedUpdateDriverDelegate>)delegate
- (instancetype)initWithHost:(SUHost *)host applicationBundle:(NSBundle *)applicationBundle updateCheck:(SPUUpdateCheck)updateCheck updater:(id)updater updaterDelegate:(nullable id <SPUUpdaterDelegate>)updaterDelegate delegate:(id<SPUCoreBasedUpdateDriverDelegate>)delegate
{
self = [super init];
if (self != nil) {
@@ -75,7 +74,7 @@
NSString *bundleIdentifier = host.bundle.bundleIdentifier;
assert(bundleIdentifier != nil);
_basicDriver = [[SPUBasicUpdateDriver alloc] initWithHost:host updater:updater updaterDelegate:updaterDelegate delegate:self];
_basicDriver = [[SPUBasicUpdateDriver alloc] initWithHost:host updateCheck:updateCheck updater:updater updaterDelegate:updaterDelegate delegate:self];
_installerDriver = [[SPUInstallerDriver alloc] initWithHost:host applicationBundle:applicationBundle updater:updater updaterDelegate:updaterDelegate delegate:self];
_host = host;
@@ -85,33 +84,14 @@
return self;
}
- (void)prepareCheckForUpdatesWithCompletion:(SPUUpdateDriverCompletion)completionBlock
- (void)setCompletionHandler:(SPUUpdateDriverCompletion)completionBlock
{
[self.basicDriver prepareCheckForUpdatesWithCompletion:completionBlock];
[self.basicDriver setCompletionHandler:completionBlock];
}
- (void)preflightForUpdatePermissionPreventingInstallerInteraction:(BOOL)preventsInstallerInteraction reply:(void (^)(NSError * _Nullable))reply
- (void)setUpdateWillInstallHandler:(void (^)(void))updateWillInstallHandler
{
// Save for later
self.preventsInstallerInteraction = preventsInstallerInteraction;
// If we don't allow interaction, make sure we have sufficient privileges to update
// If we don't, then we should abort early before trying to check for updates
// Note if we don't have permission to update an application update without interaction,
// then we won't have permission for package type of updates either (converse is not true)
if (!preventsInstallerInteraction) {
reply(nil);
} else {
// Otherwise check if we have sufficient privileges to update without interaction
[self.installerDriver checkIfApplicationInstallationRequiresAuthorizationWithReply:^(BOOL requiresAuthorization) {
if (requiresAuthorization) {
reply([NSError errorWithDomain:SUSparkleErrorDomain code:SUNotAllowedInteractionError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"No new update has been checked because the installation will require interaction, which has been prevented."] }]);
} else {
reply(nil);
}
}];
}
[self.installerDriver setUpdateWillInstallHandler:updateWillInstallHandler];
}
- (void)checkForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders inBackground:(BOOL)background requiresSilentInstall:(BOOL)silentInstall
@@ -123,23 +103,20 @@
[self.basicDriver checkForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders inBackground:background];
}
- (void)resumeInstallingUpdateWithCompletion:(SPUUpdateDriverCompletion)completionBlock
- (void)resumeInstallingUpdate
{
self.resumingInstallingUpdate = YES;
self.silentInstall = NO;
[self.basicDriver resumeInstallingUpdateWithCompletion:completionBlock];
[self.basicDriver resumeInstallingUpdate];
}
- (void)resumeUpdate:(id<SPUResumableUpdate>)resumableUpdate completion:(SPUUpdateDriverCompletion)completionBlock
- (void)resumeUpdate:(id<SPUResumableUpdate>)resumableUpdate
{
self.resumableUpdate = resumableUpdate;
self.silentInstall = NO;
// Note if installer interaction isn't allowed, we shouldn't have downloaded the update, and shouldn't be able to get here
// So no need to do a test if we can perform an update without authorization
[self.basicDriver resumeUpdate:resumableUpdate completion:completionBlock];
[self.basicDriver resumeUpdate:resumableUpdate];
}
- (void)basicDriverDidFinishLoadingAppcast
@@ -157,21 +134,9 @@
if (self.resumingInstallingUpdate) {
assert(systemDomain != nil);
[self.installerDriver resumeInstallingUpdateWithUpdateItem:updateItem systemDomain:systemDomain.boolValue];
[self.delegate basicDriverDidFindUpdateWithAppcastItem:updateItem secondaryAppcastItem:secondaryUpdateItem];
} else {
if (!self.preventsInstallerInteraction) {
// Simple case - delegate allows interaction, so we should continue along
[self.delegate basicDriverDidFindUpdateWithAppcastItem:updateItem secondaryAppcastItem:secondaryUpdateItem];
} else {
// Package type installations will always require installer interaction as long as we don't support running as root
// If it's not a package type installation, we should be okay since we did an auth check before checking for updates above
if (![updateItem.installationType isEqualToString:SPUInstallationTypeApplication]) {
[self.delegate coreDriverIsRequestingAbortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUNotAllowedInteractionError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"A new update is available but cannot be installed because interaction has been prevented."] }]];
} else {
[self.delegate basicDriverDidFindUpdateWithAppcastItem:updateItem secondaryAppcastItem:secondaryUpdateItem];
}
}
}
[self.delegate basicDriverDidFindUpdateWithAppcastItem:updateItem secondaryAppcastItem:secondaryUpdateItem];
}
- (void)downloadUpdateFromAppcastItem:(SUAppcastItem *)updateItem secondaryAppcastItem:(SUAppcastItem * _Nullable)secondaryUpdateItem inBackground:(BOOL)background
@@ -265,7 +230,7 @@
[self.delegate coreDriverDidStartExtractingUpdate];
}
[self.installerDriver extractDownloadedUpdate:downloadedUpdate silently:self.silentInstall preventsInstallerInteraction:self.preventsInstallerInteraction completion:^(NSError * _Nullable error) {
[self.installerDriver extractDownloadedUpdate:downloadedUpdate silently:self.silentInstall completion:^(NSError * _Nullable error) {
if (error != nil) {
if (error.code != SUInstallationAuthorizeLaterError) {
[self clearDownloadedUpdate];
@@ -288,24 +253,31 @@
- (void)downloadDriverDidFailToDownloadFileWithError:(NSError *)error
{
if ([self.updaterDelegate respondsToSelector:@selector((updater:failedToDownloadUpdate:error:))]) {
NSError *errorToReport = [error.userInfo objectForKey:NSUnderlyingErrorKey];
if (errorToReport == nil) {
errorToReport = error;
if ([self.updateItem isDeltaUpdate]) {
SULog(SULogLevelError, @"Failed to download delta update. Falling back to regular update...");
SULogError(error);
[self fallBackAndDownloadRegularUpdate];
} else {
if ([self.updaterDelegate respondsToSelector:@selector((updater:failedToDownloadUpdate:error:))]) {
NSError *errorToReport = [error.userInfo objectForKey:NSUnderlyingErrorKey];
if (errorToReport == nil) {
errorToReport = error;
}
[self.updaterDelegate updater:self.updater
failedToDownloadUpdate:self.updateItem
error:errorToReport];
}
[self.updaterDelegate updater:self.updater
failedToDownloadUpdate:self.updateItem
error:errorToReport];
[self.delegate coreDriverIsRequestingAbortUpdateWithError:error];
}
[self.delegate coreDriverIsRequestingAbortUpdateWithError:error];
}
- (void)installerDidStartInstalling
- (void)installerDidStartInstallingWithApplicationTerminated:(BOOL)applicationTerminated
{
if ([self.delegate respondsToSelector:@selector(installerDidStartInstalling)]) {
[self.delegate installerDidStartInstalling];
if ([self.delegate respondsToSelector:@selector(installerDidStartInstallingWithApplicationTerminated:)]) {
[self.delegate installerDidStartInstallingWithApplicationTerminated:applicationTerminated];
}
}
@@ -365,14 +337,6 @@
}
}
- (void)installerIsSendingAppTerminationSignal
{
// If they don't respond or do anything, we'll just install after the user terminates the app anyway
if ([self.delegate respondsToSelector:@selector(installerIsSendingAppTerminationSignal)]) {
[self.delegate installerIsSendingAppTerminationSignal];
}
}
- (void)installerIsRequestingAbortInstallWithError:(nullable NSError *)error
{
[self.delegate coreDriverIsRequestingAbortUpdateWithError:error];
@@ -384,15 +348,13 @@
[self.delegate basicDriverIsRequestingAbortUpdateWithError:error];
}
- (void)installerDidFailToApplyDeltaUpdate
- (void)fallBackAndDownloadRegularUpdate
{
SUAppcastItem *secondaryUpdateItem = self.secondaryUpdateItem;
assert(secondaryUpdateItem != nil);
BOOL backgroundDownload = self.downloadDriver.inBackground;
[self clearDownloadedUpdate];
// Fall back to the non-delta update. Note that we don't want to trigger another update was found event.
self.updateItem = secondaryUpdateItem;
self.secondaryUpdateItem = nil;
@@ -400,6 +362,13 @@
[self downloadUpdateFromAppcastItem:secondaryUpdateItem secondaryAppcastItem:nil inBackground:backgroundDownload];
}
- (void)installerDidFailToApplyDeltaUpdate
{
[self clearDownloadedUpdate];
[self fallBackAndDownloadRegularUpdate];
}
- (void)abortUpdateAndShowNextUpdateImmediately:(BOOL)shouldShowUpdateImmediately error:(nullable NSError *)error
{
[self.installerDriver abortInstall];
+3 -4
View File
@@ -16,7 +16,6 @@
#import "SUHost.h"
#import "SULog.h"
#import "SUErrors.h"
#import "SPUURLRequest.h"
#import "SPUDownloadedUpdate.h"
#import "SPUDownloadData.h"
@@ -61,7 +60,7 @@
if (self != nil) {
_host = host;
if (!SPUXPCServiceExists(@DOWNLOADER_BUNDLE_ID)) {
if (!SPUXPCServiceIsEnabled(SUEnableDownloaderServiceKey)) {
_downloader = [[SPUDownloader alloc] initWithDelegate:self];
} else {
_connection = [[NSXPCConnection alloc] initWithServiceName:@DOWNLOADER_BUNDLE_ID];
@@ -160,9 +159,9 @@
NSString *bundleIdentifier = self.host.bundle.bundleIdentifier;
assert(bundleIdentifier != nil);
[self.downloader startPersistentDownloadWithRequest:[SPUURLRequest URLRequestWithRequest:self.request] bundleIdentifier:bundleIdentifier desiredFilename:desiredFilename];
[self.downloader startPersistentDownloadWithRequest:self.request bundleIdentifier:bundleIdentifier desiredFilename:desiredFilename];
} else {
[self.downloader startTemporaryDownloadWithRequest:[SPUURLRequest URLRequestWithRequest:self.request]];
[self.downloader startTemporaryDownloadWithRequest:self.request];
}
}
+22
View File
@@ -0,0 +1,22 @@
//
// SPUGentleUserDriverReminders.h
// Sparkle
//
// Copyright © 2022 Sparkle Project. All rights reserved.
//
#ifndef SPUGentleUserDriverReminders_h
#define SPUGentleUserDriverReminders_h
/**
A private protocol for user drivers implementing gentle scheduled reminders
*/
@protocol SPUGentleUserDriverReminders
- (void)logGentleScheduledUpdateReminderWarningIfNeeded;
- (void)resetTimeSinceOpportuneUpdateNotice;
@end
#endif /* SPUGentleUserDriverReminders_h */
+3 -4
View File
@@ -15,11 +15,10 @@ NS_ASSUME_NONNULL_BEGIN
@protocol SPUInstallerDriverDelegate <NSObject>
- (void)installerDidStartInstalling;
- (void)installerDidStartInstallingWithApplicationTerminated:(BOOL)applicationTerminated;
- (void)installerDidStartExtracting;
- (void)installerDidExtractUpdateWithProgress:(double)progress;
- (void)installerDidFinishPreparationAndWillInstallImmediately:(BOOL)willInstallImmediately silently:(BOOL)willInstallSilently;
- (void)installerIsSendingAppTerminationSignal;
- (void)installerWillFinishInstallationAndRelaunch:(BOOL)relaunch;
- (void)installerDidFinishInstallationAndRelaunched:(BOOL)relaunch acknowledgement:(void(^)(void))acknowledgement;
@@ -34,9 +33,9 @@ NS_ASSUME_NONNULL_BEGIN
- (void)resumeInstallingUpdateWithUpdateItem:(SUAppcastItem *)updateItem systemDomain:(BOOL)systemDomain;
- (void)checkIfApplicationInstallationRequiresAuthorizationWithReply:(void (^)(BOOL requiresAuthorization))reply;
- (void)setUpdateWillInstallHandler:(void (^)(void))updateWillInstallHandler;
- (void)extractDownloadedUpdate:(SPUDownloadedUpdate *)downloadedUpdate silently:(BOOL)silently preventsInstallerInteraction:(BOOL)preventsInstallerInteraction completion:(void (^)(NSError * _Nullable))completionHandler;
- (void)extractDownloadedUpdate:(SPUDownloadedUpdate *)downloadedUpdate silently:(BOOL)silently completion:(void (^)(NSError * _Nullable))completionHandler;
- (void)installWithToolAndRelaunch:(BOOL)relaunch displayingUserInterface:(BOOL)showUI;
+82 -103
View File
@@ -43,7 +43,6 @@
@property (nonatomic, readonly) NSBundle *applicationBundle;
@property (nonatomic, weak, readonly) id<SPUInstallerDriverDelegate> delegate;
@property (nonatomic) SPUInstallerMessageType currentStage;
@property (nonatomic) BOOL startedInstalling;
@property (nonatomic) id<SUInstallerConnectionProtocol> installerConnection;
@@ -65,12 +64,14 @@
@end
@implementation SPUInstallerDriver
{
void (^_updateWillInstallHandler)(void);
}
@synthesize host = _host;
@synthesize applicationBundle = _applicationBundle;
@synthesize delegate = _delegate;
@synthesize currentStage = _currentStage;
@synthesize startedInstalling = _startedInstalling;
@synthesize installerConnection = _installerConnection;
@synthesize extractionAttempts = _extractionAttempts;
@synthesize postponedOnce = _postponedOnce;
@@ -97,6 +98,68 @@
return self;
}
- (void)setUpdateWillInstallHandler:(void (^)(void))updateWillInstallHandler
{
_updateWillInstallHandler = [updateWillInstallHandler copy];
}
- (void)_reportInstallerError:(nullable NSError *)currentInstallerError genericErrorCode:(NSInteger)genericErrorCode genericUserInfo:(NSDictionary *)genericUserInfo
{
// First see if there is a good custom error we can show
// We only check for signing validation errors and installation errors due to not having write permission currently
NSError *customError = nil;
if (currentInstallerError != nil) {
NSError *underlyingError = currentInstallerError.userInfo[NSUnderlyingErrorKey];
if (underlyingError != nil) {
if (underlyingError.code == SUValidationError) {
NSDictionary *userInfo = @{
NSLocalizedDescriptionKey: SULocalizedString(@"The update is improperly signed and could not be validated. Please try again later or contact the app developer.", nil),
NSUnderlyingErrorKey: (NSError * _Nonnull)currentInstallerError
};
customError = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:userInfo];
} else if (underlyingError.code == SUInstallationError) {
NSError *secondUnderlyingError = underlyingError.userInfo[NSUnderlyingErrorKey];
if (secondUnderlyingError != nil && [secondUnderlyingError.domain isEqualToString:NSCocoaErrorDomain] && secondUnderlyingError.code == NSFileWriteNoPermissionError) {
// Note: these error strings will only surface for external app updaters like sparkle-cli (i.e, updaters that update other app bundles)
NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:@{
NSLocalizedDescriptionKey: SULocalizedString(@"The installation failed due to not having permission to write the new update.", nil),
NSUnderlyingErrorKey: (NSError * _Nonnull)currentInstallerError
}];
// macOS 13 and later introduce a policy where Gatekeeper can block app modifications if the apps have different Team IDs
if (@available(macOS 13, *)) {
NSBundle *mainBundle = [NSBundle mainBundle];
if (![mainBundle isEqual:self.host.bundle]) {
SUHost *mainBundleHost = [[SUHost alloc] initWithBundle:mainBundle];
userInfo[NSLocalizedRecoverySuggestionErrorKey] = [NSString stringWithFormat:SULocalizedString(@"You may need to allow modifications from %1$@ in System Settings under Privacy & Security and App Management to install future updates.", nil), mainBundleHost.name];
}
}
customError = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationWriteNoPermissionError userInfo:userInfo];
}
}
}
}
// Otherwise if there's no custom error, then use a generic installer error to show
// and keep the underlying error around for logging
NSError *installerError;
if (customError != nil) {
installerError = customError;
} else {
NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:genericUserInfo];
if (currentInstallerError != nil) {
userInfo[NSUnderlyingErrorKey] = currentInstallerError;
}
installerError = [NSError errorWithDomain:SUSparkleErrorDomain code:genericErrorCode userInfo:userInfo];
}
[self.delegate installerIsRequestingAbortInstallWithError:installerError];
}
- (void)setUpConnection
{
if (self.installerConnection != nil) {
@@ -106,8 +169,8 @@
NSString *hostBundleIdentifier = self.host.bundle.bundleIdentifier;
assert(hostBundleIdentifier != nil);
if (!SPUXPCServiceExists(@INSTALLER_CONNECTION_BUNDLE_ID)) {
self.installerConnection = [[SUInstallerConnection alloc] initWithDelegate:self];
if (!SPUXPCServiceIsEnabled(SUEnableInstallerConnectionServiceKey)) {
self.installerConnection = [[SUInstallerConnection alloc] initWithDelegate:self remote:NO];
} else {
self.installerConnection = [[SUXPCInstallerConnection alloc] initWithDelegate:self];
}
@@ -117,18 +180,12 @@
dispatch_async(dispatch_get_main_queue(), ^{
SPUInstallerDriver *strongSelf = weakSelf;
if (strongSelf.installerConnection != nil && !strongSelf.aborted) {
NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:@{
NSDictionary *genericUserInfo = @{
NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while running the updater. Please try again later.", nil),
NSLocalizedFailureReasonErrorKey:@"The remote port connection was invalidated from the updater. For additional details, please check Console logs for "@SPARKLE_RELAUNCH_TOOL_NAME". If your application is sandboxed, please also ensure Installer Connection & Status entitlements are correctly set up: https://sparkle-project.org/documentation/sandboxing/"
}];
};
NSError *installerError = strongSelf.installerError;
if (installerError != nil) {
userInfo[NSUnderlyingErrorKey] = installerError;
}
[strongSelf.delegate installerIsRequestingAbortInstallWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:userInfo]];
[strongSelf _reportInstallerError:strongSelf.installerError genericErrorCode:SUInstallationError genericUserInfo:genericUserInfo];
}
});
}];
@@ -141,7 +198,7 @@
}
// This can be called multiple times (eg: if a delta update fails, this may be called again with a regular update item)
- (void)extractDownloadedUpdate:(SPUDownloadedUpdate *)downloadedUpdate silently:(BOOL)silently preventsInstallerInteraction:(BOOL)preventsInstallerInteraction completion:(void (^)(NSError * _Nullable))completionHandler
- (void)extractDownloadedUpdate:(SPUDownloadedUpdate *)downloadedUpdate silently:(BOOL)silently completion:(void (^)(NSError * _Nullable))completionHandler
{
self.updateItem = downloadedUpdate.updateItem;
self.temporaryDirectory = downloadedUpdate.temporaryDirectory;
@@ -150,7 +207,7 @@
self.currentStage = SPUInstallerNotStarted;
if (self.installerConnection == nil) {
[self launchAutoUpdateSilently:silently preventsInstallerInteraction:preventsInstallerInteraction completion:completionHandler];
[self launchAutoUpdateSilently:silently completion:completionHandler];
} else {
// The Install tool is already alive; just send out installation input data again
[self sendInstallationData];
@@ -238,22 +295,15 @@
[self.delegate installerDidFailToApplyDeltaUpdate];
} else {
// Don't have to store current stage because we're going to abort
NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:@{ NSLocalizedDescriptionKey:SULocalizedString(@"An error occurred while extracting the archive. Please try again later.", nil) }];
NSDictionary *genericUserInfo = @{ NSLocalizedDescriptionKey:SULocalizedString(@"An error occurred while extracting the archive. Please try again later.", nil) };
NSError *unarchivedError = (NSError *)SPUUnarchiveRootObjectSecurely(data, [NSError class]);
if (unarchivedError != nil) {
userInfo[NSUnderlyingErrorKey] = unarchivedError;
}
[self.delegate installerIsRequestingAbortInstallWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:userInfo]];
[self _reportInstallerError:unarchivedError genericErrorCode:SUUnarchivingError genericUserInfo:genericUserInfo];
}
} else if (identifier == SPUValidationStarted) {
self.currentStage = identifier;
} else if (identifier == SPUInstallationStartedStage1) {
self.currentStage = identifier;
[self.delegate installerDidStartInstalling];
self.startedInstalling = YES;
} else if (identifier == SPUInstallationFinishedStage1) {
self.currentStage = identifier;
@@ -281,12 +331,6 @@
} else if (identifier == SPUInstallationFinishedStage2) {
self.currentStage = identifier;
if (!self.startedInstalling) {
// It's possible we can start from resuming to stage 2 rather than doing stage 1 again, so we should notify to start installing if we haven't done so already
self.startedInstalling = YES;
[self.delegate installerDidStartInstalling];
}
BOOL hasTargetTerminated = NO;
if (data.length >= sizeof(uint8_t)) {
hasTargetTerminated = (BOOL)*((const uint8_t *)data.bytes);
@@ -294,9 +338,7 @@
[self.delegate installerWillFinishInstallationAndRelaunch:self.relaunch];
if (!hasTargetTerminated) {
[self.delegate installerIsSendingAppTerminationSignal];
}
[self.delegate installerDidStartInstallingWithApplicationTerminated:hasTargetTerminated];
} else if (identifier == SPUInstallationFinishedStage3) {
self.currentStage = identifier;
@@ -317,80 +359,13 @@
}
}
- (void)checkIfApplicationInstallationRequiresAuthorizationWithReply:(void (^)(BOOL requiresAuthorization))reply
{
id<SUInstallerLauncherProtocol> installerLauncher = nil;
__block BOOL madeReply = NO;
NSXPCConnection *launcherConnection = nil;
if (!SPUXPCServiceExists(@INSTALLER_LAUNCHER_BUNDLE_ID)) {
installerLauncher = [[SUInstallerLauncher alloc] init];
} else {
launcherConnection = [[NSXPCConnection alloc] initWithServiceName:@INSTALLER_LAUNCHER_BUNDLE_ID];
launcherConnection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUInstallerLauncherProtocol)];
launcherConnection.interruptionHandler = ^{
dispatch_async(dispatch_get_main_queue(), ^{
if (!madeReply) {
// We'll break the retain cycle in the invalidation handler
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-retain-cycles"
[launcherConnection invalidate];
#pragma clang diagnostic pop
}
});
};
launcherConnection.invalidationHandler = ^{
dispatch_async(dispatch_get_main_queue(), ^{
#pragma clang diagnostic push
#if __has_warning("-Wcompletion-handler")
#pragma clang diagnostic ignored "-Wcompletion-handler"
#endif
if (!madeReply) {
#pragma clang diagnostic pop
// If something went horribly wrong, just guess that we won't require authorization
reply(NO);
// Break the retain cycle
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-retain-cycles"
launcherConnection.interruptionHandler = nil;
launcherConnection.invalidationHandler = nil;
#pragma clang diagnostic pop
}
});
};
[launcherConnection resume];
installerLauncher = launcherConnection.remoteObjectProxy;
}
[installerLauncher checkIfApplicationInstallationRequiresAuthorizationWithHostBundlePath:self.host.bundlePath reply:^(BOOL requiresAuthorization) {
dispatch_async(dispatch_get_main_queue(), ^{
#pragma clang diagnostic push
#if __has_warning("-Wcompletion-handler")
#pragma clang diagnostic ignored "-Wcompletion-handler"
#endif
if (!madeReply) {
#pragma clang diagnostic pop
madeReply = YES;
[launcherConnection invalidate];
reply(requiresAuthorization);
}
});
}];
}
- (void)launchAutoUpdateSilently:(BOOL)silently preventsInstallerInteraction:(BOOL)preventsInstallerInteraction completion:(void (^)(NSError *_Nullable))completionHandler
- (void)launchAutoUpdateSilently:(BOOL)silently completion:(void (^)(NSError *_Nullable))completionHandler
{
id<SUInstallerLauncherProtocol> installerLauncher = nil;
__block BOOL retrievedLaunchStatus = NO;
NSXPCConnection *launcherConnection = nil;
if (!SPUXPCServiceExists(@INSTALLER_LAUNCHER_BUNDLE_ID)) {
if (!SPUXPCServiceIsEnabled(SUEnableInstallerLauncherServiceKey)) {
installerLauncher = [[SUInstallerLauncher alloc] init];
} else {
launcherConnection = [[NSXPCConnection alloc] initWithServiceName:@INSTALLER_LAUNCHER_BUNDLE_ID];
@@ -473,7 +448,7 @@
mainBundleIdentifier = (bundleIdentifier == nil) ? mainBundleName : bundleIdentifier;
}
[installerLauncher launchInstallerWithHostBundlePath:hostBundlePath updaterIdentifier:mainBundleIdentifier authorizationPrompt:authorizationPrompt installationType:installationType allowingDriverInteraction:driverAllowsInteraction allowingUpdaterInteraction:!preventsInstallerInteraction completion:^(SUInstallerLauncherStatus result, BOOL systemDomain) {
[installerLauncher launchInstallerWithHostBundlePath:hostBundlePath updaterIdentifier:mainBundleIdentifier authorizationPrompt:authorizationPrompt installationType:installationType allowingDriverInteraction:driverAllowsInteraction completion:^(SUInstallerLauncherStatus result, BOOL systemDomain) {
dispatch_async(dispatch_get_main_queue(), ^{
retrievedLaunchStatus = YES;
[launcherConnection invalidate];
@@ -529,6 +504,10 @@
}
}
if (_updateWillInstallHandler != NULL) {
_updateWillInstallHandler();
}
// Set up connection to the installer if one is not set up already
[self setUpConnection];
+5 -4
View File
@@ -13,6 +13,7 @@
#import "SPUSecureCoding.h"
#import "SUInstallerStatus.h"
#import "SUXPCInstallerStatus.h"
#import "SUConstants.h"
#import "SULog.h"
@@ -27,9 +28,9 @@
+ (void)probeInstallerInProgressForHostBundleIdentifier:(NSString *)hostBundleIdentifier completion:(void (^)(BOOL))completionHandler
{
id<SUInstallerStatusProtocol> installerStatus = nil;
BOOL usesXPC = SPUXPCServiceExists(@INSTALLER_STATUS_BUNDLE_ID);
BOOL usesXPC = SPUXPCServiceIsEnabled(SUEnableInstallerStatusServiceKey);
if (!usesXPC) {
installerStatus = [[SUInstallerStatus alloc] init];
installerStatus = [[SUInstallerStatus alloc] initWithRemote:NO];
} else {
installerStatus = [[SUXPCInstallerStatus alloc] init];
}
@@ -90,9 +91,9 @@
+ (void)probeInstallerUpdateItemForHostBundleIdentifier:(NSString *)hostBundleIdentifier completion:(void (^)(SPUInstallationInfo * _Nullable))completionHandler
{
id<SUInstallerStatusProtocol> installerStatus = nil;
BOOL usesXPC = SPUXPCServiceExists(@INSTALLER_STATUS_BUNDLE_ID);
BOOL usesXPC = SPUXPCServiceIsEnabled(SUEnableInstallerStatusServiceKey);
if (!usesXPC) {
installerStatus = [[SUInstallerStatus alloc] init];
installerStatus = [[SUInstallerStatus alloc] initWithRemote:NO];
} else {
installerStatus = [[SUXPCInstallerStatus alloc] init];
}
+19 -10
View File
@@ -28,30 +28,39 @@
{
self = [super init];
if (self != nil) {
_basicDriver = [[SPUBasicUpdateDriver alloc] initWithHost:host updater:updater updaterDelegate:updaterDelegate delegate:self];
_basicDriver = [[SPUBasicUpdateDriver alloc] initWithHost:host updateCheck:SPUUpdateCheckUpdateInformation updater:updater updaterDelegate:updaterDelegate delegate:self];
}
return self;
}
- (void)checkForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders preventingInstallerInteraction:(BOOL)__unused preventsInstallerInteraction completion:(SPUUpdateDriverCompletion)completionBlock
- (void)setCompletionHandler:(SPUUpdateDriverCompletion)completionBlock
{
[self.basicDriver setCompletionHandler:completionBlock];
}
- (void)setUpdateShownHandler:(void (^)(void))updateShownHandler
{
}
- (void)setUpdateWillInstallHandler:(void (^)(void))updateWillInstallHandler
{
}
- (void)checkForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders
{
// We don't preflight for update permission in this driver because we are just interested if an update is available
[self.basicDriver prepareCheckForUpdatesWithCompletion:completionBlock];
[self.basicDriver checkForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders inBackground:YES];
}
- (void)resumeInstallingUpdateWithCompletion:(SPUUpdateDriverCompletion)completionBlock
- (void)resumeInstallingUpdate
{
[self.basicDriver resumeInstallingUpdateWithCompletion:completionBlock];
[self.basicDriver resumeInstallingUpdate];
}
- (void)resumeUpdate:(id<SPUResumableUpdate>)resumableUpdate completion:(SPUUpdateDriverCompletion)completionBlock
- (void)resumeUpdate:(id<SPUResumableUpdate>)resumableUpdate
{
self.resumableUpdate = resumableUpdate;
[self.basicDriver resumeUpdate:resumableUpdate completion:completionBlock];
[self.basicDriver resumeUpdate:resumableUpdate];
}
- (void)basicDriverDidFindUpdateWithAppcastItem:(SUAppcastItem *)__unused appcastItem secondaryAppcastItem:(SUAppcastItem * _Nullable)__unused secondaryAppcastItem systemDomain:(NSNumber * _Nullable)__unused systemDomain
+30 -20
View File
@@ -19,6 +19,7 @@
@property (nonatomic, readonly) SPUUIBasedUpdateDriver *uiDriver;
@property (nonatomic) BOOL showedUpdate;
@property (nonatomic) void (^updateDidShowHandler)(void);
@end
@@ -26,6 +27,7 @@
@synthesize uiDriver = _uiDriver;
@synthesize showedUpdate = _showedUpdate;
@synthesize updateDidShowHandler = _updateDidShowHandler;
- (instancetype)initWithHost:(SUHost *)host applicationBundle:(NSBundle *)applicationBundle updater:(id)updater userDriver:(id <SPUUserDriver>)userDriver updaterDelegate:(nullable id <SPUUpdaterDelegate>)updaterDelegate
{
@@ -36,33 +38,43 @@
return self;
}
- (void)checkForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders preventingInstallerInteraction:(BOOL)preventsInstallerInteraction completion:(SPUUpdateDriverCompletion)completionBlock
- (void)setCompletionHandler:(SPUUpdateDriverCompletion)completionBlock
{
[self.uiDriver prepareCheckForUpdatesWithCompletion:completionBlock];
[self.uiDriver preflightForUpdatePermissionPreventingInstallerInteraction:preventsInstallerInteraction reply:^(NSError * _Nullable error) {
if (error != nil) {
// Don't tell the user about the permission error for scheduled update checks
[self abortUpdateWithError:nil];
} else {
[self.uiDriver checkForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders inBackground:YES];
}
}];
[self.uiDriver setCompletionHandler:completionBlock];
}
- (void)resumeInstallingUpdateWithCompletion:(SPUUpdateDriverCompletion)completionBlock
- (void)setUpdateShownHandler:(void (^)(void))handler
{
[self.uiDriver resumeInstallingUpdateWithCompletion:completionBlock];
self.updateDidShowHandler = handler;
}
- (void)resumeUpdate:(id<SPUResumableUpdate>)resumableUpdate completion:(SPUUpdateDriverCompletion)completionBlock
- (void)setUpdateWillInstallHandler:(void (^)(void))updateWillInstallHandler
{
[self.uiDriver resumeUpdate:resumableUpdate completion:completionBlock];
[self.uiDriver setUpdateWillInstallHandler:updateWillInstallHandler];
}
- (void)checkForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders
{
[self.uiDriver checkForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders inBackground:YES];
}
- (void)resumeInstallingUpdate
{
[self.uiDriver resumeInstallingUpdate];
}
- (void)resumeUpdate:(id<SPUResumableUpdate>)resumableUpdate
{
[self.uiDriver resumeUpdate:resumableUpdate];
}
- (void)uiDriverDidShowUpdate
{
self.showedUpdate = YES;
if (self.updateDidShowHandler != nil) {
self.updateDidShowHandler();
}
}
- (BOOL)showingUpdate
@@ -72,14 +84,12 @@
- (void)basicDriverIsRequestingAbortUpdateWithError:(nullable NSError *) error
{
// Don't tell the user that no update was found or some appcast fetch error occurred for scheduled update checks if we haven't shown the update
[self abortUpdateWithError:self.showedUpdate ? error : nil];
[self abortUpdateWithError:error];
}
- (void)coreDriverIsRequestingAbortUpdateWithError:(nullable NSError *) error
{
// Don't tell the user that an update error occurred for scheduled update checks if we haven't shown the update
[self abortUpdateWithError:self.showedUpdate ? error : nil];
[self abortUpdateWithError:error];
}
- (void)uiDriverIsRequestingAbortUpdateWithError:(nullable NSError *)error
@@ -94,7 +104,7 @@
- (void)abortUpdateWithError:(nullable NSError *)error
{
[self.uiDriver abortUpdateWithError:error];
[self.uiDriver abortUpdateWithError:error showErrorToUser:self.showedUpdate];
}
@end
+47 -22
View File
@@ -16,33 +16,58 @@ static NSString *SURootObjectArchiveKey = @"SURootObjectArchive";
NSData * _Nullable SPUArchiveRootObjectSecurely(id<NSSecureCoding> rootObject)
{
NSMutableData *data = [NSMutableData data];
NSKeyedArchiver *keyedArchiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
keyedArchiver.requiresSecureCoding = YES;
@try {
[keyedArchiver encodeObject:rootObject forKey:SURootObjectArchiveKey];
[keyedArchiver finishEncoding];
return [data copy];
} @catch (NSException *exception) {
SULog(SULogLevelError, @"Exception while securely archiving object: %@", exception);
[keyedArchiver finishEncoding];
return nil;
if (@available(macOS 10.13, *)) {
NSError *error = nil;
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:rootObject requiringSecureCoding:YES error:&error];
if (data == nil) {
SULog(SULogLevelError, @"Error while securely archiving object: %@", error);
}
return data;
} else {
NSMutableData *data = [NSMutableData data];
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
NSKeyedArchiver *keyedArchiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
#pragma clang diagnostic pop
keyedArchiver.requiresSecureCoding = YES;
@try {
[keyedArchiver encodeObject:rootObject forKey:SURootObjectArchiveKey];
[keyedArchiver finishEncoding];
return [data copy];
} @catch (NSException *exception) {
SULog(SULogLevelError, @"Exception while securely archiving object: %@", exception);
[keyedArchiver finishEncoding];
return nil;
}
}
}
id<NSSecureCoding> _Nullable SPUUnarchiveRootObjectSecurely(NSData *data, Class klass)
{
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
unarchiver.requiresSecureCoding = YES;
@try {
id<NSSecureCoding> rootObject = [unarchiver decodeObjectOfClass:klass forKey:SURootObjectArchiveKey];
[unarchiver finishDecoding];
if (@available(macOS 10.13, *)) {
NSError *error = nil;
id<NSSecureCoding> rootObject = [NSKeyedUnarchiver unarchivedObjectOfClass:klass fromData:data error:&error];
if (rootObject == nil) {
SULog(SULogLevelError, @"Error while securely unarchiving object: %@", error);
}
return rootObject;
} @catch (NSException *exception) {
SULog(SULogLevelError, @"Exception while securely unarchiving object: %@", exception);
[unarchiver finishDecoding];
return nil;
} else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
#pragma clang diagnostic pop
unarchiver.requiresSecureCoding = YES;
@try {
id<NSSecureCoding> rootObject = [unarchiver decodeObjectOfClass:klass forKey:SURootObjectArchiveKey];
[unarchiver finishDecoding];
return rootObject;
} @catch (NSException *exception) {
SULog(SULogLevelError, @"Exception while securely unarchiving object: %@", exception);
[unarchiver finishDecoding];
return nil;
}
}
}
+4 -2
View File
@@ -27,12 +27,14 @@ NS_ASSUME_NONNULL_BEGIN
+ (void)skipUpdate:(SUAppcastItem *)updateItem host:(SUHost *)host;
// At least one of minorVersion or majorVersion should be non-nil
- (instancetype)initWithMinorVersion:(nullable NSString *)minorVersion majorVersion:(nullable NSString *)majorVersion;
- (instancetype)initWithMinorVersion:(nullable NSString *)minorVersion majorVersion:(nullable NSString *)majorVersion majorSubreleaseVersion:(nullable NSString *)majorSubreleaseVersion;
// At least one of these version properties will be non-nil
// At least one of these two version properties will be non-nil
@property (nonatomic, readonly, nullable) NSString *minorVersion;
@property (nonatomic, readonly, nullable) NSString *majorVersion;
@property (nonatomic, readonly, nullable) NSString *majorSubreleaseVersion;
@end
NS_ASSUME_NONNULL_END
Loaded 100 of 284 files, more files were not shown because too many files have changed in this diff. Show more