Skip to content

Use native Xray TUN for connection info and updates - #6109

Open
eliotcougar wants to merge 18 commits into
2dust:masterfrom
eliotcougar:codex/xray-tun-connection-info
Open

eliotcougar wants to merge 18 commits into
2dust:masterfrom
eliotcougar:codex/xray-tun-connection-info

Conversation

@eliotcougar

@eliotcougar eliotcougar commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • restore country and IP enrichment for current-connection tests in native Xray TUN mode when the local proxy is disabled
  • download subscriptions, application-update metadata, and asset files through the already-running Xray core in the same mode
  • force ordinary profiles through the proxy outbound
  • resolve a primary policy group's first viable principle target and use that concrete member
  • preserve the existing local-proxy and direct fallback paths for other modes, including HEV and root configurations that force a local proxy
  • preserve request headers, including custom Host authorities, user agents, and embedded URL credentials
  • prevent incomplete or overlapping asset downloads from replacing valid files
  • keep daemon URL downloads and service controls private to this app
  • cancel pending daemon downloads with the core service lifecycle

Root cause

The connection test measures delay and then requests Current connection info test URL to display the exit country code and IP address. Subscription and asset updates similarly relied on an HTTP client configured for the local proxy. Native Xray TUN can run with that proxy disabled, leaving no listener for these requests even though the core and tunnel are active.

Application update checks had a related problem: the app first fetched GitHub release metadata directly. Because v2rayNG excludes its own process from its VPN interface, that request could bypass the active Xray connection. With the local proxy disabled, there was no app-owned path that followed the selected outbound.

An unqualified core request would not be equivalent: user routing rules could send the URL or its resolved IP through direct or another detour, producing incorrect connection information or bypassing the selected route for updates.

The daemon also registered its internal service action in the same dynamic receiver filter as system screen broadcasts. On Android 13 and newer, that mixed receiver was exported, allowing another app to send internal control messages. Once MSG_DOWNLOAD_URL was added, this included arbitrary URL, header, timeout, and ResultReceiver input, creating a request and success oracle through the user's active tunnel.

Implementation

The app sends eligible requests to the daemon process, which downloads them through the running core and an explicit outbound. Ordinary profiles use proxy; primary policy groups resolve balancer-main and use its first non-empty principle target.

One shared eligibility decision now controls connection-info and app-owned download routing. It selects the core only for native Xray TUN with the local proxy disabled, and excludes HEV, root, and root-LAN configurations because those modes force a local proxy regardless of the visible setting.

The application update checker uses the same core download bridge for GitHub release metadata. Once the daemon accepts an eligible request, a transfer failure is reported instead of silently retrying outside the tunnel. The eventual APK link still opens in the user's browser, whose traffic is handled by the VPN normally.

Subscription headers, custom user agents, custom Host authorities, and embedded URL credentials are preserved. Binary and large responses are streamed through a UUID-constrained cache file, avoiding string corruption and Binder payload limits.

Asset updates use a separate UUID staging file for every attempt. This prevents overlapping updates from writing through the same temporary inode. A downloaded asset is promoted only when it is non-empty; direct HTTP downloads also reject unsolicited partial-content responses and declared-length mismatches. The AndroidLib method writes through a sibling temporary file and atomically replaces its destination only after the transfer completes, so network, write, or close failures preserve the previous file.

The internal service-action receiver is separate from the screen-state receiver and registered with RECEIVER_NOT_EXPORTED. System screen broadcasts keep their existing receiver behavior. URL downloads run in a service-owned SupervisorJob scope; stopping the core cancels the scope and prevents a cancelled request from delivering a late ResultReceiver callback. The conflict resolution retains upstream request IDs, cancellation callbacks, and the dedicated connection-test scope while keeping URL downloads independently owned by the core lifecycle.

Fallback behavior remains deliberate:

  • native Xray TUN with local proxy disabled: use the running core
  • daemon unavailable: application-update metadata retains its existing direct fallback; subscription refresh reports failure rather than bypassing the selected route
  • accepted core request fails: report failure instead of silently bypassing the tunnel
  • local proxy enabled, HEV TUN, root mode, root-LAN sharing, and proxy-only mode: retain their existing paths

For strategies that expose several principle candidates, policy-group selection is intentionally best-effort and does not advance random or round-robin state.

AndroidLib dependency

This branch updates the AndroidLibXrayLite gitlink to 2dust/AndroidLibXrayLite#205, which provides:

  • CoreController.GetUrlContent(url, outboundTag)
  • CoreController.GetBalancerPrincipleTarget(balancerTag)
  • CoreController.DownloadUrlToFile(url, outboundTag, headersJSON, filePath, timeoutMillis)
  • CoreController.DownloadUrlToFileWithHeaders(...) to preserve response metadata such as subscription usage headers
  • correct Go handling for custom Host authorities
  • transactional file replacement and response-length validation for downloads

Validation

On app head f6b84c9e7, merged with upstream 57907cf35 (2.3.15), using AndroidLib #205 at 9057fa777 and HEV 2.19.3:

  • Focused routing, connection-info, HTTP download, subscription metadata and application-update regressions passed.
  • Play Store and F-Droid debug JVM suites: 144 tests each, zero failures/errors.
  • Both distributions passed Kotlin compilation and ARM64 debug APK assembly.
  • All three packaged ARM64 native libraries match their verified inputs.
  • AndroidLib v2rayNG无法使用 疑似在下载内容 #205 and 测试中,使用流量并没有走v2ray,不知道是否是bug #204 both passed go test -race ./... and go vet ./... after merging upstream 2ffe5f794 (v26.10.31).
  • The rebuilt v2rayNG无法使用 疑似在下载内容 #205 AAR includes all four Android ABIs, three geodata assets and the required generated APIs.
  • git diff --check passed. All three branches were updated with merge commits and ordinary fast-forward pushes.

Not run: live native-Xray-TUN connection-info, subscription/asset/application-update downloads, sender-boundary and service lifecycle scenarios on the updated heads. No ADB device was attached; existing emulator processes had unresolved ownership and were left running. Compilation and JVM/Go tests do not establish device behavior.

The native repository's Actions runs are marked action_required before any jobs start. Maintainer approval is needed for hosted CI; no failing CI test job was recorded.

Fixes #5523

@eliotcougar
eliotcougar marked this pull request as ready for review August 18, 2026 15:51
@2dust

2dust commented Aug 20, 2026

Copy link
Copy Markdown
Owner

关闭了本地端口的用户,只是实现测试连接还是不够的;因为更新订阅和下载geo 等功能也是要依赖这个本地端口。
所以需要找到能解决上面所有问题的方法,不然只实现测试不够

@eliotcougar
eliotcougar marked this pull request as draft August 20, 2026 07:12
@eliotcougar

Copy link
Copy Markdown
Contributor Author

关闭了本地端口的用户,只是实现测试连接还是不够的;因为更新订阅和下载geo 等功能也是要依赖这个本地端口。 所以需要找到能解决上面所有问题的方法,不然只实现测试不够

In case of Assets and Subscriptions, should we let users choose "Update without proxy" vs "Update through proxy", like in v2rayN?..

@eliotcougar
eliotcougar force-pushed the codex/xray-tun-connection-info branch from 09da5be to 0c2a141 Compare August 20, 2026 12:31
@eliotcougar eliotcougar changed the title Restore connection info in Xray TUN mode Use native Xray TUN for connection info and updates Aug 20, 2026
@eliotcougar
eliotcougar marked this pull request as ready for review August 20, 2026 13:09
@eliotcougar

Copy link
Copy Markdown
Contributor Author

Security follow-up pushed in a00589a.

The daemon's dynamic receiver previously combined BROADCAST_ACTION_SERVICE with ACTION_SCREEN_ON/OFF and used the exported receiver flag on Android 13+. Setting the destination package limited where the intent went, but did not authenticate who sent it. After MSG_DOWNLOAD_URL was introduced, another app could therefore supply an arbitrary URL, headers, timeout, and ResultReceiver, using the active Xray connection as a request/success oracle. The same receiver also exposed the other internal service-control message keys.

The fix separates the two trust boundaries:

  • BROADCAST_ACTION_SERVICE is registered on an app-private RECEIVER_NOT_EXPORTED receiver.
  • System screen-state broadcasts retain a separate receiver with the existing flags.
  • URL downloads use a service-owned SupervisorJob + Dispatchers.IO scope.
  • Core shutdown cancels pending downloads, and cancellation is checked before sending the ResultReceiver callback.

Validation on an API 33 emulator confirmed that an external shell-UID stop message was not delivered and the tunnel remained connected, while the app's own UI stop message still worked. The focused unit test and Play Store debug build also pass.

@2dust, a related but broader privacy issue is that existing code still writes some complete subscription/configuration/download/WebDAV URLs, and some URL-bearing exception messages, to Logcat. Android's guidance recommends removing sensitive values and keeping production log messages predictable: https://developer.android.com/privacy-and-security/risks/log-info-disclosure

Would you be open to a separate, small PR that removes those URL values and retains only operation names and safe status codes? I kept that cleanup out of #6109 to avoid expanding this PR's scope and merge noise.

@eliotcougar
eliotcougar force-pushed the codex/xray-tun-connection-info branch 2 times, most recently from 83a2eff to d6eb2c3 Compare September 11, 2026 16:25
Use the active Xray core to fetch the configured connection-info URL when VPN mode runs with Xray TUN and the local proxy is disabled. This restores the country and IP result without requiring a local proxy inbound.

Preserve the existing proxy-based path for configurations that expose or force the local proxy, including HEV and root modes. Pin AndroidLibXrayLite to the new GetUrlContent API.
Pass the app proxy tag to the core-backed URL fetch instead of leaving the request to normal routing. This prevents direct or alternate routing rules from changing the country and IP reported by the current-connection test.

Advance AndroidLibXrayLite to the explicit outbound API so Xray TUN retains connection-info parity when the local proxy listener is disabled.
Resolve the primary balancer's first principle target when the running profile is a policy group, then fetch connection metadata through that concrete outbound. Keep the existing proxy-tag path unchanged for all other profiles.
Use the running core to download subscriptions and asset files when native Xray TUN is active without a local proxy. Stream responses through a shared cache file so binary geodata stays intact and large payloads never cross Binder, while preserving subscription headers and the existing proxy/direct paths for other modes.
Use per-attempt staging files so overlapping updates cannot corrupt one another. Reject empty, unsolicited partial-content, and length-mismatched responses, and advance AndroidLib to its atomic file-replacement implementation.
The service receiver shared its filter with system screen broadcasts and was exported on Android 13+, allowing external apps to send internal control messages, including URL download requests through the active core.

Split screen-state handling into its own receiver and register the internal service action as not exported. Run downloads in a service-owned scope so shutdown cancels pending work and suppresses late ResultReceiver callbacks.
The upstream merge in 4bae3a4 retained both upstream's proxy-based IP
lookup and this branch's core-aware lookup. A successful connection test
therefore queried the endpoint twice and could publish two results. In
native Xray TUN mode it also tried the local proxy even when that listener
was disabled.

Build one complete ConnectionTestResult after a single mode-appropriate
lookup, then publish it once. Native TUN keeps using the active core and
outbound; HEV, proxy-only and root modes retain their existing proxy path.
Failed delay tests skip enrichment, and unavailable IP information does
not discard a successful delay result.

Reuse the existing service-owned URL-request scope and check cancellation
before enrichment and delivery, so connection-test work does not publish
a stale result after its core session ends. Keep the deterministic result
assembly in SpeedtestManager, with regression tests for successful, zero,
failed and unenriched results.

Validation: all 63 Play Store unit tests, Kotlin compilation and four-ABI
debug assembly passed. API 37.1 Pixel 9 Pro emulator checks passed in HEV
mode and native Xray TUN mode with the local SOCKS proxy disabled. The HEV
check recorded one IP-info endpoint connection per successful test.
Replace the obsolete SOCKS-only warning with wording explaining that subscription updates and similar actions use the active VPN tunnel when the local proxy is disabled.

Update the summary in all nine supported locales without changing setting behavior.

Validation: locale XML checks, git diff --check, and :app:assemblePlaystoreDebug passed.
Use the core download bridge for GitHub release metadata when native Xray TUN is active without a local proxy. Once the daemon accepts a request, keep failures on that path instead of bypassing the tunnel; preserve the existing direct and local-proxy behavior in other modes.

Share one eligibility decision across connection info and app-owned downloads, excluding HEV, root, and root-LAN modes where a local proxy is forced. Advance AndroidLib for correct custom Host handling and cover the routing decisions with focused unit tests.
Restore the Utils import still required by native asset-download staging. Upstream removed its old built-in-row UUID use, but this branch must retain unique temporary download paths and validation before replacing an asset.

Rebased onto upstream 2.3.8 with AndroidLibXrayLite b4a7cad. The matching four-ABI AAR, native Go and race tests, and app Play Store debug compilation, manifest processing and JVM tests pass.
@eliotcougar
eliotcougar force-pushed the codex/xray-tun-connection-info branch from d6eb2c3 to 252e262 Compare September 22, 2026 16:32
Resolve shared-resource conflicts without dropping feature-specific semantics or current upstream translations. Retain upstream service and UI updates, and migrate feature regression tests to the upstream JUnit Platform setup.

Validation: PlaystoreDebug JVM suite, Kotlin compilation and APK assembly passed. All declared ABIs contain the current Xray library and both HEV libraries. Full device and OEM lifecycle regression coverage was not run.
Stop resolving the custom library gitlink to an older upstream release tag. Build AndroidLibXrayLite at the checked-out source revision with the workflow NDK and its pinned Go mobile tools, including the assets and all four default Android ABIs. Keep HEV packaging and release signing unchanged so required native-TUN APIs are present in clean CI builds.
Resolve the subscription-update conflict by retaining upstream SubscriptionUsageInfo capture through the daemon/core download path. Forward final response headers alongside the completed body, then persist or clear account metadata only after a successful subscription import.

Pin AndroidLibXrayLite to db309b146a17698bf1029989b19fd7007a0daa98, whose compatible DownloadUrlToFileWithHeaders API retains selected-outbound routing and transactional downloads. Eligible native-TUN subscription requests fail closed on core failure, daemon unavailability, or empty content; other modes retain their existing HTTP behavior. Preserve upstream pill-group UI, Kotlin/Gradle versions, and Azerbaijani locale, updating that locale for the local-proxy setting.

Validation: 30 focused JVM tests and the full 133-test Play Store debug JVM suite passed without failures or skips; Kotlin compilation and x86_64 debug assembly passed using the freshly built four-ABI AAR. Packaged JNI bytes match that AAR and both HEV libraries match official v2.3.13 inputs. Instruction-file staging gates and whitespace checks passed. Android IPC, native-TUN live routing, and service runtime scenarios were not run because the parent owns the VM.
Resolve AndroidLibXrayLite to the URL-request feature branch merged with upstream v26.10.31. This keeps outbound-aware URL downloads and response headers while adopting the current Xray core. Retain upstream DNS handling, WireGuard fixes, and HEV 2.19.3.
Keep the early visual delay result and use the active outbound for IP lookup when required. Preserve asset replacement failure reporting across both download paths and pin the corresponding AndroidLibXrayLite merge.
Track the AndroidLibXrayLite revision that keeps URL request and observatory tests independently mergeable. Production native source is identical.
Use the native outbound resolver for IP lookup and downloads so they honor a configured fallback during observatory warm-up.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Country and IP of the server after the connection test missing with dynamic port, user and password

3 participants