Compare commits

..
594 Commits
Author SHA1 Message Date
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
Michael Ehrmann 0ed83cf9f2 Fixing issue with update as non admin user where the quarantine flag did not get correctly removed from new application 2013-02-04 08:18:49 -08:00
Michael Ehrmann c37fc01bb1 Release notes referenced by URL in updates item description field can be delivered via https:// 2013-02-04 08:18:48 -08:00
Andy Matuschak 7fae28135e Merge pull request #229 from mugginsoft/master
Hush method return type warnings when importing SUUpdater.h
2013-02-04 08:13:00 -08:00
Andy Matuschak 82c722ba37 Merge pull request #240 from ryanmaxwell/master
Correct build warnings for 3 issues - detailed in each commit
2013-02-04 08:08:40 -08:00
Ryan Maxwell aba5567a15 Fix stuffing unsigned int into int variable, causing build warning 2013-01-30 11:30:58 +13:00
Ryan Maxwell d593a04dda Update Project file/Scheme to recommended Xcode settings 2013-01-12 14:45:10 +13:00
Ryan Maxwell 8fa758f8aa Fix "corrupted" turkish strings file 2013-01-12 14:42:50 +13:00
Ryan Maxwell 2a0d8afe4e update .gitignore 2012-12-08 14:28:08 +13:00
Andy Matuschak 3e3a11bd0f Merge remote-tracking branch 'blackpixel/warnings-pull-request'
Conflicts:
	th.lproj/Sparkle.strings
2012-12-06 18:47:02 -08:00
Doug Russell 41b2f054f8 Fixed warnings in xibs, switched to lldb and fixed occasional copy phase error from incorrect text encoding 2012-12-06 13:40:55 -08:00
Jonathan Mitchell 69c9c70d21 Add explicit method return types in header to supress warnings when including framework in projects with more exacting warnings such as -Wextra. 2012-11-27 10:20:02 +00:00
Andy Matuschak 243fdf8f7f Fall back on DSA-only installation checks for .pkg installations 2012-11-20 14:56:35 -08:00
Andy Matuschak 337002f421 Merge branch 'CodeSigning' 2012-11-19 17:37:53 -08:00
Andy Matuschak a7ba6a7421 Merge pull request #210 from kainjow/master
Disable row selection in system profile table
2012-11-15 23:06:33 -08:00
Andy Matuschak 7b3928db9b Fixes #222: Long version ids (12 digits based on reverse date) cause update to work no longer 2012-11-15 22:49:55 -08:00
Andy Matuschak b86770c39f Fixed unit tests for 10.8 2012-11-15 22:49:43 -08:00
Andy Matuschak f6622104bf Fixes #221: char *oldDestinationString 2012-11-15 22:40:39 -08:00
Andy Matuschak 860739fce2 Merge remote-tracking branch 'ryanmaxwell/master' 2012-11-15 22:28:47 -08:00
Andy Matuschak 38eb63a7a2 Updates to Turkish localization courtesy Emir Sarı 2012-11-13 09:22:51 -08:00
Ryan Maxwell f7daf04204 Update remaining english straight single ' quotes to curly ’ quotes 2012-11-10 20:10:46 +13:00
Ryan Maxwell 2350c59cc8 Update strings files to standardize ellipsis character (…) instead of three dots (…)
Also change don't to curly quote don’t in dialog.
2012-11-10 19:46:44 +13:00
Andy Matuschak 16cdd6bf64 Adding Arabic localization, courtesy Muhammad Azmi Al-Hashemi 2012-09-12 22:56:07 -07:00
Kevin Wojniak e657bcf03a Disable row selection in the system profile table by implementing the table delegate and turning off "Avoid Empty Selection", "Preserve Selection" and "Select Inserted Objects" on the array controller in the nib. 2012-09-05 10:16:33 -07:00
Andy Matuschak d138f64bd6 Fixes #198: Problem with 10.5
Implicitly linking the Obj-C runtime with the 10.7 SDK is causing us to
inadvertently reference libblocks symbols, which don't exist prior to
10.6.
2012-08-16 20:03:45 -07:00
Andy Matuschak 3c37f775fb Merge branch 'master' into CodeSigning 2012-08-15 18:14:37 -07:00
Andy Matuschak 7a283bfaeb Fixes #133: Sparkle deleting/replacing the wrong executable when it unpacks
-[SUHost installationPath] can return different values before and after
the installation is performed, because it may attempt to normalize the
installation path--but only if the normalized version of the path isn't
already present. Which it would be after the installation had completed.

Now we only compute the installation path once for the whole installation
process.
2012-08-15 18:01:35 -07: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
Andy Matuschak c1510a5bea Adding Thai localizations to the project. 2012-07-26 19:00:21 -07:00
Chotiwat Chawannakul 7a20432b1b Add Thai localization 2012-07-27 00:25:35 +07:00
Andy Matuschak 3d8be2d2da Fixed potential crasher in code signing in the case that the host application is not code signed. 2012-07-24 09:13:47 -07:00
Andy Matuschak a59e8ff958 Added kSecCSCheckAllArchitectures to the flags for code signing validation so that inactive architecture binaries are checked as well in the update. 2012-07-24 09:08:42 -07:00
Andy Matuschak 26077f47af Update to the Brazilian Portuguese localization from Victor Figueriedo 2012-07-23 17:03:59 -07:00
Andy Matuschak 118f3c5141 Merge pull request #183 from sinbad/fix-10.6-arg-list-too-long
Use NSFileManager interface for DMG unarchive only for 10.7+.
2012-07-05 18:27:47 -07:00
Andy Matuschak 22b65a3095 Making sure to initialize all Security types 2012-07-05 18:13:28 -07:00
Andy Matuschak 05c51a1c05 Merge branch 'EncryptedDiskImages' 2012-07-05 18:09:42 -07:00
Andy Matuschak 21f95465da Fixes #48: Adopt standard code signing in favor of DSA signing
Thanks to Mattt Thompson (@mattt) for tag-team-ing this with me.

With this change, if your app deploys only to 10.6+, then you can
dispense altogether with the DSA signatures on future updates to your
application: just make sure the "to" version satisfies the "from"
version's Apple code signing requirements. Most of you are probably
already doing that, and if you're not, you should be anyway.

Specifically, Sparkle validates the designated requirement of the "from"
version against the "to" version. By default, as of this writing, that
means that the bundle identifiers must be the same, and that the leaf
certificate of the signature is the same. So if you keep code signing
your app with the same cert, Sparkle will Just Work without any
additional DSA signature nonsense for you to deal with.

Traditional Sparkle DSA signatures will still be honored.

This support has only been extended to updates to the main app bundle.
If you're updating some other bundle, you will have to use DSA signatures
to secure your updates in the future.

***IMPORTANT: previously, Sparkle considered an update "safe" if both the
appcast and update were distributed over https. That is nowhere near as
strong a verification measure as code signing or the old-school DSA
signatures, so with this change, support for unsigned, https-distributed
updates has been removed. If you're targeting 10.6+, start code-signing
your apps if you haven't already, and everything will be fine. If you're
targeting earlier OS Xs, you'll need to start adding DSA signatures to
your appcasts. When you link this changed version of Sparkle into your
app, it will warn you on launch if you are not code signed and do not
have a DSA public key specified in your Info.plist.
2012-07-05 10:04:17 -07:00
Andy Matuschak ab74bdca79 Removed Japanese localization of password prompt from the Xcode project 2012-07-03 18:52:08 -07:00
Andy Matuschak 69d471aefb Allow the user to try reentering his password if authentication fails. 2012-07-03 18:51:21 -07:00
Andy Matuschak d620dc0b52 Removing Japanese localization of the password prompt, since I changed the design 2012-07-03 18:43:22 -07:00
Andy Matuschak d3f975816e Delegated password prompting to the update driver.
The SUDiskImageUnarchiver shouldn't know about UI, and besides,
it's important that update drivers which should not display UI (like
the automatically-installing and probing drivers) should not display
password prompts.
2012-07-03 18:37:50 -07:00
Steve Streeting 91ac9178f1 Use NSFileManager interface for DMG unarchive only for 10.7+. On 10.6, [NSFileManager copyItemAtPath:toPath:error:] can fail with "Argument list too long" if the app bundle contains too many files.
The switch to NSFileManager was only required for 10.7 anyway, 10.6 always worked fine.
2012-06-28 13:28:30 +01:00
Andy Matuschak ae52d2743e Removed changes to the project.pbxproj that were unrelated to the password prompt 2012-06-26 18:45:41 -07:00
Andy Matuschak a4082a0e54 Redesigned password prompt UI 2012-06-26 18:44:55 -07:00
Andy Matuschak 9c8e825289 Removed methods from SUPasswordPrompt.h that didn't need to be exposed there 2012-06-26 18:43:52 -07:00
Stefan Hoffmann 9662452c09 Fixes #44: maximumSystemVersion key 2012-05-28 23:02:14 +02:00
Rudy Richter 0a3051349a remove the ASW tags since we're submitting this as a pull request to andy 2012-05-23 17:11:31 -04:00
Andy Matuschak 1c258cb690 Updating Danish localization courtesy Daniel Østergaard Nielsen 2012-05-23 09:47:43 -07:00
Rudy Richter 4ba453f337 support for encrypted disk images 2012-05-22 10:59:20 -04:00
Andy Matuschak 6960045e2b Fixes #175: Bug: update alert text collides with automatic download checkbox 2012-05-09 09:19:20 -07:00
Andy Matuschak 803925f2cf Fixes #174: Bug: sparkle:shortVersionString ignored for non-enclosure items 2012-05-09 08:49:55 -07:00
Andy Matuschak 97c71ef700 Fixes #170: An environment variable set by Sparkle 2012-05-07 19:39:31 -07:00
Andy Matuschak 6b7752792d Fixing some new Clang warnings from Xcode 4.4 2012-04-28 20:38:18 -07:00
Andy Matuschak b7dc2438a7 Fixes #169: Security Issue in Parsing XML using NSXMLDocument
External entities are no longer parsed in appcasts: pre-10.7, we use the
"tidy" option for XML document parsing, which happens to behave this way,
and in 10.7+ we use a new explicit option for this behavior.
2012-04-28 20:32:35 -07: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
Andy Matuschak 9aa3015929 Merge pull request #159 from ivira/master
Ukrainian localization
2012-03-01 18:41:46 -08:00
Vera Tkachenko 09f0c43e7c Minor fix of Ukrainian localization 2012-03-01 01:02:21 +02:00
Vera Tkachenko a570191859 Minor improvements of Russian localization: proofing and truncated button labels. 2012-02-29 23:50:21 +02:00
Vera Tkachenko d7dea30de6 Added Ukrainian localization 2012-02-29 23:07:04 +02:00
Andy Matuschak 8a25500eca Merge pull request #23 from tzikis/master
Greek Translation
2012-02-29 09:42:23 -08:00
Andy Matuschak 4d00e8c569 Fixes #157: Delayed relaunch not working 2012-02-24 08:55:22 -08:00
Andy Matuschak 02088e0da6 Merge pull request #156 from christianz/master
Corrected some minor spelling errors in the Norwegian Sparkle.strings
2012-02-22 08:22:55 -08:00
Christian Zachariasen f341d0c3a9 Corrected minor spelling errors 2012-02-22 12:35:42 +01:00
Andy Matuschak e27828d248 Merge pull request #144 from mattstevens/custom-defaults-domain
Support a custom user defaults domain
2012-02-14 09:52:34 -08:00
Andy Matuschak 44cf0d0e51 Merge pull request #145 from mattstevens/install-on-quit-cleanup
Clean up after install on quit updates
2012-02-14 09:48:12 -08:00
Matt Stevens 6be55685c8 Clean up after install on quit updates 2012-02-12 20:02:46 -07:00
Matt Stevens 29b7321094 Support a custom user defaults domain
This is useful for situations like a background app that updates a
parent preference pane but wants to maintain defaults in the background
app's domain.
2012-02-11 15:31:12 -07:00
Andy Matuschak 449b00ed3e Merge pull request #139 from mattstevens/pathToRelaunch
Host bundle is changed by pathToRelaunchForUpdater:
2012-02-08 22:37:19 -08:00
Andy Matuschak 4c2573702e Merge pull request #142 from mzch/master
Improved Japanese translations (fixes #141)
2012-02-08 22:14:25 -08:00
Koichi MATSUMOTO 88d4b348d9 Improved Japanese translations
Improved some strange translations in Japanese
2012-02-08 15:37:30 +09:00
Matt Stevens bf07a9435b Pass both host and executable paths to finish_installation
This fixes pathToRelaunchForUpdater by supporting an executable path
other than the host bundle path.
2012-02-06 22:16:25 -07:00
Andy Matuschak 799b2a381f Merge pull request #136 from ksuther/master
Xcode warning cleanup
2012-02-01 11:02:56 -08:00
Kent Sutherland 8b4cf14e53 Explicitly set the file encoding of Romanian Sparkle.strings to stop Xcode warning. 2012-02-01 13:29:25 -05:00
Kent Sutherland 515511d5e9 Adjusted initial window position of SUUpdateAlert for Romanian/Slovenian so Xcode doesn't show warnings. 2012-02-01 13:27:46 -05:00
Andy Matuschak aca8cc6fbf Renamed GC build configuration for clarity per #135 2012-01-27 08:46:46 -08:00
Andy Matuschak 1bc3834345 Fixing feature that normalizes installed app names and disabling it by default. Fixes #133. 2012-01-17 22:39:49 -08:00
Andy Matuschak 73e96cdcab Updating project for 4.2.1; changing SDK to 10.7 2012-01-17 21:51:43 -08:00
Andy Matuschak 760e32c5bd Added Slovenian localization courtesy Mojca Miklavec 2012-01-11 09:21:24 -08:00
Andy Matuschak cf1b167954 Merge branch 'master' of github.com:andymatuschak/Sparkle 2012-01-05 18:44:48 -08:00
Andy Matuschak 5ef6c64568 Fixes #129: Still need the OpenSSL license? 2012-01-05 18:44:26 -08:00
Andy Matuschak 7e05e97c95 Merge pull request #126 from dmdeller/patch-1
OpenSSL path should be globally replaced, right?
2011-12-19 11:41:27 -08:00
David Deller 5cd98c5508 OpenSSL path should be globally replaced, right?
With MacPorts OpenSSL installed, this version produces different results, which makes me nervous.
2011-12-18 11:40:58 -05:00
Andy Matuschak 290f64f552 Fixes #121: finish_installation deployment target is 10.6, not 10.5 2011-11-18 19:17:11 -08:00
Andy Matuschak 59caa1f300 Re-added Romanian resources with relative paths to the project. 2011-11-18 19:14:24 -08:00
Andy Matuschak 882b5c9b8a Minor layout adjustments to the Romanian localization 2011-11-18 19:11:49 -08:00
Gabriel Ulici 7ba0c583af Translated the string and xib files 2011-11-18 13:31:36 +01:00
Gabriel Ulici b275cab13f Added Romanian Localization 2011-11-18 13:30:08 +01:00
Andy Matuschak f20c121745 No longer linking to libcrypto 2011-11-11 17:59:39 -08:00
Andy Matuschak 25040affc2 Fixes #111: Sparkle won't build due to -Werror with -Wformat=2 and missing newlines 2011-11-11 17:57:40 -08:00
Andy Matuschak 82e6250250 Merge pull request #118 from smiranda/master
Improvements to the European Portuguese localization (pt_PT)
2011-11-10 09:13:52 -08:00
Sérgio Miranda 9f2d53a3a2 Improvements to the European Portuguese localization (pt_PT) 2011-11-10 14:24:35 +00:00
Andy Matuschak ec4ebbdcfb Merging darkshadow2's changes for libcrypto -> CDSA 2011-11-09 21:34:27 -08:00
Andy Matuschak aeeae26d1c Critical security patch--re-enabling signature and downgrade checking.
When merging Uli Kusterer's branch, we left enabled a preprocessor flag that would disable DSA checking and downgrade prevention. That should not have been merged into master. My apologies to the community for not noticing this sooner.
2011-11-09 21:22:38 -08:00
Andy Matuschak 095d223e70 Fixes #116: Update error: Can't make a temporary directory 2011-11-09 20:53:18 -08:00
Andy Matuschak 55eed9efd8 Fixes #113: Need to check isReadableFileAtPath: when copying out DMG contents 2011-11-02 10:27:32 -07:00
Andy Matuschak d092ae9295 Resolved merge 2011-10-27 22:04:01 -07:00
Andy Matuschak 5457476e4a Fixes #109: Error extracting dmg archives 2011-10-27 21:59:45 -07:00
Andy Matuschak 5dce90eafa Merge pull request #28 from wildchocolate/master
Fixed leaks with NSFileManager
2011-10-20 08:05:26 -07:00
Brittany Tarvin 268ea201da Fixed leaks with NSFileManager 2011-10-20 09:52:02 -05:00
Brittany Tarvin 613b759077 Fixed issues that led to crashes on Mac OS X 10.7 Lion.
These fixes remove the use of the File Manager API that was causing crashes on Lion. This should resolve issue #827357. We are now using NSFileManager instead of the older File Manager API, but only on 10.6 and later. These changes should work for those targeting 10.4, but will allow users running 10.7 to still update without crashing.
2011-10-17 14:30:00 -05:00
Andy Matuschak fc725cce01 Background updates would never get scheduled when the net's down. 2011-10-10 10:29:52 -07:00
Andy Matuschak 95398cd26f Fixed a no-autorelease-pool leak. 2011-10-10 09:28:56 -07:00
Andy Matuschak 01e8cf90c6 finish_installation doesn't show any UI if it's not relaunching, since those installations were not kicked off by user action. 2011-10-04 20:48:09 -07:00
Andy Matuschak 7152bd0ffa Merge branch 'master' of github.com:andymatuschak/Sparkle 2011-10-03 22:55:57 -07:00
Andy Matuschak 05861e5340 Merging "ulimerge," which contains a great number of changes and contributions from Uli Kusterer, Elgato, and other contributors.
Highlights:
- appcast entries with a "new version" but without a download (paid updates, update notification for users of dropped HW)
- installation now happens in a tool, rather than in the app being replaced
- Sparkle-related logs now separated into a separate file ~/Library/Logs/SparkleUpdateLog.log for easier QA/triage
- tons of small bug fixes
- more details at https://github.com/andymatuschak/Sparkle/pull/18
2011-10-03 22:45:50 -07:00
Andy Matuschak aa853a0f0f Increased the time required before finish_installation shows a dock icon from 1.2 seconds to 5 seconds 2011-09-30 09:52:32 -07:00
Andy Matuschak a47151c638 Moved the finish_installation plist into its Xcode group 2011-09-30 09:52:32 -07:00
Andy Matuschak 06642bba20 Fix to reachability patch in 9cc1905f87 for file:// URLs, which were crashing 2011-09-30 09:42:30 -07:00
Andy Matuschak f04a460d63 Removing the SDKROOT from ConfigBinaryDelta.xcconfig so it'll use ConfigCommon's (10.6) 2011-09-30 09:29:06 -07:00
Andy Matuschak 7d4ce0daeb Actually put the archs back; that didn't get caught in the last commit. 2011-09-29 18:32:56 -07:00
Andy Matuschak a2bcd53eaa Put the deployment targets and architectures back from 950e3894b35dd8bcfc1d4d692ebc0aafdeda8e44; kept the SDK root. 2011-09-29 18:29:19 -07:00
Andy Matuschak 5a47fb64c3 Merge remote branch 'ksuther/ulimerge' into ulimerge 2011-09-29 10:29:15 -07:00
Andy Matuschak c96aa2eda8 The finish_installation tool will not relaunch the host app if it's using the "Install on Quit" functionality. 2011-09-28 18:11:43 -07:00
Vasileios Georgitzikis e30a342813 Updated Greek translation 2011-08-28 14:59:05 +03:00
Kent Sutherland 320672c1f9 Disabled skip install on finish_installation so it isn't archived by Xcode 4. 2011-08-15 12:47:27 -04:00
Kent Sutherland 436107f20e Fixed preprocessor error if DEBUG isn't defined. 2011-08-01 13:14:02 -04:00
Kent Sutherland 950e3894b3 Compile for i386/x86_64 on 10.6 only. 2011-07-25 16:44:32 -04:00
Kent Sutherland 2300f2bcb0 Set the level of the update check status window to NSFloatingWindowLevel if the host application is background-only. 2011-07-25 16:44:32 -04:00
Kent Sutherland a6d776ca04 Add SUVersionDisplayProtocol to public headers of framework. 2011-07-25 16:44:32 -04:00
Kent Sutherland 76e79d6f92 Set the base configuration of finish_install to the old relaunch configuration. 2011-07-25 16:44:32 -04:00
Kent Sutherland 9cc1905f87 Use SCNetworkReachabilityCreateWithName rather than SCNetworkCheckReachabilityByName, which is deprecated. 2011-07-25 16:44:31 -04:00
Michael Nickerson 78e24a6fe6 Changed from using OpenSSL to Apple's CDSA to verify DSA signatures. 2011-07-05 20:31:36 -04:00
Andy Matuschak f1a353840a Merge pull request #19 from dmgctrl/pr_gitignore
Added gitignore to strip out Xcode cruft.
2011-06-30 19:10:29 -07:00
Jason Allum 0f34252f4a Added gitignore to strip out Xcode cruft. 2011-06-30 09:17:01 -04:00
Andy Matuschak 000a24c63b Using /usr/bin/openssl in the signing scripts instead of /usr/bin/env openssl.
Fixes bug 793221.
2011-06-13 18:47:17 -07:00
Andy Matuschak 32d4f249d4 Added a new Info.plist key: SUPromptUserOnFirstLaunch. Set this to YES to disable Sparkle's usual behavior of waiting 'till the second launch of an app to prompt for update permission.
This is useful for apps which don't, under normal operations, get quit. Like a menu extra.
2011-05-26 18:52:24 -07:00
Andy Matuschak e71915b4fb Revert "Removing dead -[SUUpdateAlert showsReleaseNotesText] method"
It wasn't so dead after all. Curse you, bindings!
2011-05-10 08:02:33 -07:00
Andy Matuschak 31b9ba8dde Fixed localization warnings. 2011-05-09 22:57:50 -07:00
Andy Matuschak 83708695af Added a canonical scheme and got the unit tests going again. 2011-05-09 22:56:09 -07:00
Andy Matuschak bb363db7f8 Fixed some project warnings. 2011-05-09 22:40:38 -07:00
Andy Matuschak ba6c3b6854 Cleaned up SUUpdater.h 2011-05-09 22:32:45 -07:00
Andy Matuschak 200da2b1be Removing BuildSparkleFinishInstallTool.command -- I don't think it belongs in master. 2011-05-09 22:25:19 -07:00
Andy Matuschak db652744ef Removing dead -[SUUpdateAlert showsReleaseNotesText] method 2011-05-09 22:22:58 -07:00
Andy Matuschak 9f3d4fb524 Nuking ThreadSafePreferences 2011-05-09 22:22:12 -07:00
Andy Matuschak 86b6502342 Fixing a merge error which put finish_installation in /tmp rather than in ~/Library/App Support 2011-05-09 22:18:17 -07:00
Andy Matuschak fa671073fa Changing download destination from ~/Desktop to ~/Library/App Support/HOST_NAME 2011-05-09 22:08:09 -07:00
Andy Matuschak 4f1e5a72a0 Added back master's Turkish localization 2011-05-09 21:39:28 -07:00
Andy Matuschak bca574119b Removed the pt_PT localization from Uli's branch, since it was largely untranslated, and used the one from master instead. 2011-05-09 21:36:46 -07:00
Andy Matuschak acb8f5f076 Fixed layout of localization XIBs 2011-05-09 21:07:51 -07:00
Uli Kusterer 16ff5c6683 Added Sparkle icon to finish_installation application. 2011-05-03 11:30:10 +02:00
Uli Kusterer 67d53c04b7 Get rid of deprecation warnings on 10.6/Xcode 4 while still allowing to build for 10.4 compatibility (I hear Patrick needs that). 2011-05-03 11:05:37 +02:00
Uli Kusterer 910f78b569 Add strings file to the finish_installation tool. Apparently also remove a leftover NIB, though I don't remember actually doing that. 2011-05-02 17:40:52 +02:00
Uli Kusterer fdaf26e95d Added two new Mac Pro models. 2011-05-02 17:30:07 +02:00
Uli Kusterer a8854375f5 Manually merge project file (recreating the finish_installation application target) and make things build and run again. 2011-05-02 17:29:53 +02:00
Uli Kusterer 9937e5a17b Merge andymatuschak/Sparkle. 2011-05-02 15:52:15 +02:00
Uli Kusterer 67b0860a9f Add a dummy line to make sure that the binary is linked against WebKit when Sparkle is used. The SUUpdateAlert.xib file contains a WebView and if we don't link against WebKit, we will get a runtime crash when decoding the NIB. It is better to get a link error. 2011-05-02 12:48:43 +02:00
Uli Kusterer 5b90432f7e Make sure the update alert is *really* not resizable. 2011-05-02 12:46:52 +02:00
Uli Kusterer 7cd8974b7e Make Sparkle more robust when the permissions of ~/Library/Application Support/EyeTV are screwed up. We now authenticate if needed, when we copy the finish_installation tool. 2011-05-02 12:46:37 +02:00
Uli Kusterer 9c042a5767 The buttons in the update alert now auto-resize. Since we change the button width when we show "Learn More..." for no-download updates (e.g. paid updates or updates that may no longer run on the user's Mac), this simplifies localization a lot.
The requisite NIB changes have been checked in previously with the newest localizations.
2011-05-02 12:42:13 +02:00
Uli Kusterer 3db00fa137 All XIBs, all the time. 2011-05-02 12:31:21 +02:00
Uli Kusterer f6710e2379 Sparkle now warns the delegate before and after it brings up a modal panel. One can e.g. use this to unfloat floating windows that would otherwise cover the alerts. 2011-05-02 12:29:30 +02:00
Uli Kusterer 990dee6a8d Newest Elgato localizations. 2011-05-02 12:25:37 +02:00
Uli Kusterer 7bfec0f3c0 Added two MacBook Air models. 2011-05-02 09:50:05 +02:00
Andy Matuschak 3ea1a9eee4 Merge branch 'master' of https://github.com/lapcat/Sparkle into lapcat-master 2011-04-07 17:37:12 -07:00
Andy Matuschak f6e292fad3 Added Turkish localization courtesy Tasin Is. 2011-04-07 17:09:37 -07:00
Jeff Johnson 1cce7890d8 Delete stray LIBRARY_SEARCH_PATHS build setting. 2011-03-25 21:26:19 -05:00
Jeff Johnson 61340cab17 Delete redundant Sparkle in test app linked libraries. For some strange reason, there were two. 2011-03-25 21:08:07 -05:00
Jeff Johnson 4a95dbeddc Link against Cocoa rather than AppKit and Foundation. 2011-03-25 21:08:07 -05:00
Jeff Johnson 45178111b3 Don't include SUStandardVersionComparator.m in test app or unit test targets, because it's already in the framework target. 2011-03-25 21:08:07 -05:00
Jeff Johnson eef0f5f0dc Delete reudundant GCC_DEBUGGING_SYMBOLS build setting, because it's already specified in the xcconfig. 2011-03-25 21:08:07 -05:00
Jeff Johnson 1e1025f17d Delete redundant -Wundeclared-selector, because it is already specified in the xcconfig. 2011-03-25 19:01:20 -05:00
Jeff Johnson 69407123ba Let Xcode add developmentRegion to the project. 2011-03-25 18:58:11 -05:00
Andy Matuschak 096d43a7a6 Updated Slovak localization; thanks to Rudolf Gavlas 2011-03-01 18:55:58 -08:00
Andy Matuschak 00b67269d6 Bug #681912: Sparkle naively double-escapes enclosure URLs 2010-11-26 12:07:32 -08:00
Adam Wróbel 7baf50506b Call EVP_MD_CTX_init and EVP_MD_CTX_cleanup.
According to openssl documentation EVP_Verify should be accompanied by
calls to EVP_MD_CTX_init and _cleanup to avoid memory leaks. Not sure, but
adding for conformity's sake.
2010-10-15 01:27:14 +08:00
Adam Wróbel 40616b864a Generate keys that actually work with openssl.
According to FIPS 186-2 standard DSA keys should be >= 512 and <= 1024 bits.
Using a 2048 bit key on my system yields an openssl error in Sparkle's
SUDSAVerifier and causes the update to be rejected.

The error says (can be read only after hacking on Sparkle's code):
error:0A071066:dsa routines:DSA_do_verify:bad q value
2010-10-15 01:27:12 +08:00
Andy Matuschak 561bbbe294 Because of the way Sparkle forces SUUpdaters to be per-bundle singletons, it was possible for an SUUpdater to be dealloced before registerAsObserver was called, which in turn made an exception get thrown on unregisterAsObserver. 2010-09-13 10:28:18 -07:00
Andy Matuschak fba7231261 We used to not register SUUpdater as an observer of the shared user defaults controller if we were running as a bundle. The performance win is minimal, and if I stop doing that, we won't accidentally try to unregister as an observer and bother developers who break on [NSException raise]. 2010-09-10 17:16:31 -07:00
aidansteele b3ac18f173 Forgot to close dangling file descriptor in previous commit. 2010-08-24 22:58:56 +08:00
aidansteele e2a59fccb2 Fixed delta updates bug wherein updates fail on empty file.
mmap()ing empty files caused EINVAL to be returned and _hashOfFile
would return an incorrect result. This has been rectified.
2010-08-24 22:58:55 +08:00
Andy Matuschak a8f26b16c2 Merge branch 'master' of git@github.com:andymatuschak/Sparkle 2010-07-30 21:08:56 -07:00
Andy Matuschak b7a3999da8 [Bug 611564] [NEW] sparkle fails to build with clang due to -Werror.\n\nAlso, switching to Clang because hoorah. 2010-07-30 21:08:11 -07:00
Andy Matuschak a5c8e0b1e2 No longer hardcoding the Installer tool's relative executable path for Tiger. 2010-07-27 18:35:04 -07:00
Lukhnos D. Liu 2768e60ce1 Properly escapes the GET parameters in the appcast string with profile. 2010-07-23 13:08:39 +08:00
Andy Matuschak 9075d4a037 Fixing 603197: Package Installs Crash on 10.4 2010-07-08 22:37:28 -07:00
Andy Matuschak da35ef695b Fixing #601842: Chromium crashes when 'Install and Relaunch' is clicked 2010-07-05 12:18:22 -07:00
Andy Matuschak 394319e1fc Merge branch 'master' of git@github.com:andymatuschak/Sparkle 2010-06-20 17:20:29 -07:00
Daniel Jalkut 0c6e6fdd84 Plug leak in SUAppcastItem caused by neglecting to release minimumSystemVersion. 2010-06-20 17:20:04 -07:00
Vaclav Slavik 39bb82bd9a Don't compress in bsdiff.
bsdiff-produced patch is included in xar archive, where it's compressed
with bzip2 a second time. Leaving the bsdiff output uncompressed makes
it possible to compress it better in xar (e.g. using LZMA2 or gzip,
either of which performs better on some files).

Changes header signature of bsdiff patch file to BSDIFN40 to clearly
mark the format as different.

Backward compatibility is preserved, bspatch can read both BSDIFF40 and
BSDIFN40 formats.
2010-06-21 01:43:46 +08:00
Andy Matuschak 25d7faea7b Updates to the Czech localization. 2010-06-09 13:16:39 -07:00
Andy Matuschak a0c2de60d3 Merge branch 'master' of git@github.com:andymatuschak/Sparkle 2010-06-08 20:48:52 -07:00
Andy Matuschak e8299fd116 Fixing 578060: minor Spanish localization fix 2010-06-08 20:47:20 -07:00
Vaclav Slavik 4548228238 Fix 10.4 compatiblity broken by delta updates.
Delta updates code uses libxar, which is only available in 10.5+, and
Sparkle framework fails to load on 10.4 because of it. Instead of having
hard dependency on libxar, Sparkle now links with it weakly and checks
for its availability at runtime.  This required bumping Xcode project
compatibility to 3.2 to get weak linking support.

With this change, delta updates are still not supported on 10.4, but
Sparkle runs there again and just ignores the deltas. This should be
good enough given 10.4's age and shrinking user base.
2010-06-07 02:19:51 +08:00
Andy Matuschak fe1372c962 Fixing 572066: some fixes to the Japanese localization. 2010-05-04 13:42:27 -07:00
Andy Matuschak a6fcfa61b5 Fixing ridiculous error in the last commit caused by non-initialization of a variable. See bug #571486. Sorry about that, all. 2010-04-28 16:37:04 -07:00
Andy Matuschak c34e9b3c34 Added an extra null check to SUAppcast downloadDidFinish because NSXMLDocument and NSFileManager throw exceptions on nil arguments. See bug 456514. 2010-04-28 00:45:45 -07:00
Andy Matuschak ea81eeec57 Fixing bug 570023; two minor localization changes. 2010-04-26 01:14:47 -07:00
Andy Matuschak 19ae8506ab Removing extraneous -L and -F flags that were causing warnings. 2010-04-09 13:28:00 -07:00
Andy Matuschak 803676d56a Landing delta-updates. 2010-03-27 17:06:51 -07:00
Andy Matuschak 5975703b13 Fixed some silly compiler warnings. 2010-03-27 17:03:07 -07:00
Andy Matuschak ecd2ce227b Fixing 527923: a minor Spanish localization layout bug. 2010-02-27 16:39:17 -08:00
Andy Matuschak 3f502b6151 Fixing bug #527318, some minor Spanish layout issues. 2010-02-25 00:47:39 -08:00
Andy Matuschak fb43787317 Fixing bug #527318, some minor Spanish layout issues. 2010-02-25 00:46:57 -08:00
Uli Kusterer f81bfd9f1c Move ThreadSafePreferences.h dummy compatibility header to a different spot in Groups & Files. 2010-02-21 18:29:56 +01:00
Uli Kusterer 24ebb7b379 SUUpdateAlert.xib: Shut up warnings about offscreen windows and clipped content. 2010-02-21 18:29:23 +01:00
Uli Kusterer 2460f2fcf7 SUUpdateAlert.nib: Made sure all installButton outlets are hooked up. Converted from NIB to XIB. 2010-02-21 18:25:01 +01:00
Uli Kusterer 401e696590 Restore support for enclosure-less appcast items. If they have a sparke:version tag at the same level as the enclosure would be (as opposed to as an attribute on the enclosure), and no enclosure, but a "link" tag, the link tag's contents will be used as the URL for a "More Info" button to replace the "install" button.
Use this for paid updates, where you want to redirect users to your store page instead of installing an update they don't have a license key for.
2010-02-21 18:09:39 +01:00
Uli Kusterer 29035199f3 That checkbox was way too narrow. 2010-02-21 15:12:29 +01:00
Uli Kusterer b4210d8f61 Use symbolic constants, that's what they're for ;-) 2010-02-21 14:06:49 +01:00
Andy Matuschak c120af6b1f Fixed the "You're up-to-date!" string in the German localization to use hyphens. 2010-02-10 12:46:05 -08:00
max 96ea09e44f Fixed a crash causes by a additional autorelease. 2010-01-27 18:43:11 +01:00
Andy Matuschak f5a1b1c27d Fixing #511784: Subclass of SUBasicUpdateDriver can't find relauncher 2010-01-24 11:00:35 -08:00
Andy Matuschak 5cdfffa521 Fixing #511784: Subclass of SUBasicUpdateDriver can't find relauncher 2010-01-24 10:58:43 -08:00
Andy Matuschak a5245accf4 Fixed a few local-vs-ivar variable ambiguities. 2010-01-11 10:19:12 -08:00
Andy Matuschak 9bc63ccf7e Merge commit 'bdash/delta-updates'
This is a big one, guys. Haven't tested the new features in the merged branch yet.
2010-01-11 00:49:28 -08:00
Andy Matuschak 2e3ed79753 Fixing #502212: clang static analyzer identifies 2 leaks in Sparkle code 2010-01-11 00:28:49 -08:00
Andy Matuschak da3b5c2570 Updated Russian localization courtesy Alexandr. 2010-01-06 17:45:06 -08:00
Sean McBride 756b37d4a5 code review of CFRelease usage, minor changes 2010-01-04 20:47:55 -05:00
Sean McBride 36b7d434ad fixed extra ref count, half of bug #502212 2010-01-04 20:09:42 -05:00
Sean McBride b21b308203 all but a few places use the typical [[[foo alloc] init] autorelease] pattern, removed 3 explicit releases and use autorelease instead. There are now only 2 exceptions to this pattern left. One is probably justified, the other looks like a leak. 2010-01-01 00:53:30 -05:00
Sean McBride dab8a36a13 renamed all methods that start with underscore, since that's reserved by Apple. Similiar for global variable that started with double underscore 2009-12-31 23:38:25 -05:00
Sean McBride 152e6f9572 SUHost's technique for getting a generic bundle icon did not work, fixed 2009-12-30 00:34:19 -05:00
Sean McBride f8fbf370bc enabled GCC_WARN_UNDECLARED_SELECTOR warning now that all such warnings are fixed 2009-12-30 00:06:27 -05:00
Sean McBride 61291c77d7 Merge branch 'master' of git://github.com/andymatuschak/Sparkle 2009-12-30 00:00:20 -05:00
Sean McBride b90df8b254 fixed warning by moving private methods higher in the source file 2009-12-29 23:58:27 -05:00
Sean McBride 4dbc0dd47f removed define that was moved to pch 2009-12-29 23:56:28 -05:00
Sean McBride 9d3db1b103 fixed warning 2009-12-29 23:56:08 -05:00
Sean McBride b8c8b9e605 conditionally define NSAppKitVersionNumber constants in pch, properly conditionalise Obj-C code 2009-12-29 23:55:31 -05:00
Sean McBride d7260665d6 fixed warning by moving private methods higher in the source file 2009-12-29 23:50:31 -05:00
Andy Matuschak b96c95066c Update driver now correctly marks itself as "finished" before terminating.
This is important for apps which checked this value during an app delegate's applicationShouldTerminate:.

Thanks to Nick Zitzmann for the patch.
2009-12-27 22:49:04 -06:00
Uli Kusterer 3d352c6fcd Merge branch 'master' of github.com:uliwitness/Sparkle 2009-12-23 11:50:05 +01:00
Uli Kusterer 874572f7bb More strings changes from Elgato. 2009-12-23 11:47:24 +01:00
Uli Kusterer 8f0d7d0805 Strings changes from Elgato. 2009-12-23 11:47:07 +01:00
Uli Kusterer 65f8d2629a Actually use the build configurations. 2009-12-23 11:44:51 +01:00
Uli Kusterer c0ca2249a5 Revert Patrick's version number change.
- It made bracketed build numbers look like components of the version, which gave wrong results
- Added a test for one such broken build-numbered version number

TODO: Tests currently fail for Patrick's version numbers. Will have to write a smarter parser, or split this into two version comparator classes.
2009-12-23 11:43:58 +01:00
Uli Kusterer efe903bc73 More detailed error handling and logging.
- Take failure of stat into account
- Use correct format for printing uids
- SULog actual failure points.
- Cope with nonexistent destinations
2009-12-23 11:41:31 +01:00
Andy Matuschak fd20e0725b Added two stupid spaces. 2009-12-21 15:02:36 -06:00
Andy Matuschak 6c8f094bbe Merge commit 'seanm/master' 2009-12-20 18:20:37 -06:00
Uli Kusterer 50b76d59f7 Add missing include. 2009-12-15 16:51:01 +01:00
Uli Kusterer 4f76b42bb5 If we install under a normalized name, make sure we take owner/group from the target directory, not from a nonexistent destination application we haven't installed yet. 2009-12-15 16:50:43 +01:00
Uli Kusterer d593ab38ad Fix configuration for finish_installation.app target:
Otherwise it won't build correctly on 10.4 and gives us "unsupported required load command" errors instead of starting up.
2009-12-15 16:49:35 +01:00
Uli Kusterer a17f974357 Merge branch 'master' of github.com:uliwitness/Sparkle 2009-12-15 16:31:19 +01:00
Andy Matuschak 40dee9958b Added Portuguese translation courtesy Sérgio Miranda. Thanks! 2009-12-14 22:35:56 -06:00
Uli Kusterer 575bdda768 Make sure that, even on 10.4, we delete our temp folder. Also, we no longer use the stop-gap measure of trashing the temp folder, we really delete it after successful installation. 2009-12-14 22:36:34 +01:00
Uli Kusterer 9b116929ad Slightly more user-suitable error message. 2009-12-14 22:34:49 +01:00
Uli Kusterer 2e8fa61a5a More more correct way of creating an NSString from a C-string path. 2009-12-14 22:34:25 +01:00
Uli Kusterer cd93eb9098 Method for removing a file with optional authorization. 2009-12-14 22:33:00 +01:00
Uli Kusterer 4c765d86ee More correct way of turning a C-string path into an NSString. 2009-12-14 22:32:32 +01:00
Uli Kusterer fa8aaced55 Make sure we also delete the temp dir when the user clicks "cancel" during the download. 2009-12-14 22:30:56 +01:00
Uli Kusterer 1b02ab5f7f Make sure we delete the temp directory. 2009-12-14 22:28:47 +01:00
Uli Kusterer 0e609cc528 Make sure we delete the temp directory. 2009-12-14 22:28:14 +01:00
Uli Kusterer 5ec4c74b0b Fix typo in LONG_INSTALLATION_TIME constant. 2009-12-14 22:24:48 +01:00
Uli Kusterer 4d7006950a Make sure mdimport is run synchronously, not asynchronously. 2009-12-14 22:22:23 +01:00
Uli Kusterer e49a69895a Fix authorized file moving code:
- We now correctly handle the case where the containing directory doesn't allow us adding files without authorization (e.g. /Applications).
- We do the quarantine release *before* the copy.
2009-12-14 22:21:27 +01:00
Uli Kusterer 27f2b9c219 Move 10.4 SDK setting into xcconfig file. 2009-12-14 22:18:15 +01:00
Patrick Stein db820fbb0f updated the installer program to show an icon when the installation takes more than 1.2 seconds,
long installations have a program in the Dock
short installations just look like the program is restarting
some variable renaming to no longer have camelCasePath for char *
2009-12-12 13:52:42 +01:00
Patrick Stein ad4e9c74e0 changed back 10.4 settings cause it broke the updater on 10.4 2009-12-11 19:44:22 +01:00
Uli Kusterer 4797446f7c Be paranoid and wait for the mdimport to finish before we launch the app. Might make spurious "no executable" errors a bit less likely. 2009-12-11 15:17:59 +01:00
Uli Kusterer 0ffcde4fbb Make sure we delete the temporary folder when the user cancels the download. Also make sure we delete it on 10.4, which seems to have a bug in removeFileAtPath: that won't delete nested empty folders. As a quick fix, I just trash the folder in that case. We already put the old version in the trash anyway, and this saves me from having to write, test and debug a recursive removal function. 2009-12-11 15:13:30 +01:00
Patrick Stein f555e1143f Merge remote branch 'uliwitness/master' 2009-12-11 14:54:32 +01:00
Uli Kusterer bc3fd4542b Remove 10.4 SDK setting. Causes more problems than it helps. 2009-12-11 14:46:30 +01:00
Patrick Stein d3fac14586 Merge remote branch 'uliwitness/master' 2009-12-11 13:31:39 +01:00
Patrick Stein d0425a140a Updating an application now longer shows the installation application n the Dock (LSUIElement) , Removed TransformProcessType call as it will force the installer application to show in the Dock. 2009-12-11 13:28:10 +01:00
Uli Kusterer 64ec0c317e Tests for version numbers with build numbers. 2009-12-11 13:10:29 +01:00
Patrick Stein 5f694f82af Intermediate Update directory name contains the version number of the downloaded version 2009-12-11 12:53:52 +01:00
Uli Kusterer 590122f25a Merge remote branch 'andymatuschak/master' 2009-12-11 12:51:33 +01:00
Patrick Stein 9b670b9ea7 removed cmdline installation tool and copied installation app to Sparkle framework. 2009-12-11 12:24:41 +01:00
Patrick Stein 65e836cba1 fixed Version Comparision , added more testcases 2009-12-11 12:12:23 +01:00
Patrick Stein c634f61f2a commented unused boxView code. 2009-12-11 11:56:18 +01:00
Patrick Stein 776e78c459 added Prefix header to finish_installation_tool
added SystemConfiguration.framework to Sparkle
added SUWindowController.m to finish_installation_tool
added SUStatusController.m to finish_installation_tool

now compiles Sparkle. Now going to fix the testbuild
2009-12-11 11:51:15 +01:00
Andy Matuschak a03235851c Removing GNU-style ?: operators. Thanks for the report, Uli. 2009-12-10 15:52:47 -08:00
Uli Kusterer d2f843f92c Danish localization updates. 2009-12-08 19:09:11 +01:00
Uli Kusterer e9c69673ad Set floating window level on the update alert again, but only for bg-only apps. Don't want to annoy users by having an always-visible panel. 2009-12-08 19:03:20 +01:00
Uli Kusterer a453afa29a Delegate can now control how version numbers are formatted/displayed to the user, so we can e.g. exclude build numbers or whatever makes sense for a particular application. 2009-12-08 19:02:10 +01:00
Uli Kusterer cee669c276 Shutting up warnings due to missing includes and fix indentation on one line. 2009-12-08 18:58:59 +01:00
Uli Kusterer 2e0c1b0086 One more SULog() replacing an NSLog(). 2009-12-08 00:44:01 +01:00
Uli Kusterer 7686c86792 Adjust the width of the status window so all localizations fit. 2009-12-08 00:43:08 +01:00
Uli Kusterer 2e0f0211d1 We now really put the old app in the trash (and any file we have to move out of the way to install a new app when we reset an edited name), even on non-admin user accounts. +++ TODO: Work around double authorization. 2009-12-08 00:37:39 +01:00
Uli Kusterer 4f8d745305 Changed a few NSLogs() to SULogs(). 2009-12-08 00:36:07 +01:00
Uli Kusterer 9788c6849e We should now correctly replace renamed apps, trashing the custom-named one, installing a new one with a default name, and also moving out of the way any existing copy with the default name. 2009-12-08 00:29:55 +01:00
Uli Kusterer 48dfbac37a Don't insist on having a file to replace. When we normalize the name, we may not have one. 2009-12-08 00:20:29 +01:00
Uli Kusterer e4eccce811 Updated localizations. 2009-12-08 00:17:50 +01:00
Uli Kusterer 097c2fea42 Build for more than just current architecture. We only build 32-bit because otherwise we'll get errors against 10.4 SDK (where 64-bit AppKit is not yet supported). 2009-12-07 23:52:43 +01:00
Uli Kusterer 5a5b171a68 Commented preprocessor switches. Added a named switch for normalizing an app name (it was just a #if 1 before). 2009-12-04 09:35:20 +01:00
Uli Kusterer 343d6866c4 - finish_installation is now a real bundled app, so it can be localized.
- It contains its own copy of Sparkle.strings and SUUpdateStatus.nib so it can show its progress prettier
- We call TransformProcessType() before our first call to [NSApplication sharedApplication], so we can be launched as a command line tool and get a proper window server connection, and so our progress bars animate.
- We still support the old "relaunch"-style mode of operation, just by not passing the folder to install. This is useful for other relaunch occasions, like setting one's own dock icon flag.

- To do: Make sample app use the new finish_installation.
2009-12-04 09:20:21 +01:00
Uli Kusterer 2ad144c739 Partial Elgato string merges. 2009-12-04 09:13:25 +01:00
Uli Kusterer 983ad61d78 Maybe that makes the progress bar animate? No, it doesn't. 2009-12-04 09:12:42 +01:00
Uli Kusterer 27e87143e1 target is an ObjC object, so nil, not NULL. 2009-12-04 09:11:50 +01:00
Uli Kusterer d0b802e09b Added preprocessor defines to SUConstants.h for turning on/off DSA and downgrades. We let users downgrade using our URL scheme, and we warn them beforehand, so the downgrade possible attack paranoia gets in the way. 2009-12-04 09:11:11 +01:00
Uli Kusterer 8c67631efb Use installPath, not bundlePath here. 2009-12-04 09:06:55 +01:00
Uli Kusterer 18df114b70 Bring window to front when progress panel changes to "Install and restart", it's essentially a new alert coming up. 2009-12-04 08:52:42 +01:00
Uli Kusterer c51bf739cf Shut up undeclared selector warning. 2009-12-04 08:51:13 +01:00
Uli Kusterer 43a0a7db4f Merge of changes from SVN repository:
- Changed NTSynchronousTask to also give the status return value and direct stderror output to the outputData.
- Changed includes so this builds as part of an app, too, not just as a framework
- Made sure SUAppcast's dealloc releases some leaked ivars.
- Added infoURL, extracted from link, that can point to a "more Info" page for download-less URLs
- Added support for version attribute on item so we can support update notifications that don't include an enclosure (e.g. paid upgrades, or upgrades that would require a system update)
- Added/improved a few description methods to ease debugging.
- Added SULog so one can ask for a special log with additional information when there are update issues.
- Added mayUpdateAndRestart for apps that absolutely, positively can't restart right now (e.g. cuz they're burning a CD and would produce a coaster).
- Added updaterWillRelaunchApplication delegate method, analogous to the notification. Useful to have app delegate quit helper apps during installation.
- Made SUBasicUpdateDriver's abortUpdate implicitly retain/autorelease the update driver, because the notification center otherwise releases it and it goes away, causing crashes in superclass's abortUpdate.
- Merge of SUKeepDownloadOnFailedInstallKey and SUFixedHTMLDisplaySizeKey.
- Avoid a few warnings about missing prototypes
- Be paranoid, hdiutil can verify the download again, so let it. Better for internal apps where we turn off DSA checks, too.
- SUHost has an -installationPath now, independent from the bundlePath, so one can normalize the app name from "MyApp 1.1b4" back to "MyApp" Users assume the file name contains the correct version number when there is one in it. Saves support a few round-trips each time.
- Be better at threading: Try calling non-thread-safe methods on main thread only, and don't assume delegates know when they need to be thread-safe, call them on main thread where possible.
- Added a method to put the old copy of the app in the trash. 1.5git changed in this spot, so I didn't actually merge the code that uses it back in yet.
- Fix version comparison so it doesn't get confused by bracketed build numbers in version strings
- Make sure cancel button is disabled during extraction, otherwise user would crash.
- Don't put auto-update window at floating window level. It's huge and can't be switched to background! If you're an NSBGOnly where you need that, turn it on only in that case, but don't generally do such nonsense.
- Hide release notes view if there aren't any.
- Test whether we are on dial-up before checking for updates in background. It's not nice to cause (possibly expensive) dial-up periodically.
- Temporarily comment out DSA complaints for easier testing.
- Don't store (possibly already invalidated) one-shot NSTimers in an ivar. It's bad style. Retain it instead.
- Decompress some monster expressions with nested method calls in ternary operators and nested in method calls again.
- Don't use implicit "id" for params or return types.
- finish_installation now puts up a progress window, so user knows update is still not finished.
- Use ThreadSafePreferences (included dummy version that uses regular prefs for projects that don't use ThreadSafePreferences).

- Todo later: Change finish_installation to be prettier.
2009-12-04 08:40:46 +01:00
Uli Kusterer bbcfe7edf4 - More WIP creating finish_installation that waits
for quit, updates and relaunches the app, so
updates don't happen while app is still running.
NSBundle gets royally confused and points to the
old path (loading new NIBs into the old app in the
worst case) when you move a running app.
- Temp folder is now user's desktop, as
NSTemporaryDirectory() doesn't stay the same
between two separate apps, and may be emptied on quit.
- Relaunch gets created in App Support now, for
same reasons as above.
- Less dependency on prefix headers, that only leads
to lazy, un-reusable code.
2009-12-04 07:46:07 +01:00
Uli Kusterer a11578a863 WIP turning the relaunch tool into a finish_installation tool. 2009-12-04 07:40:28 +01:00
Andy Matuschak b546304d5d Updated Danish localization courtesy David Munch. 2009-11-28 12:37:27 -08:00
Sean McBride d7774c0dc0 performed a code review, specifically:
- changed some #include to #import
- fixed some NULL -> nil Cocoa coding conventions
- added new compiler warnings and fixed some warnings they generated
- check for nil from NSTemporaryDirectory
- added missing files to unit test and test app targets
- added xcconfig files for unit test target
- added @private to some ivars
- changes some variables from signed to unsigned as appropriate
- changed from base 2 to base 10 measurements of file size, consistent with both the actual meaning of metric prefixes and Apple's new policy as of 10.6
- reduced some unneeded copy-paste of code
- fixed failure to check for null from malloc and unneeded check against null before calling free
- OSErr was incorrectly used instead of OSStatus
- added some consts & statics to global strings
- fixed some issues discovered by static analysis
- fixed some 64bit issues, mostly related to casting and the use of slightly incorrect types/sizes
- some dealloc methods were using accessors, changed to access ivars directly, as per Apple guidelines
- removed old NS_DURING, NS_HANDLER, NS_ENDHANDLER macros
- fixed a bug where immutable data was being mutated
- removed all instance of "== YES" as they are dangerous
- removed some redundant nil checks
- fixed some leaks
- conditionally replaced deprecated method usage
- cleanup CF/NSMakeCollectable usage
- fixed bug in GC where memory could be collected too early due to lack of strong references when using UTF8String
- prevent passing null to CFRelease
2009-10-31 21:07:00 -04:00
Andy Matuschak bd80144c7b Fixing #456514: Appcast download crashes on 10.5 if download fails 2009-10-20 13:55:03 -07:00
Andy Matuschak af37928283 Fixed a Spanish localization issue in the update permissions prompt; fixed release-mode compatibility for Leopard. 2009-09-20 00:15:06 -04:00
Andy Matuschak 6a3df43017 Fixed Bug #428216: "Update alert does not use a proper emdash" 2009-09-20 00:05:23 -04:00
Joachim Bengtsson 7bfbe83d87 When failing to parse a feed item, tell the developer *what* the error is. No need for a full-fledged NSError because these errors only go to the console, not displayed to the user (who doesn't care). 2009-09-06 17:54:02 -07:00
Joy Zhao a871569867 Bug #423014: "Translation errors in Spanish and Italian" 2009-09-03 23:42:46 -07:00
Grant Erickson 65b071eb86 If no suitable packages or bundles are found to be installed, Sparkle will install the first package it finds in the distribution archive. 2009-09-03 23:29:50 -07:00
Christiaan Hofman 0e99d4fa80 Bug #402074: ".pkg installations should support asynchronous installation" 2009-09-03 23:20:03 -07:00
Andy Matuschak 8f00c3c274 Fixing Bug #422201: ""Checking for updates..." needs to be added to spanish (es.lproj) strings"
The Spanish localizer actually sent these over, but I forgot to add 'em in!
2009-09-01 20:36:46 -07:00
Stuart Morgan 4fad53007f Change availability checks so that they build on 10.4 2009-09-01 20:10:16 -07:00
Andy Matuschak e7435964a2 Fixing Bug #421608: "Update fails if more than one .app exists in the archive" 2009-08-30 20:24:28 -07:00
Ernesto Gomez Cereijo 8ea15468b4 Updated the Spanish localization. 2009-08-28 09:17:35 -07:00
Andy Matuschak 9025bef687 Fixed moving to trash on Tiger. 2009-08-27 22:04:51 -07:00
Fraser Speirs ffc44bb089 Added a space in the description of the SUNoFeedURL exception becuase it led me to believe that the value of SUFeedURLKey was actually @"SUFeedURLKey" and not @"SUFeedURL". 2009-08-27 11:29:15 +01:00
Andy Matuschak 6c968489eb Bug #381138: "Translator erros on check updates dialog"
A bunch of small localization tweaks courtesy Joy Zhao.
2009-08-27 00:54:21 -07:00
Andy Matuschak 2fc1b66a79 Fixing:
Bug #389869: "Sparkle runs thread-unsafe code on secondary threads"
Bug #312995: "Canceling authentication request causes crash on next update"
Bug #388793: "Need to notify SUUpdateDriverFinishedNotification on main thread"

The unfortunate side-effect of this fix is that all the file-handling code is now CoreServices-based, since NSFileManager is not thread-safe. This is disgusting and will be stricken from all records when installation is performed by relaunch in Next Major, as it should have been in the first place.
2009-08-27 00:43:32 -07:00
Andy Matuschak bd99d0451d Fixing Bug #274872: "Activate host app on automatic update when when host runs in background" 2009-08-27 00:04:53 -07:00
Andy Matuschak d62e47cd2e Fixing Bug #416798: "Sparkle should warn developers if the app has no public key and the appcast isn't https://" 2009-08-27 00:02:10 -07:00
Mark Rowe ab23fedd0c Merge branch 'master' into delta-updates 2009-08-23 15:18:46 -07:00
Simone Manganelli 43a603c1cc if the user chooses to not restart the host app after installing the new version, the Sparkle update status window goes away and stops annoying the user by staying on screen; originally by simX, http://github.com/rentzsch/clicktoflash/commit/c768f07087c769f12f7645e78dd42802da46048b 2009-08-23 14:19:57 -07:00
Simone Manganelli 9b5b541c82 Fix for Sparkle crasher in scheduleNextUpdateCheck. Originally by lapcat, http://github.com/rentzsch/clicktoflash/commit/f7ca07b3e6e6e13de8133d8e237f284f2ccdc066 2009-08-23 14:16:02 -07:00
Andy Matuschak 119bac527f Merge branch 'bdash/leak-fixes' 2009-08-23 09:52:55 -07:00
Andy Matuschak e9bc6a2915 Merge branch 'leak-fixes' of git://github.com/bdash/sparkle into bdash/leak-fixes 2009-08-23 09:52:40 -07:00
Andy Matuschak 2979338f8a Merge branch 'master' of git://github.com/bdash/sparkle into bdash/custom-user-agent-string 2009-08-23 09:46:39 -07:00
Andy Matuschak 830f633a6e Added new IB3 files for the changed localizations in the last revision.
Updated the German localization, courtesy Christoph Schmitz.
2009-08-21 19:07:37 -07:00
Mark Rowe 0d51d12e43 Merge branch 'master' into leak-fix 2009-08-21 15:28:30 -07:00
Mark Rowe 2d47989616 Remove bogus call to retain that results in a leak of an NSMethodSignature. 2009-08-21 15:26:55 -07:00
Mark Rowe f259b5e825 Return an autoreleased object as callers expect rather than leaking the dictionary. 2009-08-21 15:25:06 -07:00
Mark Rowe 3800b33c1a Merge branch 'master' into custom-user-agent-string 2009-08-21 14:47:51 -07:00
Mark Rowe dfe0eff095 Provide the ability to set a custom user agent string on all HTTP requests that Sparkle initiates. 2009-08-21 14:46:39 -07:00
Mark Rowe 8cdec40a03 Merge branch 'master' into delta-updates 2009-08-21 14:40:05 -07:00
Mark Rowe 6169234300 Rework the BinaryDelta tool to use NSOperationQueue in order to be slightly more portable.
There's slightly less concurrency as a result as all archiving operations are now performed
serially on the main thread.  Since these make up a small percentage of the overall runtime,
the increased portability makes this a reasonable tradeoff.
2009-08-21 14:40:00 -07:00
Mark Rowe 3ff2d82ecf Fix warnings and binary compatibility issues that crop up when building the BinaryDelta tool against different SDKs. 2009-08-21 14:40:00 -07:00
Mark Rowe 3ef4c09f71 Link against a static build of libxar as libxar.dylib didn't ship on Tiger. 2009-08-21 14:40:00 -07:00
Mark Rowe 79bd7ac090 Add an unarchiver for the delta format so that Sparkle can successfully install the delta updates. 2009-08-21 14:40:00 -07:00
Mark Rowe 6e648f14f4 Add support for parsing an extended <sparkle:deltas> element in the appcast that describes
the delta updates that are available for a given version.

The appcast would look a little something like the following:

<enclosure url="http://you.com/app/Your Great App 2.0.zip" sparkle:version="2.0" length="1623481" type="application/octet-stream" sparkle:dsaSignature="BAFJW4B6B1K1JyW30nbkBwainOzrN6EQuAh" />
<sparkle:deltas>
    <enclosure url="http://you.com/app/Your Great App 1.5 to 2.0.delta" sparkle:version="2.0" sparkle:deltaFrom="1.5" length="642381" type="application/octet-stream" sparkle:dsaSignature="MCa1JyW30nbkBwaC0CFBfeinOzrN6EQuAh=" />
    <enclosure url="http://you.com/app/Your Great App 1.4 to 2.0.delta" sparkle:version="2.0" sparkle:deltaFrom="1.4" length="928231" type="application/octet-stream" sparkle:dsaSignature="B6B1K1JyW30nbkBDBfeinOAszrN6Ea1JyW3" />
</sparkle:deltas>
2009-08-21 14:40:00 -07:00
Mark Rowe c3d8254324 Add a command-line tool that can generate and apply a binary delta between two versions of an application.
The delta file is a custom format created from the xar container format.  It describes the necessary
modifications to transform the contents of the old directory in to the contents of the new.  Binary
diffs are used to compress the differences between large files such as Mach-O binaries.  The binary
diffs are generated by bsdiff and applied via bspatch, both from bsdiff 4.3, the source of which is
included and used under a BSD-style license.
2009-08-21 14:39:54 -07:00
Andy Matuschak 15095640eb Fixing Bug #400536: @"The update is improperly signed." does not localized 2009-08-20 23:53:14 -07:00
Andy Matuschak 6070419761 Bug #377834: "MoreInfoView summary appears empty in SUUpdatePermissionPrompt in non-English locales" 2009-08-20 23:48:28 -07:00
Andy Matuschak db2f48ad09 Oops: *actually* finished doing the architecture configuration update. 2009-08-20 23:42:16 -07:00
Andy Matuschak cfe5206252 Fixing Bug #396495: "Wrong method name"
Just a convention mismatch in a private method.
2009-08-20 23:32:51 -07:00
Andy Matuschak 975f679148 Removing deprecated warning flag. 2009-08-20 23:29:39 -07:00
Andy Matuschak b571a3d58d Fixing Bug #398921: Sparkle should detect read/write errors on archive extraction
Thanks to Jim Turner for the patch.
2009-08-20 23:28:26 -07:00
Andy Matuschak 5090d4b3a0 Giving the "seconds" field a little more space. 2009-08-20 23:25:04 -07:00
Andy Matuschak 799b00211d Fixing Bug #338324: "Unsigned updates delivered over https fail"
Silly boolean logic error.
2009-08-20 23:24:13 -07:00
Andy Matuschak afe8afc41f Fixing Bug #393388: Leaking NSFileManager errors 2009-08-20 23:18:15 -07:00
Andy Matuschak 090e7c0ecb Fixing Bug #304674: "Debug linking can break on default Xcode projects"
Sparkle now builds for all architectures in debug mode.
2009-08-20 23:14:52 -07:00
Andy Matuschak e557b78394 Updated the CFBundleVersion script to use the Sparkle git hash instead of the Bzr revno. 2009-08-20 23:12:51 -07:00
Andy Matuschak c53f961690 Fixing Bug #272346: "Sparkle Test App needs to use the new preferences bindings" 2009-08-20 23:02:55 -07:00
Andy Matuschak 9e6b51fac9 Fixing Bug #415707: "Crash on hitting Esc in an update alert in garbage-collected Sparkle" 2009-08-20 22:50:34 -07:00
Andy Matuschak a6f98158a7 Removed a warning caused by the last commit. 2009-08-20 22:49:15 -07:00
Andy Matuschak ca040bdf9a Fixing #394787: "SUUnarchiver passes NSNumber to method requiring long" 2009-08-20 21:22:24 -07:00
Andy Matuschak f95cf6454d A little cleanup on bricooke's patch. 2009-08-20 20:58:53 -07:00
Brian Cooke 827c6adc03 when about to show the user what will be anonymously sent, make sure the delegate is told that systemprofile info will be sent so it knows to put its custom additions in there. 2009-08-20 10:00:41 -06:00
Andy Matuschak 59d9ece06b Fixes bug #337331: "Status progress still doesn't animate"
In general, the progress indicator bindings for animate and isDeterminate are totally unreliable. Giving up on them.
2009-08-19 23:29:21 -07:00
Andy Matuschak 1dd1b09e5f Fixing #341643: "wrong version number in automatic update alert"
Thanks to Jim Turner for the patch.
2009-08-18 22:20:46 -07:00
Andy Matuschak 58296ecaf7 Added a Czech localization courtesy the Czech X Team. 2009-08-18 21:58:50 -07:00
Andy Matuschak 3b0674320f Made the test app use garbage collection when built in the GC build configuration. 2009-08-18 19:53:45 -07:00
Andy Matuschak a8b2b4f962 Removed an extraneous space from an Italian string. 2009-08-16 02:27:37 -07:00
Clint Shryock 6fc32b6800 added readme file.
Pulled information from http://sparkle.andymatuschak.org/
2009-08-13 21:09:53 -05:00
Andy Matuschak 1e20d43c2a Added brazilian portuguese localization courtesy Paulo Neto. 2009-08-11 23:37:33 -07:00
Andy Matuschak 52814bcbd0 Removed .bzrignore 2009-08-11 00:06:29 -07:00
Andy Matuschak 74fccaaab5 Added the new Polish and Japanese localizations to the project. Oops. 2009-07-31 22:46:32 -07:00
Andy Matuschak 6813a06455 Added Japanese translation courtesy Koichi Matsumoto. 2009-07-30 19:35:45 -07:00
Andy Matuschak e423cfee35 Going back to GCC for compilation. 2009-07-11 00:56:43 -07:00
Andy Matuschak 7316a00e9c Removed SL-deprecated NSFileManager methods. Left the old ones around #if'd for 10.4 support; I look forward to removing them. :)
Thanks for the patch, August.
2009-06-20 18:41:40 -05:00
August Joki 54299d766a added #ifdef's for Tiger support 2009-06-14 21:37:45 -07:00
August Joki f2a7b4b349 Fixed deprecated APIs to use replacements. 2009-06-14 19:30:46 -07:00
Andy Matuschak 150718ad6f Fixing the behavior of one of the build scripts when run multiple times; thanks for the patch, Stuart. 2009-05-22 00:02:43 -07:00
Stuart Morgan 0904ec151c Fix fr_CA linking so that it works correctly when run multiple times. 2009-05-21 21:02:35 -07:00
Andy Matuschak dff6e0832c Merging in a fix to a bug which caused the user agent string not to be null-terminated. 2009-05-19 11:44:02 -07:00
Andy Matuschak e983c03232 Added missing "Cancel Update" string. 2009-05-19 11:35:52 -07:00
Jeremiah Boyle d1c54608f7 [cleanedAgent bytes] is not null-terminated so stringWithCString produces a bad NSString. use initWithData instead. 2009-05-09 17:31:35 -04:00
Andy Matuschak 24b6c88935 Added Icelandic localization courtesy Steingrímur Árnason. 2009-05-08 09:26:46 -07:00
Andy Matuschak 6397e56c06 Updated Sparkle's license to include external licenses. 2009-04-28 20:27:24 -07:00
Andy Matuschak 9785111857 Merging in fix for 10.4 SDK 2009-04-05 14:42:09 -07:00
Stuart Morgan 522ffb08f0 Add a conditional definition of NSAppKitVersionNumber10_4 to allow building against the 10.4 SDK. 2009-04-04 21:48:21 -07:00
Andy Matuschak 22129e3ec7 Fixes #353896: SUWindowController should #import SUHost 2009-04-02 10:41:24 -07:00
Andy Matuschak 4431864770 Added Danish, Chinese Traditional, and Chinese Simplified translations to the project. 2009-04-01 20:51:21 -07:00
Andy Matuschak 23a57f7876 Fixed a bug that might occur in debug configurations with weird working paths. Thanks to Uli Kusterer for catching it. 2009-03-30 15:40:12 -07:00
Andy Matuschak 05b75aa44c Fixes Bug #321761: Update crashes below NSTask if /usr/bin/mdimport does not exist or is not executable 2009-02-11 14:54:55 -08:00
Andy Matuschak e35a1ca231 Added Polish localization courtesy Grzegorz Wilk.
Fixed a string in the Spanish localization.
2009-02-10 10:21:40 -08:00
Andy Matuschak 1cc6c2b9ca Updated Spanish localization courtesy Alexsander Akers. 2009-02-10 10:16:22 -08:00
Andy Matuschak 8c092c7453 Fixing 316105: "Icon defaults to app icon, also for non-app bundles"
Thanks to Hofman.
2009-01-12 14:31:52 -08:00
Andy Matuschak 6631fce15f Undoing accidental change to a build configuration. Oops! 2009-01-10 00:14:05 -08:00
Andy Matuschak 7071142aad Improving Sparkle's robustness against apps without a CFBundleVersion. 2009-01-09 18:57:29 -08:00
Andy Matuschak 34586bca5a Finishing fixing #279454 (up to date -> up-to-date) 2009-01-08 10:49:41 -08:00
Andy Matuschak 516638a6d7 Fixing Bug #314456 "SUPackageInstaller exec of 'open' on 10.4"
Thanks to Peter Speck for the patch. This could use some testing!
2009-01-06 14:32:10 -08:00
Peter Speck d4c39a2ad9 Fallback to Installer.app on 10.4 2009-01-06 23:09:32 +01:00
Andy Matuschak d6288c175e Fixing Bug #301614: "SUUpdater initForBundle: should be public" 2009-01-05 23:12:48 -08:00
Andy Matuschak 08b785083a Fixing Bug #300053: "Disable signature requirement when appcast and update archive URLs are local" 2009-01-05 23:11:26 -08:00
Andy Matuschak a7818f0f64 Fixing Bug #279454: "Spelling error in update framework"
"up to date" -> "up-to-date"
2009-01-05 23:06:20 -08:00
Andy Matuschak 52642aa11a Fixing Bug #275463: "SUScheduledUpdateDriver doesn't call updaterDidNotFindUpdate"
Thanks to Peter Speck for the patch!
2009-01-05 22:58:55 -08:00
Andy Matuschak 27c886f6b9 Updated French localization; thanks to Ronald Leroux. 2009-01-05 15:12:48 -08:00
Andy Matuschak 85eb5a7496 Fixing #314047: "Wrong version check in SUHost code"
Thanks to Hofman for the patch and the catch.
2009-01-05 09:42:35 -08:00
Andy Matuschak 91c242ac04 Fixes Bug #312381: "Bundles can't ask for permission to update; developers have to hard-code YES for SUEnableAutomaticChecks"
Thanks to Hofman for the patch! Now the update cycle will be started once the SUUpdater instance is instantiated; bundles no longer need to expressly start the update cycle.
2009-01-01 13:37:08 -08:00
Andy Matuschak 8ff6c147f2 Fixing 301644: Limit WebView Contextual Menu
Thanks to David Dauer for the patch.
2008-12-27 23:14:55 -06:00
Andy Matuschak 8b4bb5a078 Fixing #302886: Standard web preferences are polluted
Thanks to Martoche for the patch.
2008-12-27 23:07:36 -06:00
Andy Matuschak 9d260f9b0e Bug #275309: Crash in NSURLConnection
This one's a little experimental. Credits to Hofman for the patch. This changes the appcast fetching over to NSURLDownload from NSURLConnection. Test, please!
2008-12-23 22:11:17 -06:00
Andy Matuschak 59cd48f3de Added Danish localization courtesy Mogens Thyregod
Added Chinese Traditional localization courtesy Jack M. H. Lin
Added Chinese Simplified localization courtesy JT Lee
2008-12-18 23:22:59 -06:00
Andy Matuschak b11db20742 Added Slovak localization courtesy Rudolf Gavlas. 2008-12-18 12:28:09 -06:00
Andy Matuschak f186aa6896 Fixed some deprecated method use which caused warnings with new versions of the iPhone SDK. 2008-12-16 00:08:33 -06:00
Andy Matuschak 2bedf000a8 Added Korean localization courtesy 동성... 2008-12-10 20:02:42 -08:00
Peter Speck 3d6f4544f1 SUScheduledUpdateDriver doesn't call updaterDidNotFindUpdate 2008-09-28 16:39:05 +02:00
Andy Matuschak 13deac9b58 Fixes 271378
Sparkle is now willing to install a bundle in the archive with the same bundle identifier as the running app as a fallback strategy.

Thanks to Jim Turner for the patch.
2008-09-19 18:24:52 -07:00
Andy Matuschak 21c60ef7ce Fixes 272211
Sparkle is now installing .pkgs by launching Installer.app with open instead of NSWorkspace; the latter resulted in strange window ordering. Thanks to Peter Speck for the patch.
2008-09-19 18:16:10 -07:00
Andy Matuschak 83adbb2979 Fixes 270585
Now symlinking fr_CA.lproj correctly.
2008-09-19 14:28:05 -07:00
Peter Speck c614b679e1 Install.app launches in semi-background from PrefsPanel 2008-09-19 19:48:10 +02:00
Peter Speck 10bcc69c80 fix fr_CA.lproj symlink 2008-09-15 18:33:36 +02:00
Andy Matuschak 9eb4368d6f Updated sample appcast to be appropriate for DSA signatures being required. 2008-09-13 22:54:16 -05:00
Andy Matuschak 783fd4b475 Merging in new Dutch localization changes. 2008-09-13 22:53:53 -05:00
Andy Matuschak 00efab8ad2 generate_key.rb => generate_keys.rb 2008-09-11 22:08:32 -05:00
Andy Matuschak d73b3745bf Fixes 268756
When determining LSUIElement status, Sparkle now asks the process manager instead of checking Info.plist; this'll support apps that change their LSUIElement status at runtime.
2008-09-11 11:33:18 -05:00
Andy Matuschak ccd44c0cb2 Fixes 268723
Now forcing a DSA signature check if the client provides a public key with the app.
2008-09-10 17:48:57 -05:00
Andy Matuschak 9a0acca849 More security tidbits!
This patch prevents malicious downgrades, which are still possible with DSA validation: suppose there's some (signed) version with a security hole. A malicious attacker could serve an appcast with that version's URL and DSA signature, but a higher version number, forcing the user to "upgrade" to the version with the security hole.

While I was at it, I fixed a bug that should have completely stopped .pkg installation from working since 1.5b1. Why didn't I hear anything about that? Does anyone actually use .pkgs? It still needs testing to be sure it works.
2008-09-10 11:47:58 -05:00
Andy Matuschak 95f9658a7e Fixes 244692
Fixing a GC leak that would occur on non-64-bit machines.
2008-09-10 10:47:22 -05:00
Andy Matuschak 0fa24ce313 Restored the old default font size for release notes, now that we're doing webview preferences a different way. 2008-09-10 10:45:58 -05:00
Andy Matuschak 28ad466aa8 Fixes 268471
-- Removed obsolete configuration settings regarding 10.3 support.
-- Stopped a configuration file from getting added to the Resources folder.
2008-09-10 10:39:31 -05:00
Andy Matuschak 7e9fc0f20b Changed the security policy once more:
The user is defined as "safe" and exempt from DSA signatures if he downloaded both the appcast and the update over SSL.
2008-09-10 10:37:47 -05:00
Andy Matuschak 7f5689835b Fixed a small security hole: release notes specified with a file:// URL would be able to read files on your file system through Javascript (basically a cross-site scripting attack). file:// URLs are therefore no longer supported for release notes. 2008-09-09 23:39:00 -05:00
Andy Matuschak 478e0a53d0 Fixed a potential security vulnerability in which the download is transmitted over SSL but is from a malicious server. Now the download has to be transmitted over SSL *and* the download's host has to be the same as the appcast's. 2008-09-09 23:34:20 -05:00
Andy Matuschak 588cad8d91 Killed off SUExpectsDSASignatureKey. 2008-09-06 19:07:54 -05:00
Andy Matuschak 1d3ab8d6bb Alright, guys. No more Mr. Nice Sparklepants. Sparkle now requires either DSA-signed updates or SSL transport. If you want to put your users at risk, you're going to have to comment out some code and recompile.
I included some scripts to help you along, though. IANASG (I Am Not a Security Guy), though, so if you know your shit, feel free to do it on your own as before.
2008-09-06 18:59:50 -05:00
Andy Matuschak e086aa1660 Munged localizations so that unicode characters like em-dashes and ellipses are now in the values of the localization strings, not the keys; putting them in the latter made Sparkle unbuildable on Tiger. Thanks to Stuart Morgan for the patch. 2008-09-06 12:34:03 -05:00
Stuart Morgan 188a15a948 Fix a key in sv.lproj 2008-09-04 20:22:45 -07:00
Andy Matuschak 874660f52e Added a warning log message for bundles which don't have a CFBundleIdentifier key. 2008-09-04 10:51:46 -05:00
Stuart Morgan 29bd46d68d Don't use unicode in NSString literals 2008-09-04 07:57:17 -07:00
Andy Matuschak cb80e0ef51 No longer polluting the standard WebView preferences. Thanks to Christiaan Hofman for the patch. 2008-09-04 09:53:53 -05:00
Andy Matuschak ccef53a3d3 Fixes 259704
Fixed a memory leak in the update permission prompt.
2008-09-04 09:44:35 -05:00
Andy Matuschak d201803259 More fixes for 258060
Fixes a bug which could cause a crash when the update item is chosen by the delegate from the appcast. Thanks, Christiaan Hofman.
2008-09-03 22:34:25 -05:00
Andy Matuschak 74b206dc77 Fixes 259455
Fixes release notes stored raw in the <description> key. Thanks to Peter Speck for the patch.
2008-08-19 21:57:23 -07:00
Andy Matuschak 42cda2d2e0 Fixes 259062
Added a SUUpdater key for lastUpdateCheckDate. Thanks to Peter Speck for the patch!
2008-08-19 21:44:39 -07:00
Andy Matuschak c386b704b5 Partial fix for 245277: basic descriptions for some Sparkle classes. Thanks to Christiaan Hofman for the patch. 2008-08-19 21:24:26 -07:00
Andy Matuschak 84be00b29f Fixes 258991
The selector for the updaterWillRelaunchApplication delegate call had a typo in it, so it wasn't getting called. Oof.
2008-08-19 21:13:15 -07:00
Andy Matuschak d064b589ae Fixed the total failure of the SUProbingUpdateDriver to notify its delegate when an update is found. Sorry about that, guys! Wow. 2008-08-19 21:09:31 -07:00
Peter Speck 90edd12e43 No update-release notes displayed for when using <description> instead of <sparkle:releaseNotesLink> 2008-08-19 17:50:28 +02:00
Peter Speck c71bf3ccbe Provide getter for SULastCheckTimeKey 2008-08-18 15:11:05 +02:00
Andy Matuschak 724b4de07e Renamed SUAppcastItem's "description" key to "itemDescription" so as not to conflict with the standard Cocoa description method. 2008-08-17 15:23:50 -07:00
Andy Matuschak 444b0a928d Fixed a stupid mistake that prevented my fix for parameterized URLs from actually functioning. 2008-08-17 14:15:57 -07:00
Andy Matuschak ec8fcbc02f If an update's display version is the same as the host's display version, the internal version number will be presented in parentheticals. 2008-08-17 13:51:55 -07:00
Andy Matuschak 68e2cd67d1 Fixes 258492
Sparkle can now handle appending parameters to URLs which already have parameters (like http://foo.org/baz?bat=4)
2008-08-17 13:42:47 -07:00
Andy Matuschak c21e1aba35 Fixes 258529 and 257967
Added backwards compatibility support for Sparkle 1.1's behavior of disabling automatic updates when the check interval was 0.

Sparkle will now properly reset the update cycle when setAutomaticallyChecksForUpdates or setUpdateCheckInterval is called for non-.app bundles.
2008-08-17 13:25:49 -07:00
Andy Matuschak ec7f38d157 Fixes 258547
SUUpdater now implements two new keys: "automaticallyDownloadsUpdates" and "sendsSystemProfile".

Here's the current state of the setting keys, as documented by Christiaan Hofman:

* UserDefaults through SUUpdater accessors with default value in Info.plist:

SUFeedURL
SUScheduledCheckInterval
SUEnableAutomaticChecks
SUSendProfileInfo
SUAutomaticallyUpdate

* Info.plist only (app settings):

SUShowReleaseNotes
SUPublicDSAKey
SUPublicDSAKeyFile
SUExpectsDSASignature
SUEnableSystemProfiling

* UserDefaults only (private persistent state):

SUHasLaunchedBefore
SUSkippedVersion
SULastCheckTime
SULastProfileSubmitDate

This revision also corrects a compilation error from r285.
2008-08-17 13:06:33 -07:00
Andy Matuschak 5b38483981 Fixes 245723
Refactoring some code through new simplified "objectForKey" and "boolForKey" methods on SUHost which abstract the behavior of a user defaults preference defaulting to an info.plist setting. Thanks to Christiaan Hofman for the patch.
2008-08-17 12:35:41 -07:00
Andy Matuschak 46312a2d15 Fixes 258060
Fixed a couple memory leaks. Thanks to Christiaan Hofman for the patch.
2008-08-17 12:15:01 -07:00
Andy Matuschak 8a240f7c46 Fixes 258708
Returning the update alert's web view's default text size to 11. I swear I've done this like twice already!
2008-08-17 11:24:36 -07:00
Maarten Van Coile 17ca061cda Update Dutch to 1.5b5 2008-08-15 19:30:29 +02:00
Andy Matuschak 4da902b46c Fixes 251968
Sparkle now requires custom feed parameters to include a "displayKey" and "displayVersion" key. These will be displayed to the user in the initial permission dialog so that he knows what he's getting.
2008-08-10 23:49:30 -07:00
Andy Matuschak 7b39268171 No longer fragile-ly using class method singletons to get to the updater's delegate from within the update driver. Update drivers now have an initWithUpdater: method which I use instead. 2008-08-10 23:05:18 -07:00
Andy Matuschak 0343569cdc Fixes 256106
Sparkle will no longer break on nil XML nodes; that would occur when a node is commented out. Thanks to Christiaan Hofman for the patch.
2008-08-10 21:31:09 -07:00
Andy Matuschak 32a804e2ea Sparkle now uses Cocoa for user defaults for .apps and CF for user defaults for non-.apps. I think this is better than having .apps use both code paths. 2008-08-10 21:06:18 -07:00
Andy Matuschak 7ce078eb16 Fixes 356328
Sparkle will now clean up the hsot app's name and version before sending it as the user agent string; some non-ASCII characters were causing problems before.

Additionally, Sparkle now uses the bzr revision encoded in the framework's CFBundleVersion as the version it sends for itself in the user agent string; before this value was hardcoded, which was dumb.
2008-08-10 18:23:32 -07:00
Andy Matuschak f9dda21088 Fixes 255399
Giving clients a chance to make multiple preference changes before they take effect.
2008-08-10 17:32:40 -07:00
Andy Matuschak 00c5ae4a42 Changing localized release notes behavior slightly: release note keys which are not tagged with an xml:lang attribute are no longer assumed to be English. So if the user has a foreign language anywhere in their preferred languages list, even if English is higher, release notes keyed to "da" will be picked before release notes not keyed to any language. 2008-08-04 20:58:54 -07:00
Andy Matuschak d73d8333a1 Changing the behavior of the level of Sparkle's update window for the case of an LSUIElement. In that case, I think it's best for Sparkle to use NSFloatingWindowLevel, so that it's clear why the menu items are disabled (due to modality) when they click the menu icon again, thus focusing the update alert. We'll see how well this works. 2008-08-03 01:15:56 -07:00
Andy Matuschak 9c720fd6b7 Updated Russian localization courtesy Alexander Bykov. Thanks! 2008-08-03 00:40:28 -07:00
Andy Matuschak 7228235ce3 Fixes 253929
Fixed a workaround for using registered user defaults on Tiger that I managed to break. Go me!
2008-08-03 00:30:37 -07:00
Andy Matuschak 5684a1477e Fixes 253967
SUDSAVerifier now inherits from NSObject; missed that very important step! Oops!
2008-08-01 22:25:00 -07:00
Andy Matuschak 347dd73269 Fixes 253739
When checking to see if an app is an LSUIElement, Sparkle now checks the info dictionary of the main bundle instead of the info dictionary of the host bundle. That didn't work at all for plugins.
2008-08-01 00:12:44 -07:00
Andy Matuschak a14850458d Fixes 252986
Adds support for xml:lang to pick localized nodes in appcasts (for release notes, etc)
2008-07-31 23:59:12 -07:00
Andy Matuschak e249e3cfb6 Fixes 253187
Added a delegate method called pathToRelaunchForUpdater: which can be used for plugins to provide the path which should be used when relaunching the client after installing an update.
2008-07-30 23:37:56 -07:00
Andy Matuschak d1c0978ee5 As discussed in https://bugs.launchpad.net/sparkle/+bug/243884/comments/11, this patch makes it so that system profiling is only submitted to the server once per week. This will normalize clients' users: those which check daily won't count much more than those which check weekly. Thanks to David Smith for the patch. 2008-07-30 23:14:39 -07:00
David Smith e3226d3511 A cleaned up and tested version of the one-submit-per-week code 2008-07-30 01:30:11 -07:00
Andy Matuschak ae7c416f16 Actually added the Russian lprojes
Changed the fr_ca localization folder to fr_CA.
2008-07-30 00:40:36 -07:00
Andy Matuschak 1456fa0f75 Updated Russian localization (courtesy Alexander Bykov and Anton Sotkov), though it's still slightly out of date from the most recent string changes
Updated French localization (courtesy Ronald Leroux and Yann Ricquebourg)
The fr_ca localization is now linked to the French localization.
2008-07-30 00:36:45 -07:00
Andy Matuschak d6acd07d5c Fixes 252733
The status window's progress bar now animates even when indeterminate.
2008-07-29 23:58:57 -07:00
Andy Matuschak d8149e9eb0 Fixes 253145
Fixed a stupid typo in the +[SUUpdater updaterForBundle:] method.
2008-07-29 22:54:39 -07:00
Andy Matuschak d6557e21a0 Turning on SEPARATE_STRIP in hopes of fixing things for older versions of Xcode. 2008-07-29 08:31:37 -07:00
Andy Matuschak 3bccef8d22 Fixes 251963
SUAppcastItem now copies the properties dictionary it's given for safety.
2008-07-28 21:55:07 -07:00
Andy Matuschak a27e8316fe Made the aggressive stripping only apply to the framework, since some people were having trouble with relaunch with that configuration. 2008-07-28 21:14:13 -07:00
Andy Matuschak b419948c8d Forgot to tell the Sparkle-GC configuration about Sparkle.pch. 2008-07-25 08:53:57 -07:00
Andy Matuschak 211555639d Removed potentially dangerous KVO magic. 2008-07-25 08:46:46 -07:00
Andy Matuschak 46125abdeb Updated French localization courtesy Ronald Leroux
Updated German localization courtesy Sven-S. Porst
2008-07-24 21:10:22 -07:00
Andy Matuschak 69e4e7cc49 Last few bits from the rearchitecting branch... 2008-07-24 20:49:48 -07:00
Andy Matuschak fe9dedb9ad 4300+-line merge! This will probably break the world.
Merging in rearchitecting work done in lp:~andymatuschak/sparkle/rearchitecting. There are some MAJOR compatibility issues you'll notice if you do most non-default things with Sparkle, so please read the commit log. Delegate methods are changed and most API is private now, to summarize.
2008-07-24 20:44:27 -07:00
Andy Matuschak 47e6a96800 Stripping framework thoroughly after release builds. This will probably bite me in the ass when I get some crash report and its contents are totally useless. 2008-07-24 20:36:24 -07:00
Andy Matuschak f42fb51952 Made automaticallyChecksForUpdates and updateCheckInterval KVO-compliant. 2008-07-24 20:15:04 -07:00
Andy Matuschak 1aea1b699a The Sparkle preference keys are now declared private / deprecated / allowed to change without me receiving hate email. However! SUUpdater is now KVC-compliant for:
automaticallyCheckForUpdates
updateCheckInterval
feedURL
2008-07-24 20:11:09 -07:00
Andy Matuschak e769ba58cc Reordered Sparkle.h to emphasize SUUpdater.h
Removed reference to the RSS class from SUAppcast.h
2008-07-24 19:35:29 -07:00
Andy Matuschak f815eec2c0 Fixes 243884
Made Sparkle.h no longer a massive multi-headed abomination: now only SUAppcastItem, SUAppcast and SUUpdater (and SUVersionComparisonProtocol because it's part of the delegate protocol) are public.

COMPATIBILITY ISSUE:
This means there's no longer a public SUProbingUpdateDriver or a checkForUpdatesWithDriver: method. Now use checkForUpdateInformation. I may change that API before release, though. I'm thinking it might be better to give the delegate the opportunity to reject a potential update instead: then you'd just call checkForUpdatesInBackground and override that delegate method to always return NO. We'll see.
2008-07-23 23:40:01 -07:00
Andy Matuschak de9be8b481 Fixes 244428
Removed all Cocoa categories from Sparkle by integrating things into other classes or making categories on existing Sparkle classes. Whoo!
2008-07-23 22:49:47 -07:00
Andy Matuschak 7454b8f2f6 Small changes for clarity. 2008-07-23 21:42:32 -07:00
Andy Matuschak b4c7dbe478 Added a guard to the piped unarchiver to fail more gracefully for bad filenames of very short length. 2008-07-23 20:54:10 -07:00
Andy Matuschak e14727dcc3 More reliable bzr revision labeling script (shouldn't break the compilation). 2008-07-23 20:41:49 -07:00
Andy Matuschak ac4e4e405b Fixes 245991
COMPATIBILITY ISSUE:
Changed updatePreferencesChanged to resetUpdateCycle to give better semantics for bundle-ish apps which need to start the update cycle manually since applicationDidFinishLaunching: won't do the right thing.
2008-07-23 20:27:01 -07:00
Andy Matuschak 898216ac9f Final fix for 246469 (I hope). Fixed a mind-bogglingly stupid typo which Xcode let compile for some reason. 2008-07-23 12:36:59 -07:00
Andy Matuschak c42e3a3f47 Fixed 251010
Fixes from Matt Stevens:
"For background applications (menu bar, completely UI-less, etc) there are a couple of issues with Sparkle notifications:

- When prompts such as the initial prompt to enable update checking are displayed they can be hidden behind other windows since the background app is not in focus. This can cause problems, as these prompts run modally and can stop the application from functioning without the user knowing why.

- If the update notification window is displayed and the user clicks away to another application, the window disappears and there is no way to get it back since there is no other UI to cause the app to activate. In this case the update should probably operate as a standard window since it is effectively operating as the application's UI."
2008-07-22 22:36:09 -07:00
Matt Stevens cec9166956 Improved notification handling for otherwise UI-less background applications. 2008-07-22 20:24:12 -06:00
Andy Matuschak 675c66ff9d Fixes 250170
Sparkle now remembers to call the delegate's didFindValidUpdate method when using a UI-based update controller. Thanks, Stefan Schimanski!
2008-07-21 23:40:52 -07:00
Andy Matuschak 962a110b16 Merged in the branch moving Sparkle back to literal path extensions from UTIs. 2008-07-21 23:18:21 -07:00
Andy Matuschak 405410b8c8 Updates to the French localization courtesy Ronald Leroux. 2008-07-21 23:16:11 -07:00
Andy Matuschak 32e014af06 Actually added the Swedish localization to the Xcode project. Oops. 2008-07-21 21:07:06 -07:00
Andy Matuschak 0af86bbb9d Hopefully actually fixing 246469: it seems that while Cocoa documents its use of gzip as having the MIME type "application/gzip", it actually uses (what it's supposed to) "application/x-gzip". 2008-07-21 20:55:04 -07:00
Andy Matuschak a31dc3a102 Fixes BOOL user defaults lookup for registered defaults on Tiger. 2008-07-17 21:19:07 -07:00
Andy Matuschak 7b212ea7fd Fixes 247749
SULocalizedString now uses a hardcoded identifier for Sparkle instead of trying to detect it with bundleForClass:[self class]. A little more robust, a little more brittle.
2008-07-17 00:27:17 -07:00
Andy Matuschak b3f3944495 Fixes 244857
Made a first crack at redifining the SUUpdater delegate protocol. Still not sure about a couple things, so please don't change your delegate methods to conform until this gets merged into trunk.

Also made the SUUpdateDrivers not have the updater's delegate as their delegate (that was really icky). Now they're just coupled with the SUUpdater, which is icky as well, but less icky, at least.
2008-07-16 23:51:39 -07:00
Andy Matuschak 58a05e2ee7 Fixes 243533 (for real this time, I hope)
I've undone all the UTI nonsense: I don't see any reason to use it if the underlying frameworks are just going to do dumber path extension comparison that what I'm already doing. I've switched back to the tried-and-true method.

I also made SUUnarchiver* path-based instead of NSURL-based because I realized that the latter didn't make any sense given that we're only unarchiving local files.
2008-07-16 22:48:10 -07:00
Andy Matuschak 3146ffb8e1 Fixes 248929, 244738
Removed NSWorkspace+RBAdditions: we're now checking if the volume is read-only instead of specifically whether it's a disk image.

This also means the warning string changed. Sorry, localizers!
2008-07-16 22:15:29 -07:00
Andy Matuschak b815ce9db4 Making *really* sure that "checking for updates..." window gets closed in all cases. 2008-07-16 21:14:43 -07:00
Andy Matuschak b14aa16a23 Merging in Swedish localization courtesy Daniel Bergman. Thanks! 2008-07-16 20:17:04 -07:00
Andy Matuschak 4397d85727 Merging crazy refactoring branch up to trunk. 2008-07-15 23:30:37 -07:00
Andy Matuschak 98832c4914 Beginnings of insane SUHost-based refactoring to get rid of NSBundle+Sparkle. More super-unstable refactorings to come... 2008-07-15 23:26:06 -07:00
Andy Matuschak 720269b118 Fixes 248581
Now putting the license in the resources folder of the built Sparkle.framework.
2008-07-15 21:53:13 -07:00
Andy Matuschak c9bd13213b Fixes 246469
This should fix the DSA-signing-on-tar-gzs issue. Sparkle now doesn't let NSURLDownload extract .gzips for us, which was making the data being verified different from the data being signed.
2008-07-15 21:36:48 -07:00
Andy Matuschak 5fdddaeede Slight project-y tweaks: now only building the host arch for development. 2008-07-15 21:00:07 -07:00
Andy Matuschak 8570539aab Hopefully finally fixing 245744; it wasn't fixed by the previous revision that claimed it was. There was a tricksy subclassing nuance that eluded me. 2008-07-15 20:57:57 -07:00
Andy Matuschak f4c6738793 Added a comment to strings appearing in the status window noting that since the status window nib is unlocalized, localizers should be careful not to make their strings too long.
Changed a French status string to fit in the status window.
2008-07-09 19:47:58 -07:00
Andy Matuschak e018ee98d3 Added Italian localization courtesy Michele Longhi. Thanks, Michele! 2008-07-09 00:33:33 -07:00
Andy Matuschak 95aabd561b Fixed the old-style em-dash in the French localization; fixed localization handling for B/KB/MB/GB by moving the code in the NSNumber category (which wouldn't work because it couldn't find the Sparkle localization table) to SUUIBasedUpdateDriver. 2008-07-08 22:24:16 -07:00
Andy Matuschak a1b295c2c9 Center the "checking for updates..." window when summoned. 2008-07-08 19:40:26 -07:00
Andy Matuschak bc7aff3f11 If Sparkle can't parse one item, it no longer fails the entire appcast. 2008-07-08 19:39:00 -07:00
Andy Matuschak dc249c1ec5 Fixes 246805
Sparkle no longer calls it a critical failure if it can't read a file on a DMG (like for .Trashes).
2008-07-08 19:37:16 -07:00
Andy Matuschak 660228fb0e Fixes 245744
Fixed a bug where the user-initiated updater could abort through abnormal means, making the "checking for updates..." window never able to go away.
2008-07-05 14:08:31 -07:00
Daniel Bergman 4e8e3b9774 Let there be nibs 2008-06-06 02:13:57 +02:00
Daniel Bergman 32129634ee Initial import, no nibs 2008-06-06 02:02:54 +02:00
401 changed files with 83389 additions and 4314 deletions

No files matched your search

-4
View File
@@ -1,4 +0,0 @@
*.pbxuser
.DS_Store
*.perspective*
.svn
+18
View File
@@ -0,0 +1,18 @@
# Xcode
build/*
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
*.xcworkspace
!default.xcworkspace
xcuserdata/
profile
*.moved-aside
## Ignore incredibly annoying .DS_Store files
.DS_Store
@@ -0,0 +1,8 @@
// BinaryDelta tool only
PRODUCT_NAME = BinaryDelta
GCC_PREFIX_HEADER =
MACOSX_DEPLOYMENT_TARGET[arch=i386] = 10.5
MACOSX_DEPLOYMENT_TARGET[arch=ppc64] = 10.5
MACOSX_DEPLOYMENT_TARGET[arch=ppc] = 10.5
MACOSX_DEPLOYMENT_TARGET[arch=x86_64] = 10.5
@@ -0,0 +1,5 @@
#include "ConfigCommon.xcconfig"
#include "ConfigCommonDebug.xcconfig"
#include "ConfigBinaryDelta.xcconfig"
OTHER_CFLAGS = -DDEBUG
@@ -0,0 +1,3 @@
#include "ConfigCommon.xcconfig"
#include "ConfigCommonRelease.xcconfig"
#include "ConfigBinaryDelta.xcconfig"
+19 -5
View File
@@ -3,17 +3,20 @@
PREBINDING = NO
ZERO_LINK = NO
CURRENT_PROJECT_VERSION = 1.5
SDKROOT = $(DEVELOPER_SDK_DIR)/MacOSX10.5.sdk
MACOSX_DEPLOYMENT_TARGET[arch=ppc] = 10.3
SDKROOT = macosx10.9
MACOSX_DEPLOYMENT_TARGET[arch=ppc] = 10.4
MACOSX_DEPLOYMENT_TARGET[arch=ppc64] = 10.5
MACOSX_DEPLOYMENT_TARGET[arch=i386] = 10.4
MACOSX_DEPLOYMENT_TARGET[arch=x86_64] = 10.5
MACOSX_DEPLOYMENT_TARGET[arch=x86_64] = 10.7
GCC_C_LANGUAGE_STANDARD = c99
GCC_ENABLE_OBJC_EXCEPTIONS = YES
GCC_DEBUGGING_SYMBOLS = full
GCC_PRECOMPILE_PREFIX_HEADER = YES
GCC_PREFIX_HEADER = $(SDKROOT)/System/Library/Frameworks/Cocoa.framework/Headers/Cocoa.h
GCC_FAST_OBJC_DISPATCH = YES
GCC_FAST_OBJC_DISPATCH[arch=ppc] = NO // requires 10.4
GCC_ENABLE_PASCAL_STRINGS = NO
GCC_VERSION = com.apple.compilers.llvm.clang.1_0
CLANG_LINK_OBJC_RUNTIME = NO
// Enable warnings
GCC_WARN_CHECK_SWITCH_STATEMENTS = YES
@@ -35,4 +38,15 @@ GCC_WARN_UNKNOWN_PRAGMAS = YES
GCC_WARN_UNUSED_VARIABLE = YES
GCC_WARN_ABOUT_DEPRECATED_FUNCTIONS = YES
GCC_WARN_ABOUT_INVALID_OFFSETOF_MACRO = YES
WARNING_CFLAGS = -Wall
GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES
GCC_WARN_HIDDEN_VIRTUAL_FUNCTIONS = YES
GCC_WARN_ABOUT_INVALID_OFFSETOF_MACRO = YES
GCC_WARN_UNUSED_FUNCTION = YES
GCC_WARN_UNUSED_LABEL = YES
GCC_WARN_UNUSED_VALUE = YES
GCC_WARN_UNUSED_PARAMETER = YES
GCC_WARN_ABOUT_MISSING_FIELD_INITIALIZERS = YES
GCC_WARN_UNDECLARED_SELECTOR = YES
COMMON_WARNING_FLAGS = -Wall -Wno-unused-parameter -Wundef -Wendif-labels -Wpointer-arith -Wcast-align -Wwrite-strings -Wmissing-format-attribute -Wpacked -Wredundant-decls -Winline -Wdisabled-optimization -Winvalid-pch
WARNING_CFLAGS = $(COMMON_WARNING_FLAGS)
+5 -2
View File
@@ -3,6 +3,9 @@
GCC_OPTIMIZATION_LEVEL = 0
DEBUG_INFORMATION_FORMAT = dwarf
GCC_GENERATE_DEBUGGING_SYMBOLS = YES
SPARKLE_EXTRA_DEBUG = -DDEBUG -fstack-protector -D_FORTIFY_SOURCE=2
SPARKLE_EXTRA_DEBUG_10_5_ONLY = -fstack-protector -D_FORTIFY_SOURCE=2
SPARKLE_EXTRA_DEBUG = -DDEBUG
OTHER_CFLAGS = $(SPARKLE_EXTRA_DEBUG)
ARCHS = $(NATIVE_ARCH_ACTUAL)
CODE_SIGN_IDENTITY = Mac Developer
// Add $(SPARKLE_EXTRA_DEBUG_10_5_ONLY) to SPARKLE_EXTRA_DEBUG if your deployment is 10.5 or greater.
@@ -0,0 +1,4 @@
// Common
ARCHS = x86_64
VALID_ARCHS = x86_64
@@ -0,0 +1,4 @@
// Common
ARCHS = ppc i386 x86_64
+2 -2
View File
@@ -2,8 +2,8 @@
GCC_OPTIMIZATION_LEVEL = s
DEBUG_INFORMATION_FORMAT = dwarf-with-dsym
GCC_GENERATE_DEBUGGING_SYMBOLS = NO
DEAD_CODE_STRIPPING = YES
GCC_TREAT_WARNINGS_AS_ERRORS = YES
GCC_WARN_UNINITIALIZED_AUTOS = YES
ARCHS = ppc i386 x86_64
WARNING_CFLAGS = $(COMMON_WARNING_FLAGS) -Wno-deprecated-declarations
CODE_SIGN_IDENTITY = Developer ID Application
+4 -4
View File
@@ -1,10 +1,10 @@
// Framework only
INSTALL_PATH = @executable_path/../Frameworks
DYLIB_COMPATIBILITY_VERSION = 1.5
DYLIB_CURRENT_VERSION = 1.5
INSTALL_PATH = @rpath
DYLIB_COMPATIBILITY_VERSION = 2.0
DYLIB_CURRENT_VERSION = 2.1.1
PRODUCT_NAME = Sparkle
WRAPPER_EXTENSION = framework
OTHER_LDFLAGS = -lcrypto
FRAMEWORK_VERSION = A
INFOPLIST_FILE = Info.plist
GCC_PREFIX_HEADER = Sparkle.pch
+1 -1
View File
@@ -2,4 +2,4 @@
#include "ConfigCommonDebug.xcconfig"
#include "ConfigFramework.xcconfig"
OTHER_CFLAGS = -fsingle-precision-constant -DDEBUG
OTHER_CFLAGS = -DDEBUG
@@ -1,3 +1,9 @@
#include "ConfigCommon.xcconfig"
#include "ConfigCommonRelease.xcconfig"
#include "ConfigFramework.xcconfig"
STRIP_INSTALLED_PRODUCT = YES
DEPLOYMENT_POSTPROCESSING = YES
STRIPFLAGS = -u -r
STRIP_STYLE = non-global
SEPARATE_STRIP = YES
+2 -1
View File
@@ -1,3 +1,4 @@
// Relaunch Tool only
PRODUCT_NAME = relaunch
PRODUCT_NAME = finish_installation
SKIP_INSTALL = YES
+1 -1
View File
@@ -2,4 +2,4 @@
#include "ConfigCommonDebug.xcconfig"
#include "ConfigRelaunch.xcconfig"
OTHER_CFLAGS = -fsingle-precision-constant -DDEBUG
OTHER_CFLAGS = -DDEBUG
+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
@@ -3,3 +3,4 @@
INFOPLIST_FILE = Test Application/Test Application-Info.plist
PRODUCT_NAME = Sparkle Test App
WRAPPER_EXTENSION = app
LD_RUNPATH_SEARCH_PATHS = @loader_path/../Frameworks
+1 -1
View File
@@ -2,4 +2,4 @@
#include "ConfigCommonDebug.xcconfig"
#include "ConfigTestApp.xcconfig"
OTHER_CFLAGS = -fsingle-precision-constant -DDEBUG
OTHER_CFLAGS = -DDEBUG
@@ -0,0 +1,3 @@
#include "ConfigTestAppRelease.xcconfig"
GCC_ENABLE_OBJC_GC = required
+11
View File
@@ -0,0 +1,11 @@
// Unit Test only
INFOPLIST_FILE = Tests/Sparkle Unit Tests-Info.plist
OTHER_LDFLAGS = -framework Cocoa -framework SenTestingKit
PRODUCT_NAME = Sparkle Unit Tests
WRAPPER_EXTENSION = octest
FRAMEWORK_SEARCH_PATHS = $(DEVELOPER_LIBRARY_DIR)/Frameworks
GCC_PREFIX_HEADER = $(SYSTEM_LIBRARY_DIR)/Frameworks/Cocoa.framework/Headers/Cocoa.h
GCC_PRECOMPILE_PREFIX_HEADER = YES
SDKROOT = macosx10.7
MACOSX_DEPLOYMENT_TARGET = 10.7
@@ -0,0 +1,3 @@
#include "ConfigCommon.xcconfig"
#include "ConfigCommonDebug.xcconfig"
#include "ConfigUnitTest.xcconfig"
@@ -0,0 +1,3 @@
#include "ConfigCommon.xcconfig"
#include "ConfigCommonRelease.xcconfig"
#include "ConfigUnitTest.xcconfig"
@@ -0,0 +1,3 @@
#include "ConfigUnitTestRelease.xcconfig"
GCC_ENABLE_OBJC_GC = required
+38
View File
@@ -0,0 +1,38 @@
//
// 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 SUAppcastDelegate DM_SUAppcastDelegate
#define SUUpdaterDelegate_DevMateInteraction DM_SUUpdaterDelegate_DevMateInteraction
#define SUUpdaterDelegateInformalProtocol DM_SUUpdaterDelegateInformalProtocol
#define SUVersionComparison DM_SUVersionComparison
#define SUVersionDisplay DM_SUVersionDisplay
#import <DevMateSparkle/SUUpdater.h>
#import <DevMateSparkle/SUUpdaterQueue.h>
#import <DevMateSparkle/SUAppcast.h>
#import <DevMateSparkle/SUAppcastItem.h>
#import <DevMateSparkle/SUVersionComparisonProtocol.h>
#import <DevMateSparkle/SUVersionDisplayProtocol.h>
#endif // USED_CUSTOM_SPARKLE_FRAMEWORK
#endif // Sparkle_DevMateSparkle_h
+54
View File
@@ -0,0 +1,54 @@
//
// DevMateSparkle.pch
// Sparkle
//
// Created by Dmytro Tretiakov on 10/1/14.
//
//
#define SPARKLE_MAIN_CLASS @"DM_SUUpdater"
#define SUUpdater DM_SUUpdater
#define SUUpdaterQueue DM_SUUpdaterQueue
#define SUAppcast DM_SUAppcast
#define SUAppcastItem DM_SUAppcastItem
#define SUAppcastDelegate DM_SUAppcastDelegate
#define SUUpdaterDelegate_DevMateInteraction DM_SUUpdaterDelegate_DevMateInteraction
#define SUUpdaterDelegateInformalProtocol DM_SUUpdaterDelegateInformalProtocol
#define SUVersionComparison DM_SUVersionComparison
#define SUVersionDisplay DM_SUVersionDisplay
#define SUPackageInstaller DM_SUPackageInstaller
#define SUDSAVerifier DM_SUDSAVerifier
#define SUUpdateAlert DM_SUUpdateAlert
#define SUUIBasedUpdateDriver DM_SUUIBasedUpdateDriver
#define SUPasswordPrompt DM_SUPasswordPrompt
#define SUStandardVersionComparator DM_SUStandardVersionComparator
#define SUSystemProfiler DM_SUSystemProfiler
#define SUXPCInstaller DM_SUXPCInstaller
#define SUXPCURLDownload DM_SUXPCURLDownload
#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 NTSynchronousTask DM_NTSynchronousTask
#define SUUpdaterWorking DM_SUUpdater // Used in SUUpdaterLoader.m file
#define SUUpdaterLoader DM_SUUpdaterLoader
#import "Sparkle.pch"
@@ -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>
@@ -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
@@ -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 */
BIN
View File
Binary file not shown.
+2 -2
View File
@@ -19,9 +19,9 @@
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1.5</string>
<string>${DYLIB_CURRENT_VERSION}</string>
<key>CFBundleShortVersionString</key>
<string>1.5 Beta (bzr)</string>
<string>${DYLIB_CURRENT_VERSION}</string>
<key>NSPrincipalClass</key>
<string></string>
</dict>
@@ -0,0 +1,39 @@
//
// SUInstallServiceConstants.h
// Sparkle
//
// Created by Dmytro Tretiakov on 8/2/13.
//
//
#ifndef Sparkle_SUInstallServiceConstants_h
#define Sparkle_SUInstallServiceConstants_h
typedef enum _SUInstallSerciveTask
{
SUInstallServiceTaskCopyPath = 1LL,
SUInstallServiceTaskAuthCopyPath = 2LL,
SUInstallServiceTaskLaunchTask = 3LL
} SUInstallServiceTask;
const char * SUInstallServiceTaskTypeKey = "task_type"; // int64_t
// SUInstallServiceTaskCopyPath & SUInstallServiceTaskAuthCopyPath keys
const char * SUInstallServiceSourcePathKey = "source_path"; // c-string
const char * SUInstallServiceDestinationPathKey = "destination_path"; // c-string
const char * SUInstallServiceTempNameKey = "tmp_name"; // c-string
// SUInstallServiceTaskLaunchTask keys
const char * SUInstallServiceLaunchTaksPathKey = "launch_task_path";
const char * SUInstallServiceLaunchTaskArgumentsKey = "launch_task_arguments"; // xpc_array of c-strings
const char * SUInstallServiceLaunchTaskEnvironmentKey = "launch_task_environment"; // xpc_dictionary with keys and values of c-strings
const char * SUInstallServiceLaunchTaskCurrentDirKey = "launch_task_cur_dir"; // c-string
const char * SUInstallServiceLaunchTaskInputDataKey = "launch_task_input_data"; // xpc_data
const char * SUInstallServiceLaunchTaskReplyImmediatelyKey = "launch_task_reply_immediately"; // bool
// Reply keys
const char * SUInstallServiceErrorCodeKey = "error_code"; // int64_t
const char * SUInstallServiceErrorLocalizedDescriptionKey = "error_localized_description"; // c-string
const char * SUInstallServiceLaunchTaskOutputDataKey = "launch_task_output_data"; // xpc_data
#endif
+29
View File
@@ -0,0 +1,29 @@
//
// 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 temporaryName:(NSString *)tmp error:(NSError **)outError;
+ (BOOL)copyPathContent:(NSString *)src toDirectory:(NSString *)dstDir error:(NSError **)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
waitForTaskResult:(BOOL)waitForTaskResult
waitUntilDone:(BOOL)waitUntilDone // for sync/async logic
completionHandler:(void (^)(int result, NSData *outputData))completionHandler;
@end
+268
View File
@@ -0,0 +1,268 @@
//
// 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"
@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 temporaryName:(NSString *)tmp error:(NSError **)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]);
if (tmp)
xpc_dictionary_set_string(message, SUInstallServiceTempNameKey, [tmp UTF8String]);
__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);
[error autorelease];
if (nil != error && NULL != outError)
{
*outError = error;
}
return (nil == error);
}
+ (BOOL)copyPathContent:(NSString *)src toDirectory:(NSString *)dstDir error:(NSError **)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);
[error autorelease];
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
waitForTaskResult:NO
waitUntilDone:YES
completionHandler:nil];
}
+ (void)launchTaskWithPath:(NSString *)launchPath
arguments:(NSArray *)arguments
environment:(NSDictionary *)environment
currentDirectoryPath:(NSString *)currentDirPath
inputData:(NSData *)inputData
waitForTaskResult:(BOOL)waitForTaskResult
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 (NSString *argument in arguments)
{
if (![argument isKindOfClass:[NSString class]])
argument = [argument description];
xpc_array_set_string(array, XPC_ARRAY_APPEND, [argument 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 *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]);
}
xpc_dictionary_set_bool(message, SUInstallServiceLaunchTaskReplyImmediatelyKey, waitForTaskResult ? false : true);
__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 (waitUntilDone)
{
while (NO == xpcTaskDidReply)
{
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.2]];
}
}
}
@end
@@ -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>
+377
View File
@@ -0,0 +1,377 @@
//
// 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"
#import "SULog.h"
#import "SUConstants.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);
const char *tmp = xpc_dictionary_get_string(message, SUInstallServiceTempNameKey);
NSFileManager *manager = [NSFileManager defaultManager];
NSString *relaunchPathToCopy = src ? [manager stringWithFileSystemRepresentation:src length:strlen(src)] : nil;
NSString *targetPath = dst ? [manager stringWithFileSystemRepresentation:dst length:strlen(dst)] : nil;
NSString *temporaryName = tmp ? [NSString stringWithUTF8String:tmp] : nil;
NSError *error = nil;
BOOL result = [SUPlainInstaller copyPathWithAuthentication:relaunchPathToCopy overPath:targetPath temporaryName:temporaryName 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] autorelease];
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] retain];
isTaskRunning = NO;
}];
id object2 = [notificationCenter addObserverForName:NSTaskDidTerminateNotification
object:task
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification *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 release];
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.
SUInstallServiceTask task = (SUInstallServiceTask)xpc_dictionary_get_int64(event, SUInstallServiceTaskTypeKey);
NSLog(@"XPC Installer: should start task with id = %lld", (int64_t)task);
xpc_object_t reply = NULL;
NSAutoreleasePool *localPool = [[NSAutoreleasePool alloc] init];
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", (int64_t)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;
}
}
[localPool release];
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 argc, const char *argv[])
{
xpc_main(event_handler);
return 0;
}
@@ -0,0 +1,11 @@
//
// install_service.pch
// Sparkle
//
// Created by Dmytro Tretiakov on 4/25/14.
//
//
#define SPARKLE_BUNDLE [NSBundle mainBundle]
#define SULocalizedString(key,comment) NSLocalizedStringFromTableInBundle(key, @"Sparkle", SPARKLE_BUNDLE, comment)
+32 -1
View File
@@ -4,4 +4,35 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
=================
EXTERNAL LICENSES
=================
License for bspatch.c and bsdiff.c, from bsdiff 4.3 (<http://www.daemonology.net/bsdiff/>:
/*-
* Copyright 2003-2005 Colin Percival
* All rights reserved
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted providing that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
-59
View File
@@ -1,59 +0,0 @@
//
// NSBundle+SUAdditions.h
// Sparkle
//
// Created by Andy Matuschak on 12/21/07.
// Copyright 2007 Andy Matuschak. All rights reserved.
//
#ifndef NSBUNDLE_PLUS_ADDITIONS_H
#define NSBUNDLE_PLUS_ADDITIONS_H
#import <Cocoa/Cocoa.h>
@interface NSBundle (SUAdditions)
/*!
@method
@abstract Returns a name for the bundle suitable for display to the user.
@discussion This is performed by asking NSFileManager for the display name of the bundle.
*/
- (NSString *)name;
/*!
@method
@abstract Returns the current internal version of the bundle.
@discussion This uses the CFBundleVersion info value. This string is not appropriate for display to users: use -displayVersion instead.
*/
- (NSString *)version;
/*!
@method
@abstract Returns the bundle's version, suitable for display to the user.
@discussion If the CFBundleShortVersionString is available and different from the CFBundleVersion, this looks like CFBundleShortVersionString (CFBundleVersion). If the version strings are the same or CFBundleShortVersionString is not defined, this is equivalent to -version.
*/
- (NSString *)displayVersion;
/*!
@method
@abstract Returns a suitable icon for this bundle.
@discussion Uses the CFBundleIconFile icon if defined; otherwise, uses the default application icon.
*/
- (NSImage *)icon;
/*!
@method
@abstract Returns whether the application is running from a disk image.
*/
- (BOOL)isRunningFromDiskImage;
/*!
@method
@abstract Returns a profile of the users system useful for statistical purposes.
@discussion Returns an array of dictionaries; each dictionary represents a piece of data and has keys "key", "visibleKey", "value", and "visibleValue".
*/
- (NSArray *)systemProfile;
- (NSString *)publicDSAKey;
@end
#endif
-89
View File
@@ -1,89 +0,0 @@
//
// NSBundle+SUAdditions.m
// Sparkle
//
// Created by Andy Matuschak on 12/21/07.
// Copyright 2007 Andy Matuschak. All rights reserved.
//
#import "Sparkle.h"
#import "NSBundle+SUAdditions.h"
#ifndef NSAppKitVersionNumber10_4
#define NSAppKitVersionNumber10_4 824
#endif
@implementation NSBundle (SUAdditions)
- (NSString *)name
{
NSString *name = [self objectForInfoDictionaryKey:@"CFBundleDisplayName"];
if (name) return name;
name = [self objectForInfoDictionaryKey:@"CFBundleName"];
if (name) return name;
return [[[NSFileManager defaultManager] displayNameAtPath:[self bundlePath]] stringByDeletingPathExtension];
}
- (NSString *)version
{
return [self objectForInfoDictionaryKey:@"CFBundleVersion"];
}
- (NSString *)displayVersion
{
NSString *shortVersionString = [self objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
if (shortVersionString)
return shortVersionString;
else
return [self version]; // Fall back on the normal version string.
}
- (NSImage *)icon
{
// Cache the application icon.
NSString *iconPath = [self pathForResource:[self objectForInfoDictionaryKey:@"CFBundleIconFile"] ofType:@"icns"];
// According to the OS X docs, "CFBundleIconFile - This key identifies the file containing
// the icon for the bundle. The filename you specify does not need to include the .icns
// extension, although it may."
//
// However, if it *does* include the '.icns' the above method fails (tested on OS X 10.3.9) so we'll also try:
if (!iconPath)
iconPath = [self pathForResource:[self objectForInfoDictionaryKey:@"CFBundleIconFile"] ofType: nil];
NSImage *icon = [[[NSImage alloc] initWithContentsOfFile:iconPath] autorelease];
// Use a default icon if none is defined.
if (!icon) { icon = [NSImage imageNamed:@"NSDefaultApplicationIcon"]; }
return icon;
}
- (BOOL)isRunningFromDiskImage
{
// This check causes crashes on 10.3; for now, we'll just skip it.
if (floor(NSAppKitVersionNumber) < NSAppKitVersionNumber10_4)
return NO;
NSDictionary *pathProperties = [[NSWorkspace sharedWorkspace] propertiesForPath:[self bundlePath]];
BOOL isDiskImage = [pathProperties objectForKey:NSWorkspace_RBimagefilepath] != nil;
BOOL isFileVault = [[pathProperties objectForKey:NSWorkspace_RBmntonname] hasPrefix:@"/Users/"];
return isDiskImage && !isFileVault;
}
- (NSString *)publicDSAKey
{
// Maybe the key is just a string in the Info.plist.
NSString *key = [self objectForInfoDictionaryKey:SUPublicDSAKeyKey];
if (key) { return key; }
// More likely, we've got a reference to a Resources file by filename:
NSString *keyFilename = [self objectForInfoDictionaryKey:SUPublicDSAKeyFileKey];
if (!keyFilename) { return nil; }
return [NSString stringWithContentsOfFile:[self pathForResource:keyFilename ofType:nil]];
}
- (NSArray *)systemProfile
{
return [[SUSystemProfiler sharedSystemProfiler] systemProfileArrayForHostBundle:self];
}
@end
-18
View File
@@ -1,18 +0,0 @@
//
// NSFileManager+Aliases.h
// Sparkle
//
// Created by Andy Matuschak on 2/4/08.
// Copyright 2008 Andy Matuschak. All rights reserved.
//
#ifndef NSFILEMANAGER_PLUS_ALIASES_H
#define NSFILEMANAGER_PLUS_ALIASES_H
#import <Cocoa/Cocoa.h>
@interface NSFileManager (SUAliases)
- (BOOL)isAliasFolderAtPath:(NSString *)path;
@end
#endif
-33
View File
@@ -1,33 +0,0 @@
//
// NSFileManager+Aliases.m
// Sparkle
//
// Created by Andy Matuschak on 2/4/08.
// Copyright 2008 Andy Matuschak. All rights reserved.
//
#import "NSFileManager+Aliases.h"
@implementation NSFileManager (SUAliases)
- (BOOL)isAliasFolderAtPath:(NSString *)path
{
FSRef fileRef;
OSStatus err = noErr;
Boolean aliasFileFlag, folderFlag;
NSURL *fileURL = [NSURL fileURLWithPath:path];
if (FALSE == CFURLGetFSRef((CFURLRef)fileURL, &fileRef))
err = coreFoundationUnknownErr;
if (noErr == err)
err = FSIsAliasFile(&fileRef, &aliasFileFlag, &folderFlag);
if (noErr == err)
return (BOOL)(aliasFileFlag && folderFlag);
else
return NO;
}
@end
-16
View File
@@ -1,16 +0,0 @@
//
// NSFileManager+Authentication.m
// Sparkle
//
// Created by Andy Matuschak on 3/9/06.
// Copyright 2006 Andy Matuschak. All rights reserved.
//
#ifndef NSFILEMANAGER_PLUS_AUTHENTICATION_H
#define NSFILEMANAGER_PLUS_AUTHENTICATION_H
@interface NSFileManager (SUAuthenticationAdditions)
- (BOOL)copyPathWithAuthentication:(NSString *)src overPath:(NSString *)dst error:(NSError **)error;
@end
#endif
-249
View File
@@ -1,249 +0,0 @@
//
// NSFileManager+Authentication.m
// Sparkle
//
// Created by Andy Matuschak on 3/9/06.
// Copyright 2006 Andy Matuschak. All rights reserved.
//
// This code based on generous contribution from Allan Odgaard. Thanks, Allan!
#import "Sparkle.h"
#import "NSFileManager+Authentication.h"
#import <Security/Security.h>
#import <sys/stat.h>
#import <sys/wait.h>
#import <dirent.h>
#import <unistd.h>
#import "NSFileManager+ExtendedAttributes.h"
static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authorization, const char* executablePath, AuthorizationFlags options, const char* const* arguments)
{
sig_t oldSigChildHandler = signal(SIGCHLD, SIG_DFL);
BOOL returnValue = YES;
if (AuthorizationExecuteWithPrivileges(authorization, executablePath, options, (char* const*)arguments, NULL) == errAuthorizationSuccess)
{
int status;
pid_t pid = wait(&status);
if (pid == -1 || !WIFEXITED(status) || WEXITSTATUS(status) != 0)
returnValue = NO;
}
else
returnValue = NO;
signal(SIGCHLD, oldSigChildHandler);
return returnValue;
}
@implementation NSFileManager (SUAuthenticationAdditions)
- (BOOL)currentUserOwnsPath:(NSString *)oPath
{
const char *path = [oPath fileSystemRepresentation];
uid_t uid = getuid();
bool res = false;
struct stat sb;
if(stat(path, &sb) == 0)
{
if(sb.st_uid == uid)
{
res = true;
if(sb.st_mode & S_IFDIR)
{
DIR* dir = opendir(path);
struct dirent* entry = NULL;
while(res && (entry = readdir(dir)))
{
if(strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
size_t len = strlen(path) + 1 + entry->d_namlen + 1;
char descend[len];
strlcpy(descend, path, len);
strlcat(descend, "/", len);
strlcat(descend, entry->d_name, len);
NSString* newPath = [[NSFileManager defaultManager] stringWithFileSystemRepresentation:descend length:strlen(descend)];
res = [self currentUserOwnsPath:newPath];
}
closedir(dir);
}
}
}
return res;
}
- (NSString *)_temporaryCopyNameForPath:(NSString *)path
{
// Let's try to read the version number so the filename will be more meaningful.
NSString *postFix;
NSBundle *bundle;
if ((bundle = [NSBundle bundleWithPath:path]))
{
// We'll clean it up a little for safety.
// The cast is necessary because of a bug in the headers in pre-10.5 SDKs
NSMutableCharacterSet *validCharacters = (id)[NSMutableCharacterSet alphanumericCharacterSet];
[validCharacters formUnionWithCharacterSet:[NSCharacterSet characterSetWithCharactersInString:@".-()"]];
postFix = [[bundle objectForInfoDictionaryKey:@"CFBundleVersion"] stringByTrimmingCharactersInSet:[validCharacters invertedSet]];
}
else
postFix = @"old";
NSString *prefix = [[path stringByDeletingPathExtension] stringByAppendingFormat:@" (%@)", postFix];
NSString *tempDir = [prefix stringByAppendingPathExtension:[path pathExtension]];
// Now let's make sure we get a unique path.
int cnt=2;
while ([[NSFileManager defaultManager] fileExistsAtPath:tempDir] && cnt <= 999999)
tempDir = [NSString stringWithFormat:@"%@ %d.%@", prefix, cnt++, [path pathExtension]];
return tempDir;
}
- (BOOL)_copyPathWithForcedAuthentication:(NSString *)src toPath:(NSString *)dst error:(NSError **)error
{
NSString *tmp = [self _temporaryCopyNameForPath:dst];
const char* srcPath = [src fileSystemRepresentation];
const char* tmpPath = [tmp fileSystemRepresentation];
const char* dstPath = [dst fileSystemRepresentation];
struct stat dstSB;
stat(dstPath, &dstSB);
AuthorizationRef auth = NULL;
OSStatus authStat = errAuthorizationDenied;
while (authStat == errAuthorizationDenied) {
authStat = AuthorizationCreate(NULL,
kAuthorizationEmptyEnvironment,
kAuthorizationFlagDefaults,
&auth);
}
BOOL res = NO;
if (authStat == errAuthorizationSuccess) {
res = YES;
char uidgid[42];
snprintf(uidgid, sizeof(uidgid), "%d:%d",
dstSB.st_uid, dstSB.st_gid);
const char* executables[] = {
"/bin/rm",
"/bin/mv",
"/bin/mv",
"/bin/rm",
NULL, // pause here and do some housekeeping before
// continuing
"/usr/sbin/chown",
NULL // stop here for real
};
// 4 is the maximum number of arguments to any command,
// including the NULL that signals the end of an argument
// list.
const char* const argumentLists[][4] = {
{ "-rf", tmpPath, NULL }, // make room for the temporary file... this is kinda unsafe; should probably do something better.
{ "-f", dstPath, tmpPath, NULL }, // mv
{ "-f", srcPath, dstPath, NULL }, // mv
{ "-rf", tmpPath, NULL }, // rm
{ NULL }, // pause
{ "-R", uidgid, dstPath, NULL }, // chown
{ NULL } // stop
};
// Process the commands up until the first NULL
int commandIndex = 0;
for (; executables[commandIndex] != NULL; ++commandIndex) {
if (res)
res = AuthorizationExecuteWithPrivilegesAndWait(auth, executables[commandIndex], kAuthorizationFlagDefaults, argumentLists[commandIndex]);
}
// If the currently-running application is trusted, the new
// version should be trusted as well. Remove it from the
// quarantine to avoid a delay at launch, and to avoid
// presenting the user with a confusing trust dialog.
//
// This needs to be done after the application is moved to its
// new home with "mv" in case it's moved across filesystems: if
// that happens, "mv" actually performs a copy and may result
// in the application being quarantined. It also needs to be
// done before "chown" changes ownership, because the ownership
// change will almost certainly make it impossible to change
// attributes to release the files from the quarantine.
if (res) {
[self releaseFromQuarantine:dst];
}
// Now move past the NULL we found and continue executing
// commands from the list.
++commandIndex;
for (; executables[commandIndex] != NULL; ++commandIndex) {
if (res)
res = AuthorizationExecuteWithPrivilegesAndWait(auth, executables[commandIndex], kAuthorizationFlagDefaults, argumentLists[commandIndex]);
}
AuthorizationFree(auth, 0);
if (!res)
{
// Something went wrong somewhere along the way, but we're not sure exactly where.
NSString *errorMessage = [NSString stringWithFormat:@"Authenticated file copy from %@ to %@ failed.", src, dst];
if (error != NULL)
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:[NSDictionary dictionaryWithObject:errorMessage forKey:NSLocalizedDescriptionKey]];
}
}
else
{
if (error != NULL)
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:[NSDictionary dictionaryWithObject:@"Couldn't get permission to authenticate." forKey:NSLocalizedDescriptionKey]];
}
return res;
}
- (BOOL)copyPathWithAuthentication:(NSString *)src overPath:(NSString *)dst error:(NSError **)error
{
if (![[NSFileManager defaultManager] fileExistsAtPath:dst])
{
NSString *errorMessage = [NSString stringWithFormat:@"Couldn't copy %@ over %@ because there is no file at %@.", src, dst, dst];
if (error != NULL)
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUFileCopyFailure userInfo:[NSDictionary dictionaryWithObject:errorMessage forKey:NSLocalizedDescriptionKey]];
return NO;
}
if (![[NSFileManager defaultManager] isWritableFileAtPath:dst] || ![[NSFileManager defaultManager] isWritableFileAtPath:[dst stringByDeletingLastPathComponent]])
return [self _copyPathWithForcedAuthentication:src toPath:dst error:error];
NSString *tmpPath = [self _temporaryCopyNameForPath:dst];
if (![[NSFileManager defaultManager] movePath:dst toPath:tmpPath handler:self])
{
if (error != NULL)
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUFileCopyFailure userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"Couldn't move %@ to %@.", dst, tmpPath] forKey:NSLocalizedDescriptionKey]];
return NO;
}
if (![[NSFileManager defaultManager] copyPath:src toPath:dst handler:self])
{
if (error != NULL)
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUFileCopyFailure userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"Couldn't copy %@ to %@.", src, dst] forKey:NSLocalizedDescriptionKey]];
return NO;
}
// Trash the old copy of the app.
NSInteger tag = 0;
if (![[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:[tmpPath stringByDeletingLastPathComponent] destination:@"" files:[NSArray arrayWithObject:[tmpPath lastPathComponent]] tag:&tag])
NSLog(@"Sparkle error: couldn't move %@ to the trash. This is often a sign of a permissions error.", tmpPath);
// If the currently-running application is trusted, the new
// version should be trusted as well. Remove it from the
// quarantine to avoid a delay at launch, and to avoid
// presenting the user with a confusing trust dialog.
//
// This needs to be done after the application is moved to its
// new home in case it's moved across filesystems: if that
// happens, the move is actually a copy, and it may result
// in the application being quarantined.
[self releaseFromQuarantine:dst];
return YES;
}
@end
-53
View File
@@ -1,53 +0,0 @@
//
// NSFileManager+ExtendedAttributes.h
// Sparkle
//
// Created by Mark Mentovai on 2008-01-22.
// Copyright 2008 Mark Mentovai. All rights reserved.
//
#ifndef NSFILEMANAGER_PLUS_EXTENDEDATTRIBUTES
#define NSFILEMANAGER_PLUS_EXTENDEDATTRIBUTES
#import <Cocoa/Cocoa.h>
@interface NSFileManager (MMExtendedAttributes)
// Wraps the removexattr system call, allowing an AppKit-style NSString* to
// be used for the pathname argument. Note that the order of the arguments
// has changed from what removexattr accepts, so that code reads more
// naturally.
//
// removexattr is only available on Mac OS X 10.4 ("Tiger") and later. If
// built with an SDK that includes removexattr, this method will link against
// removexattr directly. When using earlier SDKs, this method will dynamically
// look up the removexattr symbol at runtime. If the symbol is not present,
// as will be the case when running on 10.3, this method returns -1 and sets
// errno to ENOSYS.
- (int)removeXAttr:(const char*)name
fromFile:(NSString*)file
options:(int)options;
// Removes the directory tree rooted at |root| from the file quarantine.
// The quarantine was introduced on Mac OS X 10.5 and is described at:
//
// http://developer.apple.com/releasenotes/Carbon/RN-LaunchServices/index.html
//#apple_ref/doc/uid/TP40001369-DontLinkElementID_2
//
// If |root| is not a directory, then it alone is removed from the quarantine.
// Symbolic links, including |root| if it is a symbolic link, will not be
// traversed.
//
// Ordinarily, the quarantine is managed by calling LSSetItemAttribute
// to set the kLSItemQuarantineProperties attribute to a dictionary specifying
// the quarantine properties to be applied. However, it does not appear to be
// possible to remove an item from the quarantine directly through any public
// Launch Services calls. Instead, this method takes advantage of the fact
// that the quarantine is implemented in part by setting an extended attribute,
// "com.apple.quarantine", on affected files. Removing this attribute is
// sufficient to remove files from the quarantine.
- (void)releaseFromQuarantine:(NSString*)root;
@end
#endif
-98
View File
@@ -1,98 +0,0 @@
//
// NSFileManager+ExtendedAttributes.m
// Sparkle
//
// Created by Mark Mentovai on 2008-01-22.
// Copyright 2008 Mark Mentovai. All rights reserved.
//
#import "NSFileManager+ExtendedAttributes.h"
#include <dlfcn.h>
#include <errno.h>
// Extended attribute support was introduced in Mac OS X 10.4 ("Tiger").
// If building with an earlier SDK, provide definitions needed to handle
// extended attributes at runtime.
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4 // SDK >= 10.4
#include <sys/xattr.h>
#else // SDK >= 10.4
#define XATTR_NOFOLLOW 1
#endif // SDK >= 10.4
@implementation NSFileManager (MMExtendedAttributes)
- (int)removeXAttr:(const char*)name
fromFile:(NSString*)file
options:(int)options
{
typedef int (*removexattr_type)(const char*, const char*, int);
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4 // SDK >= 10.4
// Reference removexattr directly, it's in the SDK.
static removexattr_type removexattr_func = removexattr;
#else // SDK >= 10.4
// removexattr isn't in this SDK, look it up at runtime.
static removexattr_type removexattr_func = NULL;
static BOOL didSymbolLookup = NO;
if (!didSymbolLookup) {
didSymbolLookup = YES;
removexattr_func = dlsym(RTLD_NEXT, "removexattr");
}
#endif // SDK >= 10.4
#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4 // DT < 10.4
// Make sure that the symbol is present. This checks the deployment
// target instead of the SDK so that it's able to catch dlsym failures
// as well as the null symbol that would result from building with the
// 10.4 SDK and a lower deployment target, and running on 10.3.
if (!removexattr_func) {
errno = ENOSYS;
return -1;
}
#endif // DT < 10.4
const char* path = NULL;
@try {
path = [file fileSystemRepresentation];
}
@catch (id exception) {
// -[NSString fileSystemRepresentation] throws an exception if it's
// unable to convert the string to something suitable. Map that to
// EDOM, "argument out of domain", which sort of conveys that there
// was a conversion failure.
errno = EDOM;
return -1;
}
return removexattr_func(path, name, options);
}
- (void)releaseFromQuarantine:(NSString*)root
{
const char* quarantineAttribute = "com.apple.quarantine";
const int removeXAttrOptions = XATTR_NOFOLLOW;
[self removeXAttr:quarantineAttribute
fromFile:root
options:removeXAttrOptions];
// Only recurse if it's actually a directory. Don't recurse into a
// root-level symbolic link.
NSDictionary* rootAttributes =
[self fileAttributesAtPath:root traverseLink:NO];
NSString* rootType = [rootAttributes objectForKey:NSFileType];
if (rootType == NSFileTypeDirectory) {
// The NSDirectoryEnumerator will avoid recursing into any contained
// symbolic links, so no further type checks are needed.
NSDirectoryEnumerator* directoryEnumerator = [self enumeratorAtPath:root];
NSString* file = nil;
while ((file = [directoryEnumerator nextObject])) {
[self removeXAttr:quarantineAttribute
fromFile:[root stringByAppendingPathComponent:file]
options:removeXAttrOptions];
}
}
}
@end
-17
View File
@@ -1,17 +0,0 @@
//
// NSFileManager+Verification.h
// Sparkle
//
// Created by Andy Matuschak on 3/16/06.
// Copyright 2006 Andy Matuschak. All rights reserved.
//
#ifndef NSFILEMANAGER_PLUS_VERIFICATION_H
#define NSFILEMANAGER_PLUS_VERIFICATION_H
// For the paranoid folks!
@interface NSFileManager (SUVerification)
- (BOOL)validatePath:(NSString *)path withEncodedDSASignature:(NSString *)encodedSignature withPublicDSAKey:(NSString *)pkeyString;
@end
#endif
-151
View File
@@ -1,151 +0,0 @@
//
// NSFileManager+Verification.m
// Sparkle
//
// Created by Andy Matuschak on 3/16/06.
// Copyright 2006 Andy Matuschak. All rights reserved.
//
// DSA stuff adapted from code provided by Allan Odgaard. Thanks, Allan!
#import "Sparkle.h"
#import "NSFileManager+Verification.h"
#import <stdio.h>
#import <openssl/evp.h>
#import <openssl/bio.h>
#import <openssl/pem.h>
#import <openssl/rsa.h>
#import <openssl/sha.h>
long b64decode(unsigned char* str)
{
unsigned char *cur, *start;
int d, dlast, phase;
unsigned char c;
static int table[256] = {
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* 00-0F */
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* 10-1F */
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63, /* 20-2F */
52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1, /* 30-3F */
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14, /* 40-4F */
15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1, /* 50-5F */
-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40, /* 60-6F */
41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1, /* 70-7F */
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* 80-8F */
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* 90-9F */
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* A0-AF */
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* B0-BF */
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* C0-CF */
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* D0-DF */
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* E0-EF */
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 /* F0-FF */
};
d = dlast = phase = 0;
start = str;
for (cur = str; *cur != '\0'; ++cur )
{
if(*cur == '\n' || *cur == '\r'){phase = dlast = 0; continue;}
d = table[(int)*cur];
if(d != -1)
{
switch(phase)
{
case 0:
++phase;
break;
case 1:
c = ((dlast << 2) | ((d & 0x30) >> 4));
*str++ = c;
++phase;
break;
case 2:
c = (((dlast & 0xf) << 4) | ((d & 0x3c) >> 2));
*str++ = c;
++phase;
break;
case 3:
c = (((dlast & 0x03 ) << 6) | d);
*str++ = c;
phase = 0;
break;
}
dlast = d;
}
}
*str = '\0';
return str - start;
}
EVP_PKEY* load_dsa_key(char *key)
{
EVP_PKEY* pkey = NULL;
BIO *bio;
if((bio = BIO_new_mem_buf(key, (int)strlen(key))))
{
DSA* dsa_key = 0;
if(PEM_read_bio_DSA_PUBKEY(bio, &dsa_key, NULL, NULL))
{
if((pkey = EVP_PKEY_new()))
{
if(EVP_PKEY_assign_DSA(pkey, dsa_key) != 1)
{
DSA_free(dsa_key);
EVP_PKEY_free(pkey);
pkey = NULL;
}
}
}
BIO_free(bio);
}
return pkey;
}
@implementation NSFileManager (SUVerification)
- (BOOL)validatePath:(NSString *)path withEncodedDSASignature:(NSString *)encodedSignature withPublicDSAKey:(NSString *)pkeyString
{
BOOL result = NO;
if (!encodedSignature) { return NO; }
if (!pkeyString) { return NO; }
// Remove whitespace around each line of the key.
NSMutableArray *pkeyTrimmedLines = [NSMutableArray array];
NSEnumerator *pkeyLinesEnumerator = [[pkeyString componentsSeparatedByString:@"\n"] objectEnumerator];
NSString *pkeyLine;
while ((pkeyLine = [pkeyLinesEnumerator nextObject]) != nil)
{
[pkeyTrimmedLines addObject:[pkeyLine stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]];
}
pkeyString = [pkeyTrimmedLines componentsJoinedByString:@"\n"]; // Put them back together.
EVP_PKEY* pkey = NULL;
pkey = load_dsa_key((char *)[pkeyString UTF8String]);
if (!pkey) { return NO; }
// Now, the signature is in base64; we have to decode it into a binary stream.
unsigned char *signature = (unsigned char *)[encodedSignature UTF8String];
long length = b64decode(signature); // Decode the signature in-place and get the new length of the signature string.
// We've got the signature, now get the file data.
NSData *pathData = [NSData dataWithContentsOfFile:path];
if (!pathData) { return NO; }
// Hash the file with SHA-1.
unsigned char md[SHA_DIGEST_LENGTH];
SHA1([pathData bytes], [pathData length], md);
// Actually verify the signature on the file.
EVP_MD_CTX ctx;
if(EVP_VerifyInit(&ctx, EVP_dss1()) == 1) // We're using DSA keys.
{
EVP_VerifyUpdate(&ctx, md, SHA_DIGEST_LENGTH);
result = (EVP_VerifyFinal(&ctx, signature, (unsigned int)length, pkey) == 1);
}
EVP_PKEY_free(pkey);
return result;
}
@end
-16
View File
@@ -1,16 +0,0 @@
//
// NSNumber+Units.h
// Sparkle
//
// Created by Jonas Witt on 5/18/08.
// Copyright 2008 __MyCompanyName__. All rights reserved.
//
#import <Cocoa/Cocoa.h>
@interface NSNumber (JWUnits)
+ (NSString *)humanReadableSizeFromDouble:(double)value;
@end
-28
View File
@@ -1,28 +0,0 @@
//
// NSNumber+Units.m
// Sparkle
//
// Created by Jonas Witt on 5/18/08.
// Copyright 2008 __MyCompanyName__. All rights reserved.
//
#import "NSNumber+Units.h"
#import "Sparkle.h"
@implementation NSNumber (JWUnits)
+ (NSString *)humanReadableSizeFromDouble:(double)value
{
if (value < 1024)
return [NSString stringWithFormat:@"%.0lf %@", value, SULocalizedString(@"B", @"the unit for bytes")];
if (value < 1024 * 1024)
return [NSString stringWithFormat:@"%.0lf %@", value / 1024.0, SULocalizedString(@"KB", @"the unit for kilobytes")];
if (value < 1024 * 1024 * 1024)
return [NSString stringWithFormat:@"%.1lf %@", value / 1024.0 / 1024.0, SULocalizedString(@"MB", @"the unit for megabytes")];
return [NSString stringWithFormat:@"%.2lf %@", value / 1024.0 / 1024.0 / 1024.0, SULocalizedString(@"GB", @"the unit for gigabytes")];
}
@end
-18
View File
@@ -1,18 +0,0 @@
//
// NSWorkspace+SystemVersion.h
// Sparkle
//
// Created by Andy Matuschak on 5/7/08.
// Copyright 2008 Andy Matuschak. All rights reserved.
//
#ifndef NSWORKSPACE_PLUS_SYSTEMVERSION_H
#define NSWORKSPACE_PLUS_SYSTEMVERSION_H
#import <Cocoa/Cocoa.h>
@interface NSWorkspace (SUSystemVersion)
+ (NSString *)systemVersionString;
@end
#endif
-36
View File
@@ -1,36 +0,0 @@
//
// NSWorkspace+SystemVersion.m
// Sparkle
//
// Created by Andy Matuschak on 5/7/08.
// Copyright 2008 Andy Matuschak. All rights reserved.
//
#import "NSWorkspace+SystemVersion.h"
@implementation NSWorkspace (SUSystemVersion)
+ (NSString *)systemVersionString
{
// This returns a version string of the form X.Y.Z
// There may be a better way to deal with the problem that gestaltSystemVersionMajor
// et al. are not defined in 10.3, but this is probably good enough.
NSString* verStr = nil;
#if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_4
SInt32 major, minor, bugfix;
OSErr err1 = Gestalt(gestaltSystemVersionMajor, &major);
OSErr err2 = Gestalt(gestaltSystemVersionMinor, &minor);
OSErr err3 = Gestalt(gestaltSystemVersionBugFix, &bugfix);
if (!err1 && !err2 && !err3)
{
verStr = [NSString stringWithFormat:@"%d.%d.%d", major, minor, bugfix];
}
else
#endif
{
NSString *versionPlistPath = @"/System/Library/CoreServices/SystemVersion.plist";
verStr = [[[NSDictionary dictionaryWithContentsOfFile:versionPlistPath] objectForKey:@"ProductVersion"] retain];
}
return verStr;
}
@end
-41
View File
@@ -1,41 +0,0 @@
//
// NSWorkspace_RBAdditions.h
// PathProps
//
// Created by Rainer Brockerhoff on 10/04/2007.
// Copyright 2007 Rainer Brockerhoff. All rights reserved.
//
#ifndef NSWORKSPACE_RBADDITIONS_H
#define NSWORKSPACE_RBADDITIONS_H
extern NSString* NSWorkspace_RBfstypename;
extern NSString* NSWorkspace_RBmntonname;
extern NSString* NSWorkspace_RBmntfromname;
extern NSString* NSWorkspace_RBdeviceinfo;
extern NSString* NSWorkspace_RBimagefilepath;
extern NSString* NSWorkspace_RBconnectiontype;
extern NSString* NSWorkspace_RBpartitionscheme;
extern NSString* NSWorkspace_RBserverURL;
@interface NSWorkspace (NSWorkspace_RBAdditions)
// This method will return nil if the input path is invalid. Otherwise, the returned NSDictionary may contain
// the following keys:
//- NSWorkspace_RBfstypename: will always be present.Shows the filesystem type (usually "hfs"), from statfs.
//- NSWorkspace_RBmntonname: will always be present. Shows the volume mount point.
//- NSWorkspace_RBmntfromname: will always be present. Shows the BSD device path for local volumes; info for
// remote volumes depends on the filesystem type.
//- NSWorkspace_RBconnectiontype: should always be present for local volumes. Shows the connection type ("SATA", "USB", etc.).
//- NSWorkspace_RBpartitionscheme: should always be present for local volumes. Shows the partition scheme.
//- NSWorkspace_RBdeviceinfo: should always be present for local volumes. Shows some information about the
// physical device; varies widely.
//- NSWorkspace_RBimagefilepath: should be present for disk images only. Shows the path of the disk image file.
//- NSWorkspace_RBserverURL: should be present for remote volumes only. Shows the server URL.
- (NSDictionary*)propertiesForPath:(NSString*)path;
@end
#endif
-177
View File
@@ -1,177 +0,0 @@
//
// NSWorkspace_RBAdditions.m
// PathProps
//
// Created by Rainer Brockerhoff on 10/04/2007.
// Copyright 2007 Rainer Brockerhoff. All rights reserved.
//
#import "Sparkle.h"
#import "NSWorkspace_RBAdditions.h"
#include <IOKit/IOKitLib.h>
#include <sys/mount.h>
#include <mach/mach.h>
NSString* NSWorkspace_RBfstypename = @"NSWorkspace_RBfstypename";
NSString* NSWorkspace_RBmntonname = @"NSWorkspace_RBmntonname";
NSString* NSWorkspace_RBmntfromname = @"NSWorkspace_RBmntfromname";
NSString* NSWorkspace_RBdeviceinfo = @"NSWorkspace_RBdeviceinfo";
NSString* NSWorkspace_RBimagefilepath = @"NSWorkspace_RBimagefilepath";
NSString* NSWorkspace_RBconnectiontype = @"NSWorkspace_RBconnectiontype";
NSString* NSWorkspace_RBpartitionscheme = @"NSWorkspace_RBpartitionscheme";
NSString* NSWorkspace_RBserverURL = @"NSWorkspace_RBserverURL";
// This static funtion concatenates two strings, but first checks several possibilities...
// like one or the other nil, or one containing the other already.
static NSString* AddPart(NSString* first,NSString* second) {
if (!second) {
return first;
}
second = [second stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if (first) {
if ([first rangeOfString:second options:NSCaseInsensitiveSearch].location==NSNotFound) {
if ([second rangeOfString:first options:NSCaseInsensitiveSearch].location==NSNotFound) {
return [NSString stringWithFormat:@"%@; %@",first,second];
}
return second;
}
return first;
}
return second;
}
// This static functions recurses "upwards" over the IO registry. Returns strings that are concatenated
// and ultimately end up under the NSWorkspace_RBdeviceinfo key.
// This isn't too robust in that it assumes that objects returned by the objectForKey methods are
// either strings or dictionaries. A "standard" implementations would use either only CoreFoundation and
// IOKit calls for this, or do more robust type checking on the returned objects.
//
// Also notice that this works as determined experimentally in 10.4.9, there's no official docs I could find.
// YMMV, and it may stop working in any new version of Mac OS X.
static NSString* CheckParents(io_object_t thing,NSString* part,NSMutableDictionary* dict) {
NSString* result = part;
io_iterator_t parentsIterator = 0;
kern_return_t kernResult = IORegistryEntryGetParentIterator(thing,kIOServicePlane,&parentsIterator);
if ((kernResult==KERN_SUCCESS)&&parentsIterator) {
io_object_t nextParent = 0;
while ((nextParent = IOIteratorNext(parentsIterator))) {
NSDictionary* props = nil;
NSString* image = nil;
NSString* partition = nil;
NSString* connection = nil;
kernResult = IORegistryEntryCreateCFProperties(nextParent,(CFMutableDictionaryRef*)&props,kCFAllocatorDefault,0);
if (IOObjectConformsTo(nextParent,"IOApplePartitionScheme")) {
partition = [props objectForKey:@"Content Mask"];
} else if (IOObjectConformsTo(nextParent,"IOMedia")) {
partition = [props objectForKey:@"Content"];
} else if (IOObjectConformsTo(nextParent,"IODiskImageBlockStorageDeviceOutKernel")) {
NSData* data = nil;
if ((data = [[props objectForKey:@"Protocol Characteristics"] objectForKey:@"Virtual Interface Location Path"])) {
image = [[[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding] autorelease];
}
} else if (IOObjectConformsTo(nextParent,"IOHDIXHDDriveInKernel")) {
image = [props objectForKey:@"KDIURLPath"];
}
NSDictionary* subdict;
if ((subdict = [props objectForKey:@"Protocol Characteristics"])) {
connection = [subdict objectForKey:@"Physical Interconnect"];
} else {
connection = [props objectForKey:@"Physical Interconnect"];
}
if (connection) {
[dict setObject:AddPart([dict objectForKey:NSWorkspace_RBconnectiontype],connection) forKey:NSWorkspace_RBconnectiontype];
}
if (partition) {
[dict setObject:partition forKey:NSWorkspace_RBpartitionscheme];
}
if (image) {
[dict setObject:image forKey:NSWorkspace_RBimagefilepath];
}
NSString* value;
if ((subdict = [props objectForKey:@"Device Characteristics"])) {
if ((value = [subdict objectForKey:@"Product Name"])) {
result = AddPart(result,value);
}
if ((value = [subdict objectForKey:@"Product Revision Level"])) {
result = AddPart(result,value);
}
if ((value = [subdict objectForKey:@"Vendor Name"])) {
result = AddPart(result,value);
}
}
if ((value = [props objectForKey:@"USB Serial Number"])) {
result = AddPart(result,value);
}
if ((value = [props objectForKey:@"USB Vendor Name"])) {
result = AddPart(result,value);
}
io_name_t ts; // char[128]
NSString* cls = ( IOObjectGetClass (nextParent, ts) == KERN_SUCCESS ) ? [NSString stringWithUTF8String:ts ] : nil;
if (![cls isEqualToString:@"IOPCIDevice"]) {
// Uncomment the following line to have the device tree dumped to the console.
// NSLog(@"=================================> %@:%@\n",cls,props);
result = CheckParents(nextParent,result,dict);
}
if (props) { CFRelease(props); }
IOObjectRelease(nextParent);
}
}
if (parentsIterator) {
IOObjectRelease(parentsIterator);
}
return result;
}
@implementation NSWorkspace (NSWorkspace_RBAdditions)
// Returns a NSDictionary with properties for the path. See details in the .h file.
// This assumes that the length of path is less than PATH_MAX (currently 1024 characters).
- (NSDictionary*)propertiesForPath:(NSString*)path {
const char* ccpath = [path fileSystemRepresentation];
NSMutableDictionary* result = nil;
struct statfs fs = {};
if (!statfs(ccpath,&fs)) {
NSString* from = [[NSFileManager defaultManager] stringWithFileSystemRepresentation:fs.f_mntfromname length:strlen(fs.f_mntfromname)];
result = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSString stringWithUTF8String:fs.f_fstypename], NSWorkspace_RBfstypename, [[NSFileManager defaultManager] stringWithFileSystemRepresentation:fs.f_mntonname length:strlen(fs.f_mntonname)], NSWorkspace_RBmntonname, nil];
const char* devstring = "/dev/";
size_t devstringlen = 5;
if (strncmp(fs.f_mntfromname,devstring,devstringlen)==0) {
// For a local volume,get the IO registry tree and search it for further info.
mach_port_t masterPort = 0;
io_iterator_t mediaIterator = 0;
kern_return_t kernResult = IOMasterPort(bootstrap_port,&masterPort);
if (kernResult==KERN_SUCCESS) {
CFMutableDictionaryRef classesToMatch = IOBSDNameMatching(masterPort,0,&fs.f_mntfromname[devstringlen]);
if (classesToMatch) {
kernResult = IOServiceGetMatchingServices(masterPort,classesToMatch,&mediaIterator);
if ((kernResult==KERN_SUCCESS)&&mediaIterator) {
io_object_t firstMedia = 0;
while ((firstMedia = IOIteratorNext(mediaIterator))) {
NSString* stuff = CheckParents(firstMedia,nil,result);
if (stuff) {
[result setObject:stuff forKey:NSWorkspace_RBdeviceinfo];
}
IOObjectRelease(firstMedia);
}
}
}
}
if (mediaIterator) {
IOObjectRelease(mediaIterator);
}
if (masterPort) {
mach_port_deallocate(mach_task_self(),masterPort);
}
}
[result setObject:from forKey:NSWorkspace_RBmntfromname];
}
return result;
}
@end
+9
View File
@@ -9,8 +9,11 @@
#ifndef NTSYNCHRONOUSTASK_H
#define NTSYNCHRONOUSTASK_H
#import <Foundation/Foundation.h>
@interface NTSynchronousTask : NSObject
{
@private
NSTask *mv_task;
NSPipe *mv_outputPipe;
NSPipe *mv_inputPipe;
@@ -22,8 +25,14 @@
// pass nil for directory if not needed
// returns the result
+ (int)task:(NSString*)toolPath directory:(NSString*)currentDirectory withArgs:(NSArray*)args input:(NSData*)input output:(NSData**)outData;
+ (NSData*)task:(NSString*)toolPath directory:(NSString*)currentDirectory withArgs:(NSArray*)args input:(NSData*)input;
- (void)run:(NSString*)toolPath directory:(NSString*)currentDirectory withArgs:(NSArray*)args input:(NSData*)input;
- (int)result;
- (NSData *)output;
@end
#endif
+149 -147
View File
@@ -6,151 +6,11 @@
// Copyright 2005 Steve Gehrman. All rights reserved.
//
#import "Sparkle.h"
#import "NTSynchronousTask.h"
@interface NTSynchronousTask (Private)
- (void)run:(NSString*)toolPath directory:(NSString*)currentDirectory withArgs:(NSArray*)args input:(NSData*)input;
- (NSTask *)task;
- (void)setTask:(NSTask *)theTask;
- (NSPipe *)outputPipe;
- (void)setOutputPipe:(NSPipe *)theOutputPipe;
- (NSPipe *)inputPipe;
- (void)setInputPipe:(NSPipe *)theInputPipe;
- (NSData *)output;
- (void)setOutput:(NSData *)theOutput;
- (BOOL)done;
- (void)setDone:(BOOL)flag;
- (int)result;
- (void)setResult:(int)theResult;
@end
#import <AppKit/NSApplication.h>
@implementation NTSynchronousTask
- (id)init;
{
self = [super init];
if (self)
{
[self setTask:[[[NSTask alloc] init] autorelease]];
[self setOutputPipe:[[[NSPipe alloc] init] autorelease]];
[self setInputPipe:[[[NSPipe alloc] init] autorelease]];
[[self task] setStandardInput:[self inputPipe]];
[[self task] setStandardOutput:[self outputPipe]];
}
return self;
}
//----------------------------------------------------------
// dealloc
//----------------------------------------------------------
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
[self setTask:nil];
[self setOutputPipe:nil];
[self setInputPipe:nil];
[self setOutput:nil];
[super dealloc];
}
+ (NSData*)task:(NSString*)toolPath directory:(NSString*)currentDirectory withArgs:(NSArray*)args input:(NSData*)input;
{
// we need this wacky pool here, otherwise we run out of pipes, the pipes are internally autoreleased
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSData* result=nil;
NS_DURING
{
NTSynchronousTask* task = [[NTSynchronousTask alloc] init];
[task run:toolPath directory:currentDirectory withArgs:args input:input];
if ([task result] == 0)
result = [[task output] retain];
[task release];
}
NS_HANDLER;
NS_ENDHANDLER;
[pool drain];
// retained above
[result autorelease];
return result;
}
@end
@implementation NTSynchronousTask (Private)
- (void)run:(NSString*)toolPath directory:(NSString*)currentDirectory withArgs:(NSArray*)args input:(NSData*)input;
{
BOOL success = NO;
if (currentDirectory)
[[self task] setCurrentDirectoryPath: currentDirectory];
[[self task] setLaunchPath:toolPath];
[[self task] setArguments:args];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(taskOutputAvailable:)
name:NSFileHandleReadToEndOfFileCompletionNotification
object:[[self outputPipe] fileHandleForReading]];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(taskDidTerminate:)
name:NSTaskDidTerminateNotification
object:[self task]];
[[[self outputPipe] fileHandleForReading] readToEndOfFileInBackgroundAndNotifyForModes:[NSArray arrayWithObjects:NSDefaultRunLoopMode, NSModalPanelRunLoopMode, NSEventTrackingRunLoopMode, nil]];
NS_DURING
[[self task] launch];
success = YES;
NS_HANDLER
;
NS_ENDHANDLER
if (success)
{
if (input)
{
// feed the running task our input
[[[self inputPipe] fileHandleForWriting] writeData:input];
[[[self inputPipe] fileHandleForWriting] closeFile];
}
// loop until we are done receiving the data
if (![self done])
{
double resolution = 1;
BOOL isRunning;
NSDate* next;
do {
next = [NSDate dateWithTimeIntervalSinceNow:resolution];
isRunning = [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
beforeDate:next];
} while (isRunning && ![self done]);
}
}
}
//----------------------------------------------------------
// task
//----------------------------------------------------------
@@ -241,10 +101,6 @@
mv_result = theResult;
}
@end
@implementation NTSynchronousTask (Notifications)
- (void)taskOutputAvailable:(NSNotification*)note
{
[self setOutput:[[note userInfo] objectForKey:NSFileHandleNotificationDataItem]];
@@ -257,6 +113,152 @@
[self setResult:[[self task] terminationStatus]];
}
- (id)init;
{
self = [super init];
if (self)
{
[self setTask:[[[NSTask alloc] init] autorelease]];
[self setOutputPipe:[[[NSPipe alloc] init] autorelease]];
[self setInputPipe:[[[NSPipe alloc] init] autorelease]];
[[self task] setStandardInput:[self inputPipe]];
[[self task] setStandardOutput:[self outputPipe]];
[[self task] setStandardError:[self outputPipe]];
}
return self;
}
//----------------------------------------------------------
// dealloc
//----------------------------------------------------------
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
[mv_task release];
[mv_outputPipe release];
[mv_inputPipe release];
[mv_output release];
[super dealloc];
}
- (void)run:(NSString*)toolPath directory:(NSString*)currentDirectory withArgs:(NSArray*)args input:(NSData*)input
{
BOOL success = NO;
if (currentDirectory)
[[self task] setCurrentDirectoryPath: currentDirectory];
[[self task] setLaunchPath:toolPath];
[[self task] setArguments:args];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(taskOutputAvailable:)
name:NSFileHandleReadToEndOfFileCompletionNotification
object:[[self outputPipe] fileHandleForReading]];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(taskDidTerminate:)
name:NSTaskDidTerminateNotification
object:[self task]];
[[[self outputPipe] fileHandleForReading] readToEndOfFileInBackgroundAndNotifyForModes:[NSArray arrayWithObjects:NSDefaultRunLoopMode, NSModalPanelRunLoopMode, NSEventTrackingRunLoopMode, nil]];
@try
{
[[self task] launch];
success = YES;
}
@catch (NSException *localException) { }
if (success)
{
if (input)
{
// feed the running task our input
[[[self inputPipe] fileHandleForWriting] writeData:input];
[[[self inputPipe] fileHandleForWriting] closeFile];
}
// loop until we are done receiving the data
if (![self done])
{
double resolution = 1;
BOOL isRunning;
NSDate* next;
do {
next = [NSDate dateWithTimeIntervalSinceNow:resolution];
isRunning = [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
beforeDate:next];
} while (isRunning && ![self done]);
}
}
}
+ (NSData*)task:(NSString*)toolPath directory:(NSString*)currentDirectory withArgs:(NSArray*)args input:(NSData*)input
{
// we need this wacky pool here, otherwise we run out of pipes, the pipes are internally autoreleased
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSData* result=nil;
@try
{
NTSynchronousTask* task = [[NTSynchronousTask alloc] init];
[task run:toolPath directory:currentDirectory withArgs:args input:input];
if ([task result] == 0)
result = [[task output] retain];
[task release];
}
@catch (NSException *localException) { }
[pool drain];
// retained above
[result autorelease];
return result;
}
+ (int)task:(NSString*)toolPath directory:(NSString*)currentDirectory withArgs:(NSArray*)args input:(NSData*)input output:(NSData**)outData
{
// we need this wacky pool here, otherwise we run out of pipes, the pipes are internally autoreleased
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int taskResult = 0;
if( outData )
*outData = nil;
NS_DURING
{
NTSynchronousTask* task = [[NTSynchronousTask alloc] init];
[task run:toolPath directory:currentDirectory withArgs:args input:input];
taskResult = [task result];
if( outData )
*outData = [[task output] retain];
[task release];
}
NS_HANDLER;
taskResult = errCppGeneral;
NS_ENDHANDLER;
[pool drain];
// retained above
if( outData )
[*outData autorelease];
return taskResult;
}
@end
Binary file not shown.
+40
View File
@@ -0,0 +1,40 @@
# Sparkle
is an easy-to-use software update framework for Cocoa developers.
* True self-updating--no work required from the user.
* Displays release notes to the user via WebKit.
* Displays a detailed progress window to the user.
* Supports authentication for installing in secure locations.
* Really, really easy to install.
* Uses appcasts for release information.
* The user can choose to automatically download and install all updates.
* Seamless integration—there's no mention of Sparkle; your icons and app name are used.
* Supports DSA signatures for ultra-secure updates.
* Sparkle requires no code in your app, so it's trivial to upgrade or remove the module.
## New in Sparkle 1.5:
* Optionally sends user demographic information to the server when checking for updates.
* Dual-mode garbage collection support for any memory management style.
* Sparkle doesn't bug the user until second launch for better first impressions.
* Sparkle can install .pkg files for more complicated products.
* Supports bundles, preference panes, plugins, and other non-.app software.
* Supports branches due to minimum OS version requirements.
* Deep delegate support to make Sparkle work exactly as you need.
* Tons of other stuff! [Read more about what's new.](http://andymatuschak.org/articles/2008/05/31/sparkle-15b1-now-available/ "Sparkle 1.5b1: now available!")
+40
View File
@@ -0,0 +1,40 @@
{\rtf1\ansi\ansicpg1252\cocoartf1265\cocoasubrtf210
{\fonttbl\f0\fswiss\fcharset0 Helvetica;}
{\colortbl;\red255\green255\blue255;\red38\green38\blue38;}
\margl1440\margr1440\vieww17920\viewh13460\viewkind0
\deftab720
\pard\pardeftab720
\f0\b\fs26 \cf2 Version 2.1.1
\b0 \
\pard\pardeftab720\sl380
\cf2 \'96 Fixed crash on launch with no internet connection.
\fs24 \cf0 \
\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\pardirnatural
\cf0 \
\pard\pardeftab720
\b\fs26 \cf2 Version 2.1\
\pard\pardeftab720\sl380
\b0 \cf2 \'96 SUFeedURL inside Info.plist file is now optional and can be automatically generated by DevMate\
\'96 Added an updater state check to avoid initiating duplicate installation processes\
\'96 Added a SUUpdaterQueue class\
\'96 Added additional delegate methods.\
\b \
\pard\pardeftab720
\cf2 Version 2.0.1\
\pard\pardeftab720\sl380
\b0 \cf2 \'96 Bug fixing for the application updates in Sandboxed environment.\
\pard\pardeftab720
\cf2 \
\pard\pardeftab720
\b \cf2 Version 2.0\
\pard\pardeftab720\sl380
\b0 \cf2 \'96 Works correctly with Sandboxed environment\
\'96 Added simple integration of beta updates check and test mode\
\'96 Integrated with DevMate service (sends additional info for statistics)}
+19
View File
@@ -0,0 +1,19 @@
//
// SUAppDelegate.h
// Sparkle
//
// Created by Dmytro Tretiakov on 8/1/14.
//
//
#import <Foundation/Foundation.h>
@class SUUpdater;
@class SUUpdaterQueue;
@interface SUAppDelegate : NSObject
@property (nonatomic, retain) IBOutlet SUUpdater *updater;
@property (nonatomic, retain) SUUpdaterQueue *updaterQueue;
@end
+27
View File
@@ -0,0 +1,27 @@
//
// SUAppDelegate.m
// Sparkle
//
// Created by Dmytro Tretiakov on 8/1/14.
//
//
#import "SUAppDelegate.h"
#import <Sparkle/Sparkle.h>
@implementation SUAppDelegate
- (void)dealloc
{
self.updater = nil;
self.updaterQueue = nil;
[super dealloc];
}
- (void)applicationDidFinishLaunching:(NSNotification *)notification
{
self.updaterQueue = [[[SUUpdaterQueue alloc] init] autorelease];
[self.updaterQueue addUpdater:self.updater];
}
@end
+11 -5
View File
@@ -9,23 +9,29 @@
#ifndef SUAPPCAST_H
#define SUAPPCAST_H
@class RSS, SUAppcastItem;
@interface SUAppcast : NSObject {
@class SUAppcastItem;
@interface SUAppcast : NSObject
{
@private
NSArray *items;
NSString *userAgentString;
NSMutableDictionary *appcastValues;
id delegate;
NSMutableData *incrementalData;
NSString *downloadFilename;
NSURLDownload *download;
}
- (void)fetchAppcastFromURL:(NSURL *)url;
- (void)setDelegate:delegate;
- (void)setDelegate:(id)delegate;
- (void)setUserAgentString:(NSString *)userAgentString;
- (void)setAppcastValue:(NSString *)value forKey:(NSString *)key;
- (void)setAllAppcastValues:(NSDictionary *)inAppcastValues;
- (NSArray *)items;
@end
@interface NSObject (SUAppcastDelegate)
- (void)appcast:(SUAppcast *)appcast willFetchURLRequest:(NSMutableURLRequest *)request;
- (void)appcastDidFinishLoading:(SUAppcast *)appcast;
- (void)appcast:(SUAppcast *)appcast failedToLoadWithError:(NSError *)error;
@end
+209 -54
View File
@@ -6,11 +6,36 @@
// Copyright 2006 Andy Matuschak. All rights reserved.
//
#import "Sparkle.h"
#import "SUAppcast.h"
#import "SUUpdater_Private.h"
@interface SUAppcast (Private)
#import "SUAppcast.h"
#import "SUAppcastItem.h"
#import "SUVersionComparisonProtocol.h"
#import "SUAppcast.h"
#import "SUConstants.h"
#import "SULog.h"
#import "SUXPCURLDownload.h"
@interface NSXMLElement (SUAppcastExtensions)
- (NSDictionary *)attributesAsDictionary;
@end
@implementation NSXMLElement (SUAppcastExtensions)
- (NSDictionary *)attributesAsDictionary
{
NSEnumerator *attributeEnum = [[self attributes] objectEnumerator];
NSXMLNode *attribute;
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
while ((attribute = [attributeEnum nextObject]))
[dictionary setObject:[attribute stringValue] forKey:[attribute name]];
return dictionary;
}
@end
@interface SUAppcast () <NSURLDownloadDelegate>
- (void)reportError:(NSError *)error;
- (NSXMLNode *)bestNodeInNodes:(NSArray *)nodes;
@end
@implementation SUAppcast
@@ -18,6 +43,10 @@
- (void)dealloc
{
[items release];
[appcastValues release];
[downloadFilename release];
[download release];
[super dealloc];
}
@@ -29,29 +58,72 @@
- (void)fetchAppcastFromURL:(NSURL *)url
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30.0];
if (userAgentString)
[request setValue:userAgentString forHTTPHeaderField:@"User-Agent"];
incrementalData = [[NSMutableData alloc] init];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
CFRetain(connection);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[incrementalData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
CFRelease(connection);
if ([appcastValues count])
[request setAllHTTPHeaderFields:appcastValues];
if ([delegate respondsToSelector:@selector(appcast:willFetchURLRequest:)])
[delegate appcast:self willFetchURLRequest:request];
if (SUShouldUseXPCDownloader())
{
download = (NSURLDownload *)[[SUXPCURLDownload alloc] initWithRequest:request delegate:self];
}
else
{
download = [[NSURLDownload alloc] initWithRequest:request delegate:self];
}
}
- (void)download:(NSURLDownload *)aDownload decideDestinationWithSuggestedFilename:(NSString *)filename
{
NSString* destinationFilename = NSTemporaryDirectory();
if (destinationFilename)
{
destinationFilename = [destinationFilename stringByAppendingPathComponent:filename];
[download setDestination:destinationFilename allowOverwrite:NO];
}
}
- (void)download:(NSURLDownload *)aDownload didCreateDestination:(NSString *)path
{
[downloadFilename release];
downloadFilename = [path copy];
}
- (void)downloadDidFinish:(NSURLDownload *)aDownload
{
NSError *error = nil;
NSXMLDocument *document = [[NSXMLDocument alloc] initWithData:incrementalData options:0 error:&error];
NSXMLDocument *document = nil;
BOOL failed = NO;
NSArray *xmlItems = nil;
NSMutableArray *appcastItems = [NSMutableArray array];
if (downloadFilename)
{
NSUInteger options = 0;
if (NSAppKitVersionNumber < NSAppKitVersionNumber10_7) {
// In order to avoid including external entities when parsing the appcast (a potential security vulnerability; see https://github.com/andymatuschak/Sparkle/issues/169), we ask NSXMLDocument to "tidy" the XML first. This happens to remove these external entities; it wouldn't be a future-proof approach, but it worked in these historical versions of OS X, and we have a more rigorous approach for 10.7+.
options = NSXMLDocumentTidyXML;
} else {
// In 10.7 and later, there's a real option for the behavior we desire.
options = NSXMLNodeLoadExternalEntitiesSameOriginOnly;
}
document = [[[NSXMLDocument alloc] initWithContentsOfURL:[NSURL fileURLWithPath:downloadFilename] options:options error:&error] autorelease];
#if MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_4
[[NSFileManager defaultManager] removeFileAtPath:downloadFilename handler:nil];
#else
[[NSFileManager defaultManager] removeItemAtPath:downloadFilename error:nil];
#endif
[downloadFilename release];
downloadFilename = nil;
}
else
{
failed = YES;
}
if (nil == document)
{
failed = YES;
@@ -70,27 +142,41 @@
NSEnumerator *nodeEnum = [xmlItems objectEnumerator];
NSXMLNode *node;
NSMutableDictionary *nodesDict = [NSMutableDictionary dictionary];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
while (failed == NO && (node = [nodeEnum nextObject]))
{
// walk the children in reverse
node = [[node children] lastObject];
while (nil != node)
// First, we'll "index" all the first-level children of this appcast item so we can pick them out by language later.
if ([[node children] count])
{
NSString *name = [node name];
if ([name isEqualToString:@"enclosure"]) {
// enclosure is flattened as a separate dictionary for some reason
NSEnumerator *attributeEnum = [[(NSXMLElement *)node attributes] objectEnumerator];
NSXMLNode *attribute;
NSMutableDictionary *encDict = [NSMutableDictionary dictionary];
while ((attribute = [attributeEnum nextObject]))
node = [node childAtIndex:0];
while (nil != node)
{
NSString *name = [node name];
if (name)
{
[encDict setObject:[attribute stringValue] forKey:[attribute name]];
}
NSMutableArray *nodes = [nodesDict objectForKey:name];
if (nodes == nil)
{
nodes = [NSMutableArray array];
[nodesDict setObject:nodes forKey:name];
}
[nodes addObject:node];
}
node = [node nextSibling];
}
}
NSEnumerator *nameEnum = [nodesDict keyEnumerator];
NSString *name;
while ((name = [nameEnum nextObject]))
{
node = [self bestNodeInNodes:[nodesDict objectForKey:name]];
if ([name isEqualToString:@"enclosure"])
{
// enclosure is flattened as a separate dictionary for some reason
NSDictionary *encDict = [(NSXMLElement *)node attributesAsDictionary];
[dict setObject:encDict forKey:@"enclosure"];
}
@@ -101,30 +187,38 @@
if (date)
[dict setObject:date forKey:name];
}
else
{
else if ([name isEqualToString:@"sparkle:deltas"])
{
NSMutableArray *deltas = [NSMutableArray array];
NSEnumerator *childEnum = [[node children] objectEnumerator];
NSXMLNode *child;
while ((child = [childEnum nextObject])) {
if ([[child name] isEqualToString:@"enclosure"])
[deltas addObject:[(NSXMLElement *)child attributesAsDictionary]];
}
[dict setObject:deltas forKey:@"deltas"];
}
else if (name != nil)
{
// add all other values as strings
[dict setObject:[[node stringValue] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] forKey:name];
}
// previous sibling; returns nil when exhausted
node = [node previousSibling];
}
SUAppcastItem *anItem = [[SUAppcastItem alloc] initWithDictionary:dict];
}
NSString *errString;
SUAppcastItem *anItem = [[[SUAppcastItem alloc] initWithDictionary:dict failureReason:&errString] autorelease];
if (anItem)
{
[appcastItems addObject:anItem];
[anItem release];
}
else
{
failed = YES;
SULog(@"Sparkle Updater: Failed to parse appcast item: %@.\nAppcast dictionary was: %@", errString, dict);
}
[nodesDict removeAllObjects];
[dict removeAllObjects];
}
}
[document release];
if ([appcastItems count])
{
@@ -143,14 +237,23 @@
}
}
- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError *)error
- (void)download:(NSURLDownload *)aDownload didFailWithError:(NSError *)error
{
CFRelease(connection);
if (downloadFilename)
{
#if MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_4
[[NSFileManager defaultManager] removeFileAtPath:downloadFilename handler:nil];
#else
[[NSFileManager defaultManager] removeItemAtPath:downloadFilename error:nil];
#endif
}
[downloadFilename release];
downloadFilename = nil;
[self reportError:error];
}
- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse
- (NSURLRequest *)download:(NSURLDownload *)aDownload willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse
{
return request;
}
@@ -163,13 +266,65 @@
}
}
- (NSXMLNode *)bestNodeInNodes:(NSArray *)nodes
{
// 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];
else if ([nodes count] == 0)
return nil;
NSEnumerator *nodeEnum = [nodes objectEnumerator];
NSXMLElement *node;
NSMutableArray *languages = [NSMutableArray array];
NSString *lang;
NSUInteger i;
while ((node = [nodeEnum nextObject]))
{
lang = [[node attributeForName:@"xml:lang"] stringValue];
[languages addObject:(lang ? lang : @"")];
}
lang = [[NSBundle preferredLocalizationsFromArray:languages] objectAtIndex:0];
i = [languages indexOfObject:([languages containsObject:lang] ? lang : @"")];
if (i == NSNotFound)
i = 0;
return [nodes objectAtIndex:i];
}
- (void)setUserAgentString:(NSString *)uas
{
if (uas != userAgentString)
{
[userAgentString release];
userAgentString = [uas copy];
}
[self setAppcastValue:uas forKey:@"User-Agent"];
}
- (void)setAppcastValue:(NSString *)value forKey:(NSString *)key
{
if (nil == key)
return;
if (nil == appcastValues)
appcastValues = [[NSMutableDictionary alloc] init];
if (nil == value)
[appcastValues removeObjectForKey:key];
else
[appcastValues setValue:[[value copy] autorelease] forKey:key];
}
- (void)setAllAppcastValues:(NSDictionary *)inAppcastValues
{
if (0 == [inAppcastValues count])
return;
NSEnumerator *keyEnumerator = [inAppcastValues keyEnumerator];
id key = nil;
while ((key = [keyEnumerator nextObject]))
{
id value = [inAppcastValues objectForKey:key];
if (![key isKindOfClass:[NSString class]] || ![value isKindOfClass:[NSString class]])
continue;
[self setAppcastValue:value forKey:key];
}
}
- (void)setDelegate:del
+17 -5
View File
@@ -9,40 +9,52 @@
#ifndef SUAPPCASTITEM_H
#define SUAPPCASTITEM_H
@interface SUAppcastItem : NSObject {
@interface SUAppcastItem : NSObject
{
@private
NSString *title;
NSDate *date;
NSString *description;
NSString *itemDescription;
NSURL *releaseNotesURL;
NSString *DSASignature;
NSString *minimumSystemVersion;
NSString *maximumSystemVersion;
NSURL *fileURL;
NSString *versionString;
NSString *displayVersionString;
NSDictionary *deltaUpdates;
NSDictionary *propertiesDictionary;
NSURL *infoURL; // UK 2007-08-31
}
// Initializes with data from a dictionary provided by the RSS class.
- initWithDictionary:(NSDictionary *)dict;
- initWithDictionary:(NSDictionary *)dict failureReason:(NSString**)error;
- (NSString *)title;
- (NSString *)versionString;
- (NSString *)displayVersionString;
- (NSDate *)date;
- (NSString *)description;
- (NSString *)itemDescription;
- (NSURL *)releaseNotesURL;
- (NSURL *)fileURL;
- (NSString *)DSASignature;
- (NSString *)minimumSystemVersion;
- (NSString *)maximumSystemVersion;
- (NSDictionary *)deltaUpdates;
- (BOOL)isDeltaUpdate;
// Returns the dictionary provided in initWithDictionary; this might be useful later for extensions.
- (NSDictionary *)propertiesDictionary;
- (NSURL *)infoURL; // UK 2007-08-31
@end
#endif
+139 -39
View File
@@ -6,8 +6,13 @@
// Copyright 2006 Andy Matuschak. All rights reserved.
//
#import "Sparkle.h"
#import "SUUpdater.h"
#import "SUAppcast.h"
#import "SUAppcastItem.h"
#import "SUVersionComparisonProtocol.h"
#import "SUAppcastItem.h"
#import "SULog.h"
@implementation SUAppcastItem
@@ -33,13 +38,13 @@
}
- (NSString *)description { return [[description retain] autorelease]; }
- (NSString *)itemDescription { return [[itemDescription retain] autorelease]; }
- (void)setDescription:(NSString *)aDescription
- (void)setItemDescription:(NSString *)anItemDescription
{
if (description == aDescription) return;
[description release];
description = [aDescription copy];
if (itemDescription == anItemDescription) return;
[itemDescription release];
itemDescription = [anItemDescription copy];
}
@@ -101,7 +106,44 @@
minimumSystemVersion = [systemVersionString copy];
}
- (NSString *)maximumSystemVersion { return [[maximumSystemVersion retain] autorelease]; }
- (void)setMaximumSystemVersion:(NSString *)systemVersionString
{
if (maximumSystemVersion == systemVersionString) return;
[maximumSystemVersion release];
maximumSystemVersion = [systemVersionString copy];
}
- (NSURL *)infoURL { return [[infoURL retain] autorelease]; } // UK 2007-08-31 (whole method)
- (void)setInfoURL:(NSURL *)aFileURL // UK 2007-08-31 (whole method)
{
if( aFileURL == infoURL ) return;
[infoURL release];
infoURL = [aFileURL copy];
}
- (NSDictionary *)deltaUpdates { return [[deltaUpdates retain] autorelease]; }
- (void)setDeltaUpdates:(NSDictionary *)updates
{
if (deltaUpdates == updates) return;
[deltaUpdates release];
deltaUpdates = [updates copy];
}
- (BOOL)isDeltaUpdate
{
return [[propertiesDictionary objectForKey:@"enclosure"] objectForKey:@"sparkle:deltaFrom"] != nil;
}
- initWithDictionary:(NSDictionary *)dict
{
return [self initWithDictionary:dict failureReason:nil];
}
- initWithDictionary:(NSDictionary *)dict failureReason:(NSString**)error
{
self = [super init];
if (self)
@@ -117,7 +159,9 @@
// 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:@"sparkle:version"];
if (newVersion == nil) // no sparkle:version attribute
if( newVersion == nil )
newVersion = [dict objectForKey:@"sparkle:version"]; // UK 2007-08-31 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?
{
// 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.
@@ -125,38 +169,92 @@
if ([fileComponents count] > 1)
newVersion = [[fileComponents lastObject] stringByDeletingPathExtension];
}
if(!newVersion )
{
if (error)
*error = @"Feed item lacks sparkle:version attribute, and version couldn't be deduced from file name (would have used last component of a file name like AppName_1.3.4.zip)";
[self release];
return nil;
}
if (enclosure == nil || [enclosure objectForKey:@"url"] == nil || newVersion == nil)
{
[self release];
self = nil;
}
else
{
propertiesDictionary = [dict retain];
[self setTitle:[dict objectForKey:@"title"]];
[self setDate:[dict objectForKey:@"pubDate"]];
[self setDescription:[dict objectForKey:@"description"]];
[self setFileURL:[NSURL URLWithString:[[enclosure objectForKey:@"url"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
[self setDSASignature:[enclosure objectForKey:@"sparkle:dsaSignature"]];
[self setVersionString:newVersion];
[self setMinimumSystemVersion:[dict objectForKey:@"sparkle:minimumSystemVersion"]];
NSString *shortVersionString = [enclosure objectForKey:@"sparkle:shortVersionString"];
if (shortVersionString)
[self setDisplayVersionString:shortVersionString];
else
[self setDisplayVersionString:[self versionString]];
// Find the appropriate release notes URL.
if ([dict objectForKey:@"sparkle:releaseNotesLink"])
[self setReleaseNotesURL:[NSURL URLWithString:[dict objectForKey:@"sparkle:releaseNotesLink"]]];
else if ([[self description] hasPrefix:@"http://"]) // if the description starts with http://, use that.
[self setReleaseNotesURL:[NSURL URLWithString:[self description]]];
else
[self setReleaseNotesURL:nil];
propertiesDictionary = [[NSMutableDictionary alloc] initWithDictionary:dict];
[self setTitle:[dict objectForKey:@"title"]];
[self setDate:[dict objectForKey:@"pubDate"]];
[self setItemDescription:[dict objectForKey:@"description"]];
NSString* theInfoURL = [dict objectForKey:@"link"];
if( theInfoURL )
{
if( ![theInfoURL isKindOfClass: [NSString class]] )
SULog(@"SUAppcastItem -initWithDictionary: Info URL is not of valid type.");
else
[self setInfoURL:[NSURL URLWithString:theInfoURL]];
}
// Need an info URL or an enclosure URL. Former to show "More Info"
// page, latter to download & install:
if( !enclosure && !theInfoURL )
{
if (error)
*error = @"No enclosure in feed item";
[self release];
return nil;
}
NSString* enclosureURLString = [enclosure objectForKey:@"url"];
if( !enclosureURLString && !theInfoURL )
{
if (error)
*error = @"Feed item's enclosure lacks URL";
[self release];
return nil;
}
if( enclosureURLString )
[self setFileURL: [NSURL URLWithString: [enclosureURLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
if( enclosure )
[self setDSASignature:[enclosure objectForKey:@"sparkle:dsaSignature"]];
[self setVersionString: newVersion];
[self setMinimumSystemVersion: [dict objectForKey:@"sparkle:minimumSystemVersion"]];
[self setMaximumSystemVersion: [dict objectForKey:@"sparkle:maximumSystemVersion"]];
NSString *shortVersionString = [enclosure objectForKey:@"sparkle:shortVersionString"];
if (nil == shortVersionString)
shortVersionString = [dict objectForKey:@"sparkle:shortVersionString"]; // fall back on the <item>
if (shortVersionString)
[self setDisplayVersionString: shortVersionString];
else
[self setDisplayVersionString: [self versionString]];
// Find the appropriate release notes URL.
if ([dict objectForKey:@"sparkle:releaseNotesLink"])
[self setReleaseNotesURL:[NSURL URLWithString:[dict objectForKey:@"sparkle:releaseNotesLink"]]];
else if ([[self itemDescription] hasPrefix:@"http://"] || [[self itemDescription] hasPrefix:@"https://"]) // if the description starts with http:// or https:// use that.
[self setReleaseNotesURL:[NSURL URLWithString:[self itemDescription]]];
else
[self setReleaseNotesURL:nil];
if ([dict objectForKey:@"deltas"])
{
NSMutableDictionary *deltas = [NSMutableDictionary dictionary];
NSArray *deltaDictionaries = [dict objectForKey:@"deltas"];
NSEnumerator *deltaDictionariesEnum = [deltaDictionaries objectEnumerator];
NSDictionary *deltaDictionary;
while ((deltaDictionary = [deltaDictionariesEnum nextObject]))
{
NSMutableDictionary *fakeAppCastDict = [dict mutableCopy];
[fakeAppCastDict removeObjectForKey:@"deltas"];
[fakeAppCastDict setObject:deltaDictionary forKey:@"enclosure"];
SUAppcastItem *deltaItem = [[[self class] alloc] initWithDictionary:fakeAppCastDict];
[fakeAppCastDict release];
[deltas setObject:deltaItem forKey:[deltaDictionary objectForKey:@"sparkle:deltaFrom"]];
[deltaItem release];
}
[self setDeltaUpdates:deltas];
}
}
return self;
@@ -166,12 +264,14 @@
{
[self setTitle:nil];
[self setDate:nil];
[self setDescription:nil];
[self setItemDescription:nil];
[self setReleaseNotesURL:nil];
[self setDSASignature:nil];
[self setMinimumSystemVersion: nil];
[self setFileURL:nil];
[self setVersionString:nil];
[self setDisplayVersionString:nil];
[self setInfoURL:nil];
[propertiesDictionary release];
[super dealloc];
}
+5 -3
View File
@@ -18,17 +18,19 @@ typedef enum
SUDoNotInstallChoice
} SUAutomaticInstallationChoice;
@class SUAppcastItem;
@class SUAppcastItem, SUHost;
@interface SUAutomaticUpdateAlert : SUWindowController {
SUAppcastItem *updateItem;
id delegate;
NSBundle *hostBundle;
SUHost *host;
IBOutlet NSButton *automaticUpdateButton;
}
- (id)initWithAppcastItem:(SUAppcastItem *)item hostBundle:(NSBundle *)hostBundle delegate:delegate;
- (id)initWithAppcastItem:(SUAppcastItem *)item host:(SUHost *)hostBundle delegate:delegate;
- (IBAction)installNow:sender;
- (IBAction)installLater:sender;
- (IBAction)doNotInstall:sender;
- (IBAction)toggleAutomaticallyDownloadUpdate:(id)sender;
@end
+21 -8
View File
@@ -6,19 +6,20 @@
// Copyright 2006 Andy Matuschak. All rights reserved.
//
#import "Sparkle.h"
#import "SUAutomaticUpdateAlert.h"
#import "SUHost.h"
@implementation SUAutomaticUpdateAlert
- (id)initWithAppcastItem:(SUAppcastItem *)item hostBundle:(NSBundle *)hb delegate:del;
- (id)initWithAppcastItem:(SUAppcastItem *)item host:(SUHost *)aHost delegate:del;
{
self = [super initWithHostBundle:hb windowNibName:@"SUAutomaticUpdateAlert"];
self = [super initWithHost:aHost windowNibName:@"SUAutomaticUpdateAlert"];
if (self)
{
updateItem = [item retain];
delegate = del;
hostBundle = [hb retain];
host = [aHost retain];
[self setShouldCascadeWindows:NO];
[[self window] center];
}
@@ -27,11 +28,18 @@
- (void)dealloc
{
[hostBundle release];
[host release];
[updateItem release];
[super dealloc];
}
- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@, %@>", [self class], [host bundlePath], [host installationPath]]; }
- (IBAction)toggleAutomaticallyDownloadUpdate:(id)sender
{
BOOL shouldUpdateAutomatically = NSOnState == [automaticUpdateButton state] ? YES : NO;
[host setBool:shouldUpdateAutomatically forUserDefaultsKey:SUAutomaticallyUpdateKey];
}
- (IBAction)installNow:sender
{
@@ -53,17 +61,22 @@
- (NSImage *)applicationIcon
{
return [hostBundle icon];
return [host icon];
}
- (NSString *)titleText
{
return [NSString stringWithFormat:SULocalizedString(@"A new version of %@ is ready to install!", nil), [hostBundle name]];
return [NSString stringWithFormat:SULocalizedString(@"A new version of %@ is ready to install!", nil), [host name]];
}
- (NSString *)descriptionText
{
return [NSString stringWithFormat:SULocalizedString(@"%1$@ %2$@ has been downloaded and is ready to use! Would you like to install it and relaunch %1$@ now?", nil), [hostBundle name], [hostBundle displayVersion]];
return [NSString stringWithFormat:SULocalizedString(@"%1$@ %2$@ has been downloaded and is ready to use! Would you like to install it and relaunch %1$@ now?", nil), [host name], [updateItem displayVersionString]];
}
- (void)awakeFromNib
{
[automaticUpdateButton setState:[host boolForUserDefaultsKey:SUAutomaticallyUpdateKey] ? NSOnState : NSOffState];
}
@end
+3 -1
View File
@@ -13,7 +13,9 @@
#import "SUBasicUpdateDriver.h"
@class SUAutomaticUpdateAlert;
@interface SUAutomaticUpdateDriver : SUBasicUpdateDriver {
@interface SUAutomaticUpdateDriver : SUBasicUpdateDriver
{
@private
BOOL postponingInstallation, showErrors;
SUAutomaticUpdateAlert *alert;
}
+83 -25
View File
@@ -7,23 +7,94 @@
//
#import "SUAutomaticUpdateDriver.h"
#import "Sparkle.h"
#import "SUAutomaticUpdateAlert.h"
#import "SUHost.h"
#import "SUConstants.h"
#import "SUUpdater_Private.h"
#import "SUXPCURLDownload.h"
@implementation SUAutomaticUpdateDriver
// -------------------------------------------------------------------
#if SPARKLE_IS_COMPATIBLE_WITH_DEVMATE
static NSString * const kSUAutomaticUpdateParamName = @"autoupdate";
- (void)downloadReleaseNotesAndWaitUntilDone
{
NSURL *releaseNotesURL = [updateItem releaseNotesURL];
if (nil == releaseNotesURL || [releaseNotesURL isFileURL])
return;
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 updateURLRequestIfNeeds:request];
if (SUShouldUseXPCDownloader())
{
[SUXPCURLDownload sendSynchronousRequest:request delegate:nil];
}
else
{
[NSURLConnection sendSynchronousRequest:request returningResponse:NULL error:NULL];
}
}
- (void)didFindValidUpdate
{
// For correct DevMate statistics need to send request for Release Notes.
[self downloadReleaseNotesAndWaitUntilDone];
[super didFindValidUpdate];
}
#endif // SPARKLE_IS_COMPATIBLE_WITH_DEVMATE
// -------------------------------------------------------------------
- (BOOL)shouldShowUI
{
return showErrors;
}
- (void)unarchiverDidFinish:(SUUnarchiver *)ua
{
alert = [[SUAutomaticUpdateAlert alloc] initWithAppcastItem:updateItem hostBundle:hostBundle delegate:self];
if ([NSApp isActive])
[[alert window] makeKeyAndOrderFront:self];
else
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:) name:NSApplicationDidBecomeActiveNotification object:NSApp];
BOOL canAutomaticallyInstallUpdate = NO;
if ([[updater delegate] respondsToSelector:@selector(updater:canAutomaticallyInstallUpdate:)])
canAutomaticallyInstallUpdate = [[updater delegate] updater:updater canAutomaticallyInstallUpdate:updateItem];
if (!canAutomaticallyInstallUpdate)
{
showErrors = YES;
alert = [[SUAutomaticUpdateAlert alloc] initWithAppcastItem:updateItem host:host delegate:self];
// If the app is a menubar app or the like, we need to focus it first and alter the
// update prompt to behave like a normal window. Otherwise if the window were hidden
// there may be no way for the application to be activated to make it visible again.
if ([host isBackgroundApplication])
{
[[alert window] setHidesOnDeactivate:NO];
[NSApp activateIgnoringOtherApps:YES];
}
if ([NSApp isActive])
[[alert window] makeKeyAndOrderFront:self];
else
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:) name:NSApplicationDidBecomeActiveNotification object:NSApp];
}
else
{
[self automaticUpdateAlert:nil finishedWithChoice:SUInstallNowChoice];
}
}
- (void)applicationDidBecomeActive:(NSNotification *)aNotification
{
[[alert window] makeKeyAndOrderFront:self];
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"NSApplicationDidBecomeActiveNotification" object:NSApp];
[[NSNotificationCenter defaultCenter] removeObserver:self name:NSApplicationDidBecomeActiveNotification object:NSApp];
}
- (void)automaticUpdateAlert:(SUAutomaticUpdateAlert *)aua finishedWithChoice:(SUAutomaticInstallationChoice)choice;
@@ -31,7 +102,7 @@
switch (choice)
{
case SUInstallNowChoice:
[self installUpdate];
[self installWithToolAndRelaunch:YES];
break;
case SUInstallLaterChoice:
@@ -40,30 +111,17 @@
break;
case SUDoNotInstallChoice:
[[SUUserDefaults standardUserDefaults] setObject:[updateItem versionString] forKey:SUSkippedVersionKey];
[self abortUpdate];
[host setObject:[updateItem versionString] forUserDefaultsKey:SUSkippedVersionKey];
[self abortUpdate:SUUpdateAbortCanceledByUser];
break;
}
}
- (BOOL)shouldInstallSynchronously { return postponingInstallation; }
- (void)installUpdate
{
showErrors = YES;
[super installUpdate];
}
- (void)applicationWillTerminate:(NSNotification *)note
{
[self installUpdate];
}
- (void)installerFinishedForHostBundle:(NSBundle *)hb
{
if (hb != hostBundle) { return; }
if (!postponingInstallation)
[self relaunchHostApp];
[self installWithToolAndRelaunch:NO];
}
- (void)abortUpdateWithError:(NSError *)error
@@ -71,7 +129,7 @@
if (showErrors)
[super abortUpdateWithError:error];
else
[self abortUpdate];
[self abortUpdate:SUUpdateAbortGotError];
}
@end
+10 -10
View File
@@ -12,18 +12,19 @@
#import <Cocoa/Cocoa.h>
#import "SUUpdateDriver.h"
@class SUAppcastItem, SUUnarchiver, SUAppcast, SUUnarchiver;
@class SUAppcastItem, SUUnarchiver, SUAppcast, SUUnarchiver, SUHost;
@interface SUBasicUpdateDriver : SUUpdateDriver {
NSBundle *hostBundle;
SUAppcastItem *updateItem;
SUAppcastItem *nonDeltaUpdateItem;
NSURLDownload *download;
NSString *downloadPath;
NSString *tempDir;
NSString *relaunchPath;
}
- (void)checkForUpdatesAtURL:(NSURL *)appcastURL hostBundle:(NSBundle *)hb;
- (void)checkForUpdatesAtURL:(NSURL *)URL host:(SUHost *)host;
- (void)appcastDidFinishLoading:(SUAppcast *)ac;
- (void)appcast:(SUAppcast *)ac failedToLoadWithError:(NSError *)error;
@@ -35,6 +36,7 @@
- (void)didFindValidUpdate;
- (void)didNotFindUpdate;
- (void)updateURLRequestIfNeeds:(NSMutableURLRequest *)request;
- (void)downloadUpdate;
- (void)download:(NSURLDownload *)d decideDestinationWithSuggestedFilename:(NSString *)name;
- (void)downloadDidFinish:(NSURLDownload *)d;
@@ -43,15 +45,13 @@
- (void)extractUpdate;
- (void)unarchiverDidFinish:(SUUnarchiver *)ua;
- (void)unarchiverDidFail:(SUUnarchiver *)ua;
- (void)failedToApplyDeltaUpdate;
- (void)installUpdate;
- (void)installerFinishedForHostBundle:(NSBundle *)hb;
- (void)installerForHostBundle:(NSBundle *)hb failedWithError:(NSError *)error;
- (void)installWithToolAndRelaunch:(BOOL)relaunch;
- (void)installerForHost:(SUHost *)host failedWithError:(NSError *)error;
- (void)cleanUpDownload;
- (void)relaunchHostApp;
- (void)cleanUp;
- (void)abortUpdate;
- (void)abortUpdate:(SUUpdateAbortReason)reason;
- (void)abortUpdateWithError:(NSError *)error;
@end
+369 -119
View File
@@ -7,17 +7,37 @@
//
#import "SUBasicUpdateDriver.h"
#import "Sparkle.h"
#import "SUHost.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 "SUXPCInstaller.h"
#import "SUXPCURLDownload.h"
#if SPARKLE_IS_COMPATIBLE_WITH_DEVMATE
CF_EXPORT CFDictionaryRef DMCopyHTTPRequestHeaders(CFBundleRef appBundle, CFDataRef httpBodyData);
#endif
@interface SUBasicUpdateDriver () <NSURLDownloadDelegate>; @end
@implementation SUBasicUpdateDriver
- (void)checkForUpdatesAtURL:(NSURL *)appcastURL hostBundle:(NSBundle *)hb
- (void)checkForUpdatesAtURL:(NSURL *)URL host:(SUHost *)aHost
{
hostBundle = [hb retain];
if ([hostBundle isRunningFromDiskImage])
[super checkForUpdatesAtURL:URL host:aHost];
if ([aHost isRunningOnReadOnlyVolume])
{
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SURunningFromDiskImageError userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:SULocalizedString(@"%1$@ can't be updated when it's running from a disk image. Move %1$@ to your Applications folder, relaunch it from there, and try again.", nil), [hostBundle name]] forKey:NSLocalizedDescriptionKey]]];
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SURunningFromDiskImageError userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:SULocalizedString(@"%1$@ can't be updated when it's running from a read-only volume like a disk image or an optical drive. Move %1$@ to your Applications folder, relaunch it from there, and try again.", nil), [aHost name]] forKey:NSLocalizedDescriptionKey]]];
return;
}
@@ -26,18 +46,17 @@
[appcast release];
[appcast setDelegate:self];
[appcast setUserAgentString:[NSString stringWithFormat: @"%@/%@ Sparkle/1.5b4", [hostBundle name], [hostBundle displayVersion]]];
[appcast fetchAppcastFromURL:appcastURL];
[[SUUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:SULastCheckTimeKey];
[appcast setUserAgentString:[updater userAgentString]];
[appcast fetchAppcastFromURL:URL];
}
- (id <SUVersionComparison>)_versionComparator
- (id <SUVersionComparison>)versionComparator
{
id <SUVersionComparison> comparator = nil;
// Give the delegate a chance to provide a custom version comparator
if ([delegate respondsToSelector:@selector(versionComparatorForHostBundle:)])
comparator = [delegate versionComparatorForHostBundle:hostBundle];
if ([[updater delegate] respondsToSelector:@selector(versionComparatorForUpdater:)])
comparator = [[updater delegate] versionComparatorForUpdater:updater];
// If we don't get a comparator from the delegate, use the default comparator
if (!comparator)
@@ -48,20 +67,33 @@
- (BOOL)isItemNewer:(SUAppcastItem *)ui
{
return [[self _versionComparator] compareVersion:[hostBundle version] toVersion:[ui versionString]] == NSOrderedAscending;
return [[self versionComparator] compareVersion:[host version] toVersion:[ui versionString]] == NSOrderedAscending;
}
- (BOOL)hostSupportsItem:(SUAppcastItem *)ui
{
if ([ui minimumSystemVersion] == nil || [[ui minimumSystemVersion] isEqualToString:@""]) { return YES; }
return [[SUStandardVersionComparator defaultComparator] compareVersion:[ui minimumSystemVersion] toVersion:[NSWorkspace systemVersionString]] != NSOrderedDescending;
if (([ui minimumSystemVersion] == nil || [[ui minimumSystemVersion] isEqualToString:@""]) &&
([ui maximumSystemVersion] == nil || [[ui maximumSystemVersion] isEqualToString:@""])) { return YES; }
BOOL minimumVersionOK = TRUE;
BOOL maximumVersionOK = TRUE;
// Check minimum and maximum System Version
if ([ui minimumSystemVersion] != nil && ![[ui minimumSystemVersion] isEqualToString:@""]) {
minimumVersionOK = [[SUStandardVersionComparator defaultComparator] compareVersion:[ui minimumSystemVersion] toVersion:[SUHost systemVersionString]] != NSOrderedDescending;
}
if ([ui maximumSystemVersion] != nil && ![[ui maximumSystemVersion] isEqualToString:@""]) {
maximumVersionOK = [[SUStandardVersionComparator defaultComparator] compareVersion:[ui maximumSystemVersion] toVersion:[SUHost systemVersionString]] != NSOrderedAscending;
}
return minimumVersionOK && maximumVersionOK;
}
- (BOOL)itemContainsSkippedVersion:(SUAppcastItem *)ui
{
NSString *skippedVersion = [[SUUserDefaults standardUserDefaults] objectForKey:SUSkippedVersionKey];
NSString *skippedVersion = [host objectForUserDefaultsKey:SUSkippedVersionKey];
if (skippedVersion == nil) { return NO; }
return [[self _versionComparator] compareVersion:[ui versionString] toVersion:skippedVersion] != NSOrderedDescending;
return [[self versionComparator] compareVersion:[ui versionString] toVersion:skippedVersion] != NSOrderedDescending;
}
- (BOOL)itemContainsValidUpdate:(SUAppcastItem *)ui
@@ -71,25 +103,35 @@
- (void)appcastDidFinishLoading:(SUAppcast *)ac
{
if ([delegate respondsToSelector:@selector(appcastDidFinishLoading:forHostBundle:)])
[delegate appcastDidFinishLoading:ac forHostBundle:hostBundle];
if ([[updater delegate] respondsToSelector:@selector(updater:didFinishLoadingAppcast:)])
[[updater delegate] updater:updater didFinishLoadingAppcast:ac];
SUAppcastItem *item = nil;
// Now we have to find the best valid update in the appcast.
if ([delegate respondsToSelector:@selector(bestValidUpdateInAppcast:forHostBundle:)]) // Does the delegate want to handle it?
if ([[updater delegate] respondsToSelector:@selector(bestValidUpdateInAppcast:forUpdater:)]) // Does the delegate want to handle it?
{
updateItem = [delegate bestValidUpdateInAppcast:ac forHostBundle:hostBundle];
item = [[updater delegate] bestValidUpdateInAppcast:ac forUpdater:updater];
}
else // If not, we'll take care of it ourselves.
{
// Find the first update we can actually use.
NSEnumerator *updateEnumerator = [[ac items] objectEnumerator];
do {
updateItem = [updateEnumerator nextObject];
} while (updateItem && ![self hostSupportsItem:updateItem]);
[updateItem retain];
item = [updateEnumerator nextObject];
} while (item && ![self hostSupportsItem:item]);
if (binaryDeltaSupported()) {
SUAppcastItem *deltaUpdateItem = [[item deltaUpdates] objectForKey:[host version]];
if (deltaUpdateItem && [self hostSupportsItem:deltaUpdateItem]) {
nonDeltaUpdateItem = [item retain];
item = deltaUpdateItem;
}
}
}
CFRelease(ac); // Remember that we're explicitly managing the memory of the appcast.
updateItem = [item retain];
if (ac) { CFRelease(ac); } // Remember that we're explicitly managing the memory of the appcast.
if (updateItem == nil) { [self didNotFindUpdate]; return; }
if ([self itemContainsValidUpdate:updateItem])
@@ -100,46 +142,97 @@
- (void)appcast:(SUAppcast *)ac failedToLoadWithError:(NSError *)error
{
CFRelease(ac); // Remember that we're explicitly managing the memory of the appcast.
if (ac) { CFRelease(ac); } // Remember that we're explicitly managing the memory of the appcast.
[self abortUpdateWithError:error];
}
- (void)appcast:(SUAppcast *)appcast willFetchURLRequest:(NSMutableURLRequest *)request
{
[self updateURLRequestIfNeeds:request];
}
- (void)updateURLRequestIfNeeds:(NSMutableURLRequest *)request
{
#if SPARKLE_IS_COMPATIBLE_WITH_DEVMATE
CFBundleRef hostBundle = CFBundleCreate(kCFAllocatorDefault, (CFURLRef)[NSURL fileURLWithPath:[host bundlePath]]);
NSDictionary *devmateHeaders = (NSDictionary *)DMCopyHTTPRequestHeaders(hostBundle, NULL) ? : [NSDictionary new];
[request setAllHTTPHeaderFields:(NSDictionary *)devmateHeaders];
[devmateHeaders release];
if (NULL != hostBundle)
CFRelease(hostBundle);
#endif
}
- (void)didFindValidUpdate
{
if ([delegate respondsToSelector:@selector(didFindValidUpdate:toHostBundle:)])
[delegate didFindValidUpdate:updateItem toHostBundle:hostBundle];
if ([[updater delegate] respondsToSelector:@selector(updater:didFindValidUpdate:)])
[[updater delegate] updater:updater didFindValidUpdate:updateItem];
[self downloadUpdate];
}
- (void)didNotFindUpdate
{
if ([delegate respondsToSelector:@selector(didNotFindUpdateToHostBundle:)])
[delegate didNotFindUpdateToHostBundle:hostBundle];
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUNoUpdateError userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:SULocalizedString(@"You already have the newest version of %@.", nil), [hostBundle name]] forKey:NSLocalizedDescriptionKey]]];
if ([[updater delegate] respondsToSelector:@selector(updaterDidNotFindUpdate:)])
[[updater delegate] updaterDidNotFindUpdate:updater];
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUNoUpdateError userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:SULocalizedString(@"You already have the newest version of %@.", nil), [host name]] forKey:NSLocalizedDescriptionKey]]];
}
- (void)downloadUpdate
{
download = [[NSURLDownload alloc] initWithRequest:[NSURLRequest requestWithURL:[updateItem fileURL]] delegate:self];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[updateItem fileURL]];
[request setValue:[updater userAgentString] forHTTPHeaderField:@"User-Agent"];
[self updateURLRequestIfNeeds:request];
if (SUShouldUseXPCDownloader())
download = (NSURLDownload *)[[SUXPCURLDownload alloc] initWithRequest:request delegate:self];
else
download = [[NSURLDownload alloc] initWithRequest:request delegate:self];
}
- (void)download:(NSURLDownload *)d decideDestinationWithSuggestedFilename:(NSString *)name
{
if (SUShouldUseXPCDownloader())
{
// The downloader will determine a file name, somewhere within our sandbox.
downloadPath = nil;
[d setDestination:name allowOverwrite:YES];
return;
}
// If name ends in .txt, the server probably has a stupid MIME configuration. We'll give the developer the benefit of the doubt and chop that off.
if ([[name pathExtension] isEqualToString:@"txt"])
name = [name stringByDeletingPathExtension];
// We create a temporary directory in /tmp and stick the file there.
// Not using a GUID here because hdiutil for some reason chokes on GUIDs. Too long? I really have no idea.
NSString *prefix = [NSString stringWithFormat:@"%@ %@ Update", [hostBundle name], [hostBundle version]];
NSString *tempDir = [NSTemporaryDirectory() stringByAppendingPathComponent:prefix];
NSString *downloadFileName = [NSString stringWithFormat:@"%@ %@", [host name], [updateItem versionString]];
[tempDir release];
tempDir = [[[host appSupportPath] stringByAppendingPathComponent:downloadFileName] retain];
int cnt=1;
while ([[NSFileManager defaultManager] fileExistsAtPath:tempDir] && cnt <= 999999)
tempDir = [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"%@ %d", prefix, cnt++]];
BOOL success = [[NSFileManager defaultManager] createDirectoryAtPath:tempDir attributes:nil];
while ([[NSFileManager defaultManager] fileExistsAtPath:tempDir] && cnt <= 999)
{
[tempDir release];
tempDir = [[[host appSupportPath] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@ %d", downloadFileName, cnt++]] retain];
}
// Create the temporary directory if necessary.
#if MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_4
BOOL success = YES;
NSEnumerator *pathComponentEnumerator = [[tempDir pathComponents] objectEnumerator];
NSString *pathComponentAccumulator = @"";
NSString *currentPathComponent;
while ((currentPathComponent = [pathComponentEnumerator nextObject])) {
pathComponentAccumulator = [pathComponentAccumulator stringByAppendingPathComponent:currentPathComponent];
if ([[NSFileManager defaultManager] fileExistsAtPath:pathComponentAccumulator]) continue;
success &= [[NSFileManager defaultManager] createDirectoryAtPath:pathComponentAccumulator attributes:nil];
}
#else
BOOL success = [[NSFileManager defaultManager] createDirectoryAtPath:tempDir withIntermediateDirectories:YES attributes:nil error:NULL];
#endif
if (!success)
{
// Okay, something's really broken with /tmp
// Okay, something's really broken with this user's file structure.
[download cancel];
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUTemporaryDirectoryError userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"Can't make a temporary directory for the update download at %@.",tempDir] forKey:NSLocalizedDescriptionKey]]];
}
@@ -148,35 +241,52 @@
[download setDestination:downloadPath allowOverwrite:YES];
}
- (void)downloadDidFinish:(NSURLDownload *)d
- (void)download:(NSURLDownload *)download didCreateDestination:(NSString *)path {
[downloadPath autorelease];
downloadPath = [path retain];
[tempDir autorelease];
tempDir = [[downloadPath stringByDeletingLastPathComponent] retain];
}
- (BOOL)validateUpdateDownloadedToPath:(NSString *)downloadedPath extractedToPath:(NSString *)extractedPath DSASignature:(NSString *)DSASignature publicDSAKey:(NSString *)publicDSAKey
{
NSString *newBundlePath = [SUInstaller appPathInUpdateFolder:extractedPath forHost:host];
if (newBundlePath)
{
NSError *error = nil;
if ([SUCodeSigningVerifier codeSignatureIsValidAtPath:newBundlePath error:&error]) {
return YES;
} else {
SULog(@"Code signature check on update failed: %@", error);
}
}
return [SUDSAVerifier validatePath:downloadedPath withEncodedDSASignature:DSASignature withPublicDSAKey:publicDSAKey];
}
- (void)downloadDidFinish:(NSURLDownload *)d
{
[self extractUpdate];
}
- (void)download:(NSURLDownload *)download didFailWithError:(NSError *)error
{
// Get rid of what we've downloaded so far, if anything.
if (downloadPath != nil)
[[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:[downloadPath stringByDeletingLastPathComponent] destination:@"" files:[NSArray arrayWithObject:[downloadPath lastPathComponent]] tag:NULL];
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SURelaunchError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:SULocalizedString(@"An error occurred while downloading the update. Please try again later.", nil), NSLocalizedDescriptionKey, [error localizedDescription], NSLocalizedFailureReasonErrorKey, nil]]];
}
- (BOOL)download:(NSURLDownload *)download shouldDecodeSourceDataOfMIMEType:(NSString *)encodingType
{
// We don't want the download system to extract our gzips.
// Note that we use a substring matching here instead of direct comparison because the docs say "application/gzip" but the system *uses* "application/x-gzip". This is a documentation bug.
return ([encodingType rangeOfString:@"gzip"].location == NSNotFound);
}
- (void)extractUpdate
{
// DSA verification, if activated by the developer
if ([[hostBundle objectForInfoDictionaryKey:SUExpectsDSASignatureKey] boolValue])
{
if (![[NSFileManager defaultManager] validatePath:downloadPath withEncodedDSASignature:[updateItem DSASignature] withPublicDSAKey:[hostBundle publicDSAKey]])
{
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUSignatureError userInfo:[NSDictionary dictionaryWithObject:@"The update is improperly signed." forKey:NSLocalizedDescriptionKey]]];
return;
}
}
SUUnarchiver *unarchiver = [SUUnarchiver unarchiverForURL:[[[NSURL alloc] initFileURLWithPath:downloadPath] autorelease]];
SUUnarchiver *unarchiver = [SUUnarchiver unarchiverForPath:downloadPath updatingHost:host];
if (!unarchiver)
{
NSLog(@"Sparkle Error: No valid unarchiver for %@!", downloadPath);
SULog(@"Sparkle Error: No valid unarchiver for %@!", downloadPath);
[self unarchiverDidFail:nil];
return;
}
@@ -185,108 +295,248 @@
[unarchiver start];
}
- (void)failedToApplyDeltaUpdate
{
// When a delta update fails to apply we fall back on updating via a full install.
[updateItem release];
updateItem = nonDeltaUpdateItem;
nonDeltaUpdateItem = nil;
[self downloadUpdate];
}
- (void)unarchiverDidFinish:(SUUnarchiver *)ua
{
if (ua) { CFRelease(ua); }
[self installUpdate];
[self installWithToolAndRelaunch:YES];
}
- (void)unarchiverDidFail:(SUUnarchiver *)ua
{
if (ua) { CFRelease(ua); }
if ([updateItem isDeltaUpdate]) {
[self failedToApplyDeltaUpdate];
return;
}
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:[NSDictionary dictionaryWithObject:SULocalizedString(@"An error occurred while extracting the archive. Please try again later.", nil) forKey:NSLocalizedDescriptionKey]]];
}
- (BOOL)shouldInstallSynchronously { return NO; }
- (void)installUpdate
- (void)installWithToolAndRelaunch:(BOOL)relaunch
{
if ([delegate respondsToSelector:@selector(updateWillInstall:toHostBundle:)])
[delegate updateWillInstall:updateItem toHostBundle:hostBundle];
// Copy the relauncher into a temporary directory so we can get to it after the new version's installed.
NSString *relaunchPathToCopy = [[NSBundle bundleForClass:[self class]] pathForResource:@"relaunch" ofType:@""];
NSString *targetPath = [NSTemporaryDirectory() stringByAppendingPathComponent:[relaunchPathToCopy lastPathComponent]];
// Only the paranoid survive: if there's already a stray copy of relaunch there, we would have problems
[[NSFileManager defaultManager] removeFileAtPath:targetPath handler:nil];
if ([[NSFileManager defaultManager] copyPath:relaunchPathToCopy toPath:targetPath handler:nil])
relaunchPath = [targetPath retain];
[SUInstaller installFromUpdateFolder:[downloadPath stringByDeletingLastPathComponent] overHostBundle:hostBundle delegate:self synchronously:[self shouldInstallSynchronously]];
}
- (void)installerFinishedForHostBundle:(NSBundle *)hb
{
if (hb != hostBundle) { return; }
[self relaunchHostApp];
}
- (void)relaunchHostApp
{
// Give the host app an opportunity to postpone the relaunch.
static BOOL postponedOnce = NO;
if (!postponedOnce && [delegate respondsToSelector:@selector(shouldPostponeRelaunchForUpdate:toHostBundle:untilInvoking:)])
{
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[[[self class] instanceMethodSignatureForSelector:@selector(relaunchHostApp)] retain]];
[invocation setSelector:@selector(relaunchHostApp)];
[invocation setTarget:self];
postponedOnce = YES;
if ([delegate shouldPostponeRelaunchForUpdate:updateItem toHostBundle:hostBundle untilInvoking:invocation])
return;
#if !ENDANGER_USERS_WITH_INSECURE_UPDATES
if (![self validateUpdateDownloadedToPath:downloadPath extractedToPath:tempDir DSASignature:[updateItem DSASignature] publicDSAKey:[host publicDSAKey]])
{
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUSignatureError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:SULocalizedString(@"An error occurred while extracting the archive. Please try again later.", nil), NSLocalizedDescriptionKey, @"The update is improperly signed.", NSLocalizedFailureReasonErrorKey, nil]]];
return;
}
#endif
if (![updater mayUpdateAndRestart])
{
[self abortUpdate:SUUpdateAbortForbiddenByDelegate];
return;
}
// Give the host app an opportunity to postpone the install and relaunch.
static BOOL postponedOnce = NO;
if (!postponedOnce && [[updater delegate] respondsToSelector:@selector(updater:shouldPostponeRelaunchForUpdate:untilInvoking:)])
{
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[[self class] instanceMethodSignatureForSelector:@selector(installWithToolAndRelaunch:)]];
[invocation setSelector:@selector(installWithToolAndRelaunch:)];
[invocation setArgument:&relaunch atIndex:2];
[invocation setTarget:self];
postponedOnce = YES;
if ([[updater delegate] updater:updater shouldPostponeRelaunchForUpdate:updateItem untilInvoking:invocation])
return;
}
[self cleanUp]; // Clean up the download and extracted files.
if ([[updater delegate] respondsToSelector:@selector(updater:willInstallUpdate:)])
[[updater delegate] updater:updater willInstallUpdate:updateItem];
SUFinishUpdateTask finishTasks = SUFinishUpdateWithDefaultInstallation;
BOOL shouldRelaunch = YES;
if ([[updater delegate] respondsToSelector:@selector(updater:overrideInstallUpdate:downloadPath:shouldRelaunch:)] &&
[[updater delegate] updater:updater overrideInstallUpdate:updateItem downloadPath:tempDir shouldRelaunch:&shouldRelaunch])
{
finishTasks = finishTasks & (~SUFinishUpdateWithInstall);
relaunch = relaunch && shouldRelaunch;
}
if (!relaunch)
{
finishTasks = finishTasks & (~SUFinishUpdateWithRelaunch);
}
[[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterWillRestartNotification object:self];
if ([delegate respondsToSelector:@selector(updaterWillRelaunchApplication)])
[delegate updaterWillRelaunchApplication];
if (SUFinishUpdateAbort == finishTasks)
{
[self abortUpdate:SUUpdateAbortTasksFinished];
if ([[updater delegate] respondsToSelector:@selector(updater:didInstallUpdate:)])
[[updater delegate] updater:updater didInstallUpdate:updateItem];
return;
}
// Copy the relauncher into a temporary directory so we can get to it after the new version's installed.
NSString *relaunchPathToCopy = [SPARKLE_BUNDLE pathForResource:@"finish_installation" ofType:@"app"];
NSString *targetPath = [[host appSupportPath] 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:[NSDictionary dictionary]
error:&error];
// Only the paranoid survive: if there's already a stray copy of relaunch there, we would have problems.
BOOL copiedRelaunchTool = NO;
if (SUShouldUseXPCInstaller())
{
copiedRelaunchTool = [SUXPCInstaller copyPathWithAuthentication:relaunchPathToCopy overPath:targetPath temporaryName:nil error:&error];
}
else
{
copiedRelaunchTool = [SUPlainInstaller copyPathWithAuthentication:relaunchPathToCopy overPath:targetPath temporaryName:nil error:&error];
}
[self finishRelaunchAfterSuccessfulCopying:copiedRelaunchTool fromPath:relaunchPathToCopy toPath:targetPath finishTaskMask:finishTasks];
}
- (void)finishRelaunchAfterSuccessfulCopying:(BOOL)copiedRelaunchTool fromPath:(NSString *)relaunchPathToCopy toPath:(NSString *)targetPath finishTaskMask:(SUFinishUpdateTask)taskMask
{
NSError *error = nil;
if (copiedRelaunchTool)
{
relaunchPath = [targetPath retain];
}
else
{
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SURelaunchError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:SULocalizedString(@"An error occurred while extracting the archive. Please try again later.", nil), NSLocalizedDescriptionKey, [NSString stringWithFormat:@"Couldn't copy relauncher (%@) to temporary path (%@)! %@", relaunchPathToCopy, targetPath, (error ? [error localizedDescription] : @"")], NSLocalizedFailureReasonErrorKey, nil]]];
}
if(!relaunchPath || ![[NSFileManager defaultManager] fileExistsAtPath:relaunchPath])
NSString *pathToRelaunch = @"";
BOOL shouldFinishUpdateWithRelaunch = (taskMask & SUFinishUpdateWithRelaunch) != 0;
if (shouldFinishUpdateWithRelaunch)
{
[[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterWillRestartNotification object:self];
if ([[updater delegate] respondsToSelector:@selector(updaterWillRelaunchApplication:)])
{
[[updater delegate] updaterWillRelaunchApplication:updater];
}
pathToRelaunch = [host bundlePath];
if ([[updater delegate] respondsToSelector:@selector(pathToRelaunchForUpdater:)])
{
pathToRelaunch = [[updater delegate] pathToRelaunchForUpdater:updater];
}
}
if(!relaunchPath || ![[NSFileManager defaultManager] fileExistsAtPath:relaunchPath])
{
// 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:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:SULocalizedString(@"An error occurred while relaunching %1$@, but the new version will be available next time you run %1$@.", nil), [host name]], NSLocalizedDescriptionKey, [NSString stringWithFormat:@"Couldn't find the relauncher (expected to find it at %@)", relaunchPath], NSLocalizedFailureReasonErrorKey, nil]]];
// We intentionally don't abandon the update here so that the host won't initiate another.
return;
}
NSString *relaunchToolPath = [relaunchPath stringByAppendingPathComponent: @"/Contents/MacOS/finish_installation"];
NSArray *arguments = [NSArray arrayWithObjects:
[host bundlePath],
pathToRelaunch,
[NSString stringWithFormat:@"%d", [[NSProcessInfo processInfo] processIdentifier]],
tempDir,
[NSString stringWithFormat:@"%lu", taskMask],
nil];
if (SUShouldUseXPCInstaller())
{
[SUXPCInstaller launchTaskWithPath:relaunchToolPath
arguments:arguments
environment:nil
currentDirectoryPath:nil
inputData:nil
waitForTaskResult:!shouldFinishUpdateWithRelaunch
waitUntilDone:YES
completionHandler:nil];
}
else
{
NSTask *task = [NSTask launchedTaskWithLaunchPath:relaunchToolPath arguments:arguments];
if (!shouldFinishUpdateWithRelaunch)
[task waitUntilExit];
}
if (shouldFinishUpdateWithRelaunch)
{
[NSApp terminate:nil];
}
else
{
[self abortUpdate:SUUpdateAbortTasksFinished];
if ([[updater delegate] respondsToSelector:@selector(updater:didInstallUpdate:)])
[[updater delegate] updater:updater didInstallUpdate:updateItem];
}
}
- (void)cleanUpDownload
{
if (tempDir != nil) // tempDir contains downloadPath, so we implicitly delete both here.
{
// 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:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:SULocalizedString(@"An error occurred while relaunching %1$@, but the new version will be available next time you run %1$@.", nil), [[NSBundle mainBundle] name]], NSLocalizedDescriptionKey, [NSString stringWithFormat:@"Couldn't find the relauncher (expected to find it at %@)", relaunchPath], NSLocalizedFailureReasonErrorKey, nil]]];
// We intentionally don't abandon the update here so that the host won't initiate another.
return;
}
[NSTask launchedTaskWithLaunchPath:relaunchPath arguments:[NSArray arrayWithObjects:[hostBundle bundlePath], [NSString stringWithFormat:@"%d", [[NSProcessInfo processInfo] processIdentifier]], nil]];
[NSApp terminate:self];
BOOL success = NO;
#if MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_4
success = [[NSFileManager defaultManager] removeFileAtPath: tempDir handler: nil]; // Clean up the copied relauncher
#else
NSError * error = nil;
success = [[NSFileManager defaultManager] removeItemAtPath: tempDir error: &error]; // Clean up the copied relauncher
#endif
if( !success )
[[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:[tempDir stringByDeletingLastPathComponent] destination:@"" files:[NSArray arrayWithObject:[tempDir lastPathComponent]] tag:NULL];
}
}
- (void)cleanUp
- (void)installerForHost:(SUHost *)aHost failedWithError:(NSError *)error
{
[[NSFileManager defaultManager] removeFileAtPath:[downloadPath stringByDeletingLastPathComponent] handler:nil];
}
- (void)installerForHostBundle:(NSBundle *)hb failedWithError:(NSError *)error
{
if (hb != hostBundle) { return; }
[[NSFileManager defaultManager] removeFileAtPath:relaunchPath handler:NULL]; // Clean up the copied relauncher.
if (aHost != host) { return; }
#if MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_4
[[NSFileManager defaultManager] removeFileAtPath: relaunchPath handler: nil]; // Clean up the copied relauncher
#else
NSError * dontThrow = nil;
[[NSFileManager defaultManager] removeItemAtPath: relaunchPath error: &dontThrow]; // Clean up the copied relauncher
#endif
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:SULocalizedString(@"An error occurred while installing the update. Please try again later.", nil), NSLocalizedDescriptionKey, [error localizedDescription], NSLocalizedFailureReasonErrorKey, nil]]];
}
- (void)abortUpdate
- (void)abortUpdate:(SUUpdateAbortReason)reason
{
[[self retain] autorelease]; // In case the notification center was the last one holding on to us.
[self cleanUpDownload];
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super abortUpdate];
[super abortUpdate:reason];
}
- (void)abortUpdateWithError:(NSError *)error
{
if ([error code] != SUNoUpdateError) // Let's not bother logging this.
NSLog(@"Sparkle Error: %@", [error localizedDescription]);
SULog(@"Sparkle Error: %@", [error localizedDescription]);
if ([error localizedFailureReason])
NSLog(@"Sparkle Error (continued): %@", [error localizedFailureReason]);
SULog(@"Sparkle Error (continued): %@", [error localizedFailureReason]);
if (download)
[download cancel];
[self abortUpdate];
[self abortUpdate:SUUpdateAbortGotError];
}
- (void)dealloc
{
[hostBundle release];
[updateItem release];
[nonDeltaUpdateItem release];
[download release];
[downloadPath release];
[tempDir release];
[relaunchPath release];
[super dealloc];
}
+15
View File
@@ -0,0 +1,15 @@
//
// SUBinaryDeltaApply.h
// Sparkle
//
// Created by Mark Rowe on 2009-06-01.
// Copyright 2009 Mark Rowe. All rights reserved.
//
#ifndef SUBINARYDELTAAPPLY_H
#define SUBINARYDELTAAPPLY_H
@class NSString;
int applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFile);
#endif
+101
View File
@@ -0,0 +1,101 @@
//
// SUBinaryDeltaApply.m
// Sparkle
//
// Created by Mark Rowe on 2009-06-01.
// Copyright 2009 Mark Rowe. All rights reserved.
//
#import "SUBinaryDeltaApply.h"
#import "SUBinaryDeltaCommon.h"
#import <CommonCrypto/CommonDigest.h>
#import <Foundation/Foundation.h>
#import <bspatch.h>
#import <stdio.h>
#import <stdlib.h>
#import <xar/xar.h>
static void applyBinaryDeltaToFile(xar_t x, xar_file_t file, NSString *sourceFilePath, NSString *destinationFilePath)
{
NSString *patchFile = temporaryFilename(@"apply-binary-delta");
xar_extract_tofile(x, file, [patchFile fileSystemRepresentation]);
const char *argv[] = {"/usr/bin/bspatch", [sourceFilePath fileSystemRepresentation], [destinationFilePath fileSystemRepresentation], [patchFile fileSystemRepresentation]};
bspatch(4, (char **)argv);
unlink([patchFile fileSystemRepresentation]);
}
int applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFile)
{
xar_t x = xar_open([patchFile UTF8String], READ);
if (!x) {
fprintf(stderr, "Unable to open %s. Giving up.\n", [patchFile UTF8String]);
return 1;
}
NSString *expectedBeforeHash = nil;
NSString *expectedAfterHash = nil;
xar_subdoc_t subdoc;
for (subdoc = xar_subdoc_first(x); subdoc; subdoc = xar_subdoc_next(subdoc)) {
if (!strcmp(xar_subdoc_name(subdoc), "binary-delta-attributes")) {
const char *value = 0;
xar_subdoc_prop_get(subdoc, "before-sha1", &value);
if (value)
expectedBeforeHash = [NSString stringWithUTF8String:value];
xar_subdoc_prop_get(subdoc, "after-sha1", &value);
if (value)
expectedAfterHash = [NSString stringWithUTF8String:value];
}
}
if (!expectedBeforeHash || !expectedAfterHash) {
fprintf(stderr, "Unable to find before-sha1 or after-sha1 metadata in delta. Giving up.\n");
return 1;
}
fprintf(stderr, "Verifying source... ");
NSString *beforeHash = hashOfTree(source);
if (![beforeHash isEqualToString:expectedBeforeHash]) {
fprintf(stderr, "Source doesn't have expected hash (%s != %s). Giving up.\n", [expectedBeforeHash UTF8String], [beforeHash UTF8String]);
return 1;
}
fprintf(stderr, "\nCopying files... ");
removeTree(destination);
copyTree(source, destination);
fprintf(stderr, "\nPatching... ");
xar_file_t file;
xar_iter_t iter = xar_iter_new();
for (file = xar_file_first(x, iter); file; file = xar_file_next(iter)) {
NSString *path = [NSString stringWithUTF8String:xar_get_path(file)];
NSString *sourceFilePath = [source stringByAppendingPathComponent:path];
NSString *destinationFilePath = [destination stringByAppendingPathComponent:path];
const char *value;
if (!xar_prop_get(file, "delete", &value) || !xar_prop_get(file, "delete-then-extract", &value)) {
removeTree(destinationFilePath);
if (!xar_prop_get(file, "delete", &value))
continue;
}
if (!xar_prop_get(file, "binary-delta", &value))
applyBinaryDeltaToFile(x, file, sourceFilePath, destinationFilePath);
else
xar_extract_tofile(x, file, [destinationFilePath fileSystemRepresentation]);
}
xar_close(x);
fprintf(stderr, "\nVerifying destination... ");
NSString *afterHash = hashOfTree(destination);
if (![afterHash isEqualToString:expectedAfterHash]) {
fprintf(stderr, "Destination doesn't have expected hash (%s != %s). Giving up.\n", [expectedAfterHash UTF8String], [afterHash UTF8String]);
removeTree(destination);
return 1;
}
fprintf(stderr, "\nDone!\n");
return 0;
}
+26
View File
@@ -0,0 +1,26 @@
//
// SUBinaryDeltaCommon.h
// Sparkle
//
// Created by Mark Rowe on 2009-06-01.
// Copyright 2009 Mark Rowe. All rights reserved.
//
#ifndef SUBINARYDELTACOMMON_H
#define SUBINARYDELTACOMMON_H
#include <fts.h>
@class NSString;
@class NSData;
extern int binaryDeltaSupported(void);
extern int compareFiles(const FTSENT **a, const FTSENT **b);
extern NSData *hashOfFile(FTSENT *ent);
extern NSString *hashOfTree(NSString *path);
extern void removeTree(NSString *path);
extern void copyTree(NSString *source, NSString *dest);
extern NSString *pathRelativeToDirectory(NSString *directory, NSString *path);
NSString *temporaryFilename(NSString *base);
#endif
+165
View File
@@ -0,0 +1,165 @@
//
// SUBinaryDeltaCommon.m
// Sparkle
//
// Created by Mark Rowe on 2009-06-01.
// Copyright 2009 Mark Rowe. All rights reserved.
//
#include "SUBinaryDeltaCommon.h"
#include <CommonCrypto/CommonDigest.h>
#include <Foundation/Foundation.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/param.h>
#include <sys/stat.h>
extern int xar_close(void*) __attribute__((weak_import));
int binaryDeltaSupported(void)
{
// OS X 10.4 didn't include libxar, so we link against it weakly.
// This checks whether libxar is available at runtime.
return xar_close != 0;
}
int compareFiles(const FTSENT **a, const FTSENT **b)
{
return strcoll((*a)->fts_name, (*b)->fts_name);
}
NSString *pathRelativeToDirectory(NSString *directory, NSString *path)
{
NSUInteger directoryLength = [directory length];
if ([path hasPrefix:directory])
return [path substringFromIndex:directoryLength];
return path;
}
NSString *temporaryFilename(NSString *base)
{
NSString *template = [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.XXXXXXXXXX", base]];
char buffer[MAXPATHLEN];
strcpy(buffer, [template fileSystemRepresentation]);
return [NSString stringWithUTF8String:mktemp(buffer)];
}
static void _hashOfBuffer(unsigned char *hash, const char* buffer, size_t bufferLength)
{
assert(bufferLength <= UINT32_MAX);
CC_SHA1_CTX hashContext;
CC_SHA1_Init(&hashContext);
CC_SHA1_Update(&hashContext, buffer, (CC_LONG)bufferLength);
CC_SHA1_Final(hash, &hashContext);
}
static void _hashOfFile(unsigned char* hash, FTSENT *ent)
{
if (ent->fts_info == FTS_SL) {
char linkDestination[MAXPATHLEN + 1];
ssize_t linkDestinationLength = readlink(ent->fts_path, linkDestination, MAXPATHLEN);
if (linkDestinationLength < 0) {
perror("readlink");
return;
}
_hashOfBuffer(hash, linkDestination, linkDestinationLength);
return;
}
if (ent->fts_info == FTS_F) {
int fileDescriptor = open(ent->fts_path, O_RDONLY);
if (fileDescriptor == -1) {
perror("open");
return;
}
size_t fileSize = (size_t)ent->fts_statp->st_size;
if (fileSize == 0) {
_hashOfBuffer(hash, NULL, 0);
close(fileDescriptor);
return;
}
void *buffer = mmap(0, fileSize, PROT_READ, MAP_FILE | MAP_PRIVATE, fileDescriptor, 0);
if (buffer == (void*)-1) {
close(fileDescriptor);
perror("mmap");
return;
}
_hashOfBuffer(hash, buffer, fileSize);
munmap(buffer, fileSize);
close(fileDescriptor);
return;
}
if (ent->fts_info == FTS_D)
memset(hash, 0xdd, CC_SHA1_DIGEST_LENGTH);
}
NSData *hashOfFile(FTSENT *ent)
{
unsigned char fileHash[CC_SHA1_DIGEST_LENGTH];
_hashOfFile(fileHash, ent);
return [NSData dataWithBytes:fileHash length:CC_SHA1_DIGEST_LENGTH];
}
NSString *hashOfTree(NSString *path)
{
const char *sourcePaths[] = {[path UTF8String], 0};
FTS *fts = fts_open((char* const*)sourcePaths, FTS_PHYSICAL | FTS_NOCHDIR, compareFiles);
if (!fts) {
perror("fts_open");
return nil;
}
CC_SHA1_CTX hashContext;
CC_SHA1_Init(&hashContext);
FTSENT *ent = 0;
while ((ent = fts_read(fts))) {
if (ent->fts_info != FTS_F && ent->fts_info != FTS_SL)
continue;
unsigned char fileHash[CC_SHA1_DIGEST_LENGTH];
_hashOfFile(fileHash, ent);
CC_SHA1_Update(&hashContext, fileHash, sizeof(fileHash));
NSString *relativePath = pathRelativeToDirectory(path, [NSString stringWithUTF8String:ent->fts_path]);
NSData *relativePathBytes = [relativePath dataUsingEncoding:NSUTF8StringEncoding];
CC_SHA1_Update(&hashContext, [relativePathBytes bytes], (uint32_t)[relativePathBytes length]);
}
fts_close(fts);
unsigned char hash[CC_SHA1_DIGEST_LENGTH];
CC_SHA1_Final(hash, &hashContext);
char hexHash[CC_SHA1_DIGEST_LENGTH * 2 + 1];
size_t i;
for (i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
sprintf(hexHash + i * 2, "%02x", hash[i]);
return [NSString stringWithUTF8String:hexHash];
}
void removeTree(NSString *path)
{
#if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4
[[NSFileManager defaultManager] removeItemAtPath:path error:0];
#else
[[NSFileManager defaultManager] removeFileAtPath:path handler:nil];
#endif
}
void copyTree(NSString *source, NSString *dest)
{
#if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4
[[NSFileManager defaultManager] copyItemAtPath:source toPath:dest error:0];
#else
[[NSFileManager defaultManager] copyPath:source toPath:dest handler:nil];
#endif
}
+269
View File
@@ -0,0 +1,269 @@
//
// SUBinaryDeltaTool.m
// Sparkle
//
// Created by Mark Rowe on 2009-06-01.
// Copyright 2009 Mark Rowe. All rights reserved.
//
#define _DARWIN_NO_64_BIT_INODE 1
#include "SUBinaryDeltaCommon.h"
#include "SUBinaryDeltaApply.h"
#include <CommonCrypto/CommonDigest.h>
#include <Foundation/Foundation.h>
#include <fcntl.h>
#include <fts.h>
#include <libgen.h>
#include <stdio.h>
#include <sys/mman.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <unistd.h>
#include <xar/xar.h>
extern int bsdiff(int argc, const char **argv);
@interface CreateBinaryDeltaOperation : NSOperation
{
NSString *_relativePath;
NSString *_fromPath;
NSString *_toPath;
NSString *_resultPath;
}
- (id)initWithRelativePath:(NSString *)relativePath oldTree:(NSString *)oldTree newTree:(NSString *)newTree;
- (NSString *)relativePath;
- (NSString *)resultPath;
@end
@implementation CreateBinaryDeltaOperation
- (id)initWithRelativePath:(NSString *)relativePath oldTree:(NSString *)oldTree newTree:(NSString *)newTree
{
if ((self = [super init])) {
_relativePath = [relativePath copy];
_fromPath = [[oldTree stringByAppendingPathComponent:relativePath] retain];
_toPath = [[newTree stringByAppendingPathComponent:relativePath] retain];
}
return self;
}
- (NSString *)relativePath
{
return [[_relativePath retain] autorelease];
}
- (NSString *)resultPath
{
return [[_resultPath retain] autorelease];
}
- (void)main
{
NSString *temporaryFile = temporaryFilename(@"BinaryDelta");
const char *argv[] = {"/usr/bin/bsdiff", [_fromPath fileSystemRepresentation], [_toPath fileSystemRepresentation], [temporaryFile fileSystemRepresentation]};
int result = bsdiff(4, argv);
if (!result)
_resultPath = [temporaryFile retain];
}
@end
static NSDictionary *infoForFile(FTSENT *ent)
{
NSData *hash = hashOfFile(ent);
NSNumber *size = nil;
if (ent->fts_info != FTS_D)
size = [NSNumber numberWithUnsignedLongLong:ent->fts_statp->st_size];
return [NSDictionary dictionaryWithObjectsAndKeys:hash, @"hash", [NSNumber numberWithUnsignedShort:ent->fts_info], @"type", size, @"size", nil];
}
static NSString *absolutePath(NSString *path)
{
NSURL *url = [[[NSURL alloc] initFileURLWithPath:path] autorelease];
return [[url absoluteURL] path];
}
static NSString *temporaryPatchFile(NSString *patchFile)
{
NSString *path = absolutePath(patchFile);
NSString *directory = [path stringByDeletingLastPathComponent];
NSString *file = [path lastPathComponent];
return [NSString stringWithFormat:@"%@/.%@.tmp", directory, file];
}
static BOOL shouldSkipDeltaCompression(NSString *key, NSDictionary* originalInfo, NSDictionary *newInfo)
{
unsigned long long fileSize = [[newInfo objectForKey:@"size"] unsignedLongLongValue];
if (fileSize < 4096)
return YES;
if (!originalInfo)
return YES;
if ([[originalInfo objectForKey:@"type"] unsignedShortValue] != [[newInfo objectForKey:@"type"] unsignedShortValue])
return YES;
return NO;
}
static BOOL shouldDeleteThenExtract(NSString *key, NSDictionary* originalInfo, NSDictionary *newInfo)
{
if (!originalInfo)
return NO;
if ([[originalInfo objectForKey:@"type"] unsignedShortValue] != [[newInfo objectForKey:@"type"] unsignedShortValue])
return YES;
return NO;
}
int main(int argc, char **argv)
{
if (argc != 5) {
usage:
fprintf(stderr, "Usage: BinaryDelta [create | apply] before-tree after-tree patch-file\n");
exit(1);
}
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *command = [NSString stringWithUTF8String:argv[1]];
NSString *oldPath = [NSString stringWithUTF8String:argv[2]];
NSString *newPath = [NSString stringWithUTF8String:argv[3]];
NSString *patchFile = [NSString stringWithUTF8String:argv[4]];
if ([command isEqualToString:@"apply"]) {
int result = applyBinaryDelta(oldPath, newPath, patchFile);
[pool drain];
return result;
}
if (![command isEqualToString:@"create"]) {
[pool drain];
goto usage;
}
NSMutableDictionary *originalTreeState = [NSMutableDictionary dictionary];
const char *sourcePaths[] = {[oldPath fileSystemRepresentation], 0};
FTS *fts = fts_open((char* const*)sourcePaths, FTS_PHYSICAL | FTS_NOCHDIR, compareFiles);
if (!fts) {
[pool drain];
perror("fts_open");
return 1;
}
fprintf(stderr, "Processing %s...", [oldPath UTF8String]);
FTSENT *ent = 0;
while ((ent = fts_read(fts))) {
if (ent->fts_info != FTS_F && ent->fts_info != FTS_SL && ent->fts_info != FTS_D)
continue;
NSString *key = pathRelativeToDirectory(oldPath, [NSString stringWithUTF8String:ent->fts_path]);
if (![key length])
continue;
NSDictionary *info = infoForFile(ent);
[originalTreeState setObject:info forKey:key];
}
fts_close(fts);
NSString *beforeHash = hashOfTree(oldPath);
NSMutableDictionary *newTreeState = [NSMutableDictionary dictionary];
for (NSString *key in originalTreeState)
{
[newTreeState setObject:[NSNull null] forKey:key];
}
fprintf(stderr, "\nProcessing %s... ", [newPath UTF8String]);
sourcePaths[0] = [newPath fileSystemRepresentation];
fts = fts_open((char* const*)sourcePaths, FTS_PHYSICAL | FTS_NOCHDIR, compareFiles);
if (!fts) {
[pool drain];
perror("fts_open");
return 1;
}
while ((ent = fts_read(fts))) {
if (ent->fts_info != FTS_F && ent->fts_info != FTS_SL && ent->fts_info != FTS_D)
continue;
NSString *key = pathRelativeToDirectory(newPath, [NSString stringWithUTF8String:ent->fts_path]);
if (![key length])
continue;
NSDictionary *info = infoForFile(ent);
NSDictionary *oldInfo = [originalTreeState objectForKey:key];
if ([info isEqual:oldInfo])
[newTreeState removeObjectForKey:key];
else
[newTreeState setObject:info forKey:key];
}
fts_close(fts);
NSString *afterHash = hashOfTree(newPath);
fprintf(stderr, "\nGenerating delta... ");
NSString *temporaryFile = temporaryPatchFile(patchFile);
xar_t x = xar_open([temporaryFile fileSystemRepresentation], WRITE);
xar_opt_set(x, XAR_OPT_COMPRESSION, "bzip2");
xar_subdoc_t attributes = xar_subdoc_new(x, "binary-delta-attributes");
xar_subdoc_prop_set(attributes, "before-sha1", [beforeHash UTF8String]);
xar_subdoc_prop_set(attributes, "after-sha1", [afterHash UTF8String]);
NSOperationQueue *deltaQueue = [[NSOperationQueue alloc] init];
NSMutableArray *deltaOperations = [NSMutableArray array];
NSArray *keys = [[newTreeState allKeys] sortedArrayUsingSelector:@selector(compare:)];
for (NSString* key in keys) {
id value = [newTreeState valueForKey:key];
if ([value isEqual:[NSNull null]]) {
xar_file_t newFile = xar_add_frombuffer(x, 0, [key fileSystemRepresentation], (char *)"", 1);
assert(newFile);
xar_prop_set(newFile, "delete", "true");
continue;
}
NSDictionary *originalInfo = [originalTreeState objectForKey:key];
NSDictionary *newInfo = [newTreeState objectForKey:key];
if (shouldSkipDeltaCompression(key, originalInfo, newInfo)) {
NSString *path = [newPath stringByAppendingPathComponent:key];
xar_file_t newFile = xar_add_frompath(x, 0, [key fileSystemRepresentation], [path fileSystemRepresentation]);
assert(newFile);
if (shouldDeleteThenExtract(key, originalInfo, newInfo))
xar_prop_set(newFile, "delete-then-extract", "true");
} else {
CreateBinaryDeltaOperation *operation = [[CreateBinaryDeltaOperation alloc] initWithRelativePath:key oldTree:oldPath newTree:newPath];
[deltaQueue addOperation:operation];
[deltaOperations addObject:operation];
[operation release];
}
}
[deltaQueue waitUntilAllOperationsAreFinished];
[deltaQueue release];
for (CreateBinaryDeltaOperation *operation in deltaOperations) {
NSString *resultPath = [operation resultPath];
xar_file_t newFile = xar_add_frompath(x, 0, [[operation relativePath] fileSystemRepresentation], [resultPath fileSystemRepresentation]);
assert(newFile);
xar_prop_set(newFile, "binary-delta", "true");
unlink([resultPath fileSystemRepresentation]);
}
xar_close(x);
unlink([patchFile fileSystemRepresentation]);
link([temporaryFile fileSystemRepresentation], [patchFile fileSystemRepresentation]);
unlink([temporaryFile fileSystemRepresentation]);
fprintf(stderr, "Done!\n");
[pool drain];
return 0;
}
+20
View File
@@ -0,0 +1,20 @@
//
// SUBinaryDeltaUnarchiver.h
// Sparkle
//
// Created by Mark Rowe on 2009-06-03.
// Copyright 2009 Mark Rowe. All rights reserved.
//
#ifndef SUBINARYDELTAUNARCHIVER_H
#define SUBINARYDELTAUNARCHIVER_H
#import <Cocoa/Cocoa.h>
#import "SUUnarchiver.h"
@interface SUBinaryDeltaUnarchiver : SUUnarchiver {
}
@end
#endif
+47
View File
@@ -0,0 +1,47 @@
//
// SUBinaryDeltaUnarchiver.m
// Sparkle
//
// Created by Mark Rowe on 2009-06-03.
// Copyright 2009 Mark Rowe. All rights reserved.
//
#import "SUBinaryDeltaCommon.h"
#import "SUBinaryDeltaUnarchiver.h"
#import "SUBinaryDeltaApply.h"
#import "SUUnarchiver_Private.h"
#import "SUHost.h"
@implementation SUBinaryDeltaUnarchiver
+ (BOOL)canUnarchivePath:(NSString *)path
{
return binaryDeltaSupported() && [[path pathExtension] isEqualToString:@"delta"];
}
- (void)applyBinaryDelta
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *sourcePath = [[updateHost bundle] bundlePath];
NSString *targetPath = [[archivePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:[sourcePath lastPathComponent]];
int result = applyBinaryDelta(sourcePath, targetPath, archivePath);
if (!result)
[self performSelectorOnMainThread:@selector(notifyDelegateOfSuccess) withObject:nil waitUntilDone:NO];
else
[self performSelectorOnMainThread:@selector(notifyDelegateOfFailure) withObject:nil waitUntilDone:NO];
[pool drain];
}
- (void)start
{
[NSThread detachNewThreadSelector:@selector(applyBinaryDelta) toTarget:self withObject:nil];
}
+ (void)load
{
[self registerImplementation:self];
}
@end
+27
View File
@@ -0,0 +1,27 @@
//
// SUCodeSigningVerifier.h
// Sparkle
//
// Created by Andy Matuschak on 7/5/12.
//
//
#ifndef SUCODESIGNINGVERIFIER_H
#define SUCODESIGNINGVERIFIER_H
#import <Foundation/Foundation.h>
@interface SUCodeSigningVerifier : NSObject
+ (BOOL)codeSignatureIsValidAtPath:(NSString *)destinationPath error:(NSError **)error;
+ (BOOL)hostApplicationIsCodeSigned;
+ (BOOL)hostApplicationIsSandboxed;
+ (BOOL)hostAppAllowsNetworkOutgoingConnections;
@end
FOUNDATION_EXTERN BOOL SUShouldUseXPCDownloader(void);
FOUNDATION_EXTERN BOOL SUShouldUseXPCInstaller(void);
#endif
+214
View File
@@ -0,0 +1,214 @@
//
// SUCodeSigningVerifier.m
// Sparkle
//
// Created by Andy Matuschak on 7/5/12.
//
//
#import <Security/CodeSigning.h>
#import "SUCodeSigningVerifier.h"
#import "SULog.h"
@implementation SUCodeSigningVerifier
extern OSStatus SecCodeCopySelf(SecCSFlags flags, SecCodeRef *self) __attribute__((weak_import));
extern OSStatus SecCodeCopyDesignatedRequirement(SecStaticCodeRef code, SecCSFlags flags, SecRequirementRef *requirement) __attribute__((weak_import));
extern OSStatus SecStaticCodeCreateWithPath(CFURLRef path, SecCSFlags flags, SecStaticCodeRef *staticCode) __attribute__((weak_import));
extern OSStatus SecStaticCodeCheckValidityWithErrors(SecStaticCodeRef staticCode, SecCSFlags flags, SecRequirementRef requirement, CFErrorRef *errors) __attribute__((weak_import));
extern OSStatus SecRequirementCreateWithString(CFStringRef text, SecCSFlags flags, SecRequirementRef *requirement) __attribute__((weak_import));
extern OSStatus SecCodeCheckValidity(SecCodeRef code, SecCSFlags flags, SecRequirementRef requirement) __attribute__((weak_import));
+ (BOOL)codeSignatureIsValidAtPath:(NSString *)destinationPath error:(NSError **)error
{
// This API didn't exist prior to 10.6.
if (SecCodeCopySelf == NULL) return NO;
OSStatus result;
SecRequirementRef requirement = NULL;
SecStaticCodeRef staticCode = NULL;
SecCodeRef hostCode = NULL;
result = SecCodeCopySelf(kSecCSDefaultFlags, &hostCode);
if (result != 0) {
SULog(@"Failed to copy host code %d", result);
goto finally;
}
result = SecCodeCopyDesignatedRequirement(hostCode, kSecCSDefaultFlags, &requirement);
if (result != 0) {
SULog(@"Failed to copy designated requirement %d", result);
goto finally;
}
NSBundle *newBundle = [NSBundle bundleWithPath:destinationPath];
if (!newBundle) {
SULog(@"Failed to load NSBundle for update");
result = -1;
goto finally;
}
result = SecStaticCodeCreateWithPath((CFURLRef)[newBundle executableURL], kSecCSDefaultFlags, &staticCode);
if (result != 0) {
SULog(@"Failed to get static code %d", result);
goto finally;
}
result = SecStaticCodeCheckValidityWithErrors(staticCode, kSecCSDefaultFlags | kSecCSCheckAllArchitectures, requirement, (CFErrorRef *)error);
if (result != 0 && error) [*error autorelease];
finally:
if (hostCode) CFRelease(hostCode);
if (staticCode) CFRelease(staticCode);
if (requirement) CFRelease(requirement);
return (result == 0);
}
+ (BOOL)hostApplicationIsCodeSigned
{
static BOOL sIsCodesigned = NO;
static BOOL onceToken = NO;
while (!onceToken)
{
onceToken = YES;
// This API didn't exist prior to 10.6.
if (SecCodeCopySelf == NULL)
break;
SecCodeRef hostCode = NULL;
OSStatus result = SecCodeCopySelf(kSecCSDefaultFlags, &hostCode);
if (result != noErr)
break;
SecRequirementRef requirement = NULL;
result = SecCodeCopyDesignatedRequirement(hostCode, kSecCSDefaultFlags, &requirement);
if (hostCode) CFRelease(hostCode);
if (requirement) CFRelease(requirement);
sIsCodesigned = (noErr == result);
}
return sIsCodesigned;
}
+ (BOOL)hostApplicationIsSandboxed
{
static BOOL sIsAppSandboxed = NO;
static BOOL onceToken = NO;
while (!onceToken)
{
onceToken = YES;
// This API didn't exist prior to 10.6
if (SecCodeCopySelf == NULL)
break;
SecCodeRef hostCode = NULL;
SecRequirementRef hostRequirement = NULL;
#define Cleanup() \
{ \
if (hostCode) CFRelease(hostCode); \
if (hostRequirement) CFRelease(hostRequirement); \
}
OSStatus status = SecCodeCopySelf(kSecCSDefaultFlags, &hostCode);
if (status != noErr || hostCode == NULL)
{
Cleanup();
break;
}
CFStringRef requirementString = CFSTR("entitlement[\"com.apple.security.app-sandbox\"] exists");
status = SecRequirementCreateWithString(requirementString, kSecCSDefaultFlags, &hostRequirement);
if (status != noErr || hostRequirement == NULL)
{
Cleanup();
break;
}
status = SecCodeCheckValidity(hostCode, kSecCSDefaultFlags, hostRequirement);
sIsAppSandboxed = (noErr == status);
Cleanup();
}
return sIsAppSandboxed;
}
+ (BOOL)hostAppAllowsNetworkOutgoingConnections
{
static BOOL sIsAppAllowsOutgoingConnections = NO;
static BOOL onceToken = NO;
while (!onceToken)
{
onceToken = YES;
if (![self hostApplicationIsSandboxed])
{
sIsAppAllowsOutgoingConnections = YES;
break;
}
SecCodeRef hostCode = NULL;
SecRequirementRef hostRequirement = NULL;
#define Cleanup() \
{ \
if (hostCode) CFRelease(hostCode); \
if (hostRequirement) CFRelease(hostRequirement); \
}
OSStatus status = SecCodeCopySelf(kSecCSDefaultFlags, &hostCode);
if (status != noErr || hostCode == NULL)
{
Cleanup();
break;
}
CFStringRef requirementString = CFSTR("entitlement[\"com.apple.security.network.client\"] exists");
status = SecRequirementCreateWithString(requirementString, kSecCSDefaultFlags, &hostRequirement);
if (status != noErr || hostRequirement == NULL)
{
Cleanup();
break;
}
status = SecCodeCheckValidity(hostCode, kSecCSDefaultFlags, hostRequirement);
sIsAppAllowsOutgoingConnections = (noErr == status);
Cleanup();
}
return sIsAppAllowsOutgoingConnections;
}
@end
#pragma mark -
BOOL SUShouldUseXPCDownloader(void)
{
if ([SUCodeSigningVerifier hostAppAllowsNetworkOutgoingConnections])
return NO;
NSString *xpcServicePrefixPath = [[NSBundle mainBundle] bundlePath];
NSString *xpcServiceSuffixPath = @"Contents/XPCServices/com.devmate.UpdateDownloader.xpc";
return [[NSFileManager defaultManager] fileExistsAtPath:[xpcServicePrefixPath stringByAppendingPathComponent:xpcServiceSuffixPath]];
}
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]];
}
+84 -18
View File
@@ -10,27 +10,86 @@
#ifndef SUCONSTANTS_H
#define SUCONSTANTS_H
#import <Foundation/Foundation.h>
extern NSString *SUUpdaterWillRestartNotification;
extern NSString *SUTechnicalErrorInformationKey;
// -----------------------------------------------------------------------------
// Preprocessor flags:
// -----------------------------------------------------------------------------
extern NSString *SUFeedURLKey;
extern NSString *SUHasLaunchedBeforeKey;
extern NSString *SUShowReleaseNotesKey;
extern NSString *SUSkippedVersionKey;
extern NSString *SUScheduledCheckIntervalKey;
extern NSString *SULastCheckTimeKey;
extern NSString *SUExpectsDSASignatureKey;
extern NSString *SUPublicDSAKeyKey;
extern NSString *SUPublicDSAKeyFileKey;
extern NSString *SUAutomaticallyUpdateKey;
extern NSString *SUAllowsAutomaticUpdatesKey;
extern NSString *SUEnableAutomaticChecksKey;
extern NSString *SUEnableAutomaticChecksKeyOld;
extern NSString *SUEnableSystemProfilingKey;
extern NSString *SUSendProfileInfoKey;
// Turn off DSA signature check (practically invites man-in-the-middle attacks):
#define ENDANGER_USERS_WITH_INSECURE_UPDATES 0
extern NSString *SUSparkleErrorDomain;
// Sparkle usually doesn't allow downgrades as they're usually accidental, but
// if your app has a downgrade function or URL handler, turn this on:
#define PERMIT_AUTOMATED_DOWNGRADES 0
// If your app file on disk is named "MyApp 1.1b4", Sparkle usually updates it
// in place, giving you an app named 1.1b4 that is actually 1.2. Turn the
// following on to always reset the name back to "MyApp":
#define NORMALIZE_INSTALLED_APP_NAME 0
#define TRY_TO_APPEND_VERSION_NUMBER 1
// -----------------------------------------------------------------------------
// Notifications:
// -----------------------------------------------------------------------------
extern NSString *const SUUpdaterWillRestartNotification;
extern NSString *const SUTechnicalErrorInformationKey;
// -----------------------------------------------------------------------------
// Typedefs:
// -----------------------------------------------------------------------------
typedef NS_OPTIONS(NSUInteger, SUFinishUpdateTask)
{
SUFinishUpdateAbort = 0,
SUFinishUpdateWithInstall = 1 << 0,
SUFinishUpdateWithRelaunch = 1 << 1,
SUFinishUpdateWithDefaultInstallation = SUFinishUpdateWithInstall | SUFinishUpdateWithRelaunch
};
typedef NS_ENUM(NSUInteger, SUUpdateAbortReason)
{
SUUpdateAbortUndefined = 0,
SUUpdateAbortForbiddenByDelegate,
SUUpdateAbortTasksFinished,
SUUpdateAbortCanceledByUser,
SUUpdateAbortDidNotFind,
SUUpdateAbortGotError
};
// -----------------------------------------------------------------------------
// PList keys::
// -----------------------------------------------------------------------------
extern NSString *const SUFeedURLKey;
extern NSString *const SUHasLaunchedBeforeKey;
extern NSString *const SUShowReleaseNotesKey;
extern NSString *const SUSkippedVersionKey;
extern NSString *const SUScheduledCheckIntervalKey;
extern NSString *const SULastCheckTimeKey;
extern NSString *const SUPublicDSAKeyKey;
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 SUFixedHTMLDisplaySizeKey;
extern NSString *const SUKeepDownloadOnFailedInstallKey;
extern NSString *const SUDefaultsDomainKey;
// -----------------------------------------------------------------------------
// Errors:
// -----------------------------------------------------------------------------
extern NSString *const SUSparkleErrorDomain;
// Appcast phase errors.
extern OSStatus SUAppcastParseError;
extern OSStatus SUNoUpdateError;
@@ -51,6 +110,13 @@ extern OSStatus SUMissingUpdateError;
extern OSStatus SUMissingInstallerToolError;
extern OSStatus SURelaunchError;
extern OSStatus SUInstallationError;
extern OSStatus SUDowngradeError;
extern OSStatus SUXPCServiceError;
// -----------------------------------------------------------------------------
// NSInteger fixer-upper:
// -----------------------------------------------------------------------------
// NSInteger is a type that was added to Leopard.
// Here is some glue to ensure that NSInteger will work with pre-10.5 SDKs:
+25 -19
View File
@@ -6,29 +6,33 @@
// Copyright 2006 Andy Matuschak. All rights reserved.
//
#import "Sparkle.h"
#import "SUConstants.h"
NSString *SUUpdaterWillRestartNotification = @"SUUpdaterWillRestartNotificationName";
NSString *SUTechnicalErrorInformationKey = @"SUTechnicalErrorInformation";
NSString *const SUUpdaterWillRestartNotification = @"SUUpdaterWillRestartNotificationName";
NSString *const SUTechnicalErrorInformationKey = @"SUTechnicalErrorInformation";
NSString *SUHasLaunchedBeforeKey = @"SUHasLaunchedBefore";
NSString *SUFeedURLKey = @"SUFeedURL";
NSString *SUShowReleaseNotesKey = @"SUShowReleaseNotes";
NSString *SUSkippedVersionKey = @"SUSkippedVersion";
NSString *SUScheduledCheckIntervalKey = @"SUScheduledCheckInterval";
NSString *SULastCheckTimeKey = @"SULastCheckTime";
NSString *SUExpectsDSASignatureKey = @"SUExpectsDSASignature";
NSString *SUPublicDSAKeyKey = @"SUPublicDSAKey";
NSString *SUPublicDSAKeyFileKey = @"SUPublicDSAKeyFile";
NSString *SUAutomaticallyUpdateKey = @"SUAutomaticallyUpdate";
NSString *SUAllowsAutomaticUpdatesKey = @"SUAllowsAutomaticUpdates";
NSString *SUEnableSystemProfilingKey = @"SUEnableSystemProfiling";
NSString *SUEnableAutomaticChecksKey = @"SUEnableAutomaticChecks";
NSString *SUEnableAutomaticChecksKeyOld = @"SUCheckAtStartup";
NSString *SUSendProfileInfoKey = @"SUSendProfileInfo";
NSString *const SUHasLaunchedBeforeKey = @"SUHasLaunchedBefore";
NSString *const SUFeedURLKey = @"SUFeedURL";
NSString *const SUShowReleaseNotesKey = @"SUShowReleaseNotes";
NSString *const SUSkippedVersionKey = @"SUSkippedVersion";
NSString *const SUScheduledCheckIntervalKey = @"SUScheduledCheckInterval";
NSString *const SULastCheckTimeKey = @"SULastCheckTime";
NSString *const SUExpectsDSASignatureKey = @"SUExpectsDSASignature";
NSString *const SUPublicDSAKeyKey = @"SUPublicDSAKey";
NSString *const SUPublicDSAKeyFileKey = @"SUPublicDSAKeyFile";
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 SUFixedHTMLDisplaySizeKey = @"SUFixedHTMLDisplaySize";
NSString *const SUKeepDownloadOnFailedInstallKey = @"SUKeepDownloadOnFailedInstall";
NSString *const SUDefaultsDomainKey = @"SUDefaultsDomain";
NSString *SUSparkleErrorDomain = @"SUSparkleErrorDomain";
NSString *const SUSparkleErrorDomain = @"SUSparkleErrorDomain";
OSStatus SUAppcastParseError = 1000;
OSStatus SUNoUpdateError = 1001;
OSStatus SUAppcastError = 1002;
@@ -45,3 +49,5 @@ OSStatus SUMissingUpdateError = 4002;
OSStatus SUMissingInstallerToolError = 4003;
OSStatus SURelaunchError = 4004;
OSStatus SUInstallationError = 4005;
OSStatus SUDowngradeError = 4006;
OSStatus SUXPCServiceError = 4007;
+18
View File
@@ -0,0 +1,18 @@
//
// SUDSAVerifier.h
// Sparkle
//
// Created by Andy Matuschak on 3/16/06.
// Copyright 2006 Andy Matuschak. All rights reserved.
//
#ifndef SUDSAVERIFIER_H
#define SUDSAVERIFIER_H
#import <Cocoa/Cocoa.h>
@interface SUDSAVerifier : NSObject {}
+ (BOOL)validatePath:(NSString *)path withEncodedDSASignature:(NSString *)encodedSignature withPublicDSAKey:(NSString *)pkeyString;
@end
#endif
+362
View File
@@ -0,0 +1,362 @@
//
// SUDSAVerifier.m
// Sparkle
//
// Created by Andy Matuschak on 3/16/06.
// Copyright 2006 Andy Matuschak. All rights reserved.
//
#import "SUDSAVerifier.h"
#import <Cocoa/Cocoa.h>
#import <Security/cssm.h>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
/* CDSA Specific */
static CSSM_CSP_HANDLE cdsaInit( void );
static void cdsaRelease( CSSM_CSP_HANDLE cspHandle );
static CSSM_KEY_PTR cdsaCreateKey( CFDataRef rawKey );
static void cdsaReleaseKey( CSSM_KEY_PTR key );
static BOOL cdsaVerifyKey( CSSM_CSP_HANDLE cspHandle, const CSSM_KEY_PTR key );
static BOOL cdsaVerifySignature( CSSM_CSP_HANDLE cspHandle, const CSSM_KEY_PTR key, const CFDataRef msg, const CFDataRef signature );
static CFDataRef cdsaCreateSHA1Digest( CSSM_CSP_HANDLE cspHandle, const CFDataRef bytes );
/* Helper Functions */
static NSData *b64decode( NSString *str );
static NSData *rawKeyData( NSString *str );
@implementation SUDSAVerifier
#pragma mark -
+ (BOOL)validatePath:(NSString *)path withEncodedDSASignature:(NSString *)encodedSignature withPublicDSAKey:(NSString *)pkeyString
{
if ( !encodedSignature || !pkeyString || !path ) return NO;
BOOL result = NO;
NSData *pathData = nil, *sigData = nil;
CFDataRef hashData = NULL;
CSSM_KEY_PTR pubKey = cdsaCreateKey((CFDataRef)rawKeyData(pkeyString)); // Create the DSA key
CSSM_CSP_HANDLE cspHandle = CSSM_INVALID_HANDLE;
if ( !pubKey ) return NO;
if ( (cspHandle = cdsaInit()) == CSSM_INVALID_HANDLE ) goto validate_end; // Init CDSA
if ( !cdsaVerifyKey(cspHandle, pubKey) ) goto validate_end; // Verify the key is valid
if ( (pathData = [NSData dataWithContentsOfFile:path]) == nil ) goto validate_end; // File data
if ( (hashData = cdsaCreateSHA1Digest(cspHandle, (CFDataRef)pathData)) == NULL ) goto validate_end; // Hash
// Remove any line feeds from end of signature
// (Not likely needed, but the verify _can_ fail if there is, so...)
if ( [encodedSignature characterAtIndex:[encodedSignature length] - 1] == '\n' ) {
NSMutableString *sig = [[encodedSignature mutableCopy] autorelease];
while ( [sig characterAtIndex:[sig length] - 1] == '\n' )
[sig deleteCharactersInRange:NSMakeRange([sig length] - 1, 1)];
encodedSignature = sig;
}
if ( (sigData = b64decode(encodedSignature)) == nil ) goto validate_end; // Decode signature
// Verify the signature on the file
result = cdsaVerifySignature( cspHandle, pubKey, hashData, (CFDataRef)sigData );
validate_end:
cdsaReleaseKey( pubKey );
cdsaRelease( cspHandle );
if ( hashData ) CFRelease( hashData );
return result;
}
@end
#pragma mark -
#pragma mark Misc Helper Functions
#pragma mark -
static NSData *b64decode( NSString *str )
{
if ( !str ) return nil;
NSMutableData *retval = nil;
NSData *input = [str dataUsingEncoding:NSUTF8StringEncoding];
UInt8 *ibuf = (UInt8 *)[input bytes], *buf = NULL, *a = NULL;
size_t len = [input length], i = 0, j = 0, size = ((len + 3) / 4) * 3;
static UInt8 table[256] = {
99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99, /* 00-0F */
99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99, /* 10-1F */
99,99,99,99,99,99,99,99,99,99,99,62,99,99,99,63, /* 20-2F */
52,53,54,55,56,57,58,59,60,61,99,99,99,99,99,99, /* 30-3F */
99, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14, /* 40-4F */
15,16,17,18,19,20,21,22,23,24,25,99,99,99,99,99, /* 50-5F */
99,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40, /* 60-6F */
41,42,43,44,45,46,47,48,49,50,51,99,99,99,99,99, /* 70-7F */
99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99, /* 80-8F */
99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99, /* 90-9F */
99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99, /* A0-AF */
99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99, /* B0-BF */
99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99, /* C0-CF */
99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99, /* D0-DF */
99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99, /* E0-EF */
99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99 /* F0-FF */
};
retval = [NSMutableData dataWithLength:size];
buf = [retval mutableBytes];
if ( (a = calloc(4, sizeof(UInt8))) == NULL ) return nil;
do {
size_t ai = 0;
a[0] = a[1] = a[2] = a[3] = 0;
do {
UInt8 d = table[ibuf[i++]];
if ( d != 99 ) {
a[ai] = d;
ai++;
if ( ai == 4 ) break;
}
} while ( i < len );
if ( ai >= 2 ) buf[j] = (a[0] << 2) | (a[1] >> 4);
if ( ai >= 3 ) buf[j+1] = (a[1] << 4) | (a[2] >> 2);
if ( ai >= 4 ) buf[j+2] = (a[2] << 6) | a[3];
j += ai-1;
} while ( i < len );
free( a );
if ( j < size ) [retval setLength:j];
return retval;
}
static NSData *rawKeyData( NSString *key )
{
if ( (key == nil) || ([key length] == 0) ) return nil;
NSMutableString *t = [[key mutableCopy] autorelease];
// Remove the PEM guards (if present)
[t replaceOccurrencesOfString:@"-" withString:@"" options:NSLiteralSearch range:NSMakeRange(0, [t length])];
[t replaceOccurrencesOfString:@"BEGIN PUBLIC KEY" withString:@"" options:NSLiteralSearch range:NSMakeRange(0, [t length])];
[t replaceOccurrencesOfString:@"END PUBLIC KEY" withString:@"" options:NSLiteralSearch range:NSMakeRange(0, [t length])];
// Remove any line feeds from the beginning of the key
while ( [t characterAtIndex:0] == '\n' ) {
[t deleteCharactersInRange:NSMakeRange(0, 1)];
}
// Remove any line feeds at the end of the key
while ( [t characterAtIndex:[t length] - 1] == '\n' ) {
[t deleteCharactersInRange:NSMakeRange([t length] - 1, 1)];
}
// Remove whitespace around each line of the key.
NSMutableArray *pkeyTrimmedLines = [NSMutableArray array];
NSEnumerator *pkeyLinesEnumerator = [[t componentsSeparatedByString:@"\n"] objectEnumerator];
NSCharacterSet *whiteSet = [NSCharacterSet whitespaceCharacterSet];
NSString *pkeyLine;
while ((pkeyLine = [pkeyLinesEnumerator nextObject]) != nil)
{
[pkeyTrimmedLines addObject:[pkeyLine stringByTrimmingCharactersInSet:whiteSet]];
}
key = [pkeyTrimmedLines componentsJoinedByString:@"\n"]; // Put them back together.
// Base64 decode to return the raw key bits (DER format rather than PEM)
return b64decode( key );
}
#pragma mark -
#pragma mark CDSA
#pragma mark -
/* Helper Functions */
static CSSM_DATA_PTR su_createData( CFDataRef bytes );
static void su_freeData( CSSM_DATA_PTR data, Boolean freeData );
static Boolean su_copyBytesToData( CSSM_DATA_PTR data, CSSM_SIZE size, const uint8 *bytes );
/* Memory functions */
static void *su_malloc( CSSM_SIZE size, void *ref );
static void su_free( void *ptr, void *ref );
static void *su_realloc( void *ptr, CSSM_SIZE size, void *ref );
static void *su_calloc( uint32 num, CSSM_SIZE size, void *ref );
/* Constants & Typedefs */
static CSSM_VERSION vers = { 2, 0 };
static const CSSM_GUID su_guid = { 'S', 'p', 'a', { 'r', 'k', 'l', 'e', 0, 0, 0, 0 } };
static CSSM_BOOL cssmInited = CSSM_FALSE;
static CSSM_API_MEMORY_FUNCS SU_MemFuncs = {
su_malloc,
su_free,
su_realloc,
su_calloc,
NULL
};
static CSSM_CSP_HANDLE cdsaInit( void )
{
CSSM_CSP_HANDLE cspHandle = CSSM_INVALID_HANDLE;
CSSM_RETURN crtn;
if ( !cssmInited ) {
CSSM_PVC_MODE pvcPolicy = CSSM_PVC_NONE;
crtn = CSSM_Init( &vers, CSSM_PRIVILEGE_SCOPE_NONE, &su_guid, CSSM_KEY_HIERARCHY_NONE, &pvcPolicy, NULL );
if ( crtn ) return CSSM_INVALID_HANDLE;
cssmInited = CSSM_TRUE;
}
crtn = CSSM_ModuleLoad( &gGuidAppleCSP, CSSM_KEY_HIERARCHY_NONE, NULL, NULL );
if ( crtn ) return CSSM_INVALID_HANDLE;
crtn = CSSM_ModuleAttach( &gGuidAppleCSP, &vers, &SU_MemFuncs, 0, CSSM_SERVICE_CSP, 0, CSSM_KEY_HIERARCHY_NONE, NULL, 0, NULL, &cspHandle );
if ( crtn ) return CSSM_INVALID_HANDLE;
return cspHandle;
}
static void cdsaRelease( CSSM_CSP_HANDLE cspHandle )
{
if ( CSSM_ModuleDetach(cspHandle) != CSSM_OK ) return;
CSSM_ModuleUnload( &gGuidAppleCSP, NULL, NULL );
}
static CSSM_KEY_PTR cdsaCreateKey( CFDataRef rawKey )
{
CSSM_KEY_PTR retval = NULL;
if ( !rawKey || (CFDataGetLength(rawKey) == 0) ) return NULL;
if ( (retval = su_malloc(sizeof(CSSM_KEY), NULL)) == NULL ) return NULL;
if ( !su_copyBytesToData(&(retval->KeyData), CFDataGetLength(rawKey), CFDataGetBytePtr(rawKey)) ) {
su_free( retval, NULL );
return NULL;
}
CSSM_KEYHEADER_PTR hdr = &(retval->KeyHeader);
memset( hdr, 0, sizeof(CSSM_KEYHEADER) );
hdr->HeaderVersion = CSSM_KEYHEADER_VERSION;
hdr->CspId = su_guid;
hdr->BlobType = CSSM_KEYBLOB_RAW;
hdr->Format = CSSM_KEYBLOB_RAW_FORMAT_X509;
hdr->AlgorithmId = CSSM_ALGID_DSA;
hdr->KeyClass = CSSM_KEYCLASS_PUBLIC_KEY;
hdr->KeyAttr = CSSM_KEYATTR_EXTRACTABLE;
hdr->KeyUsage = CSSM_KEYUSE_ANY;
return retval;
}
static void cdsaReleaseKey( CSSM_KEY_PTR key )
{
if ( key ) {
if ( key->KeyData.Data ) su_free( key->KeyData.Data, NULL );
su_free( key, NULL );
}
}
BOOL cdsaVerifyKey( CSSM_CSP_HANDLE cspHandle, CSSM_KEY_PTR key )
{
if ( key->KeyHeader.LogicalKeySizeInBits == 0 ) {
CSSM_RETURN crtn;
CSSM_KEY_SIZE keySize;
/* This will fail if the key isn't valid */
crtn = CSSM_QueryKeySizeInBits( cspHandle, CSSM_INVALID_HANDLE, key, &keySize );
if ( crtn ) return NO;
key->KeyHeader.LogicalKeySizeInBits = keySize.LogicalKeySizeInBits;
}
return YES;
}
static BOOL cdsaVerifySignature( CSSM_CSP_HANDLE cspHandle, const CSSM_KEY_PTR key, const CFDataRef msg, const CFDataRef signature )
{
CSSM_CC_HANDLE ccHandle = CSSM_INVALID_HANDLE;
CSSM_DATA_PTR plain = su_createData( msg ), cipher = su_createData( signature );
BOOL retval = NO;
if ( !plain || !cipher || (CSSM_CSP_CreateSignatureContext(cspHandle, CSSM_ALGID_SHA1WithDSA, NULL, key, &ccHandle) != CSSM_OK) )
goto verify_end;
retval = ( CSSM_VerifyData(ccHandle, plain, 1, CSSM_ALGID_NONE, cipher) == CSSM_OK );
verify_end:
su_freeData( plain, true );
su_freeData( cipher, true );
if ( ccHandle ) CSSM_DeleteContext( ccHandle );
return retval;
}
static CFDataRef cdsaCreateSHA1Digest( CSSM_CSP_HANDLE cspHandle, const CFDataRef bytes )
{
CSSM_CC_HANDLE ccHandle = CSSM_INVALID_HANDLE;
CSSM_DATA_PTR data = su_createData( bytes ), dgst = su_createData( NULL );
CFDataRef retval = NULL;
if ( !data || !dgst || (CSSM_CSP_CreateDigestContext(cspHandle, CSSM_ALGID_SHA1, &ccHandle) != CSSM_OK) )
goto digest_end;
if ( CSSM_DigestData(ccHandle, data, 1, dgst) == CSSM_OK )
retval = CFDataCreate( kCFAllocatorDefault, (const UInt8 *)dgst->Data, (CFIndex)dgst->Length );
digest_end:
su_freeData( data, true );
su_freeData( dgst, true );
if ( ccHandle ) CSSM_DeleteContext( ccHandle );
return retval;
}
/* Memory Functions */
static void *su_malloc( CSSM_SIZE size, void *ref )
{
return malloc( size );
}
static void su_free( void *ptr, void *ref )
{
free( ptr );
}
static void *su_realloc( void *ptr, CSSM_SIZE size, void *ref )
{
return realloc( ptr, size );
}
static void *su_calloc( uint32 num, CSSM_SIZE size, void *ref )
{
return calloc( num, size );
}
/* Helper Functions */
static CSSM_DATA_PTR su_createData( CFDataRef bytes )
{
CSSM_DATA_PTR data = su_malloc( sizeof(CSSM_DATA), NULL );
if ( !data ) return NULL;
data->Data = NULL;
data->Length = 0;
if ( bytes ) su_copyBytesToData( data, CFDataGetLength(bytes), CFDataGetBytePtr(bytes) );
return data;
}
static void su_freeData( CSSM_DATA_PTR data, Boolean freeData )
{
if ( data ) {
if ( freeData && data->Data ) su_free( data->Data, NULL );
su_free( data, NULL );
}
}
static Boolean su_copyBytesToData( CSSM_DATA_PTR data, CSSM_SIZE size, const uint8 *bytes )
{
Boolean retval = false;
if ( size && bytes ) {
if ( (data->Data = su_malloc(size, NULL)) ) {
memcpy( data->Data, bytes, size );
data->Length = size;
retval = true;
}
}
return retval;
}
#pragma GCC diagnostic pop
+264 -53
View File
@@ -9,71 +9,282 @@
#import "SUDiskImageUnarchiver.h"
#import "SUUnarchiver_Private.h"
#import "NTSynchronousTask.h"
#import "SUCodeSigningVerifier.h"
#import "SUXPCInstaller.h"
#import "SULog.h"
#import <CoreServices/CoreServices.h>
@implementation SUDiskImageUnarchiver
+ (BOOL)_canUnarchiveURL:(NSURL *)URL
+ (BOOL)canUnarchivePath:(NSString *)path
{
return [URL conformsToType:@"public.disk-image"];
return [[path pathExtension] isEqualToString:@"dmg"];
}
// Called on a non-main thread.
- (void)extractDMG
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *hdiutilPath = @"/usr/bin/hdiutil";
NSArray *args = [NSArray arrayWithObjects: @"isencrypted", archivePath, nil];
NSString *currentDirPath = @"/";
__block NSData *result = nil;
if (SUShouldUseXPCInstaller())
{
[SUXPCInstaller launchTaskWithPath:hdiutilPath
arguments:args
environment:nil
currentDirectoryPath:currentDirPath
inputData:nil
waitForTaskResult:YES
waitUntilDone:YES
completionHandler:^(int resultCode, NSData *outputData) {
result = [outputData copy];
}];
[result autorelease];
}
else
{
result = [NTSynchronousTask task:hdiutilPath directory:currentDirPath withArgs:args input:nil];
}
if ([self isEncrypted:result] && [delegate respondsToSelector:@selector(unarchiver:requiresPasswordReturnedViaInvocation:)])
{
[self performSelectorOnMainThread:@selector(requestPasswordFromDelegate) withObject:nil waitUntilDone:NO];
}
else
{
[self extractDMGWithPassword:nil];
}
[pool release];
}
// Called on a non-main thread.
- (void)extractDMGWithPassword:(NSString *)password
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
BOOL mountedSuccessfully = NO;
SULog(@"Extracting %@ as a DMG", archivePath);
// get a unique mount point path
NSString *mountPoint = nil;
do
{
CFUUIDRef uuid = CFUUIDCreate(NULL);
if (uuid)
{
CFStringRef uuidString = CFUUIDCreateString(NULL, uuid);
if (uuidString)
{
mountPoint = [@"/Volumes" stringByAppendingPathComponent:(NSString *)uuidString];
CFRelease(uuidString);
}
CFRelease(uuid);
}
}
while ([[NSFileManager defaultManager] fileExistsAtPath:mountPoint]);
NSData *promptData = nil;
if ([password length])
{
NSString *data = [NSString stringWithFormat:@"%@\nyes\n", password];
const char *bytes = [data cStringUsingEncoding:NSUTF8StringEncoding];
NSUInteger length = [data lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
promptData = [NSData dataWithBytes:bytes length:length];
}
else
{
promptData = [NSData dataWithBytes:"yes\n" length:4];
}
BOOL shouldUseXPC = SUShouldUseXPCInstaller();
NSString *hdiutilPath = @"/usr/bin/hdiutil";
NSArray* arguments = [NSArray arrayWithObjects:@"attach", archivePath, @"-mountpoint", mountPoint, /*@"-noverify",*/ @"-nobrowse", @"-noautoopen", nil];
NSString *currentDirPath = @"/";
__block NSData *output = nil;
__block NSInteger taskResult = -1;
@try
{
if (shouldUseXPC)
{
[SUXPCInstaller launchTaskWithPath:hdiutilPath
arguments:arguments
environment:nil
currentDirectoryPath:currentDirPath
inputData:promptData
waitForTaskResult:YES
waitUntilDone:YES
completionHandler:^(int result, NSData *outputData) {
taskResult = (NSInteger)result;
output = [outputData copy];
}];
[output autorelease];
}
else
{
NTSynchronousTask* task = [[NTSynchronousTask alloc] init];
[task run:hdiutilPath directory:currentDirPath withArgs:arguments input:promptData];
taskResult = [task result];
output = [[[task output] copy] autorelease];
[task release];
}
}
@catch (NSException *localException)
{
SULog(@"Got DMG mount exception: %@ - %@", [localException name], [localException reason]);
goto reportError;
}
if (taskResult != 0)
{
NSString *resultStr = output ? [[[NSString alloc] initWithData:output encoding:NSUTF8StringEncoding] autorelease] : nil;
if (password != nil &&
[resultStr rangeOfString:@"Authentication error"].location != NSNotFound &&
[delegate respondsToSelector:@selector(unarchiver:requiresPasswordReturnedViaInvocation:)])
{
[self performSelectorOnMainThread:@selector(requestPasswordFromDelegate) withObject:nil waitUntilDone:NO];
goto finally;
}
else
{
SULog( @"hdiutil failed with code: %d data: <<%@>>", taskResult, resultStr);
goto reportError;
}
}
mountedSuccessfully = YES;
// Now that we've mounted it, we need to copy out its contents.
if (floor(NSAppKitVersionNumber) >= NSAppKitVersionNumber10_6)
{
if (shouldUseXPC)
{
NSError *error = nil;
[SUXPCInstaller copyPathContent:mountPoint
toDirectory:[archivePath stringByDeletingLastPathComponent]
error:&error];
if (nil != error)
{
SULog(@"Couldn't copy volume content: %d - %@", [error code], [error localizedDescription]);
goto reportError;
}
}
else
{
// On 10.7 and later we don't want to use the File Manager API and instead want to use NSFileManager (fixes #827357).
NSFileManager *manager = [[[NSFileManager alloc] init] autorelease];
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;
}
NSEnumerator *contentsEnumerator = [contents objectEnumerator];
NSString *item = nil;
while ((item = [contentsEnumerator nextObject]))
{
NSString *fromPath = [mountPoint stringByAppendingPathComponent:item];
NSString *toPath = [[archivePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:item];
// 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;
}
}
}
}
else
{
SULog(@"This version of Sparkle don't support OS X version earlier than 10.6");
goto reportError;
}
[self performSelectorOnMainThread:@selector(notifyDelegateOfSuccess) withObject:nil waitUntilDone:NO];
goto finally;
reportError:
[self performSelectorOnMainThread:@selector(notifyDelegateOfFailure) withObject:nil waitUntilDone:NO];
finally:
if (mountedSuccessfully)
{
NSArray *args = [NSArray arrayWithObjects:@"detach", mountPoint, @"-force", nil];
if (shouldUseXPC)
{
[SUXPCInstaller launchTaskWithPath:hdiutilPath
arguments:args
environment:nil
currentDirectoryPath:nil
inputData:nil
waitForTaskResult:NO
waitUntilDone:NO
completionHandler:nil];
}
else
{
[NSTask launchedTaskWithLaunchPath:hdiutilPath arguments:args];
}
}
else
{
SULog(@"Can't mount DMG %@", archivePath);
}
[pool drain];
}
- (void)start
{
[NSThread detachNewThreadSelector:@selector(_extractDMG) toTarget:self withObject:nil];
}
- (void)_extractDMG
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *archivePath = [archiveURL path];
BOOL mountedSuccessfully = NO;
// get a unique mount point path
NSString *mountPrefix = [@"/Volumes" stringByAppendingPathComponent:[[archivePath lastPathComponent] stringByDeletingPathExtension]];
NSString *mountPoint = [mountPrefix stringByAppendingString:[[NSProcessInfo processInfo] globallyUniqueString]];
if ([[NSFileManager defaultManager] fileExistsAtPath:mountPoint]) goto reportError;
// create mount point folder
[[NSFileManager defaultManager] createDirectoryAtPath:mountPoint attributes:nil];
if (![[NSFileManager defaultManager] fileExistsAtPath:mountPoint]) goto reportError;
NSArray* arguments = [NSArray arrayWithObjects:@"attach", archivePath, @"-mountpoint", mountPoint, @"-noverify", @"-nobrowse", @"-noautoopen", nil];
// set up a pipe and push "yes" (y works too), this will accept any license agreement crap
// not every .dmg needs this, but this will make sure it works with everyone
NSData* yesData = [[[NSData alloc] initWithBytes:"yes\n" length:4] autorelease];
NSData *result = [NTSynchronousTask task:@"/usr/bin/hdiutil" directory:@"/" withArgs:arguments input:yesData];
if (!result) goto reportError;
mountedSuccessfully = YES;
// Now that we've mounted it, we need to copy out its contents.
NSString *targetPath = [[archivePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:[mountPoint lastPathComponent]];
if (![[NSFileManager defaultManager] createDirectoryAtPath:targetPath attributes:nil]) goto reportError;
// We can't just copyPath: from the volume root because that always fails. Seems to be a bug.
id subpathEnumerator = [[[NSFileManager defaultManager] directoryContentsAtPath:mountPoint] objectEnumerator], currentSubpath;
while ((currentSubpath = [subpathEnumerator nextObject]))
{
if (![[NSFileManager defaultManager] copyPath:[mountPoint stringByAppendingPathComponent:currentSubpath] toPath:[targetPath stringByAppendingPathComponent:currentSubpath] handler:nil])
goto reportError;
}
[self performSelectorOnMainThread:@selector(_notifyDelegateOfSuccess) withObject:nil waitUntilDone:NO];
goto finally;
reportError:
[self performSelectorOnMainThread:@selector(_notifyDelegateOfFailure) withObject:nil waitUntilDone:NO];
finally:
if (mountedSuccessfully)
[NSTask launchedTaskWithLaunchPath:@"/usr/bin/hdiutil" arguments:[NSArray arrayWithObjects:@"detach", mountPoint, @"-force", nil]];
[pool drain];
[NSThread detachNewThreadSelector:@selector(extractDMG) toTarget:self withObject:nil];
}
+ (void)load
{
[self _registerImplementation:self];
[self registerImplementation:self];
}
- (BOOL)isEncrypted:(NSData*)resultData
{
BOOL result = NO;
if(resultData)
{
NSString *data = [NSString stringWithCString:(char*)[resultData bytes] encoding:NSUTF8StringEncoding];
if (!NSEqualRanges([data rangeOfString:@"passphrase-count"], NSMakeRange(NSNotFound, 0)))
{
result = YES;
}
}
return result;
}
- (void)requestPasswordFromDelegate
{
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(continueWithPassword:)]];
[invocation setSelector:@selector(continueWithPassword:)];
[invocation setTarget:self];
[invocation retainArguments];
[delegate unarchiver:self requiresPasswordReturnedViaInvocation:invocation];
}
- (void)continueWithPassword:(NSString *)password
{
[NSThread detachNewThreadSelector:@selector(extractDMGWithPassword:) toTarget:self withObject:password];
}
@end
+45
View File
@@ -0,0 +1,45 @@
//
// SUHost.h
// Sparkle
//
// Copyright 2008 Andy Matuschak. All rights reserved.
//
#import "SUUpdater.h"
#import "SUAppcast.h"
#import "SUAppcastItem.h"
#import "SUVersionComparisonProtocol.h"
@interface SUHost : NSObject
{
@private
NSBundle *bundle;
NSString *defaultsDomain;
BOOL usesStandardUserDefaults;
}
+ (NSString *)systemVersionString;
- (id)initWithBundle:(NSBundle *)aBundle;
- (NSBundle *)bundle;
- (NSString *)bundlePath;
- (NSString *)appSupportPath;
- (NSString *)installationPath;
- (NSString *)name;
- (NSString *)version;
- (NSString *)displayVersion;
- (NSImage *)icon;
- (BOOL)isRunningOnReadOnlyVolume;
- (BOOL)isBackgroundApplication;
- (NSString *)publicDSAKey;
- (NSArray *)systemProfile;
- (id)objectForInfoDictionaryKey:(NSString *)key;
- (BOOL)boolForInfoDictionaryKey:(NSString *)key;
- (id)objectForUserDefaultsKey:(NSString *)defaultName;
- (void)setObject:(id)value forUserDefaultsKey:(NSString *)defaultName;
- (BOOL)boolForUserDefaultsKey:(NSString *)defaultName;
- (void)setBool:(BOOL)value forUserDefaultsKey:(NSString *)defaultName;
- (id)objectForKey:(NSString *)key;
- (BOOL)boolForKey:(NSString *)key;
@end
+270
View File
@@ -0,0 +1,270 @@
//
// SUHost.m
// Sparkle
//
// Copyright 2008 Andy Matuschak. All rights reserved.
//
#import "SUHost.h"
#import "SUConstants.h"
#import "SUSystemProfiler.h"
#import <sys/mount.h> // For statfs for isRunningOnReadOnlyVolume
#import "SULog.h"
@implementation SUHost
- (id)initWithBundle:(NSBundle *)aBundle
{
if ((self = [super init]))
{
if (aBundle == nil) aBundle = [NSBundle mainBundle];
bundle = [aBundle retain];
if (![bundle bundleIdentifier])
SULog(@"Sparkle Error: the bundle being updated at %@ has no CFBundleIdentifier! This will cause preference read/write to not work properly.", bundle);
defaultsDomain = [[bundle objectForInfoDictionaryKey:SUDefaultsDomainKey] retain];
if (!defaultsDomain)
defaultsDomain = [[bundle bundleIdentifier] retain];
// If we're using the main bundle's defaults we'll use the standard user defaults mechanism, otherwise we have to get CF-y.
usesStandardUserDefaults = [defaultsDomain isEqualToString:[[NSBundle mainBundle] bundleIdentifier]];
}
return self;
}
- (void)dealloc
{
[defaultsDomain release];
[bundle release];
[super dealloc];
}
- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@, %@>", [self class], [self bundlePath], [self installationPath]]; }
- (NSBundle *)bundle
{
return bundle;
}
- (NSString *)bundlePath
{
return [bundle bundlePath];
}
- (NSString *)appSupportPath
{
NSArray *appSupportPaths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *appSupportPath = nil;
if (!appSupportPaths || [appSupportPaths count] == 0)
{
SULog(@"Failed to find app support directory! Using ~/Library/Application Support...");
appSupportPath = [@"~/Library/Application Support" stringByExpandingTildeInPath];
}
else
appSupportPath = [appSupportPaths objectAtIndex:0];
appSupportPath = [appSupportPath stringByAppendingPathComponent:[self name]];
return appSupportPath;
}
- (NSString *)installationPath
{
#if NORMALIZE_INSTALLED_APP_NAME
// We'll install to "#{CFBundleName}.app", but only if that path doesn't already exist. If we're "Foo 4.2.app," and there's a "Foo.app" in this directory, we don't want to overwrite it! But if there's no "Foo.app," we'll take that name.
NSString *normalizedAppPath = [[[bundle bundlePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent: [NSString stringWithFormat: @"%@.%@", [bundle objectForInfoDictionaryKey:@"CFBundleName"], [[bundle bundlePath] pathExtension]]];
if (![[NSFileManager defaultManager] fileExistsAtPath:[[[bundle bundlePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent: [NSString stringWithFormat: @"%@.%@", [bundle objectForInfoDictionaryKey:@"CFBundleName"], [[bundle bundlePath] pathExtension]]]])
return normalizedAppPath;
#endif
return [bundle bundlePath];
}
- (NSString *)name
{
NSString *name = [bundle objectForInfoDictionaryKey:@"CFBundleDisplayName"];
if (name) return name;
name = [self objectForInfoDictionaryKey:@"CFBundleName"];
if (name) return name;
return [[[NSFileManager defaultManager] displayNameAtPath:[bundle bundlePath]] stringByDeletingPathExtension];
}
- (NSString *)version
{
NSString *version = [bundle objectForInfoDictionaryKey:@"CFBundleVersion"];
if (!version || [version isEqualToString:@""])
[NSException raise:@"SUNoVersionException" format:@"This host (%@) has no CFBundleVersion! This attribute is required.", [self bundlePath]];
return version;
}
- (NSString *)displayVersion
{
NSString *shortVersionString = [bundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
if (shortVersionString)
return shortVersionString;
else
return [self version]; // Fall back on the normal version string.
}
- (NSImage *)icon
{
// Cache the application icon.
NSString *iconPath = [bundle pathForResource:[bundle objectForInfoDictionaryKey:@"CFBundleIconFile"] ofType:@"icns"];
// According to the OS X docs, "CFBundleIconFile - This key identifies the file containing
// the icon for the bundle. The filename you specify does not need to include the .icns
// extension, although it may."
//
// However, if it *does* include the '.icns' the above method fails (tested on OS X 10.3.9) so we'll also try:
if (!iconPath)
iconPath = [bundle pathForResource:[bundle objectForInfoDictionaryKey:@"CFBundleIconFile"] ofType: nil];
NSImage *icon = [[[NSImage alloc] initWithContentsOfFile:iconPath] autorelease];
// Use a default icon if none is defined.
if (!icon) {
BOOL isMainBundle = (bundle == [NSBundle mainBundle]);
// Starting with 10.6, iconForFileType: accepts a UTI.
NSString *fileType = nil;
if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_5)
fileType = isMainBundle ? NSFileTypeForHFSTypeCode(kGenericApplicationIcon) : @".bundle";
else
fileType = isMainBundle ? (NSString*)kUTTypeApplication : (NSString*)kUTTypeBundle;
icon = [[NSWorkspace sharedWorkspace] iconForFileType:fileType];
}
return icon;
}
- (BOOL)isRunningOnReadOnlyVolume
{
struct statfs statfs_info;
statfs([[bundle bundlePath] fileSystemRepresentation], &statfs_info);
return (statfs_info.f_flags & MNT_RDONLY);
}
- (BOOL)isBackgroundApplication
{
ProcessSerialNumber PSN;
GetCurrentProcess(&PSN);
CFDictionaryRef processInfo = ProcessInformationCopyDictionary(&PSN, kProcessDictionaryIncludeAllInformationMask);
BOOL isElement = [[(NSDictionary *)processInfo objectForKey:@"LSUIElement"] boolValue];
if (processInfo)
CFRelease(processInfo);
return isElement;
}
- (NSString *)publicDSAKey
{
// Maybe the key is just a string in the Info.plist.
NSString *key = [bundle objectForInfoDictionaryKey:SUPublicDSAKeyKey];
if (key) { return key; }
// More likely, we've got a reference to a Resources file by filename:
NSString *keyFilename = [self objectForInfoDictionaryKey:SUPublicDSAKeyFileKey];
if (!keyFilename) { return nil; }
NSError *ignoreErr = nil;
return [NSString stringWithContentsOfFile:[bundle pathForResource:keyFilename ofType:nil] encoding:NSASCIIStringEncoding error: &ignoreErr];
}
- (NSArray *)systemProfile
{
return [[SUSystemProfiler sharedSystemProfiler] systemProfileArrayForHost:self];
}
- (id)objectForInfoDictionaryKey:(NSString *)key
{
return [bundle objectForInfoDictionaryKey:key];
}
- (BOOL)boolForInfoDictionaryKey:(NSString *)key
{
return [[self objectForInfoDictionaryKey:key] boolValue];
}
- (id)objectForUserDefaultsKey:(NSString *)defaultName
{
// Under Tiger, CFPreferencesCopyAppValue doesn't get values from NSRegistrationDomain, so anything
// passed into -[NSUserDefaults registerDefaults:] is ignored. The following line falls
// back to using NSUserDefaults, but only if the host bundle is the main bundle.
if (usesStandardUserDefaults)
return [[NSUserDefaults standardUserDefaults] objectForKey:defaultName];
CFPropertyListRef obj = CFPreferencesCopyAppValue((CFStringRef)defaultName, (CFStringRef)defaultsDomain);
return [(id)CFMakeCollectable(obj) autorelease];
}
- (void)setObject:(id)value forUserDefaultsKey:(NSString *)defaultName;
{
if (usesStandardUserDefaults)
{
[[NSUserDefaults standardUserDefaults] setObject:value forKey:defaultName];
}
else
{
CFPreferencesSetValue((CFStringRef)defaultName, value, (CFStringRef)defaultsDomain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
CFPreferencesSynchronize((CFStringRef)defaultsDomain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
}
}
- (BOOL)boolForUserDefaultsKey:(NSString *)defaultName
{
if (usesStandardUserDefaults)
return [[NSUserDefaults standardUserDefaults] boolForKey:defaultName];
BOOL value;
CFPropertyListRef plr = CFPreferencesCopyAppValue((CFStringRef)defaultName, (CFStringRef)defaultsDomain);
if (plr == NULL)
value = NO;
else
{
value = (BOOL)CFBooleanGetValue((CFBooleanRef)plr);
CFRelease(plr);
}
return value;
}
- (void)setBool:(BOOL)value forUserDefaultsKey:(NSString *)defaultName
{
if (usesStandardUserDefaults)
{
[[NSUserDefaults standardUserDefaults] setBool:value forKey:defaultName];
}
else
{
CFPreferencesSetValue((CFStringRef)defaultName, (CFBooleanRef)[NSNumber numberWithBool:value], (CFStringRef)defaultsDomain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
CFPreferencesSynchronize((CFStringRef)defaultsDomain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
}
}
- (id)objectForKey:(NSString *)key {
return [self objectForUserDefaultsKey:key] ? [self objectForUserDefaultsKey:key] : [self objectForInfoDictionaryKey:key];
}
- (BOOL)boolForKey:(NSString *)key {
return [self objectForUserDefaultsKey:key] ? [self boolForUserDefaultsKey:key] : [self boolForInfoDictionaryKey:key];
}
+ (NSString *)systemVersionString
{
// This returns a version string of the form X.Y.Z
// There may be a better way to deal with the problem that gestaltSystemVersionMajor
// et al. are not defined in 10.3, but this is probably good enough.
NSString* verStr = nil;
#if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_4
SInt32 major, minor, bugfix;
OSErr err1 = Gestalt(gestaltSystemVersionMajor, &major);
OSErr err2 = Gestalt(gestaltSystemVersionMinor, &minor);
OSErr err3 = Gestalt(gestaltSystemVersionBugFix, &bugfix);
if (!err1 && !err2 && !err3)
{
verStr = [NSString stringWithFormat:@"%ld.%ld.%ld", (long)major, (long)minor, (long)bugfix];
}
else
#endif
{
NSString *versionPlistPath = @"/System/Library/CoreServices/SystemVersion.plist";
verStr = [[NSDictionary dictionaryWithContentsOfFile:versionPlistPath] objectForKey:@"ProductVersion"];
}
return verStr;
}
@end
+9 -4
View File
@@ -10,15 +10,20 @@
#define SUINSTALLER_H
#import <Cocoa/Cocoa.h>
#import "SUVersionComparisonProtocol.h"
@class SUHost;
@interface SUInstaller : NSObject { }
+ (void)installFromUpdateFolder:(NSString *)updateFolder overHostBundle:(NSBundle *)hostBundle delegate:delegate synchronously:(BOOL)synchronously;
+ (void)_finishInstallationWithResult:(BOOL)result hostBundle:(NSBundle *)hostBundle error:(NSError *)error delegate:delegate;
+ (NSString *) appPathInUpdateFolder:(NSString *)updateFolder forHost:(SUHost *)host;
+ (void) installFromUpdateFolder:(NSString *)updateFolder overHost:(SUHost *)host installationPath:(NSString *)installationPath delegate:delegate synchronously:(BOOL)synchronously versionComparator:(id <SUVersionComparison>)comparator;
+ (void) finishInstallationToPath:(NSString *)installationPath withResult:(BOOL)result host:(SUHost *)host error:(NSError *)error delegate:delegate;
+ (NSString*) updateFolder;
+ (void) notifyDelegateOfFailure: (NSDictionary*)dict;
@end
@interface NSObject (SUInstallerDelegateInformalProtocol)
- (void)installerFinishedForHostBundle:(NSBundle *)hostBundle;
- (void)installerForHostBundle:(NSBundle *)hostBundle failedWithError:(NSError *)error;
- (void)installerFinishedForHost:(SUHost *)host;
- (void)installerForHost:(SUHost *)host failedWithError:(NSError *)error;
@end
#endif
+128 -32
View File
@@ -9,22 +9,56 @@
#import "SUInstaller.h"
#import "SUPlainInstaller.h"
#import "SUPackageInstaller.h"
#import "SUHost.h"
#import "SUConstants.h"
#import "SULog.h"
NSString *SUInstallerPathKey = @"SUInstallerPath";
NSString *SUInstallerHostBundleKey = @"SUInstallerHostBundle";
NSString *SUInstallerDelegateKey = @"SUInstallerDelegate";
@implementation SUInstaller
+ (void)installFromUpdateFolder:(NSString *)updateFolder overHostBundle:(NSBundle *)hostBundle delegate:delegate synchronously:(BOOL)synchronously
static NSString* sUpdateFolder = nil;
+(NSString*) updateFolder
{
// Search subdirectories for the application
NSString *currentFile, *newAppDownloadPath = nil, *bundleFileName = [[hostBundle bundlePath] lastPathComponent], *alternateBundleFileName = [[hostBundle name] stringByAppendingPathExtension:[[hostBundle bundlePath] pathExtension]];
return sUpdateFolder;
}
+ (BOOL)isAliasFolderAtPath:(NSString *)path
{
FSRef fileRef;
OSStatus err = noErr;
Boolean aliasFileFlag, folderFlag;
NSURL *fileURL = [NSURL fileURLWithPath:path];
if (FALSE == CFURLGetFSRef((CFURLRef)fileURL, &fileRef))
err = coreFoundationUnknownErr;
if (noErr == err)
err = FSIsAliasFile(&fileRef, &aliasFileFlag, &folderFlag);
if (noErr == err)
return (BOOL)(aliasFileFlag && folderFlag);
else
return NO;
}
+ (NSString *)installSourcePathInUpdateFolder:(NSString *)inUpdateFolder forHost:(SUHost *)host isPackage:(BOOL *)isPackagePtr
{
// Search subdirectories for the application
NSString *currentFile,
*newAppDownloadPath = nil,
*bundleFileName = [[host bundlePath] lastPathComponent],
*alternateBundleFileName = [[host name] stringByAppendingPathExtension:[[host bundlePath] pathExtension]];
BOOL isPackage = NO;
NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath:updateFolder];
NSString *fallbackPackagePath = nil;
NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath: inUpdateFolder];
[sUpdateFolder release];
sUpdateFolder = [inUpdateFolder retain];
while ((currentFile = [dirEnum nextObject]))
{
NSString *currentPath = [updateFolder stringByAppendingPathComponent:currentFile];
NSString *currentPath = [inUpdateFolder stringByAppendingPathComponent:currentFile];
if ([[currentFile lastPathComponent] isEqualToString:bundleFileName] ||
[[currentFile lastPathComponent] isEqualToString:alternateBundleFileName]) // We found one!
{
@@ -32,55 +66,117 @@ NSString *SUInstallerDelegateKey = @"SUInstallerDelegate";
newAppDownloadPath = currentPath;
break;
}
else if (([[currentFile pathExtension] isEqualToString:@"pkg"] || [[currentFile pathExtension] isEqualToString:@"mpkg"]) &&
[[[currentFile lastPathComponent] stringByDeletingPathExtension] isEqualToString:[bundleFileName stringByDeletingPathExtension]])
else if ([[currentFile pathExtension] isEqualToString:@"pkg"] ||
[[currentFile pathExtension] isEqualToString:@"mpkg"])
{
isPackage = YES;
newAppDownloadPath = currentPath;
break;
if ([[[currentFile lastPathComponent] stringByDeletingPathExtension] isEqualToString:[bundleFileName stringByDeletingPathExtension]])
{
isPackage = YES;
newAppDownloadPath = currentPath;
break;
}
else
{
// Remember any other non-matching packages we have seen should we need to use one of them as a fallback.
fallbackPackagePath = currentPath;
}
}
else
{
// Try matching on bundle identifiers in case the user has changed the name of the host app
NSBundle *incomingBundle = [NSBundle bundleWithPath:currentPath];
if(incomingBundle && [[incomingBundle bundleIdentifier] isEqualToString:[[host bundle] bundleIdentifier]])
{
isPackage = NO;
newAppDownloadPath = currentPath;
break;
}
}
// Some DMGs have symlinks into /Applications! That's no good! And there's no point in looking in bundles.
if ([[NSFileManager defaultManager] isAliasFolderAtPath:currentPath] ||
[[currentFile pathExtension] isEqualToString:[[hostBundle bundlePath] pathExtension]] ||
[[currentFile pathExtension] isEqualToString:@"pkg"] ||
[[currentFile pathExtension] isEqualToString:@"mpkg"])
{
// Some DMGs have symlinks into /Applications! That's no good!
if ([self isAliasFolderAtPath:currentPath])
[dirEnum skipDescendents];
}
}
// We don't have a valid path. Try to use the fallback package.
if (newAppDownloadPath == nil && fallbackPackagePath != nil)
{
isPackage = YES;
newAppDownloadPath = fallbackPackagePath;
}
if (isPackagePtr) *isPackagePtr = isPackage;
return newAppDownloadPath;
}
+ (NSString *)appPathInUpdateFolder:(NSString *)updateFolder forHost:(SUHost *)host
{
BOOL isPackage = NO;
NSString *path = [self installSourcePathInUpdateFolder:updateFolder forHost:host isPackage:&isPackage];
return isPackage ? nil : path;
}
+ (void)installFromUpdateFolder:(NSString *)inUpdateFolder overHost:(SUHost *)host installationPath:(NSString *)installationPath delegate:delegate synchronously:(BOOL)synchronously versionComparator:(id <SUVersionComparison>)comparator
{
BOOL isPackage = NO;
NSString *newAppDownloadPath = [self installSourcePathInUpdateFolder:inUpdateFolder forHost:host isPackage:&isPackage];
if (newAppDownloadPath == nil)
{
[self _finishInstallationWithResult:NO hostBundle:hostBundle error:[NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingUpdateError userInfo:[NSDictionary dictionaryWithObject:@"Couldn't find an appropriate update in the downloaded package." forKey:NSLocalizedDescriptionKey]] delegate:delegate];
[self finishInstallationToPath:installationPath withResult:NO host:host error:[NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingUpdateError userInfo:[NSDictionary dictionaryWithObject:@"Couldn't find an appropriate update in the downloaded package." forKey:NSLocalizedDescriptionKey]] delegate:delegate];
}
else
{
[(isPackage ? [SUPackageInstaller class] : [SUPlainInstaller class]) performInstallationWithPath:newAppDownloadPath hostBundle:hostBundle delegate:delegate synchronously:synchronously];
[(isPackage ? [SUPackageInstaller class] : [SUPlainInstaller class]) performInstallationToPath:installationPath fromPath:newAppDownloadPath host:host delegate:delegate synchronously:synchronously versionComparator:comparator];
}
}
+ (void)_mdimportBundle:(NSBundle *)bundle
+ (void)mdimportInstallationPath:(NSString *)installationPath
{
// *** GETS CALLED ON NON-MAIN THREAD!
SULog( @"mdimporting" );
NSTask *mdimport = [[[NSTask alloc] init] autorelease];
[mdimport setLaunchPath:@"/usr/bin/mdimport"];
[mdimport setArguments:[NSArray arrayWithObject:[bundle bundlePath]]];
[mdimport launch];
[mdimport setArguments:[NSArray arrayWithObject:installationPath]];
@try
{
[mdimport launch];
[mdimport waitUntilExit];
}
@catch (NSException * launchException)
{
// No big deal.
SULog(@"Sparkle Error: %@", [launchException description]);
}
}
+ (void)_finishInstallationWithResult:(BOOL)result hostBundle:(NSBundle *)hostBundle error:(NSError *)error delegate:delegate
#define SUNotifyDictHostKey @"SUNotifyDictHost"
#define SUNotifyDictErrorKey @"SUNotifyDictError"
#define SUNotifyDictDelegateKey @"SUNotifyDictDelegate"
+ (void)finishInstallationToPath:(NSString *)installationPath withResult:(BOOL)result host:(SUHost *)host error:(NSError *)error delegate:delegate
{
if (result == YES)
if (result)
{
[self _mdimportBundle:hostBundle];
if ([delegate respondsToSelector:@selector(installerFinishedForHostBundle:)])
[delegate installerFinishedForHostBundle:hostBundle];
[self mdimportInstallationPath:installationPath];
if ([delegate respondsToSelector:@selector(installerFinishedForHost:)])
[delegate performSelectorOnMainThread: @selector(installerFinishedForHost:) withObject: host waitUntilDone: NO];
}
else
{
if ([delegate respondsToSelector:@selector(installerForHostBundle:failedWithError:)])
[delegate installerForHostBundle:hostBundle failedWithError:error];
if ([delegate respondsToSelector:@selector(installerForHost:failedWithError:)])
[self performSelectorOnMainThread: @selector(notifyDelegateOfFailure:) withObject: [NSDictionary dictionaryWithObjectsAndKeys: host, SUNotifyDictHostKey, error, SUNotifyDictErrorKey, delegate, SUNotifyDictDelegateKey, nil] waitUntilDone: NO];
}
}
+(void) notifyDelegateOfFailure: (NSDictionary*)dict
{
[[dict objectForKey: SUNotifyDictDelegateKey] installerForHost: [dict objectForKey: SUNotifyDictHostKey] failedWithError: [dict objectForKey: SUNotifyDictErrorKey]];
}
@end
+31
View File
@@ -0,0 +1,31 @@
/*
* SULog.h
* EyeTV
*
* Created by Uli Kusterer on 12/03/2009.
* Copyright 2008 Elgato Systems GmbH. All rights reserved.
*
*/
/*
Log output for troubleshooting Sparkle failures on end-user machines.
Your tech support will hug you if you tell them about this.
*/
#pragma once
// -----------------------------------------------------------------------------
// Headers:
// -----------------------------------------------------------------------------
#include <Foundation/Foundation.h>
// -----------------------------------------------------------------------------
// Prototypes:
// -----------------------------------------------------------------------------
void SUClearLog( void );
void SULog( NSString* format, ... );
+80
View File
@@ -0,0 +1,80 @@
/*
* SULog.m
* EyeTV
*
* Created by Uli Kusterer on 12/03/2009.
* Copyright 2009 Elgato Systems GmbH. All rights reserved.
*
*/
// -----------------------------------------------------------------------------
// Headers:
// -----------------------------------------------------------------------------
#include "SULog.h"
// -----------------------------------------------------------------------------
// Constants:
// -----------------------------------------------------------------------------
#define LOG_FILE_PATH @"~/Library/Logs/SparkleUpdateLog.log"
// -----------------------------------------------------------------------------
// SUClearLog:
// Erase the log at the start of an update. We don't want to litter the
// user's hard disk with logging data that's mostly unused, so each app
// should clear the log before it starts updating, so only the most recent
// update is kept around.
//
// TAKES:
// sender - Object that sent this message, typically of type X.
//
// GIVES:
// param - who owns the returned value?
// result - same here.
// -----------------------------------------------------------------------------
void SUClearLog( void )
{
FILE* logfile = fopen([[LOG_FILE_PATH stringByExpandingTildeInPath] fileSystemRepresentation],"w");
if( logfile )
fclose(logfile);
else
NSLog(@"----- Sparkle Log -----");
}
// -----------------------------------------------------------------------------
// SULog:
// Like NSLog, but logs to one specific log file. Each line is prefixed
// with the current date and time, to help in regressing issues.
//
// TAKES:
// format - NSLog/printf-style format string.
// ... - More parameters depending on format string's contents.
// -----------------------------------------------------------------------------
void SULog( NSString* format, ... )
{
va_list ap;
va_start(ap, format);
NSString* theStr = [[[NSString alloc] initWithFormat: format arguments: ap] autorelease];
FILE* logfile = fopen([[LOG_FILE_PATH stringByExpandingTildeInPath] fileSystemRepresentation],"a");
if( !logfile )
NSLog( @"%@",theStr );
else
{
theStr = [NSString stringWithFormat: @"%@: %@", [NSDate date], theStr];
NSData* theData = [theStr dataUsingEncoding: NSUTF8StringEncoding];
char newlineChar = '\n';
fwrite( [theData bytes], 1, [theData length], logfile );
fwrite( &newlineChar, 1, 1, logfile ); // Append a newline.
fclose( logfile );
logfile = NULL;
}
va_end(ap);
}
+25 -17
View File
@@ -4,6 +4,20 @@
<dict>
<key>ADP2,1</key>
<string>Developer Transition Kit</string>
<key>iMac1,1</key>
<string>iMac G3 (Rev A-D)</string>
<key>iMac4,1</key>
<string>iMac (Core Duo)</string>
<key>iMac4,2</key>
<string>iMac for Education (17-inch, Core Duo)</string>
<key>iMac5,1</key>
<string>iMac (Core 2 Duo, 17 or 20 inch, SuperDrive)</string>
<key>iMac5,2</key>
<string>iMac (Core 2 Duo, 17 inch, Combo Drive)</string>
<key>iMac6,1</key>
<string>iMac (Core 2 Duo, 24 inch, SuperDrive)</string>
<key>iMac8,1</key>
<string>iMac (April 2008)</string>
<key>MacBook1,1</key>
<string>MacBook (Core Duo)</string>
<key>MacBook2,1</key>
@@ -12,6 +26,10 @@
<string>MacBook (Core 2 Duo Feb 2008)</string>
<key>MacBookAir1,1</key>
<string>MacBook Air (January 2008)</string>
<key>MacBookAir2,1</key>
<string>MacBook Air (June 2009)</string>
<key>MacBookAir3,1</key>
<string>MacBook Air (October 2010)</string>
<key>MacBookPro1,1</key>
<string>MacBook Pro Core Duo (15-inch)</string>
<key>MacBookPro1,2</key>
@@ -26,14 +44,18 @@
<string>MacBook Pro Core 2 Duo (17-inch HD, Core 2 Duo)</string>
<key>MacBookPro4,1</key>
<string>MacBook Pro (Core 2 Duo Feb 2008)</string>
<key>Macmini1,1</key>
<string>Mac Mini (Core Solo/Duo)</string>
<key>MacPro1,1</key>
<string>Mac Pro (four-core)</string>
<key>MacPro2,1</key>
<string>Mac Pro (eight-core)</string>
<key>MacPro3,1</key>
<string>Mac Pro (January 2008 4- or 8- core "Harpertown")</string>
<key>Macmini1,1</key>
<string>Mac Mini (Core Solo/Duo)</string>
<string>Mac Pro (January 2008 4- or 8- core &quot;Harpertown&quot;)</string>
<key>MacPro4,1</key>
<string>Mac Pro (March 2009)</string>
<key>MacPro5,1</key>
<string>Mac Pro (August 2010)</string>
<key>PowerBook1,1</key>
<string>PowerBook G3</string>
<key>PowerBook2,1</key>
@@ -156,19 +178,5 @@
<string>Xserve (Intel Xeon)</string>
<key>Xserve2,1</key>
<string>Xserve (January 2008 quad-core)</string>
<key>iMac1,1</key>
<string>iMac G3 (Rev A-D)</string>
<key>iMac4,1</key>
<string>iMac (Core Duo)</string>
<key>iMac4,2</key>
<string>iMac for Education (17-inch, Core Duo)</string>
<key>iMac5,1</key>
<string>iMac (Core 2 Duo, 17 or 20 inch, SuperDrive)</string>
<key>iMac5,2</key>
<string>iMac (Core 2 Duo, 17 inch, Combo Drive)</string>
<key>iMac6,1</key>
<string>iMac (Core 2 Duo, 24 inch, SuperDrive)</string>
<key>iMac8,1</key>
<string>iMac (April 2008)</string>
</dict>
</plist>
-2
View File
@@ -9,11 +9,9 @@
#ifndef SUPACKAGEINSTALLER_H
#define SUPACKAGEINSTALLER_H
#import "Sparkle.h"
#import "SUPlainInstaller.h"
@interface SUPackageInstaller : SUPlainInstaller { }
+ (void)installPath:(NSString *)path overHostBundle:(NSBundle *)bundle delegate:delegate;
@end
#endif
Loaded 100 of 401 files, more files were not shown because too many files have changed in this diff. Show more