using System.Globalization;
using System.Net;
using Febe.Browser.Hosting;
using Febe.Browser.Recipes;
using Febe.Web;
namespace Febe.Server;
///
/// 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).
///
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";
/// FEBE_PASSWORD: the interface password. Mandatory; never logged or shown.
public string? Password { get; init; }
/// Where Kestrel listens: every address in Docker (the port is published), 127.0.0.1 with --ascolta.
public IPAddress ListenAddress { get; init; } = IPAddress.Any;
/// FEBE_PORTA, 8480 by default.
public int Port { get; init; } = FebeListen.DefaultPort;
/// TZ, Europe/Rome by default: the clock of the engine, file names, and the browser's time zone.
public string ZoneId { get; init; } = DefaultZone;
public TimeZoneInfo Zone { get; init; } = FindZone(DefaultZone) ?? TimeZoneInfo.Utc;
/// LANG, it_IT.UTF-8 by default: the browser's language comes from it (spec §6.1).
public string Language { get; init; } = DefaultLanguage;
/// Data folder: database, browser profile, thumbnails, backups, log (/dati).
public string DataFolder { get; init; } = "/dati";
/// Library folder (/libreria).
public string LibraryFolder { get; init; } = "/libreria";
/// Import sources, read-only (/importa).
public string ImportFolder { get; init; } = "/importa";
/// FEBE_HOST: names the interface is reached with (comma separated). Empty: any name.
public IReadOnlyList Hosts { get; init; } = [];
/// FEBE_PROXY_FIDATO=1: behind an HTTPS reverse proxy, X-Forwarded-Host counts for the Origin check.
public bool TrustForwardedHost { get; init; }
/// FEBE_SENZA_SANDBOX=1: Chromium with --no-sandbox (the compromise of S5, written in docs/docker.md).
public bool NoSandbox { get; init; }
/// FEBE_CHROMIUM: Chromium executable (default: Debian's chromium from PATH).
public string? ChromiumPath { get; init; }
/// FEBE_PORTA_DEBUG: the fixed DevTools port, on 127.0.0.1 only and never published (spec §6.1).
public int DebugPort { get; init; } = DefaultDebugPort;
/// FEBE_DISPLAY: the Xvfb display (:99).
public string Display { get; init; } = DefaultDisplay;
/// Size of the browser window, always the same (spec §6.1); Xvfb's screen has the same size.
public int WindowWidth { get; init; } = 1280;
public int WindowHeight { get; init; } = 900;
/// Development: the local test site (tools/Febe.SitoDiProva) instead of Instagram.
public Uri? TestSite { get; init; }
/// Development: the «CDN» of the test site (default: 127.0.0.2, site port + 1, as the tool starts it).
public Uri? TestCdn { get; init; }
/// Development, test site only: opens the site once at start-up so its session cookie exists, as after a login.
public bool TestSiteAutoLogin { get; init; }
/// Development: the first session comes after this delay instead of 2–10 minutes.
public TimeSpan? FirstSessionDelay { get; init; }
/// FEBE_INTERFACCIA: serve the interface from this folder (development).
public string? InterfaceFolder { get; init; }
/// Warnings found while reading the configuration (unknown time zone...), for the log.
public IReadOnlyList Warnings { get; init; } = [];
/// The site the browser works on: Instagram, or the local test site in development.
public CollectionSite Site => TestSite is { } site
? CollectionSite.TestSite(site.Authority, (TestCdn ?? DefaultCdn(site)).Authority)
: CollectionSite.Instagram;
///
/// 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).
///
public string LoginUrl => TestSite is { } site ? new Uri(site, "/benvenuto").AbsoluteUri : "https://www.instagram.com/accounts/login/";
/// The interface options of the Docker edition.
public FebeWebOptions WebOptions() => new()
{
Edition = FebeEdition.Docker,
Access = AccessMode.Password,
Password = string.IsNullOrEmpty(Password) ? null : Password,
AllowedHosts = AllowedHostList(),
TrustForwardedHost = TrustForwardedHost,
InterfaceFolder = InterfaceFolder,
};
///
/// 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).
///
public IReadOnlyList AllowedHostList()
{
if (Hosts.Count == 0)
{
return [];
}
var list = new List();
foreach (var host in Hosts.Concat(["127.0.0.1", "localhost", "[::1]"]))
{
list.Add(host);
list.Add(host + ":*");
}
return list.Distinct(StringComparer.OrdinalIgnoreCase).ToList();
}
///
/// Reads the configuration. gives environment variables (tests pass their own).
/// Returns false with an Italian for a wrong command line.
///
public static bool TryParse(string[] args, Func environment, out ServerOptions options, out string problem)
{
ArgumentNullException.ThrowIfNull(args);
ArgumentNullException.ThrowIfNull(environment);
options = new ServerOptions();
problem = string.Empty;
var warnings = new List();
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;
}
/// The time zone named by TZ, or null when unknown.
public static TimeZoneInfo? FindZone(string id) =>
TimeZoneInfo.TryFindSystemTimeZoneById(id, out var zone) ? zone : null;
/// The environment of Chromium: LANG and TZ (defaults when unset), a home of its own, and no proxy (rule 2).
public IReadOnlyDictionary BrowserEnvironment(string home) => new Dictionary
{
["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,
};
/// How the browser is started (spec §6.1, §11).
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 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;
/// The test site must be on this computer: the switch can never point the browser elsewhere.
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;
}
}