Compare commits

..
510 Commits
Author SHA1 Message Date
Antonin Hildebrand 5b1f7fc88d HACK: never ever ask for password (we don't ship encrypted DMGz)
http://discuss.binaryage.com/t/the-update-asked-for-my-password-why/838
2013-11-07 21:47:19 +00:00
Antonin Hildebrand f50dde6a50 comment out logging statement again 2013-07-03 20:06:07 -07:00
Antonin Hildebrand efe2a7db68 do NOT check for updates when network is not available 2013-07-03 19:21:46 -07:00
Antonin Hildebrand bd365be8b2 solve warnings in Asepsis project 2013-07-02 21:39:05 -07:00
Antonin Hildebrand 374a62495b converted project under XCode5 2013-06-12 21:16:41 -07:00
Antonin Hildebrand 71228f248c enable DWARF+dSYM generation for Release builds 2013-03-19 15:19:58 +01:00
Antonin Hildebrand 731321f861 fix XCode 4.6 warnings 2013-02-24 11:55:20 +01:00
Antonin Hildebrand 333098985b fixes for XCode 4.6 project 2013-02-24 11:36:36 +01:00
Antonin Hildebrand 891be09d49 fix unsafe string manipulation, XCode 4.5 treats it as error 2013-01-08 18:32:29 +01:00
Antonin Hildebrand 8f1e63c8d3 all projects build 64-bit only with latest SDK 2013-01-08 18:27:50 +01:00
Antonin Hildebrand 7021e4356f fix duplicit Sparle.strings 2013-01-06 23:41:33 +01:00
Antonin Hildebrand f9fd4d16c8 disable some static analyzer warnings 2012-12-14 00:24:58 +01:00
Antonin Hildebrand 5c22d0e46e fix broken tr.lproj/Sparkle.strings 2012-12-14 00:16:49 +01:00
Antonin Hildebrand c4de5e38a8 define correct dependencies on locale scripts 2012-12-14 00:10:10 +01:00
Antonin Hildebrand 1ad1373357 disable verbose output in build logs 2012-12-14 00:10:10 +01:00
Antonin Hildebrand a5ea60b5a8 update project settings for Xcode 4.5 2012-12-14 00:10:10 +01:00
Antonin Hildebrand 9b05410c95 hack for TotalFinder, this should be configurable from outside 2012-12-14 00:10:10 +01:00
Antonin Hildebrand 6fd2fc832b make it compile under Xcode 4.2 2012-12-14 00:08:55 +01:00
Antonin Hildebrand 7a1dc310d6 Sparkle source code should be independent on bundle identifier 2012-12-14 00:08:55 +01:00
Antonin Hildebrand 6d967e8641 use shared bundle identifier com.binaryage.sparkle 2012-12-14 00:08:55 +01:00
Antonin Hildebrand 36b35865fb force Sparkle to use my own bundle identifer 2012-12-14 00:08:55 +01: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
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
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
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
367 changed files with 97976 additions and 4239 deletions

No files matched your search

-4
View File
@@ -1,4 +0,0 @@
*.pbxuser
.DS_Store
*.perspective*
.svn
@@ -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"
+17 -4
View File
@@ -3,17 +3,21 @@
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.7
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
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
ARCHS = ppc i386 x86_64
GCC_VERSION = com.apple.compilers.llvm.clang.1_0
CLANG_LINK_OBJC_RUNTIME = NO
// Enable warnings
GCC_WARN_CHECK_SWITCH_STATEMENTS = YES
@@ -35,4 +39,13 @@ 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
WARNING_CFLAGS = -Wall -Wno-unused-parameter -Werror -Wundef -Wendif-labels -Wpointer-arith -Wcast-align -Wwrite-strings -Wmissing-format-attribute -Wpacked -Wredundant-decls -Winline -Wdisabled-optimization -Winvalid-pch
+4 -2
View File
@@ -3,6 +3,8 @@
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)
// Add $(SPARKLE_EXTRA_DEBUG_10_5_ONLY) to SPARKLE_EXTRA_DEBUG if your deployment is 10.5 or greater.
@@ -6,4 +6,3 @@ 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
+2 -2
View File
@@ -1,10 +1,10 @@
// Framework only
INSTALL_PATH = @executable_path/../Frameworks
INSTALL_PATH = @loader_path/../Frameworks
DYLIB_COMPATIBILITY_VERSION = 1.5
DYLIB_CURRENT_VERSION = 1.5
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
@@ -1,3 +1,3 @@
#include "ConfigFrameworkRelease.xcconfig"
GCC_ENABLE_OBJC_GC = supported
//GCC_ENABLE_OBJC_GC = supported
+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
+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
+10
View File
@@ -0,0 +1,10 @@
// 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
MACOSX_DEPLOYMENT_TARGET = 10.6
@@ -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
+5 -5
View File
@@ -6,22 +6,22 @@
<string>en</string>
<key>CFBundleExecutable</key>
<string>${EXECUTABLE_NAME}</string>
<key>CFBundleName</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundleIconFile</key>
<string></string>
<key>CFBundleIdentifier</key>
<string>org.andymatuschak.Sparkle</string>
<string>com.binaryage.sparkle</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>1.5 Beta (git)</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1.5</string>
<key>CFBundleShortVersionString</key>
<string>1.5 Beta (bzr)</string>
<key>NSPrincipalClass</key>
<string></string>
</dict>
+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
+8 -1
View File
@@ -11,6 +11,7 @@
@interface NTSynchronousTask : NSObject
{
@private
NSTask *mv_task;
NSPipe *mv_outputPipe;
NSPipe *mv_inputPipe;
@@ -22,7 +23,13 @@
// pass nil for directory if not needed
// returns the result
+ (NSData*)task:(NSString*)toolPath directory:(NSString*)currentDirectory withArgs:(NSArray*)args input:(NSData*)input;
+(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
+153 -147
View File
@@ -6,151 +6,15 @@
// Copyright 2005 Steve Gehrman. All rights reserved.
//
#import "Sparkle.h"
#import "SUUpdater.h"
#import "SUAppcast.h"
#import "SUAppcastItem.h"
#import "SUVersionComparisonProtocol.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
@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 +105,6 @@
mv_result = theResult;
}
@end
@implementation NTSynchronousTask (Notifications)
- (void)taskOutputAvailable:(NSNotification*)note
{
[self setOutput:[[note userInfo] objectForKey:NSFileHandleNotificationDataItem]];
@@ -257,6 +117,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
+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!")
+1 -1
View File
@@ -7,7 +7,7 @@
<key>CFBundleExecutable</key>
<string>${EXECUTABLE_NAME}</string>
<key>CFBundleIdentifier</key>
<string>org.andymatuschak.Sparkle.relaunch</string>
<string>com.binaryage.totalfinder.sparkle.relaunch</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundlePackageType</key>
+6 -3
View File
@@ -9,12 +9,15 @@
#ifndef SUAPPCAST_H
#define SUAPPCAST_H
@class RSS, SUAppcastItem;
@interface SUAppcast : NSObject {
@class SUAppcastItem;
@interface SUAppcast : NSObject<NSURLDownloadDelegate>
{
@private
NSArray *items;
NSString *userAgentString;
id delegate;
NSMutableData *incrementalData;
NSString *downloadFilename;
NSURLDownload *download;
}
- (void)fetchAppcastFromURL:(NSURL *)url;
+162 -41
View File
@@ -6,11 +6,35 @@
// Copyright 2006 Andy Matuschak. All rights reserved.
//
#import "Sparkle.h"
#import "SUAppcast.h"
#import "SUUpdater.h"
@interface SUAppcast (Private)
#import "SUAppcast.h"
#import "SUAppcastItem.h"
#import "SUVersionComparisonProtocol.h"
#import "SUAppcast.h"
#import "SUConstants.h"
#import "SULog.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 +42,14 @@
- (void)dealloc
{
[items release];
items = nil;
[userAgentString release];
userAgentString = nil;
[downloadFilename release];
downloadFilename = nil;
[download release];
download = nil;
[super dealloc];
}
@@ -32,26 +64,59 @@
if (userAgentString)
[request setValue:userAgentString forHTTPHeaderField:@"User-Agent"];
incrementalData = [[NSMutableData alloc] init];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
CFRetain(connection);
download = [[NSURLDownload alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
- (void)download:(NSURLDownload *)aDownload decideDestinationWithSuggestedFilename:(NSString *)filename
{
[incrementalData appendData:data];
NSString* destinationFilename = NSTemporaryDirectory();
if (destinationFilename)
{
destinationFilename = [destinationFilename stringByAppendingPathComponent:filename];
[download setDestination:destinationFilename allowOverwrite:NO];
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
- (void)download:(NSURLDownload *)aDownload didCreateDestination:(NSString *)path
{
CFRelease(connection);
[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 +135,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 +180,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 +230,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,6 +259,31 @@
}
}
- (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)
+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://"]) // if the description starts with http://, 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];
}
+3 -3
View File
@@ -18,14 +18,14 @@ typedef enum
SUDoNotInstallChoice
} SUAutomaticInstallationChoice;
@class SUAppcastItem;
@class SUAppcastItem, SUHost;
@interface SUAutomaticUpdateAlert : SUWindowController {
SUAppcastItem *updateItem;
id delegate;
NSBundle *hostBundle;
SUHost *host;
}
- (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;
+10 -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,12 @@
- (void)dealloc
{
[hostBundle release];
[host release];
[updateItem release];
[super dealloc];
}
- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@, %@>", [self class], [host bundlePath], [host installationPath]]; }
- (IBAction)installNow:sender
{
@@ -53,17 +55,17 @@
- (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]];
}
@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;
}
+20 -14
View File
@@ -7,13 +7,26 @@
//
#import "SUAutomaticUpdateDriver.h"
#import "Sparkle.h"
#import "SUAutomaticUpdateAlert.h"
#import "SUHost.h"
#import "SUConstants.h"
@implementation SUAutomaticUpdateDriver
- (void)unarchiverDidFinish:(SUUnarchiver *)ua
{
alert = [[SUAutomaticUpdateAlert alloc] initWithAppcastItem:updateItem hostBundle:hostBundle delegate:self];
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
@@ -31,7 +44,7 @@
switch (choice)
{
case SUInstallNowChoice:
[self installUpdate];
[self installWithToolAndRelaunch:YES];
break;
case SUInstallLaterChoice:
@@ -40,7 +53,7 @@
break;
case SUDoNotInstallChoice:
[[SUUserDefaults standardUserDefaults] setObject:[updateItem versionString] forKey:SUSkippedVersionKey];
[host setObject:[updateItem versionString] forUserDefaultsKey:SUSkippedVersionKey];
[self abortUpdate];
break;
}
@@ -48,22 +61,15 @@
- (BOOL)shouldInstallSynchronously { return postponingInstallation; }
- (void)installUpdate
- (void)installWithToolAndRelaunch:(BOOL)relaunch
{
showErrors = YES;
[super installUpdate];
[super installWithToolAndRelaunch:relaunch];
}
- (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
+9 -9
View File
@@ -12,18 +12,19 @@
#import <Cocoa/Cocoa.h>
#import "SUUpdateDriver.h"
@class SUAppcastItem, SUUnarchiver, SUAppcast, SUUnarchiver;
@interface SUBasicUpdateDriver : SUUpdateDriver {
NSBundle *hostBundle;
@class SUAppcastItem, SUUnarchiver, SUAppcast, SUUnarchiver, SUHost;
@interface SUBasicUpdateDriver : SUUpdateDriver<NSURLDownloadDelegate> {
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;
@@ -43,13 +44,12 @@
- (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)relaunchHostApp;
- (void)cleanUp;
- (void)cleanUpDownload;
- (void)abortUpdate;
- (void)abortUpdateWithError:(NSError *)error;
+248 -128
View File
@@ -7,61 +7,87 @@
//
#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"
@interface SUBasicUpdateDriver () <NSURLDownloadDelegate>; @end
@implementation SUBasicUpdateDriver
- (void)checkForUpdatesAtURL:(NSURL *)appcastURL hostBundle:(NSBundle *)hb
{
hostBundle = [hb retain];
if ([hostBundle isRunningFromDiskImage])
- (void)checkForUpdatesAtURL:(NSURL *)URL host:(SUHost *)aHost
{
[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;
}
}
SUAppcast *appcast = [[SUAppcast alloc] init];
CFRetain(appcast); // We'll manage the appcast's memory ourselves so we don't have to make it an IV to support GC.
[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)
comparator = [SUStandardVersionComparator defaultComparator];
return comparator;
return comparator;
}
- (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,27 +97,37 @@
- (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])
[self didFindValidUpdate];
else
@@ -100,27 +136,29 @@
- (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)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"];
download = [[NSURLDownload alloc] initWithRequest:request delegate:self];
}
- (void)download:(NSURLDownload *)d decideDestinationWithSuggestedFilename:(NSString *)name
@@ -128,26 +166,60 @@
// 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]]];
}
downloadPath = [[tempDir stringByAppendingPathComponent:name] retain];
[download setDestination:downloadPath allowOverwrite:YES];
}
- (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];
@@ -155,28 +227,22 @@
- (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,88 +251,140 @@
[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
relaunch = NO; // TOTALFINDER-related HACK to prevent relaunch, installer does relaunch automatically
[self cleanUp]; // Clean up the download and extracted files.
[[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterWillRestartNotification object:self];
if ([delegate respondsToSelector:@selector(updaterWillRelaunchApplication)])
[delegate updaterWillRelaunchApplication];
if(!relaunchPath || ![[NSFileManager defaultManager] fileExistsAtPath:relaunchPath])
if (![updater mayUpdateAndRestart])
{
[self abortUpdate];
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;
}
if ([[updater delegate] respondsToSelector:@selector(updater:willInstallUpdate:)])
[[updater delegate] updater:updater willInstallUpdate:updateItem];
// 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;
#if MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_4
[[NSFileManager defaultManager] createDirectoryAtPath: [targetPath stringByDeletingLastPathComponent] attributes: [NSDictionary dictionary]];
#else
[[NSFileManager defaultManager] createDirectoryAtPath: [targetPath stringByDeletingLastPathComponent] withIntermediateDirectories: YES attributes: [NSDictionary dictionary] error: &error];
#endif
// Only the paranoid survive: if there's already a stray copy of relaunch there, we would have problems.
if( [SUPlainInstaller copyPathWithAuthentication: relaunchPathToCopy overPath: targetPath temporaryName: nil error: &error] )
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]]];
[[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterWillRestartNotification object:self];
if ([[updater delegate] respondsToSelector:@selector(updaterWillRelaunchApplication:)])
[[updater delegate] updaterWillRelaunchApplication: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 *pathToRelaunch = [host bundlePath];
if ([[updater delegate] respondsToSelector:@selector(pathToRelaunchForUpdater:)])
pathToRelaunch = [[updater delegate] pathToRelaunchForUpdater:updater];
NSString *relaunchToolPath = [relaunchPath stringByAppendingPathComponent: @"/Contents/MacOS/finish_installation"];
[NSTask launchedTaskWithLaunchPath: relaunchToolPath arguments:[NSArray arrayWithObjects:[host bundlePath], pathToRelaunch, [NSString stringWithFormat:@"%d", [[NSProcessInfo processInfo] processIdentifier]], tempDir, relaunch ? @"1" : @"0", nil]];
[NSApp terminate:self];
}
- (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
{
[[self retain] autorelease]; // In case the notification center was the last one holding on to us.
[self cleanUpDownload];
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super abortUpdate];
}
@@ -274,9 +392,9 @@
- (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];
@@ -284,9 +402,11 @@
- (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
+48
View File
@@ -0,0 +1,48 @@
//
// 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"
#import "NTSynchronousTask.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
+19
View File
@@ -0,0 +1,19 @@
//
// 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;
@end
#endif
+86
View File
@@ -0,0 +1,86 @@
//
// 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));
+ (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
{
// This API didn't exist prior to 10.6.
if (SecCodeCopySelf == NULL) return NO;
OSStatus result;
SecCodeRef hostCode = NULL;
result = SecCodeCopySelf(kSecCSDefaultFlags, &hostCode);
if (result != 0) return NO;
SecRequirementRef requirement = NULL;
result = SecCodeCopyDesignatedRequirement(hostCode, kSecCSDefaultFlags, &requirement);
if (hostCode) CFRelease(hostCode);
if (requirement) CFRelease(requirement);
return (result == 0);
}
@end
+59 -18
View File
@@ -10,27 +10,62 @@
#ifndef SUCONSTANTS_H
#define SUCONSTANTS_H
// -----------------------------------------------------------------------------
// Preprocessor flags:
// -----------------------------------------------------------------------------
extern NSString *SUUpdaterWillRestartNotification;
extern NSString *SUTechnicalErrorInformationKey;
// Turn off DSA signature check (practically invites man-in-the-middle attacks):
#define ENDANGER_USERS_WITH_INSECURE_UPDATES 0
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;
// 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
extern NSString *SUSparkleErrorDomain;
// 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;
// -----------------------------------------------------------------------------
// 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 +86,12 @@ extern OSStatus SUMissingUpdateError;
extern OSStatus SUMissingInstallerToolError;
extern OSStatus SURelaunchError;
extern OSStatus SUInstallationError;
extern OSStatus SUDowngradeError;
// -----------------------------------------------------------------------------
// 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:
+29 -19
View File
@@ -6,29 +6,38 @@
// Copyright 2006 Andy Matuschak. All rights reserved.
//
#import "Sparkle.h"
#import "SUUpdater.h"
#import "SUAppcast.h"
#import "SUAppcastItem.h"
#import "SUVersionComparisonProtocol.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 +54,4 @@ OSStatus SUMissingUpdateError = 4002;
OSStatus SUMissingInstallerToolError = 4003;
OSStatus SURelaunchError = 4004;
OSStatus SUInstallationError = 4005;
OSStatus SUDowngradeError = 4006;
+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
+357
View File
@@ -0,0 +1,357 @@
//
// 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>
/* 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;
}
+180 -53
View File
@@ -9,71 +9,198 @@
#import "SUDiskImageUnarchiver.h"
#import "SUUnarchiver_Private.h"
#import "NTSynchronousTask.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];
NSData *result = [NTSynchronousTask task:@"/usr/bin/hdiutil" directory:@"/" withArgs:[NSArray arrayWithObjects: @"isencrypted", archivePath, nil] input:NULL];
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 *mountPointName = nil;
NSString *mountPoint = nil;
FSRef tmpRef;
do
{
CFUUIDRef uuid = CFUUIDCreate(NULL);
if (uuid)
{
CFStringRef uuidString = CFUUIDCreateString(NULL, uuid);
if (uuidString)
{
mountPoint = [@"/Volumes" stringByAppendingPathComponent:(NSString*)uuidString];
CFRelease(uuidString);
}
CFRelease(uuid);
}
}
while (noErr == FSPathMakeRefWithOptions((UInt8 *)[mountPoint fileSystemRepresentation], kFSPathMakeRefDoNotFollowLeafSymlink, &tmpRef, NULL));
NSData *promptData = nil;
if (password) {
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];
NSArray* arguments = [NSArray arrayWithObjects:@"attach", archivePath, @"-mountpoint", mountPoint, /*@"-noverify",*/ @"-nobrowse", @"-noautoopen", nil];
NSData *output = nil;
NSInteger taskResult = -1;
@try
{
NTSynchronousTask* task = [[NTSynchronousTask alloc] init];
[task run:@"/usr/bin/hdiutil" directory:@"/" withArgs:arguments input:promptData];
taskResult = [task result];
output = [[[task output] copy] autorelease];
[task release];
}
@catch (NSException *localException)
{
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) {
// 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;
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 {
FSRef srcRef, dstRef;
OSStatus err;
err = FSPathMakeRef((UInt8 *)[mountPoint fileSystemRepresentation], &srcRef, NULL);
if (err != noErr) goto reportError;
err = FSPathMakeRef((UInt8 *)[[archivePath stringByDeletingLastPathComponent] fileSystemRepresentation], &dstRef, NULL);
if (err != noErr) goto reportError;
err = FSCopyObjectSync(&srcRef, &dstRef, (CFStringRef)mountPointName, NULL, kFSFileOperationSkipSourcePermissionErrors);
if (err != noErr) 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]];
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>
+5 -2
View File
@@ -9,11 +9,14 @@
#ifndef SUPACKAGEINSTALLER_H
#define SUPACKAGEINSTALLER_H
#import "Sparkle.h"
#import "SUUpdater.h"
#import "SUAppcast.h"
#import "SUAppcastItem.h"
#import "SUVersionComparisonProtocol.h"
#import "SUPlainInstaller.h"
@interface SUPackageInstaller : SUPlainInstaller { }
+ (void)installPath:(NSString *)path overHostBundle:(NSBundle *)bundle delegate:delegate;
@end
#endif
+52 -12
View File
@@ -7,26 +7,66 @@
//
#import "SUPackageInstaller.h"
#import <Cocoa/Cocoa.h>
#import "SUConstants.h"
NSString *SUPackageInstallerCommandKey = @"SUPackageInstallerCommand";
NSString *SUPackageInstallerArgumentsKey = @"SUPackageInstallerArguments";
NSString *SUPackageInstallerHostKey = @"SUPackageInstallerHost";
NSString *SUPackageInstallerDelegateKey = @"SUPackageInstallerDelegate";
NSString *SUPackageInstallerInstallationPathKey = @"SUPackageInstallerInstallationPathKey";
@implementation SUPackageInstaller
+ (void)installPath:(NSString *)path overHostBundle:(NSBundle *)bundle delegate:delegate
+ (void)finishInstallationWithInfo:(NSDictionary *)info
{
NSError *error = nil;
BOOL result = YES;
[self finishInstallationToPath:[info objectForKey:SUPackageInstallerInstallationPathKey] withResult:YES host:[info objectForKey:SUPackageInstallerHostKey] error:nil delegate:[info objectForKey:SUPackageInstallerDelegateKey]];
}
+ (void)performInstallationWithInfo:(NSDictionary *)info
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *installerPath = [[NSWorkspace sharedWorkspace] absolutePathForAppBundleWithIdentifier:@"com.apple.installer"];
installerPath = [installerPath stringByAppendingString:@"/Contents/MacOS/Installer"];
if (![[NSFileManager defaultManager] fileExistsAtPath:installerPath])
{
error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingInstallerToolError userInfo:[NSDictionary dictionaryWithObject:@"Couldn't find Apple's installer tool!" forKey:NSLocalizedDescriptionKey]];
result = NO;
}
NSTask *installer = [NSTask launchedTaskWithLaunchPath:installerPath arguments:[NSArray arrayWithObjects:path, nil]];
NSTask *installer = [NSTask launchedTaskWithLaunchPath:[info objectForKey:SUPackageInstallerCommandKey] arguments:[info objectForKey:SUPackageInstallerArgumentsKey]];
[installer waitUntilExit];
// Known bug: if the installation fails or is canceled, Sparkle goes ahead and restarts, thinking everything is fine.
[self _finishInstallationWithResult:result hostBundle:bundle error:error delegate:delegate];
[self performSelectorOnMainThread:@selector(finishInstallationWithInfo:) withObject:info waitUntilDone:NO];
[pool drain];
}
+ (void)performInstallationToPath:(NSString *)installationPath fromPath:(NSString *)path host:(SUHost *)host delegate:delegate synchronously:(BOOL)synchronously versionComparator:(id <SUVersionComparison>)comparator
{
NSString *command;
NSArray *args;
if (floor(NSAppKitVersionNumber) == NSAppKitVersionNumber10_4) {
// 10.4 uses Installer.app because the "open" command in 10.4 doesn't support -W and -n
command = [[NSBundle bundleWithIdentifier:@"com.apple.installer"] executablePath];
args = [NSArray arrayWithObjects:path, nil];
} else {
// 10.5 and later. Run installer using the "open" command to ensure it is launched in front of current application.
// The -W and -n options were added to the 'open' command in 10.5
// -W = wait until the app has quit.
// -n = Open another instance if already open.
// -b = app bundle identifier
command = @"/usr/bin/open";
args = [NSArray arrayWithObjects:@"-W", @"-n", @"-b", @"com.apple.installer", path, nil];
}
if (![[NSFileManager defaultManager] fileExistsAtPath:command])
{
NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingInstallerToolError userInfo:[NSDictionary dictionaryWithObject:@"Couldn't find Apple's installer tool!" forKey:NSLocalizedDescriptionKey]];
[self finishInstallationToPath:installationPath withResult:NO host:host error:error delegate:delegate];
}
else
{
NSDictionary *info = [NSDictionary dictionaryWithObjectsAndKeys:command, SUPackageInstallerCommandKey, args, SUPackageInstallerArgumentsKey, host, SUPackageInstallerHostKey, delegate, SUPackageInstallerDelegateKey, installationPath, SUPackageInstallerInstallationPathKey, nil];
if (synchronously)
[self performInstallationWithInfo:info];
else
[NSThread detachNewThreadSelector:@selector(performInstallationWithInfo:) toTarget:self withObject:info];
}
}
@end
+26
View File
@@ -0,0 +1,26 @@
//
// SUPasswordPrompt.h
// Sparkle
//
// Created by rudy on 8/18/09.
// Copyright 2009 Ambrosia Software, Inc.. All rights reserved.
//
#import <Cocoa/Cocoa.h>
#import "Sparkle/SUWindowController.h"
@interface SUPasswordPrompt : SUWindowController
{
IBOutlet NSImageView *mIconView;
IBOutlet NSTextField *mTextDescription;
IBOutlet NSSecureTextField *mPasswordField;
NSString *mPassword;
NSString *mName;
NSImage *mIcon;
}
- (id)initWithHost:(SUHost *)aHost;
- (NSInteger)run;
- (NSString *)password;
@end
+86
View File
@@ -0,0 +1,86 @@
//
// SUPasswordPrompt.m
// Sparkle
//
// Created by rudy on 8/18/09.
// Copyright 2009 Ambrosia Software, Inc.. All rights reserved.
//
#import "SUPasswordPrompt.h"
@implementation SUPasswordPrompt
- (id)initWithHost:(SUHost *)aHost
{
self = [super initWithHost:aHost windowNibName:@"SUPasswordPrompt"];
if (self)
{
[self setName:[aHost name]];
[self setIcon:[aHost icon]];
mPassword = nil;
[self setShouldCascadeWindows:NO];
}
return self;
}
- (void)awakeFromNib
{
[mIconView setImage:[self icon]];
}
- (void)setName:(NSString*)name
{
[mName release];
mName = [name retain];
}
- (NSString*)name
{
return mName;
}
- (void)setIcon:(NSImage*)icon
{
[mIcon release];
mIcon = [icon retain];
}
- (NSImage*)icon
{
return mIcon;
}
- (NSString *)password
{
return mPassword;
}
- (void)setPassword:(NSString*)password
{
[mPassword release];
mPassword = [password retain];
}
- (NSInteger)run
{
//modally run a password prompt
NSInteger result = [NSApp runModalForWindow:[self window]];
if(result)
[self setPassword:[mPasswordField stringValue]];
return result;
}
- (IBAction)accept:(id)sender
{
[[self window] orderOut:self];
[NSApp stopModalWithCode:1];
}
- (IBAction)cancel:(id)sender
{
[[self window] orderOut:self];
[NSApp stopModalWithCode:0];
}
@end
+63 -29
View File
@@ -8,24 +8,26 @@
#import "SUPipedUnarchiver.h"
#import "SUUnarchiver_Private.h"
#import "SULog.h"
@implementation SUPipedUnarchiver
+ (SEL)_selectorConformingToTypeOfURL:(NSURL *)URL
+ (SEL)selectorConformingToTypeOfPath:(NSString *)path
{
static NSDictionary *typeSelectorDictionary;
// HACK: The UTI detector is dumb (not my fault!) and sees .tar.gz files as plain .gz files. If we see something of type .bz2 or .gz, we'll assume it's really a .tar.bz2 or .tar.gz.
if (!typeSelectorDictionary)
typeSelectorDictionary = [[NSDictionary dictionaryWithObjectsAndKeys:@"_extractZIP", @"com.pkware.zip-archive",
@"_extractTGZ", @"org.gnu.gnu-zip-tar-archive", @"_extractTGZ", @"org.gnu.gnu-zip-archive",
@"_extractTBZ", @"org.bzip.bzip2-tar-archive", @"_extractTBZ", @"org.bzip.bzip2-archive", @"_extractTBZ", @"public.archive.bzip2",
@"_extractTAR", @"public.tar-archive", nil] retain];
typeSelectorDictionary = [[NSDictionary dictionaryWithObjectsAndKeys:@"extractZIP", @".zip", @"extractTAR", @".tar",
@"extractTGZ", @".tar.gz", @"extractTGZ", @".tgz",
@"extractTBZ", @".tar.bz2", @"extractTBZ", @".tbz", nil] retain];
NSString *lastPathComponent = [path lastPathComponent];
NSEnumerator *typeEnumerator = [typeSelectorDictionary keyEnumerator];
id currentType;
while ((currentType = [typeEnumerator nextObject]))
{
if ([URL conformsToType:currentType])
if ([currentType length] > [lastPathComponent length]) continue;
if ([[lastPathComponent substringFromIndex:[lastPathComponent length] - [currentType length]] isEqualToString:currentType])
return NSSelectorFromString([typeSelectorDictionary objectForKey:currentType]);
}
return NULL;
@@ -33,23 +35,32 @@
- (void)start
{
[NSThread detachNewThreadSelector:[[self class] _selectorConformingToTypeOfURL:archiveURL] toTarget:self withObject:nil];
[NSThread detachNewThreadSelector:[[self class] selectorConformingToTypeOfPath:archivePath] toTarget:self withObject:nil];
}
+ (BOOL)_canUnarchiveURL:(NSURL *)URL
+ (BOOL)canUnarchivePath:(NSString *)path
{
return ([self _selectorConformingToTypeOfURL:URL] != nil);
return ([self selectorConformingToTypeOfPath:path] != nil);
}
// This method abstracts the types that use a command line tool piping data from stdin.
- (void)_extractArchivePipingDataToCommand:(NSString *)command
- (void)extractArchivePipingDataToCommand:(NSString *)command
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *archivePath = [archiveURL path];
FILE *fp = NULL, *cmdFP = NULL;
// *** GETS CALLED ON NON-MAIN THREAD!!!
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
FILE *fp = NULL, *cmdFP = NULL;
char *oldDestinationString = NULL;
SULog(@"Extracting %@ using '%@'",archivePath,command);
// Get the file size.
#if MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_4
NSNumber *fs = [[[NSFileManager defaultManager] fileAttributesAtPath:archivePath traverseLink:NO] objectForKey:NSFileSize];
#else
NSNumber *fs = [[[NSFileManager defaultManager] attributesOfItemAtPath:archivePath error:nil] objectForKey:NSFileSize];
#endif
if (fs == nil) goto reportError;
// Thank you, Allan Odgaard!
@@ -57,54 +68,77 @@
fp = fopen([archivePath fileSystemRepresentation], "r");
if (!fp) goto reportError;
oldDestinationString = getenv("DESTINATION");
setenv("DESTINATION", [[archivePath stringByDeletingLastPathComponent] fileSystemRepresentation], 1);
cmdFP = popen([command fileSystemRepresentation], "w");
size_t written;
if (!cmdFP) goto reportError;
char buf[32*1024];
long len;
size_t len;
while((len = fread(buf, 1, 32*1024, fp)))
{
fwrite(buf, 1, len, cmdFP);
[self performSelectorOnMainThread:@selector(_notifyDelegateOfExtractedLength:) withObject:[NSNumber numberWithLong:len] waitUntilDone:NO];
written = fwrite(buf, 1, len, cmdFP);
if( written < len )
{
pclose(cmdFP);
goto reportError;
}
[self performSelectorOnMainThread:@selector(notifyDelegateOfExtractedLength:) withObject:[NSNumber numberWithUnsignedLong:len] waitUntilDone:NO];
}
pclose(cmdFP);
[self performSelectorOnMainThread:@selector(_notifyDelegateOfSuccess) withObject:nil waitUntilDone:NO];
if( ferror( fp ) )
goto reportError;
[self performSelectorOnMainThread:@selector(notifyDelegateOfSuccess) withObject:nil waitUntilDone:NO];
goto finally;
reportError:
[self performSelectorOnMainThread:@selector(_notifyDelegateOfFailure) withObject:nil waitUntilDone:NO];
[self performSelectorOnMainThread:@selector(notifyDelegateOfFailure) withObject:nil waitUntilDone:NO];
finally:
if (fp)
fclose(fp);
[pool drain];
if (oldDestinationString)
setenv("DESTINATION", oldDestinationString, 1);
else
unsetenv("DESTINATION");
[pool release];
}
- (void)_extractTAR
- (void)extractTAR
{
return [self _extractArchivePipingDataToCommand:@"tar -xC \"$DESTINATION\""];
// *** GETS CALLED ON NON-MAIN THREAD!!!
return [self extractArchivePipingDataToCommand:@"tar -xC \"$DESTINATION\""];
}
- (void)_extractTGZ
- (void)extractTGZ
{
return [self _extractArchivePipingDataToCommand:@"tar -zxC \"$DESTINATION\""];
// *** GETS CALLED ON NON-MAIN THREAD!!!
return [self extractArchivePipingDataToCommand:@"tar -zxC \"$DESTINATION\""];
}
- (void)_extractTBZ
- (void)extractTBZ
{
return [self _extractArchivePipingDataToCommand:@"tar -jxC \"$DESTINATION\""];
// *** GETS CALLED ON NON-MAIN THREAD!!!
return [self extractArchivePipingDataToCommand:@"tar -jxC \"$DESTINATION\""];
}
- (void)_extractZIP
- (void)extractZIP
{
return [self _extractArchivePipingDataToCommand:@"ditto -x -k - \"$DESTINATION\""];
// *** GETS CALLED ON NON-MAIN THREAD!!!
return [self extractArchivePipingDataToCommand:@"ditto -x -k - \"$DESTINATION\""];
}
+ (void)load
{
[self _registerImplementation:self];
[self registerImplementation:self];
}
@end
+10 -2
View File
@@ -9,10 +9,18 @@
#ifndef SUPLAININSTALLER_H
#define SUPLAININSTALLER_H
#import "Sparkle.h"
#import "SUUpdater.h"
#import "SUAppcast.h"
#import "SUAppcastItem.h"
#import "SUVersionComparisonProtocol.h"
#import "SUInstaller.h"
#import "SUVersionComparisonProtocol.h"
@class SUHost;
@interface SUPlainInstaller : SUInstaller { }
+ (void)performInstallationWithPath:(NSString *)path hostBundle:(NSBundle *)hostBundle delegate:delegate synchronously:(BOOL)synchronously;
+ (void)performInstallationToPath:(NSString *)installationPath fromPath:(NSString *)path host:(SUHost *)host delegate:delegate synchronously:(BOOL)synchronously versionComparator:(id <SUVersionComparison>)comparator;
@end
#endif
+54 -13
View File
@@ -7,36 +7,77 @@
//
#import "SUPlainInstaller.h"
#import "SUPlainInstallerInternals.h"
#import "SUConstants.h"
#import "SUHost.h"
extern NSString *SUInstallerPathKey;
extern NSString *SUInstallerHostBundleKey;
extern NSString *SUInstallerDelegateKey;
static NSString * const SUInstallerPathKey = @"SUInstallerPath";
static NSString * const SUInstallerTargetPathKey = @"SUInstallerTargetPath";
static NSString * const SUInstallerTempNameKey = @"SUInstallerTempName";
static NSString * const SUInstallerHostKey = @"SUInstallerHost";
static NSString * const SUInstallerDelegateKey = @"SUInstallerDelegate";
static NSString * const SUInstallerResultKey = @"SUInstallerResult";
static NSString * const SUInstallerErrorKey = @"SUInstallerError";
static NSString * const SUInstallerInstallationPathKey = @"SUInstallerInstallationPath";
@implementation SUPlainInstaller
+ (void)installPath:(NSString *)path overHostBundle:(NSBundle *)bundle delegate:delegate
+ (void)finishInstallationWithInfo:(NSDictionary *)info
{
NSError *error;
BOOL result = [[NSFileManager defaultManager] copyPathWithAuthentication:path overPath:[bundle bundlePath] error:&error];
[self _finishInstallationWithResult:result hostBundle:bundle error:error delegate:delegate];
// *** GETS CALLED ON NON-MAIN THREAD!
[self finishInstallationToPath:[info objectForKey:SUInstallerInstallationPathKey] withResult:[[info objectForKey:SUInstallerResultKey] boolValue] host:[info objectForKey:SUInstallerHostKey] error:[info objectForKey:SUInstallerErrorKey] delegate:[info objectForKey:SUInstallerDelegateKey]];
}
+ (void)_performInstallationWithInfo:(NSDictionary *)info
+ (void)performInstallationWithInfo:(NSDictionary *)info
{
// *** GETS CALLED ON NON-MAIN THREAD!
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[self installPath:[info objectForKey:SUInstallerPathKey] overHostBundle:[info objectForKey:SUInstallerHostBundleKey] delegate:[info objectForKey:SUInstallerDelegateKey]];
NSError *error = nil;
NSString * oldPath = [[info objectForKey:SUInstallerHostKey] bundlePath];
NSString * installationPath = [info objectForKey:SUInstallerInstallationPathKey];
BOOL result = [self copyPathWithAuthentication:[info objectForKey:SUInstallerPathKey] overPath: installationPath temporaryName:[info objectForKey:SUInstallerTempNameKey] error:&error];
if( result )
{
BOOL haveOld = [[NSFileManager defaultManager] fileExistsAtPath: oldPath];
BOOL differentFromNew = ![oldPath isEqualToString: installationPath];
if( haveOld && differentFromNew )
[self _movePathToTrash: oldPath]; // On success, trash old copy if there's still one due to renaming.
}
NSMutableDictionary *mutableInfo = [[info mutableCopy] autorelease];
[mutableInfo setObject:[NSNumber numberWithBool:result] forKey:SUInstallerResultKey];
[mutableInfo setObject:installationPath forKey:SUInstallerInstallationPathKey];
if (!result && error)
[mutableInfo setObject:error forKey:SUInstallerErrorKey];
[self performSelectorOnMainThread:@selector(finishInstallationWithInfo:) withObject:mutableInfo waitUntilDone:NO];
[pool drain];
}
+ (void)performInstallationWithPath:(NSString *)path hostBundle:(NSBundle *)hostBundle delegate:delegate synchronously:(BOOL)synchronously;
+ (void)performInstallationToPath:(NSString *)installationPath fromPath:(NSString *)path host:(SUHost *)host delegate:delegate synchronously:(BOOL)synchronously versionComparator:(id <SUVersionComparison>)comparator
{
NSDictionary *info = [NSDictionary dictionaryWithObjectsAndKeys:path, SUInstallerPathKey, hostBundle, SUInstallerHostBundleKey, delegate, SUInstallerDelegateKey, nil];
// Prevent malicious downgrades:
#if !PERMIT_AUTOMATED_DOWNGRADES
if ([comparator compareVersion:[host version] toVersion:[[NSBundle bundleWithPath:path] objectForInfoDictionaryKey:@"CFBundleVersion"]] == NSOrderedDescending)
{
NSString * errorMessage = [NSString stringWithFormat:@"Sparkle Updater: Possible attack in progress! Attempting to \"upgrade\" from %@ to %@. Aborting update.", [host version], [[NSBundle bundleWithPath:path] objectForInfoDictionaryKey:@"CFBundleVersion"]];
NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUDowngradeError userInfo:[NSDictionary dictionaryWithObject:errorMessage forKey:NSLocalizedDescriptionKey]];
[self finishInstallationToPath:installationPath withResult:NO host:host error:error delegate:delegate];
return;
}
#endif
NSString *targetPath = [host installationPath];
NSString *tempName = [self temporaryNameForPath:targetPath];
NSDictionary *info = [NSDictionary dictionaryWithObjectsAndKeys:path, SUInstallerPathKey, targetPath, SUInstallerTargetPathKey, tempName, SUInstallerTempNameKey, host, SUInstallerHostKey, delegate, SUInstallerDelegateKey, installationPath, SUInstallerInstallationPathKey, nil];
if (synchronously)
[self _performInstallationWithInfo:info];
[self performInstallationWithInfo:info];
else
[NSThread detachNewThreadSelector:@selector(_performInstallationWithInfo:) toTarget:self withObject:info];
[NSThread detachNewThreadSelector:@selector(performInstallationWithInfo:) toTarget:self withObject:info];
}
@end
+22
View File
@@ -0,0 +1,22 @@
//
// SUPlainInstallerInternals.m
// Sparkle
//
// Created by Andy Matuschak on 3/9/06.
// Copyright 2006 Andy Matuschak. All rights reserved.
//
#ifndef SUPLAININSTALLERINTERNALS_H
#define SUPLAININSTALLERINTERNALS_H
#import "SUPlainInstaller.h"
@interface SUPlainInstaller (Internals)
+ (NSString *)temporaryNameForPath:(NSString *)path;
+ (BOOL)copyPathWithAuthentication:(NSString *)src overPath:(NSString *)dst temporaryName:(NSString *)tmp error:(NSError **)error;
+ (void)_movePathToTrash:(NSString *)path;
+ (BOOL)_removeFileAtPath:(NSString *)path error: (NSError**)error;
+ (BOOL)_removeFileAtPathWithForcedAuthentication:(NSString *)src error:(NSError **)error;
@end
#endif
+608
View File
@@ -0,0 +1,608 @@
//
// SUPlainInstallerInternals.m
// Sparkle
//
// Created by Andy Matuschak on 3/9/06.
// Copyright 2006 Andy Matuschak. All rights reserved.
//
#import "SUUpdater.h"
#import "SUAppcast.h"
#import "SUAppcastItem.h"
#import "SUVersionComparisonProtocol.h"
#import "SUPlainInstallerInternals.h"
#import "SUConstants.h"
#import "SULog.h"
#import <CoreServices/CoreServices.h>
#import <Security/Security.h>
#import <sys/stat.h>
#import <sys/wait.h>
#import <dirent.h>
#import <unistd.h>
#import <sys/param.h>
@interface SUPlainInstaller (MMExtendedAttributes)
// 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
// Authorization code based on generous contribution from Allan Odgaard. Thanks, Allan!
static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authorization, const char* executablePath, AuthorizationFlags options, const char* const* arguments)
{
// *** MUST BE SAFE TO CALL ON NON-MAIN THREAD!
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 SUPlainInstaller (Internals)
+ (NSString *)temporaryNameForPath:(NSString *)path
{
// Let's try to read the version number so the filename will be more meaningful.
NSString *postFix;
NSString *version;
if ((version = [[NSBundle bundleWithPath:path] objectForInfoDictionaryKey:@"CFBundleVersion"]) && ![version isEqualToString:@""])
{
// 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 = [version 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.
unsigned int cnt=2;
while ([[NSFileManager defaultManager] fileExistsAtPath:tempDir] && cnt <= 999)
tempDir = [NSString stringWithFormat:@"%@ %u.%@", prefix, cnt++, [path pathExtension]];
return [tempDir lastPathComponent];
}
+ (NSString *)_temporaryCopyNameForPath:(NSString *)path didFindTrash: (BOOL*)outDidFindTrash
{
// *** MUST BE SAFE TO CALL ON NON-MAIN THREAD!
NSString *tempDir = nil;
UInt8 trashPath[MAXPATHLEN +1] = { 0 };
FSRef trashRef, pathRef;
FSVolumeRefNum vSrcRefNum = kFSInvalidVolumeRefNum;
FSCatalogInfo catInfo;
memset( &catInfo, 0, sizeof(catInfo) );
OSStatus err = FSPathMakeRef( (UInt8*) [path fileSystemRepresentation], &pathRef, NULL );
if( err == noErr )
{
err = FSGetCatalogInfo( &pathRef, kFSCatInfoVolume, &catInfo, NULL, NULL, NULL );
vSrcRefNum = catInfo.volume;
}
if( err == noErr )
err = FSFindFolder( vSrcRefNum, kTrashFolderType, kCreateFolder, &trashRef );
if( err == noErr )
err = FSGetCatalogInfo( &trashRef, kFSCatInfoVolume, &catInfo, NULL, NULL, NULL );
if( err == noErr && vSrcRefNum != catInfo.volume )
err = nsvErr; // Couldn't find a trash folder on same volume as given path. Docs say this may happen in the future.
if( err == noErr )
err = FSRefMakePath( &trashRef, trashPath, MAXPATHLEN );
if( err == noErr )
tempDir = [[NSFileManager defaultManager] stringWithFileSystemRepresentation: (char*) trashPath length: strlen((char*) trashPath)];
if( outDidFindTrash )
*outDidFindTrash = (tempDir != nil);
if( !tempDir )
tempDir = [path stringByDeletingLastPathComponent];
// Let's try to read the version number so the filename will be more meaningful.
#if TRY_TO_APPEND_VERSION_NUMBER
NSString *postFix = nil;
NSString *version = nil;
if ((version = [[NSBundle bundleWithPath: path] objectForInfoDictionaryKey:@"CFBundleVersion"]) && ![version isEqualToString:@""])
{
// 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 = [version stringByTrimmingCharactersInSet:[validCharacters invertedSet]];
}
else
postFix = @"old";
NSString *prefix = [NSString stringWithFormat: @"%@ (%@)", [[path lastPathComponent] stringByDeletingPathExtension], postFix];
#else
NSString *prefix = [[path lastPathComponent] stringByDeletingPathExtension];
#endif
NSString *tempName = [prefix stringByAppendingPathExtension: [path pathExtension]];
tempDir = [tempDir stringByAppendingPathComponent: tempName];
// Now let's make sure we get a unique path.
int cnt=2;
while ([[NSFileManager defaultManager] fileExistsAtPath:tempDir] && cnt <= 9999)
tempDir = [[tempDir stringByDeletingLastPathComponent] stringByAppendingPathComponent: [NSString stringWithFormat:@"%@ %d.%@", prefix, cnt++, [path pathExtension]]];
return tempDir;
}
+ (BOOL)_copyPathWithForcedAuthentication:(NSString *)src toPath:(NSString *)dst temporaryPath:(NSString *)tmp error:(NSError **)error
{
// *** MUST BE SAFE TO CALL ON NON-MAIN THREAD!
const char* srcPath = [src fileSystemRepresentation];
const char* tmpPath = [tmp fileSystemRepresentation];
const char* dstPath = [dst fileSystemRepresentation];
struct stat dstSB;
if( stat(dstPath, &dstSB) != 0 ) // Doesn't exist yet, try containing folder.
{
const char* dstDirPath = [[dst stringByDeletingLastPathComponent] fileSystemRepresentation];
if( stat(dstDirPath, &dstSB) != 0 )
{
NSString *errorMessage = [NSString stringWithFormat:@"Stat on %@ during authenticated file copy failed.", dst];
if (error != NULL)
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUFileCopyFailure userInfo:[NSDictionary dictionaryWithObject:errorMessage forKey:NSLocalizedDescriptionKey]];
return NO;
}
}
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), "%u:%u",
dstSB.st_uid, dstSB.st_gid);
// 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)
{
SULog(@"releaseFromQuarantine");
[self performSelectorOnMainThread:@selector(releaseFromQuarantine:) withObject:dst waitUntilDone:YES];
}
if( res ) // Set permissions while it's still in source, so we have it with working and correct perms when it arrives at destination.
{
const char* coParams[] = { "-R", uidgid, srcPath, NULL };
res = AuthorizationExecuteWithPrivilegesAndWait( auth, "/usr/sbin/chown", kAuthorizationFlagDefaults, coParams );
if( !res )
SULog( @"chown -R %s %s failed.", uidgid, srcPath );
}
BOOL haveDst = [[NSFileManager defaultManager] fileExistsAtPath: dst];
if( res && haveDst ) // If there's something at our tmp path (previous failed update or whatever) delete that first.
{
const char* rmParams[] = { "-rf", tmpPath, NULL };
res = AuthorizationExecuteWithPrivilegesAndWait( auth, "/bin/rm", kAuthorizationFlagDefaults, rmParams );
if( !res )
SULog( @"rm failed" );
}
if( res && haveDst ) // Move old exe to tmp path.
{
const char* mvParams[] = { "-f", dstPath, tmpPath, NULL };
res = AuthorizationExecuteWithPrivilegesAndWait( auth, "/bin/mv", kAuthorizationFlagDefaults, mvParams );
if( !res )
SULog( @"mv 1 failed" );
}
if( res ) // Move new exe to old exe's path.
{
const char* mvParams2[] = { "-f", srcPath, dstPath, NULL };
res = AuthorizationExecuteWithPrivilegesAndWait( auth, "/bin/mv", kAuthorizationFlagDefaults, mvParams2 );
if( !res )
SULog( @"mv 2 failed" );
}
// if( res && haveDst /*&& !foundTrash*/ ) // If we managed to put the old exe in the trash, leave it there for the user to delete or recover.
// { // ... Otherwise we better delete it, wouldn't want dozens of old versions lying around next to the new one.
// const char* rmParams2[] = { "-rf", tmpPath, NULL };
// res = AuthorizationExecuteWithPrivilegesAndWait( auth, "/bin/rm", kAuthorizationFlagDefaults, rmParams2 );
// }
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 != nil)
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:[NSDictionary dictionaryWithObject:errorMessage forKey:NSLocalizedDescriptionKey]];
}
}
else
{
if (error != nil)
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:[NSDictionary dictionaryWithObject:@"Couldn't get permission to authenticate." forKey:NSLocalizedDescriptionKey]];
}
return res;
}
+ (BOOL)_movePathWithForcedAuthentication:(NSString *)src toPath:(NSString *)dst error:(NSError **)error
{
// *** MUST BE SAFE TO CALL ON NON-MAIN THREAD!
const char* srcPath = [src fileSystemRepresentation];
const char* dstPath = [dst fileSystemRepresentation];
const char* dstContainerPath = [[dst stringByDeletingLastPathComponent] fileSystemRepresentation];
struct stat dstSB;
stat(dstContainerPath, &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);
if( res ) // Set permissions while it's still in source, so we have it with working and correct perms when it arrives at destination.
{
const char* coParams[] = { "-R", uidgid, srcPath, NULL };
res = AuthorizationExecuteWithPrivilegesAndWait( auth, "/usr/sbin/chown", kAuthorizationFlagDefaults, coParams );
if( !res )
SULog(@"Can't set permissions");
}
BOOL haveDst = [[NSFileManager defaultManager] fileExistsAtPath: dst];
if( res && haveDst ) // If there's something at our tmp path (previous failed update or whatever) delete that first.
{
const char* rmParams[] = { "-rf", dstPath, NULL };
res = AuthorizationExecuteWithPrivilegesAndWait( auth, "/bin/rm", kAuthorizationFlagDefaults, rmParams );
if( !res )
SULog(@"Can't remove destination file");
}
if( res ) // Move!.
{
const char* mvParams[] = { "-f", srcPath, dstPath, NULL };
res = AuthorizationExecuteWithPrivilegesAndWait( auth, "/bin/mv", kAuthorizationFlagDefaults, mvParams );
if( !res )
SULog(@"Can't move source file");
}
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 move 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)_removeFileAtPathWithForcedAuthentication:(NSString *)src error:(NSError **)error
{
// *** MUST BE SAFE TO CALL ON NON-MAIN THREAD!
const char* srcPath = [src fileSystemRepresentation];
AuthorizationRef auth = NULL;
OSStatus authStat = errAuthorizationDenied;
while( authStat == errAuthorizationDenied )
{
authStat = AuthorizationCreate(NULL,
kAuthorizationEmptyEnvironment,
kAuthorizationFlagDefaults,
&auth);
}
BOOL res = NO;
if (authStat == errAuthorizationSuccess)
{
res = YES;
if( res ) // If there's something at our tmp path (previous failed update or whatever) delete that first.
{
const char* rmParams[] = { "-rf", srcPath, NULL };
res = AuthorizationExecuteWithPrivilegesAndWait( auth, "/bin/rm", kAuthorizationFlagDefaults, rmParams );
if( !res )
SULog(@"Can't remove destination file");
}
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 remove from %@ failed.", src];
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)_removeFileAtPath:(NSString *)path error: (NSError**)error
{
BOOL success = YES;
#if MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_4
if( ![[NSFileManager defaultManager] removeFileAtPath: path handler: nil] )
#else
if( ![[NSFileManager defaultManager] removeItemAtPath: path error: NULL] )
#endif
{
success = [self _removeFileAtPathWithForcedAuthentication: path error: error];
}
return success;
}
+ (void)_movePathToTrash:(NSString *)path
{
//SULog(@"Moving %@ to the trash.", path);
NSInteger tag = 0;
if (![[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:[path stringByDeletingLastPathComponent] destination:@"" files:[NSArray arrayWithObject:[path lastPathComponent]] tag:&tag])
{
BOOL didFindTrash = NO;
NSString* trashPath = [self _temporaryCopyNameForPath: path didFindTrash: &didFindTrash];
if( didFindTrash )
{
NSError *err = nil;
if( ![self _movePathWithForcedAuthentication: path toPath: trashPath error: &err] )
SULog(@"Sparkle error: couldn't move %@ to the trash (%@). %@", path, trashPath, err);
}
else
SULog(@"Sparkle error: couldn't move %@ to the trash. This is often a sign of a permissions error.", path);
}
else
;//SULog(@"Moved %@ to the trash.", path);
}
+ (BOOL)copyPathWithAuthentication:(NSString *)src overPath:(NSString *)dst temporaryName:(NSString *)tmp error:(NSError **)error
{
FSRef srcRef, dstRef, dstDirRef, movedRef, tmpDirRef;
OSStatus err;
BOOL hadFileAtDest = NO, didFindTrash = NO;
NSString *tmpPath = [self _temporaryCopyNameForPath: dst didFindTrash: &didFindTrash];
// Make FSRef for destination:
err = FSPathMakeRefWithOptions((UInt8 *)[dst fileSystemRepresentation], kFSPathMakeRefDoNotFollowLeafSymlink, &dstRef, NULL);
hadFileAtDest = (err == noErr); // There is a file at the destination, move it aside. If we normalized the name, we might not get here, so don't error.
if( hadFileAtDest )
{
if (0 != access([dst fileSystemRepresentation], W_OK) || 0 != access([[dst stringByDeletingLastPathComponent] fileSystemRepresentation], W_OK))
{
return [self _copyPathWithForcedAuthentication:src toPath:dst temporaryPath:tmpPath error:error];
}
}
else
{
if (0 != access([[dst stringByDeletingLastPathComponent] fileSystemRepresentation], W_OK)
|| 0 != access([[[dst stringByDeletingLastPathComponent] stringByDeletingLastPathComponent] fileSystemRepresentation], W_OK))
{
return [self _copyPathWithForcedAuthentication:src toPath:dst temporaryPath:tmpPath error:error];
}
}
if( hadFileAtDest )
{
err = FSPathMakeRef((UInt8 *)[[tmpPath stringByDeletingLastPathComponent] fileSystemRepresentation], &tmpDirRef, NULL);
if (err != noErr)
err = FSPathMakeRef((UInt8 *)[[dst stringByDeletingLastPathComponent] fileSystemRepresentation], &tmpDirRef, NULL);
}
err = FSPathMakeRef((UInt8 *)[[dst stringByDeletingLastPathComponent] fileSystemRepresentation], &dstDirRef, NULL);
if (err == noErr && hadFileAtDest)
{
if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_5)
{
NSFileManager *manager = [[[NSFileManager alloc] init] autorelease];
BOOL success = [manager moveItemAtPath:dst toPath:tmpPath error:error];
if (!success && hadFileAtDest)
{
if (error != NULL)
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUFileCopyFailure userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"Couldn't move %@ to %@.", dst, tmpPath] forKey:NSLocalizedDescriptionKey]];
return NO;
}
} else {
err = FSMoveObjectSync(&dstRef, &tmpDirRef, (CFStringRef)[tmpPath lastPathComponent], &movedRef, 0);
if (err != noErr && hadFileAtDest)
{
if (error != NULL)
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUFileCopyFailure userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"Couldn't move %@ to %@.", dst, tmpPath] forKey:NSLocalizedDescriptionKey]];
return NO;
}
}
}
err = FSPathMakeRef((UInt8 *)[src fileSystemRepresentation], &srcRef, NULL);
if (err == noErr)
{
if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_5)
{
NSFileManager *manager = [[[NSFileManager alloc] init] autorelease];
BOOL success = [manager copyItemAtPath:src toPath:dst error:error];
if (!success)
{
// We better move the old version back to its old location
if( hadFileAtDest )
success = [manager moveItemAtPath:tmpPath toPath:dst error:error];
if (error != NULL)
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUFileCopyFailure userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"Couldn't move %@ to %@.", dst, tmpPath] forKey:NSLocalizedDescriptionKey]];
return NO;
}
} else {
err = FSCopyObjectSync(&srcRef, &dstDirRef, (CFStringRef)[dst lastPathComponent], NULL, 0);
if (err != noErr)
{
// We better move the old version back to its old location
if( hadFileAtDest )
FSMoveObjectSync(&movedRef, &dstDirRef, (CFStringRef)[dst lastPathComponent], &movedRef, 0);
if (error != NULL)
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUFileCopyFailure userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"Couldn't copy %@ to %@.", src, dst] forKey:NSLocalizedDescriptionKey]];
return NO;
}
}
}
// 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 performSelectorOnMainThread:@selector(releaseFromQuarantine:) withObject:dst waitUntilDone:YES];
return YES;
}
@end
#import <dlfcn.h>
#import <errno.h>
#import <sys/xattr.h>
@implementation SUPlainInstaller (MMExtendedAttributes)
+ (int)removeXAttr:(const char*)name
fromFile:(NSString*)file
options:(int)options
{
// *** MUST BE SAFE TO CALL ON NON-MAIN THREAD!
typedef int (*removexattr_type)(const char*, const char*, int);
// Reference removexattr directly, it's in the SDK.
static removexattr_type removexattr_func = removexattr;
// 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;
}
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
{
// *** MUST BE SAFE TO CALL ON NON-MAIN THREAD!
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.
#if MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_4
NSDictionary* rootAttributes = [[NSFileManager defaultManager] fileAttributesAtPath:root traverseLink:NO];
#else
NSDictionary* rootAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:root error:nil];
#endif
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 = [[NSFileManager defaultManager] enumeratorAtPath:root];
NSString* file = nil;
while ((file = [directoryEnumerator nextObject])) {
[self removeXAttr:quarantineAttribute
fromFile:[root stringByAppendingPathComponent:file]
options:removeXAttrOptions];
}
}
}
@end
+6 -2
View File
@@ -7,19 +7,23 @@
//
#import "SUProbingUpdateDriver.h"
#import "SUUpdater.h"
@implementation SUProbingUpdateDriver
// Stop as soon as we have an answer! The superclasses will already have taken care of notifying the delegate.
// Stop as soon as we have an answer! Since the superclass implementations are not called, we are responsible for notifying the delegate.
- (void)didFindValidUpdate
{
if ([[updater delegate] respondsToSelector:@selector(updater:didFindValidUpdate:)])
[[updater delegate] updater:updater didFindValidUpdate:updateItem];
[self abortUpdate];
}
- (void)didNotFindUpdate
{
if ([[updater delegate] respondsToSelector:@selector(updaterDidNotFindUpdate:)])
[[updater delegate] updaterDidNotFindUpdate:updater];
[self abortUpdate];
}
+3 -1
View File
@@ -12,7 +12,9 @@
#import <Cocoa/Cocoa.h>
#import "SUUIBasedUpdateDriver.h"
@interface SUScheduledUpdateDriver : SUUIBasedUpdateDriver {
@interface SUScheduledUpdateDriver : SUUIBasedUpdateDriver
{
@private
BOOL showErrors;
}
+7 -1
View File
@@ -7,7 +7,11 @@
//
#import "SUScheduledUpdateDriver.h"
#import "Sparkle.h"
#import "SUUpdater.h"
#import "SUAppcast.h"
#import "SUAppcastItem.h"
#import "SUVersionComparisonProtocol.h"
@implementation SUScheduledUpdateDriver
@@ -19,6 +23,8 @@
- (void)didNotFindUpdate
{
if ([[updater delegate] respondsToSelector:@selector(updaterDidNotFindUpdate:)])
[[updater delegate] updaterDidNotFindUpdate:updater];
[self abortUpdate]; // Don't tell the user that no update was found; this was a scheduled update.
}
+23 -13
View File
@@ -6,7 +6,11 @@
// Copyright 2007 Andy Matuschak. All rights reserved.
//
#import "Sparkle.h"
#import "SUUpdater.h"
#import "SUAppcast.h"
#import "SUAppcastItem.h"
#import "SUVersionComparisonProtocol.h"
#import "SUStandardVersionComparator.h"
@implementation SUStandardVersionComparator
@@ -22,15 +26,19 @@
typedef enum {
kNumberType,
kStringType,
kPeriodType
kSeparatorType,
} SUCharacterType;
- (SUCharacterType)typeOfCharacter:(NSString *)character
{
if ([character isEqualToString:@"."]) {
return kPeriodType;
return kSeparatorType;
} else if ([[NSCharacterSet decimalDigitCharacterSet] characterIsMember:[character characterAtIndex:0]]) {
return kNumberType;
} else if ([[NSCharacterSet whitespaceAndNewlineCharacterSet] characterIsMember:[character characterAtIndex:0]]) {
return kSeparatorType;
} else if ([[NSCharacterSet punctuationCharacterSet] characterIsMember:[character characterAtIndex:0]]) {
return kSeparatorType;
} else {
return kStringType;
}
@@ -40,7 +48,8 @@ typedef enum {
{
NSString *character;
NSMutableString *s;
NSInteger i, n, oldType, newType;
NSUInteger i, n;
SUCharacterType oldType, newType;
NSMutableArray *parts = [NSMutableArray array];
if ([version length] == 0) {
// Nothing to do here
@@ -52,11 +61,10 @@ typedef enum {
for (i = 1; i <= n; ++i) {
character = [version substringWithRange:NSMakeRange(i, 1)];
newType = [self typeOfCharacter:character];
if (oldType != newType || oldType == kPeriodType) {
if (oldType != newType || oldType == kSeparatorType) {
// We've reached a new segment
NSString *aPart = [[NSString alloc] initWithString:s];
NSString *aPart = [[[NSString alloc] initWithString:s] autorelease];
[parts addObject:aPart];
[aPart release];
[s setString:character];
} else {
// Add character to string and continue
@@ -76,8 +84,10 @@ typedef enum {
NSArray *partsB = [self splitVersionString:versionB];
NSString *partA, *partB;
NSInteger i, n, typeA, typeB, intA, intB;
NSUInteger i, n;
long long valueA, valueB;
SUCharacterType typeA, typeB;
n = MIN([partsA count], [partsB count]);
for (i = 0; i < n; ++i) {
partA = [partsA objectAtIndex:i];
@@ -90,11 +100,11 @@ typedef enum {
if (typeA == typeB) {
// Same type; we can compare
if (typeA == kNumberType) {
intA = [partA intValue];
intB = [partB intValue];
if (intA > intB) {
valueA = [partA longLongValue];
valueB = [partB longLongValue];
if (valueA > valueB) {
return NSOrderedDescending;
} else if (intA < intB) {
} else if (valueA < valueB) {
return NSOrderedAscending;
}
} else if (typeA == kStringType) {
-56
View File
@@ -1,56 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IBClasses</key>
<array>
<dict>
<key>CLASS</key>
<string>SUWindowController</string>
<key>LANGUAGE</key>
<string>ObjC</string>
<key>SUPERCLASS</key>
<string>NSWindowController</string>
</dict>
<dict>
<key>CLASS</key>
<string>NSApplication</string>
<key>LANGUAGE</key>
<string>ObjC</string>
<key>SUPERCLASS</key>
<string>NSResponder</string>
</dict>
<dict>
<key>CLASS</key>
<string>FirstResponder</string>
<key>LANGUAGE</key>
<string>ObjC</string>
<key>SUPERCLASS</key>
<string>NSObject</string>
</dict>
<dict>
<key>CLASS</key>
<string>NSObject</string>
<key>LANGUAGE</key>
<string>ObjC</string>
</dict>
<dict>
<key>CLASS</key>
<string>SUStatusController</string>
<key>LANGUAGE</key>
<string>ObjC</string>
<key>OUTLETS</key>
<dict>
<key>actionButton</key>
<string>NSButton</string>
<key>progressBar</key>
<string>NSProgressIndicator</string>
</dict>
<key>SUPERCLASS</key>
<string>SUWindowController</string>
</dict>
</array>
<key>IBVersion</key>
<string>1</string>
</dict>
</plist>
-20
View File
@@ -1,20 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IBFramework Version</key>
<string>667</string>
<key>IBLastKnownRelativeProjectPath</key>
<string>Sparkle.xcodeproj</string>
<key>IBOldestOS</key>
<integer>5</integer>
<key>IBOpenObjects</key>
<array>
<integer>6</integer>
</array>
<key>IBSystem Version</key>
<string>9D34</string>
<key>targetFramework</key>
<string>IBCocoaFramework</string>
</dict>
</plist>
BIN
View File
Binary file not shown.
+589
View File
@@ -0,0 +1,589 @@
<?xml version="1.0" encoding="UTF-8"?>
<archive type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="7.10">
<data>
<int key="IBDocument.SystemTarget">1050</int>
<string key="IBDocument.SystemVersion">10D573</string>
<string key="IBDocument.InterfaceBuilderVersion">762</string>
<string key="IBDocument.AppKitVersion">1038.29</string>
<string key="IBDocument.HIToolboxVersion">460.00</string>
<object class="NSMutableDictionary" key="IBDocument.PluginVersions">
<bool key="EncodedWithXMLCoder">YES</bool>
<object class="NSArray" key="dict.sortedKeys" id="0">
<bool key="EncodedWithXMLCoder">YES</bool>
</object>
<object class="NSMutableArray" key="dict.values">
<bool key="EncodedWithXMLCoder">YES</bool>
</object>
</object>
<object class="NSMutableArray" key="IBDocument.EditedObjectIDs">
<bool key="EncodedWithXMLCoder">YES</bool>
<integer value="6"/>
</object>
<reference key="IBDocument.PluginDependencies" ref="0"/>
<object class="NSMutableDictionary" key="IBDocument.Metadata">
<bool key="EncodedWithXMLCoder">YES</bool>
<reference key="dict.sortedKeys" ref="0"/>
<object class="NSMutableArray" key="dict.values">
<bool key="EncodedWithXMLCoder">YES</bool>
</object>
</object>
<object class="NSMutableArray" key="IBDocument.RootObjects" id="780577916">
<bool key="EncodedWithXMLCoder">YES</bool>
<object class="NSCustomObject" id="245526436">
<string key="NSClassName">SUStatusController</string>
</object>
<object class="NSCustomObject" id="879485556">
<string key="NSClassName">FirstResponder</string>
</object>
<object class="NSCustomObject" id="472338989">
<string key="NSClassName">NSApplication</string>
</object>
<object class="NSWindowTemplate" id="661323156">
<int key="NSWindowStyleMask">1</int>
<int key="NSWindowBacking">2</int>
<string key="NSWindowRect">{{200, 222}, {400, 107}}</string>
<int key="NSWTFlags">1886912512</int>
<string key="NSWindowTitle">Set in Code</string>
<object class="NSMutableString" key="NSWindowClass">
<characters key="NS.bytes">NSWindow</characters>
</object>
<object class="NSMutableString" key="NSViewClass">
<characters key="NS.bytes">View</characters>
</object>
<string key="NSWindowContentMaxSize">{3.40282e+38, 3.40282e+38}</string>
<string key="NSWindowContentMinSize">{213, 107}</string>
<object class="NSView" key="NSWindowView" id="512815736">
<reference key="NSNextResponder"/>
<int key="NSvFlags">256</int>
<object class="NSMutableArray" key="NSSubviews">
<bool key="EncodedWithXMLCoder">YES</bool>
<object class="NSImageView" id="56655866">
<reference key="NSNextResponder" ref="512815736"/>
<int key="NSvFlags">268</int>
<object class="NSMutableSet" key="NSDragTypes">
<bool key="EncodedWithXMLCoder">YES</bool>
<object class="NSArray" key="set.sortedObjects">
<bool key="EncodedWithXMLCoder">YES</bool>
<string>Apple PDF pasteboard type</string>
<string>Apple PICT pasteboard type</string>
<string>Apple PNG pasteboard type</string>
<string>NSFilenamesPboardType</string>
<string>NeXT Encapsulated PostScript v1.2 pasteboard type</string>
<string>NeXT TIFF v4.0 pasteboard type</string>
</object>
</object>
<string key="NSFrame">{{24, 28}, {64, 64}}</string>
<reference key="NSSuperview" ref="512815736"/>
<bool key="NSEnabled">YES</bool>
<object class="NSImageCell" key="NSCell" id="381943368">
<int key="NSCellFlags">130560</int>
<int key="NSCellFlags2">33554432</int>
<object class="NSCustomResource" key="NSContents">
<string key="NSClassName">NSImage</string>
<string key="NSResourceName">NSApplicationIcon</string>
</object>
<int key="NSAlign">0</int>
<int key="NSScale">1</int>
<int key="NSStyle">0</int>
<bool key="NSAnimates">NO</bool>
</object>
<bool key="NSEditable">YES</bool>
</object>
<object class="NSTextField" id="692218720">
<reference key="NSNextResponder" ref="512815736"/>
<int key="NSvFlags">268</int>
<string key="NSFrame">{{106, 75}, {277, 17}}</string>
<reference key="NSSuperview" ref="512815736"/>
<bool key="NSEnabled">YES</bool>
<object class="NSTextFieldCell" key="NSCell" id="597081861">
<int key="NSCellFlags">67239424</int>
<int key="NSCellFlags2">272629760</int>
<string key="NSContents">Status Text (set by loc. string in code)</string>
<object class="NSFont" key="NSSupport">
<string key="NSName">LucidaGrande-Bold</string>
<double key="NSSize">13</double>
<int key="NSfFlags">2072</int>
</object>
<reference key="NSControlView" ref="692218720"/>
<object class="NSColor" key="NSBackgroundColor" id="747797151">
<int key="NSColorSpace">6</int>
<string key="NSCatalogName">System</string>
<string key="NSColorName">controlColor</string>
<object class="NSColor" key="NSColor">
<int key="NSColorSpace">3</int>
<bytes key="NSWhite">MC42NjY2NjY2ODY1AA</bytes>
</object>
</object>
<object class="NSColor" key="NSTextColor" id="640273742">
<int key="NSColorSpace">6</int>
<string key="NSCatalogName">System</string>
<string key="NSColorName">controlTextColor</string>
<object class="NSColor" key="NSColor">
<int key="NSColorSpace">3</int>
<bytes key="NSWhite">MAA</bytes>
</object>
</object>
</object>
</object>
<object class="NSProgressIndicator" id="454270533">
<reference key="NSNextResponder" ref="512815736"/>
<int key="NSvFlags">1280</int>
<object class="NSPSMatrix" key="NSDrawMatrix"/>
<string key="NSFrame">{{107, 47}, {275, 20}}</string>
<reference key="NSSuperview" ref="512815736"/>
<int key="NSpiFlags">16394</int>
<double key="NSMaxValue">100</double>
</object>
<object class="NSButton" id="566879706">
<reference key="NSNextResponder" ref="512815736"/>
<int key="NSvFlags">259</int>
<string key="NSFrame">{{272, 12}, {114, 32}}</string>
<reference key="NSSuperview" ref="512815736"/>
<bool key="NSEnabled">YES</bool>
<object class="NSButtonCell" key="NSCell" id="130218013">
<int key="NSCellFlags">67239424</int>
<int key="NSCellFlags2">134217728</int>
<string key="NSContents">Button</string>
<object class="NSFont" key="NSSupport" id="531315841">
<string key="NSName">LucidaGrande</string>
<double key="NSSize">13</double>
<int key="NSfFlags">1044</int>
</object>
<reference key="NSControlView" ref="566879706"/>
<int key="NSButtonFlags">-2038284033</int>
<int key="NSButtonFlags2">1</int>
<reference key="NSAlternateImage" ref="531315841"/>
<string key="NSAlternateContents"/>
<object class="NSMutableString" key="NSKeyEquivalent">
<characters key="NS.bytes"/>
</object>
<int key="NSPeriodicDelay">200</int>
<int key="NSPeriodicInterval">25</int>
</object>
</object>
<object class="NSTextField" id="65200871">
<reference key="NSNextResponder" ref="512815736"/>
<int key="NSvFlags">256</int>
<string key="NSFrame">{{106, 22}, {167, 17}}</string>
<reference key="NSSuperview" ref="512815736"/>
<bool key="NSEnabled">YES</bool>
<object class="NSTextFieldCell" key="NSCell" id="180962568">
<int key="NSCellFlags">67239424</int>
<int key="NSCellFlags2">272629760</int>
<string key="NSContents">Small System Font Text</string>
<reference key="NSSupport" ref="531315841"/>
<reference key="NSControlView" ref="65200871"/>
<reference key="NSBackgroundColor" ref="747797151"/>
<reference key="NSTextColor" ref="640273742"/>
</object>
</object>
</object>
<string key="NSFrameSize">{400, 107}</string>
<reference key="NSSuperview"/>
</object>
<string key="NSScreenRect">{{0, 0}, {1920, 1178}}</string>
<string key="NSMinSize">{213, 129}</string>
<string key="NSMaxSize">{3.40282e+38, 3.40282e+38}</string>
</object>
</object>
<object class="IBObjectContainer" key="IBDocument.Objects">
<object class="NSMutableArray" key="connectionRecords">
<bool key="EncodedWithXMLCoder">YES</bool>
<object class="IBConnectionRecord">
<object class="IBBindingConnection" key="connection">
<string key="label">value: applicationIcon</string>
<reference key="source" ref="56655866"/>
<reference key="destination" ref="245526436"/>
<object class="NSNibBindingConnector" key="connector">
<reference key="NSSource" ref="56655866"/>
<reference key="NSDestination" ref="245526436"/>
<string key="NSLabel">value: applicationIcon</string>
<string key="NSBinding">value</string>
<string key="NSKeyPath">applicationIcon</string>
<int key="NSNibBindingConnectorVersion">2</int>
</object>
</object>
<int key="connectionID">9</int>
</object>
<object class="IBConnectionRecord">
<object class="IBBindingConnection" key="connection">
<string key="label">maxValue: maxProgressValue</string>
<reference key="source" ref="454270533"/>
<reference key="destination" ref="245526436"/>
<object class="NSNibBindingConnector" key="connector" id="110266706">
<reference key="NSSource" ref="454270533"/>
<reference key="NSDestination" ref="245526436"/>
<string key="NSLabel">maxValue: maxProgressValue</string>
<string key="NSBinding">maxValue</string>
<string key="NSKeyPath">maxProgressValue</string>
<int key="NSNibBindingConnectorVersion">2</int>
</object>
</object>
<int key="connectionID">13</int>
</object>
<object class="IBConnectionRecord">
<object class="IBBindingConnection" key="connection">
<string key="label">value: statusText</string>
<reference key="source" ref="65200871"/>
<reference key="destination" ref="245526436"/>
<object class="NSNibBindingConnector" key="connector">
<reference key="NSSource" ref="65200871"/>
<reference key="NSDestination" ref="245526436"/>
<string key="NSLabel">value: statusText</string>
<string key="NSBinding">value</string>
<string key="NSKeyPath">statusText</string>
<int key="NSNibBindingConnectorVersion">2</int>
</object>
</object>
<int key="connectionID">17</int>
</object>
<object class="IBConnectionRecord">
<object class="IBBindingConnection" key="connection">
<string key="label">title: buttonTitle</string>
<reference key="source" ref="566879706"/>
<reference key="destination" ref="245526436"/>
<object class="NSNibBindingConnector" key="connector">
<reference key="NSSource" ref="566879706"/>
<reference key="NSDestination" ref="245526436"/>
<string key="NSLabel">title: buttonTitle</string>
<string key="NSBinding">title</string>
<string key="NSKeyPath">buttonTitle</string>
<int key="NSNibBindingConnectorVersion">2</int>
</object>
</object>
<int key="connectionID">21</int>
</object>
<object class="IBConnectionRecord">
<object class="IBBindingConnection" key="connection">
<string key="label">title: windowTitle</string>
<reference key="source" ref="661323156"/>
<reference key="destination" ref="245526436"/>
<object class="NSNibBindingConnector" key="connector">
<reference key="NSSource" ref="661323156"/>
<reference key="NSDestination" ref="245526436"/>
<string key="NSLabel">title: windowTitle</string>
<string key="NSBinding">title</string>
<string key="NSKeyPath">windowTitle</string>
<int key="NSNibBindingConnectorVersion">2</int>
</object>
</object>
<int key="connectionID">24</int>
</object>
<object class="IBConnectionRecord">
<object class="IBOutletConnection" key="connection">
<string key="label">window</string>
<reference key="source" ref="245526436"/>
<reference key="destination" ref="661323156"/>
</object>
<int key="connectionID">25</int>
</object>
<object class="IBConnectionRecord">
<object class="IBBindingConnection" key="connection">
<string key="label">value: title</string>
<reference key="source" ref="692218720"/>
<reference key="destination" ref="245526436"/>
<object class="NSNibBindingConnector" key="connector">
<reference key="NSSource" ref="692218720"/>
<reference key="NSDestination" ref="245526436"/>
<string key="NSLabel">value: title</string>
<string key="NSBinding">value</string>
<string key="NSKeyPath">title</string>
<int key="NSNibBindingConnectorVersion">2</int>
</object>
</object>
<int key="connectionID">26</int>
</object>
<object class="IBConnectionRecord">
<object class="IBBindingConnection" key="connection">
<string key="label">value: progressValue</string>
<reference key="source" ref="454270533"/>
<reference key="destination" ref="245526436"/>
<object class="NSNibBindingConnector" key="connector">
<reference key="NSSource" ref="454270533"/>
<reference key="NSDestination" ref="245526436"/>
<string key="NSLabel">value: progressValue</string>
<string key="NSBinding">value</string>
<string key="NSKeyPath">progressValue</string>
<reference key="NSPreviousConnector" ref="110266706"/>
<int key="NSNibBindingConnectorVersion">2</int>
</object>
</object>
<int key="connectionID">27</int>
</object>
<object class="IBConnectionRecord">
<object class="IBBindingConnection" key="connection">
<string key="label">hidden: statusText</string>
<reference key="source" ref="65200871"/>
<reference key="destination" ref="245526436"/>
<object class="NSNibBindingConnector" key="connector">
<reference key="NSSource" ref="65200871"/>
<reference key="NSDestination" ref="245526436"/>
<string key="NSLabel">hidden: statusText</string>
<string key="NSBinding">hidden</string>
<string key="NSKeyPath">statusText</string>
<object class="NSDictionary" key="NSOptions">
<string key="NS.key.0">NSValueTransformerName</string>
<string key="NS.object.0">NSIsNil</string>
</object>
<int key="NSNibBindingConnectorVersion">2</int>
</object>
</object>
<int key="connectionID">33</int>
</object>
<object class="IBConnectionRecord">
<object class="IBOutletConnection" key="connection">
<string key="label">actionButton</string>
<reference key="source" ref="245526436"/>
<reference key="destination" ref="566879706"/>
</object>
<int key="connectionID">34</int>
</object>
<object class="IBConnectionRecord">
<object class="IBOutletConnection" key="connection">
<string key="label">progressBar</string>
<reference key="source" ref="245526436"/>
<reference key="destination" ref="454270533"/>
</object>
<int key="connectionID">49</int>
</object>
</object>
<object class="IBMutableOrderedSet" key="objectRecords">
<object class="NSArray" key="orderedObjects">
<bool key="EncodedWithXMLCoder">YES</bool>
<object class="IBObjectRecord">
<int key="objectID">0</int>
<reference key="object" ref="0"/>
<reference key="children" ref="780577916"/>
<nil key="parent"/>
</object>
<object class="IBObjectRecord">
<int key="objectID">-2</int>
<reference key="object" ref="245526436"/>
<reference key="parent" ref="0"/>
<string key="objectName">File's Owner</string>
</object>
<object class="IBObjectRecord">
<int key="objectID">-1</int>
<reference key="object" ref="879485556"/>
<reference key="parent" ref="0"/>
<string key="objectName">First Responder</string>
</object>
<object class="IBObjectRecord">
<int key="objectID">-3</int>
<reference key="object" ref="472338989"/>
<reference key="parent" ref="0"/>
<string key="objectName">Application</string>
</object>
<object class="IBObjectRecord">
<int key="objectID">5</int>
<reference key="object" ref="661323156"/>
<object class="NSMutableArray" key="children">
<bool key="EncodedWithXMLCoder">YES</bool>
<reference ref="512815736"/>
</object>
<reference key="parent" ref="0"/>
<string key="objectName">Window</string>
</object>
<object class="IBObjectRecord">
<int key="objectID">6</int>
<reference key="object" ref="512815736"/>
<object class="NSMutableArray" key="children">
<bool key="EncodedWithXMLCoder">YES</bool>
<reference ref="56655866"/>
<reference ref="692218720"/>
<reference ref="454270533"/>
<reference ref="566879706"/>
<reference ref="65200871"/>
</object>
<reference key="parent" ref="661323156"/>
</object>
<object class="IBObjectRecord">
<int key="objectID">7</int>
<reference key="object" ref="56655866"/>
<object class="NSMutableArray" key="children">
<bool key="EncodedWithXMLCoder">YES</bool>
<reference ref="381943368"/>
</object>
<reference key="parent" ref="512815736"/>
</object>
<object class="IBObjectRecord">
<int key="objectID">8</int>
<reference key="object" ref="692218720"/>
<object class="NSMutableArray" key="children">
<bool key="EncodedWithXMLCoder">YES</bool>
<reference ref="597081861"/>
</object>
<reference key="parent" ref="512815736"/>
</object>
<object class="IBObjectRecord">
<int key="objectID">11</int>
<reference key="object" ref="454270533"/>
<reference key="parent" ref="512815736"/>
</object>
<object class="IBObjectRecord">
<int key="objectID">12</int>
<reference key="object" ref="566879706"/>
<object class="NSMutableArray" key="children">
<bool key="EncodedWithXMLCoder">YES</bool>
<reference ref="130218013"/>
</object>
<reference key="parent" ref="512815736"/>
</object>
<object class="IBObjectRecord">
<int key="objectID">16</int>
<reference key="object" ref="65200871"/>
<object class="NSMutableArray" key="children">
<bool key="EncodedWithXMLCoder">YES</bool>
<reference ref="180962568"/>
</object>
<reference key="parent" ref="512815736"/>
</object>
<object class="IBObjectRecord">
<int key="objectID">53</int>
<reference key="object" ref="381943368"/>
<reference key="parent" ref="56655866"/>
</object>
<object class="IBObjectRecord">
<int key="objectID">54</int>
<reference key="object" ref="597081861"/>
<reference key="parent" ref="692218720"/>
</object>
<object class="IBObjectRecord">
<int key="objectID">55</int>
<reference key="object" ref="130218013"/>
<reference key="parent" ref="566879706"/>
</object>
<object class="IBObjectRecord">
<int key="objectID">56</int>
<reference key="object" ref="180962568"/>
<reference key="parent" ref="65200871"/>
</object>
</object>
</object>
<object class="NSMutableDictionary" key="flattenedProperties">
<bool key="EncodedWithXMLCoder">YES</bool>
<object class="NSArray" key="dict.sortedKeys">
<bool key="EncodedWithXMLCoder">YES</bool>
<string>-3.ImportedFromIB2</string>
<string>11.ImportedFromIB2</string>
<string>12.ImportedFromIB2</string>
<string>16.ImportedFromIB2</string>
<string>5.IBEditorWindowLastContentRect</string>
<string>5.IBWindowTemplateEditedContentRect</string>
<string>5.ImportedFromIB2</string>
<string>5.windowTemplate.hasMinSize</string>
<string>5.windowTemplate.minSize</string>
<string>6.ImportedFromIB2</string>
<string>7.ImportedFromIB2</string>
<string>8.ImportedFromIB2</string>
</object>
<object class="NSMutableArray" key="dict.values">
<bool key="EncodedWithXMLCoder">YES</bool>
<boolean value="YES"/>
<boolean value="YES"/>
<boolean value="YES"/>
<boolean value="YES"/>
<string>{{294, 716}, {400, 107}}</string>
<string>{{294, 716}, {400, 107}}</string>
<boolean value="YES"/>
<boolean value="YES"/>
<string>{213, 107}</string>
<boolean value="YES"/>
<boolean value="YES"/>
<boolean value="YES"/>
</object>
</object>
<object class="NSMutableDictionary" key="unlocalizedProperties">
<bool key="EncodedWithXMLCoder">YES</bool>
<reference key="dict.sortedKeys" ref="0"/>
<object class="NSMutableArray" key="dict.values">
<bool key="EncodedWithXMLCoder">YES</bool>
</object>
</object>
<nil key="activeLocalization"/>
<object class="NSMutableDictionary" key="localizations">
<bool key="EncodedWithXMLCoder">YES</bool>
<reference key="dict.sortedKeys" ref="0"/>
<object class="NSMutableArray" key="dict.values">
<bool key="EncodedWithXMLCoder">YES</bool>
</object>
</object>
<nil key="sourceID"/>
<int key="maxID">56</int>
</object>
<object class="IBClassDescriber" key="IBDocument.Classes">
<object class="NSMutableArray" key="referencedPartialClassDescriptions">
<bool key="EncodedWithXMLCoder">YES</bool>
<object class="IBPartialClassDescription">
<string key="className">FirstResponder</string>
<string key="superclassName">NSObject</string>
<object class="IBClassDescriptionSource" key="sourceIdentifier">
<string key="majorKey">IBUserSource</string>
<string key="minorKey"/>
</object>
</object>
<object class="IBPartialClassDescription">
<string key="className">NSApplication</string>
<string key="superclassName">NSResponder</string>
<object class="IBClassDescriptionSource" key="sourceIdentifier">
<string key="majorKey">IBUserSource</string>
<string key="minorKey"/>
</object>
</object>
<object class="IBPartialClassDescription">
<string key="className">NSObject</string>
<object class="IBClassDescriptionSource" key="sourceIdentifier">
<string key="majorKey">IBUserSource</string>
<string key="minorKey"/>
</object>
</object>
<object class="IBPartialClassDescription">
<string key="className">SUStatusController</string>
<string key="superclassName">SUWindowController</string>
<object class="NSMutableDictionary" key="outlets">
<bool key="EncodedWithXMLCoder">YES</bool>
<object class="NSArray" key="dict.sortedKeys">
<bool key="EncodedWithXMLCoder">YES</bool>
<string>actionButton</string>
<string>progressBar</string>
</object>
<object class="NSMutableArray" key="dict.values">
<bool key="EncodedWithXMLCoder">YES</bool>
<string>NSButton</string>
<string>NSProgressIndicator</string>
</object>
</object>
<object class="IBClassDescriptionSource" key="sourceIdentifier">
<string key="majorKey">IBUserSource</string>
<string key="minorKey"/>
</object>
</object>
<object class="IBPartialClassDescription">
<string key="className">SUWindowController</string>
<string key="superclassName">NSWindowController</string>
<object class="IBClassDescriptionSource" key="sourceIdentifier">
<string key="majorKey">IBUserSource</string>
<string key="minorKey"/>
</object>
</object>
</object>
</object>
<int key="IBDocument.localizationMode">0</int>
<string key="IBDocument.TargetRuntimeIdentifier">IBCocoaFramework</string>
<object class="NSMutableDictionary" key="IBDocument.PluginDeclaredDependencies">
<string key="NS.key.0">com.apple.InterfaceBuilder.CocoaPlugin.macosx</string>
<integer value="1050" key="NS.object.0"/>
</object>
<object class="NSMutableDictionary" key="IBDocument.PluginDeclaredDevelopmentDependencies">
<string key="NS.key.0">com.apple.InterfaceBuilder.CocoaPlugin.InterfaceBuilder3</string>
<integer value="3100" key="NS.object.0"/>
</object>
<bool key="IBDocument.PluginDeclaredDependenciesTrackSystemTargetVersion">YES</bool>
<string key="IBDocument.LastKnownRelativeProjectPath">Sparkle.xcodeproj</string>
<int key="IBDocument.defaultPropertyAccessControl">3</int>
<object class="NSMutableDictionary" key="IBDocument.LastKnownImageSizes">
<string key="NS.key.0">NSApplicationIcon</string>
<string key="NS.object.0">{128, 128}</string>
</object>
</data>
</archive>
+6 -3
View File
@@ -11,15 +11,18 @@
#import "SUWindowController.h"
@interface SUStatusController : SUWindowController {
@class SUHost;
@interface SUStatusController : SUWindowController
{
@private
double progressValue, maxProgressValue;
NSString *title, *statusText, *buttonTitle;
IBOutlet NSButton *actionButton;
IBOutlet NSProgressIndicator* progressBar;
NSBundle *hostBundle;
SUHost *host;
}
- (id)initWithHostBundle:(NSBundle *)hostBundle;
- (id)initWithHost:(SUHost *)host;
// Pass 0 for the max progress value to get an indeterminate progress bar.
// Pass nil for the status text to not show it.
+32 -10
View File
@@ -6,17 +6,23 @@
// Copyright 2006 Andy Matuschak. All rights reserved.
//
#import "Sparkle.h"
#import "SUUpdater.h"
#import "SUAppcast.h"
#import "SUAppcastItem.h"
#import "SUVersionComparisonProtocol.h"
#import "SUStatusController.h"
#import "SUHost.h"
@implementation SUStatusController
- (id)initWithHostBundle:(NSBundle *)hb
- (id)initWithHost:(SUHost *)aHost
{
self = [super initWithHostBundle:hb windowNibName:@"SUStatus"];
self = [super initWithHost:aHost windowNibName:@"SUStatus"];
if (self)
{
hostBundle = [hb retain];
host = [aHost retain];
[self setShouldCascadeWindows:NO];
}
return self;
@@ -24,15 +30,21 @@
- (void)dealloc
{
[hostBundle release];
[host release];
[title release];
[statusText release];
[buttonTitle release];
[super dealloc];
}
- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@, %@>", [self class], [host bundlePath], [host installationPath]]; }
- (void)awakeFromNib
{
if ([host isBackgroundApplication]) {
[[self window] setLevel:NSFloatingWindowLevel];
}
[[self window] center];
[[self window] setFrameAutosaveName:@"SUStatusFrame"];
[progressBar setUsesThreadedAnimation:YES];
@@ -40,12 +52,12 @@
- (NSString *)windowTitle
{
return [NSString stringWithFormat:SULocalizedString(@"Updating %@", nil), [hostBundle name]];
return [NSString stringWithFormat:SULocalizedString(@"Updating %@", nil), [host name]];
}
- (NSImage *)applicationIcon
{
return [hostBundle icon];
return [host icon];
}
- (void)beginActionWithTitle:(NSString *)aTitle maxProgressValue:(double)aMaxProgressValue statusText:(NSString *)aStatusText
@@ -58,7 +70,7 @@
[self setStatusText:aStatusText];
}
- (void)setButtonTitle:(NSString *)aButtonTitle target:target action:(SEL)action isDefault:(BOOL)isDefault
- (void)setButtonTitle:(NSString *)aButtonTitle target: (id)target action:(SEL)action isDefault:(BOOL)isDefault
{
[self willChangeValueForKey:@"buttonTitle"];
if (buttonTitle != aButtonTitle)
@@ -80,6 +92,14 @@
[actionButton setTarget:target];
[actionButton setAction:action];
[actionButton setKeyEquivalent:isDefault ? @"\r" : @""];
// 06/05/2008 Alex: Avoid a crash when cancelling during the extraction
[self setButtonEnabled: (target != nil)];
}
- (BOOL)progressBarShouldAnimate
{
return YES;
}
- (void)setButtonEnabled:(BOOL)enabled
@@ -104,10 +124,12 @@
- (void)setMaxProgressValue:(double)value
{
if (value < 0) value = 0;
if (value < 0.0) value = 0.0;
maxProgressValue = value;
[self setProgressValue:0];
[self setProgressValue:0.0];
[progressBar setIndeterminate:(value == 0.0)];
[progressBar startAnimation:self];
[progressBar setUsesThreadedAnimation: YES];
}
- (void)setStatusText:(NSString *)aStatusText
+4 -1
View File
@@ -9,9 +9,12 @@
#ifndef SUSYSTEMPROFILER_H
#define SUSYSTEMPROFILER_H
#import <Cocoa/Cocoa.h>
@class SUHost;
@interface SUSystemProfiler : NSObject {}
+ (SUSystemProfiler *)sharedSystemProfiler;
- (NSMutableArray *)systemProfileArrayForHostBundle:(NSBundle *)hostBundle;
- (NSMutableArray *)systemProfileArrayForHost:(SUHost *)host;
@end
#endif
+25 -26
View File
@@ -7,9 +7,9 @@
// Adapted from Sparkle+, by Tom Harrington.
//
#import "Sparkle.h"
#import "SUSystemProfiler.h"
#import "SUHost.h"
#import <sys/sysctl.h>
@implementation SUSystemProfiler
@@ -27,19 +27,19 @@
return [[[NSDictionary alloc] initWithContentsOfFile:path] autorelease];
}
- (NSMutableArray *)systemProfileArrayForHostBundle:(NSBundle *)hostBundle
- (NSMutableArray *)systemProfileArrayForHost:(SUHost *)host
{
NSDictionary *modelTranslation = [self modelTranslationTable];
// Gather profile information and append it to the URL.
NSMutableArray *profileArray = [NSMutableArray array];
NSArray *profileDictKeys = [NSArray arrayWithObjects:@"key", @"visibleKey", @"value", @"visibleValue", nil];
int error = 0 ;
int value = 0 ;
unsigned long length = sizeof(value) ;
NSArray *profileDictKeys = [NSArray arrayWithObjects:@"key", @"displayKey", @"value", @"displayValue", nil];
int error = 0;
int value = 0;
size_t length = sizeof(value);
// OS version
NSString *currentSystemVersion = [NSWorkspace systemVersionString];
NSString *currentSystemVersion = [SUHost systemVersionString];
if (currentSystemVersion != nil)
[profileArray addObject:[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"osVersion",@"OS Version",currentSystemVersion,currentSystemVersion,nil] forKeys:profileDictKeys]];
@@ -50,9 +50,9 @@
cpuType = value;
NSString *visibleCPUType;
switch(value) {
case 7: visibleCPUType=@"Intel"; break;
case 18: visibleCPUType=@"PowerPC"; break;
default: visibleCPUType=@"Unknown"; break;
case CPU_TYPE_X86: visibleCPUType = @"Intel"; break;
case CPU_TYPE_POWERPC: visibleCPUType = @"PowerPC"; break;
default: visibleCPUType = @"Unknown"; break;
}
[profileArray addObject:[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"cputype",@"CPU Type", [NSNumber numberWithInt:value], visibleCPUType,nil] forKeys:profileDictKeys]];
}
@@ -89,18 +89,18 @@
}
error = sysctlbyname("hw.model", NULL, &length, NULL, 0);
if (error == 0) {
char *cpuModel;
cpuModel = (char *)malloc(sizeof(char) * length);
error = sysctlbyname("hw.model", cpuModel, &length, NULL, 0);
if (error == 0) {
NSString *rawModelName = [NSString stringWithUTF8String:cpuModel];
NSString *visibleModelName = [modelTranslation objectForKey:rawModelName];
if (visibleModelName == nil)
visibleModelName = rawModelName;
[profileArray addObject:[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"model",@"Mac Model", rawModelName, visibleModelName, nil] forKeys:profileDictKeys]];
}
if (cpuModel != NULL)
char *cpuModel = (char *)malloc(sizeof(char) * length);
if (cpuModel != NULL) {
error = sysctlbyname("hw.model", cpuModel, &length, NULL, 0);
if (error == 0) {
NSString *rawModelName = [NSString stringWithUTF8String:cpuModel];
NSString *visibleModelName = [modelTranslation objectForKey:rawModelName];
if (visibleModelName == nil)
visibleModelName = rawModelName;
[profileArray addObject:[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"model",@"Mac Model", rawModelName, visibleModelName, nil] forKeys:profileDictKeys]];
}
free(cpuModel);
}
}
// Number of CPUs
@@ -111,22 +111,21 @@
// User preferred language
NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
NSArray *languages = [defs objectForKey:@"AppleLanguages"];
if (languages && ([languages count] > 0))
if ([languages count] > 0)
[profileArray addObject:[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"lang",@"Preferred Language", [languages objectAtIndex:0], [languages objectAtIndex:0],nil] forKeys:profileDictKeys]];
// Application sending the request
NSString *appName = [hostBundle name];
NSString *appName = [host name];
if (appName)
[profileArray addObject:[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"appName",@"Application Name", appName, appName,nil] forKeys:profileDictKeys]];
NSString *appVersion = [hostBundle version];
NSString *appVersion = [host version];
if (appVersion)
[profileArray addObject:[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"appVersion",@"Application Version", appVersion, appVersion,nil] forKeys:profileDictKeys]];
// Number of displays?
// CPU speed
OSErr err;
SInt32 gestaltInfo;
err = Gestalt(gestaltProcClkSpeedMHz,&gestaltInfo);
OSErr err = Gestalt(gestaltProcClkSpeedMHz,&gestaltInfo);
if (err == noErr)
[profileArray addObject:[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"cpuFreqMHz",@"CPU Speed (GHz)", [NSNumber numberWithInt:gestaltInfo], [NSNumber numberWithDouble:gestaltInfo/1000.0],nil] forKeys:profileDictKeys]];
+7 -1
View File
@@ -13,11 +13,17 @@
#import "SUBasicUpdateDriver.h"
@class SUStatusController, SUUpdateAlert;
@interface SUUIBasedUpdateDriver : SUBasicUpdateDriver {
@interface SUUIBasedUpdateDriver : SUBasicUpdateDriver
{
SUStatusController *statusController;
SUUpdateAlert *updateAlert;
}
- (void)showModalAlert:(NSAlert *)alert;
- (IBAction)cancelDownload: (id)sender;
- (void)installAndRestart: (id)sender;
@end
#endif
+136 -39
View File
@@ -7,18 +7,37 @@
//
#import "SUUIBasedUpdateDriver.h"
#import "Sparkle.h"
#import "NSNumber+Units.h"
#import "SUUpdateAlert.h"
#import "SUUpdater_Private.h"
#import "SUHost.h"
#import "SUStatusController.h"
#import "SUConstants.h"
#import "SUPasswordPrompt.h"
@implementation SUUIBasedUpdateDriver
- (void)didFindValidUpdate
{
updateAlert = [[SUUpdateAlert alloc] initWithAppcastItem:updateItem hostBundle:hostBundle];
updateAlert = [[SUUpdateAlert alloc] initWithAppcastItem:updateItem host:host];
[updateAlert setDelegate:self];
// If the app is a menubar app or the like, we need to focus it first:
if ([[hostBundle objectForInfoDictionaryKey:@"LSUIElement"] doubleValue]) { [NSApp activateIgnoringOtherApps:YES]; }
id<SUVersionDisplay> versDisp = nil;
if ([[updater delegate] respondsToSelector:@selector(versionDisplayerForUpdater:)])
versDisp = [[updater delegate] versionDisplayerForUpdater: updater];
[updateAlert setVersionDisplayer: versDisp];
if ([[updater delegate] respondsToSelector:@selector(updater:didFindValidUpdate:)])
[[updater delegate] updater:updater didFindValidUpdate:updateItem];
// 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])
{
[[updateAlert window] setHidesOnDeactivate:NO];
[NSApp activateIgnoringOtherApps:YES];
}
// Only show the update alert if the app is active; otherwise, we'll wait until it is.
if ([NSApp isActive])
@@ -29,11 +48,11 @@
- (void)didNotFindUpdate
{
if ([delegate respondsToSelector:@selector(didNotFindUpdateToHostBundle:)])
[delegate didNotFindUpdateToHostBundle:hostBundle];
NSAlert *alert = [NSAlert alertWithMessageText:SULocalizedString(@"You're up to date!", nil) defaultButton:SULocalizedString(@"OK", nil) alternateButton:nil otherButton:nil informativeTextWithFormat:SULocalizedString(@"%@ %@ is currently the newest version available.", nil), [hostBundle name], [hostBundle displayVersion]];
[alert setIcon:[hostBundle icon]];
[alert runModal];
if ([[updater delegate] respondsToSelector:@selector(updaterDidNotFindUpdate:)])
[[updater delegate] updaterDidNotFindUpdate:updater];
NSAlert *alert = [NSAlert alertWithMessageText:SULocalizedString(@"You're up-to-date!", nil) defaultButton:SULocalizedString(@"OK", nil) alternateButton:nil otherButton:nil informativeTextWithFormat:SULocalizedString(@"%@ %@ is currently the newest version available.", nil), [host name], [host displayVersion]];
[self showModalAlert:alert];
[self abortUpdate];
}
@@ -46,21 +65,27 @@
- (void)updateAlert:(SUUpdateAlert *)alert finishedWithChoice:(SUUpdateAlertChoice)choice
{
[updateAlert release]; updateAlert = nil;
if ([delegate respondsToSelector:@selector(userChoseAction:forUpdate:toHostBundle:)])
[delegate userChoseAction:choice forUpdate:updateItem toHostBundle:hostBundle];
[[SUUserDefaults standardUserDefaults] setObject:nil forKey:SUSkippedVersionKey];
[host setObject:nil forUserDefaultsKey:SUSkippedVersionKey];
switch (choice)
{
case SUInstallUpdateChoice:
statusController = [[SUStatusController alloc] initWithHostBundle:hostBundle];
[statusController beginActionWithTitle:SULocalizedString(@"Downloading update\u2026", nil) maxProgressValue:0 statusText:nil];
statusController = [[SUStatusController alloc] initWithHost:host];
[statusController beginActionWithTitle:SULocalizedString(@"Downloading update...", @"Take care not to overflow the status window.") maxProgressValue:0.0 statusText:nil];
[statusController setButtonTitle:SULocalizedString(@"Cancel", nil) target:self action:@selector(cancelDownload:) isDefault:NO];
[statusController showWindow:self];
[self downloadUpdate];
break;
case SUOpenInfoURLChoice:
[[NSWorkspace sharedWorkspace] openURL: [updateItem infoURL]];
[self abortUpdate];
break;
case SUSkipThisVersionChoice:
[[SUUserDefaults standardUserDefaults] setObject:[updateItem versionString] forKey:SUSkippedVersionKey];
[host setObject:[updateItem versionString] forUserDefaultsKey:SUSkippedVersionKey];
[self abortUpdate];
break;
case SURemindMeLaterChoice:
[self abortUpdate];
break;
@@ -72,16 +97,30 @@
[statusController setMaxProgressValue:[response expectedContentLength]];
}
- (void)download:(NSURLDownload *)download didReceiveDataOfLength:(NSUInteger)length
- (NSString *)humanReadableSizeFromDouble:(double)value
{
[statusController setProgressValue:[statusController progressValue] + length];
if ([statusController maxProgressValue] > 0)
[statusController setStatusText:[NSString stringWithFormat:SULocalizedString(@"%@ of %@", nil), [NSNumber humanReadableSizeFromDouble:[statusController progressValue]], [NSNumber humanReadableSizeFromDouble:[statusController maxProgressValue]]]];
else
[statusController setStatusText:[NSString stringWithFormat:SULocalizedString(@"%@ downloaded", nil), [NSNumber humanReadableSizeFromDouble:[statusController progressValue]]]];
if (value < 1000)
return [NSString stringWithFormat:@"%.0lf %@", value, SULocalizedString(@"B", @"the unit for bytes")];
if (value < 1000 * 1000)
return [NSString stringWithFormat:@"%.0lf %@", value / 1000.0, SULocalizedString(@"KB", @"the unit for kilobytes")];
if (value < 1000 * 1000 * 1000)
return [NSString stringWithFormat:@"%.1lf %@", value / 1000.0 / 1000.0, SULocalizedString(@"MB", @"the unit for megabytes")];
return [NSString stringWithFormat:@"%.2lf %@", value / 1000.0 / 1000.0 / 1000.0, SULocalizedString(@"GB", @"the unit for gigabytes")];
}
- (IBAction)cancelDownload:sender
- (void)download:(NSURLDownload *)download didReceiveDataOfLength:(NSUInteger)length
{
[statusController setProgressValue:[statusController progressValue] + (double)length];
if ([statusController maxProgressValue] > 0.0)
[statusController setStatusText:[NSString stringWithFormat:SULocalizedString(@"%@ of %@", nil), [self humanReadableSizeFromDouble:[statusController progressValue]], [self humanReadableSizeFromDouble:[statusController maxProgressValue]]]];
else
[statusController setStatusText:[NSString stringWithFormat:SULocalizedString(@"%@ downloaded", nil), [self humanReadableSizeFromDouble:[statusController progressValue]]]];
}
- (IBAction)cancelDownload: (id)sender
{
if (download)
[download cancel];
@@ -91,42 +130,83 @@
- (void)extractUpdate
{
// Now we have to extract the downloaded archive.
[statusController beginActionWithTitle:SULocalizedString(@"Extracting update\u2026", nil) maxProgressValue:0 statusText:nil];
[statusController beginActionWithTitle:SULocalizedString(@"Extracting update...", @"Take care not to overflow the status window.") maxProgressValue:0.0 statusText:nil];
[statusController setButtonEnabled:NO];
[super extractUpdate];
}
- (void)unarchiver:(SUUnarchiver *)ua extractedLength:(long)length
- (void)unarchiver:(SUUnarchiver *)ua extractedLength:(unsigned long)length
{
// We do this here instead of in extractUpdate so that we only have a determinate progress bar for archives with progress.
if ([statusController maxProgressValue] == 0)
[statusController setMaxProgressValue:[[[[NSFileManager defaultManager] fileAttributesAtPath:downloadPath traverseLink:NO] objectForKey:NSFileSize] doubleValue]];
[statusController setProgressValue:[statusController progressValue] + length];
if ([statusController maxProgressValue] == 0.0)
{
NSDictionary * attributes;
#if MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_4
attributes = [[NSFileManager defaultManager] fileAttributesAtPath:downloadPath traverseLink:NO];
#else
attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:downloadPath error:nil];
#endif
[statusController setMaxProgressValue:[[attributes objectForKey:NSFileSize] doubleValue]];
}
[statusController setProgressValue:[statusController progressValue] + (double)length];
}
- (void)unarchiverDidFinish:(SUUnarchiver *)ua
{
[statusController beginActionWithTitle:SULocalizedString(@"Ready to Install", nil) maxProgressValue:1 statusText:nil];
[statusController setProgressValue:1]; // Fill the bar.
[statusController beginActionWithTitle:SULocalizedString(@"Ready to Install", nil) maxProgressValue:1.0 statusText:nil];
[statusController setProgressValue:1.0]; // Fill the bar.
[statusController setButtonEnabled:YES];
[statusController setButtonTitle:SULocalizedString(@"Install and Relaunch", nil) target:self action:@selector(installAndRestart:) isDefault:YES];
[[statusController window] makeKeyAndOrderFront: self];
[NSApp requestUserAttention:NSInformationalRequest];
}
- (void)installAndRestart:sender { [self installUpdate]; }
- (void)installUpdate
- (void)unarchiver:(SUUnarchiver *)unarchiver requiresPasswordReturnedViaInvocation:(NSInvocation *)invocation
{
[statusController beginActionWithTitle:SULocalizedString(@"Installing update\u2026", nil) maxProgressValue:0 statusText:nil];
NSString *password = @"";
// some users reported sparkle is asking for password randomly
// HACK: do not open prompt and pass empty string as a password
//
// SUPasswordPrompt *prompt = [[SUPasswordPrompt alloc] initWithHost:host];
// NSString *password = nil;
// if([prompt run])
// {
// password = [prompt password];
// }
// [prompt release];
[invocation setArgument:&password atIndex:2];
[invocation invoke];
}
- (void)installAndRestart: (id)sender
{
[self installWithToolAndRelaunch:YES];
}
- (void)installWithToolAndRelaunch:(BOOL)relaunch
{
[statusController beginActionWithTitle:SULocalizedString(@"Installing update...", @"Take care not to overflow the status window.") maxProgressValue:0.0 statusText:nil];
[statusController setButtonEnabled:NO];
[super installUpdate];
[super installWithToolAndRelaunch:relaunch];
// if a user chooses to NOT relaunch the app (as is the case with WebKit
// when it asks you if you are sure you want to close the app with multiple
// tabs open), the status window still stays on the screen and obscures
// other windows; with this fix, it doesn't
if (statusController)
{
[statusController close];
[statusController autorelease];
statusController = nil;
}
}
- (void)abortUpdateWithError:(NSError *)error
{
NSAlert *alert = [NSAlert alertWithMessageText:SULocalizedString(@"Update Error!", nil) defaultButton:SULocalizedString(@"Cancel Update", nil) alternateButton:nil otherButton:nil informativeTextWithFormat:[error localizedDescription]];
[alert setIcon:[hostBundle icon]];
[alert runModal];
NSAlert *alert = [NSAlert alertWithMessageText:SULocalizedString(@"Update Error!", nil) defaultButton:SULocalizedString(@"Cancel Update", nil) alternateButton:nil otherButton:nil informativeTextWithFormat:@"%@", [error localizedDescription]];
[self showModalAlert:alert];
[super abortUpdateWithError:error];
}
@@ -136,8 +216,25 @@
{
[statusController close];
[statusController autorelease];
statusController = nil;
}
[super abortUpdate];
}
- (void)showModalAlert:(NSAlert *)alert
{
if ([[updater delegate] respondsToSelector:@selector(updaterWillShowModalAlert:)])
[[updater delegate] updaterWillShowModalAlert: updater];
// When showing a modal alert we need to ensure that background applications
// are focused to inform the user since there is no dock icon to notify them.
if ([host isBackgroundApplication]) { [NSApp activateIgnoringOtherApps:YES]; }
[alert setIcon:[host icon]];
[alert runModal];
if ([[updater delegate] respondsToSelector:@selector(updaterDidShowModalAlert:)])
[[updater delegate] updaterDidShowModalAlert: updater];
}
@end
+7 -3
View File
@@ -9,12 +9,15 @@
#ifndef SUUNARCHIVER_H
#define SUUNARCHIVER_H
@class SUHost;
@interface SUUnarchiver : NSObject {
id delegate;
NSURL *archiveURL;
NSString *archivePath;
SUHost *updateHost;
}
+ (SUUnarchiver *)unarchiverForURL:(NSURL *)URL;
+ (SUUnarchiver *)unarchiverForPath:(NSString *)path updatingHost:(SUHost *)host;
- (void)setDelegate:delegate;
- (void)start;
@@ -22,9 +25,10 @@
@end
@interface NSObject (SUUnarchiverDelegate)
- (void)unarchiver:(SUUnarchiver *)unarchiver extractedLength:(long)length;
- (void)unarchiver:(SUUnarchiver *)unarchiver extractedLength:(unsigned long)length;
- (void)unarchiverDidFinish:(SUUnarchiver *)unarchiver;
- (void)unarchiverDidFail:(SUUnarchiver *)unarchiver;
- (void)unarchiver:(SUUnarchiver *)unarchiver requiresPasswordReturnedViaInvocation:(NSInvocation *)invocation;
@end
#endif
+11 -7
View File
@@ -7,26 +7,30 @@
//
#import "Sparkle.h"
#import "SUUpdater.h"
#import "SUAppcast.h"
#import "SUAppcastItem.h"
#import "SUVersionComparisonProtocol.h"
#import "SUUnarchiver.h"
#import "SUUnarchiver_Private.h"
@implementation SUUnarchiver
extern NSMutableArray *__unarchiverImplementations;
+ (SUUnarchiver *)unarchiverForURL:(NSURL *)URL
+ (SUUnarchiver *)unarchiverForPath:(NSString *)path updatingHost:(SUHost *)host
{
NSEnumerator *implementationEnumerator = [[self _unarchiverImplementations] objectEnumerator];
NSEnumerator *implementationEnumerator = [[self unarchiverImplementations] objectEnumerator];
id current;
while ((current = [implementationEnumerator nextObject]))
{
if ([current _canUnarchiveURL:URL])
return [[[current alloc] _initWithURL:URL] autorelease];
if ([current canUnarchivePath:path])
return [[[current alloc] initWithPath:path host:host] autorelease];
}
return nil;
}
- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], archivePath]; }
- (void)setDelegate:del
{
delegate = del;
+7 -11
View File
@@ -13,18 +13,14 @@
#import "SUUnarchiver.h"
@interface SUUnarchiver (Private)
+ (void)_registerImplementation:(Class)implementation;
+ (NSArray *)_unarchiverImplementations;
+ (BOOL)_canUnarchiveURL:(NSURL *)URL;
- _initWithURL:(NSURL *)URL;
+ (void)registerImplementation:(Class)implementation;
+ (NSArray *)unarchiverImplementations;
+ (BOOL)canUnarchivePath:(NSString *)path;
- (id)initWithPath:(NSString *)path host:(SUHost *)host;;
- (void)_notifyDelegateOfExtractedLength:(long)length;
- (void)_notifyDelegateOfSuccess;
- (void)_notifyDelegateOfFailure;
@end
@interface NSURL (SUTypeDetection)
- (BOOL)conformsToType:(NSString *)type;
- (void)notifyDelegateOfExtractedLength:(NSNumber *)length;
- (void)notifyDelegateOfSuccess;
- (void)notifyDelegateOfFailure;
@end
#endif
+19 -32
View File
@@ -10,71 +10,58 @@
@implementation SUUnarchiver (Private)
- _initWithURL:(NSURL *)URL
- (id)initWithPath:(NSString *)path host:(SUHost *)host
{
if ((self = [super init]))
archiveURL = [URL copy];
{
archivePath = [path copy];
updateHost = [host retain];
}
return self;
}
- (void)dealloc
{
[archiveURL release];
[archivePath release];
[updateHost release];
[super dealloc];
}
+ (BOOL)_canUnarchiveURL:(NSURL *)URL
+ (BOOL)canUnarchivePath:(NSString *)path
{
return NO;
}
- (void)_notifyDelegateOfExtractedLength:(long)length
- (void)notifyDelegateOfExtractedLength:(NSNumber *)length
{
if ([delegate respondsToSelector:@selector(unarchiver:extractedLength:)])
[delegate unarchiver:self extractedLength:length];
[delegate unarchiver:self extractedLength:[length unsignedLongValue]];
}
- (void)_notifyDelegateOfSuccess
- (void)notifyDelegateOfSuccess
{
if ([delegate respondsToSelector:@selector(unarchiverDidFinish:)])
[delegate performSelector:@selector(unarchiverDidFinish:) withObject:self];
}
- (void)_notifyDelegateOfFailure
- (void)notifyDelegateOfFailure
{
if ([delegate respondsToSelector:@selector(unarchiverDidFail:)])
[delegate performSelector:@selector(unarchiverDidFail:) withObject:self];
}
static NSMutableArray *__unarchiverImplementations;
static NSMutableArray *gUnarchiverImplementations;
+ (void)_registerImplementation:(Class)implementation
+ (void)registerImplementation:(Class)implementation
{
if (!__unarchiverImplementations)
__unarchiverImplementations = [[NSMutableArray alloc] init];
[__unarchiverImplementations addObject:implementation];
if (!gUnarchiverImplementations)
gUnarchiverImplementations = [[NSMutableArray alloc] init];
[gUnarchiverImplementations addObject:implementation];
}
+ (NSArray *)_unarchiverImplementations
+ (NSArray *)unarchiverImplementations
{
return [NSArray arrayWithArray:__unarchiverImplementations];
return [NSArray arrayWithArray:gUnarchiverImplementations];
}
@end
@implementation NSURL (SUTypeDetection)
- (NSString *)__UTI
{
FSRef fsRefToItem;
FSPathMakeRef((UInt8 *)[[self path] fileSystemRepresentation], &fsRefToItem, NULL );
NSString *UTI = nil;
LSCopyItemAttribute(&fsRefToItem, kLSRolesAll, kLSItemContentType, (CFTypeRef *)(&UTI));
return [UTI autorelease];
}
- (BOOL)conformsToType:(NSString *)type
{
return UTTypeConformsTo((CFStringRef)[self __UTI], (CFStringRef)type);
}
@end
+14 -4
View File
@@ -10,37 +10,47 @@
#define SUUPDATEALERT_H
#import "SUWindowController.h"
#import "SUVersionDisplayProtocol.h"
typedef enum
{
SUInstallUpdateChoice,
SURemindMeLaterChoice,
SUSkipThisVersionChoice
SUSkipThisVersionChoice,
SUOpenInfoURLChoice
} SUUpdateAlertChoice;
@class WebView, SUAppcastItem;
@class WebView, SUAppcastItem, SUHost;
@interface SUUpdateAlert : SUWindowController {
SUAppcastItem *updateItem;
NSBundle *hostBundle;
SUHost *host;
id delegate;
id<SUVersionDisplay> versionDisplayer;
IBOutlet WebView *releaseNotesView;
IBOutlet NSTextField *description;
IBOutlet NSButton *installButton; // UK 2007-08-31.
IBOutlet NSButton *skipButton;
IBOutlet NSButton *laterButton;
NSProgressIndicator *releaseNotesSpinner;
BOOL webViewFinishedLoading;
}
- (id)initWithAppcastItem:(SUAppcastItem *)item hostBundle:(NSBundle *)hostBundle;
- (id)initWithAppcastItem:(SUAppcastItem *)item host:(SUHost *)host;
- (void)setDelegate:delegate;
- (IBAction)installUpdate:sender;
- (IBAction)skipThisVersion:sender;
- (IBAction)remindMeLater:sender;
- (void)setVersionDisplayer: (id<SUVersionDisplay>)disp;
@end
@interface NSObject (SUUpdateAlertDelegate)
- (void)updateAlert:(SUUpdateAlert *)updateAlert finishedWithChoice:(SUUpdateAlertChoice)updateChoice;
- (void)updateAlert:(SUUpdateAlert *)updateAlert shouldAllowAutoUpdate: (BOOL*)shouldAllowAutoUpdate;
@end
#endif
Loaded 100 of 367 files, more files were not shown because too many files have changed in this diff. Show more