using System.Diagnostics;
using System.Globalization;
using Febe.Browser.Diagnostics;
using Febe.Core.Abstractions;
using Febe.Core.Security;
namespace Febe.Browser.Hosting;
///
/// The virtual display of the Docker version (spec §6.1, §11): Chromium runs as a normal windowed browser on it.
/// Supervised: restarted with backoff if it exits; Chromium, which loses its display, is restarted by its own host.
///
public sealed class XvfbProcess : IAsyncDisposable
{
private readonly SupervisedProcess _supervisor;
private readonly int _displayNumber;
/// Display name, e.g. «:99».
/// Screen width: at least the browser window width.
/// Screen height: at least the browser window height.
/// Xvfb executable; null searches PATH.
public XvfbProcess(
string display = ":99",
int width = 1280,
int height = 900,
string? executable = null,
IClock? clock = null,
IBrowserLog? log = null,
RestartPolicy? restart = null)
{
_displayNumber = ParseDisplay(display);
Display = display;
Width = width;
Height = height;
var exe = executable ?? FindExecutable() ?? throw new FileNotFoundException("Xvfb non è installato.");
var effectiveClock = clock ?? new SystemClock();
_supervisor = new SupervisedProcess(
"Xvfb",
() => BuildStartInfo(exe),
(process, ct) => WaitForSocketAsync(process, effectiveClock, ct),
effectiveClock,
log,
restart);
}
public string Display { get; }
public int Width { get; }
public int Height { get; }
public SupervisedState State => _supervisor.State;
public int? ProcessId => _supervisor.ProcessId;
/// Path of the X socket that appears when the display is ready.
public string SocketPath => $"/tmp/.X11-unix/X{_displayNumber.ToString(CultureInfo.InvariantCulture)}";
public event EventHandler? Restarted
{
add => _supervisor.Restarted += value;
remove => _supervisor.Restarted -= value;
}
public Task StartAsync(CancellationToken ct)
{
if (!OperatingSystem.IsLinux())
{
throw new PlatformNotSupportedException("Xvfb serve solo su Linux (Docker).");
}
if (IsLockHeldByLiveProcess())
{
throw new InvalidOperationException($"Il display {Display} è già in uso da un altro processo.");
}
return _supervisor.StartAsync(ct);
}
public Task StopAsync() => _supervisor.StopAsync(TimeSpan.FromSeconds(3));
public ValueTask DisposeAsync() => _supervisor.DisposeAsync();
/// Finds Xvfb in PATH or in the usual places.
public static string? FindExecutable() => ExecutableSearch.Find(["Xvfb"], ["/usr/bin/Xvfb", "/usr/local/bin/Xvfb"]);
/// First display number in [, ] with neither socket nor lock file.
public static string? FindFreeDisplay(int from = 90, int to = 199)
{
for (var n = from; n <= to; n++)
{
var id = n.ToString(CultureInfo.InvariantCulture);
if (!File.Exists($"/tmp/.X11-unix/X{id}") && !File.Exists($"/tmp/.X{id}-lock"))
{
return $":{id}";
}
}
return null;
}
/// The start of Xvfb, without Febe's secrets in its environment ().
internal ProcessStartInfo BuildStartInfo(string exe)
{
var info = new ProcessStartInfo(exe);
info.ArgumentList.Add(Display);
info.ArgumentList.Add("-screen");
info.ArgumentList.Add("0");
info.ArgumentList.Add(string.Create(CultureInfo.InvariantCulture, $"{Width}x{Height}x24"));
info.ArgumentList.Add("-nolisten");
info.ArgumentList.Add("tcp");
info.ArgumentList.Add("-noreset");
return info.WithoutSecrets();
}
private async Task WaitForSocketAsync(Process process, IClock clock, CancellationToken ct)
{
var deadline = clock.Now + TimeSpan.FromSeconds(10);
while (!File.Exists(SocketPath) || LockOwner() != process.Id)
{
if (process.HasExited)
{
throw new InvalidOperationException($"Xvfb si è chiuso all'avvio (codice {process.ExitCode}). {_supervisor.StderrTail()}");
}
if (clock.Now >= deadline)
{
throw new TimeoutException($"Il display {Display} non è pronto dopo 10 secondi.");
}
await clock.Delay(TimeSpan.FromMilliseconds(50), ct).ConfigureAwait(false);
}
}
/// Process id written in the X lock file, or null.
private int? LockOwner()
{
var lockFile = $"/tmp/.X{_displayNumber.ToString(CultureInfo.InvariantCulture)}-lock";
try
{
return File.Exists(lockFile) && int.TryParse(File.ReadAllText(lockFile).Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out var pid)
? pid
: null;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
return null;
}
}
private bool IsLockHeldByLiveProcess()
{
if (LockOwner() is not { } pid)
{
return false;
}
try
{
using var holder = Process.GetProcessById(pid);
return !holder.HasExited;
}
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException)
{
return false;
}
}
private static int ParseDisplay(string display)
{
if (string.IsNullOrEmpty(display) || display[0] != ':'
|| !int.TryParse(display.AsSpan(1).ToString().Split('.')[0], NumberStyles.None, CultureInfo.InvariantCulture, out var number))
{
throw new ArgumentException($"Display «{display}» non valido: si scrive come «:99».", nameof(display));
}
return number;
}
}
/// Looks for executables in PATH and in a few known places.
internal static class ExecutableSearch
{
public static string? Find(IEnumerable names, IEnumerable knownPaths)
{
var path = Environment.GetEnvironmentVariable("PATH") ?? string.Empty;
foreach (var name in names)
{
foreach (var dir in path.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries))
{
var candidate = Path.Combine(dir, name);
if (File.Exists(candidate))
{
return candidate;
}
if (OperatingSystem.IsWindows() && File.Exists(candidate + ".exe"))
{
return candidate + ".exe";
}
}
}
return knownPaths.FirstOrDefault(File.Exists);
}
}