using System.Globalization; using System.Net; using System.Net.Sockets; using System.Text; using System.Text.Json.Nodes; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace Febe.SitoDiProva; /// Options of the test site. public sealed record TestSiteOptions { /// Port of the site on 127.0.0.1; 0 picks a free one. public int Port { get; init; } /// Port of the «CDN»; 0 picks a free one. public int CdnPort { get; init; } /// Address of the «CDN»: a second loopback address, so cookies of the site do not reach it. public string CdnAddress { get; init; } = "127.0.0.2"; /// Seed of the synthetic data. public int Seed { get; init; } = 13; /// Clock of the site (dates, address expiry). public TimeProvider Time { get; init; } = TimeProvider.System; /// Write requests to the console (the command-line tool does; tests do not). public bool ConsoleLog { get; init; } } /// /// The local test site of spec §14.2, served on 127.0.0.1 with its «CDN» on a second address. Pages are plain and /// fetch JSON in a synthetic format of our own; stop cases are switched through or the /// /_controllo endpoints. Never Instagram, never anything that looks like it. /// public sealed class TestSite : IAsyncDisposable { /// Name of the session cookie of the site. public const string SessionCookie = "sessione_prova"; private readonly WebApplication _app; private readonly TimeProvider _time; private TestSite(WebApplication app, World world, SiteControl control, MediaFactory media, CdnSigner signer, int sitePort, string cdnAddress, int cdnPort, TimeProvider time) { _app = app; World = world; Control = control; Media = media; Signer = signer; SitePort = sitePort; CdnAddress = cdnAddress; CdnPort = cdnPort; _time = time; } public World World { get; } public SiteControl Control { get; } public MediaFactory Media { get; } public CdnSigner Signer { get; } public int SitePort { get; } public string CdnAddress { get; } public int CdnPort { get; } /// «127.0.0.1:port»: an entry for the host classifier. public string SiteHost => $"127.0.0.1:{SitePort.ToString(CultureInfo.InvariantCulture)}"; public string CdnHost => $"{CdnAddress}:{CdnPort.ToString(CultureInfo.InvariantCulture)}"; public string SiteUrl => $"http://{SiteHost}"; public string CdnUrl => $"http://{CdnHost}"; public string Url(string path) => SiteUrl + path; public static async Task StartAsync(TestSiteOptions? options = null, CancellationToken ct = default) { options ??= new TestSiteOptions(); var cdnAddress = CanBind(options.CdnAddress) ? options.CdnAddress : "127.0.0.1"; var sitePort = options.Port > 0 ? options.Port : FreePort(IPAddress.Loopback); var cdnPort = options.CdnPort > 0 ? options.CdnPort : FreePort(IPAddress.Parse(cdnAddress)); if (cdnAddress == "127.0.0.1" && cdnPort == sitePort) { cdnPort = FreePort(IPAddress.Loopback); } var world = World.Generate(options.Seed, options.Time.GetUtcNow()); var control = new SiteControl(); var media = new MediaFactory(); var signer = new CdnSigner(); var builder = WebApplication.CreateSlimBuilder(); builder.Services.Configure(o => o.ShutdownTimeout = TimeSpan.FromSeconds(2)); builder.Logging.ClearProviders(); if (options.ConsoleLog) { builder.Logging.AddSimpleConsole(o => o.SingleLine = true); builder.Logging.SetMinimumLevel(LogLevel.Warning); } builder.WebHost.UseKestrel(k => { k.Listen(IPAddress.Loopback, sitePort); k.Listen(IPAddress.Parse(cdnAddress), cdnPort); }); var app = builder.Build(); var site = new TestSite(app, world, control, media, signer, sitePort, cdnAddress, cdnPort, options.Time); app.Run(site.HandleAsync); await app.StartAsync(ct).ConfigureAwait(false); return site; } public async ValueTask DisposeAsync() { await _app.StopAsync().ConfigureAwait(false); await _app.DisposeAsync().ConfigureAwait(false); } /// The JSON of a data endpoint as the page would receive it (sample capture, tests). public async Task GetDataAsync(string pathAndQuery, CancellationToken ct = default) { using var client = new HttpClient(new SocketsHttpHandler { UseProxy = false, UseCookies = false }); return await client.GetStringAsync(new Uri(Url(pathAndQuery)), ct).ConfigureAwait(false); } private DataApi Api => new(World, Signer, Control, () => CdnUrl, _time); private async Task HandleAsync(HttpContext context) { context.Response.Headers.CacheControl = "no-store"; if (context.Connection.LocalPort == CdnPort && context.Connection.LocalIpAddress?.ToString() == CdnAddress) { await ServeCdnAsync(context).ConfigureAwait(false); return; } var path = context.Request.Path.Value ?? "/"; if (path.StartsWith("/_controllo/", StringComparison.Ordinal)) { await ControlAsync(context, path["/_controllo/".Length..]).ConfigureAwait(false); return; } if (path.StartsWith("/risorse/", StringComparison.Ordinal)) { await ResourceAsync(context, path["/risorse/".Length..]).ConfigureAwait(false); return; } if (path.StartsWith("/dati/", StringComparison.Ordinal)) { await DataAsync(context, path).ConfigureAwait(false); return; } await PageAsync(context, path).ConfigureAwait(false); } private async Task PageAsync(HttpContext context, string path) { var mode = Control.Mode; if (path is "/verifica" or "/verifica/") { await HtmlAsync(context, 200, Pages.Challenge()).ConfigureAwait(false); return; } if (path is "/sessione-scaduta" or "/sessione-scaduta/") { await HtmlAsync(context, 200, Pages.SessionEnded()).ConfigureAwait(false); return; } if (path == "/favicon.ico") { context.Response.StatusCode = 404; return; } switch (mode) { case StopMode.Challenge: context.Response.Redirect("/verifica?motivo=prova"); return; case StopMode.SessionEnded: ExpireSession(context); context.Response.Redirect("/sessione-scaduta"); return; } if (!context.Request.Cookies.ContainsKey(SessionCookie)) { context.Response.Cookies.Append(SessionCookie, "attiva", new CookieOptions { Path = "/", MaxAge = TimeSpan.FromDays(1), SameSite = SameSiteMode.Lax, HttpOnly = true }); } var segments = path.Split('/', StringSplitOptions.RemoveEmptyEntries).Select(Uri.UnescapeDataString).ToArray(); string html; var status = 200; lock (World.Gate) { switch (segments) { case []: html = Pages.Home(); break; case ["profilo", var user, ..] when World.FindByUsername(user) is null: html = Pages.ProfileNotFound(user); status = 404; break; case ["profilo", var user]: html = Pages.Profile(user, ProfileTab.Posts); break; case ["profilo", var user, "reel"]: html = Pages.Profile(user, ProfileTab.Reels); break; case ["profilo", var user, "taggati"]: html = Pages.Profile(user, ProfileTab.Tagged); break; case ["profilo", var user, "seguiti"] when World.FindByUsername(user)?.IsViewer == true: html = Pages.Following(user); break; case ["post", var code, ..]: html = Pages.Post(code); break; case ["storie", _, ..]: html = Pages.Viewer("storie", Control.StoryDuration); break; case ["evidenza", _, ..]: html = Pages.Viewer("evidenza", Control.StoryDuration); break; default: html = Pages.NotFound(); status = 404; break; } } await HtmlAsync(context, status, html).ConfigureAwait(false); } private async Task DataAsync(HttpContext context, string path) { var query = context.Request.Query; var mode = Control.OnDataRequest(path + context.Request.QueryString.Value); switch (mode) { case StopMode.TooManyRequests: await JsonAsync(context, 429, new JsonObject { ["errore"] = "troppe-richieste", ["messaggio"] = "Troppe richieste: riprova più tardi." }).ConfigureAwait(false); return; case StopMode.Challenge: await JsonAsync(context, 403, new JsonObject { ["errore"] = "verifica" }).ConfigureAwait(false); return; case StopMode.SessionEnded: ExpireSession(context); await JsonAsync(context, 401, new JsonObject { ["errore"] = "sessione" }).ConfigureAwait(false); return; case StopMode.EmptyPages: await JsonAsync(context, 200, DataApi.EmptyPage()).ConfigureAwait(false); return; case StopMode.UnknownFormat: await JsonAsync(context, 200, DataApi.UnknownShape()).ConfigureAwait(false); return; } var segments = path.Split('/', StringSplitOptions.RemoveEmptyEntries).Select(Uri.UnescapeDataString).ToArray(); var tab = query["scheda"].ToString() switch { "reel" => ProfileTab.Reels, "taggati" => ProfileTab.Tagged, _ => ProfileTab.Posts }; var after = query["dopo"].ToString(); JsonObject? result; lock (World.Gate) { var api = Api; result = segments switch { ["dati", "inizio"] => api.Home(), ["dati", "inizio", "altri"] => api.HomeMore(after), ["dati", "profilo", var user] => api.Profile(user, tab, after), ["dati", "profilo", var user, "altri"] => api.ProfileMore(user, tab, after), ["dati", "post", var code] => api.SinglePost(code), ["dati", "storie", var user] => api.Stories(user), ["dati", "evidenza", var id] => api.HighlightItems(id), ["dati", "seguiti"] => api.Following(after), _ => null, }; } if (result is null) { await JsonAsync(context, 404, new JsonObject { ["errore"] = "non-trovato" }).ConfigureAwait(false); return; } await JsonAsync(context, 200, result).ConfigureAwait(false); } private async Task ServeCdnAsync(HttpContext context) { var path = context.Request.Path.Value ?? string.Empty; if (Control.CdnTooManyRequests) { Control.OnCdnThrottled(); context.Response.StatusCode = 429; context.Response.ContentType = "text/plain; charset=utf-8"; await context.Response.WriteAsync("Troppe richieste.").ConfigureAwait(false); return; } var query = context.Request.Query; var check = Signer.Check(path, query["scad"].ToString(), query["firma"].ToString(), _time.GetUtcNow()); if (check != CdnCheck.Valid) { if (check == CdnCheck.Expired) { Control.OnCdnExpired(); } context.Response.StatusCode = 403; context.Response.ContentType = "text/plain; charset=utf-8"; await context.Response.WriteAsync(check == CdnCheck.Expired ? "Indirizzo scaduto." : "Firma non valida.").ConfigureAwait(false); return; } // /m/{key}/{w}x{h}.jpg, /m/{key}/{w}x{h}.mp4, /m/{key}/{w}x{h}-muto.mp4 var segments = path.Split('/', StringSplitOptions.RemoveEmptyEntries); if (segments is not ["m", var key, var file] || !TryParseSize(file, out var width, out var height, out var extension, out var silent)) { context.Response.StatusCode = 404; return; } var bytes = extension == "mp4" ? Media.Video(key, width, height, !silent) : Media.Picture(key, width, height); Control.OnCdnServed(); context.Response.ContentType = extension == "mp4" ? "video/mp4" : "image/jpeg"; context.Response.ContentLength = bytes.Length; await context.Response.Body.WriteAsync(bytes).ConfigureAwait(false); } private async Task ControlAsync(HttpContext context, string command) { var q = context.Request.Query; JsonObject answer = new() { ["ok"] = true }; lock (World.Gate) { switch (command) { case "stato": answer["modo"] = Control.Mode.ToString(); answer["richieste"] = Control.DataRequests.Count; break; case "modo": var mode = q["valore"].ToString() switch { "troppe-richieste" => StopMode.TooManyRequests, "verifica" => StopMode.Challenge, "sessione-scaduta" => StopMode.SessionEnded, "vuoto" => StopMode.EmptyPages, "formato-sconosciuto" => StopMode.UnknownFormat, _ => StopMode.Normal, }; Control.Set(mode, int.TryParse(q["dopo"], NumberStyles.Integer, CultureInfo.InvariantCulture, out var after) ? after : 0); answer["modo"] = mode.ToString(); break; case "reimposta": Control.Reset(); break; case "durata-storie": Control.StoryDuration = TimeSpan.FromMilliseconds(int.Parse(q["ms"].ToString(), CultureInfo.InvariantCulture)); break; case "cdn-troppe-richieste": Control.CdnTooManyRequests = q["valore"].ToString() is "si" or "sì" or "true"; break; case "scadenza-indirizzi": Control.AddressLifetime = TimeSpan.FromSeconds(int.Parse(q["secondi"].ToString(), CultureInfo.InvariantCulture)); break; case "rinomina": var account = World.FindByUsername(q["da"].ToString()); if (account is null) { answer["ok"] = false; } else { account.Username = q["a"].ToString(); } break; case "ritratto": if (World.FindByUsername(q["nome"].ToString()) is { } owner) { owner.PictureVersion++; } break; case "pubblica": if (World.FindByUsername(q["nome"].ToString()) is { } author) { var post = World.Publish(author, q["tipo"].ToString() is { Length: > 0 } t ? t : "foto", _time.GetUtcNow()); answer["sigla"] = post.Code; answer["numero"] = post.Id; } break; default: answer["ok"] = false; break; } } await JsonAsync(context, answer["ok"]!.GetValue() ? 200 : 400, answer).ConfigureAwait(false); } private static async Task ResourceAsync(HttpContext context, string name) { if (name is not ("sito.js" or "sito.css")) { context.Response.StatusCode = 404; return; } await using var stream = typeof(TestSite).Assembly.GetManifestResourceStream($"Febe.SitoDiProva.Risorse.{name}"); if (stream is null) { context.Response.StatusCode = 404; return; } context.Response.ContentType = name.EndsWith(".js", StringComparison.Ordinal) ? "text/javascript; charset=utf-8" : "text/css; charset=utf-8"; await stream.CopyToAsync(context.Response.Body).ConfigureAwait(false); } private static void ExpireSession(HttpContext context) => context.Response.Cookies.Delete(SessionCookie, new CookieOptions { Path = "/" }); private static Task HtmlAsync(HttpContext context, int status, string html) { context.Response.StatusCode = status; context.Response.ContentType = "text/html; charset=utf-8"; return context.Response.WriteAsync(html); } private static Task JsonAsync(HttpContext context, int status, JsonObject body) { context.Response.StatusCode = status; context.Response.ContentType = "application/json; charset=utf-8"; return context.Response.WriteAsync(body.ToJsonString(), Encoding.UTF8); } private static bool TryParseSize(string file, out int width, out int height, out string extension, out bool silent) { width = height = 0; extension = string.Empty; silent = false; var dot = file.LastIndexOf('.'); if (dot < 0) { return false; } extension = file[(dot + 1)..]; var name = file[..dot]; if (name.EndsWith("-muto", StringComparison.Ordinal)) { silent = true; name = name[..^"-muto".Length]; } var x = name.IndexOf('x', StringComparison.Ordinal); return x > 0 && int.TryParse(name.AsSpan(0, x), NumberStyles.Integer, CultureInfo.InvariantCulture, out width) && int.TryParse(name.AsSpan(x + 1), NumberStyles.Integer, CultureInfo.InvariantCulture, out height) && extension is "jpg" or "mp4"; } private static bool CanBind(string address) { try { using var probe = new TcpListener(IPAddress.Parse(address), 0); probe.Start(); probe.Stop(); return true; } catch (Exception ex) when (ex is SocketException or FormatException) { return false; } } private static int FreePort(IPAddress address) { var probe = new TcpListener(address, 0); probe.Start(); var port = ((IPEndPoint)probe.LocalEndpoint).Port; probe.Stop(); return port; } }