Compare commits

..
127 Commits
Author SHA1 Message Date
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
285 changed files with 8957 additions and 10171 deletions

No files matched your search

-7
View File
@@ -28,13 +28,6 @@ Icon
.Spotlight-V100
.Trashes
# With Carthage, if Sparkle is included as a Git submodule (e.g. with the
# --use-submodules option), the main module's .gitignore can't reach all the
# way inside the submodule to ignore the added Carthage/Build symlink, and Git
# keeps complaining about untracked changes in the submodule forever, which
# is very annoying. To avoid that issue, ignore here in Sparkle instead.
Carthage/Build
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
+3 -1
View File
@@ -1,5 +1,7 @@
language: objective-c
osx_image: xcode8
osx_image: xcode7
before_install:
- brew update
- brew install macmade/tap/xcode-coveralls
script: make ci
after_success: xcode-coveralls --exclude /Applications --exclude Tests --exclude Vendor build/Build/Intermediates/Sparkle.build/Coverage/Sparkle.build/Objects-normal/x86_64
+26 -113
View File
@@ -1,112 +1,25 @@
# 1.15.0
* A new icon! Thanks to 1024jp
* Show alert when an update is sent over insecure HTTP with no DSA key (Zorg)
- If you can't use HTTPS, you must at least sign updates with a DSA key.
* Improved binary delta implementation (Zorg)
* Added improved -validateMenuItem: as a method in SUUpdater.h for public use (Zorg)
* Removed reachability preflight check (Zorg)
* Clear update caches directory before downloading new update (Zorg)
* Check the bundle's parent directory for writability too (Zorg)
* Don't follow symbolic links for file operations (Zorg)
* Don't bring up an authorized dialog during cleanup (Zorg)
* Made Sparkle look for the highest compatible version regardless of timestamps (Zorg)
* Fixed compatibility with 10.7
* Fixed crash on 10.7 - subscript operator not available (kleuter)
* Fixed warnings caused by -Wpartial-availability (Zorg)
* Fixed german l10n. (Sebastian Volland)
* Error code for download errors (Kornel Lesiński)
* Update last update check date when the update driver finishes (Zorg)
* Scale app icon up if needed in Software Update window (Nicholas Riley)
* Don't register for termination notifications more than once (Zorg)
* Don't terminate the app if we're already terminating (Zorg)
* Removed SUEnableAutomaticChecksKeyOld and SUCheckAtStartup constants (Eitot)
* Updated Sparkle framework headers to use modules if modules are available (B. Kevin Hardman)
* Fixed warnings, fixed uses of SULocalizedString (Jerry Krinock)
* Improved signing verifier to take any host and s/application/bundle/ (Zorg)
* Improved Spotlight updates after delta extraction (Zorg)
# 1.14.0 (Mar 11, 2016)
* Disable javascript by default and make it opt-in (Zorg)
* URL-encoding of appcast URLs is preserved (Kornel Lesiński)
* Delegate is asked for fallback updates if delta update fails (Kornel Lesiński)
* Fixed crash on 10.7 - subscript operator not available (kleuter)
* Fixed check of feed URL before delegate had a chance to set it (Kornel Lesiński)
* Re-added support for password-protected dmg images (Andrew K. Boyd)
* Added warning about ATS blocking (Kornel Lesiński)
* Translation fixes for pt-BR. (vitu)
* Add some Japanese lozalized strings (1024jp)
* Made test app available in all languages #695 (LIU Dongyuan / 柳东原)
* Czech localizations update (Frantisek Erben)
* Removed a test resource from the framework bundle (Karl Moskowski)
* Test if the updated app is the frontmost one (Zorg)
* UI Tests for the Test Application (Zorg)
# 1.13.1 (Jan 31, 2016)
Important security fixes:
* Prevent inclusion of local files via file:// XML entities
* Disable redirects to non-HTTP URLs in release notes webview
# 1.13.0 (Dec 18, 2015)
* Changed framework's bundle ID from `org.andymatuschak.Sparkle` to `org.sparkle-project.Sparkle`.
# 1.12.0 (Dec 13, 2015)
* Rewritten file operations for updating an app (Zorg)
- Ensuring atomic move operations, robust error handling.
- Faster.
- Using modern APIs where possible (no FSPathMakeRef, FSGetCatalogInfo, FSFindFolder, etc.)
- Strong documentation, easier to read code.
* Automatic updates won't be installed if the system is about to shut off (Zorg)
* Deprecated serving over HTTP without DSA (Zorg)
- Note that Apple has deprecated insecure HTTP in macOS 10.11
* Improved Autoupdate application (Zorg)
* Do all the installation work after the runloop is set up
* TerminationListener only does termination listening now
* Handle cases where host path is not installation path and host path is not desired executable path
* Don't show Autoupdate dock icon if we shouldn't show UI
* Update modification & access time for new update
* Added installUpdatesIfAvailable (Ian Langworth)
* Removed extensions from shell scripts (Jake Petroules)
* Rewritten test app so it works again, and from a local web server (Zorg)
* Replaced use of Python with built-in web server (Kevin Wojniak)
* Set LD_RUNPATH_SEARCH_PATHS in Podspec (Jake Petroules)
* Don't install automatic updates if the system might shut off (Zorg)
* Don't show Autoupdate dock icon if we shouldn't show UI (Zorg)
* Updated layout constraints when removing release notes (Zorg)
* Improved BinaryDelta error handling & logging (Zorg)
* Refactored quarantine removal (Zorg)
* Fixed German localization (1024jp)
* Updated zh_CN translation (LIU Dongyuan / 柳东原)
* Updated Mac models list until July 2015 (Gabriel Ulici)
* Updated Polish translation (Kornel Lesiński)
* Updated Xcode project languages for which we have translations (Jake Petroules)
* Updated XIB files (Kornel Lesiński)
* Use NSByteCountFormatter if available (Jake Petroules)
* Declared protocols on SUUpdateAlert for the 10.11 SDK (Daniel Jalkut)
* Silenced warning about casting away const-ness and -Wassign-enum (Daniel Jalkut)
* Added script to generate a report comparing the Sparkle.strings files (Kevin Wojniak)
* Check for empty strings (as well as nil) in SUHost's -name method (Karl Moskowski)
* Don't follow symlinks for checking file existence (Zorg)
* Unit tests in Swift (Zorg, Jake Petroules)
* Fixed framework imports (Felix Schulze)
* Fixed issues with copying files from different mounted drives (Zorg)
* Disallowed automatic updates when user can't write to the bundle (Zorg)
* Set the task working directories instead of changing the process working directory (Kevin Wojniak)
# 1.11.1 (Nov 9, 2015)
* Don't install automatic updates when system is about to shut down
# 1.11.0 (Aug 24, 2015)
# 1.11.0
* Big improvements to code signing and DSA verification
- Sparkle now checks not only whether an update is correctly signed, but also whether the updated version will be able to verify future updates. Updates now must either use DSA keys correctly, or not try to use them at all. Same goes for Apple Code Signing.
- Rely on code signing and the DSA key in the new app instead of appcast. If the new app has a public DSA key, then the appcast item must have a DSA signature for the app, even if the app is code signed. (Zorg)
* Deprecated serving over http without DSA (Zorg)
* Removed extensions from shell scripts (Jake Petroules)
* Improved Autoupdate application (Zorg)
* Do all the installation work after the runloop is set up
* TerminationListener only does termination listening now
* Handle cases where host path is not installation path and host path is not desired executable path
* Set LD_RUNPATH_SEARCH_PATHS in Podspec. (Jake Petroules)
* Updated layout constraints when removing release notes (Zorg)
* Fix German localization (1024jp)
* Updated zh_CN translation (LIU Dongyuan / 柳东原)
* Updated Mac models list until July 2015 (Gabriel Ulici)
* Updated Xcode project languages for which we have translations (Jake Petroules)
* Use NSByteCountFormatter if available (Jake Petroules)
* Declared protocols on SUUpdateAlert for the 10.11 SDK (Daniel Jalkut)
* Silenced warning about casting away const-ness and -Wassign-enum (Daniel Jalkut)
* Rewritten test app so it works again, and from a local web server (Zorg)
* Added script to generate a report comparing the Sparkle.strings files (Kevin Wojniak)
* More verbose error message when DSA keys don't match (Kornel Lesiński)
* Added delegate methods for pre-download and immediately post-failed-download (Isaac Greenspan)
* Fix Lucida Grande is always used for release notes (LIU Dongyuan / 柳东原)
@@ -120,7 +33,7 @@ Important security fixes:
* Added logging of appcast/download URL on error (Kornel Lesiński)
* More robust reading of Autoupdate.app path from Sparkle bundle
# 1.10.0 (Apr 26, 2015)
# 1.10.0
* Massive improvements to the BinaryDelta tool (Zorg)
- Ability to track file permissions (Zorg)
@@ -136,7 +49,7 @@ Important security fixes:
* Stdout used for non error outputs (JDuquennoy)
* French locale update (Kent Sutherland)
# 1.9.0 (Jan 26, 2015)
# 1.9.0
* Added SUUpdater delegate method for failures. (Benjamin Gordon)
* Make the error definitions public (C.W. Betts)
@@ -146,7 +59,7 @@ Important security fixes:
* Use Library/Caches rather than app support directory (Kornel Lesiński)
* Check for a modal window being onscreen before trying to put up the Sparkle prompt (Alf Watt)
* Fixed crashes on 10.7 (Chris Campbell, Ger Teunis)
* Fixed Sparkle tags parsing (Tamás Lustyik)
* Fixed Sparkle tags parsing (Tamás Lustyik)
* SULog code cleanups (Kevin Wojniak)
* Make sure CFBundleVersion is a semantic version number. (Jake Petroules)
* Replace typedef enums with typedef NS_ENUM to make Swift happier (C.W. Betts)
@@ -159,18 +72,18 @@ Important security fixes:
* Turkish localization fixes (Emir)
* Proofing of Ukrainian localization (Vera Tkachenko)
# 1.8.0 (Jul 26, 2014)
# 1.8.0
* 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)
* Converted Sparkle to ARC (C.W. Betts)
* Converted ivars to properties. (Jake Petroules)
* 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)
* Added Greek localization
# 1.7.1 (Jul 2, 2014)
# 1.7.1
* Removed option to install unverified updates (Kornel Lesiński)
* Added detailed log when code signing verification fails (Sam Deane)
@@ -187,7 +100,7 @@ Important security fixes:
# 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)
* Switched to modern Obj-C runtime and new literals syntax
* 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/
+6 -9
View File
@@ -1,8 +1,7 @@
// Common
SPARKLE_BUNDLE_IDENTIFIER = org.sparkle-project.Sparkle
SPARKLE_BUNDLE_IDENTIFIER = org.andymatuschak.Sparkle
SPARKLE_RELAUNCH_TOOL_NAME = Autoupdate
SPARKLE_FILEOP_TOOL_NAME = fileop
SPARKLE_APPEND_VERSION_NUMBER = 1
@@ -16,8 +15,8 @@ SPARKLE_AUTOMATED_DOWNGRADES = 0
SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME = 0
SPARKLE_VERSION_MAJOR = 1
SPARKLE_VERSION_MINOR = 15
SPARKLE_VERSION_PATCH = 1
SPARKLE_VERSION_MINOR = 12
SPARKLE_VERSION_PATCH = 0
SPARKLE_VERSION = $(SPARKLE_VERSION_MAJOR).$(SPARKLE_VERSION_MINOR).$(SPARKLE_VERSION_PATCH)
CURRENT_PROJECT_VERSION = $(SPARKLE_VERSION)
@@ -32,15 +31,12 @@ MACOSX_DEPLOYMENT_TARGET = 10.7
PRODUCT_NAME = ${TARGET_NAME}
PRODUCT_BUNDLE_IDENTIFIER = org.sparkle-project.Sparkle.${PRODUCT_NAME:rfc1034identifier}
GCC_PREPROCESSOR_DEFINITIONS_COMMON = SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME=$(SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME) SPARKLE_AUTOMATED_DOWNGRADES=$(SPARKLE_AUTOMATED_DOWNGRADES) SPARKLE_APPEND_VERSION_NUMBER=$(SPARKLE_APPEND_VERSION_NUMBER) SPARKLE_BUNDLE_IDENTIFIER=\"$(SPARKLE_BUNDLE_IDENTIFIER)\" SPARKLE_RELAUNCH_TOOL_NAME=\"$(SPARKLE_RELAUNCH_TOOL_NAME)\" 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
GCC_ENABLE_PASCAL_STRINGS = NO
GCC_NO_COMMON_BLOCKS = YES;
COMBINE_HIDPI_IMAGES = NO;
// Enable warnings
CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;
CLANG_ANALYZER_SECURITY_FLOATLOOPCOUNTER = YES
CLANG_ANALYZER_SECURITY_INSECUREAPI_RAND = YES
CLANG_ANALYZER_SECURITY_INSECUREAPI_STRCPY = YES
@@ -55,6 +51,7 @@ CLANG_WARN_OBJC_EXPLICIT_OWNERSHIP_TYPE = YES
CLANG_WARN_OBJC_IMPLICIT_ATOMIC_PROPERTIES = YES
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES
CLANG_WARN_OBJC_MISSING_PROPERTY_SYNTHESIS = YES
CLANG_WARN_OBJC_RECEIVER_WEAK = YES
CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES
CLANG_WARN_SUSPICIOUS_IMPLICIT_CONVERSION = YES
CLANG_WARN_UNREACHABLE_CODE = YES
@@ -90,4 +87,4 @@ CLANG_ENABLE_MODULES[sdk=macosx10.8] = NO
WARNING_CFLAGS_EXTRA = -Wno-custom-atomic-properties -Wno-implicit-atomic-properties
// Turn on all warnings, then disable a few which are almost impossible to avoid
WARNING_CFLAGS = -Wall -Weverything -Wno-unused-macros -Wno-gnu-statement-expression -Wno-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
OTHER_LDFLAGS = -Wl,-U,_NSURLQuarantinePropertiesKey
SKIP_INSTALL = YES
DEFINES_MODULE = YES
DEFINES_MODULE = NO
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
LD_RUNPATH_SEARCH_PATHS = @executable_path/../Frameworks
PRODUCT_BUNDLE_IDENTIFIER = org.sparkle-project.SparkleTestApp
GCC_PREPROCESSOR_DEFINITIONS = $(inherited) CODE_SIGN_IDENTITY="$(CODE_SIGN_IDENTITY)"
-13
View File
@@ -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
#include "ConfigSwift.xcconfig"
INFOPLIST_FILE = Tests/SparkleTests-Info.plist
WRAPPER_EXTENSION = xctest
OTHER_CFLAGS = $(inherited) -iframework"$(DEVELOPER_FRAMEWORKS_DIR)" -iframework"$(PLATFORM_DIR)/Developer/Library/Frameworks"
@@ -1,2 +1 @@
#include "ConfigUnitTest.xcconfig"
#include "ConfigSwiftDebug.xcconfig"
@@ -1,2 +1 @@
#include "ConfigUnitTest.xcconfig"
#include "ConfigSwiftRelease.xcconfig"
-7
View File
@@ -2,13 +2,6 @@
set -e
if [ "$ACTION" = "" ] ; then
# Sanity check that the Podspec version matches the Sparkle version
spec_version=$(printf "require 'cocoapods'\nspec = %s\nprint spec.version" "$(cat "$SRCROOT/Sparkle.podspec")" | LANG=en_US.UTF-8 ruby)
if [ "$spec_version" != "$CURRENT_PROJECT_VERSION" ] ; then
echo "podspec version '$spec_version' does not match the current project version '$CURRENT_PROJECT_VERSION'" >&2
exit 1
fi
rm -rf "$CONFIGURATION_BUILD_DIR/staging"
rm -f "Sparkle-$CURRENT_PROJECT_VERSION.tar.bz2"
+5 -11
View File
@@ -13,20 +13,14 @@ if [ -z "$SRCROOT" ] || \
exit 1
fi
version="$CURRENT_PROJECT_VERSION"
# Get version in format 1.x.x-commits-hash
gitversion=$( cd "$SRCROOT"; git describe --tags --match '[12].*' || true )
if [ -z "$gitversion" ] ; then
echo "$0: Can't find a Git hash!" 1>&2
# Get the current Git master hash
version=$(cd "$SRCROOT" ; git show-ref --abbrev heads/master | awk '{print $1}')
if [ -z "$version" ] ; then
echo "$0: Can't find a Git hash!" 1>&2
exit 0
fi
# remove everything before the first "-" to keep the hash part only
versionsuffix=${gitversion#*-};
if [ "$versionsuffix" != "$gitversion" ]; then
version="$version $versionsuffix"
fi
version="$CURRENT_PROJECT_VERSION git-$version"
# and use it to set the CFBundleShortVersionString value
export PATH="$PATH:/usr/libexec"
+2 -2
View File
@@ -1,6 +1,6 @@
PROJECT_NAME = Sparkle
PROJECT_NUMBER = 1.14.0
PROJECT_BRIEF = "A software update framework for macOS"
PROJECT_NUMBER = 1.7.1
PROJECT_BRIEF = "A software update framework for OS X"
PROJECT_LOGO = Resources/Images.xcassets/AppIcon.appiconset/icon_32x32@2x.png
RECURSIVE = YES
BIN
View File
Binary file not shown.
-5
View File
@@ -13,8 +13,6 @@ localizable-strings:
release:
xcodebuild -scheme Distribution -configuration Release -derivedDataPath "$(BUILDDIR)" build
open -R "$(BUILDDIR)/Build/Products/Release/Sparkle-"*.tar.bz2
cat Sparkle.podspec
@echo "Don't forget to update CocoaPods! pod trunk push"
build:
xcodebuild clean build
@@ -22,9 +20,6 @@ build:
test:
xcodebuild -scheme Distribution -configuration Debug test
uitest:
xcodebuild -scheme UITests -configuration Debug test
ci:
for i in {7..9} ; do \
if xcrun --sdk "macosx10.$$i" --show-sdk-path 2> /dev/null ; then \
-24
View File
@@ -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)
+10 -20
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) <a href='https://app.ship.io/dashboard#/jobs/8814/history' target='_blank'><img src='https://app.ship.io/jobs/V3PoCLcN5ft5Pnq0/build_status.png' height='20' /></a> [![Coverage Status](https://coveralls.io/repos/sparkle-project/Sparkle/badge.svg?branch=master&service=github)](https://coveralls.io/github/sparkle-project/Sparkle?branch=master)
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
* Up-to-date with 10.11 SDK and Xcode 7. Supports macOS 10.7+.
* Important security fixes.
* Up-to-date with 10.11 SDK and Xcode 7. Supports OS X 10.7+.
* Cleaned up and modernized code, using ARC and Autolayout.
* Merged bugfixes, security fixes and some features from multiple Sparkle forks.
* Truly automatic background updates (no UI at all) when user agreed to "Automatically download and install updates in the future."
* Ability to mark updates as critical.
* Progress and status notifications for the host app.
@@ -17,41 +17,31 @@ An easy-to-use software update framework for Cocoa developers.
## Features
* Seamless integration—there's no mention of Sparkle; your icons and app name are used.
* True self-updating—the user can choose to automatically download and install all updates.
* Displays a detailed progress window to the user.
* Supports authentication for installing in secure locations.
* Supports Apple Code Signing and DSA signatures for ultra-secure updates.
* Easy to install. Sparkle requires no code in your app, so it's trivial to upgrade or remove the framework.
* Uses 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.
* Sparkle doesn't bug the user until second launch for better first impressions.
* Seamless integration—there's no mention of Sparkle; your icons and app name are used.
* Deep delegate support to make Sparkle work exactly as you need.
* Optionally sends system information to the server when checking for updates.
* Supports bundles, preference panes, plugins, and other non-.app software. Can install .pkg files for more complicated products.
* Supports branches due to minimum OS version requirements.
## Requirements
## Developers
* Runtime: macOS 10.7 or greater
* Build: Xcode 5 and 10.8 SDK or greater
* HTTPS server for serving updates (see [App Transport Security](http://sparkle-project.org/documentation/app-transport-security/))
Building Sparkle requires Xcode 5 or above.
## API
### API
Sparkle is built with `-fvisibility=hidden -fvisibility-inlines-hidden` which means no symbols are exported by default.
If you are adding a symbol to the public API you must decorate the declaration with the `SU_EXPORT` macro (grep the source code for examples).
## Building the distribution package
### Building the distribution package
`cd` to the root of the Sparkle source tree and run `make release`. Sparkle-*VERSION*.tar.bz2 will be created in a temporary directory and revealed in Finder after the build has completed.
Alternatively, build the Distribution scheme in the Xcode UI.
## Code of Conduct
We pledge to have an open and welcoming environment. See our [Code of Conduct](CODE_OF_CONDUCT.md).
## Project Sponsor
[StackPath](https://www.stackpath.com/?utm_source=sparkle-github&utm_medium=link&utm_campaign=readme-footer)
Binary file not shown.
@@ -43,21 +43,18 @@
"scale" : "1x"
},
{
"size" : "256x256",
"idiom" : "mac",
"filename" : "icon_256x256@2x.png",
"size" : "256x256",
"scale" : "2x"
},
{
"size" : "512x512",
"idiom" : "mac",
"filename" : "icon_512x512.png",
"size" : "512x512",
"scale" : "1x"
},
{
"size" : "512x512",
"idiom" : "mac",
"filename" : "icon_512x512@2x.png",
"size" : "512x512",
"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 -7
View File
@@ -47,13 +47,7 @@
<key>iMac14,4</key>
<string>iMac (Core i5, 21.5 inch Mid 2014)</string>
<key>iMac15,1</key>
<string>iMac (Retina 5K Core i5 or i7, 27 inch Late 2014 or Mid 2015)</string>
<key>iMac16,1</key>
<string>iMac (Core i5, 21,5 inch Late 2015)</string>
<key>iMac16,2</key>
<string>iMac (Retina 4K Core i5 or i7, 21.5 inch Late 2015)</string>
<key>iMac17,1</key>
<string>iMac (Retina 5K Core i5 or i7, 27 inch Late 2015)</string>
<string>iMac (Retina 5K Core i5 or i7, 27 inch 2014 or 2015)</string>
<key>MacBook1,1</key>
<string>MacBook (Core Duo)</string>
<key>MacBook2,1</key>
+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/">
<channel>
<title>Your Great App's Changelog</title>
<link>http://you.com/app/appcast.xml</link>
<description>Most recent changes with links to updates.</description>
<language>en</language>
<item>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 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>
+7 -10
View File
@@ -1,29 +1,26 @@
Pod::Spec.new do |s|
s.name = "Sparkle"
s.version = "1.15.1"
s.summary = "A software update framework for macOS"
s.version = "1.11.0"
s.summary = "A software update framework for OS X"
s.description = "Sparkle is an easy-to-use software update framework for Cocoa developers."
s.homepage = "http://sparkle-project.org"
s.documentation_url = "http://sparkle-project.org/documentation/"
s.screenshot = "http://sparkle-project.org/images/screenshot-noshadow@2x.png"
s.license = {
:type => 'MIT',
:file => 'LICENSE'
}
s.authors = {
'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',
'Kornel Lesiński' => 'pornel@pornel.net',
'C.W. Betts' => 'computers57@hotmail.com',
'Jake Petroules' => 'jake.petroules@petroules.com',
}
s.platform = :osx, '10.7'
s.source = { :http => "https://github.com/sparkle-project/Sparkle/releases/download/#{s.version}/Sparkle-#{s.version}.tar.bz2" }
s.source_files = 'Sparkle.framework/Versions/A/Headers/*.h'
s.public_header_files = 'Sparkle.framework/Versions/A/Headers/*.h'
s.vendored_frameworks = 'Sparkle.framework'
s.vendored_framework = 'Sparkle.framework'
s.resources = 'Sparkle.framework'
s.xcconfig = {
'FRAMEWORK_SEARCH_PATHS' => '"${PODS_ROOT}/Sparkle"',
'LD_RUNPATH_SEARCH_PATHS' => '@loader_path/../Frameworks'
File diff suppressed because it is too large. Load diff
@@ -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"?>
<Scheme
LastUpgradeVersion = "0800"
LastUpgradeVersion = "0700"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0800"
LastUpgradeVersion = "0700"
version = "2.0">
<BuildAction
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>
<key>NSPrincipalClass</key>
<string>NSApplication</string>
<key>CFBundleIconFile</key>
<string>${ASSETCATALOG_COMPILER_APPICON_NAME}.icns</string>
</dict>
</plist>
+47 -77
View File
@@ -3,6 +3,7 @@
#import "SUHost.h"
#import "SUStandardVersionComparator.h"
#import "SUStatusController.h"
#import "SUPlainInstallerInternals.h"
#import "SULog.h"
#include <unistd.h>
@@ -45,6 +46,7 @@ static const NSTimeInterval SUParentQuitCheckInterval = .25;
{
[self.watchdogTimer invalidate];
completionBlock();
completionBlock = nil;
}
- (void)startListeningWithCompletion:(void (^)(void))completionBlock
@@ -70,13 +72,6 @@ static const NSTimeInterval SUParentQuitCheckInterval = .25;
*/
static const NSTimeInterval SUInstallationTimeLimit = 5;
/*!
* Terminate the application after a delay from launching the new update to avoid OS activation issues
* This delay should be be high enough to increase the likelihood that our updated app will be launched up front,
* but should be low enough so that the user doesn't ponder why the updater hasn't finished terminating yet
*/
static const NSTimeInterval SUTerminationTimeDelay = 0.5;
@interface AppInstaller : NSObject <NSApplicationDelegate>
/*
@@ -102,8 +97,6 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.5;
@property (nonatomic, assign) BOOL shouldRelaunch;
@property (nonatomic, assign) BOOL shouldShowUI;
@property (nonatomic, assign) BOOL isTerminating;
@end
@implementation AppInstaller
@@ -115,7 +108,6 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.5;
@synthesize relaunchPath = _relaunchPath;
@synthesize shouldRelaunch = _shouldRelaunch;
@synthesize shouldShowUI = _shouldShowUI;
@synthesize isTerminating = _isTerminating;
- (instancetype)initWithHostPath:(NSString *)hostPath relaunchPath:(NSString *)relaunchPath parentProcessId:(pid_t)parentProcessId updateFolderPath:(NSString *)updateFolderPath shouldRelaunch:(BOOL)shouldRelaunch shouldShowUI:(BOOL)shouldShowUI
{
@@ -137,16 +129,12 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.5;
{
[self.terminationListener startListeningWithCompletion:^{
self.terminationListener = nil;
if (self.shouldShowUI) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(SUInstallationTimeLimit * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
if (!self.isTerminating) {
// Show app icon in the dock
ProcessSerialNumber psn = { 0, kCurrentProcess };
TransformProcessType(&psn, kProcessTransformToForegroundApplication);
}
});
}
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(SUInstallationTimeLimit * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
// Show app icon in the dock
ProcessSerialNumber psn = { 0, kCurrentProcess };
TransformProcessType(&psn, kProcessTransformToForegroundApplication);
});
[self install];
}];
@@ -162,32 +150,21 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.5;
self.statusController = [[SUStatusController alloc] initWithHost:host];
[self.statusController setButtonTitle:SULocalizedString(@"Cancel Update", @"") target:nil action:Nil isDefault:NO];
[self.statusController beginActionWithTitle:SULocalizedString(@"Installing update...", @"")
maxProgressValue: 0 statusText: @""];
maxProgressValue: 0 statusText: @""];
[self.statusController showWindow:self];
}
NSString *fileOperationToolPath = [[[[NSBundle mainBundle] executablePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@""SPARKLE_FILEOP_TOOL_NAME];
if (![[NSFileManager defaultManager] fileExistsAtPath:fileOperationToolPath]) {
SULog(@"Potential Installation Error: File operation tool path %@ is not found", fileOperationToolPath);
}
[SUInstaller installFromUpdateFolder:self.updateFolderPath
overHost:host
installationPath:installationPath
fileOperationToolPath:fileOperationToolPath
versionComparator:[SUStandardVersionComparator defaultComparator]
completionHandler:^(NSError *error) {
if (error) {
NSError *underlyingError = [error.userInfo objectForKey:NSUnderlyingErrorKey];
if (underlyingError == nil || underlyingError.code != SUInstallationCancelledError) {
SULog(@"Installation Error: %@", error);
if (self.shouldShowUI) {
NSAlert *alert = [[NSAlert alloc] init];
alert.messageText = @"";
alert.informativeText = [NSString stringWithFormat:@"%@", [error localizedDescription]];
[alert runModal];
}
if (self.shouldShowUI) {
NSAlert *alert = [[NSAlert alloc] init];
alert.messageText = @"";
alert.informativeText = [NSString stringWithFormat:@"%@", [error localizedDescription]];
[alert runModal];
}
exit(EXIT_FAILURE);
} else {
@@ -204,44 +181,27 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.5;
}];
}
- (void)cleanupAndTerminateWithPathToRelaunch:(NSString *)relaunchPath
- (void)cleanupAndTerminateWithPathToRelaunch:(NSString *)relaunchPath __attribute__((noreturn))
{
self.isTerminating = YES;
dispatch_block_t cleanupAndExit = ^{
NSError *theError = nil;
if (![[NSFileManager defaultManager] removeItemAtPath:self.updateFolderPath error:&theError]) {
SULog(@"Couldn't remove update folder: %@.", theError);
}
[[NSFileManager defaultManager] removeItemAtPath:[[NSBundle mainBundle] bundlePath] error:NULL];
exit(EXIT_SUCCESS);
};
if (self.shouldRelaunch) {
// The auto updater can terminate before the newly updated app is finished launching
// If that happens, the OS may not make the updated app active and frontmost
// (Or it does become frontmost, but the OS backgrounds it afterwards.. It's some kind of timing/activation issue that doesn't occur all the time)
// The only remedy I've been able to find is waiting an arbitrary delay before exiting our application
// Don't use -launchApplication: because we may not be launching an application. Eg: it could be a system prefpane
if (![[NSWorkspace sharedWorkspace] openFile:relaunchPath]) {
SULog(@"Failed to launch %@", relaunchPath);
NSError *error = nil;
[[NSWorkspace sharedWorkspace] launchApplicationAtURL:[NSURL fileURLWithPath:relaunchPath]
options:NSWorkspaceLaunchNewInstance
configuration:nil
error:&error];
if (error.code != noErr)
{
SULog(@"%ld - %@", error.code, error.localizedDescription);
}
[self.statusController close];
// Don't even think about hiding the app icon from the dock if we've already shown it
// Transforming the app back to a background one has a backfiring effect, decreasing the likelihood
// that the updated app will be brought up front
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(SUTerminationTimeDelay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
cleanupAndExit();
});
} else {
cleanupAndExit();
}
NSError *theError = nil;
if (![SUPlainInstaller _removeFileAtPath:self.updateFolderPath error:&theError])
SULog(@"Couldn't remove update folder: %@.", theError);
[[NSFileManager defaultManager] removeItemAtPath:[[NSBundle mainBundle] bundlePath] error:NULL];
exit(EXIT_SUCCESS);
}
@end
@@ -257,19 +217,29 @@ int main(int __unused argc, const char __unused *argv[])
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) {
[application activateIgnoringOtherApps:YES];
}
AppInstaller *appInstaller = [[AppInstaller alloc] initWithHostPath:[args objectAtIndex:1]
relaunchPath:[args objectAtIndex:2]
parentProcessId:[[args objectAtIndex:3] intValue]
updateFolderPath:[args objectAtIndex:4]
shouldRelaunch:(args.count > 5) ? [[args objectAtIndex:5] boolValue] : YES
AppInstaller *appInstaller = [[AppInstaller alloc] initWithHostPath:args[1]
relaunchPath:args[2]
parentProcessId:[args[3] intValue]
updateFolderPath:args[4]
shouldRelaunch:(args.count > 5) ? [args[5] boolValue] : YES
shouldShowUI:shouldShowUI];
NSConnection *connection = [[NSConnection alloc] init];
[connection setRootObject:appInstaller];
if (![connection registerName:[NSString stringWithFormat:@"Sparkle-%@", [NSBundle bundleWithPath:appInstaller.hostPath].bundleIdentifier]])
{
SULog(@"%@ server: could not register server. Is one already running?\n", args.firstObject);
}
[application setDelegate:appInstaller];
[application run];
// Ensure connection is not deallocated by ARC before caling -[NSApplication run]
[connection class];
}
return EXIT_SUCCESS;
+10 -10
View File
@@ -3,7 +3,7 @@
import Foundation
func die(msg: String) {
print("ERROR: \(msg)")
println("ERROR: \(msg)")
exit(1)
}
@@ -28,8 +28,8 @@ if enStringsDict == nil {
}
let enStringsDictKeys = enStringsDict!.allKeys
let dirPath = NSString(string: sparkleRoot! + "/Sparkle")
let dirContents = try! NSFileManager.defaultManager().contentsOfDirectoryAtPath(dirPath as String)
let dirPath = sparkleRoot! + "/Sparkle"
let dirContents = NSFileManager.defaultManager().contentsOfDirectoryAtPath(dirPath, error: nil) as! [String]
let css =
"body { font-family: sans-serif; font-size: 10pt; }" +
"h1 { font-size: 12pt; }" +
@@ -51,14 +51,14 @@ head.addChild(NSXMLElement(name: "style", stringValue: css))
let locale = NSLocale.currentLocale()
for dirEntry in dirContents {
if NSString(string: dirEntry).pathExtension != "lproj" || dirEntry == "en.lproj" {
if dirEntry.pathExtension != "lproj" || dirEntry == "en.lproj" {
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!))"))
let stringsPath = NSString(string: dirPath.stringByAppendingPathComponent(dirEntry)).stringByAppendingPathComponent("Sparkle.strings")
let stringsPath = dirPath.stringByAppendingPathComponent(dirEntry).stringByAppendingPathComponent("Sparkle.strings")
let stringsDict = NSDictionary(contentsOfFile: stringsPath)
if stringsDict == nil {
die("Invalid strings file \(dirEntry)")
@@ -90,12 +90,12 @@ for dirEntry in dirContents {
let sorter = { (s1: String, s2: String) -> Bool in
return s1 < s2
}
missing.sortInPlace(sorter)
unlocalized.sortInPlace(sorter)
unused.sortInPlace(sorter)
missing.sort(sorter)
unlocalized.sort(sorter)
unused.sort(sorter)
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 {
+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">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<string>English</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<string>${EXECUTABLE_NAME}</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<string>${EXECUTABLE_NAME}</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<string>${PRODUCT_NAME}</string>
<key>CFBundlePackageType</key>
<string>BNDL</string>
<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>
@@ -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,
SUInstallServiceTaskAuthCopyPath = 2LL,
SUInstallServiceTaskLaunchTask = 3LL
};
static const char * SUInstallServiceTaskTypeKey = "task_type"; // int64_t
// SUInstallServiceTaskCopyPath & SUInstallServiceTaskAuthCopyPath keys
static const char * SUInstallServiceSourcePathKey = "source_path"; // c-string
static const char * SUInstallServiceDestinationPathKey = "destination_path"; // c-string
static const char * SUInstallServiceAppendVersionKey = "append_version"; // bool
// SUInstallServiceTaskLaunchTask keys
static const char * SUInstallServiceLaunchTaksPathKey = "launch_task_path";
static const char * SUInstallServiceLaunchTaskArgumentsKey = "launch_task_arguments"; // xpc_array of c-strings
static const char * SUInstallServiceLaunchTaskEnvironmentKey = "launch_task_environment"; // xpc_dictionary with keys and values of c-strings
static const char * SUInstallServiceLaunchTaskCurrentDirKey = "launch_task_cur_dir"; // c-string
static const char * SUInstallServiceLaunchTaskInputDataKey = "launch_task_input_data"; // xpc_data
static const char * SUInstallServiceLaunchTaskReplyImmediatelyKey = "launch_task_reply_immediately"; // bool
// Reply keys
static const char * SUInstallServiceErrorCodeKey = "error_code"; // int64_t
static const char * SUInstallServiceErrorLocalizedDescriptionKey = "error_localized_description"; // c-string
static const char * SUInstallServiceLaunchTaskOutputDataKey = "launch_task_output_data"; // xpc_data
#endif
+30
View File
@@ -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)copyPathWithAuthentication:(NSString *)src overPath:(NSString *)dst appendVersion:(BOOL)appendVersion error:(NSError *__autoreleasing *)outError;
+ (BOOL)copyPathContent:(NSString *)src toDirectory:(NSString *)dstDir error:(NSError *__autoreleasing *)outError; // dstDir will be created if absent
+ (void)launchTaskWithLaunchPath:(NSString *)path arguments:(NSArray *)arguments;
+ (void)launchTaskWithPath:(NSString *)launchPath
arguments:(NSArray *)arguments
environment:(NSDictionary *)environment
currentDirectoryPath:(NSString *)currentDirPath
inputData:(NSData *)inputData
waitUntilDone:(BOOL)waitUntilDone
completionHandler:(void (^)(int result, NSData *outputData))completionHandler;
@end
FOUNDATION_EXPORT BOOL SUShouldUseXPCInstaller(void);
+275
View File
@@ -0,0 +1,275 @@
//
// SUXPCInstaller.m
// Sparkle
//
// Created by Whitney Young on 3/19/12.
// Copyright (c) 2012 FadingRed. All rights reserved.
//
#import <xpc/xpc.h>
#import "SUXPCInstaller.h"
#import "SUInstallServiceConstants.h"
#import "SUCodeSigningVerifier.h"
BOOL SUShouldUseXPCInstaller(void)
{
if (![SUCodeSigningVerifier hostApplicationIsSandboxed])
return NO;
NSString *xpcServicePrefixPath = [[NSBundle mainBundle] bundlePath];
NSString *xpcServiceSuffixPath = @"Contents/XPCServices/com.devmate.UpdateInstaller.xpc";
return [[NSFileManager defaultManager] fileExistsAtPath:[xpcServicePrefixPath stringByAppendingPathComponent:xpcServiceSuffixPath]];
}
@implementation SUXPCInstaller
+ (xpc_connection_t)getSandboxXPCService
{
__block xpc_connection_t serviceConnection = xpc_connection_create("com.devmate.UpdateInstaller", dispatch_get_main_queue());
if (!serviceConnection)
{
NSLog(@"Can't connect to XPC service");
return (NULL);
}
xpc_connection_set_event_handler(serviceConnection, ^(xpc_object_t event) {
xpc_type_t type = xpc_get_type(event);
if (type == XPC_TYPE_ERROR)
{
if (event == XPC_ERROR_CONNECTION_INVALID)
{
// The service is invalid. Either the service name supplied to
// xpc_connection_create() is incorrect or we (this process) have
// canceled the service; we can do any cleanup of appliation
// state at this point.
xpc_release(serviceConnection);
}
}
});
// Need to resume the service in order for it to process messages.
xpc_connection_resume(serviceConnection);
return (serviceConnection);
}
+ (BOOL)copyPathWithAuthentication:(NSString *)src overPath:(NSString *)dst appendVersion:(BOOL)appendVersion error:(NSError *__autoreleasing *)outError
{
xpc_connection_t connection = [self getSandboxXPCService];
xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0);
xpc_dictionary_set_int64(message, SUInstallServiceTaskTypeKey, (int64_t)SUInstallServiceTaskAuthCopyPath);
if (src)
xpc_dictionary_set_string(message, SUInstallServiceSourcePathKey, [src fileSystemRepresentation]);
if (dst)
xpc_dictionary_set_string(message, SUInstallServiceDestinationPathKey, [dst fileSystemRepresentation]);
xpc_dictionary_set_bool(message, SUInstallServiceAppendVersionKey, appendVersion ? true : false);
__block BOOL xpcDidReply = NO;
__block NSError *error = nil;
dispatch_queue_t queue = dispatch_queue_create(NULL, DISPATCH_QUEUE_SERIAL);
xpc_connection_send_message_with_reply(connection, message, queue, ^(xpc_object_t response) {
if (XPC_TYPE_ERROR == xpc_get_type(response))
{
NSDictionary *errorInfo = [NSDictionary dictionaryWithObject:@"Internal XPC error."
forKey:NSLocalizedDescriptionKey];
error = [[NSError alloc] initWithDomain:SUSparkleErrorDomain code:SUXPCServiceError userInfo:errorInfo];
}
else if (XPC_TYPE_DICTIONARY == xpc_get_type(response))
{
const char *errorString = xpc_dictionary_get_string(response, SUInstallServiceErrorLocalizedDescriptionKey);
if (errorString != NULL)
{
NSDictionary *errorInfo = [NSDictionary dictionaryWithObject:[NSString stringWithCString:errorString encoding:NSUTF8StringEncoding]
forKey:NSLocalizedDescriptionKey];
error = [[NSError alloc] initWithDomain:SUSparkleErrorDomain code:SUXPCServiceError userInfo:errorInfo];
}
}
xpcDidReply = YES;
});
while (NO == xpcDidReply)
{
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.2]];
}
xpc_release(message);
dispatch_release(queue);
if (nil != error && NULL != outError)
{
*outError = error;
}
return (nil == error);
}
+ (BOOL)copyPathContent:(NSString *)src toDirectory:(NSString *)dstDir error:(NSError * __autoreleasing*)outError
{
xpc_connection_t connection = [self getSandboxXPCService];
xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0);
xpc_dictionary_set_int64(message, SUInstallServiceTaskTypeKey, (int64_t)SUInstallServiceTaskCopyPath);
if (src)
xpc_dictionary_set_string(message, SUInstallServiceSourcePathKey, [src fileSystemRepresentation]);
if (dstDir)
xpc_dictionary_set_string(message, SUInstallServiceDestinationPathKey, [dstDir fileSystemRepresentation]);
__block BOOL xpcDidReply = NO;
__block NSError *error = nil;
dispatch_queue_t queue = dispatch_queue_create(NULL, DISPATCH_QUEUE_SERIAL);
xpc_connection_send_message_with_reply(connection, message, queue, ^(xpc_object_t response) {
if (XPC_TYPE_ERROR == xpc_get_type(response))
{
NSDictionary *errorInfo = [NSDictionary dictionaryWithObject:@"Internal XPC error."
forKey:NSLocalizedDescriptionKey];
error = [[NSError alloc] initWithDomain:SUSparkleErrorDomain code:SUXPCServiceError userInfo:errorInfo];
}
else if (XPC_TYPE_DICTIONARY == xpc_get_type(response))
{
const char *errorString = xpc_dictionary_get_string(response, SUInstallServiceErrorLocalizedDescriptionKey);
if (errorString != NULL)
{
NSDictionary *errorInfo = [NSDictionary dictionaryWithObject:[NSString stringWithCString:errorString encoding:NSUTF8StringEncoding]
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>
+373
View File
@@ -0,0 +1,373 @@
//
// main.m
// Update
//
// Created by Whitney Young on 3/19/12.
// Copyright (c) 2012 FadingRed. All rights reserved.
//
#include <xpc/xpc.h>
#include <asl.h>
#import <Foundation/Foundation.h>
#import "SUPlainInstallerInternals.h"
#import "SUInstallServiceConstants.h"
static xpc_object_t SUSICopyPathContent(xpc_object_t message)
{
if (NULL == message)
return NULL;
const char *src = xpc_dictionary_get_string(message, SUInstallServiceSourcePathKey);
const char *dst = xpc_dictionary_get_string(message, SUInstallServiceDestinationPathKey);
NSFileManager *manager = [NSFileManager defaultManager];
NSString *sourcePath = src ? [manager stringWithFileSystemRepresentation:src length:strlen(src)] : nil;
NSString *targetPath = dst ? [manager stringWithFileSystemRepresentation:dst length:strlen(dst)] : nil;
NSError *error = nil;
do
{
if (nil == sourcePath)
{
NSDictionary *errorInfo = [NSDictionary dictionaryWithObject:@"Source path is absent." forKey:NSLocalizedDescriptionKey];
error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUXPCServiceError userInfo:errorInfo];
break;
}
if (nil == targetPath)
{
NSDictionary *errorInfo = [NSDictionary dictionaryWithObject:@"Destination path is absent." forKey:NSLocalizedDescriptionKey];
error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUXPCServiceError userInfo:errorInfo];
break;
}
NSArray *contents = nil;
BOOL isSrcDirectory = NO;
BOOL isSrcExist = [manager fileExistsAtPath:sourcePath isDirectory:&isSrcDirectory];
isSrcDirectory = isSrcDirectory && ![[NSWorkspace sharedWorkspace] isFilePackageAtPath:sourcePath];
if (isSrcExist && isSrcDirectory)
{
contents = [manager contentsOfDirectoryAtPath:sourcePath error:&error];
}
else if (isSrcExist)
{
contents = [NSArray arrayWithObject:@""];
}
else
{
NSDictionary *errorInfo = [NSDictionary dictionaryWithObject:@"Source does not exist on disk." forKey:NSLocalizedDescriptionKey];
error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUXPCServiceError userInfo:errorInfo];
}
if (nil != error)
{
break;
}
BOOL isDstDirectory = NO;
BOOL isDstExist = [manager fileExistsAtPath:targetPath isDirectory:&isDstDirectory];
if (isSrcDirectory && (!isDstExist || !isDstDirectory))
{
if (isDstExist)
[manager removeItemAtPath:targetPath error:&error];
[manager createDirectoryAtPath:targetPath withIntermediateDirectories:YES attributes:nil error:&error];
}
else if (!isSrcDirectory)
{
if (isDstExist && !isDstDirectory)
[manager removeItemAtPath:targetPath error:&error];
[manager createDirectoryAtPath:targetPath withIntermediateDirectories:YES attributes:nil error:&error];
}
if (nil != error)
{
break;
}
for (NSString *item in contents)
{
NSString *fromPath = [item length] ? [sourcePath stringByAppendingPathComponent:item] : sourcePath;
NSString *toPath = [item length] ? [targetPath stringByAppendingPathComponent:item] : [targetPath stringByAppendingPathComponent:[sourcePath lastPathComponent]];
if (![manager isReadableFileAtPath:fromPath])
{
SULog(@"XPC Install Service: will skip \"%@\"", fromPath);
continue;
}
SULog(@"XPC Install Service: will copy \"%@\" to \"%@\"", fromPath, toPath);
if ([manager fileExistsAtPath:toPath])
[manager removeItemAtPath:toPath error:&error];
if (![manager copyItemAtPath:fromPath toPath:toPath error:&error])
break;
}
}
while (NO);
xpc_object_t reply = xpc_dictionary_create_reply(message);
if (nil != error)
{
xpc_dictionary_set_int64(reply, SUInstallServiceErrorCodeKey, (int64_t)[error code]);
const char *errorMsg = [[error localizedDescription] length] ? [[error localizedDescription] UTF8String] : "";
xpc_dictionary_set_string(reply, SUInstallServiceErrorLocalizedDescriptionKey, errorMsg);
}
return reply;
}
static xpc_object_t SUISCopyPathWithAuthentication(xpc_object_t message)
{
if (NULL == message)
return NULL;
const char *src = xpc_dictionary_get_string(message, SUInstallServiceSourcePathKey);
const char *dst = xpc_dictionary_get_string(message, SUInstallServiceDestinationPathKey);
bool appendVersion = xpc_dictionary_get_bool(message, SUInstallServiceAppendVersionKey);
NSFileManager *manager = [NSFileManager defaultManager];
NSString *relaunchPathToCopy = src ? [manager stringWithFileSystemRepresentation:src length:strlen(src)] : nil;
NSString *targetPath = dst ? [manager stringWithFileSystemRepresentation:dst length:strlen(dst)] : nil;
NSError *error = nil;
BOOL result = [SUPlainInstaller copyPathWithAuthentication:relaunchPathToCopy overPath:targetPath appendVersion:appendVersion error:&error];
// send response to indicate ok
xpc_object_t reply = xpc_dictionary_create_reply(message);
if (!result && error != nil)
{
xpc_dictionary_set_int64(reply, SUInstallServiceErrorCodeKey, (int64_t)[error code]);
const char *errorMsg = [[error localizedDescription] length] ? [[error localizedDescription] UTF8String] : "";
xpc_dictionary_set_string(reply, SUInstallServiceErrorLocalizedDescriptionKey, errorMsg);
}
return reply;
}
static xpc_object_t SUISLaunchTask(xpc_object_t message)
{
if (NULL == message)
return NULL;
const char *path = xpc_dictionary_get_string(message, SUInstallServiceLaunchTaksPathKey);
NSString *launchPath = path ? [[NSFileManager defaultManager] stringWithFileSystemRepresentation:path length:strlen(path)] : nil;
xpc_object_t array = xpc_dictionary_get_value(message, SUInstallServiceLaunchTaskArgumentsKey);
NSArray *arguments = nil;
if (NULL != array)
{
size_t count = xpc_array_get_count(array);
NSMutableArray *mutableArgs = [NSMutableArray arrayWithCapacity:count];
for (size_t i = 0; i < count; i++)
{
[mutableArgs addObject:[NSString stringWithUTF8String:xpc_array_get_string(array, i)]];
}
arguments = mutableArgs;
}
xpc_object_t dict = xpc_dictionary_get_value(message, SUInstallServiceLaunchTaskEnvironmentKey);
NSDictionary *environment = nil;
if (NULL != dict)
{
size_t count = xpc_dictionary_get_count(dict);
__block NSMutableDictionary *mutableEnv = [NSMutableDictionary dictionaryWithCapacity:count];
xpc_dictionary_apply(dict, ^bool(const char *key, xpc_object_t value) {
NSString *envKey = [NSString stringWithUTF8String:key];
NSString *envValue = [NSString stringWithUTF8String:value];
[mutableEnv setObject:envValue forKey:envKey];
return true;
});
environment = mutableEnv;
}
path = xpc_dictionary_get_string(message, SUInstallServiceLaunchTaskCurrentDirKey);
NSString *currentDirPath = path ? [[NSFileManager defaultManager] stringWithFileSystemRepresentation:path length:strlen(path)] : nil;
size_t bytesLen = 0;
const void *bytes = xpc_dictionary_get_data(message, SUInstallServiceLaunchTaskInputDataKey, &bytesLen);
NSData *inputData = bytes ? [NSData dataWithBytes:bytes length:bytesLen] : nil;
bool shouldReplyImmediatly = xpc_dictionary_get_bool(message, SUInstallServiceLaunchTaskReplyImmediatelyKey);
// prepare NSTask
NSTask *task = [[NSTask alloc] init];
NSPipe *inputPipe = [NSPipe pipe];
NSPipe *outputPipe = [NSPipe pipe];
[task setStandardInput:inputPipe];
[task setStandardOutput:outputPipe];
[task setStandardError:outputPipe];
if (launchPath != nil)
[task setLaunchPath:launchPath];
if ([arguments count])
[task setArguments:arguments];
if ([environment count])
[task setEnvironment:environment];
if (currentDirPath != nil)
[task setCurrentDirectoryPath:currentDirPath];
__block NSData *outputData = nil;
__block int taskResult = 0;
__block BOOL isTaskRunning = YES;
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
NSArray *notificationObjects = nil;
if (!shouldReplyImmediatly)
{
id object1 = [notificationCenter addObserverForName:NSFileHandleReadToEndOfFileCompletionNotification
object:[outputPipe fileHandleForReading]
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification *note) {
outputData = [[note userInfo] objectForKey:NSFileHandleNotificationDataItem];
isTaskRunning = NO;
}];
id object2 = [notificationCenter addObserverForName:NSTaskDidTerminateNotification
object:task
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification __unused *note) {
taskResult = [task terminationStatus];
}];
notificationObjects = [NSArray arrayWithObjects:object1, object2, nil];
}
[[outputPipe fileHandleForReading] readToEndOfFileInBackgroundAndNotifyForModes:[NSArray arrayWithObject:NSDefaultRunLoopMode]];
@try
{
[task launch];
if ([inputData length])
{
[[inputPipe fileHandleForWriting] writeData:inputData];
[[inputPipe fileHandleForWriting] closeFile];
}
if (!shouldReplyImmediatly)
{
// loop until we are done receiving the data
while (YES == isTaskRunning)
{
CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.5, true);
}
}
}
@catch (...)
{
taskResult = SUXPCServiceError;
}
// send response to indicate ok
xpc_object_t reply = xpc_dictionary_create_reply(message);
xpc_dictionary_set_int64(reply, SUInstallServiceErrorCodeKey, (int64_t)taskResult);
if (outputData != nil)
{
xpc_dictionary_set_data(reply, SUInstallServiceLaunchTaskOutputDataKey, [outputData bytes], [outputData length]);
}
for (id object in notificationObjects)
{
[notificationCenter removeObserver:object];
}
outputData = nil;
return reply;
}
static void peer_event_handler(xpc_connection_t peer, xpc_object_t event)
{
xpc_type_t type = xpc_get_type(event);
if (type == XPC_TYPE_ERROR)
{
if (event == XPC_ERROR_CONNECTION_INVALID)
{
// The client process on the other end of the connection has either
// crashed or cancelled the connection. After receiving this error,
// the connection is in an invalid state, and you do not need to
// call xpc_connection_cancel(). Just tear down any associated state
// here.
}
else if (event == XPC_ERROR_TERMINATION_IMMINENT)
{
// Handle per-connection termination cleanup.
}
}
else if (type == XPC_TYPE_DICTIONARY)
{
// Handle the message.
int64_t task = xpc_dictionary_get_int64(event, SUInstallServiceTaskTypeKey);
NSLog(@"XPC Installer: will do the task %lld", (int64_t)task);
xpc_object_t reply = NULL;
@autoreleasepool
{
switch (task)
{
case SUInstallServiceTaskCopyPath:
{
reply = SUSICopyPathContent(event);
break;
}
case SUInstallServiceTaskAuthCopyPath:
{
reply = SUISCopyPathWithAuthentication(event);
break;
}
case SUInstallServiceTaskLaunchTask:
{
reply = SUISLaunchTask(event);
break;
}
default:
{
SULog(@"XPC Install Service: Unknown XPC service task %lld", task);
reply = xpc_dictionary_create_reply(event);
xpc_dictionary_set_int64(reply, SUInstallServiceErrorCodeKey, (int64_t)SUXPCServiceError);
xpc_dictionary_set_string(reply, SUInstallServiceErrorLocalizedDescriptionKey, "Unknown install cervice task.");
break;
}
}
}
if (NULL == reply)
{
reply = xpc_dictionary_create_reply(event);
}
xpc_connection_send_message(peer, reply);
xpc_release(reply);
}
}
static void event_handler(xpc_connection_t peer)
{
// By defaults, new connections will target the default dispatch
// concurrent queue.
xpc_connection_set_event_handler(peer, ^(xpc_object_t event) {
peer_event_handler(peer, event);
});
// This will tell the connection to begin listening for events. If you
// have some other initialization that must be done asynchronously, then
// you can defer this call until after that initialization is done.
xpc_connection_resume(peer);
}
int main(int __unused argc, const char __unused *argv[])
{
xpc_main(event_handler);
}
+10
View File
@@ -0,0 +1,10 @@
//
// install_service.pch
// Sparkle
//
// Created by Dmytro Tretiakov on 4/25/14.
//
//
#import "Sparkle.pch"
#import "SULog.h"
-5
View File
@@ -9,11 +9,7 @@
#ifndef SUAPPCAST_H
#define SUAPPCAST_H
#if __has_feature(modules)
@import Foundation;
#else
#import <Foundation/Foundation.h>
#endif
#import "SUExport.h"
@class SUAppcastItem;
@@ -23,7 +19,6 @@ SU_EXPORT @interface SUAppcast : NSObject<NSURLDownloadDelegate>
@property (copy) NSDictionary *httpHeaders;
- (void)fetchAppcastFromURL:(NSURL *)url completionBlock:(void (^)(NSError *))err;
- (SUAppcast *)copyWithoutDeltaUpdates;
@property (readonly, copy) NSArray *items;
@end
+136 -174
View File
@@ -30,10 +30,7 @@
if (!attrName) {
continue;
}
NSString *attributeStringValue = [attribute stringValue];
if (attributeStringValue != nil) {
[dictionary setObject:attributeStringValue forKey:attrName];
}
dictionary[attrName] = [attribute stringValue];
}
return dictionary;
}
@@ -96,166 +93,147 @@
- (void)downloadDidFinish:(NSURLDownload *)__unused aDownload
{
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];
NSEnumerator *nodeEnum = [xmlItems objectEnumerator];
NSXMLNode *node;
while((node = [nodeEnum nextObject])) {
if (self.downloadFilename)
{
NSUInteger options = 0;
options = NSXMLNodeLoadExternalEntitiesSameOriginOnly;
document = [[NSXMLDocument alloc] initWithContentsOfURL:[NSURL fileURLWithPath:self.downloadFilename] options:options error:&error];
[[NSFileManager defaultManager] removeItemAtPath:self.downloadFilename error:nil];
self.downloadFilename = nil;
}
else
{
failed = YES;
}
if (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 *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.
if ([[node children] count]) {
node = [node childAtIndex:0];
while (nil != node) {
NSString *name = [self sparkleNamespacedNameOfNode:node];
if (name) {
NSMutableArray *nodes = [nodesDict objectForKey:name];
if (nodes == nil) {
nodes = [NSMutableArray array];
[nodesDict setObject:nodes forKey:name];
while (failed == NO && (node = [nodeEnum nextObject]))
{
// First, we'll "index" all the first-level children of this appcast item so we can pick them out by language later.
if ([[node children] count])
{
node = [node childAtIndex:0];
while (nil != node)
{
NSString *name = [node name];
if (name)
{
NSMutableArray *nodes = nodesDict[name];
if (nodes == nil)
{
nodes = [NSMutableArray array];
nodesDict[name] = nodes;
}
[nodes addObject:node];
}
[nodes addObject:node];
node = [node nextSibling];
}
node = [node nextSibling];
}
}
for (NSString *name in nodesDict) {
node = [self bestNodeInNodes:[nodesDict objectForKey:name]];
if ([name isEqualToString:SURSSElementEnclosure]) {
// enclosure is flattened as a separate dictionary for some reason
NSDictionary *encDict = [self attributesOfNode:(NSXMLElement *)node];
[dict setObject:encDict forKey:name];
}
else if ([name isEqualToString:SURSSElementPubDate]) {
// We don't want to parse and create a NSDate instance -
// that's a risk we can avoid. We don't use the date anywhere other
// than it being accessible from SUAppcastItem
NSString *dateString = node.stringValue;
if (dateString) {
[dict setObject:dateString forKey:name];
}
}
else if ([name isEqualToString:SUAppcastElementDeltas]) {
NSMutableArray *deltas = [NSMutableArray array];
NSEnumerator *childEnum = [[node children] objectEnumerator];
for (NSXMLNode *child in childEnum) {
if ([[child name] isEqualToString:SURSSElementEnclosure]) {
[deltas addObject:[self attributesOfNode:(NSXMLElement *)child]];
}
}
[dict setObject:deltas forKey:name];
}
else if ([name isEqualToString:SUAppcastElementTags]) {
NSMutableArray *tags = [NSMutableArray array];
NSEnumerator *childEnum = [[node children] objectEnumerator];
for (NSXMLNode *child in childEnum) {
NSString *childName = child.name;
if (childName) {
[tags addObject:childName];
}
}
[dict setObject:tags forKey:name];
}
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];
}
}
}
for (NSString *name in nodesDict)
{
node = [self bestNodeInNodes:nodesDict[name]];
if ([name isEqualToString:SURSSElementEnclosure])
{
// enclosure is flattened as a separate dictionary for some reason
NSDictionary *encDict = [(NSXMLElement *)node attributesAsDictionary];
dict[name] = encDict;
NSString *errString;
SUAppcastItem *anItem = [[SUAppcastItem alloc] initWithDictionary:dict failureReason:&errString];
if (anItem) {
[appcastItems addObject:anItem];
}
else {
SULog(@"Sparkle Updater: Failed to parse appcast item: %@.\nAppcast dictionary was: %@", errString, dict);
if (errorp) *errorp = [NSError errorWithDomain:SUSparkleErrorDomain
code:SUAppcastParseError
userInfo:@{NSLocalizedDescriptionKey: errString}];
return nil;
}
else if ([name isEqualToString:SURSSElementPubDate])
{
// pubDate is expected to be an NSDate by SUAppcastItem, but the RSS class was returning an NSString
NSString *string = node.stringValue;
if (string) {
NSDate *date = [NSDate dateWithNaturalLanguageString:string];
if (date)
dict[name] = date;
}
}
else if ([name isEqualToString:SUAppcastElementDeltas])
{
NSMutableArray *deltas = [NSMutableArray array];
NSEnumerator *childEnum = [[node children] objectEnumerator];
for (NSXMLNode *child in childEnum) {
if ([[child name] isEqualToString:SURSSElementEnclosure])
[deltas addObject:[(NSXMLElement *)child attributesAsDictionary]];
}
dict[name] = deltas;
}
else if ([name isEqualToString:SUAppcastElementTags]) {
NSMutableArray *tags = [NSMutableArray array];
NSEnumerator *childEnum = [[node children] objectEnumerator];
for (NSXMLNode *child in childEnum) {
NSString *childName = child.name;
if (childName)
[tags addObject:childName];
}
dict[name] = tags;
}
else if (name != nil)
{
// add all other values as strings
NSString *theValue = [[node stringValue] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if (theValue != nil) {
dict[name] = theValue;
}
}
}
NSString *errString;
SUAppcastItem *anItem = [[SUAppcastItem alloc] initWithDictionary:dict failureReason:&errString];
if (anItem)
{
[appcastItems addObject:anItem];
}
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
@@ -275,18 +253,14 @@
- (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),
NSLocalizedFailureReasonErrorKey: [error localizedDescription],
NSUnderlyingErrorKey: error,
}];
NSURL *failingUrl = [error.userInfo objectForKey:NSURLErrorFailingURLErrorKey];
if (failingUrl) {
[userInfo setObject:failingUrl forKey:NSURLErrorFailingURLErrorKey];
}
self.completionBlock([NSError errorWithDomain:SUSparkleErrorDomain code:SUAppcastError userInfo:userInfo]);
NSURLErrorFailingURLErrorKey: failingUrl ? failingUrl : [NSNull null],
}]);
self.completionBlock = nil;
}
@@ -294,7 +268,7 @@
{
// We use this method to pick out the localized version of a node when one's available.
if ([nodes count] == 1)
return [nodes objectAtIndex:0];
return nodes[0];
else if ([nodes count] == 0)
return nil;
@@ -305,24 +279,12 @@
lang = [[node attributeForName:@"xml:lang"] stringValue];
[languages addObject:(lang ? lang : @"")];
}
lang = [[NSBundle preferredLocalizationsFromArray:languages] objectAtIndex:0];
lang = [NSBundle preferredLocalizationsFromArray:languages][0];
i = [languages indexOfObject:([languages containsObject:lang] ? lang : @"")];
if (i == NSNotFound) {
i = 0;
}
return [nodes objectAtIndex:i];
}
- (SUAppcast *)copyWithoutDeltaUpdates {
SUAppcast *other = [SUAppcast new];
NSMutableArray *nonDeltaItems = [NSMutableArray new];
for(SUAppcastItem *item in self.items) {
if (![item isDeltaUpdate]) [nonDeltaItems addObject:item];
}
other.items = nonDeltaItems;
return other;
return nodes[i];
}
@end
+1 -5
View File
@@ -9,16 +9,12 @@
#ifndef SUAPPCASTITEM_H
#define SUAPPCASTITEM_H
#if __has_feature(modules)
@import Foundation;
#else
#import <Foundation/Foundation.h>
#endif
#import "SUExport.h"
SU_EXPORT @interface SUAppcastItem : NSObject
@property (copy, readonly) NSString *title;
@property (copy, readonly) NSString *dateString;
@property (copy, readonly) NSDate *date;
@property (copy, readonly) NSString *itemDescription;
@property (strong, readonly) NSURL *releaseNotesURL;
@property (copy, readonly) NSString *DSASignature;
+26 -33
View File
@@ -16,7 +16,7 @@
@interface SUAppcastItem ()
@property (copy, readwrite) NSString *title;
@property (copy, readwrite) NSString *dateString;
@property (copy, readwrite) NSDate *date;
@property (copy, readwrite) NSString *itemDescription;
@property (strong, readwrite) NSURL *releaseNotesURL;
@property (copy, readwrite) NSString *DSASignature;
@@ -31,7 +31,7 @@
@end
@implementation SUAppcastItem
@synthesize dateString;
@synthesize date;
@synthesize deltaUpdates;
@synthesize displayVersionString;
@synthesize DSASignature;
@@ -47,13 +47,12 @@
- (BOOL)isDeltaUpdate
{
NSDictionary *rssElementEnclosure = [self.propertiesDictionary objectForKey:SURSSElementEnclosure];
return [rssElementEnclosure objectForKey:SUAppcastAttributeDeltaFrom] != nil;
return self.propertiesDictionary[SURSSElementEnclosure][SUAppcastAttributeDeltaFrom] != nil;
}
- (BOOL)isCriticalUpdate
{
return [[self.propertiesDictionary objectForKey:SUAppcastElementTags] containsObject:SUAppcastElementCriticalUpdate];
return [self.propertiesDictionary[SUAppcastElementTags] containsObject:SUAppcastElementCriticalUpdate];
}
- (BOOL)isInformationOnlyUpdate
@@ -70,7 +69,7 @@
{
self = [super init];
if (self) {
NSDictionary *enclosure = [dict objectForKey:SURSSElementEnclosure];
id enclosure = dict[SURSSElementEnclosure];
// Try to find a version string.
// Finding the new version number from the RSS feed is a little bit hacky. There are two ways:
@@ -80,17 +79,17 @@
// underscore and the last period as the version number. So name your packages like this: APPNAME_VERSION.extension.
// The big caveat with this is that you can't have underscores in your version strings, as that'll confuse Sparkle.
// Feel free to change the separator string to a hyphen or something more suited to your needs if you like.
NSString *newVersion = [enclosure objectForKey:SUAppcastAttributeVersion];
NSString *newVersion = enclosure[SUAppcastAttributeVersion];
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?
{
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,
// 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) {
newVersion = [[fileComponents lastObject] stringByDeletingPathExtension];
}
@@ -104,11 +103,11 @@
}
propertiesDictionary = [[NSMutableDictionary alloc] initWithDictionary:dict];
self.title = [dict objectForKey:SURSSElementTitle];
self.dateString = [dict objectForKey:SURSSElementPubDate];
self.itemDescription = [dict objectForKey:SURSSElementDescription];
self.title = dict[SURSSElementTitle];
self.date = dict[SURSSElementPubDate];
self.itemDescription = dict[SURSSElementDescription];
NSString *theInfoURL = [dict objectForKey:SURSSElementLink];
NSString *theInfoURL = dict[SURSSElementLink];
if (theInfoURL) {
if (![theInfoURL isKindOfClass:[NSString class]]) {
SULog(@"%@ -%@ Info URL is not of valid type.", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
@@ -126,7 +125,7 @@
return nil;
}
NSString *enclosureURLString = [enclosure objectForKey:SURSSAttributeURL];
NSString *enclosureURLString = enclosure[SURSSAttributeURL];
if (!enclosureURLString && !theInfoURL) {
if (error) {
*error = @"Feed item's enclosure lacks URL";
@@ -135,21 +134,20 @@
}
if (enclosureURLString) {
// Sparkle used to always URL-encode, so for backwards compatibility spaces in URLs must be forgiven.
NSString *fileURLString = [enclosureURLString stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
NSString *fileURLString = [[enclosureURLString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
self.fileURL = [NSURL URLWithString:fileURLString];
}
if (enclosure) {
self.DSASignature = [enclosure objectForKey:SUAppcastAttributeDSASignature];
self.DSASignature = enclosure[SUAppcastAttributeDSASignature];
}
self.versionString = newVersion;
self.minimumSystemVersion = [dict objectForKey:SUAppcastElementMinimumSystemVersion];
self.maximumSystemVersion = [dict objectForKey:SUAppcastElementMaximumSystemVersion];
self.minimumSystemVersion = dict[SUAppcastElementMinimumSystemVersion];
self.maximumSystemVersion = dict[SUAppcastElementMaximumSystemVersion];
NSString *shortVersionString = [enclosure objectForKey:SUAppcastAttributeShortVersionString];
NSString *shortVersionString = enclosure[SUAppcastAttributeShortVersionString];
if (nil == shortVersionString) {
shortVersionString = [dict objectForKey:SUAppcastAttributeShortVersionString]; // fall back on the <item>
shortVersionString = dict[SUAppcastAttributeShortVersionString]; // fall back on the <item>
}
if (shortVersionString) {
@@ -159,33 +157,28 @@
}
// Find the appropriate release notes URL.
NSString *releaseNotesString = [dict objectForKey:SUAppcastElementReleaseNotesLink];
NSString *releaseNotesString = dict[SUAppcastElementReleaseNotesLink];
if (releaseNotesString) {
NSURL *url = [NSURL URLWithString:releaseNotesString];
if ([url isFileURL]) {
SULog(@"Release notes with file:// URLs are not supported");
} else {
self.releaseNotesURL = url;
}
self.releaseNotesURL = [NSURL URLWithString:releaseNotesString];
} else if ([self.itemDescription hasPrefix:@"http://"] || [self.itemDescription hasPrefix:@"https://"]) { // if the description starts with http:// or https:// use that.
self.releaseNotesURL = [NSURL URLWithString:self.itemDescription];
} else {
self.releaseNotesURL = nil;
}
NSArray *deltaDictionaries = [dict objectForKey:SUAppcastElementDeltas];
NSArray *deltaDictionaries = dict[SUAppcastElementDeltas];
if (deltaDictionaries) {
NSMutableDictionary *deltas = [NSMutableDictionary dictionary];
for (NSDictionary *deltaDictionary in deltaDictionaries) {
NSString *deltaFrom = [deltaDictionary objectForKey:SUAppcastAttributeDeltaFrom];
NSString *deltaFrom = deltaDictionary[SUAppcastAttributeDeltaFrom];
if (!deltaFrom) continue;
NSMutableDictionary *fakeAppCastDict = [dict mutableCopy];
[fakeAppCastDict removeObjectForKey:SUAppcastElementDeltas];
[fakeAppCastDict setObject:deltaDictionary forKey:SURSSElementEnclosure];
fakeAppCastDict[SURSSElementEnclosure] = deltaDictionary;
SUAppcastItem *deltaItem = [[SUAppcastItem alloc] initWithDictionary:fakeAppCastDict];
[deltas setObject:deltaItem forKey:deltaFrom];
deltas[deltaFrom] = deltaItem;
}
self.deltaUpdates = deltas;
}
+35 -31
View File
@@ -26,7 +26,6 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
@property (assign) BOOL postponingInstallation;
@property (assign) BOOL showErrors;
@property (assign) BOOL willUpdateOnTermination;
@property (assign) BOOL isTerminating;
@property (strong) SUAutomaticUpdateAlert *alert;
@property (strong) NSTimer *showUpdateAlertTimer;
@@ -37,10 +36,14 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
@synthesize postponingInstallation;
@synthesize showErrors;
@synthesize willUpdateOnTermination;
@synthesize isTerminating;
@synthesize alert;
@synthesize showUpdateAlertTimer;
- (BOOL)shouldShowUI
{
return self.showErrors;
}
- (void)showUpdateAlert
{
self.interruptible = NO;
@@ -62,10 +65,34 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:) name:NSApplicationDidBecomeActiveNotification object:NSApp];
}
- (void)downloadReleaseNotesAndWaitUntilDone
{
NSURL *releaseNotesURL = self.updateItem.releaseNotesURL;
if (nil == releaseNotesURL || [releaseNotesURL isFileURL])
return;
static NSString * const kSUAutomaticUpdateParamName = @"autoupdate";
NSString *URLString = releaseNotesURL.absoluteString;
URLString = [URLString stringByAppendingFormat:@"%@%@=1", (releaseNotesURL.query != nil) ? @"&" : @"?", kSUAutomaticUpdateParamName];
releaseNotesURL = [NSURL URLWithString:URLString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:releaseNotesURL];
[request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
[self updateURLRequestHTTPHeaders:request];
[NSURLConnection sendSynchronousRequest:request returningResponse:NULL error:NULL];
}
- (void)didFindValidUpdate
{
// For correct DevMate statistics need to send request for Release Notes.
[self downloadReleaseNotesAndWaitUntilDone];
[super didFindValidUpdate];
}
- (void)unarchiverDidFinish:(SUUnarchiver *)__unused ua
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:) name:NSApplicationWillTerminateNotification object:nil];
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(systemWillPowerOff:) name:NSWorkspaceWillPowerOffNotification object:nil];
// Sudden termination is available on 10.6+
NSProcessInfo *processInfo = [NSProcessInfo processInfo];
@@ -106,8 +133,6 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
if (self.willUpdateOnTermination)
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:NSApplicationWillTerminateNotification object:nil];
[[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self name:NSWorkspaceWillPowerOffNotification object:nil];
NSProcessInfo *processInfo = [NSProcessInfo processInfo];
[processInfo enableSuddenTermination];
@@ -131,12 +156,11 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
[self invalidateShowUpdateAlertTimer];
}
- (void)abortUpdate
- (void)abortUpdate:(SUUpdateAbortReason)reason
{
self.isTerminating = NO;
[self stopUpdatingOnTermination];
[self invalidateShowUpdateAlertTimer];
[super abortUpdate];
[super abortUpdate:reason];
}
- (void)applicationDidBecomeActive:(NSNotification *)__unused aNotification
@@ -156,18 +180,18 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
case SUInstallLaterChoice:
self.postponingInstallation = YES;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:) name:NSApplicationWillTerminateNotification object:nil];
// We're already waiting on quit, just indicate that we're idle.
self.interruptible = YES;
break;
case SUDoNotInstallChoice:
[self.host setObject:[self.updateItem versionString] forUserDefaultsKey:SUSkippedVersionKey];
[self abortUpdate];
[self abortUpdate:SUUpdateAbortCanceledByUser];
break;
}
}
- (void)installWithToolAndRelaunch:(BOOL)relaunch displayingUserInterface:(BOOL)showUI
{
if (relaunch) {
@@ -178,31 +202,11 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
[super installWithToolAndRelaunch:relaunch displayingUserInterface:showUI];
}
- (void)systemWillPowerOff:(NSNotification *)__unused note
{
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUSystemPowerOffError userInfo:@{
NSLocalizedDescriptionKey: SULocalizedString(@"The update will not be installed because the user requested for the system to power off", nil)
}]];
}
- (void)applicationWillTerminate:(NSNotification *)__unused note
{
// We don't want to terminate the app if the user or someone else initiated a termination
// Use a property instead of passing an argument to installWithToolAndRelaunch:
// because we give the delegate an invocation to our install methods and
// this code was added later :|
self.isTerminating = YES;
[self installWithToolAndRelaunch:NO];
}
- (void)terminateApp
{
if (!self.isTerminating) {
[super terminateApp];
}
}
- (void)abortUpdateWithError:(NSError *)error
{
if (self.showErrors) {
@@ -215,7 +219,7 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
[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;
- (BOOL)isItemNewer:(SUAppcastItem *)ui;
+ (BOOL)hostSupportsItem:(SUAppcastItem *)ui;
- (BOOL)hostSupportsItem:(SUAppcastItem *)ui;
- (BOOL)itemContainsSkippedVersion:(SUAppcastItem *)ui;
- (BOOL)itemContainsValidUpdate:(SUAppcastItem *)ui;
- (void)appcastDidFinishLoading:(SUAppcast *)ac;
- (void)didFindValidUpdate;
- (void)didNotFindUpdate;
- (void)updateURLRequestHTTPHeaders:(NSMutableURLRequest *)request;
- (void)downloadUpdate;
- (void)download:(NSURLDownload *)d decideDestinationWithSuggestedFilename:(NSString *)name;
- (void)downloadDidFinish:(NSURLDownload *)d;
@@ -47,7 +48,7 @@
- (void)cleanUpDownload;
- (void)abortUpdate;
- (void)abortUpdate:(SUUpdateAbortReason)reason;
- (void)abortUpdateWithError:(NSError *)error;
- (void)terminateApp;
+183 -184
View File
@@ -9,15 +9,20 @@
#import "SUBasicUpdateDriver.h"
#import "SUHost.h"
#import "SUOperatingSystem.h"
#import "SUDSAVerifier.h"
#import "SUInstaller.h"
#import "SUStandardVersionComparator.h"
#import "SUUnarchiver.h"
#import "SUConstants.h"
#import "SULog.h"
#import "SUPlainInstaller.h"
#import "SUPlainInstallerInternals.h"
#import "SUBinaryDeltaCommon.h"
#import "SUCodeSigningVerifier.h"
#import "SUUpdater_Private.h"
#import "SUFileManager.h"
#import "SUUpdateValidator.h"
#import "SUXPCInstaller.h"
CF_EXPORT CFDictionaryRef DMCopyHTTPRequestHeaders(CFBundleRef appBundle, CFDataRef httpBodyData);
@interface SUBasicUpdateDriver ()
@@ -29,8 +34,6 @@
@property (copy) NSString *tempDir;
@property (copy) NSString *relaunchPath;
@property (nonatomic) SUUpdateValidator *updateValidator;
@end
@implementation SUBasicUpdateDriver
@@ -43,8 +46,6 @@
@synthesize tempDir;
@synthesize relaunchPath;
@synthesize updateValidator = _updateValidator;
- (void)checkForUpdatesAtURL:(NSURL *)URL host:(SUHost *)aHost
{
[super checkForUpdatesAtURL:URL host:aHost];
@@ -54,10 +55,14 @@
return;
}
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
request.allHTTPHeaderFields = [self.updater httpHeaders];
[self updateURLRequestHTTPHeaders:request];
SUAppcast *appcast = [[SUAppcast alloc] init];
[appcast setUserAgentString:[self.updater userAgentString]];
[appcast setHttpHeaders:[self.updater httpHeaders]];
[appcast setHttpHeaders:request.allHTTPHeaderFields];
[appcast fetchAppcastFromURL:URL completionBlock:^(NSError *error) {
if (error) {
[self abortUpdateWithError:error];
@@ -84,28 +89,12 @@
return comparator;
}
+ (SUAppcastItem *)bestItemFromAppcastItems:(NSArray *)appcastItems getDeltaItem:(SUAppcastItem * __autoreleasing *)deltaItem withHostVersion:(NSString *)hostVersion comparator:(id<SUVersionComparison>)comparator
- (BOOL)isItemNewer:(SUAppcastItem *)ui
{
SUAppcastItem *item = nil;
for(SUAppcastItem *candidate in appcastItems) {
if ([[self class] hostSupportsItem:candidate]) {
if (!item || [comparator compareVersion:item.versionString toVersion:candidate.versionString] == NSOrderedAscending) {
item = candidate;
}
}
}
if (item && deltaItem) {
SUAppcastItem *deltaUpdateItem = [[item deltaUpdates] objectForKey:hostVersion];
if (deltaUpdateItem && [[self class] hostSupportsItem:deltaUpdateItem]) {
*deltaItem = deltaUpdateItem;
}
}
return item;
return [[self versionComparator] compareVersion:[self.host version] toVersion:[ui versionString]] == NSOrderedAscending;
}
+ (BOOL)hostSupportsItem:(SUAppcastItem *)ui
- (BOOL)hostSupportsItem:(SUAppcastItem *)ui
{
if (([ui minimumSystemVersion] == nil || [[ui minimumSystemVersion] isEqualToString:@""]) &&
([ui maximumSystemVersion] == nil || [[ui maximumSystemVersion] isEqualToString:@""])) { return YES; }
@@ -115,20 +104,15 @@
// Check minimum and maximum System Version
if ([ui minimumSystemVersion] != nil && ![[ui minimumSystemVersion] isEqualToString:@""]) {
minimumVersionOK = [[SUStandardVersionComparator defaultComparator] compareVersion:[ui minimumSystemVersion] toVersion:[SUOperatingSystem systemVersionString]] != NSOrderedDescending;
minimumVersionOK = [[SUStandardVersionComparator defaultComparator] compareVersion:[ui minimumSystemVersion] toVersion:[SUHost systemVersionString]] != NSOrderedDescending;
}
if ([ui maximumSystemVersion] != nil && ![[ui maximumSystemVersion] isEqualToString:@""]) {
maximumVersionOK = [[SUStandardVersionComparator defaultComparator] compareVersion:[ui maximumSystemVersion] toVersion:[SUOperatingSystem systemVersionString]] != NSOrderedAscending;
maximumVersionOK = [[SUStandardVersionComparator defaultComparator] compareVersion:[ui maximumSystemVersion] toVersion:[SUHost systemVersionString]] != NSOrderedAscending;
}
return minimumVersionOK && maximumVersionOK;
}
- (BOOL)isItemNewer:(SUAppcastItem *)ui
{
return [[self versionComparator] compareVersion:[self.host version] toVersion:[ui versionString]] == NSOrderedAscending;
}
- (BOOL)itemContainsSkippedVersion:(SUAppcastItem *)ui
{
NSString *skippedVersion = [self.host objectForUserDefaultsKey:SUSkippedVersionKey];
@@ -138,7 +122,7 @@
- (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
@@ -156,17 +140,17 @@
if ([[self.updater delegate] respondsToSelector:@selector(bestValidUpdateInAppcast:forUpdater:)]) // Does the delegate want to handle it?
{
item = [[self.updater delegate] bestValidUpdateInAppcast:ac forUpdater:self.updater];
if ([item isDeltaUpdate]) {
self.nonDeltaUpdateItem = [[self.updater delegate] bestValidUpdateInAppcast:[ac copyWithoutDeltaUpdates] forUpdater:self.updater];
}
}
else // If not, we'll take care of it ourselves.
{
// Find the best supported update
SUAppcastItem *deltaUpdateItem = nil;
item = [[self class] bestItemFromAppcastItems:ac.items getDeltaItem:&deltaUpdateItem withHostVersion:self.host.version comparator:[self versionComparator]];
if (item && deltaUpdateItem) {
// Find the first update we can actually use.
NSEnumerator *updateEnumerator = [[ac items] objectEnumerator];
do {
item = [updateEnumerator nextObject];
} while (item && ![self hostSupportsItem:item]);
SUAppcastItem *deltaUpdateItem = [item deltaUpdates][[self.host version]];
if (deltaUpdateItem && [self hostSupportsItem:deltaUpdateItem]) {
self.nonDeltaUpdateItem = item;
item = deltaUpdateItem;
}
@@ -210,38 +194,26 @@
}]];
}
- (NSString *)appCachePath
- (void)updateURLRequestHTTPHeaders:(NSMutableURLRequest *)request
{
NSArray *cachePaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachePath = nil;
if ([cachePaths count]) {
cachePath = [cachePaths objectAtIndex:0];
}
if (!cachePath) {
SULog(@"Failed to find user's cache directory! Using system default");
cachePath = NSTemporaryDirectory();
CFBundleRef hostBundle = CFBundleCreate(kCFAllocatorDefault, (__bridge CFURLRef)[NSURL fileURLWithPath:self.host.bundlePath]);
NSDictionary *devmateHeaders = (__bridge_transfer NSDictionary *)DMCopyHTTPRequestHeaders(hostBundle, NULL);
if (devmateHeaders.count)
{
[request setAllHTTPHeaderFields:devmateHeaders];
}
NSString *name = [self.host.bundle bundleIdentifier];
if (!name) {
name = [self.host name];
if (NULL != hostBundle)
{
CFRelease(hostBundle);
}
cachePath = [cachePath stringByAppendingPathComponent:name];
cachePath = [cachePath stringByAppendingPathComponent:@SPARKLE_BUNDLE_IDENTIFIER];
return cachePath;
}
- (void)downloadUpdate
{
// Clear cache directory so that downloads can't possibly accumulate inside
NSString *appCachePath = [self appCachePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:appCachePath]) {
[[NSFileManager defaultManager] removeItemAtPath:appCachePath error:NULL];
}
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[self.updateItem fileURL]];
[request setValue:[self.updater userAgentString] forHTTPHeaderField:@"User-Agent"];
[self updateURLRequestHTTPHeaders:request];
if ([[self.updater delegate] respondsToSelector:@selector(updater:willDownloadUpdate:withRequest:)]) {
[[self.updater delegate] updater:self.updater
willDownloadUpdate:self.updateItem
@@ -253,14 +225,13 @@
- (void)download:(NSURLDownload *)__unused d decideDestinationWithSuggestedFilename:(NSString *)name
{
NSString *downloadFileName = [NSString stringWithFormat:@"%@ %@", [self.host name], [self.updateItem versionString]];
NSString *appCachePath = [self appCachePath];
self.tempDir = [appCachePath stringByAppendingPathComponent:downloadFileName];
self.tempDir = [self.host.appCachePath stringByAppendingPathComponent:downloadFileName];
int cnt = 1;
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.
@@ -276,6 +247,90 @@
[self.download setDestination:self.downloadPath allowOverwrite:YES];
}
/**
* If the update is a package, then it must be signed using DSA. No other verification is done.
*
* If the update is a bundle, then it must meet any one of:
*
* * old and new DSA public keys are the same and valid (it allows change of Code Signing identity), or
*
* * old and new Code Signing identity are the same and valid
*
*/
- (BOOL)validateUpdateDownloadedToPath:(NSString *)downloadedPath extractedToPath:(NSString *)extractedPath DSASignature:(NSString *)DSASignature publicDSAKey:(NSString *)publicDSAKey
{
BOOL isUpdateValid = NO;
do
{
BOOL isPackage = NO;
NSString *installSourcePath = [SUInstaller installSourcePathInUpdateFolder:extractedPath forHost:self.host isPackage:&isPackage isGuided:NULL];
if (installSourcePath == nil)
{
SULog(@"No suitable install is found in the update. The update will be rejected.");
break;
}
// Modern packages are not distributed as bundles and are code signed differently than regular applications
if (isPackage)
{
isUpdateValid = [SUDSAVerifier validatePath:downloadedPath withEncodedDSASignature:DSASignature withPublicDSAKey:publicDSAKey];
if (!isUpdateValid)
{
SULog(@"DSA signature validation of the package failed. The update will be rejected.");
}
break;
}
NSBundle *newBundle = [NSBundle bundleWithPath:installSourcePath];
if (newBundle == nil)
{
SULog(@"No suitable bundle is found in the update. The update will be rejected.");
break;
}
// Check Code Signing equality
NSError *error = nil;
BOOL updateIsCodeSigned = [SUCodeSigningVerifier applicationAtPathIsCodeSigned:installSourcePath];
updateIsCodeSigned = updateIsCodeSigned && [SUCodeSigningVerifier codeSignatureIsValidAtPath:installSourcePath error:&error];
if (!updateIsCodeSigned)
{
SULog(@"Update has no valid Code Signing (%ld - %@)", error.code, error.localizedDescription);
}
BOOL shouldCheckCodeSignEquality = updateIsCodeSigned ? [SUCodeSigningVerifier hostApplicationIsCodeSigned] : NO;
if (shouldCheckCodeSignEquality && [SUCodeSigningVerifier codeSignatureMatchesHostAndIsValidAtPath:installSourcePath error:&error])
{
isUpdateValid = YES;
break;
}
else
{
SULog(@"Code signatures differs in application and update (%ld - %@)", error.code, error.localizedDescription);
}
// Check DSA signature
SUHost *newHost = [[SUHost alloc] initWithBundle:newBundle];
NSString *newPublicDSAKey = newHost.publicDSAKey;
BOOL dsaKeysMatch = (publicDSAKey == nil || newPublicDSAKey == nil) ? NO : [publicDSAKey isEqualToString:newPublicDSAKey];
if (!dsaKeysMatch)
{
SULog(@"DSA keys are different for update and application.");
}
isUpdateValid = dsaKeysMatch && [SUDSAVerifier validatePath:downloadedPath withEncodedDSASignature:DSASignature withPublicDSAKey:newPublicDSAKey];
if (!isUpdateValid)
{
SULog(@"DSA signature validation failed. The update has a public DSA key and is signed with a DSA key, but the %@ doesn't match the signature. The update will be rejected.", dsaKeysMatch ? @"public key" : @"new public key shipped with the update");
}
}
while (NO);
return isUpdateValid;
}
- (void)downloadDidFinish:(NSURLDownload *)__unused d
{
assert(self.updateItem);
@@ -285,26 +340,22 @@
- (void)download:(NSURLDownload *)__unused download didFailWithError:(NSError *)error
{
NSURL *failingUrl = [error.userInfo objectForKey:NSURLErrorFailingURLErrorKey];
NSURL *failingUrl = error.userInfo[NSURLErrorFailingURLErrorKey];
if (!failingUrl) {
failingUrl = [self.updateItem fileURL];
}
if ([[self.updater delegate] respondsToSelector:@selector(updater:failedToDownloadUpdate:error:)]) {
[[self.updater delegate] updater:self.updater
failedToDownloadUpdate:self.updateItem
error:error];
}
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),
NSUnderlyingErrorKey: error,
}];
if (failingUrl) {
[userInfo setObject:failingUrl forKey:NSURLErrorFailingURLErrorKey];
}
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUDownloadError userInfo:userInfo]];
NSURLErrorFailingURLErrorKey: failingUrl ? failingUrl : [NSNull null],
}]];
}
- (BOOL)download:(NSURLDownload *)__unused download shouldDecodeSourceDataOfMIMEType:(NSString *)encodingType
@@ -316,28 +367,14 @@
- (void)extractUpdate
{
SUUnarchiver *unarchiver = [SUUnarchiver unarchiverForPath:self.downloadPath updatingHostBundlePath:self.host.bundlePath withPassword:self.updater.decryptionPassword];
BOOL success;
SUUnarchiver *unarchiver = [SUUnarchiver unarchiverForPath:self.downloadPath updatingHostBundlePath:[[self.host bundle] bundlePath]];
if (!unarchiver) {
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];
} else {
unarchiver.delegate = self;
[unarchiver start];
return;
}
unarchiver.delegate = self;
[unarchiver start];
}
- (void)failedToApplyDeltaUpdate
@@ -358,9 +395,6 @@
- (void)unarchiverDidFail:(SUUnarchiver *)__unused ua
{
// No longer needed
self.updateValidator = nil;
if ([self.updateItem isDeltaUpdate]) {
[self failedToApplyDeltaUpdate];
return;
@@ -375,49 +409,23 @@
[self installWithToolAndRelaunch:relaunch displayingUserInterface:relaunch];
}
// Creates intermediate directories up until targetPath if they don't already exist,
// and removes the directory at targetPath if one already exists there
- (BOOL)preparePathForRelaunchTool:(NSString *)targetPath error:(NSError * __autoreleasing *)error
{
NSFileManager *fileManager = [[NSFileManager alloc] init];
if ([fileManager fileExistsAtPath:targetPath]) {
NSError *removeError = nil;
if (![fileManager removeItemAtPath:targetPath error:&removeError]) {
if (error != NULL) {
*error = removeError;
}
return NO;
}
} else {
NSError *createDirectoryError = nil;
if (![fileManager createDirectoryAtPath:[targetPath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:@{} error:&createDirectoryError]) {
if (error != NULL) {
*error = createDirectoryError;
}
return NO;
}
}
return YES;
}
- (void)installWithToolAndRelaunch:(BOOL)relaunch displayingUserInterface:(BOOL)showUI
{
assert(self.updateItem);
assert(self.updateValidator);
BOOL validationCheckSuccess = [self.updateValidator validateWithUpdateDirectory:self.tempDir];
if (!validationCheckSuccess) {
if (![self validateUpdateDownloadedToPath:self.downloadPath extractedToPath:self.tempDir DSASignature:self.updateItem.DSASignature publicDSAKey:self.host.publicDSAKey])
{
NSDictionary *userInfo = @{
NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while extracting the archive. Please try again later.", nil),
NSLocalizedFailureReasonErrorKey: SULocalizedString(@"The update is improperly signed.", nil),
};
NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while extracting the archive. Please try again later.", nil),
NSLocalizedFailureReasonErrorKey: SULocalizedString(@"The update is improperly signed.", nil),
};
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUSignatureError userInfo:userInfo]];
return;
}
if (![self.updater mayUpdateAndRestart])
{
[self abortUpdate];
[self abortUpdate:SUUpdateAbortForbiddenByDelegate];
return;
}
@@ -446,43 +454,32 @@
// Copy the relauncher into a temporary directory so we can get to it after the new version's installed.
// Only the paranoid survive: if there's already a stray copy of relaunch there, we would have problems.
NSString *const relaunchToolName = @"" SPARKLE_RELAUNCH_TOOL_NAME;
NSString *const relaunchToolSourcePath = [sparkleBundle pathForResource:relaunchToolName ofType:@"app"];
NSString *relaunchCopyTargetPath = nil;
NSError *error = nil;
BOOL copiedRelaunchPath = NO;
NSString *const relaunchPathToCopy = [sparkleBundle pathForResource:relaunchToolName ofType:@"app"];
if (relaunchPathToCopy != nil) {
NSString *targetPath = [self.host.appCachePath stringByAppendingPathComponent:[relaunchPathToCopy lastPathComponent]];
// Only the paranoid survive: if there's already a stray copy of relaunch there, we would have problems.
NSError *error = nil;
[[NSFileManager defaultManager] createDirectoryAtPath:[targetPath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:@{} error:&error];
if (relaunchToolSourcePath) {
relaunchCopyTargetPath = [[self appCachePath] stringByAppendingPathComponent:[relaunchToolSourcePath lastPathComponent]];
SUFileManager *fileManager = [SUFileManager defaultManager];
NSURL *relaunchToolSourceURL = [NSURL fileURLWithPath:relaunchToolSourcePath];
NSURL *relaunchCopyTargetURL = [NSURL fileURLWithPath:relaunchCopyTargetPath];
// We only need to run our copy of the app by spawning a task
// Since we are copying the app to a directory that is write-accessible, we don't need to muck with owner/group IDs
if ([self preparePathForRelaunchTool:relaunchCopyTargetPath error:&error] && [fileManager copyItemAtURL:relaunchToolSourceURL toURL:relaunchCopyTargetURL error:&error]) {
copiedRelaunchPath = YES;
// We probably don't need to release the quarantine, but we'll do it just in case it's necessary.
// Perhaps in a sandboxed environment this matters more. Note that this may not be a fatal error.
NSError *quarantineError = nil;
if (![fileManager releaseItemFromQuarantineAtRootURL:relaunchCopyTargetURL error:&quarantineError]) {
SULog(@"Failed to release quarantine on %@ with error %@", relaunchCopyTargetPath, quarantineError);
}
BOOL copySuccess = NO;
if (SUShouldUseXPCInstaller())
{
copySuccess = [SUXPCInstaller copyPathWithAuthentication:relaunchPathToCopy overPath:targetPath appendVersion:SPARKLE_APPEND_VERSION_NUMBER error:&error];
}
else
{
copySuccess = [SUPlainInstaller copyPathWithAuthentication:relaunchPathToCopy overPath:targetPath appendVersion:SPARKLE_APPEND_VERSION_NUMBER error:&error];
}
if (copySuccess) {
self.relaunchPath = targetPath;
} else {
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SURelaunchError userInfo:@{
NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while extracting the archive. Please try again later.", nil),
NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:@"Couldn't copy relauncher (%@) to temporary path (%@)! %@", relaunchPathToCopy, targetPath, (error ? [error localizedDescription] : @"")]
}]];
}
}
if (!copiedRelaunchPath) {
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SURelaunchError userInfo:@{
NSLocalizedDescriptionKey: [NSString stringWithFormat:SULocalizedString(@"An error occurred while relaunching %1$@, but the new version will be available next time you run %1$@.", nil), [self.host name]],
NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:@"Couldn't copy relauncher (%@) to temporary path (%@)! %@",
relaunchToolSourcePath, relaunchCopyTargetPath, (error ? [error localizedDescription] : @"")],
}]];
return;
}
self.relaunchPath = relaunchCopyTargetPath; // Set for backwards compatibility, in case any delegates modify it
[[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterWillRestartNotification object:self];
if ([updaterDelegate respondsToSelector:@selector(updaterWillRelaunchApplication:)])
[updaterDelegate updaterWillRelaunchApplication:self.updater];
@@ -492,8 +489,9 @@
// Note that we explicitly use the host app's name here, since updating plugin for Mail relaunches Mail, not just the plugin.
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SURelaunchError userInfo:@{
NSLocalizedDescriptionKey: [NSString stringWithFormat:SULocalizedString(@"An error occurred while relaunching %1$@, but the new version will be available next time you run %1$@.", nil), [self.host name]],
NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:@"Couldn't find the relauncher (expected to find it at %@ 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;
}
@@ -501,17 +499,23 @@
if ([updaterDelegate respondsToSelector:@selector(pathToRelaunchForUpdater:)]) {
pathToRelaunch = [updaterDelegate pathToRelaunchForUpdater:self.updater];
}
[NSTask launchedTaskWithLaunchPath:relaunchToolPath arguments:@[[self.host bundlePath],
pathToRelaunch,
[NSString stringWithFormat:@"%d", [[NSProcessInfo processInfo] processIdentifier]],
self.tempDir,
relaunch ? @"1" : @"0",
showUI ? @"1" : @"0"]];
NSArray *arguments = @[[self.host bundlePath],
pathToRelaunch,
[NSString stringWithFormat:@"%d", [[NSProcessInfo processInfo] processIdentifier]],
self.tempDir,
relaunch ? @"1" : @"0",
showUI ? @"1" : @"0"];
if (SUShouldUseXPCInstaller())
{
[SUXPCInstaller launchTaskWithPath:relaunchToolPath arguments:arguments environment:nil currentDirectoryPath:nil inputData:nil waitUntilDone:NO completionHandler:nil];
}
else
{
[NSTask launchedTaskWithLaunchPath:relaunchToolPath arguments:arguments];
}
[self terminateApp];
}
// Note: this is overridden by the automatic update driver to not terminate in some cases
- (void)terminateApp
{
[NSApp terminate:self];
@@ -543,23 +547,18 @@
}]];
}
- (void)abortUpdate
- (void)abortUpdate:(SUUpdateAbortReason)reason
{
[self cleanUpDownload];
[[NSNotificationCenter defaultCenter] removeObserver:self];
self.updateItem = nil;
[super abortUpdate];
[super abortUpdate:reason];
}
- (void)abortUpdateWithError:(NSError *)error
{
if ([error code] != SUNoUpdateError) { // Let's not bother logging this.
NSError *errorToDisplay = error;
int finiteRecursion=5;
do {
SULog(@"Error: %@ %@ (URL %@)", errorToDisplay.localizedDescription, errorToDisplay.localizedFailureReason, [errorToDisplay.userInfo objectForKey:NSURLErrorFailingURLErrorKey]);
errorToDisplay = [errorToDisplay.userInfo objectForKey:NSUnderlyingErrorKey];
} while(--finiteRecursion && errorToDisplay);
SULog(@"Error: %@ %@ (URL %@)", error.localizedDescription, error.localizedFailureReason, error.userInfo[NSURLErrorFailingURLErrorKey]);
}
if (self.download) {
[self.download cancel];
@@ -571,7 +570,7 @@
[updaterDelegate updater:self.updater didAbortWithError:error];
}
[self abortUpdate];
[self abortUpdate:SUUpdateAbortGotError];
}
@end
+3 -4
View File
@@ -7,7 +7,6 @@
//
#include "SUBinaryDeltaCommon.h"
#import "SUFileManager.h"
#include <CommonCrypto/CommonDigest.h>
#include <Foundation/Foundation.h>
#include <fcntl.h>
@@ -221,7 +220,7 @@ BOOL removeTree(NSString *path)
BOOL copyTree(NSString *source, NSString *dest)
{
return [[SUFileManager defaultManager] copyItemAtURL:[NSURL fileURLWithPath:source] toURL:[NSURL fileURLWithPath:dest] error:NULL];
return [[NSFileManager defaultManager] copyItemAtPath:source toPath:dest error:nil];
}
BOOL modifyPermissions(NSString *path, mode_t desiredPermissions)
@@ -231,12 +230,12 @@ BOOL modifyPermissions(NSString *path, mode_t desiredPermissions)
if (!attributes) {
return NO;
}
NSNumber *permissions = [attributes objectForKey:NSFilePosixPermissions];
NSNumber *permissions = attributes[NSFilePosixPermissions];
if (!permissions) {
return NO;
}
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) {
return NO;
}
+1 -11
View File
@@ -87,7 +87,7 @@ static NSDictionary *infoForFile(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) {
return NO;
}
@@ -439,16 +439,6 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
NSString *temporaryFile = temporaryPatchFile(patchFile);
xar_t x = xar_open([temporaryFile fileSystemRepresentation], WRITE);
if (!x) {
if (verbose) {
fprintf(stderr, "\n");
}
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileWriteUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to write to %@", temporaryFile] }];
}
return NO;
}
xar_opt_set(x, XAR_OPT_COMPRESSION, "bzip2");
xar_subdoc_t attributes = xar_subdoc_new(x, BINARY_DELTA_ATTRIBUTES_KEY);
+1 -43
View File
@@ -10,9 +10,9 @@
#import "SUBinaryDeltaUnarchiver.h"
#import "SUBinaryDeltaApply.h"
#import "SUUnarchiver_Private.h"
#import "SUFileManager.h"
#import "SUHost.h"
#import "SULog.h"
#import "NTSynchronousTask.h"
@implementation SUBinaryDeltaUnarchiver
@@ -21,46 +21,6 @@
return [[path pathExtension] isEqualToString:@"delta"];
}
+ (BOOL)unsafeIfArchiveIsNotValidated
{
return YES;
}
// According to https://developer.apple.com/library/mac/documentation/Carbon/Conceptual/MDImporters/Concepts/Troubleshooting.html
// We should make sure mdimporter bundles have an up to date time in the event they were delta updated.
// We used to invoke mdimport on the bundle but this is not a very good approach.
// There's no need to do that for non-delta updates and for updates that contain no mdimporters.
// Moreover, updating the timestamp on the mdimporter bundles is what developers have to do anyway when shipping their new update outside of Sparkle
+ (void)updateSpotlightImportersAtBundlePath:(NSString *)targetPath
{
NSURL *targetURL = [NSURL fileURLWithPath:targetPath];
// Only recurse if it's actually a directory. Don't recurse into a
// root-level symbolic link.
NSDictionary *rootAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:targetPath error:nil];
NSString *rootType = [rootAttributes objectForKey:NSFileType];
if ([rootType isEqualToString:NSFileTypeDirectory]) {
// The NSDirectoryEnumerator will avoid recursing into any contained
// symbolic links, so no further type checks are needed.
NSDirectoryEnumerator *directoryEnumerator = [[NSFileManager defaultManager] enumeratorAtURL:targetURL includingPropertiesForKeys:nil options:(NSDirectoryEnumerationOptions)0 errorHandler:nil];
NSMutableArray *filesToUpdate = [[NSMutableArray alloc] init];
for (NSURL *file in directoryEnumerator) {
if ([file.pathExtension isEqualToString:@"mdimporter"]) {
[filesToUpdate addObject:file];
}
}
SUFileManager *fileManager = [SUFileManager defaultManager];
for (NSURL *file in filesToUpdate) {
NSError *error = nil;
if (![fileManager updateModificationAndAccessTimeOfItemAtURL:file error:&error]) {
SULog(@"Error: During delta unarchiving, failed to touch %@", error);
}
}
}
}
- (void)applyBinaryDelta
{
@autoreleasepool {
@@ -70,8 +30,6 @@
NSError *applyDiffError = nil;
BOOL success = applyBinaryDelta(sourcePath, targetPath, self.archivePath, NO, &applyDiffError);
if (success) {
[[self class] updateSpotlightImportersAtBundlePath:targetPath];
dispatch_async(dispatch_get_main_queue(), ^{
[self notifyDelegateOfSuccess];
});
+5 -3
View File
@@ -12,9 +12,11 @@
#import <Foundation/Foundation.h>
@interface SUCodeSigningVerifier : NSObject
+ (BOOL)codeSignatureAtBundleURL:(NSURL *)oldBundlePath matchesSignatureAtBundleURL:(NSURL *)newBundlePath error:(NSError **)error;
+ (BOOL)codeSignatureIsValidAtBundleURL:(NSURL *)bundlePath error:(NSError **)error;
+ (BOOL)bundleAtURLIsCodeSigned:(NSURL *)bundlePath;
+ (BOOL)codeSignatureMatchesHostAndIsValidAtPath:(NSString *)applicationPath error:(NSError **)error;
+ (BOOL)codeSignatureIsValidAtPath:(NSString *)applicationPath error:(NSError **)error;
+ (BOOL)hostApplicationIsCodeSigned;
+ (BOOL)applicationAtPathIsCodeSigned:(NSString *)applicationPath;
+ (BOOL)hostApplicationIsSandboxed;
@end
#endif
+108 -33
View File
@@ -13,46 +13,53 @@
@implementation SUCodeSigningVerifier
+ (BOOL)codeSignatureAtBundleURL:(NSURL *)oldBundleURL matchesSignatureAtBundleURL:(NSURL *)newBundleURL error:(NSError *__autoreleasing *)error
+ (BOOL)codeSignatureMatchesHostAndIsValidAtPath:(NSString *)applicationPath error:(NSError *__autoreleasing *)error
{
OSStatus result;
SecRequirementRef requirement = NULL;
SecStaticCodeRef staticCode = NULL;
SecStaticCodeRef oldCode = NULL;
SecCodeRef hostCode = NULL;
NSBundle *newBundle;
CFErrorRef cfError = NULL;
if (error) {
*error = nil;
}
result = SecStaticCodeCreateWithPath((__bridge CFURLRef)oldBundleURL, kSecCSDefaultFlags, &oldCode);
if (result == errSecCSUnsigned) {
return NO;
result = SecCodeCopySelf(kSecCSDefaultFlags, &hostCode);
if (result != noErr) {
SULog(@"Failed to copy host code %d", result);
goto finally;
}
result = SecCodeCopyDesignatedRequirement(oldCode, kSecCSDefaultFlags, &requirement);
result = SecCodeCopyDesignatedRequirement(hostCode, kSecCSDefaultFlags, &requirement);
if (result != noErr) {
SULog(@"Failed to copy designated requirement. Code Signing OSStatus code: %d", result);
goto finally;
}
result = SecStaticCodeCreateWithPath((__bridge CFURLRef)newBundleURL, kSecCSDefaultFlags, &staticCode);
newBundle = [NSBundle bundleWithPath:applicationPath];
if (!newBundle) {
SULog(@"Failed to load NSBundle for update");
result = -1;
goto finally;
}
result = SecStaticCodeCreateWithPath((__bridge CFURLRef)[newBundle bundleURL], kSecCSDefaultFlags, &staticCode);
if (result != noErr) {
SULog(@"Failed to get static code %d", result);
goto finally;
}
// Note that kSecCSCheckNestedCode may not work with pre-Mavericks code signing.
// See https://github.com/sparkle-project/Sparkle/issues/376#issuecomment-48824267 and https://developer.apple.com/library/mac/technotes/tn2206
// Aditionally, there are several reasons to stay away from deep verification and to prefer DSA signing the download archive instead.
// See https://github.com/sparkle-project/Sparkle/pull/523#commitcomment-17549302 and https://github.com/sparkle-project/Sparkle/issues/543
SecCSFlags flags = (SecCSFlags) (kSecCSDefaultFlags | kSecCSCheckAllArchitectures);
SecCSFlags flags = (SecCSFlags) (kSecCSDefaultFlags | kSecCSCheckAllArchitectures);
result = SecStaticCodeCheckValidityWithErrors(staticCode, flags, requirement, &cfError);
if (cfError) {
NSError *tmpError = CFBridgingRelease(cfError);
if (error) *error = tmpError;
}
if (result != noErr) {
if (result == errSecCSUnsigned) {
SULog(@"The host app is signed, but the new version of the app is not signed using Apple Code Signing. Please ensure that the new app is signed and that archiving did not corrupt the signature.");
@@ -63,52 +70,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);
CFRelease(requirementString);
}
[self logSigningInfoForCode:oldCode label:@"old info"];
[self logSigningInfoForCode:hostCode label:@"host info"];
[self logSigningInfoForCode:staticCode label:@"new info"];
}
}
finally:
if (oldCode) CFRelease(oldCode);
if (hostCode) CFRelease(hostCode);
if (staticCode) CFRelease(staticCode);
if (requirement) CFRelease(requirement);
return (result == noErr);
}
+ (BOOL)codeSignatureIsValidAtBundleURL:(NSURL *)bundleURL error:(NSError *__autoreleasing *)error
+ (BOOL)codeSignatureIsValidAtPath:(NSString *)applicationPath error:(NSError *__autoreleasing *)error
{
OSStatus result;
SecStaticCodeRef staticCode = NULL;
NSBundle *newBundle;
CFErrorRef cfError = NULL;
if (error) {
*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) {
SULog(@"Failed to get static code %d", result);
goto finally;
}
// See in -codeSignatureAtBundleURL:matchesSignatureAtBundleURL:error: for why kSecCSCheckNestedCode is not passed
SecCSFlags flags = (SecCSFlags) (kSecCSDefaultFlags | kSecCSCheckAllArchitectures);
// Note that kSecCSCheckNestedCode may not work with pre-Mavericks code signing.
// See https://github.com/sparkle-project/Sparkle/issues/376#issuecomment-48824267 and https://developer.apple.com/library/mac/technotes/tn2206
SecCSFlags flags = (SecCSFlags) (kSecCSDefaultFlags | kSecCSCheckAllArchitectures);
result = SecStaticCodeCheckValidityWithErrors(staticCode, flags, NULL, &cfError);
if (cfError) {
NSError *tmpError = CFBridgingRelease(cfError);
if (error) *error = tmpError;
}
if (result != noErr) {
if (result == errSecCSUnsigned) {
SULog(@"Error: The app is not signed using Apple Code Signing. %@", bundleURL);
SULog(@"Error: The app is not signed using Apple Code Signing. %@", applicationPath);
}
if (result == errSecCSReqFailed) {
[self logSigningInfoForCode:staticCode label:@"new info"];
}
}
finally:
if (staticCode) CFRelease(staticCode);
return (result == noErr);
@@ -125,23 +141,82 @@ static id valueOrNSNull(id value) {
NSDictionary *signingDict = CFBridgingRelease(signingInfo);
NSMutableDictionary *relevantInfo = [NSMutableDictionary dictionary];
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"];
[relevantInfo setObject:valueOrNSNull([infoPlist objectForKey:@"CFBundleShortVersionString"]) forKey:@"version"];
[relevantInfo setObject:valueOrNSNull([infoPlist objectForKey:(__bridge NSString *)kCFBundleVersionKey]) forKey:@"build"];
NSDictionary *infoPlist = signingDict[@"info-plist"];
relevantInfo[@"version"] = valueOrNSNull(infoPlist[@"CFBundleShortVersionString"]);
relevantInfo[@"build"] = valueOrNSNull(infoPlist[(__bridge NSString *)kCFBundleVersionKey]);
SULog(@"%@: %@", label, relevantInfo);
}
}
+ (BOOL)bundleAtURLIsCodeSigned:(NSURL *)bundleURL
+ (BOOL)hostApplicationIsCodeSigned
{
OSStatus result;
SecCodeRef hostCode = NULL;
result = SecCodeCopySelf(kSecCSDefaultFlags, &hostCode);
if (result != 0) return NO;
SecRequirementRef requirement = NULL;
result = SecCodeCopyDesignatedRequirement(hostCode, kSecCSDefaultFlags, &requirement);
if (hostCode) CFRelease(hostCode);
if (requirement) CFRelease(requirement);
return (result == 0);
}
+ (BOOL)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;
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) {
return NO;
return NO;
}
SecRequirementRef requirement = NULL;
@@ -153,7 +228,7 @@ static id valueOrNSNull(id value) {
CFRelease(requirement);
}
if (result == errSecCSUnsigned) {
return NO;
return NO;
}
return (result == 0);
}
+16 -1
View File
@@ -12,6 +12,21 @@
#import <Foundation/Foundation.h>
// -----------------------------------------------------------------------------
// Typedefs:
// -----------------------------------------------------------------------------
typedef NS_ENUM(NSUInteger, SUUpdateAbortReason)
{
SUUpdateAbortUndefined = 0,
SUUpdateAbortForbiddenByDelegate,
SUUpdateAbortTasksFinished,
SUUpdateAbortCanceledByUser,
SUUpdateAbortDidNotFind,
SUUpdateAbortInterrupred,
SUUpdateAbortGotError
};
// -----------------------------------------------------------------------------
// Misc:
// -----------------------------------------------------------------------------
@@ -43,13 +58,13 @@ extern NSString *const SUPublicDSAKeyFileKey;
extern NSString *const SUAutomaticallyUpdateKey;
extern NSString *const SUAllowsAutomaticUpdatesKey;
extern NSString *const SUEnableAutomaticChecksKey;
extern NSString *const SUEnableAutomaticChecksKeyOld;
extern NSString *const SUEnableSystemProfilingKey;
extern NSString *const SUSendProfileInfoKey;
extern NSString *const SULastProfileSubmitDateKey;
extern NSString *const SUPromptUserOnFirstLaunchKey;
extern NSString *const SUKeepDownloadOnFailedInstallKey;
extern NSString *const SUDefaultsDomainKey;
extern NSString *const SUEnableJavaScriptKey;
extern NSString *const SUFixedHTMLDisplaySizeKey __attribute__((deprecated("This key is obsolete and has no effect.")));
extern NSString *const SUAppendVersionNumberKey __attribute__((deprecated("This key is obsolete. See SPARKLE_APPEND_VERSION_NUMBER.")));
extern NSString *const SUEnableAutomatedDowngradesKey __attribute__((deprecated("This key is obsolete. See SPARKLE_AUTOMATED_DOWNGRADES.")));
+2 -1
View File
@@ -12,6 +12,7 @@
#import "SUAppcastItem.h"
#import "SUVersionComparisonProtocol.h"
#import "SUConstants.h"
#import "SUErrors.h"
#ifndef DEBUG
#define DEBUG 0
@@ -38,10 +39,10 @@ NSString *const SUAutomaticallyUpdateKey = @"SUAutomaticallyUpdate";
NSString *const SUAllowsAutomaticUpdatesKey = @"SUAllowsAutomaticUpdates";
NSString *const SUEnableSystemProfilingKey = @"SUEnableSystemProfiling";
NSString *const SUEnableAutomaticChecksKey = @"SUEnableAutomaticChecks";
NSString *const SUEnableAutomaticChecksKeyOld = @"SUCheckAtStartup";
NSString *const SUSendProfileInfoKey = @"SUSendProfileInfo";
NSString *const SULastProfileSubmitDateKey = @"SULastProfileSubmissionDate";
NSString *const SUPromptUserOnFirstLaunchKey = @"SUPromptUserOnFirstLaunch";
NSString *const SUEnableJavaScriptKey = @"SUEnableJavaScript";
NSString *const SUFixedHTMLDisplaySizeKey = @"SUFixedHTMLDisplaySize";
NSString *const SUKeepDownloadOnFailedInstallKey = @"SUKeepDownloadOnFailedInstall";
NSString *const SUDefaultsDomainKey = @"SUDefaultsDomain";
+78 -77
View File
@@ -8,8 +8,10 @@
#import "SUDiskImageUnarchiver.h"
#import "SUUnarchiver_Private.h"
#import "NTSynchronousTask.h"
#import "SULog.h"
#include <CoreServices/CoreServices.h>
#import "SUXPCInstaller.h"
@implementation SUDiskImageUnarchiver
@@ -18,11 +20,6 @@
return [[path pathExtension] isEqualToString:@"dmg"];
}
+ (BOOL)unsafeIfArchiveIsNotValidated
{
return NO;
}
// Called on a non-main thread.
- (void)extractDMG
{
@@ -39,12 +36,6 @@
SULog(@"Extracting %@ as a DMG", self.archivePath);
// get a unique mount point path
NSString *mountPoint = nil;
FSRef tmpRef;
NSFileManager *manager;
NSError *error;
NSArray *contents;
// We have to declare these before a goto to prevent an error under ARC.
// No, we cannot have them in the dispatch_async calls, as the goto "jump enters
// lifetime of block which strongly captures a variable"
@@ -54,7 +45,10 @@
dispatch_block_t delegateSuccess = ^{
[self notifyDelegateOfSuccess];
};
do
// get a unique mount point path
NSString *mountPoint = nil;
do
{
// Using NSUUID would make creating UUIDs be done in Cocoa,
// and thus managed under ARC. Sadly, the class is in 10.8 and later.
@@ -69,51 +63,37 @@
CFRelease(uuid);
}
}
while (noErr == FSPathMakeRefWithOptions((const UInt8 *)[mountPoint fileSystemRepresentation], kFSPathMakeRefDoNotFollowLeafSymlink, &tmpRef, NULL));
while ([[NSFileManager defaultManager] fileExistsAtPath:mountPoint]);
NSData *promptData = nil;
promptData = [NSData dataWithBytes:"yes\n" length:4];
NSMutableArray *arguments = [@[@"attach", self.archivePath, @"-mountpoint", mountPoint, /*@"-noverify",*/ @"-nobrowse", @"-noautoopen"] mutableCopy];
NSString *hdiutilPath = @"/usr/bin/hdiutil";
NSArray *arguments = @[@"attach", self.archivePath, @"-mountpoint", mountPoint, /*@"-noverify",*/ @"-nobrowse", @"-noautoopen"];
NSString *currentDirPath = @"/";
if (self.decryptionPassword) {
NSMutableData *passwordData = [[self.decryptionPassword dataUsingEncoding:NSUTF8StringEncoding] mutableCopy];
// From the hdiutil docs:
// read a null-terminated passphrase from standard input
//
// Add the null terminator, then the newline
[passwordData appendData:[NSData dataWithBytes:"\0" length:1]];
[passwordData appendData:promptData];
promptData = passwordData;
[arguments addObject:@"-stdinpass"];
}
NSData *output = nil;
NSInteger taskResult = -1;
BOOL shouldUseXPC = SUShouldUseXPCInstaller();
__block NSData *output = nil;
__block NSInteger taskResult = -1;
@try
{
NSTask *task = [[NSTask alloc] init];
task.launchPath = @"/usr/bin/hdiutil";
task.currentDirectoryPath = @"/";
task.arguments = arguments;
NSPipe *inputPipe = [NSPipe pipe];
NSPipe *outputPipe = [NSPipe pipe];
task.standardInput = inputPipe;
task.standardOutput = outputPipe;
[task launch];
[inputPipe.fileHandleForWriting writeData:promptData];
[inputPipe.fileHandleForWriting closeFile];
// Read data to end *before* waiting until the task ends so we don't deadlock if the stdout buffer becomes full if we haven't consumed from it
output = [outputPipe.fileHandleForReading readDataToEndOfFile];
[task waitUntilExit];
taskResult = task.terminationStatus;
if (shouldUseXPC)
{
[SUXPCInstaller launchTaskWithPath:hdiutilPath arguments:arguments environment:nil currentDirectoryPath:currentDirPath inputData:promptData waitUntilDone:YES completionHandler:^(int result, NSData *outputData) {
taskResult = (NSInteger)result;
output = [outputData copy];
}];
}
else
{
NTSynchronousTask *task = [[NTSynchronousTask alloc] init];
[task run:hdiutilPath directory:currentDirPath withArgs:arguments input:promptData];
taskResult = [task result];
output = [[task output] copy];
}
}
@catch (NSException *)
{
@@ -129,30 +109,45 @@
mountedSuccessfully = YES;
// Now that we've mounted it, we need to copy out its contents.
manager = [[NSFileManager alloc] init];
contents = [manager contentsOfDirectoryAtPath:mountPoint error:&error];
if (error)
{
SULog(@"Couldn't enumerate contents of archive mounted at %@: %@", mountPoint, error);
goto reportError;
if (shouldUseXPC)
{
NSError *error = nil;
[SUXPCInstaller copyPathContent:mountPoint toDirectory:[self.archivePath stringByDeletingLastPathComponent] error:&error];
if (nil != error)
{
SULog(@"Couldn't copy volume content: %ld - %@", error.code, error.localizedDescription);
goto reportError;
}
}
for (NSString *item in contents)
{
NSString *fromPath = [mountPoint stringByAppendingPathComponent:item];
NSString *toPath = [[self.archivePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:item];
// We skip any files in the DMG which are not readable.
if (![manager isReadableFileAtPath:fromPath]) {
continue;
else
{
NSFileManager *manager = [[NSFileManager alloc] init];
NSError *error = nil;
NSArray *contents = [manager contentsOfDirectoryAtPath:mountPoint error:&error];
if (error)
{
SULog(@"Couldn't enumerate contents of archive mounted at %@: %@", mountPoint, error);
goto reportError;
}
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])
{
SULog(@"Couldn't copy item: %@ : %@", error, error.userInfo ? error.userInfo : @"");
goto reportError;
// We skip any files in the DMG which are not readable.
if (![manager isReadableFileAtPath:fromPath]) {
continue;
}
SULog(@"copyItemAtPath:%@ toPath:%@", fromPath, toPath);
if (![manager copyItemAtPath:fromPath toPath:toPath error:&error])
{
SULog(@"Couldn't copy item: %@ : %@", error, error.userInfo ? error.userInfo : @"");
goto reportError;
}
}
}
@@ -163,14 +158,20 @@
dispatch_async(dispatch_get_main_queue(), delegateFailure);
finally:
if (mountedSuccessfully) {
@try {
[NSTask launchedTaskWithLaunchPath:@"/usr/bin/hdiutil" arguments:@[@"detach", mountPoint, @"-force"]];
} @catch (NSException *exception) {
SULog(@"Failed to unmount %@", mountPoint);
SULog(@"Exception: %@", exception);
if (mountedSuccessfully)
{
arguments = @[@"detach", mountPoint, @"-force"];
if (shouldUseXPC)
{
[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);
}
}
+4 -11
View File
@@ -9,11 +9,7 @@
#ifndef SUERRORS_H
#define SUERRORS_H
#if __has_feature(modules)
@import Foundation;
#else
#import <Foundation/Foundation.h>
#endif
#import "SUExport.h"
/**
@@ -27,11 +23,10 @@ typedef NS_ENUM(OSStatus, SUError) {
SUNoUpdateError = 1001,
SUAppcastError = 1002,
SURunningFromDiskImageError = 1003,
// Download phase errors.
// Downlaod phase errors.
SUTemporaryDirectoryError = 2000,
SUDownloadError = 2001,
// Extraction phase errors.
SUUnarchivingError = 3000,
SUSignatureError = 3001,
@@ -44,10 +39,8 @@ typedef NS_ENUM(OSStatus, SUError) {
SURelaunchError = 4004,
SUInstallationError = 4005,
SUDowngradeError = 4006,
SUInstallationCancelledError = 4007,
// System phase errors
SUSystemPowerOffError = 5000
SUXPCServiceError = 4007
};
#endif
-171
View File
@@ -1,171 +0,0 @@
//
// SUFileManager.h
// Sparkle
//
// Created by Mayur Pawashe on 7/18/15.
// Copyright (c) 2015 zgcoder. All rights reserved.
//
#import <Foundation/Foundation.h>
/**
* A class used for performing file operations that may also perform authorization if allowed and if permission is denied when trying to
* perform them normally as the running user. All operations on this class may be used on thread other than the main thread.
* This class provides basic file operations and stays away from including much application-level logic.
*/
@interface SUFileManager : NSObject
/**
* Creates a file manager that will not authorize for file operations
* @return A new file manager instance
*/
+ (instancetype)defaultManager;
/**
* Creates a file manager that allows authorizing for file operations
* @param authorizationToolPath Specifies the path to the tool that can perform file operations and be run as root.
* This tool will be invoked when read or write access is denied when attempting ordinary file operations. See the `fileop` tool included in Sparkle.
* @return A new file manager instance
*
* This method just creates the file manager. It doesn't acquire authorization immediately or if it doesn't need to.
*/
+ (instancetype)fileManagerWithAuthorizationToolPath:(NSString *)authorizationToolPath;
/**
* Returns a file manager that allows or disallows authorizing for file operations based on the current file manager
* @return A file manager instance that can perform authorized operations if the current file manager has already performed them.
* If the current file manager instance hasn't yet performed authorized operations, then neither can the instance returned by this method
*
* This may return a newly created file manager or re-use the existing file manager depending on the current authorization rights.
*/
- (instancetype)fileManagerByPreservingAuthorizationRights;
/**
* Creates a temporary directory on the same volume as a provided URL
* @param preferredName A name that may be used when creating the temporary directory. Note that in the uncommon case this name is used, the temporary directory will be created inside the directory pointed by appropriateURL
* @param appropriateURL A URL to a directory that resides on the volume that the temporary directory will be created on. In the uncommon case, the temporary directory may be created inside this directory.
* @param error If an error occurs, upon returns contains an NSError object that describes the problem. If you are not interested in possible errors, you may pass in NULL.
* @return A URL pointing to the newly created temporary directory, or nil with a populated error object if an error occurs.
*
* When moving an item from a source to a destination, it is desirable to create a temporary intermediate destination on the same volume as the destination to ensure
* that the item will be moved, and not copied, from the intermediate point to the final destination. This ensures file atomicity.
*/
- (NSURL *)makeTemporaryDirectoryWithPreferredName:(NSString *)preferredName appropriateForDirectoryURL:(NSURL *)appropriateURL error:(NSError **)error;
/**
* Creates a directory at the target URL
* @param targetURL A URL pointing to the directory to create. The item at this URL must not exist, and the parent directory of this URL must already exist.
* @param error If an error occurs, upon returns contains an NSError object that describes the problem. If you are not interested in possible errors, you may pass in NULL.
* @return YES if the item was created successfully, otherwise NO along with a populated error object
*
* This is an atomic operation.
*/
- (BOOL)makeDirectoryAtURL:(NSURL *)targetURL error:(NSError **)error;
/**
* Moves an item from a source to a destination
* @param sourceURL A URL pointing to the item to move. The item at this URL must exist.
* @param destinationURL A URL pointing to the destination the item will be moved at. An item must not already exist at this URL.
* @param error If an error occurs, upon returns contains an NSError object that describes the problem. If you are not interested in possible errors, you may pass in NULL.
* @return YES if the item was moved successfully, otherwise NO along with a populated error object
*
* If sourceURL and destinationURL reside on the same volume, this operation will be an atomic move operation.
* Otherwise this will be equivalent to a copy & remove which will be a nonatomic operation.
*/
- (BOOL)moveItemAtURL:(NSURL *)sourceURL toURL:(NSURL *)destinationURL error:(NSError **)error;
/**
* Copies an item from a source to a destination
* @param sourceURL A URL pointing to the item to move. The item at this URL must exist.
* @param destinationURL A URL pointing to the destination the item will be moved at. An item must not already exist at this URL.
* @param error If an error occurs, upon returns contains an NSError object that describes the problem. If you are not interested in possible errors, you may pass in NULL.
* @return YES if the item was copied successfully, otherwise NO along with a populated error object
*
* This is not an atomic operation.
*/
- (BOOL)copyItemAtURL:(NSURL *)sourceURL toURL:(NSURL *)destinationURL error:(NSError **)error;
/**
* Moves an item at a specified URL to the running user's trash directory
* @param url A URL pointing to the item to move to the trash. The item at this URL must exist.
* @param error If an error occurs, upon returns contains an NSError object that describes the problem. If you are not interested in possible errors, you may pass in NULL.
* @return YES if the item was moved to the trash successfully, otherwise NO along with a populated error object
*
*
* This method has to locate the trash directory and uses an intermediate temporary directory before trashing the item.
* A copy may have to be done if the url is not on the same volume as the running user's trash directory.
* If a failure occurs in the middle of this operation, the item to remove may be lost forever or stuck in a temporary location.
*
* This is not an atomic operation, nor intended to be a recoverable operation if the worst comes to worst.
*/
- (BOOL)moveItemAtURLToTrash:(NSURL *)url error:(NSError **)error;
/**
* Removes an item at a URL
* @param url A URL pointing to the item to remove. The item at this URL must exist.
* @param error If an error occurs, upon returns contains an NSError object that describes the problem. If you are not interested in possible errors, you may pass in NULL.
* @return YES if the item was removed successfully, otherwise NO along with a populated error object
*
* This is not an atomic operation.
*/
- (BOOL)removeItemAtURL:(NSURL *)url error:(NSError **)error;
/**
* Changes the owner and group IDs of an item at a specified target URL to match another URL
* @param targetURL A URL pointing to the target item whose owner and group IDs to alter. This will be applied recursively if the item is a directory. The item at this URL must exist.
* @param matchURL A URL pointing to the item whose owner and group IDs will be used for changing on the targetURL. The item at this URL must exist.
* @param error If an error occurs, upon returns contains an NSError object that describes the problem. If you are not interested in possible errors, you may pass in NULL.
* @return YES if the target item's owner and group IDs have changed to match the origin's ones, otherwise NO along with a populated error object
*
* If the owner and group IDs match on the root items of targetURL and matchURL, this method stops and assumes that nothing needs to be done.
* Otherwise this method recursively changes the IDs if the target is a directory. If an item in the directory is encountered that is unable to be changed,
* then this method stops and returns NO.
*
* This is not an atomic operation.
*/
- (BOOL)changeOwnerAndGroupOfItemAtRootURL:(NSURL *)targetURL toMatchURL:(NSURL *)matchURL error:(NSError **)error;
/**
* Updates the modification and access time of an item at a specified target URL to the current time
* @param targetURL A URL pointing to the target item whose modification and access time to update. The item at this URL must exist.
* @param error If an error occurs, upon returns contains an NSError object that describes the problem. If you are not interested in possible errors, you may pass in NULL.
* @return YES if the target item's modification and access times have been updated, otherwise NO along with a populated error object
*
* This method updates the modification and access time of an item to the current time, ideal for letting the system know we installed a new file or
* application.
*
* This is not an atomic operation.
*/
- (BOOL)updateModificationAndAccessTimeOfItemAtURL:(NSURL *)targetURL error:(NSError **)error;
/**
* Releases Apple's quarantine extended attribute from the item at the specified root URL
* @param rootURL A URL pointing to the item to release from Apple's quarantine. This will be applied recursively if the item is a directory. The item at this URL must exist.
* @param error If an error occurs, upon returns contains an NSError object that describes the problem. If you are not interested in possible errors, you may pass in NULL.
* @return YES if all the items at the target could be released from quarantine, otherwise NO if any items couldn't along with a populated error object
*
* This method removes quarantine attributes from an item, ideally an application, so that when the user launches a new application themselves, they
* don't have to witness the system dialog alerting them that they downloaded an application from the internet and asking if they want to continue.
* Note that this may not exactly mimic the system behavior when a user opens an application for the first time (i.e, the xattr isn't deleted),
* but this should be sufficient enough for our purposes.
*
* This method may return NO even if some items do get released from quarantine if the target URL is pointing to a directory.
* Thus if an item cannot be released from quarantine, this method still continues on to the next enumerated item.
*
* This is not an atomic operation.
*/
- (BOOL)releaseItemFromQuarantineAtRootURL:(NSURL *)rootURL error:(NSError **)error;
/**
* Runs an installer package (pkg) in a headless mode using /usr/sbin/installer
* @param packageURL A URL pointing to the package to execute. The item at this URL must exist.
* @param error If an error occurs, upon returns contains an NSError object that describes the problem. If you are not interested in possible errors, you may pass in NULL.
* @return YES if the installer ran the package successfully, otherwise NO with a populated error object
*
* This method uses the system wide installer tool to run the provided package. This process does not show any UI, except for
* an initial authorization prompt if the calling process does not have root privileges. In other words, root privileges are required to use this method, and the file manager instance must have been created by allowing authorization.
* An error can occur if the package is unable to be ran by the installer, or if the installer reports a non-zero exit status code.
*/
- (BOOL)executePackageAtURL:(NSURL *)packageURL error:(NSError **)error;
@end
-1036
View File
File diff suppressed because it is too large. Load diff
+2 -2
View File
@@ -11,7 +11,7 @@
A guided installation allows Sparkle to download and install a package (pkg) or multi-package (mpkg) without user interaction.
The installer package is installed using 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.
@@ -29,7 +29,7 @@ A guided installation can be started by applications other than the application
@interface SUGuidedPackageInstaller : SUInstaller
/*! Perform the guided installation */
+ (void)performInstallationToPath:(NSString *)path fromPath:(NSString *)installerGuide host:(SUHost *)host 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
#endif
+119 -9
View File
@@ -6,27 +6,137 @@
// Copyright 2010 Dragon Systems Software Limited. All rights reserved.
//
#import <sys/stat.h>
#import <Security/Security.h>
#import "SUGuidedPackageInstaller.h"
#import "SUFileManager.h"
static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authorization, const char* executablePath, AuthorizationFlags options, char* const* arguments)
{
sig_t oldSigChildHandler = signal(SIGCHLD, SIG_DFL);
BOOL returnValue = YES;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
/* AuthorizationExecuteWithPrivileges used to support 10.4+; should be replaced with XPC or external process */
if (AuthorizationExecuteWithPrivileges(authorization, executablePath, options, arguments, NULL) == errAuthorizationSuccess)
#pragma clang diagnostic pop
{
int status = 0;
pid_t pid = wait(&status);
if (pid == -1 || !WIFEXITED(status) || WEXITSTATUS(status) != 0)
returnValue = NO;
}
else
returnValue = NO;
signal(SIGCHLD, oldSigChildHandler);
return returnValue;
}
@implementation SUGuidedPackageInstaller (SUGuidedPackageInstallerAuthentication)
+ (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
+ (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);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
SUFileManager *fileManager = [SUFileManager fileManagerWithAuthorizationToolPath:fileOperationToolPath];
NSError *error = nil;
BOOL validInstallation = [fileManager executePackageAtURL:[NSURL fileURLWithPath:packagePath] error:&error];
// Preflight
NSString* installerPath = @"/usr/sbin/installer"; // Mac OS X 10.2+ command line installer tool
NSError* error = nil;
// Create authorization for installer executable
BOOL validInstallation = NO;
AuthorizationRef auth = [self authorizationForExecutable:installerPath];
if (auth != NULL)
{
char pathBuffer[PATH_MAX] = {0};
[packagePath getFileSystemRepresentation:pathBuffer maxLength:sizeof(pathBuffer)];
// Permission was granted to execute the installer with privileges
char * const arguments[] = {
"-pkg",
pathBuffer,
"-target",
"/",
NULL
};
validInstallation = AuthorizationExecuteWithPrivilegesAndWait(auth,
[installerPath fileSystemRepresentation],
kAuthorizationFlagDefaults,
arguments);
// TODO: wait for communications pipe to close via fileno & CFSocketCreateWithNative
AuthorizationFree(auth,kAuthorizationFlagDefaults);
}
else
{
NSString* errorMessage = [NSString stringWithFormat:@"Sparkle Updater: Script authorization denied."];
error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:[NSDictionary dictionaryWithObject:errorMessage forKey:NSLocalizedDescriptionKey]];
}
dispatch_async(dispatch_get_main_queue(), ^{
[self finishInstallationToPath:destinationPath
withResult:validInstallation
error:error
completionHandler:completionHandler];
});
});
}
+4 -2
View File
@@ -23,9 +23,12 @@ typedef struct {
@property (strong, readonly) NSBundle *bundle;
+ (NSOperatingSystemVersion)operatingSystemVersion;
+ (NSString *)systemVersionString;
- (instancetype)initWithBundle:(NSBundle *)aBundle;
@property (readonly, copy) NSString *bundlePath;
@property (readonly) BOOL allowsAutomaticUpdates;
@property (readonly, copy) NSString *appCachePath;
@property (readonly, copy) NSString *installationPath;
@property (readonly, copy) NSString *name;
@property (readonly, copy) NSString *version;
@@ -34,7 +37,6 @@ typedef struct {
@property (getter=isRunningOnReadOnlyVolume, readonly) BOOL runningOnReadOnlyVolume;
@property (getter=isBackgroundApplication, readonly) BOOL backgroundApplication;
@property (readonly, copy) NSString *publicDSAKey;
@property (readonly, nonatomic, copy) NSString *publicDSAKeyFileKey;
@property (readonly, copy) NSArray *systemProfile;
- (id)objectForInfoDictionaryKey:(NSString *)key;
+46 -45
View File
@@ -11,7 +11,6 @@
#import "SUSystemProfiler.h"
#include <sys/mount.h> // For statfs for isRunningOnReadOnlyVolume
#import "SULog.h"
#import "SUFileManager.h"
#if __MAC_OS_X_VERSION_MAX_ALLOWED < 101000
@interface NSProcessInfo ()
@@ -63,46 +62,26 @@
return [self.bundle bundlePath];
}
- (BOOL)allowsAutomaticUpdates
- (NSString *)appCachePath
{
// Does the developer want us to disable automatic updates?
NSNumber *developerAllowsAutomaticUpdates = [self objectForInfoDictionaryKey:SUAllowsAutomaticUpdatesKey];
if (developerAllowsAutomaticUpdates != nil && !developerAllowsAutomaticUpdates.boolValue) {
return NO;
NSArray *cachePaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachePath = nil;
if ([cachePaths count]) {
cachePath = cachePaths[0];
}
// Can we automatically update in the background without bugging the user (e.g, with a administrator password prompt)?
// Note it's very well possible to have the bundle be writable but not be able to write into the parent directory
// And if the bundle isn't writable, but we can write into the parent directory, we will still need to authorize to replace it
NSString *bundlePath = [self bundlePath];
if (![[NSFileManager defaultManager] isWritableFileAtPath:bundlePath.stringByDeletingLastPathComponent] || ![[NSFileManager defaultManager] isWritableFileAtPath:bundlePath]) {
return NO;
if (!cachePath) {
SULog(@"Failed to find user's cache directory! Using system default");
cachePath = NSTemporaryDirectory();
}
// Just because we have writability access does not mean we can set the correct owner/group silently
// Test if we can set the owner/group on a temporarily created file
// If we can, then we can probably perform an update without authorization
// One place where this matters is if you copy and run an app from /tmp/
NSString *tempFilename = @"permission_test" ;
SUFileManager *suFileManager = [SUFileManager defaultManager];
NSURL *tempDirectoryURL = [suFileManager makeTemporaryDirectoryWithPreferredName:tempFilename appropriateForDirectoryURL:[NSURL fileURLWithPath:NSTemporaryDirectory()] error:NULL];
if (tempDirectoryURL == nil) {
// I don't imagine this ever happening but in case it does, requesting authorization may be the better option
return NO;
NSString *name = [self.bundle bundleIdentifier];
if (!name) {
name = [self name];
}
NSURL *tempFileURL = [tempDirectoryURL URLByAppendingPathComponent:tempFilename];
BOOL changeOwnerAndGroupSuccess =
[[NSData data] writeToURL:tempFileURL atomically:NO] &&
[suFileManager changeOwnerAndGroupOfItemAtRootURL:tempFileURL toMatchURL:self.bundle.bundleURL error:NULL];
[suFileManager removeItemAtURL:tempDirectoryURL error:NULL];
return changeOwnerAndGroupSuccess;
cachePath = [cachePath stringByAppendingPathComponent:name];
cachePath = [cachePath stringByAppendingPathComponent:@"Sparkle"];
return cachePath;
}
- (NSString *)installationPath
@@ -156,11 +135,11 @@
{
// Cache the application icon.
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
// 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) {
iconPath = [self.bundle pathForResource:[self.bundle objectForInfoDictionaryKey:@"CFBundleIconFile"] ofType:nil];
}
@@ -196,7 +175,7 @@
}
// More likely, we've got a reference to a Resources file by filename:
NSString *keyFilename = [self publicDSAKeyFileKey];
NSString *keyFilename = [self objectForInfoDictionaryKey:SUPublicDSAKeyFileKey];
if (!keyFilename) {
return nil;
}
@@ -208,11 +187,6 @@
return [NSString stringWithContentsOfFile:keyPath encoding:NSASCIIStringEncoding error:nil];
}
- (NSString * __nullable)publicDSAKeyFileKey
{
return [self objectForInfoDictionaryKey:SUPublicDSAKeyFileKey];
}
- (NSArray *)systemProfile
{
return [[SUSystemProfiler sharedSystemProfiler] systemProfileArrayForHost:self];
@@ -298,4 +272,31 @@
return [self objectForUserDefaultsKey:key] ? [self boolForUserDefaultsKey:key] : [self boolForInfoDictionaryKey:key];
}
+ (NSOperatingSystemVersion)operatingSystemVersion
{
#if __MAC_OS_X_VERSION_MIN_REQUIRED < 1090 // Present in 10.9 despite NS_AVAILABLE's claims
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wselector"
// Xcode 5.1.1: operatingSystemVersion is clearly declared, must warn due to a compiler bug?
if (![NSProcessInfo instancesRespondToSelector:@selector(operatingSystemVersion)])
#pragma clang diagnostic pop
{
NSOperatingSystemVersion version = { 0, 0, 0 };
NSURL *coreServices = [[NSFileManager defaultManager] URLForDirectory:NSCoreServiceDirectory inDomain:NSSystemDomainMask appropriateForURL:nil create:NO error:nil];
NSArray *components = [[NSDictionary dictionaryWithContentsOfURL:[coreServices URLByAppendingPathComponent:@"SystemVersion.plist"]][@"ProductVersion"] componentsSeparatedByString:@"."];
version.majorVersion = components.count > 0 ? [components[0] integerValue] : 0;
version.minorVersion = components.count > 1 ? [components[1] integerValue] : 0;
version.patchVersion = components.count > 2 ? [components[2] integerValue] : 0;
return version;
}
#endif
return [[NSProcessInfo processInfo] operatingSystemVersion];
}
+ (NSString *)systemVersionString
{
NSOperatingSystemVersion version = self.operatingSystemVersion;
return [NSString stringWithFormat:@"%ld.%ld.%ld", (long)version.majorVersion, (long)version.minorVersion, (long)version.patchVersion];
}
@end
+1 -1
View File
@@ -16,7 +16,7 @@
@interface SUInstaller : NSObject
+ (NSString *)installSourcePathInUpdateFolder:(NSString *)inUpdateFolder forHost:(SUHost *)host isPackage:(BOOL *)isPackagePtr isGuided:(BOOL *)isGuidedPtr;
+ (void)installFromUpdateFolder:(NSString *)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;
@end
+26 -5
View File
@@ -103,7 +103,7 @@
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 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];
} else {
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) {
[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 {
[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) {
[self mdimportInstallationPath:installationPath];
dispatch_async(dispatch_get_main_queue(), ^{
completionHandler(nil);
});
+4 -1
View File
@@ -63,7 +63,11 @@ void SULog(NSString *format, ...)
va_list ap;
va_start(ap, format);
NSString *theStr = [[NSString alloc] initWithFormat:format arguments:ap];
va_end(ap);
#ifdef DEBUG
NSLog(@"Sparkle: %@", theStr);
#endif
FILE *logfile = fopen([[SULogFilePath stringByExpandingTildeInPath] fileSystemRepresentation], "a");
if (logfile) {
@@ -72,7 +76,6 @@ void SULog(NSString *format, ...)
fwrite([theData bytes], 1, [theData length], logfile);
fclose(logfile);
}
va_end(ap);
}
Loaded 100 of 285 files, more files were not shown because too many files have changed in this diff. Show more