diff --git a/.gitignore b/.gitignore index 8b390eb4..b18d235c 100644 --- a/.gitignore +++ b/.gitignore @@ -28,6 +28,13 @@ Icon .Spotlight-V100 .Trashes +# With Carthage, if Sparkle is included as a Git submodule (e.g. with the +# --use-submodules option), the main module's .gitignore can't reach all the +# way inside the submodule to ignore the added Carthage/Build symlink, and Git +# keeps complaining about untracked changes in the submodule forever, which +# is very annoying. To avoid that issue, ignore here in Sparkle instead. +Carthage/Build + # Directories potentially created on remote AFP share .AppleDB .AppleDesktop diff --git a/.travis.yml b/.travis.yml index 20dc67d5..a6bcf53f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,5 @@ language: objective-c -osx_image: xcode7 +osx_image: xcode8 before_install: - brew update - - brew install macmade/tap/xcode-coveralls script: make ci -after_success: xcode-coveralls --exclude /Applications --exclude Tests --exclude Vendor build/Build/Intermediates/Sparkle.build/Coverage/Sparkle.build/Objects-normal/x86_64 diff --git a/CHANGELOG b/CHANGELOG index 4f500418..717c8bf1 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,14 +1,47 @@ -# 1.14.0 +# 1.15.0 +* A new icon! Thanks to 1024jp +* Show alert when an update is sent over insecure HTTP with no DSA key (Zorg) + - If you can't use HTTPS, you must at least sign updates with a DSA key. +* Improved binary delta implementation (Zorg) +* Added improved -validateMenuItem: as a method in SUUpdater.h for public use (Zorg) +* Removed reachability preflight check (Zorg) +* Clear update caches directory before downloading new update (Zorg) +* Check the bundle's parent directory for writability too (Zorg) +* Don't follow symbolic links for file operations (Zorg) +* Don't bring up an authorized dialog during cleanup (Zorg) +* Made Sparkle look for the highest compatible version regardless of timestamps (Zorg) +* Fixed compatibility with 10.7 + * Fixed crash on 10.7 - subscript operator not available (kleuter) + * Fixed warnings caused by -Wpartial-availability (Zorg) +* Fixed german l10n. (Sebastian Volland) +* Error code for download errors (Kornel Lesiński) +* Update last update check date when the update driver finishes (Zorg) +* Scale app icon up if needed in Software Update window (Nicholas Riley) +* Don't register for termination notifications more than once (Zorg) +* Don't terminate the app if we're already terminating (Zorg) +* Removed SUEnableAutomaticChecksKeyOld and SUCheckAtStartup constants (Eitot) +* Updated Sparkle framework headers to use modules if modules are available (B. Kevin Hardman) +* Fixed warnings, fixed uses of SULocalizedString (Jerry Krinock) +* Improved signing verifier to take any host and s/application/bundle/ (Zorg) +* Improved Spotlight updates after delta extraction (Zorg) + +# 1.14.0 (Mar 11, 2016) + +* Disable javascript by default and make it opt-in (Zorg) * URL-encoding of appcast URLs is preserved (Kornel Lesiński) * Delegate is asked for fallback updates if delta update fails (Kornel Lesiński) +* Fixed crash on 10.7 - subscript operator not available (kleuter) * Fixed check of feed URL before delegate had a chance to set it (Kornel Lesiński) * Re-added support for password-protected dmg images (Andrew K. Boyd) * Added warning about ATS blocking (Kornel Lesiński) * Translation fixes for pt-BR. (vitu) * Add some Japanese lozalized strings (1024jp) * Made test app available in all languages #695 (LIU Dongyuan / 柳东原) +* Czech localizations update (Frantisek Erben) * Removed a test resource from the framework bundle (Karl Moskowski) +* Test if the updated app is the frontmost one (Zorg) +* UI Tests for the Test Application (Zorg) # 1.13.1 (Jan 31, 2016) @@ -30,7 +63,7 @@ Important security fixes: - Strong documentation, easier to read code. * Automatic updates won't be installed if the system is about to shut off (Zorg) * Deprecated serving over HTTP without DSA (Zorg) - - Note that Apple has deprecated insecure HTTP in OS X 10.11 + - Note that Apple has deprecated insecure HTTP in macOS 10.11 * Improved Autoupdate application (Zorg) * Do all the installation work after the runloop is set up * TerminationListener only does termination listening now @@ -128,12 +161,12 @@ Important security fixes: # 1.8.0 (Jul 26, 2014) -* New SUDSAVerifier based on up-to-date OS X APIs (Zachary Waldowski) +* New SUDSAVerifier based on up-to-date macOS APIs (Zachary Waldowski) * Detailed error log for failed signature checks (Kornel Lesiński) * Converted Sparkle to ARC (C.W. Betts) * Converted ivars to properties. (Jake Petroules) * Cocoapod support (Xhacker Liu) -* Quarantine removal on OS X 10.10 (C.W. Betts) +* Quarantine removal on macOS 10.10 (C.W. Betts) * Updated Japanese localization (1024jp) * Added Greek localization @@ -154,7 +187,7 @@ Important security fixes: # 1.7.0 -* Dropped support for OS X 10.6. Sparkle now supports 10.7 and newer (including 10.10 Yosemite) on 64-bit Intel Macs (the last 32-bit Mac was released in 2006). +* Dropped support for macOS 10.6. Sparkle now supports 10.7 and newer (including 10.10 Yosemite) on 64-bit Intel Macs (the last 32-bit Mac was released in 2006). * Removed use of deprecated functions (Zachary Waldowski) * Switched to modern Obj-C runtime and new literals syntax * Removed pre-10.7 code. (C.W. Betts) diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..a1ac5dbf --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,74 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, gender identity and expression, level of experience, +nationality, personal appearance, race, religion, or sexual identity and +orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or +advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at kornel+sparkle@geekhood.net. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at [http://contributor-covenant.org/version/1/4][version] + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/4/ diff --git a/Configurations/ConfigCommon.xcconfig b/Configurations/ConfigCommon.xcconfig index d5b355a8..d4bb1089 100644 --- a/Configurations/ConfigCommon.xcconfig +++ b/Configurations/ConfigCommon.xcconfig @@ -2,6 +2,7 @@ SPARKLE_BUNDLE_IDENTIFIER = com.binaryage.sparkle SPARKLE_RELAUNCH_TOOL_NAME = Updater +SPARKLE_FILEOP_TOOL_NAME = fileop SPARKLE_APPEND_VERSION_NUMBER = 1 @@ -15,8 +16,8 @@ SPARKLE_AUTOMATED_DOWNGRADES = 0 SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME = 0 SPARKLE_VERSION_MAJOR = 1 -SPARKLE_VERSION_MINOR = 14 -SPARKLE_VERSION_PATCH = 0 +SPARKLE_VERSION_MINOR = 15 +SPARKLE_VERSION_PATCH = 1 SPARKLE_VERSION = $(SPARKLE_VERSION_MAJOR).$(SPARKLE_VERSION_MINOR).$(SPARKLE_VERSION_PATCH) CURRENT_PROJECT_VERSION = $(SPARKLE_VERSION) @@ -31,12 +32,15 @@ MACOSX_DEPLOYMENT_TARGET = 10.9 PRODUCT_NAME = ${TARGET_NAME} PRODUCT_BUNDLE_IDENTIFIER = org.sparkle-project.Sparkle.${PRODUCT_NAME:rfc1034identifier} -GCC_PREPROCESSOR_DEFINITIONS_COMMON = SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME=$(SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME) SPARKLE_AUTOMATED_DOWNGRADES=$(SPARKLE_AUTOMATED_DOWNGRADES) SPARKLE_APPEND_VERSION_NUMBER=$(SPARKLE_APPEND_VERSION_NUMBER) SPARKLE_BUNDLE_IDENTIFIER=\"$(SPARKLE_BUNDLE_IDENTIFIER)\" SPARKLE_RELAUNCH_TOOL_NAME=\"$(SPARKLE_RELAUNCH_TOOL_NAME)\" +GCC_PREPROCESSOR_DEFINITIONS_COMMON = SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME=$(SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME) SPARKLE_AUTOMATED_DOWNGRADES=$(SPARKLE_AUTOMATED_DOWNGRADES) SPARKLE_APPEND_VERSION_NUMBER=$(SPARKLE_APPEND_VERSION_NUMBER) SPARKLE_BUNDLE_IDENTIFIER=\"$(SPARKLE_BUNDLE_IDENTIFIER)\" SPARKLE_RELAUNCH_TOOL_NAME=\"$(SPARKLE_RELAUNCH_TOOL_NAME)\" SPARKLE_FILEOP_TOOL_NAME=\"$(SPARKLE_FILEOP_TOOL_NAME)\" CLANG_ENABLE_OBJC_ARC = YES GCC_ENABLE_PASCAL_STRINGS = NO +GCC_NO_COMMON_BLOCKS = YES; +COMBINE_HIDPI_IMAGES = NO; // Enable warnings +CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; CLANG_ANALYZER_SECURITY_FLOATLOOPCOUNTER = YES CLANG_ANALYZER_SECURITY_INSECUREAPI_RAND = YES CLANG_ANALYZER_SECURITY_INSECUREAPI_STRCPY = YES @@ -51,7 +55,6 @@ CLANG_WARN_OBJC_EXPLICIT_OWNERSHIP_TYPE = YES CLANG_WARN_OBJC_IMPLICIT_ATOMIC_PROPERTIES = YES CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES CLANG_WARN_OBJC_MISSING_PROPERTY_SYNTHESIS = YES -CLANG_WARN_OBJC_RECEIVER_WEAK = YES CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES CLANG_WARN_SUSPICIOUS_IMPLICIT_CONVERSION = YES CLANG_WARN_UNREACHABLE_CODE = YES diff --git a/Configurations/ConfigFileop.xcconfig b/Configurations/ConfigFileop.xcconfig new file mode 100644 index 00000000..33efd218 --- /dev/null +++ b/Configurations/ConfigFileop.xcconfig @@ -0,0 +1,5 @@ +// Fileop tool only + +PRODUCT_NAME = $(SPARKLE_FILEOP_TOOL_NAME) +SKIP_INSTALL = YES +CLANG_ENABLE_MODULES = NO diff --git a/Configurations/ConfigSwift.xcconfig b/Configurations/ConfigSwift.xcconfig new file mode 100644 index 00000000..8e0862f9 --- /dev/null +++ b/Configurations/ConfigSwift.xcconfig @@ -0,0 +1 @@ +SWIFT_VERSION = 3.0 diff --git a/Configurations/ConfigSwiftDebug.xcconfig b/Configurations/ConfigSwiftDebug.xcconfig new file mode 100644 index 00000000..4a437b26 --- /dev/null +++ b/Configurations/ConfigSwiftDebug.xcconfig @@ -0,0 +1 @@ +SWIFT_OPTIMIZATION_LEVEL = -Onone diff --git a/Configurations/ConfigSwiftRelease.xcconfig b/Configurations/ConfigSwiftRelease.xcconfig new file mode 100644 index 00000000..05d2efe9 --- /dev/null +++ b/Configurations/ConfigSwiftRelease.xcconfig @@ -0,0 +1 @@ +SWIFT_OPTIMIZATION_LEVEL = -Ofast diff --git a/Configurations/ConfigUITest.xcconfig b/Configurations/ConfigUITest.xcconfig new file mode 100644 index 00000000..badc3e13 --- /dev/null +++ b/Configurations/ConfigUITest.xcconfig @@ -0,0 +1,13 @@ +// UI Test only + +#include "ConfigSwift.xcconfig" + +INFOPLIST_FILE = UITests/UITests-Info.plist +WRAPPER_EXTENSION = xctest +MACOSX_DEPLOYMENT_TARGET = 10.11 + +FRAMEWORK_SEARCH_PATHS = $(inherited) $(DEVELOPER_FRAMEWORKS_DIR) +LD_RUNPATH_SEARCH_PATHS = @loader_path/../Frameworks + +TEST_TARGET_NAME = Sparkle Test App +USES_XCTRUNNER = YES diff --git a/Configurations/ConfigUITestCoverage.xcconfig b/Configurations/ConfigUITestCoverage.xcconfig new file mode 100644 index 00000000..c4cf79fd --- /dev/null +++ b/Configurations/ConfigUITestCoverage.xcconfig @@ -0,0 +1,4 @@ +#include "ConfigUITest.xcconfig" + +GCC_GENERATE_TEST_COVERAGE_FILES = NO +GCC_INSTRUMENT_PROGRAM_FLOW_ARCS = NO diff --git a/Configurations/ConfigUITestDebug.xcconfig b/Configurations/ConfigUITestDebug.xcconfig new file mode 100644 index 00000000..486dab5b --- /dev/null +++ b/Configurations/ConfigUITestDebug.xcconfig @@ -0,0 +1,2 @@ +#include "ConfigUITest.xcconfig" +#include "ConfigSwiftDebug.xcconfig" diff --git a/Configurations/ConfigUITestRelease.xcconfig b/Configurations/ConfigUITestRelease.xcconfig new file mode 100644 index 00000000..f8ae8bbf --- /dev/null +++ b/Configurations/ConfigUITestRelease.xcconfig @@ -0,0 +1,2 @@ +#include "ConfigUITest.xcconfig" +#include "ConfigSwiftRelease.xcconfig" diff --git a/Configurations/ConfigUnitTest.xcconfig b/Configurations/ConfigUnitTest.xcconfig index 36dc8857..f9e7cea3 100644 --- a/Configurations/ConfigUnitTest.xcconfig +++ b/Configurations/ConfigUnitTest.xcconfig @@ -1,5 +1,7 @@ // Unit Test only +#include "ConfigSwift.xcconfig" + INFOPLIST_FILE = Tests/SparkleTests-Info.plist WRAPPER_EXTENSION = xctest OTHER_CFLAGS = $(inherited) -iframework"$(DEVELOPER_FRAMEWORKS_DIR)" -iframework"$(PLATFORM_DIR)/Developer/Library/Frameworks" diff --git a/Configurations/ConfigUnitTestDebug.xcconfig b/Configurations/ConfigUnitTestDebug.xcconfig index e2481b5e..869437db 100644 --- a/Configurations/ConfigUnitTestDebug.xcconfig +++ b/Configurations/ConfigUnitTestDebug.xcconfig @@ -1 +1,2 @@ #include "ConfigUnitTest.xcconfig" +#include "ConfigSwiftDebug.xcconfig" diff --git a/Configurations/ConfigUnitTestRelease.xcconfig b/Configurations/ConfigUnitTestRelease.xcconfig index e2481b5e..e89e456c 100644 --- a/Configurations/ConfigUnitTestRelease.xcconfig +++ b/Configurations/ConfigUnitTestRelease.xcconfig @@ -1 +1,2 @@ #include "ConfigUnitTest.xcconfig" +#include "ConfigSwiftRelease.xcconfig" diff --git a/Configurations/make-release-package.sh b/Configurations/make-release-package.sh index 98cdd7b6..bddecff9 100755 --- a/Configurations/make-release-package.sh +++ b/Configurations/make-release-package.sh @@ -2,6 +2,13 @@ set -e if [ "$ACTION" = "" ] ; then + # Sanity check that the Podspec version matches the Sparkle version + spec_version=$(printf "require 'cocoapods'\nspec = %s\nprint spec.version" "$(cat "$SRCROOT/Sparkle.podspec")" | LANG=en_US.UTF-8 ruby) + if [ "$spec_version" != "$CURRENT_PROJECT_VERSION" ] ; then + echo "podspec version '$spec_version' does not match the current project version '$CURRENT_PROJECT_VERSION'" >&2 + exit 1 + fi + rm -rf "$CONFIGURATION_BUILD_DIR/staging" rm -f "Sparkle-$CURRENT_PROJECT_VERSION.tar.bz2" diff --git a/Configurations/set-git-version-info.sh b/Configurations/set-git-version-info.sh index 8a79052c..f1f31624 100755 --- a/Configurations/set-git-version-info.sh +++ b/Configurations/set-git-version-info.sh @@ -13,14 +13,20 @@ if [ -z "$SRCROOT" ] || \ exit 1 fi -# Get the current Git master hash -version=$(cd "$SRCROOT" ; git show-ref --abbrev heads/master | awk '{print $1}') -if [ -z "$version" ] ; then - echo "$0: Can't find a Git hash!" 1>&2 +version="$CURRENT_PROJECT_VERSION" + +# Get version in format 1.x.x-commits-hash +gitversion=$( cd "$SRCROOT"; git describe --tags --match '[12].*' || true ) +if [ -z "$gitversion" ] ; then + echo "$0: Can't find a Git hash!" 1>&2 exit 0 fi -version="$CURRENT_PROJECT_VERSION git-$version" +# remove everything before the first "-" to keep the hash part only +versionsuffix=${gitversion#*-}; +if [ "$versionsuffix" != "$gitversion" ]; then + version="$version $versionsuffix" +fi # and use it to set the CFBundleShortVersionString value export PATH="$PATH:/usr/libexec" diff --git a/Documentation/Doxyfile b/Documentation/Doxyfile index a2d21a3e..4b6ae1ae 100644 --- a/Documentation/Doxyfile +++ b/Documentation/Doxyfile @@ -1,6 +1,6 @@ PROJECT_NAME = Sparkle -PROJECT_NUMBER = 1.7.1 -PROJECT_BRIEF = "A software update framework for OS X" +PROJECT_NUMBER = 1.14.0 +PROJECT_BRIEF = "A software update framework for macOS" PROJECT_LOGO = Resources/Images.xcassets/AppIcon.appiconset/icon_32x32@2x.png RECURSIVE = YES diff --git a/Makefile b/Makefile index 4f1b4a9f..2aa20aa9 100644 --- a/Makefile +++ b/Makefile @@ -13,6 +13,8 @@ localizable-strings: release: xcodebuild -scheme Distribution -configuration Release -derivedDataPath "$(BUILDDIR)" build open -R "$(BUILDDIR)/Build/Products/Release/Sparkle-"*.tar.bz2 + cat Sparkle.podspec + @echo "Don't forget to update CocoaPods! pod trunk push" build: xcodebuild clean build @@ -20,6 +22,9 @@ build: test: xcodebuild -scheme Distribution -configuration Debug test +uitest: + xcodebuild -scheme UITests -configuration Debug test + ci: for i in {7..9} ; do \ if xcrun --sdk "macosx10.$$i" --show-sdk-path 2> /dev/null ; then \ diff --git a/Makefile-icon b/Makefile-icon new file mode 100644 index 00000000..7a04bb84 --- /dev/null +++ b/Makefile-icon @@ -0,0 +1,24 @@ +# To update the icon run make -f Makefile-icon +# Requires: +# autoconf, automake, libtool, pkg-config, pngquant + +ICONDIR=./Resources/Images.xcassets/AppIcon.appiconset +OPTIMIZEDICONS=$(ICONDIR)/optimized_16x16.png $(ICONDIR)/optimized_32x32.png $(ICONDIR)/optimized_128x128.png $(ICONDIR)/optimized_512x512.png +DESTICON=Resources/AppIcon.icns + +all: $(DESTICON) + +libicns: + git clone https://github.com/pornel/libicns.git + +libicns/Makefile: libicns + ( cd libicns && autoreconf -vif && ./configure ) + +libicns/icnsutils/png2icns: libicns/Makefile + ( cd libicns && make -j8 ) + +optimized_%.png: icon_%.png + pngquant -s1 -f -o $@ $< + +$(DESTICON): libicns/icnsutils/png2icns $(OPTIMIZEDICONS) + ./libicns/icnsutils/png2icns $@ $(OPTIMIZEDICONS) diff --git a/README.markdown b/README.markdown index 0195ed05..d7595acd 100644 --- a/README.markdown +++ b/README.markdown @@ -1,31 +1,32 @@ -# Sparkle [![Build Status](https://travis-ci.org/sparkle-project/Sparkle.svg?branch=master)](https://travis-ci.org/sparkle-project/Sparkle) [![Coverage Status](https://coveralls.io/repos/sparkle-project/Sparkle/badge.svg?branch=master&service=github)](https://coveralls.io/github/sparkle-project/Sparkle?branch=master) sponsored by: bandwidth hog +# Sparkle [![Build Status](https://travis-ci.org/sparkle-project/Sparkle.svg?branch=master)](https://travis-ci.org/sparkle-project/Sparkle) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) [![CocoaPods](https://img.shields.io/cocoapods/v/Sparkle.svg?maxAge=2592000)]() sponsored by: StackPath An easy-to-use software update framework for Cocoa developers. -Sparkle shows familiar update window with release notes +Sparkle shows familiar update window with release notes ## Changes since 1.5b -* Up-to-date with 10.11 SDK and Xcode 7. Supports OS X 10.7+. +* Compatibilty with macOS Sierra. +* Up-to-date with 10.12 SDK and Xcode 8 (supports macOS 10.7+). +* Important security fixes. * Cleaned up and modernized code, using ARC and Autolayout. -* Merged bugfixes, security fixes and some features from multiple Sparkle forks. * Truly automatic background updates (no UI at all) when user agreed to "Automatically download and install updates in the future." +* Upgraded and more reliable binary delta and code signing verification. * 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. -* Upgraded and more reliable binary delta and code signing verification. ## Features +* Seamless integration—there's no mention of Sparkle; your icons and app name are used. * True self-updating—the user can choose to automatically download and install all updates. * Displays a detailed progress window to the user. * Supports authentication for installing in secure locations. * Supports Apple Code Signing and DSA signatures for ultra-secure updates. * Easy to install. Sparkle requires no code in your app, so it's trivial to upgrade or remove the framework. -* Uses appcasts for release information. Appcasts are supported by 3rd party update-tracking programs and websites. +* Uses RSS-based appcasts for release information. Appcasts are supported by 3rd party update-tracking programs and websites. * Displays release notes to the user via WebKit. * Sparkle doesn't bug the user until second launch for better first impressions. -* Seamless integration—there's no mention of Sparkle; your icons and app name are used. * Deep delegate support to make Sparkle work exactly as you need. * Optionally sends system information to the server when checking for updates. * Supports bundles, preference panes, plugins, and other non-.app software. Can install .pkg files for more complicated products. @@ -33,7 +34,7 @@ An easy-to-use software update framework for Cocoa developers. ## Requirements -* Runtime: OS X 10.7 or greater +* Runtime: macOS 10.7 or greater * Build: Xcode 5 and 10.8 SDK or greater * HTTPS server for serving updates (see [App Transport Security](http://sparkle-project.org/documentation/app-transport-security/)) @@ -48,7 +49,10 @@ If you are adding a symbol to the public API you must decorate the declaration w Alternatively, build the Distribution scheme in the Xcode UI. +## Code of Conduct + +We pledge to have an open and welcoming environment. See our [Code of Conduct](CODE_OF_CONDUCT.md). + ## Project Sponsor -[Bandwidth Hog](https://www.bandwidthhog.com/?utm_source=sparkle-github&utm_medium=link&utm_campaign=readme-footer) is a service from MaxCDN -that allows you to push software updates to your customers for only 1¢ a gigabyte. Best part is there are no contracts, it is all Pay-as-you-Go. +[StackPath](https://www.stackpath.com/?utm_source=sparkle-github&utm_medium=link&utm_campaign=readme-footer) diff --git a/Resources/AppIcon.icns b/Resources/AppIcon.icns new file mode 100644 index 00000000..7f2a571c Binary files /dev/null and b/Resources/AppIcon.icns differ diff --git a/Resources/Images.xcassets/AppIcon.appiconset/Contents.json b/Resources/Images.xcassets/AppIcon.appiconset/Contents.json index 5ddf68b4..7cd4f8e1 100644 --- a/Resources/Images.xcassets/AppIcon.appiconset/Contents.json +++ b/Resources/Images.xcassets/AppIcon.appiconset/Contents.json @@ -43,18 +43,21 @@ "scale" : "1x" }, { - "idiom" : "mac", "size" : "256x256", + "idiom" : "mac", + "filename" : "icon_256x256@2x.png", "scale" : "2x" }, { - "idiom" : "mac", "size" : "512x512", + "idiom" : "mac", + "filename" : "icon_512x512.png", "scale" : "1x" }, { - "idiom" : "mac", "size" : "512x512", + "idiom" : "mac", + "filename" : "icon_512x512@2x.png", "scale" : "2x" } ], diff --git a/Resources/Images.xcassets/AppIcon.appiconset/icon_128x128.png b/Resources/Images.xcassets/AppIcon.appiconset/icon_128x128.png index 4d798520..02080831 100644 Binary files a/Resources/Images.xcassets/AppIcon.appiconset/icon_128x128.png and b/Resources/Images.xcassets/AppIcon.appiconset/icon_128x128.png differ diff --git a/Resources/Images.xcassets/AppIcon.appiconset/icon_128x128@2x.png b/Resources/Images.xcassets/AppIcon.appiconset/icon_128x128@2x.png index 2bf2b0b8..c0583922 100644 Binary files a/Resources/Images.xcassets/AppIcon.appiconset/icon_128x128@2x.png and b/Resources/Images.xcassets/AppIcon.appiconset/icon_128x128@2x.png differ diff --git a/Resources/Images.xcassets/AppIcon.appiconset/icon_16x16.png b/Resources/Images.xcassets/AppIcon.appiconset/icon_16x16.png index 23eada4e..a67751fa 100644 Binary files a/Resources/Images.xcassets/AppIcon.appiconset/icon_16x16.png and b/Resources/Images.xcassets/AppIcon.appiconset/icon_16x16.png differ diff --git a/Resources/Images.xcassets/AppIcon.appiconset/icon_16x16@2x.png b/Resources/Images.xcassets/AppIcon.appiconset/icon_16x16@2x.png index fa1e0dac..3e77a450 100644 Binary files a/Resources/Images.xcassets/AppIcon.appiconset/icon_16x16@2x.png and b/Resources/Images.xcassets/AppIcon.appiconset/icon_16x16@2x.png differ diff --git a/Resources/Images.xcassets/AppIcon.appiconset/icon_256x256.png b/Resources/Images.xcassets/AppIcon.appiconset/icon_256x256.png index 2bf2b0b8..1777fcc9 100644 Binary files a/Resources/Images.xcassets/AppIcon.appiconset/icon_256x256.png and b/Resources/Images.xcassets/AppIcon.appiconset/icon_256x256.png differ diff --git a/Resources/Images.xcassets/AppIcon.appiconset/icon_256x256@2x.png b/Resources/Images.xcassets/AppIcon.appiconset/icon_256x256@2x.png new file mode 100644 index 00000000..6ec496fe Binary files /dev/null and b/Resources/Images.xcassets/AppIcon.appiconset/icon_256x256@2x.png differ diff --git a/Resources/Images.xcassets/AppIcon.appiconset/icon_32x32.png b/Resources/Images.xcassets/AppIcon.appiconset/icon_32x32.png index eb1d810a..3be1d474 100644 Binary files a/Resources/Images.xcassets/AppIcon.appiconset/icon_32x32.png and b/Resources/Images.xcassets/AppIcon.appiconset/icon_32x32.png differ diff --git a/Resources/Images.xcassets/AppIcon.appiconset/icon_32x32@2x.png b/Resources/Images.xcassets/AppIcon.appiconset/icon_32x32@2x.png index f44f9779..f51f5972 100644 Binary files a/Resources/Images.xcassets/AppIcon.appiconset/icon_32x32@2x.png and b/Resources/Images.xcassets/AppIcon.appiconset/icon_32x32@2x.png differ diff --git a/Resources/Images.xcassets/AppIcon.appiconset/icon_512x512.png b/Resources/Images.xcassets/AppIcon.appiconset/icon_512x512.png new file mode 100644 index 00000000..54d52234 Binary files /dev/null and b/Resources/Images.xcassets/AppIcon.appiconset/icon_512x512.png differ diff --git a/Resources/Images.xcassets/AppIcon.appiconset/icon_512x512@2x.png b/Resources/Images.xcassets/AppIcon.appiconset/icon_512x512@2x.png new file mode 100644 index 00000000..8fe6aa07 Binary files /dev/null and b/Resources/Images.xcassets/AppIcon.appiconset/icon_512x512@2x.png differ diff --git a/Resources/SampleAppcast.xml b/Resources/SampleAppcast.xml index 1abb2c2c..dd9c089d 100755 --- a/Resources/SampleAppcast.xml +++ b/Resources/SampleAppcast.xml @@ -2,7 +2,6 @@ Your Great App's Changelog - http://you.com/app/appcast.xml Most recent changes with links to updates. en diff --git a/Resources/Screenshot.png b/Resources/Screenshot.png index 19c755d4..1b52ba3d 100644 Binary files a/Resources/Screenshot.png and b/Resources/Screenshot.png differ diff --git a/Resources/Sparkle-Icon.psd b/Resources/Sparkle-Icon.psd deleted file mode 100644 index 7097a190..00000000 Binary files a/Resources/Sparkle-Icon.psd and /dev/null differ diff --git a/Resources/Sparkle-Icon.sketch b/Resources/Sparkle-Icon.sketch new file mode 100644 index 00000000..4116f3aa Binary files /dev/null and b/Resources/Sparkle-Icon.sketch differ diff --git a/Resources/Sparkle.png b/Resources/Sparkle.png deleted file mode 100644 index 13d59cd2..00000000 Binary files a/Resources/Sparkle.png and /dev/null differ diff --git a/Sparkle.podspec b/Sparkle.podspec index 889a31e7..882746a6 100644 --- a/Sparkle.podspec +++ b/Sparkle.podspec @@ -1,7 +1,7 @@ Pod::Spec.new do |s| s.name = "Sparkle" - s.version = "1.13.1" - s.summary = "A software update framework for OS X" + s.version = "1.15.1" + s.summary = "A software update framework for macOS" s.description = "Sparkle is an easy-to-use software update framework for Cocoa developers." s.homepage = "http://sparkle-project.org" s.documentation_url = "http://sparkle-project.org/documentation/" @@ -11,15 +11,16 @@ Pod::Spec.new do |s| :file => 'LICENSE' } s.authors = { - 'Andy Matuschak' => 'andy@andymatuschak.org', - 'Kornel Lesiński' => 'pornel@pornel.net', - 'C.W. Betts' => 'computers57@hotmail.com', - 'Jake Petroules' => 'jake.petroules@petroules.com', 'Mayur Pawashe' => 'zorgiepoo@gmail.com', + 'Kornel Lesiński' => 'pornel@pornel.net', + 'Jake Petroules' => 'jake.petroules@petroules.com', + 'C.W. Betts' => 'computers57@hotmail.com', + 'Andy Matuschak' => 'andy@andymatuschak.org', } s.platform = :osx, '10.7' s.source = { :http => "https://github.com/sparkle-project/Sparkle/releases/download/#{s.version}/Sparkle-#{s.version}.tar.bz2" } + s.source_files = 'Sparkle.framework/Versions/A/Headers/*.h' s.public_header_files = 'Sparkle.framework/Versions/A/Headers/*.h' s.vendored_frameworks = 'Sparkle.framework' diff --git a/Sparkle.xcodeproj/project.pbxproj b/Sparkle.xcodeproj/project.pbxproj index bc20f2a0..2a500946 100644 --- a/Sparkle.xcodeproj/project.pbxproj +++ b/Sparkle.xcodeproj/project.pbxproj @@ -26,14 +26,13 @@ /* Begin PBXBuildFile section */ 1420DF50196247F900203BB0 /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 1420DF4F196247F900203BB0 /* Images.xcassets */; }; - 1420DF51196247F900203BB0 /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 1420DF4F196247F900203BB0 /* Images.xcassets */; }; 142E0E0019A6954400E4312B /* Sparkle.framework in Copy Frameworks */ = {isa = PBXBuildFile; fileRef = 8DC2EF5B0486A6940098B216 /* Sparkle.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; 142E0E0219A6A14700E4312B /* Sparkle.framework in Copy Files */ = {isa = PBXBuildFile; fileRef = 8DC2EF5B0486A6940098B216 /* Sparkle.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; 142E0E0419A6A26F00E4312B /* Updater.app in CopyFiles */ = {isa = PBXBuildFile; fileRef = 55C14BB7136EEF1500649790 /* Updater.app */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; 142E0E0919A83AAC00E4312B /* SUBinaryDeltaTest.m in Sources */ = {isa = PBXBuildFile; fileRef = 142E0E0819A83AAC00E4312B /* SUBinaryDeltaTest.m */; }; 14652F7C19A9725300959E44 /* SUBinaryDeltaCommon.m in Sources */ = {isa = PBXBuildFile; fileRef = 5D06E8E20FD68CC7005AE3F6 /* SUBinaryDeltaCommon.m */; }; 14652F7D19A9726700959E44 /* SUBinaryDeltaApply.m in Sources */ = {isa = PBXBuildFile; fileRef = 5D06E8E00FD68CC7005AE3F6 /* SUBinaryDeltaApply.m */; }; - 14652F7E19A9728A00959E44 /* bspatch.c in Sources */ = {isa = PBXBuildFile; fileRef = 5D06E8DC0FD68CB9005AE3F6 /* bspatch.c */; settings = {COMPILER_FLAGS = "-w"; }; }; + 14652F7E19A9728A00959E44 /* bspatch.c in Sources */ = {isa = PBXBuildFile; fileRef = 5D06E8DC0FD68CB9005AE3F6 /* bspatch.c */; }; 14652F8019A9740F00959E44 /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 61B5F8F609C4CEB300B25A18 /* Security.framework */; }; 14652F8219A9746000959E44 /* SULog.m in Sources */ = {isa = PBXBuildFile; fileRef = 55C14F05136EF6DB00649790 /* SULog.m */; }; 14652F8419A978C200959E44 /* SUExport.h in Headers */ = {isa = PBXBuildFile; fileRef = 14652F8319A9759F00959E44 /* SUExport.h */; settings = {ATTRIBUTES = (Public, ); }; }; @@ -72,16 +71,19 @@ 55C14F9A136F045400649790 /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 61B5F8F609C4CEB300B25A18 /* Security.framework */; }; 55C14FC7136F05E100649790 /* Sparkle.strings in Resources */ = {isa = PBXBuildFile; fileRef = 61AAE8220A321A7F00D8810D /* Sparkle.strings */; }; 55E6F33319EC9F6C00005E76 /* SUErrors.h in Headers */ = {isa = PBXBuildFile; fileRef = 55E6F33219EC9F6C00005E76 /* SUErrors.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 5A4094481C74EA5200983BE0 /* SUAppcastTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5AA4DCD01C73E5510078F128 /* SUAppcastTest.swift */; }; 5A6D31EE1BF53245009C5157 /* SUFileManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 7275F9C01B5F1F2900B1D19E /* SUFileManager.m */; }; 5A6D31EF1BF5325F009C5157 /* SUOperatingSystem.m in Sources */ = {isa = PBXBuildFile; fileRef = 726F2CE41BC9C33D001971A4 /* SUOperatingSystem.m */; }; + 5AD0FA7F1C73F2E2004BCEFF /* testappcast.xml in Resources */ = {isa = PBXBuildFile; fileRef = 5AD0FA7E1C73F2E2004BCEFF /* testappcast.xml */; }; 5AE459001C34118500E3BB47 /* SUUpdaterTest.m in Sources */ = {isa = PBXBuildFile; fileRef = 14950074195FDF5900BC5B5B /* SUUpdaterTest.m */; }; 5AE459021C34118500E3BB47 /* SUVersionComparisonTest.m in Sources */ = {isa = PBXBuildFile; fileRef = 61227A150DB548B800AB99EA /* SUVersionComparisonTest.m */; }; + 5AE7E1111DC81AD3009C2C12 /* AppIcon.icns in Resources */ = {isa = PBXBuildFile; fileRef = 5AE7E10E1DC81ACA009C2C12 /* AppIcon.icns */; }; 5AF6C74F1AEA46D10014A3AB /* test.sparkle_guided.pkg in Resources */ = {isa = PBXBuildFile; fileRef = 5AF6C74E1AEA46D10014A3AB /* test.sparkle_guided.pkg */; }; 5AF6C7541AEA49840014A3AB /* SUInstallerTest.m in Sources */ = {isa = PBXBuildFile; fileRef = 5AF6C74C1AEA40760014A3AB /* SUInstallerTest.m */; }; 5AF9DC3C1981DBEE001EA135 /* SUDSAVerifierTest.m in Sources */ = {isa = PBXBuildFile; fileRef = 5AF9DC3B1981DBEE001EA135 /* SUDSAVerifierTest.m */; }; - 5D06E8E90FD68CDB005AE3F6 /* bsdiff.c in Sources */ = {isa = PBXBuildFile; fileRef = 5D06E8DB0FD68CB9005AE3F6 /* bsdiff.c */; settings = {COMPILER_FLAGS = "-w"; }; }; + 5D06E8E90FD68CDB005AE3F6 /* bsdiff.c in Sources */ = {isa = PBXBuildFile; fileRef = 5D06E8DB0FD68CB9005AE3F6 /* bsdiff.c */; }; 5D06E8EA0FD68CDB005AE3F6 /* SUBinaryDeltaTool.m in Sources */ = {isa = PBXBuildFile; fileRef = 5D06E8E30FD68CC7005AE3F6 /* SUBinaryDeltaTool.m */; }; - 5D06E8EB0FD68CE4005AE3F6 /* bspatch.c in Sources */ = {isa = PBXBuildFile; fileRef = 5D06E8DC0FD68CB9005AE3F6 /* bspatch.c */; settings = {COMPILER_FLAGS = "-w"; }; }; + 5D06E8EB0FD68CE4005AE3F6 /* bspatch.c in Sources */ = {isa = PBXBuildFile; fileRef = 5D06E8DC0FD68CB9005AE3F6 /* bspatch.c */; }; 5D06E8EC0FD68CE4005AE3F6 /* SUBinaryDeltaApply.m in Sources */ = {isa = PBXBuildFile; fileRef = 5D06E8E00FD68CC7005AE3F6 /* SUBinaryDeltaApply.m */; }; 5D06E8ED0FD68CE4005AE3F6 /* SUBinaryDeltaCommon.m in Sources */ = {isa = PBXBuildFile; fileRef = 5D06E8E20FD68CC7005AE3F6 /* SUBinaryDeltaCommon.m */; }; 5D06E8FD0FD68D6B005AE3F6 /* libbz2.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 5D06E8FB0FD68D61005AE3F6 /* libbz2.dylib */; }; @@ -94,6 +96,7 @@ 5D1AF5900FD767AD0065DB48 /* libxml2.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 5D1AF58F0FD767AD0065DB48 /* libxml2.dylib */; }; 5D1AF59A0FD767E50065DB48 /* libz.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 5D1AF5990FD767E50065DB48 /* libz.dylib */; }; 5D1AF82B0FD768180065DB48 /* libz.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 5D1AF5990FD767E50065DB48 /* libz.dylib */; }; + 5F1510A21C96E591006E1629 /* testnamespaces.xml in Resources */ = {isa = PBXBuildFile; fileRef = 5F1510A11C96E591006E1629 /* testnamespaces.xml */; }; 610134730DD250470049ACDF /* SUUpdateDriver.h in Headers */ = {isa = PBXBuildFile; fileRef = 610134710DD250470049ACDF /* SUUpdateDriver.h */; settings = {ATTRIBUTES = (); }; }; 610134740DD250470049ACDF /* SUUpdateDriver.m in Sources */ = {isa = PBXBuildFile; fileRef = 610134720DD250470049ACDF /* SUUpdateDriver.m */; }; 6101347B0DD2541A0049ACDF /* SUProbingUpdateDriver.h in Headers */ = {isa = PBXBuildFile; fileRef = 610134790DD2541A0049ACDF /* SUProbingUpdateDriver.h */; settings = {ATTRIBUTES = (); }; }; @@ -102,7 +105,6 @@ 6102FE4A0E07803800F85D09 /* SUDiskImageUnarchiver.h in Headers */ = {isa = PBXBuildFile; fileRef = 6102FE480E07803800F85D09 /* SUDiskImageUnarchiver.h */; settings = {ATTRIBUTES = (); }; }; 6102FE4B0E07803800F85D09 /* SUDiskImageUnarchiver.m in Sources */ = {isa = PBXBuildFile; fileRef = 6102FE490E07803800F85D09 /* SUDiskImageUnarchiver.m */; }; 6102FE5B0E08C7EC00F85D09 /* SUUnarchiver_Private.h in Headers */ = {isa = PBXBuildFile; fileRef = 6102FE590E08C7EC00F85D09 /* SUUnarchiver_Private.h */; settings = {ATTRIBUTES = (); }; }; - 610EC1E00CF3A5FE00AE239E /* NTSynchronousTask.m in Sources */ = {isa = PBXBuildFile; fileRef = 610EC1BF0CF3914D00AE239E /* NTSynchronousTask.m */; }; 611142E910FB1BE5009810AA /* bspatch.h in Headers */ = {isa = PBXBuildFile; fileRef = 611142E810FB1BE5009810AA /* bspatch.h */; }; 61177A1F0D1112E900749C97 /* IOKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6117796E0D1112E000749C97 /* IOKit.framework */; }; 61180BCA0D64138900B4E0D1 /* SUWindowController.h in Headers */ = {isa = PBXBuildFile; fileRef = 61180BC80D64138900B4E0D1 /* SUWindowController.h */; settings = {ATTRIBUTES = (); }; }; @@ -120,7 +122,6 @@ 612DCBB00D488BC60015DBEA /* SUUpdatePermissionPrompt.m in Sources */ = {isa = PBXBuildFile; fileRef = 612DCBAE0D488BC60015DBEA /* SUUpdatePermissionPrompt.m */; }; 6158A1C5137904B300487EC1 /* SUUpdater_Private.h in Headers */ = {isa = PBXBuildFile; fileRef = 6158A1C4137904B300487EC1 /* SUUpdater_Private.h */; }; 615AE3D00D64DC40001CA7BD /* SUModelTranslation.plist in Resources */ = {isa = PBXBuildFile; fileRef = 615AE3CF0D64DC40001CA7BD /* SUModelTranslation.plist */; }; - 6160E7E10D3B4A8800E9CD71 /* NTSynchronousTask.h in Headers */ = {isa = PBXBuildFile; fileRef = 610EC1C00CF3914D00AE239E /* NTSynchronousTask.h */; settings = {ATTRIBUTES = (); }; }; 618FA5010DAE88B40026945C /* SUInstaller.h in Headers */ = {isa = PBXBuildFile; fileRef = 618FA4FF0DAE88B40026945C /* SUInstaller.h */; settings = {ATTRIBUTES = (); }; }; 618FA5020DAE88B40026945C /* SUInstaller.m in Sources */ = {isa = PBXBuildFile; fileRef = 618FA5000DAE88B40026945C /* SUInstaller.m */; }; 618FA5050DAE8AB80026945C /* SUPlainInstaller.h in Headers */ = {isa = PBXBuildFile; fileRef = 618FA5030DAE8AB80026945C /* SUPlainInstaller.h */; settings = {ATTRIBUTES = (); }; }; @@ -166,13 +167,33 @@ 61F83F720DBFE140006FDD30 /* SUBasicUpdateDriver.m in Sources */ = {isa = PBXBuildFile; fileRef = 61F83F700DBFE137006FDD30 /* SUBasicUpdateDriver.m */; }; 61F83F740DBFE141006FDD30 /* SUBasicUpdateDriver.h in Headers */ = {isa = PBXBuildFile; fileRef = 61F83F6F0DBFE137006FDD30 /* SUBasicUpdateDriver.h */; settings = {ATTRIBUTES = (); }; }; 61FA52880E2D9EA400EF58AD /* Sparkle.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8DC2EF5B0486A6940098B216 /* Sparkle.framework */; settings = {ATTRIBUTES = (Required, ); }; }; + 720B16451C66433D006985FB /* SUTestApplicationTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 720B16431C66433D006985FB /* SUTestApplicationTest.swift */; }; 7210C7681B9A9A1500EB90AC /* SUUnarchiverTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7210C7671B9A9A1500EB90AC /* SUUnarchiverTest.swift */; }; - 721CF1A71AD7643600D9AC09 /* bsdiff.c in Sources */ = {isa = PBXBuildFile; fileRef = 5D06E8DB0FD68CB9005AE3F6 /* bsdiff.c */; settings = {COMPILER_FLAGS = "-w"; }; }; - 721CF1A81AD7644100D9AC09 /* bspatch.c in Sources */ = {isa = PBXBuildFile; fileRef = 5D06E8DC0FD68CB9005AE3F6 /* bspatch.c */; settings = {COMPILER_FLAGS = "-w"; }; }; - 721CF1A91AD7644C00D9AC09 /* sais.c in Sources */ = {isa = PBXBuildFile; fileRef = 7223E7611AD1AEFF008E3161 /* sais.c */; settings = {COMPILER_FLAGS = "-w"; }; }; + 721BC2111D1DFF05002BC71E /* SUFileOperationConstants.m in Sources */ = {isa = PBXBuildFile; fileRef = 722954C31D04E66F00ECF9CA /* SUFileOperationConstants.m */; }; + 721CF1A71AD7643600D9AC09 /* bsdiff.c in Sources */ = {isa = PBXBuildFile; fileRef = 5D06E8DB0FD68CB9005AE3F6 /* bsdiff.c */; }; + 721CF1A81AD7644100D9AC09 /* bspatch.c in Sources */ = {isa = PBXBuildFile; fileRef = 5D06E8DC0FD68CB9005AE3F6 /* bspatch.c */; }; + 721CF1A91AD7644C00D9AC09 /* sais.c in Sources */ = {isa = PBXBuildFile; fileRef = 7223E7611AD1AEFF008E3161 /* sais.c */; }; 721CF1AA1AD7647000D9AC09 /* libxar.1.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 5D1AF5890FD7678C0065DB48 /* libxar.1.dylib */; }; 721CF1AB1AD764EB00D9AC09 /* libbz2.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 5D06E8FB0FD68D61005AE3F6 /* libbz2.dylib */; }; 7223E7631AD1AEFF008E3161 /* sais.c in Sources */ = {isa = PBXBuildFile; fileRef = 7223E7611AD1AEFF008E3161 /* sais.c */; }; + 722954B71D04ADAF00ECF9CA /* fileop.m in Sources */ = {isa = PBXBuildFile; fileRef = 722954B61D04ADAF00ECF9CA /* fileop.m */; }; + 722954BC1D04AE1100ECF9CA /* SUFileManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 7275F9C01B5F1F2900B1D19E /* SUFileManager.m */; }; + 722954BD1D04AE3800ECF9CA /* SUConstants.m in Sources */ = {isa = PBXBuildFile; fileRef = 61299A5F09CA6EB100B7442F /* SUConstants.m */; }; + 722954C11D04D9ED00ECF9CA /* fileop in Copy fileop */ = {isa = PBXBuildFile; fileRef = 722954B41D04ADAF00ECF9CA /* fileop */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; }; + 722954C41D04E66F00ECF9CA /* SUFileOperationConstants.h in Headers */ = {isa = PBXBuildFile; fileRef = 722954C21D04E66F00ECF9CA /* SUFileOperationConstants.h */; }; + 722954C51D04E66F00ECF9CA /* SUFileOperationConstants.m in Sources */ = {isa = PBXBuildFile; fileRef = 722954C31D04E66F00ECF9CA /* SUFileOperationConstants.m */; }; + 722954C61D04E66F00ECF9CA /* SUFileOperationConstants.m in Sources */ = {isa = PBXBuildFile; fileRef = 722954C31D04E66F00ECF9CA /* SUFileOperationConstants.m */; }; + 722954C71D04E66F00ECF9CA /* SUFileOperationConstants.m in Sources */ = {isa = PBXBuildFile; fileRef = 722954C31D04E66F00ECF9CA /* SUFileOperationConstants.m */; }; + 722954C91D04EA5C00ECF9CA /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0867D69BFE84028FC02AAC07 /* Foundation.framework */; }; + 722954CA1D04EA6000ECF9CA /* AppKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0867D6A5FE840307C02AAC07 /* AppKit.framework */; }; + 722954CB1D04EA6900ECF9CA /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 61B5F8F609C4CEB300B25A18 /* Security.framework */; }; + 722954CC1D04EA7000ECF9CA /* SUOperatingSystem.m in Sources */ = {isa = PBXBuildFile; fileRef = 726F2CE41BC9C33D001971A4 /* SUOperatingSystem.m */; }; + 723A920E1D722438004A9DED /* SUSpotlightImporterTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 723A920D1D722438004A9DED /* SUSpotlightImporterTest.swift */; }; + 723B252D1CEAB3A600909873 /* bscommon.c in Sources */ = {isa = PBXBuildFile; fileRef = 723B252B1CEAB3A600909873 /* bscommon.c */; }; + 723B252E1CEAB3A600909873 /* bscommon.c in Sources */ = {isa = PBXBuildFile; fileRef = 723B252B1CEAB3A600909873 /* bscommon.c */; }; + 723B252F1CEAB3A600909873 /* bscommon.c in Sources */ = {isa = PBXBuildFile; fileRef = 723B252B1CEAB3A600909873 /* bscommon.c */; }; + 723B25301CEAB3A600909873 /* bscommon.h in Headers */ = {isa = PBXBuildFile; fileRef = 723B252C1CEAB3A600909873 /* bscommon.h */; }; + 72544FFC1D0991A4000CFB2C /* SUFileOperationConstants.m in Sources */ = {isa = PBXBuildFile; fileRef = 722954C31D04E66F00ECF9CA /* SUFileOperationConstants.m */; }; 7268AC631AD634C200C3E0C1 /* SUBinaryDeltaCreate.m in Sources */ = {isa = PBXBuildFile; fileRef = 7268AC621AD634C200C3E0C1 /* SUBinaryDeltaCreate.m */; }; 726F2CDE1BC9BE5B001971A4 /* SUFileManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 7275F9C01B5F1F2900B1D19E /* SUFileManager.m */; }; 726F2CE51BC9C33D001971A4 /* SUOperatingSystem.h in Headers */ = {isa = PBXBuildFile; fileRef = 726F2CE31BC9C33D001971A4 /* SUOperatingSystem.h */; }; @@ -184,6 +205,8 @@ 7275F9C11B5F1F2900B1D19E /* SUFileManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 7275F9BF1B5F1F2900B1D19E /* SUFileManager.h */; }; 7275F9C21B5F1F2900B1D19E /* SUFileManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 7275F9C01B5F1F2900B1D19E /* SUFileManager.m */; }; 7275F9C31B5F1F2900B1D19E /* SUFileManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 7275F9C01B5F1F2900B1D19E /* SUFileManager.m */; }; + 729924731DF3478A00DBCDF5 /* SUUpdateValidator.h in Headers */ = {isa = PBXBuildFile; fileRef = 729924711DF3478A00DBCDF5 /* SUUpdateValidator.h */; }; + 729924741DF3478A00DBCDF5 /* SUUpdateValidator.m in Sources */ = {isa = PBXBuildFile; fileRef = 729924721DF3478A00DBCDF5 /* SUUpdateValidator.m */; }; 72A4A2401BB6567D00E7820D /* SUFileManagerTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 72A4A23F1BB6567D00E7820D /* SUFileManagerTest.swift */; }; 72AC6B261B9AAC8800F62325 /* SparkleTestCodeSignApp.tar.gz in Resources */ = {isa = PBXBuildFile; fileRef = 72AC6B251B9AAC8800F62325 /* SparkleTestCodeSignApp.tar.gz */; }; 72AC6B281B9AAD6700F62325 /* SparkleTestCodeSignApp.tar in Resources */ = {isa = PBXBuildFile; fileRef = 72AC6B271B9AAD6700F62325 /* SparkleTestCodeSignApp.tar */; }; @@ -197,6 +220,7 @@ 72E45CFC1B641961005C701A /* sparkletestcast.xml in Resources */ = {isa = PBXBuildFile; fileRef = 72E45CFB1B641961005C701A /* sparkletestcast.xml */; }; 72E45CFE1B641D0D005C701A /* test_app_only_dsa_priv_dont_ever_do_this_for_real.pem in Resources */ = {isa = PBXBuildFile; fileRef = 72E45CFD1B641D0D005C701A /* test_app_only_dsa_priv_dont_ever_do_this_for_real.pem */; }; 72E45DDD1B65C3BD005C701A /* sign_update in Resources */ = {isa = PBXBuildFile; fileRef = 72E45DDC1B65C3BD005C701A /* sign_update */; }; + 72E641801D08D754000404CA /* fileop in Resources */ = {isa = PBXBuildFile; fileRef = 722954B41D04ADAF00ECF9CA /* fileop */; }; 767B61AC1972D488004E0C3C /* SUGuidedPackageInstaller.h in Headers */ = {isa = PBXBuildFile; fileRef = 767B61AA1972D488004E0C3C /* SUGuidedPackageInstaller.h */; }; 767B61AD1972D488004E0C3C /* SUGuidedPackageInstaller.m in Sources */ = {isa = PBXBuildFile; fileRef = 767B61AB1972D488004E0C3C /* SUGuidedPackageInstaller.m */; }; 767B61AE1972D488004E0C3C /* SUGuidedPackageInstaller.m in Sources */ = {isa = PBXBuildFile; fileRef = 767B61AB1972D488004E0C3C /* SUGuidedPackageInstaller.m */; }; @@ -299,6 +323,20 @@ remoteGlobalIDString = 8DC2EF4F0486A6940098B216; remoteInfo = Sparkle; }; + 722954BE1D04D9CB00ECF9CA /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 0867D690FE84028FC02AAC07 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 722954B31D04ADAF00ECF9CA; + remoteInfo = fileop; + }; + 726B2B621C645FC900388755 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 0867D690FE84028FC02AAC07 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 61B5F90109C4CEE200B25A18; + remoteInfo = "Sparkle Test App"; + }; /* End PBXContainerItemProxy section */ /* Begin PBXCopyFilesBuildPhase section */ @@ -334,6 +372,26 @@ name = "Copy Frameworks"; runOnlyForDeploymentPostprocessing = 0; }; + 722954B21D04ADAF00ECF9CA /* CopyFiles */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = /usr/share/man/man1/; + dstSubfolderSpec = 0; + files = ( + ); + runOnlyForDeploymentPostprocessing = 1; + }; + 722954C01D04D9D600ECF9CA /* Copy fileop */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 6; + files = ( + 722954C11D04D9ED00ECF9CA /* fileop in Copy fileop */, + ); + name = "Copy fileop"; + runOnlyForDeploymentPostprocessing = 0; + }; /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ @@ -479,6 +537,9 @@ 55C14F05136EF6DB00649790 /* SULog.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SULog.m; sourceTree = ""; }; 55C14F31136EFC2400649790 /* SystemConfiguration.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SystemConfiguration.framework; path = System/Library/Frameworks/SystemConfiguration.framework; sourceTree = SDKROOT; }; 55E6F33219EC9F6C00005E76 /* SUErrors.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUErrors.h; sourceTree = ""; }; + 5AA4DCD01C73E5510078F128 /* SUAppcastTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SUAppcastTest.swift; sourceTree = ""; }; + 5AD0FA7E1C73F2E2004BCEFF /* testappcast.xml */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xml; path = testappcast.xml; sourceTree = ""; }; + 5AE7E10E1DC81ACA009C2C12 /* AppIcon.icns */ = {isa = PBXFileReference; lastKnownFileType = image.icns; path = AppIcon.icns; sourceTree = ""; }; 5AEF45D9189D1CC90030D7DC /* tr */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = tr; path = tr.lproj/Sparkle.strings; sourceTree = ""; }; 5AF6C74C1AEA40760014A3AB /* SUInstallerTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SUInstallerTest.m; sourceTree = ""; }; 5AF6C74E1AEA46D10014A3AB /* test.sparkle_guided.pkg */ = {isa = PBXFileReference; lastKnownFileType = file; path = test.sparkle_guided.pkg; sourceTree = ""; }; @@ -500,6 +561,7 @@ 5D1AF5890FD7678C0065DB48 /* libxar.1.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libxar.1.dylib; path = usr/lib/libxar.1.dylib; sourceTree = SDKROOT; }; 5D1AF58F0FD767AD0065DB48 /* libxml2.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libxml2.dylib; path = usr/lib/libxml2.dylib; sourceTree = SDKROOT; }; 5D1AF5990FD767E50065DB48 /* libz.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libz.dylib; path = usr/lib/libz.dylib; sourceTree = SDKROOT; }; + 5F1510A11C96E591006E1629 /* testnamespaces.xml */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xml; path = testnamespaces.xml; sourceTree = ""; }; 610134710DD250470049ACDF /* SUUpdateDriver.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUUpdateDriver.h; sourceTree = ""; }; 610134720DD250470049ACDF /* SUUpdateDriver.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SUUpdateDriver.m; sourceTree = ""; }; 610134790DD2541A0049ACDF /* SUProbingUpdateDriver.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUProbingUpdateDriver.h; sourceTree = ""; }; @@ -508,8 +570,6 @@ 6102FE480E07803800F85D09 /* SUDiskImageUnarchiver.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUDiskImageUnarchiver.h; sourceTree = ""; }; 6102FE490E07803800F85D09 /* SUDiskImageUnarchiver.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SUDiskImageUnarchiver.m; sourceTree = ""; }; 6102FE590E08C7EC00F85D09 /* SUUnarchiver_Private.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUUnarchiver_Private.h; sourceTree = ""; }; - 610EC1BF0CF3914D00AE239E /* NTSynchronousTask.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = NTSynchronousTask.m; sourceTree = ""; }; - 610EC1C00CF3914D00AE239E /* NTSynchronousTask.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = NTSynchronousTask.h; sourceTree = ""; }; 611142E810FB1BE5009810AA /* bspatch.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = bspatch.h; sourceTree = ""; }; 61131A050F846CE600E97AF6 /* da */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.strings; name = da; path = da.lproj/Sparkle.strings; sourceTree = ""; }; 61131A090F846D0A00E97AF6 /* zh_CN */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.strings; name = zh_CN; path = zh_CN.lproj/Sparkle.strings; sourceTree = ""; }; @@ -610,15 +670,35 @@ 61F614540E24A12D009F47E7 /* it */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.strings; name = it; path = it.lproj/Sparkle.strings; sourceTree = ""; }; 61F83F6F0DBFE137006FDD30 /* SUBasicUpdateDriver.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUBasicUpdateDriver.h; sourceTree = ""; }; 61F83F700DBFE137006FDD30 /* SUBasicUpdateDriver.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SUBasicUpdateDriver.m; sourceTree = ""; }; + 720B16421C66433D006985FB /* UITests-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = "UITests-Info.plist"; path = "UITests/UITests-Info.plist"; sourceTree = SOURCE_ROOT; }; + 720B16431C66433D006985FB /* SUTestApplicationTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SUTestApplicationTest.swift; path = UITests/SUTestApplicationTest.swift; sourceTree = SOURCE_ROOT; }; 7210C7671B9A9A1500EB90AC /* SUUnarchiverTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SUUnarchiverTest.swift; sourceTree = ""; }; 7223E7611AD1AEFF008E3161 /* sais.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = sais.c; sourceTree = ""; }; 7223E7621AD1AEFF008E3161 /* sais.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = sais.h; sourceTree = ""; }; + 722954B41D04ADAF00ECF9CA /* fileop */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = fileop; sourceTree = BUILT_PRODUCTS_DIR; }; + 722954B61D04ADAF00ECF9CA /* fileop.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = fileop.m; sourceTree = ""; }; + 722954C21D04E66F00ECF9CA /* SUFileOperationConstants.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUFileOperationConstants.h; sourceTree = ""; }; + 722954C31D04E66F00ECF9CA /* SUFileOperationConstants.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SUFileOperationConstants.m; sourceTree = ""; }; + 722954C81D04E89500ECF9CA /* ConfigFileop.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = ConfigFileop.xcconfig; sourceTree = ""; }; + 722FB7471DD51331001D40CE /* ConfigSwift.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = ConfigSwift.xcconfig; sourceTree = ""; }; + 722FB7481DD51350001D40CE /* ConfigSwiftDebug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = ConfigSwiftDebug.xcconfig; sourceTree = ""; }; + 722FB7491DD51350001D40CE /* ConfigSwiftRelease.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = ConfigSwiftRelease.xcconfig; sourceTree = ""; }; + 723A920D1D722438004A9DED /* SUSpotlightImporterTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SUSpotlightImporterTest.swift; sourceTree = ""; }; + 723B252B1CEAB3A600909873 /* bscommon.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = bscommon.c; sourceTree = ""; }; + 723B252C1CEAB3A600909873 /* bscommon.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = bscommon.h; sourceTree = ""; }; 7268AC621AD634C200C3E0C1 /* SUBinaryDeltaCreate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SUBinaryDeltaCreate.m; sourceTree = ""; }; 7268AC641AD634E400C3E0C1 /* SUBinaryDeltaCreate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUBinaryDeltaCreate.h; sourceTree = ""; }; + 726B2B5D1C645FC900388755 /* UI Tests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "UI Tests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; }; 726F2CE31BC9C33D001971A4 /* SUOperatingSystem.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUOperatingSystem.h; sourceTree = ""; }; 726F2CE41BC9C33D001971A4 /* SUOperatingSystem.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SUOperatingSystem.m; sourceTree = ""; }; 7275F9BF1B5F1F2900B1D19E /* SUFileManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUFileManager.h; sourceTree = ""; }; 7275F9C01B5F1F2900B1D19E /* SUFileManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SUFileManager.m; sourceTree = ""; }; + 729924711DF3478A00DBCDF5 /* SUUpdateValidator.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUUpdateValidator.h; sourceTree = ""; }; + 729924721DF3478A00DBCDF5 /* SUUpdateValidator.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SUUpdateValidator.m; sourceTree = ""; }; + 729F10FD1C65A9B500DFCCC5 /* ConfigUITest.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = ConfigUITest.xcconfig; sourceTree = ""; }; + 729F10FE1C65A9B500DFCCC5 /* ConfigUITestCoverage.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = ConfigUITestCoverage.xcconfig; sourceTree = ""; }; + 729F10FF1C65A9B500DFCCC5 /* ConfigUITestDebug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = ConfigUITestDebug.xcconfig; sourceTree = ""; }; + 729F11001C65A9B500DFCCC5 /* ConfigUITestRelease.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = ConfigUITestRelease.xcconfig; sourceTree = ""; }; 72A4A23F1BB6567D00E7820D /* SUFileManagerTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SUFileManagerTest.swift; sourceTree = ""; }; 72AC6B251B9AAC8800F62325 /* SparkleTestCodeSignApp.tar.gz */ = {isa = PBXFileReference; lastKnownFileType = archive.gzip; path = SparkleTestCodeSignApp.tar.gz; sourceTree = ""; }; 72AC6B271B9AAD6700F62325 /* SparkleTestCodeSignApp.tar */ = {isa = PBXFileReference; lastKnownFileType = archive.tar; path = SparkleTestCodeSignApp.tar; sourceTree = ""; }; @@ -709,6 +789,23 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + 722954B11D04ADAF00ECF9CA /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 722954CB1D04EA6900ECF9CA /* Security.framework in Frameworks */, + 722954CA1D04EA6000ECF9CA /* AppKit.framework in Frameworks */, + 722954C91D04EA5C00ECF9CA /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 726B2B5A1C645FC900388755 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; 8DC2EF560486A6940098B216 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; @@ -736,6 +833,8 @@ 61B5F90209C4CEE200B25A18 /* Sparkle Test App.app */, 612279D90DB5470200AB99EA /* Sparkle Unit Tests.xctest */, 8DC2EF5B0486A6940098B216 /* Sparkle.framework */, + 726B2B5D1C645FC900388755 /* UI Tests.xctest */, + 722954B41D04ADAF00ECF9CA /* fileop */, ); name = Products; sourceTree = ""; @@ -750,6 +849,7 @@ 14732BB51960ECBA00593899 /* Third Party */, 1420DE391962322200203BB0 /* Documentation */, FA1941C40D94A6EA00DD942E /* Configurations */, + 726B2B5E1C645FC900388755 /* UI Tests */, 0867D69AFE84028FC02AAC07 /* Frameworks */, 034768DFFF38A50411DB9C8B /* Products */, ); @@ -802,7 +902,6 @@ isa = PBXGroup; children = ( 14732BB61960ECE800593899 /* bsdiff */, - 14732BB71960ECF000593899 /* CocoatechCore */, ); name = "Third Party"; path = Vendor; @@ -811,6 +910,8 @@ 14732BB61960ECE800593899 /* bsdiff */ = { isa = PBXGroup; children = ( + 723B252B1CEAB3A600909873 /* bscommon.c */, + 723B252C1CEAB3A600909873 /* bscommon.h */, 5D06E8DB0FD68CB9005AE3F6 /* bsdiff.c */, 5D06E8DC0FD68CB9005AE3F6 /* bspatch.c */, 611142E810FB1BE5009810AA /* bspatch.h */, @@ -820,15 +921,6 @@ path = bsdiff; sourceTree = ""; }; - 14732BB71960ECF000593899 /* CocoatechCore */ = { - isa = PBXGroup; - children = ( - 610EC1C00CF3914D00AE239E /* NTSynchronousTask.h */, - 610EC1BF0CF3914D00AE239E /* NTSynchronousTask.m */, - ); - path = CocoatechCore; - sourceTree = ""; - }; 14732BB81960EEB600593899 /* Resources */ = { isa = PBXGroup; children = ( @@ -840,6 +932,7 @@ 1420DF4F196247F900203BB0 /* Images.xcassets */, 14732BBC1960EFB500593899 /* README.markdown */, 14732BB91960EEEE00593899 /* SampleAppcast.xml */, + 5AE7E10E1DC81ACA009C2C12 /* AppIcon.icns */, 615AE3CF0D64DC40001CA7BD /* SUModelTranslation.plist */, ); path = Resources; @@ -882,6 +975,8 @@ F8761EB21ADC50EB000C9034 /* SparkleTestCodeSignApp.zip */, 14958C6C19AEBC610061B14F /* test-pubkey.pem */, 5AF6C74E1AEA46D10014A3AB /* test.sparkle_guided.pkg */, + 5AD0FA7E1C73F2E2004BCEFF /* testappcast.xml */, + 5F1510A11C96E591006E1629 /* testnamespaces.xml */, ); path = Resources; sourceTree = ""; @@ -889,6 +984,7 @@ 55C14BD5136EEFD000649790 /* Autoupdate */ = { isa = PBXGroup; children = ( + 722954B51D04ADAF00ECF9CA /* fileop */, 55C14BB9136EEF1500649790 /* Autoupdate-Info.plist */, 55C14BD3136EEFCE00649790 /* Autoupdate.m */, ); @@ -932,11 +1028,13 @@ 14958C7019AEBE350061B14F /* Resources */, 72AFC6121B9A944200F6B565 /* Sparkle Unit Tests-Bridging-Header.h */, 612279DA0DB5470200AB99EA /* SparkleTests-Info.plist */, + 5AA4DCD01C73E5510078F128 /* SUAppcastTest.swift */, 142E0E0819A83AAC00E4312B /* SUBinaryDeltaTest.m */, F8761EB01ADC5068000C9034 /* SUCodeSigningVerifierTest.m */, 5AF9DC3B1981DBEE001EA135 /* SUDSAVerifierTest.m */, 72A4A23F1BB6567D00E7820D /* SUFileManagerTest.swift */, 5AF6C74C1AEA40760014A3AB /* SUInstallerTest.m */, + 723A920D1D722438004A9DED /* SUSpotlightImporterTest.swift */, 7210C7671B9A9A1500EB90AC /* SUUnarchiverTest.swift */, 14950074195FDF5900BC5B5B /* SUUpdaterTest.m */, 61227A150DB548B800AB99EA /* SUVersionComparisonTest.m */, @@ -1040,6 +1138,8 @@ 61CFB2C10E384958007A1735 /* Support */ = { isa = PBXGroup; children = ( + 729924711DF3478A00DBCDF5 /* SUUpdateValidator.h */, + 729924721DF3478A00DBCDF5 /* SUUpdateValidator.m */, 61B078CC15A5FB6100600039 /* SUCodeSigningVerifier.h */, 61B078CD15A5FB6100600039 /* SUCodeSigningVerifier.m */, 61299A2D09CA2DAB00B7442F /* SUDSAVerifier.h */, @@ -1081,6 +1181,26 @@ name = "Update Control"; sourceTree = ""; }; + 722954B51D04ADAF00ECF9CA /* fileop */ = { + isa = PBXGroup; + children = ( + 722954B61D04ADAF00ECF9CA /* fileop.m */, + 722954C21D04E66F00ECF9CA /* SUFileOperationConstants.h */, + 722954C31D04E66F00ECF9CA /* SUFileOperationConstants.m */, + ); + name = fileop; + path = ../../fileop; + sourceTree = ""; + }; + 726B2B5E1C645FC900388755 /* UI Tests */ = { + isa = PBXGroup; + children = ( + 720B16431C66433D006985FB /* SUTestApplicationTest.swift */, + 720B16421C66433D006985FB /* UITests-Info.plist */, + ); + path = "UI Tests"; + sourceTree = ""; + }; FA1941C40D94A6EA00DD942E /* Configurations */ = { isa = PBXGroup; children = ( @@ -1098,6 +1218,7 @@ FA1941CE0D94A70100DD942E /* ConfigRelaunch.xcconfig */, FA1941D30D94A70100DD942E /* ConfigRelaunchDebug.xcconfig */, FA1941D40D94A70100DD942E /* ConfigRelaunchRelease.xcconfig */, + 722954C81D04E89500ECF9CA /* ConfigFileop.xcconfig */, FA1941CD0D94A70100DD942E /* ConfigTestApp.xcconfig */, FA1941CB0D94A70100DD942E /* ConfigTestAppDebug.xcconfig */, FA1941D20D94A70100DD942E /* ConfigTestAppRelease.xcconfig */, @@ -1105,6 +1226,13 @@ 149B78641B7D3A4800D7D62C /* ConfigUnitTestCoverage.xcconfig */, FA3AAF3A1050B273004B3130 /* ConfigUnitTestDebug.xcconfig */, FA3AAF391050B273004B3130 /* ConfigUnitTestRelease.xcconfig */, + 729F10FD1C65A9B500DFCCC5 /* ConfigUITest.xcconfig */, + 729F10FE1C65A9B500DFCCC5 /* ConfigUITestCoverage.xcconfig */, + 729F10FF1C65A9B500DFCCC5 /* ConfigUITestDebug.xcconfig */, + 729F11001C65A9B500DFCCC5 /* ConfigUITestRelease.xcconfig */, + 722FB7471DD51331001D40CE /* ConfigSwift.xcconfig */, + 722FB7481DD51350001D40CE /* ConfigSwiftDebug.xcconfig */, + 722FB7491DD51350001D40CE /* ConfigSwiftRelease.xcconfig */, 14732BC91960F70A00593899 /* make-release-package.sh */, 14652F7919A93E5F00959E44 /* set-git-version-info.sh */, 146EC84E19A68CF8004A50C5 /* Sparkle.podspec */, @@ -1120,7 +1248,6 @@ buildActionMask = 2147483647; files = ( 611142E910FB1BE5009810AA /* bspatch.h in Headers */, - 6160E7E10D3B4A8800E9CD71 /* NTSynchronousTask.h in Headers */, 61299B3609CB04E000B7442F /* Sparkle.h in Headers */, 61CFB3290E385186007A1735 /* Sparkle.pch in Headers */, 61B5FC0D09C4FC8200B25A18 /* SUAppcast.h in Headers */, @@ -1138,6 +1265,8 @@ 7275F9C11B5F1F2900B1D19E /* SUFileManager.h in Headers */, 767B61AC1972D488004E0C3C /* SUGuidedPackageInstaller.h in Headers */, 61EF67590E25C5B400F754E0 /* SUHost.h in Headers */, + 729924731DF3478A00DBCDF5 /* SUUpdateValidator.h in Headers */, + 723B25301CEAB3A600909873 /* bscommon.h in Headers */, 618FA5010DAE88B40026945C /* SUInstaller.h in Headers */, 55C14F06136EF6DB00649790 /* SULog.h in Headers */, 726F2CE51BC9C33D001971A4 /* SUOperatingSystem.h in Headers */, @@ -1160,6 +1289,7 @@ 61A354550DF113C70076ECB1 /* SUUserInitiatedUpdateDriver.h in Headers */, 61A2259E0D1C495D00430CCD /* SUVersionComparisonProtocol.h in Headers */, 3772FEA913DE0B6B00F79537 /* SUVersionDisplayProtocol.h in Headers */, + 722954C41D04E66F00ECF9CA /* SUFileOperationConstants.h in Headers */, 61180BCA0D64138900B4E0D1 /* SUWindowController.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; @@ -1210,10 +1340,12 @@ 55C14BB4136EEF1500649790 /* Sources */, 55C14BB5136EEF1500649790 /* Frameworks */, 14652F7B19A945D600959E44 /* Run Script: Set Git Version Info */, + 722954C01D04D9D600ECF9CA /* Copy fileop */, ); buildRules = ( ); dependencies = ( + 722954BF1D04D9CB00ECF9CA /* PBXTargetDependency */, ); name = Autoupdate; productName = Autoupdate; @@ -1275,6 +1407,41 @@ productReference = 61B5F90209C4CEE200B25A18 /* Sparkle Test App.app */; productType = "com.apple.product-type.application"; }; + 722954B31D04ADAF00ECF9CA /* fileop */ = { + isa = PBXNativeTarget; + buildConfigurationList = 722954BB1D04ADAF00ECF9CA /* Build configuration list for PBXNativeTarget "fileop" */; + buildPhases = ( + 722954B01D04ADAF00ECF9CA /* Sources */, + 722954B11D04ADAF00ECF9CA /* Frameworks */, + 722954B21D04ADAF00ECF9CA /* CopyFiles */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = fileop; + productName = fileop; + productReference = 722954B41D04ADAF00ECF9CA /* fileop */; + productType = "com.apple.product-type.tool"; + }; + 726B2B5C1C645FC900388755 /* UI Tests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 726B2B671C645FC900388755 /* Build configuration list for PBXNativeTarget "UI Tests" */; + buildPhases = ( + 726B2B591C645FC900388755 /* Sources */, + 726B2B5A1C645FC900388755 /* Frameworks */, + 726B2B5B1C645FC900388755 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 726B2B631C645FC900388755 /* PBXTargetDependency */, + ); + name = "UI Tests"; + productName = "UI Tests"; + productReference = 726B2B5D1C645FC900388755 /* UI Tests.xctest */; + productType = "com.apple.product-type.bundle.ui-testing"; + }; 8DC2EF4F0486A6940098B216 /* Sparkle */ = { isa = PBXNativeTarget; buildConfigurationList = 1DEB91AD08733DA50010E9CD /* Build configuration list for PBXNativeTarget "Sparkle" */; @@ -1311,8 +1478,17 @@ ORGANIZATIONNAME = "Sparkle Project"; TargetAttributes = { 612279D80DB5470200AB99EA = { + LastSwiftMigration = 0800; TestTargetID = 8DC2EF4F0486A6940098B216; }; + 722954B31D04ADAF00ECF9CA = { + CreatedOnToolsVersion = 7.3.1; + }; + 726B2B5C1C645FC900388755 = { + CreatedOnToolsVersion = 7.2.1; + LastSwiftMigration = 0800; + TestTargetID = 61B5F90109C4CEE200B25A18; + }; }; }; buildConfigurationList = 1DEB91B108733DA50010E9CD /* Build configuration list for PBXProject "Sparkle" */; @@ -1380,6 +1556,8 @@ 14732BC51960F69300593899 /* Distribution */, 1420DF491962329200203BB0 /* Documentation */, 1495005F195FB89400BC5B5B /* All */, + 726B2B5C1C645FC900388755 /* UI Tests */, + 722954B31D04ADAF00ECF9CA /* fileop */, ); }; /* End PBXProject section */ @@ -1389,7 +1567,9 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( + 72E641801D08D754000404CA /* fileop in Resources */, 14958C6E19AEBC950061B14F /* signed-test-file.txt in Resources */, + 5F1510A21C96E591006E1629 /* testnamespaces.xml in Resources */, 72AC6B2E1B9B218C00F62325 /* SparkleTestCodeSignApp.dmg in Resources */, C23E885B1BE7B24F0050BB73 /* SparkleTestCodeSignApp.enc.dmg in Resources */, 72AC6B281B9AAD6700F62325 /* SparkleTestCodeSignApp.tar in Resources */, @@ -1399,6 +1579,7 @@ F8761EB31ADC50EB000C9034 /* SparkleTestCodeSignApp.zip in Resources */, 14958C6F19AEBC980061B14F /* test-pubkey.pem in Resources */, 5AF6C74F1AEA46D10014A3AB /* test.sparkle_guided.pkg in Resources */, + 5AD0FA7F1C73F2E2004BCEFF /* testappcast.xml in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -1406,7 +1587,7 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( - 1420DF51196247F900203BB0 /* Images.xcassets in Resources */, + 5AE7E1111DC81AD3009C2C12 /* AppIcon.icns in Resources */, 55C14FC7136F05E100649790 /* Sparkle.strings in Resources */, 55C14BD9136EF00C00649790 /* SUStatus.xib in Resources */, ); @@ -1427,6 +1608,13 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + 726B2B5B1C645FC900388755 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; 8DC2EF520486A6940098B216 /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; @@ -1525,6 +1713,7 @@ 726F2CE71BC9C3E2001971A4 /* SUOperatingSystem.m in Sources */, 55C14F24136EF86F00649790 /* SUPackageInstaller.m in Sources */, 55C14F21136EF84D00649790 /* SUPlainInstaller.m in Sources */, + 722954C61D04E66F00ECF9CA /* SUFileOperationConstants.m in Sources */, 55C14F22136EF86000649790 /* SUStandardVersionComparator.m in Sources */, 55C14F20136EF84300649790 /* SUStatusController.m in Sources */, 55C14F23136EF86700649790 /* SUSystemProfiler.m in Sources */, @@ -1536,9 +1725,11 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 72544FFC1D0991A4000CFB2C /* SUFileOperationConstants.m in Sources */, 5D06E8E90FD68CDB005AE3F6 /* bsdiff.c in Sources */, 14652F7E19A9728A00959E44 /* bspatch.c in Sources */, 7223E7631AD1AEFF008E3161 /* sais.c in Sources */, + 723B252F1CEAB3A600909873 /* bscommon.c in Sources */, 14652F7D19A9726700959E44 /* SUBinaryDeltaApply.m in Sources */, 14652F7C19A9725300959E44 /* SUBinaryDeltaCommon.m in Sources */, 7268AC631AD634C200C3E0C1 /* SUBinaryDeltaCreate.m in Sources */, @@ -1553,10 +1744,13 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 723A920E1D722438004A9DED /* SUSpotlightImporterTest.swift in Sources */, 721CF1A71AD7643600D9AC09 /* bsdiff.c in Sources */, 721CF1A81AD7644100D9AC09 /* bspatch.c in Sources */, 721CF1A91AD7644C00D9AC09 /* sais.c in Sources */, + 5A4094481C74EA5200983BE0 /* SUAppcastTest.swift in Sources */, 72D4DAA11AD7632900B211E2 /* SUBinaryDeltaCreate.m in Sources */, + 723B252E1CEAB3A600909873 /* bscommon.c in Sources */, 142E0E0919A83AAC00E4312B /* SUBinaryDeltaTest.m in Sources */, F8761EB11ADC5068000C9034 /* SUCodeSigningVerifierTest.m in Sources */, 5AF9DC3C1981DBEE001EA135 /* SUDSAVerifierTest.m in Sources */, @@ -1576,6 +1770,7 @@ 61B5F93009C4CFDC00B25A18 /* main.m in Sources */, 726F2CEB1BC9C733001971A4 /* SUConstants.m in Sources */, 5A6D31EE1BF53245009C5157 /* SUFileManager.m in Sources */, + 721BC2111D1DFF05002BC71E /* SUFileOperationConstants.m in Sources */, 5A6D31EF1BF5325F009C5157 /* SUOperatingSystem.m in Sources */, 72E45CF31B640CDD005C701A /* SUTestApplicationDelegate.m in Sources */, A5BF4F1D1BC7668B007A052A /* SUTestWebServer.m in Sources */, @@ -1583,12 +1778,32 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + 722954B01D04ADAF00ECF9CA /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 722954CC1D04EA7000ECF9CA /* SUOperatingSystem.m in Sources */, + 722954BD1D04AE3800ECF9CA /* SUConstants.m in Sources */, + 722954BC1D04AE1100ECF9CA /* SUFileManager.m in Sources */, + 722954B71D04ADAF00ECF9CA /* fileop.m in Sources */, + 722954C71D04E66F00ECF9CA /* SUFileOperationConstants.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 726B2B591C645FC900388755 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 720B16451C66433D006985FB /* SUTestApplicationTest.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; 8DC2EF540486A6940098B216 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 5D06E8EB0FD68CE4005AE3F6 /* bspatch.c in Sources */, - 610EC1E00CF3A5FE00AE239E /* NTSynchronousTask.m in Sources */, + 722954C51D04E66F00ECF9CA /* SUFileOperationConstants.m in Sources */, 61B5FBB709C4FAFF00B25A18 /* SUAppcast.m in Sources */, 61B5FC6F09C51F4900B25A18 /* SUAppcastItem.m in Sources */, 6120721309CC5C4B007FE0F6 /* SUAutomaticUpdateAlert.m in Sources */, @@ -1606,6 +1821,8 @@ 61EF67560E25B58D00F754E0 /* SUHost.m in Sources */, 618FA5020DAE88B40026945C /* SUInstaller.m in Sources */, 55C14F07136EF6DB00649790 /* SULog.m in Sources */, + 729924741DF3478A00DBCDF5 /* SUUpdateValidator.m in Sources */, + 723B252D1CEAB3A600909873 /* bscommon.c in Sources */, 726F2CE61BC9C33D001971A4 /* SUOperatingSystem.m in Sources */, 618FA5230DAE8E8A0026945C /* SUPackageInstaller.m in Sources */, 61D85D6D0E10B2ED00F9B4A9 /* SUPipedUnarchiver.m in Sources */, @@ -1694,6 +1911,16 @@ target = 8DC2EF4F0486A6940098B216 /* Sparkle */; targetProxy = 61FA528C0E2D9EB200EF58AD /* PBXContainerItemProxy */; }; + 722954BF1D04D9CB00ECF9CA /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 722954B31D04ADAF00ECF9CA /* fileop */; + targetProxy = 722954BE1D04D9CB00ECF9CA /* PBXContainerItemProxy */; + }; + 726B2B631C645FC900388755 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 61B5F90109C4CEE200B25A18 /* Sparkle Test App */; + targetProxy = 726B2B621C645FC900388755 /* PBXContainerItemProxy */; + }; /* End PBXTargetDependency section */ /* Begin PBXVariantGroup section */ @@ -2069,6 +2296,54 @@ }; name = Release; }; + 722954B81D04ADAF00ECF9CA /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 722954C81D04E89500ECF9CA /* ConfigFileop.xcconfig */; + buildSettings = { + GCC_WARN_UNUSED_VARIABLE = YES; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Debug; + }; + 722954B91D04ADAF00ECF9CA /* Coverage */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 722954C81D04E89500ECF9CA /* ConfigFileop.xcconfig */; + buildSettings = { + GCC_WARN_UNUSED_VARIABLE = YES; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Coverage; + }; + 722954BA1D04ADAF00ECF9CA /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 722954C81D04E89500ECF9CA /* ConfigFileop.xcconfig */; + buildSettings = { + GCC_WARN_UNUSED_VARIABLE = YES; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Release; + }; + 726B2B641C645FC900388755 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 729F10FF1C65A9B500DFCCC5 /* ConfigUITestDebug.xcconfig */; + buildSettings = { + }; + name = Debug; + }; + 726B2B651C645FC900388755 /* Coverage */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 729F10FE1C65A9B500DFCCC5 /* ConfigUITestCoverage.xcconfig */; + buildSettings = { + }; + name = Coverage; + }; + 726B2B661C645FC900388755 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 729F11001C65A9B500DFCCC5 /* ConfigUITestRelease.xcconfig */; + buildSettings = { + }; + name = Release; + }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ @@ -2162,6 +2437,26 @@ defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; + 722954BB1D04ADAF00ECF9CA /* Build configuration list for PBXNativeTarget "fileop" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 722954B81D04ADAF00ECF9CA /* Debug */, + 722954B91D04ADAF00ECF9CA /* Coverage */, + 722954BA1D04ADAF00ECF9CA /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 726B2B671C645FC900388755 /* Build configuration list for PBXNativeTarget "UI Tests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 726B2B641C645FC900388755 /* Debug */, + 726B2B651C645FC900388755 /* Coverage */, + 726B2B661C645FC900388755 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; /* End XCConfigurationList section */ }; rootObject = 0867D690FE84028FC02AAC07 /* Project object */; diff --git a/Sparkle.xcodeproj/xcshareddata/xcschemes/UITests.xcscheme b/Sparkle.xcodeproj/xcshareddata/xcschemes/UITests.xcscheme new file mode 100644 index 00000000..26db70de --- /dev/null +++ b/Sparkle.xcodeproj/xcshareddata/xcschemes/UITests.xcscheme @@ -0,0 +1,56 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Sparkle/Autoupdate/Autoupdate-Info.plist b/Sparkle/Autoupdate/Autoupdate-Info.plist index f5a076f7..579d8ed9 100644 --- a/Sparkle/Autoupdate/Autoupdate-Info.plist +++ b/Sparkle/Autoupdate/Autoupdate-Info.plist @@ -28,5 +28,7 @@ MainMenu NSPrincipalClass NSApplication + CFBundleIconFile + ${ASSETCATALOG_COMPILER_APPICON_NAME}.icns diff --git a/Sparkle/Autoupdate/Autoupdate.m b/Sparkle/Autoupdate/Autoupdate.m index ddc60f6c..a021172b 100644 --- a/Sparkle/Autoupdate/Autoupdate.m +++ b/Sparkle/Autoupdate/Autoupdate.m @@ -166,18 +166,28 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.5; [self.statusController showWindow:self]; } + NSString *fileOperationToolPath = [[[[NSBundle mainBundle] executablePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@""SPARKLE_FILEOP_TOOL_NAME]; + + if (![[NSFileManager defaultManager] fileExistsAtPath:fileOperationToolPath]) { + SULog(@"Potential Installation Error: File operation tool path %@ is not found", fileOperationToolPath); + } + [SUInstaller installFromUpdateFolder:self.updateFolderPath overHost:host installationPath:installationPath + fileOperationToolPath:fileOperationToolPath versionComparator:[SUStandardVersionComparator defaultComparator] completionHandler:^(NSError *error) { if (error) { - SULog(@"Installation Error: %@", error); - if (self.shouldShowUI) { - NSAlert *alert = [[NSAlert alloc] init]; - alert.messageText = @""; - alert.informativeText = [NSString stringWithFormat:@"%@", [error localizedDescription]]; - [alert runModal]; + NSError *underlyingError = [error.userInfo objectForKey:NSUnderlyingErrorKey]; + if (underlyingError == nil || underlyingError.code != SUInstallationCancelledError) { + SULog(@"Installation Error: %@", error); + if (self.shouldShowUI) { + NSAlert *alert = [[NSAlert alloc] init]; + alert.messageText = @""; + alert.informativeText = [NSString stringWithFormat:@"%@", [error localizedDescription]]; + [alert runModal]; + } } exit(EXIT_FAILURE); } else { @@ -247,16 +257,16 @@ int main(int __unused argc, const char __unused *argv[]) NSApplication *application = [NSApplication sharedApplication]; - BOOL shouldShowUI = (args.count > 6) ? [args[6] boolValue] : YES; + BOOL shouldShowUI = (args.count > 6) ? [[args objectAtIndex:6] boolValue] : YES; if (shouldShowUI) { [application activateIgnoringOtherApps:YES]; } - AppInstaller *appInstaller = [[AppInstaller alloc] initWithHostPath:args[1] - relaunchPath:args[2] - parentProcessId:[args[3] intValue] - updateFolderPath:args[4] - shouldRelaunch:(args.count > 5) ? [args[5] boolValue] : YES + AppInstaller *appInstaller = [[AppInstaller alloc] initWithHostPath:[args objectAtIndex:1] + relaunchPath:[args objectAtIndex:2] + parentProcessId:[[args objectAtIndex:3] intValue] + updateFolderPath:[args objectAtIndex:4] + shouldRelaunch:(args.count > 5) ? [[args objectAtIndex:5] boolValue] : YES shouldShowUI:shouldShowUI]; [application setDelegate:appInstaller]; [application run]; diff --git a/Sparkle/CheckLocalizations.swift b/Sparkle/CheckLocalizations.swift index f0c05797..431e8348 100755 --- a/Sparkle/CheckLocalizations.swift +++ b/Sparkle/CheckLocalizations.swift @@ -3,7 +3,7 @@ import Foundation func die(msg: String) { - println("ERROR: \(msg)") + print("ERROR: \(msg)") exit(1) } @@ -28,8 +28,8 @@ if enStringsDict == nil { } let enStringsDictKeys = enStringsDict!.allKeys -let dirPath = sparkleRoot! + "/Sparkle" -let dirContents = NSFileManager.defaultManager().contentsOfDirectoryAtPath(dirPath, error: nil) as! [String] +let dirPath = NSString(string: sparkleRoot! + "/Sparkle") +let dirContents = try! NSFileManager.defaultManager().contentsOfDirectoryAtPath(dirPath as String) let css = "body { font-family: sans-serif; font-size: 10pt; }" + "h1 { font-size: 12pt; }" + @@ -51,14 +51,14 @@ head.addChild(NSXMLElement(name: "style", stringValue: css)) let locale = NSLocale.currentLocale() for dirEntry in dirContents { - if dirEntry.pathExtension != "lproj" || dirEntry == "en.lproj" { + if NSString(string: dirEntry).pathExtension != "lproj" || dirEntry == "en.lproj" { continue } - let lang = locale.displayNameForKey(NSLocaleLanguageCode, value: dirEntry.stringByDeletingPathExtension) + let lang = locale.displayNameForKey(NSLocaleLanguageCode, value: NSString(string: dirEntry).stringByDeletingPathExtension) body.addChild(NSXMLElement(name: "h1", stringValue: "\(dirEntry) (\(lang!))")) - let stringsPath = dirPath.stringByAppendingPathComponent(dirEntry).stringByAppendingPathComponent("Sparkle.strings") + let stringsPath = NSString(string: dirPath.stringByAppendingPathComponent(dirEntry)).stringByAppendingPathComponent("Sparkle.strings") let stringsDict = NSDictionary(contentsOfFile: stringsPath) if stringsDict == nil { die("Invalid strings file \(dirEntry)") @@ -90,12 +90,12 @@ for dirEntry in dirContents { let sorter = { (s1: String, s2: String) -> Bool in return s1 < s2 } - missing.sort(sorter) - unlocalized.sort(sorter) - unused.sort(sorter) + missing.sortInPlace(sorter) + unlocalized.sortInPlace(sorter) + unused.sortInPlace(sorter) let addRow = { (prefix: String, cssClass: String, key: String) -> Void in - body.addChild(NSXMLElement(name: "span", attributes: ["class": cssClass], stringValue: " ".join([prefix, key]) + "\n")) + body.addChild(NSXMLElement(name: "span", attributes: ["class": cssClass], stringValue: [prefix, key].joinWithSeparator(" ") + "\n")) } for key in missing { diff --git a/Sparkle/SUAppcast.h b/Sparkle/SUAppcast.h index a035f18f..fee97567 100644 --- a/Sparkle/SUAppcast.h +++ b/Sparkle/SUAppcast.h @@ -9,7 +9,11 @@ #ifndef SUAPPCAST_H #define SUAPPCAST_H +#if __has_feature(modules) +@import Foundation; +#else #import +#endif #import "SUExport.h" @class SUAppcastItem; diff --git a/Sparkle/SUAppcast.m b/Sparkle/SUAppcast.m index 7690028c..d4f32fd9 100644 --- a/Sparkle/SUAppcast.m +++ b/Sparkle/SUAppcast.m @@ -30,7 +30,10 @@ if (!attrName) { continue; } - dictionary[attrName] = [attribute stringValue]; + NSString *attributeStringValue = [attribute stringValue]; + if (attributeStringValue != nil) { + [dictionary setObject:attributeStringValue forKey:attrName]; + } } return dictionary; } @@ -93,151 +96,166 @@ - (void)downloadDidFinish:(NSURLDownload *)__unused aDownload { NSError *error = nil; + NSArray *appcastItems = [self parseAppcastItemsFromXMLFile:[NSURL fileURLWithPath:self.downloadFilename] error:&error]; - NSXMLDocument *document = nil; - BOOL failed = NO; - NSArray *xmlItems = nil; - NSMutableArray *appcastItems = [NSMutableArray array]; + [[NSFileManager defaultManager] removeItemAtPath:self.downloadFilename error:nil]; + self.downloadFilename = nil; - if (self.downloadFilename) - { - NSUInteger options = 0; - options = NSXMLNodeLoadExternalEntitiesNever; // Prevent inclusion from file:// - document = [[NSXMLDocument alloc] initWithContentsOfURL:[NSURL fileURLWithPath:self.downloadFilename] options:options error:&error]; - - [[NSFileManager defaultManager] removeItemAtPath:self.downloadFilename error:nil]; - self.downloadFilename = nil; - } - else - { - failed = YES; + if (appcastItems) { + self.items = appcastItems; + self.completionBlock(nil); + self.completionBlock = nil; + } else { + NSMutableDictionary *userInfo = [NSMutableDictionary + dictionaryWithObject: SULocalizedString(@"An error occurred while parsing the update feed.", nil) + forKey: NSLocalizedDescriptionKey]; + if (error) { + [userInfo setObject:error forKey:NSUnderlyingErrorKey]; + } + [self reportError:[NSError errorWithDomain:SUSparkleErrorDomain + code:SUAppcastParseError + userInfo:userInfo]]; } +} - if (nil == document) - { - failed = YES; - } - else - { - xmlItems = [document nodesForXPath:@"/rss/channel/item" error:&error]; - if (nil == xmlItems) - { - failed = YES; +- (NSDictionary *)attributesOfNode:(NSXMLElement *)node +{ + NSEnumerator *attributeEnum = [[node attributes] objectEnumerator]; + NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; + + for (NSXMLNode *attribute in attributeEnum) { + NSString *attrName = [self sparkleNamespacedNameOfNode:attribute]; + if (!attrName) { + continue; + } + NSString *stringValue = [attribute stringValue]; + if (stringValue) { + [dictionary setObject:stringValue forKey:attrName]; } } + return dictionary; +} - if (failed == NO) - { +-(NSString *)sparkleNamespacedNameOfNode:(NSXMLNode *)node { + // XML namespace prefix is semantically meaningless, so compare namespace URI + // NS URI isn't used to fetch anything, and must match exactly, so we look for http:// not https:// + if ([[node URI] isEqualToString:@"http://www.andymatuschak.org/xml-namespaces/sparkle"]) { + NSString *localName = [node localName]; + assert(localName); + return [@"sparkle:" stringByAppendingString:localName]; + } else { + return [node name]; // Backwards compatibility + } +} - NSEnumerator *nodeEnum = [xmlItems objectEnumerator]; - NSXMLNode *node; +-(NSArray *)parseAppcastItemsFromXMLFile:(NSURL *)appcastFile error:(NSError *__autoreleasing*)errorp { + if (errorp) { + *errorp = nil; + } + + if (!appcastFile) { + return nil; + } + + NSUInteger options = NSXMLNodeLoadExternalEntitiesNever; // Prevent inclusion from file:// + NSXMLDocument *document = [[NSXMLDocument alloc] initWithContentsOfURL:appcastFile options:options error:errorp]; + if (nil == document) { + return nil; + } + + NSArray *xmlItems = [document nodesForXPath:@"/rss/channel/item" error:errorp]; + if (nil == xmlItems) { + return nil; + } + + NSMutableArray *appcastItems = [NSMutableArray array]; + NSEnumerator *nodeEnum = [xmlItems objectEnumerator]; + NSXMLNode *node; + + while((node = [nodeEnum nextObject])) { NSMutableDictionary *nodesDict = [NSMutableDictionary dictionary]; NSMutableDictionary *dict = [NSMutableDictionary dictionary]; - while (failed == NO && (node = [nodeEnum nextObject])) - { - // First, we'll "index" all the first-level children of this appcast item so we can pick them out by language later. - if ([[node children] count]) - { - node = [node childAtIndex:0]; - while (nil != node) - { - NSString *name = [node name]; - if (name) - { - NSMutableArray *nodes = nodesDict[name]; - if (nodes == nil) - { - nodes = [NSMutableArray array]; - nodesDict[name] = nodes; - } - [nodes addObject:node]; + // First, we'll "index" all the first-level children of this appcast item so we can pick them out by language later. + if ([[node children] count]) { + node = [node childAtIndex:0]; + while (nil != node) { + NSString *name = [self sparkleNamespacedNameOfNode:node]; + if (name) { + NSMutableArray *nodes = [nodesDict objectForKey:name]; + if (nodes == nil) { + nodes = [NSMutableArray array]; + [nodesDict setObject:nodes forKey:name]; } - node = [node nextSibling]; + [nodes addObject:node]; } + node = [node nextSibling]; } + } - for (NSString *name in nodesDict) - { - node = [self bestNodeInNodes:nodesDict[name]]; - if ([name isEqualToString:SURSSElementEnclosure]) - { - // enclosure is flattened as a separate dictionary for some reason - NSDictionary *encDict = [(NSXMLElement *)node attributesAsDictionary]; - dict[name] = encDict; - - } - else if ([name isEqualToString:SURSSElementPubDate]) - { - // pubDate is expected to be an NSDate by SUAppcastItem, but the RSS class was returning an NSString - NSString *string = node.stringValue; - if (string) { - NSDate *date = [NSDate dateWithNaturalLanguageString:string]; - if (date) - dict[name] = date; - } - } - else if ([name isEqualToString:SUAppcastElementDeltas]) - { - NSMutableArray *deltas = [NSMutableArray array]; - NSEnumerator *childEnum = [[node children] objectEnumerator]; - for (NSXMLNode *child in childEnum) { - if ([[child name] isEqualToString:SURSSElementEnclosure]) - [deltas addObject:[(NSXMLElement *)child attributesAsDictionary]]; - } - dict[name] = deltas; - } - else if ([name isEqualToString:SUAppcastElementTags]) { - NSMutableArray *tags = [NSMutableArray array]; - NSEnumerator *childEnum = [[node children] objectEnumerator]; - for (NSXMLNode *child in childEnum) { - NSString *childName = child.name; - if (childName) - [tags addObject:childName]; - } - dict[name] = tags; - } - else if (name != nil) - { - // add all other values as strings - NSString *theValue = [[node stringValue] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; - if (theValue != nil) { - dict[name] = theValue; - } - } - } - - NSString *errString; - SUAppcastItem *anItem = [[SUAppcastItem alloc] initWithDictionary:dict failureReason:&errString]; - if (anItem) - { - [appcastItems addObject:anItem]; + for (NSString *name in nodesDict) { + node = [self bestNodeInNodes:[nodesDict objectForKey:name]]; + if ([name isEqualToString:SURSSElementEnclosure]) { + // enclosure is flattened as a separate dictionary for some reason + NSDictionary *encDict = [self attributesOfNode:(NSXMLElement *)node]; + [dict setObject:encDict forKey:name]; } - else - { - SULog(@"Sparkle Updater: Failed to parse appcast item: %@.\nAppcast dictionary was: %@", errString, dict); + else if ([name isEqualToString:SURSSElementPubDate]) { + // We don't want to parse and create a NSDate instance - + // that's a risk we can avoid. We don't use the date anywhere other + // than it being accessible from SUAppcastItem + NSString *dateString = node.stringValue; + if (dateString) { + [dict setObject:dateString forKey:name]; + } + } + else if ([name isEqualToString:SUAppcastElementDeltas]) { + NSMutableArray *deltas = [NSMutableArray array]; + NSEnumerator *childEnum = [[node children] objectEnumerator]; + for (NSXMLNode *child in childEnum) { + if ([[child name] isEqualToString:SURSSElementEnclosure]) { + [deltas addObject:[self attributesOfNode:(NSXMLElement *)child]]; + } + } + [dict setObject:deltas forKey:name]; + } + else if ([name isEqualToString:SUAppcastElementTags]) { + NSMutableArray *tags = [NSMutableArray array]; + NSEnumerator *childEnum = [[node children] objectEnumerator]; + for (NSXMLNode *child in childEnum) { + NSString *childName = child.name; + if (childName) { + [tags addObject:childName]; + } + } + [dict setObject:tags forKey:name]; } - [nodesDict removeAllObjects]; - [dict removeAllObjects]; + else if (name != nil) { + // add all other values as strings + NSString *theValue = [[node stringValue] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; + if (theValue != nil) { + [dict setObject:theValue forKey:name]; + } + } + } + + NSString *errString; + SUAppcastItem *anItem = [[SUAppcastItem alloc] initWithDictionary:dict failureReason:&errString]; + if (anItem) { + [appcastItems addObject:anItem]; + } + else { + SULog(@"Sparkle Updater: Failed to parse appcast item: %@.\nAppcast dictionary was: %@", errString, dict); + if (errorp) *errorp = [NSError errorWithDomain:SUSparkleErrorDomain + code:SUAppcastParseError + userInfo:@{NSLocalizedDescriptionKey: errString}]; + return nil; } } + + self.items = appcastItems; - if ([appcastItems count]) { - NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:NO]; - [appcastItems sortUsingDescriptors:@[sort]]; - self.items = appcastItems; - } - - if (failed) { - [self reportError:[NSError errorWithDomain:SUSparkleErrorDomain - code:SUAppcastParseError - userInfo:@{ - NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while parsing the update feed.", nil), - NSUnderlyingErrorKey: error ? error : [NSNull null]}]]; - } else { - self.completionBlock(nil); - self.completionBlock = nil; - } + return appcastItems; } - (void)download:(NSURLDownload *)__unused aDownload didFailWithError:(NSError *)error @@ -257,14 +275,18 @@ - (void)reportError:(NSError *)error { - NSURL *failingUrl = error.userInfo[NSURLErrorFailingURLErrorKey]; - - self.completionBlock([NSError errorWithDomain:SUSparkleErrorDomain code:SUAppcastError userInfo:@{ + NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:@{ NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred in retrieving update information. Please try again later.", nil), NSLocalizedFailureReasonErrorKey: [error localizedDescription], NSUnderlyingErrorKey: error, - NSURLErrorFailingURLErrorKey: failingUrl ? failingUrl : [NSNull null], - }]); + }]; + + NSURL *failingUrl = [error.userInfo objectForKey:NSURLErrorFailingURLErrorKey]; + if (failingUrl) { + [userInfo setObject:failingUrl forKey:NSURLErrorFailingURLErrorKey]; + } + + self.completionBlock([NSError errorWithDomain:SUSparkleErrorDomain code:SUAppcastError userInfo:userInfo]); self.completionBlock = nil; } @@ -272,7 +294,7 @@ { // We use this method to pick out the localized version of a node when one's available. if ([nodes count] == 1) - return nodes[0]; + return [nodes objectAtIndex:0]; else if ([nodes count] == 0) return nil; @@ -283,12 +305,12 @@ lang = [[node attributeForName:@"xml:lang"] stringValue]; [languages addObject:(lang ? lang : @"")]; } - lang = [NSBundle preferredLocalizationsFromArray:languages][0]; + lang = [[NSBundle preferredLocalizationsFromArray:languages] objectAtIndex:0]; i = [languages indexOfObject:([languages containsObject:lang] ? lang : @"")]; if (i == NSNotFound) { i = 0; } - return nodes[i]; + return [nodes objectAtIndex:i]; } - (SUAppcast *)copyWithoutDeltaUpdates { diff --git a/Sparkle/SUAppcastItem.h b/Sparkle/SUAppcastItem.h index 86843bfb..51b9393f 100644 --- a/Sparkle/SUAppcastItem.h +++ b/Sparkle/SUAppcastItem.h @@ -9,12 +9,16 @@ #ifndef SUAPPCASTITEM_H #define SUAPPCASTITEM_H +#if __has_feature(modules) +@import Foundation; +#else #import +#endif #import "SUExport.h" SU_EXPORT @interface SUAppcastItem : NSObject @property (copy, readonly) NSString *title; -@property (copy, readonly) NSDate *date; +@property (copy, readonly) NSString *dateString; @property (copy, readonly) NSString *itemDescription; @property (strong, readonly) NSURL *releaseNotesURL; @property (copy, readonly) NSString *DSASignature; diff --git a/Sparkle/SUAppcastItem.m b/Sparkle/SUAppcastItem.m index a98d7afa..4cbc4e44 100644 --- a/Sparkle/SUAppcastItem.m +++ b/Sparkle/SUAppcastItem.m @@ -16,7 +16,7 @@ @interface SUAppcastItem () @property (copy, readwrite) NSString *title; -@property (copy, readwrite) NSDate *date; +@property (copy, readwrite) NSString *dateString; @property (copy, readwrite) NSString *itemDescription; @property (strong, readwrite) NSURL *releaseNotesURL; @property (copy, readwrite) NSString *DSASignature; @@ -31,7 +31,7 @@ @end @implementation SUAppcastItem -@synthesize date; +@synthesize dateString; @synthesize deltaUpdates; @synthesize displayVersionString; @synthesize DSASignature; @@ -47,12 +47,13 @@ - (BOOL)isDeltaUpdate { - return self.propertiesDictionary[SURSSElementEnclosure][SUAppcastAttributeDeltaFrom] != nil; + NSDictionary *rssElementEnclosure = [self.propertiesDictionary objectForKey:SURSSElementEnclosure]; + return [rssElementEnclosure objectForKey:SUAppcastAttributeDeltaFrom] != nil; } - (BOOL)isCriticalUpdate { - return [self.propertiesDictionary[SUAppcastElementTags] containsObject:SUAppcastElementCriticalUpdate]; + return [[self.propertiesDictionary objectForKey:SUAppcastElementTags] containsObject:SUAppcastElementCriticalUpdate]; } - (BOOL)isInformationOnlyUpdate @@ -69,7 +70,7 @@ { self = [super init]; if (self) { - id enclosure = dict[SURSSElementEnclosure]; + NSDictionary *enclosure = [dict objectForKey:SURSSElementEnclosure]; // Try to find a version string. // Finding the new version number from the RSS feed is a little bit hacky. There are two ways: @@ -79,17 +80,17 @@ // underscore and the last period as the version number. So name your packages like this: APPNAME_VERSION.extension. // The big caveat with this is that you can't have underscores in your version strings, as that'll confuse Sparkle. // Feel free to change the separator string to a hyphen or something more suited to your needs if you like. - NSString *newVersion = enclosure[SUAppcastAttributeVersion]; + NSString *newVersion = [enclosure objectForKey:SUAppcastAttributeVersion]; if (newVersion == nil) { - newVersion = dict[SUAppcastAttributeVersion]; // Get version from the item, in case it's a download-less item (i.e. paid upgrade). + newVersion = [dict objectForKey:SUAppcastAttributeVersion]; // Get version from the item, in case it's a download-less item (i.e. paid upgrade). } if (newVersion == nil) // no sparkle:version attribute anywhere? { - SULog(@"warning: <%@> for URL '%@' is missing %@ attribute. Version comparison may be unreliable. Please always specify %@", SURSSElementEnclosure, enclosure[SURSSAttributeURL], SUAppcastAttributeVersion, SUAppcastAttributeVersion); + SULog(@"warning: <%@> for URL '%@' is missing %@ attribute. Version comparison may be unreliable. Please always specify %@", SURSSElementEnclosure, [enclosure objectForKey:SURSSAttributeURL], SUAppcastAttributeVersion, SUAppcastAttributeVersion); // Separate the url by underscores and take the last component, as that'll be closest to the end, // then we remove the extension. Hopefully, this will be the version. - NSArray *fileComponents = [enclosure[SURSSAttributeURL] componentsSeparatedByString:@"_"]; + NSArray *fileComponents = [[enclosure objectForKey:SURSSAttributeURL] componentsSeparatedByString:@"_"]; if ([fileComponents count] > 1) { newVersion = [[fileComponents lastObject] stringByDeletingPathExtension]; } @@ -103,11 +104,11 @@ } propertiesDictionary = [[NSMutableDictionary alloc] initWithDictionary:dict]; - self.title = dict[SURSSElementTitle]; - self.date = dict[SURSSElementPubDate]; - self.itemDescription = dict[SURSSElementDescription]; + self.title = [dict objectForKey:SURSSElementTitle]; + self.dateString = [dict objectForKey:SURSSElementPubDate]; + self.itemDescription = [dict objectForKey:SURSSElementDescription]; - NSString *theInfoURL = dict[SURSSElementLink]; + NSString *theInfoURL = [dict objectForKey:SURSSElementLink]; if (theInfoURL) { if (![theInfoURL isKindOfClass:[NSString class]]) { SULog(@"%@ -%@ Info URL is not of valid type.", NSStringFromClass([self class]), NSStringFromSelector(_cmd)); @@ -125,7 +126,7 @@ return nil; } - NSString *enclosureURLString = enclosure[SURSSAttributeURL]; + NSString *enclosureURLString = [enclosure objectForKey:SURSSAttributeURL]; if (!enclosureURLString && !theInfoURL) { if (error) { *error = @"Feed item's enclosure lacks URL"; @@ -139,16 +140,16 @@ self.fileURL = [NSURL URLWithString:fileURLString]; } if (enclosure) { - self.DSASignature = enclosure[SUAppcastAttributeDSASignature]; + self.DSASignature = [enclosure objectForKey:SUAppcastAttributeDSASignature]; } self.versionString = newVersion; - self.minimumSystemVersion = dict[SUAppcastElementMinimumSystemVersion]; - self.maximumSystemVersion = dict[SUAppcastElementMaximumSystemVersion]; + self.minimumSystemVersion = [dict objectForKey:SUAppcastElementMinimumSystemVersion]; + self.maximumSystemVersion = [dict objectForKey:SUAppcastElementMaximumSystemVersion]; - NSString *shortVersionString = enclosure[SUAppcastAttributeShortVersionString]; + NSString *shortVersionString = [enclosure objectForKey:SUAppcastAttributeShortVersionString]; if (nil == shortVersionString) { - shortVersionString = dict[SUAppcastAttributeShortVersionString]; // fall back on the + shortVersionString = [dict objectForKey:SUAppcastAttributeShortVersionString]; // fall back on the } if (shortVersionString) { @@ -158,7 +159,7 @@ } // Find the appropriate release notes URL. - NSString *releaseNotesString = dict[SUAppcastElementReleaseNotesLink]; + NSString *releaseNotesString = [dict objectForKey:SUAppcastElementReleaseNotesLink]; if (releaseNotesString) { NSURL *url = [NSURL URLWithString:releaseNotesString]; if ([url isFileURL]) { @@ -172,19 +173,19 @@ self.releaseNotesURL = nil; } - NSArray *deltaDictionaries = dict[SUAppcastElementDeltas]; + NSArray *deltaDictionaries = [dict objectForKey:SUAppcastElementDeltas]; if (deltaDictionaries) { NSMutableDictionary *deltas = [NSMutableDictionary dictionary]; for (NSDictionary *deltaDictionary in deltaDictionaries) { - NSString *deltaFrom = deltaDictionary[SUAppcastAttributeDeltaFrom]; + NSString *deltaFrom = [deltaDictionary objectForKey:SUAppcastAttributeDeltaFrom]; if (!deltaFrom) continue; NSMutableDictionary *fakeAppCastDict = [dict mutableCopy]; [fakeAppCastDict removeObjectForKey:SUAppcastElementDeltas]; - fakeAppCastDict[SURSSElementEnclosure] = deltaDictionary; + [fakeAppCastDict setObject:deltaDictionary forKey:SURSSElementEnclosure]; SUAppcastItem *deltaItem = [[SUAppcastItem alloc] initWithDictionary:fakeAppCastDict]; - deltas[deltaFrom] = deltaItem; + [deltas setObject:deltaItem forKey:deltaFrom]; } self.deltaUpdates = deltas; } diff --git a/Sparkle/SUAutomaticUpdateDriver.m b/Sparkle/SUAutomaticUpdateDriver.m index 562f2d05..6727d0d9 100644 --- a/Sparkle/SUAutomaticUpdateDriver.m +++ b/Sparkle/SUAutomaticUpdateDriver.m @@ -26,6 +26,7 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2 @property (assign) BOOL postponingInstallation; @property (assign) BOOL showErrors; @property (assign) BOOL willUpdateOnTermination; +@property (assign) BOOL isTerminating; @property (strong) SUAutomaticUpdateAlert *alert; @property (strong) NSTimer *showUpdateAlertTimer; @@ -36,6 +37,7 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2 @synthesize postponingInstallation; @synthesize showErrors; @synthesize willUpdateOnTermination; +@synthesize isTerminating; @synthesize alert; @synthesize showUpdateAlertTimer; @@ -131,6 +133,7 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2 - (void)abortUpdate { + self.isTerminating = NO; [self stopUpdatingOnTermination]; [self invalidateShowUpdateAlertTimer]; [super abortUpdate]; @@ -153,8 +156,6 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2 case SUInstallLaterChoice: self.postponingInstallation = YES; - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:) name:NSApplicationWillTerminateNotification object:nil]; - [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(systemWillPowerOff:) name:NSWorkspaceWillPowerOffNotification object:nil]; // We're already waiting on quit, just indicate that we're idle. self.interruptible = YES; break; @@ -166,6 +167,7 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2 } } + - (void)installWithToolAndRelaunch:(BOOL)relaunch displayingUserInterface:(BOOL)showUI { if (relaunch) { @@ -185,9 +187,22 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2 - (void)applicationWillTerminate:(NSNotification *)__unused note { + // We don't want to terminate the app if the user or someone else initiated a termination + // Use a property instead of passing an argument to installWithToolAndRelaunch: + // because we give the delegate an invocation to our install methods and + // this code was added later :| + self.isTerminating = YES; + [self installWithToolAndRelaunch:NO]; } +- (void)terminateApp +{ + if (!self.isTerminating) { + [super terminateApp]; + } +} + - (void)abortUpdateWithError:(NSError *)error { if (self.showErrors) { diff --git a/Sparkle/SUBasicUpdateDriver.h b/Sparkle/SUBasicUpdateDriver.h index 8c6960d8..301b4bc5 100644 --- a/Sparkle/SUBasicUpdateDriver.h +++ b/Sparkle/SUBasicUpdateDriver.h @@ -24,7 +24,7 @@ - (void)checkForUpdatesAtURL:(NSURL *)URL host:(SUHost *)host; - (BOOL)isItemNewer:(SUAppcastItem *)ui; -- (BOOL)hostSupportsItem:(SUAppcastItem *)ui; ++ (BOOL)hostSupportsItem:(SUAppcastItem *)ui; - (BOOL)itemContainsSkippedVersion:(SUAppcastItem *)ui; - (BOOL)itemContainsValidUpdate:(SUAppcastItem *)ui; - (void)appcastDidFinishLoading:(SUAppcast *)ac; diff --git a/Sparkle/SUBasicUpdateDriver.m b/Sparkle/SUBasicUpdateDriver.m index f295259c..1c18bf81 100644 --- a/Sparkle/SUBasicUpdateDriver.m +++ b/Sparkle/SUBasicUpdateDriver.m @@ -10,16 +10,14 @@ #import "SUHost.h" #import "SUOperatingSystem.h" -#import "SUDSAVerifier.h" -#import "SUInstaller.h" #import "SUStandardVersionComparator.h" #import "SUUnarchiver.h" #import "SUConstants.h" #import "SULog.h" #import "SUBinaryDeltaCommon.h" -#import "SUCodeSigningVerifier.h" #import "SUUpdater_Private.h" #import "SUFileManager.h" +#import "SUUpdateValidator.h" @interface SUBasicUpdateDriver () @@ -31,6 +29,8 @@ @property (copy) NSString *tempDir; @property (copy) NSString *relaunchPath; +@property (nonatomic) SUUpdateValidator *updateValidator; + @end @implementation SUBasicUpdateDriver @@ -43,6 +43,8 @@ @synthesize tempDir; @synthesize relaunchPath; +@synthesize updateValidator = _updateValidator; + - (void)checkForUpdatesAtURL:(NSURL *)URL host:(SUHost *)aHost { [super checkForUpdatesAtURL:URL host:aHost]; @@ -82,12 +84,28 @@ return comparator; } -- (BOOL)isItemNewer:(SUAppcastItem *)ui ++ (SUAppcastItem *)bestItemFromAppcastItems:(NSArray *)appcastItems getDeltaItem:(SUAppcastItem * __autoreleasing *)deltaItem withHostVersion:(NSString *)hostVersion comparator:(id)comparator { - return [[self versionComparator] compareVersion:[self.host version] toVersion:[ui versionString]] == NSOrderedAscending; + SUAppcastItem *item = nil; + for(SUAppcastItem *candidate in appcastItems) { + if ([[self class] hostSupportsItem:candidate]) { + if (!item || [comparator compareVersion:item.versionString toVersion:candidate.versionString] == NSOrderedAscending) { + item = candidate; + } + } + } + + if (item && deltaItem) { + SUAppcastItem *deltaUpdateItem = [[item deltaUpdates] objectForKey:hostVersion]; + if (deltaUpdateItem && [[self class] hostSupportsItem:deltaUpdateItem]) { + *deltaItem = deltaUpdateItem; + } + } + + return item; } -- (BOOL)hostSupportsItem:(SUAppcastItem *)ui ++ (BOOL)hostSupportsItem:(SUAppcastItem *)ui { if (([ui minimumSystemVersion] == nil || [[ui minimumSystemVersion] isEqualToString:@""]) && ([ui maximumSystemVersion] == nil || [[ui maximumSystemVersion] isEqualToString:@""])) { return YES; } @@ -106,6 +124,11 @@ return minimumVersionOK && maximumVersionOK; } +- (BOOL)isItemNewer:(SUAppcastItem *)ui +{ + return [[self versionComparator] compareVersion:[self.host version] toVersion:[ui versionString]] == NSOrderedAscending; +} + - (BOOL)itemContainsSkippedVersion:(SUAppcastItem *)ui { NSString *skippedVersion = [self.host objectForUserDefaultsKey:SUSkippedVersionKey]; @@ -115,7 +138,7 @@ - (BOOL)itemContainsValidUpdate:(SUAppcastItem *)ui { - return ui && [self hostSupportsItem:ui] && [self isItemNewer:ui] && ![self itemContainsSkippedVersion:ui]; + return ui && [[self class] hostSupportsItem:ui] && [self isItemNewer:ui] && ![self itemContainsSkippedVersion:ui]; } - (void)appcastDidFinishLoading:(SUAppcast *)ac @@ -139,20 +162,13 @@ } else // If not, we'll take care of it ourselves. { - // Find the first update we can actually use. - for(SUAppcastItem *i in ac.items) { - if ([self hostSupportsItem:i]) { - item = i; - break; - } - } - - if (item) { - SUAppcastItem *deltaUpdateItem = [item deltaUpdates][[self.host version]]; - if (deltaUpdateItem && [self hostSupportsItem:deltaUpdateItem]) { - self.nonDeltaUpdateItem = item; - item = deltaUpdateItem; - } + // Find the best supported update + SUAppcastItem *deltaUpdateItem = nil; + item = [[self class] bestItemFromAppcastItems:ac.items getDeltaItem:&deltaUpdateItem withHostVersion:self.host.version comparator:[self versionComparator]]; + + if (item && deltaUpdateItem) { + self.nonDeltaUpdateItem = item; + item = deltaUpdateItem; } } @@ -194,8 +210,36 @@ }]]; } +- (NSString *)appCachePath +{ + NSArray *cachePaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); + NSString *cachePath = nil; + if ([cachePaths count]) { + cachePath = [cachePaths objectAtIndex:0]; + } + if (!cachePath) { + SULog(@"Failed to find user's cache directory! Using system default"); + cachePath = NSTemporaryDirectory(); + } + + NSString *name = [self.host.bundle bundleIdentifier]; + if (!name) { + name = [self.host name]; + } + + cachePath = [cachePath stringByAppendingPathComponent:name]; + cachePath = [cachePath stringByAppendingPathComponent:@SPARKLE_BUNDLE_IDENTIFIER]; + return cachePath; +} + - (void)downloadUpdate { + // Clear cache directory so that downloads can't possibly accumulate inside + NSString *appCachePath = [self appCachePath]; + if ([[NSFileManager defaultManager] fileExistsAtPath:appCachePath]) { + [[NSFileManager defaultManager] removeItemAtPath:appCachePath error:NULL]; + } + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[self.updateItem fileURL]]; [request setValue:[self.updater userAgentString] forHTTPHeaderField:@"User-Agent"]; if ([[self.updater delegate] respondsToSelector:@selector(updater:willDownloadUpdate:withRequest:)]) { @@ -209,13 +253,14 @@ - (void)download:(NSURLDownload *)__unused d decideDestinationWithSuggestedFilename:(NSString *)name { NSString *downloadFileName = [NSString stringWithFormat:@"%@ %@", [self.host name], [self.updateItem versionString]]; - - - self.tempDir = [self.host.appCachePath stringByAppendingPathComponent:downloadFileName]; + + NSString *appCachePath = [self appCachePath]; + + self.tempDir = [appCachePath stringByAppendingPathComponent:downloadFileName]; int cnt = 1; while ([[NSFileManager defaultManager] fileExistsAtPath:self.tempDir] && cnt <= 999) { - self.tempDir = [self.host.appCachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@ %d", downloadFileName, cnt++]]; + self.tempDir = [appCachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@ %d", downloadFileName, cnt++]]; } // Create the temporary directory if necessary. @@ -231,87 +276,6 @@ [self.download setDestination:self.downloadPath allowOverwrite:YES]; } -/** - * If the update is a package, then it must be signed using DSA. No other verification is done. - * - * If the update is a bundle, then it must meet any one of: - * - * * old and new DSA public keys are the same and valid (it allows change of Code Signing identity), or - * - * * old and new Code Signing identity are the same and valid - * - */ -- (BOOL)validateUpdateDownloadedToPath:(NSString *)downloadedPath extractedToPath:(NSString *)extractedPath DSASignature:(NSString *)DSASignature publicDSAKey:(NSString *)publicDSAKey -{ - BOOL isPackage = NO; - NSString *installSourcePath = [SUInstaller installSourcePathInUpdateFolder:extractedPath forHost:self.host isPackage:&isPackage isGuided:NULL]; - if (installSourcePath == nil) { - SULog(@"No suitable install is found in the update. The update will be rejected."); - return NO; - } - - // Modern packages are not distributed as bundles and are code signed differently than regular applications - if (isPackage) { - if (nil == publicDSAKey) { - SULog(@"The existing app bundle does not have a DSA key, so it can't verify installer packages."); - } - - BOOL packageValidated = [SUDSAVerifier validatePath:downloadedPath withEncodedDSASignature:DSASignature withPublicDSAKey:publicDSAKey]; - - if (!packageValidated) { - SULog(@"DSA signature validation of the package failed. The update contains an installer package, and valid DSA signatures are mandatory for all installer packages. The update will be rejected. Sign the installer with a valid DSA key or use an .app bundle update instead."); - } - - return packageValidated; - } - - NSBundle *newBundle = [NSBundle bundleWithPath:installSourcePath]; - if (newBundle == nil) { - SULog(@"No suitable bundle is found in the update. The update will be rejected."); - return NO; - } - - SUHost *newHost = [[SUHost alloc] initWithBundle:newBundle]; - NSString *newPublicDSAKey = newHost.publicDSAKey; - - BOOL dsaKeysMatch = (publicDSAKey == nil || newPublicDSAKey == nil) ? NO : [publicDSAKey isEqualToString:newPublicDSAKey]; - - if (newPublicDSAKey != nil) { - if (![SUDSAVerifier validatePath:downloadedPath withEncodedDSASignature:DSASignature withPublicDSAKey:newPublicDSAKey]) { - SULog(@"DSA signature validation failed. The update has a public DSA key and is signed with a DSA key, but the %@ doesn't match the signature. The update will be rejected.", - dsaKeysMatch ? @"public key" : @"new public key shipped with the update"); - return NO; - } - } - - BOOL updateIsCodeSigned = [SUCodeSigningVerifier applicationAtPathIsCodeSigned:installSourcePath]; - - if (dsaKeysMatch) { - NSError *error = nil; - if (updateIsCodeSigned && ![SUCodeSigningVerifier codeSignatureIsValidAtPath:installSourcePath error:&error]) { - SULog(@"The update archive has a valid DSA signature, but the app is also signed with Code Signing, which is corrupted: %@. The update will be rejected.", error); - return NO; - } - } else { - BOOL hostIsCodeSigned = [SUCodeSigningVerifier hostApplicationIsCodeSigned]; - - NSString *dsaStatus = newPublicDSAKey ? @"has a new DSA key that doesn't match the previous one" : (publicDSAKey ? @"removes the DSA key" : @"isn't signed with a DSA key"); - if (!hostIsCodeSigned || !updateIsCodeSigned) { - NSString *acsStatus = !hostIsCodeSigned ? @"old app hasn't been signed with app Code Signing" : @"new app isn't signed with app Code Signing"; - SULog(@"The update archive %@, and the %@. At least one method of signature verification must be valid. The update will be rejected.", dsaStatus, acsStatus); - return NO; - } - - NSError *error = nil; - if (![SUCodeSigningVerifier codeSignatureMatchesHostAndIsValidAtPath:installSourcePath error:&error]) { - SULog(@"The update archive %@, and the app is signed with a new Code Signing identity that doesn't match code signing of the original app: %@. At least one method of signature verification must be valid. The update will be rejected.", dsaStatus, error); - return NO; - } - } - - return YES; -} - - (void)downloadDidFinish:(NSURLDownload *)__unused d { assert(self.updateItem); @@ -321,22 +285,26 @@ - (void)download:(NSURLDownload *)__unused download didFailWithError:(NSError *)error { - NSURL *failingUrl = error.userInfo[NSURLErrorFailingURLErrorKey]; + NSURL *failingUrl = [error.userInfo objectForKey:NSURLErrorFailingURLErrorKey]; if (!failingUrl) { failingUrl = [self.updateItem fileURL]; } - + if ([[self.updater delegate] respondsToSelector:@selector(updater:failedToDownloadUpdate:error:)]) { [[self.updater delegate] updater:self.updater failedToDownloadUpdate:self.updateItem error:error]; } - [self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SURelaunchError userInfo:@{ + NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:@{ NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while downloading the update. Please try again later.", nil), NSUnderlyingErrorKey: error, - NSURLErrorFailingURLErrorKey: failingUrl ? failingUrl : [NSNull null], - }]]; + }]; + if (failingUrl) { + [userInfo setObject:failingUrl forKey:NSURLErrorFailingURLErrorKey]; + } + + [self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUDownloadError userInfo:userInfo]]; } - (BOOL)download:(NSURLDownload *)__unused download shouldDecodeSourceDataOfMIMEType:(NSString *)encodingType @@ -348,14 +316,28 @@ - (void)extractUpdate { - SUUnarchiver *unarchiver = [SUUnarchiver unarchiverForPath:self.downloadPath updatingHostBundlePath:[[self.host bundle] bundlePath] withPassword:self.updater.decryptionPassword]; + SUUnarchiver *unarchiver = [SUUnarchiver unarchiverForPath:self.downloadPath updatingHostBundlePath:self.host.bundlePath withPassword:self.updater.decryptionPassword]; + + BOOL success; if (!unarchiver) { SULog(@"Error: No valid unarchiver for %@!", self.downloadPath); - [self unarchiverDidFail:nil]; - return; + + success = NO; + } else { + // Currently unsafe archives are the only case where we can prevalidate before extraction, but that could change in the future + BOOL needsPrevalidation = [[unarchiver class] unsafeIfArchiveIsNotValidated]; + + self.updateValidator = [[SUUpdateValidator alloc] initWithDownloadPath:self.downloadPath dsaSignature:self.updateItem.DSASignature host:self.host performingPrevalidation:needsPrevalidation]; + + success = self.updateValidator.canValidate; + } + + if (!success) { + [self unarchiverDidFail:nil]; + } else { + unarchiver.delegate = self; + [unarchiver start]; } - unarchiver.delegate = self; - [unarchiver start]; } - (void)failedToApplyDeltaUpdate @@ -376,6 +358,9 @@ - (void)unarchiverDidFail:(SUUnarchiver *)__unused ua { + // No longer needed + self.updateValidator = nil; + if ([self.updateItem isDeltaUpdate]) { [self failedToApplyDeltaUpdate]; return; @@ -422,13 +407,14 @@ - (void)installWithToolAndRelaunch:(BOOL)relaunch displayingUserInterface:(BOOL)showUI { assert(self.updateItem); - - if (![self validateUpdateDownloadedToPath:self.downloadPath extractedToPath:self.tempDir DSASignature:self.updateItem.DSASignature publicDSAKey:self.host.publicDSAKey]) - { + assert(self.updateValidator); + + BOOL validationCheckSuccess = [self.updateValidator validateWithUpdateDirectory:self.tempDir]; + if (!validationCheckSuccess) { NSDictionary *userInfo = @{ - NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while extracting the archive. Please try again later.", nil), - NSLocalizedFailureReasonErrorKey: SULocalizedString(@"The update is improperly signed.", nil), - }; + NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while extracting the archive. Please try again later.", nil), + NSLocalizedFailureReasonErrorKey: SULocalizedString(@"The update is improperly signed.", nil), + }; [self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUSignatureError userInfo:userInfo]]; return; } @@ -464,34 +450,43 @@ // Copy the relauncher into a temporary directory so we can get to it after the new version's installed. // Only the paranoid survive: if there's already a stray copy of relaunch there, we would have problems. NSString *const relaunchToolName = @"" SPARKLE_RELAUNCH_TOOL_NAME; - NSString *const relaunchPathToCopy = [sparkleBundle pathForResource:relaunchToolName ofType:@"app"]; - if (relaunchPathToCopy != nil) { - NSString *targetPath = [self.host.appCachePath stringByAppendingPathComponent:[relaunchPathToCopy lastPathComponent]]; - - SUFileManager *fileManager = [SUFileManager fileManagerAllowingAuthorization:NO]; - NSError *error = nil; - - NSURL *relaunchURLToCopy = [NSURL fileURLWithPath:relaunchPathToCopy]; - NSURL *targetURL = [NSURL fileURLWithPath:targetPath]; - + NSString *const relaunchToolSourcePath = [sparkleBundle pathForResource:relaunchToolName ofType:@"app"]; + NSString *relaunchCopyTargetPath = nil; + NSError *error = nil; + BOOL copiedRelaunchPath = NO; + + if (relaunchToolSourcePath) { + relaunchCopyTargetPath = [[self appCachePath] stringByAppendingPathComponent:[relaunchToolSourcePath lastPathComponent]]; + + SUFileManager *fileManager = [SUFileManager defaultManager]; + + NSURL *relaunchToolSourceURL = [NSURL fileURLWithPath:relaunchToolSourcePath]; + NSURL *relaunchCopyTargetURL = [NSURL fileURLWithPath:relaunchCopyTargetPath]; + // We only need to run our copy of the app by spawning a task // Since we are copying the app to a directory that is write-accessible, we don't need to muck with owner/group IDs - if ([self preparePathForRelaunchTool:targetPath error:&error] && [fileManager copyItemAtURL:relaunchURLToCopy toURL:targetURL error:&error]) { + if ([self preparePathForRelaunchTool:relaunchCopyTargetPath error:&error] && [fileManager copyItemAtURL:relaunchToolSourceURL toURL:relaunchCopyTargetURL error:&error]) { + copiedRelaunchPath = YES; + // We probably don't need to release the quarantine, but we'll do it just in case it's necessary. // Perhaps in a sandboxed environment this matters more. Note that this may not be a fatal error. NSError *quarantineError = nil; - if (![fileManager releaseItemFromQuarantineAtRootURL:targetURL error:&quarantineError]) { - SULog(@"Failed to release quarantine on %@ with error %@", targetPath, quarantineError); + if (![fileManager releaseItemFromQuarantineAtRootURL:relaunchCopyTargetURL error:&quarantineError]) { + SULog(@"Failed to release quarantine on %@ with error %@", relaunchCopyTargetPath, quarantineError); } - self.relaunchPath = targetPath; - } else { - [self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SURelaunchError userInfo:@{ - NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while extracting the archive. Please try again later.", nil), - NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:@"Couldn't copy relauncher (%@) to temporary path (%@)! %@", relaunchPathToCopy, targetPath, (error ? [error localizedDescription] : @"")] - }]]; } } + if (!copiedRelaunchPath) { + [self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SURelaunchError userInfo:@{ + NSLocalizedDescriptionKey: [NSString stringWithFormat:SULocalizedString(@"An error occurred while relaunching %1$@, but the new version will be available next time you run %1$@.", nil), [self.host name]], + NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:@"Couldn't copy relauncher (%@) to temporary path (%@)! %@", + relaunchToolSourcePath, relaunchCopyTargetPath, (error ? [error localizedDescription] : @"")], + }]]; + return; + } + + self.relaunchPath = relaunchCopyTargetPath; // Set for backwards compatibility, in case any delegates modify it [[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterWillRestartNotification object:self]; if ([updaterDelegate respondsToSelector:@selector(updaterWillRelaunchApplication:)]) [updaterDelegate updaterWillRelaunchApplication:self.updater]; @@ -501,9 +496,8 @@ // Note that we explicitly use the host app's name here, since updating plugin for Mail relaunches Mail, not just the plugin. [self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SURelaunchError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:SULocalizedString(@"An error occurred while relaunching %1$@, but the new version will be available next time you run %1$@.", nil), [self.host name]], - NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:@"Couldn't find the relauncher (expected to find it at %@)", self.relaunchPath] + NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:@"Couldn't find the relauncher (expected to find it at %@ and %@)", relaunchToolSourcePath, self.relaunchPath], }]]; - // We intentionally don't abandon the update here so that the host won't initiate another. return; } @@ -511,6 +505,7 @@ if ([updaterDelegate respondsToSelector:@selector(pathToRelaunchForUpdater:)]) { pathToRelaunch = [updaterDelegate pathToRelaunchForUpdater:self.updater]; } + [NSTask launchedTaskWithLaunchPath:relaunchToolPath arguments:@[[self.host bundlePath], pathToRelaunch, [NSString stringWithFormat:@"%d", [[NSProcessInfo processInfo] processIdentifier]], @@ -520,6 +515,7 @@ [self terminateApp]; } +// Note: this is overridden by the automatic update driver to not terminate in some cases - (void)terminateApp { [NSApp terminate:self]; @@ -565,8 +561,8 @@ NSError *errorToDisplay = error; int finiteRecursion=5; do { - SULog(@"Error: %@ %@ (URL %@)", errorToDisplay.localizedDescription, errorToDisplay.localizedFailureReason, errorToDisplay.userInfo[NSURLErrorFailingURLErrorKey]); - errorToDisplay = errorToDisplay.userInfo[NSUnderlyingErrorKey]; + SULog(@"Error: %@ %@ (URL %@)", errorToDisplay.localizedDescription, errorToDisplay.localizedFailureReason, [errorToDisplay.userInfo objectForKey:NSURLErrorFailingURLErrorKey]); + errorToDisplay = [errorToDisplay.userInfo objectForKey:NSUnderlyingErrorKey]; } while(--finiteRecursion && errorToDisplay); } if (self.download) { diff --git a/Sparkle/SUBinaryDeltaCommon.m b/Sparkle/SUBinaryDeltaCommon.m index be3966ce..5f6ce079 100644 --- a/Sparkle/SUBinaryDeltaCommon.m +++ b/Sparkle/SUBinaryDeltaCommon.m @@ -221,7 +221,7 @@ BOOL removeTree(NSString *path) BOOL copyTree(NSString *source, NSString *dest) { - return [[SUFileManager fileManagerAllowingAuthorization:NO] copyItemAtURL:[NSURL fileURLWithPath:source] toURL:[NSURL fileURLWithPath:dest] error:NULL]; + return [[SUFileManager defaultManager] copyItemAtURL:[NSURL fileURLWithPath:source] toURL:[NSURL fileURLWithPath:dest] error:NULL]; } BOOL modifyPermissions(NSString *path, mode_t desiredPermissions) @@ -231,12 +231,12 @@ BOOL modifyPermissions(NSString *path, mode_t desiredPermissions) if (!attributes) { return NO; } - NSNumber *permissions = attributes[NSFilePosixPermissions]; + NSNumber *permissions = [attributes objectForKey:NSFilePosixPermissions]; if (!permissions) { return NO; } mode_t newMode = ([permissions unsignedShortValue] & ~PERMISSION_FLAGS) | desiredPermissions; - int (*changeModeFunc)(const char *, mode_t) = [attributes[NSFileType] isEqualToString:NSFileTypeSymbolicLink] ? lchmod : chmod; + int (*changeModeFunc)(const char *, mode_t) = [[attributes objectForKey:NSFileType] isEqualToString:NSFileTypeSymbolicLink] ? lchmod : chmod; if (changeModeFunc([path fileSystemRepresentation], newMode) != 0) { return NO; } diff --git a/Sparkle/SUBinaryDeltaCreate.m b/Sparkle/SUBinaryDeltaCreate.m index 98a6f08b..0a8fbc52 100644 --- a/Sparkle/SUBinaryDeltaCreate.m +++ b/Sparkle/SUBinaryDeltaCreate.m @@ -87,7 +87,7 @@ static NSDictionary *infoForFile(FTSENT *ent) static bool aclExists(const FTSENT *ent) { - // OS X does not currently support ACLs for symlinks + // macOS does not currently support ACLs for symlinks if (ent->fts_info == FTS_SL) { return NO; } diff --git a/Sparkle/SUBinaryDeltaUnarchiver.m b/Sparkle/SUBinaryDeltaUnarchiver.m index 7d1e1496..5ff34bd8 100644 --- a/Sparkle/SUBinaryDeltaUnarchiver.m +++ b/Sparkle/SUBinaryDeltaUnarchiver.m @@ -10,9 +10,9 @@ #import "SUBinaryDeltaUnarchiver.h" #import "SUBinaryDeltaApply.h" #import "SUUnarchiver_Private.h" +#import "SUFileManager.h" #import "SUHost.h" #import "SULog.h" -#import "NTSynchronousTask.h" @implementation SUBinaryDeltaUnarchiver @@ -21,6 +21,46 @@ return [[path pathExtension] isEqualToString:@"delta"]; } ++ (BOOL)unsafeIfArchiveIsNotValidated +{ + return YES; +} + +// According to https://developer.apple.com/library/mac/documentation/Carbon/Conceptual/MDImporters/Concepts/Troubleshooting.html +// We should make sure mdimporter bundles have an up to date time in the event they were delta updated. +// We used to invoke mdimport on the bundle but this is not a very good approach. +// There's no need to do that for non-delta updates and for updates that contain no mdimporters. +// Moreover, updating the timestamp on the mdimporter bundles is what developers have to do anyway when shipping their new update outside of Sparkle ++ (void)updateSpotlightImportersAtBundlePath:(NSString *)targetPath +{ + NSURL *targetURL = [NSURL fileURLWithPath:targetPath]; + // Only recurse if it's actually a directory. Don't recurse into a + // root-level symbolic link. + NSDictionary *rootAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:targetPath error:nil]; + NSString *rootType = [rootAttributes objectForKey:NSFileType]; + + if ([rootType isEqualToString:NSFileTypeDirectory]) { + // The NSDirectoryEnumerator will avoid recursing into any contained + // symbolic links, so no further type checks are needed. + NSDirectoryEnumerator *directoryEnumerator = [[NSFileManager defaultManager] enumeratorAtURL:targetURL includingPropertiesForKeys:nil options:(NSDirectoryEnumerationOptions)0 errorHandler:nil]; + + NSMutableArray *filesToUpdate = [[NSMutableArray alloc] init]; + for (NSURL *file in directoryEnumerator) { + if ([file.pathExtension isEqualToString:@"mdimporter"]) { + [filesToUpdate addObject:file]; + } + } + + SUFileManager *fileManager = [SUFileManager defaultManager]; + for (NSURL *file in filesToUpdate) { + NSError *error = nil; + if (![fileManager updateModificationAndAccessTimeOfItemAtURL:file error:&error]) { + SULog(@"Error: During delta unarchiving, failed to touch %@", error); + } + } + } +} + - (void)applyBinaryDelta { @autoreleasepool { @@ -30,6 +70,8 @@ NSError *applyDiffError = nil; BOOL success = applyBinaryDelta(sourcePath, targetPath, self.archivePath, NO, &applyDiffError); if (success) { + [[self class] updateSpotlightImportersAtBundlePath:targetPath]; + dispatch_async(dispatch_get_main_queue(), ^{ [self notifyDelegateOfSuccess]; }); diff --git a/Sparkle/SUCodeSigningVerifier.h b/Sparkle/SUCodeSigningVerifier.h index eddd1b26..bae76685 100644 --- a/Sparkle/SUCodeSigningVerifier.h +++ b/Sparkle/SUCodeSigningVerifier.h @@ -12,10 +12,9 @@ #import @interface SUCodeSigningVerifier : NSObject -+ (BOOL)codeSignatureMatchesHostAndIsValidAtPath:(NSString *)applicationPath error:(NSError **)error; -+ (BOOL)codeSignatureIsValidAtPath:(NSString *)applicationPath error:(NSError **)error; -+ (BOOL)hostApplicationIsCodeSigned; -+ (BOOL)applicationAtPathIsCodeSigned:(NSString *)applicationPath; ++ (BOOL)codeSignatureAtBundleURL:(NSURL *)oldBundlePath matchesSignatureAtBundleURL:(NSURL *)newBundlePath error:(NSError **)error; ++ (BOOL)codeSignatureIsValidAtBundleURL:(NSURL *)bundlePath error:(NSError **)error; ++ (BOOL)bundleAtURLIsCodeSigned:(NSURL *)bundlePath; @end #endif diff --git a/Sparkle/SUCodeSigningVerifier.m b/Sparkle/SUCodeSigningVerifier.m index 8690641b..1da556f2 100644 --- a/Sparkle/SUCodeSigningVerifier.m +++ b/Sparkle/SUCodeSigningVerifier.m @@ -13,53 +13,46 @@ @implementation SUCodeSigningVerifier -+ (BOOL)codeSignatureMatchesHostAndIsValidAtPath:(NSString *)applicationPath error:(NSError *__autoreleasing *)error ++ (BOOL)codeSignatureAtBundleURL:(NSURL *)oldBundleURL matchesSignatureAtBundleURL:(NSURL *)newBundleURL error:(NSError *__autoreleasing *)error { OSStatus result; SecRequirementRef requirement = NULL; SecStaticCodeRef staticCode = NULL; - SecCodeRef hostCode = NULL; - NSBundle *newBundle; + SecStaticCodeRef oldCode = NULL; CFErrorRef cfError = NULL; if (error) { *error = nil; } - result = SecCodeCopySelf(kSecCSDefaultFlags, &hostCode); - if (result != noErr) { - SULog(@"Failed to copy host code %d", result); - goto finally; + result = SecStaticCodeCreateWithPath((__bridge CFURLRef)oldBundleURL, kSecCSDefaultFlags, &oldCode); + if (result == errSecCSUnsigned) { + return NO; } - result = SecCodeCopyDesignatedRequirement(hostCode, kSecCSDefaultFlags, &requirement); + result = SecCodeCopyDesignatedRequirement(oldCode, kSecCSDefaultFlags, &requirement); if (result != noErr) { SULog(@"Failed to copy designated requirement. Code Signing OSStatus code: %d", result); goto finally; } - newBundle = [NSBundle bundleWithPath:applicationPath]; - if (!newBundle) { - SULog(@"Failed to load NSBundle for update"); - result = -1; - goto finally; - } - - result = SecStaticCodeCreateWithPath((__bridge CFURLRef)[newBundle bundleURL], kSecCSDefaultFlags, &staticCode); + result = SecStaticCodeCreateWithPath((__bridge CFURLRef)newBundleURL, kSecCSDefaultFlags, &staticCode); if (result != noErr) { SULog(@"Failed to get static code %d", result); goto finally; } - + // Note that kSecCSCheckNestedCode may not work with pre-Mavericks code signing. // See https://github.com/sparkle-project/Sparkle/issues/376#issuecomment-48824267 and https://developer.apple.com/library/mac/technotes/tn2206 - SecCSFlags flags = (SecCSFlags) (kSecCSDefaultFlags | kSecCSCheckAllArchitectures); + // Aditionally, there are several reasons to stay away from deep verification and to prefer DSA signing the download archive instead. + // See https://github.com/sparkle-project/Sparkle/pull/523#commitcomment-17549302 and https://github.com/sparkle-project/Sparkle/issues/543 + SecCSFlags flags = (SecCSFlags) (kSecCSDefaultFlags | kSecCSCheckAllArchitectures); result = SecStaticCodeCheckValidityWithErrors(staticCode, flags, requirement, &cfError); - + if (cfError) { NSError *tmpError = CFBridgingRelease(cfError); if (error) *error = tmpError; } - + if (result != noErr) { if (result == errSecCSUnsigned) { SULog(@"The host app is signed, but the new version of the app is not signed using Apple Code Signing. Please ensure that the new app is signed and that archiving did not corrupt the signature."); @@ -70,61 +63,52 @@ SULog(@"Code signature of the new version doesn't match the old version: %@. Please ensure that old and new app is signed using exactly the same certificate.", requirementString); CFRelease(requirementString); } - - [self logSigningInfoForCode:hostCode label:@"host info"]; + + [self logSigningInfoForCode:oldCode label:@"old info"]; [self logSigningInfoForCode:staticCode label:@"new info"]; } } - + finally: - if (hostCode) CFRelease(hostCode); + if (oldCode) CFRelease(oldCode); if (staticCode) CFRelease(staticCode); if (requirement) CFRelease(requirement); return (result == noErr); } -+ (BOOL)codeSignatureIsValidAtPath:(NSString *)applicationPath error:(NSError *__autoreleasing *)error ++ (BOOL)codeSignatureIsValidAtBundleURL:(NSURL *)bundleURL error:(NSError *__autoreleasing *)error { OSStatus result; SecStaticCodeRef staticCode = NULL; - NSBundle *newBundle; CFErrorRef cfError = NULL; if (error) { *error = nil; } - newBundle = [NSBundle bundleWithPath:applicationPath]; - if (!newBundle) { - SULog(@"Failed to load NSBundle"); - result = -1; - goto finally; - } - - result = SecStaticCodeCreateWithPath((__bridge CFURLRef)[newBundle bundleURL], kSecCSDefaultFlags, &staticCode); + result = SecStaticCodeCreateWithPath((__bridge CFURLRef)bundleURL, kSecCSDefaultFlags, &staticCode); if (result != noErr) { SULog(@"Failed to get static code %d", result); goto finally; } - // Note that kSecCSCheckNestedCode may not work with pre-Mavericks code signing. - // See https://github.com/sparkle-project/Sparkle/issues/376#issuecomment-48824267 and https://developer.apple.com/library/mac/technotes/tn2206 - SecCSFlags flags = (SecCSFlags) (kSecCSDefaultFlags | kSecCSCheckAllArchitectures); + // See in -codeSignatureAtBundleURL:matchesSignatureAtBundleURL:error: for why kSecCSCheckNestedCode is not passed + SecCSFlags flags = (SecCSFlags) (kSecCSDefaultFlags | kSecCSCheckAllArchitectures); result = SecStaticCodeCheckValidityWithErrors(staticCode, flags, NULL, &cfError); - + if (cfError) { NSError *tmpError = CFBridgingRelease(cfError); if (error) *error = tmpError; } - + if (result != noErr) { if (result == errSecCSUnsigned) { - SULog(@"Error: The app is not signed using Apple Code Signing. %@", applicationPath); + SULog(@"Error: The app is not signed using Apple Code Signing. %@", bundleURL); } if (result == errSecCSReqFailed) { [self logSigningInfoForCode:staticCode label:@"new info"]; } } - + finally: if (staticCode) CFRelease(staticCode); return (result == noErr); @@ -141,44 +125,23 @@ static id valueOrNSNull(id value) { NSDictionary *signingDict = CFBridgingRelease(signingInfo); NSMutableDictionary *relevantInfo = [NSMutableDictionary dictionary]; for (NSString *key in @[@"format", @"identifier", @"requirements", @"teamid", @"signing-time"]) { - relevantInfo[key] = valueOrNSNull(signingDict[key]); + [relevantInfo setObject:valueOrNSNull([signingDict objectForKey:key]) forKey:key]; } - NSDictionary *infoPlist = signingDict[@"info-plist"]; - relevantInfo[@"version"] = valueOrNSNull(infoPlist[@"CFBundleShortVersionString"]); - relevantInfo[@"build"] = valueOrNSNull(infoPlist[(__bridge NSString *)kCFBundleVersionKey]); + NSDictionary *infoPlist = [signingDict objectForKey:@"info-plist"]; + [relevantInfo setObject:valueOrNSNull([infoPlist objectForKey:@"CFBundleShortVersionString"]) forKey:@"version"]; + [relevantInfo setObject:valueOrNSNull([infoPlist objectForKey:(__bridge NSString *)kCFBundleVersionKey]) forKey:@"build"]; SULog(@"%@: %@", label, relevantInfo); } } -+ (BOOL)hostApplicationIsCodeSigned -{ - OSStatus result; - SecCodeRef hostCode = NULL; - result = SecCodeCopySelf(kSecCSDefaultFlags, &hostCode); - if (result != 0) return NO; - - SecRequirementRef requirement = NULL; - result = SecCodeCopyDesignatedRequirement(hostCode, kSecCSDefaultFlags, &requirement); - if (hostCode) CFRelease(hostCode); - if (requirement) CFRelease(requirement); - return (result == 0); -} - -+ (BOOL)applicationAtPathIsCodeSigned:(NSString *)applicationPath ++ (BOOL)bundleAtURLIsCodeSigned:(NSURL *)bundleURL { OSStatus result; SecStaticCodeRef staticCode = NULL; - NSBundle *newBundle; - newBundle = [NSBundle bundleWithPath:applicationPath]; - if (!newBundle) { - SULog(@"Failed to load NSBundle"); - return NO; - } - - result = SecStaticCodeCreateWithPath((__bridge CFURLRef)[newBundle bundleURL], kSecCSDefaultFlags, &staticCode); + result = SecStaticCodeCreateWithPath((__bridge CFURLRef)bundleURL, kSecCSDefaultFlags, &staticCode); if (result == errSecCSUnsigned) { - return NO; + return NO; } SecRequirementRef requirement = NULL; @@ -190,7 +153,7 @@ static id valueOrNSNull(id value) { CFRelease(requirement); } if (result == errSecCSUnsigned) { - return NO; + return NO; } return (result == 0); } diff --git a/Sparkle/SUConstants.h b/Sparkle/SUConstants.h index b717d843..fe2dfd2c 100644 --- a/Sparkle/SUConstants.h +++ b/Sparkle/SUConstants.h @@ -43,13 +43,13 @@ extern NSString *const SUPublicDSAKeyFileKey; extern NSString *const SUAutomaticallyUpdateKey; extern NSString *const SUAllowsAutomaticUpdatesKey; extern NSString *const SUEnableAutomaticChecksKey; -extern NSString *const SUEnableAutomaticChecksKeyOld; extern NSString *const SUEnableSystemProfilingKey; extern NSString *const SUSendProfileInfoKey; extern NSString *const SULastProfileSubmitDateKey; extern NSString *const SUPromptUserOnFirstLaunchKey; extern NSString *const SUKeepDownloadOnFailedInstallKey; extern NSString *const SUDefaultsDomainKey; +extern NSString *const SUEnableJavaScriptKey; extern NSString *const SUFixedHTMLDisplaySizeKey __attribute__((deprecated("This key is obsolete and has no effect."))); extern NSString *const SUAppendVersionNumberKey __attribute__((deprecated("This key is obsolete. See SPARKLE_APPEND_VERSION_NUMBER."))); extern NSString *const SUEnableAutomatedDowngradesKey __attribute__((deprecated("This key is obsolete. See SPARKLE_AUTOMATED_DOWNGRADES."))); diff --git a/Sparkle/SUConstants.m b/Sparkle/SUConstants.m index 31c80ca3..33aa91fd 100644 --- a/Sparkle/SUConstants.m +++ b/Sparkle/SUConstants.m @@ -38,10 +38,10 @@ NSString *const SUAutomaticallyUpdateKey = @"SUAutomaticallyUpdate"; NSString *const SUAllowsAutomaticUpdatesKey = @"SUAllowsAutomaticUpdates"; NSString *const SUEnableSystemProfilingKey = @"SUEnableSystemProfiling"; NSString *const SUEnableAutomaticChecksKey = @"SUEnableAutomaticChecks"; -NSString *const SUEnableAutomaticChecksKeyOld = @"SUCheckAtStartup"; NSString *const SUSendProfileInfoKey = @"SUSendProfileInfo"; NSString *const SULastProfileSubmitDateKey = @"SULastProfileSubmissionDate"; NSString *const SUPromptUserOnFirstLaunchKey = @"SUPromptUserOnFirstLaunch"; +NSString *const SUEnableJavaScriptKey = @"SUEnableJavaScript"; NSString *const SUFixedHTMLDisplaySizeKey = @"SUFixedHTMLDisplaySize"; NSString *const SUKeepDownloadOnFailedInstallKey = @"SUKeepDownloadOnFailedInstall"; NSString *const SUDefaultsDomainKey = @"SUDefaultsDomain"; diff --git a/Sparkle/SUDiskImageUnarchiver.m b/Sparkle/SUDiskImageUnarchiver.m index 89558716..5b223064 100644 --- a/Sparkle/SUDiskImageUnarchiver.m +++ b/Sparkle/SUDiskImageUnarchiver.m @@ -8,7 +8,6 @@ #import "SUDiskImageUnarchiver.h" #import "SUUnarchiver_Private.h" -#import "NTSynchronousTask.h" #import "SULog.h" #include @@ -19,6 +18,11 @@ return [[path pathExtension] isEqualToString:@"dmg"]; } ++ (BOOL)unsafeIfArchiveIsNotValidated +{ + return NO; +} + // Called on a non-main thread. - (void)extractDMG { @@ -92,12 +96,27 @@ NSInteger taskResult = -1; @try { - NTSynchronousTask *task = [[NTSynchronousTask alloc] init]; - - [task run:@"/usr/bin/hdiutil" directory:@"/" withArgs:arguments input:promptData]; - - taskResult = [task result]; - output = [[task output] copy]; + NSTask *task = [[NSTask alloc] init]; + task.launchPath = @"/usr/bin/hdiutil"; + task.currentDirectoryPath = @"/"; + task.arguments = arguments; + + NSPipe *inputPipe = [NSPipe pipe]; + NSPipe *outputPipe = [NSPipe pipe]; + + task.standardInput = inputPipe; + task.standardOutput = outputPipe; + + [task launch]; + + [inputPipe.fileHandleForWriting writeData:promptData]; + [inputPipe.fileHandleForWriting closeFile]; + + // Read data to end *before* waiting until the task ends so we don't deadlock if the stdout buffer becomes full if we haven't consumed from it + output = [outputPipe.fileHandleForReading readDataToEndOfFile]; + + [task waitUntilExit]; + taskResult = task.terminationStatus; } @catch (NSException *) { @@ -147,10 +166,16 @@ dispatch_async(dispatch_get_main_queue(), delegateFailure); finally: - if (mountedSuccessfully) - [NSTask launchedTaskWithLaunchPath:@"/usr/bin/hdiutil" arguments:@[@"detach", mountPoint, @"-force"]]; - else + if (mountedSuccessfully) { + @try { + [NSTask launchedTaskWithLaunchPath:@"/usr/bin/hdiutil" arguments:@[@"detach", mountPoint, @"-force"]]; + } @catch (NSException *exception) { + SULog(@"Failed to unmount %@", mountPoint); + SULog(@"Exception: %@", exception); + } + } else { SULog(@"Can't mount DMG %@", self.archivePath); + } } } diff --git a/Sparkle/SUErrors.h b/Sparkle/SUErrors.h index d73aadba..8557d7fb 100644 --- a/Sparkle/SUErrors.h +++ b/Sparkle/SUErrors.h @@ -9,7 +9,11 @@ #ifndef SUERRORS_H #define SUERRORS_H +#if __has_feature(modules) +@import Foundation; +#else #import +#endif #import "SUExport.h" /** @@ -23,10 +27,11 @@ typedef NS_ENUM(OSStatus, SUError) { SUNoUpdateError = 1001, SUAppcastError = 1002, SURunningFromDiskImageError = 1003, - - // Downlaod phase errors. + + // Download phase errors. SUTemporaryDirectoryError = 2000, - + SUDownloadError = 2001, + // Extraction phase errors. SUUnarchivingError = 3000, SUSignatureError = 3001, @@ -39,6 +44,7 @@ typedef NS_ENUM(OSStatus, SUError) { SURelaunchError = 4004, SUInstallationError = 4005, SUDowngradeError = 4006, + SUInstallationCancelledError = 4007, // System phase errors SUSystemPowerOffError = 5000 diff --git a/Sparkle/SUFileManager.h b/Sparkle/SUFileManager.h index f6897ced..6aa0f9af 100644 --- a/Sparkle/SUFileManager.h +++ b/Sparkle/SUFileManager.h @@ -9,21 +9,36 @@ #import /** - * A class used for performing file operations that may also perform authentication if allowed and if permission is denied when trying to + * A class used for performing file operations that may also perform authorization if allowed and if permission is denied when trying to * perform them normally as the running user. All operations on this class may be used on thread other than the main thread. * This class provides basic file operations and stays away from including much application-level logic. */ @interface SUFileManager : NSObject /** - * Creates a file manager that allows or disallows authorizing for file operations - * @param allowsAuthorization Specifies whether operations invoked on this instance are allowed to acquire authorization in order - * to perform file operations when read or write access is denied +* Creates a file manager that will not authorize for file operations +* @return A new file manager instance +*/ ++ (instancetype)defaultManager; + +/** + * Creates a file manager that allows authorizing for file operations + * @param authorizationToolPath Specifies the path to the tool that can perform file operations and be run as root. + * This tool will be invoked when read or write access is denied when attempting ordinary file operations. See the `fileop` tool included in Sparkle. * @return A new file manager instance - * - * This method just creates the file manager. It doesn't acquire authorization immediately if allowsAuthorization is YES + * + * This method just creates the file manager. It doesn't acquire authorization immediately or if it doesn't need to. */ -+ (instancetype)fileManagerAllowingAuthorization:(BOOL)allowsAuthorization; ++ (instancetype)fileManagerWithAuthorizationToolPath:(NSString *)authorizationToolPath; + +/** + * Returns a file manager that allows or disallows authorizing for file operations based on the current file manager + * @return A file manager instance that can perform authorized operations if the current file manager has already performed them. + * If the current file manager instance hasn't yet performed authorized operations, then neither can the instance returned by this method + * + * This may return a newly created file manager or re-use the existing file manager depending on the current authorization rights. + */ +- (instancetype)fileManagerByPreservingAuthorizationRights; /** * Creates a temporary directory on the same volume as a provided URL @@ -37,6 +52,16 @@ */ - (NSURL *)makeTemporaryDirectoryWithPreferredName:(NSString *)preferredName appropriateForDirectoryURL:(NSURL *)appropriateURL error:(NSError **)error; +/** + * Creates a directory at the target URL + * @param targetURL A URL pointing to the directory to create. The item at this URL must not exist, and the parent directory of this URL must already exist. + * @param error If an error occurs, upon returns contains an NSError object that describes the problem. If you are not interested in possible errors, you may pass in NULL. + * @return YES if the item was created successfully, otherwise NO along with a populated error object + * + * This is an atomic operation. + */ +- (BOOL)makeDirectoryAtURL:(NSURL *)targetURL error:(NSError **)error; + /** * Moves an item from a source to a destination * @param sourceURL A URL pointing to the item to move. The item at this URL must exist. @@ -120,8 +145,8 @@ * @return YES if all the items at the target could be released from quarantine, otherwise NO if any items couldn't along with a populated error object * * This method removes quarantine attributes from an item, ideally an application, so that when the user launches a new application themselves, they - * don't have to witness the OS X dialog alerting them that they downloaded an application from the internet and asking if they want to continue. - * Note that this may not exactly mimic OS X's behavior when a user opens an application for the first time (i.e, the xattr isn't deleted), + * don't have to witness the system dialog alerting them that they downloaded an application from the internet and asking if they want to continue. + * Note that this may not exactly mimic the system behavior when a user opens an application for the first time (i.e, the xattr isn't deleted), * but this should be sufficient enough for our purposes. * * This method may return NO even if some items do get released from quarantine if the target URL is pointing to a directory. @@ -131,4 +156,16 @@ */ - (BOOL)releaseItemFromQuarantineAtRootURL:(NSURL *)rootURL error:(NSError **)error; +/** + * Runs an installer package (pkg) in a headless mode using /usr/sbin/installer + * @param packageURL A URL pointing to the package to execute. The item at this URL must exist. + * @param error If an error occurs, upon returns contains an NSError object that describes the problem. If you are not interested in possible errors, you may pass in NULL. + * @return YES if the installer ran the package successfully, otherwise NO with a populated error object + * + * This method uses the system wide installer tool to run the provided package. This process does not show any UI, except for + * an initial authorization prompt if the calling process does not have root privileges. In other words, root privileges are required to use this method, and the file manager instance must have been created by allowing authorization. + * An error can occur if the package is unable to be ran by the installer, or if the installer reports a non-zero exit status code. + */ +- (BOOL)executePackageAtURL:(NSURL *)packageURL error:(NSError **)error; + @end diff --git a/Sparkle/SUFileManager.m b/Sparkle/SUFileManager.m index be5ef09b..6488e016 100644 --- a/Sparkle/SUFileManager.m +++ b/Sparkle/SUFileManager.m @@ -8,6 +8,7 @@ #import "SUFileManager.h" #import "SUOperatingSystem.h" +#import "SUFileOperationConstants.h" #include #include @@ -15,30 +16,6 @@ static char SUAppleQuarantineIdentifier[] = "com.apple.quarantine"; -// Authorization code based on generous contribution from Allan Odgaard. Thanks, Allan! -static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authorization, const char *executablePath, AuthorizationFlags options, char *const *arguments) -{ - sig_t oldSigChildHandler = signal(SIGCHLD, SIG_DFL); - BOOL returnValue = YES; - -#pragma clang diagnostic push - // In the future, we may have to look at SMJobBless API to avoid deprecation. See issue #558 -#pragma clang diagnostic ignored "-Wdeprecated-declarations" - if (AuthorizationExecuteWithPrivileges(authorization, executablePath, options, arguments, NULL) == errAuthorizationSuccess) -#pragma clang diagnostic pop - { - int status; - pid_t pid = wait(&status); - if (pid == -1 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) - returnValue = NO; - } - else - returnValue = NO; - - signal(SIGCHLD, oldSigChildHandler); - return returnValue; -} - static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { char path[PATH_MAX] = {0}; @@ -75,26 +52,37 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { { AuthorizationRef _auth; NSFileManager *_fileManager; - BOOL _allowsAuthorization; + NSString *_authorizationToolPath; } -- (instancetype)initAllowingAuthorization:(BOOL)allowsAuthorization +- (instancetype)initWithAuthorizationToolPath:(NSString *)authorizationToolPath { self = [super init]; if (self != nil) { _fileManager = [[NSFileManager alloc] init]; - _allowsAuthorization = allowsAuthorization; + _authorizationToolPath = [authorizationToolPath copy]; } return self; } - -+ (instancetype)fileManagerAllowingAuthorization:(BOOL)allowsAuthorization ++ (instancetype)defaultManager { - return [[self alloc] initAllowingAuthorization:allowsAuthorization]; + return [[self alloc] initWithAuthorizationToolPath:nil]; } -// Acquires an authorization reference which is intended to be used for future authorized file operations ++ (instancetype)fileManagerWithAuthorizationToolPath:(NSString *)authorizationToolPath +{ + return [[self alloc] initWithAuthorizationToolPath:authorizationToolPath]; +} + +- (instancetype)fileManagerByPreservingAuthorizationRights +{ + // Check if we don't allow authorization, or that we haven't needed to authorize yet, to create or re-use a + // file manager instance with these restrictions + return (_authorizationToolPath != nil && _auth != NULL) ? self : [SUFileManager defaultManager]; +} + +// Acquires an authorization reference with root privileges which is intended to be used for authorized file operations - (BOOL)_acquireAuthorizationWithError:(NSError *__autoreleasing *)error { // No need to continue if we already acquired an authorization reference @@ -102,21 +90,112 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { return YES; } - if (!_allowsAuthorization) { + if (_authorizationToolPath == nil) { if (error != NULL) { *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: @"Unable to grant authorization to perform action because it is explicitly turned off" }]; } return NO; } - OSStatus status = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &_auth); - if (status != errAuthorizationSuccess) { + OSStatus createStatus = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &_auth); + if (createStatus != errAuthorizationSuccess) { if (error != NULL) { - *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed creating authorization reference with status code %d.", status] }]; + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed creating authorization reference with status code %d.", createStatus] }]; } _auth = NULL; return NO; } + + AuthorizationItem rightItems[] = { + // The right that allows us to run tools as root user + {.name = kAuthorizationRightExecute, .valueLength = 0, .value = NULL, .flags = 0} + }; + + AuthorizationRights rights = { + .count = sizeof(rightItems) / sizeof(*rightItems), + .items = rightItems + }; + + AuthorizationFlags flags = + (AuthorizationFlags)(kAuthorizationFlagDefaults | kAuthorizationFlagInteractionAllowed | kAuthorizationFlagExtendRights | kAuthorizationFlagPreAuthorize); + + // This will test if we can gain authorization for running utlities as root + OSStatus copyStatus = AuthorizationCopyRights(_auth, &rights, kAuthorizationEmptyEnvironment, flags, NULL); + if (copyStatus != errAuthorizationSuccess) { + if (error != NULL) { + if (copyStatus == errAuthorizationCanceled) { + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationCancelledError userInfo:@{ NSLocalizedDescriptionKey: @"Authorization access was cancelled by the user." }]; + } else { + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed granting authorization rights with status code %d.", copyStatus] }]; + } + } + + AuthorizationFree(_auth, kAuthorizationFlagDefaults); + _auth = NULL; + + return NO; + } + + return YES; +} + +- (BOOL)_authorizeAndExecuteCommand:(char *)command sourcePath:(char *)sourcePath destinationPath:(char *)destinationPath error:(NSError * __autoreleasing *)error +{ + NSError *acquireError = nil; + if (![self _acquireAuthorizationWithError:&acquireError]) { + if (error != NULL) { + *error = acquireError; + } + return NO; + } + + char *arguments[] = { command, sourcePath, destinationPath, NULL }; + + char toolPath[PATH_MAX] = {0}; + if (![_authorizationToolPath getFileSystemRepresentation:toolPath maxLength:sizeof(toolPath)]) { + if (error != NULL) { + *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Authorization tool (%@) cannot be represented as a valid file name.", _authorizationToolPath.lastPathComponent] }]; + } + return NO; + } + + FILE *pipe = NULL; +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + if (AuthorizationExecuteWithPrivileges(_auth, toolPath, kAuthorizationFlagDefaults, arguments, &pipe) != errAuthorizationSuccess) { +#pragma clang diagnostic pop + if (error != NULL) { + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:@"Failed to run authorization tool." }]; + } + return NO; + } + + uint32_t pidData = 0; + if (fread(&pidData, sizeof(pidData), 1, pipe) < 1) { + if (error != NULL) { + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:@"Failed to retrieve authorized executable process identifier." }]; + } + fclose(pipe); + return NO; + } + + pid_t childPid = (int32_t)CFSwapInt32LittleToHost(pidData); + int status = 0; + + pid_t waitResult; + do { + waitResult = waitpid(childPid, &status, 0); + } while (waitResult == -1 && errno == EINTR); + + fclose(pipe); + + if (waitResult == -1 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) { + if (error != NULL) { + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Failed to execute authorized executable with result %d and status (%d, %d, %d).", waitResult, status, WIFEXITED(status), WEXITSTATUS(status)] }]; + } + return NO; + } + return YES; } @@ -151,7 +230,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } if (isDirectory != NULL) { - *isDirectory = [attributes[NSFileType] isEqualToString:NSFileTypeDirectory]; + *isDirectory = [[attributes objectForKey:NSFileType] isEqualToString:NSFileTypeDirectory]; } return YES; @@ -183,7 +262,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { #define XATTR_UTILITY_PATH "/usr/bin/xattr" // Recursively remove an xattr at a specified root URL with authentication -- (BOOL)_removeXAttrWithAuthentication:(char *__nonnull)xattrName fromRootURL:(NSURL *)rootURL error:(NSError *__autoreleasing *)error +- (BOOL)_removeQuarantineWithAuthenticationAtRootURL:(NSURL *)rootURL error:(NSError *__autoreleasing *)error { // Because this is a system utility, it's fine to follow the symbolic link if one exists if (![_fileManager fileExistsAtPath:@(XATTR_UTILITY_PATH)]) { @@ -200,16 +279,11 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } return NO; } - - if (![self _acquireAuthorizationWithError:error]) { - return NO; - } - - BOOL success = AuthorizationExecuteWithPrivilegesAndWait(_auth, XATTR_UTILITY_PATH, kAuthorizationFlagDefaults, (char *[]){ "-s", "-r", "-d", xattrName, path, NULL }); - + + NSError *executeError = nil; + BOOL success = [self _authorizeAndExecuteCommand:SUFileOpRemoveQuarantineCommand sourcePath:path destinationPath:NULL error:&executeError]; if (!success && error != NULL) { - NSString *errorMessage = [NSString stringWithFormat:@"Authenticated extended attribute deletion for %@ failed on %@.", [NSString stringWithUTF8String:xattrName], rootURL.path.lastPathComponent]; - *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:errorMessage }]; + *error = executeError; } return success; @@ -234,7 +308,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { removedQuarantine = YES; } else { if (isAccessError(removalError)) { - removedQuarantine = [self _removeXAttrWithAuthentication:SUAppleQuarantineIdentifier fromRootURL:rootURL error:error]; + removedQuarantine = [self _removeQuarantineWithAuthenticationAtRootURL:rootURL error:error]; attemptedAuthentication = YES; } else { if (success != NULL) { @@ -267,7 +341,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { // root-level symbolic link. NSString *rootURLPath = rootURL.path; NSDictionary *rootAttributes = [_fileManager attributesOfItemAtPath:rootURLPath error:nil]; - NSString *rootType = rootAttributes[NSFileType]; + NSString *rootType = [rootAttributes objectForKey:NSFileType]; // 10.7 can't subscript this if ([rootType isEqualToString:NSFileTypeDirectory]) { // The NSDirectoryEnumerator will avoid recursing into any contained @@ -286,7 +360,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } // Removes the directory tree rooted at |root| from the file quarantine. -// The quarantine was introduced on OS X 10.5 and is described at: +// The quarantine was introduced on macOS 10.5 and is described at: // // http://developer.apple.com/releasenotes/Carbon/RN-LaunchServices/index.html#apple_ref/doc/uid/TP40001369-DontLinkElementID_2 // @@ -388,11 +462,6 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { return NO; } - if (![self _acquireAuthorizationWithError:error]) { - return NO; - } - - char sourcePath[PATH_MAX] = {0}; if (![sourceURL.path getFileSystemRepresentation:sourcePath maxLength:sizeof(sourcePath)]) { if (error != NULL) { @@ -408,11 +477,11 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } return NO; } - - if (!AuthorizationExecuteWithPrivilegesAndWait(_auth, "/bin/cp", kAuthorizationFlagDefaults, (char *[]){ "-Rf", "--", sourcePath, destinationPath, NULL })) { + + NSError *executeError = nil; + if (![self _authorizeAndExecuteCommand:SUFileOpCopyCommand sourcePath:sourcePath destinationPath:destinationPath error:&executeError]) { if (error != NULL) { - NSString *errorMessage = [NSString stringWithFormat:@"Failed to perform authenticated file copy for %@.", sourceURL.lastPathComponent]; - *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:errorMessage }]; + *error = executeError; } return NO; } @@ -501,10 +570,6 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { return NO; } - if (![self _acquireAuthorizationWithError:error]) { - return NO; - } - char sourcePath[PATH_MAX] = {0}; if (![sourceURL.path getFileSystemRepresentation:sourcePath maxLength:sizeof(sourcePath)]) { if (error != NULL) { @@ -520,11 +585,12 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } return NO; } - - if (!AuthorizationExecuteWithPrivilegesAndWait(_auth, "/bin/mv", kAuthorizationFlagDefaults, (char *[]){ "-f", "--", sourcePath, destinationPath, NULL })) { + + NSError *executeError = nil; + if (![self _authorizeAndExecuteCommand:SUFileOpMoveCommand sourcePath:sourcePath destinationPath:destinationPath error:&executeError]) { if (error != NULL) { - NSString *errorMessage = [NSString stringWithFormat:@"Failed to perform authenticated file move for %@.", sourceURL.lastPathComponent]; - *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:errorMessage }]; + NSString *errorMessage = [NSString stringWithFormat:@"Failed to perform authorized file move for %@.", sourceURL.lastPathComponent]; + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:errorMessage, NSUnderlyingErrorKey: executeError }]; } return NO; } @@ -542,7 +608,19 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { return NO; } - if (chown(path, ownerID.unsignedIntValue, groupID.unsignedIntValue) != 0) { + int fileDescriptor = open(path, O_RDONLY | O_SYMLINK); + if (fileDescriptor == -1) { + if (error != NULL) { + *error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to open file descriptor to %@", targetURL.path.lastPathComponent] }]; + } + return NO; + } + + // We use fchown instead of chown because the latter can follow symbolic links + BOOL success = fchown(fileDescriptor, ownerID.unsignedIntValue, groupID.unsignedIntValue) == 0; + close(fileDescriptor); + + if (!success) { if (errno == EPERM) { if (needsAuth != NULL) { *needsAuth = YES; @@ -595,7 +673,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { return NO; } - NSNumber *ownerID = matchFileAttributes[NSFileOwnerAccountID]; + NSNumber *ownerID = [matchFileAttributes objectForKey:NSFileOwnerAccountID]; if (ownerID == nil) { // shouldn't be possible to error here, but just in case if (error != NULL) { @@ -604,7 +682,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { return NO; } - NSNumber *groupID = matchFileAttributes[NSFileGroupOwnerAccountID]; + NSNumber *groupID = [matchFileAttributes objectForKey:NSFileGroupOwnerAccountID]; if (groupID == nil) { // shouldn't be possible to error here, but just in case if (error != NULL) { @@ -613,8 +691,8 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { return NO; } - NSNumber *targetOwnerID = targetFileAttributes[NSFileOwnerAccountID]; - NSNumber *targetGroupID = targetFileAttributes[NSFileGroupOwnerAccountID]; + NSNumber *targetOwnerID = [targetFileAttributes objectForKey:NSFileOwnerAccountID]; + NSNumber *targetGroupID = [targetFileAttributes objectForKey:NSFileGroupOwnerAccountID]; if ((targetOwnerID != nil && [ownerID isEqualToNumber:targetOwnerID]) && (targetGroupID != nil && [groupID isEqualToNumber:targetGroupID])) { // Assume they're the same even if we don't check every file recursively @@ -652,21 +730,20 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } return NO; } - - char userAndGroup[100]; - int written = snprintf(userAndGroup, sizeof(userAndGroup), "%u:%u", ownerID.unsignedIntValue, groupID.unsignedIntValue); - if (written < 0 || written >= 100) { - return NO; // No custom error, because it's too unlikely to ever happen - } - - if (![self _acquireAuthorizationWithError:error]) { + + char matchPath[PATH_MAX] = {0}; + if (![matchURLPath getFileSystemRepresentation:matchPath maxLength:sizeof(matchPath)]) { + if (error != NULL) { + *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Match file (%@) cannot be represented as a valid file name.", matchURL.path.lastPathComponent] }]; + } return NO; } - BOOL success = AuthorizationExecuteWithPrivilegesAndWait(_auth, "/usr/sbin/chown", kAuthorizationFlagDefaults, (char *[]){ "-R", userAndGroup, targetPath, NULL }); + NSError *executeError = nil; + BOOL success = [self _authorizeAndExecuteCommand:SUFileOpChangeOwnerAndGroupCommand sourcePath:targetPath destinationPath:matchPath error:&executeError]; if (!success && error != NULL) { - NSString *errorMessage = [NSString stringWithFormat:@"Failed to change owner:group %@ on %@ with authentication.", [NSString stringWithUTF8String:userAndGroup], targetURL.path.lastPathComponent]; - *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: errorMessage }]; + NSString *errorMessage = [NSString stringWithFormat:@"Failed to change owner & group on %@ to match %@ with authorization.", targetURL.path.lastPathComponent, matchURLPath.lastPathComponent]; + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: errorMessage, NSUnderlyingErrorKey: executeError }]; } return success; @@ -695,7 +772,20 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { return NO; } - if (utimes(path, NULL) == 0) { + int fileDescriptor = open(path, O_RDONLY | O_SYMLINK); + if (fileDescriptor == -1) { + if (error != NULL) { + *error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to open file descriptor to %@", targetURL.path.lastPathComponent] }]; + } + return NO; + } + + // Using futimes() because utimes() follows symbolic links + BOOL updatedTime = (futimes(fileDescriptor, NULL) == 0); + + close(fileDescriptor); + + if (updatedTime) { return YES; } @@ -705,15 +795,12 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } return NO; } - - if (![self _acquireAuthorizationWithError:error]) { - return NO; - } - - BOOL success = AuthorizationExecuteWithPrivilegesAndWait(_auth, "/usr/bin/touch", kAuthorizationFlagDefaults, (char *[]){ "--", path, NULL }); + + NSError *executeError = nil; + BOOL success = [self _authorizeAndExecuteCommand:SUFileOpUpdateModificationAndAccessTimeCommand sourcePath:path destinationPath:NULL error:&executeError]; if (!success && error != NULL) { - NSString *errorMessage = [NSString stringWithFormat:@"Failed to update modification & access time on %@ with authentication.", targetURL.path.lastPathComponent]; - *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: errorMessage }]; + NSString *errorMessage = [NSString stringWithFormat:@"Failed to update modification & access time on %@ with authorization.", targetURL.path.lastPathComponent]; + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: errorMessage, NSUnderlyingErrorKey: executeError }]; } return success; @@ -721,7 +808,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { // Creates a directory at the item pointed by url // An item cannot already exist at the url, but the parent must be a directory that exists -- (BOOL)_makeDirectoryAtURL:(NSURL *)url error:(NSError * __autoreleasing *)error +- (BOOL)makeDirectoryAtURL:(NSURL *)url error:(NSError * __autoreleasing *)error { if ([self _itemExistsAtURL:url]) { if (error != NULL) { @@ -758,16 +845,16 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } return NO; } - - if (![self _acquireAuthorizationWithError:error]) { - return NO; - } - - BOOL success = AuthorizationExecuteWithPrivilegesAndWait(_auth, "/bin/mkdir", kAuthorizationFlagDefaults, (char *[]){ "--", path, NULL }); - if (!success && error != NULL) { - NSString *errorMessage = [NSString stringWithFormat:@"Failed to make directory %@ with authentication.", url.path.lastPathComponent]; - *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: errorMessage }]; + + NSError *executeError = nil; + BOOL success = [self _authorizeAndExecuteCommand:SUFileOpMakeDirectoryCommand sourcePath:path destinationPath:NULL error:&executeError]; + if (!success) { + if (error != NULL) { + NSString *errorMessage = [NSString stringWithFormat:@"Failed to make directory %@ with authorization.", url.path.lastPathComponent]; + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: errorMessage, NSUnderlyingErrorKey: executeError }]; + } } + return success; } @@ -789,7 +876,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { desiredURL = [directoryURL URLByAppendingPathComponent:[preferredName stringByAppendingFormat:@" (%lu)", (unsigned long)++tagIndex]]; } - return [self _makeDirectoryAtURL:desiredURL error:error] ? desiredURL : nil; + return [self makeDirectoryAtURL:desiredURL error:error] ? desiredURL : nil; } - (BOOL)removeItemAtURL:(NSURL *)url error:(NSError * __autoreleasing *)error @@ -813,10 +900,6 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { return NO; } - if (![self _acquireAuthorizationWithError:error]) { - return NO; - } - char path[PATH_MAX] = {0}; if (![url.path getFileSystemRepresentation:path maxLength:sizeof(path)]) { if (error != NULL) { @@ -824,11 +907,14 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } return NO; } + + NSError *executeError = nil; + BOOL success = [self _authorizeAndExecuteCommand:SUFileOpRemoveCommand sourcePath:path destinationPath:NULL error:&executeError]; - BOOL success = AuthorizationExecuteWithPrivilegesAndWait(_auth, "/bin/rm", kAuthorizationFlagDefaults, (char *[]){ "-rf", "--", path, NULL }); if (!success && error != NULL) { - *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to remove %@ with authentication.", url.path.lastPathComponent] }]; + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to remove %@ with authentication.", url.path.lastPathComponent], NSUnderlyingErrorKey: executeError }]; } + return success; } @@ -903,7 +989,10 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { if (canUseNewTrashAPI) { NSError *trashError = nil; +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wpartial-availability" success = [_fileManager trashItemAtURL:tempItemURL resultingItemURL:NULL error:&trashError]; +#pragma clang diagnostic pop if (!success && error != NULL) { *error = trashError; } @@ -914,6 +1003,34 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { return success; } +// Unlike other methods, authorization is required to execute this method successfully +- (BOOL)executePackageAtURL:(NSURL *)packageURL error:(NSError * __autoreleasing *)error +{ + if (![self _itemExistsAtURL:packageURL]) { + if (error != NULL) { + *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileNoSuchFileError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to execute package %@ because the file does not exist.", packageURL.path.lastPathComponent] }]; + } + return NO; + } + + char path[PATH_MAX] = {0}; + if (![packageURL.path getFileSystemRepresentation:path maxLength:sizeof(path)]) { + if (error != NULL) { + *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Package to execute (%@) cannot be represented as a valid file name.", packageURL.path.lastPathComponent] }]; + } + return NO; + } + + NSError *executeError = nil; + BOOL success = [self _authorizeAndExecuteCommand:SUFileOpInstallCommand sourcePath:path destinationPath:NULL error:&executeError]; + + if (!success && error != NULL) { + NSString* errorMessage = @"Failed to execute package installer."; + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{NSLocalizedDescriptionKey: errorMessage, NSUnderlyingErrorKey: executeError}]; + } + return success; +} + @end #pragma clang diagnostic pop diff --git a/Sparkle/SUGuidedPackageInstaller.h b/Sparkle/SUGuidedPackageInstaller.h index 292f14af..4a9fc74b 100644 --- a/Sparkle/SUGuidedPackageInstaller.h +++ b/Sparkle/SUGuidedPackageInstaller.h @@ -11,7 +11,7 @@ A guided installation allows Sparkle to download and install a package (pkg) or multi-package (mpkg) without user interaction. -The installer package is installed using Mac OS X's built-in command line installer, `/usr/sbin/installer`. No installation interface is shown to the user. +The installer package is installed using macOS's built-in command line installer, `/usr/sbin/installer`. No installation interface is shown to the user. A guided installation can be started by applications other than the application being replaced. This is particularly useful where helper applications or agents are used. @@ -29,7 +29,7 @@ A guided installation can be started by applications other than the application @interface SUGuidedPackageInstaller : SUInstaller /*! Perform the guided installation */ -+ (void)performInstallationToPath:(NSString *)path fromPath:(NSString *)installerGuide host:(SUHost *)host versionComparator:(id)comparator completionHandler:(void (^)(NSError *))completionHandler; ++ (void)performInstallationToPath:(NSString *)path fromPath:(NSString *)installerGuide host:(SUHost *)host fileOperationToolPath:(NSString *)fileOperationToolPath versionComparator:(id)comparator completionHandler:(void (^)(NSError *))completionHandler; @end #endif diff --git a/Sparkle/SUGuidedPackageInstaller.m b/Sparkle/SUGuidedPackageInstaller.m index c2d25de2..97decfa2 100644 --- a/Sparkle/SUGuidedPackageInstaller.m +++ b/Sparkle/SUGuidedPackageInstaller.m @@ -6,137 +6,27 @@ // Copyright 2010 Dragon Systems Software Limited. All rights reserved. // -#import -#import - #import "SUGuidedPackageInstaller.h" - -static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authorization, const char* executablePath, AuthorizationFlags options, char* const* arguments) -{ - sig_t oldSigChildHandler = signal(SIGCHLD, SIG_DFL); - BOOL returnValue = YES; - -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdeprecated-declarations" - /* AuthorizationExecuteWithPrivileges used to support 10.4+; should be replaced with XPC or external process */ - if (AuthorizationExecuteWithPrivileges(authorization, executablePath, options, arguments, NULL) == errAuthorizationSuccess) -#pragma clang diagnostic pop - { - int status = 0; - pid_t pid = wait(&status); - if (pid == -1 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) - returnValue = NO; - } - else - returnValue = NO; - - signal(SIGCHLD, oldSigChildHandler); - return returnValue; -} - -@implementation SUGuidedPackageInstaller (SUGuidedPackageInstallerAuthentication) - -+ (AuthorizationRef)authorizationForExecutable:(NSString*)executablePath -{ - SUParameterAssert(executablePath); - - // Get authorization using advice in Apple's Technical Q&A1172 - - // ...create authorization without specific rights - AuthorizationRef auth = NULL; - OSStatus validAuth = AuthorizationCreate(NULL, - kAuthorizationEmptyEnvironment, - kAuthorizationFlagDefaults, - &auth); - // ...then extend authorization with desired rights - if ((validAuth == errAuthorizationSuccess) && - (auth != NULL)) - { - char executableFileSystemRepresentation[PATH_MAX]; - [executablePath getFileSystemRepresentation:executableFileSystemRepresentation maxLength:sizeof(executableFileSystemRepresentation)]; - - // Prepare a right allowing script to execute with privileges - AuthorizationItem right = { - .name = kAuthorizationRightExecute, - .value = executableFileSystemRepresentation, - .valueLength = strlen(executableFileSystemRepresentation), - }; - - // Package up the single right - AuthorizationRights rights; - memset(&rights,0,sizeof(rights)); - rights.count = 1; - rights.items = &right; - - // Extend rights to run script - validAuth = AuthorizationCopyRights(auth, - &rights, - kAuthorizationEmptyEnvironment, - (AuthorizationFlags) - (kAuthorizationFlagPreAuthorize | - kAuthorizationFlagExtendRights | - kAuthorizationFlagInteractionAllowed), - NULL); - if (validAuth != errAuthorizationSuccess) - { - // Error, clean up authorization - (void) AuthorizationFree(auth,kAuthorizationFlagDefaults); - auth = NULL; - } - } - - return auth; -} - -@end +#import "SUFileManager.h" @implementation SUGuidedPackageInstaller -+ (void)performInstallationToPath:(NSString *)destinationPath fromPath:(NSString *)packagePath host:(SUHost *)__unused host versionComparator:(id)__unused comparator completionHandler:(void (^)(NSError *))completionHandler ++ (void)performInstallationToPath:(NSString *)destinationPath fromPath:(NSString *)packagePath host:(SUHost *)__unused host fileOperationToolPath:(NSString *)fileOperationToolPath versionComparator:(id)__unused comparator completionHandler:(void (^)(NSError *))completionHandler { SUParameterAssert(packagePath); - + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ - - // Preflight - NSString* installerPath = @"/usr/sbin/installer"; // Mac OS X 10.2+ command line installer tool - NSError* error = nil; - - // Create authorization for installer executable - BOOL validInstallation = NO; - AuthorizationRef auth = [self authorizationForExecutable:installerPath]; - if (auth != NULL) - { - char pathBuffer[PATH_MAX] = {0}; - [packagePath getFileSystemRepresentation:pathBuffer maxLength:sizeof(pathBuffer)]; - - // Permission was granted to execute the installer with privileges - char * const arguments[] = { - "-pkg", - pathBuffer, - "-target", - "/", - NULL - }; - validInstallation = AuthorizationExecuteWithPrivilegesAndWait(auth, - [installerPath fileSystemRepresentation], - kAuthorizationFlagDefaults, - arguments); - // TODO: wait for communications pipe to close via fileno & CFSocketCreateWithNative - AuthorizationFree(auth,kAuthorizationFlagDefaults); - } - else - { - NSString* errorMessage = [NSString stringWithFormat:@"Sparkle Updater: Script authorization denied."]; - error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:[NSDictionary dictionaryWithObject:errorMessage forKey:NSLocalizedDescriptionKey]]; - } - + SUFileManager *fileManager = [SUFileManager fileManagerWithAuthorizationToolPath:fileOperationToolPath]; + + NSError *error = nil; + BOOL validInstallation = [fileManager executePackageAtURL:[NSURL fileURLWithPath:packagePath] error:&error]; + dispatch_async(dispatch_get_main_queue(), ^{ [self finishInstallationToPath:destinationPath withResult:validInstallation error:error completionHandler:completionHandler]; - + }); }); } diff --git a/Sparkle/SUHost.h b/Sparkle/SUHost.h index 5f73f955..56fa7d18 100644 --- a/Sparkle/SUHost.h +++ b/Sparkle/SUHost.h @@ -26,7 +26,6 @@ typedef struct { - (instancetype)initWithBundle:(NSBundle *)aBundle; @property (readonly, copy) NSString *bundlePath; @property (readonly) BOOL allowsAutomaticUpdates; -@property (readonly, copy) NSString *appCachePath; @property (readonly, copy) NSString *installationPath; @property (readonly, copy) NSString *name; @property (readonly, copy) NSString *version; @@ -35,6 +34,7 @@ typedef struct { @property (getter=isRunningOnReadOnlyVolume, readonly) BOOL runningOnReadOnlyVolume; @property (getter=isBackgroundApplication, readonly) BOOL backgroundApplication; @property (readonly, copy) NSString *publicDSAKey; +@property (readonly, nonatomic, copy) NSString *publicDSAKeyFileKey; @property (readonly, copy) NSArray *systemProfile; - (id)objectForInfoDictionaryKey:(NSString *)key; diff --git a/Sparkle/SUHost.m b/Sparkle/SUHost.m index c49ba368..d941e066 100644 --- a/Sparkle/SUHost.m +++ b/Sparkle/SUHost.m @@ -11,6 +11,7 @@ #import "SUSystemProfiler.h" #include // For statfs for isRunningOnReadOnlyVolume #import "SULog.h" +#import "SUFileManager.h" #if __MAC_OS_X_VERSION_MAX_ALLOWED < 101000 @interface NSProcessInfo () @@ -71,29 +72,37 @@ } // Can we automatically update in the background without bugging the user (e.g, with a administrator password prompt)? - return [[NSFileManager defaultManager] isWritableFileAtPath:self.bundlePath]; -} - -- (NSString *)appCachePath -{ - NSArray *cachePaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); - NSString *cachePath = nil; - if ([cachePaths count]) { - cachePath = cachePaths[0]; + // Note it's very well possible to have the bundle be writable but not be able to write into the parent directory + // And if the bundle isn't writable, but we can write into the parent directory, we will still need to authorize to replace it + NSString *bundlePath = [self bundlePath]; + if (![[NSFileManager defaultManager] isWritableFileAtPath:bundlePath.stringByDeletingLastPathComponent] || ![[NSFileManager defaultManager] isWritableFileAtPath:bundlePath]) { + return NO; } - if (!cachePath) { - SULog(@"Failed to find user's cache directory! Using system default"); - cachePath = NSTemporaryDirectory(); + + // Just because we have writability access does not mean we can set the correct owner/group silently + // Test if we can set the owner/group on a temporarily created file + // If we can, then we can probably perform an update without authorization + // One place where this matters is if you copy and run an app from /tmp/ + + NSString *tempFilename = @"permission_test" ; + + SUFileManager *suFileManager = [SUFileManager defaultManager]; + NSURL *tempDirectoryURL = [suFileManager makeTemporaryDirectoryWithPreferredName:tempFilename appropriateForDirectoryURL:[NSURL fileURLWithPath:NSTemporaryDirectory()] error:NULL]; + + if (tempDirectoryURL == nil) { + // I don't imagine this ever happening but in case it does, requesting authorization may be the better option + return NO; } - - NSString *name = [self.bundle bundleIdentifier]; - if (!name) { - name = [self name]; - } - - cachePath = [cachePath stringByAppendingPathComponent:name]; - cachePath = [cachePath stringByAppendingPathComponent:@"Sparkle"]; - return cachePath; + + NSURL *tempFileURL = [tempDirectoryURL URLByAppendingPathComponent:tempFilename]; + + BOOL changeOwnerAndGroupSuccess = + [[NSData data] writeToURL:tempFileURL atomically:NO] && + [suFileManager changeOwnerAndGroupOfItemAtRootURL:tempFileURL toMatchURL:self.bundle.bundleURL error:NULL]; + + [suFileManager removeItemAtURL:tempDirectoryURL error:NULL]; + + return changeOwnerAndGroupSuccess; } - (NSString *)installationPath @@ -147,11 +156,11 @@ { // Cache the application icon. NSString *iconPath = [self.bundle pathForResource:[self.bundle objectForInfoDictionaryKey:@"CFBundleIconFile"] ofType:@"icns"]; - // According to the OS X docs, "CFBundleIconFile - This key identifies the file containing + // According to the macOS docs, "CFBundleIconFile - This key identifies the file containing // the icon for the bundle. The filename you specify does not need to include the .icns // extension, although it may." // - // However, if it *does* include the '.icns' the above method fails (tested on OS X 10.3.9) so we'll also try: + // However, if it *does* include the '.icns' the above method fails (tested on macOS 10.3.9) so we'll also try: if (!iconPath) { iconPath = [self.bundle pathForResource:[self.bundle objectForInfoDictionaryKey:@"CFBundleIconFile"] ofType:nil]; } @@ -187,7 +196,7 @@ } // More likely, we've got a reference to a Resources file by filename: - NSString *keyFilename = [self objectForInfoDictionaryKey:SUPublicDSAKeyFileKey]; + NSString *keyFilename = [self publicDSAKeyFileKey]; if (!keyFilename) { return nil; } @@ -199,6 +208,11 @@ return [NSString stringWithContentsOfFile:keyPath encoding:NSASCIIStringEncoding error:nil]; } +- (NSString * __nullable)publicDSAKeyFileKey +{ + return [self objectForInfoDictionaryKey:SUPublicDSAKeyFileKey]; +} + - (NSArray *)systemProfile { return [[SUSystemProfiler sharedSystemProfiler] systemProfileArrayForHost:self]; diff --git a/Sparkle/SUInstaller.h b/Sparkle/SUInstaller.h index 4afe1cbe..0bb08c11 100644 --- a/Sparkle/SUInstaller.h +++ b/Sparkle/SUInstaller.h @@ -16,7 +16,7 @@ @interface SUInstaller : NSObject + (NSString *)installSourcePathInUpdateFolder:(NSString *)inUpdateFolder forHost:(SUHost *)host isPackage:(BOOL *)isPackagePtr isGuided:(BOOL *)isGuidedPtr; -+ (void)installFromUpdateFolder:(NSString *)updateFolder overHost:(SUHost *)host installationPath:(NSString *)installationPath versionComparator:(id)comparator completionHandler:(void (^)(NSError *))completionHandler; ++ (void)installFromUpdateFolder:(NSString *)inUpdateFolder overHost:(SUHost *)host installationPath:(NSString *)installationPath fileOperationToolPath:(NSString *)fileOperationToolPath versionComparator:(id)comparator completionHandler:(void (^)(NSError *))completionHandler; + (void)finishInstallationToPath:(NSString *)installationPath withResult:(BOOL)result error:(NSError *)error completionHandler:(void (^)(NSError *))completionHandler; @end diff --git a/Sparkle/SUInstaller.m b/Sparkle/SUInstaller.m index 400f9597..c96ffadd 100644 --- a/Sparkle/SUInstaller.m +++ b/Sparkle/SUInstaller.m @@ -103,7 +103,7 @@ return newAppDownloadPath; } -+ (void)installFromUpdateFolder:(NSString *)inUpdateFolder overHost:(SUHost *)host installationPath:(NSString *)installationPath versionComparator:(id)comparator completionHandler:(void (^)(NSError *))completionHandler ++ (void)installFromUpdateFolder:(NSString *)inUpdateFolder overHost:(SUHost *)host installationPath:(NSString *)installationPath fileOperationToolPath:(NSString *)fileOperationToolPath versionComparator:(id)comparator completionHandler:(void (^)(NSError *))completionHandler { BOOL isPackage = NO; BOOL isGuided = NO; @@ -113,39 +113,18 @@ [self finishInstallationToPath:installationPath withResult:NO error:[NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingUpdateError userInfo:@{ NSLocalizedDescriptionKey: @"Couldn't find an appropriate update in the downloaded package." }] completionHandler:completionHandler]; } else { if (isPackage && isGuided) { - [SUGuidedPackageInstaller performInstallationToPath:installationPath fromPath:newAppDownloadPath host:host versionComparator:comparator completionHandler:completionHandler]; + [SUGuidedPackageInstaller performInstallationToPath:installationPath fromPath:newAppDownloadPath host:host fileOperationToolPath:fileOperationToolPath versionComparator:comparator completionHandler:completionHandler]; } else if (isPackage) { - [SUPackageInstaller performInstallationToPath:installationPath fromPath:newAppDownloadPath host:host versionComparator:comparator completionHandler:completionHandler]; + [SUPackageInstaller performInstallationToPath:installationPath fromPath:newAppDownloadPath host:host fileOperationToolPath:fileOperationToolPath versionComparator:comparator completionHandler:completionHandler]; } else { - [SUPlainInstaller performInstallationToPath:installationPath fromPath:newAppDownloadPath host:host versionComparator:comparator completionHandler:completionHandler]; + [SUPlainInstaller performInstallationToPath:installationPath fromPath:newAppDownloadPath host:host fileOperationToolPath:fileOperationToolPath versionComparator:comparator completionHandler:completionHandler]; } } } -+ (void)mdimportInstallationPath:(NSString *)installationPath -{ - // *** GETS CALLED ON NON-MAIN THREAD! - - SULog(@"mdimporting"); - - NSTask *mdimport = [[NSTask alloc] init]; - [mdimport setLaunchPath:@"/usr/bin/mdimport"]; - [mdimport setArguments:@[installationPath]]; - @try { - [mdimport launch]; - [mdimport waitUntilExit]; - } - @catch (NSException *launchException) - { - // No big deal. - SULog(@"Error: %@", [launchException description]); - } -} - -+ (void)finishInstallationToPath:(NSString *)installationPath withResult:(BOOL)result error:(NSError *)error completionHandler:(void (^)(NSError *))completionHandler ++ (void)finishInstallationToPath:(NSString *)__unused installationPath withResult:(BOOL)result error:(NSError *)error completionHandler:(void (^)(NSError *))completionHandler { if (result) { - [self mdimportInstallationPath:installationPath]; dispatch_async(dispatch_get_main_queue(), ^{ completionHandler(nil); }); diff --git a/Sparkle/SUOperatingSystem.m b/Sparkle/SUOperatingSystem.m index d411b4dd..5e173d10 100644 --- a/Sparkle/SUOperatingSystem.m +++ b/Sparkle/SUOperatingSystem.m @@ -20,15 +20,21 @@ { NSOperatingSystemVersion version = { 0, 0, 0 }; NSURL *coreServices = [[NSFileManager defaultManager] URLForDirectory:NSCoreServiceDirectory inDomain:NSSystemDomainMask appropriateForURL:nil create:NO error:nil]; - NSURL* systemVersionPlistUrl = [coreServices URLByAppendingPathComponent:@"SystemVersion.plist"]; - NSArray *components = [[NSDictionary dictionaryWithContentsOfURL:systemVersionPlistUrl][@"ProductVersion"] componentsSeparatedByString:@"."]; - version.majorVersion = components.count > 0 ? [components[0] integerValue] : 0; - version.minorVersion = components.count > 1 ? [components[1] integerValue] : 0; - version.patchVersion = components.count > 2 ? [components[2] integerValue] : 0; + NSURL *url = [coreServices URLByAppendingPathComponent:@"SystemVersion.plist"]; + assert(url != nil); + NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfURL:url]; + NSArray *components = [ [dictionary objectForKey: @"ProductVersion"] componentsSeparatedByString:@"."]; + version.majorVersion = components.count > 0 ? [ [components objectAtIndex:0] integerValue] : 0; + version.minorVersion = components.count > 1 ? [ [components objectAtIndex:1] integerValue] : 0; + version.patchVersion = components.count > 2 ? [ [components objectAtIndex:2] integerValue] : 0; return version; } #endif + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wpartial-availability" return [[NSProcessInfo processInfo] operatingSystemVersion]; +#pragma clang diagnostic pop } + (BOOL)isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion)version diff --git a/Sparkle/SUPackageInstaller.m b/Sparkle/SUPackageInstaller.m index 64637433..2a38db44 100644 --- a/Sparkle/SUPackageInstaller.m +++ b/Sparkle/SUPackageInstaller.m @@ -12,7 +12,7 @@ @implementation SUPackageInstaller -+ (void)performInstallationToPath:(NSString *)installationPath fromPath:(NSString *)path host:(SUHost *)__unused host versionComparator:(id)__unused comparator completionHandler:(void (^)(NSError *))completionHandler ++ (void)performInstallationToPath:(NSString *)installationPath fromPath:(NSString *)path host:(SUHost *)__unused host fileOperationToolPath:(NSString *)__unused fileOperationToolPath versionComparator:(id)__unused comparator completionHandler:(void (^)(NSError *))completionHandler { // Run installer using the "open" command to ensure it is launched in front of current application. // -W = wait until the app has quit. diff --git a/Sparkle/SUPipedUnarchiver.m b/Sparkle/SUPipedUnarchiver.m index 7317143d..0b0157c3 100644 --- a/Sparkle/SUPipedUnarchiver.m +++ b/Sparkle/SUPipedUnarchiver.m @@ -30,7 +30,7 @@ NSString *lastPathComponent = [path lastPathComponent]; for (NSString *currentType in typeSelectorDictionary) { - NSString *value = typeSelectorDictionary[currentType]; + NSString *value = [typeSelectorDictionary objectForKey:currentType]; assert(value); if ([currentType length] > [lastPathComponent length]) continue; @@ -41,6 +41,11 @@ return NULL; } ++ (BOOL)unsafeIfArchiveIsNotValidated +{ + return NO; +} + - (void)start { [NSThread detachNewThreadSelector:[[self class] selectorConformingToTypeOfPath:self.archivePath] toTarget:self withObject:nil]; @@ -62,7 +67,8 @@ SULog(@"Extracting using '%@' '%@' < '%@' '%@'", command, [args componentsJoinedByString:@"' '"], self.archivePath, destination); // Get the file size. - NSUInteger expectedLength = [[[NSFileManager defaultManager] attributesOfItemAtPath:self.archivePath error:nil][NSFileSize] unsignedIntegerValue]; + NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:self.archivePath error:nil]; + NSUInteger expectedLength = [[attributes objectForKey:NSFileSize] unsignedIntegerValue]; if (expectedLength > 0) { NSFileHandle *archiveInput = [NSFileHandle fileHandleForReadingAtPath:self.archivePath]; diff --git a/Sparkle/SUPlainInstaller.h b/Sparkle/SUPlainInstaller.h index 1119aaab..5bebdee8 100644 --- a/Sparkle/SUPlainInstaller.h +++ b/Sparkle/SUPlainInstaller.h @@ -23,7 +23,7 @@ @interface SUPlainInstaller : SUInstaller -+ (void)performInstallationToPath:(NSString *)installationPath fromPath:(NSString *)path host:(SUHost *)host versionComparator:(id)comparator completionHandler:(void (^)(NSError *))completionHandler; ++ (void)performInstallationToPath:(NSString *)installationPath fromPath:(NSString *)path host:(SUHost *)host fileOperationToolPath:(NSString *)fileOperationToolPath versionComparator:(id)comparator completionHandler:(void (^)(NSError *))completionHandler; @end diff --git a/Sparkle/SUPlainInstaller.m b/Sparkle/SUPlainInstaller.m index 70a7ded9..d11e3bb8 100644 --- a/Sparkle/SUPlainInstaller.m +++ b/Sparkle/SUPlainInstaller.m @@ -31,7 +31,7 @@ return trimmedVersion.length > 0 ? trimmedVersion : nil; } -+ (BOOL)performInstallationToURL:(NSURL *)installationURL fromUpdateAtURL:(NSURL *)newURL withHost:(SUHost *)host error:(NSError * __autoreleasing *)error ++ (BOOL)performInstallationToURL:(NSURL *)installationURL fromUpdateAtURL:(NSURL *)newURL withHost:(SUHost *)host fileOperationToolPath:(NSString *)fileOperationToolPath error:(NSError * __autoreleasing *)error { if (installationURL == nil || newURL == nil) { // this really shouldn't happen but just in case @@ -42,7 +42,7 @@ return NO; } - SUFileManager *fileManager = [SUFileManager fileManagerAllowingAuthorization:YES]; + SUFileManager *fileManager = [SUFileManager fileManagerWithAuthorizationToolPath:fileOperationToolPath]; // Create a temporary directory for our new app that resides on our destination's volume NSURL *tempNewDirectoryURL = [fileManager makeTemporaryDirectoryWithPreferredName:[installationURL.lastPathComponent.stringByDeletingPathExtension stringByAppendingString:@" (Incomplete Update)"] appropriateForDirectoryURL:installationURL.URLByDeletingLastPathComponent error:error]; @@ -139,20 +139,23 @@ return NO; } + // From here on out, we don't really need to bring up authorization if we haven't done so prior + SUFileManager *constrainedFileManager = [fileManager fileManagerByPreservingAuthorizationRights]; + // Cleanup: move the old app to the trash NSError *trashError = nil; - if (![fileManager moveItemAtURLToTrash:oldTempURL error:&trashError]) { + if (![constrainedFileManager moveItemAtURLToTrash:oldTempURL error:&trashError]) { SULog(@"Failed to move %@ to trash with error %@", oldTempURL, trashError); } - [fileManager removeItemAtURL:tempOldDirectoryURL error:NULL]; + [constrainedFileManager removeItemAtURL:tempOldDirectoryURL error:NULL]; - [fileManager removeItemAtURL:tempNewDirectoryURL error:NULL]; + [constrainedFileManager removeItemAtURL:tempNewDirectoryURL error:NULL]; return YES; } -+ (void)performInstallationToPath:(NSString *)installationPath fromPath:(NSString *)path host:(SUHost *)host versionComparator:(id)comparator completionHandler:(void (^)(NSError *))completionHandler ++ (void)performInstallationToPath:(NSString *)installationPath fromPath:(NSString *)path host:(SUHost *)host fileOperationToolPath:(NSString *)fileOperationToolPath versionComparator:(id)comparator completionHandler:(void (^)(NSError *))completionHandler { SUParameterAssert(host); @@ -161,7 +164,7 @@ // Prevent malicious downgrades if (!allowDowngrades) { if ([comparator compareVersion:[host version] toVersion:[[NSBundle bundleWithPath:path] objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleVersionKey]] == NSOrderedDescending) { - NSString *errorMessage = [NSString stringWithFormat:@"Sparkle Updater: Possible attack in progress! Attempting to \"upgrade\" from %@ to %@. Aborting update.", [host version], [[NSBundle bundleWithPath:path] objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleVersionKey]]; + NSString *errorMessage = [NSString stringWithFormat:@"For security reasons, updates that downgrade version of the application are not allowed. Refusing to downgrade app from version %@ to %@. Aborting update.", [host version], [[NSBundle bundleWithPath:path] objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleVersionKey]]; NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUDowngradeError userInfo:@{ NSLocalizedDescriptionKey: errorMessage }]; [self finishInstallationToPath:installationPath withResult:NO error:error completionHandler:completionHandler]; return; @@ -170,7 +173,7 @@ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSError *error = nil; - BOOL result = [self performInstallationToURL:[NSURL fileURLWithPath:installationPath] fromUpdateAtURL:[NSURL fileURLWithPath:path] withHost:host error:&error]; + BOOL result = [self performInstallationToURL:[NSURL fileURLWithPath:installationPath] fromUpdateAtURL:[NSURL fileURLWithPath:path] withHost:host fileOperationToolPath:fileOperationToolPath error:&error]; dispatch_async(dispatch_get_main_queue(), ^{ [self finishInstallationToPath:installationPath withResult:result error:error completionHandler:completionHandler]; diff --git a/Sparkle/SUStandardVersionComparator.h b/Sparkle/SUStandardVersionComparator.h index d7f2a48c..2eaee42f 100644 --- a/Sparkle/SUStandardVersionComparator.h +++ b/Sparkle/SUStandardVersionComparator.h @@ -9,7 +9,11 @@ #ifndef SUSTANDARDVERSIONCOMPARATOR_H #define SUSTANDARDVERSIONCOMPARATOR_H +#if __has_feature(modules) +@import Foundation; +#else #import +#endif #import "SUExport.h" #import "SUVersionComparisonProtocol.h" diff --git a/Sparkle/SUStandardVersionComparator.m b/Sparkle/SUStandardVersionComparator.m index b7c876a5..415c3074 100644 --- a/Sparkle/SUStandardVersionComparator.m +++ b/Sparkle/SUStandardVersionComparator.m @@ -91,8 +91,8 @@ typedef NS_ENUM(NSInteger, SUCharacterType) { n = MIN([partsA count], [partsB count]); for (i = 0; i < n; ++i) { - partA = partsA[i]; - partB = partsB[i]; + partA = [partsA objectAtIndex:i]; + partB = [partsB objectAtIndex:i]; typeA = [self typeOfCharacter:partA]; typeB = [self typeOfCharacter:partB]; @@ -142,11 +142,11 @@ typedef NS_ENUM(NSInteger, SUCharacterType) { NSComparisonResult shorterResult, largerResult; if ([partsA count] > [partsB count]) { - missingPart = partsA[n]; + missingPart = [partsA objectAtIndex:n]; shorterResult = NSOrderedAscending; largerResult = NSOrderedDescending; } else { - missingPart = partsB[n]; + missingPart = [partsB objectAtIndex:n]; shorterResult = NSOrderedDescending; largerResult = NSOrderedAscending; } diff --git a/Sparkle/SUStatus.xib b/Sparkle/SUStatus.xib index fca3d15d..d225d6c2 100644 --- a/Sparkle/SUStatus.xib +++ b/Sparkle/SUStatus.xib @@ -10,6 +10,7 @@ + diff --git a/Sparkle/SUStatusController.h b/Sparkle/SUStatusController.h index 8a279258..03407c87 100644 --- a/Sparkle/SUStatusController.h +++ b/Sparkle/SUStatusController.h @@ -15,6 +15,7 @@ @interface SUStatusController : SUWindowController @property (weak) IBOutlet NSButton *actionButton; @property (weak) IBOutlet NSProgressIndicator *progressBar; +@property (weak) IBOutlet NSTextField *statusTextField; @property (copy) NSString *statusText; @property double progressValue; diff --git a/Sparkle/SUStatusController.m b/Sparkle/SUStatusController.m index 290bfeae..23363248 100644 --- a/Sparkle/SUStatusController.m +++ b/Sparkle/SUStatusController.m @@ -11,6 +11,7 @@ #import "SUAppcast.h" #import "SUAppcastItem.h" #import "SUVersionComparisonProtocol.h" +#import "SUOperatingSystem.h" #import "SUStatusController.h" #import "SUHost.h" @@ -28,6 +29,7 @@ @synthesize host; @synthesize actionButton; @synthesize progressBar; +@synthesize statusTextField; - (instancetype)initWithHost:(SUHost *)aHost { @@ -51,6 +53,13 @@ [[self window] center]; [[self window] setFrameAutosaveName:@"SUStatusFrame"]; [self.progressBar setUsesThreadedAnimation:YES]; + + if ([SUOperatingSystem isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){10, 11, 0}]) { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wpartial-availability" + [self.statusTextField setFont:[NSFont monospacedDigitSystemFontOfSize:0 weight:NSFontWeightRegular]]; +#pragma clang diagnostic pop + } } - (NSString *)windowTitle diff --git a/Sparkle/SUSystemProfiler.m b/Sparkle/SUSystemProfiler.m index 230c808f..4071da6b 100644 --- a/Sparkle/SUSystemProfiler.m +++ b/Sparkle/SUSystemProfiler.m @@ -115,7 +115,7 @@ static NSString *const SUSystemProfilerPreferredLanguageKey = @"lang"; error = sysctlbyname("hw.model", cpuModel, &length, NULL, 0); if (error == 0) { NSString *rawModelName = @(cpuModel); - NSString *visibleModelName = modelTranslation[rawModelName]; + NSString *visibleModelName = [modelTranslation objectForKey:rawModelName]; if (visibleModelName == nil) { visibleModelName = rawModelName; } @@ -135,7 +135,7 @@ static NSString *const SUSystemProfilerPreferredLanguageKey = @"lang"; NSUserDefaults *defs = [NSUserDefaults standardUserDefaults]; NSArray *languages = [defs objectForKey:@"AppleLanguages"]; if ([languages count] > 0) { - [profileArray addObject:[NSDictionary dictionaryWithObjects:@[SUSystemProfilerPreferredLanguageKey, @"Preferred Language", languages[0], languages[0]] forKeys:profileDictKeys]]; + [profileArray addObject:[NSDictionary dictionaryWithObjects:@[SUSystemProfilerPreferredLanguageKey, @"Preferred Language", [languages objectAtIndex:0], [languages objectAtIndex:0]] forKeys:profileDictKeys]]; } // Application sending the request diff --git a/Sparkle/SUUIBasedUpdateDriver.m b/Sparkle/SUUIBasedUpdateDriver.m index a3b25d0b..0a0ae572 100644 --- a/Sparkle/SUUIBasedUpdateDriver.m +++ b/Sparkle/SUUIBasedUpdateDriver.m @@ -98,8 +98,9 @@ alert.informativeText = [NSString stringWithFormat:SULocalizedString(@"%@ %@ is currently the newest version available.", nil), [self.host name], [self.host displayVersion]]; [alert addButtonWithTitle:SULocalizedString(@"OK", nil)]; [self showAlert:alert]; - [self abortUpdate]; } + + [self abortUpdate]; } - (void)applicationDidBecomeActive:(NSNotification *)__unused aNotification @@ -114,10 +115,6 @@ [self.host setObject:nil forUserDefaultsKey:SUSkippedVersionKey]; switch (choice) { case SUInstallUpdateChoice: - self.statusController = [[SUStatusController alloc] initWithHost:self.host]; - [self.statusController beginActionWithTitle:SULocalizedString(@"Downloading update...", @"Take care not to overflow the status window.") maxProgressValue:0.0 statusText:nil]; - [self.statusController setButtonTitle:SULocalizedString(@"Cancel", nil) target:self action:@selector(cancelDownload:) isDefault:NO]; - [self.statusController showWindow:self]; [self downloadUpdate]; break; @@ -137,6 +134,25 @@ } } +- (void)downloadUpdate +{ + BOOL createdStatusController = NO; + if (self.statusController == nil) { + self.statusController = [[SUStatusController alloc] initWithHost:self.host]; + createdStatusController = YES; + } + + [self.statusController beginActionWithTitle:SULocalizedString(@"Downloading update...", @"Take care not to overflow the status window.") maxProgressValue:0.0 statusText:nil]; + [self.statusController setButtonTitle:SULocalizedString(@"Cancel", nil) target:self action:@selector(cancelDownload:) isDefault:NO]; + [self.statusController setButtonEnabled:YES]; + + if (createdStatusController) { + [self.statusController showWindow:self]; + } + + [super downloadUpdate]; +} + - (void)download:(NSURLDownload *)__unused download didReceiveResponse:(NSURLResponse *)response { [self.statusController setMaxProgressValue:[response expectedContentLength]]; @@ -164,8 +180,12 @@ SULocalizedString(@"GB", @"the unit for gigabytes")]; } - return [NSByteCountFormatter stringFromByteCount:value - countStyle:NSByteCountFormatterCountStyleFile]; +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wpartial-availability" + NSByteCountFormatter *formatter = [[NSByteCountFormatter alloc] init]; + [formatter setZeroPadsFractionDigits:YES]; + return [formatter stringFromByteCount:value]; +#pragma clang diagnostic pop } - (void)download:(NSURLDownload *)__unused download didReceiveDataOfLength:(NSUInteger)length diff --git a/Sparkle/SUUnarchiver.h b/Sparkle/SUUnarchiver.h index ccd5611d..e2f79f04 100644 --- a/Sparkle/SUUnarchiver.h +++ b/Sparkle/SUUnarchiver.h @@ -23,7 +23,10 @@ + (SUUnarchiver *)unarchiverForPath:(NSString *)path updatingHostBundlePath:(NSString *)host withPassword:(NSString *)decryptionPassword; ++ (BOOL)unsafeIfArchiveIsNotValidated; + - (void)start; + @end @protocol SUUnarchiverDelegate diff --git a/Sparkle/SUUnarchiver.m b/Sparkle/SUUnarchiver.m index e887f4ca..b12d0648 100644 --- a/Sparkle/SUUnarchiver.m +++ b/Sparkle/SUUnarchiver.m @@ -55,6 +55,11 @@ return NO; } ++ (BOOL)unsafeIfArchiveIsNotValidated +{ + return NO; +} + - (void)notifyDelegateOfProgress:(double)progress { if ([self.delegate respondsToSelector:@selector(unarchiver:extractedProgress:)]) { diff --git a/Sparkle/SUUpdateAlert.m b/Sparkle/SUUpdateAlert.m index 9a6b649f..3589ffd3 100644 --- a/Sparkle/SUUpdateAlert.m +++ b/Sparkle/SUUpdateAlert.m @@ -122,11 +122,13 @@ self.releaseNotesView.preferencesIdentifier = SUBundleIdentifier; WebPreferences *prefs = [self.releaseNotesView preferences]; prefs.plugInsEnabled = NO; + prefs.javaEnabled = NO; + prefs.javaScriptEnabled = [self.host boolForInfoDictionaryKey:SUEnableJavaScriptKey]; self.releaseNotesView.frameLoadDelegate = self; self.releaseNotesView.policyDelegate = self; // Set the default font - // "-apple-system-font" is a reference to the system UI font on OS X. "-apple-system" is the new recommended token, but for backward compatibility we can't use it. + // "-apple-system-font" is a reference to the system UI font. "-apple-system" is the new recommended token, but for backward compatibility we can't use it. prefs.standardFontFamily = @"-apple-system-font"; prefs.defaultFontSize = (int)[NSFont systemFontSize]; @@ -258,8 +260,7 @@ { NSURL *requestURL = request.URL; NSString *scheme = requestURL.scheme; - NSString *url = requestURL.absoluteString; - BOOL whitelistedSafe = [@"http" isEqualToString:scheme] || [@"https" isEqualToString:scheme] || [@"about:blank" isEqualToString:url]; + BOOL whitelistedSafe = [scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"] || [requestURL.absoluteString isEqualToString:@"about:blank"]; // Do not allow redirects to dangerous protocols such as file:// if (!whitelistedSafe) { diff --git a/Sparkle/SUUpdateValidator.h b/Sparkle/SUUpdateValidator.h new file mode 100644 index 00000000..0a5f14c6 --- /dev/null +++ b/Sparkle/SUUpdateValidator.h @@ -0,0 +1,25 @@ +// +// SUUpdateValidator.h +// Sparkle +// +// Created by Mayur Pawashe on 12/3/16. +// Copyright © 2016 Sparkle Project. All rights reserved. +// + +#import + +@class SUHost; + +@interface SUUpdateValidator : NSObject + +// Pass YES to performingPrevalidation if archive validation must be done immediately, before extraction +- (instancetype)initWithDownloadPath:(NSString *)downloadPath dsaSignature:(NSString *)dsaSignature host:(SUHost *)host performingPrevalidation:(BOOL)performingPrevalidation; + +// Indicates whether we can perform (post) validation later +@property (nonatomic, readonly) BOOL canValidate; + +// precondition: validation must be possible (see -canValidate) +// This is "post" validation, after an archive has been extracted +- (BOOL)validateWithUpdateDirectory:(NSString *)updateDirectory; + +@end diff --git a/Sparkle/SUUpdateValidator.m b/Sparkle/SUUpdateValidator.m new file mode 100644 index 00000000..71727e89 --- /dev/null +++ b/Sparkle/SUUpdateValidator.m @@ -0,0 +1,192 @@ +// +// SUUpdateValidator.m +// Sparkle +// +// Created by Mayur Pawashe on 12/3/16. +// Copyright © 2016 Sparkle Project. All rights reserved. +// + +#import "SUUpdateValidator.h" +#import "SUDSAVerifier.h" +#import "SUCodeSigningVerifier.h" +#import "SUInstaller.h" +#import "SUHost.h" +#import "SULog.h" + +@interface SUUpdateValidator () + +@property (nonatomic, readonly) SUHost *host; +@property (nonatomic, readonly) BOOL prevalidatedDsaSignature; +@property (nonatomic, readonly) NSString *dsaSignature; +@property (nonatomic, readonly) NSString *downloadPath; + +@end + +@implementation SUUpdateValidator + +@synthesize host = _host; +@synthesize canValidate = _canValidate; +@synthesize prevalidatedDsaSignature = _prevalidatedDsaSignature; +@synthesize dsaSignature = _dsaSignature; +@synthesize downloadPath = _downloadPath; + +- (instancetype)initWithDownloadPath:(NSString *)downloadPath dsaSignature:(NSString *)dsaSignature host:(SUHost *)host performingPrevalidation:(BOOL)performingPrevalidation +{ + self = [super init]; + if (self != nil) { + BOOL canValidate; + BOOL prevalidatedDsaSignature; + if (performingPrevalidation) { + NSString *publicDSAKey = host.publicDSAKey; + + if (publicDSAKey == nil) { + prevalidatedDsaSignature = NO; + SULog(@"Failed to validate update before unarchiving because no DSA key was found"); + } else if (dsaSignature == nil) { + prevalidatedDsaSignature = NO; + SULog(@"Failed to validate update before unarchiving because no DSA signature was found"); + } else { + prevalidatedDsaSignature = [SUDSAVerifier validatePath:downloadPath withEncodedDSASignature:dsaSignature withPublicDSAKey:publicDSAKey]; + if (!prevalidatedDsaSignature) { + SULog(@"DSA signature validation before unarchiving failed for update %@", downloadPath); + } + } + + canValidate = prevalidatedDsaSignature; + } else { + prevalidatedDsaSignature = NO; + canValidate = YES; + } + + _canValidate = canValidate; + _prevalidatedDsaSignature = prevalidatedDsaSignature; + _downloadPath = [downloadPath copy]; + _dsaSignature = [dsaSignature copy]; + _host = host; + } + return self; +} + +- (BOOL)validateWithUpdateDirectory:(NSString *)updateDirectory +{ + assert(self.canValidate); + + NSString *DSASignature = self.dsaSignature; + NSString *publicDSAKey = self.host.publicDSAKey; + NSString *downloadPath = self.downloadPath; + SUHost *host = self.host; + + BOOL prevalidatedDsaSignature = self.prevalidatedDsaSignature; + + BOOL validationCheckSuccess; + BOOL isPackage = NO; + + // install source could point to a new bundle or a package + NSString *installSource = [SUInstaller installSourcePathInUpdateFolder:updateDirectory forHost:host isPackage:&isPackage isGuided:NULL]; + if (installSource == nil) { + SULog(@"No suitable install is found in the update. The update will be rejected."); + validationCheckSuccess = NO; + } else { + NSURL *installSourceURL = [NSURL fileURLWithPath:installSource]; + + if (!prevalidatedDsaSignature) { + // Check to see if we have a package or bundle to validate + if (isPackage) { + // For package type updates, all we do is check if the DSA signature is valid + validationCheckSuccess = [SUDSAVerifier validatePath:downloadPath withEncodedDSASignature:DSASignature withPublicDSAKey:publicDSAKey]; + if (!validationCheckSuccess) { + SULog(@"DSA signature validation of the package failed. The update contains an installer package, and valid DSA signatures are mandatory for all installer packages. The update will be rejected. Sign the installer with a valid DSA key or use an .app bundle update instead."); + } + } else { + // For application bundle updates, we check both the DSA and Apple code signing signatures + validationCheckSuccess = [self validateUpdateForHost:host downloadedToPath:downloadPath newBundleURL:installSourceURL DSASignature:DSASignature]; + } + } else if (isPackage) { + // We shouldn't get here because we don't validate packages before extracting them currently + SULog(@"Error: not expecting to find package after being required to validate update before extraction"); + validationCheckSuccess = NO; + } else { + // Because we already validated the DSA signature, this is just a consistency check to see + // if the developer signed their application properly with their Apple ID + // Currently, this case only gets hit for binary delta updates + NSError *error = nil; + if ([SUCodeSigningVerifier bundleAtURLIsCodeSigned:installSourceURL] && ![SUCodeSigningVerifier codeSignatureIsValidAtBundleURL:installSourceURL error:&error]) { + SULog(@"Failed to validate apple code sign signature on bundle after archive validation with error: %@", error); + validationCheckSuccess = NO; + } else { + validationCheckSuccess = YES; + } + } + } + + return validationCheckSuccess; +} + +/** + * If the update is a bundle, then it must meet any one of: + * + * * old and new DSA public keys are the same and valid (it allows change of Code Signing identity), or + * + * * old and new Code Signing identity are the same and valid + * + */ +- (BOOL)validateUpdateForHost:(SUHost *)host downloadedToPath:(NSString *)downloadedPath newBundleURL:(NSURL *)newBundleURL DSASignature:(NSString *)DSASignature +{ + NSBundle *newBundle = [NSBundle bundleWithURL:newBundleURL]; + if (newBundle == nil) { + SULog(@"No suitable bundle is found in the update. The update will be rejected."); + return NO; + } + + NSString *publicDSAKey = host.publicDSAKey; + + SUHost *newHost = [[SUHost alloc] initWithBundle:newBundle]; + NSString *newPublicDSAKey = newHost.publicDSAKey; + + // Downgrade in DSA security should not be possible + if (publicDSAKey != nil && newPublicDSAKey == nil) { + SULog(@"A public DSA key is found in the old bundle but no public DSA key is found in the new update. For security reasons, the update will be rejected."); + return NO; + } + + BOOL dsaKeysMatch = (publicDSAKey == nil || newPublicDSAKey == nil) ? NO : [publicDSAKey isEqualToString:newPublicDSAKey]; + + // If the new DSA key differs from the old, then this check is not a security measure, because the new key is not trusted. + // In that case, the check ensures that the app author has correctly used DSA keys, so that the app will be updateable in the next version. + // However if the new and old DSA keys are the same, then this is a security measure. + if (newPublicDSAKey != nil) { + if (![SUDSAVerifier validatePath:downloadedPath withEncodedDSASignature:DSASignature withPublicDSAKey:newPublicDSAKey]) { + SULog(@"DSA signature validation failed. The update has a public DSA key and is signed with a DSA key, but the %@ doesn't match the signature. The update will be rejected.", + dsaKeysMatch ? @"public key" : @"new public key shipped with the update"); + return NO; + } + } + BOOL updateIsCodeSigned = [SUCodeSigningVerifier bundleAtURLIsCodeSigned:newHost.bundle.bundleURL]; + + if (dsaKeysMatch) { + NSError *error = nil; + if (updateIsCodeSigned && ![SUCodeSigningVerifier codeSignatureIsValidAtBundleURL:newHost.bundle.bundleURL error:&error]) { + SULog(@"The update archive has a valid DSA signature, but the app is also signed with Code Signing, which is corrupted: %@. The update will be rejected.", error); + return NO; + } + } else { + BOOL hostIsCodeSigned = [SUCodeSigningVerifier bundleAtURLIsCodeSigned:host.bundle.bundleURL]; + + NSString *dsaStatus = newPublicDSAKey ? @"has a new DSA key that doesn't match the previous one" : (publicDSAKey ? @"removes the DSA key" : @"isn't signed with a DSA key"); + if (!hostIsCodeSigned || !updateIsCodeSigned) { + NSString *acsStatus = !hostIsCodeSigned ? @"old app hasn't been signed with app Code Signing" : @"new app isn't signed with app Code Signing"; + SULog(@"The update archive %@, and the %@. At least one method of signature verification must be valid. The update will be rejected.", dsaStatus, acsStatus); + return NO; + } + + NSError *error = nil; + if (![SUCodeSigningVerifier codeSignatureAtBundleURL:host.bundle.bundleURL matchesSignatureAtBundleURL:newHost.bundle.bundleURL error:&error]) { + SULog(@"The update archive %@, and the app is signed with a new Code Signing identity that doesn't match code signing of the original app: %@. At least one method of signature verification must be valid. The update will be rejected.", dsaStatus, error); + return NO; + } + } + + return YES; +} + +@end diff --git a/Sparkle/SUUpdater.h b/Sparkle/SUUpdater.h index 86024858..ac7600eb 100644 --- a/Sparkle/SUUpdater.h +++ b/Sparkle/SUUpdater.h @@ -9,7 +9,11 @@ #ifndef SUUPDATER_H #define SUUPDATER_H +#if __has_feature(modules) +@import Foundation; +#else #import +#endif #import "SUExport.h" #import "SUVersionComparisonProtocol.h" #import "SUVersionDisplayProtocol.h" @@ -28,64 +32,158 @@ SU_EXPORT @interface SUUpdater : NSObject @property (unsafe_unretained) IBOutlet id delegate; +/*! + The shared updater for the main bundle. + + This is equivalent to passing [NSBundle mainBundle] to SUUpdater::updaterForBundle: + */ + (SUUpdater *)sharedUpdater; + +/*! + The shared updater for a specified bundle. + + If an updater has already been initialized for the provided bundle, that shared instance will be returned. + */ + (SUUpdater *)updaterForBundle:(NSBundle *)bundle; + +/*! + Designated initializer for SUUpdater. + + If an updater has already been initialized for the provided bundle, that shared instance will be returned. + */ - (instancetype)initForBundle:(NSBundle *)bundle; -@property (readonly, strong) NSBundle *hostBundle; -@property (strong, readonly) NSBundle *sparkleBundle; - -@property BOOL automaticallyChecksForUpdates; - -@property NSTimeInterval updateCheckInterval; - /*! - * The URL of the appcast used to download update information. - * - * This property must be called on the main thread. - */ -@property (copy) NSURL *feedURL; + Explicitly checks for updates and displays a progress dialog while doing so. -@property (nonatomic, copy) NSString *userAgentString; + This method is meant for a main menu item. + Connect any menu item to this action in Interface Builder, + and Sparkle will check for updates and report back its findings verbosely + when it is invoked. -@property (copy) NSDictionary *httpHeaders; - -@property BOOL sendsSystemProfile; - -@property BOOL automaticallyDownloadsUpdates; - -@property (nonatomic, copy) NSString *decryptionPassword; - -/*! - Explicitly checks for updates and displays a progress dialog while doing so. - - This method is meant for a main menu item. - Connect any menu item to this action in Interface Builder, - and Sparkle will check for updates and report back its findings verbosely - when it is invoked. + This will find updates that the user has opted into skipping. */ - (IBAction)checkForUpdates:(id)sender; /*! - Checks for updates, but does not display any UI unless an update is found. + The menu item validation used for the -checkForUpdates: action + */ +- (BOOL)validateMenuItem:(NSMenuItem *)menuItem; - This is meant for programmatically initating a check for updates. That is, - it will display no UI unless it actually finds an update, in which case it - proceeds as usual. +/*! + Checks for updates, but does not display any UI unless an update is found. - If the fully automated updating is turned on, however, this will invoke that - behavior, and if an update is found, it will be downloaded and prepped for - installation. + This is meant for programmatically initating a check for updates. That is, + it will display no UI unless it actually finds an update, in which case it + proceeds as usual. + + If automatic downloading of updates it turned on and allowed, however, + this will invoke that behavior, and if an update is found, it will be downloaded + in the background silently and will be prepped for installation. + + This will not find updates that the user has opted into skipping. */ - (void)checkForUpdatesInBackground; +/*! + A property indicating whether or not to check for updates automatically. + + Setting this property will persist in the host bundle's user defaults. + The update schedule cycle will be reset in a short delay after the property's new value is set. + This is to allow reverting this property without kicking off a schedule change immediately + */ +@property BOOL automaticallyChecksForUpdates; + +/*! + A property indicating whether or not updates can be automatically downloaded in the background. + + Note that automatic downloading of updates can be disallowed by the developer + or by the user's system if silent updates cannot be done (eg: if they require authentication). + In this case, -automaticallyDownloadsUpdates will return NO regardless of how this property is set. + + Setting this property will persist in the host bundle's user defaults. + */ +@property BOOL automaticallyDownloadsUpdates; + +/*! + A property indicating the current automatic update check interval. + + Setting this property will persist in the host bundle's user defaults. + The update schedule cycle will be reset in a short delay after the property's new value is set. + This is to allow reverting this property without kicking off a schedule change immediately + */ +@property NSTimeInterval updateCheckInterval; + +/*! + Begins a "probing" check for updates which will not actually offer to + update to that version. + + However, the delegate methods + SUUpdaterDelegate::updater:didFindValidUpdate: and + SUUpdaterDelegate::updaterDidNotFindUpdate: will be called, + so you can use that information in your UI. + + Updates that have been skipped by the user will not be found. + */ +- (void)checkForUpdateInformation; + +/*! + The URL of the appcast used to download update information. + + Setting this property will persist in the host bundle's user defaults. + If you don't want persistence, you may want to consider instead implementing + SUUpdaterDelegate::feedURLStringForUpdater: or SUUpdaterDelegate::feedParametersForUpdater:sendingSystemProfile: + + This property must be called on the main thread. + */ +@property (copy) NSURL *feedURL; + +/*! + The host bundle that is being updated. + */ +@property (readonly, strong) NSBundle *hostBundle; + +/*! + The bundle this class (SUUpdater) is loaded into. + */ +@property (strong, readonly) NSBundle *sparkleBundle; + +/*! + The user agent used when checking for updates. + + The default implementation can be overrided. + */ +@property (nonatomic, copy) NSString *userAgentString; + +/*! + The HTTP headers used when checking for updates. + + The keys of this dictionary are HTTP header fields (NSString) and values are corresponding values (NSString) + */ +@property (copy) NSDictionary *httpHeaders; + +/*! + A property indicating whether or not the user's system profile information is sent when checking for updates. + + Setting this property will persist in the host bundle's user defaults. + */ +@property BOOL sendsSystemProfile; + +/*! + A property indicating the decryption password used for extracting updates shipped as Apple Disk Images (dmg) + */ +@property (nonatomic, copy) NSString *decryptionPassword; + /*! Checks for updates and, if available, immediately downloads and installs them. A progress dialog is shown but the user will never be prompted to read the release notes. - + You may want to respond to the userDidCancelDownload delegate method in case the user clicks the "Cancel" button while the update is downloading. + + If you are writing a UI-less background application, you probably want to instead use + SUUpdaterDelegate::updater:willInstallUpdateOnQuit:immediateInstallationInvocation: */ - (void)installUpdatesIfAvailable; @@ -96,17 +194,6 @@ SU_EXPORT @interface SUUpdater : NSObject */ @property (readonly, copy) NSDate *lastUpdateCheckDate; -/*! - Begins a "probing" check for updates which will not actually offer to - update to that version. - - However, the delegate methods - SUUpdaterDelegate::updater:didFindValidUpdate: and - SUUpdaterDelegate::updaterDidNotFindUpdate: will be called, - so you can use that information in your UI. - */ -- (void)checkForUpdateInformation; - /*! Appropriately schedules or cancels the update checking timer according to the preferences for time interval and automatic checks. @@ -116,6 +203,12 @@ SU_EXPORT @interface SUUpdater : NSObject */ - (void)resetUpdateCycle; +/*! + A property indicating whether or not an update is in progress. + + Note this property is not indicative of whether or not user initiated updates can be performed. + Use SUUpdater::validateMenuItem: for that instead. + */ @property (readonly) BOOL updateInProgress; @end @@ -172,6 +265,9 @@ SU_EXPORT extern NSString *const SUUpdaterAppcastNotificationKey; Override this to dynamically specify the entire URL. + An alternative may be to use SUUpdaterDelegate::feedParametersForUpdater:sendingSystemProfile: + and let the server handle what kind of feed to provide. + \param updater The SUUpdater instance. */ - (NSString *)feedURLStringForUpdater:(SUUpdater *)updater; @@ -263,7 +359,7 @@ SU_EXPORT extern NSString *const SUUpdaterAppcastNotificationKey; \param updater The SUUpdater instance. \param item The appcast item corresponding to the update that is proposed to be installed. - \param invocation The invocation that must be completed before continuing with the relaunch. + \param invocation The invocation that must be completed with `[invocation invoke]` before continuing with the relaunch. \return \c YES to delay the relaunch until \p invocation is invoked. */ @@ -338,6 +434,8 @@ SU_EXPORT extern NSString *const SUUpdaterAppcastNotificationKey; /*! Called when an update is scheduled to be silently installed on quit. + This is after an update has been automatically downloaded in the background. + (i.e. SUUpdater::automaticallyDownloadsUpdates is YES) \param updater The SUUpdater instance. \param item The appcast item corresponding to the update that is proposed to be installed. diff --git a/Sparkle/SUUpdater.m b/Sparkle/SUUpdater.m index 77998375..d7a51f62 100644 --- a/Sparkle/SUUpdater.m +++ b/Sparkle/SUUpdater.m @@ -59,6 +59,15 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification static NSMutableDictionary *sharedUpdaters = nil; static NSString *const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefaultsObservationContext"; +#ifdef DEBUG ++ (void)load +{ + // Debug builds have different configurations for update check intervals + // We're using NSLog instead of SULog here because we don't want to start Sparkle's logger here + NSLog(@"WARNING: This is running a Debug build of Sparkle; don't use this in production!"); +} +#endif + + (SUUpdater *)sharedUpdater { return [self updaterForBundle:[NSBundle mainBundle]]; @@ -68,7 +77,7 @@ static NSString *const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefaults + (SUUpdater *)updaterForBundle:(NSBundle *)bundle { if (bundle == nil) bundle = [NSBundle mainBundle]; - id updater = sharedUpdaters[[NSValue valueWithNonretainedObject:bundle]]; + id updater = [sharedUpdaters objectForKey:[NSValue valueWithNonretainedObject:bundle]]; if (updater == nil) { updater = [[[self class] alloc] initForBundle:bundle]; } @@ -93,7 +102,7 @@ static NSString *const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefaults [self registerAsObserver]; } - id updater = sharedUpdaters[[NSValue valueWithNonretainedObject:bundle]]; + id updater = [sharedUpdaters objectForKey:[NSValue valueWithNonretainedObject:bundle]]; if (updater) { self = updater; @@ -103,7 +112,7 @@ static NSString *const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefaults if (sharedUpdaters == nil) { sharedUpdaters = [[NSMutableDictionary alloc] init]; } - sharedUpdaters[[NSValue valueWithNonretainedObject:bundle]] = self; + [sharedUpdaters setObject:self forKey:[NSValue valueWithNonretainedObject:bundle]]; host = [[SUHost alloc] initWithBundle:bundle]; // This runs the permission prompt if needed, but never before the app has finished launching because the runloop won't run before that @@ -122,28 +131,42 @@ static NSString *const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefaults -(void)checkIfConfiguredProperly { BOOL hasPublicDSAKey = [self.host publicDSAKey] != nil; BOOL isMainBundle = [self.host.bundle isEqualTo:[NSBundle mainBundle]]; - BOOL hostIsCodeSigned = [SUCodeSigningVerifier hostApplicationIsCodeSigned]; + BOOL hostIsCodeSigned = [SUCodeSigningVerifier bundleAtURLIsCodeSigned:self.host.bundle.bundleURL]; NSURL *feedURL = [self feedURL]; BOOL servingOverHttps = [[[feedURL scheme] lowercaseString] isEqualToString:@"https"]; - if (!isMainBundle && !hasPublicDSAKey) { - [self showAlertText:@"Insecure update error!" - informativeText:@"For security reasons, you need to sign your updates with a DSA key. See Sparkle's documentation for more information."]; - } else if (isMainBundle && !(hasPublicDSAKey || hostIsCodeSigned)) { - [self showAlertText:@"Insecure update error!" - informativeText:@"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."]; - } else if (isMainBundle && !hasPublicDSAKey && !servingOverHttps) { - SULog(@"WARNING: Serving updates over HTTP without signing them with a DSA key is deprecated and may not be possible in a future release. Please serve your updates over https, or sign them with a DSA key, or do both. See Sparkle's documentation for more information."); + + if (!hasPublicDSAKey) { + // If we failed to retrieve a DSA key but the bundle specifies a path to one, we should consider this a configuration failure + NSString *publicDSAKeyFileKey = [self.host publicDSAKeyFileKey]; + if (publicDSAKeyFileKey != nil) { + [self showAlertText:SULocalizedString(@"Insecure update error!", nil) + informativeText:[NSString stringWithFormat:SULocalizedString(@"For security reasons, the file (%@) indicated by the '%@' key needs to exist in the bundle's Resources.", nil), publicDSAKeyFileKey, SUPublicDSAKeyFileKey]]; + } else { + if (!isMainBundle) { + [self showAlertText:SULocalizedString(@"Insecure update error!", nil) + informativeText:SULocalizedString(@"For security reasons, you need to sign your updates with a DSA key. See Sparkle's documentation for more information.", nil)]; + } else { + if (!hostIsCodeSigned) { + [self showAlertText:SULocalizedString(@"Insecure update error!", nil) + informativeText:SULocalizedString(@"For security reasons, you need to code sign your application or sign your updates with a DSA key. See https://sparkle-project.org/documentation/ for more information.", nil)]; + } else if (!servingOverHttps) { + [self showAlertText:SULocalizedString(@"Insecure update error!", nil) + informativeText:SULocalizedString(@"For security reasons, you need to serve your updates over HTTPS and/or sign your updates with a DSA key. See https://sparkle-project.org/documentation/ for more information.", nil)]; + } + } + } } #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 101100 - BOOL atsExceptionsExist = nil != [self.host objectForInfoDictionaryKey:@"NSAppTransportSecurity"]; - if (isMainBundle && !servingOverHttps && !atsExceptionsExist) { - [self showAlertText:@"Insecure feed URL is blocked in OS X 10.11" - informativeText:[NSString stringWithFormat:@"You must change the feed URL (%@) to use HTTPS or disable App Transport Security.\n\nFor more information:\nhttp://sparkle-project.org/documentation/app-transport-security/", [feedURL absoluteString]]]; + if (!servingOverHttps) { + BOOL atsExceptionsExist = nil != [self.host objectForInfoDictionaryKey:@"NSAppTransportSecurity"]; + if (isMainBundle && !atsExceptionsExist) { + [self showAlertText:SULocalizedString(@"Insecure feed URL is blocked in macOS 10.11", nil) + informativeText:[NSString stringWithFormat:SULocalizedString(@"You must change the feed URL (%@) to use HTTPS or disable App Transport Security.\n\nFor more information:\nhttps://sparkle-project.org/documentation/app-transport-security/", nil), [feedURL absoluteString]]]; + } else if (!isMainBundle) { + // SULog(@"WARNING: Serving updates over HTTP may be blocked in macOS 10.11. Please change the feed URL (%@) to use HTTPS. For more information:\nhttps://sparkle-project.org/documentation/app-transport-security/", feedURL); + } } -// if (!isMainBundle && !servingOverHttps) { -// SULog(@"WARNING: Serving updates over HTTP may be blocked in OS X 10.11. Please change the feed URL (%@) to use HTTPS. For more information:\nhttp://sparkle-project.org/documentation/app-transport-security/", feedURL); -// } #endif } @@ -206,6 +229,7 @@ static NSString *const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefaults if ([note object] == self.driver && [self.driver finished]) { self.driver = nil; + [self updateLastUpdateCheckDate]; [self scheduleNextUpdateCheck]; } } @@ -215,6 +239,13 @@ static NSString *const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefaults return [self.host objectForUserDefaultsKey:SULastCheckTimeKey]; } +- (void)updateLastUpdateCheckDate +{ + [self willChangeValueForKey:@"lastUpdateCheckDate"]; + [self.host setObject:[NSDate date] forUserDefaultsKey:SULastCheckTimeKey]; + [self didChangeValueForKey:@"lastUpdateCheckDate"]; +} + - (void)scheduleNextUpdateCheck { if (self.checkTimer) @@ -240,76 +271,14 @@ static NSString *const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefaults self.checkTimer = [NSTimer scheduledTimerWithTimeInterval:delayUntilCheck target:self selector:@selector(checkForUpdatesInBackground) userInfo:nil repeats:NO]; // Timer is non-repeating, may have invalidated itself, so we had to retain it. } - -- (void)putFeedURLIntoDictionary:(NSMutableDictionary *)theDict // You release this. -{ - theDict[@"feedURL"] = [self feedURL]; -} - -- (void)checkForUpdatesInBgReachabilityCheckWithDriver:(SUUpdateDriver *)inDriver /* RUNS ON ITS OWN THREAD */ -{ - @try { - // This method *must* be called on its own thread. SCNetworkReachabilityCheckByName - // can block, and it can be waiting a long time on slow networks, and we - // wouldn't want to beachball the main thread for a background operation. - // We could use asynchronous reachability callbacks, but those aren't - // reliable enough and can 'get lost' sometimes, which we don't want. - - @autoreleasepool { - SCNetworkConnectionFlags flags = 0; - BOOL isNetworkReachable = YES; - - // Don't perform automatic checks on unconnected laptops or dial-up connections that aren't online: - NSMutableDictionary *theDict = [NSMutableDictionary dictionary]; - dispatch_sync(dispatch_get_main_queue(), ^{ - [self putFeedURLIntoDictionary:theDict]; // Get feed URL on main thread, it's not safe to call elsewhere. - }); - - const char *hostname = [[(NSURL *)theDict[@"feedURL"] host] cStringUsingEncoding:NSUTF8StringEncoding]; - SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, hostname); - Boolean reachabilityResult = NO; - // If the feed's using a file:// URL, we won't be able to use reachability. - if (reachability != NULL) { - SCNetworkReachabilityGetFlags(reachability, &flags); - CFRelease(reachability); - } - - if( reachabilityResult ) - { - BOOL reachable = (flags & kSCNetworkFlagsReachable) == kSCNetworkFlagsReachable; - BOOL automatic = (flags & kSCNetworkFlagsConnectionAutomatic) == kSCNetworkFlagsConnectionAutomatic; - BOOL local = (flags & kSCNetworkFlagsIsLocalAddress) == kSCNetworkFlagsIsLocalAddress; - - if (!(reachable || automatic || local)) - isNetworkReachable = NO; - } - - // If the network's not reachable, we pass a nil driver into checkForUpdatesWithDriver, which will then reschedule the next update so we try again later. - dispatch_async(dispatch_get_main_queue(), ^{ - [self checkForUpdatesWithDriver: isNetworkReachable ? inDriver : nil]; - }); - - } - } @catch (NSException *localException) { - SULog(@"UNCAUGHT EXCEPTION IN UPDATE CHECK TIMER: %@", [localException reason]); - // Don't propagate the exception beyond here. In Carbon apps that would trash the stack. - } -} - - - (void)checkForUpdatesInBackground { - // Background update checks should only happen if we have a network connection. - // Wouldn't want to annoy users on dial-up by establishing a connection every - // hour or so: + // Do not use reachability for a preflight check. This can be deceptive and a bad idea. Apple does not recommend doing it. SUUpdateDriver *theUpdateDriver = [[([self automaticallyDownloadsUpdates] ? [SUAutomaticUpdateDriver class] : [SUScheduledUpdateDriver class])alloc] initWithUpdater:self]; - dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ - [self checkForUpdatesInBgReachabilityCheckWithDriver:theUpdateDriver]; - }); + [self checkForUpdatesWithDriver:theUpdateDriver]; } - - (BOOL)mayUpdateAndRestart { return (!self.delegate || ![self.delegate respondsToSelector:@selector(updaterShouldRelaunchApplication:)] || [self.delegate updaterShouldRelaunchApplication:self]); @@ -345,9 +314,7 @@ static NSString *const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefaults if ([self updateInProgress]) { return; } if (self.checkTimer) { [self.checkTimer invalidate]; self.checkTimer = nil; } // Timer is non-repeating, may have invalidated itself, so we had to retain it. - [self willChangeValueForKey:@"lastUpdateCheckDate"]; - [self.host setObject:[NSDate date] forUserDefaultsKey:SULastCheckTimeKey]; - [self didChangeValueForKey:@"lastUpdateCheckDate"]; + [self updateLastUpdateCheckDate]; if( [self.delegate respondsToSelector: @selector(updaterMayCheckForUpdates:)] && ![self.delegate updaterMayCheckForUpdates: self] ) { @@ -531,7 +498,7 @@ static NSString *const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefaults // Build up the parameterized URL. NSMutableArray *parameterStrings = [NSMutableArray array]; for (NSDictionary *currentProfileInfo in parameters) { - [parameterStrings addObject:[NSString stringWithFormat:@"%@=%@", [[currentProfileInfo[@"key"] description] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding], [[currentProfileInfo[@"value"] description] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]; + [parameterStrings addObject:[NSString stringWithFormat:@"%@=%@", [[[currentProfileInfo objectForKey:@"key"] description] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding], [[[currentProfileInfo objectForKey:@"value"] description] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]; } NSString *separatorCharacter = @"?"; @@ -575,7 +542,7 @@ static NSString *const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefaults - (BOOL)validateMenuItem:(NSMenuItem *)item { if ([item action] == @selector(checkForUpdates:)) { - return ![self updateInProgress]; + return ![self updateInProgress] || [self.driver isInterruptible]; } return YES; } diff --git a/Sparkle/SUUserInitiatedUpdateDriver.m b/Sparkle/SUUserInitiatedUpdateDriver.m index d1e0c9a6..04e96b23 100644 --- a/Sparkle/SUUserInitiatedUpdateDriver.m +++ b/Sparkle/SUUserInitiatedUpdateDriver.m @@ -81,7 +81,7 @@ - (BOOL)itemContainsValidUpdate:(SUAppcastItem *)ui { // We don't check to see if this update's been skipped, because the user explicitly *asked* if he had the latest version. - return [self hostSupportsItem:ui] && [self isItemNewer:ui]; + return [[self class] hostSupportsItem:ui] && [self isItemNewer:ui]; } @end diff --git a/Sparkle/SUVersionComparisonProtocol.h b/Sparkle/SUVersionComparisonProtocol.h index 10c42669..c099ad57 100644 --- a/Sparkle/SUVersionComparisonProtocol.h +++ b/Sparkle/SUVersionComparisonProtocol.h @@ -9,7 +9,11 @@ #ifndef SUVERSIONCOMPARISONPROTOCOL_H #define SUVERSIONCOMPARISONPROTOCOL_H +#if __has_feature(modules) +@import Cocoa; +#else #import +#endif #import "SUExport.h" /*! diff --git a/Sparkle/SUVersionDisplayProtocol.h b/Sparkle/SUVersionDisplayProtocol.h index 97fae4c9..16e444ff 100644 --- a/Sparkle/SUVersionDisplayProtocol.h +++ b/Sparkle/SUVersionDisplayProtocol.h @@ -6,7 +6,11 @@ // Copyright 2009 Elgato Systems GmbH. All rights reserved. // +#if __has_feature(modules) +@import Cocoa; +#else #import +#endif #import "SUExport.h" /*! diff --git a/Sparkle/Sparkle.h b/Sparkle/Sparkle.h index 20ed6979..ab828c29 100644 --- a/Sparkle/Sparkle.h +++ b/Sparkle/Sparkle.h @@ -9,7 +9,11 @@ #ifndef SPARKLE_H #define SPARKLE_H +#if __has_feature(modules) +@import Cocoa; +#else #import +#endif // This list should include the shared headers. It doesn't matter if some of them aren't shared (unless // there are name-space collisions) so we can list all of them to start with: diff --git a/Sparkle/ar.lproj/SUUpdateAlert.xib b/Sparkle/ar.lproj/SUUpdateAlert.xib index e74564ce..c4309fe9 100644 --- a/Sparkle/ar.lproj/SUUpdateAlert.xib +++ b/Sparkle/ar.lproj/SUUpdateAlert.xib @@ -41,7 +41,7 @@ - + diff --git a/Sparkle/cs.lproj/SUAutomaticUpdateAlert.xib b/Sparkle/cs.lproj/SUAutomaticUpdateAlert.xib index 1b2be43d..0c30faaa 100644 --- a/Sparkle/cs.lproj/SUAutomaticUpdateAlert.xib +++ b/Sparkle/cs.lproj/SUAutomaticUpdateAlert.xib @@ -1,7 +1,7 @@ - + - + @@ -24,7 +24,6 @@ - @@ -33,7 +32,6 @@ - @@ -46,7 +44,6 @@ - @@ -57,10 +54,9 @@ + + - - - diff --git a/Sparkle/cs.lproj/SUUpdateAlert.xib b/Sparkle/cs.lproj/SUUpdateAlert.xib index afa0cf85..7ef103de 100644 --- a/Sparkle/cs.lproj/SUUpdateAlert.xib +++ b/Sparkle/cs.lproj/SUUpdateAlert.xib @@ -1,8 +1,8 @@ - + - - + + @@ -26,7 +26,7 @@ - + @@ -40,8 +40,7 @@ - - + @@ -51,7 +50,6 @@ - @@ -61,13 +59,12 @@ - + - @@ -88,7 +85,6 @@ - @@ -101,7 +97,6 @@ - @@ -110,7 +105,6 @@ - @@ -127,7 +121,6 @@ - @@ -150,14 +143,12 @@ - - @@ -149,13 +140,12 @@ Gw - - Informace z anonymního systémového profilu pomáhají vývojářům lépe plánovat budoucí vývoj aplikace -Obraťte se na nás v případě, že budete mít k němu nějaký dotaz. + Informace z anonymního systémového profilu pomáhají vývojářům lépe plánovat budoucí vývoj aplikace. +Budete-li mít nějaký dotaz, obraťte se na nás. -Tyto informace by měli být odeslány: +Tyto informace by měly být odeslány: @@ -165,12 +155,11 @@ Tyto informace by měli být odeslány: - + - @@ -210,23 +199,18 @@ Tyto informace by měli být odeslány: - - - diff --git a/Sparkle/cs.lproj/Sparkle.strings b/Sparkle/cs.lproj/Sparkle.strings index 0cf3adb4..251d007f 100644 --- a/Sparkle/cs.lproj/Sparkle.strings +++ b/Sparkle/cs.lproj/Sparkle.strings @@ -1,6 +1,6 @@ "%1$@ %2$@ has been downloaded and is ready to use! Would you like to install it and relaunch %1$@ now?" = "%1$@ %2$@ byl instalován a je připraven k použití po příštím spuštění. Přejete si aplikaci %1$@ nyní nainstalovat a znovu spustit?"; -"%1$@ can't be updated when it's running from a read-only volume like a disk image or an optical drive. Move %1$@ to your Applications folder, relaunch it from there, and try again." = "Aplikace %1$@ nemůže být aktualizována, protože je spuštěna z nezapisovatelného média. Může to být CD/DVD-ROM, obraz disku nebo jen nemáte právo zápisu na disk. Přesuňte aplikaci %1$@ do vaší složky Aplikace, spusťte ji z tohoto umístěni znovu."; +"%1$@ can't be updated when it's running from a read-only volume like a disk image or an optical drive. Move %1$@ to your Applications folder, relaunch it from there, and try again." = "Aplikace %1$@ nemůže být aktualizována, protože je spuštěna z média na které nelze zapisovat. Může to být CD/DVD-ROM, obraz disku nebo jen nemáte právo zápisu na disk. Přesuňte aplikaci %1$@ do vaší složky Aplikace, spusťte ji z tohoto umístěni znovu."; "%@ %@ is currently the newest version available." = "%1$@ %2$@ je nejnovější dostupná verze"; @@ -8,7 +8,7 @@ "%@ %@ is now available--you have %@. Would you like to download it now?" = "Je k dispozici %1$@ %2$@ - máte %3$@. Přejete si nyní zkopírovat aktualizaci?"; /* Description text for SUUpdateAlert when the update informational with no download. */ -"%@ %@ is now available--you have %@. Would you like to learn more about this update on the web?" = "%1$@ %2$@ is now available--you have %3$@. Would you like to learn more about this update on the web?"; +"%@ %@ is now available--you have %@. Would you like to learn more about this update on the web?" = "%1$@ %2$@ je nyní k dispozici – vy máte %3$@. Přejete si zobrazit o této aktualizaci další informace?"; "%@ downloaded" = "zkopírováno %@"; @@ -24,7 +24,7 @@ "An error occurred while extracting the archive. Please try again later." = "Při rozbalování archivu se vyskytla chyba. Zkuste to prosím později."; -"An error occurred while installing the update. Please try again later." = "Při instalování aktualizace se vyskytla chyba. Zkuste to prosím později."; +"An error occurred while installing the update. Please try again later." = "Při instalaci aktualizace se vyskytla chyba. Zkuste to prosím později."; "An error occurred while parsing the update feed." = "Při zpracovávání údajů o aktualizaci se vyskytla chyba. Zkuste to prosím později."; diff --git a/Sparkle/da.lproj/SUUpdateAlert.xib b/Sparkle/da.lproj/SUUpdateAlert.xib index 901353fa..77fcdd65 100644 --- a/Sparkle/da.lproj/SUUpdateAlert.xib +++ b/Sparkle/da.lproj/SUUpdateAlert.xib @@ -41,7 +41,7 @@ - + diff --git a/Sparkle/de.lproj/SUAutomaticUpdateAlert.xib b/Sparkle/de.lproj/SUAutomaticUpdateAlert.xib index 665268ff..2672e10c 100644 --- a/Sparkle/de.lproj/SUAutomaticUpdateAlert.xib +++ b/Sparkle/de.lproj/SUAutomaticUpdateAlert.xib @@ -1,7 +1,8 @@ - + - + + @@ -14,26 +15,24 @@ - + - + - - + - @@ -44,9 +43,8 @@ - + - @@ -57,9 +55,8 @@ - + - + diff --git a/Sparkle/de.lproj/SUUpdateAlert.xib b/Sparkle/de.lproj/SUUpdateAlert.xib index fc93ca11..615bbaf7 100644 --- a/Sparkle/de.lproj/SUUpdateAlert.xib +++ b/Sparkle/de.lproj/SUUpdateAlert.xib @@ -41,7 +41,7 @@ - + diff --git a/Sparkle/de.lproj/Sparkle.strings b/Sparkle/de.lproj/Sparkle.strings index 643af47f..1fc6a3d7 100644 --- a/Sparkle/de.lproj/Sparkle.strings +++ b/Sparkle/de.lproj/Sparkle.strings @@ -1,3 +1,5 @@ +"%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?" = "%1$@ %2$@ wurde heruntergeladen und steht zur Verwendung bereit! Dies ist eine wichtige Aktualisierung. Möchten Sie %1$@ jetzt durch die neue Version ersetzen und neu starten?"; + "%1$@ %2$@ has been downloaded and is ready to use! Would you like to install it and relaunch %1$@ now?" = "%1$@ %2$@ wurde heruntergeladen und steht zur Verwendung bereit! Möchten Sie %1$@ jetzt durch die neue Version ersetzen und neu starten?"; "%1$@ can't be updated when it's running from a read-only volume like a disk image or an optical drive. Move %1$@ to your Applications folder, relaunch it from there, and try again." = "%1$@ kann nicht aktualisiert werden, wenn es von einem Volumen ohne Schreibzugriff (z.B. Disk Image oder CD/DVD) gestartet wurde. Kopieren Sie %1$@ in den Programme Ordner, aktualisieren Sie es von dort."; @@ -8,7 +10,7 @@ "%@ %@ is now available--you have %@. Would you like to download it now?" = "%1$@ %2$@ ist verfügbar (Sie verwenden Version %3$@). Möchten Sie die neue Version jetzt herunterladen?"; /* Description text for SUUpdateAlert when the update informational with no download. */ -"%@ %@ is now available--you have %@. Would you like to learn more about this update on the web?" = "%1$@ %2$@ is now available--you have %3$@. Would you like to learn more about this update on the web?"; +"%@ %@ is now available--you have %@. Would you like to learn more about this update on the web?" = "%1$@ %2$@ ist verfügbar (Sie verwenden Version %3$@). Möchten Sie mehr über diese Aktualisierung erfahren?"; "%@ downloaded" = "%@ heruntergeladen"; @@ -30,6 +32,8 @@ "An error occurred while relaunching %1$@, but the new version will be available next time you run %1$@." = "Beim erneuten Starten von %1$@ ist ein Fehler aufgetreten. Die neue Version von %1$@ steht beim nächsten Programmstart zur Verfügung."; +"An important update to %@ is ready to install" = "Eine wichtige Aktualisierung von %@ steht zur Installation bereit"; + /* the unit for bytes */ "B" = "B"; @@ -65,6 +69,8 @@ "Should %1$@ automatically check for updates? You can always check for updates manually from the %1$@ menu." = "Soll %1$@ automatisch nach Aktualisierungen suchen? Sie können im %1$@-Menü auch manuell nach Aktualisierungen suchen."; +"The update is improperly signed." = "Die Aktualisierung ist nicht ordnungsgemäß signiert."; + "Update Error!" = "Fehler beim Aktualisieren!"; "Updating %@" = "Aktualisierung von %@"; diff --git a/Sparkle/el.lproj/SUUpdateAlert.xib b/Sparkle/el.lproj/SUUpdateAlert.xib index 2795750a..01cc4651 100644 --- a/Sparkle/el.lproj/SUUpdateAlert.xib +++ b/Sparkle/el.lproj/SUUpdateAlert.xib @@ -41,7 +41,7 @@ - + diff --git a/Sparkle/en.lproj/SUUpdateAlert.xib b/Sparkle/en.lproj/SUUpdateAlert.xib index bbab3974..dbf344ac 100644 --- a/Sparkle/en.lproj/SUUpdateAlert.xib +++ b/Sparkle/en.lproj/SUUpdateAlert.xib @@ -41,7 +41,7 @@ - + diff --git a/Sparkle/es.lproj/SUUpdateAlert.xib b/Sparkle/es.lproj/SUUpdateAlert.xib index 7479b1e7..bb491ac2 100644 --- a/Sparkle/es.lproj/SUUpdateAlert.xib +++ b/Sparkle/es.lproj/SUUpdateAlert.xib @@ -41,7 +41,7 @@ - + diff --git a/Sparkle/fr.lproj/SUUpdateAlert.xib b/Sparkle/fr.lproj/SUUpdateAlert.xib index c3bf2078..9caa8a80 100644 --- a/Sparkle/fr.lproj/SUUpdateAlert.xib +++ b/Sparkle/fr.lproj/SUUpdateAlert.xib @@ -41,7 +41,7 @@ - + diff --git a/Sparkle/is.lproj/SUUpdateAlert.xib b/Sparkle/is.lproj/SUUpdateAlert.xib index 6052b26e..19c7a86e 100644 --- a/Sparkle/is.lproj/SUUpdateAlert.xib +++ b/Sparkle/is.lproj/SUUpdateAlert.xib @@ -41,7 +41,7 @@ - + diff --git a/Sparkle/it.lproj/SUUpdateAlert.xib b/Sparkle/it.lproj/SUUpdateAlert.xib index 612252b7..87fe5288 100644 --- a/Sparkle/it.lproj/SUUpdateAlert.xib +++ b/Sparkle/it.lproj/SUUpdateAlert.xib @@ -41,7 +41,7 @@ - + diff --git a/Sparkle/ja.lproj/SUUpdateAlert.xib b/Sparkle/ja.lproj/SUUpdateAlert.xib index 15d13fc4..67f62ec6 100644 --- a/Sparkle/ja.lproj/SUUpdateAlert.xib +++ b/Sparkle/ja.lproj/SUUpdateAlert.xib @@ -41,7 +41,7 @@ - + diff --git a/Sparkle/ko.lproj/SUUpdateAlert.xib b/Sparkle/ko.lproj/SUUpdateAlert.xib index 3e50f3ed..bc001093 100644 --- a/Sparkle/ko.lproj/SUUpdateAlert.xib +++ b/Sparkle/ko.lproj/SUUpdateAlert.xib @@ -41,7 +41,7 @@ - + diff --git a/Sparkle/nb.lproj/SUUpdateAlert.xib b/Sparkle/nb.lproj/SUUpdateAlert.xib index 4998d82f..5faca233 100644 --- a/Sparkle/nb.lproj/SUUpdateAlert.xib +++ b/Sparkle/nb.lproj/SUUpdateAlert.xib @@ -41,7 +41,7 @@ - + diff --git a/Sparkle/nl.lproj/SUUpdateAlert.xib b/Sparkle/nl.lproj/SUUpdateAlert.xib index e7a16211..d5f082de 100644 --- a/Sparkle/nl.lproj/SUUpdateAlert.xib +++ b/Sparkle/nl.lproj/SUUpdateAlert.xib @@ -41,7 +41,7 @@ - + diff --git a/Sparkle/pl.lproj/SUUpdateAlert.xib b/Sparkle/pl.lproj/SUUpdateAlert.xib index b3b17766..881723d1 100644 --- a/Sparkle/pl.lproj/SUUpdateAlert.xib +++ b/Sparkle/pl.lproj/SUUpdateAlert.xib @@ -41,7 +41,7 @@ - + diff --git a/Sparkle/pt_BR.lproj/SUUpdateAlert.xib b/Sparkle/pt_BR.lproj/SUUpdateAlert.xib index 7dbdb40a..12057104 100644 --- a/Sparkle/pt_BR.lproj/SUUpdateAlert.xib +++ b/Sparkle/pt_BR.lproj/SUUpdateAlert.xib @@ -41,7 +41,7 @@ - + diff --git a/Sparkle/pt_PT.lproj/SUUpdateAlert.xib b/Sparkle/pt_PT.lproj/SUUpdateAlert.xib index 20127569..15f20b6e 100644 --- a/Sparkle/pt_PT.lproj/SUUpdateAlert.xib +++ b/Sparkle/pt_PT.lproj/SUUpdateAlert.xib @@ -41,7 +41,7 @@ - + diff --git a/Sparkle/ro.lproj/SUUpdateAlert.xib b/Sparkle/ro.lproj/SUUpdateAlert.xib index c01f1e25..795641ff 100644 --- a/Sparkle/ro.lproj/SUUpdateAlert.xib +++ b/Sparkle/ro.lproj/SUUpdateAlert.xib @@ -41,7 +41,7 @@ - + diff --git a/Sparkle/ru.lproj/SUUpdateAlert.xib b/Sparkle/ru.lproj/SUUpdateAlert.xib index 1443e41d..d68be810 100644 --- a/Sparkle/ru.lproj/SUUpdateAlert.xib +++ b/Sparkle/ru.lproj/SUUpdateAlert.xib @@ -41,7 +41,7 @@ - + diff --git a/Sparkle/sk.lproj/SUUpdateAlert.xib b/Sparkle/sk.lproj/SUUpdateAlert.xib index 1843eab7..d0db891b 100644 --- a/Sparkle/sk.lproj/SUUpdateAlert.xib +++ b/Sparkle/sk.lproj/SUUpdateAlert.xib @@ -41,7 +41,7 @@ - + diff --git a/Sparkle/sl.lproj/SUUpdateAlert.xib b/Sparkle/sl.lproj/SUUpdateAlert.xib index 9faa755a..792b9529 100644 --- a/Sparkle/sl.lproj/SUUpdateAlert.xib +++ b/Sparkle/sl.lproj/SUUpdateAlert.xib @@ -41,7 +41,7 @@ - + diff --git a/Sparkle/sv.lproj/SUUpdateAlert.xib b/Sparkle/sv.lproj/SUUpdateAlert.xib index f528e060..f759f3d9 100644 --- a/Sparkle/sv.lproj/SUUpdateAlert.xib +++ b/Sparkle/sv.lproj/SUUpdateAlert.xib @@ -41,7 +41,7 @@ - + diff --git a/Sparkle/th.lproj/SUUpdateAlert.xib b/Sparkle/th.lproj/SUUpdateAlert.xib index d9aeb245..797ae34e 100644 --- a/Sparkle/th.lproj/SUUpdateAlert.xib +++ b/Sparkle/th.lproj/SUUpdateAlert.xib @@ -41,7 +41,7 @@ - + diff --git a/Sparkle/tr.lproj/SUUpdateAlert.xib b/Sparkle/tr.lproj/SUUpdateAlert.xib index ec099118..91fd7d32 100644 --- a/Sparkle/tr.lproj/SUUpdateAlert.xib +++ b/Sparkle/tr.lproj/SUUpdateAlert.xib @@ -41,7 +41,7 @@ - + diff --git a/Sparkle/uk.lproj/SUUpdateAlert.xib b/Sparkle/uk.lproj/SUUpdateAlert.xib index 831479c1..c3cbcd3b 100644 --- a/Sparkle/uk.lproj/SUUpdateAlert.xib +++ b/Sparkle/uk.lproj/SUUpdateAlert.xib @@ -41,7 +41,7 @@ - + diff --git a/Sparkle/zh_CN.lproj/SUUpdateAlert.xib b/Sparkle/zh_CN.lproj/SUUpdateAlert.xib index 02148ff7..60a343b5 100644 --- a/Sparkle/zh_CN.lproj/SUUpdateAlert.xib +++ b/Sparkle/zh_CN.lproj/SUUpdateAlert.xib @@ -41,7 +41,7 @@ - + diff --git a/Sparkle/zh_TW.lproj/SUUpdateAlert.xib b/Sparkle/zh_TW.lproj/SUUpdateAlert.xib index d95da7c8..b4171c4c 100644 --- a/Sparkle/zh_TW.lproj/SUUpdateAlert.xib +++ b/Sparkle/zh_TW.lproj/SUUpdateAlert.xib @@ -41,7 +41,7 @@ - + diff --git a/TestApplication/SUTestApplicationDelegate.m b/TestApplication/SUTestApplicationDelegate.m index c42f5cfb..10929a4b 100644 --- a/TestApplication/SUTestApplicationDelegate.m +++ b/TestApplication/SUTestApplicationDelegate.m @@ -39,7 +39,7 @@ static NSString * const UPDATED_VERSION = @"2.0"; [[NSApplication sharedApplication] terminate:nil]; } - SUFileManager *fileManager = [SUFileManager fileManagerAllowingAuthorization:NO]; + SUFileManager *fileManager = [SUFileManager defaultManager]; // Locate user's cache directory NSError *cacheError = nil; @@ -54,7 +54,7 @@ static NSString * const UPDATED_VERSION = @"2.0"; assert(bundleIdentifier != nil); // Create a directory that'll be used for our web server listing - NSURL *serverDirectoryURL = [cacheDirectoryURL URLByAppendingPathComponent:bundleIdentifier]; + NSURL *serverDirectoryURL = [[cacheDirectoryURL URLByAppendingPathComponent:bundleIdentifier] URLByAppendingPathComponent:@"ServerData"]; if ([serverDirectoryURL checkResourceIsReachableAndReturnError:nil]) { NSError *removeServerDirectoryError = nil; @@ -73,7 +73,10 @@ static NSString * const UPDATED_VERSION = @"2.0"; assert(bundleURL != nil); // Copy main bundle into server directory - NSURL *destinationBundleURL = [serverDirectoryURL URLByAppendingPathComponent:bundleURL.lastPathComponent]; + NSString *bundleURLLastComponent = bundleURL.lastPathComponent; + assert(bundleURLLastComponent != nil); + + NSURL *destinationBundleURL = [serverDirectoryURL URLByAppendingPathComponent:bundleURLLastComponent]; NSError *copyBundleError = nil; if (![fileManager copyItemAtURL:bundleURL toURL:destinationBundleURL error:©BundleError]) { NSLog(@"Failed to copy main bundle into server directory with error %@", copyBundleError); @@ -87,8 +90,8 @@ static NSString * const UPDATED_VERSION = @"2.0"; assert(infoFileExists); NSMutableDictionary *infoDictionary = [[NSMutableDictionary alloc] initWithContentsOfURL:infoURL]; - infoDictionary[(__bridge NSString *)kCFBundleVersionKey] = UPDATED_VERSION; - infoDictionary[@"CFBundleShortVersionString"] = UPDATED_VERSION; + [infoDictionary setObject:UPDATED_VERSION forKey:(__bridge NSString *)kCFBundleVersionKey]; + [infoDictionary setObject:UPDATED_VERSION forKey:@"CFBundleShortVersionString"]; BOOL wroteInfoFile = [infoDictionary writeToURL:infoURL atomically:NO]; assert(wroteInfoFile); @@ -139,7 +142,9 @@ static NSString * const UPDATED_VERSION = @"2.0"; // Obtain the file attributes to get the file size of our update later NSError *fileAttributesError = nil; - NSDictionary *archiveFileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:archiveURL.path error:&fileAttributesError]; + NSString *archivePath = archiveURL.path; + assert(archivePath != nil); + NSDictionary *archiveFileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:archivePath error:&fileAttributesError]; if (archiveFileAttributes == nil) { NSLog(@"Failed to retrieve file attributes from archive with error %@", fileAttributesError); assert(NO); diff --git a/TestApplication/SUTestWebServer.m b/TestApplication/SUTestWebServer.m index d8093272..2ca31e8e 100644 --- a/TestApplication/SUTestWebServer.m +++ b/TestApplication/SUTestWebServer.m @@ -93,12 +93,12 @@ if (numBytes > 0) { NSString *request = [[NSString alloc] initWithBytes:buffer length:(NSUInteger)numBytes encoding:NSUTF8StringEncoding]; NSArray *lines = [request componentsSeparatedByString:@"\r\n"]; - NSString *requestLine = lines.count >= 3 ? lines[0] : nil; + NSString *requestLine = lines.count >= 3 ? [lines objectAtIndex:0] : nil; NSArray *parts = requestLine ? [requestLine componentsSeparatedByString:@" "] : nil; // Only process GET requests for existing files - if ([parts[0] isEqualToString:@"GET"]) { + if ([[parts objectAtIndex:0] isEqualToString:@"GET"]) { // Use NSURL to strip out query parameters - NSString *path = [NSURL URLWithString:parts[1] relativeToURL:nil].path; + NSString *path = [NSURL URLWithString:[parts objectAtIndex:1] relativeToURL:nil].path; NSString *filePath = [self.workingDirectory stringByAppendingString:path]; BOOL isDir = NO; if (![[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:&isDir] || isDir) { diff --git a/TestApplication/SUUpdateSettingsWindowController.m b/TestApplication/SUUpdateSettingsWindowController.m index 3d651044..24516509 100644 --- a/TestApplication/SUUpdateSettingsWindowController.m +++ b/TestApplication/SUUpdateSettingsWindowController.m @@ -29,4 +29,12 @@ [self.updater checkForUpdates:nil]; } +- (BOOL)validateMenuItem:(NSMenuItem *)menuItem +{ + if (menuItem.action == @selector(checkForUpdates:)) { + return [self.updater validateMenuItem:menuItem]; + } + return YES; +} + @end diff --git a/Tests/Resources/testappcast.xml b/Tests/Resources/testappcast.xml new file mode 100644 index 00000000..e3894b41 --- /dev/null +++ b/Tests/Resources/testappcast.xml @@ -0,0 +1,45 @@ + + + + For unit test only + + Version 2.0 + desc + Sat, 26 Jul 2014 15:20:11 +0000 + + + + + Version 3.0 + + + + + + + + + + Version 4.0 + Sat, 26 Jul 2014 15:20:13 +0000 + + 17.0.0 + + + + Version 5.0 + + 2.0.0 + + + diff --git a/Tests/Resources/testnamespaces.xml b/Tests/Resources/testnamespaces.xml new file mode 100644 index 00000000..94f5f1de --- /dev/null +++ b/Tests/Resources/testnamespaces.xml @@ -0,0 +1,18 @@ + + + + For unit test only + + Version 3.0 + Sat, 26 Jul 2014 15:20:12 +0000 + https://sparkle-project.org/#works + + + + Version 2.0 + desc + Sat, 26 Jul 2014 15:20:11 +0000 + + + + diff --git a/Tests/SUAppcastTest.swift b/Tests/SUAppcastTest.swift new file mode 100644 index 00000000..c5250a60 --- /dev/null +++ b/Tests/SUAppcastTest.swift @@ -0,0 +1,87 @@ +// +// SUAppcastTest.swift +// Sparkle +// +// Created by Kornel on 17/02/2016. +// Copyright © 2016 Sparkle Project. All rights reserved. +// + +import XCTest +import Sparkle; + +class SUAppcastTest: XCTestCase { + + func testParseAppcast() { + let appcast = SUAppcast(); + let testFile = Bundle(for: SUAppcastTest.self).path(forResource: "testappcast", ofType: "xml")!; + let testFileUrl = URL(fileURLWithPath: testFile); + XCTAssertNotNil(testFileUrl); + + do { + let items = try appcast.parseAppcastItems(fromXMLFile: testFileUrl) as! [SUAppcastItem]; + + XCTAssertEqual(4, items.count); + + XCTAssertEqual("Version 2.0", items[0].title); + XCTAssertEqual("desc", items[0].itemDescription); + XCTAssertEqual("Sat, 26 Jul 2014 15:20:11 +0000", items[0].dateString) + + // This is the best release matching our system version + XCTAssertEqual("Version 3.0", items[1].title); + XCTAssertNil(items[1].itemDescription); + XCTAssertNil(items[1].dateString) + + XCTAssertEqual("Version 4.0", items[2].title); + XCTAssertNil(items[2].itemDescription); + XCTAssertEqual("Sat, 26 Jul 2014 15:20:13 +0000", items[2].dateString) + + XCTAssertEqual("Version 5.0", items[3].title); + XCTAssertNil(items[3].itemDescription); + XCTAssertNil(items[3].dateString) + + // Test best appcast item & a delta update item + var deltaItem: SUAppcastItem? = nil + let bestAppcastItem = SUBasicUpdateDriver.bestItem(fromAppcastItems: items, getDeltaItem: &deltaItem, withHostVersion: "1.0", comparator: SUStandardVersionComparator.default()) + + XCTAssertEqual(bestAppcastItem, items[1]) + XCTAssertEqual(deltaItem!.fileURL.lastPathComponent, "3.0_from_1.0.patch") + + // Test latest delta update item available + var latestDeltaItem: SUAppcastItem? = nil + SUBasicUpdateDriver.bestItem(fromAppcastItems: items, getDeltaItem: &latestDeltaItem, withHostVersion: "2.0", comparator: SUStandardVersionComparator.default()) + + XCTAssertEqual(latestDeltaItem!.fileURL.lastPathComponent, "3.0_from_2.0.patch") + + // Test a delta item that does not exist + var nonexistantDeltaItem: SUAppcastItem? = nil + SUBasicUpdateDriver.bestItem(fromAppcastItems: items, getDeltaItem: &nonexistantDeltaItem, withHostVersion: "2.1", comparator: SUStandardVersionComparator.default()) + + XCTAssertNil(nonexistantDeltaItem) + } catch let err as NSError { + NSLog("%@", err); + XCTFail(err.localizedDescription); + } + } + + func testNamespaces() { + let appcast = SUAppcast(); + let testFile = Bundle(for: SUAppcastTest.self).path(forResource: "testnamespaces", ofType: "xml")!; + let testFileUrl = URL(fileURLWithPath: testFile); + XCTAssertNotNil(testFileUrl); + + do { + let items = try appcast.parseAppcastItems(fromXMLFile: testFileUrl) as! [SUAppcastItem]; + + XCTAssertEqual(2, items.count); + + XCTAssertEqual("Version 2.0", items[1].title); + XCTAssertEqual("desc", items[1].itemDescription); + XCTAssertNotNil(items[0].releaseNotesURL); + XCTAssertEqual("https://sparkle-project.org/#works", items[0].releaseNotesURL!.absoluteString); + } catch let err as NSError { + NSLog("%@", err); + XCTFail(err.localizedDescription); + } + } + +} diff --git a/Tests/SUCodeSigningVerifierTest.m b/Tests/SUCodeSigningVerifierTest.m index 95e394f0..918b0550 100644 --- a/Tests/SUCodeSigningVerifierTest.m +++ b/Tests/SUCodeSigningVerifierTest.m @@ -8,22 +8,26 @@ #import #import -#import "NTSynchronousTask.h" #import "SUCodeSigningVerifier.h" +#import "SUFileManager.h" + +#define CALCULATOR_PATH @"/Applications/Calculator.app" @interface SUCodeSigningVerifierTest : XCTestCase -@property (copy) NSString *notSignedAppPath; -@property (copy) NSString *validSignedAppPath; -@property (copy) NSString *invalidSignedAppPath; +@property (copy) NSURL *notSignedAppURL; +@property (copy) NSURL *validSignedAppURL; +@property (copy) NSURL *invalidSignedAppURL; +@property (copy) NSURL *calculatorCopyURL; @end @implementation SUCodeSigningVerifierTest -@synthesize notSignedAppPath = _notSignedAppPath; -@synthesize validSignedAppPath = _validSignedAppPath; -@synthesize invalidSignedAppPath = _invalidSignedAppPath; +@synthesize notSignedAppURL = _notSignedAppURL; +@synthesize validSignedAppURL = _validSignedAppURL; +@synthesize invalidSignedAppURL = _invalidSignedAppURL; +@synthesize calculatorCopyURL = _calculatorCopyURL; - (void)setUp { @@ -31,17 +35,28 @@ NSBundle *unitTestBundle = [NSBundle bundleForClass:[self class]]; NSString *unitTestBundleIdentifier = unitTestBundle.bundleIdentifier; - NSString *zippedAppPath = [unitTestBundle pathForResource:@"SparkleTestCodeSignApp" ofType:@"zip"]; - NSString *tempDir = [NSTemporaryDirectory() stringByAppendingPathComponent:unitTestBundleIdentifier]; + NSString *zippedAppURL = [unitTestBundle pathForResource:@"SparkleTestCodeSignApp" ofType:@"zip"]; + + SUFileManager *fileManager = [SUFileManager defaultManager]; + + NSError *tempError = nil; + NSURL *tempDir = [fileManager makeTemporaryDirectoryWithPreferredName:unitTestBundleIdentifier appropriateForDirectoryURL:[NSURL fileURLWithPath:zippedAppURL] error:&tempError]; + + if (tempDir == nil) { + XCTFail(@"Failed to create temporary directory with error: %@", tempError); + return; + } + NSError *error = nil; - if ([[NSFileManager defaultManager] createDirectoryAtPath:tempDir withIntermediateDirectories:YES attributes:nil error:&error]) { - if ([self unzip:zippedAppPath toPath:tempDir]) { - self.notSignedAppPath = [tempDir stringByAppendingPathComponent:@"SparkleTestCodeSignApp.app"]; + if ([[NSFileManager defaultManager] createDirectoryAtURL:tempDir withIntermediateDirectories:YES attributes:nil error:&error]) { + if ([self unzip:zippedAppURL toPath:tempDir.path]) { + self.notSignedAppURL = [tempDir URLByAppendingPathComponent:@"SparkleTestCodeSignApp.app"]; [self setupValidSignedApp]; + [self setupCalculatorCopy]; [self setupInvalidSignedApp]; } else { - NSLog(@"Failed to unzip %@", zippedAppPath); + NSLog(@"Failed to unzip %@", zippedAppURL); } } else { @@ -52,53 +67,82 @@ - (void)tearDown { [super tearDown]; - - if (self.notSignedAppPath) { - [[NSFileManager defaultManager] removeItemAtPath:self.notSignedAppPath error:nil]; - } - if (self.validSignedAppPath) { - [[NSFileManager defaultManager] removeItemAtPath:self.validSignedAppPath error:nil]; - } - if (self.invalidSignedAppPath) { - [[NSFileManager defaultManager] removeItemAtPath:self.invalidSignedAppPath error:nil]; + + if (self.notSignedAppURL) { + NSURL *tempDir = [self.notSignedAppURL URLByDeletingLastPathComponent]; + [[NSFileManager defaultManager] removeItemAtURL:tempDir error:nil]; } } - (void)setupValidSignedApp { NSError *error = nil; - NSString *tempDir = [self.notSignedAppPath stringByDeletingLastPathComponent]; - NSString *signedAndValid = [tempDir stringByAppendingPathComponent:@"valid-signed.app"]; - if ([[NSFileManager defaultManager] copyItemAtPath:self.notSignedAppPath toPath:signedAndValid error:&error]) { - self.validSignedAppPath = signedAndValid; - if (![self codesignAppPath:self.validSignedAppPath]) { - NSLog(@"Failed to codesign %@", self.validSignedAppPath); - } + NSURL *tempDir = [self.notSignedAppURL URLByDeletingLastPathComponent]; + NSURL *signedAndValid = [tempDir URLByAppendingPathComponent:@"valid-signed.app"]; + + [[NSFileManager defaultManager] removeItemAtURL:signedAndValid error:NULL]; + if (![[NSFileManager defaultManager] copyItemAtURL:self.notSignedAppURL toURL:signedAndValid error:&error]) { + XCTFail("Failed to copy %@ to %@ with error: %@", self.notSignedAppURL, signedAndValid, error); } - else { - NSLog(@"Failed to copy %@ to %@ with error %@", self.notSignedAppPath, signedAndValid, error); + + self.validSignedAppURL = signedAndValid; + + if (![self codesignAppURL:self.validSignedAppURL]) { + XCTFail(@"Failed to codesign %@", self.validSignedAppURL); } } +- (void)setupCalculatorCopy +{ + NSURL *tempDir = [self.notSignedAppURL URLByDeletingLastPathComponent]; + NSURL *calculatorCopy = [tempDir URLByAppendingPathComponent:@"calc.app"]; + + [[NSFileManager defaultManager] removeItemAtURL:calculatorCopy error:NULL]; + + // Make a copy of the signed calculator app so we can match signatures later + // Matching signatures on ad-hoc signed apps does *not* work + NSError *copyError = nil; + // Don't check the return value of this operation - seems like on 10.11 the API can say it fails even though the operation really succeeds, + // which sounds like some kind of (SIP / attribute?) bug + [[NSFileManager defaultManager] copyItemAtURL:[NSURL fileURLWithPath:CALCULATOR_PATH] toURL:calculatorCopy error:©Error]; + + if (![calculatorCopy checkResourceIsReachableAndReturnError:nil]) { + XCTFail(@"Copied calculator application does not exist"); + } + + // Alter the signed copy slightly, this won't invalidate signature matching (although it will invalidate the integrity part of the signature) + // Which is what we want. If a user alters an app bundle, we should still be able to update as long as its identity is still valid + NSError *removeError = nil; + NSURL *calculatorPkgInfo = [[calculatorCopy URLByAppendingPathComponent:@"Contents"] URLByAppendingPathComponent:@"PkgInfo"]; + XCTAssertNotNil(calculatorPkgInfo); + if (![[NSFileManager defaultManager] removeItemAtURL:calculatorPkgInfo error:&removeError]) { + XCTFail(@"Failed to remove file in calculator copy with error: %@", removeError); + } + + self.calculatorCopyURL = calculatorCopy; +} + - (void)setupInvalidSignedApp { NSError *error = nil; - NSString *tempDir = [self.notSignedAppPath stringByDeletingLastPathComponent]; - NSString *signedAndInvalid = [tempDir stringByAppendingPathComponent:@"invalid-signed.app"]; - if ([[NSFileManager defaultManager] copyItemAtPath:self.notSignedAppPath toPath:signedAndInvalid error:&error]) { - self.invalidSignedAppPath = signedAndInvalid; - if ([self codesignAppPath:self.invalidSignedAppPath]) { - NSString *fileInAppBundleToRemove = [self.invalidSignedAppPath stringByAppendingPathComponent:@"Contents/Resources/test_app_only_dsa_pub.pem"]; - if (![[NSFileManager defaultManager] removeItemAtPath:fileInAppBundleToRemove error:&error]) { + NSURL *tempDir = [self.notSignedAppURL URLByDeletingLastPathComponent]; + NSURL *signedAndInvalid = [tempDir URLByAppendingPathComponent:@"invalid-signed.app"]; + + [[NSFileManager defaultManager] removeItemAtURL:signedAndInvalid error:NULL]; + if ([[NSFileManager defaultManager] copyItemAtURL:self.notSignedAppURL toURL:signedAndInvalid error:&error]) { + self.invalidSignedAppURL = signedAndInvalid; + if ([self codesignAppURL:self.invalidSignedAppURL]) { + NSURL *fileInAppBundleToRemove = [self.invalidSignedAppURL URLByAppendingPathComponent:@"Contents/Resources/test_app_only_dsa_pub.pem"]; + if (![[NSFileManager defaultManager] removeItemAtURL:fileInAppBundleToRemove error:&error]) { NSLog(@"Failed to remove %@ with error %@", fileInAppBundleToRemove, error); } } else { - NSLog(@"Failed to codesign %@", self.invalidSignedAppPath); + NSLog(@"Failed to codesign %@", self.invalidSignedAppURL); } } else { - NSLog(@"Failed to copy %@ to %@ with error %@", self.notSignedAppPath, signedAndInvalid, error); + NSLog(@"Failed to copy %@ to %@ with error %@", self.notSignedAppURL, signedAndInvalid, error); } } @@ -107,10 +151,14 @@ BOOL success = NO; @try { - NTSynchronousTask *task = [[NTSynchronousTask alloc] init]; - NSArray *arguments = @[ zipPath ]; - [task run:@"/usr/bin/unzip" directory:destPath withArgs:arguments input:nil]; - success = ([task result] == 0); + NSTask *task = [[NSTask alloc] init]; + task.launchPath = @"/usr/bin/unzip"; + task.currentDirectoryPath = destPath; + task.arguments = @[zipPath]; + + [task launch]; + [task waitUntilExit]; + success = (task.terminationStatus == 0); } @catch (NSException *exception) { @@ -119,16 +167,16 @@ return success; } -- (BOOL)codesignAppPath:(NSString *)appPath +- (BOOL)codesignAppURL:(NSURL *)appPath { BOOL success = NO; @try { // ad-hoc signing with the dash NSArray *arguments = @[ @"--force", @"--deep", @"--sign", @"-", appPath ]; - NTSynchronousTask *task = [[NTSynchronousTask alloc] init]; - [task run:@"/usr/bin/codesign" directory:nil withArgs:arguments input:nil]; - success = ([task result] == 0); + NSTask *task = [NSTask launchedTaskWithLaunchPath:@"/usr/bin/codesign" arguments:arguments]; + [task waitUntilExit]; + success = (task.terminationStatus == 0); } @catch (NSException *exception) { @@ -139,38 +187,61 @@ - (void)testUnsignedApp { - XCTAssertFalse([SUCodeSigningVerifier applicationAtPathIsCodeSigned:self.notSignedAppPath], @"App not expected to be code signed"); + XCTAssertFalse([SUCodeSigningVerifier bundleAtURLIsCodeSigned:self.notSignedAppURL], @"App not expected to be code signed"); NSError *error = nil; - XCTAssertFalse([SUCodeSigningVerifier codeSignatureIsValidAtPath:self.notSignedAppPath error:&error], @"signature should not be valid as it's not code signed"); + XCTAssertFalse([SUCodeSigningVerifier codeSignatureIsValidAtBundleURL:self.notSignedAppURL error:&error], @"signature should not be valid as it's not code signed"); XCTAssertNotNil(error, @"error should not be nil"); } - (void)testValidSignedApp { - XCTAssertTrue([SUCodeSigningVerifier applicationAtPathIsCodeSigned:self.validSignedAppPath], @"App expected to be code signed"); + XCTAssertTrue([SUCodeSigningVerifier bundleAtURLIsCodeSigned:self.validSignedAppURL], @"App expected to be code signed"); NSError *error = nil; - XCTAssertTrue([SUCodeSigningVerifier codeSignatureIsValidAtPath:self.validSignedAppPath error:&error], @"signature should be valid"); + XCTAssertTrue([SUCodeSigningVerifier codeSignatureIsValidAtBundleURL:self.validSignedAppURL error:&error], @"signature should be valid"); XCTAssertNil(error, @"error should be nil"); } - (void)testValidSignedCalculatorApp { - NSString *appPath = @"/Applications/Calculator.app"; - XCTAssertTrue([SUCodeSigningVerifier applicationAtPathIsCodeSigned:appPath], @"App expected to be code signed"); + NSURL *appPath = [NSURL fileURLWithPath:CALCULATOR_PATH]; + XCTAssertTrue([SUCodeSigningVerifier bundleAtURLIsCodeSigned:appPath], @"App expected to be code signed"); NSError *error = nil; - XCTAssertTrue([SUCodeSigningVerifier codeSignatureIsValidAtPath:appPath error:&error], @"signature should be valid"); + XCTAssertTrue([SUCodeSigningVerifier codeSignatureIsValidAtBundleURL:appPath error:&error], @"signature should be valid"); XCTAssertNil(error, @"error should be nil"); } +- (void)testValidMatchingSelf +{ + NSError *error = nil; + NSURL *appPath = [NSURL fileURLWithPath:CALCULATOR_PATH]; + + XCTAssertTrue([SUCodeSigningVerifier codeSignatureAtBundleURL:appPath matchesSignatureAtBundleURL:appPath error:&error], @"Our valid signed app expected to having matching signature to itself"); +} + +- (void)testValidMatching +{ + // We can't test our own app because matching with ad-hoc signed apps understandably does not succeed + NSError *error = nil; + NSURL *appPath = [NSURL fileURLWithPath:CALCULATOR_PATH]; + XCTAssertTrue([SUCodeSigningVerifier codeSignatureAtBundleURL:appPath matchesSignatureAtBundleURL:self.calculatorCopyURL error:&error], @"The calculator app is expected to have matching identity signature to its altered copy"); +} + +- (void)testInvalidMatching +{ + NSURL *appPath = [NSURL fileURLWithPath:CALCULATOR_PATH]; + NSError *error = nil; + XCTAssertFalse([SUCodeSigningVerifier codeSignatureAtBundleURL:appPath matchesSignatureAtBundleURL:self.validSignedAppURL error:&error], @"Calculator app bundle expected to have different signature than our valid signed app"); +} + - (void)testInvalidSignedApp { - XCTAssertTrue([SUCodeSigningVerifier applicationAtPathIsCodeSigned:self.invalidSignedAppPath], @"App expected to be code signed, but signature is invalid"); + XCTAssertTrue([SUCodeSigningVerifier bundleAtURLIsCodeSigned:self.invalidSignedAppURL], @"App expected to be code signed, but signature is invalid"); NSError *error = nil; - XCTAssertFalse([SUCodeSigningVerifier codeSignatureIsValidAtPath:self.invalidSignedAppPath error:&error], @"signature should not be valid"); + XCTAssertFalse([SUCodeSigningVerifier codeSignatureIsValidAtBundleURL:self.invalidSignedAppURL error:&error], @"signature should not be valid"); XCTAssertNotNil(error, @"error should not be nil"); } diff --git a/Tests/SUFileManagerTest.swift b/Tests/SUFileManagerTest.swift index 260ff2f1..fe5cd6d7 100644 --- a/Tests/SUFileManagerTest.swift +++ b/Tests/SUFileManagerTest.swift @@ -10,269 +10,307 @@ import XCTest class SUFileManagerTest: XCTestCase { - func makeTempFiles(testBlock: (SUFileManager, NSURL, NSURL, NSURL, NSURL) -> Void) + func makeTempFiles(_ testBlock: (SUFileManager, URL, URL, URL, URL, URL, URL) -> Void) { - let fileManager = SUFileManager(allowingAuthorization: false) + let fileManager = SUFileManager.default() - let tempDirectoryURL = try! fileManager.makeTemporaryDirectoryWithPreferredName("Sparkle Unit Test Data", appropriateForDirectoryURL: NSURL(fileURLWithPath: NSHomeDirectory())) + let tempDirectoryURL = try! fileManager?.makeTemporaryDirectory(withPreferredName: "Sparkle Unit Test Data", appropriateForDirectoryURL: URL(fileURLWithPath: NSHomeDirectory())) defer { - try! fileManager.removeItemAtURL(tempDirectoryURL) + try! fileManager?.removeItem(at: tempDirectoryURL) } - let ordinaryFileURL = tempDirectoryURL.URLByAppendingPathComponent("a file written by sparkles unit tests") - try! "foo".dataUsingEncoding(NSUTF8StringEncoding)!.writeToURL(ordinaryFileURL, options: .DataWritingAtomic) + let ordinaryFileURL = tempDirectoryURL?.appendingPathComponent("a file written by sparkles unit tests") + try! "foo".data(using: String.Encoding.utf8)!.write(to: ordinaryFileURL!, options: .atomic) - let directoryURL = tempDirectoryURL.URLByAppendingPathComponent("a directory written by sparkles unit tests") - try! NSFileManager.defaultManager().createDirectoryAtURL(directoryURL, withIntermediateDirectories: false, attributes: nil) + let directoryURL = tempDirectoryURL?.appendingPathComponent("a directory written by sparkles unit tests") + try! FileManager.default.createDirectory(at: directoryURL!, withIntermediateDirectories: false, attributes: nil) - let fileInDirectoryURL = directoryURL.URLByAppendingPathComponent("a file inside a directory written by sparkles unit tests") - try! "bar baz".dataUsingEncoding(NSUTF8StringEncoding)!.writeToURL(fileInDirectoryURL, options: .DataWritingAtomic) + let fileInDirectoryURL = directoryURL?.appendingPathComponent("a file inside a directory written by sparkles unit tests") + try! "bar baz".data(using: String.Encoding.utf8)!.write(to: fileInDirectoryURL!, options: .atomic) - testBlock(fileManager, tempDirectoryURL, ordinaryFileURL, directoryURL, fileInDirectoryURL) + let validSymlinkURL = tempDirectoryURL?.appendingPathComponent("symlink test") + try! FileManager.default.createSymbolicLink(at: validSymlinkURL!, withDestinationURL: directoryURL!) + + let invalidSymlinkURL = tempDirectoryURL?.appendingPathComponent("symlink test 2") + try! FileManager.default.createSymbolicLink(at: invalidSymlinkURL!, withDestinationURL: (tempDirectoryURL?.appendingPathComponent("does not exist"))!) + + testBlock(fileManager!, tempDirectoryURL!, ordinaryFileURL!, directoryURL!, fileInDirectoryURL!, validSymlinkURL!, invalidSymlinkURL!) } func testMoveFiles() { - makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL in - XCTAssertNil(try? fileManager.moveItemAtURL(ordinaryFileURL, toURL: directoryURL)) - XCTAssertNil(try? fileManager.moveItemAtURL(ordinaryFileURL, toURL: directoryURL.URLByAppendingPathComponent("foo").URLByAppendingPathComponent("bar"))) - XCTAssertNil(try? fileManager.moveItemAtURL(rootURL.URLByAppendingPathComponent("does not exist"), toURL: directoryURL)) + makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL, validSymlinkURL, invalidSymlinkURL in + XCTAssertNil(try? fileManager.moveItem(at: ordinaryFileURL, to: directoryURL)) + XCTAssertNil(try? fileManager.moveItem(at: ordinaryFileURL, to: directoryURL.appendingPathComponent("foo").appendingPathComponent("bar"))) + XCTAssertNil(try? fileManager.moveItem(at: rootURL.appendingPathComponent("does not exist"), to: directoryURL)) - let newFileURL = (ordinaryFileURL.URLByDeletingLastPathComponent?.URLByAppendingPathComponent("new file"))! - try! fileManager.moveItemAtURL(ordinaryFileURL, toURL: newFileURL) - XCTAssertFalse(fileManager._itemExistsAtURL(ordinaryFileURL)) - XCTAssertTrue(fileManager._itemExistsAtURL(newFileURL)) + let newFileURL = (ordinaryFileURL.deletingLastPathComponent().appendingPathComponent("new file")) + try! fileManager.moveItem(at: ordinaryFileURL, to: newFileURL) + XCTAssertFalse(fileManager._itemExists(at: ordinaryFileURL)) + XCTAssertTrue(fileManager._itemExists(at: newFileURL)) - let newDirectoryURL = (ordinaryFileURL.URLByDeletingLastPathComponent?.URLByAppendingPathComponent("new directory"))! - try! fileManager.moveItemAtURL(directoryURL, toURL: newDirectoryURL) - XCTAssertFalse(fileManager._itemExistsAtURL(directoryURL)) - XCTAssertTrue(fileManager._itemExistsAtURL(newDirectoryURL)) - XCTAssertFalse(fileManager._itemExistsAtURL(fileInDirectoryURL)) - XCTAssertTrue(fileManager._itemExistsAtURL(newDirectoryURL.URLByAppendingPathComponent(fileInDirectoryURL.lastPathComponent!))) + let newValidSymlinkURL = (ordinaryFileURL.deletingLastPathComponent().appendingPathComponent("new symlink")) + try! fileManager.moveItem(at: validSymlinkURL, to: newValidSymlinkURL) + XCTAssertFalse(fileManager._itemExists(at: validSymlinkURL)) + XCTAssertTrue(fileManager._itemExists(at: newValidSymlinkURL)) + XCTAssertTrue(fileManager._itemExists(at: directoryURL)) + + let newInvalidSymlinkURL = (ordinaryFileURL.deletingLastPathComponent().appendingPathComponent("new invalid symlink")) + try! fileManager.moveItem(at: invalidSymlinkURL, to: newInvalidSymlinkURL) + XCTAssertFalse(fileManager._itemExists(at: invalidSymlinkURL)) + XCTAssertTrue(fileManager._itemExists(at: newValidSymlinkURL)) + + let newDirectoryURL = (ordinaryFileURL.deletingLastPathComponent().appendingPathComponent("new directory")) + try! fileManager.moveItem(at: directoryURL, to: newDirectoryURL) + XCTAssertFalse(fileManager._itemExists(at: directoryURL)) + XCTAssertTrue(fileManager._itemExists(at: newDirectoryURL)) + XCTAssertFalse(fileManager._itemExists(at: fileInDirectoryURL)) + XCTAssertTrue(fileManager._itemExists(at: newDirectoryURL.appendingPathComponent(fileInDirectoryURL.lastPathComponent))) } } func testMoveFilesToTrash() { - makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL in - XCTAssertNil(try? fileManager.moveItemAtURLToTrash(rootURL.URLByAppendingPathComponent("does not exist"))) + makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL, validSymlinkURL, invalidSymlinkURL in + XCTAssertNil(try? fileManager.moveItemAtURL(toTrash: rootURL.appendingPathComponent("does not exist"))) - let trashURL = try! NSFileManager.defaultManager().URLForDirectory(.TrashDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false) + let trashURL = try! FileManager.default.url(for: .trashDirectory, in: .userDomainMask, appropriateFor: nil, create: false) - try! fileManager.moveItemAtURLToTrash(ordinaryFileURL) - XCTAssertFalse(fileManager._itemExistsAtURL(ordinaryFileURL)) + try! fileManager.moveItemAtURL(toTrash: ordinaryFileURL) + XCTAssertFalse(fileManager._itemExists(at: ordinaryFileURL)) - let ordinaryFileTrashURL = trashURL.URLByAppendingPathComponent(ordinaryFileURL.lastPathComponent!) - XCTAssertTrue(fileManager._itemExistsAtURL(ordinaryFileTrashURL)) - try! fileManager.removeItemAtURL(ordinaryFileTrashURL) + let ordinaryFileTrashURL = trashURL.appendingPathComponent(ordinaryFileURL.lastPathComponent) + XCTAssertTrue(fileManager._itemExists(at: ordinaryFileTrashURL)) + try! fileManager.removeItem(at: ordinaryFileTrashURL) - try! fileManager.moveItemAtURLToTrash(directoryURL) - XCTAssertFalse(fileManager._itemExistsAtURL(directoryURL)) - XCTAssertFalse(fileManager._itemExistsAtURL(fileInDirectoryURL)) + let validSymlinkTrashURL = trashURL.appendingPathComponent(validSymlinkURL.lastPathComponent) + try! fileManager.moveItemAtURL(toTrash: validSymlinkURL) + XCTAssertTrue(fileManager._itemExists(at: validSymlinkTrashURL)) + XCTAssertTrue(fileManager._itemExists(at: directoryURL)) + try! fileManager.removeItem(at: validSymlinkTrashURL) - let directoryTrashURL = trashURL.URLByAppendingPathComponent(directoryURL.lastPathComponent!) - XCTAssertTrue(fileManager._itemExistsAtURL(directoryTrashURL)) - XCTAssertTrue(fileManager._itemExistsAtURL(directoryTrashURL.URLByAppendingPathComponent(fileInDirectoryURL.lastPathComponent!))) + try! fileManager.moveItemAtURL(toTrash: directoryURL) + XCTAssertFalse(fileManager._itemExists(at: directoryURL)) + XCTAssertFalse(fileManager._itemExists(at: fileInDirectoryURL)) - try! fileManager.removeItemAtURL(directoryTrashURL) + let directoryTrashURL = trashURL.appendingPathComponent(directoryURL.lastPathComponent) + XCTAssertTrue(fileManager._itemExists(at: directoryTrashURL)) + XCTAssertTrue(fileManager._itemExists(at: directoryTrashURL.appendingPathComponent(fileInDirectoryURL.lastPathComponent))) + + try! fileManager.removeItem(at: directoryTrashURL) } } func testCopyFiles() { - makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL in - XCTAssertNil(try? fileManager.copyItemAtURL(ordinaryFileURL, toURL: directoryURL)) - XCTAssertNil(try? fileManager.copyItemAtURL(ordinaryFileURL, toURL: directoryURL.URLByAppendingPathComponent("foo").URLByAppendingPathComponent("bar"))) - XCTAssertNil(try? fileManager.copyItemAtURL(rootURL.URLByAppendingPathComponent("does not exist"), toURL: directoryURL)) + makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL, validSymlinkURL, invalidSymlinkURL in + XCTAssertNil(try? fileManager.copyItem(at: ordinaryFileURL, to: directoryURL)) + XCTAssertNil(try? fileManager.copyItem(at: ordinaryFileURL, to: directoryURL.appendingPathComponent("foo").appendingPathComponent("bar"))) + XCTAssertNil(try? fileManager.copyItem(at: rootURL.appendingPathComponent("does not exist"), to: directoryURL)) - let newFileURL = (ordinaryFileURL.URLByDeletingLastPathComponent?.URLByAppendingPathComponent("new file"))! - try! fileManager.copyItemAtURL(ordinaryFileURL, toURL: newFileURL) - XCTAssertTrue(fileManager._itemExistsAtURL(ordinaryFileURL)) - XCTAssertTrue(fileManager._itemExistsAtURL(newFileURL)) + let newFileURL = (ordinaryFileURL.deletingLastPathComponent().appendingPathComponent("new file")) + try! fileManager.copyItem(at: ordinaryFileURL, to: newFileURL) + XCTAssertTrue(fileManager._itemExists(at: ordinaryFileURL)) + XCTAssertTrue(fileManager._itemExists(at: newFileURL)) - let newDirectoryURL = (ordinaryFileURL.URLByDeletingLastPathComponent?.URLByAppendingPathComponent("new directory"))! - try! fileManager.copyItemAtURL(directoryURL, toURL: newDirectoryURL) - XCTAssertTrue(fileManager._itemExistsAtURL(directoryURL)) - XCTAssertTrue(fileManager._itemExistsAtURL(newDirectoryURL)) - XCTAssertTrue(fileManager._itemExistsAtURL(fileInDirectoryURL)) - XCTAssertTrue(fileManager._itemExistsAtURL(newDirectoryURL.URLByAppendingPathComponent(fileInDirectoryURL.lastPathComponent!))) + let newSymlinkURL = (ordinaryFileURL.deletingLastPathComponent().appendingPathComponent("new symlink file")) + try! fileManager.copyItem(at: invalidSymlinkURL, to: newSymlinkURL) + XCTAssertTrue(fileManager._itemExists(at: newSymlinkURL)) + + let newDirectoryURL = (ordinaryFileURL.deletingLastPathComponent().appendingPathComponent("new directory")) + try! fileManager.copyItem(at: directoryURL, to: newDirectoryURL) + XCTAssertTrue(fileManager._itemExists(at: directoryURL)) + XCTAssertTrue(fileManager._itemExists(at: newDirectoryURL)) + XCTAssertTrue(fileManager._itemExists(at: fileInDirectoryURL)) + XCTAssertTrue(fileManager._itemExists(at: newDirectoryURL.appendingPathComponent(fileInDirectoryURL.lastPathComponent))) } } func testRemoveFiles() { - makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL in - XCTAssertNil(try? fileManager.removeItemAtURL(rootURL.URLByAppendingPathComponent("does not exist"))) + makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL, validSymlinkURL, invalidSymlinkURL in + XCTAssertNil(try? fileManager.removeItem(at: rootURL.appendingPathComponent("does not exist"))) - try! fileManager.removeItemAtURL(ordinaryFileURL) - XCTAssertFalse(fileManager._itemExistsAtURL(ordinaryFileURL)) + try! fileManager.removeItem(at: ordinaryFileURL) + XCTAssertFalse(fileManager._itemExists(at: ordinaryFileURL)) - try! fileManager.removeItemAtURL(directoryURL) - XCTAssertFalse(fileManager._itemExistsAtURL(directoryURL)) - XCTAssertFalse(fileManager._itemExistsAtURL(fileInDirectoryURL)) + try! fileManager.removeItem(at: validSymlinkURL) + XCTAssertFalse(fileManager._itemExists(at: validSymlinkURL)) + XCTAssertTrue(fileManager._itemExists(at: directoryURL)) + + try! fileManager.removeItem(at: directoryURL) + XCTAssertFalse(fileManager._itemExists(at: directoryURL)) + XCTAssertFalse(fileManager._itemExists(at: fileInDirectoryURL)) } } func testReleaseFilesFromQuarantine() { - makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL in - try! fileManager.releaseItemFromQuarantineAtRootURL(ordinaryFileURL) - try! fileManager.releaseItemFromQuarantineAtRootURL(directoryURL) + makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL, validSymlinkURL, invalidSymlinkURL in + try! fileManager.releaseItemFromQuarantine(atRootURL: ordinaryFileURL) + try! fileManager.releaseItemFromQuarantine(atRootURL: directoryURL) + try! fileManager.releaseItemFromQuarantine(atRootURL: validSymlinkURL) - let quarantineData = "does not really matter what is here".cStringUsingEncoding(NSUTF8StringEncoding)! + let quarantineData = "does not really matter what is here".cString(using: String.Encoding.utf8)! let quarantineDataLength = Int(strlen(quarantineData)) - XCTAssertEqual(0, setxattr(ordinaryFileURL.path!, SUAppleQuarantineIdentifier, quarantineData, quarantineDataLength, 0, XATTR_CREATE)) - XCTAssertGreaterThan(getxattr(ordinaryFileURL.path!, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW), 0) + XCTAssertEqual(0, setxattr(ordinaryFileURL.path, SUAppleQuarantineIdentifier, quarantineData, quarantineDataLength, 0, XATTR_CREATE)) + XCTAssertGreaterThan(getxattr(ordinaryFileURL.path, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW), 0) - try! fileManager.releaseItemFromQuarantineAtRootURL(ordinaryFileURL) - XCTAssertEqual(-1, getxattr(ordinaryFileURL.path!, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW)) + try! fileManager.releaseItemFromQuarantine(atRootURL: ordinaryFileURL) + XCTAssertEqual(-1, getxattr(ordinaryFileURL.path, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW)) - XCTAssertEqual(0, setxattr(directoryURL.path!, SUAppleQuarantineIdentifier, quarantineData, quarantineDataLength, 0, XATTR_CREATE)) - XCTAssertGreaterThan(getxattr(directoryURL.path!, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW), 0) + XCTAssertEqual(0, setxattr(directoryURL.path, SUAppleQuarantineIdentifier, quarantineData, quarantineDataLength, 0, XATTR_CREATE)) + XCTAssertGreaterThan(getxattr(directoryURL.path, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW), 0) - XCTAssertEqual(0, setxattr(fileInDirectoryURL.path!, SUAppleQuarantineIdentifier, quarantineData, quarantineDataLength, 0, XATTR_CREATE)) - XCTAssertGreaterThan(getxattr(fileInDirectoryURL.path!, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW), 0) + XCTAssertEqual(0, setxattr(fileInDirectoryURL.path, SUAppleQuarantineIdentifier, quarantineData, quarantineDataLength, 0, XATTR_CREATE)) + XCTAssertGreaterThan(getxattr(fileInDirectoryURL.path, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW), 0) - try! fileManager.releaseItemFromQuarantineAtRootURL(directoryURL) + // Extended attributes can't be set on symbolic links currently + try! fileManager.releaseItemFromQuarantine(atRootURL: validSymlinkURL) + XCTAssertGreaterThan(getxattr(directoryURL.path, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW), 0) + XCTAssertEqual(-1, getxattr(validSymlinkURL.path, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW)) - XCTAssertEqual(-1, getxattr(directoryURL.path!, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW)) - XCTAssertEqual(-1, getxattr(fileInDirectoryURL.path!, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW)) + try! fileManager.releaseItemFromQuarantine(atRootURL: directoryURL) + + XCTAssertEqual(-1, getxattr(directoryURL.path, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW)) + XCTAssertEqual(-1, getxattr(fileInDirectoryURL.path, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW)) } } - func groupIDAtPath(path: String) -> gid_t + func groupIDAtPath(_ path: String) -> gid_t { - let attributes = try! NSFileManager.defaultManager().attributesOfItemAtPath(path) - let groupID = attributes[NSFileGroupOwnerAccountID] as! NSNumber - return groupID.unsignedIntValue + let attributes = try! FileManager.default.attributesOfItem(atPath: path) + let groupID = attributes[FileAttributeKey.groupOwnerAccountID] as! NSNumber + return groupID.uint32Value } // Only the super user can alter user IDs, so changing user IDs is not tested here // Instead we try to change the group ID - we just have to be a member of that group func testAlterFilesGroupID() { - makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL in - XCTAssertNil(try? fileManager.changeOwnerAndGroupOfItemAtRootURL(ordinaryFileURL, toMatchURL: rootURL.URLByAppendingPathComponent("does not exist"))) + makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL, validSymlinkURL, invalidSymlinkURL in + XCTAssertNil(try? fileManager.changeOwnerAndGroupOfItem(atRootURL: ordinaryFileURL, toMatch: rootURL.appendingPathComponent("does not exist"))) - XCTAssertNil(try? fileManager.changeOwnerAndGroupOfItemAtRootURL(rootURL.URLByAppendingPathComponent("does not exist"), toMatchURL: ordinaryFileURL)) + XCTAssertNil(try? fileManager.changeOwnerAndGroupOfItem(atRootURL: rootURL.appendingPathComponent("does not exist"), toMatch: ordinaryFileURL)) let everyoneGroup = getgrnam("everyone") - let everyoneGroupID = everyoneGroup.memory.gr_gid + let everyoneGroupID = everyoneGroup?.pointee.gr_gid let staffGroup = getgrnam("staff") - let staffGroupID = staffGroup.memory.gr_gid + let staffGroupID = staffGroup?.pointee.gr_gid XCTAssertNotEqual(staffGroupID, everyoneGroupID) - XCTAssertEqual(staffGroupID, self.groupIDAtPath(ordinaryFileURL.path!)) - XCTAssertEqual(staffGroupID, self.groupIDAtPath(directoryURL.path!)) - XCTAssertEqual(staffGroupID, self.groupIDAtPath(fileInDirectoryURL.path!)) + XCTAssertEqual(staffGroupID, self.groupIDAtPath(ordinaryFileURL.path)) + XCTAssertEqual(staffGroupID, self.groupIDAtPath(directoryURL.path)) + XCTAssertEqual(staffGroupID, self.groupIDAtPath(fileInDirectoryURL.path)) + XCTAssertEqual(staffGroupID, self.groupIDAtPath(validSymlinkURL.path)) + + try! fileManager.changeOwnerAndGroupOfItem(atRootURL: fileInDirectoryURL, toMatch: ordinaryFileURL) + try! fileManager.changeOwnerAndGroupOfItem(atRootURL: ordinaryFileURL, toMatch: ordinaryFileURL) + try! fileManager.changeOwnerAndGroupOfItem(atRootURL: validSymlinkURL, toMatch: ordinaryFileURL) - try! fileManager.changeOwnerAndGroupOfItemAtRootURL(fileInDirectoryURL, toMatchURL: ordinaryFileURL) - try! fileManager.changeOwnerAndGroupOfItemAtRootURL(ordinaryFileURL, toMatchURL: ordinaryFileURL) + XCTAssertEqual(staffGroupID, self.groupIDAtPath(ordinaryFileURL.path)) + XCTAssertEqual(staffGroupID, self.groupIDAtPath(directoryURL.path)) + XCTAssertEqual(staffGroupID, self.groupIDAtPath(validSymlinkURL.path)) - XCTAssertEqual(staffGroupID, self.groupIDAtPath(ordinaryFileURL.path!)) - XCTAssertEqual(staffGroupID, self.groupIDAtPath(directoryURL.path!)) + XCTAssertEqual(0, chown(ordinaryFileURL.path, getuid(), everyoneGroupID!)) + XCTAssertEqual(everyoneGroupID, self.groupIDAtPath(ordinaryFileURL.path)) - XCTAssertEqual(0, chown(ordinaryFileURL.path!, getuid(), everyoneGroupID)) - XCTAssertEqual(everyoneGroupID, self.groupIDAtPath(ordinaryFileURL.path!)) + try! fileManager.changeOwnerAndGroupOfItem(atRootURL: fileInDirectoryURL, toMatch: ordinaryFileURL) + XCTAssertEqual(everyoneGroupID, self.groupIDAtPath(fileInDirectoryURL.path)) - try! fileManager.changeOwnerAndGroupOfItemAtRootURL(fileInDirectoryURL, toMatchURL: ordinaryFileURL) - XCTAssertEqual(everyoneGroupID, self.groupIDAtPath(fileInDirectoryURL.path!)) + try! fileManager.changeOwnerAndGroupOfItem(atRootURL: fileInDirectoryURL, toMatch: directoryURL) + XCTAssertEqual(staffGroupID, self.groupIDAtPath(fileInDirectoryURL.path)) - try! fileManager.changeOwnerAndGroupOfItemAtRootURL(fileInDirectoryURL, toMatchURL: directoryURL) - XCTAssertEqual(staffGroupID, self.groupIDAtPath(fileInDirectoryURL.path!)) + try! fileManager.changeOwnerAndGroupOfItem(atRootURL: validSymlinkURL, toMatch: ordinaryFileURL) + XCTAssertEqual(everyoneGroupID, self.groupIDAtPath(validSymlinkURL.path)) - try! fileManager.changeOwnerAndGroupOfItemAtRootURL(directoryURL, toMatchURL: ordinaryFileURL) - XCTAssertEqual(everyoneGroupID, self.groupIDAtPath(directoryURL.path!)) - XCTAssertEqual(everyoneGroupID, self.groupIDAtPath(fileInDirectoryURL.path!)) + try! fileManager.changeOwnerAndGroupOfItem(atRootURL: directoryURL, toMatch: ordinaryFileURL) + XCTAssertEqual(everyoneGroupID, self.groupIDAtPath(directoryURL.path)) + XCTAssertEqual(everyoneGroupID, self.groupIDAtPath(fileInDirectoryURL.path)) } } func testUpdateFileModificationTime() { - makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL in - XCTAssertNil(try? fileManager.updateModificationAndAccessTimeOfItemAtURL(rootURL.URLByAppendingPathComponent("does not exist"))) + makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL, validSymlinkURL, invalidSymlinkURL in + XCTAssertNil(try? fileManager.updateModificationAndAccessTimeOfItem(at: rootURL.appendingPathComponent("does not exist"))) - let oldOrdinaryFileAttributes = try! NSFileManager.defaultManager().attributesOfItemAtPath(ordinaryFileURL.path!) - let oldDirectoryAttributes = try! NSFileManager.defaultManager().attributesOfItemAtPath(directoryURL.path!) + let oldOrdinaryFileAttributes = try! FileManager.default.attributesOfItem(atPath: ordinaryFileURL.path) + let oldDirectoryAttributes = try! FileManager.default.attributesOfItem(atPath: directoryURL.path) + let oldValidSymlinkAttributes = try! FileManager.default.attributesOfItem(atPath: validSymlinkURL.path) sleep(1); // wait for clock to advance - try! fileManager.updateModificationAndAccessTimeOfItemAtURL(ordinaryFileURL) - try! fileManager.updateModificationAndAccessTimeOfItemAtURL(directoryURL) + try! fileManager.updateModificationAndAccessTimeOfItem(at: ordinaryFileURL) + try! fileManager.updateModificationAndAccessTimeOfItem(at: directoryURL) + try! fileManager.updateModificationAndAccessTimeOfItem(at: validSymlinkURL) - let newOrdinaryFileAttributes = try! NSFileManager.defaultManager().attributesOfItemAtPath(ordinaryFileURL.path!) - XCTAssertGreaterThan((newOrdinaryFileAttributes[NSFileModificationDate] as! NSDate).timeIntervalSinceDate(oldOrdinaryFileAttributes[NSFileModificationDate] as! NSDate), 0) + let newOrdinaryFileAttributes = try! FileManager.default.attributesOfItem(atPath: ordinaryFileURL.path) + XCTAssertGreaterThan((newOrdinaryFileAttributes[FileAttributeKey.modificationDate] as! Date).timeIntervalSince(oldOrdinaryFileAttributes[FileAttributeKey.modificationDate] as! Date), 0) - let newDirectoryAttributes = try! NSFileManager.defaultManager().attributesOfItemAtPath(directoryURL.path!) - XCTAssertGreaterThan((newDirectoryAttributes[NSFileModificationDate] as! NSDate).timeIntervalSinceDate(oldDirectoryAttributes[NSFileModificationDate] as! NSDate), 0) + let newDirectoryAttributes = try! FileManager.default.attributesOfItem(atPath: directoryURL.path) + XCTAssertGreaterThan((newDirectoryAttributes[FileAttributeKey.modificationDate] as! Date).timeIntervalSince(oldDirectoryAttributes[FileAttributeKey.modificationDate] as! Date), 0) + + let newSymlinkAttributes = try! FileManager.default.attributesOfItem(atPath: validSymlinkURL.path) + XCTAssertGreaterThan((newSymlinkAttributes[FileAttributeKey.modificationDate] as! Date).timeIntervalSince(oldValidSymlinkAttributes[FileAttributeKey.modificationDate] as! Date), 0) } } func testFileExists() { - makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL in - XCTAssertTrue(fileManager._itemExistsAtURL(ordinaryFileURL)) - XCTAssertTrue(fileManager._itemExistsAtURL(directoryURL)) - XCTAssertFalse(fileManager._itemExistsAtURL(rootURL.URLByAppendingPathComponent("does not exist"))) + makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL, validSymlinkURL, invalidSymlinkURL in + XCTAssertTrue(fileManager._itemExists(at: ordinaryFileURL)) + XCTAssertTrue(fileManager._itemExists(at: directoryURL)) + XCTAssertFalse(fileManager._itemExists(at: rootURL.appendingPathComponent("does not exist"))) var isOrdinaryFileDirectory: ObjCBool = false - XCTAssertTrue(fileManager._itemExistsAtURL(ordinaryFileURL, isDirectory: &isOrdinaryFileDirectory) && !isOrdinaryFileDirectory) + XCTAssertTrue(fileManager._itemExists(at: ordinaryFileURL, isDirectory: &isOrdinaryFileDirectory) && !isOrdinaryFileDirectory.boolValue) var isDirectoryADirectory: ObjCBool = false - XCTAssertTrue(fileManager._itemExistsAtURL(directoryURL, isDirectory: &isDirectoryADirectory) && isDirectoryADirectory) + XCTAssertTrue(fileManager._itemExists(at: directoryURL, isDirectory: &isDirectoryADirectory) && isDirectoryADirectory.boolValue) - XCTAssertFalse(fileManager._itemExistsAtURL(rootURL.URLByAppendingPathComponent("does not exist"), isDirectory: nil)) + XCTAssertFalse(fileManager._itemExists(at: rootURL.appendingPathComponent("does not exist"), isDirectory: nil)) - let validSymlinkURL = rootURL.URLByAppendingPathComponent("symlink test") - try! NSFileManager.defaultManager().createSymbolicLinkAtURL(validSymlinkURL, withDestinationURL: directoryURL) - - XCTAssertTrue(fileManager._itemExistsAtURL(validSymlinkURL)) + XCTAssertTrue(fileManager._itemExists(at: validSymlinkURL)) var validSymlinkIsADirectory: ObjCBool = false - XCTAssertTrue(fileManager._itemExistsAtURL(validSymlinkURL, isDirectory: &validSymlinkIsADirectory) && !validSymlinkIsADirectory) - - let invalidSymlinkURL = rootURL.URLByAppendingPathComponent("symlink test 2") - try! NSFileManager.defaultManager().createSymbolicLinkAtURL(invalidSymlinkURL, withDestinationURL: rootURL.URLByAppendingPathComponent("does not exist")) + XCTAssertTrue(fileManager._itemExists(at: validSymlinkURL, isDirectory: &validSymlinkIsADirectory) && !validSymlinkIsADirectory.boolValue) // Symlink should still exist even if it doesn't point to a file that exists - XCTAssertTrue(fileManager._itemExistsAtURL(invalidSymlinkURL)) + XCTAssertTrue(fileManager._itemExists(at: invalidSymlinkURL)) var invalidSymlinkIsADirectory: ObjCBool = false - XCTAssertTrue(fileManager._itemExistsAtURL(invalidSymlinkURL, isDirectory: &invalidSymlinkIsADirectory) && !invalidSymlinkIsADirectory) + XCTAssertTrue(fileManager._itemExists(at: invalidSymlinkURL, isDirectory: &invalidSymlinkIsADirectory) && !invalidSymlinkIsADirectory.boolValue) } } func testMakeDirectory() { - makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL in - XCTAssertNil(try? fileManager._makeDirectoryAtURL(ordinaryFileURL)) - XCTAssertNil(try? fileManager._makeDirectoryAtURL(directoryURL)) + makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL, validSymlinkURL, invalidSymlinkURL in + XCTAssertNil(try? fileManager.makeDirectory(at: ordinaryFileURL)) + XCTAssertNil(try? fileManager.makeDirectory(at: directoryURL)) - XCTAssertNil(try? fileManager._makeDirectoryAtURL(rootURL.URLByAppendingPathComponent("this should").URLByAppendingPathComponent("be a failure"))) + XCTAssertNil(try? fileManager.makeDirectory(at: rootURL.appendingPathComponent("this should").appendingPathComponent("be a failure"))) - let newDirectoryURL = rootURL.URLByAppendingPathComponent("new test directory") - XCTAssertFalse(fileManager._itemExistsAtURL(newDirectoryURL)) - try! fileManager._makeDirectoryAtURL(newDirectoryURL) + let newDirectoryURL = rootURL.appendingPathComponent("new test directory") + XCTAssertFalse(fileManager._itemExists(at: newDirectoryURL)) + try! fileManager.makeDirectory(at: newDirectoryURL) var isDirectory: ObjCBool = false - XCTAssertTrue(fileManager._itemExistsAtURL(newDirectoryURL, isDirectory: &isDirectory)) + XCTAssertTrue(fileManager._itemExists(at: newDirectoryURL, isDirectory: &isDirectory)) + + try! fileManager.removeItem(at: directoryURL) + XCTAssertNil(try? fileManager.makeDirectory(at: validSymlinkURL)) } } - // This alone shouldn't prompt a password dialog and should always succeed - func testAcquireAuthorization() - { - let fileManager = SUFileManager(allowingAuthorization: true) - try! fileManager._acquireAuthorization() - } - func testAcquireBadAuthorization() { - let fileManager = SUFileManager(allowingAuthorization: false) - XCTAssertNil(try? fileManager._acquireAuthorization()) + let fileManager = SUFileManager.default() + XCTAssertNil(try? fileManager?._acquireAuthorization()) } } diff --git a/Tests/SUInstallerTest.m b/Tests/SUInstallerTest.m index 8b73abe3..278060b0 100644 --- a/Tests/SUInstallerTest.m +++ b/Tests/SUInstallerTest.m @@ -53,7 +53,13 @@ SUHost *host = [[SUHost alloc] initWithBundle:bundle]; - [SUInstaller installFromUpdateFolder:[path stringByDeletingLastPathComponent] overHost:host installationPath:@"/tmp" versionComparator:nil completionHandler:^(NSError *error) { + NSString *fileOperationToolPath = [bundle pathForResource:@""SPARKLE_FILEOP_TOOL_NAME ofType:@""]; + XCTAssertNotNil(fileOperationToolPath); + + [SUInstaller installFromUpdateFolder:[path stringByDeletingLastPathComponent] overHost:host installationPath:@"/tmp" fileOperationToolPath:fileOperationToolPath versionComparator:nil completionHandler:^(NSError *error) { + if (error != nil) { + NSLog(@"Underlying error: %@", [error.userInfo objectForKey:NSUnderlyingErrorKey]); + } XCTAssertNil(error); XCTAssertTrue([fm fileExistsAtPath:expectedDestination isDirectory:nil]); [done fulfill]; diff --git a/Tests/SUSpotlightImporterTest.swift b/Tests/SUSpotlightImporterTest.swift new file mode 100644 index 00000000..3c086e0a --- /dev/null +++ b/Tests/SUSpotlightImporterTest.swift @@ -0,0 +1,60 @@ +// +// SUSpotlightImporterTest.swift +// Sparkle +// +// Created by Mayur Pawashe on 8/27/16. +// Copyright © 2016 Sparkle Project. All rights reserved. +// + +import XCTest + +class SUSpotlightImporterTest: XCTestCase +{ + func testUpdatingSpotlightBundles() + { + let fileManager = SUFileManager.default() + let tempDirectoryURL = try! fileManager?.makeTemporaryDirectory(withPreferredName: "Sparkle Unit Test Data", appropriateForDirectoryURL: URL(fileURLWithPath: NSHomeDirectory())) + + let bundleDirectory = tempDirectoryURL?.appendingPathComponent("bundle.app") + try! fileManager?.makeDirectory(at: bundleDirectory) + + let innerDirectory = bundleDirectory?.appendingPathComponent("foo") + try! fileManager?.makeDirectory(at: innerDirectory) + try! Data().write(to: (bundleDirectory?.appendingPathComponent("bar"))!, options: .atomicWrite) + + let importerDirectory = innerDirectory?.appendingPathComponent("baz.mdimporter") + + try! fileManager?.makeDirectory(at: importerDirectory) + try! fileManager?.makeDirectory(at: innerDirectory?.appendingPathComponent("flag")) + + try! Data().write(to: (importerDirectory?.appendingPathComponent("file"))!, options: .atomicWrite) + + let oldFooDirectoryAttributes = try! FileManager.default.attributesOfItem(atPath: innerDirectory!.path) + let oldBarFileAttributes = try! FileManager.default.attributesOfItem(atPath: bundleDirectory!.appendingPathComponent("bar").path) + let oldImporterAttributes = try! FileManager.default.attributesOfItem(atPath: importerDirectory!.path) + let oldFlagAttributes = try! FileManager.default.attributesOfItem(atPath: innerDirectory!.appendingPathComponent("flag").path) + let oldFileInImporterAttributes = try! FileManager.default.attributesOfItem(atPath: importerDirectory!.appendingPathComponent("file").path) + + sleep(1) // wait for clock to advance + + // Update spotlight bundles + SUBinaryDeltaUnarchiver.updateSpotlightImporters(atBundlePath: bundleDirectory!.path) + + let newFooDirectoryAttributes = try! FileManager.default.attributesOfItem(atPath: innerDirectory!.path) + XCTAssertEqual((newFooDirectoryAttributes[FileAttributeKey.modificationDate] as! Date).timeIntervalSince(oldFooDirectoryAttributes[FileAttributeKey.modificationDate] as! Date), 0) + + let newBarFileAttributes = try! FileManager.default.attributesOfItem(atPath: bundleDirectory!.appendingPathComponent("bar").path) + XCTAssertEqual((newBarFileAttributes[FileAttributeKey.modificationDate] as! Date).timeIntervalSince(oldBarFileAttributes[FileAttributeKey.modificationDate] as! Date), 0) + + let newImporterAttributes = try! FileManager.default.attributesOfItem(atPath: importerDirectory!.path) + XCTAssertGreaterThan((newImporterAttributes[FileAttributeKey.modificationDate] as! Date).timeIntervalSince(oldImporterAttributes[FileAttributeKey.modificationDate] as! Date), 0) + + let newFlagAttributes = try! FileManager.default.attributesOfItem(atPath: innerDirectory!.appendingPathComponent("flag").path) + XCTAssertEqual((newFlagAttributes[FileAttributeKey.modificationDate] as! Date).timeIntervalSince(oldFlagAttributes[FileAttributeKey.modificationDate] as! Date), 0) + + let newFileInImporterAttributes = try! FileManager.default.attributesOfItem(atPath: importerDirectory!.appendingPathComponent("file").path) + XCTAssertEqual((newFileInImporterAttributes[FileAttributeKey.modificationDate] as! Date).timeIntervalSince(oldFileInImporterAttributes[FileAttributeKey.modificationDate] as! Date), 0) + + try! fileManager?.removeItem(at: tempDirectoryURL) + } +} diff --git a/Tests/SUUnarchiverTest.swift b/Tests/SUUnarchiverTest.swift index b81ffc38..4e70bba8 100644 --- a/Tests/SUUnarchiverTest.swift +++ b/Tests/SUUnarchiverTest.swift @@ -14,52 +14,52 @@ class SUUnarchiverTest: XCTestCase, SUUnarchiverDelegate var unarchivedExpectation: XCTestExpectation? = nil var unarchivedResult: Bool = false - func unarchiver(unarchiver: SUUnarchiver!, extractedProgress progress: Double) + func unarchiver(_ unarchiver: SUUnarchiver!, extractedProgress progress: Double) { } - func unarchiverDidFail(unarchiver: SUUnarchiver!) + func unarchiverDidFail(_ unarchiver: SUUnarchiver!) { self.unarchivedResult = false self.unarchivedExpectation!.fulfill() } - func unarchiverDidFinish(unarchiver: SUUnarchiver!) + func unarchiverDidFinish(_ unarchiver: SUUnarchiver!) { self.unarchivedResult = true self.unarchivedExpectation!.fulfill() } - func unarchiveTestAppWithExtension(archiveExtension: String) + func unarchiveTestAppWithExtension(_ archiveExtension: String) { let appName = "SparkleTestCodeSignApp" - let archiveResourceURL = NSBundle(forClass: self.dynamicType).URLForResource(appName, withExtension: archiveExtension)! + let archiveResourceURL = Bundle(for: type(of: self)).url(forResource: appName, withExtension: archiveExtension)! - let fileManager = NSFileManager.defaultManager() + let fileManager = FileManager.default - let tempDirectoryURL = try! fileManager.URLForDirectory(.ItemReplacementDirectory, inDomain: .UserDomainMask, appropriateForURL: NSURL(fileURLWithPath: NSHomeDirectory()), create: true) + let tempDirectoryURL = try! fileManager.url(for: .itemReplacementDirectory, in: .userDomainMask, appropriateFor: URL(fileURLWithPath: NSHomeDirectory()), create: true) defer { - try! fileManager.removeItemAtURL(tempDirectoryURL) + try! fileManager.removeItem(at: tempDirectoryURL) } - let tempArchiveURL = tempDirectoryURL.URLByAppendingPathComponent(archiveResourceURL.lastPathComponent!) - let extractedAppURL = tempDirectoryURL.URLByAppendingPathComponent(appName).URLByAppendingPathExtension("app") + let tempArchiveURL = tempDirectoryURL.appendingPathComponent(archiveResourceURL.lastPathComponent) + let extractedAppURL = tempDirectoryURL.appendingPathComponent(appName).appendingPathExtension("app") - try! fileManager.copyItemAtURL(archiveResourceURL, toURL: tempArchiveURL) + try! fileManager.copyItem(at: archiveResourceURL, to: tempArchiveURL) - self.unarchivedExpectation = super.expectationWithDescription("Unarchived Application (format: \(archiveExtension))") + self.unarchivedExpectation = super.expectation(description: "Unarchived Application (format: \(archiveExtension))") - let unarchiver = SUUnarchiver(forPath: tempArchiveURL.path!, updatingHostBundlePath: nil, withPassword: self.password) + let unarchiver = SUUnarchiver(forPath: tempArchiveURL.path, updatingHostBundlePath: nil, withPassword: self.password) - unarchiver.delegate = self - unarchiver.start() + unarchiver?.delegate = self + unarchiver?.start() - super.waitForExpectationsWithTimeout(7.0, handler: nil) + super.waitForExpectations(timeout: 7.0, handler: nil) XCTAssertTrue(self.unarchivedResult) - XCTAssertTrue(fileManager.fileExistsAtPath(extractedAppURL.path!)) + XCTAssertTrue(fileManager.fileExists(atPath: extractedAppURL.path)) - XCTAssertEqual("6a60ab31430cfca8fb499a884f4a29f73e59b472", hashOfTree(extractedAppURL.path!)) + XCTAssertEqual("6a60ab31430cfca8fb499a884f4a29f73e59b472", hashOfTree(extractedAppURL.path)) } func testUnarchivingZip() diff --git a/Tests/SUUpdaterTest.m b/Tests/SUUpdaterTest.m index 0e7d6e76..0ff7e930 100644 --- a/Tests/SUUpdaterTest.m +++ b/Tests/SUUpdaterTest.m @@ -24,7 +24,7 @@ { [super setUp]; self.queue = [[NSOperationQueue alloc] init]; - self.updater = [[SUUpdater alloc] init]; + self.updater = [[SUUpdater alloc] initForBundle:[NSBundle bundleForClass:[self class]]]; self.updater.delegate = self; } diff --git a/Tests/Sparkle Unit Tests-Bridging-Header.h b/Tests/Sparkle Unit Tests-Bridging-Header.h index ab678027..c38a9f78 100644 --- a/Tests/Sparkle Unit Tests-Bridging-Header.h +++ b/Tests/Sparkle Unit Tests-Bridging-Header.h @@ -3,9 +3,15 @@ // #import "SUUnarchiver.h" +#import "SUBinaryDeltaUnarchiver.h" #import "SUPipedUnarchiver.h" #import "SUBinaryDeltaCommon.h" #import "SUFileManager.h" +#import "SUAppcast.h" +#import "SUAppcastItem.h" +#import "SUBasicUpdateDriver.h" +#import "SUVersionComparisonProtocol.h" +#import "SUStandardVersionComparator.h" // Duplicated to avoid exporting a private symbol from SUFileManager static const char *SUAppleQuarantineIdentifier = "com.apple.quarantine"; @@ -17,6 +23,21 @@ static const char *SUAppleQuarantineIdentifier = "com.apple.quarantine"; - (BOOL)_itemExistsAtURL:(NSURL *)fileURL; - (BOOL)_itemExistsAtURL:(NSURL *)fileURL isDirectory:(BOOL *)isDirectory; -- (BOOL)_makeDirectoryAtURL:(NSURL *)url error:(NSError * __autoreleasing *)error; +@end + +@interface SUBasicUpdateDriver (Private) + ++ (SUAppcastItem *)bestItemFromAppcastItems:(NSArray *)appcastItems getDeltaItem:(SUAppcastItem * __autoreleasing *)deltaItem withHostVersion:(NSString *)hostVersion comparator:(id)comparator; + +@end + + +@interface SUAppcast (Private) +- (NSArray *)parseAppcastItemsFromXMLFile:(NSURL *)appcastFile error:(NSError *__autoreleasing*)errorp; +@end + +@interface SUBinaryDeltaUnarchiver (Private) + ++ (void)updateSpotlightImportersAtBundlePath:(NSString *)targetPath; @end diff --git a/Tests/SparkleTests-Info.plist b/Tests/SparkleTests-Info.plist index 460a7d93..e7e83b9d 100644 --- a/Tests/SparkleTests-Info.plist +++ b/Tests/SparkleTests-Info.plist @@ -16,5 +16,11 @@ ???? CFBundleVersion 1.0 + SUEnableAutomaticChecks + + SUEnableSystemProfiling + + SUPublicDSAKeyFile + test-pubkey.pem diff --git a/UITests/SUTestApplicationTest.swift b/UITests/SUTestApplicationTest.swift new file mode 100644 index 00000000..72cd02fb --- /dev/null +++ b/UITests/SUTestApplicationTest.swift @@ -0,0 +1,106 @@ +// +// SUTestApplicationTest.swift +// Sparkle +// +// Created by Mayur Pawashe on 8/27/15. +// Copyright © 2015 Sparkle Project. All rights reserved. +// + +import XCTest + +class SUTestApplicationTest: XCTestCase +{ + var testApplicationURL: URL? = nil + var testApplicationBackupURL: URL? = nil + var tempDirectoryURL: URL? = nil + + func runningTestApplication() -> NSRunningApplication + { + // TODO: don't hardcode bundle ID? + let runningApplications = NSRunningApplication.runningApplications(withBundleIdentifier: "org.sparkle-project.SparkleTestApp") + XCTAssertEqual(runningApplications.count, 1, "More than one or zero running instances of the Test Application are found") + return runningApplications[0] + } + + override func setUp() + { + super.setUp() + + let app = XCUIApplication() + app.launch() + + XCTAssertFalse(app.dialogs["alert"].staticTexts["Update succeeded!"].exists, "Update is already installed; please do a clean build") + + // We need to grab the app URL so we can back up the app + // When a successful test is over we'll revert the update + let testApplicationURL = self.runningTestApplication().bundleURL! + + let tempDirectoryURL = try! FileManager.default.url(for: .itemReplacementDirectory, in: FileManager.SearchPathDomainMask.userDomainMask, appropriateFor: testApplicationURL, create: true) + + let testApplicationBackupURL = tempDirectoryURL.appendingPathComponent(testApplicationURL.lastPathComponent) + + try! FileManager.default.copyItem(at: testApplicationURL, to: testApplicationBackupURL) + + self.testApplicationURL = testApplicationURL + self.testApplicationBackupURL = testApplicationBackupURL + self.tempDirectoryURL = tempDirectoryURL + + // when we add more tests we don't want to continue after a failure + // since a test can fail after the new app has been placed in + self.continueAfterFailure = false + } + + override func tearDown() + { + // Terminate just in case the app hasn't already quit + XCUIApplication().terminate() + + // Revert our update with the original test application + + var resultingURL: NSURL? = nil + try! FileManager.default.replaceItem(at: self.testApplicationURL!, withItemAt: self.testApplicationBackupURL!, backupItemName: nil, options: .usingNewMetadataOnly, resultingItemURL: &resultingURL) + + do { + try FileManager.default.removeItem(at: self.tempDirectoryURL!) + } catch let error as NSError { + NSLog("Failed to remove temporary directory \(self.tempDirectoryURL) with error: \(error)") + } + + // The URL we get back from NSFileManager should be the same.. + XCTAssertEqual(self.testApplicationURL, resultingURL as URL?, "Test application was replaced, but at a different location") + + super.tearDown() + } + + func testRegularUpdate() + { + let app = XCUIApplication() + let menuBarsQuery = app.menuBars + + menuBarsQuery.menuBarItems["Sparkle Test App"].click() + + // If the update window already showed up automatically, this option will be disabled. + // Even if it's disabled, attempting to click it will do no harm and continue on + menuBarsQuery.menuItems["Check for Updates…"].click() + + app.dialogs["SUUpdateAlert"].buttons["Install Update"].click() + app.buttons["Install and Relaunch"].click() + + // Wait for the new updated app to finish launching so we can test if it's the frontmost app + sleep(3) + + // Our new updated app should be launched now. Test if it's the active app + // We used to run into timing issues where the updated app sometimes may not show up as the frontmost one + XCTAssertTrue(self.runningTestApplication().isActive) + + // Grab another XCUIApplication instance rather than using the old one, just in case + let updatedApp = XCUIApplication() + + // Check if we can click the "Update succeeded!" label rather than using the exists property + // Checking the exists property doesn't reload the "cache" and as such the UI tests still would think we are + // referring to the older app. Clicking does force the UI tests to find the new app however + updatedApp.dialogs["alert"].staticTexts["Update succeeded!"].click() + + updatedApp.dialogs["alert"].buttons["OK"].click() + } +} diff --git a/UITests/UITests-Info.plist b/UITests/UITests-Info.plist new file mode 100644 index 00000000..ba72822e --- /dev/null +++ b/UITests/UITests-Info.plist @@ -0,0 +1,24 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + BNDL + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1 + + diff --git a/Vendor/CocoatechCore/NTSynchronousTask.h b/Vendor/CocoatechCore/NTSynchronousTask.h deleted file mode 100644 index cbcbf2c8..00000000 --- a/Vendor/CocoatechCore/NTSynchronousTask.h +++ /dev/null @@ -1,26 +0,0 @@ -// -// NTSynchronousTask.h -// CocoatechCore -// -// Created by Steve Gehrman on 9/29/05. -// Copyright 2005 Steve Gehrman. All rights reserved. -// - -#ifndef NTSYNCHRONOUSTASK_H -#define NTSYNCHRONOUSTASK_H - -@interface NTSynchronousTask : NSObject -@property (readonly, strong) 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; - -+(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; - -@end - -#endif diff --git a/Vendor/CocoatechCore/NTSynchronousTask.m b/Vendor/CocoatechCore/NTSynchronousTask.m deleted file mode 100644 index f96bdbf8..00000000 --- a/Vendor/CocoatechCore/NTSynchronousTask.m +++ /dev/null @@ -1,169 +0,0 @@ -// -// NTSynchronousTask.m -// CocoatechCore -// -// Created by Steve Gehrman on 9/29/05. -// Copyright 2005 Steve Gehrman. All rights reserved. -// - -#import "NTSynchronousTask.h" - -@interface NTSynchronousTask () -@property (strong) NSTask *task; -@property (strong) NSPipe *outputPipe; -@property (strong) NSPipe *inputPipe; -@property (readwrite, strong) NSData *output; -@property (getter = isDone) BOOL done; -@property (readwrite) int result; -@end - -@implementation NTSynchronousTask -@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.output = [note userInfo][NSFileHandleNotificationDataItem]; - - self.done = YES; -} - -- (void)taskDidTerminate:(NSNotification *) __unused note -{ - self.result = [self.task terminationStatus]; -} - -- (instancetype)init -{ - self = [super init]; - if (self) - { - self.task = [[NSTask alloc] init]; - self.outputPipe = [[NSPipe alloc] init]; - self.inputPipe = [[NSPipe alloc] init]; - - self.task.standardInput = self.inputPipe; - self.task.standardOutput = self.outputPipe; - self.task.standardError = self.outputPipe; - } - - return self; -} - -//---------------------------------------------------------- -// dealloc -//---------------------------------------------------------- -- (void)dealloc -{ - [[NSNotificationCenter defaultCenter] removeObserver:self]; -} - -- (void)run:(NSString*)toolPath directory:(NSString*)currentDirectory withArgs:(NSArray*)args input:(NSData*)input -{ - BOOL success = NO; - - if (currentDirectory) { - self.task.currentDirectoryPath = currentDirectory; - } - - self.task.launchPath = toolPath; - self.task.arguments = args; - - [[NSNotificationCenter defaultCenter] addObserver:self - selector:@selector(taskOutputAvailable:) - name:NSFileHandleReadToEndOfFileCompletionNotification - object:[[self outputPipe] fileHandleForReading]]; - - [[NSNotificationCenter defaultCenter] addObserver:self - selector:@selector(taskDidTerminate:) - name:NSTaskDidTerminateNotification - object:[self task]]; - - [[[self outputPipe] fileHandleForReading] readToEndOfFileInBackgroundAndNotifyForModes:@[NSDefaultRunLoopMode, NSModalPanelRunLoopMode, NSEventTrackingRunLoopMode]]; - - @try - { - [self.task launch]; - success = YES; - } - @catch (NSException *) { } - - if (success) - { - if (input) - { - // feed the running task our input - [[self.inputPipe fileHandleForWriting] writeData:input]; - [[self.inputPipe fileHandleForWriting] closeFile]; - } - - // loop until we are done receiving the data - if (!self.done) - { - double resolution = 1; - BOOL isRunning; - NSDate* next; - - do { - next = [NSDate dateWithTimeIntervalSinceNow:resolution]; - - isRunning = [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode - beforeDate:next]; - } while (isRunning && !self.done); - } - } -} - -+ (NSData*)task:(NSString*)toolPath directory:(NSString*)currentDirectory withArgs:(NSArray*)args input:(NSData*)input -{ - @autoreleasepool { - NSData* result = nil; - // we need this wacky pool here, otherwise we run out of pipes, the pipes are internally autoreleased - @try { - NTSynchronousTask* task = [[NTSynchronousTask alloc] init]; - - [task run:toolPath directory:currentDirectory withArgs:args input:input]; - - if ([task result] == 0) { - result = [task output]; - } - } - @catch (NSException *) { } - - return result; - } -} - - -+(int) task:(NSString*)toolPath directory:(NSString*)currentDirectory withArgs:(NSArray*)args input:(NSData*)input output: (NSData*__autoreleasing *)outData -{ - // we need this wacky pool here, otherwise we run out of pipes, the pipes are internally autoreleased - @autoreleasepool { - int taskResult = 0; - if (outData) { - *outData = nil; - } - - @try { - NTSynchronousTask* task = [[NTSynchronousTask alloc] init]; - - [task run:toolPath directory:currentDirectory withArgs:args input:input]; - - taskResult = [task result]; - if (outData) { - *outData = [task output]; - } - - } @catch (NSException *) { - taskResult = errCppGeneral; - } - - return taskResult; - } -} - -@end diff --git a/Vendor/bsdiff/bscommon.c b/Vendor/bsdiff/bscommon.c new file mode 100644 index 00000000..f492a1d6 --- /dev/null +++ b/Vendor/bsdiff/bscommon.c @@ -0,0 +1,62 @@ +/* + * bscommon.c + * Sparkle + * + * Created by Mayur Pawashe on 5/16/16. + */ + +#include "bscommon.h" +#include + +u_char *readfile(const char *filename, off_t *outSize) +{ + int success = -1; + u_char *buffer = NULL; + + FILE *file = fopen(filename, "r"); + if (file == NULL) { + goto cleanup; + } + + if (fseek(file, 0L, SEEK_END) != 0) { + goto cleanup; + } + + long offset = ftell(file); + if (offset == -1) { + goto cleanup; + } + + size_t size = (size_t)offset; + + if (outSize != NULL) { + *outSize = (off_t)size; + } + + /* Allocate size + 1 bytes instead of newsize bytes to ensure + that we never try to malloc(0) and get a NULL pointer */ + buffer = malloc(size + 1); + if (buffer == NULL) { + goto cleanup; + } + + if (fseek(file, 0L, SEEK_SET) != 0) { + goto cleanup; + } + + if (fread(buffer, 1, size, file) < size) { + goto cleanup; + } + + success = 0; +cleanup: + if (success == -1) { + free(buffer); + buffer = NULL; + } + if (file != NULL) { + fclose(file); + } + + return buffer; +} diff --git a/Vendor/bsdiff/bscommon.h b/Vendor/bsdiff/bscommon.h new file mode 100644 index 00000000..d90273fc --- /dev/null +++ b/Vendor/bsdiff/bscommon.h @@ -0,0 +1,16 @@ +/* + * bscommon.h + * Sparkle + * + * Created by Mayur Pawashe on 5/16/16. + */ + +#ifndef BS_COMMON_H +#define BS_COMMON_H + +#include +#include + +u_char *readfile(const char *filename, off_t *outSize); + +#endif diff --git a/Vendor/bsdiff/bsdiff.c b/Vendor/bsdiff/bsdiff.c index 9d55aded..8dfb3c20 100644 --- a/Vendor/bsdiff/bsdiff.c +++ b/Vendor/bsdiff/bsdiff.c @@ -38,6 +38,8 @@ __FBSDID("$FreeBSD: src/usr.bin/bsdiff/bsdiff/bsdiff.c, v 1.1 2005/08/06 01:59:0 #include #include +#include "bscommon.h" + #define MIN(x, y) (((x)<(y)) ? (x) : (y)) /* matchlen(old, oldsize, new, newsize) @@ -82,7 +84,7 @@ static off_t search(off_t *I, u_char *old, off_t oldsize, } x = st + (en - st)/2; - if (memcmp(old + I[x], new, MIN(oldsize - I[x], newsize)) < 0) { + if (memcmp(old + I[x], new, (size_t)(MIN(oldsize - I[x], newsize))) < 0) { return search(I, old, oldsize, new, newsize, x, en, pos); } else { return search(I, old, oldsize, new, newsize, st, x, pos); @@ -101,15 +103,15 @@ static void offtout(off_t x, u_char *buf) else y = x; - buf[0] = y % 256; + buf[0] = (u_char)(y % 256); y -= buf[0]; - y = y/256; buf[1] = y%256; y -= buf[1]; - y = y/256; buf[2] = y%256; y -= buf[2]; - y = y/256; buf[3] = y%256; y -= buf[3]; - y = y/256; buf[4] = y%256; y -= buf[4]; - y = y/256; buf[5] = y%256; y -= buf[5]; - y = y/256; buf[6] = y%256; y -= buf[6]; - y = y/256; buf[7] = y%256; + y = y/256; buf[1] = (u_char)(y%256); y -= buf[1]; + y = y/256; buf[2] = (u_char)(y%256); y -= buf[2]; + y = y/256; buf[3] = (u_char)(y%256); y -= buf[3]; + y = y/256; buf[4] = (u_char)(y%256); y -= buf[4]; + y = y/256; buf[5] = (u_char)(y%256); y -= buf[5]; + y = y/256; buf[6] = (u_char)(y%256); y -= buf[6]; + y = y/256; buf[7] = (u_char)(y%256); if (x < 0) buf[7] |= 0x80; @@ -119,67 +121,69 @@ int bsdiff(int argc, char *argv[]); // Added by AMM: suppresses a warning about int bsdiff(int argc, char *argv[]) { - int fd; - u_char *old,*new; /* contents of old, new files */ - off_t oldsize, newsize; /* length of old, new files */ - off_t *I,*V; /* arrays used for suffix sort; I is ordering */ - off_t scan; /* position of current match in old file */ + u_char *old = NULL,*new = NULL; /* contents of old, new files */ + off_t oldsize = 0, newsize = 0; /* length of old, new files */ + off_t *I = NULL,*V = NULL; /* arrays used for suffix sort; I is ordering */ + off_t scan = 0; /* position of current match in old file */ off_t pos = 0; /* position of current match in new file */ - off_t len; /* length of current match */ - off_t lastscan; /* position of previous match in old file */ - off_t lastpos; /* position of previous match in new file */ - off_t lastoffset; /* lastpos - lastscan */ - off_t oldscore, scsc; /* temp variables in match search */ - off_t s, Sf, lenf, Sb, lenb; /* temp vars in match extension */ - off_t overlap, Ss, lens; - off_t i; - off_t dblen, eblen; /* length of diff, extra sections */ - u_char *db,*eb; /* contents of diff, extra sections */ - u_char buf[8]; - u_char header[32]; - FILE * pf; + off_t len = 0; /* length of current match */ + off_t lastscan = 0; /* position of previous match in old file */ + off_t lastpos = 0; /* position of previous match in new file */ + off_t lastoffset = 0; /* lastpos - lastscan */ + off_t oldscore = 0, scsc = 0; /* temp variables in match search */ + off_t s = 0, Sf = 0, lenf = 0, Sb = 0, lenb = 0; /* temp vars in match extension */ + off_t overlap = 0, Ss = 0, lens = 0; + off_t i = 0; + off_t dblen = 0, eblen = 0; /* length of diff, extra sections */ + u_char *db = NULL,*eb = NULL; /* contents of diff, extra sections */ + u_char buf[8] = {0}; + u_char header[32] = {0}; + FILE * pf = NULL; + int exitstatus = -1; - if (argc != 4) - errx(1,"usage: %s oldfile newfile patchfile\n", argv[0]); + if (argc != 4) { + warnx("usage: %s oldfile newfile patchfile\n", argv[0]); + goto cleanup; + } - /* Allocate oldsize + 1 bytes instead of oldsize bytes to ensure - that we never try to malloc(0) and get a NULL pointer */ - if (((fd = open(argv[1], O_RDONLY, 0)) < 0) || - ((oldsize = lseek(fd, 0, SEEK_END)) == -1) || - ((old = malloc(oldsize + 1)) == NULL) || - (lseek(fd, 0, SEEK_SET) != 0) || - (read(fd, old, oldsize) != oldsize) || - (close(fd) == -1)) - err(1,"%s", argv[1]); + old = readfile(argv[1], &oldsize); + if (old == NULL) { + warn("old file error: %s", argv[1]); + goto cleanup; + } - if (((I = malloc((oldsize + 1) * sizeof(off_t))) == NULL) || - ((V = malloc((oldsize + 1) * sizeof(off_t))) == NULL)) - err(1, NULL); + if (((I = malloc(((size_t)oldsize + 1) * sizeof(off_t))) == NULL) || + ((V = malloc(((size_t)oldsize + 1) * sizeof(off_t))) == NULL)) { + warn("Failed to allocate memory for I or V"); + goto cleanup; + } /* Do a suffix sort on the old file. */ - I[0] = oldsize; sais(old, I+1, oldsize); + I[0] = oldsize; + sais(old, I+1, (int)oldsize); free(V); + V = NULL; + + new = readfile(argv[2], &newsize); + if (new == NULL) { + warn("new file error: %s", argv[2]); + goto cleanup; + } - /* Allocate newsize + 1 bytes instead of newsize bytes to ensure - that we never try to malloc(0) and get a NULL pointer */ - if (((fd = open(argv[2], O_RDONLY, 0)) < 0) || - ((newsize = lseek(fd, 0, SEEK_END)) == -1) || - ((new = malloc(newsize + 1)) == NULL) || - (lseek(fd, 0, SEEK_SET) != 0) || - (read(fd, new, newsize) != newsize) || - (close(fd) == -1)) - err(1,"%s", argv[2]); - - if (((db = malloc(newsize + 1)) == NULL) || - ((eb = malloc(newsize + 1)) == NULL)) - err(1, NULL); + if (((db = malloc((size_t)newsize + 1)) == NULL) || + ((eb = malloc((size_t)newsize + 1)) == NULL)) { + warn("Failed to allocate memory for db or eb"); + goto cleanup; + } dblen = 0; eblen = 0; /* Create the patch file */ - if ((pf = fopen(argv[3], "w")) == NULL) - err(1, "%s", argv[3]); + if ((pf = fopen(argv[3], "w")) == NULL) { + warn("%s", argv[3]); + goto cleanup; + } /* Header is 0 8 "BSDIFN40" @@ -195,8 +199,10 @@ int bsdiff(int argc, char *argv[]) offtout(0, header + 8); offtout(0, header + 16); offtout(newsize, header + 24); - if (fwrite(header, 32, 1, pf) != 1) - err(1, "fwrite(%s)", argv[3]); + if (fwrite(header, 32, 1, pf) != 1) { + warn("fwrite(%s)", argv[3]); + goto cleanup; + } /* Compute the differences, writing ctrl as we go */ scan = 0; @@ -312,16 +318,22 @@ int bsdiff(int argc, char *argv[]) * diff, in the old file */ offtout(lenf, buf); - if (fwrite(buf, 8, 1, pf) != 1) - errx(1, "fwrite"); + if (fwrite(buf, 8, 1, pf) != 1) { + warnx("fwrite"); + goto cleanup; + } offtout((scan - lenb) - (lastscan + lenf), buf); - if (fwrite(buf, 8, 1, pf) != 1) - err(1, "fwrite"); + if (fwrite(buf, 8, 1, pf) != 1) { + warn("fwrite"); + goto cleanup; + } offtout((pos - lenb) - (lastpos + lenf), buf); - if (fwrite(buf, 8, 1, pf) != 1) - err(1, "fwrite"); + if (fwrite(buf, 8, 1, pf) != 1) { + warn("fwrite"); + goto cleanup; + } /* Update the variables describing the last match. Note that * 'lastscan' is set to the start of the current match _after_ the @@ -334,37 +346,61 @@ int bsdiff(int argc, char *argv[]) } /* Compute size of compressed ctrl data */ - if ((len = ftello(pf)) == -1) - err(1, "ftello"); + if ((len = ftello(pf)) == -1) { + warn("ftello"); + goto cleanup; + } offtout(len - 32, header + 8); /* Write diff data */ - if (dblen && fwrite(db, dblen, 1, pf) != 1) - err(1, "fwrite"); + if (dblen && fwrite(db, (size_t)dblen, 1, pf) != 1) { + warn("fwrite"); + goto cleanup; + } /* Compute size of compressed diff data */ - if ((newsize = ftello(pf)) == -1) - err(1, "ftello"); + if ((newsize = ftello(pf)) == -1) { + warn("ftello"); + goto cleanup; + } offtout(newsize - len, header + 16); /* Write extra data */ - if (eblen && fwrite(eb, eblen, 1, pf) != 1) - err(1, "fwrite"); + if (eblen && fwrite(eb, (size_t)eblen, 1, pf) != 1) { + warn("fwrite"); + goto cleanup; + } /* Seek to the beginning, write the header, and close the file */ - if (fseeko(pf, 0, SEEK_SET)) - err(1, "fseeko"); - if (fwrite(header, 32, 1, pf) != 1) - err(1, "fwrite(%s)", argv[3]); - if (fclose(pf)) - err(1, "fclose"); + if (fseeko(pf, 0, SEEK_SET)) { + warn("fseeko"); + goto cleanup; + } + if (fwrite(header, 32, 1, pf) != 1) { + warn("fwrite(%s)", argv[3]); + goto cleanup; + } + if (fclose(pf)) { + warn("fclose"); + pf = NULL; + goto cleanup; + } + pf = NULL; + + exitstatus = 0; +cleanup: + if (pf != NULL) { + fclose(pf); + } + /* Free the memory we used */ free(db); free(eb); free(I); + free(V); free(old); free(new); - return 0; + return exitstatus; } diff --git a/Vendor/bsdiff/bspatch.c b/Vendor/bsdiff/bspatch.c index ca7a72ab..753b78cd 100644 --- a/Vendor/bsdiff/bspatch.c +++ b/Vendor/bsdiff/bspatch.c @@ -37,6 +37,8 @@ __FBSDID("$FreeBSD: src/usr.bin/bsdiff/bspatch/bspatch.c,v 1.1 2005/08/06 01:59: #include #include +#include "bscommon.h" + /* Compatibility layer for reading either the old BSDIFF40 or the new BSDIFN40 patch formats: */ @@ -44,60 +46,63 @@ typedef void* stream_t; typedef struct { - stream_t (*open)(FILE*); - void (*close)(stream_t); - int (*read)(stream_t, void*, int); + stream_t (*open)(FILE*); + void (*close)(stream_t); + off_t (*read)(stream_t, void*, off_t); } io_funcs_t; static stream_t BSDIFF40_open(FILE *f) { - int bzerr; - BZFILE *s; - if ((s = BZ2_bzReadOpen(&bzerr, f, 0, 0, NULL, 0)) == NULL) - errx(1, "BZ2_bzReadOpen, bz2err = %d", bzerr); - return s; + int bzerr = 0; + BZFILE *s = NULL; + if ((s = BZ2_bzReadOpen(&bzerr, f, 0, 0, NULL, 0)) == NULL) { + warnx("BZ2_bzReadOpen, bz2err = %d", bzerr); + } + return s; } static void BSDIFF40_close(stream_t s) { - int bzerr; - BZ2_bzReadClose(&bzerr, (BZFILE*)s); + int bzerr; + BZ2_bzReadClose(&bzerr, (BZFILE*)s); } -static int BSDIFF40_read(stream_t s, void *buf, int len) +static off_t BSDIFF40_read(stream_t s, void *buf, off_t len) { - int bzerr, lenread; - lenread = BZ2_bzRead(&bzerr, (BZFILE*)s, buf, len); - if (bzerr != BZ_OK && bzerr != BZ_STREAM_END) - errx(1, "Corrupt patch\n"); - return lenread; + int bzerr = 0, lenread = 0; + lenread = BZ2_bzRead(&bzerr, (BZFILE*)s, buf, (int)len); + if (bzerr != BZ_OK && bzerr != BZ_STREAM_END) { + warnx("Corrupt patch\n"); + lenread = -1; + } + return lenread; } static io_funcs_t BSDIFF40_funcs = { - BSDIFF40_open, - BSDIFF40_close, - BSDIFF40_read + BSDIFF40_open, + BSDIFF40_close, + BSDIFF40_read }; static stream_t BSDIFN40_open(FILE *f) { - return f; + return f; } -static void BSDIFN40_close(stream_t s) +static void BSDIFN40_close(stream_t __unused s) { } -static int BSDIFN40_read(stream_t s, void *buf, int len) +static off_t BSDIFN40_read(stream_t s, void *buf, off_t len) { - return fread(buf, 1, len, (FILE*)s); + return (off_t)fread(buf, 1, (size_t)len, (FILE*)s); } static io_funcs_t BSDIFN40_funcs = { - BSDIFN40_open, - BSDIFN40_close, - BSDIFN40_read + BSDIFN40_open, + BSDIFN40_close, + BSDIFN40_read }; @@ -107,165 +112,287 @@ typedef unsigned char u_char; static off_t offtin(u_char *buf) { - off_t y; + off_t y; - y=buf[7]&0x7F; - y=y*256;y+=buf[6]; - y=y*256;y+=buf[5]; - y=y*256;y+=buf[4]; - y=y*256;y+=buf[3]; - y=y*256;y+=buf[2]; - y=y*256;y+=buf[1]; - y=y*256;y+=buf[0]; + y=buf[7]&0x7F; + y=y*256;y+=buf[6]; + y=y*256;y+=buf[5]; + y=y*256;y+=buf[4]; + y=y*256;y+=buf[3]; + y=y*256;y+=buf[2]; + y=y*256;y+=buf[1]; + y=y*256;y+=buf[0]; - if(buf[7]&0x80) y=-y; + if(buf[7]&0x80) y=-y; - return y; + return y; } int bspatch(int argc,const char * const argv[]) { - FILE * f, * cpf, * dpf, * epf; - stream_t cstream, dstream, estream; - int fd; - ssize_t oldsize,newsize; - ssize_t bzctrllen,bzdatalen; - u_char header[32],buf[8]; - u_char *old, *new; - off_t oldpos,newpos; - off_t ctrl[3]; - off_t lenread; - off_t i; - io_funcs_t * io; + FILE * f = NULL, * cpf = NULL, * dpf = NULL, * epf = NULL; + stream_t cstream = NULL, dstream = NULL, estream = NULL; + ssize_t oldsize = 0,newsize = 0; + ssize_t bzctrllen = 0,bzdatalen = 0; + u_char header[32] = {0},buf[8] = {0}; + u_char *old = NULL, *new = NULL; + off_t oldpos = 0,newpos = 0; + off_t ctrl[3] = {0}; + off_t lenread = 0; + off_t i = 0; + io_funcs_t * io = NULL; + int exitstatus = -1; - if(argc!=4) errx(1,"usage: %s oldfile newfile patchfile\n",argv[0]); + if(argc!=4) { + warnx("usage: %s oldfile newfile patchfile\n",argv[0]); + goto cleanup; + } - /* Open patch file */ - if ((f = fopen(argv[3], "r")) == NULL) - err(1, "fopen(%s)", argv[3]); + /* Open patch file */ + if ((f = fopen(argv[3], "r")) == NULL) { + warn("fopen(%s)", argv[3]); + goto cleanup; + } - /* - File format: - 0 8 "BSDIFF40" (bzip2) or "BSDIFN40" (raw) - 8 8 X - 16 8 Y - 24 8 sizeof(newfile) - 32 X bzip2(control block) - 32+X Y bzip2(diff block) - 32+X+Y ??? bzip2(extra block) - with control block a set of triples (x,y,z) meaning "add x bytes - from oldfile to x bytes from the diff block; copy y bytes from the - extra block; seek forwards in oldfile by z bytes". - */ + /* + File format: + 0 8 "BSDIFF40" (bzip2) or "BSDIFN40" (raw) + 8 8 X + 16 8 Y + 24 8 sizeof(newfile) + 32 X bzip2(control block) + 32+X Y bzip2(diff block) + 32+X+Y ??? bzip2(extra block) + with control block a set of triples (x,y,z) meaning "add x bytes + from oldfile to x bytes from the diff block; copy y bytes from the + extra block; seek forwards in oldfile by z bytes". + */ - /* Read header */ - if (fread(header, 1, 32, f) < 32) { - if (feof(f)) - errx(1, "Corrupt patch\n"); - err(1, "fread(%s)", argv[3]); - } + /* Read header */ + if (fread(header, 1, 32, f) < 32) { + if (feof(f)) { + warnx("Corrupt patch\n"); + } else { + warn("fread(%s)", argv[3]); + } + goto cleanup; + } - /* Check for appropriate magic */ - if (memcmp(header, "BSDIFF40", 8) == 0) - io = &BSDIFF40_funcs; - else if (memcmp(header, "BSDIFN40", 8) == 0) - io = &BSDIFN40_funcs; - else - errx(1, "Corrupt patch\n"); + /* Check for appropriate magic */ + if (memcmp(header, "BSDIFF40", 8) == 0) + io = &BSDIFF40_funcs; + else if (memcmp(header, "BSDIFN40", 8) == 0) + io = &BSDIFN40_funcs; + else { + warnx("Corrupt patch\n"); + goto cleanup; + } - /* Read lengths from header */ - bzctrllen=offtin(header+8); - bzdatalen=offtin(header+16); - newsize=offtin(header+24); - if((bzctrllen<0) || (bzdatalen<0) || (newsize<0)) - errx(1,"Corrupt patch\n"); + /* Read lengths from header */ + bzctrllen=offtin(header+8); + bzdatalen=offtin(header+16); + newsize=offtin(header+24); + if((bzctrllen<0) || (bzdatalen<0) || (newsize<0)) { + warnx("Corrupt patch\n"); + goto cleanup; + } - /* Close patch file and re-open it via libbzip2 at the right places */ - if (fclose(f)) - err(1, "fclose(%s)", argv[3]); - if ((cpf = fopen(argv[3], "r")) == NULL) - err(1, "fopen(%s)", argv[3]); - if (fseeko(cpf, 32, SEEK_SET)) - err(1, "fseeko(%s, %lld)", argv[3], - (long long)32); - cstream = io->open(cpf); - if ((dpf = fopen(argv[3], "r")) == NULL) - err(1, "fopen(%s)", argv[3]); - if (fseeko(dpf, 32 + bzctrllen, SEEK_SET)) - err(1, "fseeko(%s, %lld)", argv[3], - (long long)(32 + bzctrllen)); - dstream = io->open(dpf); - if ((epf = fopen(argv[3], "r")) == NULL) - err(1, "fopen(%s)", argv[3]); - if (fseeko(epf, 32 + bzctrllen + bzdatalen, SEEK_SET)) - err(1, "fseeko(%s, %lld)", argv[3], - (long long)(32 + bzctrllen + bzdatalen)); - estream = io->open(epf); + /* Close patch file and re-open it via libbzip2 at the right places */ + if (fclose(f)) { + warn("fclose(%s)", argv[3]); + f = NULL; + goto cleanup; + } + f = NULL; + + if ((cpf = fopen(argv[3], "r")) == NULL) { + warn("fopen(%s)", argv[3]); + goto cleanup; + } + if (fseeko(cpf, 32, SEEK_SET)) { + warn("fseeko(%s, %lld)", argv[3], + (long long)32); + goto cleanup; + } + cstream = io->open(cpf); + if (cstream == NULL) { + warn("cstream open"); + goto cleanup; + } + if ((dpf = fopen(argv[3], "r")) == NULL) { + warn("fopen(%s)", argv[3]); + goto cleanup; + } + if (fseeko(dpf, 32 + bzctrllen, SEEK_SET)) { + warn("fseeko(%s, %lld)", argv[3], + (long long)(32 + bzctrllen)); + goto cleanup; + } + dstream = io->open(dpf); + if (dstream == NULL) { + warn("dstream open"); + goto cleanup; + } + if ((epf = fopen(argv[3], "r")) == NULL) { + warn("fopen(%s)", argv[3]); + goto cleanup; + } + if (fseeko(epf, 32 + bzctrllen + bzdatalen, SEEK_SET)) { + warn("fseeko(%s, %lld)", argv[3], + (long long)(32 + bzctrllen + bzdatalen)); + goto cleanup; + } + estream = io->open(epf); + if (estream == NULL) { + warn("estream open"); + goto cleanup; + } + off_t size = 0; + old = readfile(argv[1], &size); + if (old == NULL) { + warn("old file: %s", argv[1]); + goto cleanup; + } + + oldsize = size; + + if((new=malloc((size_t)newsize+1))==NULL) { + warn("Failed to allocate memory for new"); + goto cleanup; + } - if(((fd=open(argv[1],O_RDONLY,0))<0) || - ((oldsize=lseek(fd,0,SEEK_END))==-1) || - ((old=malloc(oldsize+1))==NULL) || - (lseek(fd,0,SEEK_SET)!=0) || - (read(fd,old,oldsize)!=oldsize) || - (close(fd)==-1)) err(1,"%s",argv[1]); - if((new=malloc(newsize+1))==NULL) err(1,NULL); + oldpos=0;newpos=0; + while(newposread(cstream, buf, 8); + if (lenread < 8) { + warnx("Corrupt patch\n"); + goto cleanup; + } + ctrl[i]=offtin(buf); + }; - oldpos=0;newpos=0; - while(newposread(cstream, buf, 8); - if (lenread < 8) - errx(1, "Corrupt patch\n"); - ctrl[i]=offtin(buf); - }; + /* Sanity-check */ + if(newpos+ctrl[0]>newsize) { + warnx("Corrupt patch\n"); + goto cleanup; + } - /* Sanity-check */ - if(newpos+ctrl[0]>newsize) - errx(1,"Corrupt patch\n"); + /* Read diff string */ + lenread = io->read(dstream, new + newpos, ctrl[0]); + if (lenread < 0 || lenread < ctrl[0]) { + warnx("Corrupt patch\n"); + goto cleanup; + } - /* Read diff string */ - lenread = io->read(dstream, new + newpos, ctrl[0]); - if (lenread < ctrl[0]) - errx(1, "Corrupt patch\n"); + /* Add old data to diff string */ + for(i=0;i=0) && (oldpos+i=0) && (oldpos+inewsize) { + warnx("Corrupt patch\n"); + goto cleanup; + } - /* Sanity-check */ - if(newpos+ctrl[1]>newsize) - errx(1,"Corrupt patch\n"); + /* Read extra string */ + lenread = io->read(estream, new + newpos, ctrl[1]); + if (lenread < 0 || lenread < ctrl[1]) { + warnx("Corrupt patch\n"); + goto cleanup; + } - /* Read extra string */ - lenread = io->read(estream, new + newpos, ctrl[1]); - if (lenread < ctrl[1]) - errx(1, "Corrupt patch\n"); + /* Adjust pointers */ + newpos+=ctrl[1]; + oldpos+=ctrl[2]; + }; - /* Adjust pointers */ - newpos+=ctrl[1]; - oldpos+=ctrl[2]; - }; + /* Clean up the bzip2 reads */ + io->close(cstream); + cstream = NULL; + io->close(dstream); + dstream = NULL; + io->close(estream); + estream = NULL; + + if (fclose(cpf) != 0) { + warn("fclose cpf(%s)", argv[3]); + cpf = NULL; + goto cleanup; + } + cpf = NULL; + + if (fclose(dpf) != 0) { + warn("fclose dpf(%s)", argv[3]); + dpf = NULL; + goto cleanup; + } + dpf = NULL; + + if (fclose(epf) != 0) { + warn("fclose epf(%s)", argv[3]); + epf = NULL; + goto cleanup; + } + epf = NULL; - /* Clean up the bzip2 reads */ - io->close(cstream); - io->close(dstream); - io->close(estream); - if (fclose(cpf) || fclose(dpf) || fclose(epf)) - err(1, "fclose(%s)", argv[3]); + /* Write the new file */ + f = fopen(argv[2], "w"); + if (f == NULL) { + warn("failed to write new file: %s", argv[2]); + goto cleanup; + } + + if (fwrite(new, 1, (size_t)newsize, f) < (size_t)newsize) { + warn("failed to write to new file: %s", argv[2]); + goto cleanup; + } + + if (fclose(f) != 0) { + warn("failed to close new file: %s", argv[2]); + f = NULL; + goto cleanup; + } + f = NULL; + + exitstatus = 0; +cleanup: + free(new); + free(old); + + if (f != NULL) { + fclose(f); + } + + if (estream != NULL) { + io->close(estream); + } + + if (epf != NULL) { + fclose(epf); + } + + if (dstream != NULL) { + io->close(dstream); + } + + if (dpf != NULL) { + fclose(dpf); + } + + if (cstream != NULL) { + io->close(cstream); + } + + if (cpf != NULL) { + fclose(cpf); + } - /* Write the new file */ - if(((fd=open(argv[2],O_CREAT|O_TRUNC|O_WRONLY,0666))<0) || - (write(fd,new,newsize)!=newsize) || (close(fd)==-1)) - err(1,"%s",argv[2]); - - free(new); - free(old); - - return 0; + return exitstatus; } diff --git a/bin/sign_update b/bin/sign_update index cd149133..7c439990 100755 --- a/bin/sign_update +++ b/bin/sign_update @@ -1,4 +1,4 @@ -#!/bin/sh +#!/bin/bash set -e set -o pipefail if [ "$#" -ne 2 ]; then diff --git a/fileop/SUFileOperationConstants.h b/fileop/SUFileOperationConstants.h new file mode 100644 index 00000000..9f4ba685 --- /dev/null +++ b/fileop/SUFileOperationConstants.h @@ -0,0 +1,16 @@ +// +// SUFileOperationConstants.h +// Sparkle +// +// Created by Mayur Pawashe on 6/5/16. +// Copyright © 2016 Sparkle Project. All rights reserved. +// + +extern char * const SUFileOpRemoveQuarantineCommand; +extern char * const SUFileOpCopyCommand; +extern char * const SUFileOpMoveCommand; +extern char * const SUFileOpChangeOwnerAndGroupCommand; +extern char * const SUFileOpUpdateModificationAndAccessTimeCommand; +extern char * const SUFileOpMakeDirectoryCommand; +extern char * const SUFileOpRemoveCommand; +extern char * const SUFileOpInstallCommand; diff --git a/fileop/SUFileOperationConstants.m b/fileop/SUFileOperationConstants.m new file mode 100644 index 00000000..5ece5917 --- /dev/null +++ b/fileop/SUFileOperationConstants.m @@ -0,0 +1,18 @@ +// +// SUFileOperationConstants.m +// Sparkle +// +// Created by Mayur Pawashe on 6/5/16. +// Copyright © 2016 Sparkle Project. All rights reserved. +// + +#import "SUFileOperationConstants.h" + +char * const SUFileOpRemoveQuarantineCommand = "xattr-d-apple-quarantine"; +char * const SUFileOpCopyCommand = "cp"; +char * const SUFileOpMoveCommand = "mv"; +char * const SUFileOpChangeOwnerAndGroupCommand = "chown"; +char * const SUFileOpUpdateModificationAndAccessTimeCommand = "touch"; +char * const SUFileOpMakeDirectoryCommand = "mkdir"; +char * const SUFileOpRemoveCommand = "rm"; +char * const SUFileOpInstallCommand = "installer"; diff --git a/fileop/fileop.m b/fileop/fileop.m new file mode 100644 index 00000000..044f2abc --- /dev/null +++ b/fileop/fileop.m @@ -0,0 +1,151 @@ +// +// fileop.m +// fileop +// +// Created by Mayur Pawashe on 6/5/16. +// Copyright © 2016 Sparkle Project. All rights reserved. +// + +#import +#import "SUFileManager.h" +#import "SUFileOperationConstants.h" + +// If we fail, we exit with a unique status code +// We don't try to NSLog because the logs can't be seen anywhere, +// and we don't want to log to a file irresponsibly (especially as root), +// nor want to communicate to the parent forcing the parent to read from the stdout pipe +// (allowing us to avoid any sort of potential blocking issues?) +typedef NS_ENUM(uint8_t, SUFileOpError) +{ + SUWritePIDFailure = 0x02, + SUFlushFailure = 0x03, + SUInsufficientNumberOfArguments = 0x04, + SUCommandNameUTF8ParseFailure = 0x05, + SUPathUTF8ParseFailure = 0x06, + SUQuarantineRemovalFailure = 0x07, + SUCopyFailure = 0x08, + SUMoveFailure = 0x09, + SUChangeOwnerAndGroupFailure = 0x0A, + SUTouchFailure = 0x0B, + SUMakeDirectoryFailure = 0x0C, + SURemoveFailure = 0x0D, + SUPackageFailureStatusCode = 0x0E, + SUPackageRaisedExceptionFailure = 0x0F, + SUInvalidCommandFailure = 0x10, + // This code can be OR'd with another one to produce a unique combination + SUInvalidOrNoDestination = 0x80 +}; + +int main(int argc, const char *argv[]) +{ + @autoreleasepool { + // Before we do anything, we should let the parent know our pid so they can wait() on us + // We do this because AuthorizationExecuteWithPrivileges() has no way of reporting back the child pid, + // but it does give us a communication pipe + uint32_t pid = CFSwapInt32HostToLittle((uint32_t)getpid()); + if (fwrite(&pid, sizeof(pid), 1, stdout) < 1) { + exit(SUWritePIDFailure); + } + + if (fflush(stdout) != 0) { + exit(SUFlushFailure); + } + + // At least we need the command name and file path arguments + if (argc < 3) { + exit(SUInsufficientNumberOfArguments); + } + + NSString *command = [[NSString alloc] initWithUTF8String:argv[1]]; + if (command == nil) { + exit(SUCommandNameUTF8ParseFailure); + } + + NSString *filepath = [[NSString alloc] initWithUTF8String:argv[2]]; + if (filepath == nil) { + exit(SUPathUTF8ParseFailure); + } + + NSURL *fileURL = [NSURL fileURLWithPath:filepath]; + if (fileURL == nil) { + exit(SUPathUTF8ParseFailure); + } + + NSURL *destinationURL = nil; + if (argc >= 4) { + NSString *destinationPath = [[NSString alloc] initWithUTF8String:argv[3]]; + if (destinationPath != nil) { + destinationURL = [NSURL fileURLWithPath:destinationPath]; + } + } + + // This tool should be executed as root, so we should not try to authorize + SUFileManager *fileManager = [SUFileManager defaultManager]; + + if ([command isEqualToString:@(SUFileOpRemoveQuarantineCommand)]) { + if (![fileManager releaseItemFromQuarantineAtRootURL:fileURL error:NULL]) { + exit(SUQuarantineRemovalFailure); + } + } else if ([command isEqualToString:@(SUFileOpCopyCommand)]) { + if (destinationURL != nil) { + if (![fileManager copyItemAtURL:fileURL toURL:destinationURL error:NULL]) { + exit(SUCopyFailure); + } + } else { + exit(SUInvalidOrNoDestination | SUCopyFailure); + } + } else if ([command isEqualToString:@(SUFileOpMoveCommand)]) { + if (destinationURL != nil) { + if (![fileManager moveItemAtURL:fileURL toURL:destinationURL error:NULL]) { + exit(SUMoveFailure); + } + } else { + exit(SUInvalidOrNoDestination | SUMoveFailure); + } + } else if ([command isEqualToString:@(SUFileOpChangeOwnerAndGroupCommand)]) { + if (destinationURL != nil) { + if (![fileManager changeOwnerAndGroupOfItemAtRootURL:fileURL toMatchURL:destinationURL error:NULL]) { + exit(SUChangeOwnerAndGroupFailure); + } + } else { + exit(SUInvalidOrNoDestination | SUChangeOwnerAndGroupFailure); + } + } else if ([command isEqualToString:@(SUFileOpUpdateModificationAndAccessTimeCommand)]) { + if (![fileManager updateModificationAndAccessTimeOfItemAtURL:fileURL error:NULL]) { + exit(SUTouchFailure); + } + } else if ([command isEqualToString:@(SUFileOpMakeDirectoryCommand)]) { + if (![fileManager makeDirectoryAtURL:fileURL error:NULL]) { + exit(SUMakeDirectoryFailure); + } + } else if ([command isEqualToString:@(SUFileOpRemoveCommand)]) { + if (![fileManager removeItemAtURL:fileURL error:NULL]) { + exit(SURemoveFailure); + } + } else if ([command isEqualToString:@(SUFileOpInstallCommand)]) { + // The one command that can *only* be run as the root user + NSString *installerPath = @"/usr/sbin/installer"; + + NSTask *task = [[NSTask alloc] init]; + task.launchPath = installerPath; + task.arguments = @[@"-pkg", filepath, @"-target", @"/"]; + // Output won't show up anyway, so we may as well ignore it + task.standardError = [NSPipe pipe]; + task.standardOutput = [NSPipe pipe]; + + @try { + [task launch]; + [task waitUntilExit]; + if (task.terminationStatus != EXIT_SUCCESS) { + exit(SUPackageFailureStatusCode); + } + } @catch (NSException *) { + exit(SUPackageRaisedExceptionFailure); + } + } else { + exit(SUInvalidCommandFailure); + } + + return EXIT_SUCCESS; + } +}