Compare commits

..
976 Commits
Author SHA1 Message Date
Sparkle-Bot 488fd7d8bd Update Package management files for version 2.8.0-beta.3 2025-09-09 13:45:15 +00:00
Zorg 86d11fd407 Update CHANGELOG and Carthage file for 2.7.3 2025-09-09 06:38:01 -07:00
Zorg 167db6f80c Double quote team identifiers in designated requirement strings (#2766)
Fixes #2765 which is a crash if team ID starts with a number.
2025-09-09 05:53:13 -07:00
Zorg f1ecf8e445 Update CHANGELOG with false dependency scan fix 2025-09-07 22:57:19 -07:00
Sparkle-Bot ba41d1b7b1 Update Package management files for version 2.8.0-beta.2 2025-09-08 05:12:05 +00:00
Zorg f52d989151 Update Carthage for 2.7.2 2025-09-07 22:01:42 -07:00
Zorg ee00f4f63c Update CHANGELOG for 2.7.2 2025-09-07 21:59:09 -07:00
Zorg 4dac8e3ce8 Harden policy on what operations clients are allowed to take (#2763)
* For the Installer and Downloader XPC Services, if these executables are code signed with an Apple issued Team ID, then the connecting client must also be code signed with a matching Team ID.
* For the Downloader XPC Service, the request URL must be http/https
* For Autoupdate, if stage 1 of installation hasn't been completed yet and this executable is code signed with an Apple issued Team ID, then the connecting client must also be code signed with a matching Team ID. As before, multiple simultaneous connections are still disallowed.
* For Autoupdate, if it's not signed with Apple issued certificate, when installing package updates the bundle being updated must be itself and owned by root on disk (as one expects from a PKG installation)
* The authorization prompt message in the Installer Service is more computed inside the service so the client can't pass a completely arbitrary message
* Add extra nullable checking of parameters coming from XPC endpoints
* Add more thread-safe synchronization for Autoupdate installer
* Add logs for more failure points
2025-09-07 18:02:45 -07:00
Daniel Jalkut 4d7ad5613b Work around the display of warnings about dependency scan analysis discovering a dependency of SparkleInstallerLauncher on Sparkle. I thought at first I could add the build setting just to the affectced XPC service target, but since the scan happens at the workspace level it needs to be set on the project. (#2762) 2025-09-03 17:38:21 -07:00
Sparkle-Bot 366e8a0bf9 Update Package management files for version 2.8.0-beta.1 2025-08-26 03:35:59 +00:00
Zorg 1603296a50 Update changelog for 2.8 2025-08-25 20:14:02 -07:00
Zorg fa4176fdb6 Move all localizations to main Sparkle.strings (#2760) 2025-08-21 20:22:19 -07:00
Zorg 782e2bf5d7 Don't use new test app icon for now to unblock CI (#2755) 2025-08-17 19:48:27 -07:00
Zorg 97bea2fcd4 Modernize update alert (#2737)
This changes the UI for the update alert to have the app icon be more stacked / inlined with the UI, refines the box view for release notes, and removes some title labels that aren't strictly needed. For Tahoe, we opt into using large size buttons which get a capsule shape.

Also this changes adds a new app icon, which is squircle shaped, for the Sparkle test when running on Tahoe.
2025-08-17 17:36:14 -07:00
Zorg b4a1b46fe1 Document and better enforce main thread only requirement for using Sparkle methods (#2754) 2025-08-17 16:17:13 -07:00
Zorg 8702e2dd11 Add tests for file types changing when framework version changes (#2753) 2025-08-17 13:06:11 -07:00
Vincent BénonyandVincent Bénony d491aafeb7 Fix an issue while searching a cloneable file (#2748)
Also bump minor version numbers for major versions 3 and 4

---------

Co-authored-by: Vincent Bénony <bsr43@hopperapp.com>
2025-08-17 08:24:40 -07:00
Zorg 2cfb1e6fe2 Workaround a corner case in which the bundle path of a running application contains Contents/MacOS/Executable (#2747) 2025-07-26 15:46:47 -07:00
Zorg 0c0317c09a Improve retrieval of main app icon for authorization dialog (#2743)
When authorization is needed, create a bitmap representation of the main app icon to save to disk.

Also remove legacy code related to icons.
2025-07-17 20:57:16 -07:00
Zorg 43b3b03886 Update retrieving app icon to work better in Tahoe (#2742)
The old logic had some inconsistencies with picking the right icon on Tahoe. Using NSImageNameApplicationIcon should also work when the color style of the icon changes in System Settings.
2025-07-12 11:17:51 -07:00
jj 21e34394d0 Add support for relative urls for delta updates (#2741) 2025-07-12 11:13:46 -07:00
Zorg e67dcb0fd2 Bump CI runners to Xcode 16.4 & Xcode 26.0 beta (#2733) 2025-06-19 10:13:00 -07:00
Zorg 5f9ee13796 Synchronize updater settings with user defaults (#2728) 2025-06-16 20:45:31 -07:00
Sparkle-Bot eadcc179d0 Update Package management files for version 2.7.1 2025-06-15 21:30:54 -07:00
Zorg f3dc1a4b9c Update changelog for 2.7.1 2025-06-15 21:30:45 -07:00
Zorg 4274e096fe Fix release notes constraints when compiled with macOS 26 SDK (#2730)
Remove trailing constraint from automatically download & install updates checkbox. This caused an issue that prevented the window from being resized smaller (so the window could only grow bigger).

Remove redundant >= width constraint on Remind Me Later button since Install Update button already had such a constraint.
2025-06-12 21:24:27 -07:00
Zorg 341c8b2c17 Fix reserved identifier warnings for static functions in Xcode 26 (#2729) 2025-06-12 21:09:00 -07:00
Zorg 8e30a08291 Avoid using set-output in GitHub Actions (#2399) 2025-05-01 09:42:57 -04:00
Zorg fea50c33c8 Add private module map (#2722)
Require importing explicit submodules for private functionality.
2025-04-30 21:30:59 -04:00
Daniel Jalkut afc4179c0d Rework the logic for avoiding re-sending the system profile more frequently than once a week (#2720)
So that it will not use a potentially problematic binary compare operation.

Fixes #278.
2025-04-28 20:40:08 -04:00
Zorg f3cd2b9ff9 Make -[SPUUserDriver showUpdateInFocus] optional (#2717)
When this method is not implemented, the updater assumes already presented updates cannot be brought in utmost focus.
2025-04-12 13:25:23 -07:00
Zorg 3b39b400e1 Set STRINGS_FILE_OUTPUT_ENCODING = binary in xcconfig (#2716) 2025-04-01 21:05:43 -07:00
Nicolas Kick 1dec7ddce9 Set STRINGS_FILE_OUTPUT_ENCODING build setting to "binary" (#2712) 2025-04-01 20:24:38 -07:00
Zorg 3e3d573d08 Fix compiler warnings for Xcode 16.3 (#2709)
Also silence project upgrade warnings.
2025-03-23 07:26:30 -07:00
Zorg 057702e757 Fix Sparkle not building when SPARKLE_COPY_LOCALIZATIONS=0 (#2707) 2025-03-22 13:41:57 -07:00
Will Fairclough 997778dd2d Improves bsdiff performance by preventing excessive iterations when processing similar data blocks (#2693)
* Port bsdiff optimizations for diffing large blocks that only differ by less than 8 bytes

* Retrigger CI

* Bump the minor version for major 2, 3, and 4

* Comments for ChromiumOS ported commits
2025-03-10 21:22:26 -07:00
Sjur N Moshagen 16819179a0 Typo in NN localisation (#2694) 2025-03-10 21:10:13 -07:00
Sparkle-Bot 0ca3004e98 Update Package management files for version 2.7.0 2025-02-02 22:21:32 +00:00
Zorg edacb83e50 Update CHANGELOG for recent 2.7 changes 2025-02-03 06:46:01 +09:00
Zorg 62a1908333 Remove SPARKLE_BUILD_DMG_SUPPORT option (#2690) 2025-01-20 20:53:35 -08:00
Zorg 19ff91d93d Process recovery suggestion from Sparkle update error messages in UI alert (#2689)
Also update read-only mount localization string to remove extraneous comma
2025-01-20 20:46:12 -08:00
Zorg 587aa028e6 Upload temporary sparkle_dist tarball instead of sparkle-dist (#2681)
The release workflow on GitHub uploads files that match "Sparkle-*" which apparently now includes sparkle-dist.tar.xz even though it's not capitalized. Rename the file to sparkle_dist to work around this.
2024-12-27 10:46:29 -08:00
Sparkle-Bot f9a3d95ce0 Update Package management files for version 2.7.0-beta.1 2024-12-27 15:56:11 +00:00
Zorg 4ad4255672 Specify macOS requirement for aar files 2024-12-27 07:50:22 -08:00
Zorg 92c78f3c27 Update CHANGELOG for 2.7.0 2024-12-25 08:21:15 -08:00
Zorg 73695f6913 Clarify that default channel must be in allowed channels set (#2676) 2024-12-08 20:56:31 -08:00
Zorg e13e63c85e Improve unable decode private key error messages (#2675) 2024-12-08 17:47:08 -08:00
Zorg 9902f2fb05 Use default NSURLRequest timeoutInterval (currently 60s) (#2673) 2024-12-08 17:24:39 -08:00
Zorg 1ca60d5ab6 Add option to verify updates before extraction (#2667)
Adds an opt-in option (SUVerifyUpdateBeforeExtraction) to enforce verifying updates before extracting them for stronger security. EdDSA signing is required to use this option. As fallback in case EdDSA keys are lost, disk image archives's code signatures are validated assuming it's Developer ID signed. Key rotation is still possible.

Apple Archives (aar, yaa) now require using this option.
2024-12-08 16:31:26 -08:00
Zorg 597825d111 Make binary delta version 4 the default (#2668) 2024-12-07 14:46:23 -08:00
Zorg 2c95fa406a Bump CI runner to Xcode 16.1 / macOS 15 (#2659) 2024-11-10 21:49:47 -08:00
Zorg 8fcdac1e6c Avoid assert/crash when app is moved before update alert shows (#2658)
Note this puts Sparkle and possibly the rest of the app running in an unsupported state even a crash doesn't occur when showing an update alert.
2024-11-10 19:43:32 -08:00
Zorg d04faabe7d Don't allow removal of signing keys more strictly (#2647)
* Don't allow removal of (Ed)DSA keys for pre-validated updates (delta updates, .aar updates)
* Don't allow removal of code signing identity in new update (at minimum, an adhoc signature can be used)
2024-10-20 18:14:05 -07:00
fujisoft ebf75782f8 Fix typo in LICENSE (#2648) 2024-10-19 21:17:20 -07:00
Zorg 14ba9efc51 Use crc32 hashes for binary delta version 4 (#2638)
This is more efficient than SHA1.
2024-10-13 16:58:54 -07:00
Zorg f3dc125d8c Skip preflight update check in sparkle-cli if user is root (#2645) 2024-10-12 16:41:36 -07:00
Zorg 544c642483 Deprecate custom version comparators (#2639) 2024-10-06 21:30:07 -07:00
Eitot ad3c8b5dc7 Fix typo in Dutch localisation (#2642) 2024-10-06 21:12:03 -07:00
Zorg ef9bc6ef58 Fix CI by using Xcode 16 instead of 16.1 betas 2024-09-29 18:31:59 -07:00
Zorg 6848a88abc Preserve bundle creation date when creating and applying delta updates (#2583)
This will preserve the file creation date of the new app bundle, but not the file creation date of any of the files inside the new app bundle because tracking those changes is complex/undesirable.

This bumps the major binary delta version to 4. A new test has been added for testing that the new bundle creation date is also preserved.
2024-09-29 18:25:38 -07:00
Zorg 8de8db001e Fix shared classes being defined both in unit tests and Sparkle (#2629)
For the unit tests, we will rename the classes so they don't conflict.
2024-09-16 17:03:59 -07:00
Zorg 8f8842214b Update CI to Xcode 15.4 and Xcode 16.1 beta (#2628) 2024-09-15 07:20:24 -07:00
Zorg 661540d088 Improve robustness around dmg passwords (#2627)
* Handle failing to extract password protected disk images even when a decryption password isn't provided.
* Propagate error with more information when hdiutil attach fails.
* Wait for detaching disk images for unit tests (fixes not being able to run tests repeatably).
2024-09-15 06:58:00 -07:00
Zorg a5c26b5cdf Call update permission prompt delegate method only when needed (#2622)
The delegate method is not called if SUEnableAutomaticChecks is specified in the Info.plist (now) or if the user has responded to a permission prompt request.

Also fixes a respondsToSelector check in legacy SUUpdater adaptor (fixes #2618).
2024-09-08 17:21:36 -07:00
Zorg 8f86cad4a2 Retry extracting zip file without piping if extraction fails (#2616)
This is to workaround a bug in ditto prior to macOS 15.
2024-09-02 17:21:50 -07:00
Zorg 8bc4976a2c Use FileHandle for reading base64 secret key from file (#2615)
Fixes process substitution failing to work for providing the private key as file argument (#2605).
2024-08-30 17:48:59 -07:00
Zorg ed987512f6 Make horizontal hugging priority required for status text field (#2614) 2024-08-26 10:32:01 -07:00
Zorg 04ad482d59 Update softprops/action-gh-release to version 2 (#2574) 2024-08-18 16:30:29 -07:00
Zorg fa4eaa977c Merge branch '2.6.x' into 2.x 2024-06-30 16:41:35 -07:00
Zorg e9726ff718 Update change log for 2.6.4 2024-06-30 16:40:08 -07:00
Sparkle-Bot 0ef1ee0220 Update Package management files for version 2.6.4 2024-06-29 23:44:15 +00:00
Zorg 6aa15e9933 Update change log for 2.6.4 2024-06-29 16:36:13 -07:00
Zorg b8986f608a Skip safe atomic swap if update has custom update security policy (#2593)
Also emit a warning when checking if the updater is configured correctly.
2024-06-29 16:34:28 -07:00
Zorg a4badefff2 Skip safe atomic swap if update has custom update security policy (#2593)
Also emit a warning when checking if the updater is configured correctly.
2024-06-29 15:15:30 -07:00
1024jp 3a9734538a Add unlocalized strings in Japanese (#2589) 2024-06-22 07:33:08 -07:00
Zorg 1b6565ded5 Require signing validation for apple archives before extraction (#2588) 2024-06-19 23:14:04 -07:00
Zorg dd9374356b Add support for extracting Apple Archives (.aar files) (#2586)
Check `man aa` and https://developer.apple.com/documentation/applearchive for more details. This is an efficient Apple custom archive format available since versions of macOS 10.15.

In macOS 10.15, this utility used to be called yaa.
2024-06-18 20:18:11 -07:00
Eitot 97a8f5a6ba Add baseline alignment to SUStatus dialog (#2587) 2024-06-16 18:46:48 -07:00
Eitot 3f93bf0150 Update localisations for Dutch and German (#2582)
Also insert missing base-localization strings into Sparkle.strings
2024-06-16 18:37:11 -07:00
Zorg 007e9aee61 Randomize the download archive name the installer extracts/executes (#2584) 2024-06-15 18:13:36 -07:00
Zorg 37d1fee019 Update he Sparkle.strings for system profile info (#2579)
Thanks to Shlomo for this update.
2024-06-12 21:04:42 -07:00
Zorg 2a48c17b03 Internationalize system profile display keys (#2577) 2024-06-07 17:14:50 -04:00
Shlomo cd6c61d47f fix: add RLM chars to he locale (#2575) (#2576) 2024-06-04 22:13:54 -07:00
Shlomo 3c180effcb Update he locale (#2573) 2024-06-03 18:43:29 -07:00
Zorg 0ad8d83066 Merge branch '2.6.x' into 2.x 2024-06-02 21:00:49 -07:00
Sparkle-Bot b456fd4049 Update Package management files for version 2.6.3 2024-06-03 01:43:04 +00:00
Zorg 5af89de393 Update changelog for 2.6.3 2024-06-02 18:35:41 -07:00
Zorg 3a87581af2 Update changelog for 2.6.3 2024-06-02 18:33:49 -07:00
Zorg 6e2366255b Add unarchiving test for regular encrypted disk image (#2571) 2024-05-27 14:10:28 -07:00
Zorg c648665724 Remove SUFileManager from BinaryDelta and Sparkle Test App (#2570) 2024-05-27 13:31:39 -07:00
Zorg 27cf3b3650 Skip extracting auxiliary files and improve extraction progress for disk images (#2569) 2024-05-27 13:30:55 -07:00
Zorg 444a537365 Remove old checksum verification checks for dmg archives (#2568)
These are antiquated checks and they can take considerable time to perform. HTTPS or EdDSA verification will validate that an archive isn't corrupt.
2024-05-25 15:32:14 -07:00
Daniel Jalkut 61054c7a9a Adjust the layout of anonymous system profile info to align better with the rest of the panel's UI. (#2564) 2024-05-20 20:05:55 -07:00
Zorg 2247105ff3 Ignore crashes due to SIGPIPE in generate_appcast (#2563) 2024-05-19 20:52:07 -07:00
Zorg f904466d35 Remove extra writeData: call when unarchiving disk images (#2562) 2024-05-19 20:51:35 -07:00
Zorg 9d6e8c24b5 Merge CHANGELOG changes from 1.x 2024-05-12 21:23:58 -07:00
Zorg dd76d0063d Update Carthage package to include 1.27.3 2024-05-12 17:05:29 -07:00
Zorg be8247efbd Guard update timer update check against sessionInProgress (#2561)
Make sure we don't perform a background update check when a user update check was initiated. This may have regressed from #2295.

Also replaces an assert with an error log if the _driver already exists.

Fixes #2560
2024-05-12 14:45:22 -07:00
Sparkle-Bot 41847a58cd Update Package management files for version 2.6.2 2024-05-06 04:25:08 +00:00
Zorg f948fafe16 Update CHANGELOG for 2.6.2 2024-05-05 21:18:17 -07:00
Zorg 946c583910 Create and use temp extraction directory in generate_appcast again (#2555)
This restores how the code used to work in 2.6.0 except we don't create a link to the archive file, and remove the temp directory before starting. I had removed too much of the prior code in 2.6.1 which included creating the extraction directory in generate_appcast.
2024-05-04 06:21:49 +02:00
Zorg 026cf54a76 Add 1.27.2 to Carthage file 2024-05-03 08:06:35 +02:00
Sparkle-Bot b328c499a3 Update Package management files for version 2.6.1 2024-05-02 15:22:43 +00:00
Zorg 00e6259c9d Update CHANGELOG for 2.6.1 2024-05-02 17:15:18 +02:00
Zorg 31b462f860 Extract archives in a separate directory from the input archive (#2550) 2024-04-30 21:24:43 +02:00
Zorg 5264c01d37 Remove assert on download response being available (#2547) 2024-04-25 20:01:14 -07:00
Zorg 0cff81740f Fix the WebKit view not transitioning from light to dark mode (#2542)
adaptReleaseNotesAppearance was over-engineered to update the transparent background state of the web view (which was causing the issue) and the background NSBox view when the system changes to dark or light mode. This is because when dark mode support was originally written, it used to use a stylesheet that was only specific to dark aqua. However this code has changed some time ago to use a universal stylesheet for both light/dark mode.

So now when the WebKit view is created, we just opt into a transparent background and set up a background NSBox view once and don't do anything when the effectiveAppearance of the views change. This fixes visual issues on current and older OS systems when changing system appearance.
2024-04-21 15:58:37 -07:00
Viktor Szépe e9989a8ae7 Fix typos (#2537) 2024-04-13 16:12:23 -07:00
Zorg 2e1bdb98f1 Update upload-artifact version to v4 (#2536) 2024-03-31 20:26:04 -07:00
Zorg d30adc8407 Create tar.xz files with built-in tar and remove bzip2 fallback (#2535) 2024-03-31 16:41:50 -07:00
Zorg 0183bf2b3f Clarify authorization prompt can show after starting extraction (#2534) 2024-03-29 11:02:35 -07:00
Zorg 2b7615fe5b Fallback in case SULocalizedStringFromTableInBundle() fails (#2533)
SULocalizedStringFromTableInBundle() should only fail in the abnormal situation where the app bundle may have been moved while it was running. Technically the app is running in an unsupported state but I suppose we can guard against it here.
2024-03-28 18:52:28 -07:00
Zorg 9aece0259c Add NN (Norwegian Nynorsk) locale (#2532) 2024-03-28 18:51:35 -07:00
Zorg 8c7476f93d Document user driver interaction with authorization (#2531) 2024-03-27 19:20:43 -07:00
Sparkle-Bot 0a4caaf7a8 Update Package management files for version 2.6.0 2024-03-15 18:08:43 +00:00
Sparkle-Bot a603047fd5 Update Package management files for version 2.6.0-beta.2 2024-03-04 02:40:08 +00:00
Zorg 2bd33682d1 Update CHANGELOG 2024-03-03 18:34:12 -08:00
Zorg dfab64efdf Remove installer status & connection entitlement files (#2517)
These entitlements are not easy to configure properly and most developers should not be using these services.

Also simplify how to opt into enabling sandboxing entitlements for the Downloader XPC Service.
2024-03-03 17:41:12 -08:00
Zorg 51ce7108c9 Swap app bundles with APFS atomic swap if team IDs match (#2516) 2024-03-02 17:32:54 -08:00
Sparkle-Bot 56e365d050 Update Package management files for version 2.6.0-beta.1 2024-02-23 05:22:24 +00:00
Zorg c983fa1548 Update CHANGELOG for 2.6 2024-02-22 21:11:53 -08:00
Zorg ef1f03cf1e Disable sandboxing for downloader XPC service by default (#2511) 2024-02-19 18:49:18 -08:00
Zorg 4d164ba4ab Update GitHub actions runners to Xcode 15.2 (#2506) 2024-02-18 12:38:30 -08:00
Zorg 66c198932d Perform Gatekeeper scan to pre-warm app launch (#2505)
This avoids users being a "Verifying..." Dialog when the installed update is (re-)launched.

This scan is only done for macOS 14.4+ onwards (gktool was introduced in macOS 14.0 but had issues).

Also this scan is only done if Autoupdate's team identifier matches the new update's team identifier. Otherwise the OS may think Autoupdate is modifying a bundle which it shouldn't be permitted to (this is a bug).
2024-02-18 12:37:58 -08:00
CheolHyun Mun 24f0f3952d Update Korean localization (#2504) 2024-02-16 22:03:03 -08:00
Zorg 7e5ebca735 Mention only 10.13 minimum macOS requirement
The last couple years of Xcode releases don't support anything less than 10.13 deployment target.
2024-01-13 08:00:01 -08:00
Zorg 001d6d6a69 Use $PROJECT_DIR instead of $SRCROOT (#2489) 2024-01-13 07:59:15 -08:00
Zorg 9e9830eb0f Update CI runners to use Xcode 15.1 (#2484) 2023-12-28 15:17:11 -05:00
Zorg 615043da2b Audit minimum supported system version in Swift Package.swift (#2483)
Also add Package.swift to the Xcode project so its contents are searchable.
2023-12-28 14:41:08 -05:00
Eitot 485f0e661d Set minimum deployment to macOS 10.13 in Package.swift (#2481) 2023-12-27 14:31:01 -05:00
Zorg f1daff840f Merge branch '2.5.2-dev' into 2.x 2023-12-21 09:29:52 -08:00
Sparkle-Bot 47d3d90aee Update Package management files for version 2.5.2 2023-12-20 04:08:02 +00:00
Zorg 9a29d14b7b Update CHANGELOG for 2.5.2 2023-12-19 19:58:50 -08:00
Zorg 7a7fb9ecd9 Don't clean up update directory when Autoupdate receives SIGTERM (#2479)
Under rare circumstances, if Autoupdate receives SIGTERM while the installer queue is installing an update this could cause potential corruption.
2023-12-19 19:56:25 -08:00
1024jp 4ad2b0d945 Update Japanese localization (#2285) (#2475) 2023-12-19 19:56:06 -08:00
Emir SARI 2afa08405c Improve Turkish translations (#2464)
Updates the strings to be more in-line with the Apple terminology, and
capitalisation. Ambiguities have been found and fixed as well.
2023-12-19 19:55:43 -08:00
Billy Gray ed1bc2fdc8 Update Spanish translation for 'You are currently running version %@.' and 'Version History'. (#2463) 2023-12-19 19:55:17 -08:00
Zorg b84c1b14ce Don't clean up update directory when Autoupdate receives SIGTERM (#2479)
Under rare circumstances, if Autoupdate receives SIGTERM while the installer queue is installing an update this could cause potential corruption.
2023-12-19 19:49:36 -08:00
1024jp 0a92e049eb Update Japanese localization (#2285) (#2475) 2023-12-02 06:57:15 -08:00
Zorg 1a0b023e1c Store private seed as the secret for newly generated keys (#2472)
This improves compatibility when using the seed onto other cryptography libraries.
2023-11-23 09:23:10 -05:00
Zorg 1e419c8c16 Improve signing error message to developers (#2471)
If we detect the wrong archive is being served (i.e, expected content length differs from archive length) we log this out to developers. If the app version in the archive (if available) also differs, we report this discrepancy as well. If the update archive looks the same but signing validation fails, we tell the developer the update may have not been signed correctly.

I'm not changing the generic error that is reported to users about the update being improperly signed (that would involve propagating this information there and updating bunch of localizations). The extra info is more for the developer than it is for the user.

Fixes #2468
2023-11-18 16:04:44 -08:00
Emir SARI ac6c897dd5 Improve Turkish translations (#2464)
Updates the strings to be more in-line with the Apple terminology, and
capitalisation. Ambiguities have been found and fixed as well.
2023-11-10 05:32:09 -08:00
Billy Gray 5a708be2a5 Update Spanish translation for 'You are currently running version %@.' and 'Version History'. (#2463) 2023-10-31 17:54:14 -07:00
Zorg 82209831c0 Update GitHub checkout action for create-draft-release (#2457) 2023-10-16 21:14:57 -07:00
Zorg 70a9ad52ae Fix false positive analyzer warning about resumableUpdate type (#2454) 2023-10-16 20:31:32 -07:00
Jozef Izso a00fd1d323 Update GHA libraries to use modern NodeJS runtime (#2451)
* Update `actions/checkout` and `actions/upload-artifact`

This removes the warning about the deprecated `node12` runtime used by existing actions.

* Update `mshick/add-pr-comment`

The v2 action uses `node16` runtime
Workflow will use the `GITHUB_TOKEN` with `pull-requests: write` permission instead of PAT
2023-10-15 20:19:37 -07:00
Sparkle-Bot 1f07f4096e Update Package management files for version 2.5.1 2023-10-15 23:57:08 +00:00
Zorg 679d3568c2 Update CHANGELOG for 2.5.1 2023-10-15 16:37:29 -07:00
Zorg bd90fb7b18 Filter for archive files in generate_appcast more intelligently (#2448) 2023-10-08 09:38:50 -07:00
floorish 9684a433ee Use correct entitlements and dsym files when using custom bundle id and XPC names in ConfigCommon (#2446) 2023-09-30 10:39:16 -07:00
Zorg ff4d4f53a8 Bring back specifying version in issue template 2023-09-30 08:13:44 -07:00
Zorg 469f423e28 Fix test cases for localized release notes (#2444) 2023-09-28 22:52:32 -07:00
Zorg 846838c90b Update issue templates (#2443) 2023-09-28 21:06:23 -07:00
Zorg f6a86f52b3 Default to English for XML nodes when no xml:lang is present (#2440)
This only applies when multiple XML nodes are present with the same name. E.g. multiple description or releaseNoteLink elements with different xml:lang's specified.

Also generate a warning if an language has to be interpreted implicitly when there is no xml:lang explicitly specified and there are multiple node items.
2023-09-28 20:02:29 -07:00
Sparkle-Bot f0ceaf5cc9 Update Package management files for version 2.5.0 2023-09-15 23:55:58 +00:00
Zorg 569f69b463 Update CHANGELOG 2023-09-15 16:48:38 -07:00
Zorg 7cc751ff4f Fail gracefully when auxiliary tool cannot be located (#2436) 2023-09-06 21:05:59 -07:00
Sparkle-Bot d005af3e03 Update Package management files for version 2.5.0-beta.2 2023-09-02 18:55:48 +00:00
Zorg 4cdfffa8e9 Update CHANGELOG 2023-09-02 11:49:30 -07:00
Zorg 0e865f07c5 Fix Updater.app not starting when running Sparkle as root on Sonoma (#2432)
This may occur for example when you run sparkle-cli as root or use Sparkle.framework in a root process. This is not typically a common use case, but could be used from daemons.

The issue is that Sonoma doesn't like starting our Updater app in the user domain when intermediate directories containing it are root owned (due to lack of file permission access that wasn't present in Ventura). So now we try to create intermediate directories in the standard user's home directory.
2023-09-02 10:01:23 -07:00
Zorg a6e22a0667 Fix make release not building distribution successfully (#2430)
For some reason, the default BUILDDIR that was set was problematic. We are now defaulting BUILDDIR inside of ./build which resolves this issue. This also means by default, builds are not placed inside of system temp directories anymore.

I do not know when this stopped working or why.
2023-08-28 21:54:48 -07:00
Zorg 8125490931 Pre-warm installs before relaunch (#2421)
Move a lot of the installation work to be done during the first phase of installation (when possible), before the target app needs to be terminated. For the common case where the old and new bundles are on the same volume, the final phase of installation requiring a restart is now just an atomic swap.

Also move the termination listener to the agent app which resolves some launch/CI failures we've been seeing.
2023-08-27 22:22:52 -07:00
Zorg 4abbb2b4f1 Update CHANGELOG 2023-08-22 19:52:44 -07:00
Zorg 28e85abe88 Remove hyphenation in "You're up to date" message (#2425) 2023-08-22 19:49:48 -07:00
Zorg 5675086860 Update CHANGELOG 2023-08-12 18:19:10 -07:00
Zorg e59cf0e101 Improve permission prompt layout spacing (#2420) 2023-08-12 18:17:11 -07:00
Sparkle-Bot b5a9c0a1f1 Update Package management files for version 2.5.0-beta.1 2023-07-31 03:02:43 +00:00
Zorg 57c3732f7d Update CHANGELOG for 2.5 2023-07-30 19:50:37 -07:00
Zorg 0155c78a99 Ignore file URL scheme in custom allowed URL schemes (#2410) 2023-07-29 22:55:44 -07:00
Zorg d41b8652ee Adopt new app activation APIs in macOS Sonoma (#2409) 2023-07-29 21:21:31 -07:00
Zorg 821b0ff37f Improve error for xattr code signing for delta updates (#2408) 2023-07-23 16:47:49 -07:00
Zorg c9c08b7f42 Report an error when detecting duplicate updates in generate_appcast (#2407) 2023-07-22 16:25:38 -07:00
Nathan Manceaux-Panot 7c8fe1d427 Expose installed version string to update notes HTML page (#2373) 2023-07-11 22:07:42 -07:00
Zorg 5528d7f9ec Fix KVO usage for updaterController.updater.* (#2404)
KVO was not set up properly when trying to retrieve the updater from the updater controller, especially when the updater controller hasn't been fully initialized yet.
2023-07-04 07:29:57 -07:00
Zorg 419552a7d3 Upgrade Xcode in CI setup (#2397) 2023-06-24 16:24:51 -07:00
Eitot c23d74d8e0 Replace CFUUID* with NSUUID (#2395)
This resolves a nullability warning by the static analyzer.
2023-06-23 22:23:37 -07:00
Zorg 456a3d4275 Allow developer to use custom URL schemes in release notes view (#2393) 2023-06-19 20:27:18 -07:00
Sparkle-Bot 87e4fcbac3 Update Package management files for version 2.4.2 2023-06-18 00:17:52 +00:00
Zorg 2af0fa916c Update CHANGELOG for 2.4.2 2023-06-17 17:07:28 -07:00
Zorg 8039288f64 Harden verification of Sparkle update download (#2392) 2023-06-17 17:01:45 -07:00
Zorg 4ca2e2eb21 Fix NSKeyedUnarchiver warning for not specifying keyed NSString class (#2383) 2023-06-11 07:04:03 -07:00
Zorg f7567e5a69 Ignore release notes download when we shouldn't show release notes (#2381) 2023-05-27 09:18:17 -04:00
Sparkle-Bot 7907f058bc Update Package management files for version 2.4.1 2023-04-13 05:37:26 +00:00
Zorg 4a322e0ab4 Update CHANGELOG 2023-04-12 22:28:29 -07:00
Zorg 270582b2e7 Pass bookmark data for the downloaded update (#2359)
Also let Xcode 14.3 update the nibs.
2023-04-12 22:23:50 -07:00
Sparkle-Bot 91a2c1c100 Update Package management files for version 2.4.1-beta.1 2023-04-07 18:35:57 +00:00
Zorg 53d58921ef Update changelog for 2.4.1 2023-04-07 11:28:04 -07:00
Zorg e15324773f Remove auxiliary apps and relocate symbols in SPM package (#2356) 2023-04-07 11:23:23 -07:00
Zorg b7b858dbf3 Fix compile error when SPARKLE_EMBED_DOWNLOADER_XPC_SERVICE=0 (#2346) 2023-03-25 21:39:55 -07:00
Kent Sutherland 8e2107a57d Add -Wno-declaration-after-statement to silence warnings that only apply to pre-C99 (#2345) 2023-03-22 20:03:17 -07:00
Sparkle-Bot 631846cc82 Update Package management files for version 2.4.0 2023-03-19 14:48:24 +00:00
Zorg 3a99b31f37 Add plain-text embedded release notes support for sparkle-cli (#2344) 2023-03-18 22:20:30 -07:00
Zorg 151c256721 Update changelog for adding plain text release notes view 2023-03-18 21:30:42 -07:00
Zorg 82b94a131d Fix name reference in changelog 2023-03-18 21:14:34 -07:00
Sparkle-Bot 4ac6ea827a Update Package management files for version 2.4.0-beta.2 2023-03-13 03:05:11 +00:00
Zorg b5199e7a05 Update changelog for Sparkle 2.4 again 2023-03-12 19:53:37 -07:00
Zorg 39495fd562 Remove redundant codesign check (#2341) 2023-03-12 19:44:50 -07:00
Zorg 60568b82ba Don't allow DSA-only updates to pass if DSA is disabled (#2340) 2023-03-12 07:59:03 -07:00
Zorg 9ab2c0d58c Hide impractical compression options only useful for debugging (#2335) 2023-03-04 18:03:45 -08:00
Zorg 665bba36cc Fix documentation formatting (#2334) 2023-03-04 16:02:03 -08:00
Sparkle-Bot 1e8308116e Update Package management files for version 2.4.0-beta.1 2023-03-04 06:29:02 +00:00
Zorg 245c6821aa Update changelog for 2.4 2023-03-03 22:14:05 -08:00
Zorg ad936155fa Upgrade CI to use Xcode 14.2 (#2333) 2023-03-03 21:46:24 -08:00
Zorg d220346206 Trigger new update check in resetUpdateCycle if feed/channels changed (#2324) 2023-03-03 21:04:07 -08:00
Daniel Jalkut 95f8e7e0cf Turn off CLANG_MODULES_AUTOLINK for XPC services, to avoid Xcode inferring that they depend upon Sparkle.framework. This seems to resolve a pesky, recurring issue in which Xcode reports dependency cycles between the XPC services, Sparkle, and/or the host apps that embed Sparkle. (#2332) 2023-03-02 23:31:11 -08:00
Zorg 362f50a8a1 Exit with an error if generate_appcast cannot sign an update (#2322) 2023-02-25 13:18:03 -08:00
Zorg 87697ce10f Update SUVersionDisplay to allow including build versions and update information (#2321) 2023-02-25 08:15:02 -08:00
Sparkle-Bot da75bb432e Update Package management files for version 2.3.2 2023-02-12 15:15:22 -08:00
Zorg fde8f0a35e Update CHANGELOG for 2.3.2 2023-02-12 15:14:20 -08:00
Zorg 06edf5695d Remove unnecessary min macro checks (#2318)
Minimum OS preprocessor checks should only be used when compiler may generate compile warnings for deprecated APIs when the deployment target is raised.
2023-02-11 22:24:56 -08:00
Zorg ffc203b89a Add support for plain text release notes view (#2315)
This also allows embedded release notes to be plain text using sparkle:format="plain-text" attribute.

Also, Catalyst apps only support plain text release notes (compared to before where release notes weren't supported for Catalyst apps).
2023-02-11 19:34:26 -08:00
Zorg 348c3a9658 Don't construct appcast item if enclosure URL is invalid (#2317) 2023-02-07 20:12:07 -08:00
Lauri-Matti Parppei 077d7228ba Finnish localization grammar fixes (#2311) 2023-01-12 22:34:40 -08:00
Zorg be7f6952c2 Reduce code size and make codebase more consistent (#2305) 2022-12-27 12:03:03 -08:00
Zorg 91b8f4eaa0 Add delegate method to hide showing version history option (#2303) 2022-12-23 07:17:44 -08:00
Sparkle-Bot cc90026ade Update Package management files for version 2.3.1 2022-12-22 21:44:04 -08:00
Zorg 68d539ce83 Update CHANGELOG for 2.3.1 2022-12-22 21:42:51 -08:00
Zorg 8154b1eab3 Add deprecations/warnings for incorrect feed & update checking usage (#2295)
* Add deprecations/warnings for incorrect feed & update checking usage

This change deprecates -[SPUUpdater setFeedURL:] and logs warnings when the updater detects that feed URLs from user defaults are still being used.

This change also logs a warning when checkForUpdatesInBackground is used incorrectly if Sparkle is configured to ask the user's permission to check for updates but a check is done when automatic update checking is NO.
2022-12-19 20:34:20 -08:00
Zorg 14e4a98b69 Log the URL that failed to download correctly (#2296) 2022-12-03 23:30:44 -08:00
Zorg f36c34f2f4 Remove duplicate Sparkle localization strings in Updater app (#2288) 2022-12-02 23:01:01 -08:00
Zorg bdc095bf3a Ask permission for automatically downloading and installing new updates (#2285) 2022-12-02 22:29:17 -08:00
Zorg 8cd13b0cfd Upgrade CI to default to using Xcode 14.1 (#2287) 2022-11-27 12:48:48 -08:00
Zorg 89e2f94872 Enable deployment post processing for Release configurations (#2286) 2022-11-27 12:48:20 -08:00
Zorg a6536ea8f1 Fix update permission alert title text overlapping with question text (#2284)
This change adjusts the layout constraints between the title and message text to be more proper.

This issue is only noticeable in Russian, Spanish, Ukrainian, and Slovenian on my machine.

Issue has been present in Sparkle 1 as well.
2022-11-27 05:36:22 -08:00
Sam df313f7f59 Update Czech translation (#2275) 2022-10-29 16:22:32 -07:00
Zorg f06ccf2711 Update ReadMe with rationale for building Sparkle 2022-10-21 09:30:18 +02:00
Bing Zheung ef9398ab32 Add zh_HK (Chinese, Hong Kong) localization (#2273) 2022-10-08 11:28:53 -07:00
Zorg 8ac92e3ffa Bump development version 2022-10-08 11:28:18 -07:00
Sparkle-Bot 2a98381dfe Update Package management files for version 2.3.0 2022-10-01 16:01:44 +00:00
Zorg 9b4c91bc58 Update CHANGELOG 2022-10-01 08:27:56 -07:00
Zorg a7855eabe6 Update secondary CI runner from Xcode 14.0 -> 14.1 beta (#2272) 2022-09-24 10:32:56 -07:00
Chiahong f86907c13c Update zh_TW localization (#2271) 2022-09-23 22:31:07 -07:00
Sparkle-Bot 028e4c2bec Update Package management files for version 2.3.0-beta.2 2022-09-19 05:53:23 +00:00
Zorg 891cd38eba Update CHANGELOG for 2.3.0-beta.2 2022-09-18 22:44:16 -07:00
Zorg a208bd5cf9 Add -p option to sign_update to only print the signed signature (#2268) 2022-09-18 07:18:39 -07:00
Zorg 005392963f Allow developer to always force allowing automatic updates (#2266)
By default, if the SUAllowsAutomaticUpdates Info.plist key is not specified, the update alert option to allow automatic downloading/installing of updates will only be shown if automatic checking of updates is enabled. However, the developer can now override this by setting SUAllowsAutomaticUpdates to true in Info.plist which indicates the option should be available even if automatic checking of updates is not enabled.
2022-09-16 20:41:08 -07:00
Sparkle-Bot 83cc66b988 Update Package management files for version 2.3.0-beta.1 2022-09-06 02:35:22 +00:00
Zorg a93317fb08 Update CHANGELOG for 2.3 2022-09-05 19:27:15 -07:00
Zorg 1b1a7db1ac Expose maximum-versions option to preserve in feed per branch (#2259) 2022-09-05 16:20:35 -07:00
Zorg d9c0cc7f53 Add delegate method for when user makes an update choice (#2257)
Also add gentle reminder support in legacy SUUpdater 1.x methods
2022-09-04 15:58:09 -07:00
Zorg 7d68f8f7ae Improve clarification on documentation for SPUUpdater properties (#2256) 2022-09-03 14:18:57 -07:00
Zorg 03f2452379 Expose -[SPUStandardUserDriver activeUpdateAlert] as private API (#2255) 2022-09-03 07:25:31 -07:00
Zorg fc8000471b Pick branch runner is running on when drafting releases (#2254) 2022-09-02 13:34:31 -07:00
kakaiikaka 6c0e685063 added zh_CN l10n for "Version History" (#2247) 2022-08-30 22:18:53 -07:00
Sparkle-Bot c7c8b719cb Update Package management files for version 2.2.2 2022-08-28 23:28:16 -07:00
Zorg 4fa7b23f09 Update CHANGELOG for 2.2.2 2022-08-28 23:26:07 -07:00
Zorg f1fe9e45f6 Revert "Add 2.2.2 to test on CI"
This reverts commit 679cbc8652.
2022-08-28 22:04:05 -07:00
Zorg 679cbc8652 Add 2.2.2 to test on CI 2022-08-28 15:54:09 -07:00
Chiahong 6ef1f7fc7f Update zh_TW localization (#2246) 2022-08-28 15:17:25 -07:00
Zorg 6831a35e28 Update Package.resolved (#2245) 2022-08-27 17:26:35 -07:00
Zorg 1c560652e7 Remove ed25519 git submodule (#2244)
Also allow release scripts to work without git repository and bump the Sparkle versions.
2022-08-27 10:46:29 -07:00
Eitot 863f85b5f5 Clean up left-over code (#2243) 2022-08-27 06:17:28 -07:00
Zorg f46ea87380 Ensure install handlers are invoked on main queue (#2235) 2022-08-22 18:23:23 -07:00
Zorg f5d4ad52ca Allow user to re-try installing/relaunching application (#2234)
If the app termination request is delayed or canceled, the user can check for updates again with the standard user driver and try installing/relaunching again, which will trigger the installer to send another quit event to the running application.

Before the install/relaunch window would close but the check for updates option would still be present but not functional.
2022-08-21 08:54:03 -07:00
Zorg 926c47d48e Find potential matching translocated running apps in updater agent (#2233)
In the installer progress agent, when we find all potential running applications for a host bundle, we should also consider any translocated running apps that look-alike the host bundle.

This matters when updating external bundles. For example if sparkle-cli tries to update an app on disk in ~/Downloads/ but a running instance of the app is translocated, sparkle-cli should terminate the translocated instance of the app before installing the update.

It's possible this could generate a false positive but we err on the side of safety here. We only use running translocated apps if we find no regular matching apps.
2022-08-20 10:30:00 -07:00
Zorg fbfcec3453 Fix recently introduced bugs in generate_appcast with multiple feeds (#2232)
We fix the validation check for using the output option when multiple feeds are present, fix not generating new feeds when no prior feed is available, and fix incorrect logic with cleaning up delta files when multiple feeds are present.
2022-08-19 21:36:50 -07:00
Zorg 8f77f066c1 Add delta update attributes for validating an app hasn't been stripped (#2231) 2022-08-19 20:48:52 -07:00
Zorg 47f335614a Wait for a threshold amount of time before replying with status info data (#2230)
This also reverts 6a69f26dcc and 4cb6719c6b
2022-08-19 10:40:25 -07:00
Zorg 80a5b80ade Move old updates to old_updates in generate_appcast (#2228)
Document --versions in generate_appcast better and add comments to explain why certain policies were made.

Add separate option to automatically pruned old update files. Now we only automatically move old update files aside. If the user passes --auto-prune-update-files we will also remove the old update files automatically.

Move old release notes files too.

Don't make old-updates directory hidden.
2022-08-14 19:07:48 -07:00
Zorg e81ccbd891 Upgrade Xcode builds in CI to 13.4.1 and 14.0 beta (#2226) 2022-08-12 18:49:40 -07:00
Kent Sutherland dc2e1ff534 Update Portuguese localization (#2224) 2022-08-08 19:24:56 -07:00
Zorg 37ef179284 Prune and preserve necessary updates in generate_appcast (#2218)
We preserve a batch of updates for each branch point (defined by an update's {majorVersion, minSystemVersion, maxSystemVersion, channel}). The latest for each branch point is used for generating delta updates.

We prune older update items that are no longer needed in the feed or needed for generating delta updates from newer items. We move pruned update files into a separate hidden directory, which is later garbage collected after a couple weeks based on each file's last modification date.

To insert new update items that are older than the latest update in the feed, --version flag needs to be used.

The overall goal is to have the feed only keep a small window of updates to serve to the user. This will also ease future processing generate_appcast needs to do and ensure the cache's directory doesn't blow up by pruning old updates.
2022-08-07 19:13:20 -07:00
Zorg 6a69f26dcc Clean up handling appcast item registration message (#2223) 2022-08-07 17:08:33 -07:00
Zorg 4cb6719c6b Critical update alerts may not show up as promptly as they should when automatically installing them (#2221)
Wait for appcast item registration before finishing automatic update driver.

This fixes a potential race issue where sometimes the automatic update driver on completion would sometimes not trigger to prompt an update alert immediately for critical updates. Note in this case, the update would still be installed on app termination and would still be scheduled to alert the user on the regular update check interval, so this issue is not severe.
2022-08-06 11:28:47 -07:00
Zorg 2c81393ec2 Remove module imports from framework headers (#2217)
Framework headers should not be using them. The warning these aim to suppress (-Wauto-import) is also going away.
2022-07-29 22:01:04 -07:00
Zorg 983d19580b Fix handle applying patches when files aren't writeable (#2216) 2022-07-23 10:37:29 -07:00
Zorg 6cbe8444a0 Refine update alert when no release notes are shown (#2206)
* Set layout constraint constant between buttons and description to 20

* Disable update alert resizing when no release notes are available

* Fix layout constraint warning

* Set alert autosave frame name only when release notes are shown
2022-07-17 20:56:17 -07:00
Zorg 45a9099082 Reject DSA only configurations for setting up the updater (#2207)
The one exception is an updater that is targeted to update another / non-main bundle.

Note we still allow configuration of not using DSA or EdDSA with the deprecation warning in tact.
2022-07-17 20:55:31 -07:00
Jie aa72b3f639 Hide automatic install check box when allowsAutomaticUpdates is disabled (#2202) 2022-07-17 16:45:02 -07:00
Zorg 372f0504a5 Bump minimum deployment target to macOS 10.13 (#2196) 2022-07-17 16:43:24 -07:00
Zorg 470296a90e Remove outdated model translation plist (#2195) 2022-07-17 15:57:43 -07:00
Zorg 242ae2c392 Disable implicit dependencies for runnable schemes (#2171)
Also add missing explicit dependencies from targets
2022-07-17 15:52:16 -07:00
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
runner 515b8259bc Update Package.swift and Sparkle.podspec for version 2.0.0-beta.1 2021-08-29 03:37:49 +00:00
Mayur Pawashe edc0fd0e56 Fix issues with GitHub release workflow (#1926) 2021-08-28 18:53:42 -07:00
Mayur Pawashe b4e0dcca6c Bump 2.x project version to 2.0.0-beta.1 (#1924) 2021-08-28 17:27:42 -07:00
Tony Arnold ee679586cf Add a workflow that builds and publishes a release via GitHub Actions (#1908)
The workflow assumes changelog and version information have been updated and the tag has not been created yet before running it. When the workflow finishes, it should take you to a release page with the uploaded binaries, where you can verify the final details and publish a tag officially.

Also the following improvements were made:

* Change CURRENT_PROJECT_VERSION to represent a monotonically increasing bundle version (starting at 2000)
* Add MARKETING_VERSION to represent marketing version of Sparkle, comprised of SPARKLE_VERSION_MAJOR, SPARKLE_VERSION_MINOR, SPARKLE_VERSION_PATCH, and the new SPARKLE_VERSION_SUFFIX for pre-releases.
* Verify code signing signatures of extracted SPM zip file in make release and CI
* Generate changes to Sparkle podspec, just like the Package.swift file, based on current marketing version
* Improve format of Info.plist version strings when appending git hash info, eliminating unnecessary whitespace
* Simplify validating that XPC Service versions align with framework version
* Handle lightweight tags in addition to annotated tags in release-move-tag.sh
2021-08-26 22:42:38 -07:00
Mayur Pawashe c6f1cd4e3c Improve API header docs (#1918)
* Don't expose SPUDownloadData initializer publicly

* Make SUAppcast -init unavailable

* Fix documented default user agent string

* Improve header documentation for SUAppcast(Item) and comparators

* Update more API documentation headers

Also allow returning nil in -allowedSystemProfileKeysForUpdater:

* Clarify documentation on -allowedSystemProfileKeysForUpdater:

* Rename willIdleScheduling -> notSchedule for delegate method

* Make minor correctness fix for reading info URL
2021-08-21 11:24:23 -07:00
Mayur Pawashe 306ea26df8 Don't expose sparkleBundle (#1917) 2021-08-21 11:19:14 -07:00
Mayur Pawashe d719b92636 Remove old DSA generation script (#1922) 2021-08-21 10:01:56 -07:00
Mayur Pawashe b43b188c82 Clear resumable info-only updates when user skips them (#1920) 2021-08-20 21:34:04 -07:00
Mayur Pawashe 6b9981f567 Add generation of API docs (#1915) 2021-08-09 18:27:44 -07:00
Mayur Pawashe 34fcb8784b Support appcast selection features in generate_appcast (#1914)
Add generate_appcast options for appcast selection features

We can now supply for new update items:

* Link
* Channel name
* Last major version / minimum autoupdate version
* Phased rollout interval
* Last critical update version
* Originating informational update versions

We can also specify the maximum number of delta items to generate.

Lastly we can specify which versions to create new items for now. This allows applying flags for only specific versions, or for exceptional cases allows adding old versions that do not meet the most recent updates threshold (maxNewVersionsInFeed) -- think for updates for a prior OS or for a prior major version.

We do not override the minimum system version element on already existing items now, if the element already exists. Apps don't strictly need to specify LSMinimumSystemVersion and this allows users specifying it themselves in the feed.

The help page for generate_appcast was expanded with how the archive directory looks like, how release notes work, that old entries are kept in tact, and how extracted archives are cached..

We now write out the number of new updates written and the number of existing items updated, to make the generated result be less confusing.

Bug fixes:

* The scheme now builds for Debug so I can properly debug generate_appcast from within Xcode (distribution builds are still in Release)
* Newly generated items were appended at the end of the appcast and not necessarily inserted in the correct order (on top). As a workaround when we process existing items, we remove them, and re-add them.
* Fixed an off-by-one error for maximum number of delta files we can generate.

Fixes #1903
2021-08-08 09:07:27 -07:00
Mayur Pawashe 4f7ed347ab Adopt Swift Argument parser for Swift tools (#1913)
Also remove the deprecated usage of passing DSA key as an argument, because it can just be provided as an option (-f)
2021-08-01 08:56:18 -07:00
Zorg 9823892062 Revert modifying Package.swift 2021-07-26 15:58:20 +01:00
Zorg a22562431b Add documentation suggestion if updater fails to start 2021-07-26 15:58:20 +01:00
Zorg 4db96f6c4f Improve error reporting for DSA validation 2021-07-26 15:58:20 +01:00
Zorg 385673ff24 Populate error objects in code signing validation methods 2021-07-26 15:58:20 +01:00
Zorg c3cdbf46cb Don't allow an app to use an invalid EdDSA public key 2021-07-26 15:58:20 +01:00
Zorg 89ab067477 Populate NSError when signature validation or code sign fails 2021-07-26 15:58:20 +01:00
Mayur Pawashe 29a2fa7974 Create valid xar files (#1906)
* Create xar files with valid directory/filename structure

* Don't use file hash for determining if files are equal or not
2021-07-24 09:04:48 -07:00
Mayur PawasheandKornel cb9386a4ea Ignore symlink permissions in binary deltas (#1905)
Co-authored-by: Kornel <kornel@geekhood.net>
2021-07-23 17:42:13 -07:00
Sungbin Jo 119766a650 Fix appcast pubDate tag generation in different locales
Fixes #1900
2021-07-21 15:11:21 +01:00
Mayur Pawashe 9eba644190 Don't expose NSMenuItemValidation programmatically (#1897)
It doesn't make much sense to call this method programmatically due to it checking a specific selector. A client should set the menu item's target/action to the controller/checkForUpdates: action or call SPUUpdater methods directly.
2021-07-19 08:03:37 -07:00
Mayur Pawashe 4a87deeb7f Update changelog for Sparkle 2 (#1896)
* Update changelog for Sparkle 2

* Add more updates about appcast elements/attributes

* Clarify bestValidUpdateInAppcast method is discouraged for some cases

* Re-order changelog bullets

* Use https:// in sample links
2021-07-18 13:08:33 -07:00
Mayur Pawashe a09aad7ca0 Don't ignore -Wcompletion-handler if compiler doesn't understand it (#1894)
* Don't ignore -Wcompletion-handler if compiler doesn't understand it

Older Xcode versions threw a warning at not recognizing this warning.

* Silence WKWebView warning too
2021-07-16 07:54:19 -07:00
Mayur Pawashe 9c360b465b Add log warning for DSA deprecation and link to documentation (#1890) 2021-07-14 00:04:45 -07:00
Mayur Pawashe d9d7e310a5 Pull current date out of appcast filtering and add tests for phased group rollouts (#1889) 2021-07-11 16:47:05 -07:00
Mayur Pawashe 5677ca3f5a Avoid DSA verification if EdDSA verification passes (#1888)
If EdDSA verification passes we don't need to have DSA verification pass, and don't need to require the new update to contain a DSA signature or keys.

Also reject updates if app has EdDSA but no EdDSA signature is provided
2021-07-11 08:59:09 -07:00
Mayur Pawashe 29d4b801fc Reset skipped updates when updates are user initiated and checked (#1887)
Instead of only when a new update is found. This resets skipped updates if the user initiates a new check even if a new update is not found.
2021-07-10 08:52:33 -07:00
Mayur Pawashe 2157f78ffd Provide reason update is not found to updater delegate (#1886) 2021-07-10 08:52:06 -07:00
Mayur Pawashe e5c63b6369 Set $USER and $HOME variables when running guided pkg installers (#1884)
Set $USER and $HOME variables when running guided pkg installers

This allows pre/post install scripts to reference the user's environment correctly. The standard pkg installer GUI preserves these two variables.
2021-07-07 08:31:33 -07:00
Zorg 9f2629c892 Fix false un-initialized warning 2021-07-05 18:20:24 -07:00
Mayur Pawashe b21647bcef Allow delegate to pick no valid items (#1880)
* Allow delegate to pick no valid items

We now allow returning SUAppcastItem.emptyAppcastItem in -bestValidUpdateInAppcast:forUpdater: to indicate no update should be picked.

We preserve returning nil to indicate Sparkle handles the best appcast selection instead.

People have expressed needs for both of these decisions (and deprecated SUUpdater relies on the nil behavior).
2021-07-05 10:01:52 -07:00
Mayur Pawashe ac1bb7036c Make installing major upgrades opt-in (#1881) 2021-07-04 08:58:26 -07:00
Mayur Pawashe eecc4802db Merge pull request #1879 from sparkle-project/channels
Add support for channels
2021-06-28 19:57:58 -07:00
Zorg e0a7304a81 Remove outdated comment 2021-06-27 23:08:50 -07:00
Zorg 78a66c7dda Add channels support to sparkle-cli 2021-06-27 22:40:16 -07:00
Zorg d8f5f58468 Restrict channel names to reasonable set of characters 2021-06-27 22:06:02 -07:00
Zorg e5f1bd5e02 Fix initializing recoveryOption 2021-06-27 22:05:13 -07:00
Zorg c329319b0c Merge branch '2.x' into channels 2021-06-27 15:49:00 -07:00
Mayur Pawashe ad4ec8e3ab Merge pull request #1878 from sparkle-project/sparkle-version-element
Favor sparkle:version and sparkle:shortVersionString elements over enclosure attributes
2021-06-27 15:40:51 -07:00
Zorg 8997bad17e Update error message to lacking version element instead of attribute 2021-06-27 15:19:46 -07:00
Zorg c631a52b48 Re-order where link element is in sample appcast 2021-06-27 15:17:11 -07:00
Zorg dab34b62a0 Merge branch '2.x' into sparkle-version-element 2021-06-27 15:16:12 -07:00
Zorg c968334192 Allow only one channel in appcast feed items 2021-06-27 15:14:37 -07:00
Mayur Pawashe 6639feaafc Merge pull request #1877 from sparkle-project/update-not-found-why
Expose why new update is unavailable
2021-06-27 15:13:49 -07:00
Zorg 29c9b72be6 Refer developers to channels API where appropriate 2021-06-27 01:16:23 -07:00
Zorg 64484507b5 Guard against delegate returning nil channels incorrectly 2021-06-27 00:47:54 -07:00
Zorg bc7e2d4845 Export SUAppcastElementBetaChannel in new exported constants header 2021-06-27 00:40:33 -07:00
Zorg 9bb59b8c00 Add tests for filtering allowed channels and macOS releases 2021-06-27 00:28:09 -07:00
Zorg 267f2b82b1 Do not say no valid update could be found if there were no items
There may not be any applicable items due to sparkle:channels now.
2021-06-26 23:49:45 -07:00
Zorg 5fba1fe046 Add channels support to Sparkle
This allows developers to post updates to specific channels like for beta updates. Updaters only get notifications from channels they're allowed to be on.
2021-06-26 23:18:22 -07:00
Zorg ccd8886bfd Adopt sparkle:version and sparkle:shortVersionString elements
We should recommend using sparkle:version and sparkle:shortVersionString elements inside the appcast item instead of inside the enclosure for consistency.

Delta updates do not need to specify sparkle:version, and can inherit the top level element. This clears up some confusion and reduces duplication (and reduces error proneness / saves me work when testing delta / info-only features).

This is also consistent with informational updates. Regardless whether you want to make an update informational only or not, the sparkle:version stays in the same top-level place.

This is a backwards compatible change. Very old versions of Sparkle (possibly up to a decade or more ago) have supported specifying sparkle:version as a top level item. Winsparkle supports it as well because it's needed for info-only updates.

This is only changing what we recommend / standardize. The attribute variants are still usable.

External tools relying on Sparkle's feed format may have to adapt to this standardization (they have always needed to support info-only updates with a missing enclosure which apps do leverage anyway).

I updated generate_appcast to prefer the element variants and updated the tool so it understands them (this was a bug).
2021-06-26 21:01:39 -07:00
Zorg 1c1b7416ba Add Version History string to localization file 2021-06-26 18:33:00 -07:00
Zorg ed3e331f56 Update SampleAppcast.xml with links to Sparkle's website 2021-06-26 18:21:47 -07:00
Zorg aa867a0cb9 Expose reason why new update is not available to user
When user is on version >= latest appcast feed item, we give them an option to view version history.

When user can't update because of a min/max OS requirement, we give them an option to view product's website.
2021-06-26 18:18:44 -07:00
Zorg 5d27dc6fb3 Expose the reason and latest appcast item when update is not found 2021-06-26 16:06:39 -07:00
Mayur Pawashe fefce16697 Merge pull request #1876 from sparkle-project/refine-standard-updater-controller
Refine standard updater controller
2021-06-26 15:04:27 -07:00
Zorg 28065e7240 Refine SPUStandardUpdaterController API
* Make updater/userDriver properties non-null
* Expose starting the updater and allowing it to be done later instead of at instantiation (so clients in some cases will not need to make their controller declared as an optional)
* Make sender in checkForUpdates: nullable
2021-06-26 12:35:13 -07:00
Zorg d0f43e04d1 Merge branch '2.x' into expose-starting-updater 2021-06-26 11:09:35 -07:00
Mayur Pawashe 746bb1b248 Merge pull request #1862 from sparkle-project/selective-critical
Select critical/informational updates by version & store state in appcast items
2021-06-26 10:51:36 -07:00
Zorg ba5d895e8f Document where to find SPUAppcastItemStateResolver 2021-06-26 10:05:25 -07:00
Zorg 7efa996ba9 Merge branch '2.x' into selective-critical 2021-06-26 10:01:33 -07:00
Mayur Pawashe 2411d7538d Merge pull request #1875 from sparkle-project/fix-analyzer-warnings
Fix analyzer warnings
2021-06-26 09:46:29 -07:00
Zorg 3e1651d1cd Expose starting updater manually on SPUStandardUpdaterController
This allows instantiating SPUStandardUpdaterController right away programmatically, but starting the updater at a later point.
2021-06-26 09:44:41 -07:00
Zorg 4780cfccd5 Reword initializer deprecation messages 2021-06-26 01:36:54 -07:00
Zorg 50df5ed438 Retrieve critical update info even if stateResolver == nil 2021-06-26 01:21:14 -07:00
Zorg 3d8e00eecd Annotate SUAppcastItem initializers as nullable
Also mark -init as unavailable.
2021-06-25 22:26:52 -07:00
Zorg 25e0de5988 Fix analyzer warnings 2021-06-25 22:17:29 -07:00
Zorg 6e3cd6b313 Mark init methods as unavailable 2021-06-21 00:11:06 -07:00
Zorg 31f6f512e1 Export SUAppcastItem designated initializer to PrivateHeaders
Clients can use this header if they need to, but they should first talk to us / explore other avenues.
2021-06-20 23:55:40 -07:00
Zorg 686fd05fce Add tests for informational only updates 2021-06-20 23:11:02 -07:00
Zorg da30373a30 Clarify informationOnlyUpdate description in user driver docs 2021-06-20 23:10:20 -07:00
Zorg 1444561899 Add support for selectively choosing what updates are info-only
Example:
<sparkle:informationalUpdate>
    <sparkle:version>1.5.0</sparkle:version>
    <sparkle:version>1.5.1</sparkle:version>
</sparkle:informationalUpdate>

Means that updating only from versions 1.5.0 and 1.5.1 are shown an informational update (provided there is an info link).

<sparkle:informationalUpdate></sparkle:informationalUpdate>

Means that updating from any version gets an informational update (provided there is an info link).

No presence of this new element falls back to current behavior in Sparkle where an informational update is shown if an enclosure is missing but an info link is provided.
2021-06-20 21:59:05 -07:00
Zorg fb8a0a02c8 Fix typos 2021-06-20 20:42:18 -07:00
Mayur Pawashe 9a3ada03f9 Merge pull request #1872 from sparkle-project/http-headers-releasenotes
Pass http headers and user agent when downloading release notes
2021-06-19 17:28:23 -07:00
Zorg d794a2d803 Merge branch '2.x' into selective-critical 2021-06-18 00:21:53 -07:00
Zorg b1f9bff9a1 Pass http headers and user agent when downloading release notes 2021-06-17 20:29:33 -07:00
Mayur Pawashe c548721e16 Merge pull request #1871 from sparkle-project/restore-removed-initializers
Restore more removed SUAppcastItem initializer methods
2021-06-17 20:13:40 -07:00
Zorg eeb24ed92d Restore more removed SUAppcastItem initializer methods 2021-06-17 19:50:37 -07:00
Mayur Pawashe 66de9697f3 Merge pull request #1868 from sparkle-project/xcode13
Upgrade and fix Xcode 13 warnings
2021-06-17 00:39:31 -07:00
Mayur Pawashe cb1e58e309 Merge pull request #1870 from tonyarnold/restore-suappcastitem-public-init
Restore public initializer for SUAppcastItem
2021-06-17 00:37:04 -07:00
Tony Arnold 24a0485e98 Restore public initializer for SUAppcastItem
Closes #1869
2021-06-16 09:56:19 +10:00
Zorg 29e7ad4495 Merge branch '2.x' into selective-critical 2021-06-12 22:33:21 -07:00
Zorg 961605c6d6 Upgrade macOS and Xcode versions for CI 2021-06-11 22:50:32 -07:00
Zorg 2b8d2a2be7 Set SDKROOT to macosx instead of nothing 2021-06-11 22:42:52 -07:00
Zorg dfdd6ac978 Update last upgrade version of project files 2021-06-11 22:40:57 -07:00
Zorg 52f3337eda Enable parallelizing building of targets
Not doing this is deprecated in Xcode 13.
2021-06-11 22:35:41 -07:00
Zorg defa8e4332 Add Sparkle.framework as dependency to Distribution 2021-06-11 22:34:55 -07:00
Zorg 3636e22cc5 Fix sparkle-cli not linking/embedding Sparkle.framework 2021-06-11 22:26:28 -07:00
Zorg 50ba774bbe Fix -Wcompletion-handler warnings 2021-06-11 22:25:14 -07:00
Mayur Pawashe 432f10f804 Merge pull request #1867 from danielpunkass/xcode13-fix-cgimage
Fix the build with Xcode 13 by explcitly importing ImageIO
2021-06-11 18:49:08 -07:00
Daniel Jalkut 232ce2543e Fix the build with Xcode 13 by explcitly importing ImageIO. Previously it was being implicitly imported along with Foundation. 2021-06-09 14:04:26 -04:00
Mayur Pawashe efe1c8c02e Merge pull request #1866 from sparkle-project/configuration-cleanup
Configuration cleanup
2021-06-07 19:25:23 -07:00
Zorg 1697c7966c Fix unit tests from not building 2021-06-06 20:26:03 -07:00
Zorg 5203518fbd Remove allowing downgrades
Downgrades hasn't worked properly with choosing the best appcast selection in a long long time.
2021-06-06 19:40:58 -07:00
Zorg 9fd2e72913 Fix missing implementation method in sparkle-cli 2021-06-06 19:38:00 -07:00
Zorg ff83896e01 Set app category for InstallerProgress agent tool 2021-06-06 19:36:56 -07:00
Zorg 89ecb88f2b Define DEBUG=0 for release builds 2021-06-06 19:35:15 -07:00
Zorg 4825ac5d62 Remove outdated comments 2021-06-06 19:31:30 -07:00
Zorg e2723717f1 Don't link to AppKit and WebKit explicitly 2021-06-06 19:26:49 -07:00
Zorg b6956a480d Don't include WebKit implementation when not building UI bits 2021-06-06 19:26:25 -07:00
Zorg 7f87d8842e Add missing appkit prevention includes 2021-06-06 19:16:51 -07:00
Zorg cbd1503c06 Add configuration option to not build UI bits 2021-06-06 19:09:19 -07:00
Zorg eda1b4bdaa Remove SparkleCore target and use <> imports
In some cases for shared headers in downloader XPC Service or generate_appcast / sign_update tools, I had to do a little dance for using double quote imports.
2021-06-06 18:38:49 -07:00
Zorg 7861cea66c Merge branch '2.x' into selective-critical 2021-06-01 23:35:03 -07:00
Mayur Pawashe c0691c4606 Merge pull request #1865 from sparkle-project/disable-automatic-downloads-manual-checks
Don't allow setting/toggling automatic updates in update alert when update checks are disabled
2021-06-01 23:33:20 -07:00
Zorg 0063fbda17 Don't allow setting automatic updates when update checks are disabled 2021-06-01 10:19:44 -07:00
Zorg d468757ee1 Revert some unnecessary changes I made 2021-05-31 12:51:09 -07:00
Zorg 1013b2506a Remove #warning 2021-05-31 12:17:43 -07:00
Zorg 1aadf1b351 Remove passing around preventsAutoupdate flag
Also improve user driver documentation slightly.
2021-05-31 11:57:33 -07:00
Zorg 5287453cfd Use dot-syntax naming 2021-05-31 11:41:30 -07:00
Zorg 88f678ebe6 Remove SPUUserUpdateStageInformational 2021-05-31 11:24:32 -07:00
Zorg ee5e98d3dd Rename SPUUpdateState back to SPUUserUpdateState 2021-05-31 11:13:05 -07:00
Zorg 062bfaaa97 Remove old code passing min/max OS tests 2021-05-31 10:59:35 -07:00
Zorg f51bb996e6 Remove critical and major upgrade properties from SPUUpdateState 2021-05-31 10:22:55 -07:00
Zorg 8fb44df0b7 Add unit tests for critical updates 2021-05-31 10:16:04 -07:00
Zorg 8f488c6ffd Fix unit tests 2021-05-31 09:58:09 -07:00
Zorg 63e0b47c98 Don't expose appcast item state publicly 2021-05-31 09:32:00 -07:00
Zorg fabf415999 Resolve appcast item properties from external environment at init 2021-05-31 09:27:21 -07:00
Zorg 0e264dae2f Add comments on critical testing functions 2021-05-31 00:20:11 -07:00
Zorg 60bbb373e2 Add comments on legacy critical update path 2021-05-31 00:17:08 -07:00
Zorg 1cc11d76a2 Fix SPUUpdateState reference 2021-05-31 00:14:55 -07:00
Zorg 90bdd84832 Move SPUUserUpdateChoice into its own header 2021-05-31 00:13:07 -07:00
Zorg b7f9b76dd9 Rename SPUUserUpdateState -> SPUUpdateState 2021-05-31 00:00:38 -07:00
Zorg 253f45b476 Add optional version field to sparkle:criticalUpdate element
This version indicates the version that was first marked critical. So versions below this specified version will treat the update as critical while versions >= the specified version will not.

Also move sparkle:criticalUpdate to root level element instead of it being a tag. The tagged version is now deprecated and doesn't support the version field.
2021-05-30 23:37:38 -07:00
Mayur Pawashe 433e1bf3de Merge pull request #1860 from 1024jp/localizeJa
Add missing Japanese localization strings
2021-05-30 10:08:44 -07:00
Mayur Pawashe bbdebfdbee Merge pull request #1858 from sparkle-project/warnings
Fix all Interface Builder and compiler warnings and require macOS 10.11 (El Capitan)
2021-05-30 09:46:10 -07:00
1024jp 8a62dc06fe Add missing Japanese localization strings
that were added in #1853.
2021-05-30 16:51:23 +09:00
Mayur Pawashe d7c504a254 Merge pull request #1853 from sparkle-project/skip-major-updates
Skip minor updates separately from major upgrades
2021-05-29 23:19:28 -07:00
Zorg 87a4e349ce Remove more legacy pre 10.11 checks 2021-05-29 22:53:25 -07:00
Zorg 549a8ce117 Re-annotate sender as unused 2021-05-29 22:46:51 -07:00
Zorg 91fc440d15 Animate resizing the window when disclosing more info 2021-05-29 14:49:28 -07:00
Zorg 79cd07fc70 Use alerts instead of notifications 2021-05-29 07:52:50 -07:00
Zorg 0cdb0976ef Don't hide skipping button for major upgrades if update is critical 2021-05-29 07:50:30 -07:00
Zorg e0a414909c Re-word skip upgrade title confirmation 2021-05-28 23:56:04 -07:00
Zorg 8e466eecc8 Fix unit tests for skipped updates 2021-05-28 23:28:44 -07:00
Zorg 17eb15e9d3 Simplify skipping major updates
We now only track one major version to skip and one minor version to skip, instead of an array of potentially growing minor/major versions.
2021-05-28 23:11:13 -07:00
Zorg 7d3c7ae78a Add alert confirmation for skipping major upgrades 2021-05-28 17:23:31 -07:00
Zorg a630614dc4 Use "update" still instead of "upgrade" for major updates 2021-05-27 22:26:23 -07:00
Zorg 87ecba77d3 Set LSMinimumSystemVersion for the test app 2021-05-27 21:50:30 -07:00
Zorg 455e63cc59 Remove hard coded 10.11 deployment targets 2021-05-27 21:50:16 -07:00
Zorg 57b39fc1e5 Update and remove 10.9 and 10.10 references 2021-05-27 21:39:24 -07:00
Zorg b2127da6f5 Add missing trailing constraint to Release Notes label 2021-05-27 16:37:44 -07:00
Zorg 8fc1689c26 Remove hidden shouldAskAboutProfile button binding 2021-05-27 16:28:41 -07:00
Zorg 898ac7253a Set code sign identity to adhoc across the project 2021-05-24 01:04:33 -07:00
Zorg f8ef9608dc Fix warning from using -stringByAddingPercentEscapesUsingEncoding: 2021-05-24 00:41:46 -07:00
Zorg d22ef79d9e Remove unused outlets 2021-05-16 15:45:06 -07:00
Zorg 8af1d18764 Update localization files 2021-05-16 15:42:05 -07:00
Zorg a7e090e3ca Revert "Start to move permission prompt localizations away from xib"
This reverts commit e607bf19dc.
2021-05-16 15:35:49 -07:00
Zorg e607bf19dc Start to move permission prompt localizations away from xib 2021-05-16 12:39:22 -07:00
Zorg 7490a91406 Re-adjust leading constraint for anonymous info button 2021-05-16 10:18:27 -07:00
Zorg 9ee2a525d0 Decrease distance between response buttons info view 2021-05-16 10:14:42 -07:00
Zorg 54caf47602 Set leading constraint of more info description to be bit higher 2021-05-16 10:06:56 -07:00
Zorg ed87bcdab6 Use NSStackView for permission prompt window 2021-05-16 10:01:48 -07:00
Zorg ef577fe0c0 Make subview for anonymous system info button 2021-05-15 21:54:06 -07:00
Zorg 7c8defb75e Create separate subviews for permission prompt 2021-05-15 21:41:19 -07:00
Zorg f6d8b506ae Align disclosure button with include anonymous info text 2021-05-15 14:21:17 -07:00
Zorg 3306ccd994 Suppress deprecation warnings for SMJobSubmit functions 2021-05-15 11:58:01 -07:00
Zorg 07aca30e11 Bump deployment target to 10.11 2021-05-15 11:53:08 -07:00
Zorg be75bb38f6 Add auto layout constraints to update permission prompt 2021-05-14 22:52:20 -07:00
Zorg debab803c9 Add auto-layout constraints to status window 2021-05-14 22:28:38 -07:00
Zorg 8dc4e78cb2 Remove unused installationPath variable from normalization changes 2021-05-14 22:09:41 -07:00
Zorg e91ae897e7 Add method to compare two minimum autoupdate versions 2021-05-14 18:28:32 -07:00
Mayur Pawashe 91e71c219c Merge pull request #1854 from sparkle-project/xpc-sha
Validate XPC Service versions
2021-05-10 19:11:57 -07:00
Zorg f56e923043 Validate XPC Services versions in startUpdater: 2021-05-10 01:02:27 -07:00
Zorg 50bec90279 Set fetch-depth to 0 in GitHub Actions CI 2021-05-10 00:26:57 -07:00
Zorg 1f9d76bc13 Retitle install button to "Install Upgrade" for major updates 2021-05-09 23:16:01 -07:00
Zorg 59fbd37bb1 Re-title skip button when update is a major one 2021-05-09 23:03:05 -07:00
Zorg f671b82e50 Test against SPUUserUpdateStageInformational 2021-05-09 22:53:58 -07:00
Zorg 1565db3fec Add secure coding to SPUUserUpdateState 2021-05-09 22:51:50 -07:00
Zorg 25b3d01efa Rename majorUpdate to majorUpgrade 2021-05-09 22:45:40 -07:00
Zorg d193f2e28b Pass majorUpdate information to user driver
We unify the user driver method showing the update to take a generic state object now. The current fields of the state object are its current stage, if it's user initiated, and if the update is a major one.

We also remove deprecated code paths that were complex to support and will otherwise generate in compile errors if people adopt the new API.
2021-05-09 22:42:42 -07:00
Zorg a79f6b2a85 Add documentation to SPUSkippedUpdate 2021-05-09 20:48:32 -07:00
Zorg 0ee12d881d Add and fix unit tests for skipping updates 2021-05-09 19:53:19 -07:00
Zorg 6d6cc2d052 Add support for skipping major and minor updates separately 2021-05-09 19:30:44 -07:00
Mayur Pawashe 039adc1ef2 Merge pull request #1850 from sparkle-project/better-appcast-selection
Better appcast selection
2021-05-03 19:02:20 -07:00
Zorg 62695379d9 Clarify what versions not to filter for 2021-05-02 23:15:01 -07:00
Zorg f82f9eb878 Fix typo 2021-05-02 23:13:58 -07:00
Zorg a1aef4eca0 Fix string localization 2021-05-02 23:12:48 -07:00
Zorg 3d2dc8a7f6 Update documentation for -bestValidUpdateInAppcast:forUpdater:
This method will not be invoked for appcast with zero items. Clients must pick best item and cannot pick "no items."
2021-05-02 23:09:45 -07:00
Zorg 5a3b71b96a Add note about not returning a delta update item in delegate 2021-05-02 22:38:27 -07:00
Zorg 3c9508bd2a Add tests for testing minimum autoupdate version 2021-05-02 22:32:50 -07:00
Zorg 79c1141155 Refactor finding latest appcast item 2021-05-02 21:44:35 -07:00
Zorg ebb822af43 Merge branch '2.x' into better-appcast-selection 2021-05-02 16:06:45 -07:00
Zorg c882da7bc7 Update documentation for -bestValidUpdateInAppcast 2021-05-02 16:06:22 -07:00
Zorg f1be9f72d5 Remove passing includesSkippedUpdates in favor of background flag 2021-05-02 15:59:43 -07:00
Zorg e7441351d7 Make improvements to best appcast selection
* Prefer using the latest update that passes minimumAutoupdateVersion

When an update is not found:
* Find latest appcast item that may fail min/max OS
* Report that user cannot install an update due to unsupported OS
2021-05-02 15:50:03 -07:00
Mayur Pawashe 3cafb688b7 Merge pull request #1849 from sparkle-project/appcast-item-nullability
Add nullability annotations to SUAppcastItem
2021-05-02 13:49:27 -07:00
Zorg d84a79cfc2 Merge branch '2.x' into appcast-item-nullability 2021-05-02 11:29:39 -07:00
Zorg c33ccd5921 Merge branch '2.x' into appcast-item-nullability 2021-05-02 11:17:42 -07:00
Zorg 6ad996338d Add nullability annotations to SUAppcastItem 2021-05-02 10:00:56 -07:00
Mayur Pawashe 46f7898d36 Merge pull request #1844 from sparkle-project/download-driver-appcast
Re-use download driver for downloading appcast & release notes
2021-05-02 09:03:20 -07:00
Mayur Pawashe 85ac073e6d Merge pull request #1846 from sparkle-project/enforce-session-in-progress
Enforce the updater session is in progress
2021-05-02 09:03:04 -07:00
Mayur Pawashe 7c46e8db3e Merge pull request #1848 from sparkle-project/skip-installing-update
Allow skipping/canceling of an update that is currently installing
2021-05-02 09:02:08 -07:00
Zorg fbe48e5738 Allow skipping/canceling of an update that is currently installing 2021-05-01 19:53:01 -07:00
Mayur Pawashe b140c05bad Merge pull request #1843 from sparkle-project/nsunavailable
Add NS_UNAVAILABLE attributes to user driver classes
2021-05-01 17:26:15 -07:00
Mayur Pawashe c79785aad4 Merge pull request #1845 from sparkle-project/version-dash-separator
Port #1504 (dash separators in version strings) to 2.x
2021-05-01 17:25:53 -07:00
Mayur Pawashe 5da8199818 Merge pull request #1847 from sparkle-project/sandbox-errors
Log more sandbox errors
2021-05-01 17:25:35 -07:00
Zorg 79a6bb1318 Disable unused debugging options in test app scheme 2021-05-01 14:48:31 -07:00
Zorg 9b8756d824 Add sandbox log if connection to installer fails 2021-05-01 14:46:34 -07:00
Zorg 712753d812 Add log linking to sandboxed steps if app isn't sandboxed at all 2021-05-01 14:36:45 -07:00
Zorg e8d5c8024c Log error if developer sandboxes installer launcher service 2021-05-01 14:30:21 -07:00
Zorg af245bfe62 Enforce the updater session is in progress
We should enforce update session is in progress before checking for new updates. I've tested checking for updates regularly, in background, and informational updates.

An update check could have been made while the permission request was in flight, which we don't want to happen.
2021-05-01 11:08:18 -07:00
Zorg 9a12dbf62a Port #1504 (dash separators in version strings) to 2.x
On second thought I realized we can support this without doing any date comparison because the code just picks the first item if two are equal.
2021-05-01 10:48:53 -07:00
Zorg 477d0a243f Fix unit tests 2021-04-30 22:21:19 -07:00
Zorg ab294d607d Hide private SUAppcast / SUAppcastItem APIs 2021-04-30 21:40:47 -07:00
Zorg 26c63c1a7b Remove commented out code 2021-04-30 21:28:56 -07:00
Zorg 6adb0c3017 Use download driver for downloading release notes 2021-04-30 21:10:41 -07:00
Zorg 7cb72238fa Use download driver for downloading appcast 2021-04-30 20:37:00 -07:00
Zorg 0eb5a706f8 Add NS_UNAVAILABLE attributes to user driver classes 2021-04-30 18:03:22 -07:00
Mayur Pawashe e179443799 Merge pull request #1836 from jaroslavas/feature/sign-update-file
Add private_key parameter in sign_update
2021-04-26 20:11:57 -07:00
Jaroslav Ozevič c00946ee20 Fixed error message in case sign_update can't find the key in the keychain 2021-04-26 10:07:38 +03:00
Jaroslav Ozevič 12a3da9629 Update sign_update to accept -f <private_key_file> or -s <private_key> parameters 2021-04-26 09:49:50 +03:00
Mayur Pawashe 84cdb0c7e8 Merge pull request #1838 from sparkle-project/fix-delta-updates
Fix delta updates edge cases
2021-04-25 21:39:53 -07:00
Mayur Pawashe 478cc98b90 Merge pull request #1839 from sparkle-project/remove-auth-promt-localization
Remove localizing authorization prompt
2021-04-25 20:26:56 -07:00
Mayur Pawashe bf35926cf3 Merge pull request #1840 from sparkle-project/fix-test-app-responder
Test App: Allow check for updates menu item to be invoked outside of settings
2021-04-25 20:26:15 -07:00
Kornel 8034404cc7 Merge pull request #1835 from 1024jp/localizeJa
Add missing Japanese localization strings
2021-04-26 02:54:37 +01:00
Zorg 411360deb2 Allow check for updates menu item to be invoked outside of settings
Previously check for updates was only in responder chain of the settings window controller. Now it's in responder chain of the entire application.
2021-04-25 15:48:20 -07:00
Zorg d91223a5b6 Remove localizing authorization prompt
The message string gets cached and I don't think this is the proper way to localize the auth dialog (which I think has some other mechanism). So I am removing localization here for now until this can possibly be done properly.
2021-04-25 14:46:42 -07:00
Zorg 063974c553 Simplify logic in -preferredUpdateForRegularAppcastItem method 2021-04-25 14:28:33 -07:00
Mayur Pawashe 97f15943e4 Merge pull request #1837 from sparkle-project/cleanup-download
Clean up downloads better
2021-04-25 14:22:56 -07:00
Zorg 564f0c316a Refactor retrieving regular & delta update items 2021-04-25 13:57:09 -07:00
Zorg 50942909f2 Add comment indicating why we don't pass full downloaded path 2021-04-25 12:24:34 -07:00
Zorg 71557fac85 Include secondary non-delta update to resumable updates 2021-04-25 12:15:44 -07:00
Zorg e51eb32403 Fix bestValidUpdateInAppcast: not handling delta updates correctly
All the top level appcast items are non-delta items. The client needs to give us back a non-delta update item. We then fetch the appropriate delta item ourselves.
2021-04-24 21:42:33 -07:00
Zorg 6d0d1a7aa8 Add comment about clearing download after beginning installation 2021-04-24 19:40:54 -07:00
Zorg c44c164aff Clean up empty / temporary progress agent tool directory immediately 2021-04-24 19:29:10 -07:00
Zorg 1244612946 Clear download from installer when extraction fails
One example of extraction failing is the delta update failing to apply.
2021-04-24 19:11:36 -07:00
Zorg 842d258330 Clean up download directory upon skipping already downloaded update 2021-04-24 19:00:06 -07:00
Jaroslav Ozevič ef7c16bb9d Add private_key parameter in sign_update 2021-04-23 15:09:30 +03:00
1024jp f56f937ad2 Add missing Japanese localization strings
that were added in #1833.
2021-04-21 09:14:07 +09:00
Mayur Pawashe 02b85635c7 Merge pull request #1833 from sparkle-project/missing-localizations
Update missing localizations strings
2021-04-18 19:32:25 -07:00
Zorg ce70a30be5 Don't localize rare/unlikely/specific scenario error strings 2021-04-18 19:00:58 -07:00
Zorg e8f41640dc Comment which localizations are rare/unlikely 2021-04-18 18:54:05 -07:00
Mayur Pawashe 7247803fea Merge pull request #1831 from sparkle-project/deprecate-dismiss-check
Deprecate -dismissUserInitiatedUpdateCheck user driver method
2021-04-18 18:29:39 -07:00
Mayur Pawashe fe8b6b3e2a Merge pull request #1827 from sparkle-project/show-update-focus
Show the present update in focus when checkForUpdates is invoked
2021-04-18 18:29:11 -07:00
Mayur Pawashe f0ff2e3ef0 Merge pull request #1832 from sparkle-project/update-auth-prompt
Update authorization prompt when updating an app
2021-04-18 18:22:30 -07:00
Zorg c7ff8f4bb0 Add Install on Quit localizations from automatic alert from 1.x 2021-04-18 12:11:46 -07:00
Zorg 669c369ce7 Add missing localization strings to Sparkle.strings 2021-04-18 12:06:34 -07:00
Zorg db6ef214ab Update authorization prompt when updating an app
We have a slightly different prompt for an app updating itself vs an app/tool updating another app. Also put prompt in the localization strings.
2021-04-18 11:44:30 -07:00
Zorg ba11897345 Deprecate -dismissUserInitiatedUpdateCheck user driver method
We don't have a dismiss method for every transition state and we don't want to. This should be up to the UI to determine how to transition from one UI state to another UI state.
2021-04-17 22:21:22 -07:00
Zorg cc4c02f467 Add showUpdateInFocus implementation to Test App user driver 2021-04-17 16:36:28 -07:00
Zorg f58cc9e9b5 Merge branch '2.x' into show-update-focus 2021-04-17 16:25:36 -07:00
Mayur Pawashe 8f3e340e47 Merge pull request #1829 from sparkle-project/merge-show-update-methods
Merge show update methods
2021-04-17 16:23:53 -07:00
Mayur Pawashe 547fde293d Merge pull request #1830 from sparkle-project/enforce-only-owner
Don't bring up authorization just because group ID doesn't match
2021-04-17 16:09:40 -07:00
Zorg 302f3f41a3 Clear downloaded update upon skipping
I had this line of code before in the legacy path but forgot to use it.
2021-04-17 16:07:18 -07:00
Zorg af9935540a Don't bring up authorization just because group ID doesn't match 2021-04-17 13:47:00 -07:00
Zorg 188a893174 Rename new state back to not downloaded 2021-04-16 19:07:48 -07:00
Zorg 3309abf936 Remove DEBUG conditional check around deprecated methods 2021-04-16 16:55:48 -07:00
Zorg 1abe5f70db Add comment for legacy path 2021-04-16 16:47:22 -07:00
Zorg ab9ffdb901 Rename SPUUserUpdateStateNotDownloaded to SPUUserUpdateStateNew
Update documentation too.

Fix test app trying to make installable update skippable.
2021-04-16 16:40:33 -07:00
Zorg e64253be0b Merge showUpdateFount: methods into single one
Handling the different variations with different completion blocks is a pain when ultimately clients want to display a mostly unified user interface.
2021-04-16 16:34:01 -07:00
Zorg 8ff356bc7d Update documentation on checkForUpdates 2021-04-16 12:16:34 -07:00
Zorg 3593157e3d Merge branch '2.x' into show-update-focus 2021-04-16 12:04:05 -07:00
Mayur Pawashe 2d0b9ae356 Merge pull request #1826 from 1024jp/localizeJa
Add missing Japanese localization strings
2021-04-16 12:02:25 -07:00
Zorg d9e0265d76 Show the present update during updater progress too
This includes updater permission request, downloading updates, downloading appcast, installing update, and so on.
2021-04-16 11:32:00 -07:00
1024jp 5ff2d7765e Add missing Japanese localization strings
that added in #1819.
2021-04-17 00:02:51 +09:00
Zorg 6b3d2af21a Simplify UI driver storing showingUpdate state 2021-04-16 00:01:37 -07:00
Zorg 2f783e01f0 Show the present update in focus when checkForUpdates is invoked
When the update is shown to the user, the menu item for checking for updates is no longer disabled. Instead it is enabled, and when invoked, will bring the update to utmost focus back to the user again.

This is consistent with other options (eg Preferences...) that bring up windows. Improved user experience here is that updates are now less "lost".

We (re)define properties on SPUUpdater:

canCheckForUpdates - to mean that the user can check for updates (start a new update check or show the already present update frontmost)

sessionInProgress - to mean if Sparkle's internal driver / scheduler is running (i.e, downloading appcast or update, showing update, starting installation).
2021-04-15 22:56:41 -07:00
Mayur Pawashe 40545494f2 Merge pull request #1819 from sparkle-project/user-driver-relaunch
Show alert that non-relaunched application was installed
2021-04-15 20:02:59 -07:00
Zorg b0d9a75f98 Add new installed update localizations to Sparkle.strings 2021-04-15 19:36:14 -07:00
Zorg ed89783a0e Merge branch '2.x' into user-driver-relaunch 2021-04-13 00:05:39 -07:00
Mayur Pawashe cb17e08b92 Merge pull request #1823 from sparkle-project/entitlements
Entitlement scripts/configuration updates
2021-04-12 19:20:46 -07:00
Mayur Pawashe 286af16842 Merge pull request #1821 from sparkle-project/api-updater-doc
Update API documentation for instantiating/using updater
2021-04-12 19:20:20 -07:00
Mayur Pawashe a084e2f09d Merge pull request #1822 from sparkle-project/sample-appcast-edSignature
Update SampleAppcast.xml to use edSignatures
2021-04-12 19:19:47 -07:00
Mayur Pawashe 9524b32024 Merge pull request #1820 from sparkle-project/simplify-user-driver
Simplify user driver
2021-04-12 19:19:27 -07:00
Zorg cb10bb8046 Remove SPUUserDriverCoreComponent usage completely 2021-04-11 23:31:04 -07:00
Zorg 2d9bf07b18 Add new user driver methods to cancel update checks / downloads
Remove SPUUserDriverCoreComponent dependency from sparkle-cli and the Test App too, which really wasn't helping at all.
2021-04-11 23:15:02 -07:00
Zorg eea87561ab Update XPC Service signing script
Add entitlements to InstallerConnection and InstallerStatus services and add option to specify bundle id in the now renamed codesign_xpc_service.py script.
2021-04-11 21:52:09 -07:00
Zorg e7bc17b192 Use $(PRODUCT_BUNDLE_IDENTIFIER) for defaults exception for test app 2021-04-11 20:19:33 -07:00
Zorg 07e96961bf Sign altered app in release too for the test app 2021-04-11 20:04:53 -07:00
Zorg 895bb71fae Add InstallerStatus and InstallerConnection services to Distribution 2021-04-11 20:03:59 -07:00
Zorg 372d711d20 Remove ATS allow-exception scripts for debug / test app 2021-04-11 19:43:12 -07:00
Zorg 5408ab10c1 Remove lesser used XPC Services for Test App
Testing WebKit2 is more important than testing sandboxed downloader service.
More people should be adding entitlements to their app for connection services, so we will do that in the test app too.
2021-04-11 19:28:46 -07:00
Zorg 3ea863d82b Remove incorrect note about when relaunch happens
User driver can also request to not relaunch the app and this is worded oddly.
2021-04-11 19:01:27 -07:00
Zorg bd1769e82e Update SampleAppcast.xml to use edSignatures 2021-04-11 15:17:53 -07:00
Zorg 0b634f4d76 Update API documentation for instantiating/using updater 2021-04-11 15:00:43 -07:00
Zorg 9052ea912d Ensure permission request response is handled on main thread
We were doing this before but I accidentally removed it in a recent commit.
2021-04-11 14:43:52 -07:00
Zorg 833eb89bb5 Simplify user driver API
Deprecate the "done" statuses for user initiated update checks and downloading updates because they really did nothing but burden implementor (there was a relic of an XPC reason back in the day that no longer applies).
2021-04-11 14:41:07 -07:00
Zorg e909c0d988 Show alert that non-relaunched application was installed
This only applies when the updater outlives the application it is updating and the application is not relaunched (i.e, an external/remote updater).
2021-04-11 14:01:03 -07:00
Mayur Pawashe 1f90f7c993 Merge pull request #1818 from sparkle-project/update-cycle-2
Defer requiring feed URL until checking for updates
2021-04-11 13:12:11 -07:00
Zorg 6db6a9892a Defer requiring feed URL until checking for updates
Also don't automatically reset update cycle if updater hasn't been started yet.
2021-04-10 15:18:13 -07:00
Mayur Pawashe e20f099c90 Merge pull request #1815 from sparkle-project/fix-interactive
Fix interactive flag being ignored in sparkle-cli
2021-04-05 19:05:59 -07:00
Zorg 9b6e7ba828 Fix interactive flag being ignored in sparkle-cli 2021-04-04 16:57:37 -07:00
Mayur Pawashe 8c53b1d3ec Merge pull request #1812 from sparkle-project/system-domain
Pass whether or not system domain is being used back to framework
2021-04-04 16:37:37 -07:00
Mayur Pawashe faf047c4ea Merge pull request #1813 from sparkle-project/service-length
Increase max mach service name length to 127 characters
2021-04-04 16:36:08 -07:00
Zorg 71a36f8be4 Add comments on message type tags 2021-04-04 14:06:27 -07:00
Zorg ebc48cee5c Increase max mach service name length to 127 characters 2021-04-03 22:43:01 -07:00
Zorg 467ffb15ca Pass whether or not system domain is being used back to framework
This avoids needing to do a file system check in InstallerConnection to determine if we need to connect to the system or user domain.
2021-04-03 17:16:38 -07:00
Mayur Pawashe a79aa1690b Merge pull request #1810 from sparkle-project/permission-prompt-no-modal
Don't make permission prompt a modal window
2021-03-29 19:12:41 -07:00
Mayur Pawashe e1fdd5a6c4 Merge pull request #1809 from sparkle-project/update-cycle
Universally start update cycle one runloop cycle later
2021-03-29 19:12:27 -07:00
Mayur Pawashe a108d4bc72 Merge pull request #1811 from sparkle-project/relaunch-host
Provide option to open host bundle path instead of app path
2021-03-29 19:08:21 -07:00
Zorg 5a0529a2cd Provide option to open host bundle path instead of app path
This is useful for plug-ins that may want Sparkle to open eg a .prefpane or .saver instead of re-launching System Preferences (which is the app used to wait for termination; normally we only relaunch an app that was proven to be alive).

In a plug-in world, it may not be possible to tell which is more desirable so we provide both options. In 1.x, there was a delegate -pathToRelaunchForUpdater: method to pick between these, however in 2.x for hardening sake, there isn't an API to open any arbitrary bundle path so we provide explicit options.
2021-03-28 23:39:10 -07:00
Zorg 3a201a45ac Don't make permission prompt a modal window
This can block the rest of the UI from being loaded on an app that is just starting. I saw this myself in a pref pane plugin.
2021-03-28 17:35:32 -07:00
Zorg 93b8700060 Add self.driver != nil assert 2021-03-28 17:10:10 -07:00
Zorg 2614af86ff Don't defer some of sparkle-cli delegate callbacks 2021-03-28 16:35:21 -07:00
Zorg 5ae944778a Set canCheckForUpdates to NO before probing install status 2021-03-28 16:25:05 -07:00
Zorg f2986ef090 Start updater one runloop cycle later
And remove logic in SPUStandardUpdaterController and SUUpdater that defers starting the updater one cycle later, because that logic is now in SPUUpdater which they invoke.

It is too easy to start the updater "too soon" (if not using SPUStandardUpdaterController or SUUpdater) and I had some weird approach before that allowed the developer to check for updates before starting the updater and it would get deferred until the updater was started (without showing a permission prompt). Instead, defer the update cycle check allowing developer to check for updates immediately after starting the updater if needed (sparkle-cli needs to do this in one case).

Errors are now logged when checking for updates without having started the updater.

This fixes edge cases of UI being shown too early.
2021-03-28 13:21:20 -07:00
Mayur Pawashe 923bb96eda Merge pull request #1802 from sparkle-project/features
Add quicker & more reliable updating to features
2021-03-28 12:47:44 -07:00
Mayur Pawashe 2af01e8844 Merge pull request #1808 from sparkle-project/normalization
Compute app path normalization in progress agent
2021-03-28 10:51:10 -07:00
Zorg 414c8affc5 Compute app path normalization in progress agent
Compute path instead of having installer pass over arbitrary path to agent.
2021-03-27 22:17:25 -07:00
Zorg 90aa98b68c Update changelog 2021-03-25 23:24:18 -07:00
Zorg 7e8084b064 Update readme / changelog 2021-03-23 19:37:20 -07:00
Mayur Pawashe 25001d83ee Merge pull request #1803 from sparkle-project/preventAccidentalInstalls-2.x
Disable keyboard shortcut for active not-initiated scheduled checks
2021-03-23 19:22:32 -07:00
Mayur Pawashe 78b0570a76 Merge pull request #1804 from sparkle-project/no-hide-on-deactivate
Don't hide standard updater window on deactivation
2021-03-23 19:22:20 -07:00
Zorg 9555cb7397 Fix UI tests from not making update alert hide on deactivation 2021-03-22 23:05:02 -07:00
Zorg 78ec0f46b7 Disable keyboard shortcut for active not-initiated scheduled checks
This ports #1036 over to 2.x. Looks like I forgot to port half of it.
2021-03-22 16:17:07 -07:00
Zorg f95bf0c7d5 Don't hide standard updater window on deactivation
Sometimes when the app is re-activated, the window is ordered back behind other applications. Also it may be useful to eg read the release notes when browsing another application. We still preserve the logic that defers showing the update alert when the application isn't initially frontmost.
2021-03-22 15:48:47 -07:00
Zorg cf14d09ee0 Update CHANGELOG 2021-03-22 01:36:31 -07:00
Zorg 90448fd564 Add quicker & more reliable updating to features 2021-03-22 01:14:20 -07:00
Mayur Pawashe 0a4846a186 Merge pull request #1801 from sparkle-project/atomic-swap
Update and replace bundle directories even more atomically on apfs
2021-03-21 18:54:36 -07:00
Zorg b3e7a03660 Update and replace bundle directories even more atomically on apfs
With these changes, it should not be possible for neither an old or new bundle to be at the destination.

We also perform temporary directory cleanup after final installation stage is and relaunching an app is performed because we can save some time (150 ms+ in one of my cases).
2021-03-21 17:54:51 -07:00
Mayur Pawashe 83aac00fe6 Merge pull request #1800 from sparkle-project/log-nserror
Add and use function to log NSError objects recursively
2021-03-19 13:50:14 -07:00
Zorg 89b7fef457 Add and use function to log NSError objects recursively 2021-03-19 12:35:22 -07:00
Mayur Pawashe 5fbf119e6a Merge pull request #1799 from sparkle-project/graceful-change-owner-group-failure
Don't make changing owner/group a hard fatal error
2021-03-19 11:18:39 -07:00
Zorg 2e8fc4d17a Don't make changing owner/group a hard fatal error 2021-03-19 10:28:59 -07:00
Mayur Pawashe 454e6d2f13 Merge pull request #1798 from sparkle-project/disable-hardened-runtime-sparkle-cli
Disable hardened runtime for sparkle-cli
2021-03-19 09:20:54 -07:00
Zorg 28924f4b2a Disable hardened runtime for sparkle-cli 2021-03-18 20:49:08 -07:00
Mayur Pawashe d102a50f66 Merge pull request #1795 from sparkle-project/main-dev
Main development change
2021-03-08 21:12:05 -08:00
Zorg bfc55ac8b0 Add 1.x feature frozen note 2021-03-08 00:54:02 -08:00
Zorg 1f35e7b5cd Add GitHub issue / pull request templates 2021-03-08 00:51:09 -08:00
Zorg f23799a531 Re-add INSTALL document which directs user to Sparkle website docs 2021-03-08 00:40:44 -08:00
Zorg 81453d1410 Update ReadMe to update development branch and feature-freeze 1.x 2021-03-08 00:40:12 -08:00
Mayur Pawashe 7064ac160b Merge pull request #1794 from sparkle-project/sync-localizations
Sync localizations
2021-03-07 10:21:45 -08:00
Mayur Pawashe f74f9d288d Merge pull request #1793 from sparkle-project/ci-upload-dist
Test validity of archived products and upload distribution in CI
2021-03-07 09:23:50 -08:00
Mayur Pawashe 3c8ebd921f Merge pull request #1792 from sparkle-project/1.x-sync
Sync SPM + changelog changes
2021-03-07 09:23:13 -08:00
Zorg 579e7bd98b Add Persian localizations 2021-03-06 23:56:24 -08:00
Zorg 6d548efb2b Sync localization changes from 1.x 2021-03-06 23:51:21 -08:00
Zorg 2179eb1e39 Upload release distribution only for Xcode 12 builds currently 2021-03-06 23:19:25 -08:00
Zorg 3ded119af5 Include Xcode version in artifact upload 2021-03-06 22:47:49 -08:00
Zorg 018d4ea630 Reference relative path 2021-03-06 22:14:27 -08:00
Zorg ef68656783 Test validity of archived products and upload distribution in CI 2021-03-06 21:53:31 -08:00
Kornel aeffb2710a Changelog 2021-03-06 20:56:07 -08:00
Kornel 7c223ef0d1 Changelog 2021-03-06 20:54:45 -08:00
Zorg 724e9eb79e Fight SPM retagging
https://github.com/sparkle-project/Sparkle/commit/b5c9539f16de5b8647418fc467c6ca8fd5c8d22c
2021-03-06 20:20:08 -08:00
Jonas Zaugg 59c2c7358f Update make-release-package.sh
Now provides an error and exits when not complying with SemVer
2021-03-06 20:19:18 -08:00
Jonas Zaugg dc7b2f2030 Update make-release-package.sh
Only check and update tag in Package.swift when not running a CI build. As long as GitHub actions are reserved for tests, this should be ok as this is a "fake" update of Package.swift anyway. If you ever use GitHub actions for releases, you'll probably have to rethink the tagging logic once again
2021-03-06 20:19:04 -08:00
Jonas Zaugg 78a0d4e4e7 Checks SemVer and default to force tagging 2021-03-06 20:18:45 -08:00
Jonas Zaugg cd8794acce Various fixes to SPM logic
Improves prompt asking to force move tag (default is NO, but can be triggered after `make release`). Fixes issues with single quotes in make-release-package.sh.
2021-03-06 20:18:23 -08:00
Jonas Zaugg fd940884c8 Include tag instead of version in Package.swift 2021-03-06 20:16:41 -08:00
Zorg e76e34ead8 Rename SPM zip
https://github.com/sparkle-project/Sparkle/commit/891afd44c7075e699924ed9b81d8dc94a5111dfd#diff-507d750ad623604486faa5c9772800e8a019c7675a08688e94bde91872c0f1d8
2021-03-06 20:16:06 -08:00
Mayur Pawashe 2dd324d316 Merge pull request #1789 from sparkle-project/relocate-tools
Move helper tools into executables directory of framework
2021-03-02 22:25:18 -08:00
Mayur Pawashe 9e7548c4ff Merge pull request #1790 from sparkle-project/propogate-errors
Propagate errors from installer and agent to Sparkle
2021-03-01 19:53:14 -08:00
Zorg e21f7c4e87 Ensure startInstallationToURL method populates error object 2021-02-28 23:47:14 -08:00
Zorg 370fdb8368 Fix auto-synthesize warning 2021-02-28 23:47:07 -08:00
Zorg d3f6370828 Re-add SUSignatureError because I didn't see Swift code using it 2021-02-28 23:27:18 -08:00
Zorg efa9cc20d0 Fix tests 2021-02-28 23:20:06 -08:00
Zorg 7d8e3059ec Add and use SUAgentInvalidationError 2021-02-28 22:23:58 -08:00
Zorg f400b27cb2 Re-add __attribute__((noreturn)) attribute 2021-02-28 22:20:32 -08:00
Zorg f43b5ee3c3 Propagate agent errors to Sparkle 2021-02-28 22:14:35 -08:00
Zorg 1526a024b8 Propagate installer errors to Sparkle 2021-02-28 21:40:17 -08:00
Zorg 5cd1d3c824 Move helper tools into executables directory of framework 2021-02-28 10:25:42 -08:00
Mayur Pawashe 8a868914e5 Merge pull request #1786 from sparkle-project/bump-unarchiving-test-timeout-2x
Bump unarchiving tests timeout from 7 seconds to 30 seconds (2.x)
2021-02-22 07:44:40 -08:00
Zorg f5ee4dedb4 Bump unarchiving tests timeout from 7 seconds to 30 seconds 2021-02-21 18:05:51 -08:00
Mayur Pawashe ef23e7d65e Merge pull request #1781 from sparkle-project/add-release-distribution-2x
Add building distribution in Release in CI (2.x)
2021-02-21 17:51:00 -08:00
Mayur Pawashe d29d3f97a5 Merge pull request #1784 from sparkle-project/bz2-make-fallback-2x
Add fallback to bz2 when building Sparkle distribution (2.x)
2021-02-21 17:50:19 -08:00
Zorg a1cba4dd91 Add fallback to bz2 when building Sparkle distribution 2021-02-21 17:21:02 -08:00
Zorg 699a9df7bf Add building distribution in Release in CI 2021-02-21 15:42:43 -08:00
Mayur Pawashe 5aa68fa82b Merge pull request #1778 from sparkle-project/user-disable-automatic
Revert logic that prevented users from disabling automatic downloads
2021-02-21 15:01:56 -08:00
Mayur Pawashe adc62f8e34 Merge pull request #1777 from sparkle-project/installer-progress-locale-symlink
Remove locale symlinks in installer progress tool
2021-02-21 08:47:38 -08:00
Zorg f977a92e4c Revert logic that prevented users from disabling automatic downloads
In 2.x, updates can be downloaded automatically and presented later even if they can't be installed automatically without user intervention. Users need to in control and be able to disable automatic downloads regardless of developer's Info.plist intention.
2021-02-21 08:33:32 -08:00
Zorg dd24e8d938 Remove locale symlinks in installer progress tool 2021-02-21 08:27:59 -08:00
Mayur Pawashe 03f20a05a8 Merge pull request #1776 from sparkle-project/error-messages
Improve error messages developers run into
2021-02-21 07:14:59 -08:00
Mayur Pawashe 7ecc624afb Merge pull request #1774 from sparkle-project/delegate-methods
Add download, extract, skip delegate methods from 1.x
2021-02-21 07:13:53 -08:00
Zorg e331afddb1 Add host name of bundle in potential user facing error messages 2021-02-20 21:50:45 -08:00
Zorg 45581d5658 Log to users to check for Autoupdate console logs 2021-02-20 21:32:34 -08:00
Zorg 9931992912 Provide URL to troubleshoot XPC timed out issues 2021-02-20 21:09:57 -08:00
Zorg df3d9e2b14 Update error messages to specify Sparkle 2
This makes it more clear the developer is using Sparkle 2.
2021-02-20 20:48:32 -08:00
Zorg e148659cbb Add userDidSkipThisVersion case for informational updates 2021-02-20 20:33:58 -08:00
Mayur Pawashe 0a8443c94a Merge pull request #1773 from sparkle-project/lovette-patch-2
Correct generate_appcast -s command line argument usage help (2.x)
2021-02-20 20:00:56 -08:00
Lance Lovette 0e26a3e27a Correct generate_appcast -s command line argument usage help
Fixes sparkle-project/Sparkle#1766
2021-02-20 19:46:34 -08:00
Zorg ea472ae3f0 Add updater:shouldPostponeRelaunchForUpdate: 1.x stub 2021-02-20 19:40:02 -08:00
Zorg 59326e80d4 Add 1.x willInstallUpdateOnQuit:immediateInstallationBlock: stub 2021-02-20 19:32:21 -08:00
Zorg 3c0962b137 Add delegate methods for downloading/extracting updates 2021-02-20 19:05:24 -08:00
Zorg 2d666b4d84 Add updater:userDidSkipThisVersion: delegate method 2021-02-20 00:38:12 -08:00
Mayur Pawashe c822f88cf1 Merge pull request #1767 from sparkle-project/generate-appcast-priv-dsa-flag
Fix -f command line argument handling (2.x)
2021-02-17 20:32:33 -08:00
Lance Lovette 16dc6c2b5b Fix -f command line argument handling
https://github.com/sparkle-project/Sparkle/issues/1763
2021-02-17 20:14:34 -08:00
Mayur Pawashe 08a7122b36 Merge pull request #1761 from sparkle-project/real-time-2
Use wall time for our updater scheduled check timer
2021-02-14 08:48:58 -08:00
Zorg 8792137fda Use wall time for our updater scheduled check timer 2021-02-14 00:40:08 -08:00
Mayur Pawashe 25820ccd4b Merge pull request #1758 from sparkle-project/flat-package-mpkg
Support mpkg for updating/installing flat non-archived packages
2021-02-13 11:12:56 -08:00
Zorg 1290b974de Support mpkg for updating/installing flat non-archived packages 2021-02-13 10:04:08 -08:00
Mayur Pawashe c39370e64b Merge pull request #1745 from sparkle-project/flat-package-2x
Add support for updating/installing from flat non-archived packages
2021-02-10 22:23:46 -08:00
Mayur Pawashe 0b9bacfd0e Merge pull request #1755 from sparkle-project/not-found-reporting
Alter update not found error message
2021-02-07 11:59:49 -08:00
Kornel ad545813f0 Merge pull request #1754 from grit96/1748-2.x
Apply custom headers to app download (2.x)
2021-02-07 15:02:19 +00:00
Geraint White 3f226ccdd7 Apply custom headers to app download
The custom headers added in #489 only applied to the appcast download.
This makes them apply to the app download as well for the case when both are hosted behind authentication.
2021-02-07 10:05:08 +00:00
Zorg 13a36cb904 Add fallback to legacy showUpdateNotFoundWithAcknowledgement method 2021-02-06 23:46:06 -08:00
Zorg c5def52133 Update user driver methods for passing error to updates not found 2021-02-06 23:31:29 -08:00
Zorg 6b0d9f0de2 Tell user if they are running newer version than latest appcast item
This ports https://github.com/sparkle-project/Sparkle/pull/1427 to 2.x
2021-02-06 23:26:51 -08:00
Zorg a9254d1e02 Create alert using NSError for update not found error 2021-02-06 23:00:44 -08:00
Mayur Pawashe 2b9a02c825 Merge pull request #1753 from sparkle-project/fix-swallow-scheduled-ui-error
Don't swallow errors for scheduled driver after update is shown
2021-02-06 10:42:00 -08:00
Zorg 9d335b1233 Don't swallow errors for scheduled driver after update is shown 2021-02-05 21:42:24 -08:00
Mayur Pawashe 43379af33e Merge pull request #1747 from sparkle-project/fix-unimplemented-preventsAutoupdate-warning
Fix minor unimplemented preventsAutoupdate synthesize warning
2021-01-31 21:48:36 -08:00
Zorg 4c14d7d556 Fix minor unimplemented preventsAutoupdate synthesize warning 2021-01-31 21:34:02 -08:00
Zorg afe03b7161 Fix compile errors in generate_appcast 2021-01-30 23:24:50 -08:00
Zorg 79a9c50d2d Add support for updating/installing from flat packages
With these changes, modern pkg's should no longer need to be archived.

Only guided package installations are supported for flat packages. Specifying an interactive package installation type will result in a rejection. If the file URL has a ".pkg" suffix it is by default assumed to be a guided pkg installation now, which relieves the burden of needing to previously specify sparkle:installationType in the app cast item enclosure, in this case (for 2.x). Moreover, this relieves the burden of developers needing to archive their pkg for Sparkle.
2021-01-30 22:59:09 -08:00
Mayur Pawashe c5add680aa Merge pull request #1736 from sparkle-project/phased-group-rollout-2x
Port phased group rollout to 2.x
2021-01-30 19:13:28 -08:00
Zorg e8ebf23504 Compute current date only once for all app cast items 2021-01-30 18:09:39 -08:00
Mayur Pawashe da5be8902c Merge pull request #1741 from sparkle-project/remove-disable-automatic-skip
Remove hiding skip button on automatic updates logic
2021-01-30 12:45:21 -08:00
Zorg 7cffceb1f7 Remove hiding skip button on automatic updates
If user opts-out of automatic downloads (eg via app pref), they should be able to skip.

This logic for detecting minimumAutoupdateVersion present isn't sufficient and consistent enough, chooses to have skip visible in cases updates aren't prevented.
2021-01-30 08:25:54 -08:00
Zorg 6c846d0fad Combine phasedUpdateGroup / background flags 2021-01-29 22:21:26 -08:00
Zorg 044313db59 Remove redundant method 2021-01-29 22:15:50 -08:00
Zorg e089b9b435 Filter supported app cast items before finding the best item
This fixes scenarios where delegates may not take min/max OS version or phased update groups in account (and they shouldn't).
2021-01-29 21:45:58 -08:00
Zorg 98dc6314a5 Remove unused delegate method addition 2021-01-24 23:44:24 -08:00
Zorg 915786e11f Fix hostSupportsItem: returning YES too early 2021-01-24 23:39:33 -08:00
Zorg 60fcc89b7e Make phased rollout interval an app cast element not an enclosure one
Previous behavior doesn't work properly with delta update items. They should not be treated separately.
2021-01-24 23:21:18 -08:00
Zorg f9d421f851 Update from previous version if newest item doesn't pass rollout 2021-01-24 21:48:33 -08:00
Zorg 27d7058e0e Don't track if update was downloaded or checked in background
Note the prior check was also wrong, it should have used the background flag from the app cast check, not the download driver.
2021-01-24 21:22:24 -08:00
Zorg 03503d37b6 Fix SUUpdateGroupIdentifierKey not being read from user defaults 2021-01-24 21:21:42 -08:00
Zorg 0364e01c3a Remove method not used publicly in SUPhasedUpdateGroupInfo.h 2021-01-24 20:18:56 -08:00
Zorg bc0e338cde Use new update group for next downloaded update if applicable 2021-01-24 20:17:10 -08:00
Zorg d97dbf7ba0 Remove unused header import 2021-01-24 18:18:01 -08:00
Zorg 9818eff9a2 Add support for phased group updates to 2.x 2021-01-24 18:14:48 -08:00
Mayur Pawashe 4767ef60ec Merge pull request #1733 from sparkle-project/alert-state
Hide skip and later buttons in appropriate scenarios
2021-01-24 10:35:53 -08:00
Zorg e197f3093a Update hiding skip button case with checking minimumAutoupdateVersion 2021-01-24 10:25:45 -08:00
Zorg 1d930b585e Merge branch '2.x' into alert-state 2021-01-24 10:20:11 -08:00
Mayur Pawashe 6da14f7c46 Merge pull request #1735 from sparkle-project/prevent-autoupdate-2x
Port preventing new version from being auto installed to 2.x
2021-01-24 10:16:42 -08:00
Zorg 5ca8984c10 Port preventing new version from being auto installed to 2.x
Original PR for master: https://github.com/sparkle-project/Sparkle/pull/1688
2021-01-24 00:21:47 -08:00
Zorg 27f31a2913 Change capitalization 2021-01-23 21:32:51 -08:00
Zorg 3e544c7d26 Use "Install On Quit" localization again 2021-01-23 21:30:47 -08:00
Zorg 507255224a Fix hidden state for automatic install button and add comments 2021-01-23 20:50:07 -08:00
Zorg c1381d48d1 Add comments and rename some title alert strings to match 1.x 2021-01-23 19:29:50 -08:00
Zorg c3ce4f624b Hide skip button when developer enables automatic downloads too 2021-01-23 18:15:58 -08:00
Zorg 0a35f9d807 Hide skip and later buttons in appropriate scenarios 2021-01-23 17:23:04 -08:00
Mayur Pawashe fd209ced12 Merge pull request #1730 from sparkle-project/migrate-keys
Add export/import options to generate_keys
2021-01-23 16:38:33 -08:00
Zorg d85c1df752 Add options to export and import private/public key pair 2021-01-23 07:51:32 -08:00
Zorg 4fdd01052b Add option to store a specified private+public key pair directly
This is useful for migrating keys from one machine to another.
2021-01-23 01:43:41 -08:00
Kornel 1278b426f2 Merge pull request #1726 from zorgiepoo/cancheckforupdates 2021-01-19 11:59:23 +00:00
Kornel e880f34f7c Merge branch '2.x' into cancheckforupdates 2021-01-19 11:41:12 +00:00
Kornel 1d178a9a19 Merge pull request #1722 from zorgiepoo/important-1x-fixes 2021-01-19 11:38:22 +00:00
Kornel 22af258dc8 Merge pull request #1728 from zorgiepoo/about-blank-fix-2x
Ignore opening about:blank URLs (2.x)
2021-01-19 11:36:28 +00:00
Zorg 01d19ca92e Ignore opening about:blank URLs
Fix from 8f19f6a8cc which I regressed accidentally.
2021-01-18 09:12:16 -08:00
Zorg 173ccc845a Fix project references from previous commit of updating bin scripts 2021-01-17 22:07:20 -08:00
Zorg a0401fade9 Update and sync bin directory from 1.x 2021-01-17 21:58:02 -08:00
Zorg c6a89eb32b Integrate "Remove locale symlinks"
https://github.com/sparkle-project/Sparkle/commit/d4d4c68ad2e11ecdf21b2a71d45710cec4834c0c
2021-01-17 19:31:44 -08:00
Zorg f7906c45c0 Fix typo 2021-01-17 17:24:29 -08:00
Zorg 6d0f7fce26 Remove outdated user driver any thread comments 2021-01-17 17:23:11 -08:00
Zorg 6308b262a0 Preserve showCanCheckForUpdates: method on user driver 2021-01-17 17:17:49 -08:00
Zorg 2066cd7232 Migrate canCheckForUpdates property from user driver -> updater 2021-01-17 17:01:48 -08:00
Zorg 64d2ee1b5d Integrate "Remove max size from update alert" (#1676)
https://github.com/sparkle-project/Sparkle/pull/1676
2021-01-17 13:14:26 -08:00
Zorg 7896b5ab44 Remove extraneous [] in ReadMe 2021-01-17 12:24:17 -08:00
Zorg c70b39ba79 Fix SUHost nullability compile errors in unit tests 2021-01-16 21:10:25 -08:00
Zorg 7c7968b2f2 Fix UIDelegate not being set from master
4390eb9eb2
2021-01-16 20:45:05 -08:00
Zorg ae81bd27a2 Update resources from master branch 2021-01-16 20:42:26 -08:00
Zorg fd6d480d3d Remove executable bit from SUHost.h/.m 2021-01-16 20:37:14 -08:00
Zorg fc18529767 Add test link in test app
https://github.com/sparkle-project/Sparkle/commit/1b209e6726a4244e131a2ab0d3c1d0098c619794
2021-01-16 20:35:27 -08:00
Zorg 6fc5011362 Integrate "tiny fixes"
https://github.com/sparkle-project/Sparkle/commit/208b0dc49a79bfea604b1c10cc1b0e50a02f7e3d
2021-01-16 20:33:52 -08:00
pierswalter 176ff8f3df Update SUSystemProfiler.m
Masked sysctl hw.cputype value when evaluating the CPU type.
Used macros from mach/machine.h instead of magic numbers.
Added support for ARM in evaluation of hw.cpusubtype.
2021-01-16 20:26:04 -08:00
Zorg f64436165b Check OS in -hostSupportsItem: 2021-01-16 20:19:15 -08:00
Zorg 154b702552 Parse and serialize osString appcast item property 2021-01-16 20:14:52 -08:00
Jake Fenton c03cc0fa17 check if SUBundleName is set before normalizing
When changing the name of an app, there's a couple things to do in order
to ensure auto-updates still work:

1. set SUBundle Name. This basically tells Sparkle "ey, expect an app
of {SUBundleName}.(app|pkg) instead of the normal name."
2. set `SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME` in
commonConfig.xccconfig to reset the name of the app.

in (2), we always used the host's bundle name, instead of checking to
see if SUBundleName was set, which means normalization doesn't work as
expected during app name changes.
2021-01-16 20:00:10 -08:00
Zorg f858b99f93 Add hr Sparkle.strings file I forgot to add previously 2021-01-16 19:52:19 -08:00
Michael Buckley 85f41927f3 Integrate "Annotate SUHost for nullability" 2021-01-16 19:52:02 -08:00
Julian Mayer d8a8282b60 fix 2021-01-16 19:48:05 -08:00
Julian Mayer a6ffe0fa71 #1352 2021-01-16 19:47:46 -08:00
Zorg 523542ad90 Re-add Croatian (hr) localization
I may have accidentally removed this.
2021-01-16 19:40:34 -08:00
Quinn Taylor 57d9a780b8 Fix second bold sentence in read-only update alert dialog. (#1515)
• Updated error dialog code in SUBasicUpdateDriver, and created a local variable to reuse `[aHost name]`.
• Updated content of Sparkle.strings files, splitting existing affected translations into 2 chunks each.
• Fixed the Catalan translation, which was using an old string key.
• Removed a few unnecessary comments in the Polish translation.
2021-01-16 19:25:44 -08:00
Zorg 8d6d81c58f Integrate "Improved error when running from translocated location"
Except correctly.

https://github.com/sparkle-project/Sparkle/pull/1392/files
2021-01-16 18:54:38 -08:00
Zorg 7a228c7e1d Integrate "fix: read SUAutomaticallyUpdate from Info.plist"
https://github.com/sparkle-project/Sparkle/commit/4f47fb02db4d2572dbd8e9822f7a985ee80bb556
2021-01-16 18:29:36 -08:00
Zorg 6e326f3cea Integrate trying to preserve Finder tags in 2.x
https://github.com/sparkle-project/Sparkle/commit/1081dcdda187a9be5635594d388090f78de940f9
2021-01-16 18:27:41 -08:00
Zorg 3c0e02f333 Integrate "Fix #1061 & #835: Sparkle clients polling too frequently"
https://github.com/sparkle-project/Sparkle/pull/1135
2021-01-16 18:13:58 -08:00
Zorg 32b0ca2e0f Fix build failure due to removed INSTALL.markdown 2021-01-12 20:19:59 -08:00
Kornel 6316c53aba Merge pull request #1720 from zorgiepoo/readme-sync 2021-01-10 22:52:01 +00:00
Zorg 8fc7cadf69 Update internal docs regarding 2.x 2021-01-10 11:10:59 -08:00
Zorg cb5eb0e47d Update repo readme & docs to sync with 1.x 2021-01-10 11:05:54 -08:00
Maurice Parker ea11447ab2 Don't initialize the webview if we don't show release notes (#1713) 2021-01-06 14:39:00 +00:00
Kornel 8a3cc2e073 Merge pull request #1711 from thebluepotato/fix-catch-22-2.x 2021-01-05 14:45:50 +00:00
Jonas Zaugg 03fb6d969f Match changes made to 1.x branch
Fixes the issue of Package.swift being updated after tag, see #1710.
2021-01-05 15:37:21 +01:00
Kornel d4fb14f1fd Merge pull request #1705 from zorgiepoo/remove-async-user-driver 2021-01-03 21:38:20 +00:00
Zorg ec4b113d17 Add assertion checks for user driver methods called from main thread 2021-01-03 10:57:49 -08:00
Boy van Amstel ace5d99a27 Update INSTALL to include submodule init step
The install description currently fails to notify the user that they should install the git submodule(s) present in the repo.

This causes `make release` to fail.
2021-01-03 15:19:03 +00:00
Zorg 164e0e4f9a Adopt WKWebView
We fallback to legacy WebView in two cases:

* On systems prior to macOS 10.11 (it may be possible to support WKWebView in 10.10, but due to an 10.11+ only API I didn't bother putting in the effort)
* For apps using the downloader XPC service which are most likely sandboxed apps without an outgoing network entitlement. WKWebView doesn't function in that case (FB6993802 - https://github.com/feedback-assistant/reports/issues/1)

Additional notes:

* Added an abstraction for using WebView or WKWebView
* Web view is created and inserted programmatically rather than from the nib which has previously caused issues (and is not allowed for WKWebView prior to 10.12 due to some NSCoding bug).
* We need to rely on WKWebView private API for drawing transparent background (FB7539179 - https://github.com/feedback-assistant/reports/issues/81). Additional notes in the code.
* We always inject a custom stylesheet for dark mode colors and default font family/size (for WKWebView).
* This should also improve the Catalyst support story (#1482)
2021-01-03 10:10:57 +00:00
Mayur Pawashe 09178f70e9 Migrate to GitHub Actions CI (2.x) (#1706) 2021-01-03 10:08:35 +00:00
Zorg 3bc20cb096 Add noreturn attributes to command line user driver methods 2020-12-31 11:17:55 -08:00
Zorg 80cecd37b5 Fix compile error with missing '[' 2020-12-31 11:16:11 -08:00
Zorg 7951b81b69 Eliminate assumption that user driver calls are invoked in any thread
This reduces friction in creating a SPUUserDriver. This assumption that the calls could be made from any thread is a relic of the past of separating the user driver into a different process from the updater/scheduler, which is no longer sane or supported.

This should speed up things very slightly too.
2020-12-31 11:00:59 -08:00
Kornel 066da58f4d Merge pull request #1703 from sparkle-project/base-internationalization-2.x 2020-12-29 21:36:32 +00:00
Zorg 5e5aebffd3 Reduce code duplication by using SUAdHocCodeSigning 2020-12-28 15:35:45 -08:00
Zorg 98eef51931 Fix Test Application by disabling hardened runtime for XPC helper 2020-12-28 15:24:03 -08:00
Zorg 5e0b3f2a19 Add localization strings files for Test Application 2020-12-28 15:20:37 -08:00
Zorg 48a1379dbe Add strings files for SUUpdateAlert and SUUpdatePermissionPrompt 2020-12-28 15:13:28 -08:00
Zorg 3038218ea7 Enable base internationalization
Fix issues with Test Application.
2020-12-28 14:48:59 -08:00
Charles Srstka 238fd42bb3 Support getting app icon from asset catalog 2020-12-10 08:56:53 +00:00
Martin Pilkington eac4522817 System profiler privacy and transparency (#1690) 2020-11-30 13:12:48 +00:00
Kornel 94d05336a6 Merge pull request #1664 from skelpo/improve-generator-tools 2020-10-13 12:35:14 +01:00
Gwynne Raskind 93e4fd9424 Fix generate_appcast so links to localized release notes are embedded as full URLs instead of unescaped filenames. This makes them load reliably in complex contexts (such as the presence of characters like spaces in the filenames). 2020-10-12 12:43:43 -05:00
Gwynne Raskind 741ec1a08b Further cleanup generate_keys and its new "lookup-only mode". 2020-10-06 08:14:44 -05:00
Gwynne Raskind 7a8ead559b Clean up generate_keys/main.swift quite a bit - more comments, better output to console, cleaner error reporting 2020-10-06 07:54:08 -05:00
Kornel c802a38c92 Merge pull request #1662 from zorgiepoo/2.x-module-imports 2020-10-04 12:37:14 +01:00
Zorg 8947a6e50d Merge branch '2.x' into 2.x-module-imports 2020-10-03 11:10:58 -07:00
Kornel 5e73e70322 Merge pull request #1660 from zorgiepoo/2.x-double-quote-include 2020-10-03 14:13:52 +01:00
Zorg e2bf94df7e Fix more missing import warnings 2020-10-03 01:59:29 -07:00
Zorg a266b400cb Add more missing module imports 2020-10-03 01:54:53 -07:00
Zorg 7b4c648812 Use module imports to avoid warnings from clients 2020-10-03 01:14:50 -07:00
Zorg d38fd92668 Use double quote includes in a bunch of other places I missed 2020-10-03 00:41:59 -07:00
Zorg 772e610537 Set CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER instead 2020-10-03 00:38:15 -07:00
Zorg 02e11f3c3a Add -Wno-quoted-include-in-framework-header to ConfigCommon 2020-10-03 00:10:53 -07:00
Zorg 8c7adbdca7 Use double quote includes with pragma ignore warning 2020-10-03 00:10:24 -07:00
Kornel 852d678585 Merge pull request #1656 from skelpo/merge-from-1.x 2020-09-23 21:13:50 +01:00
Gwynne Raskind e3ba2388e8 Fix tests to actually build 2020-09-23 07:36:55 -05:00
Denis Dzyubenko 6f1fceb7d4 generate_appcast follow symbolic links
When archives are stored as symlinks e.g. due to storing binary files in a
git-annex repository, everything works file except file size in the generate
feed xml file. This patch makes generate_appcast correctly determine file size
by following the symlink

(cherry picked from commit 7233bb93e7)
2020-09-23 07:28:12 -05:00
Bi11 bc6d15a13c Support App Store URL scheme in release note webview
(cherry picked from commit f2fc729b69)
2020-09-23 07:27:51 -05:00
Brad Andalman 65cab6a14d generate_appcast can update the release notes element’s URL when required
Previously, generate_appcast could only add or remove the release notes element for an update. This was probably fine, because it was unlikely to change: the release notes URL was determined by the SUFeedURL.

However, now that —release-notes-url-prefix was added, the release notes element CAN change. So, with this commit, if the release notes element is present for an update, the URL will be set correctly.

(cherry picked from commit 7c7e924ed4)
2020-09-23 07:26:54 -05:00
Kornel 923f15220f Merge pull request #1648 from oneeightyg/feature-1646-generate-appcast-output-filename 2020-09-23 07:26:36 -05:00
Kornel 5fcc9a8aa9 Merge pull request #1644 from oneeightyg/feature-1642-release-notes-url-prefix
Add —release-notes-url-prefix to generate_appcast

(cherry picked from commit 7ea72a2af4)
2020-09-23 07:24:03 -05:00
Kornel 500d97d8ff Merge pull request #1635 from thebluepotato/spm-xcframework-2.x 2020-08-29 14:02:45 +01:00
Jonas Zaugg d1367393c2 Travis Xcode updated to newer beta 2020-08-29 02:02:24 +02:00
Jonas Zaugg 404b67a256 Mirror changes made to 1.x branch
Fixup Travis, build through Xcode scheme, etc.
2020-08-03 02:36:04 +02:00
Jonas Zaugg de8de29df2 Mirror changes made to the spm-xcframework branch and include SparkleCore 2020-08-03 02:09:39 +02:00
Jonas Zaugg 6a55563307 Add SPM binary target support 2020-08-03 02:06:48 +02:00
Kornel 438f4a21d5 Merge pull request #1636 from skelpo/forward-fixes 2020-08-01 20:58:28 +01:00
Gwynne Raskind 32bb57c029 Cosmetic fixes to ConfigCommon.xcconfig. Disable COPY_PHASE_STRIP in ConfigCommonRelease.xcconfig to silence a large number of warnings about failing to strip codesigned binaries. 2020-07-25 02:20:53 -05:00
Gwynne Raskind 1c77f59214 Fix incorrect paths in project file 2020-07-25 02:20:08 -05:00
Gwynne Raskind a95f1592cd Fix several dozen warnings. Fix several things to actually respect the 10.9 minimum of the beta. 2020-07-25 02:19:50 -05:00
Gwynne Raskind e7f8161ae4 Update last migration check version of project and schemes as of Xcode 12's checks. Fix how WMO is enabled for Swift code in Release builds. 2020-07-25 02:17:07 -05:00
Gwynne Raskind 9422bf16ae Forward-port improvements to generate_appcast from main branch (overridable download URL prefixes, extracting archives to uniqued output directory names during generation, -h flag to print usage, support for specifying Ed25519 key as string on command line, much smarter args parsing, ability to override keychain used to find signing keys) 2020-07-24 20:43:22 -05:00
Gwynne Raskind 418068e902 Forward-port PR #1499 (localized release notes in appcast) to 2.x 2020-07-24 20:33:35 -05:00
Gwynne Raskind 04b2122fed SUPublicEDKey expects to be a string, not data. Sigh. 2020-07-22 14:15:43 -05:00
Gwynne Raskind bdffcb0dd5 Disable the ability to create synchronizable keys for now. Requires entitlements on the generate tool which is a giant pain in the rear. Tweak the output a bit more so it's nice and consistent. 2020-07-22 10:52:01 -05:00
Gwynne Raskind be25c2ac64 Add the ability to make a generated signing key syncable over iCloud Keychain. Heavily overhauls the UI to actually explain things a little and behave how it's supposed to. 2020-07-22 10:45:02 -05:00
Gwynne Raskind 8487a24584 Default the Distribution scheme to build Release because who cares 2020-07-22 07:52:22 -05:00
Gwynne Raskind 820fdadfd7 Forward-port the fix for the stupid use of backticks in an echo command in build-docs.sh 2020-07-22 07:52:06 -05:00
Gwynne Raskind 1343c27805 Forward-port the newer generate_keys and sign_update tools (or at least their inclusion in the build) from 1.x, including changing the distribution archive from bzip2 to xz. 2020-07-22 07:51:45 -05:00
Kornel Lesiński 7acb6c4292 Revert "Add dependencies to "Set Git Version Info" Run Script phase"
This reverts commit 9592e35d1c.
2020-07-20 21:29:54 +01:00
Jordan Rose 9592e35d1c Add dependencies to "Set Git Version Info" Run Script phase
This keeps it from running when nothing's changed, which keeps Xcode
from re-signing the framework when nothing's changed, which keeps
downstream clients from re-copying the framework when nothing's
changed.
2020-07-16 15:40:39 +01:00
Jordan Rose e7e20e6ac8 Represent invalid public keys and signatures explicitly
Rather than using a valid-but-incorrect public key or signature to
make sure a failure to parse turns into a failure to validate, only
return a public key / signature when it is both present and at least
minimally valid. Syntactically invalid public keys / signatures are
also logged explicitly.
2020-06-25 00:01:09 +01:00
Jordan Rose 2b4b2a4443 SUDSAVerifierTest -> SUSignatureVerifierTest
The file got renamed, but the test class did not.
No functionality change.
2020-06-25 00:01:09 +01:00
Jordan Rose bd601b2f8c If a signature is present but invalid, don't just ignore it
Otherwise, a typo in an Ed25519 signature could lead to falling back
to DSA.
2020-06-25 00:01:09 +01:00
Jordan Rose b137b7f072 Test SUSignatureVerifier with Ed25519 keys 2020-06-25 00:01:09 +01:00
Jordan Rose 705638799c Allow relative URLs in appcasts
The base URL is taken from the server response rather than from the
original requested URL to account for redirects.
2020-06-23 22:40:53 +01:00
Jordan Rose 6b47d3fe90 Remove classes from test target that are already in Sparkle.framework
Avoids "Class SUCodeSigningVerifier is implemented in both
Sparkle.framework/Versions/A/Sparkle and
Sparkle Unit Tests.xctest/Contents/MacOS/Sparkle Unit Tests.
One of the two will be used. Which one is undefined."
2020-06-23 22:37:50 +01:00
Jordan Rose 3e000a897f Test post-validation of code-signed binaries
This gets more complicated, since binaries can be just code-signed, or
use both code signing and DSA keys, or be rotating keys for one or the
other.

The code signing test cases emulate certificate rotation by changing
the "identifier" for the bundle; the script used to sign each bundle
(with ad hoc signing) is included to support future expansion of
testing.
2020-06-16 21:13:39 +01:00
Jordan Rose b969c31f07 Test SUUpdateValidator's post-validation logic
The actual tests here are the same as pre-validation; things only get
complicated when validating with code signing. The setup's a little
more involved though, since we need a supposedly-downloaded bundle to
do anything.

Also test invalid signatures, which are not always the same as absent
signatures.
2020-06-16 21:13:39 +01:00
Jordan Rose 299157c3e7 Start SUUpdateValidatorTest with prevalidation testing 2020-06-16 21:13:39 +01:00
Philippe Casgrain 3a8040ae2e Fixed typo in sign_update usage 2020-06-16 13:19:43 +01:00
Philippe Casgrain 9a74b23f7f Replaced deprecated method
-initWithBase64Encoding has been deprecated since OS X 10.9, and that
is our deployment target.
2020-06-16 13:19:43 +01:00
672 changed files with 43913 additions and 26405 deletions

No files matched your search

@@ -0,0 +1,32 @@
---
name: Enhancements and Bug Fixes
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]
## Possible Fix
[not obligatory, but suggest fixes or reasons for the bug]
## Version
[please specify versions of Sparkle this is applicable to]
@@ -0,0 +1,35 @@
---
name: Sparkle doesn't work in my app
about: Problems with integration, unexpected errors using Sparkle
title: ''
assignees: ''
---
<!--
The answer to your issue is probably already in Console.app on your computer.
Please use Console.app and search for Sparkle.
Please try troubleshooting steps:
https://github.com/sparkle-project/Sparkle#troubleshooting
-->
### Description of the problem
### Do you use Sandboxing in your app?
### Version of `Sparkle.framework` in the latest version of your app
### Version of `Sparkle.framework` in the old version of app that your users have (or N/A)
### Sparkle's output from Console.app
```
```
### Steps to reproduce the behavior
[The more information provided and pasted verbatim, the easier it will be to diagnose an issue. If you can provide the affected application/binary and XML feed to reproduce an issue, share them]
+21
View File
@@ -0,0 +1,21 @@
(Insert summary of your pull request here)
Fixes # (issue)
## Misc Checklist
- [ ] 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
## Testing
I tested and verified my change by using one or multiple of these methods:
- [ ] Sparkle Test App
- [ ] Unit Tests
- [ ] My own app
- [ ] Other (please specify)
(Describe all the cases that were tested)
macOS version tested: [place version here]
+111
View File
@@ -0,0 +1,111 @@
name: Build & Tests
on:
push:
branches: [ 2.x, master ]
pull_request:
branches: [ 2.x, master ]
jobs:
build:
strategy:
matrix:
xcode: ['xcode26', 'xcode16.4']
include:
- xcode: 'xcode16.4'
xcode-path: '/Applications/Xcode_16.4.app/Contents/Developer'
upload-dist: true
run-analyzer: true
macos: 'macos-15'
- xcode: 'xcode26'
xcode-path: '/Applications/Xcode_26.0.app'
upload-dist: false
run-analyzer: false
macos: 'macos-15'
name: Build and Test Sparkle
runs-on: ${{ matrix.macos }}
permissions:
pull-requests: write
steps:
- name: Checkout
uses: actions/checkout@v4
with:
submodules: true
fetch-depth: 0
- name: Build Unit Tests
env:
DEVELOPER_DIR: ${{ matrix.xcode-path }}
run: |
xcodebuild build-for-testing -project Sparkle.xcodeproj -scheme Distribution -enableCodeCoverage YES -derivedDataPath build
- name: Run Unit Tests
env:
DEVELOPER_DIR: ${{ matrix.xcode-path }}
run: |
xcodebuild test-without-building -project Sparkle.xcodeproj -scheme Distribution -enableCodeCoverage YES -derivedDataPath build
- name: Build UI Tests
env:
DEVELOPER_DIR: ${{ matrix.xcode-path }}
run: |
xcodebuild build-for-testing -project Sparkle.xcodeproj -scheme UITests -configuration Debug -derivedDataPath build
- name: Run UI Tests
env:
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 > analyze_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 "warning:" analyze_output.txt | grep -q -v "dependency scan of"; then
echo "analyzestatus=0" >> $GITHUB_OUTPUT
else
echo "analyzestatus=1" >> $GITHUB_OUTPUT
fi
- name: Extract Analyzed Warnings
if: ${{ success() && matrix.run-analyzer && github.event_name == 'pull_request' && steps.findwarnings.outputs.analyzestatus == '0' }}
id: warnings
run: |
{
echo 'content<<EOF'
cat analyze_output.txt
echo 'EOF'
} >> $GITHUB_OUTPUT
- name: Post Analyzed Warnings
if: ${{ success() && matrix.run-analyzer && github.event_name == 'pull_request' && steps.findwarnings.outputs.analyzestatus == '0' }}
uses: mshick/add-pr-comment@v2
with:
allow-repeats: false
message: "``` ${{ steps.warnings.outputs.content }} ```"
- name: Build Release Distribution
env:
DEVELOPER_DIR: ${{ matrix.xcode-path }}
run: |
xcodebuild build -project Sparkle.xcodeproj -scheme Distribution -configuration Release -derivedDataPath build
- name: Archive Test Results
if: failure()
uses: actions/upload-artifact@v4
with:
name: build-logs
path: build/Logs
- name: Upload Distribution
if: ${{ success() && matrix.upload-dist }}
uses: actions/upload-artifact@v4
with:
name: Sparkle-distribution-${{ matrix.xcode }}.tar.xz
path: build/Build/Products/Release/sparkle_dist.tar.xz
+101
View File
@@ -0,0 +1,101 @@
name: "Create Draft Release"
env:
BUILDDIR: "build"
DEVELOPER_DIR: "/Applications/Xcode_16.4.app/Contents/Developer"
on:
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 }}
cancel-in-progress: true
jobs:
release:
name: "Publish binaries for release"
runs-on: macos-15
steps:
- name: "Checkout sources"
uses: actions/checkout@v4
with:
token: ${{ secrets.BOT_PERSONAL_ACCESS_TOKEN }}
submodules: true
fetch-depth: 0
- name: "Extract latest changes from CHANGELOG"
run: |
./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: |
if [[ ! -z "${{ github.event.inputs.prereleaseSuffix }}" ]]; then
echo "PRERELEASE_VERSION=true" >> $GITHUB_ENV
else
echo "PRERELEASE_VERSION=false" >> $GITHUB_ENV
fi
- 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.BOT_PERSONAL_ACCESS_TOKEN }}
- name: "Push the updated package description"
env:
GITHUB_TOKEN: ${{ secrets.BOT_PERSONAL_ACCESS_TOKEN }}
run: git push
- name: "Draft a release"
uses: softprops/action-gh-release@v2
with:
draft: true
prerelease: ${{ env.PRERELEASE_VERSION }}
target_commitish: ${{ github.ref_name }}
name: "${{ github.event.inputs.marketingVersion }}${{ github.event.inputs.prereleaseSuffix }}"
tag_name: "${{ github.event.inputs.marketingVersion }}${{ github.event.inputs.prereleaseSuffix }}"
fail_on_unmatched_files: true
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
+4
View File
@@ -41,3 +41,7 @@ Carthage/Build
Network Trash Folder
Temporary Items
.apdisk
# Swift Package Manager
/.build
.swiftpm
-3
View File
@@ -1,3 +0,0 @@
[submodule "Vendor/ed25519"]
path = Vendor/ed25519
url = https://github.com/orlp/ed25519
-7
View File
@@ -1,7 +0,0 @@
os: osx
language: objective-c
osx_image:
- xcode10.3
- xcode11.4
script:
- set -o pipefail && xcodebuild test -project Sparkle.xcodeproj -scheme Distribution -derivedDataPath build -enableCodeCoverage YES | xcpretty
+2 -1
View File
@@ -19,7 +19,7 @@ NS_ASSUME_NONNULL_BEGIN
@protocol SPUInstallerAgentProtocol;
@interface AgentConnection : NSObject
SPU_OBJC_DIRECT_MEMBERS @interface AgentConnection : NSObject
- (instancetype)initWithHostBundleIdentifier:(NSString *)bundleIdentifier delegate:(id<AgentConnectionDelegate>)delegate;
@@ -28,6 +28,7 @@ NS_ASSUME_NONNULL_BEGIN
@property (nonatomic, readonly, nullable) id<SPUInstallerAgentProtocol> agent;
@property (nonatomic, readonly) BOOL connected;
@property (nonatomic, nullable) NSError *invalidationError;
@end
+59 -26
View File
@@ -10,27 +10,26 @@
#import "SPUMessageTypes.h"
#import "SPUInstallerAgentProtocol.h"
#import "SUInstallerAgentInitiationProtocol.h"
#import "SUCodeSigningVerifier.h"
#import "SULog.h"
#include "AppKitPrevention.h"
@interface AgentConnection () <NSXPCListenerDelegate, SUInstallerAgentInitiationProtocol>
@property (nonatomic) NSXPCListener *xpcListener;
@property (nonatomic, nullable) NSXPCConnection *activeConnection;
@property (nonatomic, nullable) id<SPUInstallerAgentProtocol> agent;
@property (nonatomic, weak) id<AgentConnectionDelegate> delegate;
@property (nonatomic) BOOL connected;
@end
@implementation AgentConnection
{
NSXPCListener *_xpcListener;
NSXPCConnection *_activeConnection;
__weak id<AgentConnectionDelegate> _delegate;
}
@synthesize xpcListener = _xpcListener;
@synthesize activeConnection = _activeConnection;
@synthesize agent = _agent;
@synthesize delegate = _delegate;
@synthesize connected = _connected;
@synthesize invalidationError = _invalidationError;
- (instancetype)initWithHostBundleIdentifier:(NSString *)bundleIdentifier delegate:(id<AgentConnectionDelegate>)delegate
{
@@ -47,62 +46,96 @@
- (void)startListener
{
[self.xpcListener resume];
[_xpcListener resume];
}
- (void)invalidate
{
self.delegate = nil;
_delegate = nil;
[self.activeConnection invalidate];
self.activeConnection = nil;
[_activeConnection invalidate];
// Don't need to set _activeConnection to nil, we don't expect new connections
[self.xpcListener invalidate];
self.xpcListener = nil;
[_xpcListener invalidate];
_xpcListener = nil;
}
- (BOOL)listener:(NSXPCListener *)__unused listener shouldAcceptNewConnection:(NSXPCConnection *)newConnection
{
if (self.activeConnection != nil) {
if (_activeConnection != nil) {
SULog(SULogLevelError, @"Error: Rejecting new connection for agent due already having an active connection");
[newConnection invalidate];
return NO;
}
// Hardening but not critical for security
NSError *validationError = nil;
SUValidateConnectionStatus validationStatus = [SUCodeSigningVerifier validateConnection:newConnection options:SUValidateConnectionOptionDefault error:&validationError];
switch (validationStatus) {
case SUValidateConnectionStatusSetCodeSigningRequirementSuccess:
break;
case SUValidateConnectionStatusSetNoRequirementSuccess:
break;
case SUValidateConnectionStatusAPIFailure:
case SUValidateConnectionStatusCodeSigningRequirementFailure:
case SUValidateConectionNoSupportedValidationMethodFailure:
SULog(SULogLevelError, @"Error: Rejecting new connection for agent due to failing validation of XPC connection with status %lu and error: %@", validationStatus, validationError.localizedDescription);
[newConnection invalidate];
return NO;
}
newConnection.exportedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUInstallerAgentInitiationProtocol)];
newConnection.exportedObject = self;
newConnection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SPUInstallerAgentProtocol)];
self.activeConnection = newConnection;
_activeConnection = newConnection;
__weak AgentConnection *weakSelf = self;
__weak __typeof__(self) weakSelf = self;
newConnection.interruptionHandler = ^{
[weakSelf.activeConnection invalidate];
dispatch_async(dispatch_get_main_queue(), ^{
__typeof__(self) strongSelf = weakSelf;
if (strongSelf != nil) {
[strongSelf->_activeConnection invalidate];
}
});
};
newConnection.invalidationHandler = ^{
dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf.delegate agentConnectionDidInvalidate];
__typeof__(self) strongSelf = weakSelf;
if (strongSelf != nil) {
[strongSelf->_delegate agentConnectionDidInvalidate];
}
});
};
_agent = newConnection.remoteObjectProxy;
[newConnection resume];
self.agent = newConnection.remoteObjectProxy;
return YES;
}
- (void)connectionDidInitiateWithReply:(void (^)(void))acknowledgement
{
dispatch_async(dispatch_get_main_queue(), ^{
self.connected = YES;
self->_connected = YES;
[self.delegate agentConnectionDidInitiate];
self.delegate = nil;
[self->_delegate agentConnectionDidInitiate];
});
acknowledgement();
if (acknowledgement != NULL) {
acknowledgement();
}
}
- (void)connectionWillInvalidateWithError:(NSError *)error
{
dispatch_async(dispatch_get_main_queue(), ^{
self->_invalidationError = error;
});
}
@end
+7 -3
View File
@@ -9,12 +9,16 @@
#import <Foundation/Foundation.h>
#import "SUUnarchiverProtocol.h"
@interface AppInstaller : NSObject
NS_ASSUME_NONNULL_BEGIN
- (instancetype)initWithHostBundleIdentifier:(NSString *)hostBundleIdentifier;
SPU_OBJC_DIRECT_MEMBERS @interface AppInstaller : NSObject
- (instancetype)initWithHostBundleIdentifier:(NSString *)hostBundleIdentifier homeDirectory:(NSString *)homeDirectory userName:(NSString *)userName;
- (void)start;
- (void)cleanupAndExitWithStatus:(int)status __attribute__((noreturn));
- (void)cleanupAndExitWithStatus:(int)status error:(NSError * _Nullable)error __attribute__((noreturn));
@end
NS_ASSUME_NONNULL_END
+514 -303
View File
File diff suppressed because it is too large. Load diff
+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
+124
View File
@@ -0,0 +1,124 @@
//
// 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 "SUBinaryDeltaCommon.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) {
#if SPARKLE_BUILD_LEGACY_DELTA_SUPPORT
NSError *archiveError = sparkleArchive.error;
if (archiveError != nil && [archiveError.domain isEqualToString:SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN] && archiveError.code == SPARKLE_DELTA_ARCHIVE_ERROR_CODE_BAD_MAGIC) {
// Retry with XAR archive if the magic value is unexpected
[sparkleArchive close];
id<SPUDeltaArchiveProtocol> xarArchive = [[SPUXarDeltaArchive alloc] initWithPatchFileForReading:patchFile];
SPUDeltaArchiveHeader *xarHeader = [xarArchive readHeader];
if (outHeader != NULL) {
*outHeader = xarHeader;
}
return xarArchive;
} else
#endif
{
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;
#if SPARKLE_BUILD_LEGACY_DELTA_SUPPORT
@synthesize xarContext = _xarContext;
#endif
@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[BINARY_DELTA_HASH_LENGTH];
unsigned char _afterTreeHash[BINARY_DELTA_HASH_LENGTH];
}
@synthesize compression = _compression;
@synthesize compressionLevel = _compressionLevel;
@synthesize fileSystemCompression = _fileSystemCompression;
@synthesize majorVersion = _majorVersion;
@synthesize minorVersion = _minorVersion;
@synthesize bundleCreationDate = _bundleCreationDate;
- (instancetype)initWithCompression:(SPUDeltaCompressionMode)compression compressionLevel:(uint8_t)compressionLevel fileSystemCompression:(bool)fileSystemCompression majorVersion:(uint16_t)majorVersion minorVersion:(uint16_t)minorVersion beforeTreeHash:(const unsigned char *)beforeTreeHash afterTreeHash:(const unsigned char *)afterTreeHash bundleCreationDate:(nullable NSDate *)bundleCreationDate
{
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));
_bundleCreationDate = bundleCreationDate;
}
return self;
}
- (unsigned char *)beforeTreeHash
{
return _beforeTreeHash;
}
- (unsigned char *)afterTreeHash
{
return _afterTreeHash;
}
@end
+113
View File
@@ -0,0 +1,113 @@
//
// 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
SPU_OBJC_DIRECT_MEMBERS @interface SPUDeltaArchiveHeader : NSObject
- (instancetype)initWithCompression:(SPUDeltaCompressionMode)compression compressionLevel:(uint8_t)compressionLevel fileSystemCompression:(bool)fileSystemCompression majorVersion:(uint16_t)majorVersion minorVersion:(uint16_t)minorVersion beforeTreeHash:(const unsigned char *)beforeTreeHash afterTreeHash:(const unsigned char *)afterTreeHash bundleCreationDate:(nullable NSDate *)bundleCreationDate;
@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;
@property (nonatomic, readonly, nullable) NSDate *bundleCreationDate;
@end
// Represents an item we read or write to in our delta archive
SPU_OBJC_DIRECT_MEMBERS @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
#if SPARKLE_BUILD_LEGACY_DELTA_SUPPORT
// xar_file context for Xar delta archiver
@property (nonatomic, nullable) const void *xarContext;
#endif
// Tracking length of item's data in data section, when encoding items and when extracting items
@property (nonatomic) uint64_t codedDataLength;
@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;
+4 -2
View File
@@ -12,13 +12,15 @@ NS_ASSUME_NONNULL_BEGIN
@class SUAppcastItem;
@interface SPUInstallationInfo : NSObject <NSSecureCoding>
SPU_OBJC_DIRECT_MEMBERS @interface SPUInstallationInfo : NSObject <NSSecureCoding>
- (instancetype)initWithAppcastItem:(SUAppcastItem *)appcastItem canSilentlyInstall:(BOOL)canSilentyInstall;
- (instancetype)initWithAppcastItem:(SUAppcastItem *)appcastItem canSilentlyInstall:(BOOL)canSilentlyInstall;
@property (nonatomic, readonly) SUAppcastItem *appcastItem;
@property (nonatomic, readonly) BOOL canSilentlyInstall;
@property (nonatomic) BOOL systemDomain;
@end
NS_ASSUME_NONNULL_END
+14 -4
View File
@@ -14,22 +14,30 @@
static NSString *SUAppcastItemKey = @"SUAppcastItem";
static NSString *SUCanSilentlyInstallKey = @"SUCanSilentlyInstall";
static NSString *SUSystemDomainKey = @"SUSystemDomain";
@implementation SPUInstallationInfo
@synthesize appcastItem = _appcastItem;
@synthesize canSilentlyInstall = _canSilentlyInstall;
@synthesize systemDomain = _systemDomain;
- (instancetype)initWithAppcastItem:(SUAppcastItem *)appcastItem canSilentlyInstall:(BOOL)canSilentlyInstall
- (instancetype)initWithAppcastItem:(SUAppcastItem *)appcastItem canSilentlyInstall:(BOOL)canSilentlyInstall systemDomain:(BOOL)systemDomain
{
self = [super init];
if (self != nil) {
_appcastItem = appcastItem;
_canSilentlyInstall = canSilentlyInstall;
_systemDomain = systemDomain;
}
return self;
}
- (instancetype)initWithAppcastItem:(SUAppcastItem *)appcastItem canSilentlyInstall:(BOOL)canSilentlyInstall
{
return [self initWithAppcastItem:appcastItem canSilentlyInstall:canSilentlyInstall systemDomain:NO];
}
- (nullable instancetype)initWithCoder:(NSCoder *)decoder
{
SUAppcastItem *appcastItem = [decoder decodeObjectOfClass:[SUAppcastItem class] forKey:SUAppcastItemKey];
@@ -38,13 +46,15 @@ static NSString *SUCanSilentlyInstallKey = @"SUCanSilentlyInstall";
}
BOOL canSilentlyInstall = [decoder decodeBoolForKey:SUCanSilentlyInstallKey];
return [self initWithAppcastItem:appcastItem canSilentlyInstall:canSilentlyInstall];
BOOL systemDomain = [decoder decodeBoolForKey:SUSystemDomainKey];
return [self initWithAppcastItem:appcastItem canSilentlyInstall:canSilentlyInstall systemDomain:systemDomain];
}
- (void)encodeWithCoder:(NSCoder *)coder
{
[coder encodeObject:self.appcastItem forKey:SUAppcastItemKey];
[coder encodeBool:self.canSilentlyInstall forKey:SUCanSilentlyInstallKey];
[coder encodeObject:_appcastItem forKey:SUAppcastItemKey];
[coder encodeBool:_canSilentlyInstall forKey:SUCanSilentlyInstallKey];
[coder encodeBool:_systemDomain forKey:SUSystemDomainKey];
}
+ (BOOL)supportsSecureCoding
+8 -5
View File
@@ -12,7 +12,7 @@
NS_ASSUME_NONNULL_BEGIN
@interface SPUInstallationInputData : NSObject <NSSecureCoding>
SPU_OBJC_DIRECT_MEMBERS @interface SPUInstallationInputData : NSObject <NSSecureCoding>
/*
* relaunchPath - path to application bundle to relaunch and listen for termination
@@ -21,16 +21,19 @@ NS_ASSUME_NONNULL_BEGIN
* downloadName - name of update archive in update directory
* signatures - signatures for the update that came from the appcast item
* decryptionPassword - optional decryption password for dmg archives
* expectedVersion - optional expected version of the new update
* expectedContentLength - optional expected content length of the new download archive
*/
- (instancetype)initWithRelaunchPath:(NSString *)relaunchPath hostBundlePath:(NSString *)hostBundlePath updateDirectoryPath:(NSString *)updateDirectoryPath downloadName:(NSString *)downloadName installationType:(NSString *)installationType signatures:(SUSignatures *)signatures decryptionPassword:(nullable NSString *)decryptionPassword;
- (instancetype)initWithRelaunchPath:(NSString *)relaunchPath hostBundlePath:(NSString *)hostBundlePath updateURLBookmarkData:(NSData *)updateURLBookmarkData installationType:(NSString *)installationType signatures:(SUSignatures * _Nullable)signatures decryptionPassword:(nullable NSString *)decryptionPassword expectedVersion:(NSString *)expectedVersion expectedContentLength:(uint64_t)expectedContentLength;
@property (nonatomic, copy, readonly) NSString *relaunchPath;
@property (nonatomic, copy, readonly) NSString *hostBundlePath;
@property (nonatomic, copy, readonly) NSString *updateDirectoryPath;
@property (nonatomic, copy, readonly) NSString *downloadName;
@property (nonatomic, copy, readonly) NSData *updateURLBookmarkData;
@property (nonatomic, copy, readonly) NSString *installationType;
@property (nonatomic, strong, readonly) SUSignatures *signatures;
@property (nonatomic, readonly, nullable) SUSignatures *signatures; // nullable because although not using signatures is deprecated, it's still supported
@property (nonatomic, copy, readonly, nullable) NSString *decryptionPassword;
@property (nonatomic, copy, readonly, nullable) NSString *expectedVersion;
@property (nonatomic, readonly) uint64_t expectedContentLength;
@end
+28 -23
View File
@@ -14,36 +14,40 @@
static NSString *SURelaunchPathKey = @"SURelaunchPath";
static NSString *SUHostBundlePathKey = @"SUHostBundlePath";
static NSString *SUUpdateDirectoryPathKey = @"SUUpdateDirectoryPath";
static NSString *SUDownloadNameKey = @"SUDownloadName";
static NSString *SUUpdateURLBookmarkDataKey = @"SUUpdateURLBookmarkData";
static NSString *SUSignaturesKey = @"SUSignatures";
static NSString *SUDecryptionPasswordKey = @"SUDecryptionPassword";
static NSString *SUInstallationTypeKey = @"SUInstallationType";
static NSString *SUExpectedVersionKey = @"SUExpectedVersion";
static NSString *SUExpectedContentLength = @"SUExpectedContentLength";
@implementation SPUInstallationInputData
@synthesize relaunchPath = _relaunchPath;
@synthesize hostBundlePath = _hostBundlePath;
@synthesize updateDirectoryPath = _updateDirectoryPath;
@synthesize downloadName = _downloadName;
@synthesize updateURLBookmarkData = _updateURLBookmarkData;
@synthesize signatures = _signatures;
@synthesize decryptionPassword = _decryptionPassword;
@synthesize installationType = _installationType;
@synthesize expectedVersion = _expectedVersion;
@synthesize expectedContentLength = _expectedContentLength;
- (instancetype)initWithRelaunchPath:(NSString *)relaunchPath hostBundlePath:(NSString *)hostBundlePath updateDirectoryPath:(NSString *)updateDirectoryPath downloadName:(NSString *)downloadName installationType:(NSString *)installationType signatures:(SUSignatures *)signatures decryptionPassword:(nullable NSString *)decryptionPassword
- (instancetype)initWithRelaunchPath:(NSString *)relaunchPath hostBundlePath:(NSString *)hostBundlePath updateURLBookmarkData:(NSData *)updateURLBookmarkData installationType:(NSString *)installationType signatures:(SUSignatures * _Nullable)signatures decryptionPassword:(nullable NSString *)decryptionPassword expectedVersion:(nonnull NSString *)expectedVersion expectedContentLength:(uint64_t)expectedContentLength
{
self = [super init];
if (self != nil) {
_relaunchPath = [relaunchPath copy];
_hostBundlePath = [hostBundlePath copy];
_updateDirectoryPath = [updateDirectoryPath copy];
_downloadName = [downloadName copy];
_updateURLBookmarkData = updateURLBookmarkData;
_installationType = [installationType copy];
assert(SPUValidInstallationType(_installationType));
_signatures = signatures;
_decryptionPassword = [decryptionPassword copy];
_expectedVersion = [expectedVersion copy];
_expectedContentLength = expectedContentLength;
}
return self;
}
@@ -60,13 +64,8 @@ static NSString *SUInstallationTypeKey = @"SUInstallationType";
return nil;
}
NSString *updateDirectoryPath = [decoder decodeObjectOfClass:[NSString class] forKey:SUUpdateDirectoryPathKey];
if (updateDirectoryPath == nil) {
return nil;
}
NSString *downloadName = [decoder decodeObjectOfClass:[NSString class] forKey:SUDownloadNameKey];
if (downloadName == nil) {
NSData *updateURLBookmarkData = [decoder decodeObjectOfClass:[NSData class] forKey:SUUpdateURLBookmarkDataKey];
if (updateURLBookmarkData == nil) {
return nil;
}
@@ -82,20 +81,26 @@ static NSString *SUInstallationTypeKey = @"SUInstallationType";
NSString *decryptionPassword = [decoder decodeObjectOfClass:[NSString class] forKey:SUDecryptionPasswordKey];
return [self initWithRelaunchPath:relaunchPath hostBundlePath:hostBundlePath updateDirectoryPath:updateDirectoryPath downloadName:downloadName installationType:installationType signatures:signatures decryptionPassword:decryptionPassword];
NSString *expectedVersion = [decoder decodeObjectOfClass:[NSString class] forKey:SUExpectedVersionKey];
uint64_t expectedContentLength = (uint64_t)[decoder decodeInt64ForKey:SUExpectedContentLength];
return [self initWithRelaunchPath:relaunchPath hostBundlePath:hostBundlePath updateURLBookmarkData:updateURLBookmarkData installationType:installationType signatures:signatures decryptionPassword:decryptionPassword expectedVersion:expectedVersion expectedContentLength:expectedContentLength];
}
- (void)encodeWithCoder:(NSCoder *)coder
{
[coder encodeObject:self.relaunchPath forKey:SURelaunchPathKey];
[coder encodeObject:self.hostBundlePath forKey:SUHostBundlePathKey];
[coder encodeObject:self.updateDirectoryPath forKey:SUUpdateDirectoryPathKey];
[coder encodeObject:self.installationType forKey:SUInstallationTypeKey];
[coder encodeObject:self.downloadName forKey:SUDownloadNameKey];
[coder encodeObject:self.signatures forKey:SUSignaturesKey];
if (self.decryptionPassword != nil) {
[coder encodeObject:self.decryptionPassword forKey:SUDecryptionPasswordKey];
[coder encodeObject:_relaunchPath forKey:SURelaunchPathKey];
[coder encodeObject:_hostBundlePath forKey:SUHostBundlePathKey];
[coder encodeObject:_updateURLBookmarkData forKey:SUUpdateURLBookmarkDataKey];
[coder encodeObject:_installationType forKey:SUInstallationTypeKey];
[coder encodeObject:_signatures forKey:SUSignaturesKey];
if (_decryptionPassword != nil) {
[coder encodeObject:_decryptionPassword forKey:SUDecryptionPasswordKey];
}
if (_expectedVersion != nil) {
[coder encodeObject:_expectedVersion forKey:SUExpectedVersionKey];
}
[coder encodeInt64:(int64_t)_expectedContentLength forKey:SUExpectedContentLength];
}
+ (BOOL)supportsSecureCoding
+7 -6
View File
@@ -10,10 +10,6 @@
NS_ASSUME_NONNULL_BEGIN
@class SUHost;
extern NSString *SPUAppcastItemArchiveKey;
// Order matters; higher stages have higher values.
typedef NS_ENUM(int32_t, SPUInstallerMessageType)
{
@@ -26,7 +22,8 @@ typedef NS_ENUM(int32_t, SPUInstallerMessageType)
SPUInstallationFinishedStage1 = 6,
SPUInstallationFinishedStage2 = 7,
SPUInstallationFinishedStage3 = 8,
SPUUpdaterAlivePing = 9
SPUUpdaterAlivePing = 9,
SPUInstallerError = 10
};
typedef NS_ENUM(int32_t, SPUUpdaterMessageType)
@@ -34,15 +31,19 @@ typedef NS_ENUM(int32_t, SPUUpdaterMessageType)
SPUInstallationData = 0,
SPUSentUpdateAppcastItemData = 1,
SPUResumeInstallationToStage2 = 2,
SPUUpdaterAlivePong = 3
SPUUpdaterAlivePong = 3,
SPUCancelInstallation = 4
};
BOOL SPUInstallerMessageTypeIsLegal(SPUInstallerMessageType oldMessageType, SPUInstallerMessageType newMessageType);
// Used by framework to communicate to installer (Autoupdate)
NSString *SPUInstallerServiceNameForBundleIdentifier(NSString *bundleIdentifier);
// Used by framework to communicate to progress agent tool (Updater)
NSString *SPUStatusInfoServiceNameForBundleIdentifier(NSString *bundleIdentifier);
// Used by progress agent tool to communicate to installer (Autoupdate)
NSString *SPUProgressAgentServiceNameForBundleIdentifier(NSString *bundleIdentifier);
NS_ASSUME_NONNULL_END
+6 -10
View File
@@ -7,24 +7,19 @@
//
#import "SPUMessageTypes.h"
#import "SUHost.h"
#include "AppKitPrevention.h"
NSString *SPUAppcastItemArchiveKey = @"SPUAppcastItemArchive";
// Tags added to the bundle identifier which is used as Mach service names
// These should be very short because length restrictions exist on earlier versions of macOS
// These should be very short because of length restrictions
#define SPARKLE_INSTALLER_TAG @"-spki"
#define SPARKLE_STATUS_TAG @"-spks"
#define SPARKLE_PROGRESS_TAG @"-spkp"
#define SPARKLE_PROGRESS_LAUNCH_INSTALLER_TAG @"-spkl"
// macOS 10.8 at least can't handle service names that are 64 characters or longer
// This was fixed some point after 10.8, but I'm not sure if it was fixed in 10.9 or 10.10 or 10.11
// If we knew when it was fixed, this could only be relevant to OS versions prior to that
#define MAX_SERVICE_NAME_LENGTH 63u
// macOS 10.8 couldn't handle service names that are >= 64 characters,
// but 10.9 raised this to >= 128 characters
#define MAX_SERVICE_NAME_LENGTH 127u
BOOL SPUInstallerMessageTypeIsLegal(SPUInstallerMessageType oldMessageType, SPUInstallerMessageType newMessageType)
{
@@ -55,9 +50,10 @@ BOOL SPUInstallerMessageTypeIsLegal(SPUInstallerMessageType oldMessageType, SPUI
case SPUInstallationFinishedStage3:
legal = (oldMessageType == SPUInstallationFinishedStage2);
break;
case SPUInstallerError:
case SPUUpdaterAlivePing:
// Having this state being dependent on other installation states would make the complicate our logic
// So just always allow this type of message
// So just always allow these type of messages
legal = YES;
break;
}
+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)
*/
SPU_OBJC_DIRECT_MEMBERS @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
+28
View File
@@ -0,0 +1,28 @@
//
// SPUXarDeltaArchive.h
// Autoupdate
//
// Created by Mayur Pawashe on 12/28/21.
// Copyright © 2021 Sparkle Project. All rights reserved.
//
#if SPARKLE_BUILD_LEGACY_DELTA_SUPPORT
#import <Foundation/Foundation.h>
#import "SPUDeltaArchiveProtocol.h"
#import "SPUDeltaCompressionMode.h"
NS_ASSUME_NONNULL_BEGIN
// Legacy container format for binary delta archives
SPU_OBJC_DIRECT_MEMBERS @interface SPUXarDeltaArchive : NSObject <SPUDeltaArchiveProtocol>
- (instancetype)initWithPatchFileForWriting:(NSString *)patchFile SPU_OBJC_DIRECT;
- (instancetype)initWithPatchFileForReading:(NSString *)patchFile SPU_OBJC_DIRECT;
@end
NS_ASSUME_NONNULL_END
#endif
+413
View File
@@ -0,0 +1,413 @@
//
// SPUXarDeltaArchive.m
// Autoupdate
//
// Created by Mayur Pawashe on 12/28/21.
// Copyright © 2021 Sparkle Project. All rights reserved.
//
#if SPARKLE_BUILD_LEGACY_DELTA_SUPPORT
#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
@implementation SPUXarDeltaArchive
{
NSMutableDictionary<NSString *, NSValue *> *_fileTable;
NSString *_patchFile;
xar_t _x;
int32_t _xarMode;
}
@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 (_x != NULL) {
xar_close(_x);
_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 = _patchFile;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
// Sparkle's XAR delta archives have been superseded by Sparkle's own format
xar_t x = xar_open(patchFile.fileSystemRepresentation, READ);
#pragma clang diagnostic pop
if (x == NULL) {
_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;
}
_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(_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[BINARY_DELTA_HASH_LENGTH] = {0};
getRawHashFromDisplayHash(rawExpectedBeforeHash, expectedBeforeHash);
unsigned char rawExpectedAfterHash[BINARY_DELTA_HASH_LENGTH] = {0};
getRawHashFromDisplayHash(rawExpectedAfterHash, expectedAfterHash);
// I wasn't able to figure out how to retrieve the compression options from xar,
// so we will use default flags to indicate the info isn't available
return [[SPUDeltaArchiveHeader alloc] initWithCompression:SPUDeltaCompressionModeDefault compressionLevel:0 fileSystemCompression:false majorVersion:majorDiffVersion minorVersion:minorDiffVersion beforeTreeHash:rawExpectedBeforeHash afterTreeHash:rawExpectedAfterHash bundleCreationDate:nil];
}
- (void)writeHeader:(SPUDeltaArchiveHeader *)header
{
NSString *patchFile = _patchFile;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
// Sparkle's XAR delta archives have been superseded by Sparkle's own format
xar_t x = xar_open(patchFile.fileSystemRepresentation, WRITE);
#pragma clang diagnostic pop
if (x == NULL) {
_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;
}
_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: {
_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
// misordering 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 (_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(_fileTable, _x, relativeFilePath, filePath);
if (newFile == NULL) {
_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 (_error != nil) {
return;
}
BOOL exitedEarly = NO;
xar_iter_t iter = xar_iter_new();
for (xar_file_t file = xar_file_first(_x, iter); file; file = xar_file_next(iter)) {
char *pathCString;
#if HAS_XAR_GET_SAFE_PATH
#pragma clang diagnostic push
#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 (_error != nil) {
return NO;
}
assert(item.itemFilePath != nil);
assert(item.xarContext != NULL);
xar_file_t file = item.xarContext;
if (xar_extract_tofile(_x, file, item.itemFilePath.fileSystemRepresentation) != 0) {
_error = [NSError errorWithDomain:SPARKLE_DELTA_XAR_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_XAR_ARCHIVE_ERROR_CODE_EXTRACT_FAILURE userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to extract xar file entry to %@", item.itemFilePath] }];
return NO;
}
return YES;
}
@end
#endif
+327 -135
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[BINARY_DELTA_HASH_LENGTH] = {0};
if (!getRawHashOfTreeWithVersion(beforeHash, source, majorDiffVersion)) {
if (verbose) {
fprintf(stderr, "\n");
}
@@ -129,13 +102,13 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi
}
return NO;
}
if (![beforeHash isEqualToString:expectedBeforeHash]) {
if (memcmp(beforeHash, expectedBeforeHash, BINARY_DELTA_HASH_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,9 +139,11 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi
return NO;
}
progressCallback(3/6.0);
progressCallback(3/7.0);
if (!copyTree(source, destination)) {
NSFileManager *fileManager = [[NSFileManager alloc] init];
if (!copyTree(fileManager, source, destination)) {
if (verbose) {
fprintf(stderr, "\n");
}
@@ -167,131 +152,338 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi
}
return NO;
}
// Preserve file creation date only for the root item if the date is recorded
// (requires major version 4 or later)
NSDate *bundleCreationDate = header.bundleCreationDate;
if (bundleCreationDate != nil) {
NSError *setFileCreationDateError = nil;
if (![fileManager setAttributes:@{NSFileCreationDate: bundleCreationDate} ofItemAtPath:destination error:&setFileCreationDateError]) {
fprintf(stderr, "\nWarning: failed to set file creation date: %s", setFileCreationDateError.localizedDescription.UTF8String);
}
}
progressCallback(4/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];
BOOL removedFile = NO;
const char *value;
if (!xar_prop_get(file, DELETE_KEY, &value) || (!hasExtractKeyAvailable && !xar_prop_get(file, DELETE_THEN_EXTRACT_OLD_KEY, &value))) {
// 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
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;
}
// Decide if we need to preserve original file permissions from the original file
// applyBinaryDeltaToFile() normally preserves file permissions on the file it's replacing.
// However this is not possible if the destination file we're patching is not writable.
// We also need to preserve permissions for clones except when we'll be changing permissions later anyway.
BOOL needsToCopyFilePermissions;
if (![fileManager isWritableFileAtPath:destinationFilePath]) {
// Remove the file non-writable we're patching that may cause issues
[fileManager removeItemAtPath:destinationFilePath error:NULL];
// We will need to preserve permissions if there is no need to make permission changes later on
needsToCopyFilePermissions = (commands & SPUDeltaItemCommandModifyPermissions) == 0;
} else {
needsToCopyFilePermissions = ((commands & SPUDeltaItemCommandClone) != 0) && ((commands & SPUDeltaItemCommandModifyPermissions) == 0);
}
if (!applyBinaryDeltaToFile(tempDiffFile, sourceDiffFilePath, destinationFilePath)) {
if (verbose) {
fprintf(stderr, "\n");
}
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;
}
if (needsToCopyFilePermissions) {
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], (unsigned int)(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];
dittoTask.executableURL = [NSURL fileURLWithPath:@"/usr/bin/ditto" isDirectory:NO];
dittoTask.arguments = @[@"--hfsCompression", destination, finalDestination];
// If we fail to apply file system compression, we will try falling back to not doing this
BOOL failedToApplyFileSystemCompression = NO;
NSError *launchError = nil;
if (![dittoTask launchAndReturnError:&launchError]) {
failedToApplyFileSystemCompression = YES;
fprintf(stderr, "\nWarning: failed to launch ditto task for file compression: %s", launchError.localizedDescription.UTF8String);
}
if (!failedToApplyFileSystemCompression) {
[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[BINARY_DELTA_HASH_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, BINARY_DELTA_HASH_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");
+35 -29
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,32 +30,52 @@
#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)
// Relative path of custom icon data that may be set on a bundle via a resource fork
#define CUSTOM_ICON_PATH @"/Icon\r"
// Each major version will be assigned a name of a color
// 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,
SUBinaryDeltaMajorVersion4 = 4,
};
#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;
// Additional compression methods for version 3 or 4 patches that we have for debugging are zlib, bzip2, none
#define COMPRESSION_METHOD_ARGUMENT_DESCRIPTION @"The compression method to use for generating delta updates. Supported methods for version 3 delta files are 'lzma' (best compression, slowest), 'lzfse' (good compression, fast), 'lz4' (worse compression, fastest), and 'default'. Note that version 2 delta files only support 'bzip2', and 'default' so other methods will be ignored if version 2 files are being generated. The 'default' compression for version 3 or 4 delta files is currently lzma."
//#define COMPRESSION_LEVEL_ARGUMENT_DESCRIPTION @"The compression level to use for generating delta updates. This only applies if the compression method used is bzip2 which accepts values from 1 - 9. A special value of 0 will use the default compression level."
// This is the same as CC_SHA1_DIGEST_LENGTH
// Major versions >= 4 use a crc32 hash (using a subset of these bytes) while older versions use a sha1 hash
#define BINARY_DELTA_HASH_LENGTH 20
SPUDeltaCompressionMode deltaCompressionModeFromDescription(NSString *description, BOOL *requestValid);
NSString *deltaCompressionStringFromMode(SPUDeltaCompressionMode mode);
extern int compareFiles(const FTSENT **a, const FTSENT **b);
extern NSData *hashOfFileContents(FTSENT *ent);
BOOL getRawHashOfTreeWithVersion(void *hashBuffer, NSString *path, uint16_t majorVersion);
BOOL getRawHashOfTreeAndFileTablesWithVersion(void *hashBuffer, NSString *path, uint16_t majorVersion, NSMutableDictionary<NSData *, NSMutableArray<NSString *> *> *hashToFileKeyDictionary, NSMutableDictionary<NSString *, NSData *> *fileKeyToHashDictionary);
NSString *displayHashFromRawHash(const unsigned char *hash);
void getRawHashFromDisplayHash(unsigned char *hash, NSString *hexHash);
extern NSString *hashOfTreeWithVersion(NSString *path, uint16_t majorVersion);
extern NSString *hashOfTree(NSString *path);
extern BOOL removeTree(NSString *path);
extern BOOL copyTree(NSString *source, NSString *dest);
extern BOOL copyTree(NSFileManager *fileManager, NSString *source, NSString *dest);
extern BOOL modifyPermissions(NSString *path, mode_t desiredPermissions);
extern NSString *pathRelativeToDirectory(NSString *directory, NSString *path);
NSString *temporaryFilename(NSString *base);
NSString *temporaryDirectory(NSString *base);
NSString *stringWithFileSystemRepresentation(const char*);
int latestMinorVersionForMajorVersion(SUBinaryDeltaMajorVersion majorVersion);
uint16_t latestMinorVersionForMajorVersion(SUBinaryDeltaMajorVersion majorVersion);
#endif
+299 -62
View File
@@ -7,8 +7,8 @@
//
#include "SUBinaryDeltaCommon.h"
#import "SUFileManager.h"
#include <CommonCrypto/CommonDigest.h>
#include <zlib.h> // for crc32()
#include <Foundation/Foundation.h>
#include <fcntl.h>
#include <stdio.h>
@@ -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 = SUBinaryDeltaMajorVersion4;
SUBinaryDeltaMajorVersion SUBinaryDeltaMajorVersionLatest = SUBinaryDeltaMajorVersion4;
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,12 +107,16 @@ 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:
return 1;
case SUBeigeMajorVersion:
case SUBinaryDeltaMajorVersion1:
return 2;
case SUBinaryDeltaMajorVersion2:
return 5;
case SUBinaryDeltaMajorVersion3:
return 3;
case SUBinaryDeltaMajorVersion4:
return 2;
}
return 0;
@@ -87,7 +159,7 @@ NSString *temporaryDirectory(NSString *base)
return stringWithFileSystemRepresentation(templateResult);
}
static void _hashOfBuffer(unsigned char *hash, const char *buffer, ssize_t bufferLength)
static void sha1HashOfBuffer(unsigned char *hash, const char *buffer, ssize_t bufferLength)
{
assert(bufferLength >= 0 && bufferLength <= UINT32_MAX);
CC_SHA1_CTX hashContext;
@@ -96,7 +168,59 @@ static void _hashOfBuffer(unsigned char *hash, const char *buffer, ssize_t buffe
CC_SHA1_Final(hash, &hashContext);
}
static BOOL _hashOfFileContents(unsigned char *hash, FTSENT *ent)
static BOOL crc32HashOfFileContents(uLong *outChecksum, FTSENT *ent, void *tempBuffer, size_t tempBufferSize)
{
uLong checksum = *outChecksum;
if (ent->fts_info == FTS_SL) {
char linkDestination[MAXPATHLEN + 1];
ssize_t linkDestinationLength = readlink(ent->fts_path, linkDestination, MAXPATHLEN);
if (linkDestinationLength < 0) {
perror("readlink");
return NO;
}
checksum = crc32(checksum, (const void *)linkDestination, (unsigned int)linkDestinationLength);
} else if (ent->fts_info == FTS_F) {
ssize_t fileSize = ent->fts_statp->st_size;
uint64_t encodedFileSize = (uint64_t)fileSize;
checksum = crc32(checksum, (const void *)&encodedFileSize, sizeof(encodedFileSize));
if (fileSize > 0) {
FILE *file = fopen(ent->fts_path, "rb");
if (file == NULL) {
perror("fopen");
return NO;
}
size_t bytesLeft = (size_t)fileSize;
while (bytesLeft > 0) {
size_t bytesToConsume = (bytesLeft >= tempBufferSize) ? tempBufferSize : bytesLeft;
if (fread(tempBuffer, bytesToConsume, 1, file) < 1) {
perror("fread");
fclose(file);
return NO;
}
checksum = crc32(checksum, tempBuffer, (uInt)bytesToConsume);
bytesLeft -= bytesToConsume;
}
fclose(file);
}
} else {
return NO;
}
*outChecksum = checksum;
return YES;
}
static BOOL sha1HashOfFileContents(unsigned char *hash, FTSENT *ent, void *tempBuffer, size_t tempBufferSize)
{
if (ent->fts_info == FTS_SL) {
char linkDestination[MAXPATHLEN + 1];
@@ -106,29 +230,39 @@ static BOOL _hashOfFileContents(unsigned char *hash, FTSENT *ent)
return NO;
}
_hashOfBuffer(hash, linkDestination, linkDestinationLength);
sha1HashOfBuffer(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) {
_hashOfBuffer(hash, NULL, 0);
if (fileSize <= 0) {
sha1HashOfBuffer(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,31 +271,40 @@ static BOOL _hashOfFileContents(unsigned char *hash, FTSENT *ent)
return YES;
}
NSData *hashOfFileContents(FTSENT *ent)
BOOL getRawHashOfTreeWithVersion(void *hashBuffer, NSString *path, uint16_t majorVersion)
{
unsigned char fileHash[CC_SHA1_DIGEST_LENGTH];
if (!_hashOfFileContents(fileHash, ent)) {
return nil;
}
return [NSData dataWithBytes:fileHash length:CC_SHA1_DIGEST_LENGTH];
return getRawHashOfTreeAndFileTablesWithVersion(hashBuffer, path, majorVersion, nil, nil);
}
NSString *hashOfTreeWithVersion(NSString *path, uint16_t majorVersion)
BOOL getRawHashOfTreeAndFileTablesWithVersion(void *hashBuffer, NSString *path, uint16_t majorVersion, NSMutableDictionary<NSData *, NSMutableArray<NSString *> *> *hashToFileKeyDictionary, NSMutableDictionary<NSString *, NSData *> *fileKeyToHashDictionary)
{
char pathBuffer[PATH_MAX] = { 0 };
if (![path getFileSystemRepresentation:pathBuffer maxLength:sizeof(pathBuffer)]) {
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;
CC_SHA1_Init(&hashContext);
const uLong initialCrc32Value = crc32(0L, Z_NULL, 0);
uLong crc32ChecksumValue = initialCrc32Value;
if (majorVersion < SUBinaryDeltaMajorVersion4) {
CC_SHA1_Init(&hashContext);
}
// Ensure the path uses filesystem-specific Unicode normalization #1017
NSString *normalizedPath = stringWithFileSystemRepresentation(pathBuffer);
@@ -171,48 +314,143 @@ 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)) {
continue;
}
NSString *relativePath = pathRelativeToDirectory(normalizedPath, stringWithFileSystemRepresentation(ent->fts_path));
if (relativePath.length == 0)
// Ignore icon resource fork data
if (relativePath.length == 0 || [relativePath isEqualToString:CUSTOM_ICON_PATH]) {
continue;
unsigned char fileHash[CC_SHA1_DIGEST_LENGTH];
if (!_hashOfFileContents(fileHash, ent)) {
return nil;
}
CC_SHA1_Update(&hashContext, fileHash, sizeof(fileHash));
NSData *fileHashKey;
if (majorVersion >= SUBinaryDeltaMajorVersion4) {
if (ent->fts_info == FTS_D) {
// No need to hash any further values for directories
// We hash relative file path and file type later
fileHashKey = nil;
} else {
uLong fileContentsChecksum = initialCrc32Value;
if (!crc32HashOfFileContents(&fileContentsChecksum, ent, tempBuffer, tempBufferSize)) {
fts_close(fts);
free(tempBuffer);
return NO;
}
uint64_t encodedFileContentsChecksum = fileContentsChecksum;
crc32ChecksumValue = crc32(crc32ChecksumValue, (const void *)&encodedFileContentsChecksum, sizeof(encodedFileContentsChecksum));
if (ent->fts_info == FTS_F) {
fileHashKey = [NSData dataWithBytes:&encodedFileContentsChecksum length:sizeof(encodedFileContentsChecksum)];
} else {
fileHashKey = nil;
}
}
} else {
unsigned char fileHash[CC_SHA1_DIGEST_LENGTH];
if (!sha1HashOfFileContents(fileHash, ent, tempBuffer, tempBufferSize)) {
fts_close(fts);
free(tempBuffer);
return NO;
}
CC_SHA1_Update(&hashContext, fileHash, sizeof(fileHash));
if (ent->fts_info == FTS_F) {
fileHashKey = [NSData dataWithBytes:fileHash length:sizeof(fileHash)];
} else {
fileHashKey = nil;
}
}
// For file hash tables we only track regular files
if (fileHashKey != nil) {
if (hashToFileKeyDictionary != nil) {
if (hashToFileKeyDictionary[fileHashKey] == nil) {
hashToFileKeyDictionary[fileHashKey] = [NSMutableArray array];
}
[hashToFileKeyDictionary[fileHashKey] addObject:relativePath];
}
if (fileKeyToHashDictionary != nil) {
fileKeyToHashDictionary[relativePath] = fileHashKey;
}
}
const char *relativePathBytes = [relativePath fileSystemRepresentation];
CC_SHA1_Update(&hashContext, relativePathBytes, (CC_LONG)strlen(relativePathBytes));
if (majorVersion >= SUBinaryDeltaMajorVersion4) {
crc32ChecksumValue = crc32(crc32ChecksumValue, (const void *)relativePathBytes, (uInt)strlen(relativePathBytes));
} else {
CC_SHA1_Update(&hashContext, relativePathBytes, (CC_LONG)strlen(relativePathBytes));
}
if (MAJOR_VERSION_IS_AT_LEAST(majorVersion, SUBeigeMajorVersion)) {
uint16_t mode = ent->fts_statp->st_mode;
uint16_t type = ent->fts_info;
uint16_t permissions = mode & PERMISSION_FLAGS;
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;
if (majorVersion >= SUBinaryDeltaMajorVersion4) {
crc32ChecksumValue = crc32(crc32ChecksumValue, (const void *)&type, sizeof(type));
crc32ChecksumValue = crc32(crc32ChecksumValue, (const void *)&hashedPermissions, sizeof(hashedPermissions));
} else {
CC_SHA1_Update(&hashContext, &type, sizeof(type));
CC_SHA1_Update(&hashContext, &permissions, sizeof(permissions));
CC_SHA1_Update(&hashContext, &hashedPermissions, sizeof(hashedPermissions));
}
}
free(tempBuffer);
fts_close(fts);
unsigned char hash[CC_SHA1_DIGEST_LENGTH];
CC_SHA1_Final(hash, &hashContext);
if (majorVersion >= SUBinaryDeltaMajorVersion4) {
uint64_t encodedCrc32ChecksumValue = crc32ChecksumValue;
memset(hashBuffer, 0, BINARY_DELTA_HASH_LENGTH);
memcpy(hashBuffer, &encodedCrc32ChecksumValue, sizeof(encodedCrc32ChecksumValue));
} else {
CC_SHA1_Final(hashBuffer, &hashContext);
}
return YES;
}
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 < BINARY_DELTA_HASH_LENGTH; blockIndex++) {
const char *currentBlock = hexString + blockIndex * 2;
char convertedBlock[3] = {currentBlock[0], currentBlock[1], '\0'};
hash[blockIndex] = (unsigned char)strtol(convertedBlock, NULL, 16);
}
}
NSString *displayHashFromRawHash(const unsigned char *hash)
{
char hexHash[BINARY_DELTA_HASH_LENGTH * 2 + 1] = {0};
for (size_t i = 0; i < BINARY_DELTA_HASH_LENGTH; i++) {
snprintf(hexHash + i * 2, 3, "%02x", hash[i]);
}
return @(hexHash);
}
NSString *hashOfTreeWithVersion(NSString *path, uint16_t majorVersion)
{
unsigned char hash[BINARY_DELTA_HASH_LENGTH] = {0};
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)
@@ -225,10 +463,9 @@ BOOL removeTree(NSString *path)
return [fileManager removeItemAtPath:path error:nil];
}
BOOL copyTree(NSString *source, NSString *dest)
BOOL copyTree(NSFileManager *fileManager, NSString *source, NSString *dest)
{
// SUFileManager will be more reliable for copying items especially across network mounts
return [[[SUFileManager alloc] init] copyItemAtURL:[NSURL fileURLWithPath:source] toURL:[NSURL fileURLWithPath:dest] error:NULL];
return [fileManager copyItemAtURL:[NSURL fileURLWithPath:source] toURL:[NSURL fileURLWithPath:dest] error:NULL];
}
BOOL modifyPermissions(NSString *path, mode_t desiredPermissions)
+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
+575 -130
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,38 +22,54 @@
#include <sys/stat.h>
#include <unistd.h>
#include <sys/xattr.h>
#include <xar/xar.h>
#include "AppKitPrevention.h"
extern int bsdiff(int argc, const char **argv);
@interface CreateBinaryDeltaOperation : NSOperation
@property (copy) NSString *relativePath;
@property (strong) NSString *resultPath;
@property (strong) NSNumber *oldPermissions;
@property (strong) NSNumber *permissions;
@property (strong) NSString *_fromPath;
@property (strong) NSString *_toPath;
- (id)initWithRelativePath:(NSString *)relativePath oldTree:(NSString *)oldTree newTree:(NSString *)newTree oldPermissions:(NSNumber *)oldPermissions newPermissions:(NSNumber *)permissions;
@property (nonatomic, copy, readonly) NSString *relativePath;
@property (nonatomic, copy, readonly) NSString *clonedRelativePath;
@property (nonatomic, readonly) NSString *resultPath;
@property (nonatomic, readonly) NSNumber *oldPermissions;
@property (nonatomic, readonly) NSNumber *permissions;
@property (nonatomic, readonly) NSString *fromPath;
@property (nonatomic, readonly) BOOL changingPermissions;
- (id)initWithRelativePath:(NSString *)relativePath clonedRelativePath:(NSString *)clonedRelativePath oldTree:(NSString *)oldTree newTree:(NSString *)newTree oldPermissions:(NSNumber *)oldPermissions newPermissions:(NSNumber *)permissions changingPermissions:(BOOL)changingPermissions SPU_OBJC_DIRECT;
@end
@implementation CreateBinaryDeltaOperation
{
NSString *_toPath;
}
@synthesize relativePath = _relativePath;
@synthesize clonedRelativePath = _clonedRelativePath;
@synthesize resultPath = _resultPath;
@synthesize oldPermissions = _oldPermissions;
@synthesize permissions = _permissions;
@synthesize _fromPath = _fromPath;
@synthesize _toPath = _toPath;
@synthesize fromPath = _fromPath;
@synthesize changingPermissions = _changingPermissions;
- (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.oldPermissions = oldPermissions;
self.permissions = permissions;
self._fromPath = [oldTree stringByAppendingPathComponent:relativePath];
self._toPath = [newTree stringByAppendingPathComponent:relativePath];
_relativePath = [relativePath copy];
_clonedRelativePath = [clonedRelativePath copy];
_oldPermissions = oldPermissions;
_permissions = permissions;
_changingPermissions = changingPermissions;
if (clonedRelativePath == nil) {
_fromPath = [oldTree stringByAppendingPathComponent:relativePath];
} else {
_fromPath = [oldTree stringByAppendingPathComponent:clonedRelativePath];
}
_toPath = [newTree stringByAppendingPathComponent:relativePath];
}
return self;
}
@@ -58,47 +77,37 @@ extern int bsdiff(int argc, const char **argv);
- (void)main
{
NSString *temporaryFile = temporaryFilename(@"BinaryDelta");
const char *argv[] = { "/usr/bin/bsdiff", [self._fromPath fileSystemRepresentation], [self._toPath fileSystemRepresentation], [temporaryFile fileSystemRepresentation] };
const char *argv[] = { "/usr/bin/bsdiff", [_fromPath fileSystemRepresentation], [_toPath fileSystemRepresentation], [temporaryFile fileSystemRepresentation] };
int result = bsdiff(4, argv);
if (!result)
self.resultPath = temporaryFile;
if (result == 0) {
_resultPath = temporaryFile;
}
}
@end
#define INFO_HASH_KEY @"hash"
#define INFO_PATH_KEY @"path"
#define INFO_TYPE_KEY @"type"
#define INFO_PERMISSIONS_KEY @"permissions"
#define INFO_SIZE_KEY @"size"
static NSDictionary *infoForFile(FTSENT *ent)
{
NSData *hash = hashOfFileContents(ent);
if (!hash) {
return nil;
}
off_t size = (ent->fts_info != FTS_D) ? ent->fts_statp->st_size : 0;
assert(ent->fts_statp != NULL);
mode_t permissions = ent->fts_statp->st_mode & PERMISSION_FLAGS;
return @{ INFO_HASH_KEY: hash,
NSString *path = @(ent->fts_path);
assert(path != nil);
return @{ INFO_PATH_KEY: path != nil ? path : @"",
INFO_TYPE_KEY: @(ent->fts_info),
INFO_PERMISSIONS_KEY: @(permissions),
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,12 +183,18 @@ static BOOL shouldSkipDeltaCompression(NSDictionary *originalInfo, NSDictionary
return YES;
}
if ([(NSNumber *)originalInfo[INFO_TYPE_KEY] unsignedShortValue] != [(NSNumber *)newInfo[INFO_TYPE_KEY] unsignedShortValue]) {
unsigned short originalInfoType = [(NSNumber *)originalInfo[INFO_TYPE_KEY] unsignedShortValue];
unsigned short newInfoType = [(NSNumber *)newInfo[INFO_TYPE_KEY] unsignedShortValue];
if (originalInfoType != newInfoType || originalInfoType != FTS_F) {
// File types are different or they're not regular files
return YES;
}
if ([(NSData *)originalInfo[INFO_HASH_KEY] isEqual:(NSData *)newInfo[INFO_HASH_KEY]]) {
// this is possible if just the permissions have changed
NSString *originalPath = originalInfo[INFO_PATH_KEY];
NSString *newPath = newInfo[INFO_PATH_KEY];
// Skip delta if the files are equal in content
if ([[NSFileManager defaultManager] contentsEqualAtPath:originalPath andPath:newPath]) {
return YES;
}
@@ -205,11 +220,21 @@ static BOOL shouldSkipExtracting(NSDictionary *originalInfo, NSDictionary *newIn
return NO;
}
if ([(NSNumber *)originalInfo[INFO_TYPE_KEY] unsignedShortValue] != [(NSNumber *)newInfo[INFO_TYPE_KEY] unsignedShortValue]) {
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
return NO;
}
if (![(NSData *)originalInfo[INFO_HASH_KEY] isEqual:(NSData *)newInfo[INFO_HASH_KEY]]) {
NSString *originalPath = originalInfo[INFO_PATH_KEY];
NSString *newPath = newInfo[INFO_PATH_KEY];
// Don't skip extract if files/symlinks entries are not equal in content
// (note if the entries are directories, they are equal)
if (originalInfoType != FTS_D && ![[NSFileManager defaultManager] contentsEqualAtPath:originalPath andPath:newPath]) {
return NO;
}
@@ -221,26 +246,176 @@ 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;
}
BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchFile, SUBinaryDeltaMajorVersion majorVersion, BOOL verbose, NSError *__autoreleasing *error)
#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)
{
// 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;
}
if ([(NSNumber *)newInfo[INFO_TYPE_KEY] unsignedShortValue] != FTS_F) {
return nil;
}
{
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;
}
}
}
// 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;
}
// The old file must have the same type as the new one
if ([(NSNumber *)oldCloneInfo[INFO_TYPE_KEY] unsignedShortValue] != FTS_F) {
continue;
}
NSNumber *newPermissions = newInfo[INFO_PERMISSIONS_KEY];
if (outNewPermissions != NULL) {
*outNewPermissions = newPermissions;
}
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, 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];
@@ -262,7 +437,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]);
}
@@ -276,6 +451,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) {
@@ -289,6 +474,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 %@", (unsigned int)VALID_SPARKLE_EXECUTABLE_PERMISSIONS, permissions, @(ent->fts_path)] }];
}
return NO;
}
}
if (aclExists(ent)) {
if (verbose) {
fprintf(stderr, "\n");
@@ -304,16 +503,18 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
fprintf(stderr, "\n");
}
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Diffing code signed extended attributes are not supported. Detected extended attribute in before-tree on file %@", @(ent->fts_path)] }];
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Diffing code signed extended attributes are not supported. Detected extended attribute in before-tree on file %@. For removing code signed extended attributes and improving your bundle's structure, please see https://developer.apple.com/documentation/bundleresources/placing_content_in_a_bundle", @(ent->fts_path)] }];
}
return NO;
}
}
fts_close(fts);
NSString *beforeHash = hashOfTreeWithVersion(source, majorVersion);
if (!beforeHash) {
// This dictionary will help us keep track of clones
NSMutableDictionary<NSData *, NSMutableArray<NSString *> *> *beforeHashToFileKeyDictionary = (majorVersion >= SUBinaryDeltaMajorVersion3) ? [NSMutableDictionary dictionary] : nil;
unsigned char beforeHash[BINARY_DELTA_HASH_LENGTH] = {0};
if (!getRawHashOfTreeAndFileTablesWithVersion(beforeHash, source, majorVersion, beforeHashToFileKeyDictionary, nil)) {
if (verbose) {
fprintf(stderr, "\n");
}
@@ -351,7 +552,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;
@@ -361,6 +566,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) {
@@ -373,23 +588,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 %@", (unsigned int)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");
@@ -405,14 +621,54 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
fprintf(stderr, "\n");
}
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Diffing code signed extended attributes are not supported. Detected extended attribute in after-tree on file %@", @(ent->fts_path)] }];
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Diffing code signed extended attributes are not supported. Detected extended attribute in after-tree on file %@. For removing code signed extended attributes and improving your bundle's structure, please see https://developer.apple.com/documentation/bundleresources/placing_content_in_a_bundle", @(ent->fts_path)] }];
}
return NO;
}
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 && (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;
@@ -432,8 +688,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 = (majorVersion >= SUBinaryDeltaMajorVersion3) ? [NSMutableDictionary dictionary] : nil;
unsigned char afterHash[BINARY_DELTA_HASH_LENGTH] = {0};
if (!getRawHashOfTreeAndFileTablesWithVersion(afterHash, destination, majorVersion, nil, afterFileKeyToHashDictionary)) {
if (verbose) {
fprintf(stderr, "\n");
}
@@ -451,31 +710,53 @@ 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 {
#if SPARKLE_BUILD_LEGACY_DELTA_SUPPORT
archive = [[SPUXarDeltaArchive alloc] initWithPatchFileForWriting:temporaryFile];
#else
if (verbose) {
fprintf(stderr, "\n");
}
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileWriteUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to write to %@", temporaryFile] }];
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadUnknownError userInfo:@{ NSLocalizedDescriptionKey: @"Support for creating legacy delta updates is disabled" }];
}
return NO;
#endif
}
// Record creation date of root bundle item
NSDate *bundleCreationDate;
if (majorVersion >= SUBinaryDeltaMajorVersion4) {
NSError *fileAttributesError = nil;
NSDictionary<NSFileAttributeKey, id> *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:destination error:&fileAttributesError];
if (fileAttributes != nil) {
bundleCreationDate = fileAttributes[NSFileCreationDate];
} else {
bundleCreationDate = nil;
fprintf(stderr, "\nWarning: unable to retrieve file creation date of new bundle: %s", fileAttributesError.localizedDescription.UTF8String);
}
} else {
bundleCreationDate = nil;
}
SPUDeltaArchiveHeader *header = [[SPUDeltaArchiveHeader alloc] initWithCompression:compression compressionLevel:compressionLevel fileSystemCompression:foundFilesystemCompression majorVersion:majorVersion minorVersion:minorVersion beforeTreeHash:beforeHash afterTreeHash:afterHash bundleCreationDate:bundleCreationDate];
[archive writeHeader:header];
if (archive.error != nil) {
if (verbose) {
fprintf(stderr, "\n");
}
if (error != NULL) {
*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];
@@ -489,13 +770,105 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
return originalTreeState[key1] ? NSOrderedAscending : NSOrderedDescending;
}];
// Using a couple of heuristics we track if files have been moved to other locations within the app bundle
NSMutableDictionary<NSString *, NSString *> *frameworkVersionsSubstitutes = [NSMutableDictionary dictionary];
NSMutableDictionary<NSString *, NSString *> *fileSubstitutes = [NSMutableDictionary dictionary];
if (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 = xar_add_frombuffer(x, 0, [key fileSystemRepresentation], (char *)"", 1);
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]);
@@ -506,47 +879,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 = xar_add_frombuffer(x, 0, [key fileSystemRepresentation], (char *)"", 1);
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 = xar_add_frompath(x, 0, [key fileSystemRepresentation], [path fileSystemRepresentation]);
assert(newFile);
if (shouldDeleteThenExtract(originalInfo, newInfo)) {
if (MAJOR_VERSION_IS_AT_LEAST(majorVersion, SUBeigeMajorVersion)) {
xar_prop_set(newFile, DELETE_KEY, "true");
// 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 = (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];
}
@@ -554,37 +953,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) {
NSString *resultPath = operation.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 = xar_add_frompath(x, 0, [[operation relativePath] fileSystemRepresentation], [resultPath fileSystemRepresentation]);
assert(newFile);
xar_prop_set(newFile, BINARY_DELTA_KEY, "true");
unlink([resultPath fileSystemRepresentation]);
if (operation.permissions) {
xar_prop_set(newFile, MODIFY_PERMISSIONS_KEY, [[NSString stringWithFormat:@"%u", [operation.permissions unsignedShortValue]] UTF8String]);
if (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 *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 *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 *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;
}
}
+6 -1
View File
@@ -14,9 +14,14 @@
NS_ASSUME_NONNULL_BEGIN
#ifndef BUILDING_SPARKLE_TESTS
SPU_OBJC_DIRECT_MEMBERS
#endif
@interface SUBinaryDeltaUnarchiver : NSObject <SUUnarchiverProtocol>
- (instancetype)initWithArchivePath:(NSString *)archivePath updateHostBundlePath:(NSString *)updateHostBundlePath;
- (instancetype)initWithArchivePath:(NSString *)archivePath extractionDirectory:(NSString *)extractionDirectory updateHostBundlePath:(NSString *)updateHostBundlePath;
+ (BOOL)canUnarchivePath:(NSString *)path;
@end
+22 -17
View File
@@ -16,17 +16,12 @@
#include "AppKitPrevention.h"
@interface SUBinaryDeltaUnarchiver ()
@property (nonatomic, copy, readonly) NSString *archivePath;
@property (nonatomic, copy, readonly) NSString *updateHostBundlePath;
@end
@implementation SUBinaryDeltaUnarchiver
@synthesize archivePath = _archivePath;
@synthesize updateHostBundlePath = _updateHostBundlePath;
{
NSString *_archivePath;
NSString *_updateHostBundlePath;
NSString *_extractionDirectory;
}
+ (BOOL)canUnarchivePath:(NSString *)path
{
@@ -43,7 +38,11 @@
// We used to invoke mdimport on the bundle but this is not a very good approach.
// There's no need to do that for non-delta updates and for updates that contain no mdimporters.
// Moreover, updating the timestamp on the mdimporter bundles is what developers have to do anyway when shipping their new update outside of Sparkle
// Note: this is used from unit tests
+ (void)updateSpotlightImportersAtBundlePath:(NSString *)targetPath
#ifndef BUILDING_SPARKLE_TESTS
SPU_OBJC_DIRECT
#endif
{
NSURL *targetURL = [NSURL fileURLWithPath:targetPath];
// Only recurse if it's actually a directory. Don't recurse into a
@@ -73,17 +72,23 @@
}
}
- (instancetype)initWithArchivePath:(NSString *)archivePath updateHostBundlePath:(NSString *)updateHostBundlePath
- (instancetype)initWithArchivePath:(NSString *)archivePath extractionDirectory:(NSString *)extractionDirectory updateHostBundlePath:(NSString *)updateHostBundlePath
{
self = [super init];
if (self != nil) {
_archivePath = [archivePath copy];
_updateHostBundlePath = [updateHostBundlePath copy];
_extractionDirectory = [extractionDirectory copy];
}
return self;
}
- (void)unarchiveWithCompletionBlock:(void (^)(NSError * _Nullable))completionBlock progressBlock:(void (^ _Nullable)(double))progressBlock
- (BOOL)needsVerifyBeforeExtractionKey
{
return NO;
}
- (void)unarchiveWithCompletionBlock:(void (^)(NSError * _Nullable))completionBlock progressBlock:(void (^ _Nullable)(double))progressBlock waitForCleanup:(BOOL)__unused waitForCleanup
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
@autoreleasepool {
@@ -95,17 +100,17 @@
- (void)extractDeltaWithNotifier:(SUUnarchiverNotifier *)notifier
{
NSString *sourcePath = self.updateHostBundlePath;
NSString *targetPath = [[self.archivePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:[sourcePath lastPathComponent]];
NSString *sourcePath = _updateHostBundlePath;
NSString *targetPath = [_extractionDirectory stringByAppendingPathComponent:[sourcePath lastPathComponent]];
NSError *applyDiffError = nil;
BOOL success = applyBinaryDelta(sourcePath, targetPath, self.archivePath, NO, ^(double progress){
BOOL success = applyBinaryDelta(sourcePath, targetPath, _archivePath, NO, ^(double progress){
[notifier notifyProgress:progress];
}, &applyDiffError);
if (success) {
[[self class] updateSpotlightImportersAtBundlePath:targetPath];
[SUBinaryDeltaUnarchiver updateSpotlightImportersAtBundlePath:targetPath];
[notifier notifySuccess];
}
else {
@@ -113,6 +118,6 @@
}
}
- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], self.archivePath]; }
- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], _archivePath]; }
@end
+43 -2
View File
@@ -11,10 +11,51 @@
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
#ifndef BUILDING_SPARKLE_TESTS
#define SUCodeSigningVerifierDefinitionAttribute SPU_OBJC_DIRECT_MEMBERS
#else
#define SUCodeSigningVerifierDefinitionAttribute __attribute__((objc_runtime_name("SUTestCodeSigningVerifier")))
#endif
typedef NS_ENUM(NSUInteger, SUValidateConnectionStatus) {
SUValidateConnectionStatusSetCodeSigningRequirementSuccess = 0,
SUValidateConnectionStatusSetNoRequirementSuccess,
SUValidateConnectionStatusAPIFailure,
SUValidateConnectionStatusCodeSigningRequirementFailure,
SUValidateConectionNoSupportedValidationMethodFailure,
};
typedef NS_OPTIONS(NSUInteger, SUValidateConnectionOptions) {
// Default validation behavior (matches against Team ID from main executable if available)
SUValidateConnectionOptionDefault = 0,
// Require that the connecting client has the app sandbox entitlement
SUValidateConnectionOptionRequireSandboxEntitlement = 1 << 0,
};
SUCodeSigningVerifierDefinitionAttribute
@interface SUCodeSigningVerifier : NSObject
+ (BOOL)codeSignatureAtBundleURL:(NSURL *)oldBundleURL matchesSignatureAtBundleURL:(NSURL *)newBundleURL error:(NSError **)error;
+ (BOOL)codeSignatureIsValidAtBundleURL:(NSURL *)bundleURL error:(NSError **)error;
+ (BOOL)codeSignatureIsValidAtBundleURL:(NSURL *)newBundleURL andMatchesSignatureAtBundleURL:(NSURL *)oldBundleURL error:(NSError **)error;
+ (BOOL)codeSignatureIsValidAtBundleURL:(NSURL *)bundleURL checkNestedCode:(BOOL)checkNestedCode error:(NSError **)error;
// Same as above except does not check for nested code. This method should be used by the framework.
+ (BOOL)codeSignatureIsValidAtBundleURL:(NSURL *)bundleURL error:(NSError *__autoreleasing *)error;
+ (BOOL)codeSignatureIsValidAtDownloadURL:(NSURL *)downloadURL andMatchesDeveloperIDTeamFromOldBundleURL:(NSURL *)oldBundleURL error:(NSError * __autoreleasing *)error;
+ (BOOL)bundleAtURLIsCodeSigned:(NSURL *)bundleURL;
+ (NSString * _Nullable)teamIdentifierAtURL:(NSURL *)url;
+ (NSString * _Nullable)teamIdentifierFromMainExecutable;
+ (SUValidateConnectionStatus)validateConnection:(NSXPCConnection *)connection options:(SUValidateConnectionOptions)options error:(NSError * __autoreleasing *)error;
@end
NS_ASSUME_NONNULL_END
#endif
+411 -54
View File
@@ -10,65 +10,123 @@
#include <Security/SecCode.h>
#import "SUCodeSigningVerifier.h"
#import "SULog.h"
#import "SUErrors.h"
#include "AppKitPrevention.h"
@interface NSXPCConnection (Private)
@property (nonatomic, readonly) audit_token_t auditToken;
@end
@implementation SUCodeSigningVerifier
+ (BOOL)codeSignatureAtBundleURL:(NSURL *)oldBundleURL matchesSignatureAtBundleURL:(NSURL *)newBundleURL error:(NSError * __autoreleasing *)error
+ (BOOL)codeSignatureIsValidAtBundleURL:(NSURL *)newBundleURL andMatchesSignatureAtBundleURL:(NSURL *)oldBundleURL error:(NSError * __autoreleasing *)error
{
OSStatus result;
SecRequirementRef requirement = NULL;
SecStaticCodeRef staticCode = NULL;
SecStaticCodeRef oldCode = NULL;
CFErrorRef cfError = NULL;
if (error) {
*error = nil;
}
result = SecStaticCodeCreateWithPath((__bridge CFURLRef)oldBundleURL, kSecCSDefaultFlags, &oldCode);
if (result == errSecCSUnsigned) {
return NO;
if (result != noErr) {
if (error != NULL) {
NSString *errorMessage =
(result == errSecCSUnsigned) ?
[NSString stringWithFormat:@"Bundle is not code signed: %@", oldBundleURL.path] :
[NSString stringWithFormat:@"Failed to get static code (%d): %@", result, oldBundleURL.path];
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInsufficientSigningError userInfo:@{ NSLocalizedDescriptionKey: errorMessage }];
}
goto finally;
}
result = SecCodeCopyDesignatedRequirement(oldCode, kSecCSDefaultFlags, &requirement);
if (result != noErr) {
SULog(SULogLevelError, @"Failed to copy designated requirement. Code Signing OSStatus code: %d", result);
NSString *message = [NSString stringWithFormat:@"Failed to copy designated requirement. Code Signing OSStatus code: %d", result];
SULog(SULogLevelError, @"%@", message);
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInsufficientSigningError userInfo:@{ NSLocalizedDescriptionKey: message }];
}
goto finally;
}
result = SecStaticCodeCreateWithPath((__bridge CFURLRef)newBundleURL, kSecCSDefaultFlags, &staticCode);
if (result != noErr) {
SULog(SULogLevelError, @"Failed to get static code %d", result);
NSString *message = [NSString stringWithFormat:@"Failed to get static code %d", result];
SULog(SULogLevelError, @"%@", message);
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInsufficientSigningError userInfo:@{ NSLocalizedDescriptionKey: message }];
}
goto finally;
}
// 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.
// Additionally, there are several reasons to stay away from deep verification and to prefer EdDSA signing the download archive instead.
// See https://github.com/sparkle-project/Sparkle/pull/523#commitcomment-17549302 and https://github.com/sparkle-project/Sparkle/issues/543
SecCSFlags flags = (SecCSFlags) (kSecCSDefaultFlags | kSecCSCheckAllArchitectures);
SecCSFlags flags = kSecCSCheckAllArchitectures;
result = SecStaticCodeCheckValidityWithErrors(staticCode, flags, requirement, &cfError);
if (cfError) {
NSError *tmpError = CFBridgingRelease(cfError);
if (error) *error = tmpError;
}
if (result != noErr) {
if (result == errSecCSUnsigned) {
SULog(SULogLevelError, @"The host app is signed, but the new version of the app is not signed using Apple Code Signing. Please ensure that the new app is signed and that archiving did not corrupt the signature.");
if (result != errSecSuccess) {
NSError *underlyingError;
if (cfError != NULL) {
NSError *tmpError = CFBridgingRelease(cfError);
underlyingError = tmpError;
} else {
underlyingError = nil;
}
if (result == errSecCSReqFailed) {
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
if (underlyingError != nil) {
userInfo[NSUnderlyingErrorKey] = underlyingError;
}
if (result == errSecCSUnsigned) {
NSString *message = @"The host app is signed, but the new version of the app is not signed using Apple Code Signing. Please ensure that the new app is signed and that archiving did not corrupt the signature.";
SULog(SULogLevelError, @"%@", message);
if (error != NULL) {
userInfo[NSLocalizedDescriptionKey] = message;
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInsufficientSigningError userInfo:[userInfo copy]];
}
} else if (result == errSecCSReqFailed) {
CFStringRef requirementString = nil;
NSString *initialMessage;
if (SecRequirementCopyString(requirement, kSecCSDefaultFlags, &requirementString) == noErr) {
SULog(SULogLevelError, @"Code signature of the new version doesn't match the old version: %@. Please ensure that old and new app is signed using exactly the same certificate.", requirementString);
initialMessage = [NSString stringWithFormat:@"Code signature of the new version doesn't match the old version: %@. Please ensure that old and new app is signed using exactly the same certificate.", requirementString];
SULog(SULogLevelError, @"%@", initialMessage);
CFRelease(requirementString);
} else {
initialMessage = @"Code signature of new version doesn't match the old version. Please ensure that old and new app is signed using exactly the same certificate.";
}
[self logSigningInfoForCode:oldCode label:@"old info"];
[self logSigningInfoForCode:staticCode label:@"new info"];
NSDictionary *oldInfo = [self logSigningInfoForCode:oldCode label:@"old info"];
NSDictionary *newInfo = [self logSigningInfoForCode:staticCode label:@"new info"];
if (error != NULL) {
userInfo[NSLocalizedDescriptionKey] = [NSString stringWithFormat:@"%@ old info: %@. new info: %@", initialMessage, oldInfo, newInfo];
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInsufficientSigningError userInfo:[userInfo copy]];
}
} else {
if (error != NULL) {
userInfo[NSLocalizedDescriptionKey] = @"Error: Old app bundle code signing signature failed to match new bundle code signature";
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInsufficientSigningError userInfo:[userInfo copy]];
}
}
}
@@ -80,35 +138,76 @@ 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;
CFErrorRef cfError = NULL;
if (error) {
*error = nil;
}
result = SecStaticCodeCreateWithPath((__bridge CFURLRef)bundleURL, kSecCSDefaultFlags, &staticCode);
if (result != noErr) {
SULog(SULogLevelError, @"Failed to get static code %d", result);
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInsufficientSigningError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to get static code for verifying code signature: %d", result] }];
}
goto finally;
}
// See in -codeSignatureAtBundleURL:matchesSignatureAtBundleURL:error: for why kSecCSCheckNestedCode is not passed
SecCSFlags flags = (SecCSFlags) (kSecCSDefaultFlags | kSecCSCheckAllArchitectures);
result = SecStaticCodeCheckValidityWithErrors(staticCode, flags, NULL, &cfError);
if (cfError) {
NSError *tmpError = CFBridgingRelease(cfError);
if (error) *error = tmpError;
// See in -codeSignatureIsValidAtBundleURL:andMatchesSignatureAtBundleURL:error: for why kSecCSCheckNestedCode is not always passed
SecCSFlags flags = kSecCSCheckAllArchitectures;
if (checkNestedCode) {
flags |= kSecCSCheckNestedCode;
}
if (result != noErr) {
if (result == errSecCSUnsigned) {
SULog(SULogLevelError, @"Error: The app is not signed using Apple Code Signing. %@", bundleURL);
result = SecStaticCodeCheckValidityWithErrors(staticCode, flags, NULL, &cfError);
if (result != errSecSuccess) {
NSError *underlyingError;
if (cfError != NULL) {
NSError *tmpError = CFBridgingRelease(cfError);
underlyingError = tmpError;
} else {
underlyingError = nil;
}
if (result == errSecCSReqFailed) {
[self logSigningInfoForCode:staticCode label:@"new info"];
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
if (underlyingError != nil) {
userInfo[NSUnderlyingErrorKey] = underlyingError;
}
if (result == errSecCSUnsigned) {
NSString *message = [NSString stringWithFormat:@"Error: The app is not signed using Apple Code Signing. %@", bundleURL];
SULog(SULogLevelError, @"%@", message);
if (error != NULL) {
userInfo[NSLocalizedDescriptionKey] = message;
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInsufficientSigningError userInfo:[userInfo copy]];
}
} else if (result == errSecCSReqFailed) {
if (error != NULL) {
NSDictionary *newInfo = [self logSigningInfoForCode:staticCode label:@"new info"];
NSString *message = [NSString stringWithFormat:@"Error: The app failed Apple Code Signing checks: %@ - new info: %@", bundleURL, newInfo];
userInfo[NSLocalizedDescriptionKey] = message;
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInsufficientSigningError userInfo:[userInfo copy]];
}
} else {
if (error != NULL) {
NSString *message = [NSString stringWithFormat:@"Error: The app failed Apple Code Signing checks: %@", bundleURL];
userInfo[NSLocalizedDescriptionKey] = message;
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInsufficientSigningError userInfo:[userInfo copy]];
}
}
}
@@ -121,22 +220,8 @@ static id valueOrNSNull(id value) {
return value ? value : [NSNull null];
}
+ (NSDictionary *)codeSignatureInfoAtBundleURL:(NSURL *)bundlePath {
NSDictionary *info = nil;
SecStaticCodeRef code = NULL;
OSStatus result = SecStaticCodeCreateWithPath((__bridge CFURLRef)bundlePath, kSecCSDefaultFlags, &code);
if (result != noErr) {
SULog(SULogLevelError, @"Failed to get static code %d", result);
goto finally;
}
info = [self codeSignatureInfoForCode:code];
finally:
if (code) CFRelease(code);
return info;
}
+ (NSDictionary *)codeSignatureInfoForCode:(SecStaticCodeRef)code {
+ (NSDictionary *)codeSignatureInfoForCode:(SecStaticCodeRef)code SPU_OBJC_DIRECT
{
CFDictionaryRef signingInfo = nil;
const SecCSFlags flags = (SecCSFlags) (kSecCSSigningInformation | kSecCSRequirementInformation | kSecCSDynamicInformation | kSecCSContentInformation);
if (SecCodeCopySigningInformation(code, flags, &signingInfo) == noErr) {
@@ -153,9 +238,11 @@ finally:
return nil;
}
+ (void)logSigningInfoForCode:(SecStaticCodeRef)code label:(NSString*)label {
+ (NSDictionary *)logSigningInfoForCode:(SecStaticCodeRef)code label:(NSString*)label SPU_OBJC_DIRECT
{
NSDictionary *relevantInfo = [self codeSignatureInfoForCode:code];
SULog(SULogLevelDefault, @"%@: %@", label, relevantInfo);
return relevantInfo;
}
+ (BOOL)bundleAtURLIsCodeSigned:(NSURL *)bundleURL
@@ -182,4 +269,274 @@ finally:
return (result == 0);
}
static NSString * _Nullable SUTeamIdentifierFromCode(SecStaticCodeRef staticCode)
{
CFDictionaryRef cfSigningInformation = NULL;
OSStatus copySigningInfoCode = SecCodeCopySigningInformation(staticCode, kSecCSSigningInformation,
&cfSigningInformation);
NSDictionary *signingInformation = CFBridgingRelease(cfSigningInformation);
if (copySigningInfoCode != noErr) {
SULog(SULogLevelError, @"Failed to get signing information for retrieving team identifier: %d", copySigningInfoCode);
return nil;
}
// Note this will return nil for ad-hoc or unsigned binaries
return signingInformation[(NSString *)kSecCodeInfoTeamIdentifier];
}
+ (NSString * _Nullable)teamIdentifierAtURL:(NSURL *)url
{
SecStaticCodeRef staticCode = NULL;
OSStatus staticCodeResult = SecStaticCodeCreateWithPath((__bridge CFURLRef)url, kSecCSDefaultFlags, &staticCode);
if (staticCodeResult != errSecSuccess) {
SULog(SULogLevelError, @"Failed to get static code for retrieving team identifier: %d", staticCodeResult);
return nil;
}
NSString *teamIdentifier = SUTeamIdentifierFromCode(staticCode);
if (staticCode != NULL) {
CFRelease(staticCode);
}
return teamIdentifier;
}
+ (NSString * _Nullable)teamIdentifierFromMainExecutable
{
SecCodeRef code = NULL;
OSStatus result = SecCodeCopySelf(kSecCSDefaultFlags, &code);
if (result != errSecSuccess) {
SULog(SULogLevelError, @"Failed to get code for retrieving team identifier of main executable: %d", result);
return nil;
}
NSString *teamIdentifier = SUTeamIdentifierFromCode(code);
CFRelease(code);
return teamIdentifier;
}
+ (BOOL)codeSignatureIsValidAtDownloadURL:(NSURL *)downloadURL andMatchesDeveloperIDTeamFromOldBundleURL:(NSURL *)oldBundleURL error:(NSError * __autoreleasing *)error
{
NSString *teamIdentifier = nil;
NSString *requirementString = nil;
SecRequirementRef requirement = NULL;
SecStaticCodeRef oldStaticCode = NULL;
SecStaticCodeRef downloadStaticCode = NULL;
OSStatus result;
NSError *resultError = nil;
NSString *commonErrorMessage = @"The download archive cannot be validated with Apple Developer ID code signing as fallback (after (Ed)DSA verification has failed)";
result = SecStaticCodeCreateWithPath((__bridge CFURLRef)oldBundleURL, kSecCSDefaultFlags, &oldStaticCode);
if (result != errSecSuccess) {
NSString *errorMessage =
(result == errSecCSUnsigned) ?
[NSString stringWithFormat:@"%@. The original app is not code signed: %@", commonErrorMessage, oldBundleURL.path] :
[NSString stringWithFormat:@"%@. The static code could not be retrieved from the original app (%d): %@", commonErrorMessage, result, oldBundleURL.path];
resultError = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInsufficientSigningError userInfo:@{ NSLocalizedDescriptionKey: errorMessage }];
goto finally;
}
teamIdentifier = SUTeamIdentifierFromCode(oldStaticCode);
if (teamIdentifier == nil) {
resultError = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInsufficientSigningError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"%@. The team identifier could not be retrieved from the original app: %@", commonErrorMessage, oldBundleURL.path] }];
goto finally;
}
// Create a designated requirement with developer ID signing with this team ID
// Validate it against code signing check of this archive
// CertificateIssuedByApple = anchor apple generic
// IssuerIsDeveloperID = certificate 1[field.1.2.840.113635.100.6.2.6]
// LeafIsDeveloperIDApp = certificate leaf[field.1.2.840.113635.100.6.1.13]
// DeveloperIDTeamID = certificate leaf[subject.OU]
// https://developer.apple.com/documentation/technotes/tn3127-inside-code-signing-requirements#Xcode-designated-requirement-for-Developer-ID-code
requirementString = [NSString stringWithFormat:@"anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] and certificate leaf[field.1.2.840.113635.100.6.1.13] and certificate leaf[subject.OU] = \"%@\"", teamIdentifier];
result = SecRequirementCreateWithString((__bridge CFStringRef)requirementString, kSecCSDefaultFlags, &requirement);
if (result != errSecSuccess) {
resultError = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInsufficientSigningError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"%@. The designated requirement string with a Developer ID requirement with team identifier '%@' could not be created with error %d", commonErrorMessage, teamIdentifier, result] }];
goto finally;
}
result = SecStaticCodeCreateWithPath((__bridge CFURLRef)downloadURL, kSecCSDefaultFlags, &downloadStaticCode);
if (result != errSecSuccess) {
NSString *message = [NSString stringWithFormat:@"%@. The static code could not be retrieved from the download archive with error %d. The download archive may not be Apple code signed.", commonErrorMessage, result];
SULog(SULogLevelError, @"%@", message);
resultError = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInsufficientSigningError userInfo:@{ NSLocalizedDescriptionKey: message }];
goto finally;
}
SecCSFlags flags = (SecCSFlags)kSecCSDefaultFlags;
CFErrorRef cfError = NULL;
result = SecStaticCodeCheckValidityWithErrors(downloadStaticCode, flags, requirement, &cfError);
if (result != errSecSuccess) {
NSError *underlyingError;
if (cfError != NULL) {
NSError *tmpError = CFBridgingRelease(cfError);
underlyingError = tmpError;
} else {
underlyingError = nil;
}
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
if (underlyingError != nil) {
userInfo[NSUnderlyingErrorKey] = underlyingError;
}
if (result == errSecCSUnsigned) {
NSString *message = [NSString stringWithFormat:@"%@. The download archive is not Apple code signed.", commonErrorMessage];
SULog(SULogLevelError, @"%@", message);
userInfo[NSLocalizedDescriptionKey] = message;
resultError = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInsufficientSigningError userInfo:[userInfo copy]];
} else if (result == errSecCSReqFailed) {
NSString *initialMessage = [NSString stringWithFormat:@"%@. The Apple code signature of new downloaded archive is either not Developer ID code signed, or doesn't have a Team ID that matches the old app version (%@). Please ensure that the archive and app are signed using the same Developer ID certificate.", commonErrorMessage, teamIdentifier];
NSDictionary *oldInfo = [self logSigningInfoForCode:oldStaticCode label:@"old info"];
NSDictionary *newInfo = [self logSigningInfoForCode:downloadStaticCode label:@"new info"];
userInfo[NSLocalizedDescriptionKey] = [NSString stringWithFormat:@"%@ old info: %@. new info: %@", initialMessage, oldInfo, newInfo];
resultError = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInsufficientSigningError userInfo:[userInfo copy]];
} else {
userInfo[NSLocalizedDescriptionKey] = [NSString stringWithFormat:@"%@. The downloaded archive code signing signature failed to validate with an unknown error (%d).", commonErrorMessage, result];
resultError = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInsufficientSigningError userInfo:[userInfo copy]];
}
goto finally;
}
finally:
if (oldStaticCode != NULL) {
CFRelease(oldStaticCode);
}
if (requirement != NULL) {
CFRelease(requirement);
}
if (downloadStaticCode != NULL) {
CFRelease(downloadStaticCode);
}
if (resultError != nil && error != NULL) {
*error = resultError;
}
return (resultError == nil);
}
+ (SUValidateConnectionStatus)validateConnection:(NSXPCConnection *)connection options:(SUValidateConnectionOptions)options error:(NSError * __autoreleasing *)error
{
NSMutableArray<NSString *> *codeSigningRequirementComponents = [NSMutableArray array];
// Build the default team ID signing requirement
NSString *hostTeamIdentifier = [self teamIdentifierFromMainExecutable];
if (hostTeamIdentifier != nil) {
NSString *teamIdentifierRequirement = [NSString stringWithFormat:@"(anchor apple generic and certificate leaf[subject.OU] = \"%@\")", hostTeamIdentifier];
[codeSigningRequirementComponents addObject:teamIdentifierRequirement];
}
// Build the sandboxing requirement
if ((options & SUValidateConnectionOptionRequireSandboxEntitlement) != 0) {
// This ensures the entitlement is set to true too
NSString *sandboxingRequirement = @"(entitlement [\"com.apple.security.app-sandbox\"] exists)";
[codeSigningRequirementComponents addObject:sandboxingRequirement];
}
// Check if no requirement is required
if (codeSigningRequirementComponents.count == 0) {
return SUValidateConnectionStatusSetNoRequirementSuccess;
}
NSString *codeSigningRequirement = [codeSigningRequirementComponents componentsJoinedByString:@" and "];
if (@available(macOS 13.0, *)) {
[connection setCodeSigningRequirement:codeSigningRequirement];
return SUValidateConnectionStatusSetCodeSigningRequirementSuccess;
}
// Fall back to audit token on older OS's
if ([connection respondsToSelector:@selector(auditToken)]) {
audit_token_t auditToken = [connection auditToken];
NSData *auditTokenData = [NSData dataWithBytes:&auditToken length:sizeof(auditToken)];
NSDictionary *attributes = @{
(NSString *)kSecGuestAttributeAudit: auditTokenData
};
SecCodeRef code = NULL;
OSStatus result = SecCodeCopyGuestWithAttributes(NULL, (__bridge CFDictionaryRef _Nullable)(attributes), kSecCSDefaultFlags, &code);
if (result != errSecSuccess) {
CFRelease(code);
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInsufficientSigningError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"The client connection could not be validated because SecCodeCopyGuestWithAttributes() failed with error %d", result] }];
}
return SUValidateConnectionStatusAPIFailure;
}
// Check if the client is code signed with our signing requirement
SecRequirementRef requirement = NULL;
result = SecRequirementCreateWithString((__bridge CFStringRef)codeSigningRequirement, kSecCSDefaultFlags, &requirement);
if (result != errSecSuccess) {
CFRelease(code);
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInsufficientSigningError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"The client connection could not be validated because SecRequirementCreateWithString() failed with error %d", result] }];
}
return SUValidateConnectionStatusAPIFailure;
}
CFErrorRef cfError = NULL;
// This is not a static code, so we don't pass kSecCSCheckAllArchitectures
result = SecCodeCheckValidityWithErrors(code, kSecCSDefaultFlags, requirement, &cfError);
CFRelease(requirement);
requirement = NULL;
if (result != errSecSuccess) {
NSError *cfBridgedError = (NSError *)CFBridgingRelease(cfError);
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInsufficientSigningError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"The client connection could not be validated because validating the code signature failed with error %d (%@). Does the app meet the designated requirement: %@", result, cfBridgedError.localizedDescription, codeSigningRequirement] }];
}
[self logSigningInfoForCode:code label:@"Client"];
CFRelease(code);
return SUValidateConnectionStatusCodeSigningRequirementFailure;
}
CFRelease(code);
return SUValidateConnectionStatusSetCodeSigningRequirementSuccess;
}
// Not much we can do if auditToken is not supported. This code should not be reached though.
return SUValidateConectionNoSupportedValidationMethodFailure;
}
@end
+4 -2
View File
@@ -14,9 +14,11 @@
NS_ASSUME_NONNULL_BEGIN
@interface SUDiskImageUnarchiver : NSObject <SUUnarchiverProtocol>
SPU_OBJC_DIRECT_MEMBERS @interface SUDiskImageUnarchiver : NSObject <SUUnarchiverProtocol>
- (instancetype)initWithArchivePath:(NSString *)archivePath decryptionPassword:(nullable NSString *)decryptionPassword;
- (instancetype)initWithArchivePath:(NSString *)archivePath extractionDirectory:(NSString *)extractionDirectory decryptionPassword:(nullable NSString *)decryptionPassword;
+ (BOOL)canUnarchivePath:(NSString *)path;
@end
+203 -86
View File
@@ -9,21 +9,24 @@
#import "SUDiskImageUnarchiver.h"
#import "SUUnarchiverNotifier.h"
#import "SULog.h"
#import "SUErrors.h"
#include "AppKitPrevention.h"
@interface SUDiskImageUnarchiver ()
@property (nonatomic, copy, readonly) NSString *archivePath;
@property (nullable, nonatomic, copy, readonly) NSString *decryptionPassword;
@interface SUDiskImageUnarchiver () <NSFileManagerDelegate>
@end
@implementation SUDiskImageUnarchiver
@synthesize archivePath = _archivePath;
@synthesize decryptionPassword = _decryptionPassword;
{
NSString *_archivePath;
NSString *_decryptionPassword;
NSString *_extractionDirectory;
SUUnarchiverNotifier *_notifier;
double _currentExtractionProgress;
double _fileProgressIncrement;
}
+ (BOOL)canUnarchivePath:(NSString *)path
{
@@ -35,26 +38,51 @@
return NO;
}
- (instancetype)initWithArchivePath:(NSString *)archivePath decryptionPassword:(nullable NSString *)decryptionPassword
- (instancetype)initWithArchivePath:(NSString *)archivePath extractionDirectory:(NSString *)extractionDirectory decryptionPassword:(nullable NSString *)decryptionPassword
{
self = [super init];
if (self != nil) {
_archivePath = [archivePath copy];
_decryptionPassword = [decryptionPassword copy];
_extractionDirectory = [extractionDirectory copy];
}
return self;
}
- (void)unarchiveWithCompletionBlock:(void (^)(NSError * _Nullable))completionBlock progressBlock:(void (^ _Nullable)(double))progressBlock
- (BOOL)needsVerifyBeforeExtractionKey
{
return NO;
}
- (void)unarchiveWithCompletionBlock:(void (^)(NSError * _Nullable))completionBlock progressBlock:(void (^ _Nullable)(double))progressBlock waitForCleanup:(BOOL)waitForCleanup
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
SUUnarchiverNotifier *notifier = [[SUUnarchiverNotifier alloc] initWithCompletionBlock:completionBlock progressBlock:progressBlock];
[self extractDMGWithNotifier:notifier];
[self extractDMGWithNotifier:notifier waitForCleanup:waitForCleanup];
});
}
static NSUInteger fileCountForDirectory(NSFileManager *fileManager, NSString *itemPath)
{
NSUInteger fileCount = 0;
NSDirectoryEnumerator *dirEnum = [fileManager enumeratorAtPath:itemPath];
for (NSString * __unused currentFile in dirEnum) {
fileCount++;
}
return fileCount;
}
- (BOOL)fileManager:(NSFileManager *)fileManager shouldCopyItemAtURL:(NSURL *)srcURL toURL:(NSURL *)dstURL
{
_currentExtractionProgress += _fileProgressIncrement;
[_notifier notifyProgress:_currentExtractionProgress];
return YES;
}
// Called on a non-main thread.
- (void)extractDMGWithNotifier:(SUUnarchiverNotifier *)notifier
- (void)extractDMGWithNotifier:(SUUnarchiverNotifier *)notifier waitForCleanup:(BOOL)waitForCleanup SPU_OBJC_DIRECT
{
@autoreleasepool {
BOOL mountedSuccessfully = NO;
@@ -62,47 +90,49 @@
// get a unique mount point path
NSString *mountPoint = nil;
NSFileManager *manager;
NSError *error;
NSArray *contents;
do
{
// Using NSUUID would make creating UUIDs be done in Cocoa,
// and thus managed under ARC. Sadly, the class is in 10.8 and later.
CFUUIDRef uuid = CFUUIDCreate(NULL);
if (uuid)
{
NSString *uuidString = CFBridgingRelease(CFUUIDCreateString(NULL, uuid));
if (uuidString)
{
mountPoint = [@"/Volumes" stringByAppendingPathComponent:uuidString];
}
CFRelease(uuid);
}
}
NSError *error = nil;
NSArray *contents = nil;
do {
NSString *uuidString = [[NSUUID UUID] UUIDString];
mountPoint = [@"/Volumes" stringByAppendingPathComponent:uuidString];
}
// Note: this check does not follow symbolic links, which is what we want
while ([[NSURL fileURLWithPath:mountPoint] checkResourceIsReachableAndReturnError:NULL]);
while ([[NSURL fileURLWithPath:mountPoint] checkResourceIsReachableAndReturnError:NULL]);
NSData *promptData = nil;
promptData = [NSData dataWithBytes:"yes\n" length:4];
NSMutableData *inputData = [NSMutableData data];
NSMutableArray *arguments = [@[@"attach", self.archivePath, @"-mountpoint", mountPoint, /*@"-noverify",*/ @"-nobrowse", @"-noautoopen"] mutableCopy];
if (self.decryptionPassword) {
NSMutableData *passwordData = [[self.decryptionPassword dataUsingEncoding:NSUTF8StringEncoding] mutableCopy];
// Prepare stdin data for passwords and license agreements
{
// If no password is supplied, we will still be asked a password.
// In that case we respond with an empty password.
NSData *decryptionPasswordData = [_decryptionPassword dataUsingEncoding:NSUTF8StringEncoding];
if (decryptionPasswordData != nil) {
[inputData appendData:decryptionPasswordData];
}
// From the hdiutil docs:
// read a null-terminated passphrase from standard input
//
// Add the null terminator, then the newline
[passwordData appendData:[NSData dataWithBytes:"\0" length:1]];
[passwordData appendData:promptData];
promptData = passwordData;
// Add the null terminator
[inputData appendBytes:"\0" length:1];
[arguments addObject:@"-stdinpass"];
// Append prompt data for license agreements
[inputData appendBytes:"yes\n" length:4];
}
// Finder doesn't verify disk images anymore beyond the code signing signature (if available)
// Opt out of the old CRC checksum checks
// Also always pass -stdinpass so we gracefully handle password protected disk images even if we aren't expecting them
NSArray *arguments = @[@"attach", _archivePath, @"-mountpoint", mountPoint, @"-noverify", @"-nobrowse", @"-noautoopen", @"-stdinpass"];
NSData *output = nil;
NSInteger taskResult = -1;
@try
NSURL *mountPointURL = [NSURL fileURLWithPath:mountPoint isDirectory:YES];
NSURL *extractionDirectoryURL = [NSURL fileURLWithPath:_extractionDirectory isDirectory:YES];
NSMutableArray<NSString *> *itemsToExtract = [NSMutableArray array];
NSUInteger totalFileExtractionCount = 0;
{
NSTask *task = [[NSTask alloc] init];
task.launchPath = @"/usr/bin/hdiutil";
@@ -115,72 +145,152 @@
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 (![task launchAndReturnError:&error]) {
goto reportError;
}
if (@available(macOS 10.15, *)) {
if (![inputPipe.fileHandleForWriting writeData:inputData error:&error]) {
goto reportError;
}
}
#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_15
else
{
@try {
[inputPipe.fileHandleForWriting writeData:inputData];
} @catch (NSException *) {
goto reportError;
}
}
#endif
[notifier notifyProgress:0.125];
[inputPipe.fileHandleForWriting writeData:promptData];
[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 *)
{
if (taskResult != 0) {
NSString *resultStr = output ? [[NSString alloc] initWithData:output encoding:NSUTF8StringEncoding] : nil;
SULog(SULogLevelError, @"hdiutil failed with code: %ld data: <<%@>>", (long)taskResult, resultStr);
error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Extraction failed due to hdiutil returning %ld status: %@", (long)taskResult, resultStr]}];
goto reportError;
}
[notifier notifyProgress:0.5];
if (taskResult != 0)
{
NSString *resultStr = output ? [[NSString alloc] initWithData:output encoding:NSUTF8StringEncoding] : nil;
SULog(SULogLevelError, @"hdiutil failed with code: %ld data: <<%@>>", (long)taskResult, resultStr);
goto reportError;
}
mountedSuccessfully = YES;
// Mounting can take some time, so increment progress
_currentExtractionProgress = 0.1;
[notifier notifyProgress:_currentExtractionProgress];
// Now that we've mounted it, we need to copy out its contents.
manager = [[NSFileManager alloc] init];
contents = [manager contentsOfDirectoryAtPath:mountPoint error:&error];
if (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];
for (NSString *item in contents)
{
NSString *fromPath = [mountPoint stringByAppendingPathComponent:item];
NSString *toPath = [[self.archivePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:item];
// Sparkle can support installing pkg files, app bundles, and other bundle types for plug-ins
// We must not filter any of those out
for (NSString *item in contents) {
NSURL *fromPathURL = [mountPointURL URLByAppendingPathComponent:item];
// We skip any files in the DMG which are not readable.
if (![manager isReadableFileAtPath:fromPath]) {
NSString *lastPathComponent = fromPathURL.lastPathComponent;
// Ignore hidden files
if ([lastPathComponent hasPrefix:@"."]) {
continue;
}
itemsCopied += 1.0;
[notifier notifyProgress:0.5 + itemsCopied/(totalItems*2.0)];
SULog(SULogLevelDefault, @"copyItemAtPath:%@ toPath:%@", fromPath, toPath);
if (![manager copyItemAtPath:fromPath toPath:toPath error:&error])
{
// Ignore aliases
NSNumber *aliasFlag = nil;
if ([fromPathURL getResourceValue:&aliasFlag forKey:NSURLIsAliasFileKey error:NULL] && aliasFlag.boolValue) {
continue;
}
// Ignore symbolic links
NSNumber *symbolicFlag = nil;
if ([fromPathURL getResourceValue:&symbolicFlag forKey:NSURLIsSymbolicLinkKey error:NULL] && symbolicFlag.boolValue) {
continue;
}
// Ensure file is readable
NSNumber *isReadableFlag = nil;
if ([fromPathURL getResourceValue:&isReadableFlag forKey:NSURLIsReadableKey error:NULL] && !isReadableFlag.boolValue) {
continue;
}
NSNumber *isDirectoryFlag = nil;
if (![fromPathURL getResourceValue:&isDirectoryFlag forKey:NSURLIsDirectoryKey error:NULL]) {
continue;
}
BOOL isDirectory = isDirectoryFlag.boolValue;
NSString *pathExtension = fromPathURL.pathExtension;
if (isDirectory) {
// Skip directory types that aren't bundles or regular directories
if ([pathExtension isEqualToString:@"rtfd"]) {
continue;
}
} else {
// The only non-directory files we care about are (m)pkg files
if (![pathExtension isEqualToString:@"pkg"] && ![pathExtension isEqualToString:@"mpkg"]) {
continue;
}
}
if (isDirectory) {
totalFileExtractionCount += fileCountForDirectory(manager, fromPathURL.path);
} else {
totalFileExtractionCount++;
}
[itemsToExtract addObject:item];
}
_fileProgressIncrement = (0.99 - _currentExtractionProgress) / totalFileExtractionCount;
_notifier = notifier;
// Copy all items we want to extract and notify of progress
manager.delegate = self;
for (NSString *item in itemsToExtract) {
NSURL *fromURL = [mountPointURL URLByAppendingPathComponent:item];
NSURL *toURL = [extractionDirectoryURL URLByAppendingPathComponent:item];
if (![manager copyItemAtURL:fromURL toURL:toURL error:&error]) {
SULog(SULogLevelError, @"Failed to copy '%@' to '%@' with error: %@", fromURL.path, toURL.path, error);
goto reportError;
}
}
[notifier notifySuccess];
[notifier notifyProgress:1.0];
BOOL success = YES;
goto finally;
reportError:
[notifier notifyFailureWithError:error];
success = NO;
finally:
if (mountedSuccessfully) {
@@ -190,18 +300,25 @@
task.standardOutput = [NSPipe pipe];
task.standardError = [NSPipe pipe];
@try {
[task launch];
} @catch (NSException *exception) {
NSError *launchCleanupError = nil;
if (![task launchAndReturnError:&launchCleanupError]) {
SULog(SULogLevelError, @"Failed to unmount %@", mountPoint);
SULog(SULogLevelError, @"Exception: %@", exception);
SULog(SULogLevelError, @"Error: %@", launchCleanupError);
} else if (waitForCleanup) {
[task waitUntilExit];
}
} else {
SULog(SULogLevelError, @"Can't mount DMG %@", self.archivePath);
SULog(SULogLevelError, @"Can't mount DMG %@", _archivePath);
}
if (success) {
[notifier notifySuccess];
} else {
[notifier notifyFailureWithError:error];
}
}
}
- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], self.archivePath]; }
- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], _archivePath]; }
@end
+27
View File
@@ -0,0 +1,27 @@
//
// SUFlatPackageUnarchiver.h
// Autoupdate
//
// Created by Mayur Pawashe on 1/30/21.
// Copyright © 2021 Sparkle Project. All rights reserved.
//
#if SPARKLE_BUILD_PACKAGE_SUPPORT
#import <Foundation/Foundation.h>
#import "SUUnarchiverProtocol.h"
NS_ASSUME_NONNULL_BEGIN
// An unarchiver for flat packages that doesn't really do any unarchiving
SPU_OBJC_DIRECT_MEMBERS @interface SUFlatPackageUnarchiver : NSObject <SUUnarchiverProtocol>
- (instancetype)initWithFlatPackagePath:(NSString *)flatPackagePath extractionDirectory:(NSString *)extractionDirectory expectingInstallationType:(NSString *)installationType;
+ (BOOL)canUnarchivePath:(NSString *)path;
@end
NS_ASSUME_NONNULL_END
#endif
+84
View File
@@ -0,0 +1,84 @@
//
// SUFlatPackageUnarchiver.m
// Autoupdate
//
// Created by Mayur Pawashe on 1/30/21.
// Copyright © 2021 Sparkle Project. All rights reserved.
//
#if SPARKLE_BUILD_PACKAGE_SUPPORT
#import "SUFlatPackageUnarchiver.h"
#import "SUUnarchiverNotifier.h"
#import "SPUInstallationType.h"
#import "SUErrors.h"
#include "AppKitPrevention.h"
@implementation SUFlatPackageUnarchiver
{
NSString *_flatPackagePath;
NSString *_expectedInstallationType;
NSString *_extractionDirectory;
}
+ (BOOL)canUnarchivePath:(NSString *)path
{
return [path.pathExtension isEqualToString:@"pkg"] || [path.pathExtension isEqualToString:@"mpkg"];
}
+ (BOOL)mustValidateBeforeExtraction
{
return YES;
}
- (instancetype)initWithFlatPackagePath:(NSString *)flatPackagePath extractionDirectory:(NSString *)extractionDirectory expectingInstallationType:(NSString *)installationType
{
self = [super init];
if (self != nil) {
_flatPackagePath = [flatPackagePath copy];
_expectedInstallationType = [installationType copy];
_extractionDirectory = [extractionDirectory copy];
}
return self;
}
- (BOOL)needsVerifyBeforeExtractionKey
{
return NO;
}
- (void)unarchiveWithCompletionBlock:(void (^)(NSError * _Nullable))completionBlock progressBlock:(void (^ _Nullable)(double))progressBlock waitForCleanup:(BOOL)__unused waitForCleanup
{
SUUnarchiverNotifier *notifier = [[SUUnarchiverNotifier alloc] initWithCompletionBlock:completionBlock progressBlock:progressBlock];
// Flat packages must use guided package installs, not interactive
BOOL isDirectory = NO;
if (![_expectedInstallationType isEqualToString:SPUInstallationTypeGuidedPackage]) {
[notifier notifyFailureWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Flat package does not have guided installation type but %@ instead", _expectedInstallationType]}]];
} else if (![[NSFileManager defaultManager] fileExistsAtPath:_flatPackagePath isDirectory:&isDirectory] || isDirectory) {
[notifier notifyFailureWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Flat package does not exist at %@", _flatPackagePath]}]];
} else {
// Copying the flat package should be very fast, especially on APFS
NSError *copyError = nil;
if (![[NSFileManager defaultManager] copyItemAtPath:_flatPackagePath toPath:[_extractionDirectory stringByAppendingPathComponent:_flatPackagePath.lastPathComponent] error:&copyError]) {
NSMutableDictionary *userInfoDictionary = [NSMutableDictionary dictionaryWithDictionary:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Flat package (%@) cannot be copied to extraction directory (%@)", _flatPackagePath, _extractionDirectory]}];
if (copyError != nil) {
userInfoDictionary[NSUnderlyingErrorKey] = copyError;
}
[notifier notifyFailureWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:userInfoDictionary]];
} else {
[notifier notifyProgress:1.0];
[notifier notifySuccess];
}
}
}
- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], _flatPackagePath]; }
@end
#endif
+7 -3
View File
@@ -6,7 +6,7 @@
// Copyright 2010 Dragon Systems Software Limited. All rights reserved.
//
/*!
/**
# Sparkle Guided Installations
A guided installation allows Sparkle to download and install a package (pkg) or multi-package (mpkg) without user interaction.
@@ -16,11 +16,15 @@ The installer package is installed using macOS's built-in command line installer
A guided installation can be started by applications other than the application being replaced. This is particularly useful where helper applications or agents are used.
*/
#if SPARKLE_BUILD_PACKAGE_SUPPORT
#import <Foundation/Foundation.h>
#import "SUInstallerProtocol.h"
@interface SUGuidedPackageInstaller : NSObject <SUInstallerProtocol>
SPU_OBJC_DIRECT_MEMBERS @interface SUGuidedPackageInstaller : NSObject <SUInstallerProtocol>
- (instancetype)initWithPackagePath:(NSString *)packagePath installationPath:(NSString *)installationPath;
- (instancetype)initWithPackagePath:(NSString *)packagePath homeDirectory:(NSString *)homeDirectory userName:(NSString *)userName;
@end
#endif
+44 -30
View File
@@ -6,31 +6,29 @@
// Copyright 2010 Dragon Systems Software Limited. All rights reserved.
//
#if SPARKLE_BUILD_PACKAGE_SUPPORT
#import <sys/stat.h>
#import "SUGuidedPackageInstaller.h"
#import <Sparkle/SUErrors.h>
#import "SUErrors.h"
#include "AppKitPrevention.h"
@interface SUGuidedPackageInstaller ()
@property (nonatomic, readonly, copy) NSString *packagePath;
@property (nonatomic, readonly, copy) NSString *installationPath;
@end
@implementation SUGuidedPackageInstaller
{
NSString *_packagePath;
NSString *_homeDirectory;
NSString *_userName;
}
@synthesize packagePath = _packagePath;
@synthesize installationPath = _installationPath;
- (instancetype)initWithPackagePath:(NSString *)packagePath installationPath:(NSString *)installationPath
- (instancetype)initWithPackagePath:(NSString *)packagePath homeDirectory:(NSString *)homeDirectory userName:(NSString *)userName
{
self = [super init];
if (self != nil) {
_packagePath = [packagePath copy];
_installationPath = [installationPath copy];
_homeDirectory = [homeDirectory copy];
_userName = [userName copy];
}
return self;
}
@@ -47,27 +45,41 @@
NSTask *task = [[NSTask alloc] init];
task.launchPath = installerPath;
task.arguments = @[@"-pkg", self.packagePath, @"-target", @"/"];
task.standardError = [NSPipe pipe];
task.standardOutput = [NSPipe pipe];
task.arguments = @[@"-pkg", _packagePath, @"-target", @"/"];
// Set the $HOME and $USER variables so pre/post install scripts reference the correct user environment
task.environment = @{@"HOME": _homeDirectory, @"USER": _userName};
task.standardError = nil;
task.standardOutput = nil;
BOOL success = YES;
@try {
[task launch];
[task waitUntilExit];
if (task.terminationStatus != EXIT_SUCCESS) {
success = NO;
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Guided package installer returned non-zero exit status (%d)", task.terminationStatus] }];
}
}
} @catch (NSException *) {
success = NO;
NSError *launchError = nil;
if (![task launchAndReturnError:&launchError]) {
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Guided package installer task threw an exception"] }];
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;
}
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
{
}
- (BOOL)canInstallSilently
@@ -76,3 +88,5 @@
}
@end
#endif
+7 -3
View File
@@ -13,11 +13,15 @@ NS_ASSUME_NONNULL_BEGIN
@class SUHost;
@interface SUInstaller : NSObject
SPU_OBJC_DIRECT_MEMBERS @interface SUInstaller : NSObject
+ (nullable id<SUInstallerProtocol>)installerForHost:(SUHost *)host expectedInstallationType:(NSString *)expectedInstallationType updateDirectory:(NSString *)updateDirectory error:(NSError **)error;
+ (nullable id<SUInstallerProtocol>)installerForHost:(SUHost *)host expectedInstallationType:(NSString *)expectedInstallationType updateDirectory:(NSString *)updateDirectory connectionCodeSigningValidationSkipped:(BOOL)connectionCodeSigningValidationSkipped homeDirectory:(NSString *)homeDirectory userName:(NSString *)userName error:(NSError **)error;
+ (nullable NSString *)installSourcePathInUpdateFolder:(NSString *)inUpdateFolder forHost:(SUHost *)host isPackage:(BOOL *)isPackagePtr isGuided:(nullable BOOL *)isGuidedPtr;
+ (nullable NSString *)installSourcePathInUpdateFolder:(NSString *)inUpdateFolder forHost:(SUHost *)host
#if SPARKLE_BUILD_PACKAGE_SUPPORT
isPackage:(BOOL *)isPackagePtr isGuided:(nullable BOOL *)isGuidedPtr
#endif
;
@end
+150 -35
View File
@@ -13,24 +13,19 @@
#import "SUHost.h"
#import "SUConstants.h"
#import "SULog.h"
#import <Sparkle/SUErrors.h>
#import "SUErrors.h"
#import "SPUInstallationType.h"
#import "SUNormalization.h"
#include "AppKitPrevention.h"
@implementation SUInstaller
+ (BOOL)isAliasFolderAtPath:(NSString *)path
{
NSNumber *aliasFlag = nil;
[[NSURL fileURLWithPath:path] getResourceValue:&aliasFlag forKey:NSURLIsAliasFileKey error:nil];
NSNumber *directoryFlag = nil;
[[NSURL fileURLWithPath:path] getResourceValue:&directoryFlag forKey:NSURLIsDirectoryKey error:nil];
return aliasFlag.boolValue && directoryFlag.boolValue;
}
+ (nullable NSString *)installSourcePathInUpdateFolder:(NSString *)inUpdateFolder forHost:(SUHost *)host isPackage:(BOOL *)isPackagePtr isGuided:(BOOL *)isGuidedPtr
+ (nullable NSString *)installSourcePathInUpdateFolder:(NSString *)inUpdateFolder forHost:(SUHost *)host
#if SPARKLE_BUILD_PACKAGE_SUPPORT
isPackage:(BOOL *)isPackagePtr isGuided:(BOOL *)isGuidedPtr
#endif
{
NSParameterAssert(inUpdateFolder);
NSParameterAssert(host);
@@ -40,23 +35,59 @@
*newAppDownloadPath = nil,
*bundleFileName = [[host bundlePath] lastPathComponent],
*alternateBundleFileName = [[host name] stringByAppendingPathExtension:[[host bundlePath] pathExtension]];
#if SPARKLE_BUILD_PACKAGE_SUPPORT
NSString *fallbackPackagePath = nil;
BOOL isPackage = NO;
BOOL isGuided = YES;
NSString *fallbackPackagePath = nil;
#endif
NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath:inUpdateFolder];
NSString *bundleFileNameNoExtension = [bundleFileName stringByDeletingPathExtension];
while ((currentFile = [dirEnum nextObject])) {
NSString *currentPath = [inUpdateFolder stringByAppendingPathComponent:currentFile];
// Ignore all symbolic links and aliases
{
NSURL *currentPathURL = [NSURL fileURLWithPath:currentPath];
NSNumber *symbolicLinkFlag = nil;
[currentPathURL getResourceValue:&symbolicLinkFlag forKey:NSURLIsSymbolicLinkKey error:NULL];
if (symbolicLinkFlag.boolValue) {
// NSDirectoryEnumerator won't recurse into symlinked directories
continue;
}
NSNumber *aliasFlag = nil;
[currentPathURL getResourceValue:&aliasFlag forKey:NSURLIsAliasFileKey error:NULL];
if (aliasFlag.boolValue) {
NSNumber *directoryFlag = nil;
[currentPathURL getResourceValue:&directoryFlag forKey:NSURLIsDirectoryKey error:NULL];
// Some DMGs have symlinks into /Applications! That's no good!
if (directoryFlag.boolValue) {
[dirEnum skipDescendents];
}
continue;
}
}
NSString *currentFilename = [currentFile lastPathComponent];
#if SPARKLE_BUILD_PACKAGE_SUPPORT
NSString *currentExtension = [currentFile pathExtension];
NSString *currentFilenameNoExtension = [currentFilename stringByDeletingPathExtension];
#endif
if ([currentFilename isEqualToString:bundleFileName] ||
[currentFilename isEqualToString:alternateBundleFileName]) // We found one!
{
#if SPARKLE_BUILD_PACKAGE_SUPPORT
isPackage = NO;
#endif
newAppDownloadPath = currentPath;
break;
#if SPARKLE_BUILD_PACKAGE_SUPPORT
} else if ([currentExtension isEqualToString:@"pkg"] ||
[currentExtension isEqualToString:@"mpkg"]) {
if ([currentFilenameNoExtension isEqualToString:bundleFileNameNoExtension]) {
@@ -67,22 +98,22 @@
// Remember any other non-matching packages we have seen should we need to use one of them as a fallback.
fallbackPackagePath = currentPath;
}
#endif
} else {
// Try matching on bundle identifiers in case the user has changed the name of the host app
NSBundle *incomingBundle = [NSBundle bundleWithPath:currentPath];
NSString *hostBundleIdentifier = host.bundle.bundleIdentifier;
if (incomingBundle && [incomingBundle.bundleIdentifier isEqualToString:hostBundleIdentifier]) {
#if SPARKLE_BUILD_PACKAGE_SUPPORT
isPackage = NO;
#endif
newAppDownloadPath = currentPath;
break;
}
}
// Some DMGs have symlinks into /Applications! That's no good!
if ([self isAliasFolderAtPath:currentPath])
[dirEnum skipDescendents];
}
#if SPARKLE_BUILD_PACKAGE_SUPPORT
// We don't have a valid path. Try to use the fallback package.
if (newAppDownloadPath == nil && fallbackPackagePath != nil) {
@@ -104,18 +135,33 @@
*isPackagePtr = isPackage;
if (isGuidedPtr)
*isGuidedPtr = isGuided;
#endif
if (!newAppDownloadPath) {
SULog(SULogLevelError, @"Searched %@ for %@.(app|pkg)", inUpdateFolder, bundleFileNameNoExtension);
SULog(SULogLevelError, @"Searched %@ for %@.(app%@)", inUpdateFolder, bundleFileNameNoExtension,
#if SPARKLE_BUILD_PACKAGE_SUPPORT
@"|pkg"
#else
@""
#endif
);
}
return newAppDownloadPath;
}
+ (nullable id<SUInstallerProtocol>)installerForHost:(SUHost *)host expectedInstallationType:(NSString *)expectedInstallationType updateDirectory:(NSString *)updateDirectory error:(NSError * __autoreleasing *)error
+ (nullable id<SUInstallerProtocol>)installerForHost:(SUHost *)host expectedInstallationType:(NSString *)expectedInstallationType updateDirectory:(NSString *)updateDirectory connectionCodeSigningValidationSkipped:(BOOL)connectionCodeSigningValidationSkipped homeDirectory:(NSString *)homeDirectory userName:(NSString *)userName error:(NSError * __autoreleasing *)error
{
#if SPARKLE_BUILD_PACKAGE_SUPPORT
BOOL isPackage = NO;
BOOL isGuided = NO;
NSString *newDownloadPath = [self installSourcePathInUpdateFolder:updateDirectory forHost:host isPackage:&isPackage isGuided:&isGuided];
#endif
NSString *newDownloadPath = [self installSourcePathInUpdateFolder:updateDirectory forHost:host
#if SPARKLE_BUILD_PACKAGE_SUPPORT
isPackage:&isPackage isGuided:&isGuided
#endif
];
if (newDownloadPath == nil) {
if (error != NULL) {
@@ -124,17 +170,95 @@
return nil;
}
#if SPARKLE_BUILD_PACKAGE_SUPPORT
if (isPackage && connectionCodeSigningValidationSkipped) {
// Package updates cannot update arbitrary bundles if code signing validation on the connection was skipped
// (This means our helper is not code signed with an Apple issued certificate).
// In this case, the main executable must be owned by root and the host must contain our installer tool
NSString *installerExecutablePath = NSBundle.mainBundle.executableURL.URLByResolvingSymlinksInPath.path;
if (installerExecutablePath == nil) {
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingUpdateError userInfo:@{ NSLocalizedDescriptionKey: @"The "@SPARKLE_RELAUNCH_TOOL_NAME" executable path failed to be retrieved, which is an internal error that shouldn't happen. Please try to update using a production build of your app." }];
}
return nil;
}
NSString *hostBundlePath = host.bundle.bundleURL.URLByResolvingSymlinksInPath.path;
if (hostBundlePath == nil) {
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingUpdateError userInfo:@{ NSLocalizedDescriptionKey: @"The host bundle path to update to be retrieved, which is an internal error that shouldn't happen. Please try to update using a production build of your app." }];
}
return nil;
}
NSError *attributesError = nil;
NSDictionary<NSFileAttributeKey, id> *fileAttributes = [NSFileManager.defaultManager attributesOfItemAtPath:installerExecutablePath error:&attributesError];
if (fileAttributes == nil) {
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingUpdateError userInfo:@{ NSLocalizedDescriptionKey: @"File attributes failed to be retrieved from the "@SPARKLE_RELAUNCH_TOOL_NAME" executable, which is an internal error that shouldn't happen. Please try to update using a production build of your app." }];
}
return nil;
}
NSNumber *installerOwnerID = fileAttributes[NSFileOwnerAccountID];
if (installerOwnerID == nil) {
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingUpdateError userInfo:@{ NSLocalizedDescriptionKey: @"File owner ID failed to be retrieved from the "@SPARKLE_RELAUNCH_TOOL_NAME" executable, which is an internal error that shouldn't happen. Please try to update using a production build of your app." }];
}
return nil;
}
// Check our helper is owned by root
if (![installerOwnerID isEqual:@(0)]) {
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingUpdateError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Due to security, updating apps with package installers is disabled when '%@' is not signed with the same Team ID as your app, and "@SPARKLE_RELAUNCH_TOOL_NAME" is not owned by root (this specific case) or not residing in '%@'. Please either test an exported & production build of your app, or for development, code sign your app and Sparkle's embedded helpers with the same team: https://sparkle-project.org/documentation/sandboxing#code-signing", installerExecutablePath, hostBundlePath] }];
}
return nil;
}
NSArray<NSString *> *installerExecutablePathComponents = installerExecutablePath.pathComponents;
NSArray<NSString *> *hostBundlePathComponents = hostBundlePath.pathComponents;
if (installerExecutablePathComponents.count <= hostBundlePathComponents.count) {
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingUpdateError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Due to security, updating apps with package installers is disabled when '%@' is not signed with the same Team ID as your app, and "@SPARKLE_RELAUNCH_TOOL_NAME" is not owned by root or not residing in '%@' (this specific case). Please either test an exported & production build of your app, or for development, code sign your app and Sparkle's embedded helpers with the same team: https://sparkle-project.org/documentation/sandboxing#code-signing", installerExecutablePath, hostBundlePath] }];
}
return nil;
}
// Check out helper resides inside the host app to be updated
if (![[installerExecutablePathComponents subarrayWithRange:NSMakeRange(0, hostBundlePathComponents.count)] isEqualToArray:hostBundlePathComponents]) {
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingUpdateError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Due to security, updating apps with package installers is disabled when '%@' is not signed with the same Team ID as your app, and "@SPARKLE_RELAUNCH_TOOL_NAME" is not owned by root or not residing in '%@' (this specific case). Please either test an exported & production build of your app, or for development, code sign your app and Sparkle's embedded helpers with the same team: https://sparkle-project.org/documentation/sandboxing#code-signing", installerExecutablePath, hostBundlePath] }];
}
return nil;
}
}
#else
(void)connectionCodeSigningValidationSkipped;
#endif
// Make sure we find the type of installer that we were expecting to find
// We shouldn't implicitly trust the installation type fed into here from the appcast because the installation type helps us determine
// ahead of time whether or not this installer tool should be ran as root or not
id <SUInstallerProtocol> installer = nil;
#if SPARKLE_BUILD_PACKAGE_SUPPORT
if (isPackage && isGuided) {
if (![expectedInstallationType isEqualToString:SPUInstallationTypeGuidedPackage]) {
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Found guided package installer but '%@=%@' was probably missing in the appcast item enclosure", SUAppcastAttributeInstallationType, SPUInstallationTypeGuidedPackage] }];
}
} else {
installer = [[SUGuidedPackageInstaller alloc] initWithPackagePath:newDownloadPath installationPath:host.bundlePath];
installer = [[SUGuidedPackageInstaller alloc] initWithPackagePath:newDownloadPath homeDirectory:homeDirectory userName:userName];
}
} else if (isPackage) {
if (![expectedInstallationType isEqualToString:SPUInstallationTypeInteractivePackage]) {
@@ -142,9 +266,11 @@
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Found package installer but '%@=%@' was probably missing in the appcast item enclosure", SUAppcastAttributeInstallationType, SPUInstallationTypeInteractivePackage] }];
}
} else {
installer = [[SUPackageInstaller alloc] initWithPackagePath:newDownloadPath installationPath:host.bundlePath];
installer = [[SUPackageInstaller alloc] initWithPackagePath:newDownloadPath];
}
} else {
} else
#endif
{
if (![expectedInstallationType isEqualToString:SPUInstallationTypeApplication]) {
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Found regular application update but expected '%@=%@' from the appcast item enclosure instead", SUAppcastAttributeInstallationType, expectedInstallationType] }];
@@ -152,11 +278,12 @@
} else {
NSString *normalizedInstallationPath = nil;
if (SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME) {
normalizedInstallationPath = [self normalizedInstallationPathForHost:host];
normalizedInstallationPath = SUNormalizedInstallationPath(host);
}
// If we have a normalized path, we'll install to "#{CFBundleName}.app", but only if that path doesn't already exist. If we're "Foo 4.2.app," and there's a "Foo.app" in this directory, we don't want to overwrite it! But if there's no "Foo.app," we'll take that name.
// Otherwise if there's no normalized path (the more likely case), we'll just use the host bundle's path
// Check progress agent app which computes normalized path too according to these rules
NSString *installationPath;
if (normalizedInstallationPath != nil && ![[NSFileManager defaultManager] fileExistsAtPath:normalizedInstallationPath]) {
installationPath = normalizedInstallationPath;
@@ -171,16 +298,4 @@
return installer;
}
+ (NSString *)normalizedInstallationPathForHost:(SUHost *)host
{
NSBundle *bundle = host.bundle;
assert(bundle != nil);
NSString *normalizedAppPath = [[[bundle bundlePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", [host objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleNameKey], [[bundle bundlePath] pathExtension]]];
// Roundtrip string through fileSystemRepresentation to ensure it uses filesystem's Unicode normalization
// rather than arbitrary Unicode form from Info.plist - #1017
return [NSString stringWithUTF8String:[normalizedAppPath fileSystemRepresentation]];
}
@end
+6 -3
View File
@@ -22,14 +22,17 @@ NS_ASSUME_NONNULL_BEGIN
// Should be able to be called from non-main thread
- (BOOL)performFinalInstallationProgressBlock:(nullable void(^)(double))cb error:(NSError **)error;
// Any clean up work can be done here
// This is work that may be performed after the user application may have been updated / relaunched,
// or after an error occurred in the previous stages.
// Should be able to be called from any thread
- (void)performCleanup;
// Indicates whether or not this installer can install the update silently in the background, without hindering the user
// If this returns NO, then the installation can fail if the user did not directly request for the install to occur.
// Should be thread safe
- (BOOL)canInstallSilently;
// The destination and installation path of the bundle being updated
- (NSString *)installationPath;
@end
NS_ASSUME_NONNULL_END
+6 -2
View File
@@ -6,14 +6,18 @@
// Copyright 2008 Andy Matuschak. All rights reserved.
//
#if SPARKLE_BUILD_PACKAGE_SUPPORT
#import <Foundation/Foundation.h>
#import "SUInstallerProtocol.h"
// This is the deprecated package installation type, aka the "interactive" package installer
// For a more supported package installation, see SUGuidedPackageInstaller
@interface SUPackageInstaller : NSObject <SUInstallerProtocol>
SPU_OBJC_DIRECT_MEMBERS @interface SUPackageInstaller : NSObject <SUInstallerProtocol>
- (instancetype)initWithPackagePath:(NSString *)packagePath installationPath:(NSString *)installationPath;
- (instancetype)initWithPackagePath:(NSString *)packagePath;
@end
#endif
+14 -14
View File
@@ -6,34 +6,28 @@
// Copyright 2008 Andy Matuschak. All rights reserved.
//
#if SPARKLE_BUILD_PACKAGE_SUPPORT
#import "SUPackageInstaller.h"
#import "SUConstants.h"
#import <Sparkle/SUErrors.h>
#import "SUErrors.h"
#import "SULog.h"
#include "AppKitPrevention.h"
@interface SUPackageInstaller ()
@property (nonatomic, readonly, copy) NSString *packagePath;
@property (nonatomic, readonly, copy) NSString *installationPath;
@end
@implementation SUPackageInstaller
{
NSString *_packagePath;
}
static NSString *SUOpenUtilityPath = @"/usr/bin/open";
@synthesize packagePath = _packagePath;
@synthesize installationPath = _installationPath;
- (instancetype)initWithPackagePath:(NSString *)packagePath installationPath:(NSString *)installationPath
- (instancetype)initWithPackagePath:(NSString *)packagePath
{
self = [super init];
if (self != nil) {
_packagePath = [packagePath copy];
_installationPath = [installationPath copy];
}
return self;
}
@@ -55,7 +49,7 @@ static NSString *SUOpenUtilityPath = @"/usr/bin/open";
// -W = wait until the app has quit.
// -n = Open another instance if already open.
// -b = app bundle identifier
NSArray *args = @[@"-W", @"-n", @"-b", @"com.apple.installer", self.packagePath];
NSArray *args = @[@"-W", @"-n", @"-b", @"com.apple.installer", _packagePath];
// Known bug: if the installation fails or is canceled, Sparkle goes ahead and restarts, thinking everything is fine.
@try {
@@ -73,9 +67,15 @@ static NSString *SUOpenUtilityPath = @"/usr/bin/open";
return YES;
}
- (void)performCleanup
{
}
- (BOOL)canInstallSilently
{
return NO;
}
@end
#endif
+4 -2
View File
@@ -14,9 +14,11 @@
NS_ASSUME_NONNULL_BEGIN
@interface SUPipedUnarchiver : NSObject <SUUnarchiverProtocol>
SPU_OBJC_DIRECT_MEMBERS @interface SUPipedUnarchiver : NSObject <SUUnarchiverProtocol>
- (instancetype)initWithArchivePath:(NSString *)archivePath;
- (instancetype)initWithArchivePath:(NSString *)archivePath extractionDirectory:(NSString *)extractionDirectory;
+ (BOOL)canUnarchivePath:(NSString *)path;
@end
+300 -74
View File
@@ -9,30 +9,28 @@
#import "SUPipedUnarchiver.h"
#import "SUUnarchiverNotifier.h"
#import "SULog.h"
#import <Sparkle/SUErrors.h>
#import "SUErrors.h"
#include "AppKitPrevention.h"
@interface SUPipedUnarchiver ()
@property (nonatomic, copy, readonly) NSString *archivePath;
@end
@implementation SUPipedUnarchiver
{
NSString *_archivePath;
NSString *_extractionDirectory;
}
@synthesize archivePath = _archivePath;
+ (nullable NSArray <NSString *> *)commandAndArgumentsConformingToTypeOfPath:(NSString *)path
// pipingData == NO is only supported for zip archives
static NSArray<NSString *> * _Nullable argumentsConformingToTypeOfPath(NSString *path, BOOL pipingData, NSString * __autoreleasing *outCommand)
{
NSArray <NSString *> *extractTGZ = @[@"/usr/bin/tar", @"-zxC"];
NSArray <NSString *> *extractTBZ = @[@"/usr/bin/tar", @"-jxC"];
NSArray <NSString *> *extractTXZ = extractTGZ;
NSDictionary <NSString *, NSArray<NSString *> *> *extractCommandDictionary =
@{
@".zip" : @[@"/usr/bin/ditto", @"-x",@"-k",@"-"],
// Note: keep this list in sync with generate_appcast's unarchiveUpdates()
NSMutableDictionary <NSString *, NSArray<NSString *> *> *extractCommandDictionary =
[@{
@".zip" : (pipingData ? @[@"/usr/bin/ditto", @"-x", @"-k", @"-"] : @[@"/usr/bin/ditto", @"-x", @"-k", path]),
@".tar" : @[@"/usr/bin/tar", @"-xC"],
@".tar.gz" : extractTGZ,
@".tgz" : extractTGZ,
@@ -40,14 +38,39 @@
@".tbz" : extractTBZ,
@".tar.xz" : extractTXZ,
@".txz" : extractTXZ,
@".tar.lzma" : extractTXZ
};
@".tar.lzma" : extractTXZ,
} mutableCopy];
// At least the latest versions of 10.15 understand how to extract aar files
// Versions before 10.15 do not understand extracting newly created aar files
// Note encrypted aea files are supported in macOS 12 onwards, if we ever want to support those one day
if (@available(macOS 10.15.7, *)) {
NSString *appleArchiveCommand;
if (@available(macOS 11, *)) {
appleArchiveCommand = @"/usr/bin/aa";
} else {
// In 10.15 the utility was named yaa, which was later renamed to aar
appleArchiveCommand = @"/usr/bin/yaa";
}
NSArray <NSString *> *extractAppleArchive = @[appleArchiveCommand, @"extract", @"-d"];
[extractCommandDictionary addEntriesFromDictionary:@{
@".aar" : extractAppleArchive,
@".yaa" : extractAppleArchive,
}];
}
NSString *lastPathComponent = [path lastPathComponent];
for (NSString *currentType in extractCommandDictionary)
{
if ([lastPathComponent hasSuffix:currentType]) {
return [extractCommandDictionary objectForKey:currentType];
NSArray<NSString *> *commandAndArguments = [extractCommandDictionary objectForKey:currentType];
if (outCommand != NULL) {
*outCommand = commandAndArguments.firstObject;
}
return [commandAndArguments subarrayWithRange:NSMakeRange(1, commandAndArguments.count - 1)];
}
}
return nil;
@@ -55,7 +78,7 @@
+ (BOOL)canUnarchivePath:(NSString *)path
{
return ([self commandAndArgumentsConformingToTypeOfPath:path] != nil);
return argumentsConformingToTypeOfPath(path, YES, NULL) != nil;
}
+ (BOOL)mustValidateBeforeExtraction
@@ -63,93 +86,296 @@
return NO;
}
- (instancetype)initWithArchivePath:(NSString *)archivePath
- (instancetype)initWithArchivePath:(NSString *)archivePath extractionDirectory:(NSString *)extractionDirectory
{
self = [super init];
if (self != nil) {
_archivePath = [archivePath copy];
_extractionDirectory = [extractionDirectory copy];
}
return self;
}
- (void)unarchiveWithCompletionBlock:(void (^)(NSError * _Nullable))completionBlock progressBlock:(void (^ _Nullable)(double))progressBlock
- (BOOL)needsVerifyBeforeExtractionKey
{
NSArray <NSString *> *commandAndArguments = [[self class] commandAndArgumentsConformingToTypeOfPath:self.archivePath];
assert(commandAndArguments != nil);
NSString *command = commandAndArguments.firstObject;
return ([_archivePath hasSuffix:@".aar"] || [_archivePath hasSuffix:@".yaa"]);
}
- (void)unarchiveWithCompletionBlock:(void (^)(NSError * _Nullable))completionBlock progressBlock:(void (^ _Nullable)(double))progressBlock waitForCleanup:(BOOL)__unused waitForCleanup
{
NSString *command = nil;
NSArray<NSString *> *arguments = argumentsConformingToTypeOfPath(_archivePath, YES, &command);
assert(arguments != nil);
assert(command != nil);
NSArray <NSString *> *arguments = [commandAndArguments subarrayWithRange:NSMakeRange(1, commandAndArguments.count - 1)];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
SUUnarchiverNotifier *notifier = [[SUUnarchiverNotifier alloc] initWithCompletionBlock:completionBlock progressBlock:progressBlock];
[self extractArchivePipingDataToCommand:command arguments:arguments notifier:notifier];
@autoreleasepool {
SUUnarchiverNotifier *notifier = [[SUUnarchiverNotifier alloc] initWithCompletionBlock:completionBlock progressBlock:progressBlock];
NSError *extractError = nil;
if ([self extractArchivePipingData:YES command:command arguments:arguments notifier:notifier error:&extractError]) {
[notifier notifySuccess];
} else {
// If we fail due to an IO PIPE write failure for zip files,
// we may re-attempt extracting the archive without piping archive data
// (and without fine grained progress reporting).
// This is to workaround a bug in ditto which causes extraction to fail when piping data for
// some types of constructed zip files.
// Note this bug is fixed on macOS 15+, so this workaround is not needed there.
// https://github.com/sparkle-project/Sparkle/issues/2544
BOOL useNonPipingWorkaround;
if (@available(macOS 15, *)) {
useNonPipingWorkaround = NO;
} else {
NSError *underlyingError = extractError.userInfo[NSUnderlyingErrorKey];
useNonPipingWorkaround = [self->_archivePath.pathExtension isEqualToString:@"zip"] && ([extractError.domain isEqualToString:SUSparkleErrorDomain] && extractError.code == SUUnarchivingError && [underlyingError.domain isEqualToString:NSPOSIXErrorDomain] && underlyingError.code == EPIPE);
}
if (!useNonPipingWorkaround) {
[notifier notifyFailureWithError:extractError];
} else {
// Re-create the extraction directory, then try extracting without piping
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *extractionDirectoryURL = [NSURL fileURLWithPath:self->_extractionDirectory isDirectory:YES];
NSError *removeError = nil;
if (![fileManager removeItemAtURL:extractionDirectoryURL error:&removeError]) {
SULog(SULogLevelError, @"Failed to remove extraction directory path for non-piping workaround with error: %@", removeError);
[notifier notifyFailureWithError:extractError];
} else {
NSError *createError = nil;
if (![fileManager createDirectoryAtPath:self->_extractionDirectory withIntermediateDirectories:NO attributes:nil error:&createError]) {
SULog(SULogLevelError, @"Failed to create new extraction directory path for non-piping workaround with error: %@", createError);
[notifier notifyFailureWithError:extractError];
} else {
// The ditto command will be the same so no need to fetch it again
NSArray<NSString *> *nonPipingArguments = argumentsConformingToTypeOfPath(self->_archivePath, NO, NULL);
assert(nonPipingArguments != nil);
NSError *nonPipingExtractError = nil;
if ([self extractArchivePipingData:NO command:command arguments:nonPipingArguments notifier:notifier error:&nonPipingExtractError]) {
[notifier notifySuccess];
} else {
[notifier notifyFailureWithError:nonPipingExtractError];
}
}
}
}
}
}
});
}
// This method abstracts the types that use a command line tool piping data from stdin.
- (void)extractArchivePipingDataToCommand:(NSString *)command arguments:(NSArray*)args notifier:(SUUnarchiverNotifier *)notifier
- (BOOL)extractArchivePipingData:(BOOL)pipingData command:(NSString *)command arguments:(NSArray*)args notifier:(SUUnarchiverNotifier *)notifier error:(NSError * __autoreleasing *)outError SPU_OBJC_DIRECT
{
// *** GETS CALLED ON NON-MAIN THREAD!!!
@autoreleasepool {
NSError *error = nil;
NSString *destination = [self.archivePath stringByDeletingLastPathComponent];
NSString *destination = _extractionDirectory;
NSFileManager *fileManager = [NSFileManager defaultManager];
if (pipingData) {
SULog(SULogLevelDefault, @"Extracting using '%@' '%@' < '%@' '%@'", command, [args componentsJoinedByString:@"' '"], _archivePath, destination);
} else {
SULog(SULogLevelDefault, @"Extracting using '%@' '%@' '%@'", command, [args componentsJoinedByString:@"' '"], destination);
}
// Get expected file size for piping the archive
NSUInteger expectedLength;
if (pipingData) {
NSDictionary *attributes = [fileManager attributesOfItemAtPath:_archivePath error:nil];
expectedLength = [(NSNumber *)[attributes objectForKey:NSFileSize] unsignedIntegerValue];
SULog(SULogLevelDefault, @"Extracting using '%@' '%@' < '%@' '%@'", command, [args componentsJoinedByString:@"' '"], self.archivePath, destination);
if (expectedLength == 0) {
NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Extraction failed, archive '%@' is empty", _archivePath]}];
if (outError != NULL) {
*outError = error;
}
return NO;
}
} else {
expectedLength = 0;
}
NSTask *task = [[NSTask alloc] init];
NSPipe *pipe;
if (pipingData) {
pipe = [NSPipe pipe];
[task setStandardInput:pipe];
} else {
pipe = nil;
}
[task setStandardError:[NSFileHandle fileHandleWithStandardError]];
[task setStandardOutput:[NSFileHandle fileHandleWithStandardOutput]];
[task setLaunchPath:command];
[task setArguments:[args arrayByAddingObject:destination]];
NSError *launchError = nil;
if (![task launchAndReturnError:&launchError]) {
if (outError != NULL) {
*outError = launchError;
}
return NO;
}
NSError *underlyingOutError = nil;
NSUInteger bytesWritten = 0;
if (pipingData) {
NSFileHandle *archiveInput = [NSFileHandle fileHandleForReadingAtPath:_archivePath];
// 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];
NSFileHandle *archiveOutput = [pipe fileHandleForWriting];
#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_15
BOOL hasIOErrorMethods;
if (@available(macOS 10.15, *)) {
hasIOErrorMethods = YES;
} else {
hasIOErrorMethods = NO;
}
#endif
do {
NSData *data;
#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_15
if (!hasIOErrorMethods) {
@try {
data = [archiveInput readDataOfLength:256*1024];
} @catch (NSException *exception) {
SULog(SULogLevelError, @"Failed to read data from archive with exception reason %@", exception.reason);
data = nil;
}
}
else
#endif
{
NSError *readError = nil;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpartial-availability"
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);
underlyingOutError = readError;
}
}
NSPipe *pipe = [NSPipe pipe];
NSFileHandle *archiveOutput = [pipe fileHandleForWriting];
NSUInteger len = [data length];
if (len == 0) {
break;
}
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]];
[task launch];
NSUInteger bytesRead = 0;
do {
NSData *data = [archiveInput readDataOfLength:256*1024];
NSUInteger len = [data length];
if (!len) {
NSError *writeError = nil;
#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_15
if (!hasIOErrorMethods) {
@try {
[archiveOutput writeData:data];
} @catch (NSException *exception) {
SULog(SULogLevelError, @"Failed to write data to pipe with exception reason %@", exception.reason);
if ([exception.name isEqualToString:NSFileHandleOperationException]) {
NSError *underlyingFileHandleError = exception.userInfo[@"NSFileHandleOperationExceptionUnderlyingError"];
NSError *underlyingPOSIXError = underlyingFileHandleError.userInfo[NSUnderlyingErrorKey];
underlyingOutError = underlyingPOSIXError;
}
break;
}
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
#endif
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpartial-availability"
if (![archiveOutput writeData:data error:&writeError]) {
#pragma clang diagnostic pop
SULog(SULogLevelError, @"Failed to write data to pipe with error %@", writeError);
NSError *underlyingPOSIXError = writeError.userInfo[NSUnderlyingErrorKey];
underlyingOutError = underlyingPOSIXError;
break;
}
} else {
error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Extraction failed, command '%@' returned %d", command, [task terminationStatus]]}];
}
} else {
error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Extraction failed, archive '%@' is empty", self.archivePath]}];
bytesWritten += len;
[notifier notifyProgress:(double)bytesWritten / (double)expectedLength];
}
[notifier notifyFailureWithError:error];
while(bytesWritten < expectedLength);
if (@available(macOS 10.15, *)) {
NSError *archiveOutputCloseError = nil;
if (![archiveOutput closeAndReturnError:&archiveOutputCloseError]) {
SULog(SULogLevelError, @"Failed to close pipe with error %@", archiveOutputCloseError);
}
}
#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_15
else
{
[archiveOutput closeFile];
}
#endif
if (@available(macOS 10.15, *)) {
NSError *archiveInputCloseError = nil;
if (![archiveInput closeAndReturnError:&archiveInputCloseError]) {
SULog(SULogLevelError, @"Failed to close archive input with error %@", archiveInputCloseError);
}
}
#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_15
else
{
[archiveInput closeFile];
}
#endif
}
[task waitUntilExit];
if ([task terminationStatus] != 0) {
NSMutableDictionary *userInfo = [@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Extraction failed, command '%@' returned %d", command, [task terminationStatus]]} mutableCopy];
if (underlyingOutError != nil) {
userInfo[NSUnderlyingErrorKey] = underlyingOutError;
}
NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:[userInfo copy]];
if (outError != NULL) {
*outError = error;
}
return NO;
}
if (!pipingData) {
[notifier notifyProgress:1.0];
} else if (bytesWritten != expectedLength) {
// Don't set underlying error in this case
// This may fail due to a write PIPE error but we don't currently support extracting archives that have
// extraneous data leftover because these may be corrupt.
// We don't want to later workaround extraction by not piping the data.
NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Extraction failed, command '%@' got only %ld of %ld bytes", command, (long)bytesWritten, (long)expectedLength]}];
if (outError != NULL) {
*outError = error;
}
return NO;
}
return YES;
}
- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], self.archivePath]; }
- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], _archivePath]; }
@end
+2 -2
View File
@@ -12,9 +12,9 @@
@class SUHost;
@protocol SUVersionComparison;
@interface SUPlainInstaller : NSObject <SUInstallerProtocol>
SPU_OBJC_DIRECT_MEMBERS @interface SUPlainInstaller : NSObject <SUInstallerProtocol>
/*!
/**
@param host The current (old) bundle host
@param bundlePath The path to the new bundle that will be installed.
@param installationPath The path the new bundlePath will be installed to.
+303 -153
View File
@@ -11,26 +11,26 @@
#import "SUConstants.h"
#import "SUHost.h"
#import "SULog.h"
#import <Sparkle/SUErrors.h>
#import <Sparkle/SUVersionComparisonProtocol.h>
#import "SUErrors.h"
#import "SUVersionComparisonProtocol.h"
#import "SUStandardVersionComparator.h"
#import "SUCodeSigningVerifier.h"
#include "AppKitPrevention.h"
@interface SUPlainInstaller ()
@property (nonatomic, readonly) SUHost *host;
@property (nonatomic, copy, readonly) NSString *bundlePath;
@property (nonatomic, copy, readonly) NSString *installationPath;
@end
@implementation SUPlainInstaller
@synthesize host = _host;
@synthesize bundlePath = _bundlePath;
@synthesize installationPath = _installationPath;
{
SUHost *_host;
NSString *_bundlePath;
NSString *_installationPath;
NSURL *_temporaryOldDirectory;
// We get an obj-c warning if we use 'newTemporaryDirectory' name about new + ownership stuff, so use 'temporaryNewDirectory' instead
NSURL *_temporaryNewDirectory;
BOOL _newAndOldBundlesOnSameVolume;
BOOL _canPerformSafeAtomicSwap;
}
- (instancetype)initWithHost:(SUHost *)host bundlePath:(NSString *)bundlePath installationPath:(NSString *)installationPath
{
@@ -43,23 +43,89 @@
return self;
}
// Returns the bundle version from the specified host that is appropriate to use as a filename, or nil if we're unable to retrieve one
- (NSString *)bundleVersionAppropriateForFilenameFromHost:(SUHost *)host
- (void)_performInitialInstallationWithFileManager:(SUFileManager *)fileManager oldBundleURL:(NSURL *)oldBundleURL newBundleURL:(NSURL *)newBundleURL performGatekeeperScan:(BOOL)performGatekeeperScan progressBlock:(nullable void(^)(double))progress SPU_OBJC_DIRECT
{
NSString *bundleVersion = [host objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleVersionKey];
NSString *trimmedVersion = @"";
if (bundleVersion != nil) {
NSMutableCharacterSet *validCharacters = [NSMutableCharacterSet alphanumericCharacterSet];
[validCharacters formUnionWithCharacterSet:[NSCharacterSet characterSetWithCharactersInString:@".-()"]];
trimmedVersion = [bundleVersion stringByTrimmingCharactersInSet:[validCharacters invertedSet]];
// Release our new app from quarantine
NSError *quarantineError = nil;
if (![fileManager releaseItemFromQuarantineAtRootURL:newBundleURL error:&quarantineError]) {
// Not big enough of a deal to fail the entire installation
SULog(SULogLevelError, @"Failed to release quarantine at %@ with error %@", newBundleURL.path, quarantineError);
}
return trimmedVersion.length > 0 ? trimmedVersion : nil;
if (progress) {
progress(5/11.0);
}
// Try to preserve Finder Tags
NSArray *resourceTags = nil;
BOOL retrievedResourceTags = [oldBundleURL getResourceValue:&resourceTags forKey:NSURLTagNamesKey error:NULL];
if (retrievedResourceTags && resourceTags.count > 0) {
[newBundleURL setResourceValue:resourceTags forKey:NSURLTagNamesKey error:NULL];
}
if (progress) {
progress(6/11.0);
}
// Update owner and group (if possible)
NSError *changeOwnerAndGroupError = nil;
if (![fileManager changeOwnerAndGroupOfItemAtRootURL:newBundleURL toMatchURL:oldBundleURL error:&changeOwnerAndGroupError]) {
// Not a fatal error
SULog(SULogLevelError, @"Failed to change owner and group of new app at %@ to match old app at %@", newBundleURL.path, oldBundleURL.path);
SULog(SULogLevelError, @"Error: %@", changeOwnerAndGroupError);
}
if (progress) {
progress(7/11.0);
}
// Register the new bundle with LaunchServices and the system
NSError *touchError = nil;
if (![fileManager updateModificationAndAccessTimeOfItemAtURL:newBundleURL error:&touchError]) {
// Not a fatal error, but a pretty unfortunate one
SULog(SULogLevelError, @"Failed to update modification and access time of new app at %@", newBundleURL.path);
SULog(SULogLevelError, @"Error: %@", touchError);
}
if (progress) {
progress(8/11.0);
}
if (performGatekeeperScan) {
// Perform a Gatekeeper scan to pre-warm the app launch
// This avoids users seeing a "Verifying..." dialog when the installed update is launched
// Note the tool we use to perform the Gatekeeper scan (gktool) is technically available on macOS 14.0,
// however there are some potential bugs/issues with performing a Gatekeeper scan on versions before 14.4:
// https://github.com/sparkle-project/Sparkle/issues/2491
if (@available(macOS 14.4, *)) {
// Only perform Gatekeeper scan if we're updating an app bundle
NSString *newBundlePath = newBundleURL.path;
if ([newBundlePath.pathExtension caseInsensitiveCompare:@"app"] == NSOrderedSame) {
NSURL *gktoolURL = [NSURL fileURLWithPath:@"/usr/bin/gktool" isDirectory:NO];
if ([gktoolURL checkResourceIsReachableAndReturnError:NULL]) {
NSTask *gatekeeperScanTask = [[NSTask alloc] init];
gatekeeperScanTask.executableURL = gktoolURL;
gatekeeperScanTask.arguments = @[@"scan", newBundlePath];
NSError *taskError;
if (![gatekeeperScanTask launchAndReturnError:&taskError]) {
// Not a fatal error
SULog(SULogLevelError, @"Failed to perform GateKeeper scan on '%@' with error %@", newBundlePath, taskError);
} else {
[gatekeeperScanTask waitUntilExit];
if (gatekeeperScanTask.terminationStatus != 0) {
SULog(SULogLevelError, @"gktool failed and returned exit status %d", gatekeeperScanTask.terminationStatus);
}
}
}
}
}
}
}
- (BOOL)startInstallationToURL:(NSURL *)installationURL fromUpdateAtURL:(NSURL *)newURL withHost:(SUHost *)host progressBlock:(nullable void(^)(double))progress error:(NSError * __autoreleasing *)error
- (BOOL)startInstallationToURL:(NSURL *)installationURL fromUpdateAtURL:(NSURL *)newURL withHost:(SUHost *)host progressBlock:(nullable void(^)(double))progress error:(NSError * __autoreleasing *)error SPU_OBJC_DIRECT
{
if (installationURL == nil || newURL == nil) {
// this really shouldn't happen but just in case
@@ -71,7 +137,7 @@
}
if (progress) {
progress(1/10.0);
progress(1/11.0);
}
SUFileManager *fileManager = [[SUFileManager alloc] init];
@@ -80,49 +146,23 @@
// 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]) {
SULog(SULogLevelError, @"Failed to recursively update new application's modification time before moving into temporary directory");
return NO;
if (!_newAndOldBundlesOnSameVolume) {
NSError *accessTimeError = nil;
if (![fileManager updateAccessTimeOfItemAtRootURL:newURL error:&accessTimeError]) {
if (error != NULL) {
NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:@{ NSLocalizedDescriptionKey: @"Failed to recursively update new application's modification time before moving into temporary directory" }];
if (accessTimeError != nil) {
userInfo[NSUnderlyingErrorKey] = accessTimeError;
}
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:userInfo];
}
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) {
SULog(SULogLevelError, @"Failed to make new temp directory");
return NO;
}
if (progress) {
progress(2/10.0);
}
// Move the new app to our temporary directory
NSString *newURLLastPathComponent = newURL.lastPathComponent;
NSURL *newTempURL = [tempNewDirectoryURL URLByAppendingPathComponent:newURLLastPathComponent];
if (![fileManager moveItemAtURL:newURL toURL:newTempURL error:error]) {
SULog(SULogLevelError, @"Failed to move the new app from %@ to its temp directory at %@", newURL.path, newTempURL.path);
[fileManager removeItemAtURL:tempNewDirectoryURL error:NULL];
return NO;
}
if (progress) {
progress(3/10.0);
}
// Release our new app from quarantine
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
@@ -133,88 +173,148 @@
return NO;
}
// 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
if (![fileManager changeOwnerAndGroupOfItemAtRootURL:newTempURL toMatchURL:oldURL error:error]) {
// But this is big enough of a deal to fail
SULog(SULogLevelError, @"Failed to change owner and group of new app at %@ to match old app at %@", newTempURL.path, oldURL.path);
[fileManager removeItemAtURL:tempNewDirectoryURL error:NULL];
return NO;
if (progress) {
progress(2/11.0);
}
if (progress) {
progress(5/10.0);
}
NSError *touchError = nil;
if (![fileManager updateModificationAndAccessTimeOfItemAtURL:newTempURL error:&touchError]) {
// Not a fatal error, but a pretty unfortunate one
SULog(SULogLevelError, @"Failed to update modification and access time of new app at %@", newTempURL.path);
SULog(SULogLevelError, @"Error: %@", touchError);
}
if (progress) {
progress(6/10.0);
}
// Decide on a destination name we should use for the older app when we move it around the file system
NSString *oldDestinationName = 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;
if (tempOldDirectoryURL == nil) {
SULog(SULogLevelError, @"Failed to create temporary directory for old app at %@", oldURL.path);
[fileManager removeItemAtURL:tempNewDirectoryURL error:NULL];
return NO;
}
if (progress) {
progress(7/10.0);
}
// Move the old app to the temporary directory
NSURL *oldTempURL = [tempOldDirectoryURL URLByAppendingPathComponent:oldDestinationNameWithPathExtension];
if (![fileManager moveItemAtURL:oldURL toURL:oldTempURL error:error]) {
SULog(SULogLevelError, @"Failed to move the old app at %@ to a temporary location at %@", oldURL.path, oldTempURL.path);
NSURL *tempNewDirectoryURL;
if (!_newAndOldBundlesOnSameVolume) {
// Create a temporary directory for our new app that resides on our destination's volume
// We use oldURL here instead of installationURL because in the case of normalization, installationURL may not exist
// And we don't want to use either of the URL's parent directories because the parent directory could be on a different volume
tempNewDirectoryURL = [fileManager makeTemporaryDirectoryAppropriateForDirectoryURL:oldURL error:error];
if (tempNewDirectoryURL == nil) {
return NO;
}
// Just forget about our updated app on failure
[fileManager removeItemAtURL:tempNewDirectoryURL error:NULL];
[fileManager removeItemAtURL:tempOldDirectoryURL error:NULL];
return NO;
_temporaryNewDirectory = tempNewDirectoryURL;
} else {
tempNewDirectoryURL = nil;
}
if (progress) {
progress(8/10.0);
progress(3/11.0);
}
// Move the new app to its final destination
if (![fileManager moveItemAtURL:newTempURL toURL:installationURL error:error]) {
SULog(SULogLevelError, @"Failed to move new app at %@ to final destination %@", newTempURL.path, installationURL.path);
// Forget about our updated app on failure
[fileManager removeItemAtURL:tempNewDirectoryURL error:NULL];
// Attempt to restore our old app back the way it was on failure
[fileManager moveItemAtURL:oldTempURL toURL:oldURL error:NULL];
[fileManager removeItemAtURL:tempOldDirectoryURL error:NULL];
return NO;
// Move the new app to our temporary directory if needed
NSURL *newFinalURL;
if (!_newAndOldBundlesOnSameVolume) {
NSString *newURLLastPathComponent = newURL.lastPathComponent;
newFinalURL = [tempNewDirectoryURL URLByAppendingPathComponent:newURLLastPathComponent];
NSError *newTempMoveError = nil;
if (![fileManager moveItemAtURL:newURL toURL:newFinalURL error:&newTempMoveError]) {
if (error != NULL) {
NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to move the new app from %@ to its temp directory at %@", newURL.path, newFinalURL.path] }];
if (newTempMoveError != nil) {
userInfo[NSUnderlyingErrorKey] = newTempMoveError;
}
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:userInfo];
}
return NO;
}
} else {
newFinalURL = newURL;
}
if (progress) {
progress(9/10.0);
progress(4/11.0);
}
if (!_newAndOldBundlesOnSameVolume) {
// If we're updating a bundle on another volume, the install process can be pretty slow.
// In this case let's get out of the way and skip the Gatekeeper scan
[self _performInitialInstallationWithFileManager:fileManager oldBundleURL:oldURL newBundleURL:newFinalURL performGatekeeperScan:NO progressBlock:progress];
}
// Cleanup
[fileManager removeItemAtURL:tempOldDirectoryURL error:NULL];
[fileManager removeItemAtURL:tempNewDirectoryURL error:NULL];
if (progress) {
progress(9/11.0);
}
// First try swapping the application atomically
NSError *swapError = nil;
BOOL swappedApp;
// If we can not safely perform an atomic swap, or if the app is normalized and the installation path differs, go through the old swap path
if (!_canPerformSafeAtomicSwap || (SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME && ![oldURL.path isEqual:installationURL.path])) {
swappedApp = NO;
} else {
// We will be cleaning up the temporary directory later in -performCleanup:
// We don't want to clean it up now because it can take some time
swappedApp = [fileManager swapItemAtURL:installationURL withItemAtURL:newFinalURL error:&swapError];
}
if (!swappedApp) {
// Otherwise swap out the old and new applications using the legacy path
if (swapError != nil) {
SULog(SULogLevelDefault, @"Invoking fallback from failing to replace original item with error: %@", swapError);
}
// Create a temporary directory for our old app that resides on its volume
NSURL *tempOldDirectoryURL = [fileManager makeTemporaryDirectoryAppropriateForDirectoryURL:oldURL error:error];
if (tempOldDirectoryURL == nil) {
return NO;
}
_temporaryOldDirectory = tempOldDirectoryURL;
if (progress) {
progress(10/11.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:oldURLFilename];
NSError *oldMoveError = nil;
if (![fileManager moveItemAtURL:oldURL toURL:oldTempURL error:&oldMoveError]) {
if (error != NULL) {
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(10.5/11.0);
}
// Move the new app to its final destination
NSError *installMoveError = nil;
if (![fileManager moveItemAtURL:newFinalURL toURL:installationURL error:&installMoveError]) {
if (error != NULL) {
NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to move new app at %@ to final destination %@", newFinalURL.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
[fileManager moveItemAtURL:oldTempURL toURL:oldURL error:NULL];
return NO;
}
}
if (progress) {
progress(10/10.0);
progress(11/11.0);
}
return YES;
@@ -222,28 +322,65 @@
- (BOOL)performInitialInstallation:(NSError * __autoreleasing *)error
{
BOOL allowDowngrades = SPARKLE_AUTOMATED_DOWNGRADES;
// Prevent malicious downgrades
// Note that we may not be able to do this for package installations, hence this code being done here
if (!allowDowngrades) {
NSString *hostVersion = [self.host version];
NSString *hostVersion = [_host version];
NSBundle *bundle = [NSBundle bundleWithPath:_bundlePath];
SUHost *updateHost = [[SUHost alloc] initWithBundle:bundle];
NSString *updateVersion = [updateHost objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleVersionKey];
id<SUVersionComparison> comparator = [[SUStandardVersionComparator alloc] init];
if (!updateVersion || [comparator compareVersion:hostVersion toVersion:updateVersion] == NSOrderedDescending) {
NSBundle *bundle = [NSBundle bundleWithPath:self.bundlePath];
SUHost *updateHost = [[SUHost alloc] initWithBundle:bundle];
NSString *updateVersion = [updateHost objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleVersionKey];
id<SUVersionComparison> comparator = [[SUStandardVersionComparator alloc] init];
if (!updateVersion || [comparator compareVersion:hostVersion toVersion:updateVersion] == NSOrderedDescending) {
if (error != NULL) {
NSString *errorMessage = [NSString stringWithFormat:@"For security reasons, updates that downgrade version of the application are not allowed. Refusing to downgrade app from version %@ to %@. Aborting update.", hostVersion, updateVersion];
if (error != NULL) {
NSString *errorMessage = [NSString stringWithFormat:@"For security reasons, updates that downgrade version of the application are not allowed. Refusing to downgrade app from version %@ to %@. Aborting update.", hostVersion, updateVersion];
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUDowngradeError userInfo:@{ NSLocalizedDescriptionKey: errorMessage }];
}
return NO;
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUDowngradeError userInfo:@{ NSLocalizedDescriptionKey: errorMessage }];
}
return NO;
}
SUFileManager *fileManager = [[SUFileManager alloc] init];
BOOL updateHasCustomUpdateSecurityPolicy = NO;
if (@available(macOS 13.0, *)) {
// If the new update is notarized / developer ID code signed and Autoupdate is not signed with the same Team ID as the new update,
// then we may run into Privacy & Security prompt issues from the OS
// which think we are modifying the update (but we're not)
// To avoid these, we skip the gatekeeper scan and skip performing an atomic swap during install
// If the update has a custom update security policy, the same team ID policy may not apply,
// so in that case we will also skip performing an atomic swap
updateHasCustomUpdateSecurityPolicy = updateHost.hasUpdateSecurityPolicy;
if (updateHasCustomUpdateSecurityPolicy) {
// We don't handle working around a custom update security policy
_canPerformSafeAtomicSwap = NO;
} else {
NSString *installerTeamIdentifier = [SUCodeSigningVerifier teamIdentifierFromMainExecutable];
NSString *bundleTeamIdentifier = [SUCodeSigningVerifier teamIdentifierAtURL:bundle.bundleURL];
// If bundleTeamIdentifier is nil, then the update isn't code signed so atomic swap is okay
_canPerformSafeAtomicSwap = (bundleTeamIdentifier == nil || (installerTeamIdentifier != nil && [installerTeamIdentifier isEqualToString:bundleTeamIdentifier]));
}
} else {
_canPerformSafeAtomicSwap = YES;
}
if (!_canPerformSafeAtomicSwap) {
if (updateHasCustomUpdateSecurityPolicy) {
SULog(SULogLevelDefault, @"Skipping atomic rename/swap and gatekeeper scan because new update %@ has a custom NSUpdateSecurityPolicy", bundle.bundleURL.lastPathComponent);
} else {
SULog(SULogLevelDefault, @"Skipping atomic rename/swap and gatekeeper scan because Autoupdate is not signed with same identity as the new update %@", bundle.bundleURL.lastPathComponent);
}
}
_newAndOldBundlesOnSameVolume = [fileManager itemAtURL:bundle.bundleURL isOnSameVolumeItemAsURL:_host.bundle.bundleURL];
// We can do a lot of the installation work ahead of time if the new app update does not need to be copied to another volume
if (_newAndOldBundlesOnSameVolume) {
[self _performInitialInstallationWithFileManager:fileManager oldBundleURL:_host.bundle.bundleURL newBundleURL:bundle.bundleURL performGatekeeperScan:_canPerformSafeAtomicSwap progressBlock:NULL];
}
return YES;
@@ -253,7 +390,20 @@
{
// Note: we must do most installation work in the third stage due to relying on our application sitting in temporary directories.
// It must not be possible for our update to sit in temporary directories for a very long time.
return [self startInstallationToURL:[NSURL fileURLWithPath:self.installationPath] fromUpdateAtURL:[NSURL fileURLWithPath:self.bundlePath] withHost:self.host progressBlock:cb error:error];
return [self startInstallationToURL:[NSURL fileURLWithPath:_installationPath] fromUpdateAtURL:[NSURL fileURLWithPath:_bundlePath] withHost:_host progressBlock:cb error:error];
}
- (void)performCleanup
{
SUFileManager *fileManager = [[SUFileManager alloc] init];
if (_temporaryNewDirectory != nil) {
[fileManager removeItemAtURL:_temporaryNewDirectory error:NULL];
}
if (_temporaryOldDirectory != nil) {
[fileManager removeItemAtURL:_temporaryOldDirectory error:NULL];
}
}
- (BOOL)canInstallSilently
+10 -3
View File
@@ -18,15 +18,22 @@
#import <Foundation/Foundation.h>
@class SUSignatures;
@class SUPublicKeys;
@class SPUVerifierInformation;
@interface SUSignatureVerifier : NSObject
NS_ASSUME_NONNULL_BEGIN
+ (BOOL)validatePath:(NSString *)path withSignatures:(SUSignatures *)signatures withPublicKeys:(SUPublicKeys *)pkeys;
SPU_OBJC_DIRECT_MEMBERS @interface SUSignatureVerifier : NSObject
+ (BOOL)validatePath:(NSString *)path withSignatures:(SUSignatures *)signatures withPublicKeys:(SUPublicKeys *)pkeys verifierInformation:(SPUVerifierInformation * _Nullable)verifierInformation error:(NSError * __autoreleasing *)error;
- (instancetype)init NS_UNAVAILABLE;
- (instancetype)initWithPublicKeys:(SUPublicKeys *)pkeys;
- (BOOL)verifyFileAtPath:(NSString *)path signatures:(SUSignatures *)signatures;
- (BOOL)verifyFileAtPath:(NSString *)path signatures:(SUSignatures *)signatures verifierInformation:(SPUVerifierInformation * _Nullable)verifierInformation error:(NSError * __autoreleasing *)error;
@end
NS_ASSUME_NONNULL_END
#endif
+268 -69
View File
@@ -15,43 +15,49 @@
#import "SUSignatureVerifier.h"
#import "SULog.h"
#import "SUSignatures.h"
#import "SUErrors.h"
#import "SPUVerifierInformation.h"
#import "SUConstants.h"
#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT
#include <CommonCrypto/CommonDigest.h>
#import "ed25519.h" // Run `git submodule update --init` if you get an error here
#endif
#import "ed25519.h"
#include "AppKitPrevention.h"
@interface SUSignatureVerifier ()
@property (readonly) SUPublicKeys *pubKeys;
@end
@implementation SUSignatureVerifier {
@implementation SUSignatureVerifier
{
SUPublicKeys *_pubKeys;
}
@synthesize pubKeys = _pubKeys;
+ (BOOL)validatePath:(NSString *)path withSignatures:(SUSignatures *)signatures withPublicKeys:(SUPublicKeys *)pkeys
+ (BOOL)validatePath:(NSString *)path withSignatures:(SUSignatures *)signatures withPublicKeys:(SUPublicKeys *)pkeys verifierInformation:(SPUVerifierInformation * _Nullable)verifierInformation error:(NSError * __autoreleasing *)error
{
SUSignatureVerifier *verifier = [(SUSignatureVerifier *)[self alloc] initWithPublicKeys:pkeys];
if (!verifier) {
if (verifier == nil) {
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:@{ NSLocalizedDescriptionKey: @"Failed to create SUSignatureVerifier instance" }];
}
return NO;
}
return [verifier verifyFileAtPath:path signatures:signatures];
return [verifier verifyFileAtPath:path signatures:signatures verifierInformation:verifierInformation error:error];
}
- (instancetype)initWithPublicKeys:(SUPublicKeys *)pubkeys
{
self = [super init];
_pubKeys = pubkeys;
if (self != nil) {
_pubKeys = pubkeys;
}
return self;
}
- (SecKeyRef)dsaSecKeyRef {
NSData *data = [self.pubKeys.dsaPubKey dataUsingEncoding:NSASCIIStringEncoding];
#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT
- (SecKeyRef)dsaSecKeyRef SPU_OBJC_DIRECT
{
NSData *data = [_pubKeys.dsaPubKey dataUsingEncoding:NSASCIIStringEncoding];
if (!self || !data.length) {
SULog(SULogLevelError, @"Could not read public DSA key");
return nil;
@@ -84,74 +90,230 @@
CFRelease(items);
return dsaPubKeySecKey;
}
#endif
- (BOOL)verifyFileAtPath:(NSString *)path signatures:(SUSignatures *)signatures
- (BOOL)verifyFileAtPath:(NSString *)path signatures:(SUSignatures *)signatures verifierInformation:(SPUVerifierInformation * _Nullable)verifierInformation error:(NSError * __autoreleasing *)error
{
if (!path || !path.length) {
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:@{ NSLocalizedDescriptionKey: @"Path passed to verify has zero length and is not valid" }];
}
return NO;
}
if (!signatures) {
SULog(SULogLevelDefault, @"No signatures given to verifyFileAtPath");
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:@{ NSLocalizedDescriptionKey: @"No signatures given to verifyFileAtPath" }];
}
return NO;
}
NSData *dsaSignature = signatures.dsaSignature;
NSString *dsaPubKey = self.pubKeys.dsaPubKey;
const unsigned char *edSignature = signatures.ed25519Signature;
const unsigned char *edPubKey = self.pubKeys.ed25519PubKey;
if (edPubKey && !edSignature) {
SULog(SULogLevelDefault, @"There is no EdDSA signature in the update, but the app is capable of verifying them");
} if (!edPubKey && edSignature) {
SULog(SULogLevelDefault, @"The update has an EdDSA signature, but it won't be used, because the old app doesn't have an EdDSA public key");
} else if (edPubKey && edSignature) {
NSError *error = nil;
NSData *data = [NSData dataWithContentsOfFile:path options:NSDataReadingMappedAlways error:&error];
if (!data || !data.length) {
SULog(SULogLevelError, @"Failed to load file %@: %@", path, error);
switch (_pubKeys.ed25519PubKeyStatus) {
case SUSigningInputStatusAbsent:
if (signatures.ed25519SignatureStatus != SUSigningInputStatusAbsent) {
SULog(SULogLevelDefault, @"The update has an EdDSA signature, but it won't be used, because the old app doesn't have an EdDSA public key");
}
break;
case SUSigningInputStatusInvalid:
if (signatures.ed25519SignatureStatus != SUSigningInputStatusAbsent) {
NSString *message = @"The update has an EdDSA signature, but the app has an invalid EdDSA public key, so the update will automatically be rejected.";
SULog(SULogLevelError, @"%@", message);
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:@{ NSLocalizedDescriptionKey: message }];
}
return NO;
}
if (ed25519_verify(edSignature, data.bytes, data.length, edPubKey)) {
SULog(SULogLevelDefault, @"OK: EdDSA signature is correct");
if (!dsaPubKey) {
return YES;
SULog(SULogLevelDefault, @"The app has an invalid EdDSA public key, but there is no EdDSA signature in the update. Falling back to DSA.");
break;
case SUSigningInputStatusPresent:
switch (signatures.ed25519SignatureStatus) {
case SUSigningInputStatusAbsent: {
NSString *message = @"The app has an EdDSA public key, but there is no EdDSA signature in the update, so the update will be rejected.";
SULog(SULogLevelError, @"%@", message);
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:@{ NSLocalizedDescriptionKey: message }];
}
return NO;
}
case SUSigningInputStatusInvalid: {
NSString *message = @"The update has an EdDSA signature, but it's invalid, so the update will automatically be rejected.";
SULog(SULogLevelError, @"%@", message);
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:@{ NSLocalizedDescriptionKey: message }];
}
return NO;
}
case SUSigningInputStatusPresent: {
NSError *dataError = nil;
NSData *data = [NSData dataWithContentsOfFile:path options:NSDataReadingMappedAlways error:&dataError];
if (!data || !data.length) {
SULog(SULogLevelError, @"Failed to load file %@: %@", path, dataError);
if (error != NULL) {
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
userInfo[NSLocalizedDescriptionKey] = [NSString stringWithFormat:@"Failed to load file: %@", path];
if (dataError != nil) {
userInfo[NSUnderlyingErrorKey] = dataError;
}
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:[userInfo copy]];
}
return NO;
}
if (ed25519_verify(signatures.ed25519Signature, data.bytes, data.length, _pubKeys.ed25519PubKey)) {
SULog(SULogLevelDefault, @"OK: EdDSA signature is correct");
#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT
// No need to check DSA when EdDSA verification succeeded, unless a DSA signature is provided and it's
// erroneously invalid
if (signatures.dsaSignatureStatus != SUSigningInputStatusInvalid)
#endif
{
return YES;
}
} else {
SULog(SULogLevelDefault, @"This app has a DSA public key, so a DSA signature is required too");
NSMutableString *message = [NSMutableString stringWithString:@"EdDSA signature does not match. Data of the update file being checked is different than data that has been signed, or the public key and the private key are not from the same set."];
// Elaborate on the error message if we have more information about the download archive
if (verifierInformation != nil) {
BOOL reportedDiscrepancy = NO;
if (verifierInformation.expectedContentLength > 0 && verifierInformation.actualContentLength > 0) {
if (verifierInformation.expectedContentLength != verifierInformation.actualContentLength) {
[message appendFormat:@" The downloaded update (%@) is likely different than the signed archive because the expected content length from the appcast item (%llu bytes) differs from the downloaded archive length (%llu bytes).", path.lastPathComponent, verifierInformation.expectedContentLength, verifierInformation.actualContentLength];
reportedDiscrepancy = YES;
}
}
NSString *actualVersion = verifierInformation.actualVersion;
if (actualVersion != nil && ![verifierInformation.expectedVersion isEqualToString:actualVersion]) {
[message appendFormat:@" The downloaded update (%@) also has a CFBundleVersion (%@) which differs from the %@ in the appcast item (%@).", path.lastPathComponent, actualVersion, SUAppcastAttributeVersion, verifierInformation.expectedVersion];
reportedDiscrepancy = YES;
}
if (!reportedDiscrepancy && verifierInformation.expectedContentLength > 0) {
[message appendFormat:@" The downloaded update (%@) is likely not signed correctly because the archive has the expected content length (%llu bytes)%@ which matches the appcast item.", path.lastPathComponent, verifierInformation.actualContentLength, (actualVersion == nil ? @"" : [NSString stringWithFormat:@" and CFBundleVersion (%@)", actualVersion])];
}
}
SULog(SULogLevelError, @"%@", [message copy]);
#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT
if (signatures.dsaSignatureStatus != SUSigningInputStatusAbsent) {
SULog(SULogLevelDefault, @"DSA signature won't be checked, because EdDSA verification has already failed");
}
#endif
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:@{ NSLocalizedDescriptionKey: message }];
}
return NO;
}
} else {
SULog(SULogLevelError, @"EdDSA signature does not match. Data of the update file being checked is different than data that has been signed, or the public key and the private key are not from the same set.");
if (dsaSignature) {
SULog(SULogLevelDefault, @"DSA signature won't be checked, because EdDSA verification has already failed");
}
return NO;
}
}
break;
}
if (!dsaSignature) {
SULog(SULogLevelError, @"There is no DSA signature in the update");
} else if (!dsaPubKey) {
SULog(SULogLevelDefault, @"The update has a DSA signature, but it can't be used, because the old app doesn't have a DSA public key");
} else {
NSInputStream *dataInputStream = [NSInputStream inputStreamWithFileAtPath:path];
return [self verifyDSASignatureOfStream:dataInputStream dsaSignature:dsaSignature];
#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT
switch (_pubKeys.dsaPubKeyStatus) {
case SUSigningInputStatusAbsent:
if (signatures.dsaSignatureStatus != SUSigningInputStatusAbsent) {
SULog(SULogLevelDefault, @"The update has a DSA signature, but it can't be used, because the old app doesn't have a DSA public key");
}
break;
case SUSigningInputStatusInvalid:
if (signatures.dsaSignatureStatus != SUSigningInputStatusAbsent) {
// We will have already logged an error for this failure when the public key was read in, so just do an informational log here.
NSString *message = @"The update has a DSA signature, but the app has an invalid DSA public key, so the update will automatically be rejected.";
SULog(SULogLevelError, @"%@", message);
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:@{ NSLocalizedDescriptionKey: message }];
}
return NO;
}
SULog(SULogLevelDefault, @"The app has an invalid DSA public key, but there is no DSA signature in the update.");
break;
case SUSigningInputStatusPresent:
switch (signatures.dsaSignatureStatus) {
case SUSigningInputStatusAbsent:
SULog(SULogLevelError, @"There is no DSA signature in the update");
break;
case SUSigningInputStatusInvalid: {
NSString *message = @"The update has a DSA signature, but it's invalid, so the update will automatically be rejected.";
SULog(SULogLevelError, @"%@", message);
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:@{ NSLocalizedDescriptionKey: message }];
}
return NO;
}
case SUSigningInputStatusPresent: {
NSInputStream *dataInputStream = [NSInputStream inputStreamWithFileAtPath:path];
return [self verifyDSASignatureOfStream:dataInputStream dsaSignature:signatures.dsaSignature error:error];
}
}
}
#else
switch (_pubKeys.dsaPubKeyStatus) {
case SUSigningInputStatusAbsent:
break;
case SUSigningInputStatusInvalid:
// We don't keep track of DSA signatures, so we will ignore this mistake and treat it as if it were absent
break;
case SUSigningInputStatusPresent:
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:@{ NSLocalizedDescriptionKey: @"The old app has a DSA public key but DSA support is disabled, and the old app does not have an EdDSA public key." }];
}
return NO;
}
#endif
if (error != NULL) {
// Use generic failure
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:@{ NSLocalizedDescriptionKey: @"EdDSA and DSA verification for the update has failed" }];
}
return NO;
}
- (BOOL)verifyDSASignatureOfStream:(NSInputStream *)stream dsaSignature:(NSData *)dsaSignature
#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT
- (BOOL)verifyDSASignatureOfStream:(NSInputStream *)stream dsaSignature:(NSData *)dsaSignature error:(NSError * __autoreleasing *)outError SPU_OBJC_DIRECT
{
if (!stream || !dsaSignature) {
SULog(SULogLevelError, @"Invalid arguments to verifyStream");
if (outError != NULL) {
*outError = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:@{ NSLocalizedDescriptionKey: @"Invalid arguments to verifyStream" }];
}
return NO;
}
SecKeyRef dsaPubKeySecKey = [self dsaSecKeyRef];
if (!dsaPubKeySecKey) {
if (outError != NULL) {
*outError = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:@{ NSLocalizedDescriptionKey: @"Failed to create DSA Sec Key Ref" }];
}
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;
@@ -170,48 +332,85 @@
dataReadTransform = SecTransformCreateReadTransformWithReadStream((__bridge CFReadStreamRef)stream);
if (!dataReadTransform) {
SULog(SULogLevelError, @"File containing update archive could not be read (failed to create SecTransform for input stream)");
if (outError != NULL) {
*outError = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:@{ NSLocalizedDescriptionKey: @"File containing update archive could not be read (failed to create SecTransform for input stream)" }];
}
return cleanup();
}
dataDigestTransform = SecDigestTransformCreate(kSecDigestSHA1, CC_SHA1_DIGEST_LENGTH, NULL);
if (!dataDigestTransform) {
if (outError != NULL) {
*outError = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:@{ NSLocalizedDescriptionKey: @"File containing update archive could not be read (failed to create SecDigest for input stream)" }];
}
return cleanup();
}
dataVerifyTransform = SecVerifyTransformCreate(dsaPubKeySecKey, (__bridge CFDataRef)dsaSignature, &error);
if (!dataVerifyTransform) {
SULog(SULogLevelError, @"Could not understand format of the signature: %@; Signature data: %@", error, dsaSignature);
if (outError != NULL) {
NSError *underlyingError = (__bridge NSError *)error;
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
userInfo[NSLocalizedDescriptionKey] = [NSString stringWithFormat:@"Could not understand format of the signature data %@", dsaSignature];
if (underlyingError != NULL) {
userInfo[NSUnderlyingErrorKey] = underlyingError;
}
*outError = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:[userInfo copy]];
}
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}];
}
return cleanup();
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdirect-ivar-access"
dataVerifyTransform = SecVerifyTransformCreate(dsaPubKeySecKey, (__bridge CFDataRef)dsaSignature, &error);
#pragma clang diagnostic pop
if (!dataVerifyTransform || error) {
SULog(SULogLevelError, @"Could not understand format of the signature: %@; Signature data: %@", error, dsaSignature);
return cleanup();
}
SecTransformConnectTransforms(dataReadTransform, kSecTransformOutputAttributeName, dataDigestTransform, kSecTransformInputAttributeName, group, &error);
if (error) {
SULog(SULogLevelError, @"%@", error);
return cleanup();
}
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
SecTransformConnectTransforms(dataDigestTransform, kSecTransformOutputAttributeName, dataVerifyTransform, kSecTransformInputAttributeName, group, &error);
#pragma clang diagnostic pop
if (error) {
SULog(SULogLevelError, @"%@", error);
if (outError != NULL) {
*outError = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:@{NSLocalizedDescriptionKey : @"Failed to connect data digest transform", NSUnderlyingErrorKey: (__bridge NSError *)error}];
}
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) {
*outError = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:@{ NSLocalizedDescriptionKey: @"DSA signature verification failed", NSUnderlyingErrorKey: (__bridge NSError *)error}];
}
return cleanup();
}
if (!result.boolValue) {
SULog(SULogLevelError, @"DSA signature does not match. Data of the update file being checked is different than data that has been signed, or the public key and the private key are not from the same set.");
if (outError != NULL) {
*outError = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:@{ NSLocalizedDescriptionKey: @"DSA signature does not match. Data of the update file being checked is different than data that has been signed, or the public key and the private key are not from the same set"}];
}
}
cleanup();
return result.boolValue;
}
#endif
@end
+2 -2
View File
@@ -12,9 +12,9 @@ NS_ASSUME_NONNULL_BEGIN
@protocol SUUnarchiverProtocol;
@interface SUUnarchiver : NSObject
SPU_OBJC_DIRECT_MEMBERS @interface SUUnarchiver : NSObject
+ (nullable id <SUUnarchiverProtocol>)unarchiverForPath:(NSString *)path updatingHostBundlePath:(nullable NSString *)hostPath decryptionPassword:(nullable NSString *)decryptionPassword;
+ (nullable id <SUUnarchiverProtocol>)unarchiverForPath:(NSString *)path extractionDirectory:(NSString *)extractionDirectory updatingHostBundlePath:(nullable NSString *)hostPath decryptionPassword:(nullable NSString *)decryptionPassword expectingInstallationType:(NSString *)installationType;
@end
+15 -8
View File
@@ -11,25 +11,32 @@
#import "SUPipedUnarchiver.h"
#import "SUDiskImageUnarchiver.h"
#import "SUBinaryDeltaUnarchiver.h"
#import "SUFlatPackageUnarchiver.h"
#include "AppKitPrevention.h"
@implementation SUUnarchiver
+ (nullable id <SUUnarchiverProtocol>)unarchiverForPath:(NSString *)path updatingHostBundlePath:(nullable NSString *)hostPath decryptionPassword:(nullable NSString *)decryptionPassword
+ (nullable id <SUUnarchiverProtocol>)unarchiverForPath:(NSString *)path extractionDirectory:(NSString *)extractionDirectory updatingHostBundlePath:(nullable NSString *)hostPath decryptionPassword:(nullable NSString *)decryptionPassword expectingInstallationType:(NSString *)installationType
{
if ([SUPipedUnarchiver canUnarchivePath:path]) {
return [[SUPipedUnarchiver alloc] initWithArchivePath:path];
} else if ([SUDiskImageUnarchiver canUnarchivePath:path]) {
return [[SUDiskImageUnarchiver alloc] initWithArchivePath:path decryptionPassword:decryptionPassword];
} else if ([SUBinaryDeltaUnarchiver canUnarchivePath:path]) {
return [[SUPipedUnarchiver alloc] initWithArchivePath:path extractionDirectory:extractionDirectory];
}
else if ([SUDiskImageUnarchiver canUnarchivePath:path]) {
return [[SUDiskImageUnarchiver alloc] initWithArchivePath:path extractionDirectory:extractionDirectory decryptionPassword:decryptionPassword];
}
else if ([SUBinaryDeltaUnarchiver canUnarchivePath:path]) {
assert(hostPath != nil);
NSString *nonNullHostPath = hostPath;
return [[SUBinaryDeltaUnarchiver alloc] initWithArchivePath:path updateHostBundlePath:nonNullHostPath];
return [[SUBinaryDeltaUnarchiver alloc] initWithArchivePath:path extractionDirectory:extractionDirectory updateHostBundlePath:nonNullHostPath];
}
#if SPARKLE_BUILD_PACKAGE_SUPPORT
else if ([SUFlatPackageUnarchiver canUnarchivePath:path]) {
// Flat packages are only supported for guided packaage installs
return [[SUFlatPackageUnarchiver alloc] initWithFlatPackagePath:path extractionDirectory:extractionDirectory expectingInstallationType:installationType];
}
#endif
return nil;
}
+1 -1
View File
@@ -10,7 +10,7 @@
NS_ASSUME_NONNULL_BEGIN
@interface SUUnarchiverNotifier : NSObject
SPU_OBJC_DIRECT_MEMBERS @interface SUUnarchiverNotifier : NSObject
- (instancetype)initWithCompletionBlock:(void (^)(NSError * _Nullable))completionBlock progressBlock:(void (^ _Nullable)(double))progressBlock;
+12 -16
View File
@@ -8,22 +8,16 @@
#import "SUUnarchiverNotifier.h"
#import "SULocalizations.h"
#import <Sparkle/SUErrors.h>
#import "SUErrors.h"
#include "AppKitPrevention.h"
@interface SUUnarchiverNotifier ()
@property (nonatomic, readonly, copy) void (^completionBlock)(NSError * _Nullable);
@property (nonatomic, readonly, copy) void (^ _Nullable progressBlock)(double);
@end
@implementation SUUnarchiverNotifier
@synthesize completionBlock = _completionBlock;
@synthesize progressBlock = _progressBlock;
{
void (^_completionBlock)(NSError * _Nullable);
void (^ _Nullable _progressBlock)(double);
}
- (instancetype)initWithCompletionBlock:(void (^)(NSError * _Nullable))completionBlock progressBlock:(void (^ _Nullable)(double))progressBlock
{
@@ -31,6 +25,8 @@
if (self != nil) {
_completionBlock = [completionBlock copy];
_progressBlock = [progressBlock copy];
} else {
assert(false);
}
return self;
}
@@ -38,13 +34,13 @@
- (void)notifySuccess
{
dispatch_async(dispatch_get_main_queue(), ^{
self.completionBlock(nil);
self->_completionBlock(nil);
});
}
- (void)notifyFailureWithError:(NSError * _Nullable)reason
{
NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithObject:SULocalizedString(@"An error occurred while extracting the archive. Please try again later.", nil) forKey:NSLocalizedDescriptionKey];
NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithObject:@"An error occurred while extracting the archive. Please try again later." forKey:NSLocalizedDescriptionKey];
if (reason) {
[userInfo setObject:(NSError * _Nonnull)reason forKey:NSUnderlyingErrorKey];
}
@@ -52,15 +48,15 @@
NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:userInfo];
dispatch_async(dispatch_get_main_queue(), ^{
self.completionBlock(error);
self->_completionBlock(error);
});
}
- (void)notifyProgress:(double)progress
{
if (self.progressBlock != nil) {
if (_progressBlock != nil) {
dispatch_async(dispatch_get_main_queue(), ^{
self.progressBlock(progress);
self->_progressBlock(progress);
});
}
}
+3 -3
View File
@@ -12,11 +12,11 @@ NS_ASSUME_NONNULL_BEGIN
@protocol SUUnarchiverProtocol <NSObject>
+ (BOOL)canUnarchivePath:(NSString *)path;
+ (BOOL)mustValidateBeforeExtraction;
- (void)unarchiveWithCompletionBlock:(void (^)(NSError * _Nullable))completionBlock progressBlock:(void (^ _Nullable)(double))progressBlock;
- (void)unarchiveWithCompletionBlock:(void (^)(NSError * _Nullable))completionBlock progressBlock:(void (^ _Nullable)(double))progressBlock waitForCleanup:(BOOL)waitForCleanup;
@property (nonatomic, readonly) BOOL needsVerifyBeforeExtractionKey;
- (NSString *)description;
+1 -1
View File
@@ -11,7 +11,7 @@
NS_ASSUME_NONNULL_BEGIN
@interface StatusInfo : NSObject <SUStatusInfoProtocol>
SPU_OBJC_DIRECT_MEMBERS @interface StatusInfo : NSObject <SUStatusInfoProtocol>
- (instancetype)initWithHostBundleIdentifier:(NSString *)bundleIdentifier;
+44 -8
View File
@@ -12,15 +12,19 @@
#include "AppKitPrevention.h"
#define REPLY_STATUS_INFO_TIMEOUT 2
@interface StatusInfo () <NSXPCListenerDelegate>
@property (nonatomic) NSXPCListener *xpcListener;
@end
@implementation StatusInfo
{
NSXPCListener *_xpcListener;
NSMutableDictionary *_pendingReplies;
NSUInteger _pendingReplyCounter;
}
@synthesize xpcListener = _xpcListener;
@synthesize installationInfoData = _installationInfoData;
- (instancetype)initWithHostBundleIdentifier:(NSString *)bundleIdentifier
@@ -29,19 +33,20 @@
if (self != nil) {
_xpcListener = [[NSXPCListener alloc] initWithMachServiceName:SPUStatusInfoServiceNameForBundleIdentifier(bundleIdentifier)];
_xpcListener.delegate = self;
_pendingReplies = [NSMutableDictionary dictionary];
}
return self;
}
- (void)startListener
{
[self.xpcListener resume];
[_xpcListener resume];
}
- (void)invalidate
{
[self.xpcListener invalidate];
self.xpcListener = nil;
[_xpcListener invalidate];
_xpcListener = nil;
}
- (BOOL)listener:(NSXPCListener *)__unused listener shouldAcceptNewConnection:(NSXPCConnection *)newConnection
@@ -54,10 +59,41 @@
return YES;
}
- (void)setInstallationInfoData:(NSData *)installationInfoData
{
_installationInfoData = installationInfoData;
// Respond to all of our pending replies
for (NSNumber *replyKey in _pendingReplies) {
void (^replyBlock)(NSData * _Nullable) = self->_pendingReplies[replyKey];
replyBlock(_installationInfoData);
}
[_pendingReplies removeAllObjects];
}
- (void)probeStatusInfoWithReply:(void (^)(NSData * _Nullable))reply
{
dispatch_async(dispatch_get_main_queue(), ^{
reply(self.installationInfoData);
if (self->_installationInfoData != nil) {
reply(self->_installationInfoData);
} else {
// If we don't have the installation info data currently, we may receive it in a very short window afterwards
// In this case wait a bit for the reply. If we receive the data it will be in -setInstallationInfoData:
NSUInteger currentReplyCounter = self->_pendingReplyCounter;
self->_pendingReplyCounter++;
NSNumber *currentReplyCounterKey = @(currentReplyCounter);
self->_pendingReplies[currentReplyCounterKey] = [reply copy];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(REPLY_STATUS_INFO_TIMEOUT * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
void (^replyBlock)(NSData * _Nullable) = self->_pendingReplies[currentReplyCounterKey];
if (replyBlock != nil) {
replyBlock(self->_installationInfoData);
[self->_pendingReplies removeObjectForKey:currentReplyCounterKey];
}
});
}
});
}
-24
View File
@@ -1,24 +0,0 @@
//
// TerminationListener.h
// Sparkle
//
// Created by Mayur Pawashe on 3/7/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface TerminationListener : NSObject
- (instancetype)initWithProcessIdentifier:(NSNumber * _Nullable)processIdentifier;
@property (nonatomic, readonly) BOOL terminated;
// If the process identifier provided was nil, then the completion block will invoke immediately with a YES success
- (void)startListeningWithCompletion:(void (^)(BOOL success))completionBlock;
@end
NS_ASSUME_NONNULL_END
-131
View File
@@ -1,131 +0,0 @@
//
// TerminationListener.m
// Sparkle
//
// Created by Mayur Pawashe on 3/7/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import "TerminationListener.h"
#import "SULog.h"
#include <sys/types.h>
#include <sys/event.h>
#include <sys/time.h>
#include "AppKitPrevention.h"
@interface TerminationListener ()
@property (nonatomic, readonly, nullable) NSNumber *processIdentifier;
@property (nonatomic) BOOL watchedTermination;
@property (nonatomic, copy) void (^completionBlock)(BOOL);
@end
@implementation TerminationListener
@synthesize completionBlock = _completionBlock;
@synthesize processIdentifier = _processIdentifier;
@synthesize watchedTermination = _watchedTermination;
- (instancetype)initWithProcessIdentifier:(NSNumber * _Nullable)processIdentifier
{
self = [super init];
if (self != nil) {
_processIdentifier = processIdentifier;
}
return self;
}
- (BOOL)terminated
{
return (self.watchedTermination || self.processIdentifier == nil) ? YES : (kill(self.processIdentifier.intValue, 0) != 0);
}
- (void)invokeCompletionWithSuccess:(BOOL)success
{
if (self.completionBlock != nil) {
self.completionBlock(success);
self.completionBlock = nil;
}
}
- (void)startListeningWithCompletion:(void (^)(BOOL))completionBlock
{
self.completionBlock = completionBlock;
if (self.processIdentifier == nil) {
[self invokeCompletionWithSuccess:YES];
return;
}
// Use kqueues to determine when the process will terminate
// As described in https://developer.apple.com/library/mac/technotes/tn2050/_index.html#//apple_ref/doc/uid/DTS10003081-CH1-SUBSECTION10
// By using kqueues, we can stay away from using AppKit in case we ever decide to abandon it
pid_t processIdentifier = self.processIdentifier.intValue;
int queue = kqueue();
if (queue == -1) {
SULog(SULogLevelError, @"Failed to create kqueue() due to error %d: %@", errno, @(strerror(errno)));
[self invokeCompletionWithSuccess:NO];
return;
}
struct kevent changes;
EV_SET(&changes, processIdentifier, EVFILT_PROC, EV_ADD | EV_RECEIPT, NOTE_EXIT, 0, NULL);
if (kevent(queue, &changes, 1, &changes, 1, NULL) == -1) {
SULog(SULogLevelError, @"Failed to invoke kevent() due to error %d: %@", errno, @(strerror(errno)));
[self invokeCompletionWithSuccess:NO];
return;
}
// We will assume this terminationListener will never be deallocated
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wcast-qual"
CFFileDescriptorContext context = { 0, (void *)CFBridgingRetain(self), NULL, NULL, NULL };
#pragma clang diagnostic pop
CFFileDescriptorRef noteExitKQueueRef = CFFileDescriptorCreate(NULL, queue, true, noteExitKQueueCallback, &context);
if (noteExitKQueueRef == NULL) {
SULog(SULogLevelError, @"Failed to create file descriptor via CFFileDescriptorCreate()");
CFRelease((__bridge CFTypeRef)(self));
[self invokeCompletionWithSuccess:NO];
return;
}
CFRunLoopSourceRef runLoopSource = CFFileDescriptorCreateRunLoopSource(NULL, noteExitKQueueRef, 0);
if (runLoopSource == NULL) {
SULog(SULogLevelError, @"Failed to create runLoopSource via CFFileDescriptorCreateRunLoopSource()");
CFRelease((__bridge CFTypeRef)(self));
[self invokeCompletionWithSuccess:NO];
return;
}
CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopDefaultMode);
CFRelease(runLoopSource);
CFFileDescriptorEnableCallBacks(noteExitKQueueRef, kCFFileDescriptorReadCallBack);
// Make sure we didn't set the listener callback to a dead PID
// If we did, we could hang forever. To avoid this, we check if the process has terminated *after* we set up the callback
// If we tried to do this check before setting the callback, we could run into an issue where the process can terminate after our check
// but before setting the callback
if ([self terminated]) {
[self invokeCompletionWithSuccess:YES];
}
}
static void noteExitKQueueCallback(CFFileDescriptorRef file, CFOptionFlags __unused callBackTypes, void *info)
{
struct kevent event;
kevent(CFFileDescriptorGetNativeDescriptor(file), NULL, 0, &event, 1, NULL);
TerminationListener *self = CFBridgingRelease(info);
self.watchedTermination = YES;
[self invokeCompletionWithSuccess:YES];
}
@end
+12 -3
View File
@@ -9,21 +9,30 @@ int main(int __unused argc, const char __unused *argv[])
@autoreleasepool
{
NSArray<NSString *> *args = [[NSProcessInfo processInfo] arguments];
if (args.count != 2) {
if (args.count != 4) {
return EXIT_FAILURE;
}
NSString *hostBundleIdentifier = args[1];
NSString *homeDirectory = args[2];
NSString *userName = args[3];
AppInstaller *appInstaller = [[AppInstaller alloc] initWithHostBundleIdentifier:hostBundleIdentifier];
AppInstaller *appInstaller = [[AppInstaller alloc] initWithHostBundleIdentifier:hostBundleIdentifier homeDirectory:homeDirectory userName:userName];
[appInstaller start];
// 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, ^{
[appInstaller cleanupAndExitWithStatus:SIGTERM];
// Don't clear the update directory because the installer may be in middle of installing an update
// We still need to set an event handler for receiving SIGTERM though, otherwise our job may not terminate
// (This is also recommended from the developer documentation).
// Simply exit with SIGTERM if we receive this signal
exit(SIGTERM);
});
dispatch_resume(sigtermSource);
+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: .hidden)
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()
+510 -2
View File
@@ -1,7 +1,515 @@
# 2.8.0
* UI modernization and macOS Tahoe support
* Modernize update alert and release notes UI (#2737) (Zorg, Noah Nuebling, Cykelero, Daniel Jalkut, Peter Nowell)
* Update retrieving app icon to work better in Tahoe (#2742) (Zorg)
* Improve retrieval of main app icon for authorization dialog (#2743) (Zorg)
* Delta updates
* Improve bsdiff performance by preventing excessive iterations when processing similar data blocks (#2693) (Will Fairclough)
* Fix an issue while searching a cloneable file for delta updates (#2748, #2753) (Vincent Bénony, Zorg)
* Add support for relative URLs for delta updates (#2741) (jj)
* Localization
* Set STRINGS_FILE_OUTPUT_ENCODING build setting to "binary" (#2712) (Nicolas Kick)
* Move all localizations to main Sparkle.strings (#2760) (Zorg)
* Synchronize updater settings with user defaults to fix out-of-sync UI state (#2728) (Zorg)
* Document and better enforce main thread only requirement for using Sparkle methods (#2746, #2754) (Sebastien Marchand, Zorg)
* Make -[SPUUserDriver showUpdateInFocus] optional (#2717) (Zorg)
* Add private module map for framework (#2722) (Zorg)
* Workaround a corner case in which the bundle path of a running application contains Contents/MacOS/Executable (#2726, #2747) (Jeremy Huddleston Sequoia, Zorg)
* Disable false dependency scan analysis warnings when building Sparkle from source (#2762) (Daniel Jalkut)
* Refactor the logic for avoiding re-sending the system profile more frequently than once a week (#2720) (Daniel Jalkut)
# 2.7.3
* Double quote team identifiers in requirement strings to fix crash if Team ID starts with number (#2766) (Zorg)
# 2.7.2
* Harden policy on what operations clients are allowed to take (#2763) (Zorg)
# 2.7.1
* Fix typo in NN localisation (#2694) (Sjur N Moshagen)
* Fix compiler warnings for Xcode 16.3 (#2709) (Zorg)
* Fix Sparkle not building when SPARKLE_COPY_LOCALIZATIONS=0 (#2707) (Zorg)
* Fix release notes constraints when compiled with macOS 26 SDK (#2730) (Zorg)
* Fix reserved identifier warnings for Xcode 26 (#2729) (Zorg)
# 2.7.0
* Unarchiver / validation improvements (Zorg)
* Remove old checksum verification checks for dmg archives to improve extraction speed (#2568) (Zorg)
* Skip extracting auxiliary files and improve extraction progress for disk images (#2569) (Zorg)
* Improve robustness around extracting dmg's with passwords (#2627, #2571) (Zorg)
* Randomize the download archive name the installer extracts/executes (#2584) (Zorg)
* Retry extracting zip file without piping if extraction fails to workaround bug prior to macOS 15 (#2616) (Zorg)
* Add opt-in SUVerifyUpdateBeforeExtraction option to force verification of updates before extraction (#2667) (Zorg)
* Add support for extracting Apple Archives (.aar files; requires SUVerifyUpdateBeforeExtraction, macOS 10.15+) (#2586, #2588, #2590) (Zorg)
* Don't allow removal of signing keys more strictly (#2647) (Zorg)
* Remove SPARKLE_BUILD_DMG_SUPPORT option (#2690) (Zorg)
* Add new BinaryDelta format (version 4) (Zorg)
* Preserve bundle creation date when creating and applying delta updates (#2583) (Zorg)
* Use faster crc32 hashes for binary delta version 4 (#2638) (Zorg)
* Make binary delta version 4 the default (#2668) (Zorg)
* Language / layout improvements
* Fix recovery error suggestion not shown when app is translocated or on read-only mount (#2689) (Zorg)
* Fix typo in Dutch localisation (#2642) (Eitot)
* Add baseline alignment to status text in SUStatus dialog (#2587) (Eitot)
* Make horizontal hugging priority required for status text field (#2614) (Zorg)
* Adjust the layout of anonymous system profile info to align better with the rest of the panel's UI (#2564) (Daniel Jalkut)
* Fix typo in Dutch localisation (#2642) (Eitot)
* Internationalize system profile display keys (#2577) (Zorg)
* Update hebrew locale and add right-to-left characters (#2573, #2576, #2578, #2579) (Shlomo)
* Update localisations for Dutch and German (#2582) (Eitot)
* Add unlocalized strings in Japanese (#2589) (1024jp)
* Fix typo in LICENSE (#2648) (fujisoft)
* Deprecate custom version comparators (#2639) (Zorg)
* Skip preflight update check in sparkle-cli if user is root (#2645) (Zorg)
* Avoid assert/crash when app is moved before update alert shows (#2658) (Zorg)
* Use default NSURLRequest timeoutInterval for the downloader (currently 60s) (#2673) (Zorg)
* Fix process substitution failing to work for providing the private key as file argument (#2615) (Zorg)
* Improve unable decode private key error messages in generate_appcast (#2675) (Zorg)
* Clarify that default channel must be in allowed channels set in API documentation (#2676) (Zorg)
* Call update permission prompt delegate method only when needed (#2622) (Zorg)
* Resolve duplicate class definitions from BinaryDelta, Sparkle Test App, and unit tests (#2570, #2629) (Zorg)
# 2.6.4
* Fix app modification prompt from appearing when downloaded update overrides NSUpdateSecurityPolicy (#2593)
# 2.6.3
* Guard update timer update check against sessionInProgress to fix rare crash when checking for updates (#2561)
* Remove extra writeData: call when unarchiving disk images (#2562)
* Ignore crashes due to SIGPIPE in generate_appcast when failing to extract zip files (#2563)
# 2.6.2
* Create and use temp extraction directory in generate_appcast again (#2555) (Zorg)
# 2.6.1
* Extract archives in a separate directory from the input archive (#2550) (Zorg)
* Fix the release notes WebKit view not updating background when transitioning from light to dark mode (#2542) (Zorg)
* Add NN (Norwegian Nynorsk) locale (#2532) (Sjur N Moshagen, Zorg)
* Create tar.xz files with built-in tar and remove bzip2 fallback for creating a release distribution (#2535) (Zorg)
* Add fallback in case SULocalizedStringFromTableInBundle() fails (#2533) (Zorg)
* Remove assert on download response being available fixing rare crash (#2547) (Zorg)
* Clarify when authoriation prompt may show in SPUUserDriver documentation (#2531, #2534) (Zorg)
* Fix typos in codebase (#2537) (Viktor Szépe)
# 2.6.0
* Perform Gatekeeper scan to pre-warm app launch (#2505) (Zorg)
* Disable sandboxing for the Downloader XPC service by default to fix downloader prompt warnings (#2511) (Zorg)
* Store private seed as the secret for newly generated keys (#2472) (Zorg)
* Improve signing error message to developers if they serve the wrong update file (#2471) (Zorg)
* Prevent app modification warnings from external updaters (like sparkli-cli) by improving installation (#2516) (Zorg)
* Update Korean localization (#2504) (CheolHyun Mun)
* Use $PROJECT_DIR instead of $SRCROOT (#2489) (Zorg)
* Set Package.swift minimum deployment to macOS 10.13 (#2481) (Eitot)
* Fix false positive analyzer warning about resumableUpdate type (#2454) (Zorg)
# 2.5.2
* Don't clean up update directory when Autoupdate receives SIGTERM (#2479) (Zorg)
* Update Japanese localization (#2475) (1024jp)
* Improve Turkish translations (#2464) (Emir SARI)
* Update Spanish translation for 'You are currently running version %@.' and 'Version History' (#2463) (Billy Gray)
# 2.5.1
* Default to English for XML nodes when no xml:lang is present (#2440) (Zorg)
* Filter for archive files in generate_appcast more intelligently (#2448) (Zorg)
* Use correct entitlements and dsym files when using custom bundle id and XPC names in ConfigCommon (#2446) (floorish)
# 2.5.0
* Add ability to adapt release notes based on the currently installed version (#2373) (Nathan Manceaux-Panot)
* Allow developers to use custom URL schemes in the release notes view (#2393) (Zorg)
* Adopt cooperative app activation APIs in macOS 14 Sonoma (#2409) (Zorg)
* Improve permission prompt layout (#2420) (Zorg)
* Remove hyphenation in "You're up to date" message (#2425) (Zorg, Dom Neill)
* Pre-warm installs before relaunch and resolve sporadic failures in CI (#2421) (Zorg)
* Fix make release not building distribution successfully (#2430) (Zorg)
* Fix Updater app not starting when running Sparkle as root (e.g. from CLI with sudo or a daemon) on macOS 14 Sonoma (#2432) (Zorg)
* Fix KVO usage for updaterController.updater.* (#2404) (Zorg)
* Replace CFUUID* with NSUUID (#2395) (Eitot)
* Report an error when detecting duplicate updates in generate_appcast (#2407) (Zorg)
* Improve error for rejecting xattr based code signing for delta updates (#2408) (Zorg)
* Fail gracefully when auxiliary tool cannot be located (#2436) (Zorg)
# 2.4.2
* Ignore release notes download when we shouldn't show release notes (#2381) (Zorg)
* Fix NSKeyedUnarchiver warning for not specifying keyed NSString class (#2381) (Zorg)
* Harden verification of Sparkle update download (#2392) (Zorg)
# 2.4.1
* Remove auxiliary apps and relocate symbols in SPM package to resolve missing AvailableLibraries warnings (#2356) (Zorg)
* Add -Wno-declaration-after-statement to silence warnings that only apply to pre-C99 (#2345) (Kent Sutherland)
* Fix compile error when setting SPARKLE_EMBED_DOWNLOADER_XPC_SERVICE=0 (#2346) (Zorg)
* Improve how downloaded update is passed to the installer (#2359) (Zorg)
# 2.4.0
* Reduce code size
* Enable deployment postprocessing in Release to properly strip debug symbols and strip all non-global symbols (#2286, #2305) (Zorg)
* Remove duplicate Sparkle localization strings in Updater app (#2288) (Zorg)
* Optimize codebase for generated code size (less properties, direct methods, etc) (#2305) (Zorg)
* Add additional settings to `ConfigCommon.xcconfig` for disabling features
* Ask permission for automatically downloading and installing new updates (#2285) (Zorg)
* Add support for plain text release notes view that does not use web view (#2315) (Zorg)
* Update `SUVersionDisplay` to better customize and display how versions are shown (#2321) (Zorg)
* Add deprecations/warnings for incorrect background update checking usage (#2295) (Zorg)
* Deprecate `-[SPUUpdater setFeedURL:]` API and add `-[SPUUpdater clearFeedURLFromUserDefaults]` for migrating away from `-[SPUUpdater setFeedURL:]` (#2295)
* Trigger a new update check in `-[SPUUpdater resetUpdateCycle]` if the updater's feed or allowed channels have changed (#2324) (Zorg)
* Exit with an error if generate_appcast cannot sign an update that must be signed (#2322) (Zorg)
* Remove a redundant Apple code signing check when verifying new updates (#2341) (Zorg)
* Turn off auto-linking for XPC targets to alleviate circular dependency issues (#2332) (Daniel Jalkut)
# 2.3.2
* Fix potential crash during download if appcast item includes invalid enclosure URL (#2317) (Zorg)
* Add delegate method to hide showing version history option (#2303) (Zorg)
* Finnish localization grammar fixes (#2311) (Lauri-Matti Parppei)
# 2.3.1
* Fix update permission alert title text overlapping with question text in some languages (#2284) (Zorg)
* Log the URL that failed to download correctly (#2296) (Zorg)
* Update Czech translation (#2275) (Sam)
* Add zh_HK (Chinese, Hong Kong) localization (#2273) (Bing Zheung)
# 2.3.0
* Bump minimum deployment target to macOS 10.13 (#2196) (Zorg)
* Remove and preserve necessary updates in generate_appcast (#2218) (Zorg)
* Move old update files no longer needed to old_updates/ in archive directory in generate_appcast (#2228) (Zorg)
* Expose maximum-versions option (per branch) in generate_appcast to preserve in the feed (#2259) (Zorg)
* Add -p option to sign_update to only print the signed signature (#2268) (Zorg)
* Hide automatic install check box when allowsAutomaticUpdates is disabled (#2202) (Jie)
* Allow developer to always force allowing automatic updates (#2266) (Zorg)
* Fix update window going haywire during resize when release notes are hidden by disabling resizing (#2200) (Zorg)
* Allow user to re-try installing/relaunching application when quit is delayed/cancelled (#2234) (Zorg)
* Add delta update attributes for validating an app hasn't been stripped from removed localizations or architectures (#2219) (Zorg)
* Fix delta patches not applying edge case if files from source that need to be diffed are not writeable (#2211) (Zorg)
* Add delegate callback when user makes choice to install, dismiss, or skip an update (#2250) (Zorg)
* Reject serving updates with DSA only and no EdDSA (#2167) (Zorg)
* Find potential matching running apps that are translocated in the updater agent (#2233) (Zorg)
* Expose -[SPUStandardUserDriver activeUpdateAlert] as private API (#2255) (Zorg)
* Add zh_CN l10n for "Version History" (#2247) (kakaiikaka)
* Update zh_TW localization (#2271) (Chiahong)
* Remove ed25519 git submodule in favor of including the dependency directly (#2244) (Zorg)
* Clean up left-over code (#2243) (Eitot)
* Update Package.resolved (#2245) (Zorg)
* Remove model translation table for system profiling (#2188) (Zorg)
* Improve documentation usage for SPUUpdater properties (#2256) (Zorg)
This release improves generate_appcast by automatically removing updates that are no longer needed in the generated appcast, and moving old update files to old_updates/ in the archives directory. New delta update attributes are also added to let Sparkle know when to skip downloading delta updates if the application has been stripped.
macOS 10.13 or later is now required (due to Xcode 14 dropping support for deploying to older OS versions).
If you're not generating appcasts automatically, remember to add `<sparkle:minimumSystemVersion>10.13</sparkle:minimumSystemVersion>` element to `<item>`s in your appcast.
# 2.2.2
* Critical update alerts may not show up as promptly as they should when they are being automatically installed (#2230) (Zorg)
* Remove module imports from framework headers (#2217) (Zorg)
* Update Portuguese localization (#2224) (Kent Sutherland)
* Update zh_TW localization (#2246) (Chiahong)
# 2.2.1
* Make scroll bar dark in dark theme for Release Notes by default (#2187) (Pavel Moiseenko)
* 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)
* 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 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 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)
* Updater Changes
* Automatic silent and manual update alert prompts are now merged together (Zorg)
* Updates will attempt to install even if the user quits the application without relaunching the application update explicitly (Zorg)
* Updates can be downloaded in the background automatically but later prompt the user to install them, particularly if Sparkle doesn't have sufficient permission to install them without the user's permission (Zorg)
* Authorization now occurs before launching the installer and before terminating the application, which can be canceled by the user cleanly (Zorg)
* 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
* 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)
* Expose why a new update is unavailable and direct user to prior release notes or website info (#1877, #1886) (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 bring up authorization just because group ID doesn't match (#1830) (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 beta versions of Sparkle 2 and use sandboxing, please re-familiarize yourself with the [Sandboxing guide](https://sparkle-project.org/documentation/sandboxing/). Some of the XPC Services are now optional and integration with XPC Services and code signing have been simplified. The SPUUserDriver protocol for custom user interfaces has been greatly simplified too.
# 1.27.3
* Create and use temp extraction directory in generate_appcast again (#2556) (Zorg)
# 1.27.2
* Extract archives in a separate directory from the input archive (#2552) (Zorg)
* Fix incorrect xz log warning in make release (#2044) (trss)
# 1.27.1
* Use px instead of pt when specifying font size to fix default font size in WebView from #1962 (regressed in 1.25.0 with WKWebView adoption) (Daniel Jalkut)
* 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
* Flat package support from #1745 (Zorg)
* Correct generate_appcast -s command line argument usage help (Lance Lovette)
* Fix -f command line argument handling (Lance Lovette)
* Fix progress for guided pkg install (Zorg)
* Fix XQuartz update failing because NSLog caused issues (Zorg)
* Update localization (Vojtěch Koňařík)
* Various fixes to SPM logic (Jonas Zaugg)
# 1.25.0
* Raise minimum system version to 10.9 (Kornel)
* Allow an appcast to prevent the new version from being installed automatically (#1688) (pierswalter)
* UI fixes
* Show check for updates button only when automatic updates are enabled (Lorena Rangel)
* Don't initialize the webview if we don't show release notes (Tobias Fonfara)
* Keep skip button available if there is a minimum autoupdate version (Zorg)
* Fix automatic updates checkbox state when not showing release notes (Zorg)
* Fix edge cases with hiding alert buttons and using "Install Later" (Zorg)
* Re-add setting WebUIDelegate fix for legacy web view (Zorg)
* Adopt WKWebView for 1.x (Zorg)
* Add auto layout constraints to SUAutomaticUpdateAlert window (Zorg)
* Made buttons wide enough to display the full text. Made window wide enough to display the widened buttons (el, fi, ru, uk) (Piers Uso Walter)
* Remove max size from update alert. (George Nachman)
* Integrate generate_keys export/import options changes from #1730 (Zorg)
* Add `—release-notes-url-prefix` support to localized release notes (Adam Tharani)
* Translations
* Enable base internalization for alert xibs (Zorg)
* Capitalizes french translation of "Vous utilisez actuellement..." ("You are currently running...") (Micah Moore)
* Fix and cleanup Hebrew, Catalan, Finnish localizations (Zorg)
* Remove non-english localizations from TestApplication (Zorg)
* Fix catch-22 Swift Package Manager binary target (Jonas Zaugg)
* Add explicit dependencies to fix Xcode linking errors (Kornel)
* Add phased rollouts feature to automatic update driver too (Zorg)
* Remove hiding skip button and retitling later button (Zorg)
* Deprecate installUpdatesIfAvailable (Zorg)
* Apply custom headers to app download (Geraint White)
# 1.24.0
* Prioritize UserDefaults when fetching value for EnableAutomaticChecks (Nicolas Bosi)
* Improve best appcast item selection handling (Ian Bytchek)
* Create lockfile for improved compatibility with 3rd party updaters (CoreCode)
* Enable SPM support via binary target (Jonas Zaugg)
* `generate_appcast` improvements:
* follow symbolic links (Denis Dzyubenko)
* update the release notes element’s URL when required (Brad Andalman)
* Added output filename option to generate_appcast (Brad Andalman)
* Added —release-notes-url-prefix to generate_appcast (Brad Andalman)
* Command line option to provide a download url prefix is now parsed and set on each archive item (Dominik H)
* Added help command line option (Dominik H)
* Locale updates:
* Update zh_CN localization (柳东原 · Dongyuan Liu)
* Update Sparkle.strings (Vojtěch Koňařík)
* Update Croatian (#1603) (milotype)
* Update SUUpdateAlert.xib (DanielFirlej)
* fix: read SUAutomaticallyUpdate from Info.plist (Trevor DeVore)
* Fix casting Boolean to BOOL on Apple Silicon (Kevin Wojniak)
* Use build matrix to test on multiple Xcode versions (Rajiv Shah)
* Set UpdateAlert and AutomaticUpdateAlert window's fullscreen collectionBehavior to NSWindowCollectionBehaviorFullScreenAuxiliary to allow them to present on top of the Main App's window if it's fullscreen. (Micah Moore)
* Fixed error about "about:blank" release notes (Louis Pontoise)
* Support App Store URL scheme in release note webview (Bi11)
* Use the SHA-256 hash of the archive as the cache path (Nate Weaver)
* Don't return an optional from the FileHandle method (Nate Weaver)
* Added URL+Hashing (Nate Weaver)
# 1.23.0
* Support generating appcast with localizations (#1499) (Alik Vovkotrub)
* Support versions with git commit SHA (#1504) (Alec Larson)
* Hide "Skip..." and "Remind..." buttons when they're not relevant (#1480) (Kenneth Johnsen)
* Preserve Finder tags while updating apps (#1512) (CoreCode)
* Read-only update alert dialog formatting improvements (#1515) (Quinn Taylor)
* Check if `SUBundleName` is set before normalizing (Jake Fenton)
* `NSInteger` cast warning on Xcode 11 (Marga Keuvelaar)
* Correct appcast file extension (Tom Vos)
* Update Sparkle.strings (Emir Sarı)
* Fix spelling (#1508) (Frank Chiarulli Jr)
# 1.22.0
* Enabled "Hardened Runtime" build option for Apple's notarization requirement
* Add delegate methods to suppress update alerts (George Nachman)
* Improved error when running from translocated location (Michael Buckley)
* Add phased rollout feature (#1381) (Fabian Jäger)
* Ignore non-standard permissions in delta updates instead of failing the build (Kornel Lesiński)
* Notify user when installed version is newer than the latest in the appcast (CoreCode)
* Reset timers after computer sleep (CoreCode)
* Block-based alternatives to `NSInvocation`-based delegate methods (Fabian Jäger)
* Add delegate `userDidSkipThisVersion` (BobZombie, Leo Natan, bono yusuke)
* Pass item to updaterShouldShowUpdateAlertForScheduledUpdate delegate method (George Nachman)
* Support providing private key as argument in `generate_appcast` (Yakuhzi, marchyang)
* Separate the ed25519 sources into a new static library (Tony Arnold)
* Disambiguate signing error messages (Nate Weaver)
* Use `XMLNode.Options.nodePrettyPrint` in `generate_appcast` instead of trying to add whitespace manually (fumoboy007)
* Annotate SUHost for nullability (Michael Buckley)
* Use SUAVAILABLE macro (Christiaan Hofman)
* Fix warnings when using modules (nivekkagicom)
* Correction of Czech localization inconsistency (#1403) (vojtakonarik)
* BR locale fix (BR Lingo)
* Update Japanese localization (fujisoft)
* French Sparkle.strings (Jean-Baptiste)
# 1.21.3
* Losslessly reduced the size of PNG (Barijaona Ramaholimihaso)
* Catch exceptions from subcommands (Julian Mayer)
* `generate_appcast` can sign any bundles instead of just apps (Nate Weaver)
* Check that effectiveAppearance is being observed before calling removeObserver (Pierluigi)
# 1.21.2
* Allow EdDSA for delta updates, too (Kornel)
* Warning fixes (Brian Bergstrand)
* Improvements to release notes view context menu and dark mode (Bi11)
# 1.21.0
* Added support EdDSA (ed25519) signatures (Kornel)
* DSA signatures are considered outdated, and Apple's `Security.framework` only supports weaker SHA-1-based DSA.
* Both old DSA and new EdDSA are still supported (and one app can use both), but new applications should use EdDSA only, and we recommend migrating away from DSA signatures.
* `generate_keys` is now a Swift tool that stores EdDSA private keys in the Keychain
* Existing apps can continue using their old DSA keys, but we've dropped support for generation of old DSA keys
* `sign_update` is now a Swift tool that signs using EdDSA from private keys in the Keychain
* The old DSA-based signing script has been moved to `bin/old_dsa_scripts`
* The old DSA-based signing script has been fixed to work on pre-10.13 systems (Thomas Tempelmann)
* `generate_appcast` has been updated to support EdDSA signatures
* It can sign both DSA (if `dsa_priv.pem` file is specified) and EdDSA (from Keychain)
* The tool now uses Caches directory and doesn't generate unnecessary delta files
* Fixed verification of delta updates on filesystems that change permissions of symlinks
* Fixed `NSURLSession` leak (Michael Ehrmann)
# 1.20.0
* `generate_appcast` option to read private key directly from the keychain (Tamás Lustyik)
* Add delegate callbacks for fininshed download and extraction related events (Csaba Horony)
* Add delegate callbacks for finished download and extraction related events (Csaba Horony)
* Don't check for updates if Do Not Disturb is on (Kornel)
* Expose `CodesigningVerifier`, add codesign info API (sunuslee)
* Threading fixes:
@@ -351,7 +859,7 @@ Important security fixes:
* All the user defaults keys are now private; instead, SUUpdater is KVC-compliant for automaticallyChecksForUpdates, updateCheckInterval, and feedURL.
* Reduced the size of the English-only framework by 25%.
* System profiling information is now only submitted to the server once per week; this will help normalize your statistics across users with different interval preferences.
* The feedParamatersForUpdater: delegate method now requires "displayKey" and "displayVersion" keys so that it can inform the user what's being sent.
* The feedParametersForUpdater: delegate method now requires "displayKey" and "displayVersion" keys so that it can inform the user what's being sent.
* Added a delegate method called pathToRelaunchForUpdater: which can be used for plugins to provide the path which should be used when relaunching the client after installing an update.
* Added support for xml:lang to pick localized nodes in appcasts (for release notes, etc).
* Fixed a bug which would cause the "checking for updates" window to not disappear in certain extraordinary error conditions.
+1
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", "2.2.2": "https://github.com/sparkle-project/Sparkle/releases/download/2.2.2/Sparkle-2.2.2.tar.xz", "2.3.0-beta.1": "https://github.com/sparkle-project/Sparkle/releases/download/2.3.0-beta.1/Sparkle-2.3.0-beta.1.tar.xz", "2.3.0-beta.2": "https://github.com/sparkle-project/Sparkle/releases/download/2.3.0-beta.2/Sparkle-2.3.0-beta.2.tar.xz", "2.3.0": "https://github.com/sparkle-project/Sparkle/releases/download/2.3.0/Sparkle-2.3.0.tar.xz", "2.3.1": "https://github.com/sparkle-project/Sparkle/releases/download/2.3.1/Sparkle-2.3.1.tar.xz", "2.3.2": "https://github.com/sparkle-project/Sparkle/releases/download/2.3.2/Sparkle-2.3.2.tar.xz", "2.4.0-beta.1": "https://github.com/sparkle-project/Sparkle/releases/download/2.4.0-beta.1/Sparkle-2.4.0-beta.1.tar.xz", "2.4.0-beta.2": "https://github.com/sparkle-project/Sparkle/releases/download/2.4.0-beta.2/Sparkle-2.4.0-beta.2.tar.xz", "2.4.0": "https://github.com/sparkle-project/Sparkle/releases/download/2.4.0/Sparkle-2.4.0.tar.xz", "2.4.1-beta.1": "https://github.com/sparkle-project/Sparkle/releases/download/2.4.1-beta.1/Sparkle-2.4.1-beta.1.tar.xz", "2.4.1": "https://github.com/sparkle-project/Sparkle/releases/download/2.4.1/Sparkle-2.4.1.tar.xz", "2.4.2": "https://github.com/sparkle-project/Sparkle/releases/download/2.4.2/Sparkle-2.4.2.tar.xz", "2.5.0-beta.1": "https://github.com/sparkle-project/Sparkle/releases/download/2.5.0-beta.1/Sparkle-2.5.0-beta.1.tar.xz", "2.5.0-beta.2": "https://github.com/sparkle-project/Sparkle/releases/download/2.5.0-beta.2/Sparkle-2.5.0-beta.2.tar.xz", "2.5.0": "https://github.com/sparkle-project/Sparkle/releases/download/2.5.0/Sparkle-2.5.0.tar.xz", "2.5.1": "https://github.com/sparkle-project/Sparkle/releases/download/2.5.1/Sparkle-2.5.1.tar.xz", "2.5.2": "https://github.com/sparkle-project/Sparkle/releases/download/2.5.2/Sparkle-2.5.2.tar.xz", "2.6.0-beta.1": "https://github.com/sparkle-project/Sparkle/releases/download/2.6.0-beta.1/Sparkle-2.6.0-beta.1.tar.xz", "2.6.0-beta.2": "https://github.com/sparkle-project/Sparkle/releases/download/2.6.0-beta.2/Sparkle-2.6.0-beta.2.tar.xz", "2.6.0": "https://github.com/sparkle-project/Sparkle/releases/download/2.6.0/Sparkle-2.6.0.tar.xz", "2.6.1": "https://github.com/sparkle-project/Sparkle/releases/download/2.6.1/Sparkle-2.6.1.tar.xz", "1.27.2": "https://github.com/sparkle-project/Sparkle/releases/download/1.27.2/Sparkle-1.27.2.tar.xz", "2.6.2": "https://github.com/sparkle-project/Sparkle/releases/download/2.6.2/Sparkle-2.6.2.tar.xz", "1.27.3": "https://github.com/sparkle-project/Sparkle/releases/download/1.27.3/Sparkle-1.27.3.tar.xz", "2.6.3": "https://github.com/sparkle-project/Sparkle/releases/download/2.6.3/Sparkle-2.6.3.tar.xz", "2.6.4": "https://github.com/sparkle-project/Sparkle/releases/download/2.6.4/Sparkle-2.6.4.tar.xz", "2.7.0-beta.1": "https://github.com/sparkle-project/Sparkle/releases/download/2.7.0-beta.1/Sparkle-2.7.0-beta.1.tar.xz", "2.7.0": "https://github.com/sparkle-project/Sparkle/releases/download/2.7.0/Sparkle-2.7.0.tar.xz", "2.7.1": "https://github.com/sparkle-project/Sparkle/releases/download/2.7.1/Sparkle-2.7.1.tar.xz", "2.7.2": "https://github.com/sparkle-project/Sparkle/releases/download/2.7.2/Sparkle-2.7.2.tar.xz", "2.7.3": "https://github.com/sparkle-project/Sparkle/releases/download/2.7.3/Sparkle-2.7.3.tar.xz", "2.8.0-beta.1": "https://github.com/sparkle-project/Sparkle/releases/download/2.8.0-beta.1/Sparkle-2.8.0-beta.1.tar.xz", "2.8.0-beta.2": "https://github.com/sparkle-project/Sparkle/releases/download/2.8.0-beta.2/Sparkle-2.8.0-beta.2.tar.xz", "2.8.0-beta.3": "https://github.com/sparkle-project/Sparkle/releases/download/2.8.0-beta.3/Sparkle-2.8.0-beta.3.tar.xz"}
@@ -3,4 +3,4 @@
#include "ConfigSwift.xcconfig"
SWIFT_OBJC_BRIDGING_HEADER = $(PRODUCT_NAME)/Bridging-Header.h
MACOSX_DEPLOYMENT_TARGET = 10.11
GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS) BUILDING_EXTERNALLY=1
@@ -1 +0,0 @@
// BinaryDelta tool only
+99 -27
View File
@@ -1,51 +1,126 @@
// Common
// Set to 1 or 0 to build and bundle the provided XPC Services in Sparkle framework
// (Note for testing purposes for sandboxed apps, disabling all XPC services and then re-enabling them
// may not work on the same login session due to a system caching issue. See comments for setting FRAMEWORK_VERSION for more info)
SPARKLE_EMBED_INSTALLER_LAUNCHER_XPC_SERVICE = 1
// Embedding the downloader service also enables building legacy WebKit1 support
SPARKLE_EMBED_DOWNLOADER_XPC_SERVICE = 1
SPARKLE_EMBED_INSTALLER_STATUS_XPC_SERVICE = 0
SPARKLE_EMBED_INSTALLER_CONNECTION_XPC_SERVICE = 0
// Set to 0 to disable building legacy 1.x SUUpdater stub
SPARKLE_BUILD_LEGACY_SUUPDATER = 1
// Set to 0 to not build legacy DSA signing support
// Don't disable this if you haven't migrated to EdDSA yet or if you support updating
// other developer's applications that haven't migrated to EdDSA yet
// If this is disabled, this requires an update to OTHER_SWIFT_FLAGS_COMMON below
SPARKLE_BUILD_LEGACY_DSA_SUPPORT = 1
// Set to 0 to not build legacy DSA signing support for generate_appcast
// Don't disable this if you still have items in your appcast feed that still need DSA signatures
// If this is disabled, this requires an update to OTHER_SWIFT_FLAGS_COMMON below
GENERATE_APPCAST_BUILD_LEGACY_DSA_SUPPORT = 1
// Set to 0 to not build legacy / xar based delta update support
SPARKLE_BUILD_LEGACY_DELTA_SUPPORT = 1
// Set to 0 to not build bzip2 support for version 3 delta based updates
SPARKLE_BUILD_BZIP2_DELTA_SUPPORT = 1
// Set to 0 to not build support for package (pkg) based installations
// If this is disabled, this requires an update to OTHER_SWIFT_FLAGS_COMMON below
SPARKLE_BUILD_PACKAGE_SUPPORT = 1
// Set to 0 to only build all non-UI bits (which means client uses a custom SPUUserDriver)
SPARKLE_BUILD_UI_BITS = 1
// Set to 0 to not use and copy localization / string files to framework
SPARKLE_COPY_LOCALIZATIONS = 1
// Compilation flags for Swift tools and unit tests
// If SPARKLE_BUILD_LEGACY_DELTA_SUPPORT is set to 0, remove -DSPARKLE_BUILD_LEGACY_DSA_SUPPORT
// If GENERATE_APPCAST_BUILD_LEGACY_DSA_SUPPORT is set to 0, remove -DGENERATE_APPCAST_BUILD_LEGACY_DSA_SUPPORT
// If SPARKLE_BUILD_PACKAGE_SUPPORT is set to 0, remove -DSPARKLE_BUILD_PACKAGE_SUPPORT
OTHER_SWIFT_FLAGS_COMMON = -DSPARKLE_BUILD_LEGACY_DSA_SUPPORT -DGENERATE_APPCAST_BUILD_LEGACY_DSA_SUPPORT -DSPARKLE_BUILD_PACKAGE_SUPPORT
// Minimum supported macOS version
MACOSX_DEPLOYMENT_TARGET = 10.13
// Supported architectures
ARCHS = $(ARCHS_STANDARD)
// Default Sparkle names
SPARKLE_BUNDLE_IDENTIFIER = org.sparkle-project.Sparkle
SPARKLE_RELAUNCH_TOOL_NAME = Autoupdate
SPARKLE_INSTALLER_PROGRESS_TOOL_NAME = Updater
SPARKLE_INSTALLER_PROGRESS_TOOL_BUNDLE_ID = $(SPARKLE_BUNDLE_IDENTIFIER).$(SPARKLE_INSTALLER_PROGRESS_TOOL_NAME)
// Set these if you want to use custom name for the XPC Services
// For the Installer one in particular, this name may show up in an authorization prompt
// when installing an update that requires authorization.
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}.DownloaderService
// The Downloader XPC Service is not sandboxed by default.
// Uncomment line to enable Sandboxing for this service.
// If this is done, you *must* set a custom XPC_SERVICE_BUNDLE_ID_PREFIX for your app above.
// Otherwise sandboxed apps that use the same sandboxed Downloader Service may conflict with each other.
//DOWNLOADER_SANDBOXED_ENTITLEMENTS = Downloader/Downloader.entitlements
// Sparkle usually doesn't allow downgrades as they're usually accidental, but
// if your app has a downgrade function or URL handler, turn this on
SPARKLE_AUTOMATED_DOWNGRADES = 0
// If your app file on disk is named "MyApp 1.1b4", Sparkle usually updates it
// in place, giving you an app named 1.1b4 that is actually 1.2. Turn the
// following on to always reset the name back to "MyApp":
// following on to always reset the name back to "MyApp"
// If you are using this option to change the name of your app, you should
// disable the option again when you no longer need it
// Note this option is only supported for regular application updates and not plug-ins
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_MINOR = 8
SPARKLE_VERSION_PATCH = 0
SPARKLE_VERSION = $(SPARKLE_VERSION_MAJOR).$(SPARKLE_VERSION_MINOR).$(SPARKLE_VERSION_PATCH)
CURRENT_PROJECT_VERSION = $(SPARKLE_VERSION)
// This should be in SemVer format or empty, ie. "-beta.1"
// These variables must have a space after the '=' too
SPARKLE_VERSION_SUFFIX = -beta.3
CURRENT_PROJECT_VERSION = 2048
MARKETING_VERSION = $(SPARKLE_VERSION_MAJOR).$(SPARKLE_VERSION_MINOR).$(SPARKLE_VERSION_PATCH)$(SPARKLE_VERSION_SUFFIX)
ALWAYS_SEARCH_USER_PATHS = NO
ENABLE_STRICT_OBJC_MSGSEND = YES
GCC_SYMBOLS_PRIVATE_EXTERN = YES
GCC_INLINES_ARE_PRIVATE_EXTERN = YES
ARCHS = $(ARCHS_STANDARD)
// NSURLSession requirements
MACOSX_DEPLOYMENT_TARGET = 10.9
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_AUTOMATED_DOWNGRADES=$(SPARKLE_AUTOMATED_DOWNGRADES) SPARKLE_BUNDLE_IDENTIFIER=\"$(SPARKLE_BUNDLE_IDENTIFIER)\" CURRENT_PROJECT_VERSION=\"$(CURRENT_PROJECT_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 = SPU_OBJC_DIRECT=__attribute__((objc_direct)) SPU_OBJC_DIRECT_MEMBERS=__attribute__((objc_direct_members)) SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME=$(SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME) SPARKLE_BUILD_UI_BITS=$(SPARKLE_BUILD_UI_BITS) SPARKLE_COPY_LOCALIZATIONS=$(SPARKLE_COPY_LOCALIZATIONS) SPARKLE_BUILD_LEGACY_SUUPDATER=$(SPARKLE_BUILD_LEGACY_SUUPDATER) SPARKLE_BUILD_PACKAGE_SUPPORT=$(SPARKLE_BUILD_PACKAGE_SUPPORT) SPARKLE_BUILD_LEGACY_DELTA_SUPPORT=$(SPARKLE_BUILD_LEGACY_DELTA_SUPPORT) SPARKLE_BUILD_BZIP2_DELTA_SUPPORT=$(SPARKLE_BUILD_BZIP2_DELTA_SUPPORT) SPARKLE_BUILD_LEGACY_DSA_SUPPORT=$(SPARKLE_BUILD_LEGACY_DSA_SUPPORT) GENERATE_APPCAST_BUILD_LEGACY_DSA_SUPPORT=$(GENERATE_APPCAST_BUILD_LEGACY_DSA_SUPPORT) SPARKLE_BUNDLE_IDENTIFIER=\"$(SPARKLE_BUNDLE_IDENTIFIER)\" CURRENT_PROJECT_VERSION=\"$(CURRENT_PROJECT_VERSION)\" MARKETING_VERSION=\"$(MARKETING_VERSION)\" SPARKLE_RELAUNCH_TOOL_NAME=\"$(SPARKLE_RELAUNCH_TOOL_NAME)\" SPARKLE_INSTALLER_PROGRESS_TOOL_NAME=\"$(SPARKLE_INSTALLER_PROGRESS_TOOL_NAME)\" SPARKLE_INSTALLER_PROGRESS_TOOL_BUNDLE_ID=\"$(SPARKLE_INSTALLER_PROGRESS_TOOL_BUNDLE_ID)\" SPARKLE_ICON_NAME=\"$(SPARKLE_ICON_NAME)\" INSTALLER_LAUNCHER_NAME=\"${INSTALLER_LAUNCHER_NAME}\" INSTALLER_LAUNCHER_BUNDLE_ID=\"${INSTALLER_LAUNCHER_BUNDLE_ID}\" INSTALLER_LAUNCHER_XPC_SERVICE_EMBEDDED=$(SPARKLE_EMBED_INSTALLER_LAUNCHER_XPC_SERVICE) INSTALLER_CONNECTION_NAME=\"${INSTALLER_CONNECTION_NAME}\" INSTALLER_CONNECTION_BUNDLE_ID=\"${INSTALLER_CONNECTION_BUNDLE_ID}\" INSTALLER_CONNECTION_XPC_SERVICE_EMBEDDED=$(SPARKLE_EMBED_INSTALLER_CONNECTION_XPC_SERVICE) INSTALLER_STATUS_NAME=\"${INSTALLER_STATUS_NAME}\" INSTALLER_STATUS_BUNDLE_ID=\"${INSTALLER_STATUS_BUNDLE_ID}\" INSTALLER_STATUS_XPC_SERVICE_EMBEDDED=$(SPARKLE_EMBED_INSTALLER_STATUS_XPC_SERVICE) DOWNLOADER_NAME=\"${DOWNLOADER_NAME}\" DOWNLOADER_BUNDLE_ID=\"${DOWNLOADER_BUNDLE_ID}\" DOWNLOADER_XPC_SERVICE_EMBEDDED=$(SPARKLE_EMBED_DOWNLOADER_XPC_SERVICE)
CODE_SIGN_IDENTITY = -
SDKROOT = macosx
ENABLE_HARDENED_RUNTIME = YES
CLANG_ENABLE_OBJC_ARC = YES
GCC_ENABLE_PASCAL_STRINGS = NO
GCC_NO_COMMON_BLOCKS = YES;
COMBINE_HIDPI_IMAGES = NO;
GCC_NO_COMMON_BLOCKS = YES
COMBINE_HIDPI_IMAGES = NO
// Enable warnings
CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;
CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES
CLANG_ANALYZER_SECURITY_FLOATLOOPCOUNTER = YES
CLANG_ANALYZER_SECURITY_INSECUREAPI_RAND = YES
CLANG_ANALYZER_SECURITY_INSECUREAPI_STRCPY = YES
@@ -88,11 +163,8 @@ GCC_WARN_UNUSED_LABEL = YES
GCC_WARN_UNUSED_PARAMETER = YES
GCC_WARN_UNUSED_VARIABLE = YES
// Fixes a strange issue where the compiler thinks references to some enums are ambiguous
CLANG_ENABLE_MODULES[sdk=macosx10.8] = NO
// These should be removed once the conversion to ARC is complete
WARNING_CFLAGS_EXTRA = -Wno-custom-atomic-properties -Wno-implicit-atomic-properties
// Turn on all warnings, then disable a few which are almost impossible to avoid
WARNING_CFLAGS = -Wall -Weverything -Wno-unused-macros -Wno-gnu-statement-expression -Wno-arc-repeated-use-of-weak -Wno-auto-import -Wno-gnu-zero-variadic-macro-arguments $(WARNING_CFLAGS_EXTRA)
WARNING_CFLAGS = -Wall -Weverything -Wno-unused-macros -Wno-gnu-statement-expression -Wno-auto-import -Wno-gnu-zero-variadic-macro-arguments -Wno-format-non-iso -Wno-direct-ivar-access -Wno-declaration-after-statement -Wno-gnu-conditional-omitted-operand -Wno-switch-default -Wno-missing-include-dirs -Werror=undef
// Prevents spurious warnings based on dependency scan considering Sparkle itself a dependency
DIAGNOSE_MISSING_TARGET_DEPENDENCIES = NO
+1 -1
View File
@@ -1,7 +1,7 @@
#include "ConfigCommonDebug.xcconfig"
SPARKLE_ALLOW_ARBITRARY_HTTP_LOADS = 1
GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS_COMMON)
OTHER_SWIFT_FLAGS = $(OTHER_SWIFT_FLAGS_COMMON)
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_COMMA = YES;
+1 -2
View File
@@ -2,8 +2,6 @@
// Debug only
SPARKLE_ALLOW_ARBITRARY_HTTP_LOADS = 1
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
@@ -15,5 +13,6 @@ DEBUG_INFORMATION_FORMAT = dwarf
ENABLE_TESTABILITY = YES
GCC_GENERATE_DEBUGGING_SYMBOLS = YES
GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS_COMMON) DEBUG=1
OTHER_SWIFT_FLAGS = $(OTHER_SWIFT_FLAGS_COMMON)
ONLY_ACTIVE_ARCH = YES
COPY_PHASE_STRIP = NO
+4 -3
View File
@@ -2,8 +2,6 @@
// Release only
SPARKLE_ALLOW_ARBITRARY_HTTP_LOADS = 0
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
@@ -13,7 +11,10 @@ CLANG_WARN_SUSPICIOUS_MOVE = YES;
GCC_OPTIMIZATION_LEVEL = s
DEBUG_INFORMATION_FORMAT = dwarf-with-dsym
GCC_GENERATE_DEBUGGING_SYMBOLS = YES
GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS_COMMON)
GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS_COMMON) DEBUG=0
OTHER_SWIFT_FLAGS = $(OTHER_SWIFT_FLAGS_COMMON)
DEAD_CODE_STRIPPING = YES
GCC_TREAT_WARNINGS_AS_ERRORS = NO
GCC_WARN_UNINITIALIZED_AUTOS = YES
COPY_PHASE_STRIP = NO
DEPLOYMENT_POSTPROCESSING = YES
+4 -2
View File
@@ -3,5 +3,7 @@
INFOPLIST_FILE = Downloader/Info.plist
WRAPPER_EXTENSION = xpc
PRODUCT_BUNDLE_IDENTIFIER = ${DOWNLOADER_BUNDLE_ID}
PRODUCT_NAME = ${DOWNLOADER_BUNDLE_ID}
CODE_SIGN_ENTITLEMENTS = Downloader/${DOWNLOADER_BUNDLE_ID}.entitlements
PRODUCT_NAME = ${DOWNLOADER_NAME}
CODE_SIGN_ENTITLEMENTS = $(DOWNLOADER_SANDBOXED_ENTITLEMENTS)
GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS) BUILDING_SPARKLE_SOURCES_EXTERNALLY=1
CLANG_MODULES_AUTOLINK = NO
@@ -1,4 +1,2 @@
// Downloader Debug
#include "ConfigDownloader.xcconfig"
CODE_SIGN_IDENTITY = -
+13 -1
View File
@@ -4,14 +4,26 @@ 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
DEFINES_MODULE = YES
PRODUCT_BUNDLE_IDENTIFIER = ${SPARKLE_BUNDLE_IDENTIFIER}
STRINGS_FILE_OUTPUT_ENCODING = binary
// As long as we don't ourselves depend upon any Frameworks that are incompatible
// with Application Extensions, then we should allow frameworks that require
// compatibility to be able to link with us.
APPLICATION_EXTENSION_API_ONLY = YES
ENABLE_MODULE_VERIFIER = YES
MODULEMAP_PRIVATE_FILE = Sparkle/Sparkle.private.modulemap
@@ -0,0 +1,4 @@
#include "ConfigFramework.xcconfig"
// Strip all non-global symbols (including debug symbols)
STRIP_STYLE = non-global
@@ -3,4 +3,6 @@
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}
GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS) BUILDING_SPARKLE_SOURCES_EXTERNALLY=1
CLANG_MODULES_AUTOLINK = NO
@@ -1,5 +1,3 @@
// InstallerConnection Debug
#include "ConfigInstallerConnection.xcconfig"
CODE_SIGN_IDENTITY = -
@@ -3,4 +3,6 @@
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}
GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS) BUILDING_SPARKLE_SOURCES_EXTERNALLY=1
CLANG_MODULES_AUTOLINK = NO
@@ -1,4 +1,2 @@
// Installer Launcher Debug
#include "ConfigInstallerLauncher.xcconfig"
CODE_SIGN_IDENTITY = -
@@ -2,5 +2,7 @@
INFOPLIST_FILE = Sparkle/InstallerProgress/InstallerProgress-Info.plist
PRODUCT_NAME = $(SPARKLE_INSTALLER_PROGRESS_TOOL_NAME)
PRODUCT_BUNDLE_IDENTIFIER = $(SPARKLE_INSTALLER_PROGRESS_TOOL_BUNDLE_ID)
GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS) BUILDING_SPARKLE=0 BUILDING_SPARKLE_SOURCES_EXTERNALLY=1
SKIP_INSTALL = YES
CLANG_ENABLE_MODULES = NO
@@ -3,4 +3,6 @@
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}
GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS) BUILDING_SPARKLE=0 BUILDING_SPARKLE_SOURCES_EXTERNALLY=1
CLANG_MODULES_AUTOLINK = NO
@@ -1,5 +1,3 @@
// InstallerStatus Debug
#include "ConfigInstallerStatus.xcconfig"
CODE_SIGN_IDENTITY = -
+1
View File
@@ -3,3 +3,4 @@
PRODUCT_NAME = $(SPARKLE_RELAUNCH_TOOL_NAME)
SKIP_INSTALL = YES
CLANG_ENABLE_MODULES = NO
GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS) BUILDING_SPARKLE_SOURCES_EXTERNALLY=1
@@ -4,3 +4,4 @@ INFOPLIST_FILE = sparkle-cli/Info.plist
PRODUCT_BUNDLE_IDENTIFIER = org.sparkle-project.sparkle-cli
PRODUCT_NAME = sparkle
LD_RUNPATH_SEARCH_PATHS = @executable_path/../Frameworks/
ENABLE_HARDENED_RUNTIME = NO
+1 -1
View File
@@ -1,2 +1,2 @@
SWIFT_VERSION = 4.0
SWIFT_VERSION = 5
SWIFT_SWIFT3_OBJC_INFERENCE = Off;
+2 -1
View File
@@ -1 +1,2 @@
SWIFT_OPTIMIZATION_LEVEL = -Owholemodule
SWIFT_OPTIMIZATION_LEVEL = -O
SWIFT_COMPILATION_MODE = wholemodule
+1 -1
View File
@@ -6,4 +6,4 @@ ASSETCATALOG_COMPILER_APPICON_NAME = $(SPARKLE_ICON_NAME)
LD_RUNPATH_SEARCH_PATHS = @executable_path/../Frameworks
PRODUCT_BUNDLE_IDENTIFIER = org.sparkle-project.SparkleTestApp
CODE_SIGN_ENTITLEMENTS = TestApplication/Sparkle-Test-App.entitlements
MACOSX_DEPLOYMENT_TARGET = 10.10
ENABLE_HARDENED_RUNTIME = NO
@@ -1,4 +1,2 @@
// Test Application Debug
#include "ConfigTestApp.xcconfig"
CODE_SIGN_IDENTITY = -
@@ -4,3 +4,4 @@ INFOPLIST_FILE = TestAppHelper/Info.plist
WRAPPER_EXTENSION = xpc
LD_RUNPATH_SEARCH_PATHS = @executable_path/../../../../Frameworks
PRODUCT_BUNDLE_IDENTIFIER = org.sparkle-project.TestAppHelper
ENABLE_HARDENED_RUNTIME = NO
@@ -1,4 +1,2 @@
// Test Application Helper Debug
#include "ConfigTestAppHelper.xcconfig"
CODE_SIGN_IDENTITY = -
+1 -1
View File
@@ -4,7 +4,7 @@
INFOPLIST_FILE = UITests/UITests-Info.plist
WRAPPER_EXTENSION = xctest
MACOSX_DEPLOYMENT_TARGET = 10.11
ENABLE_HARDENED_RUNTIME = NO
FRAMEWORK_SEARCH_PATHS = $(inherited) $(DEVELOPER_FRAMEWORKS_DIR)
LD_RUNPATH_SEARCH_PATHS = @loader_path/../Frameworks
+1 -1
View File
@@ -9,6 +9,6 @@ GCC_SYMBOLS_PRIVATE_EXTERN = NO
WARNING_CFLAGS = $(inherited) -Wno-variadic-macros -Wno-gnu-zero-variadic-macro-arguments
FRAMEWORK_SEARCH_PATHS = $(inherited) $(DEVELOPER_FRAMEWORKS_DIR)
LD_RUNPATH_SEARCH_PATHS = @loader_path/../Frameworks
MACOSX_DEPLOYMENT_TARGET = 10.9
CLANG_ENABLE_MODULES = YES
SWIFT_OBJC_BRIDGING_HEADER = Tests/Sparkle Unit Tests-Bridging-Header.h
GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS) BUILDING_SPARKLE_TESTS=1 BUILDING_SPARKLE_SOURCES_EXTERNALLY=1
+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
+3
View File
@@ -12,3 +12,6 @@ ALWAYS_SEARCH_USER_PATHS = NO
// Disable Warnings - this is a third-party project, and we'll trust that the maintainers know what they're doing.
WARNING_CFLAGS = $(inherited) -Wno-cast-qual -Wno-conversion -Wno-sign-conversion
// Disable dead stores analyzer warning
CLANG_ANALYZER_DEADCODE_DEADSTORES = NO
+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)
+16
View File
@@ -0,0 +1,16 @@
#!/bin/sh
# 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}"
ln -h -f -s "Versions/Current/""${SPARKLE_RELAUNCH_TOOL_NAME}" "${FRAMEWORK_PATH}"/"${SPARKLE_RELAUNCH_TOOL_NAME}"
ln -h -f -s "Versions/Current/""${SPARKLE_INSTALLER_PROGRESS_TOOL_NAME}".app "${FRAMEWORK_PATH}"/"${SPARKLE_INSTALLER_PROGRESS_TOOL_NAME}".app
+138 -32
View File
@@ -1,56 +1,162 @@
#!/bin/bash
set -e
if [ "$ACTION" = "" ] ; then
# If using cocoapods, sanity check that the Podspec version matches the Sparkle version
if [ -x "$(command -v pod)" ]; then
spec_version=$(printf "require 'cocoapods'\nspec = %s\nprint spec.version" "$(cat "$SRCROOT/Sparkle.podspec")" | LANG=en_US.UTF-8 ruby)
if [ "$spec_version" != "$CURRENT_PROJECT_VERSION" ] ; then
echo "podspec version '$spec_version' does not match the current project version '$CURRENT_PROJECT_VERSION'" >&2
exit 1
fi
# Tests the code signing validity of the extracted products within the provided path.
# This guards against our archives being corrupt / created incorrectly.
function verify_code_signatures() {
verification_directory="$1"
check_aux_apps="$2"
if [[ -z "$verification_directory" ]]; then
echo "Provided verification directory does not exist" >&2
exit 1
fi
# 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 {} \;
if [ "$check_aux_apps" = true ] ; then
codesign --verify -vvv --deep "${verification_directory}/sparkle.app"
codesign --verify -vvv --deep "${verification_directory}/Sparkle Test App.app"
fi
codesign --verify -vvv --deep "${verification_directory}/bin/BinaryDelta"
codesign --verify -vvv --deep "${verification_directory}/bin/generate_appcast"
codesign --verify -vvv --deep "${verification_directory}/bin/sign_update"
codesign --verify -vvv --deep "${verification_directory}/bin/generate_keys"
}
if [ "$ACTION" = "" ] ; then
rm -rf "$CONFIGURATION_BUILD_DIR/staging"
rm -f "Sparkle-$CURRENT_PROJECT_VERSION.tar.bz2"
rm -rf "$CONFIGURATION_BUILD_DIR/staging-spm"
rm -f "Sparkle-$MARKETING_VERSION.tar.xz"
rm -f "Sparkle-$MARKETING_VERSION.tar.bz2"
rm -f "Sparkle-for-Swift-Package-Manager.zip"
mkdir -p "$CONFIGURATION_BUILD_DIR/staging"
cp "$SRCROOT/CHANGELOG" "$SRCROOT/LICENSE" "$SRCROOT/INSTALL.markdown" "$SRCROOT/Resources/SampleAppcast.xml" "$CONFIGURATION_BUILD_DIR/staging"
cp -R "$SRCROOT/bin" "$CONFIGURATION_BUILD_DIR/staging"
mkdir -p "$CONFIGURATION_BUILD_DIR/staging-spm"
cp "$PROJECT_DIR/CHANGELOG" "$PROJECT_DIR/LICENSE" "$PROJECT_DIR/INSTALL" "$PROJECT_DIR/Resources/SampleAppcast.xml" "$CONFIGURATION_BUILD_DIR/staging"
cp "$PROJECT_DIR/CHANGELOG" "$PROJECT_DIR/LICENSE" "$PROJECT_DIR/INSTALL" "$PROJECT_DIR/Resources/SampleAppcast.xml" "$CONFIGURATION_BUILD_DIR/staging-spm"
cp -R "$PROJECT_DIR/bin" "$CONFIGURATION_BUILD_DIR/staging"
cp "$CONFIGURATION_BUILD_DIR/BinaryDelta" "$CONFIGURATION_BUILD_DIR/staging/bin"
cp "$CONFIGURATION_BUILD_DIR/generate_appcast" "$CONFIGURATION_BUILD_DIR/staging/bin"
cp "$CONFIGURATION_BUILD_DIR/generate_keys" "$CONFIGURATION_BUILD_DIR/staging/bin"
cp "$CONFIGURATION_BUILD_DIR/sign_update" "$CONFIGURATION_BUILD_DIR/staging/bin"
cp -R "$CONFIGURATION_BUILD_DIR/Sparkle Test App.app" "$CONFIGURATION_BUILD_DIR/staging"
cp -R "$CONFIGURATION_BUILD_DIR/sparkle.app" "$CONFIGURATION_BUILD_DIR/staging"
cp -R "$CONFIGURATION_BUILD_DIR/Sparkle.framework" "$CONFIGURATION_BUILD_DIR/staging"
cp -R "$CONFIGURATION_BUILD_DIR/SparkleCore.framework" "$CONFIGURATION_BUILD_DIR/staging"
cp -R "$CONFIGURATION_BUILD_DIR/Sparkle.xcframework" "$CONFIGURATION_BUILD_DIR/staging-spm"
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"
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/Sparkle Test App.app.dSYM" "$CONFIGURATION_BUILD_DIR/staging"
cp -R "$CONFIGURATION_BUILD_DIR/sparkle.app.dSYM" "$CONFIGURATION_BUILD_DIR/staging"
cp -R "$CONFIGURATION_BUILD_DIR/Sparkle.framework.dSYM" "$CONFIGURATION_BUILD_DIR/staging"
cp -R "$CONFIGURATION_BUILD_DIR/SparkleCore.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"
cd "$CONFIGURATION_BUILD_DIR/staging"
rm -rf "/tmp/sparkle-extract"
mkdir -p "/tmp/sparkle-extract"
# Sorted file list groups similar files together, which improves tar compression
find . \! -type d | rev | sort | rev | tar cjvf "../Sparkle-$CURRENT_PROJECT_VERSION.tar.bz2" --files-from=-
find . \! -type d | rev | sort | rev | tar --no-xattrs -cJvf "../Sparkle-$MARKETING_VERSION.tar.xz" --files-from=-
# Copy archived distribution for CI
cp -f "../Sparkle-$MARKETING_VERSION.tar.xz" "../sparkle_dist.tar.xz"
# Extract archive for testing binary validity
tar -xf "../Sparkle-$MARKETING_VERSION.tar.xz" -C "/tmp/sparkle-extract"
# Test code signing validity of the extracted products
# This guards against our archives being corrupt / created incorrectly
verify_code_signatures "/tmp/sparkle-extract" true
rm -rf "/tmp/sparkle-extract"
rm -rf "$CONFIGURATION_BUILD_DIR/staging"
# Get latest git tag
cd "$PROJECT_DIR"
latest_git_tag=$( git describe --tags --abbrev=0 || true )
if [ -n "$latest_git_tag" ] ; then
# Generate zip containing the xcframework for SPM
rm -rf "/tmp/sparkle-spm-extract"
mkdir -p "/tmp/sparkle-spm-extract"
cd "$CONFIGURATION_BUILD_DIR/staging-spm"
# rm -rf "$CONFIGURATION_BUILD_DIR/Sparkle.xcarchive"
ditto -c -k --zlibCompressionLevel 9 --rsrc . "../Sparkle-for-Swift-Package-Manager.zip"
# Test code signing validity of the extracted Swift package
# This guards against our archives being corrupt / created incorrectly
ditto -x -k "../Sparkle-for-Swift-Package-Manager.zip" "/tmp/sparkle-spm-extract"
verify_code_signatures "/tmp/sparkle-spm-extract" false
rm -rf "/tmp/sparkle-spm-extract"
rm -rf "$CONFIGURATION_BUILD_DIR/staging-spm"
cd "$PROJECT_DIR"
# Check semantic versioning
if [[ $latest_git_tag =~ ^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-((0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*))*))?(\\+([0-9a-zA-Z-]+(\.[0-9a-zA-Z-]+)*))?$ ]]; then
echo "Tag $latest_git_tag follows semantic versioning"
else
echo "ERROR: Tag $latest_git_tag does not follow semantic versioning! SPM will not be able to resolve the repository" >&2
exit 1
fi
# Generate new Package manifest, podspec, and carthage files
cd "$CONFIGURATION_BUILD_DIR"
cp "$PROJECT_DIR/Package.swift" "$CONFIGURATION_BUILD_DIR"
cp "$PROJECT_DIR/Sparkle.podspec" "$CONFIGURATION_BUILD_DIR"
cp "$PROJECT_DIR/Carthage-dev.json" "$CONFIGURATION_BUILD_DIR"
fi
if [ -z "$latest_git_tag" ] ; then
echo "warning: No git repository found so skipping updating package management files"
elif [ "$XCODE_VERSION_MAJOR" -ge "1200" ]; then
# is equivalent to shasum -a 256 FILE
spm_checksum=$(swift package compute-checksum "Sparkle-for-Swift-Package-Manager.zip")
rm -rf ".build"
sed -E -i '' -e "/let tag/ s/\".+\"/\"$latest_git_tag\"/" -e "/let version/ s/\".+\"/\"$MARKETING_VERSION\"/" -e "/let checksum/ s/[[:xdigit:]]{64}/$spm_checksum/" "Package.swift"
cp "Package.swift" "$PROJECT_DIR"
echo "Package.swift updated with the following values:"
echo "Version: $MARKETING_VERSION"
echo "Tag: $latest_git_tag"
echo "Checksum: $spm_checksum"
sed -E -i '' -e "/s\.version.+=/ s/\".+\"/\"$MARKETING_VERSION\"/" "Sparkle.podspec"
"$PROJECT_DIR/Configurations/update-carthage.py" "Carthage-dev.json" "$MARKETING_VERSION"
cp "Sparkle.podspec" "$PROJECT_DIR"
# Note the Carthage-dev.json file will finally be copied to the website repo in Carthage/Sparkle.json in the end
cp "Carthage-dev.json" "$PROJECT_DIR"
echo "Sparkle.podspec and Carthage-dev.json updated with following values:"
echo "Version: $MARKETING_VERSION"
else
echo "warning: Xcode version $XCODE_VERSION_ACTUAL does not support computing checksums for Swift Packages. Please update the Package manifest manually."
fi
rm -rf "$CONFIGURATION_BUILD_DIR/staging-spm"
fi
+15
View File
@@ -0,0 +1,15 @@
#!/bin/bash
# Deleting old products
rm -rd "$BUILT_PRODUCTS_DIR/Sparkle.xcarchive"
rm -rd "$BUILT_PRODUCTS_DIR/Sparkle.xcframework"
xcodebuild archive -scheme Sparkle -archivePath "$BUILT_PRODUCTS_DIR/Sparkle.xcarchive" BUILD_LIBRARY_FOR_DISTRIBUTION=YES SKIP_INSTALL=NO
if [ $XCODE_VERSION_MAJOR -ge "1200" ]; then
xcodebuild -create-xcframework -framework "$BUILT_PRODUCTS_DIR/Sparkle.xcarchive/Products/Library/Frameworks/Sparkle.framework" -debug-symbols "$BUILT_PRODUCTS_DIR/Sparkle.xcarchive/dSYMs/Sparkle.framework.dSYM" -debug-symbols "$BUILT_PRODUCTS_DIR/Sparkle.xcarchive/dSYMs/Autoupdate.dSYM" -debug-symbols "$BUILT_PRODUCTS_DIR/Sparkle.xcarchive/dSYMs/Updater.app.dSYM" -debug-symbols "$BUILT_PRODUCTS_DIR/Sparkle.xcarchive/dSYMs/$INSTALLER_LAUNCHER_NAME.xpc.dSYM" -debug-symbols "$BUILT_PRODUCTS_DIR/Sparkle.xcarchive/dSYMs/$DOWNLOADER_NAME.xpc.dSYM" -output "$BUILT_PRODUCTS_DIR/Sparkle.xcframework"
else
echo "warning: Your Xcode version does not support bundling dSYMs in XCFrameworks directly. You should copy them manually into the XCFramework."
echo "note: cp '$BUILT_PRODUCTS_DIR/Sparkle.xcarchive/dSYMs/Sparkle.framework.dSYM' '$BUILT_PRODUCTS_DIR/Sparkle.xcframework/your_architecture/dSYMs'"
xcodebuild -create-xcframework -framework "$BUILT_PRODUCTS_DIR/Sparkle.xcarchive/Products/Library/Frameworks/Sparkle.framework" -output "$BUILT_PRODUCTS_DIR/Sparkle.xcframework"
fi
Loaded 100 of 672 files, more files were not shown because too many files have changed in this diff. Show more