public void WeCanFetchAllProcesses()
        {
            var result = UnsafeUtility.EnumerateProcesses();

            Assert.True(result.Count > 1);
            Assert.True(result.Count != 2048);
        }
Beispiel #2
0
            public void KillAllProcessesBelongingToPackage()
            {
                var ourExe     = Assembly.GetEntryAssembly();
                var ourExePath = ourExe != null
                    ? ourExe.Location
                    : null;

                UnsafeUtility.EnumerateProcesses()
                .Where(
                    x =>
                {
                    // Processes we can't query will have an empty process name, we can't kill them
                    // anyways
                    if (string.IsNullOrWhiteSpace(x.Item1))
                    {
                        return(false);
                    }

                    // Files that aren't in our root app directory are untouched
                    if (!x.Item1.StartsWith(rootAppDirectory, StringComparison.OrdinalIgnoreCase))
                    {
                        return(false);
                    }

                    // Never kill our own EXE
                    if (ourExePath != null && x.Item1.Equals(ourExePath, StringComparison.OrdinalIgnoreCase))
                    {
                        return(false);
                    }

                    var name = Path.GetFileName(x.Item1).ToLowerInvariant();
                    if (name == "squirrel.exe" || name == "update.exe")
                    {
                        return(false);
                    }

                    return(true);
                })
                .ForEach(
                    x =>
                {
                    try
                    {
                        Log.WarnIfThrows(() => Process.GetProcessById(x.Item2).Kill());
                    }
                    catch
                    {
                    }
                });
            }
            // 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);
            }