ServiceLib downloads, updates, and speed tests
Overview
This area owns ServiceLib's outbound network plumbing and the higher-level flows that use it for file downloads, release discovery, geo-data updates, and node connectivity tests. The main entry points are v2rayN/…/DownloadService.cs, v2rayN/…/UpdateService.cs, and v2rayN/…/SpeedtestService.cs.
DownloadService is the caller-facing wrapper around DownloaderHelper and HttpClient. Its Handler defaults to HttpClientHelper.Instance.DirectHandler, but callers can inject any HttpMessageHandler; DisposeHandler controls whether DownloadService.Dispose() owns that handler. CreateDownloadServiceWithCheck() probes the local SOCKS inbound with a SOCKS5 greeting before creating a proxy handler, and falls back to a direct cookie-enabled handler if the proxy is not ready. CreateDownloadServiceWithFallback() instead installs HttpClientHelper.CreateFallbackHandler(), which retries the same request through the alternate direct/proxy handler on 502/503/504 or HttpRequestException/TaskCanceledException.
Request construction is split across HttpClientHelper, HttpRequestHeadersHelper, and DownloaderHelper. HttpClientHelper.cs creates direct SocketsHttpHandlers with UseProxy = false and Global.DirectDownloadConnect, proxy handlers for socks5://127.0.0.1:<local socks port> with Global.ProxyDownloadConnect, optional shared CookieContainers, and optional certificate chain policy from CertPemManager. Shared handlers are wrapped in SharedHandlerAdapter so creating/disposing a per-call HttpClient does not dispose the singleton handler. HttpRequestHeadersHelper.cs validates user-supplied JSON headers as a string-valued object, rejects invalid/control-containing header values, and applies headers in a delegating handler after downloader defaults so caller headers replace default values. DownloaderHelper.cs adds HTTP Basic authorization when the URL contains UserInfo, configures the third-party Downloader.DownloadService, and uses the supplied handler through CustomHttpMessageHandlerFactory.
Download state is reported with FileDownloadState from v2rayN/…/FileDownloadState.cs. DownloaderHelper.DownloadFileAsync() deletes an existing target before starting, downloads large files with chunked parallel download settings, and emits immutable state snapshots containing the original FileDownloadRequest, byte counts, current bytes/sec, completion, and any completion error. DownloadService.DownloadFileAsync() translates those snapshots into UpdateCompleted events with localized progress text; completion sets UpdateResult.Success = true, while exceptions are logged and raised through the Error event. DownloaderHelper.DownloadSmallFilesAsync() downloads multiple small files with MaxDegreeOfParallelism = 4, mutates an array of per-file states, and calls back with a ReadOnlyMemory<FileDownloadState> view; DownloadService.DownloadSmallFilesAsync() aggregates completed count, active speed, byte totals, active file names, and throws the first failed state's error only once all files have completed.
String and speed-oriented downloads use narrower contracts. DownloadService.TryDownloadString() first calls a plain HttpClient.GetStringAsync() with Global.ProxyFetch timeout and URL-userinfo Basic auth, then falls back to DownloaderHelper.DownloadStringAsync(); both paths log and raise Error, return null on failure, and rethrow caller cancellation. DownloadService.DownloadDataAsync() calls DownloaderHelper.DownloadDataAsync4Speed(), which downloads a test URL only to measure peak transfer speed, reports at most once per second as a decimal megabytes-per-second string, and reports the final peak speed, error message, or "0" on completion.
UpdateService.cs coordinates release checks and downloads. CheckUpdateGuiN() and CheckUpdateCore() subscribe to a DownloadService's progress/error events, call CheckUpdateAsync(), and, when an update exists, download the selected asset to a temp file. GUI updates notify callers with Utils.UrlEncode(fileName) on successful download; core updates notify with the temp archive path after emitting an unpacking message. CheckHasUpdateOnly() returns an UpdateResult without downloading, and CheckHasUpdateOnlyAll() iterates CoreInfoManager.Instance.GetCheckUpdateCoreTypes(), honoring Config.CheckUpdateItem.SelectedCoreTypes and pre-release selections, then stores the last per-core message in AppManager.
Release discovery in UpdateService comes from CoreInfoManager metadata. For pre-release checks, or cores with LockedMaxVersion, GetRemoteVersion() downloads the GitHub releases API URL and deserializes GitHubRelease records from v2rayN/…/GitHubRelease.cs; it picks the first release for pre-release checks or the first non-prerelease otherwise, and clamps to the newest release at or below LockedMaxVersion when configured. For normal checks it requests <coreInfo.Url>/latest through DownloadService.UrlRedirectAsync() and extracts the tag after /tag/ from the redirect location. ParseDownloadUrl() compares the remote SemanticVersion with either the installed core CLI version (parsed from Utils.GetCliWrapOutput() using SemVerRegex) or the v2rayN app version, chooses the platform/architecture download URL from CoreInfo, applies v2rayN desktop/AOT filename substitutions on Windows, and returns UpdateResult.Url only when the remote version is newer.
Geo and ruleset updates are also handled by UpdateService. UpdateGeoFileAll() builds FileDownloadRequests for geosite.dat, geoip.dat, optional Global.OtherGeoUrls, and sing-box .srs rule sets discovered from routing rules and DNS JSON; it reverses the combined request list so smaller SRS files run first. DownloadGeoFiles() downloads every file to a temp path, then on overall success copies temp files over the real bin targets and deletes the temps. This means callers see progress from DownloadSmallFilesAsync(), while the write to the final geo/ruleset files happens only after the batch reports success.
SpeedtestService.cs runs node tests and reports SpeedTestResult DTOs from v2rayN/…/SpeedTestResult.cs. RunLoop() creates a linked run CancellationTokenSource, tracks it in _runCtsList, and dispatches Tcping, Realping, UdpTest, Speedtest, or Mixedtest; ExitLoop() cancels all tracked runs and emits a stop message. Every run first converts eligible ProfileItems into ServerTestItems, skipping custom configs and simple configs without ports, reloading full profiles from ConfigDbQuery, assigning CoreType through AppManager, and clearing visible delay/speed messages with ResUI.Speedtesting.
Speed test mechanics differ by action. Tcping resolves DNS when needed and measures a raw TCP connect with a five-second timeout, batching by SpeedTestPageSize and separating Xray and sing-box cores. Realping starts a temporary core config via CoreManager.Instance.LoadCoreConfigSpeedtest(), waits one second, sends two HTTP requests to ConfigTextHandler.Config.SpeedTestItem.SpeedPingTestUrl through a per-node SOCKS proxy, and records the fastest positive response; if IP info is visible, it reuses the same handler in a DownloadService to call the configured IP API. UdpTest starts the temporary core and sends a UDP request through UdpTestService.CreateFromTarget(). Speedtest and Mixedtest run per-node temporary cores, real-ping first, then call DownloadService.DownloadDataAsync() through the node's SOCKS proxy against Config.SpeedTestItem.SpeedTestUrl with SpeedTestTimeout; positive numeric progress updates ProfileExManager.SetTestSpeed(). Completed delays, speeds, messages, and IP info are persisted through ProfileExManager, saved in RunLoopAsync() finally, and streamed to the UI via the supplied Func<SpeedTestResult, Task>.
Supporting utilities are intentionally small. NetworkUtils.cs exposes bind-interface helpers and a heuristic default physical interface selector that filters active IP-capable interfaces, blacklists virtual/VPN/tunnel names, and prefers Ethernet before Wi-Fi. FileUtils.cs contains archive/file helpers used around downloaded artifacts: gzip and tar.gz extraction, zip extraction/listing/creation, non-exclusive text reads, directory copy, expired-file cleanup, and Linux shell file creation with chmod. ProcUtils.cs wraps shell process starts and admin relaunch, logging failures instead of throwing.
Routing / covers
This document owns these paths:
- v2rayN/…/DownloadService.cs
- v2rayN/…/UpdateService.cs
- v2rayN/…/SpeedtestService.cs
- v2rayN/…/DownloaderHelper.cs
- v2rayN/…/HttpClientHelper.cs
- v2rayN/…/HttpRequestHeadersHelper.cs
- v2rayN/…/NetworkUtils.cs
- v2rayN/…/FileUtils.cs
- v2rayN/…/ProcUtils.cs
v2rayN/ServiceLib/Models/Dto/*Download*v2rayN/ServiceLib/Models/Dto/*Update*v2rayN/ServiceLib/Models/Dto/*Release*v2rayN/ServiceLib/Models/Dto/*Speed*v2rayN/ServiceLib/Models/Dto/*Test*
Coupling
- If
HttpClientHelper.CreateFallbackHandler()is changed, verify bothDownloadService.CreateDownloadServiceWithFallback()and downloader-based calls still receive replayable requests. The fallback handler buffers and restoresHttpRequestMessage.Content; without that, retrying a request after a network error can send an empty or disposed body. - If the local SOCKS inbound behavior or port allocation changes, update both
DownloadService.CheckProxy()andHttpClientHelper.ProxyHandler/CreateProxySocketsHttpHandler(int).CheckProxy()requires a successful SOCKS5 greeting before proxy-backed update downloads, while speed tests directly build per-node proxy handlers from node ports. - If custom subscription/download headers change format, update
HttpRequestHeadersHelper.TryParse()and every caller that stores the JSON string together. The parser only accepts a JSON object with string values and validates both request and content headers, so non-string values are rejected before the handler is created. - If
FileDownloadStateorFileDownloadRequestchanges, audit bothDownloaderHelper.DownloadSmallFilesAsync()andDownloadService.DownloadSmallFilesAsync(). The batch code relies onCompleted,Error,TotalBytes, andRequest.FileNameto decide when to surface failures and how to aggregate progress. - If
CoreInfoManagerrelease metadata orECoreTypesupport changes, updateUpdateService.GetRemoteVersion(),GetUrlFromCore(), andParseDownloadUrl(). These methods assume GitHub/latestredirects for normal releases, GitHub releases API JSON for pre-release/locked-version checks, and format-string download URLs with different placeholders for sing-box. - If geo/ruleset source URL templates change, verify
UpdateService.GetGeoFilesRequest(),GetOtherFilesRequest(), andGetSrsFileRequest(). The geo URL is formatted with one argument (geoip/geosite), while the SRS URL is formatted with three arguments (type, full rule-set file stem, short name). - If
ConnectionHandler.GetRealPingTime()or IP API parsing changes, verifySpeedtestService.DoRealPing(). Real-ping and IP info share a per-node SOCKS handler; disposing that handler too early would break the IP lookup path, while hiding IP info deliberately reportsResUI.SpeedtestingSkipinstead of calling the API. - If
ProfileExManagertest fields or UI sorting semantics change, updateSpeedtestService.SetTestResultAsync()andDoSpeedTest(). Speed and mixed tests explicitly reset stored speed to0before running so skipped/failed tests do not retain old speeds for sorting.
Risks
- v2rayN/…/UpdateService.cs adds anonymous event handlers to a shared
DownloadServiceinCheckUpdateGuiN(),CheckUpdateCore(), andDownloadGeoFiles()without unsubscribing. Reusing the sameDownloadServiceinstance across update operations can duplicate progress/error messages or run stale success callbacks with captured temp file names. - v2rayN/…/UpdateService.cs extracts the latest stable release with
gitHubReleases?.First(r => r.Prerelease == false). If the GitHub API returns only prereleases or an empty list,Firstthrows and the caller receives a generic failedUpdateResultinstead of a clean "no update" result. - v2rayN/…/DownloaderHelper.cs mutates the shared
FileDownloadState[]from up to four parallel small-file downloads and passes the sameReadOnlyMemory<FileDownloadState>to progress callbacks. Callers must treat the memory as a transient snapshot source only; retaining it can observe later mutations from other downloads. - v2rayN/…/SpeedtestService.cs swallows many per-node test exceptions and records
-1,0, or skip messages. A broken test URL, DNS failure, or temporary core startup issue may look like ordinary node failure unless reviewers checkLogging.SaveLogoutput for theSpeedtestServicetag. - v2rayN/…/FileUtils.cs extracts zip entries with
Path.Combine(toPath, entry.Name)and ignores entry directories. Archives that rely on nested paths or duplicate file names can be flattened or partially skipped, so update/unpack callers should validate archive layout before relying on this helper for new artifact formats.