using System.Globalization; using System.Net; using System.Text.Json; using System.Text.Json.Serialization; using Titano.Data; using Titano.Server.Hosting; namespace Titano.Server.Configuration; public enum TlsMode { /// Self-signed certificate generated at first start (stored under /data/tls). Auto, /// Certificate and key from PEM files. Pem, /// Plain HTTP behind a TLS-terminating reverse proxy. Proxy, } public enum DatabaseKind { Postgres, Sqlite, } /// /// Server configuration (BRIEF §14.9): environment variables override /data/server.json, which overrides defaults. /// Settings applied from the environment are listed in ; the admin panel cannot change them. /// public sealed class ServerOptions { /// Environment variable → setting it fixes, and how its text is applied. private static readonly (string Variable, string Setting, Action Apply)[] Variables = [ ("TITANO_SERVER_NAME", nameof(ServerName), (o, v) => o.ServerName = v), ("TITANO_ARCHIVE_PATH", nameof(ArchivePath), (o, v) => o.ArchivePath = v), ("TITANO_ADMIN_USER", nameof(AdminUser), (o, v) => o.AdminUser = v), ("TITANO_ADMIN_PASSWORD", nameof(AdminPassword), (o, v) => o.AdminPassword = v), ("TITANO_DB", nameof(Database), (o, v) => o.ApplyDatabase(v)), ("TITANO_DB_HOST", nameof(DbHost), (o, v) => o.DbHost = v), ("TITANO_DB_PORT", nameof(DbPort), (o, v) => o.DbPort = Int("TITANO_DB_PORT", v)), ("TITANO_DB_NAME", nameof(DbName), (o, v) => o.DbName = v), ("TITANO_DB_USER", nameof(DbUser), (o, v) => o.DbUser = v), ("TITANO_DB_PASSWORD", nameof(DbPassword), (o, v) => o.DbPassword = v), ("TITANO_DB_SSLMODE", nameof(DbSslMode), (o, v) => o.DbSslMode = v), ("TITANO_HTTP_PORT", nameof(HttpPort), (o, v) => o.HttpPort = Int("TITANO_HTTP_PORT", v)), ("TITANO_HTTPS_PORT", nameof(HttpsPort), (o, v) => o.HttpsPort = Int("TITANO_HTTPS_PORT", v)), ("TITANO_PUBLIC_HTTP_PORT", nameof(PublicHttpPort), (o, v) => o.PublicHttpPort = Int("TITANO_PUBLIC_HTTP_PORT", v)), ("TITANO_PUBLIC_HTTPS_PORT", nameof(PublicHttpsPort), (o, v) => o.PublicHttpsPort = Int("TITANO_PUBLIC_HTTPS_PORT", v)), ("TITANO_TLS_MODE", nameof(TlsMode), (o, v) => o.TlsMode = Enum.Parse(v, ignoreCase: true)), ("TITANO_TLS_CERT", nameof(TlsCert), (o, v) => o.TlsCert = v), ("TITANO_TLS_KEY", nameof(TlsKey), (o, v) => o.TlsKey = v), ("TITANO_TRUSTED_PROXIES", nameof(TrustedProxies), (o, v) => o.TrustedProxies = v), ("TITANO_LANG", nameof(Language), (o, v) => o.Language = v), ("TITANO_WORKERS", nameof(Workers), (o, v) => o.Workers = Math.Max(1, Int("TITANO_WORKERS", v))), ("TITANO_DISCOVERY", nameof(Discovery), (o, v) => o.Discovery = bool.Parse(v)), ("TITANO_LOG_LEVEL", nameof(LogLevel), (o, v) => o.LogLevel = Enum.Parse(v, ignoreCase: true)), ]; /// /// Reverse proxies whose X-Forwarded-* headers count in TLS mode proxy when none are configured: loopback only. /// A home network's machines reach the HTTP port directly from private addresses (also through Docker's port /// publishing, which keeps the client's address), so trusting a private network would let them pick their own /// address again; a proxy in another container or on another machine is listed by its address or network. /// public const string DefaultTrustedProxies = "127.0.0.0/8, ::1/128"; /// The environment variables the server reads (--help lists them all). public static IEnumerable EnvironmentVariables => Variables.Select(v => v.Variable).Prepend("TITANO_DATA_PATH"); public string ServerName { get; set; } = "Titano Server"; public string ArchivePath { get; set; } = OperatingSystem.IsWindows() ? @"C:\TitanoArchive" : "/archive"; public string DataPath { get; set; } = OperatingSystem.IsWindows() ? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Titano Server") : "/data"; public string? AdminUser { get; set; } public string? AdminPassword { get; set; } public DatabaseKind Database { get; set; } = OperatingSystem.IsWindows() ? DatabaseKind.Sqlite : DatabaseKind.Postgres; /// Complete connection string (from TITANO_DB when it holds one); overrides the Db* parts. public string? DbConnectionString { get; set; } public string DbHost { get; set; } = "postgres"; public int DbPort { get; set; } = 5432; public string DbName { get; set; } = "titano"; public string DbUser { get; set; } = "titano"; public string? DbPassword { get; set; } public string DbSslMode { get; set; } = "prefer"; public int HttpPort { get; set; } = 8080; public int HttpsPort { get; set; } = 8443; /// /// Port clients reach the HTTP listener on, when it differs from (a container port published /// as another host port); advertised by LAN discovery. Null: . /// public int? PublicHttpPort { get; set; } /// Port clients reach the HTTPS listener on (admin redirect, LAN discovery). Null: . public int? PublicHttpsPort { get; set; } public TlsMode TlsMode { get; set; } = TlsMode.Auto; public string? TlsCert { get; set; } public string? TlsKey { get; set; } /// /// Addresses or networks (CIDR), separated by commas or spaces, of the reverse proxies trusted in TLS mode proxy. /// Forwarded headers from any other peer are ignored, so a client that reaches the HTTP port directly cannot choose /// the address the sign-in rate limit and the audit log see. /// public string TrustedProxies { get; set; } = DefaultTrustedProxies; public string Language { get; set; } = "en"; public int Workers { get; set; } = Math.Max(1, Environment.ProcessorCount / 2); public bool Discovery { get; set; } = true; /// Least severe level written to the console and the log files. public LogLevel LogLevel { get; set; } = LogLevel.Information; public long MaxUploadBytes { get; set; } = 2L * 1024 * 1024 * 1024; public int ChunkSizeBytes { get; set; } = 8 * 1024 * 1024; public int JobHistoryDays { get; set; } = 90; public int TokenLifetimeDays { get; set; } = 30; /// Uploads untouched for this long are abandoned: their partial files are deleted. public int UploadRetentionHours { get; set; } = 48; /// Sign-in attempts accepted per minute and client address (BRIEF §14.2: 5). public int LoginAttemptsPerMinute { get; set; } = 5; /// Consecutive failed sign-ins that lock an account name for . public int LockoutThreshold { get; set; } = 10; public int LockoutMinutes { get; set; } = 15; /// A render node silent for this long is offline and its jobs go back to the queue. public int NodeTimeoutSeconds { get; set; } = 90; /// Chunk uploads one user may run at the same time; more are answered 429. public int ConcurrentChunksPerUser { get; set; } = 8; /// Settings fixed by environment variables (names of the properties above). [JsonIgnore] public IReadOnlyCollection Locked { get; private set; } = []; [JsonIgnore] public string LogPath => Path.Combine(DataPath, "logs"); [JsonIgnore] public string TlsPath => Path.Combine(DataPath, "tls"); [JsonIgnore] public string UploadsPath => Path.Combine(DataPath, "uploads"); [JsonIgnore] public string SettingsFile => Path.Combine(DataPath, "server.json"); /// Verified uploads wait here, on the archive volume, until the archive ingest moves them into place. [JsonIgnore] public string StagingPath => Path.Combine(ArchivePath, ".titano", "staging"); /// Deleted sequences are moved here (never erased by the server). [JsonIgnore] public string TrashPath => Path.Combine(ArchivePath, ".titano", "trash"); /// Loads {DataPath}/server.json (if present) then applies TITANO_* environment variables. public static ServerOptions Load(IReadOnlyDictionary? environment = null) { var env = environment ?? ReadEnvironment(); string? Env(string name) => env.TryGetValue(name, out var v) && !string.IsNullOrWhiteSpace(v) ? v : null; var dataPath = Env("TITANO_DATA_PATH") ?? new ServerOptions().DataPath; var options = new ServerOptions(); var file = Path.Combine(dataPath, "server.json"); if (File.Exists(file)) { try { // Its owner is checked first: a file another user planted would choose the archive, database and TLS key. options = JsonSerializer.Deserialize(DataFolderAccess.ReadTrustedText(file), ServerOptionsJson.Default.ServerOptions) ?? options; } catch (JsonException ex) { throw new InvalidOperationException($"{file} is not valid JSON: {ex.Message}", ex); } } options.DataPath = dataPath; var locked = new List(); foreach (var (variable, setting, apply) in Variables) { if (Env(variable) is not { } value) continue; try { apply(options, value); } catch (Exception ex) when (ex is FormatException or ArgumentException) { throw new InvalidOperationException($"{variable} has an invalid value.", ex); } locked.Add(setting); } options.Locked = locked; options.Validate(); return options; } /// The database to open: , the SQLite file in the data folder, or PostgreSQL from the parts. public DatabaseOptions ToDatabaseOptions() { if (DbConnectionString is { Length: > 0 } cs) return DatabaseOptions.Parse(cs); if (Database == DatabaseKind.Sqlite) return DatabaseOptions.Sqlite(Path.Combine(DataPath, "titano.db")); var builder = new System.Text.StringBuilder() .Append("Host=").Append(Quote(DbHost)) .Append(";Port=").Append(DbPort.ToString(CultureInfo.InvariantCulture)) .Append(";Database=").Append(Quote(DbName)) .Append(";Username=").Append(Quote(DbUser)) .Append(";SslMode=").Append(Quote(DbSslMode)); if (DbPassword is not null) builder.Append(";Password=").Append(Quote(DbPassword)); return DatabaseOptions.Postgres(builder.ToString()); } public void Validate() { if (!OperatingSystem.IsWindows() && Database == DatabaseKind.Sqlite) throw new InvalidOperationException("TITANO_DB=sqlite is supported on Windows only; use postgres (BRIEF §14.9)."); if (TlsMode == TlsMode.Pem && (string.IsNullOrEmpty(TlsCert) || string.IsNullOrEmpty(TlsKey))) throw new InvalidOperationException("TITANO_TLS_MODE=pem requires TITANO_TLS_CERT and TITANO_TLS_KEY."); // Port 0 asks the OS for a free port (used by the in-process test host). if (HttpPort is < 0 or > 65535 || HttpsPort is < 0 or > 65535) throw new InvalidOperationException("Ports must be between 0 and 65535."); if (PublicHttpPort is < 1 or > 65535 || PublicHttpsPort is < 1 or > 65535) throw new InvalidOperationException("TITANO_PUBLIC_HTTP_PORT and TITANO_PUBLIC_HTTPS_PORT must be between 1 and 65535."); try { TrustedProxyNetworks(); } catch (FormatException ex) { throw new InvalidOperationException($"TITANO_TRUSTED_PROXIES must list IP addresses (such as 172.30.0.10) or networks in CIDR form: {ex.Message}", ex); } if (ChunkSizeBytes is < 64 * 1024 or > 64 * 1024 * 1024) throw new InvalidOperationException("The chunk size must be between 64 KiB and 64 MiB."); if (MaxUploadBytes < 1 || TokenLifetimeDays < 1 || JobHistoryDays < 1 || UploadRetentionHours < 1) throw new InvalidOperationException("Upload size, token lifetime, job history and upload retention must be positive."); } /// The parsed ; a single address is a network of one. /// An entry is neither an IP address nor a network in CIDR notation. public IReadOnlyList TrustedProxyNetworks() { var networks = new List(); foreach (var entry in TrustedProxies.Split([',', ';', ' ', '\t'], StringSplitOptions.RemoveEmptyEntries)) { if (IPNetwork.TryParse(entry, out var network)) networks.Add(network); else if (!entry.Contains('/', StringComparison.Ordinal) && IPAddress.TryParse(entry, out var address) && (address.AddressFamily != System.Net.Sockets.AddressFamily.InterNetworkV6 || address.ScopeId == 0)) networks.Add(new IPNetwork(address, address.GetAddressBytes().Length * 8)); else throw new FormatException($"'{entry}' is neither an address nor a network."); } return networks; } /// TITANO_DB is postgres, sqlite or a complete connection string (Host=… / Data Source=…). private void ApplyDatabase(string value) { if (value.Contains('=', StringComparison.Ordinal)) { DbConnectionString = value; Database = DatabaseOptions.Parse(value).Dialect == Dialect.Postgres ? DatabaseKind.Postgres : DatabaseKind.Sqlite; return; } Database = Enum.Parse(value, ignoreCase: true); } private static int Int(string variable, string value) => int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var n) ? n : throw new FormatException($"{variable} must be a number."); private static string Quote(string value) => "'" + value.Replace("'", "''", StringComparison.Ordinal) + "'"; private static Dictionary ReadEnvironment() { // Variables may differ only by case on Linux (no_proxy/NO_PROXY); the last one wins. var result = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (System.Collections.DictionaryEntry e in Environment.GetEnvironmentVariables()) result[(string)e.Key] = (string?)e.Value; return result; } } [JsonSourceGenerationOptions(WriteIndented = true, UseStringEnumConverter = true, PropertyNameCaseInsensitive = true)] [JsonSerializable(typeof(ServerOptions))] internal sealed partial class ServerOptionsJson : JsonSerializerContext;