Compare commits

..
129 Commits
Author SHA1 Message Date
Kornel Lesiński 59f9e0ee1b Sorted Xcode config 2014-03-01 14:19:27 +00:00
Kornel Lesiński ac7fd917d3 Removed Elgato-specific code 2014-02-17 23:07:13 +00:00
Kornel Lesiński 53f0f4f9ee Deleted redundant strings files 2014-02-17 22:58:07 +00:00
Kornel Lesiński 55c57abd2f Deleted untranslated strings files 2014-02-17 03:58:12 +00:00
Kornel Lesiński 006e71fa89 Removed junk comment from strings files 2014-02-17 03:57:43 +00:00
Kornel c6d47ed68d Merge pull request #3 from MaddTheSane/master
Fix a bug
2014-02-12 09:53:15 +00:00
MaddTheSane fd906d9589 The checkTimer Invar should have been retained. 2014-02-11 23:42:52 -07:00
Kornel 3e6431f94d Merge pull request #2 from MaddTheSane/master
More Objective C @properties
2014-02-10 14:55:44 +00:00
C.W. Betts 4a015ada8f Remove redundant semicolon. 2014-02-09 15:58:13 -07:00
C.W. Betts 2c1b3783e4 Use for… in… Objective C enumeration where possible. 2014-02-09 14:52:32 -07:00
C.W. Betts 808bde2699 Use dot notation in NTSynchronousTask.
Change the getter for the done ivar to isDone.
2014-02-09 14:46:26 -07:00
C.W. Betts fde6b4775e Move the NTSynchronousTask class to Objective C properties. 2014-02-09 14:40:11 -07:00
C.W. Betts 92bafa92bf Make SUAppcastDelegate a formal protocol.
Synthesize more Objective C getters and setters using Objective C properties.
2014-02-09 14:25:02 -07:00
Kornel Lesiński 7e2d4b019e Fixed unit test bundle identifier 2014-02-08 22:11:47 +00:00
C.W. Betts 10b8872afb Removed an unused variable. 2014-02-02 21:15:16 -07:00
MaddTheSane d4d984f42c Merge pull request #1 from pornel/master
Merge
2014-02-02 20:13:23 -08:00
C.W. Betts bd98b33e25 Use more modern Objective C syntax. 2014-02-02 15:56:05 -07:00
C.W. Betts 79f447d537 Use Objective-C properties for the SUAppcastItem class. 2014-02-02 15:44:20 -07:00
Kornel Lesiński a4759c871e Removed 10.4 code 2014-02-02 22:18:34 +00:00
Kornel Lesiński a3b9a74fe1 Disable plug-ins in release notes WebView 2014-02-02 21:25:45 +00:00
Kornel Lesiński faba759574 Avoid setting useless private font family name in the WebView 2014-02-02 21:25:41 +00:00
C.W. Betts 91800e3036 Quiet protocol warnings. 2014-02-02 14:22:55 -07:00
C.W. Betts d7dbbe4bb9 Implementing formal protocols for most Sparkle delegates. 2014-02-02 14:15:28 -07:00
Kornel Lesiński 2579f2c3a3 Holy megabyte icon, Batman! 2014-02-02 19:41:24 +00:00
Kornel Lesiński 01e9bd82be Use preprocessor config instead of cflags
Newer terminology for relaunch.
Fail if finish_install tool name not defined.
2014-02-02 17:30:49 +00:00
Kornel Lesiński d34d2853f6 Configurable name for finish_installation.app 2014-02-01 17:27:27 +00:00
Kornel Lesiński fd1ffce3e2 Version bump 2014-02-01 17:27:17 +00:00
Kornel Lesiński 6ae7b68659 Trimmed config further 2014-02-01 13:32:12 +00:00
Kornel Lesiński 54dc6d0071 Converted old NIBs to XIB 2014-02-01 12:41:36 +00:00
Kornel Lesiński a773ac5856 Enabled all translations 2014-02-01 12:24:40 +00:00
Kornel Lesiński 686c87242c Removed code for 10.4 2014-02-01 11:58:25 +00:00
Kornel Lesiński f2eaaeb4a3 Fixed XIB layout issue
Changed XIBs to support at least 10.6
2014-02-01 10:45:05 +00:00
Kornel Lesiński 5676acaebc Removed duplicate/irrelevant config 2014-02-01 10:45:05 +00:00
Kornel Lesiński 0055adcc52 Merge update zh_CN #259
* pull/259/head:
  update zh_CN

Conflicts:
	zh_CN.lproj/SUAutomaticUpdateAlert.strings
2014-02-01 02:26:09 +00:00
Kornel Lesiński ad518eb209 Merge pt-BR L10n polishing #274
* pull/274/head:
  pt-BR localization polishing

Conflicts:
	pt_BR.lproj/Sparkle.strings
2014-02-01 02:19:41 +00:00
Kornel Lesiński 20100c283f Merge remote-tracking branch 'pull/277/head'
* pull/277/head:
  Updated the Romanian translation

Conflicts:
	Sparkle.xcodeproj/project.pbxproj
2014-02-01 02:17:47 +00:00
Kornel Lesiński fc88f94d5d Merge remote-tracking branch 'pull/287/head'
* pull/287/head:
  Select Korean and Slovak for Sparkle.strings localization
2014-02-01 02:15:50 +00:00
Kornel Lesiński 222ab3edd9 Merge remote-tracking branch 'pull/290/head'
* pull/290/head:
  finish_installation.app and pkg files will not removed when we use *.pkg installer and restart system in the installer.
2014-02-01 02:15:22 +00:00
Kornel Lesiński 4b831a1394 Merge remote-tracking branch 'pull/292/head'
* pull/292/head:
  add a return type to the -init methods to satisfy a warning for missing-method-return-type
2014-02-01 02:13:53 +00:00
Kornel Lesiński bdc45d7e47 Prevent catastrophic data loss when finish_installation.app is not present for any reason #295
* pull/295/head:
  Quiet a warning caused by using a non-constant template format string.
  Take care not to attempt copying the finish_installation.app unless we have actually succeeded in locating it. In the strange scenario that the finish_installation.app was not present in the Sparkle bundle, the target path was evaluated as being the host app's Application Support folder itself, and Sparkle would proceed to completely wipe out the host's Application Support folder as it tried to copy the non-existent

Conflicts:
	SUUIBasedUpdateDriver.m
2014-02-01 02:13:03 +00:00
Kornel Lesiński 6ca5c3a337 Updated README 2014-02-01 01:10:08 +00:00
porneL 4ab8fd1010 Added NSURLDownloadDelegate declarations 2014-02-01 00:50:45 +00:00
Kornel Lesiński 3f40f444db Warnings-- 2014-02-01 00:50:45 +00:00
Kornel Lesiński f1d5103a07 10.6 deployment target 2014-02-01 00:50:45 +00:00
Kornel Lesiński 890f1fb393 Fixed format argument 2014-02-01 00:31:43 +00:00
Kornel Lesiński d7993257fe Merge remote-tracking branch 'origin/quiet-automatic-update'
* origin/quiet-automatic-update:
  Allow manual checks when an install on quit update is pending
  Allow the delegate to trigger a silent install and relaunch
  Support silent relaunches
  Increment the sudden termination counter if installing on quit
  Set up install on quit for critical automatic updates too
  Updating Sparkle.strings for the new, more strongly worded strings that are displayed for a 'critical update'
  Prompts the user to update after a week (rather than a day) if he doesn't quit the app.
  Adding <sparkle:tags> appcast item element, <sparkle:criticalUpdate /> tag
  Fixed a no-autorelease-pool leak.
  We have this check box that says "Automatically download and install updates in the future." But we only download them automatically. We still ask permission again before installing them.

Conflicts:
	SUBasicUpdateDriver.m
	en.lproj/Sparkle.strings
	finish_installation.m
2014-02-01 00:31:23 +00:00
Kornel Lesiński c99378c170 Xcode 5.1 config check 2014-01-31 23:31:46 +00:00
Kornel Lesiński 00d8b64b41 Ignore DerivedData 2014-01-31 23:31:45 +00:00
Kornel Lesiński 6a79789d32 Convert all strings files to UTF-8 (UTF-16 must die) 2014-01-31 23:31:45 +00:00
Kornel Lesiński ec8f46af91 Merge branch 'vslavik'
* vslavik:
  Disable -Werror in release builds.
  Another Werror to remove
  Need to turn this -Werror off too
  Build only active ARCH (at Xcode5 suggestion)
  Clang errors when format strings expected but aren’t provided
  Setting Deployment Target 10.7 globally
  Removing unneeded GC configurations
  Removing GC target
  remove SDK

Conflicts:
	Configurations/ConfigFrameworkReleaseGCSupport.xcconfig
	SUUIBasedUpdateDriver.m
	Sparkle.xcodeproj/project.pbxproj
2014-01-31 23:26:08 +00:00
Brian Webster 2ae8248c35 Removed redundant method declaration 2014-01-31 23:20:56 +00:00
Brian Webster d9d3ff2a8e Fixed pt_BR strings file encoding 2014-01-31 23:20:56 +00:00
Nate Weaver b420ad65be Wrap AuthorizationExecuteWithPrivilegesAndWait in pragmas to ignore deprecated functions.
I feel dirty.
2014-01-31 23:20:56 +00:00
Jorge Leandro Perez 5504d6896f Fixes static analyzer warnings 2014-01-31 23:20:47 +00:00
Jorge Leandro Perez d888705fd8 Enables Skip Install flag 2014-01-31 23:20:32 +00:00
Doug Russell 8d1109b59f Disable turkish localization because xcode believes it is corrupted 2014-01-31 23:19:11 +00:00
Kornel Lesiński 25aca9f56f Merge branch 'blackpixel'
* blackpixel:
  Fixed issue with icon
  New icon
  Updated icon.
  Switched the icon to be representative of the app. We'll want to find a better way of doing this once we have multiple apps pointed at this repo.
  fixed a 'content rectangle not entirely onscreen' warning
  updated sends system profile to use info.plist if user defaults key isn't present
  Support for notifications on some updater events
  Fix warnings
  fixed the Debug App Store configuration.. it was misnamed and causing a build error.
  fixing up the xcode configs to match ours for simpler building

Conflicts:
	Sparkle.xcodeproj/project.pbxproj
	Sparkle.xcodeproj/xcshareddata/xcschemes/Sparkle.xcscheme
	th.lproj/Sparkle.strings
2014-01-31 23:18:25 +00:00
Kornel Lesiński e75a9b0591 Merge branch 'earthlingsoft'
* earthlingsoft:
  Set development region to English
  Fixed Bug #428216: "Update alert does not use a proper emdash"
2014-01-31 23:16:38 +00:00
Kornel Lesiński 5dfc6ab3b2 Merge branch 'MrNoodle'
* MrNoodle:
  - Was using non-nil terminated c-string resulting in a nil string being returned which caused an erroneous condition check.
2014-01-31 23:16:22 +00:00
Kornel Lesiński 76cca58776 Merge branch 'uliwitness'
* uliwitness:
  Revert "Switch off secure updates for now"
  Shut up all of Xcode's complaints.
  Don't look at error variables if result says success.
  Less warnings.
  Shut up some warnings & make build with newer Xcode.
  Less unsafety with format strings.
  Switch off secure updates for now
  Quick hack to make this build again. Should probably just move to Sparkle mainline, now that they're halfway current.
  Satisfy some overly picky compilers.
  Make this build on 10.7. Might break building on earlier OSes.
  Removed the pt_PT localization from Uli's branch, since it was largely untranslated, and used the one from master instead.
  Fixed layout of localization XIBs
2014-01-31 21:46:49 +00:00
Kornel Lesiński 7141818b31 Revert "Switch off secure updates for now"
This reverts commit 6a48420e07.
2014-01-31 21:46:11 +00:00
Vaclav Slavik 52bee98867 Disable -Werror in release builds. 2013-11-14 17:36:57 +01:00
Paul Kim b262c2b581 - Was using non-nil terminated c-string resulting in a nil string being returned which caused an erroneous condition check. 2013-10-29 11:14:03 -04:00
Daniel Jalkut 192c3b4c2d Quiet a warning caused by using a non-constant template format string. 2013-09-26 15:59:44 -04:00
Daniel Jalkut cfe375b5f3 Take care not to attempt copying the finish_installation.app unless we have actually succeeded in locating it. In the strange scenario that the finish_installation.app was not present in the Sparkle bundle, the target path was evaluated as being the host app's Application Support folder itself, and Sparkle would proceed to completely wipe out the host's Application Support folder as it tried to copy the non-existent 2013-09-26 15:58:57 -04:00
Matt Thomas 271970697e Another Werror to remove 2013-09-21 12:29:02 +02:00
Matt Thomas 1539c0c077 Need to turn this -Werror off too 2013-09-21 12:29:02 +02:00
Matt Thomas aa25194536 Build only active ARCH (at Xcode5 suggestion) 2013-09-21 12:29:02 +02:00
Matt Thomas 6ab4163957 Clang errors when format strings expected
but aren’t provided
2013-09-21 12:29:02 +02:00
Matt Thomas dfa27acde2 Setting Deployment Target 10.7 globally
(we don}t really care about PPC support, etc)
2013-09-21 12:29:02 +02:00
Matt Thomas 50c3df3a6f Removing unneeded GC configurations 2013-09-21 12:29:02 +02:00
Matt Thomas 31a49c83b5 Removing GC target 2013-09-21 12:29:02 +02:00
Matt Thomas a57eb736cb remove SDK
This will default to the current one (SDKROOT = macosx)
2013-09-21 12:29:02 +02:00
Andy Kim 52b2d75d63 Merge branch 'master' of git://github.com/andymatuschak/Sparkle 2013-09-17 18:20:42 +09:00
Andy Kim 9ea81e21b9 Set development region to English 2013-09-17 18:12:35 +09:00
Dan Schimpf eda214a3ec add a return type to the -init methods to satisfy a warning for missing-method-return-type 2013-08-30 14:51:55 -07:00
Andy Matuschak d2b7fd6236 Adding left-behind SUPasswordPrompt.xib from 048ce10 2013-08-11 09:05:36 -07:00
Takayama Fumihiko 77ce7c19e9 finish_installation.app and pkg files will not removed when
we use *.pkg installer and restart system in the installer.

In this case, "Application Support" directory is corrupted
by unnecessary pkg files.
We need to scan files under "Application Support" directory
and examine whether pkg file or not.

It is quite annoying.

Therefore, this patch changes location of
finish_installation.app and pkg files to
"~/Library/Application Support/APPNAME/.Sparkle".
Then, we can remove finish_installation.app and pkg files
certainly.
2013-08-11 16:54:38 +09:00
Andy Matuschak 048ce10ed5 Updated Danish localization courtesy Daniel Østergaard Nielsen. 2013-08-07 16:12:03 -07:00
Shon Frazier b23d4a9641 Select Korean and Slovak for Sparkle.strings localization 2013-07-26 11:06:07 -04:00
Gabe 843bbe7ece Updated the Romanian translation 2013-06-11 02:56:05 +02:00
BR Lingo a7dbe4184c pt-BR localization polishing 2013-05-23 19:23:23 -03:00
61 3287299f53 update zh_CN 2013-03-25 16:53:11 +08:00
Uli Kusterer 1b71d3ebd1 Shut up all of Xcode's complaints. 2013-03-16 16:59:02 +01:00
Uli Kusterer ef8edef094 Don't look at error variables if result says success. 2013-03-16 16:58:37 +01:00
Uli Kusterer c793adf2ed Less warnings. 2013-02-09 20:22:25 +01:00
Uli Kusterer 5cf229ba41 Shut up some warnings & make build with newer Xcode. 2013-02-09 20:19:38 +01:00
Uli Kusterer 4789ebdec5 Less unsafety with format strings. 2013-02-09 20:19:09 +01:00
Rick Fillion 1325d3fe40 Fixed issue with icon 2013-01-14 13:30:40 -05:00
Rick Fillion 8d2054e62a New icon 2013-01-14 10:03:40 -05:00
Rick Fillion 93ebf843c2 Updated icon. 2012-12-05 12:57:27 -05:00
Rick Fillion 984aac852f Switched the icon to be representative of the app. We'll want to find a better way of doing this once we have multiple apps pointed at this repo. 2012-12-04 13:24:52 -05:00
Simone Manganelli 478c7fd8cd fixed a 'content rectangle not entirely onscreen' warning 2012-11-26 13:35:42 -08:00
Jamie Pinkham 08065bc05b updated sends system profile to use info.plist if user defaults key isn't present 2012-11-15 11:46:54 -05:00
Doug Russell 4eebdb82c4 Support for notifications on some updater events 2012-10-18 14:39:59 -07:00
Doug Russell 066d634ef6 Fix warnings 2012-10-18 12:20:08 -07:00
Jamie Pinkham 9e2e489109 fixed the Debug App Store configuration.. it was misnamed and causing a build error. 2012-10-18 11:07:42 -04:00
Jamie Pinkham f9c428ee06 fixing up the xcode configs to match ours for simpler building 2012-10-17 13:08:24 -04:00
Andy Matuschak 595c6ce491 Merge branch 'master' into quiet-automatic-update 2012-04-28 20:38:42 -07:00
Andy Matuschak 12904a5af6 Merge pull request #160 from mattstevens/manual-check-fix
Fix manual update checks when an automatic update is pending
2012-03-02 21:08:09 -08:00
Matt Stevens 7fc9e32ce7 Allow manual checks when an install on quit update is pending 2012-03-01 22:41:49 -07:00
Andy Matuschak 409e7e22bf Merge remote-tracking branch 'mattstevens/delegate-auto-update' into quiet-automatic-update 2012-02-29 09:45:08 -08:00
Andy Matuschak ed456740b0 Merge branch 'master' into quiet-automatic-update 2012-02-29 09:45:01 -08:00
Matt Stevens cdfcd1469e Allow the delegate to trigger a silent install and relaunch 2012-02-28 19:53:52 -07:00
Andy Matuschak 4c54349c23 Merge branch 'master' into quiet-automatic-update 2012-02-24 08:57:23 -08:00
Matt Stevens 833081ffa9 Support silent relaunches 2012-02-16 00:42:40 -07:00
Andy Matuschak faed494d4e Merge branch 'quiet-automatic-update' of github.com:andymatuschak/Sparkle into quiet-automatic-update 2012-02-15 22:38:23 -08:00
Andy Matuschak dbebe4b3b2 Merge branch 'master' into quiet-automatic-update 2012-02-15 22:38:01 -08:00
Andy Matuschak 320b3aa62a Merge pull request #148 from mattstevens/silent-update-fixes
Silent update fixes
2012-02-14 09:45:01 -08:00
Matt Stevens 1d8adc8fac Increment the sudden termination counter if installing on quit 2012-02-12 21:15:57 -07:00
Matt Stevens bc458a6ab5 Set up install on quit for critical automatic updates too
Fixes the SUInstallLaterChoice for critical update prompts.
2012-02-12 21:15:57 -07:00
Andy Matuschak e6deed9c56 Merge branch 'master' into quiet-automatic-update 2011-11-18 19:17:37 -08:00
Uli Kusterer 6a48420e07 Switch off secure updates for now 2011-11-12 15:03:46 +01:00
Uli Kusterer 59f9236009 Merge remote-tracking branch 'andymatuschak/master'
Conflicts:
	pt_PT.lproj/SUAutomaticUpdateAlert.xib
2011-11-12 13:39:34 +01:00
Andy Matuschak 716bb30e7c Merge branch 'master' into quiet-automatic-update 2011-11-09 21:23:18 -08:00
Uli Kusterer 02e090c291 Quick hack to make this build again. Should probably just move to Sparkle mainline, now that they're halfway current. 2011-10-15 12:02:18 +02:00
Uli Kusterer f6a2e76685 Merge branch 'master' of git://github.com/andymatuschak/Sparkle
Conflicts:
	Sparkle.xcodeproj/project.pbxproj
	pt.lproj/SUAutomaticUpdateAlert.xib
	pt_PT.lproj/SUAutomaticUpdateAlert.xib
	tr.lproj/SUAutomaticUpdateAlert.xib
2011-10-11 10:19:30 +02:00
Andy Matuschak 8f5b9f03ac Updating Sparkle.strings for the new, more strongly worded strings that are displayed for a 'critical update' 2011-10-10 22:49:49 -07:00
Andy Matuschak bb682da743 Prompts the user to update after a week (rather than a day) if he doesn't quit the app. 2011-10-10 22:44:17 -07:00
Andy Matuschak bf38b0c9fd Adding <sparkle:tags> appcast item element, <sparkle:criticalUpdate /> tag
You would use this like:
<item>
    <title>My great update</title>
    ...
    <sparkle:tags>
        <sparkle:criticalUpdate />
    </sparkle:tags>
</item>

The behavior of this tag presently is: rather than waiting for the user to quit the app (or for some large amount of time to pass), the user will be prompted to install the update (with a stronger message) immediately upon its receipt. This behavior could be improved for the manual update case as well.

We can also use this new mechanism to create special behavior for e.g. paid updates.
2011-10-10 22:40:27 -07:00
Andy Matuschak e64516c089 Fixed a no-autorelease-pool leak. 2011-10-10 22:40:24 -07:00
Andy Matuschak b515c15f9b We have this check box that says "Automatically download and install updates in the future." But we only download them automatically. We still ask permission again before installing them.
With this patch, we make good on the description of that box: updates are automatically installed when the app is quit. No user intervention involved whatsoever if they checked that box.

If the user doesn't quit the app for a day after the update is downloaded, we'll show the dialog we've always used for automatically downloaded updates (Install Now / Install on Quit / Skip This Update).
2011-10-04 20:48:28 -07:00
Uli Kusterer 0bd27c0cb7 Satisfy some overly picky compilers. 2011-08-08 04:34:45 +02:00
Uli Kusterer abda56d047 Make this build on 10.7. Might break building on earlier OSes. 2011-07-31 20:04:35 +02:00
Andy Matuschak 96272fce7d Removed the pt_PT localization from Uli's branch, since it was largely untranslated, and used the one from master instead. 2011-05-10 17:28:45 +02:00
Andy Matuschak dc925712dc Fixed layout of localization XIBs 2011-05-10 17:24:27 +02:00
Andy Kim 5fe0a7cb59 Merge branch 'master' of git://github.com/andymatuschak/Sparkle 2010-11-25 02:22:37 -08:00
Andy Kim 315cbaab1b Merge branch 'master' of git://github.com/andymatuschak/Sparkle
Conflicts:
	en.lproj/Sparkle.strings
2009-09-29 18:33:44 -07:00
Andy Matuschak c747ffc35b Fixed Bug #428216: "Update alert does not use a proper emdash" 2009-09-19 16:55:16 -04:00
295 changed files with 32460 additions and 21283 deletions

No files matched your search

+1
View File
@@ -16,3 +16,4 @@ profile
## Ignore incredibly annoying .DS_Store files
.DS_Store
DerivedData/
@@ -2,7 +2,3 @@
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
@@ -2,4 +2,3 @@
#include "ConfigCommonDebug.xcconfig"
#include "ConfigBinaryDelta.xcconfig"
OTHER_CFLAGS = -DDEBUG
+6 -29
View File
@@ -1,52 +1,29 @@
// Common
PREBINDING = NO
ZERO_LINK = NO
CURRENT_PROJECT_VERSION = 1.5
SDKROOT = macosx10.9
MACOSX_DEPLOYMENT_TARGET[arch=ppc] = 10.4
MACOSX_DEPLOYMENT_TARGET[arch=ppc64] = 10.5
MACOSX_DEPLOYMENT_TARGET[arch=i386] = 10.4
MACOSX_DEPLOYMENT_TARGET[arch=x86_64] = 10.7
GCC_C_LANGUAGE_STANDARD = c99
GCC_ENABLE_OBJC_EXCEPTIONS = YES
GCC_DEBUGGING_SYMBOLS = full
FINISH_INSTALL_TOOL_NAME = Autoupdate
CURRENT_PROJECT_VERSION = 1.6
GCC_PRECOMPILE_PREFIX_HEADER = YES
GCC_PREFIX_HEADER = $(SDKROOT)/System/Library/Frameworks/Cocoa.framework/Headers/Cocoa.h
GCC_FAST_OBJC_DISPATCH = YES
GCC_ENABLE_PASCAL_STRINGS = NO
GCC_VERSION = com.apple.compilers.llvm.clang.1_0
CLANG_LINK_OBJC_RUNTIME = NO
ARCHS = i386 x86_64
GCC_PREPROCESSOR_DEFINITIONS = FINISH_INSTALL_TOOL_NAME=$(FINISH_INSTALL_TOOL_NAME)
// Enable warnings
GCC_WARN_CHECK_SWITCH_STATEMENTS = YES
GCC_WARN_EFFECTIVE_CPLUSPLUS_VIOLATIONS = YES
GCC_WARN_FOUR_CHARACTER_CONSTANTS = YES
GCC_WARN_SHADOW = YES
GCC_WARN_64_TO_32_BIT_CONVERSION = YES
GCC_WARN_ALLOW_INCOMPLETE_PROTOCOL = YES
GCC_WARN_INITIALIZER_NOT_FULLY_BRACKETED = YES
GCC_WARN_ABOUT_RETURN_TYPE = YES
GCC_WARN_MISSING_PARENTHESES = YES
GCC_WARN_ABOUT_MISSING_NEWLINE = YES
GCC_WARN_NON_VIRTUAL_DESTRUCTOR = YES
GCC_WARN_HIDDEN_VIRTUAL_FUNCTIONS = YES
GCC_WARN_ABOUT_POINTER_SIGNEDNESS = YES
GCC_WARN_SIGN_COMPARE = YES
GCC_WARN_TYPECHECK_CALLS_TO_PRINTF = YES
GCC_WARN_UNKNOWN_PRAGMAS = YES
GCC_WARN_UNUSED_VARIABLE = YES
GCC_WARN_ABOUT_DEPRECATED_FUNCTIONS = YES
GCC_WARN_ABOUT_INVALID_OFFSETOF_MACRO = YES
GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES
GCC_WARN_HIDDEN_VIRTUAL_FUNCTIONS = YES
GCC_WARN_ABOUT_INVALID_OFFSETOF_MACRO = YES
GCC_WARN_UNUSED_FUNCTION = YES
GCC_WARN_UNUSED_LABEL = YES
GCC_WARN_UNUSED_VALUE = YES
GCC_WARN_UNUSED_PARAMETER = YES
GCC_WARN_ABOUT_MISSING_FIELD_INITIALIZERS = YES
GCC_WARN_UNDECLARED_SELECTOR = YES
COMMON_WARNING_FLAGS = -Wall -Wno-unused-parameter -Wundef -Wendif-labels -Wpointer-arith -Wcast-align -Wwrite-strings -Wmissing-format-attribute -Wpacked -Wredundant-decls -Winline -Wdisabled-optimization -Winvalid-pch
WARNING_CFLAGS = $(COMMON_WARNING_FLAGS)
@@ -3,9 +3,6 @@
GCC_OPTIMIZATION_LEVEL = 0
DEBUG_INFORMATION_FORMAT = dwarf
GCC_GENERATE_DEBUGGING_SYMBOLS = YES
SPARKLE_EXTRA_DEBUG_10_5_ONLY = -fstack-protector -D_FORTIFY_SOURCE=2
SPARKLE_EXTRA_DEBUG = -DDEBUG
OTHER_CFLAGS = $(SPARKLE_EXTRA_DEBUG)
CODE_SIGN_IDENTITY = Mac Developer
// Add $(SPARKLE_EXTRA_DEBUG_10_5_ONLY) to SPARKLE_EXTRA_DEBUG if your deployment is 10.5 or greater.
@@ -1,4 +0,0 @@
// Common
ARCHS = x86_64
VALID_ARCHS = x86_64
@@ -1,4 +0,0 @@
// Common
ARCHS = ppc i386 x86_64
+2 -3
View File
@@ -2,8 +2,7 @@
GCC_OPTIMIZATION_LEVEL = s
DEBUG_INFORMATION_FORMAT = dwarf-with-dsym
GCC_GENERATE_DEBUGGING_SYMBOLS = NO
DEAD_CODE_STRIPPING = YES
GCC_TREAT_WARNINGS_AS_ERRORS = YES
GCC_TREAT_WARNINGS_AS_ERRORS = NO
GCC_WARN_UNINITIALIZED_AUTOS = YES
WARNING_CFLAGS = $(COMMON_WARNING_FLAGS) -Wno-deprecated-declarations
CODE_SIGN_IDENTITY = Developer ID Application
+3 -3
View File
@@ -1,8 +1,8 @@
// Framework only
INSTALL_PATH = @rpath
DYLIB_COMPATIBILITY_VERSION = 2.0
DYLIB_CURRENT_VERSION = 2.1.1
INSTALL_PATH = @loader_path/../Frameworks
DYLIB_COMPATIBILITY_VERSION = 1.5
DYLIB_CURRENT_VERSION = 1.5
PRODUCT_NAME = Sparkle
WRAPPER_EXTENSION = framework
FRAMEWORK_VERSION = A
@@ -2,4 +2,3 @@
#include "ConfigCommonDebug.xcconfig"
#include "ConfigFramework.xcconfig"
OTHER_CFLAGS = -DDEBUG
@@ -4,6 +4,3 @@
STRIP_INSTALLED_PRODUCT = YES
DEPLOYMENT_POSTPROCESSING = YES
STRIPFLAGS = -u -r
STRIP_STYLE = non-global
SEPARATE_STRIP = YES
@@ -1,3 +0,0 @@
#include "ConfigFrameworkRelease.xcconfig"
GCC_ENABLE_OBJC_GC = supported
+1 -1
View File
@@ -1,4 +1,4 @@
// Relaunch Tool only
PRODUCT_NAME = finish_installation
PRODUCT_NAME = $(FINISH_INSTALL_TOOL_NAME)
SKIP_INSTALL = YES
@@ -1,5 +1,3 @@
#include "ConfigCommon.xcconfig"
#include "ConfigCommonDebug.xcconfig"
#include "ConfigRelaunch.xcconfig"
OTHER_CFLAGS = -DDEBUG
-10
View File
@@ -1,10 +0,0 @@
// Sandbox Service only
WRAPPER_EXTENSION = xpc
MACH_O_TYPE = mh_execute
MACOSX_DEPLOYMENT_TARGET = 10.7
MACOSX_DEPLOYMENT_TARGET[arch=x86_64] = 10.7
GCC_WARN_SHADOW = NO
GCC_WARN_ABOUT_DEPRECATED_FUNCTIONS = NO
GCC_WARN_ABOUT_MISSING_FIELD_INITIALIZERS = NO
@@ -1,5 +0,0 @@
#include "ConfigCommon.xcconfig"
#include "ConfigCommonDebug.xcconfig"
#include "ConfigService.xcconfig"
OTHER_CFLAGS = -DDEBUG
@@ -1,3 +0,0 @@
#include "ConfigCommon.xcconfig"
#include "ConfigCommonRelease.xcconfig"
#include "ConfigService.xcconfig"
-1
View File
@@ -3,4 +3,3 @@
INFOPLIST_FILE = Test Application/Test Application-Info.plist
PRODUCT_NAME = Sparkle Test App
WRAPPER_EXTENSION = app
LD_RUNPATH_SEARCH_PATHS = @loader_path/../Frameworks
@@ -2,4 +2,3 @@
#include "ConfigCommonDebug.xcconfig"
#include "ConfigTestApp.xcconfig"
OTHER_CFLAGS = -DDEBUG
@@ -1,3 +0,0 @@
#include "ConfigTestAppRelease.xcconfig"
GCC_ENABLE_OBJC_GC = required
-2
View File
@@ -7,5 +7,3 @@ WRAPPER_EXTENSION = octest
FRAMEWORK_SEARCH_PATHS = $(DEVELOPER_LIBRARY_DIR)/Frameworks
GCC_PREFIX_HEADER = $(SYSTEM_LIBRARY_DIR)/Frameworks/Cocoa.framework/Headers/Cocoa.h
GCC_PRECOMPILE_PREFIX_HEADER = YES
SDKROOT = macosx10.7
MACOSX_DEPLOYMENT_TARGET = 10.7
@@ -1,3 +0,0 @@
#include "ConfigUnitTestRelease.xcconfig"
GCC_ENABLE_OBJC_GC = required
-38
View File
@@ -1,38 +0,0 @@
//
// DevMateSparkle.h
// Sparkle
//
// Created by Dmytro Tretiakov on 10/1/14.
//
//
#ifndef Sparkle_DevMateSparkle_h
#define Sparkle_DevMateSparkle_h
#import <Cocoa/Cocoa.h>
// If you are using your own copy of Sparkle.framework just define
// USED_CUSTOM_SPARKLE_FRAMEWORK macro.
#ifndef USED_CUSTOM_SPARKLE_FRAMEWORK
#define SUUpdater DM_SUUpdater
#define SUUpdaterQueue DM_SUUpdaterQueue
#define SUAppcast DM_SUAppcast
#define SUAppcastItem DM_SUAppcastItem
#define SUAppcastDelegate DM_SUAppcastDelegate
#define SUUpdaterDelegate_DevMateInteraction DM_SUUpdaterDelegate_DevMateInteraction
#define SUUpdaterDelegateInformalProtocol DM_SUUpdaterDelegateInformalProtocol
#define SUVersionComparison DM_SUVersionComparison
#define SUVersionDisplay DM_SUVersionDisplay
#import <DevMateSparkle/SUUpdater.h>
#import <DevMateSparkle/SUUpdaterQueue.h>
#import <DevMateSparkle/SUAppcast.h>
#import <DevMateSparkle/SUAppcastItem.h>
#import <DevMateSparkle/SUVersionComparisonProtocol.h>
#import <DevMateSparkle/SUVersionDisplayProtocol.h>
#endif // USED_CUSTOM_SPARKLE_FRAMEWORK
#endif // Sparkle_DevMateSparkle_h
-54
View File
@@ -1,54 +0,0 @@
//
// DevMateSparkle.pch
// Sparkle
//
// Created by Dmytro Tretiakov on 10/1/14.
//
//
#define SPARKLE_MAIN_CLASS @"DM_SUUpdater"
#define SUUpdater DM_SUUpdater
#define SUUpdaterQueue DM_SUUpdaterQueue
#define SUAppcast DM_SUAppcast
#define SUAppcastItem DM_SUAppcastItem
#define SUAppcastDelegate DM_SUAppcastDelegate
#define SUUpdaterDelegate_DevMateInteraction DM_SUUpdaterDelegate_DevMateInteraction
#define SUUpdaterDelegateInformalProtocol DM_SUUpdaterDelegateInformalProtocol
#define SUVersionComparison DM_SUVersionComparison
#define SUVersionDisplay DM_SUVersionDisplay
#define SUPackageInstaller DM_SUPackageInstaller
#define SUDSAVerifier DM_SUDSAVerifier
#define SUUpdateAlert DM_SUUpdateAlert
#define SUUIBasedUpdateDriver DM_SUUIBasedUpdateDriver
#define SUPasswordPrompt DM_SUPasswordPrompt
#define SUStandardVersionComparator DM_SUStandardVersionComparator
#define SUSystemProfiler DM_SUSystemProfiler
#define SUXPCInstaller DM_SUXPCInstaller
#define SUXPCURLDownload DM_SUXPCURLDownload
#define SUPlainInstaller DM_SUPlainInstaller
#define SUUpdatePermissionPrompt DM_SUUpdatePermissionPrompt
#define SUUnarchiver DM_SUUnarchiver
#define SUUserInitiatedUpdateDriver DM_SUUserInitiatedUpdateDriver
#define SUUpdateDriver DM_SUUpdateDriver
#define SUProbingUpdateDriver DM_SUProbingUpdateDriver
#define SUAutomaticUpdateAlert DM_SUAutomaticUpdateAlert
#define SUBasicUpdateDriver DM_SUBasicUpdateDriver
#define SUWindowController DM_SUWindowController
#define SUStatusController DM_SUStatusController
#define SUHost DM_SUHost
#define SUPipedUnarchiver DM_SUPipedUnarchiver
#define SUAutomaticUpdateDriver DM_SUAutomaticUpdateDriver
#define SUCodeSigningVerifier DM_SUCodeSigningVerifier
#define SUBinaryDeltaUnarchiver DM_SUBinaryDeltaUnarchiver
#define SUDelegateProxy DM_SUDelegateProxy
#define SUInstaller DM_SUInstaller
#define SUScheduledUpdateDriver DM_SUScheduledUpdateDriver
#define SUDiskImageUnarchiver DM_SUDiskImageUnarchiver
#define NTSynchronousTask DM_NTSynchronousTask
#define SUUpdaterWorking DM_SUUpdater // Used in SUUpdaterLoader.m file
#define SUUpdaterLoader DM_SUUpdaterLoader
#import "Sparkle.pch"
@@ -1,31 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>English</string>
<key>CFBundleExecutable</key>
<string>${EXECUTABLE_NAME}</string>
<key>CFBundleIdentifier</key>
<string>${EXECUTABLE_NAME}</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundlePackageType</key>
<string>XPC!</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>XPCService</key>
<dict>
<key>ServiceType</key>
<string>Application</string>
<key>JoinExistingSession</key>
<true/>
</dict>
</dict>
</plist>
@@ -1,4 +0,0 @@
//
// Prefix header for all source files of the 'Downloading XPC Service' target in the 'Downloading XPC Service' project
//
-60
View File
@@ -1,60 +0,0 @@
//
// SUDSDownloader.h
// Sparkle
//
// Created by Dmytro Tretiakov on 8/1/13.
//
//
#import <Foundation/Foundation.h>
#define DEBUG_LOGGING_ENABLED defined(DEBUG) && 1
@class SUDSDownloader;
typedef void (^SUDSDownloadDidBegin)(SUDSDownloader *downloader);
typedef void (^SUDSDownloadDidFinish)(SUDSDownloader *downloader);
typedef void (^SUDSDownloadDidFail)(SUDSDownloader *downloader, NSError *error);
typedef void (^SUDSDownloadDidReceiveResponse)(SUDSDownloader *downloader, NSURLResponse *response);
typedef void (^SUDSDownloadDidReceiveData)(SUDSDownloader *downloader, NSUInteger dataLength);
typedef void (^SUDSDownloadDidCreateDestination)(SUDSDownloader *downloader, NSString *destinationPath);
typedef BOOL (^SUDSDownloadShouldDecodeSourceData)(SUDSDownloader *downloader, NSString *MIMEType);
typedef struct SUDSDownloaderCallBacks
{
SUDSDownloadDidBegin downloadDidBegin;
SUDSDownloadDidFinish downloadDidFinish;
SUDSDownloadDidFail downloadDidFail;
SUDSDownloadDidReceiveResponse downloadDidReceiveResponse;
SUDSDownloadDidReceiveData downloadDidReceiveData;
SUDSDownloadDidCreateDestination downloadDidCreateDestination;
SUDSDownloadShouldDecodeSourceData downloadShouldDecodeSourceData;
} SUDSDownloaderCallBacks;
FOUNDATION_EXTERN SUDSDownloaderCallBacks SUDSCopyDownloaderCallBacks(SUDSDownloaderCallBacks callBacks);
FOUNDATION_EXTERN void SUDSReleaseDownloaderCallBacks(SUDSDownloaderCallBacks callBacks);
@interface SUDSDownloader : NSObject <NSURLDownloadDelegate>
{
@private
NSURLRequest *_request;
NSString *_destFilePath;
SUDSDownloaderCallBacks _callBacks;
NSURLDownload *_download;
}
- (id)initWithURLRequest:(NSURLRequest *)request destinationPath:(NSString *)filePath;
+ (id)downloaderWithURLRequest:(NSURLRequest *)request destinationPath:(NSString *)filePath;
- (NSURLRequest *)request;
- (NSString *)destinationPath;
- (void)setCallBacks:(SUDSDownloaderCallBacks)callBacks;
- (void)startDownload;
- (void)stopDownload;
- (BOOL)isInProgress;
@end
-210
View File
@@ -1,210 +0,0 @@
//
// SUDSDownloader.m
// Sparkle
//
// Created by Dmytro Tretiakov on 8/1/13.
//
//
#import "SUDSDownloader.h"
SUDSDownloaderCallBacks SUDSCopyDownloaderCallBacks(SUDSDownloaderCallBacks callBacks)
{
SUDSDownloaderCallBacks callBacksCopy = {0};
if (callBacks.downloadDidBegin)
callBacksCopy.downloadDidBegin = Block_copy(callBacks.downloadDidBegin);
if (callBacks.downloadDidFinish)
callBacksCopy.downloadDidFinish = Block_copy(callBacks.downloadDidFinish);
if (callBacks.downloadDidFail)
callBacksCopy.downloadDidFail = Block_copy(callBacks.downloadDidFail);
if (callBacks.downloadDidReceiveData)
callBacksCopy.downloadDidReceiveData = Block_copy(callBacks.downloadDidReceiveData);
if (callBacks.downloadDidCreateDestination)
callBacksCopy.downloadDidCreateDestination = Block_copy(callBacks.downloadDidCreateDestination);
if (callBacks.downloadDidReceiveResponse)
callBacksCopy.downloadDidReceiveResponse = Block_copy(callBacks.downloadDidReceiveResponse);
if (callBacks.downloadShouldDecodeSourceData)
callBacksCopy.downloadShouldDecodeSourceData = Block_copy(callBacks.downloadShouldDecodeSourceData);
return callBacksCopy;
}
void SUDSReleaseDownloaderCallBacks(SUDSDownloaderCallBacks callBacks)
{
if (callBacks.downloadDidBegin)
Block_release(callBacks.downloadDidBegin);
if (callBacks.downloadDidFinish)
Block_release(callBacks.downloadDidFinish);
if (callBacks.downloadDidFail)
Block_release(callBacks.downloadDidFail);
if (callBacks.downloadDidReceiveData)
Block_release(callBacks.downloadDidReceiveData);
if (callBacks.downloadDidCreateDestination)
Block_release(callBacks.downloadDidCreateDestination);
if (callBacks.downloadDidReceiveResponse)
Block_release(callBacks.downloadDidReceiveResponse);
if (callBacks.downloadShouldDecodeSourceData)
Block_release(callBacks.downloadShouldDecodeSourceData);
}
@implementation SUDSDownloader
- (id)initWithURLRequest:(NSURLRequest *)request destinationPath:(NSString *)filePath
{
self = [super init];
if (self != nil)
{
_request = [request retain];
_destFilePath = [filePath copy];
}
return self;
}
+ (id)downloaderWithURLRequest:(NSURLRequest *)request destinationPath:(NSString *)filePath
{
return [[[[self class] alloc] initWithURLRequest:request destinationPath:filePath] autorelease];
}
- (void)dealloc
{
[self stopDownload];
[_request release];
[_destFilePath release];
SUDSReleaseDownloaderCallBacks(_callBacks);
[super dealloc];
}
- (NSURLRequest *)request
{
return _request;
}
- (NSString *)destinationPath
{
return _destFilePath;
}
- (void)setCallBacks:(SUDSDownloaderCallBacks)callBacks
{
SUDSDownloaderCallBacks oldCallBacks = _callBacks;
_callBacks = SUDSCopyDownloaderCallBacks(callBacks);
SUDSReleaseDownloaderCallBacks(oldCallBacks);
}
- (void)startDownload
{
[self stopDownload];
// to ensure that parent folder exists
[[NSFileManager defaultManager] createDirectoryAtPath:[_destFilePath stringByDeletingLastPathComponent]
withIntermediateDirectories:YES
attributes:nil
error:NULL];
NSURLDownload *urlDownload = [[NSURLDownload alloc] initWithRequest:_request delegate:self];
@synchronized (self)
{
_download = urlDownload;
}
[urlDownload setDestination:_destFilePath allowOverwrite:YES];
}
- (void)stopDownload
{
@synchronized (self)
{
[_download cancel];
[_download release];
_download = nil;
}
}
- (BOOL)isInProgress
{
BOOL result = YES;
@synchronized (self)
{
result = _download != nil;
}
return result;
}
#pragma mark -
- (void)downloadDidBegin:(NSURLDownload *)download
{
#if DEBUG_LOGGING_ENABLED
NSLog(@"XPC Downloader did begin process.");
#endif
if (_callBacks.downloadDidBegin)
_callBacks.downloadDidBegin(self);
}
- (void)download:(NSURLDownload *)download didReceiveResponse:(NSURLResponse *)response
{
#if DEBUG_LOGGING_ENABLED
NSLog(@"XPC Downloader did receive response: %@", [response description]);
#endif
if (_callBacks.downloadDidReceiveResponse)
_callBacks.downloadDidReceiveResponse(self, response);
}
- (void)download:(NSURLDownload *)download didCreateDestination:(NSString *)path
{
#if DEBUG_LOGGING_ENABLED
NSLog(@"XPC Downloader did create destination: %@", path);
#endif
if (_callBacks.downloadDidCreateDestination)
_callBacks.downloadDidCreateDestination(self, path);
}
- (void)download:(NSURLDownload *)download didReceiveDataOfLength:(NSUInteger)length
{
#if DEBUG_LOGGING_ENABLED
NSLog(@"XPC Downloader did receive data of length %ld bytes", (unsigned long)length);
#endif
if (_callBacks.downloadDidReceiveData)
_callBacks.downloadDidReceiveData(self, length);
}
- (void)download:(NSURLDownload *)download didFailWithError:(NSError *)error
{
#if DEBUG_LOGGING_ENABLED
NSLog(@"XPC Downloader did fail: %@", [error description]);
#endif
if (_callBacks.downloadDidFail)
_callBacks.downloadDidFail(self, error);
[self stopDownload];
}
- (void)downloadDidFinish:(NSURLDownload *)download
{
#if DEBUG_LOGGING_ENABLED
NSLog(@"XPC Downloader did finish");
#endif
if (_callBacks.downloadDidFinish)
_callBacks.downloadDidFinish(self);
[self stopDownload];
}
- (BOOL)download:(NSURLDownload *)download shouldDecodeSourceDataOfMIMEType:(NSString *)encodingType
{
BOOL shouldDecode = NO;
#if DEBUG_LOGGING_ENABLED
NSLog(@"XPC Downloader wants decode source data of MIME type: %@", encodingType);
#endif
if (_callBacks.downloadShouldDecodeSourceData)
shouldDecode = _callBacks.downloadShouldDecodeSourceData(self, encodingType);
return shouldDecode;
}
@end
@@ -1,29 +0,0 @@
//
// SUDownloadServiceConstants.h
// Sparkle
//
// Created by Dmytro Tretiakov on 7/29/13.
//
//
#ifndef Sparkle_SUDownloadServiceConstants_h
#define Sparkle_SUDownloadServiceConstants_h
const char * SUDownloadServiceURLRequestDataKey = "request_data"; // data of archived NSURLRequest
const char * SUDownloadServiceDelegateConnectionKey = "connection"; // xpc_connection_t
const char * SUDownloadServiceFilePathKey = "file_path"; // c-string
const char * SUDownloadServiceReceivedDataLengthKey = "received_data_length"; // int64_t
const char * SUDownloadServiceReceivedResponseDataKey = "received_response_data"; // data of archived NSURLResponse
const char * SUDownloadServiceCreatedDestinationPathKey = "created_destination_path"; // c-string
const char * SUDownloadServiceDidBeginDownloadingKey = "did_begin_downloading"; // bool 1
const char * SUDownloadServiceDidFinishDownloadingKey = "did_finish_downloading"; // bool 1
const char * SUDownloadServiceReceivedFailErrorKey = "received_fail_error"; // data of archived NSError
const char * SUDownloadServiceMIMETypeToDecodeKey = "MIME_type_to_decode"; // c-string
const char * SUDownloadServiceShouldDecodeMIMETypeKey = "should_decode_MIME_type"; // bool
const char * SUDownloadServiceErrorCodeKey = "errcode"; // int64_t
const char * SUDownloadServiceErrorMessageKey = "errmsg"; // c-string
const char * SUDownloadServiceErrorDomainKey = "errdomain"; // c-string
#endif
@@ -1,36 +0,0 @@
//
// SUXPCURLDownload.h
// Sparkle
//
// Created by Erik Aderstedt on 2012-08-09.
//
//
#import <Foundation/Foundation.h>
@interface SUXPCURLDownload : NSObject
{
@private
id <NSURLDownloadDelegate> _delegate; // weak ref
xpc_connection_t _connection;
xpc_connection_t _delegateConnection;
NSURLRequest *_request;
NSThread *_startedThread; // weak ref
BOOL _isDownloading;
BOOL _allowOverwrite;
NSString *_destination;
NSString *_connectionDestination;
NSError *_downloadError;
}
- (id <NSURLDownloadDelegate>)delegate;
- (void)setDelegate:(id <NSURLDownloadDelegate>)delegate;
- (id)initWithRequest:(NSURLRequest *)request delegate:(id <NSURLDownloadDelegate>)delegate;
- (void)setDestination:(NSString *)path allowOverwrite:(BOOL)allowOverwrite;
// Delegate methods for this method will be called from another thread.
+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request delegate:(id <NSURLDownloadDelegate>)delegate;
@end
-448
View File
@@ -1,448 +0,0 @@
//
// SUXPCURLDownload.m
// Sparkle
//
// Created by Erik Aderstedt on 2012-08-09.
//
//
#import "SUXPCURLDownload.h"
#import "SUDownloadServiceConstants.h"
#import "SUConstants.h"
#import "SULog.h"
static NSString * const kSUFetchFolderName = @"fetch.XXXXXXXX";
@interface SUXPCURLDownload (Private)
- (void)performBlock:(void (^)(void))block onThread:(NSThread *)thread synchronous:(BOOL)flag;
- (void)fireBlock:(void (^)(void))block;
@end
@implementation SUXPCURLDownload
+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request delegate:(id <NSURLDownloadDelegate>)delegate
{
__block SUXPCURLDownload *download = nil;
static const char *sSynchronousDownloadQueueName = "com.devmate.SynchronousXPCDownloadQueue";
dispatch_queue_t queue = dispatch_queue_create(sSynchronousDownloadQueueName, NULL);
dispatch_sync(queue, ^{
download = [[SUXPCURLDownload alloc] initWithRequest:request delegate:delegate];
});
while (download && download->_isDownloading)
{
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.5]];
}
NSData *downloadData = (nil == download->_downloadError) ? [NSData dataWithContentsOfFile:download->_destination] : nil;
[download release];
dispatch_release(queue);
return downloadData;
}
- (id)initWithRequest:(NSURLRequest *)request delegate:(id <NSURLDownloadDelegate>)delegate
{
self = [super init];
if (self != nil)
{
_request = [request retain];
_delegate = [delegate retain];
_startedThread = [NSThread currentThread];
// Set up a connection.
_connection = [self getSandboxXPCService];
dispatch_async(dispatch_get_current_queue(), ^{
[self startDownload:request];
});
_isDownloading = YES;
}
return self;
}
- (void)dealloc
{
[self cancel];
[_request release];
[_destination release];
[_connectionDestination release];
[_downloadError release];
[super dealloc];
}
- (NSURLRequest *)request
{
return _request;
}
- (void)startDownload:(NSURLRequest *)urlRequest
{
// Send a message to download a specific url.
if ([_delegate respondsToSelector:@selector(download:decideDestinationWithSuggestedFilename:)] && _destination == nil)
{
void (^block)(void) = ^{
[_delegate download:(NSURLDownload *)self decideDestinationWithSuggestedFilename:[[urlRequest URL] lastPathComponent]];
};
[self performBlock:block onThread:_startedThread synchronous:YES];
}
if (nil == _destination)
{
_destination = [[[urlRequest URL] lastPathComponent] copy];
}
// ivar 'destination' now contains the destination URL.
NSURL *tempFolder = [NSURL fileURLWithPath:NSTemporaryDirectory()];
NSString *tempFileTemplate = [[tempFolder URLByAppendingPathComponent:kSUFetchFolderName] path];
NSString *tempFilePath = [tempFileTemplate stringByAppendingPathComponent:[_destination lastPathComponent]];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:tempFilePath])
[fileManager removeItemAtPath:tempFilePath error:nil];
_connectionDestination = [tempFilePath copy];
NSData *requestData = [NSKeyedArchiver archivedDataWithRootObject:urlRequest];
xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0);
xpc_dictionary_set_data(message, SUDownloadServiceURLRequestDataKey, [requestData bytes], [requestData length]);
xpc_dictionary_set_string(message, SUDownloadServiceFilePathKey, [tempFilePath cStringUsingEncoding:NSUTF8StringEncoding]);
xpc_dictionary_set_connection(message, SUDownloadServiceDelegateConnectionKey, _delegateConnection);
xpc_connection_send_message_with_reply(_connection, message, dispatch_get_main_queue(), ^(xpc_object_t object) {
xpc_type_t type = xpc_get_type(object);
if (type == XPC_TYPE_ERROR && nil == _downloadError)
{
NSString *errMessage = @"";
if (object == XPC_ERROR_CONNECTION_INTERRUPTED)
{
errMessage = @"Got XPC_ERROR_CONNECTION_INTERRUPTED error.";
}
else if (object == XPC_ERROR_CONNECTION_INVALID)
{
errMessage = @"Got XPC_ERROR_CONNECTION_INVALID error.";
}
NSDictionary *errInfo = [NSDictionary dictionaryWithObject:errMessage forKey:NSLocalizedDescriptionKey];
_downloadError = [[NSError alloc] initWithDomain:SUSparkleErrorDomain code:SUXPCServiceError userInfo:errInfo];
}
else if (type == XPC_TYPE_DICTIONARY && noErr != xpc_dictionary_get_int64(object, SUDownloadServiceErrorCodeKey) && nil == _downloadError)
{
NSInteger errCode = (NSInteger)xpc_dictionary_get_int64(object, SUDownloadServiceErrorCodeKey);
const char *errDomainStr = xpc_dictionary_get_string(object, SUDownloadServiceErrorDomainKey);
NSString *errDomain = errDomainStr ? [NSString stringWithUTF8String:errDomainStr] : NSCocoaErrorDomain;
const char *errMessage = xpc_dictionary_get_string(object, SUDownloadServiceErrorMessageKey) ? : "";
NSDictionary *errInfo = [NSDictionary dictionaryWithObject:[NSString stringWithUTF8String:errMessage]
forKey:NSLocalizedDescriptionKey];
_downloadError = [[NSError alloc] initWithDomain:errDomain code:errCode userInfo:errInfo];
}
if (nil != _downloadError)
{
if ([_delegate respondsToSelector:@selector(download:didFailWithError:)])
{
void (^block)(void) = ^{
[_delegate download:(NSURLDownload *)self didFailWithError:_downloadError];
_isDownloading = NO;
};
[self performBlock:block onThread:_startedThread synchronous:NO];
}
else
{
SULog(@"SUXPCURLDownload: got download error (%d - %@)", [_downloadError code], [_downloadError localizedDescription]);
_isDownloading = NO;
}
}
});
xpc_release(message);
}
- (id <NSURLDownloadDelegate>)delegate
{
return _delegate;
}
- (void)setDelegate:(id <NSURLDownloadDelegate>)delegate
{
_delegate = delegate;
}
- (void)setDestination:(NSString *)path allowOverwrite:(BOOL)allowOverwrite
{
[_destination release];
_destination = [path copy];
_allowOverwrite = allowOverwrite;
}
- (void)cancel
{
if (_connection)
{
xpc_connection_cancel(_connection);
xpc_release(_connection);
_connection = NULL;
}
if (_delegateConnection)
{
xpc_connection_cancel(_delegateConnection);
xpc_release(_delegateConnection);
_delegateConnection = NULL;
}
}
- (xpc_connection_t)getSandboxXPCService
{
// Set up two connections, one for instructing the XPC and getting a response,
// and another to listen for incoming connections for progress and file creation
// notifications.
_connection = xpc_connection_create("com.devmate.UpdateDownloader", dispatch_get_main_queue());
if (!_connection)
{
NSLog(@"Can't connect to XPC service");
return (NULL);
}
xpc_connection_set_event_handler(_connection, ^(xpc_object_t event) {
xpc_type_t type = xpc_get_type(event);
if (type == XPC_TYPE_ERROR)
{
if (event == XPC_ERROR_CONNECTION_INTERRUPTED)
{
NSLog(@"Got XPC_ERROR_CONNECTION_INTERRUPTED error.");
// The service has either cancaled itself, crashed, or been
// terminated. The XPC connection is still valid and sending a
// message to it will re-launch the service. If the service is
// state-full, this is the time to initialize the new service.
}
else if (event == XPC_ERROR_CONNECTION_INVALID)
{
NSLog(@"Got XPC_ERROR_CONNECTION_INVALID error.");
// The service is invalid. Either the service name supplied to
// xpc_connection_create() is incorrect or we (this process) have
// canceled the service; we can do any cleanup of appliation
// state at this point.
if (_delegateConnection)
{
xpc_connection_cancel(_delegateConnection);
xpc_release(_delegateConnection);
_delegateConnection = NULL;
}
}
}
});
dispatch_queue_t delegate_queue = dispatch_queue_create("com.devmate.UpdateDownloader.delegate", NULL);
assert(delegate_queue != NULL);
_delegateConnection = xpc_connection_create(NULL, delegate_queue);
xpc_connection_set_event_handler(_delegateConnection, ^(xpc_object_t event) {
xpc_type_t type = xpc_get_type(event);
if (type == XPC_TYPE_ERROR)
{
if (event == XPC_ERROR_TERMINATION_IMMINENT)
{
NSLog(@"received XPC_ERROR_TERMINATION_IMMINENT");
}
else if (event == XPC_ERROR_CONNECTION_INVALID)
{
NSLog(@"progress connection is closed");
dispatch_release(delegate_queue);
}
}
else if (type == XPC_TYPE_CONNECTION)
{
xpc_connection_t peer = (xpc_connection_t)event;
// A new anonymous connection, from an XPC service that wants to supply us with updates.
char *queue_name = NULL;
dispatch_queue_t peer_event_queue = dispatch_queue_create(queue_name, NULL);
assert(peer_event_queue != NULL);
free(queue_name);
xpc_connection_set_target_queue(peer, peer_event_queue);
xpc_connection_set_event_handler(peer, ^(xpc_object_t nevent) {
xpc_type_t ntype = xpc_get_type(nevent);
if (ntype == XPC_TYPE_ERROR && nevent == XPC_ERROR_CONNECTION_INVALID)
dispatch_release(peer_event_queue);
if (ntype != XPC_TYPE_DICTIONARY)
return;
__block xpc_object_t answer = xpc_dictionary_create_reply(nevent);
xpc_dictionary_apply(nevent, ^bool(const char *key, xpc_object_t value) {
NSAutoreleasePool *localPool = [[NSAutoreleasePool alloc] init];
if (0 == strcmp(key, SUDownloadServiceDidBeginDownloadingKey))
{
if ([_delegate respondsToSelector:@selector(downloadDidBegin:)])
{
void (^block)(void) = ^ {
[_delegate downloadDidBegin:(NSURLDownload *)self];
};
[self performBlock:block onThread:_startedThread synchronous:NO];
}
}
else if (0 == strcmp(key, SUDownloadServiceReceivedResponseDataKey))
{
if ([_delegate respondsToSelector:@selector(download:didReceiveResponse:)])
{
size_t dataLength = 0;
const void * responseDataBytes = xpc_dictionary_get_data(nevent, SUDownloadServiceReceivedResponseDataKey, &dataLength);
NSData *responseData = [NSData dataWithBytes:responseDataBytes length:(NSUInteger)dataLength];
NSURLResponse *response = [NSKeyedUnarchiver unarchiveObjectWithData:responseData];
void (^block)(void) = ^ {
[_delegate download:(NSURLDownload *)self didReceiveResponse:response];
};
[self performBlock:block onThread:_startedThread synchronous:NO];
}
}
else if (0 == strcmp(key, SUDownloadServiceReceivedDataLengthKey))
{
if ([_delegate respondsToSelector:@selector(download:didReceiveDataOfLength:)])
{
int64_t dataLength = xpc_dictionary_get_int64(nevent, SUDownloadServiceReceivedDataLengthKey);
void (^block)(void) = ^ {
[_delegate download:(NSURLDownload *)self didReceiveDataOfLength:(NSUInteger)dataLength];
};
[self performBlock:block onThread:_startedThread synchronous:NO];
}
}
else if (0 == strcmp(key, SUDownloadServiceCreatedDestinationPathKey))
{
[_connectionDestination release];
_connectionDestination = [[NSString alloc] initWithCString:xpc_dictionary_get_string(nevent, SUDownloadServiceCreatedDestinationPathKey)
encoding:NSUTF8StringEncoding];
}
else if (0 == strcmp(key, SUDownloadServiceReceivedFailErrorKey))
{
size_t dataLength = 0;
const void * errorDataBytes = xpc_dictionary_get_data(nevent, SUDownloadServiceReceivedFailErrorKey, &dataLength);
NSData *errorData = [NSData dataWithBytes:errorDataBytes length:dataLength];
NSError *error = [NSKeyedUnarchiver unarchiveObjectWithData:errorData];
_downloadError = [error retain];
}
else if (0 == strcmp(key, SUDownloadServiceDidFinishDownloadingKey))
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *destPath = _destination;
if (nil == destPath || [destPath isEqualToString:[destPath lastPathComponent]])
{
destPath = _connectionDestination;
}
else if (!_allowOverwrite)
{
NSUInteger index = 1;
NSString *parentFolder = [destPath stringByDeletingLastPathComponent];
NSString *initialFileName = [[destPath lastPathComponent] stringByDeletingPathExtension];
NSString *fileExtension = [destPath pathExtension];
while ([fileManager fileExistsAtPath:destPath])
{
NSString *fileName = [initialFileName stringByAppendingFormat:@"_%ld", index];
destPath = [[parentFolder stringByAppendingPathComponent:fileName] stringByAppendingPathExtension:fileExtension];
++index;
}
}
NSError *error = nil;
BOOL success = YES;
if (![destPath isEqualToString:_connectionDestination])
{
success = success && [fileManager createDirectoryAtPath:[destPath stringByDeletingLastPathComponent]
withIntermediateDirectories:YES
attributes:nil
error:&error];
if (success && [fileManager fileExistsAtPath:destPath])
success = [fileManager removeItemAtPath:destPath error:&error];
success = success && [fileManager moveItemAtPath:_connectionDestination toPath:destPath error:&error];
}
if (success)
{
[self setDestination:destPath allowOverwrite:_allowOverwrite];
void (^block)(void) = ^ {
if ([_delegate respondsToSelector:@selector(download:didCreateDestination:)])
[_delegate download:(NSURLDownload *)self didCreateDestination:destPath];
if ([_delegate respondsToSelector:@selector(downloadDidFinish:)])
[_delegate downloadDidFinish:(NSURLDownload *)self];
_isDownloading = NO;
};
[self performBlock:block onThread:_startedThread synchronous:NO];
}
else
{
_downloadError = [error retain];
}
}
else if (0 == strcmp(key, SUDownloadServiceMIMETypeToDecodeKey))
{
void (^block)(void) = ^{
BOOL shouldDecode = NO;
if ([_delegate respondsToSelector:@selector(download:shouldDecodeSourceDataOfMIMEType:)])
{
NSString *MIMEType = [NSString stringWithCString:xpc_dictionary_get_string(nevent, SUDownloadServiceMIMETypeToDecodeKey)
encoding:NSUTF8StringEncoding];
shouldDecode = [_delegate download:(NSURLDownload *)self shouldDecodeSourceDataOfMIMEType:MIMEType];
}
xpc_dictionary_set_bool(answer, SUDownloadServiceShouldDecodeMIMETypeKey, YES);
};
[self performBlock:block onThread:_startedThread synchronous:YES];
}
[localPool release];
return true;
});
xpc_connection_send_message(peer, answer);
xpc_release(answer);
});
xpc_connection_resume(peer);
}
});
// Need to resume the service in order for it to process messages.
xpc_connection_resume(_delegateConnection);
xpc_connection_resume(_connection);
return _connection;
}
#pragma mark - Private
- (void)performBlock:(void (^)(void))block onThread:(NSThread *)thread synchronous:(BOOL)flag
{
void (^blockCopy)(void) = block != NULL ? Block_copy(block) : NULL;
[self performSelector:@selector(fireBlock:) onThread:thread withObject:blockCopy waitUntilDone:flag];
}
- (void)fireBlock:(void (^)(void))block
{
if (NULL == block)
return;
block();
Block_release(block);
}
@end
-265
View File
@@ -1,265 +0,0 @@
//
// main.m
// Downloading XPC Service
//
// Created by Erik Aderstedt on 2012-08-09.
// Based on the Apple sample code 'SandboxedFetch'.
//
#import <xpc/xpc.h>
#import <asl.h>
#import <assert.h>
#import <errno.h>
#import <stdio.h>
#import "SUDownloadServiceConstants.h"
#import "SUDSDownloader.h"
#import "SUConstants.h"
static void fetch_process_request(xpc_object_t request, xpc_object_t reply);
static void fetch_peer_event_handler(xpc_connection_t peer, xpc_object_t event);
static void fetch_event_handler(xpc_connection_t peer);
#pragma mark -
// Process the XPC request, create a temporary file to hold downloaded,
// data, and build/return XPC reply.
static void fetch_process_request(xpc_object_t request, xpc_object_t reply)
{
__block int32_t errcode = 0;
__block const char *errmsg = NULL;
__block const char *errdomain = NULL;
xpc_connection_t connection = NULL;
NSAutoreleasePool *localPool = [[NSAutoreleasePool alloc] init];
do
{
size_t dataLength = 0;
const void *data = xpc_dictionary_get_data(request, SUDownloadServiceURLRequestDataKey, &dataLength);
NSData *requestData = [NSData dataWithBytes:data length:dataLength];
NSURLRequest *urlRequest = [NSKeyedUnarchiver unarchiveObjectWithData:requestData];
if (nil == urlRequest)
{
errcode = SUXPCServiceError;
errdomain = [SUSparkleErrorDomain cStringUsingEncoding:NSUTF8StringEncoding];
errmsg = "Invalid URL request data";
break;
}
// Get the URL and XPC connection from the XPC request
connection = xpc_dictionary_create_connection(request, SUDownloadServiceDelegateConnectionKey);
if (connection == NULL)
{
errcode = SUXPCServiceError;
errdomain = [SUSparkleErrorDomain cStringUsingEncoding:NSUTF8StringEncoding];
errmsg = "Invalid XPC delegate connection";
break;
}
// Set up XPC connection endpoint for sending progress reports and receiving cancel notification.
__block BOOL shouldStopDownload = NO;
xpc_connection_set_event_handler(connection, ^(xpc_object_t event) {
xpc_type_t type = xpc_get_type(event);
// If the remote end of this connection has gone away then stop download
if (XPC_TYPE_ERROR == type &&
(XPC_ERROR_CONNECTION_INTERRUPTED == event || XPC_ERROR_CONNECTION_INVALID == event))
{
asl_log(NULL, NULL, ASL_LEVEL_NOTICE, "Stopping download process...\n");
shouldStopDownload = YES;
}
});
xpc_connection_resume(connection);
NSString *destinationPath = [NSString stringWithCString:xpc_dictionary_get_string(request, SUDownloadServiceFilePathKey)
encoding:NSUTF8StringEncoding];
SUDSDownloader *downloader = [SUDSDownloader downloaderWithURLRequest:urlRequest
destinationPath:destinationPath];
SUDSDownloaderCallBacks callBacks = {0};
callBacks.downloadDidReceiveData = ^(SUDSDownloader *downloader, NSUInteger dataLength) {
xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0);
xpc_dictionary_set_int64(message, SUDownloadServiceReceivedDataLengthKey, (int64_t)dataLength);
xpc_object_t answer = xpc_connection_send_message_with_reply_sync(connection, message);
xpc_release(message);
xpc_release(answer);
};
callBacks.downloadDidReceiveResponse = ^(SUDSDownloader *downloader, NSURLResponse *response) {
NSData *responseData = [NSKeyedArchiver archivedDataWithRootObject:response];
xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0);
xpc_dictionary_set_data(message, SUDownloadServiceReceivedResponseDataKey, [responseData bytes], [responseData length]);
xpc_object_t answer = xpc_connection_send_message_with_reply_sync(connection, message);
xpc_release(message);
xpc_release(answer);
};
callBacks.downloadDidCreateDestination = ^(SUDSDownloader *downloader, NSString *destinationPath) {
xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0);
xpc_dictionary_set_string(message, SUDownloadServiceCreatedDestinationPathKey, [destinationPath cStringUsingEncoding:NSUTF8StringEncoding]);
xpc_object_t answer = xpc_connection_send_message_with_reply_sync(connection, message);
xpc_release(message);
xpc_release(answer);
};
callBacks.downloadDidBegin = ^(SUDSDownloader *downloader) {
xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0);
xpc_dictionary_set_bool(message, SUDownloadServiceDidBeginDownloadingKey, true);
xpc_object_t answer = xpc_connection_send_message_with_reply_sync(connection, message);
xpc_release(message);
xpc_release(answer);
};
callBacks.downloadDidFail = ^(SUDSDownloader *downloader, NSError *error) {
errcode = (int32_t)[error code];
errdomain = [[error domain] cStringUsingEncoding:NSUTF8StringEncoding];
errmsg = [[error localizedDescription] cStringUsingEncoding:NSUTF8StringEncoding];
NSData *errorData = [NSKeyedArchiver archivedDataWithRootObject:error];
xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0);
xpc_dictionary_set_data(message, SUDownloadServiceReceivedFailErrorKey, [errorData bytes], [errorData length]);
xpc_object_t answer = xpc_connection_send_message_with_reply_sync(connection, message);
xpc_release(message);
xpc_release(answer);
};
callBacks.downloadDidFinish = ^(SUDSDownloader *downloader) {
xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0);
xpc_dictionary_set_bool(message, SUDownloadServiceDidFinishDownloadingKey, true);
xpc_object_t answer = xpc_connection_send_message_with_reply_sync(connection, message);
xpc_release(message);
xpc_release(answer);
};
callBacks.downloadShouldDecodeSourceData = ^BOOL(SUDSDownloader *downloader, NSString *MIMEType) {
xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0);
xpc_dictionary_set_string(message, SUDownloadServiceMIMETypeToDecodeKey, [MIMEType cStringUsingEncoding:NSUTF8StringEncoding]);
xpc_object_t answer = xpc_connection_send_message_with_reply_sync(connection, message);
xpc_release(message);
BOOL result = NO;
if (xpc_get_type(answer) == XPC_TYPE_DICTIONARY)
result = (BOOL)xpc_dictionary_get_bool(answer, SUDownloadServiceShouldDecodeMIMETypeKey);
xpc_release(answer);
return result;
};
[downloader setCallBacks:callBacks];
[downloader startDownload];
while ([downloader isInProgress])
{
if (shouldStopDownload)
{
[downloader stopDownload];
asl_log(NULL, NULL, ASL_LEVEL_NOTICE, "Download process stopped.\n");
break;
}
CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, true);
}
}
while (NO);
[localPool release];
#if DEBUG_LOGGING_ENABLED
NSLog(@"Download process finished. Will send last message...");
#endif
// Clean up and add errcode/errmsg to reply
if (connection)
{
xpc_connection_cancel(connection);
xpc_release(connection);
}
xpc_dictionary_set_int64(reply, SUDownloadServiceErrorCodeKey, (int64_t)errcode);
if (errmsg)
{
xpc_dictionary_set_string(reply, SUDownloadServiceErrorMessageKey, errmsg);
}
if (errdomain)
{
xpc_dictionary_set_string(reply, SUDownloadServiceErrorDomainKey, errdomain);
}
}
static void fetch_peer_event_handler(xpc_connection_t peer, xpc_object_t event)
{
// Get the object type.
xpc_type_t type = xpc_get_type(event);
if (XPC_TYPE_ERROR == type)
{
// Handle an error.
if (XPC_ERROR_CONNECTION_INVALID == event)
{
// The client process on the other end of the connection
// has either crashed or cancelled the connection.
asl_log(NULL, NULL, ASL_LEVEL_NOTICE, "peer(%d) received "
"XPC_ERROR_CONNECTION_INVALID",
xpc_connection_get_pid(peer));
xpc_connection_cancel(peer);
}
else if (XPC_ERROR_TERMINATION_IMMINENT == event)
{
// Handle per-connection termination cleanup. This
// service is about to exit.
asl_log(NULL, NULL, ASL_LEVEL_NOTICE, "peer(%d) received "
"XPC_ERROR_TERMINATION_IMMINENT",
xpc_connection_get_pid(peer));
}
}
else if (XPC_TYPE_DICTIONARY == type)
{
xpc_object_t requestMessage = event;
xpc_object_t replyMessage = xpc_dictionary_create_reply(requestMessage);
assert(replyMessage != NULL);
// Process request and build a reply message.
fetch_process_request(requestMessage, replyMessage);
xpc_connection_send_message(peer, replyMessage);
xpc_release(replyMessage);
}
}
static void release_dispatch_queue(void *queue)
{
dispatch_release(queue);
}
static void fetch_event_handler(xpc_connection_t peer)
{
// Generate an unique name for the queue to handle messages from
// this peer and create a new dispatch queue for it.
char *queue_name = NULL;
asprintf(&queue_name, "%s-peer-%d", "com.devmate.UpdateDownloader", xpc_connection_get_pid(peer));
dispatch_queue_t peer_event_queue = dispatch_queue_create(queue_name, DISPATCH_QUEUE_SERIAL);
assert(peer_event_queue != NULL);
free(queue_name);
// Set the target queue for connection.
xpc_connection_set_target_queue(peer, peer_event_queue);
xpc_connection_set_context(peer, peer_event_queue);
xpc_connection_set_finalizer_f(peer, release_dispatch_queue);
// Set the handler block for connection.
xpc_connection_set_event_handler(peer, ^(xpc_object_t event) {
fetch_peer_event_handler(peer, event);
});
// Enable the peer connection to receive messages.
xpc_connection_resume(peer);
}
int main(int argc, const char *argv[])
{
xpc_main(fetch_event_handler);
exit(EXIT_FAILURE);
}
@@ -1,2 +0,0 @@
/* Localized versions of Info.plist keys */
BIN
View File
Binary file not shown.
+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>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>${CURRENT_PROJECT_VERSION} git</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>${DYLIB_CURRENT_VERSION}</string>
<key>CFBundleShortVersionString</key>
<string>${DYLIB_CURRENT_VERSION}</string>
<string>${CURRENT_PROJECT_VERSION}</string>
<key>NSPrincipalClass</key>
<string></string>
</dict>
@@ -1,39 +0,0 @@
//
// SUInstallServiceConstants.h
// Sparkle
//
// Created by Dmytro Tretiakov on 8/2/13.
//
//
#ifndef Sparkle_SUInstallServiceConstants_h
#define Sparkle_SUInstallServiceConstants_h
typedef enum _SUInstallSerciveTask
{
SUInstallServiceTaskCopyPath = 1LL,
SUInstallServiceTaskAuthCopyPath = 2LL,
SUInstallServiceTaskLaunchTask = 3LL
} SUInstallServiceTask;
const char * SUInstallServiceTaskTypeKey = "task_type"; // int64_t
// SUInstallServiceTaskCopyPath & SUInstallServiceTaskAuthCopyPath keys
const char * SUInstallServiceSourcePathKey = "source_path"; // c-string
const char * SUInstallServiceDestinationPathKey = "destination_path"; // c-string
const char * SUInstallServiceTempNameKey = "tmp_name"; // c-string
// SUInstallServiceTaskLaunchTask keys
const char * SUInstallServiceLaunchTaksPathKey = "launch_task_path";
const char * SUInstallServiceLaunchTaskArgumentsKey = "launch_task_arguments"; // xpc_array of c-strings
const char * SUInstallServiceLaunchTaskEnvironmentKey = "launch_task_environment"; // xpc_dictionary with keys and values of c-strings
const char * SUInstallServiceLaunchTaskCurrentDirKey = "launch_task_cur_dir"; // c-string
const char * SUInstallServiceLaunchTaskInputDataKey = "launch_task_input_data"; // xpc_data
const char * SUInstallServiceLaunchTaskReplyImmediatelyKey = "launch_task_reply_immediately"; // bool
// Reply keys
const char * SUInstallServiceErrorCodeKey = "error_code"; // int64_t
const char * SUInstallServiceErrorLocalizedDescriptionKey = "error_localized_description"; // c-string
const char * SUInstallServiceLaunchTaskOutputDataKey = "launch_task_output_data"; // xpc_data
#endif
-29
View File
@@ -1,29 +0,0 @@
//
// SUXPCInstaller.h
// Sparkle
//
// Created by Whitney Young on 3/19/12.
// Copyright (c) 2012 FadingRed. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface SUXPCInstaller : NSObject
+ (BOOL)copyPathWithAuthentication:(NSString *)src overPath:(NSString *)dst temporaryName:(NSString *)tmp error:(NSError **)outError;
+ (BOOL)copyPathContent:(NSString *)src toDirectory:(NSString *)dstDir error:(NSError **)outError; // dstDir will be created if absent
+ (void)launchTaskWithLaunchPath:(NSString *)path arguments:(NSArray *)arguments;
+ (void)launchTaskWithPath:(NSString *)launchPath
arguments:(NSArray *)arguments
environment:(NSDictionary *)environment
currentDirectoryPath:(NSString *)currentDirPath
inputData:(NSData *)inputData
waitForTaskResult:(BOOL)waitForTaskResult
waitUntilDone:(BOOL)waitUntilDone // for sync/async logic
completionHandler:(void (^)(int result, NSData *outputData))completionHandler;
@end
-268
View File
@@ -1,268 +0,0 @@
//
// SUXPCInstaller.m
// Sparkle
//
// Created by Whitney Young on 3/19/12.
// Copyright (c) 2012 FadingRed. All rights reserved.
//
#import <xpc/xpc.h>
#import "SUXPCInstaller.h"
#import "SUInstallServiceConstants.h"
@implementation SUXPCInstaller
+ (xpc_connection_t)getSandboxXPCService
{
__block xpc_connection_t serviceConnection = xpc_connection_create("com.devmate.UpdateInstaller", dispatch_get_main_queue());
if (!serviceConnection)
{
NSLog(@"Can't connect to XPC service");
return (NULL);
}
xpc_connection_set_event_handler(serviceConnection, ^(xpc_object_t event) {
xpc_type_t type = xpc_get_type(event);
if (type == XPC_TYPE_ERROR)
{
if (event == XPC_ERROR_CONNECTION_INVALID)
{
// The service is invalid. Either the service name supplied to
// xpc_connection_create() is incorrect or we (this process) have
// canceled the service; we can do any cleanup of appliation
// state at this point.
xpc_release(serviceConnection);
}
}
});
// Need to resume the service in order for it to process messages.
xpc_connection_resume(serviceConnection);
return (serviceConnection);
}
+ (BOOL)copyPathWithAuthentication:(NSString *)src overPath:(NSString *)dst temporaryName:(NSString *)tmp error:(NSError **)outError
{
xpc_connection_t connection = [self getSandboxXPCService];
xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0);
xpc_dictionary_set_int64(message, SUInstallServiceTaskTypeKey, (int64_t)SUInstallServiceTaskAuthCopyPath);
if (src)
xpc_dictionary_set_string(message, SUInstallServiceSourcePathKey, [src fileSystemRepresentation]);
if (dst)
xpc_dictionary_set_string(message, SUInstallServiceDestinationPathKey, [dst fileSystemRepresentation]);
if (tmp)
xpc_dictionary_set_string(message, SUInstallServiceTempNameKey, [tmp UTF8String]);
__block BOOL xpcDidReply = NO;
__block NSError *error = nil;
dispatch_queue_t queue = dispatch_queue_create(NULL, DISPATCH_QUEUE_SERIAL);
xpc_connection_send_message_with_reply(connection, message, queue, ^(xpc_object_t response) {
if (XPC_TYPE_ERROR == xpc_get_type(response))
{
NSDictionary *errorInfo = [NSDictionary dictionaryWithObject:@"Internal XPC error."
forKey:NSLocalizedDescriptionKey];
error = [[NSError alloc] initWithDomain:SUSparkleErrorDomain code:SUXPCServiceError userInfo:errorInfo];
}
else if (XPC_TYPE_DICTIONARY == xpc_get_type(response))
{
const char *errorString = xpc_dictionary_get_string(response, SUInstallServiceErrorLocalizedDescriptionKey);
if (errorString != NULL)
{
NSDictionary *errorInfo = [NSDictionary dictionaryWithObject:[NSString stringWithCString:errorString encoding:NSUTF8StringEncoding]
forKey:NSLocalizedDescriptionKey];
error = [[NSError alloc] initWithDomain:SUSparkleErrorDomain code:SUXPCServiceError userInfo:errorInfo];
}
}
xpcDidReply = YES;
});
while (NO == xpcDidReply)
{
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.2]];
}
xpc_release(message);
dispatch_release(queue);
[error autorelease];
if (nil != error && NULL != outError)
{
*outError = error;
}
return (nil == error);
}
+ (BOOL)copyPathContent:(NSString *)src toDirectory:(NSString *)dstDir error:(NSError **)outError
{
xpc_connection_t connection = [self getSandboxXPCService];
xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0);
xpc_dictionary_set_int64(message, SUInstallServiceTaskTypeKey, (int64_t)SUInstallServiceTaskCopyPath);
if (src)
xpc_dictionary_set_string(message, SUInstallServiceSourcePathKey, [src fileSystemRepresentation]);
if (dstDir)
xpc_dictionary_set_string(message, SUInstallServiceDestinationPathKey, [dstDir fileSystemRepresentation]);
__block BOOL xpcDidReply = NO;
__block NSError *error = nil;
dispatch_queue_t queue = dispatch_queue_create(NULL, DISPATCH_QUEUE_SERIAL);
xpc_connection_send_message_with_reply(connection, message, queue, ^(xpc_object_t response) {
if (XPC_TYPE_ERROR == xpc_get_type(response))
{
NSDictionary *errorInfo = [NSDictionary dictionaryWithObject:@"Internal XPC error."
forKey:NSLocalizedDescriptionKey];
error = [[NSError alloc] initWithDomain:SUSparkleErrorDomain code:SUXPCServiceError userInfo:errorInfo];
}
else if (XPC_TYPE_DICTIONARY == xpc_get_type(response))
{
const char *errorString = xpc_dictionary_get_string(response, SUInstallServiceErrorLocalizedDescriptionKey);
if (errorString != NULL)
{
NSDictionary *errorInfo = [NSDictionary dictionaryWithObject:[NSString stringWithCString:errorString encoding:NSUTF8StringEncoding]
forKey:NSLocalizedDescriptionKey];
error = [[NSError alloc] initWithDomain:SUSparkleErrorDomain code:SUXPCServiceError userInfo:errorInfo];
}
}
xpcDidReply = YES;
});
while (NO == xpcDidReply)
{
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.2]];
}
xpc_release(message);
dispatch_release(queue);
[error autorelease];
if (nil != error && NULL != outError)
{
*outError = error;
}
return (nil == error);
}
+ (void)launchTaskWithLaunchPath:(NSString *)path arguments:(NSArray *)arguments
{
[self launchTaskWithPath:path
arguments:arguments
environment:nil
currentDirectoryPath:nil
inputData:nil
waitForTaskResult:NO
waitUntilDone:YES
completionHandler:nil];
}
+ (void)launchTaskWithPath:(NSString *)launchPath
arguments:(NSArray *)arguments
environment:(NSDictionary *)environment
currentDirectoryPath:(NSString *)currentDirPath
inputData:(NSData *)inputData
waitForTaskResult:(BOOL)waitForTaskResult
waitUntilDone:(BOOL)waitUntilDone
completionHandler:(void (^)(int result, NSData *outputData))completionHandler
{
xpc_connection_t connection = [self getSandboxXPCService];
xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0);
xpc_dictionary_set_int64(message, SUInstallServiceTaskTypeKey, (int64_t)SUInstallServiceTaskLaunchTask);
if ([launchPath length])
{
xpc_dictionary_set_string(message, SUInstallServiceLaunchTaksPathKey, [launchPath fileSystemRepresentation]);
}
if ([arguments count])
{
xpc_object_t array = xpc_array_create(NULL, 0);
for (NSString *argument in arguments)
{
if (![argument isKindOfClass:[NSString class]])
argument = [argument description];
xpc_array_set_string(array, XPC_ARRAY_APPEND, [argument UTF8String]);
}
xpc_dictionary_set_value(message, SUInstallServiceLaunchTaskArgumentsKey, array);
xpc_release(array);
}
if ([environment count])
{
__block xpc_object_t dict = xpc_dictionary_create(NULL, NULL, 0);
[environment enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSString *xpc_key = [key isKindOfClass:[NSString class]] ? key : [key description];
NSString *xpc_value = [obj isKindOfClass:[NSString class]] ? obj : [obj description];
xpc_dictionary_set_string(dict, [xpc_key UTF8String], [xpc_value UTF8String]);
}];
xpc_dictionary_set_value(message, SUInstallServiceLaunchTaskEnvironmentKey, dict);
xpc_release(dict);
}
if ([currentDirPath length])
{
xpc_dictionary_set_string(message, SUInstallServiceLaunchTaskCurrentDirKey, [currentDirPath fileSystemRepresentation]);
}
if ([inputData length])
{
xpc_dictionary_set_data(message, SUInstallServiceLaunchTaskInputDataKey, [inputData bytes], [inputData length]);
}
xpc_dictionary_set_bool(message, SUInstallServiceLaunchTaskReplyImmediatelyKey, waitForTaskResult ? false : true);
__block BOOL xpcTaskDidReply = NO;
xpc_connection_send_message_with_reply(connection, message, dispatch_get_current_queue(), ^(xpc_object_t response) {
int taskResult = 0;
NSData *outputData = nil;
if (completionHandler != NULL)
{
xpc_type_t type = xpc_get_type(response);
if (type == XPC_TYPE_ERROR)
{
taskResult = SUXPCServiceError;
}
else if (type == XPC_TYPE_DICTIONARY)
{
taskResult = (int)xpc_dictionary_get_int64(response, SUInstallServiceErrorCodeKey);
size_t bytesLen = 0;
const void *bytes = xpc_dictionary_get_data(response, SUInstallServiceLaunchTaskOutputDataKey, &bytesLen);
if (NULL != bytes)
{
outputData = [NSData dataWithBytes:bytes length:bytesLen];
}
}
completionHandler(taskResult, outputData);
}
xpcTaskDidReply = YES;
});
xpc_release(message);
if (waitUntilDone)
{
while (NO == xpcTaskDidReply)
{
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.2]];
}
}
}
@end
@@ -1,31 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>English</string>
<key>CFBundleExecutable</key>
<string>${EXECUTABLE_NAME}</string>
<key>CFBundleIdentifier</key>
<string>${EXECUTABLE_NAME}</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundlePackageType</key>
<string>XPC!</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>XPCService</key>
<dict>
<key>ServiceType</key>
<string>Application</string>
<key>JoinExistingSession</key>
<true/>
</dict>
</dict>
</plist>
-377
View File
@@ -1,377 +0,0 @@
//
// main.m
// Update
//
// Created by Whitney Young on 3/19/12.
// Copyright (c) 2012 FadingRed. All rights reserved.
//
#include <xpc/xpc.h>
#include <asl.h>
#import <Foundation/Foundation.h>
#import "SUPlainInstallerInternals.h"
#import "SUInstallServiceConstants.h"
#import "SULog.h"
#import "SUConstants.h"
static xpc_object_t SUSICopyPathContent(xpc_object_t message)
{
if (NULL == message)
return NULL;
const char *src = xpc_dictionary_get_string(message, SUInstallServiceSourcePathKey);
const char *dst = xpc_dictionary_get_string(message, SUInstallServiceDestinationPathKey);
NSFileManager *manager = [NSFileManager defaultManager];
NSString *sourcePath = src ? [manager stringWithFileSystemRepresentation:src length:strlen(src)] : nil;
NSString *targetPath = dst ? [manager stringWithFileSystemRepresentation:dst length:strlen(dst)] : nil;
NSError *error = nil;
do
{
if (nil == sourcePath)
{
NSDictionary *errorInfo = [NSDictionary dictionaryWithObject:@"Source path is absent." forKey:NSLocalizedDescriptionKey];
error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUXPCServiceError userInfo:errorInfo];
break;
}
if (nil == targetPath)
{
NSDictionary *errorInfo = [NSDictionary dictionaryWithObject:@"Destination path is absent." forKey:NSLocalizedDescriptionKey];
error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUXPCServiceError userInfo:errorInfo];
break;
}
NSArray *contents = nil;
BOOL isSrcDirectory = NO;
BOOL isSrcExist = [manager fileExistsAtPath:sourcePath isDirectory:&isSrcDirectory];
isSrcDirectory = isSrcDirectory && ![[NSWorkspace sharedWorkspace] isFilePackageAtPath:sourcePath];
if (isSrcExist && isSrcDirectory)
{
contents = [manager contentsOfDirectoryAtPath:sourcePath error:&error];
}
else if (isSrcExist)
{
contents = [NSArray arrayWithObject:@""];
}
else
{
NSDictionary *errorInfo = [NSDictionary dictionaryWithObject:@"Source does not exist on disk." forKey:NSLocalizedDescriptionKey];
error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUXPCServiceError userInfo:errorInfo];
}
if (nil != error)
{
break;
}
BOOL isDstDirectory = NO;
BOOL isDstExist = [manager fileExistsAtPath:targetPath isDirectory:&isDstDirectory];
if (isSrcDirectory && (!isDstExist || !isDstDirectory))
{
if (isDstExist)
[manager removeItemAtPath:targetPath error:&error];
[manager createDirectoryAtPath:targetPath withIntermediateDirectories:YES attributes:nil error:&error];
}
else if (!isSrcDirectory)
{
if (isDstExist && !isDstDirectory)
[manager removeItemAtPath:targetPath error:&error];
[manager createDirectoryAtPath:targetPath withIntermediateDirectories:YES attributes:nil error:&error];
}
if (nil != error)
{
break;
}
for (NSString *item in contents)
{
NSString *fromPath = [item length] ? [sourcePath stringByAppendingPathComponent:item] : sourcePath;
NSString *toPath = [item length] ? [targetPath stringByAppendingPathComponent:item] : [targetPath stringByAppendingPathComponent:[sourcePath lastPathComponent]];
if (![manager isReadableFileAtPath:fromPath])
{
SULog(@"XPC Install Service: will skip \"%@\"", fromPath);
continue;
}
SULog(@"XPC Install Service: will copy \"%@\" to \"%@\"", fromPath, toPath);
if ([manager fileExistsAtPath:toPath])
[manager removeItemAtPath:toPath error:&error];
if (![manager copyItemAtPath:fromPath toPath:toPath error:&error])
break;
}
}
while (NO);
xpc_object_t reply = xpc_dictionary_create_reply(message);
if (nil != error)
{
xpc_dictionary_set_int64(reply, SUInstallServiceErrorCodeKey, (int64_t)[error code]);
const char *errorMsg = [[error localizedDescription] length] ? [[error localizedDescription] UTF8String] : "";
xpc_dictionary_set_string(reply, SUInstallServiceErrorLocalizedDescriptionKey, errorMsg);
}
return reply;
}
static xpc_object_t SUISCopyPathWithAuthentication(xpc_object_t message)
{
if (NULL == message)
return NULL;
const char *src = xpc_dictionary_get_string(message, SUInstallServiceSourcePathKey);
const char *dst = xpc_dictionary_get_string(message, SUInstallServiceDestinationPathKey);
const char *tmp = xpc_dictionary_get_string(message, SUInstallServiceTempNameKey);
NSFileManager *manager = [NSFileManager defaultManager];
NSString *relaunchPathToCopy = src ? [manager stringWithFileSystemRepresentation:src length:strlen(src)] : nil;
NSString *targetPath = dst ? [manager stringWithFileSystemRepresentation:dst length:strlen(dst)] : nil;
NSString *temporaryName = tmp ? [NSString stringWithUTF8String:tmp] : nil;
NSError *error = nil;
BOOL result = [SUPlainInstaller copyPathWithAuthentication:relaunchPathToCopy overPath:targetPath temporaryName:temporaryName error:&error];
// send response to indicate ok
xpc_object_t reply = xpc_dictionary_create_reply(message);
if (!result && error != nil)
{
xpc_dictionary_set_int64(reply, SUInstallServiceErrorCodeKey, (int64_t)[error code]);
const char *errorMsg = [[error localizedDescription] length] ? [[error localizedDescription] UTF8String] : "";
xpc_dictionary_set_string(reply, SUInstallServiceErrorLocalizedDescriptionKey, errorMsg);
}
return reply;
}
static xpc_object_t SUISLaunchTask(xpc_object_t message)
{
if (NULL == message)
return NULL;
const char *path = xpc_dictionary_get_string(message, SUInstallServiceLaunchTaksPathKey);
NSString *launchPath = path ? [[NSFileManager defaultManager] stringWithFileSystemRepresentation:path length:strlen(path)] : nil;
xpc_object_t array = xpc_dictionary_get_value(message, SUInstallServiceLaunchTaskArgumentsKey);
NSArray *arguments = nil;
if (NULL != array)
{
size_t count = xpc_array_get_count(array);
NSMutableArray *mutableArgs = [NSMutableArray arrayWithCapacity:count];
for (size_t i = 0; i < count; i++)
{
[mutableArgs addObject:[NSString stringWithUTF8String:xpc_array_get_string(array, i)]];
}
arguments = mutableArgs;
}
xpc_object_t dict = xpc_dictionary_get_value(message, SUInstallServiceLaunchTaskEnvironmentKey);
NSDictionary *environment = nil;
if (NULL != dict)
{
size_t count = xpc_dictionary_get_count(dict);
__block NSMutableDictionary *mutableEnv = [NSMutableDictionary dictionaryWithCapacity:count];
xpc_dictionary_apply(dict, ^bool(const char *key, xpc_object_t value) {
NSString *envKey = [NSString stringWithUTF8String:key];
NSString *envValue = [NSString stringWithUTF8String:value];
[mutableEnv setObject:envValue forKey:envKey];
return true;
});
environment = mutableEnv;
}
path = xpc_dictionary_get_string(message, SUInstallServiceLaunchTaskCurrentDirKey);
NSString *currentDirPath = path ? [[NSFileManager defaultManager] stringWithFileSystemRepresentation:path length:strlen(path)] : nil;
size_t bytesLen = 0;
const void *bytes = xpc_dictionary_get_data(message, SUInstallServiceLaunchTaskInputDataKey, &bytesLen);
NSData *inputData = bytes ? [NSData dataWithBytes:bytes length:bytesLen] : nil;
bool shouldReplyImmediatly = xpc_dictionary_get_bool(message, SUInstallServiceLaunchTaskReplyImmediatelyKey);
// prepare NSTask
NSTask *task = [[[NSTask alloc] init] autorelease];
NSPipe *inputPipe = [NSPipe pipe];
NSPipe *outputPipe = [NSPipe pipe];
[task setStandardInput:inputPipe];
[task setStandardOutput:outputPipe];
[task setStandardError:outputPipe];
if (launchPath != nil)
[task setLaunchPath:launchPath];
if ([arguments count])
[task setArguments:arguments];
if ([environment count])
[task setEnvironment:environment];
if (currentDirPath != nil)
[task setCurrentDirectoryPath:currentDirPath];
__block NSData *outputData = nil;
__block int taskResult = 0;
__block BOOL isTaskRunning = YES;
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
NSArray *notificationObjects = nil;
if (!shouldReplyImmediatly)
{
id object1 = [notificationCenter addObserverForName:NSFileHandleReadToEndOfFileCompletionNotification
object:[outputPipe fileHandleForReading]
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification *note) {
outputData = [[[note userInfo] objectForKey:NSFileHandleNotificationDataItem] retain];
isTaskRunning = NO;
}];
id object2 = [notificationCenter addObserverForName:NSTaskDidTerminateNotification
object:task
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification *note) {
taskResult = [task terminationStatus];
}];
notificationObjects = [NSArray arrayWithObjects:object1, object2, nil];
}
[[outputPipe fileHandleForReading] readToEndOfFileInBackgroundAndNotifyForModes:[NSArray arrayWithObject:NSDefaultRunLoopMode]];
@try
{
[task launch];
if ([inputData length])
{
[[inputPipe fileHandleForWriting] writeData:inputData];
[[inputPipe fileHandleForWriting] closeFile];
}
if (!shouldReplyImmediatly)
{
// loop until we are done receiving the data
while (YES == isTaskRunning)
{
CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.5, true);
}
}
}
@catch (...)
{
taskResult = SUXPCServiceError;
}
// send response to indicate ok
xpc_object_t reply = xpc_dictionary_create_reply(message);
xpc_dictionary_set_int64(reply, SUInstallServiceErrorCodeKey, (int64_t)taskResult);
if (outputData != nil)
{
xpc_dictionary_set_data(reply, SUInstallServiceLaunchTaskOutputDataKey, [outputData bytes], [outputData length]);
}
for (id object in notificationObjects)
{
[notificationCenter removeObserver:object];
}
[outputData release];
return reply;
}
static void peer_event_handler(xpc_connection_t peer, xpc_object_t event)
{
xpc_type_t type = xpc_get_type(event);
if (type == XPC_TYPE_ERROR)
{
if (event == XPC_ERROR_CONNECTION_INVALID)
{
// The client process on the other end of the connection has either
// crashed or cancelled the connection. After receiving this error,
// the connection is in an invalid state, and you do not need to
// call xpc_connection_cancel(). Just tear down any associated state
// here.
}
else if (event == XPC_ERROR_TERMINATION_IMMINENT)
{
// Handle per-connection termination cleanup.
}
}
else if (type == XPC_TYPE_DICTIONARY)
{
// Handle the message.
SUInstallServiceTask task = (SUInstallServiceTask)xpc_dictionary_get_int64(event, SUInstallServiceTaskTypeKey);
NSLog(@"XPC Installer: should start task with id = %lld", (int64_t)task);
xpc_object_t reply = NULL;
NSAutoreleasePool *localPool = [[NSAutoreleasePool alloc] init];
switch (task)
{
case SUInstallServiceTaskCopyPath:
{
reply = SUSICopyPathContent(event);
break;
}
case SUInstallServiceTaskAuthCopyPath:
{
reply = SUISCopyPathWithAuthentication(event);
break;
}
case SUInstallServiceTaskLaunchTask:
{
reply = SUISLaunchTask(event);
break;
}
default:
{
SULog(@"XPC Install Service: Unknown XPC service task %lld", (int64_t)task);
reply = xpc_dictionary_create_reply(event);
xpc_dictionary_set_int64(reply, SUInstallServiceErrorCodeKey, (int64_t)SUXPCServiceError);
xpc_dictionary_set_string(reply, SUInstallServiceErrorLocalizedDescriptionKey, "Unknown install cervice task.");
break;
}
}
[localPool release];
if (NULL == reply)
{
reply = xpc_dictionary_create_reply(event);
}
xpc_connection_send_message(peer, reply);
xpc_release(reply);
}
}
static void event_handler(xpc_connection_t peer)
{
// By defaults, new connections will target the default dispatch
// concurrent queue.
xpc_connection_set_event_handler(peer, ^(xpc_object_t event) {
peer_event_handler(peer, event);
});
// This will tell the connection to begin listening for events. If you
// have some other initialization that must be done asynchronously, then
// you can defer this call until after that initialization is done.
xpc_connection_resume(peer);
}
int main(int argc, const char *argv[])
{
xpc_main(event_handler);
return 0;
}
@@ -1,11 +0,0 @@
//
// install_service.pch
// Sparkle
//
// Created by Dmytro Tretiakov on 4/25/14.
//
//
#define SPARKLE_BUNDLE [NSBundle mainBundle]
#define SULocalizedString(key,comment) NSLocalizedStringFromTableInBundle(key, @"Sparkle", SPARKLE_BUNDLE, comment)
+4 -6
View File
@@ -9,8 +9,6 @@
#ifndef NTSYNCHRONOUSTASK_H
#define NTSYNCHRONOUSTASK_H
#import <Foundation/Foundation.h>
@interface NTSynchronousTask : NSObject
{
@private
@@ -22,16 +20,16 @@
BOOL mv_done;
int mv_result;
}
@property (readonly, retain) NSData *output;
@property (readonly) int result;
// pass nil for directory if not needed
// returns the result
+ (int)task:(NSString*)toolPath directory:(NSString*)currentDirectory withArgs:(NSArray*)args input:(NSData*)input output:(NSData**)outData;
+(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;
+(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
+46 -119
View File
@@ -6,111 +6,40 @@
// Copyright 2005 Steve Gehrman. All rights reserved.
//
#import "SUUpdater.h"
#import "SUAppcast.h"
#import "SUAppcastItem.h"
#import "SUVersionComparisonProtocol.h"
#import "NTSynchronousTask.h"
#import <AppKit/NSApplication.h>
@interface NTSynchronousTask ()
@property (retain) NSTask *task;
@property (retain) NSPipe *outputPipe;
@property (retain) NSPipe *inputPipe;
@property (readwrite, retain) NSData *output;
@property (getter = isDone) BOOL done;
@property (readwrite) int result;
@end
@implementation NTSynchronousTask
//----------------------------------------------------------
// task
//----------------------------------------------------------
- (NSTask *)task
{
return mv_task;
}
- (void)setTask:(NSTask *)theTask
{
if (mv_task != theTask) {
[mv_task release];
mv_task = [theTask retain];
}
}
//----------------------------------------------------------
// outputPipe
//----------------------------------------------------------
- (NSPipe *)outputPipe
{
return mv_outputPipe;
}
- (void)setOutputPipe:(NSPipe *)theOutputPipe
{
if (mv_outputPipe != theOutputPipe) {
[mv_outputPipe release];
mv_outputPipe = [theOutputPipe retain];
}
}
//----------------------------------------------------------
// inputPipe
//----------------------------------------------------------
- (NSPipe *)inputPipe
{
return mv_inputPipe;
}
- (void)setInputPipe:(NSPipe *)theInputPipe
{
if (mv_inputPipe != theInputPipe) {
[mv_inputPipe release];
mv_inputPipe = [theInputPipe retain];
}
}
//----------------------------------------------------------
// output
//----------------------------------------------------------
- (NSData *)output
{
return mv_output;
}
- (void)setOutput:(NSData *)theOutput
{
if (mv_output != theOutput) {
[mv_output release];
mv_output = [theOutput retain];
}
}
//----------------------------------------------------------
// done
//----------------------------------------------------------
- (BOOL)done
{
return mv_done;
}
- (void)setDone:(BOOL)flag
{
mv_done = flag;
}
//----------------------------------------------------------
// result
//----------------------------------------------------------
- (int)result
{
return mv_result;
}
- (void)setResult:(int)theResult
{
mv_result = theResult;
}
@synthesize output = mv_output;
@synthesize result = mv_result;
@synthesize task = mv_task;
@synthesize outputPipe = mv_outputPipe;
@synthesize inputPipe = mv_inputPipe;
@synthesize done = mv_done;
- (void)taskOutputAvailable:(NSNotification*)note
{
[self setOutput:[[note userInfo] objectForKey:NSFileHandleNotificationDataItem]];
self.output = [[note userInfo] objectForKey:NSFileHandleNotificationDataItem];
[self setDone:YES];
self.done = YES;
}
- (void)taskDidTerminate:(NSNotification*)note
{
[self setResult:[[self task] terminationStatus]];
self.result = [self.task terminationStatus];
}
- (id)init;
@@ -118,13 +47,13 @@
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 = [[[NSTask alloc] init] autorelease];
self.outputPipe = [[[NSPipe alloc] init] autorelease];
self.inputPipe = [[[NSPipe alloc] init] autorelease];
[[self task] setStandardInput:[self inputPipe]];
[[self task] setStandardOutput:[self outputPipe]];
[[self task] setStandardError:[self outputPipe]];
self.task.standardInput = self.inputPipe;
self.task.standardOutput = self.outputPipe;
self.task.standardError = self.outputPipe;
}
return self;
@@ -137,10 +66,10 @@
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
[mv_task release];
[mv_outputPipe release];
[mv_inputPipe release];
[mv_output release];
self.task = nil;
self.outputPipe = nil;
self.inputPipe = nil;
self.output = nil;
[super dealloc];
}
@@ -150,10 +79,10 @@
BOOL success = NO;
if (currentDirectory)
[[self task] setCurrentDirectoryPath: currentDirectory];
self.task.currentDirectoryPath = currentDirectory;
[[self task] setLaunchPath:toolPath];
[[self task] setArguments:args];
self.task.launchPath = toolPath;
self.task.arguments = args;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(taskOutputAvailable:)
@@ -169,7 +98,7 @@
@try
{
[[self task] launch];
[self.task launch];
success = YES;
}
@catch (NSException *localException) { }
@@ -179,12 +108,12 @@
if (input)
{
// feed the running task our input
[[[self inputPipe] fileHandleForWriting] writeData:input];
[[[self inputPipe] fileHandleForWriting] closeFile];
[[self.inputPipe fileHandleForWriting] writeData:input];
[[self.inputPipe fileHandleForWriting] closeFile];
}
// loop until we are done receiving the data
if (![self done])
if (!self.done)
{
double resolution = 1;
BOOL isRunning;
@@ -195,7 +124,7 @@
isRunning = [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
beforeDate:next];
} while (isRunning && ![self done]);
} while (isRunning && !self.done);
}
}
}
@@ -204,7 +133,7 @@
{
// 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;
NSData* result = nil;
@try
{
@@ -228,7 +157,7 @@
}
+ (int)task:(NSString*)toolPath directory:(NSString*)currentDirectory withArgs:(NSArray*)args input:(NSData*)input output:(NSData**)outData
+(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];
@@ -236,8 +165,7 @@
if( outData )
*outData = nil;
NS_DURING
{
@try {
NTSynchronousTask* task = [[NTSynchronousTask alloc] init];
[task run:toolPath directory:currentDirectory withArgs:args input:input];
@@ -247,10 +175,9 @@
*outData = [[task output] retain];
[task release];
}
NS_HANDLER;
} @catch (NSException *localException) {
taskResult = errCppGeneral;
NS_ENDHANDLER;
}
[pool drain];
Binary file not shown.
+12 -22
View File
@@ -1,40 +1,30 @@
# Sparkle
# Sparkle <img src="Sparkle.png" width=48 height=48 alt="">
is an easy-to-use software update framework for Cocoa developers.
* True self-updating--no work required from the user.
## This fork
* Up to date with 10.9 SDK and Xcode 5.1.
* Merged bugfixes, security fixes and some features from multiple Sparkle forks.
* Merged official Sparkle branch with truly automatic background updates (no UI at all) when user agreed to "Automatically download and install updates in the future."
* Ability to mark updates as critical.
* Progress and status notifications for the host app.
* Name of finish_installation.app can be configured to match your app's name.
## Features
* True self-updating—no work required from the user.
* Displays release notes to the user via WebKit.
* Displays a detailed progress window to the user.
* Supports authentication for installing in secure locations.
* Really, really easy to install.
* Uses appcasts for release information.
* The user can choose to automatically download and install all updates.
* Seamless integration—there's no mention of Sparkle; your icons and app name are used.
* Supports DSA signatures for ultra-secure updates.
* Sparkle requires no code in your app, so it's trivial to upgrade or remove the module.
## New in Sparkle 1.5:
* Optionally sends user demographic information to the server when checking for updates.
* Dual-mode garbage collection support for any memory management style.
* Sparkle doesn't bug the user until second launch for better first impressions.
* Sparkle can install .pkg files for more complicated products.
* Supports bundles, preference panes, plugins, and other non-.app software.
* Supports branches due to minimum OS version requirements.
* Deep delegate support to make Sparkle work exactly as you need.
* Tons of other stuff! [Read more about what's new.](http://andymatuschak.org/articles/2008/05/31/sparkle-15b1-now-available/ "Sparkle 1.5b1: now available!")
-40
View File
@@ -1,40 +0,0 @@
{\rtf1\ansi\ansicpg1252\cocoartf1265\cocoasubrtf210
{\fonttbl\f0\fswiss\fcharset0 Helvetica;}
{\colortbl;\red255\green255\blue255;\red38\green38\blue38;}
\margl1440\margr1440\vieww17920\viewh13460\viewkind0
\deftab720
\pard\pardeftab720
\f0\b\fs26 \cf2 Version 2.1.1
\b0 \
\pard\pardeftab720\sl380
\cf2 \'96 Fixed crash on launch with no internet connection.
\fs24 \cf0 \
\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\pardirnatural
\cf0 \
\pard\pardeftab720
\b\fs26 \cf2 Version 2.1\
\pard\pardeftab720\sl380
\b0 \cf2 \'96 SUFeedURL inside Info.plist file is now optional and can be automatically generated by DevMate\
\'96 Added an updater state check to avoid initiating duplicate installation processes\
\'96 Added a SUUpdaterQueue class\
\'96 Added additional delegate methods.\
\b \
\pard\pardeftab720
\cf2 Version 2.0.1\
\pard\pardeftab720\sl380
\b0 \cf2 \'96 Bug fixing for the application updates in Sandboxed environment.\
\pard\pardeftab720
\cf2 \
\pard\pardeftab720
\b \cf2 Version 2.0\
\pard\pardeftab720\sl380
\b0 \cf2 \'96 Works correctly with Sandboxed environment\
\'96 Added simple integration of beta updates check and test mode\
\'96 Integrated with DevMate service (sends additional info for statistics)}
-19
View File
@@ -1,19 +0,0 @@
//
// SUAppDelegate.h
// Sparkle
//
// Created by Dmytro Tretiakov on 8/1/14.
//
//
#import <Foundation/Foundation.h>
@class SUUpdater;
@class SUUpdaterQueue;
@interface SUAppDelegate : NSObject
@property (nonatomic, retain) IBOutlet SUUpdater *updater;
@property (nonatomic, retain) SUUpdaterQueue *updaterQueue;
@end
-27
View File
@@ -1,27 +0,0 @@
//
// SUAppDelegate.m
// Sparkle
//
// Created by Dmytro Tretiakov on 8/1/14.
//
//
#import "SUAppDelegate.h"
#import <Sparkle/Sparkle.h>
@implementation SUAppDelegate
- (void)dealloc
{
self.updater = nil;
self.updaterQueue = nil;
[super dealloc];
}
- (void)applicationDidFinishLaunching:(NSNotification *)notification
{
self.updaterQueue = [[[SUUpdaterQueue alloc] init] autorelease];
[self.updaterQueue addUpdater:self.updater];
}
@end
+8 -10
View File
@@ -9,29 +9,27 @@
#ifndef SUAPPCAST_H
#define SUAPPCAST_H
@protocol SUAppcastDelegate;
@class SUAppcastItem;
@interface SUAppcast : NSObject
@interface SUAppcast : NSObject<NSURLDownloadDelegate>
{
@private
NSArray *items;
NSMutableDictionary *appcastValues;
id delegate;
NSString *userAgentString;
id<SUAppcastDelegate> delegate;
NSString *downloadFilename;
NSURLDownload *download;
}
@property (assign) id<SUAppcastDelegate> delegate;
@property (copy) NSString *userAgentString;
- (void)fetchAppcastFromURL:(NSURL *)url;
- (void)setDelegate:(id)delegate;
- (void)setUserAgentString:(NSString *)userAgentString;
- (void)setAppcastValue:(NSString *)value forKey:(NSString *)key;
- (void)setAllAppcastValues:(NSDictionary *)inAppcastValues;
- (NSArray *)items;
@end
@interface NSObject (SUAppcastDelegate)
- (void)appcast:(SUAppcast *)appcast willFetchURLRequest:(NSMutableURLRequest *)request;
@protocol SUAppcastDelegate <NSObject>
- (void)appcastDidFinishLoading:(SUAppcast *)appcast;
- (void)appcast:(SUAppcast *)appcast failedToLoadWithError:(NSError *)error;
@end
+30 -93
View File
@@ -6,7 +6,7 @@
// Copyright 2006 Andy Matuschak. All rights reserved.
//
#import "SUUpdater_Private.h"
#import "SUUpdater.h"
#import "SUAppcast.h"
#import "SUAppcastItem.h"
@@ -14,7 +14,6 @@
#import "SUAppcast.h"
#import "SUConstants.h"
#import "SULog.h"
#import "SUXPCURLDownload.h"
@interface NSXMLElement (SUAppcastExtensions)
- (NSDictionary *)attributesAsDictionary;
@@ -24,54 +23,47 @@
- (NSDictionary *)attributesAsDictionary
{
NSEnumerator *attributeEnum = [[self attributes] objectEnumerator];
NSXMLNode *attribute;
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
while ((attribute = [attributeEnum nextObject]))
for (NSXMLNode *attribute in attributeEnum) {
[dictionary setObject:[attribute stringValue] forKey:[attribute name]];
}
return dictionary;
}
@end
@interface SUAppcast () <NSURLDownloadDelegate>
@property (copy) NSString *downloadFilename;
@property (retain) NSURLDownload *download;
@property (copy) NSArray *items;
- (void)reportError:(NSError *)error;
- (NSXMLNode *)bestNodeInNodes:(NSArray *)nodes;
@end
@implementation SUAppcast
@synthesize downloadFilename;
@synthesize delegate;
@synthesize userAgentString;
@synthesize download;
@synthesize items;
- (void)dealloc
{
[items release];
[appcastValues release];
[downloadFilename release];
[download release];
self.items = nil;
self.userAgentString = nil;
self.downloadFilename = nil;
self.download = nil;
[super dealloc];
}
- (NSArray *)items
{
return items;
}
- (void)fetchAppcastFromURL:(NSURL *)url
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30.0];
if ([appcastValues count])
[request setAllHTTPHeaderFields:appcastValues];
if ([delegate respondsToSelector:@selector(appcast:willFetchURLRequest:)])
[delegate appcast:self willFetchURLRequest:request];
if (SUShouldUseXPCDownloader())
{
download = (NSURLDownload *)[[SUXPCURLDownload alloc] initWithRequest:request delegate:self];
}
else
{
download = [[NSURLDownload alloc] initWithRequest:request delegate:self];
}
if (userAgentString)
[request setValue:userAgentString forHTTPHeaderField:@"User-Agent"];
self.download = [[[NSURLDownload alloc] initWithRequest:request delegate:self] autorelease];
}
- (void)download:(NSURLDownload *)aDownload decideDestinationWithSuggestedFilename:(NSString *)filename
@@ -86,8 +78,7 @@
- (void)download:(NSURLDownload *)aDownload didCreateDestination:(NSString *)path
{
[downloadFilename release];
downloadFilename = [path copy];
self.downloadFilename = path;
}
- (void)downloadDidFinish:(NSURLDownload *)aDownload
@@ -111,13 +102,8 @@
}
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;
self.downloadFilename = nil;
}
else
{
@@ -168,9 +154,7 @@
}
}
NSEnumerator *nameEnum = [nodesDict keyEnumerator];
NSString *name;
while ((name = [nameEnum nextObject]))
for (NSString *name in nodesDict)
{
node = [self bestNodeInNodes:[nodesDict objectForKey:name]];
if ([name isEqualToString:@"enclosure"])
@@ -191,8 +175,7 @@
{
NSMutableArray *deltas = [NSMutableArray array];
NSEnumerator *childEnum = [[node children] objectEnumerator];
NSXMLNode *child;
while ((child = [childEnum nextObject])) {
for (NSXMLNode *child in childEnum) {
if ([[child name] isEqualToString:@"enclosure"])
[deltas addObject:[(NSXMLElement *)child attributesAsDictionary]];
}
@@ -201,7 +184,10 @@
else if (name != nil)
{
// add all other values as strings
[dict setObject:[[node stringValue] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] forKey:name];
NSString *theValue = [[node stringValue] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if (theValue != nil) {
[dict setObject:theValue forKey:name];
}
}
}
@@ -224,7 +210,7 @@
{
NSSortDescriptor *sort = [[[NSSortDescriptor alloc] initWithKey:@"date" ascending:NO] autorelease];
[appcastItems sortUsingDescriptors:[NSArray arrayWithObject:sort]];
items = [appcastItems copy];
self.items = appcastItems;
}
if (failed)
@@ -241,14 +227,9 @@
{
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.downloadFilename = nil;
[self reportError:error];
}
@@ -274,13 +255,10 @@
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]))
{
for (NSXMLElement *node in nodes) {
lang = [[node attributeForName:@"xml:lang"] stringValue];
[languages addObject:(lang ? lang : @"")];
}
@@ -291,45 +269,4 @@
return [nodes objectAtIndex:i];
}
- (void)setUserAgentString:(NSString *)uas
{
[self setAppcastValue:uas forKey:@"User-Agent"];
}
- (void)setAppcastValue:(NSString *)value forKey:(NSString *)key
{
if (nil == key)
return;
if (nil == appcastValues)
appcastValues = [[NSMutableDictionary alloc] init];
if (nil == value)
[appcastValues removeObjectForKey:key];
else
[appcastValues setValue:[[value copy] autorelease] forKey:key];
}
- (void)setAllAppcastValues:(NSDictionary *)inAppcastValues
{
if (0 == [inAppcastValues count])
return;
NSEnumerator *keyEnumerator = [inAppcastValues keyEnumerator];
id key = nil;
while ((key = [keyEnumerator nextObject]))
{
id value = [inAppcastValues objectForKey:key];
if (![key isKindOfClass:[NSString class]] || ![value isKindOfClass:[NSString class]])
continue;
[self setAppcastValue:value forKey:key];
}
}
- (void)setDelegate:del
{
delegate = del;
}
@end
+16 -14
View File
@@ -29,26 +29,28 @@
NSDictionary *deltaUpdates;
NSDictionary *propertiesDictionary;
NSURL *infoURL; // UK 2007-08-31
}
@property (copy, readonly) NSString *title;
@property (copy, readonly) NSDate *date;
@property (copy, readonly) NSString *itemDescription;
@property (retain, readonly) NSURL *releaseNotesURL;
@property (copy, readonly) NSString *DSASignature;
@property (copy, readonly) NSString *minimumSystemVersion;
@property (copy, readonly) NSString *maximumSystemVersion;
@property (retain, readonly) NSURL *fileURL;
@property (copy, readonly) NSString *versionString;
@property (copy, readonly) NSString *displayVersionString;
@property (copy, readonly) NSDictionary *deltaUpdates;
@property (retain, readonly) NSURL *infoURL;
// Initializes with data from a dictionary provided by the RSS class.
- initWithDictionary:(NSDictionary *)dict;
- initWithDictionary:(NSDictionary *)dict failureReason:(NSString**)error;
- (id)initWithDictionary:(NSDictionary *)dict;
- (id)initWithDictionary:(NSDictionary *)dict failureReason:(NSString**)error;
- (NSString *)title;
- (NSString *)versionString;
- (NSString *)displayVersionString;
- (NSDate *)date;
- (NSString *)itemDescription;
- (NSURL *)releaseNotesURL;
- (NSURL *)fileURL;
- (NSString *)DSASignature;
- (NSString *)minimumSystemVersion;
- (NSString *)maximumSystemVersion;
- (NSDictionary *)deltaUpdates;
- (BOOL)isDeltaUpdate;
- (BOOL)isCriticalUpdate;
// Returns the dictionary provided in initWithDictionary; this might be useful later for extensions.
- (NSDictionary *)propertiesDictionary;
+61 -149
View File
@@ -14,130 +14,45 @@
#import "SUAppcastItem.h"
#import "SULog.h"
@interface SUAppcastItem ()
@property (copy, readwrite) NSString *title;
@property (copy, readwrite) NSDate *date;
@property (copy, readwrite) NSString *itemDescription;
@property (retain, readwrite) NSURL *releaseNotesURL;
@property (copy, readwrite) NSString *DSASignature;
@property (copy, readwrite) NSString *minimumSystemVersion;
@property (copy, readwrite) NSString *maximumSystemVersion;
@property (retain, readwrite) NSURL *fileURL;
@property (copy, readwrite) NSString *versionString;
@property (copy, readwrite) NSString *displayVersionString;
@property (copy, readwrite) NSDictionary *deltaUpdates;
@property (retain, readwrite) NSURL *infoURL;
@end
@implementation SUAppcastItem
// Attack of accessors!
- (NSString *)title { return [[title retain] autorelease]; }
- (void)setTitle:(NSString *)aTitle
{
if (title == aTitle) return;
[title release];
title = [aTitle copy];
}
- (NSDate *)date { return [[date retain] autorelease]; }
- (void)setDate:(NSDate *)aDate
{
if (date == aDate) return;
[date release];
date = [aDate copy];
}
- (NSString *)itemDescription { return [[itemDescription retain] autorelease]; }
- (void)setItemDescription:(NSString *)anItemDescription
{
if (itemDescription == anItemDescription) return;
[itemDescription release];
itemDescription = [anItemDescription copy];
}
- (NSURL *)releaseNotesURL { return [[releaseNotesURL retain] autorelease]; }
- (void)setReleaseNotesURL:(NSURL *)aReleaseNotesURL
{
if (releaseNotesURL == aReleaseNotesURL) return;
[releaseNotesURL release];
releaseNotesURL = [aReleaseNotesURL copy];
}
- (NSString *)DSASignature { return [[DSASignature retain] autorelease]; }
- (void)setDSASignature:(NSString *)aDSASignature
{
if (DSASignature == aDSASignature) return;
[DSASignature release];
DSASignature = [aDSASignature copy];
}
- (NSURL *)fileURL { return [[fileURL retain] autorelease]; }
- (void)setFileURL:(NSURL *)aFileURL
{
if (fileURL == aFileURL) return;
[fileURL release];
fileURL = [aFileURL copy];
}
- (NSString *)versionString { return [[versionString retain] autorelease]; }
- (void)setVersionString:(NSString *)s
{
if (versionString == s) return;
[versionString release];
versionString = [s copy];
}
- (NSString *)displayVersionString { return [[displayVersionString retain] autorelease]; }
- (void)setDisplayVersionString:(NSString *)s
{
if (displayVersionString == s) return;
[displayVersionString release];
displayVersionString = [s copy];
}
- (NSString *)minimumSystemVersion { return [[minimumSystemVersion retain] autorelease]; }
- (void)setMinimumSystemVersion:(NSString *)systemVersionString
{
if (minimumSystemVersion == systemVersionString) return;
[minimumSystemVersion release];
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];
}
@synthesize date;
@synthesize deltaUpdates;
@synthesize displayVersionString;
@synthesize DSASignature;
@synthesize fileURL;
@synthesize infoURL;
@synthesize itemDescription;
@synthesize maximumSystemVersion;
@synthesize minimumSystemVersion;
@synthesize releaseNotesURL;
@synthesize title;
@synthesize versionString;
- (BOOL)isDeltaUpdate
{
return [[propertiesDictionary objectForKey:@"enclosure"] objectForKey:@"sparkle:deltaFrom"] != nil;
}
- (BOOL)isCriticalUpdate
{
return [[propertiesDictionary objectForKey:@"sparkle:tags"] containsObject:@"sparkle:criticalUpdate"];
}
- initWithDictionary:(NSDictionary *)dict
{
return [self initWithDictionary:dict failureReason:nil];
@@ -179,9 +94,9 @@
}
propertiesDictionary = [[NSMutableDictionary alloc] initWithDictionary:dict];
[self setTitle:[dict objectForKey:@"title"]];
[self setDate:[dict objectForKey:@"pubDate"]];
[self setItemDescription:[dict objectForKey:@"description"]];
self.title = [dict objectForKey:@"title"];
self.date = [dict objectForKey:@"pubDate"];
self.itemDescription = [dict objectForKey:@"description"];
NSString* theInfoURL = [dict objectForKey:@"link"];
if( theInfoURL )
@@ -189,7 +104,7 @@
if( ![theInfoURL isKindOfClass: [NSString class]] )
SULog(@"SUAppcastItem -initWithDictionary: Info URL is not of valid type.");
else
[self setInfoURL:[NSURL URLWithString:theInfoURL]];
self.infoURL = [NSURL URLWithString:theInfoURL];
}
// Need an info URL or an enclosure URL. Former to show "More Info"
@@ -212,40 +127,37 @@
}
if( enclosureURLString )
[self setFileURL: [NSURL URLWithString: [enclosureURLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
self.fileURL = [NSURL URLWithString: [enclosureURLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
if( enclosure )
[self setDSASignature:[enclosure objectForKey:@"sparkle:dsaSignature"]];
self.DSASignature = [enclosure objectForKey:@"sparkle:dsaSignature"];
[self setVersionString: newVersion];
[self setMinimumSystemVersion: [dict objectForKey:@"sparkle:minimumSystemVersion"]];
[self setMaximumSystemVersion: [dict objectForKey:@"sparkle:maximumSystemVersion"]];
self.versionString = newVersion;
self.minimumSystemVersion = [dict objectForKey:@"sparkle:minimumSystemVersion"];
self.maximumSystemVersion = [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];
self.displayVersionString = shortVersionString;
else
[self setDisplayVersionString: [self versionString]];
self.displayVersionString = [self versionString];
// Find the appropriate release notes URL.
if ([dict objectForKey:@"sparkle:releaseNotesLink"])
[self setReleaseNotesURL:[NSURL URLWithString:[dict objectForKey:@"sparkle:releaseNotesLink"]]];
else if ([[self itemDescription] hasPrefix:@"http://"] || [[self itemDescription] hasPrefix:@"https://"]) // if the description starts with http:// or https:// use that.
[self setReleaseNotesURL:[NSURL URLWithString:[self itemDescription]]];
self.releaseNotesURL = [NSURL URLWithString:[dict objectForKey:@"sparkle:releaseNotesLink"]];
else if ([self.itemDescription hasPrefix:@"http://"] || [self.itemDescription hasPrefix:@"https://"]) // if the description starts with http:// or https:// use that.
self.releaseNotesURL = [NSURL URLWithString:self.itemDescription];
else
[self setReleaseNotesURL:nil];
self.releaseNotesURL = 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];
for (NSDictionary *deltaDictionary in [deltaDictionaries objectEnumerator]) {
NSMutableDictionary *fakeAppCastDict = [dict mutableCopy];
[fakeAppCastDict removeObjectForKey:@"deltas"];
[fakeAppCastDict setObject:deltaDictionary forKey:@"enclosure"];
SUAppcastItem *deltaItem = [[[self class] alloc] initWithDictionary:fakeAppCastDict];
@@ -253,8 +165,8 @@
[deltas setObject:deltaItem forKey:[deltaDictionary objectForKey:@"sparkle:deltaFrom"]];
[deltaItem release];
}
[self setDeltaUpdates:deltas];
}
self.deltaUpdates = deltas;
}
}
return self;
@@ -262,16 +174,16 @@
- (void)dealloc
{
[self setTitle:nil];
[self setDate: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];
self.title = nil;
self.date = nil;
self.itemDescription = nil;
self.releaseNotesURL = nil;
self.DSASignature = nil;
self.minimumSystemVersion = nil;
self.fileURL = nil;
self.versionString = nil;
self.displayVersionString = nil;
self.infoURL = nil;
[propertiesDictionary release];
[super dealloc];
}
+5 -5
View File
@@ -11,6 +11,8 @@
#import "SUWindowController.h"
@protocol SUAutomaticUpdateAlertDelegateProtocol;
typedef enum
{
SUInstallNowChoice,
@@ -21,20 +23,18 @@ typedef enum
@class SUAppcastItem, SUHost;
@interface SUAutomaticUpdateAlert : SUWindowController {
SUAppcastItem *updateItem;
id delegate;
id<SUAutomaticUpdateAlertDelegateProtocol> delegate;
SUHost *host;
IBOutlet NSButton *automaticUpdateButton;
}
- (id)initWithAppcastItem:(SUAppcastItem *)item host:(SUHost *)hostBundle delegate:delegate;
- (id)initWithAppcastItem:(SUAppcastItem *)item host:(SUHost *)hostBundle delegate:(id<SUAutomaticUpdateAlertDelegateProtocol>)delegate;
- (IBAction)installNow:sender;
- (IBAction)installLater:sender;
- (IBAction)doNotInstall:sender;
- (IBAction)toggleAutomaticallyDownloadUpdate:(id)sender;
@end
@interface NSObject (SUAutomaticUpdateAlertDelegateProtocol)
@protocol SUAutomaticUpdateAlertDelegateProtocol <NSObject>
- (void)automaticUpdateAlert:(SUAutomaticUpdateAlert *)aua finishedWithChoice:(SUAutomaticInstallationChoice)choice;
@end
+17 -14
View File
@@ -12,7 +12,7 @@
@implementation SUAutomaticUpdateAlert
- (id)initWithAppcastItem:(SUAppcastItem *)item host:(SUHost *)aHost delegate:del;
- (id)initWithAppcastItem:(SUAppcastItem *)item host:(SUHost *)aHost delegate:(id<SUAutomaticUpdateAlertDelegateProtocol>)del
{
self = [super initWithHost:aHost windowNibName:@"SUAutomaticUpdateAlert"];
if (self)
@@ -35,12 +35,6 @@
- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@, %@>", [self class], [host bundlePath], [host installationPath]]; }
- (IBAction)toggleAutomaticallyDownloadUpdate:(id)sender
{
BOOL shouldUpdateAutomatically = NSOnState == [automaticUpdateButton state] ? YES : NO;
[host setBool:shouldUpdateAutomatically forUserDefaultsKey:SUAutomaticallyUpdateKey];
}
- (IBAction)installNow:sender
{
[self close];
@@ -66,17 +60,26 @@
- (NSString *)titleText
{
return [NSString stringWithFormat:SULocalizedString(@"A new version of %@ is ready to install!", nil), [host name]];
if ([updateItem isCriticalUpdate])
{
return [NSString stringWithFormat:SULocalizedString(@"An important update to %@ is ready to install", nil), [host name]];
}
else
{
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), [host name], [updateItem displayVersionString]];
}
- (void)awakeFromNib
{
[automaticUpdateButton setState:[host boolForUserDefaultsKey:SUAutomaticallyUpdateKey] ? NSOnState : NSOffState];
if ([updateItem isCriticalUpdate])
{
return [NSString stringWithFormat:SULocalizedString(@"%1$@ %2$@ has been downloaded and is ready to use! This is an important update; would you like to install it and relaunch %1$@ now?", nil), [host name], [updateItem displayVersionString]];
}
else
{
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
+4 -2
View File
@@ -11,13 +11,15 @@
#import <Cocoa/Cocoa.h>
#import "SUBasicUpdateDriver.h"
#import "SUAutomaticUpdateAlert.h"
@class SUAutomaticUpdateAlert;
@interface SUAutomaticUpdateDriver : SUBasicUpdateDriver
@interface SUAutomaticUpdateDriver : SUBasicUpdateDriver <SUUnarchiverDelegate, SUAutomaticUpdateAlertDelegateProtocol>
{
@private
BOOL postponingInstallation, showErrors;
BOOL willUpdateOnTermination;
SUAutomaticUpdateAlert *alert;
NSTimer *showUpdateAlertTimer;
}
@end
+103 -68
View File
@@ -11,90 +11,113 @@
#import "SUAutomaticUpdateAlert.h"
#import "SUHost.h"
#import "SUConstants.h"
#import "SUUpdater_Private.h"
#import "SUXPCURLDownload.h"
// If the user hasn't quit in a week, ask them if they want to relaunch to get the latest bits. It doesn't matter that this measure of "one day" is imprecise.
static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 24 * 7;
@implementation SUAutomaticUpdateDriver
// -------------------------------------------------------------------
#if SPARKLE_IS_COMPATIBLE_WITH_DEVMATE
static NSString * const kSUAutomaticUpdateParamName = @"autoupdate";
- (void)downloadReleaseNotesAndWaitUntilDone
- (void)showUpdateAlert
{
NSURL *releaseNotesURL = [updateItem releaseNotesURL];
if (nil == releaseNotesURL || [releaseNotesURL isFileURL])
return;
NSString *URLString = [releaseNotesURL absoluteString];
URLString = [URLString stringByAppendingFormat:@"%@%@=1", ([releaseNotesURL query] != nil) ? @"&" : @"?", kSUAutomaticUpdateParamName];
releaseNotesURL = [NSURL URLWithString:URLString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:releaseNotesURL];
[request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
[self updateURLRequestIfNeeds:request];
if (SUShouldUseXPCDownloader())
{
[SUXPCURLDownload sendSynchronousRequest:request delegate:nil];
}
else
{
[NSURLConnection sendSynchronousRequest:request returningResponse:NULL error:NULL];
}
}
- (void)didFindValidUpdate
{
// For correct DevMate statistics need to send request for Release Notes.
[self downloadReleaseNotesAndWaitUntilDone];
[super didFindValidUpdate];
}
#endif // SPARKLE_IS_COMPATIBLE_WITH_DEVMATE
// -------------------------------------------------------------------
- (BOOL)shouldShowUI
{
return showErrors;
isInterruptible = NO;
alert = [[SUAutomaticUpdateAlert alloc] initWithAppcastItem:updateItem host:host delegate:self];
// If the app is a menubar app or the like, we need to focus it first and alter the
// update prompt to behave like a normal window. Otherwise if the window were hidden
// there may be no way for the application to be activated to make it visible again.
if ([host isBackgroundApplication])
{
[[alert window] setHidesOnDeactivate:NO];
[NSApp activateIgnoringOtherApps:YES];
}
if ([NSApp isActive])
[[alert window] makeKeyAndOrderFront:self];
else
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:) name:NSApplicationDidBecomeActiveNotification object:NSApp];
}
- (void)unarchiverDidFinish:(SUUnarchiver *)ua
{
BOOL canAutomaticallyInstallUpdate = NO;
if ([[updater delegate] respondsToSelector:@selector(updater:canAutomaticallyInstallUpdate:)])
canAutomaticallyInstallUpdate = [[updater delegate] updater:updater canAutomaticallyInstallUpdate:updateItem];
if (!canAutomaticallyInstallUpdate)
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:) name:NSApplicationWillTerminateNotification object:nil];
// Sudden termination is available on 10.6+
NSProcessInfo *processInfo = [NSProcessInfo processInfo];
if ([processInfo respondsToSelector:@selector(disableSuddenTermination)]) {
[processInfo disableSuddenTermination];
}
willUpdateOnTermination = YES;
if ([[updater delegate] respondsToSelector:@selector(updater:willInstallUpdateOnQuit:immediateInstallationInvocation:)])
{
showErrors = YES;
alert = [[SUAutomaticUpdateAlert alloc] initWithAppcastItem:updateItem host:host delegate:self];
// If the app is a menubar app or the like, we need to focus it first and alter the
// update prompt to behave like a normal window. Otherwise if the window were hidden
// there may be no way for the application to be activated to make it visible again.
if ([host isBackgroundApplication])
{
[[alert window] setHidesOnDeactivate:NO];
[NSApp activateIgnoringOtherApps:YES];
}
if ([NSApp isActive])
[[alert window] makeKeyAndOrderFront:self];
else
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:) name:NSApplicationDidBecomeActiveNotification object:NSApp];
BOOL relaunch = YES;
BOOL showUI = NO;
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[[self class] instanceMethodSignatureForSelector:@selector(installWithToolAndRelaunch:displayingUserInterface:)]];
[invocation setSelector:@selector(installWithToolAndRelaunch:displayingUserInterface:)];
[invocation setArgument:&relaunch atIndex:2];
[invocation setArgument:&showUI atIndex:3];
[invocation setTarget:self];
[[updater delegate] updater:updater willInstallUpdateOnQuit:updateItem immediateInstallationInvocation:invocation];
}
// If this is marked as a critical update, we'll prompt the user to install it right away.
if ([updateItem isCriticalUpdate])
{
[self showUpdateAlert];
}
else
{
[self automaticUpdateAlert:nil finishedWithChoice:SUInstallNowChoice];
showUpdateAlertTimer = [[NSTimer scheduledTimerWithTimeInterval:SUAutomaticUpdatePromptImpatienceTimer target:self selector:@selector(showUpdateAlert) userInfo:nil repeats:NO] retain];
// At this point the driver is idle, allow it to be interrupted for user-initiated update checks.
isInterruptible = YES;
}
}
- (void)stopUpdatingOnTermination
{
if (willUpdateOnTermination)
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:NSApplicationWillTerminateNotification object:nil];
NSProcessInfo *processInfo = [NSProcessInfo processInfo];
if ([processInfo respondsToSelector:@selector(enableSuddenTermination)]) {
[processInfo enableSuddenTermination];
}
willUpdateOnTermination = NO;
if ([[updater delegate] respondsToSelector:@selector(updater:didCancelInstallUpdateOnQuit:)])
[[updater delegate] updater:updater didCancelInstallUpdateOnQuit:updateItem];
}
}
- (void)invalidateShowUpdateAlertTimer
{
[showUpdateAlertTimer invalidate];
[showUpdateAlertTimer release];
showUpdateAlertTimer = nil;
}
- (void)dealloc
{
[self stopUpdatingOnTermination];
[self invalidateShowUpdateAlertTimer];
[alert release];
[super dealloc];
}
- (void)abortUpdate
{
[self stopUpdatingOnTermination];
[self invalidateShowUpdateAlertTimer];
[super abortUpdate];
}
- (void)applicationDidBecomeActive:(NSNotification *)aNotification
{
[[alert window] makeKeyAndOrderFront:self];
[[NSNotificationCenter defaultCenter] removeObserver:self name:NSApplicationDidBecomeActiveNotification object:NSApp];
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"NSApplicationDidBecomeActiveNotification" object:NSApp];
}
- (void)automaticUpdateAlert:(SUAutomaticUpdateAlert *)aua finishedWithChoice:(SUAutomaticInstallationChoice)choice;
@@ -102,23 +125,35 @@ static NSString * const kSUAutomaticUpdateParamName = @"autoupdate";
switch (choice)
{
case SUInstallNowChoice:
[self stopUpdatingOnTermination];
[self installWithToolAndRelaunch:YES];
break;
case SUInstallLaterChoice:
postponingInstallation = YES;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:) name:NSApplicationWillTerminateNotification object:nil];
// We're already waiting on quit, just indicate that we're idle.
isInterruptible = YES;
break;
case SUDoNotInstallChoice:
[host setObject:[updateItem versionString] forUserDefaultsKey:SUSkippedVersionKey];
[self abortUpdate:SUUpdateAbortCanceledByUser];
[self abortUpdate];
break;
}
}
- (BOOL)shouldInstallSynchronously { return postponingInstallation; }
- (void)installWithToolAndRelaunch:(BOOL)relaunch displayingUserInterface:(BOOL)showUI
{
if (relaunch)
[self stopUpdatingOnTermination];
showErrors = YES;
[super installWithToolAndRelaunch:relaunch displayingUserInterface:showUI];
}
- (void)applicationWillTerminate:(NSNotification *)note
{
[self installWithToolAndRelaunch:NO];
@@ -129,7 +164,7 @@ static NSString * const kSUAutomaticUpdateParamName = @"autoupdate";
if (showErrors)
[super abortUpdateWithError:error];
else
[self abortUpdate:SUUpdateAbortGotError];
[self abortUpdate];
}
@end
+7 -7
View File
@@ -11,9 +11,11 @@
#import <Cocoa/Cocoa.h>
#import "SUUpdateDriver.h"
#import "SUUnarchiver.h"
#import "SUAppcast.h"
@class SUAppcastItem, SUUnarchiver, SUAppcast, SUUnarchiver, SUHost;
@interface SUBasicUpdateDriver : SUUpdateDriver {
@class SUAppcastItem, SUHost;
@interface SUBasicUpdateDriver : SUUpdateDriver<NSURLDownloadDelegate, SUUnarchiverDelegate, SUAppcastDelegate> {
SUAppcastItem *updateItem;
SUAppcastItem *nonDeltaUpdateItem;
@@ -26,9 +28,6 @@
- (void)checkForUpdatesAtURL:(NSURL *)URL host:(SUHost *)host;
- (void)appcastDidFinishLoading:(SUAppcast *)ac;
- (void)appcast:(SUAppcast *)ac failedToLoadWithError:(NSError *)error;
- (BOOL)isItemNewer:(SUAppcastItem *)ui;
- (BOOL)hostSupportsItem:(SUAppcastItem *)ui;
- (BOOL)itemContainsSkippedVersion:(SUAppcastItem *)ui;
@@ -36,7 +35,6 @@
- (void)didFindValidUpdate;
- (void)didNotFindUpdate;
- (void)updateURLRequestIfNeeds:(NSMutableURLRequest *)request;
- (void)downloadUpdate;
- (void)download:(NSURLDownload *)d decideDestinationWithSuggestedFilename:(NSString *)name;
- (void)downloadDidFinish:(NSURLDownload *)d;
@@ -48,10 +46,12 @@
- (void)failedToApplyDeltaUpdate;
- (void)installWithToolAndRelaunch:(BOOL)relaunch;
- (void)installWithToolAndRelaunch:(BOOL)relaunch displayingUserInterface:(BOOL)showUI;
- (void)installerForHost:(SUHost *)host failedWithError:(NSError *)error;
- (void)cleanUpDownload;
- (void)abortUpdate:(SUUpdateAbortReason)reason;
- (void)abortUpdate;
- (void)abortUpdateWithError:(NSError *)error;
@end
+67 -178
View File
@@ -20,16 +20,29 @@
#import "SUBinaryDeltaCommon.h"
#import "SUCodeSigningVerifier.h"
#import "SUUpdater_Private.h"
#import "SUXPCInstaller.h"
#import "SUXPCURLDownload.h"
#if SPARKLE_IS_COMPATIBLE_WITH_DEVMATE
CF_EXPORT CFDictionaryRef DMCopyHTTPRequestHeaders(CFBundleRef appBundle, CFDataRef httpBodyData);
#ifdef FINISH_INSTALL_TOOL_NAME
// FINISH_INSTALL_TOOL_NAME expands to unquoted finish_install
#define QUOTE_NS_STRING2(str) @"" #str
#define QUOTE_NS_STRING1(str) QUOTE_NS_STRING2(str)
#define FINISH_INSTALL_TOOL_NAME_STRING QUOTE_NS_STRING1(FINISH_INSTALL_TOOL_NAME)
#else
#error FINISH_INSTALL_TOOL_NAME not defined
#endif
@interface SUBasicUpdateDriver () <NSURLDownloadDelegate>; @end
@interface SUBasicUpdateDriver () <NSURLDownloadDelegate>
@end
@interface SUBasicUpdateDriver () <NSURLDownloadDelegate>
@end
@implementation SUBasicUpdateDriver
- (void)checkForUpdatesAtURL:(NSURL *)URL host:(SUHost *)aHost
@@ -105,6 +118,9 @@ CF_EXPORT CFDictionaryRef DMCopyHTTPRequestHeaders(CFBundleRef appBundle, CFData
{
if ([[updater delegate] respondsToSelector:@selector(updater:didFinishLoadingAppcast:)])
[[updater delegate] updater:updater didFinishLoadingAppcast:ac];
NSDictionary *userInfo = (ac != nil) ? @{SUUpdaterAppcastNotificationKey : ac} : nil;
[[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterDidFinishLoadingAppCastNotification object:updater userInfo:userInfo];
SUAppcastItem *item = nil;
@@ -146,28 +162,12 @@ CF_EXPORT CFDictionaryRef DMCopyHTTPRequestHeaders(CFBundleRef appBundle, CFData
[self abortUpdateWithError:error];
}
- (void)appcast:(SUAppcast *)appcast willFetchURLRequest:(NSMutableURLRequest *)request
{
[self updateURLRequestIfNeeds:request];
}
- (void)updateURLRequestIfNeeds:(NSMutableURLRequest *)request
{
#if SPARKLE_IS_COMPATIBLE_WITH_DEVMATE
CFBundleRef hostBundle = CFBundleCreate(kCFAllocatorDefault, (CFURLRef)[NSURL fileURLWithPath:[host bundlePath]]);
NSDictionary *devmateHeaders = (NSDictionary *)DMCopyHTTPRequestHeaders(hostBundle, NULL) ? : [NSDictionary new];
[request setAllHTTPHeaderFields:(NSDictionary *)devmateHeaders];
[devmateHeaders release];
if (NULL != hostBundle)
CFRelease(hostBundle);
#endif
}
- (void)didFindValidUpdate
{
if ([[updater delegate] respondsToSelector:@selector(updater:didFindValidUpdate:)])
[[updater delegate] updater:updater didFindValidUpdate:updateItem];
NSDictionary *userInfo = (updateItem != nil) ? @{SUUpdaterAppcastItemNotificationKey : updateItem} : nil;
[[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterDidFinishLoadingAppCastNotification object:updater userInfo:userInfo];
[self downloadUpdate];
}
@@ -175,6 +175,8 @@ CF_EXPORT CFDictionaryRef DMCopyHTTPRequestHeaders(CFBundleRef appBundle, CFData
{
if ([[updater delegate] respondsToSelector:@selector(updaterDidNotFindUpdate:)])
[[updater delegate] updaterDidNotFindUpdate:updater];
[[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterDidNotFindUpdateNotification object: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]]];
}
@@ -182,24 +184,11 @@ CF_EXPORT CFDictionaryRef DMCopyHTTPRequestHeaders(CFBundleRef appBundle, CFData
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[updateItem fileURL]];
[request setValue:[updater userAgentString] forHTTPHeaderField:@"User-Agent"];
[self updateURLRequestIfNeeds:request];
if (SUShouldUseXPCDownloader())
download = (NSURLDownload *)[[SUXPCURLDownload alloc] initWithRequest:request delegate:self];
else
download = [[NSURLDownload alloc] initWithRequest:request delegate:self];
download = [[NSURLDownload alloc] initWithRequest:request delegate:self];
}
- (void)download:(NSURLDownload *)d decideDestinationWithSuggestedFilename:(NSString *)name
{
if (SUShouldUseXPCDownloader())
{
// The downloader will determine a file name, somewhere within our sandbox.
downloadPath = nil;
[d setDestination:name allowOverwrite:YES];
return;
}
// If name ends in .txt, the server probably has a stupid MIME configuration. We'll give the developer the benefit of the doubt and chop that off.
if ([[name pathExtension] isEqualToString:@"txt"])
name = [name stringByDeletingPathExtension];
@@ -217,19 +206,7 @@ CF_EXPORT CFDictionaryRef DMCopyHTTPRequestHeaders(CFBundleRef appBundle, CFData
}
// 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 this user's file structure.
@@ -241,13 +218,6 @@ CF_EXPORT CFDictionaryRef DMCopyHTTPRequestHeaders(CFBundleRef appBundle, CFData
[download setDestination:downloadPath allowOverwrite:YES];
}
- (void)download:(NSURLDownload *)download didCreateDestination:(NSString *)path {
[downloadPath autorelease];
downloadPath = [path retain];
[tempDir autorelease];
tempDir = [[downloadPath stringByDeletingLastPathComponent] retain];
}
- (BOOL)validateUpdateDownloadedToPath:(NSString *)downloadedPath extractedToPath:(NSString *)extractedPath DSASignature:(NSString *)DSASignature publicDSAKey:(NSString *)publicDSAKey
{
NSString *newBundlePath = [SUInstaller appPathInUpdateFolder:extractedPath forHost:host];
@@ -282,7 +252,7 @@ CF_EXPORT CFDictionaryRef DMCopyHTTPRequestHeaders(CFBundleRef appBundle, CFData
}
- (void)extractUpdate
{
{
SUUnarchiver *unarchiver = [SUUnarchiver unarchiverForPath:downloadPath updatingHost:host];
if (!unarchiver)
{
@@ -326,6 +296,12 @@ CF_EXPORT CFDictionaryRef DMCopyHTTPRequestHeaders(CFBundleRef appBundle, CFData
- (BOOL)shouldInstallSynchronously { return NO; }
- (void)installWithToolAndRelaunch:(BOOL)relaunch
{
// Perhaps a poor assumption but: if we're not relaunching, we assume we shouldn't be showing any UI either. Because non-relaunching installations are kicked off without any user interaction, we shouldn't be interrupting them.
[self installWithToolAndRelaunch:relaunch displayingUserInterface:relaunch];
}
- (void)installWithToolAndRelaunch:(BOOL)relaunch displayingUserInterface:(BOOL)showUI
{
#if !ENDANGER_USERS_WITH_INSECURE_UPDATES
if (![self validateUpdateDownloadedToPath:downloadPath extractedToPath:tempDir DSASignature:[updateItem DSASignature] publicDSAKey:[host publicDSAKey]])
@@ -337,7 +313,7 @@ CF_EXPORT CFDictionaryRef DMCopyHTTPRequestHeaders(CFBundleRef appBundle, CFData
if (![updater mayUpdateAndRestart])
{
[self abortUpdate:SUUpdateAbortForbiddenByDelegate];
[self abortUpdate];
return;
}
@@ -357,82 +333,28 @@ CF_EXPORT CFDictionaryRef DMCopyHTTPRequestHeaders(CFBundleRef appBundle, CFData
if ([[updater delegate] respondsToSelector:@selector(updater:willInstallUpdate:)])
[[updater delegate] updater:updater willInstallUpdate:updateItem];
SUFinishUpdateTask finishTasks = SUFinishUpdateWithDefaultInstallation;
BOOL shouldRelaunch = YES;
if ([[updater delegate] respondsToSelector:@selector(updater:overrideInstallUpdate:downloadPath:shouldRelaunch:)] &&
[[updater delegate] updater:updater overrideInstallUpdate:updateItem downloadPath:tempDir shouldRelaunch:&shouldRelaunch])
{
finishTasks = finishTasks & (~SUFinishUpdateWithInstall);
relaunch = relaunch && shouldRelaunch;
}
if (!relaunch)
{
finishTasks = finishTasks & (~SUFinishUpdateWithRelaunch);
}
if (SUFinishUpdateAbort == finishTasks)
{
[self abortUpdate:SUUpdateAbortTasksFinished];
if ([[updater delegate] respondsToSelector:@selector(updater:didInstallUpdate:)])
[[updater delegate] updater:updater didInstallUpdate:updateItem];
NSString *const finishInstallToolName = FINISH_INSTALL_TOOL_NAME_STRING;
return;
}
// Copy the relauncher into a temporary directory so we can get to it after the new version's installed.
NSString *relaunchPathToCopy = [SPARKLE_BUNDLE pathForResource:@"finish_installation" ofType:@"app"];
NSString *targetPath = [[host appSupportPath] stringByAppendingPathComponent:[relaunchPathToCopy lastPathComponent]];
// Only the paranoid survive: if there's already a stray copy of relaunch there, we would have problems.
NSError *error = nil;
[[NSFileManager defaultManager] createDirectoryAtPath:[targetPath stringByDeletingLastPathComponent]
withIntermediateDirectories:YES
attributes:[NSDictionary dictionary]
error:&error];
NSString *relaunchPathToCopy = [SPARKLE_BUNDLE pathForResource:finishInstallToolName ofType:@"app"];
if (relaunchPathToCopy != nil)
{
NSString *targetPath = [[host appSupportPath] stringByAppendingPathComponent:[relaunchPathToCopy lastPathComponent]];
// Only the paranoid survive: if there's already a stray copy of relaunch there, we would have problems.
NSError *error = nil;
[[NSFileManager defaultManager] createDirectoryAtPath: [targetPath stringByDeletingLastPathComponent] withIntermediateDirectories: YES attributes: [NSDictionary dictionary] error: &error];
// Only the paranoid survive: if there's already a stray copy of relaunch there, we would have problems.
BOOL copiedRelaunchTool = NO;
if (SUShouldUseXPCInstaller())
{
copiedRelaunchTool = [SUXPCInstaller copyPathWithAuthentication:relaunchPathToCopy overPath:targetPath temporaryName:nil error:&error];
}
else
{
copiedRelaunchTool = [SUPlainInstaller copyPathWithAuthentication:relaunchPathToCopy overPath:targetPath temporaryName:nil error:&error];
}
[self finishRelaunchAfterSuccessfulCopying:copiedRelaunchTool fromPath:relaunchPathToCopy toPath:targetPath finishTaskMask:finishTasks];
}
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]]];
}
- (void)finishRelaunchAfterSuccessfulCopying:(BOOL)copiedRelaunchTool fromPath:(NSString *)relaunchPathToCopy toPath:(NSString *)targetPath finishTaskMask:(SUFinishUpdateTask)taskMask
{
NSError *error = nil;
if (copiedRelaunchTool)
{
relaunchPath = [targetPath retain];
}
else
{
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SURelaunchError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:SULocalizedString(@"An error occurred while extracting the archive. Please try again later.", nil), NSLocalizedDescriptionKey, [NSString stringWithFormat:@"Couldn't copy relauncher (%@) to temporary path (%@)! %@", relaunchPathToCopy, targetPath, (error ? [error localizedDescription] : @"")], NSLocalizedFailureReasonErrorKey, nil]]];
}
NSString *pathToRelaunch = @"";
BOOL shouldFinishUpdateWithRelaunch = (taskMask & SUFinishUpdateWithRelaunch) != 0;
if (shouldFinishUpdateWithRelaunch)
{
[[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterWillRestartNotification object:self];
if ([[updater delegate] respondsToSelector:@selector(updaterWillRelaunchApplication:)])
{
[[updater delegate] updaterWillRelaunchApplication:updater];
}
pathToRelaunch = [host bundlePath];
if ([[updater delegate] respondsToSelector:@selector(pathToRelaunchForUpdater:)])
{
pathToRelaunch = [[updater delegate] pathToRelaunchForUpdater:updater];
}
}
[[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterWillRestartNotification object:self];
if ([[updater delegate] respondsToSelector:@selector(updaterWillRelaunchApplication:)])
[[updater delegate] updaterWillRelaunchApplication:updater];
if(!relaunchPath || ![[NSFileManager defaultManager] fileExistsAtPath:relaunchPath])
{
@@ -440,47 +362,22 @@ CF_EXPORT CFDictionaryRef DMCopyHTTPRequestHeaders(CFBundleRef appBundle, CFData
[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"] stringByAppendingPathComponent: finishInstallToolName];
[NSTask launchedTaskWithLaunchPath: relaunchToolPath arguments:[NSArray arrayWithObjects:
[host bundlePath],
pathToRelaunch,
[NSString stringWithFormat:@"%d", [[NSProcessInfo processInfo] processIdentifier]],
tempDir,
relaunch ? @"1" : @"0",
showUI ? @"1" : @"0",
nil]];
NSString *relaunchToolPath = [relaunchPath stringByAppendingPathComponent: @"/Contents/MacOS/finish_installation"];
NSArray *arguments = [NSArray arrayWithObjects:
[host bundlePath],
pathToRelaunch,
[NSString stringWithFormat:@"%d", [[NSProcessInfo processInfo] processIdentifier]],
tempDir,
[NSString stringWithFormat:@"%lu", taskMask],
nil];
if (SUShouldUseXPCInstaller())
{
[SUXPCInstaller launchTaskWithPath:relaunchToolPath
arguments:arguments
environment:nil
currentDirectoryPath:nil
inputData:nil
waitForTaskResult:!shouldFinishUpdateWithRelaunch
waitUntilDone:YES
completionHandler:nil];
}
else
{
NSTask *task = [NSTask launchedTaskWithLaunchPath:relaunchToolPath arguments:arguments];
if (!shouldFinishUpdateWithRelaunch)
[task waitUntilExit];
}
if (shouldFinishUpdateWithRelaunch)
{
[NSApp terminate:nil];
}
else
{
[self abortUpdate:SUUpdateAbortTasksFinished];
if ([[updater delegate] respondsToSelector:@selector(updater:didInstallUpdate:)])
[[updater delegate] updater:updater didInstallUpdate:updateItem];
}
[NSApp terminate:self];
}
- (void)cleanUpDownload
@@ -488,12 +385,8 @@ CF_EXPORT CFDictionaryRef DMCopyHTTPRequestHeaders(CFBundleRef appBundle, CFData
if (tempDir != nil) // tempDir contains downloadPath, so we implicitly delete both here.
{
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];
}
@@ -502,21 +395,17 @@ CF_EXPORT CFDictionaryRef DMCopyHTTPRequestHeaders(CFBundleRef appBundle, CFData
- (void)installerForHost:(SUHost *)aHost failedWithError:(NSError *)error
{
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:(SUUpdateAbortReason)reason
- (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:reason];
[super abortUpdate];
}
- (void)abortUpdateWithError:(NSError *)error
@@ -527,7 +416,7 @@ CF_EXPORT CFDictionaryRef DMCopyHTTPRequestHeaders(CFBundleRef appBundle, CFData
SULog(@"Sparkle Error (continued): %@", [error localizedFailureReason]);
if (download)
[download cancel];
[self abortUpdate:SUUpdateAbortGotError];
[self abortUpdate];
}
- (void)dealloc
+3 -11
View File
@@ -44,7 +44,7 @@ NSString *temporaryFilename(NSString *base)
NSString *template = [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.XXXXXXXXXX", base]];
char buffer[MAXPATHLEN];
strcpy(buffer, [template fileSystemRepresentation]);
return [NSString stringWithUTF8String:mktemp(buffer)];
return [NSString stringWithUTF8String:mkstemp(buffer)];
}
static void _hashOfBuffer(unsigned char *hash, const char* buffer, size_t bufferLength)
@@ -148,18 +148,10 @@ NSString *hashOfTree(NSString *path)
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
[[NSFileManager defaultManager] removeItemAtPath:path error:nil];
}
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
[[NSFileManager defaultManager] copyItemAtPath:source toPath:dest error:nil];
}
+1 -2
View File
@@ -12,8 +12,7 @@
#import <Cocoa/Cocoa.h>
#import "SUUnarchiver.h"
@interface SUBinaryDeltaUnarchiver : SUUnarchiver {
}
@interface SUBinaryDeltaUnarchiver : SUUnarchiver
@end
+1
View File
@@ -11,6 +11,7 @@
#import "SUBinaryDeltaApply.h"
#import "SUUnarchiver_Private.h"
#import "SUHost.h"
#import "NTSynchronousTask.h"
@implementation SUBinaryDeltaUnarchiver
-8
View File
@@ -12,16 +12,8 @@
#import <Foundation/Foundation.h>
@interface SUCodeSigningVerifier : NSObject
+ (BOOL)codeSignatureIsValidAtPath:(NSString *)destinationPath error:(NSError **)error;
+ (BOOL)hostApplicationIsCodeSigned;
+ (BOOL)hostApplicationIsSandboxed;
+ (BOOL)hostAppAllowsNetworkOutgoingConnections;
@end
FOUNDATION_EXTERN BOOL SUShouldUseXPCDownloader(void);
FOUNDATION_EXTERN BOOL SUShouldUseXPCInstaller(void);
#endif
+15 -143
View File
@@ -13,11 +13,13 @@
@implementation SUCodeSigningVerifier
extern OSStatus SecCodeCopySelf(SecCSFlags flags, SecCodeRef *self) __attribute__((weak_import));
extern OSStatus SecCodeCopyDesignatedRequirement(SecStaticCodeRef code, SecCSFlags flags, SecRequirementRef *requirement) __attribute__((weak_import));
extern OSStatus SecStaticCodeCreateWithPath(CFURLRef path, SecCSFlags flags, SecStaticCodeRef *staticCode) __attribute__((weak_import));
extern OSStatus SecStaticCodeCheckValidityWithErrors(SecStaticCodeRef staticCode, SecCSFlags flags, SecRequirementRef requirement, CFErrorRef *errors) __attribute__((weak_import));
extern OSStatus SecRequirementCreateWithString(CFStringRef text, SecCSFlags flags, SecRequirementRef *requirement) __attribute__((weak_import));
extern OSStatus SecCodeCheckValidity(SecCodeRef code, SecCSFlags flags, SecRequirementRef requirement) __attribute__((weak_import));
+ (BOOL)codeSignatureIsValidAtPath:(NSString *)destinationPath error:(NSError **)error
{
@@ -66,149 +68,19 @@ finally:
+ (BOOL)hostApplicationIsCodeSigned
{
static BOOL sIsCodesigned = NO;
// This API didn't exist prior to 10.6.
if (SecCodeCopySelf == NULL) return NO;
static BOOL onceToken = NO;
while (!onceToken)
{
onceToken = YES;
// This API didn't exist prior to 10.6.
if (SecCodeCopySelf == NULL)
break;
OSStatus result;
SecCodeRef hostCode = NULL;
result = SecCodeCopySelf(kSecCSDefaultFlags, &hostCode);
if (result != 0) return NO;
SecCodeRef hostCode = NULL;
OSStatus result = SecCodeCopySelf(kSecCSDefaultFlags, &hostCode);
if (result != noErr)
break;
SecRequirementRef requirement = NULL;
result = SecCodeCopyDesignatedRequirement(hostCode, kSecCSDefaultFlags, &requirement);
if (hostCode) CFRelease(hostCode);
if (requirement) CFRelease(requirement);
sIsCodesigned = (noErr == result);
}
return sIsCodesigned;
}
+ (BOOL)hostApplicationIsSandboxed
{
static BOOL sIsAppSandboxed = NO;
static BOOL onceToken = NO;
while (!onceToken)
{
onceToken = YES;
// This API didn't exist prior to 10.6
if (SecCodeCopySelf == NULL)
break;
SecCodeRef hostCode = NULL;
SecRequirementRef hostRequirement = NULL;
#define Cleanup() \
{ \
if (hostCode) CFRelease(hostCode); \
if (hostRequirement) CFRelease(hostRequirement); \
}
OSStatus status = SecCodeCopySelf(kSecCSDefaultFlags, &hostCode);
if (status != noErr || hostCode == NULL)
{
Cleanup();
break;
}
CFStringRef requirementString = CFSTR("entitlement[\"com.apple.security.app-sandbox\"] exists");
status = SecRequirementCreateWithString(requirementString, kSecCSDefaultFlags, &hostRequirement);
if (status != noErr || hostRequirement == NULL)
{
Cleanup();
break;
}
status = SecCodeCheckValidity(hostCode, kSecCSDefaultFlags, hostRequirement);
sIsAppSandboxed = (noErr == status);
Cleanup();
}
return sIsAppSandboxed;
}
+ (BOOL)hostAppAllowsNetworkOutgoingConnections
{
static BOOL sIsAppAllowsOutgoingConnections = NO;
static BOOL onceToken = NO;
while (!onceToken)
{
onceToken = YES;
if (![self hostApplicationIsSandboxed])
{
sIsAppAllowsOutgoingConnections = YES;
break;
}
SecCodeRef hostCode = NULL;
SecRequirementRef hostRequirement = NULL;
#define Cleanup() \
{ \
if (hostCode) CFRelease(hostCode); \
if (hostRequirement) CFRelease(hostRequirement); \
}
OSStatus status = SecCodeCopySelf(kSecCSDefaultFlags, &hostCode);
if (status != noErr || hostCode == NULL)
{
Cleanup();
break;
}
CFStringRef requirementString = CFSTR("entitlement[\"com.apple.security.network.client\"] exists");
status = SecRequirementCreateWithString(requirementString, kSecCSDefaultFlags, &hostRequirement);
if (status != noErr || hostRequirement == NULL)
{
Cleanup();
break;
}
status = SecCodeCheckValidity(hostCode, kSecCSDefaultFlags, hostRequirement);
sIsAppAllowsOutgoingConnections = (noErr == status);
Cleanup();
}
return sIsAppAllowsOutgoingConnections;
SecRequirementRef requirement = NULL;
result = SecCodeCopyDesignatedRequirement(hostCode, kSecCSDefaultFlags, &requirement);
if (hostCode) CFRelease(hostCode);
if (requirement) CFRelease(requirement);
return (result == 0);
}
@end
#pragma mark -
BOOL SUShouldUseXPCDownloader(void)
{
if ([SUCodeSigningVerifier hostAppAllowsNetworkOutgoingConnections])
return NO;
NSString *xpcServicePrefixPath = [[NSBundle mainBundle] bundlePath];
NSString *xpcServiceSuffixPath = @"Contents/XPCServices/com.devmate.UpdateDownloader.xpc";
return [[NSFileManager defaultManager] fileExistsAtPath:[xpcServicePrefixPath stringByAppendingPathComponent:xpcServiceSuffixPath]];
}
BOOL SUShouldUseXPCInstaller(void)
{
if (![SUCodeSigningVerifier hostApplicationIsSandboxed])
return NO;
NSString *xpcServicePrefixPath = [[NSBundle mainBundle] bundlePath];
NSString *xpcServiceSuffixPath = @"Contents/XPCServices/com.devmate.UpdateInstaller.xpc";
return [[NSFileManager defaultManager] fileExistsAtPath:[xpcServicePrefixPath stringByAppendingPathComponent:xpcServiceSuffixPath]];
}
-25
View File
@@ -10,8 +10,6 @@
#ifndef SUCONSTANTS_H
#define SUCONSTANTS_H
#import <Foundation/Foundation.h>
// -----------------------------------------------------------------------------
// Preprocessor flags:
// -----------------------------------------------------------------------------
@@ -39,28 +37,6 @@ extern NSString *const SUUpdaterWillRestartNotification;
extern NSString *const SUTechnicalErrorInformationKey;
// -----------------------------------------------------------------------------
// Typedefs:
// -----------------------------------------------------------------------------
typedef NS_OPTIONS(NSUInteger, SUFinishUpdateTask)
{
SUFinishUpdateAbort = 0,
SUFinishUpdateWithInstall = 1 << 0,
SUFinishUpdateWithRelaunch = 1 << 1,
SUFinishUpdateWithDefaultInstallation = SUFinishUpdateWithInstall | SUFinishUpdateWithRelaunch
};
typedef NS_ENUM(NSUInteger, SUUpdateAbortReason)
{
SUUpdateAbortUndefined = 0,
SUUpdateAbortForbiddenByDelegate,
SUUpdateAbortTasksFinished,
SUUpdateAbortCanceledByUser,
SUUpdateAbortDidNotFind,
SUUpdateAbortGotError
};
// -----------------------------------------------------------------------------
// PList keys::
// -----------------------------------------------------------------------------
@@ -111,7 +87,6 @@ extern OSStatus SUMissingInstallerToolError;
extern OSStatus SURelaunchError;
extern OSStatus SUInstallationError;
extern OSStatus SUDowngradeError;
extern OSStatus SUXPCServiceError;
// -----------------------------------------------------------------------------
+5 -1
View File
@@ -6,6 +6,11 @@
// Copyright 2006 Andy Matuschak. All rights reserved.
//
#import "SUUpdater.h"
#import "SUAppcast.h"
#import "SUAppcastItem.h"
#import "SUVersionComparisonProtocol.h"
#import "SUConstants.h"
NSString *const SUUpdaterWillRestartNotification = @"SUUpdaterWillRestartNotificationName";
@@ -50,4 +55,3 @@ OSStatus SUMissingInstallerToolError = 4003;
OSStatus SURelaunchError = 4004;
OSStatus SUInstallationError = 4005;
OSStatus SUDowngradeError = 4006;
OSStatus SUXPCServiceError = 4007;
+1 -1
View File
@@ -11,7 +11,7 @@
#import <Cocoa/Cocoa.h>
@interface SUDSAVerifier : NSObject {}
@interface SUDSAVerifier : NSObject
+ (BOOL)validatePath:(NSString *)path withEncodedDSASignature:(NSString *)encodedSignature withPublicDSAKey:(NSString *)pkeyString;
@end
+1 -8
View File
@@ -11,9 +11,6 @@
#import <Security/cssm.h>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
/* CDSA Specific */
static CSSM_CSP_HANDLE cdsaInit( void );
static void cdsaRelease( CSSM_CSP_HANDLE cspHandle );
@@ -148,10 +145,8 @@ static NSData *rawKeyData( NSString *key )
// 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)
for (NSString *pkeyLine in [t componentsSeparatedByString:@"\n"])
{
[pkeyTrimmedLines addObject:[pkeyLine stringByTrimmingCharactersInSet:whiteSet]];
}
@@ -358,5 +353,3 @@ static Boolean su_copyBytesToData( CSSM_DATA_PTR data, CSSM_SIZE size, const uin
}
return retval;
}
#pragma GCC diagnostic pop
+1 -2
View File
@@ -12,8 +12,7 @@
#import <Cocoa/Cocoa.h>
#import "SUUnarchiver.h"
@interface SUDiskImageUnarchiver : SUUnarchiver {
}
@interface SUDiskImageUnarchiver : SUUnarchiver
@end
+59 -144
View File
@@ -9,8 +9,6 @@
#import "SUDiskImageUnarchiver.h"
#import "SUUnarchiver_Private.h"
#import "NTSynchronousTask.h"
#import "SUCodeSigningVerifier.h"
#import "SUXPCInstaller.h"
#import "SULog.h"
#import <CoreServices/CoreServices.h>
@@ -24,37 +22,13 @@
// Called on a non-main thread.
- (void)extractDMG
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *hdiutilPath = @"/usr/bin/hdiutil";
NSArray *args = [NSArray arrayWithObjects: @"isencrypted", archivePath, nil];
NSString *currentDirPath = @"/";
__block NSData *result = nil;
if (SUShouldUseXPCInstaller())
{
[SUXPCInstaller launchTaskWithPath:hdiutilPath
arguments:args
environment:nil
currentDirectoryPath:currentDirPath
inputData:nil
waitForTaskResult:YES
waitUntilDone:YES
completionHandler:^(int resultCode, NSData *outputData) {
result = [outputData copy];
}];
[result autorelease];
}
else
{
result = [NTSynchronousTask task:hdiutilPath directory:currentDirPath withArgs:args input:nil];
}
if ([self isEncrypted:result] && [delegate respondsToSelector:@selector(unarchiver:requiresPasswordReturnedViaInvocation:)])
{
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
{
} else {
[self extractDMGWithPassword:nil];
}
@@ -64,6 +38,7 @@
// Called on a non-main thread.
- (void)extractDMGWithPassword:(NSString *)password
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
BOOL mountedSuccessfully = NO;
@@ -71,7 +46,9 @@
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);
@@ -80,139 +57,96 @@
CFStringRef uuidString = CFUUIDCreateString(NULL, uuid);
if (uuidString)
{
mountPoint = [@"/Volumes" stringByAppendingPathComponent:(NSString *)uuidString];
mountPoint = [@"/Volumes" stringByAppendingPathComponent:(NSString*)uuidString];
CFRelease(uuidString);
}
CFRelease(uuid);
}
}
while ([[NSFileManager defaultManager] fileExistsAtPath:mountPoint]);
while (noErr == FSPathMakeRefWithOptions((UInt8 *)[mountPoint fileSystemRepresentation], kFSPathMakeRefDoNotFollowLeafSymlink, &tmpRef, NULL));
NSData *promptData = nil;
if ([password length])
{
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];
}
BOOL shouldUseXPC = SUShouldUseXPCInstaller();
NSString *hdiutilPath = @"/usr/bin/hdiutil";
NSArray* arguments = [NSArray arrayWithObjects:@"attach", archivePath, @"-mountpoint", mountPoint, /*@"-noverify",*/ @"-nobrowse", @"-noautoopen", nil];
NSString *currentDirPath = @"/";
__block NSData *output = nil;
__block NSInteger taskResult = -1;
NSData *output = nil;
NSInteger taskResult = -1;
@try
{
if (shouldUseXPC)
{
[SUXPCInstaller launchTaskWithPath:hdiutilPath
arguments:arguments
environment:nil
currentDirectoryPath:currentDirPath
inputData:promptData
waitForTaskResult:YES
waitUntilDone:YES
completionHandler:^(int result, NSData *outputData) {
taskResult = (NSInteger)result;
output = [outputData copy];
}];
[output autorelease];
}
else
{
NTSynchronousTask* task = [[NTSynchronousTask alloc] init];
[task run:hdiutilPath directory:currentDirPath withArgs:arguments input:promptData];
NTSynchronousTask* task = [[NTSynchronousTask alloc] init];
taskResult = [task result];
output = [[[task output] copy] autorelease];
[task release];
}
[task run:@"/usr/bin/hdiutil" directory:@"/" withArgs:arguments input:promptData];
taskResult = [task result];
output = [[[task output] copy] autorelease];
[task release];
}
@catch (NSException *localException)
{
SULog(@"Got DMG mount exception: %@ - %@", [localException name], [localException reason]);
{
goto reportError;
}
if (taskResult != 0)
{
NSString *resultStr = output ? [[[NSString alloc] initWithData:output encoding:NSUTF8StringEncoding] autorelease] : nil;
if (password != nil &&
[resultStr rangeOfString:@"Authentication error"].location != NSNotFound &&
[delegate respondsToSelector:@selector(unarchiver:requiresPasswordReturnedViaInvocation:)])
{
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);
} else {
SULog( @"hdiutil failed with code: %d data: <<%@>>", taskResult, resultStr );
goto reportError;
}
}
mountedSuccessfully = YES;
// Now that we've mounted it, we need to copy out its contents.
if (floor(NSAppKitVersionNumber) >= NSAppKitVersionNumber10_6)
{
if (shouldUseXPC)
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)
{
NSError *error = nil;
[SUXPCInstaller copyPathContent:mountPoint
toDirectory:[archivePath stringByDeletingLastPathComponent]
error:&error];
if (nil != error)
{
SULog(@"Couldn't copy volume content: %d - %@", [error code], [error localizedDescription]);
goto reportError;
}
SULog(@"Couldn't enumerate contents of archive mounted at %@: %@", mountPoint, error);
goto reportError;
}
else
for (NSString *item in contents)
{
// 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;
}
NSString *fromPath = [mountPoint stringByAppendingPathComponent:item];
NSString *toPath = [[archivePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:item];
NSEnumerator *contentsEnumerator = [contents objectEnumerator];
NSString *item = nil;
while ((item = [contentsEnumerator nextObject]))
// 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])
{
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;
}
SULog(@"Couldn't copy item: %@ : %@", error, error.userInfo ? error.userInfo : @"");
goto reportError;
}
}
}
else
{
SULog(@"This version of Sparkle don't support OS X version earlier than 10.6");
goto reportError;
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];
@@ -223,29 +157,9 @@ reportError:
finally:
if (mountedSuccessfully)
{
NSArray *args = [NSArray arrayWithObjects:@"detach", mountPoint, @"-force", nil];
if (shouldUseXPC)
{
[SUXPCInstaller launchTaskWithPath:hdiutilPath
arguments:args
environment:nil
currentDirectoryPath:nil
inputData:nil
waitForTaskResult:NO
waitUntilDone:NO
completionHandler:nil];
}
else
{
[NSTask launchedTaskWithLaunchPath:hdiutilPath arguments:args];
}
}
[NSTask launchedTaskWithLaunchPath:@"/usr/bin/hdiutil" arguments:[NSArray arrayWithObjects:@"detach", mountPoint, @"-force", nil]];
else
{
SULog(@"Can't mount DMG %@", archivePath);
}
SULog(@"Can't mount DMG %@",archivePath);
[pool drain];
}
@@ -264,8 +178,9 @@ finally:
BOOL result = NO;
if(resultData)
{
NSString *data = [NSString stringWithCString:(char*)[resultData bytes] encoding:NSUTF8StringEncoding];
if (!NSEqualRanges([data rangeOfString:@"passphrase-count"], NSMakeRange(NSNotFound, 0)))
NSString *data = [[[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding] autorelease];
if ((data != nil) && !NSEqualRanges([data rangeOfString:@"passphrase-count"], NSMakeRange(NSNotFound, 0)))
{
result = YES;
}
+1 -1
View File
@@ -17,11 +17,11 @@
NSString *defaultsDomain;
BOOL usesStandardUserDefaults;
}
@property (retain, readonly) NSBundle *bundle;
+ (NSString *)systemVersionString;
- (id)initWithBundle:(NSBundle *)aBundle;
- (NSBundle *)bundle;
- (NSString *)bundlePath;
- (NSString *)appSupportPath;
- (NSString *)installationPath;
+10 -17
View File
@@ -12,15 +12,19 @@
#import <sys/mount.h> // For statfs for isRunningOnReadOnlyVolume
#import "SULog.h"
@interface SUHost ()
@property (retain, readwrite) NSBundle *bundle;
@end
@implementation SUHost
@synthesize bundle;
- (id)initWithBundle:(NSBundle *)aBundle
{
if ((self = [super init]))
{
if (aBundle == nil) aBundle = [NSBundle mainBundle];
bundle = [aBundle retain];
self.bundle = aBundle;
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);
@@ -37,17 +41,12 @@
- (void)dealloc
{
[defaultsDomain release];
[bundle release];
self.bundle = nil;
[super dealloc];
}
- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@, %@>", [self class], [self bundlePath], [self installationPath]]; }
- (NSBundle *)bundle
{
return bundle;
}
- (NSString *)bundlePath
{
return [bundle bundlePath];
@@ -65,6 +64,7 @@
else
appSupportPath = [appSupportPaths objectAtIndex:0];
appSupportPath = [appSupportPath stringByAppendingPathComponent:[self name]];
appSupportPath = [appSupportPath stringByAppendingPathComponent:@".Sparkle"];
return appSupportPath;
}
@@ -122,20 +122,15 @@
// 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;
NSString *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);
@@ -249,7 +244,6 @@
// 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);
@@ -259,7 +253,6 @@
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"];
+1 -1
View File
@@ -13,7 +13,7 @@
#import "SUVersionComparisonProtocol.h"
@class SUHost;
@interface SUInstaller : NSObject { }
@interface SUInstaller : NSObject
+ (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;
+6 -1
View File
@@ -9,9 +9,14 @@
#ifndef SUPACKAGEINSTALLER_H
#define SUPACKAGEINSTALLER_H
#import "SUUpdater.h"
#import "SUAppcast.h"
#import "SUAppcastItem.h"
#import "SUVersionComparisonProtocol.h"
#import "SUPlainInstaller.h"
@interface SUPackageInstaller : SUPlainInstaller { }
@interface SUPackageInstaller : SUPlainInstaller
@end
#endif
+1 -1
View File
@@ -7,7 +7,7 @@
//
#import <Cocoa/Cocoa.h>
#import "SUWindowController.h"
#import "Sparkle/SUWindowController.h"
@interface SUPasswordPrompt : SUWindowController
{
+1 -3
View File
@@ -12,9 +12,7 @@
#import <Cocoa/Cocoa.h>
#import "SUUnarchiver.h"
@interface SUPipedUnarchiver : SUUnarchiver {
}
@interface SUPipedUnarchiver : SUUnarchiver
@end
+1 -7
View File
@@ -22,9 +22,7 @@
@"extractTBZ", @".tar.bz2", @"extractTBZ", @".tbz", nil] retain];
NSString *lastPathComponent = [path lastPathComponent];
NSEnumerator *typeEnumerator = [typeSelectorDictionary keyEnumerator];
id currentType;
while ((currentType = [typeEnumerator nextObject]))
for (id currentType in typeSelectorDictionary)
{
if ([currentType length] > [lastPathComponent length]) continue;
if ([[lastPathComponent substringFromIndex:[lastPathComponent length] - [currentType length]] isEqualToString:currentType])
@@ -56,11 +54,7 @@
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!
+6 -1
View File
@@ -9,12 +9,17 @@
#ifndef SUPLAININSTALLER_H
#define SUPLAININSTALLER_H
#import "SUUpdater.h"
#import "SUAppcast.h"
#import "SUAppcastItem.h"
#import "SUVersionComparisonProtocol.h"
#import "SUInstaller.h"
#import "SUVersionComparisonProtocol.h"
@class SUHost;
@interface SUPlainInstaller : SUInstaller { }
@interface SUPlainInstaller : SUInstaller
+ (void)performInstallationToPath:(NSString *)installationPath fromPath:(NSString *)path host:(SUHost *)host delegate:delegate synchronously:(BOOL)synchronously versionComparator:(id <SUVersionComparison>)comparator;
@end
+86 -164
View File
@@ -6,7 +6,11 @@
// 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"
@@ -18,7 +22,7 @@
#import <dirent.h>
#import <unistd.h>
#import <sys/param.h>
#import <dlfcn.h>
@interface SUPlainInstaller (MMExtendedAttributes)
// Removes the directory tree rooted at |root| from the file quarantine.
@@ -43,104 +47,29 @@
@end
// Authorization code based on generous contribution from Allan Odgaard. Thanks, Allan!
static BOOL SUAuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authorization, const char* executablePath, AuthorizationFlags options, const char* const* arguments)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations" // this is terrible; will fix later probably
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;
// Create func pointer to AuthorizationExecuteWithPrivileges in case it doesn't exist
// in this version of MacOS
static OSStatus (*_AuthExecuteWithPrivilegesFunc)(AuthorizationRef authorization,
const char *pathToTool,
AuthorizationFlags options,
char * const *arguments,
FILE **communicationsPipe) = NULL;
// Check to see if we have the correct function in our loaded libraries
if (NULL == _AuthExecuteWithPrivilegesFunc)
{
// On 10.7, AuthorizationExecuteWithPrivileges is deprecated. We want
// to still use it since there's no good alternative (without requiring
// code signing). We'll look up the function through dyld and fail if
// it is no longer accessible. If Apple removes the function entirely
// this will fail gracefully. If they keep the function and throw some
// sort of exception, this won't fail gracefully, but that's a risk
// we'll have to take for now.
// Pattern by Andy Kim from Potion Factory LLC
_AuthExecuteWithPrivilegesFunc = dlsym(RTLD_DEFAULT, "AuthorizationExecuteWithPrivileges");
}
if (NULL != _AuthExecuteWithPrivilegesFunc &&
errAuthorizationSuccess == _AuthExecuteWithPrivilegesFunc(authorization, executablePath, options, (char* const*)arguments, NULL))
if (AuthorizationExecuteWithPrivileges(authorization, executablePath, options, (char* const*)arguments, NULL) == errAuthorizationSuccess)
{
int status = 0;
int status;
pid_t pid = wait(&status);
if (pid == -1 || !WIFEXITED(status) || WEXITSTATUS(status) != 0)
returnValue = NO;
}
else
{
returnValue = NO;
}
signal(SIGCHLD, oldSigChildHandler);
return returnValue;
}
static void SUAuthorizationRelease(AuthorizationRef authorization)
{
if (NULL == authorization)
return;
AuthorizationFree(authorization, kAuthorizationFlagDefaults);
}
static AuthorizationRef SUAuthorizationCreate(OSStatus *outStatus)
{
AuthorizationRef auth = NULL;
OSStatus authStat = errAuthorizationDenied;
while (errAuthorizationDenied == authStat)
{
authStat = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &auth);
}
if (errAuthorizationSuccess == authStat)
{
AuthorizationFlags theFlags = kAuthorizationFlagDefaults | kAuthorizationFlagPreAuthorize | kAuthorizationFlagInteractionAllowed | kAuthorizationFlagExtendRights;
AuthorizationItem rightsItems = {kAuthorizationRightExecute, 0, NULL, 0};
AuthorizationRights authRights = {1, &rightsItems};
AuthorizationItem envItems[1];
envItems[0].name = kAuthorizationEnvironmentPrompt;
envItems[0].value = (void *)[SULocalizedString(@"The update requires administrative permissions to be completed.", nil) cStringUsingEncoding:NSUTF8StringEncoding];
envItems[0].valueLength = strlen((const char *)envItems[0].value);
envItems[0].flags = 0;
AuthorizationEnvironment environment;
environment.count = sizeof(envItems) / sizeof(AuthorizationItem);
environment.items = envItems;
authStat = AuthorizationCopyRights(auth, &authRights, &environment, theFlags, NULL);
}
if (errAuthorizationSuccess != authStat)
{
SUAuthorizationRelease(auth);
auth = NULL;
}
if (NULL != outStatus)
{
*outStatus = authStat;
}
return auth;
}
#pragma clang diagnostic pop
@implementation SUPlainInstaller (Internals)
@@ -249,10 +178,17 @@ static AuthorizationRef SUAuthorizationCreate(OSStatus *outStatus)
}
}
AuthorizationRef auth = SUAuthorizationCreate(NULL);
AuthorizationRef auth = NULL;
OSStatus authStat = errAuthorizationDenied;
while (authStat == errAuthorizationDenied) {
authStat = AuthorizationCreate(NULL,
kAuthorizationEmptyEnvironment,
kAuthorizationFlagDefaults,
&auth);
}
BOOL res = NO;
if (NULL != auth)
{
if (authStat == errAuthorizationSuccess) {
res = YES;
char uidgid[42];
@@ -264,8 +200,13 @@ static AuthorizationRef SUAuthorizationCreate(OSStatus *outStatus)
// quarantine to avoid a delay at launch, and to avoid
// presenting the user with a confusing trust dialog.
//
// This needs to be done before "chown" changes ownership,
// because the ownership change will fail if the file is quarantined.
// 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");
@@ -275,7 +216,7 @@ static AuthorizationRef SUAuthorizationCreate(OSStatus *outStatus)
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 = SUAuthorizationExecuteWithPrivilegesAndWait( auth, "/usr/sbin/chown", kAuthorizationFlagDefaults, coParams );
res = AuthorizationExecuteWithPrivilegesAndWait( auth, "/usr/sbin/chown", kAuthorizationFlagDefaults, coParams );
if( !res )
SULog( @"chown -R %s %s failed.", uidgid, srcPath );
}
@@ -284,7 +225,7 @@ static AuthorizationRef SUAuthorizationCreate(OSStatus *outStatus)
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 = SUAuthorizationExecuteWithPrivilegesAndWait( auth, "/bin/rm", kAuthorizationFlagDefaults, rmParams );
res = AuthorizationExecuteWithPrivilegesAndWait( auth, "/bin/rm", kAuthorizationFlagDefaults, rmParams );
if( !res )
SULog( @"rm failed" );
}
@@ -292,7 +233,7 @@ static AuthorizationRef SUAuthorizationCreate(OSStatus *outStatus)
if( res && haveDst ) // Move old exe to tmp path.
{
const char* mvParams[] = { "-f", dstPath, tmpPath, NULL };
res = SUAuthorizationExecuteWithPrivilegesAndWait( auth, "/bin/mv", kAuthorizationFlagDefaults, mvParams );
res = AuthorizationExecuteWithPrivilegesAndWait( auth, "/bin/mv", kAuthorizationFlagDefaults, mvParams );
if( !res )
SULog( @"mv 1 failed" );
}
@@ -300,7 +241,7 @@ static AuthorizationRef SUAuthorizationCreate(OSStatus *outStatus)
if( res ) // Move new exe to old exe's path.
{
const char* mvParams2[] = { "-f", srcPath, dstPath, NULL };
res = SUAuthorizationExecuteWithPrivilegesAndWait( auth, "/bin/mv", kAuthorizationFlagDefaults, mvParams2 );
res = AuthorizationExecuteWithPrivilegesAndWait( auth, "/bin/mv", kAuthorizationFlagDefaults, mvParams2 );
if( !res )
SULog( @"mv 2 failed" );
}
@@ -308,10 +249,10 @@ static AuthorizationRef SUAuthorizationCreate(OSStatus *outStatus)
// 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 = SUAuthorizationExecuteWithPrivilegesAndWait( auth, "/bin/rm", kAuthorizationFlagDefaults, rmParams2 );
// res = AuthorizationExecuteWithPrivilegesAndWait( auth, "/bin/rm", kAuthorizationFlagDefaults, rmParams2 );
// }
SUAuthorizationRelease(auth);
AuthorizationFree(auth, 0);
// If the currently-running application is trusted, the new
// version should be trusted as well. Remove it from the
@@ -355,9 +296,18 @@ static AuthorizationRef SUAuthorizationCreate(OSStatus *outStatus)
struct stat dstSB;
stat(dstContainerPath, &dstSB);
AuthorizationRef auth = SUAuthorizationCreate(NULL);
AuthorizationRef auth = NULL;
OSStatus authStat = errAuthorizationDenied;
while( authStat == errAuthorizationDenied )
{
authStat = AuthorizationCreate(NULL,
kAuthorizationEmptyEnvironment,
kAuthorizationFlagDefaults,
&auth);
}
BOOL res = NO;
if (NULL != auth)
if (authStat == errAuthorizationSuccess)
{
res = YES;
@@ -368,7 +318,7 @@ static AuthorizationRef SUAuthorizationCreate(OSStatus *outStatus)
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 = SUAuthorizationExecuteWithPrivilegesAndWait( auth, "/usr/sbin/chown", kAuthorizationFlagDefaults, coParams );
res = AuthorizationExecuteWithPrivilegesAndWait( auth, "/usr/sbin/chown", kAuthorizationFlagDefaults, coParams );
if( !res )
SULog(@"Can't set permissions");
}
@@ -377,7 +327,7 @@ static AuthorizationRef SUAuthorizationCreate(OSStatus *outStatus)
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 = SUAuthorizationExecuteWithPrivilegesAndWait( auth, "/bin/rm", kAuthorizationFlagDefaults, rmParams );
res = AuthorizationExecuteWithPrivilegesAndWait( auth, "/bin/rm", kAuthorizationFlagDefaults, rmParams );
if( !res )
SULog(@"Can't remove destination file");
}
@@ -385,12 +335,12 @@ static AuthorizationRef SUAuthorizationCreate(OSStatus *outStatus)
if( res ) // Move!.
{
const char* mvParams[] = { "-f", srcPath, dstPath, NULL };
res = SUAuthorizationExecuteWithPrivilegesAndWait( auth, "/bin/mv", kAuthorizationFlagDefaults, mvParams );
res = AuthorizationExecuteWithPrivilegesAndWait( auth, "/bin/mv", kAuthorizationFlagDefaults, mvParams );
if( !res )
SULog(@"Can't move source file");
}
SUAuthorizationRelease(auth);
AuthorizationFree(auth, 0);
if (!res)
{
@@ -415,21 +365,30 @@ static AuthorizationRef SUAuthorizationCreate(OSStatus *outStatus)
const char* srcPath = [src fileSystemRepresentation];
AuthorizationRef auth = SUAuthorizationCreate(NULL);
AuthorizationRef auth = NULL;
OSStatus authStat = errAuthorizationDenied;
while( authStat == errAuthorizationDenied )
{
authStat = AuthorizationCreate(NULL,
kAuthorizationEmptyEnvironment,
kAuthorizationFlagDefaults,
&auth);
}
BOOL res = NO;
if (NULL != auth)
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 = SUAuthorizationExecuteWithPrivilegesAndWait( auth, "/bin/rm", kAuthorizationFlagDefaults, rmParams );
res = AuthorizationExecuteWithPrivilegesAndWait( auth, "/bin/rm", kAuthorizationFlagDefaults, rmParams );
if( !res )
SULog(@"Can't remove destination file");
}
SUAuthorizationRelease(auth);
AuthorizationFree(auth, 0);
if (!res)
{
@@ -450,11 +409,7 @@ static AuthorizationRef SUAuthorizationCreate(OSStatus *outStatus)
+ (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];
}
@@ -485,7 +440,7 @@ static AuthorizationRef SUAuthorizationCreate(OSStatus *outStatus)
+ (BOOL)copyPathWithAuthentication:(NSString *)src overPath:(NSString *)dst temporaryName:(NSString *)tmp error:(NSError **)error
{
FSRef srcRef, dstRef, dstDirRef, movedRef, tmpDirRef;
FSRef srcRef, dstRef, dstDirRef, tmpDirRef;
OSStatus err;
BOOL hadFileAtDest = NO, didFindTrash = NO;
NSString *tmpPath = [self _temporaryCopyNameForPath: dst didFindTrash: &didFindTrash];
@@ -513,66 +468,40 @@ static AuthorizationRef SUAuthorizationCreate(OSStatus *outStatus)
{
err = FSPathMakeRef((UInt8 *)[[tmpPath stringByDeletingLastPathComponent] fileSystemRepresentation], &tmpDirRef, NULL);
if (err != noErr)
err = FSPathMakeRef((UInt8 *)[[dst stringByDeletingLastPathComponent] fileSystemRepresentation], &tmpDirRef, NULL);
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;
}
}
{
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;
}
}
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)
{
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;
// We better move the old version back to its old location
if( hadFileAtDest )
success = [manager moveItemAtPath:tmpPath toPath:dst error:error];
if (!success && 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
@@ -582,10 +511,7 @@ static AuthorizationRef SUAuthorizationCreate(OSStatus *outStatus)
// 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.
if ([NSThread isMultiThreaded])
[self performSelectorOnMainThread:@selector(releaseFromQuarantine:) withObject:dst waitUntilDone:YES];
else
[self releaseFromQuarantine:dst];
[self performSelectorOnMainThread:@selector(releaseFromQuarantine:) withObject:dst waitUntilDone:YES];
return YES;
}
@@ -646,11 +572,7 @@ static AuthorizationRef SUAuthorizationCreate(OSStatus *outStatus)
// 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) {
+6 -2
View File
@@ -17,14 +17,18 @@
{
if ([[updater delegate] respondsToSelector:@selector(updater:didFindValidUpdate:)])
[[updater delegate] updater:updater didFindValidUpdate:updateItem];
[self abortUpdate:SUUpdateAbortTasksFinished];
NSDictionary *userInfo = (updateItem != nil) ? @{SUUpdaterAppcastItemNotificationKey : updateItem} : nil;
[[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterDidFindValidUpdateNotification object:updater userInfo:userInfo];
[self abortUpdate];
}
- (void)didNotFindUpdate
{
if ([[updater delegate] respondsToSelector:@selector(updaterDidNotFindUpdate:)])
[[updater delegate] updaterDidNotFindUpdate:updater];
[self abortUpdate:SUUpdateAbortDidNotFind];
[[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterDidNotFindUpdateNotification object:updater];
[self abortUpdate];
}
@end
+4 -7
View File
@@ -15,11 +15,6 @@
@implementation SUScheduledUpdateDriver
- (BOOL)shouldShowUI
{
return showErrors;
}
- (void)didFindValidUpdate
{
showErrors = YES; // We only start showing errors after we present the UI for the first time.
@@ -30,7 +25,9 @@
{
if ([[updater delegate] respondsToSelector:@selector(updaterDidNotFindUpdate:)])
[[updater delegate] updaterDidNotFindUpdate:updater];
[self abortUpdate:SUUpdateAbortDidNotFind]; // Don't tell the user that no update was found; this was a scheduled update.
[[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterDidNotFindUpdateNotification object:updater];
[self abortUpdate]; // Don't tell the user that no update was found; this was a scheduled update.
}
- (void)abortUpdateWithError:(NSError *)error
@@ -38,7 +35,7 @@
if (showErrors)
[super abortUpdateWithError:error];
else
[self abortUpdate:SUUpdateAbortGotError];
[self abortUpdate];
}
@end
+1 -1
View File
@@ -12,7 +12,7 @@
#import <Cocoa/Cocoa.h>
@class SUHost;
@interface SUSystemProfiler : NSObject {}
@interface SUSystemProfiler : NSObject
+ (SUSystemProfiler *)sharedSystemProfiler;
- (NSMutableArray *)systemProfileArrayForHost:(SUHost *)host;
@end
+3 -2
View File
@@ -11,10 +11,11 @@
#import <Cocoa/Cocoa.h>
#import "SUBasicUpdateDriver.h"
#import "SUUpdateAlert.h"
@class SUStatusController, SUUpdateAlert;
@class SUStatusController;
@interface SUUIBasedUpdateDriver : SUBasicUpdateDriver
@interface SUUIBasedUpdateDriver : SUBasicUpdateDriver <SUUnarchiverDelegate, SUUpdateAlertDelegate>
{
SUStatusController *statusController;
SUUpdateAlert *updateAlert;
+10 -35
View File
@@ -17,11 +17,6 @@
@implementation SUUIBasedUpdateDriver
- (BOOL)shouldShowUI
{
return YES;
}
- (void)didFindValidUpdate
{
updateAlert = [[SUUpdateAlert alloc] initWithAppcastItem:updateItem host:host];
@@ -55,21 +50,17 @@
{
if ([[updater delegate] respondsToSelector:@selector(updaterDidNotFindUpdate:)])
[[updater delegate] updaterDidNotFindUpdate:updater];
[[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterDidNotFindUpdateNotification object: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:SUUpdateAbortDidNotFind];
[self abortUpdate];
}
- (void)applicationDidBecomeActive:(NSNotification *)aNotification
{
[[updateAlert window] makeKeyAndOrderFront:self];
[[NSNotificationCenter defaultCenter] removeObserver:self name:NSApplicationDidBecomeActiveNotification object:NSApp];
}
- (void)updateAlert:(SUUpdateAlert *)updateAlert willLoadReleaseNotesWithRequest:(NSMutableURLRequest *)request
{
[self updateURLRequestIfNeeds:request];
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"NSApplicationDidBecomeActiveNotification" object:NSApp];
}
- (void)updateAlert:(SUUpdateAlert *)alert finishedWithChoice:(SUUpdateAlertChoice)choice
@@ -88,16 +79,16 @@
case SUOpenInfoURLChoice:
[[NSWorkspace sharedWorkspace] openURL: [updateItem infoURL]];
[self abortUpdate:SUUpdateAbortCanceledByUser];
[self abortUpdate];
break;
case SUSkipThisVersionChoice:
[host setObject:[updateItem versionString] forUserDefaultsKey:SUSkippedVersionKey];
[self abortUpdate:SUUpdateAbortCanceledByUser];
[self abortUpdate];
break;
case SURemindMeLaterChoice:
[self abortUpdate:SUUpdateAbortCanceledByUser];
[self abortUpdate];
break;
}
}
@@ -134,7 +125,7 @@
{
if (download)
[download cancel];
[self abortUpdate:SUUpdateAbortCanceledByUser];
[self abortUpdate];
}
- (void)extractUpdate
@@ -151,11 +142,7 @@
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];
@@ -211,17 +198,12 @@
- (void)abortUpdateWithError:(NSError *)error
{
abortReason = SUUpdateAbortGotError;
NSAlert *alert = [NSAlert alertWithMessageText:SULocalizedString(@"Update Error!", nil)
defaultButton:SULocalizedString(@"Cancel Update", nil)
alternateButton:nil
otherButton:nil
informativeTextWithFormat:[error localizedDescription], nil];
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];
}
- (void)abortUpdate:(SUUpdateAbortReason)reason
- (void)abortUpdate
{
if (statusController)
{
@@ -229,18 +211,11 @@
[statusController autorelease];
statusController = nil;
}
[super abortUpdate:reason];
[super abortUpdate];
}
- (void)showModalAlert:(NSAlert *)alert
{
if ([[updater delegate] respondsToSelector:@selector(updater:mayShowModalAlert:)] &&
![[updater delegate] updater:updater mayShowModalAlert:alert])
{
// delegate forbids to show this alert!
return;
}
if ([[updater delegate] respondsToSelector:@selector(updaterWillShowModalAlert:)])
[[updater delegate] updaterWillShowModalAlert: updater];
+6 -5
View File
@@ -10,25 +10,26 @@
#define SUUNARCHIVER_H
@class SUHost;
@protocol SUUnarchiverDelegate;
@interface SUUnarchiver : NSObject {
id delegate;
id<SUUnarchiverDelegate> delegate;
NSString *archivePath;
SUHost *updateHost;
}
@property (assign) id<SUUnarchiverDelegate> delegate;
+ (SUUnarchiver *)unarchiverForPath:(NSString *)path updatingHost:(SUHost *)host;
- (void)setDelegate:delegate;
- (void)start;
@end
@interface NSObject (SUUnarchiverDelegate)
- (void)unarchiver:(SUUnarchiver *)unarchiver extractedLength:(unsigned long)length;
@protocol SUUnarchiverDelegate <NSObject>
- (void)unarchiverDidFinish:(SUUnarchiver *)unarchiver;
- (void)unarchiverDidFail:(SUUnarchiver *)unarchiver;
@optional
- (void)unarchiver:(SUUnarchiver *)unarchiver requiresPasswordReturnedViaInvocation:(NSInvocation *)invocation;
- (void)unarchiver:(SUUnarchiver *)unarchiver extractedLength:(unsigned long)length;
@end
#endif
+2 -8
View File
@@ -16,12 +16,11 @@
#import "SUUnarchiver_Private.h"
@implementation SUUnarchiver
@synthesize delegate;
+ (SUUnarchiver *)unarchiverForPath:(NSString *)path updatingHost:(SUHost *)host
{
NSEnumerator *implementationEnumerator = [[self unarchiverImplementations] objectEnumerator];
id current;
while ((current = [implementationEnumerator nextObject]))
for (id current in [self unarchiverImplementations])
{
if ([current canUnarchivePath:path])
return [[[current alloc] initWithPath:path host:host] autorelease];
@@ -31,11 +30,6 @@
- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], archivePath]; }
- (void)setDelegate:del
{
delegate = del;
}
- (void)start
{
// No-op
+1 -1
View File
@@ -16,7 +16,7 @@
+ (void)registerImplementation:(Class)implementation;
+ (NSArray *)unarchiverImplementations;
+ (BOOL)canUnarchivePath:(NSString *)path;
- (id)initWithPath:(NSString *)path host:(SUHost *)host;;
- (id)initWithPath:(NSString *)path host:(SUHost *)host;
- (void)notifyDelegateOfExtractedLength:(NSNumber *)length;
- (void)notifyDelegateOfSuccess;
+6 -10
View File
@@ -12,6 +12,7 @@
#import "SUWindowController.h"
#import "SUVersionDisplayProtocol.h"
@protocol SUUpdateAlertDelegate;
typedef enum
{
@@ -22,29 +23,24 @@ typedef enum
} SUUpdateAlertChoice;
@class WebView, SUAppcastItem, SUHost;
@interface SUUpdateAlert : SUWindowController <NSURLDownloadDelegate> {
@interface SUUpdateAlert : SUWindowController {
SUAppcastItem *updateItem;
SUHost *host;
id delegate;
id<SUUpdateAlertDelegate> delegate;
id<SUVersionDisplay> versionDisplayer;
IBOutlet WebView *releaseNotesView;
IBOutlet NSTextField *description;
IBOutlet NSButton *automaticUpdateButton;
IBOutlet NSButton *installButton; // UK 2007-08-31.
IBOutlet NSButton *skipButton;
IBOutlet NSButton *laterButton;
NSProgressIndicator *releaseNotesSpinner;
BOOL webViewFinishedLoading;
NSURLDownload *releaseNotesDownloader;
NSString *downloadedReleaseNotesPath;
}
@property (assign) id<SUUpdateAlertDelegate> delegate;
- (id)initWithAppcastItem:(SUAppcastItem *)item host:(SUHost *)host;
- (void)setDelegate:delegate;
- (IBAction)toggleAutomaticallyDownloadUpdate:(id)sender;
- (IBAction)installUpdate:sender;
- (IBAction)skipThisVersion:sender;
- (IBAction)remindMeLater:sender;
@@ -53,9 +49,9 @@ typedef enum
@end
@interface NSObject (SUUpdateAlertDelegate)
- (void)updateAlert:(SUUpdateAlert *)updateAlert willLoadReleaseNotesWithRequest:(NSMutableURLRequest *)request;
@protocol SUUpdateAlertDelegate <NSObject>
- (void)updateAlert:(SUUpdateAlert *)updateAlert finishedWithChoice:(SUUpdateAlertChoice)updateChoice;
@optional
- (void)updateAlert:(SUUpdateAlert *)updateAlert shouldAllowAutoUpdate: (BOOL*)shouldAllowAutoUpdate;
@end
+13 -54
View File
@@ -15,11 +15,10 @@
#import "SUHost.h"
#import <WebKit/WebKit.h>
#import "SUUpdater_Private.h"
#import "SUConstants.h"
#import "SUXPCURLDownload.h"
@interface WebView (SUTenFiveProperty)
@interface WebView ()
-(void) setDrawsBackground: (BOOL)state;
@@ -27,6 +26,7 @@
@implementation SUUpdateAlert
@synthesize delegate;
- (id)initWithAppcastItem:(SUAppcastItem *)item host:(SUHost *)aHost
{
@@ -51,9 +51,6 @@
{
[updateItem release];
[host release];
[releaseNotesDownloader release];
[downloadedReleaseNotesPath release];
[super dealloc];
}
@@ -73,12 +70,6 @@
[delegate updateAlert:self finishedWithChoice:choice];
}
- (IBAction)toggleAutomaticallyDownloadUpdate:(id)sender
{
BOOL shouldUpdateAutomatically = NSOnState == [automaticUpdateButton state] ? YES : NO;
[host setBool:shouldUpdateAutomatically forUserDefaultsKey:SUAutomaticallyUpdateKey];
}
- (IBAction)installUpdate: (id)sender
{
[self endWithSelection:SUInstallUpdateChoice];
@@ -103,8 +94,14 @@
{
// Set the default font
[releaseNotesView setPreferencesIdentifier:[SPARKLE_BUNDLE bundleIdentifier]];
[[releaseNotesView preferences] setStandardFontFamily:[[NSFont systemFontOfSize:8] familyName]];
[[releaseNotesView preferences] setDefaultFontSize:(int)[NSFont systemFontSizeForControlSize:NSSmallControlSize]];
WebPreferences *prefs = [releaseNotesView preferences];
NSString *familyName = [[NSFont systemFontOfSize:8] familyName];
if ([familyName hasPrefix:@"."]) { // 10.9 returns ".Lucida Grande UI", which isn't a valid name for the WebView
familyName = @"Lucida Grande";
}
[prefs setStandardFontFamily:familyName];
[prefs setDefaultFontSize:(int)[NSFont systemFontSizeForControlSize:NSSmallControlSize]];
[prefs setPlugInsEnabled:NO];
[releaseNotesView setFrameLoadDelegate:self];
[releaseNotesView setPolicyDelegate:self];
@@ -125,23 +122,7 @@
}
else
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[updateItem releaseNotesURL]
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:30];
if ([delegate respondsToSelector:@selector(updateAlert:willLoadReleaseNotesWithRequest:)])
{
[delegate updateAlert:self willLoadReleaseNotesWithRequest:request];
}
if (SUShouldUseXPCDownloader())
{
[releaseNotesDownloader release];
releaseNotesDownloader = (NSURLDownload *)[[SUXPCURLDownload alloc] initWithRequest:request delegate:self];
}
else
{
[[releaseNotesView mainFrame] loadRequest:request];
}
[[releaseNotesView mainFrame] loadRequest:[NSURLRequest requestWithURL:[updateItem releaseNotesURL] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30]];
}
}
else
@@ -150,18 +131,6 @@
}
}
- (void)download:(NSURLDownload *)aDownload didCreateDestination:(NSString *)path
{
[downloadedReleaseNotesPath release];
downloadedReleaseNotesPath = [path copy];
}
- (void)downloadDidFinish:(NSURLDownload *)aDownload
{
NSString *s = [NSString stringWithContentsOfFile:downloadedReleaseNotesPath encoding:NSUTF8StringEncoding error:nil];
[[releaseNotesView mainFrame] loadHTMLString:s baseURL:nil];
}
- (BOOL)showsReleaseNotes
{
NSNumber *shouldShowReleaseNotes = [host objectForInfoDictionaryKey:SUShowReleaseNotesKey];
@@ -228,9 +197,6 @@
[installButton setTitle: SULocalizedString( @"Learn More...", @"Alternate title for 'Install Update' button when there's no download in RSS feed." )];
[installButton setAction: @selector(openInfoURL:)];
}
[automaticUpdateButton setHidden:![self allowsAutomaticUpdates]];
[automaticUpdateButton setState:[host boolForUserDefaultsKey:SUAutomaticallyUpdateKey] ? NSOnState : NSOffState];
// Make sure button widths are OK:
#define DISTANCE_BETWEEN_BUTTONS 3
@@ -364,9 +330,7 @@
if (webViewMenuItems)
{
NSEnumerator *itemEnumerator = [defaultMenuItems objectEnumerator];
NSMenuItem *menuItem = nil;
while ((menuItem = [itemEnumerator nextObject]))
for (NSMenuItem *menuItem in defaultMenuItems)
{
NSInteger tag = [menuItem tag];
@@ -389,9 +353,4 @@
return webViewMenuItems;
}
- (void)setDelegate:del
{
delegate = del;
}
@end
+7 -8
View File
@@ -14,23 +14,22 @@
extern NSString * const SUUpdateDriverFinishedNotification;
@class SUHost, SUUpdater;
@interface SUUpdateDriver : NSObject
@interface SUUpdateDriver : NSObject<NSURLDownloadDelegate>
{
SUHost *host;
SUUpdater *updater;
NSURL *appcastURL;
SUUpdateAbortReason abortReason;
BOOL finished;
BOOL isInterruptible;
}
@property (retain) SUHost *host;
- (id)initWithUpdater:(SUUpdater *)updater;
- initWithUpdater:(SUUpdater *)updater;
- (void)checkForUpdatesAtURL:(NSURL *)URL host:(SUHost *)host;
- (void)abortUpdate:(SUUpdateAbortReason)reason;
- (void)abortUpdate;
- (BOOL)isInterruptible;
- (BOOL)finished;
- (SUHost*)host;
- (void)setHost:(SUHost*)newHost;
- (SUUpdateAbortReason)abortReason;
- (BOOL)shouldShowUI; // can change it's value
@end
+8 -28
View File
@@ -12,6 +12,9 @@
NSString * const SUUpdateDriverFinishedNotification = @"SUUpdateDriverFinished";
@implementation SUUpdateDriver
@synthesize host;
- initWithUpdater:(SUUpdater *)anUpdater
{
if ((self = [super init]))
@@ -23,48 +26,25 @@ NSString * const SUUpdateDriverFinishedNotification = @"SUUpdateDriverFinished";
- (void)checkForUpdatesAtURL:(NSURL *)URL host:(SUHost *)h
{
abortReason = SUUpdateAbortUndefined;
appcastURL = [URL copy];
host = [h retain];
}
- (void)abortUpdate:(SUUpdateAbortReason)reason
- (void)abortUpdate
{
abortReason = reason;
[self setValue:[NSNumber numberWithBool:YES] forKey:@"finished"];
[[NSNotificationCenter defaultCenter] postNotificationName:SUUpdateDriverFinishedNotification object:self];
}
- (BOOL)finished
{
return abortReason != SUUpdateAbortUndefined;
}
- (BOOL)isInterruptible { return isInterruptible; }
- (SUUpdateAbortReason)abortReason
{
return abortReason;
}
- (BOOL)shouldShowUI
{
return NO;
}
- (BOOL)finished { return finished; }
- (void)dealloc
{
[host release];
self.host = nil;
[appcastURL release];
[super dealloc];
}
- (SUHost*)host
{
return host;
}
- (void)setHost:(SUHost*)newHost
{
[host release];
host = [newHost retain];
}
@end
+31 -35
View File
@@ -9,8 +9,10 @@
#ifndef SUUPDATER_H
#define SUUPDATER_H
#import "SUVersionComparisonProtocol.h"
#import "SUVersionDisplayProtocol.h"
@class SUUpdateDriver, SUAppcastItem, SUHost, SUAppcast;
@protocol SUVersionComparison, SUVersionDisplay;
@interface SUUpdater : NSObject
{
@@ -22,6 +24,7 @@
SUHost *host;
IBOutlet id delegate;
}
@property (assign) id delegate;
+ (SUUpdater *)sharedUpdater;
+ (SUUpdater *)updaterForBundle:(NSBundle *)bundle;
@@ -29,9 +32,6 @@
- (NSBundle *)hostBundle;
- (void)setDelegate:(id)delegate;
- (id)delegate;
- (void)setAutomaticallyChecksForUpdates:(BOOL)automaticallyChecks;
- (BOOL)automaticallyChecksForUpdates;
@@ -71,10 +71,22 @@
- (BOOL)updateInProgress;
- (BOOL)installationInProgress;
@end
// -----------------------------------------------------------------------------
// SUUpdater Notifications for events that might be interesting to more than just the delegate
// The updater will be the notification object
// -----------------------------------------------------------------------------
extern NSString *const SUUpdaterDidFinishLoadingAppCastNotification;
extern NSString *const SUUpdaterDidFindValidUpdateNotification;
extern NSString *const SUUpdaterDidNotFindUpdateNotification;
extern NSString *const SUUpdaterWillInstallUpdateNotification;
extern NSString *const SUUpdaterWillRelaunchApplicationNotification;
// Key for the SUAppcastItem object in the SUUpdaterDidFindValidUpdateNotification & SUUpdaterWillInstallUpdateNotification userInfos
extern NSString *const SUUpdaterAppcastItemNotificationKey;
// Key for the SUAppcast object in the SUUpdaterDidFinishLoadingAppCastNotification userInfo
extern NSString *const SUUpdaterAppcastNotificationKey;
// -----------------------------------------------------------------------------
// SUUpdater Delegate:
@@ -83,7 +95,7 @@
@interface NSObject (SUUpdaterDelegateInformalProtocol)
// Use this to keep Sparkle from popping up e.g. while your setup assistant is showing:
- (BOOL)updaterMayCheckForUpdates:(SUUpdater *)updater;
- (BOOL)updaterMayCheckForUpdates:(SUUpdater *)bundle;
// This method allows you to add extra parameters to the appcast URL, potentially based on whether or not Sparkle will also be sending along the system profile. This method should return an array of dictionaries with keys: "key", "value", "displayKey", "displayValue", the latter two being specifically for display to the user.
- (NSArray *)feedParametersForUpdater:(SUUpdater *)updater sendingSystemProfile:(BOOL)sendingProfile;
@@ -107,18 +119,9 @@
// Sent when a valid update is not found.
- (void)updaterDidNotFindUpdate:(SUUpdater *)update;
// For cases when updater automatically downloads updates
- (BOOL)updater:(SUUpdater *)updater canAutomaticallyInstallUpdate:(SUAppcastItem *)update;
// Sent immediately before installing the specified update.
- (void)updater:(SUUpdater *)updater willInstallUpdate:(SUAppcastItem *)update;
// Sent immediately after installing the specified update in case when relaunch was forbidden.
- (void)updater:(SUUpdater *)updater didInstallUpdate:(SUAppcastItem *)update;
// Override to handle update manually
- (BOOL)updater:(SUUpdater *)updater overrideInstallUpdate:(SUAppcastItem *)update downloadPath:(NSString *)downloadPath shouldRelaunch:(BOOL *)outShouldRelaunch;
// Return YES to delay the relaunch until you do some processing; invoke the given NSInvocation to continue.
// This is not called if the user didn't relaunch on the previous update, in that case it will immediately
// restart.
@@ -144,33 +147,26 @@
// Called before and after, respectively, an updater shows a modal alert window, to give the host
// the opportunity to hide attached windows etc. that may get in the way:
- (BOOL)updater:(SUUpdater *)updater mayShowModalAlert:(NSAlert *)alertToShow;
- (void)updaterWillShowModalAlert:(SUUpdater *)updater;
- (void)updaterDidShowModalAlert:(SUUpdater *)updater;
-(void) updaterWillShowModalAlert:(SUUpdater *)updater;
-(void) updaterDidShowModalAlert:(SUUpdater *)updater;
// Called when an update is scheduled to be silently installed on quit.
// The invocation can be used to trigger an immediate silent install and relaunch.
- (void)updater:(SUUpdater *)updater willInstallUpdateOnQuit:(SUAppcastItem *)update immediateInstallationInvocation:(NSInvocation *)invocation;
- (void)updater:(SUUpdater *)updater didCancelInstallUpdateOnQuit:(SUAppcastItem *)update;
@end
// -----------------------------------------------------------------------------
// SUUpdater Delegate: DevMate Interaction
// -----------------------------------------------------------------------------
// NOTE!!! Implemented delegate methods have higher priority than values saved in user preferences
#define SUUpdaterChecksForBetaUpdatesPrefKey @"SUUpdaterChecksForBetaUpdates" // bool value
#define SUUpdaterIsInTestModePrefKey @"SUUpdaterIsInTestMode" // bool value
@interface NSObject (SUUpdaterDelegate_DevMateInteraction)
- (BOOL)updaterShouldCheckForBetaUpdates:(SUUpdater *)updater;
- (BOOL)isUpdaterInTestMode:(SUUpdater *)updater;
@end
// -----------------------------------------------------------------------------
// Constants:
// -----------------------------------------------------------------------------
// Define some minimum intervals (in seconds) to avoid DoS-like checking attacks.
#ifndef DEBUG
#define DEBUG 0
#endif
// Define some minimum intervals to avoid DOS-like checking attacks. These are in seconds.
#if defined(DEBUG) && DEBUG && 0
#define SU_MIN_CHECK_INTERVAL 60
#else
+39 -131
View File
@@ -7,7 +7,6 @@
//
#import "SUUpdater.h"
#import "SUUpdater_Private.h"
#import "SUHost.h"
#import "SUUpdatePermissionPrompt.h"
@@ -21,50 +20,40 @@
#import "SUCodeSigningVerifier.h"
#include <SystemConfiguration/SystemConfiguration.h>
NSString *const SUUpdaterDidFinishLoadingAppCastNotification = @"SUUpdaterDidFinishLoadingAppCastNotification";
NSString *const SUUpdaterDidFindValidUpdateNotification = @"SUUpdaterDidFindValidUpdateNotification";
NSString *const SUUpdaterDidNotFindUpdateNotification = @"SUUpdaterDidNotFindUpdateNotification";
NSString *const SUUpdaterWillInstallUpdateNotification = @"SUUpdaterWillInstallUpdateNotification";
NSString *const SUUpdaterWillRelaunchApplicationNotification = @"SUUpdaterWillRelaunchApplicationNotification";
NSString *const SUUpdaterAppcastItemNotificationKey = @"SUUpdaterAppcastItemNotificationKey";
NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotificationKey";
@interface SUUpdater ()
@property (retain) NSTimer *checkTimer;
- (id)initForBundle:(NSBundle *)bundle;
- (void)startUpdateCycle;
- (void)checkForUpdatesWithDriver:(SUUpdateDriver *)updateDriver;
- (BOOL)automaticallyDownloadsUpdates;
- (void)scheduleNextUpdateCheck;
- (void)registerAsObserver;
- (void)unregisterAsObserver;
- (void)updateDriverDidFinish:(NSNotification *)note;
- (NSURL *)parameterizedFeedURL;
-(void)notifyWillShowModalAlert;
-(void)notifyDidShowModalAlert;
-(void) notifyWillShowModalAlert;
-(void) notifyDidShowModalAlert;
@end
@implementation SUUpdater
@synthesize delegate;
@synthesize checkTimer;
#pragma mark Initialization
static NSMutableDictionary *sharedUpdaters = nil;
static NSString * const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefaultsObservationContext";
- (BOOL)installationInProgress
{
BOOL result = NO;
@try
{
NSConnection *connection = [NSConnection connectionWithRegisteredName:[NSString stringWithFormat:@"Sparkle %@", [[host bundle] bundleIdentifier]] host:nil];
if (connection != nil)
{
NSDistantObject *proxyBundle = [connection rootProxy];
result = proxyBundle != nil;
}
}
@catch (NSException *exception)
{
}
return result;
}
+ (SUUpdater *)sharedUpdater
{
return [self updaterForBundle:[NSBundle mainBundle]];
@@ -108,30 +97,13 @@ static NSString * const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefault
BOOL hasPublicDSAKey = [host publicDSAKey] != nil;
BOOL isMainBundle = [bundle isEqualTo:[NSBundle mainBundle]];
BOOL hostIsCodeSigned = [SUCodeSigningVerifier hostApplicationIsCodeSigned];
NSAlert *warnAlert = nil;
if (!isMainBundle && !hasPublicDSAKey)
{
warnAlert = [NSAlert alertWithMessageText:SULocalizedString(@"Insecure update error!", nil)
defaultButton:SULocalizedString(@"OK", nil)
alternateButton:nil
otherButton:nil
informativeTextWithFormat:SULocalizedString(@"For security reasons, you need to sign your updates with a DSA key. See Sparkle's documentation for more information.", nil)];
}
else if (isMainBundle && !(hasPublicDSAKey || hostIsCodeSigned))
{
warnAlert = [NSAlert alertWithMessageText:SULocalizedString(@"Insecure update error!", nil)
defaultButton:SULocalizedString(@"OK", nil)
alternateButton:nil
otherButton:nil
informativeTextWithFormat:SULocalizedString(@"For security reasons, you need to code sign your application or sign your updates with a DSA key. See Sparkle's documentation for more information.", nil)];
}
if (warnAlert != nil &&
(![[self delegate] respondsToSelector:@selector(updater:mayShowModalAlert:)] ||
[[self delegate] updater:self mayShowModalAlert:warnAlert]))
{
if (!isMainBundle && !hasPublicDSAKey) {
[self notifyWillShowModalAlert];
[warnAlert runModal];
NSRunAlertPanel(@"Insecure update error!", @"For security reasons, you need to sign your updates with a DSA key. See Sparkle's documentation for more information.", @"OK", nil, nil);
[self notifyDidShowModalAlert];
} else if (isMainBundle && !(hasPublicDSAKey || hostIsCodeSigned)) {
[self notifyWillShowModalAlert];
NSRunAlertPanel(@"Insecure update error!", @"For security reasons, you need to code sign your application or sign your updates with a DSA key. See Sparkle's documentation for more information.", @"OK", nil, nil);
[self notifyDidShowModalAlert];
}
#endif
@@ -222,15 +194,9 @@ static NSString * const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefault
- (void)updateDriverDidFinish:(NSNotification *)note
{
if ([note object] == driver && (!driver || [driver finished]))
if ([note object] == driver && [driver finished])
{
if ([[self delegate] respondsToSelector:@selector(updaterDidEndUpdateProcess:)])
{
[[self delegate] updaterDidEndUpdateProcess:self];
}
[driver release];
driver = nil;
[driver release]; driver = nil;
[self scheduleNextUpdateCheck];
}
}
@@ -245,8 +211,7 @@ static NSString * const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefault
if (checkTimer)
{
[checkTimer invalidate];
[checkTimer release]; // UK 2009-03-16 Timer is non-repeating, may have invalidated itself, so we had to retain it.
checkTimer = nil;
self.checkTimer = nil; // UK 2009-03-16 Timer is non-repeating, may have invalidated itself, so we had to retain it.
}
if (![self automaticallyChecksForUpdates]) return;
@@ -257,27 +222,19 @@ static NSString * const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefault
// Now we want to figure out how long until we check again.
NSTimeInterval delayUntilCheck, updateCheckInterval = [self updateCheckInterval];
if (updateCheckInterval < 5 /*SU_MIN_CHECK_INTERVAL*/)
updateCheckInterval = 5 /*SU_MIN_CHECK_INTERVAL*/;
if (updateCheckInterval < SU_MIN_CHECK_INTERVAL)
updateCheckInterval = SU_MIN_CHECK_INTERVAL;
if (intervalSinceCheck < updateCheckInterval)
delayUntilCheck = (updateCheckInterval - intervalSinceCheck); // It hasn't been long enough.
else
delayUntilCheck = 0; // We're overdue! Run one now.
checkTimer = [[NSTimer scheduledTimerWithTimeInterval:delayUntilCheck target:self selector:@selector(checkForUpdatesInBackground) userInfo:nil repeats:NO] retain]; // UK 2009-03-16 Timer is non-repeating, may have invalidated itself, so we had to retain it.
self.checkTimer = [NSTimer scheduledTimerWithTimeInterval:delayUntilCheck target:self selector:@selector(checkForUpdatesInBackground) userInfo:nil repeats:NO]; // UK 2009-03-16 Timer is non-repeating, may have invalidated itself, so we had to retain it.
}
-(void) putFeedURLIntoDictionary: (NSMutableDictionary*)theDict // You release this.
{
NSURL *feedURL = [self feedURL];
if (feedURL != nil)
{
[theDict setObject:feedURL forKey: @"feedURL"];
}
else
{
SULog(@"Cannot put feedURL into dictionary: feedURL is nil");
}
[theDict setObject: [self feedURL] forKey: @"feedURL"];
}
-(void) checkForUpdatesInBgReachabilityCheckWithDriver: (SUUpdateDriver*)inDriver /* RUNS ON ITS OWN THREAD */
@@ -347,6 +304,9 @@ static NSString * const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefault
- (IBAction)checkForUpdates: (id)sender
{
if (driver && [driver isInterruptible])
[driver abortUpdate];
[self checkForUpdatesWithDriver:[[[SUUserInitiatedUpdateDriver alloc] initWithUpdater:self] autorelease]];
}
@@ -358,13 +318,8 @@ static NSString * const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefault
- (void)checkForUpdatesWithDriver:(SUUpdateDriver *)d
{
if ([self updateInProgress]) { return; }
if (checkTimer) { [checkTimer invalidate]; [checkTimer release]; checkTimer = nil; } // UK 2009-03-16 Timer is non-repeating, may have invalidated itself, so we had to retain it.
if (checkTimer) { [checkTimer invalidate]; self.checkTimer = nil; } // UK 2009-03-16 Timer is non-repeating, may have invalidated itself, so we had to retain it.
if ([[self delegate] respondsToSelector:@selector(updaterWillStartUpdateProcess:)])
{
[[self delegate] updaterWillStartUpdateProcess:self];
}
SUClearLog();
SULog( @"===== %@ =====", [[NSFileManager defaultManager] displayNameAtPath: [[NSBundle mainBundle] bundlePath]] );
@@ -374,7 +329,7 @@ static NSString * const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefault
if( [delegate respondsToSelector: @selector(updaterMayCheckForUpdates:)] && ![delegate updaterMayCheckForUpdates: self] )
{
[self updateDriverDidFinish:nil];
[self scheduleNextUpdateCheck];
return;
}
@@ -383,7 +338,7 @@ static NSString * const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefault
// If we're not given a driver at all, just schedule the next update check and bail.
if (!driver)
{
[self updateDriverDidFinish:nil];
[self scheduleNextUpdateCheck];
return;
}
@@ -391,7 +346,7 @@ static NSString * const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefault
if( theFeedURL ) // Use a NIL URL to cancel quietly.
[driver checkForUpdatesAtURL: theFeedURL host:host];
else
[driver abortUpdate:SUUpdateAbortGotError];
[driver abortUpdate];
}
- (void)registerAsObserver
@@ -480,18 +435,10 @@ static NSString * const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefault
{
// A value in the user defaults overrides one in the Info.plist (so preferences panels can be created wherein users choose between beta / release feeds).
NSString *appcastString = [host objectForKey:SUFeedURLKey];
if ([delegate respondsToSelector: @selector(feedURLStringForUpdater:)])
{
if( [delegate respondsToSelector: @selector(feedURLStringForUpdater:)] )
appcastString = [delegate feedURLStringForUpdater: self];
}
if (!appcastString) // Can't find an appcast string!
{
static NSString * const sDevMateFeedURLBase = @"http://updates.devmate.com/";
NSString *bundleId = [[host bundle] bundleIdentifier] ? : @"";
NSString *feedURLComponent = [bundleId stringByAppendingPathExtension:@"xml"];
appcastString = [sDevMateFeedURLBase stringByAppendingString:feedURLComponent];
}
[NSException raise:@"SUNoFeedURL" format:@"You must specify the URL of the appcast as the SUFeedURL key in either the Info.plist or the user defaults!"];
NSCharacterSet* quoteSet = [NSCharacterSet characterSetWithCharactersInString: @"\"\'"]; // Some feed publishers add quotes; strip 'em.
NSString* castUrlStr = [appcastString stringByTrimmingCharactersInSet:quoteSet];
if( !castUrlStr || [castUrlStr length] == 0 )
@@ -527,7 +474,7 @@ static NSString * const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefault
- (BOOL)sendsSystemProfile
{
return [host boolForUserDefaultsKey:SUSendProfileInfoKey];
return [host boolForKey:SUSendProfileInfoKey];
}
- (NSURL *)parameterizedFeedURL
@@ -544,7 +491,7 @@ static NSString * const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefault
const NSTimeInterval oneWeek = 60 * 60 * 24 * 7;
sendingSystemProfile &= (-[lastSubmitDate timeIntervalSinceNow] >= oneWeek);
NSArray *parameters = [self devmateFeedParameters];
NSArray *parameters = [NSArray array];
if ([delegate respondsToSelector:@selector(feedParametersForUpdater:sendingSystemProfile:)])
parameters = [parameters arrayByAddingObjectsFromArray:[delegate feedParametersForUpdater:self sendingSystemProfile:sendingSystemProfile]];
if (sendingSystemProfile)
@@ -556,9 +503,7 @@ static NSString * const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefault
// Build up the parameterized URL.
NSMutableArray *parameterStrings = [NSMutableArray array];
NSEnumerator *profileInfoEnumerator = [parameters objectEnumerator];
NSDictionary *currentProfileInfo;
while ((currentProfileInfo = [profileInfoEnumerator nextObject]))
for (NSDictionary *currentProfileInfo in parameters)
[parameterStrings addObject:[NSString stringWithFormat:@"%@=%@", [[[currentProfileInfo objectForKey:@"key"] description] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding], [[[currentProfileInfo objectForKey:@"value"] description] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
NSString *separatorCharacter = @"?";
@@ -595,7 +540,7 @@ static NSString * const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefault
{
[self unregisterAsObserver];
[host release];
if (checkTimer) { [checkTimer invalidate]; [checkTimer release]; checkTimer = nil; } // UK 2009-03-16 Timer is non-repeating, may have invalidated itself, so we had to retain it.
if (checkTimer) { [checkTimer invalidate]; [checkTimer release]; self.checkTimer = nil; } // UK 2009-03-16 Timer is non-repeating, may have invalidated itself, so we had to retain it.
[super dealloc];
}
@@ -606,48 +551,11 @@ static NSString * const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefault
return YES;
}
- (void)setDelegate:aDelegate
{
delegate = aDelegate;
}
- (BOOL)updateInProgress
{
return driver && ([driver finished] == NO);
}
- (id)delegate { return delegate; }
- (SUHost *)host { return host; }
- (NSBundle *)hostBundle { return [host bundle]; }
- (SUBasicUpdateDriver *)driver { return (SUBasicUpdateDriver *)driver; }
#pragma mark - DevMate Interaction
- (NSArray *)devmateFeedParameters
{
NSMutableArray *parameters = [NSMutableArray array];
BOOL isInTestMode = [host boolForUserDefaultsKey:SUUpdaterIsInTestModePrefKey];
if ([delegate respondsToSelector:@selector(isUpdaterInTestMode:)])
{
isInTestMode = [delegate isUpdaterInTestMode:self];
}
if (isInTestMode)
{
[parameters addObject:[NSDictionary dictionaryWithObjectsAndKeys:@"test", @"key", @"1", @"value", nil]];
}
BOOL shouldCheckBeta = [host boolForUserDefaultsKey:SUUpdaterChecksForBetaUpdatesPrefKey];
if ([delegate respondsToSelector:@selector(updaterShouldCheckForBetaUpdates:)])
{
shouldCheckBeta = [delegate updaterShouldCheckForBetaUpdates:self];
}
if (shouldCheckBeta)
{
[parameters addObject:[NSDictionary dictionaryWithObjectsAndKeys:@"beta", @"key", @"1", @"value", nil]];
}
return parameters;
}
@end
-81
View File
@@ -1,81 +0,0 @@
//
// SUUpdaterProxy.m
// Sparkle
//
// Created by Dmytro Tretiakov on 10/1/14.
//
//
#import "SUUpdater.h"
#import <objc/runtime.h>
// This is a proxy for DM_SUUpdater class used in DevMateSparkle_lib target.
// In cases when developer uses this lib in it's own project but forgot to change
// updater object class inside XIB file from SUUpdater to DM_SUUpdater updating process won't be broken.
static NSString *sOriginalSUUpdaterClass = @"SUUpdater";
@interface SUUpdaterLoader : NSObject
@end
@implementation SUUpdaterLoader
+ (void)load
{
if (Nil == NSClassFromString(sOriginalSUUpdaterClass))
{
// Custom Sparkle.framework is absent
// Add own SUUpdater proxy class
Class SUUpdaterClass = objc_allocateClassPair([NSObject class], [sOriginalSUUpdaterClass UTF8String], 0);
if (Nil != SUUpdaterClass)
{
objc_registerClassPair(SUUpdaterClass);
}
Class SUUpdaterMetaclass = objc_getMetaClass(class_getName(SUUpdaterClass));
Class LoaderClass = [self class];
Class LoaderMetaclass = objc_getMetaClass(class_getName(LoaderClass));
BOOL success = SUUpdaterClass != Nil && SUUpdaterMetaclass != Nil;
void *runtimeMethods[][3] = {
{ SUUpdaterClass, LoaderClass, @selector(init) },
{ SUUpdaterMetaclass, LoaderMetaclass, @selector(sharedUpdater) },
{ SUUpdaterMetaclass, LoaderMetaclass, @selector(updaterForBundle:) },
};
size_t methodsCount = sizeof(runtimeMethods) / sizeof(runtimeMethods[0]);
for (size_t i = 0; success && i < methodsCount; ++i)
{
Class changeClass = runtimeMethods[i][0];
Class prototypeClass = runtimeMethods[i][1];
SEL selector = runtimeMethods[i][2];
IMP implementation = class_getMethodImplementation(prototypeClass, selector);
const char *types = method_getTypeEncoding(class_getInstanceMethod(prototypeClass, selector));
success = class_addMethod(changeClass, selector, implementation, types);
}
if (!success)
{
objc_disposeClassPair(SUUpdaterClass);
}
}
}
- (id)init
{
[self release];
return (id)[[SUUpdaterWorking alloc] init];
}
+ (id)sharedUpdater
{
return [SUUpdaterWorking sharedUpdater];
}
+ (id)updaterForBundle:(NSBundle *)bundle
{
return [SUUpdaterWorking updaterForBundle:bundle];
}
@end
-19
View File
@@ -1,19 +0,0 @@
//
// SUUpdaterQueue.h
// Sparkle
//
// Created by Dmytro Tretiakov on 7/31/14.
//
//
@class SUUpdater;
@interface SUUpdaterQueue : NSObject
- (void)addUpdater:(SUUpdater *)updater;
- (void)removeUpdater:(SUUpdater *)updater;
- (void)checkForUpdates;
- (void)checkForUpdatesInBackground;
@end
-441
View File
@@ -1,441 +0,0 @@
//
// SUUpdaterQueue.m
// Sparkle
//
// Created by Dmytro Tretiakov on 7/31/14.
//
//
#import "SUUpdaterQueue.h"
#import "SUUpdater.h"
#import "SUUpdater_Private.h"
#import "SUConstants.h"
#import "SUUserInitiatedUpdateDriver.h"
@interface SUDelegateProxy : NSProxy
@property (nonatomic, assign) id realDelegate;
@property (nonatomic, assign) SUUpdaterQueue *updaterQueue;
@end
@implementation SUDelegateProxy
+ (BOOL)shouldRedirectToUpdaterQueue:(SEL)aSelector
{
if (nil == aSelector)
return NO;
static NSSet *sSelectorsToRedirect = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sSelectorsToRedirect = [[NSSet alloc] initWithObjects:
NSStringFromSelector(@selector(updaterWillStartUpdateProcess:)),
NSStringFromSelector(@selector(updaterDidEndUpdateProcess:)),
NSStringFromSelector(@selector(updaterMayCheckForUpdates:)),
NSStringFromSelector(@selector(updater:mayShowModalAlert:)),
nil];
});
return [sSelectorsToRedirect containsObject:NSStringFromSelector(aSelector)];
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector
{
NSMethodSignature *signature = [self.realDelegate methodSignatureForSelector:selector];
if (!signature)
{
signature = [self.updaterQueue methodSignatureForSelector:selector];
}
if (!signature)
{
signature = [self methodSignatureForSelector:selector];
}
return signature;
}
- (BOOL)respondsToSelector:(SEL)aSelector
{
BOOL result = NO;
if ([SUDelegateProxy shouldRedirectToUpdaterQueue:aSelector])
{
result = YES;
}
else
{
result = [self.realDelegate respondsToSelector:aSelector];
}
return result;
}
- (void)forwardInvocation:(NSInvocation *)anInvocation
{
if ([SUDelegateProxy shouldRedirectToUpdaterQueue:[anInvocation selector]])
{
[anInvocation invokeWithTarget:self.updaterQueue];
}
else if ([self.realDelegate respondsToSelector:anInvocation.selector])
{
[anInvocation invokeWithTarget:self.realDelegate];
}
}
- (BOOL)isKindOfClass:(Class)aClass
{
if (self.realDelegate)
return [self.realDelegate isKindOfClass:aClass];
return NO;
}
@end
#pragma mark -
@interface SUUpdaterQueue ()
{
NSMutableArray *_updaters;
NSMutableDictionary *_delegatesMap;
}
@property (readonly) NSMutableArray *updaters;
@property (readonly) NSMutableDictionary *delegatesMap;
@property (retain) SUUpdater *currentUpdater;
@property (atomic, assign) dispatch_semaphore_t currentUpdaterSema;
@property (nonatomic, retain) NSObject *semaphoreSynchronizer;
@property (assign) BOOL shouldContinueCheck;
@property (nonatomic, retain) NSMutableArray *resultUIDrivers;
@property (assign, getter=isProcessingUpdatersCheck) BOOL processingUpdatersCheck;
@end
@implementation SUUpdaterQueue
- (instancetype)init
{
self = [super init];
if (self)
{
self.semaphoreSynchronizer = [[NSObject alloc] init];
}
return self;
}
- (void)dealloc
{
for (SUUpdater *updater in self.updaters)
{
[self removeUpdater:updater];
}
[_updaters release];
[_delegatesMap release];
@synchronized (self.semaphoreSynchronizer)
{
if (!self.currentUpdater && self.currentUpdaterSema)
{
dispatch_release(self.currentUpdaterSema);
self.currentUpdaterSema = nil;
}
}
self.semaphoreSynchronizer = nil;
self.currentUpdater = nil;
self.resultUIDrivers = nil;
[super dealloc];
}
- (NSMutableArray *)updaters
{
if (nil == _updaters)
{
@synchronized (self)
{
_updaters = _updaters ? : [[NSMutableArray alloc] init];
}
}
return [[_updaters retain] autorelease];
}
- (NSMutableDictionary *)delegatesMap
{
if (nil == _delegatesMap)
{
@synchronized (self)
{
_delegatesMap = _delegatesMap ? : [[NSMutableDictionary alloc] init];
}
}
return [[_delegatesMap retain] autorelease];
}
#pragma mark -
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([object isKindOfClass:[SUUpdater class]])
{
[self updateUpdaterDelegate:object];
}
}
- (void)updateUpdaterDelegate:(SUUpdater *)updater
{
if ([SUDelegateProxy class] == [[updater delegate] class] &&
self == [[updater delegate] updaterQueue])
{
return;
}
@synchronized (self.delegatesMap)
{
id realDelegate = [updater delegate];
SUDelegateProxy *proxy = [[SUDelegateProxy alloc] autorelease];
proxy.realDelegate = realDelegate;
proxy.updaterQueue = self;
[updater setDelegate:proxy];
NSString *updaterKey = [self mapKeyForUpdater:updater];
[self.delegatesMap setObject:proxy forKey:updaterKey];
}
}
- (NSString *)mapKeyForUpdater:(SUUpdater *)updater
{
return [NSString stringWithFormat:@"%p", updater];
}
- (id)realDelegateForUpdater:(SUUpdater *)updater
{
if (nil == updater)
return nil;
id delegate = nil;
@synchronized (self.delegatesMap)
{
delegate = [self.delegatesMap objectForKey:[self mapKeyForUpdater:updater]];
}
return delegate;
}
#pragma mark -
- (void)addUpdater:(SUUpdater *)updater
{
if (nil == updater)
return;
if ([updater updateInProgress])
{
NSLog(@"Could not add updater while it's in progress");
return;
}
NSMutableArray *updaters = self.updaters;
@synchronized (updaters)
{
if (![updaters containsObject:updater])
{
[self updateUpdaterDelegate:updater];
[updater addObserver:self forKeyPath:@"delegate" options:NSKeyValueObservingOptionNew context:NULL];
[self.updaters addObject:updater];
}
}
}
- (void)removeUpdater:(SUUpdater *)updater
{
if (nil == updater)
return;
if (updater == self.currentUpdater && self.currentUpdaterSema)
{
NSLog(@"Could not remove updater while it's in progress.");
return;
}
NSMutableArray *updaters = self.updaters;
@synchronized (updaters)
{
if ([updaters containsObject:updater])
{
[updater removeObserver:self forKeyPath:@"delegate"];
id realDelegate = nil;
NSString *updaterKey = [self mapKeyForUpdater:updater];
@synchronized (self.delegatesMap)
{
realDelegate = [[self.delegatesMap objectForKey:updaterKey] realDelegate];
[self.delegatesMap removeObjectForKey:updaterKey];
}
[updater setDelegate:realDelegate];
[updaters removeObject:updater];
}
}
}
#pragma mark -
- (void)performCheckForUpdates:(NSString *)selectorName
{
if (self.isProcessingUpdatersCheck)
return;
self.processingUpdatersCheck = YES;
NSUInteger index = 0;
self.shouldContinueCheck = YES;
self.resultUIDrivers = [NSMutableArray array];
do
{
// in case if some of queued updaters is already in process
if (self.currentUpdater && self.currentUpdaterSema)
{
dispatch_semaphore_wait(self.currentUpdaterSema, DISPATCH_TIME_FOREVER);
@synchronized (self.semaphoreSynchronizer)
{
dispatch_release(self.currentUpdaterSema);
self.currentUpdaterSema = nil;
}
}
if (!self.shouldContinueCheck)
break;
@synchronized (self.updaters)
{
self.currentUpdater = index < [self.updaters count] ? [self.updaters objectAtIndex:index] : nil;
index++;
}
if (nil == self.currentUpdater)
break;
@synchronized (self.semaphoreSynchronizer)
{
if (nil == self.currentUpdaterSema)
self.currentUpdaterSema = dispatch_semaphore_create(0);
}
[self.currentUpdater performSelectorOnMainThread:NSSelectorFromString(selectorName)
withObject:nil
waitUntilDone:YES];
}
while (YES);
if (SUUpdateAbortDidNotFind == [[self.resultUIDrivers lastObject] abortReason])
{
SUBasicUpdateDriver *driver = nil;
if ([self.resultUIDrivers count] > 1)
{
SUUpdater *mainUpdater = [SUUpdater sharedUpdater];
driver = [[[SUUserInitiatedUpdateDriver alloc] initWithUpdater:mainUpdater] autorelease];
[driver setHost:[mainUpdater host]];
}
else
{
driver = [self.resultUIDrivers lastObject];
}
[driver performSelectorOnMainThread:@selector(didNotFindUpdate) withObject:nil waitUntilDone:YES];
}
self.resultUIDrivers = nil;
self.processingUpdatersCheck = NO;
}
- (void)checkForUpdates
{
[self performSelectorInBackground:@selector(performCheckForUpdates:)
withObject:NSStringFromSelector(@selector(checkForUpdates:))];
}
- (void)checkForUpdatesInBackground
{
[self performSelectorInBackground:@selector(performCheckForUpdates:)
withObject:NSStringFromSelector(@selector(checkForUpdatesInBackground))];
}
#pragma mark -
- (void)updaterWillStartUpdateProcess:(SUUpdater *)updater
{
if ((nil != updater && nil == self.currentUpdater) ||
(self.currentUpdater == updater))
{
self.currentUpdater = updater;
@synchronized (self.semaphoreSynchronizer)
{
if (nil == self.currentUpdaterSema)
self.currentUpdaterSema = dispatch_semaphore_create(0);
}
}
}
- (void)updaterDidEndUpdateProcess:(SUUpdater *)updater
{
if (self.currentUpdater == updater)
{
self.currentUpdater = nil;
@synchronized (self.semaphoreSynchronizer)
{
if (self.currentUpdaterSema)
dispatch_semaphore_signal(self.currentUpdaterSema);
}
SUBasicUpdateDriver *driver = [updater driver];
do
{
if (![driver shouldShowUI])
break;
if (SUUpdateAbortGotError == [driver abortReason])
{
self.resultUIDrivers = nil;
self.shouldContinueCheck = NO;
break;
}
[self.resultUIDrivers addObject:driver];
}
while (NO);
}
}
- (BOOL)updaterMayCheckForUpdates:(SUUpdater *)updater
{
BOOL result = NO;
if (updater != nil && updater == self.currentUpdater)
{
id realDelegate = [SUDelegateProxy class] == [[updater delegate] class] ? [[updater delegate] realDelegate] : [updater delegate];
result = ![realDelegate respondsToSelector:_cmd] || [realDelegate updaterMayCheckForUpdates:updater];
}
return result;
}
- (BOOL)updater:(SUUpdater *)updater mayShowModalAlert:(NSAlert *)alertToShow
{
BOOL result = YES;
if (updater != nil && updater == self.currentUpdater && self.shouldContinueCheck)
{
if (SUUpdateAbortGotError != [[updater driver] abortReason])
result = NO;
}
else
{
id realDelegate = [SUDelegateProxy class] == [[updater delegate] class] ? [[updater delegate] realDelegate] : [updater delegate];
result = ![realDelegate respondsToSelector:_cmd] || [realDelegate updater:updater mayShowModalAlert:alertToShow];
}
return result;
}
@end
-11
View File
@@ -7,20 +7,9 @@
//
#import "SUUpdater.h"
#import "SUCodeSigningVerifier.h"
#import "SUBasicUpdateDriver.h"
@interface SUUpdater (Private)
- (BOOL)mayUpdateAndRestart;
- (SUHost *)host;
- (SUBasicUpdateDriver *)driver;
@end
@interface NSObject (SUPrivateUpdaterDelegateInformalProtocol)
- (void)updaterWillStartUpdateProcess:(SUUpdater *)updater;
- (void)updaterDidEndUpdateProcess:(SUUpdater *)updater;
@end
+4 -4
View File
@@ -50,7 +50,7 @@
{
if (isCanceled)
{
[self abortUpdate:SUUpdateAbortCanceledByUser];
[self abortUpdate];
return;
}
[self closeCheckingWindow];
@@ -63,17 +63,17 @@
[super abortUpdateWithError:error];
}
- (void)abortUpdate:(SUUpdateAbortReason)reason
- (void)abortUpdate
{
[self closeCheckingWindow];
[super abortUpdate:reason];
[super abortUpdate];
}
- (void)appcast:(SUAppcast *)ac failedToLoadWithError:(NSError *)error
{
if (isCanceled)
{
[self abortUpdate:SUUpdateAbortCanceledByUser];
[self abortUpdate];
return;
}
[super appcast:ac failedToLoadWithError:error];
+2
View File
@@ -9,6 +9,8 @@
#ifndef SUVERSIONCOMPARISONPROTOCOL_H
#define SUVERSIONCOMPARISONPROTOCOL_H
#import <Cocoa/Cocoa.h>
/*!
@protocol
@abstract Implement this protocol to provide version comparison facilities for Sparkle.
+2
View File
@@ -6,6 +6,8 @@
// Copyright 2009 Elgato Systems GmbH. All rights reserved.
//
#import <Cocoa/Cocoa.h>
/*!
@protocol
-8
View File
@@ -1,8 +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>com.apple.security.app-sandbox</key>
<true/>
</dict>
</plist>
Loaded 100 of 295 files, more files were not shown because too many files have changed in this diff. Show more