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 / service-lib-core-runtime-processes

ServiceLib core runtime processes

Overview

This area owns the runtime boundary between ServiceLib and the external proxy cores. v2rayN/…/CoreManager.cs is the lifecycle orchestrator: Init copies bundled binaries into the configured bin storage when needed, chmods non-Windows core executables, and LoadCore generates the active client config before stopping any existing core and starting a new one. The main core is launched from Global.CoreConfigFileName; an optional pre-service core is launched from Global.CorePreConfigFileName after WaitForProxyPort confirms the main SOCKS port can complete a SOCKS5 greeting for TUN protection flows.

Core executable metadata lives in v2rayN/…/CoreInfoManager.cs. It maps each ECoreType to candidate binary names, command arguments, environment variables, update URLs, version commands, and platform-specific mihomo binary names. CoreManager.RunProcess resolves the first existing executable through CoreInfoManager.GetCoreExecFile, then either starts it normally through v2rayN/…/ProcessService.cs or, for non-Windows TUN launches of sing-box, mihomo, or Xray, delegates to v2rayN/…/CoreAdminManager.cs to run via sudo -S. Normal launches set the bin directory as the working directory, format config-path arguments and environment values, stream stdout/stderr into the update callback when enabled, and attach Windows child processes to v2rayN/…/WindowsJobService.cs so closing the job handle terminates the process tree. Stop paths call CoreAdminManager.KillProcessAsLinuxSudo for elevated launches, then stop and dispose both main and pre-service ProcessService instances.

v2rayN/…/ProcessService.cs is the narrow process wrapper. It constructs ProcessStartInfo with UseShellExecute=false, optional stdout/stderr redirection, optional stdin redirection for sudo password injection, explicit working directory, and supplied environment variables. StopAsync cancels async output readers, tries recursive kill on non-Windows, then kills the root process and reports exceptions through the same update callback used for core logs.

System proxy integration starts at v2rayN/…/SysProxyHandler.cs. UpdateSysProxy derives the local SOCKS port from AppManager.Instance.GetLocalPort(EInboundProtocol.socks), applies forced changes or forced clears per platform, and on Windows can also start a PAC server through PacManager and set WinINET's AutoConfigURL. v2rayN/…/ProxySettingWindows.cs updates LAN and RAS connection proxy settings through WinINET/RAS P/Invoke and falls back to Internet Settings registry values. v2rayN/…/ProxySettingLinux.cs and v2rayN/…/ProxySettingOSX.cs execute either a user-provided script from ConfigTextHandler.Config.SystemProxyItem.CustomSystemProxyScriptPath or an embedded platform script, passing sanitized bypass exceptions.

Connectivity helpers live in v2rayN/…/ConnectionHandler.cs and v2rayN/…/CertPemManager.cs. ConnectionHandler.RunAvailabilityCheck measures the configured speed-test URL through the local proxy, retries once, and only fetches IP API metadata when ping succeeds. CertPemManager opens raw TCP/TLS connections to a target, validates the certificate chain against either embedded Chrome or Mozilla roots when configured, allows name mismatch only when verifyPeerCertByName matches a SAN DNS name, and exports leaf or full-chain PEM plus SHA-256 thumbprints for later config use.

Statistics are coordinated by v2rayN/…/StatisticsManager.cs. When Config.GuiItem.EnableStatistics or DisplayRealTimeSpeed is enabled, it cleans orphaned ServerStatItem rows, resets daily counters by date tick, loads persisted rows from SQLite, and starts both v2rayN/…/StatisticsXrayService.cs and v2rayN/…/StatisticsSingboxService.cs. The Xray collector polls http://127.0.0.1:{AppManager.Instance.StatePort}/debug/vars once per second while RunningCoreType is Xray-family, computes deltas from cumulative outbound counters, and resets its baseline if counters move backwards. The sing-box collector connects to ws://127.0.0.1:{AppManager.Instance.StatePort2}/traffic while the running core is sing-box-family and reports per-message traffic. StatisticsManager.UpdateServerStat attributes proxy deltas to the current _config.IndexId, updates today's and total counters in memory, and invokes the UI update callback; persistence is batched through SaveTo.

Auto-start is handled by v2rayN/…/AutoStartupHandler.cs. UpdateTask first clears the platform's existing registration, then recreates it only when Config.GuiItem.AutoRun is true. Windows uses a per-install name derived from the startup path MD5 and either HKCU Run values or an elevated Scheduled Task created from an embedded XML template. Linux writes a desktop entry under ~/.config/autostart. macOS writes a LaunchAgent plist under ~/Library/LaunchAgents and loads it; its clear path intentionally deletes the plist without launchctl unload to avoid terminating v2rayN when it was itself launched by that agent.

Routing / covers

This doc owns:

Coupling

  • If core config generation changes TUN or pre-service behavior, verify v2rayN/…/CoreManager.cs: it decides sudo elevation from the immutable CoreConfigContext.IsTunEnabled, waits for the main proxy port before launching the pre-service, and sets AppManager.Instance.RunningCoreType to the pre-service core when one exists.
  • If core executable names, command-line flags, or config path conventions change, update v2rayN/…/CoreInfoManager.cs and check both launch paths in v2rayN/…/CoreManager.cs and v2rayN/…/CoreAdminManager.cs; the normal path formats arguments and environment values differently from the sudo shell-script path.
  • If local inbound port allocation changes, verify v2rayN/…/SysProxyHandler.cs, v2rayN/…/ConnectionHandler.cs, and the statistics services. They all assume AppManager.Instance.GetLocalPort(EInboundProtocol.socks) is the user-facing proxy port, with PAC and API ports derived from neighboring inbound protocol offsets.
  • If Xray or sing-box statistics config changes, keep the collectors aligned: v2rayN/…/StatisticsXrayService.cs expects Xray metrics at /debug/vars on AppManager.Instance.StatePort, while v2rayN/…/StatisticsSingboxService.cs expects a WebSocket /traffic endpoint on AppManager.Instance.StatePort2.
  • If root certificate provider settings change, check v2rayN/…/CertPemManager.cs; TLS fetches use embedded Chrome/Mozilla root stores when selected, but BuildCertificateChainPolicy returns null for the system provider, leaving callers to use platform trust.
  • If auto-start packaging or executable paths change, verify all three branches in v2rayN/…/AutoStartupHandler.cs; Windows scheduled-task XML, Linux desktop entry content, and macOS LaunchAgent shell command each embed the current executable path differently.

Risks

  • v2rayN/…/CoreManager.cs stops the existing core before starting the new one. If config generation succeeds but process launch fails, the previous working proxy is already gone and only the update callback reports the failure.
  • v2rayN/…/CoreManager.cs has a documented recovery path around CoreStartPreService: a failed optional TUN protection core leaves the ordinary proxy core running, but callers must not treat that as successful TUN startup. Changes that collapse main-core and pre-service errors can silently regress this behavior.
  • v2rayN/…/ProxySettingWindows.cs falls back to direct registry writes when WinINET/RAS P/Invoke fails, while v2rayN/…/SysProxyHandler.cs catches and logs all exceptions and still returns true. A proxy update can therefore appear successful even when Windows did not refresh the effective system proxy.
  • v2rayN/…/CoreAdminManager.cs kills elevated non-Windows launches by remembering the sudo wrapper process id and invoking an embedded kill script. If the sudo wrapper exits or re-parents the actual core unexpectedly, CoreManager.CoreStop can fail to terminate the privileged proxy process.