Compare commits

..
6 Commits
Author SHA1 Message Date
Marcus Ososbase 5064a9e26c 1.14.2 2016-11-01 14:25:00 -04:00
mosobase f6dbebb0e2 Merge pull request #1 from mosobase/ui-suppresion
Patched loophole that allowed Sparkle to present UI even though it wa…
2016-11-01 14:23:01 -04:00
Marcus Ososbase 85478fc2bb Patched loophole that allowed Sparkle to present UI even though it was suppressed
Added some log statements for future debugging if necessary
2016-10-31 15:12:08 -04:00
Marcus Osobase b3ce4141d1 Automatically download update and wait until restart to install 2016-05-05 16:07:51 -04:00
Marcus Osobase 2095b97ae3 Allow delegate to decide how to proceed with new update 2016-05-03 15:56:09 -04:00
Marcus Osobase aae539bc9b Dont show update window 2016-05-03 11:54:36 -04:00
286 changed files with 4518 additions and 7389 deletions

No files matched your search

-7
View File
@@ -28,13 +28,6 @@ Icon
.Spotlight-V100
.Trashes
# With Carthage, if Sparkle is included as a Git submodule (e.g. with the
# --use-submodules option), the main module's .gitignore can't reach all the
# way inside the submodule to ignore the added Carthage/Build symlink, and Git
# keeps complaining about untracked changes in the submodule forever, which
# is very annoying. To avoid that issue, ignore here in Sparkle instead.
Carthage/Build
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
+3 -1
View File
@@ -1,5 +1,7 @@
language: objective-c
osx_image: xcode8.2
osx_image: xcode7
before_install:
- brew update
- brew install macmade/tap/xcode-coveralls
script: make ci
after_success: xcode-coveralls --exclude /Applications --exclude Tests --exclude Vendor build/Build/Intermediates/Sparkle.build/Coverage/Sparkle.build/Objects-normal/x86_64
+4 -82
View File
@@ -1,81 +1,3 @@
# 1.18.0
* Name of the host app is used in authorization prompt (the `SPARKLE_RELAUNCH_TOOL_NAME` setting is now obsolete)
* More detailed progress bar for package installers (Kornel Lesiński)
* Disabled the keyboard shortcut for the install button for scheduled updates to avoid accidental installs. (George Nachman)
* generate_appcast tool adds release notes if there's an .html file with the same base name as the archive (Brett Walker)
* Added `sparkle:shortVersionString` to the enclosure, #1032 (Brett Walker)
* Fixed Japanese localization (1024jp)
* Fixed escaping of system profile URLs
* Added more logging in various failure cases (Kornel Lesiński)
* Better error message for quarantined apps that can't be updated
# 1.17.0
* Added Touch Bar support (Bi11)
* Upgraded SULog to use logging APIs that Apple provides built-in (Zorg)
* Skip buttons are disabled if the update is marked as critical (Kornel Lesiński)
* Background updates ask OS for lower-priority networking (Kornel Lesiński)
* Refactorings to sync with upcoming 2.0
* Added kqueue based termination listener (Zorg)
* Added AppKit prevention guards to modules that shouldn't import it (Zorg)
* Added Obj-C generics where applicable (Zorg)
* Made SUBundleIcon & SUApplicationInfo take SUHost, not NSBundle (Zorg)
* Improved -[SUHost objectForInfoDictionaryKey:] (Zorg)
* Detect and fail if any two-way dependencies exist in the project (Zorg)
* generate_appcast:
* fixed handling of multiple directories in an archive
* percent encode the filename used in the delta url (Brett Walker)
* Update Sparkle.strings (BR Lingo)
* Improved handling of non-ASCII names in delta archives (Kornel Lesiński)
* Don't touch Info.plist unless git version changes (Václav Slavík)
# 1.16.0
* Guided package installs are now the default for updating packages (Zorg)
- `pkg` installers won't show any UI. If you require the old behavior of showing a full installer window, rename the `*.pkg` file to `*.sparkle_interactive.pkg`
* Previous version of the app is now deleted instead of staying in the trash (Zorg)
* Added `generate_appcast` helper tool (Kornel Lesiński)
* Made manual check resume pending automatic updates instead of starting a new update (Kornel Lesiński)
* Started using `length` value from RSS if HTTP doesn't give one (Zorg)
* Hidden automatic updates checkbox for information only updates (Bi11)
* Added progressbar for DMG and binary delta extraction (Kornel Lesiński)
* Fixed showing of download status if we attempt a 2nd download (Zorg)
* Refactorings to sync with upcoming 2.0
* Decoupled and simplified installation code using protocols (Zorg)
* Added nullability annotations (Zorg)
* Allowed delegate methods that return an object to return nil (Zorg)
* Decreased responsibility of SUHost and moved code into other components (Zorg)
* Removed Sparkle.pch and many file #includes (Zorg)
# 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)
@@ -113,7 +35,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 macOS 10.11
- Note that Apple has deprecated insecure HTTP in OS X 10.11
* Improved Autoupdate application (Zorg)
* Do all the installation work after the runloop is set up
* TerminationListener only does termination listening now
@@ -211,12 +133,12 @@ Important security fixes:
# 1.8.0 (Jul 26, 2014)
* New SUDSAVerifier based on up-to-date macOS APIs (Zachary Waldowski)
* New SUDSAVerifier based on up-to-date OS X APIs (Zachary Waldowski)
* Detailed error log for failed signature checks (Kornel Lesiński)
* Converted Sparkle to ARC (C.W. Betts)
* Converted ivars to properties. (Jake Petroules)
* Cocoapod support (Xhacker Liu)
* Quarantine removal on macOS 10.10 (C.W. Betts)
* Quarantine removal on OS X 10.10 (C.W. Betts)
* Updated Japanese localization (1024jp)
* Added Greek localization
@@ -237,7 +159,7 @@ Important security fixes:
# 1.7.0
* Dropped support for macOS 10.6. Sparkle now supports 10.7 and newer (including 10.10 Yosemite) on 64-bit Intel Macs (the last 32-bit Mac was released in 2006).
* Dropped support for OS X 10.6. Sparkle now supports 10.7 and newer (including 10.10 Yosemite) on 64-bit Intel Macs (the last 32-bit Mac was released in 2006).
* Removed use of deprecated functions (Zachary Waldowski)
* Switched to modern Obj-C runtime and new literals syntax
* Removed pre-10.7 code. (C.W. Betts)
-74
View File
@@ -1,74 +0,0 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level of experience,
nationality, personal appearance, race, religion, or sexual identity and
orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at kornel+sparkle@geekhood.net. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/
+7 -9
View File
@@ -2,7 +2,6 @@
SPARKLE_BUNDLE_IDENTIFIER = org.sparkle-project.Sparkle
SPARKLE_RELAUNCH_TOOL_NAME = Autoupdate
SPARKLE_FILEOP_TOOL_NAME = fileop
SPARKLE_APPEND_VERSION_NUMBER = 1
@@ -16,14 +15,15 @@ SPARKLE_AUTOMATED_DOWNGRADES = 0
SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME = 0
SPARKLE_VERSION_MAJOR = 1
SPARKLE_VERSION_MINOR = 18
SPARKLE_VERSION_MINOR = 14
SPARKLE_VERSION_PATCH = 0
TUNNELBEAR_ID = TB
SPARKLE_VERSION = $(SPARKLE_VERSION_MAJOR).$(SPARKLE_VERSION_MINOR).$(SPARKLE_VERSION_PATCH)$(TUNNELBEAR_ID)
SPARKLE_VERSION = $(SPARKLE_VERSION_MAJOR).$(SPARKLE_VERSION_MINOR).$(SPARKLE_VERSION_PATCH)
CURRENT_PROJECT_VERSION = $(SPARKLE_VERSION)
ALWAYS_SEARCH_USER_PATHS = NO
ENABLE_STRICT_OBJC_MSGSEND = YES
GCC_PRECOMPILE_PREFIX_HEADER = YES
GCC_PREFIX_HEADER = Sparkle/Sparkle.pch
GCC_SYMBOLS_PRIVATE_EXTERN = YES
GCC_INLINES_ARE_PRIVATE_EXTERN = YES
ARCHS = $(ARCHS_STANDARD)
@@ -31,15 +31,12 @@ MACOSX_DEPLOYMENT_TARGET = 10.7
PRODUCT_NAME = ${TARGET_NAME}
PRODUCT_BUNDLE_IDENTIFIER = org.sparkle-project.Sparkle.${PRODUCT_NAME:rfc1034identifier}
GCC_PREPROCESSOR_DEFINITIONS_COMMON = SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME=$(SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME) SPARKLE_AUTOMATED_DOWNGRADES=$(SPARKLE_AUTOMATED_DOWNGRADES) SPARKLE_APPEND_VERSION_NUMBER=$(SPARKLE_APPEND_VERSION_NUMBER) SPARKLE_BUNDLE_IDENTIFIER=\"$(SPARKLE_BUNDLE_IDENTIFIER)\" SPARKLE_RELAUNCH_TOOL_NAME=\"$(SPARKLE_RELAUNCH_TOOL_NAME)\" SPARKLE_FILEOP_TOOL_NAME=\"$(SPARKLE_FILEOP_TOOL_NAME)\"
GCC_PREPROCESSOR_DEFINITIONS_COMMON = SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME=$(SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME) SPARKLE_AUTOMATED_DOWNGRADES=$(SPARKLE_AUTOMATED_DOWNGRADES) SPARKLE_APPEND_VERSION_NUMBER=$(SPARKLE_APPEND_VERSION_NUMBER) SPARKLE_BUNDLE_IDENTIFIER=\"$(SPARKLE_BUNDLE_IDENTIFIER)\" SPARKLE_RELAUNCH_TOOL_NAME=\"$(SPARKLE_RELAUNCH_TOOL_NAME)\"
CLANG_ENABLE_OBJC_ARC = YES
GCC_ENABLE_PASCAL_STRINGS = NO
GCC_NO_COMMON_BLOCKS = YES;
COMBINE_HIDPI_IMAGES = NO;
// Enable warnings
CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;
CLANG_ANALYZER_SECURITY_FLOATLOOPCOUNTER = YES
CLANG_ANALYZER_SECURITY_INSECUREAPI_RAND = YES
CLANG_ANALYZER_SECURITY_INSECUREAPI_STRCPY = YES
@@ -54,6 +51,7 @@ CLANG_WARN_OBJC_EXPLICIT_OWNERSHIP_TYPE = YES
CLANG_WARN_OBJC_IMPLICIT_ATOMIC_PROPERTIES = YES
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES
CLANG_WARN_OBJC_MISSING_PROPERTY_SYNTHESIS = YES
CLANG_WARN_OBJC_RECEIVER_WEAK = YES
CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES
CLANG_WARN_SUSPICIOUS_IMPLICIT_CONVERSION = YES
CLANG_WARN_UNREACHABLE_CODE = YES
@@ -89,4 +87,4 @@ CLANG_ENABLE_MODULES[sdk=macosx10.8] = NO
WARNING_CFLAGS_EXTRA = -Wno-custom-atomic-properties -Wno-implicit-atomic-properties
// Turn on all warnings, then disable a few which are almost impossible to avoid
WARNING_CFLAGS = -Wall -Weverything -Wno-unused-macros -Wno-gnu-statement-expression -Wno-arc-repeated-use-of-weak -Wno-auto-import $(WARNING_CFLAGS_EXTRA)
WARNING_CFLAGS = -Wall -Weverything -Wno-unused-macros -Wno-gnu-statement-expression -Wno-receiver-is-weak -Wno-arc-repeated-use-of-weak -Wno-auto-import $(WARNING_CFLAGS_EXTRA)
@@ -3,6 +3,7 @@
// Debug only
GCC_OPTIMIZATION_LEVEL = 0
SWIFT_OPTIMIZATION_LEVEL = -Onone
DEBUG_INFORMATION_FORMAT = dwarf
ENABLE_TESTABILITY = YES
GCC_GENERATE_DEBUGGING_SYMBOLS = YES
@@ -3,6 +3,7 @@
// Release only
GCC_OPTIMIZATION_LEVEL = s
SWIFT_OPTIMIZATION_LEVEL = -Ofast
DEBUG_INFORMATION_FORMAT = dwarf-with-dsym
GCC_GENERATE_DEBUGGING_SYMBOLS = YES
GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS_COMMON)
-5
View File
@@ -1,5 +0,0 @@
// Fileop tool only
PRODUCT_NAME = $(SPARKLE_FILEOP_TOOL_NAME)
SKIP_INSTALL = YES
CLANG_ENABLE_MODULES = NO
@@ -1,7 +0,0 @@
// Generate Appcast only
#include "ConfigSwift.xcconfig"
SWIFT_OBJC_BRIDGING_HEADER = generate_appcast/Appcast-Bridging-Header.h
MACOSX_DEPLOYMENT_TARGET = 10.11
PRODUCT_NAME = generate_appcast
@@ -1,4 +0,0 @@
// Generate Appcast Debug
#include "ConfigGenerateAppcast.xcconfig"
#include "ConfigSwiftDebug.xcconfig"
@@ -1,4 +0,0 @@
// Generate Appcast Release
#include "ConfigGenerateAppcast.xcconfig"
#include "ConfigSwiftRelease.xcconfig"
-1
View File
@@ -1 +0,0 @@
SWIFT_VERSION = 3.0
-1
View File
@@ -1 +0,0 @@
SWIFT_OPTIMIZATION_LEVEL = -Onone
@@ -1 +0,0 @@
SWIFT_OPTIMIZATION_LEVEL = -Owholemodule
-2
View File
@@ -1,7 +1,5 @@
// UI Test only
#include "ConfigSwift.xcconfig"
INFOPLIST_FILE = UITests/UITests-Info.plist
WRAPPER_EXTENSION = xctest
MACOSX_DEPLOYMENT_TARGET = 10.11
@@ -1,2 +1 @@
#include "ConfigUITest.xcconfig"
#include "ConfigSwiftDebug.xcconfig"
@@ -1,2 +1 @@
#include "ConfigUITest.xcconfig"
#include "ConfigSwiftRelease.xcconfig"
-2
View File
@@ -1,7 +1,5 @@
// Unit Test only
#include "ConfigSwift.xcconfig"
INFOPLIST_FILE = Tests/SparkleTests-Info.plist
WRAPPER_EXTENSION = xctest
OTHER_CFLAGS = $(inherited) -iframework"$(DEVELOPER_FRAMEWORKS_DIR)" -iframework"$(PLATFORM_DIR)/Developer/Library/Frameworks"
@@ -1,2 +1 @@
#include "ConfigUnitTest.xcconfig"
#include "ConfigSwiftDebug.xcconfig"
@@ -1,2 +1 @@
#include "ConfigUnitTest.xcconfig"
#include "ConfigSwiftRelease.xcconfig"
-9
View File
@@ -2,13 +2,6 @@
set -e
if [ "$ACTION" = "" ] ; then
# Sanity check that the Podspec version matches the Sparkle version
spec_version=$(printf "require 'cocoapods'\nspec = %s\nprint spec.version" "$(cat "$SRCROOT/Sparkle.podspec")" | LANG=en_US.UTF-8 ruby)
if [ "$spec_version" != "$CURRENT_PROJECT_VERSION" ] ; then
echo "podspec version '$spec_version' does not match the current project version '$CURRENT_PROJECT_VERSION'" >&2
exit 1
fi
rm -rf "$CONFIGURATION_BUILD_DIR/staging"
rm -f "Sparkle-$CURRENT_PROJECT_VERSION.tar.bz2"
@@ -16,7 +9,6 @@ if [ "$ACTION" = "" ] ; then
cp "$SRCROOT/CHANGELOG" "$SRCROOT/LICENSE" "$SRCROOT/Resources/SampleAppcast.xml" "$CONFIGURATION_BUILD_DIR/staging"
cp -R "$SRCROOT/bin" "$CONFIGURATION_BUILD_DIR/staging"
cp "$CONFIGURATION_BUILD_DIR/BinaryDelta" "$CONFIGURATION_BUILD_DIR/staging/bin"
cp "$CONFIGURATION_BUILD_DIR/generate_appcast" "$CONFIGURATION_BUILD_DIR/staging/bin"
cp -R "$CONFIGURATION_BUILD_DIR/Sparkle Test App.app" "$CONFIGURATION_BUILD_DIR/staging"
cp -R "$CONFIGURATION_BUILD_DIR/Sparkle.framework" "$CONFIGURATION_BUILD_DIR/staging"
@@ -24,7 +16,6 @@ if [ "$ACTION" = "" ] ; then
# because missing dSYMs in a release build SHOULD trigger a build failure
if [ "$CONFIGURATION" = "Release" ] ; then
cp -R "$CONFIGURATION_BUILD_DIR/BinaryDelta.dSYM" "$CONFIGURATION_BUILD_DIR/staging/bin"
cp -R "$CONFIGURATION_BUILD_DIR/generate_appcast.dSYM" "$CONFIGURATION_BUILD_DIR/staging/bin"
cp -R "$CONFIGURATION_BUILD_DIR/Sparkle Test App.app.dSYM" "$CONFIGURATION_BUILD_DIR/staging"
cp -R "$CONFIGURATION_BUILD_DIR/Sparkle.framework.dSYM" "$CONFIGURATION_BUILD_DIR/staging"
fi
+7 -19
View File
@@ -13,28 +13,16 @@ if [ -z "$SRCROOT" ] || \
exit 1
fi
version="$CURRENT_PROJECT_VERSION"
# Get version in format 1.x.x-commits-hash
gitversion=$( cd "$SRCROOT"; git describe --tags --match '[12].*' || true )
if [ -z "$gitversion" ] ; then
echo "$0: Can't find a Git hash!" 1>&2
# Get the current Git master hash
version=$(cd "$SRCROOT" ; git show-ref --abbrev heads/master | awk '{print $1}')
if [ -z "$version" ] ; then
echo "$0: Can't find a Git hash!" 1>&2
exit 0
fi
# remove everything before the first "-" to keep the hash part only
versionsuffix=${gitversion#*-};
if [ "$versionsuffix" != "$gitversion" ]; then
version="$version $versionsuffix"
fi
version="$CURRENT_PROJECT_VERSION git-$version"
# and use it to set the CFBundleShortVersionString value
export PATH="$PATH:/usr/libexec"
if [ -f "$BUILT_PRODUCTS_DIR/$INFOPLIST_PATH" ] ; then
oldversion=$(PlistBuddy -c "Print :CFBundleShortVersionString" "$BUILT_PRODUCTS_DIR/$INFOPLIST_PATH")
fi
if [ "$version" != "$oldversion" ] ; then
PlistBuddy -c "Set :CFBundleShortVersionString '$version'" \
"$BUILT_PRODUCTS_DIR/$INFOPLIST_PATH"
fi
PlistBuddy -c "Set :CFBundleShortVersionString '$version'" \
"$BUILT_PRODUCTS_DIR/$INFOPLIST_PATH"
+2 -2
View File
@@ -1,6 +1,6 @@
PROJECT_NAME = Sparkle
PROJECT_NUMBER = 1.14.0
PROJECT_BRIEF = "A software update framework for macOS"
PROJECT_NUMBER = 1.7.1
PROJECT_BRIEF = "A software update framework for OS X"
PROJECT_LOGO = Resources/Images.xcassets/AppIcon.appiconset/icon_32x32@2x.png
RECURSIVE = YES
-1
View File
@@ -1,7 +1,6 @@
Copyright (c) 2006-2013 Andy Matuschak.
Copyright (c) 2009-2013 Elgato Systems GmbH.
Copyright (c) 2011-2014 Kornel Lesiński.
Copyright (c) 2015-2017 Mayur Pawashe.
Copyright (c) 2014 C.W. Betts.
Copyright (c) 2014 Petroules Corporation.
Copyright (c) 2014 Big Nerd Ranch.
+2 -3
View File
@@ -14,14 +14,13 @@ 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"
@echo "Don't forget to update CocoaPods!"
build:
xcodebuild clean build
test:
xcodebuild -scheme Distribution -configuration Debug test
./objc_dep/objc_dep.py -t .
uitest:
xcodebuild -scheme UITests -configuration Debug test
@@ -32,7 +31,7 @@ ci:
( rm -rf build && xcodebuild -sdk "macosx10.$$i" -scheme Distribution -configuration Coverage -derivedDataPath build ) || exit 1 ; \
fi ; \
done
for i in {10..12} ; do \
for i in {10..11} ; do \
if xcrun --sdk "macosx10.$$i" --show-sdk-path 2> /dev/null ; then \
( rm -rf build && xcodebuild -sdk "macosx10.$$i" -scheme Distribution -configuration Coverage -derivedDataPath build test ) || exit 1 ; \
fi ; \
-24
View File
@@ -1,24 +0,0 @@
# To update the icon run make -f Makefile-icon
# Requires:
# autoconf, automake, libtool, pkg-config, pngquant
ICONDIR=./Resources/Images.xcassets/AppIcon.appiconset
OPTIMIZEDICONS=$(ICONDIR)/optimized_16x16.png $(ICONDIR)/optimized_32x32.png $(ICONDIR)/optimized_128x128.png $(ICONDIR)/optimized_512x512.png
DESTICON=Resources/AppIcon.icns
all: $(DESTICON)
libicns:
git clone https://github.com/pornel/libicns.git
libicns/Makefile: libicns
( cd libicns && autoreconf -vif && ./configure )
libicns/icnsutils/png2icns: libicns/Makefile
( cd libicns && make -j8 )
optimized_%.png: icon_%.png
pngquant -s1 -f -o $@ $<
$(DESTICON): libicns/icnsutils/png2icns $(OPTIMIZEDICONS)
./libicns/icnsutils/png2icns $@ $(OPTIMIZEDICONS)
+27 -33
View File
@@ -1,59 +1,53 @@
# Sparkle [![Build Status](https://travis-ci.org/sparkle-project/Sparkle.svg?branch=master)](https://travis-ci.org/sparkle-project/Sparkle) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) [![CocoaPods](https://img.shields.io/cocoapods/v/Sparkle.svg?maxAge=2592000)]() <a href="https://www.stackpath.com/?utm_source=sparkle-github&amp;utm_medium=badge&amp;utm_campaign=readme"><img src="https://img.shields.io/badge/sponsored%20by-StackPath-orange.svg" alt="sponsored by: StackPath"></a>
# Sparkle [![Build Status](https://travis-ci.org/sparkle-project/Sparkle.svg?branch=master)](https://travis-ci.org/sparkle-project/Sparkle) [![Coverage Status](https://coveralls.io/repos/sparkle-project/Sparkle/badge.svg?branch=master&service=github)](https://coveralls.io/github/sparkle-project/Sparkle?branch=master) <a href="https://www.maxcdn.com/?utm_source=sparkle-github&amp;utm_medium=badge&amp;utm_campaign=readme"><img src="https://img.shields.io/badge/sponsored%20by-MaxCDN-orange.svg" alt="sponsored by: MaxCDN"></a>
Secure and reliable software update framework for Cocoa developers.
An easy-to-use software update framework for Cocoa developers.
<img src="Resources/Screenshot.png" width="732" alt="Sparkle shows familiar update window with release notes">
## Features
* Seamless. There's no mention of Sparkle; your icons and app name are used.
* Secure. Updates are verified using DSA signatures and Apple Code Signing.
* Fast. Supports delta updates which only patch files that have changed.
* Easy to install. Sparkle requires no code in your app, and only needs static files on a web server.
* Supports bundles, preference panes, plugins, and other non-.app software. Can install .pkg files for more complicated products.
* Handles permissions, quarantine and automatically asks for authentication if needed.
* Uses RSS-based appcasts for release information. Appcasts are a de-facto standard supported by 3rd party update-tracking programs and websites.
* Sparkle stays hidden until second launch for better first impressions.
* Truly self-updating — the user can choose to automatically download and install all updates in the background.
## Changes since 1.5b
* Compatibilty with macOS Sierra.
* Up-to-date with 10.12 SDK and Xcode 8 (supports macOS 10.7+).
* Important security fixes.
* Up-to-date with 10.11 SDK and Xcode 7. Supports OS X 10.7+.
* Cleaned up and modernized code, using ARC and Autolayout.
* Merged bugfixes, security fixes and some features from multiple Sparkle forks.
* Truly automatic background updates (no UI at all) when user agreed to "Automatically download and install updates in the future."
* 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
* 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.
* Displays release notes to the user via WebKit.
* Sparkle doesn't bug the user until second launch for better first impressions.
* Seamless integration—there's no mention of Sparkle; your icons and app name are used.
* Deep delegate support to make Sparkle work exactly as you need.
* Optionally sends system information to the server when checking for updates.
* Supports bundles, preference panes, plugins, and other non-.app software. Can install .pkg files for more complicated products.
* Supports branches due to minimum OS version requirements.
## Requirements
* Runtime: macOS 10.7 or greater
* Build: Xcode 7 and 10.8 SDK or greater
* Runtime: OS X 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/))
## Usage
See [getting started guide](https://sparkle-project.org/documentation/). No code is necessary, but a bit of Xcode configuration is required.
## Development
### API symbols
## API
Sparkle is built with `-fvisibility=hidden -fvisibility-inlines-hidden` which means no symbols are exported by default.
If you are adding a symbol to the public API you must decorate the declaration with the `SU_EXPORT` macro (grep the source code for examples).
### Building the distribution package
## Building the distribution package
`cd` to the root of the Sparkle source tree and run `make release`. Sparkle-*VERSION*.tar.bz2 will be created in a temporary directory and revealed in Finder after the build has completed.
Alternatively, build the Distribution scheme in the Xcode UI.
### Code of Conduct
We pledge to have an open and welcoming environment. See our [Code of Conduct](CODE_OF_CONDUCT.md).
## Project Sponsor
[StackPath](https://www.stackpath.com/?utm_source=sparkle-github&utm_medium=link&utm_campaign=readme-footer)
[MaxCDN](https://www.maxcdn.com/?utm_source=sparkle-github&utm_medium=link&utm_campaign=readme-footer)
Binary file not shown.
+1
View File
@@ -2,6 +2,7 @@
<rss version="2.0" xmlns:sparkle="http://www.andymatuschak.org/xml-namespaces/sparkle" xmlns:dc="http://purl.org/dc/elements/1.1/">
<channel>
<title>Your Great App's Changelog</title>
<link>http://you.com/app/appcast.xml</link>
<description>Most recent changes with links to updates.</description>
<language>en</language>
<item>
+6 -8
View File
@@ -1,7 +1,7 @@
Pod::Spec.new do |s|
s.name = "Sparkle"
s.version = "1.18.0TB"
s.summary = "A software update framework for macOS"
s.version = "1.14.2"
s.summary = "A software update framework for OS X"
s.description = "Sparkle is an easy-to-use software update framework for Cocoa developers."
s.homepage = "http://sparkle-project.org"
s.documentation_url = "http://sparkle-project.org/documentation/"
@@ -11,18 +11,16 @@ Pod::Spec.new do |s|
:file => 'LICENSE'
}
s.authors = {
'Mayur Pawashe' => 'zorgiepoo@gmail.com',
'Kornel Lesiński' => 'pornel@pornel.net',
'Jake Petroules' => 'jake.petroules@petroules.com',
'C.W. Betts' => 'computers57@hotmail.com',
'Andy Matuschak' => 'andy@andymatuschak.org',
'Kornel Lesiński' => 'pornel@pornel.net',
'C.W. Betts' => 'computers57@hotmail.com',
'Jake Petroules' => 'jake.petroules@petroules.com',
'Mayur Pawashe' => 'zorgiepoo@gmail.com',
}
s.platform = :osx, '10.7'
s.source = { :http => "https://s3.amazonaws.com/tunnelbear/sparkle/Sparkle-#{s.version}.tar.bz2" }
s.source_files = 'Sparkle.framework/Versions/A/Headers/*.h'
s.preserve_paths = 'bin/*'
s.public_header_files = 'Sparkle.framework/Versions/A/Headers/*.h'
s.vendored_frameworks = 'Sparkle.framework'
s.xcconfig = {
File diff suppressed because it is too large. Load diff
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0830"
LastUpgradeVersion = "0710"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0830"
LastUpgradeVersion = "0710"
version = "2.0">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0830"
LastUpgradeVersion = "0720"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,93 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0830"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "5AA96C541E0AE0DB00CA4346"
BuildableName = "generate_appcast"
BlueprintName = "generate_appcast"
ReferencedContainer = "container:Sparkle.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "5AA96C541E0AE0DB00CA4346"
BuildableName = "generate_appcast"
BlueprintName = "generate_appcast"
ReferencedContainer = "container:Sparkle.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Release"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "5AA96C541E0AE0DB00CA4346"
BuildableName = "generate_appcast"
BlueprintName = "generate_appcast"
ReferencedContainer = "container:Sparkle.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<CommandLineArguments>
</CommandLineArguments>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "5AA96C541E0AE0DB00CA4346"
BuildableName = "generate_appcast"
BlueprintName = "generate_appcast"
ReferencedContainer = "container:Sparkle.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
-20
View File
@@ -1,20 +0,0 @@
//
// AppKitPrevention.h
// Sparkle
//
// Created by Mayur Pawashe on 1/17/17.
// Copyright © 2017 Sparkle Project. All rights reserved.
//
// #include (not #import) this header to prevent AppKit from being imported
// Note this should be your LAST #include in your implementation file
// If this error is triggered, you can have Xcode indicate to you which source file including this header caused the issue
// One may wonder for certain targets where AppKit is banned completely, why just not link AppKit instead.
// Well, Xcode has thing called auto-linking that I don't trust very much.
// Even after trying to disable the setting, I've had targets able to link to AppKit without AppKit being specified in the list of linked libraries.
#ifdef _APPKITDEFINES_H
#error This is a core or daemon-safe module and should NOT import AppKit
#endif
-2
View File
@@ -28,7 +28,5 @@
<string>MainMenu</string>
<key>NSPrincipalClass</key>
<string>NSApplication</string>
<key>CFBundleIconFile</key>
<string>${ASSETCATALOG_COMPILER_APPICON_NAME}.icns</string>
</dict>
</plist>
+92 -84
View File
@@ -1,16 +1,70 @@
#import <Cocoa/Cocoa.h>
#import "SULocalizations.h"
#import "SUErrors.h"
#import <AppKit/AppKit.h>
#import "SUInstaller.h"
#import "SUHost.h"
#import "SUStandardVersionComparator.h"
#import "SUStatusController.h"
#import "SULog.h"
#import "SUInstallerProtocol.h"
#import "TerminationListener.h"
#include <unistd.h>
/*!
* Time this app uses to recheck if the parent has already died.
*/
static const NSTimeInterval SUParentQuitCheckInterval = .25;
@interface TerminationListener : NSObject
- (instancetype)initWithProcessId:(pid_t)pid;
@end
@interface TerminationListener ()
@property (nonatomic, assign) pid_t processIdentifier;
@property (nonatomic, strong) NSTimer *watchdogTimer;
@end
@implementation TerminationListener
@synthesize processIdentifier = _processIdentifier;
@synthesize watchdogTimer = _watchdogTimer;
- (instancetype)initWithProcessId:(pid_t)pid
{
if (!(self = [super init])) {
return nil;
}
self.processIdentifier = pid;
return self;
}
- (void)cleanupWithCompletion:(void (^)(void))completionBlock
{
[self.watchdogTimer invalidate];
completionBlock();
}
- (void)startListeningWithCompletion:(void (^)(void))completionBlock
{
BOOL alreadyTerminated = (getppid() == 1); // ppid is launchd (1) => parent terminated already
if (alreadyTerminated)
[self cleanupWithCompletion:completionBlock];
else
self.watchdogTimer = [NSTimer scheduledTimerWithTimeInterval:SUParentQuitCheckInterval target:self selector:@selector(watchdog:) userInfo:completionBlock repeats:YES];
}
- (void)watchdog:(NSTimer *)timer
{
if (![NSRunningApplication runningApplicationWithProcessIdentifier:self.processIdentifier]) {
[self cleanupWithCompletion:timer.userInfo];
}
}
@end
/*!
* If the Installation takes longer than this time the Application Icon is shown in the Dock so that the user has some feedback.
*/
@@ -71,8 +125,7 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.5;
self.hostPath = hostPath;
self.relaunchPath = relaunchPath;
SULog(SULogLevelDefault, @"PID to listen: %d", parentProcessId);
self.terminationListener = [[TerminationListener alloc] initWithProcessIdentifier:@(parentProcessId)];
self.terminationListener = [[TerminationListener alloc] initWithProcessId:parentProcessId];
self.updateFolderPath = updateFolderPath;
self.shouldRelaunch = shouldRelaunch;
self.shouldShowUI = shouldShowUI;
@@ -82,13 +135,8 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.5;
- (void)applicationDidFinishLaunching:(NSNotification __unused *)notification
{
[self.terminationListener startListeningWithCompletion:^(BOOL terminationSuccess) {
[self.terminationListener startListeningWithCompletion:^{
self.terminationListener = nil;
if (!terminationSuccess) {
SULog(SULogLevelError, @"Failed to listen for application termination");
// Continue on with the installation anyway?
}
if (self.shouldShowUI) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(SUInstallationTimeLimit * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
@@ -104,86 +152,46 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.5;
}];
}
- (void)showError:(NSError *)error
{
if (self.shouldShowUI) {
NSAlert *alert = [[NSAlert alloc] init];
alert.messageText = @"";
alert.informativeText = [NSString stringWithFormat:@"%@", [error localizedDescription]];
[alert runModal];
}
}
- (void)install
{
NSBundle *theBundle = [NSBundle bundleWithPath:self.hostPath];
SUHost *host = [[SUHost alloc] initWithBundle:theBundle];
NSString *installationPath = [[host installationPath] copy];
NSString *fileOperationToolPath = [[[[NSBundle mainBundle] executablePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@""SPARKLE_FILEOP_TOOL_NAME];
if (![[NSFileManager defaultManager] fileExistsAtPath:fileOperationToolPath]) {
SULog(SULogLevelError, @"Potential Installation Error: File operation tool path %@ is not found", fileOperationToolPath);
}
NSError *retrieveInstallerError = nil;
id<SUInstallerProtocol> installer = [SUInstaller installerForHost:host fileOperationToolPath:fileOperationToolPath updateDirectory:self.updateFolderPath error:&retrieveInstallerError];
if (installer == nil) {
SULog(SULogLevelError, @"Retrieved Installer Error: %@", retrieveInstallerError);
exit(EXIT_FAILURE);
}
if (self.shouldShowUI && [installer canInstallSilently]) {
if (self.shouldShowUI) {
self.statusController = [[SUStatusController alloc] initWithHost:host];
[self.statusController setButtonTitle:SULocalizedString(@"Cancel Update", @"") target:nil action:Nil isDefault:NO];
[self.statusController beginActionWithTitle:SULocalizedString(@"Installing update...", @"")
maxProgressValue:100 statusText: @""];
maxProgressValue: 0 statusText: @""];
[self.statusController showWindow:self];
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSError *initialInstallationError = nil;
if (![installer performInitialInstallation:&initialInstallationError]) {
SULog(SULogLevelError, @"Failed to perform initial installation with error: %@", initialInstallationError);
dispatch_async(dispatch_get_main_queue(), ^{
[self showError:initialInstallationError];
exit(EXIT_FAILURE);
});
return;
}
void(^progressBlock)(double) = ^(double progress){
dispatch_async(dispatch_get_main_queue(), ^(){
self.statusController.progressValue = progress * 100.0;
});
};
NSError *finalInstallationError = nil;
if (![installer performFinalInstallationProgressBlock:progressBlock error:&finalInstallationError]) {
NSError *underlyingError = [finalInstallationError.userInfo objectForKey:NSUnderlyingErrorKey];
dispatch_async(dispatch_get_main_queue(), ^{
if (underlyingError == nil || underlyingError.code != SUInstallationCancelledError) {
SULog(SULogLevelError, @"Failed to perform final installation Error: %@", finalInstallationError);
[self showError:finalInstallationError];
}
exit(EXIT_FAILURE);
});
return;
}
NSString *installationPath = [installer installationPath];
dispatch_async(dispatch_get_main_queue(), ^{
NSString *pathToRelaunch = nil;
// If the relaunch path is the same as the host bundle path, use the installation path from the installer which may be normalized
// Otherwise use the requested relaunch path in all other cases
if ([self.relaunchPath.pathComponents isEqualToArray:host.bundlePath.pathComponents]) {
pathToRelaunch = installationPath;
} else {
pathToRelaunch = self.relaunchPath;
}
[self cleanupAndTerminateWithPathToRelaunch:pathToRelaunch];
});
});
[SUInstaller installFromUpdateFolder:self.updateFolderPath
overHost:host
installationPath:installationPath
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];
}
exit(EXIT_FAILURE);
} else {
NSString *pathToRelaunch = nil;
// If the installation path differs from the host path, we give higher precedence for it than
// if the desired relaunch path differs from the host path
if (![installationPath.pathComponents isEqualToArray:self.hostPath.pathComponents] || [self.relaunchPath.pathComponents isEqualToArray:self.hostPath.pathComponents]) {
pathToRelaunch = installationPath;
} else {
pathToRelaunch = self.relaunchPath;
}
[self cleanupAndTerminateWithPathToRelaunch:pathToRelaunch];
}
}];
}
- (void)cleanupAndTerminateWithPathToRelaunch:(NSString *)relaunchPath
@@ -193,7 +201,7 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.5;
dispatch_block_t cleanupAndExit = ^{
NSError *theError = nil;
if (![[NSFileManager defaultManager] removeItemAtPath:self.updateFolderPath error:&theError]) {
SULog(SULogLevelError, @"Couldn't remove update folder: %@.", theError);
SULog(@"Couldn't remove update folder: %@.", theError);
}
[[NSFileManager defaultManager] removeItemAtPath:[[NSBundle mainBundle] bundlePath] error:NULL];
@@ -209,7 +217,7 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.5;
// Don't use -launchApplication: because we may not be launching an application. Eg: it could be a system prefpane
if (![[NSWorkspace sharedWorkspace] openFile:relaunchPath]) {
SULog(SULogLevelError, @"Failed to launch %@", relaunchPath);
SULog(@"Failed to launch %@", relaunchPath);
}
[self.statusController close];
-24
View File
@@ -1,24 +0,0 @@
//
// TerminationListener.h
// Sparkle
//
// Created by Mayur Pawashe on 3/7/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface TerminationListener : NSObject
- (instancetype)initWithProcessIdentifier:(NSNumber * _Nullable)processIdentifier;
@property (nonatomic, readonly) BOOL terminated;
// If the process identifier provided was nil, then the completion block will invoke immediately with a YES success
- (void)startListeningWithCompletion:(void (^)(BOOL success))completionBlock;
@end
NS_ASSUME_NONNULL_END
-131
View File
@@ -1,131 +0,0 @@
//
// TerminationListener.m
// Sparkle
//
// Created by Mayur Pawashe on 3/7/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import "TerminationListener.h"
#import "SULog.h"
#include <sys/types.h>
#include <sys/event.h>
#include <sys/time.h>
#include "AppKitPrevention.h"
@interface TerminationListener ()
@property (nonatomic, readonly, nullable) NSNumber *processIdentifier;
@property (nonatomic) BOOL watchedTermination;
@property (nonatomic, copy) void (^completionBlock)(BOOL);
@end
@implementation TerminationListener
@synthesize completionBlock = _completionBlock;
@synthesize processIdentifier = _processIdentifier;
@synthesize watchedTermination = _watchedTermination;
- (instancetype)initWithProcessIdentifier:(NSNumber * _Nullable)processIdentifier
{
self = [super init];
if (self != nil) {
_processIdentifier = processIdentifier;
}
return self;
}
- (BOOL)terminated
{
return (self.watchedTermination || self.processIdentifier == nil) ? YES : (kill(self.processIdentifier.intValue, 0) != 0);
}
- (void)invokeCompletionWithSuccess:(BOOL)success
{
if (self.completionBlock != nil) {
self.completionBlock(success);
self.completionBlock = nil;
}
}
- (void)startListeningWithCompletion:(void (^)(BOOL))completionBlock
{
self.completionBlock = completionBlock;
if (self.processIdentifier == nil) {
[self invokeCompletionWithSuccess:YES];
return;
}
// Use kqueues to determine when the process will terminate
// As described in https://developer.apple.com/library/mac/technotes/tn2050/_index.html#//apple_ref/doc/uid/DTS10003081-CH1-SUBSECTION10
// By using kqueues, we can stay away from using AppKit in case we ever decide to abandon it
pid_t processIdentifier = self.processIdentifier.intValue;
int queue = kqueue();
if (queue == -1) {
SULog(SULogLevelError, @"Failed to create kqueue() due to error %d: %@", errno, @(strerror(errno)));
[self invokeCompletionWithSuccess:NO];
return;
}
struct kevent changes;
EV_SET(&changes, processIdentifier, EVFILT_PROC, EV_ADD | EV_RECEIPT, NOTE_EXIT, 0, NULL);
if (kevent(queue, &changes, 1, &changes, 1, NULL) == -1) {
SULog(SULogLevelError, @"Failed to invoke kevent() due to error %d: %@", errno, @(strerror(errno)));
[self invokeCompletionWithSuccess:NO];
return;
}
// We will assume this terminationListener will never be deallocated
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wcast-qual"
CFFileDescriptorContext context = { 0, (void *)CFBridgingRetain(self), NULL, NULL, NULL };
#pragma clang diagnostic pop
CFFileDescriptorRef noteExitKQueueRef = CFFileDescriptorCreate(NULL, queue, true, noteExitKQueueCallback, &context);
if (noteExitKQueueRef == NULL) {
SULog(SULogLevelError, @"Failed to create file descriptor via CFFileDescriptorCreate()");
CFRelease((__bridge CFTypeRef)(self));
[self invokeCompletionWithSuccess:NO];
return;
}
CFRunLoopSourceRef runLoopSource = CFFileDescriptorCreateRunLoopSource(NULL, noteExitKQueueRef, 0);
if (runLoopSource == NULL) {
SULog(SULogLevelError, @"Failed to create runLoopSource via CFFileDescriptorCreateRunLoopSource()");
CFRelease((__bridge CFTypeRef)(self));
[self invokeCompletionWithSuccess:NO];
return;
}
CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopDefaultMode);
CFRelease(runLoopSource);
CFFileDescriptorEnableCallBacks(noteExitKQueueRef, kCFFileDescriptorReadCallBack);
// Make sure we didn't set the listener callback to a dead PID
// If we did, we could hang forever. To avoid this, we check if the process has terminated *after* we set up the callback
// If we tried to do this check before setting the callback, we could run into an issue where the process can terminate after our check
// but before setting the callback
if ([self terminated]) {
[self invokeCompletionWithSuccess:YES];
}
}
static void noteExitKQueueCallback(CFFileDescriptorRef file, CFOptionFlags __unused callBackTypes, void *info)
{
struct kevent event;
kevent(CFFileDescriptorGetNativeDescriptor(file), NULL, 0, &event, 1, NULL);
TerminationListener *self = CFBridgingRelease(info);
self.watchedTermination = YES;
[self invokeCompletionWithSuccess:YES];
}
@end
+29 -29
View File
@@ -2,21 +2,21 @@
import Foundation
func die(_ msg: String) {
func die(msg: String) {
print("ERROR: \(msg)")
exit(1)
}
extension XMLElement {
extension NSXMLElement {
convenience init(name: String, attributes: [String: String], stringValue string: String? = nil) {
self.init(name: name, stringValue: string)
setAttributesWith(attributes)
setAttributesWithDictionary(attributes)
}
}
let ud = UserDefaults.standard
let sparkleRoot = ud.object(forKey: "root") as? String
let htmlPath = ud.object(forKey: "htmlPath") as? String
let ud = NSUserDefaults.standardUserDefaults()
let sparkleRoot = ud.objectForKey("root") as? String
let htmlPath = ud.objectForKey("htmlPath") as? String
if sparkleRoot == nil || htmlPath == nil {
die("Missing arguments")
}
@@ -29,36 +29,36 @@ if enStringsDict == nil {
let enStringsDictKeys = enStringsDict!.allKeys
let dirPath = NSString(string: sparkleRoot! + "/Sparkle")
let dirContents = try! FileManager.default.contentsOfDirectory(atPath: dirPath as String)
let dirContents = try! NSFileManager.defaultManager().contentsOfDirectoryAtPath(dirPath as String)
let css =
"body { font-family: sans-serif; font-size: 10pt; }" +
"h1 { font-size: 12pt; }" +
".missing { background-color: #FFBABA; color: #D6010E; white-space: pre; }" +
".unused { background-color: #BDE5F8; color: #00529B; white-space: pre; }" +
".unlocalized { background-color: #FEEFB3; color: #9F6000; white-space: pre; }"
var html = XMLDocument(rootElement: XMLElement(name: "html"))
html.dtd = XMLDTD()
html.dtd!.name = html.rootElement()!.name
var html = NSXMLDocument(rootElement: NSXMLElement(name: "html"))
html.DTD = NSXMLDTD()
html.DTD!.name = html.rootElement()!.name
html.characterEncoding = "UTF-8"
html.documentContentKind = XMLDocument.ContentKind.xhtml
var body = XMLElement(name: "body")
var head = XMLElement(name: "head")
html.documentContentKind = NSXMLDocumentContentKind.XHTMLKind
var body = NSXMLElement(name: "body")
var head = NSXMLElement(name: "head")
html.rootElement()!.addChild(head)
html.rootElement()!.addChild(body)
head.addChild(XMLElement(name: "meta", attributes: ["charset": html.characterEncoding!]))
head.addChild(XMLElement(name: "title", stringValue: "Sparkle Localizations Report"))
head.addChild(XMLElement(name: "style", stringValue: css))
head.addChild(NSXMLElement(name: "meta", attributes: ["charset": html.characterEncoding!]))
head.addChild(NSXMLElement(name: "title", stringValue: "Sparkle Localizations Report"))
head.addChild(NSXMLElement(name: "style", stringValue: css))
let locale = Locale.current
let locale = NSLocale.currentLocale()
for dirEntry in dirContents {
if NSString(string: dirEntry).pathExtension != "lproj" || dirEntry == "en.lproj" {
continue
}
let lang = (locale as NSLocale).displayName(forKey: NSLocale.Key.languageCode, value: NSString(string: dirEntry).deletingPathExtension)
body.addChild(XMLElement(name: "h1", stringValue: "\(dirEntry) (\(lang!))"))
let lang = locale.displayNameForKey(NSLocaleLanguageCode, value: NSString(string: dirEntry).stringByDeletingPathExtension)
body.addChild(NSXMLElement(name: "h1", stringValue: "\(dirEntry) (\(lang!))"))
let stringsPath = NSString(string: dirPath.appendingPathComponent(dirEntry)).appendingPathComponent("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)")
@@ -70,10 +70,10 @@ for dirEntry in dirContents {
var unused: [String] = []
for key in enStringsDictKeys {
let str = stringsDict?.object(forKey: key) as? String
let str = stringsDict?.objectForKey(key) as? String
if str == nil {
missing.append(key as! String)
} else if let enStr = enStringsDict?.object(forKey: key) as? String {
} else if let enStr = enStringsDict?.objectForKey(key) as? String {
if enStr == str {
unlocalized.append(key as! String)
}
@@ -82,7 +82,7 @@ for dirEntry in dirContents {
let stringsDictKeys = stringsDict!.allKeys
for key in stringsDictKeys {
if enStringsDict?.object(forKey: key) == nil {
if enStringsDict?.objectForKey(key) == nil {
unused.append(key as! String)
}
}
@@ -90,12 +90,12 @@ for dirEntry in dirContents {
let sorter = { (s1: String, s2: String) -> Bool in
return s1 < s2
}
missing.sort(by: sorter)
unlocalized.sort(by: sorter)
unused.sort(by: sorter)
missing.sortInPlace(sorter)
unlocalized.sortInPlace(sorter)
unused.sortInPlace(sorter)
let addRow = { (prefix: String, cssClass: String, key: String) -> Void in
body.addChild(XMLElement(name: "span", attributes: ["class": cssClass], stringValue: [prefix, key].joined(separator: " ") + "\n"))
body.addChild(NSXMLElement(name: "span", attributes: ["class": cssClass], stringValue: [prefix, key].joinWithSeparator(" ") + "\n"))
}
for key in missing {
@@ -110,6 +110,6 @@ for dirEntry in dirContents {
}
var err: NSError?
if !((try? html.xmlData.write(to: URL(fileURLWithPath: htmlPath!), options: [.atomic])) != nil) {
die("Can't write report: \(err!)")
if !html.XMLData.writeToFile(htmlPath!, atomically: true) {
die("Can't write report: \(err)")
}
+4 -17
View File
@@ -9,32 +9,19 @@
#ifndef SUAPPCAST_H
#define SUAPPCAST_H
#if __has_feature(modules)
@import Foundation;
#else
#import <Foundation/Foundation.h>
#endif
#import "SUExport.h"
NS_ASSUME_NONNULL_BEGIN
@class SUAppcastItem;
SU_EXPORT @interface SUAppcast : NSObject<NSURLDownloadDelegate>
@property (copy, nullable) NSString *userAgentString;
@property (copy) NSString *userAgentString;
@property (copy) NSDictionary *httpHeaders;
#if __has_feature(objc_generics)
@property (copy, nullable) NSDictionary<NSString *, NSString *> *httpHeaders;
#else
@property (copy, nullable) NSDictionary *httpHeaders;
#endif
- (void)fetchAppcastFromURL:(NSURL *)url inBackground:(BOOL)bg completionBlock:(void (^)(NSError *_Nullable))err;
- (void)fetchAppcastFromURL:(NSURL *)url completionBlock:(void (^)(NSError *))err;
- (SUAppcast *)copyWithoutDeltaUpdates;
@property (readonly, copy, nullable) NSArray *items;
@property (readonly, copy) NSArray *items;
@end
NS_ASSUME_NONNULL_END
#endif
+11 -45
View File
@@ -6,14 +6,14 @@
// Copyright 2006 Andy Matuschak. All rights reserved.
//
#import "SUUpdater.h"
#import "SUAppcast.h"
#import "SUAppcastItem.h"
#import "SUVersionComparisonProtocol.h"
#import "SUAppcast.h"
#import "SUConstants.h"
#import "SULog.h"
#import "SULocalizations.h"
#import "SUErrors.h"
#include "AppKitPrevention.h"
@interface NSXMLElement (SUAppcastExtensions)
@property (readonly, copy) NSDictionary *attributesAsDictionary;
@@ -57,22 +57,18 @@
@synthesize download;
@synthesize items;
- (void)fetchAppcastFromURL:(NSURL *)url inBackground:(BOOL)background completionBlock:(void (^)(NSError *))block
- (void)fetchAppcastFromURL:(NSURL *)url completionBlock:(void (^)(NSError *))block
{
self.completionBlock = block;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30.0];
if (background) {
request.networkServiceType = NSURLNetworkServiceTypeBackground;
}
if (self.userAgentString) {
[request setValue:self.userAgentString forHTTPHeaderField:@"User-Agent"];
}
if (self.httpHeaders) {
for (NSString *key in self.httpHeaders) {
NSString *value = [self.httpHeaders objectForKey:key];
id value = [self.httpHeaders objectForKey:key];
[request setValue:value forHTTPHeaderField:key];
}
}
@@ -122,36 +118,6 @@
}
}
- (NSDictionary *)attributesOfNode:(NSXMLElement *)node
{
NSEnumerator *attributeEnum = [[node attributes] objectEnumerator];
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
for (NSXMLNode *attribute in attributeEnum) {
NSString *attrName = [self sparkleNamespacedNameOfNode:attribute];
if (!attrName) {
continue;
}
NSString *stringValue = [attribute stringValue];
if (stringValue) {
[dictionary setObject:stringValue forKey:attrName];
}
}
return dictionary;
}
-(NSString *)sparkleNamespacedNameOfNode:(NSXMLNode *)node {
// XML namespace prefix is semantically meaningless, so compare namespace URI
// NS URI isn't used to fetch anything, and must match exactly, so we look for http:// not https://
if ([[node URI] isEqualToString:@"http://www.andymatuschak.org/xml-namespaces/sparkle"]) {
NSString *localName = [node localName];
assert(localName);
return [@"sparkle:" stringByAppendingString:localName];
} else {
return [node name]; // Backwards compatibility
}
}
-(NSArray *)parseAppcastItemsFromXMLFile:(NSURL *)appcastFile error:(NSError *__autoreleasing*)errorp {
if (errorp) {
*errorp = nil;
@@ -184,7 +150,7 @@
if ([[node children] count]) {
node = [node childAtIndex:0];
while (nil != node) {
NSString *name = [self sparkleNamespacedNameOfNode:node];
NSString *name = [node name];
if (name) {
NSMutableArray *nodes = [nodesDict objectForKey:name];
if (nodes == nil) {
@@ -201,7 +167,7 @@
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];
NSDictionary *encDict = [(NSXMLElement *)node attributesAsDictionary];
[dict setObject:encDict forKey:name];
}
else if ([name isEqualToString:SURSSElementPubDate]) {
@@ -218,7 +184,7 @@
NSEnumerator *childEnum = [[node children] objectEnumerator];
for (NSXMLNode *child in childEnum) {
if ([[child name] isEqualToString:SURSSElementEnclosure]) {
[deltas addObject:[self attributesOfNode:(NSXMLElement *)child]];
[deltas addObject:[(NSXMLElement *)child attributesAsDictionary]];
}
}
[dict setObject:deltas forKey:name];
@@ -249,7 +215,7 @@
[appcastItems addObject:anItem];
}
else {
SULog(SULogLevelError, @"Sparkle Updater: Failed to parse appcast item: %@.\nAppcast dictionary was: %@", errString, dict);
SULog(@"Sparkle Updater: Failed to parse appcast item: %@.\nAppcast dictionary was: %@", errString, dict);
if (errorp) *errorp = [NSError errorWithDomain:SUSparkleErrorDomain
code:SUAppcastParseError
userInfo:@{NSLocalizedDescriptionKey: errString}];
-8
View File
@@ -9,11 +9,7 @@
#ifndef SUAPPCASTITEM_H
#define SUAPPCASTITEM_H
#if __has_feature(modules)
@import Foundation;
#else
#import <Foundation/Foundation.h>
#endif
#import "SUExport.h"
SU_EXPORT @interface SUAppcastItem : NSObject
@@ -25,13 +21,10 @@ SU_EXPORT @interface SUAppcastItem : NSObject
@property (copy, readonly) NSString *minimumSystemVersion;
@property (copy, readonly) NSString *maximumSystemVersion;
@property (strong, readonly) NSURL *fileURL;
@property (nonatomic, readonly) uint64_t contentLength;
@property (copy, readonly) NSString *versionString;
@property (copy, readonly) NSString *osString;
@property (copy, readonly) NSString *displayVersionString;
@property (copy, readonly) NSDictionary *deltaUpdates;
@property (strong, readonly) NSURL *infoURL;
@property (strong) NSString *localInstallationPath;
// Initializes with data from a dictionary provided by the RSS class.
- (instancetype)initWithDictionary:(NSDictionary *)dict;
@@ -39,7 +32,6 @@ SU_EXPORT @interface SUAppcastItem : NSObject
@property (getter=isDeltaUpdate, readonly) BOOL deltaUpdate;
@property (getter=isCriticalUpdate, readonly) BOOL criticalUpdate;
@property (getter=isMacOsUpdate, readonly) BOOL macOsUpdate;
@property (getter=isInformationOnlyUpdate, readonly) BOOL informationOnlyUpdate;
// Returns the dictionary provided in initWithDictionary; this might be useful later for extensions.
+9 -26
View File
@@ -6,12 +6,13 @@
// Copyright 2006 Andy Matuschak. All rights reserved.
//
#import "SUUpdater.h"
#import "SUAppcast.h"
#import "SUAppcastItem.h"
#import "SUVersionComparisonProtocol.h"
#import "SUAppcastItem.h"
#import "SULog.h"
#import "SUConstants.h"
#include "AppKitPrevention.h"
@interface SUAppcastItem ()
@property (copy, readwrite) NSString *title;
@@ -23,7 +24,6 @@
@property (copy, readwrite) NSString *maximumSystemVersion;
@property (strong, readwrite) NSURL *fileURL;
@property (copy, readwrite) NSString *versionString;
@property (copy, readwrite) NSString *osString;
@property (copy, readwrite) NSString *displayVersionString;
@property (copy, readwrite) NSDictionary *deltaUpdates;
@property (strong, readwrite) NSURL *infoURL;
@@ -36,7 +36,6 @@
@synthesize displayVersionString;
@synthesize DSASignature;
@synthesize fileURL;
@synthesize contentLength = _contentLength;
@synthesize infoURL;
@synthesize itemDescription;
@synthesize maximumSystemVersion;
@@ -44,7 +43,6 @@
@synthesize releaseNotesURL;
@synthesize title;
@synthesize versionString;
@synthesize osString;
@synthesize propertiesDictionary;
- (BOOL)isDeltaUpdate
@@ -58,11 +56,6 @@
return [[self.propertiesDictionary objectForKey:SUAppcastElementTags] containsObject:SUAppcastElementCriticalUpdate];
}
- (BOOL)isMacOsUpdate
{
return self.osString == nil || [self.osString isEqualToString:SUAppcastAttributeValueMacOS];
}
- (BOOL)isInformationOnlyUpdate
{
return self.infoURL && !self.fileURL;
@@ -93,7 +86,7 @@
}
if (newVersion == nil) // no sparkle:version attribute anywhere?
{
SULog(SULogLevelError, @"warning: <%@> for URL '%@' is missing %@ attribute. Version comparison may be unreliable. Please always specify %@", SURSSElementEnclosure, [enclosure objectForKey:SURSSAttributeURL], SUAppcastAttributeVersion, SUAppcastAttributeVersion);
SULog(@"warning: <%@> for URL '%@' is missing %@ attribute. Version comparison may be unreliable. Please always specify %@", SURSSElementEnclosure, [enclosure 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.
@@ -118,7 +111,7 @@
NSString *theInfoURL = [dict objectForKey:SURSSElementLink];
if (theInfoURL) {
if (![theInfoURL isKindOfClass:[NSString class]]) {
SULog(SULogLevelError, @"%@ -%@ Info URL is not of valid type.", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
SULog(@"%@ -%@ Info URL is not of valid type.", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
} else {
self.infoURL = [NSURL URLWithString:theInfoURL];
}
@@ -140,15 +133,6 @@
}
return nil;
}
if (enclosureURLString) {
NSString *enclosureLengthString = [enclosure objectForKey:SURSSAttributeLength];
long long contentLength = 0;
if (enclosureLengthString != nil) {
contentLength = [enclosureLengthString longLongValue];
}
_contentLength = (contentLength > 0) ? (uint64_t)contentLength : 0;
}
if (enclosureURLString) {
// Sparkle used to always URL-encode, so for backwards compatibility spaces in URLs must be forgiven.
@@ -157,9 +141,8 @@
}
if (enclosure) {
self.DSASignature = [enclosure objectForKey:SUAppcastAttributeDSASignature];
self.osString = [enclosure objectForKey:SUAppcastAttributeOsType];
}
self.versionString = newVersion;
self.minimumSystemVersion = [dict objectForKey:SUAppcastElementMinimumSystemVersion];
self.maximumSystemVersion = [dict objectForKey:SUAppcastElementMaximumSystemVersion];
@@ -180,7 +163,7 @@
if (releaseNotesString) {
NSURL *url = [NSURL URLWithString:releaseNotesString];
if ([url isFileURL]) {
SULog(SULogLevelError, @"Release notes with file:// URLs are not supported");
SULog(@"Release notes with file:// URLs are not supported");
} else {
self.releaseNotesURL = url;
}
-23
View File
@@ -1,23 +0,0 @@
//
// SUApplicationInfo.h
// Sparkle
//
// Created by Mayur Pawashe on 2/28/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import <Cocoa/Cocoa.h>
NS_ASSUME_NONNULL_BEGIN
@class SUHost;
@interface SUApplicationInfo : NSObject
+ (BOOL)isBackgroundApplication:(NSApplication *)application;
+ (NSImage *)bestIconForHost:(SUHost *)host;
@end
NS_ASSUME_NONNULL_END
-37
View File
@@ -1,37 +0,0 @@
//
// SUApplicationInfo.m
// Sparkle
//
// Created by Mayur Pawashe on 2/28/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import "SUApplicationInfo.h"
#import "SUBundleIcon.h"
#import "SUHost.h"
@implementation SUApplicationInfo
+ (BOOL)isBackgroundApplication:(NSApplication *)application
{
return (application.activationPolicy == NSApplicationActivationPolicyAccessory);
}
+ (NSImage *)bestIconForHost:(SUHost *)host
{
NSURL *iconURL = [SUBundleIcon iconURLForHost:host];
NSImage *icon = (iconURL == nil) ? nil : [[NSImage alloc] initWithContentsOfURL:iconURL];
// Use a default icon if none is defined.
if (!icon) {
// this asumption may not be correct (eg. even though we're not the main bundle, it could be still be a regular app)
// but still better than nothing if no icon was included
BOOL isMainBundle = [host.bundle isEqualTo:[NSBundle mainBundle]];
NSString *fileType = isMainBundle ? (__bridge NSString *)kUTTypeApplication : (__bridge NSString *)kUTTypeBundle;
icon = [[NSWorkspace sharedWorkspace] iconForFileType:fileType];
}
return icon;
}
@end
+2 -2
View File
@@ -9,7 +9,7 @@
#ifndef SUAUTOMATICUPDATEALERT_H
#define SUAUTOMATICUPDATEALERT_H
#import <Cocoa/Cocoa.h>
#import "SUWindowController.h"
typedef NS_ENUM(NSInteger, SUAutomaticInstallationChoice) {
SUInstallNowChoice,
@@ -18,7 +18,7 @@ typedef NS_ENUM(NSInteger, SUAutomaticInstallationChoice) {
};
@class SUAppcastItem, SUHost;
@interface SUAutomaticUpdateAlert : NSWindowController
@interface SUAutomaticUpdateAlert : SUWindowController
- (instancetype)initWithAppcastItem:(SUAppcastItem *)item host:(SUHost *)hostBundle completionBlock:(void (^)(SUAutomaticInstallationChoice))c;
- (IBAction)installNow:sender;
+4 -45
View File
@@ -7,32 +7,19 @@
//
#import "SUAutomaticUpdateAlert.h"
#import "SULocalizations.h"
#import "SUAppcastItem.h"
#import "SUApplicationInfo.h"
#import "SUHost.h"
#import "SUTouchBarForwardDeclarations.h"
#import "SUTouchBarButtonGroup.h"
static NSString *const SUAutomaticUpdateAlertTouchBarIndentifier = @"" SPARKLE_BUNDLE_IDENTIFIER ".SUAutomaticUpdateAlert";
@interface SUAutomaticUpdateAlert () <NSTouchBarDelegate>
@interface SUAutomaticUpdateAlert ()
@property (strong) void(^completionBlock)(SUAutomaticInstallationChoice);
@property (strong) SUAppcastItem *updateItem;
@property (strong) SUHost *host;
@property (weak) IBOutlet NSButton *skipButton;
@property (weak) IBOutlet NSButton *laterButton;
@property (weak) IBOutlet NSButton *installButton;
@end
@implementation SUAutomaticUpdateAlert
@synthesize host;
@synthesize updateItem;
@synthesize completionBlock;
@synthesize skipButton;
@synthesize laterButton;
@synthesize installButton;
- (instancetype)initWithAppcastItem:(SUAppcastItem *)item host:(SUHost *)aHost completionBlock:(void (^)(SUAutomaticInstallationChoice))block
{
@@ -42,13 +29,12 @@ static NSString *const SUAutomaticUpdateAlertTouchBarIndentifier = @"" SPARKLE_B
self.completionBlock = block;
self.host = aHost;
[self setShouldCascadeWindows:NO];
[[self window] center];
}
return self;
}
- (NSString *__nonnull)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], [self.host bundlePath]]; }
- (NSString *__nonnull)description { return [NSString stringWithFormat:@"%@ <%@, %@>", [self class], [self.host bundlePath], [self.host installationPath]]; }
- (IBAction)installNow:(id)__unused sender
{
@@ -71,17 +57,9 @@ static NSString *const SUAutomaticUpdateAlertTouchBarIndentifier = @"" SPARKLE_B
self.completionBlock = nil;
}
- (void)windowDidLoad
{
if ([self.updateItem isCriticalUpdate]) {
self.skipButton.enabled = NO;
}
}
- (NSImage *__nonnull)applicationIcon
{
return [SUApplicationInfo bestIconForHost:self.host];
return [self.host icon];
}
- (NSString *__nonnull)titleText
@@ -108,23 +86,4 @@ static NSString *const SUAutomaticUpdateAlertTouchBarIndentifier = @"" SPARKLE_B
}
}
- (NSTouchBar *)makeTouchBar
{
NSTouchBar *touchBar = [[NSClassFromString(@"NSTouchBar") alloc] init];
touchBar.defaultItemIdentifiers = @[SUAutomaticUpdateAlertTouchBarIndentifier,];
touchBar.principalItemIdentifier = SUAutomaticUpdateAlertTouchBarIndentifier;
touchBar.delegate = self;
return touchBar;
}
- (NSTouchBarItem *)touchBar:(NSTouchBar * __unused)touchBar makeItemForIdentifier:(NSTouchBarItemIdentifier)identifier
{
if ([identifier isEqualToString:SUAutomaticUpdateAlertTouchBarIndentifier]) {
NSCustomTouchBarItem* item = [(NSCustomTouchBarItem *)[NSClassFromString(@"NSCustomTouchBarItem") alloc] initWithIdentifier:identifier];
item.viewController = [[SUTouchBarButtonGroup alloc] initByReferencingButtons:@[self.installButton, self.laterButton, self.skipButton]];
return item;
}
return nil;
}
@end
+3 -1
View File
@@ -9,9 +9,11 @@
#ifndef SUAUTOMATICUPDATEDRIVER_H
#define SUAUTOMATICUPDATEDRIVER_H
#import <Cocoa/Cocoa.h>
#import "SUBasicUpdateDriver.h"
#import "SUAutomaticUpdateAlert.h"
@interface SUAutomaticUpdateDriver : SUBasicUpdateDriver
@interface SUAutomaticUpdateDriver : SUBasicUpdateDriver <SUUnarchiverDelegate>
@end
+31 -56
View File
@@ -7,15 +7,10 @@
//
#import "SUAutomaticUpdateDriver.h"
#import "SUUpdaterPrivate.h"
#import "SUUpdaterDelegate.h"
#import "SULocalizations.h"
#import "SUErrors.h"
#import "SUAutomaticUpdateAlert.h"
#import "SUHost.h"
#import "SUConstants.h"
#import "SUAppcastItem.h"
#import "SUApplicationInfo.h"
// If the user hasn't quit in a week, ask them if they want to relaunch to get the latest bits. It doesn't matter that this measure of "one day" is imprecise.
static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 24 * 7;
@@ -29,6 +24,7 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
@interface SUAutomaticUpdateDriver ()
@property (assign) BOOL postponingInstallation;
@property (assign) BOOL showErrors;
@property (assign) BOOL willUpdateOnTermination;
@property (assign) BOOL isTerminating;
@property (strong) SUAutomaticUpdateAlert *alert;
@@ -39,6 +35,7 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
@implementation SUAutomaticUpdateDriver
@synthesize postponingInstallation;
@synthesize showErrors;
@synthesize willUpdateOnTermination;
@synthesize isTerminating;
@synthesize alert;
@@ -46,22 +43,15 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
- (void)showUpdateAlert
{
id<SUUpdaterPrivate> updater = self.updater;
id<SUUpdaterDelegate> updaterDelegate = [updater delegate];
if ([updaterDelegate suppressSparkleUI])
{
[self automaticUpdateAlertFinishedWithChoice:SUInstallLaterChoice];
return;
}
id<SUUpdaterDelegate> updaterDelegate = [self.updater delegate];
if ([updaterDelegate suppressSparkleUI])
{
[self automaticUpdateAlertFinishedWithChoice:SUInstallLaterChoice];
return;
}
// NSLog(@"[Sparkle showUpdateAlert]");
self.interruptible = NO;
[self invalidateShowUpdateAlertTimer];
if (self.alert) {
[self.alert close];
}
self.alert = [[SUAutomaticUpdateAlert alloc] initWithAppcastItem:self.updateItem host:self.host completionBlock:^(SUAutomaticInstallationChoice choice) {
[self automaticUpdateAlertFinishedWithChoice:choice];
}];
@@ -69,7 +59,7 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
// If the app is a menubar app or the like, we need to focus it first and alter the
// update prompt to behave like a normal window. Otherwise if the window were hidden
// there may be no way for the application to be activated to make it visible again.
if ([SUApplicationInfo isBackgroundApplication:[NSApplication sharedApplication]]) {
if ([self.host isBackgroundApplication]) {
[[self.alert window] setHidesOnDeactivate:NO];
[NSApp activateIgnoringOtherApps:YES];
}
@@ -80,7 +70,7 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:) name:NSApplicationDidBecomeActiveNotification object:NSApp];
}
- (void)unarchiverDidFinish:(id)__unused ua
- (void)unarchiverDidFinish:(SUUnarchiver *)__unused ua
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:) name:NSApplicationWillTerminateNotification object:nil];
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(systemWillPowerOff:) name:NSWorkspaceWillPowerOffNotification object:nil];
@@ -91,8 +81,7 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
self.willUpdateOnTermination = YES;
id<SUUpdaterPrivate> updater = self.updater;
id<SUUpdaterDelegate> updaterDelegate = [updater delegate];
id<SUUpdaterDelegate> updaterDelegate = [self.updater delegate];
if ([updaterDelegate respondsToSelector:@selector(updater:willInstallUpdateOnQuit:immediateInstallationInvocation:)])
{
BOOL relaunch = YES;
@@ -102,24 +91,9 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
[invocation setArgument:&relaunch atIndex:2];
[invocation setArgument:&showUI atIndex:3];
[invocation setTarget:self];
[updaterDelegate updater:self.updater willInstallUpdateOnQuit:self.updateItem immediateInstallationInvocation:invocation];
}
//For Swift
else if ([updaterDelegate respondsToSelector:@selector(updater: willInstallUpdateOnQuit:immediateInstallationBlock:)])
{
BOOL relaunch = YES;
BOOL showUI = NO;
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[[self class] instanceMethodSignatureForSelector:@selector(installWithToolAndRelaunch:displayingUserInterface:)]];
[invocation setSelector:@selector(installWithToolAndRelaunch:displayingUserInterface:)];
[invocation setArgument:&relaunch atIndex:2];
[invocation setArgument:&showUI atIndex:3];
[invocation setTarget:self];
[updaterDelegate updater:self.updater willInstallUpdateOnQuit:self.updateItem immediateInstallationBlock:^{
[invocation invoke];
}];
}
// If this is marked as a critical update, we'll prompt the user to install it right away.
if ([self.updateItem isCriticalUpdate])
@@ -136,18 +110,6 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
}
}
-(BOOL)resumeUpdateInteractively {
if ([self isInterruptible]) {
[self showUpdateAlert];
return YES;
}
return NO;
}
-(BOOL)downloadsUpdatesInBackground {
return YES;
}
- (void)stopUpdatingOnTermination
{
if (self.willUpdateOnTermination)
@@ -160,8 +122,7 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
self.willUpdateOnTermination = NO;
id<SUUpdaterPrivate> updater = self.updater;
id<SUUpdaterDelegate> updaterDelegate = [updater delegate];
id<SUUpdaterDelegate> updaterDelegate = [self.updater delegate];
if ([updaterDelegate respondsToSelector:@selector(updater:didCancelInstallUpdateOnQuit:)])
[updaterDelegate updater:self.updater didCancelInstallUpdateOnQuit:self.updateItem];
}
@@ -181,8 +142,6 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
- (void)abortUpdate
{
[self.alert close];
self.isTerminating = NO;
[self stopUpdatingOnTermination];
[self invalidateShowUpdateAlertTimer];
@@ -197,7 +156,6 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
- (void)automaticUpdateAlertFinishedWithChoice:(SUAutomaticInstallationChoice)choice
{
self.alert = nil;
switch (choice)
{
case SUInstallNowChoice:
@@ -225,6 +183,7 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
[self stopUpdatingOnTermination];
}
self.showErrors = YES;
[super installWithToolAndRelaunch:relaunch displayingUserInterface:showUI];
}
@@ -253,4 +212,20 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2
}
}
- (void)abortUpdateWithError:(NSError *)error
{
if (self.showErrors) {
[super abortUpdateWithError:error];
} else {
// Call delegate separately here because otherwise it won't know we stopped.
// Normally this gets called by the superclass
id<SUUpdaterDelegate> updaterDelegate = [self.updater delegate];
if ([updaterDelegate respondsToSelector:@selector(updater:didAbortWithError:)]) {
[updaterDelegate updater:self.updater didAbortWithError:error];
}
[self abortUpdate];
}
}
@end
+7 -6
View File
@@ -9,10 +9,13 @@
#ifndef SUBASICUPDATEDRIVER_H
#define SUBASICUPDATEDRIVER_H
#import <Cocoa/Cocoa.h>
#import "SUUpdateDriver.h"
#import "SUUnarchiver.h"
#import "SUAppcast.h"
@class SUAppcast, SUAppcastItem, SUHost;
@interface SUBasicUpdateDriver : SUUpdateDriver <NSURLDownloadDelegate>
@class SUAppcastItem, SUHost;
@interface SUBasicUpdateDriver : SUUpdateDriver <NSURLDownloadDelegate, SUUnarchiverDelegate>
@property (strong, readonly) SUAppcastItem *updateItem;
@property (strong, readonly) NSURLDownload *download;
@@ -34,12 +37,10 @@
- (void)download:(NSURLDownload *)download didFailWithError:(NSError *)error;
- (void)extractUpdate;
- (void)unarchiverDidFinish:(SUUnarchiver *)ua;
- (void)unarchiverDidFail:(SUUnarchiver *)ua;
- (void)failedToApplyDeltaUpdate;
// Needed to preserve compatibility to subclasses, even though our unarchiver code uses blocks now
- (void)unarchiver:(id)ua extractedProgress:(double)progress;
- (void)unarchiverDidFinish:(id)ua;
- (void)installWithToolAndRelaunch:(BOOL)relaunch;
- (void)installWithToolAndRelaunch:(BOOL)relaunch displayingUserInterface:(BOOL)showUI;
- (void)installerForHost:(SUHost *)host failedWithError:(NSError *)error;
+165 -196
View File
@@ -8,22 +8,18 @@
#import "SUBasicUpdateDriver.h"
#import "SUUnarchiverProtocol.h"
#import "SUHost.h"
#import "SUOperatingSystem.h"
#import "SUDSAVerifier.h"
#import "SUInstaller.h"
#import "SUStandardVersionComparator.h"
#import "SUUnarchiver.h"
#import "SUConstants.h"
#import "SULog.h"
#import "SUBinaryDeltaCommon.h"
#import "SUUpdaterPrivate.h"
#import "SUUpdaterDelegate.h"
#import "SUCodeSigningVerifier.h"
#import "SUUpdater_Private.h"
#import "SUFileManager.h"
#import "SUUpdateValidator.h"
#import "SULocalizations.h"
#import "SUErrors.h"
#import "SUAppcast.h"
#import "SUAppcastItem.h"
@interface SUBasicUpdateDriver ()
@@ -35,8 +31,6 @@
@property (copy) NSString *tempDir;
@property (copy) NSString *relaunchPath;
@property (nonatomic) SUUpdateValidator *updateValidator;
@end
@implementation SUBasicUpdateDriver
@@ -49,23 +43,20 @@
@synthesize tempDir;
@synthesize relaunchPath;
@synthesize updateValidator = _updateValidator;
- (void)checkForUpdatesAtURL:(NSURL *)URL host:(SUHost *)aHost
{
[super checkForUpdatesAtURL:URL host:aHost];
if ([aHost isRunningOnReadOnlyVolume])
{
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SURunningFromDiskImageError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:SULocalizedString(@"%1$@ can't be updated, because it was opened from a read-only or a temporary location. Use Finder to copy %1$@ to the Applications folder, relaunch it from there, and try again.", nil), [aHost name]] }]];
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SURunningFromDiskImageError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:SULocalizedString(@"%1$@ can't be updated when it's running from a read-only volume like a disk image or an optical drive. Move %1$@ to your Applications folder, relaunch it from there, and try again.", nil), [aHost name]] }]];
return;
}
SUAppcast *appcast = [[SUAppcast alloc] init];
id<SUUpdaterPrivate> updater = self.updater;
[appcast setUserAgentString:[updater userAgentString]];
[appcast setHttpHeaders:[updater httpHeaders]];
[appcast fetchAppcastFromURL:URL inBackground:self.downloadsAppcastInBackground completionBlock:^(NSError *error) {
[appcast setUserAgentString:[self.updater userAgentString]];
[appcast setHttpHeaders:[self.updater httpHeaders]];
[appcast fetchAppcastFromURL:URL completionBlock:^(NSError *error) {
if (error) {
[self abortUpdateWithError:error];
} else {
@@ -77,16 +68,15 @@
- (id<SUVersionComparison>)versionComparator
{
id<SUVersionComparison> comparator = nil;
id<SUUpdaterPrivate> updater = self.updater;
// Give the delegate a chance to provide a custom version comparator
if ([[updater delegate] respondsToSelector:@selector(versionComparatorForUpdater:)]) {
comparator = [[updater delegate] versionComparatorForUpdater:self.updater];
if ([[self.updater delegate] respondsToSelector:@selector(versionComparatorForUpdater:)]) {
comparator = [[self.updater delegate] versionComparatorForUpdater:self.updater];
}
// If we don't get a comparator from the delegate, use the default comparator
if (!comparator) {
comparator = [[SUStandardVersionComparator alloc] init];
comparator = [SUStandardVersionComparator defaultComparator];
}
return comparator;
@@ -115,26 +105,21 @@
+ (BOOL)hostSupportsItem:(SUAppcastItem *)ui
{
BOOL osOK = [ui isMacOsUpdate];
if (([ui minimumSystemVersion] == nil || [[ui minimumSystemVersion] isEqualToString:@""]) &&
([ui maximumSystemVersion] == nil || [[ui maximumSystemVersion] isEqualToString:@""])) {
return osOK;
}
([ui maximumSystemVersion] == nil || [[ui maximumSystemVersion] isEqualToString:@""])) { return YES; }
BOOL minimumVersionOK = TRUE;
BOOL maximumVersionOK = TRUE;
id<SUVersionComparison> versionComparator = [[SUStandardVersionComparator alloc] init];
// Check minimum and maximum System Version
if ([ui minimumSystemVersion] != nil && ![[ui minimumSystemVersion] isEqualToString:@""]) {
minimumVersionOK = [versionComparator compareVersion:[ui minimumSystemVersion] toVersion:[SUOperatingSystem systemVersionString]] != NSOrderedDescending;
minimumVersionOK = [[SUStandardVersionComparator defaultComparator] compareVersion:[ui minimumSystemVersion] toVersion:[SUOperatingSystem systemVersionString]] != NSOrderedDescending;
}
if ([ui maximumSystemVersion] != nil && ![[ui maximumSystemVersion] isEqualToString:@""]) {
maximumVersionOK = [versionComparator compareVersion:[ui maximumSystemVersion] toVersion:[SUOperatingSystem systemVersionString]] != NSOrderedAscending;
maximumVersionOK = [[SUStandardVersionComparator defaultComparator] compareVersion:[ui maximumSystemVersion] toVersion:[SUOperatingSystem systemVersionString]] != NSOrderedAscending;
}
return minimumVersionOK && maximumVersionOK && osOK;
return minimumVersionOK && maximumVersionOK;
}
- (BOOL)isItemNewer:(SUAppcastItem *)ui
@@ -156,29 +141,24 @@
- (void)appcastDidFinishLoading:(SUAppcast *)ac
{
id<SUUpdaterPrivate> updater = self.updater;
if ([[updater delegate] respondsToSelector:@selector(updater:didFinishLoadingAppcast:)]) {
[[updater delegate] updater:self.updater didFinishLoadingAppcast:ac];
if ([[self.updater delegate] respondsToSelector:@selector(updater:didFinishLoadingAppcast:)]) {
[[self.updater delegate] updater:self.updater didFinishLoadingAppcast:ac];
}
NSDictionary *userInfo = @{ SUUpdaterAppcastNotificationKey: ac };
NSDictionary *userInfo = (ac != nil) ? @{ SUUpdaterAppcastNotificationKey: ac } : nil;
[[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterDidFinishLoadingAppCastNotification object:self.updater userInfo:userInfo];
SUAppcastItem *item = nil;
// Now we have to find the best valid update in the appcast.
if ([[updater delegate] respondsToSelector:@selector(bestValidUpdateInAppcast:forUpdater:)]) // Does the delegate want to handle it?
{
item = [[updater delegate] bestValidUpdateInAppcast:ac forUpdater:self.updater];
}
if (item != nil) // Does the delegate want to handle it?
if ([[self.updater delegate] respondsToSelector:@selector(bestValidUpdateInAppcast:forUpdater:)]) // Does the delegate want to handle it?
{
item = [[self.updater delegate] bestValidUpdateInAppcast:ac forUpdater:self.updater];
if ([item isDeltaUpdate]) {
self.nonDeltaUpdateItem = [[updater delegate] bestValidUpdateInAppcast:[ac copyWithoutDeltaUpdates] forUpdater:self.updater];
self.nonDeltaUpdateItem = [[self.updater delegate] bestValidUpdateInAppcast:[ac copyWithoutDeltaUpdates] forUpdater:self.updater];
}
}
else // If not, we'll take care of it ourselves.
}
else // If not, we'll take care of it ourselves.
{
// Find the best supported update
SUAppcastItem *deltaUpdateItem = nil;
@@ -202,29 +182,21 @@
- (void)didFindValidUpdate
{
assert(self.updateItem);
id<SUUpdaterPrivate> updater = self.updater;
if ([[updater delegate] respondsToSelector:@selector(updater:didFindValidUpdate:)]) {
[[updater delegate] updater:self.updater didFindValidUpdate:self.updateItem];
if ([[self.updater delegate] respondsToSelector:@selector(updater:didFindValidUpdate:)]) {
[[self.updater delegate] updater:self.updater didFindValidUpdate:self.updateItem];
}
[[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterDidFindValidUpdateNotification
object:self.updater
userInfo:@{ SUUpdaterAppcastItemNotificationKey: self.updateItem }];
// TB: Always download update.
// Stadard accounts will recieve an auth prompt before installation
[self downloadUpdate];
[self downloadUpdate];
}
- (void)didNotFindUpdate
{
id<SUUpdaterPrivate> updater = self.updater;
if ([[updater delegate] respondsToSelector:@selector(updaterDidNotFindUpdate:)]) {
[[updater delegate] updaterDidNotFindUpdate:self.updater];
if ([[self.updater delegate] respondsToSelector:@selector(updaterDidNotFindUpdate:)]) {
[[self.updater delegate] updaterDidNotFindUpdate:self.updater];
}
[[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterDidNotFindUpdateNotification object:self.updater];
@@ -244,7 +216,7 @@
cachePath = [cachePaths objectAtIndex:0];
}
if (!cachePath) {
SULog(SULogLevelError, @"Failed to find user's cache directory! Using system default");
SULog(@"Failed to find user's cache directory! Using system default");
cachePath = NSTemporaryDirectory();
}
@@ -265,17 +237,11 @@
if ([[NSFileManager defaultManager] fileExistsAtPath:appCachePath]) {
[[NSFileManager defaultManager] removeItemAtPath:appCachePath error:NULL];
}
id<SUUpdaterPrivate> updater = self.updater;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[self.updateItem fileURL]];
if (self.downloadsUpdatesInBackground) {
request.networkServiceType = NSURLNetworkServiceTypeBackground;
}
[request setValue:[updater userAgentString] forHTTPHeaderField:@"User-Agent"];
if ([[updater delegate] respondsToSelector:@selector(updater:willDownloadUpdate:withRequest:)]) {
[[updater delegate] updater:self.updater
[request setValue:[self.updater userAgentString] forHTTPHeaderField:@"User-Agent"];
if ([[self.updater delegate] respondsToSelector:@selector(updater:willDownloadUpdate:withRequest:)]) {
[[self.updater delegate] updater:self.updater
willDownloadUpdate:self.updateItem
withRequest:request];
}
@@ -308,6 +274,87 @@
[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,11 +368,9 @@
if (!failingUrl) {
failingUrl = [self.updateItem fileURL];
}
id<SUUpdaterPrivate> updater = self.updater;
if ([[updater delegate] respondsToSelector:@selector(updater:failedToDownloadUpdate:error:)]) {
[[updater delegate] updater:self.updater
if ([[self.updater delegate] respondsToSelector:@selector(updater:failedToDownloadUpdate:error:)]) {
[[self.updater delegate] updater:self.updater
failedToDownloadUpdate:self.updateItem
error:error];
}
@@ -350,40 +395,14 @@
- (void)extractUpdate
{
id<SUUpdaterPrivate> updater = self.updater;
id<SUUnarchiverProtocol> unarchiver = [SUUnarchiver unarchiverForPath:self.downloadPath updatingHostBundlePath:self.host.bundlePath decryptionPassword:updater.decryptionPassword];
BOOL success;
SUUnarchiver *unarchiver = [SUUnarchiver unarchiverForPath:self.downloadPath updatingHostBundlePath:[[self.host bundle] bundlePath] withPassword:self.updater.decryptionPassword];
if (!unarchiver) {
SULog(SULogLevelError, @"Error: No valid unarchiver for %@!", self.downloadPath);
success = NO;
} else {
// Currently unsafe archives are the only case where we can prevalidate before extraction, but that could change in the future
BOOL needsPrevalidation = [[unarchiver class] unsafeIfArchiveIsNotValidated];
self.updateValidator = [[SUUpdateValidator alloc] initWithDownloadPath:self.downloadPath dsaSignature:self.updateItem.DSASignature host:self.host performingPrevalidation:needsPrevalidation];
success = self.updateValidator.canValidate;
}
if (!success) {
NSError *reason = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{NSLocalizedDescriptionKey: @"Failed to extract update."}];
[self unarchiverDidFailWithError:reason];
} else {
self.updateItem.localInstallationPath = self.downloadPath.stringByDeletingLastPathComponent;
[unarchiver unarchiveWithCompletionBlock:^(NSError *err){
if (err) {
[self unarchiverDidFailWithError:err];
return;
}
[self unarchiverDidFinish:nil];
} progressBlock:^(double progress) {
[self unarchiver:nil extractedProgress:progress];
}];
SULog(@"Error: No valid unarchiver for %@!", self.downloadPath);
[self unarchiverDidFail:nil];
return;
}
unarchiver.delegate = self;
[unarchiver start];
}
- (void)failedToApplyDeltaUpdate
@@ -395,30 +414,21 @@
[self downloadUpdate];
}
// By default does nothing, can be overridden
- (void)unarchiver:(id)__unused ua extractedProgress:(double)__unused progress
{
}
// Note this method can be overridden (and is)
- (void)unarchiverDidFinish:(id)__unused ua
- (void)unarchiverDidFinish:(SUUnarchiver *)__unused ua
{
assert(self.updateItem);
[self installWithToolAndRelaunch:YES];
}
- (void)unarchiverDidFailWithError:(NSError *)err
- (void)unarchiverDidFail:(SUUnarchiver *)__unused ua
{
// No longer needed
self.updateValidator = nil;
if ([self.updateItem isDeltaUpdate]) {
[self failedToApplyDeltaUpdate];
return;
}
[self abortUpdateWithError:err];
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while extracting the archive. Please try again later.", nil) }]];
}
- (void)installWithToolAndRelaunch:(BOOL)relaunch
@@ -452,37 +462,29 @@
return YES;
}
- (BOOL)mayUpdateAndRestart
{
id<SUUpdaterPrivate> updater = self.updater;
return (!updater.delegate || ![updater.delegate respondsToSelector:@selector(updaterShouldRelaunchApplication:)] || [updater.delegate updaterShouldRelaunchApplication:self.updater]);
}
- (void)installWithToolAndRelaunch:(BOOL)relaunch displayingUserInterface:(BOOL)showUI
{
assert(self.updateItem);
assert(self.updateValidator);
BOOL validationCheckSuccess = [self.updateValidator validateWithUpdateDirectory:self.tempDir];
if (!validationCheckSuccess) {
if (![self validateUpdateDownloadedToPath:self.downloadPath extractedToPath:self.tempDir DSASignature:self.updateItem.DSASignature publicDSAKey:self.host.publicDSAKey])
{
NSDictionary *userInfo = @{
NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while extracting the archive. Please try again later.", nil),
NSLocalizedFailureReasonErrorKey: SULocalizedString(@"The update is improperly signed.", nil),
};
NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while extracting the archive. Please try again later.", nil),
NSLocalizedFailureReasonErrorKey: SULocalizedString(@"The update is improperly signed.", nil),
};
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUSignatureError userInfo:userInfo]];
return;
}
if (![self mayUpdateAndRestart])
if (![self.updater mayUpdateAndRestart])
{
[self abortUpdate];
return;
}
// Give the host app an opportunity to postpone the install and relaunch.
id<SUUpdaterPrivate> updater = self.updater;
static BOOL postponedOnce = NO;
id<SUUpdaterDelegate> updaterDelegate = [updater delegate];
id<SUUpdaterDelegate> updaterDelegate = [self.updater delegate];
if (!postponedOnce && [updaterDelegate respondsToSelector:@selector(updater:shouldPostponeRelaunchForUpdate:untilInvoking:)])
{
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[[self class] instanceMethodSignatureForSelector:@selector(installWithToolAndRelaunch:)]];
@@ -495,74 +497,44 @@
}
}
if ([updaterDelegate respondsToSelector:@selector(updater:willInstallUpdate:)]) {
BOOL continueInstall = [updaterDelegate updater:self.updater willInstallUpdate:self.updateItem];
if (!continueInstall) {
return;
}
[updaterDelegate updater:self.updater willInstallUpdate:self.updateItem];
}
NSBundle *sparkleBundle = updater.sparkleBundle;
if (!sparkleBundle) {
SULog(SULogLevelError, @"Sparkle bundle is gone?");
return;
}
NSBundle *sparkleBundle = self.updater.sparkleBundle;
// 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 relaunchToolSourceName = @"" SPARKLE_RELAUNCH_TOOL_NAME;
NSString *const relaunchToolSourcePath = [sparkleBundle pathForResource:relaunchToolSourceName ofType:@"app"];
NSString *relaunchCopyTargetPath = nil;
NSError *error = nil;
BOOL copiedRelaunchPath = NO;
if (!relaunchToolSourceName || ![relaunchToolSourceName length]) {
SULog(SULogLevelError, @"SPARKLE_RELAUNCH_TOOL_NAME not configued");
}
if (!relaunchToolSourcePath) {
SULog(SULogLevelError, @"Sparkle.framework is damaged. %@ is missing", relaunchToolSourceName);
}
if (relaunchToolSourcePath) {
NSString *hostBundleBaseName = [[self.host.bundlePath lastPathComponent] stringByDeletingPathExtension];
if (!hostBundleBaseName) {
SULog(SULogLevelError, @"Unable to get bundlePath");
hostBundleBaseName = @"Sparkle";
}
NSString *relaunchCopyBaseName = [NSString stringWithFormat:@"%@ (Autoupdate).app", hostBundleBaseName];
relaunchCopyTargetPath = [[self appCachePath] stringByAppendingPathComponent:relaunchCopyBaseName];
SUFileManager *fileManager = [SUFileManager defaultManager];
NSURL *relaunchToolSourceURL = [NSURL fileURLWithPath:relaunchToolSourcePath];
NSURL *relaunchCopyTargetURL = [NSURL fileURLWithPath:relaunchCopyTargetPath];
NSString *const relaunchToolName = @"" SPARKLE_RELAUNCH_TOOL_NAME;
NSString *const relaunchPathToCopy = [sparkleBundle pathForResource:relaunchToolName ofType:@"app"];
if (relaunchPathToCopy != nil) {
NSString *targetPath = [[self appCachePath] stringByAppendingPathComponent:[relaunchPathToCopy lastPathComponent]];
SUFileManager *fileManager = [SUFileManager fileManagerAllowingAuthorization:NO];
NSError *error = nil;
NSURL *relaunchURLToCopy = [NSURL fileURLWithPath:relaunchPathToCopy];
NSURL *targetURL = [NSURL fileURLWithPath:targetPath];
// We only need to run our copy of the app by spawning a task
// Since we are copying the app to a directory that is write-accessible, we don't need to muck with owner/group IDs
if ([self preparePathForRelaunchTool:relaunchCopyTargetPath error:&error] && [fileManager copyItemAtURL:relaunchToolSourceURL toURL:relaunchCopyTargetURL error:&error]) {
copiedRelaunchPath = YES;
if ([self preparePathForRelaunchTool:targetPath error:&error] && [fileManager copyItemAtURL:relaunchURLToCopy toURL:targetURL error:&error]) {
// We probably don't need to release the quarantine, but we'll do it just in case it's necessary.
// Perhaps in a sandboxed environment this matters more. Note that this may not be a fatal error.
NSError *quarantineError = nil;
if (![fileManager releaseItemFromQuarantineAtRootURL:relaunchCopyTargetURL error:&quarantineError]) {
SULog(SULogLevelError, @"Failed to release quarantine on %@ with error %@", relaunchCopyTargetPath, quarantineError);
if (![fileManager releaseItemFromQuarantineAtRootURL:targetURL error:&quarantineError]) {
SULog(@"Failed to release quarantine on %@ with error %@", targetPath, 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];
@@ -572,19 +544,17 @@
// Note that we explicitly use the host app's name here, since updating plugin for Mail relaunches Mail, not just the plugin.
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SURelaunchError userInfo:@{
NSLocalizedDescriptionKey: [NSString stringWithFormat:SULocalizedString(@"An error occurred while relaunching %1$@, but the new version will be available next time you run %1$@.", nil), [self.host name]],
NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:@"Couldn't find the relauncher (expected to find it at %@ and %@)", relaunchToolSourcePath, self.relaunchPath],
NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:@"Couldn't find the relauncher (expected to find it at %@)", self.relaunchPath]
}]];
// We intentionally don't abandon the update here so that the host won't initiate another.
return;
}
NSString *pathToRelaunch = [self.host bundlePath];
if ([updaterDelegate respondsToSelector:@selector(pathToRelaunchForUpdater:)]) {
NSString *delegateRelaunchPath = [updaterDelegate pathToRelaunchForUpdater:self.updater];
if (delegateRelaunchPath != nil) {
pathToRelaunch = delegateRelaunchPath;
}
pathToRelaunch = [updaterDelegate pathToRelaunchForUpdater:self.updater];
}
[NSTask launchedTaskWithLaunchPath:relaunchToolPath arguments:@[[self.host bundlePath],
pathToRelaunch,
[NSString stringWithFormat:@"%d", [[NSProcessInfo processInfo] processIdentifier]],
@@ -640,7 +610,7 @@
NSError *errorToDisplay = error;
int finiteRecursion=5;
do {
SULog(SULogLevelError, @"Error: %@ %@ (URL %@)", errorToDisplay.localizedDescription, errorToDisplay.localizedFailureReason, [errorToDisplay.userInfo objectForKey:NSURLErrorFailingURLErrorKey]);
SULog(@"Error: %@ %@ (URL %@)", errorToDisplay.localizedDescription, errorToDisplay.localizedFailureReason, [errorToDisplay.userInfo objectForKey:NSURLErrorFailingURLErrorKey]);
errorToDisplay = [errorToDisplay.userInfo objectForKey:NSUnderlyingErrorKey];
} while(--finiteRecursion && errorToDisplay);
}
@@ -649,8 +619,7 @@
}
// Notify host app that update has aborted
id<SUUpdaterPrivate> updater = self.updater;
id<SUUpdaterDelegate> updaterDelegate = [updater delegate];
id<SUUpdaterDelegate> updaterDelegate = [self.updater delegate];
if ([updaterDelegate respondsToSelector:@selector(updater:didAbortWithError:)]) {
[updaterDelegate updater:self.updater didAbortWithError:error];
}
+1 -3
View File
@@ -9,9 +9,7 @@
#ifndef SUBINARYDELTAAPPLY_H
#define SUBINARYDELTAAPPLY_H
#import <Foundation/Foundation.h>
@class NSString;
BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFile, BOOL verbose, void (^progressCallback)(double), NSError * __autoreleasing *error);
BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFile, BOOL verbose, NSError * __autoreleasing *error);
#endif
+31 -46
View File
@@ -15,19 +15,17 @@
#include <stdlib.h>
#include <xar/xar.h>
#include "AppKitPrevention.h"
static BOOL applyBinaryDeltaToFile(xar_t x, xar_file_t file, NSString *sourceFilePath, NSString *destinationFilePath)
{
NSString *patchFile = temporaryFilename(@"apply-binary-delta");
xar_extract_tofile(x, file, [patchFile fileSystemRepresentation]);
const char *argv[] = { "/usr/bin/bspatch", [sourceFilePath fileSystemRepresentation], [destinationFilePath fileSystemRepresentation], [patchFile fileSystemRepresentation] };
const char *argv[] = {"/usr/bin/bspatch", [sourceFilePath fileSystemRepresentation], [destinationFilePath fileSystemRepresentation], [patchFile fileSystemRepresentation]};
BOOL success = (bspatch(4, argv) == 0);
unlink([patchFile fileSystemRepresentation]);
return success;
}
BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFile, BOOL verbose, void (^progressCallback)(double progress), NSError *__autoreleasing *error)
BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFile, BOOL verbose, NSError * __autoreleasing *error)
{
xar_t x = xar_open([patchFile fileSystemRepresentation], READ);
if (!x) {
@@ -36,71 +34,69 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi
}
return NO;
}
SUBinaryDeltaMajorVersion majorDiffVersion = FIRST_DELTA_DIFF_MAJOR_VERSION;
int minorDiffVersion = 0;
SUBinaryDeltaMinorVersion minorDiffVersion = FIRST_DELTA_DIFF_MINOR_VERSION;
NSString *expectedBeforeHashv1 = nil;
NSString *expectedAfterHashv1 = nil;
NSString *expectedNewBeforeHash = nil;
NSString *expectedNewAfterHash = nil;
progressCallback(0/6.0);
xar_subdoc_t subdoc;
for (subdoc = xar_subdoc_first(x); subdoc; subdoc = xar_subdoc_next(subdoc)) {
if (!strcmp(xar_subdoc_name(subdoc), BINARY_DELTA_ATTRIBUTES_KEY)) {
const char *value = 0;
// available in version 2.0 or later
xar_subdoc_prop_get(subdoc, MAJOR_DIFF_VERSION_KEY, &value);
if (value)
majorDiffVersion = (SUBinaryDeltaMajorVersion)[@(value) intValue];
// available in version 2.0 or later
xar_subdoc_prop_get(subdoc, MINOR_DIFF_VERSION_KEY, &value);
if (value)
minorDiffVersion = [@(value) intValue];
minorDiffVersion = (SUBinaryDeltaMinorVersion)[@(value) intValue];
// available in version 2.0 or later
xar_subdoc_prop_get(subdoc, BEFORE_TREE_SHA1_KEY, &value);
if (value)
expectedNewBeforeHash = @(value);
// available in version 2.0 or later
xar_subdoc_prop_get(subdoc, AFTER_TREE_SHA1_KEY, &value);
if (value)
expectedNewAfterHash = @(value);
// only available in version 1.0
xar_subdoc_prop_get(subdoc, BEFORE_TREE_SHA1_OLD_KEY, &value);
if (value)
expectedBeforeHashv1 = @(value);
// only available in version 1.0
xar_subdoc_prop_get(subdoc, AFTER_TREE_SHA1_OLD_KEY, &value);
if (value)
expectedAfterHashv1 = @(value);
}
}
if (majorDiffVersion < FIRST_DELTA_DIFF_MAJOR_VERSION) {
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadCorruptFileError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Unable to identify diff-version %u in delta. Giving up.", majorDiffVersion] }];
}
return NO;
}
if (majorDiffVersion > LATEST_DELTA_DIFF_MAJOR_VERSION) {
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"A later version is needed to apply this patch (on major version %u, but patch requests version %u).", LATEST_DELTA_DIFF_MAJOR_VERSION, majorDiffVersion] }];
}
return NO;
}
BOOL usesNewTreeHash = MAJOR_VERSION_IS_AT_LEAST(majorDiffVersion, SUBeigeMajorVersion);
NSString *expectedBeforeHash = usesNewTreeHash ? expectedNewBeforeHash : expectedBeforeHashv1;
NSString *expectedAfterHash = usesNewTreeHash ? expectedNewAfterHash : expectedAfterHashv1;
@@ -115,9 +111,7 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi
fprintf(stderr, "Applying version %u.%u patch...\n", majorDiffVersion, minorDiffVersion);
fprintf(stderr, "Verifying source...");
}
progressCallback(1/6.0);
NSString *beforeHash = hashOfTreeWithVersion(source, majorDiffVersion);
if (!beforeHash) {
if (verbose) {
@@ -142,9 +136,7 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi
if (verbose) {
fprintf(stderr, "\nCopying files...");
}
progressCallback(2/6.0);
if (!removeTree(destination)) {
if (verbose) {
fprintf(stderr, "\n");
@@ -154,9 +146,6 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi
}
return NO;
}
progressCallback(3/6.0);
if (!copyTree(source, destination)) {
if (verbose) {
fprintf(stderr, "\n");
@@ -166,9 +155,7 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi
}
return NO;
}
progressCallback(4/6.0);
BOOL hasExtractKeyAvailable = MAJOR_VERSION_IS_AT_LEAST(majorDiffVersion, SUBeigeMajorVersion);
if (verbose) {
@@ -185,9 +172,10 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi
// Don't use -[NSFileManager fileExistsAtPath:] because it will follow symbolic links
BOOL fileExisted = verbose && [fileManager attributesOfItemAtPath:destinationFilePath error:nil];
BOOL removedFile = NO;
const char *value;
if (!xar_prop_get(file, DELETE_KEY, &value) || (!hasExtractKeyAvailable && !xar_prop_get(file, DELETE_THEN_EXTRACT_OLD_KEY, &value))) {
if (!xar_prop_get(file, DELETE_KEY, &value) ||
(!hasExtractKeyAvailable && !xar_prop_get(file, DELETE_THEN_EXTRACT_OLD_KEY, &value))) {
if (!removeTree(destinationFilePath)) {
if (verbose) {
fprintf(stderr, "\n");
@@ -203,7 +191,7 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi
}
continue;
}
removedFile = YES;
}
@@ -217,12 +205,13 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi
}
return NO;
}
if (verbose) {
fprintf(stderr, "\n🔨 %s %s", VERBOSE_PATCHED, [path fileSystemRepresentation]);
}
} else if ((hasExtractKeyAvailable && !xar_prop_get(file, EXTRACT_KEY, &value)) || (!hasExtractKeyAvailable && xar_prop_get(file, MODIFY_PERMISSIONS_KEY, &value))) { // extract and permission modifications don't coexist
} else if ((hasExtractKeyAvailable && !xar_prop_get(file, EXTRACT_KEY, &value)) ||
(!hasExtractKeyAvailable && xar_prop_get(file, MODIFY_PERMISSIONS_KEY, &value))) { // extract and permission modifications don't coexist
if (xar_extract_tofile(x, file, [destinationFilePath fileSystemRepresentation]) != 0) {
if (verbose) {
fprintf(stderr, "\n");
@@ -232,7 +221,7 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi
}
return NO;
}
if (verbose) {
if (fileExisted) {
fprintf(stderr, "\n✏️ %s %s", VERBOSE_UPDATED, [path fileSystemRepresentation]);
@@ -243,7 +232,7 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi
} else if (verbose && removedFile) {
fprintf(stderr, "\n❌ %s %s", VERBOSE_DELETED, [path fileSystemRepresentation]);
}
if (!xar_prop_get(file, MODIFY_PERMISSIONS_KEY, &value)) {
mode_t mode = (mode_t)[[NSString stringWithUTF8String:value] intValue];
if (!modifyPermissions(destinationFilePath, mode)) {
@@ -255,7 +244,7 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi
}
return NO;
}
if (verbose) {
fprintf(stderr, "\n👮 %s %s (0%o)", VERBOSE_MODIFIED, [path fileSystemRepresentation], mode);
}
@@ -263,8 +252,6 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi
}
xar_close(x);
progressCallback(5/6.0);
if (verbose) {
fprintf(stderr, "\nVerifying destination...");
}
@@ -290,8 +277,6 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi
return NO;
}
progressCallback(6/6.0);
if (verbose) {
fprintf(stderr, "\nDone!\n");
}
+10 -1
View File
@@ -57,7 +57,16 @@ typedef NS_ENUM(uint16_t, SUBinaryDeltaMajorVersion)
SUBeigeMajorVersion = 2
};
// Only keep track of the latest minor version for each major version
typedef NS_ENUM(uint16_t, SUBinaryDeltaMinorVersion)
{
SUAzureMinorVersion = 1,
SUBeigeMinorVersion = 1,
};
#define FIRST_DELTA_DIFF_MAJOR_VERSION SUAzureMajorVersion
#define FIRST_DELTA_DIFF_MINOR_VERSION ((SUBinaryDeltaMinorVersion)0)
#define LATEST_DELTA_DIFF_MAJOR_VERSION SUBeigeMajorVersion
extern int compareFiles(const FTSENT **a, const FTSENT **b);
@@ -71,5 +80,5 @@ extern NSString *pathRelativeToDirectory(NSString *directory, NSString *path);
NSString *temporaryFilename(NSString *base);
NSString *temporaryDirectory(NSString *base);
NSString *stringWithFileSystemRepresentation(const char*);
int latestMinorVersionForMajorVersion(SUBinaryDeltaMajorVersion majorVersion);
SUBinaryDeltaMinorVersion latestMinorVersionForMajorVersion(SUBinaryDeltaMajorVersion majorVersion);
#endif
+19 -25
View File
@@ -18,8 +18,6 @@
#include <sys/stat.h>
#include <xar/xar.h>
#include "AppKitPrevention.h"
int compareFiles(const FTSENT **a, const FTSENT **b)
{
return strcoll((*a)->fts_name, (*b)->fts_name);
@@ -34,20 +32,19 @@ NSString *pathRelativeToDirectory(NSString *directory, NSString *path)
return path;
}
NSString *stringWithFileSystemRepresentation(const char *input)
{
NSString *stringWithFileSystemRepresentation(const char *input) {
return [[NSFileManager defaultManager] stringWithFileSystemRepresentation:input length:strlen(input)];
}
int latestMinorVersionForMajorVersion(SUBinaryDeltaMajorVersion majorVersion)
SUBinaryDeltaMinorVersion latestMinorVersionForMajorVersion(SUBinaryDeltaMajorVersion majorVersion)
{
switch (majorVersion) {
case SUAzureMajorVersion:
return 1;
return SUAzureMinorVersion;
case SUBeigeMajorVersion:
return 2;
return SUBeigeMinorVersion;
}
return 0;
return (SUBinaryDeltaMinorVersion)0;
}
NSString *temporaryFilename(NSString *base)
@@ -76,18 +73,18 @@ NSString *temporaryDirectory(NSString *base)
NSString *template = [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.XXXXXXXXXX", base]];
NSMutableData *data = [NSMutableData data];
[data appendBytes:template.fileSystemRepresentation length:strlen(template.fileSystemRepresentation) + 1];
char *buffer = data.mutableBytes;
char *templateResult = mkdtemp(buffer);
if (templateResult == NULL) {
perror("mkdtemp");
return nil;
}
return stringWithFileSystemRepresentation(templateResult);
}
static void _hashOfBuffer(unsigned char *hash, const char *buffer, ssize_t bufferLength)
static void _hashOfBuffer(unsigned char *hash, const char* buffer, ssize_t bufferLength)
{
assert(bufferLength >= 0 && bufferLength <= UINT32_MAX);
CC_SHA1_CTX hashContext;
@@ -96,7 +93,7 @@ static void _hashOfBuffer(unsigned char *hash, const char *buffer, ssize_t buffe
CC_SHA1_Final(hash, &hashContext);
}
static BOOL _hashOfFileContents(unsigned char *hash, FTSENT *ent)
static BOOL _hashOfFileContents(unsigned char* hash, FTSENT *ent)
{
if (ent->fts_info == FTS_SL) {
char linkDestination[MAXPATHLEN + 1];
@@ -119,12 +116,12 @@ static BOOL _hashOfFileContents(unsigned char *hash, FTSENT *ent)
_hashOfBuffer(hash, NULL, 0);
} else {
void *buffer = mmap(0, (size_t)fileSize, PROT_READ, MAP_FILE | MAP_PRIVATE, fileDescriptor, 0);
if (buffer == (void *)-1) {
if (buffer == (void*)-1) {
close(fileDescriptor);
perror("mmap");
return NO;
}
_hashOfBuffer(hash, buffer, fileSize);
munmap(buffer, (size_t)fileSize);
}
@@ -148,12 +145,12 @@ NSData *hashOfFileContents(FTSENT *ent)
NSString *hashOfTreeWithVersion(NSString *path, uint16_t majorVersion)
{
char pathBuffer[PATH_MAX] = { 0 };
char pathBuffer[PATH_MAX] = {0};
if (![path getFileSystemRepresentation:pathBuffer maxLength:sizeof(pathBuffer)]) {
return nil;
}
char *const sourcePaths[] = { pathBuffer, 0 };
char * const sourcePaths[] = {pathBuffer, 0};
FTS *fts = fts_open(sourcePaths, FTS_PHYSICAL | FTS_NOCHDIR, compareFiles);
if (!fts) {
perror("fts_open");
@@ -163,19 +160,16 @@ NSString *hashOfTreeWithVersion(NSString *path, uint16_t majorVersion)
CC_SHA1_CTX hashContext;
CC_SHA1_Init(&hashContext);
// Ensure the path uses filesystem-specific Unicode normalization #1017
NSString *normalizedPath = stringWithFileSystemRepresentation(pathBuffer);
FTSENT *ent = 0;
while ((ent = fts_read(fts))) {
if (ent->fts_info != FTS_F && ent->fts_info != FTS_SL && ent->fts_info != FTS_D)
continue;
if (ent->fts_info == FTS_D && !MAJOR_VERSION_IS_AT_LEAST(majorVersion, SUBeigeMajorVersion)) {
continue;
}
NSString *relativePath = pathRelativeToDirectory(normalizedPath, stringWithFileSystemRepresentation(ent->fts_path));
NSString *relativePath = pathRelativeToDirectory(path, stringWithFileSystemRepresentation(ent->fts_path));
if (relativePath.length == 0)
continue;
@@ -187,12 +181,12 @@ NSString *hashOfTreeWithVersion(NSString *path, uint16_t majorVersion)
const char *relativePathBytes = [relativePath fileSystemRepresentation];
CC_SHA1_Update(&hashContext, relativePathBytes, (CC_LONG)strlen(relativePathBytes));
if (MAJOR_VERSION_IS_AT_LEAST(majorVersion, SUBeigeMajorVersion)) {
uint16_t mode = ent->fts_statp->st_mode;
uint16_t type = ent->fts_info;
uint16_t permissions = mode & PERMISSION_FLAGS;
CC_SHA1_Update(&hashContext, &type, sizeof(type));
CC_SHA1_Update(&hashContext, &permissions, sizeof(permissions));
}
@@ -227,7 +221,7 @@ BOOL removeTree(NSString *path)
BOOL copyTree(NSString *source, NSString *dest)
{
return [[SUFileManager defaultManager] copyItemAtURL:[NSURL fileURLWithPath:source] toURL:[NSURL fileURLWithPath:dest] error:NULL];
return [[SUFileManager fileManagerAllowingAuthorization:NO] copyItemAtURL:[NSURL fileURLWithPath:source] toURL:[NSURL fileURLWithPath:dest] error:NULL];
}
BOOL modifyPermissions(NSString *path, mode_t desiredPermissions)
+72 -71
View File
@@ -21,8 +21,6 @@
#include <sys/xattr.h>
#include <xar/xar.h>
#include "AppKitPrevention.h"
extern int bsdiff(int argc, const char **argv);
@interface CreateBinaryDeltaOperation : NSOperation
@@ -58,7 +56,7 @@ extern int bsdiff(int argc, const char **argv);
- (void)main
{
NSString *temporaryFile = temporaryFilename(@"BinaryDelta");
const char *argv[] = { "/usr/bin/bsdiff", [self._fromPath fileSystemRepresentation], [self._toPath fileSystemRepresentation], [temporaryFile fileSystemRepresentation] };
const char *argv[] = {"/usr/bin/bsdiff", [self._fromPath fileSystemRepresentation], [self._toPath fileSystemRepresentation], [temporaryFile fileSystemRepresentation]};
int result = bsdiff(4, argv);
if (!result)
self.resultPath = temporaryFile;
@@ -77,26 +75,23 @@ static NSDictionary *infoForFile(FTSENT *ent)
if (!hash) {
return nil;
}
off_t size = (ent->fts_info != FTS_D) ? ent->fts_statp->st_size : 0;
assert(ent->fts_statp != NULL);
mode_t permissions = ent->fts_statp->st_mode & PERMISSION_FLAGS;
return @{ INFO_HASH_KEY: hash,
INFO_TYPE_KEY: @(ent->fts_info),
INFO_PERMISSIONS_KEY: @(permissions),
INFO_SIZE_KEY: @(size) };
return @{INFO_HASH_KEY: hash, INFO_TYPE_KEY: @(ent->fts_info), INFO_PERMISSIONS_KEY : @(permissions), INFO_SIZE_KEY: @(size)};
}
static bool aclExists(const FTSENT *ent)
{
// macOS does not currently support ACLs for symlinks
// OS X does not currently support ACLs for symlinks
if (ent->fts_info == FTS_SL) {
return NO;
}
acl_t acl = acl_get_link_np(ent->fts_path, ACL_TYPE_EXTENDED);
if (acl != NULL) {
acl_entry_t entry;
@@ -114,26 +109,28 @@ static bool codeSignatureExtendedAttributeExists(const FTSENT *ent)
if (listSize == -1) {
return false;
}
char *buffer = malloc((size_t)listSize);
assert(buffer != NULL);
ssize_t sizeBack = listxattr(ent->fts_path, buffer, (size_t)listSize, options);
assert(sizeBack == listSize);
size_t startCharacterIndex = 0;
for (size_t characterIndex = 0; characterIndex < (size_t)listSize; characterIndex++) {
if (buffer[characterIndex] == '\0') {
char *attribute = &buffer[startCharacterIndex];
size_t length = characterIndex - startCharacterIndex;
if (strncmp(APPLE_CODE_SIGN_XATTR_CODE_DIRECTORY_KEY, attribute, length) == 0 || strncmp(APPLE_CODE_SIGN_XATTR_CODE_REQUIREMENTS_KEY, attribute, length) == 0 || strncmp(APPLE_CODE_SIGN_XATTR_CODE_SIGNATURE_KEY, attribute, length) == 0) {
if (strncmp(APPLE_CODE_SIGN_XATTR_CODE_DIRECTORY_KEY, attribute, length) == 0 ||
strncmp(APPLE_CODE_SIGN_XATTR_CODE_REQUIREMENTS_KEY, attribute, length) == 0 ||
strncmp(APPLE_CODE_SIGN_XATTR_CODE_SIGNATURE_KEY, attribute, length) == 0) {
free(buffer);
return true;
}
startCharacterIndex = characterIndex + 1;
}
}
free(buffer);
return false;
}
@@ -141,7 +138,7 @@ static bool codeSignatureExtendedAttributeExists(const FTSENT *ent)
static NSString *absolutePath(NSString *path)
{
NSURL *url = [[NSURL alloc] initFileURLWithPath:path];
return [[url absoluteURL] path];
return [[url absoluteURL] path];
}
static NSString *temporaryPatchFile(NSString *patchFile)
@@ -154,7 +151,7 @@ static NSString *temporaryPatchFile(NSString *patchFile)
#define MIN_FILE_SIZE_FOR_CREATING_DELTA 4096
static BOOL shouldSkipDeltaCompression(NSDictionary *originalInfo, NSDictionary *newInfo)
static BOOL shouldSkipDeltaCompression(NSDictionary* originalInfo, NSDictionary *newInfo)
{
unsigned long long fileSize = [newInfo[INFO_SIZE_KEY] unsignedLongLongValue];
if (fileSize < MIN_FILE_SIZE_FOR_CREATING_DELTA) {
@@ -168,7 +165,7 @@ static BOOL shouldSkipDeltaCompression(NSDictionary *originalInfo, NSDictionary
if ([originalInfo[INFO_TYPE_KEY] unsignedShortValue] != [newInfo[INFO_TYPE_KEY] unsignedShortValue]) {
return YES;
}
if ([originalInfo[INFO_HASH_KEY] isEqual:newInfo[INFO_HASH_KEY]]) {
// this is possible if just the permissions have changed
return YES;
@@ -177,7 +174,7 @@ static BOOL shouldSkipDeltaCompression(NSDictionary *originalInfo, NSDictionary
return NO;
}
static BOOL shouldDeleteThenExtract(NSDictionary *originalInfo, NSDictionary *newInfo)
static BOOL shouldDeleteThenExtract(NSDictionary* originalInfo, NSDictionary *newInfo)
{
if (!originalInfo) {
return NO;
@@ -195,15 +192,15 @@ static BOOL shouldSkipExtracting(NSDictionary *originalInfo, NSDictionary *newIn
if (!originalInfo) {
return NO;
}
if ([originalInfo[INFO_TYPE_KEY] unsignedShortValue] != [newInfo[INFO_TYPE_KEY] unsignedShortValue]) {
return NO;
}
if (![originalInfo[INFO_HASH_KEY] isEqual:newInfo[INFO_HASH_KEY]]) {
return NO;
}
return YES;
}
@@ -212,30 +209,30 @@ static BOOL shouldChangePermissions(NSDictionary *originalInfo, NSDictionary *ne
if (!originalInfo) {
return NO;
}
if ([originalInfo[INFO_TYPE_KEY] unsignedShortValue] != [newInfo[INFO_TYPE_KEY] unsignedShortValue]) {
return NO;
}
if ([originalInfo[INFO_PERMISSIONS_KEY] unsignedShortValue] == [newInfo[INFO_PERMISSIONS_KEY] unsignedShortValue]) {
return NO;
}
return YES;
}
BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchFile, SUBinaryDeltaMajorVersion majorVersion, BOOL verbose, NSError *__autoreleasing *error)
BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchFile, SUBinaryDeltaMajorVersion majorVersion, BOOL verbose, NSError * __autoreleasing *error)
{
assert(source);
assert(destination);
assert(patchFile);
assert(majorVersion >= FIRST_DELTA_DIFF_MAJOR_VERSION && majorVersion <= LATEST_DELTA_DIFF_MAJOR_VERSION);
int minorVersion = latestMinorVersionForMajorVersion(majorVersion);
SUBinaryDeltaMinorVersion minorVersion = latestMinorVersionForMajorVersion(majorVersion);
NSMutableDictionary *originalTreeState = [NSMutableDictionary dictionary];
char pathBuffer[PATH_MAX] = { 0 };
char pathBuffer[PATH_MAX] = {0};
if (![source getFileSystemRepresentation:pathBuffer maxLength:sizeof(pathBuffer)]) {
if (error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to retrieve file system path representation from source %@", source] }];
@@ -243,7 +240,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
return NO;
}
char *sourcePaths[] = { pathBuffer, 0 };
char *sourcePaths[] = {pathBuffer, 0};
FTS *fts = fts_open(sourcePaths, FTS_PHYSICAL | FTS_NOCHDIR, compareFiles);
if (!fts) {
if (error != NULL) {
@@ -256,7 +253,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
fprintf(stderr, "Creating version %u.%u patch...\n", majorVersion, minorVersion);
fprintf(stderr, "Processing %s...", [source fileSystemRepresentation]);
}
FTSENT *ent = 0;
while ((ent = fts_read(fts))) {
if (ent->fts_info != FTS_F && ent->fts_info != FTS_SL && ent->fts_info != FTS_D) {
@@ -279,7 +276,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
return NO;
}
originalTreeState[key] = info;
if (aclExists(ent)) {
if (verbose) {
fprintf(stderr, "\n");
@@ -289,7 +286,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
}
return NO;
}
if (codeSignatureExtendedAttributeExists(ent)) {
if (verbose) {
fprintf(stderr, "\n");
@@ -301,7 +298,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
}
}
fts_close(fts);
NSString *beforeHash = hashOfTreeWithVersion(source, majorVersion);
if (!beforeHash) {
@@ -315,7 +312,8 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
}
NSMutableDictionary *newTreeState = [NSMutableDictionary dictionary];
for (NSString *key in originalTreeState) {
for (NSString *key in originalTreeState)
{
newTreeState[key] = [NSNull null];
}
@@ -333,7 +331,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
}
return NO;
}
sourcePaths[0] = pathBuffer;
fts = fts_open(sourcePaths, FTS_PHYSICAL | FTS_NOCHDIR, compareFiles);
if (!fts) {
@@ -343,6 +341,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
return NO;
}
while ((ent = fts_read(fts))) {
if (ent->fts_info != FTS_F && ent->fts_info != FTS_SL && ent->fts_info != FTS_D) {
continue;
@@ -363,13 +362,13 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
}
return NO;
}
// We should validate permissions and ACLs even if we don't store the info in the diff in the case of ACLs,
// or in the case of permissions if the patch version is 1
// We should also not allow files with code signed extended attributes since Apple doesn't recommend inserting these
// inside an application, and since we don't preserve extended attribitutes anyway
mode_t permissions = [info[INFO_PERMISSIONS_KEY] unsignedShortValue];
if (!IS_VALID_PERMISSIONS(permissions)) {
if (verbose) {
@@ -380,7 +379,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
}
return NO;
}
if (aclExists(ent)) {
if (verbose) {
fprintf(stderr, "\n");
@@ -390,7 +389,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
}
return NO;
}
if (codeSignatureExtendedAttributeExists(ent)) {
if (verbose) {
fprintf(stderr, "\n");
@@ -400,14 +399,14 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
}
return NO;
}
NSDictionary *oldInfo = originalTreeState[key];
if ([info isEqual:oldInfo]) {
[newTreeState removeObjectForKey:key];
} else {
newTreeState[key] = info;
if (oldInfo && [oldInfo[INFO_TYPE_KEY] unsignedShortValue] == FTS_D && [info[INFO_TYPE_KEY] unsignedShortValue] != FTS_D) {
NSArray *parentPathComponents = key.pathComponents;
@@ -433,7 +432,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
}
return NO;
}
if (verbose) {
fprintf(stderr, "\nGenerating delta...");
}
@@ -449,18 +448,20 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
}
return NO;
}
xar_opt_set(x, XAR_OPT_COMPRESSION, "bzip2");
xar_subdoc_t attributes = xar_subdoc_new(x, BINARY_DELTA_ATTRIBUTES_KEY);
xar_subdoc_prop_set(attributes, MAJOR_DIFF_VERSION_KEY, [[NSString stringWithFormat:@"%u", majorVersion] UTF8String]);
xar_subdoc_prop_set(attributes, MINOR_DIFF_VERSION_KEY, [[NSString stringWithFormat:@"%u", minorVersion] UTF8String]);
// Version 1 patches don't have a major or minor version field, so we need to differentiate between the hash keys
const char *beforeHashKey = MAJOR_VERSION_IS_AT_LEAST(majorVersion, SUBeigeMajorVersion) ? BEFORE_TREE_SHA1_KEY : BEFORE_TREE_SHA1_OLD_KEY;
const char *afterHashKey = MAJOR_VERSION_IS_AT_LEAST(majorVersion, SUBeigeMajorVersion) ? AFTER_TREE_SHA1_KEY : AFTER_TREE_SHA1_OLD_KEY;
const char *beforeHashKey =
MAJOR_VERSION_IS_AT_LEAST(majorVersion, SUBeigeMajorVersion) ? BEFORE_TREE_SHA1_KEY : BEFORE_TREE_SHA1_OLD_KEY;
const char *afterHashKey =
MAJOR_VERSION_IS_AT_LEAST(majorVersion, SUBeigeMajorVersion) ? AFTER_TREE_SHA1_KEY : AFTER_TREE_SHA1_OLD_KEY;
xar_subdoc_prop_set(attributes, beforeHashKey, [beforeHash UTF8String]);
xar_subdoc_prop_set(attributes, afterHashKey, [afterHash UTF8String]);
@@ -470,21 +471,21 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
// Sort the keys by preferring the ones from the original tree to appear first
// We want to enforce deleting before extracting in the case paths differ only by case
NSArray *keys = [[newTreeState allKeys] sortedArrayUsingComparator:^NSComparisonResult(NSString *key1, NSString *key2) {
NSComparisonResult insensitiveCompareResult = [key1 caseInsensitiveCompare:key2];
if (insensitiveCompareResult != NSOrderedSame) {
return insensitiveCompareResult;
}
NSComparisonResult insensitiveCompareResult = [key1 caseInsensitiveCompare:key2];
if (insensitiveCompareResult != NSOrderedSame) {
return insensitiveCompareResult;
}
return originalTreeState[key1] ? NSOrderedAscending : NSOrderedDescending;
return originalTreeState[key1] ? NSOrderedAscending : NSOrderedDescending;
}];
for (NSString *key in keys) {
for (NSString* key in keys) {
id value = [newTreeState valueForKey:key];
if ([value isEqual:[NSNull null]]) {
xar_file_t newFile = xar_add_frombuffer(x, 0, [key fileSystemRepresentation], (char *)"", 1);
assert(newFile);
xar_prop_set(newFile, DELETE_KEY, "true");
if (verbose) {
fprintf(stderr, "\n❌ %s %s", VERBOSE_REMOVED, [key fileSystemRepresentation]);
}
@@ -499,7 +500,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
xar_file_t newFile = xar_add_frombuffer(x, 0, [key fileSystemRepresentation], (char *)"", 1);
assert(newFile);
xar_prop_set(newFile, MODIFY_PERMISSIONS_KEY, [[NSString stringWithFormat:@"%u", [newInfo[INFO_PERMISSIONS_KEY] unsignedShortValue]] UTF8String]);
if (verbose) {
fprintf(stderr, "\n👮 %s %s (0%o -> 0%o)", VERBOSE_MODIFIED, [key fileSystemRepresentation], [originalInfo[INFO_PERMISSIONS_KEY] unsignedShortValue], [newInfo[INFO_PERMISSIONS_KEY] unsignedShortValue]);
}
@@ -508,7 +509,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
NSString *path = [destination stringByAppendingPathComponent:key];
xar_file_t newFile = xar_add_frompath(x, 0, [key fileSystemRepresentation], [path fileSystemRepresentation]);
assert(newFile);
if (shouldDeleteThenExtract(originalInfo, newInfo)) {
if (MAJOR_VERSION_IS_AT_LEAST(majorVersion, SUBeigeMajorVersion)) {
xar_prop_set(newFile, DELETE_KEY, "true");
@@ -516,11 +517,11 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
xar_prop_set(newFile, DELETE_THEN_EXTRACT_OLD_KEY, "true");
}
}
if (MAJOR_VERSION_IS_AT_LEAST(majorVersion, SUBeigeMajorVersion)) {
xar_prop_set(newFile, EXTRACT_KEY, "true");
}
if (verbose) {
if (originalInfo) {
fprintf(stderr, "\n✏️ %s %s", VERBOSE_UPDATED, [key fileSystemRepresentation]);
@@ -553,19 +554,19 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
}
return NO;
}
if (verbose) {
fprintf(stderr, "\n🔨 %s %s", VERBOSE_DIFFED, [[operation relativePath] fileSystemRepresentation]);
}
xar_file_t newFile = xar_add_frompath(x, 0, [[operation relativePath] fileSystemRepresentation], [resultPath fileSystemRepresentation]);
assert(newFile);
xar_prop_set(newFile, BINARY_DELTA_KEY, "true");
unlink([resultPath fileSystemRepresentation]);
if (operation.permissions) {
xar_prop_set(newFile, MODIFY_PERMISSIONS_KEY, [[NSString stringWithFormat:@"%u", [operation.permissions unsignedShortValue]] UTF8String]);
if (verbose) {
fprintf(stderr, "\n👮 %s %s (0%o -> 0%o)", VERBOSE_MODIFIED, [[operation relativePath] fileSystemRepresentation], operation.oldPermissions.unsignedShortValue, operation.permissions.unsignedShortValue);
}
@@ -577,7 +578,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF
unlink([patchFile fileSystemRepresentation]);
link([temporaryFile fileSystemRepresentation], [patchFile fileSystemRepresentation]);
unlink([temporaryFile fileSystemRepresentation]);
if (verbose) {
fprintf(stderr, "\nDone!\n");
}
+37 -43
View File
@@ -20,8 +20,6 @@
#define VERSION_COMMAND @"version"
#define VERSION_ALTERNATE_COMMAND @"--version"
#include "AppKitPrevention.h"
static void printUsage(NSString *programName)
{
fprintf(stderr, "Usage:\n");
@@ -36,7 +34,7 @@ static BOOL runCreateCommand(NSString *programName, NSArray *args)
printUsage(programName);
return NO;
}
NSUInteger numberOflagsFound = 0;
NSUInteger verboseIndex = [args indexOfObject:VERBOSE_FLAG];
NSUInteger versionIndex = NSNotFound;
@@ -46,22 +44,22 @@ static BOOL runCreateCommand(NSString *programName, NSArray *args)
break;
}
}
if (verboseIndex != NSNotFound) {
++numberOflagsFound;
}
if (versionIndex != NSNotFound) {
++numberOflagsFound;
}
if (args.count - numberOflagsFound < 3) {
printUsage(programName);
return NO;
}
BOOL verbose = (verboseIndex != NSNotFound);
NSString *versionField = (versionIndex != NSNotFound) ? args[versionIndex] : nil;
NSArray *versionComponents = nil;
if (versionField) {
versionComponents = [versionField componentsSeparatedByString:@"="];
@@ -70,17 +68,17 @@ static BOOL runCreateCommand(NSString *programName, NSArray *args)
return NO;
}
}
SUBinaryDeltaMajorVersion patchVersion =
!versionComponents ?
LATEST_DELTA_DIFF_MAJOR_VERSION :
(SUBinaryDeltaMajorVersion)[[versionComponents[1] componentsSeparatedByString:@"."][0] intValue]; // ignore minor version if provided
if (patchVersion < FIRST_DELTA_DIFF_MAJOR_VERSION) {
fprintf(stderr, "Version provided (%u) is not valid\n", patchVersion);
return NO;
}
if (patchVersion > LATEST_DELTA_DIFF_MAJOR_VERSION) {
fprintf(stderr, "This program is too old to create a version %u patch, or the version number provided is invalid\n", patchVersion);
return NO;
@@ -92,35 +90,31 @@ static BOOL runCreateCommand(NSString *programName, NSArray *args)
[fileArgs addObject:argument];
}
}
if (fileArgs.count != 3) {
printUsage(programName);
return NO;
}
NSString *sourcePath = fileArgs[0];
NSString *destPath = fileArgs[1];
NSString *patchPath = fileArgs[2];
BOOL isDirectory;
if (![[NSFileManager defaultManager] fileExistsAtPath:sourcePath isDirectory:&isDirectory] || !isDirectory) {
if (![[NSFileManager defaultManager] fileExistsAtPath:fileArgs[0] isDirectory:&isDirectory] || !isDirectory) {
printUsage(programName);
fprintf(stderr, "Error: before-tree must be a directory\n");
return NO;
}
if (![[NSFileManager defaultManager] fileExistsAtPath:destPath isDirectory:&isDirectory] || !isDirectory) {
if (![[NSFileManager defaultManager] fileExistsAtPath:fileArgs[1] isDirectory:&isDirectory] || !isDirectory) {
printUsage(programName);
fprintf(stderr, "Error: after-tree must be a directory\n");
return NO;
}
NSError *createDiffError = nil;
if (!createBinaryDelta(sourcePath, destPath, patchPath, patchVersion, verbose, &createDiffError)) {
if (!createBinaryDelta(fileArgs[0], fileArgs[1], fileArgs[2], patchVersion, verbose, &createDiffError)) {
fprintf(stderr, "%s\n", [createDiffError.localizedDescription UTF8String]);
return NO;
}
return YES;
}
@@ -130,45 +124,45 @@ static BOOL runApplyCommand(NSString *programName, NSArray *args)
printUsage(programName);
return NO;
}
BOOL verbose = [args containsObject:VERBOSE_FLAG];
if (args.count == 4 && !verbose) {
printUsage(programName);
return NO;
}
NSMutableArray *fileArgs = [NSMutableArray array];
for (NSString *argument in args) {
if (![argument isEqualToString:VERBOSE_FLAG]) {
[fileArgs addObject:argument];
}
}
if (fileArgs.count != 3) {
printUsage(programName);
return NO;
}
BOOL isDirectory;
if (![[NSFileManager defaultManager] fileExistsAtPath:fileArgs[0] isDirectory:&isDirectory] || !isDirectory) {
printUsage(programName);
fprintf(stderr, "Error: before-tree must be a directory\n");
return NO;
}
if (![[NSFileManager defaultManager] fileExistsAtPath:fileArgs[2] isDirectory:&isDirectory] || isDirectory) {
printUsage(programName);
fprintf(stderr, "Error: patch-file must be a file %d\n", isDirectory);
return NO;
}
NSError *applyDiffError = nil;
if (!applyBinaryDelta(fileArgs[0], fileArgs[1], fileArgs[2], verbose, ^(__unused double x){}, &applyDiffError)) {
if (!applyBinaryDelta(fileArgs[0], fileArgs[1], fileArgs[2], verbose, &applyDiffError)) {
fprintf(stderr, "%s\n", [applyDiffError.localizedDescription UTF8String]);
return NO;
}
return YES;
}
@@ -178,7 +172,7 @@ static BOOL runVersionCommand(NSString *programName, NSArray *args)
printUsage(programName);
return NO;
}
if (args.count == 0) {
fprintf(stdout, "%u.%u\n", LATEST_DELTA_DIFF_MAJOR_VERSION, latestMinorVersionForMajorVersion(LATEST_DELTA_DIFF_MAJOR_VERSION));
} else {
@@ -188,30 +182,30 @@ static BOOL runVersionCommand(NSString *programName, NSArray *args)
fprintf(stderr, "Unable to open patch %s\n", [patchFile fileSystemRepresentation]);
return NO;
}
SUBinaryDeltaMajorVersion majorDiffVersion = FIRST_DELTA_DIFF_MAJOR_VERSION;
int minorDiffVersion = 0;
SUBinaryDeltaMinorVersion minorDiffVersion = FIRST_DELTA_DIFF_MINOR_VERSION;
xar_subdoc_t subdoc;
for (subdoc = xar_subdoc_first(x); subdoc; subdoc = xar_subdoc_next(subdoc)) {
if (!strcmp(xar_subdoc_name(subdoc), BINARY_DELTA_ATTRIBUTES_KEY)) {
const char *value = 0;
// available in version 2.0 or later
xar_subdoc_prop_get(subdoc, MAJOR_DIFF_VERSION_KEY, &value);
if (value)
majorDiffVersion = (SUBinaryDeltaMajorVersion)[@(value) intValue];
// available in version 2.0 or later
xar_subdoc_prop_get(subdoc, MINOR_DIFF_VERSION_KEY, &value);
if (value)
minorDiffVersion = [@(value) intValue];
minorDiffVersion = (SUBinaryDeltaMinorVersion)[@(value) intValue];
}
}
fprintf(stdout, "%u.%u\n", majorDiffVersion, minorDiffVersion);
}
return YES;
}
@@ -220,7 +214,7 @@ int main(int __unused argc, char __unused *argv[])
@autoreleasepool {
NSArray *args = [[NSProcessInfo processInfo] arguments];
NSString *programName = [args[0] lastPathComponent];
if (args.count < 2) {
printUsage(programName);
return 1;
@@ -228,7 +222,7 @@ int main(int __unused argc, char __unused *argv[])
NSString *command = args[1];
NSArray *commandArguments = [args subarrayWithRange:NSMakeRange(2, args.count - 2)];
BOOL result;
if ([command isEqualToString:CREATE_COMMAND]) {
result = runCreateCommand(programName, commandArguments);
@@ -240,7 +234,7 @@ int main(int __unused argc, char __unused *argv[])
result = NO;
printUsage(programName);
}
return result ? 0 : 1;
}
}
+3 -9
View File
@@ -9,17 +9,11 @@
#ifndef SUBINARYDELTAUNARCHIVER_H
#define SUBINARYDELTAUNARCHIVER_H
#import <Foundation/Foundation.h>
#import "SUUnarchiverProtocol.h"
#import <Cocoa/Cocoa.h>
#import "SUUnarchiver.h"
NS_ASSUME_NONNULL_BEGIN
@interface SUBinaryDeltaUnarchiver : NSObject <SUUnarchiverProtocol>
- (instancetype)initWithArchivePath:(NSString *)archivePath updateHostBundlePath:(NSString *)updateHostBundlePath;
@interface SUBinaryDeltaUnarchiver : SUUnarchiver
@end
NS_ASSUME_NONNULL_END
#endif
+23 -83
View File
@@ -6,113 +6,53 @@
// Copyright 2009 Mark Rowe. All rights reserved.
//
#import "SUBinaryDeltaUnarchiver.h"
#import "SUUnarchiverNotifier.h"
#import "SUBinaryDeltaCommon.h"
#import "SUBinaryDeltaUnarchiver.h"
#import "SUBinaryDeltaApply.h"
#import "SUUnarchiver_Private.h"
#import "SUHost.h"
#import "SULog.h"
#import "SUFileManager.h"
#include "AppKitPrevention.h"
@interface SUBinaryDeltaUnarchiver ()
@property (nonatomic, copy, readonly) NSString *archivePath;
@property (nonatomic, copy, readonly) NSString *updateHostBundlePath;
@end
#import "NTSynchronousTask.h"
@implementation SUBinaryDeltaUnarchiver
@synthesize archivePath = _archivePath;
@synthesize updateHostBundlePath = _updateHostBundlePath;
+ (BOOL)canUnarchivePath:(NSString *)path
{
return [[path pathExtension] isEqualToString:@"delta"];
}
+ (BOOL)unsafeIfArchiveIsNotValidated
- (void)applyBinaryDelta
{
return YES;
}
@autoreleasepool {
NSString *sourcePath = self.updateHostBundlePath;
NSString *targetPath = [[self.archivePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:[sourcePath lastPathComponent]];
// 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];
}
NSError *applyDiffError = nil;
BOOL success = applyBinaryDelta(sourcePath, targetPath, self.archivePath, NO, &applyDiffError);
if (success) {
dispatch_async(dispatch_get_main_queue(), ^{
[self notifyDelegateOfSuccess];
});
}
SUFileManager *fileManager = [SUFileManager defaultManager];
for (NSURL *file in filesToUpdate) {
NSError *error = nil;
if (![fileManager updateModificationAndAccessTimeOfItemAtURL:file error:&error]) {
SULog(SULogLevelError, @"Error: During delta unarchiving, failed to touch %@", error);
}
else {
SULog(@"Applying delta patch failed with error: %@", applyDiffError);
dispatch_async(dispatch_get_main_queue(), ^{
[self notifyDelegateOfFailure];
});
}
}
}
- (instancetype)initWithArchivePath:(NSString *)archivePath updateHostBundlePath:(NSString *)updateHostBundlePath
{
self = [super init];
if (self != nil) {
_archivePath = [archivePath copy];
_updateHostBundlePath = [updateHostBundlePath copy];
}
return self;
}
- (void)unarchiveWithCompletionBlock:(void (^)(NSError * _Nullable))completionBlock progressBlock:(void (^ _Nullable)(double))progressBlock
- (void)start
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
@autoreleasepool {
SUUnarchiverNotifier *notifier = [[SUUnarchiverNotifier alloc] initWithCompletionBlock:completionBlock progressBlock:progressBlock];
[self extractDeltaWithNotifier:notifier];
}
[self applyBinaryDelta];
});
}
- (void)extractDeltaWithNotifier:(SUUnarchiverNotifier *)notifier
+ (void)load
{
NSString *sourcePath = self.updateHostBundlePath;
NSString *targetPath = [[self.archivePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:[sourcePath lastPathComponent]];
NSError *applyDiffError = nil;
BOOL success = applyBinaryDelta(sourcePath, targetPath, self.archivePath, NO, ^(double progress){
[notifier notifyProgress:progress];
}, &applyDiffError);
if (success) {
[[self class] updateSpotlightImportersAtBundlePath:targetPath];
[notifier notifySuccess];
}
else {
[notifier notifyFailureWithError:applyDiffError];
}
[self registerImplementation:self];
}
- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], self.archivePath]; }
@end
-21
View File
@@ -1,21 +0,0 @@
//
// SUBundleIcon.h
// Sparkle
//
// Created by Mayur Pawashe on 7/24/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@class SUHost;
@interface SUBundleIcon : NSObject
+ (NSURL * _Nullable)iconURLForHost:(SUHost *)host;
@end
NS_ASSUME_NONNULL_END
-34
View File
@@ -1,34 +0,0 @@
//
// SUBundleIcon.m
// Sparkle
//
// Created by Mayur Pawashe on 7/24/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import "SUBundleIcon.h"
#import "SUHost.h"
#include "AppKitPrevention.h"
@implementation SUBundleIcon
// Note: To obtain the most current bundle icon file from the Info dictionary, this should take a SUHost, not a NSBundle
+ (NSURL *)iconURLForHost:(SUHost *)host
{
NSString *resource = [host objectForInfoDictionaryKey:@"CFBundleIconFile"];
if (resource == nil || ![resource isKindOfClass:[NSString class]]) {
return nil;
}
NSURL *iconURL = [host.bundle URLForResource:resource withExtension:@"icns"];
// The resource could already be containing the path extension, so try again without the extra extension
if (iconURL == nil) {
iconURL = [host.bundle URLForResource:resource withExtension:nil];
}
return iconURL;
}
@end
+4 -3
View File
@@ -12,9 +12,10 @@
#import <Foundation/Foundation.h>
@interface SUCodeSigningVerifier : NSObject
+ (BOOL)codeSignatureAtBundleURL:(NSURL *)oldBundlePath matchesSignatureAtBundleURL:(NSURL *)newBundlePath error:(NSError **)error;
+ (BOOL)codeSignatureIsValidAtBundleURL:(NSURL *)bundlePath error:(NSError **)error;
+ (BOOL)bundleAtURLIsCodeSigned:(NSURL *)bundlePath;
+ (BOOL)codeSignatureMatchesHostAndIsValidAtPath:(NSString *)applicationPath error:(NSError **)error;
+ (BOOL)codeSignatureIsValidAtPath:(NSString *)applicationPath error:(NSError **)error;
+ (BOOL)hostApplicationIsCodeSigned;
+ (BOOL)applicationAtPathIsCodeSigned:(NSString *)applicationPath;
@end
#endif
+75 -41
View File
@@ -11,107 +11,120 @@
#import "SUCodeSigningVerifier.h"
#import "SULog.h"
#include "AppKitPrevention.h"
@implementation SUCodeSigningVerifier
+ (BOOL)codeSignatureAtBundleURL:(NSURL *)oldBundleURL matchesSignatureAtBundleURL:(NSURL *)newBundleURL error:(NSError *__autoreleasing *)error
+ (BOOL)codeSignatureMatchesHostAndIsValidAtPath:(NSString *)applicationPath error:(NSError *__autoreleasing *)error
{
OSStatus result;
SecRequirementRef requirement = NULL;
SecStaticCodeRef staticCode = NULL;
SecStaticCodeRef oldCode = NULL;
SecCodeRef hostCode = NULL;
NSBundle *newBundle;
CFErrorRef cfError = NULL;
if (error) {
*error = nil;
}
result = SecStaticCodeCreateWithPath((__bridge CFURLRef)oldBundleURL, kSecCSDefaultFlags, &oldCode);
if (result == errSecCSUnsigned) {
return NO;
}
result = SecCodeCopyDesignatedRequirement(oldCode, kSecCSDefaultFlags, &requirement);
result = SecCodeCopySelf(kSecCSDefaultFlags, &hostCode);
if (result != noErr) {
SULog(SULogLevelError, @"Failed to copy designated requirement. Code Signing OSStatus code: %d", result);
SULog(@"Failed to copy host code %d", result);
goto finally;
}
result = SecStaticCodeCreateWithPath((__bridge CFURLRef)newBundleURL, kSecCSDefaultFlags, &staticCode);
result = SecCodeCopyDesignatedRequirement(hostCode, kSecCSDefaultFlags, &requirement);
if (result != noErr) {
SULog(SULogLevelError, @"Failed to get static code %d", result);
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);
if (result != noErr) {
SULog(@"Failed to get static code %d", result);
goto finally;
}
// Note that kSecCSCheckNestedCode may not work with pre-Mavericks code signing.
// See https://github.com/sparkle-project/Sparkle/issues/376#issuecomment-48824267 and https://developer.apple.com/library/mac/technotes/tn2206
// Aditionally, there are several reasons to stay away from deep verification and to prefer DSA signing the download archive instead.
// See https://github.com/sparkle-project/Sparkle/pull/523#commitcomment-17549302 and https://github.com/sparkle-project/Sparkle/issues/543
SecCSFlags flags = (SecCSFlags) (kSecCSDefaultFlags | kSecCSCheckAllArchitectures);
SecCSFlags flags = (SecCSFlags) (kSecCSDefaultFlags | kSecCSCheckAllArchitectures);
result = SecStaticCodeCheckValidityWithErrors(staticCode, flags, requirement, &cfError);
if (cfError) {
NSError *tmpError = CFBridgingRelease(cfError);
if (error) *error = tmpError;
}
if (result != noErr) {
if (result == errSecCSUnsigned) {
SULog(SULogLevelError, @"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.");
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.");
}
if (result == errSecCSReqFailed) {
CFStringRef requirementString = nil;
if (SecRequirementCopyString(requirement, kSecCSDefaultFlags, &requirementString) == noErr) {
SULog(SULogLevelError, @"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);
SULog(@"Code signature of the new version doesn't match the old version: %@. Please ensure that old and new app is signed using exactly the same certificate.", requirementString);
CFRelease(requirementString);
}
[self logSigningInfoForCode:oldCode label:@"old info"];
[self logSigningInfoForCode:hostCode label:@"host info"];
[self logSigningInfoForCode:staticCode label:@"new info"];
}
}
finally:
if (oldCode) CFRelease(oldCode);
if (hostCode) CFRelease(hostCode);
if (staticCode) CFRelease(staticCode);
if (requirement) CFRelease(requirement);
return (result == noErr);
}
+ (BOOL)codeSignatureIsValidAtBundleURL:(NSURL *)bundleURL error:(NSError *__autoreleasing *)error
+ (BOOL)codeSignatureIsValidAtPath:(NSString *)applicationPath error:(NSError *__autoreleasing *)error
{
OSStatus result;
SecStaticCodeRef staticCode = NULL;
NSBundle *newBundle;
CFErrorRef cfError = NULL;
if (error) {
*error = nil;
}
result = SecStaticCodeCreateWithPath((__bridge CFURLRef)bundleURL, kSecCSDefaultFlags, &staticCode);
if (result != noErr) {
SULog(SULogLevelError, @"Failed to get static code %d", result);
newBundle = [NSBundle bundleWithPath:applicationPath];
if (!newBundle) {
SULog(@"Failed to load NSBundle");
result = -1;
goto finally;
}
// See in -codeSignatureAtBundleURL:matchesSignatureAtBundleURL:error: for why kSecCSCheckNestedCode is not passed
SecCSFlags flags = (SecCSFlags) (kSecCSDefaultFlags | kSecCSCheckAllArchitectures);
result = SecStaticCodeCreateWithPath((__bridge CFURLRef)[newBundle bundleURL], kSecCSDefaultFlags, &staticCode);
if (result != noErr) {
SULog(@"Failed to get static code %d", result);
goto finally;
}
// Note that kSecCSCheckNestedCode may not work with pre-Mavericks code signing.
// See https://github.com/sparkle-project/Sparkle/issues/376#issuecomment-48824267 and https://developer.apple.com/library/mac/technotes/tn2206
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(SULogLevelError, @"Error: The app is not signed using Apple Code Signing. %@", bundleURL);
SULog(@"Error: The app is not signed using Apple Code Signing. %@", applicationPath);
}
if (result == errSecCSReqFailed) {
[self logSigningInfoForCode:staticCode label:@"new info"];
}
}
finally:
if (staticCode) CFRelease(staticCode);
return (result == noErr);
@@ -133,18 +146,39 @@ static id valueOrNSNull(id value) {
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(SULogLevelDefault, @"%@: %@", label, relevantInfo);
SULog(@"%@: %@", label, relevantInfo);
}
}
+ (BOOL)bundleAtURLIsCodeSigned:(NSURL *)bundleURL
+ (BOOL)hostApplicationIsCodeSigned
{
OSStatus result;
SecCodeRef hostCode = NULL;
result = SecCodeCopySelf(kSecCSDefaultFlags, &hostCode);
if (result != 0) return NO;
SecRequirementRef requirement = NULL;
result = SecCodeCopyDesignatedRequirement(hostCode, kSecCSDefaultFlags, &requirement);
if (hostCode) CFRelease(hostCode);
if (requirement) CFRelease(requirement);
return (result == 0);
}
+ (BOOL)applicationAtPathIsCodeSigned:(NSString *)applicationPath
{
OSStatus result;
SecStaticCodeRef staticCode = NULL;
NSBundle *newBundle;
result = SecStaticCodeCreateWithPath((__bridge CFURLRef)bundleURL, kSecCSDefaultFlags, &staticCode);
newBundle = [NSBundle bundleWithPath:applicationPath];
if (!newBundle) {
SULog(@"Failed to load NSBundle");
return NO;
}
result = SecStaticCodeCreateWithPath((__bridge CFURLRef)[newBundle bundleURL], kSecCSDefaultFlags, &staticCode);
if (result == errSecCSUnsigned) {
return NO;
return NO;
}
SecRequirementRef requirement = NULL;
@@ -156,7 +190,7 @@ static id valueOrNSNull(id value) {
CFRelease(requirement);
}
if (result == errSecCSUnsigned) {
return NO;
return NO;
}
return (result == 0);
}
+1 -6
View File
@@ -21,8 +21,6 @@ extern const NSTimeInterval SUDefaultUpdateCheckInterval;
extern NSString *const SUBundleIdentifier;
extern NSString *const SUAppcastAttributeValueMacOS;
// -----------------------------------------------------------------------------
// Notifications:
// -----------------------------------------------------------------------------
@@ -49,6 +47,7 @@ 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.")));
@@ -65,9 +64,6 @@ extern NSString *const SUAppcastAttributeDeltaFrom;
extern NSString *const SUAppcastAttributeDSASignature;
extern NSString *const SUAppcastAttributeShortVersionString;
extern NSString *const SUAppcastAttributeVersion;
extern NSString *const SUAppcastAttributeOsType;
extern NSString *const SUAppcastElementCriticalUpdate;
extern NSString *const SUAppcastElementDeltas;
@@ -77,7 +73,6 @@ extern NSString *const SUAppcastElementReleaseNotesLink;
extern NSString *const SUAppcastElementTags;
extern NSString *const SURSSAttributeURL;
extern NSString *const SURSSAttributeLength;
extern NSString *const SURSSElementDescription;
extern NSString *const SURSSElementEnclosure;
+6 -7
View File
@@ -6,23 +6,23 @@
// Copyright 2006 Andy Matuschak. All rights reserved.
//
#import "SUUpdater.h"
#import "SUAppcast.h"
#import "SUAppcastItem.h"
#import "SUVersionComparisonProtocol.h"
#import "SUConstants.h"
#import "SUErrors.h"
#ifndef DEBUG
#define DEBUG 0
#endif
#include "AppKitPrevention.h"
// Define some minimum intervals to avoid DoS-like checking attacks
const NSTimeInterval SUMinimumUpdateCheckInterval = DEBUG ? 60 : (60 * 60);
const NSTimeInterval SUDefaultUpdateCheckInterval = DEBUG ? 60 : (60 * 60 * 24);
NSString *const SUBundleIdentifier = @SPARKLE_BUNDLE_IDENTIFIER;
NSString *const SUAppcastAttributeValueMacOS = @"macos";
NSString *const SUTechnicalErrorInformationKey = @"SUTechnicalErrorInformation";
NSString *const SUHasLaunchedBeforeKey = @"SUHasLaunchedBefore";
@@ -43,6 +43,7 @@ NSString *const SULastProfileSubmitDateKey = @"SULastProfileSubmissionDate";
NSString *const SUPromptUserOnFirstLaunchKey = @"SUPromptUserOnFirstLaunch";
NSString *const SUEnableJavaScriptKey = @"SUEnableJavaScript";
NSString *const SUFixedHTMLDisplaySizeKey = @"SUFixedHTMLDisplaySize";
NSString *const SUKeepDownloadOnFailedInstallKey = @"SUKeepDownloadOnFailedInstall";
NSString *const SUDefaultsDomainKey = @"SUDefaultsDomain";
NSString *const SUSparkleErrorDomain = @"SUSparkleErrorDomain";
@@ -55,7 +56,6 @@ NSString *const SUAppcastAttributeDeltaFrom = @"sparkle:deltaFrom";
NSString *const SUAppcastAttributeDSASignature = @"sparkle:dsaSignature";
NSString *const SUAppcastAttributeShortVersionString = @"sparkle:shortVersionString";
NSString *const SUAppcastAttributeVersion = @"sparkle:version";
NSString *const SUAppcastAttributeOsType = @"sparkle:os";
NSString *const SUAppcastElementCriticalUpdate = @"sparkle:criticalUpdate";
NSString *const SUAppcastElementDeltas = @"sparkle:deltas";
@@ -65,7 +65,6 @@ NSString *const SUAppcastElementReleaseNotesLink = @"sparkle:releaseNotesLink";
NSString *const SUAppcastElementTags = @"sparkle:tags";
NSString *const SURSSAttributeURL = @"url";
NSString *const SURSSAttributeLength = @"length";
NSString *const SURSSElementDescription = @"description";
NSString *const SURSSElementEnclosure = @"enclosure";
+9 -12
View File
@@ -16,9 +16,6 @@
#import "SULog.h"
#include <CommonCrypto/CommonDigest.h>
#include "AppKitPrevention.h"
@implementation SUDSAVerifier {
SecKeyRef _secKey;
}
@@ -26,7 +23,7 @@
+ (BOOL)validatePath:(NSString *)path withEncodedDSASignature:(NSString *)encodedSignature withPublicDSAKey:(NSString *)pkeyString
{
if (!encodedSignature) {
SULog(SULogLevelError, @"There is no DSA signature to check");
SULog(@"There is no DSA signature to check");
return NO;
}
@@ -50,7 +47,7 @@
self = [super init];
if (!self || !data.length) {
SULog(SULogLevelError, @"Could not read public DSA key");
SULog(@"Could not read public DSA key");
return nil;
}
@@ -63,7 +60,7 @@
if (items) {
CFRelease(items);
}
SULog(SULogLevelError, @"Public DSA key could not be imported: %d", status);
SULog(@"Public DSA key could not be imported: %d", status);
return nil;
}
@@ -121,7 +118,7 @@
dataReadTransform = SecTransformCreateReadTransformWithReadStream((__bridge CFReadStreamRef)stream);
if (!dataReadTransform) {
SULog(SULogLevelError, @"File containing update archive could not be read (failed to create SecTransform for input stream)");
SULog(@"File containing update archive could not be read (failed to create SecTransform for input stream)");
return cleanup();
}
@@ -135,30 +132,30 @@
dataVerifyTransform = SecVerifyTransformCreate(_secKey, (__bridge CFDataRef)signature, &error);
#pragma clang diagnostic pop
if (!dataVerifyTransform || error) {
SULog(SULogLevelError, @"Could not understand format of the signature: %@; Signature data: %@", error, signature);
SULog(@"Could not understand format of the signature: %@; Signature data: %@", error, signature);
return cleanup();
}
SecTransformConnectTransforms(dataReadTransform, kSecTransformOutputAttributeName, dataDigestTransform, kSecTransformInputAttributeName, group, &error);
if (error) {
SULog(SULogLevelError, @"%@", error);
SULog(@"%@", error);
return cleanup();
}
SecTransformConnectTransforms(dataDigestTransform, kSecTransformOutputAttributeName, dataVerifyTransform, kSecTransformInputAttributeName, group, &error);
if (error) {
SULog(SULogLevelError, @"%@", error);
SULog(@"%@", error);
return cleanup();
}
NSNumber *result = CFBridgingRelease(SecTransformExecute(group, &error));
if (error) {
SULog(SULogLevelError, @"DSA signature verification failed: %@", error);
SULog(@"DSA signature verification failed: %@", error);
return cleanup();
}
if (!result.boolValue) {
SULog(SULogLevelError, @"DSA signature does not match. Data of the update file being checked is different than data that has been signed, or the public key and the private key are not from the same set.");
SULog(@"DSA signature does not match. Data of the update file being checked is different than data that has been signed, or the public key and the private key are not from the same set.");
}
cleanup();
+3 -9
View File
@@ -9,17 +9,11 @@
#ifndef SUDISKIMAGEUNARCHIVER_H
#define SUDISKIMAGEUNARCHIVER_H
#import <Foundation/Foundation.h>
#import "SUUnarchiverProtocol.h"
#import <Cocoa/Cocoa.h>
#import "SUUnarchiver.h"
NS_ASSUME_NONNULL_BEGIN
@interface SUDiskImageUnarchiver : NSObject <SUUnarchiverProtocol>
- (instancetype)initWithArchivePath:(NSString *)archivePath decryptionPassword:(nullable NSString *)decryptionPassword;
@interface SUDiskImageUnarchiver : SUUnarchiver
@end
NS_ASSUME_NONNULL_END
#endif
+83 -108
View File
@@ -7,86 +7,71 @@
//
#import "SUDiskImageUnarchiver.h"
#import "SUUnarchiverNotifier.h"
#import "SUUnarchiver_Private.h"
#import "NTSynchronousTask.h"
#import "SULog.h"
#include "AppKitPrevention.h"
@interface SUDiskImageUnarchiver ()
@property (nonatomic, copy, readonly) NSString *archivePath;
@property (nullable, nonatomic, copy, readonly) NSString *decryptionPassword;
@end
#include <CoreServices/CoreServices.h>
@implementation SUDiskImageUnarchiver
@synthesize archivePath = _archivePath;
@synthesize decryptionPassword = _decryptionPassword;
+ (BOOL)canUnarchivePath:(NSString *)path
{
return [[path pathExtension] isEqualToString:@"dmg"];
}
+ (BOOL)unsafeIfArchiveIsNotValidated
// Called on a non-main thread.
- (void)extractDMG
{
return NO;
}
- (instancetype)initWithArchivePath:(NSString *)archivePath decryptionPassword:(nullable NSString *)decryptionPassword
{
self = [super init];
if (self != nil) {
_archivePath = [archivePath copy];
_decryptionPassword = [decryptionPassword copy];
@autoreleasepool {
[self extractDMGWithPassword:nil];
}
return self;
}
- (void)unarchiveWithCompletionBlock:(void (^)(NSError * _Nullable))completionBlock progressBlock:(void (^ _Nullable)(double))progressBlock
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
SUUnarchiverNotifier *notifier = [[SUUnarchiverNotifier alloc] initWithCompletionBlock:completionBlock progressBlock:progressBlock];
[self extractDMGWithNotifier:notifier];
});
}
// Called on a non-main thread.
- (void)extractDMGWithNotifier:(SUUnarchiverNotifier *)notifier
- (void)extractDMGWithPassword:(NSString *)__unused password
{
@autoreleasepool {
BOOL mountedSuccessfully = NO;
SULog(@"Extracting %@ as a DMG", self.archivePath);
// get a unique mount point path
NSString *mountPoint = nil;
FSRef tmpRef;
NSFileManager *manager;
NSError *error;
NSArray *contents;
do
// We have to declare these before a goto to prevent an error under ARC.
// No, we cannot have them in the dispatch_async calls, as the goto "jump enters
// lifetime of block which strongly captures a variable"
dispatch_block_t delegateFailure = ^{
[self notifyDelegateOfFailure];
};
dispatch_block_t delegateSuccess = ^{
[self notifyDelegateOfSuccess];
};
do
{
// Using NSUUID would make creating UUIDs be done in Cocoa,
// and thus managed under ARC. Sadly, the class is in 10.8 and later.
CFUUIDRef uuid = CFUUIDCreate(NULL);
if (uuid)
{
if (uuid)
{
NSString *uuidString = CFBridgingRelease(CFUUIDCreateString(NULL, uuid));
if (uuidString)
{
if (uuidString)
{
mountPoint = [@"/Volumes" stringByAppendingPathComponent:uuidString];
}
CFRelease(uuid);
}
}
// Note: this check does not follow symbolic links, which is what we want
while ([[NSURL fileURLWithPath:mountPoint] checkResourceIsReachableAndReturnError:NULL]);
}
while (noErr == FSPathMakeRefWithOptions((const UInt8 *)[mountPoint fileSystemRepresentation], kFSPathMakeRefDoNotFollowLeafSymlink, &tmpRef, NULL));
NSData *promptData = nil;
promptData = [NSData dataWithBytes:"yes\n" length:4];
NSMutableArray *arguments = [@[@"attach", self.archivePath, @"-mountpoint", mountPoint, /*@"-noverify",*/ @"-nobrowse", @"-noautoopen"] mutableCopy];
if (self.decryptionPassword) {
NSMutableData *passwordData = [[self.decryptionPassword dataUsingEncoding:NSUTF8StringEncoding] mutableCopy];
// From the hdiutil docs:
@@ -96,111 +81,101 @@
[passwordData appendData:[NSData dataWithBytes:"\0" length:1]];
[passwordData appendData:promptData];
promptData = passwordData;
[arguments addObject:@"-stdinpass"];
}
NSData *output = nil;
NSInteger taskResult = -1;
@try
{
NSTask *task = [[NSTask alloc] init];
task.launchPath = @"/usr/bin/hdiutil";
task.currentDirectoryPath = @"/";
task.arguments = arguments;
NSPipe *inputPipe = [NSPipe pipe];
NSPipe *outputPipe = [NSPipe pipe];
task.standardInput = inputPipe;
task.standardOutput = outputPipe;
[task launch];
[notifier notifyProgress:0.125];
@try
{
NTSynchronousTask *task = [[NTSynchronousTask alloc] init];
[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;
[task run:@"/usr/bin/hdiutil" directory:@"/" withArgs:arguments input:promptData];
taskResult = [task result];
output = [[task output] copy];
}
@catch (NSException *)
{
goto reportError;
}
[notifier notifyProgress:0.5];
if (taskResult != 0)
{
NSString *resultStr = output ? [[NSString alloc] initWithData:output encoding:NSUTF8StringEncoding] : nil;
SULog(SULogLevelError, @"hdiutil failed with code: %ld data: <<%@>>", (long)taskResult, resultStr);
SULog(@"hdiutil failed with code: %ld data: <<%@>>", (long)taskResult, resultStr);
goto reportError;
}
mountedSuccessfully = YES;
// Now that we've mounted it, we need to copy out its contents.
manager = [[NSFileManager alloc] init];
contents = [manager contentsOfDirectoryAtPath:mountPoint error:&error];
if (error)
{
SULog(SULogLevelError, @"Couldn't enumerate contents of archive mounted at %@: %@", mountPoint, error);
if (error)
{
SULog(@"Couldn't enumerate contents of archive mounted at %@: %@", mountPoint, error);
goto reportError;
}
double itemsCopied = 0;
double totalItems = [contents count];
for (NSString *item in contents)
{
NSString *fromPath = [mountPoint stringByAppendingPathComponent:item];
NSString *toPath = [[self.archivePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:item];
// We skip any files in the DMG which are not readable.
if (![manager isReadableFileAtPath:fromPath]) {
continue;
}
itemsCopied += 1.0;
[notifier notifyProgress:0.5 + itemsCopied/(totalItems*2.0)];
SULog(SULogLevelDefault, @"copyItemAtPath:%@ toPath:%@", fromPath, toPath);
SULog(@"copyItemAtPath:%@ toPath:%@", fromPath, toPath);
if (![manager copyItemAtPath:fromPath toPath:toPath error:&error])
{
SULog(@"Couldn't copy item: %@ : %@", error, error.userInfo ? error.userInfo : @"");
goto reportError;
}
}
[notifier notifySuccess];
dispatch_async(dispatch_get_main_queue(), delegateSuccess);
goto finally;
reportError:
[notifier notifyFailureWithError:error];
dispatch_async(dispatch_get_main_queue(), delegateFailure);
finally:
if (mountedSuccessfully) {
NSTask *task = [[NSTask alloc] init];
task.launchPath = @"/usr/bin/hdiutil";
task.arguments = @[@"detach", mountPoint, @"-force"];
task.standardOutput = [NSPipe pipe];
task.standardError = [NSPipe pipe];
@try {
[task launch];
} @catch (NSException *exception) {
SULog(SULogLevelError, @"Failed to unmount %@", mountPoint);
SULog(SULogLevelError, @"Exception: %@", exception);
}
} else {
SULog(SULogLevelError, @"Can't mount DMG %@", self.archivePath);
}
if (mountedSuccessfully)
[NSTask launchedTaskWithLaunchPath:@"/usr/bin/hdiutil" arguments:@[@"detach", mountPoint, @"-force"]];
else
SULog(@"Can't mount DMG %@", self.archivePath);
}
}
- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], self.archivePath]; }
- (void)start
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self extractDMG];
});
}
+ (void)load
{
[self registerImplementation:self];
}
- (BOOL)isEncrypted:(NSData *)resultData
{
BOOL result = NO;
if(resultData)
{
NSString *data = [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding];
if ((data != nil) && !NSEqualRanges([data rangeOfString:@"passphrase-count"], NSMakeRange(NSNotFound, 0)))
{
result = YES;
}
}
return result;
}
@end
-5
View File
@@ -9,11 +9,7 @@
#ifndef SUERRORS_H
#define SUERRORS_H
#if __has_feature(modules)
@import Foundation;
#else
#import <Foundation/Foundation.h>
#endif
#import "SUExport.h"
/**
@@ -45,7 +41,6 @@ typedef NS_ENUM(OSStatus, SUError) {
SURelaunchError = 4004,
SUInstallationError = 4005,
SUDowngradeError = 4006,
SUInstallationCancelledError = 4007,
// System phase errors
SUSystemPowerOffError = 5000
+32 -50
View File
@@ -8,30 +8,22 @@
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/**
* A class used for performing file operations that may also perform authorization if allowed and if permission is denied when trying to
* A class used for performing file operations that may also perform authentication if allowed and if permission is denied when trying to
* perform them normally as the running user. All operations on this class may be used on thread other than the main thread.
* This class provides basic file operations and stays away from including much application-level logic.
*/
@interface SUFileManager : NSObject
/**
* Creates a file manager that will not authorize for file operations
* @return A new file manager instance
*/
+ (instancetype)defaultManager;
/**
* Creates a file manager that allows authorizing for file operations
* @param authorizationToolPath Specifies the path to the tool that can perform file operations and be run as root.
* This tool will be invoked when read or write access is denied when attempting ordinary file operations. See the `fileop` tool included in Sparkle.
* 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
* @return A new file manager instance
*
* This method just creates the file manager. It doesn't acquire authorization immediately or if it doesn't need to.
*
* This method just creates the file manager. It doesn't acquire authorization immediately if allowsAuthorization is YES
*/
+ (instancetype)fileManagerWithAuthorizationToolPath:(NSString *)authorizationToolPath;
+ (instancetype)fileManagerAllowingAuthorization:(BOOL)allowsAuthorization;
/**
* Returns a file manager that allows or disallows authorizing for file operations based on the current file manager
@@ -52,17 +44,7 @@ NS_ASSUME_NONNULL_BEGIN
* When moving an item from a source to a destination, it is desirable to create a temporary intermediate destination on the same volume as the destination to ensure
* that the item will be moved, and not copied, from the intermediate point to the final destination. This ensures file atomicity.
*/
- (nullable NSURL *)makeTemporaryDirectoryWithPreferredName:(NSString *)preferredName appropriateForDirectoryURL:(NSURL *)appropriateURL error:(NSError *_Nullable*_Nullable)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 *_Nullable*_Nullable)error;
- (NSURL *)makeTemporaryDirectoryWithPreferredName:(NSString *)preferredName appropriateForDirectoryURL:(NSURL *)appropriateURL error:(NSError **)error;
/**
* Moves an item from a source to a destination
@@ -70,11 +52,11 @@ NS_ASSUME_NONNULL_BEGIN
* @param destinationURL A URL pointing to the destination the item will be moved at. An item must not already exist at this URL.
* @param error If an error occurs, upon returns contains an NSError object that describes the problem. If you are not interested in possible errors, you may pass in NULL.
* @return YES if the item was moved successfully, otherwise NO along with a populated error object
*
*
* If sourceURL and destinationURL reside on the same volume, this operation will be an atomic move operation.
* Otherwise this will be equivalent to a copy & remove which will be a nonatomic operation.
*/
- (BOOL)moveItemAtURL:(NSURL *)sourceURL toURL:(NSURL *)destinationURL error:(NSError *_Nullable*_Nullable)error;
- (BOOL)moveItemAtURL:(NSURL *)sourceURL toURL:(NSURL *)destinationURL error:(NSError **)error;
/**
* Copies an item from a source to a destination
@@ -85,7 +67,22 @@ NS_ASSUME_NONNULL_BEGIN
*
* This is not an atomic operation.
*/
- (BOOL)copyItemAtURL:(NSURL *)sourceURL toURL:(NSURL *)destinationURL error:(NSError *_Nullable*_Nullable)error;
- (BOOL)copyItemAtURL:(NSURL *)sourceURL toURL:(NSURL *)destinationURL error:(NSError **)error;
/**
* Moves an item at a specified URL to the running user's trash directory
* @param url A URL pointing to the item to move to the trash. The item at this URL must exist.
* @param error If an error occurs, upon returns contains an NSError object that describes the problem. If you are not interested in possible errors, you may pass in NULL.
* @return YES if the item was moved to the trash successfully, otherwise NO along with a populated error object
*
*
* This method has to locate the trash directory and uses an intermediate temporary directory before trashing the item.
* A copy may have to be done if the url is not on the same volume as the running user's trash directory.
* If a failure occurs in the middle of this operation, the item to remove may be lost forever or stuck in a temporary location.
*
* This is not an atomic operation, nor intended to be a recoverable operation if the worst comes to worst.
*/
- (BOOL)moveItemAtURLToTrash:(NSURL *)url error:(NSError **)error;
/**
* Removes an item at a URL
@@ -95,7 +92,7 @@ NS_ASSUME_NONNULL_BEGIN
*
* This is not an atomic operation.
*/
- (BOOL)removeItemAtURL:(NSURL *)url error:(NSError *_Nullable*_Nullable)error;
- (BOOL)removeItemAtURL:(NSURL *)url error:(NSError **)error;
/**
* Changes the owner and group IDs of an item at a specified target URL to match another URL
@@ -110,7 +107,7 @@ NS_ASSUME_NONNULL_BEGIN
*
* This is not an atomic operation.
*/
- (BOOL)changeOwnerAndGroupOfItemAtRootURL:(NSURL *)targetURL toMatchURL:(NSURL *)matchURL error:(NSError *_Nullable*_Nullable)error;
- (BOOL)changeOwnerAndGroupOfItemAtRootURL:(NSURL *)targetURL toMatchURL:(NSURL *)matchURL error:(NSError **)error;
/**
* Updates the modification and access time of an item at a specified target URL to the current time
@@ -123,7 +120,7 @@ NS_ASSUME_NONNULL_BEGIN
*
* This is not an atomic operation.
*/
- (BOOL)updateModificationAndAccessTimeOfItemAtURL:(NSURL *)targetURL error:(NSError *_Nullable*_Nullable)error;
- (BOOL)updateModificationAndAccessTimeOfItemAtURL:(NSURL *)targetURL error:(NSError **)error;
/**
* Releases Apple's quarantine extended attribute from the item at the specified root URL
@@ -132,8 +129,8 @@ NS_ASSUME_NONNULL_BEGIN
* @return YES if all the items at the target could be released from quarantine, otherwise NO if any items couldn't along with a populated error object
*
* This method removes quarantine attributes from an item, ideally an application, so that when the user launches a new application themselves, they
* don't have to witness the system dialog alerting them that they downloaded an application from the internet and asking if they want to continue.
* Note that this may not exactly mimic the system behavior when a user opens an application for the first time (i.e, the xattr isn't deleted),
* 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),
* 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.
@@ -141,21 +138,6 @@ NS_ASSUME_NONNULL_BEGIN
*
* This is not an atomic operation.
*/
- (BOOL)releaseItemFromQuarantineAtRootURL:(NSURL *)rootURL error:(NSError *_Nullable*_Nullable)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 progressBlock Callback that takes double value (0..1 range) notifying how far the installation has progressed
* @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 progressBlock:(nullable void(^)(double))progressBlock error:(NSError *_Nullable*_Nullable)error;
NS_ASSUME_NONNULL_END
- (BOOL)releaseItemFromQuarantineAtRootURL:(NSURL *)rootURL error:(NSError **)error;
@end
+172 -213
View File
@@ -7,19 +7,38 @@
//
#import "SUFileManager.h"
#import "SUErrors.h"
#import "SUOperatingSystem.h"
#import "SUFileOperationConstants.h"
#include <sys/xattr.h>
#include <sys/errno.h>
#include <sys/time.h>
#include "AppKitPrevention.h"
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};
@@ -56,37 +75,32 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
{
AuthorizationRef _auth;
NSFileManager *_fileManager;
NSString *_authorizationToolPath;
BOOL _allowsAuthorization;
}
- (instancetype)initWithAuthorizationToolPath:(NSString *)authorizationToolPath
- (instancetype)initAllowingAuthorization:(BOOL)allowsAuthorization
{
self = [super init];
if (self != nil) {
_fileManager = [[NSFileManager alloc] init];
_authorizationToolPath = [authorizationToolPath copy];
_allowsAuthorization = allowsAuthorization;
}
return self;
}
+ (instancetype)defaultManager
+ (instancetype)fileManagerAllowingAuthorization:(BOOL)allowsAuthorization
{
return [[self alloc] initWithAuthorizationToolPath:nil];
}
+ (instancetype)fileManagerWithAuthorizationToolPath:(NSString *)authorizationToolPath
{
return [[self alloc] initWithAuthorizationToolPath:authorizationToolPath];
return [[self alloc] initAllowingAuthorization:allowsAuthorization];
}
- (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];
return (_allowsAuthorization && _auth != NULL) ? self : [SUFileManager fileManagerAllowingAuthorization:NO];
}
// Acquires an authorization reference with root privileges which is intended to be used for authorized file operations
// Acquires an authorization reference which is intended to be used for future authorized file operations
- (BOOL)_acquireAuthorizationWithError:(NSError *__autoreleasing *)error
{
// No need to continue if we already acquired an authorization reference
@@ -94,150 +108,24 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
return YES;
}
if (_authorizationToolPath == nil) {
if (!_allowsAuthorization) {
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 createStatus = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &_auth);
if (createStatus != errAuthorizationSuccess) {
OSStatus status = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &_auth);
if (status != errAuthorizationSuccess) {
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed creating authorization reference with status code %d.", createStatus] }];
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed creating authorization reference with status code %d.", status] }];
}
_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 {
return [self _authorizeAndExecuteCommand:command sourcePath:sourcePath destinationPath:destinationPath lineCallback:nil error:error];
}
- (BOOL)_authorizeAndExecuteCommand:(char *)command sourcePath:(char *)sourcePath destinationPath:(char *)destinationPath lineCallback:(void(^)(NSString*))lineCallback 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"
OSStatus runStatus = AuthorizationExecuteWithPrivileges(_auth, toolPath, kAuthorizationFlagDefaults, arguments, &pipe);
if (runStatus != errAuthorizationSuccess) {
#pragma clang diagnostic pop
if (error != NULL) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wcstring-format-directive"
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Failed to run authorization tool %s (error code %d).", toolPath, (int)runStatus] }];
#pragma clang diagnostic pop
}
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;
}
if (lineCallback) {
NSFileHandle *pipeHandle = [[NSFileHandle alloc] initWithFileDescriptor:fileno(pipe) closeOnDealloc:NO];
[self parseLines:pipeHandle lineCallback:lineCallback];
}
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;
}
- (void)parseLines:(NSFileHandle *)pipeHandle lineCallback:(void(^)(NSString *))lineCallback {
__block NSMutableData *line = [NSMutableData new];
pipeHandle.readabilityHandler = ^(NSFileHandle *handle){
NSData *data = handle.availableData;
NSUInteger length = data.length;
if (!length) {
return;
}
const char *bytes = data.bytes;
for(NSUInteger i = 0; i < length; i++) {
if (bytes[i] == '\n') {
NSData *dataToEOL = [data subdataWithRange:NSMakeRange(0, i)];
[line appendData:dataToEOL];
NSString *fullLine = [[NSString alloc] initWithData:line encoding:NSUTF8StringEncoding];
lineCallback(fullLine);
line = [[data subdataWithRange:NSMakeRange(i+1, length-i-1)] mutableCopy];
break;
}
}
};
}
- (void)dealloc
{
if (_auth != NULL) {
@@ -301,7 +189,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)_removeQuarantineWithAuthenticationAtRootURL:(NSURL *)rootURL error:(NSError *__autoreleasing *)error
- (BOOL)_removeXAttrWithAuthentication:(char *__nonnull)xattrName fromRootURL:(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)]) {
@@ -318,11 +206,16 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
}
return NO;
}
NSError *executeError = nil;
BOOL success = [self _authorizeAndExecuteCommand:SUFileOpRemoveQuarantineCommand sourcePath:path destinationPath:NULL error:&executeError];
if (![self _acquireAuthorizationWithError:error]) {
return NO;
}
BOOL success = AuthorizationExecuteWithPrivilegesAndWait(_auth, XATTR_UTILITY_PATH, kAuthorizationFlagDefaults, (char *[]){ "-s", "-r", "-d", xattrName, path, NULL });
if (!success && error != NULL) {
*error = executeError;
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 }];
}
return success;
@@ -347,7 +240,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
removedQuarantine = YES;
} else {
if (isAccessError(removalError)) {
removedQuarantine = [self _removeQuarantineWithAuthenticationAtRootURL:rootURL error:error];
removedQuarantine = [self _removeXAttrWithAuthentication:SUAppleQuarantineIdentifier fromRootURL:rootURL error:error];
attemptedAuthentication = YES;
} else {
if (success != NULL) {
@@ -399,7 +292,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 macOS 10.5 and is described at:
// The quarantine was introduced on OS X 10.5 and is described at:
//
// http://developer.apple.com/releasenotes/Carbon/RN-LaunchServices/index.html#apple_ref/doc/uid/TP40001369-DontLinkElementID_2
//
@@ -501,6 +394,11 @@ 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) {
@@ -516,11 +414,11 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
}
return NO;
}
NSError *executeError = nil;
if (![self _authorizeAndExecuteCommand:SUFileOpCopyCommand sourcePath:sourcePath destinationPath:destinationPath error:&executeError]) {
if (!AuthorizationExecuteWithPrivilegesAndWait(_auth, "/bin/cp", kAuthorizationFlagDefaults, (char *[]){ "-Rf", "--", sourcePath, destinationPath, NULL })) {
if (error != NULL) {
*error = executeError;
NSString *errorMessage = [NSString stringWithFormat:@"Failed to perform authenticated file copy for %@.", sourceURL.lastPathComponent];
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:errorMessage }];
}
return NO;
}
@@ -609,6 +507,10 @@ 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) {
@@ -624,12 +526,11 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
}
return NO;
}
NSError *executeError = nil;
if (![self _authorizeAndExecuteCommand:SUFileOpMoveCommand sourcePath:sourcePath destinationPath:destinationPath error:&executeError]) {
if (!AuthorizationExecuteWithPrivilegesAndWait(_auth, "/bin/mv", kAuthorizationFlagDefaults, (char *[]){ "-f", "--", sourcePath, destinationPath, NULL })) {
if (error != NULL) {
NSString *errorMessage = [NSString stringWithFormat:@"Failed to perform authorized file move for %@.", sourceURL.lastPathComponent];
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:errorMessage, NSUnderlyingErrorKey: executeError }];
NSString *errorMessage = [NSString stringWithFormat:@"Failed to perform authenticated file move for %@.", sourceURL.lastPathComponent];
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:errorMessage }];
}
return NO;
}
@@ -769,20 +670,21 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
}
return NO;
}
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] }];
}
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]) {
return NO;
}
NSError *executeError = nil;
BOOL success = [self _authorizeAndExecuteCommand:SUFileOpChangeOwnerAndGroupCommand sourcePath:targetPath destinationPath:matchPath error:&executeError];
BOOL success = AuthorizationExecuteWithPrivilegesAndWait(_auth, "/usr/sbin/chown", kAuthorizationFlagDefaults, (char *[]){ "-R", userAndGroup, targetPath, NULL });
if (!success && error != NULL) {
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 }];
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 }];
}
return success;
@@ -834,12 +736,15 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
}
return NO;
}
NSError *executeError = nil;
BOOL success = [self _authorizeAndExecuteCommand:SUFileOpUpdateModificationAndAccessTimeCommand sourcePath:path destinationPath:NULL error:&executeError];
if (![self _acquireAuthorizationWithError:error]) {
return NO;
}
BOOL success = AuthorizationExecuteWithPrivilegesAndWait(_auth, "/usr/bin/touch", kAuthorizationFlagDefaults, (char *[]){ "-h", "--", path, NULL });
if (!success && error != NULL) {
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 }];
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 }];
}
return success;
@@ -847,7 +752,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) {
@@ -884,16 +789,16 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
}
return NO;
}
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 }];
}
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 }];
}
return success;
}
@@ -915,7 +820,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
@@ -939,6 +844,10 @@ 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) {
@@ -946,46 +855,96 @@ 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], NSUnderlyingErrorKey: executeError }];
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to remove %@ with authentication.", url.path.lastPathComponent] }];
}
return success;
}
// Unlike other methods, authorization is required to execute this method successfully
- (BOOL)executePackageAtURL:(NSURL *)packageURL progressBlock:(void(^)(double))progressBlock error:(NSError * __autoreleasing *)error
- (BOOL)moveItemAtURLToTrash:(NSURL *)url error:(NSError *__autoreleasing *)error
{
if (![self _itemExistsAtURL:packageURL]) {
if (![self _itemExistsAtURL:url]) {
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] }];
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileNoSuchFileError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to move %@ to the trash because the file does not exist.", url.path.lastPathComponent] }];
}
return NO;
}
char path[PATH_MAX] = {0};
if (![packageURL.path getFileSystemRepresentation:path maxLength:sizeof(path)]) {
NSURL *trashURL = nil;
BOOL canUseNewTrashAPI = YES;
#if __MAC_OS_X_VERSION_MIN_REQUIRED < 1080
canUseNewTrashAPI = [SUOperatingSystem isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){10, 8, 0}];
if (!canUseNewTrashAPI) {
FSRef trashRef;
if (FSFindFolder(kUserDomain, kTrashFolderType, kDontCreateFolder, &trashRef) == noErr) {
trashURL = CFBridgingRelease(CFURLCreateFromFSRef(kCFAllocatorDefault, &trashRef));
}
}
#endif
if (canUseNewTrashAPI) {
trashURL = [_fileManager URLForDirectory:NSTrashDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
}
if (trashURL == nil) {
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] }];
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileNoSuchFileError userInfo:@{ NSLocalizedDescriptionKey: @"Failed to locate the user's trash folder." }];
}
return NO;
}
NSError *executeError = nil;
BOOL success = [self _authorizeAndExecuteCommand:SUFileOpInstallCommand sourcePath:path destinationPath:NULL lineCallback:^(NSString *line){
if ([line hasPrefix:@"installer:%"]) {
progressBlock([[line substringFromIndex:11] doubleValue]/100.0);
}
} error:&executeError];
if (!success && error != NULL) {
NSString* errorMessage = @"Failed to execute package installer.";
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{NSLocalizedDescriptionKey: errorMessage, NSUnderlyingErrorKey: executeError}];
// In the rare worst case scenario, our temporary directory will be labeled incomplete and be in the user's trash directory,
// indicating that whatever inside of there is not yet completely moved.
// Regardless, we want the item to be in our Volume before we try moving it to the trash
NSString *preferredName = [url.lastPathComponent.stringByDeletingPathExtension stringByAppendingString:@" (Incomplete Files)"];
NSURL *tempDirectory = [self makeTemporaryDirectoryWithPreferredName:preferredName appropriateForDirectoryURL:trashURL error:error];
if (tempDirectory == nil) {
return NO;
}
NSString *urlLastPathComponent = url.lastPathComponent;
NSURL *tempItemURL = [tempDirectory URLByAppendingPathComponent:urlLastPathComponent];
if (![self moveItemAtURL:url toURL:tempItemURL error:error]) {
// If we can't move the item at url, just remove it completely; chances are it's not going to be missed
[self removeItemAtURL:url error:NULL];
[self removeItemAtURL:tempDirectory error:NULL];
return NO;
}
if (![self changeOwnerAndGroupOfItemAtRootURL:tempItemURL toMatchURL:trashURL error:error]) {
// Removing the item inside of the temp directory is better than trying to move the item to the trash with incorrect ownership
[self removeItemAtURL:tempDirectory error:NULL];
return NO;
}
// If we get here, we should be able to trash the item normally without authentication
BOOL success = NO;
#if __MAC_OS_X_VERSION_MIN_REQUIRED < 1080
if (!canUseNewTrashAPI) {
NSString *tempParentPath = tempItemURL.URLByDeletingLastPathComponent.path;
success = [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:tempParentPath destination:@"" files:@[tempItemURL.lastPathComponent] tag:NULL];
if (!success && error != NULL) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileNoSuchFileError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to move file %@ into the trash.", tempItemURL.lastPathComponent] }];
}
}
#endif
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;
}
}
[self removeItemAtURL:tempDirectory error:NULL];
return success;
}
+10 -8
View File
@@ -11,7 +11,7 @@
A guided installation allows Sparkle to download and install a package (pkg) or multi-package (mpkg) without user interaction.
The installer package is installed using macOS's built-in command line installer, `/usr/sbin/installer`. No installation interface is shown to the user.
The installer package is installed using Mac OS X's built-in command line installer, `/usr/sbin/installer`. No installation interface is shown to the user.
A guided installation can be started by applications other than the application being replaced. This is particularly useful where helper applications or agents are used.
@@ -19,15 +19,17 @@ A guided installation can be started by applications other than the application
- Replace the use of `AuthorizationExecuteWithPrivilegesAndWait`. This method remains because it is well supported and tested. Ideally a helper tool or XPC would be used.
*/
#ifndef SUGUIDEDPACKAGEINSTALLER_H
#define SUGUIDEDPACKAGEINSTALLER_H
#import <Foundation/Foundation.h>
#import "SUInstallerProtocol.h"
#import "Sparkle.h"
#import "SUInstaller.h"
NS_ASSUME_NONNULL_BEGIN
@interface SUGuidedPackageInstaller : NSObject <SUInstallerProtocol>
- (instancetype)initWithPackagePath:(NSString *)packagePath installationPath:(NSString *)installationPath fileOperationToolPath:(NSString *)fileOperationToolPath;
@interface SUGuidedPackageInstaller : SUInstaller
/*! Perform the guided installation */
+ (void)performInstallationToPath:(NSString *)path fromPath:(NSString *)installerGuide host:(SUHost *)host versionComparator:(id<SUVersionComparison>)comparator completionHandler:(void (^)(NSError *))completionHandler;
@end
NS_ASSUME_NONNULL_END
#endif
+120 -33
View File
@@ -6,52 +6,139 @@
// Copyright 2010 Dragon Systems Software Limited. All rights reserved.
//
#import <sys/stat.h>
#import <Security/Security.h>
#import "SUGuidedPackageInstaller.h"
#import "SUFileManager.h"
static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authorization, const char* executablePath, AuthorizationFlags options, char* const* arguments)
{
sig_t oldSigChildHandler = signal(SIGCHLD, SIG_DFL);
BOOL returnValue = YES;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
/* AuthorizationExecuteWithPrivileges used to support 10.4+; should be replaced with XPC or external process */
if (AuthorizationExecuteWithPrivileges(authorization, executablePath, options, arguments, NULL) == errAuthorizationSuccess)
#pragma clang diagnostic pop
{
int status = 0;
pid_t pid = wait(&status);
if (pid == -1 || !WIFEXITED(status) || WEXITSTATUS(status) != 0)
returnValue = NO;
}
else
returnValue = NO;
signal(SIGCHLD, oldSigChildHandler);
return returnValue;
}
#include "AppKitPrevention.h"
@implementation SUGuidedPackageInstaller (SUGuidedPackageInstallerAuthentication)
@interface SUGuidedPackageInstaller ()
@property (nonatomic, readonly, copy) NSString *packagePath;
@property (nonatomic, readonly, copy) NSString *installationPath;
@property (nonatomic, readonly, copy) NSString *fileOperationToolPath;
+ (AuthorizationRef)authorizationForExecutable:(NSString*)executablePath
{
SUParameterAssert(executablePath);
// Get authorization using advice in Apple's Technical Q&A1172
// ...create authorization without specific rights
AuthorizationRef auth = NULL;
OSStatus validAuth = AuthorizationCreate(NULL,
kAuthorizationEmptyEnvironment,
kAuthorizationFlagDefaults,
&auth);
// ...then extend authorization with desired rights
if ((validAuth == errAuthorizationSuccess) &&
(auth != NULL))
{
char executableFileSystemRepresentation[PATH_MAX];
[executablePath getFileSystemRepresentation:executableFileSystemRepresentation maxLength:sizeof(executableFileSystemRepresentation)];
// Prepare a right allowing script to execute with privileges
AuthorizationItem right = {
.name = kAuthorizationRightExecute,
.value = executableFileSystemRepresentation,
.valueLength = strlen(executableFileSystemRepresentation),
};
// Package up the single right
AuthorizationRights rights;
memset(&rights,0,sizeof(rights));
rights.count = 1;
rights.items = &right;
// Extend rights to run script
validAuth = AuthorizationCopyRights(auth,
&rights,
kAuthorizationEmptyEnvironment,
(AuthorizationFlags)
(kAuthorizationFlagPreAuthorize |
kAuthorizationFlagExtendRights |
kAuthorizationFlagInteractionAllowed),
NULL);
if (validAuth != errAuthorizationSuccess)
{
// Error, clean up authorization
(void) AuthorizationFree(auth,kAuthorizationFlagDefaults);
auth = NULL;
}
}
return auth;
}
@end
@implementation SUGuidedPackageInstaller
@synthesize packagePath = _packagePath;
@synthesize installationPath = _installationPath;
@synthesize fileOperationToolPath = _fileOperationToolPath;
- (instancetype)initWithPackagePath:(NSString *)packagePath installationPath:(NSString *)installationPath fileOperationToolPath:(NSString *)fileOperationToolPath
+ (void)performInstallationToPath:(NSString *)destinationPath fromPath:(NSString *)packagePath host:(SUHost *)__unused host versionComparator:(id<SUVersionComparison>)__unused comparator completionHandler:(void (^)(NSError *))completionHandler
{
self = [super init];
if (self != nil) {
_packagePath = [packagePath copy];
_installationPath = [installationPath copy];
_fileOperationToolPath = [fileOperationToolPath copy];
}
return self;
}
SUParameterAssert(packagePath);
- (BOOL)performInitialInstallation:(NSError * __autoreleasing *)__unused error
{
return YES;
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
- (BOOL)performFinalInstallationProgressBlock:(nullable void(^)(double))progressBlock error:(NSError * __autoreleasing *)error
{
SUFileManager *fileManager = [SUFileManager fileManagerWithAuthorizationToolPath:self.fileOperationToolPath];
return [fileManager executePackageAtURL:[NSURL fileURLWithPath:self.packagePath] progressBlock:progressBlock error:error];
}
// Preflight
NSString* installerPath = @"/usr/sbin/installer"; // Mac OS X 10.2+ command line installer tool
NSError* error = nil;
- (BOOL)canInstallSilently
{
return YES;
// Create authorization for installer executable
BOOL validInstallation = NO;
AuthorizationRef auth = [self authorizationForExecutable:installerPath];
if (auth != NULL)
{
char pathBuffer[PATH_MAX] = {0};
[packagePath getFileSystemRepresentation:pathBuffer maxLength:sizeof(pathBuffer)];
// Permission was granted to execute the installer with privileges
char * const arguments[] = {
"-pkg",
pathBuffer,
"-target",
"/",
NULL
};
validInstallation = AuthorizationExecuteWithPrivilegesAndWait(auth,
[installerPath fileSystemRepresentation],
kAuthorizationFlagDefaults,
arguments);
// TODO: wait for communications pipe to close via fileno & CFSocketCreateWithNative
AuthorizationFree(auth,kAuthorizationFlagDefaults);
}
else
{
NSString* errorMessage = [NSString stringWithFormat:@"Sparkle Updater: Script authorization denied."];
error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:[NSDictionary dictionaryWithObject:errorMessage forKey:NSLocalizedDescriptionKey]];
}
dispatch_async(dispatch_get_main_queue(), ^{
[self finishInstallationToPath:destinationPath
withResult:validInstallation
error:error
completionHandler:completionHandler];
});
});
}
@end
+17 -1
View File
@@ -6,6 +6,18 @@
//
#import <Foundation/Foundation.h>
#import "SUUpdater.h"
#import "SUAppcast.h"
#import "SUAppcastItem.h"
#import "SUVersionComparisonProtocol.h"
#if __MAC_OS_X_VERSION_MAX_ALLOWED < 101000
typedef struct {
NSInteger majorVersion;
NSInteger minorVersion;
NSInteger patchVersion;
} NSOperatingSystemVersion;
#endif
@interface SUHost : NSObject
@@ -13,12 +25,16 @@
- (instancetype)initWithBundle:(NSBundle *)aBundle;
@property (readonly, copy) NSString *bundlePath;
@property (readonly) BOOL allowsAutomaticUpdates;
@property (readonly, copy) NSString *installationPath;
@property (readonly, copy) NSString *name;
@property (readonly, copy) NSString *version;
@property (readonly, copy) NSString *displayVersion;
@property (readonly, copy) NSImage *icon;
@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;
- (BOOL)boolForInfoDictionaryKey:(NSString *)key;
+76 -46
View File
@@ -8,22 +8,19 @@
#import "SUHost.h"
#import "SUConstants.h"
#import "SUSystemProfiler.h"
#include <sys/mount.h> // For statfs for isRunningOnReadOnlyVolume
#import "SULog.h"
#include "AppKitPrevention.h"
// This class should not rely on AppKit and should also be process independent
// For example, it should not have code that tests writabilty to somewhere on disk,
// as that may depend on the privileges of the process owner. Or code that depends on
// if the process is sandboxed or not; eg: finding the user's caches directory. Or code that depends
// on compilation flags and if other files exist relative to the host bundle.
#if __MAC_OS_X_VERSION_MAX_ALLOWED < 101000
@interface NSProcessInfo ()
- (NSOperatingSystemVersion)operatingSystemVersion;
@end
#endif
@interface SUHost ()
@property (strong, readwrite) NSBundle *bundle;
@property (nonatomic, readonly) BOOL isMainBundle;
@property (copy) NSString *defaultsDomain;
@property (assign) BOOL usesStandardUserDefaults;
@@ -32,7 +29,6 @@
@implementation SUHost
@synthesize bundle;
@synthesize isMainBundle = _isMainBundle;
@synthesize defaultsDomain;
@synthesize usesStandardUserDefaults;
@@ -40,15 +36,13 @@
{
if ((self = [super init]))
{
NSParameterAssert(aBundle);
SUParameterAssert(aBundle);
self.bundle = aBundle;
if (![self.bundle bundleIdentifier]) {
SULog(SULogLevelError, @"Error: the bundle being updated at %@ has no %@! This will cause preference read/write to not work properly.", self.bundle, kCFBundleIdentifierKey);
SULog(@"Error: the bundle being updated at %@ has no %@! This will cause preference read/write to not work properly.", self.bundle, kCFBundleIdentifierKey);
}
_isMainBundle = [aBundle isEqualTo:[NSBundle mainBundle]];
self.defaultsDomain = [self objectForInfoDictionaryKey:SUDefaultsDomainKey];
self.defaultsDomain = [self.bundle objectForInfoDictionaryKey:SUDefaultsDomainKey];
if (!self.defaultsDomain) {
self.defaultsDomain = [self.bundle bundleIdentifier];
}
@@ -61,13 +55,41 @@
}
- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], [self bundlePath]]; }
- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@, %@>", [self class], [self bundlePath], [self installationPath]]; }
- (NSString *)bundlePath
{
return [self.bundle bundlePath];
}
- (BOOL)allowsAutomaticUpdates
{
// Does the developer want us to disable automatic updates?
NSNumber *developerAllowsAutomaticUpdates = [self objectForInfoDictionaryKey:SUAllowsAutomaticUpdatesKey];
if (developerAllowsAutomaticUpdates != nil && !developerAllowsAutomaticUpdates.boolValue) {
return NO;
}
// Can we automatically update in the background without bugging the user (e.g, with a administrator password prompt)?
// Note it's very well possible to have the bundle be writable but not be able to write into the parent directory
// And if the bundle isn't writable, but we can write into the parent directory, we will still need to authorize to replace it
NSString *bundlePath = [self bundlePath];
return [[NSFileManager defaultManager] isWritableFileAtPath:bundlePath.stringByDeletingLastPathComponent] && [[NSFileManager defaultManager] isWritableFileAtPath:bundlePath];
}
- (NSString *)installationPath
{
if (SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME) {
// We'll install to "#{CFBundleName}.app", but only if that path doesn't already exist. If we're "Foo 4.2.app," and there's a "Foo.app" in this directory, we don't want to overwrite it! But if there's no "Foo.app," we'll take that name.
NSString *normalizedAppPath = [[[self.bundle bundlePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", [self.bundle objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleNameKey], [[self.bundle bundlePath] pathExtension]]];
if (![[NSFileManager defaultManager] fileExistsAtPath:normalizedAppPath]) {
return normalizedAppPath;
}
}
return [self.bundle bundlePath];
}
- (NSString *__nonnull)name
{
NSString *name;
@@ -76,18 +98,18 @@
name = [self objectForInfoDictionaryKey:@"SUBundleName"];
if (name && name.length > 0) return name;
name = [self objectForInfoDictionaryKey:@"CFBundleDisplayName"];
name = [self.bundle objectForInfoDictionaryKey:@"CFBundleDisplayName"];
if (name && name.length > 0) return name;
name = [self objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleNameKey];
if (name && name.length > 0) return name;
return [[[NSFileManager defaultManager] displayNameAtPath:[self bundlePath]] stringByDeletingPathExtension];
return [[[NSFileManager defaultManager] displayNameAtPath:[self.bundle bundlePath]] stringByDeletingPathExtension];
}
- (NSString *__nonnull)version
{
NSString *version = [self objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleVersionKey];
NSString *version = [self.bundle objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleVersionKey];
if (!version || [version isEqualToString:@""])
[NSException raise:@"SUNoVersionException" format:@"This host (%@) has no %@! This attribute is required.", [self bundlePath], (__bridge NSString *)kCFBundleVersionKey];
return version;
@@ -95,13 +117,36 @@
- (NSString *__nonnull)displayVersion
{
NSString *shortVersionString = [self objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
NSString *shortVersionString = [self.bundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
if (shortVersionString)
return shortVersionString;
else
return [self version]; // Fall back on the normal version string.
}
- (NSImage *__nonnull)icon
{
// 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
// the icon for the bundle. The filename you specify does not need to include the .icns
// extension, although it may."
//
// However, if it *does* include the '.icns' the above method fails (tested on OS X 10.3.9) so we'll also try:
if (!iconPath) {
iconPath = [self.bundle pathForResource:[self.bundle objectForInfoDictionaryKey:@"CFBundleIconFile"] ofType:nil];
}
NSImage *icon = [[NSImage alloc] initWithContentsOfFile:iconPath];
// Use a default icon if none is defined.
if (!icon) {
BOOL isMainBundle = (self.bundle == [NSBundle mainBundle]);
NSString *fileType = isMainBundle ? (__bridge NSString *)kUTTypeApplication : (__bridge NSString *)kUTTypeBundle;
icon = [[NSWorkspace sharedWorkspace] iconForFileType:fileType];
}
return icon;
}
- (BOOL)isRunningOnReadOnlyVolume
{
struct statfs statfs_info;
@@ -109,16 +154,21 @@
return (statfs_info.f_flags & MNT_RDONLY) != 0;
}
- (BOOL)isBackgroundApplication
{
return ([[NSApplication sharedApplication] activationPolicy] == NSApplicationActivationPolicyAccessory);
}
- (NSString *__nullable)publicDSAKey
{
// Maybe the key is just a string in the Info.plist.
NSString *key = [self objectForInfoDictionaryKey:SUPublicDSAKeyKey];
NSString *key = [self.bundle objectForInfoDictionaryKey:SUPublicDSAKeyKey];
if (key) {
return key;
}
// More likely, we've got a reference to a Resources file by filename:
NSString *keyFilename = [self publicDSAKeyFileKey];
NSString *keyFilename = [self objectForInfoDictionaryKey:SUPublicDSAKeyFileKey];
if (!keyFilename) {
return nil;
}
@@ -127,36 +177,17 @@
if (!keyPath) {
return nil;
}
NSError *error = nil;
key = [NSString stringWithContentsOfFile:keyPath encoding:NSASCIIStringEncoding error:&error];
if (error) {
SULog(SULogLevelError, @"Error loading %@: %@", keyPath, error);
}
return key;
return [NSString stringWithContentsOfFile:keyPath encoding:NSASCIIStringEncoding error:nil];
}
- (NSString * __nullable)publicDSAKeyFileKey
- (NSArray *)systemProfile
{
return [self objectForInfoDictionaryKey:SUPublicDSAKeyFileKey];
return [[SUSystemProfiler sharedSystemProfiler] systemProfileArrayForHost:self];
}
- (id)objectForInfoDictionaryKey:(NSString *)key
{
if (self.isMainBundle) {
// Common fast path - if we're updating the main bundle, that means our updater and host bundle's lifetime is the same
// If the bundle happens to be updated or change, that means our updater process needs to be terminated first to do it safely
// Thus we can rely on the cached Info dictionary
return [self.bundle objectForInfoDictionaryKey:key];
} else {
// Slow path - if we're updating another bundle, we should read in the most up to date Info dictionary because
// the bundle can be replaced externally or even by us.
// This is the easiest way to read the Info dictionary values *correctly* despite some performance loss.
// A mutable method to reload the Info dictionary at certain points and have it cached at other points is challenging to do correctly.
CFDictionaryRef cfInfoDictionary = CFBundleCopyInfoDictionaryInDirectory((CFURLRef)self.bundle.bundleURL);
NSDictionary *infoDictionary = CFBridgingRelease(cfInfoDictionary);
return [infoDictionary objectForKey:key];
}
return [self.bundle objectForInfoDictionaryKey:key];
}
- (BOOL)boolForInfoDictionaryKey:(NSString *)key
@@ -181,7 +212,6 @@
return CFBridgingRelease(obj);
}
// Note this handles nil being passed for defaultName, in which case the user default will be removed
- (void)setObject:(id)value forUserDefaultsKey:(NSString *)defaultName
{
if (self.usesStandardUserDefaults)
+8 -10
View File
@@ -6,21 +6,19 @@
// Copyright 2008 Andy Matuschak. All rights reserved.
//
#import <Foundation/Foundation.h>
#ifndef SUINSTALLER_H
#define SUINSTALLER_H
#import <Cocoa/Cocoa.h>
#import "SUVersionComparisonProtocol.h"
NS_ASSUME_NONNULL_BEGIN
@class SUHost;
@protocol SUInstallerProtocol;
@interface SUInstaller : NSObject
+ (nullable id<SUInstallerProtocol>)installerForHost:(SUHost *)host fileOperationToolPath:(NSString *)fileOperationToolPath updateDirectory:(NSString *)updateDirectory error:(NSError **)error;
+ (nullable NSString *)installSourcePathInUpdateFolder:(NSString *)inUpdateFolder forHost:(SUHost *)host isPackage:(BOOL *)isPackagePtr isGuided:(nullable BOOL *)isGuidedPtr;
+ (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<SUVersionComparison>)comparator completionHandler:(void (^)(NSError *))completionHandler;
+ (void)finishInstallationToPath:(NSString *)installationPath withResult:(BOOL)result error:(NSError *)error completionHandler:(void (^)(NSError *))completionHandler;
@end
NS_ASSUME_NONNULL_END
#endif
+52 -53
View File
@@ -7,16 +7,12 @@
//
#import "SUInstaller.h"
#import "SUInstallerProtocol.h"
#import "SUPlainInstaller.h"
#import "SUPackageInstaller.h"
#import "SUGuidedPackageInstaller.h"
#import "SUHost.h"
#import "SUConstants.h"
#import "SULog.h"
#import "SUErrors.h"
#include "AppKitPrevention.h"
@implementation SUInstaller
@@ -29,10 +25,10 @@
return aliasFlag.boolValue && directoryFlag.boolValue;
}
+ (nullable NSString *)installSourcePathInUpdateFolder:(NSString *)inUpdateFolder forHost:(SUHost *)host isPackage:(BOOL *)isPackagePtr isGuided:(nullable BOOL *)isGuidedPtr
+ (NSString *)installSourcePathInUpdateFolder:(NSString *)inUpdateFolder forHost:(SUHost *)host isPackage:(BOOL *)isPackagePtr isGuided:(BOOL *)isGuidedPtr
{
NSParameterAssert(inUpdateFolder);
NSParameterAssert(host);
SUParameterAssert(inUpdateFolder);
SUParameterAssert(host);
// Search subdirectories for the application
NSString *currentFile,
@@ -40,7 +36,7 @@
*bundleFileName = [[host bundlePath] lastPathComponent],
*alternateBundleFileName = [[host name] stringByAppendingPathExtension:[[host bundlePath] pathExtension]];
BOOL isPackage = NO;
BOOL isGuided = YES;
BOOL isGuided = NO;
NSString *fallbackPackagePath = nil;
NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath:inUpdateFolder];
NSString *bundleFileNameNoExtension = [bundleFileName stringByDeletingPathExtension];
@@ -90,12 +86,9 @@
}
if (isPackage) {
// Guided (or now "normal") installs used to be opt-in (i.e, Sparkle would detect foo.sparkle_guided.pkg or foo.sparkle_guided.mpkg),
// but to get an interactive (or "unguided") install, the developer now must opt-out of guided installations.
// foo.app -> foo.sparkle_interactive.pkg or foo.sparkle_interactive.mpkg
if ([[[newAppDownloadPath stringByDeletingPathExtension] pathExtension] isEqualToString:@"sparkle_interactive"]) {
isGuided = NO;
// foo.app -> foo.sparkle_guided.pkg or foo.sparkle_guided.mpkg
if ([[[newAppDownloadPath stringByDeletingPathExtension] pathExtension] isEqualToString:@"sparkle_guided"]) {
isGuided = YES;
}
}
@@ -105,59 +98,65 @@
*isGuidedPtr = isGuided;
if (!newAppDownloadPath) {
SULog(SULogLevelError, @"Searched %@ for %@.(app|pkg)", inUpdateFolder, bundleFileNameNoExtension);
SULog(@"Searched %@ for %@.(app|pkg)", inUpdateFolder, bundleFileNameNoExtension);
}
return newAppDownloadPath;
}
+ (nullable id<SUInstallerProtocol>)installerForHost:(SUHost *)host fileOperationToolPath:(NSString *)fileOperationToolPath updateDirectory:(NSString *)updateDirectory error:(NSError * __autoreleasing *)error
+ (void)installFromUpdateFolder:(NSString *)inUpdateFolder overHost:(SUHost *)host installationPath:(NSString *)installationPath versionComparator:(id<SUVersionComparison>)comparator completionHandler:(void (^)(NSError *))completionHandler
{
BOOL isPackage = NO;
BOOL isGuided = NO;
NSString *newDownloadPath = [self installSourcePathInUpdateFolder:updateDirectory forHost:host isPackage:&isPackage isGuided:&isGuided];
if (newDownloadPath == nil) {
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingUpdateError userInfo:@{ NSLocalizedDescriptionKey: @"Couldn't find an appropriate update in the downloaded package." }];
}
return nil;
}
id <SUInstallerProtocol> installer;
if (isPackage && isGuided) {
installer = [[SUGuidedPackageInstaller alloc] initWithPackagePath:newDownloadPath installationPath:host.bundlePath fileOperationToolPath:fileOperationToolPath];
} else if (isPackage) {
installer = [[SUPackageInstaller alloc] initWithPackagePath:newDownloadPath installationPath:host.bundlePath];
NSString *newAppDownloadPath = [self installSourcePathInUpdateFolder:inUpdateFolder forHost:host isPackage:&isPackage isGuided:&isGuided];
if (newAppDownloadPath == nil) {
[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 {
NSString *normalizedInstallationPath = nil;
if (SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME) {
normalizedInstallationPath = [self normalizedInstallationPathForHost:host];
}
// If we have a normalized path, we'll install to "#{CFBundleName}.app", but only if that path doesn't already exist. If we're "Foo 4.2.app," and there's a "Foo.app" in this directory, we don't want to overwrite it! But if there's no "Foo.app," we'll take that name.
// Otherwise if there's no normalized path (the more likely case), we'll just use the host bundle's path
NSString *installationPath;
if (normalizedInstallationPath != nil && ![[NSFileManager defaultManager] fileExistsAtPath:normalizedInstallationPath]) {
installationPath = normalizedInstallationPath;
if (isPackage && isGuided) {
[SUGuidedPackageInstaller performInstallationToPath:installationPath fromPath:newAppDownloadPath host:host versionComparator:comparator completionHandler:completionHandler];
} else if (isPackage) {
[SUPackageInstaller performInstallationToPath:installationPath fromPath:newAppDownloadPath host:host versionComparator:comparator completionHandler:completionHandler];
} else {
installationPath = host.bundlePath;
[SUPlainInstaller performInstallationToPath:installationPath fromPath:newAppDownloadPath host:host versionComparator:comparator completionHandler:completionHandler];
}
installer = [[SUPlainInstaller alloc] initWithHost:host bundlePath:newDownloadPath installationPath:installationPath fileOperationToolPath:fileOperationToolPath];
}
return installer;
}
+ (NSString *)normalizedInstallationPathForHost:(SUHost *)host
+ (void)mdimportInstallationPath:(NSString *)installationPath
{
NSBundle *bundle = host.bundle;
assert(bundle != nil);
NSString *normalizedAppPath = [[[bundle bundlePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", [host objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleNameKey], [[bundle bundlePath] pathExtension]]];
// *** GETS CALLED ON NON-MAIN THREAD!
// Roundtrip string through fileSystemRepresentation to ensure it uses filesystem's Unicode normalization
// rather than arbitrary Unicode form from Info.plist - #1017
return [NSString stringWithUTF8String:[normalizedAppPath fileSystemRepresentation]];
SULog(@"mdimporting");
NSTask *mdimport = [[NSTask alloc] init];
[mdimport setLaunchPath:@"/usr/bin/mdimport"];
[mdimport setArguments:@[installationPath]];
@try {
[mdimport launch];
[mdimport waitUntilExit];
}
@catch (NSException *launchException)
{
// No big deal.
SULog(@"Error: %@", [launchException description]);
}
}
+ (void)finishInstallationToPath:(NSString *)installationPath withResult:(BOOL)result error:(NSError *)error completionHandler:(void (^)(NSError *))completionHandler
{
if (result) {
[self mdimportInstallationPath:installationPath];
dispatch_async(dispatch_get_main_queue(), ^{
completionHandler(nil);
});
} else {
if (!error) {
error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:nil];
}
dispatch_async(dispatch_get_main_queue(), ^{
completionHandler(error);
});
}
}
@end
-36
View File
@@ -1,36 +0,0 @@
//
// SUInstallerProtocol.h
// Sparkle
//
// Created by Mayur Pawashe on 12/26/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@protocol SUInstallerProtocol <NSObject>
// Any installation work can be done prior to user application being terminated and relaunched
// Currently this is invoked after the user application is terminated, but this may change in the future.
// No UI should occur during this stage (i.e, do not show package installer apps, etc..)
// Should be able to be called from non-main thread
- (BOOL)performInitialInstallation:(NSError **)error;
// Any installation work after the user application has been terminated. This is where the final installation work can be done.
// After this stage is done, the user application may be relaunched.
// Should be able to be called from non-main thread
- (BOOL)performFinalInstallationProgressBlock:(nullable void(^)(double))cb error:(NSError **)error;
// Indicates whether or not this installer can install the update silently in the background, without hindering the user
// Should be thread safe
- (BOOL)canInstallSilently;
// The destination and installation path of the bundle being updated
// Should be thread safe
- (NSString *)installationPath;
@end
NS_ASSUME_NONNULL_END
-16
View File
@@ -1,16 +0,0 @@
//
// SULocalizations.h
// Sparkle
//
// Created by Mayur Pawashe on 2/28/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#ifndef SULocalizations_h
#define SULocalizations_h
#import "SUConstants.h"
#define SULocalizedString(key, comment) NSLocalizedStringFromTableInBundle(key, @"Sparkle", (NSBundle * _Nonnull)([NSBundle bundleWithIdentifier:SUBundleIdentifier] ? [NSBundle bundleWithIdentifier:SUBundleIdentifier] : [NSBundle mainBundle]), comment)
#endif /* SULocalizations_h */
+23 -20
View File
@@ -1,29 +1,32 @@
//
// SULog.h
// Sparkle
//
// Created by Mayur Pawashe on 5/18/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
/*
* SULog.h
* EyeTV
*
* Created by Uli Kusterer on 12/03/2009.
* Copyright 2008 Elgato Systems GmbH. All rights reserved.
*
*/
/*
Log output for troubleshooting Sparkle failures on end-user machines.
Your tech support will hug you if you tell them about this.
*/
#ifndef SULOG_H
#define SULOG_H
// -----------------------------------------------------------------------------
// Headers:
// -----------------------------------------------------------------------------
#include <Foundation/Foundation.h>
typedef NS_ENUM(uint8_t, SULogLevel) {
// This level is for information that *might* result a failure
// For now until other levels are added, this may serve as a level for other information as well
SULogLevelDefault,
// This level is for errors that occurred
SULogLevelError
};
// Logging utlity function that is thread-safe
// On 10.12 or later this uses os_log
// Otherwise on older systems this uses ASL
// For debugging command line tools, you may have to use Console.app or log(1) to view log messages
// Try to keep log messages as compact/short as possible
void SULog(SULogLevel level, NSString *format, ...) NS_FORMAT_FUNCTION(2, 3);
// -----------------------------------------------------------------------------
// Prototypes:
// -----------------------------------------------------------------------------
void SUClearLog(void);
void SULog(NSString *format, ...) NS_FORMAT_FUNCTION(1, 2);
#endif
+62 -97
View File
@@ -1,113 +1,78 @@
//
// SULog.m
// Sparkle
//
// Created by Mayur Pawashe on 5/18/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
/*
* SULog.m
* EyeTV
*
* Created by Uli Kusterer on 12/03/2009.
* Copyright 2009 Elgato Systems GmbH. All rights reserved.
*
*/
// -----------------------------------------------------------------------------
// Headers:
// -----------------------------------------------------------------------------
#include "SULog.h"
#include <asl.h>
#include <os/log.h>
#import "SUOperatingSystem.h"
// For converting constants to string literals using the preprocessor
#define STRINGIFY(x) #x
#define TO_STRING(x) STRINGIFY(x)
#include "AppKitPrevention.h"
// -----------------------------------------------------------------------------
// Constants:
// -----------------------------------------------------------------------------
void SULog(SULogLevel level, NSString *format, ...)
static NSString *const SULogFilePath = @"~/Library/Logs/SparkleUpdateLog.log";
// -----------------------------------------------------------------------------
// SUClearLog:
// Erase the log at the start of an update. We don't want to litter the
// user's hard disk with logging data that's mostly unused, so each app
// should clear the log before it starts updating, so only the most recent
// update is kept around.
//
// TAKES:
// sender - Object that sent this message, typically of type X.
// -----------------------------------------------------------------------------
void SUClearLog(void)
{
static aslclient client;
static dispatch_queue_t queue;
static dispatch_once_t onceToken;
FILE *logfile = fopen([[SULogFilePath stringByExpandingTildeInPath] fileSystemRepresentation], "w");
if (logfile) {
fclose(logfile);
SULog(@"===== %@ =====", [[NSFileManager defaultManager] displayNameAtPath:[[NSBundle mainBundle] bundlePath]]);
}
}
static os_log_t logger;
static BOOL hasOSLogging;
dispatch_once(&onceToken, ^{
NSBundle *mainBundle = [NSBundle mainBundle];
// -----------------------------------------------------------------------------
// SULog:
// Like NSLog, but logs to one specific log file. Each line is prefixed
// with the current date and time, to help in regressing issues.
//
// TAKES:
// format - NSLog/printf-style format string.
// ... - More parameters depending on format string's contents.
// -----------------------------------------------------------------------------
hasOSLogging = [SUOperatingSystem isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){10, 12, 0}];
if (hasOSLogging) {
const char *subsystem = SPARKLE_BUNDLE_IDENTIFIER;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpartial-availability"
// This creates a thread-safe object
logger = os_log_create(subsystem, "Sparkle");
#pragma clang diagnostic pop
} else {
uint32_t options = ASL_OPT_NO_DELAY;
// Act the same way os_log() does; don't log to stderr if a terminal device is attached
if (!isatty(STDERR_FILENO)) {
options |= ASL_OPT_STDERR;
}
NSString *displayName = [[NSFileManager defaultManager] displayNameAtPath:mainBundle.bundlePath];
client = asl_open([displayName stringByAppendingString:@" [Sparkle]"].UTF8String, SPARKLE_BUNDLE_IDENTIFIER, options);
queue = dispatch_queue_create(NULL, DISPATCH_QUEUE_SERIAL);
}
});
if (!hasOSLogging && client == NULL) {
return;
void SULog(NSString *format, ...)
{
static BOOL loggedYet = NO;
if (!loggedYet) {
loggedYet = YES;
SUClearLog();
}
va_list ap;
va_start(ap, format);
NSString *logMessage = [[NSString alloc] initWithFormat:format arguments:ap];
va_end(ap);
NSString *theStr = [[NSString alloc] initWithFormat:format arguments:ap];
NSLog(@"Sparkle: %@", theStr);
// Use os_log if available (on 10.12+)
if (hasOSLogging) {
// We'll make all of our messages formatted as public; just don't log sensitive information.
// Note we don't take advantage of info like the source line number because we wrap this macro inside our own function
// And we don't really leverage of os_log's deferred formatting processing because we format the string before passing it in
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpartial-availability"
switch (level) {
case SULogLevelDefault:
// See docs for OS_LOG_TYPE_DEFAULT
// By default, OS_LOG_TYPE_DEFAULT seems to be more noticable than OS_LOG_TYPE_INFO
os_log(logger, "%{public}@", logMessage);
break;
case SULogLevelError:
// See docs for OS_LOG_TYPE_ERROR
os_log_error(logger, "%{public}@", logMessage);
break;
}
#pragma clang diagnostic pop
return;
FILE *logfile = fopen([[SULogFilePath stringByExpandingTildeInPath] fileSystemRepresentation], "a");
if (logfile) {
theStr = [NSString stringWithFormat:@"%@: %@\n", [NSDate date], theStr];
NSData *theData = [theStr dataUsingEncoding:NSUTF8StringEncoding];
fwrite([theData bytes], 1, [theData length], logfile);
fclose(logfile);
}
// Otherwise use ASL
// Make sure we do not async, because if we async, the log may not be delivered deterministically
dispatch_sync(queue, ^{
aslmsg message = asl_new(ASL_TYPE_MSG);
if (message == NULL) {
return;
}
if (asl_set(message, ASL_KEY_MSG, logMessage.UTF8String) != 0) {
return;
}
int levelSetResult;
switch (level) {
case SULogLevelDefault:
// Just use one level below the error level
levelSetResult = asl_set(message, ASL_KEY_LEVEL, TO_STRING(ASL_LEVEL_WARNING));
break;
case SULogLevelError:
levelSetResult = asl_set(message, ASL_KEY_LEVEL, TO_STRING(ASL_LEVEL_ERR));
break;
}
if (levelSetResult != 0) {
return;
}
asl_send(client, message);
});
va_end(ap);
}
-8
View File
@@ -7,14 +7,6 @@
#import <Foundation/Foundation.h>
#if __MAC_OS_X_VERSION_MAX_ALLOWED < 101000
typedef struct {
NSInteger majorVersion;
NSInteger minorVersion;
NSInteger patchVersion;
} NSOperatingSystemVersion;
#endif
@interface SUOperatingSystem : NSObject
+ (NSOperatingSystemVersion)operatingSystemVersion;
+1 -12
View File
@@ -7,15 +7,6 @@
#import "SUOperatingSystem.h"
#include "AppKitPrevention.h"
#if __MAC_OS_X_VERSION_MAX_ALLOWED < 101000
@interface NSProcessInfo ()
- (NSOperatingSystemVersion)operatingSystemVersion;
@end
#endif
@implementation SUOperatingSystem
+ (NSOperatingSystemVersion)operatingSystemVersion
@@ -29,9 +20,7 @@
{
NSOperatingSystemVersion version = { 0, 0, 0 };
NSURL *coreServices = [[NSFileManager defaultManager] URLForDirectory:NSCoreServiceDirectory inDomain:NSSystemDomainMask appropriateForURL:nil create:NO error:nil];
NSURL *url = [coreServices URLByAppendingPathComponent:@"SystemVersion.plist"];
assert(url != nil);
NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfURL:url];
NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfURL:[coreServices URLByAppendingPathComponent:@"SystemVersion.plist"]];
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;
+10 -6
View File
@@ -6,15 +6,19 @@
// Copyright 2008 Andy Matuschak. All rights reserved.
//
#ifndef SUPACKAGEINSTALLER_H
#define SUPACKAGEINSTALLER_H
#import <Foundation/Foundation.h>
#import "SUInstallerProtocol.h"
NS_ASSUME_NONNULL_BEGIN
#import "SUUpdater.h"
@interface SUPackageInstaller : NSObject <SUInstallerProtocol>
- (instancetype)initWithPackagePath:(NSString *)packagePath installationPath:(NSString *)installationPath;
#import "SUAppcast.h"
#import "SUAppcastItem.h"
#import "SUVersionComparisonProtocol.h"
#import "SUPlainInstaller.h"
@interface SUPackageInstaller : SUPlainInstaller
@end
NS_ASSUME_NONNULL_END
#endif
+19 -59
View File
@@ -7,75 +7,35 @@
//
#import "SUPackageInstaller.h"
#import <Cocoa/Cocoa.h>
#import "SUConstants.h"
#import "SUErrors.h"
#import "SULog.h"
#include "AppKitPrevention.h"
@interface SUPackageInstaller ()
@property (nonatomic, readonly, copy) NSString *packagePath;
@property (nonatomic, readonly, copy) NSString *installationPath;
@end
@implementation SUPackageInstaller
static NSString *SUOpenUtilityPath = @"/usr/bin/open";
@synthesize packagePath = _packagePath;
@synthesize installationPath = _installationPath;
- (instancetype)initWithPackagePath:(NSString *)packagePath installationPath:(NSString *)installationPath
{
self = [super init];
if (self != nil) {
_packagePath = [packagePath copy];
_installationPath = [installationPath copy];
}
return self;
}
- (BOOL)performInitialInstallation:(NSError * __autoreleasing *)error
{
if (![[NSFileManager defaultManager] fileExistsAtPath:SUOpenUtilityPath]) {
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingInstallerToolError userInfo:@{ NSLocalizedDescriptionKey: @"Couldn't find Apple's installer tool!" }];
}
return NO;
}
return YES;
}
- (BOOL)performFinalInstallationProgressBlock:(nullable void(^)(double))__unused cb error:(NSError *__autoreleasing*)error
+ (void)performInstallationToPath:(NSString *)installationPath fromPath:(NSString *)path host:(SUHost *)__unused host versionComparator:(id<SUVersionComparison>)__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.
// -n = Open another instance if already open.
// -b = app bundle identifier
NSArray *args = @[@"-W", @"-n", @"-b", @"com.apple.installer", self.packagePath];
// Known bug: if the installation fails or is canceled, Sparkle goes ahead and restarts, thinking everything is fine.
@try {
NSTask *installer = [NSTask launchedTaskWithLaunchPath:SUOpenUtilityPath arguments:args];
[installer waitUntilExit];
}
@catch (NSException *exception) {
SULog(SULogLevelError, @"Error: Failed to launch package installer: %@", exception);
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: @"Package installer failed to launch." }];
}
return NO;
}
return YES;
}
NSString *command = @"/usr/bin/open";
NSArray *args = @[@"-W", @"-n", @"-b", @"com.apple.installer", path];
- (BOOL)canInstallSilently
{
return NO;
if (![[NSFileManager defaultManager] fileExistsAtPath:command]) {
NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingInstallerToolError userInfo:@{ NSLocalizedDescriptionKey: @"Couldn't find Apple's installer tool!" }];
[self finishInstallationToPath:installationPath withResult:NO error:error completionHandler:completionHandler];
return;
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSTask *installer = [NSTask launchedTaskWithLaunchPath:command arguments:args];
[installer waitUntilExit];
// Known bug: if the installation fails or is canceled, Sparkle goes ahead and restarts, thinking everything is fine.
dispatch_async(dispatch_get_main_queue(), ^{
[self finishInstallationToPath:installationPath withResult:YES error:nil completionHandler:completionHandler];
});
});
}
@end
+3 -9
View File
@@ -9,17 +9,11 @@
#ifndef SUPIPEDUNARCHIVER_H
#define SUPIPEDUNARCHIVER_H
#import <Foundation/Foundation.h>
#import "SUUnarchiverProtocol.h"
#import <Cocoa/Cocoa.h>
#import "SUUnarchiver.h"
NS_ASSUME_NONNULL_BEGIN
@interface SUPipedUnarchiver : NSObject <SUUnarchiverProtocol>
- (instancetype)initWithArchivePath:(NSString *)archivePath;
@interface SUPipedUnarchiver : SUUnarchiver
@end
NS_ASSUME_NONNULL_END
#endif
+89 -82
View File
@@ -7,106 +7,69 @@
//
#import "SUPipedUnarchiver.h"
#import "SUUnarchiverNotifier.h"
#import "SUUnarchiver_Private.h"
#import "SULog.h"
#import "SUErrors.h"
#include "AppKitPrevention.h"
@interface SUPipedUnarchiver ()
@property (nonatomic, copy, readonly) NSString *archivePath;
@end
@implementation SUPipedUnarchiver
@synthesize archivePath = _archivePath;
+ (nullable NSArray <NSString *> *)commandAndArgumentsConformingToTypeOfPath:(NSString *)path
+ (SEL)selectorConformingToTypeOfPath:(NSString *)path
{
NSArray <NSString *> *extractTGZ = @[@"/usr/bin/tar", @"-zxC"];
NSArray <NSString *> *extractTBZ = @[@"/usr/bin/tar", @"-jxC"];
NSArray <NSString *> *extractTXZ = extractTGZ;
NSDictionary <NSString *, NSArray<NSString *> *> *extractCommandDictionary =
@{
@".zip" : @[@"/usr/bin/ditto", @"-x",@"-k",@"-"],
@".tar" : @[@"/usr/bin/tar", @"-xC"],
@".tar.gz" : extractTGZ,
@".tgz" : extractTGZ,
@".tar.bz2" : extractTBZ,
@".tbz" : extractTBZ,
@".tar.xz" : extractTXZ,
@".txz" : extractTXZ,
@".tar.lzma" : extractTXZ
};
static NSDictionary *typeSelectorDictionary;
if (!typeSelectorDictionary)
typeSelectorDictionary = @{ @".zip": @"extractZIP",
@".tar": @"extractTAR",
@".tar.gz": @"extractTGZ",
@".tgz": @"extractTGZ",
@".tar.bz2": @"extractTBZ",
@".tbz": @"extractTBZ",
@".tar.xz": @"extractTXZ",
@".txz": @"extractTXZ",
@".tar.lzma": @"extractTXZ"};
NSString *lastPathComponent = [path lastPathComponent];
for (NSString *currentType in extractCommandDictionary)
{
if ([lastPathComponent hasSuffix:currentType]) {
return [extractCommandDictionary objectForKey:currentType];
for (NSString *currentType in typeSelectorDictionary)
{
NSString *value = [typeSelectorDictionary objectForKey:currentType];
assert(value);
if ([currentType length] > [lastPathComponent length]) continue;
if ([[lastPathComponent substringFromIndex:[lastPathComponent length] - [currentType length]] isEqualToString:currentType]) {
return NSSelectorFromString(value);
}
}
return nil;
return NULL;
}
- (void)start
{
[NSThread detachNewThreadSelector:[[self class] selectorConformingToTypeOfPath:self.archivePath] toTarget:self withObject:nil];
}
+ (BOOL)canUnarchivePath:(NSString *)path
{
return ([self commandAndArgumentsConformingToTypeOfPath:path] != nil);
}
+ (BOOL)unsafeIfArchiveIsNotValidated
{
return NO;
}
- (instancetype)initWithArchivePath:(NSString *)archivePath
{
self = [super init];
if (self != nil) {
_archivePath = [archivePath copy];
}
return self;
}
- (void)unarchiveWithCompletionBlock:(void (^)(NSError * _Nullable))completionBlock progressBlock:(void (^ _Nullable)(double))progressBlock
{
NSArray <NSString *> *commandAndArguments = [[self class] commandAndArgumentsConformingToTypeOfPath:self.archivePath];
assert(commandAndArguments != nil);
NSString *command = commandAndArguments.firstObject;
assert(command != nil);
NSArray <NSString *> *arguments = [commandAndArguments subarrayWithRange:NSMakeRange(1, commandAndArguments.count - 1)];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
SUUnarchiverNotifier *notifier = [[SUUnarchiverNotifier alloc] initWithCompletionBlock:completionBlock progressBlock:progressBlock];
[self extractArchivePipingDataToCommand:command arguments:arguments notifier:notifier];
});
return ([self selectorConformingToTypeOfPath:path] != nil);
}
// This method abstracts the types that use a command line tool piping data from stdin.
- (void)extractArchivePipingDataToCommand:(NSString *)command arguments:(NSArray*)args notifier:(SUUnarchiverNotifier *)notifier
- (void)extractArchivePipingDataToCommand:(NSString *)command args:(NSArray*)args
{
// *** GETS CALLED ON NON-MAIN THREAD!!!
@autoreleasepool {
NSError *error = nil;
NSString *destination = [self.archivePath stringByDeletingLastPathComponent];
SULog(SULogLevelDefault, @"Extracting using '%@' '%@' < '%@' '%@'", command, [args componentsJoinedByString:@"' '"], self.archivePath, destination);
SULog(@"Extracting using '%@' '%@' < '%@' '%@'", command, [args componentsJoinedByString:@"' '"], self.archivePath, destination);
// Get the file size.
NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:self.archivePath error:nil];
NSUInteger expectedLength = [[attributes objectForKey:NSFileSize] unsignedIntegerValue];
if (expectedLength > 0) {
NSFileHandle *archiveInput = [NSFileHandle fileHandleForReadingAtPath:self.archivePath];
NSPipe *pipe = [NSPipe pipe];
NSFileHandle *archiveOutput = [pipe fileHandleForWriting];
NSTask *task = [[NSTask alloc] init];
[task setStandardInput:[pipe fileHandleForReading]];
[task setStandardError:[NSFileHandle fileHandleWithStandardError]];
@@ -114,7 +77,7 @@
[task setLaunchPath:command];
[task setArguments:[args arrayByAddingObject:destination]];
[task launch];
NSUInteger bytesRead = 0;
do {
NSData *data = [archiveInput readDataOfLength:256*1024];
@@ -124,32 +87,76 @@
}
bytesRead += len;
[archiveOutput writeData:data];
[notifier notifyProgress:(double)bytesRead / (double)expectedLength];
dispatch_async(dispatch_get_main_queue(), ^{
[self notifyDelegateOfProgress:(double)bytesRead / (double)expectedLength];
});
}
while(bytesRead < expectedLength);
[archiveOutput closeFile];
[task waitUntilExit];
if ([task terminationStatus] == 0) {
if (bytesRead == expectedLength) {
[notifier notifySuccess];
dispatch_async(dispatch_get_main_queue(), ^{
[self notifyDelegateOfSuccess];
});
return;
} else {
error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Extraction failed, command '%@' got only %ld of %ld bytes", command, (long)bytesRead, (long)expectedLength]}];
SULog(@"Extraction failed, command '%@' got only %ld of %ld bytes", command, (long)bytesRead, (long)expectedLength);
}
} else {
error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Extraction failed, command '%@' returned %d", command, [task terminationStatus]]}];
SULog(@"Extraction failed, command '%@' returned %d", command, [task terminationStatus]);
}
} else {
error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Extraction failed, archive '%@' is empty", self.archivePath]}];
SULog(@"Extraction failed, archive '%@' is empty", self.archivePath);
}
[notifier notifyFailureWithError:error];
dispatch_async(dispatch_get_main_queue(), ^{
[self notifyDelegateOfFailure];
});
}
}
- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], self.archivePath]; }
- (void)extractTAR
{
// *** GETS CALLED ON NON-MAIN THREAD!!!
[self extractArchivePipingDataToCommand:@"/usr/bin/tar" args:@[@"-xC"]];
}
- (void)extractTGZ
{
// *** GETS CALLED ON NON-MAIN THREAD!!!
[self extractArchivePipingDataToCommand:@"/usr/bin/tar" args:@[@"-zxC"]];
}
- (void)extractTBZ
{
// *** GETS CALLED ON NON-MAIN THREAD!!!
[self extractArchivePipingDataToCommand:@"/usr/bin/tar" args:@[@"-jxC"]];
}
- (void)extractZIP
{
// *** GETS CALLED ON NON-MAIN THREAD!!!
[self extractArchivePipingDataToCommand:@"/usr/bin/ditto" args:@[@"-x",@"-k",@"-"]];
}
- (void)extractTXZ
{
// *** GETS CALLED ON NON-MAIN THREAD!!!
[self extractArchivePipingDataToCommand:@"/usr/bin/tar" args:@[@"-zxC"]];
}
+ (void)load
{
[self registerImplementation:self];
}
@end
+14 -12
View File
@@ -6,23 +6,25 @@
// Copyright 2008 Andy Matuschak. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "SUInstallerProtocol.h"
#ifndef SUPLAININSTALLER_H
#define SUPLAININSTALLER_H
NS_ASSUME_NONNULL_BEGIN
#import <Foundation/Foundation.h>
#import "SUUpdater.h"
#import "SUAppcast.h"
#import "SUAppcastItem.h"
#import "SUVersionComparisonProtocol.h"
#import "SUInstaller.h"
#import "SUVersionComparisonProtocol.h"
@class SUHost;
@interface SUPlainInstaller : NSObject <SUInstallerProtocol>
@interface SUPlainInstaller : SUInstaller
/*!
@param host The current (old) bundle host
@param bundlePath The path to the new bundle that will be installed.
@param installationPath The path the new bundlePath will be installed to.
@param fileOperationToolPath The path to the file operation tool for authorized operations.
*/
- (instancetype)initWithHost:(SUHost *)host bundlePath:(NSString *)bundlePath installationPath:(NSString *)installationPath fileOperationToolPath:(NSString *)fileOperationToolPath;
+ (void)performInstallationToPath:(NSString *)installationPath fromPath:(NSString *)path host:(SUHost *)host versionComparator:(id<SUVersionComparison>)comparator completionHandler:(void (^)(NSError *))completionHandler;
@end
NS_ASSUME_NONNULL_END
#endif
+50 -126
View File
@@ -7,46 +7,16 @@
//
#import "SUPlainInstaller.h"
#import "SUVersionComparisonProtocol.h"
#import "SUStandardVersionComparator.h"
#import "SUFileManager.h"
#import "SUCodeSigningVerifier.h"
#import "SUConstants.h"
#import "SUHost.h"
#import "SULog.h"
#import "SUErrors.h"
#include "AppKitPrevention.h"
@interface SUPlainInstaller ()
@property (nonatomic, readonly) SUHost *host;
@property (nonatomic, copy, readonly) NSString *bundlePath;
@property (nonatomic, copy, readonly) NSString *installationPath;
@property (nonatomic, copy, readonly) NSString *fileOperationToolPath;
@end
@implementation SUPlainInstaller
@synthesize host = _host;
@synthesize bundlePath = _bundlePath;
@synthesize installationPath = _installationPath;
@synthesize fileOperationToolPath = _fileOperationToolPath;
- (instancetype)initWithHost:(SUHost *)host bundlePath:(NSString *)bundlePath installationPath:(NSString *)installationPath fileOperationToolPath:(NSString *)fileOperationToolPath
{
self = [super init];
if (self != nil) {
_host = host;
_bundlePath = [bundlePath copy];
_installationPath = [installationPath copy];
_fileOperationToolPath = [fileOperationToolPath copy];
}
return self;
}
// Returns the bundle version from the specified host that is appropriate to use as a filename, or nil if we're unable to retrieve one
- (NSString *)bundleVersionAppropriateForFilenameFromHost:(SUHost *)host
+ (NSString *)bundleVersionAppropriateForFilenameFromHost:(SUHost *)host
{
NSString *bundleVersion = [host objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleVersionKey];
NSString *trimmedVersion = @"";
@@ -61,49 +31,35 @@
return trimmedVersion.length > 0 ? trimmedVersion : nil;
}
- (BOOL)performInstallationToURL:(NSURL *)installationURL fromUpdateAtURL:(NSURL *)newURL withHost:(SUHost *)host fileOperationToolPath:(NSString *)fileOperationToolPath progressBlock:(nullable void(^)(double))progress error:(NSError * __autoreleasing *)error
+ (BOOL)performInstallationToURL:(NSURL *)installationURL fromUpdateAtURL:(NSURL *)newURL withHost:(SUHost *)host error:(NSError * __autoreleasing *)error
{
if (installationURL == nil || newURL == nil) {
// this really shouldn't happen but just in case
SULog(SULogLevelError, @"Failed to perform installation because either installation URL (%@) or new URL (%@) is nil", installationURL, newURL);
SULog(@"Failed to perform installation because either installation URL (%@) or new URL (%@) is nil", installationURL, newURL);
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: @"Failed to perform installation because the paths to install at and from are not valid" }];
}
return NO;
}
if (progress) {
progress(1/10.0);
}
SUFileManager *fileManager = [SUFileManager fileManagerWithAuthorizationToolPath:fileOperationToolPath];
SUFileManager *fileManager = [SUFileManager fileManagerAllowingAuthorization:YES];
// Create a temporary directory for our new app that resides on our destination's volume
NSString *preferredName = [installationURL.lastPathComponent.stringByDeletingPathExtension stringByAppendingString:@" (Incomplete Update)"];
NSURL *installationDirectory = installationURL.URLByDeletingLastPathComponent;
NSURL *tempNewDirectoryURL = [fileManager makeTemporaryDirectoryWithPreferredName:preferredName appropriateForDirectoryURL:installationDirectory error:error];
NSURL *tempNewDirectoryURL = [fileManager makeTemporaryDirectoryWithPreferredName:[installationURL.lastPathComponent.stringByDeletingPathExtension stringByAppendingString:@" (Incomplete Update)"] appropriateForDirectoryURL:installationURL.URLByDeletingLastPathComponent error:error];
if (tempNewDirectoryURL == nil) {
SULog(SULogLevelError, @"Failed to make new temp directory");
SULog(@"Failed to make new temp directory");
return NO;
}
if (progress) {
progress(2/10.0);
}
// Move the new app to our temporary directory
NSString *newURLLastPathComponent = newURL.lastPathComponent;
NSURL *newTempURL = [tempNewDirectoryURL URLByAppendingPathComponent:newURLLastPathComponent];
if (![fileManager moveItemAtURL:newURL toURL:newTempURL error:error]) {
SULog(SULogLevelError, @"Failed to move the new app from %@ to its temp directory at %@", newURL.path, newTempURL.path);
SULog(@"Failed to move the new app from %@ to its temp directory at %@", newURL.path, newTempURL.path);
[fileManager removeItemAtURL:tempNewDirectoryURL error:NULL];
return NO;
}
if (progress) {
progress(3/10.0);
}
// Release our new app from quarantine, fix its owner and group IDs, and update its modification time while it's at our temporary destination
// We must leave moving the app to its destination as the final step in installing it, so that
// it's not possible our new app can be left in an incomplete state at the final destination
@@ -111,17 +67,13 @@
NSError *quarantineError = nil;
if (![fileManager releaseItemFromQuarantineAtRootURL:newTempURL error:&quarantineError]) {
// Not big enough of a deal to fail the entire installation
SULog(SULogLevelError, @"Failed to release quarantine at %@ with error %@", newTempURL.path, quarantineError);
SULog(@"Failed to release quarantine at %@ with error %@", newTempURL.path, quarantineError);
}
if (progress) {
progress(4/10.0);
}
NSURL *oldURL = [NSURL fileURLWithPath:host.bundlePath];
if (oldURL == nil) {
// this really shouldn't happen but just in case
SULog(SULogLevelError, @"Failed to construct URL from bundle path: %@", host.bundlePath);
SULog(@"Failed to construct URL from bundle path: %@", host.bundlePath);
if (error != NULL) {
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: @"Failed to perform installation because a path could not be constructed for the old installation" }];
}
@@ -130,24 +82,16 @@
if (![fileManager changeOwnerAndGroupOfItemAtRootURL:newTempURL toMatchURL:oldURL error:error]) {
// But this is big enough of a deal to fail
SULog(SULogLevelError, @"Failed to change owner and group of new app at %@ to match old app at %@", newTempURL.path, oldURL.path);
SULog(@"Failed to change owner and group of new app at %@ to match old app at %@", newTempURL.path, oldURL.path);
[fileManager removeItemAtURL:tempNewDirectoryURL error:NULL];
return NO;
}
if (progress) {
progress(5/10.0);
}
if (![fileManager updateModificationAndAccessTimeOfItemAtURL:newTempURL error:error]) {
// Not a fatal error, but a pretty unfortunate one
SULog(SULogLevelError, @"Failed to update modification and access time of new app at %@", newTempURL.path);
SULog(@"Failed to update modification and access time of new app at %@", newTempURL.path);
}
if (progress) {
progress(6/10.0);
}
// Decide on a destination name we should use for the older app when we move it around the file system
NSString *oldDestinationName = nil;
if (SPARKLE_APPEND_VERSION_NUMBER) {
@@ -160,24 +104,19 @@
NSString *oldURLExtension = oldURL.pathExtension;
NSString *oldDestinationNameWithPathExtension = [oldDestinationName stringByAppendingPathExtension:oldURLExtension];
NSURL *oldURLDirectory = oldURL.URLByDeletingLastPathComponent;
// Create a temporary directory for our old app that resides on its volume
NSURL *tempOldDirectoryURL = [fileManager makeTemporaryDirectoryWithPreferredName:oldDestinationName appropriateForDirectoryURL:oldURLDirectory error:error];
NSURL *tempOldDirectoryURL = [fileManager makeTemporaryDirectoryWithPreferredName:oldDestinationName appropriateForDirectoryURL:oldURL.URLByDeletingLastPathComponent error:error];
if (tempOldDirectoryURL == nil) {
SULog(SULogLevelError, @"Failed to create temporary directory for old app at %@", oldURL.path);
SULog(@"Failed to create temporary directory for old app at %@", oldURL.path);
[fileManager removeItemAtURL:tempNewDirectoryURL error:NULL];
return NO;
}
if (progress) {
progress(7/10.0);
}
// Move the old app to the temporary directory
NSURL *oldTempURL = [tempOldDirectoryURL URLByAppendingPathComponent:oldDestinationNameWithPathExtension];
if (![fileManager moveItemAtURL:oldURL toURL:oldTempURL error:error]) {
SULog(SULogLevelError, @"Failed to move the old app at %@ to a temporary location at %@", oldURL.path, oldTempURL.path);
SULog(@"Failed to move the old app at %@ to a temporary location at %@", oldURL.path, oldTempURL.path);
// Just forget about our updated app on failure
[fileManager removeItemAtURL:tempNewDirectoryURL error:NULL];
@@ -185,14 +124,10 @@
return NO;
}
if (progress) {
progress(8/10.0);
}
// Move the new app to its final destination
if (![fileManager moveItemAtURL:newTempURL toURL:installationURL error:error]) {
SULog(SULogLevelError, @"Failed to move new app at %@ to final destination %@", newTempURL.path, installationURL.path);
SULog(@"Failed to move new app at %@ to final destination %@", newTempURL.path, installationURL.path);
// Forget about our updated app on failure
[fileManager removeItemAtURL:tempNewDirectoryURL error:NULL];
@@ -203,58 +138,47 @@
return NO;
}
if (progress) {
progress(9/10.0);
}
// 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
[constrainedFileManager removeItemAtURL:tempOldDirectoryURL error:NULL];
[constrainedFileManager removeItemAtURL:tempNewDirectoryURL error:NULL];
if (progress) {
progress(10/10.0);
// Cleanup: move the old app to the trash
NSError *trashError = nil;
if (![constrainedFileManager moveItemAtURLToTrash:oldTempURL error:&trashError]) {
SULog(@"Failed to move %@ to trash with error %@", oldTempURL, trashError);
}
[constrainedFileManager removeItemAtURL:tempOldDirectoryURL error:NULL];
[constrainedFileManager removeItemAtURL:tempNewDirectoryURL error:NULL];
return YES;
}
- (BOOL)performInitialInstallation:(NSError * __autoreleasing *)error
+ (void)performInstallationToPath:(NSString *)installationPath fromPath:(NSString *)path host:(SUHost *)host versionComparator:(id<SUVersionComparison>)comparator completionHandler:(void (^)(NSError *))completionHandler
{
SUParameterAssert(host);
BOOL allowDowngrades = SPARKLE_AUTOMATED_DOWNGRADES;
// Prevent malicious downgrades
if (!allowDowngrades) {
NSString *hostVersion = [self.host version];
NSBundle *bundle = [NSBundle bundleWithPath:self.bundlePath];
SUHost *updateHost = [[SUHost alloc] initWithBundle:bundle];
NSString *updateVersion = [updateHost objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleVersionKey];
id<SUVersionComparison> comparator = [[SUStandardVersionComparator alloc] init];
if (!updateVersion || [comparator compareVersion:hostVersion toVersion:updateVersion] == NSOrderedDescending) {
if (error != NULL) {
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.", hostVersion, updateVersion];
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUDowngradeError userInfo:@{ NSLocalizedDescriptionKey: errorMessage }];
}
return NO;
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]];
NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUDowngradeError userInfo:@{ NSLocalizedDescriptionKey: errorMessage }];
[self finishInstallationToPath:installationPath withResult:NO error:error completionHandler:completionHandler];
return;
}
}
return YES;
}
- (BOOL)performFinalInstallationProgressBlock:(nullable void(^)(double))cb error:(NSError *__autoreleasing*)error
{
return [self performInstallationToURL:[NSURL fileURLWithPath:self.installationPath] fromUpdateAtURL:[NSURL fileURLWithPath:self.bundlePath] withHost:self.host fileOperationToolPath:self.fileOperationToolPath progressBlock:cb error:error];
}
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)canInstallSilently
{
return YES;
dispatch_async(dispatch_get_main_queue(), ^{
[self finishInstallationToPath:installationPath withResult:result error:error completionHandler:completionHandler];
});
});
}
@end
+1
View File
@@ -9,6 +9,7 @@
#ifndef SUPROBINGUPDATEDRIVER_H
#define SUPROBINGUPDATEDRIVER_H
#import <Cocoa/Cocoa.h>
#import "SUBasicUpdateDriver.h"
// This replaces the old SUStatusChecker.
+3 -6
View File
@@ -7,8 +7,7 @@
//
#import "SUProbingUpdateDriver.h"
#import "SUUpdaterPrivate.h"
#import "SUUpdaterDelegate.h"
#import "SUUpdater.h"
@implementation SUProbingUpdateDriver
@@ -16,8 +15,7 @@
- (void)didFindValidUpdate
{
id<SUUpdaterPrivate> updater = self.updater;
id<SUUpdaterDelegate> updaterDelegate = [updater delegate];
id<SUUpdaterDelegate> updaterDelegate = [self.updater delegate];
if ([updaterDelegate respondsToSelector:@selector(updater:didFindValidUpdate:)])
[updaterDelegate updater:self.updater didFindValidUpdate:self.updateItem];
@@ -28,8 +26,7 @@
- (void)didNotFindUpdate
{
id<SUUpdaterPrivate> updater = self.updater;
id<SUUpdaterDelegate> updaterDelegate = [updater delegate];
id<SUUpdaterDelegate> updaterDelegate = [self.updater delegate];
if ([updaterDelegate respondsToSelector:@selector(updaterDidNotFindUpdate:)]) {
[updaterDelegate updaterDidNotFindUpdate:self.updater];
+1
View File
@@ -9,6 +9,7 @@
#ifndef SUSCHEDULEDUPDATEDRIVER_H
#define SUSCHEDULEDUPDATEDRIVER_H
#import <Cocoa/Cocoa.h>
#import "SUUIBasedUpdateDriver.h"
@interface SUScheduledUpdateDriver : SUUIBasedUpdateDriver
+23 -13
View File
@@ -7,22 +7,21 @@
//
#import "SUScheduledUpdateDriver.h"
#import "SUUpdaterPrivate.h"
#import "SUUpdaterDelegate.h"
#import "SUUpdater.h"
#import "SUAppcast.h"
#import "SUAppcastItem.h"
#import "SUVersionComparisonProtocol.h"
@interface SUScheduledUpdateDriver ()
@property (assign) BOOL showErrors;
@end
@implementation SUScheduledUpdateDriver
- (instancetype)initWithUpdater:(id<SUUpdaterPrivate>)anUpdater
{
if ((self = [super initWithUpdater:anUpdater])) {
self.showErrors = NO;
}
return self;
}
@synthesize showErrors;
- (void)didFindValidUpdate
{
@@ -32,8 +31,7 @@
- (void)didNotFindUpdate
{
id<SUUpdaterPrivate> updater = self.updater;
id<SUUpdaterDelegate> updaterDelegate = [updater delegate];
id<SUUpdaterDelegate> updaterDelegate = [self.updater delegate];
if ([updaterDelegate respondsToSelector:@selector(updaterDidNotFindUpdate:)]) {
[updaterDelegate updaterDidNotFindUpdate:self.updater];
@@ -43,8 +41,20 @@
[self abortUpdate]; // Don't tell the user that no update was found; this was a scheduled update.
}
- (BOOL)shouldDisableKeyboardShortcutForInstallButton {
return YES;
- (void)abortUpdateWithError:(NSError *)error
{
if (self.showErrors) {
[super abortUpdateWithError:error];
} else {
// Call delegate separately here because otherwise it won't know we stopped.
// Normally this gets called by the superclass
id<SUUpdaterDelegate> updaterDelegate = [self.updater delegate];
if ([updaterDelegate respondsToSelector:@selector(updater:didAbortWithError:)]) {
[updaterDelegate updater:self.updater didAbortWithError:error];
}
[self abortUpdate];
}
}
@end
-14
View File
@@ -9,16 +9,10 @@
#ifndef SUSTANDARDVERSIONCOMPARATOR_H
#define SUSTANDARDVERSIONCOMPARATOR_H
#if __has_feature(modules)
@import Foundation;
#else
#import <Foundation/Foundation.h>
#endif
#import "SUExport.h"
#import "SUVersionComparisonProtocol.h"
NS_ASSUME_NONNULL_BEGIN
/*!
Sparkle's default version comparator.
@@ -28,15 +22,8 @@ NS_ASSUME_NONNULL_BEGIN
*/
SU_EXPORT @interface SUStandardVersionComparator : NSObject <SUVersionComparison>
/*!
Initializes a new instance of the standard version comparator.
*/
- (instancetype)init;
/*!
Returns a singleton instance of the comparator.
It is usually preferred to alloc/init new a comparator instead.
*/
+ (SUStandardVersionComparator *)defaultComparator;
@@ -48,5 +35,4 @@ SU_EXPORT @interface SUStandardVersionComparator : NSObject <SUVersionComparison
- (NSComparisonResult)compareVersion:(NSString *)versionA toVersion:(NSString *)versionB;
@end
NS_ASSUME_NONNULL_END
#endif
+6 -11
View File
@@ -6,26 +6,21 @@
// Copyright 2007 Andy Matuschak. All rights reserved.
//
#import "SUUpdater.h"
#import "SUAppcast.h"
#import "SUAppcastItem.h"
#import "SUVersionComparisonProtocol.h"
#import "SUStandardVersionComparator.h"
#include "AppKitPrevention.h"
@implementation SUStandardVersionComparator
- (instancetype)init
{
return [super init];
}
+ (SUStandardVersionComparator *)defaultComparator
{
static SUStandardVersionComparator *defaultComparator = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if (defaultComparator == nil) {
defaultComparator = [[SUStandardVersionComparator alloc] init];
});
}
return defaultComparator;
}
+1 -2
View File
@@ -10,13 +10,12 @@
<connections>
<outlet property="actionButton" destination="12" id="34"/>
<outlet property="progressBar" destination="11" id="49"/>
<outlet property="statusTextField" destination="16" id="MiZ-Tn-yVg"/>
<outlet property="window" destination="5" id="25"/>
</connections>
</customObject>
<customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/>
<customObject id="-3" userLabel="Application"/>
<window identifier="SUStatus" title="Set in Code" allowsToolTipsWhenApplicationIsInactive="NO" autorecalculatesKeyViewLoop="NO" releasedWhenClosed="NO" visibleAtLaunch="NO" animationBehavior="default" id="5" userLabel="Window">
<window title="Set in Code" allowsToolTipsWhenApplicationIsInactive="NO" autorecalculatesKeyViewLoop="NO" releasedWhenClosed="NO" visibleAtLaunch="NO" animationBehavior="default" id="5" userLabel="Window">
<windowStyleMask key="styleMask" titled="YES"/>
<windowPositionMask key="initialPositionMask" leftStrut="YES" rightStrut="YES" topStrut="YES" bottomStrut="YES"/>
<rect key="contentRect" x="200" y="222" width="400" height="107"/>
+2 -3
View File
@@ -9,13 +9,12 @@
#ifndef SUSTATUSCONTROLLER_H
#define SUSTATUSCONTROLLER_H
#import <Cocoa/Cocoa.h>
#import "SUWindowController.h"
@class SUHost;
@interface SUStatusController : NSWindowController
@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;
+9 -49
View File
@@ -6,20 +6,17 @@
// Copyright 2006 Andy Matuschak. All rights reserved.
//
#import "SUOperatingSystem.h"
#import "SUUpdater.h"
#import "SUAppcast.h"
#import "SUAppcastItem.h"
#import "SUVersionComparisonProtocol.h"
#import "SUStatusController.h"
#import "SUHost.h"
#import "SULocalizations.h"
#import "SUApplicationInfo.h"
#import "SUTouchBarForwardDeclarations.h"
#import "SUTouchBarButtonGroup.h"
static NSString *const SUStatusControllerTouchBarIndentifier = @"" SPARKLE_BUNDLE_IDENTIFIER ".SUStatusController";
@interface SUStatusController () <NSTouchBarDelegate>
@interface SUStatusController ()
@property (copy) NSString *title, *buttonTitle;
@property (strong) SUHost *host;
@property NSButton *touchBarButton;
@end
@implementation SUStatusController
@@ -31,8 +28,6 @@ static NSString *const SUStatusControllerTouchBarIndentifier = @"" SPARKLE_BUNDL
@synthesize host;
@synthesize actionButton;
@synthesize progressBar;
@synthesize statusTextField;
@synthesize touchBarButton;
- (instancetype)initWithHost:(SUHost *)aHost
{
@@ -45,24 +40,17 @@ static NSString *const SUStatusControllerTouchBarIndentifier = @"" SPARKLE_BUNDL
return self;
}
- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], [self.host bundlePath]]; }
- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@, %@>", [self class], [self.host bundlePath], [self.host installationPath]]; }
- (void)windowDidLoad
{
if ([SUApplicationInfo isBackgroundApplication:[NSApplication sharedApplication]]) {
if ([self.host isBackgroundApplication]) {
[[self window] setLevel:NSFloatingWindowLevel];
}
[[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
@@ -72,7 +60,7 @@ static NSString *const SUStatusControllerTouchBarIndentifier = @"" SPARKLE_BUNDL
- (NSImage *)applicationIcon
{
return [SUApplicationInfo bestIconForHost:self.host];
return [self.host icon];
}
- (void)beginActionWithTitle:(NSString *)aTitle maxProgressValue:(double)aMaxProgressValue statusText:(NSString *)aStatusText
@@ -99,10 +87,6 @@ static NSString *const SUStatusControllerTouchBarIndentifier = @"" SPARKLE_BUNDL
[self.actionButton setTarget:target];
[self.actionButton setAction:action];
[self.actionButton setKeyEquivalent:isDefault ? @"\r" : @""];
self.touchBarButton.target = self.actionButton.target;
self.touchBarButton.action = self.actionButton.action;
self.touchBarButton.keyEquivalent = self.actionButton.keyEquivalent;
// 06/05/2008 Alex: Avoid a crash when cancelling during the extraction
[self setButtonEnabled:(target != nil)];
@@ -133,28 +117,4 @@ static NSString *const SUStatusControllerTouchBarIndentifier = @"" SPARKLE_BUNDL
[self.progressBar setUsesThreadedAnimation:YES];
}
- (NSTouchBar *)makeTouchBar
{
NSTouchBar *touchBar = [[NSClassFromString(@"NSTouchBar") alloc] init];
touchBar.defaultItemIdentifiers = @[ SUStatusControllerTouchBarIndentifier,];
touchBar.principalItemIdentifier = SUStatusControllerTouchBarIndentifier;
touchBar.delegate = self;
return touchBar;
}
- (NSTouchBarItem *)touchBar:(NSTouchBar * __unused)touchBar makeItemForIdentifier:(NSTouchBarItemIdentifier)identifier
{
if ([identifier isEqualToString:SUStatusControllerTouchBarIndentifier]) {
NSCustomTouchBarItem *item = [(NSCustomTouchBarItem *)[NSClassFromString(@"NSCustomTouchBarItem") alloc] initWithIdentifier:identifier];
SUTouchBarButtonGroup *group = [[SUTouchBarButtonGroup alloc] initByReferencingButtons:@[self.actionButton,]];
item.viewController = group;
self.touchBarButton = group.buttons.firstObject;
[self.touchBarButton bind:@"title" toObject:self.actionButton withKeyPath:@"title" options:nil];
[self.touchBarButton bind:@"enabled" toObject:self.actionButton withKeyPath:@"enabled" options:nil];
return item;
}
return nil;
}
@end
Loaded 100 of 286 files, more files were not shown because too many files have changed in this diff. Show more