Files
2026-10-11 23:23:20 +00:00

54 lines
2.4 KiB
C#

using System.Diagnostics;
using System.Text.Json;
namespace UCVL.VPNPlus;
internal static class NetworkOwnerSelfTest
{
internal static int Child(string path)
{
using var lease = NetworkOwnerLease.Acquire(path);
File.WriteAllText(path + ".ready", "ready");
Thread.Sleep(30000);
return 0;
}
internal static async Task<int> RunAsync()
{
var folder = Path.Combine(Path.GetTempPath(), "ucvl-owner-test-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(folder);
var path = Path.Combine(folder, "owner.lock");
Process? child = null;
var stage = "spawn";
try
{
var info = new ProcessStartInfo(Environment.ProcessPath!) { UseShellExecute = false, CreateNoWindow = true };
info.ArgumentList.Add("--owner-lease-child"); info.ArgumentList.Add(path);
child = Process.Start(info)!;
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10));
while (!File.Exists(path + ".ready")) await Task.Delay(50, timeout.Token);
stage = "contention";
var blocked = false;
try { using var denied = NetworkOwnerLease.Acquire(path); }
catch (LocalNetworkException) { blocked = true; }
if (!blocked) throw new IOException("Second process acquired occupied lease");
child.Kill(); await child.WaitForExitAsync(timeout.Token);
stage = "crash release";
await Task.Delay(200, timeout.Token);
using (NetworkOwnerLease.Acquire(path)) { await Task.Yield(); }
stage = "async dispose";
using (NetworkOwnerLease.Acquire(path)) { }
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "network-owner-self-test.json"),
JsonSerializer.Serialize(new { passed = true, cross_process_exclusive = true, crash_released = true, async_release = true, network_changed = false }));
return 0;
}
catch (Exception ex) { AppPaths.WriteLog("Owner test stage: " + stage); AppPaths.WriteError(ex); return 31; }
finally
{
try { if (child is { HasExited: false }) child.Kill(); child?.Dispose(); } catch { }
foreach (var name in new[] { path, path + ".ready" }) try { File.Delete(name); } catch { }
try { Directory.Delete(folder); } catch { }
}
}
}