You have to remember to invoke prevalidation anyway, so it doesn't
gain much for post-validation to check whether prevalidation failed.
Also, remove a no-longer correct comment from the corresponding
header.
-cleanup is only called when the task has finished, so it's safe to do this.
This silences a spurious warning logged by NSURLSession (or somewhere else internal):
Task <BB2AE4EF-8E93-44D7-9AB3-6EE9A9E3ACF8>.<1> load failed with error Error Domain=NSURLErrorDomain Code=-999 "cancelled" UserInfo={NSErrorFailingURLStringKey=https://example.com/appcast.xml, NSErrorFailingURLKey=https://example.com/appcast.xml, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDownloadTask <BB2AE4EF-8E93-44D7-9AB3-6EE9A9E3ACF8>.<1>"
), _NSURLErrorFailingURLSessionTaskErrorKey=LocalDownloadTask <BB2AE4EF-8E93-44D7-9AB3-6EE9A9E3ACF8>.<1>, NSLocalizedDescription=cancelled} [-999]
* tag '1.20.0': (28 commits)
Bump
Fix binary delta creation on network drives
New Spanish localisation
Fix compilation issues on Xcode 10 with new build system
Bump
Updated readme to indicate that the 10.11 SDK is required to compile Xcode 7 was released with 10.11, the reference to the 10.8 SDK is out of date.
Explicitly specify types to silence "Messaging unqualified id" warning that's new in Xcode 10. Removed __has_feature(objc_generics) check and use generisc to help silence the warnings.
Updated Finnish language resources
Remove executable bit on distributed source files.
Fix potential hang with dispatch_sync to main thread
Deliver SPUDownloaderSession delegate messages on the main queue
add tips for user to install doxygen
add delegate callbacks for fininshed download and extraction related events
Restored legacy CLI for backward compatibility
Fixed index out of bounds
More complex argument parsing to support both inputs
Function to load the private key directly from the keychain
Minor naming improvement
Bump
Explain why auth is requested
...
* tag '1.19.0': (44 commits)
Ensure cocoapods is installed before performing the release “sanity check” (#860)
Silence ‘This block declaration is not a prototype’ Xcode warning
Silence ‘decodeObjectOfClass:forKey: is only available on macOS 10.8’ Xcode warnings, similar to commit ea94969188
10.7 compatibility
Avoid invalid use of main thread
Update wording of read-only error
Improve 'read-only' error message (#1192)
"all" target
Hidden verbose flag
Outdated comment
Amend to avoid gender issue
Changelog
Bump
move Xcode 9.2 automatic changes from project to xcconfig files
Bring project up to Xcode 9.2 settings
silence 10.9 availability and other warnings and use modules when available
Ensure UI is changed only on the main thread
nil checks
Fix typo in expectation description
Finish tests for persistent download
...
* Quiet warnings from Swift compiler: "Using '!' here is deprecated and will be removed in a future release"
* Ignore diagnostics that yield 'messaging unqualified id' warnings when calling XCTAssertNotEqualObjects. I have filed a bug with Apple, Radar #45968630, requesting that they quiet the warning internally to the macro implementation.
* When setting the access time on a directory and its contents, set the access time on the directory last so that it will be guaranteed to match the expected value. There is a side-effect of calling getFileSystemRepresentation that it sets the access time of its container folder, presumably because of an implementatiton detail of how Foundation builds up the path. Note there is another problem here that the order of items from NSDirectoryEnumerator is undefined, so some of the interior items of a directory will undoubtedly end up getting slightly varying access times set upon them. However, for the purposes of Sparkle's use of this method to "keep things alive" in /tmp, I don't think there is an issue. This fix addresses a failing unit test testUpdateFileAccessTime, which was failing because of very slight differences in access time created by the problem described.
This is done by applying a user stylesheet, making the background of the WebView transparent, and using a NSBox to display the dynamic dark background color. The appearance of the release notes will unfortunately not adapt if the theme is changed while the release notes window is open.
I personally have my projects on iCloud Drive which contains a space in the path (`~/Library/Mobile Documents/...`) and the build fails running these two scripts.
* origin/master: (21 commits)
Bump
Update Xcode version for Travis CI
Fix for the timing issue of termination detection.
Add optional updaterDidRelaunchApplication: method on SUUpdaterDelegate (#1115)
Better error message
Warning
Update to Xcode 9/Swift 4
Revert "Ensure UI code always runs on the main thread"
Update German localization with some terminology changes
Update German localization for informal style
Update Dutch localization for informal style
Update Dutch localization with some style changes
Include bin files in CocoaPods installation
Simplified check
Rename OSX macOS
[BasicUpdateDriver] - extend hostSupportsItem method to also check the sparkle:os attribute from the enclosure element to decide if an update item is valid for the host
[AppcastItem] - parse and save the sparkle:os attribute of the enclosure element and add isOsxUpdate method to item class
Updated Japanese translation to reflect change on 55be13c
Updated translation to reflect change on “Update error message to mention temp folders rather than optical drives”.
Changelog
...
The scheduleNextUpdateCheckFiringImmediately: method includes an asynchronous callback. It invalidates the timer before invoking the method with the callback (retrieveNextUpdateCheckInterval:), but doesn’t not invalidate again inside the callback block.
The problem with this is that it is possible the timer is started during the delay. In release versions of an app, crashes have been seen due to an assertion that the NSTimer be nil when scheduling.
The proposed fix is to invalidate the timer in the callback, ensuring the NSTimer is nil before scheduling.
* origin/master:
Don't assume that the progress block exists (the parameter is nullable)
Prepend app name to Autoupdate.app name
Error message tweak
Update error message to mention temp folders rather than optical drives
1.18.0
Log more errors
Unify handling of aborted updates
* commit '60727bffa53ebfbfaf701575904847827bc1656a':
Log key read failure
Formatting
Escape + as well
Escape profile URLs better
Special case for .tar.gz extension
Inline release notes if they don't look like a standalone HTML document
Simplify release notes link check
Feed formatting
* origin/master: (39 commits)
%s is deliberate in this format string
Unused
Make generate_appcast available as a shared scheme
Shush Xcode
Link straight to docs from the readme
ignore .html files when scanning for archives
Missing strings translation.
Updated swift
Warn against abusing installUpdatesIfAvailable
when generating the appcast, if an .html file exists of the same name as the archive, then it will be linked in as the releaseNotesLink
Revert "Fix pt_BR translations"
Revert "Fix pt_BR translations (#1039)"
Fix Japanse localization
Add more info to auth tool run failure
Fix pt_BR translations (#1039)
Fix pt_BR translations
Disable the keyboard shortcut for the install button for scheduled updates to avoid accidental installs.
added `sparkle:shortVersionString` to the enclosure, #1032
Changelog
percent encode the filename used in the delta url
...
Before our TerminationListener didn't handle a process that has already been terminated. In my fork this is unlikely to be an actual issue but in master, the application can very well be dead before the termination listener initiates.
I don't think I have a great justification anymore for waiting more than 'x' hours. This may just be an artifact when I was initially architecting Sparkle so that the entire framework could be stuffed into an XPC service.
We use the cached host bundle if the host bundle is equal to the main bundle.
Otherwise we read in the latest Info dictionary every time.
The cached case is the most common case. The odd case (updating other bundles) is less common. Thus we have better performance for the common case, and we retain correct code in both cases.
This will increase the chance of a user driver implementing being able to show informational only updates. Also it's better to use a new method rather than re-use another existing one inappropriately.
The automatic update driver defers the informational only update & aborts, allowing a scheduled UI driver to resume it. The automatic update driver aborts before the point an update would normally be downloaded.
This is better than the hack in the previous commit. Also, a user driver may very well want to act differently in showing UI if the user initiated the update check.
SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME=1 now works properly again. In the progress agent, we don't use the path sent from the installer unless the normalized setting is enabled.
This allows us to remove SPUUserDriverUIComponent and remove a bunch of logic in the user driver regarding termination. The user drivers generally don't need to know about the application bundle anymore, and strictly now only show UI events.
This has another advantage of the agent being able to quit multiple instances of an application even if the application to update is sandboxed.
We enforce the logic that an application can only be relaunched if it was running initially.
We don't import SPUUserDriverUIComponent in SparkleCore because it is an exported class a part of Sparkle framework, which causes issues.
Instead, we import SPUApplicationInfo which is not exported from Sparkle.
This only affects updater delegates that return NO from -updaterShouldAllowInstallerInteraction:
This improves the user experience in sparkle-cli where now the checking can be aborted before even downloading the update feed, if it knows ahead of time that installation will fail.
This is triggered if the update is automatically downloaded and the installer is started in the background, and the updater's delegate decides to handle silent installation and installs the update invoking its immediate installation block. In this scenario, this fixes an issue where the application may not be terminated silently.
Switching between a sandboxed and non-sandboxed app with regards to user defaults has some bugs with saving user defaults.
Confirmed by an Apple engineer.
Until I find a good reason to have them there, they should not be publicly available.
I actually found a couple bugs from code that was accidently referencing them.
This may be useful if user defaults can't be relied on for the feed URL.
For example, if an app is sandboxed, its user defaults may differ from the defaults sparkle-cli looks up.
I think I used to have this when the remote XPC callbacks were in the user driver and I removed them at some point.
These callbacks are now part of the SPUUpdaterDelegate and the logic is simpler now than before.
The command line utility makes use of these callbacks.
This is more consistent with how the last update check logic works.
I changed the value of SUTimeIntervalAtFirstLaunchKey for backwards compatibility purposes.
Although it is interesting to separate the user driver and update scheduler in different processes, this has yet to prove useful. Further, this management should not exist in the user driver protocol since the protocol would be doing double duty. If this separation is useful in the future, it should be separated into another driver altogether. Note that it is also hard to write correct code that separates the user driver and updater. Removing this code should greatly reduce maintenance costs.
This fixes issues where the user driver may not be displaying release notes properly because it doesn't know what kind of data was downloaded (eg: html vs plain text).
New classes will soon be prefixed with "SPU"
I still need to look into adding a compatibility layer for -updater:willInstallUpdateOnQuit:immediateInstallationInvocation: and possibly deprecating no-DSA instead of outright rejecting it.
If we download a package type installation or a delta update, we should validate the update before trying to unarchive it.
We can't do this with ordinary updates because we handle changing of DSA keys for that particular case.
We first create a directory with respect to the app's bundle ID being updated, sparkle's bundle ID, and a directory inside for a specific purpose. Then we remove all old directories inside there, and create a new unique temporary directory.
This is to avoid conflicts with eg: multiple updaters running against each other around the same time, or files for one function interfering with files from another purpose, while still having a way to clean up old files.
Create distinct subdirectories in our cache directory so files for different purposes won't conflict.
For the installer, move the download archive to the installer's cache location. If the installer is running as root, this moves it to a place only root can access I believe. This is also to prevent other functionality from touching these files.
This is only for debug builds. Release products aren't signed. This allows the updater agent app to be placed in the installer launcher service's MacOS directory, which is more convenient for developers to sign.
The InstallerLauncher code now tries to locate these tools inside Contents/MacOS/ or inside the Resources directory. The installer launcher XPC service now has a copy of the tools included in its bundle.
This may seem like wasting space but it enables eg, the XPC service not trusting a sandboxed application. A developer could always remove the tools from the Sparkle framework if necessary (we can't because the XPC services are optional..)
Using the XPC service allows the developer to sign the installer executable (Autoupdate.app). The agent app can be moved and signed into the MacOS executables directory as well. We don't do that automatically because Xcode's tooling doesn't play nice with attempting that, although that could be looked at later.
We now distinguish between the updater delegate allowing interaction and the update driver allowing interaction. We also remove an interaction allowed flag from the AppInstaller, letting shouldShowUI flag suffice.
Assume that the updater will be run as a logged in user.
The command line driver and progress app aren't completely root safe anyway, and running the progress app under a different user could be quite awkward from root
Several reasons:
* The user may not look at the trash anyway, and it would bloat their HD space
* Other sofware updaters don't move old versions to the trash either. Can confuse the user or not be seemly transparent experience.
* Moving app to trash will not work if user has to authenticate anyway
* Unclear how long and expensive this operation *could* take in all scenarios
* App replacements in Apple's new file system can be atomic-safe, but that may only be the case if the old app is no longer needed
Cons:
* Few tech savvy users may not be able to restore an app without re-downloading it. This would still be rarely done even amongst them.
This is now necessary for package type installations so we can know whether or not we should authenticate ahead of time.
Of course, we also verify that the download contains the type of installation we expect (because the appcast is not very trusted).
We now present a better worded dialog (X wants to update. Please type your password to allow this. OK/Cancel)
We still need to set the icon for the dialog window.
I also fixed some issues with canceling the dialog still throwing an error.
This allows automatically downloading updates, and having them prompt up later, so the user can perform authorization later for starting up the installer
I need to at least look at:
* Automatic downloaded / silent updates
* Running updates as root user from beginning
* Status info query service
* Add guided flag in the appcast
This fixes an issue where relative external references could not be loaded from the release notes.
Note this just affects apps that have a 'com.apple.security.network.client' entitlement or apps that aren't sandboxed.
We now use XPC for communication between Sparkle.framework and Autoupdate.
Autoupdate is now ran as a launchd agaent/daemon. (Most of the time, it acts as an agent).
Using XPC can only be done from non-sandboxed processes, so a connection and status service had to be created.
Currently, the GUI progress tool doesn't work properly, but everything else should be behaving like before.
This fixes installation failing when we check for the wrong child and don't let the installer finish. However, this code now ignores the status from the child. I might see if there's a better way around fixing that..
I don't think this feature would be used much, and I don't want to deal with additional maintainability. As it is, the progress app should show up in rare cases.
This way we don't have to include an icon for the installer progress app. There is a minor issue where the dock icon changes back before termination. However, this app should show up in rare cases in the first place, so I still think this is a good trade off.
For most applications, it makes more sense to use the app's icon than Sparkle's. That and we can save some disk space usage.
This allows installation by requesting the user to enter a password when elevated privileges are necessary. This only works if the application is alive before installation begins.
If the file manager is used for authorization, we can now supply an authorization environment.
This allows us to specify a customized prompt message and an icon to use in the authorization dialog window. We no longer need to include an icon for Autoupdate app.
We now also see if we can get authorization rights access right away, rather than lazily when executing a tool.
1. Use Apple's logging system (ASL) - don't invent our own inefficient mechanism.
2. Logging is not dependent on a global file that any process and thread using Sparkle can write to now, which could also be cleared at any point before.
3. Don't write to stderr on non-debug builds. This is ideal for sparkle-cli utility.
We don't export an API for configuring this in SUUpdater.
Messing with the user defaults is not ideal, and we don't use hasLaunchedBefore anymore
For testing this, the user defaults should just be removed manually, and the test app should be relaunched.
This option never used to work for me that well before anyway.
The old behavior used to be to prompt on second launch.
However, applications can be re-launched in a short amount of time, and Sparkle can be loaded multiple times during a single app launch.
So prompting after a certain amount of time after first launch works better.
If an update permission request comes up, this alows us to make a decision.
Also I renamed the defer and checknow flags to defer-install and check-immediately
What is new is that we can now disable checking for updates immediately.
sparkle-cli is not intended to be run for a long time, so if the next update check is not soon, we exit.
A client can now launch sparkle-cli without having to necessarily check for updates, so that they don't check for updates too soon.
The installer can now inherit privileges from the updater, which inherits
privileges from the process that spawns the updater. As such, we can now
run the updater & installer as root, and no authorization dialog can prompt up.
The installer now must abort or install if the target app has terminated.
Zombie processes will no longer stay around.
Because the root user has no trash directory, we ignore logging the error if it was not found.
We also avoid invoking mdimport which fails as root on the installed app.
mdimport may have been used before for updating mdimporter files, however, it should be the developer's
responsibility to ensure their mdimporter files have an updated date stamp, which will work if a user updates an app manually.
Other than that, we already touch the app to register it with LaunchServices, so that should suffice.
For sparkle-cli and out-of-process updaters, I added a did finish installing event.
I also have logic dealing with whether an update can be silently installed or not.
I made closing status windows before app termination a reponsibility for the user driver now, not
the installer drivers.
I improved checking for updates before starting the updater, if Sparle didn't ask the user for permission yet.
Currently, Autoupdate can persist in the background even when the app is terminated,
if we don't have sufficient privilleges to install right away for example, or if an update isn't silent.
After much thinking, I need to ditch this strategy because:
1. An app can be manually replaced and so the installer would have to monitor that
2. We leave a zombie process running
I'm hoping this will ease some of the build configuration issues I've been running into.
Apps (eg: unsigned, not-sandboxed) don't need to (although they still can) use the XPC services.
Sandboxed apps naturally should use the XPC services. Although, you can for example, choose not to use the
downloader services if the host app already entitlements to allow network connections.
If you use the downloader services, you must configure ATS exceptions in them. And if you use those services,
you probably want to sign them with the required entitlements.
If you don't use the services, Sparkle will fall back on almost-identical code executed within the framework instead.
There may be other reasons to use the services or not other than for sandboxing, like fault tolerance.
Lastly, XPC services work within an application namespace. They are discoverable as long as they're in the app.
That's why we can have an app incorporate the services and let the framework use them.
Rename the XPC service products so that they start with 'Sparkle'
Make the bundle IDs of the services a part of the build configuration, so we can pass it to the preprocessor.
We have a custom codesign-after-copy script because Xcode's code sign on copy feature is bad when it
comes to frameworks including signable tools. In release build configurations, nothing we build uses
an ad-hoc code signature. This is logical because ad-hoc signatures are only meant to be used for testing purposes.
Only the XPC services need to be ad-hoc signed (else Xcode gets cranky),
or targets with entitlements like our Test Application.
Distributing ad-hoc binaries can be mixed with distributing unsigned apps,
and ad-hoc is no worse than unsigned when it comes to distributing, so we're all good.
Updating without DSA signing the download is simply not secure.
Before, we were keen on allowing no DSA signing as long as https is used.
However, under the separate process security model, the installer can't know or trust
if the download came over from https. We could move downloading into the installer, but
the installer may run with full privileges one day in the future, and this would
complicate the installer & updater interaction. Furthermore, this could disallow us from being able
to silently download the update in the future if the installer runs at full privileges.
An upside is that the validation and configuration checking code is simpler to read through now.
Even if we could validate that an update came over https, it is still not as secure as people may like to believe.
For example, a hijacked server can choose to manipulate the download (within restrictions), even if it's signed by a developer ID, but not with our DSA support.
Changing of DSA keys and Apple code signing identities is still allowed as long as one of these pairs match and are valid.
Hence requiring DSA signing is also safer when it comes to losing one of your keys. It's only a bit less convenient.
In debug mode we always build with arbitrary http loads, but in release mode we
only want to build sparkle-cli and SparkleTestApp with arbitrary http loads.
An ATS error was added back if arbitrary HTTP loads are not allowed and if the feed URL is http://
The "distribution" target/scheme is now not very up to date because it builds everything under Release configuration.
An app can contain a XPC service with restricted entitlements and own ATS exceptions.
Indeed, Sparkle now is a framework that embeds two XPC services that include download entitlements.
If ATS is disabled, it'd have to be disabled in those services, not within the root of the application.
So we can't keep this detection because it will generate false positives. And it's not really our responsibility anyway.
We really want to differentiate between apps and prefpanes/plug-ins.
Using the main bundle is not at all a reliable indicator because an updater could target
any kind of bundle anywhere.
This new method also takes an error object as output, which means we can now
read a bundle in Sparkle without having to abort. If a check for updates action is invoked
before the updater has been started, it becomes a pending scheduled operation.
I added an application target but it's really intended to be used as a command line tool. The reason being was that it was the easiest way to bundle the Sparkle framework, I've found.
Note this doesn't work perfectly yet, but it's a good start. Trying to update anything that's not Sparkle based will crash for instance. And it will use the installer progress tool which may be undesirable.
This created more complexity than it was worth and leads to subpar user experience because the user can see the icon switch back to the generic one when the updater terminates. So we now bundle the icon in the install progress tool. If a developer wants to use a custom icon, they can provide their own customized tool.
Following cases where after an update has been automatically downloaded, Sparkle may alert the user right away:
1) Critical updates
2) Insufficient write access to install without being root
3) Package type installations
In addition to alerting the user right away, if they dismiss the update, the schedule timer will be on regular intervals. We also no longer need to care about writability in the updater, only just in the installer.
Duplicated code from SUFileManager and SUGuidedPackageInstaller has been removed.
SUPlainInstaller now tests if it needs authorization rather than by trying to touch the old app.
SUGuidedPackageInstaller now tries to grab authorization during stage 2 of the installation.
This more accurately reflects its intended purpose. From the beginning,
the user cannot check for updates until the updater is ready;
however this doesn't mean that the update is in progress.
ATS exceptions now need to be included in the appcast & update downloader services - *shrugs*.
I've a run script configured to disable ATS for release builds.
This allows Sparkle to be used as-is in a sandboxed application,
without needing to place Sparkle into its own XPC service.
Currently the main app may need to set a global mach service lookup exception
and a client download exception, however this can be fixed by creating a couple more
services. Testing for disk writability will need be done in a service too.
If permissions are abnormal during cleanup or somewhere along the lines, it may be
possible to bring up authorization dialog that is not really needed. Prevent this from happening.
We would want to restrict authorization from being possible anyway when not needed.
Just do all installation in 3rd stage at the moment and reconsider this idea..
Doing any work prior to finishing the installation that requires keeping files in
a temporary directory for potentially a long time turns not to probably not be a great idea.
Unfortunately I don't think trying to keep the files up to date every some interval is a _great_ idea.
I will need to rethink this some more.
This is inevitable if we stick to a three stage installation.
The other direction to consider is to defer most installation until after the app terminated,
although that may have disadvantages of its own.
One important addition is touching the new app recursively before moving it in a temp directory.
This is important because archives can preserve modification & access times, but we don't want that.
This is convenient if the updater and app live in separate processes.
No need to use XPC to find out what certain settings are, and it may take too long to find out that way.
Before there were implicit dependencies and unarchivers were globally registered as their classes were loaded.
This flexibilty is unnecessary and comes with a safety (eg: forgetting to link in a class) and harder to read cost
Resumability works by asking the installer for its progress and for the appcast item we've given it before.
If an automatic silent download occurs, we abort it after the installer tool finishes with its basic steps.
Then, a user initiated or scheduled check can resume the update. The scheduled check fires during a longer-than-normal
span since usually the user can install by quitting the app, unless the app has been alive for a very long time.
One exception to this is when the update is marked critical; in that case, the scheduled check is fired immediately after
an automatic update download. Subsequent attempts will be fired using a normal update check interval.
Todo: delta updates probably don't work when they fail and fallback to a regular update
Copy the bytes manually using -[NSData dataWithBytes:length:]
If we use -[NSData copy] instead, we may be using already freed memory
(according to ASAN), which is no good. This may be because the bytes aren't
deep copied.
Also add some @autoreleasepool wrappers because why not.
This removes subclassing usage making the code harder to follow.
Todo: handle resuming an update already waiting to be installed,
adding impatience timer for automatic update scheduling
We now have a stage where authorization is allowed (when the user intiates a relaunch).
This stage occurs before the user application is terminated (if the operation succeeds).
An install attempt will always be made after the validation is finished now. However, if the
user doesn't explicitly relaunch the app, we don't bug the user about auth prompts which means
updates can fail in this kind of scenario.
This decreases coupling for the updater and updater drivers.
We still pass in the updater because we need it for invoking the updater delegate's methods,
but we now use type 'id' instead of SUUpdater* because we don't want to invoke anything on the object.
Furthermore, we never #import SUUpdater, only forward class declarations.
I added public DSA file, automatic update checking, disabled system profiling
in the unit test's info.plist so that SUUpdater won't complain that DSA is missing,
and it won't prompt for update permission the first time.
This is bad for a number of reasons.
1. Our SUUserDriver protocol wasn't quite the right protocol to pass in.
2. This made the UI/Core components to hold a depedency to the user driver, when it
really was not used for anything other than passing to the delegate. We can now
remove this bidirectional depedency between the components and the user driver.
3. This encourages that the client can handle multiple user drivers within the same class,
which encourages complexity. If they were able to set the delegate, they should have a reference
to the user driver.
Indeed, SUUpdater, SUUpdaterDelegate, and the update drivers all have the same problem.
An unfortunate design decision..
This is to minimize the amount of time the app is left terminated.
App restarts should always be near instantaneous.
More work needs to be done to make authenticated installs more friendly,
and not making installs abortable after validation is done.
The installer (Autoupdate.app) is now responsible for extracting & verifying the update.
It talks to the updater via mach ports. We can't afford to use a XPC service due to
lack of perfoming privileged tasks.
This adds delegate outlets to the updater and to the user driver, so a
developer can hook either of them up. Note we now initialize the updater and
user driver after being awoken from the nib.
We also took this chance to make the delegates to the updater and user driver read only.
This means that the delegates have to be available on initialization, which is good because
changing delegates or setting delegates too late (and missing messages) is bad.
For sandbox testing, we really have to use ad-hoc signing.
Which means we have to sign the "new" app after we alter its info.plist file,
so that our code signing verifier doesn't (rightfully) complain
We should terminate even if the update aborts.
We should also terminate even if the connection is invalidated or interrupted, if we've
already been told to quit
I decided it was less evil to allow SUUpdater to defer cycling and have
a mutable delegate, than it was for SUUpdateController to have a nullable SUUpdater
that could be instantiated an arbitrary time later
I have also changed the delay from 0 to 1, on the safer side.
Also move system shut off handling to the user driver.
Observing system shut off is difficult without AppKit, and
a client may want to observe for varying types of events.
I suppose this is consistent with application termination
notifications though.
This solves several problems:
1) we can't spawn a task reliably from a XPC process
2) we don't want to link to AppKit from SUBasicUpdateDriver
3) spawning a task to invoke open utility is poor with bad inputs
These operations also make incorrect assumptions when called from out of process,
so it makes sense to separate them out. Furthermore, SUHost can now only depend on
Foundation
Yeah, this isn't backwards compatible with older code that uses Sparkle
Few notes:
* Mostly everything from *.pch has been moved out for saner dependency tracking
* 10.7 compatibility has been removed out so I don't import Cocoa when I don't have to
* sharedUpdaters/SUUpdater singletons has been removed out so updaters can actually be deallocated properly
(and since singletons are generally horrible idea anyway)
* SUUpdater doesn't have UI/cocoa/bindings/menu validation code. Its new initializer method takes a user driver
(perhaps in the future I'll create another class that "binds" the UI and core)
In a XPC environment, a delegate may handle update checks by sending a message
to the XPC process that tells it to reset the sparkle updater's check cycle.
If the user driver delegate can do this, the XPC process will not need to wait
for a reply, allowing the system to kill the XPC process when it becomes idle.
These changes are to make XPC environment more friendly. Every reply block must
get a response and is not optional to respond to. For example we can no longer have
a reply block that is just "cancelUpdate()"; it must now take an option whether
we are done now or if we want to cancel, and the receiver should now be aware
when canceling doesn't make sense (i.e, if update already aborted). Furthermore,
a reply block must get exactly *one* response.
non-void/synchronous calls over XPC don't work properly, and
these methods don't seem very proper architecture wise anyway.
A proper solution will be needed for notifying the delegate of modal alerts
If an automatic update needs to be applied at termination,
the app delegate will need to hold responsibility of delaying
termination until Sparkle is ready to relaunch
Note that the protocol API for the user updater driver can still be improved.
applicationWillTerminate: is done from the user driver because that's the only way that will
function across different processes.
We support NSSecureCoding for SUAppcastItem and SUHost
Callbacks from XPC <-> Host app now async to main GCD queue.
This is needed for everything to be thread safe.
Todo: NSDate parsing sucks and is temporarily disabled.
In particular, we're using deprecated methods to read the dates,
which don't support NSSecureCoding. The other problem is that the dates are
really useless technically and we shouldn't sort by them.
Everything related to the protocol is intended for showing & dismissing progress,
as well as making UI actions such as canceling, installing, confirming update permissions
This is still incomplete and not perfect yet.
In particular, these delegate methods ought to perhaps be grouped in a separate class.
The UI code that is currently done should be treated the same manner as a custom UI
Relaunching Sparkle should give customization over showing the UI of the autoupdater app
fprintf(stderr,"\nwarning: file permissions %o of '%s' won't be preserved in the delta update (only permissions with modes 0755 and 0644 are supported).\n",permissions&PERMISSION_FLAGS,ent->fts_path);
fprintf(stderr,"\n");
}
if(error!=NULL){
*error=[NSErrorerrorWithDomain:NSCocoaErrorDomaincode:NSFileReadUnknownErroruserInfo:@{NSLocalizedDescriptionKey:[NSStringstringWithFormat:@"Invalid file permissions after-tree on file %@ (only permissions with modes 0755 and 0644 are supported)",@(ent->fts_path)]}];
@@ -14,20 +14,13 @@ A guided installation allows Sparkle to download and install a package (pkg) or
The installer package is installed using macOS's built-in command line installer, `/usr/sbin/installer`. No installation interface is shown to the user.
A guided installation can be started by applications other than the application being replaced. This is particularly useful where helper applications or agents are used.
## To Do
- Replace the use of `AuthorizationExecuteWithPrivilegesAndWait`. This method remains because it is well supported and tested. Ideally a helper tool or XPC would be used.
*error=[NSErrorerrorWithDomain:SUSparkleErrorDomaincode:SUInstallationErroruserInfo:@{NSLocalizedDescriptionKey:[NSStringstringWithFormat:@"Guided package installer returned non-zero exit status (%d)",task.terminationStatus]}];
}
}
}@catch(NSException*){
success=NO;
if(error!=NULL){
*error=[NSErrorerrorWithDomain:SUSparkleErrorDomaincode:SUInstallationErroruserInfo:@{NSLocalizedDescriptionKey:[NSStringstringWithFormat:@"Guided package installer task threw an exception"]}];
// 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
*error=[NSErrorerrorWithDomain:SUSparkleErrorDomaincode:SUInstallationErroruserInfo:@{NSLocalizedDescriptionKey:[NSStringstringWithFormat:@"Found guided package installer but '%@=%@' was probably missing in the appcast item enclosure",SUAppcastAttributeInstallationType,SPUInstallationTypeGuidedPackage]}];
*error=[NSErrorerrorWithDomain:SUSparkleErrorDomaincode:SUInstallationErroruserInfo:@{NSLocalizedDescriptionKey:[NSStringstringWithFormat:@"Found package installer but '%@=%@' was probably missing in the appcast item enclosure",SUAppcastAttributeInstallationType,SPUInstallationTypeInteractivePackage]}];
*error=[NSErrorerrorWithDomain:SUSparkleErrorDomaincode:SUInstallationErroruserInfo:@{NSLocalizedDescriptionKey:[NSStringstringWithFormat:@"Found regular application update but expected '%@=%@' from the appcast item enclosure instead",SUAppcastAttributeInstallationType,expectedInstallationType]}];
// 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
error=[NSErrorerrorWithDomain:SUSparkleErrorDomaincode:SUUnarchivingErroruserInfo:@{NSLocalizedDescriptionKey:[NSStringstringWithFormat:@"Extraction failed, command '%@' got only %ld of %ld bytes",command,(long)bytesRead,(long)expectedLength]}];
error=[NSErrorerrorWithDomain:SUSparkleErrorDomaincode:SUUnarchivingErroruserInfo:@{NSLocalizedDescriptionKey:[NSStringstringWithFormat:@"Extraction failed, command '%@' returned %d",command,[taskterminationStatus]]}];
error=[NSErrorerrorWithDomain:SUSparkleErrorDomaincode:SUUnarchivingErroruserInfo:@{NSLocalizedDescriptionKey:[NSStringstringWithFormat:@"Extraction failed, command '%@' got only %ld of %ld bytes",command,(long)bytesRead,(long)expectedLength]}];
}
}else{
error=[NSErrorerrorWithDomain:SUSparkleErrorDomaincode:SUUnarchivingErroruserInfo:@{NSLocalizedDescriptionKey:[NSStringstringWithFormat:@"Extraction failed, command '%@' returned %d",command,[taskterminationStatus]]}];
}
}else{
error=[NSErrorerrorWithDomain:SUSparkleErrorDomaincode:SUUnarchivingErroruserInfo:@{NSLocalizedDescriptionKey:[NSStringstringWithFormat:@"Extraction failed, archive '%@' is empty",self.archivePath]}];
NSString*errorMessage=[NSStringstringWithFormat:@"For security reasons, updates that downgrade version of the application are not allowed. Refusing to downgrade app from version %@ to %@. Aborting update.",hostVersion,updateVersion];
* Use `XMLNode.Options.nodePrettyPrint` in `generate_appcast` instead of trying to add whitespace manually (fumoboy007)
* Annotate SUHost for nullability (Michael Buckley)
* Use SUAVAILABLE macro (Christiaan Hofman)
* Fix warnings when using modules (nivekkagicom)
* Correction of Czech localization inconsistency (#1403) (vojtakonarik)
* BR locale fix (BR Lingo)
* Update Japanese localization (fujisoft)
* French Sparkle.strings (Jean-Baptiste)
# 1.21.3
* Losslessly reduced the size of PNG (Barijaona Ramaholimihaso)
* Catch exceptions from subcommands (Julian Mayer)
* `generate_appcast` can sign any bundles instead of just apps (Nate Weaver)
* Check that effectiveAppearance is being observed before calling removeObserver (Pierluigi)
# 1.21.2
* Allow EdDSA for delta updates, too (Kornel)
* Warning fixes (Brian Bergstrand)
* Improvements to release notes view context menu and dark mode (Bi11)
# 1.21.0
* Added support EdDSA (ed25519) signatures (Kornel)
* DSA signatures are considered outdated, and Apple's `Security.framework` only supports weaker SHA-1-based DSA.
* Both old DSA and new EdDSA are still supported (and one app can use both), but new applications should use EdDSA only, and we recommend migrating away from DSA signatures.
* `generate_keys` is now a Swift tool that stores EdDSA private keys in the Keychain
* Existing apps can continue using their old DSA keys, but we've dropped support for generation of old DSA keys
* `sign_update` is now a Swift tool that signs using EdDSA from private keys in the Keychain
* The old DSA-based signing script has been moved to `bin/old_dsa_scripts`
* The old DSA-based signing script has been fixed to work on pre-10.13 systems (Thomas Tempelmann)
* `generate_appcast` has been updated to support EdDSA signatures
* It can sign both DSA (if `dsa_priv.pem` file is specified) and EdDSA (from Keychain)
* The tool now uses Caches directory and doesn't generate unnecessary delta files
* Fixed verification of delta updates on filesystems that change permissions of symlinks
* Fixed `NSURLSession` leak (Michael Ehrmann)
# 1.20.0
* `generate_appcast` option to read private key directly from the keychain (Tamás Lustyik)
XPC services in Sparkle are all optional, so the code involved in the services needs to be usable directly from the framework as well. For this to work well, if the class used in the XPC service takes a delegate, it must not be weakly referenced, so the retain cycle will have to be broken explicitly (via an explicit added invalidate method). dealloc also must not be implemented (do cleanup in custom invalidate method). As one may tell, a couple of the services are simply proxies (InstallerConnection, InstallerStatus), and I wish that didn't have to be the case -- it would be a burden to require a developer to set up a temporary exception with a specific bundle ID, and unsure how long that approach would work for in the future.
The protocols used in XPC services must also not adopt other protocols (i.e, one protocol inheriting from another protocol). This is because the XPC protocol decoder on older supported systems doesn't properly handle this case, and won't be able to find that methods exist on a class.
## Singletons
Singletons and other global mutable variables have been either removed entirely or completely avoided with an exception to backwards compatibility. They have no place in a well architectured framework.
`SPUUpdater` doesn't maintain singleton instances and can now be properly deconstructed. Note because a caller is not expected to explicitly invalidate an updater, this means that the updater needs to avoid geting into a retain cycle. Intermediate clasess were created for the update cycle and schedule timer to avoid just this.
One may argue that we shouldn't allow multiple live updaters running at the same bundle simutaneously, but I disagree and I think that is missing the point. It also does not account for updaters running external to the process. For example, it may be perfectly reasonable to start an update from `sparkle-cli` that defers the installation until quit, and have the application that is being updated be able to resume that installation and relaunch immediately.
The original `SUUpdater` may have also been created to assist plug-ins and other non-app bundles. My advice there is in order to be truely safe, you must not inject a framework like Sparkle into the host application anyway. An external tool that is bundled like `sparkle-cli` may be more appropriate to use here.
## Extensibility
This fork does not support subclassing classes internal (not exported) to Sparkle anymore. Doing so would be almost impossible to maintain into the future. Subclassing in general has been banned in this fork. Composition is prefered everywhere, even amongst the internal update drivers which were rewritten to follow a protocol oriented approach. The reason why composition is preferred is because it's easier to follow the flow of logic.
I hope the user driver API gives enough extensibility without someone wanting to create another fork.
## Delegation
Newer classes, other than assisting backwards compatibility, that support delegation don't pass the delegator around anymore. Doing so has some [bad consequences](https://zgcoder.net/ramblings/avoid-passing-the-delegator) and makes code hard to maintain.
Optional delegate methods that have return types need to be optional or have known default values for primitive types.
You may notice that the delegate and user driver are not accessible as properties from `SPUUpdater`. This is intentional. The methods that belong to these types aren't meaningful to any caller except from internal classes.
## Decoupling
Two software components should not directly know about each other. Preferrably they wouldn't know about each other at all, but if they must, they can use the delegation pattern with a declared protocol.
See `Documentation/graph-of-sparkle.png` for a graph of how the code looks like currently. This was generated via [objc_dep](https://github.com/nst/objc_dep) (great tool). Note that there are no red edges which would mean that two nodes know of each other.
## Attributes
`nonatomic` should really be used wherever possible with regards to obj-c properties (`atomic` is a bad default). `readonly` should be used wherever possible as well, which also implies that only ivar access should be used in initializers. `NS_ASSUME_NONNULL_BEGIN` and `NS_ASSUME_NONNULL_END` should be used around new headers whenever possible. AppKit prevention guards should be used for any non-UI class whenever possible.
* The application to listen for termination & to relaunch. This can be the same bundle as the one being updated, but this doesn't have to be the case (eg: the bundle being updated could be a plug-in that is hosted by another application).
* The updater that lives in Sparkle.framework - this schedules & downloads updates and starts the installer. This updater's life can be tied to the application's lifetime, but this doesn't have to be the case.
* The installer (Autoupdate) which does all the extraction, validation, and installation work. This program is submitted by the updater and is run as a launchd agent or daemon, depending on the type of installation and if elevated permissions are needed to perform the update.
* The progress or agent application which hosts the installation status service and is also responsible for showing UI if the installation takes a sufficiently long period of time, as well as responsible for launching the new update.
## After downloading the update:
### Launching the Installer
SPUCoreBasedUpdateDriver invokes SPUInstallerDriver's extraction method which invokes SUInstallerLauncher's launch installer method. The launcher can be inside a XPC service or running inside the updater/sparkle framework itself. The launcher XPC bundle includes a copy of the installer and agent application in its bundle so it can compute the path to them itself (instead of relying on the updater to pass the paths), which is for security trust reasons.
First, the launcher makes sure that if the updater delegate doesn't allow interaction, that installation can be done without interaction. If it can't, then the launcher fails. If the updater driver that invoked the launcher doesn't allow for interaction (in particular, the automatic/silent update driver does not allow interaction), then the launcher fails with a hint to try again with interaction enabled (in particular, with a UI based update driver). If this happens, the updater keeps a reference to the downloaded update and appcast item that is used for resuming with a UI based update driver later. The launcher in this case is telling that authorization can only be done if interaction is allowed from the driver, so the user can enter their password to start up the installer as root to install over a location that requires such privileges.
The launcher then looks for the installer and agent application first in its bundle's auxiliary directory path, and then its resources path. If the launcher is running inside a XPC service, the tools will be in the auxiliary path location, which allows the developer using the service to also code sign the tools. Once those paths are found, the launcher copies the progress agent application to a temporary cache location. The installer is not copied because it is a plain single executable that does not rely on external relative depedencies, whereas the agent application relies on bundle resources. This is important to consider because the old application may be moved around and removed when the installation process occurs. Leaving the installer inside its bundle also could leave it in a place the user doesn't necessarily have write privileges to.
The installer is first submitted. If it requires root privileges, it will ask for an admin user name and password. How it determines if root privileges are necessary is based on:
* If the installation type from the appcast is an interactive package based installer, then no root privileges are necessary because the package installer will ask for them. Note this type of installation is deprecated however.
* If the installation type from the appcast is a guided or regular package based installer, then root privileges are necessary because the system installer utility has to run as root.
* Otherwise the installation type is a normal application update, and root privileges are only needed if write permission or changing the owner/group is currently insufficient.
The installer makes sure, after extraction, that the expected installation type from the appcast matches the type of installation found within the archive. So this hint from the appcast is not just trusted implicitly.
If the user cancels submitting the installer on authorization (if it's required), the launcher aborts the installation process silently. If everything does alright, the progress agent application is submitted next. If either of the submissions fail, the installation fails and aborts, otherwise the launcher succeeds and its job is done. Note before the submissions are done, the jobs are removed from launchd, and the jobs are submitted in a way that act as "one-time" jobs. If they fail or succeed, the jobs aren't restarted, and the jobs aren't installed in a system location for launchd to attempt launching again.
The only argument passed to the installer is the host bundle identifier of the bundle to update. This bundle identifier is used so that the installer and updater know what Mach service to connect to for IPC. Everything else to the installer is sent via a XPC connection. The host bundle path is passed to the progress agent, which is just used for obtaining the bundle identifier, and for UI purposes (eg: displaying app icon and name when the app needs to show progress). The type of domain the installer is running in (user vs system) is also passed to the progress agent application so it can know which domain to use to connect to the installer.
### Timeouts
Upon starting the progress agent, it tries to establish a connection to the installer and send a "hello" message expecting a reply back. If a reply isn't received back within a certain threshold, the agent application aborts (unless it's already planning to terminate in the near future after relaunching the new update).
If the installer doesn't receive the "hello" message from the agent in a certain threshold, the installer aborts. If the installer doesn't receive the installation input data from the data in a certain threshold also, it aborts there too. If the installer aborts and the agent is connected to the installer, the agent will abort as well.
When the updater attempts to set up a connection to the installer, after a certain threshold, if the installation hasn't progressed from not beginning (i.e, extraction hasn't begun), then the updater aborts the installation.
Note, we don't have a "version tag" for the installer or agent because they are either bundled inside the framework or in the XPC service, and the XPC service already has a version check of its own.
### Installation Data
After the installer launches, the updater creates a connection to the installer and sends installation data to the installer using the `SPUInstallationData` message. This data includes the bundle application path to relaunch, the path to the bundle to update and replace, DSA signature from the appcast item, decryption password for dmg if available, the path to the downloaded directory and name of the downloaded item, and the type of expected installation.
The installer takes note of all this information, but it moves the downloaded item into a update directory it chooses for itself. This is for two reasons:
1. If the installer is running at a higher level than the process that submitted it (eg: sandboxed -> user, or user -> root), it make sense from a security perspective to move the file into its own support directory. This could prevent an attacker from manipulating the download while the installer is using it.
2. The updater, or another updater running, or someone else probably won't accidently remove the downloaded item if the installer decides to 'own' it.
After the installer moves the downloaded item, it makes sure the item is not a symbolic link. If it is a non-regular file, the installer aborts, causing the updater to abort as well. Note this check is done after the move rather than before due to potential race conditions an attacker could create.
### Update Extraction
After the installer receives the input installation data, it starts extracting the update. The installer first sends a `SPUExtractionStarted` message.
If the unarchiver requires DSA validation before extraction (binary delta archives do) or if the expected installation type is a package type, then before starting the unarchiver, validation is checked to make sure the signature for the archive is valid. If the signature is not valid, then a `SPUArchiveExtractionFailed` message is sent to the updater (see below on what happens after that). We can't require validation before extracting for normal application updates because they allow changes to DSA keys. Delta updates are fine however because if those fail, then a full update can be tried.
After extraction starts, one or more `SPUExtractedArchiveWithProgress` messages indicating the unarchival progress are sent back to the updater. On failure, the installer will send `SPUArchiveExtractionFailed`. In the updater, if the update is a delta update and extraction fails, then the full archive is downloaded and we go back to the "Sending Installation Data" section to re-send the data and begin extraction again. If the update is not a delta update and extraction fails on the other hand, then the updater aborts causing the installer to abort as well.
### Post Validation
If the unarchiving succeeds, a `SPUValidationStarted` message is sent back to the updater, and the installer begins post validating the update.
If validation was already done before extraction, just the code signature is checked on the extracted bundle to make sure it's valid (if there's a code signature on the bundle). This is just a consistency check to make sure the developer didn't make a careless erorr.
If validation fails, the installer aborts, causing the updater to abort the update as well. Otherwise, the installer sends a message `SPUInstallationStartedStage1` to the updater and begins the installation.
### Retrieving Process Identifier
If the installer hasn't made a connection to the agent yet within the time threshold, the installer waits until a connection is made. Otherwise, the installer asks the agent for the process identifier of the application bundle that it wants to wait for termination. If the installer doesn't get a response within a certain threshold, the installer aborts.
When the installer gets the process identifier, it begins the installation. At this point on, the installer will try to perform the installation even if the connection to the updater or the connection to the agent invalidates.
### Starting the Installation
The installer figures out what kind of installer to use (regular, guided pkg, interactive pkg) based on the type of file inside the archive. If the type of file doesn't match the expected installation type from the input installation data, then the installer aborts causing the updater to abort as well.
Once the type of installer is found, the first stage of installation is performed:
* Regular application installer 1st stage: Makes sure this update is not a downgrade.
* Guided Package installer 1st stage: Does nothing.
* Interactive Package installer (deprecated) 1st stage: Makes sure /usr/bin/open utility is available.
If the first stage fails, the installer aborts causing the updater to abort the update.
Otherwise a `SPUInstallationFinishedStage1` message is sent back to the updater along with some data. This data includes whether the application bundle to relaunch is currently terminated, and whether the installation at later stages can be performed silently (that is, with no user interaction allowed). If we reach here, only the interactive package installer can't be performed silently.
The installer then listens and waits for the target application to relaunch terminates. If it is already terminated, then it resumes to stage 2 and 3 of the installation immediately on the assumption that the installer does not have permission to show UI interaction to the user. Thus if the installer has to show user interaction here and hasn't received an OK from the updater (it won't if the target application is already terminated), the install will fail. If the target is already terminated, the installer will also assume that the target should not be relaunched after installation.
### Installation Waiting Period
The updater receives `SPUInstallationFinishedStage1` message. The updater sends a message `SPUSentUpdateAppcastItemData` with the appcast data in case the updater may request for it later (due to installer resumability, discussed later). It also reads if the target has already been terminated (implying that the installer will continue installing the update immediately), and if the installation will be done silently.
For UI based update drivers, the updater tells the user driver to show that the application is ready to be relaunched - the user can continue to install & relaunch the app. The user driver is only alerted however if the installation isn't happening immediately (that is, if the target application to relaunch is still alive). The user driver can decide whether to a) install b) install & relaunch or c) delay installation. If installation is delayed, it can be resumed later, or if the target application terminates, the installer will try to continue installation if it is capable to without user interaction.
For automatic based drivers, if the update is not going to be installed immediately and if it can be installed silently, the updater's delegate has a choice to handle the immediate installation of the update. If the delegate handles the installation, it can invoke a block that will trigger the automatic update driver to tell the installer to resume to stage 2 as detailed in step the "Continue to Installation" section - except without displaying any user interface and by relaunching the application afterwards. If the delegate handles the immediate installation, the automatic update driver will not abort, it will just leave the driver running until the installer requests for the app to be terminated later. This means the update can't be resumed later and the user driver won't be involved.
Otherwise if the updater delegate doesn't handle immediate installation for automatic based drivers (assuming still the update is not going to be installed immediately), the update driver is aborted; the installer will still wait for the target to terminate however. If the update cannot be silently installed or if the update is marked as critical from the appcast, the update procedure is actually 'resumed' as a scheduled UI based update driver immediately. The update driver can also be 'resumed' later when the user initiates for an update manually or when a long duration (I think a week) has passed by without the user terminating the application. Note automatic based drivers are unable to do a resume, so only UI based ones can.
If an update driver is resumed (which cannot happen if the target applicaton is already terminated by the way), then the updater first requests the installer for the appcast item data that the installer received before. The updater does this by creating a temporary distinct connection for the purpose of querying for the installation status. The connection will give up if a short timeout passes. If the updater fails to retrieve resume data, it assumes that there's no update to resume and will start back from the beginning. The updater can use this data for showing release notes, etc. Note the updater and target application don't have to live in the same process, and the updater could choose to terminate and resume later as a new process - so having the installer keep the appcast item data is nice.
Afterwards the resumed update driver then allows the user driver to decide whether to a) install the update now, b) install & relaunch the update, or to c) delay the update installation and abort the update driver. Note we are now back to the same options discussed earlier.
### Continue to Installation
If the user driver decides to install the update, it sends a `SPUResumeInstallationToStage2` message to the installer and supplies whether the update should be relaunched, and whether user interface can be displayed. The user driver specifies that the user interface can be displayed as long as the updater delegate allows interaction. If the updater's delegate handles immediate installation in the automatic based update driver, UI cannot be displayed there too.
The installer receives `SPUResumeInstallationToStage2` and reads whether it should relaunch the target application and whether it can show UI (thus be allowed to show user interaction). The installer then resumes to stage 2 of the installation if it has not been performed already (that is if the target app already terminated). Note if the installer doesn't receive this message before the target application terminates, then the installer will not relaunch or show UI and resume stage 2 & 3 by itself. Again not displaying UI is only an issue for interactive based package installers which are deprecated.
If the 2nd stage succeeds, the installer sends a `SPUInstallationFinishedStage2` message back to the updater, including if the target application has already terminated at this time. If the target application has not already been terminated, the installer sends a request to the progress agent to *terminate* the application. By *terminate*, we mean sending an Apple quit event, allowing the application or user to possibly cancel or delay termination.
The updater receives a `SPUInstallationFinishedStage2` message, and reads if the target application had already been terminated. If the target application has not already terminated, the updater tells the user driver to show that the application is being sent a termination request.
### Showing Progress
When the target application is terminated, if the updater allowed the installer to show UI progress and the installation type doesn't show progress on its own (only interactive package installer shows progress on its own), then the installer sends a `SPUUpdaterAlivePing` message to the updater. If the updater is still alive by now and receives the message, the updater will then send back a `SPUUpdaterAlivePong` message. This lets the installer know that the updater is still active after the target application is terminated, and whether the installer should later be responsible for displaying updater progress or not if a short time passes by, and the installation is still not finished. If the updater is still not alive, then the installer should be responsible for showing progress if otherwise allowed.
If the installer decides to show progress, it sends a message to the progress agent to show progress UI. Under most circumstances, the installation will finish faster than this point is reached however (exceptions may be potentially large updates with many scattered files, guided package installers, and updates over a remote network mount). If the connection to the updater is still connected after this short time passes (eg: like with sparkle-cli), then it's the updater's job to show progress instead.
### Finishing the Installation
The installer starts stage 3 of the installation after the target application is terminated as well. The third stage does the final installation for updating and replacing the new updated bundle.
If the third stage fails, then the installer aborts, causing the updater driver to abort if it's still running. The target application is not ever relaunched on failure.
Otherwise if the third stage succeeds, the installer sends a message to the agent to stop showing progress. The agent uses this hint to acknowledge that it should stop broadcasting the status info service for the updater. If the connection to the updater is still alive, a `SPUInstallationFinishedStage3` message is sent back to the updater and the updater driver silently aborts the update.
The installer then sends a message to the agent to relaunch the new application if the installer was requested to relaunch it. This also signals to the agent that it will terminate shortly. If the installer decides not to relaunch the update, the agent will terminate when its connection to the installer invalidates. The installer lastly does cleanup work by removing its update directory it was using and exits.
When the progress agent exits, it cleans up by removing itself from disk. The installer doesn't do that because the installer isn't copied to another location in the first place.
## Notes:
* Performing an update as the root user is not currently supported. The command line driver (minorly) and the agent application link to AppKit, and running the agent as a different user (i.e, dropping from root -> logged in user) is not particularly the most elegant idea.
* We use IPC in such a way that the installer process does not trust the updater process, which is why the installer does extraction, validation, and installation -- all in a single process. The launcher portion of code (which could be running as a XPC service) also does not trust the updater for determining the paths to the installer and agent tool. This portion of code does not check the code signing signature of the installer or agent though for reasons explained in the code.
* We have timeouts and ping/pong messages in various cases because we don't want to trust the other end very much for communicating back quickly. On older systems in my testing (eg: 10.8), connection invalidation events don't even get sent to the other end when interacting with launchd, possibly due a bug that is outputted in Console.app.
* When we terminate the application before doing final installation work, we send an Apple quit event to all running application instances we find under the agent's GUI login session. This does not include running instances from other logged in sessions -- that may require authenticating all the time, so trade off is not worthwhile. Also currently the installer only handles a single process identifier to watch for until termination, and certainly doesn't handle the case if more instances are launched afterwards. Note all of this only applies to instances being launched from the same bundle path, and the consequence may rarely be updating a bundle when a running instance is still left alive.
* SMJobBless() would be interesting to explore and perhaps more suitable for sparkle-cli than ordinary application updaters because using this API is less approriate for one-off installations. There may be some issues to take account of though (eg: http://www.openradar.me/20446733). Furthermore, the installer would have to change to persist rather than be a one-time install, and may have to handle mutliple connections for installing multiple bundles simutaneously.
First, some references I've found to be quite useful:
* WWDC 2010 video on "Creating Secure Applications" - [asciiwwdc](http://asciiwwdc.com/2010/sessions/204?q=security).
* [EvenBetterAuthorizationExample](https://developer.apple.com/library/mac/samplecode/EvenBetterAuthorizationSample/Introduction/Intro.html) sample code by Apple for showing off privileged authorization as well as in sandboxed applications.
* Apple's [Daemons and Agents Technote](https://developer.apple.com/library/mac/technotes/tn2083/_index.html). Outdated and before XPC existed, but insightful.
This fork puts a huge emphasis on splitting Sparkle into several components to achieve privilege separation.
* User Driver (Application; AppKit permitted)
* Updater Scheduler (Framework)
* XPC Services (Instead of some portions of Framework)
* Progress Agent (Application; AppKit permitted)
* Installer (Agent and Daemon safe)
These achieve privilege separation, because at least theoretically, they can all be placed into different processes from one another.
In practice, the user driver and updater framework will likely be in the same process, but leaving this possibility speaks well for the quality of the architecture. This is why for instance all the methods on the user driver are not assumed to be executed on the main thread, if one decided to use NSXPC to drive them.
For XPC Services, it's significant to understand that their purpose is not only for sandboxing. The services can be used regardless of whether an application is sandboxed or not. Besides privilege separation, they also have an impact on fault tolerance and termination.
XPC Services also act inside an application bundle namespace, which is one of many reasons why they aren't bundled inside the framework. We have code that detects whether or not services are available inside the main bundle. This is simpler and more efficient than attempting to create a connection and wait for a timeout. We don't have *any* checks for seeing if the "current process" is sandboxed; doing so is a rather broken behavior. The XPC Services are important, not the sandboxing.
I said above that XPC services are looked up in the main bundle. One may think this assumption doesn't hold for helpers or plug-ins inside applications. My response to that is they probably don't need the services, and they probably shoudn't be injecting Sparkle inside the host application anyway due to unintended conflicts and other consequences. A more appropriate approach may be to bundle a separate tool such as the sparkle command line utility.
The `InstallerLauncher` XPC service needs a `JoinExistingSession` key set to `YES` otherwise authorization will not work properly, and even less so on older systems. It took me forever to debug this, so it's worth mentioning.
When developing this fork, I still had a huge hole in the privilege separation even after supporting XPC Services and sandboxing. I fixed that by removing references to `AuthorizationExecuteWithPrivileges` and submitting a launchd agent/daemon for the installer. This is overlooked, but absolutely essential for our model to be secure.
When communicating to a launchd job, we've several options to use for IPC such as BSD Sockets, Mach ports, XPC (note: XPC is an IPC API and is != "XPC Services"), and file IO. The technote I linked above describes why Mach ports have user namespace issues and why BSD sockets may be preferred over them. However, now, XPC which allows you to choose which domain to look up is the simplest, best, and most modern choice. It's crucial in any event we don't have a daemon (running in system domain) try to *connect* to something in the user domain. Our launchd tasks should also be connected to rather than the other way around. As for communication via file IO, I just wouldn't go anywhere close to trusting such a model mixing in system and user running processes.
For sending Obj-C objects across the wire, we use `SPUSecureCoding` because Cocoa doesn't support sending objects securely out of the box unless working with XPC Services. It's very important the objects implement `NSSecureCoding` and whitelist types that are expected to be decoded, as well as whitelist types inside collections before decoding them.
The installer handles extraction, validation, and installation of the update. This was the main reason why other forks were rejected from being secure. The point to be stressed anyway is that these all need to be done in the same process; they can't be handed off by some other process. This is also why removing references to `AuthorizationExecuteWithPrivileges` is crucial as well.
Note that the installer does *not* handle downloading. That is handled by the updater framework. This is ideal because downloading can be done without disrupting the user, allowing it to be done silently without presenting an authorization dialog. The downloading portion of code can also be stuck into a XPC service with just an entitlement for allowing incoming connections. This also means for secure installations the installer cannot know (or trust) what protocol the update was downloaded from (i.e: http vs https). A good installer will not care, which is why applying updates without a DSA signature/key is now deprecated (reminder that Apple's code signature checks are not intended for complete integrity).
Loaded 100 of 419 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.