private async Task InvokePostInstall(SemanticVersion currentVersion, bool isInitialInstall, bool firstRunOnly, bool silentInstall) { var targetDir = GetDirectoryForRelease(currentVersion); var args = isInitialInstall ? $"--squirrel-install {currentVersion}" : $"--squirrel-updated {currentVersion}"; var squirrelApps = SquirrelAwareExecutableDetector.GetAllSquirrelAwareApps(targetDir.FullName); Log.InfoFormat("Squirrel Enabled Apps: [{0}]", string.Join(",", squirrelApps)); // For each app, run the install command in-order and wait if (!firstRunOnly) { await squirrelApps.ForEachAsync( async exe => { using (var cts = new CancellationTokenSource()) { cts.CancelAfter(15 * 1000); try { await Utility.InvokeProcessAsync(exe, args, cts.Token); } catch (Exception ex) { Log.Error("Couldn't run Squirrel hook, continuing: " + exe, ex); } } }, 1 /* at a time */); } // If this is the first run, we run the apps with first-run and // *don't* wait for them, since they're probably the main EXE if (squirrelApps.Count == 0) { Log.WarnFormat("No apps are marked as Squirrel-aware! Going to run them all"); squirrelApps = targetDir.EnumerateFiles() .Where(x => x.Name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) .Where(x => !x.Name.StartsWith("squirrel.", StringComparison.OrdinalIgnoreCase)) .Select(x => x.FullName) .ToList(); // Create shortcuts for apps automatically if they didn't // create any Squirrel-aware apps squirrelApps.ForEach( x => CreateShortcutsForExecutable( Path.GetFileName(x), ShortcutLocation.Desktop | ShortcutLocation.StartMenu, isInitialInstall == false, null, null)); } if (!isInitialInstall || silentInstall) { return; } var firstRunParam = isInitialInstall ? "--squirrel-firstrun" : ""; squirrelApps .Select(exe => new ProcessStartInfo(exe, firstRunParam) { WorkingDirectory = Path.GetDirectoryName(exe) }) .ForEach(info => Process.Start(info)); }
// NB: Once we uninstall the old version of the app, we try to schedule // it to be deleted at next reboot. Unfortunately, depending on whether // the user has admin permissions, this can fail. So as a failsafe, // before we try to apply any update, we assume previous versions in the // directory are "dead" (i.e. already uninstalled, but not deleted), and // we blow them away. This is to make sure that we don't attempt to run // an uninstaller on an already-uninstalled version. private async Task CleanDeadVersions(SemanticVersion originalVersion, SemanticVersion currentVersion, bool forceUninstall = false) { if (currentVersion == null) { return; } var di = new DirectoryInfo(rootAppDirectory); if (!di.Exists) { return; } Log.InfoFormat("cleanDeadVersions: for version {0}", currentVersion); string originalVersionFolder = null; if (originalVersion != null) { originalVersionFolder = GetDirectoryForRelease(originalVersion).Name; Log.InfoFormat("cleanDeadVersions: exclude folder {0}", originalVersionFolder); } string currentVersionFolder = null; if (currentVersion != null) { currentVersionFolder = GetDirectoryForRelease(currentVersion).Name; Log.InfoFormat("cleanDeadVersions: exclude folder {0}", currentVersionFolder); } // NB: If we try to access a directory that has already been // scheduled for deletion by MoveFileEx it throws what seems like // NT's only error code, ERROR_ACCESS_DENIED. Squelch errors that // come from here. var toCleanup = di.GetDirectories() .Where(x => x.Name.ToLowerInvariant().Contains("app-")) .Where(x => x.Name != currentVersionFolder && x.Name != originalVersionFolder) .Where(x => !IsAppFolderDead(x.FullName)); if (forceUninstall == false) { await toCleanup.ForEachAsync( async x => { var squirrelApps = SquirrelAwareExecutableDetector.GetAllSquirrelAwareApps(x.FullName); var args = $"--squirrel-obsolete {x.Name.Replace("app-", "")}"; if (squirrelApps.Count > 0) { // For each app, run the install command in-order and wait await squirrelApps.ForEachAsync( async exe => { using (var cts = new CancellationTokenSource()) { cts.CancelAfter(10 * 1000); try { await Utility.InvokeProcessAsync(exe, args, cts.Token); } catch (Exception ex) { Log.Error("Coudln't run Squirrel hook, continuing: " + exe, ex); } } }, 1 /* at a time */); } }); } // Include dead folders in folders to :fire: toCleanup = di.GetDirectories() .Where(x => x.Name.ToLowerInvariant().Contains("app-")) .Where(x => x.Name != currentVersionFolder && x.Name != originalVersionFolder); // Get the current process list in an attempt to not burn // directories which have running processes var runningProcesses = UnsafeUtility.EnumerateProcesses(); // Finally, clean up the app-X.Y.Z directories await toCleanup.ForEachAsync( async x => { try { if (runningProcesses.All(p => p.Item1 == null || !p.Item1.StartsWith(x.FullName, StringComparison.OrdinalIgnoreCase))) { await Utility.DeleteDirectoryOrJustGiveUp(x.FullName); } if (Directory.Exists(x.FullName)) { // NB: If we cannot clean up a directory, we need to make // sure that anyone finding it later won't attempt to run // Squirrel events on it. We'll mark it with a .dead file MarkAppFolderAsDead(x.FullName); } } catch (UnauthorizedAccessException ex) { Log.Warn("Couldn't delete directory: " + x.FullName, ex); // NB: Same deal as above MarkAppFolderAsDead(x.FullName); } }); // Clean up the packages directory too var releasesFile = Utility.LocalReleaseFileForAppDir(rootAppDirectory); var entries = ReleaseEntry.ParseReleaseFile(File.ReadAllText(releasesFile, Encoding.UTF8)); var pkgDir = Utility.PackageDirectoryForAppDir(rootAppDirectory); var releaseEntry = default(ReleaseEntry); foreach (var entry in entries) { if (entry.Version == currentVersion) { releaseEntry = ReleaseEntry.GenerateFromFile(Path.Combine(pkgDir, entry.Filename)); continue; } File.Delete(Path.Combine(pkgDir, entry.Filename)); } ReleaseEntry.WriteReleaseFile(new[] { releaseEntry }, releasesFile); }
public async Task FullUninstall() { var currentRelease = GetReleases().MaxBy(x => x.Name.ToSemanticVersion()).First(); Log.InfoFormat("Starting full uninstall"); if (currentRelease.Exists) { var version = currentRelease.Name.ToSemanticVersion(); try { var squirrelAwareApps = SquirrelAwareExecutableDetector.GetAllSquirrelAwareApps(currentRelease.FullName); if (IsAppFolderDead(currentRelease.FullName)) { throw new Exception("App folder is dead, but we're trying to uninstall it?"); } var allApps = currentRelease.EnumerateFiles() .Where(x => x.Name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) .Where( x => !x.Name.StartsWith("squirrel.", StringComparison.OrdinalIgnoreCase) && !x.Name.StartsWith("update.", StringComparison.OrdinalIgnoreCase)) .ToList(); if (squirrelAwareApps.Count > 0) { await squirrelAwareApps.ForEachAsync( async exe => { using (var cts = new CancellationTokenSource()) { cts.CancelAfter(10 * 1000); try { await Utility.InvokeProcessAsync(exe, $"--squirrel-uninstall {version}", cts.Token); } catch (Exception ex) { Log.Error("Failed to run cleanup hook, continuing: " + exe, ex); } } }, 1 /*at a time*/); } else { allApps.ForEach(x => RemoveShortcutsForExecutable(x.Name, ShortcutLocation.StartMenu | ShortcutLocation.Desktop)); } } catch (Exception ex) { Log.Warn("Failed to run pre-uninstall hooks, uninstalling anyways", ex); } } try { Log.ErrorIfThrows(() => FixPinnedExecutables(new SemanticVersion(255, 255, 255, 255), true)); } catch { } await Log.ErrorIfThrows( () => Utility.DeleteDirectoryOrJustGiveUp(rootAppDirectory), "Failed to delete app directory: " + rootAppDirectory); // NB: We drop this file here so that --checkInstall will ignore // this folder - if we don't do this, users who "accidentally" run as // administrator will find the app reinstalling itself on every // reboot if (!Directory.Exists(rootAppDirectory)) { Directory.CreateDirectory(rootAppDirectory); } File.WriteAllText(Path.Combine(rootAppDirectory, ".dead"), " "); }