Il client del sito ha bisogno della sessione del browser di Febe: ora la copia c'è, cifrata e dietro un interruttore, senza cambiare nulla di predefinito. - Opzione «raccolta» (pagine predefinita, richieste): solo con «richieste» e almeno un'operazione configurata si costruiscono sessione salvata, client del sito e copia. Con Instagram nulla cambia: le dieci operazioni restano non configurate (mancano __spin_*, __req, __s, __dyn, __csr e altri). - Cookie con dominio, percorso, solo-host, Secure, HttpOnly e scadenza, mandati solo dove il browser li manderebbe (RFC 6265). - Sezione «page» del catalogo: dove la pagina tiene ogni valore; nuovi campi rev, hs, hsi, dpr, ccg, comet_req, entry_nonce. Il caricatore rifiuta un'operazione configurata con un valore di sessione senza fonte nella pagina. - Dati/sessione/sessione.json: DPAPI su Windows, AES-256-GCM in Docker (chiave da FEBE_CHIAVE_SESSIONE o chiave.bin), scrittura atomica, file illeggibile = nessuna sessione. «Scollega» la cancella; chiave.bin resta. - Copia a «Ho finito» con Network.getCookies e una sola Runtime.evaluate in sola lettura, solo da una pagina del sito e finché dura il permesso di guida. - FEBE_PASSWORD e FEBE_CHIAVE_SESSIONE non passano a Chromium, Xvfb, ffmpeg. - Sito di prova: csrftoken, cookie limitato a /api/, registro di moduli suo. - Revisione su tre lenti: 11 punti confermati, tutti corretti. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
207 lines
7.0 KiB
C#
207 lines
7.0 KiB
C#
using System.Diagnostics;
|
|
using System.Globalization;
|
|
using Febe.Browser.Diagnostics;
|
|
using Febe.Core.Abstractions;
|
|
using Febe.Core.Security;
|
|
|
|
namespace Febe.Browser.Hosting;
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
public sealed class XvfbProcess : IAsyncDisposable
|
|
{
|
|
private readonly SupervisedProcess _supervisor;
|
|
private readonly int _displayNumber;
|
|
|
|
/// <param name="display">Display name, e.g. «:99».</param>
|
|
/// <param name="width">Screen width: at least the browser window width.</param>
|
|
/// <param name="height">Screen height: at least the browser window height.</param>
|
|
/// <param name="executable">Xvfb executable; null searches PATH.</param>
|
|
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;
|
|
|
|
/// <summary>Path of the X socket that appears when the display is ready.</summary>
|
|
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();
|
|
|
|
/// <summary>Finds Xvfb in PATH or in the usual places.</summary>
|
|
public static string? FindExecutable() => ExecutableSearch.Find(["Xvfb"], ["/usr/bin/Xvfb", "/usr/local/bin/Xvfb"]);
|
|
|
|
/// <summary>First display number in [<paramref name="from"/>, <paramref name="to"/>] with neither socket nor lock file.</summary>
|
|
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;
|
|
}
|
|
|
|
/// <summary>The start of Xvfb, without Febe's secrets in its environment (<see cref="ChildProcessEnvironment"/>).</summary>
|
|
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);
|
|
}
|
|
}
|
|
|
|
/// <summary>Process id written in the X lock file, or null.</summary>
|
|
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;
|
|
}
|
|
}
|
|
|
|
/// <summary>Looks for executables in PATH and in a few known places.</summary>
|
|
internal static class ExecutableSearch
|
|
{
|
|
public static string? Find(IEnumerable<string> names, IEnumerable<string> 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);
|
|
}
|
|
}
|