Server reale e veste Docker (M5): composizione, collegamento, vista remota, salute, immagine e modello Unraid

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
Claude committed 2026-10-13 20:17:22 +00:00
1 parent 0515776b04
commit 550c220cd4
35 files changed
+6124 -10

No files matched your search

+14
View File
@@ -123,6 +123,20 @@ public static class Keyboard
public static Task KeyUpAsync(ICdpSession cdp, KeyStroke key, CancellationToken ct = default) =>
cdp.SendAsync("Input.dispatchKeyEvent", Build("keyUp", key), ct);
/// <summary>
/// Inserts text without key codes (<c>Input.dispatchKeyEvent</c> of type «char»): composed characters of the
/// remote view, such as «è» typed with a dead key. Never logged.
/// </summary>
public static Task CharAsync(ICdpSession cdp, string text, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(cdp);
ArgumentException.ThrowIfNullOrEmpty(text);
return cdp.SendAsync(
"Input.dispatchKeyEvent",
new JsonObject { ["type"] = "char", ["text"] = text, ["unmodifiedText"] = text },
ct);
}
/// <summary>Presses and releases one key, with a human hold time when a clock is given.</summary>
public static async Task PressAsync(ICdpSession cdp, KeyStroke key, IClock? clock = null, IRandomSource? random = null, CancellationToken ct = default)
{
@@ -27,12 +27,14 @@ public sealed class ChromiumProcessHost : IBrowserHost
private readonly IBrowserLog _log;
private readonly ReconnectingCdpSession _session = new();
private readonly SemaphoreSlim _connectLock = new(1, 1);
private readonly SemaphoreSlim _restartLock = new(1, 1);
// Not disposed on purpose: background reconnection may still read its token; it holds no timer or handle.
private readonly CancellationTokenSource _lifetime = new();
private SupervisedProcess? _supervisor;
private CdpClient? _client;
private BrowserOptions? _options;
private int _stopping;
private int _restarting;
public ChromiumProcessHost(ChromiumLaunchOptions? launch = null, IClock? clock = null, IBrowserLog? log = null)
{
@@ -62,6 +64,9 @@ public sealed class ChromiumProcessHost : IBrowserHost
public event EventHandler<SupervisedState>? StateChanged;
/// <summary>True while a page connection is attached (commands can be sent).</summary>
public bool IsAttached => _session.IsAttached;
public async Task StartAsync(BrowserOptions options, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(options);
@@ -70,6 +75,47 @@ public sealed class ChromiumProcessHost : IBrowserHost
throw new InvalidOperationException("Il browser è già avviato.");
}
await StartCoreAsync(options, ct).ConfigureAwait(false);
}
/// <summary>
/// Stops the browser (SIGINT, so the profile is written to disk), runs <paramref name="whileStopped"/> — «Scollega»
/// deletes the profile there — and starts it again with the same options. <see cref="Cdp"/> stays the same object:
/// subscriptions survive and <see cref="ICdpConnectionEvents.Reconnected"/> is raised once the new browser is
/// connected.
/// </summary>
public async Task RestartAsync(Action? whileStopped, CancellationToken ct)
{
var options = _options ?? throw new InvalidOperationException("Il browser non è mai partito.");
if (Volatile.Read(ref _stopping) == 1)
{
throw new InvalidOperationException("Il browser si sta fermando.");
}
await _restartLock.WaitAsync(ct).ConfigureAwait(false);
Interlocked.Exchange(ref _restarting, 1);
try
{
if (_supervisor is { } current)
{
await DropClientAsync().ConfigureAwait(false);
await current.StopAsync(StopGrace).ConfigureAwait(false);
_supervisor = null;
_log.Info("Chromium è fermo per un nuovo avvio.");
}
whileStopped?.Invoke();
await StartCoreAsync(options, ct).ConfigureAwait(false);
}
finally
{
Interlocked.Exchange(ref _restarting, 0);
_restartLock.Release();
}
}
private async Task StartCoreAsync(BrowserOptions options, CancellationToken ct)
{
var executable = ChromiumCommandLine.FindExecutable(options.ExecutablePath)
?? throw new FileNotFoundException("Chromium non è installato o non si trova (si può indicare con FEBE_CHROMIUM).");
var arguments = ChromiumCommandLine.Build(options, _launch);
@@ -131,10 +177,20 @@ public sealed class ChromiumProcessHost : IBrowserHost
}
await _lifetime.CancelAsync().ConfigureAwait(false);
await DropClientAsync().ConfigureAwait(false);
if (_supervisor is { } supervisor)
// A restart in progress («Scollega») finishes first, so that no browser is left running behind the stop.
await _restartLock.WaitAsync().ConfigureAwait(false);
try
{
await supervisor.StopAsync(StopGrace).ConfigureAwait(false);
await DropClientAsync().ConfigureAwait(false);
if (_supervisor is { } supervisor)
{
await supervisor.StopAsync(StopGrace).ConfigureAwait(false);
}
}
finally
{
_restartLock.Release();
}
_log.Info("Chromium è fermo.");
@@ -248,7 +304,7 @@ public sealed class ChromiumProcessHost : IBrowserHost
private void OnClientDisconnected(object? sender, Exception? reason)
{
if (Volatile.Read(ref _stopping) == 1 || !ReferenceEquals(sender, Volatile.Read(ref _client)))
if (Volatile.Read(ref _stopping) == 1 || Volatile.Read(ref _restarting) == 1 || !ReferenceEquals(sender, Volatile.Read(ref _client)))
{
return;
}
@@ -167,6 +167,13 @@ public sealed class RemoteViewSession : IAsyncDisposable
return e.Down ? Keyboard.KeyDownAsync(_cdp, e.Key, ct) : Keyboard.KeyUpAsync(_cdp, e.Key, ct);
}
/// <summary>Inserts composed text (a «char» event without key codes). Never logged.</summary>
public Task CharAsync(string text, CancellationToken ct = default)
{
EnsureActive();
return Keyboard.CharAsync(_cdp, text, ct);
}
/// <summary>Opens an address chosen by Alberto (e.g. the login page from the connection page).</summary>
public Task<NavigationResult> NavigateAsync(string url, CancellationToken ct = default)
{
+460
View File
@@ -0,0 +1,460 @@
using System.Runtime.CompilerServices;
using System.Text.Json;
using Febe.Browser.Cdp;
using Febe.Browser.Gestures;
using Febe.Browser.RemoteView;
using Febe.Core.Abstractions;
using Febe.Web.Connection;
using Febe.Web.Engine;
namespace Febe.Server;
/// <summary>
/// The remote view over the real Chromium (spec §4.1, §11, PROTOCOLLO.md): a <see cref="RemoteViewSession"/> per open
/// view, which holds the «Alberto is driving» lease while it is open, so the engine is still. One view at a time: a
/// view opened in another tab replaces the older one. Keys go to the browser and nowhere else.
/// </summary>
internal sealed class BrowserRemoteViewHost(BrowserSupervisor browser, BrowserUseTracker tracker, IClock clock, ServerLog log) : IRemoteViewHost
{
private readonly Lock _gate = new();
private BrowserRemoteViewConnection? _current;
private bool _shuttingDown;
public async Task<IRemoteViewConnection> OpenAsync(CancellationToken ct)
{
if (!browser.IsAvailable)
{
throw new RemoteViewUnavailableException(browser.LastError is { } error
? "Il browser di Febe non è in funzione: " + error
: "Il browser di Febe si sta avviando: riprova fra qualche secondo.");
}
BrowserRemoteViewConnection? previous;
lock (_gate)
{
if (_shuttingDown)
{
throw new RemoteViewUnavailableException("Febe si sta fermando.");
}
previous = _current;
_current = null;
}
if (previous is not null)
{
await previous.EndAsync(RemoteViewEnd.Replaced).ConfigureAwait(false);
}
var connection = new BrowserRemoteViewConnection(this, browser, tracker, clock);
try
{
await connection.StartAsync(browser.BrowserOptions.WindowWidth, browser.BrowserOptions.WindowHeight, ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException)
{
await connection.DisposeAsync().ConfigureAwait(false);
throw new RemoteViewUnavailableException("Il browser di Febe non risponde: riprova fra qualche secondo.", ex);
}
lock (_gate)
{
_current = connection;
}
log.Info("vista", "Vista remota aperta: il motore resta fermo finché è aperta.");
return connection;
}
/// <summary>Febe is stopping: the open view is closed with a reason the page can show.</summary>
public async Task ShutdownAsync()
{
BrowserRemoteViewConnection? current;
lock (_gate)
{
_shuttingDown = true;
current = _current;
_current = null;
}
if (current is not null)
{
await current.EndAsync(RemoteViewEnd.ShuttingDown).ConfigureAwait(false);
}
}
internal void Closed(BrowserRemoteViewConnection connection)
{
lock (_gate)
{
if (ReferenceEquals(_current, connection))
{
_current = null;
}
}
log.Info("vista", "Vista remota chiusa.");
}
}
/// <summary>One open remote view on the real browser.</summary>
internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
{
private readonly BrowserRemoteViewHost _owner;
private readonly BrowserSupervisor _browser;
private readonly BrowserUseTracker _tracker;
private readonly IClock _clock;
private readonly RemoteViewSession _session;
private readonly Lock _gate = new();
private readonly Queue<RemoteViewMeta> _meta = new();
private readonly SemaphoreSlim _signal = new(0, int.MaxValue);
private readonly CancellationTokenSource _ended = new();
private readonly List<IDisposable> _subscriptions = [];
// Full addresses of this view, for «back»: kept in memory only, never logged and never sent (the page gets them
// without query string).
private readonly List<string> _history = [];
private ScreencastFrame? _pendingFrame;
private string? _mainFrameId;
private string _url = "about:blank";
private int _width;
private int _height;
private int _disposed;
private bool _used;
public BrowserRemoteViewConnection(BrowserRemoteViewHost owner, BrowserSupervisor browser, BrowserUseTracker tracker, IClock clock)
{
_owner = owner;
_browser = browser;
_tracker = tracker;
_clock = clock;
_session = new RemoteViewSession(browser.Host.Cdp, browser.Host.UserDriving);
}
public RemoteViewEnd? Ended { get; private set; }
private ICdpSession Cdp => _browser.Host.Cdp;
public async Task StartAsync(int width, int height, CancellationToken ct)
{
_width = width;
_height = height;
_subscriptions.Add(Cdp.On("Page.frameNavigated", OnFrameNavigated));
_subscriptions.Add(Cdp.On("Page.navigatedWithinDocument", OnNavigatedWithinDocument));
var tree = await Cdp.SendAsync("Page.getFrameTree", null, ct).ConfigureAwait(false);
var frame = tree.GetProperty("frameTree").GetProperty("frame");
_mainFrameId = frame.GetProperty("id").GetString();
var url = frame.TryGetProperty("url", out var u) ? u.GetString() ?? string.Empty : string.Empty;
lock (_gate)
{
_history.Add(url);
_url = WithoutQuery(url);
_meta.Enqueue(new RemoteViewMeta(_width, _height, _url));
}
_signal.Release();
_session.Screencast.FrameReceived += OnFrame;
await _session.StartAsync(new ScreencastOptions(Quality: 70, MaxWidth: width, MaxHeight: height), ct).ConfigureAwait(false);
}
public async IAsyncEnumerable<RemoteViewOutput> ReadAsync([EnumeratorCancellation] CancellationToken ct)
{
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, _ended.Token);
while (true)
{
try
{
await _signal.WaitAsync(linked.Token).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
yield break;
}
RemoteViewMeta? meta = null;
ScreencastFrame? frame = null;
lock (_gate)
{
if (_meta.Count > 0)
{
meta = _meta.Dequeue();
}
else
{
frame = _pendingFrame;
_pendingFrame = null;
}
}
if (meta is not null)
{
yield return meta;
}
else if (frame is not null)
{
yield return new RemoteViewFrame(frame.Jpeg);
}
}
}
public Task MouseAsync(RemoteViewMouse input, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(input);
if (_session.Screencast.LastFrame is null)
{
return Task.CompletedTask; // no frame yet: nothing on screen to point at
}
MarkUsed();
var action = input.Action switch
{
RemoteViewMouseAction.Down => RemoteMouseAction.Down,
RemoteViewMouseAction.Up => RemoteMouseAction.Up,
RemoteViewMouseAction.Wheel => RemoteMouseAction.Wheel,
_ => RemoteMouseAction.Move,
};
var button = input.Button switch
{
RemoteViewButton.Left => RemoteMouseButton.Left,
RemoteViewButton.Middle => RemoteMouseButton.Middle,
RemoteViewButton.Right => RemoteMouseButton.Right,
_ => RemoteMouseButton.None,
};
return _session.MouseAsync(new RemoteMouseEvent(action, input.X, input.Y, button, input.ClickCount, input.DeltaX, input.DeltaY), ct);
}
public Task KeyAsync(RemoteViewKey input, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(input);
MarkUsed();
if (input.Action == RemoteViewKeyAction.Char)
{
return _session.CharAsync(input.Text!, ct);
}
return _session.KeyAsync(new RemoteKeyEvent(input.Action == RemoteViewKeyAction.Down, RemoteKeys.ToStroke(input)), ct);
}
public async Task NavigateAsync(RemoteViewNavigation action, CancellationToken ct)
{
MarkUsed();
string? target;
lock (_gate)
{
if (action == RemoteViewNavigation.Back)
{
if (_history.Count < 2)
{
return;
}
_history.RemoveAt(_history.Count - 1);
target = _history[^1];
}
else
{
target = _history.Count > 0 ? _history[^1] : null;
}
}
if (string.IsNullOrEmpty(target))
{
return;
}
// Alberto's own navigation while he drives (rule 7): not an engine action, no Governor.
await _session.NavigateAsync(target, ct).ConfigureAwait(false);
}
/// <summary>Ends the view from the server side (another tab, shutdown): the page is told why.</summary>
public async Task EndAsync(RemoteViewEnd reason)
{
Ended ??= reason;
await DisposeAsync().ConfigureAwait(false);
}
public async ValueTask DisposeAsync()
{
if (Interlocked.Exchange(ref _disposed, 1) == 1)
{
return;
}
Ended ??= RemoteViewEnd.BrowserStopped;
await _ended.CancelAsync().ConfigureAwait(false);
_session.Screencast.FrameReceived -= OnFrame;
foreach (var subscription in _subscriptions)
{
subscription.Dispose();
}
try
{
await _session.DisposeAsync().ConfigureAwait(false);
}
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException or OperationCanceledException)
{
// The browser is gone: the lease is released anyway.
}
_owner.Closed(this);
}
private void MarkUsed()
{
if (!_used)
{
_used = true;
_tracker.MarkUsed(_clock.Now);
}
}
private void OnFrame(object? sender, ScreencastFrame frame)
{
var width = (int)Math.Round(frame.DeviceWidth);
var height = (int)Math.Round(frame.DeviceHeight);
lock (_gate)
{
if (width > 0 && height > 0 && (width != _width || height != _height))
{
_width = width;
_height = height;
_meta.Enqueue(new RemoteViewMeta(width, height, _url));
_signal.Release();
}
var hadPending = _pendingFrame is not null;
_pendingFrame = frame;
if (hadPending)
{
return; // the older frame is replaced: the reader is behind
}
}
_signal.Release();
}
private void OnFrameNavigated(JsonElement e)
{
if (!e.TryGetProperty("frame", out var frame) || frame.TryGetProperty("parentId", out _))
{
return;
}
if (frame.TryGetProperty("id", out var id) && id.GetString() is { } frameId)
{
_mainFrameId = frameId; // a new main frame after a browser restart
}
Navigated(frame.TryGetProperty("url", out var u) ? u.GetString() : null);
}
private void OnNavigatedWithinDocument(JsonElement e)
{
if (e.TryGetProperty("frameId", out var id) && id.GetString() is { } frameId && frameId == _mainFrameId)
{
Navigated(e.TryGetProperty("url", out var u) ? u.GetString() : null);
}
}
private void Navigated(string? url)
{
if (string.IsNullOrEmpty(url))
{
return;
}
lock (_gate)
{
if (_history.Count == 0 || _history[^1] != url)
{
_history.Add(url);
if (_history.Count > 50)
{
_history.RemoveAt(0);
}
}
var shown = WithoutQuery(url);
if (shown == _url)
{
return;
}
_url = shown;
_meta.Enqueue(new RemoteViewMeta(_width, _height, shown));
}
_signal.Release();
}
/// <summary>The address without query string or fragment (they may carry tokens).</summary>
internal static string WithoutQuery(string url)
{
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri))
{
var cut = url.IndexOfAny(['?', '#']);
return cut < 0 ? url : url[..cut];
}
return uri.Scheme is "http" or "https" ? uri.GetLeftPart(UriPartial.Path) : uri.GetLeftPart(UriPartial.Scheme) + uri.AbsolutePath;
}
}
/// <summary>Turns the DOM key of the page into what <c>Input.dispatchKeyEvent</c> needs (virtual key codes).</summary>
internal static class RemoteKeys
{
private static readonly Dictionary<string, int> Named = new(StringComparer.Ordinal)
{
["Backspace"] = 8, ["Tab"] = 9, ["Enter"] = 13, ["Shift"] = 16, ["Control"] = 17, ["Alt"] = 18, ["Pause"] = 19,
["CapsLock"] = 20, ["Escape"] = 27, [" "] = 32, ["PageUp"] = 33, ["PageDown"] = 34, ["End"] = 35, ["Home"] = 36,
["ArrowLeft"] = 37, ["ArrowUp"] = 38, ["ArrowRight"] = 39, ["ArrowDown"] = 40, ["Insert"] = 45, ["Delete"] = 46,
["Meta"] = 91, ["ContextMenu"] = 93,
};
private static readonly Dictionary<string, int> Codes = new(StringComparer.Ordinal)
{
["Space"] = 32, ["Semicolon"] = 186, ["Equal"] = 187, ["Comma"] = 188, ["Minus"] = 189, ["Period"] = 190,
["Slash"] = 191, ["Backquote"] = 192, ["BracketLeft"] = 219, ["Backslash"] = 220, ["BracketRight"] = 221,
["Quote"] = 222, ["IntlBackslash"] = 226, ["NumpadEnter"] = 13,
};
public static KeyStroke ToStroke(RemoteViewKey key)
{
ArgumentNullException.ThrowIfNull(key);
var code = key.Code;
var keyCode = 0;
if (Named.TryGetValue(key.Key, out var named))
{
keyCode = named;
}
else if (code.Length == 4 && code.StartsWith("Key", StringComparison.Ordinal) && code[3] is >= 'A' and <= 'Z')
{
keyCode = code[3];
}
else if (code.Length == 6 && code.StartsWith("Digit", StringComparison.Ordinal) && code[5] is >= '0' and <= '9')
{
keyCode = code[5];
}
else if (code.Length == 7 && code.StartsWith("Numpad", StringComparison.Ordinal) && code[6] is >= '0' and <= '9')
{
keyCode = 96 + (code[6] - '0');
}
else if (code.Length is 2 or 3 && code[0] == 'F' && int.TryParse(code.AsSpan(1), out var f) && f is >= 1 and <= 12)
{
keyCode = 111 + f;
}
else if (Codes.TryGetValue(code, out var byCode))
{
keyCode = byCode;
}
else if (key.Key.Length == 1 && char.ToUpperInvariant(key.Key[0]) is var c && c is >= 'A' and <= 'Z' or >= '0' and <= '9')
{
keyCode = c;
}
// Enter must carry its text, or forms are not submitted.
var text = key.Text ?? (key.Key == "Enter" ? "\r" : null);
return new KeyStroke(key.Key, code, keyCode, (KeyModifiers)(key.Modifiers & 15), text);
}
}
+240
View File
@@ -0,0 +1,240 @@
using System.Globalization;
using Febe.Browser.Hosting;
using Febe.Core.Abstractions;
namespace Febe.Server;
/// <summary>
/// Xvfb and Chromium of the Docker edition (spec §5, §6.1, §11): started by Febe.Server itself, never by a shell
/// script. A start that fails (Chromium missing, sandbox refused, port taken) is retried with a growing wait; once
/// running, the supervisors of <see cref="XvfbProcess"/> and <see cref="ChromiumProcessHost"/> restart what crashes.
/// </summary>
internal sealed class BrowserSupervisor : IAsyncDisposable
{
private static readonly TimeSpan[] Retry = [TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(30), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(5)];
private readonly ServerOptions _options;
private readonly IClock _clock;
private readonly ServerLog _log;
private readonly TaskCompletionSource _ready = new(TaskCreationOptions.RunContinuationsAsynchronously);
private XvfbProcess? _xvfb;
private volatile bool _started;
private volatile string? _lastError;
public BrowserSupervisor(ServerOptions options, string profileDirectory, string homeDirectory, IClock clock, ServerLog log)
{
_options = options ?? throw new ArgumentNullException(nameof(options));
ArgumentNullException.ThrowIfNull(clock);
_log = log ?? throw new ArgumentNullException(nameof(log));
// Processes start, time out and restart in wall-clock time, whatever clock the engine runs on.
_clock = new SystemClock(clock.LocalZone);
ProfileDirectory = Path.GetFullPath(profileDirectory);
HomeDirectory = Path.GetFullPath(homeDirectory);
Host = new ChromiumProcessHost(options.LaunchOptions(HomeDirectory), _clock, log.ForBrowser());
BrowserOptions = new BrowserOptions(
ProfileDirectory,
options.WindowWidth,
options.WindowHeight,
options.DebugPort,
options.ChromiumPath,
UsesXvfb ? options.Display : null);
}
/// <summary>The browser: stable for the whole life of the server (a «Scollega» restarts it in place).</summary>
public ChromiumProcessHost Host { get; }
public BrowserOptions BrowserOptions { get; }
/// <summary>Dati/browser: holds the Instagram session.</summary>
public string ProfileDirectory { get; }
/// <summary>HOME of the browser process (certificate database, font cache).</summary>
public string HomeDirectory { get; }
/// <summary>Linux needs the virtual display; elsewhere (development on Windows) the browser opens a normal window.</summary>
public static bool UsesXvfb => OperatingSystem.IsLinux();
/// <summary>True when the browser runs and a page connection is attached.</summary>
public bool IsAvailable => _started && Host.IsAttached;
/// <summary>Completes when the browser started the first time.</summary>
public Task Ready => _ready.Task;
/// <summary>Why the last start failed, in Italian (for the log and the connection status); null when running.</summary>
public string? LastError => _lastError;
public bool UserIsDriving => Host.UserIsDriving;
/// <summary>Starts Xvfb and Chromium, retrying until it works or <paramref name="ct"/> is cancelled.</summary>
public async Task RunAsync(CancellationToken ct)
{
for (var attempt = 0; !ct.IsCancellationRequested; attempt++)
{
try
{
await StartOnceAsync(ct).ConfigureAwait(false);
_started = true;
_lastError = null;
_ready.TrySetResult();
_log.Info("browser", $"Browser pronto: finestra {_options.WindowWidth.ToString(CultureInfo.InvariantCulture)}×{_options.WindowHeight.ToString(CultureInfo.InvariantCulture)}, porta di debug {_options.DebugPort.ToString(CultureInfo.InvariantCulture)} solo su 127.0.0.1{(_options.NoSandbox ? ", senza sandbox (FEBE_SENZA_SANDBOX)" : string.Empty)}.");
return;
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
return;
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
_lastError = Explain(ex);
var wait = Retry[Math.Min(attempt, Retry.Length - 1)];
_log.Error("browser", $"Il browser non parte: {_lastError} Nuovo tentativo fra {wait.TotalSeconds.ToString("0", CultureInfo.InvariantCulture)} s.");
// A failed start leaves nothing running in the host (it can be started again); Xvfb, if it started, stays.
try
{
await _clock.Delay(wait, ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
return;
}
}
}
}
/// <summary>
/// «Scollega» (spec §4.1): stops Chromium (SIGINT, so it closes cleanly), deletes the profile folder with the
/// Instagram session, and starts the browser again with an empty profile.
/// </summary>
public async Task RestartWithEmptyProfileAsync(CancellationToken ct)
{
if (!_started)
{
DeleteProfile();
return;
}
await Host.RestartAsync(DeleteProfile, ct).ConfigureAwait(false);
_log.Info("browser", "Profilo del browser cancellato; il browser è ripartito vuoto.");
}
public async ValueTask DisposeAsync()
{
await StopProcessesAsync().ConfigureAwait(false);
}
private async Task StartOnceAsync(CancellationToken ct)
{
Directory.CreateDirectory(HomeDirectory);
if (UsesXvfb && _xvfb is null)
{
RemoveStaleDisplayLock(_options.Display);
var xvfb = new XvfbProcess(_options.Display, _options.WindowWidth, _options.WindowHeight, clock: _clock, log: _log.ForBrowser());
await xvfb.StartAsync(ct).ConfigureAwait(false);
_xvfb = xvfb;
}
RemoveStaleProfileLocks(ProfileDirectory);
await Host.StartAsync(BrowserOptions, ct).ConfigureAwait(false);
}
private async Task StopProcessesAsync()
{
try
{
await Host.StopAsync().ConfigureAwait(false);
}
catch (Exception ex) when (ex is InvalidOperationException or IOException)
{
}
if (_xvfb is { } xvfb)
{
_xvfb = null;
await xvfb.DisposeAsync().ConfigureAwait(false);
}
}
private void DeleteProfile()
{
if (Directory.Exists(ProfileDirectory))
{
Directory.Delete(ProfileDirectory, recursive: true);
}
}
/// <summary>
/// Chromium's «profile in use on another computer» lock: after the container is recreated the host name changes and
/// Chromium would refuse the profile with a dialog nobody sees. Only Febe starts this browser, and it is not running
/// now, so the lock files are stale by definition.
/// </summary>
internal static void RemoveStaleProfileLocks(string profileDirectory)
{
foreach (var name in new[] { "SingletonLock", "SingletonSocket", "SingletonCookie" })
{
var path = Path.Combine(profileDirectory, name);
try
{
if (File.Exists(path) || new FileInfo(path).LinkTarget is not null)
{
File.Delete(path);
}
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
}
}
}
/// <summary>
/// A display lock left by an Xvfb of an earlier run of the same container (restart after a crash): its process
/// number may now belong to another process, so a lock whose owner is not an Xvfb is removed.
/// </summary>
internal static void RemoveStaleDisplayLock(string display)
{
if (!OperatingSystem.IsLinux() || !int.TryParse(display.AsSpan(1), NumberStyles.None, CultureInfo.InvariantCulture, out var number))
{
return;
}
var id = number.ToString(CultureInfo.InvariantCulture);
var lockFile = $"/tmp/.X{id}-lock";
try
{
if (!File.Exists(lockFile))
{
return;
}
var owner = int.TryParse(File.ReadAllText(lockFile).Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out var pid) ? pid : 0;
var comm = owner > 0 && File.Exists($"/proc/{owner.ToString(CultureInfo.InvariantCulture)}/comm")
? File.ReadAllText($"/proc/{owner.ToString(CultureInfo.InvariantCulture)}/comm").Trim()
: string.Empty;
if (comm.Equals("Xvfb", StringComparison.Ordinal))
{
return;
}
File.Delete(lockFile);
var socket = $"/tmp/.X11-unix/X{id}";
if (File.Exists(socket))
{
File.Delete(socket);
}
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
}
}
private static string Explain(Exception ex) => ex switch
{
FileNotFoundException => ex.Message,
PlatformNotSupportedException => ex.Message,
TimeoutException => ex.Message,
InvalidOperationException when ex.Message.Contains("sandbox", StringComparison.OrdinalIgnoreCase) =>
ex.Message + " Se il registro parla della sandbox, vedi docs/docker.md: profilo seccomp oppure FEBE_SENZA_SANDBOX=1.",
_ => $"{ex.GetType().Name}: {ex.Message}",
};
}
+27
View File
@@ -0,0 +1,27 @@
using Febe.Core.Engine;
namespace Febe.Server;
/// <summary>
/// The recipe runner of the engine before the browser exists: the engine and its monitor are built at start-up (the
/// interface shows them at once), the collection pipeline only when Chromium is up. The engine loop is started after
/// <see cref="Target"/> is set, so a recipe never runs without it.
/// </summary>
internal sealed class DeferredRecipeRunner : IRecipeRunner
{
private volatile IRecipeRunner? _target;
/// <summary>The real runner (the collection pipeline's), once the browser is up.</summary>
public IRecipeRunner? Target
{
get => _target;
set => _target = value;
}
public Task<RecipeOutcome> RunAsync(RecipeRequest request, ISessionContext session, CancellationToken ct) =>
_target is { } target
? target.RunAsync(request, session, ct)
: Task.FromResult(new RecipeOutcome(RecipeStatus.Cancelled, 0, 0, "Il browser non è ancora pronto."));
public Task RestAsync(CancellationToken ct) => _target?.RestAsync(ct) ?? Task.CompletedTask;
}
+605
View File
@@ -0,0 +1,605 @@
using System.Globalization;
using Febe.Browser.Recipes;
using Febe.Core.Abstractions;
using Febe.Core.Collection.Downloads;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Import;
using Febe.Core.Library;
using Febe.Core.Storage;
using Febe.Data;
using Febe.Web;
using Febe.Web.Connection;
using Febe.Web.Engine;
using Febe.Web.Library;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace Febe.Server;
/// <summary>Things tests (and only tests) replace in the composition.</summary>
internal sealed record ServerHooks
{
public IClock? Clock { get; init; }
public IRandomSource? Random { get; init; }
/// <summary>The Data folder check (tests inject a mount table with a network share).</summary>
public DataFolderCheck? DataFolderCheck { get; init; }
public TextWriter? Console { get; init; }
/// <summary>How long the web host waits for open requests (events, remote view) when stopping.</summary>
public TimeSpan ShutdownTimeout { get; init; } = TimeSpan.FromSeconds(3);
}
/// <summary>
/// The real composition of the Docker edition (spec §5, §11, milestone M5). Start-up checks first: with a problem
/// (password missing, Data folder not writable or on a network share) neither the engine nor the browser start, and
/// the interface shows only the page that explains it. Otherwise: database, library, thumbnails, perceptual hashes,
/// import, daily backup, Xvfb and Chromium, the collection pipeline, the download queue and the engine, behind the
/// password-protected interface. Disposing stops everything in order (engine, downloads, browser with SIGINT, Xvfb).
/// </summary>
internal sealed class FebeServer : IAsyncDisposable
{
private readonly ServerOptions _options;
private readonly ServerLog _log;
private readonly CancellationTokenSource _lifetime = new();
private readonly List<Task> _background = [];
private readonly List<IDisposable> _disposables = [];
private readonly List<Action> _unsubscribe = [];
private string? _temporaryFolder;
private int _disposed;
private FebeServer(ServerOptions options, ServerLog log, IClock clock, IReadOnlyList<ConfigurationProblem> problems)
{
_options = options;
_log = log;
Clock = clock;
Problems = problems;
}
public IClock Clock { get; }
public IReadOnlyList<ConfigurationProblem> Problems { get; }
public WebApplication Web { get; private set; } = null!;
/// <summary>Where the interface answers (with 127.0.0.1 in place of «any address»).</summary>
public Uri Address { get; private set; } = null!;
public FebeDatabase Database { get; private set; } = null!;
public DataFolderLayout? Data { get; private set; }
public LibraryLayout? Library { get; private set; }
public BrowserSupervisor? Browser { get; private set; }
public ServerConnectionService? Connection { get; private set; }
public BrowserRemoteViewHost? RemoteView { get; private set; }
public EngineHost? Engine { get; private set; }
public CollectionPipeline? Pipeline { get; private set; }
public ImportService? Import { get; private set; }
public PerceptualHashIndex? HashIndex { get; private set; }
/// <summary>Completes when browser, pipeline and engine are running (never, with a configuration problem).</summary>
public Task Running => _running.Task;
private readonly TaskCompletionSource _running = new(TaskCreationOptions.RunContinuationsAsynchronously);
public static async Task<FebeServer> StartAsync(ServerOptions options, ServerHooks? hooks = null, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(options);
hooks ??= new ServerHooks();
var clock = hooks.Clock ?? new SystemClock(options.Zone);
var problems = StartupChecks.Run(options, hooks.DataFolderCheck);
var logFolder = problems.Count == 0 ? new DataFolderLayout(options.DataFolder).Logs : null;
var log = new ServerLog(logFolder, hooks.Console ?? System.Console.Out, clock);
var server = new FebeServer(options, log, clock, problems);
try
{
foreach (var warning in options.Warnings)
{
log.Warn("avvio", warning);
}
if (problems.Count > 0)
{
await server.StartWithProblemsAsync(hooks, ct).ConfigureAwait(false);
}
else
{
await server.StartNormallyAsync(hooks, ct).ConfigureAwait(false);
}
return server;
}
catch
{
await server.DisposeAsync().ConfigureAwait(false);
throw;
}
}
/// <summary>
/// A configuration problem: only the interface, on an empty temporary database, behind the configuration gate. No
/// engine, no browser, nothing written in the Data folder.
/// </summary>
private async Task StartWithProblemsAsync(ServerHooks hooks, CancellationToken ct)
{
foreach (var problem in Problems)
{
_log.Error("avvio", $"{problem.Title}. {problem.Remedy}");
}
_log.Error("avvio", "Il motore e il browser non partono finché il problema non è risolto: l'interfaccia mostra solo la pagina che lo spiega.");
_temporaryFolder = Path.Combine(Path.GetTempPath(), "febe-problema-" + Guid.NewGuid().ToString("N")[..10]);
Database = await FebeDatabase.OpenAsync(Path.Combine(_temporaryFolder, "dati"), ct).ConfigureAwait(false);
var data = new DataFolderLayout(Path.Combine(_temporaryFolder, "dati"));
var layout = new LibraryLayout(Path.Combine(_temporaryFolder, "libreria"));
var library = new FebeLibrary(Database, data, layout, Clock);
// The same services as a normal start, on the empty temporary database, so that every endpoint can be built;
// the configuration gate answers 503 before any of them runs.
Import = new ImportService(new ImportEnvironment
{
Storage = Database,
Layout = layout,
Journal = new AccountJournal(Clock),
Clock = Clock,
Sources = ImportSourceOptions.Docker(Path.Combine(_temporaryFolder, "importa")),
DataFolder = data.Root,
});
await StartWebAsync(hooks, services =>
{
services.AddSingleton<IFebeStorage>(Database);
services.AddSingleton(library);
services.AddSingleton<IClock>(Clock);
services.AddSingleton(Import);
services.AddSingleton(new DailyBackup(Database, Clock, data.Backups));
services.AddSingleton<IConfigurationProblems>(new StartupProblems(Problems));
services.AddSingleton<IConnectionService>(new UnavailableConnectionService(Problems));
}).ConfigureAwait(false);
}
private async Task StartNormallyAsync(ServerHooks hooks, CancellationToken ct)
{
var o = _options;
var random = hooks.Random ?? new SystemRandom();
var data = new DataFolderLayout(o.DataFolder);
Data = data;
_log.Info("avvio", $"Febe {typeof(FebeServer).Assembly.GetName().Version?.ToString(3)}: dati in {data.Root}, libreria in {Path.GetFullPath(o.LibraryFolder)}, importazioni da {Path.GetFullPath(o.ImportFolder)}, fuso {o.ZoneId}, lingua {o.Language}.");
if (o.TestSite is not null)
{
_log.Warn("avvio", $"Modalità di sviluppo: il browser lavora sul sito di prova {o.TestSite.Authority}, non su Instagram.");
}
// Database and library.
Database = await FebeDatabase.OpenAsync(data.Root, ct).ConfigureAwait(false);
var settings = await LibrarySettings.LoadAsync(Database.Settings, o.LibraryFolder, ct).ConfigureAwait(false);
var layout = new LibraryLayout(o.LibraryFolder);
Library = layout;
TryCreateFolder(layout.Root, "libreria");
var thumbnails = new ThumbnailStore(data.Thumbnails);
var hashes = new PerceptualHashIndex();
hashes.Load(await Database.Media.LoadPerceptualHashesAsync(ct).ConfigureAwait(false));
HashIndex = hashes;
var journal = new AccountJournal(Clock);
var ingest = new LibraryIngest(Database, layout, settings.Naming, journal, Clock, thumbnails, hashes, settings.SetFileTimeToPublication);
var library = new FebeLibrary(Database, data, layout, Clock, hashes);
var staging = Path.Combine(data.Root, "temporanei");
// Import (spec §9): sources under /importa, read-only; what was running when Febe stopped becomes «interrotto».
Import = new ImportService(new ImportEnvironment
{
Storage = Database,
Layout = layout,
Naming = settings.Naming,
Journal = journal,
Clock = Clock,
Thumbnails = thumbnails,
HashIndex = hashes,
Frames = VideoFrameExtractor.TryCreate(),
VideoProbe = FfprobeVideoMetadataProbe.TryCreate(),
SetFileTimeToPublication = settings.SetFileTimeToPublication,
Sources = ImportSourceOptions.Docker(Path.GetFullPath(o.ImportFolder)),
DataFolder = data.Root,
});
var recovered = await Import.RecoverAsync(ct).ConfigureAwait(false);
if (recovered > 0)
{
_log.Info("importazione", $"{recovered.ToString(CultureInfo.InvariantCulture)} importazioni interrotte dall'arresto precedente: si riprendono dalla pagina Importa.");
}
// Browser, connection, remote view, engine. The engine loop starts only once the browser is up.
var tracker = new BrowserUseTracker();
var browser = new BrowserSupervisor(o, data.BrowserProfile, Path.Combine(data.Root, "home"), Clock, _log);
Browser = browser;
var connection = new ServerConnectionService(browser, Database, tracker, Clock, _log, o.LoginUrl, o.Site.SessionCookie);
Connection = connection;
RemoteView = new BrowserRemoteViewHost(browser, tracker, Clock, _log);
var engineOptions = o.FirstSessionDelay is { } delay
? EngineOptions.Default with { StartupDelayMin = delay, StartupDelayMax = delay }
: EngineOptions.Default;
var services = await EngineServices.CreateAsync(
Database,
Clock,
random,
engineOptions,
userIsDriving: () => browser.UserIsDriving,
isConnected: () => connection.IsConnected == true,
ct: ct).ConfigureAwait(false);
var runner = new DeferredRecipeRunner();
var engine = new EngineHost(services, runner);
Engine = engine;
connection.AttachEngine(engine);
browser.Host.UserDriving.Changed += (_, _) => engine.NotifyUserDrivingChanged();
await StartWebAsync(hooks, s =>
{
s.AddSingleton<IFebeStorage>(Database);
s.AddSingleton(library);
s.AddSingleton<IClock>(Clock);
s.AddSingleton(tracker);
s.AddSingleton(engine.Monitor);
s.AddSingleton<IEngineControl>(new EngineHostControl(engine));
s.AddSingleton<IConnectionService>(connection);
s.AddSingleton<IRemoteViewHost>(RemoteView);
s.AddSingleton<IConfigurationProblems>(new StartupProblems([]));
s.AddSingleton(Import);
s.AddSingleton(new DailyBackup(Database, Clock, data.Backups));
}).ConfigureAwait(false);
// Housekeeping in the background: temporary files of an interrupted run, the daily copy of the database.
var lifetime = _lifetime.Token;
_background.Add(Task.Run(() => CleanTemporaryFilesAsync(staging, layout, lifetime), CancellationToken.None));
_background.Add(Task.Run(() => BackupLoopAsync(new DailyBackup(Database, Clock, data.Backups), lifetime), CancellationToken.None));
_background.Add(Task.Run(() => BringUpBrowserAsync(ingest, staging, services, engine, runner, lifetime), CancellationToken.None));
}
private async Task StartWebAsync(ServerHooks hooks, Action<IServiceCollection> register)
{
var web = FebeWebHost.Build(
_options.WebOptions(),
new FebeListen(_options.ListenAddress, _options.Port),
services =>
{
register(services);
services.Configure<HostOptions>(h => h.ShutdownTimeout = hooks.ShutdownTimeout);
},
logging => logging.AddProvider(_log.ForAspNet()));
try
{
await web.StartAsync().ConfigureAwait(false);
}
catch
{
await web.DisposeAsync().ConfigureAwait(false);
throw;
}
Web = web;
Address = FebeWebHost.BoundAddress(web);
_log.Info("avvio", $"Interfaccia sulla porta {Address.Port.ToString(CultureInfo.InvariantCulture)}{(Problems.Count > 0 ? " (solo la pagina del problema)" : string.Empty)}.");
}
/// <summary>Xvfb and Chromium, then the pipeline, the downloads, the connection check and the engine.</summary>
private async Task BringUpBrowserAsync(LibraryIngest ingest, string staging, EngineServices services, EngineHost engine, DeferredRecipeRunner runner, CancellationToken ct)
{
var browser = Browser!;
await browser.RunAsync(ct).ConfigureAwait(false);
if (ct.IsCancellationRequested)
{
return;
}
try
{
var o = _options;
Pipeline = await CollectionPipeline.StartAsync(
new CollectionPipelineOptions
{
Cdp = browser.Host.Cdp,
Site = o.Site,
Storage = Database,
Ingest = ingest,
Governor = services.Governor,
Budget = services.Governor,
DataBudget = services.Governor,
Breaker = services.Breaker,
Clock = Clock,
Random = services.Random,
StagingFolder = staging,
ConfigFolder = Data!.Root,
Pace = services.Settings.Pace,
UserIsDriving = () => browser.UserIsDriving,
Log = _log.ForBrowser(),
},
ct).ConfigureAwait(false);
runner.Target = Pipeline.Runner;
var changes = Web.Services.GetRequiredService<LibraryChanges>();
_disposables.Add(changes.Attach(Pipeline.Downloads, Clock));
_background.Add(Task.Run(() => DownloadLoopAsync(Pipeline.Downloads, ct), CancellationToken.None));
// Every finished recipe may have queued files: the queue looks at once instead of at its next idle poll.
var downloads = Pipeline.Downloads;
void WakeDownloads(object? sender, EngineNotification n)
{
if (n.Event?.Code.StartsWith("ricetta.", StringComparison.Ordinal) == true)
{
downloads.Wake();
}
}
services.Events.Notified += WakeDownloads;
_unsubscribe.Add(() => services.Events.Notified -= WakeDownloads);
await Connection!.RefreshAsync(ct).ConfigureAwait(false);
if (o.TestSiteAutoLogin && Connection.IsConnected != true)
{
await TestSiteLoginAsync(ct).ConfigureAwait(false);
}
_background.Add(Task.Run(() => Connection.RunAsync(ct), CancellationToken.None));
await engine.StartAsync(ct).ConfigureAwait(false);
_log.Info("motore", Connection.IsConnected == true
? "Motore avviato: il browser è collegato."
: "Motore avviato: aspetta il collegamento (pagina Collegamento, «Accedi a Instagram»).");
_running.TrySetResult();
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
_log.Error("avvio", "La raccolta non è partita.", ex);
_running.TrySetException(ex);
}
}
/// <summary>
/// Development with the test site only (<c>--accesso-di-prova</c>): what Alberto does by hand on Instagram — open
/// the site once, so that its session cookie exists — then back to the rest page.
/// </summary>
private async Task TestSiteLoginAsync(CancellationToken ct)
{
var host = Browser!.Host;
await Febe.Browser.Cdp.CdpPageExtensions.NavigateAsync(host.Cdp, _options.LoginUrl, ct).ConfigureAwait(false);
await Febe.Browser.Cdp.CdpPageExtensions.WaitForLoadAsync(host.Cdp, Clock, TimeSpan.FromSeconds(15), ct).ConfigureAwait(false);
await host.RestAsync(ct).ConfigureAwait(false);
await Connection!.RefreshAsync(ct).ConfigureAwait(false);
_log.Info("collegamento", "Sito di prova: accesso automatico fatto.");
}
/// <summary>
/// The download queue runs all the time (spec §6.5): it talks only to the CDN, so it goes on during a stop of the
/// breaker. An error (browser restarting) ends a pass, never the loop.
/// </summary>
private async Task DownloadLoopAsync(DownloadQueue queue, CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
try
{
await queue.RunAsync(ct).ConfigureAwait(false);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
return;
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
_log.Warn("scaricamenti", "Scaricamenti interrotti: riprendo fra 30 secondi.", ex);
try
{
await Clock.Delay(TimeSpan.FromSeconds(30), ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
return;
}
}
}
}
/// <summary>The daily copy of the database (spec §8.5): at start-up if today's is missing, then once a day.</summary>
private async Task BackupLoopAsync(DailyBackup backup, CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
try
{
var result = await backup.RunAsync(ct).ConfigureAwait(false);
if (result.Created is { } created)
{
_log.Info("copie", $"Copia del database del giorno fatta ({Febe.Core.Engine.ItalianText.Bytes(created.Bytes)}); copie tenute: {backup.List().Count.ToString(CultureInfo.InvariantCulture)}.");
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
return;
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
_log.Error("copie", "Copia del database non riuscita: riprovo fra un'ora.", ex);
try
{
await Clock.Delay(TimeSpan.FromHours(1), ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
return;
}
continue;
}
try
{
await Clock.Delay(UntilNextBackup(Clock.Now, Clock.LocalZone), ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
return;
}
}
}
/// <summary>The next copy: a few minutes after local midnight (03:20, outside the active window of every profile).</summary>
internal static TimeSpan UntilNextBackup(DateTimeOffset now, TimeZoneInfo zone)
{
var tomorrow = LocalCalendar.Today(now, zone).AddDays(1);
var target = LocalCalendar.StartOfDay(tomorrow, zone) + TimeSpan.FromMinutes(200);
var wait = target - now;
return wait < TimeSpan.FromMinutes(1) ? TimeSpan.FromMinutes(1) : wait;
}
/// <summary>Temporary files left by an interrupted run (only <c>.febe-*.part</c>: never a library file, rule 12).</summary>
private async Task CleanTemporaryFilesAsync(string staging, LibraryLayout layout, CancellationToken ct)
{
try
{
var removed = SafeFileWriter.CleanupTemporaryFiles(staging, recursive: false);
removed += SafeFileWriter.CleanupTemporaryFiles(layout.Root);
var root = Path.TrimEndingDirectorySeparator(layout.Root) + Path.DirectorySeparatorChar;
foreach (var account in await Database.Accounts.ListAsync(ct).ConfigureAwait(false))
{
var folder = layout.AccountFolder(account);
if (!(folder + Path.DirectorySeparatorChar).StartsWith(root, StringComparison.Ordinal))
{
removed += SafeFileWriter.CleanupTemporaryFiles(folder);
}
}
if (removed > 0)
{
_log.Info("libreria", $"Tolti {removed.ToString(CultureInfo.InvariantCulture)} file temporanei lasciati da un arresto precedente.");
}
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or OperationCanceledException)
{
_log.Warn("libreria", "Pulizia dei file temporanei non completata.", ex);
}
}
private void TryCreateFolder(string folder, string what)
{
try
{
Directory.CreateDirectory(folder);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
_log.Error("avvio", $"La cartella della {what} ({folder}) non si può creare: i file scaricati non avranno dove andare.", ex);
}
}
/// <summary>Stops everything in order: remote view, interface, engine, downloads, import, pipeline, browser, database.</summary>
public async ValueTask DisposeAsync()
{
if (Interlocked.Exchange(ref _disposed, 1) == 1)
{
return;
}
_log.Info("arresto", "Arresto in corso.");
if (RemoteView is { } view)
{
await Quietly(view.ShutdownAsync).ConfigureAwait(false);
}
if (Web is { } web)
{
await Quietly(() => web.StopAsync()).ConfigureAwait(false);
}
if (Engine is { } engine)
{
await Quietly(() => engine.DisposeAsync().AsTask()).ConfigureAwait(false);
}
await _lifetime.CancelAsync().ConfigureAwait(false);
foreach (var task in _background.ToArray())
{
await Quietly(() => task).ConfigureAwait(false);
}
foreach (var disposable in _disposables)
{
disposable.Dispose();
}
foreach (var unsubscribe in _unsubscribe)
{
unsubscribe();
}
if (Import is { } import)
{
await Quietly(() => import.DisposeAsync().AsTask()).ConfigureAwait(false);
}
if (Pipeline is { } pipeline)
{
await Quietly(() => pipeline.DisposeAsync().AsTask()).ConfigureAwait(false);
}
if (Connection is { } connection)
{
await connection.DisposeAsync().ConfigureAwait(false);
}
if (Browser is { } browser)
{
// Chromium with SIGINT, so that the session is written to the profile (decisions, S3); then Xvfb.
await Quietly(() => browser.DisposeAsync().AsTask()).ConfigureAwait(false);
}
if (Web is { } app)
{
await Quietly(() => app.DisposeAsync().AsTask()).ConfigureAwait(false);
}
if (Database is { } database)
{
await Quietly(() => database.DisposeAsync().AsTask()).ConfigureAwait(false);
}
if (_temporaryFolder is { } temporary)
{
try
{
Directory.Delete(temporary, recursive: true);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
}
}
_log.Info("arresto", "Febe è fermo.");
_log.Dispose();
_lifetime.Dispose();
}
private async Task Quietly(Func<Task> step)
{
try
{
await step().ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
if (ex is not OperationCanceledException)
{
_log.Warn("arresto", "Un passo dell'arresto non è riuscito.", ex);
}
}
}
}
+14 -4
View File
@@ -1,4 +1,4 @@
// Composition root for Linux and Docker. Filled in by milestones M3–M5.
// Composition root for Linux and Docker (spec §5, §11).
using Febe.Server;
Console.OutputEncoding = System.Text.Encoding.UTF8;
@@ -13,6 +13,16 @@ if (DemoCommand.Matches(args))
return await DemoCommand.RunAsync(args, Console.Out, Console.Error);
}
Console.WriteLine("Febe");
Console.WriteLine("Comandi: --demo (interfaccia con dati dimostrativi), --simula 30g --profilo prudente (simulazione del motore).");
return 0;
if (HealthCheckCommand.Matches(args))
{
return await HealthCheckCommand.RunAsync(Environment.GetEnvironmentVariable, Console.Out);
}
if (args.Any(a => a is "--aiuto" or "--help" or "-h"))
{
Console.WriteLine(ServerCommand.Usage);
return 0;
}
// Default: the real server (Docker edition).
return await ServerCommand.RunAsync(args, Console.Out, Console.Error);
+114
View File
@@ -0,0 +1,114 @@
using System.Runtime.InteropServices;
namespace Febe.Server;
/// <summary>
/// The real server (default when neither <c>--demo</c> nor <c>--simula</c> is given): the Docker edition with the
/// browser, the engine and the password-protected interface. Stops cleanly on SIGTERM (<c>docker stop</c>) and Ctrl+C.
/// Exit code 0 after a clean stop, 1 when the interface cannot start, 2 for a wrong command line.
/// </summary>
internal static class ServerCommand
{
public const string Usage =
"Uso: febe [--dati /dati] [--libreria /libreria] [--importa /importa] [--porta 8480] [--ascolta 0.0.0.0]\n"
+ " [--porta-debug 9222] [--display :99] [--chromium percorso] [--senza-sandbox]\n"
+ " [--sito-di-prova http://127.0.0.1:8481 [--cdn-di-prova http://127.0.0.2:8482] [--accesso-di-prova]] [--prima-sessione secondi]\n"
+ "Variabili: FEBE_PASSWORD (obbligatoria), FEBE_PORTA, TZ, LANG, FEBE_HOST, FEBE_PROXY_FIDATO, FEBE_SENZA_SANDBOX, FEBE_CHROMIUM.\n"
+ "Altri comandi: --demo, --simula 30g --profilo prudente, --controllo-salute.";
public static async Task<int> RunAsync(string[] args, TextWriter output, TextWriter error)
{
if (!ServerOptions.TryParse(args, Environment.GetEnvironmentVariable, out var options, out var problem))
{
await error.WriteLineAsync(problem).ConfigureAwait(false);
await error.WriteLineAsync(Usage).ConfigureAwait(false);
return 2;
}
using var stop = new CancellationTokenSource();
ConsoleCancelEventHandler onCancel = (_, e) =>
{
e.Cancel = true;
stop.Cancel();
};
Console.CancelKeyPress += onCancel;
using var terminate = PosixSignalRegistration.Create(PosixSignal.SIGTERM, context =>
{
context.Cancel = true;
stop.Cancel();
});
try
{
FebeServer server;
try
{
server = await FebeServer.StartAsync(options, new ServerHooks { Console = output }, stop.Token).ConfigureAwait(false);
}
catch (IOException ex) when (ex.Message.Contains("address", StringComparison.OrdinalIgnoreCase) || ex.InnerException is System.Net.Sockets.SocketException)
{
await error.WriteLineAsync($"La porta {options.Port} è già occupata: cambia FEBE_PORTA o ferma l'altro programma.").ConfigureAwait(false);
return 1;
}
catch (OperationCanceledException) when (stop.IsCancellationRequested)
{
return 0;
}
await using (server.ConfigureAwait(false))
{
try
{
await Task.Delay(Timeout.Infinite, stop.Token).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
}
}
return 0;
}
finally
{
Console.CancelKeyPress -= onCancel;
}
}
}
/// <summary>
/// <c>--controllo-salute</c>: the Docker HEALTHCHECK. Asks <c>/salute</c> on 127.0.0.1 and exits 0 for «ok», 1 otherwise.
/// The image has no curl: the program checks itself.
/// </summary>
internal static class HealthCheckCommand
{
public const string Flag = "--controllo-salute";
public static bool Matches(string[] args) => args.Any(a => string.Equals(a, Flag, StringComparison.OrdinalIgnoreCase));
public static async Task<int> RunAsync(Func<string, string?> environment, TextWriter output)
{
var port = int.TryParse(environment("FEBE_PORTA"), System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var p) && p is >= 1 and <= 65535
? p
: Febe.Web.FebeListen.DefaultPort;
return await CheckAsync(new Uri($"http://127.0.0.1:{port}/salute"), output).ConfigureAwait(false);
}
public static async Task<int> CheckAsync(Uri address, TextWriter output)
{
using var client = new HttpClient(new SocketsHttpHandler { UseProxy = false, UseCookies = false, AllowAutoRedirect = false })
{
Timeout = TimeSpan.FromSeconds(8),
};
try
{
using var response = await client.GetAsync(address).ConfigureAwait(false);
var body = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
await output.WriteLineAsync(body).ConfigureAwait(false);
return response.IsSuccessStatusCode ? 0 : 1;
}
catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException)
{
await output.WriteLineAsync("Febe non risponde.").ConfigureAwait(false);
return 1;
}
}
}
+412
View File
@@ -0,0 +1,412 @@
using System.Globalization;
using Febe.Browser.Cdp;
using Febe.Browser.Hosting;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Storage;
using Febe.Web.Api;
using Febe.Web.Connection;
using Febe.Web.Engine;
namespace Febe.Server;
/// <summary>
/// The link to Instagram in the Docker edition (spec §4.1, PROTOCOLLO.md) over the real browser. «Collegato» means
/// that the session cookie exists in the browser profile: only its existence is checked (<c>Network.getCookies</c>,
/// names only), never its value. Opening the login page is Alberto's action, not the engine's (rule 7, last
/// sentence): it happens only while he holds the «driving» lease and the engine is still.
/// </summary>
internal sealed class ServerConnectionService : IConnectionService, IAsyncDisposable
{
/// <summary>Setting written at the first connection ever (Unix ms): the gradual start begins only once.</summary>
public const string FirstConnectionKey = "collegamento.primo";
/// <summary>A cookie check younger than this is reused by the status (the sidebar asks often).</summary>
public static readonly TimeSpan CookieCacheLifetime = TimeSpan.FromSeconds(3);
/// <summary>How often the cookie is looked at in the background (outside sessions it is the only way to notice).</summary>
public static readonly TimeSpan BackgroundCheck = TimeSpan.FromSeconds(30);
private readonly BrowserSupervisor _browser;
private readonly IFebeStorage _storage;
private readonly BrowserUseTracker _tracker;
private readonly IClock _clock;
private readonly ServerLog _log;
private readonly string _loginUrl;
private readonly SessionCookieOptions _cookie;
private readonly SemaphoreSlim _commands = new(1, 1);
private readonly Lock _gate = new();
private EngineHost? _engine;
private IDisposable? _lease;
private bool? _connected;
private DateTimeOffset _checkedAt = DateTimeOffset.MinValue;
public ServerConnectionService(BrowserSupervisor browser, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, ServerLog log, string loginUrl, SessionCookieOptions cookie)
{
_browser = browser ?? throw new ArgumentNullException(nameof(browser));
_storage = storage ?? throw new ArgumentNullException(nameof(storage));
_tracker = tracker ?? throw new ArgumentNullException(nameof(tracker));
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
_log = log ?? throw new ArgumentNullException(nameof(log));
_loginUrl = loginUrl ?? throw new ArgumentNullException(nameof(loginUrl));
_cookie = cookie ?? throw new ArgumentNullException(nameof(cookie));
}
/// <summary>
/// Whether the browser holds the session, from the last check (null before the first one). The engine reads it
/// on every turn (<see cref="EngineRuntime.IsConnected"/>): it never waits for the browser.
/// </summary>
public bool? IsConnected
{
get
{
lock (_gate)
{
return _connected;
}
}
}
/// <summary>
/// Hook for the readers (hypothesis H10): when the data of the page tell which account is connected, the composition
/// marks it as «Tu» (<see cref="Account.IsMine"/>); the status shows that account. Raised after every change of the
/// connection, so that whoever learns the account can look again.
/// </summary>
public event EventHandler<bool>? ConnectionChanged;
/// <summary>The engine, once it exists (it is built after the browser).</summary>
public void AttachEngine(EngineHost engine) => _engine = engine ?? throw new ArgumentNullException(nameof(engine));
public async Task<ConnectionStatus> GetStatusAsync(CancellationToken ct)
{
var driving = _browser.UserIsDriving;
if (!_browser.IsAvailable)
{
return new ConnectionStatus(ConnectionState.BrowserUnavailable, null, null, driving, null);
}
var breaker = _engine?.Services.Breaker.State.Status;
var state = breaker is BreakerStatus.Challenge or BreakerStatus.Disconnected
? ConnectionState.VerificationRequired
: await CheckAsync(force: false, ct).ConfigureAwait(false) == true ? ConnectionState.Connected : ConnectionState.NotConnected;
Account? mine = null;
if (state != ConnectionState.NotConnected)
{
mine = await _storage.Accounts.GetMineAsync(ct).ConfigureAwait(false);
}
return new ConnectionStatus(state, mine?.Username, mine?.DisplayName, driving, await CurrentUrlAsync(ct).ConfigureAwait(false));
}
public async Task BeginUserDrivingAsync(bool openLogin, CancellationToken ct)
{
EnsureBrowser();
await _commands.WaitAsync(ct).ConfigureAwait(false);
try
{
lock (_gate)
{
_lease ??= _browser.Host.UserDriving.Begin();
}
_tracker.MarkUsed(_clock.Now);
if (openLogin)
{
// The engine ends its session when the lease starts; wait for it before taking the page.
await WaitForSessionEndAsync(ct).ConfigureAwait(false);
var result = await _browser.Host.Cdp.NavigateAsync(_loginUrl, ct).ConfigureAwait(false);
_log.Info("collegamento", result.Succeeded
? "Alberto usa il browser: pagina di accesso aperta."
: "Alberto usa il browser: la pagina di accesso non si è aperta (errore di rete del browser).");
}
else
{
_log.Info("collegamento", "Alberto usa il browser.");
}
}
finally
{
_commands.Release();
}
}
public async Task<FinishResult> FinishAsync(CancellationToken ct)
{
await _commands.WaitAsync(ct).ConfigureAwait(false);
try
{
if (!_browser.IsAvailable)
{
ReleaseLease();
return new FinishResult(false, "Il browser di Febe non è in funzione in questo momento, quindi Febe non può controllare il collegamento. Riprova fra qualche minuto; se il problema resta, guarda il registro.");
}
var connected = await CheckAsync(force: true, ct).ConfigureAwait(false) == true;
_tracker.MarkUsed(_clock.Now);
var first = connected && await MarkConnectedAsync(ct).ConfigureAwait(false);
await RestQuietlyAsync().ConfigureAwait(false);
ReleaseLease();
var stopped = _engine?.Services.Breaker.State.Status is BreakerStatus.Challenge or BreakerStatus.Disconnected;
string message;
if (!connected)
{
message = "Febe non trova la sessione di Instagram nel browser: l'accesso non sembra completato. Riprova con «Accedi a Instagram» e premi «Ho finito» solo dopo aver visto la tua pagina iniziale.";
}
else if (stopped)
{
message = "Collegato. Febe è ancora fermo per la verifica o la disconnessione: premi «Riprendi» quando vuoi che ricominci.";
}
else if (first)
{
message = "Collegato a Instagram. Febe comincia fra qualche minuto, con calma: nei primi giorni i tetti sono ridotti (avvio graduale).";
}
else
{
message = "Collegato a Instagram. Febe riprende da solo alla prossima sessione.";
}
_log.Info("collegamento", connected ? "«Ho finito»: sessione presente nel browser." : "«Ho finito»: sessione assente nel browser.");
return new FinishResult(connected, message);
}
finally
{
_commands.Release();
}
}
public async Task CancelAsync(CancellationToken ct)
{
await _commands.WaitAsync(ct).ConfigureAwait(false);
try
{
if (_browser.IsAvailable)
{
await RestQuietlyAsync().ConfigureAwait(false);
}
ReleaseLease();
_log.Info("collegamento", "«Annulla»: il browser torna a riposo.");
}
finally
{
_commands.Release();
}
}
public async Task DisconnectAsync(CancellationToken ct)
{
await _commands.WaitAsync(ct).ConfigureAwait(false);
var hold = _browser.Host.UserDriving.Begin();
try
{
var engine = _engine;
if (engine is not null)
{
await engine.StopAsync().ConfigureAwait(false);
}
await _browser.RestartWithEmptyProfileAsync(ct).ConfigureAwait(false);
SetConnected(false);
if (engine is not null)
{
await engine.Services.Events.WriteAsync(
EventSeverity.Info,
"collegamento.scollegato",
"Scollegato da te: il profilo del browser con la sessione di Instagram è stato cancellato.",
ct: CancellationToken.None).ConfigureAwait(false);
await engine.StartAsync(CancellationToken.None).ConfigureAwait(false);
}
_log.Info("collegamento", "«Scollega»: motore fermo, profilo del browser cancellato, browser ripartito vuoto.");
}
finally
{
ReleaseLease();
hold.Dispose();
_commands.Release();
}
}
/// <summary>
/// Looks at the cookie now (outside the cache) and records the change. Used at start-up, by the background loop
/// and after the test site's automatic login.
/// </summary>
public async Task<bool?> RefreshAsync(CancellationToken ct)
{
if (!_browser.IsAvailable)
{
return IsConnected;
}
var connected = await CheckAsync(force: true, ct).ConfigureAwait(false);
if (connected == true)
{
await MarkConnectedAsync(ct).ConfigureAwait(false);
}
return connected;
}
/// <summary>The background check of the cookie, every <see cref="BackgroundCheck"/>, until cancelled.</summary>
public async Task RunAsync(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
try
{
await _clock.Delay(BackgroundCheck, ct).ConfigureAwait(false);
if (!_browser.UserIsDriving)
{
await RefreshAsync(ct).ConfigureAwait(false);
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
return;
}
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException or IOException)
{
// The browser is restarting: the next turn looks again.
}
}
}
public ValueTask DisposeAsync()
{
ReleaseLease();
_commands.Dispose();
return ValueTask.CompletedTask;
}
private async Task<bool?> CheckAsync(bool force, CancellationToken ct)
{
lock (_gate)
{
if (!force && _connected is not null && _clock.Now - _checkedAt < CookieCacheLifetime)
{
return _connected;
}
}
bool has;
try
{
has = await SessionCookieProbe.HasSessionCookieAsync(_browser.Host.Cdp, _cookie, ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException)
{
return IsConnected;
}
SetConnected(has);
return has;
}
private void SetConnected(bool connected)
{
bool changed;
lock (_gate)
{
changed = _connected != connected;
_connected = connected;
_checkedAt = _clock.Now;
}
if (changed)
{
_log.Info("collegamento", connected ? "Sessione presente nel browser: collegato." : "Nessuna sessione nel browser: non collegato.");
// Wakes the engine: it looks again whether it can work (it only cancels a session if Alberto is driving).
_engine?.NotifyUserDrivingChanged();
ConnectionChanged?.Invoke(this, connected);
}
}
/// <summary>The first connection ever starts the gradual start (spec §7.2). True when it was the first.</summary>
private async Task<bool> MarkConnectedAsync(CancellationToken ct)
{
if (await _storage.Settings.GetInt64Async(FirstConnectionKey, ct).ConfigureAwait(false) is not null)
{
return false;
}
var now = _clock.Now;
await _storage.Settings.SetAsync(FirstConnectionKey, now.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture), ct).ConfigureAwait(false);
if (_engine is { } engine)
{
await engine.Services.NotifyFirstConnectionAsync(ct).ConfigureAwait(false);
await engine.Services.Events.WriteAsync(
EventSeverity.Info,
"collegamento.primo",
"Primo collegamento a Instagram: comincia l'avvio graduale.",
ct: ct).ConfigureAwait(false);
}
_log.Info("collegamento", "Primo collegamento: comincia l'avvio graduale.");
return true;
}
private async Task WaitForSessionEndAsync(CancellationToken ct)
{
if (_engine is not { } engine)
{
return;
}
var deadline = _clock.Now + TimeSpan.FromSeconds(15);
while (engine.Services.Runtime.CurrentSession is not null && _clock.Now < deadline)
{
await _clock.Delay(TimeSpan.FromMilliseconds(100), ct).ConfigureAwait(false);
}
}
private async Task<string?> CurrentUrlAsync(CancellationToken ct)
{
try
{
var url = await _browser.Host.Cdp.GetMainFrameUrlAsync(ct).ConfigureAwait(false);
return BrowserRemoteViewConnection.WithoutQuery(url);
}
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException or KeyNotFoundException or InvalidOperationException)
{
return null;
}
}
private async Task RestQuietlyAsync()
{
try
{
await _browser.Host.RestAsync().ConfigureAwait(false);
}
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException)
{
// The browser is restarting: it starts on the rest page anyway.
}
}
private void ReleaseLease()
{
IDisposable? lease;
lock (_gate)
{
lease = _lease;
_lease = null;
}
lease?.Dispose();
}
private void EnsureBrowser()
{
if (!_browser.IsAvailable)
{
throw new BadRequestException(_browser.LastError is { } error
? "Il browser di Febe non è in funzione: " + error
: "Il browser di Febe si sta avviando: riprova fra qualche secondo.");
}
}
}
+261
View File
@@ -0,0 +1,261 @@
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
using Febe.Browser.Diagnostics;
using Febe.Core.Abstractions;
using Microsoft.Extensions.Logging;
namespace Febe.Server;
/// <summary>
/// The log of the server (spec §8.2, §13.2): one file per local day in <c>Dati/registro</c>
/// (<c>febe-AAAA-MM-GG.log</c>), kept fourteen days, at most 20 MB a day, and the same lines on the console
/// (<c>docker logs</c>). Only actions and outcomes: every message passes through <see cref="Scrub"/>, which removes
/// addresses (signed CDN addresses, tokens); exceptions are written as type and first line only. Passwords, cookies,
/// keys and response bodies never reach this class.
/// </summary>
internal sealed partial class ServerLog : IDisposable
{
public const int DefaultKeepDays = 14;
public const long DefaultMaxBytesPerDay = 20L * 1024 * 1024;
private const string Prefix = "febe-";
private const string Extension = ".log";
private readonly Lock _gate = new();
private readonly string? _folder;
private readonly TextWriter? _console;
private readonly IClock _clock;
private readonly int _keepDays;
private readonly long _maxBytesPerDay;
private StreamWriter? _file;
private DateOnly _day;
private long _written;
private bool _capped;
private bool _disposed;
/// <param name="folder">Dati/registro; null writes to the console only (configuration problems, tests).</param>
/// <param name="console">Console writer; null for none.</param>
/// <param name="clock">Time of the lines and of the daily file.</param>
/// <param name="keepDays">Days of files kept.</param>
/// <param name="maxBytesPerDay">Above this the day's file stops growing (the console still gets the lines).</param>
public ServerLog(string? folder, TextWriter? console, IClock clock, int keepDays = DefaultKeepDays, long maxBytesPerDay = DefaultMaxBytesPerDay)
{
_folder = folder is null ? null : Path.GetFullPath(folder);
_console = console;
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
_keepDays = Math.Max(1, keepDays);
_maxBytesPerDay = maxBytesPerDay;
}
/// <summary>Lowest level written to the console; the file gets everything from Information up.</summary>
public LogLevel ConsoleLevel { get; init; } = LogLevel.Information;
/// <summary>The log folder, when there is one.</summary>
public string? Folder => _folder;
public void Info(string source, string message) => Write(LogLevel.Information, source, message);
public void Warn(string source, string message, Exception? exception = null) => Write(LogLevel.Warning, source, message, exception);
public void Error(string source, string message, Exception? exception = null) => Write(LogLevel.Error, source, message, exception);
/// <summary>Writes one line. Never throws: a log that cannot be written must not stop Febe.</summary>
public void Write(LogLevel level, string source, string message, Exception? exception = null)
{
if (level < LogLevel.Information)
{
return;
}
var now = _clock.Now;
var local = TimeZoneInfo.ConvertTime(now, _clock.LocalZone);
var text = Scrub(message);
if (exception is not null)
{
text += $" ({exception.GetType().Name}: {Scrub(FirstLine(exception.Message))})";
}
var line = string.Create(CultureInfo.InvariantCulture, $"{local:yyyy-MM-dd HH:mm:ss.fff zzz} {Label(level)} [{source}] {text}");
lock (_gate)
{
if (_disposed)
{
return;
}
if (_console is not null && level >= ConsoleLevel)
{
try
{
_console.WriteLine(line);
}
catch (IOException)
{
}
}
WriteFileLocked(DateOnly.FromDateTime(local.DateTime), line);
}
}
/// <summary>The adapter for the browser layer (it logs only CDP command names, states and counts).</summary>
public IBrowserLog ForBrowser() => new DelegateBrowserLog((level, message, exception) => Write(
level switch
{
BrowserLogLevel.Error => LogLevel.Error,
BrowserLogLevel.Warning => LogLevel.Warning,
BrowserLogLevel.Information => LogLevel.Information,
_ => LogLevel.Debug,
},
"browser",
message,
exception));
/// <summary>The adapter for ASP.NET Core (warnings and errors only; messages scrubbed like every other line).</summary>
public ILoggerProvider ForAspNet() => new Provider(this);
public void Dispose()
{
lock (_gate)
{
_disposed = true;
_file?.Dispose();
_file = null;
}
}
/// <summary>Removes addresses (anything like <c>scheme://…</c>) and line breaks from a message.</summary>
public static string Scrub(string? message)
{
if (string.IsNullOrEmpty(message))
{
return string.Empty;
}
var clean = Addresses().Replace(message, "<indirizzo>");
return clean.Replace('\r', ' ').Replace('\n', ' ');
}
/// <summary>Log files older than <paramref name="keepDays"/> days (today included) are removed; only <c>febe-*.log</c>.</summary>
public static IReadOnlyList<string> ApplyRetention(string folder, DateOnly today, int keepDays)
{
var removed = new List<string>();
if (!Directory.Exists(folder))
{
return removed;
}
var oldestKept = today.AddDays(-(Math.Max(1, keepDays) - 1));
foreach (var file in Directory.EnumerateFiles(folder, Prefix + "*" + Extension))
{
var name = Path.GetFileNameWithoutExtension(file);
if (DateOnly.TryParseExact(name[Prefix.Length..], "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var day) && day < oldestKept)
{
try
{
File.Delete(file);
removed.Add(file);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
}
}
}
return removed;
}
public static string FileNameFor(DateOnly day) => Prefix + day.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + Extension;
private void WriteFileLocked(DateOnly day, string line)
{
if (_folder is null)
{
return;
}
try
{
if (_file is null || day != _day)
{
_file?.Dispose();
_file = null;
Directory.CreateDirectory(_folder);
ApplyRetention(_folder, day, _keepDays);
var path = Path.Combine(_folder, FileNameFor(day));
var stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Read);
_written = stream.Length;
_file = new StreamWriter(stream, new UTF8Encoding(false)) { AutoFlush = true };
_day = day;
_capped = false;
}
if (_capped)
{
return;
}
if (_written + line.Length + 1 > _maxBytesPerDay)
{
_file.WriteLine("Registro di oggi troppo lungo: le righe successive vanno solo sulla console.");
_capped = true;
return;
}
_file.WriteLine(line);
_written += Encoding.UTF8.GetByteCount(line) + 1;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// The disk is full or the folder went away: the console still has the line.
_file?.Dispose();
_file = null;
}
}
private static string Label(LogLevel level) => level switch
{
LogLevel.Critical or LogLevel.Error => "ERRORE ",
LogLevel.Warning => "AVVISO ",
_ => "INFO ",
};
private static string FirstLine(string text)
{
var line = text.Split('\n')[0].Trim();
return line.Length > 300 ? line[..300] : line;
}
[GeneratedRegex(@"\b[a-zA-Z][a-zA-Z0-9+.-]*://\S+", RegexOptions.CultureInvariant)]
private static partial Regex Addresses();
private sealed class Provider(ServerLog log) : ILoggerProvider
{
public ILogger CreateLogger(string categoryName) => new Logger(log, categoryName);
public void Dispose()
{
}
}
private sealed class Logger(ServerLog log, string category) : ILogger
{
public IDisposable? BeginScope<TState>(TState state)
where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => logLevel >= LogLevel.Warning;
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
{
if (!IsEnabled(logLevel))
{
return;
}
var source = category.StartsWith("Febe.", StringComparison.Ordinal) ? "web" : "aspnet";
log.Write(logLevel, source, formatter(state, exception), exception);
}
}
}
+381
View File
@@ -0,0 +1,381 @@
using System.Globalization;
using System.Net;
using Febe.Browser.Hosting;
using Febe.Browser.Recipes;
using Febe.Web;
namespace Febe.Server;
/// <summary>
/// Configuration of the real server (spec §11): environment variables of the container, plus a few command-line
/// options for development (other folders, the local test site, a short first-session delay). The password comes only
/// from the environment, never from the command line (which other users of the machine can read).
/// </summary>
internal sealed record ServerOptions
{
public const string DefaultZone = "Europe/Rome";
public const string DefaultLanguage = "it_IT.UTF-8";
public const int DefaultDebugPort = 9222;
public const string DefaultDisplay = ":99";
/// <summary>FEBE_PASSWORD: the interface password. Mandatory; never logged or shown.</summary>
public string? Password { get; init; }
/// <summary>Where Kestrel listens: every address in Docker (the port is published), 127.0.0.1 with <c>--ascolta</c>.</summary>
public IPAddress ListenAddress { get; init; } = IPAddress.Any;
/// <summary>FEBE_PORTA, 8480 by default.</summary>
public int Port { get; init; } = FebeListen.DefaultPort;
/// <summary>TZ, Europe/Rome by default: the clock of the engine, file names, and the browser's time zone.</summary>
public string ZoneId { get; init; } = DefaultZone;
public TimeZoneInfo Zone { get; init; } = FindZone(DefaultZone) ?? TimeZoneInfo.Utc;
/// <summary>LANG, it_IT.UTF-8 by default: the browser's language comes from it (spec §6.1).</summary>
public string Language { get; init; } = DefaultLanguage;
/// <summary>Data folder: database, browser profile, thumbnails, backups, log (/dati).</summary>
public string DataFolder { get; init; } = "/dati";
/// <summary>Library folder (/libreria).</summary>
public string LibraryFolder { get; init; } = "/libreria";
/// <summary>Import sources, read-only (/importa).</summary>
public string ImportFolder { get; init; } = "/importa";
/// <summary>FEBE_HOST: names the interface is reached with (comma separated). Empty: any name.</summary>
public IReadOnlyList<string> Hosts { get; init; } = [];
/// <summary>FEBE_PROXY_FIDATO=1: behind an HTTPS reverse proxy, X-Forwarded-Host counts for the Origin check.</summary>
public bool TrustForwardedHost { get; init; }
/// <summary>FEBE_SENZA_SANDBOX=1: Chromium with <c>--no-sandbox</c> (the compromise of S5, written in docs/docker.md).</summary>
public bool NoSandbox { get; init; }
/// <summary>FEBE_CHROMIUM: Chromium executable (default: Debian's chromium from PATH).</summary>
public string? ChromiumPath { get; init; }
/// <summary>FEBE_PORTA_DEBUG: the fixed DevTools port, on 127.0.0.1 only and never published (spec §6.1).</summary>
public int DebugPort { get; init; } = DefaultDebugPort;
/// <summary>FEBE_DISPLAY: the Xvfb display (:99).</summary>
public string Display { get; init; } = DefaultDisplay;
/// <summary>Size of the browser window, always the same (spec §6.1); Xvfb's screen has the same size.</summary>
public int WindowWidth { get; init; } = 1280;
public int WindowHeight { get; init; } = 900;
/// <summary>Development: the local test site (tools/Febe.SitoDiProva) instead of Instagram.</summary>
public Uri? TestSite { get; init; }
/// <summary>Development: the «CDN» of the test site (default: 127.0.0.2, site port + 1, as the tool starts it).</summary>
public Uri? TestCdn { get; init; }
/// <summary>Development, test site only: opens the site once at start-up so its session cookie exists, as after a login.</summary>
public bool TestSiteAutoLogin { get; init; }
/// <summary>Development: the first session comes after this delay instead of 2–10 minutes.</summary>
public TimeSpan? FirstSessionDelay { get; init; }
/// <summary>FEBE_INTERFACCIA: serve the interface from this folder (development).</summary>
public string? InterfaceFolder { get; init; }
/// <summary>Warnings found while reading the configuration (unknown time zone...), for the log.</summary>
public IReadOnlyList<string> Warnings { get; init; } = [];
/// <summary>The site the browser works on: Instagram, or the local test site in development.</summary>
public CollectionSite Site => TestSite is { } site
? CollectionSite.TestSite(site.Authority, (TestCdn ?? DefaultCdn(site)).Authority)
: CollectionSite.Instagram;
/// <summary>
/// The page «Accedi a Instagram» opens (PROTOCOLLO.md): Instagram's real login page, or a page of the test site,
/// whose first visit starts its session (it has no login form).
/// </summary>
public string LoginUrl => TestSite is { } site ? new Uri(site, "/benvenuto").AbsoluteUri : "https://www.instagram.com/accounts/login/";
/// <summary>The interface options of the Docker edition.</summary>
public FebeWebOptions WebOptions() => new()
{
Edition = FebeEdition.Docker,
Access = AccessMode.Password,
Password = string.IsNullOrEmpty(Password) ? null : Password,
AllowedHosts = AllowedHostList(),
TrustForwardedHost = TrustForwardedHost,
InterfaceFolder = InterfaceFolder,
};
/// <summary>
/// FEBE_HOST names with any port, plus the loopback names (the health check comes from inside the container).
/// Empty when FEBE_HOST is not set: any name, as documented for Docker (password and Origin protect it).
/// </summary>
public IReadOnlyList<string> AllowedHostList()
{
if (Hosts.Count == 0)
{
return [];
}
var list = new List<string>();
foreach (var host in Hosts.Concat(["127.0.0.1", "localhost", "[::1]"]))
{
list.Add(host);
list.Add(host + ":*");
}
return list.Distinct(StringComparer.OrdinalIgnoreCase).ToList();
}
/// <summary>
/// Reads the configuration. <paramref name="environment"/> gives environment variables (tests pass their own).
/// Returns false with an Italian <paramref name="problem"/> for a wrong command line.
/// </summary>
public static bool TryParse(string[] args, Func<string, string?> environment, out ServerOptions options, out string problem)
{
ArgumentNullException.ThrowIfNull(args);
ArgumentNullException.ThrowIfNull(environment);
options = new ServerOptions();
problem = string.Empty;
var warnings = new List<string>();
string? Env(string name) => environment(name) is { Length: > 0 } value ? value.Trim() : null;
bool Flag(string name) => Env(name) is { } value && value is "1" or "true" or "sì" or "si" or "yes";
var zoneId = Env("TZ") ?? DefaultZone;
var zone = FindZone(zoneId);
if (zone is null)
{
warnings.Add($"Fuso orario sconosciuto in TZ («{zoneId}»): uso {DefaultZone}.");
zoneId = DefaultZone;
zone = FindZone(DefaultZone) ?? TimeZoneInfo.Utc;
}
var port = FebeListen.DefaultPort;
if (Env("FEBE_PORTA") is { } portText && !TryPort(portText, out port))
{
problem = $"FEBE_PORTA non valida («{portText}»): un numero fra 1 e 65535.";
return false;
}
var debugPort = DefaultDebugPort;
if (Env("FEBE_PORTA_DEBUG") is { } debugText && (!TryPort(debugText, out debugPort) || debugPort < 1024))
{
problem = $"FEBE_PORTA_DEBUG non valida («{debugText}»): un numero fra 1024 e 65535.";
return false;
}
options = options with
{
Password = environment("FEBE_PASSWORD") is { Length: > 0 } password ? password : null,
Port = port,
ZoneId = zoneId,
Zone = zone,
Language = Env("LANG") ?? DefaultLanguage,
Hosts = SplitHosts(Env("FEBE_HOST")),
TrustForwardedHost = Flag("FEBE_PROXY_FIDATO"),
NoSandbox = Flag("FEBE_SENZA_SANDBOX"),
ChromiumPath = Env("FEBE_CHROMIUM"),
DebugPort = debugPort,
Display = Env("FEBE_DISPLAY") ?? DefaultDisplay,
InterfaceFolder = Env("FEBE_INTERFACCIA") is { } folder && Directory.Exists(folder) ? folder : null,
};
for (var i = 0; i < args.Length; i++)
{
var arg = args[i];
string? Next() => i + 1 < args.Length ? args[++i] : null;
switch (arg.ToLowerInvariant())
{
case "--dati":
options = options with { DataFolder = Next() ?? string.Empty };
break;
case "--libreria":
options = options with { LibraryFolder = Next() ?? string.Empty };
break;
case "--importa":
options = options with { ImportFolder = Next() ?? string.Empty };
break;
case "--porta":
{
var text = Next();
if (!TryPort(text, out var value))
{
problem = $"Porta non valida («{text}»): un numero fra 1 e 65535.";
return false;
}
options = options with { Port = value };
break;
}
case "--ascolta":
{
var text = Next();
if (!IPAddress.TryParse(text, out var address))
{
problem = $"Indirizzo non valido dopo --ascolta («{text}»), per esempio 127.0.0.1.";
return false;
}
options = options with { ListenAddress = address };
break;
}
case "--porta-debug":
{
var text = Next();
if (!TryPort(text, out var value) || value < 1024)
{
problem = $"Porta di debug non valida («{text}»): un numero fra 1024 e 65535.";
return false;
}
options = options with { DebugPort = value };
break;
}
case "--display":
options = options with { Display = Next() ?? string.Empty };
break;
case "--chromium":
options = options with { ChromiumPath = Next() };
break;
case "--senza-sandbox":
options = options with { NoSandbox = true };
break;
case "--sito-di-prova":
case "--cdn-di-prova":
{
var text = Next();
if (!TryLocalAddress(text, out var address))
{
problem = $"Indirizzo non valido dopo {arg} («{text}»): serve un indirizzo http di questo computer, per esempio http://127.0.0.1:8481.";
return false;
}
options = arg.Equals("--sito-di-prova", StringComparison.OrdinalIgnoreCase)
? options with { TestSite = address }
: options with { TestCdn = address };
break;
}
case "--accesso-di-prova":
options = options with { TestSiteAutoLogin = true };
break;
case "--prima-sessione":
{
var text = Next();
if (!int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var seconds) || seconds is < 1 or > 3600)
{
problem = $"Valore non valido dopo --prima-sessione («{text}»): secondi fra 1 e 3600.";
return false;
}
options = options with { FirstSessionDelay = TimeSpan.FromSeconds(seconds) };
break;
}
default:
problem = $"Opzione sconosciuta: {arg}.";
return false;
}
}
if (string.IsNullOrWhiteSpace(options.DataFolder) || string.IsNullOrWhiteSpace(options.LibraryFolder) || string.IsNullOrWhiteSpace(options.ImportFolder))
{
problem = "Dopo --dati, --libreria e --importa serve una cartella.";
return false;
}
if (options.TestSiteAutoLogin && options.TestSite is null)
{
problem = "--accesso-di-prova vale solo con --sito-di-prova: con Instagram l'accesso lo fa sempre Alberto, a mano.";
return false;
}
if (options.TestCdn is not null && options.TestSite is null)
{
problem = "--cdn-di-prova vale solo con --sito-di-prova.";
return false;
}
if (options.Display.Length < 2 || options.Display[0] != ':')
{
problem = $"Display non valido («{options.Display}»): si scrive come «:99».";
return false;
}
if (options.DebugPort == options.Port)
{
problem = "La porta di debug del browser deve essere diversa da quella dell'interfaccia.";
return false;
}
options = options with { Warnings = warnings };
return true;
}
/// <summary>The time zone named by TZ, or null when unknown.</summary>
public static TimeZoneInfo? FindZone(string id) =>
TimeZoneInfo.TryFindSystemTimeZoneById(id, out var zone) ? zone : null;
/// <summary>The environment of Chromium: LANG and TZ (defaults when unset), a home of its own, and no proxy (rule 2).</summary>
public IReadOnlyDictionary<string, string?> BrowserEnvironment(string home) => new Dictionary<string, string?>
{
["LANG"] = Language,
["TZ"] = ZoneId,
["HOME"] = home,
["LANGUAGE"] = null,
["LC_ALL"] = null,
["http_proxy"] = null,
["https_proxy"] = null,
["HTTP_PROXY"] = null,
["HTTPS_PROXY"] = null,
["ALL_PROXY"] = null,
["all_proxy"] = null,
["no_proxy"] = null,
["NO_PROXY"] = null,
};
/// <summary>How the browser is started (spec §6.1, §11).</summary>
public ChromiumLaunchOptions LaunchOptions(string home) => new()
{
NoSandbox = NoSandbox,
Environment = BrowserEnvironment(home),
SessionCookie = Site.SessionCookie,
SeedProfilePreferences = true,
};
private static Uri DefaultCdn(Uri site) => new UriBuilder(site) { Host = "127.0.0.2", Port = site.Port + 1, Path = "/" }.Uri;
private static IReadOnlyList<string> SplitHosts(string? value) => value is null
? []
: [.. value.Split([',', ' ', ';'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Select(h => h.ToLowerInvariant())];
private static bool TryPort(string? text, out int port) =>
int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out port) && port is >= 1 and <= 65535;
/// <summary>The test site must be on this computer: the switch can never point the browser elsewhere.</summary>
private static bool TryLocalAddress(string? text, out Uri address)
{
address = null!;
if (!Uri.TryCreate(text, UriKind.Absolute, out var uri) || uri.Scheme != Uri.UriSchemeHttp)
{
return false;
}
var local = uri.IsLoopback || (IPAddress.TryParse(uri.Host, out var ip) && IPAddress.IsLoopback(ip));
if (!local)
{
return false;
}
address = new Uri(uri.GetLeftPart(UriPartial.Authority) + "/");
return true;
}
}
+71
View File
@@ -0,0 +1,71 @@
using Febe.Core.Library;
using Febe.Web.Connection;
namespace Febe.Server;
/// <summary>
/// The checks made before anything starts (spec §8.2, §11): the interface password and the Data folder. With a problem
/// the engine and the browser do not start, and the interface shows only the page that explains it.
/// </summary>
internal static class StartupChecks
{
public const string PasswordMissing = "password-mancante";
public const string DataNotWritable = "dati-non-scrivibili";
public const string DataOnNetwork = "dati-in-rete";
/// <summary>Every problem found, in the order the error page shows them.</summary>
public static IReadOnlyList<ConfigurationProblem> Run(ServerOptions options, DataFolderCheck? check = null)
{
ArgumentNullException.ThrowIfNull(options);
var problems = new List<ConfigurationProblem>();
if (string.IsNullOrEmpty(options.Password))
{
problems.Add(new ConfigurationProblem(
PasswordMissing,
"Manca la password dell'interfaccia",
"Il contenitore è partito senza la variabile FEBE_PASSWORD. Senza password l'interfaccia, e con lei la vista "
+ "remota del browser, sarebbe aperta a chiunque raggiunga il server: per questo Febe non ha avviato né il motore né il browser.",
"Imposta FEBE_PASSWORD (nel modello di Unraid o in compose.yml) con una frase lunga che usi solo qui, poi riavvia il contenitore."));
}
if ((check ?? new DataFolderCheck()).Check(options.DataFolder) is { } data)
{
problems.Add(new ConfigurationProblem(
data.Kind == DataFolderProblemKind.NetworkPath ? DataOnNetwork : DataNotWritable,
data.Title,
data.Explanation,
data.Remedy));
}
return problems;
}
}
/// <summary>The problems found at start-up; fixed for the life of the process (fixing one needs a restart).</summary>
internal sealed class StartupProblems(IReadOnlyList<ConfigurationProblem> problems) : IConfigurationProblems
{
public IReadOnlyList<ConfigurationProblem> Current { get; } = problems;
}
/// <summary>
/// The link to Instagram while a configuration problem keeps the browser from starting: always «browser non
/// disponibile», and every command refused with the problem (the configuration gate refuses them earlier anyway).
/// </summary>
internal sealed class UnavailableConnectionService(IReadOnlyList<ConfigurationProblem> problems) : IConnectionService
{
public Task<ConnectionStatus> GetStatusAsync(CancellationToken ct) =>
Task.FromResult(new ConnectionStatus(ConnectionState.BrowserUnavailable, null, null, false, null));
public Task BeginUserDrivingAsync(bool openLogin, CancellationToken ct) => throw Refused();
public Task<FinishResult> FinishAsync(CancellationToken ct) => throw Refused();
public Task CancelAsync(CancellationToken ct) => Task.CompletedTask;
public Task DisconnectAsync(CancellationToken ct) => throw Refused();
private Febe.Web.Api.BadRequestException Refused() =>
new($"{(problems.Count > 0 ? problems[0].Title : "Configurazione da sistemare")}: il browser di Febe non è partito.");
}
@@ -0,0 +1,69 @@
using Febe.Web.Api;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
namespace Febe.Web.Connection;
/// <summary>
/// <c>GET /salute</c> (PROTOCOLLO.md, spec §11): <c>200 {"stato":"ok"}</c> or <c>503 {"stato":"problema"}</c> and
/// nothing else, without authentication, for the Docker health check. It says no more than that on purpose.
/// </summary>
public static class HealthEndpoint
{
public const string Path = "/salute";
public const string Ok = """{"stato":"ok"}""";
public const string Problem = """{"stato":"problema"}""";
public static void Map(IEndpointRouteBuilder endpoints)
{
ArgumentNullException.ThrowIfNull(endpoints);
endpoints.MapMethods(Path, [HttpMethods.Get, HttpMethods.Head], (HttpContext context, IConfigurationProblems problems) =>
{
context.Response.Headers.CacheControl = "no-store";
var healthy = problems.Current.Count == 0;
return Results.Text(healthy ? Ok : Problem, "application/json; charset=utf-8", statusCode: healthy ? StatusCodes.Status200OK : StatusCodes.Status503ServiceUnavailable);
});
}
/// <summary>True for the health check request, which needs neither a session nor an allowed Host.</summary>
public static bool IsHealthRequest(HttpRequest request)
{
ArgumentNullException.ThrowIfNull(request);
return (HttpMethods.IsGet(request.Method) || HttpMethods.IsHead(request.Method))
&& string.Equals(request.Path.Value, Path, StringComparison.OrdinalIgnoreCase);
}
}
/// <summary>
/// While a configuration problem keeps the engine from starting (spec §8.2, §11), the interface shows only the page
/// that explains it: the API answers only what that page and the frame around it need, everything else (library,
/// accounts, connection, remote view) gets 503 with the problem in Italian.
/// </summary>
public sealed class ConfigurationGateMiddleware(RequestDelegate next, IConfigurationProblems problems)
{
/// <summary>API addresses still answered while there is a problem.</summary>
public static readonly IReadOnlyList<string> AllowedApi =
["/api/capabilities", "/api/preferences", "/api/accesso", "/api/uscita", "/api/engine", "/api/eventi"];
public async Task InvokeAsync(HttpContext context)
{
ArgumentNullException.ThrowIfNull(context);
var current = problems.Current;
var path = context.Request.Path;
if (current.Count == 0
|| !path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase)
|| AllowedApi.Any(a => string.Equals(path.Value, a, StringComparison.OrdinalIgnoreCase)))
{
await next(context).ConfigureAwait(false);
return;
}
context.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
await context.Response.WriteAsJsonAsync(
new ProblemDto($"{current[0].Title}. Il motore non è partito: {current[0].Remedy}"),
FebeJsonContext.Default.ProblemDto).ConfigureAwait(false);
}
}
+136
View File
@@ -0,0 +1,136 @@
namespace Febe.Web.Connection;
/// <summary>
/// The browser seen through the interface (Docker only, spec §4.1, §11, mockup 10). Implemented by the server
/// composition over the real Chromium; the web layer only speaks the protocol of <c>PROTOCOLLO.md</c> over a WebSocket.
/// </summary>
public interface IRemoteViewHost
{
/// <summary>
/// Opens a remote view: Alberto is now driving (the engine is still) and frames start. A view opened earlier
/// (another tab) is closed with <see cref="RemoteViewEnd.Replaced"/>.
/// </summary>
/// <exception cref="RemoteViewUnavailableException">The browser is not running: nothing to show.</exception>
Task<IRemoteViewConnection> OpenAsync(CancellationToken ct);
}
/// <summary>One open remote view. Disposing it stops the frames and ends «Alberto is driving».</summary>
public interface IRemoteViewConnection : IAsyncDisposable
{
/// <summary>What goes to the page, in order: meta first, then frames (the oldest dropped when the page is slow).</summary>
IAsyncEnumerable<RemoteViewOutput> ReadAsync(CancellationToken ct);
/// <summary>Why the view ended on the server side (null while it is open).</summary>
RemoteViewEnd? Ended { get; }
Task MouseAsync(RemoteViewMouse input, CancellationToken ct);
Task KeyAsync(RemoteViewKey input, CancellationToken ct);
Task NavigateAsync(RemoteViewNavigation action, CancellationToken ct);
}
/// <summary>Why a remote view ended without Alberto closing it.</summary>
public enum RemoteViewEnd
{
/// <summary>Opened again in another tab or window: the newest wins.</summary>
Replaced,
/// <summary>The browser stopped or is restarting.</summary>
BrowserStopped,
/// <summary>The server is shutting down.</summary>
ShuttingDown,
}
/// <summary>A message for the page: a JPEG frame, or a meta message (address and size).</summary>
public abstract record RemoteViewOutput;
/// <summary>A frame of the screencast, sent as one binary WebSocket message.</summary>
/// <param name="Jpeg">The JPEG bytes.</param>
public sealed record RemoteViewFrame(ReadOnlyMemory<byte> Jpeg) : RemoteViewOutput;
/// <summary>Sent at the start and whenever the address or the size changes.</summary>
/// <param name="Width">Page width in CSS pixels the frames represent.</param>
/// <param name="Height">Page height in CSS pixels the frames represent.</param>
/// <param name="Url">Address of the page without query string or fragment.</param>
public sealed record RemoteViewMeta(int Width, int Height, string Url) : RemoteViewOutput;
public enum RemoteViewMouseAction
{
Move,
Down,
Up,
Wheel,
}
public enum RemoteViewButton
{
None,
Left,
Middle,
Right,
}
/// <summary>A mouse event; <paramref name="X"/> and <paramref name="Y"/> are 0–1 of the frame.</summary>
public sealed record RemoteViewMouse(
RemoteViewMouseAction Action,
double X,
double Y,
RemoteViewButton Button,
int ClickCount,
double DeltaX,
double DeltaY);
public enum RemoteViewKeyAction
{
/// <summary>Key pressed; when it has <see cref="RemoteViewKey.Text"/> the text is inserted.</summary>
Down,
Up,
/// <summary>Text only (composed characters): inserted without key codes.</summary>
Char,
}
/// <summary>
/// A key from the page. Contains what Alberto types, passwords included: never logged, never stored, never shown
/// (spec §13.2). <see cref="ToString"/> hides everything on purpose.
/// </summary>
/// <param name="Action">Down, up or char.</param>
/// <param name="Key">DOM <c>key</c>.</param>
/// <param name="Code">DOM <c>code</c>.</param>
/// <param name="Text">Text the key produces, if any.</param>
/// <param name="Modifiers">Bit mask of <c>Input.dispatchKeyEvent</c>: Alt 1, Ctrl 2, Meta 4, Shift 8.</param>
public sealed record RemoteViewKey(RemoteViewKeyAction Action, string Key, string Code, string? Text, int Modifiers)
{
public override string ToString() => "RemoteViewKey(…)";
}
public enum RemoteViewNavigation
{
/// <summary>Back to the previous address of this view.</summary>
Back,
/// <summary>Reload the current page.</summary>
Reload,
}
/// <summary>The browser is not available (starting, restarting, missing, or Febe stopped by a configuration problem).</summary>
public sealed class RemoteViewUnavailableException : Exception
{
public RemoteViewUnavailableException()
: base("Il browser di Febe non è disponibile in questo momento.")
{
}
public RemoteViewUnavailableException(string message)
: base(message)
{
}
public RemoteViewUnavailableException(string message, Exception? inner)
: base(message, inner)
{
}
}
+349
View File
@@ -0,0 +1,349 @@
using System.Buffers;
using System.Net.WebSockets;
using System.Text.Json;
using Febe.Web.Api;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
namespace Febe.Web.Connection;
/// <summary>
/// <c>/api/vista</c>: the remote view over a WebSocket (PROTOCOLLO.md, spec §4.1, §11). The security middleware has
/// already checked the session and the <c>Origin</c> (spec §13.1) before this runs. Frames go out as binary messages,
/// meta as text; mouse, keys and back/reload come in as small JSON text messages and go to the browser. Nothing that
/// comes in is ever logged: it contains what Alberto types.
/// </summary>
public static class RemoteViewSocket
{
public const string Path = "/api/vista";
/// <summary>Largest message accepted from the page; larger ones close the view.</summary>
public const int MaxMessageBytes = 4096;
/// <summary>Close code when the view was opened again elsewhere (the newest wins).</summary>
public const int CloseReplaced = 4001;
/// <summary>Close code when the browser stopped or is restarting.</summary>
public const int CloseBrowserStopped = 4002;
public static void Map(IEndpointRouteBuilder endpoints)
{
ArgumentNullException.ThrowIfNull(endpoints);
endpoints.Map(Path, HandleAsync);
}
public static async Task HandleAsync(HttpContext context)
{
ArgumentNullException.ThrowIfNull(context);
var options = context.RequestServices.GetRequiredService<FebeWebOptions>();
if (options.Edition == FebeEdition.Desktop && !options.Demo)
{
await RefuseAsync(context, StatusCodes.Status404NotFound, "Sul desktop il browser di Febe ha la sua finestra: la vista remota c'è solo nel contenitore.").ConfigureAwait(false);
return;
}
if (!context.WebSockets.IsWebSocketRequest)
{
await RefuseAsync(context, StatusCodes.Status400BadRequest, "La vista remota si apre solo con una connessione WebSocket.").ConfigureAwait(false);
return;
}
if (context.RequestServices.GetService<IRemoteViewHost>() is not { } host)
{
await RefuseAsync(context, StatusCodes.Status503ServiceUnavailable, "La vista remota non è disponibile: il browser di Febe non è in funzione.").ConfigureAwait(false);
return;
}
IRemoteViewConnection connection;
try
{
connection = await host.OpenAsync(context.RequestAborted).ConfigureAwait(false);
}
catch (RemoteViewUnavailableException ex)
{
await RefuseAsync(context, StatusCodes.Status503ServiceUnavailable, ex.Message).ConfigureAwait(false);
return;
}
await using (connection.ConfigureAwait(false))
{
using var socket = await context.WebSockets.AcceptWebSocketAsync(new WebSocketAcceptContext
{
KeepAliveInterval = TimeSpan.FromSeconds(20),
DangerousEnableCompression = false,
}).ConfigureAwait(false);
await RunAsync(socket, connection, context.RequestAborted).ConfigureAwait(false);
}
}
/// <summary>Pumps one view until either side closes it.</summary>
internal static async Task RunAsync(WebSocket socket, IRemoteViewConnection connection, CancellationToken aborted)
{
using var stop = CancellationTokenSource.CreateLinkedTokenSource(aborted);
var sender = Task.Run(() => SendLoopAsync(socket, connection, stop.Token), CancellationToken.None);
var closeStatus = WebSocketCloseStatus.NormalClosure;
var closeText = "Vista chiusa";
try
{
if (!await ReceiveLoopAsync(socket, connection, stop.Token).ConfigureAwait(false))
{
closeStatus = WebSocketCloseStatus.MessageTooBig;
closeText = "Messaggio troppo lungo";
}
}
catch (Exception ex) when (ex is WebSocketException or OperationCanceledException)
{
// The page went away.
}
finally
{
await stop.CancelAsync().ConfigureAwait(false);
try
{
await sender.ConfigureAwait(false);
}
catch (Exception ex) when (ex is WebSocketException or OperationCanceledException or ObjectDisposedException)
{
}
}
if (socket.State is WebSocketState.Open or WebSocketState.CloseReceived)
{
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(2));
try
{
await socket.CloseOutputAsync(closeStatus, closeText, timeout.Token).ConfigureAwait(false);
}
catch (Exception ex) when (ex is WebSocketException or OperationCanceledException or ObjectDisposedException)
{
}
}
}
private static async Task SendLoopAsync(WebSocket socket, IRemoteViewConnection connection, CancellationToken ct)
{
await foreach (var output in connection.ReadAsync(ct).ConfigureAwait(false))
{
switch (output)
{
case RemoteViewMeta meta:
await socket.SendAsync(MetaJson(meta), WebSocketMessageType.Text, endOfMessage: true, ct).ConfigureAwait(false);
break;
case RemoteViewFrame frame:
await socket.SendAsync(frame.Jpeg, WebSocketMessageType.Binary, endOfMessage: true, ct).ConfigureAwait(false);
break;
}
}
// The server ended the view (another tab, browser stopped, shutdown): tell the page why.
if (!ct.IsCancellationRequested && socket.State == WebSocketState.Open)
{
var (status, text) = connection.Ended switch
{
RemoteViewEnd.Replaced => ((WebSocketCloseStatus)CloseReplaced, "Vista aperta in un'altra finestra"),
RemoteViewEnd.ShuttingDown => (WebSocketCloseStatus.EndpointUnavailable, "Febe si sta fermando"),
_ => ((WebSocketCloseStatus)CloseBrowserStopped, "Il browser si è fermato"),
};
await socket.CloseOutputAsync(status, text, ct).ConfigureAwait(false);
}
}
/// <summary>
/// Reads the page's messages until it closes. Returns false when a message was too long: the caller closes the
/// view (only one task may send at a time, and the frames are being sent by another).
/// </summary>
private static async Task<bool> ReceiveLoopAsync(WebSocket socket, IRemoteViewConnection connection, CancellationToken ct)
{
var buffer = ArrayPool<byte>.Shared.Rent(MaxMessageBytes + 1);
try
{
while (socket.State == WebSocketState.Open && !ct.IsCancellationRequested)
{
var length = 0;
ValueWebSocketReceiveResult result;
do
{
if (length >= MaxMessageBytes + 1)
{
return false;
}
result = await socket.ReceiveAsync(buffer.AsMemory(length, MaxMessageBytes + 1 - length), ct).ConfigureAwait(false);
if (result.MessageType == WebSocketMessageType.Close)
{
return true;
}
length += result.Count;
}
while (!result.EndOfMessage);
if (length > MaxMessageBytes)
{
return false;
}
if (result.MessageType != WebSocketMessageType.Text)
{
continue;
}
await DispatchAsync(buffer.AsMemory(0, length), connection, ct).ConfigureAwait(false);
}
return true;
}
finally
{
ArrayPool<byte>.Shared.Return(buffer, clearArray: true);
}
}
/// <summary>Parses one message of the page and forwards it. Unknown or malformed messages are dropped silently.</summary>
internal static async Task DispatchAsync(ReadOnlyMemory<byte> message, IRemoteViewConnection connection, CancellationToken ct)
{
object? input;
try
{
input = Parse(message);
}
catch (JsonException)
{
return;
}
try
{
switch (input)
{
case RemoteViewMouse mouse:
await connection.MouseAsync(mouse, ct).ConfigureAwait(false);
break;
case RemoteViewKey key:
await connection.KeyAsync(key, ct).ConfigureAwait(false);
break;
case RemoteViewNavigation navigation:
await connection.NavigateAsync(navigation, ct).ConfigureAwait(false);
break;
}
}
catch (Exception ex) when (ex is not OperationCanceledException && ex is not OutOfMemoryException)
{
// A lost gesture (no frame yet, browser restarting): the page simply tries again. Never logged: it may
// be a key of a password.
}
}
/// <summary>
/// The input messages of PROTOCOLLO.md: <c>mouse</c>, <c>key</c>, <c>navigate</c>. Returns null for anything else
/// (unknown type or action, missing fields, values out of range).
/// </summary>
internal static object? Parse(ReadOnlyMemory<byte> message)
{
using var document = JsonDocument.Parse(message, new JsonDocumentOptions { MaxDepth = 3 });
var root = document.RootElement;
if (root.ValueKind != JsonValueKind.Object || Text(root, "type", 16) is not { } type)
{
return null;
}
var action = Text(root, "action", 16);
switch (type)
{
case "mouse":
{
RemoteViewMouseAction? kind = action switch
{
"move" => RemoteViewMouseAction.Move,
"down" => RemoteViewMouseAction.Down,
"up" => RemoteViewMouseAction.Up,
"wheel" => RemoteViewMouseAction.Wheel,
_ => null,
};
if (kind is null || Number(root, "x") is not { } x || Number(root, "y") is not { } y || x is < 0 or > 1 || y is < 0 or > 1)
{
return null;
}
var button = Text(root, "button", 16) switch
{
"left" => RemoteViewButton.Left,
"middle" => RemoteViewButton.Middle,
"right" => RemoteViewButton.Right,
_ => kind is RemoteViewMouseAction.Down or RemoteViewMouseAction.Up ? RemoteViewButton.Left : RemoteViewButton.None,
};
var clicks = (int)Math.Clamp(Number(root, "clickCount") ?? 1, 1, 3);
var dx = Math.Clamp(Number(root, "deltaX") ?? 0, -5000, 5000);
var dy = Math.Clamp(Number(root, "deltaY") ?? 0, -5000, 5000);
return new RemoteViewMouse(kind.Value, x, y, button, clicks, dx, dy);
}
case "key":
{
RemoteViewKeyAction? kind = action switch
{
"down" => RemoteViewKeyAction.Down,
"up" => RemoteViewKeyAction.Up,
"char" => RemoteViewKeyAction.Char,
_ => null,
};
var key = Text(root, "key", 64) ?? string.Empty;
var code = Text(root, "code", 64) ?? string.Empty;
var text = Text(root, "text", 32);
var modifiers = (int)Math.Clamp(Number(root, "modifiers") ?? 0, 0, 15);
if (kind is null || (kind == RemoteViewKeyAction.Char ? string.IsNullOrEmpty(text) : key.Length == 0))
{
return null;
}
return new RemoteViewKey(kind.Value, key, code, string.IsNullOrEmpty(text) ? null : text, modifiers);
}
case "navigate":
return action switch
{
"back" => RemoteViewNavigation.Back,
"reload" => RemoteViewNavigation.Reload,
_ => null,
};
default:
return null;
}
}
/// <summary>The meta message as UTF-8 JSON.</summary>
internal static ReadOnlyMemory<byte> MetaJson(RemoteViewMeta meta)
{
var buffer = new ArrayBufferWriter<byte>(256);
using (var writer = new Utf8JsonWriter(buffer))
{
writer.WriteStartObject();
writer.WriteString("type", "meta");
writer.WriteNumber("width", meta.Width);
writer.WriteNumber("height", meta.Height);
writer.WriteString("url", meta.Url);
writer.WriteEndObject();
}
return buffer.WrittenMemory;
}
private static string? Text(JsonElement root, string name, int maxLength) =>
root.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String && value.GetString() is { } s && s.Length <= maxLength
? s
: null;
private static double? Number(JsonElement root, string name) =>
root.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.Number && value.TryGetDouble(out var d) && double.IsFinite(d)
? d
: null;
private static Task RefuseAsync(HttpContext context, int status, string message)
{
context.Response.StatusCode = status;
return context.Response.WriteAsJsonAsync(new ProblemDto(message), FebeJsonContext.Default.ProblemDto);
}
}
+8
View File
@@ -2,6 +2,7 @@ using System.Net;
using Febe.Core.Abstractions;
using Febe.Core.Engine;
using Febe.Web.Api;
using Febe.Web.Connection;
using Febe.Web.Demo;
using Febe.Web.Engine;
using Febe.Web.Hosting;
@@ -58,6 +59,7 @@ public static class FebeWeb
services.TryAddSingleton<OfflineEngine>();
services.TryAddSingleton<IEngineMonitor>(sp => sp.GetRequiredService<OfflineEngine>());
services.TryAddSingleton<IEngineControl>(sp => sp.GetRequiredService<OfflineEngine>());
services.TryAddSingleton<IConfigurationProblems, NoConfigurationProblems>();
services.AddHttpContextAccessor();
if (options.Access == AccessMode.Password && !string.IsNullOrEmpty(options.Password))
{
@@ -86,6 +88,10 @@ public static class FebeWeb
}
app.UseMiddleware<ApiErrorMiddleware>();
app.UseMiddleware<ConfigurationGateMiddleware>();
// The remote view (/api/vista). Origin and session are checked by the security middleware above.
app.UseWebSockets();
var types = new FileExtensionContentTypeProvider();
types.Mappings[".json"] = "application/json; charset=utf-8";
types.Mappings[".js"] = "text/javascript; charset=utf-8";
@@ -111,6 +117,8 @@ public static class FebeWeb
LibraryApi.Map(endpoints);
AccountsApi.Map(endpoints);
AccessApi.Map(endpoints);
RemoteViewSocket.Map(endpoints);
HealthEndpoint.Map(endpoints);
endpoints.Map("/api/{**rest}", static context =>
{
+27 -1
View File
@@ -51,7 +51,7 @@ var address = FebeWebHost.BoundAddress(app);
| Veste | Opzioni | Effetto |
|---|---|---|
| Docker | `Edition = Docker`, `Access = Password`, `Password = FEBE_PASSWORD`, `AllowedHosts` = nomi con cui si raggiunge il server (anche `nome:*`), `FebeListen.Any(8480)` | Pagina `/accesso`, cookie `febe_sessione` HttpOnly SameSite=Strict, blocco dopo 5 errori per client e 20 in tutto in 15 minuti. Senza password risponde 503 e non si apre |
| Docker | `Edition = Docker`, `Access = Password`, `Password = FEBE_PASSWORD`, `AllowedHosts` = nomi con cui si raggiunge il server (anche `nome:*`), `FebeListen.Any(8480)` | Pagina `/accesso`, cookie `febe_sessione` HttpOnly SameSite=Strict, blocco dopo 5 errori per client e 20 in tutto in 15 minuti. Senza password risponde solo alla pagina dell'errore (indirizzi delle pagine, file dell'interfaccia, `GET /api/capabilities` e `/api/preferences`, `/salute`); tutto il resto, vista remota compresa, 503 |
| Windows | `Edition = Desktop`, `Access = Token`, `AccessToken = AccessToken.Create()`, `AllowedHosts = FebeWebOptions.LoopbackHosts(porta)`, `FebeListen.Loopback(0)` | La finestra apre `/?gettone=…` una volta: il gettone diventa un cookie HttpOnly Strict e sparisce dall'indirizzo. Anche l'intestazione `X-Febe-Gettone` vale |
| Prove e dimostrazione | `Access = None` | Solo su 127.0.0.1 |
@@ -88,6 +88,32 @@ sono anche `day` (`aaaa-mm-gg`) e `clock` calcolati sul fuso di Febe.
Ogni altro indirizzo senza estensione risponde con `index.html`; `/api/…` sconosciuto risponde 404 in JSON.
## Collegamento, vista remota, salute (veste Docker)
Il contratto con l'interfaccia è `Connection/PROTOCOLLO.md`. Lato server:
- `IConnectionService` lo registra la composizione (`Febe.Server/ServerConnectionService`, sul Chromium vero; con un
problema di configurazione `UnavailableConnectionService`). Gli endpoint `/api/connection/*` lo usano.
- `IRemoteViewHost` (`Connection/RemoteView.cs`) apre una vista: `IRemoteViewConnection.ReadAsync` dà prima `meta` poi
fotogrammi (i vecchi si scartano se la pagina è lenta), `MouseAsync`/`KeyAsync`/`NavigateAsync` portano i gesti al
browser. Una vista alla volta: aprirne un'altra chiude la precedente. Senza `IRemoteViewHost` registrato,
`/api/vista` risponde 503.
- `/api/vista` (`Connection/RemoteViewSocket.cs`): WebSocket dietro il controllo di sessione e di `Origin` del
`SecurityMiddleware`; 404 sulla veste desktop (fuori dalla dimostrazione), 400 se non è un WebSocket, 503 senza
browser. Messaggi in arrivo solo testo, al massimo 4 KB (oltre: chiusura 1009); quelli sconosciuti, malformati o con
valori fuori intervallo (x e y fuori da 0–1) si scartano in silenzio. Mai registrati.
- `modifiers` dei tasti: la maschera di `Input.dispatchKeyEvent` (Alt 1, Ctrl 2, Meta 4, Shift 8).
- `key` con `action: "down"` e `text` inserisce il testo; `action: "char"` (con il solo `text`) inserisce un carattere
composto senza codici tasto. Per un tasto normale si manda `down` (con `text`) e poi `up`, non anche `char`.
- `navigate`: `back` torna all'indirizzo precedente di questa vista (con `Page.navigate`: fra i comandi ammessi di
§6.1 non c'è la cronologia del browser), `reload` ricarica l'indirizzo attuale.
- Chiusure dal server: 4001 «Vista aperta in un'altra finestra», 4002 «Il browser si è fermato», 1001 «Febe si sta
fermando», 1000 normale.
- `GET /salute` (`Connection/ConfigurationGate.cs`): senza sessione e con qualunque Host, `200 {"stato":"ok"}` o
`503 {"stato":"problema"}` quando `IConfigurationProblems.Current` non è vuoto.
- `ConfigurationGateMiddleware`: con un problema di configurazione l'API risponde solo a `capabilities`, `preferences`,
`accesso`, `uscita`, `engine` (GET, motore spento) ed `eventi`; il resto 503 con il problema in italiano.
## Interfaccia (`wwwroot/`)
Moduli ES, nessuna dipendenza, nessuna build. Durante lo sviluppo si servono da disco:
+39 -1
View File
@@ -14,6 +14,13 @@ public sealed class SecurityMiddleware(RequestDelegate next, FebeWebOptions opti
public static readonly IReadOnlyList<string> PublicPrefixes =
["/accesso", "/api/accesso", "/css/", "/caratteri/", "/img/", "/testi/", "/js/", "/favicon.ico"];
/// <summary>
/// Without a password (FEBE_PASSWORD missing) only these answer, so that the interface can show the page that
/// explains the problem (spec §11): the application page, its files, the capabilities with the problems, the
/// preferences (theme). Everything else, the remote view first, gets 503.
/// </summary>
public static readonly IReadOnlyList<string> WithoutPasswordApi = ["/api/capabilities", "/api/preferences"];
public async Task InvokeAsync(HttpContext context)
{
ArgumentNullException.ThrowIfNull(context);
@@ -21,6 +28,13 @@ public sealed class SecurityMiddleware(RequestDelegate next, FebeWebOptions opti
var response = context.Response;
SetHeaders(response);
// The Docker health check: no session, any Host (it comes from inside the container), «ok» or «problema» only.
if (Connection.HealthEndpoint.IsHealthRequest(request))
{
await next(context).ConfigureAwait(false);
return;
}
if (!HostOriginGuard.HostAllowed(request, options))
{
await RefuseAsync(context, StatusCodes.Status400BadRequest, "Indirizzo non ammesso: apri Febe dal suo indirizzo.").ConfigureAwait(false);
@@ -99,13 +113,18 @@ public sealed class SecurityMiddleware(RequestDelegate next, FebeWebOptions opti
private async Task<bool> PasswordAsync(HttpContext context)
{
var path = context.Request.Path.Value ?? "/";
if (passwords is null)
{
if (OpenWithoutPassword(context.Request, path))
{
return true;
}
await RefuseAsync(context, StatusCodes.Status503ServiceUnavailable, "Manca la password dell'interfaccia (FEBE_PASSWORD): Febe non si apre senza.").ConfigureAwait(false);
return false;
}
var path = context.Request.Path.Value ?? "/";
if (PublicPrefixes.Any(p => path.StartsWith(p, StringComparison.OrdinalIgnoreCase)))
{
return true;
@@ -130,6 +149,25 @@ public sealed class SecurityMiddleware(RequestDelegate next, FebeWebOptions opti
private static bool IsApi(HttpRequest request) => request.Path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase);
/// <summary>What may be read without a password: the error page and what it needs, never a command.</summary>
private static bool OpenWithoutPassword(HttpRequest request, string path)
{
if (!HttpMethods.IsGet(request.Method) && !HttpMethods.IsHead(request.Method))
{
return false;
}
if (IsApi(request))
{
return WithoutPasswordApi.Any(a => string.Equals(path, a, StringComparison.OrdinalIgnoreCase));
}
// Interface files, and page addresses (no extension) that answer with the application page.
return PublicPrefixes.Any(p => path.StartsWith(p, StringComparison.OrdinalIgnoreCase))
|| path.StartsWith("/icone/", StringComparison.OrdinalIgnoreCase)
|| !Path.HasExtension(path);
}
private static async Task RefuseAsync(HttpContext context, int status, string message)
{
context.Response.StatusCode = status;