-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathProcessControlService.cs
More file actions
490 lines (425 loc) · 17.7 KB
/
ProcessControlService.cs
File metadata and controls
490 lines (425 loc) · 17.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.ServiceProcess;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace TidyWindow.App.Services;
/// <summary>
/// Issues start/stop/restart commands for Windows services that back the Known Processes tab.
/// </summary>
public sealed class ProcessControlService
{
private static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(25);
private static readonly string OriginalStartTypesPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"TidyWindow", "service-original-starttypes.json");
/// <summary>
/// Remembers the original start type of each service before we disabled it,
/// so we can restore it accurately when the user switches back to Keep.
/// Maps service name → sc.exe start type string (e.g. "auto", "demand", "delayed-auto").
/// </summary>
private readonly ConcurrentDictionary<string, string> _originalStartTypes;
public ProcessControlService()
: this(OriginalStartTypesPath)
{
}
/// <summary>Internal constructor for testing — accepts a custom persistence path.</summary>
internal ProcessControlService(string startTypesFilePath)
{
_startTypesFilePath = startTypesFilePath;
_originalStartTypes = LoadOriginalStartTypes(startTypesFilePath);
}
private readonly string _startTypesFilePath;
public Task<ProcessControlResult> StopAsync(string serviceName, TimeSpan? timeout = null, CancellationToken cancellationToken = default)
{
return Task.Run(() => ControlService(serviceName, timeout, (controller, effectiveTimeout) =>
{
controller.Refresh();
if (controller.StartType == ServiceStartMode.Disabled)
{
return ProcessControlResult.CreateSuccess($"{serviceName} is disabled; skipping stop.");
}
if (controller.Status == ServiceControllerStatus.Stopped)
{
return ProcessControlResult.CreateSuccess($"{serviceName} is already stopped.");
}
controller.Stop();
controller.WaitForStatus(ServiceControllerStatus.Stopped, effectiveTimeout);
return ProcessControlResult.CreateSuccess($"Stopped {serviceName}.");
}), cancellationToken);
}
public Task<ProcessControlResult> StartAsync(string serviceName, TimeSpan? timeout = null, CancellationToken cancellationToken = default)
{
return Task.Run(() => ControlService(serviceName, timeout, (controller, effectiveTimeout) =>
{
controller.Refresh();
if (controller.StartType == ServiceStartMode.Disabled)
{
return ProcessControlResult.CreateFailure($"{serviceName} is disabled and cannot be started.");
}
if (controller.Status is ServiceControllerStatus.Running or ServiceControllerStatus.StartPending)
{
return ProcessControlResult.CreateSuccess($"{serviceName} is already running.");
}
controller.Start();
controller.WaitForStatus(ServiceControllerStatus.Running, effectiveTimeout);
return ProcessControlResult.CreateSuccess($"Started {serviceName}.");
}), cancellationToken);
}
public async Task<ProcessControlResult> RestartAsync(string serviceName, TimeSpan? timeout = null, CancellationToken cancellationToken = default)
{
// First check if the service is disabled before attempting restart.
var disabledCheck = await Task.Run(() =>
{
if (!OperatingSystem.IsWindows() || string.IsNullOrWhiteSpace(serviceName))
{
return (IsDisabled: false, Message: string.Empty);
}
try
{
using var controller = new ServiceController(serviceName.Trim());
controller.Refresh();
if (controller.StartType == ServiceStartMode.Disabled)
{
return (IsDisabled: true, Message: $"{serviceName} is disabled and cannot be restarted.");
}
}
catch
{
// If we can't check, proceed with normal restart flow.
}
return (IsDisabled: false, Message: string.Empty);
}, cancellationToken).ConfigureAwait(false);
if (disabledCheck.IsDisabled)
{
return ProcessControlResult.CreateFailure(disabledCheck.Message);
}
var stopResult = await StopAsync(serviceName, timeout, cancellationToken).ConfigureAwait(false);
if (!stopResult.Success)
{
return stopResult;
}
return await StartAsync(serviceName, timeout, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Stops a service and disables it so Windows cannot restart it via recovery policies.
/// </summary>
public Task<ProcessControlResult> StopAndDisableAsync(string serviceName, TimeSpan? timeout = null, CancellationToken cancellationToken = default)
{
return Task.Run(() => ControlService(serviceName, timeout, (controller, effectiveTimeout) =>
{
controller.Refresh();
if (controller.StartType == ServiceStartMode.Disabled && controller.Status == ServiceControllerStatus.Stopped)
{
return ProcessControlResult.CreateSuccess($"{serviceName} is already disabled and stopped.");
}
// Save the original start type BEFORE disabling, so we can restore it later.
SaveOriginalStartType(serviceName, controller.StartType);
if (controller.Status is not (ServiceControllerStatus.Stopped or ServiceControllerStatus.StopPending))
{
controller.Stop();
controller.WaitForStatus(ServiceControllerStatus.Stopped, effectiveTimeout);
}
// Disable via sc.exe — ServiceController doesn't expose StartType mutation.
var disableResult = SetServiceStartType(serviceName, "disabled");
// Clear recovery actions so Windows doesn't auto-restart the service.
ClearServiceRecoveryActions(serviceName);
if (!disableResult)
{
return ProcessControlResult.CreateSuccess($"Stopped {serviceName} but could not disable it.");
}
return ProcessControlResult.CreateSuccess($"Stopped and disabled {serviceName}.");
}), cancellationToken);
}
/// <summary>
/// Re-enables a previously disabled service by setting its start type to Manual (demand).
/// Optionally starts it afterward.
/// </summary>
public Task<ProcessControlResult> EnableAsync(string serviceName, bool startAfterEnable = false, TimeSpan? timeout = null, CancellationToken cancellationToken = default)
{
return Task.Run(() => ControlService(serviceName, timeout, (controller, effectiveTimeout) =>
{
controller.Refresh();
// Only re-enable if currently disabled.
if (controller.StartType != ServiceStartMode.Disabled)
{
return ProcessControlResult.CreateSuccess($"{serviceName} is already enabled ({controller.StartType}).");
}
var targetStartType = GetOriginalStartType(serviceName);
var enableResult = SetServiceStartType(serviceName, targetStartType);
if (!enableResult)
{
return ProcessControlResult.CreateFailure($"Could not re-enable {serviceName}.");
}
// Clean up saved original — it's been restored.
RemoveOriginalStartType(serviceName);
// Restore a sensible default recovery action (restart once after 60s).
RestoreDefaultRecoveryActions(serviceName);
var startTypeLabel = targetStartType switch
{
"auto" => "Automatic",
"delayed-auto" => "Automatic (Delayed Start)",
"demand" => "Manual",
_ => targetStartType
};
if (startAfterEnable)
{
controller.Refresh();
if (controller.Status == ServiceControllerStatus.Stopped)
{
controller.Start();
controller.WaitForStatus(ServiceControllerStatus.Running, effectiveTimeout);
return ProcessControlResult.CreateSuccess($"Re-enabled and started {serviceName} ({startTypeLabel}).");
}
}
return ProcessControlResult.CreateSuccess($"Re-enabled {serviceName} (set to {startTypeLabel} start).");
}), cancellationToken);
}
/// <summary>
/// Restores a sensible default recovery policy: restart the service once
/// after 60 seconds, then take no action on subsequent failures.
/// </summary>
private static void RestoreDefaultRecoveryActions(string serviceName)
{
try
{
using var process = Process.Start(new ProcessStartInfo
{
FileName = "sc.exe",
Arguments = $"failure \"{serviceName}\" reset= 86400 actions= restart/60000/\"\"/0/\"\"/0",
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true
});
process?.WaitForExit(10_000);
}
catch
{
// Best-effort.
}
}
/// <summary>
/// Clears recovery (failure) actions for a service so Windows won't
/// automatically restart it on crash or stop.
/// </summary>
private static void ClearServiceRecoveryActions(string serviceName)
{
try
{
using var process = Process.Start(new ProcessStartInfo
{
FileName = "sc.exe",
Arguments = $"failure \"{serviceName}\" reset= 0 actions= \"\"",
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true
});
process?.WaitForExit(10_000);
}
catch
{
// Best-effort — if we can't clear recovery actions, the disable should still help.
}
}
/// <summary>
/// Uses sc.exe to change the start type of a Windows service.
/// </summary>
private static bool SetServiceStartType(string serviceName, string startType)
{
try
{
using var process = Process.Start(new ProcessStartInfo
{
FileName = "sc.exe",
Arguments = $"config \"{serviceName}\" start= {startType}",
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true
});
if (process is null)
{
return false;
}
process.WaitForExit(10_000);
return process.ExitCode == 0;
}
catch
{
return false;
}
}
// ── Original start type tracking ──────────────────────────────────
/// <summary>
/// Converts <see cref="ServiceStartMode"/> to the sc.exe start type string.
/// </summary>
internal static string MapStartModeToScString(ServiceStartMode mode) => mode switch
{
ServiceStartMode.Automatic => "auto",
ServiceStartMode.Manual => "demand",
ServiceStartMode.Disabled => "demand", // fallback — shouldn't normally save Disabled
ServiceStartMode.Boot => "boot",
ServiceStartMode.System => "system",
_ => "demand"
};
/// <summary>
/// Saves the current start type before we disable. If delayed-auto, uses registry to detect it.
/// </summary>
internal void SaveOriginalStartType(string serviceName, ServiceStartMode currentMode)
{
var key = serviceName.Trim();
if (_originalStartTypes.ContainsKey(key))
{
return; // Already saved from a previous stop — don't overwrite.
}
var scValue = MapStartModeToScString(currentMode);
// ServiceStartMode.Automatic doesn't distinguish normal Auto from Delayed-Auto.
// Check the registry to determine if it's delayed.
if (currentMode == ServiceStartMode.Automatic && IsDelayedAutoStart(serviceName))
{
scValue = "delayed-auto";
}
_originalStartTypes[key] = scValue;
PersistOriginalStartTypes();
}
/// <summary>
/// Gets the saved original start type, falling back to "demand" (Manual) if unknown.
/// </summary>
internal string GetOriginalStartType(string serviceName)
{
return _originalStartTypes.TryGetValue(serviceName.Trim(), out var startType)
? startType
: "demand";
}
/// <summary>
/// Removes the saved original start type after successful restore.
/// </summary>
internal void RemoveOriginalStartType(string serviceName)
{
if (_originalStartTypes.TryRemove(serviceName.Trim(), out _))
{
PersistOriginalStartTypes();
}
}
/// <summary>
/// Checks the registry to determine if a service is set to Delayed Auto-Start.
/// </summary>
private static bool IsDelayedAutoStart(string serviceName)
{
try
{
using var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(
$@"SYSTEM\CurrentControlSet\Services\{serviceName}");
if (key?.GetValue("DelayedAutostart") is int delayed)
{
return delayed == 1;
}
}
catch
{
// Best-effort.
}
return false;
}
/// <summary>
/// Persists the original start type map to a sidecar JSON file so it
/// survives app restarts. Fire-and-forget, best-effort.
/// </summary>
private void PersistOriginalStartTypes()
{
try
{
var dir = Path.GetDirectoryName(_startTypesFilePath);
if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
var dict = new Dictionary<string, string>(_originalStartTypes, StringComparer.OrdinalIgnoreCase);
var json = JsonSerializer.Serialize(dict, new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText(_startTypesFilePath, json);
}
catch
{
// Best-effort persistence.
}
}
/// <summary>
/// Loads previously saved original start types from the sidecar file.
/// </summary>
private static ConcurrentDictionary<string, string> LoadOriginalStartTypes(string filePath)
{
try
{
if (File.Exists(filePath))
{
var json = File.ReadAllText(filePath);
var dict = JsonSerializer.Deserialize<Dictionary<string, string>>(json);
if (dict is not null)
{
return new ConcurrentDictionary<string, string>(dict, StringComparer.OrdinalIgnoreCase);
}
}
}
catch
{
// Corrupted file — start fresh.
}
return new ConcurrentDictionary<string, string>(StringComparer.OrdinalIgnoreCase);
}
private static ProcessControlResult ControlService(string? serviceName, TimeSpan? timeout, Func<ServiceController, TimeSpan, ProcessControlResult> action)
{
if (!OperatingSystem.IsWindows())
{
return ProcessControlResult.CreateFailure("Service control is only supported on Windows.");
}
if (string.IsNullOrWhiteSpace(serviceName))
{
return ProcessControlResult.CreateFailure("Service name was not provided.");
}
var trimmedName = serviceName.Trim();
try
{
var effectiveTimeout = ResolveTimeout(timeout);
using var controller = new ServiceController(trimmedName);
return action(controller, effectiveTimeout);
}
catch (InvalidOperationException ex) when (IsServiceMissing(ex))
{
return ProcessControlResult.CreateSuccess($"{trimmedName} is not installed; skipping.");
}
catch (Exception ex)
{
var message = string.IsNullOrWhiteSpace(ex.Message) ? ex.GetType().Name : ex.Message;
return ProcessControlResult.CreateFailure(message);
}
}
private static bool IsServiceMissing(InvalidOperationException exception)
{
if (exception.InnerException is Win32Exception win32 && win32.NativeErrorCode == 1060)
{
return true;
}
return exception.Message?.IndexOf("does not exist", StringComparison.OrdinalIgnoreCase) >= 0
|| exception.Message?.IndexOf("cannot open", StringComparison.OrdinalIgnoreCase) >= 0;
}
private static TimeSpan ResolveTimeout(TimeSpan? timeout)
{
if (timeout is null || timeout <= TimeSpan.Zero)
{
return DefaultTimeout;
}
return timeout.Value;
}
}
public readonly record struct ProcessControlResult(bool Success, string Message)
{
public static ProcessControlResult CreateSuccess(string message) => new(true, string.IsNullOrWhiteSpace(message) ? "Operation succeeded." : message);
public static ProcessControlResult CreateFailure(string message) => new(false, string.IsNullOrWhiteSpace(message) ? "Operation failed." : message);
}