176 lines
9.1 KiB
C#
176 lines
9.1 KiB
C#
using System.Diagnostics;
|
|
using System.Security.Cryptography;
|
|
|
|
namespace UCVL.VPNPlus;
|
|
|
|
internal static class ClientUpdater
|
|
{
|
|
private const long MaximumInstallerBytes = 200L * 1024 * 1024;
|
|
// A 200 MiB package takes 1024 seconds on a slow 200 KiB/s link.
|
|
// Keep a bounded transfer budget with headroom; idle reads still stop at 30s.
|
|
internal static readonly TimeSpan DefaultTotalTimeout = TimeSpan.FromMinutes(20);
|
|
|
|
internal static bool IsNewerVersion(string candidate, string? current = null)
|
|
{
|
|
var currentText = current ?? Application.ProductVersion;
|
|
return GitReleaseUpdater.IsStableVersion(candidate)
|
|
&& TryParseComparableVersion(candidate, out var candidateVersion)
|
|
&& TryParseComparableVersion(currentText, out var currentVersion)
|
|
&& (candidateVersion > currentVersion
|
|
|| candidateVersion == currentVersion && currentText.Split('+')[0].Contains('-'));
|
|
}
|
|
|
|
internal static bool ShouldOffer(ClientUpdateInfo update, string? current = null)
|
|
=> update.Available && IsNewerVersion(update.Version, current);
|
|
|
|
private static bool TryParseComparableVersion(string? value, out Version version)
|
|
{
|
|
version = new Version(0, 0);
|
|
if (string.IsNullOrWhiteSpace(value)) return false;
|
|
|
|
// Older development builds displayed versions such as 0.2.4+d. Build
|
|
// metadata and prerelease labels must not prevent those clients from
|
|
// recognizing a newer stable release.
|
|
var normalized = value.Trim();
|
|
var suffixIndex = normalized.IndexOfAny(['+', '-']);
|
|
if (suffixIndex >= 0) normalized = normalized[..suffixIndex];
|
|
return Version.TryParse(normalized, out version!);
|
|
}
|
|
|
|
internal static bool SelfTest()
|
|
{
|
|
return TryParseComparableVersion("0.2.4+d", out var development)
|
|
&& development == new Version(0, 2, 4)
|
|
&& TryParseComparableVersion("0.2.7-beta.1", out var prerelease)
|
|
&& prerelease == new Version(0, 2, 7)
|
|
&& !TryParseComparableVersion("not-a-version", out _)
|
|
&& IsNewerVersion("99.0.0")
|
|
&& !IsNewerVersion("0.0.1");
|
|
}
|
|
|
|
internal static Task<string> DownloadAsync(ClientUpdateInfo update, CancellationToken cancellationToken, IProgress<int>? progress = null)
|
|
=> DownloadCoreAsync(update, cancellationToken, progress, AppPaths.DataDirectory);
|
|
|
|
// The fixture uses a disposable temp directory and in-memory HTTP transport.
|
|
// It exercises the same downloader without publishing or installing a release.
|
|
internal static Task<string> DownloadForTestAsync(ClientUpdateInfo update, CancellationToken cancellationToken,
|
|
IProgress<int> progress, string directory, HttpMessageHandler transport,
|
|
TimeSpan? totalTimeout = null, TimeSpan? idleTimeout = null)
|
|
=> DownloadCoreAsync(update, cancellationToken, progress, directory, transport, totalTimeout, idleTimeout);
|
|
|
|
private static async Task<string> DownloadCoreAsync(ClientUpdateInfo update, CancellationToken cancellationToken,
|
|
IProgress<int>? progress, string dataDirectory, HttpMessageHandler? transport = null,
|
|
TimeSpan? totalTimeout = null, TimeSpan? idleTimeout = null)
|
|
{
|
|
if (!GitReleaseUpdater.IsStableVersion(update.Version)) throw new InvalidOperationException("更新版本号无效。");
|
|
var expectedPath = $"/admin/ucvl-software-downloads/releases/download/windows-v{update.Version}/UCVL-Zonghengjia-{update.Version}-win-x64-setup.exe";
|
|
if (!Uri.TryCreate(update.DownloadUrl, UriKind.Absolute, out var uri)
|
|
|| uri.Scheme != Uri.UriSchemeHttps
|
|
|| !string.Equals(uri.Host, "pro.ucvl.cn", StringComparison.OrdinalIgnoreCase)
|
|
|| uri.Port != 443 || uri.UserInfo.Length != 0 || uri.Query.Length != 0 || uri.Fragment.Length != 0
|
|
|| uri.AbsolutePath != expectedPath)
|
|
{
|
|
throw new InvalidOperationException("更新下载地址未通过安全校验。");
|
|
}
|
|
if (update.Size <= 0 || update.Size > MaximumInstallerBytes)
|
|
{
|
|
throw new InvalidOperationException("更新包大小异常。");
|
|
}
|
|
if (update.Sha256.Length != 64 || update.Sha256.Any(character => !Uri.IsHexDigit(character)))
|
|
{
|
|
throw new InvalidOperationException("更新包校验值无效。");
|
|
}
|
|
|
|
var updateDirectory = Path.Combine(dataDirectory, "updates");
|
|
Directory.CreateDirectory(updateDirectory);
|
|
var finalPath = Path.Combine(updateDirectory, $"UCVL-Zonghengjia-{update.Version}-win-x64-setup.exe");
|
|
var partialPath = finalPath + ".part";
|
|
if (File.Exists(partialPath)) File.Delete(partialPath);
|
|
|
|
// ResponseHeadersRead ends HttpClient.Timeout at the response headers.
|
|
// Bound the entire transfer and each body read independently; a stalled
|
|
// download must not leave the update UI disabled indefinitely.
|
|
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
|
deadline.CancelAfter(totalTimeout ?? DefaultTotalTimeout);
|
|
var idleLimit = idleTimeout ?? TimeSpan.FromSeconds(30);
|
|
try
|
|
{
|
|
using var client = new HttpClient(transport ?? new SocketsHttpHandler { UseProxy = false, ConnectTimeout = TimeSpan.FromSeconds(10), AllowAutoRedirect = false }) { Timeout = TimeSpan.FromSeconds(30) };
|
|
client.DefaultRequestHeaders.UserAgent.ParseAdd($"UCVL-VPNPlus/{Application.ProductVersion} Windows-x64 Updater");
|
|
using var response = await client.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead, deadline.Token);
|
|
response.EnsureSuccessStatusCode();
|
|
if (response.Content.Headers.ContentLength is long contentLength
|
|
&& (contentLength != update.Size || contentLength > MaximumInstallerBytes))
|
|
{
|
|
throw new InvalidOperationException("更新包长度与发布信息不一致。");
|
|
}
|
|
|
|
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
|
|
var buffer = new byte[128 * 1024];
|
|
long total = 0;
|
|
await using (var source = await response.Content.ReadAsStreamAsync(deadline.Token))
|
|
await using (var destination = new FileStream(
|
|
partialPath,
|
|
FileMode.CreateNew,
|
|
FileAccess.Write,
|
|
FileShare.None,
|
|
128 * 1024,
|
|
FileOptions.Asynchronous | FileOptions.SequentialScan))
|
|
{
|
|
while (true)
|
|
{
|
|
using var readDeadline = CancellationTokenSource.CreateLinkedTokenSource(deadline.Token);
|
|
readDeadline.CancelAfter(idleLimit);
|
|
var read = await source.ReadAsync(buffer, readDeadline.Token);
|
|
if (read == 0) break;
|
|
total += read;
|
|
if (total > MaximumInstallerBytes || total > update.Size)
|
|
{
|
|
throw new InvalidOperationException("更新包超出允许大小。");
|
|
}
|
|
hash.AppendData(buffer, 0, read);
|
|
await destination.WriteAsync(buffer.AsMemory(0, read), deadline.Token);
|
|
progress?.Report((int)(total * 100 / update.Size));
|
|
}
|
|
await destination.FlushAsync(deadline.Token);
|
|
}
|
|
if (total != update.Size)
|
|
{
|
|
throw new InvalidOperationException("更新包下载不完整。");
|
|
}
|
|
var actualHash = Convert.ToHexString(hash.GetHashAndReset()).ToLowerInvariant();
|
|
if (!CryptographicOperations.FixedTimeEquals(
|
|
Convert.FromHexString(actualHash),
|
|
Convert.FromHexString(update.Sha256)))
|
|
{
|
|
throw new InvalidOperationException("更新包 SHA-256 校验失败。");
|
|
}
|
|
File.Move(partialPath, finalPath, overwrite: true);
|
|
return finalPath;
|
|
}
|
|
catch (Exception error)
|
|
{
|
|
try
|
|
{
|
|
if (File.Exists(partialPath)) File.Delete(partialPath);
|
|
}
|
|
catch { }
|
|
if (error is OperationCanceledException && !cancellationToken.IsCancellationRequested)
|
|
throw new TimeoutException("更新下载超时或长时间未收到数据,未启动安装;当前版本和连接保持不变,请稍后重试。", error);
|
|
throw;
|
|
}
|
|
}
|
|
|
|
internal static Process LaunchInstaller(string installerPath)
|
|
{
|
|
return Process.Start(new ProcessStartInfo
|
|
{
|
|
FileName = installerPath,
|
|
Arguments = $"/UPDATE /D={Path.TrimEndingDirectorySeparator(AppContext.BaseDirectory)}",
|
|
UseShellExecute = true,
|
|
Verb = "runas",
|
|
WorkingDirectory = Path.GetDirectoryName(installerPath) ?? AppPaths.DataDirectory,
|
|
}) ?? throw new IOException("安装器未能启动,当前程序保持运行。");
|
|
}
|
|
}
|