using System.Globalization; using Febe.Browser.Cdp; using Febe.Browser.Hosting; using Febe.Core.Abstractions; namespace Febe.App; /// How a Chromium-family browser is started and looked after (spec §6.1, §11; S2 fallback on Windows). public sealed record ChromiumBrowserSettings { /// The profile folder given to the browser (--user-data-dir): it holds the Instagram session. public required string ProfileDirectory { get; init; } /// /// The folder «Scollega» deletes while the browser is stopped. Null: . On Windows the /// Edge profile is a subfolder of Dati\browser, and «Scollega» deletes the whole Dati\browser. /// public string? ProfileFolderToDelete { get; init; } /// Folder created before the start (Docker: the HOME of the browser process). Null: none. public string? HomeDirectory { get; init; } /// Size of the browser window, always the same (spec §6.1). public int WindowWidth { get; init; } = 1280; public int WindowHeight { get; init; } = 900; /// The fixed DevTools port, on 127.0.0.1 only (spec §6.1). public int DebugPort { get; init; } = 9222; /// The executable; null: . public string? ExecutablePath { get; init; } /// The Xvfb display (Docker, «:99»). Null: no virtual display, the browser opens a normal window. public string? Display { get; init; } /// Arguments, environment, cookie of the session, restart policy. public ChromiumLaunchOptions Launch { get; init; } = new(); /// Added to the «browser ready» log line (Docker: «, senza sandbox (FEBE_SENZA_SANDBOX)»). public string? ReadyRemark { get; init; } /// Added to a start error that mentions the sandbox (Docker: where the seccomp profile is explained). public string? SandboxAdvice { get; init; } } /// /// A Chromium-family browser started and supervised by Febe itself, never by a shell script (spec §5, §6.1, §11): the /// distribution's Chromium on Xvfb in Docker, or Edge on Windows as the last fallback of S2. A start that fails /// (browser missing, sandbox refused, port taken) is retried with a growing wait; once running, the supervisors of /// and restart what crashes. /// public sealed class ChromiumBrowser : IFebeBrowser { private static readonly TimeSpan[] Retry = [TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(30), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(5)]; private readonly ChromiumBrowserSettings _settings; private readonly IClock _clock; private readonly FebeLog _log; private readonly TaskCompletionSource _ready = new(TaskCreationOptions.RunContinuationsAsynchronously); private XvfbProcess? _xvfb; private volatile bool _started; private volatile string? _lastError; public ChromiumBrowser(ChromiumBrowserSettings settings, IClock clock, FebeLog log) { _settings = settings ?? throw new ArgumentNullException(nameof(settings)); 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(settings.ProfileDirectory); HomeDirectory = settings.HomeDirectory is { } home ? Path.GetFullPath(home) : null; Host = new ChromiumProcessHost(settings.Launch, _clock, log.ForBrowser()); BrowserOptions = new BrowserOptions( ProfileDirectory, settings.WindowWidth, settings.WindowHeight, settings.DebugPort, settings.ExecutablePath, settings.Display); } /// The browser: stable for the whole life of the composition (a «Scollega» restarts it in place). public ChromiumProcessHost Host { get; } public BrowserOptions BrowserOptions { get; } public ICdpSession Cdp => Host.Cdp; public UserDrivingGate UserDriving => Host.UserDriving; public string ProfileDirectory { get; } /// HOME of the browser process (certificate database, font cache); null when not set. public string? HomeDirectory { get; } public int WindowWidth => BrowserOptions.WindowWidth; public int WindowHeight => BrowserOptions.WindowHeight; /// True when the browser runs on a virtual display (Docker). public bool UsesXvfb => _settings.Display is not null; /// True when the browser runs and a page connection is attached. public bool IsAvailable => _started && Host.IsAttached; /// Completes when the browser started the first time. public Task Ready => _ready.Task; public string? LastError => _lastError; public bool UserIsDriving => Host.UserIsDriving; 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 {WindowWidth.ToString(CultureInfo.InvariantCulture)}×{WindowHeight.ToString(CultureInfo.InvariantCulture)}, porta di debug {_settings.DebugPort.ToString(CultureInfo.InvariantCulture)} solo su 127.0.0.1{_settings.ReadyRemark}."); 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; } } } } public Task RestAsync(CancellationToken ct) => Host.RestAsync(ct); /// Nothing: in Docker the remote view shows the browser (on Windows, EdgeBrowser moves the window). public Task ShowToUserAsync(CancellationToken ct) => Task.CompletedTask; /// Nothing: on Xvfb the window is never in anyone's view. public Task HideFromUserAsync(CancellationToken ct) => Task.CompletedTask; /// /// «Scollega» (spec §4.1): stops the browser (SIGINT on Linux, so it closes cleanly), deletes the profile folder with /// the Instagram session, and starts the browser again with an empty profile. /// 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) { if (HomeDirectory is { } home) { Directory.CreateDirectory(home); } if (_settings.Display is { } display && _xvfb is null) { RemoveStaleDisplayLock(display); var xvfb = new XvfbProcess(display, WindowWidth, 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() { var folder = _settings.ProfileFolderToDelete is { } root ? Path.GetFullPath(root) : ProfileDirectory; if (Directory.Exists(folder)) { Directory.Delete(folder, recursive: true); } } /// /// 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. /// 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) { } } } /// /// 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. /// 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 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 + _settings.SandboxAdvice, _ => $"{ex.GetType().Name}: {ex.Message}", }; }