Compare commits

..
137 Commits
Author SHA1 Message Date
Dmytro Tretiakov b005fc5151 Updated DMCore lib (fix of potential crash). 2016-02-10 14:07:05 +02:00
Dmytro Tretiakov 47d1aa0bcd Fixed build phase of test app for release configuration. 2016-02-01 19:10:18 +02:00
Dmytro Tretiakov dd2d8b1d26 Merge tag '1.13.1' into develop
# Conflicts:
#	Sparkle.xcodeproj/project.pbxproj
#	Sparkle/SUDiskImageUnarchiver.m
#	Sparkle/SUUIBasedUpdateDriver.m
#	Sparkle/SUUpdateAlert.m
#	Sparkle/SUUpdateDriver.h
#	Sparkle/SUUpdateDriver.m
#	Sparkle/SUUpdater.m
2016-02-01 18:53:03 +02:00
Dmytro Tretiakov d6b1b0adf5 Fixed updating for sandboxed apps. 2016-02-01 17:51:45 +02:00
Dmytro Tretiakov b01c8ab023 Merge tag '1.13.0' into develop
# Conflicts:
#	Sparkle/Autoupdate/Autoupdate.m
#	Sparkle/SUBasicUpdateDriver.m
#	Sparkle/SUErrors.h
#	Sparkle/SUUIBasedUpdateDriver.m
#	Sparkle/SUUpdateDriver.h
#	Sparkle/SUUpdateDriver.m
#	Sparkle/Sparkle.h
2016-01-29 17:17:19 +02:00
Dmytro Tretiakov 62ee3fa6b1 Removed compile warnings. 2015-11-02 12:24:46 +02:00
Dmytro Tretiakov d79643b458 Removed compile warnings. 2015-10-28 12:33:26 +02:00
Dmytro Tretiakov 08ad834d3f Fixed update codesing check for case when host app is not the main bundle. 2015-10-28 12:32:48 +02:00
Dmytro Tretiakov 65ccd10a9c Fixed potential exceptions. 2015-10-22 17:17:27 +03:00
Dmytro Tretiakov 045875ae08 Corrected class forward declarations for public headers. 2015-10-22 17:16:49 +03:00
Dmytro Tretiakov f5f5c517a5 Merge branch 'sparkle_master'. 2015-09-23 14:05:30 +03:00
Dmytro Tretiakov 3a1e60890e Fixed problem with sanboxed updates under OS X 10.11. 2015-09-23 13:52:59 +03:00
Dmytro Tretiakov ba30bb137d Removed unneeded files that left after merging with develop branch. 2015-09-03 12:15:26 +03:00
Dmytro Tretiakov d9e7ec2cf9 Merge branch 'develop' (Updated Sparkle to the latest public release). 2015-08-28 13:16:43 +03:00
Dmytro Tretiakov 30d8815213 Changed updated validation logic to support DevMate specific. 2015-08-27 11:30:24 +03:00
Dmytro Tretiakov 8a7857ba59 Patch updates loging for sandboxed apps. 2015-08-26 17:32:54 +03:00
Dmytro Tretiakov 45345c0a44 Corrected test app updates check when it's signed. 2015-08-26 12:07:42 +03:00
Dmytro Tretiakov bf11f076dc Merge branch 'sparkle_master' into develop. 2015-08-26 10:44:00 +03:00
Dmytro Tretiakov 38ec6273fb Use https protocol for DevMate feed URL. 2015-08-20 14:47:56 +03:00
Dmytro Tretiakov a728f9a712 Corrected code sign identity configuration. 2015-08-18 15:35:57 +03:00
Dmytro Tretiakov 19ff4dce3d Merge branch 'sparkle_master' into develop. 2015-08-17 15:29:26 +03:00
Dmytro Tretiakov e649d2f4e1 Merge branch 'sparkle_master' into develop. 2015-08-04 14:29:47 +03:00
Dmytro Tretiakov 80cb274d4c Revert "Revert "Used https:// instead of http:// protocol for dfault updates URL.""
This reverts commit e6891906ef.
2015-08-04 13:44:55 +03:00
Dmytro Tretiakov 5a1732fdd8 Updated DMCore lib to the latest version. 2015-07-17 17:53:05 +03:00
Dmytro Tretiakov fbd4272819 Updated DMCore lib to the latest version. 2015-07-17 16:20:11 +03:00
Dmytro Tretiakov e6891906ef Revert "Used https:// instead of http:// protocol for dfault updates URL."
This reverts commit af366b8b8c.
2015-07-17 16:15:59 +03:00
Dmytro Tretiakov b4b8ac9e12 Corrected build setting for XPC service target. 2015-07-14 12:16:43 +03:00
Dmytro Tretiakov 5593774b34 Merge branch 'sparkle_master' into develop. 2015-07-14 11:51:45 +03:00
Dmytro Tretiakov f343053e67 Merge branch 'sparkle_master' into develop 2015-07-10 16:45:25 +03:00
Dmytro Tretiakov 211f930059 Corrected relaunch of application that should make app active right after launch. 2015-07-10 15:42:38 +03:00
Dmytro Tretiakov 7677f2d4ac Corrected default DevMate URL for updates. Corrected static lib build config. 2015-07-09 16:32:47 +03:00
Dmytro Tretiakov e4c65a32de Merged latest changes from sparkle master. 2015-07-08 18:13:45 +03:00
Dmytro Tretiakov ef62c4ef15 Created special static lib target for DevMateKit framework. 2015-07-08 18:09:41 +03:00
Dmytro Tretiakov e3990c0e42 Added .strings file to XPC service. 2015-07-08 11:58:44 +03:00
Dmytro Tretiakov d9e9a1bcee Implemented SUUpdaterQueue class. 2015-07-07 16:19:38 +03:00
Dmytro Tretiakov 253de444e6 Added 'installationInProgress' property. 2015-07-07 13:05:05 +03:00
Dmytro Tretiakov dd3aca874b Added main delegate methods for setting up 'test' and 'beta' updates checking. 2015-07-06 18:10:21 +03:00
Dmytro Tretiakov 90f35f87dc Added sending correct DevMate update requests. 2015-07-06 17:37:21 +03:00
Dmytro Tretiakov 4149bf0103 Added XPC services to support sandboxed versions. 2015-07-06 15:50:08 +03:00
Dmytro Tretiakov af366b8b8c Used https:// instead of http:// protocol for dfault updates URL. 2015-06-25 16:02:31 +03:00
Dmytro Tretiakov 756023500c Used constants instead of macros. 2015-06-19 11:21:01 +03:00
Dmytro Tretiakov 7f6cbe4577 Made it possible to send custom http-headers to all request URLs (no just to devmate.com domain). 2015-06-03 12:25:25 +03:00
Dmytro Tretiakov c94eac3673 Corrected script for correcting locales names. 2015-04-07 18:26:31 +03:00
Dmytro Tretiakov acea9b0d1d Fixed crash when releasing semaphore in different class methods. 2015-04-05 13:28:59 +03:00
Dmytro Tretiakov 3b15ab08e1 [SUUpdaterQueue] Used dispatch_semaphore instead of running run loop. 2015-03-24 17:39:43 +02:00
Dmytro Tretiakov 02d5d44ffd Renamed XPC services with "com.devmate" prefix 2015-02-11 12:38:13 +02:00
Dmytro Tretiakov 1daba4d60f Updated DMCore lib to the latest version. 2015-01-26 16:16:36 +02:00
Dmytro Tretiakov 910f6a5966 Updated DMCore lib (Fixed problems with opening Firefox cookies database). 2014-11-07 11:51:10 +02:00
Dmytro Tretiakov 5ed577fe78 Updated DMCore lib to the latest version. 2014-11-06 18:29:57 +02:00
Dmytro Tretiakov d37bea0e67 Fixed problem with incorrect main class for static lib. 2014-10-27 16:29:28 +02:00
Dmytro Tretiakov 5ca9c2fbbe Small corrections. 2014-10-16 15:53:37 +03:00
Dmytro Tretiakov bc1dc3ebf1 Removed download XPC service from build phase of static lib. 2014-10-15 13:54:02 +03:00
Dmytro Tretiakov b9f6e9c8ae Corrected script for static lib. 2014-10-13 15:26:00 +03:00
Dmytro Tretiakov a30d745158 Corrected building resources for static lib. 2014-10-13 14:22:36 +03:00
Dmytro Tretiakov aa916f4bfe Updated SUUpdaterLoader class with new load methods. 2014-10-08 19:33:11 +03:00
Dmytro Tretiakov b820e4f288 Corrected scheme name. 2014-10-03 14:05:20 +03:00
Dmytro Tretiakov 2beaa9602c Added SUUpdater class loader for DevMateSparkle target. 2014-10-01 15:52:20 +03:00
Dmytro Tretiakov 4953a96658 Added special header for DevMateSparkle lib target. 2014-10-01 13:11:05 +03:00
Dmytro Tretiakov d47560283c Some corrections for static lib target. 2014-09-30 19:59:00 +03:00
Dmytro Tretiakov b57ca4769c Added target that creates static lib of Sparkle for DevMateKit framework. 2014-09-30 19:33:09 +03:00
Dmytro Tretiakov 01b1ce7b9c Corrected headers import section. 2014-09-30 19:32:05 +03:00
Dmytro Tretiakov 32e59c6ea4 Updated DMCore lib. 2014-09-30 19:31:07 +03:00
Dmytro Tretiakov 941a65f78f Corrected build configurations. 2014-09-18 11:50:18 +03:00
Volodymyr Radchenko bd046ab1ad Sparkle Release Notes update to version 2.1.1 2014-09-11 17:54:44 +03:00
Dmytro Tretiakov ebfb5f82b2 Corrected creating DevMate feed URL. 2014-09-11 15:46:35 +03:00
Dmytro Tretiakov 8039ce9862 Updated DMCore lib (DM-2675 From Smile: Crash on launch when there is no internet connection). Incremented version to 2.1.1. 2014-09-11 14:19:35 +03:00
Volodymyr Radchenko 26818ca11d Release notes update to version 2.1 2014-08-19 19:13:18 +03:00
Dmytro Tretiakov 1dcb87cc44 DM-2540 We need to have SUFeedURL inside Info.plist file should be optional for DevMate customer. 2014-08-19 13:17:49 +03:00
Dmytro Tretiakov 313daa4711 Removed ResourceRules file. 2014-08-12 19:02:12 +03:00
Dmytro Tretiakov 86278a2f32 Incremented framework version to 2.1. 2014-08-11 18:10:48 +03:00
Dmytro Tretiakov a91749781d Merge branch 'develop'
For ReleaseNotes: 1) Added SUUpdaterQueue class; 2) Added additional delegate methods; 3) Made it possible to check if updater is in installation process while installing with finish_installation utility.
2014-08-11 18:07:47 +03:00
Dmytro Tretiakov b52291cfc6 Finished updater queue task. 2014-08-11 17:48:38 +03:00
Dmytro Tretiakov d5d9824b6c Added additional delegate methods. 2014-08-11 17:48:00 +03:00
Dmytro Tretiakov d487361cb9 Corrected finish_install toll for case when only components install needs. 2014-08-11 17:46:32 +03:00
Dmytro Tretiakov 5e906948f3 Made it impossible to add duplicated updaters to queue. 2014-08-11 11:38:09 +03:00
Dmytro Tretiakov 48ab89338b Implemented updaters queue. 2014-08-07 16:03:02 +03:00
Dmytro Tretiakov 1c09a01ef9 Corrected method name. 2014-07-31 15:09:30 +03:00
Dmytro Tretiakov 4094dc3e83 Corrected public comments. 2014-07-31 12:00:26 +03:00
Vera Tkachenko d25e96f220 Small layout fixes. 2014-07-30 18:17:17 +03:00
Vera Tkachenko 12531b635d Fix automatic updates preference for non main bundle. Related issue: CMM-976 2014-07-30 18:09:42 +03:00
Sergey Tatarchuk bb645e9832 Safer work with NSConnection 2014-07-30 16:59:58 +03:00
Dmytro Tretiakov e24212f797 Add possibility to check update is in progress. 2014-07-30 16:59:30 +03:00
Sergey Tatarchuk 6b97e4a533 Fixed compile errors after pre commit. 2014-07-30 16:58:38 +03:00
Dmytro Tretiakov 3956a27bd0 Add ability to skip install in finish_installation tool. 2014-07-30 16:26:11 +03:00
Vera Tkachenko 8a4578fe4d Add ability to override update installation process. 2014-07-30 16:14:34 +03:00
Dmytro Tretiakov 3c7b0805e1 Corrected configs. 2014-07-30 16:09:53 +03:00
Sergey Tatarchuk d81139830e Fix crash when feedURL is nil for some reason. 2014-07-30 15:38:12 +03:00
Dmytro Tretiakov b6b704ea55 Updated release notes. 2014-07-23 18:46:24 +03:00
Dmytro Tretiakov 77fc6ca681 Incremented framework version to 2.0.1. 2014-07-22 13:14:12 +03:00
Dmytro Tretiakov 46c22e2bbf Extra follow-up for prev.rev. 2014-07-14 14:20:55 +03:00
Dmytro Tretiakov 92d7b9f68f DM-2385 [Sparkle FW] SandBox-related Updated Issues. 2014-07-14 14:08:57 +03:00
Dmytro Tretiakov 6b6b6b2405 Removed useless imports. 2014-07-14 14:05:53 +03:00
Dmytro Tretiakov b854b01e6a Made XPC-using check as functions instead of methods. 2014-07-14 14:05:13 +03:00
Dmytro Tretiakov 61e16cf276 Removed compile warnings. 2014-07-14 13:54:47 +03:00
Dmytro Tretiakov e7088fc788 Corrected release notes with proofed text. 2014-05-28 11:14:25 +03:00
Dmytro Tretiakov 54aa6f2cc2 Incremented bundle version to 2.0. Added release notes. 2014-05-27 17:09:21 +03:00
Dmytro Tretiakov acf758e485 Separate check of using XPC installer and XPC downloader. 2014-05-07 12:43:28 +03:00
Dmytro Tretiakov ceedfba634 Made it more compatible with DevMate (for correct statistics in DevMate now updater tries to download release notes even for automatic update). 2014-05-06 19:47:34 +03:00
Dmytro Tretiakov addedeac13 Removed check for min time interval before next update check. 2014-04-30 15:09:34 +03:00
Dmytro Tretiakov eedb0ff0dd Hides XPC using check to private updater API. 2014-04-30 13:40:55 +03:00
Dmytro Tretiakov 67a7bc3d62 Added custom prompt text when asking for admin rights. 2014-04-25 13:28:14 +03:00
Dmytro Tretiakov 65d7c38ab6 Added test deviate domain for sending special headers. 2014-04-24 17:43:57 +03:00
Dmytro Tretiakov 5b786043c2 DM-2131 Update sanboxed app by non-admin user. 2014-04-23 18:14:24 +03:00
Dmytro Tretiakov ca23238d59 DM-2123 Added code sign rules file to exclude headers from code signing. 2014-04-14 14:23:10 +03:00
Dmytro Tretiakov fc1870cbd2 Used defined constants instead of extern strings to add possibility to use these string values directly. 2014-03-25 11:13:00 +02:00
Dmytro Tretiakov 659aec4eaf Added codesign identity for framework. 2014-03-11 17:20:48 +02:00
Dmytro Tretiakov 88a197a7f0 Corrected build configuration to correctly generate dSYM files. 2014-02-28 14:04:15 +02:00
Dmytro Tretiakov 9119d287ab Added delegate methods that interacts with DevMate (beta updates, test mode). 2014-02-10 18:31:42 +02:00
Dmytro Tretiakov 7797a8f58c Updated DMCore lib (corrected HTTP request headers according to new documentation). 2014-02-07 19:25:33 +02:00
Dmytro Tretiakov 1f0da95e59 Updated DMCore lib. 2014-02-05 14:31:32 +02:00
Dmytro Tretiakov 84a2feb0ad Added compatibility with DevMate. 2014-01-27 12:11:14 +02:00
Dmytro Tretiakov bbe75fc6f2 Corrected releasing of xlc connection queue. 2013-10-18 18:53:26 +03:00
Dmytro Tretiakov 9c8e08b7ae Updated archive with built Sparkle framework. 2013-10-18 18:34:35 +03:00
dimaty 371c51fe5a Fixed crash under 10.9. Fixed some memory leaks. 2013-10-18 18:17:57 +03:00
dimaty feb2ad4b64 Fixed compile errors for new LLVM compiler (used in Xcode 5.0). 2013-10-18 18:07:02 +03:00
Dmytro Tretiakov 1e75acb963 Updated Sparkle version to 1.5 2013-08-20 13:24:05 +03:00
Dmytro Tretiakov b3c69f8b8c Updated product archive. 2013-08-19 17:46:47 +03:00
Dmytro Tretiakov 5cd9bdccf6 Merge branch 'sandboxing' 2013-08-19 17:40:24 +03:00
Dmytro Tretiakov 12eede4123 Updated products archive. 2013-08-07 17:01:03 +03:00
Dmytro Tretiakov 9633a57c6c Made download service callback messages with sync reply to make sure that main app receive it.
Leave some connection leaks to avoid crash while closing it.
2013-08-07 13:08:48 +03:00
Dmytro Tretiakov ab389260be Follow up for rev. [67ebc6f] 2013-08-06 18:29:54 +03:00
Dmytro Tretiakov abf70ab8dc Updated xlc services configs. 2013-08-06 16:12:35 +03:00
Dmytro Tretiakov 67ebc6ff74 Adds removing old data before downloading new one via XPC. 2013-08-06 15:16:29 +03:00
Dmytro Tretiakov 1e14f7d7b6 Corrected using of macro. 2013-08-05 17:01:31 +03:00
Dmytro Tretiakov 5bd4c1ecb6 Added sandbox check. 2013-08-05 16:53:10 +03:00
Dmytro Tretiakov 406f3da615 [Downloading XPC service] Added support of additional delegate method. 2013-08-02 17:08:56 +03:00
Dmytro Tretiakov 302eb082d6 [Installation XPC Service] Added xpc message key constants instead of hard-coded string keys. Fixed memory leaks. 2013-08-02 13:01:46 +03:00
Dmytro Tretiakov 16b75653dc Refactored download XPC service: used NSURLDownload instead of lib curl; corrected behavior of SUXPCURLDownload class to be more common with NSURLDownload. 2013-08-01 18:33:38 +03:00
Dmytro Tretiakov fc8176a229 Merged with master. 2013-07-18 18:57:51 +03:00
Vera Tkachenko 502c7fb6db Add 64-bit binary framework. 2013-06-07 19:59:50 +03:00
Vera Tkachenko 71f747aec1 Add configuration for 64bit only. 2013-06-07 19:58:01 +03:00
Erik Aderstedt aebb767cfb Cancel download no longer crashes the app. 2012-08-10 12:29:38 +02:00
Erik Aderstedt 04b1514452 Added limited support for remote release notes. Images / links / style sheets in notes won't work. 2012-08-10 12:25:16 +02:00
Erik Aderstedt 22f9c96a1f Removed additional log statements 2012-08-10 11:30:46 +02:00
Erik Aderstedt 78b08a0bee Put networking code in XPC, too. Minor compiler fixes. 2012-08-10 11:00:53 +02:00
Erik Aderstedt 6fc58a1025 Made XPC service calls asynchronous 2012-08-09 08:39:01 +02:00
Whitney Young dbd2b9b30a Added an XPC service to deal with sandboxing.
This fixes #163. It requires that you copy the XPC service into your main application bundle in
Contents/XPCServices and runs the remove from quarantine step of copying the finish_installation
app as well as launching finish_installation app outside of the sandbox. Sparkle will function
exactly as it does now for applications that do not copy the XPC service into their application
bundle.
2012-03-20 10:01:21 -05:00
223 changed files with 5402 additions and 3753 deletions

No files matched your search

-7
View File
@@ -28,13 +28,6 @@ Icon
.Spotlight-V100 .Spotlight-V100
.Trashes .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 # Directories potentially created on remote AFP share
.AppleDB .AppleDB
.AppleDesktop .AppleDesktop
+3 -1
View File
@@ -1,5 +1,7 @@
language: objective-c language: objective-c
osx_image: xcode8 osx_image: xcode7
before_install: before_install:
- brew update - brew update
- brew install macmade/tap/xcode-coveralls
script: make ci 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
+4 -55
View File
@@ -1,54 +1,3 @@
# 1.15.0
* A new icon! Thanks to 1024jp
* Show alert when an update is sent over insecure HTTP with no DSA key (Zorg)
- If you can't use HTTPS, you must at least sign updates with a DSA key.
* Improved binary delta implementation (Zorg)
* Added improved -validateMenuItem: as a method in SUUpdater.h for public use (Zorg)
* Removed reachability preflight check (Zorg)
* Clear update caches directory before downloading new update (Zorg)
* Check the bundle's parent directory for writability too (Zorg)
* Don't follow symbolic links for file operations (Zorg)
* Don't bring up an authorized dialog during cleanup (Zorg)
* Made Sparkle look for the highest compatible version regardless of timestamps (Zorg)
* Fixed compatibility with 10.7
* Fixed crash on 10.7 - subscript operator not available (kleuter)
* Fixed warnings caused by -Wpartial-availability (Zorg)
* Fixed german l10n. (Sebastian Volland)
* Error code for download errors (Kornel Lesiński)
* Update last update check date when the update driver finishes (Zorg)
* Scale app icon up if needed in Software Update window (Nicholas Riley)
* Don't register for termination notifications more than once (Zorg)
* Don't terminate the app if we're already terminating (Zorg)
* Removed SUEnableAutomaticChecksKeyOld and SUCheckAtStartup constants (Eitot)
* Updated Sparkle framework headers to use modules if modules are available (B. Kevin Hardman)
* Fixed warnings, fixed uses of SULocalizedString (Jerry Krinock)
* Improved signing verifier to take any host and s/application/bundle/ (Zorg)
* Improved Spotlight updates after delta extraction (Zorg)
# 1.14.0 (Mar 11, 2016)
* Disable javascript by default and make it opt-in (Zorg)
* URL-encoding of appcast URLs is preserved (Kornel Lesiński)
* Delegate is asked for fallback updates if delta update fails (Kornel Lesiński)
* Fixed crash on 10.7 - subscript operator not available (kleuter)
* Fixed check of feed URL before delegate had a chance to set it (Kornel Lesiński)
* Re-added support for password-protected dmg images (Andrew K. Boyd)
* Added warning about ATS blocking (Kornel Lesiński)
* Translation fixes for pt-BR. (vitu)
* Add some Japanese lozalized strings (1024jp)
* Made test app available in all languages #695 (LIU Dongyuan / 柳东原)
* Czech localizations update (Frantisek Erben)
* Removed a test resource from the framework bundle (Karl Moskowski)
* Test if the updated app is the frontmost one (Zorg)
* UI Tests for the Test Application (Zorg)
# 1.13.1 (Jan 31, 2016)
Important security fixes:
* Prevent inclusion of local files via file:// XML entities
* Disable redirects to non-HTTP URLs in release notes webview
# 1.13.0 (Dec 18, 2015) # 1.13.0 (Dec 18, 2015)
@@ -63,7 +12,7 @@ Important security fixes:
- Strong documentation, easier to read code. - Strong documentation, easier to read code.
* Automatic updates won't be installed if the system is about to shut off (Zorg) * Automatic updates won't be installed if the system is about to shut off (Zorg)
* Deprecated serving over HTTP without DSA (Zorg) * Deprecated serving over HTTP without DSA (Zorg)
- Note that Apple has deprecated insecure HTTP in macOS 10.11 - Note that Apple has deprecated insecure HTTP in OS X 10.11
* Improved Autoupdate application (Zorg) * Improved Autoupdate application (Zorg)
* Do all the installation work after the runloop is set up * Do all the installation work after the runloop is set up
* TerminationListener only does termination listening now * TerminationListener only does termination listening now
@@ -161,12 +110,12 @@ Important security fixes:
# 1.8.0 (Jul 26, 2014) # 1.8.0 (Jul 26, 2014)
* New SUDSAVerifier based on up-to-date macOS APIs (Zachary Waldowski) * New SUDSAVerifier based on up-to-date OS X APIs (Zachary Waldowski)
* Detailed error log for failed signature checks (Kornel Lesiński) * Detailed error log for failed signature checks (Kornel Lesiński)
* Converted Sparkle to ARC (C.W. Betts) * Converted Sparkle to ARC (C.W. Betts)
* Converted ivars to properties. (Jake Petroules) * Converted ivars to properties. (Jake Petroules)
* Cocoapod support (Xhacker Liu) * Cocoapod support (Xhacker Liu)
* Quarantine removal on macOS 10.10 (C.W. Betts) * Quarantine removal on OS X 10.10 (C.W. Betts)
* Updated Japanese localization (1024jp) * Updated Japanese localization (1024jp)
* Added Greek localization * Added Greek localization
@@ -187,7 +136,7 @@ Important security fixes:
# 1.7.0 # 1.7.0
* 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). * 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).
* Removed use of deprecated functions (Zachary Waldowski) * Removed use of deprecated functions (Zachary Waldowski)
* Switched to modern Obj-C runtime and new literals syntax * Switched to modern Obj-C runtime and new literals syntax
* Removed pre-10.7 code. (C.W. Betts) * Removed pre-10.7 code. (C.W. Betts)
-74
View File
@@ -1,74 +0,0 @@
# 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/
+4 -7
View File
@@ -2,7 +2,6 @@
SPARKLE_BUNDLE_IDENTIFIER = org.sparkle-project.Sparkle SPARKLE_BUNDLE_IDENTIFIER = org.sparkle-project.Sparkle
SPARKLE_RELAUNCH_TOOL_NAME = Autoupdate SPARKLE_RELAUNCH_TOOL_NAME = Autoupdate
SPARKLE_FILEOP_TOOL_NAME = fileop
SPARKLE_APPEND_VERSION_NUMBER = 1 SPARKLE_APPEND_VERSION_NUMBER = 1
@@ -16,7 +15,7 @@ SPARKLE_AUTOMATED_DOWNGRADES = 0
SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME = 0 SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME = 0
SPARKLE_VERSION_MAJOR = 1 SPARKLE_VERSION_MAJOR = 1
SPARKLE_VERSION_MINOR = 15 SPARKLE_VERSION_MINOR = 13
SPARKLE_VERSION_PATCH = 1 SPARKLE_VERSION_PATCH = 1
SPARKLE_VERSION = $(SPARKLE_VERSION_MAJOR).$(SPARKLE_VERSION_MINOR).$(SPARKLE_VERSION_PATCH) SPARKLE_VERSION = $(SPARKLE_VERSION_MAJOR).$(SPARKLE_VERSION_MINOR).$(SPARKLE_VERSION_PATCH)
@@ -32,15 +31,12 @@ MACOSX_DEPLOYMENT_TARGET = 10.7
PRODUCT_NAME = ${TARGET_NAME} PRODUCT_NAME = ${TARGET_NAME}
PRODUCT_BUNDLE_IDENTIFIER = org.sparkle-project.Sparkle.${PRODUCT_NAME:rfc1034identifier} 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)\" SPARKLE_FILEOP_TOOL_NAME=\"$(SPARKLE_FILEOP_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)\"
CLANG_ENABLE_OBJC_ARC = YES CLANG_ENABLE_OBJC_ARC = YES
GCC_ENABLE_PASCAL_STRINGS = NO GCC_ENABLE_PASCAL_STRINGS = NO
GCC_NO_COMMON_BLOCKS = YES;
COMBINE_HIDPI_IMAGES = NO;
// Enable warnings // Enable warnings
CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;
CLANG_ANALYZER_SECURITY_FLOATLOOPCOUNTER = YES CLANG_ANALYZER_SECURITY_FLOATLOOPCOUNTER = YES
CLANG_ANALYZER_SECURITY_INSECUREAPI_RAND = YES CLANG_ANALYZER_SECURITY_INSECUREAPI_RAND = YES
CLANG_ANALYZER_SECURITY_INSECUREAPI_STRCPY = YES CLANG_ANALYZER_SECURITY_INSECUREAPI_STRCPY = YES
@@ -55,6 +51,7 @@ CLANG_WARN_OBJC_EXPLICIT_OWNERSHIP_TYPE = YES
CLANG_WARN_OBJC_IMPLICIT_ATOMIC_PROPERTIES = YES CLANG_WARN_OBJC_IMPLICIT_ATOMIC_PROPERTIES = YES
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES
CLANG_WARN_OBJC_MISSING_PROPERTY_SYNTHESIS = YES CLANG_WARN_OBJC_MISSING_PROPERTY_SYNTHESIS = YES
CLANG_WARN_OBJC_RECEIVER_WEAK = YES
CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES
CLANG_WARN_SUSPICIOUS_IMPLICIT_CONVERSION = YES CLANG_WARN_SUSPICIOUS_IMPLICIT_CONVERSION = YES
CLANG_WARN_UNREACHABLE_CODE = YES CLANG_WARN_UNREACHABLE_CODE = YES
@@ -90,4 +87,4 @@ CLANG_ENABLE_MODULES[sdk=macosx10.8] = NO
WARNING_CFLAGS_EXTRA = -Wno-custom-atomic-properties -Wno-implicit-atomic-properties 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 // Turn on all warnings, then disable a few which are almost impossible to avoid
WARNING_CFLAGS = -Wall -Weverything -Wno-unused-macros -Wno-gnu-statement-expression -Wno-arc-repeated-use-of-weak -Wno-auto-import $(WARNING_CFLAGS_EXTRA) 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)
@@ -0,0 +1,4 @@
// Common
ARCHS = x86_64
VALID_ARCHS = x86_64
@@ -0,0 +1,4 @@
// Common
ARCHS = ppc i386 x86_64
-5
View File
@@ -1,5 +0,0 @@
// 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 GCC_PREPROCESSOR_DEFINITIONS = $(inherited) BUILDING_SPARKLE=1
OTHER_LDFLAGS = -Wl,-U,_NSURLQuarantinePropertiesKey OTHER_LDFLAGS = -Wl,-U,_NSURLQuarantinePropertiesKey
SKIP_INSTALL = YES SKIP_INSTALL = YES
DEFINES_MODULE = YES DEFINES_MODULE = NO
PRODUCT_BUNDLE_IDENTIFIER = ${SPARKLE_BUNDLE_IDENTIFIER} PRODUCT_BUNDLE_IDENTIFIER = ${SPARKLE_BUNDLE_IDENTIFIER}
+10
View File
@@ -0,0 +1,10 @@
// 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
@@ -0,0 +1,5 @@
#include "ConfigCommon.xcconfig"
#include "ConfigCommonDebug.xcconfig"
#include "ConfigService.xcconfig"
OTHER_CFLAGS = -DDEBUG
@@ -0,0 +1,3 @@
#include "ConfigCommon.xcconfig"
#include "ConfigCommonRelease.xcconfig"
#include "ConfigService.xcconfig"
-1
View File
@@ -1 +0,0 @@
SWIFT_VERSION = 3.0
-1
View File
@@ -1 +0,0 @@
SWIFT_OPTIMIZATION_LEVEL = -Onone
@@ -1 +0,0 @@
SWIFT_OPTIMIZATION_LEVEL = -Ofast
+1
View File
@@ -5,3 +5,4 @@ WRAPPER_EXTENSION = app
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon
LD_RUNPATH_SEARCH_PATHS = @executable_path/../Frameworks LD_RUNPATH_SEARCH_PATHS = @executable_path/../Frameworks
PRODUCT_BUNDLE_IDENTIFIER = org.sparkle-project.SparkleTestApp PRODUCT_BUNDLE_IDENTIFIER = org.sparkle-project.SparkleTestApp
GCC_PREPROCESSOR_DEFINITIONS = $(inherited) CODE_SIGN_IDENTITY="$(CODE_SIGN_IDENTITY)"
-13
View File
@@ -1,13 +0,0 @@
// 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
@@ -1,4 +0,0 @@
#include "ConfigUITest.xcconfig"
GCC_GENERATE_TEST_COVERAGE_FILES = NO
GCC_INSTRUMENT_PROGRAM_FLOW_ARCS = NO
@@ -1,2 +0,0 @@
#include "ConfigUITest.xcconfig"
#include "ConfigSwiftDebug.xcconfig"
@@ -1,2 +0,0 @@
#include "ConfigUITest.xcconfig"
#include "ConfigSwiftRelease.xcconfig"
-2
View File
@@ -1,7 +1,5 @@
// Unit Test only // Unit Test only
#include "ConfigSwift.xcconfig"
INFOPLIST_FILE = Tests/SparkleTests-Info.plist INFOPLIST_FILE = Tests/SparkleTests-Info.plist
WRAPPER_EXTENSION = xctest WRAPPER_EXTENSION = xctest
OTHER_CFLAGS = $(inherited) -iframework"$(DEVELOPER_FRAMEWORKS_DIR)" -iframework"$(PLATFORM_DIR)/Developer/Library/Frameworks" OTHER_CFLAGS = $(inherited) -iframework"$(DEVELOPER_FRAMEWORKS_DIR)" -iframework"$(PLATFORM_DIR)/Developer/Library/Frameworks"
@@ -1,2 +1 @@
#include "ConfigUnitTest.xcconfig" #include "ConfigUnitTest.xcconfig"
#include "ConfigSwiftDebug.xcconfig"
@@ -1,2 +1 @@
#include "ConfigUnitTest.xcconfig" #include "ConfigUnitTest.xcconfig"
#include "ConfigSwiftRelease.xcconfig"
-7
View File
@@ -2,13 +2,6 @@
set -e set -e
if [ "$ACTION" = "" ] ; then 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 -rf "$CONFIGURATION_BUILD_DIR/staging"
rm -f "Sparkle-$CURRENT_PROJECT_VERSION.tar.bz2" rm -f "Sparkle-$CURRENT_PROJECT_VERSION.tar.bz2"
+5 -11
View File
@@ -13,20 +13,14 @@ if [ -z "$SRCROOT" ] || \
exit 1 exit 1
fi fi
version="$CURRENT_PROJECT_VERSION" # Get the current Git master hash
version=$(cd "$SRCROOT" ; git show-ref --abbrev heads/master | awk '{print $1}')
# Get version in format 1.x.x-commits-hash if [ -z "$version" ] ; then
gitversion=$( cd "$SRCROOT"; git describe --tags --match '[12].*' || true ) echo "$0: Can't find a Git hash!" 1>&2
if [ -z "$gitversion" ] ; then
echo "$0: Can't find a Git hash!" 1>&2
exit 0 exit 0
fi fi
# remove everything before the first "-" to keep the hash part only version="$CURRENT_PROJECT_VERSION git-$version"
versionsuffix=${gitversion#*-};
if [ "$versionsuffix" != "$gitversion" ]; then
version="$version $versionsuffix"
fi
# and use it to set the CFBundleShortVersionString value # and use it to set the CFBundleShortVersionString value
export PATH="$PATH:/usr/libexec" export PATH="$PATH:/usr/libexec"
+2 -2
View File
@@ -1,6 +1,6 @@
PROJECT_NAME = Sparkle PROJECT_NAME = Sparkle
PROJECT_NUMBER = 1.14.0 PROJECT_NUMBER = 1.7.1
PROJECT_BRIEF = "A software update framework for macOS" PROJECT_BRIEF = "A software update framework for OS X"
PROJECT_LOGO = Resources/Images.xcassets/AppIcon.appiconset/icon_32x32@2x.png PROJECT_LOGO = Resources/Images.xcassets/AppIcon.appiconset/icon_32x32@2x.png
RECURSIVE = YES RECURSIVE = YES
BIN
View File
Binary file not shown.
-5
View File
@@ -13,8 +13,6 @@ localizable-strings:
release: release:
xcodebuild -scheme Distribution -configuration Release -derivedDataPath "$(BUILDDIR)" build xcodebuild -scheme Distribution -configuration Release -derivedDataPath "$(BUILDDIR)" build
open -R "$(BUILDDIR)/Build/Products/Release/Sparkle-"*.tar.bz2 open -R "$(BUILDDIR)/Build/Products/Release/Sparkle-"*.tar.bz2
cat Sparkle.podspec
@echo "Don't forget to update CocoaPods! pod trunk push"
build: build:
xcodebuild clean build xcodebuild clean build
@@ -22,9 +20,6 @@ build:
test: test:
xcodebuild -scheme Distribution -configuration Debug test xcodebuild -scheme Distribution -configuration Debug test
uitest:
xcodebuild -scheme UITests -configuration Debug test
ci: ci:
for i in {7..9} ; do \ for i in {7..9} ; do \
if xcrun --sdk "macosx10.$$i" --show-sdk-path 2> /dev/null ; then \ if xcrun --sdk "macosx10.$$i" --show-sdk-path 2> /dev/null ; then \
-24
View File
@@ -1,24 +0,0 @@
# 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)
+9 -12
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) [![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> # Sparkle [![Build Status](https://travis-ci.org/sparkle-project/Sparkle.svg?branch=master)](https://travis-ci.org/sparkle-project/Sparkle) [![Coverage Status](https://coveralls.io/repos/sparkle-project/Sparkle/badge.svg?branch=master&service=github)](https://coveralls.io/github/sparkle-project/Sparkle?branch=master) <a href="https://www.bandwidthhog.com/?utm_source=sparkle-github&amp;utm_medium=badge&amp;utm_campaign=readme"><img src="https://img.shields.io/badge/sponsored%20by-Bandwidth%20Hog-orange.svg" alt="sponsored by: bandwidth hog"></a>
An easy-to-use software update framework for Cocoa developers. An easy-to-use software update framework for Cocoa developers.
<img src="Resources/Screenshot.png" width="732" alt="Sparkle shows familiar update window with release notes"> <img src="Resources/Screenshot.png" width="715" alt="Sparkle shows familiar update window with release notes">
## Changes since 1.5b ## Changes since 1.5b
* Up-to-date with 10.11 SDK and Xcode 7. Supports macOS 10.7+. * Up-to-date with 10.11 SDK and Xcode 7. Supports OS X 10.7+.
* Important security fixes.
* Cleaned up and modernized code, using ARC and Autolayout. * 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." * 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. * Ability to mark updates as critical.
* Progress and status notifications for the host app. * Progress and status notifications for the host app.
@@ -17,15 +17,15 @@ An easy-to-use software update framework for Cocoa developers.
## Features ## 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. * True self-updating—the user can choose to automatically download and install all updates.
* Displays a detailed progress window to the user. * Displays a detailed progress window to the user.
* Supports authentication for installing in secure locations. * Supports authentication for installing in secure locations.
* Supports Apple Code Signing and DSA signatures for ultra-secure updates. * 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. * Easy to install. Sparkle requires no code in your app, so it's trivial to upgrade or remove the framework.
* Uses RSS-based appcasts for release information. Appcasts are supported by 3rd party update-tracking programs and websites. * Uses appcasts for release information. Appcasts are supported by 3rd party update-tracking programs and websites.
* Displays release notes to the user via WebKit. * Displays release notes to the user via WebKit.
* Sparkle doesn't bug the user until second launch for better first impressions. * 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. * Deep delegate support to make Sparkle work exactly as you need.
* Optionally sends system information to the server when checking for updates. * 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 bundles, preference panes, plugins, and other non-.app software. Can install .pkg files for more complicated products.
@@ -33,7 +33,7 @@ An easy-to-use software update framework for Cocoa developers.
## Requirements ## Requirements
* Runtime: macOS 10.7 or greater * Runtime: OS X 10.7 or greater
* Build: Xcode 5 and 10.8 SDK 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/)) * HTTPS server for serving updates (see [App Transport Security](http://sparkle-project.org/documentation/app-transport-security/))
@@ -48,10 +48,7 @@ If you are adding a symbol to the public API you must decorate the declaration w
Alternatively, build the Distribution scheme in the Xcode UI. 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 ## Project Sponsor
[StackPath](https://www.stackpath.com/?utm_source=sparkle-github&utm_medium=link&utm_campaign=readme-footer) [Bandwidth Hog](https://www.bandwidthhog.com/?utm_source=sparkle-github&utm_medium=link&utm_campaign=readme-footer) is a service from MaxCDN
that allows you to push software updates to your customers for only 1¢ a gigabyte. Best part is there are no contracts, it is all Pay-as-you-Go.
Binary file not shown.
@@ -43,21 +43,18 @@
"scale" : "1x" "scale" : "1x"
}, },
{ {
"size" : "256x256",
"idiom" : "mac", "idiom" : "mac",
"filename" : "icon_256x256@2x.png", "size" : "256x256",
"scale" : "2x" "scale" : "2x"
}, },
{ {
"size" : "512x512",
"idiom" : "mac", "idiom" : "mac",
"filename" : "icon_512x512.png", "size" : "512x512",
"scale" : "1x" "scale" : "1x"
}, },
{ {
"size" : "512x512",
"idiom" : "mac", "idiom" : "mac",
"filename" : "icon_512x512@2x.png", "size" : "512x512",
"scale" : "2x" "scale" : "2x"
} }
], ],
Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 46 KiB

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 827 B

After

Width:  |  Height:  |  Size: 754 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: 46 KiB

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

Before

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.

Before

Width:  |  Height:  |  Size: 130 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 368 KiB

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

Before

Width:  |  Height:  |  Size: 228 KiB

After

Width:  |  Height:  |  Size: 44 KiB

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

After

Width:  |  Height:  |  Size: 11 KiB

+5
View File
@@ -0,0 +1,5 @@
<?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>
+6 -7
View File
@@ -1,7 +1,7 @@
Pod::Spec.new do |s| Pod::Spec.new do |s|
s.name = "Sparkle" s.name = "Sparkle"
s.version = "1.15.1" s.version = "1.13.0"
s.summary = "A software update framework for macOS" s.summary = "A software update framework for OS X"
s.description = "Sparkle is an easy-to-use software update framework for Cocoa developers." s.description = "Sparkle is an easy-to-use software update framework for Cocoa developers."
s.homepage = "http://sparkle-project.org" s.homepage = "http://sparkle-project.org"
s.documentation_url = "http://sparkle-project.org/documentation/" s.documentation_url = "http://sparkle-project.org/documentation/"
@@ -11,16 +11,15 @@ Pod::Spec.new do |s|
:file => 'LICENSE' :file => 'LICENSE'
} }
s.authors = { s.authors = {
'Mayur Pawashe' => 'zorgiepoo@gmail.com',
'Kornel Lesiński' => 'pornel@pornel.net',
'Jake Petroules' => 'jake.petroules@petroules.com',
'C.W. Betts' => 'computers57@hotmail.com',
'Andy Matuschak' => 'andy@andymatuschak.org', 'Andy Matuschak' => 'andy@andymatuschak.org',
'Kornel Lesiński' => 'pornel@pornel.net',
'C.W. Betts' => 'computers57@hotmail.com',
'Jake Petroules' => 'jake.petroules@petroules.com',
'Mayur Pawashe' => 'zorgiepoo@gmail.com',
} }
s.platform = :osx, '10.7' 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 = { :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.public_header_files = 'Sparkle.framework/Versions/A/Headers/*.h'
s.vendored_frameworks = 'Sparkle.framework' s.vendored_frameworks = 'Sparkle.framework'
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,100 @@
<?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"?> <?xml version="1.0" encoding="UTF-8"?>
<Scheme <Scheme
LastUpgradeVersion = "0800" LastUpgradeVersion = "0710"
version = "1.3"> version = "1.3">
<BuildAction <BuildAction
parallelizeBuildables = "YES" parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<Scheme <Scheme
LastUpgradeVersion = "0800" LastUpgradeVersion = "0710"
version = "2.0"> version = "2.0">
<BuildAction <BuildAction
parallelizeBuildables = "YES" parallelizeBuildables = "YES"
@@ -1,56 +0,0 @@
<?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,7 +28,5 @@
<string>MainMenu</string> <string>MainMenu</string>
<key>NSPrincipalClass</key> <key>NSPrincipalClass</key>
<string>NSApplication</string> <string>NSApplication</string>
<key>CFBundleIconFile</key>
<string>${ASSETCATALOG_COMPILER_APPICON_NAME}.icns</string>
</dict> </dict>
</plist> </plist>
+22 -22
View File
@@ -166,28 +166,18 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.5;
[self.statusController showWindow:self]; [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 [SUInstaller installFromUpdateFolder:self.updateFolderPath
overHost:host overHost:host
installationPath:installationPath installationPath:installationPath
fileOperationToolPath:fileOperationToolPath
versionComparator:[SUStandardVersionComparator defaultComparator] versionComparator:[SUStandardVersionComparator defaultComparator]
completionHandler:^(NSError *error) { completionHandler:^(NSError *error) {
if (error) { if (error) {
NSError *underlyingError = [error.userInfo objectForKey:NSUnderlyingErrorKey]; SULog(@"Installation Error: %@", error);
if (underlyingError == nil || underlyingError.code != SUInstallationCancelledError) { if (self.shouldShowUI) {
SULog(@"Installation Error: %@", error); NSAlert *alert = [[NSAlert alloc] init];
if (self.shouldShowUI) { alert.messageText = @"";
NSAlert *alert = [[NSAlert alloc] init]; alert.informativeText = [NSString stringWithFormat:@"%@", [error localizedDescription]];
alert.messageText = @""; [alert runModal];
alert.informativeText = [NSString stringWithFormat:@"%@", [error localizedDescription]];
[alert runModal];
}
} }
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} else { } else {
@@ -257,19 +247,29 @@ int main(int __unused argc, const char __unused *argv[])
NSApplication *application = [NSApplication sharedApplication]; NSApplication *application = [NSApplication sharedApplication];
BOOL shouldShowUI = (args.count > 6) ? [[args objectAtIndex:6] boolValue] : YES; BOOL shouldShowUI = (args.count > 6) ? [args[6] boolValue] : YES;
if (shouldShowUI) { if (shouldShowUI) {
[application activateIgnoringOtherApps:YES]; [application activateIgnoringOtherApps:YES];
} }
AppInstaller *appInstaller = [[AppInstaller alloc] initWithHostPath:[args objectAtIndex:1] AppInstaller *appInstaller = [[AppInstaller alloc] initWithHostPath:args[1]
relaunchPath:[args objectAtIndex:2] relaunchPath:args[2]
parentProcessId:[[args objectAtIndex:3] intValue] parentProcessId:[args[3] intValue]
updateFolderPath:[args objectAtIndex:4] updateFolderPath:args[4]
shouldRelaunch:(args.count > 5) ? [[args objectAtIndex:5] boolValue] : YES shouldRelaunch:(args.count > 5) ? [args[5] boolValue] : YES
shouldShowUI:shouldShowUI]; 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 setDelegate:appInstaller];
[application run]; [application run];
// Ensure connection is not deallocated by ARC before caling -[NSApplication run]
[connection class];
} }
return EXIT_SUCCESS; return EXIT_SUCCESS;
+10 -10
View File
@@ -3,7 +3,7 @@
import Foundation import Foundation
func die(msg: String) { func die(msg: String) {
print("ERROR: \(msg)") println("ERROR: \(msg)")
exit(1) exit(1)
} }
@@ -28,8 +28,8 @@ if enStringsDict == nil {
} }
let enStringsDictKeys = enStringsDict!.allKeys let enStringsDictKeys = enStringsDict!.allKeys
let dirPath = NSString(string: sparkleRoot! + "/Sparkle") let dirPath = sparkleRoot! + "/Sparkle"
let dirContents = try! NSFileManager.defaultManager().contentsOfDirectoryAtPath(dirPath as String) let dirContents = NSFileManager.defaultManager().contentsOfDirectoryAtPath(dirPath, error: nil) as! [String]
let css = let css =
"body { font-family: sans-serif; font-size: 10pt; }" + "body { font-family: sans-serif; font-size: 10pt; }" +
"h1 { font-size: 12pt; }" + "h1 { font-size: 12pt; }" +
@@ -51,14 +51,14 @@ head.addChild(NSXMLElement(name: "style", stringValue: css))
let locale = NSLocale.currentLocale() let locale = NSLocale.currentLocale()
for dirEntry in dirContents { for dirEntry in dirContents {
if NSString(string: dirEntry).pathExtension != "lproj" || dirEntry == "en.lproj" { if dirEntry.pathExtension != "lproj" || dirEntry == "en.lproj" {
continue continue
} }
let lang = locale.displayNameForKey(NSLocaleLanguageCode, value: NSString(string: dirEntry).stringByDeletingPathExtension) let lang = locale.displayNameForKey(NSLocaleLanguageCode, value: dirEntry.stringByDeletingPathExtension)
body.addChild(NSXMLElement(name: "h1", stringValue: "\(dirEntry) (\(lang!))")) body.addChild(NSXMLElement(name: "h1", stringValue: "\(dirEntry) (\(lang!))"))
let stringsPath = NSString(string: dirPath.stringByAppendingPathComponent(dirEntry)).stringByAppendingPathComponent("Sparkle.strings") let stringsPath = dirPath.stringByAppendingPathComponent(dirEntry).stringByAppendingPathComponent("Sparkle.strings")
let stringsDict = NSDictionary(contentsOfFile: stringsPath) let stringsDict = NSDictionary(contentsOfFile: stringsPath)
if stringsDict == nil { if stringsDict == nil {
die("Invalid strings file \(dirEntry)") die("Invalid strings file \(dirEntry)")
@@ -90,12 +90,12 @@ for dirEntry in dirContents {
let sorter = { (s1: String, s2: String) -> Bool in let sorter = { (s1: String, s2: String) -> Bool in
return s1 < s2 return s1 < s2
} }
missing.sortInPlace(sorter) missing.sort(sorter)
unlocalized.sortInPlace(sorter) unlocalized.sort(sorter)
unused.sortInPlace(sorter) unused.sort(sorter)
let addRow = { (prefix: String, cssClass: String, key: String) -> Void in let addRow = { (prefix: String, cssClass: String, key: String) -> Void in
body.addChild(NSXMLElement(name: "span", attributes: ["class": cssClass], stringValue: [prefix, key].joinWithSeparator(" ") + "\n")) body.addChild(NSXMLElement(name: "span", attributes: ["class": cssClass], stringValue: " ".join([prefix, key]) + "\n"))
} }
for key in missing { for key in missing {
+40
View File
@@ -0,0 +1,40 @@
//
// 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
@@ -0,0 +1,50 @@
//
// 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"
@@ -3,22 +3,29 @@
<plist version="1.0"> <plist version="1.0">
<dict> <dict>
<key>CFBundleDevelopmentRegion</key> <key>CFBundleDevelopmentRegion</key>
<string>en</string> <string>English</string>
<key>CFBundleExecutable</key> <key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string> <string>${EXECUTABLE_NAME}</string>
<key>CFBundleIdentifier</key> <key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string> <string>${EXECUTABLE_NAME}</string>
<key>CFBundleInfoDictionaryVersion</key> <key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string> <string>6.0</string>
<key>CFBundleName</key> <key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string> <string>${PRODUCT_NAME}</string>
<key>CFBundlePackageType</key> <key>CFBundlePackageType</key>
<string>BNDL</string> <string>XPC!</string>
<key>CFBundleShortVersionString</key> <key>CFBundleShortVersionString</key>
<string>1.0</string> <string>1.0</string>
<key>CFBundleSignature</key> <key>CFBundleSignature</key>
<string>????</string> <string>????</string>
<key>CFBundleVersion</key> <key>CFBundleVersion</key>
<string>1</string> <string>1</string>
<key>XPCService</key>
<dict>
<key>ServiceType</key>
<string>Application</string>
<key>JoinExistingSession</key>
<true/>
</dict>
</dict> </dict>
</plist> </plist>
@@ -0,0 +1,4 @@
//
// Prefix header for all source files of the 'Downloading XPC Service' target in the 'Downloading XPC Service' project
//
+60
View File
@@ -0,0 +1,60 @@
//
// 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
@@ -0,0 +1,210 @@
//
// 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
@@ -0,0 +1,29 @@
//
// 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
@@ -0,0 +1,36 @@
//
// 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
@@ -0,0 +1,448 @@
//
// 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
@@ -0,0 +1,265 @@
//
// 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);
}
@@ -0,0 +1,2 @@
/* Localized versions of Info.plist keys */
@@ -0,0 +1,40 @@
//
// 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,
SUInstallServiceTaskAuthReleaseFromQuarantine = 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 * SUInslallServiceAllowsAuthKey = "allows_authorization"; // 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
@@ -0,0 +1,30 @@
//
// 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)releaseItemFromQuarantineAtRootURL:(NSURL *)rootURL allowsAuthorization:(BOOL)flag error:(NSError *__autoreleasing *)error;
+ (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);
+273
View File
@@ -0,0 +1,273 @@
//
// 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)releaseItemFromQuarantineAtRootURL:(NSURL *)rootURL allowsAuthorization:(BOOL)flag 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)SUInstallServiceTaskAuthReleaseFromQuarantine);
if (rootURL)
xpc_dictionary_set_string(message, SUInstallServiceSourcePathKey, rootURL.path.fileSystemRepresentation);
xpc_dictionary_set_bool(message, SUInslallServiceAllowsAuthKey, flag ? 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 = @{NSLocalizedDescriptionKey : @"Internal XPC error."};
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 = @{NSLocalizedDescriptionKey : errorStr ? errorStr : @""};
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
@@ -0,0 +1,31 @@
<?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
@@ -0,0 +1,374 @@
//
// 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 "SUFileManager.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 SUISReleaseFromQuarantineWithAuthentication(xpc_object_t message)
{
if (NULL == message)
return NULL;
const char *src = xpc_dictionary_get_string(message, SUInstallServiceSourcePathKey);
bool allowsAuth = xpc_dictionary_get_bool(message, SUInslallServiceAllowsAuthKey);
NSFileManager *manager = [NSFileManager defaultManager];
NSString *sourcePath = src ? [manager stringWithFileSystemRepresentation:src length:strlen(src)] : nil;
NSURL *sourceURL = sourcePath ? [NSURL fileURLWithPath:sourcePath] : nil;
SUFileManager *fileManager = [SUFileManager fileManagerAllowingAuthorization:allowsAuth];
NSError *error = nil;
BOOL result = [fileManager releaseItemFromQuarantineAtRootURL:sourceURL 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 SUInstallServiceTaskAuthReleaseFromQuarantine:
{
reply = SUISReleaseFromQuarantineWithAuthentication(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
@@ -0,0 +1,10 @@
//
// install_service.pch
// Sparkle
//
// Created by Dmytro Tretiakov on 4/25/14.
//
//
#import "Sparkle.pch"
#import "SULog.h"
-4
View File
@@ -9,11 +9,7 @@
#ifndef SUAPPCAST_H #ifndef SUAPPCAST_H
#define SUAPPCAST_H #define SUAPPCAST_H
#if __has_feature(modules)
@import Foundation;
#else
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>
#endif
#import "SUExport.h" #import "SUExport.h"
@class SUAppcastItem; @class SUAppcastItem;
+136 -162
View File
@@ -30,10 +30,7 @@
if (!attrName) { if (!attrName) {
continue; continue;
} }
NSString *attributeStringValue = [attribute stringValue]; dictionary[attrName] = [attribute stringValue];
if (attributeStringValue != nil) {
[dictionary setObject:attributeStringValue forKey:attrName];
}
} }
return dictionary; return dictionary;
} }
@@ -96,166 +93,147 @@
- (void)downloadDidFinish:(NSURLDownload *)__unused aDownload - (void)downloadDidFinish:(NSURLDownload *)__unused aDownload
{ {
NSError *error = nil; NSError *error = nil;
NSArray *appcastItems = [self parseAppcastItemsFromXMLFile:[NSURL fileURLWithPath:self.downloadFilename] error:&error];
[[NSFileManager defaultManager] removeItemAtPath:self.downloadFilename error:nil];
self.downloadFilename = nil;
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]];
}
}
- (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;
}
-(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
}
}
-(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;
}
NSXMLDocument *document = nil;
BOOL failed = NO;
NSArray *xmlItems = nil;
NSMutableArray *appcastItems = [NSMutableArray array]; NSMutableArray *appcastItems = [NSMutableArray array];
NSEnumerator *nodeEnum = [xmlItems objectEnumerator];
NSXMLNode *node;
while((node = [nodeEnum nextObject])) { if (self.downloadFilename)
{
NSUInteger options = 0;
options = NSXMLNodeLoadExternalEntitiesNever; // Prevent inclusion from file://
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 (nil == document)
{
failed = YES;
}
else
{
xmlItems = [document nodesForXPath:@"/rss/channel/item" error:&error];
if (nil == xmlItems)
{
failed = YES;
}
}
if (failed == NO)
{
NSEnumerator *nodeEnum = [xmlItems objectEnumerator];
NSXMLNode *node;
NSMutableDictionary *nodesDict = [NSMutableDictionary dictionary]; NSMutableDictionary *nodesDict = [NSMutableDictionary dictionary];
NSMutableDictionary *dict = [NSMutableDictionary dictionary]; NSMutableDictionary *dict = [NSMutableDictionary dictionary];
// First, we'll "index" all the first-level children of this appcast item so we can pick them out by language later. while (failed == NO && (node = [nodeEnum nextObject]))
if ([[node children] count]) { {
node = [node childAtIndex:0]; // First, we'll "index" all the first-level children of this appcast item so we can pick them out by language later.
while (nil != node) { if ([[node children] count])
NSString *name = [self sparkleNamespacedNameOfNode:node]; {
if (name) { node = [node childAtIndex:0];
NSMutableArray *nodes = [nodesDict objectForKey:name]; while (nil != node)
if (nodes == nil) { {
nodes = [NSMutableArray array]; NSString *name = [node name];
[nodesDict setObject:nodes forKey:name]; if (name)
{
NSMutableArray *nodes = nodesDict[name];
if (nodes == nil)
{
nodes = [NSMutableArray array];
nodesDict[name] = nodes;
}
[nodes addObject:node];
} }
[nodes addObject:node]; node = [node nextSibling];
} }
node = [node nextSibling];
} }
}
for (NSString *name in nodesDict) { for (NSString *name in nodesDict)
node = [self bestNodeInNodes:[nodesDict objectForKey:name]]; {
if ([name isEqualToString:SURSSElementEnclosure]) { node = [self bestNodeInNodes:nodesDict[name]];
// enclosure is flattened as a separate dictionary for some reason if ([name isEqualToString:SURSSElementEnclosure])
NSDictionary *encDict = [self attributesOfNode:(NSXMLElement *)node]; {
[dict setObject:encDict forKey:name]; // enclosure is flattened as a separate dictionary for some reason
} NSDictionary *encDict = [(NSXMLElement *)node attributesAsDictionary];
else if ([name isEqualToString:SURSSElementPubDate]) { dict[name] = encDict;
// 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];
}
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]; else if ([name isEqualToString:SURSSElementPubDate])
if (anItem) { {
[appcastItems addObject:anItem]; // pubDate is expected to be an NSDate by SUAppcastItem, but the RSS class was returning an NSString
} NSString *string = node.stringValue;
else { if (string) {
SULog(@"Sparkle Updater: Failed to parse appcast item: %@.\nAppcast dictionary was: %@", errString, dict); NSDate *date = [NSDate dateWithNaturalLanguageString:string];
if (errorp) *errorp = [NSError errorWithDomain:SUSparkleErrorDomain if (date)
code:SUAppcastParseError dict[name] = date;
userInfo:@{NSLocalizedDescriptionKey: errString}]; }
return nil; }
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];
}
else
{
SULog(@"Sparkle Updater: Failed to parse appcast item: %@.\nAppcast dictionary was: %@", errString, dict);
}
[nodesDict removeAllObjects];
[dict removeAllObjects];
} }
} }
self.items = appcastItems;
return 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;
}
} }
- (void)download:(NSURLDownload *)__unused aDownload didFailWithError:(NSError *)error - (void)download:(NSURLDownload *)__unused aDownload didFailWithError:(NSError *)error
@@ -275,18 +253,14 @@
- (void)reportError:(NSError *)error - (void)reportError:(NSError *)error
{ {
NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:@{ NSURL *failingUrl = error.userInfo[NSURLErrorFailingURLErrorKey];
self.completionBlock([NSError errorWithDomain:SUSparkleErrorDomain code:SUAppcastError userInfo:@{
NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred in retrieving update information. Please try again later.", nil), NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred in retrieving update information. Please try again later.", nil),
NSLocalizedFailureReasonErrorKey: [error localizedDescription], NSLocalizedFailureReasonErrorKey: [error localizedDescription],
NSUnderlyingErrorKey: error, 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; self.completionBlock = nil;
} }
@@ -294,7 +268,7 @@
{ {
// We use this method to pick out the localized version of a node when one's available. // We use this method to pick out the localized version of a node when one's available.
if ([nodes count] == 1) if ([nodes count] == 1)
return [nodes objectAtIndex:0]; return nodes[0];
else if ([nodes count] == 0) else if ([nodes count] == 0)
return nil; return nil;
@@ -305,12 +279,12 @@
lang = [[node attributeForName:@"xml:lang"] stringValue]; lang = [[node attributeForName:@"xml:lang"] stringValue];
[languages addObject:(lang ? lang : @"")]; [languages addObject:(lang ? lang : @"")];
} }
lang = [[NSBundle preferredLocalizationsFromArray:languages] objectAtIndex:0]; lang = [NSBundle preferredLocalizationsFromArray:languages][0];
i = [languages indexOfObject:([languages containsObject:lang] ? lang : @"")]; i = [languages indexOfObject:([languages containsObject:lang] ? lang : @"")];
if (i == NSNotFound) { if (i == NSNotFound) {
i = 0; i = 0;
} }
return [nodes objectAtIndex:i]; return nodes[i];
} }
- (SUAppcast *)copyWithoutDeltaUpdates { - (SUAppcast *)copyWithoutDeltaUpdates {
+1 -5
View File
@@ -9,16 +9,12 @@
#ifndef SUAPPCASTITEM_H #ifndef SUAPPCASTITEM_H
#define SUAPPCASTITEM_H #define SUAPPCASTITEM_H
#if __has_feature(modules)
@import Foundation;
#else
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>
#endif
#import "SUExport.h" #import "SUExport.h"
SU_EXPORT @interface SUAppcastItem : NSObject SU_EXPORT @interface SUAppcastItem : NSObject
@property (copy, readonly) NSString *title; @property (copy, readonly) NSString *title;
@property (copy, readonly) NSString *dateString; @property (copy, readonly) NSDate *date;
@property (copy, readonly) NSString *itemDescription; @property (copy, readonly) NSString *itemDescription;
@property (strong, readonly) NSURL *releaseNotesURL; @property (strong, readonly) NSURL *releaseNotesURL;
@property (copy, readonly) NSString *DSASignature; @property (copy, readonly) NSString *DSASignature;
+24 -25
View File
@@ -16,7 +16,7 @@
@interface SUAppcastItem () @interface SUAppcastItem ()
@property (copy, readwrite) NSString *title; @property (copy, readwrite) NSString *title;
@property (copy, readwrite) NSString *dateString; @property (copy, readwrite) NSDate *date;
@property (copy, readwrite) NSString *itemDescription; @property (copy, readwrite) NSString *itemDescription;
@property (strong, readwrite) NSURL *releaseNotesURL; @property (strong, readwrite) NSURL *releaseNotesURL;
@property (copy, readwrite) NSString *DSASignature; @property (copy, readwrite) NSString *DSASignature;
@@ -31,7 +31,7 @@
@end @end
@implementation SUAppcastItem @implementation SUAppcastItem
@synthesize dateString; @synthesize date;
@synthesize deltaUpdates; @synthesize deltaUpdates;
@synthesize displayVersionString; @synthesize displayVersionString;
@synthesize DSASignature; @synthesize DSASignature;
@@ -47,13 +47,12 @@
- (BOOL)isDeltaUpdate - (BOOL)isDeltaUpdate
{ {
NSDictionary *rssElementEnclosure = [self.propertiesDictionary objectForKey:SURSSElementEnclosure]; return self.propertiesDictionary[SURSSElementEnclosure][SUAppcastAttributeDeltaFrom] != nil;
return [rssElementEnclosure objectForKey:SUAppcastAttributeDeltaFrom] != nil;
} }
- (BOOL)isCriticalUpdate - (BOOL)isCriticalUpdate
{ {
return [[self.propertiesDictionary objectForKey:SUAppcastElementTags] containsObject:SUAppcastElementCriticalUpdate]; return [self.propertiesDictionary[SUAppcastElementTags] containsObject:SUAppcastElementCriticalUpdate];
} }
- (BOOL)isInformationOnlyUpdate - (BOOL)isInformationOnlyUpdate
@@ -70,7 +69,7 @@
{ {
self = [super init]; self = [super init];
if (self) { if (self) {
NSDictionary *enclosure = [dict objectForKey:SURSSElementEnclosure]; id enclosure = dict[SURSSElementEnclosure];
// Try to find a version string. // Try to find a version string.
// Finding the new version number from the RSS feed is a little bit hacky. There are two ways: // Finding the new version number from the RSS feed is a little bit hacky. There are two ways:
@@ -80,17 +79,17 @@
// underscore and the last period as the version number. So name your packages like this: APPNAME_VERSION.extension. // 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. // 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. // Feel free to change the separator string to a hyphen or something more suited to your needs if you like.
NSString *newVersion = [enclosure objectForKey:SUAppcastAttributeVersion]; NSString *newVersion = enclosure[SUAppcastAttributeVersion];
if (newVersion == nil) { if (newVersion == nil) {
newVersion = [dict objectForKey:SUAppcastAttributeVersion]; // Get version from the item, in case it's a download-less item (i.e. paid upgrade). newVersion = dict[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? 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 objectForKey:SURSSAttributeURL], SUAppcastAttributeVersion, SUAppcastAttributeVersion); SULog(@"warning: <%@> for URL '%@' is missing %@ attribute. Version comparison may be unreliable. Please always specify %@", SURSSElementEnclosure, enclosure[SURSSAttributeURL], SUAppcastAttributeVersion, SUAppcastAttributeVersion);
// Separate the url by underscores and take the last component, as that'll be closest to the end, // 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. // then we remove the extension. Hopefully, this will be the version.
NSArray *fileComponents = [[enclosure objectForKey:SURSSAttributeURL] componentsSeparatedByString:@"_"]; NSArray *fileComponents = [enclosure[SURSSAttributeURL] componentsSeparatedByString:@"_"];
if ([fileComponents count] > 1) { if ([fileComponents count] > 1) {
newVersion = [[fileComponents lastObject] stringByDeletingPathExtension]; newVersion = [[fileComponents lastObject] stringByDeletingPathExtension];
} }
@@ -104,11 +103,11 @@
} }
propertiesDictionary = [[NSMutableDictionary alloc] initWithDictionary:dict]; propertiesDictionary = [[NSMutableDictionary alloc] initWithDictionary:dict];
self.title = [dict objectForKey:SURSSElementTitle]; self.title = dict[SURSSElementTitle];
self.dateString = [dict objectForKey:SURSSElementPubDate]; self.date = dict[SURSSElementPubDate];
self.itemDescription = [dict objectForKey:SURSSElementDescription]; self.itemDescription = dict[SURSSElementDescription];
NSString *theInfoURL = [dict objectForKey:SURSSElementLink]; NSString *theInfoURL = dict[SURSSElementLink];
if (theInfoURL) { if (theInfoURL) {
if (![theInfoURL isKindOfClass:[NSString class]]) { if (![theInfoURL isKindOfClass:[NSString class]]) {
SULog(@"%@ -%@ Info URL is not of valid type.", NSStringFromClass([self class]), NSStringFromSelector(_cmd)); SULog(@"%@ -%@ Info URL is not of valid type.", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
@@ -126,7 +125,7 @@
return nil; return nil;
} }
NSString *enclosureURLString = [enclosure objectForKey:SURSSAttributeURL]; NSString *enclosureURLString = enclosure[SURSSAttributeURL];
if (!enclosureURLString && !theInfoURL) { if (!enclosureURLString && !theInfoURL) {
if (error) { if (error) {
*error = @"Feed item's enclosure lacks URL"; *error = @"Feed item's enclosure lacks URL";
@@ -140,16 +139,16 @@
self.fileURL = [NSURL URLWithString:fileURLString]; self.fileURL = [NSURL URLWithString:fileURLString];
} }
if (enclosure) { if (enclosure) {
self.DSASignature = [enclosure objectForKey:SUAppcastAttributeDSASignature]; self.DSASignature = enclosure[SUAppcastAttributeDSASignature];
} }
self.versionString = newVersion; self.versionString = newVersion;
self.minimumSystemVersion = [dict objectForKey:SUAppcastElementMinimumSystemVersion]; self.minimumSystemVersion = dict[SUAppcastElementMinimumSystemVersion];
self.maximumSystemVersion = [dict objectForKey:SUAppcastElementMaximumSystemVersion]; self.maximumSystemVersion = dict[SUAppcastElementMaximumSystemVersion];
NSString *shortVersionString = [enclosure objectForKey:SUAppcastAttributeShortVersionString]; NSString *shortVersionString = enclosure[SUAppcastAttributeShortVersionString];
if (nil == shortVersionString) { if (nil == shortVersionString) {
shortVersionString = [dict objectForKey:SUAppcastAttributeShortVersionString]; // fall back on the <item> shortVersionString = dict[SUAppcastAttributeShortVersionString]; // fall back on the <item>
} }
if (shortVersionString) { if (shortVersionString) {
@@ -159,7 +158,7 @@
} }
// Find the appropriate release notes URL. // Find the appropriate release notes URL.
NSString *releaseNotesString = [dict objectForKey:SUAppcastElementReleaseNotesLink]; NSString *releaseNotesString = dict[SUAppcastElementReleaseNotesLink];
if (releaseNotesString) { if (releaseNotesString) {
NSURL *url = [NSURL URLWithString:releaseNotesString]; NSURL *url = [NSURL URLWithString:releaseNotesString];
if ([url isFileURL]) { if ([url isFileURL]) {
@@ -173,19 +172,19 @@
self.releaseNotesURL = nil; self.releaseNotesURL = nil;
} }
NSArray *deltaDictionaries = [dict objectForKey:SUAppcastElementDeltas]; NSArray *deltaDictionaries = dict[SUAppcastElementDeltas];
if (deltaDictionaries) { if (deltaDictionaries) {
NSMutableDictionary *deltas = [NSMutableDictionary dictionary]; NSMutableDictionary *deltas = [NSMutableDictionary dictionary];
for (NSDictionary *deltaDictionary in deltaDictionaries) { for (NSDictionary *deltaDictionary in deltaDictionaries) {
NSString *deltaFrom = [deltaDictionary objectForKey:SUAppcastAttributeDeltaFrom]; NSString *deltaFrom = deltaDictionary[SUAppcastAttributeDeltaFrom];
if (!deltaFrom) continue; if (!deltaFrom) continue;
NSMutableDictionary *fakeAppCastDict = [dict mutableCopy]; NSMutableDictionary *fakeAppCastDict = [dict mutableCopy];
[fakeAppCastDict removeObjectForKey:SUAppcastElementDeltas]; [fakeAppCastDict removeObjectForKey:SUAppcastElementDeltas];
[fakeAppCastDict setObject:deltaDictionary forKey:SURSSElementEnclosure]; fakeAppCastDict[SURSSElementEnclosure] = deltaDictionary;
SUAppcastItem *deltaItem = [[SUAppcastItem alloc] initWithDictionary:fakeAppCastDict]; SUAppcastItem *deltaItem = [[SUAppcastItem alloc] initWithDictionary:fakeAppCastDict];
[deltas setObject:deltaItem forKey:deltaFrom]; deltas[deltaFrom] = deltaItem;
} }
self.deltaUpdates = deltas; self.deltaUpdates = deltas;
} }
+36 -21
View File
@@ -26,7 +26,6 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
@property (assign) BOOL postponingInstallation; @property (assign) BOOL postponingInstallation;
@property (assign) BOOL showErrors; @property (assign) BOOL showErrors;
@property (assign) BOOL willUpdateOnTermination; @property (assign) BOOL willUpdateOnTermination;
@property (assign) BOOL isTerminating;
@property (strong) SUAutomaticUpdateAlert *alert; @property (strong) SUAutomaticUpdateAlert *alert;
@property (strong) NSTimer *showUpdateAlertTimer; @property (strong) NSTimer *showUpdateAlertTimer;
@@ -37,10 +36,14 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
@synthesize postponingInstallation; @synthesize postponingInstallation;
@synthesize showErrors; @synthesize showErrors;
@synthesize willUpdateOnTermination; @synthesize willUpdateOnTermination;
@synthesize isTerminating;
@synthesize alert; @synthesize alert;
@synthesize showUpdateAlertTimer; @synthesize showUpdateAlertTimer;
- (BOOL)shouldShowUI
{
return self.showErrors;
}
- (void)showUpdateAlert - (void)showUpdateAlert
{ {
self.interruptible = NO; self.interruptible = NO;
@@ -62,6 +65,31 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:) name:NSApplicationDidBecomeActiveNotification object:NSApp]; [[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 - (void)unarchiverDidFinish:(SUUnarchiver *)__unused ua
{ {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:) name:NSApplicationWillTerminateNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:) name:NSApplicationWillTerminateNotification object:nil];
@@ -131,12 +159,11 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
[self invalidateShowUpdateAlertTimer]; [self invalidateShowUpdateAlertTimer];
} }
- (void)abortUpdate - (void)abortUpdate:(SUUpdateAbortReason)reason
{ {
self.isTerminating = NO;
[self stopUpdatingOnTermination]; [self stopUpdatingOnTermination];
[self invalidateShowUpdateAlertTimer]; [self invalidateShowUpdateAlertTimer];
[super abortUpdate]; [super abortUpdate:reason];
} }
- (void)applicationDidBecomeActive:(NSNotification *)__unused aNotification - (void)applicationDidBecomeActive:(NSNotification *)__unused aNotification
@@ -156,18 +183,19 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
case SUInstallLaterChoice: case SUInstallLaterChoice:
self.postponingInstallation = YES; self.postponingInstallation = YES;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:) name:NSApplicationWillTerminateNotification object:nil];
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(systemWillPowerOff:) name:NSWorkspaceWillPowerOffNotification object:nil];
// We're already waiting on quit, just indicate that we're idle. // We're already waiting on quit, just indicate that we're idle.
self.interruptible = YES; self.interruptible = YES;
break; break;
case SUDoNotInstallChoice: case SUDoNotInstallChoice:
[self.host setObject:[self.updateItem versionString] forUserDefaultsKey:SUSkippedVersionKey]; [self.host setObject:[self.updateItem versionString] forUserDefaultsKey:SUSkippedVersionKey];
[self abortUpdate]; [self abortUpdate:SUUpdateAbortCanceledByUser];
break; break;
} }
} }
- (void)installWithToolAndRelaunch:(BOOL)relaunch displayingUserInterface:(BOOL)showUI - (void)installWithToolAndRelaunch:(BOOL)relaunch displayingUserInterface:(BOOL)showUI
{ {
if (relaunch) { if (relaunch) {
@@ -187,22 +215,9 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
- (void)applicationWillTerminate:(NSNotification *)__unused note - (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]; [self installWithToolAndRelaunch:NO];
} }
- (void)terminateApp
{
if (!self.isTerminating) {
[super terminateApp];
}
}
- (void)abortUpdateWithError:(NSError *)error - (void)abortUpdateWithError:(NSError *)error
{ {
if (self.showErrors) { if (self.showErrors) {
@@ -215,7 +230,7 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
[updaterDelegate updater:self.updater didAbortWithError:error]; [updaterDelegate updater:self.updater didAbortWithError:error];
} }
[self abortUpdate]; [self abortUpdate:SUUpdateAbortGotError];
} }
} }
+3 -2
View File
@@ -24,13 +24,14 @@
- (void)checkForUpdatesAtURL:(NSURL *)URL host:(SUHost *)host; - (void)checkForUpdatesAtURL:(NSURL *)URL host:(SUHost *)host;
- (BOOL)isItemNewer:(SUAppcastItem *)ui; - (BOOL)isItemNewer:(SUAppcastItem *)ui;
+ (BOOL)hostSupportsItem:(SUAppcastItem *)ui; - (BOOL)hostSupportsItem:(SUAppcastItem *)ui;
- (BOOL)itemContainsSkippedVersion:(SUAppcastItem *)ui; - (BOOL)itemContainsSkippedVersion:(SUAppcastItem *)ui;
- (BOOL)itemContainsValidUpdate:(SUAppcastItem *)ui; - (BOOL)itemContainsValidUpdate:(SUAppcastItem *)ui;
- (void)appcastDidFinishLoading:(SUAppcast *)ac; - (void)appcastDidFinishLoading:(SUAppcast *)ac;
- (void)didFindValidUpdate; - (void)didFindValidUpdate;
- (void)didNotFindUpdate; - (void)didNotFindUpdate;
- (void)updateURLRequestHTTPHeaders:(NSMutableURLRequest *)request;
- (void)downloadUpdate; - (void)downloadUpdate;
- (void)download:(NSURLDownload *)d decideDestinationWithSuggestedFilename:(NSString *)name; - (void)download:(NSURLDownload *)d decideDestinationWithSuggestedFilename:(NSString *)name;
- (void)downloadDidFinish:(NSURLDownload *)d; - (void)downloadDidFinish:(NSURLDownload *)d;
@@ -47,7 +48,7 @@
- (void)cleanUpDownload; - (void)cleanUpDownload;
- (void)abortUpdate; - (void)abortUpdate:(SUUpdateAbortReason)reason;
- (void)abortUpdateWithError:(NSError *)error; - (void)abortUpdateWithError:(NSError *)error;
- (void)terminateApp; - (void)terminateApp;
+193 -148
View File
@@ -10,14 +10,19 @@
#import "SUHost.h" #import "SUHost.h"
#import "SUOperatingSystem.h" #import "SUOperatingSystem.h"
#import "SUDSAVerifier.h"
#import "SUInstaller.h"
#import "SUStandardVersionComparator.h" #import "SUStandardVersionComparator.h"
#import "SUUnarchiver.h" #import "SUUnarchiver.h"
#import "SUConstants.h" #import "SUConstants.h"
#import "SULog.h" #import "SULog.h"
#import "SUBinaryDeltaCommon.h" #import "SUBinaryDeltaCommon.h"
#import "SUCodeSigningVerifier.h"
#import "SUUpdater_Private.h" #import "SUUpdater_Private.h"
#import "SUFileManager.h" #import "SUFileManager.h"
#import "SUUpdateValidator.h" #import "SUXPCInstaller.h"
CF_EXPORT CFDictionaryRef DMCopyHTTPRequestHeaders(CFBundleRef appBundle, CFDataRef httpBodyData);
@interface SUBasicUpdateDriver () @interface SUBasicUpdateDriver ()
@@ -29,8 +34,6 @@
@property (copy) NSString *tempDir; @property (copy) NSString *tempDir;
@property (copy) NSString *relaunchPath; @property (copy) NSString *relaunchPath;
@property (nonatomic) SUUpdateValidator *updateValidator;
@end @end
@implementation SUBasicUpdateDriver @implementation SUBasicUpdateDriver
@@ -43,8 +46,6 @@
@synthesize tempDir; @synthesize tempDir;
@synthesize relaunchPath; @synthesize relaunchPath;
@synthesize updateValidator = _updateValidator;
- (void)checkForUpdatesAtURL:(NSURL *)URL host:(SUHost *)aHost - (void)checkForUpdatesAtURL:(NSURL *)URL host:(SUHost *)aHost
{ {
[super checkForUpdatesAtURL:URL host:aHost]; [super checkForUpdatesAtURL:URL host:aHost];
@@ -54,10 +55,14 @@
return; return;
} }
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
request.allHTTPHeaderFields = [self.updater httpHeaders];
[self updateURLRequestHTTPHeaders:request];
SUAppcast *appcast = [[SUAppcast alloc] init]; SUAppcast *appcast = [[SUAppcast alloc] init];
[appcast setUserAgentString:[self.updater userAgentString]]; [appcast setUserAgentString:[self.updater userAgentString]];
[appcast setHttpHeaders:[self.updater httpHeaders]]; [appcast setHttpHeaders:request.allHTTPHeaderFields];
[appcast fetchAppcastFromURL:URL completionBlock:^(NSError *error) { [appcast fetchAppcastFromURL:URL completionBlock:^(NSError *error) {
if (error) { if (error) {
[self abortUpdateWithError:error]; [self abortUpdateWithError:error];
@@ -84,28 +89,12 @@
return comparator; return comparator;
} }
+ (SUAppcastItem *)bestItemFromAppcastItems:(NSArray *)appcastItems getDeltaItem:(SUAppcastItem * __autoreleasing *)deltaItem withHostVersion:(NSString *)hostVersion comparator:(id<SUVersionComparison>)comparator - (BOOL)isItemNewer:(SUAppcastItem *)ui
{ {
SUAppcastItem *item = nil; return [[self versionComparator] compareVersion:[self.host version] toVersion:[ui versionString]] == NSOrderedAscending;
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:@""]) && if (([ui minimumSystemVersion] == nil || [[ui minimumSystemVersion] isEqualToString:@""]) &&
([ui maximumSystemVersion] == nil || [[ui maximumSystemVersion] isEqualToString:@""])) { return YES; } ([ui maximumSystemVersion] == nil || [[ui maximumSystemVersion] isEqualToString:@""])) { return YES; }
@@ -124,11 +113,6 @@
return minimumVersionOK && maximumVersionOK; return minimumVersionOK && maximumVersionOK;
} }
- (BOOL)isItemNewer:(SUAppcastItem *)ui
{
return [[self versionComparator] compareVersion:[self.host version] toVersion:[ui versionString]] == NSOrderedAscending;
}
- (BOOL)itemContainsSkippedVersion:(SUAppcastItem *)ui - (BOOL)itemContainsSkippedVersion:(SUAppcastItem *)ui
{ {
NSString *skippedVersion = [self.host objectForUserDefaultsKey:SUSkippedVersionKey]; NSString *skippedVersion = [self.host objectForUserDefaultsKey:SUSkippedVersionKey];
@@ -138,7 +122,7 @@
- (BOOL)itemContainsValidUpdate:(SUAppcastItem *)ui - (BOOL)itemContainsValidUpdate:(SUAppcastItem *)ui
{ {
return ui && [[self class] hostSupportsItem:ui] && [self isItemNewer:ui] && ![self itemContainsSkippedVersion:ui]; return ui && [self hostSupportsItem:ui] && [self isItemNewer:ui] && ![self itemContainsSkippedVersion:ui];
} }
- (void)appcastDidFinishLoading:(SUAppcast *)ac - (void)appcastDidFinishLoading:(SUAppcast *)ac
@@ -162,13 +146,20 @@
} }
else // If not, we'll take care of it ourselves. else // If not, we'll take care of it ourselves.
{ {
// Find the best supported update // Find the first update we can actually use.
SUAppcastItem *deltaUpdateItem = nil; for(SUAppcastItem *i in ac.items) {
item = [[self class] bestItemFromAppcastItems:ac.items getDeltaItem:&deltaUpdateItem withHostVersion:self.host.version comparator:[self versionComparator]]; if ([self hostSupportsItem:i]) {
item = i;
if (item && deltaUpdateItem) { break;
self.nonDeltaUpdateItem = item; }
item = deltaUpdateItem; }
if (item) {
SUAppcastItem *deltaUpdateItem = [item deltaUpdates][[self.host version]];
if (deltaUpdateItem && [self hostSupportsItem:deltaUpdateItem]) {
self.nonDeltaUpdateItem = item;
item = deltaUpdateItem;
}
} }
} }
@@ -210,38 +201,27 @@
}]]; }]];
} }
- (NSString *)appCachePath - (void)updateURLRequestHTTPHeaders:(NSMutableURLRequest *)request
{ {
NSArray *cachePaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); NSURL *hostBundleURL = self.host.bundlePath.length ? [NSURL fileURLWithPath:self.host.bundlePath] : nil;
NSString *cachePath = nil; CFBundleRef hostBundle = hostBundleURL ? CFBundleCreate(kCFAllocatorDefault, (__bridge CFURLRef)hostBundleURL) : NULL;
if ([cachePaths count]) { NSDictionary *devmateHeaders = (__bridge_transfer NSDictionary *)DMCopyHTTPRequestHeaders(hostBundle, NULL);
cachePath = [cachePaths objectAtIndex:0]; if (devmateHeaders.count)
} {
if (!cachePath) { [request setAllHTTPHeaderFields:devmateHeaders];
SULog(@"Failed to find user's cache directory! Using system default");
cachePath = NSTemporaryDirectory();
} }
NSString *name = [self.host.bundle bundleIdentifier]; if (NULL != hostBundle)
if (!name) { {
name = [self.host name]; CFRelease(hostBundle);
} }
cachePath = [cachePath stringByAppendingPathComponent:name];
cachePath = [cachePath stringByAppendingPathComponent:@SPARKLE_BUNDLE_IDENTIFIER];
return cachePath;
} }
- (void)downloadUpdate - (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]]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[self.updateItem fileURL]];
[request setValue:[self.updater userAgentString] forHTTPHeaderField:@"User-Agent"]; [request setValue:[self.updater userAgentString] forHTTPHeaderField:@"User-Agent"];
[self updateURLRequestHTTPHeaders:request];
if ([[self.updater delegate] respondsToSelector:@selector(updater:willDownloadUpdate:withRequest:)]) { if ([[self.updater delegate] respondsToSelector:@selector(updater:willDownloadUpdate:withRequest:)]) {
[[self.updater delegate] updater:self.updater [[self.updater delegate] updater:self.updater
willDownloadUpdate:self.updateItem willDownloadUpdate:self.updateItem
@@ -253,14 +233,13 @@
- (void)download:(NSURLDownload *)__unused d decideDestinationWithSuggestedFilename:(NSString *)name - (void)download:(NSURLDownload *)__unused d decideDestinationWithSuggestedFilename:(NSString *)name
{ {
NSString *downloadFileName = [NSString stringWithFormat:@"%@ %@", [self.host name], [self.updateItem versionString]]; NSString *downloadFileName = [NSString stringWithFormat:@"%@ %@", [self.host name], [self.updateItem versionString]];
NSString *appCachePath = [self appCachePath];
self.tempDir = [self.host.appCachePath stringByAppendingPathComponent:downloadFileName];
self.tempDir = [appCachePath stringByAppendingPathComponent:downloadFileName];
int cnt = 1; int cnt = 1;
while ([[NSFileManager defaultManager] fileExistsAtPath:self.tempDir] && cnt <= 999) while ([[NSFileManager defaultManager] fileExistsAtPath:self.tempDir] && cnt <= 999)
{ {
self.tempDir = [appCachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@ %d", downloadFileName, cnt++]]; self.tempDir = [self.host.appCachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@ %d", downloadFileName, cnt++]];
} }
// Create the temporary directory if necessary. // Create the temporary directory if necessary.
@@ -276,6 +255,95 @@
[self.download setDestination:self.downloadPath allowOverwrite:YES]; [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)
{
if (nil == publicDSAKey)
{
SULog(@"The existing app bundle does not have a DSA key, so it can't verify installer packages.");
}
isUpdateValid = [SUDSAVerifier validatePath:downloadedPath withEncodedDSASignature:DSASignature withPublicDSAKey:publicDSAKey];
if (!isUpdateValid)
{
SULog(@"DSA signature validation of the package failed. The update contains an installer package, and valid DSA signatures are mandatory for all installer packages. The update will be rejected. Sign the installer with a valid DSA key or use an .app bundle update instead.");
}
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 - (void)downloadDidFinish:(NSURLDownload *)__unused d
{ {
assert(self.updateItem); assert(self.updateItem);
@@ -285,26 +353,22 @@
- (void)download:(NSURLDownload *)__unused download didFailWithError:(NSError *)error - (void)download:(NSURLDownload *)__unused download didFailWithError:(NSError *)error
{ {
NSURL *failingUrl = [error.userInfo objectForKey:NSURLErrorFailingURLErrorKey]; NSURL *failingUrl = error.userInfo[NSURLErrorFailingURLErrorKey];
if (!failingUrl) { if (!failingUrl) {
failingUrl = [self.updateItem fileURL]; failingUrl = [self.updateItem fileURL];
} }
if ([[self.updater delegate] respondsToSelector:@selector(updater:failedToDownloadUpdate:error:)]) { if ([[self.updater delegate] respondsToSelector:@selector(updater:failedToDownloadUpdate:error:)]) {
[[self.updater delegate] updater:self.updater [[self.updater delegate] updater:self.updater
failedToDownloadUpdate:self.updateItem failedToDownloadUpdate:self.updateItem
error:error]; error:error];
} }
NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:@{ [self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SURelaunchError userInfo:@{
NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while downloading the update. Please try again later.", nil), NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while downloading the update. Please try again later.", nil),
NSUnderlyingErrorKey: error, 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 - (BOOL)download:(NSURLDownload *)__unused download shouldDecodeSourceDataOfMIMEType:(NSString *)encodingType
@@ -316,28 +380,14 @@
- (void)extractUpdate - (void)extractUpdate
{ {
SUUnarchiver *unarchiver = [SUUnarchiver unarchiverForPath:self.downloadPath updatingHostBundlePath:self.host.bundlePath withPassword:self.updater.decryptionPassword]; SUUnarchiver *unarchiver = [SUUnarchiver unarchiverForPath:self.downloadPath updatingHostBundlePath:[[self.host bundle] bundlePath] withPassword:self.updater.decryptionPassword];
BOOL success;
if (!unarchiver) { if (!unarchiver) {
SULog(@"Error: No valid unarchiver for %@!", self.downloadPath); SULog(@"Error: No valid unarchiver for %@!", self.downloadPath);
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]; [self unarchiverDidFail:nil];
} else { return;
unarchiver.delegate = self;
[unarchiver start];
} }
unarchiver.delegate = self;
[unarchiver start];
} }
- (void)failedToApplyDeltaUpdate - (void)failedToApplyDeltaUpdate
@@ -358,9 +408,6 @@
- (void)unarchiverDidFail:(SUUnarchiver *)__unused ua - (void)unarchiverDidFail:(SUUnarchiver *)__unused ua
{ {
// No longer needed
self.updateValidator = nil;
if ([self.updateItem isDeltaUpdate]) { if ([self.updateItem isDeltaUpdate]) {
[self failedToApplyDeltaUpdate]; [self failedToApplyDeltaUpdate];
return; return;
@@ -403,21 +450,20 @@
- (void)installWithToolAndRelaunch:(BOOL)relaunch displayingUserInterface:(BOOL)showUI - (void)installWithToolAndRelaunch:(BOOL)relaunch displayingUserInterface:(BOOL)showUI
{ {
assert(self.updateItem); assert(self.updateItem);
assert(self.updateValidator);
if (![self validateUpdateDownloadedToPath:self.downloadPath extractedToPath:self.tempDir DSASignature:self.updateItem.DSASignature publicDSAKey:self.host.publicDSAKey])
BOOL validationCheckSuccess = [self.updateValidator validateWithUpdateDirectory:self.tempDir]; {
if (!validationCheckSuccess) {
NSDictionary *userInfo = @{ NSDictionary *userInfo = @{
NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while extracting the archive. Please try again later.", nil), NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while extracting the archive. Please try again later.", nil),
NSLocalizedFailureReasonErrorKey: SULocalizedString(@"The update is improperly signed.", nil), NSLocalizedFailureReasonErrorKey: SULocalizedString(@"The update is improperly signed.", nil),
}; };
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUSignatureError userInfo:userInfo]]; [self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUSignatureError userInfo:userInfo]];
return; return;
} }
if (![self.updater mayUpdateAndRestart]) if (![self.updater mayUpdateAndRestart])
{ {
[self abortUpdate]; [self abortUpdate:SUUpdateAbortForbiddenByDelegate];
return; return;
} }
@@ -446,43 +492,40 @@
// Copy the relauncher into a temporary directory so we can get to it after the new version's installed. // 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. // 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 relaunchToolName = @"" SPARKLE_RELAUNCH_TOOL_NAME;
NSString *const relaunchToolSourcePath = [sparkleBundle pathForResource:relaunchToolName ofType:@"app"]; NSString *const relaunchPathToCopy = [sparkleBundle pathForResource:relaunchToolName ofType:@"app"];
NSString *relaunchCopyTargetPath = nil; if (relaunchPathToCopy != nil) {
NSError *error = nil; NSString *targetPath = [self.host.appCachePath stringByAppendingPathComponent:[relaunchPathToCopy lastPathComponent]];
BOOL copiedRelaunchPath = NO;
SUFileManager *fileManager = [SUFileManager fileManagerAllowingAuthorization:NO];
if (relaunchToolSourcePath) { NSError *error = nil;
relaunchCopyTargetPath = [[self appCachePath] stringByAppendingPathComponent:[relaunchToolSourcePath lastPathComponent]];
NSURL *relaunchURLToCopy = [NSURL fileURLWithPath:relaunchPathToCopy];
SUFileManager *fileManager = [SUFileManager defaultManager]; NSURL *targetURL = [NSURL fileURLWithPath:targetPath];
NSURL *relaunchToolSourceURL = [NSURL fileURLWithPath:relaunchToolSourcePath];
NSURL *relaunchCopyTargetURL = [NSURL fileURLWithPath:relaunchCopyTargetPath];
// We only need to run our copy of the app by spawning a task // 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 // 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]) { if ([self preparePathForRelaunchTool:targetPath error:&error] && [fileManager copyItemAtURL:relaunchURLToCopy toURL:targetURL error:&error]) {
copiedRelaunchPath = YES;
// We probably don't need to release the quarantine, but we'll do it just in case it's necessary. // 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. // Perhaps in a sandboxed environment this matters more. Note that this may not be a fatal error.
NSError *quarantineError = nil; NSError *quarantineError = nil;
if (![fileManager releaseItemFromQuarantineAtRootURL:relaunchCopyTargetURL error:&quarantineError]) { if (SUShouldUseXPCInstaller()) {
SULog(@"Failed to release quarantine on %@ with error %@", relaunchCopyTargetPath, quarantineError); [SUXPCInstaller releaseItemFromQuarantineAtRootURL:targetURL allowsAuthorization:fileManager.allowsAuthorization error:&quarantineError];
} else {
[fileManager releaseItemFromQuarantineAtRootURL:targetURL error:&quarantineError];
} }
if (quarantineError != nil) {
SULog(@"Failed to release quarantine on %@ with error %@", targetPath, quarantineError);
}
self.relaunchPath = targetPath;
} else {
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SURelaunchError userInfo:@{
NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while extracting the archive. Please try again later.", nil),
NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:@"Couldn't copy relauncher (%@) to temporary path (%@)! %@", relaunchPathToCopy, targetPath, (error ? [error localizedDescription] : @"")]
}]];
} }
} }
if (!copiedRelaunchPath) {
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SURelaunchError userInfo:@{
NSLocalizedDescriptionKey: [NSString stringWithFormat:SULocalizedString(@"An error occurred while relaunching %1$@, but the new version will be available next time you run %1$@.", nil), [self.host name]],
NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:@"Couldn't copy relauncher (%@) to temporary path (%@)! %@",
relaunchToolSourcePath, relaunchCopyTargetPath, (error ? [error localizedDescription] : @"")],
}]];
return;
}
self.relaunchPath = relaunchCopyTargetPath; // Set for backwards compatibility, in case any delegates modify it
[[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterWillRestartNotification object:self]; [[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterWillRestartNotification object:self];
if ([updaterDelegate respondsToSelector:@selector(updaterWillRelaunchApplication:)]) if ([updaterDelegate respondsToSelector:@selector(updaterWillRelaunchApplication:)])
[updaterDelegate updaterWillRelaunchApplication:self.updater]; [updaterDelegate updaterWillRelaunchApplication:self.updater];
@@ -492,8 +535,9 @@
// Note that we explicitly use the host app's name here, since updating plugin for Mail relaunches Mail, not just the plugin. // 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:@{ [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]], 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 %@ and %@)", relaunchToolSourcePath, self.relaunchPath], NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:@"Couldn't find the relauncher (expected to find it at %@)", self.relaunchPath]
}]]; }]];
// We intentionally don't abandon the update here so that the host won't initiate another.
return; return;
} }
@@ -501,17 +545,23 @@
if ([updaterDelegate respondsToSelector:@selector(pathToRelaunchForUpdater:)]) { if ([updaterDelegate respondsToSelector:@selector(pathToRelaunchForUpdater:)]) {
pathToRelaunch = [updaterDelegate pathToRelaunchForUpdater:self.updater]; pathToRelaunch = [updaterDelegate pathToRelaunchForUpdater:self.updater];
} }
NSArray *arguments = @[self.host.bundlePath.length ? self.host.bundlePath: @"",
[NSTask launchedTaskWithLaunchPath:relaunchToolPath arguments:@[[self.host bundlePath], pathToRelaunch.length ? pathToRelaunch : @"",
pathToRelaunch, [NSString stringWithFormat:@"%d", [[NSProcessInfo processInfo] processIdentifier]],
[NSString stringWithFormat:@"%d", [[NSProcessInfo processInfo] processIdentifier]], self.tempDir.length ? self.tempDir : @"",
self.tempDir, relaunch ? @"1" : @"0",
relaunch ? @"1" : @"0", showUI ? @"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];
}
[self terminateApp]; [self terminateApp];
} }
// Note: this is overridden by the automatic update driver to not terminate in some cases
- (void)terminateApp - (void)terminateApp
{ {
[NSApp terminate:self]; [NSApp terminate:self];
@@ -543,23 +593,18 @@
}]]; }]];
} }
- (void)abortUpdate - (void)abortUpdate:(SUUpdateAbortReason)reason
{ {
[self cleanUpDownload]; [self cleanUpDownload];
[[NSNotificationCenter defaultCenter] removeObserver:self]; [[NSNotificationCenter defaultCenter] removeObserver:self];
self.updateItem = nil; self.updateItem = nil;
[super abortUpdate]; [super abortUpdate:reason];
} }
- (void)abortUpdateWithError:(NSError *)error - (void)abortUpdateWithError:(NSError *)error
{ {
if ([error code] != SUNoUpdateError) { // Let's not bother logging this. if ([error code] != SUNoUpdateError) { // Let's not bother logging this.
NSError *errorToDisplay = error; SULog(@"Error: %@ %@ (URL %@)", error.localizedDescription, error.localizedFailureReason, error.userInfo[NSURLErrorFailingURLErrorKey]);
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) { if (self.download) {
[self.download cancel]; [self.download cancel];
@@ -571,7 +616,7 @@
[updaterDelegate updater:self.updater didAbortWithError:error]; [updaterDelegate updater:self.updater didAbortWithError:error];
} }
[self abortUpdate]; [self abortUpdate:SUUpdateAbortGotError];
} }
@end @end
+3 -3
View File
@@ -221,7 +221,7 @@ BOOL removeTree(NSString *path)
BOOL copyTree(NSString *source, NSString *dest) BOOL copyTree(NSString *source, NSString *dest)
{ {
return [[SUFileManager defaultManager] copyItemAtURL:[NSURL fileURLWithPath:source] toURL:[NSURL fileURLWithPath:dest] error:NULL]; return [[SUFileManager fileManagerAllowingAuthorization:NO] copyItemAtURL:[NSURL fileURLWithPath:source] toURL:[NSURL fileURLWithPath:dest] error:NULL];
} }
BOOL modifyPermissions(NSString *path, mode_t desiredPermissions) BOOL modifyPermissions(NSString *path, mode_t desiredPermissions)
@@ -231,12 +231,12 @@ BOOL modifyPermissions(NSString *path, mode_t desiredPermissions)
if (!attributes) { if (!attributes) {
return NO; return NO;
} }
NSNumber *permissions = [attributes objectForKey:NSFilePosixPermissions]; NSNumber *permissions = attributes[NSFilePosixPermissions];
if (!permissions) { if (!permissions) {
return NO; return NO;
} }
mode_t newMode = ([permissions unsignedShortValue] & ~PERMISSION_FLAGS) | desiredPermissions; mode_t newMode = ([permissions unsignedShortValue] & ~PERMISSION_FLAGS) | desiredPermissions;
int (*changeModeFunc)(const char *, mode_t) = [[attributes objectForKey:NSFileType] isEqualToString:NSFileTypeSymbolicLink] ? lchmod : chmod; int (*changeModeFunc)(const char *, mode_t) = [attributes[NSFileType] isEqualToString:NSFileTypeSymbolicLink] ? lchmod : chmod;
if (changeModeFunc([path fileSystemRepresentation], newMode) != 0) { if (changeModeFunc([path fileSystemRepresentation], newMode) != 0) {
return NO; return NO;
} }
+1 -1
View File
@@ -87,7 +87,7 @@ static NSDictionary *infoForFile(FTSENT *ent)
static bool aclExists(const FTSENT *ent) static bool aclExists(const FTSENT *ent)
{ {
// macOS does not currently support ACLs for symlinks // OS X does not currently support ACLs for symlinks
if (ent->fts_info == FTS_SL) { if (ent->fts_info == FTS_SL) {
return NO; return NO;
} }
+1 -43
View File
@@ -10,9 +10,9 @@
#import "SUBinaryDeltaUnarchiver.h" #import "SUBinaryDeltaUnarchiver.h"
#import "SUBinaryDeltaApply.h" #import "SUBinaryDeltaApply.h"
#import "SUUnarchiver_Private.h" #import "SUUnarchiver_Private.h"
#import "SUFileManager.h"
#import "SUHost.h" #import "SUHost.h"
#import "SULog.h" #import "SULog.h"
#import "NTSynchronousTask.h"
@implementation SUBinaryDeltaUnarchiver @implementation SUBinaryDeltaUnarchiver
@@ -21,46 +21,6 @@
return [[path pathExtension] isEqualToString:@"delta"]; 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 - (void)applyBinaryDelta
{ {
@autoreleasepool { @autoreleasepool {
@@ -70,8 +30,6 @@
NSError *applyDiffError = nil; NSError *applyDiffError = nil;
BOOL success = applyBinaryDelta(sourcePath, targetPath, self.archivePath, NO, &applyDiffError); BOOL success = applyBinaryDelta(sourcePath, targetPath, self.archivePath, NO, &applyDiffError);
if (success) { if (success) {
[[self class] updateSpotlightImportersAtBundlePath:targetPath];
dispatch_async(dispatch_get_main_queue(), ^{ dispatch_async(dispatch_get_main_queue(), ^{
[self notifyDelegateOfSuccess]; [self notifyDelegateOfSuccess];
}); });
+5 -3
View File
@@ -12,9 +12,11 @@
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>
@interface SUCodeSigningVerifier : NSObject @interface SUCodeSigningVerifier : NSObject
+ (BOOL)codeSignatureAtBundleURL:(NSURL *)oldBundlePath matchesSignatureAtBundleURL:(NSURL *)newBundlePath error:(NSError **)error; // pass nil as an application path to check a host one
+ (BOOL)codeSignatureIsValidAtBundleURL:(NSURL *)bundlePath error:(NSError **)error; + (BOOL)codeSignatureAtPath:(NSString *)hostPath matchesSignatureAtPath:(NSString *)otherAppPath error:(NSError **)error;
+ (BOOL)bundleAtURLIsCodeSigned:(NSURL *)bundlePath; + (BOOL)codeSignatureIsValidAtPath:(NSString *)applicationPath error:(NSError **)error;
+ (BOOL)applicationAtPathIsCodeSigned:(NSString *)applicationPath;
+ (BOOL)hostApplicationIsSandboxed;
@end @end
#endif #endif
+145 -43
View File
@@ -13,46 +13,94 @@
@implementation SUCodeSigningVerifier @implementation SUCodeSigningVerifier
+ (BOOL)codeSignatureAtBundleURL:(NSURL *)oldBundleURL matchesSignatureAtBundleURL:(NSURL *)newBundleURL error:(NSError *__autoreleasing *)error + (BOOL)codeSignatureAtPath:(NSString *)hostPath matchesSignatureAtPath:(NSString *)otherAppPath error:(NSError *__autoreleasing *)error
{ {
OSStatus result; OSStatus result;
SecRequirementRef requirement = NULL; SecRequirementRef requirement = NULL;
SecStaticCodeRef staticCode = NULL; SecStaticCodeRef staticHostCode = NULL;
SecStaticCodeRef oldCode = NULL; SecStaticCodeRef staticAppCode = NULL;
CFErrorRef cfError = NULL;
if (error) { if (error) {
*error = nil; *error = nil;
} }
result = SecStaticCodeCreateWithPath((__bridge CFURLRef)oldBundleURL, kSecCSDefaultFlags, &oldCode); if (0 == hostPath.length) {
if (result == errSecCSUnsigned) { SecCodeRef hostCode = NULL;
return NO; 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 = SecCodeCopyDesignatedRequirement(oldCode, kSecCSDefaultFlags, &requirement); result = SecCodeCopyDesignatedRequirement(staticHostCode, kSecCSDefaultFlags, &requirement);
if (result != noErr) { if (result != noErr) {
SULog(@"Failed to copy designated requirement. Code Signing OSStatus code: %d", result); SULog(@"Failed to copy designated requirement. Code Signing OSStatus code: %d", result);
goto finally; goto finally;
} }
result = SecStaticCodeCreateWithPath((__bridge CFURLRef)newBundleURL, kSecCSDefaultFlags, &staticCode); if (0 == otherAppPath.length) {
if (result != noErr) { SecCodeRef hostCode = NULL;
SULog(@"Failed to get static code %d", result); result = SecCodeCopySelf(kSecCSDefaultFlags, &hostCode);
goto finally; 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;
}
} }
// Note that kSecCSCheckNestedCode may not work with pre-Mavericks code signing. // 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 // See https://github.com/sparkle-project/Sparkle/issues/376#issuecomment-48824267 and https://developer.apple.com/library/mac/technotes/tn2206
// Aditionally, there are several reasons to stay away from deep verification and to prefer DSA signing the download archive instead. CFErrorRef cfError = NULL;
// See https://github.com/sparkle-project/Sparkle/pull/523#commitcomment-17549302 and https://github.com/sparkle-project/Sparkle/issues/543 SecCSFlags flags = (SecCSFlags) (kSecCSDefaultFlags | kSecCSCheckAllArchitectures);
SecCSFlags flags = (SecCSFlags) (kSecCSDefaultFlags | kSecCSCheckAllArchitectures); result = SecStaticCodeCheckValidityWithErrors(staticAppCode, flags, requirement, &cfError);
result = SecStaticCodeCheckValidityWithErrors(staticCode, flags, requirement, &cfError);
if (cfError) { if (cfError) {
NSError *tmpError = CFBridgingRelease(cfError); NSError *tmpError = CFBridgingRelease(cfError);
if (error) *error = tmpError; if (error) {
*error = tmpError;
}
} }
if (result != noErr) { if (result != noErr) {
if (result == errSecCSUnsigned) { 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."); 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.");
@@ -63,52 +111,61 @@
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); 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); CFRelease(requirementString);
} }
[self logSigningInfoForCode:oldCode label:@"old info"]; [self logSigningInfoForCode:staticHostCode label:@"host info"];
[self logSigningInfoForCode:staticCode label:@"new info"]; [self logSigningInfoForCode:staticAppCode label:@"new info"];
} }
} }
finally: finally:
if (oldCode) CFRelease(oldCode); if (staticHostCode) CFRelease(staticHostCode);
if (staticCode) CFRelease(staticCode); if (staticAppCode) CFRelease(staticAppCode);
if (requirement) CFRelease(requirement); if (requirement) CFRelease(requirement);
return (result == noErr); return (result == noErr);
} }
+ (BOOL)codeSignatureIsValidAtBundleURL:(NSURL *)bundleURL error:(NSError *__autoreleasing *)error + (BOOL)codeSignatureIsValidAtPath:(NSString *)applicationPath error:(NSError *__autoreleasing *)error
{ {
OSStatus result; OSStatus result;
SecStaticCodeRef staticCode = NULL; SecStaticCodeRef staticCode = NULL;
NSBundle *newBundle;
CFErrorRef cfError = NULL; CFErrorRef cfError = NULL;
if (error) { if (error) {
*error = nil; *error = nil;
} }
result = SecStaticCodeCreateWithPath((__bridge CFURLRef)bundleURL, kSecCSDefaultFlags, &staticCode); newBundle = [NSBundle bundleWithPath:applicationPath];
if (!newBundle) {
SULog(@"Failed to load NSBundle");
result = -1;
goto finally;
}
result = SecStaticCodeCreateWithPath((__bridge CFURLRef)[newBundle bundleURL], kSecCSDefaultFlags, &staticCode);
if (result != noErr) { if (result != noErr) {
SULog(@"Failed to get static code %d", result); SULog(@"Failed to get static code %d", result);
goto finally; goto finally;
} }
// See in -codeSignatureAtBundleURL:matchesSignatureAtBundleURL:error: for why kSecCSCheckNestedCode is not passed // Note that kSecCSCheckNestedCode may not work with pre-Mavericks code signing.
SecCSFlags flags = (SecCSFlags) (kSecCSDefaultFlags | kSecCSCheckAllArchitectures); // 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);
result = SecStaticCodeCheckValidityWithErrors(staticCode, flags, NULL, &cfError); result = SecStaticCodeCheckValidityWithErrors(staticCode, flags, NULL, &cfError);
if (cfError) { if (cfError) {
NSError *tmpError = CFBridgingRelease(cfError); NSError *tmpError = CFBridgingRelease(cfError);
if (error) *error = tmpError; if (error) *error = tmpError;
} }
if (result != noErr) { if (result != noErr) {
if (result == errSecCSUnsigned) { if (result == errSecCSUnsigned) {
SULog(@"Error: The app is not signed using Apple Code Signing. %@", bundleURL); SULog(@"Error: The app is not signed using Apple Code Signing. %@", applicationPath);
} }
if (result == errSecCSReqFailed) { if (result == errSecCSReqFailed) {
[self logSigningInfoForCode:staticCode label:@"new info"]; [self logSigningInfoForCode:staticCode label:@"new info"];
} }
} }
finally: finally:
if (staticCode) CFRelease(staticCode); if (staticCode) CFRelease(staticCode);
return (result == noErr); return (result == noErr);
@@ -125,23 +182,68 @@ static id valueOrNSNull(id value) {
NSDictionary *signingDict = CFBridgingRelease(signingInfo); NSDictionary *signingDict = CFBridgingRelease(signingInfo);
NSMutableDictionary *relevantInfo = [NSMutableDictionary dictionary]; NSMutableDictionary *relevantInfo = [NSMutableDictionary dictionary];
for (NSString *key in @[@"format", @"identifier", @"requirements", @"teamid", @"signing-time"]) { for (NSString *key in @[@"format", @"identifier", @"requirements", @"teamid", @"signing-time"]) {
[relevantInfo setObject:valueOrNSNull([signingDict objectForKey:key]) forKey:key]; relevantInfo[key] = valueOrNSNull(signingDict[key]);
} }
NSDictionary *infoPlist = [signingDict objectForKey:@"info-plist"]; NSDictionary *infoPlist = signingDict[@"info-plist"];
[relevantInfo setObject:valueOrNSNull([infoPlist objectForKey:@"CFBundleShortVersionString"]) forKey:@"version"]; relevantInfo[@"version"] = valueOrNSNull(infoPlist[@"CFBundleShortVersionString"]);
[relevantInfo setObject:valueOrNSNull([infoPlist objectForKey:(__bridge NSString *)kCFBundleVersionKey]) forKey:@"build"]; relevantInfo[@"build"] = valueOrNSNull(infoPlist[(__bridge NSString *)kCFBundleVersionKey]);
SULog(@"%@: %@", label, relevantInfo); SULog(@"%@: %@", label, relevantInfo);
} }
} }
+ (BOOL)bundleAtURLIsCodeSigned:(NSURL *)bundleURL + (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
{ {
OSStatus result; OSStatus result;
SecStaticCodeRef staticCode = NULL; SecStaticCodeRef staticCode = NULL;
NSBundle *newBundle;
result = SecStaticCodeCreateWithPath((__bridge CFURLRef)bundleURL, kSecCSDefaultFlags, &staticCode); newBundle = [NSBundle bundleWithPath:applicationPath];
if (!newBundle) {
SULog(@"Failed to load NSBundle");
return NO;
}
result = SecStaticCodeCreateWithPath((__bridge CFURLRef)[newBundle bundleURL], kSecCSDefaultFlags, &staticCode);
if (result == errSecCSUnsigned) { if (result == errSecCSUnsigned) {
return NO; return NO;
} }
SecRequirementRef requirement = NULL; SecRequirementRef requirement = NULL;
@@ -153,7 +255,7 @@ static id valueOrNSNull(id value) {
CFRelease(requirement); CFRelease(requirement);
} }
if (result == errSecCSUnsigned) { if (result == errSecCSUnsigned) {
return NO; return NO;
} }
return (result == 0); return (result == 0);
} }
+16 -1
View File
@@ -12,6 +12,21 @@
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>
// -----------------------------------------------------------------------------
// Typedefs:
// -----------------------------------------------------------------------------
typedef NS_ENUM(NSUInteger, SUUpdateAbortReason)
{
SUUpdateAbortUndefined = 0,
SUUpdateAbortForbiddenByDelegate,
SUUpdateAbortTasksFinished,
SUUpdateAbortCanceledByUser,
SUUpdateAbortDidNotFind,
SUUpdateAbortInterrupred,
SUUpdateAbortGotError
};
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
// Misc: // Misc:
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
@@ -43,13 +58,13 @@ extern NSString *const SUPublicDSAKeyFileKey;
extern NSString *const SUAutomaticallyUpdateKey; extern NSString *const SUAutomaticallyUpdateKey;
extern NSString *const SUAllowsAutomaticUpdatesKey; extern NSString *const SUAllowsAutomaticUpdatesKey;
extern NSString *const SUEnableAutomaticChecksKey; extern NSString *const SUEnableAutomaticChecksKey;
extern NSString *const SUEnableAutomaticChecksKeyOld;
extern NSString *const SUEnableSystemProfilingKey; extern NSString *const SUEnableSystemProfilingKey;
extern NSString *const SUSendProfileInfoKey; extern NSString *const SUSendProfileInfoKey;
extern NSString *const SULastProfileSubmitDateKey; extern NSString *const SULastProfileSubmitDateKey;
extern NSString *const SUPromptUserOnFirstLaunchKey; extern NSString *const SUPromptUserOnFirstLaunchKey;
extern NSString *const SUKeepDownloadOnFailedInstallKey; extern NSString *const SUKeepDownloadOnFailedInstallKey;
extern NSString *const SUDefaultsDomainKey; 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 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 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."))); extern NSString *const SUEnableAutomatedDowngradesKey __attribute__((deprecated("This key is obsolete. See SPARKLE_AUTOMATED_DOWNGRADES.")));
+2 -1
View File
@@ -12,6 +12,7 @@
#import "SUAppcastItem.h" #import "SUAppcastItem.h"
#import "SUVersionComparisonProtocol.h" #import "SUVersionComparisonProtocol.h"
#import "SUConstants.h" #import "SUConstants.h"
#import "SUErrors.h"
#ifndef DEBUG #ifndef DEBUG
#define DEBUG 0 #define DEBUG 0
@@ -38,10 +39,10 @@ NSString *const SUAutomaticallyUpdateKey = @"SUAutomaticallyUpdate";
NSString *const SUAllowsAutomaticUpdatesKey = @"SUAllowsAutomaticUpdates"; NSString *const SUAllowsAutomaticUpdatesKey = @"SUAllowsAutomaticUpdates";
NSString *const SUEnableSystemProfilingKey = @"SUEnableSystemProfiling"; NSString *const SUEnableSystemProfilingKey = @"SUEnableSystemProfiling";
NSString *const SUEnableAutomaticChecksKey = @"SUEnableAutomaticChecks"; NSString *const SUEnableAutomaticChecksKey = @"SUEnableAutomaticChecks";
NSString *const SUEnableAutomaticChecksKeyOld = @"SUCheckAtStartup";
NSString *const SUSendProfileInfoKey = @"SUSendProfileInfo"; NSString *const SUSendProfileInfoKey = @"SUSendProfileInfo";
NSString *const SULastProfileSubmitDateKey = @"SULastProfileSubmissionDate"; NSString *const SULastProfileSubmitDateKey = @"SULastProfileSubmissionDate";
NSString *const SUPromptUserOnFirstLaunchKey = @"SUPromptUserOnFirstLaunch"; NSString *const SUPromptUserOnFirstLaunchKey = @"SUPromptUserOnFirstLaunch";
NSString *const SUEnableJavaScriptKey = @"SUEnableJavaScript";
NSString *const SUFixedHTMLDisplaySizeKey = @"SUFixedHTMLDisplaySize"; NSString *const SUFixedHTMLDisplaySizeKey = @"SUFixedHTMLDisplaySize";
NSString *const SUKeepDownloadOnFailedInstallKey = @"SUKeepDownloadOnFailedInstall"; NSString *const SUKeepDownloadOnFailedInstallKey = @"SUKeepDownloadOnFailedInstall";
NSString *const SUDefaultsDomainKey = @"SUDefaultsDomain"; NSString *const SUDefaultsDomainKey = @"SUDefaultsDomain";
+79 -65
View File
@@ -8,8 +8,10 @@
#import "SUDiskImageUnarchiver.h" #import "SUDiskImageUnarchiver.h"
#import "SUUnarchiver_Private.h" #import "SUUnarchiver_Private.h"
#import "NTSynchronousTask.h"
#import "SULog.h" #import "SULog.h"
#include <CoreServices/CoreServices.h> #include <CoreServices/CoreServices.h>
#import "SUXPCInstaller.h"
@implementation SUDiskImageUnarchiver @implementation SUDiskImageUnarchiver
@@ -18,11 +20,6 @@
return [[path pathExtension] isEqualToString:@"dmg"]; return [[path pathExtension] isEqualToString:@"dmg"];
} }
+ (BOOL)unsafeIfArchiveIsNotValidated
{
return NO;
}
// Called on a non-main thread. // Called on a non-main thread.
- (void)extractDMG - (void)extractDMG
{ {
@@ -39,12 +36,6 @@
SULog(@"Extracting %@ as a DMG", self.archivePath); 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. // 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 // No, we cannot have them in the dispatch_async calls, as the goto "jump enters
// lifetime of block which strongly captures a variable" // lifetime of block which strongly captures a variable"
@@ -54,7 +45,10 @@
dispatch_block_t delegateSuccess = ^{ dispatch_block_t delegateSuccess = ^{
[self notifyDelegateOfSuccess]; [self notifyDelegateOfSuccess];
}; };
do
// get a unique mount point path
NSString *mountPoint = nil;
do
{ {
// Using NSUUID would make creating UUIDs be done in Cocoa, // Using NSUUID would make creating UUIDs be done in Cocoa,
// and thus managed under ARC. Sadly, the class is in 10.8 and later. // and thus managed under ARC. Sadly, the class is in 10.8 and later.
@@ -69,12 +63,14 @@
CFRelease(uuid); CFRelease(uuid);
} }
} }
while (noErr == FSPathMakeRefWithOptions((const UInt8 *)[mountPoint fileSystemRepresentation], kFSPathMakeRefDoNotFollowLeafSymlink, &tmpRef, NULL)); while ([[NSFileManager defaultManager] fileExistsAtPath:mountPoint]);
NSData *promptData = nil; NSData *promptData = nil;
promptData = [NSData dataWithBytes:"yes\n" length:4]; promptData = [NSData dataWithBytes:"yes\n" length:4];
NSMutableArray *arguments = [@[@"attach", self.archivePath, @"-mountpoint", mountPoint, /*@"-noverify",*/ @"-nobrowse", @"-noautoopen"] mutableCopy]; NSString *hdiutilPath = @"/usr/bin/hdiutil";
NSString *currentDirPath = @"/";
NSArray *arguments = @[@"attach", self.archivePath, @"-mountpoint", mountPoint, /*@"-noverify",*/ @"-nobrowse", @"-noautoopen"];
if (self.decryptionPassword) { if (self.decryptionPassword) {
NSMutableData *passwordData = [[self.decryptionPassword dataUsingEncoding:NSUTF8StringEncoding] mutableCopy]; NSMutableData *passwordData = [[self.decryptionPassword dataUsingEncoding:NSUTF8StringEncoding] mutableCopy];
@@ -86,34 +82,31 @@
[passwordData appendData:promptData]; [passwordData appendData:promptData];
promptData = passwordData; promptData = passwordData;
[arguments addObject:@"-stdinpass"]; arguments = [arguments arrayByAddingObject:@"-stdinpass"];
} }
NSData *output = nil; BOOL shouldUseXPC = SUShouldUseXPCInstaller();
NSInteger taskResult = -1;
__block NSData *output = nil;
__block NSInteger taskResult = -1;
@try @try
{ {
NSTask *task = [[NSTask alloc] init]; if (shouldUseXPC)
task.launchPath = @"/usr/bin/hdiutil"; {
task.currentDirectoryPath = @"/"; [SUXPCInstaller launchTaskWithPath:hdiutilPath arguments:arguments environment:nil currentDirectoryPath:currentDirPath inputData:promptData waitUntilDone:YES completionHandler:^(int result, NSData *outputData) {
task.arguments = arguments; taskResult = (NSInteger)result;
output = [outputData copy];
NSPipe *inputPipe = [NSPipe pipe]; }];
NSPipe *outputPipe = [NSPipe pipe]; }
else
task.standardInput = inputPipe; {
task.standardOutput = outputPipe; NTSynchronousTask *task = [[NTSynchronousTask alloc] init];
[task launch]; [task run:hdiutilPath directory:currentDirPath withArgs:arguments input:promptData];
[inputPipe.fileHandleForWriting writeData:promptData]; taskResult = [task result];
[inputPipe.fileHandleForWriting closeFile]; output = [[task output] copy];
}
// 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 *) @catch (NSException *)
{ {
@@ -129,30 +122,45 @@
mountedSuccessfully = YES; mountedSuccessfully = YES;
// Now that we've mounted it, we need to copy out its contents. // Now that we've mounted it, we need to copy out its contents.
manager = [[NSFileManager alloc] init]; if (shouldUseXPC)
contents = [manager contentsOfDirectoryAtPath:mountPoint error:&error]; {
if (error) NSError *error = nil;
{ [SUXPCInstaller copyPathContent:mountPoint toDirectory:[self.archivePath stringByDeletingLastPathComponent] error:&error];
SULog(@"Couldn't enumerate contents of archive mounted at %@: %@", mountPoint, error);
goto reportError; if (nil != error)
{
SULog(@"Couldn't copy volume content: %ld - %@", error.code, error.localizedDescription);
goto reportError;
}
} }
else
for (NSString *item in contents) {
{ NSFileManager *manager = [[NSFileManager alloc] init];
NSString *fromPath = [mountPoint stringByAppendingPathComponent:item]; NSError *error = nil;
NSString *toPath = [[self.archivePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:item]; NSArray *contents = [manager contentsOfDirectoryAtPath:mountPoint error:&error];
if (error)
// We skip any files in the DMG which are not readable. {
if (![manager isReadableFileAtPath:fromPath]) { SULog(@"Couldn't enumerate contents of archive mounted at %@: %@", mountPoint, error);
continue; goto reportError;
} }
SULog(@"copyItemAtPath:%@ toPath:%@", fromPath, toPath); for (NSString *item in contents)
{
NSString *fromPath = [mountPoint stringByAppendingPathComponent:item];
NSString *toPath = [[self.archivePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:item];
if (![manager copyItemAtPath:fromPath toPath:toPath error:&error]) // We skip any files in the DMG which are not readable.
{ if (![manager isReadableFileAtPath:fromPath]) {
SULog(@"Couldn't copy item: %@ : %@", error, error.userInfo ? error.userInfo : @""); continue;
goto reportError; }
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;
}
} }
} }
@@ -163,14 +171,20 @@
dispatch_async(dispatch_get_main_queue(), delegateFailure); dispatch_async(dispatch_get_main_queue(), delegateFailure);
finally: finally:
if (mountedSuccessfully) { if (mountedSuccessfully)
@try { {
[NSTask launchedTaskWithLaunchPath:@"/usr/bin/hdiutil" arguments:@[@"detach", mountPoint, @"-force"]]; arguments = @[@"detach", mountPoint, @"-force"];
} @catch (NSException *exception) { if (shouldUseXPC)
SULog(@"Failed to unmount %@", mountPoint); {
SULog(@"Exception: %@", exception); [SUXPCInstaller launchTaskWithPath:hdiutilPath arguments:arguments environment:nil currentDirectoryPath:nil inputData:nil waitUntilDone:NO completionHandler:nil];
} }
} else { else
{
[NSTask launchedTaskWithLaunchPath:hdiutilPath arguments:arguments];
}
}
else
{
SULog(@"Can't mount DMG %@", self.archivePath); SULog(@"Can't mount DMG %@", self.archivePath);
} }
} }
+5 -9
View File
@@ -9,11 +9,7 @@
#ifndef SUERRORS_H #ifndef SUERRORS_H
#define SUERRORS_H #define SUERRORS_H
#if __has_feature(modules)
@import Foundation;
#else
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>
#endif
#import "SUExport.h" #import "SUExport.h"
/** /**
@@ -27,11 +23,10 @@ typedef NS_ENUM(OSStatus, SUError) {
SUNoUpdateError = 1001, SUNoUpdateError = 1001,
SUAppcastError = 1002, SUAppcastError = 1002,
SURunningFromDiskImageError = 1003, SURunningFromDiskImageError = 1003,
// Download phase errors. // Downlaod phase errors.
SUTemporaryDirectoryError = 2000, SUTemporaryDirectoryError = 2000,
SUDownloadError = 2001,
// Extraction phase errors. // Extraction phase errors.
SUUnarchivingError = 3000, SUUnarchivingError = 3000,
SUSignatureError = 3001, SUSignatureError = 3001,
@@ -44,8 +39,9 @@ typedef NS_ENUM(OSStatus, SUError) {
SURelaunchError = 4004, SURelaunchError = 4004,
SUInstallationError = 4005, SUInstallationError = 4005,
SUDowngradeError = 4006, SUDowngradeError = 4006,
SUInstallationCancelledError = 4007,
SUXPCServiceError = 4007,
// System phase errors // System phase errors
SUSystemPowerOffError = 5000 SUSystemPowerOffError = 5000
}; };
+10 -45
View File
@@ -9,36 +9,23 @@
#import <Foundation/Foundation.h> #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 * A class used for performing file operations that may also perform authentication 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. * 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. * This class provides basic file operations and stays away from including much application-level logic.
*/ */
@interface SUFileManager : NSObject @interface SUFileManager : NSObject
/** /**
* Creates a file manager that will not authorize for file operations * Creates a file manager that allows or disallows authorizing for file operations
* @return A new file manager instance * @param allowsAuthorization Specifies whether operations invoked on this instance are allowed to acquire authorization in order
*/ * to perform file operations when read or write access is denied
+ (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 * @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. * This method just creates the file manager. It doesn't acquire authorization immediately if allowsAuthorization is YES
*/ */
+ (instancetype)fileManagerWithAuthorizationToolPath:(NSString *)authorizationToolPath; + (instancetype)fileManagerAllowingAuthorization:(BOOL)allowsAuthorization;
/** @property (nonatomic, assign, readonly) BOOL allowsAuthorization;
* 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 * Creates a temporary directory on the same volume as a provided URL
@@ -52,16 +39,6 @@
*/ */
- (NSURL *)makeTemporaryDirectoryWithPreferredName:(NSString *)preferredName appropriateForDirectoryURL:(NSURL *)appropriateURL error:(NSError **)error; - (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 * 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 sourceURL A URL pointing to the item to move. The item at this URL must exist.
@@ -145,8 +122,8 @@
* @return YES if all the items at the target could be released from quarantine, otherwise NO if any items couldn't along with a populated error object * @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 * 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. * don't have to witness the OS X dialog alerting them that they downloaded an application from the internet and asking if they want to continue.
* Note that this may not exactly mimic the system behavior when a user opens an application for the first time (i.e, the xattr isn't deleted), * Note that this may not exactly mimic OS X's behavior when a user opens an application for the first time (i.e, the xattr isn't deleted),
* but this should be sufficient enough for our purposes. * 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. * This method may return NO even if some items do get released from quarantine if the target URL is pointing to a directory.
@@ -156,16 +133,4 @@
*/ */
- (BOOL)releaseItemFromQuarantineAtRootURL:(NSURL *)rootURL error:(NSError **)error; - (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 @end
+110 -222
View File
@@ -8,7 +8,6 @@
#import "SUFileManager.h" #import "SUFileManager.h"
#import "SUOperatingSystem.h" #import "SUOperatingSystem.h"
#import "SUFileOperationConstants.h"
#include <sys/xattr.h> #include <sys/xattr.h>
#include <sys/errno.h> #include <sys/errno.h>
@@ -16,6 +15,30 @@
static char SUAppleQuarantineIdentifier[] = "com.apple.quarantine"; static char SUAppleQuarantineIdentifier[] = "com.apple.quarantine";
// Authorization code based on generous contribution from Allan Odgaard. Thanks, Allan!
static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authorization, const char *executablePath, AuthorizationFlags options, char *const *arguments)
{
sig_t oldSigChildHandler = signal(SIGCHLD, SIG_DFL);
BOOL returnValue = YES;
#pragma clang diagnostic push
// In the future, we may have to look at SMJobBless API to avoid deprecation. See issue #558
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
if (AuthorizationExecuteWithPrivileges(authorization, executablePath, options, arguments, NULL) == errAuthorizationSuccess)
#pragma clang diagnostic pop
{
int status;
pid_t pid = wait(&status);
if (pid == -1 || !WIFEXITED(status) || WEXITSTATUS(status) != 0)
returnValue = NO;
}
else
returnValue = NO;
signal(SIGCHLD, oldSigChildHandler);
return returnValue;
}
static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
char path[PATH_MAX] = {0}; char path[PATH_MAX] = {0};
@@ -52,37 +75,31 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
{ {
AuthorizationRef _auth; AuthorizationRef _auth;
NSFileManager *_fileManager; NSFileManager *_fileManager;
NSString *_authorizationToolPath; BOOL _allowsAuthorization;
} }
- (instancetype)initWithAuthorizationToolPath:(NSString *)authorizationToolPath - (instancetype)initAllowingAuthorization:(BOOL)allowsAuthorization
{ {
self = [super init]; self = [super init];
if (self != nil) { if (self != nil) {
_fileManager = [[NSFileManager alloc] init]; _fileManager = [[NSFileManager alloc] init];
_authorizationToolPath = [authorizationToolPath copy]; _allowsAuthorization = allowsAuthorization;
} }
return self; return self;
} }
+ (instancetype)defaultManager
+ (instancetype)fileManagerAllowingAuthorization:(BOOL)allowsAuthorization
{ {
return [[self alloc] initWithAuthorizationToolPath:nil]; return [[self alloc] initAllowingAuthorization:allowsAuthorization];
} }
+ (instancetype)fileManagerWithAuthorizationToolPath:(NSString *)authorizationToolPath - (BOOL)allowsAuthorization
{ {
return [[self alloc] initWithAuthorizationToolPath:authorizationToolPath]; return _allowsAuthorization;
} }
- (instancetype)fileManagerByPreservingAuthorizationRights // Acquires an authorization reference which is intended to be used for future authorized file operations
{
// Check if we don't allow authorization, or that we haven't needed to authorize yet, to create or re-use a
// file manager instance with these restrictions
return (_authorizationToolPath != nil && _auth != NULL) ? self : [SUFileManager defaultManager];
}
// Acquires an authorization reference with root privileges which is intended to be used for authorized file operations
- (BOOL)_acquireAuthorizationWithError:(NSError *__autoreleasing *)error - (BOOL)_acquireAuthorizationWithError:(NSError *__autoreleasing *)error
{ {
// No need to continue if we already acquired an authorization reference // No need to continue if we already acquired an authorization reference
@@ -90,112 +107,21 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
return YES; return YES;
} }
if (_authorizationToolPath == nil) { if (!_allowsAuthorization) {
if (error != NULL) { if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: @"Unable to grant authorization to perform action because it is explicitly turned off" }]; *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: @"Unable to grant authorization to perform action because it is explicitly turned off" }];
} }
return NO; return NO;
} }
OSStatus createStatus = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &_auth); OSStatus status = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &_auth);
if (createStatus != errAuthorizationSuccess) { if (status != errAuthorizationSuccess) {
if (error != NULL) { if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed creating authorization reference with status code %d.", createStatus] }]; *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed creating authorization reference with status code %d.", status] }];
} }
_auth = NULL; _auth = NULL;
return NO; return NO;
} }
AuthorizationItem rightItems[] = {
// The right that allows us to run tools as root user
{.name = kAuthorizationRightExecute, .valueLength = 0, .value = NULL, .flags = 0}
};
AuthorizationRights rights = {
.count = sizeof(rightItems) / sizeof(*rightItems),
.items = rightItems
};
AuthorizationFlags flags =
(AuthorizationFlags)(kAuthorizationFlagDefaults | kAuthorizationFlagInteractionAllowed | kAuthorizationFlagExtendRights | kAuthorizationFlagPreAuthorize);
// This will test if we can gain authorization for running utlities as root
OSStatus copyStatus = AuthorizationCopyRights(_auth, &rights, kAuthorizationEmptyEnvironment, flags, NULL);
if (copyStatus != errAuthorizationSuccess) {
if (error != NULL) {
if (copyStatus == errAuthorizationCanceled) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationCancelledError userInfo:@{ NSLocalizedDescriptionKey: @"Authorization access was cancelled by the user." }];
} else {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed granting authorization rights with status code %d.", copyStatus] }];
}
}
AuthorizationFree(_auth, kAuthorizationFlagDefaults);
_auth = NULL;
return NO;
}
return YES;
}
- (BOOL)_authorizeAndExecuteCommand:(char *)command sourcePath:(char *)sourcePath destinationPath:(char *)destinationPath error:(NSError * __autoreleasing *)error
{
NSError *acquireError = nil;
if (![self _acquireAuthorizationWithError:&acquireError]) {
if (error != NULL) {
*error = acquireError;
}
return NO;
}
char *arguments[] = { command, sourcePath, destinationPath, NULL };
char toolPath[PATH_MAX] = {0};
if (![_authorizationToolPath getFileSystemRepresentation:toolPath maxLength:sizeof(toolPath)]) {
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Authorization tool (%@) cannot be represented as a valid file name.", _authorizationToolPath.lastPathComponent] }];
}
return NO;
}
FILE *pipe = NULL;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
if (AuthorizationExecuteWithPrivileges(_auth, toolPath, kAuthorizationFlagDefaults, arguments, &pipe) != errAuthorizationSuccess) {
#pragma clang diagnostic pop
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:@"Failed to run authorization tool." }];
}
return NO;
}
uint32_t pidData = 0;
if (fread(&pidData, sizeof(pidData), 1, pipe) < 1) {
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:@"Failed to retrieve authorized executable process identifier." }];
}
fclose(pipe);
return NO;
}
pid_t childPid = (int32_t)CFSwapInt32LittleToHost(pidData);
int status = 0;
pid_t waitResult;
do {
waitResult = waitpid(childPid, &status, 0);
} while (waitResult == -1 && errno == EINTR);
fclose(pipe);
if (waitResult == -1 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Failed to execute authorized executable with result %d and status (%d, %d, %d).", waitResult, status, WIFEXITED(status), WEXITSTATUS(status)] }];
}
return NO;
}
return YES; return YES;
} }
@@ -230,7 +156,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
} }
if (isDirectory != NULL) { if (isDirectory != NULL) {
*isDirectory = [[attributes objectForKey:NSFileType] isEqualToString:NSFileTypeDirectory]; *isDirectory = [attributes[NSFileType] isEqualToString:NSFileTypeDirectory];
} }
return YES; return YES;
@@ -262,7 +188,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
#define XATTR_UTILITY_PATH "/usr/bin/xattr" #define XATTR_UTILITY_PATH "/usr/bin/xattr"
// Recursively remove an xattr at a specified root URL with authentication // Recursively remove an xattr at a specified root URL with authentication
- (BOOL)_removeQuarantineWithAuthenticationAtRootURL:(NSURL *)rootURL error:(NSError *__autoreleasing *)error - (BOOL)_removeXAttrWithAuthentication:(char *__nonnull)xattrName fromRootURL:(NSURL *)rootURL error:(NSError *__autoreleasing *)error
{ {
// Because this is a system utility, it's fine to follow the symbolic link if one exists // Because this is a system utility, it's fine to follow the symbolic link if one exists
if (![_fileManager fileExistsAtPath:@(XATTR_UTILITY_PATH)]) { if (![_fileManager fileExistsAtPath:@(XATTR_UTILITY_PATH)]) {
@@ -279,11 +205,16 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
} }
return NO; return NO;
} }
NSError *executeError = nil; if (![self _acquireAuthorizationWithError:error]) {
BOOL success = [self _authorizeAndExecuteCommand:SUFileOpRemoveQuarantineCommand sourcePath:path destinationPath:NULL error:&executeError]; return NO;
}
BOOL success = AuthorizationExecuteWithPrivilegesAndWait(_auth, XATTR_UTILITY_PATH, kAuthorizationFlagDefaults, (char *[]){ "-s", "-r", "-d", xattrName, path, NULL });
if (!success && error != NULL) { if (!success && error != NULL) {
*error = executeError; NSString *errorMessage = [NSString stringWithFormat:@"Authenticated extended attribute deletion for %@ failed on %@.", [NSString stringWithUTF8String:xattrName], rootURL.path.lastPathComponent];
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:errorMessage }];
} }
return success; return success;
@@ -308,7 +239,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
removedQuarantine = YES; removedQuarantine = YES;
} else { } else {
if (isAccessError(removalError)) { if (isAccessError(removalError)) {
removedQuarantine = [self _removeQuarantineWithAuthenticationAtRootURL:rootURL error:error]; removedQuarantine = [self _removeXAttrWithAuthentication:SUAppleQuarantineIdentifier fromRootURL:rootURL error:error];
attemptedAuthentication = YES; attemptedAuthentication = YES;
} else { } else {
if (success != NULL) { if (success != NULL) {
@@ -341,7 +272,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
// root-level symbolic link. // root-level symbolic link.
NSString *rootURLPath = rootURL.path; NSString *rootURLPath = rootURL.path;
NSDictionary *rootAttributes = [_fileManager attributesOfItemAtPath:rootURLPath error:nil]; NSDictionary *rootAttributes = [_fileManager attributesOfItemAtPath:rootURLPath error:nil];
NSString *rootType = [rootAttributes objectForKey:NSFileType]; // 10.7 can't subscript this NSString *rootType = rootAttributes[NSFileType];
if ([rootType isEqualToString:NSFileTypeDirectory]) { if ([rootType isEqualToString:NSFileTypeDirectory]) {
// The NSDirectoryEnumerator will avoid recursing into any contained // The NSDirectoryEnumerator will avoid recursing into any contained
@@ -360,7 +291,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
} }
// Removes the directory tree rooted at |root| from the file quarantine. // Removes the directory tree rooted at |root| from the file quarantine.
// The quarantine was introduced on macOS 10.5 and is described at: // The quarantine was introduced on OS X 10.5 and is described at:
// //
// http://developer.apple.com/releasenotes/Carbon/RN-LaunchServices/index.html#apple_ref/doc/uid/TP40001369-DontLinkElementID_2 // http://developer.apple.com/releasenotes/Carbon/RN-LaunchServices/index.html#apple_ref/doc/uid/TP40001369-DontLinkElementID_2
// //
@@ -462,6 +393,11 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
return NO; return NO;
} }
if (![self _acquireAuthorizationWithError:error]) {
return NO;
}
char sourcePath[PATH_MAX] = {0}; char sourcePath[PATH_MAX] = {0};
if (![sourceURL.path getFileSystemRepresentation:sourcePath maxLength:sizeof(sourcePath)]) { if (![sourceURL.path getFileSystemRepresentation:sourcePath maxLength:sizeof(sourcePath)]) {
if (error != NULL) { if (error != NULL) {
@@ -477,11 +413,11 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
} }
return NO; return NO;
} }
NSError *executeError = nil; if (!AuthorizationExecuteWithPrivilegesAndWait(_auth, "/bin/cp", kAuthorizationFlagDefaults, (char *[]){ "-Rf", "--", sourcePath, destinationPath, NULL })) {
if (![self _authorizeAndExecuteCommand:SUFileOpCopyCommand sourcePath:sourcePath destinationPath:destinationPath error:&executeError]) {
if (error != NULL) { if (error != NULL) {
*error = executeError; NSString *errorMessage = [NSString stringWithFormat:@"Failed to perform authenticated file copy for %@.", sourceURL.lastPathComponent];
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:errorMessage }];
} }
return NO; return NO;
} }
@@ -570,6 +506,10 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
return NO; return NO;
} }
if (![self _acquireAuthorizationWithError:error]) {
return NO;
}
char sourcePath[PATH_MAX] = {0}; char sourcePath[PATH_MAX] = {0};
if (![sourceURL.path getFileSystemRepresentation:sourcePath maxLength:sizeof(sourcePath)]) { if (![sourceURL.path getFileSystemRepresentation:sourcePath maxLength:sizeof(sourcePath)]) {
if (error != NULL) { if (error != NULL) {
@@ -585,12 +525,11 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
} }
return NO; return NO;
} }
NSError *executeError = nil; if (!AuthorizationExecuteWithPrivilegesAndWait(_auth, "/bin/mv", kAuthorizationFlagDefaults, (char *[]){ "-f", "--", sourcePath, destinationPath, NULL })) {
if (![self _authorizeAndExecuteCommand:SUFileOpMoveCommand sourcePath:sourcePath destinationPath:destinationPath error:&executeError]) {
if (error != NULL) { if (error != NULL) {
NSString *errorMessage = [NSString stringWithFormat:@"Failed to perform authorized file move for %@.", sourceURL.lastPathComponent]; NSString *errorMessage = [NSString stringWithFormat:@"Failed to perform authenticated file move for %@.", sourceURL.lastPathComponent];
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:errorMessage, NSUnderlyingErrorKey: executeError }]; *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:errorMessage }];
} }
return NO; return NO;
} }
@@ -608,19 +547,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
return NO; return NO;
} }
int fileDescriptor = open(path, O_RDONLY | O_SYMLINK); if (chown(path, ownerID.unsignedIntValue, groupID.unsignedIntValue) != 0) {
if (fileDescriptor == -1) {
if (error != NULL) {
*error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to open file descriptor to %@", targetURL.path.lastPathComponent] }];
}
return NO;
}
// We use fchown instead of chown because the latter can follow symbolic links
BOOL success = fchown(fileDescriptor, ownerID.unsignedIntValue, groupID.unsignedIntValue) == 0;
close(fileDescriptor);
if (!success) {
if (errno == EPERM) { if (errno == EPERM) {
if (needsAuth != NULL) { if (needsAuth != NULL) {
*needsAuth = YES; *needsAuth = YES;
@@ -673,7 +600,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
return NO; return NO;
} }
NSNumber *ownerID = [matchFileAttributes objectForKey:NSFileOwnerAccountID]; NSNumber *ownerID = matchFileAttributes[NSFileOwnerAccountID];
if (ownerID == nil) { if (ownerID == nil) {
// shouldn't be possible to error here, but just in case // shouldn't be possible to error here, but just in case
if (error != NULL) { if (error != NULL) {
@@ -682,7 +609,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
return NO; return NO;
} }
NSNumber *groupID = [matchFileAttributes objectForKey:NSFileGroupOwnerAccountID]; NSNumber *groupID = matchFileAttributes[NSFileGroupOwnerAccountID];
if (groupID == nil) { if (groupID == nil) {
// shouldn't be possible to error here, but just in case // shouldn't be possible to error here, but just in case
if (error != NULL) { if (error != NULL) {
@@ -691,8 +618,8 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
return NO; return NO;
} }
NSNumber *targetOwnerID = [targetFileAttributes objectForKey:NSFileOwnerAccountID]; NSNumber *targetOwnerID = targetFileAttributes[NSFileOwnerAccountID];
NSNumber *targetGroupID = [targetFileAttributes objectForKey:NSFileGroupOwnerAccountID]; NSNumber *targetGroupID = targetFileAttributes[NSFileGroupOwnerAccountID];
if ((targetOwnerID != nil && [ownerID isEqualToNumber:targetOwnerID]) && (targetGroupID != nil && [groupID isEqualToNumber:targetGroupID])) { if ((targetOwnerID != nil && [ownerID isEqualToNumber:targetOwnerID]) && (targetGroupID != nil && [groupID isEqualToNumber:targetGroupID])) {
// Assume they're the same even if we don't check every file recursively // Assume they're the same even if we don't check every file recursively
@@ -730,20 +657,21 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
} }
return NO; return NO;
} }
char matchPath[PATH_MAX] = {0}; char userAndGroup[100];
if (![matchURLPath getFileSystemRepresentation:matchPath maxLength:sizeof(matchPath)]) { int written = snprintf(userAndGroup, sizeof(userAndGroup), "%u:%u", ownerID.unsignedIntValue, groupID.unsignedIntValue);
if (error != NULL) { if (written < 0 || written >= 100) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Match file (%@) cannot be represented as a valid file name.", matchURL.path.lastPathComponent] }]; return NO; // No custom error, because it's too unlikely to ever happen
} }
if (![self _acquireAuthorizationWithError:error]) {
return NO; return NO;
} }
NSError *executeError = nil; BOOL success = AuthorizationExecuteWithPrivilegesAndWait(_auth, "/usr/sbin/chown", kAuthorizationFlagDefaults, (char *[]){ "-R", userAndGroup, targetPath, NULL });
BOOL success = [self _authorizeAndExecuteCommand:SUFileOpChangeOwnerAndGroupCommand sourcePath:targetPath destinationPath:matchPath error:&executeError];
if (!success && error != NULL) { if (!success && error != NULL) {
NSString *errorMessage = [NSString stringWithFormat:@"Failed to change owner & group on %@ to match %@ with authorization.", targetURL.path.lastPathComponent, matchURLPath.lastPathComponent]; NSString *errorMessage = [NSString stringWithFormat:@"Failed to change owner:group %@ on %@ with authentication.", [NSString stringWithUTF8String:userAndGroup], targetURL.path.lastPathComponent];
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: errorMessage, NSUnderlyingErrorKey: executeError }]; *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: errorMessage }];
} }
return success; return success;
@@ -772,20 +700,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
return NO; return NO;
} }
int fileDescriptor = open(path, O_RDONLY | O_SYMLINK); if (utimes(path, NULL) == 0) {
if (fileDescriptor == -1) {
if (error != NULL) {
*error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to open file descriptor to %@", targetURL.path.lastPathComponent] }];
}
return NO;
}
// Using futimes() because utimes() follows symbolic links
BOOL updatedTime = (futimes(fileDescriptor, NULL) == 0);
close(fileDescriptor);
if (updatedTime) {
return YES; return YES;
} }
@@ -795,12 +710,15 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
} }
return NO; return NO;
} }
NSError *executeError = nil; if (![self _acquireAuthorizationWithError:error]) {
BOOL success = [self _authorizeAndExecuteCommand:SUFileOpUpdateModificationAndAccessTimeCommand sourcePath:path destinationPath:NULL error:&executeError]; return NO;
}
BOOL success = AuthorizationExecuteWithPrivilegesAndWait(_auth, "/usr/bin/touch", kAuthorizationFlagDefaults, (char *[]){ "--", path, NULL });
if (!success && error != NULL) { if (!success && error != NULL) {
NSString *errorMessage = [NSString stringWithFormat:@"Failed to update modification & access time on %@ with authorization.", targetURL.path.lastPathComponent]; NSString *errorMessage = [NSString stringWithFormat:@"Failed to update modification & access time on %@ with authentication.", targetURL.path.lastPathComponent];
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: errorMessage, NSUnderlyingErrorKey: executeError }]; *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: errorMessage }];
} }
return success; return success;
@@ -808,7 +726,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
// Creates a directory at the item pointed by url // Creates a directory at the item pointed by url
// An item cannot already exist at the url, but the parent must be a directory that exists // An item cannot already exist at the url, but the parent must be a directory that exists
- (BOOL)makeDirectoryAtURL:(NSURL *)url error:(NSError * __autoreleasing *)error - (BOOL)_makeDirectoryAtURL:(NSURL *)url error:(NSError * __autoreleasing *)error
{ {
if ([self _itemExistsAtURL:url]) { if ([self _itemExistsAtURL:url]) {
if (error != NULL) { if (error != NULL) {
@@ -845,16 +763,16 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
} }
return NO; return NO;
} }
NSError *executeError = nil; if (![self _acquireAuthorizationWithError:error]) {
BOOL success = [self _authorizeAndExecuteCommand:SUFileOpMakeDirectoryCommand sourcePath:path destinationPath:NULL error:&executeError]; return NO;
if (!success) { }
if (error != NULL) {
NSString *errorMessage = [NSString stringWithFormat:@"Failed to make directory %@ with authorization.", url.path.lastPathComponent]; BOOL success = AuthorizationExecuteWithPrivilegesAndWait(_auth, "/bin/mkdir", kAuthorizationFlagDefaults, (char *[]){ "--", path, NULL });
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: errorMessage, NSUnderlyingErrorKey: executeError }]; if (!success && error != NULL) {
} NSString *errorMessage = [NSString stringWithFormat:@"Failed to make directory %@ with authentication.", url.path.lastPathComponent];
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: errorMessage }];
} }
return success; return success;
} }
@@ -876,7 +794,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
desiredURL = [directoryURL URLByAppendingPathComponent:[preferredName stringByAppendingFormat:@" (%lu)", (unsigned long)++tagIndex]]; desiredURL = [directoryURL URLByAppendingPathComponent:[preferredName stringByAppendingFormat:@" (%lu)", (unsigned long)++tagIndex]];
} }
return [self makeDirectoryAtURL:desiredURL error:error] ? desiredURL : nil; return [self _makeDirectoryAtURL:desiredURL error:error] ? desiredURL : nil;
} }
- (BOOL)removeItemAtURL:(NSURL *)url error:(NSError * __autoreleasing *)error - (BOOL)removeItemAtURL:(NSURL *)url error:(NSError * __autoreleasing *)error
@@ -900,6 +818,10 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
return NO; return NO;
} }
if (![self _acquireAuthorizationWithError:error]) {
return NO;
}
char path[PATH_MAX] = {0}; char path[PATH_MAX] = {0};
if (![url.path getFileSystemRepresentation:path maxLength:sizeof(path)]) { if (![url.path getFileSystemRepresentation:path maxLength:sizeof(path)]) {
if (error != NULL) { if (error != NULL) {
@@ -907,14 +829,11 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
} }
return NO; return NO;
} }
NSError *executeError = nil;
BOOL success = [self _authorizeAndExecuteCommand:SUFileOpRemoveCommand sourcePath:path destinationPath:NULL error:&executeError];
BOOL success = AuthorizationExecuteWithPrivilegesAndWait(_auth, "/bin/rm", kAuthorizationFlagDefaults, (char *[]){ "-rf", "--", path, NULL });
if (!success && error != NULL) { if (!success && error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to remove %@ with authentication.", url.path.lastPathComponent], NSUnderlyingErrorKey: executeError }]; *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to remove %@ with authentication.", url.path.lastPathComponent] }];
} }
return success; return success;
} }
@@ -989,10 +908,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
if (canUseNewTrashAPI) { if (canUseNewTrashAPI) {
NSError *trashError = nil; NSError *trashError = nil;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpartial-availability"
success = [_fileManager trashItemAtURL:tempItemURL resultingItemURL:NULL error:&trashError]; success = [_fileManager trashItemAtURL:tempItemURL resultingItemURL:NULL error:&trashError];
#pragma clang diagnostic pop
if (!success && error != NULL) { if (!success && error != NULL) {
*error = trashError; *error = trashError;
} }
@@ -1003,34 +919,6 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
return success; return success;
} }
// Unlike other methods, authorization is required to execute this method successfully
- (BOOL)executePackageAtURL:(NSURL *)packageURL error:(NSError * __autoreleasing *)error
{
if (![self _itemExistsAtURL:packageURL]) {
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileNoSuchFileError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to execute package %@ because the file does not exist.", packageURL.path.lastPathComponent] }];
}
return NO;
}
char path[PATH_MAX] = {0};
if (![packageURL.path getFileSystemRepresentation:path maxLength:sizeof(path)]) {
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Package to execute (%@) cannot be represented as a valid file name.", packageURL.path.lastPathComponent] }];
}
return NO;
}
NSError *executeError = nil;
BOOL success = [self _authorizeAndExecuteCommand:SUFileOpInstallCommand sourcePath:path destinationPath:NULL error:&executeError];
if (!success && error != NULL) {
NSString* errorMessage = @"Failed to execute package installer.";
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{NSLocalizedDescriptionKey: errorMessage, NSUnderlyingErrorKey: executeError}];
}
return success;
}
@end @end
#pragma clang diagnostic pop #pragma clang diagnostic pop
+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. 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 macOS's built-in command line installer, `/usr/sbin/installer`. No installation interface is shown to the user. 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.
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. 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 @interface SUGuidedPackageInstaller : SUInstaller
/*! Perform the guided installation */ /*! Perform the guided installation */
+ (void)performInstallationToPath:(NSString *)path fromPath:(NSString *)installerGuide host:(SUHost *)host fileOperationToolPath:(NSString *)fileOperationToolPath versionComparator:(id<SUVersionComparison>)comparator completionHandler:(void (^)(NSError *))completionHandler; + (void)performInstallationToPath:(NSString *)path fromPath:(NSString *)installerGuide host:(SUHost *)host versionComparator:(id<SUVersionComparison>)comparator completionHandler:(void (^)(NSError *))completionHandler;
@end @end
#endif #endif
+119 -9
View File
@@ -6,27 +6,137 @@
// Copyright 2010 Dragon Systems Software Limited. All rights reserved. // Copyright 2010 Dragon Systems Software Limited. All rights reserved.
// //
#import <sys/stat.h>
#import <Security/Security.h>
#import "SUGuidedPackageInstaller.h" #import "SUGuidedPackageInstaller.h"
#import "SUFileManager.h"
static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authorization, const char* executablePath, AuthorizationFlags options, char* const* arguments)
{
sig_t oldSigChildHandler = signal(SIGCHLD, SIG_DFL);
BOOL returnValue = YES;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
/* AuthorizationExecuteWithPrivileges used to support 10.4+; should be replaced with XPC or external process */
if (AuthorizationExecuteWithPrivileges(authorization, executablePath, options, arguments, NULL) == errAuthorizationSuccess)
#pragma clang diagnostic pop
{
int status = 0;
pid_t pid = wait(&status);
if (pid == -1 || !WIFEXITED(status) || WEXITSTATUS(status) != 0)
returnValue = NO;
}
else
returnValue = NO;
signal(SIGCHLD, oldSigChildHandler);
return returnValue;
}
@implementation SUGuidedPackageInstaller (SUGuidedPackageInstallerAuthentication)
+ (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
@implementation SUGuidedPackageInstaller @implementation SUGuidedPackageInstaller
+ (void)performInstallationToPath:(NSString *)destinationPath fromPath:(NSString *)packagePath host:(SUHost *)__unused host fileOperationToolPath:(NSString *)fileOperationToolPath versionComparator:(id<SUVersionComparison>)__unused comparator completionHandler:(void (^)(NSError *))completionHandler + (void)performInstallationToPath:(NSString *)destinationPath fromPath:(NSString *)packagePath host:(SUHost *)__unused host versionComparator:(id<SUVersionComparison>)__unused comparator completionHandler:(void (^)(NSError *))completionHandler
{ {
SUParameterAssert(packagePath); SUParameterAssert(packagePath);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
SUFileManager *fileManager = [SUFileManager fileManagerWithAuthorizationToolPath:fileOperationToolPath];
// Preflight
NSError *error = nil; NSString* installerPath = @"/usr/sbin/installer"; // Mac OS X 10.2+ command line installer tool
BOOL validInstallation = [fileManager executePackageAtURL:[NSURL fileURLWithPath:packagePath] error:&error]; 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]];
}
dispatch_async(dispatch_get_main_queue(), ^{ dispatch_async(dispatch_get_main_queue(), ^{
[self finishInstallationToPath:destinationPath [self finishInstallationToPath:destinationPath
withResult:validInstallation withResult:validInstallation
error:error error:error
completionHandler:completionHandler]; completionHandler:completionHandler];
}); });
}); });
} }
+1 -1
View File
@@ -26,6 +26,7 @@ typedef struct {
- (instancetype)initWithBundle:(NSBundle *)aBundle; - (instancetype)initWithBundle:(NSBundle *)aBundle;
@property (readonly, copy) NSString *bundlePath; @property (readonly, copy) NSString *bundlePath;
@property (readonly) BOOL allowsAutomaticUpdates; @property (readonly) BOOL allowsAutomaticUpdates;
@property (readonly, copy) NSString *appCachePath;
@property (readonly, copy) NSString *installationPath; @property (readonly, copy) NSString *installationPath;
@property (readonly, copy) NSString *name; @property (readonly, copy) NSString *name;
@property (readonly, copy) NSString *version; @property (readonly, copy) NSString *version;
@@ -34,7 +35,6 @@ typedef struct {
@property (getter=isRunningOnReadOnlyVolume, readonly) BOOL runningOnReadOnlyVolume; @property (getter=isRunningOnReadOnlyVolume, readonly) BOOL runningOnReadOnlyVolume;
@property (getter=isBackgroundApplication, readonly) BOOL backgroundApplication; @property (getter=isBackgroundApplication, readonly) BOOL backgroundApplication;
@property (readonly, copy) NSString *publicDSAKey; @property (readonly, copy) NSString *publicDSAKey;
@property (readonly, nonatomic, copy) NSString *publicDSAKeyFileKey;
@property (readonly, copy) NSArray *systemProfile; @property (readonly, copy) NSArray *systemProfile;
- (id)objectForInfoDictionaryKey:(NSString *)key; - (id)objectForInfoDictionaryKey:(NSString *)key;
+24 -38
View File
@@ -11,7 +11,6 @@
#import "SUSystemProfiler.h" #import "SUSystemProfiler.h"
#include <sys/mount.h> // For statfs for isRunningOnReadOnlyVolume #include <sys/mount.h> // For statfs for isRunningOnReadOnlyVolume
#import "SULog.h" #import "SULog.h"
#import "SUFileManager.h"
#if __MAC_OS_X_VERSION_MAX_ALLOWED < 101000 #if __MAC_OS_X_VERSION_MAX_ALLOWED < 101000
@interface NSProcessInfo () @interface NSProcessInfo ()
@@ -72,37 +71,29 @@
} }
// Can we automatically update in the background without bugging the user (e.g, with a administrator password prompt)? // 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 return [[NSFileManager defaultManager] isWritableFileAtPath:self.bundlePath];
// 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]) { - (NSString *)appCachePath
return NO; {
NSArray *cachePaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachePath = nil;
if ([cachePaths count]) {
cachePath = cachePaths[0];
} }
if (!cachePath) {
// Just because we have writability access does not mean we can set the correct owner/group silently SULog(@"Failed to find user's cache directory! Using system default");
// Test if we can set the owner/group on a temporarily created file cachePath = NSTemporaryDirectory();
// 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;
} }
NSURL *tempFileURL = [tempDirectoryURL URLByAppendingPathComponent:tempFilename]; NSString *name = [self.bundle bundleIdentifier];
if (!name) {
BOOL changeOwnerAndGroupSuccess = name = [self name];
[[NSData data] writeToURL:tempFileURL atomically:NO] && }
[suFileManager changeOwnerAndGroupOfItemAtRootURL:tempFileURL toMatchURL:self.bundle.bundleURL error:NULL];
cachePath = [cachePath stringByAppendingPathComponent:name];
[suFileManager removeItemAtURL:tempDirectoryURL error:NULL]; cachePath = [cachePath stringByAppendingPathComponent:@"Sparkle"];
return cachePath;
return changeOwnerAndGroupSuccess;
} }
- (NSString *)installationPath - (NSString *)installationPath
@@ -156,11 +147,11 @@
{ {
// Cache the application icon. // Cache the application icon.
NSString *iconPath = [self.bundle pathForResource:[self.bundle objectForInfoDictionaryKey:@"CFBundleIconFile"] ofType:@"icns"]; NSString *iconPath = [self.bundle pathForResource:[self.bundle objectForInfoDictionaryKey:@"CFBundleIconFile"] ofType:@"icns"];
// According to the macOS docs, "CFBundleIconFile - This key identifies the file containing // According to the OS X docs, "CFBundleIconFile - This key identifies the file containing
// the icon for the bundle. The filename you specify does not need to include the .icns // the icon for the bundle. The filename you specify does not need to include the .icns
// extension, although it may." // extension, although it may."
// //
// However, if it *does* include the '.icns' the above method fails (tested on macOS 10.3.9) so we'll also try: // However, if it *does* include the '.icns' the above method fails (tested on OS X 10.3.9) so we'll also try:
if (!iconPath) { if (!iconPath) {
iconPath = [self.bundle pathForResource:[self.bundle objectForInfoDictionaryKey:@"CFBundleIconFile"] ofType:nil]; iconPath = [self.bundle pathForResource:[self.bundle objectForInfoDictionaryKey:@"CFBundleIconFile"] ofType:nil];
} }
@@ -196,7 +187,7 @@
} }
// More likely, we've got a reference to a Resources file by filename: // More likely, we've got a reference to a Resources file by filename:
NSString *keyFilename = [self publicDSAKeyFileKey]; NSString *keyFilename = [self objectForInfoDictionaryKey:SUPublicDSAKeyFileKey];
if (!keyFilename) { if (!keyFilename) {
return nil; return nil;
} }
@@ -208,11 +199,6 @@
return [NSString stringWithContentsOfFile:keyPath encoding:NSASCIIStringEncoding error:nil]; return [NSString stringWithContentsOfFile:keyPath encoding:NSASCIIStringEncoding error:nil];
} }
- (NSString * __nullable)publicDSAKeyFileKey
{
return [self objectForInfoDictionaryKey:SUPublicDSAKeyFileKey];
}
- (NSArray *)systemProfile - (NSArray *)systemProfile
{ {
return [[SUSystemProfiler sharedSystemProfiler] systemProfileArrayForHost:self]; return [[SUSystemProfiler sharedSystemProfiler] systemProfileArrayForHost:self];
+1 -1
View File
@@ -16,7 +16,7 @@
@interface SUInstaller : NSObject @interface SUInstaller : NSObject
+ (NSString *)installSourcePathInUpdateFolder:(NSString *)inUpdateFolder forHost:(SUHost *)host isPackage:(BOOL *)isPackagePtr isGuided:(BOOL *)isGuidedPtr; + (NSString *)installSourcePathInUpdateFolder:(NSString *)inUpdateFolder forHost:(SUHost *)host isPackage:(BOOL *)isPackagePtr isGuided:(BOOL *)isGuidedPtr;
+ (void)installFromUpdateFolder:(NSString *)inUpdateFolder overHost:(SUHost *)host installationPath:(NSString *)installationPath fileOperationToolPath:(NSString *)fileOperationToolPath versionComparator:(id<SUVersionComparison>)comparator completionHandler:(void (^)(NSError *))completionHandler; + (void)installFromUpdateFolder:(NSString *)updateFolder overHost:(SUHost *)host installationPath:(NSString *)installationPath versionComparator:(id<SUVersionComparison>)comparator completionHandler:(void (^)(NSError *))completionHandler;
+ (void)finishInstallationToPath:(NSString *)installationPath withResult:(BOOL)result error:(NSError *)error completionHandler:(void (^)(NSError *))completionHandler; + (void)finishInstallationToPath:(NSString *)installationPath withResult:(BOOL)result error:(NSError *)error completionHandler:(void (^)(NSError *))completionHandler;
@end @end
+26 -5
View File
@@ -103,7 +103,7 @@
return newAppDownloadPath; return newAppDownloadPath;
} }
+ (void)installFromUpdateFolder:(NSString *)inUpdateFolder overHost:(SUHost *)host installationPath:(NSString *)installationPath fileOperationToolPath:(NSString *)fileOperationToolPath versionComparator:(id<SUVersionComparison>)comparator completionHandler:(void (^)(NSError *))completionHandler + (void)installFromUpdateFolder:(NSString *)inUpdateFolder overHost:(SUHost *)host installationPath:(NSString *)installationPath versionComparator:(id<SUVersionComparison>)comparator completionHandler:(void (^)(NSError *))completionHandler
{ {
BOOL isPackage = NO; BOOL isPackage = NO;
BOOL isGuided = NO; BOOL isGuided = NO;
@@ -113,18 +113,39 @@
[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]; [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 { } else {
if (isPackage && isGuided) { if (isPackage && isGuided) {
[SUGuidedPackageInstaller performInstallationToPath:installationPath fromPath:newAppDownloadPath host:host fileOperationToolPath:fileOperationToolPath versionComparator:comparator completionHandler:completionHandler]; [SUGuidedPackageInstaller performInstallationToPath:installationPath fromPath:newAppDownloadPath host:host versionComparator:comparator completionHandler:completionHandler];
} else if (isPackage) { } else if (isPackage) {
[SUPackageInstaller performInstallationToPath:installationPath fromPath:newAppDownloadPath host:host fileOperationToolPath:fileOperationToolPath versionComparator:comparator completionHandler:completionHandler]; [SUPackageInstaller performInstallationToPath:installationPath fromPath:newAppDownloadPath host:host versionComparator:comparator completionHandler:completionHandler];
} else { } else {
[SUPlainInstaller performInstallationToPath:installationPath fromPath:newAppDownloadPath host:host fileOperationToolPath:fileOperationToolPath versionComparator:comparator completionHandler:completionHandler]; [SUPlainInstaller performInstallationToPath:installationPath fromPath:newAppDownloadPath host:host versionComparator:comparator completionHandler:completionHandler];
} }
} }
} }
+ (void)finishInstallationToPath:(NSString *)__unused installationPath withResult:(BOOL)result error:(NSError *)error completionHandler:(void (^)(NSError *))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
{ {
if (result) { if (result) {
[self mdimportInstallationPath:installationPath];
dispatch_async(dispatch_get_main_queue(), ^{ dispatch_async(dispatch_get_main_queue(), ^{
completionHandler(nil); completionHandler(nil);
}); });
+4 -1
View File
@@ -63,7 +63,11 @@ void SULog(NSString *format, ...)
va_list ap; va_list ap;
va_start(ap, format); va_start(ap, format);
NSString *theStr = [[NSString alloc] initWithFormat:format arguments:ap]; NSString *theStr = [[NSString alloc] initWithFormat:format arguments:ap];
va_end(ap);
#ifdef DEBUG
NSLog(@"Sparkle: %@", theStr); NSLog(@"Sparkle: %@", theStr);
#endif
FILE *logfile = fopen([[SULogFilePath stringByExpandingTildeInPath] fileSystemRepresentation], "a"); FILE *logfile = fopen([[SULogFilePath stringByExpandingTildeInPath] fileSystemRepresentation], "a");
if (logfile) { if (logfile) {
@@ -72,7 +76,6 @@ void SULog(NSString *format, ...)
fwrite([theData bytes], 1, [theData length], logfile); fwrite([theData bytes], 1, [theData length], logfile);
fclose(logfile); fclose(logfile);
} }
va_end(ap);
} }
+4 -11
View File
@@ -20,21 +20,14 @@
{ {
NSOperatingSystemVersion version = { 0, 0, 0 }; NSOperatingSystemVersion version = { 0, 0, 0 };
NSURL *coreServices = [[NSFileManager defaultManager] URLForDirectory:NSCoreServiceDirectory inDomain:NSSystemDomainMask appropriateForURL:nil create:NO error:nil]; NSURL *coreServices = [[NSFileManager defaultManager] URLForDirectory:NSCoreServiceDirectory inDomain:NSSystemDomainMask appropriateForURL:nil create:NO error:nil];
NSURL *url = [coreServices URLByAppendingPathComponent:@"SystemVersion.plist"]; NSArray *components = [[NSDictionary dictionaryWithContentsOfURL:[coreServices URLByAppendingPathComponent:@"SystemVersion.plist"]][@"ProductVersion"] componentsSeparatedByString:@"."];
assert(url != nil); version.majorVersion = components.count > 0 ? [components[0] integerValue] : 0;
NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfURL:url]; version.minorVersion = components.count > 1 ? [components[1] integerValue] : 0;
NSArray *components = [ [dictionary objectForKey: @"ProductVersion"] componentsSeparatedByString:@"."]; version.patchVersion = components.count > 2 ? [components[2] integerValue] : 0;
version.majorVersion = components.count > 0 ? [ [components objectAtIndex:0] integerValue] : 0;
version.minorVersion = components.count > 1 ? [ [components objectAtIndex:1] integerValue] : 0;
version.patchVersion = components.count > 2 ? [ [components objectAtIndex:2] integerValue] : 0;
return version; return version;
} }
#endif #endif
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpartial-availability"
return [[NSProcessInfo processInfo] operatingSystemVersion]; return [[NSProcessInfo processInfo] operatingSystemVersion];
#pragma clang diagnostic pop
} }
+ (BOOL)isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion)version + (BOOL)isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion)version
Loaded 100 of 223 files, more files were not shown because too many files have changed in this diff. Show more