LD-Uninstaller/src-csharp/LDUninstaller.Core/Bulk/BulkUninstallTask.cs

656 lines
24 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Runtime.CompilerServices;
using System.ServiceProcess;
using System.Threading;
using System.Threading.Tasks;
using LDUninstaller.Core.Algorithms;
using LDUninstaller.Core.Models;
using LDUninstaller.Core.Native;
namespace LDUninstaller.Core.Bulk
{
public enum BulkStatus
{
Queued,
Running,
Succeeded,
Failed,
Skipped,
Cancelled
}
public class BulkUninstallEntry : INotifyPropertyChanged
{
public ApplicationUninstallerEntry Entry { get; }
private BulkStatus _status = BulkStatus.Queued;
public BulkStatus Status
{
get => _status;
set
{
if (_status != value)
{
_status = value;
OnPropertyChanged();
OnPropertyChanged(nameof(StatusBadgeColor));
}
}
}
private string _statusMessage = "Kuyrukta";
public string StatusMessage
{
get => _statusMessage;
set
{
if (_statusMessage != value)
{
_statusMessage = value;
OnPropertyChanged();
}
}
}
public bool PreferQuiet { get; set; } = true;
public int ExitCode { get; set; } = -1;
public bool IsEffectivelyUninstalled { get; set; }
public string StatusBadgeColor => Status switch
{
BulkStatus.Succeeded => "#10B981",
BulkStatus.Failed => "#EF4444",
BulkStatus.Running => "#3B82F6",
BulkStatus.Cancelled => "#F59E0B",
_ => "#6B7280"
};
public BulkUninstallEntry(ApplicationUninstallerEntry entry, bool preferQuiet = true)
{
Entry = entry;
PreferQuiet = preferQuiet;
}
public event PropertyChangedEventHandler? PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string? name = null) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
public class BulkUninstallTask
{
public List<BulkUninstallEntry> Items { get; }
public int MaxConcurrentQuiet { get; set; } = 2;
public bool CreateRestorePoint { get; set; } = true;
public bool EnableAutomatizer { get; set; } = true;
public event Action<BulkUninstallEntry>? OnItemStarted;
public event Action<BulkUninstallEntry>? OnItemCompleted;
public event Action<string>? OnLog;
private readonly SemaphoreSlim _msiLock = new(1, 1);
private readonly SemaphoreSlim _loudLimitLock = new(1, 1);
private readonly object _stateLock = new();
private readonly HashSet<string> _activePublishers = new(StringComparer.OrdinalIgnoreCase);
private readonly HashSet<string> _activeDirectories = new(StringComparer.OrdinalIgnoreCase);
public BulkUninstallTask(IEnumerable<ApplicationUninstallerEntry> entries, bool preferQuiet = true)
{
Items = entries.Select(e => new BulkUninstallEntry(e, preferQuiet)).ToList();
}
public async Task ExecuteAsync(CancellationToken cancellationToken = default)
{
long restoreSeq = 0;
if (CreateRestorePoint)
{
OnLog?.Invoke("Sistem Geri Yükleme Noktası oluşturuluyor...");
await Task.Run(() => Win32.CreateRestorePoint("LD Uninstaller Bulk Pre-Restore Point", out restoreSeq));
}
if (EnableAutomatizer)
{
EnsureAutomatizerRunning();
}
var throttler = new SemaphoreSlim(MaxConcurrentQuiet, MaxConcurrentQuiet);
var runningTasks = new List<Task>();
try
{
foreach (var item in Items)
{
if (cancellationToken.IsCancellationRequested)
{
item.Status = BulkStatus.Cancelled;
item.StatusMessage = "İptal edildi";
continue;
}
bool isSerialized = IsSerializedType(item.Entry.UninstallerKind);
if (isSerialized)
{
await Task.WhenAll(runningTasks);
runningTasks.Clear();
await RunSingleItemAsync(item, cancellationToken);
}
else
{
await throttler.WaitAsync(cancellationToken);
var t = Task.Run(async () =>
{
try
{
await RunSingleItemAsync(item, cancellationToken);
}
finally
{
throttler.Release();
}
}, cancellationToken);
runningTasks.Add(t);
}
}
await Task.WhenAll(runningTasks);
}
finally
{
if (restoreSeq > 0)
{
Win32.EndRestorePoint(restoreSeq);
}
if (EnableAutomatizer)
{
StopAutomatizerDaemon();
}
OnLog?.Invoke("Tüm toplu kaldırma işlemleri tamamlandı.");
}
}
private async Task RunSingleItemAsync(BulkUninstallEntry item, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
item.Status = BulkStatus.Cancelled;
item.StatusMessage = "İptal edildi";
return;
}
string pub = Sift4.NormalizeName(item.Entry.Publisher);
bool pubAcquired = false;
string dir = !string.IsNullOrWhiteSpace(item.Entry.InstallLocation)
? Path.GetFullPath(item.Entry.InstallLocation).TrimEnd('\\')
: string.Empty;
while (!pubAcquired && !cancellationToken.IsCancellationRequested)
{
lock (_stateLock)
{
bool pubConflict = !string.IsNullOrWhiteSpace(pub) && _activePublishers.Contains(pub);
bool dirConflict = !string.IsNullOrWhiteSpace(dir) && _activeDirectories.Any(d =>
d.Equals(dir, StringComparison.OrdinalIgnoreCase) ||
dir.StartsWith(d + "\\", StringComparison.OrdinalIgnoreCase) ||
d.StartsWith(dir + "\\", StringComparison.OrdinalIgnoreCase));
if (!pubConflict && !dirConflict)
{
if (!string.IsNullOrWhiteSpace(pub)) _activePublishers.Add(pub);
if (!string.IsNullOrWhiteSpace(dir)) _activeDirectories.Add(dir);
pubAcquired = true;
}
}
if (!pubAcquired)
{
await Task.Delay(500, cancellationToken);
}
}
bool msiLocked = false;
if (item.Entry.UninstallerKind == UninstallerType.Msiexec)
{
await _msiLock.WaitAsync(cancellationToken);
msiLocked = true;
await WaitForActiveMsiProcesses(cancellationToken);
}
bool isQuiet = item.PreferQuiet && !string.IsNullOrWhiteSpace(item.Entry.QuietUninstallString);
bool loudLocked = false;
if (!isQuiet)
{
await _loudLimitLock.WaitAsync(cancellationToken);
loudLocked = true;
}
try
{
item.Status = BulkStatus.Running;
item.StatusMessage = "Çalıştırılıyor...";
OnItemStarted?.Invoke(item);
OnLog?.Invoke($"Kaldırma başladı: {item.Entry.DisplayName}");
// Pre-kill locking processes in install folder (B9, P9)
PreKillLockingProcesses(item.Entry);
// Stop services in install folder (B9)
PreStopServices(item.Entry);
// Execute Uninstaller Process
int exitCode = await ExecuteUninstallerProcessAsync(item, cancellationToken);
item.ExitCode = exitCode;
// B18: Valid exit codes for success: 0, 1605 (already uninstalled), 1641, 3010
bool exitCodeSuccess = exitCode == 0 || exitCode == 1605 || exitCode == 1641 || exitCode == 3010;
// B3: Verify whether it is effectively uninstalled
bool isTargetGone = IsTargetEffectivelyRemoved(item.Entry);
if (exitCodeSuccess || isTargetGone)
{
item.IsEffectivelyUninstalled = true;
item.Status = BulkStatus.Succeeded;
item.StatusMessage = (exitCode == 3010 || exitCode == 1641)
? "Başarılı (Yeniden başlatma gerekli)"
: "Başarıyla kaldırıldı";
}
else
{
item.IsEffectivelyUninstalled = false;
item.Status = BulkStatus.Failed;
item.StatusMessage = $"Hata (Çıkış kodu: {exitCode})";
}
}
catch (OperationCanceledException)
{
item.Status = BulkStatus.Cancelled;
item.StatusMessage = "İptal edildi";
}
catch (Exception ex)
{
item.Status = BulkStatus.Failed;
item.StatusMessage = $"Hata: {ex.Message}";
}
finally
{
lock (_stateLock)
{
if (!string.IsNullOrWhiteSpace(pub)) _activePublishers.Remove(pub);
if (!string.IsNullOrWhiteSpace(dir)) _activeDirectories.Remove(dir);
}
if (msiLocked) _msiLock.Release();
if (loudLocked) _loudLimitLock.Release();
OnItemCompleted?.Invoke(item);
OnLog?.Invoke($"Tamamlandı [{item.Status}]: {item.Entry.DisplayName}");
}
}
private static bool IsTargetEffectivelyRemoved(ApplicationUninstallerEntry entry)
{
// If install directory was populated and is now gone:
if (!string.IsNullOrWhiteSpace(entry.InstallLocation) && !Directory.Exists(entry.InstallLocation))
return true;
// If registry key existed and is now gone:
if (!string.IsNullOrWhiteSpace(entry.RegistryPath))
{
try
{
var (hive, subKey, view) = RegistryJunkResult.ParseRegistryPath(entry.RegistryPath);
using var baseKey = Microsoft.Win32.RegistryKey.OpenBaseKey(hive, view);
using var key = baseKey.OpenSubKey(subKey);
if (key == null) return true;
}
catch { }
}
return false;
}
private async Task<int> ExecuteUninstallerProcessAsync(BulkUninstallEntry item, CancellationToken token)
{
string command = item.PreferQuiet && !string.IsNullOrWhiteSpace(item.Entry.QuietUninstallString)
? item.Entry.QuietUninstallString
: item.Entry.UninstallString;
if (string.IsNullOrWhiteSpace(command))
{
// Simple delete fallback for orphaned software (only if specifically marked orphaned)
if (item.Entry.IsOrphaned && Directory.Exists(item.Entry.InstallLocation) && !Junk.SafetyBlacklist.IsDangerousDirectory(item.Entry.InstallLocation))
{
try
{
Win32.SendToRecycleBin(item.Entry.InstallLocation);
return 0;
}
catch { return -1; }
}
return -1;
}
// B18: Protocol commands like steam://
if (command.StartsWith("steam://", StringComparison.OrdinalIgnoreCase))
{
try
{
Process.Start(new ProcessStartInfo(command) { UseShellExecute = true });
await Task.Delay(4000, token);
return 0;
}
catch
{
return -1;
}
}
var (fileName, args) = SplitCommand(command);
var psi = new ProcessStartInfo
{
FileName = fileName,
Arguments = args,
UseShellExecute = true,
CreateNoWindow = item.PreferQuiet
};
if (!string.IsNullOrWhiteSpace(item.Entry.InstallLocation) && Directory.Exists(item.Entry.InstallLocation))
{
psi.WorkingDirectory = item.Entry.InstallLocation;
}
Process? process = null;
try
{
process = Process.Start(psi);
}
catch (Exception ex)
{
OnLog?.Invoke($"Çalıştırma hatası ({fileName}): {ex.Message}");
return -1;
}
if (process == null) return -1;
using (process)
{
if (EnableAutomatizer)
{
NotifyAutomatizerDaemon(process.Id);
}
var sw = Stopwatch.StartNew();
// Wait for main process
try
{
await process.WaitForExitAsync(token);
}
catch (OperationCanceledException)
{
try { Win32.GentleKillProcess(process, 1500); } catch { }
throw;
}
int exitCode = process.ExitCode;
// B4: Watch for child / temp uninstaller processes (Inno Setup / NSIS)
if (sw.ElapsedMilliseconds < 4000 && (exitCode == 0 || exitCode == 3010))
{
await WaitForPotentialChildUninstallers(item.Entry, token);
}
return exitCode;
}
}
private static async Task WaitForPotentialChildUninstallers(ApplicationUninstallerEntry entry, CancellationToken token)
{
string tempDir = Path.GetTempPath();
for (int i = 0; i < 30; i++)
{
if (token.IsCancellationRequested) break;
bool childActive = false;
try
{
// Inno Setup spawns _iu*.tmp processes
// NSIS spawns Au_.exe processes
var procs = Process.GetProcesses();
foreach (var p in procs)
{
using (p)
{
try
{
string name = p.ProcessName.ToLowerInvariant();
if (name.StartsWith("_iu") || name.Equals("au_") || name.Contains("uninstall"))
{
string? path = Win32.GetProcessPath(p.Id);
if (!string.IsNullOrEmpty(path) && path.StartsWith(tempDir, StringComparison.OrdinalIgnoreCase))
{
childActive = true;
break;
}
}
}
catch { }
}
}
}
catch { }
if (!childActive)
{
if (i >= 2) break; // If no child after a couple seconds, assume finished
}
await Task.Delay(1000, token);
}
}
private static void EnsureAutomatizerRunning()
{
_ = Task.Run(() =>
{
try
{
var existing = Process.GetProcessesByName("LDUninstaller.Automatizer");
if (existing.Length > 0)
{
foreach (var p in existing) p.Dispose();
return;
}
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string autoExe = Path.Combine(baseDir, "LDUninstaller.Automatizer.exe");
if (File.Exists(autoExe))
{
Process.Start(new ProcessStartInfo(autoExe, "--daemon")
{
UseShellExecute = false,
CreateNoWindow = true
});
}
}
catch { }
});
}
private static void StopAutomatizerDaemon()
{
_ = Task.Run(() =>
{
try
{
using var client = new NamedPipeClientStream(".", "LDUninstallerDaemon", PipeDirection.Out);
client.Connect(500);
using var writer = new StreamWriter(client);
writer.WriteLine("SHUTDOWN");
writer.Flush();
}
catch { }
});
}
private static void NotifyAutomatizerDaemon(int pid)
{
_ = Task.Run(() =>
{
try
{
using var client = new NamedPipeClientStream(".", "LDUninstallerDaemon", PipeDirection.Out);
client.Connect(1000);
using var writer = new StreamWriter(client);
writer.WriteLine($"ATTACH:{pid}");
writer.Flush();
}
catch { }
});
}
private static void PreKillLockingProcesses(ApplicationUninstallerEntry entry)
{
if (string.IsNullOrWhiteSpace(entry.InstallLocation) || !Directory.Exists(entry.InstallLocation))
return;
try
{
// B9: Add trailing directory separator so C:\Foo doesn't kill C:\FooBar
string norm = Path.GetFullPath(entry.InstallLocation).TrimEnd('\\') + Path.DirectorySeparatorChar;
int currentPid = Process.GetCurrentProcess().Id;
var procs = Process.GetProcesses();
foreach (var p in procs)
{
using (p)
{
try
{
if (p.Id == currentPid) continue;
// P9: Use Win32 QueryFullProcessImageName to avoid Access Denied Win32Exceptions
string? exePath = Win32.GetProcessPath(p.Id);
if (!string.IsNullOrWhiteSpace(exePath))
{
if (Path.GetFullPath(exePath).StartsWith(norm, StringComparison.OrdinalIgnoreCase))
{
Win32.GentleKillProcess(p, 2000);
}
}
}
catch { }
}
}
}
catch { }
}
private static void PreStopServices(ApplicationUninstallerEntry entry)
{
if (string.IsNullOrWhiteSpace(entry.InstallLocation) || !Directory.Exists(entry.InstallLocation))
return;
try
{
// B9: Add trailing separator and parse clean ImagePath
string norm = Path.GetFullPath(entry.InstallLocation).TrimEnd('\\') + Path.DirectorySeparatorChar;
var services = ServiceController.GetServices();
foreach (var sc in services)
{
using (sc)
{
try
{
using var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey($@"SYSTEM\CurrentControlSet\Services\{sc.ServiceName}");
string? rawPath = key?.GetValue("ImagePath")?.ToString();
if (!string.IsNullOrWhiteSpace(rawPath))
{
string cleanPath = rawPath.Replace("\"", "").Trim();
if (cleanPath.StartsWith(@"\??\")) cleanPath = cleanPath.Substring(4);
int exeIdx = cleanPath.IndexOf(".exe", StringComparison.OrdinalIgnoreCase);
if (exeIdx > 0) cleanPath = cleanPath.Substring(0, exeIdx + 4).Trim();
if (cleanPath.StartsWith(norm, StringComparison.OrdinalIgnoreCase))
{
if (sc.Status == ServiceControllerStatus.Running)
{
sc.Stop();
sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(3));
}
}
}
}
catch { }
}
}
}
catch { }
}
private static async Task WaitForActiveMsiProcesses(CancellationToken token)
{
// B15: Timeout after 60 seconds
var sw = Stopwatch.StartNew();
while (!token.IsCancellationRequested && sw.ElapsedMilliseconds < 60000)
{
var msiProcs = Process.GetProcessesByName("msiexec");
int count = msiProcs.Length;
foreach (var p in msiProcs) p.Dispose();
if (count <= 1)
break;
await Task.Delay(1000, token);
}
}
private static bool IsSerializedType(UninstallerType type)
{
return type is UninstallerType.WindowsFeature
or UninstallerType.WindowsUpdate
or UninstallerType.InstallShield
or UninstallerType.SdbInst
or UninstallerType.PowerShell;
}
private static (string fileName, string arguments) SplitCommand(string command)
{
string trimmed = command.Trim();
if (trimmed.StartsWith("\""))
{
int endQuote = trimmed.IndexOf('\"', 1);
if (endQuote > 0)
{
string file = trimmed.Substring(1, endQuote - 1);
string args = endQuote + 1 < trimmed.Length ? trimmed[(endQuote + 1)..].Trim() : "";
return (file, args);
}
}
int space = trimmed.IndexOf(' ');
if (space > 0)
{
return (trimmed[..space], trimmed[(space + 1)..].Trim());
}
return (trimmed, "");
}
}
}