Compare commits

...
372 Commits
Author SHA1 Message Date
Kornel Lesiński c0d45952a9 Removed unimportant changelog entry 2017-01-23 01:21:31 +00:00
Kornel 34179edd6d Merge pull request #1001 from zorgiepoo/appkit-prevention
Add AppKit prevention guards to modules that shouldn't import it
2017-01-17 13:09:38 +00:00
Zorg 530f3a4a63 Explain why I'm not relying on the compiler to throw linkage errors 2017-01-17 07:17:14 -05:00
Zorg 135d05b8b8 Add AppKitPrevention header to reduce redundancy.
Note this header should be included last in implementation files, which is why I added extra padding.
2017-01-17 07:08:29 -05:00
Zorg c56694382e Add AppKit prevention guards to modules that shouldn't import it 2017-01-16 21:17:25 -05:00
Kornel a39023e95b Merge pull request #1000 from zorgiepoo/generics
Add Obj-C generics where applicable
2017-01-17 00:58:20 +00:00
Zorg 282f0ae58e Add Obj-C generics where applicable
In headers that are exported, we test to see if generic support is available.
2017-01-16 18:09:04 -05:00
Thomas Tempelmann c1488b0515 Adds test cases for "sparkle:criticalUpdate" tag. (#999)
* Adds a test case for the "criticalUpdate" appcast tag (not as a XCTest but simply as an assert inside the test app, because I was lazy and am working on an older Xcode version that does not support the currently needed swift version for the XCTest in SUAppcastTest.swift).

* Tests the "criticalUpdate" appcast tag, using the proper XCTest swift class. I haven't tested this, though, due to the lack of the needed Xcode version.

* Test case for Appcast now checks all 4 items for the correct "criticalUpdate" state.

* Adds a test case for the "criticalUpdate" appcast tag (not as a XCTest but simply as an assert inside the test app, because I was lazy and am working on an older Xcode version that does not support the currently needed swift version for the XCTest in SUAppcastTest.swift). (reverted from commit 3ce1c9790b)
2017-01-16 00:02:32 +00:00
Kornel Lesiński 27c560b7d5 Proper fix for #995 2017-01-13 01:02:55 +00:00
Kornel Lesiński fbb040926e Fix URL/path confusion
Fixes #995
2017-01-13 00:44:41 +00:00
Kornel 548908628f Merge pull request #991 from zorgiepoo/upgrade-ci
Add 10.12 as SDK to run in Makefile and use Xcode 8.2 for Travis
2017-01-10 13:07:39 +00:00
Zorg d40bdb615a Add 10.12 as SDK to run in Makefile and use Xcode 8.2 for Travis 2017-01-10 06:40:35 -05:00
Kornel f43b9f7f02 Merge pull request #982 from sparkle-project/genapp
Workaround for bugs in NSXMLDocument prefix handling
2017-01-07 22:07:56 +00:00
Kornel Lesiński eafbb2cfad Copy debug symbols for generate_appcast 2017-01-07 21:57:39 +00:00
Kornel 5c408f5019 Merge pull request #984 from zorgiepoo/appcast-nonnil
The SUAppcast * is not going to be nil here; fixes analyzer warning
2017-01-07 17:43:46 +00:00
Zorg 9d35c819fd The SUAppcast * is not going to be nil here; fixes analyzer warning 2017-01-07 11:26:53 -05:00
Kornel Lesiński ee80a66896 Don't try to preserve namespace prefixes, because Apple's serializer is buggy
filed as rdar 29901669
2017-01-06 16:29:29 +00:00
Kornel Lesiński 187ae4fe57 Verify that the XML is serialized properly 2017-01-06 16:29:29 +00:00
Kornel Lesiński ca4d51561e Silence too-verbose delta 2017-01-06 16:29:29 +00:00
Kornel Lesiński 915c2047bf Fix accuracy of error message 2017-01-06 16:29:29 +00:00
Kornel f172cd32a8 Merge pull request #980 from sparkle-project/features
Updated README
2017-01-06 10:31:49 +00:00
Kornel Lesiński 8481035fb9 No server-side logic is a plus 2017-01-05 22:50:26 +00:00
Kornel Lesiński 7238c2aeb6 Updated README 2017-01-05 22:35:20 +00:00
Kornel Lesiński ee16e5ae55 1.16.0a2 2017-01-04 13:59:17 +00:00
Kornel d50e823b3d Merge pull request #972 from sparkle-project/misc
Misc
2017-01-04 00:07:29 +00:00
Kornel 4636588e76 Merge pull request #973 from sparkle-project/nothrowaway
Resume pending automatic update when possible
2017-01-04 00:07:10 +00:00
Kornel Lesiński 2be4dc11a0 Resume pending automatic update when possible
Fixes #970
2017-01-03 17:44:40 +00:00
Kornel Lesiński 6181c9276a Close alert on abort 2017-01-03 17:42:18 +00:00
Kornel Lesiński 49845d8246 Re-init alert when called again
A lazy way to bring it to front
2017-01-03 17:42:18 +00:00
Kornel Lesiński 8fa136c0a3 Invalidate timer when auto-update window is shown
In case it's shown manually, not by the timer
2017-01-03 17:42:18 +00:00
Kornel Lesiński dc1151a5ff Null warning 2017-01-03 16:13:15 +00:00
Kornel a920ecc197 Merge pull request #964 from zorgiepoo/guided-default
Make guided package installs the default for updating packages
2017-01-02 20:40:39 +00:00
Kornel Lesiński 271d504f6d Expose magic numbers 2017-01-01 14:14:25 +00:00
Kornel Lesiński 9c0ccd4a57 Put latest version first to make wildcard filename matching easier 2017-01-01 14:14:25 +00:00
Kornel 266be254d2 Merge pull request #967 from zorgiepoo/length-fallback
Fallback to the appcast's length value if HTTP doesn't give us one
2017-01-01 15:12:44 +01:00
Kornel efe93c492f Merge pull request #968 from Bi11/info-only
Hide automatic updates checkbox for information only updates
2016-12-31 19:45:46 +01:00
Kornel 74b09ad904 Merge pull request #966 from zorgiepoo/update-podspec-file
Update pod spec file so that `make release` works
2016-12-31 19:44:05 +01:00
Kornel b9012aa8dc Merge pull request #965 from zorgiepoo/unarchiver-test-no-ivar
Remove instance variables from SUUnarchiverTest.swift
2016-12-31 19:43:05 +01:00
Kornel ae41185267 Merge pull request #963 from zorgiepoo/remove-old-app
Remove the old app/bundle instead of moving it to the trash
2016-12-31 18:29:08 +01:00
Bi11 6634ed7d69 Hide automatic updates checkbox for information only updates 2016-12-31 23:37:53 +08:00
Zorg 799ebdcf7d Fallback to the appcast's length value if HTTP doesn't give us one 2016-12-29 14:08:14 -05:00
Zorg d911db7357 Update pod spec file so that make release works 2016-12-29 11:15:22 -05:00
Zorg d2e1987ce3 Remove instance variables from SUUnarchiverTest.swift
I have been receiving unarchiver test errors lately (after the unarchiver blocks changes) somewhat rarely (it's very hard to reproduce) when running all the tests locally. Thus, hoping this change may make a difference.
2016-12-28 23:44:31 -05:00
Zorg 2d1688c063 Make guided package installs the default for updating packages
Interactive package installs now need to be opted into (foo.sparkle_interactive.pkg or foo.sparkle_interactive.mpkg)

The website documentation may need to be updated later, and this should be noted as an important point in the change log.
2016-12-28 23:15:22 -05:00
Zorg b56910f455 Remove the old app/bundle instead of moving it to the trash
Fixes #827
2016-12-28 22:01:00 -05:00
Kornel Lesiński a3e96581b4 We're not testing with old Xcode, so we can't promise that compatibility 2016-12-27 22:44:01 +01:00
Kornel Lesiński 94423a10c9 Sorted project file 2016-12-27 21:25:52 +01:00
Kornel Lesiński b14c00136e Changelog 2016-12-27 21:23:15 +01:00
Kornel ebf8d2105b Merge pull request #953 from zorgiepoo/gen-appcast-xcconfig
Add xcconfig file for generate_appcast target
2016-12-27 20:53:53 +01:00
Zorg 14ac885ea0 Add ConfigGenerateAppcastDebug.xcconfig 2016-12-27 11:13:32 -05:00
Zorg 355e239df9 Add xcconfig file for generate_appcast target
Also remove swift configurations from Common config files, and change swift optimization from fast to whole module.
2016-12-27 11:01:25 -05:00
Kornel Lesiński e7ae7d5330 Version bump 2016-12-27 15:32:43 +01:00
Kornel daaadf1c44 Merge pull request #946 from sparkle-project/appcast
Tool to generate appcasts automatically
2016-12-27 15:31:30 +01:00
Kornel 87064c9304 Merge pull request #952 from zorgiepoo/small-changes
Small changes
2016-12-27 14:21:33 +01:00
Zorg 0af392f808 Remove SUWindowController.m because it wasn't really being used 2016-12-26 22:51:55 -05:00
Zorg fb8ad9f75d Enhance SUUpdatePermissionPrompt by using a reply block
Also add SUUpdatePermissionResponse class which matches the response class from my fork.
2016-12-26 22:42:58 -05:00
Zorg b4210a85b9 Add and use normal initializer for SUStandardVersionComparator 2016-12-26 21:23:30 -05:00
Kornel 091986b12f Merge pull request #951 from zorgiepoo/installer-protocol
Decouple and simplify installation code using protocols
2016-12-27 00:48:57 +01:00
Zorg 1ecb620986 Decouple and simplify installation code using protocols
This also fixes a bug where the status window would stay visible during interactive (non-guided) package installations.
2016-12-26 17:59:32 -05:00
Kornel 21f3c8a157 Merge pull request #950 from zorgiepoo/updater-delegation
Updater delegation
2016-12-26 15:44:58 +01:00
Zorg 468bcb9640 Remove typecasting self.updater to id 2016-12-26 09:20:52 -05:00
Kornel Lesiński d38b29c858 Use more precise version for deltas to avoid filename clashes 2016-12-26 14:32:26 +01:00
Kornel Lesiński e2b9fc7ffd Fix path 2016-12-26 14:26:03 +01:00
Zorg f016cd8086 Add nullability annotations to SUUpdaterDelegate.h 2016-12-25 18:45:49 -05:00
Zorg 796967cf24 Allow delegate methods that return an object to return nil
Returning nil from these delegate methods is equivalent to not implementing the delegate method. The caller should be able to make this kind of decision when implementing an optional delegate method.
2016-12-25 18:41:38 -05:00
Zorg 578e78876c Separate SUUpdater delegate methods into different file
Also create SUUpdaterPrivate protocol to expose as little as possible to the internal update drivers. Ideally this would be minimized and not even exist at all, but I don't want to make the architectural and potential backwards-incompatible changes required to do that.
2016-12-25 18:25:42 -05:00
Kornel 2f438186d6 Merge pull request #949 from zorgiepoo/decouple-host
Decrease responsibility of SUHost and move code into other components
2016-12-24 14:22:56 +01:00
Zorg 2c1820f2a9 Decrease responsibility of SUHost and move code into other components 2016-12-23 22:21:19 -05:00
Kornel a30eff3680 Merge pull request #947 from zorgiepoo/remove-deps
Remove Sparkle.pch and many file #includes
2016-12-24 00:06:56 +01:00
Zorg 1a09baf0ed Remove Sparkle.pch and many file #includes
This eliminates many dependencies that don't need to exist.
2016-12-23 16:13:35 -05:00
Kornel Lesiński a1095ff29c Null fix 2016-12-23 20:00:45 +01:00
Kornel Lesiński 51b3931485 Simpler suffix check 2016-12-23 19:59:48 +01:00
Kornel Lesiński 1e3f5482d0 Additional files 2016-12-23 19:26:30 +01:00
Kornel Lesiński 0a45be54c4 Appcast helper tool 2016-12-23 19:22:13 +01:00
Kornel b5bc2a7374 Merge pull request #940 from sparkle-project/nulz
Nulz
2016-12-23 18:56:57 +01:00
Kornel 3666b89add Merge pull request #933 from sparkle-project/statevars
Minor tweaks
2016-12-23 18:56:06 +01:00
Kornel 23f9e747c1 Merge pull request #942 from zorgiepoo/unarchiver-protocol
Unarchiver protocol
2016-12-23 18:54:25 +01:00
Kornel Lesiński c77895066a Appropriate deployment target for test app xib 2016-12-23 17:01:16 +01:00
Kornel Lesiński c98017dbe2 Fixed binary delta tool 2016-12-23 16:33:12 +01:00
Kornel Lesiński 657e3d47d0 Removed unnecessary nullability 2016-12-23 16:25:09 +01:00
Kornel 4d34e4358a Merge pull request #943 from zorgiepoo/improve-tests
Improve tests
2016-12-22 23:32:19 +01:00
Zorg 6fcd6beb84 Fix UI tests from not working when update alert automatically shows 2016-12-22 12:18:31 -05:00
Zorg 98b3a9828a Use localhost instead of 0.0.0.0. Latter doesn't work when offline. 2016-12-22 12:17:45 -05:00
Zorg 137b73af4e Fix subclass compatibility and update schedule unarchiving behavior 2016-12-21 16:39:33 -05:00
Zorg dd1bda5066 Some error reason is better than no reason 2016-12-21 16:14:25 -05:00
Zorg 7bc7a90a09 Fix UI update scheduler not prompting for install & relaunch 2016-12-21 15:59:13 -05:00
Zorg 91d13c7239 Merge branch 'master' into unarchiver-protocol 2016-12-21 15:53:41 -05:00
Zorg fd6ba1820a Merge branch 'master' into unarchiver-protocol 2016-12-21 15:39:38 -05:00
Kornel fb61777024 Merge pull request #941 from sparkle-project/unarch
Error handling test + fix
2016-12-21 19:18:23 +01:00
Kornel Lesiński 2519eb573f Test unarchiving failure 2016-12-21 18:06:22 +01:00
Kornel Lesiński 8a3338b078 Extracted function 2016-12-21 18:06:22 +01:00
Kornel Lesiński b03ae0d765 Moved assert 2016-12-21 18:06:19 +01:00
Kornel Lesiński 97c652e3b0 Fixed method name 2016-12-21 17:42:38 +01:00
Kornel 301af71228 Merge pull request #938 from sparkle-project/unarch
Unarchiving blocks
2016-12-21 17:07:19 +01:00
Zorg 60d4f05743 Add SUUnarchiverProtocol & remove runtime registration of unarchivers 2016-12-21 11:07:03 -05:00
Kornel Lesiński 464972126c Unwrap early 2016-12-21 16:44:04 +01:00
Kornel Lesiński c1392bc190 Nullability 2016-12-21 16:44:04 +01:00
Kornel Lesiński 921aed0fae Temp vars 2016-12-21 16:44:04 +01:00
Kornel Lesiński 59d90e0bb1 Basic binary delta progress 2016-12-21 15:23:41 +01:00
Kornel Lesiński e3fb6bb1a8 Report DMG extraction progress 2016-12-21 15:23:41 +01:00
Kornel Lesiński 8103f5fd43 Replaced progress delegate with a block 2016-12-21 15:23:40 +01:00
Kornel Lesiński 70f5681797 Use completion block for unarchiving 2016-12-21 15:22:59 +01:00
Kornel Lesiński 5ee02e954e Renamed callbacks 2016-12-21 15:22:59 +01:00
Kornel Lesiński 23b2b49663 Ability to report specific unarchiving error 2016-12-21 15:22:59 +01:00
Kornel Lesiński 311ed493b4 Unused 2016-12-21 15:22:59 +01:00
Kornel Lesiński 9d8b3c0c36 DRY async dispatch of unarchiver notifications 2016-12-21 15:22:59 +01:00
Kornel Lesiński f3f268388b Nullability declarations 2016-12-21 15:22:57 +01:00
Kornel 8d0effe327 Merge pull request #934 from sparkle-project/msg
Less alarming error message
2016-12-17 23:51:34 +01:00
Kornel Lesiński 19455099ff Formatting 2016-12-10 16:15:02 +00:00
Kornel Lesiński 6e754d7e4f Use return instead of state variable 2016-12-10 16:15:02 +00:00
Kornel Lesiński ab6fa76303 Xcode 8 now 2016-12-10 12:04:26 +00:00
Kornel Lesiński 93fc4b0151 Highlight Sierra compat 2016-12-10 12:03:58 +00:00
Kornel Lesiński 021950a5b2 Less alarming error message 2016-12-10 11:59:47 +00:00
Kornel 2ff0da4f15 Merge pull request #881 from zorgiepoo/separate-validation
Separate validation
2016-12-04 13:35:07 +00:00
Kornel Lesiński 945968a0ef Reminder 2016-12-04 12:19:25 +00:00
Kornel Lesiński 1e4f126f7e Podspec version bump 2016-12-04 12:18:11 +00:00
Kornel Lesiński f47115d81f Version bump 2016-12-04 12:14:24 +00:00
Kornel Lesiński 49781561f3 Cocoapods fudge 2016-12-04 12:10:27 +00:00
Zorg 1587dd1dc3 Refactor pre & post update validation into its own class 2016-12-03 15:37:00 -05:00
Zorg c0b9eaaa0e s/requiresValidationBeforUnarchiving/unsafeIfArchiveIsNotValidated/ 2016-12-03 11:06:10 -05:00
Kornel 91ac90ffcf Merge pull request #928 from sparkle-project/script
Fix #926
2016-12-03 00:05:09 +00:00
Kornel Lesiński 8375922755 Fix #926 2016-12-02 21:10:37 +00:00
Kornel 9dec304f64 Merge pull request #919 from sparkle-project/tag
Don't append hash to versions of builds with a tag
2016-12-01 20:16:43 +00:00
Kornel 8acd915b7b Merge branch 'master' into tag 2016-11-12 23:44:03 +00:00
Kornel Lesiński eb36100388 Allow 2.x 2016-11-12 17:14:56 +00:00
Kornel Lesiński fb22a01a08 Don't append hash to versions of builds with a tag 2016-11-12 14:22:42 +00:00
Zorg 9a32766aeb Merge branch 'master' into separate-validation 2016-11-11 23:35:28 -05:00
Kornel fc468771c1 Merge pull request #916 from zorgiepoo/swift-xcconfig
Move swift and other build settings into xcconfig files
2016-11-11 23:09:15 +00:00
Zorg 42dbf94738 Move swift and other build settings into xcconfig files 2016-11-10 15:51:30 -05:00
Kornel 86a0ca3883 Merge pull request #914 from sparkle-project/appiconname
Rename Sparkle.icns to be consistent with ASSETCATALOG_COMPILER_APPICON_NAME
2016-11-09 22:46:27 +00:00
Kornel Lesiński ddb53f330d Rename Sparkle.icns to be consistent with ASSETCATALOG_COMPILER_APPICON_NAME 2016-11-09 21:45:03 +00:00
Kornel 9dbaae64f1 Merge pull request #908 from sparkle-project/icon
Use optimized icon for Autoupdate.app
2016-11-01 22:56:27 +00:00
Kornel Lesiński d2f4687333 Specify requirements 2016-11-01 21:52:23 +00:00
Kornel Lesiński 143045d673 Use optimized icon for Autoupdate.app
#803
2016-11-01 00:44:54 +00:00
Kornel d67351cb62 Merge pull request #906 from vslavik/stable-byte-counts
Fix flickering download progress status text
2016-10-31 13:06:40 +00:00
Václav Slavík 07d2897250 Fix flickering download progress status text
Fix status text during download (e.g. "10MB of 22MB") so that it no
longer distractingly jumps around and flickers. This was caused by two
things:

1. Flicker on macOS >= 10.8 due to the use of NSByteCountFormatter's
   default mode which isn't optimized for stable display and is not
   suitable for rapidly updated values.

2. Smaller movements of text on macOS >= 10.11 due to the use of San
   Francisco font's default variant, where digits don't have fixed
   width.

Fixed by using monospacedDigitSystemFontOfSize for the text field and
enabling NSByteCountFormatter's zeroPadsFractionDigits mode.
2016-10-31 11:13:15 +01:00
Jake Petroules 625c942561 Update references to MaxCDN to StackPath
The latter acquired the former and requested this change.
2016-10-04 17:56:44 -07:00
Kornel bb299d075b Merge pull request #884 from sparkle-project/xcode8
Xcode8
2016-09-16 11:02:53 +01:00
Kornel 73229f84f7 Merge pull request #889 from zorgiepoo/swift3
Swift 3
2016-09-16 11:02:10 +01:00
Zorg 8152516b7f Remove coveralls
Coveralls hasn't worked properly in months since Swift code started being used, and it's causing a build failure at the moment.
2016-09-14 23:14:41 -04:00
Zorg 96baf2b2ce Update travis to use Xcode 8 2016-09-14 23:05:45 -04:00
Zorg ed5dca3423 Update unit tests to Swift 3 2016-09-14 23:05:05 -04:00
Kornel 3a5c620b60 Merge pull request #886 from zorgiepoo/debug-warning
Warn a developer if they're using a debug version of Sparkle
2016-09-06 17:03:40 +01:00
Kornel 23ae527b96 Merge pull request #885 from zorgiepoo/docs
Add more documentation to SUUpdater.h
2016-09-05 11:50:00 +01:00
Zorg 2268f96759 Add more documentation to SUUpdater.h 2016-09-04 22:11:29 -04:00
Zorg 898e063b4f Remove unnecessary 'return;' 2016-09-04 18:38:08 -04:00
Zorg e8f88bf0f1 Merge branch 'master' into separate-validation 2016-09-04 18:37:14 -04:00
Kornel Lesiński a3407a2dbf Xcode 8 config 2016-09-04 17:04:54 +01:00
Kornel Lesiński 88933a1e65 Unused 2016-09-04 17:04:54 +01:00
Kornel Lesiński c3d8e4bbc5 Changelog 2016-09-04 17:02:56 +01:00
Kornel f70c2a15b1 Merge pull request #883 from sparkle-project/nulfix
Test nullability
2016-09-04 16:50:36 +01:00
Kornel Lesiński 4eb518de7e Test nullability 2016-09-04 16:07:11 +01:00
Zorg 5b2ce958bd Merge branch 'master' into separate-validation 2016-09-03 23:27:16 -04:00
Kornel 077c64419f Merge pull request #882 from sparkle-project/bundleurl
Use bundle URLs
2016-09-03 17:09:14 +01:00
Kornel Lesiński 1195d4b5d2 Fixed test 2016-09-03 16:14:02 +01:00
Kornel Lesiński c7a7704f3b Switch test to NSURL 2016-09-02 19:08:42 +01:00
Kornel Lesiński 64af6d04c2 Use bundle URLs instead of paths to avoid creation of temp bundle objects 2016-09-02 18:53:23 +01:00
Kornel 0af27ea783 Merge pull request #877 from zorgiepoo/host-independent-signing
Improve Host Signing Verification
2016-09-02 18:31:37 +01:00
Kornel Lesiński c36413ce46 CoC 2016-09-02 12:43:37 +01:00
Kornel Lesiński 13b9081873 Readme text refresh 2016-09-02 12:33:48 +01:00
Kornel Lesiński 3dccca8044 Coveralls badge is a year out of date 2016-09-02 12:31:50 +01:00
Zorg e28c62244a Re-show download status if we attempt a 2nd download
This fixes a bug where the status would stay at "Extracting update" after validation from the 1st delta patch failed, and it continued on to a full download.
2016-09-01 23:19:58 -04:00
Zorg fec76fee12 Validate binary delta patches before unarchiving
Also keep package and bundle validation separate.
2016-09-01 23:14:26 -04:00
Kornel ed3eab64d2 Merge pull request #878 from zorgiepoo/automatic-writability
Improve host writability check by testing ownership/group changes
2016-08-28 14:10:02 +01:00
Kornel ee257c4070 Merge pull request #876 from zorgiepoo/delta-spotlight-import
Update mdimporter modification dates after delta extractions
2016-08-28 02:34:49 +01:00
Zorg bfec7a82c0 Improve host writability check by testing ownership/group changes 2016-08-27 21:09:51 -04:00
Zorg 4cd472abe6 Update comment on why kSecCSCheckNestedCode is not used 2016-08-27 19:16:48 -04:00
Zorg 39268a13e5 Add unit tests for Apple code signature matching 2016-08-27 19:06:58 -04:00
Zorg 4864dfb5aa Update signing verifier to take any host and s/application/bundle/ 2016-08-27 18:07:40 -04:00
Zorg 71125e3d16 Add unit test for updating spotlight mdimporter bundles 2016-08-27 17:03:54 -04:00
Zorg 779d16e5a7 Update spotlight bundles after delta extraction; don't use mdimport 2016-08-27 15:27:11 -04:00
Kornel Lesiński ee2e7fb46b Version bump 2016-08-27 17:01:33 +01:00
Kornel d350cf33e0 Merge pull request #865 from denniss/bug-864_missing-abort-update
[BUG-864] Call abort update after updater cannot find valid update
2016-08-27 16:21:03 +01:00
Kornel Lesiński 20be93e96b Version bump 2016-08-27 16:13:05 +01:00
Kornel Lesiński 668e258cff Updated CHANGELOG 2016-08-27 16:12:02 +01:00
Kornel 20f90f1544 Merge pull request #873 from zorgiepoo/dsa-existence
Dsa existence
2016-08-27 16:05:26 +01:00
Kornel 6dbb0d9988 Merge pull request #874 from zorgiepoo/dmg-remove-vendor
Remove NTSynchronousTask
2016-08-27 16:04:58 +01:00
Zorg f700c96e47 Read stdout to end before waiting for task to end to prevent deadlock 2016-08-27 09:27:06 -04:00
Zorg 626d2c96f5 Show the public DSA file key that doesn't exist in the insecure alert 2016-08-27 09:11:08 -04:00
Kornel 5db4e1505b Merge pull request #872 from zorgiepoo/menuvalidation
Menu item validation
2016-08-27 10:42:25 +01:00
Zorg 115686cd07 Change dmg and test verifying code by removing NTSynchronousTask 2016-08-27 01:09:24 -04:00
Zorg e2fc8b4258 Prevent public DSA key -> no public DSA key downgrade
This may prevent developers from making accidental downgrades.
2016-08-27 00:32:01 -04:00
Zorg 99f34299f1 Show alert if no pub key exists, but SUPublicDSAKeyFileKey exists 2016-08-27 00:07:11 -04:00
Zorg fdf79bc3a6 Enable check for updates menu item if update driver is interruptible 2016-08-26 23:07:13 -04:00
Zorg eb810c7d8f Implement menu item validation in Test Applications window controller 2016-08-26 23:03:08 -04:00
Zorg 38af7cd8cd Export -validateMenuItem: as a method in SUUpdater.h for public use 2016-08-26 23:01:30 -04:00
Dennis Suratna 09889d01b1 [BUG-864] Call abort update after updater cannot find valid update 2016-08-15 14:36:41 -07:00
Kornel 5f2ebb8edf Merge pull request #862 from moubry/master
Remove <link> from SampleAppCast.xml
2016-08-10 23:37:09 +01:00
Sean Moubry ac4ef7d9a0 Remove <link> from SampleAppCast.xml
Sparkle doesn’t use the channel’s link element. This resolves issue:
https://github.com/sparkle-project/Sparkle/issues/861.
2016-08-10 17:11:48 -05:00
Kornel cc7c0ae052 Merge pull request #858 from catnapgames/patch-1
Make sign_update work when Bash is not the default
2016-08-09 16:34:51 +01:00
Tomas Andrle b8dc5b3f3d Make sign_update work when Bash is not the default
This script fails when Bash is not the default shell. This fixes it and allows the script to run on a default Ubuntu system, for example.
2016-08-09 14:52:26 +02:00
Kornel 43e96f7ee8 Merge pull request #847 from sparkle-project/relaunch
Better error message when relaunch tool bundle is not found.
2016-08-01 19:15:18 +01:00
Kornel dbff23ea9d Merge pull request #851 from sorccu/patch-1
Add Carthage/Build to .gitignore
2016-07-22 13:02:36 +01:00
Simo Kinnunen ed97e6cb75 Add Carthage/Build to .gitignore
With Carthage, if Sparkle is included as a Git submodule (e.g. with the --use-submodules option), the main module's .gitignore can't reach all the way inside the submodule to ignore the added Carthage/Build symlink, and Git keeps complaining about untracked changes in the submodule forever, which is very annoying. To avoid that issue, ignore here in Sparkle instead.
2016-07-22 18:26:15 +09:00
Kornel Lesiński 492664c611 Clarify comment 2016-07-21 20:01:22 +01:00
Kornel Lesiński fdf07644d0 Better error message when relaunch tool bundle is not found. 2016-07-19 16:06:03 +01:00
Kornel 092feba9f9 Merge pull request #836 from zorgiepoo/remove-reachability
Don't use reachability as a preflight check
2016-07-08 10:27:13 +01:00
Zorg 91c813b6ab Don't use reachability as a preflight check
This removes the reachability code that we have for background scheduled updates.
Apple (and others) don't recommend using reachability to test if a network connection is online.

See:
http://stackoverflow.com/questions/7178330/what-is-the-advantage-of-using-reachability
https://www.mikeash.com/pyblog/friday-qa-2013-06-14-reachability.html (just the comments)
Apple 2012/2011 WWDC videos on networking

Also, our current reachability code is rather illogical:

* reachabilityResult is always NO
* isNetworkReachable is always YES
* flags is ignored
* horrible use of dispatch_sync & putFeedURLIntoDictionary is terrifying
* NSException handling shouldn't be done

Removing this code which wasn't even coded properly, and which would still be misusing the reachability API anyway, also leads to removing some multithreading races and simpler logic :)
2016-07-06 22:38:49 -04:00
Kornel 1ced9c428a Merge pull request #834 from zorgiepoo/dsa-key-comment
DSA security check comment
2016-07-05 14:44:11 +01:00
Zorg 16de00d81d If the old & new DSA keys are the same, then DSA validation must pass for security 2016-07-04 23:43:05 -04:00
Jake Petroules 3f637c9674 Sanity check that the Podspec version matches the Sparkle version. 2016-06-26 15:03:48 -07:00
Kornel 4a4dc3629f Merge pull request #828 from zorgiepoo/fileop-compile-error
Fix SUFileOperationConstants not found in Test App under Release
2016-06-25 11:45:10 +01:00
Zorg 6437e0448a Warn a developer if they're using a debug version of Sparkle
Due to different values for min/default update check intervals, production apps should not use a debug version of Sparkle
2016-06-24 20:13:17 -04:00
Zorg c77cd49036 Fix SUFileOperationConstants not found in Test App under Release 2016-06-24 19:55:40 -04:00
Kornel 9d7e4d676d Merge pull request #823 from nivekkagicom/master
update Sparkle framework headers to use modules if modules are available
2016-06-23 17:41:44 +01:00
Kornel 1aa0ee8152 Merge pull request #825 from jerrykrinock/xcode8
Changes for Xcode 8
2016-06-23 17:38:47 +01:00
Kornel Lesiński 9944f2496c Comment 2016-06-23 17:24:16 +01:00
Jerry Krinock 33907ec4ed • In SUUpdater.m, use SULocalizedString macro instead of NSLocalizedString.
• In SUOperatingSystem.m, assert instead of test for nil URL.
2016-06-17 22:24:43 -07:00
Jerry Krinock 7892e41b27 Fix for warning in in SUAppcast.m now tests for nil instead of using setValue:forKey: 2016-06-17 20:23:32 -07:00
Jerry Krinock 53983d9452 The following changes were made to clear warnings from static analyzer in Xcode 8:
• In ConfigCommon.xcconfig, removed references to CLANG_WARN_OBJC_RECEIVER_WEAK and -Wno-receiver-is-weak, because apparently these had been deprecated and are now no longer recognized.
• In SUAppcast.m, changed to method which can accept nil.
• In SUOperatingSystem.h, added a check for nil which probably never happens.
• In SUUpdateAlert.m, swapped receiver with parameter in -isEqualToString, 3 places, so that nonnull parameter could never be nil.
• In SUUpdater.m, added NSLocalizedString() wrappers around 8 recently-added (in the last few years, I think) user-facing warning strings.
2016-06-17 14:42:44 -07:00
B. Kevin Hardman f3a151d473 update Sparkle framework headers to use modules if modules are available 2016-06-16 12:16:31 -04:00
Jake Petroules bb624ffa59 Replace OS X with macOS or more generic terminology. 2016-06-15 13:46:19 -07:00
Jake Petroules 2963f788e1 Fix version number in Doxyfile. 2016-06-15 13:43:40 -07:00
Kornel 9017962ab9 Merge pull request #818 from zorgiepoo/auth-wait-fileop
Improve Authorization Usage (Take 2)
2016-06-11 00:24:22 +01:00
Zorg dd0805c05b No need to log the underlying error
This is already logged when logging the main error
2016-06-10 16:13:18 -04:00
Zorg e4c3c29a85 Fix SUFileOperationConstants link errors in BinaryDelta 2016-06-09 07:59:46 -04:00
Zorg be1e86174a Wait for the appropriate process when authorizing file operations
This changes the way we authorize & execute commands, and how we wait for their completion. In order to obtain the correct child to wait (instead of another one terminating intermediately), we use a wrapper tool (fileop) to output its pid onto the communication pipe that we read from the other end.
2016-06-08 21:49:58 -04:00
Kornel 8b56fba39b Merge pull request #814 from DivineDominion/master
add Carthage & CocoaPods compatibility indicators to README
2016-05-26 11:06:42 +01:00
Christian Tietze db232a263b add CocoaPods indicator 2016-05-26 10:44:15 +02:00
Christian Tietze 4d952e9961 add Carthage indicator 2016-05-26 10:43:29 +02:00
Kornel Lesiński 64fd27d918 Fix 10.7 compat in new code 2016-05-22 23:09:23 +01:00
Kornel Lesiński 666e86b0bb Merge remote-tracking branch 'origin/master' into nsparse
* origin/master: (31 commits)
  Fix indentation with bspatch.c
  Fix warnings for bsdiff.c
  Improve error handling on readfile()
  Don't forget to free the buffer on failure
  Don't exit the program on failure for bsdiff.c
  Don't exit the program on failure for bspatch.c
  Use FILE* functions in bspatch.c
  Use FILE* (fopen/fread/etc) functions for bsdiff.c
  Fix warnings for bspatch
  Don't hide warnings for bsdiff/bspatch
  Reorganize checks for clarity
  Update changelog
  Update screenshot with new logo.
  Remove Sparkle.png. This does not appear to be used anywhere anymore.
  Set correct DPI for all images (72 for @1x, 144 for @2x).
  Assign newly added icon images in asset catalog (#801) (#804)
  Update app icon for Autoupdate.app (#347)
  Updated sponsored by text and links (#800)
  Upgrade warning to alert for signing update over HTTP with no DSA key
  Clear update caches directory before downloading new update
  ...
2016-05-22 23:09:08 +01:00
Kornel 601b4a7a7f Merge pull request #811 from zorgiepoo/bsdiff-fixes
bsdiff fixes
2016-05-22 22:31:12 +01:00
Zorg 1316707136 Fix indentation with bspatch.c 2016-05-16 22:30:48 -04:00
Zorg e485baf8b8 Fix warnings for bsdiff.c 2016-05-16 22:20:35 -04:00
Zorg d71fe4a17d Improve error handling on readfile() 2016-05-16 22:05:53 -04:00
Zorg f990f5fcfc Don't forget to free the buffer on failure 2016-05-16 22:05:43 -04:00
Zorg 07ac154e2e Don't exit the program on failure for bsdiff.c 2016-05-16 22:05:29 -04:00
Zorg 48eb25fbf3 Don't exit the program on failure for bspatch.c
We call warn type functions instead of err ones now and do some cleanup
2016-05-16 22:05:19 -04:00
Zorg 914bf9e333 Use FILE* functions in bspatch.c 2016-05-16 22:04:44 -04:00
Zorg 271b7a1daf Use FILE* (fopen/fread/etc) functions for bsdiff.c
This way we don't have to handle EINTR
2016-05-16 22:01:41 -04:00
Zorg c11c660f22 Fix warnings for bspatch 2016-05-16 21:58:32 -04:00
Zorg 0e2fe68399 Don't hide warnings for bsdiff/bspatch 2016-05-16 21:57:19 -04:00
Kornel 852965d824 Merge pull request #807 from sparkle-project/seccheck
Simpler conditions for security config check
2016-05-12 23:19:08 +01:00
Kornel Lesiński e2c60be805 Reorganize checks for clarity 2016-05-12 15:19:57 +01:00
Kornel Lesiński 71e15f4b1d Update changelog 2016-05-10 13:32:27 +01:00
Jake Petroules 8a4e4aea2c Update screenshot with new logo. 2016-04-30 17:47:37 -07:00
Jake Petroules 8fea6670c2 Remove Sparkle.png. This does not appear to be used anywhere anymore. 2016-04-30 17:27:26 -07:00
Jake Petroules 19fcca11f0 Set correct DPI for all images (72 for @1x, 144 for @2x). 2016-04-30 17:24:02 -07:00
1024jp fd082a93d4 Assign newly added icon images in asset catalog (#801) (#804) 2016-04-30 17:20:51 -07:00
Kornel b9e8830f60 Merge pull request #801 from 1024jp/appIcon
Update app icon for Autoupdate.app (#347)
2016-04-30 13:40:04 +01:00
1024jp 8576eb7cad Update app icon for Autoupdate.app (#347) 2016-04-30 18:42:17 +09:00
Justin Dorfman cf4c02f1b0 Updated sponsored by text and links (#800)
We are migrating the Bandwidth Hog brand with MaxCDN.
2016-04-28 19:51:32 -07:00
Kornel 8e57ca9284 Merge pull request #798 from zorgiepoo/http-no-dsa-alert
Upgrade warning to alert for signing update over HTTP with no DSA key
2016-04-20 22:56:02 +01:00
Kornel 3c2f24c340 Merge pull request #797 from zorgiepoo/download-cleanup
Download cleanup
2016-04-19 10:16:48 +01:00
Kornel 7a9ff3de48 Merge pull request #780 from zorgiepoo/fix-tests
Fix issues with unit tests
2016-04-19 10:11:35 +01:00
Zorg a3d4d9fac4 Upgrade warning to alert for signing update over HTTP with no DSA key 2016-04-19 02:59:33 -04:00
Zorg a937fa0a17 Clear update caches directory before downloading new update
This aims to make it impossible to have download data accumulate inside the caches directory.
We still try to deal with if an intermediate file is created at the path we want.

appCachePath method was also moved away from SUHost into SUBasicUpdateDriver which is the only class that needs it.
This method also has very little to do with host bundles.

appCachePath is also called less when checking for the existence of intermediate file paths.

Lastly, we now create a directory whose name is the sparkle bundle ID instead of just "Sparkle"
This is to improve potential name collision issues.
2016-04-19 02:39:00 -04:00
Zorg 99be33d83b Move Test App server directory data into subdirectory inside Caches
We want to wipe the caches directory we create for the test app data on launch,
and want to make sure no other data is being inserted into the same directory.
Before, Sparkle was inserting data into the same directory when downloading an update.
2016-04-19 02:31:02 -04:00
Kornel 0132377a2a Merge pull request #795 from zorgiepoo/check-parent-writability
Check the bundle's parent directory for writability too
2016-04-13 00:02:55 +01:00
Kornel 7fdedad68e Merge pull request #794 from zorgiepoo/fix-symlinks
Don't follow symbolic links for file operations
2016-04-12 15:58:29 +01:00
Zorg aa7c46ba4f Check the bundle's parent directory for writability too
This is to decide if we should allow automatic downloading & installing of updates or not.
2016-04-11 03:15:36 -04:00
Zorg d263bf4fd0 Don't follow symbolic links for file operations
This fixes issues with updating modification/access time, and changing owner/group
where symbolic links used to be followed. Symbolic link tests are included.
2016-04-11 03:05:53 -04:00
Kornel bdb3dd8c36 Merge pull request #790 from zorgiepoo/no-auth-cleanup
Don't bring up an authorized dialog during cleanup
2016-04-04 14:41:25 +01:00
Zorg c8ff1c0453 Don't bring up an authorized dialog during cleanup
If permissions are abnormal during cleanup or somewhere along the lines, it may be
possible to bring up authorization dialog that is not really needed. Prevent this from happening.

We would want to restrict authorization from being possible anyway when not needed.
2016-04-04 01:54:02 -04:00
Kornel bb40663d37 Merge pull request #789 from Eitot/patch
Remove SUEnableAutomaticChecksKeyOld and SUCheckAtStartup constants
2016-04-02 12:18:45 +01:00
Eitot b8588543cf Remove SUEnableAutomaticChecksKeyOld and SUCheckAtStartup constants 2016-04-02 00:07:20 +02:00
Kornel cc332de4d1 Merge pull request #786 from zorgiepoo/fix-warnings
Fix warnings
2016-03-23 09:32:50 +00:00
Zorg d6b1c7de54 Fix another place where I accidently swapped key & object value 2016-03-22 23:51:20 -04:00
Zorg 3a3f46f2c1 Fix one place where I accidently swapped key & object value 2016-03-22 22:52:40 -04:00
Zorg 1ae0999082 Fix nullability warnings 2016-03-22 22:08:14 -04:00
Zorg c265e3f7bf Fix warnings caused by -Wpartial-availability
Most of this is removing Obj-C subscripting usage
Some bits are adding pragma ignores to places where we are careful to not use the API at runtime on older OS's

Note that for NSMutableDictionary:
x[y] = z is not the same as [x setObject:z forKey:y]

In particular, z can be nil for subscripting (removing the element if it exists) where it cannot for setObject:forKey:
Personally I like the non-subscripting semantics better. Most cases we were using this we were checking if the object was non-nil anyway
2016-03-22 22:07:49 -04:00
Kornel 2faf8ccdd2 Merge pull request #783 from sebcode/l10n-fixes
Fix german l10n.
2016-03-20 00:45:14 +00:00
Sebastian Volland 2f724659a7 Fix german l10n.
Update german translation.
Update german version of SUAutomaticUpdateAlert.xib (Button widths).
Update CheckLocalizations.swift for Swift 2.
2016-03-19 18:40:41 +01:00
Kornel Lesiński 8cca51d08b Merge remote-tracking branch 'origin/master' into nsparse 2016-03-14 12:32:15 +00:00
Kornel Lesiński c9fa1142c9 Formatting/comments 2016-03-14 12:22:35 +00:00
Kornel 445cc55794 Merge pull request #781 from zorgiepoo/subscripting
Don't use subscripting where it may potentially be risky on 10.7
2016-03-14 12:16:43 +00:00
Zorg 013e60204d Don't use subscripting where it may potentially be risky on 10.7 2016-03-13 23:40:23 -04:00
Zorg b8fecf1f36 Fix issues with unit tests
I added public DSA file, automatic update checking, disabled system profiling
in the unit test's info.plist so that SUUpdater won't complain that DSA is missing,
and it won't prompt for update permission the first time.

I also made SUUpdater use the correct bundle in SUUpdaterTest
2016-03-13 22:27:57 -04:00
Kornel b319fb50f9 Merge pull request #756 from zorgiepoo/best-update-by-version
Best Update by Version & Date Removal
2016-03-12 15:39:38 +00:00
Kornel Lesiński 698e737b56 CocoaPods 2016-03-12 01:16:51 +00:00
Kornel Lesiński 0be862708f Merge tag '1.14.0'
* tag '1.14.0':
  v1.14.0
  Fixed crash on 10.7 - subscript operator not available https://github.com/sparkle-project/Sparkle/issues/776 related
2016-03-11 09:20:21 +00:00
Kornel Lesiński 1c8d54166b v1.14.0 2016-03-11 09:11:12 +00:00
kleuter 77511c8f19 Fixed crash on 10.7 - subscript operator not available https://github.com/sparkle-project/Sparkle/issues/776 related 2016-03-11 09:07:42 +00:00
Kornel d9a3afb869 Merge pull request #778 from kleuter/master
Fixed crash on 10.7 - subscript operator not available https://github.com/sparkle-project/Sparkle/issues/776 related
2016-03-09 16:44:12 +00:00
kleuter 34a78d59fc Fixed crash on 10.7 - subscript operator not available https://github.com/sparkle-project/Sparkle/issues/776 related 2016-03-09 12:07:51 +01:00
Kornel Lesiński b95008e248 Merge branch '1.14.x'
* 1.14.x:
  One more attr fix
2016-03-09 00:34:10 +00:00
Kornel Lesiński 317423ae78 One more attr fix
#776
2016-03-09 00:33:59 +00:00
Kornel Lesiński 27cb8e66fe Merge branch '1.14.x'
* 1.14.x:
  More workarounds for OS X 10.7
2016-03-09 00:10:14 +00:00
Kornel Lesiński 28e8a1fdaf More workarounds for OS X 10.7
#776
2016-03-09 00:09:04 +00:00
Kornel Lesiński f43c284f14 Merge tag '1.14.0'
* tag '1.14.0':
  Fix #776
2016-03-08 23:43:46 +00:00
Kornel Lesiński cd3d7d9f98 Fix #776 2016-03-08 23:24:26 +00:00
Kornel 864044e44e Merge pull request #772 from zorgiepoo/fix-codesigning-tests
Fix code signing verifier tests when ran locally
2016-03-01 00:39:49 +00:00
Kornel Lesiński 48f18d000c Support XML namespace prefixes when parsing appcasts
Fixes #771
2016-03-01 00:37:52 +00:00
Zorg d0adc0af39 Fix code signing verifier tests when ran locally
The tests sometimes fail for me when copying these files over,
because they already may exist. I guess they're not torn down properly.
2016-02-29 18:30:36 -05:00
Kornel Lesiński 64d95bb36f Error code for download errors
Fixes #770
2016-02-29 13:39:08 +00:00
Kornel a52cbc38a1 Merge pull request #769 from zorgiepoo/update-last-check-date
Update last update check date when the update driver finishes
2016-02-28 00:04:45 +00:00
Zorg 530a90cb73 Update last update check date when the update driver finishes
This fixes the issue where if an update alert is present for a long time,
and the user dismisses it, they may be prompted with another update alert
immediately after.
2016-02-27 18:39:18 -05:00
Kornel 168c769eb0 Merge pull request #764 from nriley/icon-scaling
Scale app icon up if needed in Software Update window (#763)
2016-02-21 01:11:45 +00:00
Nicholas Riley 5b3577c14c Scale app icon up if needed in Software Update window (#763) 2016-02-20 13:56:28 -05:00
Zorg b9c664687d Take delta updates in account and add tests for them 2016-02-19 12:43:41 -05:00
Zorg 2a3e88bf96 Test the dateString field 2016-02-19 11:45:54 -05:00
Zorg 004ac3f9ae Test the best chosen appcast item 2016-02-19 11:26:35 -05:00
Zorg 8a04cc726f Appcast items are no longer sorted; reflect that in unit tests 2016-02-19 10:19:00 -05:00
Zorg 9f2604b888 Merge branch 'master' into best-update-by-version 2016-02-19 10:17:27 -05:00
Kornel 0171ab2d84 Merge pull request #761 from zorgiepoo/automatic-update-termination
Fix Installation process being initiated twice
2016-02-19 14:52:25 +00:00
Zorg c3ffd7f739 Don't register for termination notifications more than once. Fixes #757
These notifications are already added by -unarchiverDidFinish: which is
always invoked before -showUpdateAlert
2016-02-19 09:38:42 -05:00
Kornel 91e929cbf9 Merge pull request #760 from sparkle-project/appcastparse
Fixed appcast parsing issue
2016-02-19 08:53:13 +00:00
Kornel Lesiński 9671f7f52d Fixed duplicated appcast item properties
Corrected scope of per-node objects
2016-02-18 19:29:05 +01:00
Kornel Lesiński 2668d18266 Appcast test 2016-02-18 19:28:58 +01:00
Kornel Lesiński a4bdbb7ab3 Merge commit 'a11b1209a97bafd713189f9b0fa14584ba6e100a' into 1.14.x
* commit 'a11b1209a97bafd713189f9b0fa14584ba6e100a':
  Unit test for appcast parsing
  v1.13.1
2016-02-18 19:28:41 +01:00
Kornel Lesiński a11b1209a9 Unit test for appcast parsing 2016-02-18 13:50:05 +01:00
Zorg 625f229a65 Don't terminate the app if we're already terminating 2016-02-18 00:40:14 -05:00
Kornel 0d52e27968 Merge pull request #755 from zorgiepoo/disable-javascript
Disable javascript
2016-02-18 00:04:44 +01:00
Zorg 674b2238b8 Make Sparkle look for the highest compatible version
Sparkle's past behavior was sorting appcast items by published dates and
picking the first compatible item. However, it makes more sense to pick
the compatible item with the highest version (see issue #31).

The NSDate instance creation & sorting has also been removed from the code.
The methods we were using to parse the string into a NSDate have been deprecated,
and are strongly discouraged. Namely, all methods taking an arbitrary/natural string
have been nuked signaling they were probably a really bad idea. Furthermore, the
date code we had created a NSCalendarDate which has been long deprecated.

So we just don't handle date parsing. Even if there is a proper format for the pubDate,
It is an extra burden on the developer to insert a conforming date.
And we shouldn't want to rely on a potentially error-prone input field.
2016-02-17 00:04:07 -05:00
Zorg 4eb2e9af00 Disable Java in the web view too
Plug-ins have already been disabled but I'm not sure if that encompasses Java or not.
May as well be explicit in either case and disable it.
2016-02-16 23:21:28 -05:00
Zorg b64cee8055 Disable javascript by default and make it opt-in
To opt-in to enabling Javascript, set SUEnableJavaScript to true in the app's info.plist
2016-02-16 23:21:08 -05:00
Kornel Lesiński 3163b6a729 1.14.0rc2 2016-02-15 21:01:25 +01:00
Kornel 7b61cdd8f8 Merge pull request #744 from sparkle-project/logs
Refactored error handling in appcast parsing
2016-02-15 10:58:15 +01:00
Kornel Lesiński b29bbdd14b Refactored error handling in appcast parsing 2016-02-12 11:52:53 +01:00
Kornel 5b79151690 Merge pull request #741 from ferben/master
Czech localizations update
2016-02-12 00:04:18 +01:00
Frantisek Erben c315a66151 Czech localizations update 2016-02-10 22:57:54 +01:00
Kornel b1d7c3ade9 Merge pull request #737 from zorgiepoo/uitests
UI Tests for Test Application
2016-02-08 15:43:37 +00:00
Zorg 682de21978 Test if the updated app is the frontmost one 2016-02-06 21:00:45 -05:00
Zorg b5b1e3d51d Add UITests scheme so UI tests can run from xcodebuild 2016-02-06 20:12:39 -05:00
Zorg efd94e2de0 Add UI Tests for the Test Application
This tests the test application checking for updates, downloading & installing, and relaunching
2016-02-06 11:32:18 -05:00
Kornel b3dbb5db1f Merge pull request #728 from sparkle-project/logs
Logs
2016-02-05 00:30:24 +00:00
Kornel b795f56842 Merge pull request #724 from xhacker/fix-zh-hans
Update zh_Hans localization
2016-02-05 00:29:50 +00:00
Kornel Lesiński c0bda0c372 Changelog 2016-02-05 00:12:14 +00:00
Kornel Lesiński 2a693e62bf v1.13.1 2016-02-04 23:57:25 +00:00
Kornel Lesiński eb3d962526 Merge branch '1.11.x' into 1.13.0
* 1.11.x:
  Prevent inclusion of local files via file:// XML entities
  Disable redirects to non-HTTP URLs in release notes webview
2016-02-04 23:56:40 +00:00
Kornel Lesiński f90700e830 Version bump 2016-02-04 23:52:55 +00:00
Kornel 2b7f61f2a2 Merge pull request #733 from FlixelPhotos/master
Remove test resource from the FW target
2016-02-03 14:20:09 +00:00
Karl Moskowski ffa449742d Remove test resource from the FW target
Fixes #732.
2016-02-03 08:35:57 -05:00
Kornel Lesiński b40a4eefde Log detailed XML parsing error 2016-02-01 10:57:18 +00:00
Kornel Lesiński 4e60a61036 Notify when URLs are blocked 2016-02-01 10:57:18 +00:00
Kornel Lesiński b3835717ab Version bump 2016-01-31 12:14:52 +00:00
Kornel Lesiński e05b397a00 Version bump 2016-01-31 12:13:55 +00:00
LIU Dongyuan / 柳东原 7c48061b85 Update zh_Hans localization 2016-01-29 16:20:10 -08:00
Kornel 03ca628eef Merge pull request #723 from xhacker/testapp-l10n
Make test app available in all languages, fix #695
2016-01-30 00:06:20 +00:00
LIU Dongyuan / 柳东原 7aad8d3586 Make test app available in all languages, fix #695 2016-01-29 15:54:54 -08:00
Jake Petroules 1e89891577 Merge pull request #721 from xhacker/patch-2
Update Sparkle.podspec
2016-01-29 13:19:55 -08:00
LIU Dongyuan / 柳东原 dd77e6bc5d Update Sparkle.podspec 2016-01-29 13:17:53 -08:00
Kornel Lesiński 0fe520f95b Merges fixes for HTTP MITM security vulnerability:
https://sparkle-project.github.io/documentation/security/#http-mitm-vulnerability
2016-01-29 15:14:11 +00:00
Kornel Lesiński a6e9c8aff6 Prevent inclusion of local files via file:// XML entities 2016-01-29 14:52:55 +00:00
Kornel Lesiński 70f6929ac7 Disable redirects to non-HTTP URLs in release notes webview 2016-01-29 14:52:55 +00:00
Kornel a360e60f76 Merge pull request #719 from vitu/master
Translated new string, fixed double space, fixed “archive” and “relau…
2016-01-25 15:29:33 +00:00
vitu 2c6941e975 Translated new string, fixed double space, fixed “archive” and “relaunch” terminologies for pt-BR. 2016-01-25 13:05:07 -02:00
Kornel 2afc553e03 Merge pull request #716 from sparkle-project/alertdriver
Alert driver
2016-01-18 15:50:38 +00:00
Kornel Lesiński 5ed9c2615c Avoid two copies in unit tests 2016-01-17 22:34:27 +00:00
Kornel Lesiński ca22a43e46 Check configuration after driver has been configured 2016-01-17 22:22:42 +00:00
Kornel Lesiński d157a6fb2a Move showing of alert to the update driver 2016-01-17 22:22:41 +00:00
Kornel Lesiński 503faf49e1 Unused 2016-01-17 22:22:41 +00:00
Kornel Lesiński 45f597cd2a Merge branch 'master' of https://github.com/GeneralElectric/Sparkle into GeneralElectric-master
* 'master' of https://github.com/GeneralElectric/Sparkle:
  Remove newline, Add explicit property synthesis
  Encrypted dmg support
2016-01-17 16:39:11 +00:00
Kornel 26fd1b168a Merge pull request #710 from sparkle-project/logerror
Don't show bad-release-notes-url error to the user
2016-01-10 13:41:25 +00:00
Kornel a9a0fe54b8 Merge pull request #711 from sparkle-project/urlencode
Don't re-encode URLs
2016-01-10 13:41:03 +00:00
Kornel 1c976de2b7 Merge pull request #712 from orta/patch-1
Adds dates to releases in the CHANGELOG
2016-01-09 20:38:55 +00:00
Orta 00ea872b76 Adds dates to releases in the CHANGELOG 2016-01-09 20:29:38 +00:00
Kornel Lesiński 836c0848cc Don't re-encode URLs
Fixes #99
2016-01-09 16:45:54 +00:00
Kornel Lesiński 95372134c8 Don't show bad-release-notes-url error to the user
Webview having local file access doesn't seem worse than the app having local file access, but still it seems like a bad idea that relies on files being in predetermined location.
2016-01-09 16:15:00 +00:00
Kornel 27ce4ee92c Merge pull request #702 from sparkle-project/secckey
Make it clear which file is secret
2016-01-09 16:00:39 +00:00
Kornel 6889b9b080 Merge pull request #706 from 1024jp/japanese
Add some Japanese lozalized strings
2016-01-04 12:30:40 +00:00
1024jp c81d190908 Add some Japanese lozalized strings 2016-01-04 11:33:23 +09:00
Kornel Lesiński 06826d426d Re-add forgotten tests 2015-12-30 13:24:52 +00:00
Kornel Lesiński 62afa6b9a9 Give time to set a delegate
#704
2015-12-30 13:24:51 +00:00
Kornel 14839e4ab5 Merge pull request #692 from sparkle-project/atswarn
Warn about ATS
2015-12-30 13:09:47 +00:00
Jake Petroules 58003a8501 Merge pull request #703 from xhacker/patch-1
Make 1.13.0 available via CocoaPods
2015-12-28 00:33:56 -08:00
LIU Dongyuan / 柳东原 698fa40647 Update Sparkle.podspec 2015-12-28 00:31:51 -08:00
Kornel Lesiński 5fe3ee1300 Make it clear which file is secret 2015-12-18 17:26:44 +00:00
Kornel Lesiński b83f4c30f2 Merge commit '75551e8d0a0ee1fa3b39840fea504e01865ec81b'
* commit '75551e8d0a0ee1fa3b39840fea504e01865ec81b':
  v1.13.0
2015-12-18 17:26:34 +00:00
Kornel Lesiński 75551e8d0a v1.13.0 2015-12-18 17:23:52 +00:00
Kornel e3d89ec3db Merge pull request #701 from sparkle-project/nondelta
Get non-delta update from delegate
2015-12-18 15:02:25 +00:00
Kornel Lesiński 27f00c04b0 Ask delegate for non-delta updates
Fixes #700
2015-12-17 23:05:09 +00:00
Kornel Lesiński 30a72a1bd6 Removed old objectEnumerator 2015-12-17 22:55:03 +00:00
Kornel bbe3d4a811 Merge pull request #696 from sparkle-project/bundleid
Change bundle ID
2015-12-17 21:12:36 +00:00
Kornel Lesiński e83540a1e9 Change bundle ID
Fixes #687
2015-12-15 10:22:43 +00:00
Kornel Lesiński 254ae41759 Limit alert to main bundle 2015-12-14 20:22:58 +00:00
Kornel Lesiński aa11a9e934 Warn about ATS blocking 2015-12-14 20:13:32 +00:00
Kornel Lesiński 0abe9ad994 Deduped alert code 2015-12-14 20:13:18 +00:00
Kornel Lesiński 452ff64740 Move sanity checks to a separate function 2015-12-14 19:49:45 +00:00
Andrew K. Boyd 47c1761137 Remove newline, Add explicit property synthesis 2015-11-13 16:49:12 -05:00
Andrew K. Boyd 4f88994cf0 Encrypted dmg support
Add the capability to set a decryption password for updating with an
encrypted dmg file.

This enables the the ability to update using an encrypted disk image without having to prompt the user for a password. This is useful when access to the application binaries is only available via distribution or from a location in which authentication is required. This can help prevent an attacker from having unwanted access to application binaries for reverse engineering.

This assists with a defense in depth approach to security.
2015-11-02 10:02:31 -05:00
257 changed files with 6448 additions and 3120 deletions

No files matched your search

+7
View File
@@ -28,6 +28,13 @@ Icon
.Spotlight-V100
.Trashes
# With Carthage, if Sparkle is included as a Git submodule (e.g. with the
# --use-submodules option), the main module's .gitignore can't reach all the
# way inside the submodule to ignore the added Carthage/Build symlink, and Git
# keeps complaining about untracked changes in the submodule forever, which
# is very annoying. To avoid that issue, ignore here in Sparkle instead.
Carthage/Build
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
+1 -3
View File
@@ -1,7 +1,5 @@
language: objective-c
osx_image: xcode7
osx_image: xcode8.2
before_install:
- brew update
- brew install macmade/tap/xcode-coveralls
script: make ci
after_success: xcode-coveralls --exclude /Applications --exclude Tests --exclude Vendor build/Build/Intermediates/Sparkle.build/Coverage/Sparkle.build/Objects-normal/x86_64
+85 -12
View File
@@ -1,5 +1,78 @@
# 1.16.0
# 1.12.0
* Guided package installs are now the default for updating packages (Zorg)
- `pkg` installers won't show any UI. If you require the old behavior of showing a full installer window, rename the `*.pkg` file to `*.sparkle_interactive.pkg`
* Previous version of the app is now deleted instead of staying in the trash (Zorg)
* Added `generate_appcast` helper tool (Kornel Lesiński)
* Made manual check resume pending automatic updates instead of starting a new update (Kornel Lesiński)
* Started using `length` value from RSS if HTTP doesn't give one (Zorg)
* Hidden automatic updates checkbox for information only updates (Bi11)
* Added progressbar for DMG and binary delta extraction (Kornel Lesiński)
* Fixed showing of download status if we attempt a 2nd download (Zorg)
* Refactorings to sync with upcoming 2.0
* Decoupled and simplified installation code using protocols (Zorg)
* Added nullability annotations (Zorg)
* Allowed delegate methods that return an object to return nil (Zorg)
* Decreased responsibility of SUHost and moved code into other components (Zorg)
* Removed Sparkle.pch and many file #includes (Zorg)
# 1.15.0
* A new icon! Thanks to 1024jp
* Show alert when an update is sent over insecure HTTP with no DSA key (Zorg)
- If you can't use HTTPS, you must at least sign updates with a DSA key.
* Improved binary delta implementation (Zorg)
* Added improved -validateMenuItem: as a method in SUUpdater.h for public use (Zorg)
* Removed reachability preflight check (Zorg)
* Clear update caches directory before downloading new update (Zorg)
* Check the bundle's parent directory for writability too (Zorg)
* Don't follow symbolic links for file operations (Zorg)
* Don't bring up an authorized dialog during cleanup (Zorg)
* Made Sparkle look for the highest compatible version regardless of timestamps (Zorg)
* Fixed compatibility with 10.7
* Fixed crash on 10.7 - subscript operator not available (kleuter)
* Fixed warnings caused by -Wpartial-availability (Zorg)
* Fixed german l10n. (Sebastian Volland)
* Error code for download errors (Kornel Lesiński)
* Update last update check date when the update driver finishes (Zorg)
* Scale app icon up if needed in Software Update window (Nicholas Riley)
* Don't register for termination notifications more than once (Zorg)
* Don't terminate the app if we're already terminating (Zorg)
* Removed SUEnableAutomaticChecksKeyOld and SUCheckAtStartup constants (Eitot)
* Updated Sparkle framework headers to use modules if modules are available (B. Kevin Hardman)
* Fixed warnings, fixed uses of SULocalizedString (Jerry Krinock)
* Improved signing verifier to take any host and s/application/bundle/ (Zorg)
* Improved Spotlight updates after delta extraction (Zorg)
# 1.14.0 (Mar 11, 2016)
* Disable javascript by default and make it opt-in (Zorg)
* URL-encoding of appcast URLs is preserved (Kornel Lesiński)
* Delegate is asked for fallback updates if delta update fails (Kornel Lesiński)
* Fixed crash on 10.7 - subscript operator not available (kleuter)
* Fixed check of feed URL before delegate had a chance to set it (Kornel Lesiński)
* Re-added support for password-protected dmg images (Andrew K. Boyd)
* Added warning about ATS blocking (Kornel Lesiński)
* Translation fixes for pt-BR. (vitu)
* Add some Japanese lozalized strings (1024jp)
* Made test app available in all languages #695 (LIU Dongyuan / 柳东原)
* Czech localizations update (Frantisek Erben)
* Removed a test resource from the framework bundle (Karl Moskowski)
* Test if the updated app is the frontmost one (Zorg)
* UI Tests for the Test Application (Zorg)
# 1.13.1 (Jan 31, 2016)
Important security fixes:
* Prevent inclusion of local files via file:// XML entities
* Disable redirects to non-HTTP URLs in release notes webview
# 1.13.0 (Dec 18, 2015)
* Changed framework's bundle ID from `org.andymatuschak.Sparkle` to `org.sparkle-project.Sparkle`.
# 1.12.0 (Dec 13, 2015)
* Rewritten file operations for updating an app (Zorg)
- Ensuring atomic move operations, robust error handling.
@@ -8,7 +81,7 @@
- Strong documentation, easier to read code.
* Automatic updates won't be installed if the system is about to shut off (Zorg)
* Deprecated serving over HTTP without DSA (Zorg)
- Note that Apple has deprecated insecure HTTP in OS X 10.11
- Note that Apple has deprecated insecure HTTP in macOS 10.11
* Improved Autoupdate application (Zorg)
* Do all the installation work after the runloop is set up
* TerminationListener only does termination listening now
@@ -43,11 +116,11 @@
* Disallowed automatic updates when user can't write to the bundle (Zorg)
* Set the task working directories instead of changing the process working directory (Kevin Wojniak)
# 1.11.1
# 1.11.1 (Nov 9, 2015)
* Don't install automatic updates when system is about to shut down
# 1.11.0
# 1.11.0 (Aug 24, 2015)
* Big improvements to code signing and DSA verification
- Sparkle now checks not only whether an update is correctly signed, but also whether the updated version will be able to verify future updates. Updates now must either use DSA keys correctly, or not try to use them at all. Same goes for Apple Code Signing.
@@ -65,7 +138,7 @@
* Added logging of appcast/download URL on error (Kornel Lesiński)
* More robust reading of Autoupdate.app path from Sparkle bundle
# 1.10.0
# 1.10.0 (Apr 26, 2015)
* Massive improvements to the BinaryDelta tool (Zorg)
- Ability to track file permissions (Zorg)
@@ -81,7 +154,7 @@
* Stdout used for non error outputs (JDuquennoy)
* French locale update (Kent Sutherland)
# 1.9.0
# 1.9.0 (Jan 26, 2015)
* Added SUUpdater delegate method for failures. (Benjamin Gordon)
* Make the error definitions public (C.W. Betts)
@@ -91,7 +164,7 @@
* Use Library/Caches rather than app support directory (Kornel Lesiński)
* Check for a modal window being onscreen before trying to put up the Sparkle prompt (Alf Watt)
* Fixed crashes on 10.7 (Chris Campbell, Ger Teunis)
* Fixed Sparkle tags parsing (Tamás Lustyik)
* Fixed Sparkle tags parsing (Tamás Lustyik)
* SULog code cleanups (Kevin Wojniak)
* Make sure CFBundleVersion is a semantic version number. (Jake Petroules)
* Replace typedef enums with typedef NS_ENUM to make Swift happier (C.W. Betts)
@@ -104,18 +177,18 @@
* Turkish localization fixes (Emir)
* Proofing of Ukrainian localization (Vera Tkachenko)
# 1.8.0
# 1.8.0 (Jul 26, 2014)
* New SUDSAVerifier based on up-to-date OS X APIs (Zachary Waldowski)
* New SUDSAVerifier based on up-to-date macOS APIs (Zachary Waldowski)
* Detailed error log for failed signature checks (Kornel Lesiński)
* Converted Sparkle to ARC (C.W. Betts)
* Converted ivars to properties. (Jake Petroules)
* Cocoapod support (Xhacker Liu)
* Quarantine removal on OS X 10.10 (C.W. Betts)
* Quarantine removal on macOS 10.10 (C.W. Betts)
* Updated Japanese localization (1024jp)
* Added Greek localization
# 1.7.1
# 1.7.1 (Jul 2, 2014)
* Removed option to install unverified updates (Kornel Lesiński)
* Added detailed log when code signing verification fails (Sam Deane)
@@ -132,7 +205,7 @@
# 1.7.0
* Dropped support for OS X 10.6. Sparkle now supports 10.7 and newer (including 10.10 Yosemite) on 64-bit Intel Macs (the last 32-bit Mac was released in 2006).
* Dropped support for macOS 10.6. Sparkle now supports 10.7 and newer (including 10.10 Yosemite) on 64-bit Intel Macs (the last 32-bit Mac was released in 2006).
* Removed use of deprecated functions (Zachary Waldowski)
* Switched to modern Obj-C runtime and new literals syntax
* Removed pre-10.7 code. (C.W. Betts)
+74
View File
@@ -0,0 +1,74 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level of experience,
nationality, personal appearance, race, religion, or sexual identity and
orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at kornel+sparkle@geekhood.net. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/
+8 -7
View File
@@ -1,7 +1,8 @@
// Common
SPARKLE_BUNDLE_IDENTIFIER = org.andymatuschak.Sparkle
SPARKLE_BUNDLE_IDENTIFIER = org.sparkle-project.Sparkle
SPARKLE_RELAUNCH_TOOL_NAME = Autoupdate
SPARKLE_FILEOP_TOOL_NAME = fileop
SPARKLE_APPEND_VERSION_NUMBER = 1
@@ -15,15 +16,13 @@ SPARKLE_AUTOMATED_DOWNGRADES = 0
SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME = 0
SPARKLE_VERSION_MAJOR = 1
SPARKLE_VERSION_MINOR = 12
SPARKLE_VERSION_MINOR = 16
SPARKLE_VERSION_PATCH = 0
SPARKLE_VERSION = $(SPARKLE_VERSION_MAJOR).$(SPARKLE_VERSION_MINOR).$(SPARKLE_VERSION_PATCH)
CURRENT_PROJECT_VERSION = $(SPARKLE_VERSION)
ALWAYS_SEARCH_USER_PATHS = NO
ENABLE_STRICT_OBJC_MSGSEND = YES
GCC_PRECOMPILE_PREFIX_HEADER = YES
GCC_PREFIX_HEADER = Sparkle/Sparkle.pch
GCC_SYMBOLS_PRIVATE_EXTERN = YES
GCC_INLINES_ARE_PRIVATE_EXTERN = YES
ARCHS = $(ARCHS_STANDARD)
@@ -31,12 +30,15 @@ MACOSX_DEPLOYMENT_TARGET = 10.7
PRODUCT_NAME = ${TARGET_NAME}
PRODUCT_BUNDLE_IDENTIFIER = org.sparkle-project.Sparkle.${PRODUCT_NAME:rfc1034identifier}
GCC_PREPROCESSOR_DEFINITIONS_COMMON = SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME=$(SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME) SPARKLE_AUTOMATED_DOWNGRADES=$(SPARKLE_AUTOMATED_DOWNGRADES) SPARKLE_APPEND_VERSION_NUMBER=$(SPARKLE_APPEND_VERSION_NUMBER) SPARKLE_BUNDLE_IDENTIFIER=\"$(SPARKLE_BUNDLE_IDENTIFIER)\" SPARKLE_RELAUNCH_TOOL_NAME=\"$(SPARKLE_RELAUNCH_TOOL_NAME)\"
GCC_PREPROCESSOR_DEFINITIONS_COMMON = SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME=$(SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME) SPARKLE_AUTOMATED_DOWNGRADES=$(SPARKLE_AUTOMATED_DOWNGRADES) SPARKLE_APPEND_VERSION_NUMBER=$(SPARKLE_APPEND_VERSION_NUMBER) SPARKLE_BUNDLE_IDENTIFIER=\"$(SPARKLE_BUNDLE_IDENTIFIER)\" SPARKLE_RELAUNCH_TOOL_NAME=\"$(SPARKLE_RELAUNCH_TOOL_NAME)\" SPARKLE_FILEOP_TOOL_NAME=\"$(SPARKLE_FILEOP_TOOL_NAME)\"
CLANG_ENABLE_OBJC_ARC = YES
GCC_ENABLE_PASCAL_STRINGS = NO
GCC_NO_COMMON_BLOCKS = YES;
COMBINE_HIDPI_IMAGES = NO;
// Enable warnings
CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;
CLANG_ANALYZER_SECURITY_FLOATLOOPCOUNTER = YES
CLANG_ANALYZER_SECURITY_INSECUREAPI_RAND = YES
CLANG_ANALYZER_SECURITY_INSECUREAPI_STRCPY = YES
@@ -51,7 +53,6 @@ CLANG_WARN_OBJC_EXPLICIT_OWNERSHIP_TYPE = YES
CLANG_WARN_OBJC_IMPLICIT_ATOMIC_PROPERTIES = YES
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES
CLANG_WARN_OBJC_MISSING_PROPERTY_SYNTHESIS = YES
CLANG_WARN_OBJC_RECEIVER_WEAK = YES
CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES
CLANG_WARN_SUSPICIOUS_IMPLICIT_CONVERSION = YES
CLANG_WARN_UNREACHABLE_CODE = YES
@@ -87,4 +88,4 @@ CLANG_ENABLE_MODULES[sdk=macosx10.8] = NO
WARNING_CFLAGS_EXTRA = -Wno-custom-atomic-properties -Wno-implicit-atomic-properties
// Turn on all warnings, then disable a few which are almost impossible to avoid
WARNING_CFLAGS = -Wall -Weverything -Wno-unused-macros -Wno-gnu-statement-expression -Wno-receiver-is-weak -Wno-arc-repeated-use-of-weak -Wno-auto-import $(WARNING_CFLAGS_EXTRA)
WARNING_CFLAGS = -Wall -Weverything -Wno-unused-macros -Wno-gnu-statement-expression -Wno-arc-repeated-use-of-weak -Wno-auto-import $(WARNING_CFLAGS_EXTRA)
@@ -3,7 +3,6 @@
// Debug only
GCC_OPTIMIZATION_LEVEL = 0
SWIFT_OPTIMIZATION_LEVEL = -Onone
DEBUG_INFORMATION_FORMAT = dwarf
ENABLE_TESTABILITY = YES
GCC_GENERATE_DEBUGGING_SYMBOLS = YES
@@ -3,7 +3,6 @@
// Release only
GCC_OPTIMIZATION_LEVEL = s
SWIFT_OPTIMIZATION_LEVEL = -Ofast
DEBUG_INFORMATION_FORMAT = dwarf-with-dsym
GCC_GENERATE_DEBUGGING_SYMBOLS = YES
GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS_COMMON)
+5
View File
@@ -0,0 +1,5 @@
// Fileop tool only
PRODUCT_NAME = $(SPARKLE_FILEOP_TOOL_NAME)
SKIP_INSTALL = YES
CLANG_ENABLE_MODULES = NO
@@ -0,0 +1,7 @@
// Generate Appcast only
#include "ConfigSwift.xcconfig"
SWIFT_OBJC_BRIDGING_HEADER = generate_appcast/Appcast-Bridging-Header.h
MACOSX_DEPLOYMENT_TARGET = 10.11
PRODUCT_NAME = generate_appcast
@@ -0,0 +1,4 @@
// Generate Appcast Debug
#include "ConfigGenerateAppcast.xcconfig"
#include "ConfigSwiftDebug.xcconfig"
@@ -0,0 +1,4 @@
// Generate Appcast Release
#include "ConfigGenerateAppcast.xcconfig"
#include "ConfigSwiftRelease.xcconfig"
+1
View File
@@ -0,0 +1 @@
SWIFT_VERSION = 3.0
+1
View File
@@ -0,0 +1 @@
SWIFT_OPTIMIZATION_LEVEL = -Onone
@@ -0,0 +1 @@
SWIFT_OPTIMIZATION_LEVEL = -Owholemodule
+13
View File
@@ -0,0 +1,13 @@
// UI Test only
#include "ConfigSwift.xcconfig"
INFOPLIST_FILE = UITests/UITests-Info.plist
WRAPPER_EXTENSION = xctest
MACOSX_DEPLOYMENT_TARGET = 10.11
FRAMEWORK_SEARCH_PATHS = $(inherited) $(DEVELOPER_FRAMEWORKS_DIR)
LD_RUNPATH_SEARCH_PATHS = @loader_path/../Frameworks
TEST_TARGET_NAME = Sparkle Test App
USES_XCTRUNNER = YES
@@ -0,0 +1,4 @@
#include "ConfigUITest.xcconfig"
GCC_GENERATE_TEST_COVERAGE_FILES = NO
GCC_INSTRUMENT_PROGRAM_FLOW_ARCS = NO
@@ -0,0 +1,2 @@
#include "ConfigUITest.xcconfig"
#include "ConfigSwiftDebug.xcconfig"
@@ -0,0 +1,2 @@
#include "ConfigUITest.xcconfig"
#include "ConfigSwiftRelease.xcconfig"
+2
View File
@@ -1,5 +1,7 @@
// Unit Test only
#include "ConfigSwift.xcconfig"
INFOPLIST_FILE = Tests/SparkleTests-Info.plist
WRAPPER_EXTENSION = xctest
OTHER_CFLAGS = $(inherited) -iframework"$(DEVELOPER_FRAMEWORKS_DIR)" -iframework"$(PLATFORM_DIR)/Developer/Library/Frameworks"
@@ -1 +1,2 @@
#include "ConfigUnitTest.xcconfig"
#include "ConfigSwiftDebug.xcconfig"
@@ -1 +1,2 @@
#include "ConfigUnitTest.xcconfig"
#include "ConfigSwiftRelease.xcconfig"
+9
View File
@@ -2,6 +2,13 @@
set -e
if [ "$ACTION" = "" ] ; then
# Sanity check that the Podspec version matches the Sparkle version
spec_version=$(printf "require 'cocoapods'\nspec = %s\nprint spec.version" "$(cat "$SRCROOT/Sparkle.podspec")" | LANG=en_US.UTF-8 ruby)
if [ "$spec_version" != "$CURRENT_PROJECT_VERSION" ] ; then
echo "podspec version '$spec_version' does not match the current project version '$CURRENT_PROJECT_VERSION'" >&2
exit 1
fi
rm -rf "$CONFIGURATION_BUILD_DIR/staging"
rm -f "Sparkle-$CURRENT_PROJECT_VERSION.tar.bz2"
@@ -9,6 +16,7 @@ if [ "$ACTION" = "" ] ; then
cp "$SRCROOT/CHANGELOG" "$SRCROOT/LICENSE" "$SRCROOT/Resources/SampleAppcast.xml" "$CONFIGURATION_BUILD_DIR/staging"
cp -R "$SRCROOT/bin" "$CONFIGURATION_BUILD_DIR/staging"
cp "$CONFIGURATION_BUILD_DIR/BinaryDelta" "$CONFIGURATION_BUILD_DIR/staging/bin"
cp "$CONFIGURATION_BUILD_DIR/generate_appcast" "$CONFIGURATION_BUILD_DIR/staging/bin"
cp -R "$CONFIGURATION_BUILD_DIR/Sparkle Test App.app" "$CONFIGURATION_BUILD_DIR/staging"
cp -R "$CONFIGURATION_BUILD_DIR/Sparkle.framework" "$CONFIGURATION_BUILD_DIR/staging"
@@ -16,6 +24,7 @@ if [ "$ACTION" = "" ] ; then
# because missing dSYMs in a release build SHOULD trigger a build failure
if [ "$CONFIGURATION" = "Release" ] ; then
cp -R "$CONFIGURATION_BUILD_DIR/BinaryDelta.dSYM" "$CONFIGURATION_BUILD_DIR/staging/bin"
cp -R "$CONFIGURATION_BUILD_DIR/generate_appcast.dSYM" "$CONFIGURATION_BUILD_DIR/staging/bin"
cp -R "$CONFIGURATION_BUILD_DIR/Sparkle Test App.app.dSYM" "$CONFIGURATION_BUILD_DIR/staging"
cp -R "$CONFIGURATION_BUILD_DIR/Sparkle.framework.dSYM" "$CONFIGURATION_BUILD_DIR/staging"
fi
+11 -5
View File
@@ -13,14 +13,20 @@ if [ -z "$SRCROOT" ] || \
exit 1
fi
# Get the current Git master hash
version=$(cd "$SRCROOT" ; git show-ref --abbrev heads/master | awk '{print $1}')
if [ -z "$version" ] ; then
echo "$0: Can't find a Git hash!" 1>&2
version="$CURRENT_PROJECT_VERSION"
# Get version in format 1.x.x-commits-hash
gitversion=$( cd "$SRCROOT"; git describe --tags --match '[12].*' || true )
if [ -z "$gitversion" ] ; then
echo "$0: Can't find a Git hash!" 1>&2
exit 0
fi
version="$CURRENT_PROJECT_VERSION git-$version"
# remove everything before the first "-" to keep the hash part only
versionsuffix=${gitversion#*-};
if [ "$versionsuffix" != "$gitversion" ]; then
version="$version $versionsuffix"
fi
# and use it to set the CFBundleShortVersionString value
export PATH="$PATH:/usr/libexec"
+2 -2
View File
@@ -1,6 +1,6 @@
PROJECT_NAME = Sparkle
PROJECT_NUMBER = 1.7.1
PROJECT_BRIEF = "A software update framework for OS X"
PROJECT_NUMBER = 1.14.0
PROJECT_BRIEF = "A software update framework for macOS"
PROJECT_LOGO = Resources/Images.xcassets/AppIcon.appiconset/icon_32x32@2x.png
RECURSIVE = YES
+6 -1
View File
@@ -13,6 +13,8 @@ localizable-strings:
release:
xcodebuild -scheme Distribution -configuration Release -derivedDataPath "$(BUILDDIR)" build
open -R "$(BUILDDIR)/Build/Products/Release/Sparkle-"*.tar.bz2
cat Sparkle.podspec
@echo "Don't forget to update CocoaPods! pod trunk push"
build:
xcodebuild clean build
@@ -20,13 +22,16 @@ build:
test:
xcodebuild -scheme Distribution -configuration Debug test
uitest:
xcodebuild -scheme UITests -configuration Debug test
ci:
for i in {7..9} ; do \
if xcrun --sdk "macosx10.$$i" --show-sdk-path 2> /dev/null ; then \
( rm -rf build && xcodebuild -sdk "macosx10.$$i" -scheme Distribution -configuration Coverage -derivedDataPath build ) || exit 1 ; \
fi ; \
done
for i in {10..11} ; do \
for i in {10..12} ; do \
if xcrun --sdk "macosx10.$$i" --show-sdk-path 2> /dev/null ; then \
( rm -rf build && xcodebuild -sdk "macosx10.$$i" -scheme Distribution -configuration Coverage -derivedDataPath build test ) || exit 1 ; \
fi ; \
+24
View File
@@ -0,0 +1,24 @@
# To update the icon run make -f Makefile-icon
# Requires:
# autoconf, automake, libtool, pkg-config, pngquant
ICONDIR=./Resources/Images.xcassets/AppIcon.appiconset
OPTIMIZEDICONS=$(ICONDIR)/optimized_16x16.png $(ICONDIR)/optimized_32x32.png $(ICONDIR)/optimized_128x128.png $(ICONDIR)/optimized_512x512.png
DESTICON=Resources/AppIcon.icns
all: $(DESTICON)
libicns:
git clone https://github.com/pornel/libicns.git
libicns/Makefile: libicns
( cd libicns && autoreconf -vif && ./configure )
libicns/icnsutils/png2icns: libicns/Makefile
( cd libicns && make -j8 )
optimized_%.png: icon_%.png
pngquant -s1 -f -o $@ $<
$(DESTICON): libicns/icnsutils/png2icns $(OPTIMIZEDICONS)
./libicns/icnsutils/png2icns $@ $(OPTIMIZEDICONS)
+29 -30
View File
@@ -1,40 +1,36 @@
# Sparkle [![Build Status](https://travis-ci.org/sparkle-project/Sparkle.svg?branch=master)](https://travis-ci.org/sparkle-project/Sparkle) [![Coverage Status](https://coveralls.io/repos/sparkle-project/Sparkle/badge.svg?branch=master&service=github)](https://coveralls.io/github/sparkle-project/Sparkle?branch=master) <a href="https://www.bandwidthhog.com/?utm_source=sparkle-github&amp;utm_medium=badge&amp;utm_campaign=readme"><img src="https://img.shields.io/badge/sponsored%20by-Bandwidth%20Hog-orange.svg" alt="sponsored by: bandwidth hog"></a>
# Sparkle [![Build Status](https://travis-ci.org/sparkle-project/Sparkle.svg?branch=master)](https://travis-ci.org/sparkle-project/Sparkle) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) [![CocoaPods](https://img.shields.io/cocoapods/v/Sparkle.svg?maxAge=2592000)]() <a href="https://www.stackpath.com/?utm_source=sparkle-github&amp;utm_medium=badge&amp;utm_campaign=readme"><img src="https://img.shields.io/badge/sponsored%20by-StackPath-orange.svg" alt="sponsored by: StackPath"></a>
An easy-to-use software update framework for Cocoa developers.
Secure and reliable software update framework for Cocoa developers.
<img src="Resources/Screenshot.png" width="715" alt="Sparkle shows familiar update window with release notes">
## Changes since 1.5b
* Up-to-date with 10.11 SDK and Xcode 7. Supports OS X 10.7+.
* Cleaned up and modernized code, using ARC and Autolayout.
* Merged bugfixes, security fixes and some features from multiple Sparkle forks.
* Truly automatic background updates (no UI at all) when user agreed to "Automatically download and install updates in the future."
* Ability to mark updates as critical.
* Progress and status notifications for the host app.
* Name of finish_installation.app can be configured to match your app's name.
* Upgraded and more reliable binary delta and code signing verification.
<img src="Resources/Screenshot.png" width="732" alt="Sparkle shows familiar update window with release notes">
## Features
* True self-updating—the user can choose to automatically download and install all updates.
* Displays a detailed progress window to the user.
* Supports authentication for installing in secure locations.
* Supports Apple Code Signing and DSA signatures for ultra-secure updates.
* Easy to install. Sparkle requires no code in your app, so it's trivial to upgrade or remove the framework.
* Uses appcasts for release information. Appcasts are supported by 3rd party update-tracking programs and websites.
* Displays release notes to the user via WebKit.
* Sparkle doesn't bug the user until second launch for better first impressions.
* Seamless integration—there's no mention of Sparkle; your icons and app name are used.
* Deep delegate support to make Sparkle work exactly as you need.
* Optionally sends system information to the server when checking for updates.
* Seamless. There's no mention of Sparkle; your icons and app name are used.
* Secure. Updates are verified using DSA signatures and Apple Code Signing.
* Fast. Supports delta updates which only patch files that have changed.
* Easy to install. Sparkle requires no code in your app, and only needs static files on a web server.
* Supports bundles, preference panes, plugins, and other non-.app software. Can install .pkg files for more complicated products.
* Supports branches due to minimum OS version requirements.
* Handles permissions, quarantine and automatically asks for authentication if needed.
* Uses RSS-based appcasts for release information. Appcasts are a de-facto standard supported by 3rd party update-tracking programs and websites.
* Sparkle stays hidden until second launch for better first impressions.
* Truly self-updating — the user can choose to automatically download and install all updates in the background.
## Changes since 1.5b
* Compatibilty with macOS Sierra.
* Up-to-date with 10.12 SDK and Xcode 8 (supports macOS 10.7+).
* Important security fixes.
* Cleaned up and modernized code, using ARC and Autolayout.
* Truly automatic background updates (no UI at all) when user agreed to "Automatically download and install updates in the future."
* Upgraded and more reliable binary delta and code signing verification.
* Ability to mark updates as critical.
* Progress and status notifications for the host app.
## Requirements
* Runtime: OS X 10.7 or greater
* Build: Xcode 5 and 10.8 SDK or greater
* Runtime: macOS 10.7 or greater
* Build: Xcode 7 and 10.8 SDK or greater
* HTTPS server for serving updates (see [App Transport Security](http://sparkle-project.org/documentation/app-transport-security/))
## API
@@ -48,7 +44,10 @@ If you are adding a symbol to the public API you must decorate the declaration w
Alternatively, build the Distribution scheme in the Xcode UI.
## Code of Conduct
We pledge to have an open and welcoming environment. See our [Code of Conduct](CODE_OF_CONDUCT.md).
## Project Sponsor
[Bandwidth Hog](https://www.bandwidthhog.com/?utm_source=sparkle-github&utm_medium=link&utm_campaign=readme-footer) is a service from MaxCDN
that allows you to push software updates to your customers for only 1¢ a gigabyte. Best part is there are no contracts, it is all Pay-as-you-Go.
[StackPath](https://www.stackpath.com/?utm_source=sparkle-github&utm_medium=link&utm_campaign=readme-footer)
Binary file not shown.
@@ -43,18 +43,21 @@
"scale" : "1x"
},
{
"idiom" : "mac",
"size" : "256x256",
"idiom" : "mac",
"filename" : "icon_256x256@2x.png",
"scale" : "2x"
},
{
"idiom" : "mac",
"size" : "512x512",
"idiom" : "mac",
"filename" : "icon_512x512.png",
"scale" : "1x"
},
{
"idiom" : "mac",
"size" : "512x512",
"idiom" : "mac",
"filename" : "icon_512x512@2x.png",
"scale" : "2x"
}
],
Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 37 KiB

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 754 B

After

Width:  |  Height:  |  Size: 827 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 KiB

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 37 KiB

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 130 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 KiB

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.9 KiB

After

Width:  |  Height:  |  Size: 5.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 130 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 368 KiB

-1
View File
@@ -2,7 +2,6 @@
<rss version="2.0" xmlns:sparkle="http://www.andymatuschak.org/xml-namespaces/sparkle" xmlns:dc="http://purl.org/dc/elements/1.1/">
<channel>
<title>Your Great App's Changelog</title>
<link>http://you.com/app/appcast.xml</link>
<description>Most recent changes with links to updates.</description>
<language>en</language>
<item>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

After

Width:  |  Height:  |  Size: 228 KiB

Binary file not shown.
Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

+7 -6
View File
@@ -1,7 +1,7 @@
Pod::Spec.new do |s|
s.name = "Sparkle"
s.version = "1.11.1"
s.summary = "A software update framework for OS X"
s.version = "1.16.0"
s.summary = "A software update framework for macOS"
s.description = "Sparkle is an easy-to-use software update framework for Cocoa developers."
s.homepage = "http://sparkle-project.org"
s.documentation_url = "http://sparkle-project.org/documentation/"
@@ -11,15 +11,16 @@ Pod::Spec.new do |s|
:file => 'LICENSE'
}
s.authors = {
'Andy Matuschak' => 'andy@andymatuschak.org',
'Kornel Lesiński' => 'pornel@pornel.net',
'C.W. Betts' => 'computers57@hotmail.com',
'Jake Petroules' => 'jake.petroules@petroules.com',
'Mayur Pawashe' => 'zorgiepoo@gmail.com',
'Kornel Lesiński' => 'pornel@pornel.net',
'Jake Petroules' => 'jake.petroules@petroules.com',
'C.W. Betts' => 'computers57@hotmail.com',
'Andy Matuschak' => 'andy@andymatuschak.org',
}
s.platform = :osx, '10.7'
s.source = { :http => "https://github.com/sparkle-project/Sparkle/releases/download/#{s.version}/Sparkle-#{s.version}.tar.bz2" }
s.source_files = 'Sparkle.framework/Versions/A/Headers/*.h'
s.public_header_files = 'Sparkle.framework/Versions/A/Headers/*.h'
s.vendored_frameworks = 'Sparkle.framework'
File diff suppressed because it is too large. Load diff
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0710"
LastUpgradeVersion = "0800"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0710"
LastUpgradeVersion = "0800"
version = "2.0">
<BuildAction
parallelizeBuildables = "YES"
@@ -0,0 +1,56 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0800"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "726B2B5C1C645FC900388755"
BuildableName = "UI Tests.xctest"
BlueprintName = "UI Tests"
ReferencedContainer = "container:Sparkle.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
+20
View File
@@ -0,0 +1,20 @@
//
// AppKitPrevention.h
// Sparkle
//
// Created by Mayur Pawashe on 1/17/17.
// Copyright © 2017 Sparkle Project. All rights reserved.
//
// #include (not #import) this header to prevent AppKit from being imported
// Note this should be your LAST #include in your implementation file
// If this error is triggered, you can have Xcode indicate to you which source file including this header caused the issue
// One may wonder for certain targets where AppKit is banned completely, why just not link AppKit instead.
// Well, Xcode has thing called auto-linking that I don't trust very much.
// Even after trying to disable the setting, I've had targets able to link to AppKit without AppKit being specified in the list of linked libraries.
#ifdef _APPKITDEFINES_H
#error This is a core or daemon-safe module and should NOT import AppKit
#endif
+2
View File
@@ -28,5 +28,7 @@
<string>MainMenu</string>
<key>NSPrincipalClass</key>
<string>NSApplication</string>
<key>CFBundleIconFile</key>
<string>${ASSETCATALOG_COMPILER_APPICON_NAME}.icns</string>
</dict>
</plist>
+72 -35
View File
@@ -1,9 +1,12 @@
#import <AppKit/AppKit.h>
#import <Cocoa/Cocoa.h>
#import "SULocalizations.h"
#import "SUErrors.h"
#import "SUInstaller.h"
#import "SUHost.h"
#import "SUStandardVersionComparator.h"
#import "SUStatusController.h"
#import "SULog.h"
#import "SUInstallerProtocol.h"
#include <unistd.h>
@@ -152,13 +155,35 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.5;
}];
}
- (void)showError:(NSError *)error
{
if (self.shouldShowUI) {
NSAlert *alert = [[NSAlert alloc] init];
alert.messageText = @"";
alert.informativeText = [NSString stringWithFormat:@"%@", [error localizedDescription]];
[alert runModal];
}
}
- (void)install
{
NSBundle *theBundle = [NSBundle bundleWithPath:self.hostPath];
SUHost *host = [[SUHost alloc] initWithBundle:theBundle];
NSString *installationPath = [[host installationPath] copy];
if (self.shouldShowUI) {
NSString *fileOperationToolPath = [[[[NSBundle mainBundle] executablePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@""SPARKLE_FILEOP_TOOL_NAME];
if (![[NSFileManager defaultManager] fileExistsAtPath:fileOperationToolPath]) {
SULog(@"Potential Installation Error: File operation tool path %@ is not found", fileOperationToolPath);
}
NSError *retrieveInstallerError = nil;
id<SUInstallerProtocol> installer = [SUInstaller installerForHost:host fileOperationToolPath:fileOperationToolPath updateDirectory:self.updateFolderPath error:&retrieveInstallerError];
if (installer == nil) {
SULog(@"Retrieved Installer Error: %@", retrieveInstallerError);
exit(EXIT_FAILURE);
}
if (self.shouldShowUI && [installer canInstallSilently]) {
self.statusController = [[SUStatusController alloc] initWithHost:host];
[self.statusController setButtonTitle:SULocalizedString(@"Cancel Update", @"") target:nil action:Nil isDefault:NO];
[self.statusController beginActionWithTitle:SULocalizedString(@"Installing update...", @"")
@@ -166,32 +191,44 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.5;
[self.statusController showWindow:self];
}
[SUInstaller installFromUpdateFolder:self.updateFolderPath
overHost:host
installationPath:installationPath
versionComparator:[SUStandardVersionComparator defaultComparator]
completionHandler:^(NSError *error) {
if (error) {
SULog(@"Installation Error: %@", error);
if (self.shouldShowUI) {
NSAlert *alert = [[NSAlert alloc] init];
alert.messageText = @"";
alert.informativeText = [NSString stringWithFormat:@"%@", [error localizedDescription]];
[alert runModal];
}
exit(EXIT_FAILURE);
} else {
NSString *pathToRelaunch = nil;
// If the installation path differs from the host path, we give higher precedence for it than
// if the desired relaunch path differs from the host path
if (![installationPath.pathComponents isEqualToArray:self.hostPath.pathComponents] || [self.relaunchPath.pathComponents isEqualToArray:self.hostPath.pathComponents]) {
pathToRelaunch = installationPath;
} else {
pathToRelaunch = self.relaunchPath;
}
[self cleanupAndTerminateWithPathToRelaunch:pathToRelaunch];
}
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSError *initialInstallationError = nil;
if (![installer performInitialInstallation:&initialInstallationError]) {
SULog(@"Failed to perform initial installation with error: %@", initialInstallationError);
dispatch_async(dispatch_get_main_queue(), ^{
[self showError:initialInstallationError];
exit(EXIT_FAILURE);
});
return;
}
NSError *finalInstallationError = nil;
if (![installer performFinalInstallation:&finalInstallationError]) {
NSError *underlyingError = [finalInstallationError.userInfo objectForKey:NSUnderlyingErrorKey];
dispatch_async(dispatch_get_main_queue(), ^{
if (underlyingError == nil || underlyingError.code != SUInstallationCancelledError) {
SULog(@"Failed to perform final installation Error: %@", finalInstallationError);
[self showError:finalInstallationError];
}
exit(EXIT_FAILURE);
});
return;
}
NSString *installationPath = [installer installationPath];
dispatch_async(dispatch_get_main_queue(), ^{
NSString *pathToRelaunch = nil;
// If the relaunch path is the same as the host bundle path, use the installation path from the installer which may be normalized
// Otherwise use the requested relaunch path in all other cases
if ([self.relaunchPath.pathComponents isEqualToArray:host.bundlePath.pathComponents]) {
pathToRelaunch = installationPath;
} else {
pathToRelaunch = self.relaunchPath;
}
[self cleanupAndTerminateWithPathToRelaunch:pathToRelaunch];
});
});
}
- (void)cleanupAndTerminateWithPathToRelaunch:(NSString *)relaunchPath
@@ -247,16 +284,16 @@ int main(int __unused argc, const char __unused *argv[])
NSApplication *application = [NSApplication sharedApplication];
BOOL shouldShowUI = (args.count > 6) ? [args[6] boolValue] : YES;
BOOL shouldShowUI = (args.count > 6) ? [[args objectAtIndex:6] boolValue] : YES;
if (shouldShowUI) {
[application activateIgnoringOtherApps:YES];
}
AppInstaller *appInstaller = [[AppInstaller alloc] initWithHostPath:args[1]
relaunchPath:args[2]
parentProcessId:[args[3] intValue]
updateFolderPath:args[4]
shouldRelaunch:(args.count > 5) ? [args[5] boolValue] : YES
AppInstaller *appInstaller = [[AppInstaller alloc] initWithHostPath:[args objectAtIndex:1]
relaunchPath:[args objectAtIndex:2]
parentProcessId:[[args objectAtIndex:3] intValue]
updateFolderPath:[args objectAtIndex:4]
shouldRelaunch:(args.count > 5) ? [[args objectAtIndex:5] boolValue] : YES
shouldShowUI:shouldShowUI];
[application setDelegate:appInstaller];
[application run];
+10 -10
View File
@@ -3,7 +3,7 @@
import Foundation
func die(msg: String) {
println("ERROR: \(msg)")
print("ERROR: \(msg)")
exit(1)
}
@@ -28,8 +28,8 @@ if enStringsDict == nil {
}
let enStringsDictKeys = enStringsDict!.allKeys
let dirPath = sparkleRoot! + "/Sparkle"
let dirContents = NSFileManager.defaultManager().contentsOfDirectoryAtPath(dirPath, error: nil) as! [String]
let dirPath = NSString(string: sparkleRoot! + "/Sparkle")
let dirContents = try! NSFileManager.defaultManager().contentsOfDirectoryAtPath(dirPath as String)
let css =
"body { font-family: sans-serif; font-size: 10pt; }" +
"h1 { font-size: 12pt; }" +
@@ -51,14 +51,14 @@ head.addChild(NSXMLElement(name: "style", stringValue: css))
let locale = NSLocale.currentLocale()
for dirEntry in dirContents {
if dirEntry.pathExtension != "lproj" || dirEntry == "en.lproj" {
if NSString(string: dirEntry).pathExtension != "lproj" || dirEntry == "en.lproj" {
continue
}
let lang = locale.displayNameForKey(NSLocaleLanguageCode, value: dirEntry.stringByDeletingPathExtension)
let lang = locale.displayNameForKey(NSLocaleLanguageCode, value: NSString(string: dirEntry).stringByDeletingPathExtension)
body.addChild(NSXMLElement(name: "h1", stringValue: "\(dirEntry) (\(lang!))"))
let stringsPath = dirPath.stringByAppendingPathComponent(dirEntry).stringByAppendingPathComponent("Sparkle.strings")
let stringsPath = NSString(string: dirPath.stringByAppendingPathComponent(dirEntry)).stringByAppendingPathComponent("Sparkle.strings")
let stringsDict = NSDictionary(contentsOfFile: stringsPath)
if stringsDict == nil {
die("Invalid strings file \(dirEntry)")
@@ -90,12 +90,12 @@ for dirEntry in dirContents {
let sorter = { (s1: String, s2: String) -> Bool in
return s1 < s2
}
missing.sort(sorter)
unlocalized.sort(sorter)
unused.sort(sorter)
missing.sortInPlace(sorter)
unlocalized.sortInPlace(sorter)
unused.sortInPlace(sorter)
let addRow = { (prefix: String, cssClass: String, key: String) -> Void in
body.addChild(NSXMLElement(name: "span", attributes: ["class": cssClass], stringValue: " ".join([prefix, key]) + "\n"))
body.addChild(NSXMLElement(name: "span", attributes: ["class": cssClass], stringValue: [prefix, key].joinWithSeparator(" ") + "\n"))
}
for key in missing {
+18 -4
View File
@@ -9,18 +9,32 @@
#ifndef SUAPPCAST_H
#define SUAPPCAST_H
#if __has_feature(modules)
@import Foundation;
#else
#import <Foundation/Foundation.h>
#endif
#import "SUExport.h"
NS_ASSUME_NONNULL_BEGIN
@class SUAppcastItem;
SU_EXPORT @interface SUAppcast : NSObject<NSURLDownloadDelegate>
@property (copy) NSString *userAgentString;
@property (copy) NSDictionary *httpHeaders;
@property (copy, nullable) NSString *userAgentString;
- (void)fetchAppcastFromURL:(NSURL *)url completionBlock:(void (^)(NSError *))err;
#if __has_feature(objc_generics)
@property (copy, nullable) NSDictionary<NSString *, NSString *> *httpHeaders;
#else
@property (copy, nullable) NSDictionary *httpHeaders;
#endif
@property (readonly, copy) NSArray *items;
- (void)fetchAppcastFromURL:(NSURL *)url completionBlock:(void (^)(NSError *_Nullable))err;
- (SUAppcast *)copyWithoutDeltaUpdates;
@property (readonly, copy, nullable) NSArray *items;
@end
NS_ASSUME_NONNULL_END
#endif
+174 -136
View File
@@ -6,14 +6,14 @@
// Copyright 2006 Andy Matuschak. All rights reserved.
//
#import "SUUpdater.h"
#import "SUAppcast.h"
#import "SUAppcastItem.h"
#import "SUVersionComparisonProtocol.h"
#import "SUAppcast.h"
#import "SUConstants.h"
#import "SULog.h"
#import "SULocalizations.h"
#import "SUErrors.h"
#include "AppKitPrevention.h"
@interface NSXMLElement (SUAppcastExtensions)
@property (readonly, copy) NSDictionary *attributesAsDictionary;
@@ -30,7 +30,10 @@
if (!attrName) {
continue;
}
dictionary[attrName] = [attribute stringValue];
NSString *attributeStringValue = [attribute stringValue];
if (attributeStringValue != nil) {
[dictionary setObject:attributeStringValue forKey:attrName];
}
}
return dictionary;
}
@@ -65,7 +68,7 @@
if (self.httpHeaders) {
for (NSString *key in self.httpHeaders) {
id value = [self.httpHeaders objectForKey:key];
NSString *value = [self.httpHeaders objectForKey:key];
[request setValue:value forHTTPHeaderField:key];
}
}
@@ -93,147 +96,166 @@
- (void)downloadDidFinish:(NSURLDownload *)__unused aDownload
{
NSError *error = nil;
NSArray *appcastItems = [self parseAppcastItemsFromXMLFile:[NSURL fileURLWithPath:self.downloadFilename] error:&error];
NSXMLDocument *document = nil;
BOOL failed = NO;
NSArray *xmlItems = nil;
NSMutableArray *appcastItems = [NSMutableArray array];
[[NSFileManager defaultManager] removeItemAtPath:self.downloadFilename error:nil];
self.downloadFilename = nil;
if (self.downloadFilename)
{
NSUInteger options = 0;
options = NSXMLNodeLoadExternalEntitiesSameOriginOnly;
document = [[NSXMLDocument alloc] initWithContentsOfURL:[NSURL fileURLWithPath:self.downloadFilename] options:options error:&error];
[[NSFileManager defaultManager] removeItemAtPath:self.downloadFilename error:nil];
self.downloadFilename = nil;
}
else
{
failed = YES;
if (appcastItems) {
self.items = appcastItems;
self.completionBlock(nil);
self.completionBlock = nil;
} else {
NSMutableDictionary *userInfo = [NSMutableDictionary
dictionaryWithObject: SULocalizedString(@"An error occurred while parsing the update feed.", nil)
forKey: NSLocalizedDescriptionKey];
if (error) {
[userInfo setObject:error forKey:NSUnderlyingErrorKey];
}
[self reportError:[NSError errorWithDomain:SUSparkleErrorDomain
code:SUAppcastParseError
userInfo:userInfo]];
}
}
if (nil == document)
{
failed = YES;
}
else
{
xmlItems = [document nodesForXPath:@"/rss/channel/item" error:&error];
if (nil == xmlItems)
{
failed = YES;
- (NSDictionary *)attributesOfNode:(NSXMLElement *)node
{
NSEnumerator *attributeEnum = [[node attributes] objectEnumerator];
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
for (NSXMLNode *attribute in attributeEnum) {
NSString *attrName = [self sparkleNamespacedNameOfNode:attribute];
if (!attrName) {
continue;
}
NSString *stringValue = [attribute stringValue];
if (stringValue) {
[dictionary setObject:stringValue forKey:attrName];
}
}
return dictionary;
}
if (failed == NO)
{
-(NSString *)sparkleNamespacedNameOfNode:(NSXMLNode *)node {
// XML namespace prefix is semantically meaningless, so compare namespace URI
// NS URI isn't used to fetch anything, and must match exactly, so we look for http:// not https://
if ([[node URI] isEqualToString:@"http://www.andymatuschak.org/xml-namespaces/sparkle"]) {
NSString *localName = [node localName];
assert(localName);
return [@"sparkle:" stringByAppendingString:localName];
} else {
return [node name]; // Backwards compatibility
}
}
NSEnumerator *nodeEnum = [xmlItems objectEnumerator];
NSXMLNode *node;
-(NSArray *)parseAppcastItemsFromXMLFile:(NSURL *)appcastFile error:(NSError *__autoreleasing*)errorp {
if (errorp) {
*errorp = nil;
}
if (!appcastFile) {
return nil;
}
NSUInteger options = NSXMLNodeLoadExternalEntitiesNever; // Prevent inclusion from file://
NSXMLDocument *document = [[NSXMLDocument alloc] initWithContentsOfURL:appcastFile options:options error:errorp];
if (nil == document) {
return nil;
}
NSArray *xmlItems = [document nodesForXPath:@"/rss/channel/item" error:errorp];
if (nil == xmlItems) {
return nil;
}
NSMutableArray *appcastItems = [NSMutableArray array];
NSEnumerator *nodeEnum = [xmlItems objectEnumerator];
NSXMLNode *node;
while((node = [nodeEnum nextObject])) {
NSMutableDictionary *nodesDict = [NSMutableDictionary dictionary];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
while (failed == NO && (node = [nodeEnum nextObject]))
{
// First, we'll "index" all the first-level children of this appcast item so we can pick them out by language later.
if ([[node children] count])
{
node = [node childAtIndex:0];
while (nil != node)
{
NSString *name = [node name];
if (name)
{
NSMutableArray *nodes = nodesDict[name];
if (nodes == nil)
{
nodes = [NSMutableArray array];
nodesDict[name] = nodes;
}
[nodes addObject:node];
// First, we'll "index" all the first-level children of this appcast item so we can pick them out by language later.
if ([[node children] count]) {
node = [node childAtIndex:0];
while (nil != node) {
NSString *name = [self sparkleNamespacedNameOfNode:node];
if (name) {
NSMutableArray *nodes = [nodesDict objectForKey:name];
if (nodes == nil) {
nodes = [NSMutableArray array];
[nodesDict setObject:nodes forKey:name];
}
node = [node nextSibling];
[nodes addObject:node];
}
node = [node nextSibling];
}
}
for (NSString *name in nodesDict)
{
node = [self bestNodeInNodes:nodesDict[name]];
if ([name isEqualToString:SURSSElementEnclosure])
{
// enclosure is flattened as a separate dictionary for some reason
NSDictionary *encDict = [(NSXMLElement *)node attributesAsDictionary];
dict[name] = encDict;
}
else if ([name isEqualToString:SURSSElementPubDate])
{
// pubDate is expected to be an NSDate by SUAppcastItem, but the RSS class was returning an NSString
NSString *string = node.stringValue;
if (string) {
NSDate *date = [NSDate dateWithNaturalLanguageString:string];
if (date)
dict[name] = date;
}
}
else if ([name isEqualToString:SUAppcastElementDeltas])
{
NSMutableArray *deltas = [NSMutableArray array];
NSEnumerator *childEnum = [[node children] objectEnumerator];
for (NSXMLNode *child in childEnum) {
if ([[child name] isEqualToString:SURSSElementEnclosure])
[deltas addObject:[(NSXMLElement *)child attributesAsDictionary]];
}
dict[name] = deltas;
}
else if ([name isEqualToString:SUAppcastElementTags]) {
NSMutableArray *tags = [NSMutableArray array];
NSEnumerator *childEnum = [[node children] objectEnumerator];
for (NSXMLNode *child in childEnum) {
NSString *childName = child.name;
if (childName)
[tags addObject:childName];
}
dict[name] = tags;
}
else if (name != nil)
{
// add all other values as strings
NSString *theValue = [[node stringValue] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if (theValue != nil) {
dict[name] = theValue;
}
}
}
NSString *errString;
SUAppcastItem *anItem = [[SUAppcastItem alloc] initWithDictionary:dict failureReason:&errString];
if (anItem)
{
[appcastItems addObject:anItem];
for (NSString *name in nodesDict) {
node = [self bestNodeInNodes:[nodesDict objectForKey:name]];
if ([name isEqualToString:SURSSElementEnclosure]) {
// enclosure is flattened as a separate dictionary for some reason
NSDictionary *encDict = [self attributesOfNode:(NSXMLElement *)node];
[dict setObject:encDict forKey:name];
}
else
{
SULog(@"Sparkle Updater: Failed to parse appcast item: %@.\nAppcast dictionary was: %@", errString, dict);
else if ([name isEqualToString:SURSSElementPubDate]) {
// We don't want to parse and create a NSDate instance -
// that's a risk we can avoid. We don't use the date anywhere other
// than it being accessible from SUAppcastItem
NSString *dateString = node.stringValue;
if (dateString) {
[dict setObject:dateString forKey:name];
}
}
else if ([name isEqualToString:SUAppcastElementDeltas]) {
NSMutableArray *deltas = [NSMutableArray array];
NSEnumerator *childEnum = [[node children] objectEnumerator];
for (NSXMLNode *child in childEnum) {
if ([[child name] isEqualToString:SURSSElementEnclosure]) {
[deltas addObject:[self attributesOfNode:(NSXMLElement *)child]];
}
}
[dict setObject:deltas forKey:name];
}
else if ([name isEqualToString:SUAppcastElementTags]) {
NSMutableArray *tags = [NSMutableArray array];
NSEnumerator *childEnum = [[node children] objectEnumerator];
for (NSXMLNode *child in childEnum) {
NSString *childName = child.name;
if (childName) {
[tags addObject:childName];
}
}
[dict setObject:tags forKey:name];
}
[nodesDict removeAllObjects];
[dict removeAllObjects];
else if (name != nil) {
// add all other values as strings
NSString *theValue = [[node stringValue] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if (theValue != nil) {
[dict setObject:theValue forKey:name];
}
}
}
NSString *errString;
SUAppcastItem *anItem = [[SUAppcastItem alloc] initWithDictionary:dict failureReason:&errString];
if (anItem) {
[appcastItems addObject:anItem];
}
else {
SULog(@"Sparkle Updater: Failed to parse appcast item: %@.\nAppcast dictionary was: %@", errString, dict);
if (errorp) *errorp = [NSError errorWithDomain:SUSparkleErrorDomain
code:SUAppcastParseError
userInfo:@{NSLocalizedDescriptionKey: errString}];
return nil;
}
}
self.items = appcastItems;
if ([appcastItems count]) {
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:NO];
[appcastItems sortUsingDescriptors:@[sort]];
self.items = appcastItems;
}
if (failed) {
[self reportError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUAppcastParseError userInfo:@{ NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while parsing the update feed.", nil) }]];
} else {
self.completionBlock(nil);
self.completionBlock = nil;
}
return appcastItems;
}
- (void)download:(NSURLDownload *)__unused aDownload didFailWithError:(NSError *)error
@@ -253,14 +275,18 @@
- (void)reportError:(NSError *)error
{
NSURL *failingUrl = error.userInfo[NSURLErrorFailingURLErrorKey];
self.completionBlock([NSError errorWithDomain:SUSparkleErrorDomain code:SUAppcastError userInfo:@{
NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:@{
NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred in retrieving update information. Please try again later.", nil),
NSLocalizedFailureReasonErrorKey: [error localizedDescription],
NSUnderlyingErrorKey: error,
NSURLErrorFailingURLErrorKey: failingUrl ? failingUrl : [NSNull null],
}]);
}];
NSURL *failingUrl = [error.userInfo objectForKey:NSURLErrorFailingURLErrorKey];
if (failingUrl) {
[userInfo setObject:failingUrl forKey:NSURLErrorFailingURLErrorKey];
}
self.completionBlock([NSError errorWithDomain:SUSparkleErrorDomain code:SUAppcastError userInfo:userInfo]);
self.completionBlock = nil;
}
@@ -268,7 +294,7 @@
{
// We use this method to pick out the localized version of a node when one's available.
if ([nodes count] == 1)
return nodes[0];
return [nodes objectAtIndex:0];
else if ([nodes count] == 0)
return nil;
@@ -279,12 +305,24 @@
lang = [[node attributeForName:@"xml:lang"] stringValue];
[languages addObject:(lang ? lang : @"")];
}
lang = [NSBundle preferredLocalizationsFromArray:languages][0];
lang = [[NSBundle preferredLocalizationsFromArray:languages] objectAtIndex:0];
i = [languages indexOfObject:([languages containsObject:lang] ? lang : @"")];
if (i == NSNotFound) {
i = 0;
}
return nodes[i];
return [nodes objectAtIndex:i];
}
- (SUAppcast *)copyWithoutDeltaUpdates {
SUAppcast *other = [SUAppcast new];
NSMutableArray *nonDeltaItems = [NSMutableArray new];
for(SUAppcastItem *item in self.items) {
if (![item isDeltaUpdate]) [nonDeltaItems addObject:item];
}
other.items = nonDeltaItems;
return other;
}
@end
+6 -1
View File
@@ -9,18 +9,23 @@
#ifndef SUAPPCASTITEM_H
#define SUAPPCASTITEM_H
#if __has_feature(modules)
@import Foundation;
#else
#import <Foundation/Foundation.h>
#endif
#import "SUExport.h"
SU_EXPORT @interface SUAppcastItem : NSObject
@property (copy, readonly) NSString *title;
@property (copy, readonly) NSDate *date;
@property (copy, readonly) NSString *dateString;
@property (copy, readonly) NSString *itemDescription;
@property (strong, readonly) NSURL *releaseNotesURL;
@property (copy, readonly) NSString *DSASignature;
@property (copy, readonly) NSString *minimumSystemVersion;
@property (copy, readonly) NSString *maximumSystemVersion;
@property (strong, readonly) NSURL *fileURL;
@property (nonatomic, readonly) uint64_t contentLength;
@property (copy, readonly) NSString *versionString;
@property (copy, readonly) NSString *displayVersionString;
@property (copy, readonly) NSDictionary *deltaUpdates;
+47 -31
View File
@@ -6,17 +6,16 @@
// Copyright 2006 Andy Matuschak. All rights reserved.
//
#import "SUUpdater.h"
#import "SUAppcast.h"
#import "SUAppcastItem.h"
#import "SUVersionComparisonProtocol.h"
#import "SUAppcastItem.h"
#import "SULog.h"
#import "SUConstants.h"
#include "AppKitPrevention.h"
@interface SUAppcastItem ()
@property (copy, readwrite) NSString *title;
@property (copy, readwrite) NSDate *date;
@property (copy, readwrite) NSString *dateString;
@property (copy, readwrite) NSString *itemDescription;
@property (strong, readwrite) NSURL *releaseNotesURL;
@property (copy, readwrite) NSString *DSASignature;
@@ -31,11 +30,12 @@
@end
@implementation SUAppcastItem
@synthesize date;
@synthesize dateString;
@synthesize deltaUpdates;
@synthesize displayVersionString;
@synthesize DSASignature;
@synthesize fileURL;
@synthesize contentLength = _contentLength;
@synthesize infoURL;
@synthesize itemDescription;
@synthesize maximumSystemVersion;
@@ -47,12 +47,13 @@
- (BOOL)isDeltaUpdate
{
return self.propertiesDictionary[SURSSElementEnclosure][SUAppcastAttributeDeltaFrom] != nil;
NSDictionary *rssElementEnclosure = [self.propertiesDictionary objectForKey:SURSSElementEnclosure];
return [rssElementEnclosure objectForKey:SUAppcastAttributeDeltaFrom] != nil;
}
- (BOOL)isCriticalUpdate
{
return [self.propertiesDictionary[SUAppcastElementTags] containsObject:SUAppcastElementCriticalUpdate];
return [[self.propertiesDictionary objectForKey:SUAppcastElementTags] containsObject:SUAppcastElementCriticalUpdate];
}
- (BOOL)isInformationOnlyUpdate
@@ -69,7 +70,7 @@
{
self = [super init];
if (self) {
id enclosure = dict[SURSSElementEnclosure];
NSDictionary *enclosure = [dict objectForKey:SURSSElementEnclosure];
// Try to find a version string.
// Finding the new version number from the RSS feed is a little bit hacky. There are two ways:
@@ -79,17 +80,17 @@
// underscore and the last period as the version number. So name your packages like this: APPNAME_VERSION.extension.
// The big caveat with this is that you can't have underscores in your version strings, as that'll confuse Sparkle.
// Feel free to change the separator string to a hyphen or something more suited to your needs if you like.
NSString *newVersion = enclosure[SUAppcastAttributeVersion];
NSString *newVersion = [enclosure objectForKey:SUAppcastAttributeVersion];
if (newVersion == nil) {
newVersion = dict[SUAppcastAttributeVersion]; // Get version from the item, in case it's a download-less item (i.e. paid upgrade).
newVersion = [dict objectForKey:SUAppcastAttributeVersion]; // Get version from the item, in case it's a download-less item (i.e. paid upgrade).
}
if (newVersion == nil) // no sparkle:version attribute anywhere?
{
SULog(@"warning: <%@> for URL '%@' is missing %@ attribute. Version comparison may be unreliable. Please always specify %@", SURSSElementEnclosure, enclosure[SURSSAttributeURL], SUAppcastAttributeVersion, SUAppcastAttributeVersion);
SULog(@"warning: <%@> for URL '%@' is missing %@ attribute. Version comparison may be unreliable. Please always specify %@", SURSSElementEnclosure, [enclosure objectForKey:SURSSAttributeURL], SUAppcastAttributeVersion, SUAppcastAttributeVersion);
// Separate the url by underscores and take the last component, as that'll be closest to the end,
// then we remove the extension. Hopefully, this will be the version.
NSArray *fileComponents = [enclosure[SURSSAttributeURL] componentsSeparatedByString:@"_"];
NSArray *fileComponents = [[enclosure objectForKey:SURSSAttributeURL] componentsSeparatedByString:@"_"];
if ([fileComponents count] > 1) {
newVersion = [[fileComponents lastObject] stringByDeletingPathExtension];
}
@@ -103,11 +104,11 @@
}
propertiesDictionary = [[NSMutableDictionary alloc] initWithDictionary:dict];
self.title = dict[SURSSElementTitle];
self.date = dict[SURSSElementPubDate];
self.itemDescription = dict[SURSSElementDescription];
self.title = [dict objectForKey:SURSSElementTitle];
self.dateString = [dict objectForKey:SURSSElementPubDate];
self.itemDescription = [dict objectForKey:SURSSElementDescription];
NSString *theInfoURL = dict[SURSSElementLink];
NSString *theInfoURL = [dict objectForKey:SURSSElementLink];
if (theInfoURL) {
if (![theInfoURL isKindOfClass:[NSString class]]) {
SULog(@"%@ -%@ Info URL is not of valid type.", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
@@ -125,29 +126,39 @@
return nil;
}
NSString *enclosureURLString = enclosure[SURSSAttributeURL];
NSString *enclosureURLString = [enclosure objectForKey:SURSSAttributeURL];
if (!enclosureURLString && !theInfoURL) {
if (error) {
*error = @"Feed item's enclosure lacks URL";
}
return nil;
}
if (enclosureURLString) {
NSString *enclosureLengthString = [enclosure objectForKey:SURSSAttributeLength];
long long contentLength = 0;
if (enclosureLengthString != nil) {
contentLength = [enclosureLengthString longLongValue];
}
_contentLength = (contentLength > 0) ? (uint64_t)contentLength : 0;
}
if (enclosureURLString) {
NSString *fileURLString = [[enclosureURLString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// Sparkle used to always URL-encode, so for backwards compatibility spaces in URLs must be forgiven.
NSString *fileURLString = [enclosureURLString stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
self.fileURL = [NSURL URLWithString:fileURLString];
}
if (enclosure) {
self.DSASignature = enclosure[SUAppcastAttributeDSASignature];
self.DSASignature = [enclosure objectForKey:SUAppcastAttributeDSASignature];
}
self.versionString = newVersion;
self.minimumSystemVersion = dict[SUAppcastElementMinimumSystemVersion];
self.maximumSystemVersion = dict[SUAppcastElementMaximumSystemVersion];
self.minimumSystemVersion = [dict objectForKey:SUAppcastElementMinimumSystemVersion];
self.maximumSystemVersion = [dict objectForKey:SUAppcastElementMaximumSystemVersion];
NSString *shortVersionString = enclosure[SUAppcastAttributeShortVersionString];
NSString *shortVersionString = [enclosure objectForKey:SUAppcastAttributeShortVersionString];
if (nil == shortVersionString) {
shortVersionString = dict[SUAppcastAttributeShortVersionString]; // fall back on the <item>
shortVersionString = [dict objectForKey:SUAppcastAttributeShortVersionString]; // fall back on the <item>
}
if (shortVersionString) {
@@ -157,28 +168,33 @@
}
// Find the appropriate release notes URL.
NSString *releaseNotesString = dict[SUAppcastElementReleaseNotesLink];
NSString *releaseNotesString = [dict objectForKey:SUAppcastElementReleaseNotesLink];
if (releaseNotesString) {
self.releaseNotesURL = [NSURL URLWithString:releaseNotesString];
NSURL *url = [NSURL URLWithString:releaseNotesString];
if ([url isFileURL]) {
SULog(@"Release notes with file:// URLs are not supported");
} else {
self.releaseNotesURL = url;
}
} else if ([self.itemDescription hasPrefix:@"http://"] || [self.itemDescription hasPrefix:@"https://"]) { // if the description starts with http:// or https:// use that.
self.releaseNotesURL = [NSURL URLWithString:self.itemDescription];
} else {
self.releaseNotesURL = nil;
}
NSArray *deltaDictionaries = dict[SUAppcastElementDeltas];
NSArray *deltaDictionaries = [dict objectForKey:SUAppcastElementDeltas];
if (deltaDictionaries) {
NSMutableDictionary *deltas = [NSMutableDictionary dictionary];
for (NSDictionary *deltaDictionary in deltaDictionaries) {
NSString *deltaFrom = deltaDictionary[SUAppcastAttributeDeltaFrom];
NSString *deltaFrom = [deltaDictionary objectForKey:SUAppcastAttributeDeltaFrom];
if (!deltaFrom) continue;
NSMutableDictionary *fakeAppCastDict = [dict mutableCopy];
[fakeAppCastDict removeObjectForKey:SUAppcastElementDeltas];
fakeAppCastDict[SURSSElementEnclosure] = deltaDictionary;
[fakeAppCastDict setObject:deltaDictionary forKey:SURSSElementEnclosure];
SUAppcastItem *deltaItem = [[SUAppcastItem alloc] initWithDictionary:fakeAppCastDict];
deltas[deltaFrom] = deltaItem;
[deltas setObject:deltaItem forKey:deltaFrom];
}
self.deltaUpdates = deltas;
}
+21
View File
@@ -0,0 +1,21 @@
//
// SUApplicationInfo.h
// Sparkle
//
// Created by Mayur Pawashe on 2/28/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import <Cocoa/Cocoa.h>
NS_ASSUME_NONNULL_BEGIN
@interface SUApplicationInfo : NSObject
+ (BOOL)isBackgroundApplication:(NSApplication *)application;
+ (NSImage *)bestIconForBundle:(NSBundle *)bundle;
@end
NS_ASSUME_NONNULL_END
+36
View File
@@ -0,0 +1,36 @@
//
// SUApplicationInfo.m
// Sparkle
//
// Created by Mayur Pawashe on 2/28/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import "SUApplicationInfo.h"
#import "SUBundleIcon.h"
@implementation SUApplicationInfo
+ (BOOL)isBackgroundApplication:(NSApplication *)application
{
return (application.activationPolicy == NSApplicationActivationPolicyAccessory);
}
+ (NSImage *)bestIconForBundle:(NSBundle *)bundle
{
NSURL *iconURL = [SUBundleIcon iconURLForBundle:bundle];
NSImage *icon = (iconURL == nil) ? nil : [[NSImage alloc] initWithContentsOfURL:iconURL];
// Use a default icon if none is defined.
if (!icon) {
// this asumption may not be correct (eg. even though we're not the main bundle, it could be still be a regular app)
// but still better than nothing if no icon was included
BOOL isMainBundle = (bundle == [NSBundle mainBundle]);
NSString *fileType = isMainBundle ? (__bridge NSString *)kUTTypeApplication : (__bridge NSString *)kUTTypeBundle;
icon = [[NSWorkspace sharedWorkspace] iconForFileType:fileType];
}
return icon;
}
@end
+2 -2
View File
@@ -9,7 +9,7 @@
#ifndef SUAUTOMATICUPDATEALERT_H
#define SUAUTOMATICUPDATEALERT_H
#import "SUWindowController.h"
#import <Cocoa/Cocoa.h>
typedef NS_ENUM(NSInteger, SUAutomaticInstallationChoice) {
SUInstallNowChoice,
@@ -18,7 +18,7 @@ typedef NS_ENUM(NSInteger, SUAutomaticInstallationChoice) {
};
@class SUAppcastItem, SUHost;
@interface SUAutomaticUpdateAlert : SUWindowController
@interface SUAutomaticUpdateAlert : NSWindowController
- (instancetype)initWithAppcastItem:(SUAppcastItem *)item host:(SUHost *)hostBundle completionBlock:(void (^)(SUAutomaticInstallationChoice))c;
- (IBAction)installNow:sender;
+5 -3
View File
@@ -7,7 +7,9 @@
//
#import "SUAutomaticUpdateAlert.h"
#import "SULocalizations.h"
#import "SUAppcastItem.h"
#import "SUApplicationInfo.h"
#import "SUHost.h"
@interface SUAutomaticUpdateAlert ()
@@ -34,7 +36,7 @@
return self;
}
- (NSString *__nonnull)description { return [NSString stringWithFormat:@"%@ <%@, %@>", [self class], [self.host bundlePath], [self.host installationPath]]; }
- (NSString *__nonnull)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], [self.host bundlePath]]; }
- (IBAction)installNow:(id)__unused sender
{
@@ -59,7 +61,7 @@
- (NSImage *__nonnull)applicationIcon
{
return [self.host icon];
return [SUApplicationInfo bestIconForBundle:self.host.bundle];
}
- (NSString *__nonnull)titleText
+1 -3
View File
@@ -9,11 +9,9 @@
#ifndef SUAUTOMATICUPDATEDRIVER_H
#define SUAUTOMATICUPDATEDRIVER_H
#import <Cocoa/Cocoa.h>
#import "SUBasicUpdateDriver.h"
#import "SUAutomaticUpdateAlert.h"
@interface SUAutomaticUpdateDriver : SUBasicUpdateDriver <SUUnarchiverDelegate>
@interface SUAutomaticUpdateDriver : SUBasicUpdateDriver
@end
+49 -9
View File
@@ -7,10 +7,15 @@
//
#import "SUAutomaticUpdateDriver.h"
#import "SUUpdaterPrivate.h"
#import "SUUpdaterDelegate.h"
#import "SULocalizations.h"
#import "SUErrors.h"
#import "SUAutomaticUpdateAlert.h"
#import "SUHost.h"
#import "SUConstants.h"
#import "SUAppcastItem.h"
#import "SUApplicationInfo.h"
// If the user hasn't quit in a week, ask them if they want to relaunch to get the latest bits. It doesn't matter that this measure of "one day" is imprecise.
static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 24 * 7;
@@ -26,6 +31,7 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
@property (assign) BOOL postponingInstallation;
@property (assign) BOOL showErrors;
@property (assign) BOOL willUpdateOnTermination;
@property (assign) BOOL isTerminating;
@property (strong) SUAutomaticUpdateAlert *alert;
@property (strong) NSTimer *showUpdateAlertTimer;
@@ -36,12 +42,19 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
@synthesize postponingInstallation;
@synthesize showErrors;
@synthesize willUpdateOnTermination;
@synthesize isTerminating;
@synthesize alert;
@synthesize showUpdateAlertTimer;
- (void)showUpdateAlert
{
self.interruptible = NO;
[self invalidateShowUpdateAlertTimer];
if (self.alert) {
[self.alert close];
}
self.alert = [[SUAutomaticUpdateAlert alloc] initWithAppcastItem:self.updateItem host:self.host completionBlock:^(SUAutomaticInstallationChoice choice) {
[self automaticUpdateAlertFinishedWithChoice:choice];
}];
@@ -49,7 +62,7 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
// If the app is a menubar app or the like, we need to focus it first and alter the
// update prompt to behave like a normal window. Otherwise if the window were hidden
// there may be no way for the application to be activated to make it visible again.
if ([self.host isBackgroundApplication]) {
if ([SUApplicationInfo isBackgroundApplication:[NSApplication sharedApplication]]) {
[[self.alert window] setHidesOnDeactivate:NO];
[NSApp activateIgnoringOtherApps:YES];
}
@@ -60,7 +73,7 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:) name:NSApplicationDidBecomeActiveNotification object:NSApp];
}
- (void)unarchiverDidFinish:(SUUnarchiver *)__unused ua
- (void)unarchiverDidFinish:(id)__unused ua
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:) name:NSApplicationWillTerminateNotification object:nil];
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(systemWillPowerOff:) name:NSWorkspaceWillPowerOffNotification object:nil];
@@ -71,7 +84,8 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
self.willUpdateOnTermination = YES;
id<SUUpdaterDelegate> updaterDelegate = [self.updater delegate];
id<SUUpdaterPrivate> updater = self.updater;
id<SUUpdaterDelegate> updaterDelegate = [updater delegate];
if ([updaterDelegate respondsToSelector:@selector(updater:willInstallUpdateOnQuit:immediateInstallationInvocation:)])
{
BOOL relaunch = YES;
@@ -81,7 +95,7 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
[invocation setArgument:&relaunch atIndex:2];
[invocation setArgument:&showUI atIndex:3];
[invocation setTarget:self];
[updaterDelegate updater:self.updater willInstallUpdateOnQuit:self.updateItem immediateInstallationInvocation:invocation];
}
@@ -99,6 +113,14 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
}
}
-(BOOL)resumeUpdateInteractively {
if ([self isInterruptible]) {
[self showUpdateAlert];
return YES;
}
return NO;
}
- (void)stopUpdatingOnTermination
{
if (self.willUpdateOnTermination)
@@ -111,7 +133,8 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
self.willUpdateOnTermination = NO;
id<SUUpdaterDelegate> updaterDelegate = [self.updater delegate];
id<SUUpdaterPrivate> updater = self.updater;
id<SUUpdaterDelegate> updaterDelegate = [updater delegate];
if ([updaterDelegate respondsToSelector:@selector(updater:didCancelInstallUpdateOnQuit:)])
[updaterDelegate updater:self.updater didCancelInstallUpdateOnQuit:self.updateItem];
}
@@ -131,6 +154,9 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
- (void)abortUpdate
{
[self.alert close];
self.isTerminating = NO;
[self stopUpdatingOnTermination];
[self invalidateShowUpdateAlertTimer];
[super abortUpdate];
@@ -144,6 +170,7 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
- (void)automaticUpdateAlertFinishedWithChoice:(SUAutomaticInstallationChoice)choice
{
self.alert = nil;
switch (choice)
{
case SUInstallNowChoice:
@@ -153,8 +180,6 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
case SUInstallLaterChoice:
self.postponingInstallation = YES;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:) name:NSApplicationWillTerminateNotification object:nil];
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(systemWillPowerOff:) name:NSWorkspaceWillPowerOffNotification object:nil];
// We're already waiting on quit, just indicate that we're idle.
self.interruptible = YES;
break;
@@ -166,6 +191,7 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
}
}
- (void)installWithToolAndRelaunch:(BOOL)relaunch displayingUserInterface:(BOOL)showUI
{
if (relaunch) {
@@ -185,9 +211,22 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
- (void)applicationWillTerminate:(NSNotification *)__unused note
{
// We don't want to terminate the app if the user or someone else initiated a termination
// Use a property instead of passing an argument to installWithToolAndRelaunch:
// because we give the delegate an invocation to our install methods and
// this code was added later :|
self.isTerminating = YES;
[self installWithToolAndRelaunch:NO];
}
- (void)terminateApp
{
if (!self.isTerminating) {
[super terminateApp];
}
}
- (void)abortUpdateWithError:(NSError *)error
{
if (self.showErrors) {
@@ -195,7 +234,8 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
} else {
// Call delegate separately here because otherwise it won't know we stopped.
// Normally this gets called by the superclass
id<SUUpdaterDelegate> updaterDelegate = [self.updater delegate];
id<SUUpdaterPrivate> updater = self.updater;
id<SUUpdaterDelegate> updaterDelegate = [updater delegate];
if ([updaterDelegate respondsToSelector:@selector(updater:didAbortWithError:)]) {
[updaterDelegate updater:self.updater didAbortWithError:error];
}
+7 -8
View File
@@ -9,13 +9,10 @@
#ifndef SUBASICUPDATEDRIVER_H
#define SUBASICUPDATEDRIVER_H
#import <Cocoa/Cocoa.h>
#import "SUUpdateDriver.h"
#import "SUUnarchiver.h"
#import "SUAppcast.h"
@class SUAppcastItem, SUHost;
@interface SUBasicUpdateDriver : SUUpdateDriver <NSURLDownloadDelegate, SUUnarchiverDelegate>
@class SUAppcast, SUAppcastItem, SUHost;
@interface SUBasicUpdateDriver : SUUpdateDriver <NSURLDownloadDelegate>
@property (strong, readonly) SUAppcastItem *updateItem;
@property (strong, readonly) NSURLDownload *download;
@@ -24,7 +21,7 @@
- (void)checkForUpdatesAtURL:(NSURL *)URL host:(SUHost *)host;
- (BOOL)isItemNewer:(SUAppcastItem *)ui;
- (BOOL)hostSupportsItem:(SUAppcastItem *)ui;
+ (BOOL)hostSupportsItem:(SUAppcastItem *)ui;
- (BOOL)itemContainsSkippedVersion:(SUAppcastItem *)ui;
- (BOOL)itemContainsValidUpdate:(SUAppcastItem *)ui;
- (void)appcastDidFinishLoading:(SUAppcast *)ac;
@@ -37,10 +34,12 @@
- (void)download:(NSURLDownload *)download didFailWithError:(NSError *)error;
- (void)extractUpdate;
- (void)unarchiverDidFinish:(SUUnarchiver *)ua;
- (void)unarchiverDidFail:(SUUnarchiver *)ua;
- (void)failedToApplyDeltaUpdate;
// Needed to preserve compatibility to subclasses, even though our unarchiver code uses blocks now
- (void)unarchiver:(id)ua extractedProgress:(double)progress;
- (void)unarchiverDidFinish:(id)ua;
- (void)installWithToolAndRelaunch:(BOOL)relaunch;
- (void)installWithToolAndRelaunch:(BOOL)relaunch displayingUserInterface:(BOOL)showUI;
- (void)installerForHost:(SUHost *)host failedWithError:(NSError *)error;
+230 -172
View File
@@ -8,18 +8,22 @@
#import "SUBasicUpdateDriver.h"
#import "SUUnarchiverProtocol.h"
#import "SUHost.h"
#import "SUOperatingSystem.h"
#import "SUDSAVerifier.h"
#import "SUInstaller.h"
#import "SUStandardVersionComparator.h"
#import "SUUnarchiver.h"
#import "SUConstants.h"
#import "SULog.h"
#import "SUBinaryDeltaCommon.h"
#import "SUCodeSigningVerifier.h"
#import "SUUpdater_Private.h"
#import "SUUpdaterPrivate.h"
#import "SUUpdaterDelegate.h"
#import "SUFileManager.h"
#import "SUUpdateValidator.h"
#import "SULocalizations.h"
#import "SUErrors.h"
#import "SUAppcast.h"
#import "SUAppcastItem.h"
@interface SUBasicUpdateDriver ()
@@ -31,6 +35,8 @@
@property (copy) NSString *tempDir;
@property (copy) NSString *relaunchPath;
@property (nonatomic) SUUpdateValidator *updateValidator;
@end
@implementation SUBasicUpdateDriver
@@ -43,6 +49,8 @@
@synthesize tempDir;
@synthesize relaunchPath;
@synthesize updateValidator = _updateValidator;
- (void)checkForUpdatesAtURL:(NSURL *)URL host:(SUHost *)aHost
{
[super checkForUpdatesAtURL:URL host:aHost];
@@ -54,8 +62,9 @@
SUAppcast *appcast = [[SUAppcast alloc] init];
[appcast setUserAgentString:[self.updater userAgentString]];
[appcast setHttpHeaders:[self.updater httpHeaders]];
id<SUUpdaterPrivate> updater = self.updater;
[appcast setUserAgentString:[updater userAgentString]];
[appcast setHttpHeaders:[updater httpHeaders]];
[appcast fetchAppcastFromURL:URL completionBlock:^(NSError *error) {
if (error) {
[self abortUpdateWithError:error];
@@ -68,44 +77,68 @@
- (id<SUVersionComparison>)versionComparator
{
id<SUVersionComparison> comparator = nil;
id<SUUpdaterPrivate> updater = self.updater;
// Give the delegate a chance to provide a custom version comparator
if ([[self.updater delegate] respondsToSelector:@selector(versionComparatorForUpdater:)]) {
comparator = [[self.updater delegate] versionComparatorForUpdater:self.updater];
if ([[updater delegate] respondsToSelector:@selector(versionComparatorForUpdater:)]) {
comparator = [[updater delegate] versionComparatorForUpdater:self.updater];
}
// If we don't get a comparator from the delegate, use the default comparator
if (!comparator) {
comparator = [SUStandardVersionComparator defaultComparator];
comparator = [[SUStandardVersionComparator alloc] init];
}
return comparator;
}
- (BOOL)isItemNewer:(SUAppcastItem *)ui
+ (SUAppcastItem *)bestItemFromAppcastItems:(NSArray *)appcastItems getDeltaItem:(SUAppcastItem * __autoreleasing *)deltaItem withHostVersion:(NSString *)hostVersion comparator:(id<SUVersionComparison>)comparator
{
return [[self versionComparator] compareVersion:[self.host version] toVersion:[ui versionString]] == NSOrderedAscending;
SUAppcastItem *item = nil;
for(SUAppcastItem *candidate in appcastItems) {
if ([[self class] hostSupportsItem:candidate]) {
if (!item || [comparator compareVersion:item.versionString toVersion:candidate.versionString] == NSOrderedAscending) {
item = candidate;
}
}
}
if (item && deltaItem) {
SUAppcastItem *deltaUpdateItem = [[item deltaUpdates] objectForKey:hostVersion];
if (deltaUpdateItem && [[self class] hostSupportsItem:deltaUpdateItem]) {
*deltaItem = deltaUpdateItem;
}
}
return item;
}
- (BOOL)hostSupportsItem:(SUAppcastItem *)ui
+ (BOOL)hostSupportsItem:(SUAppcastItem *)ui
{
if (([ui minimumSystemVersion] == nil || [[ui minimumSystemVersion] isEqualToString:@""]) &&
([ui maximumSystemVersion] == nil || [[ui maximumSystemVersion] isEqualToString:@""])) { return YES; }
BOOL minimumVersionOK = TRUE;
BOOL maximumVersionOK = TRUE;
id<SUVersionComparison> versionComparator = [[SUStandardVersionComparator alloc] init];
// Check minimum and maximum System Version
if ([ui minimumSystemVersion] != nil && ![[ui minimumSystemVersion] isEqualToString:@""]) {
minimumVersionOK = [[SUStandardVersionComparator defaultComparator] compareVersion:[ui minimumSystemVersion] toVersion:[SUOperatingSystem systemVersionString]] != NSOrderedDescending;
minimumVersionOK = [versionComparator compareVersion:[ui minimumSystemVersion] toVersion:[SUOperatingSystem systemVersionString]] != NSOrderedDescending;
}
if ([ui maximumSystemVersion] != nil && ![[ui maximumSystemVersion] isEqualToString:@""]) {
maximumVersionOK = [[SUStandardVersionComparator defaultComparator] compareVersion:[ui maximumSystemVersion] toVersion:[SUOperatingSystem systemVersionString]] != NSOrderedAscending;
maximumVersionOK = [versionComparator compareVersion:[ui maximumSystemVersion] toVersion:[SUOperatingSystem systemVersionString]] != NSOrderedAscending;
}
return minimumVersionOK && maximumVersionOK;
}
- (BOOL)isItemNewer:(SUAppcastItem *)ui
{
return [[self versionComparator] compareVersion:[self.host version] toVersion:[ui versionString]] == NSOrderedAscending;
}
- (BOOL)itemContainsSkippedVersion:(SUAppcastItem *)ui
{
NSString *skippedVersion = [self.host objectForUserDefaultsKey:SUSkippedVersionKey];
@@ -115,35 +148,40 @@
- (BOOL)itemContainsValidUpdate:(SUAppcastItem *)ui
{
return ui && [self hostSupportsItem:ui] && [self isItemNewer:ui] && ![self itemContainsSkippedVersion:ui];
return ui && [[self class] hostSupportsItem:ui] && [self isItemNewer:ui] && ![self itemContainsSkippedVersion:ui];
}
- (void)appcastDidFinishLoading:(SUAppcast *)ac
{
if ([[self.updater delegate] respondsToSelector:@selector(updater:didFinishLoadingAppcast:)]) {
[[self.updater delegate] updater:self.updater didFinishLoadingAppcast:ac];
id<SUUpdaterPrivate> updater = self.updater;
if ([[updater delegate] respondsToSelector:@selector(updater:didFinishLoadingAppcast:)]) {
[[updater delegate] updater:self.updater didFinishLoadingAppcast:ac];
}
NSDictionary *userInfo = (ac != nil) ? @{ SUUpdaterAppcastNotificationKey: ac } : nil;
NSDictionary *userInfo = @{ SUUpdaterAppcastNotificationKey: ac };
[[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterDidFinishLoadingAppCastNotification object:self.updater userInfo:userInfo];
SUAppcastItem *item = nil;
// Now we have to find the best valid update in the appcast.
if ([[self.updater delegate] respondsToSelector:@selector(bestValidUpdateInAppcast:forUpdater:)]) // Does the delegate want to handle it?
if ([[updater delegate] respondsToSelector:@selector(bestValidUpdateInAppcast:forUpdater:)]) // Does the delegate want to handle it?
{
item = [[self.updater delegate] bestValidUpdateInAppcast:ac forUpdater:self.updater];
}
else // If not, we'll take care of it ourselves.
item = [[updater delegate] bestValidUpdateInAppcast:ac forUpdater:self.updater];
}
if (item != nil) // Does the delegate want to handle it?
{
// Find the first update we can actually use.
NSEnumerator *updateEnumerator = [[ac items] objectEnumerator];
do {
item = [updateEnumerator nextObject];
} while (item && ![self hostSupportsItem:item]);
SUAppcastItem *deltaUpdateItem = [item deltaUpdates][[self.host version]];
if (deltaUpdateItem && [self hostSupportsItem:deltaUpdateItem]) {
if ([item isDeltaUpdate]) {
self.nonDeltaUpdateItem = [[updater delegate] bestValidUpdateInAppcast:[ac copyWithoutDeltaUpdates] forUpdater:self.updater];
}
}
else // If not, we'll take care of it ourselves.
{
// Find the best supported update
SUAppcastItem *deltaUpdateItem = nil;
item = [[self class] bestItemFromAppcastItems:ac.items getDeltaItem:&deltaUpdateItem withHostVersion:self.host.version comparator:[self versionComparator]];
if (item && deltaUpdateItem) {
self.nonDeltaUpdateItem = item;
item = deltaUpdateItem;
}
@@ -161,9 +199,11 @@
- (void)didFindValidUpdate
{
assert(self.updateItem);
id<SUUpdaterPrivate> updater = self.updater;
if ([[self.updater delegate] respondsToSelector:@selector(updater:didFindValidUpdate:)]) {
[[self.updater delegate] updater:self.updater didFindValidUpdate:self.updateItem];
if ([[updater delegate] respondsToSelector:@selector(updater:didFindValidUpdate:)]) {
[[updater delegate] updater:self.updater didFindValidUpdate:self.updateItem];
}
[[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterDidFindValidUpdateNotification
@@ -174,8 +214,10 @@
- (void)didNotFindUpdate
{
if ([[self.updater delegate] respondsToSelector:@selector(updaterDidNotFindUpdate:)]) {
[[self.updater delegate] updaterDidNotFindUpdate:self.updater];
id<SUUpdaterPrivate> updater = self.updater;
if ([[updater delegate] respondsToSelector:@selector(updaterDidNotFindUpdate:)]) {
[[updater delegate] updaterDidNotFindUpdate:self.updater];
}
[[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterDidNotFindUpdateNotification object:self.updater];
@@ -187,12 +229,42 @@
}]];
}
- (NSString *)appCachePath
{
NSArray *cachePaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachePath = nil;
if ([cachePaths count]) {
cachePath = [cachePaths objectAtIndex:0];
}
if (!cachePath) {
SULog(@"Failed to find user's cache directory! Using system default");
cachePath = NSTemporaryDirectory();
}
NSString *name = [self.host.bundle bundleIdentifier];
if (!name) {
name = [self.host name];
}
cachePath = [cachePath stringByAppendingPathComponent:name];
cachePath = [cachePath stringByAppendingPathComponent:@SPARKLE_BUNDLE_IDENTIFIER];
return cachePath;
}
- (void)downloadUpdate
{
// Clear cache directory so that downloads can't possibly accumulate inside
NSString *appCachePath = [self appCachePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:appCachePath]) {
[[NSFileManager defaultManager] removeItemAtPath:appCachePath error:NULL];
}
id<SUUpdaterPrivate> updater = self.updater;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[self.updateItem fileURL]];
[request setValue:[self.updater userAgentString] forHTTPHeaderField:@"User-Agent"];
if ([[self.updater delegate] respondsToSelector:@selector(updater:willDownloadUpdate:withRequest:)]) {
[[self.updater delegate] updater:self.updater
[request setValue:[updater userAgentString] forHTTPHeaderField:@"User-Agent"];
if ([[updater delegate] respondsToSelector:@selector(updater:willDownloadUpdate:withRequest:)]) {
[[updater delegate] updater:self.updater
willDownloadUpdate:self.updateItem
withRequest:request];
}
@@ -202,13 +274,14 @@
- (void)download:(NSURLDownload *)__unused d decideDestinationWithSuggestedFilename:(NSString *)name
{
NSString *downloadFileName = [NSString stringWithFormat:@"%@ %@", [self.host name], [self.updateItem versionString]];
self.tempDir = [self.host.appCachePath stringByAppendingPathComponent:downloadFileName];
NSString *appCachePath = [self appCachePath];
self.tempDir = [appCachePath stringByAppendingPathComponent:downloadFileName];
int cnt = 1;
while ([[NSFileManager defaultManager] fileExistsAtPath:self.tempDir] && cnt <= 999)
{
self.tempDir = [self.host.appCachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@ %d", downloadFileName, cnt++]];
self.tempDir = [appCachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@ %d", downloadFileName, cnt++]];
}
// Create the temporary directory if necessary.
@@ -224,87 +297,6 @@
[self.download setDestination:self.downloadPath allowOverwrite:YES];
}
/**
* If the update is a package, then it must be signed using DSA. No other verification is done.
*
* If the update is a bundle, then it must meet any one of:
*
* * old and new DSA public keys are the same and valid (it allows change of Code Signing identity), or
*
* * old and new Code Signing identity are the same and valid
*
*/
- (BOOL)validateUpdateDownloadedToPath:(NSString *)downloadedPath extractedToPath:(NSString *)extractedPath DSASignature:(NSString *)DSASignature publicDSAKey:(NSString *)publicDSAKey
{
BOOL isPackage = NO;
NSString *installSourcePath = [SUInstaller installSourcePathInUpdateFolder:extractedPath forHost:self.host isPackage:&isPackage isGuided:NULL];
if (installSourcePath == nil) {
SULog(@"No suitable install is found in the update. The update will be rejected.");
return NO;
}
// Modern packages are not distributed as bundles and are code signed differently than regular applications
if (isPackage) {
if (nil == publicDSAKey) {
SULog(@"The existing app bundle does not have a DSA key, so it can't verify installer packages.");
}
BOOL packageValidated = [SUDSAVerifier validatePath:downloadedPath withEncodedDSASignature:DSASignature withPublicDSAKey:publicDSAKey];
if (!packageValidated) {
SULog(@"DSA signature validation of the package failed. The update contains an installer package, and valid DSA signatures are mandatory for all installer packages. The update will be rejected. Sign the installer with a valid DSA key or use an .app bundle update instead.");
}
return packageValidated;
}
NSBundle *newBundle = [NSBundle bundleWithPath:installSourcePath];
if (newBundle == nil) {
SULog(@"No suitable bundle is found in the update. The update will be rejected.");
return NO;
}
SUHost *newHost = [[SUHost alloc] initWithBundle:newBundle];
NSString *newPublicDSAKey = newHost.publicDSAKey;
BOOL dsaKeysMatch = (publicDSAKey == nil || newPublicDSAKey == nil) ? NO : [publicDSAKey isEqualToString:newPublicDSAKey];
if (newPublicDSAKey != nil) {
if (![SUDSAVerifier validatePath:downloadedPath withEncodedDSASignature:DSASignature withPublicDSAKey:newPublicDSAKey]) {
SULog(@"DSA signature validation failed. The update has a public DSA key and is signed with a DSA key, but the %@ doesn't match the signature. The update will be rejected.",
dsaKeysMatch ? @"public key" : @"new public key shipped with the update");
return NO;
}
}
BOOL updateIsCodeSigned = [SUCodeSigningVerifier applicationAtPathIsCodeSigned:installSourcePath];
if (dsaKeysMatch) {
NSError *error = nil;
if (updateIsCodeSigned && ![SUCodeSigningVerifier codeSignatureIsValidAtPath:installSourcePath error:&error]) {
SULog(@"The update archive has a valid DSA signature, but the app is also signed with Code Signing, which is corrupted: %@. The update will be rejected.", error);
return NO;
}
} else {
BOOL hostIsCodeSigned = [SUCodeSigningVerifier hostApplicationIsCodeSigned];
NSString *dsaStatus = newPublicDSAKey ? @"has a new DSA key that doesn't match the previous one" : (publicDSAKey ? @"removes the DSA key" : @"isn't signed with a DSA key");
if (!hostIsCodeSigned || !updateIsCodeSigned) {
NSString *acsStatus = !hostIsCodeSigned ? @"old app hasn't been signed with app Code Signing" : @"new app isn't signed with app Code Signing";
SULog(@"The update archive %@, and the %@. At least one method of signature verification must be valid. The update will be rejected.", dsaStatus, acsStatus);
return NO;
}
NSError *error = nil;
if (![SUCodeSigningVerifier codeSignatureMatchesHostAndIsValidAtPath:installSourcePath error:&error]) {
SULog(@"The update archive %@, and the app is signed with a new Code Signing identity that doesn't match code signing of the original app: %@. At least one method of signature verification must be valid. The update will be rejected.", dsaStatus, error);
return NO;
}
}
return YES;
}
- (void)downloadDidFinish:(NSURLDownload *)__unused d
{
assert(self.updateItem);
@@ -314,22 +306,28 @@
- (void)download:(NSURLDownload *)__unused download didFailWithError:(NSError *)error
{
NSURL *failingUrl = error.userInfo[NSURLErrorFailingURLErrorKey];
NSURL *failingUrl = [error.userInfo objectForKey:NSURLErrorFailingURLErrorKey];
if (!failingUrl) {
failingUrl = [self.updateItem fileURL];
}
if ([[self.updater delegate] respondsToSelector:@selector(updater:failedToDownloadUpdate:error:)]) {
[[self.updater delegate] updater:self.updater
id<SUUpdaterPrivate> updater = self.updater;
if ([[updater delegate] respondsToSelector:@selector(updater:failedToDownloadUpdate:error:)]) {
[[updater delegate] updater:self.updater
failedToDownloadUpdate:self.updateItem
error:error];
}
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SURelaunchError userInfo:@{
NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:@{
NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while downloading the update. Please try again later.", nil),
NSUnderlyingErrorKey: error,
NSURLErrorFailingURLErrorKey: failingUrl ? failingUrl : [NSNull null],
}]];
}];
if (failingUrl) {
[userInfo setObject:failingUrl forKey:NSURLErrorFailingURLErrorKey];
}
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUDownloadError userInfo:userInfo]];
}
- (BOOL)download:(NSURLDownload *)__unused download shouldDecodeSourceDataOfMIMEType:(NSString *)encodingType
@@ -341,14 +339,38 @@
- (void)extractUpdate
{
SUUnarchiver *unarchiver = [SUUnarchiver unarchiverForPath:self.downloadPath updatingHostBundlePath:[[self.host bundle] bundlePath]];
id<SUUpdaterPrivate> updater = self.updater;
id<SUUnarchiverProtocol> unarchiver = [SUUnarchiver unarchiverForPath:self.downloadPath updatingHostBundlePath:self.host.bundlePath decryptionPassword:updater.decryptionPassword];
BOOL success;
if (!unarchiver) {
SULog(@"Error: No valid unarchiver for %@!", self.downloadPath);
[self unarchiverDidFail:nil];
return;
success = NO;
} else {
// Currently unsafe archives are the only case where we can prevalidate before extraction, but that could change in the future
BOOL needsPrevalidation = [[unarchiver class] unsafeIfArchiveIsNotValidated];
self.updateValidator = [[SUUpdateValidator alloc] initWithDownloadPath:self.downloadPath dsaSignature:self.updateItem.DSASignature host:self.host performingPrevalidation:needsPrevalidation];
success = self.updateValidator.canValidate;
}
if (!success) {
NSError *reason = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{NSLocalizedDescriptionKey: @"Failed to extract update."}];
[self unarchiverDidFailWithError:reason];
} else {
[unarchiver unarchiveWithCompletionBlock:^(NSError *err){
if (err) {
[self unarchiverDidFailWithError:err];
return;
}
[self unarchiverDidFinish:nil];
} progressBlock:^(double progress) {
[self unarchiver:nil extractedProgress:progress];
}];
}
unarchiver.delegate = self;
[unarchiver start];
}
- (void)failedToApplyDeltaUpdate
@@ -360,21 +382,30 @@
[self downloadUpdate];
}
- (void)unarchiverDidFinish:(SUUnarchiver *)__unused ua
// By default does nothing, can be overridden
- (void)unarchiver:(id)__unused ua extractedProgress:(double)__unused progress
{
}
// Note this method can be overridden (and is)
- (void)unarchiverDidFinish:(id)__unused ua
{
assert(self.updateItem);
[self installWithToolAndRelaunch:YES];
}
- (void)unarchiverDidFail:(SUUnarchiver *)__unused ua
- (void)unarchiverDidFailWithError:(NSError *)err
{
// No longer needed
self.updateValidator = nil;
if ([self.updateItem isDeltaUpdate]) {
[self failedToApplyDeltaUpdate];
return;
}
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while extracting the archive. Please try again later.", nil) }]];
[self abortUpdateWithError:err];
}
- (void)installWithToolAndRelaunch:(BOOL)relaunch
@@ -408,29 +439,37 @@
return YES;
}
- (BOOL)mayUpdateAndRestart
{
id<SUUpdaterPrivate> updater = self.updater;
return (!updater.delegate || ![updater.delegate respondsToSelector:@selector(updaterShouldRelaunchApplication:)] || [updater.delegate updaterShouldRelaunchApplication:self.updater]);
}
- (void)installWithToolAndRelaunch:(BOOL)relaunch displayingUserInterface:(BOOL)showUI
{
assert(self.updateItem);
if (![self validateUpdateDownloadedToPath:self.downloadPath extractedToPath:self.tempDir DSASignature:self.updateItem.DSASignature publicDSAKey:self.host.publicDSAKey])
{
assert(self.updateValidator);
BOOL validationCheckSuccess = [self.updateValidator validateWithUpdateDirectory:self.tempDir];
if (!validationCheckSuccess) {
NSDictionary *userInfo = @{
NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while extracting the archive. Please try again later.", nil),
NSLocalizedFailureReasonErrorKey: SULocalizedString(@"The update is improperly signed.", nil),
};
NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while extracting the archive. Please try again later.", nil),
NSLocalizedFailureReasonErrorKey: SULocalizedString(@"The update is improperly signed.", nil),
};
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUSignatureError userInfo:userInfo]];
return;
}
if (![self.updater mayUpdateAndRestart])
if (![self mayUpdateAndRestart])
{
[self abortUpdate];
return;
}
// Give the host app an opportunity to postpone the install and relaunch.
id<SUUpdaterPrivate> updater = self.updater;
static BOOL postponedOnce = NO;
id<SUUpdaterDelegate> updaterDelegate = [self.updater delegate];
id<SUUpdaterDelegate> updaterDelegate = [updater delegate];
if (!postponedOnce && [updaterDelegate respondsToSelector:@selector(updater:shouldPostponeRelaunchForUpdate:untilInvoking:)])
{
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[[self class] instanceMethodSignatureForSelector:@selector(installWithToolAndRelaunch:)]];
@@ -448,39 +487,48 @@
[updaterDelegate updater:self.updater willInstallUpdate:self.updateItem];
}
NSBundle *sparkleBundle = self.updater.sparkleBundle;
NSBundle *sparkleBundle = updater.sparkleBundle;
// Copy the relauncher into a temporary directory so we can get to it after the new version's installed.
// Only the paranoid survive: if there's already a stray copy of relaunch there, we would have problems.
NSString *const relaunchToolName = @"" SPARKLE_RELAUNCH_TOOL_NAME;
NSString *const relaunchPathToCopy = [sparkleBundle pathForResource:relaunchToolName ofType:@"app"];
if (relaunchPathToCopy != nil) {
NSString *targetPath = [self.host.appCachePath stringByAppendingPathComponent:[relaunchPathToCopy lastPathComponent]];
SUFileManager *fileManager = [SUFileManager fileManagerAllowingAuthorization:NO];
NSError *error = nil;
NSURL *relaunchURLToCopy = [NSURL fileURLWithPath:relaunchPathToCopy];
NSURL *targetURL = [NSURL fileURLWithPath:targetPath];
NSString *const relaunchToolSourcePath = [sparkleBundle pathForResource:relaunchToolName ofType:@"app"];
NSString *relaunchCopyTargetPath = nil;
NSError *error = nil;
BOOL copiedRelaunchPath = NO;
if (relaunchToolSourcePath) {
relaunchCopyTargetPath = [[self appCachePath] stringByAppendingPathComponent:[relaunchToolSourcePath lastPathComponent]];
SUFileManager *fileManager = [SUFileManager defaultManager];
NSURL *relaunchToolSourceURL = [NSURL fileURLWithPath:relaunchToolSourcePath];
NSURL *relaunchCopyTargetURL = [NSURL fileURLWithPath:relaunchCopyTargetPath];
// We only need to run our copy of the app by spawning a task
// Since we are copying the app to a directory that is write-accessible, we don't need to muck with owner/group IDs
if ([self preparePathForRelaunchTool:targetPath error:&error] && [fileManager copyItemAtURL:relaunchURLToCopy toURL:targetURL error:&error]) {
if ([self preparePathForRelaunchTool:relaunchCopyTargetPath error:&error] && [fileManager copyItemAtURL:relaunchToolSourceURL toURL:relaunchCopyTargetURL error:&error]) {
copiedRelaunchPath = YES;
// We probably don't need to release the quarantine, but we'll do it just in case it's necessary.
// Perhaps in a sandboxed environment this matters more. Note that this may not be a fatal error.
NSError *quarantineError = nil;
if (![fileManager releaseItemFromQuarantineAtRootURL:targetURL error:&quarantineError]) {
SULog(@"Failed to release quarantine on %@ with error %@", targetPath, quarantineError);
if (![fileManager releaseItemFromQuarantineAtRootURL:relaunchCopyTargetURL error:&quarantineError]) {
SULog(@"Failed to release quarantine on %@ with error %@", relaunchCopyTargetPath, quarantineError);
}
self.relaunchPath = targetPath;
} else {
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SURelaunchError userInfo:@{
NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while extracting the archive. Please try again later.", nil),
NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:@"Couldn't copy relauncher (%@) to temporary path (%@)! %@", relaunchPathToCopy, targetPath, (error ? [error localizedDescription] : @"")]
}]];
}
}
if (!copiedRelaunchPath) {
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SURelaunchError userInfo:@{
NSLocalizedDescriptionKey: [NSString stringWithFormat:SULocalizedString(@"An error occurred while relaunching %1$@, but the new version will be available next time you run %1$@.", nil), [self.host name]],
NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:@"Couldn't copy relauncher (%@) to temporary path (%@)! %@",
relaunchToolSourcePath, relaunchCopyTargetPath, (error ? [error localizedDescription] : @"")],
}]];
return;
}
self.relaunchPath = relaunchCopyTargetPath; // Set for backwards compatibility, in case any delegates modify it
[[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterWillRestartNotification object:self];
if ([updaterDelegate respondsToSelector:@selector(updaterWillRelaunchApplication:)])
[updaterDelegate updaterWillRelaunchApplication:self.updater];
@@ -490,16 +538,19 @@
// Note that we explicitly use the host app's name here, since updating plugin for Mail relaunches Mail, not just the plugin.
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SURelaunchError userInfo:@{
NSLocalizedDescriptionKey: [NSString stringWithFormat:SULocalizedString(@"An error occurred while relaunching %1$@, but the new version will be available next time you run %1$@.", nil), [self.host name]],
NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:@"Couldn't find the relauncher (expected to find it at %@)", self.relaunchPath]
NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:@"Couldn't find the relauncher (expected to find it at %@ and %@)", relaunchToolSourcePath, self.relaunchPath],
}]];
// We intentionally don't abandon the update here so that the host won't initiate another.
return;
}
NSString *pathToRelaunch = [self.host bundlePath];
if ([updaterDelegate respondsToSelector:@selector(pathToRelaunchForUpdater:)]) {
pathToRelaunch = [updaterDelegate pathToRelaunchForUpdater:self.updater];
NSString *delegateRelaunchPath = [updaterDelegate pathToRelaunchForUpdater:self.updater];
if (delegateRelaunchPath != nil) {
pathToRelaunch = delegateRelaunchPath;
}
}
[NSTask launchedTaskWithLaunchPath:relaunchToolPath arguments:@[[self.host bundlePath],
pathToRelaunch,
[NSString stringWithFormat:@"%d", [[NSProcessInfo processInfo] processIdentifier]],
@@ -509,6 +560,7 @@
[self terminateApp];
}
// Note: this is overridden by the automatic update driver to not terminate in some cases
- (void)terminateApp
{
[NSApp terminate:self];
@@ -551,14 +603,20 @@
- (void)abortUpdateWithError:(NSError *)error
{
if ([error code] != SUNoUpdateError) { // Let's not bother logging this.
SULog(@"Error: %@ %@ (URL %@)", error.localizedDescription, error.localizedFailureReason, error.userInfo[NSURLErrorFailingURLErrorKey]);
NSError *errorToDisplay = error;
int finiteRecursion=5;
do {
SULog(@"Error: %@ %@ (URL %@)", errorToDisplay.localizedDescription, errorToDisplay.localizedFailureReason, [errorToDisplay.userInfo objectForKey:NSURLErrorFailingURLErrorKey]);
errorToDisplay = [errorToDisplay.userInfo objectForKey:NSUnderlyingErrorKey];
} while(--finiteRecursion && errorToDisplay);
}
if (self.download) {
[self.download cancel];
}
// Notify host app that update has aborted
id<SUUpdaterDelegate> updaterDelegate = [self.updater delegate];
id<SUUpdaterPrivate> updater = self.updater;
id<SUUpdaterDelegate> updaterDelegate = [updater delegate];
if ([updaterDelegate respondsToSelector:@selector(updater:didAbortWithError:)]) {
[updaterDelegate updater:self.updater didAbortWithError:error];
}
+3 -1
View File
@@ -9,7 +9,9 @@
#ifndef SUBINARYDELTAAPPLY_H
#define SUBINARYDELTAAPPLY_H
#import <Foundation/Foundation.h>
@class NSString;
BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFile, BOOL verbose, NSError * __autoreleasing *error);
BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFile, BOOL verbose, void (^progressCallback)(double), NSError * __autoreleasing *error);
#endif
+19 -1
View File
@@ -15,6 +15,9 @@
#include <stdlib.h>
#include <xar/xar.h>
#include "AppKitPrevention.h"
static BOOL applyBinaryDeltaToFile(xar_t x, xar_file_t file, NSString *sourceFilePath, NSString *destinationFilePath)
{
NSString *patchFile = temporaryFilename(@"apply-binary-delta");
@@ -25,7 +28,7 @@ static BOOL applyBinaryDeltaToFile(xar_t x, xar_file_t file, NSString *sourceFil
return success;
}
BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFile, BOOL verbose, NSError * __autoreleasing *error)
BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFile, BOOL verbose, void (^progressCallback)(double progress), NSError * __autoreleasing *error)
{
xar_t x = xar_open([patchFile fileSystemRepresentation], READ);
if (!x) {
@@ -44,6 +47,8 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi
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)) {
@@ -112,6 +117,8 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi
fprintf(stderr, "Verifying source...");
}
progressCallback(1/6.0);
NSString *beforeHash = hashOfTreeWithVersion(source, majorDiffVersion);
if (!beforeHash) {
if (verbose) {
@@ -137,6 +144,8 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi
fprintf(stderr, "\nCopying files...");
}
progressCallback(2/6.0);
if (!removeTree(destination)) {
if (verbose) {
fprintf(stderr, "\n");
@@ -146,6 +155,9 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi
}
return NO;
}
progressCallback(3/6.0);
if (!copyTree(source, destination)) {
if (verbose) {
fprintf(stderr, "\n");
@@ -156,6 +168,8 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi
return NO;
}
progressCallback(4/6.0);
BOOL hasExtractKeyAvailable = MAJOR_VERSION_IS_AT_LEAST(majorDiffVersion, SUBeigeMajorVersion);
if (verbose) {
@@ -252,6 +266,8 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi
}
xar_close(x);
progressCallback(5/6.0);
if (verbose) {
fprintf(stderr, "\nVerifying destination...");
}
@@ -277,6 +293,8 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi
return NO;
}
progressCallback(6/6.0);
if (verbose) {
fprintf(stderr, "\nDone!\n");
}
+6 -3
View File
@@ -18,6 +18,9 @@
#include <sys/stat.h>
#include <xar/xar.h>
#include "AppKitPrevention.h"
int compareFiles(const FTSENT **a, const FTSENT **b)
{
return strcoll((*a)->fts_name, (*b)->fts_name);
@@ -221,7 +224,7 @@ BOOL removeTree(NSString *path)
BOOL copyTree(NSString *source, NSString *dest)
{
return [[SUFileManager fileManagerAllowingAuthorization:NO] copyItemAtURL:[NSURL fileURLWithPath:source] toURL:[NSURL fileURLWithPath:dest] error:NULL];
return [[SUFileManager defaultManager] copyItemAtURL:[NSURL fileURLWithPath:source] toURL:[NSURL fileURLWithPath:dest] error:NULL];
}
BOOL modifyPermissions(NSString *path, mode_t desiredPermissions)
@@ -231,12 +234,12 @@ BOOL modifyPermissions(NSString *path, mode_t desiredPermissions)
if (!attributes) {
return NO;
}
NSNumber *permissions = attributes[NSFilePosixPermissions];
NSNumber *permissions = [attributes objectForKey:NSFilePosixPermissions];
if (!permissions) {
return NO;
}
mode_t newMode = ([permissions unsignedShortValue] & ~PERMISSION_FLAGS) | desiredPermissions;
int (*changeModeFunc)(const char *, mode_t) = [attributes[NSFileType] isEqualToString:NSFileTypeSymbolicLink] ? lchmod : chmod;
int (*changeModeFunc)(const char *, mode_t) = [[attributes objectForKey:NSFileType] isEqualToString:NSFileTypeSymbolicLink] ? lchmod : chmod;
if (changeModeFunc([path fileSystemRepresentation], newMode) != 0) {
return NO;
}
+4 -1
View File
@@ -21,6 +21,9 @@
#include <sys/xattr.h>
#include <xar/xar.h>
#include "AppKitPrevention.h"
extern int bsdiff(int argc, const char **argv);
@interface CreateBinaryDeltaOperation : NSOperation
@@ -87,7 +90,7 @@ static NSDictionary *infoForFile(FTSENT *ent)
static bool aclExists(const FTSENT *ent)
{
// OS X does not currently support ACLs for symlinks
// macOS does not currently support ACLs for symlinks
if (ent->fts_info == FTS_SL) {
return NO;
}
+10 -4
View File
@@ -20,6 +20,8 @@
#define VERSION_COMMAND @"version"
#define VERSION_ALTERNATE_COMMAND @"--version"
#include "AppKitPrevention.h"
static void printUsage(NSString *programName)
{
fprintf(stderr, "Usage:\n");
@@ -96,21 +98,25 @@ static BOOL runCreateCommand(NSString *programName, NSArray *args)
return NO;
}
NSString *sourcePath = fileArgs[0];
NSString *destPath = fileArgs[1];
NSString *patchPath = fileArgs[2];
BOOL isDirectory;
if (![[NSFileManager defaultManager] fileExistsAtPath:fileArgs[0] isDirectory:&isDirectory] || !isDirectory) {
if (![[NSFileManager defaultManager] fileExistsAtPath:sourcePath isDirectory:&isDirectory] || !isDirectory) {
printUsage(programName);
fprintf(stderr, "Error: before-tree must be a directory\n");
return NO;
}
if (![[NSFileManager defaultManager] fileExistsAtPath:fileArgs[1] isDirectory:&isDirectory] || !isDirectory) {
if (![[NSFileManager defaultManager] fileExistsAtPath:destPath isDirectory:&isDirectory] || !isDirectory) {
printUsage(programName);
fprintf(stderr, "Error: after-tree must be a directory\n");
return NO;
}
NSError *createDiffError = nil;
if (!createBinaryDelta(fileArgs[0], fileArgs[1], fileArgs[2], patchVersion, verbose, &createDiffError)) {
if (!createBinaryDelta(sourcePath, destPath, patchPath, patchVersion, verbose, &createDiffError)) {
fprintf(stderr, "%s\n", [createDiffError.localizedDescription UTF8String]);
return NO;
}
@@ -158,7 +164,7 @@ static BOOL runApplyCommand(NSString *programName, NSArray *args)
}
NSError *applyDiffError = nil;
if (!applyBinaryDelta(fileArgs[0], fileArgs[1], fileArgs[2], verbose, &applyDiffError)) {
if (!applyBinaryDelta(fileArgs[0], fileArgs[1], fileArgs[2], verbose, ^(__unused double x){}, &applyDiffError)) {
fprintf(stderr, "%s\n", [applyDiffError.localizedDescription UTF8String]);
return NO;
}
+9 -3
View File
@@ -9,11 +9,17 @@
#ifndef SUBINARYDELTAUNARCHIVER_H
#define SUBINARYDELTAUNARCHIVER_H
#import <Cocoa/Cocoa.h>
#import "SUUnarchiver.h"
#import <Foundation/Foundation.h>
#import "SUUnarchiverProtocol.h"
@interface SUBinaryDeltaUnarchiver : SUUnarchiver
NS_ASSUME_NONNULL_BEGIN
@interface SUBinaryDeltaUnarchiver : NSObject <SUUnarchiverProtocol>
- (instancetype)initWithArchivePath:(NSString *)archivePath updateHostBundlePath:(NSString *)updateHostBundlePath;
@end
NS_ASSUME_NONNULL_END
#endif
+83 -23
View File
@@ -6,53 +6,113 @@
// Copyright 2009 Mark Rowe. All rights reserved.
//
#import "SUBinaryDeltaCommon.h"
#import "SUBinaryDeltaUnarchiver.h"
#import "SUUnarchiverNotifier.h"
#import "SUBinaryDeltaCommon.h"
#import "SUBinaryDeltaApply.h"
#import "SUUnarchiver_Private.h"
#import "SUHost.h"
#import "SULog.h"
#import "NTSynchronousTask.h"
#import "SUFileManager.h"
#include "AppKitPrevention.h"
@interface SUBinaryDeltaUnarchiver ()
@property (nonatomic, copy, readonly) NSString *archivePath;
@property (nonatomic, copy, readonly) NSString *updateHostBundlePath;
@end
@implementation SUBinaryDeltaUnarchiver
@synthesize archivePath = _archivePath;
@synthesize updateHostBundlePath = _updateHostBundlePath;
+ (BOOL)canUnarchivePath:(NSString *)path
{
return [[path pathExtension] isEqualToString:@"delta"];
}
- (void)applyBinaryDelta
+ (BOOL)unsafeIfArchiveIsNotValidated
{
@autoreleasepool {
NSString *sourcePath = self.updateHostBundlePath;
NSString *targetPath = [[self.archivePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:[sourcePath lastPathComponent]];
return YES;
}
NSError *applyDiffError = nil;
BOOL success = applyBinaryDelta(sourcePath, targetPath, self.archivePath, NO, &applyDiffError);
if (success) {
dispatch_async(dispatch_get_main_queue(), ^{
[self notifyDelegateOfSuccess];
});
// According to https://developer.apple.com/library/mac/documentation/Carbon/Conceptual/MDImporters/Concepts/Troubleshooting.html
// We should make sure mdimporter bundles have an up to date time in the event they were delta updated.
// 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
+ (void)updateSpotlightImportersAtBundlePath:(NSString *)targetPath
{
NSURL *targetURL = [NSURL fileURLWithPath:targetPath];
// Only recurse if it's actually a directory. Don't recurse into a
// root-level symbolic link.
NSDictionary *rootAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:targetPath error:nil];
NSString *rootType = [rootAttributes objectForKey:NSFileType];
if ([rootType isEqualToString:NSFileTypeDirectory]) {
// The NSDirectoryEnumerator will avoid recursing into any contained
// symbolic links, so no further type checks are needed.
NSDirectoryEnumerator *directoryEnumerator = [[NSFileManager defaultManager] enumeratorAtURL:targetURL includingPropertiesForKeys:nil options:(NSDirectoryEnumerationOptions)0 errorHandler:nil];
NSMutableArray *filesToUpdate = [[NSMutableArray alloc] init];
for (NSURL *file in directoryEnumerator) {
if ([file.pathExtension isEqualToString:@"mdimporter"]) {
[filesToUpdate addObject:file];
}
}
else {
SULog(@"Applying delta patch failed with error: %@", applyDiffError);
dispatch_async(dispatch_get_main_queue(), ^{
[self notifyDelegateOfFailure];
});
SUFileManager *fileManager = [SUFileManager defaultManager];
for (NSURL *file in filesToUpdate) {
NSError *error = nil;
if (![fileManager updateModificationAndAccessTimeOfItemAtURL:file error:&error]) {
SULog(@"Error: During delta unarchiving, failed to touch %@", error);
}
}
}
}
- (void)start
- (instancetype)initWithArchivePath:(NSString *)archivePath updateHostBundlePath:(NSString *)updateHostBundlePath
{
self = [super init];
if (self != nil) {
_archivePath = [archivePath copy];
_updateHostBundlePath = [updateHostBundlePath copy];
}
return self;
}
- (void)unarchiveWithCompletionBlock:(void (^)(NSError * _Nullable))completionBlock progressBlock:(void (^ _Nullable)(double))progressBlock
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self applyBinaryDelta];
@autoreleasepool {
SUUnarchiverNotifier *notifier = [[SUUnarchiverNotifier alloc] initWithCompletionBlock:completionBlock progressBlock:progressBlock];
[self extractDeltaWithNotifier:notifier];
}
});
}
+ (void)load
- (void)extractDeltaWithNotifier:(SUUnarchiverNotifier *)notifier
{
[self registerImplementation:self];
NSString *sourcePath = self.updateHostBundlePath;
NSString *targetPath = [[self.archivePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:[sourcePath lastPathComponent]];
NSError *applyDiffError = nil;
BOOL success = applyBinaryDelta(sourcePath, targetPath, self.archivePath, NO, ^(double progress){
[notifier notifyProgress:progress];
}, &applyDiffError);
if (success) {
[[self class] updateSpotlightImportersAtBundlePath:targetPath];
[notifier notifySuccess];
}
else {
[notifier notifyFailureWithError:applyDiffError];
}
}
- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], self.archivePath]; }
@end
+19
View File
@@ -0,0 +1,19 @@
//
// SUBundleIcon.h
// Sparkle
//
// Created by Mayur Pawashe on 7/24/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface SUBundleIcon : NSObject
+ (NSURL * _Nullable)iconURLForBundle:(NSBundle *)bundle;
@end
NS_ASSUME_NONNULL_END
+32
View File
@@ -0,0 +1,32 @@
//
// SUBundleIcon.m
// Sparkle
//
// Created by Mayur Pawashe on 7/24/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import "SUBundleIcon.h"
#include "AppKitPrevention.h"
@implementation SUBundleIcon
+ (NSURL *)iconURLForBundle:(NSBundle *)bundle
{
NSString *resource = [bundle objectForInfoDictionaryKey:@"CFBundleIconFile"];
if (resource == nil || ![resource isKindOfClass:[NSString class]]) {
return nil;
}
NSURL *iconURL = [bundle URLForResource:resource withExtension:@"icns"];
// The resource could already be containing the path extension, so try again without the extra extension
if (iconURL == nil) {
iconURL = [bundle URLForResource:resource withExtension:nil];
}
return iconURL;
}
@end
+3 -4
View File
@@ -12,10 +12,9 @@
#import <Foundation/Foundation.h>
@interface SUCodeSigningVerifier : NSObject
+ (BOOL)codeSignatureMatchesHostAndIsValidAtPath:(NSString *)applicationPath error:(NSError **)error;
+ (BOOL)codeSignatureIsValidAtPath:(NSString *)applicationPath error:(NSError **)error;
+ (BOOL)hostApplicationIsCodeSigned;
+ (BOOL)applicationAtPathIsCodeSigned:(NSString *)applicationPath;
+ (BOOL)codeSignatureAtBundleURL:(NSURL *)oldBundlePath matchesSignatureAtBundleURL:(NSURL *)newBundlePath error:(NSError **)error;
+ (BOOL)codeSignatureIsValidAtBundleURL:(NSURL *)bundlePath error:(NSError **)error;
+ (BOOL)bundleAtURLIsCodeSigned:(NSURL *)bundlePath;
@end
#endif
+36 -70
View File
@@ -11,55 +11,51 @@
#import "SUCodeSigningVerifier.h"
#import "SULog.h"
#include "AppKitPrevention.h"
@implementation SUCodeSigningVerifier
+ (BOOL)codeSignatureMatchesHostAndIsValidAtPath:(NSString *)applicationPath error:(NSError *__autoreleasing *)error
+ (BOOL)codeSignatureAtBundleURL:(NSURL *)oldBundleURL matchesSignatureAtBundleURL:(NSURL *)newBundleURL error:(NSError *__autoreleasing *)error
{
OSStatus result;
SecRequirementRef requirement = NULL;
SecStaticCodeRef staticCode = NULL;
SecCodeRef hostCode = NULL;
NSBundle *newBundle;
SecStaticCodeRef oldCode = NULL;
CFErrorRef cfError = NULL;
if (error) {
*error = nil;
}
result = SecCodeCopySelf(kSecCSDefaultFlags, &hostCode);
if (result != noErr) {
SULog(@"Failed to copy host code %d", result);
goto finally;
result = SecStaticCodeCreateWithPath((__bridge CFURLRef)oldBundleURL, kSecCSDefaultFlags, &oldCode);
if (result == errSecCSUnsigned) {
return NO;
}
result = SecCodeCopyDesignatedRequirement(hostCode, kSecCSDefaultFlags, &requirement);
result = SecCodeCopyDesignatedRequirement(oldCode, kSecCSDefaultFlags, &requirement);
if (result != noErr) {
SULog(@"Failed to copy designated requirement. Code Signing OSStatus code: %d", result);
goto finally;
}
newBundle = [NSBundle bundleWithPath:applicationPath];
if (!newBundle) {
SULog(@"Failed to load NSBundle for update");
result = -1;
goto finally;
}
result = SecStaticCodeCreateWithPath((__bridge CFURLRef)[newBundle bundleURL], kSecCSDefaultFlags, &staticCode);
result = SecStaticCodeCreateWithPath((__bridge CFURLRef)newBundleURL, kSecCSDefaultFlags, &staticCode);
if (result != noErr) {
SULog(@"Failed to get static code %d", result);
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
SecCSFlags flags = (SecCSFlags) (kSecCSDefaultFlags | kSecCSCheckAllArchitectures);
// Aditionally, there are several reasons to stay away from deep verification and to prefer DSA signing the download archive instead.
// See https://github.com/sparkle-project/Sparkle/pull/523#commitcomment-17549302 and https://github.com/sparkle-project/Sparkle/issues/543
SecCSFlags flags = (SecCSFlags) (kSecCSDefaultFlags | kSecCSCheckAllArchitectures);
result = SecStaticCodeCheckValidityWithErrors(staticCode, flags, requirement, &cfError);
if (cfError) {
NSError *tmpError = CFBridgingRelease(cfError);
if (error) *error = tmpError;
}
if (result != noErr) {
if (result == errSecCSUnsigned) {
SULog(@"The host app is signed, but the new version of the app is not signed using Apple Code Signing. Please ensure that the new app is signed and that archiving did not corrupt the signature.");
@@ -70,61 +66,52 @@
SULog(@"Code signature of the new version doesn't match the old version: %@. Please ensure that old and new app is signed using exactly the same certificate.", requirementString);
CFRelease(requirementString);
}
[self logSigningInfoForCode:hostCode label:@"host info"];
[self logSigningInfoForCode:oldCode label:@"old info"];
[self logSigningInfoForCode:staticCode label:@"new info"];
}
}
finally:
if (hostCode) CFRelease(hostCode);
if (oldCode) CFRelease(oldCode);
if (staticCode) CFRelease(staticCode);
if (requirement) CFRelease(requirement);
return (result == noErr);
}
+ (BOOL)codeSignatureIsValidAtPath:(NSString *)applicationPath error:(NSError *__autoreleasing *)error
+ (BOOL)codeSignatureIsValidAtBundleURL:(NSURL *)bundleURL error:(NSError *__autoreleasing *)error
{
OSStatus result;
SecStaticCodeRef staticCode = NULL;
NSBundle *newBundle;
CFErrorRef cfError = NULL;
if (error) {
*error = nil;
}
newBundle = [NSBundle bundleWithPath:applicationPath];
if (!newBundle) {
SULog(@"Failed to load NSBundle");
result = -1;
goto finally;
}
result = SecStaticCodeCreateWithPath((__bridge CFURLRef)[newBundle bundleURL], kSecCSDefaultFlags, &staticCode);
result = SecStaticCodeCreateWithPath((__bridge CFURLRef)bundleURL, kSecCSDefaultFlags, &staticCode);
if (result != noErr) {
SULog(@"Failed to get static code %d", result);
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
SecCSFlags flags = (SecCSFlags) (kSecCSDefaultFlags | kSecCSCheckAllArchitectures);
// 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;
}
if (result != noErr) {
if (result == errSecCSUnsigned) {
SULog(@"Error: The app is not signed using Apple Code Signing. %@", applicationPath);
SULog(@"Error: The app is not signed using Apple Code Signing. %@", bundleURL);
}
if (result == errSecCSReqFailed) {
[self logSigningInfoForCode:staticCode label:@"new info"];
}
}
finally:
if (staticCode) CFRelease(staticCode);
return (result == noErr);
@@ -141,44 +128,23 @@ static id valueOrNSNull(id value) {
NSDictionary *signingDict = CFBridgingRelease(signingInfo);
NSMutableDictionary *relevantInfo = [NSMutableDictionary dictionary];
for (NSString *key in @[@"format", @"identifier", @"requirements", @"teamid", @"signing-time"]) {
relevantInfo[key] = valueOrNSNull(signingDict[key]);
[relevantInfo setObject:valueOrNSNull([signingDict objectForKey:key]) forKey:key];
}
NSDictionary *infoPlist = signingDict[@"info-plist"];
relevantInfo[@"version"] = valueOrNSNull(infoPlist[@"CFBundleShortVersionString"]);
relevantInfo[@"build"] = valueOrNSNull(infoPlist[(__bridge NSString *)kCFBundleVersionKey]);
NSDictionary *infoPlist = [signingDict objectForKey:@"info-plist"];
[relevantInfo setObject:valueOrNSNull([infoPlist objectForKey:@"CFBundleShortVersionString"]) forKey:@"version"];
[relevantInfo setObject:valueOrNSNull([infoPlist objectForKey:(__bridge NSString *)kCFBundleVersionKey]) forKey:@"build"];
SULog(@"%@: %@", label, relevantInfo);
}
}
+ (BOOL)hostApplicationIsCodeSigned
{
OSStatus result;
SecCodeRef hostCode = NULL;
result = SecCodeCopySelf(kSecCSDefaultFlags, &hostCode);
if (result != 0) return NO;
SecRequirementRef requirement = NULL;
result = SecCodeCopyDesignatedRequirement(hostCode, kSecCSDefaultFlags, &requirement);
if (hostCode) CFRelease(hostCode);
if (requirement) CFRelease(requirement);
return (result == 0);
}
+ (BOOL)applicationAtPathIsCodeSigned:(NSString *)applicationPath
+ (BOOL)bundleAtURLIsCodeSigned:(NSURL *)bundleURL
{
OSStatus result;
SecStaticCodeRef staticCode = NULL;
NSBundle *newBundle;
newBundle = [NSBundle bundleWithPath:applicationPath];
if (!newBundle) {
SULog(@"Failed to load NSBundle");
return NO;
}
result = SecStaticCodeCreateWithPath((__bridge CFURLRef)[newBundle bundleURL], kSecCSDefaultFlags, &staticCode);
result = SecStaticCodeCreateWithPath((__bridge CFURLRef)bundleURL, kSecCSDefaultFlags, &staticCode);
if (result == errSecCSUnsigned) {
return NO;
return NO;
}
SecRequirementRef requirement = NULL;
@@ -190,7 +156,7 @@ static id valueOrNSNull(id value) {
CFRelease(requirement);
}
if (result == errSecCSUnsigned) {
return NO;
return NO;
}
return (result == 0);
}
+2 -1
View File
@@ -43,13 +43,13 @@ extern NSString *const SUPublicDSAKeyFileKey;
extern NSString *const SUAutomaticallyUpdateKey;
extern NSString *const SUAllowsAutomaticUpdatesKey;
extern NSString *const SUEnableAutomaticChecksKey;
extern NSString *const SUEnableAutomaticChecksKeyOld;
extern NSString *const SUEnableSystemProfilingKey;
extern NSString *const SUSendProfileInfoKey;
extern NSString *const SULastProfileSubmitDateKey;
extern NSString *const SUPromptUserOnFirstLaunchKey;
extern NSString *const SUKeepDownloadOnFailedInstallKey;
extern NSString *const SUDefaultsDomainKey;
extern NSString *const SUEnableJavaScriptKey;
extern NSString *const SUFixedHTMLDisplaySizeKey __attribute__((deprecated("This key is obsolete and has no effect.")));
extern NSString *const SUAppendVersionNumberKey __attribute__((deprecated("This key is obsolete. See SPARKLE_APPEND_VERSION_NUMBER.")));
extern NSString *const SUEnableAutomatedDowngradesKey __attribute__((deprecated("This key is obsolete. See SPARKLE_AUTOMATED_DOWNGRADES.")));
@@ -73,6 +73,7 @@ extern NSString *const SUAppcastElementReleaseNotesLink;
extern NSString *const SUAppcastElementTags;
extern NSString *const SURSSAttributeURL;
extern NSString *const SURSSAttributeLength;
extern NSString *const SURSSElementDescription;
extern NSString *const SURSSElementEnclosure;
+5 -6
View File
@@ -6,17 +6,15 @@
// Copyright 2006 Andy Matuschak. All rights reserved.
//
#import "SUUpdater.h"
#import "SUAppcast.h"
#import "SUAppcastItem.h"
#import "SUVersionComparisonProtocol.h"
#import "SUConstants.h"
#import "SUErrors.h"
#ifndef DEBUG
#define DEBUG 0
#endif
#include "AppKitPrevention.h"
// Define some minimum intervals to avoid DoS-like checking attacks
const NSTimeInterval SUMinimumUpdateCheckInterval = DEBUG ? 60 : (60 * 60);
const NSTimeInterval SUDefaultUpdateCheckInterval = DEBUG ? 60 : (60 * 60 * 24);
@@ -38,10 +36,10 @@ NSString *const SUAutomaticallyUpdateKey = @"SUAutomaticallyUpdate";
NSString *const SUAllowsAutomaticUpdatesKey = @"SUAllowsAutomaticUpdates";
NSString *const SUEnableSystemProfilingKey = @"SUEnableSystemProfiling";
NSString *const SUEnableAutomaticChecksKey = @"SUEnableAutomaticChecks";
NSString *const SUEnableAutomaticChecksKeyOld = @"SUCheckAtStartup";
NSString *const SUSendProfileInfoKey = @"SUSendProfileInfo";
NSString *const SULastProfileSubmitDateKey = @"SULastProfileSubmissionDate";
NSString *const SUPromptUserOnFirstLaunchKey = @"SUPromptUserOnFirstLaunch";
NSString *const SUEnableJavaScriptKey = @"SUEnableJavaScript";
NSString *const SUFixedHTMLDisplaySizeKey = @"SUFixedHTMLDisplaySize";
NSString *const SUKeepDownloadOnFailedInstallKey = @"SUKeepDownloadOnFailedInstall";
NSString *const SUDefaultsDomainKey = @"SUDefaultsDomain";
@@ -65,6 +63,7 @@ NSString *const SUAppcastElementReleaseNotesLink = @"sparkle:releaseNotesLink";
NSString *const SUAppcastElementTags = @"sparkle:tags";
NSString *const SURSSAttributeURL = @"url";
NSString *const SURSSAttributeLength = @"length";
NSString *const SURSSElementDescription = @"description";
NSString *const SURSSElementEnclosure = @"enclosure";
+3
View File
@@ -16,6 +16,9 @@
#import "SULog.h"
#include <CommonCrypto/CommonDigest.h>
#include "AppKitPrevention.h"
@implementation SUDSAVerifier {
SecKeyRef _secKey;
}
+9 -3
View File
@@ -9,11 +9,17 @@
#ifndef SUDISKIMAGEUNARCHIVER_H
#define SUDISKIMAGEUNARCHIVER_H
#import <Cocoa/Cocoa.h>
#import "SUUnarchiver.h"
#import <Foundation/Foundation.h>
#import "SUUnarchiverProtocol.h"
@interface SUDiskImageUnarchiver : SUUnarchiver
NS_ASSUME_NONNULL_BEGIN
@interface SUDiskImageUnarchiver : NSObject <SUUnarchiverProtocol>
- (instancetype)initWithArchivePath:(NSString *)archivePath decryptionPassword:(nullable NSString *)decryptionPassword;
@end
NS_ASSUME_NONNULL_END
#endif
+116 -78
View File
@@ -7,86 +7,133 @@
//
#import "SUDiskImageUnarchiver.h"
#import "SUUnarchiver_Private.h"
#import "NTSynchronousTask.h"
#import "SUUnarchiverNotifier.h"
#import "SULog.h"
#include <CoreServices/CoreServices.h>
#include "AppKitPrevention.h"
@interface SUDiskImageUnarchiver ()
@property (nonatomic, copy, readonly) NSString *archivePath;
@property (nullable, nonatomic, copy, readonly) NSString *decryptionPassword;
@end
@implementation SUDiskImageUnarchiver
@synthesize archivePath = _archivePath;
@synthesize decryptionPassword = _decryptionPassword;
+ (BOOL)canUnarchivePath:(NSString *)path
{
return [[path pathExtension] isEqualToString:@"dmg"];
}
// Called on a non-main thread.
- (void)extractDMG
+ (BOOL)unsafeIfArchiveIsNotValidated
{
@autoreleasepool {
[self extractDMGWithPassword:nil];
return NO;
}
- (instancetype)initWithArchivePath:(NSString *)archivePath decryptionPassword:(nullable NSString *)decryptionPassword
{
self = [super init];
if (self != nil) {
_archivePath = [archivePath copy];
_decryptionPassword = [decryptionPassword copy];
}
return self;
}
- (void)unarchiveWithCompletionBlock:(void (^)(NSError * _Nullable))completionBlock progressBlock:(void (^ _Nullable)(double))progressBlock
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
SUUnarchiverNotifier *notifier = [[SUUnarchiverNotifier alloc] initWithCompletionBlock:completionBlock progressBlock:progressBlock];
[self extractDMGWithNotifier:notifier];
});
}
// Called on a non-main thread.
- (void)extractDMGWithPassword:(NSString *)__unused password
- (void)extractDMGWithNotifier:(SUUnarchiverNotifier *)notifier
{
@autoreleasepool {
BOOL mountedSuccessfully = NO;
SULog(@"Extracting %@ as a DMG", self.archivePath);
// get a unique mount point path
NSString *mountPoint = nil;
FSRef tmpRef;
NSFileManager *manager;
NSError *error;
NSArray *contents;
// We have to declare these before a goto to prevent an error under ARC.
// No, we cannot have them in the dispatch_async calls, as the goto "jump enters
// lifetime of block which strongly captures a variable"
dispatch_block_t delegateFailure = ^{
[self notifyDelegateOfFailure];
};
dispatch_block_t delegateSuccess = ^{
[self notifyDelegateOfSuccess];
};
do
do
{
// Using NSUUID would make creating UUIDs be done in Cocoa,
// and thus managed under ARC. Sadly, the class is in 10.8 and later.
CFUUIDRef uuid = CFUUIDCreate(NULL);
if (uuid)
{
if (uuid)
{
NSString *uuidString = CFBridgingRelease(CFUUIDCreateString(NULL, uuid));
if (uuidString)
{
if (uuidString)
{
mountPoint = [@"/Volumes" stringByAppendingPathComponent:uuidString];
}
CFRelease(uuid);
}
}
while (noErr == FSPathMakeRefWithOptions((const UInt8 *)[mountPoint fileSystemRepresentation], kFSPathMakeRefDoNotFollowLeafSymlink, &tmpRef, NULL));
}
// Note: this check does not follow symbolic links, which is what we want
while ([[NSURL fileURLWithPath:mountPoint] checkResourceIsReachableAndReturnError:NULL]);
NSData *promptData = nil;
promptData = [NSData dataWithBytes:"yes\n" length:4];
NSArray *arguments = @[@"attach", self.archivePath, @"-mountpoint", mountPoint, /*@"-noverify",*/ @"-nobrowse", @"-noautoopen"];
NSMutableArray *arguments = [@[@"attach", self.archivePath, @"-mountpoint", mountPoint, /*@"-noverify",*/ @"-nobrowse", @"-noautoopen"] mutableCopy];
if (self.decryptionPassword) {
NSMutableData *passwordData = [[self.decryptionPassword dataUsingEncoding:NSUTF8StringEncoding] mutableCopy];
// From the hdiutil docs:
// 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;
[arguments addObject:@"-stdinpass"];
}
NSData *output = nil;
NSInteger taskResult = -1;
@try
{
NTSynchronousTask *task = [[NTSynchronousTask alloc] init];
@try
{
NSTask *task = [[NSTask alloc] init];
task.launchPath = @"/usr/bin/hdiutil";
task.currentDirectoryPath = @"/";
task.arguments = arguments;
NSPipe *inputPipe = [NSPipe pipe];
NSPipe *outputPipe = [NSPipe pipe];
task.standardInput = inputPipe;
task.standardOutput = outputPipe;
[task launch];
[notifier notifyProgress:0.125];
[task run:@"/usr/bin/hdiutil" directory:@"/" withArgs:arguments input:promptData];
taskResult = [task result];
output = [[task output] copy];
[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];
[task waitUntilExit];
taskResult = task.terminationStatus;
}
@catch (NSException *)
{
goto reportError;
}
[notifier notifyProgress:0.5];
if (taskResult != 0)
{
@@ -95,74 +142,65 @@
goto reportError;
}
mountedSuccessfully = YES;
// Now that we've mounted it, we need to copy out its contents.
manager = [[NSFileManager alloc] init];
contents = [manager contentsOfDirectoryAtPath:mountPoint error:&error];
if (error)
{
if (error)
{
SULog(@"Couldn't enumerate contents of archive mounted at %@: %@", mountPoint, error);
goto reportError;
}
double itemsCopied = 0;
double totalItems = [contents count];
for (NSString *item in contents)
{
NSString *fromPath = [mountPoint stringByAppendingPathComponent:item];
NSString *toPath = [[self.archivePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:item];
// We skip any files in the DMG which are not readable.
if (![manager isReadableFileAtPath:fromPath]) {
continue;
}
itemsCopied += 1.0;
[notifier notifyProgress:0.5 + itemsCopied/(totalItems*2.0)];
SULog(@"copyItemAtPath:%@ toPath:%@", fromPath, toPath);
if (![manager copyItemAtPath:fromPath toPath:toPath error:&error])
{
SULog(@"Couldn't copy item: %@ : %@", error, error.userInfo ? error.userInfo : @"");
goto reportError;
}
}
dispatch_async(dispatch_get_main_queue(), delegateSuccess);
[notifier notifySuccess];
goto finally;
reportError:
dispatch_async(dispatch_get_main_queue(), delegateFailure);
[notifier notifyFailureWithError:error];
finally:
if (mountedSuccessfully)
[NSTask launchedTaskWithLaunchPath:@"/usr/bin/hdiutil" arguments:@[@"detach", mountPoint, @"-force"]];
else
if (mountedSuccessfully) {
NSTask *task = [[NSTask alloc] init];
task.launchPath = @"/usr/bin/hdiutil";
task.arguments = @[@"detach", mountPoint, @"-force"];
task.standardOutput = [NSPipe pipe];
task.standardError = [NSPipe pipe];
@try {
[task launch];
} @catch (NSException *exception) {
SULog(@"Failed to unmount %@", mountPoint);
SULog(@"Exception: %@", exception);
}
} else {
SULog(@"Can't mount DMG %@", self.archivePath);
}
}
- (void)start
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self extractDMG];
});
}
+ (void)load
{
[self registerImplementation:self];
}
- (BOOL)isEncrypted:(NSData *)resultData
{
BOOL result = NO;
if(resultData)
{
NSString *data = [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding];
if ((data != nil) && !NSEqualRanges([data rangeOfString:@"passphrase-count"], NSMakeRange(NSNotFound, 0)))
{
result = YES;
}
}
return result;
}
- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], self.archivePath]; }
@end
+9 -3
View File
@@ -9,7 +9,11 @@
#ifndef SUERRORS_H
#define SUERRORS_H
#if __has_feature(modules)
@import Foundation;
#else
#import <Foundation/Foundation.h>
#endif
#import "SUExport.h"
/**
@@ -23,10 +27,11 @@ typedef NS_ENUM(OSStatus, SUError) {
SUNoUpdateError = 1001,
SUAppcastError = 1002,
SURunningFromDiskImageError = 1003,
// Downlaod phase errors.
// Download phase errors.
SUTemporaryDirectoryError = 2000,
SUDownloadError = 2001,
// Extraction phase errors.
SUUnarchivingError = 3000,
SUSignatureError = 3001,
@@ -39,6 +44,7 @@ typedef NS_ENUM(OSStatus, SUError) {
SURelaunchError = 4004,
SUInstallationError = 4005,
SUDowngradeError = 4006,
SUInstallationCancelledError = 4007,
// System phase errors
SUSystemPowerOffError = 5000
+58 -32
View File
@@ -8,22 +8,39 @@
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/**
* A class used for performing file operations that may also perform authentication if allowed and if permission is denied when trying to
* A class used for performing file operations that may also perform authorization if allowed and if permission is denied when trying to
* perform them normally as the running user. All operations on this class may be used on thread other than the main thread.
* This class provides basic file operations and stays away from including much application-level logic.
*/
@interface SUFileManager : NSObject
/**
* Creates a file manager that allows or disallows authorizing for file operations
* @param allowsAuthorization Specifies whether operations invoked on this instance are allowed to acquire authorization in order
* to perform file operations when read or write access is denied
* Creates a file manager that will not authorize for file operations
* @return A new file manager instance
*/
+ (instancetype)defaultManager;
/**
* Creates a file manager that allows authorizing for file operations
* @param authorizationToolPath Specifies the path to the tool that can perform file operations and be run as root.
* This tool will be invoked when read or write access is denied when attempting ordinary file operations. See the `fileop` tool included in Sparkle.
* @return A new file manager instance
*
* This method just creates the file manager. It doesn't acquire authorization immediately if allowsAuthorization is YES
*
* This method just creates the file manager. It doesn't acquire authorization immediately or if it doesn't need to.
*/
+ (instancetype)fileManagerAllowingAuthorization:(BOOL)allowsAuthorization;
+ (instancetype)fileManagerWithAuthorizationToolPath:(NSString *)authorizationToolPath;
/**
* Returns a file manager that allows or disallows authorizing for file operations based on the current file manager
* @return A file manager instance that can perform authorized operations if the current file manager has already performed them.
* If the current file manager instance hasn't yet performed authorized operations, then neither can the instance returned by this method
*
* This may return a newly created file manager or re-use the existing file manager depending on the current authorization rights.
*/
- (instancetype)fileManagerByPreservingAuthorizationRights;
/**
* Creates a temporary directory on the same volume as a provided URL
@@ -35,7 +52,17 @@
* When moving an item from a source to a destination, it is desirable to create a temporary intermediate destination on the same volume as the destination to ensure
* that the item will be moved, and not copied, from the intermediate point to the final destination. This ensures file atomicity.
*/
- (NSURL *)makeTemporaryDirectoryWithPreferredName:(NSString *)preferredName appropriateForDirectoryURL:(NSURL *)appropriateURL error:(NSError **)error;
- (nullable NSURL *)makeTemporaryDirectoryWithPreferredName:(NSString *)preferredName appropriateForDirectoryURL:(NSURL *)appropriateURL error:(NSError *_Nullable*_Nullable)error;
/**
* Creates a directory at the target URL
* @param targetURL A URL pointing to the directory to create. The item at this URL must not exist, and the parent directory of this URL must already exist.
* @param error If an error occurs, upon returns contains an NSError object that describes the problem. If you are not interested in possible errors, you may pass in NULL.
* @return YES if the item was created successfully, otherwise NO along with a populated error object
*
* This is an atomic operation.
*/
- (BOOL)makeDirectoryAtURL:(NSURL *)targetURL error:(NSError *_Nullable*_Nullable)error;
/**
* Moves an item from a source to a destination
@@ -43,11 +70,11 @@
* @param destinationURL A URL pointing to the destination the item will be moved at. An item must not already exist at this URL.
* @param error If an error occurs, upon returns contains an NSError object that describes the problem. If you are not interested in possible errors, you may pass in NULL.
* @return YES if the item was moved successfully, otherwise NO along with a populated error object
*
*
* If sourceURL and destinationURL reside on the same volume, this operation will be an atomic move operation.
* Otherwise this will be equivalent to a copy & remove which will be a nonatomic operation.
*/
- (BOOL)moveItemAtURL:(NSURL *)sourceURL toURL:(NSURL *)destinationURL error:(NSError **)error;
- (BOOL)moveItemAtURL:(NSURL *)sourceURL toURL:(NSURL *)destinationURL error:(NSError *_Nullable*_Nullable)error;
/**
* Copies an item from a source to a destination
@@ -58,22 +85,7 @@
*
* This is not an atomic operation.
*/
- (BOOL)copyItemAtURL:(NSURL *)sourceURL toURL:(NSURL *)destinationURL error:(NSError **)error;
/**
* Moves an item at a specified URL to the running user's trash directory
* @param url A URL pointing to the item to move to the trash. The item at this URL must exist.
* @param error If an error occurs, upon returns contains an NSError object that describes the problem. If you are not interested in possible errors, you may pass in NULL.
* @return YES if the item was moved to the trash successfully, otherwise NO along with a populated error object
*
*
* This method has to locate the trash directory and uses an intermediate temporary directory before trashing the item.
* A copy may have to be done if the url is not on the same volume as the running user's trash directory.
* If a failure occurs in the middle of this operation, the item to remove may be lost forever or stuck in a temporary location.
*
* This is not an atomic operation, nor intended to be a recoverable operation if the worst comes to worst.
*/
- (BOOL)moveItemAtURLToTrash:(NSURL *)url error:(NSError **)error;
- (BOOL)copyItemAtURL:(NSURL *)sourceURL toURL:(NSURL *)destinationURL error:(NSError *_Nullable*_Nullable)error;
/**
* Removes an item at a URL
@@ -83,7 +95,7 @@
*
* This is not an atomic operation.
*/
- (BOOL)removeItemAtURL:(NSURL *)url error:(NSError **)error;
- (BOOL)removeItemAtURL:(NSURL *)url error:(NSError *_Nullable*_Nullable)error;
/**
* Changes the owner and group IDs of an item at a specified target URL to match another URL
@@ -98,7 +110,7 @@
*
* This is not an atomic operation.
*/
- (BOOL)changeOwnerAndGroupOfItemAtRootURL:(NSURL *)targetURL toMatchURL:(NSURL *)matchURL error:(NSError **)error;
- (BOOL)changeOwnerAndGroupOfItemAtRootURL:(NSURL *)targetURL toMatchURL:(NSURL *)matchURL error:(NSError *_Nullable*_Nullable)error;
/**
* Updates the modification and access time of an item at a specified target URL to the current time
@@ -111,7 +123,7 @@
*
* This is not an atomic operation.
*/
- (BOOL)updateModificationAndAccessTimeOfItemAtURL:(NSURL *)targetURL error:(NSError **)error;
- (BOOL)updateModificationAndAccessTimeOfItemAtURL:(NSURL *)targetURL error:(NSError *_Nullable*_Nullable)error;
/**
* Releases Apple's quarantine extended attribute from the item at the specified root URL
@@ -120,8 +132,8 @@
* @return YES if all the items at the target could be released from quarantine, otherwise NO if any items couldn't along with a populated error object
*
* This method removes quarantine attributes from an item, ideally an application, so that when the user launches a new application themselves, they
* don't have to witness the OS X dialog alerting them that they downloaded an application from the internet and asking if they want to continue.
* Note that this may not exactly mimic OS X's behavior when a user opens an application for the first time (i.e, the xattr isn't deleted),
* don't have to witness the system dialog alerting them that they downloaded an application from the internet and asking if they want to continue.
* Note that this may not exactly mimic the system behavior when a user opens an application for the first time (i.e, the xattr isn't deleted),
* but this should be sufficient enough for our purposes.
*
* This method may return NO even if some items do get released from quarantine if the target URL is pointing to a directory.
@@ -129,6 +141,20 @@
*
* This is not an atomic operation.
*/
- (BOOL)releaseItemFromQuarantineAtRootURL:(NSURL *)rootURL error:(NSError **)error;
- (BOOL)releaseItemFromQuarantineAtRootURL:(NSURL *)rootURL error:(NSError *_Nullable*_Nullable)error;
/**
* Runs an installer package (pkg) in a headless mode using /usr/sbin/installer
* @param packageURL A URL pointing to the package to execute. The item at this URL must exist.
* @param error If an error occurs, upon returns contains an NSError object that describes the problem. If you are not interested in possible errors, you may pass in NULL.
* @return YES if the installer ran the package successfully, otherwise NO with a populated error object
*
* This method uses the system wide installer tool to run the provided package. This process does not show any UI, except for
* an initial authorization prompt if the calling process does not have root privileges. In other words, root privileges are required to use this method, and the file manager instance must have been created by allowing authorization.
* An error can occur if the package is unable to be ran by the installer, or if the installer reports a non-zero exit status code.
*/
- (BOOL)executePackageAtURL:(NSURL *)packageURL error:(NSError *_Nullable*_Nullable)error;
NS_ASSUME_NONNULL_END
@end
+213 -177
View File
@@ -7,38 +7,19 @@
//
#import "SUFileManager.h"
#import "SUErrors.h"
#import "SUOperatingSystem.h"
#import "SUFileOperationConstants.h"
#include <sys/xattr.h>
#include <sys/errno.h>
#include <sys/time.h>
#include "AppKitPrevention.h"
static char SUAppleQuarantineIdentifier[] = "com.apple.quarantine";
// Authorization code based on generous contribution from Allan Odgaard. Thanks, Allan!
static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authorization, const char *executablePath, AuthorizationFlags options, char *const *arguments)
{
sig_t oldSigChildHandler = signal(SIGCHLD, SIG_DFL);
BOOL returnValue = YES;
#pragma clang diagnostic push
// In the future, we may have to look at SMJobBless API to avoid deprecation. See issue #558
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
if (AuthorizationExecuteWithPrivileges(authorization, executablePath, options, arguments, NULL) == errAuthorizationSuccess)
#pragma clang diagnostic pop
{
int status;
pid_t pid = wait(&status);
if (pid == -1 || !WIFEXITED(status) || WEXITSTATUS(status) != 0)
returnValue = NO;
}
else
returnValue = NO;
signal(SIGCHLD, oldSigChildHandler);
return returnValue;
}
static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
char path[PATH_MAX] = {0};
@@ -75,26 +56,37 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
{
AuthorizationRef _auth;
NSFileManager *_fileManager;
BOOL _allowsAuthorization;
NSString *_authorizationToolPath;
}
- (instancetype)initAllowingAuthorization:(BOOL)allowsAuthorization
- (instancetype)initWithAuthorizationToolPath:(NSString *)authorizationToolPath
{
self = [super init];
if (self != nil) {
_fileManager = [[NSFileManager alloc] init];
_allowsAuthorization = allowsAuthorization;
_authorizationToolPath = [authorizationToolPath copy];
}
return self;
}
+ (instancetype)fileManagerAllowingAuthorization:(BOOL)allowsAuthorization
+ (instancetype)defaultManager
{
return [[self alloc] initAllowingAuthorization:allowsAuthorization];
return [[self alloc] initWithAuthorizationToolPath:nil];
}
// Acquires an authorization reference which is intended to be used for future authorized file operations
+ (instancetype)fileManagerWithAuthorizationToolPath:(NSString *)authorizationToolPath
{
return [[self alloc] initWithAuthorizationToolPath:authorizationToolPath];
}
- (instancetype)fileManagerByPreservingAuthorizationRights
{
// Check if we don't allow authorization, or that we haven't needed to authorize yet, to create or re-use a
// file manager instance with these restrictions
return (_authorizationToolPath != nil && _auth != NULL) ? self : [SUFileManager defaultManager];
}
// Acquires an authorization reference with root privileges which is intended to be used for authorized file operations
- (BOOL)_acquireAuthorizationWithError:(NSError *__autoreleasing *)error
{
// No need to continue if we already acquired an authorization reference
@@ -102,21 +94,112 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
return YES;
}
if (!_allowsAuthorization) {
if (_authorizationToolPath == nil) {
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: @"Unable to grant authorization to perform action because it is explicitly turned off" }];
}
return NO;
}
OSStatus status = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &_auth);
if (status != errAuthorizationSuccess) {
OSStatus createStatus = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &_auth);
if (createStatus != errAuthorizationSuccess) {
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed creating authorization reference with status code %d.", status] }];
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed creating authorization reference with status code %d.", createStatus] }];
}
_auth = NULL;
return NO;
}
AuthorizationItem rightItems[] = {
// The right that allows us to run tools as root user
{.name = kAuthorizationRightExecute, .valueLength = 0, .value = NULL, .flags = 0}
};
AuthorizationRights rights = {
.count = sizeof(rightItems) / sizeof(*rightItems),
.items = rightItems
};
AuthorizationFlags flags =
(AuthorizationFlags)(kAuthorizationFlagDefaults | kAuthorizationFlagInteractionAllowed | kAuthorizationFlagExtendRights | kAuthorizationFlagPreAuthorize);
// This will test if we can gain authorization for running utlities as root
OSStatus copyStatus = AuthorizationCopyRights(_auth, &rights, kAuthorizationEmptyEnvironment, flags, NULL);
if (copyStatus != errAuthorizationSuccess) {
if (error != NULL) {
if (copyStatus == errAuthorizationCanceled) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationCancelledError userInfo:@{ NSLocalizedDescriptionKey: @"Authorization access was cancelled by the user." }];
} else {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed granting authorization rights with status code %d.", copyStatus] }];
}
}
AuthorizationFree(_auth, kAuthorizationFlagDefaults);
_auth = NULL;
return NO;
}
return YES;
}
- (BOOL)_authorizeAndExecuteCommand:(char *)command sourcePath:(char *)sourcePath destinationPath:(char *)destinationPath error:(NSError * __autoreleasing *)error
{
NSError *acquireError = nil;
if (![self _acquireAuthorizationWithError:&acquireError]) {
if (error != NULL) {
*error = acquireError;
}
return NO;
}
char *arguments[] = { command, sourcePath, destinationPath, NULL };
char toolPath[PATH_MAX] = {0};
if (![_authorizationToolPath getFileSystemRepresentation:toolPath maxLength:sizeof(toolPath)]) {
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Authorization tool (%@) cannot be represented as a valid file name.", _authorizationToolPath.lastPathComponent] }];
}
return NO;
}
FILE *pipe = NULL;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
if (AuthorizationExecuteWithPrivileges(_auth, toolPath, kAuthorizationFlagDefaults, arguments, &pipe) != errAuthorizationSuccess) {
#pragma clang diagnostic pop
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:@"Failed to run authorization tool." }];
}
return NO;
}
uint32_t pidData = 0;
if (fread(&pidData, sizeof(pidData), 1, pipe) < 1) {
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:@"Failed to retrieve authorized executable process identifier." }];
}
fclose(pipe);
return NO;
}
pid_t childPid = (int32_t)CFSwapInt32LittleToHost(pidData);
int status = 0;
pid_t waitResult;
do {
waitResult = waitpid(childPid, &status, 0);
} while (waitResult == -1 && errno == EINTR);
fclose(pipe);
if (waitResult == -1 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Failed to execute authorized executable with result %d and status (%d, %d, %d).", waitResult, status, WIFEXITED(status), WEXITSTATUS(status)] }];
}
return NO;
}
return YES;
}
@@ -151,7 +234,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
}
if (isDirectory != NULL) {
*isDirectory = [attributes[NSFileType] isEqualToString:NSFileTypeDirectory];
*isDirectory = [[attributes objectForKey:NSFileType] isEqualToString:NSFileTypeDirectory];
}
return YES;
@@ -183,7 +266,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
#define XATTR_UTILITY_PATH "/usr/bin/xattr"
// Recursively remove an xattr at a specified root URL with authentication
- (BOOL)_removeXAttrWithAuthentication:(char *__nonnull)xattrName fromRootURL:(NSURL *)rootURL error:(NSError *__autoreleasing *)error
- (BOOL)_removeQuarantineWithAuthenticationAtRootURL:(NSURL *)rootURL error:(NSError *__autoreleasing *)error
{
// Because this is a system utility, it's fine to follow the symbolic link if one exists
if (![_fileManager fileExistsAtPath:@(XATTR_UTILITY_PATH)]) {
@@ -200,16 +283,11 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
}
return NO;
}
if (![self _acquireAuthorizationWithError:error]) {
return NO;
}
BOOL success = AuthorizationExecuteWithPrivilegesAndWait(_auth, XATTR_UTILITY_PATH, kAuthorizationFlagDefaults, (char *[]){ "-s", "-r", "-d", xattrName, path, NULL });
NSError *executeError = nil;
BOOL success = [self _authorizeAndExecuteCommand:SUFileOpRemoveQuarantineCommand sourcePath:path destinationPath:NULL error:&executeError];
if (!success && error != NULL) {
NSString *errorMessage = [NSString stringWithFormat:@"Authenticated extended attribute deletion for %@ failed on %@.", [NSString stringWithUTF8String:xattrName], rootURL.path.lastPathComponent];
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:errorMessage }];
*error = executeError;
}
return success;
@@ -234,7 +312,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
removedQuarantine = YES;
} else {
if (isAccessError(removalError)) {
removedQuarantine = [self _removeXAttrWithAuthentication:SUAppleQuarantineIdentifier fromRootURL:rootURL error:error];
removedQuarantine = [self _removeQuarantineWithAuthenticationAtRootURL:rootURL error:error];
attemptedAuthentication = YES;
} else {
if (success != NULL) {
@@ -267,7 +345,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
// root-level symbolic link.
NSString *rootURLPath = rootURL.path;
NSDictionary *rootAttributes = [_fileManager attributesOfItemAtPath:rootURLPath error:nil];
NSString *rootType = rootAttributes[NSFileType];
NSString *rootType = [rootAttributes objectForKey:NSFileType]; // 10.7 can't subscript this
if ([rootType isEqualToString:NSFileTypeDirectory]) {
// The NSDirectoryEnumerator will avoid recursing into any contained
@@ -286,7 +364,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
}
// Removes the directory tree rooted at |root| from the file quarantine.
// The quarantine was introduced on OS X 10.5 and is described at:
// The quarantine was introduced on macOS 10.5 and is described at:
//
// http://developer.apple.com/releasenotes/Carbon/RN-LaunchServices/index.html#apple_ref/doc/uid/TP40001369-DontLinkElementID_2
//
@@ -388,11 +466,6 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
return NO;
}
if (![self _acquireAuthorizationWithError:error]) {
return NO;
}
char sourcePath[PATH_MAX] = {0};
if (![sourceURL.path getFileSystemRepresentation:sourcePath maxLength:sizeof(sourcePath)]) {
if (error != NULL) {
@@ -408,11 +481,11 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
}
return NO;
}
if (!AuthorizationExecuteWithPrivilegesAndWait(_auth, "/bin/cp", kAuthorizationFlagDefaults, (char *[]){ "-Rf", "--", sourcePath, destinationPath, NULL })) {
NSError *executeError = nil;
if (![self _authorizeAndExecuteCommand:SUFileOpCopyCommand sourcePath:sourcePath destinationPath:destinationPath error:&executeError]) {
if (error != NULL) {
NSString *errorMessage = [NSString stringWithFormat:@"Failed to perform authenticated file copy for %@.", sourceURL.lastPathComponent];
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:errorMessage }];
*error = executeError;
}
return NO;
}
@@ -501,10 +574,6 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
return NO;
}
if (![self _acquireAuthorizationWithError:error]) {
return NO;
}
char sourcePath[PATH_MAX] = {0};
if (![sourceURL.path getFileSystemRepresentation:sourcePath maxLength:sizeof(sourcePath)]) {
if (error != NULL) {
@@ -520,11 +589,12 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
}
return NO;
}
if (!AuthorizationExecuteWithPrivilegesAndWait(_auth, "/bin/mv", kAuthorizationFlagDefaults, (char *[]){ "-f", "--", sourcePath, destinationPath, NULL })) {
NSError *executeError = nil;
if (![self _authorizeAndExecuteCommand:SUFileOpMoveCommand sourcePath:sourcePath destinationPath:destinationPath error:&executeError]) {
if (error != NULL) {
NSString *errorMessage = [NSString stringWithFormat:@"Failed to perform authenticated file move for %@.", sourceURL.lastPathComponent];
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:errorMessage }];
NSString *errorMessage = [NSString stringWithFormat:@"Failed to perform authorized file move for %@.", sourceURL.lastPathComponent];
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:errorMessage, NSUnderlyingErrorKey: executeError }];
}
return NO;
}
@@ -542,7 +612,19 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
return NO;
}
if (chown(path, ownerID.unsignedIntValue, groupID.unsignedIntValue) != 0) {
int fileDescriptor = open(path, O_RDONLY | O_SYMLINK);
if (fileDescriptor == -1) {
if (error != NULL) {
*error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to open file descriptor to %@", targetURL.path.lastPathComponent] }];
}
return NO;
}
// We use fchown instead of chown because the latter can follow symbolic links
BOOL success = fchown(fileDescriptor, ownerID.unsignedIntValue, groupID.unsignedIntValue) == 0;
close(fileDescriptor);
if (!success) {
if (errno == EPERM) {
if (needsAuth != NULL) {
*needsAuth = YES;
@@ -595,7 +677,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
return NO;
}
NSNumber *ownerID = matchFileAttributes[NSFileOwnerAccountID];
NSNumber *ownerID = [matchFileAttributes objectForKey:NSFileOwnerAccountID];
if (ownerID == nil) {
// shouldn't be possible to error here, but just in case
if (error != NULL) {
@@ -604,7 +686,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
return NO;
}
NSNumber *groupID = matchFileAttributes[NSFileGroupOwnerAccountID];
NSNumber *groupID = [matchFileAttributes objectForKey:NSFileGroupOwnerAccountID];
if (groupID == nil) {
// shouldn't be possible to error here, but just in case
if (error != NULL) {
@@ -613,8 +695,8 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
return NO;
}
NSNumber *targetOwnerID = targetFileAttributes[NSFileOwnerAccountID];
NSNumber *targetGroupID = targetFileAttributes[NSFileGroupOwnerAccountID];
NSNumber *targetOwnerID = [targetFileAttributes objectForKey:NSFileOwnerAccountID];
NSNumber *targetGroupID = [targetFileAttributes objectForKey:NSFileGroupOwnerAccountID];
if ((targetOwnerID != nil && [ownerID isEqualToNumber:targetOwnerID]) && (targetGroupID != nil && [groupID isEqualToNumber:targetGroupID])) {
// Assume they're the same even if we don't check every file recursively
@@ -652,21 +734,20 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
}
return NO;
}
char userAndGroup[100];
int written = snprintf(userAndGroup, sizeof(userAndGroup), "%u:%u", ownerID.unsignedIntValue, groupID.unsignedIntValue);
if (written < 0 || written >= 100) {
return NO; // No custom error, because it's too unlikely to ever happen
}
if (![self _acquireAuthorizationWithError:error]) {
char matchPath[PATH_MAX] = {0};
if (![matchURLPath getFileSystemRepresentation:matchPath maxLength:sizeof(matchPath)]) {
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Match file (%@) cannot be represented as a valid file name.", matchURL.path.lastPathComponent] }];
}
return NO;
}
BOOL success = AuthorizationExecuteWithPrivilegesAndWait(_auth, "/usr/sbin/chown", kAuthorizationFlagDefaults, (char *[]){ "-R", userAndGroup, targetPath, NULL });
NSError *executeError = nil;
BOOL success = [self _authorizeAndExecuteCommand:SUFileOpChangeOwnerAndGroupCommand sourcePath:targetPath destinationPath:matchPath error:&executeError];
if (!success && error != NULL) {
NSString *errorMessage = [NSString stringWithFormat:@"Failed to change owner:group %@ on %@ with authentication.", [NSString stringWithUTF8String:userAndGroup], targetURL.path.lastPathComponent];
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: errorMessage }];
NSString *errorMessage = [NSString stringWithFormat:@"Failed to change owner & group on %@ to match %@ with authorization.", targetURL.path.lastPathComponent, matchURLPath.lastPathComponent];
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: errorMessage, NSUnderlyingErrorKey: executeError }];
}
return success;
@@ -695,7 +776,20 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
return NO;
}
if (utimes(path, NULL) == 0) {
int fileDescriptor = open(path, O_RDONLY | O_SYMLINK);
if (fileDescriptor == -1) {
if (error != NULL) {
*error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to open file descriptor to %@", targetURL.path.lastPathComponent] }];
}
return NO;
}
// Using futimes() because utimes() follows symbolic links
BOOL updatedTime = (futimes(fileDescriptor, NULL) == 0);
close(fileDescriptor);
if (updatedTime) {
return YES;
}
@@ -705,15 +799,12 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
}
return NO;
}
if (![self _acquireAuthorizationWithError:error]) {
return NO;
}
BOOL success = AuthorizationExecuteWithPrivilegesAndWait(_auth, "/usr/bin/touch", kAuthorizationFlagDefaults, (char *[]){ "--", path, NULL });
NSError *executeError = nil;
BOOL success = [self _authorizeAndExecuteCommand:SUFileOpUpdateModificationAndAccessTimeCommand sourcePath:path destinationPath:NULL error:&executeError];
if (!success && error != NULL) {
NSString *errorMessage = [NSString stringWithFormat:@"Failed to update modification & access time on %@ with authentication.", targetURL.path.lastPathComponent];
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: errorMessage }];
NSString *errorMessage = [NSString stringWithFormat:@"Failed to update modification & access time on %@ with authorization.", targetURL.path.lastPathComponent];
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: errorMessage, NSUnderlyingErrorKey: executeError }];
}
return success;
@@ -721,7 +812,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
// Creates a directory at the item pointed by url
// An item cannot already exist at the url, but the parent must be a directory that exists
- (BOOL)_makeDirectoryAtURL:(NSURL *)url error:(NSError * __autoreleasing *)error
- (BOOL)makeDirectoryAtURL:(NSURL *)url error:(NSError * __autoreleasing *)error
{
if ([self _itemExistsAtURL:url]) {
if (error != NULL) {
@@ -758,16 +849,16 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
}
return NO;
}
if (![self _acquireAuthorizationWithError:error]) {
return NO;
}
BOOL success = AuthorizationExecuteWithPrivilegesAndWait(_auth, "/bin/mkdir", kAuthorizationFlagDefaults, (char *[]){ "--", path, NULL });
if (!success && error != NULL) {
NSString *errorMessage = [NSString stringWithFormat:@"Failed to make directory %@ with authentication.", url.path.lastPathComponent];
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: errorMessage }];
NSError *executeError = nil;
BOOL success = [self _authorizeAndExecuteCommand:SUFileOpMakeDirectoryCommand sourcePath:path destinationPath:NULL error:&executeError];
if (!success) {
if (error != NULL) {
NSString *errorMessage = [NSString stringWithFormat:@"Failed to make directory %@ with authorization.", url.path.lastPathComponent];
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: errorMessage, NSUnderlyingErrorKey: executeError }];
}
}
return success;
}
@@ -789,7 +880,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
desiredURL = [directoryURL URLByAppendingPathComponent:[preferredName stringByAppendingFormat:@" (%lu)", (unsigned long)++tagIndex]];
}
return [self _makeDirectoryAtURL:desiredURL error:error] ? desiredURL : nil;
return [self makeDirectoryAtURL:desiredURL error:error] ? desiredURL : nil;
}
- (BOOL)removeItemAtURL:(NSURL *)url error:(NSError * __autoreleasing *)error
@@ -813,10 +904,6 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
return NO;
}
if (![self _acquireAuthorizationWithError:error]) {
return NO;
}
char path[PATH_MAX] = {0};
if (![url.path getFileSystemRepresentation:path maxLength:sizeof(path)]) {
if (error != NULL) {
@@ -824,93 +911,42 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
}
return NO;
}
NSError *executeError = nil;
BOOL success = [self _authorizeAndExecuteCommand:SUFileOpRemoveCommand sourcePath:path destinationPath:NULL error:&executeError];
BOOL success = AuthorizationExecuteWithPrivilegesAndWait(_auth, "/bin/rm", kAuthorizationFlagDefaults, (char *[]){ "-rf", "--", path, NULL });
if (!success && error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to remove %@ with authentication.", url.path.lastPathComponent] }];
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to remove %@ with authentication.", url.path.lastPathComponent], NSUnderlyingErrorKey: executeError }];
}
return success;
}
- (BOOL)moveItemAtURLToTrash:(NSURL *)url error:(NSError *__autoreleasing *)error
// Unlike other methods, authorization is required to execute this method successfully
- (BOOL)executePackageAtURL:(NSURL *)packageURL error:(NSError * __autoreleasing *)error
{
if (![self _itemExistsAtURL:url]) {
if (![self _itemExistsAtURL:packageURL]) {
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileNoSuchFileError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to move %@ to the trash because the file does not exist.", url.path.lastPathComponent] }];
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileNoSuchFileError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to execute package %@ because the file does not exist.", packageURL.path.lastPathComponent] }];
}
return NO;
}
NSURL *trashURL = nil;
BOOL canUseNewTrashAPI = YES;
#if __MAC_OS_X_VERSION_MIN_REQUIRED < 1080
canUseNewTrashAPI = [SUOperatingSystem isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){10, 8, 0}];
if (!canUseNewTrashAPI) {
FSRef trashRef;
if (FSFindFolder(kUserDomain, kTrashFolderType, kDontCreateFolder, &trashRef) == noErr) {
trashURL = CFBridgingRelease(CFURLCreateFromFSRef(kCFAllocatorDefault, &trashRef));
}
}
#endif
if (canUseNewTrashAPI) {
trashURL = [_fileManager URLForDirectory:NSTrashDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
}
if (trashURL == nil) {
char path[PATH_MAX] = {0};
if (![packageURL.path getFileSystemRepresentation:path maxLength:sizeof(path)]) {
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileNoSuchFileError userInfo:@{ NSLocalizedDescriptionKey: @"Failed to locate the user's trash folder." }];
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Package to execute (%@) cannot be represented as a valid file name.", packageURL.path.lastPathComponent] }];
}
return NO;
}
// In the rare worst case scenario, our temporary directory will be labeled incomplete and be in the user's trash directory,
// indicating that whatever inside of there is not yet completely moved.
// Regardless, we want the item to be in our Volume before we try moving it to the trash
NSString *preferredName = [url.lastPathComponent.stringByDeletingPathExtension stringByAppendingString:@" (Incomplete Files)"];
NSURL *tempDirectory = [self makeTemporaryDirectoryWithPreferredName:preferredName appropriateForDirectoryURL:trashURL error:error];
if (tempDirectory == nil) {
return NO;
NSError *executeError = nil;
BOOL success = [self _authorizeAndExecuteCommand:SUFileOpInstallCommand sourcePath:path destinationPath:NULL error:&executeError];
if (!success && error != NULL) {
NSString* errorMessage = @"Failed to execute package installer.";
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{NSLocalizedDescriptionKey: errorMessage, NSUnderlyingErrorKey: executeError}];
}
NSString *urlLastPathComponent = url.lastPathComponent;
NSURL *tempItemURL = [tempDirectory URLByAppendingPathComponent:urlLastPathComponent];
if (![self moveItemAtURL:url toURL:tempItemURL error:error]) {
// If we can't move the item at url, just remove it completely; chances are it's not going to be missed
[self removeItemAtURL:url error:NULL];
[self removeItemAtURL:tempDirectory error:NULL];
return NO;
}
if (![self changeOwnerAndGroupOfItemAtRootURL:tempItemURL toMatchURL:trashURL error:error]) {
// Removing the item inside of the temp directory is better than trying to move the item to the trash with incorrect ownership
[self removeItemAtURL:tempDirectory error:NULL];
return NO;
}
// If we get here, we should be able to trash the item normally without authentication
BOOL success = NO;
#if __MAC_OS_X_VERSION_MIN_REQUIRED < 1080
if (!canUseNewTrashAPI) {
NSString *tempParentPath = tempItemURL.URLByDeletingLastPathComponent.path;
success = [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:tempParentPath destination:@"" files:@[tempItemURL.lastPathComponent] tag:NULL];
if (!success && error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileNoSuchFileError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to move file %@ into the trash.", tempItemURL.lastPathComponent] }];
}
}
#endif
if (canUseNewTrashAPI) {
NSError *trashError = nil;
success = [_fileManager trashItemAtURL:tempItemURL resultingItemURL:NULL error:&trashError];
if (!success && error != NULL) {
*error = trashError;
}
}
[self removeItemAtURL:tempDirectory error:NULL];
return success;
}
+8 -10
View File
@@ -11,7 +11,7 @@
A guided installation allows Sparkle to download and install a package (pkg) or multi-package (mpkg) without user interaction.
The installer package is installed using Mac OS X's built-in command line installer, `/usr/sbin/installer`. No installation interface is shown to the user.
The installer package is installed using macOS's built-in command line installer, `/usr/sbin/installer`. No installation interface is shown to the user.
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.
@@ -19,17 +19,15 @@ A guided installation can be started by applications other than the application
- Replace the use of `AuthorizationExecuteWithPrivilegesAndWait`. This method remains because it is well supported and tested. Ideally a helper tool or XPC would be used.
*/
#ifndef SUGUIDEDPACKAGEINSTALLER_H
#define SUGUIDEDPACKAGEINSTALLER_H
#import <Foundation/Foundation.h>
#import "Sparkle.h"
#import "SUInstaller.h"
#import "SUInstallerProtocol.h"
@interface SUGuidedPackageInstaller : SUInstaller
NS_ASSUME_NONNULL_BEGIN
@interface SUGuidedPackageInstaller : NSObject <SUInstallerProtocol>
- (instancetype)initWithPackagePath:(NSString *)packagePath installationPath:(NSString *)installationPath fileOperationToolPath:(NSString *)fileOperationToolPath;
/*! Perform the guided installation */
+ (void)performInstallationToPath:(NSString *)path fromPath:(NSString *)installerGuide host:(SUHost *)host versionComparator:(id<SUVersionComparison>)comparator completionHandler:(void (^)(NSError *))completionHandler;
@end
#endif
NS_ASSUME_NONNULL_END
+33 -120
View File
@@ -6,139 +6,52 @@
// Copyright 2010 Dragon Systems Software Limited. All rights reserved.
//
#import <sys/stat.h>
#import <Security/Security.h>
#import "SUGuidedPackageInstaller.h"
#import "SUFileManager.h"
static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authorization, const char* executablePath, AuthorizationFlags options, char* const* arguments)
{
sig_t oldSigChildHandler = signal(SIGCHLD, SIG_DFL);
BOOL returnValue = YES;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
/* AuthorizationExecuteWithPrivileges used to support 10.4+; should be replaced with XPC or external process */
if (AuthorizationExecuteWithPrivileges(authorization, executablePath, options, arguments, NULL) == errAuthorizationSuccess)
#pragma clang diagnostic pop
{
int status = 0;
pid_t pid = wait(&status);
if (pid == -1 || !WIFEXITED(status) || WEXITSTATUS(status) != 0)
returnValue = NO;
}
else
returnValue = NO;
signal(SIGCHLD, oldSigChildHandler);
return returnValue;
}
@implementation SUGuidedPackageInstaller (SUGuidedPackageInstallerAuthentication)
#include "AppKitPrevention.h"
+ (AuthorizationRef)authorizationForExecutable:(NSString*)executablePath
{
SUParameterAssert(executablePath);
// Get authorization using advice in Apple's Technical Q&A1172
// ...create authorization without specific rights
AuthorizationRef auth = NULL;
OSStatus validAuth = AuthorizationCreate(NULL,
kAuthorizationEmptyEnvironment,
kAuthorizationFlagDefaults,
&auth);
// ...then extend authorization with desired rights
if ((validAuth == errAuthorizationSuccess) &&
(auth != NULL))
{
char executableFileSystemRepresentation[PATH_MAX];
[executablePath getFileSystemRepresentation:executableFileSystemRepresentation maxLength:sizeof(executableFileSystemRepresentation)];
// Prepare a right allowing script to execute with privileges
AuthorizationItem right = {
.name = kAuthorizationRightExecute,
.value = executableFileSystemRepresentation,
.valueLength = strlen(executableFileSystemRepresentation),
};
// Package up the single right
AuthorizationRights rights;
memset(&rights,0,sizeof(rights));
rights.count = 1;
rights.items = &right;
// Extend rights to run script
validAuth = AuthorizationCopyRights(auth,
&rights,
kAuthorizationEmptyEnvironment,
(AuthorizationFlags)
(kAuthorizationFlagPreAuthorize |
kAuthorizationFlagExtendRights |
kAuthorizationFlagInteractionAllowed),
NULL);
if (validAuth != errAuthorizationSuccess)
{
// Error, clean up authorization
(void) AuthorizationFree(auth,kAuthorizationFlagDefaults);
auth = NULL;
}
}
return auth;
}
@interface SUGuidedPackageInstaller ()
@property (nonatomic, readonly, copy) NSString *packagePath;
@property (nonatomic, readonly, copy) NSString *installationPath;
@property (nonatomic, readonly, copy) NSString *fileOperationToolPath;
@end
@implementation SUGuidedPackageInstaller
+ (void)performInstallationToPath:(NSString *)destinationPath fromPath:(NSString *)packagePath host:(SUHost *)__unused host versionComparator:(id<SUVersionComparison>)__unused comparator completionHandler:(void (^)(NSError *))completionHandler
@synthesize packagePath = _packagePath;
@synthesize installationPath = _installationPath;
@synthesize fileOperationToolPath = _fileOperationToolPath;
- (instancetype)initWithPackagePath:(NSString *)packagePath installationPath:(NSString *)installationPath fileOperationToolPath:(NSString *)fileOperationToolPath
{
SUParameterAssert(packagePath);
self = [super init];
if (self != nil) {
_packagePath = [packagePath copy];
_installationPath = [installationPath copy];
_fileOperationToolPath = [fileOperationToolPath copy];
}
return self;
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
- (BOOL)performInitialInstallation:(NSError * __autoreleasing *)__unused error
{
return YES;
}
// Preflight
NSString* installerPath = @"/usr/sbin/installer"; // Mac OS X 10.2+ command line installer tool
NSError* error = nil;
- (BOOL)performFinalInstallation:(NSError * __autoreleasing *)error
{
SUFileManager *fileManager = [SUFileManager fileManagerWithAuthorizationToolPath:self.fileOperationToolPath];
return [fileManager executePackageAtURL:[NSURL fileURLWithPath:self.packagePath] error:error];
}
// Create authorization for installer executable
BOOL validInstallation = NO;
AuthorizationRef auth = [self authorizationForExecutable:installerPath];
if (auth != NULL)
{
char pathBuffer[PATH_MAX] = {0};
[packagePath getFileSystemRepresentation:pathBuffer maxLength:sizeof(pathBuffer)];
// Permission was granted to execute the installer with privileges
char * const arguments[] = {
"-pkg",
pathBuffer,
"-target",
"/",
NULL
};
validInstallation = AuthorizationExecuteWithPrivilegesAndWait(auth,
[installerPath fileSystemRepresentation],
kAuthorizationFlagDefaults,
arguments);
// TODO: wait for communications pipe to close via fileno & CFSocketCreateWithNative
AuthorizationFree(auth,kAuthorizationFlagDefaults);
}
else
{
NSString* errorMessage = [NSString stringWithFormat:@"Sparkle Updater: Script authorization denied."];
error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:[NSDictionary dictionaryWithObject:errorMessage forKey:NSLocalizedDescriptionKey]];
}
dispatch_async(dispatch_get_main_queue(), ^{
[self finishInstallationToPath:destinationPath
withResult:validInstallation
error:error
completionHandler:completionHandler];
});
});
- (BOOL)canInstallSilently
{
return YES;
}
@end
+1 -18
View File
@@ -6,18 +6,6 @@
//
#import <Foundation/Foundation.h>
#import "SUUpdater.h"
#import "SUAppcast.h"
#import "SUAppcastItem.h"
#import "SUVersionComparisonProtocol.h"
#if __MAC_OS_X_VERSION_MAX_ALLOWED < 101000
typedef struct {
NSInteger majorVersion;
NSInteger minorVersion;
NSInteger patchVersion;
} NSOperatingSystemVersion;
#endif
@interface SUHost : NSObject
@@ -25,17 +13,12 @@ typedef struct {
- (instancetype)initWithBundle:(NSBundle *)aBundle;
@property (readonly, copy) NSString *bundlePath;
@property (readonly) BOOL allowsAutomaticUpdates;
@property (readonly, copy) NSString *appCachePath;
@property (readonly, copy) NSString *installationPath;
@property (readonly, copy) NSString *name;
@property (readonly, copy) NSString *version;
@property (readonly, copy) NSString *displayVersion;
@property (readonly, copy) NSImage *icon;
@property (getter=isRunningOnReadOnlyVolume, readonly) BOOL runningOnReadOnlyVolume;
@property (getter=isBackgroundApplication, readonly) BOOL backgroundApplication;
@property (readonly, copy) NSString *publicDSAKey;
@property (readonly, copy) NSArray *systemProfile;
@property (readonly, nonatomic, copy) NSString *publicDSAKeyFileKey;
- (id)objectForInfoDictionaryKey:(NSString *)key;
- (BOOL)boolForInfoDictionaryKey:(NSString *)key;
+14 -86
View File
@@ -8,15 +8,17 @@
#import "SUHost.h"
#import "SUConstants.h"
#import "SUSystemProfiler.h"
#include <sys/mount.h> // For statfs for isRunningOnReadOnlyVolume
#import "SULog.h"
#if __MAC_OS_X_VERSION_MAX_ALLOWED < 101000
@interface NSProcessInfo ()
- (NSOperatingSystemVersion)operatingSystemVersion;
@end
#endif
#include "AppKitPrevention.h"
// This class should not rely on AppKit and should also be process independent
// For example, it should not have code that tests writabilty to somewhere on disk,
// as that may depend on the privileges of the process owner. Or code that depends on
// if the process is sandboxed or not; eg: finding the user's caches directory. Or code that depends
// on compilation flags and if other files exist relative to the host bundle.
@interface SUHost ()
@@ -36,7 +38,7 @@
{
if ((self = [super init]))
{
SUParameterAssert(aBundle);
NSParameterAssert(aBundle);
self.bundle = aBundle;
if (![self.bundle bundleIdentifier]) {
SULog(@"Error: the bundle being updated at %@ has no %@! This will cause preference read/write to not work properly.", self.bundle, kCFBundleIdentifierKey);
@@ -55,60 +57,13 @@
}
- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@, %@>", [self class], [self bundlePath], [self installationPath]]; }
- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], [self bundlePath]]; }
- (NSString *)bundlePath
{
return [self.bundle bundlePath];
}
- (BOOL)allowsAutomaticUpdates
{
// Does the developer want us to disable automatic updates?
NSNumber *developerAllowsAutomaticUpdates = [self objectForInfoDictionaryKey:SUAllowsAutomaticUpdatesKey];
if (developerAllowsAutomaticUpdates != nil && !developerAllowsAutomaticUpdates.boolValue) {
return NO;
}
// Can we automatically update in the background without bugging the user (e.g, with a administrator password prompt)?
return [[NSFileManager defaultManager] isWritableFileAtPath:self.bundlePath];
}
- (NSString *)appCachePath
{
NSArray *cachePaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachePath = nil;
if ([cachePaths count]) {
cachePath = cachePaths[0];
}
if (!cachePath) {
SULog(@"Failed to find user's cache directory! Using system default");
cachePath = NSTemporaryDirectory();
}
NSString *name = [self.bundle bundleIdentifier];
if (!name) {
name = [self name];
}
cachePath = [cachePath stringByAppendingPathComponent:name];
cachePath = [cachePath stringByAppendingPathComponent:@"Sparkle"];
return cachePath;
}
- (NSString *)installationPath
{
if (SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME) {
// We'll install to "#{CFBundleName}.app", but only if that path doesn't already exist. If we're "Foo 4.2.app," and there's a "Foo.app" in this directory, we don't want to overwrite it! But if there's no "Foo.app," we'll take that name.
NSString *normalizedAppPath = [[[self.bundle bundlePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", [self.bundle objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleNameKey], [[self.bundle bundlePath] pathExtension]]];
if (![[NSFileManager defaultManager] fileExistsAtPath:normalizedAppPath]) {
return normalizedAppPath;
}
}
return [self.bundle bundlePath];
}
- (NSString *__nonnull)name
{
NSString *name;
@@ -143,29 +98,6 @@
return [self version]; // Fall back on the normal version string.
}
- (NSImage *__nonnull)icon
{
// Cache the application icon.
NSString *iconPath = [self.bundle pathForResource:[self.bundle objectForInfoDictionaryKey:@"CFBundleIconFile"] ofType:@"icns"];
// According to the OS X docs, "CFBundleIconFile - This key identifies the file containing
// the icon for the bundle. The filename you specify does not need to include the .icns
// extension, although it may."
//
// However, if it *does* include the '.icns' the above method fails (tested on OS X 10.3.9) so we'll also try:
if (!iconPath) {
iconPath = [self.bundle pathForResource:[self.bundle objectForInfoDictionaryKey:@"CFBundleIconFile"] ofType:nil];
}
NSImage *icon = [[NSImage alloc] initWithContentsOfFile:iconPath];
// Use a default icon if none is defined.
if (!icon) {
BOOL isMainBundle = (self.bundle == [NSBundle mainBundle]);
NSString *fileType = isMainBundle ? (__bridge NSString *)kUTTypeApplication : (__bridge NSString *)kUTTypeBundle;
icon = [[NSWorkspace sharedWorkspace] iconForFileType:fileType];
}
return icon;
}
- (BOOL)isRunningOnReadOnlyVolume
{
struct statfs statfs_info;
@@ -173,11 +105,6 @@
return (statfs_info.f_flags & MNT_RDONLY) != 0;
}
- (BOOL)isBackgroundApplication
{
return ([[NSApplication sharedApplication] activationPolicy] == NSApplicationActivationPolicyAccessory);
}
- (NSString *__nullable)publicDSAKey
{
// Maybe the key is just a string in the Info.plist.
@@ -187,7 +114,7 @@
}
// More likely, we've got a reference to a Resources file by filename:
NSString *keyFilename = [self objectForInfoDictionaryKey:SUPublicDSAKeyFileKey];
NSString *keyFilename = [self publicDSAKeyFileKey];
if (!keyFilename) {
return nil;
}
@@ -199,9 +126,9 @@
return [NSString stringWithContentsOfFile:keyPath encoding:NSASCIIStringEncoding error:nil];
}
- (NSArray *)systemProfile
- (NSString * __nullable)publicDSAKeyFileKey
{
return [[SUSystemProfiler sharedSystemProfiler] systemProfileArrayForHost:self];
return [self objectForInfoDictionaryKey:SUPublicDSAKeyFileKey];
}
- (id)objectForInfoDictionaryKey:(NSString *)key
@@ -231,6 +158,7 @@
return CFBridgingRelease(obj);
}
// Note this handles nil being passed for defaultName, in which case the user default will be removed
- (void)setObject:(id)value forUserDefaultsKey:(NSString *)defaultName
{
if (self.usesStandardUserDefaults)
+10 -8
View File
@@ -6,19 +6,21 @@
// Copyright 2008 Andy Matuschak. All rights reserved.
//
#ifndef SUINSTALLER_H
#define SUINSTALLER_H
#import <Cocoa/Cocoa.h>
#import <Foundation/Foundation.h>
#import "SUVersionComparisonProtocol.h"
NS_ASSUME_NONNULL_BEGIN
@class SUHost;
@protocol SUInstallerProtocol;
@interface SUInstaller : NSObject
+ (NSString *)installSourcePathInUpdateFolder:(NSString *)inUpdateFolder forHost:(SUHost *)host isPackage:(BOOL *)isPackagePtr isGuided:(BOOL *)isGuidedPtr;
+ (void)installFromUpdateFolder:(NSString *)updateFolder overHost:(SUHost *)host installationPath:(NSString *)installationPath versionComparator:(id<SUVersionComparison>)comparator completionHandler:(void (^)(NSError *))completionHandler;
+ (void)finishInstallationToPath:(NSString *)installationPath withResult:(BOOL)result error:(NSError *)error completionHandler:(void (^)(NSError *))completionHandler;
+ (nullable id<SUInstallerProtocol>)installerForHost:(SUHost *)host fileOperationToolPath:(NSString *)fileOperationToolPath updateDirectory:(NSString *)updateDirectory error:(NSError **)error;
+ (nullable NSString *)installSourcePathInUpdateFolder:(NSString *)inUpdateFolder forHost:(SUHost *)host isPackage:(BOOL *)isPackagePtr isGuided:(nullable BOOL *)isGuidedPtr;
@end
#endif
NS_ASSUME_NONNULL_END
+51 -52
View File
@@ -7,12 +7,16 @@
//
#import "SUInstaller.h"
#import "SUInstallerProtocol.h"
#import "SUPlainInstaller.h"
#import "SUPackageInstaller.h"
#import "SUGuidedPackageInstaller.h"
#import "SUHost.h"
#import "SUConstants.h"
#import "SULog.h"
#import "SUErrors.h"
#include "AppKitPrevention.h"
@implementation SUInstaller
@@ -25,10 +29,10 @@
return aliasFlag.boolValue && directoryFlag.boolValue;
}
+ (NSString *)installSourcePathInUpdateFolder:(NSString *)inUpdateFolder forHost:(SUHost *)host isPackage:(BOOL *)isPackagePtr isGuided:(BOOL *)isGuidedPtr
+ (nullable NSString *)installSourcePathInUpdateFolder:(NSString *)inUpdateFolder forHost:(SUHost *)host isPackage:(BOOL *)isPackagePtr isGuided:(nullable BOOL *)isGuidedPtr
{
SUParameterAssert(inUpdateFolder);
SUParameterAssert(host);
NSParameterAssert(inUpdateFolder);
NSParameterAssert(host);
// Search subdirectories for the application
NSString *currentFile,
@@ -36,7 +40,7 @@
*bundleFileName = [[host bundlePath] lastPathComponent],
*alternateBundleFileName = [[host name] stringByAppendingPathExtension:[[host bundlePath] pathExtension]];
BOOL isPackage = NO;
BOOL isGuided = NO;
BOOL isGuided = YES;
NSString *fallbackPackagePath = nil;
NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath:inUpdateFolder];
NSString *bundleFileNameNoExtension = [bundleFileName stringByDeletingPathExtension];
@@ -86,9 +90,12 @@
}
if (isPackage) {
// foo.app -> foo.sparkle_guided.pkg or foo.sparkle_guided.mpkg
if ([[[newAppDownloadPath stringByDeletingPathExtension] pathExtension] isEqualToString:@"sparkle_guided"]) {
isGuided = YES;
// Guided (or now "normal") installs used to be opt-in (i.e, Sparkle would detect foo.sparkle_guided.pkg or foo.sparkle_guided.mpkg),
// but to get an interactive (or "unguided") install, the developer now must opt-out of guided installations.
// foo.app -> foo.sparkle_interactive.pkg or foo.sparkle_interactive.mpkg
if ([[[newAppDownloadPath stringByDeletingPathExtension] pathExtension] isEqualToString:@"sparkle_interactive"]) {
isGuided = NO;
}
}
@@ -103,60 +110,52 @@
return newAppDownloadPath;
}
+ (void)installFromUpdateFolder:(NSString *)inUpdateFolder overHost:(SUHost *)host installationPath:(NSString *)installationPath versionComparator:(id<SUVersionComparison>)comparator completionHandler:(void (^)(NSError *))completionHandler
+ (nullable id<SUInstallerProtocol>)installerForHost:(SUHost *)host fileOperationToolPath:(NSString *)fileOperationToolPath updateDirectory:(NSString *)updateDirectory error:(NSError * __autoreleasing *)error
{
BOOL isPackage = NO;
BOOL isGuided = NO;
NSString *newAppDownloadPath = [self installSourcePathInUpdateFolder:inUpdateFolder forHost:host isPackage:&isPackage isGuided:&isGuided];
if (newAppDownloadPath == nil) {
[self finishInstallationToPath:installationPath withResult:NO error:[NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingUpdateError userInfo:@{ NSLocalizedDescriptionKey: @"Couldn't find an appropriate update in the downloaded package." }] completionHandler:completionHandler];
NSString *newDownloadPath = [self installSourcePathInUpdateFolder:updateDirectory forHost:host isPackage:&isPackage isGuided:&isGuided];
if (newDownloadPath == nil) {
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingUpdateError userInfo:@{ NSLocalizedDescriptionKey: @"Couldn't find an appropriate update in the downloaded package." }];
}
return nil;
}
id <SUInstallerProtocol> installer;
if (isPackage && isGuided) {
installer = [[SUGuidedPackageInstaller alloc] initWithPackagePath:newDownloadPath installationPath:host.bundlePath fileOperationToolPath:fileOperationToolPath];
} else if (isPackage) {
installer = [[SUPackageInstaller alloc] initWithPackagePath:newDownloadPath installationPath:host.bundlePath];
} else {
if (isPackage && isGuided) {
[SUGuidedPackageInstaller performInstallationToPath:installationPath fromPath:newAppDownloadPath host:host versionComparator:comparator completionHandler:completionHandler];
} else if (isPackage) {
[SUPackageInstaller performInstallationToPath:installationPath fromPath:newAppDownloadPath host:host versionComparator:comparator completionHandler:completionHandler];
NSString *normalizedInstallationPath = nil;
if (SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME) {
normalizedInstallationPath = [self normalizedInstallationPathForHost:host];
}
// If we have a normalized path, we'll install to "#{CFBundleName}.app", but only if that path doesn't already exist. If we're "Foo 4.2.app," and there's a "Foo.app" in this directory, we don't want to overwrite it! But if there's no "Foo.app," we'll take that name.
// Otherwise if there's no normalized path (the more likely case), we'll just use the host bundle's path
NSString *installationPath;
if (normalizedInstallationPath != nil && ![[NSFileManager defaultManager] fileExistsAtPath:normalizedInstallationPath]) {
installationPath = normalizedInstallationPath;
} else {
[SUPlainInstaller performInstallationToPath:installationPath fromPath:newAppDownloadPath host:host versionComparator:comparator completionHandler:completionHandler];
installationPath = host.bundlePath;
}
installer = [[SUPlainInstaller alloc] initWithHost:host bundlePath:newDownloadPath installationPath:installationPath fileOperationToolPath:fileOperationToolPath];
}
return installer;
}
+ (void)mdimportInstallationPath:(NSString *)installationPath
+ (NSString *)normalizedInstallationPathForHost:(SUHost *)host
{
// *** GETS CALLED ON NON-MAIN THREAD!
SULog(@"mdimporting");
NSTask *mdimport = [[NSTask alloc] init];
[mdimport setLaunchPath:@"/usr/bin/mdimport"];
[mdimport setArguments:@[installationPath]];
@try {
[mdimport launch];
[mdimport waitUntilExit];
}
@catch (NSException *launchException)
{
// No big deal.
SULog(@"Error: %@", [launchException description]);
}
}
+ (void)finishInstallationToPath:(NSString *)installationPath withResult:(BOOL)result error:(NSError *)error completionHandler:(void (^)(NSError *))completionHandler
{
if (result) {
[self mdimportInstallationPath:installationPath];
dispatch_async(dispatch_get_main_queue(), ^{
completionHandler(nil);
});
} else {
if (!error) {
error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:nil];
}
dispatch_async(dispatch_get_main_queue(), ^{
completionHandler(error);
});
}
NSBundle *bundle = host.bundle;
assert(bundle != nil);
NSString *normalizedAppPath = [[[bundle bundlePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", [bundle objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleNameKey], [[bundle bundlePath] pathExtension]]];
return normalizedAppPath;
}
@end
+36
View File
@@ -0,0 +1,36 @@
//
// SUInstallerProtocol.h
// Sparkle
//
// Created by Mayur Pawashe on 12/26/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@protocol SUInstallerProtocol <NSObject>
// Any installation work can be done prior to user application being terminated and relaunched
// Currently this is invoked after the user application is terminated, but this may change in the future.
// No UI should occur during this stage (i.e, do not show package installer apps, etc..)
// Should be able to be called from non-main thread
- (BOOL)performInitialInstallation:(NSError **)error;
// Any installation work after the user application has been terminated. This is where the final installation work can be done.
// After this stage is done, the user application may be relaunched.
// Should be able to be called from non-main thread
- (BOOL)performFinalInstallation:(NSError **)error;
// Indicates whether or not this installer can install the update silently in the background, without hindering the user
// Should be thread safe
- (BOOL)canInstallSilently;
// The destination and installation path of the bundle being updated
// Should be thread safe
- (NSString *)installationPath;
@end
NS_ASSUME_NONNULL_END
+16
View File
@@ -0,0 +1,16 @@
//
// SULocalizations.h
// Sparkle
//
// Created by Mayur Pawashe on 2/28/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#ifndef SULocalizations_h
#define SULocalizations_h
#import "SUConstants.h"
#define SULocalizedString(key, comment) NSLocalizedStringFromTableInBundle(key, @"Sparkle", (NSBundle * _Nonnull)([NSBundle bundleWithIdentifier:SUBundleIdentifier] ? [NSBundle bundleWithIdentifier:SUBundleIdentifier] : [NSBundle mainBundle]), comment)
#endif /* SULocalizations_h */
+2
View File
@@ -14,6 +14,8 @@
#include "SULog.h"
#include "AppKitPrevention.h"
// -----------------------------------------------------------------------------
// Constants:
// -----------------------------------------------------------------------------
+8
View File
@@ -7,6 +7,14 @@
#import <Foundation/Foundation.h>
#if __MAC_OS_X_VERSION_MAX_ALLOWED < 101000
typedef struct {
NSInteger majorVersion;
NSInteger minorVersion;
NSInteger patchVersion;
} NSOperatingSystemVersion;
#endif
@interface SUOperatingSystem : NSObject
+ (NSOperatingSystemVersion)operatingSystemVersion;
+20 -4
View File
@@ -7,6 +7,15 @@
#import "SUOperatingSystem.h"
#include "AppKitPrevention.h"
#if __MAC_OS_X_VERSION_MAX_ALLOWED < 101000
@interface NSProcessInfo ()
- (NSOperatingSystemVersion)operatingSystemVersion;
@end
#endif
@implementation SUOperatingSystem
+ (NSOperatingSystemVersion)operatingSystemVersion
@@ -20,14 +29,21 @@
{
NSOperatingSystemVersion version = { 0, 0, 0 };
NSURL *coreServices = [[NSFileManager defaultManager] URLForDirectory:NSCoreServiceDirectory inDomain:NSSystemDomainMask appropriateForURL:nil create:NO error:nil];
NSArray *components = [[NSDictionary dictionaryWithContentsOfURL:[coreServices URLByAppendingPathComponent:@"SystemVersion.plist"]][@"ProductVersion"] componentsSeparatedByString:@"."];
version.majorVersion = components.count > 0 ? [components[0] integerValue] : 0;
version.minorVersion = components.count > 1 ? [components[1] integerValue] : 0;
version.patchVersion = components.count > 2 ? [components[2] integerValue] : 0;
NSURL *url = [coreServices URLByAppendingPathComponent:@"SystemVersion.plist"];
assert(url != nil);
NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfURL:url];
NSArray *components = [ [dictionary objectForKey: @"ProductVersion"] componentsSeparatedByString:@"."];
version.majorVersion = components.count > 0 ? [ [components objectAtIndex:0] integerValue] : 0;
version.minorVersion = components.count > 1 ? [ [components objectAtIndex:1] integerValue] : 0;
version.patchVersion = components.count > 2 ? [ [components objectAtIndex:2] integerValue] : 0;
return version;
}
#endif
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpartial-availability"
return [[NSProcessInfo processInfo] operatingSystemVersion];
#pragma clang diagnostic pop
}
+ (BOOL)isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion)version
+6 -10
View File
@@ -6,19 +6,15 @@
// Copyright 2008 Andy Matuschak. All rights reserved.
//
#ifndef SUPACKAGEINSTALLER_H
#define SUPACKAGEINSTALLER_H
#import <Foundation/Foundation.h>
#import "SUInstallerProtocol.h"
#import "SUUpdater.h"
NS_ASSUME_NONNULL_BEGIN
#import "SUAppcast.h"
#import "SUAppcastItem.h"
#import "SUVersionComparisonProtocol.h"
#import "SUPlainInstaller.h"
@interface SUPackageInstaller : NSObject <SUInstallerProtocol>
- (instancetype)initWithPackagePath:(NSString *)packagePath installationPath:(NSString *)installationPath;
@interface SUPackageInstaller : SUPlainInstaller
@end
#endif
NS_ASSUME_NONNULL_END
+58 -18
View File
@@ -7,35 +7,75 @@
//
#import "SUPackageInstaller.h"
#import <Cocoa/Cocoa.h>
#import "SUConstants.h"
#import "SUErrors.h"
#import "SULog.h"
#include "AppKitPrevention.h"
@interface SUPackageInstaller ()
@property (nonatomic, readonly, copy) NSString *packagePath;
@property (nonatomic, readonly, copy) NSString *installationPath;
@end
@implementation SUPackageInstaller
+ (void)performInstallationToPath:(NSString *)installationPath fromPath:(NSString *)path host:(SUHost *)__unused host versionComparator:(id<SUVersionComparison>)__unused comparator completionHandler:(void (^)(NSError *))completionHandler
static NSString *SUOpenUtilityPath = @"/usr/bin/open";
@synthesize packagePath = _packagePath;
@synthesize installationPath = _installationPath;
- (instancetype)initWithPackagePath:(NSString *)packagePath installationPath:(NSString *)installationPath
{
self = [super init];
if (self != nil) {
_packagePath = [packagePath copy];
_installationPath = [installationPath copy];
}
return self;
}
- (BOOL)performInitialInstallation:(NSError * __autoreleasing *)error
{
if (![[NSFileManager defaultManager] fileExistsAtPath:SUOpenUtilityPath]) {
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingInstallerToolError userInfo:@{ NSLocalizedDescriptionKey: @"Couldn't find Apple's installer tool!" }];
}
return NO;
}
return YES;
}
- (BOOL)performFinalInstallation:(NSError * __autoreleasing *)error
{
// Run installer using the "open" command to ensure it is launched in front of current application.
// -W = wait until the app has quit.
// -n = Open another instance if already open.
// -b = app bundle identifier
NSString *command = @"/usr/bin/open";
NSArray *args = @[@"-W", @"-n", @"-b", @"com.apple.installer", path];
if (![[NSFileManager defaultManager] fileExistsAtPath:command]) {
NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingInstallerToolError userInfo:@{ NSLocalizedDescriptionKey: @"Couldn't find Apple's installer tool!" }];
[self finishInstallationToPath:installationPath withResult:NO error:error completionHandler:completionHandler];
return;
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSTask *installer = [NSTask launchedTaskWithLaunchPath:command arguments:args];
NSArray *args = @[@"-W", @"-n", @"-b", @"com.apple.installer", self.packagePath];
// Known bug: if the installation fails or is canceled, Sparkle goes ahead and restarts, thinking everything is fine.
@try {
NSTask *installer = [NSTask launchedTaskWithLaunchPath:SUOpenUtilityPath arguments:args];
[installer waitUntilExit];
}
@catch (NSException *exception) {
SULog(@"Error: Failed to launch package installer: %@", exception);
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: @"Package installer failed to launch." }];
}
return NO;
}
return YES;
}
// Known bug: if the installation fails or is canceled, Sparkle goes ahead and restarts, thinking everything is fine.
dispatch_async(dispatch_get_main_queue(), ^{
[self finishInstallationToPath:installationPath withResult:YES error:nil completionHandler:completionHandler];
});
});
- (BOOL)canInstallSilently
{
return NO;
}
@end
+9 -3
View File
@@ -9,11 +9,17 @@
#ifndef SUPIPEDUNARCHIVER_H
#define SUPIPEDUNARCHIVER_H
#import <Cocoa/Cocoa.h>
#import "SUUnarchiver.h"
#import <Foundation/Foundation.h>
#import "SUUnarchiverProtocol.h"
@interface SUPipedUnarchiver : SUUnarchiver
NS_ASSUME_NONNULL_BEGIN
@interface SUPipedUnarchiver : NSObject <SUUnarchiverProtocol>
- (instancetype)initWithArchivePath:(NSString *)archivePath;
@end
NS_ASSUME_NONNULL_END
#endif
+83 -89
View File
@@ -7,68 +7,106 @@
//
#import "SUPipedUnarchiver.h"
#import "SUUnarchiver_Private.h"
#import "SUUnarchiverNotifier.h"
#import "SULog.h"
#import "SUErrors.h"
#include "AppKitPrevention.h"
@interface SUPipedUnarchiver ()
@property (nonatomic, copy, readonly) NSString *archivePath;
@end
@implementation SUPipedUnarchiver
+ (SEL)selectorConformingToTypeOfPath:(NSString *)path
@synthesize archivePath = _archivePath;
+ (nullable NSArray <NSString *> *)commandAndArgumentsConformingToTypeOfPath:(NSString *)path
{
static NSDictionary *typeSelectorDictionary;
if (!typeSelectorDictionary)
typeSelectorDictionary = @{ @".zip": @"extractZIP",
@".tar": @"extractTAR",
@".tar.gz": @"extractTGZ",
@".tgz": @"extractTGZ",
@".tar.bz2": @"extractTBZ",
@".tbz": @"extractTBZ",
@".tar.xz": @"extractTXZ",
@".txz": @"extractTXZ",
@".tar.lzma": @"extractTXZ"};
NSArray <NSString *> *extractTGZ = @[@"/usr/bin/tar", @"-zxC"];
NSArray <NSString *> *extractTBZ = @[@"/usr/bin/tar", @"-jxC"];
NSArray <NSString *> *extractTXZ = extractTGZ;
NSDictionary <NSString *, NSArray<NSString *> *> *extractCommandDictionary =
@{
@".zip" : @[@"/usr/bin/ditto", @"-x",@"-k",@"-"],
@".tar" : @[@"/usr/bin/tar", @"-xC"],
@".tar.gz" : extractTGZ,
@".tgz" : extractTGZ,
@".tar.bz2" : extractTBZ,
@".tbz" : extractTBZ,
@".tar.xz" : extractTXZ,
@".txz" : extractTXZ,
@".tar.lzma" : extractTXZ
};
NSString *lastPathComponent = [path lastPathComponent];
for (NSString *currentType in typeSelectorDictionary)
{
NSString *value = typeSelectorDictionary[currentType];
assert(value);
if ([currentType length] > [lastPathComponent length]) continue;
if ([[lastPathComponent substringFromIndex:[lastPathComponent length] - [currentType length]] isEqualToString:currentType]) {
return NSSelectorFromString(value);
for (NSString *currentType in extractCommandDictionary)
{
if ([lastPathComponent hasSuffix:currentType]) {
return [extractCommandDictionary objectForKey:currentType];
}
}
return NULL;
}
- (void)start
{
[NSThread detachNewThreadSelector:[[self class] selectorConformingToTypeOfPath:self.archivePath] toTarget:self withObject:nil];
return nil;
}
+ (BOOL)canUnarchivePath:(NSString *)path
{
return ([self selectorConformingToTypeOfPath:path] != nil);
return ([self commandAndArgumentsConformingToTypeOfPath:path] != nil);
}
+ (BOOL)unsafeIfArchiveIsNotValidated
{
return NO;
}
- (instancetype)initWithArchivePath:(NSString *)archivePath
{
self = [super init];
if (self != nil) {
_archivePath = [archivePath copy];
}
return self;
}
- (void)unarchiveWithCompletionBlock:(void (^)(NSError * _Nullable))completionBlock progressBlock:(void (^ _Nullable)(double))progressBlock
{
NSArray <NSString *> *commandAndArguments = [[self class] commandAndArgumentsConformingToTypeOfPath:self.archivePath];
assert(commandAndArguments != nil);
NSString *command = commandAndArguments.firstObject;
assert(command != nil);
NSArray <NSString *> *arguments = [commandAndArguments subarrayWithRange:NSMakeRange(1, commandAndArguments.count - 1)];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
SUUnarchiverNotifier *notifier = [[SUUnarchiverNotifier alloc] initWithCompletionBlock:completionBlock progressBlock:progressBlock];
[self extractArchivePipingDataToCommand:command arguments:arguments notifier:notifier];
});
}
// This method abstracts the types that use a command line tool piping data from stdin.
- (void)extractArchivePipingDataToCommand:(NSString *)command args:(NSArray*)args
- (void)extractArchivePipingDataToCommand:(NSString *)command arguments:(NSArray*)args notifier:(SUUnarchiverNotifier *)notifier
{
// *** GETS CALLED ON NON-MAIN THREAD!!!
@autoreleasepool {
NSError *error = nil;
NSString *destination = [self.archivePath stringByDeletingLastPathComponent];
SULog(@"Extracting using '%@' '%@' < '%@' '%@'", command, [args componentsJoinedByString:@"' '"], self.archivePath, destination);
// Get the file size.
NSUInteger expectedLength = [[[NSFileManager defaultManager] attributesOfItemAtPath:self.archivePath error:nil][NSFileSize] unsignedIntegerValue];
NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:self.archivePath error:nil];
NSUInteger expectedLength = [[attributes objectForKey:NSFileSize] unsignedIntegerValue];
if (expectedLength > 0) {
NSFileHandle *archiveInput = [NSFileHandle fileHandleForReadingAtPath:self.archivePath];
NSPipe *pipe = [NSPipe pipe];
NSFileHandle *archiveOutput = [pipe fileHandleForWriting];
NSTask *task = [[NSTask alloc] init];
[task setStandardInput:[pipe fileHandleForReading]];
[task setStandardError:[NSFileHandle fileHandleWithStandardError]];
@@ -76,7 +114,7 @@
[task setLaunchPath:command];
[task setArguments:[args arrayByAddingObject:destination]];
[task launch];
NSUInteger bytesRead = 0;
do {
NSData *data = [archiveInput readDataOfLength:256*1024];
@@ -86,76 +124,32 @@
}
bytesRead += len;
[archiveOutput writeData:data];
dispatch_async(dispatch_get_main_queue(), ^{
[self notifyDelegateOfProgress:(double)bytesRead / (double)expectedLength];
});
[notifier notifyProgress:(double)bytesRead / (double)expectedLength];
}
while(bytesRead < expectedLength);
[archiveOutput closeFile];
[task waitUntilExit];
if ([task terminationStatus] == 0) {
if (bytesRead == expectedLength) {
dispatch_async(dispatch_get_main_queue(), ^{
[self notifyDelegateOfSuccess];
});
[notifier notifySuccess];
return;
} else {
SULog(@"Extraction failed, command '%@' got only %ld of %ld bytes", command, (long)bytesRead, (long)expectedLength);
error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Extraction failed, command '%@' got only %ld of %ld bytes", command, (long)bytesRead, (long)expectedLength]}];
}
} else {
SULog(@"Extraction failed, command '%@' returned %d", command, [task terminationStatus]);
error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Extraction failed, command '%@' returned %d", command, [task terminationStatus]]}];
}
} else {
SULog(@"Extraction failed, archive '%@' is empty", self.archivePath);
error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Extraction failed, archive '%@' is empty", self.archivePath]}];
}
dispatch_async(dispatch_get_main_queue(), ^{
[self notifyDelegateOfFailure];
});
[notifier notifyFailureWithError:error];
}
}
- (void)extractTAR
{
// *** GETS CALLED ON NON-MAIN THREAD!!!
[self extractArchivePipingDataToCommand:@"/usr/bin/tar" args:@[@"-xC"]];
}
- (void)extractTGZ
{
// *** GETS CALLED ON NON-MAIN THREAD!!!
[self extractArchivePipingDataToCommand:@"/usr/bin/tar" args:@[@"-zxC"]];
}
- (void)extractTBZ
{
// *** GETS CALLED ON NON-MAIN THREAD!!!
[self extractArchivePipingDataToCommand:@"/usr/bin/tar" args:@[@"-jxC"]];
}
- (void)extractZIP
{
// *** GETS CALLED ON NON-MAIN THREAD!!!
[self extractArchivePipingDataToCommand:@"/usr/bin/ditto" args:@[@"-x",@"-k",@"-"]];
}
- (void)extractTXZ
{
// *** GETS CALLED ON NON-MAIN THREAD!!!
[self extractArchivePipingDataToCommand:@"/usr/bin/tar" args:@[@"-zxC"]];
}
+ (void)load
{
[self registerImplementation:self];
}
- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], self.archivePath]; }
@end
+11 -13
View File
@@ -6,25 +6,23 @@
// Copyright 2008 Andy Matuschak. All rights reserved.
//
#ifndef SUPLAININSTALLER_H
#define SUPLAININSTALLER_H
#import <Foundation/Foundation.h>
#import "SUInstallerProtocol.h"
#import "SUUpdater.h"
#import "SUAppcast.h"
#import "SUAppcastItem.h"
#import "SUVersionComparisonProtocol.h"
#import "SUInstaller.h"
#import "SUVersionComparisonProtocol.h"
NS_ASSUME_NONNULL_BEGIN
@class SUHost;
@interface SUPlainInstaller : SUInstaller
@interface SUPlainInstaller : NSObject <SUInstallerProtocol>
+ (void)performInstallationToPath:(NSString *)installationPath fromPath:(NSString *)path host:(SUHost *)host versionComparator:(id<SUVersionComparison>)comparator completionHandler:(void (^)(NSError *))completionHandler;
/*!
@param host The current (old) bundle host
@param bundlePath The path to the new bundle that will be installed.
@param installationPath The path the new bundlePath will be installed to.
@param fileOperationToolPath The path to the file operation tool for authorized operations.
*/
- (instancetype)initWithHost:(SUHost *)host bundlePath:(NSString *)bundlePath installationPath:(NSString *)installationPath fileOperationToolPath:(NSString *)fileOperationToolPath;
@end
#endif
NS_ASSUME_NONNULL_END
Loaded 100 of 257 files, more files were not shown because too many files have changed in this diff. Show more