mirror of
https://github.com/2dust/v2rayN.git
synced 2026-10-21 20:55:01 +03:00
66dd7da6e6
* feat(web): add headless ServiceLib API and replaceable UI host * build(web): package API without bundled WebUI * ci(web): build and test headless API packages * docs(web): document the headless API and optional WebUI * test(web): verify restore and build before API tests * docs(web): align API release examples with current upstream * test(web): cover creating and editing an empty-URL subscription group Verify the API accepts and persists a subscription whose Url and MoreUrl stay empty, that an edit keeps the empty URL and zero interval, and that ServiceLib is untouched. * fix(web): support per-target prerelease update preferences * fix(web): require management key for non-loopback listeners * ci: reduce development Web API build matrix * fix(web): make native self-update rollback atomic and preserve progress * docs(web): remove self-update E2E report * ci(web): decouple Web releases from Linux Desktop * feat(web): support standalone WebUI clients and rename the API to v2rayN.WebAPI - Resolve every REST, login, setup, download, SSE-ticket and EventSource request through one configurable Backend base per WebUI origin, with a strict exact-match origin allowlist and no wildcard or credential CORS. - Run the origin guard before authentication, and keep first-run setup, instance diagnostics and the hosted-UI CSP same-origin as before. - Rename the project directory, csproj, namespace, executable, lock, build identity and self-update target to v2rayN.WebAPI while retaining V2RAYN_WEB_* settings, WebVersion metadata, webVersion fields and the existing release asset contracts. - Migrate API-owned update preference identifiers and reject legacy v2rayN.Web update packages with a manual reinstall instruction. - Require staged native executables to be Linux ELF images for their RID. - Add CORS, update-identity and setup-security tests, and record the standalone-WebUI audit under v2rayN.WebAPI/STANDALONE-WEBUI-AUDIT.md. * Remove WebUI hosting and configuration coupling from WebAPI * Finish WebAPI cleanup and isolate native self-update worker * Keep WebAPI client documentation implementation-neutral * ci(webapi): verify Windows win-x64 build and startup * fix(webapi): validate keys and unify loopback limits * test(webapi): isolate update smoke from systemd runner * feat(webapi): add Windows x64 release and self-update * fix(webapi): verify release manifest version * ci(webapi): publish web packages through the official release flow * ci(webapi): run the web release inside the release-all workflow * webapi: finish the rename and fix shutdown, terminal launch and help - finish the Web -> WebAPI product rename: workflow files build-WebAPI.yml / release-WebAPI.yml (path filters, reusable call sites, container tag), solution entry, health headers X-v2rayn-WebAPI-*, WebAPI.self-update capability, WebAPI-update-progress.json / WebAPI-update-runtime-state.json, WebAPIData/WebAPI-auth.json with a migration from the legacy locations, and the README compatibility notes - end /api/events when the host starts stopping so Kestrel's graceful stop cannot pin the whole shutdown budget with a client attached; a runtime cleanup that starts after the host budget was exhausted now runs a reduced fresh pass instead of skipping Core stop and shared-state saves entirely - record the interactive launch context for detached children and helpers so systemd markers leaked into a terminal (INVOCATION_ID / JOURNAL_STREAM) no longer force foreground mode or misfire the supervised-deployment key check, self-update gating and lifecycle decisions - add --help / -h with the options and common environment variables in all three launcher locales, and keep help flags out of the host arguments * fix(webapi): retry transient file replacements during native updates Windows antivirus and the search indexer can hold a freshly written executable open for a moment, so replacing the installed executable or its build identity could fail with a bare access-denied error and abort the update or its rollback. Retry these replacements for a bounded window and report the operation, target path and cause when they still fail. * ci(webapi): display the release-all Web job as release-WebAPI The reusable-workflow job key still used the pre-rename name, which is the label the Actions UI shows for the nested Web release jobs. * feat(webapi): add win-arm64, linux-riscv64 and linux-loongarch64 coverage - build, package, sign and self-update support for the three architectures: win-arm64 (windows-11-arm native startup smoke), linux-riscv64 (RISE RISC-V runners with the community xujiegb/dotnet-riscv SDK; single-file publishing verified on real hardware) and linux-loongarch64 (the upstream QEMU loong64 VM with the official Loongson SDK, smoke-tested inside the VM) - per-RID native executable validation: ELF machines x86-64/AArch64/RISC-V (0xF3)/LoongArch (0x102) and Windows PE AMD64/ARM64 (0xAA64), behind a single IsSupportedRid gate - release asset map and packager/manifest tables extended; the riscv64 and loongarch64 Core bundles ship without the cronet payload - release manifests now ignore unknown RID entries so a newer manifest cannot be rejected wholesale by an older build * fix(webapi): keep the loongarch64 QEMU smoke out of the packaged publish tree The in-VM smoke ran the app inside the virtiofs-shared publish directory and left runtime files owned by the VM root (v2rayN.WebAPI.instance.lock) that the host runner could not read, so packaging failed with EACCES. The smoke now runs in a VM-local copy, and a host-side guard verifies the shared tree is complete and readable before packaging. * docs(webapi): document the six-platform release matrix Releases now cover linux-x64/arm64/riscv64/loongarch64 and win-x64/arm64; note the per-RID machine validation and the forward-compatible manifest behavior in the API release documentation. * ci(webapi): keep the release-all desktop dispatch exactly upstream build-all.yml dispatches the desktop workflows with "ref": "master" exactly as upstream does. The fork-only github.ref_name change is reverted so the PR leaves the existing release behavior untouched; the WebAPI release stays an additive reusable job in the same workflow. * fix(webapi): probe the effective listener and refuse unverifiable updates GetCurrentHealthUri and GetLauncherUris forced every probe to 127.0.0.1 and fell back to port 5080, so IPv6-only, wildcard and port-only listeners could be checked at the wrong endpoint. The detached update helper then either rolled back a healthy replacement or restarted without being able to verify the old instance, and --stop could probe the wrong process. Both callers now resolve the probe through one WebProbeUriResolver that uses the same effective Kestrel configuration as the host (command line, urls, http/https ports, Kestrel endpoints, preferHostingUrls) and maps each listener to its matching loopback address: "*", "+" and host names probe localhost, 0.0.0.0 probes 127.0.0.1, [::] probes [::1], and loopback literals keep their family. When no loopback HTTP probe exists (HTTPS-only or an explicit non-loopback address), GetWebUpdateTarget reports canInstall=false with maintenance.webUpdateProbeUnavailable and the update is refused before anything is stopped; the helper still accepts only loopback HTTP plan URIs, now including [::1]. --stop reports the new stopUnprobeable result instead of signalling an unverified owner, and the background launcher fails closed with startUnprobeable. Regression: new resolver/listener tests (default, custom port, IPv6-only, HTTP_PORTS, Kestrel override, HTTPS-only) and the real update fixture now covers an IPv6-only replacement, asserts that a failed update leaves the old build running (replacement PID), and proves that an unprobeable instance refuses both the API and --stop while staying up. * ci(webapi): capture the real smoke PID and bound the SIGTERM waits The riscv64 smoke backgrounded "cd && app" and recorded the subshell PID, so the later kill could target the wrapper while the app kept running. Both the riscv64 and loong64 smokes now start the app directly, record the application PID, fail fast when the process exits before health, wait a bounded time for SIGTERM before printing the log and force-killing, and assert a zero exit status. The loong64 VM smoke replaces its fixed two-second sleep with the same exit assertion. * chore(webapi): drop unreferenced legacy scripts bootstrap-xray.sh installed the removed bundled core-bin layout, and test-backup-fixtures.py compared desktop/Web backup ZIPs from before the WebUI decoupling; nothing references either script. * fix(webapi): unify the loopback probe, diagnostics and helper rules The resolver rewrote a configured localhost to 127.0.0.1 while the health diagnostics and the update helper each carried their own copy of the accepted-host rule. Keep localhost as localhost (resolving it covers both families instead of forcing one IPv4 literal) and make WebProbeUriResolver.IsProbeableLoopbackUri the single rule: plain HTTP to a host the diagnostics accept as local (localhost, 127.0.0.1 or ::1). The helper validates plans with that rule, the health endpoint uses the shared WebSetupAccessPolicy.IsLocalDiagnosticSource predicate, and every probe URI the resolver produces satisfies the rule. Unprobeable listeners (HTTPS-only or an explicit non-loopback address) still refuse the self-update up front: canInstall=false with maintenance.webUpdateProbeUnavailable while the current instance keeps running. Regression: localhost stays localhost across the resolver and launcher tests, the probe-rule invariant, the shared diagnostics/probe address rule, a direct unit test of the refusal reason, and a real localhost-listener replacement scenario in the update fixture. * fix(webapi): gate generated probes through the shared loopback rule MapToLoopbackHost accepted every address the OS reports as loopback, which in .NET is the whole 127.0.0.0/8 range, and TryCreateHealthUri returned true without checking the generated URI against the same rule the diagnostics and the update helper use. A listener on 127.0.0.2 therefore passed the up-front canInstall check, but the helper rejected its plan (and refused to restart the previous build for the same reason), so an update could stop the service without bringing anything back. TryCreateHealthUri now gates the constructed probe through IsProbeableLoopbackUri, so loopback aliases are refused before the instance is stopped and a mixed listener list falls through to the next verifiable endpoint. Regression: 127.0.0.2/127.255.255.254 mapping rows, a dedicated loopback-alias rejection test, the alias canInstall=false reason case, the mixed-list fall-through, and a real 127.0.0.2-listener fixture scenario that proves the update is refused while the current instance keeps running. * refactor(webapi): centralize integration tests and simplify release scripts Move the Linux integration tests (startup security, release packaging dry-run, full-ZIP runtime, native update regression and its fixture) from Scripts/ into Tests/Integration/; Scripts/verify.sh stays the unified entry and all path resolution, workflow calls, README text and cross-script invocations were updated. No test coverage changes. Merge Test-Windows.ps1 and Test-WindowsUpdate.ps1 into one Tests/Integration/Test-Windows.ps1 with -Mode startup|update: both modes share the native process control (CREATE_NEW_PROCESS_GROUP + CTRL_BREAK), environment isolation, free-port selection, no-proxy health waiting, JSON fixtures and retained-on-failure cleanup. CI keeps the Windows x64/ARM64 startup smokes and the x64 replacement/rollback smoke. Delete the package-native.sh thin wrapper; the workflow and the packaging dry-run now call web-release-assets.py package directly with the same --rid/--publish/--dist arguments, so asset names and ZIP boundaries stay unchanged. * test(webapi): keep the Windows health-body assertion in the merged smoke The merged Wait-TestHealth only accepted HTTP 200 in startup mode, while the original startup smoke parsed the health JSON and required status == "ok". Restore the body assertion in the shared helper so both modes verify the health payload instead of trusting the status code alone. * fix(webapi): preflight and verify native backup restores * test(webapi): isolate restore preflight smoke from systemd * test(webapi): set Windows smoke autostart default * test(webapi): retry transient Windows smoke cleanup * test(webapi): retry Windows smoke temp cleanup longer * ci(webapi): check whitespace on workflow dispatch
316 lines
13 KiB
C#
316 lines
13 KiB
C#
using System.ComponentModel;
|
|
using System.Diagnostics;
|
|
|
|
namespace v2rayN.WebAPI.Services;
|
|
|
|
internal sealed record CoreProcessIdentity(int ProcessId, string ProcessName, long StartTimeUtcTicks, string ExecutablePath);
|
|
|
|
/// <summary>
|
|
/// Tracks Core processes started by this Web host without depending on ServiceLib internals.
|
|
/// CoreManager remains responsible for launching/stopping; Web snapshots process identities
|
|
/// around its public LoadCore call and validates those identities during runtime transitions.
|
|
/// </summary>
|
|
internal static class CoreProcessTracker
|
|
{
|
|
public static HashSet<int> CaptureExistingProcessIds()
|
|
{
|
|
var ids = new HashSet<int>();
|
|
foreach (var process in Process.GetProcesses())
|
|
{
|
|
using (process)
|
|
{
|
|
try { ids.Add(process.Id); }
|
|
catch (InvalidOperationException) { }
|
|
}
|
|
}
|
|
return ids;
|
|
}
|
|
|
|
public static CoreProcessIdentity[] CaptureStartedProcesses(
|
|
IReadOnlySet<int> existingProcessIds,
|
|
IEnumerable<string> expectedExecutablePaths,
|
|
IEnumerable<string>? expectedConfigPaths = null)
|
|
{
|
|
var expected = expectedExecutablePaths
|
|
.Select(NormalizeExecutablePath)
|
|
.Where(path => path is not null)
|
|
.Select(path => path!)
|
|
.ToHashSet(PathComparer);
|
|
var expectedConfigs = expectedConfigPaths?
|
|
.Select(NormalizeAbsolutePath)
|
|
.Where(path => path is not null)
|
|
.Select(path => path!)
|
|
.ToHashSet(PathComparer);
|
|
if (expected.Count == 0) return [];
|
|
|
|
var processes = new List<CoreProcessIdentity>();
|
|
foreach (var process in Process.GetProcesses())
|
|
{
|
|
using (process)
|
|
{
|
|
try
|
|
{
|
|
if (existingProcessIds.Contains(process.Id) || process.HasExited) continue;
|
|
var startTimeTicks = GetStartTimeUtcTicks(process);
|
|
var executablePath = GetProcessExecutablePath(process);
|
|
if (startTimeTicks is null || executablePath is null
|
|
|| !IsExpectedCoreProcess(process.Id, executablePath, expected, expectedConfigs))
|
|
{
|
|
continue;
|
|
}
|
|
|
|
processes.Add(new CoreProcessIdentity(
|
|
process.Id,
|
|
NormalizeProcessName(process.ProcessName),
|
|
startTimeTicks.Value,
|
|
executablePath));
|
|
}
|
|
catch (Exception exception) when (exception is InvalidOperationException or Win32Exception or NotSupportedException)
|
|
{
|
|
// A process may exit or become inaccessible while the process table is sampled.
|
|
}
|
|
}
|
|
}
|
|
|
|
return processes
|
|
.DistinctBy(process => process.ProcessId)
|
|
.OrderBy(process => process.ProcessId)
|
|
.ToArray();
|
|
}
|
|
|
|
public static CoreProcessIdentity[] GetActiveProcesses(IEnumerable<CoreProcessIdentity> identities)
|
|
{
|
|
var active = new List<CoreProcessIdentity>();
|
|
foreach (var identity in identities.DistinctBy(process => process.ProcessId))
|
|
{
|
|
try
|
|
{
|
|
using var process = Process.GetProcessById(identity.ProcessId);
|
|
if (process.HasExited
|
|
|| !string.Equals(NormalizeProcessName(process.ProcessName), identity.ProcessName, StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
continue;
|
|
}
|
|
|
|
var startTimeTicks = GetStartTimeUtcTicks(process);
|
|
if (startTimeTicks is long observedStartTime && observedStartTime != identity.StartTimeUtcTicks) continue;
|
|
var executablePath = GetProcessExecutablePath(process);
|
|
if (executablePath is not null && !PathComparer.Equals(executablePath, identity.ExecutablePath)) continue;
|
|
|
|
// If an otherwise matching live PID becomes inaccessible, keep it as an
|
|
// uncertain active identity. This may report a conservative stop failure,
|
|
// but it cannot mistake the process for stopped or authorize killing a PID.
|
|
active.Add(identity);
|
|
}
|
|
catch (ArgumentException)
|
|
{
|
|
// The PID no longer exists.
|
|
}
|
|
catch (Exception exception) when (exception is InvalidOperationException or Win32Exception or NotSupportedException or UnauthorizedAccessException)
|
|
{
|
|
// An inaccessible PID is uncertain, so report it as active rather than
|
|
// claiming a clean stop. No process is ever terminated from this tracker.
|
|
active.Add(identity);
|
|
}
|
|
}
|
|
return active.OrderBy(process => process.ProcessId).ToArray();
|
|
}
|
|
|
|
private static string NormalizeProcessName(string name) =>
|
|
Path.GetFileNameWithoutExtension(name.Trim());
|
|
|
|
private static bool IsExpectedCoreProcess(
|
|
int processId,
|
|
string executablePath,
|
|
HashSet<string> expectedPaths,
|
|
HashSet<string>? expectedConfigPaths)
|
|
{
|
|
if (!OperatingSystem.IsLinux()) return expectedPaths.Contains(executablePath);
|
|
|
|
try
|
|
{
|
|
var arguments = File.ReadAllText($"/proc/{processId}/cmdline")
|
|
.Split('\0', StringSplitOptions.RemoveEmptyEntries);
|
|
var executableMatches = expectedPaths.Contains(executablePath);
|
|
foreach (var expectedPath in expectedPaths)
|
|
{
|
|
if (arguments.Any(argument => PathComparer.Equals(NormalizeExecutablePath(argument), expectedPath))
|
|
&& GetShebangInterpreters(expectedPath).Contains(executablePath, PathComparer))
|
|
{
|
|
executableMatches = true;
|
|
break;
|
|
}
|
|
}
|
|
|
|
return executableMatches && (expectedConfigPaths is null
|
|
|| expectedConfigPaths.Count == 0
|
|
|| CommandLineReferencesConfig(processId, arguments, expectedConfigPaths));
|
|
}
|
|
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or ArgumentException)
|
|
{
|
|
// Process metadata can disappear between enumeration and inspection.
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
private static bool CommandLineReferencesConfig(int processId, IEnumerable<string> arguments, HashSet<string> expectedConfigPaths)
|
|
{
|
|
var workingDirectory = GetProcessWorkingDirectory(processId);
|
|
if (workingDirectory is null) return false;
|
|
|
|
foreach (var argument in arguments)
|
|
{
|
|
var configArgument = argument.StartsWith("--config=", StringComparison.Ordinal)
|
|
? argument["--config=".Length..]
|
|
: argument.StartsWith("--config-file=", StringComparison.Ordinal)
|
|
? argument["--config-file=".Length..]
|
|
: argument;
|
|
if (configArgument.Length == 0 || configArgument.StartsWith("-", StringComparison.Ordinal)) continue;
|
|
var fullPath = NormalizeAbsolutePath(Path.IsPathRooted(configArgument)
|
|
? configArgument
|
|
: Path.Combine(workingDirectory, configArgument));
|
|
if (fullPath is not null && expectedConfigPaths.Contains(fullPath)) return true;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
private static string? GetProcessWorkingDirectory(int processId)
|
|
{
|
|
try
|
|
{
|
|
return new DirectoryInfo($"/proc/{processId}/cwd").ResolveLinkTarget(returnFinalTarget: false)?.FullName;
|
|
}
|
|
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException)
|
|
{
|
|
return null;
|
|
}
|
|
}
|
|
|
|
private static long? GetStartTimeUtcTicks(Process process)
|
|
{
|
|
try { return process.StartTime.ToUniversalTime().Ticks; }
|
|
catch (Exception exception) when (exception is InvalidOperationException or Win32Exception or NotSupportedException or UnauthorizedAccessException)
|
|
{
|
|
return null;
|
|
}
|
|
}
|
|
|
|
private static string? GetProcessExecutablePath(Process process)
|
|
{
|
|
try
|
|
{
|
|
var path = OperatingSystem.IsLinux()
|
|
? new FileInfo($"/proc/{process.Id}/exe").ResolveLinkTarget(returnFinalTarget: false)?.FullName
|
|
: process.MainModule?.FileName;
|
|
return path is null ? null : NormalizeExecutablePath(path);
|
|
}
|
|
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or InvalidOperationException or Win32Exception or NotSupportedException or ArgumentException)
|
|
{
|
|
return null;
|
|
}
|
|
}
|
|
|
|
private static string? NormalizeExecutablePath(string? path)
|
|
{
|
|
var fullPath = NormalizeAbsolutePath(path);
|
|
if (fullPath is null) return null;
|
|
try
|
|
{
|
|
var executablePath = fullPath;
|
|
if (OperatingSystem.IsLinux() && executablePath.EndsWith(" (deleted)", StringComparison.Ordinal))
|
|
{
|
|
executablePath = executablePath[..^" (deleted)".Length];
|
|
}
|
|
|
|
if (!OperatingSystem.IsLinux())
|
|
{
|
|
var target = new FileInfo(executablePath).ResolveLinkTarget(returnFinalTarget: true);
|
|
return Path.GetFullPath(target?.FullName ?? executablePath);
|
|
}
|
|
|
|
var root = Path.GetPathRoot(executablePath)!;
|
|
var current = root;
|
|
foreach (var segment in executablePath[root.Length..].Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries))
|
|
{
|
|
current = Path.Combine(current, segment);
|
|
FileSystemInfo info = Directory.Exists(current) ? new DirectoryInfo(current) : new FileInfo(current);
|
|
var linkTarget = info.ResolveLinkTarget(returnFinalTarget: false);
|
|
if (linkTarget is not null) current = linkTarget.FullName;
|
|
}
|
|
return Path.GetFullPath(current);
|
|
}
|
|
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException)
|
|
{
|
|
return null;
|
|
}
|
|
}
|
|
|
|
private static string? NormalizeAbsolutePath(string? path)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(path) || !Path.IsPathRooted(path)) return null;
|
|
try { return Path.GetFullPath(path.TrimEnd('\0')); }
|
|
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException)
|
|
{
|
|
return null;
|
|
}
|
|
}
|
|
|
|
private static HashSet<string> GetShebangInterpreters(string executablePath)
|
|
{
|
|
var interpreters = new HashSet<string>(PathComparer);
|
|
try
|
|
{
|
|
using var stream = File.OpenRead(executablePath);
|
|
var prefix = new byte[256];
|
|
var length = stream.Read(prefix);
|
|
var lineEnd = Array.IndexOf(prefix, (byte)'\n', 0, length);
|
|
if (lineEnd < 0) lineEnd = length;
|
|
var firstLine = System.Text.Encoding.UTF8.GetString(prefix, 0, lineEnd).TrimEnd('\r');
|
|
if (!firstLine.StartsWith("#!", StringComparison.Ordinal)) return interpreters;
|
|
|
|
var tokens = firstLine[2..].Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
|
|
if (tokens.Length == 0) return interpreters;
|
|
var interpreter = tokens[0];
|
|
if (string.Equals(Path.GetFileName(interpreter), "env", StringComparison.Ordinal))
|
|
{
|
|
var index = 1;
|
|
while (index < tokens.Length && tokens[index].StartsWith("-", StringComparison.Ordinal))
|
|
{
|
|
if (tokens[index] is "-u" or "--unset" or "-C" or "--chdir" or "-a" or "--argv0") index++;
|
|
index++;
|
|
}
|
|
if (index >= tokens.Length) return interpreters;
|
|
interpreter = FindOnPath(tokens[index]) ?? string.Empty;
|
|
}
|
|
|
|
var normalized = NormalizeExecutablePath(interpreter);
|
|
if (normalized is not null) interpreters.Add(normalized);
|
|
}
|
|
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException)
|
|
{
|
|
// A script that cannot be inspected is not claimed based on its process name alone.
|
|
}
|
|
|
|
return interpreters;
|
|
}
|
|
|
|
private static string? FindOnPath(string executableName)
|
|
{
|
|
if (Path.IsPathRooted(executableName)) return executableName;
|
|
var path = Environment.GetEnvironmentVariable("PATH");
|
|
if (string.IsNullOrEmpty(path)) return null;
|
|
foreach (var directory in path.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries))
|
|
{
|
|
var candidate = Path.Combine(directory, executableName);
|
|
if (File.Exists(candidate)) return candidate;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
private static StringComparer PathComparer => OperatingSystem.IsWindows()
|
|
? StringComparer.OrdinalIgnoreCase
|
|
: StringComparer.Ordinal;
|
|
}
|