Introducing a new way to review your PRs.

Read the announcement

2dust / v2rayn

A GUI client for Windows, Linux and macOS, support Xray and sing-box and others

View on GitHub

13 documents · Updated Nov 16, 2026

docs / webapi-runtime-and-endpoints

WebAPI runtime and endpoints

Overview

v2rayN/…/Program.cs is the headless ASP.NET Core entry point. Startup first loads a native .env from the executable directory through Configuration/NativeEnvironmentFile.cs, validates the optional V2RAYN_WEB_API_KEY, applies listener/CORS security defaults, prepares the ServiceLib data scope from V2RAYN_DATA_HOME or local-app-data fallback, and enforces a single instance with v2rayN.WebAPI.instance.lock. The same entry point also handles launcher modes (--help, Linux background/stop flows) and the detached native self-update helper mode --apply-WebAPI-update before it builds the web host.

Program.RunWebHostAsync registers the process-wide runtime services: EventHub, LogBuffer, RuntimeOperationCoordinator, V2rayRuntime, WebAuthService, WebSessionService, auth rate limiting, CORS, JSON enum conversion, and V2rayHostedService. Middleware order is intentional: security headers/body limits, routing, origin guard, CORS preflight, rate limiting, session authentication, API exception normalization, and then runtime-operation leasing. Public paths are limited to /api/health, /api/setup/*, /api/auth/*, and /api/events ticket/session handling; protected API paths are mapped by Api/WebApiEndpoints.cs, Api/WebAuthEndpoints.cs, and Api/WebSetupEndpoints.cs, with an /api/{**path} fallback returning the stable envelope from Contracts/ApiModels.cs.

Endpoint groups in Api/WebApiEndpoints.cs are thin adapters over Services/V2rayRuntime* partials:

  • Health/status/logging/events: /api/health, /api/status, /api/operations, /api/logs, /api/logs/page, and /api/events. Api/WebHealthEndpoint.cs only emits diagnostic headers such as PID, version, core state, process IDs, and shutdown stage for direct local diagnostic requests. SSE events come from Services/EventHub.cs; logs are retained by Services/LogBuffer.cs and optionally streamed as log events.
  • Auth/setup: Api/WebAuthEndpoints.cs exchanges the Management Key at POST /api/auth/login, revokes sessions at logout, and issues one-use SSE tickets at /api/auth/sse-ticket. Api/WebSetupEndpoints.cs allows first-run key setup only when the setup access policy permits it and returns a session immediately after setup.
  • Profiles and subscriptions: profile groups, CRUD/import/export/move/sort/deduplicate, profile selection, latency/speed tests, subscription CRUD/share/update, and subscription background progress. State is read and written through ServiceLib database/config APIs from V2rayRuntime.cs and V2rayRuntime.Profiles.cs under the runtime mutation gate.
  • Settings: inbound, core, application, speed-test, core-type mapping, routing, DNS, full config templates, WebDAV settings, regional presets, statistics cleanup, backup/restore, and option discovery. These live primarily in V2rayRuntime.Settings.cs and use ServiceLib option lists rather than duplicating desktop constants.
  • Core/Web/Geo maintenance: /api/core/start|stop|restart, /api/core-updates*, legacy Xray endpoints, /api/core/geo/update, and /api/web-updates* are implemented by V2rayRuntime.cs, V2rayRuntime.CoreUpdate.cs, and V2rayRuntime.WebUpdate.cs.

Services/V2rayRuntime.cs owns the ServiceLib bridge and hosted core lifecycle. V2rayHostedService.cs calls InitializeAsync at host start and ShutdownAsync at host stop; initialization runs AppManager.Instance.InitApp/InitComponents, installs Adapters/HeadlessWindowDialog.cs, initializes builtin DNS/templates/routing, normalizes Web update target names, applies Web proxy environment overrides, initializes CoreManager, StatisticsManager, certificates, profile extensions, and scheduled operations. Core start builds ServiceLib core config with CoreLaunchPreflight.cs, rejects TUN-generated contexts, validates selected core executables, checks projected TCP/UDP listener availability, snapshots CoreRuntimeSnapshot, launches through CoreManager.Instance.LoadCore, tracks child process identities with CoreProcessTracker.cs, waits for the configured listener, and starts a monitor that marks the runtime faulted if the tracked child exits or no longer owns the listener. Core stop/restart always uses _coreGate, StopCoreAndConfirmAsync, and tracked process identity rather than port ownership alone.

Runtime mutation and restart coordination is split between two gates. RuntimeMutationGate.cs serializes Web-owned writes to ServiceLib config and SQLite state. RuntimeOperationCoordinator.cs leases request/runtime work: normal operations can overlap, exclusive maintenance blocks mutations/restores/updates, some exclusive windows permit read-only observations, and shutdown cancels linked operation tokens before cleanup. RuntimeRequestOperationPolicy.cs classifies HTTP requests before endpoint execution: background starters (subscription updates, speed tests, update starts, restores, regional presets) enqueue work without holding the request lease for the full operation; settings mutations and backups take stronger leases so runtime state cannot be swapped underneath them.

Core-affecting settings in V2rayRuntime.Settings.cs use a transactional apply path. BeginCoreSettingsApplyAsync snapshots Config, active runtime state, routing rows, DNS rows, and full config templates while holding _coreGate. After ServiceLib/SQLite writes, CompleteCoreAffectingChangeAsync uses CoreSettingsApplyPolicy.cs to decide save-only versus restart versus busy/inconsistent failure. If restart fails, RollBackCoreSettingsAsync restores config/database snapshots and attempts to recover the old core runtime; responses include rollback flags so clients can distinguish saved settings, restored settings, and restart failures.

Backup and restore live in V2rayRuntime.Backup.cs. Backup downloads and WebDAV uploads create the existing guiConfigs/ ZIP shape while excluding WebAPI-auth.json; Api/DeleteAfterFileResult.cs deletes temporary download archives after streaming. Restore validates archive size/shape, rejects path traversal/symlinks, ignores any auth file in the archive, parses config.json, checks SQLite compatibility through BackupDatabaseCompatibility.cs, writes a runtime restart intent, stops Core, saves/flushes ServiceLib state, closes SQLite, atomically replaces the config directory, rejects new operations, and requests host shutdown. Native Linux/Windows restores can plan a replacement process through launcher types and are gated by BackupRestorePreflightGate.cs; startup reads the restore marker and RuntimeRestartRecovery.cs restarts the previous, selected, or default profile when possible.

Core, GeoFiles, and Web update flows are staged before destructive actions. V2rayRuntime.CoreUpdate.cs exposes update settings/progress/check/apply and serializes all update tasks with _updateTaskGate; core package installation uses CoreUpdatePackageStager.cs to flatten/extract supported archives, version-check staged executables with CoreExecutableVersionCheck.cs, copy existing Geo data for Xray, move install/candidate/backup directories, restart only the affected running core, and roll back files/runtime if apply fails. GeoFiles updates wrap ServiceLib UpdateService.UpdateGeoFileAll in GeoFilesUpdateGate.cs, GeoFilesUpdateTransaction.cs, and GeoFilesUpdateCompletion.cs: managed required files and configured SRS rule-set files are backed up, symlinks/directories are rejected, completion must be reported, and failures roll files back before progress is marked failed.

Web self-update is a separate v2rayN.WebAPI target. WebBuildIdentity.cs reads assembly metadata from v2rayN.WebAPI.csproj; WebReleaseChannel.cs trusts only upstream GitHub release assets matching WebAPI-update.json; WebReleaseAssets.cs is the embedded source of release asset names; WebUpdatePackageStager.cs validates manifest product/version/RID, asset URL/size/SHA-256, ZIP boundaries, allowed app-only files, build identity, and native ELF/PE architecture. V2rayRuntime.WebUpdate.cs permits install only for writable native Linux/Windows single-file deployments according to WebUpdateDeploymentPolicy.cs, with containers/systemd/read-only deployments check-only. Apply writes runtime intent and progress files, creates a native helper plan, launches --apply-WebAPI-update, and stops the host only after network download and package verification complete.

API contracts are centralized in Contracts/ApiModels.cs: response envelopes are { success, code, messageKey, data }, operations use OperationView, stable message keys live in ApiMessageKeys, status includes runtime/build/capability fields, and request/view records cover subscriptions, profiles, settings, DNS/routing, backup/WebDAV, updates, traffic, logs, and SSE events. Contracts/WebApiCapabilities.cs advertises durable feature flags such as auth.sessions, events.sse, backup.restore, core.updates, and WebAPI.self-update. The module is an ASP.NET Microsoft.NET.Sdk.Web app targeting net10.0 and references ServiceLib directly in v2rayN.WebAPI.csproj; README.md and FEATURE-MAP.md document the ServiceLib/API boundary and release/update contract.

Routing / covers

This doc owns the headless WebAPI runtime and endpoint surface under:

Use this doc for reviews involving /api/* endpoint behavior, hosted ServiceLib/Core lifecycle, runtime mutation or restart coordination, WebDAV backup/restore, core/GeoFiles/Web update workflows, WebAPI release identity, and the contracts returned to WebAPI clients.

Coupling

Risks

  • Services/V2rayRuntime.Settings.cs and Services/CoreSettingsApplyPolicy.cs: a settings save that affects the running core must either restart successfully or roll back config/database/runtime. If new settings paths bypass BeginCoreSettingsApplyAsync/CompleteCoreAffectingChangeAsync, clients can observe saved settings while the old core keeps serving stale configuration.
  • Services/V2rayRuntime.CoreUpdate.cs, Services/CoreUpdatePackageStager.cs, and Services/GeoFilesUpdateTransaction.cs: update flows modify executable/core/geofile directories on disk. If archive validation, version checks, or rollback moves are weakened, a bad package can replace the running core or leave GeoFiles partially updated after ServiceLib reports progress errors.
  • Services/V2rayRuntime.WebUpdate.cs and Services/WebUpdatePackageStager.cs: Web self-update deliberately verifies the release manifest, asset URL, SHA-256, RID identity, and ELF/PE architecture before stopping the host. If installation starts before WebProbeUriResolver can produce a loopback health probe, the helper cannot prove replacement health or rollback safely.
  • Services/V2rayRuntime.Backup.cs: restore closes SQLite and atomically replaces the config directory before requesting host shutdown. If restore runtime-state markers are not written/committed correctly, startup may fail to recover a previously running core or may retry stale restore intent.
  • Services/CoreProcessTracker.cs and Services/V2rayRuntime.cs: the runtime treats tracked process identity as ownership and explicitly avoids using port occupancy as ownership. If future stop/restart/update code infers ownership from a listening port, it may mistake an unrelated process for the Web-owned core or report a clean stop while the actual child remains alive.