LD-Uninstaller/src-csharp/LDUninstaller.Core/Services/FileUnlockerService.cs

606 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.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.ServiceProcess;
using System.Threading;
using LDUninstaller.Core.Junk;
using LDUninstaller.Core.Native;
using Microsoft.Win32;
namespace LDUninstaller.Core.Services
{
public class ProcessLockInfo
{
public int ProcessId { get; set; }
public string ProcessName { get; set; } = string.Empty;
public string ExecutablePath { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public bool IsService { get; set; }
public string ServiceName { get; set; } = string.Empty;
}
public class UnlockAndDestroyResult
{
public bool Success { get; set; }
public string TargetPath { get; set; } = string.Empty;
public int KilledProcessesCount { get; set; }
public int StoppedServicesCount { get; set; }
public int DeletedFilesCount { get; set; }
public List<string> ErrorMessages { get; } = new();
public bool ScheduledForReboot { get; set; }
}
public static class FileUnlockerService
{
#region Windows Restart Manager Interop
private const int CCH_RM_SESSION_KEY = 32;
[DllImport("rstrtmgr.dll", CharSet = CharSet.Unicode)]
private static extern int RmStartSession(out uint pSessionHandle, int dwSessionFlags, string strSessionKey);
[DllImport("rstrtmgr.dll", CharSet = CharSet.Unicode)]
private static extern int RmRegisterResources(
uint pSessionHandle,
uint nFiles,
string[]? rgsFileNames,
uint nApplications,
RM_UNIQUE_PROCESS[]? rgApplications,
uint nServices,
string[]? rgsServiceNames);
[DllImport("rstrtmgr.dll")]
private static extern int RmGetList(
uint pSessionHandle,
out uint pnProcInfoNeeded,
ref uint pnProcInfo,
[In, Out] RM_PROCESS_INFO[]? rgAffectedApps,
out uint lpdwRebootReasons);
[DllImport("rstrtmgr.dll")]
private static extern int RmEndSession(uint pSessionHandle);
[StructLayout(LayoutKind.Sequential)]
private struct RM_UNIQUE_PROCESS
{
public int dwProcessId;
public System.Runtime.InteropServices.ComTypes.FILETIME ProcessStartTime;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct RM_PROCESS_INFO
{
public RM_UNIQUE_PROCESS Process;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string strAppName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
public string strServiceShortName;
public int ApplicationType;
public uint AppStatus;
public uint TSSessionId;
[MarshalAs(UnmanagedType.Bool)]
public bool bRestartable;
}
#endregion
/// <summary>
/// Kısayol (.lnk) veya dosya/klasör yolunu analiz ederek asıl kurulum klasörünü ve hedefi çözümler.
/// </summary>
public static (string targetFolder, string? primaryFile, string? originalLnk) ResolveTarget(string inputPath)
{
if (string.IsNullOrWhiteSpace(inputPath))
return (string.Empty, null, null);
string norm = Path.GetFullPath(inputPath).TrimEnd('\\');
// Eğer .lnk kısayolu ise, hedef exe'yi ve onun üst klasörünü çöz
if (norm.EndsWith(".lnk", StringComparison.OrdinalIgnoreCase) && File.Exists(norm))
{
string? resolved = ResolveShortcutTarget(norm);
if (!string.IsNullOrWhiteSpace(resolved))
{
if (Directory.Exists(resolved))
{
return (resolved, null, norm);
}
if (File.Exists(resolved))
{
string? parent = Path.GetDirectoryName(resolved);
if (!string.IsNullOrWhiteSpace(parent) && Directory.Exists(parent))
{
return (parent, resolved, norm);
}
}
}
}
// Normal dosya ise üst klasörünü hedef klasör al (ör. C:\Program Files\App\app.exe)
if (File.Exists(norm))
{
string? parent = Path.GetDirectoryName(norm);
if (!string.IsNullOrWhiteSpace(parent) && Directory.Exists(parent))
{
return (parent, norm, null);
}
}
// Normal klasör ise doğrudan kendisi
return (norm, null, null);
}
public static string? ResolveShortcutTarget(string lnkPath)
{
try
{
Type? shellType = Type.GetTypeFromProgID("WScript.Shell");
if (shellType != null)
{
dynamic? shell = Activator.CreateInstance(shellType);
if (shell != null)
{
dynamic? shortcut = shell.CreateShortcut(lnkPath);
string? target = shortcut?.TargetPath;
if (!string.IsNullOrWhiteSpace(target))
return target;
}
}
}
catch { }
return null;
}
/// <summary>
/// Hedef klasör ve içindeki dosyaları o an kilitleyen tüm süreçleri ve servisleri listeler.
/// </summary>
public static List<ProcessLockInfo> InspectLocks(string targetPath)
{
var results = new Dictionary<int, ProcessLockInfo>();
if (string.IsNullOrWhiteSpace(targetPath) || (!Directory.Exists(targetPath) && !File.Exists(targetPath)))
return results.Values.ToList();
string normDir = Path.GetFullPath(targetPath).TrimEnd('\\');
// 1. Klasör içi imaj yoluna sahip süreçler
try
{
foreach (var proc in Process.GetProcesses())
{
try
{
string? img = Win32.GetProcessPath(proc.Id);
if (!string.IsNullOrEmpty(img))
{
string normImg = img.TrimEnd('\\');
if (normImg.StartsWith(normDir + "\\", StringComparison.OrdinalIgnoreCase) ||
normImg.Equals(normDir, StringComparison.OrdinalIgnoreCase))
{
if (!results.ContainsKey(proc.Id))
{
results[proc.Id] = new ProcessLockInfo
{
ProcessId = proc.Id,
ProcessName = proc.ProcessName,
ExecutablePath = img,
Description = "Klasör içinde çalışan aktif süreç"
};
}
}
}
}
catch { }
finally { proc.Dispose(); }
}
}
catch { }
// 2. Windows Restart Manager ile kilitli DLL/dosya tutan dış süreçler
try
{
var filesToCheck = new List<string>();
if (File.Exists(targetPath))
{
filesToCheck.Add(targetPath);
}
else if (Directory.Exists(targetPath))
{
// En kritik kilit adaylarını topla (exe, dll, sys, log, db)
var topFiles = Directory.EnumerateFiles(targetPath, "*.*", SearchOption.AllDirectories)
.Where(f =>
{
string ext = Path.GetExtension(f).ToLowerInvariant();
return ext is ".exe" or ".dll" or ".sys" or ".dat" or ".db" or ".log";
})
.Take(64)
.ToList();
filesToCheck.AddRange(topFiles);
}
if (filesToCheck.Count > 0)
{
var rmProcs = GetProcessesLockingFilesWithRm(filesToCheck);
foreach (var rm in rmProcs)
{
if (!results.ContainsKey(rm.ProcessId))
results[rm.ProcessId] = rm;
}
}
}
catch { }
// 3. Klasör içi dosyaları kullanan Windows Servisleri
try
{
var services = FindServicesInDirectory(normDir);
foreach (var s in services)
{
// Servise ait bir PID varsa listeye ekle veya yeni bilgi oluştur
if (s.ProcessId > 0 && results.TryGetValue(s.ProcessId, out var existing))
{
existing.IsService = true;
existing.ServiceName = s.ServiceName;
}
else
{
results[s.ProcessId > 0 ? s.ProcessId : -Math.Abs(s.ServiceName.GetHashCode())] = s;
}
}
}
catch { }
return results.Values.ToList();
}
/// <summary>
/// 4 Aşamalı kilit kırma boru hattını çalıştırır, süreç ve servisleri sonlandırır ve klasörü tamamen siler.
/// </summary>
public static UnlockAndDestroyResult UnlockAndDestroy(
string targetPath,
bool sendToRecycleBin = true,
Action<string>? onLog = null)
{
var res = new UnlockAndDestroyResult { TargetPath = targetPath };
if (string.IsNullOrWhiteSpace(targetPath) || (!Directory.Exists(targetPath) && !File.Exists(targetPath)))
{
res.Success = true;
return res;
}
// GÜVENLİK KALKANI: Kritik sistem veya kullanıcı kök dizini ise asla silme!
if (SafetyBlacklist.IsDangerousDirectory(targetPath))
{
string msg = $"GÜVENLİK ENGELİ: '{targetPath}' kritik bir Windows sistem veya profil kök dizinidir ve silinemez!";
onLog?.Invoke(msg);
res.ErrorMessages.Add(msg);
res.Success = false;
return res;
}
string normPath = Path.GetFullPath(targetPath).TrimEnd('\\');
onLog?.Invoke($"[1/4] Kilit kırma başlatılıyor: {normPath}");
// AŞAMA 1 & 2: Süreçleri Sonlandırma (Restart Manager + Process Tree Kill)
var locks = InspectLocks(normPath);
int currentPid = Process.GetCurrentProcess().Id;
foreach (var lockInfo in locks)
{
if (lockInfo.ProcessId <= 4 || lockInfo.ProcessId == currentPid)
continue;
// explorer.exe kontrolü
if (lockInfo.ProcessName.Equals("explorer", StringComparison.OrdinalIgnoreCase))
{
onLog?.Invoke("Dosya Gezgini (explorer.exe) kilit tutuyor; tutamaç serbest bırakılacak.");
continue;
}
try
{
using var proc = Process.GetProcessById(lockInfo.ProcessId);
onLog?.Invoke($"Süreç sonlandırılıyor: {proc.ProcessName} (PID: {proc.Id})");
proc.Kill(entireProcessTree: true);
proc.WaitForExit(1500);
res.KilledProcessesCount++;
}
catch { }
}
// AŞAMA 3: İlgili Windows Servislerini Durdurma ve Kaldırma
var services = FindServicesInDirectory(normPath);
foreach (var svc in services)
{
try
{
onLog?.Invoke($"Servis durduruluyor ve kaldırılıyor: {svc.ServiceName}");
using var sc = new ServiceController(svc.ServiceName);
if (sc.Status != ServiceControllerStatus.Stopped && sc.Status != ServiceControllerStatus.StopPending)
{
sc.Stop();
sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(3));
}
// sc delete ile servisi sistemden temizle
RunCommandSilent("sc.exe", $"delete \"{svc.ServiceName}\"");
res.StoppedServicesCount++;
}
catch { }
}
// AŞAMA 4: İzinleri Sıfırlama ve Agresif Silme Döngüsü
onLog?.Invoke("[4/4] Dosya öznitelikleri sıfırlanıyor ve sahiplik alınıyor...");
ResetAttributesAndTakeOwnership(normPath);
// 5 Aşamalı Agresif Silme Döngüsü
for (int attempt = 1; attempt <= 5; attempt++)
{
if (!Directory.Exists(normPath) && !File.Exists(normPath))
{
res.Success = true;
onLog?.Invoke("Hedef başarıyla silindi ve yok edildi!");
return res;
}
onLog?.Invoke($"Silme denemesi {attempt}/5...");
bool deleted = false;
if (sendToRecycleBin)
{
deleted = Win32.SendToRecycleBin(normPath);
}
if (!deleted)
{
try
{
if (File.Exists(normPath))
{
File.Delete(normPath);
deleted = !File.Exists(normPath);
}
else if (Directory.Exists(normPath))
{
Directory.Delete(normPath, true);
deleted = !Directory.Exists(normPath);
}
}
catch (Exception ex)
{
res.ErrorMessages.Add($"Deneme {attempt} hatası: {ex.Message}");
}
}
if (deleted || (!Directory.Exists(normPath) && !File.Exists(normPath)))
{
res.Success = true;
onLog?.Invoke("Hedef klasör tamamen temizlendi.");
return res;
}
// Silinemeyen dosya kaldıysa tekrar Restart Manager ile kilitleyen süreci avla
var remainingLocks = InspectLocks(normPath);
foreach (var rmProc in remainingLocks)
{
if (rmProc.ProcessId > 4 && rmProc.ProcessId != currentPid && !rmProc.ProcessName.Equals("explorer", StringComparison.OrdinalIgnoreCase))
{
try
{
using var p = Process.GetProcessById(rmProc.ProcessId);
p.Kill(entireProcessTree: true);
res.KilledProcessesCount++;
}
catch { }
}
}
Thread.Sleep(300);
}
// Eğer hala silinemeyen bir kernel driver veya sistem dosyası kaldıysa, yeniden başlatmada silinmeye ayarla
if (Directory.Exists(normPath) || File.Exists(normPath))
{
onLog?.Invoke("Bazı dosyalar çekirdek düzeyinde kilitli; ilk sistem yeniden başlatmasında (MoveFileEx) silinmek üzere zamanlanıyor...");
ScheduleAllForRebootDelete(normPath);
res.ScheduledForReboot = true;
res.Success = true;
}
return res;
}
private static List<ProcessLockInfo> GetProcessesLockingFilesWithRm(List<string> filePaths)
{
var list = new List<ProcessLockInfo>();
string sessionKey = Guid.NewGuid().ToString();
int res = RmStartSession(out uint sessionHandle, 0, sessionKey);
if (res != 0) return list;
try
{
int regRes = RmRegisterResources(sessionHandle, (uint)filePaths.Count, filePaths.ToArray(), 0, null, 0, null);
if (regRes != 0) return list;
uint procInfoNeeded = 0;
uint procInfo = 0;
RM_PROCESS_INFO[]? processInfo = null;
res = RmGetList(sessionHandle, out procInfoNeeded, ref procInfo, processInfo, out uint rebootReasons);
if (res == 234) // ERROR_MORE_DATA
{
processInfo = new RM_PROCESS_INFO[procInfoNeeded];
procInfo = procInfoNeeded;
res = RmGetList(sessionHandle, out procInfoNeeded, ref procInfo, processInfo, out rebootReasons);
}
if (res == 0 && processInfo != null)
{
foreach (var pi in processInfo)
{
int pid = pi.Process.dwProcessId;
if (pid <= 4) continue;
string exePath = Win32.GetProcessPath(pid) ?? "";
list.Add(new ProcessLockInfo
{
ProcessId = pid,
ProcessName = string.IsNullOrEmpty(pi.strAppName) ? Path.GetFileNameWithoutExtension(exePath) : pi.strAppName,
ExecutablePath = exePath,
ServiceName = pi.strServiceShortName,
IsService = !string.IsNullOrEmpty(pi.strServiceShortName),
Description = "Restart Manager tarafından yakalanan kilitli süreç"
});
}
}
}
finally
{
RmEndSession(sessionHandle);
}
return list;
}
private static List<ProcessLockInfo> FindServicesInDirectory(string dirPath)
{
var services = new List<ProcessLockInfo>();
string normDir = dirPath.TrimEnd('\\');
try
{
using var servicesKey = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services");
if (servicesKey == null) return services;
foreach (var svcName in servicesKey.GetSubKeyNames())
{
try
{
using var svcKey = servicesKey.OpenSubKey(svcName);
string? imagePath = svcKey?.GetValue("ImagePath")?.ToString();
if (string.IsNullOrWhiteSpace(imagePath)) continue;
string clean = imagePath.Replace("\"", "").Trim();
if (clean.StartsWith(@"\??\")) clean = clean.Substring(4);
int exeIdx = clean.IndexOf(".exe", StringComparison.OrdinalIgnoreCase);
if (exeIdx > 0) clean = clean.Substring(0, exeIdx + 4).Trim();
if (clean.StartsWith(normDir + "\\", StringComparison.OrdinalIgnoreCase) ||
clean.Equals(normDir, StringComparison.OrdinalIgnoreCase))
{
int pid = GetServicePid(svcName);
services.Add(new ProcessLockInfo
{
ProcessId = pid,
ProcessName = svcName,
ExecutablePath = clean,
ServiceName = svcName,
IsService = true,
Description = $"Windows Servisi ({svcName})"
});
}
}
catch { }
}
}
catch { }
return services;
}
private static int GetServicePid(string serviceName)
{
try
{
using var sc = new ServiceController(serviceName);
// ServiceProcessId is available via reflection or sc queryex
string output = RunCommandSilent("sc.exe", $"queryex \"{serviceName}\"");
foreach (var line in output.Split('\n'))
{
if (line.Contains("PID", StringComparison.OrdinalIgnoreCase))
{
int colon = line.IndexOf(':');
if (colon > 0 && int.TryParse(line.Substring(colon + 1).Trim(), out int pid))
return pid;
}
}
}
catch { }
return 0;
}
private static void ResetAttributesAndTakeOwnership(string path)
{
try
{
if (File.Exists(path))
{
File.SetAttributes(path, FileAttributes.Normal);
}
else if (Directory.Exists(path))
{
var di = new DirectoryInfo(path) { Attributes = FileAttributes.Normal };
foreach (var info in di.GetFileSystemInfos("*", SearchOption.AllDirectories))
{
try { info.Attributes = FileAttributes.Normal; } catch { }
}
// Sahiplik alma (Take Ownership)
RunCommandSilent("takeown.exe", $"/f \"{path}\" /r /d y");
RunCommandSilent("icacls.exe", $"\"{path}\" /grant administrators:F /t /c /q");
}
}
catch { }
}
private static void ScheduleAllForRebootDelete(string path)
{
try
{
if (File.Exists(path))
{
Win32.MoveFileEx(path, null, Win32.MOVEFILE_DELAY_UNTIL_REBOOT);
}
else if (Directory.Exists(path))
{
foreach (var file in Directory.GetFiles(path, "*.*", SearchOption.AllDirectories))
{
Win32.MoveFileEx(file, null, Win32.MOVEFILE_DELAY_UNTIL_REBOOT);
}
foreach (var dir in Directory.GetDirectories(path, "*", SearchOption.AllDirectories).OrderByDescending(d => d.Length))
{
Win32.MoveFileEx(dir, null, Win32.MOVEFILE_DELAY_UNTIL_REBOOT);
}
Win32.MoveFileEx(path, null, Win32.MOVEFILE_DELAY_UNTIL_REBOOT);
}
}
catch { }
}
private static string RunCommandSilent(string fileName, string arguments)
{
try
{
var psi = new ProcessStartInfo(fileName, arguments)
{
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
using var proc = Process.Start(psi);
if (proc == null) return string.Empty;
string output = proc.StandardOutput.ReadToEnd();
proc.WaitForExit(3000);
return output;
}
catch
{
return string.Empty;
}
}
}
}