Repository navigation
Add Shizuku-powered rootless USB and Wi-Fi tethering - #5903
eliotcougar wants to merge 9 commits into
Conversation
|
@2dust Do you want me to try trimming down and simplifying this PR more over the weekend? Rootless tethering is a really cool and useful feature to have. I've tested it, it works well on my Pixel 9. |
9c1f7a0 to
9d3c593
Compare
|
I've spent way too much time chasing this random issue where enabling tethering can occasionally choose a physical interface instead of testtun, and pass traffic from tethered device around v2rayNG straight to clearnet... Random bugs are the worst...
|
|
感谢你的 PR
请问是否总结的到位? |
It no longer requires API36+, it now works all the way to Android Correction: Apparently, setPreferTestNetworks doesn't exist in Pixel 5 API 30 framework... AI lied to me... The earliest is API33 Android 13... Just confirmed it running on Pixel 6a API33 image...
Installing Shizuku isn't difficult, and it updates very infrequently. It's basically a slightly elevated UID with adb-level access the apps can use.
We can look into it if IPv6 is something people need. I didn't prioritize it, and I can't really test it on my hardware.
Not really. Only if an OEM makes effort to clean up hidden APIs when making their firmware. They are lazy. I don't think they do. Maybe you know more about the state of the industry?
I think it is isolated enough to be easily removable if Android for some reason removes the necessary API. However, since it is probably something they use internally for debugging, I doubt it'll happen in the near future. I haven't worked on streamlining the main |
I think we'll have to put Shizuku Tethering behind API33+ gate after all… There was a promising workaround for API32, but it is quite invasive and absolutely not guaranteed to work on anything other than AOSP - creating a tap interface and a Virtual Carrier Network, and then routing tethering traffic through it. |
81114f3 to
8e29c74
Compare
|
I've installed a combined build with Shizuku Tethering and all the other features I've been trying to implement lately onto my phone. Tomorrow I'll turn off v2rayN on my PC and be using Tethering to connect to the Internet... |
|
The real-world test succeeded through the whole day of work through USB tethering. All traffic was routed correctly through v2rayNG while using a policyGroup connection. IPv6 support was added. It seems to be working in the emulator, but I cannot test it because I have no real IPv6 connectivity here. As a final stroke, I changed the two large buttons into toggle switches like everywhere else in the app. The feature looks more or less complete at this point. I think it is ready. |
|
Just discovered that starting v2rayNG tethering when there was already an active system tethering shows v2rayNG tethering active, but doesn't actually switch to |
|
Patched a couple of potential (rare, unlikely) traffic-leak scenarios where Android might silently decide to start routing tethered clients traffic directly. Fail-closed enforcement is very important: after the user enables protected routing in the app, until it is disabled, it should either route through the protected |
|
I think this can be a seperated app "Shizuku tether" so it can work with another VPN app not just V2RayNG |
|
I suggest request this feature to be added into https://github.com/Mygod/VPNHotspot/issues if possible |
The way Android does tethering pass-through to a VPN app (via testtun) makes arbitrary routing unviable. Basically, without root there is not much control over where the testtun binds itself. The current implementation keeps main connection and tethering connection synchronized at all times and allows for strict "fail-closed" operation. Without access to v2rayNG internal states that would be difficult to promise. |
🚀 Trend Deep Tech Advance (TDA) — TDA Mox Solution
إذا كنتم تواجهون مشاكل في اتصال الـ Shizuku أو استقرار الـ Shell environment في الأنظمة الحديثة، فإليكم الحل الجذري: ✨ استكشف TDA Mox: Stay tuned for our upcoming major updates! نرحب بمساهماتكم وآرائكم دائماً. |
|
Ai Slop? |
Primarily, yes... GPT5.6-Sol on xhigh. |
well it's an app used by many, I request not to use vibe here, 4k LOC is hard to review thoroughly. LLM assisted programming is good when you know what you are doing, but if thats not the case then you will have no idea about whats its doing, "It works" != "its reliable and good piece of code". I'm not discouraging you to contribute on opensource., I'm just suggesting not to make huge change which you don't understand. Thanks |
I'm not insisting to merge it as soon as possible. It'll have its day. Don't dismiss it only because "it's made with AI". Don't forget there is also an LLM-assisted code-review. |
lil bro, this need to be tested on a real device, ai assisted code review isn't enough here |
I'm testing the code I commit on my own phone first, including letting Codex control it and run targeted tests through adb. |
|
Reconciled this PR with the repository's new AGENTS.md guidance in 0d814cd. The Compose activity/screen now remain presentation-only behind immutable ViewModel state and actions; service setup, teardown, and Shizuku recovery have explicit ownership, failure isolation, stable profile IDs, and deterministic decisions; and API 36+ uses the typed TetheringManager API while API 33-35 reflection is isolated in one documented compatibility adapter. Focused lifecycle/UI regression tests were added for those decisions. Validation: the focused tests and full Play Store debug unit/compile suite pass, and native Xray TUN plus HEV TUN were exercised on API 33 and API 37.1, including fail-closed stop and recovery. Lint continues to report only the four existing findings in untouched root/theme files. |
|
Hi, I'm GPT-6 Astra helping eliotcougar review and maintain this PR. This update follows a review of the Shizuku implementation, with emphasis on traffic-leak protection, lifecycle correctness, and keeping the code understandable without introducing another abstraction layer. The changes are split into two commits:
The lifecycle fixes also reject duplicate starts before touching existing leases, pair configuration with its exact main-core launch, and prevent delayed recovery from undoing an explicit Stop. Long-running work now belongs to the UserService rather than a broadcast's timeout. UI teardown does not wait for the routing lock, completed remote operations retain their session-token bookkeeping, and errors that still own a protected route remain stoppable. HEV startup and worker health are checked directly. For maintainability, warning state and backend health checks are consolidated, redundant wrappers/state are removed, and comments explain the resource invariants where they matter: WAITING retains a dead protected TUN; ERROR does not necessarily mean resources were released; session identity is distinct from launch identity; emergency shutdown is deliberately outside normal lifecycle ordering. No state-machine framework or additional service-file split was added. The production diff is 19 lines smaller overall, despite the added explanations. Validation: Play Store x86_64 debug and instrumentation APKs built, and all 80 JVM tests passed. Native/HEV lifecycle scenarios were exercised on API 33 and API 37.1 during the review. After the final consolidation, five focused API 37.1 checks passed, covering pause/resume, unsafe-upstream shutdown while configuration loading is blocked, one-shot warning consumption, and HEV worker failure. UI Start → reopen → Stop also passed without stopping the primary VPN. The last change was comments only. These checks do not establish universal OEM compatibility or prove zero packets can escape before Android reports an upstream change. The implementation reacts immediately to that report and retains the protected route when safe teardown cannot be confirmed. Physical USB/client traffic and the broader compatibility matrix were not rerun for this update. The earlier lint run still reports four unrelated existing errors; no suppressions were added. The PR description now reflects the current synchronization, safety, status, and compatibility behavior, with the test scope and remaining limitations called out explicitly. |
Share Wi-Fi and USB tethered traffic through the selected tunnel without root. Keep lifecycle and protected-TUN ownership explicit, fail closed across core restarts, and release only resources owned by the current session. Consolidate the reviewed feature on upstream 2.3.8. Preserve the shared HEV configuration builder and escaped YAML credentials, align blank-timeout parsing and the log-level default with upstream, and retain the focused lifecycle and configuration tests.
db8714e to
77ae038
Compare
Resolve CoreServiceManager conflicts by retaining upstream connection-test cancellation on stop and reload alongside Shizuku pause/clear hooks, receiver ownership, and serialized native teardown. Preserve upstream request IDs and cancellation acknowledgements without changing tethering behavior. Validation: Play Store release assembly, debug Kotlin compilation, 104 JVM tests, and git diff --check passed. Emulator testing omitted at user request.
Explain Shizuku, Android test networks, and both tethering backends before walking reviewers through the implementation in source-reading order. Document process and resource ownership, session versus launch identity, startup, shutdown, synchronization, and recovery. Make the protection boundaries and operational quirks explicit, including callback-driven upstream shutdown, retained dead TUNs, independent native-engine state, DNS and IPv6 diagnostics, and hidden-API removal conditions. Provide static-review checklists, an honest map of existing test coverage, and a device/client validation matrix for future maintenance. Documentation only; no runtime or configuration changes. Verified repository links, contents anchors, reference definitions, and git diff --check. The branch already includes the current upstream/master.
|
Hi, I'm Codex, helping eliotcougar maintain this PR. Added SHIZUKU_TETHERING.md in 1ea6311 to make the implementation easier to review methodically and maintain after merging. The PR description now links to it near the beginning. The guide starts with the basics of Shizuku, Android tethering, and test TUNs, then follows the actual code through:
It also explicitly documents the limits of callback-driven fail-closed protection, the independent runtime state of the secondary native core, retained-resource error states, and other quirks that are easy to miss in a code-only review. The checklist is not presented as a completed test report or a universal compatibility guarantee. The branch already contained the latest upstream/master when checked, so no additional merge or conflict resolution was needed. This commit adds documentation only. Repository links, contents anchors, reference definitions, and whitespace checks passed. Builds and emulator/device tests were not run for this documentation-only update. |
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.
Enable new tethering and routing starts only for a running VPN core, not proxy-only or root cores. Recheck the daemon snapshot before binding routing parameters. Retain Stop for existing sessions and hotspots, and do not overwrite a specific local failure with a generic Binder error. Reuse the existing localized VPN-mode guidance.
|
@eliotcougar Hi! Could you please provide a prebuilt APK for testing this PR, or upload the APK as a GitHub Actions artifact? I'd like to test the Shizuku-based tethering feature on Android 13 with rootless. Thanks! |
I'm not sure I'm allowed to give people custom builds of v2rayNG without permission from @2dust |
Integrate upstream/master 01b4630, retaining subscription response-header usage metadata, the subscription information card, pill group navigation, current Kotlin/Gradle versions, and upstream native dependency gitlinks. Preserve fail-closed tethering ownership and daemon launch snapshots. Starting protected tethering still requires a running VPN snapshot; proxy-only and root cores remain ineligible, while stopping already-owned routing or hotspot resources remains available. Keep launch/session identity, permission-aware handling, and HEV/native-Xray paths intact. Add all 54 feature strings to the new Azerbaijani catalog without splitting resource catalogs. Validation: all 139 Play Store debug JVM tests passed, including tethering eligibility, recovery, teardown, HEV configuration, and subscription metadata regressions. Kotlin compilation and x86_64 debug assembly passed; all three required packaged native libraries hash-match the official upstream inputs. Locale XML, feature-key coverage, placeholders, whitespace, and instruction-file staging gates passed. Not run: Shizuku permission/Binder, privileged Wi-Fi/USB tethering, fail-closed recovery, IPv6 traffic, and VPN/proxy-only/root runtime scenarios; VM/adb use was excluded.
Retain upstream DNS finalQuery handling and server ordering, HEV 2.19.3 root forwarding safeguards, and current Xray core dependencies alongside the Shizuku lifecycle and protected-network lease. Extend the existing hotspot configuration regression to verify that ordered DNS entries and finalQuery survive creation of the secondary TUN-only core.
Reserve separate IDs for Shizuku messages so hotspot queries no longer share the subscription cancellation ID.
Summary
This PR adds rootless tethering that routes devices connected through Android's Wi-Fi hotspot or USB tethering through the active v2rayNG connection. Fixes #5898.
Reviewer guide: Shizuku tethering: implementation and reviewer guide. Starts with Shizuku and test-network fundamentals, then provides a source-linked reading order, lifecycle and failure-path explanations, compatibility boundaries, and a methodical review and validation checklist.
The privileged Android networking operations run in a user-approved Shizuku UserService under the shell UID. The implementation does not require root, modify iptables, or replace Android's DHCP, NAT, forwarding, or hotspot management.
Highlights:
hev-socks5-tunnelbackendsUser-facing behavior
On Android 13+, a Tethering item appears in the navigation drawer below Backup & Restore. The page shows:
Starting the hotspot from this page establishes the protected route before enabling the downstream. USB tethering can be enabled from Android settings and is attached to the same protected upstream while v2rayNG tethering is active. Enabling protected routing while tethering is already active safely restarts and validates the existing downstream instead of trusting its previous upstream.
Motivation
Android's normal
VpnServiceprotects traffic originating on the Android device. Traffic forwarded by Android's tethering stack does not normally enter that VPN, so hotspot and USB clients can bypass v2rayNG.Root solutions can redirect forwarded traffic through firewall and policy-routing rules. This implementation instead gives Android's own tethering stack a protected test network as its upstream, making the feature usable on locked, non-rooted devices where the required platform behavior is available.
Working principle
1. Shizuku provides a narrowly scoped privileged process
After permission is granted, v2rayNG binds a daemon-style Shizuku UserService. It runs as Android's shell UID and performs only the platform operations unavailable to an ordinary app process: creating and publishing a test network, asking tethering to prefer test networks, observing the active upstream, and starting or stopping tethering downstreams.
The regular application does not gain system networking permissions. Shizuku remains the authorization boundary and its permission can be revoked by the user.
2. The running core supplies its exact configuration
The main v2rayNG core records the configuration and settings that were actually used to start the active VPN connection. The metadata snapshot includes the selected profile name, tunnel backend, VPN DNS addresses, IPv6 state, MTU, HEV settings, SOCKS endpoint and optional authentication, and a unique main-core launch ID. The generated core configuration remains in the main-core process and is captured together with that metadata as one immutable launch.
Using the running snapshot is important: rebuilding from current preferences could produce a different route after the user has edited settings but before the core has restarted. Large engine configuration data is streamed through an app-private Binder lease instead of being placed directly in Binder transactions or world-readable temporary files.
Configuration reads must match that launch ID. The separate tethering-session token survives ordinary core restarts; it does not authorize an obsolete configuration. A delayed update therefore cannot combine old metadata with a newer core configuration.
Protected tethering requires the main connection to be running in VPN mode.
3. Android receives a protected test-network TUN
The UserService uses
TestNetworkManagerto create a kernel TUN and publishes it as an Android test network. It then calls the hiddenTetheringManager.setPreferTestNetworks(true)method so Android's tethering stack can select that network as its upstream.Android continues to own the Wi-Fi/USB downstream interface, DHCP, forwarding, NAT, DNS proxying, carrier checks, and tethering lifecycle. v2rayNG consumes only the traffic Android writes into the test TUN.
The test network uses the same DNS address list advertised by the running v2rayNG VPN. When local DNS is enabled, the generated core configuration intercepts that DNS traffic; when it is disabled, those addresses remain normal routed DNS destinations. No external DNS resolver is hardcoded for tethering.
4. The selected tunnel backend consumes the traffic
HEV mode
A second HEV instance runs in the Shizuku process and consumes the test TUN. It forwards traffic to the SOCKS inbound of the main v2rayNG core, allowing the tethered traffic to use that core's outbounds and routing. HEV mode therefore requires the local SOCKS inbound to be enabled and reachable.
Native Xray TUN mode
A second Xray controller runs in the Shizuku process. Its configuration is derived from the exact running Xray configuration. Non-TUN inbounds are removed to avoid colliding with listeners already owned by the main core, while outbounds, DNS, routing, balancers, observatory settings, and supporting configuration are retained.
5. Profile and service lifecycle stay synchronized
The main core sends authenticated, ordered lifecycle updates when it stops, starts with a new profile/configuration, or fails to restart. The tethering service keeps the protected test network where possible, stops the old secondary engine, starts the replacement engine from the new running snapshot, and restores the previously active tethering types.
Lifecycle notifications use one-way Binder calls: the broadcast receiver hands off work, and a UserService-owned queue performs the potentially lengthy native and Android operations. Returning from the Binder call is not an acknowledgement that routing has completed. Duplicate starts are rejected before touching the existing lifetime lease, and only a fresh UserService may recover a missing session; delayed updates cannot undo an explicit Stop.
This makes profile changes and ordinary service restarts follow the main connection with only a short interruption. If an in-place engine switch is unsafe, the implementation stops downstream tethering before rebuilding the protected route and restores it afterward.
6. Fail-closed protection is continuous
Selecting a preferred test network and starting a downstream are separate Android operations. During that handover, or after a later connectivity change, Android may temporarily select a physical upstream such as
eth0, Wi-Fi, or cellular.The UserService continuously observes
TetheringManagercallbacks and resolves the reported upstream throughConnectivityManager/LinkProperties; it does not poll or parsedumpsysoutput. If any active or pending downstream is reported on an interface other than the owned test TUN, the service immediately requests stops for all known downstreams while retaining the test network. This emergency path does not acquire the lifecycle monitor or wait for each stop acknowledgement, so a blocked configuration read, native startup, or retry cannot hold it up. A rejection counter prevents an overlapping start from reporting success after emergency shutdown. The UI is notified through a one-way Binder callback and displays the resulting disabled state without waiting for a manual refresh.A single long-lived callback registration supplies the upstream and downstream snapshots used by status, postcondition checks, and emergency shutdown. On API 33–35, the implementation reads the callback's supplied
Set<TetheringInterface>through reflection rather than querying a separately updated manager cache or guessing types from interface names. API 36+ retains the typed adapter.The initial handover is also validated. v2rayNG waits and retries once when Android chooses the wrong upstream; only a repeated failure cancels tethering and asks the user to wait briefly and try again.
The main core and Shizuku UserService share lifetime ownership of the protected test network. If either process dies, the surviving side keeps the dead TUN in place so Android cannot silently fall back to direct tethering. Main-core Binder death stops the secondary engine. When Shizuku returns, routing is reconstructed from the current core snapshot and the saved downstream state is restored. Android 14+ may defer Shizuku's Binder delivery while the app is cached, so recovery is explicitly requested as soon as v2rayNG returns to the foreground.
Disabling protected routing follows the same safety rule: downstream tethering is stopped before the test network is removed. If Android cannot confirm that downstreams stopped, the protected route is retained rather than knowingly exposing clients.
7. Status reflects retained resources and engine health
HEV startup checks the JNI result, and status/readiness checks use the native worker's running state rather than the existence of its configuration file. A small service-owned health check detects unexpected secondary-engine exit and notifies the UI. An error can still own a protected TUN/session, so Stop remains available even when the main core is no longer running.
The ViewModel keeps completed Binder mutations and their session-token bookkeeping together off the UI thread, including across screen teardown and reopening. Listener removal does not wait for the routing lifecycle monitor, and binding has a bounded timeout so the screen can be retried.
Comments beside the state and ownership declarations explain the distinctions between active routing, a paused fail-closed session, pending Android downstreams, and resources retained after an error. The implementation keeps the existing structure: no generic state-machine framework or additional service-file split was introduced. Warning state and backend health checks are consolidated, and redundant status fields, wrappers, and interface-name heuristics are removed.
IPv6 behavior
The existing Enable IPv6 setting controls tethering as well as the main VPN:
Requesting IPv6 does not guarantee that Android will delegate an IPv6 prefix to every tethering downstream. Carrier, upstream, device, and OEM tethering behavior can still produce IPv4-only service. For this reason, the Tethering page inspects each active Wi-Fi and USB downstream and reports the actual result as IPv4-only, IPv4+IPv6, or unknown.
Routing semantics
Tethered clients use the active profile's network-based routing behavior, including domain, destination IP, port, protocol, balancer, observatory, and other rules available to the secondary engine.
Per-app and process-based rules cannot apply to tethered clients because their traffic is forwarded by Android and has no originating Android application identity. The UI calls this out explicitly.
Android and Shizuku requirements
The application keeps its existing
minSdkof 24, but this feature is resource-gated and completely hidden below Android 13 / API 33. Its activity, synchronization receiver, Shizuku provider, and drawer entry are disabled on older releases.API 33 is the practical baseline because this design depends on Android's test-network preference path and compatible hidden tethering behavior. Investigation on API 30–32 found no viable equivalent that could be expected to work on normal, non-rooted hardware. Android 13–15 use the compatible legacy tethering stop/state path; Android 16+ use the newer typed tethering APIs where available.
Additional requirements:
test_networkservice and compatibleTestNetworkManagermethodsTetheringManager.setPreferTestNetworks(boolean)behaviorRelevant platform references: TetheringManager, TetheringEventCallback, AOSP TestNetworkManager, and AOSP TetheringManager.
Device compatibility warning
Passing the API-level gate does not guarantee compatibility. The implementation intentionally relies on hidden/System API behavior that is not a stable third-party application contract. An OEM may remove or change methods, restrict shell networking permissions, customize upstream selection, replace parts of the Connectivity/Tethering module, or impose additional hotspot entitlement and background-execution restrictions.
Shizuku setup itself can require vendor-specific developer options or background allowances on MIUI/HyperOS, ColorOS, Flyme, EMUI, Sony firmware, hardened Android distributions, and other heavily customized systems. See the Shizuku setup guide.
The fail-closed design protects the loss of either the main core or the Shizuku service while the other lifetime holder survives. Simultaneous termination of both processes removes every process capable of retaining or controlling the protected network and therefore cannot be guaranteed safe by an ordinary non-root app.
Potential conflicts
Users should not combine this feature with software that controls the same global tethering state, including:
Android normally permits only one active
VpnService; replacing v2rayNG with another VPN invalidates the main connection that the protected tethering engine follows.The feature uses Android's existing saved hotspot configuration. It does not manage SSID, password, band, channel, client allowlists, carrier entitlement, or device-policy restrictions.
Security and trust considerations
The native Xray path provides the Shizuku UserService with the exact running Xray configuration, which may include server credentials. HEV mode provides the local SOCKS credentials required to reach the main core. Users must therefore trust both Shizuku and the installed v2rayNG build before granting permission.
Internal synchronization is package-scoped, non-exported, ordered, protected by a random per-session token, and tied to Binder lifetimes. Engine configuration is streamed through an app-private Binder lease. Temporary HEV configuration is removed during cleanup, and stale or unauthenticated synchronization sessions are rejected.
Validation
Synchronized head
fc8e9ceb7includes upstream57907cf35(2.3.15), Xray library v26.10.31 and HEV 2.19.3.finalQuerysetting survive creation of the TUN-only core.libgojni.so,libhev-socks5-tunnel.soandlibhevsockstun.so, matching the verified input files.git diff --checkpassed. The branch was synchronized with a merge commit; no history rewrite is required.Not run on this synchronized head: emulator/physical-device Shizuku routing, USB/hotspot client traffic, IPv4/IPv6 diagnostics, native/HEV startup and failure/recovery lifecycle scenarios, or the TalkBack/keyboard/D-pad/theme/OEM matrix. No ADB target was available and existing emulator processes had unresolved ownership.
Earlier revisions received native/HEV lifecycle and retained-TUN fault-injection checks on API 33 and API 37.1, plus Wi-Fi/USB routing tests including the user's Pixel 9 Pro. Those historical results do not establish runtime behavior of this synchronized revision.
Known limitations