using System.Net; using System.Net.Sockets; using System.Security.Cryptography; using System.Text; namespace Febe.Tests.Browser.TestSupport; /// /// Tiny local site served by the test itself on 127.0.0.1 (never Instagram): one port plays the site, another the CDN. /// public sealed class LocalTestSite : IDisposable { public const int BigFileBytes = 24 * 1024 * 1024; private static readonly Lazy<(byte[] Bytes, string Sha256)> BigFile = new(() => { var bytes = new byte[BigFileBytes]; new Random(20261013).NextBytes(bytes); return (bytes, Convert.ToHexString(SHA256.HashData(bytes))); }); private readonly HttpListener _listener = new(); private readonly CancellationTokenSource _stop = new(); public LocalTestSite() { SitePort = FreePort(); CdnPort = FreePort(); _listener.Prefixes.Add($"http://127.0.0.1:{SitePort}/"); _listener.Prefixes.Add($"http://127.0.0.1:{CdnPort}/"); _listener.Start(); _ = Task.Run(LoopAsync); } public int SitePort { get; } public int CdnPort { get; } public string SiteHost => $"127.0.0.1:{SitePort}"; public string CdnHost => $"127.0.0.1:{CdnPort}"; public static string BigFileSha256 => BigFile.Value.Sha256; public string Url(string path) => $"http://{SiteHost}{path}"; /// The same site under the name «localhost»: another site for Chromium, so another renderer. public string LocalhostUrl(string path) => $"http://localhost:{SitePort}{path}"; public string CdnUrl(string path) => $"http://{CdnHost}{path}"; // Ports handed out by FreePort come from 20000-29999: below the ephemeral ranges of Linux (32768-60999) and Windows // (49152-65535), so an outgoing connection of another test cannot take one between the probe and the moment the // test binds it (a port handed out by the system's port 0 could, CI run 350 of #52). Each port is handed out once // per process; the start depends on the process id, so two test processes on one machine rarely meet. private const int FirstTestPort = 20000; private const int TestPorts = 10000; private static int _nextPort = Environment.ProcessId * 7919 % TestPorts; /// /// A port of 127.0.0.1 that is free now, never handed out before in this process and outside the system's ephemeral /// range. The caller binds it soon after; nothing can reserve it in between, but no other test of this process gets /// it and no outgoing connection is given it. /// public static int FreePort() { for (var attempt = 0; attempt < TestPorts; attempt++) { var port = FirstTestPort + (int)((uint)Interlocked.Increment(ref _nextPort) % TestPorts); var probe = new TcpListener(IPAddress.Loopback, port); try { probe.Start(); } catch (SocketException) { continue; } finally { probe.Stop(); } return port; } throw new InvalidOperationException("Nessuna porta libera fra 20000 e 29999."); } private int _disposed; public void Dispose() { if (Interlocked.Exchange(ref _disposed, 1) == 1) { return; } _stop.Cancel(); try { _listener.Stop(); _listener.Close(); } catch (ObjectDisposedException) { } _stop.Dispose(); } private async Task LoopAsync() { while (!_stop.IsCancellationRequested) { HttpListenerContext context; try { context = await _listener.GetContextAsync(); } catch (Exception ex) when (ex is HttpListenerException or ObjectDisposedException or InvalidOperationException) { return; } _ = Task.Run(() => HandleAsync(context)); } } private async Task HandleAsync(HttpListenerContext context) { var response = context.Response; try { var path = context.Request.Url!.AbsolutePath; if (context.Request.Url.Port == CdnPort) { if (path == "/file.bin") { response.ContentType = "application/octet-stream"; response.ContentLength64 = BigFile.Value.Bytes.Length; await response.OutputStream.WriteAsync(BigFile.Value.Bytes); } else { response.StatusCode = 404; } return; } switch (path) { case "/api/dati.json": await JsonAsync(response, 200, """{"elementi":[{"id":"1","testo":"ciao"},{"id":"2","testo":"mondo"}]}"""); return; case "/api/troppe": await JsonAsync(response, 429, """{"messaggio":"troppe richieste"}"""); return; case "/api/attendi.json": await JsonAsync(response, 200, """{"messaggio":"Attendi qualche minuto prima di riprovare."}"""); return; case "/vai-a-verifica": response.StatusCode = 302; response.RedirectLocation = "/verifica?da=prova"; return; case "/cookie": response.AppendHeader("Set-Cookie", "sessionid=valore-finto-di-prova; Path=/; Max-Age=86400; SameSite=Lax"); await HtmlAsync(response, "

Cookie impostato

"); return; default: await HtmlAsync(response, Page(path)); return; } } catch (Exception ex) when (ex is HttpListenerException or IOException or ObjectDisposedException) { } finally { try { response.Close(); } catch (Exception ex) when (ex is HttpListenerException or ObjectDisposedException or InvalidOperationException) { } } } private static string Page(string path) => path switch { "/lunga" => string.Concat(Enumerable.Range(1, 300).Select(i => $"

Riga {i} di una pagina lunga.

")) + "", "/bottoni" => """
alice Storia di alice
""", "/cattura" => "

Cattura

", "/cattura-429" => "

Troppe

", "/cattura-attendi" => "

Attendi

", "/animata" => """
""", "/modulo" => """ """, "/spa" => "

Applicazione

", "/verifica" => "

Verifica

", "/accesso" => "

Accesso

", // Keeps its renderer busy for 2 s, from 0.1 s after it has committed: a navigation away from it to a page of the // same site (same renderer) reaches «ready to commit» at once but commits only when the script lets go. "/occupata" => "

Occupata

", _ => "

Pagina di prova

", }; private static Task HtmlAsync(HttpListenerResponse response, string body) => WriteAsync(response, 200, "text/html; charset=utf-8", $"Prova{body}"); private static Task JsonAsync(HttpListenerResponse response, int status, string json) => WriteAsync(response, status, "application/json; charset=utf-8", json); private static async Task WriteAsync(HttpListenerResponse response, int status, string contentType, string body) { var bytes = Encoding.UTF8.GetBytes(body); response.StatusCode = status; response.ContentType = contentType; response.ContentLength64 = bytes.Length; response.AddHeader("Cache-Control", "no-store"); await response.OutputStream.WriteAsync(bytes); } }