874 lines
31 KiB
C#
874 lines
31 KiB
C#
using System.Diagnostics;
|
|
using System.IO.Compression;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
|
|
namespace NginxMan;
|
|
|
|
public sealed class NginxManager
|
|
{
|
|
private const string ConfigFileName = "nginxman.json";
|
|
private const string BackupTemplateEntryName = "www/index.template.html";
|
|
private const string ServiceCardsToken = "{{NGINXMAN_SERVICE_CARDS}}";
|
|
private const long MaximumConfigImportBytes = 5 * 1024 * 1024;
|
|
private const long MaximumTemplateImportBytes = 10 * 1024 * 1024;
|
|
private const int MaximumManagedBackups = 10;
|
|
|
|
private readonly string _baseDirectory;
|
|
private readonly string _dataDirectory;
|
|
private readonly string _configPath;
|
|
private NginxManagerConfig _config;
|
|
|
|
private static readonly JsonSerializerOptions JsonOptions = new()
|
|
{
|
|
WriteIndented = true,
|
|
PropertyNameCaseInsensitive = true,
|
|
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
|
|
};
|
|
|
|
private static readonly UTF8Encoding Utf8WithoutBom = new(false);
|
|
|
|
public NginxManager(string baseDirectory)
|
|
{
|
|
_baseDirectory = baseDirectory;
|
|
_dataDirectory = Path.Combine(_baseDirectory, "data");
|
|
Directory.CreateDirectory(_dataDirectory);
|
|
Directory.CreateDirectory(BackupDirectory);
|
|
WebPortal.ExtractTo(_dataDirectory);
|
|
_configPath = Path.Combine(_dataDirectory, ConfigFileName);
|
|
MoveLegacyConfigIfNeeded();
|
|
_config = LoadOrCreateConfig();
|
|
ConfigureBundledNginx();
|
|
SaveConfig();
|
|
RenderConfig();
|
|
}
|
|
|
|
public string ConfigPath => _configPath;
|
|
|
|
public string BackupDirectory => Path.Combine(_dataDirectory, "backups");
|
|
|
|
public IReadOnlyList<RouteEntry> Routes => _config.Routes.AsReadOnly();
|
|
|
|
public string PortalDomain => _config.PortalDomain;
|
|
|
|
public int PortalListenPort => _config.PortalListenPort;
|
|
|
|
public PortalContentSettings PortalContent => new(
|
|
_config.PortalSiteName,
|
|
_config.PortalHeadline,
|
|
_config.PortalIntroduction);
|
|
|
|
public string NginxExePath
|
|
{
|
|
get => _config.NginxExePath;
|
|
set
|
|
{
|
|
_config.NginxExePath = value;
|
|
SaveConfig();
|
|
}
|
|
}
|
|
|
|
public bool IsRunning => Process.GetProcessesByName("nginx").Any();
|
|
|
|
public void UpdatePortalSettings(string domain, int listenPort)
|
|
{
|
|
domain = NormalizeOptionalDomain(domain);
|
|
listenPort = NormalizePort(listenPort, "入口页监听端口");
|
|
|
|
if (!string.IsNullOrWhiteSpace(domain) &&
|
|
_config.Routes.Any(route =>
|
|
route.Domain.Equals(domain, StringComparison.OrdinalIgnoreCase) &&
|
|
route.ListenPort == listenPort))
|
|
{
|
|
throw new InvalidOperationException("入口页域名和端口不能与现有代理映射完全相同。");
|
|
}
|
|
|
|
_config.PortalDomain = domain;
|
|
_config.PortalListenPort = listenPort;
|
|
SaveConfig();
|
|
}
|
|
|
|
public void UpdatePortalContent(string siteName, string headline, string introduction)
|
|
{
|
|
_config.PortalSiteName = NormalizeLimitedText(siteName, "入口页名称", 80);
|
|
_config.PortalHeadline = NormalizeLimitedText(headline, "主页标题", 120);
|
|
_config.PortalIntroduction = NormalizeLimitedText(introduction, "主页简介", 500);
|
|
SaveConfig();
|
|
}
|
|
|
|
public void AddOrUpdateRoute(
|
|
string domain,
|
|
string upstream,
|
|
int listenPort,
|
|
string websiteName,
|
|
string description)
|
|
{
|
|
domain = NormalizeDomain(domain);
|
|
upstream = NormalizeUpstream(upstream);
|
|
listenPort = NormalizePort(listenPort, "监听端口");
|
|
websiteName = NormalizeRequiredText(websiteName, "网站名称");
|
|
description = NormalizeRequiredText(description, "网站简介");
|
|
EnsureRouteDoesNotConflictWithPortal(domain, listenPort);
|
|
|
|
var index = _config.Routes.FindIndex(x => x.Domain.Equals(domain, StringComparison.OrdinalIgnoreCase));
|
|
if (index >= 0)
|
|
{
|
|
_config.Routes[index] = new RouteEntry
|
|
{
|
|
Domain = domain,
|
|
Upstream = upstream,
|
|
ListenPort = listenPort,
|
|
WebsiteName = websiteName,
|
|
Description = description
|
|
};
|
|
}
|
|
else
|
|
{
|
|
_config.Routes.Add(new RouteEntry
|
|
{
|
|
Domain = domain,
|
|
Upstream = upstream,
|
|
ListenPort = listenPort,
|
|
WebsiteName = websiteName,
|
|
Description = description
|
|
});
|
|
}
|
|
|
|
SaveConfig();
|
|
}
|
|
|
|
public bool UpdateRoute(
|
|
string oldDomain,
|
|
string newDomain,
|
|
string upstream,
|
|
int listenPort,
|
|
string websiteName,
|
|
string description)
|
|
{
|
|
oldDomain = NormalizeDomain(oldDomain);
|
|
newDomain = NormalizeDomain(newDomain);
|
|
upstream = NormalizeUpstream(upstream);
|
|
listenPort = NormalizePort(listenPort, "监听端口");
|
|
websiteName = NormalizeRequiredText(websiteName, "网站名称");
|
|
description = NormalizeRequiredText(description, "网站简介");
|
|
EnsureRouteDoesNotConflictWithPortal(newDomain, listenPort);
|
|
|
|
var oldIndex = _config.Routes.FindIndex(x => x.Domain.Equals(oldDomain, StringComparison.OrdinalIgnoreCase));
|
|
if (oldIndex < 0)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
if (!oldDomain.Equals(newDomain, StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
var duplicate = _config.Routes.Any(
|
|
x => x.Domain.Equals(newDomain, StringComparison.OrdinalIgnoreCase) &&
|
|
!x.Domain.Equals(oldDomain, StringComparison.OrdinalIgnoreCase));
|
|
if (duplicate)
|
|
{
|
|
throw new InvalidOperationException($"域名已存在: {newDomain}");
|
|
}
|
|
}
|
|
|
|
_config.Routes[oldIndex] = new RouteEntry
|
|
{
|
|
Domain = newDomain,
|
|
Upstream = upstream,
|
|
ListenPort = listenPort,
|
|
WebsiteName = websiteName,
|
|
Description = description
|
|
};
|
|
|
|
SaveConfig();
|
|
return true;
|
|
}
|
|
|
|
public bool RemoveRoute(string domain)
|
|
{
|
|
domain = NormalizeDomain(domain);
|
|
var removed = _config.Routes.RemoveAll(x => x.Domain.Equals(domain, StringComparison.OrdinalIgnoreCase));
|
|
if (removed <= 0)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
SaveConfig();
|
|
return true;
|
|
}
|
|
|
|
public string RenderConfig()
|
|
{
|
|
var confPath = ResolvePath(_config.NginxConfPath);
|
|
EnsureDirectory(Path.GetDirectoryName(confPath));
|
|
|
|
var accessLog = ResolvePath(_config.AccessLogPath);
|
|
var errorLog = ResolvePath(_config.ErrorLogPath);
|
|
EnsureDirectory(Path.GetDirectoryName(accessLog));
|
|
EnsureDirectory(Path.GetDirectoryName(errorLog));
|
|
|
|
var content = BuildNginxConfContent(accessLog, errorLog);
|
|
File.WriteAllText(confPath, content, Utf8WithoutBom);
|
|
return confPath;
|
|
}
|
|
|
|
public int Start()
|
|
{
|
|
var conf = RenderConfig();
|
|
return RunNginx($"-c \"{conf}\"", allowPersistentProcess: true);
|
|
}
|
|
|
|
public int Reload()
|
|
{
|
|
var conf = RenderConfig();
|
|
return RunNginx($"-c \"{conf}\" -s reload");
|
|
}
|
|
|
|
public int Stop()
|
|
{
|
|
return RunNginx("-s stop");
|
|
}
|
|
|
|
public void SaveConfig()
|
|
{
|
|
File.WriteAllText(_configPath, JsonSerializer.Serialize(_config, JsonOptions), Encoding.UTF8);
|
|
WebPortal.RenderTo(_dataDirectory, PortalContent, _config.Routes);
|
|
}
|
|
|
|
public string CreateBackup(string destinationPath)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(destinationPath))
|
|
{
|
|
throw new ArgumentException("备份文件路径不能为空。", nameof(destinationPath));
|
|
}
|
|
|
|
SaveConfig();
|
|
var fullDestinationPath = Path.GetFullPath(destinationPath);
|
|
EnsureDirectory(Path.GetDirectoryName(fullDestinationPath));
|
|
var temporaryPath = fullDestinationPath + ".tmp-" + Guid.NewGuid().ToString("N");
|
|
|
|
try
|
|
{
|
|
using (var archive = ZipFile.Open(temporaryPath, ZipArchiveMode.Create))
|
|
{
|
|
archive.CreateEntryFromFile(_configPath, ConfigFileName, CompressionLevel.Optimal);
|
|
|
|
var templatePath = GetTemplatePath();
|
|
if (File.Exists(templatePath))
|
|
{
|
|
archive.CreateEntryFromFile(
|
|
templatePath,
|
|
BackupTemplateEntryName,
|
|
CompressionLevel.Optimal);
|
|
}
|
|
}
|
|
|
|
File.Move(temporaryPath, fullDestinationPath, overwrite: true);
|
|
return fullDestinationPath;
|
|
}
|
|
finally
|
|
{
|
|
if (File.Exists(temporaryPath))
|
|
{
|
|
File.Delete(temporaryPath);
|
|
}
|
|
}
|
|
}
|
|
|
|
public string CreateAutomaticBackup() => CreateTimestampedBackup("auto-close");
|
|
|
|
public string CreateManualBackup() => CreateTimestampedBackup("manual");
|
|
|
|
public BackupImportResult ImportBackup(string sourcePath)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(sourcePath))
|
|
{
|
|
throw new ArgumentException("导入文件路径不能为空。", nameof(sourcePath));
|
|
}
|
|
|
|
var fullSourcePath = Path.GetFullPath(sourcePath);
|
|
if (!File.Exists(fullSourcePath))
|
|
{
|
|
throw new FileNotFoundException("未找到要导入的备份文件。", fullSourcePath);
|
|
}
|
|
|
|
var imported = ReadImportFile(fullSourcePath);
|
|
var importedConfig = DeserializeAndValidateImportedConfig(imported.ConfigJson);
|
|
if (imported.Template is not null &&
|
|
!imported.Template.Contains(ServiceCardsToken, StringComparison.Ordinal))
|
|
{
|
|
throw new InvalidDataException($"备份中的网页模板缺少入口占位符 {ServiceCardsToken}。");
|
|
}
|
|
|
|
var safetyBackupPath = CreateTimestampedBackup("before-import");
|
|
var previousConfig = _config;
|
|
var templatePath = GetTemplatePath();
|
|
var previousTemplate = File.Exists(templatePath)
|
|
? File.ReadAllText(templatePath, Encoding.UTF8)
|
|
: null;
|
|
|
|
try
|
|
{
|
|
_config = importedConfig;
|
|
if (imported.Template is not null)
|
|
{
|
|
EnsureDirectory(Path.GetDirectoryName(templatePath));
|
|
File.WriteAllText(templatePath, imported.Template, Utf8WithoutBom);
|
|
}
|
|
|
|
SaveConfig();
|
|
RenderConfig();
|
|
return new BackupImportResult(
|
|
fullSourcePath,
|
|
safetyBackupPath,
|
|
_config.Routes.Count,
|
|
imported.Template is not null);
|
|
}
|
|
catch (Exception importException)
|
|
{
|
|
_config = previousConfig;
|
|
try
|
|
{
|
|
if (imported.Template is not null)
|
|
{
|
|
if (previousTemplate is null)
|
|
{
|
|
if (File.Exists(templatePath))
|
|
{
|
|
File.Delete(templatePath);
|
|
}
|
|
}
|
|
else
|
|
{
|
|
File.WriteAllText(templatePath, previousTemplate, Utf8WithoutBom);
|
|
}
|
|
}
|
|
|
|
SaveConfig();
|
|
RenderConfig();
|
|
}
|
|
catch
|
|
{
|
|
// The safety backup remains available even if restoring files fails.
|
|
}
|
|
|
|
throw new InvalidOperationException(
|
|
$"导入失败,原配置已保留。导入前备份位于:{safetyBackupPath}",
|
|
importException);
|
|
}
|
|
}
|
|
|
|
private NginxManagerConfig LoadOrCreateConfig()
|
|
{
|
|
if (!File.Exists(_configPath))
|
|
{
|
|
return DefaultConfig();
|
|
}
|
|
|
|
try
|
|
{
|
|
var json = File.ReadAllText(_configPath, Encoding.UTF8);
|
|
var config = JsonSerializer.Deserialize<NginxManagerConfig>(json, JsonOptions);
|
|
if (config is null)
|
|
{
|
|
return DefaultConfig();
|
|
}
|
|
|
|
config.Routes ??= [];
|
|
if (config.PortalListenPort is < 1 or > 65535)
|
|
{
|
|
config.PortalListenPort = 80;
|
|
}
|
|
|
|
NormalizeDataPaths(config);
|
|
NormalizePortalContent(config);
|
|
NormalizeRouteMetadata(config.Routes);
|
|
|
|
return config;
|
|
}
|
|
catch
|
|
{
|
|
return DefaultConfig();
|
|
}
|
|
}
|
|
|
|
private string CreateTimestampedBackup(string category)
|
|
{
|
|
Directory.CreateDirectory(BackupDirectory);
|
|
var fileName = $"{DateTime.Now:yyyyMMdd-HHmmss-fff}-{category}.zip";
|
|
var backupPath = CreateBackup(Path.Combine(BackupDirectory, fileName));
|
|
PruneManagedBackups();
|
|
return backupPath;
|
|
}
|
|
|
|
private void PruneManagedBackups()
|
|
{
|
|
var managedBackups = Directory
|
|
.EnumerateFiles(BackupDirectory, "*.zip", SearchOption.TopDirectoryOnly)
|
|
.Where(path =>
|
|
Path.GetFileName(path).EndsWith("-auto-close.zip", StringComparison.OrdinalIgnoreCase) ||
|
|
Path.GetFileName(path).EndsWith("-before-import.zip", StringComparison.OrdinalIgnoreCase) ||
|
|
Path.GetFileName(path).EndsWith("-manual.zip", StringComparison.OrdinalIgnoreCase))
|
|
.Select(path => new FileInfo(path))
|
|
.OrderByDescending(file => file.LastWriteTimeUtc)
|
|
.ThenByDescending(file => file.Name, StringComparer.OrdinalIgnoreCase)
|
|
.Skip(MaximumManagedBackups)
|
|
.ToArray();
|
|
|
|
foreach (var oldBackup in managedBackups)
|
|
{
|
|
oldBackup.Delete();
|
|
}
|
|
}
|
|
|
|
private ImportedBackup ReadImportFile(string sourcePath)
|
|
{
|
|
var extension = Path.GetExtension(sourcePath);
|
|
if (extension.Equals(".json", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
var fileInfo = new FileInfo(sourcePath);
|
|
if (fileInfo.Length > MaximumConfigImportBytes)
|
|
{
|
|
throw new InvalidDataException("配置文件过大,无法导入。");
|
|
}
|
|
|
|
return new ImportedBackup(File.ReadAllText(sourcePath, Encoding.UTF8), null);
|
|
}
|
|
|
|
if (!extension.Equals(".zip", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
throw new InvalidDataException("仅支持导入 .zip 备份包或 .json 配置文件。");
|
|
}
|
|
|
|
using var archive = ZipFile.OpenRead(sourcePath);
|
|
var configEntries = archive.Entries
|
|
.Where(entry => entry.FullName.Equals(ConfigFileName, StringComparison.OrdinalIgnoreCase))
|
|
.ToArray();
|
|
if (configEntries.Length != 1)
|
|
{
|
|
throw new InvalidDataException($"备份包必须包含且只能包含一个 {ConfigFileName}。");
|
|
}
|
|
|
|
var templateEntries = archive.Entries
|
|
.Where(entry => entry.FullName.Replace('\\', '/').Equals(
|
|
BackupTemplateEntryName,
|
|
StringComparison.OrdinalIgnoreCase))
|
|
.ToArray();
|
|
if (templateEntries.Length > 1)
|
|
{
|
|
throw new InvalidDataException("备份包中包含重复的网页模板。");
|
|
}
|
|
|
|
var configJson = ReadArchiveTextEntry(
|
|
configEntries[0],
|
|
MaximumConfigImportBytes,
|
|
"配置文件");
|
|
var template = templateEntries.Length == 1
|
|
? ReadArchiveTextEntry(templateEntries[0], MaximumTemplateImportBytes, "网页模板")
|
|
: null;
|
|
return new ImportedBackup(configJson, template);
|
|
}
|
|
|
|
private static string ReadArchiveTextEntry(ZipArchiveEntry entry, long maximumBytes, string displayName)
|
|
{
|
|
if (entry.Length > maximumBytes)
|
|
{
|
|
throw new InvalidDataException($"备份包中的{displayName}过大,无法导入。");
|
|
}
|
|
|
|
using var stream = entry.Open();
|
|
using var reader = new StreamReader(stream, Encoding.UTF8, detectEncodingFromByteOrderMarks: true);
|
|
return reader.ReadToEnd();
|
|
}
|
|
|
|
private static NginxManagerConfig DeserializeAndValidateImportedConfig(string json)
|
|
{
|
|
NginxManagerConfig config;
|
|
try
|
|
{
|
|
config = JsonSerializer.Deserialize<NginxManagerConfig>(json, JsonOptions)
|
|
?? throw new InvalidDataException("配置文件内容为空。");
|
|
}
|
|
catch (JsonException ex)
|
|
{
|
|
throw new InvalidDataException("配置文件不是有效的 JSON。", ex);
|
|
}
|
|
|
|
var defaults = DefaultConfig();
|
|
config.NginxExePath = NormalizePathSetting(config.NginxExePath, defaults.NginxExePath);
|
|
config.NginxConfPath = NormalizePathSetting(config.NginxConfPath, defaults.NginxConfPath);
|
|
config.AccessLogPath = NormalizePathSetting(config.AccessLogPath, defaults.AccessLogPath);
|
|
config.ErrorLogPath = NormalizePathSetting(config.ErrorLogPath, defaults.ErrorLogPath);
|
|
config.PortalDomain = NormalizeOptionalDomain(config.PortalDomain ?? string.Empty);
|
|
config.PortalListenPort = NormalizePort(config.PortalListenPort, "入口页监听端口");
|
|
NormalizePortalContent(config);
|
|
config.PortalSiteName = NormalizeLimitedText(config.PortalSiteName, "入口页名称", 80);
|
|
config.PortalHeadline = NormalizeLimitedText(config.PortalHeadline, "主页标题", 120);
|
|
config.PortalIntroduction = NormalizeLimitedText(config.PortalIntroduction, "主页简介", 500);
|
|
config.Routes ??= [];
|
|
NormalizeDataPaths(config);
|
|
NormalizeRouteMetadata(config.Routes);
|
|
|
|
var domains = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
|
foreach (var route in config.Routes)
|
|
{
|
|
if (route is null)
|
|
{
|
|
throw new InvalidDataException("代理映射中包含空记录。");
|
|
}
|
|
|
|
route.Domain = NormalizeDomain(route.Domain);
|
|
route.Upstream = NormalizeUpstream(route.Upstream);
|
|
route.ListenPort = NormalizePort(route.ListenPort, "监听端口");
|
|
route.WebsiteName = NormalizeRequiredText(route.WebsiteName, "网站名称");
|
|
route.Description = NormalizeRequiredText(route.Description, "网站简介");
|
|
|
|
if (!domains.Add(route.Domain))
|
|
{
|
|
throw new InvalidDataException($"配置中存在重复域名:{route.Domain}");
|
|
}
|
|
|
|
if (!string.IsNullOrWhiteSpace(config.PortalDomain) &&
|
|
config.PortalDomain.Equals(route.Domain, StringComparison.OrdinalIgnoreCase) &&
|
|
config.PortalListenPort == route.ListenPort)
|
|
{
|
|
throw new InvalidDataException("入口页不能与代理映射使用相同的域名和监听端口。");
|
|
}
|
|
}
|
|
|
|
return config;
|
|
}
|
|
|
|
private static string NormalizePathSetting(string? path, string fallback) =>
|
|
string.IsNullOrWhiteSpace(path) ? fallback : path.Trim();
|
|
|
|
private string GetTemplatePath() => Path.Combine(_dataDirectory, "www", "index.template.html");
|
|
|
|
private int RunNginx(string arguments, bool allowPersistentProcess = false)
|
|
{
|
|
var exe = ResolvePath(_config.NginxExePath);
|
|
if (!File.Exists(exe))
|
|
{
|
|
throw new FileNotFoundException($"未找到 nginx.exe: {exe}。请先配置正确路径。");
|
|
}
|
|
|
|
var workingDirectory = Path.GetDirectoryName(exe) ?? _baseDirectory;
|
|
Directory.CreateDirectory(Path.Combine(workingDirectory, "logs"));
|
|
Directory.CreateDirectory(Path.Combine(workingDirectory, "temp"));
|
|
using var process = new Process();
|
|
process.StartInfo = new ProcessStartInfo
|
|
{
|
|
FileName = exe,
|
|
Arguments = arguments,
|
|
WorkingDirectory = workingDirectory,
|
|
UseShellExecute = false,
|
|
CreateNoWindow = true
|
|
};
|
|
|
|
process.Start();
|
|
if (!process.WaitForExit(10000))
|
|
{
|
|
if (allowPersistentProcess && IsRunning)
|
|
{
|
|
return 0;
|
|
}
|
|
|
|
throw new TimeoutException("Nginx 执行超时,请检查 data\\logs\\error.log。");
|
|
}
|
|
|
|
if (process.ExitCode != 0)
|
|
{
|
|
throw new InvalidOperationException(
|
|
$"Nginx 执行失败,退出码: {process.ExitCode}\n请检查 data\\logs\\error.log。");
|
|
}
|
|
|
|
return process.ExitCode;
|
|
}
|
|
|
|
private string BuildNginxConfContent(string accessLog, string errorLog)
|
|
{
|
|
var nginxAccessLog = accessLog.Replace('\\', '/');
|
|
var nginxErrorLog = errorLog.Replace('\\', '/');
|
|
var sb = new StringBuilder();
|
|
sb.AppendLine("worker_processes 1;");
|
|
sb.AppendLine("events { worker_connections 1024; }");
|
|
sb.AppendLine("http {");
|
|
sb.AppendLine(" default_type application/octet-stream;");
|
|
sb.AppendLine(" sendfile on;");
|
|
sb.AppendLine($" access_log {nginxAccessLog};");
|
|
sb.AppendLine($" error_log {nginxErrorLog} warn;");
|
|
sb.AppendLine(" keepalive_timeout 65;");
|
|
sb.AppendLine();
|
|
|
|
if (!string.IsNullOrWhiteSpace(_config.PortalDomain))
|
|
{
|
|
var portalRoot = Path.Combine(_dataDirectory, "www").Replace('\\', '/');
|
|
sb.AppendLine(" server {");
|
|
sb.AppendLine($" listen {_config.PortalListenPort} default_server;");
|
|
sb.AppendLine($" server_name {_config.PortalDomain};");
|
|
sb.AppendLine($" root \"{portalRoot}\";");
|
|
sb.AppendLine(" index index.html;");
|
|
sb.AppendLine(" location / {");
|
|
sb.AppendLine(" try_files $uri $uri/ /index.html;");
|
|
sb.AppendLine(" }");
|
|
sb.AppendLine(" }");
|
|
sb.AppendLine();
|
|
}
|
|
|
|
foreach (var route in _config.Routes)
|
|
{
|
|
sb.AppendLine(" server {");
|
|
sb.AppendLine($" listen {route.ListenPort};");
|
|
sb.AppendLine($" server_name {route.Domain};");
|
|
sb.AppendLine(" location / {");
|
|
sb.AppendLine($" proxy_pass {route.Upstream};");
|
|
sb.AppendLine(" proxy_set_header Host $host;");
|
|
sb.AppendLine(" proxy_set_header X-Real-IP $remote_addr;");
|
|
sb.AppendLine(" proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;");
|
|
sb.AppendLine(" proxy_set_header X-Forwarded-Proto $scheme;");
|
|
sb.AppendLine(" }");
|
|
sb.AppendLine(" }");
|
|
sb.AppendLine();
|
|
}
|
|
|
|
sb.AppendLine("}");
|
|
return sb.ToString();
|
|
}
|
|
|
|
private static NginxManagerConfig DefaultConfig() => new()
|
|
{
|
|
NginxExePath = Path.Combine("data", "nginx", "nginx.exe"),
|
|
NginxConfPath = Path.Combine("data", "nginx.conf"),
|
|
AccessLogPath = Path.Combine("data", "logs", "access.log"),
|
|
ErrorLogPath = Path.Combine("data", "logs", "error.log"),
|
|
PortalDomain = string.Empty,
|
|
PortalListenPort = 80,
|
|
PortalSiteName = PortalContentSettings.DefaultSiteName,
|
|
PortalHeadline = PortalContentSettings.DefaultHeadline,
|
|
PortalIntroduction = PortalContentSettings.DefaultIntroduction,
|
|
Routes = []
|
|
};
|
|
|
|
private void ConfigureBundledNginx()
|
|
{
|
|
var bundledExePath = BundledNginx.ExtractTo(_dataDirectory);
|
|
if (bundledExePath is null ||
|
|
!string.Equals(_config.NginxExePath, "nginx.exe", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
return;
|
|
}
|
|
|
|
_config.NginxExePath = Path.GetRelativePath(_baseDirectory, bundledExePath);
|
|
}
|
|
|
|
private void MoveLegacyConfigIfNeeded()
|
|
{
|
|
var legacyConfigPath = Path.Combine(_baseDirectory, ConfigFileName);
|
|
if (!File.Exists(_configPath) && File.Exists(legacyConfigPath))
|
|
{
|
|
File.Move(legacyConfigPath, _configPath);
|
|
}
|
|
}
|
|
|
|
private static void NormalizeDataPaths(NginxManagerConfig config)
|
|
{
|
|
if (IsLegacyPath(config.NginxConfPath, "nginx.conf"))
|
|
{
|
|
config.NginxConfPath = Path.Combine("data", "nginx.conf");
|
|
}
|
|
|
|
if (IsLegacyPath(config.AccessLogPath, Path.Combine("logs", "access.log")))
|
|
{
|
|
config.AccessLogPath = Path.Combine("data", "logs", "access.log");
|
|
}
|
|
|
|
if (IsLegacyPath(config.ErrorLogPath, Path.Combine("logs", "error.log")))
|
|
{
|
|
config.ErrorLogPath = Path.Combine("data", "logs", "error.log");
|
|
}
|
|
}
|
|
|
|
private static void NormalizeRouteMetadata(IEnumerable<RouteEntry> routes)
|
|
{
|
|
foreach (var route in routes)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(route.WebsiteName))
|
|
{
|
|
route.WebsiteName = route.Domain;
|
|
}
|
|
|
|
if (string.IsNullOrWhiteSpace(route.Description))
|
|
{
|
|
route.Description = $"访问 {route.Domain} 服务。";
|
|
}
|
|
}
|
|
}
|
|
|
|
private static void NormalizePortalContent(NginxManagerConfig config)
|
|
{
|
|
config.PortalSiteName = string.IsNullOrWhiteSpace(config.PortalSiteName)
|
|
? PortalContentSettings.DefaultSiteName
|
|
: config.PortalSiteName.Trim();
|
|
config.PortalHeadline = string.IsNullOrWhiteSpace(config.PortalHeadline)
|
|
? PortalContentSettings.DefaultHeadline
|
|
: config.PortalHeadline.Trim();
|
|
config.PortalIntroduction = string.IsNullOrWhiteSpace(config.PortalIntroduction)
|
|
? PortalContentSettings.DefaultIntroduction
|
|
: config.PortalIntroduction.Trim();
|
|
}
|
|
|
|
private static bool IsLegacyPath(string path, string expectedPath) =>
|
|
string.Equals(
|
|
path.Replace('/', '\\'),
|
|
expectedPath.Replace('/', '\\'),
|
|
StringComparison.OrdinalIgnoreCase);
|
|
|
|
private string ResolvePath(string path)
|
|
{
|
|
if (Path.IsPathFullyQualified(path))
|
|
{
|
|
return Path.GetFullPath(path);
|
|
}
|
|
|
|
return Path.GetFullPath(Path.Combine(_baseDirectory, path));
|
|
}
|
|
|
|
private static void EnsureDirectory(string? directory)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(directory))
|
|
{
|
|
return;
|
|
}
|
|
|
|
Directory.CreateDirectory(directory);
|
|
}
|
|
|
|
private static string NormalizeDomain(string domain)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(domain))
|
|
{
|
|
throw new ArgumentException("域名不能为空");
|
|
}
|
|
|
|
domain = domain.Trim().TrimEnd('.');
|
|
if (domain.Contains("://", StringComparison.Ordinal) || domain.Contains('/') ||
|
|
domain.Any(char.IsWhiteSpace) || Uri.CheckHostName(domain) == UriHostNameType.Unknown)
|
|
{
|
|
throw new ArgumentException("请输入有效域名,例如 app.example.com。");
|
|
}
|
|
|
|
return domain;
|
|
}
|
|
|
|
private static string NormalizeOptionalDomain(string domain) =>
|
|
string.IsNullOrWhiteSpace(domain) ? string.Empty : NormalizeDomain(domain);
|
|
|
|
private static int NormalizePort(int port, string fieldName)
|
|
{
|
|
if (port is < 1 or > 65535)
|
|
{
|
|
throw new ArgumentOutOfRangeException(nameof(port), $"{fieldName}必须在 1 到 65535 之间。");
|
|
}
|
|
|
|
return port;
|
|
}
|
|
|
|
private void EnsureRouteDoesNotConflictWithPortal(string domain, int listenPort)
|
|
{
|
|
if (!string.IsNullOrWhiteSpace(_config.PortalDomain) &&
|
|
_config.PortalDomain.Equals(domain, StringComparison.OrdinalIgnoreCase) &&
|
|
_config.PortalListenPort == listenPort)
|
|
{
|
|
throw new InvalidOperationException("代理映射不能与入口页使用相同的域名和监听端口。");
|
|
}
|
|
}
|
|
|
|
private static string NormalizeUpstream(string upstream)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(upstream))
|
|
{
|
|
throw new ArgumentException("上游地址不能为空");
|
|
}
|
|
|
|
upstream = upstream.Trim();
|
|
if (!upstream.StartsWith("http://", StringComparison.OrdinalIgnoreCase) &&
|
|
!upstream.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
upstream = "http://" + upstream;
|
|
}
|
|
|
|
upstream = upstream.TrimEnd('/');
|
|
if (!Uri.TryCreate(upstream, UriKind.Absolute, out var uri) ||
|
|
(uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps) ||
|
|
string.IsNullOrWhiteSpace(uri.Host))
|
|
{
|
|
throw new ArgumentException("上游接口必须是有效的 http:// 或 https:// 地址。");
|
|
}
|
|
|
|
return upstream;
|
|
}
|
|
|
|
private static string NormalizeRequiredText(string value, string fieldName)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(value))
|
|
{
|
|
throw new ArgumentException($"{fieldName}不能为空");
|
|
}
|
|
|
|
return value.Trim();
|
|
}
|
|
|
|
private static string NormalizeLimitedText(string value, string fieldName, int maximumLength)
|
|
{
|
|
var normalized = NormalizeRequiredText(value, fieldName);
|
|
if (normalized.Length > maximumLength)
|
|
{
|
|
throw new ArgumentException($"{fieldName}不能超过 {maximumLength} 个字符。");
|
|
}
|
|
|
|
return normalized;
|
|
}
|
|
}
|
|
|
|
public sealed record BackupImportResult(
|
|
string SourcePath,
|
|
string SafetyBackupPath,
|
|
int RouteCount,
|
|
bool TemplateImported);
|
|
|
|
internal sealed record ImportedBackup(string ConfigJson, string? Template);
|
|
|
|
public sealed class NginxManagerConfig
|
|
{
|
|
public string NginxExePath { get; set; } = "nginx.exe";
|
|
public string NginxConfPath { get; set; } = "nginx.conf";
|
|
public string AccessLogPath { get; set; } = Path.Combine("logs", "access.log");
|
|
public string ErrorLogPath { get; set; } = Path.Combine("logs", "error.log");
|
|
public string PortalDomain { get; set; } = string.Empty;
|
|
public int PortalListenPort { get; set; } = 80;
|
|
public string PortalSiteName { get; set; } = PortalContentSettings.DefaultSiteName;
|
|
public string PortalHeadline { get; set; } = PortalContentSettings.DefaultHeadline;
|
|
public string PortalIntroduction { get; set; } = PortalContentSettings.DefaultIntroduction;
|
|
public List<RouteEntry> Routes { get; set; } = [];
|
|
}
|
|
|
|
public sealed record PortalContentSettings(string SiteName, string Headline, string Introduction)
|
|
{
|
|
public const string DefaultSiteName = "服务导航";
|
|
public const string DefaultHeadline = "欢迎访问统一服务入口";
|
|
public const string DefaultIntroduction = "请选择下方网站或服务,点击卡片即可开始访问。";
|
|
|
|
public static PortalContentSettings Default { get; } = new(
|
|
DefaultSiteName,
|
|
DefaultHeadline,
|
|
DefaultIntroduction);
|
|
}
|
|
|
|
public sealed class RouteEntry
|
|
{
|
|
public string Domain { get; set; } = string.Empty;
|
|
public string Upstream { get; set; } = string.Empty;
|
|
public int ListenPort { get; set; } = 80;
|
|
public string WebsiteName { get; set; } = string.Empty;
|
|
public string Description { get; set; } = string.Empty;
|
|
}
|