Compare commits

..
392 Commits
Author SHA1 Message Date
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
Kornel 4b2c4a5823 ATS note 2015-12-14 01:10:45 +00:00
Kornel Lesiński db3c9cb9c5 Explain rejection for installer packages 2015-12-08 18:08:03 +00:00
Kornel 68e7fb5caa Merge pull request #690 from ksuther/permission-prompt-xibs
SUUpdatePermissionPrompt xib fixes
2015-12-08 02:03:29 +00:00
Kent Sutherland 8420abe5b9 Updated button sizes in SUUpdatePermissionPrompt.
Fixed overlapping title and message text in some languages in SUUpdatePermissionPrompt.
2015-12-07 11:18:25 -05:00
Jake Petroules 5e90d987de Fix Podfile.
Closes #658
2015-11-29 23:47:40 -08:00
Kornel a0716aac49 #686 2015-11-14 17:46:17 +00:00
Kornel Lesiński 1659180864 Merge tag '1.12.0b1'
* tag '1.12.0b1':
  Release build fix
2015-11-14 17:24:41 +00:00
Kornel Lesiński d308707f09 Added docs, screenshot to cocoapod metadata 2015-11-14 17:23:43 +00:00
Kornel Lesiński 916554046d Merge remote-tracking branch 'origin/1.11.x'
* origin/1.11.x:
  Updated podspec
  1.11.1
  Don't install automatic updates if the system might shut off
2015-11-14 17:23:21 +00:00
Andrew K. Boyd 47c1761137 Remove newline, Add explicit property synthesis 2015-11-13 16:49:12 -05:00
Kornel Lesiński 4022b01041 Updated podspec 2015-11-13 19:15:26 +00:00
Kornel Lesiński 558f3bb10e Release build fix 2015-11-12 21:00:27 +00:00
Kornel Lesiński ccc2c7cb5d Updated changelog 2015-11-12 21:00:01 +00:00
Kornel 3ed092e764 Merge pull request #678 from sparkle-project/sufsref
fsref func and --
2015-11-12 15:16:54 +00:00
Kornel 3bdf4aab9b Merge pull request #681 from sparkle-project/newxibs
Re-generated XIBs
2015-11-12 14:00:43 +00:00
Kornel Lesiński 373a3b4227 Protect shell commands from filenames starting with - 2015-11-12 13:55:32 +00:00
Kornel Lesiński c78a314385 Wording 2015-11-12 13:55:22 +00:00
Kornel Lesiński 533a0ecf17 cp -- to stop argument parsing 2015-11-12 13:55:22 +00:00
Kornel Lesiński 155782708b Helper function for FSRef 2015-11-12 13:55:20 +00:00
Kornel Lesiński b6c023fdea typo 2015-11-12 13:52:46 +00:00
Kornel 6351ee86b9 Merge pull request #683 from zorgiepoo/copy-auth-perm
Handle additional permission denied code when copying files
2015-11-12 13:51:28 +00:00
Zorg a4bd5443f3 Handle additional permission denied code when copying files
afpAccessDenied can be returned even when not using a AFP mount,
at least according to my testing.

Having an installation do a copy (because of different mounts) and auth
may not be a likely scenario, so this may not be hit often.
2015-11-11 23:08:41 -05:00
Kornel 3120b47404 Merge pull request #665 from GabrielUlici/master
Updated the latest iMac - Late 2015
2015-11-10 23:35:11 +00:00
Kornel Lesiński 2ae4e42561 Re-generated Arabic XIBs 2015-11-10 10:57:56 +00:00
Kornel Lesiński 5112748e1b Re-generated XIBs 2015-11-10 10:53:56 +00:00
Kornel Lesiński 1388639079 Upgraded XIBs 2015-11-10 10:30:37 +00:00
Kornel Lesiński 72618a0d3a 1.11.1 2015-11-09 00:33:29 +00:00
Zorg 66a11b83f0 Don't install automatic updates if the system might shut off 2015-11-08 23:43:12 +00:00
Kornel 0bc66ab011 Merge pull request #657 from zorgiepoo/fileop-copy
File Operations Copy Fixes
2015-11-08 23:18:51 +00:00
Zorg c98ef7c614 Merge branch 'master' into fileop-copy 2015-11-08 17:03:19 -05:00
Zorg 896a01cd40 Remove compiled classes in the Test App that exist in the framework
This removes run-time warnings that SUFileManager and SUOperatingSystem are
defined in both the test app and the framework, and which one
is used is undefined.
2015-11-08 17:00:27 -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
Kornel 93a5228f5b Merge pull request #669 from AutoScout24/x2on-patch-1
Fix framework imports
2015-10-27 11:10:38 +00:00
Felix Schulze 124d9a901f Fix framework imports
Fixes #668
2015-10-27 11:26:25 +01:00
Gabriel Ulici 97c1a222ab corrected the comma 2015-10-25 20:08:53 +02:00
Gabriel Ulici 35802dbb4d Updated the latest iMac - Late 2015 2015-10-25 17:25:37 +02:00
Zorg c848882778 Merge branch 'master' into fileop-copy 2015-10-24 21:57:07 -04:00
Kornel 374b8d6195 Merge pull request #655 from kainjow/webserver
Replace use of Python with built-in web server
2015-10-23 16:25:35 +01:00
Kornel 27c1b0f045 Merge pull request #650 from zorgiepoo/binarydelta-no-write-perm
Fix segfault when patch path has insufficient write permissions
2015-10-23 00:35:06 +01:00
Kornel Lesiński 154aa1b0db Subclassing fixes #661 2015-10-22 13:55:01 +01:00
Kornel 658e5fcb9f Merge pull request #661 from osolo/misc-fixes
Misc fixes
2015-10-21 16:41:16 +02:00
Oz Solomon 292ba01dbf Removed invalid deployment target version 2015-10-21 09:39:26 -04:00
Oz Solomon ff7966d96a Fix: sparkleBundle not calculated correctly when SUUpdater is subclassed by a class in a different bundle. 2015-10-21 09:39:14 -04:00
Zorg 9cf7437392 Update explanation of why copyfile() is insufficient 2015-10-17 14:47:16 -04:00
Zorg 9f1884f100 Add compile sources to Test App to fix building issues 2015-10-10 18:23:45 -04:00
Zorg 8a208ce520 Move OS methods from SUHost to SUOperatingSystem
This reduces the bloat that BinaryDelta and SUFileManager need to include
2015-10-10 18:14:06 -04:00
Zorg c850146ef6 Forgot to update SUFileManager constuctor in Test App 2015-10-10 18:10:24 -04:00
Zorg ccf4f81ea0 Use SUFileManager for copyTree in BinaryDelta
Fixes app not being able to be patched because the original app
was on a network mounted volume
2015-10-10 17:58:44 -04:00
Zorg 3c957096c6 Use class constructor instead of an init method for SUFileManager
I think it's more natural this way
2015-10-10 17:42:27 -04:00
Zorg bc5ad0d919 Merge branch 'master' into binarydelta-no-write-perm 2015-10-10 00:38:38 -04:00
Zorg 9d06f5bc4d Meant to use NSFileNoSuchFileError here 2015-10-10 00:28:12 -04:00
Zorg 6818d1f180 Verify existence of destination parent directory for moving/copying 2015-10-10 00:12:58 -04:00
Zorg ee72ec3dab Fix issues with copying files from different mounted drives
The move operation now does an explict copy & remove.

We also copy items using FSCopyObjectSync due to issues
existing in copyfile (and NSFileManager).

Both of these fix bugs in some cases where items cannot be moved
from one network drive to another. In my testing before this patch,
I was unable to get the test application to launch and was unable
to move the old installation to the trash.
2015-10-09 23:58:23 -04:00
Zorg 9b74309eb5 Make allowsAuthorization apply to all of SUFileManager's methods 2015-10-09 17:49:46 -04:00
Kevin Wojniak 948eccb169 Use properties to avoid having to disable warning for entire file 2015-10-09 09:37:25 -07:00
Kevin Wojniak ff342f1e5b Use nil instead of 0. Fix pointer style. 2015-10-09 09:22:20 -07:00
Kornel a7af6fb82d Merge pull request #654 from zorgiepoo/nstask-string
Fix Test App crashing on systems earlier than 10.9
2015-10-09 16:02:48 +01:00
Zorg d7e3b01bd6 Merge branch 'master' into binarydelta-no-write-perm 2015-10-09 08:26:22 -04:00
Kevin Wojniak 117716da9e Replace use of Python with built-in web server
See issue #637
2015-10-08 20:41:26 -07:00
Zorg 17da7b5fb8 Fix Test App crashing on systems earlier than 10.9
Passing a NSURL instance to a NSTask's arguments calls
-[NSURL fileSystemRepresentation] which is only available on 10.9+
2015-10-08 22:49:03 -04:00
Kornel 545b8f2416 Merge pull request #653 from artillery/artillery-seamless2
Fire didFindValidUpdate even if automatically installing updates
2015-10-08 23:45:44 +01:00
Ian Langworth ☠ d1a62bba89 Fire didFindValidUpdate even if automatically installing updates 2015-10-08 15:33:00 -07:00
Kornel Lesiński 7ccf706a1d Synthesize automaticallyInstallUpdates 2015-10-08 23:25:21 +01:00
Kornel ef61691b34 Merge pull request #620 from artillery/artillery-seamless
Add automatically-install-updates option
2015-10-08 23:17:21 +01:00
Ian Langworth ☠ a92c23bb26 Add automatically install updates option 2015-10-08 14:45:05 -07:00
Zorg 21e4cc42cc Fix segfault when patch path has insufficient write permissions 2015-10-07 18:44:14 -04:00
Kornel abc307dc35 Merge pull request #647 from kainjow/patch-1
Fix readme headings
2015-10-05 11:10:02 +01:00
Kevin Wojniak 49e262e718 Fix readme headings 2015-10-04 16:36:57 -07:00
Jake Petroules 25be040bfc Merge pull request #643 from sparkle-project/maxcdn
MaxCDN
2015-10-03 05:56:59 -07:00
Kornel 46c677ea57 Merge pull request #641 from sparkle-project/charconv
Char conversions
2015-09-30 19:00:16 +01:00
Kornel Lesiński 165b772f8f MaxCDN 2015-09-29 00:39:35 +01:00
Kornel Lesiński bac2463ff2 Use a C formatting function for a C string 2015-09-28 10:54:30 +01:00
Kornel Lesiński c61b5d99a2 Avoid conversion from NSString to char[] 2015-09-28 10:46:36 +01:00
Jake Petroules e54498dd35 Merge pull request #640 from sparkle-project/fix-warnings
Fix warnings.
2015-09-27 16:21:28 -07:00
Jake Petroules 9ca70a5157 Fix warnings. 2015-09-27 16:16:37 -07:00
Jake Petroules f9b9184a39 Merge pull request #639 from sparkle-project/at-least-version
Use proper version checking.
2015-09-27 16:00:32 -07:00
Jake Petroules b943af3b59 Use proper version checking. 2015-09-27 15:55:26 -07:00
Jake Petroules 5afdc4f20e Implement isOperatingSystemAtLeastVersion: 2015-09-27 15:41:23 -07:00
Kornel f85ac88595 Merge pull request #635 from zorgiepoo/update-mod-time
Update modification & access time for new update
2015-09-27 23:02:29 +01:00
Zorg e9e04e2cb4 Merge branch 'master' into update-mod-time 2015-09-27 17:05:07 -04:00
Jake Petroules 114252dd09 Merge pull request #637 from kainjow/test-app-urls
Test app cleanup
2015-09-27 13:35:31 -07:00
Zorg 2f41dec805 Log any installation error that may occur 2015-09-27 16:19:35 -04:00
Kevin Wojniak 2ad01ad672 Reuse file manager variable 2015-09-27 12:33:14 -07:00
Kevin Wojniak 079666643d Set the task working directories instead of changing the process working directory 2015-09-27 12:31:45 -07:00
Kevin Wojniak da370c0f2b Avoid converting URLs to paths to check for existence 2015-09-27 12:24:47 -07:00
Zorg b98026040f Merge branch 'master' into update-mod-time 2015-09-27 11:19:36 -04:00
Kornel Lesiński 6d833143fe Xcode 7.1 config upgrade marker 2015-09-27 16:09:33 +01:00
Zorg 83578c1f38 Merge branch 'master' into update-mod-time 2015-09-27 11:05:22 -04:00
Kornel Lesiński 2bc0b2a2b3 Updated changelog 2015-09-27 15:58:55 +01:00
Zorg 6af2fbfb6e Update modification & access time for new update
If we don't do this, Finder may not report the correct file size for the new update.
The system also may not register the new app in its database if we don't do this.

We may have been able to get away with not doing this before because we used to perform a copy
to install the update. However, now updates in some cases can be done with only move operations.

This should also be an alternative way of addressing issue #508
2015-09-27 10:53:22 -04:00
Kornel 999b265908 Merge pull request #631 from kainjow/patch-1
Make requirements more explicit
2015-09-27 15:33:42 +01:00
Kornel 6599ba3a2d Merge pull request #632 from zorgiepoo/fileop-tests
Fileop tests
2015-09-27 15:33:12 +01:00
Kornel 888f35c756 Merge pull request #634 from zorgiepoo/autolayout-issues
Fix releasenotes container not being right-aligned with its box
2015-09-27 12:32:57 +01:00
Zorg cc354cf8cf Fix releasenotes container not being right-aligned with its box
This fixes an issue where the vertical border of the release notes view would sometimes not be visible.

Instead of making the widths of the views equal, we use the trailing property.
This is consistent with leading and bottom being used elsewhere
2015-09-26 23:58:56 -04:00
Zorg 2b6ae33911 Merge branch 'master' into fileop-tests 2015-09-26 21:35:48 -04:00
Kornel 93a87a4dfd Merge pull request #633 from zorgiepoo/no-auto-updates
Disallow automatic updates when user can't write to the bundle
2015-09-27 02:20:11 +01:00
Zorg a7ff41b3ce If the developer disables automatic updating, don't check writability 2015-09-26 21:10:09 -04:00
Zorg 6079739534 Disallow automatic updates when user can't write to the bundle
The automatic updates checkbox is also hidden in this scenario, and
we also update the layout constraints if the releasenotes are still visible
2015-09-26 20:56:44 -04:00
Zorg 9822b4d2a1 Fix typo 2015-09-26 15:21:33 -04:00
Zorg 03655cf8b2 Resolve nullability warnings 2015-09-26 15:11:23 -04:00
Zorg 32591954bc Add SUFileManager tests and fix issues along the way
* Fix uid / gid not being applied to the root path or non-directory inputs
* Remove the code that released quarantines using the NSURL way.
  It turned out not to be very reliable and didn't pass the tests.
  More explanation is given in the code.
* Prefix private methods with _ and expose some of them to the tests
2015-09-26 14:28:53 -04:00
Kornel e17d4fc99f Merge pull request #623 from zorgiepoo/update-delay
Keep Auto Updater alive for small delay before launching app
2015-09-26 01:19:46 +01:00
Kornel b746fc56bf Merge pull request #630 from sparkle-project/fix-1080-build
Avoid firstObject method in order to build with older SDKs.
2015-09-26 01:18:48 +01:00
Zorg 831947ff55 Merge branch 'master' into update-delay 2015-09-25 18:56:12 -04:00
Zorg e1002f0662 Revert using -[NSWorkspace openFile:] 2015-09-25 18:52:54 -04:00
Kevin Wojniak 222fe94a05 Specify required SDK 2015-09-25 09:54:32 -07:00
Kevin Wojniak aae9e12b8a Make requirements more explicit 2015-09-25 09:34:40 -07:00
Jake Petroules dc0aca1d16 Avoid firstObject method in order to build with older SDKs. 2015-09-25 09:26:54 -07:00
Kornel 452aee0b83 Merge pull request #629 from zorgiepoo/poweroff-note
Don't install automatic updates if the system might shut off
2015-09-25 16:09:40 +01:00
Kornel 73977c9aa5 Merge pull request #575 from zorgiepoo/fileoperations
Rewrite file operations for updating an app
2015-09-25 16:09:02 +01:00
Kornel f9731c92c1 Merge pull request #627 from zorgiepoo/no-dock
Don't show Autoupdate dock icon if we shouldn't show UI
2015-09-25 16:05:05 +01:00
Kornel 88f308e2ae Merge pull request #628 from kainjow/master
Fix analyzer warning "Value stored to completionBlock is never read"
2015-09-25 16:00:53 +01:00
Zorg aa4cc6a7dc Don't install automatic updates if the system might shut off 2015-09-25 00:31:53 -04:00
Kevin Wojniak eead36eb47 Fix analyzer warning "Value stored to completionBlock is never read" 2015-09-24 19:28:31 -07:00
Zorg 39f17764e3 Don't show Autoupdate dock icon if we shouldn't show UI 2015-09-24 20:43:20 -04:00
Zorg a9743f01fa Merge branch 'master' into fileoperations 2015-09-24 00:05:34 -04:00
Zorg e60baaeec8 Keep Auto Updater alive for small delay before launching app
This increases the likelihood that the updated launched app will
be brought up front and active.
2015-09-21 23:26:41 -04:00
Zorg bd3be288f2 Merge branch 'master' into fileoperations 2015-09-19 01:28:31 -04:00
Zorg d1a5aae242 Merge branch 'master' into fileoperations 2015-09-18 01:51:23 -04:00
Zorg 2782b426d9 Reduce even more releasing quarantine duplication 2015-08-16 12:08:24 -04:00
Zorg 182652a231 Error if file doesn't exist when releasing quarantine 2015-08-16 11:01:04 -04:00
Zorg ba73e52f09 Reduce more duplication for releasing quarantine 2015-08-16 10:47:37 -04:00
Zorg 5b469d702e Reduce code duplication for releasing quarantine 2015-08-16 01:38:41 -04:00
Zorg 758ed1dc38 Remove installation URL != old URL case
By not taking account the rare case, we simplify the code by having
less duplication. The tradeoff is that the rare case will be slightly
less efficient.
2015-08-15 22:56:47 -04:00
Zorg 5d53d7277c Merge branch 'master' into fileoperations 2015-08-15 19:27:38 -04:00
Zorg ea959cbd87 Release quarantine for Autoupdate.app
I don't think this is actually needed, but better be safe than sorry.
2015-08-15 18:10:55 -04:00
Zorg fd7628e658 Don't follow symlinks for checking file existence 2015-08-15 17:39:06 -04:00
Zorg a746219a3f Merge branch 'master' into fileoperations 2015-07-28 21:04:34 -04:00
Zorg 62f7b7aa0c Merge branch 'master' into fileoperations 2015-07-26 22:48:13 -04:00
Zorg dbae37bb5b Make errors/directory names more user friendly
Since it is possible for the user to see these strings, we should not make them seem as 'gibberish' or unfriendly. More detailed error information is logged to the console.
2015-07-25 12:57:01 -04:00
Zorg d4b7a696af Append bundle version for older app when moving it 2015-07-25 12:13:16 -04:00
Zorg 19876c5a56 -moveItemAtURLToTrash:error: now works on 10.7 2015-07-24 23:47:16 -04:00
Zorg 9c8fb99184 Move deciding to abort an update into a procedure 2015-07-24 18:47:50 -04:00
Zorg 984c3dc0e1 Rewrote file operations for updating an app
The improvements we want to achieve:
* Stability - No more corrupt / incomplete updates by ensuring atomic move operations
* Efficiency - Faster updates because of reduction of file copies that need to be done
* Separation from Host and Helper - No usage of SUFileManager in the host application
* Cleanness - Minimized deprecated APIs (no FSPathMakeRef, FSGetCatalogInfo, FSFindFolder, etc), use modern Cocoa APIs when possible, robust error handling, strong documentation, easier to read code.

Many other small notes:
* SUFileManager does not have class methods. Methods across an instance share an AuthorizationRef, instead of having to authorize every time a privileged operation needs to be done
* The odd logic of `while (authStat == errAuthorizationDenied)` was removed
* Instead of checking if we have write access, we try to invoke a normal operation first. If that doesn't work, with the right error returned back, we try authorizing, which is what Apple recommends doing
* The trash is not used as a temporary location anymore. Rather we now request for a temporary directory to be created. This is more likely to succeed too (eg: on a drive that has no trash folder)
* The old method for releasing the quarantine did not work until I used the "com.apple.quarantine" key instead of the LS constant that was being used.
* For the old method for releasing the quarantine, we now check if a file has the quarantine xattr bit set before removing it. Just like how the new method works.
* Quarantines can now be removed with authorization
* The result of calling temporaryNameForPath: was never actually used in the old code
* -[NSString fileSystemRepresentation] which can throw an exception is not used. Only getFileSystemRepresentation:maxLength: is used and the error on it is always checked
* The desperate/hopeless check for if the code signature for the update is valid after the installation is complete is removed

Potential issues that still needs to be looked in to:
* Currently the method to move a file to the trash only works on 10.8+
* Appending of version number / picking destination name of app moved to trash
2015-07-22 23:38:07 -04:00
285 changed files with 10193 additions and 9010 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
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
+104 -17
View File
@@ -1,25 +1,112 @@
# 1.11.0
# 1.15.0
* 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.
- Rely on code signing and the DSA key in the new app instead of appcast. If the new app has a public DSA key, then the appcast item must have a DSA signature for the app, even if the app is code signed. (Zorg)
* Deprecated serving over http without DSA (Zorg)
* Removed extensions from shell scripts (Jake Petroules)
* 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.
- Faster.
- Using modern APIs where possible (no FSPathMakeRef, FSGetCatalogInfo, FSFindFolder, etc.)
- 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 macOS 10.11
* Improved Autoupdate application (Zorg)
* Do all the installation work after the runloop is set up
* TerminationListener only does termination listening now
* Handle cases where host path is not installation path and host path is not desired executable path
* Set LD_RUNPATH_SEARCH_PATHS in Podspec. (Jake Petroules)
* Don't show Autoupdate dock icon if we shouldn't show UI
* Update modification & access time for new update
* Added installUpdatesIfAvailable (Ian Langworth)
* Removed extensions from shell scripts (Jake Petroules)
* Rewritten test app so it works again, and from a local web server (Zorg)
* Replaced use of Python with built-in web server (Kevin Wojniak)
* Set LD_RUNPATH_SEARCH_PATHS in Podspec (Jake Petroules)
* Don't install automatic updates if the system might shut off (Zorg)
* Don't show Autoupdate dock icon if we shouldn't show UI (Zorg)
* Updated layout constraints when removing release notes (Zorg)
* Fix German localization (1024jp)
* Improved BinaryDelta error handling & logging (Zorg)
* Refactored quarantine removal (Zorg)
* Fixed German localization (1024jp)
* Updated zh_CN translation (LIU Dongyuan / 柳东原)
* Updated Mac models list until July 2015 (Gabriel Ulici)
* Updated Polish translation (Kornel Lesiński)
* Updated Xcode project languages for which we have translations (Jake Petroules)
* Updated XIB files (Kornel Lesiński)
* Use NSByteCountFormatter if available (Jake Petroules)
* Declared protocols on SUUpdateAlert for the 10.11 SDK (Daniel Jalkut)
* Silenced warning about casting away const-ness and -Wassign-enum (Daniel Jalkut)
* Rewritten test app so it works again, and from a local web server (Zorg)
* Added script to generate a report comparing the Sparkle.strings files (Kevin Wojniak)
* Check for empty strings (as well as nil) in SUHost's -name method (Karl Moskowski)
* Don't follow symlinks for checking file existence (Zorg)
* Unit tests in Swift (Zorg, Jake Petroules)
* Fixed framework imports (Felix Schulze)
* Fixed issues with copying files from different mounted drives (Zorg)
* 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 (Nov 9, 2015)
* Don't install automatic updates when system is about to shut down
# 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.
- Rely on code signing and the DSA key in the new app instead of appcast. If the new app has a public DSA key, then the appcast item must have a DSA signature for the app, even if the app is code signed. (Zorg)
* More verbose error message when DSA keys don't match (Kornel Lesiński)
* Added delegate methods for pre-download and immediately post-failed-download (Isaac Greenspan)
* Fix Lucida Grande is always used for release notes (LIU Dongyuan / 柳东原)
@@ -33,7 +120,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)
@@ -49,7 +136,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)
@@ -59,7 +146,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)
@@ -72,18 +159,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)
@@ -100,7 +187,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/
+9 -6
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,8 +16,8 @@ SPARKLE_AUTOMATED_DOWNGRADES = 0
SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME = 0
SPARKLE_VERSION_MAJOR = 1
SPARKLE_VERSION_MINOR = 12
SPARKLE_VERSION_PATCH = 0
SPARKLE_VERSION_MINOR = 15
SPARKLE_VERSION_PATCH = 1
SPARKLE_VERSION = $(SPARKLE_VERSION_MAJOR).$(SPARKLE_VERSION_MINOR).$(SPARKLE_VERSION_PATCH)
CURRENT_PROJECT_VERSION = $(SPARKLE_VERSION)
@@ -31,12 +32,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 +55,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 +90,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)
@@ -1,4 +0,0 @@
// Common
ARCHS = x86_64
VALID_ARCHS = x86_64
@@ -1,4 +0,0 @@
// Common
ARCHS = ppc i386 x86_64
+5
View File
@@ -0,0 +1,5 @@
// Fileop tool only
PRODUCT_NAME = $(SPARKLE_FILEOP_TOOL_NAME)
SKIP_INSTALL = YES
CLANG_ENABLE_MODULES = NO
+1 -1
View File
@@ -9,5 +9,5 @@ INFOPLIST_FILE = Sparkle/Sparkle-Info.plist
GCC_PREPROCESSOR_DEFINITIONS = $(inherited) BUILDING_SPARKLE=1
OTHER_LDFLAGS = -Wl,-U,_NSURLQuarantinePropertiesKey
SKIP_INSTALL = YES
DEFINES_MODULE = NO
DEFINES_MODULE = YES
PRODUCT_BUNDLE_IDENTIFIER = ${SPARKLE_BUNDLE_IDENTIFIER}
-10
View File
@@ -1,10 +0,0 @@
// Sandbox Service only
WRAPPER_EXTENSION = xpc
MACH_O_TYPE = mh_execute
MACOSX_DEPLOYMENT_TARGET = 10.7
MACOSX_DEPLOYMENT_TARGET[arch=x86_64] = 10.7
GCC_WARN_SHADOW = NO
GCC_WARN_ABOUT_DEPRECATED_FUNCTIONS = NO
GCC_WARN_ABOUT_MISSING_FIELD_INITIALIZERS = NO
@@ -1,5 +0,0 @@
#include "ConfigCommon.xcconfig"
#include "ConfigCommonDebug.xcconfig"
#include "ConfigService.xcconfig"
OTHER_CFLAGS = -DDEBUG
@@ -1,3 +0,0 @@
#include "ConfigCommon.xcconfig"
#include "ConfigCommonRelease.xcconfig"
#include "ConfigService.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 = -Ofast
-1
View File
@@ -5,4 +5,3 @@ WRAPPER_EXTENSION = app
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon
LD_RUNPATH_SEARCH_PATHS = @executable_path/../Frameworks
PRODUCT_BUNDLE_IDENTIFIER = org.sparkle-project.SparkleTestApp
GCC_PREPROCESSOR_DEFINITIONS = $(inherited) CODE_SIGN_IDENTITY="$(CODE_SIGN_IDENTITY)"
+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"
+7
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"
+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
BIN
View File
Binary file not shown.
+5
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,6 +22,9 @@ 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 \
+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)
+20 -10
View File
@@ -1,14 +1,14 @@
# Sparkle [![Build Status](https://travis-ci.org/sparkle-project/Sparkle.svg?branch=master)](https://travis-ci.org/sparkle-project/Sparkle) <a href='https://app.ship.io/dashboard#/jobs/8814/history' target='_blank'><img src='https://app.ship.io/jobs/V3PoCLcN5ft5Pnq0/build_status.png' height='20' /></a> [![Coverage Status](https://coveralls.io/repos/sparkle-project/Sparkle/badge.svg?branch=master&service=github)](https://coveralls.io/github/sparkle-project/Sparkle?branch=master)
# 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.
<img src="Resources/Screenshot.png" width="715" alt="Sparkle shows familiar update window with release notes">
<img src="Resources/Screenshot.png" width="732" 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+.
* Up-to-date with 10.11 SDK and Xcode 7. Supports macOS 10.7+.
* Important security fixes.
* 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.
@@ -17,31 +17,41 @@ An easy-to-use software update framework for Cocoa developers.
## Features
* Seamless integration—there's no mention of Sparkle; your icons and app name are used.
* True self-updating—the user can choose to automatically download and install all updates.
* Displays a detailed progress window to the user.
* Supports authentication for installing in secure locations.
* Supports Apple Code Signing and DSA signatures for ultra-secure updates.
* Easy to install. Sparkle requires no code in your app, so it's trivial to upgrade or remove the framework.
* Uses appcasts for release information. Appcasts are supported by 3rd party update-tracking programs and websites.
* Uses RSS-based appcasts for release information. Appcasts are supported by 3rd party update-tracking programs and websites.
* Displays release notes to the user via WebKit.
* Sparkle doesn't bug the user until second launch for better first impressions.
* 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.
* 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.
## Developers
## Requirements
Building Sparkle requires Xcode 5 or above.
* Runtime: macOS 10.7 or greater
* Build: Xcode 5 and 10.8 SDK or greater
* HTTPS server for serving updates (see [App Transport Security](http://sparkle-project.org/documentation/app-transport-security/))
### API
## API
Sparkle is built with `-fvisibility=hidden -fvisibility-inlines-hidden` which means no symbols are exported by default.
If you are adding a symbol to the public API you must decorate the declaration with the `SU_EXPORT` macro (grep the source code for examples).
### Building the distribution package
## Building the distribution package
`cd` to the root of the Sparkle source tree and run `make release`. Sparkle-*VERSION*.tar.bz2 will be created in a temporary directory and revealed in Finder after the build has completed.
Alternatively, build the Distribution scheme in the Xcode UI.
## Code of Conduct
We pledge to have an open and welcoming environment. See our [Code of Conduct](CODE_OF_CONDUCT.md).
## Project Sponsor
[StackPath](https://www.stackpath.com/?utm_source=sparkle-github&utm_medium=link&utm_campaign=readme-footer)
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

+7 -1
View File
@@ -47,7 +47,13 @@
<key>iMac14,4</key>
<string>iMac (Core i5, 21.5 inch Mid 2014)</string>
<key>iMac15,1</key>
<string>iMac (Retina 5K Core i5 or i7, 27 inch 2014 or 2015)</string>
<string>iMac (Retina 5K Core i5 or i7, 27 inch Late 2014 or Mid 2015)</string>
<key>iMac16,1</key>
<string>iMac (Core i5, 21,5 inch Late 2015)</string>
<key>iMac16,2</key>
<string>iMac (Retina 4K Core i5 or i7, 21.5 inch Late 2015)</string>
<key>iMac17,1</key>
<string>iMac (Retina 5K Core i5 or i7, 27 inch Late 2015)</string>
<key>MacBook1,1</key>
<string>MacBook (Core Duo)</string>
<key>MacBook2,1</key>
-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

-5
View File
@@ -1,5 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict/>
</plist>
+9 -6
View File
@@ -1,26 +1,29 @@
Pod::Spec.new do |s|
s.name = "Sparkle"
s.version = "1.11.0"
s.summary = "A software update framework for OS X"
s.version = "1.15.1"
s.summary = "A software update framework for macOS"
s.description = "Sparkle is an easy-to-use software update framework for Cocoa developers."
s.homepage = "http://sparkle-project.org"
s.documentation_url = "http://sparkle-project.org/documentation/"
s.screenshot = "http://sparkle-project.org/images/screenshot-noshadow@2x.png"
s.license = {
:type => 'MIT',
:file => 'LICENSE'
}
s.authors = {
'Andy Matuschak' => 'andy@andymatuschak.org',
'Mayur Pawashe' => 'zorgiepoo@gmail.com',
'Kornel Lesiński' => 'pornel@pornel.net',
'C.W. Betts' => 'computers57@hotmail.com',
'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_framework = 'Sparkle.framework'
s.resources = 'Sparkle.framework'
s.vendored_frameworks = 'Sparkle.framework'
s.xcconfig = {
'FRAMEWORK_SEARCH_PATHS' => '"${PODS_ROOT}/Sparkle"',
'LD_RUNPATH_SEARCH_PATHS' => '@loader_path/../Frameworks'
File diff suppressed because it is too large. Load diff
@@ -1,100 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0640"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "331726961B4D5F27008B2D77"
BuildableName = "libDevMateSparkle.a"
BlueprintName = "DevMateSparkle_lib"
ReferencedContainer = "container:Sparkle.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "NO"
buildForArchiving = "NO"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "331726A01B4D5F27008B2D77"
BuildableName = "DevMateSparkle_libTests.xctest"
BlueprintName = "DevMateSparkle_libTests"
ReferencedContainer = "container:Sparkle.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
buildConfiguration = "Debug">
<Testables>
</Testables>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "331726961B4D5F27008B2D77"
BuildableName = "libDevMateSparkle.a"
BlueprintName = "DevMateSparkle_lib"
ReferencedContainer = "container:Sparkle.xcodeproj">
</BuildableReference>
</MacroExpansion>
</TestAction>
<LaunchAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
buildConfiguration = "Debug"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
allowLocationSimulation = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "331726961B4D5F27008B2D77"
BuildableName = "libDevMateSparkle.a"
BlueprintName = "DevMateSparkle_lib"
ReferencedContainer = "container:Sparkle.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
buildConfiguration = "Release"
debugDocumentVersioning = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "331726961B4D5F27008B2D77"
BuildableName = "libDevMateSparkle.a"
BlueprintName = "DevMateSparkle_lib"
ReferencedContainer = "container:Sparkle.xcodeproj">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0700"
LastUpgradeVersion = "0800"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0700"
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>
+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>
+78 -48
View File
@@ -3,7 +3,6 @@
#import "SUHost.h"
#import "SUStandardVersionComparator.h"
#import "SUStatusController.h"
#import "SUPlainInstallerInternals.h"
#import "SULog.h"
#include <unistd.h>
@@ -46,7 +45,6 @@ static const NSTimeInterval SUParentQuitCheckInterval = .25;
{
[self.watchdogTimer invalidate];
completionBlock();
completionBlock = nil;
}
- (void)startListeningWithCompletion:(void (^)(void))completionBlock
@@ -72,6 +70,13 @@ static const NSTimeInterval SUParentQuitCheckInterval = .25;
*/
static const NSTimeInterval SUInstallationTimeLimit = 5;
/*!
* Terminate the application after a delay from launching the new update to avoid OS activation issues
* This delay should be be high enough to increase the likelihood that our updated app will be launched up front,
* but should be low enough so that the user doesn't ponder why the updater hasn't finished terminating yet
*/
static const NSTimeInterval SUTerminationTimeDelay = 0.5;
@interface AppInstaller : NSObject <NSApplicationDelegate>
/*
@@ -97,6 +102,8 @@ static const NSTimeInterval SUInstallationTimeLimit = 5;
@property (nonatomic, assign) BOOL shouldRelaunch;
@property (nonatomic, assign) BOOL shouldShowUI;
@property (nonatomic, assign) BOOL isTerminating;
@end
@implementation AppInstaller
@@ -108,6 +115,7 @@ static const NSTimeInterval SUInstallationTimeLimit = 5;
@synthesize relaunchPath = _relaunchPath;
@synthesize shouldRelaunch = _shouldRelaunch;
@synthesize shouldShowUI = _shouldShowUI;
@synthesize isTerminating = _isTerminating;
- (instancetype)initWithHostPath:(NSString *)hostPath relaunchPath:(NSString *)relaunchPath parentProcessId:(pid_t)parentProcessId updateFolderPath:(NSString *)updateFolderPath shouldRelaunch:(BOOL)shouldRelaunch shouldShowUI:(BOOL)shouldShowUI
{
@@ -129,12 +137,16 @@ static const NSTimeInterval SUInstallationTimeLimit = 5;
{
[self.terminationListener startListeningWithCompletion:^{
self.terminationListener = nil;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(SUInstallationTimeLimit * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
// Show app icon in the dock
ProcessSerialNumber psn = { 0, kCurrentProcess };
TransformProcessType(&psn, kProcessTransformToForegroundApplication);
});
if (self.shouldShowUI) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(SUInstallationTimeLimit * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
if (!self.isTerminating) {
// Show app icon in the dock
ProcessSerialNumber psn = { 0, kCurrentProcess };
TransformProcessType(&psn, kProcessTransformToForegroundApplication);
}
});
}
[self install];
}];
@@ -150,21 +162,32 @@ static const NSTimeInterval SUInstallationTimeLimit = 5;
self.statusController = [[SUStatusController alloc] initWithHost:host];
[self.statusController setButtonTitle:SULocalizedString(@"Cancel Update", @"") target:nil action:Nil isDefault:NO];
[self.statusController beginActionWithTitle:SULocalizedString(@"Installing update...", @"")
maxProgressValue: 0 statusText: @""];
maxProgressValue: 0 statusText: @""];
[self.statusController showWindow:self];
}
NSString *fileOperationToolPath = [[[[NSBundle mainBundle] executablePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@""SPARKLE_FILEOP_TOOL_NAME];
if (![[NSFileManager defaultManager] fileExistsAtPath:fileOperationToolPath]) {
SULog(@"Potential Installation Error: File operation tool path %@ is not found", fileOperationToolPath);
}
[SUInstaller installFromUpdateFolder:self.updateFolderPath
overHost:host
installationPath:installationPath
fileOperationToolPath:fileOperationToolPath
versionComparator:[SUStandardVersionComparator defaultComparator]
completionHandler:^(NSError *error) {
if (error) {
if (self.shouldShowUI) {
NSAlert *alert = [[NSAlert alloc] init];
alert.messageText = @"";
alert.informativeText = [NSString stringWithFormat:@"%@", [error localizedDescription]];
[alert runModal];
NSError *underlyingError = [error.userInfo objectForKey:NSUnderlyingErrorKey];
if (underlyingError == nil || underlyingError.code != SUInstallationCancelledError) {
SULog(@"Installation Error: %@", error);
if (self.shouldShowUI) {
NSAlert *alert = [[NSAlert alloc] init];
alert.messageText = @"";
alert.informativeText = [NSString stringWithFormat:@"%@", [error localizedDescription]];
[alert runModal];
}
}
exit(EXIT_FAILURE);
} else {
@@ -181,27 +204,44 @@ static const NSTimeInterval SUInstallationTimeLimit = 5;
}];
}
- (void)cleanupAndTerminateWithPathToRelaunch:(NSString *)relaunchPath __attribute__((noreturn))
- (void)cleanupAndTerminateWithPathToRelaunch:(NSString *)relaunchPath
{
if (self.shouldRelaunch) {
NSError *error = nil;
[[NSWorkspace sharedWorkspace] launchApplicationAtURL:[NSURL fileURLWithPath:relaunchPath]
options:NSWorkspaceLaunchNewInstance
configuration:@{}
error:&error];
if (error.code != noErr)
{
SULog(@"%ld - %@", error.code, error.localizedDescription);
self.isTerminating = YES;
dispatch_block_t cleanupAndExit = ^{
NSError *theError = nil;
if (![[NSFileManager defaultManager] removeItemAtPath:self.updateFolderPath error:&theError]) {
SULog(@"Couldn't remove update folder: %@.", theError);
}
[[NSFileManager defaultManager] removeItemAtPath:[[NSBundle mainBundle] bundlePath] error:NULL];
exit(EXIT_SUCCESS);
};
if (self.shouldRelaunch) {
// The auto updater can terminate before the newly updated app is finished launching
// If that happens, the OS may not make the updated app active and frontmost
// (Or it does become frontmost, but the OS backgrounds it afterwards.. It's some kind of timing/activation issue that doesn't occur all the time)
// The only remedy I've been able to find is waiting an arbitrary delay before exiting our application
// Don't use -launchApplication: because we may not be launching an application. Eg: it could be a system prefpane
if (![[NSWorkspace sharedWorkspace] openFile:relaunchPath]) {
SULog(@"Failed to launch %@", relaunchPath);
}
[self.statusController close];
// Don't even think about hiding the app icon from the dock if we've already shown it
// Transforming the app back to a background one has a backfiring effect, decreasing the likelihood
// that the updated app will be brought up front
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(SUTerminationTimeDelay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
cleanupAndExit();
});
} else {
cleanupAndExit();
}
NSError *theError = nil;
if (![SUPlainInstaller _removeFileAtPath:self.updateFolderPath error:&theError])
SULog(@"Couldn't remove update folder: %@.", theError);
[[NSFileManager defaultManager] removeItemAtPath:[[NSBundle mainBundle] bundlePath] error:NULL];
exit(EXIT_SUCCESS);
}
@end
@@ -217,29 +257,19 @@ 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];
NSConnection *connection = [[NSConnection alloc] init];
[connection setRootObject:appInstaller];
if (![connection registerName:[NSString stringWithFormat:@"Sparkle-%@", [NSBundle bundleWithPath:appInstaller.hostPath].bundleIdentifier]])
{
SULog(@"%@ server: could not register server. Is one already running?\n", args.firstObject);
}
[application setDelegate:appInstaller];
[application run];
// Ensure connection is not deallocated by ARC before caling -[NSApplication run]
[connection class];
}
return EXIT_SUCCESS;
+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 {
-40
View File
@@ -1,40 +0,0 @@
//
// DevMateSparkle.h
// Sparkle
//
// Created by Dmytro Tretiakov on 10/1/14.
//
//
#ifndef Sparkle_DevMateSparkle_h
#define Sparkle_DevMateSparkle_h
#import <Cocoa/Cocoa.h>
// If you are using your own copy of Sparkle.framework just define
// USED_CUSTOM_SPARKLE_FRAMEWORK macro.
#ifndef USED_CUSTOM_SPARKLE_FRAMEWORK
#define SUUpdater DM_SUUpdater
#define SUUpdaterQueue DM_SUUpdaterQueue
#define SUAppcast DM_SUAppcast
#define SUAppcastItem DM_SUAppcastItem
#define SUUpdaterDelegate DM_SUUpdaterDelegate
#define SUUpdaterDelegate_DevMateInteraction DM_SUUpdaterDelegate_DevMateInteraction
#define SUVersionComparison DM_SUVersionComparison
#define SUStandardVersionComparator DM_SUStandardVersionComparator
#define SUVersionDisplay DM_SUVersionDisplay
#import <DevMateSparkle/SUExport.h>
#import <DevMateSparkle/SUUpdater.h>
#import <DevMateSparkle/SUUpdaterQueue.h>
#import <DevMateSparkle/SUAppcast.h>
#import <DevMateSparkle/SUAppcastItem.h>
#import <DevMateSparkle/SUVersionComparisonProtocol.h>
#import <DevMateSparkle/SUStandardVersionComparator.h>
#import <DevMateSparkle/SUVersionDisplayProtocol.h>
#import <DevMateSparkle/SUErrors.h>
#endif // USED_CUSTOM_SPARKLE_FRAMEWORK
#endif // Sparkle_DevMateSparkle_h
-50
View File
@@ -1,50 +0,0 @@
//
// DevMateSparkle.pch
// Sparkle
//
// Created by Dmytro Tretiakov on 10/1/14.
//
//
#define SUUpdater DM_SUUpdater
#define SUUpdaterQueue DM_SUUpdaterQueue
#define SUAppcast DM_SUAppcast
#define SUAppcastItem DM_SUAppcastItem
#define SUUpdaterDelegate DM_SUUpdaterDelegate
#define SUUpdaterDelegate_DevMateInteraction DM_SUUpdaterDelegate_DevMateInteraction
#define SUVersionComparison DM_SUVersionComparison
#define SUStandardVersionComparator DM_SUStandardVersionComparator
#define SUVersionDisplay DM_SUVersionDisplay
#define SUPackageInstaller DM_SUPackageInstaller
#define SUDSAVerifier DM_SUDSAVerifier
#define SUUpdateAlert DM_SUUpdateAlert
#define SUUIBasedUpdateDriver DM_SUUIBasedUpdateDriver
#define SUSystemProfiler DM_SUSystemProfiler
#define SUXPCInstaller DM_SUXPCInstaller
#define SUPlainInstaller DM_SUPlainInstaller
#define SUUpdatePermissionPrompt DM_SUUpdatePermissionPrompt
#define SUUnarchiver DM_SUUnarchiver
#define SUUserInitiatedUpdateDriver DM_SUUserInitiatedUpdateDriver
#define SUUpdateDriver DM_SUUpdateDriver
#define SUProbingUpdateDriver DM_SUProbingUpdateDriver
#define SUAutomaticUpdateAlert DM_SUAutomaticUpdateAlert
#define SUBasicUpdateDriver DM_SUBasicUpdateDriver
#define SUWindowController DM_SUWindowController
#define SUStatusController DM_SUStatusController
#define SUHost DM_SUHost
#define SUPipedUnarchiver DM_SUPipedUnarchiver
#define SUAutomaticUpdateDriver DM_SUAutomaticUpdateDriver
#define SUCodeSigningVerifier DM_SUCodeSigningVerifier
#define SUBinaryDeltaUnarchiver DM_SUBinaryDeltaUnarchiver
#define SUDelegateProxy DM_SUDelegateProxy
#define SUInstaller DM_SUInstaller
#define SUScheduledUpdateDriver DM_SUScheduledUpdateDriver
#define SUDiskImageUnarchiver DM_SUDiskImageUnarchiver
#define SUGuidedPackageInstaller DM_SUGuidedPackageInstaller
#define NTSynchronousTask DM_NTSynchronousTask
#define SUUpdaterWorking DM_SUUpdater // Used in SUUpdaterLoader.m file
#define SUUpdaterLoader DM_SUUpdaterLoader
#import "Sparkle.pch"
@@ -1,4 +0,0 @@
//
// Prefix header for all source files of the 'Downloading XPC Service' target in the 'Downloading XPC Service' project
//
-60
View File
@@ -1,60 +0,0 @@
//
// SUDSDownloader.h
// Sparkle
//
// Created by Dmytro Tretiakov on 8/1/13.
//
//
#import <Foundation/Foundation.h>
#define DEBUG_LOGGING_ENABLED defined(DEBUG) && 1
@class SUDSDownloader;
typedef void (^SUDSDownloadDidBegin)(SUDSDownloader *downloader);
typedef void (^SUDSDownloadDidFinish)(SUDSDownloader *downloader);
typedef void (^SUDSDownloadDidFail)(SUDSDownloader *downloader, NSError *error);
typedef void (^SUDSDownloadDidReceiveResponse)(SUDSDownloader *downloader, NSURLResponse *response);
typedef void (^SUDSDownloadDidReceiveData)(SUDSDownloader *downloader, NSUInteger dataLength);
typedef void (^SUDSDownloadDidCreateDestination)(SUDSDownloader *downloader, NSString *destinationPath);
typedef BOOL (^SUDSDownloadShouldDecodeSourceData)(SUDSDownloader *downloader, NSString *MIMEType);
typedef struct SUDSDownloaderCallBacks
{
SUDSDownloadDidBegin downloadDidBegin;
SUDSDownloadDidFinish downloadDidFinish;
SUDSDownloadDidFail downloadDidFail;
SUDSDownloadDidReceiveResponse downloadDidReceiveResponse;
SUDSDownloadDidReceiveData downloadDidReceiveData;
SUDSDownloadDidCreateDestination downloadDidCreateDestination;
SUDSDownloadShouldDecodeSourceData downloadShouldDecodeSourceData;
} SUDSDownloaderCallBacks;
FOUNDATION_EXTERN SUDSDownloaderCallBacks SUDSCopyDownloaderCallBacks(SUDSDownloaderCallBacks callBacks);
FOUNDATION_EXTERN void SUDSReleaseDownloaderCallBacks(SUDSDownloaderCallBacks callBacks);
@interface SUDSDownloader : NSObject <NSURLDownloadDelegate>
{
@private
NSURLRequest *_request;
NSString *_destFilePath;
SUDSDownloaderCallBacks _callBacks;
NSURLDownload *_download;
}
- (id)initWithURLRequest:(NSURLRequest *)request destinationPath:(NSString *)filePath;
+ (id)downloaderWithURLRequest:(NSURLRequest *)request destinationPath:(NSString *)filePath;
- (NSURLRequest *)request;
- (NSString *)destinationPath;
- (void)setCallBacks:(SUDSDownloaderCallBacks)callBacks;
- (void)startDownload;
- (void)stopDownload;
- (BOOL)isInProgress;
@end
-210
View File
@@ -1,210 +0,0 @@
//
// SUDSDownloader.m
// Sparkle
//
// Created by Dmytro Tretiakov on 8/1/13.
//
//
#import "SUDSDownloader.h"
SUDSDownloaderCallBacks SUDSCopyDownloaderCallBacks(SUDSDownloaderCallBacks callBacks)
{
SUDSDownloaderCallBacks callBacksCopy = {0};
if (callBacks.downloadDidBegin)
callBacksCopy.downloadDidBegin = Block_copy(callBacks.downloadDidBegin);
if (callBacks.downloadDidFinish)
callBacksCopy.downloadDidFinish = Block_copy(callBacks.downloadDidFinish);
if (callBacks.downloadDidFail)
callBacksCopy.downloadDidFail = Block_copy(callBacks.downloadDidFail);
if (callBacks.downloadDidReceiveData)
callBacksCopy.downloadDidReceiveData = Block_copy(callBacks.downloadDidReceiveData);
if (callBacks.downloadDidCreateDestination)
callBacksCopy.downloadDidCreateDestination = Block_copy(callBacks.downloadDidCreateDestination);
if (callBacks.downloadDidReceiveResponse)
callBacksCopy.downloadDidReceiveResponse = Block_copy(callBacks.downloadDidReceiveResponse);
if (callBacks.downloadShouldDecodeSourceData)
callBacksCopy.downloadShouldDecodeSourceData = Block_copy(callBacks.downloadShouldDecodeSourceData);
return callBacksCopy;
}
void SUDSReleaseDownloaderCallBacks(SUDSDownloaderCallBacks callBacks)
{
if (callBacks.downloadDidBegin)
Block_release(callBacks.downloadDidBegin);
if (callBacks.downloadDidFinish)
Block_release(callBacks.downloadDidFinish);
if (callBacks.downloadDidFail)
Block_release(callBacks.downloadDidFail);
if (callBacks.downloadDidReceiveData)
Block_release(callBacks.downloadDidReceiveData);
if (callBacks.downloadDidCreateDestination)
Block_release(callBacks.downloadDidCreateDestination);
if (callBacks.downloadDidReceiveResponse)
Block_release(callBacks.downloadDidReceiveResponse);
if (callBacks.downloadShouldDecodeSourceData)
Block_release(callBacks.downloadShouldDecodeSourceData);
}
@implementation SUDSDownloader
- (id)initWithURLRequest:(NSURLRequest *)request destinationPath:(NSString *)filePath
{
self = [super init];
if (self != nil)
{
_request = [request retain];
_destFilePath = [filePath copy];
}
return self;
}
+ (id)downloaderWithURLRequest:(NSURLRequest *)request destinationPath:(NSString *)filePath
{
return [[[[self class] alloc] initWithURLRequest:request destinationPath:filePath] autorelease];
}
- (void)dealloc
{
[self stopDownload];
[_request release];
[_destFilePath release];
SUDSReleaseDownloaderCallBacks(_callBacks);
[super dealloc];
}
- (NSURLRequest *)request
{
return _request;
}
- (NSString *)destinationPath
{
return _destFilePath;
}
- (void)setCallBacks:(SUDSDownloaderCallBacks)callBacks
{
SUDSDownloaderCallBacks oldCallBacks = _callBacks;
_callBacks = SUDSCopyDownloaderCallBacks(callBacks);
SUDSReleaseDownloaderCallBacks(oldCallBacks);
}
- (void)startDownload
{
[self stopDownload];
// to ensure that parent folder exists
[[NSFileManager defaultManager] createDirectoryAtPath:[_destFilePath stringByDeletingLastPathComponent]
withIntermediateDirectories:YES
attributes:nil
error:NULL];
NSURLDownload *urlDownload = [[NSURLDownload alloc] initWithRequest:_request delegate:self];
@synchronized (self)
{
_download = urlDownload;
}
[urlDownload setDestination:_destFilePath allowOverwrite:YES];
}
- (void)stopDownload
{
@synchronized (self)
{
[_download cancel];
[_download release];
_download = nil;
}
}
- (BOOL)isInProgress
{
BOOL result = YES;
@synchronized (self)
{
result = _download != nil;
}
return result;
}
#pragma mark -
- (void)downloadDidBegin:(NSURLDownload *)download
{
#if DEBUG_LOGGING_ENABLED
NSLog(@"XPC Downloader did begin process.");
#endif
if (_callBacks.downloadDidBegin)
_callBacks.downloadDidBegin(self);
}
- (void)download:(NSURLDownload *)download didReceiveResponse:(NSURLResponse *)response
{
#if DEBUG_LOGGING_ENABLED
NSLog(@"XPC Downloader did receive response: %@", [response description]);
#endif
if (_callBacks.downloadDidReceiveResponse)
_callBacks.downloadDidReceiveResponse(self, response);
}
- (void)download:(NSURLDownload *)download didCreateDestination:(NSString *)path
{
#if DEBUG_LOGGING_ENABLED
NSLog(@"XPC Downloader did create destination: %@", path);
#endif
if (_callBacks.downloadDidCreateDestination)
_callBacks.downloadDidCreateDestination(self, path);
}
- (void)download:(NSURLDownload *)download didReceiveDataOfLength:(NSUInteger)length
{
#if DEBUG_LOGGING_ENABLED
NSLog(@"XPC Downloader did receive data of length %ld bytes", (unsigned long)length);
#endif
if (_callBacks.downloadDidReceiveData)
_callBacks.downloadDidReceiveData(self, length);
}
- (void)download:(NSURLDownload *)download didFailWithError:(NSError *)error
{
#if DEBUG_LOGGING_ENABLED
NSLog(@"XPC Downloader did fail: %@", [error description]);
#endif
if (_callBacks.downloadDidFail)
_callBacks.downloadDidFail(self, error);
[self stopDownload];
}
- (void)downloadDidFinish:(NSURLDownload *)download
{
#if DEBUG_LOGGING_ENABLED
NSLog(@"XPC Downloader did finish");
#endif
if (_callBacks.downloadDidFinish)
_callBacks.downloadDidFinish(self);
[self stopDownload];
}
- (BOOL)download:(NSURLDownload *)download shouldDecodeSourceDataOfMIMEType:(NSString *)encodingType
{
BOOL shouldDecode = NO;
#if DEBUG_LOGGING_ENABLED
NSLog(@"XPC Downloader wants decode source data of MIME type: %@", encodingType);
#endif
if (_callBacks.downloadShouldDecodeSourceData)
shouldDecode = _callBacks.downloadShouldDecodeSourceData(self, encodingType);
return shouldDecode;
}
@end
@@ -1,29 +0,0 @@
//
// SUDownloadServiceConstants.h
// Sparkle
//
// Created by Dmytro Tretiakov on 7/29/13.
//
//
#ifndef Sparkle_SUDownloadServiceConstants_h
#define Sparkle_SUDownloadServiceConstants_h
const char * SUDownloadServiceURLRequestDataKey = "request_data"; // data of archived NSURLRequest
const char * SUDownloadServiceDelegateConnectionKey = "connection"; // xpc_connection_t
const char * SUDownloadServiceFilePathKey = "file_path"; // c-string
const char * SUDownloadServiceReceivedDataLengthKey = "received_data_length"; // int64_t
const char * SUDownloadServiceReceivedResponseDataKey = "received_response_data"; // data of archived NSURLResponse
const char * SUDownloadServiceCreatedDestinationPathKey = "created_destination_path"; // c-string
const char * SUDownloadServiceDidBeginDownloadingKey = "did_begin_downloading"; // bool 1
const char * SUDownloadServiceDidFinishDownloadingKey = "did_finish_downloading"; // bool 1
const char * SUDownloadServiceReceivedFailErrorKey = "received_fail_error"; // data of archived NSError
const char * SUDownloadServiceMIMETypeToDecodeKey = "MIME_type_to_decode"; // c-string
const char * SUDownloadServiceShouldDecodeMIMETypeKey = "should_decode_MIME_type"; // bool
const char * SUDownloadServiceErrorCodeKey = "errcode"; // int64_t
const char * SUDownloadServiceErrorMessageKey = "errmsg"; // c-string
const char * SUDownloadServiceErrorDomainKey = "errdomain"; // c-string
#endif
-36
View File
@@ -1,36 +0,0 @@
//
// SUXPCURLDownload.h
// Sparkle
//
// Created by Erik Aderstedt on 2012-08-09.
//
//
#import <Foundation/Foundation.h>
@interface SUXPCURLDownload : NSObject
{
@private
id <NSURLDownloadDelegate> _delegate; // weak ref
xpc_connection_t _connection;
xpc_connection_t _delegateConnection;
NSURLRequest *_request;
NSThread *_startedThread; // weak ref
BOOL _isDownloading;
BOOL _allowOverwrite;
NSString *_destination;
NSString *_connectionDestination;
NSError *_downloadError;
}
- (id <NSURLDownloadDelegate>)delegate;
- (void)setDelegate:(id <NSURLDownloadDelegate>)delegate;
- (id)initWithRequest:(NSURLRequest *)request delegate:(id <NSURLDownloadDelegate>)delegate;
- (void)setDestination:(NSString *)path allowOverwrite:(BOOL)allowOverwrite;
// Delegate methods for this method will be called from another thread.
+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request delegate:(id <NSURLDownloadDelegate>)delegate;
@end
-448
View File
@@ -1,448 +0,0 @@
//
// SUXPCURLDownload.m
// Sparkle
//
// Created by Erik Aderstedt on 2012-08-09.
//
//
#import "SUXPCURLDownload.h"
#import "SUDownloadServiceConstants.h"
#import "SUConstants.h"
#import "SULog.h"
static NSString * const kSUFetchFolderName = @"fetch.XXXXXXXX";
@interface SUXPCURLDownload (Private)
- (void)performBlock:(void (^)(void))block onThread:(NSThread *)thread synchronous:(BOOL)flag;
- (void)fireBlock:(void (^)(void))block;
@end
@implementation SUXPCURLDownload
+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request delegate:(id <NSURLDownloadDelegate>)delegate
{
__block SUXPCURLDownload *download = nil;
static const char *sSynchronousDownloadQueueName = "com.devmate.SynchronousXPCDownloadQueue";
dispatch_queue_t queue = dispatch_queue_create(sSynchronousDownloadQueueName, NULL);
dispatch_sync(queue, ^{
download = [[SUXPCURLDownload alloc] initWithRequest:request delegate:delegate];
});
while (download && download->_isDownloading)
{
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.5]];
}
NSData *downloadData = (nil == download->_downloadError) ? [NSData dataWithContentsOfFile:download->_destination] : nil;
[download release];
dispatch_release(queue);
return downloadData;
}
- (id)initWithRequest:(NSURLRequest *)request delegate:(id <NSURLDownloadDelegate>)delegate
{
self = [super init];
if (self != nil)
{
_request = [request retain];
_delegate = [delegate retain];
_startedThread = [NSThread currentThread];
// Set up a connection.
_connection = [self getSandboxXPCService];
dispatch_async(dispatch_get_current_queue(), ^{
[self startDownload:request];
});
_isDownloading = YES;
}
return self;
}
- (void)dealloc
{
[self cancel];
[_request release];
[_destination release];
[_connectionDestination release];
[_downloadError release];
[super dealloc];
}
- (NSURLRequest *)request
{
return _request;
}
- (void)startDownload:(NSURLRequest *)urlRequest
{
// Send a message to download a specific url.
if ([_delegate respondsToSelector:@selector(download:decideDestinationWithSuggestedFilename:)] && _destination == nil)
{
void (^block)(void) = ^{
[_delegate download:(NSURLDownload *)self decideDestinationWithSuggestedFilename:[[urlRequest URL] lastPathComponent]];
};
[self performBlock:block onThread:_startedThread synchronous:YES];
}
if (nil == _destination)
{
_destination = [[[urlRequest URL] lastPathComponent] copy];
}
// ivar 'destination' now contains the destination URL.
NSURL *tempFolder = [NSURL fileURLWithPath:NSTemporaryDirectory()];
NSString *tempFileTemplate = [[tempFolder URLByAppendingPathComponent:kSUFetchFolderName] path];
NSString *tempFilePath = [tempFileTemplate stringByAppendingPathComponent:[_destination lastPathComponent]];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:tempFilePath])
[fileManager removeItemAtPath:tempFilePath error:nil];
_connectionDestination = [tempFilePath copy];
NSData *requestData = [NSKeyedArchiver archivedDataWithRootObject:urlRequest];
xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0);
xpc_dictionary_set_data(message, SUDownloadServiceURLRequestDataKey, [requestData bytes], [requestData length]);
xpc_dictionary_set_string(message, SUDownloadServiceFilePathKey, [tempFilePath cStringUsingEncoding:NSUTF8StringEncoding]);
xpc_dictionary_set_connection(message, SUDownloadServiceDelegateConnectionKey, _delegateConnection);
xpc_connection_send_message_with_reply(_connection, message, dispatch_get_main_queue(), ^(xpc_object_t object) {
xpc_type_t type = xpc_get_type(object);
if (type == XPC_TYPE_ERROR && nil == _downloadError)
{
NSString *errMessage = @"";
if (object == XPC_ERROR_CONNECTION_INTERRUPTED)
{
errMessage = @"Got XPC_ERROR_CONNECTION_INTERRUPTED error.";
}
else if (object == XPC_ERROR_CONNECTION_INVALID)
{
errMessage = @"Got XPC_ERROR_CONNECTION_INVALID error.";
}
NSDictionary *errInfo = [NSDictionary dictionaryWithObject:errMessage forKey:NSLocalizedDescriptionKey];
_downloadError = [[NSError alloc] initWithDomain:SUSparkleErrorDomain code:SUXPCServiceError userInfo:errInfo];
}
else if (type == XPC_TYPE_DICTIONARY && noErr != xpc_dictionary_get_int64(object, SUDownloadServiceErrorCodeKey) && nil == _downloadError)
{
NSInteger errCode = (NSInteger)xpc_dictionary_get_int64(object, SUDownloadServiceErrorCodeKey);
const char *errDomainStr = xpc_dictionary_get_string(object, SUDownloadServiceErrorDomainKey);
NSString *errDomain = errDomainStr ? [NSString stringWithUTF8String:errDomainStr] : NSCocoaErrorDomain;
const char *errMessage = xpc_dictionary_get_string(object, SUDownloadServiceErrorMessageKey) ? : "";
NSDictionary *errInfo = [NSDictionary dictionaryWithObject:[NSString stringWithUTF8String:errMessage]
forKey:NSLocalizedDescriptionKey];
_downloadError = [[NSError alloc] initWithDomain:errDomain code:errCode userInfo:errInfo];
}
if (nil != _downloadError)
{
if ([_delegate respondsToSelector:@selector(download:didFailWithError:)])
{
void (^block)(void) = ^{
[_delegate download:(NSURLDownload *)self didFailWithError:_downloadError];
_isDownloading = NO;
};
[self performBlock:block onThread:_startedThread synchronous:NO];
}
else
{
SULog(@"SUXPCURLDownload: got download error (%d - %@)", [_downloadError code], [_downloadError localizedDescription]);
_isDownloading = NO;
}
}
});
xpc_release(message);
}
- (id <NSURLDownloadDelegate>)delegate
{
return _delegate;
}
- (void)setDelegate:(id <NSURLDownloadDelegate>)delegate
{
_delegate = delegate;
}
- (void)setDestination:(NSString *)path allowOverwrite:(BOOL)allowOverwrite
{
[_destination release];
_destination = [path copy];
_allowOverwrite = allowOverwrite;
}
- (void)cancel
{
if (_connection)
{
xpc_connection_cancel(_connection);
xpc_release(_connection);
_connection = NULL;
}
if (_delegateConnection)
{
xpc_connection_cancel(_delegateConnection);
xpc_release(_delegateConnection);
_delegateConnection = NULL;
}
}
- (xpc_connection_t)getSandboxXPCService
{
// Set up two connections, one for instructing the XPC and getting a response,
// and another to listen for incoming connections for progress and file creation
// notifications.
_connection = xpc_connection_create("com.devmate.UpdateDownloader", dispatch_get_main_queue());
if (!_connection)
{
NSLog(@"Can't connect to XPC service");
return (NULL);
}
xpc_connection_set_event_handler(_connection, ^(xpc_object_t event) {
xpc_type_t type = xpc_get_type(event);
if (type == XPC_TYPE_ERROR)
{
if (event == XPC_ERROR_CONNECTION_INTERRUPTED)
{
NSLog(@"Got XPC_ERROR_CONNECTION_INTERRUPTED error.");
// The service has either cancaled itself, crashed, or been
// terminated. The XPC connection is still valid and sending a
// message to it will re-launch the service. If the service is
// state-full, this is the time to initialize the new service.
}
else if (event == XPC_ERROR_CONNECTION_INVALID)
{
NSLog(@"Got XPC_ERROR_CONNECTION_INVALID error.");
// The service is invalid. Either the service name supplied to
// xpc_connection_create() is incorrect or we (this process) have
// canceled the service; we can do any cleanup of appliation
// state at this point.
if (_delegateConnection)
{
xpc_connection_cancel(_delegateConnection);
xpc_release(_delegateConnection);
_delegateConnection = NULL;
}
}
}
});
dispatch_queue_t delegate_queue = dispatch_queue_create("com.devmate.UpdateDownloader.delegate", NULL);
assert(delegate_queue != NULL);
_delegateConnection = xpc_connection_create(NULL, delegate_queue);
xpc_connection_set_event_handler(_delegateConnection, ^(xpc_object_t event) {
xpc_type_t type = xpc_get_type(event);
if (type == XPC_TYPE_ERROR)
{
if (event == XPC_ERROR_TERMINATION_IMMINENT)
{
NSLog(@"received XPC_ERROR_TERMINATION_IMMINENT");
}
else if (event == XPC_ERROR_CONNECTION_INVALID)
{
NSLog(@"progress connection is closed");
dispatch_release(delegate_queue);
}
}
else if (type == XPC_TYPE_CONNECTION)
{
xpc_connection_t peer = (xpc_connection_t)event;
// A new anonymous connection, from an XPC service that wants to supply us with updates.
char *queue_name = NULL;
dispatch_queue_t peer_event_queue = dispatch_queue_create(queue_name, NULL);
assert(peer_event_queue != NULL);
free(queue_name);
xpc_connection_set_target_queue(peer, peer_event_queue);
xpc_connection_set_event_handler(peer, ^(xpc_object_t nevent) {
xpc_type_t ntype = xpc_get_type(nevent);
if (ntype == XPC_TYPE_ERROR && nevent == XPC_ERROR_CONNECTION_INVALID)
dispatch_release(peer_event_queue);
if (ntype != XPC_TYPE_DICTIONARY)
return;
__block xpc_object_t answer = xpc_dictionary_create_reply(nevent);
xpc_dictionary_apply(nevent, ^bool(const char *key, xpc_object_t value) {
NSAutoreleasePool *localPool = [[NSAutoreleasePool alloc] init];
if (0 == strcmp(key, SUDownloadServiceDidBeginDownloadingKey))
{
if ([_delegate respondsToSelector:@selector(downloadDidBegin:)])
{
void (^block)(void) = ^ {
[_delegate downloadDidBegin:(NSURLDownload *)self];
};
[self performBlock:block onThread:_startedThread synchronous:NO];
}
}
else if (0 == strcmp(key, SUDownloadServiceReceivedResponseDataKey))
{
if ([_delegate respondsToSelector:@selector(download:didReceiveResponse:)])
{
size_t dataLength = 0;
const void * responseDataBytes = xpc_dictionary_get_data(nevent, SUDownloadServiceReceivedResponseDataKey, &dataLength);
NSData *responseData = [NSData dataWithBytes:responseDataBytes length:(NSUInteger)dataLength];
NSURLResponse *response = [NSKeyedUnarchiver unarchiveObjectWithData:responseData];
void (^block)(void) = ^ {
[_delegate download:(NSURLDownload *)self didReceiveResponse:response];
};
[self performBlock:block onThread:_startedThread synchronous:NO];
}
}
else if (0 == strcmp(key, SUDownloadServiceReceivedDataLengthKey))
{
if ([_delegate respondsToSelector:@selector(download:didReceiveDataOfLength:)])
{
int64_t dataLength = xpc_dictionary_get_int64(nevent, SUDownloadServiceReceivedDataLengthKey);
void (^block)(void) = ^ {
[_delegate download:(NSURLDownload *)self didReceiveDataOfLength:(NSUInteger)dataLength];
};
[self performBlock:block onThread:_startedThread synchronous:NO];
}
}
else if (0 == strcmp(key, SUDownloadServiceCreatedDestinationPathKey))
{
[_connectionDestination release];
_connectionDestination = [[NSString alloc] initWithCString:xpc_dictionary_get_string(nevent, SUDownloadServiceCreatedDestinationPathKey)
encoding:NSUTF8StringEncoding];
}
else if (0 == strcmp(key, SUDownloadServiceReceivedFailErrorKey))
{
size_t dataLength = 0;
const void * errorDataBytes = xpc_dictionary_get_data(nevent, SUDownloadServiceReceivedFailErrorKey, &dataLength);
NSData *errorData = [NSData dataWithBytes:errorDataBytes length:dataLength];
NSError *error = [NSKeyedUnarchiver unarchiveObjectWithData:errorData];
_downloadError = [error retain];
}
else if (0 == strcmp(key, SUDownloadServiceDidFinishDownloadingKey))
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *destPath = _destination;
if (nil == destPath || [destPath isEqualToString:[destPath lastPathComponent]])
{
destPath = _connectionDestination;
}
else if (!_allowOverwrite)
{
NSUInteger index = 1;
NSString *parentFolder = [destPath stringByDeletingLastPathComponent];
NSString *initialFileName = [[destPath lastPathComponent] stringByDeletingPathExtension];
NSString *fileExtension = [destPath pathExtension];
while ([fileManager fileExistsAtPath:destPath])
{
NSString *fileName = [initialFileName stringByAppendingFormat:@"_%ld", index];
destPath = [[parentFolder stringByAppendingPathComponent:fileName] stringByAppendingPathExtension:fileExtension];
++index;
}
}
NSError *error = nil;
BOOL success = YES;
if (![destPath isEqualToString:_connectionDestination])
{
success = success && [fileManager createDirectoryAtPath:[destPath stringByDeletingLastPathComponent]
withIntermediateDirectories:YES
attributes:nil
error:&error];
if (success && [fileManager fileExistsAtPath:destPath])
success = [fileManager removeItemAtPath:destPath error:&error];
success = success && [fileManager moveItemAtPath:_connectionDestination toPath:destPath error:&error];
}
if (success)
{
[self setDestination:destPath allowOverwrite:_allowOverwrite];
void (^block)(void) = ^ {
if ([_delegate respondsToSelector:@selector(download:didCreateDestination:)])
[_delegate download:(NSURLDownload *)self didCreateDestination:destPath];
if ([_delegate respondsToSelector:@selector(downloadDidFinish:)])
[_delegate downloadDidFinish:(NSURLDownload *)self];
_isDownloading = NO;
};
[self performBlock:block onThread:_startedThread synchronous:NO];
}
else
{
_downloadError = [error retain];
}
}
else if (0 == strcmp(key, SUDownloadServiceMIMETypeToDecodeKey))
{
void (^block)(void) = ^{
BOOL shouldDecode = NO;
if ([_delegate respondsToSelector:@selector(download:shouldDecodeSourceDataOfMIMEType:)])
{
NSString *MIMEType = [NSString stringWithCString:xpc_dictionary_get_string(nevent, SUDownloadServiceMIMETypeToDecodeKey)
encoding:NSUTF8StringEncoding];
shouldDecode = [_delegate download:(NSURLDownload *)self shouldDecodeSourceDataOfMIMEType:MIMEType];
}
xpc_dictionary_set_bool(answer, SUDownloadServiceShouldDecodeMIMETypeKey, YES);
};
[self performBlock:block onThread:_startedThread synchronous:YES];
}
[localPool release];
return true;
});
xpc_connection_send_message(peer, answer);
xpc_release(answer);
});
xpc_connection_resume(peer);
}
});
// Need to resume the service in order for it to process messages.
xpc_connection_resume(_delegateConnection);
xpc_connection_resume(_connection);
return _connection;
}
#pragma mark - Private
- (void)performBlock:(void (^)(void))block onThread:(NSThread *)thread synchronous:(BOOL)flag
{
void (^blockCopy)(void) = block != NULL ? Block_copy(block) : NULL;
[self performSelector:@selector(fireBlock:) onThread:thread withObject:blockCopy waitUntilDone:flag];
}
- (void)fireBlock:(void (^)(void))block
{
if (NULL == block)
return;
block();
Block_release(block);
}
@end
-265
View File
@@ -1,265 +0,0 @@
//
// main.m
// Downloading XPC Service
//
// Created by Erik Aderstedt on 2012-08-09.
// Based on the Apple sample code 'SandboxedFetch'.
//
#import <xpc/xpc.h>
#import <asl.h>
#import <assert.h>
#import <errno.h>
#import <stdio.h>
#import "SUDownloadServiceConstants.h"
#import "SUDSDownloader.h"
#import "SUConstants.h"
static void fetch_process_request(xpc_object_t request, xpc_object_t reply);
static void fetch_peer_event_handler(xpc_connection_t peer, xpc_object_t event);
static void fetch_event_handler(xpc_connection_t peer);
#pragma mark -
// Process the XPC request, create a temporary file to hold downloaded,
// data, and build/return XPC reply.
static void fetch_process_request(xpc_object_t request, xpc_object_t reply)
{
__block int32_t errcode = 0;
__block const char *errmsg = NULL;
__block const char *errdomain = NULL;
xpc_connection_t connection = NULL;
NSAutoreleasePool *localPool = [[NSAutoreleasePool alloc] init];
do
{
size_t dataLength = 0;
const void *data = xpc_dictionary_get_data(request, SUDownloadServiceURLRequestDataKey, &dataLength);
NSData *requestData = [NSData dataWithBytes:data length:dataLength];
NSURLRequest *urlRequest = [NSKeyedUnarchiver unarchiveObjectWithData:requestData];
if (nil == urlRequest)
{
errcode = SUXPCServiceError;
errdomain = [SUSparkleErrorDomain cStringUsingEncoding:NSUTF8StringEncoding];
errmsg = "Invalid URL request data";
break;
}
// Get the URL and XPC connection from the XPC request
connection = xpc_dictionary_create_connection(request, SUDownloadServiceDelegateConnectionKey);
if (connection == NULL)
{
errcode = SUXPCServiceError;
errdomain = [SUSparkleErrorDomain cStringUsingEncoding:NSUTF8StringEncoding];
errmsg = "Invalid XPC delegate connection";
break;
}
// Set up XPC connection endpoint for sending progress reports and receiving cancel notification.
__block BOOL shouldStopDownload = NO;
xpc_connection_set_event_handler(connection, ^(xpc_object_t event) {
xpc_type_t type = xpc_get_type(event);
// If the remote end of this connection has gone away then stop download
if (XPC_TYPE_ERROR == type &&
(XPC_ERROR_CONNECTION_INTERRUPTED == event || XPC_ERROR_CONNECTION_INVALID == event))
{
asl_log(NULL, NULL, ASL_LEVEL_NOTICE, "Stopping download process...\n");
shouldStopDownload = YES;
}
});
xpc_connection_resume(connection);
NSString *destinationPath = [NSString stringWithCString:xpc_dictionary_get_string(request, SUDownloadServiceFilePathKey)
encoding:NSUTF8StringEncoding];
SUDSDownloader *downloader = [SUDSDownloader downloaderWithURLRequest:urlRequest
destinationPath:destinationPath];
SUDSDownloaderCallBacks callBacks = {0};
callBacks.downloadDidReceiveData = ^(SUDSDownloader *downloader, NSUInteger dataLength) {
xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0);
xpc_dictionary_set_int64(message, SUDownloadServiceReceivedDataLengthKey, (int64_t)dataLength);
xpc_object_t answer = xpc_connection_send_message_with_reply_sync(connection, message);
xpc_release(message);
xpc_release(answer);
};
callBacks.downloadDidReceiveResponse = ^(SUDSDownloader *downloader, NSURLResponse *response) {
NSData *responseData = [NSKeyedArchiver archivedDataWithRootObject:response];
xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0);
xpc_dictionary_set_data(message, SUDownloadServiceReceivedResponseDataKey, [responseData bytes], [responseData length]);
xpc_object_t answer = xpc_connection_send_message_with_reply_sync(connection, message);
xpc_release(message);
xpc_release(answer);
};
callBacks.downloadDidCreateDestination = ^(SUDSDownloader *downloader, NSString *destinationPath) {
xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0);
xpc_dictionary_set_string(message, SUDownloadServiceCreatedDestinationPathKey, [destinationPath cStringUsingEncoding:NSUTF8StringEncoding]);
xpc_object_t answer = xpc_connection_send_message_with_reply_sync(connection, message);
xpc_release(message);
xpc_release(answer);
};
callBacks.downloadDidBegin = ^(SUDSDownloader *downloader) {
xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0);
xpc_dictionary_set_bool(message, SUDownloadServiceDidBeginDownloadingKey, true);
xpc_object_t answer = xpc_connection_send_message_with_reply_sync(connection, message);
xpc_release(message);
xpc_release(answer);
};
callBacks.downloadDidFail = ^(SUDSDownloader *downloader, NSError *error) {
errcode = (int32_t)[error code];
errdomain = [[error domain] cStringUsingEncoding:NSUTF8StringEncoding];
errmsg = [[error localizedDescription] cStringUsingEncoding:NSUTF8StringEncoding];
NSData *errorData = [NSKeyedArchiver archivedDataWithRootObject:error];
xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0);
xpc_dictionary_set_data(message, SUDownloadServiceReceivedFailErrorKey, [errorData bytes], [errorData length]);
xpc_object_t answer = xpc_connection_send_message_with_reply_sync(connection, message);
xpc_release(message);
xpc_release(answer);
};
callBacks.downloadDidFinish = ^(SUDSDownloader *downloader) {
xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0);
xpc_dictionary_set_bool(message, SUDownloadServiceDidFinishDownloadingKey, true);
xpc_object_t answer = xpc_connection_send_message_with_reply_sync(connection, message);
xpc_release(message);
xpc_release(answer);
};
callBacks.downloadShouldDecodeSourceData = ^BOOL(SUDSDownloader *downloader, NSString *MIMEType) {
xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0);
xpc_dictionary_set_string(message, SUDownloadServiceMIMETypeToDecodeKey, [MIMEType cStringUsingEncoding:NSUTF8StringEncoding]);
xpc_object_t answer = xpc_connection_send_message_with_reply_sync(connection, message);
xpc_release(message);
BOOL result = NO;
if (xpc_get_type(answer) == XPC_TYPE_DICTIONARY)
result = (BOOL)xpc_dictionary_get_bool(answer, SUDownloadServiceShouldDecodeMIMETypeKey);
xpc_release(answer);
return result;
};
[downloader setCallBacks:callBacks];
[downloader startDownload];
while ([downloader isInProgress])
{
if (shouldStopDownload)
{
[downloader stopDownload];
asl_log(NULL, NULL, ASL_LEVEL_NOTICE, "Download process stopped.\n");
break;
}
CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, true);
}
}
while (NO);
[localPool release];
#if DEBUG_LOGGING_ENABLED
NSLog(@"Download process finished. Will send last message...");
#endif
// Clean up and add errcode/errmsg to reply
if (connection)
{
xpc_connection_cancel(connection);
xpc_release(connection);
}
xpc_dictionary_set_int64(reply, SUDownloadServiceErrorCodeKey, (int64_t)errcode);
if (errmsg)
{
xpc_dictionary_set_string(reply, SUDownloadServiceErrorMessageKey, errmsg);
}
if (errdomain)
{
xpc_dictionary_set_string(reply, SUDownloadServiceErrorDomainKey, errdomain);
}
}
static void fetch_peer_event_handler(xpc_connection_t peer, xpc_object_t event)
{
// Get the object type.
xpc_type_t type = xpc_get_type(event);
if (XPC_TYPE_ERROR == type)
{
// Handle an error.
if (XPC_ERROR_CONNECTION_INVALID == event)
{
// The client process on the other end of the connection
// has either crashed or cancelled the connection.
asl_log(NULL, NULL, ASL_LEVEL_NOTICE, "peer(%d) received "
"XPC_ERROR_CONNECTION_INVALID",
xpc_connection_get_pid(peer));
xpc_connection_cancel(peer);
}
else if (XPC_ERROR_TERMINATION_IMMINENT == event)
{
// Handle per-connection termination cleanup. This
// service is about to exit.
asl_log(NULL, NULL, ASL_LEVEL_NOTICE, "peer(%d) received "
"XPC_ERROR_TERMINATION_IMMINENT",
xpc_connection_get_pid(peer));
}
}
else if (XPC_TYPE_DICTIONARY == type)
{
xpc_object_t requestMessage = event;
xpc_object_t replyMessage = xpc_dictionary_create_reply(requestMessage);
assert(replyMessage != NULL);
// Process request and build a reply message.
fetch_process_request(requestMessage, replyMessage);
xpc_connection_send_message(peer, replyMessage);
xpc_release(replyMessage);
}
}
static void release_dispatch_queue(void *queue)
{
dispatch_release(queue);
}
static void fetch_event_handler(xpc_connection_t peer)
{
// Generate an unique name for the queue to handle messages from
// this peer and create a new dispatch queue for it.
char *queue_name = NULL;
asprintf(&queue_name, "%s-peer-%d", "com.devmate.UpdateDownloader", xpc_connection_get_pid(peer));
dispatch_queue_t peer_event_queue = dispatch_queue_create(queue_name, DISPATCH_QUEUE_SERIAL);
assert(peer_event_queue != NULL);
free(queue_name);
// Set the target queue for connection.
xpc_connection_set_target_queue(peer, peer_event_queue);
xpc_connection_set_context(peer, peer_event_queue);
xpc_connection_set_finalizer_f(peer, release_dispatch_queue);
// Set the handler block for connection.
xpc_connection_set_event_handler(peer, ^(xpc_object_t event) {
fetch_peer_event_handler(peer, event);
});
// Enable the peer connection to receive messages.
xpc_connection_resume(peer);
}
int main(int argc, const char *argv[])
{
xpc_main(fetch_event_handler);
exit(EXIT_FAILURE);
}
@@ -1,2 +0,0 @@
/* Localized versions of Info.plist keys */
@@ -1,40 +0,0 @@
//
// SUInstallServiceConstants.h
// Sparkle
//
// Created by Dmytro Tretiakov on 8/2/13.
//
//
#ifndef Sparkle_SUInstallServiceConstants_h
#define Sparkle_SUInstallServiceConstants_h
typedef NS_ENUM(UInt64, SUInstallServiceTask)
{
SUInstallServiceTaskUnknown = 0,
SUInstallServiceTaskCopyPath = 1LL,
SUInstallServiceTaskAuthCopyPath = 2LL,
SUInstallServiceTaskLaunchTask = 3LL
};
static const char * SUInstallServiceTaskTypeKey = "task_type"; // int64_t
// SUInstallServiceTaskCopyPath & SUInstallServiceTaskAuthCopyPath keys
static const char * SUInstallServiceSourcePathKey = "source_path"; // c-string
static const char * SUInstallServiceDestinationPathKey = "destination_path"; // c-string
static const char * SUInstallServiceAppendVersionKey = "append_version"; // bool
// SUInstallServiceTaskLaunchTask keys
static const char * SUInstallServiceLaunchTaksPathKey = "launch_task_path";
static const char * SUInstallServiceLaunchTaskArgumentsKey = "launch_task_arguments"; // xpc_array of c-strings
static const char * SUInstallServiceLaunchTaskEnvironmentKey = "launch_task_environment"; // xpc_dictionary with keys and values of c-strings
static const char * SUInstallServiceLaunchTaskCurrentDirKey = "launch_task_cur_dir"; // c-string
static const char * SUInstallServiceLaunchTaskInputDataKey = "launch_task_input_data"; // xpc_data
static const char * SUInstallServiceLaunchTaskReplyImmediatelyKey = "launch_task_reply_immediately"; // bool
// Reply keys
static const char * SUInstallServiceErrorCodeKey = "error_code"; // int64_t
static const char * SUInstallServiceErrorLocalizedDescriptionKey = "error_localized_description"; // c-string
static const char * SUInstallServiceLaunchTaskOutputDataKey = "launch_task_output_data"; // xpc_data
#endif
-30
View File
@@ -1,30 +0,0 @@
//
// SUXPCInstaller.h
// Sparkle
//
// Created by Whitney Young on 3/19/12.
// Copyright (c) 2012 FadingRed. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface SUXPCInstaller : NSObject
+ (BOOL)copyPathWithAuthentication:(NSString *)src overPath:(NSString *)dst appendVersion:(BOOL)appendVersion error:(NSError *__autoreleasing *)outError;
+ (BOOL)copyPathContent:(NSString *)src toDirectory:(NSString *)dstDir error:(NSError *__autoreleasing *)outError; // dstDir will be created if absent
+ (void)launchTaskWithLaunchPath:(NSString *)path arguments:(NSArray *)arguments;
+ (void)launchTaskWithPath:(NSString *)launchPath
arguments:(NSArray *)arguments
environment:(NSDictionary *)environment
currentDirectoryPath:(NSString *)currentDirPath
inputData:(NSData *)inputData
waitUntilDone:(BOOL)waitUntilDone
completionHandler:(void (^)(int result, NSData *outputData))completionHandler;
@end
FOUNDATION_EXPORT BOOL SUShouldUseXPCInstaller(void);
-277
View File
@@ -1,277 +0,0 @@
//
// SUXPCInstaller.m
// Sparkle
//
// Created by Whitney Young on 3/19/12.
// Copyright (c) 2012 FadingRed. All rights reserved.
//
#import <xpc/xpc.h>
#import "SUXPCInstaller.h"
#import "SUInstallServiceConstants.h"
#import "SUCodeSigningVerifier.h"
BOOL SUShouldUseXPCInstaller(void)
{
if (![SUCodeSigningVerifier hostApplicationIsSandboxed])
return NO;
NSString *xpcServicePrefixPath = [[NSBundle mainBundle] bundlePath];
NSString *xpcServiceSuffixPath = @"Contents/XPCServices/com.devmate.UpdateInstaller.xpc";
return [[NSFileManager defaultManager] fileExistsAtPath:[xpcServicePrefixPath stringByAppendingPathComponent:xpcServiceSuffixPath]];
}
@implementation SUXPCInstaller
+ (xpc_connection_t)getSandboxXPCService
{
__block xpc_connection_t serviceConnection = xpc_connection_create("com.devmate.UpdateInstaller", dispatch_get_main_queue());
if (!serviceConnection)
{
NSLog(@"Can't connect to XPC service");
return (NULL);
}
xpc_connection_set_event_handler(serviceConnection, ^(xpc_object_t event) {
xpc_type_t type = xpc_get_type(event);
if (type == XPC_TYPE_ERROR)
{
if (event == XPC_ERROR_CONNECTION_INVALID)
{
// The service is invalid. Either the service name supplied to
// xpc_connection_create() is incorrect or we (this process) have
// canceled the service; we can do any cleanup of appliation
// state at this point.
xpc_release(serviceConnection);
}
}
});
// Need to resume the service in order for it to process messages.
xpc_connection_resume(serviceConnection);
return (serviceConnection);
}
+ (BOOL)copyPathWithAuthentication:(NSString *)src overPath:(NSString *)dst appendVersion:(BOOL)appendVersion error:(NSError *__autoreleasing *)outError
{
xpc_connection_t connection = [self getSandboxXPCService];
xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0);
xpc_dictionary_set_int64(message, SUInstallServiceTaskTypeKey, (int64_t)SUInstallServiceTaskAuthCopyPath);
if (src)
xpc_dictionary_set_string(message, SUInstallServiceSourcePathKey, [src fileSystemRepresentation]);
if (dst)
xpc_dictionary_set_string(message, SUInstallServiceDestinationPathKey, [dst fileSystemRepresentation]);
xpc_dictionary_set_bool(message, SUInstallServiceAppendVersionKey, appendVersion ? true : false);
__block BOOL xpcDidReply = NO;
__block NSError *error = nil;
dispatch_queue_t queue = dispatch_queue_create(NULL, DISPATCH_QUEUE_SERIAL);
xpc_connection_send_message_with_reply(connection, message, queue, ^(xpc_object_t response) {
if (XPC_TYPE_ERROR == xpc_get_type(response))
{
NSDictionary *errorInfo = [NSDictionary dictionaryWithObject:@"Internal XPC error."
forKey:NSLocalizedDescriptionKey];
error = [[NSError alloc] initWithDomain:SUSparkleErrorDomain code:SUXPCServiceError userInfo:errorInfo];
}
else if (XPC_TYPE_DICTIONARY == xpc_get_type(response))
{
const char *errorString = xpc_dictionary_get_string(response, SUInstallServiceErrorLocalizedDescriptionKey);
if (errorString != NULL)
{
NSString *errorStr = [NSString stringWithCString:errorString encoding:NSUTF8StringEncoding];
NSDictionary *errorInfo = [NSDictionary dictionaryWithObject:errorStr ? errorStr : @""
forKey:NSLocalizedDescriptionKey];
error = [[NSError alloc] initWithDomain:SUSparkleErrorDomain code:SUXPCServiceError userInfo:errorInfo];
}
}
xpcDidReply = YES;
});
while (NO == xpcDidReply)
{
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.2]];
}
xpc_release(message);
dispatch_release(queue);
if (nil != error && NULL != outError)
{
*outError = error;
}
return (nil == error);
}
+ (BOOL)copyPathContent:(NSString *)src toDirectory:(NSString *)dstDir error:(NSError * __autoreleasing*)outError
{
xpc_connection_t connection = [self getSandboxXPCService];
xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0);
xpc_dictionary_set_int64(message, SUInstallServiceTaskTypeKey, (int64_t)SUInstallServiceTaskCopyPath);
if (src)
xpc_dictionary_set_string(message, SUInstallServiceSourcePathKey, [src fileSystemRepresentation]);
if (dstDir)
xpc_dictionary_set_string(message, SUInstallServiceDestinationPathKey, [dstDir fileSystemRepresentation]);
__block BOOL xpcDidReply = NO;
__block NSError *error = nil;
dispatch_queue_t queue = dispatch_queue_create(NULL, DISPATCH_QUEUE_SERIAL);
xpc_connection_send_message_with_reply(connection, message, queue, ^(xpc_object_t response) {
if (XPC_TYPE_ERROR == xpc_get_type(response))
{
NSDictionary *errorInfo = [NSDictionary dictionaryWithObject:@"Internal XPC error."
forKey:NSLocalizedDescriptionKey];
error = [[NSError alloc] initWithDomain:SUSparkleErrorDomain code:SUXPCServiceError userInfo:errorInfo];
}
else if (XPC_TYPE_DICTIONARY == xpc_get_type(response))
{
const char *errorString = xpc_dictionary_get_string(response, SUInstallServiceErrorLocalizedDescriptionKey);
if (errorString != NULL)
{
NSString *errorStr = [NSString stringWithCString:errorString encoding:NSUTF8StringEncoding];
NSDictionary *errorInfo = [NSDictionary dictionaryWithObject:errorStr ? errorStr : @""
forKey:NSLocalizedDescriptionKey];
error = [[NSError alloc] initWithDomain:SUSparkleErrorDomain code:SUXPCServiceError userInfo:errorInfo];
}
}
xpcDidReply = YES;
});
while (NO == xpcDidReply)
{
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.2]];
}
xpc_release(message);
dispatch_release(queue);
if (nil != error && NULL != outError)
{
*outError = error;
}
return (nil == error);
}
+ (void)launchTaskWithLaunchPath:(NSString *)path arguments:(NSArray *)arguments
{
[self launchTaskWithPath:path
arguments:arguments
environment:nil
currentDirectoryPath:nil
inputData:nil
waitUntilDone:NO
completionHandler:nil];
}
+ (void)launchTaskWithPath:(NSString *)launchPath
arguments:(NSArray *)arguments
environment:(NSDictionary *)environment
currentDirectoryPath:(NSString *)currentDirPath
inputData:(NSData *)inputData
waitUntilDone:(BOOL)waitUntilDone
completionHandler:(void (^)(int result, NSData *outputData))completionHandler
{
xpc_connection_t connection = [self getSandboxXPCService];
xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0);
xpc_dictionary_set_int64(message, SUInstallServiceTaskTypeKey, (int64_t)SUInstallServiceTaskLaunchTask);
if ([launchPath length])
{
xpc_dictionary_set_string(message, SUInstallServiceLaunchTaksPathKey, [launchPath fileSystemRepresentation]);
}
if ([arguments count])
{
xpc_object_t array = xpc_array_create(NULL, 0);
for (id argument in arguments)
{
NSString *strArgument = argument;
if (![strArgument isKindOfClass:[NSString class]])
strArgument = [argument description];
xpc_array_set_string(array, XPC_ARRAY_APPEND, [strArgument UTF8String]);
}
xpc_dictionary_set_value(message, SUInstallServiceLaunchTaskArgumentsKey, array);
xpc_release(array);
}
if ([environment count])
{
__block xpc_object_t dict = xpc_dictionary_create(NULL, NULL, 0);
[environment enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL __unused *stop) {
NSString *xpc_key = [key isKindOfClass:[NSString class]] ? key : [key description];
NSString *xpc_value = [obj isKindOfClass:[NSString class]] ? obj : [obj description];
xpc_dictionary_set_string(dict, [xpc_key UTF8String], [xpc_value UTF8String]);
}];
xpc_dictionary_set_value(message, SUInstallServiceLaunchTaskEnvironmentKey, dict);
xpc_release(dict);
}
if ([currentDirPath length])
{
xpc_dictionary_set_string(message, SUInstallServiceLaunchTaskCurrentDirKey, [currentDirPath fileSystemRepresentation]);
}
if ([inputData length])
{
xpc_dictionary_set_data(message, SUInstallServiceLaunchTaskInputDataKey, [inputData bytes], [inputData length]);
}
BOOL replyImmediately = (waitUntilDone || completionHandler != nil) ? NO : YES;
xpc_dictionary_set_bool(message, SUInstallServiceLaunchTaskReplyImmediatelyKey, replyImmediately);
__block BOOL xpcTaskDidReply = NO;
xpc_connection_send_message_with_reply(connection, message, dispatch_get_current_queue(), ^(xpc_object_t response) {
int taskResult = 0;
NSData *outputData = nil;
if (completionHandler != NULL)
{
xpc_type_t type = xpc_get_type(response);
if (type == XPC_TYPE_ERROR)
{
taskResult = SUXPCServiceError;
}
else if (type == XPC_TYPE_DICTIONARY)
{
taskResult = (int)xpc_dictionary_get_int64(response, SUInstallServiceErrorCodeKey);
size_t bytesLen = 0;
const void *bytes = xpc_dictionary_get_data(response, SUInstallServiceLaunchTaskOutputDataKey, &bytesLen);
if (NULL != bytes)
{
outputData = [NSData dataWithBytes:bytes length:bytesLen];
}
}
completionHandler(taskResult, outputData);
}
xpcTaskDidReply = YES;
});
xpc_release(message);
if (replyImmediately || waitUntilDone)
{
while (NO == xpcTaskDidReply)
{
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
}
}
}
@end
-31
View File
@@ -1,31 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>English</string>
<key>CFBundleExecutable</key>
<string>${EXECUTABLE_NAME}</string>
<key>CFBundleIdentifier</key>
<string>${EXECUTABLE_NAME}</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundlePackageType</key>
<string>XPC!</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>XPCService</key>
<dict>
<key>ServiceType</key>
<string>Application</string>
<key>JoinExistingSession</key>
<true/>
</dict>
</dict>
</plist>
-374
View File
@@ -1,374 +0,0 @@
//
// main.m
// Update
//
// Created by Whitney Young on 3/19/12.
// Copyright (c) 2012 FadingRed. All rights reserved.
//
#include <xpc/xpc.h>
#include <asl.h>
#import <Foundation/Foundation.h>
#import "SUPlainInstallerInternals.h"
#import "SUInstallServiceConstants.h"
static xpc_object_t SUSICopyPathContent(xpc_object_t message)
{
if (NULL == message)
return NULL;
const char *src = xpc_dictionary_get_string(message, SUInstallServiceSourcePathKey);
const char *dst = xpc_dictionary_get_string(message, SUInstallServiceDestinationPathKey);
NSFileManager *manager = [NSFileManager defaultManager];
NSString *sourcePath = src ? [manager stringWithFileSystemRepresentation:src length:strlen(src)] : nil;
NSString *targetPath = dst ? [manager stringWithFileSystemRepresentation:dst length:strlen(dst)] : nil;
NSError *error = nil;
do
{
if (nil == sourcePath)
{
NSDictionary *errorInfo = [NSDictionary dictionaryWithObject:@"Source path is absent." forKey:NSLocalizedDescriptionKey];
error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUXPCServiceError userInfo:errorInfo];
break;
}
if (nil == targetPath)
{
NSDictionary *errorInfo = [NSDictionary dictionaryWithObject:@"Destination path is absent." forKey:NSLocalizedDescriptionKey];
error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUXPCServiceError userInfo:errorInfo];
break;
}
NSArray *contents = nil;
BOOL isSrcDirectory = NO;
BOOL isSrcExist = [manager fileExistsAtPath:sourcePath isDirectory:&isSrcDirectory];
isSrcDirectory = isSrcDirectory && ![[NSWorkspace sharedWorkspace] isFilePackageAtPath:sourcePath];
if (isSrcExist && isSrcDirectory)
{
contents = [manager contentsOfDirectoryAtPath:sourcePath error:&error];
}
else if (isSrcExist)
{
contents = [NSArray arrayWithObject:@""];
}
else
{
NSDictionary *errorInfo = [NSDictionary dictionaryWithObject:@"Source does not exist on disk." forKey:NSLocalizedDescriptionKey];
error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUXPCServiceError userInfo:errorInfo];
}
if (nil != error)
{
break;
}
BOOL isDstDirectory = NO;
BOOL isDstExist = [manager fileExistsAtPath:targetPath isDirectory:&isDstDirectory];
if (isSrcDirectory && (!isDstExist || !isDstDirectory))
{
if (isDstExist)
[manager removeItemAtPath:targetPath error:&error];
[manager createDirectoryAtPath:targetPath withIntermediateDirectories:YES attributes:nil error:&error];
}
else if (!isSrcDirectory)
{
if (isDstExist && !isDstDirectory)
[manager removeItemAtPath:targetPath error:&error];
[manager createDirectoryAtPath:targetPath withIntermediateDirectories:YES attributes:nil error:&error];
}
if (nil != error)
{
break;
}
for (NSString *item in contents)
{
NSString *fromPath = [item length] ? [sourcePath stringByAppendingPathComponent:item] : sourcePath;
NSString *toPath = [item length] ? [targetPath stringByAppendingPathComponent:item] : [targetPath stringByAppendingPathComponent:[sourcePath lastPathComponent]];
if (![manager isReadableFileAtPath:fromPath])
{
SULog(@"XPC Install Service: will skip \"%@\"", fromPath);
continue;
}
SULog(@"XPC Install Service: will copy \"%@\" to \"%@\"", fromPath, toPath);
if ([manager fileExistsAtPath:toPath])
[manager removeItemAtPath:toPath error:&error];
if (![manager copyItemAtPath:fromPath toPath:toPath error:&error])
break;
}
}
while (NO);
xpc_object_t reply = xpc_dictionary_create_reply(message);
if (nil != error)
{
xpc_dictionary_set_int64(reply, SUInstallServiceErrorCodeKey, (int64_t)[error code]);
const char *errorMsg = [[error localizedDescription] length] ? [[error localizedDescription] UTF8String] : "";
xpc_dictionary_set_string(reply, SUInstallServiceErrorLocalizedDescriptionKey, errorMsg);
}
return reply;
}
static xpc_object_t SUISCopyPathWithAuthentication(xpc_object_t message)
{
if (NULL == message)
return NULL;
const char *src = xpc_dictionary_get_string(message, SUInstallServiceSourcePathKey);
const char *dst = xpc_dictionary_get_string(message, SUInstallServiceDestinationPathKey);
bool appendVersion = xpc_dictionary_get_bool(message, SUInstallServiceAppendVersionKey);
NSFileManager *manager = [NSFileManager defaultManager];
NSString *relaunchPathToCopy = src ? [manager stringWithFileSystemRepresentation:src length:strlen(src)] : nil;
NSString *targetPath = dst ? [manager stringWithFileSystemRepresentation:dst length:strlen(dst)] : nil;
NSError *error = nil;
BOOL result = [SUPlainInstaller copyPathWithAuthentication:relaunchPathToCopy overPath:targetPath appendVersion:appendVersion error:&error];
// send response to indicate ok
xpc_object_t reply = xpc_dictionary_create_reply(message);
if (!result && error != nil)
{
xpc_dictionary_set_int64(reply, SUInstallServiceErrorCodeKey, (int64_t)[error code]);
const char *errorMsg = [[error localizedDescription] length] ? [[error localizedDescription] UTF8String] : "";
xpc_dictionary_set_string(reply, SUInstallServiceErrorLocalizedDescriptionKey, errorMsg);
}
return reply;
}
static xpc_object_t SUISLaunchTask(xpc_object_t message)
{
if (NULL == message)
return NULL;
const char *path = xpc_dictionary_get_string(message, SUInstallServiceLaunchTaksPathKey);
NSString *launchPath = path ? [[NSFileManager defaultManager] stringWithFileSystemRepresentation:path length:strlen(path)] : nil;
xpc_object_t array = xpc_dictionary_get_value(message, SUInstallServiceLaunchTaskArgumentsKey);
NSArray *arguments = nil;
if (NULL != array)
{
size_t count = xpc_array_get_count(array);
NSMutableArray *mutableArgs = [NSMutableArray arrayWithCapacity:count];
for (size_t i = 0; i < count; i++)
{
NSString *argument = [NSString stringWithUTF8String:xpc_array_get_string(array, i)];
[mutableArgs addObject: argument ? argument : @""];
}
arguments = mutableArgs;
}
xpc_object_t dict = xpc_dictionary_get_value(message, SUInstallServiceLaunchTaskEnvironmentKey);
NSDictionary *environment = nil;
if (NULL != dict)
{
size_t count = xpc_dictionary_get_count(dict);
__block NSMutableDictionary *mutableEnv = [NSMutableDictionary dictionaryWithCapacity:count];
xpc_dictionary_apply(dict, ^bool(const char *key, xpc_object_t value) {
NSString *envKey = [NSString stringWithUTF8String:key];
NSString *envValue = [NSString stringWithUTF8String:value];
[mutableEnv setObject:envValue forKey:envKey];
return true;
});
environment = mutableEnv;
}
path = xpc_dictionary_get_string(message, SUInstallServiceLaunchTaskCurrentDirKey);
NSString *currentDirPath = path ? [[NSFileManager defaultManager] stringWithFileSystemRepresentation:path length:strlen(path)] : nil;
size_t bytesLen = 0;
const void *bytes = xpc_dictionary_get_data(message, SUInstallServiceLaunchTaskInputDataKey, &bytesLen);
NSData *inputData = bytes ? [NSData dataWithBytes:bytes length:bytesLen] : nil;
bool shouldReplyImmediatly = xpc_dictionary_get_bool(message, SUInstallServiceLaunchTaskReplyImmediatelyKey);
// prepare NSTask
NSTask *task = [[NSTask alloc] init];
NSPipe *inputPipe = [NSPipe pipe];
NSPipe *outputPipe = [NSPipe pipe];
[task setStandardInput:inputPipe];
[task setStandardOutput:outputPipe];
[task setStandardError:outputPipe];
if (launchPath != nil)
[task setLaunchPath:launchPath];
if ([arguments count])
[task setArguments:arguments];
if ([environment count])
[task setEnvironment:environment];
if (currentDirPath != nil)
[task setCurrentDirectoryPath:currentDirPath];
__block NSData *outputData = nil;
__block int taskResult = 0;
__block BOOL isTaskRunning = YES;
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
NSArray *notificationObjects = nil;
if (!shouldReplyImmediatly)
{
id object1 = [notificationCenter addObserverForName:NSFileHandleReadToEndOfFileCompletionNotification
object:[outputPipe fileHandleForReading]
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification *note) {
outputData = [[note userInfo] objectForKey:NSFileHandleNotificationDataItem];
isTaskRunning = NO;
}];
id object2 = [notificationCenter addObserverForName:NSTaskDidTerminateNotification
object:task
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification __unused *note) {
taskResult = [task terminationStatus];
}];
notificationObjects = [NSArray arrayWithObjects:object1, object2, nil];
}
[[outputPipe fileHandleForReading] readToEndOfFileInBackgroundAndNotifyForModes:[NSArray arrayWithObject:NSDefaultRunLoopMode]];
@try
{
[task launch];
if ([inputData length])
{
[[inputPipe fileHandleForWriting] writeData:inputData];
[[inputPipe fileHandleForWriting] closeFile];
}
if (!shouldReplyImmediatly)
{
// loop until we are done receiving the data
while (YES == isTaskRunning)
{
CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.5, true);
}
}
}
@catch (...)
{
taskResult = SUXPCServiceError;
}
// send response to indicate ok
xpc_object_t reply = xpc_dictionary_create_reply(message);
xpc_dictionary_set_int64(reply, SUInstallServiceErrorCodeKey, (int64_t)taskResult);
if (outputData != nil)
{
xpc_dictionary_set_data(reply, SUInstallServiceLaunchTaskOutputDataKey, [outputData bytes], [outputData length]);
}
for (id object in notificationObjects)
{
[notificationCenter removeObserver:object];
}
outputData = nil;
return reply;
}
static void peer_event_handler(xpc_connection_t peer, xpc_object_t event)
{
xpc_type_t type = xpc_get_type(event);
if (type == XPC_TYPE_ERROR)
{
if (event == XPC_ERROR_CONNECTION_INVALID)
{
// The client process on the other end of the connection has either
// crashed or cancelled the connection. After receiving this error,
// the connection is in an invalid state, and you do not need to
// call xpc_connection_cancel(). Just tear down any associated state
// here.
}
else if (event == XPC_ERROR_TERMINATION_IMMINENT)
{
// Handle per-connection termination cleanup.
}
}
else if (type == XPC_TYPE_DICTIONARY)
{
// Handle the message.
int64_t task = xpc_dictionary_get_int64(event, SUInstallServiceTaskTypeKey);
NSLog(@"XPC Installer: will do the task %lld", (int64_t)task);
xpc_object_t reply = NULL;
@autoreleasepool
{
switch (task)
{
case SUInstallServiceTaskCopyPath:
{
reply = SUSICopyPathContent(event);
break;
}
case SUInstallServiceTaskAuthCopyPath:
{
reply = SUISCopyPathWithAuthentication(event);
break;
}
case SUInstallServiceTaskLaunchTask:
{
reply = SUISLaunchTask(event);
break;
}
default:
{
SULog(@"XPC Install Service: Unknown XPC service task %lld", task);
reply = xpc_dictionary_create_reply(event);
xpc_dictionary_set_int64(reply, SUInstallServiceErrorCodeKey, (int64_t)SUXPCServiceError);
xpc_dictionary_set_string(reply, SUInstallServiceErrorLocalizedDescriptionKey, "Unknown install cervice task.");
break;
}
}
}
if (NULL == reply)
{
reply = xpc_dictionary_create_reply(event);
}
xpc_connection_send_message(peer, reply);
xpc_release(reply);
}
}
static void event_handler(xpc_connection_t peer)
{
// By defaults, new connections will target the default dispatch
// concurrent queue.
xpc_connection_set_event_handler(peer, ^(xpc_object_t event) {
peer_event_handler(peer, event);
});
// This will tell the connection to begin listening for events. If you
// have some other initialization that must be done asynchronously, then
// you can defer this call until after that initialization is done.
xpc_connection_resume(peer);
}
int main(int __unused argc, const char __unused *argv[])
{
xpc_main(event_handler);
}
-10
View File
@@ -1,10 +0,0 @@
//
// install_service.pch
// Sparkle
//
// Created by Dmytro Tretiakov on 4/25/14.
//
//
#import "Sparkle.pch"
#import "SULog.h"
+5
View File
@@ -9,7 +9,11 @@
#ifndef SUAPPCAST_H
#define SUAPPCAST_H
#if __has_feature(modules)
@import Foundation;
#else
#import <Foundation/Foundation.h>
#endif
#import "SUExport.h"
@class SUAppcastItem;
@@ -19,6 +23,7 @@ SU_EXPORT @interface SUAppcast : NSObject<NSURLDownloadDelegate>
@property (copy) NSDictionary *httpHeaders;
- (void)fetchAppcastFromURL:(NSURL *)url completionBlock:(void (^)(NSError *))err;
- (SUAppcast *)copyWithoutDeltaUpdates;
@property (readonly, copy) NSArray *items;
@end
+168 -130
View File
@@ -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;
}
@@ -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
+5 -1
View File
@@ -9,12 +9,16 @@
#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;
+33 -26
View File
@@ -16,7 +16,7 @@
@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,7 +31,7 @@
@end
@implementation SUAppcastItem
@synthesize date;
@synthesize dateString;
@synthesize deltaUpdates;
@synthesize displayVersionString;
@synthesize DSASignature;
@@ -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,7 +126,7 @@
return nil;
}
NSString *enclosureURLString = enclosure[SURSSAttributeURL];
NSString *enclosureURLString = [enclosure objectForKey:SURSSAttributeURL];
if (!enclosureURLString && !theInfoURL) {
if (error) {
*error = @"Feed item's enclosure lacks URL";
@@ -134,20 +135,21 @@
}
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 +159,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;
}
+31 -35
View File
@@ -26,6 +26,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,14 +37,10 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
@synthesize postponingInstallation;
@synthesize showErrors;
@synthesize willUpdateOnTermination;
@synthesize isTerminating;
@synthesize alert;
@synthesize showUpdateAlertTimer;
- (BOOL)shouldShowUI
{
return self.showErrors;
}
- (void)showUpdateAlert
{
self.interruptible = NO;
@@ -65,34 +62,10 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:) name:NSApplicationDidBecomeActiveNotification object:NSApp];
}
- (void)downloadReleaseNotesAndWaitUntilDone
{
NSURL *releaseNotesURL = self.updateItem.releaseNotesURL;
if (nil == releaseNotesURL || [releaseNotesURL isFileURL])
return;
static NSString * const kSUAutomaticUpdateParamName = @"autoupdate";
NSString *URLString = releaseNotesURL.absoluteString;
URLString = [URLString stringByAppendingFormat:@"%@%@=1", (releaseNotesURL.query != nil) ? @"&" : @"?", kSUAutomaticUpdateParamName];
releaseNotesURL = [NSURL URLWithString:URLString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:releaseNotesURL];
[request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
[self updateURLRequestHTTPHeaders:request];
[NSURLConnection sendSynchronousRequest:request returningResponse:NULL error:NULL];
}
- (void)didFindValidUpdate
{
// For correct DevMate statistics need to send request for Release Notes.
[self downloadReleaseNotesAndWaitUntilDone];
[super didFindValidUpdate];
}
- (void)unarchiverDidFinish:(SUUnarchiver *)__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];
// Sudden termination is available on 10.6+
NSProcessInfo *processInfo = [NSProcessInfo processInfo];
@@ -133,6 +106,8 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
if (self.willUpdateOnTermination)
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:NSApplicationWillTerminateNotification object:nil];
[[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self name:NSWorkspaceWillPowerOffNotification object:nil];
NSProcessInfo *processInfo = [NSProcessInfo processInfo];
[processInfo enableSuddenTermination];
@@ -156,11 +131,12 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
[self invalidateShowUpdateAlertTimer];
}
- (void)abortUpdate:(SUUpdateAbortReason)reason
- (void)abortUpdate
{
self.isTerminating = NO;
[self stopUpdatingOnTermination];
[self invalidateShowUpdateAlertTimer];
[super abortUpdate:reason];
[super abortUpdate];
}
- (void)applicationDidBecomeActive:(NSNotification *)__unused aNotification
@@ -180,18 +156,18 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
case SUInstallLaterChoice:
self.postponingInstallation = YES;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:) name:NSApplicationWillTerminateNotification object:nil];
// We're already waiting on quit, just indicate that we're idle.
self.interruptible = YES;
break;
case SUDoNotInstallChoice:
[self.host setObject:[self.updateItem versionString] forUserDefaultsKey:SUSkippedVersionKey];
[self abortUpdate:SUUpdateAbortCanceledByUser];
[self abortUpdate];
break;
}
}
- (void)installWithToolAndRelaunch:(BOOL)relaunch displayingUserInterface:(BOOL)showUI
{
if (relaunch) {
@@ -202,11 +178,31 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
[super installWithToolAndRelaunch:relaunch displayingUserInterface:showUI];
}
- (void)systemWillPowerOff:(NSNotification *)__unused note
{
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUSystemPowerOffError userInfo:@{
NSLocalizedDescriptionKey: SULocalizedString(@"The update will not be installed because the user requested for the system to power off", nil)
}]];
}
- (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) {
@@ -219,7 +215,7 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
[updaterDelegate updater:self.updater didAbortWithError:error];
}
[self abortUpdate:SUUpdateAbortGotError];
[self abortUpdate];
}
}
+2 -3
View File
@@ -24,14 +24,13 @@
- (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;
- (void)didFindValidUpdate;
- (void)didNotFindUpdate;
- (void)updateURLRequestHTTPHeaders:(NSMutableURLRequest *)request;
- (void)downloadUpdate;
- (void)download:(NSURLDownload *)d decideDestinationWithSuggestedFilename:(NSString *)name;
- (void)downloadDidFinish:(NSURLDownload *)d;
@@ -48,7 +47,7 @@
- (void)cleanUpDownload;
- (void)abortUpdate:(SUUpdateAbortReason)reason;
- (void)abortUpdate;
- (void)abortUpdateWithError:(NSError *)error;
- (void)terminateApp;
+185 -185
View File
@@ -9,20 +9,15 @@
#import "SUBasicUpdateDriver.h"
#import "SUHost.h"
#import "SUDSAVerifier.h"
#import "SUInstaller.h"
#import "SUOperatingSystem.h"
#import "SUStandardVersionComparator.h"
#import "SUUnarchiver.h"
#import "SUConstants.h"
#import "SULog.h"
#import "SUPlainInstaller.h"
#import "SUPlainInstallerInternals.h"
#import "SUBinaryDeltaCommon.h"
#import "SUCodeSigningVerifier.h"
#import "SUUpdater_Private.h"
#import "SUXPCInstaller.h"
CF_EXPORT CFDictionaryRef DMCopyHTTPRequestHeaders(CFBundleRef appBundle, CFDataRef httpBodyData);
#import "SUFileManager.h"
#import "SUUpdateValidator.h"
@interface SUBasicUpdateDriver ()
@@ -34,6 +29,8 @@ CF_EXPORT CFDictionaryRef DMCopyHTTPRequestHeaders(CFBundleRef appBundle, CFData
@property (copy) NSString *tempDir;
@property (copy) NSString *relaunchPath;
@property (nonatomic) SUUpdateValidator *updateValidator;
@end
@implementation SUBasicUpdateDriver
@@ -46,6 +43,8 @@ CF_EXPORT CFDictionaryRef DMCopyHTTPRequestHeaders(CFBundleRef appBundle, CFData
@synthesize tempDir;
@synthesize relaunchPath;
@synthesize updateValidator = _updateValidator;
- (void)checkForUpdatesAtURL:(NSURL *)URL host:(SUHost *)aHost
{
[super checkForUpdatesAtURL:URL host:aHost];
@@ -55,14 +54,10 @@ CF_EXPORT CFDictionaryRef DMCopyHTTPRequestHeaders(CFBundleRef appBundle, CFData
return;
}
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
request.allHTTPHeaderFields = [self.updater httpHeaders];
[self updateURLRequestHTTPHeaders:request];
SUAppcast *appcast = [[SUAppcast alloc] init];
[appcast setUserAgentString:[self.updater userAgentString]];
[appcast setHttpHeaders:request.allHTTPHeaderFields];
[appcast setHttpHeaders:[self.updater httpHeaders]];
[appcast fetchAppcastFromURL:URL completionBlock:^(NSError *error) {
if (error) {
[self abortUpdateWithError:error];
@@ -89,12 +84,28 @@ CF_EXPORT CFDictionaryRef DMCopyHTTPRequestHeaders(CFBundleRef appBundle, CFData
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; }
@@ -104,15 +115,20 @@ CF_EXPORT CFDictionaryRef DMCopyHTTPRequestHeaders(CFBundleRef appBundle, CFData
// Check minimum and maximum System Version
if ([ui minimumSystemVersion] != nil && ![[ui minimumSystemVersion] isEqualToString:@""]) {
minimumVersionOK = [[SUStandardVersionComparator defaultComparator] compareVersion:[ui minimumSystemVersion] toVersion:[SUHost systemVersionString]] != NSOrderedDescending;
minimumVersionOK = [[SUStandardVersionComparator defaultComparator] compareVersion:[ui minimumSystemVersion] toVersion:[SUOperatingSystem systemVersionString]] != NSOrderedDescending;
}
if ([ui maximumSystemVersion] != nil && ![[ui maximumSystemVersion] isEqualToString:@""]) {
maximumVersionOK = [[SUStandardVersionComparator defaultComparator] compareVersion:[ui maximumSystemVersion] toVersion:[SUHost systemVersionString]] != NSOrderedAscending;
maximumVersionOK = [[SUStandardVersionComparator defaultComparator] 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];
@@ -122,7 +138,7 @@ CF_EXPORT CFDictionaryRef DMCopyHTTPRequestHeaders(CFBundleRef appBundle, CFData
- (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
@@ -140,17 +156,17 @@ CF_EXPORT CFDictionaryRef DMCopyHTTPRequestHeaders(CFBundleRef appBundle, CFData
if ([[self.updater delegate] respondsToSelector:@selector(bestValidUpdateInAppcast:forUpdater:)]) // Does the delegate want to handle it?
{
item = [[self.updater delegate] bestValidUpdateInAppcast:ac forUpdater:self.updater];
if ([item isDeltaUpdate]) {
self.nonDeltaUpdateItem = [[self.updater delegate] bestValidUpdateInAppcast:[ac copyWithoutDeltaUpdates] forUpdater:self.updater];
}
}
else // If not, we'll take care of it ourselves.
{
// 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]) {
// 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;
}
@@ -194,27 +210,38 @@ CF_EXPORT CFDictionaryRef DMCopyHTTPRequestHeaders(CFBundleRef appBundle, CFData
}]];
}
- (void)updateURLRequestHTTPHeaders:(NSMutableURLRequest *)request
- (NSString *)appCachePath
{
NSURL *hostBundleURL = self.host.bundlePath.length ? [NSURL fileURLWithPath:self.host.bundlePath] : nil;
CFBundleRef hostBundle = hostBundleURL ? CFBundleCreate(kCFAllocatorDefault, (__bridge CFURLRef)hostBundleURL) : NULL;
NSDictionary *devmateHeaders = (__bridge_transfer NSDictionary *)DMCopyHTTPRequestHeaders(hostBundle, NULL);
if (devmateHeaders.count)
{
[request setAllHTTPHeaderFields:devmateHeaders];
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();
}
if (NULL != hostBundle)
{
CFRelease(hostBundle);
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];
}
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[self.updateItem fileURL]];
[request setValue:[self.updater userAgentString] forHTTPHeaderField:@"User-Agent"];
[self updateURLRequestHTTPHeaders:request];
if ([[self.updater delegate] respondsToSelector:@selector(updater:willDownloadUpdate:withRequest:)]) {
[[self.updater delegate] updater:self.updater
willDownloadUpdate:self.updateItem
@@ -226,13 +253,14 @@ CF_EXPORT CFDictionaryRef DMCopyHTTPRequestHeaders(CFBundleRef appBundle, CFData
- (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.
@@ -248,90 +276,6 @@ CF_EXPORT CFDictionaryRef DMCopyHTTPRequestHeaders(CFBundleRef appBundle, CFData
[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 isUpdateValid = NO;
do
{
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.");
break;
}
// Modern packages are not distributed as bundles and are code signed differently than regular applications
if (isPackage)
{
isUpdateValid = [SUDSAVerifier validatePath:downloadedPath withEncodedDSASignature:DSASignature withPublicDSAKey:publicDSAKey];
if (!isUpdateValid)
{
SULog(@"DSA signature validation of the package failed. The update will be rejected.");
}
break;
}
NSBundle *newBundle = [NSBundle bundleWithPath:installSourcePath];
if (newBundle == nil)
{
SULog(@"No suitable bundle is found in the update. The update will be rejected.");
break;
}
// Check Code Signing equality
NSError *error = nil;
BOOL updateIsCodeSigned = [SUCodeSigningVerifier applicationAtPathIsCodeSigned:installSourcePath];
updateIsCodeSigned = updateIsCodeSigned && [SUCodeSigningVerifier codeSignatureIsValidAtPath:installSourcePath error:&error];
if (!updateIsCodeSigned)
{
SULog(@"Update has no valid Code Signing (%ld - %@)", error.code, error.localizedDescription);
}
BOOL shouldCheckCodeSignEquality = updateIsCodeSigned ? [SUCodeSigningVerifier applicationAtPathIsCodeSigned:self.host.bundlePath] : NO;
if (shouldCheckCodeSignEquality && [SUCodeSigningVerifier codeSignatureAtPath:self.host.bundlePath matchesSignatureAtPath:installSourcePath error:&error])
{
isUpdateValid = YES;
break;
}
else
{
SULog(@"Code signatures differs in application and update (%ld - %@)", error.code, error.localizedDescription);
}
// Check DSA signature
SUHost *newHost = [[SUHost alloc] initWithBundle:newBundle];
NSString *newPublicDSAKey = newHost.publicDSAKey;
BOOL dsaKeysMatch = (publicDSAKey == nil || newPublicDSAKey == nil) ? NO : [publicDSAKey isEqualToString:newPublicDSAKey];
if (!dsaKeysMatch)
{
SULog(@"DSA keys are different for update and application.");
}
isUpdateValid = dsaKeysMatch && [SUDSAVerifier validatePath:downloadedPath withEncodedDSASignature:DSASignature withPublicDSAKey:newPublicDSAKey];
if (!isUpdateValid)
{
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");
}
}
while (NO);
return isUpdateValid;
}
- (void)downloadDidFinish:(NSURLDownload *)__unused d
{
assert(self.updateItem);
@@ -341,22 +285,26 @@ CF_EXPORT CFDictionaryRef DMCopyHTTPRequestHeaders(CFBundleRef appBundle, CFData
- (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
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
@@ -368,14 +316,28 @@ CF_EXPORT CFDictionaryRef DMCopyHTTPRequestHeaders(CFBundleRef appBundle, CFData
- (void)extractUpdate
{
SUUnarchiver *unarchiver = [SUUnarchiver unarchiverForPath:self.downloadPath updatingHostBundlePath:[[self.host bundle] bundlePath]];
SUUnarchiver *unarchiver = [SUUnarchiver unarchiverForPath:self.downloadPath updatingHostBundlePath:self.host.bundlePath withPassword:self.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) {
[self unarchiverDidFail:nil];
} else {
unarchiver.delegate = self;
[unarchiver start];
}
unarchiver.delegate = self;
[unarchiver start];
}
- (void)failedToApplyDeltaUpdate
@@ -396,6 +358,9 @@ CF_EXPORT CFDictionaryRef DMCopyHTTPRequestHeaders(CFBundleRef appBundle, CFData
- (void)unarchiverDidFail:(SUUnarchiver *)__unused ua
{
// No longer needed
self.updateValidator = nil;
if ([self.updateItem isDeltaUpdate]) {
[self failedToApplyDeltaUpdate];
return;
@@ -410,23 +375,49 @@ CF_EXPORT CFDictionaryRef DMCopyHTTPRequestHeaders(CFBundleRef appBundle, CFData
[self installWithToolAndRelaunch:relaunch displayingUserInterface:relaunch];
}
// Creates intermediate directories up until targetPath if they don't already exist,
// and removes the directory at targetPath if one already exists there
- (BOOL)preparePathForRelaunchTool:(NSString *)targetPath error:(NSError * __autoreleasing *)error
{
NSFileManager *fileManager = [[NSFileManager alloc] init];
if ([fileManager fileExistsAtPath:targetPath]) {
NSError *removeError = nil;
if (![fileManager removeItemAtPath:targetPath error:&removeError]) {
if (error != NULL) {
*error = removeError;
}
return NO;
}
} else {
NSError *createDirectoryError = nil;
if (![fileManager createDirectoryAtPath:[targetPath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:@{} error:&createDirectoryError]) {
if (error != NULL) {
*error = createDirectoryError;
}
return NO;
}
}
return YES;
}
- (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])
{
[self abortUpdate:SUUpdateAbortForbiddenByDelegate];
[self abortUpdate];
return;
}
@@ -455,32 +446,43 @@ CF_EXPORT CFDictionaryRef DMCopyHTTPRequestHeaders(CFBundleRef appBundle, CFData
// 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]];
// Only the paranoid survive: if there's already a stray copy of relaunch there, we would have problems.
NSError *error = nil;
[[NSFileManager defaultManager] createDirectoryAtPath:[targetPath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:@{} error:&error];
NSString *const relaunchToolSourcePath = [sparkleBundle pathForResource:relaunchToolName ofType:@"app"];
NSString *relaunchCopyTargetPath = nil;
NSError *error = nil;
BOOL copiedRelaunchPath = NO;
BOOL copySuccess = NO;
if (SUShouldUseXPCInstaller())
{
copySuccess = [SUXPCInstaller copyPathWithAuthentication:relaunchPathToCopy overPath:targetPath appendVersion:SPARKLE_APPEND_VERSION_NUMBER error:&error];
}
else
{
copySuccess = [SUPlainInstaller copyPathWithAuthentication:relaunchPathToCopy overPath:targetPath appendVersion:SPARKLE_APPEND_VERSION_NUMBER error:&error];
}
if (copySuccess) {
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 (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: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:relaunchCopyTargetURL error:&quarantineError]) {
SULog(@"Failed to release quarantine on %@ with error %@", relaunchCopyTargetPath, quarantineError);
}
}
}
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,9 +492,8 @@ CF_EXPORT CFDictionaryRef DMCopyHTTPRequestHeaders(CFBundleRef appBundle, CFData
// 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;
}
@@ -500,23 +501,17 @@ CF_EXPORT CFDictionaryRef DMCopyHTTPRequestHeaders(CFBundleRef appBundle, CFData
if ([updaterDelegate respondsToSelector:@selector(pathToRelaunchForUpdater:)]) {
pathToRelaunch = [updaterDelegate pathToRelaunchForUpdater:self.updater];
}
NSArray *arguments = @[self.host.bundlePath.length ? self.host.bundlePath: @"",
pathToRelaunch.length ? pathToRelaunch : @"",
[NSString stringWithFormat:@"%d", [[NSProcessInfo processInfo] processIdentifier]],
self.tempDir.length ? self.tempDir : @"",
relaunch ? @"1" : @"0",
showUI ? @"1" : @"0"];
if (SUShouldUseXPCInstaller())
{
[SUXPCInstaller launchTaskWithPath:relaunchToolPath arguments:arguments environment:nil currentDirectoryPath:nil inputData:nil waitUntilDone:NO completionHandler:nil];
}
else
{
[NSTask launchedTaskWithLaunchPath:relaunchToolPath arguments:arguments];
}
[NSTask launchedTaskWithLaunchPath:relaunchToolPath arguments:@[[self.host bundlePath],
pathToRelaunch,
[NSString stringWithFormat:@"%d", [[NSProcessInfo processInfo] processIdentifier]],
self.tempDir,
relaunch ? @"1" : @"0",
showUI ? @"1" : @"0"]];
[self terminateApp];
}
// Note: this is overridden by the automatic update driver to not terminate in some cases
- (void)terminateApp
{
[NSApp terminate:self];
@@ -548,18 +543,23 @@ CF_EXPORT CFDictionaryRef DMCopyHTTPRequestHeaders(CFBundleRef appBundle, CFData
}]];
}
- (void)abortUpdate:(SUUpdateAbortReason)reason
- (void)abortUpdate
{
[self cleanUpDownload];
[[NSNotificationCenter defaultCenter] removeObserver:self];
self.updateItem = nil;
[super abortUpdate:reason];
[super abortUpdate];
}
- (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];
@@ -571,7 +571,7 @@ CF_EXPORT CFDictionaryRef DMCopyHTTPRequestHeaders(CFBundleRef appBundle, CFData
[updaterDelegate updater:self.updater didAbortWithError:error];
}
[self abortUpdate:SUUpdateAbortGotError];
[self abortUpdate];
}
@end
+4 -3
View File
@@ -7,6 +7,7 @@
//
#include "SUBinaryDeltaCommon.h"
#import "SUFileManager.h"
#include <CommonCrypto/CommonDigest.h>
#include <Foundation/Foundation.h>
#include <fcntl.h>
@@ -220,7 +221,7 @@ BOOL removeTree(NSString *path)
BOOL copyTree(NSString *source, NSString *dest)
{
return [[NSFileManager defaultManager] copyItemAtPath:source toPath:dest error:nil];
return [[SUFileManager defaultManager] copyItemAtURL:[NSURL fileURLWithPath:source] toURL:[NSURL fileURLWithPath:dest] error:NULL];
}
BOOL modifyPermissions(NSString *path, mode_t desiredPermissions)
@@ -230,12 +231,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;
}
+11 -1
View File
@@ -87,7 +87,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;
}
@@ -439,6 +439,16 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
NSString *temporaryFile = temporaryPatchFile(patchFile);
xar_t x = xar_open([temporaryFile fileSystemRepresentation], WRITE);
if (!x) {
if (verbose) {
fprintf(stderr, "\n");
}
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileWriteUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to write to %@", temporaryFile] }];
}
return NO;
}
xar_opt_set(x, XAR_OPT_COMPRESSION, "bzip2");
xar_subdoc_t attributes = xar_subdoc_new(x, BINARY_DELTA_ATTRIBUTES_KEY);
+43 -1
View File
@@ -10,9 +10,9 @@
#import "SUBinaryDeltaUnarchiver.h"
#import "SUBinaryDeltaApply.h"
#import "SUUnarchiver_Private.h"
#import "SUFileManager.h"
#import "SUHost.h"
#import "SULog.h"
#import "NTSynchronousTask.h"
@implementation SUBinaryDeltaUnarchiver
@@ -21,6 +21,46 @@
return [[path pathExtension] isEqualToString:@"delta"];
}
+ (BOOL)unsafeIfArchiveIsNotValidated
{
return YES;
}
// 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];
}
}
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)applyBinaryDelta
{
@autoreleasepool {
@@ -30,6 +70,8 @@
NSError *applyDiffError = nil;
BOOL success = applyBinaryDelta(sourcePath, targetPath, self.archivePath, NO, &applyDiffError);
if (success) {
[[self class] updateSpotlightImportersAtBundlePath:targetPath];
dispatch_async(dispatch_get_main_queue(), ^{
[self notifyDelegateOfSuccess];
});
+3 -5
View File
@@ -12,11 +12,9 @@
#import <Foundation/Foundation.h>
@interface SUCodeSigningVerifier : NSObject
// pass nil as an application path to check a host one
+ (BOOL)codeSignatureAtPath:(NSString *)hostPath matchesSignatureAtPath:(NSString *)otherAppPath error:(NSError **)error;
+ (BOOL)codeSignatureIsValidAtPath:(NSString *)applicationPath error:(NSError **)error;
+ (BOOL)applicationAtPathIsCodeSigned:(NSString *)applicationPath;
+ (BOOL)hostApplicationIsSandboxed;
+ (BOOL)codeSignatureAtBundleURL:(NSURL *)oldBundlePath matchesSignatureAtBundleURL:(NSURL *)newBundlePath error:(NSError **)error;
+ (BOOL)codeSignatureIsValidAtBundleURL:(NSURL *)bundlePath error:(NSError **)error;
+ (BOOL)bundleAtURLIsCodeSigned:(NSURL *)bundlePath;
@end
#endif
+43 -145
View File
@@ -13,94 +13,46 @@
@implementation SUCodeSigningVerifier
+ (BOOL)codeSignatureAtPath:(NSString *)hostPath matchesSignatureAtPath:(NSString *)otherAppPath error:(NSError *__autoreleasing *)error
+ (BOOL)codeSignatureAtBundleURL:(NSURL *)oldBundleURL matchesSignatureAtBundleURL:(NSURL *)newBundleURL error:(NSError *__autoreleasing *)error
{
OSStatus result;
SecRequirementRef requirement = NULL;
SecStaticCodeRef staticHostCode = NULL;
SecStaticCodeRef staticAppCode = NULL;
SecStaticCodeRef staticCode = NULL;
SecStaticCodeRef oldCode = NULL;
CFErrorRef cfError = NULL;
if (error) {
*error = nil;
}
if (0 == hostPath.length) {
SecCodeRef hostCode = NULL;
result = SecCodeCopySelf(kSecCSDefaultFlags, &hostCode);
if (result != noErr) {
SULog(@"Failed to copy host code %d", result);
goto finally;
}
result = SecCodeCopyStaticCode(hostCode, kSecCSDefaultFlags, &staticHostCode);
CFRelease(hostCode);
if (result != noErr) {
SULog(@"Failed to copy host code %d", result);
goto finally;
}
} else {
NSBundle *hostAppBundle = [NSBundle bundleWithPath:hostPath];
if (nil == hostAppBundle) {
SULog(@"Failed to create bundle at path %@", hostPath);
result = -1;
goto finally;
}
result = SecStaticCodeCreateWithPath((__bridge CFURLRef)hostAppBundle.bundleURL, kSecCSDefaultFlags, &staticHostCode);
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(staticHostCode, kSecCSDefaultFlags, &requirement);
result = SecCodeCopyDesignatedRequirement(oldCode, kSecCSDefaultFlags, &requirement);
if (result != noErr) {
SULog(@"Failed to copy designated requirement. Code Signing OSStatus code: %d", result);
goto finally;
}
if (0 == otherAppPath.length) {
SecCodeRef hostCode = NULL;
result = SecCodeCopySelf(kSecCSDefaultFlags, &hostCode);
if (result != noErr) {
SULog(@"Failed to copy other app code %d", result);
goto finally;
}
result = SecCodeCopyStaticCode(hostCode, kSecCSDefaultFlags, &staticAppCode);
CFRelease(hostCode);
if (result != noErr) {
SULog(@"Failed to copy other app code %d", result);
goto finally;
}
} else {
NSBundle *otherAppBundle = [NSBundle bundleWithPath:otherAppPath];
if (nil == otherAppBundle) {
SULog(@"Failed to create bundle at path %@", otherAppPath);
result = -1;
goto finally;
}
result = SecStaticCodeCreateWithPath((__bridge CFURLRef)otherAppBundle.bundleURL, kSecCSDefaultFlags, &staticAppCode);
if (result != noErr) {
SULog(@"Failed to copy other app code %d", result);
goto finally;
}
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
CFErrorRef cfError = NULL;
SecCSFlags flags = (SecCSFlags) (kSecCSDefaultFlags | kSecCSCheckAllArchitectures);
result = SecStaticCodeCheckValidityWithErrors(staticAppCode, flags, requirement, &cfError);
// 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 (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.");
@@ -111,61 +63,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:staticHostCode label:@"host info"];
[self logSigningInfoForCode:staticAppCode label:@"new info"];
[self logSigningInfoForCode:oldCode label:@"old info"];
[self logSigningInfoForCode:staticCode label:@"new info"];
}
}
finally:
if (staticHostCode) CFRelease(staticHostCode);
if (staticAppCode) CFRelease(staticAppCode);
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);
@@ -182,68 +125,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)hostApplicationIsSandboxed
{
static BOOL sIsAppSandboxed = NO;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
__block SecCodeRef hostCode = NULL;
__block SecRequirementRef hostRequirement = NULL;
void (^Cleanup)(void) = ^ {
if (hostCode) { CFRelease(hostCode); hostCode = NULL; }
if (hostRequirement) { CFRelease(hostRequirement); hostRequirement = NULL; }
};
OSStatus status = SecCodeCopySelf(kSecCSDefaultFlags, &hostCode);
if (status != noErr || hostCode == NULL)
{
Cleanup();
return;
}
CFStringRef requirementString = CFSTR("entitlement[\"com.apple.security.app-sandbox\"] exists");
status = SecRequirementCreateWithString(requirementString, kSecCSDefaultFlags, &hostRequirement);
if (status != noErr || hostRequirement == NULL)
{
Cleanup();
return;
}
status = SecCodeCheckValidity(hostCode, kSecCSDefaultFlags, hostRequirement);
sIsAppSandboxed = (noErr == status);
Cleanup();
});
return sIsAppSandboxed;
}
+ (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;
@@ -255,7 +153,7 @@ static id valueOrNSNull(id value) {
CFRelease(requirement);
}
if (result == errSecCSUnsigned) {
return NO;
return NO;
}
return (result == 0);
}
+1 -16
View File
@@ -12,21 +12,6 @@
#import <Foundation/Foundation.h>
// -----------------------------------------------------------------------------
// Typedefs:
// -----------------------------------------------------------------------------
typedef NS_ENUM(NSUInteger, SUUpdateAbortReason)
{
SUUpdateAbortUndefined = 0,
SUUpdateAbortForbiddenByDelegate,
SUUpdateAbortTasksFinished,
SUUpdateAbortCanceledByUser,
SUUpdateAbortDidNotFind,
SUUpdateAbortInterrupred,
SUUpdateAbortGotError
};
// -----------------------------------------------------------------------------
// Misc:
// -----------------------------------------------------------------------------
@@ -58,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.")));
+1 -2
View File
@@ -12,7 +12,6 @@
#import "SUAppcastItem.h"
#import "SUVersionComparisonProtocol.h"
#import "SUConstants.h"
#import "SUErrors.h"
#ifndef DEBUG
#define DEBUG 0
@@ -39,10 +38,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";
+77 -78
View File
@@ -8,10 +8,8 @@
#import "SUDiskImageUnarchiver.h"
#import "SUUnarchiver_Private.h"
#import "NTSynchronousTask.h"
#import "SULog.h"
#include <CoreServices/CoreServices.h>
#import "SUXPCInstaller.h"
@implementation SUDiskImageUnarchiver
@@ -20,6 +18,11 @@
return [[path pathExtension] isEqualToString:@"dmg"];
}
+ (BOOL)unsafeIfArchiveIsNotValidated
{
return NO;
}
// Called on a non-main thread.
- (void)extractDMG
{
@@ -36,6 +39,12 @@
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"
@@ -45,10 +54,7 @@
dispatch_block_t delegateSuccess = ^{
[self notifyDelegateOfSuccess];
};
// get a unique mount point path
NSString *mountPoint = nil;
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.
@@ -63,37 +69,51 @@
CFRelease(uuid);
}
}
while ([[NSFileManager defaultManager] fileExistsAtPath:mountPoint]);
while (noErr == FSPathMakeRefWithOptions((const UInt8 *)[mountPoint fileSystemRepresentation], kFSPathMakeRefDoNotFollowLeafSymlink, &tmpRef, NULL));
NSData *promptData = nil;
promptData = [NSData dataWithBytes:"yes\n" length:4];
NSString *hdiutilPath = @"/usr/bin/hdiutil";
NSArray *arguments = @[@"attach", self.archivePath, @"-mountpoint", mountPoint, /*@"-noverify",*/ @"-nobrowse", @"-noautoopen"];
NSString *currentDirPath = @"/";
NSMutableArray *arguments = [@[@"attach", self.archivePath, @"-mountpoint", mountPoint, /*@"-noverify",*/ @"-nobrowse", @"-noautoopen"] mutableCopy];
BOOL shouldUseXPC = SUShouldUseXPCInstaller();
__block NSData *output = nil;
__block NSInteger taskResult = -1;
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
{
if (shouldUseXPC)
{
[SUXPCInstaller launchTaskWithPath:hdiutilPath arguments:arguments environment:nil currentDirectoryPath:currentDirPath inputData:promptData waitUntilDone:YES completionHandler:^(int result, NSData *outputData) {
taskResult = (NSInteger)result;
output = [outputData copy];
}];
}
else
{
NTSynchronousTask *task = [[NTSynchronousTask alloc] init];
[task run:hdiutilPath directory:currentDirPath withArgs:arguments input:promptData];
taskResult = [task result];
output = [[task output] copy];
}
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];
[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 *)
{
@@ -109,45 +129,30 @@
mountedSuccessfully = YES;
// Now that we've mounted it, we need to copy out its contents.
if (shouldUseXPC)
{
NSError *error = nil;
[SUXPCInstaller copyPathContent:mountPoint toDirectory:[self.archivePath stringByDeletingLastPathComponent] error:&error];
if (nil != error)
{
SULog(@"Couldn't copy volume content: %ld - %@", error.code, error.localizedDescription);
goto reportError;
}
manager = [[NSFileManager alloc] init];
contents = [manager contentsOfDirectoryAtPath:mountPoint error:&error];
if (error)
{
SULog(@"Couldn't enumerate contents of archive mounted at %@: %@", mountPoint, error);
goto reportError;
}
else
{
NSFileManager *manager = [[NSFileManager alloc] init];
NSError *error = nil;
NSArray *contents = [manager contentsOfDirectoryAtPath:mountPoint error:&error];
if (error)
{
SULog(@"Couldn't enumerate contents of archive mounted at %@: %@", mountPoint, error);
goto reportError;
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;
}
for (NSString *item in contents)
{
NSString *fromPath = [mountPoint stringByAppendingPathComponent:item];
NSString *toPath = [[self.archivePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:item];
SULog(@"copyItemAtPath:%@ toPath:%@", fromPath, toPath);
// We skip any files in the DMG which are not readable.
if (![manager isReadableFileAtPath:fromPath]) {
continue;
}
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;
}
if (![manager copyItemAtPath:fromPath toPath:toPath error:&error])
{
SULog(@"Couldn't copy item: %@ : %@", error, error.userInfo ? error.userInfo : @"");
goto reportError;
}
}
@@ -158,20 +163,14 @@
dispatch_async(dispatch_get_main_queue(), delegateFailure);
finally:
if (mountedSuccessfully)
{
arguments = @[@"detach", mountPoint, @"-force"];
if (shouldUseXPC)
{
[SUXPCInstaller launchTaskWithPath:hdiutilPath arguments:arguments environment:nil currentDirectoryPath:nil inputData:nil waitUntilDone:NO completionHandler:nil];
if (mountedSuccessfully) {
@try {
[NSTask launchedTaskWithLaunchPath:@"/usr/bin/hdiutil" arguments:@[@"detach", mountPoint, @"-force"]];
} @catch (NSException *exception) {
SULog(@"Failed to unmount %@", mountPoint);
SULog(@"Exception: %@", exception);
}
else
{
[NSTask launchedTaskWithLaunchPath:hdiutilPath arguments:arguments];
}
}
else
{
} else {
SULog(@"Can't mount DMG %@", self.archivePath);
}
}
+11 -4
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,8 +44,10 @@ typedef NS_ENUM(OSStatus, SUError) {
SURelaunchError = 4004,
SUInstallationError = 4005,
SUDowngradeError = 4006,
SUInstallationCancelledError = 4007,
SUXPCServiceError = 4007
// System phase errors
SUSystemPowerOffError = 5000
};
#endif
+171
View File
@@ -0,0 +1,171 @@
//
// SUFileManager.h
// Sparkle
//
// Created by Mayur Pawashe on 7/18/15.
// Copyright (c) 2015 zgcoder. All rights reserved.
//
#import <Foundation/Foundation.h>
/**
* 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 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 or if it doesn't need to.
*/
+ (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
* @param preferredName A name that may be used when creating the temporary directory. Note that in the uncommon case this name is used, the temporary directory will be created inside the directory pointed by appropriateURL
* @param appropriateURL A URL to a directory that resides on the volume that the temporary directory will be created on. In the uncommon case, the temporary directory may be created inside this directory.
* @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 A URL pointing to the newly created temporary directory, or nil with a populated error object if an error occurs.
*
* 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;
/**
* 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 **)error;
/**
* Moves an item from a source to a destination
* @param sourceURL A URL pointing to the item to move. The item at this URL must exist.
* @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;
/**
* Copies an item from a source to a destination
* @param sourceURL A URL pointing to the item to move. The item at this URL must exist.
* @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 copied successfully, otherwise NO along with a populated error object
*
* 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;
/**
* Removes an item at a URL
* @param url A URL pointing to the item to remove. 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 removed successfully, otherwise NO along with a populated error object
*
* This is not an atomic operation.
*/
- (BOOL)removeItemAtURL:(NSURL *)url error:(NSError **)error;
/**
* Changes the owner and group IDs of an item at a specified target URL to match another URL
* @param targetURL A URL pointing to the target item whose owner and group IDs to alter. This will be applied recursively if the item is a directory. The item at this URL must exist.
* @param matchURL A URL pointing to the item whose owner and group IDs will be used for changing on the targetURL. 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 target item's owner and group IDs have changed to match the origin's ones, otherwise NO along with a populated error object
*
* If the owner and group IDs match on the root items of targetURL and matchURL, this method stops and assumes that nothing needs to be done.
* Otherwise this method recursively changes the IDs if the target is a directory. If an item in the directory is encountered that is unable to be changed,
* then this method stops and returns NO.
*
* This is not an atomic operation.
*/
- (BOOL)changeOwnerAndGroupOfItemAtRootURL:(NSURL *)targetURL toMatchURL:(NSURL *)matchURL error:(NSError **)error;
/**
* Updates the modification and access time of an item at a specified target URL to the current time
* @param targetURL A URL pointing to the target item whose modification and access time to update. 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 target item's modification and access times have been updated, otherwise NO along with a populated error object
*
* This method updates the modification and access time of an item to the current time, ideal for letting the system know we installed a new file or
* application.
*
* This is not an atomic operation.
*/
- (BOOL)updateModificationAndAccessTimeOfItemAtURL:(NSURL *)targetURL error:(NSError **)error;
/**
* Releases Apple's quarantine extended attribute from the item at the specified root URL
* @param rootURL A URL pointing to the item to release from Apple's quarantine. This will be applied recursively if the item is a directory. 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 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 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.
* Thus if an item cannot be released from quarantine, this method still continues on to the next enumerated item.
*
* This is not an atomic operation.
*/
- (BOOL)releaseItemFromQuarantineAtRootURL:(NSURL *)rootURL error:(NSError **)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 **)error;
@end
+1036
View File
File diff suppressed because it is too large. Load diff
+2 -2
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.
@@ -29,7 +29,7 @@ A guided installation can be started by applications other than the application
@interface SUGuidedPackageInstaller : SUInstaller
/*! Perform the guided installation */
+ (void)performInstallationToPath:(NSString *)path fromPath:(NSString *)installerGuide host:(SUHost *)host versionComparator:(id<SUVersionComparison>)comparator completionHandler:(void (^)(NSError *))completionHandler;
+ (void)performInstallationToPath:(NSString *)path fromPath:(NSString *)installerGuide host:(SUHost *)host fileOperationToolPath:(NSString *)fileOperationToolPath versionComparator:(id<SUVersionComparison>)comparator completionHandler:(void (^)(NSError *))completionHandler;
@end
#endif
+9 -119
View File
@@ -6,137 +6,27 @@
// Copyright 2010 Dragon Systems Software Limited. All rights reserved.
//
#import <sys/stat.h>
#import <Security/Security.h>
#import "SUGuidedPackageInstaller.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)
+ (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;
}
@end
#import "SUFileManager.h"
@implementation SUGuidedPackageInstaller
+ (void)performInstallationToPath:(NSString *)destinationPath fromPath:(NSString *)packagePath host:(SUHost *)__unused host versionComparator:(id<SUVersionComparison>)__unused comparator completionHandler:(void (^)(NSError *))completionHandler
+ (void)performInstallationToPath:(NSString *)destinationPath fromPath:(NSString *)packagePath host:(SUHost *)__unused host fileOperationToolPath:(NSString *)fileOperationToolPath versionComparator:(id<SUVersionComparison>)__unused comparator completionHandler:(void (^)(NSError *))completionHandler
{
SUParameterAssert(packagePath);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Preflight
NSString* installerPath = @"/usr/sbin/installer"; // Mac OS X 10.2+ command line installer tool
NSError* error = nil;
// 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]];
}
SUFileManager *fileManager = [SUFileManager fileManagerWithAuthorizationToolPath:fileOperationToolPath];
NSError *error = nil;
BOOL validInstallation = [fileManager executePackageAtURL:[NSURL fileURLWithPath:packagePath] error:&error];
dispatch_async(dispatch_get_main_queue(), ^{
[self finishInstallationToPath:destinationPath
withResult:validInstallation
error:error
completionHandler:completionHandler];
});
});
}
+2 -4
View File
@@ -23,12 +23,9 @@ typedef struct {
@property (strong, readonly) NSBundle *bundle;
+ (NSOperatingSystemVersion)operatingSystemVersion;
+ (NSString *)systemVersionString;
- (instancetype)initWithBundle:(NSBundle *)aBundle;
@property (readonly, copy) NSString *bundlePath;
@property (readonly, copy) NSString *appCachePath;
@property (readonly) BOOL allowsAutomaticUpdates;
@property (readonly, copy) NSString *installationPath;
@property (readonly, copy) NSString *name;
@property (readonly, copy) NSString *version;
@@ -37,6 +34,7 @@ typedef struct {
@property (getter=isRunningOnReadOnlyVolume, readonly) BOOL runningOnReadOnlyVolume;
@property (getter=isBackgroundApplication, readonly) BOOL backgroundApplication;
@property (readonly, copy) NSString *publicDSAKey;
@property (readonly, nonatomic, copy) NSString *publicDSAKeyFileKey;
@property (readonly, copy) NSArray *systemProfile;
- (id)objectForInfoDictionaryKey:(NSString *)key;
+45 -46
View File
@@ -11,6 +11,7 @@
#import "SUSystemProfiler.h"
#include <sys/mount.h> // For statfs for isRunningOnReadOnlyVolume
#import "SULog.h"
#import "SUFileManager.h"
#if __MAC_OS_X_VERSION_MAX_ALLOWED < 101000
@interface NSProcessInfo ()
@@ -62,26 +63,46 @@
return [self.bundle bundlePath];
}
- (NSString *)appCachePath
- (BOOL)allowsAutomaticUpdates
{
NSArray *cachePaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachePath = nil;
if ([cachePaths count]) {
cachePath = cachePaths[0];
// Does the developer want us to disable automatic updates?
NSNumber *developerAllowsAutomaticUpdates = [self objectForInfoDictionaryKey:SUAllowsAutomaticUpdatesKey];
if (developerAllowsAutomaticUpdates != nil && !developerAllowsAutomaticUpdates.boolValue) {
return NO;
}
if (!cachePath) {
SULog(@"Failed to find user's cache directory! Using system default");
cachePath = NSTemporaryDirectory();
// Can we automatically update in the background without bugging the user (e.g, with a administrator password prompt)?
// Note it's very well possible to have the bundle be writable but not be able to write into the parent directory
// And if the bundle isn't writable, but we can write into the parent directory, we will still need to authorize to replace it
NSString *bundlePath = [self bundlePath];
if (![[NSFileManager defaultManager] isWritableFileAtPath:bundlePath.stringByDeletingLastPathComponent] || ![[NSFileManager defaultManager] isWritableFileAtPath:bundlePath]) {
return NO;
}
NSString *name = [self.bundle bundleIdentifier];
if (!name) {
name = [self name];
// Just because we have writability access does not mean we can set the correct owner/group silently
// Test if we can set the owner/group on a temporarily created file
// If we can, then we can probably perform an update without authorization
// One place where this matters is if you copy and run an app from /tmp/
NSString *tempFilename = @"permission_test" ;
SUFileManager *suFileManager = [SUFileManager defaultManager];
NSURL *tempDirectoryURL = [suFileManager makeTemporaryDirectoryWithPreferredName:tempFilename appropriateForDirectoryURL:[NSURL fileURLWithPath:NSTemporaryDirectory()] error:NULL];
if (tempDirectoryURL == nil) {
// I don't imagine this ever happening but in case it does, requesting authorization may be the better option
return NO;
}
cachePath = [cachePath stringByAppendingPathComponent:name];
cachePath = [cachePath stringByAppendingPathComponent:@"Sparkle"];
return cachePath;
NSURL *tempFileURL = [tempDirectoryURL URLByAppendingPathComponent:tempFilename];
BOOL changeOwnerAndGroupSuccess =
[[NSData data] writeToURL:tempFileURL atomically:NO] &&
[suFileManager changeOwnerAndGroupOfItemAtRootURL:tempFileURL toMatchURL:self.bundle.bundleURL error:NULL];
[suFileManager removeItemAtURL:tempDirectoryURL error:NULL];
return changeOwnerAndGroupSuccess;
}
- (NSString *)installationPath
@@ -135,11 +156,11 @@
{
// 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
// According to the macOS docs, "CFBundleIconFile - This key identifies the file containing
// the icon for the bundle. The filename you specify does not need to include the .icns
// extension, although it may."
//
// However, if it *does* include the '.icns' the above method fails (tested on OS X 10.3.9) so we'll also try:
// However, if it *does* include the '.icns' the above method fails (tested on macOS 10.3.9) so we'll also try:
if (!iconPath) {
iconPath = [self.bundle pathForResource:[self.bundle objectForInfoDictionaryKey:@"CFBundleIconFile"] ofType:nil];
}
@@ -175,7 +196,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;
}
@@ -187,6 +208,11 @@
return [NSString stringWithContentsOfFile:keyPath encoding:NSASCIIStringEncoding error:nil];
}
- (NSString * __nullable)publicDSAKeyFileKey
{
return [self objectForInfoDictionaryKey:SUPublicDSAKeyFileKey];
}
- (NSArray *)systemProfile
{
return [[SUSystemProfiler sharedSystemProfiler] systemProfileArrayForHost:self];
@@ -272,31 +298,4 @@
return [self objectForUserDefaultsKey:key] ? [self boolForUserDefaultsKey:key] : [self boolForInfoDictionaryKey:key];
}
+ (NSOperatingSystemVersion)operatingSystemVersion
{
#if __MAC_OS_X_VERSION_MIN_REQUIRED < 1090 // Present in 10.9 despite NS_AVAILABLE's claims
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wselector"
// Xcode 5.1.1: operatingSystemVersion is clearly declared, must warn due to a compiler bug?
if (![NSProcessInfo instancesRespondToSelector:@selector(operatingSystemVersion)])
#pragma clang diagnostic pop
{
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;
return version;
}
#endif
return [[NSProcessInfo processInfo] operatingSystemVersion];
}
+ (NSString *)systemVersionString
{
NSOperatingSystemVersion version = self.operatingSystemVersion;
return [NSString stringWithFormat:@"%ld.%ld.%ld", (long)version.majorVersion, (long)version.minorVersion, (long)version.patchVersion];
}
@end
+1 -1
View File
@@ -16,7 +16,7 @@
@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)installFromUpdateFolder:(NSString *)inUpdateFolder overHost:(SUHost *)host installationPath:(NSString *)installationPath fileOperationToolPath:(NSString *)fileOperationToolPath versionComparator:(id<SUVersionComparison>)comparator completionHandler:(void (^)(NSError *))completionHandler;
+ (void)finishInstallationToPath:(NSString *)installationPath withResult:(BOOL)result error:(NSError *)error completionHandler:(void (^)(NSError *))completionHandler;
@end
+5 -26
View File
@@ -103,7 +103,7 @@
return newAppDownloadPath;
}
+ (void)installFromUpdateFolder:(NSString *)inUpdateFolder overHost:(SUHost *)host installationPath:(NSString *)installationPath versionComparator:(id<SUVersionComparison>)comparator completionHandler:(void (^)(NSError *))completionHandler
+ (void)installFromUpdateFolder:(NSString *)inUpdateFolder overHost:(SUHost *)host installationPath:(NSString *)installationPath fileOperationToolPath:(NSString *)fileOperationToolPath versionComparator:(id<SUVersionComparison>)comparator completionHandler:(void (^)(NSError *))completionHandler
{
BOOL isPackage = NO;
BOOL isGuided = NO;
@@ -113,39 +113,18 @@
[self finishInstallationToPath:installationPath withResult:NO error:[NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingUpdateError userInfo:@{ NSLocalizedDescriptionKey: @"Couldn't find an appropriate update in the downloaded package." }] completionHandler:completionHandler];
} else {
if (isPackage && isGuided) {
[SUGuidedPackageInstaller performInstallationToPath:installationPath fromPath:newAppDownloadPath host:host versionComparator:comparator completionHandler:completionHandler];
[SUGuidedPackageInstaller performInstallationToPath:installationPath fromPath:newAppDownloadPath host:host fileOperationToolPath:fileOperationToolPath versionComparator:comparator completionHandler:completionHandler];
} else if (isPackage) {
[SUPackageInstaller performInstallationToPath:installationPath fromPath:newAppDownloadPath host:host versionComparator:comparator completionHandler:completionHandler];
[SUPackageInstaller performInstallationToPath:installationPath fromPath:newAppDownloadPath host:host fileOperationToolPath:fileOperationToolPath versionComparator:comparator completionHandler:completionHandler];
} else {
[SUPlainInstaller performInstallationToPath:installationPath fromPath:newAppDownloadPath host:host versionComparator:comparator completionHandler:completionHandler];
[SUPlainInstaller performInstallationToPath:installationPath fromPath:newAppDownloadPath host:host fileOperationToolPath:fileOperationToolPath versionComparator:comparator completionHandler:completionHandler];
}
}
}
+ (void)mdimportInstallationPath:(NSString *)installationPath
{
// *** 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
+ (void)finishInstallationToPath:(NSString *)__unused installationPath withResult:(BOOL)result error:(NSError *)error completionHandler:(void (^)(NSError *))completionHandler
{
if (result) {
[self mdimportInstallationPath:installationPath];
dispatch_async(dispatch_get_main_queue(), ^{
completionHandler(nil);
});
+1 -4
View File
@@ -63,11 +63,7 @@ void SULog(NSString *format, ...)
va_list ap;
va_start(ap, format);
NSString *theStr = [[NSString alloc] initWithFormat:format arguments:ap];
va_end(ap);
#ifdef DEBUG
NSLog(@"Sparkle: %@", theStr);
#endif
FILE *logfile = fopen([[SULogFilePath stringByExpandingTildeInPath] fileSystemRepresentation], "a");
if (logfile) {
@@ -76,6 +72,7 @@ void SULog(NSString *format, ...)
fwrite([theData bytes], 1, [theData length], logfile);
fclose(logfile);
}
va_end(ap);
}
+16
View File
@@ -0,0 +1,16 @@
//
// SUOperatingSystem.h
// Sparkle
//
// Copyright © 2015 Sparkle Project. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface SUOperatingSystem : NSObject
+ (NSOperatingSystemVersion)operatingSystemVersion;
+ (BOOL)isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion)version;
+ (NSString *)systemVersionString;
@end
Loaded 100 of 285 files, more files were not shown because too many files have changed in this diff. Show more