Windows 0.3.7 updater exit and Windows session cleanup reliability; no private history or other platform changes
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
// Only uiOnly fixtures may substitute recovery. Production always uses Xray's
|
||||
// ownership-checked route/DNS journals and exact child process handle.
|
||||
internal sealed record ClientExitRecoveryFixture(Func<Task> Dispose, TimeSpan? Deadline = null);
|
||||
@@ -0,0 +1,51 @@
|
||||
using System.Diagnostics;
|
||||
using System.Reflection;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace UCVL.VPNPlus;
|
||||
internal static class ClientShutdownChildSelfTest
|
||||
{
|
||||
internal static int Run()
|
||||
{
|
||||
var checks = new Dictionary<string, bool>();
|
||||
var children = new List<Process>();
|
||||
string? error = null;
|
||||
Process Start(int delay, int exitCode)
|
||||
{
|
||||
var info = new ProcessStartInfo(Environment.ProcessPath!) { UseShellExecute = false, CreateNoWindow = true };
|
||||
if (Path.GetFileNameWithoutExtension(Environment.ProcessPath).Equals("dotnet", StringComparison.OrdinalIgnoreCase))
|
||||
info.ArgumentList.Add(Assembly.GetExecutingAssembly().Location);
|
||||
info.ArgumentList.Add("--client-shutdown-test-child"); info.ArgumentList.Add(delay.ToString()); info.ArgumentList.Add(exitCode.ToString());
|
||||
var child = Process.Start(info)!;
|
||||
_ = child.Handle; // Pin the exact owned child before waiting.
|
||||
children.Add(child);
|
||||
return child;
|
||||
}
|
||||
try
|
||||
{
|
||||
var delayed = Start(1200, 0);
|
||||
checks["exact_owned_child_exits_cleanly_before_handoff"] = ClientShutdownScope.WaitForExit([delayed]) && delayed.HasExited;
|
||||
var failed = Start(10, 7);
|
||||
checks["nonzero_old_client_exit_blocks_replacement"] = !ClientShutdownScope.WaitForExit([failed]);
|
||||
var slow = Start(1200, 0);
|
||||
var timer = Stopwatch.StartNew();
|
||||
checks["timeout_blocks_replacement_without_killing_client"] = !ClientShutdownScope.WaitForExit([slow], TimeSpan.FromMilliseconds(70)) && !slow.HasExited;
|
||||
checks["wait_is_bounded"] = timer.ElapsedMilliseconds < 1000;
|
||||
checks["timed_out_child_can_finish_gracefully"] = ClientShutdownScope.WaitForExit([slow]);
|
||||
checks["all_exact_handles_reap_successfully"] = children.All(c => c.HasExited);
|
||||
}
|
||||
catch (Exception exception) { error = exception.ToString(); }
|
||||
finally
|
||||
{
|
||||
foreach (var child in children)
|
||||
{
|
||||
try { if (!child.HasExited) { child.Kill(entireProcessTree: true); child.WaitForExit(2000); } } catch { }
|
||||
child.Dispose();
|
||||
}
|
||||
}
|
||||
var passed = error is null && checks.Values.All(v => v);
|
||||
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "client-exit-child-handoff-self-test.json"),
|
||||
JsonSerializer.Serialize(new { Passed = passed, Checks = checks, Error = error, ProductionProcessQueried = false, NetworkingModified = false }, new JsonSerializerOptions { WriteIndented = true }));
|
||||
return passed ? 0 : 87;
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,21 @@ internal static class ClientShutdownScope
|
||||
internal static bool IsUnambiguous(string expected, int session, IEnumerable<Instance> processes)
|
||||
=> processes.Where(p => p.SessionId == session).All(p => !string.IsNullOrWhiteSpace(p.Executable)
|
||||
&& string.Equals(Path.GetFullPath(p.Executable), Path.GetFullPath(expected), StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
// Call only after path/session verification and pinning exact handles.
|
||||
// All instances consume one shared budget; a timeout never kills a client.
|
||||
internal static bool WaitForExit(IEnumerable<System.Diagnostics.Process> processes, TimeSpan? budget = null)
|
||||
{
|
||||
var watch = System.Diagnostics.Stopwatch.StartNew();
|
||||
var limit = budget ?? TimeSpan.FromSeconds(90);
|
||||
foreach (var process in processes)
|
||||
{
|
||||
var remaining = (int)Math.Clamp(limit.TotalMilliseconds - watch.ElapsedMilliseconds, 0, int.MaxValue);
|
||||
if (!process.HasExited && (remaining == 0 || !process.WaitForExit(remaining))) return false;
|
||||
if (process.ExitCode != 0) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
internal static bool SelfTest()
|
||||
{
|
||||
const string expected = @"C:\fixture\installed\VPNPlus.exe";
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
using System.Diagnostics;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
internal static class ClientShutdownSelfTest
|
||||
{
|
||||
internal static int Run()
|
||||
{
|
||||
var flow = RunFlowAsync().GetAwaiter().GetResult();
|
||||
var ui = flow == 0 ? ClientShutdownUiSelfTest.Run() : -1;
|
||||
var handoff = flow == 0 && ui == 0 ? ClientShutdownChildSelfTest.Run() : -1;
|
||||
var passed = flow == 0 && ui == 0 && handoff == 0;
|
||||
var checks = new Dictionary<string, bool>();
|
||||
foreach (var (prefix, file) in new[] { ("flow", "client-exit-self-test.json"),
|
||||
("ui", "client-exit-ui-self-test.json"), ("handoff", "client-exit-child-handoff-self-test.json") })
|
||||
{
|
||||
var path = Path.Combine(AppContext.BaseDirectory, file);
|
||||
if (!File.Exists(path)) { checks[prefix + ".report_exists"] = false; continue; }
|
||||
using var document = JsonDocument.Parse(File.ReadAllText(path));
|
||||
foreach (var assertion in document.RootElement.GetProperty("Checks").EnumerateObject())
|
||||
checks[prefix + "." + assertion.Name] = assertion.Value.GetBoolean();
|
||||
}
|
||||
passed &= checks.Count > 0 && checks.Values.All(value => value);
|
||||
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "client-shutdown-self-test.json"),
|
||||
JsonSerializer.Serialize(new { passed, checks, flow_exit_code = flow, ui_exit_code = ui, child_handoff_exit_code = handoff,
|
||||
network_modified = false, installed_client_modified = false }, new JsonSerializerOptions { WriteIndented = true }));
|
||||
return passed ? 0 : 85;
|
||||
}
|
||||
|
||||
private static async Task<int> RunFlowAsync()
|
||||
{
|
||||
var checks = new Dictionary<string, bool>();
|
||||
try
|
||||
{
|
||||
var current = false;
|
||||
var confirms = 0; var downloads = 0; var launches = 0;
|
||||
var accepted = await ClientUpdateFlow.RunAsync(() => current,
|
||||
() => { confirms++; return true; },
|
||||
() => { downloads++; return Task.FromResult("fixture.exe"); }, _ => launches++);
|
||||
checks["closed_before_offer_has_no_side_effect"] = !accepted && confirms == 0 && downloads == 0 && launches == 0;
|
||||
|
||||
current = true; confirms = downloads = launches = 0;
|
||||
accepted = await ClientUpdateFlow.RunAsync(() => current,
|
||||
() => { confirms++; current = false; return true; },
|
||||
() => { downloads++; return Task.FromResult("fixture.exe"); }, _ => launches++);
|
||||
checks["shutdown_during_confirmation_never_opens_progress_or_installer"] = !accepted && confirms == 1 && downloads == 0 && launches == 0;
|
||||
|
||||
current = true; confirms = downloads = launches = 0;
|
||||
var downloaded = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var pending = ClientUpdateFlow.RunAsync(() => current,
|
||||
() => { confirms++; return true; },
|
||||
() => { downloads++; return downloaded.Task; }, _ => launches++);
|
||||
current = false;
|
||||
downloaded.SetResult("fixture.exe");
|
||||
accepted = await pending;
|
||||
checks["shutdown_during_download_never_launches_installer"] = !accepted && confirms == 1 && downloads == 1 && launches == 0;
|
||||
|
||||
current = true; confirms = downloads = launches = 0;
|
||||
accepted = await ClientUpdateFlow.RunAsync(() => current, () => false,
|
||||
() => { downloads++; return Task.FromResult("fixture.exe"); }, _ => launches++);
|
||||
checks["declined_offer_retains_client"] = !accepted && downloads == 0 && launches == 0;
|
||||
accepted = await ClientUpdateFlow.RunAsync(() => current, () => true,
|
||||
() => Task.FromResult("verified-fixture.exe"), path => { if (path == "verified-fixture.exe") launches++; });
|
||||
checks["active_accepted_update_launches_exact_download_once"] = accepted && launches == 1;
|
||||
}
|
||||
catch (Exception error) { checks["unexpected_error"] = false; Console.Error.WriteLine(error); }
|
||||
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "client-exit-self-test.json"),
|
||||
JsonSerializer.Serialize(new { Passed = checks.Values.All(x => x), Checks = checks }, new JsonSerializerOptions { WriteIndented = true }));
|
||||
return checks.Values.All(x => x) ? 0 : 85;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
using System.Reflection;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
internal static class ClientShutdownUiSelfTest
|
||||
{
|
||||
internal static int Run()
|
||||
{
|
||||
var checks = new Dictionary<string, bool>();
|
||||
string? error = null;
|
||||
try
|
||||
{
|
||||
var uiThread = Environment.CurrentManagedThreadId;
|
||||
var disposals = 0;
|
||||
var background = false;
|
||||
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
using (var form = new MainForm(uiOnly: true, exitRecoveryFixture: new(
|
||||
async () => { Interlocked.Increment(ref disposals); background = Environment.CurrentManagedThreadId != uiThread; await release.Task; })))
|
||||
{
|
||||
form.Show(); PumpUntil(() => form.LoginReadyForTest);
|
||||
form.WindowChromeForTest!.SetLoginMode(false);
|
||||
form.Close();
|
||||
checks["ordinary_authenticated_close_is_blocked"] = form.Visible && !form.IsDisposed && disposals == 0;
|
||||
form.RequestExitForUpdate();
|
||||
PumpUntil(() => Volatile.Read(ref disposals) == 1);
|
||||
form.RequestExitForUpdate();
|
||||
checks["installer_exit_bypasses_tray_and_starts_cleanup_once"] = disposals == 1 && !form.IsDisposed && background;
|
||||
release.SetResult();
|
||||
checks["installer_closes_when_tracked_cleanup_finishes"] = PumpUntil(() => form.IsDisposed);
|
||||
}
|
||||
|
||||
using (var failed = new MainForm(uiOnly: true, exitRecoveryFixture: new(
|
||||
() => Task.FromException(new IOException("isolated recovery failure")))))
|
||||
{
|
||||
failed.Show(); PumpUntil(() => failed.LoginReadyForTest);
|
||||
failed.RequestExitForUpdate();
|
||||
checks["installer_recovery_error_closes_without_blocking_modal"] = PumpUntil(() => failed.IsDisposed)
|
||||
&& failed.NetworkRecoveryFailed;
|
||||
}
|
||||
|
||||
var timedOutRecovery = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
using (var timedOut = new MainForm(uiOnly: true, exitRecoveryFixture: new(
|
||||
() => timedOutRecovery.Task, TimeSpan.FromMilliseconds(80))))
|
||||
{
|
||||
timedOut.Show(); PumpUntil(() => timedOut.LoginReadyForTest);
|
||||
timedOut.RequestExitForUpdate();
|
||||
checks["stalled_recovery_bounds_exit_and_blocks_install_success"] = PumpUntil(() => timedOut.IsDisposed)
|
||||
&& timedOut.NetworkRecoveryFailed;
|
||||
timedOutRecovery.SetResult();
|
||||
}
|
||||
|
||||
disposals = 0;
|
||||
using (var canceled = new MainForm(uiOnly: true, exitRecoveryFixture: new(
|
||||
() => { Interlocked.Increment(ref disposals); return Task.CompletedTask; })))
|
||||
{
|
||||
canceled.Show(); PumpUntil(() => canceled.LoginReadyForTest);
|
||||
Invoke(canceled, "SetBusy", true, null);
|
||||
var watch = System.Diagnostics.Stopwatch.StartNew();
|
||||
var query = Dispatch(canceled, 0x11, IntPtr.Zero);
|
||||
var repeat = Dispatch(canceled, 0x11, IntPtr.Zero);
|
||||
checks["repeated_session_query_returns_promptly_without_recovery"] = watch.ElapsedMilliseconds < 300
|
||||
&& query == (IntPtr)1 && repeat == (IntPtr)1 && disposals == 0
|
||||
&& !Lifetime(canceled).IsCancellationRequested && !canceled.IsDisposed;
|
||||
// Query/canceled END must not reset an active operation or its UI.
|
||||
canceled.Enabled = false; canceled.UseWaitCursor = true;
|
||||
Dispatch(canceled, 0x16, IntPtr.Zero);
|
||||
Dispatch(canceled, 0x16, IntPtr.Zero);
|
||||
checks["canceled_session_query_preserves_active_ui_state"] = !canceled.Enabled && canceled.UseWaitCursor
|
||||
&& !Lifetime(canceled).IsCancellationRequested && disposals == 0;
|
||||
canceled.Enabled = true; Invoke(canceled, "SetBusy", false, null);
|
||||
checks["operation_can_finish_after_canceled_shutdown"] = canceled.LoginReadyForTest;
|
||||
canceled.RequestExitForUpdate();
|
||||
checks["canceled_query_client_can_later_exit"] = PumpUntil(() => canceled.IsDisposed) && disposals == 1;
|
||||
}
|
||||
|
||||
disposals = 0;
|
||||
using (var queued = new MainForm(uiOnly: true, exitRecoveryFixture: new(
|
||||
() => { Interlocked.Increment(ref disposals); return Task.CompletedTask; })))
|
||||
{
|
||||
queued.Show(); PumpUntil(() => queued.LoginReadyForTest);
|
||||
Dispatch(queued, 0x11, IntPtr.Zero);
|
||||
queued.RequestExitForUpdate();
|
||||
checks["installer_exit_still_works_after_session_query"] = PumpUntil(() => queued.IsDisposed) && disposals == 1;
|
||||
}
|
||||
|
||||
disposals = 0;
|
||||
using (var confirmed = new MainForm(uiOnly: true, exitRecoveryFixture: new(
|
||||
() => { Interlocked.Increment(ref disposals); return Task.CompletedTask; })))
|
||||
{
|
||||
confirmed.Show(); PumpUntil(() => confirmed.LoginReadyForTest);
|
||||
Dispatch(confirmed, 0x11, IntPtr.Zero);
|
||||
Invoke(confirmed, "CompleteSessionEnding");
|
||||
Invoke(confirmed, "CompleteSessionEnding");
|
||||
Dispatch(confirmed, 0x16, IntPtr.Zero);
|
||||
checks["confirmed_session_finalizes_once_and_cannot_resume"] = disposals == 1
|
||||
&& Lifetime(confirmed).IsCancellationRequested && !confirmed.NetworkRecoveryFailed;
|
||||
}
|
||||
}
|
||||
catch (Exception exception) { error = exception.ToString(); }
|
||||
var passed = error is null && checks.Values.All(v => v);
|
||||
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "client-exit-ui-self-test.json"),
|
||||
JsonSerializer.Serialize(new { Passed = passed, Checks = checks, Error = error, ProductionNetworking = false, ActualWindowsShutdown = false }, new JsonSerializerOptions { WriteIndented = true }));
|
||||
return passed ? 0 : 86;
|
||||
}
|
||||
|
||||
private static object? Invoke(MainForm form, string method, params object?[] args) => typeof(MainForm)
|
||||
.GetMethod(method, BindingFlags.Instance | BindingFlags.NonPublic)!.Invoke(form, args);
|
||||
private static IntPtr Dispatch(MainForm form, int message, IntPtr wparam)
|
||||
{
|
||||
object?[] args = [Message.Create(form.Handle, message, wparam, IntPtr.Zero)];
|
||||
typeof(MainForm).GetMethod("WndProc", BindingFlags.Instance | BindingFlags.NonPublic)!.Invoke(form, args);
|
||||
return ((Message)args[0]!).Result;
|
||||
}
|
||||
private static CancellationTokenSource Lifetime(MainForm form) => (CancellationTokenSource)typeof(MainForm)
|
||||
.GetField("_lifetime", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(form)!;
|
||||
private static bool PumpUntil(Func<bool> condition)
|
||||
{
|
||||
var watch = System.Diagnostics.Stopwatch.StartNew();
|
||||
while (!condition() && watch.ElapsedMilliseconds < 2500) { Application.DoEvents(); Thread.Sleep(5); }
|
||||
return condition();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
// The confirmation dialog runs a nested message loop. Shutdown may win while
|
||||
// it is open, or while the package is downloading; never launch afterwards.
|
||||
internal static class ClientUpdateFlow
|
||||
{
|
||||
internal static async Task<bool> RunAsync(Func<bool> isCurrent, Func<bool> confirm,
|
||||
Func<Task<string>> download, Action<string> launch)
|
||||
{
|
||||
if (!isCurrent() || !confirm() || !isCurrent()) return false;
|
||||
var installer = await download();
|
||||
if (!isCurrent()) return false;
|
||||
launch(installer);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
+71
-40
@@ -74,6 +74,8 @@ internal sealed partial class MainForm : Form
|
||||
private Task<Exception?>? _exitCleanupTask;
|
||||
private bool _exitResourcesDisposed;
|
||||
private bool _sessionEnding;
|
||||
private bool _installerExitRequested;
|
||||
private readonly ClientExitRecoveryFixture? _exitRecoveryFixture;
|
||||
private bool _windowExitSelfTestConnected;
|
||||
private bool _updateCheckRunning;
|
||||
private DateTimeOffset _nextUpdateCheckAt = DateTimeOffset.MinValue;
|
||||
@@ -85,8 +87,11 @@ internal sealed partial class MainForm : Form
|
||||
internal bool NetworkRecoveryFailed { get; private set; }
|
||||
|
||||
internal MainForm(bool runWindowExitSelfTest = false, bool preview = false, bool uiOnly = false,
|
||||
bool autoConnect = false, Func<CancellationToken, Task>? startupRecovery = null)
|
||||
bool autoConnect = false, Func<CancellationToken, Task>? startupRecovery = null,
|
||||
ClientExitRecoveryFixture? exitRecoveryFixture = null)
|
||||
{
|
||||
if (exitRecoveryFixture is not null && !uiOnly) throw new ArgumentException("Recovery fixtures require uiOnly isolation.");
|
||||
_exitRecoveryFixture = exitRecoveryFixture;
|
||||
_uiOnly = uiOnly;
|
||||
_preview = preview;
|
||||
_startupRecovery = startupRecovery;
|
||||
@@ -192,33 +197,34 @@ internal sealed partial class MainForm : Form
|
||||
return false;
|
||||
}
|
||||
var notes = string.IsNullOrWhiteSpace(update.Notes) ? "包含稳定性和网络恢复改进。" : update.Notes.Trim();
|
||||
var choice = MessageBox.Show(
|
||||
$"发现新版本 {update.Version}\n\n{notes}\n\n是否现在安全升级?\n升级将覆盖原安装目录,但会保留账号、设备标识和本机配置。",
|
||||
"纵横家·发现更新",
|
||||
update.Mandatory ? MessageBoxButtons.OKCancel : MessageBoxButtons.YesNo,
|
||||
MessageBoxIcon.Information);
|
||||
accepted = update.Mandatory ? choice == DialogResult.OK : choice == DialogResult.Yes;
|
||||
if (!accepted)
|
||||
{
|
||||
_nextUpdateCheckAt = DateTimeOffset.UtcNow.AddHours(6);
|
||||
return false;
|
||||
}
|
||||
|
||||
UseWaitCursor = true;
|
||||
Text = $"纵横家 · 正在下载 {update.Version}…";
|
||||
using var progressWindow = new UpdateProgressForm(update.Version);
|
||||
progressWindow.Show(this);
|
||||
Enabled = false;
|
||||
string installer;
|
||||
try { installer = await ClientUpdater.DownloadAsync(update, _lifetime.Token, new Progress<int>(progressWindow.Report)); }
|
||||
finally { Enabled = true; }
|
||||
// Start and authorize the installer BEFORE stopping the working client.
|
||||
// The installer stages and validates all files, then requests graceful shutdown.
|
||||
// Cancelling UAC or failing to start must leave the current connection alive.
|
||||
var installerProcess = ClientUpdater.LaunchInstaller(installer);
|
||||
_installerLaunched = true;
|
||||
_ = ObserveInstallerAsync(installerProcess);
|
||||
return true;
|
||||
return await ClientUpdateFlow.RunAsync(
|
||||
() => !_exiting && !_sessionEnding && !IsDisposed && !Disposing && !_lifetime.IsCancellationRequested,
|
||||
() => {
|
||||
var choice = MessageBox.Show(this,
|
||||
$"发现新版本 {update.Version}\n\n{notes}\n\n是否现在安全升级?\n升级将覆盖原安装目录,但会保留账号、设备标识和本机配置。",
|
||||
"纵横家·发现更新",
|
||||
update.Mandatory ? MessageBoxButtons.OKCancel : MessageBoxButtons.YesNo,
|
||||
MessageBoxIcon.Information);
|
||||
accepted = update.Mandatory ? choice == DialogResult.OK : choice == DialogResult.Yes;
|
||||
if (!accepted) _nextUpdateCheckAt = DateTimeOffset.UtcNow.AddHours(6);
|
||||
return accepted;
|
||||
}, async () => {
|
||||
UseWaitCursor = true;
|
||||
Text = $"纵横家 · 正在下载 {update.Version}…";
|
||||
using var progressWindow = new UpdateProgressForm(update.Version);
|
||||
progressWindow.Show(this);
|
||||
Enabled = false;
|
||||
try { return await ClientUpdater.DownloadAsync(update, _lifetime.Token, new Progress<int>(progressWindow.Report)); }
|
||||
finally { if (!_exiting && !IsDisposed && !Disposing) Enabled = true; }
|
||||
}, installer => {
|
||||
// Start and authorize the installer BEFORE stopping the working client.
|
||||
// The installer stages and validates all files, then requests graceful shutdown.
|
||||
// Cancelling UAC or failing to start must leave the current connection alive.
|
||||
var installerProcess = ClientUpdater.LaunchInstaller(installer);
|
||||
_installerLaunched = true;
|
||||
_ = ObserveInstallerAsync(installerProcess);
|
||||
AppPaths.WriteLog("update.install.started version=" + update.Version);
|
||||
});
|
||||
}
|
||||
catch (OperationCanceledException) when (_lifetime.IsCancellationRequested)
|
||||
{
|
||||
@@ -228,7 +234,7 @@ internal sealed partial class MainForm : Form
|
||||
{
|
||||
_nextUpdateCheckAt = DateTimeOffset.UtcNow.AddMinutes(accepted ? 30 : 2);
|
||||
AppPaths.WriteError(exception);
|
||||
if (accepted)
|
||||
if (accepted && !_exiting && !_sessionEnding && !IsDisposed && !Disposing)
|
||||
{
|
||||
MessageBox.Show(
|
||||
$"更新未启动,已保留当前版本和当前连接。\n\n{exception.Message}",
|
||||
@@ -241,8 +247,7 @@ internal sealed partial class MainForm : Form
|
||||
finally
|
||||
{
|
||||
_updateCheckRunning = false;
|
||||
UseWaitCursor = false;
|
||||
Text = "纵横家";
|
||||
if (!_exiting && !IsDisposed && !Disposing) { UseWaitCursor = false; Text = "纵横家"; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1249,7 +1254,7 @@ internal sealed partial class MainForm : Form
|
||||
eventArgs.Cancel = true;
|
||||
return;
|
||||
}
|
||||
if (_uiOnly || _preview)
|
||||
if ((_uiOnly || _preview) && _exitRecoveryFixture is null)
|
||||
{
|
||||
_ = BeginExitCleanup();
|
||||
CompleteExitResources();
|
||||
@@ -1269,13 +1274,21 @@ internal sealed partial class MainForm : Form
|
||||
SetConnectionState(false, "正在恢复本地网络", "正在恢复系统代理并关闭内核,请稍候…");
|
||||
}
|
||||
|
||||
var error = await cleanup;
|
||||
Exception? error;
|
||||
try { error = await cleanup.WaitAsync(_exitRecoveryFixture?.Deadline ?? TimeSpan.FromSeconds(85)); }
|
||||
catch (TimeoutException timeout)
|
||||
{
|
||||
// Leave every still-owned recovery journal intact. The installer
|
||||
// observes a nonzero client exit and must not replace its files.
|
||||
error = timeout;
|
||||
AppPaths.WriteLog("exit.recovery.timeout journals_retained=true");
|
||||
}
|
||||
if (_sessionEnding || IsDisposed || Disposing) return;
|
||||
if (error is not null)
|
||||
{
|
||||
// Never install over a client whose network recovery failed.
|
||||
NetworkRecoveryFailed = true;
|
||||
MessageBox.Show("网络恢复未全部完成,恢复记录已保留;本次不继续自动安装。\n" + error.GetBaseException().Message,
|
||||
if (!_installerExitRequested) MessageBox.Show("网络恢复未全部完成,恢复记录已保留;本次不继续自动安装。\n" + error.GetBaseException().Message,
|
||||
"纵横家 · 网络恢复提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
|
||||
}
|
||||
CompleteExitResources();
|
||||
@@ -1293,13 +1306,19 @@ internal sealed partial class MainForm : Form
|
||||
_refreshTimer.Stop(); _updateTimer.Stop(); _trafficTimer.Stop(); _healthTimer.Stop();
|
||||
_nodeTrafficTimer.Stop();
|
||||
_lifetime.Cancel();
|
||||
if (_uiOnly || _preview) return _exitCleanupTask = Task.FromResult<Exception?>(null);
|
||||
if ((_uiOnly || _preview) && _exitRecoveryFixture is null) return _exitCleanupTask = Task.FromResult<Exception?>(null);
|
||||
// The same tracked cleanup serves menu/installer exit and session end.
|
||||
// Run it without a UI synchronization context so WM_ENDSESSION can
|
||||
// wait within Windows' shutdown budget without blocking its continuations.
|
||||
return _exitCleanupTask = Task.Run(async () =>
|
||||
{
|
||||
try { await _xray.DisposeAsync().ConfigureAwait(false); return (Exception?)null; }
|
||||
try
|
||||
{
|
||||
if (_exitRecoveryFixture is { } fixture) await fixture.Dispose().ConfigureAwait(false);
|
||||
else await _xray.DisposeAsync().ConfigureAwait(false);
|
||||
return (Exception?)null;
|
||||
}
|
||||
catch (OperationCanceledException error) when (_sessionEnding) { return error; }
|
||||
catch (Exception error) { AppPaths.WriteError(error); return error; }
|
||||
});
|
||||
}
|
||||
@@ -1320,14 +1339,17 @@ internal sealed partial class MainForm : Form
|
||||
{
|
||||
if (message.Msg == 0x11 /* WM_QUERYENDSESSION */)
|
||||
{
|
||||
// A query may be canceled by another application. Do not cancel
|
||||
// our session or await network cleanup until Windows confirms it.
|
||||
// A query can be canceled. Return promptly without disconnecting
|
||||
// or launching any recovery helper before Windows confirms it.
|
||||
message.Result = (IntPtr)1;
|
||||
return;
|
||||
}
|
||||
if (message.Msg == 0x16 /* WM_ENDSESSION */)
|
||||
{
|
||||
if (message.WParam == IntPtr.Zero) { message.Result = IntPtr.Zero; return; }
|
||||
if (message.WParam == IntPtr.Zero)
|
||||
{
|
||||
message.Result = IntPtr.Zero; return;
|
||||
}
|
||||
CompleteSessionEnding();
|
||||
}
|
||||
base.WndProc(ref message);
|
||||
@@ -1337,6 +1359,7 @@ internal sealed partial class MainForm : Form
|
||||
{
|
||||
if (_sessionEnding) return;
|
||||
_sessionEnding = true;
|
||||
_xray.ConfirmSessionShutdown();
|
||||
var cleanup = BeginExitCleanup();
|
||||
// Windows can terminate us after its short shutdown allowance. Never
|
||||
// remove recovery journals here or display a modal recovery error.
|
||||
@@ -1436,11 +1459,19 @@ internal sealed partial class MainForm : Form
|
||||
|
||||
internal void RequestExit()
|
||||
{
|
||||
if (_exiting || IsDisposed || Disposing) return;
|
||||
if (IsDisposed || Disposing) return;
|
||||
_exitRequested = true;
|
||||
if (_exiting) return;
|
||||
Close();
|
||||
}
|
||||
|
||||
internal void RequestExitForUpdate()
|
||||
{
|
||||
_installerExitRequested = true;
|
||||
AppPaths.WriteLog("update.shutdown.requested");
|
||||
RequestExit();
|
||||
}
|
||||
|
||||
private static void OpenRegistrationPage()
|
||||
{
|
||||
try
|
||||
|
||||
+20
-15
@@ -11,6 +11,19 @@ internal static class Program
|
||||
[STAThread]
|
||||
private static int Main(string[] args)
|
||||
{
|
||||
if (args.Length == 1 && args[0] == "--client-shutdown-self-test")
|
||||
{
|
||||
ApplicationConfiguration.Initialize();
|
||||
return ClientShutdownSelfTest.Run();
|
||||
}
|
||||
if (args.Length == 3 && args[0] == "--client-shutdown-test-child"
|
||||
&& int.TryParse(args[1], out var childDelay) && childDelay is >= 10 and <= 2000
|
||||
&& int.TryParse(args[2], out var childExit) && childExit is 0 or 7)
|
||||
{
|
||||
Thread.Sleep(childDelay);
|
||||
return childExit;
|
||||
}
|
||||
if (args.Any(a => a.StartsWith("--client-shutdown-test-child", StringComparison.OrdinalIgnoreCase))) return 87;
|
||||
if (args.Length == 5 && args[0] is "--installer-guardian-gate" or "--installer-guardian-apply")
|
||||
return InstallerGuardianGate.Run(args[1], args[2], args[3], args[4], apply: args[0] == "--installer-guardian-apply");
|
||||
// Malformed maintenance arguments must never fall through to the GUI.
|
||||
@@ -195,9 +208,12 @@ internal static class Program
|
||||
shutdownEvent,
|
||||
(_, _) =>
|
||||
{
|
||||
var form = Application.OpenForms.OfType<MainForm>().FirstOrDefault();
|
||||
if (form is null || form.IsDisposed || !form.IsHandleCreated) return;
|
||||
form.BeginInvoke(form.RequestExit);
|
||||
try
|
||||
{
|
||||
if (!mainForm.IsDisposed && mainForm.IsHandleCreated)
|
||||
mainForm.BeginInvoke(mainForm.RequestExitForUpdate);
|
||||
}
|
||||
catch (InvalidOperationException) { /* A concurrent close destroyed the HWND. */ }
|
||||
},
|
||||
null,
|
||||
Timeout.Infinite,
|
||||
@@ -335,18 +351,7 @@ internal static class Program
|
||||
foreach (var process in processes) process.CloseMainWindow();
|
||||
}
|
||||
|
||||
foreach (var process in processes)
|
||||
{
|
||||
using (process)
|
||||
{
|
||||
if (!process.WaitForExit(15_000))
|
||||
{
|
||||
return 2;
|
||||
}
|
||||
if (process.ExitCode != 0) return 2;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
return ClientShutdownScope.WaitForExit(processes) ? 0 : 2;
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
+3
-3
@@ -1,6 +1,6 @@
|
||||
# 纵横家 Windows 0.3.6 开源源码
|
||||
# 纵横家 Windows 0.3.7 开源源码
|
||||
|
||||
基于已冻结的 0.3.6 r22 第一方 Windows Forms / .NET 8 源码整理。此导出不是原安装包的逐字节副本:删除许可来源不明的可选登录插图及内部运维历史,保留原创山水缺图 fallback;端点为示例配置。原候选测试报告不能当作本导出的构建或生产验收证明。
|
||||
基于已冻结的 0.3.7 r22 第一方 Windows Forms / .NET 8 源码整理。此导出不是原安装包的逐字节副本:删除许可来源不明的可选登录插图及内部运维历史,保留原创山水缺图 fallback;端点为示例配置。原候选测试报告不能当作本导出的构建或生产验收证明。
|
||||
|
||||
## 构建
|
||||
|
||||
@@ -17,4 +17,4 @@ dotnet publish VPNPlus.csproj -c Release -r win-x64 --self-contained true
|
||||
|
||||
公司自有代码适用 LICENSE;公司 Logo/商标保留来源识别用途、不授予品牌权利;第三方许可文本在 licenses/ 中,原 THIRD_PARTY_NOTICES.md 保持原文。
|
||||
|
||||
0.3.6:连接前检查本机Xray及必要运行文件;组件缺失时一次性明确提示修复安装,避免逐节点重复失败。延长受限速环境下完整升级包下载的总时间预算。保留0.3.5本机和服务器趋势图、连接容错、调度与路由规则,不宣称网络提速。清洁源码保留原MIT/GPL和第三方许可边界,不含用户提供的可选JPG;同包离线、合成界面与隔离文件事务验证不等于生产网络或覆盖安装验收。
|
||||
0.3.7:修复升级确认后窗口退出竞态、旧进程退出等待期限、安装器退出的阻塞提示,并改进Windows会话结束的限时清理和恢复记录保留。保留0.3.6连接与运行组件修复。已进行隔离回归,不代表实际关机验收。可选JPG保持从开源代码中省略,许可边界保持不变。
|
||||
|
||||
@@ -10,10 +10,10 @@
|
||||
<ApplicationIcon>assets\zonghengjia-app-v1.ico</ApplicationIcon>
|
||||
<ApplicationManifest>app.manifest</ApplicationManifest>
|
||||
<ApplicationHighDpiMode>PerMonitorV2</ApplicationHighDpiMode>
|
||||
<Version>0.3.6</Version>
|
||||
<AssemblyVersion>0.3.6.0</AssemblyVersion>
|
||||
<FileVersion>0.3.6.0</FileVersion>
|
||||
<InformationalVersion>0.3.6</InformationalVersion>
|
||||
<Version>0.3.7</Version>
|
||||
<AssemblyVersion>0.3.7.0</AssemblyVersion>
|
||||
<FileVersion>0.3.7.0</FileVersion>
|
||||
<InformationalVersion>0.3.7</InformationalVersion>
|
||||
<Product>纵横家</Product>
|
||||
<Company>优创未来(UCVL)</Company>
|
||||
<Description>纵横家 Windows 智能网络客户端</Description>
|
||||
|
||||
+25
-9
@@ -22,6 +22,8 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
private bool _disposed;
|
||||
private NetworkOwnerLease? _ownerLease;
|
||||
private bool _recoveryComplete;
|
||||
private bool _stoppedCleanly;
|
||||
private readonly CancellationTokenSource _systemShutdown = new();
|
||||
private readonly SemaphoreSlim _lifecycle = new(1, 1);
|
||||
private readonly string _xrayDirectory = Path.Combine(AppContext.BaseDirectory, "xray");
|
||||
private string? _baseConfigJson;
|
||||
@@ -66,6 +68,8 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
public bool CanRebindNetwork => !string.IsNullOrWhiteSpace(_baseConfigJson) && _boundNetwork is not null;
|
||||
bool IHandoverRuntime.IsRunning => IsRunning;
|
||||
|
||||
internal void ConfirmSessionShutdown() => _systemShutdown.Cancel();
|
||||
|
||||
public async Task SuspendForNetworkChangeAsync(CancellationToken token)
|
||||
{
|
||||
await _lifecycle.WaitAsync(token);
|
||||
@@ -288,6 +292,7 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
{
|
||||
ValidateRuntime();
|
||||
if (string.IsNullOrWhiteSpace(_baseConfigJson)) throw new InvalidOperationException("线路配置为空。");
|
||||
_stoppedCleanly = false;
|
||||
PrivateAuxiliaryRuntime.ValidateLifetime(_baseConfigJson);
|
||||
var privateAuxiliary = PrivateAuxiliaryRuntime.IsPrivate(_baseConfigJson);
|
||||
var preservePrivateRoute = privateAuxiliary && PrivateAuxiliaryRuntime.Address(_baseConfigJson) != PrivateAuxiliaryRouting.PublicPhoneHost;
|
||||
@@ -435,16 +440,18 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
{
|
||||
// A rejected second instance must not delete the active owner's DNS,
|
||||
// routes, PID journal or virtual adapter through its error/Dispose path.
|
||||
if (_ownerLease is null || !_recoveryComplete) return;
|
||||
if (_ownerLease is null || !_recoveryComplete || _stoppedCleanly) return;
|
||||
_learningEpoch.Cancel();
|
||||
var proxyRestored = SystemProxy.Restore();
|
||||
Exception? restoreError = null;
|
||||
using var recovery = new CancellationTokenSource(TimeSpan.FromSeconds(25));
|
||||
var sessionToken = _systemShutdown.Token;
|
||||
using var recovery = CancellationTokenSource.CreateLinkedTokenSource(sessionToken);
|
||||
recovery.CancelAfter(TimeSpan.FromSeconds(25));
|
||||
Exception? dnsRestoreError = null;
|
||||
try { await ProxyDnsPolicy.RestoreAsync(recovery.Token).ConfigureAwait(false); }
|
||||
catch (Exception error) { dnsRestoreError = error; AppPaths.WriteError(error); }
|
||||
try { await TunRouting.RestoreAsync(recovery.Token).ConfigureAwait(false); }
|
||||
catch (Exception error) { restoreError = error; AppPaths.WriteError(error); }
|
||||
try { recovery.Token.ThrowIfCancellationRequested(); await ProxyDnsPolicy.RestoreAsync(recovery.Token).ConfigureAwait(false); }
|
||||
catch (Exception error) { dnsRestoreError = error; if (!sessionToken.IsCancellationRequested) AppPaths.WriteError(error); }
|
||||
try { recovery.Token.ThrowIfCancellationRequested(); await TunRouting.RestoreAsync(recovery.Token).ConfigureAwait(false); }
|
||||
catch (Exception error) { restoreError = error; if (!sessionToken.IsCancellationRequested) AppPaths.WriteError(error); }
|
||||
try
|
||||
{
|
||||
if (_process is { HasExited: false })
|
||||
@@ -464,21 +471,30 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
SafeDelete(AppPaths.PidFile);
|
||||
SafeDeleteConfig();
|
||||
}
|
||||
await TunRouting.CleanupOwnedAdapterAsync(CancellationToken.None).ConfigureAwait(false);
|
||||
// Confirmed system shutdown forbids launching fresh helper processes.
|
||||
// Kill the already-owned core above, retain failed journals, and let
|
||||
// startup recovery finish after Windows is ready again.
|
||||
sessionToken.ThrowIfCancellationRequested();
|
||||
await TunRouting.CleanupOwnedAdapterAsync(sessionToken).ConfigureAwait(false);
|
||||
if (restoreError is not null)
|
||||
{
|
||||
// Removal of a failed TUN device may have removed its routes too.
|
||||
// Retry the retained journal; never erase it merely because exit was requested.
|
||||
using var retry = new CancellationTokenSource(TimeSpan.FromSeconds(15));
|
||||
using var retry = CancellationTokenSource.CreateLinkedTokenSource(sessionToken);
|
||||
retry.CancelAfter(TimeSpan.FromSeconds(15));
|
||||
retry.Token.ThrowIfCancellationRequested();
|
||||
await TunRouting.RestoreAsync(retry.Token).ConfigureAwait(false);
|
||||
}
|
||||
if (!proxyRestored && !SystemProxy.Restore())
|
||||
throw new IOException("系统代理恢复未完成,恢复记录已保留。请勿继续升级安装。");
|
||||
if (dnsRestoreError is not null)
|
||||
{
|
||||
using var retry = new CancellationTokenSource(TimeSpan.FromSeconds(25));
|
||||
using var retry = CancellationTokenSource.CreateLinkedTokenSource(sessionToken);
|
||||
retry.CancelAfter(TimeSpan.FromSeconds(25));
|
||||
retry.Token.ThrowIfCancellationRequested();
|
||||
await ProxyDnsPolicy.RestoreAsync(retry.Token).ConfigureAwait(false);
|
||||
}
|
||||
_stoppedCleanly = true;
|
||||
}
|
||||
|
||||
private async Task HandleCoreExitAsync(Process exited)
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
# 纵横家 Windows 0.3.7
|
||||
|
||||
修复自动升级确认后旧程序偶发无法退出,以及退出过程中后台升级检查继续操作已销毁窗口的问题。
|
||||
|
||||
- 升级确认和下载完成后重新检查窗口生命周期,退出时取消升级检查,避免关闭后再次弹窗。
|
||||
- 安装器等待旧程序的期限与网络恢复流程对齐,后台升级退出不被恢复警告弹窗挡住。
|
||||
- 关闭事件与窗口销毁发生竞争时安全结束回调。
|
||||
- Windows 查询关机时立即响应,取消关机不会改变当前连接;确认结束时使用限时清理,不再启动新的外部恢复工具或交互提示,未完成的恢复记录保留供下次启动处理。
|
||||
- 保留 0.3.6 的运行组件修复、内网优先和本机与服务器独立流量趋势。
|
||||
|
||||
验证包含同包离线回归和隔离退出/会话消息测试。没有重启当前电脑,不将模拟消息测试称为真实关机验收。安装包未签名,安装时仍需 Windows 授权。
|
||||
Reference in New Issue
Block a user