133 lines
7.9 KiB
C#
133 lines
7.9 KiB
C#
|
|
using System.Net;
|
||
|
|
using System.Security.Cryptography;
|
||
|
|
using System.Text.Json;
|
||
|
|
|
||
|
|
namespace UCVL.VPNPlus;
|
||
|
|
|
||
|
|
// Cancellable in-memory HTTP bodies; never connects, installs, or reads an account.
|
||
|
|
internal static class UpdateStreamSelfTest
|
||
|
|
{
|
||
|
|
private sealed class ProgressCapture : IProgress<int>
|
||
|
|
{
|
||
|
|
internal readonly List<int> Values = [];
|
||
|
|
public void Report(int value) => Values.Add(value);
|
||
|
|
}
|
||
|
|
private sealed class SlowStream(byte[] data, int chunk = 1, int delayMs = 0, bool stall = false) : Stream
|
||
|
|
{
|
||
|
|
private int _offset;
|
||
|
|
internal bool Disposed;
|
||
|
|
internal int BytesRead => _offset;
|
||
|
|
public override bool CanRead => true;
|
||
|
|
public override bool CanSeek => false;
|
||
|
|
public override bool CanWrite => false;
|
||
|
|
public override long Length => throw new NotSupportedException();
|
||
|
|
public override long Position { get => _offset; set => throw new NotSupportedException(); }
|
||
|
|
public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken ct = default)
|
||
|
|
{
|
||
|
|
if (stall) await Task.Delay(Timeout.Infinite, ct);
|
||
|
|
ct.ThrowIfCancellationRequested();
|
||
|
|
if (_offset == data.Length) return 0;
|
||
|
|
if (delayMs > 0) await Task.Delay(delayMs, ct);
|
||
|
|
var count = Math.Min(Math.Min(chunk, buffer.Length), data.Length - _offset);
|
||
|
|
data.AsMemory(_offset, count).CopyTo(buffer); _offset += count; return count;
|
||
|
|
}
|
||
|
|
protected override void Dispose(bool disposing) { Disposed = true; base.Dispose(disposing); }
|
||
|
|
public override void Flush() => throw new NotSupportedException();
|
||
|
|
public override int Read(byte[] b, int o, int n) => throw new NotSupportedException();
|
||
|
|
public override long Seek(long o, SeekOrigin s) => throw new NotSupportedException();
|
||
|
|
public override void SetLength(long n) => throw new NotSupportedException();
|
||
|
|
public override void Write(byte[] b, int o, int n) => throw new NotSupportedException();
|
||
|
|
}
|
||
|
|
private sealed class Handler(SlowStream stream, long size, string? metadata = null, bool stallHeaders = false) : HttpMessageHandler
|
||
|
|
{
|
||
|
|
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
|
||
|
|
{
|
||
|
|
if (request.RequestUri?.Host != "pro.ucvl.cn" || request.Headers.Authorization is not null)
|
||
|
|
throw new IOException("Unexpected update test destination or credentials.");
|
||
|
|
if (stallHeaders) await Task.Delay(Timeout.Infinite, ct);
|
||
|
|
if (metadata is not null && request.RequestUri.AbsolutePath.EndsWith("/releases", StringComparison.Ordinal))
|
||
|
|
return new(HttpStatusCode.OK) { Content = new StringContent(metadata) };
|
||
|
|
var content = new StreamContent(stream); content.Headers.ContentLength = size;
|
||
|
|
return new(HttpStatusCode.OK) { Content = content };
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
internal static async Task RunAsync(Dictionary<string, object> report, string folder)
|
||
|
|
{
|
||
|
|
var bytes = RandomNumberGenerator.GetBytes(4096);
|
||
|
|
const string filename = "UCVL-Zonghengjia-0.2.16-win-x64-setup.exe";
|
||
|
|
var info = new ClientUpdateInfo {
|
||
|
|
Version = "0.2.16", Available = true, Size = bytes.Length,
|
||
|
|
Sha256 = Convert.ToHexString(SHA256.HashData(bytes)),
|
||
|
|
DownloadUrl = "https://pro.ucvl.cn/admin/ucvl-software-downloads/releases/download/windows-v0.2.16/" + filename,
|
||
|
|
};
|
||
|
|
var shortLimit = TimeSpan.FromMilliseconds(250);
|
||
|
|
var longLimit = TimeSpan.FromSeconds(4);
|
||
|
|
var metadata = JsonSerializer.Serialize(new[] { new {
|
||
|
|
tag_name = "windows-v0.2.16", draft = false, prerelease = false,
|
||
|
|
assets = new[] { new { name = filename, size = bytes.Length }, new { name = filename + ".sha256", size = 120 } },
|
||
|
|
} });
|
||
|
|
foreach (var checksumStage in new[] { false, true })
|
||
|
|
{
|
||
|
|
using var fallback = new CancellationTokenSource(TimeSpan.FromSeconds(3));
|
||
|
|
using var stalled = new SlowStream(bytes, stall: true);
|
||
|
|
var rejected = false;
|
||
|
|
try { await GitReleaseUpdater.GetLatestAsync(fallback.Token,
|
||
|
|
new Handler(stalled, bytes.Length, checksumStage ? metadata : null), "0.2.15", shortLimit); }
|
||
|
|
catch (OperationCanceledException) { rejected = !fallback.IsCancellationRequested; }
|
||
|
|
report[checksumStage ? "git_checksum_body_deadline" : "git_metadata_body_deadline"] = rejected && stalled.Disposed;
|
||
|
|
}
|
||
|
|
|
||
|
|
var stalledDirectory = Path.Combine(folder, "stall");
|
||
|
|
Directory.CreateDirectory(Path.Combine(stalledDirectory, "updates"));
|
||
|
|
var previousDownload = Path.Combine(stalledDirectory, "updates", filename);
|
||
|
|
File.WriteAllBytes(previousDownload, bytes); // inert test bytes, never run
|
||
|
|
using (var stalled = new SlowStream(bytes, stall: true))
|
||
|
|
using (var fallback = new CancellationTokenSource(TimeSpan.FromSeconds(3)))
|
||
|
|
{
|
||
|
|
var rejected = false;
|
||
|
|
try { await ClientUpdater.DownloadForTestAsync(info, fallback.Token, new ProgressCapture(), stalledDirectory,
|
||
|
|
new Handler(stalled, bytes.Length), longLimit, shortLimit); }
|
||
|
|
catch (TimeoutException) { rejected = !fallback.IsCancellationRequested; }
|
||
|
|
report["download_idle_body_deadline"] = rejected && stalled.Disposed;
|
||
|
|
report["timeout_preserves_previous_verified_download"] = File.ReadAllBytes(previousDownload).SequenceEqual(bytes);
|
||
|
|
}
|
||
|
|
using (var trickle = new SlowStream(bytes, delayMs: 20))
|
||
|
|
using (var fallback = new CancellationTokenSource(TimeSpan.FromSeconds(3)))
|
||
|
|
{
|
||
|
|
var rejected = false;
|
||
|
|
try { await ClientUpdater.DownloadForTestAsync(info, fallback.Token, new ProgressCapture(), Path.Combine(folder, "trickle"),
|
||
|
|
new Handler(trickle, bytes.Length), shortLimit, TimeSpan.FromSeconds(2)); }
|
||
|
|
catch (TimeoutException) { rejected = !fallback.IsCancellationRequested; }
|
||
|
|
report["download_total_deadline_despite_continuous_data"] = rejected && trickle.BytesRead > 0 && trickle.Disposed;
|
||
|
|
}
|
||
|
|
using (var stalled = new SlowStream(bytes, stall: true))
|
||
|
|
using (var caller = new CancellationTokenSource(shortLimit))
|
||
|
|
{
|
||
|
|
var cancelled = false;
|
||
|
|
try { await ClientUpdater.DownloadForTestAsync(info, caller.Token, new ProgressCapture(), Path.Combine(folder, "caller"),
|
||
|
|
new Handler(stalled, bytes.Length), longLimit, longLimit); }
|
||
|
|
catch (OperationCanceledException) { cancelled = caller.IsCancellationRequested; }
|
||
|
|
report["mid_body_caller_cancellation_not_relabelled_timeout"] = cancelled && stalled.Disposed;
|
||
|
|
}
|
||
|
|
using (var stream = new SlowStream(bytes))
|
||
|
|
using (var fallback = new CancellationTokenSource(TimeSpan.FromSeconds(3)))
|
||
|
|
{
|
||
|
|
var rejected = false;
|
||
|
|
try { await ClientUpdater.DownloadForTestAsync(info, fallback.Token, new ProgressCapture(), Path.Combine(folder, "headers"),
|
||
|
|
new Handler(stream, bytes.Length, stallHeaders: true), shortLimit, longLimit); }
|
||
|
|
catch (TimeoutException) { rejected = !fallback.IsCancellationRequested; }
|
||
|
|
report["download_deadline_includes_waiting_for_headers"] = rejected;
|
||
|
|
}
|
||
|
|
using (var slow = new SlowStream(bytes, chunk: 1024, delayMs: 25))
|
||
|
|
{
|
||
|
|
var progress = new ProgressCapture();
|
||
|
|
var file = await ClientUpdater.DownloadForTestAsync(info, CancellationToken.None, progress, Path.Combine(folder, "slow-success"),
|
||
|
|
new Handler(slow, bytes.Length), longLimit, TimeSpan.FromSeconds(2));
|
||
|
|
report["slow_valid_stream_completes_and_disposes"] = File.ReadAllBytes(file).SequenceEqual(bytes)
|
||
|
|
&& slow.Disposed && progress.Values.Count == 4 && progress.Values[^1] == 100;
|
||
|
|
}
|
||
|
|
report["stalled_stream_partials_cleaned"] = !Directory.EnumerateFiles(folder, "*.part", SearchOption.AllDirectories).Any();
|
||
|
|
}
|
||
|
|
}
|