diff --git a/SHIZUKU_TETHERING.md b/SHIZUKU_TETHERING.md new file mode 100644 index 00000000000..3e55b1a07f6 --- /dev/null +++ b/SHIZUKU_TETHERING.md @@ -0,0 +1,569 @@ +# Shizuku tethering: implementation and reviewer guide + +This document explains the rootless tethering implementation from its Android prerequisites to its failure paths. It is a reading guide and review checklist, not a claim that every scenario below has passed on every device. Read it alongside the source in the same revision; test results belong to a separately recorded build, device, and configuration. + +The feature's central idea is simple: **give Android tethering a TUN-backed upstream, then let v2rayNG consume the packets from that TUN.** Most of the lifecycle code exists because creating that upstream, starting a hotspot, changing a core configuration, and terminating a process are not one atomic Android operation. + +## Contents + +1. [Foundations: Shizuku, tethering, and testtun](#1-foundations-shizuku-tethering-and-testtun) +2. [Scope and platform boundary](#2-scope-and-platform-boundary) +3. [Code map and suggested reading order](#3-code-map-and-suggested-reading-order) +4. [Processes, resources, and identities](#4-processes-resources-and-identities) +5. [Routing state versus Android tethering state](#5-routing-state-versus-android-tethering-state) +6. [Startup and shutdown walkthrough](#6-startup-and-shutdown-walkthrough) +7. [Profile changes, process death, and recovery](#7-profile-changes-process-death-and-recovery) +8. [Upstream protection and its limits](#8-upstream-protection-and-its-limits) +9. [Configuration, DNS, IPv6, and routing semantics](#9-configuration-dns-ipv6-and-routing-semantics) +10. [Concurrency, IPC, and bounded waits](#10-concurrency-ipc-and-bounded-waits) +11. [UI and status interpretation](#11-ui-and-status-interpretation) +12. [Compatibility adapters and removal conditions](#12-compatibility-adapters-and-removal-conditions) +13. [Security, conflicts, and operational quirks](#13-security-conflicts-and-operational-quirks) +14. [Methodical review and validation](#14-methodical-review-and-validation) +15. [Maintaining this feature](#15-maintaining-this-feature) + +## 1. Foundations: Shizuku, tethering, and testtun + +### What Shizuku contributes + +An ordinary Android application runs under its own restricted UID. Declaring a permission in its manifest does not grant privileged control over Android networking. + +[Shizuku][shizuku-api] lets a user-authorized application execute code in a separate privileged process. On a non-rooted device it is started through ADB and uses the shell identity, UID 2000. Its UserService mechanism loads application-supplied Binder code into that separate process. The application talks to it through IPC; the application's own UID does not become shell. Non-root Shizuku normally needs restarting after a device reboot. + +This implementation is designed around that shell process. `ShizukuTetheringService` is an AIDL implementation hosted by Shizuku, **not** another ordinary Android foreground `Service`. The binding is daemon-style, so closing the Tethering screen does not stop it. Shizuku itself, the UserService it hosts, and the main v2rayNG core are different lifetime participants. + +The UserService calls Android framework APIs directly. It does not run a terminal script, install firewall rules, or parse `dumpsys` to perform normal operations. `ShellContextCompat` gives those framework calls package attribution matching `com.android.shell`; possessing the shell UID alone does not make an app-attributed context suitable for these calls. + +### Why the existing VPN is not enough + +The main v2rayNG VPN obtains a virtual interface through Android's [VpnService][vpn-api]. Android routes selected device-originated traffic into that interface. Android tethering, however, has its own forwarding and upstream-selection machinery. A connected laptop's packets do not automatically become traffic originating from an Android application protected by that VPN. + +Two terms recur throughout the code: + +- **Downstream:** the interface serving clients, such as the Wi-Fi hotspot or USB tethering interface. +- **Upstream:** the Android `Network` chosen to carry forwarded client traffic toward its destination. + +Android still manages downstream creation, hotspot configuration, DHCP, forwarding, IPv4 NAT, IPv6 advertisement, and DNS forwarding. v2rayNG changes the upstream available to that machinery; it does not reimplement those services. + +### What a test TUN actually is + +A TUN is a virtual IP interface backed by a file descriptor. The kernel delivers outgoing IP packets to a userspace reader; the reader's implementation determines what happens next. A TUN is not a remote VPN server and does not provide internet access by itself. A TAP, by contrast, carries Ethernet frames; this implementation does not create a TAP. + +Android's privileged [TestNetworkManager][test-network-api] creates the interface and publishes an Android test `Network` for it. The framework assigns an interface name, typically `testtunN`. The code retrieves that name; it does not assume `testtun0`, rename the interface, or depend on the numeric suffix. The published network has `LinkProperties` describing the interface, addresses, and DNS servers. + +The hidden `TetheringManager.setPreferTestNetworks(true)` call allows Android's tethering upstream selection to use test networks. It is a system-wide preference, **not a firewall rule or an exclusive reservation of our particular TUN**. The service must observe which upstream Android actually chose. + +The resulting packet paths are: + +```text +Wi-Fi or USB client + -> Android downstream and tethering forwarding + -> the owned testtun interface + -> one of: + HEV in the shell UserService -> main core's local SOCKS inbound -> main core outbounds + Xray in the shell UserService -> secondary core outbounds + -> underlying network, as directed by the selected routing configuration +``` + +Responses return through the corresponding engine, TUN, and Android downstream. The main VPN's interface and the tethering test TUN are distinct resources. Stopping the tethering engine must not stop the main core or close its VPN interface. + +## 2. Scope and platform boundary + +The feature is enabled on Android 13 / API 33 and newer. This is a **feature gate**, not an increase in the application's overall minimum Android version. The same `shizuku_tethering_enabled` resource is false in [default resources][bools] and true in [values-v33][bools33]. The [manifest][manifest] and [drawer][drawer] use it to disable the feature's activity, synchronization receiver, Shizuku provider, and navigation entry on older versions. Service entry points also guard the relevant API boundary. + +Shizuku availability on an older Android release does not imply this tethering design is available there. The design requires the test-network preference and compatible upstream-selection behavior, not merely the ability to allocate a TUN. There is no API 30–32 alternative path in this implementation. + +Other prerequisites are: + +- Shizuku running, permitted for v2rayNG, and accepted by the ViewModel's version check. +- A running main v2rayNG connection in VPN mode, with a valid launch snapshot and core lease. +- A functioning Android test-network service and the shell privileges needed by the platform calls. +- Android/carrier/device-policy permission to start the requested tethering type. +- For HEV, a usable SOCKS inbound in the main core, including UDP support where required. + +The page directly controls Wi-Fi hotspot and displays USB status. USB is enabled through Android's own UI. Protection, stop, restore, and retry operate on generic tethering-type masks rather than Wi-Fi-specific interface names. That shared logic is not evidence that Bluetooth, Ethernet, or every OEM-specific downstream has been tested or has a dedicated UI here. + +Read current SDK, distribution, dependency, and ABI declarations from [app/build.gradle.kts][app-build], [libs.versions.toml][versions], and [the build workflow][workflow], rather than treating a version list in this guide as authoritative. + +## 3. Code map and suggested reading order + +Follow this order to establish contracts before reading the long service implementation. Paths link to the actual files; names in the right column are useful search anchors. + +| Read | File or group | Responsibility and review anchors | +| --- | --- | --- | +| 1 | [HotspotRoutingSnapshot][snapshot], [HotspotRoutingSync][sync-dto] | Small cross-process launch metadata and lifecycle events; distinguish `launchId` from `token`. | +| 2 | [AIDL contracts][aidl] and [TetheringStatusSnapshot][status] | What crosses Binder, which calls are synchronous, and which are one-way. | +| 3 | [HotspotRoutingConfig][config] | Convert a running launch into HEV YAML or a TUN-only native configuration. | +| 4 | [TetheringCoreSync][core-sync] | Main-core hooks, immutable `CoreTetheringLease.Launch`, descriptor ownership, and Shizuku recovery decisions. | +| 5 | [ShizukuRoutingSyncReceiver][sync-receiver] | Ordered forwarding from the app's broadcast channel to the UserService. | +| 6 | [ShizukuTetheringService][service] | Resource/state declarations, `startRouting`, `shutdownRoutingLocked`, `applyRoutingConfigLocked`, and `stopUnprotectedDownstreams`. Then read platform/network/engine helpers. | +| 7 | [TetheringPlatformCompat][compat] and [TetheringApi36][api36] | Legacy versus typed operations; the shared `TetheringUpstreamMonitor`; observed upstream identity. | +| 8 | [ShellContextCompat][shell-context] | Why the privileged process needs shell package attribution. | +| 9 | [ShizukuViewModel][viewmodel] | Permission/binding, fresh snapshot requests, token bookkeeping, operation ordering, and event-driven status refresh. | +| 10 | [ShizukuActivity][activity] and [TetheringScreen][screen] | Presentation only; UI state/action helpers, switches, diagnostics, and accessibility semantics. | +| 11 | [CoreServiceManager][core-manager] | `TetheringCoreSync` hooks around start/stop/reload, `TetheringMessageHandler`, and shared teardown ownership. | +| 12 | [AngApplication][application] and [ShizukuForegroundRecovery][foreground] | Multiprocess Shizuku setup and the API 34+ foreground recovery request. | +| 13 | [TProxyService][tproxy] and [HevTunnelConfig][hev-config] | Process-local HEV JNI control and shared configuration generation; normal VPN behavior must remain intact. | +| 14 | [AppConfig][app-config], manifest, resources, drawer, and tests in [section 14](#14-methodical-review-and-validation) | Constants, component gates, strings, integration surfaces, and executable assertions. | + +The service deliberately keeps routing orchestration in one file. Small adapters isolate incompatible Android API signatures; they are not separate owners of routing policy. Likewise, UI control helpers model presentation, not an independent authoritative networking state machine. + +## 4. Processes, resources, and identities + +### Ownership is more important than the status label + +| Owner | Owns | Must not be mistaken for | +| --- | --- | --- | +| Normal app/UI process | Activity/ViewModel, permission UI, status listener, synchronization dispatcher, persisted session token access | The main core or the protected TUN's sole owner | +| Main core process (`:RunSoLibV2RayDaemon`) | Primary VPN/core, authoritative running snapshot, `CoreTetheringLease`, duplicate test-TUN descriptor and network request | A ViewModel singleton; stopping the core is not necessarily killing this process | +| Shizuku UserService | Secondary native Xray or HEV worker, `RoutingSession`, `TestNetworkHandle`, upstream observer, lifecycle queue | Android's own tethering service or the main app's VPN service | +| Android networking services | Published test `Network`, interface/route setup, selected upstream, downstream interfaces | State that the app can infer merely from a successful start callback | + +Three distinct mechanisms keep the protected route alive: + +1. The UserService retains `TestNetworkInterface` and its TUN descriptor in `TestNetworkHandle`. +2. The main core receives a duplicate descriptor through `holdTestNetwork()` and registers another test-network request. Ordinary core stop clears the launch configuration, **not this protective lease**. +3. `setupTestNetwork()` receives the connectivity-service Binder as its lifetime token. Its lifetime is anchored outside either app-owned process, rather than disappearing just because the publishing UserService dies. + +The third item alone is insufficient: the interface descriptors and network requests must also remain alive. Conversely, keeping a descriptor alone is not equivalent to keeping a published, selectable Android network. Review these resources together. + +Both network requests use `TRANSPORT_TEST` with the default `NOT_VPN` and `TRUSTED` requirements removed. They are not reservations against other applications creating test networks. `TestNetworkHandle` identifies its own published network by interface name; the tethering observer separately validates Android's chosen upstream. + +### Two identities with different purposes + +| Identity | Created/held by | Changes when | Prevents | +| --- | --- | --- | --- | +| Tethering session token | ViewModel creates it; MMKV and `RoutingSession.token` retain it | User establishes a new protected-routing session | Old lifecycle events controlling a different or explicitly stopped session | +| Main-core launch ID | Main core creates it in `createSnapshot()`; immutable lease launch retains it | Main core starts/reloads with a new configuration | Combining metadata from one launch with another launch's engine configuration | + +The session can survive a profile switch; the launch ID cannot. `openEngineConfig(launchId)` captures one matching immutable launch before parsing or file I/O. `synchronizeRouting()` also checks whether the supplied launch is still current. These are stale-work safeguards, not an atomic transaction spanning every subsequent native operation. + +`freshUserService` distinguishes recovery after the privileged process was replaced from a late update arriving after an explicit Stop in the existing process. Only a fresh process may turn a missing session into a recovered session. Duplicate `startRouting()` is rejected before it reads or releases either lease. + +## 5. Routing state versus Android tethering state + +Read the declarations at the start of [ShizukuTetheringService][service] before following any transition. + +| Routing state | Meaning | Resources / UI consequence | +| --- | --- | --- | +| `DISABLED` | Protected-routing shutdown has completed | No owned route; hotspot status is still independently derived from Android | +| `STARTING` | Network or engine setup/switch is underway | Partial resources may exist; not proof that clients are routed | +| `ACTIVE_HEV` / `ACTIVE_NATIVE` | The selected secondary engine was started | Readiness/health checks inspect the worker; downstreams can still be absent or a restore can fail | +| `WAITING` | Main core stopped, died, or could not be synchronized | Secondary engine stopped; protected TUN retained where available, intentionally providing no working datapath | +| `STOPPING` | Confirmed downstream shutdown is followed by resource release | A transient lifecycle state | +| `ERROR` | An operation or engine health check failed | **Does not mean resources were released.** `hasRoutingSession` keeps Stop available for retained resources | + +The UI's operation (`CHECKING`, `STARTING_HOTSPOT`, etc.) is a separate notion: it describes an in-flight screen request, not kernel forwarding state. + +Three downstream masks are also deliberately separate: + +- The monitor's **active interfaces** are Android's latest callback snapshot. +- `requestedTetheringTypes` remembers starts that have crossed into Android but may not yet appear in that snapshot. Cleanup must not call those "already stopped". +- `RoutingSession.desiredTetheringTypes` records what to restore after a core interruption. It is not a substitute for observing current interfaces. + +Type numbers become bits through `tetheringTypeBit()`. Only bits 0–30 are representable; `-1` is the unknown-state sentinel, not "all active" or "nothing active". Normal start refuses an unreadable initial downstream state. Shutdown uses remembered types as a fallback and refuses unsafe release when it cannot establish enough state. + +## 6. Startup and shutdown walkthrough + +### Enable protected routing + +Trace `ShizukuViewModel.startRouting()` into the service: + +1. Request a fresh snapshot and core lease from the daemon through `MessageHelper`. A UI-selected profile or a settings read is not proof of what is running. +2. Validate that the snapshot describes a running VPN and has a launch identity. +3. Within the process-wide remote-operation lock, save the previous MMKV token and write a new random session token. Restore the previous token if the start does not succeed. +4. The UserService rejects an empty token or duplicate session before changing owned resources, reads Android's active downstreams, and obtains engine content for the requested launch. +5. Install a Binder death watch on the core lease. +6. For a new test network, stop pre-existing downstreams **before** releasing/replacing any old protection. A hotspot already enabled in Android Settings must not be assumed to migrate safely by itself. +7. Set the test-network preference, create the TUN, share its descriptor with the core, register the UserService's network request, and publish `LinkProperties` using the system-owned lifetime token. +8. Wait for publication of the network whose interface matches the newly created TUN. Start the chosen engine and begin health observation. +9. Restore previously active tethering types through the same validated start path used by the page's hotspot switch. +10. Commit the new `RoutingSession` when routing setup succeeds. + +`startRoutingLocked()` can return success while one or more downstream restores failed: those failures are logged, and actual downstream status/warnings remain authoritative. Success establishing the route must not be read as success restoring every client connection. + +If engine/network construction fails, its partial resources are cleaned up. Pre-existing downstreams were stopped before replacement; if they could not be stopped, replacement must not proceed. Recovery and rebuild paths depend on this ordering. + +### Enable the Wi-Fi hotspot + +`toggleHotspot()` first establishes protected routing if it is not active. It then calls `setWifiHotspotEnabled(true)`. If hotspot startup fails, the ViewModel stops routing only when this operation created that route; it does not unconditionally dismantle a pre-existing session. + +The service treats Android's `onTetheringStarted()` as an acknowledgement, not the final safety condition. It requires a ready engine, a TUN, an active downstream, and an observed upstream equal to the owned interface. The rejection counter must also remain unchanged across the attempt. An existing but incorrectly routed downstream is stopped and restarted through this path. + +### Disable hotspot versus disable protected routing + +- **Hotspot off:** stop and confirm the Wi-Fi downstream, then remove that type from the desired mask. The protected route and any other downstreams can remain. +- **Protected routing off:** stop all active, requested, and remembered downstream types; confirm their absence; stop the secondary engine; release the core's duplicate network hold; tear down the published network and local descriptor; reset the test-network preference; clear the lease watch and session. +- **Main connection off:** pause the secondary engine but retain the protected route. This is not the same command as disabling protected tethering. + +If Android cannot confirm downstream shutdown, `shutdownRoutingLocked()` reports failure and retains protection. `destroy()` refuses to exit on that failure. The UI must still permit a subsequent Stop. Successful protected-routing stop clears the persisted session token in the same IO operation as its Binder result, even if the screen has been closed meanwhile. + +## 7. Profile changes, process death, and recovery + +### Ordinary main-core stop and restart + +[CoreServiceManager][core-manager] calls `TetheringCoreSync` around initial start, reload, stop, and failure. The lifecycle event carries the persisted session token. A successful start supplies launch metadata and a lease; large engine configuration is not included in the broadcast. + +[ShizukuRoutingSyncReceiver][sync-receiver] forwards events in order, checking that their token still matches MMKV. It finishes its broadcast work after handing off a one-way Binder call. The UserService's own queue performs the potentially long transition. + +On stop, `pauseForCoreRestartLocked()` remembers downstreams, stops the secondary engine, marks `coreRestartPending`, and enters `WAITING` when a TUN remains. Clients may stay associated with Wi-Fi or USB while traffic stops. The phone itself can use its ordinary internet connection after its VPN stops; retained tethering clients must not inherit that direct fallback merely because the main core stopped. + +On restart, `applyRoutingConfigLocked()` prefers reusing the same TUN if DNS addresses and IPv6 enablement have not changed and the retained state is usable. It replaces the engine, then restores/validates downstreams. If reuse fails or network properties changed, it stops downstreams first, rebuilds the protected network, and restores them afterward. Connections may be interrupted; this does not migrate existing TCP sessions between independent engines. + +On synchronization failure, the secondary engine is stopped. A retained TUN yields `WAITING`; without it, the service attempts downstream shutdown and reports error. Tethering hook failures are isolated by `runCoreSyncHook()` so that this optional feature does not throw into the primary core lifecycle. + +### The main core process dies without sending Stop + +`watchCoreLifetimeLocked()` links a death recipient to the core lease. If that Binder dies, the surviving UserService pauses its engine and keeps the test TUN/network resources. This covers a crash or force-stop that bypasses normal lifecycle broadcasts. Closing just the activity is different and should not stop either engine. + +The death handler uses the lifecycle monitor, and normal Stop is asynchronous. Neither promises an instantaneous secondary-engine stop at the exact CPU instruction where the main core exits. Review eventual shutdown and the retained protected route independently; do not confuse this callback with the lock-independent unsafe-upstream emergency path. + +When the user starts the main connection again, a new lease and launch can resume the retained session. Recovery does not silently start a main connection the user chose to stop. + +### Shizuku disappears while the main core survives + +The core's duplicate TUN descriptor and network request retain the protected upstream even if the shell engine disappears. The network's lifetime token is not owned by the dying UserService. Traffic is intentionally stranded on that route until recovery. + +`TetheringCoreSync` observes Shizuku Binder death and return. If a core is still running, a replacement Binder triggers synchronization from its current snapshot and the persisted session token. A fresh UserService stops active downstreams before releasing the old core-held network and creating a replacement. Only after the new route is ready does it restore downstreams. + +On API 34+, replacement-Binder delivery can be deferred while the app is cached. `ShizukuForegroundRecovery` forwards activity-resume events to the core, which requests the Binder for its non-provider process. `TetheringRecoveryState` coalesces these requests and clears pending recovery when the core stops. This is a fallback when delivery is deferred, not a claim that every API 34+ device always needs foregrounding. + +An isolated UserService failure while the Shizuku server remains alive is not identical to server Binder death: the server-death recovery listener does not itself prove automatic recovery for that case. A subsequent bind/core synchronization can reach a fresh service. Include isolated failure in device review rather than assuming all process losses take the same notification path. + +### Both failure domains disappear + +There is no surviving app-owned descriptor/request holder if both the core process and UserService are terminated. The system-owned lifetime token does not turn this into an OS-enforced lockdown policy. Simultaneous loss of both holders, reboot, system networking failure, or hostile privileged interference is outside the single-process-loss protection guarantee. + +## 8. Upstream protection and its limits + +### Observe the actual route, not the requested route + +One long-lived `TetheringUpstreamMonitor` records Android's upstream and downstream callbacks. The selected `Network` is resolved through `ConnectivityManager.getLinkProperties()` to its interface name. Only exact equality with the owned TUN name is accepted; a string containing that name among other text is not accepted. + +On API 33–35, downstream identities come from the callback's supplied `Set`. Reading the manager's separate cached interface getter at that moment could observe an older state. Both adapters publish the same small `ActiveTetheringInterface(type, name)` model. + +`eth0` was a useful emulator reproducer, not the name of the bug. Any unexpected physical or other application's test interface is rejected. A real device may expose cellular, Wi-Fi, or Ethernet under different names. An allocated `testtunN` alone proves neither Android's upstream choice nor working proxy traffic. + +### Initial handover + +`startTetheringTypeAttemptLocked()` records the pending type before calling Android. It waits for downstream activation and then checks the upstream: + +- An empty interface means selection/properties are not yet available; the bounded check can wait. +- The exact owned interface is acceptable. +- Any other non-empty interface fails immediately. Waiting for a physical path to become protected later would leave clients exposed during the wait. + +Failed attempts explicitly stop the possibly in-flight downstream. If cleanup fails, its error takes precedence over the original start error. A wrong-upstream result gets one delayed retry after cleanup; other failures do not automatically receive that retry. The delay and retry are shared across tethering types, not special-cased for Wi-Fi. + +### Later unexpected upstream changes + +`stopUnprotectedDownstreams()` deliberately does **not** take the routing lifecycle monitor. It reads the observed interface and known downstream masks, increments `upstreamRejections`, records warning bits, and requests every affected downstream stop without waiting for each acknowledgement. An in-flight start checks that counter before claiming success. + +The ordinary lifecycle path still verifies final shutdown before releasing a TUN. Emergency stop dispatch is independent of that monitor, but remains dependent on Android processing Binder requests and actually stopping tethering. It is not a kernel packet filter. The implementation does not continually retry a failed emergency stop on a timer; subsequent callbacks and explicit lifecycle operations are separate opportunities to act. + +Warnings are tracked by type. A successful retry clears only its own bit. `getStatus()` consumes accumulated warning bits once, and the UI presents the localized wrong-upstream message through `toastInfo`. Reading status for diagnostics can therefore consume a warning before the screen reads it. + +### What "fail-closed" means here + +The implementation is designed to retain a dead protected route when an engine stops and to stop downstreams when Android reports an unsafe upstream. It does not intentionally remove the protected route while known clients remain active. + +It **cannot prove that zero packets escape before Android delivers an upstream-change callback or completes a stop request**. Protection of a hotspot already active before enabling this feature begins during the transition; traffic sent before that transition was not protected retroactively. Missing callbacks, OEM forwarding/offload behavior, and both-process loss require separate scrutiny. A successful status assertion is not a packet capture. + +Also, a routing rule intentionally selecting Xray's direct outbound is not an Android upstream escape: the packet still traversed the chosen engine and obeyed its configuration. Leak testing must use a profile/rule whose expected destination is unambiguously proxied or blocked. + +## 9. Configuration, DNS, IPv6, and routing semantics + +### Use the running launch, not newly edited settings + +`TetheringCoreSync.onStarted()` pairs the exact generated main-core JSON with launch metadata. Changing preferences without restarting the main core must not make tethering build a different configuration from that still-running core. The lease captures metadata/configuration together; the shell service obtains engine content through a read-only descriptor. + +The descriptor refers to a temporary file created in app-private cache. Its pathname is unlinked after opening, and the open descriptor keeps its contents available for the recipient. This avoids large Binder payloads and a normal shared pathname containing the full configuration. It is not a pipe, and it does not mean configuration contains no credentials. + +### HEV and native Xray are not interchangeable internals + +| Aspect | HEV | Native Xray TUN | +| --- | --- | --- | +| TUN consumer | Another process-local HEV worker in the UserService | Another Xray controller in the UserService | +| Routing decisions | Main core, reached through its local SOCKS inbound | Secondary core, using the copied running configuration | +| Configuration | `HevTunnelConfig` with captured MTU, timeouts, log level, SOCKS port/authentication, and synthetic TUN addresses | `nativeTunOnlyConfig()` retains all TUN inbounds and removes other inbounds | +| Local SOCKS requirement | Must be enabled and usable | Not required by the tethering backend itself | +| Runtime state | Shares main core's routing/balancer state through SOCKS | Has independent connections, DNS caches, counters, and balancer/observatory runtime state | + +Native configuration retains outbounds, routing, DNS, balancers, and other non-inbound sections at the JSON-model level, not byte-for-byte text. Removing SOCKS/HTTP inbounds avoids listener-port collisions. It is not a general repair of arbitrary custom configurations: inbound-tag-specific rules and other listener-producing sections must be reviewed in their actual configuration. + +Equal policy-group/balancer configuration does not guarantee that two independent native controllers select the same member at every instant. Profile/configuration synchronization is the contract; identical mutable runtime state is not. + +HEV's JNI state is process-global. `startExternalTunnel()` is safe as a separate tethering instance because it runs in a separate process. Moving it into the main core process would destroy that isolation. `isExternalTunnelRunning()` checks native worker state; the existence of the YAML file is not a health check. A running worker also does not prove its SOCKS endpoint or the remote server is reachable. + +### DNS follows existing app behavior + +`SettingsManager.getVpnDnsServers()` supplies the IP-address list advertised by the main VPN; the snapshot carries the same list to the test network. The tethering feature does not introduce a separate public resolver preference. + +When Local DNS is enabled, the normal configuration builder installs port-53 routing to `dns-out` for the relevant inbound (`socks` for HEV, `tun` for native). HEV traffic reaches those rules in the main core; native mode preserves them in its TUN-only configuration. With Local DNS disabled, configured resolver addresses are ordinary routed destinations. Android still handles the downstream-facing DNS service. Custom configurations can have different rules; inspect the actual generated configuration. + +Do not confuse the VPN DNS address list, the core's internal DNS server settings, Android's DNS proxy, and a client's own encrypted DNS. A client choosing its own resolver exercises routing of that traffic, not necessarily the app's port-53 handling. + +### IPv6 is requested separately from being observed + +The captured Enable IPv6 setting determines whether the test network has an IPv6 address and whether HEV receives an IPv6 tunnel address. Native mode uses the running core's TUN configuration. The synthetic addresses live in `AppConfig.SHIZUKU_TUN_ADDR_V4` and `SHIZUKU_TUN_ADDR_V6`; they are not real public allocations or proxy endpoints. + +The IPv6 prefix is a documentation-range /64 chosen to satisfy Android's upstream-prefix handling. A ULA-shaped DNS hint (`SHIZUKU_TUN_DNS_HINT_V6`) is appended only when IPv6 is enabled and the configured DNS list has no IPv6 address. Configured servers stay first. The hint is not an independently running resolver; successful resolution must come from the configured servers or applicable core DNS interception. Review DNS behavior with Local DNS both on and off rather than assuming this synthetic hint can resolve names by itself. + +Android decides whether to advertise the prefix downstream. `hasDelegatedIpv6Prefix()` inspects the real downstream interface for an address inside the configured /64; the UI reports per-type IPv4-only, dual-stack, or unknown from that observation. This is a **prefix-setup diagnostic**, not proof that a particular client acquired an address, that its DNS works, or that the remote proxy has IPv6 egress. A newly enabled setting is not proof the currently running launch has already applied it; status display enablement reads the current preference while routing follows its launch snapshot. + +Prefer IPv6 is not a second downstream-enablement switch. Its effects in the normal configuration/resolution path are inherited through the running core or copied native configuration. It cannot force Android to delegate IPv6, force a client to choose IPv6, or provide IPv6 connectivity that the selected outbound lacks. + +Per-app/process routing cannot identify the original application on a tethered laptop or phone. Domain/IP/port/protocol rules still apply as expressed by the effective core configuration. The screen's disclaimer communicates that distinction. + +## 10. Concurrency, IPC, and bounded waits + +Read the [AIDL][aidl] before interpreting a returned method call as completion: + +- UI mutations (`startRouting`, `stopRouting`, `setWifiHotspotEnabled`) and `getStatus` are synchronous Binder calls, performed off the UI thread. +- `notifyCoreStopping`, `synchronizeRouting`, and `notifyCoreStartFailed` are one-way. Their return means handoff, not a completed transition. +- Status notifications and listener registration are one-way. The notification carries no state; the ViewModel fetches current state. +- Lease calls are synchronous and can involve configuration generation, file I/O, or resource acquisition. + +| Ordering mechanism | Purpose | Deliberately not covered | +| --- | --- | --- | +| UserService monitor (`@Synchronized` / `synchronized(this)`) | Prevent normal start/stop/configuration transitions interleaving | Emergency downstream stop dispatch and listener replacement | +| `coreUpdates` single-thread scheduler | Order core lifecycle events and run engine health checks | Acknowledgement to the sender; unsafe-upstream emergency processing | +| Monitor change executor | Process upstream/downstream changes after publishing callback snapshots | Waiting for ordinary lifecycle work to finish | +| UI process-wide `serviceOperationLock` on IO | Keep remote mutations and MMKV bookkeeping ordered across closing/reopening the screen | Android cancelling a Binder transaction already submitted | +| ViewModel operation generation | Discard obsolete asynchronous UI results | Undoing an already executed remote mutation | +| Sync dispatcher queue | Order forwarded broadcasts, bound service connection wait, retry one stale Binder proxy | Completing the actual routing transition within a BroadcastReceiver lifetime | + +Callbacks publish atomic references before scheduling change handling. Active interfaces and upstream identity arrive independently; `getStatus()` is one Binder response, not a transactionally simultaneous kernel snapshot of every field. Fresh callbacks and postcondition checks remain important. + +The source currently bounds individual waits as follows; these are diagnostic expectations, not a maximum duration for the whole operation: + +| Wait | Current bound | +| --- | --- | +| UI core snapshot / UserService binding; dispatcher binding | 5 seconds each | +| Android start/stop acknowledgement; initial interface snapshot | 10 seconds each | +| Test network publication | 15 seconds | +| Downstream active/stopped postcondition | 10 seconds | +| Upstream selection while no interface is reported | 5 seconds | +| Delay before the one wrong-upstream retry | 8 seconds | +| Postcondition polling interval | 200 ms | +| Secondary-engine health observation | 2-second scheduled delay | + +Multiple downstreams and retry phases can add these waits. Native calls and synchronous Binder work do not acquire a universal deadline from this table. Health observation also shares the lifecycle queue/monitor and can be delayed by ongoing work. Review responsiveness with blocked operations; do not infer it solely from the presence of timeout constants. + +## 11. UI and status interpretation + +[ShizukuActivity][activity] collects immutable ViewModel state with lifecycle awareness and passes actions to [TetheringScreen][screen]. The screen does not create tunnels or mutate preferences. Its routing switch means "a protected session/resources are retained", not always "packets are flowing"; therefore it can remain checked in `WAITING` or a retained-resource error. + +Permission status, shell-service connectivity, main-core state, routing state, hotspot state, and IPv6 observation are distinct. In particular: + +- Shizuku permission granted does not prove a UserService can bind or a platform API works. +- Main-core running status is queried from the daemon, not reconstructed from a UI singleton. +- Closing the page unregisters listeners and unbinds **without destroying** the daemon UserService. +- Losing the service connection makes the screen unavailable; its cleared local fields do not prove the OS released the retained route. +- A hotspot can exist without protected routing, including one started outside the app. The screen has a separate direct/unprotected presentation for that case. +- The diagnostic detail uses the **observed upstream interface** and profile, not the requested interface name. It can be empty while Android is still resolving an upstream. +- Status refresh is callback-driven. A refresh arriving during a check is coalesced into another read; a toggle performs a final refresh. There is no continuous UI polling loop. +- `getStatus()` includes backend health and can consume warnings. Do not use repeated reads as a passive packet-safety proof. + +The row is the switch's action/semantic target; the visual `Switch` does not add a second action. Icons are decorative. Review actual TalkBack, keyboard, D-pad, long translations, and large-font behavior; a screenshot only establishes appearance. Resource keys retain the `shizuku_` prefix although the page is called Tethering. + +## 12. Compatibility adapters and removal conditions + +"Typed API on API 36+" does not mean "no hidden API on API 36+". The following dependencies are intentional review boundaries, not universally stable contracts: + +| Dependency | Location / why | Exact migration or removal condition | +| --- | --- | --- | +| API 33–35 tethering lookup, request, start/stop, callback and interface reflection | `TetheringPlatformCompat` plus service lookup | Remove legacy branches when the feature stops supporting APIs below 36; retain shared helpers still used by the typed path. | +| Typed tethering requests and callbacks | `TetheringApi36`, reached through `usesPublicTetheringApi()` | Keep above-minimum types isolated so older supported devices never load an incompatible path. | +| `onUpstreamChanged(Network?)` on the typed callback | Hidden callback member with `@Keep`, matching the framework binary signature; not a Kotlin `override` against the current SDK | Replace with a normal `override` when the compile SDK exposes it. Remove only if upstream identity ceases to be part of protection. Validate shrinker behavior when changing it. | +| Test-network create/setup/teardown | `ShizukuTetheringService` reflection | Public replacements must provide equivalent descriptor and lifetime-token semantics on every supported feature API. | +| `setPreferTestNetworks(boolean)` | Service reflection on every supported API | A public equivalent must provide the same upstream opt-in everywhere supported, or the design must stop using test networks. | +| `TRANSPORT_TEST` numeric value in the request | Shared request builder and narrow `WrongConstant` suppression | Use a public constant when exposed, or delete the request when no longer using test networks. | +| CIDR `LinkAddress` construction | `createLinkAddress()` reflection | A public equivalent must exist on every supported feature API. | +| Shell-attributed `ContextImpl` construction | `ShellContextCompat` | Android/Shizuku supplies a public equivalent whose operation package is shell across supported versions. | +| Foreground Binder request on API 34+ | `ShizukuForegroundRecovery` and core sync | Minimum supported Shizuku reliably delivers replacement Binders to cached non-provider processes across supported Android versions. | + +API presence is not permission or OEM-behavior equivalence. A device can pass the resource/API gate and still lack a usable service, method, permission, upstream behavior, or hotspot entitlement. Check actual firmware before extending compatibility claims. Root-started Shizuku/Sui identity variants are not established by testing the non-root shell path. + +## 13. Security, conflicts, and operational quirks + +### Trust and sensitive material + +Granting Shizuku permission allows this feature's privileged code to act outside ordinary app privileges. The UserService receives the running native configuration or SOCKS credentials, so the user must trust both Shizuku and the installed app. + +The manifest's synchronization receiver/activity are non-exported. UI snapshot reception is non-exported. Shizuku's exported provider is protected by `INTERACT_ACROSS_USERS_FULL`. Internal intents are package-scoped/explicit as appropriate, and the sync dispatcher checks the random session token before forwarding. The lease is a sensitive Binder capability: its holder can request engine content and assets. Tokens and launch IDs complement component/IPC boundaries; they are not encryption or a defense against another actor with equivalent privileged access. + +Native geodata and user assets are app-private, so `stageNativeAssets()` streams them through the core lease into `/data/local/tmp/v2rayng-tethering-assets`. Names are restricted to basenames; the cache fingerprint uses names, sizes, and modification times, not a content hash. Files are staged via temporary files, stale names are removed on restaging, and unchanged files are reused. This directory is not cleared by ordinary routing shutdown. Review its shell-level visibility and lifetime separately from app-private configuration. + +HEV YAML is written to a PID-specific file in `/data/local/tmp` and removed by normal engine cleanup. Abrupt process death can bypass that cleanup, and the YAML can include SOCKS authentication. Do not describe shell temporary storage as app-private or guaranteed erased. Avoid putting real credentials, full configurations, or unredacted user assets in review logs or test artifacts. + +### Shared global state + +Do not combine this feature casually with another test-network owner, root VPN-hotspot tool, firewall/tethering controller, or v2rayNG root-mode forwarding. `setPreferTestNetworks` and Android tethering state are global; cleanup resets the preference to false rather than restoring another controller's prior state. Emergency and explicit shutdown may stop downstreams originally enabled outside v2rayNG. + +The implementation uses Android's existing SSID/password/band settings and does not manage client allowlists or bypass carrier/device-policy checks. It does not silently disconnect station Wi-Fi or enable mobile data. Some devices support [simultaneous station Wi-Fi and hotspot][wifi-concurrency]; others cannot satisfy the requested combination. + +Positive Android error `5` is [TETHER_ERROR_INTERNAL_ERROR][tethering-api], not a Wi-Fi-specific failure. It is also different from this service's negative `RESULT_ALREADY_ACTIVE` (`-5`) and routing state `ERROR` (`5`). Current hotspot error presentation can expose the platform number; contextual Wi-Fi guidance/automatic switching is not implemented here. + +### Resource and naming surprises + +- A rising `testtun` suffix is not itself proof of a leaked interface. Inspect live interfaces and retained descriptors/requests. The API chooses the name; review must not rely on suffix reuse. +- A retained TUN with no worker is often the intended safety state. Deleting it to make an error screen look clean can expose clients. +- A successful engine start is not a remote connectivity probe, and a successful route start is not proof all downstream restores succeeded. +- Native profile switches replace an independent engine; balancer choices and established connections can differ from the main engine even with equivalent configuration. +- `USER_SERVICE_VERSION` in `createUserServiceArgs()` must change when implementation/AIDL compatibility changes, because an old daemon can survive an APK update. An ordinary app versionCode alone is insufficient for local rebuilds. Documentation-only changes do not require a bump. + +## 14. Methodical review and validation + +### A. Static review, in order + +Use the code map above and mark each item only after following both the happy and failure paths. + +1. **Boundary:** check resource gate, manifest components, drawer entry, permission flow, API guards, and shell context attribution. Confirm older app-supported APIs do not enter the feature. +2. **IPC:** read every AIDL method, snapshot field, event, and receiver. Identify the process executing it and whether return means handoff or completion. +3. **Launch consistency:** trace main-core config capture to `openEngineConfig`; check stale/nullable launch handling and distinguish session authorization from launch freshness. +4. **Resource ownership:** follow TUN creation, publication token, both descriptor/request holders, Binder death, normal release, partial failure, and refused shutdown. +5. **Start/restore:** begin with no downstream, then pre-existing downstreams, then an accepted-but-not-yet-published start. Check every early return's cleanup. +6. **Stop:** distinguish hotspot off, protected-routing off, main-core stop, UI close, and process death. Verify primary-core teardown is not reached by the tethering Stop action. +7. **Concurrency:** draw an execution timeline for blocked configuration read plus bad-upstream callback. Verify emergency dispatch and listener removal do not require the lifecycle monitor. Check rejection-counter and stale-event behavior. +8. **Configuration:** compare native JSON before/after inbound filtering; review HEV credentials/timeouts/MTU; check policy groups, custom inbound rules, geodata staging, and DNS with Local DNS on/off. +9. **IPv6:** inspect requested addresses and DNS hint separately from actual downstream prefix detection. Check unknown versus disabled versus IPv4-only UI states. +10. **Recovery:** trace core death, Shizuku server death, isolated UserService death, foreground recovery, explicit Stop followed by a late event, and both-holder loss. Do not turn missing evidence into a guarantee. +11. **Presentation:** map every state/result to enabled controls, switch state, strings, warning consumption, and accessibility semantics. Verify translated strings across the declared locale set. +12. **Maintenance/performance:** inspect per-process threads, callback registrations, health scheduling, cancellation, asset copying, native resources, and compatibility removal comments. Confirm the feature does not add per-packet Kotlin/Binder work. + +### B. Automated tests: what they actually cover + +| Test source | Assertions to inspect | Does not establish | +| --- | --- | --- | +| [HotspotRoutingConfigTest][test-config] | Missing launch rejection, TUN-only filtering, retained sections, HEV settings/quoting/IPv6 output | All custom configs, DNS reachability, or packet routing | +| [TetheringCoreSyncTest][test-sync] | Hook failure isolation; recovery only with a running core; foreground API boundary/coalescing | Actual Android process death or Binder delivery timing | +| [TetheringPlatformCompatTest][test-compat] | API dispatch boundary, valid bit masks, exact upstream comparison | Runtime hidden-method availability on an OEM | +| [TetheringUpstreamMonitorTest][test-monitor] | Latest callback snapshot, initial missing state, invalid state, close | Framework callback reliability or ordering | +| [TetheringUiStateTest][test-ui] | Control/state mapping, Stop for retained errors, per-type IPv6/unknown behavior | TalkBack speech, D-pad interaction, or actual forwarding | +| [HevTunnelConfigTest][test-hev] and [CoreTeardownDecisionTest][test-teardown] | Shared YAML generation and teardown scheduling decisions | JNI worker lifetime, descriptor ownership, or complete service teardown | +| [TetheringLifecycleTest][test-device] | Duplicate start leaves leases untouched; stale update cannot undo Stop; listener removal while startup blocks; stale launch read rejection; HEV failure status; retained-TUN pause/resume; emergency shutdown during blocked configuration read | The complete physical-client, OEM, process-death, and IPv6 matrix below | + +Important details of the device tests: + +- They require a usable selected profile, VPN/Shizuku authorization, and a compatible test device. +- The `backend` argument changes VPN/backend preferences and enables local SOCKS for HEV. They are not settings-preserving tests. Record settings before/after and agree on the desired final configuration. +- Setup/teardown stops protected routing and can affect tethering clients. Use a dedicated device/network, not a production hotspot. +- Client Wi-Fi is disabled for the isolated lifecycle tests so switching into hotspot mode does not independently reload the main VPN. That isolates a race; it does **not** test the connected-Wi-Fi user scenario. +- `coreStopKeepsHotspotOnDeadTunAndRestartResumesIt` sends lifecycle calls to the UserService with a live lease; it is not a real crash/force-stop test. +- The unsafe-upstream test deliberately changes the global preference and restarts a downstream from outside the service while a lease read is blocked. It uses shell permission adoption and hidden-API access for fault injection. It must not be run with sensitive client traffic. +- That test uses an independent Android observer because `getStatus()` legitimately waits behind the blocked lifecycle monitor. It asserts downstream shutdown, not absence of every escaped packet. + +For a prepared checkout, run the repository's required tests from `V2rayNG/`; Windows uses `gradlew.bat` and other systems use `./gradlew`. Typical Play Store tasks are: + +```text +./gradlew :app:testPlaystoreDebugUnitTest :app:compilePlaystoreDebugKotlin +./gradlew :app:assemblePlaystoreDebug :app:assemblePlaystoreDebugAndroidTest +``` + +For targeted instrumentation, after installing the matching app/test APKs and preparing the device: + +```text +adb -s shell am instrument -w --no-hidden-api-checks -e class com.v2ray.ang.shizuku.TetheringLifecycleTest -e backend native com.v2ray.ang.test/androidx.test.runner.AndroidJUnitRunner +adb -s shell am instrument -w --no-hidden-api-checks -e class com.v2ray.ang.shizuku.TetheringLifecycleTest -e backend hev com.v2ray.ang.test/androidx.test.runner.AndroidJUnitRunner +``` + +These package names are for the Play Store variant; verify the installed instrumentation component with `adb -s shell pm list instrumentation`. Hidden-API relaxation is for the isolated test invocation, not a production setup requirement. Do not leave device-wide testing-policy changes behind. Follow repository build instructions for the pinned AndroidLibXrayLite AAR and HEV libraries; successful compilation with stale native inputs is not validation. Inspect packaged `libgojni.so`, `libhev-socks5-tunnel.so`, and `libhevsockstun.so` for the tested ABI. + +### C. Device and real-client review matrix + +Run both backends on at least one API 33–35 device and one API 36+ device. Check an older API where the feature is hidden. Add a physical phone/client pair: emulator upstream/interface observations cannot substitute for USB or Wi-Fi client traffic. Unsupported hardware scenarios should be explicitly marked Not run, with the reason. + +| Scenario | Procedure | Evidence / expected outcome | +| --- | --- | --- | +| Permission and absence | Test missing/stopped Shizuku, grant, deny, and reconnect | Truthful status; no false connected/routed state; normal app still works | +| Fresh hotspot | Main VPN running; enable hotspot through the page | Route ready before validated success; actual upstream matches owned TUN; client uses expected outbound | +| Pre-existing hotspot | Start hotspot in Android Settings, then enable protected routing | Old downstream is stopped/re-established and validated; do not count earlier direct traffic as protected | +| USB and mixed downstreams | Repeat with USB already active, USB enabled later, and Wi-Fi plus USB | Observe actual types/upstream and traffic from each client; independent per-type diagnostics | +| Start race | Start/change main profile, immediately enable hotspot; repeat | No success on wrong upstream; bounded cancellation/retry or valid protected start | +| Rapid toggles | Enable hotspot then request protected-routing Stop as soon as UI permits; close/reopen during operation | No orphan pending hotspot; UI remains usable; primary VPN remains running | +| Wi-Fi handover | Repeat while attached to station Wi-Fi, including supported/unsupported concurrency | Record OEM result and core reload; error 5 alone is not a diagnosis; no assumed automatic mobile-data switch | +| Profile/group switch | Use two distinguishable exits/rules; switch profile and policy group | New client flows obey replacement config; retained TUN where reusable; native balancer state need not match main runtime exactly | +| Main-core normal Stop | Keep client probes running, stop main connection, then restart | Dead protected TUN while paused; no unintended physical upstream; restored routing follows new launch | +| Main-core abrupt death | Kill the identified main-core process in an isolated session, not just the activity | Secondary engine stops after death handling; surviving UserService retains protection; new launch can recover | +| Shizuku death | From launcher/background, stop Shizuku while main core survives; restart it | Core-held route remains; recovery when replacement Binder arrives, including foreground fallback where needed | +| Isolated UserService death | Terminate only the identified UserService while server/core survive | Record retained route and actual recovery trigger; do not infer server-death notification occurred | +| Failed main restart | Use an intentionally unusable replacement configuration | Secondary engine does not keep serving the old profile; retained route or downstream shutdown with error | +| Bad upstream after success | On a dedicated device, provoke an upstream change; also test blocked lifecycle work | All affected downstream stops requested without waiting on lifecycle monitor; warning/status update; capture traffic during transition | +| Failed cleanup | Fault-inject stop failure or unavailable state without sensitive clients | Error keeps retained route stoppable; resource release must not be treated as success without downstream absence | +| DNS combinations | Local DNS on/off; custom VPN DNS; IPv4-only and IPv6 DNS settings; client DNS probes | Effective routing and DNS match intended config; no reliance on synthetic DNS hint as a real server | +| IPv6 combinations | IPv6 off/on with Wi-Fi and USB; obtain client addresses/routes and exercise IPv4 and IPv6 separately | Prefix diagnostic matches downstream observation; real client connectivity recorded separately; unknown is not silently IPv4-only | +| Native assets / HEV prerequisites | Use geodata/custom assets; change an asset; HEV with valid then unavailable SOCKS | Current assets used; useful failure evidence; running worker not confused with reachable upstream | +| UI lifecycle/accessibility | Leave/reopen, recreate activity, foreground after Shizuku restart; touch/keyboard/D-pad/TalkBack | No networking teardown from page closure; correct final state; one switch action per row; readable localized diagnostics | +| Packaging/update | Debug and release/shrunk build; update while daemon exists | Current service version/contract used; typed hidden callback preserved; correct native libraries packaged | + +For packet-level review, collect both new-connection and established-flow behavior with a controlled destination. Compare the client's egress with the intended proxy/direct policy; record IPv4, IPv6, TCP, UDP, and DNS separately. Where a zero-leak claim matters, capture traffic at the controlled upstream/client during fault injection. Interface names, successful HTTP requests, and a green UI label alone cannot establish that claim. + +Useful read-only device observations include: + +```text +adb -s shell dumpsys tethering +adb -s shell dumpsys connectivity +adb -s shell ip addr +adb -s logcat -d -s ShizukuTethering ShizukuSyncReceiver TetheringPlatformCompat TetheringLifecycleTest +``` + +`dumpsys` is a diagnostic tool here, not a production dependency. Also capture relevant app/framework logs when these tags are insufficient, but redact secrets and client identifiers before publication. Record process identities before fault injection so a test does not accidentally kill both protective holders. + +For each result, record source SHA, build variant, native-library revisions, ABI, Android/API and firmware, Shizuku mode/version, backend, relevant settings, downstream types, observed interface, client-side result, and final cleanup state. Separate static reasoning, automated assertions, emulator results, and physical traffic evidence. This guide's checklists are not a completed test report. + +## 15. Maintaining this feature + +When reviewing an upstream merge or a future simplification, preserve these invariants: + +- The main daemon remains the authority for the running configuration; normal VPN/proxy/root lifecycle behavior must not be replaced by UI assumptions. +- The protected route is not removed before downstream shutdown is established. +- An engine can stop while its TUN intentionally remains alive. +- Pending starts count during cleanup even before Android reports active interfaces. +- Session identity, launch identity, resource ownership, and observed forwarding state remain distinct. +- Unsafe-upstream stop dispatch must not queue behind the normal lifecycle monitor. +- Closing a page must not destroy the routing daemon, and a completed remote mutation must retain its bookkeeping. +- Older supported APIs still use their compatible adapter; newer typed APIs do not remove unrelated hidden dependencies. +- Error/status text and tests must describe observed behavior, not promise universal OEM compatibility or an atomic firewall guarantee. + +Update this guide when one of those contracts changes, especially when adding/removing IPC fields, changing process ownership, changing the network-lifetime mechanism, or replacing hidden APIs. Link new regression tests to the relevant invariant. Prefer comments explaining why the unusual ordering exists over restating the next line of code. + +[snapshot]: V2rayNG/app/src/main/java/com/v2ray/ang/dto/HotspotRoutingSnapshot.kt +[sync-dto]: V2rayNG/app/src/main/java/com/v2ray/ang/dto/HotspotRoutingSync.kt +[aidl]: V2rayNG/app/src/main/aidl/com/v2ray/ang/shizuku +[status]: V2rayNG/app/src/main/java/com/v2ray/ang/shizuku/TetheringStatusSnapshot.kt +[config]: V2rayNG/app/src/main/java/com/v2ray/ang/shizuku/HotspotRoutingConfig.kt +[core-sync]: V2rayNG/app/src/main/java/com/v2ray/ang/shizuku/TetheringCoreSync.kt +[sync-receiver]: V2rayNG/app/src/main/java/com/v2ray/ang/shizuku/ShizukuRoutingSyncReceiver.kt +[service]: V2rayNG/app/src/main/java/com/v2ray/ang/shizuku/ShizukuTetheringService.kt +[compat]: V2rayNG/app/src/main/java/com/v2ray/ang/shizuku/TetheringPlatformCompat.kt +[api36]: V2rayNG/app/src/main/java/com/v2ray/ang/shizuku/TetheringApi36.kt +[shell-context]: V2rayNG/app/src/main/java/com/v2ray/ang/shizuku/ShellContextCompat.kt +[viewmodel]: V2rayNG/app/src/main/java/com/v2ray/ang/ui/ShizukuViewModel.kt +[activity]: V2rayNG/app/src/main/java/com/v2ray/ang/ui/ShizukuActivity.kt +[screen]: V2rayNG/app/src/main/java/com/v2ray/ang/ui/TetheringScreen.kt +[core-manager]: V2rayNG/app/src/main/java/com/v2ray/ang/core/CoreServiceManager.kt +[application]: V2rayNG/app/src/main/java/com/v2ray/ang/AngApplication.kt +[foreground]: V2rayNG/app/src/main/java/com/v2ray/ang/shizuku/ShizukuForegroundRecovery.kt +[tproxy]: V2rayNG/app/src/main/java/com/v2ray/ang/service/TProxyService.kt +[hev-config]: V2rayNG/app/src/main/java/com/v2ray/ang/service/HevTunnelConfig.kt +[app-config]: V2rayNG/app/src/main/java/com/v2ray/ang/AppConfig.kt +[manifest]: V2rayNG/app/src/main/AndroidManifest.xml +[drawer]: V2rayNG/app/src/main/java/com/v2ray/ang/ui/main/MainDrawer.kt +[bools]: V2rayNG/app/src/main/res/values/bools.xml +[bools33]: V2rayNG/app/src/main/res/values-v33/bools.xml +[app-build]: V2rayNG/app/build.gradle.kts +[versions]: V2rayNG/gradle/libs.versions.toml +[workflow]: .github/workflows/build.yml +[test-config]: V2rayNG/app/src/test/java/com/v2ray/ang/shizuku/HotspotRoutingConfigTest.kt +[test-sync]: V2rayNG/app/src/test/java/com/v2ray/ang/shizuku/TetheringCoreSyncTest.kt +[test-compat]: V2rayNG/app/src/test/java/com/v2ray/ang/shizuku/TetheringPlatformCompatTest.kt +[test-monitor]: V2rayNG/app/src/test/java/com/v2ray/ang/shizuku/TetheringUpstreamMonitorTest.kt +[test-ui]: V2rayNG/app/src/test/java/com/v2ray/ang/ui/TetheringUiStateTest.kt +[test-hev]: V2rayNG/app/src/test/java/com/v2ray/ang/service/HevTunnelConfigTest.kt +[test-teardown]: V2rayNG/app/src/test/java/com/v2ray/ang/service/CoreTeardownDecisionTest.kt +[test-device]: V2rayNG/app/src/androidTest/java/com/v2ray/ang/shizuku/TetheringLifecycleTest.kt +[shizuku-api]: https://github.com/RikkaApps/Shizuku-API +[vpn-api]: https://developer.android.com/reference/android/net/VpnService +[test-network-api]: https://android.googlesource.com/platform/packages/modules/Connectivity/+/311feaff8b4a66b0c8a7bc5ed72f916d666c683e/framework/src/android/net/TestNetworkManager.java +[tethering-api]: https://developer.android.com/reference/android/net/TetheringManager#TETHER_ERROR_INTERNAL_ERROR +[wifi-concurrency]: https://source.android.com/docs/core/connect/wifi-sta-ap-concurrency diff --git a/V2rayNG/app/build.gradle.kts b/V2rayNG/app/build.gradle.kts index 5c12c0f7b06..6b11e3b10d5 100644 --- a/V2rayNG/app/build.gradle.kts +++ b/V2rayNG/app/build.gradle.kts @@ -126,6 +126,7 @@ android { buildFeatures { buildConfig = true compose = true + aidl = true } androidResources { @@ -170,6 +171,8 @@ dependencies { // AndroidX Core Libraries implementation(libs.androidx.core.ktx) implementation(libs.androidx.appcompat) + implementation(libs.shizuku.api) + implementation(libs.shizuku.provider) // Compose Libraries implementation(platform(libs.androidx.compose.bom)) diff --git a/V2rayNG/app/src/androidTest/java/com/v2ray/ang/shizuku/TetheringLifecycleTest.kt b/V2rayNG/app/src/androidTest/java/com/v2ray/ang/shizuku/TetheringLifecycleTest.kt new file mode 100644 index 00000000000..9974b98f586 --- /dev/null +++ b/V2rayNG/app/src/androidTest/java/com/v2ray/ang/shizuku/TetheringLifecycleTest.kt @@ -0,0 +1,324 @@ +package com.v2ray.ang.shizuku + +import android.content.BroadcastReceiver +import android.content.ComponentName +import android.content.Context +import android.content.Intent +import android.content.IntentFilter +import android.content.ServiceConnection +import android.os.IBinder +import android.os.ParcelFileDescriptor +import android.util.Log +import androidx.core.content.ContextCompat +import androidx.test.core.app.ActivityScenario +import androidx.test.filters.SdkSuppress +import androidx.test.platform.app.InstrumentationRegistry +import com.v2ray.ang.AppConfig +import com.v2ray.ang.core.LauncherManager +import com.v2ray.ang.dto.HotspotRoutingSnapshot +import com.v2ray.ang.extension.serializable +import com.v2ray.ang.handler.MmkvManager +import com.v2ray.ang.helper.MessageHelper +import com.v2ray.ang.ui.main.MainActivity +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Assume.assumeTrue +import org.junit.Before +import org.junit.Test +import rikka.shizuku.Shizuku +import java.io.File +import java.util.UUID +import java.util.concurrent.CountDownLatch +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger + +/** + * Device regression tests: grant VPN/Shizuku permission and select a working profile first. + * Run with -e backend native|hev and --no-hidden-api-checks for the fault injector only. + * Disable client Wi-Fi first so hotspot setup does not independently restart the main VPN. + */ +@SdkSuppress(minSdkVersion = 33) +class TetheringLifecycleTest { + private val instrumentation = InstrumentationRegistry.getInstrumentation() + private val context = instrumentation.targetContext + private val args = ShizukuTetheringService.createUserServiceArgs() + private lateinit var service: IShizukuTetheringService + private lateinit var snapshot: HotspotRoutingSnapshot + private lateinit var lease: ICoreTetheringLease + private val connected = CountDownLatch(1) + private var activity: ActivityScenario? = null + private val connection = object : ServiceConnection { + override fun onServiceConnected(name: ComponentName, binder: IBinder) { + service = IShizukuTetheringService.Stub.asInterface(binder) + connected.countDown() + } + override fun onServiceDisconnected(name: ComponentName) = Unit + } + + @Before + fun connectToRunningCore() { + InstrumentationRegistry.getArguments().getString("backend")?.let { backend -> + require(backend == "native" || backend == "hev") + MmkvManager.encodeSettings(AppConfig.PREF_MODE, AppConfig.VPN) + MmkvManager.encodeSettings(AppConfig.PREF_USE_HEV_TUNNEL, backend == "hev") + if (backend == "hev") MmkvManager.encodeSettings(AppConfig.PREF_ENABLE_LOCAL_PROXY, true) + } + activity = ActivityScenario.launch(MainActivity::class.java) + LauncherManager.startService(context) + instrumentation.runOnMainSync { Shizuku.bindUserService(args, connection) } + assertTrue("Shizuku UserService did not bind", connected.await(10, TimeUnit.SECONDS)) + assertEquals(0, service.stopRouting()) + val received = CountDownLatch(1) + val receiver = object : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + if (intent.getIntExtra("key", 0) != AppConfig.MSG_HOTSPOT_CONFIG_RESPONSE) return + val current = intent.serializable("content") ?: return + if (!current.running) return + val currentLease = intent.coreTetheringLease() ?: return + snapshot = current + lease = currentLease + received.countDown() + } + } + ContextCompat.registerReceiver(context, receiver, IntentFilter(AppConfig.BROADCAST_ACTION_ACTIVITY), ContextCompat.RECEIVER_NOT_EXPORTED) + try { + // Starting the main core is asynchronous; query until it publishes its launch lease. + repeat(20) { + if (received.count == 0L) return@repeat + MessageHelper.sendMsg2Service(context, AppConfig.MSG_QUERY_HOTSPOT_CONFIG, "") + received.await(500, TimeUnit.MILLISECONDS) + } + assertTrue("Start the main VPN before running this test", received.await(5, TimeUnit.SECONDS)) + assertTrue(snapshot.running && snapshot.vpnMode) + Log.i("TetheringLifecycleTest", "Testing ${if (snapshot.useHev) "HEV" else "native Xray"} tethering") + } finally { + context.unregisterReceiver(receiver) + } + } + + @After + fun disconnect() { + if (::service.isInitialized) { + service.setStatusListener(null) + assertEquals(0, service.stopRouting()) + } + instrumentation.runOnMainSync { Shizuku.unbindUserService(args, connection, false) } + activity?.close() + } + + private fun start(token: String, coreLease: ICoreTetheringLease = lease): Int { + val parameters = HotspotRoutingConfig.parametersFromSnapshot(snapshot) + return service.startRouting( + parameters.useHev, parameters.profileName, parameters.dnsServers.toTypedArray(), + parameters.ipv6Enabled, parameters.xudpKey, token, parameters.launchId, coreLease, + ) + } + + @Test + fun duplicateStartDoesNotTouchEitherLease() { + val calls = AtomicInteger() + val countedLease = object : DelegatingLease(lease) { + override fun openEngineConfig(launchId: String): ParcelFileDescriptor { + calls.incrementAndGet() + return super.openEngineConfig(launchId) + } + override fun holdTestNetwork(tun: ParcelFileDescriptor) { + calls.incrementAndGet() + super.holdTestNetwork(tun) + } + override fun releaseTestNetwork() { + calls.incrementAndGet() + super.releaseTestNetwork() + } + } + assertEquals(0, start(UUID.randomUUID().toString(), countedLease)) + calls.set(0) + assertEquals(ShizukuTetheringService.RESULT_ALREADY_ACTIVE, start(UUID.randomUUID().toString(), countedLease)) + assertEquals(0, calls.get()) + assertTrue(service.getStatus(false).hasRoutingSession) + } + + @Test + fun lateCoreUpdateCannotUndoExplicitStop() { + val token = UUID.randomUUID().toString() + assertEquals(0, start(token)) + assertEquals(0, service.stopRouting()) + val applied = CountDownLatch(1) + service.setStatusListener(object : ITetheringStatusListener.Stub() { + override fun onStatusChanged() { applied.countDown() } + }) + val parameters = HotspotRoutingConfig.parametersFromSnapshot(snapshot) + service.synchronizeRouting( + token, parameters.useHev, parameters.profileName, parameters.dnsServers.toTypedArray(), + parameters.ipv6Enabled, parameters.xudpKey, parameters.launchId, lease, + ) + assertTrue(applied.await(5, TimeUnit.SECONDS)) + assertFalse(service.getStatus(false).hasRoutingSession) + } + + @Test + fun listenerRemovalDoesNotWaitForBlockedStartup() { + val entered = CountDownLatch(1) + val release = CountDownLatch(1) + val blockingLease = object : DelegatingLease(lease) { + override fun openEngineConfig(launchId: String): ParcelFileDescriptor { + entered.countDown() + check(release.await(10, TimeUnit.SECONDS)) + return super.openEngineConfig(launchId) + } + } + val worker = Executors.newSingleThreadExecutor() + try { + val start = worker.submit { start(UUID.randomUUID().toString(), blockingLease) } + assertTrue(entered.await(5, TimeUnit.SECONDS)) + val before = System.nanoTime() + service.setStatusListener(null) + assertTrue(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - before) < 1000) + release.countDown() + assertEquals(0, start.get(30, TimeUnit.SECONDS)) + } finally { + release.countDown() + worker.shutdownNow() + } + } + + @Test + fun staleLaunchCannotReadCurrentConfiguration() { + assertFalse(lease.isCurrentLaunch("obsolete-launch")) + assertThrows(Exception::class.java) { lease.openEngineConfig("obsolete-launch") } + assertTrue(lease.isCurrentLaunch(requireNotNull(snapshot.launchId))) + lease.openEngineConfig(snapshot.launchId).use { assertTrue(it.statSize > 0) } + } + + @Test + fun exitedHevWorkerIsReportedAndCanStillBeStopped() { + assumeTrue(snapshot.useHev) + val invalidConfig = object : DelegatingLease(lease) { + override fun openEngineConfig(launchId: String): ParcelFileDescriptor { + val file = File.createTempFile("invalid-hev-", ".yaml", context.cacheDir) + try { + file.writeText("this is not a HEV configuration") + return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY) + } finally { + file.delete() + } + } + } + val result = start(UUID.randomUUID().toString(), invalidConfig) + assertTrue(result == 0 || result == ShizukuTetheringService.RESULT_ROUTING_FAILED) + awaitStatus { it.routingState == ShizukuTetheringService.ROUTING_STATE_ERROR } + if (result == 0) assertTrue(service.getStatus(false).hasRoutingSession) + assertEquals(0, service.stopRouting()) + assertFalse(service.getStatus(false).hasRoutingSession) + } + + @Test + fun coreStopKeepsHotspotOnDeadTunAndRestartResumesIt() { + val token = UUID.randomUUID().toString() + assertEquals(0, start(token)) + assertEquals(0, service.setWifiHotspotEnabled(true)) + val before = service.getStatus(false) + assertEquals(ShizukuTetheringService.RESULT_OK, before.warning) + assertEquals(1, before.activeTetheringTypes and 1) + assertTrue(before.routingDetail.startsWith("testtun")) + service.notifyCoreStopping(token) + awaitStatus { it.routingState == ShizukuTetheringService.ROUTING_STATE_WAITING } + val stopped = service.getStatus(false) + assertEquals(before.routingDetail, stopped.routingDetail) + assertEquals(before.activeTetheringTypes, stopped.activeTetheringTypes) + val parameters = HotspotRoutingConfig.parametersFromSnapshot(snapshot) + service.synchronizeRouting( + token, parameters.useHev, parameters.profileName, parameters.dnsServers.toTypedArray(), + parameters.ipv6Enabled, parameters.xudpKey, parameters.launchId, lease, + ) + awaitStatus { it.routingState == before.routingState } + assertEquals(before.activeTetheringTypes, service.getStatus(false).activeTetheringTypes) + } + + @Test + fun unsafeUpstreamStopsHotspotEvenWhileConfigurationReadIsBlocked() { + val token = UUID.randomUUID().toString() + assertEquals(0, start(token)) + assertEquals(0, service.setWifiHotspotEnabled(true)) + val entered = CountDownLatch(1) + val release = CountDownLatch(1) + val blockingLease = object : DelegatingLease(lease) { + override fun openEngineConfig(launchId: String): ParcelFileDescriptor { + entered.countDown() + check(release.await(20, TimeUnit.SECONDS)) + return super.openEngineConfig(launchId) + } + } + instrumentation.uiAutomation.adoptShellPermissionIdentity() + var observer: TetheringUpstreamMonitor? = null + try { + val manager = requireNotNull(context.getSystemService("tethering")) + val connectivity = context.getSystemService(android.net.ConnectivityManager::class.java) + observer = if (usesPublicTetheringApi()) { + TetheringApi36.observeUpstream(manager, connectivity, Runnable::run) {} + } else { + TetheringPlatformCompat.observeUpstreamLegacy(manager, connectivity, Runnable::run) {} + } + assertTrue(observer.awaitInterfaces(5).isNotEmpty()) + val parameters = HotspotRoutingConfig.parametersFromSnapshot(snapshot) + service.synchronizeRouting( + token, parameters.useHev, parameters.profileName, parameters.dnsServers.toTypedArray(), + parameters.ipv6Enabled, parameters.xudpKey, parameters.launchId, blockingLease, + ) + assertTrue(entered.await(5, TimeUnit.SECONDS)) + manager.javaClass.getMethod("setPreferTestNetworks", Boolean::class.javaPrimitiveType).invoke(manager, false) + // The preference only affects the next upstream selection. Start a downstream from + // outside our service while its lifecycle is blocked to force that selection now. + if (usesPublicTetheringApi()) { + assertEquals(0, TetheringApi36.stopTethering(manager, 0, Runnable::run, 5)) + } else { + assertEquals(0, TetheringPlatformCompat.stopTethering(manager, 0)) + } + val stoppedDeadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5) + while (observer.awaitInterfaces(2).isNotEmpty() && System.nanoTime() < stoppedDeadline) Thread.sleep(100) + assertTrue(observer.awaitInterfaces(2).isEmpty()) + val startResult = if (usesPublicTetheringApi()) { + TetheringApi36.startTethering(manager, 0, Runnable::run, 5) + } else { + TetheringPlatformCompat.startTethering(manager, 0, Runnable::run, 5) + } + assertEquals(0, startResult) + Thread.sleep(1000) + // Read Android's independent observer, not getStatus(), which correctly serializes + // with the deliberately blocked lifecycle operation under test. + val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(8) + while (observer.awaitInterfaces(2).isNotEmpty() && System.nanoTime() < deadline) Thread.sleep(100) + assertTrue("Unsafe hotspot remained active behind the lifecycle lock", observer.awaitInterfaces(2).isEmpty()) + release.countDown() + assertEquals(ShizukuTetheringService.RESULT_UNPROTECTED_UPSTREAM, service.getStatus(false).warning) + assertEquals(ShizukuTetheringService.RESULT_OK, service.getStatus(false).warning) + } finally { + release.countDown() + observer?.close() + instrumentation.uiAutomation.dropShellPermissionIdentity() + } + } + + private fun awaitStatus(matches: (TetheringStatusSnapshot) -> Boolean) { + val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(15) + while (System.nanoTime() < deadline) { + if (matches(service.getStatus(false))) return + Thread.sleep(100) + } + throw AssertionError("Timed out waiting for tethering status") + } + + private open class DelegatingLease(private val delegate: ICoreTetheringLease) : ICoreTetheringLease.Stub() { + override fun openEngineConfig(launchId: String): ParcelFileDescriptor = delegate.openEngineConfig(launchId) + override fun isCurrentLaunch(launchId: String): Boolean = delegate.isCurrentLaunch(launchId) + override fun holdTestNetwork(tun: ParcelFileDescriptor) = delegate.holdTestNetwork(tun) + override fun releaseTestNetwork() = delegate.releaseTestNetwork() + override fun assetFingerprint(): String = delegate.assetFingerprint() + override fun listAssetFiles(): Array = delegate.listAssetFiles() + override fun openAssetFile(name: String): ParcelFileDescriptor = delegate.openAssetFile(name) + } +} diff --git a/V2rayNG/app/src/main/AndroidManifest.xml b/V2rayNG/app/src/main/AndroidManifest.xml index 1b658411df8..b69567b5cce 100644 --- a/V2rayNG/app/src/main/AndroidManifest.xml +++ b/V2rayNG/app/src/main/AndroidManifest.xml @@ -211,6 +211,14 @@ + + @@ -218,6 +226,14 @@ android:name=".ui.TranslatorsActivity" android:exported="false" /> + + = Build.VERSION_CODES.TIRAMISU) { + // The VPN core process must receive replacement Shizuku Binders after a server restart. + ShizukuProvider.enableMultiProcessSupport(Application.getProcessName() == packageName) + } } private val workManagerConfiguration: Configuration = Configuration.Builder() @@ -47,5 +54,7 @@ class AngApplication : Application() { // Initialize theme state from MMKV ThemeManager.refresh() + + ShizukuForegroundRecovery.register(this) } } diff --git a/V2rayNG/app/src/main/java/com/v2ray/ang/AppConfig.kt b/V2rayNG/app/src/main/java/com/v2ray/ang/AppConfig.kt index e55b1d5a3d7..54487ab67be 100644 --- a/V2rayNG/app/src/main/java/com/v2ray/ang/AppConfig.kt +++ b/V2rayNG/app/src/main/java/com/v2ray/ang/AppConfig.kt @@ -86,6 +86,7 @@ object AppConfig { const val PREF_HEV_TUNNEL_RW_TIMEOUT = "pref_hev_tunnel_rw_timeout_v2" const val PREF_UPDATE_SUBSCRIPTION = "pref_update_subscription" const val PREF_AUTO_TEST_AFTER_UPDATE_SUBSCRIPTION = "pref_auto_test_after_update_subscription" + const val PREF_SHIZUKU_SYNC_TOKEN = "pref_shizuku_sync_token" const val PREF_AUTO_REMOVE_INVALID_AFTER_TEST = "pref_auto_remove_invalid_after_test" const val PREF_AUTO_SORT_AFTER_TEST = "pref_auto_sort_after_test" const val PREF_REAL_PING_CONCURRENCY = "pref_real_ping_concurrency" @@ -199,6 +200,9 @@ object AppConfig { const val MSG_MEASURE_CONFIG_SUCCESS = 72 const val MSG_MEASURE_CONFIG_NOTIFY = 73 const val MSG_MEASURE_CONFIG_FINISH = 74 + const val MSG_QUERY_HOTSPOT_CONFIG = 91 + const val MSG_HOTSPOT_CONFIG_RESPONSE = 92 + const val MSG_SHIZUKU_APP_FOREGROUND = 93 const val MSG_SUB_UPDATE_START = 8 const val MSG_SUB_UPDATE_CANCEL = 81 @@ -252,6 +256,17 @@ object AppConfig { const val ROOT_LAN_DNS = "1.1.1.1" // fallback resolver for tethered clients when no plain-IPv4 DNS is configured const val ROOT_OOM_SCORE = "-1000" // oom_score_adj that makes the LMK never kill us + /** Shizuku test-network TUN used as Android tethering's preferred upstream. */ + const val SHIZUKU_TUN_ADDR_V4 = "192.0.2.2/24" + /** + * Android only delegates a /64 that it considers globally scoped. The documentation + * prefix satisfies that platform requirement without claiming a real public network. + */ + const val SHIZUKU_TUN_ADDR_V6 = "2001:db8:9877::1/64" + + /** IPv6-shaped DNS hint required by Android; configured app resolvers remain first. */ + const val SHIZUKU_TUN_DNS_HINT_V6 = "fdfe:dcba:9877::53" + /** hev-sock5-tunnel read-write-timeout value */ const val HEVTUN_RW_TIMEOUT = "300,60" diff --git a/V2rayNG/app/src/main/java/com/v2ray/ang/core/CoreServiceManager.kt b/V2rayNG/app/src/main/java/com/v2ray/ang/core/CoreServiceManager.kt index 56bd3d28e03..f325c0f5555 100644 --- a/V2rayNG/app/src/main/java/com/v2ray/ang/core/CoreServiceManager.kt +++ b/V2rayNG/app/src/main/java/com/v2ray/ang/core/CoreServiceManager.kt @@ -28,6 +28,7 @@ import com.v2ray.ang.helper.MessageHelper import com.v2ray.ang.service.DialerNativeService import com.v2ray.ang.service.DialerWebviewService import com.v2ray.ang.service.NetworkMonitor +import com.v2ray.ang.shizuku.TetheringCoreSync import com.v2ray.ang.util.LogUtil import com.v2ray.ang.util.Utils import kotlinx.coroutines.CoroutineScope @@ -43,15 +44,22 @@ import libv2ray.CoreController import libv2ray.ProcessFinder import java.lang.ref.SoftReference import java.net.InetSocketAddress +import java.util.concurrent.ExecutorService +import java.util.concurrent.Executors object CoreServiceManager { private val coreController: CoreController = CoreNativeManager.newCoreController(CoreCallback()) private val mMsgReceive = ReceiveMessageHandler() + private val tetheringMsgReceive = TetheringMessageHandler() private var currentConfig: ProfileItem? = null + private var currentProfileId = "" private var processFinder: XrayProcessFinder? = null private var browserDialer: IDialerService? = null private var networkMonitor: NetworkMonitor? = null + private val teardownLock = Any() + private var teardownExecutor: ExecutorService? = null + private var receiversRegistered = false private val connectionTestScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) @Volatile @@ -100,12 +108,15 @@ object CoreServiceManager { return false } + TetheringCoreSync.onStarting() try { doStartCoreLoop(service, vpnInterface) return true } catch (e: Exception) { val message = e.message?.takeUnless { it.isBlank() } ?: e.javaClass.simpleName LogUtil.e(AppConfig.TAG, "StartCore-Manager: $message", e) + TetheringCoreSync.onStartFailed(service, message) + cleanupFailedStart(service) MessageHelper.sendMsg2UI(service, AppConfig.MSG_STATE_START_FAILURE, message) NotificationManager.cancelNotification() return false @@ -114,11 +125,7 @@ object CoreServiceManager { @Throws(Exception::class) private fun doStartCoreLoop(service: Service, vpnInterface: ParcelFileDescriptor?) { - val mFilter = IntentFilter(AppConfig.BROADCAST_ACTION_SERVICE) - mFilter.addAction(Intent.ACTION_SCREEN_ON) - mFilter.addAction(Intent.ACTION_SCREEN_OFF) - mFilter.addAction(Intent.ACTION_USER_PRESENT) - ContextCompat.registerReceiver(service, mMsgReceive, mFilter, Utils.receiverFlags()) + registerCoreReceivers(service) currentVpnInterface = vpnInterface launchCore(service, vpnInterface) @@ -129,6 +136,7 @@ object CoreServiceManager { private fun launchCore(service: Service, vpnInterface: ParcelFileDescriptor?, isReload: Boolean = false) { val guid = MmkvManager.getSelectServer() ?: error("No server selected") val config = MmkvManager.decodeServerConfig(guid) ?: error("Failed to decode server config") + currentProfileId = guid LogUtil.i(AppConfig.TAG, "StartCore-Manager: Starting core loop for ${config.remarks}") val result = CoreConfigManager.getV2rayConfig(service, guid) @@ -138,6 +146,7 @@ object CoreServiceManager { } currentConfig = config + val usesHevTun = SettingsManager.isUsingHevTun() var tunFd = vpnInterface?.fd ?: 0 val dialerMode = BrowserDialerMode.from(config.browserDialerMode) val dialerAddr = if (dialerMode != null) { @@ -145,7 +154,7 @@ object CoreServiceManager { } else { "" } - if (SettingsManager.isUsingHevTun()) { + if (usesHevTun) { tunFd = 0 } @@ -177,6 +186,13 @@ object CoreServiceManager { else -> {} } + TetheringCoreSync.onStarted( + service, + guid, + getRunningServerName(), + result.content, + usesHevTun, + ) if (!isReload) { MessageHelper.sendMsg2UI(service, AppConfig.MSG_STATE_START_SUCCESS, "") } @@ -191,21 +207,18 @@ object CoreServiceManager { */ fun stopCoreLoop(): Boolean { connectionTestScope.coroutineContext.cancelChildren() - val service = getService() ?: return false + val service = getService() + if (service == null) { + TetheringCoreSync.clear() + return false + } + TetheringCoreSync.onStopping(service) networkMonitor?.unregister() networkMonitor = null currentVpnInterface = null - if (isRunning()) { - CoroutineScope(Dispatchers.IO).launch { - try { - coreController.stopLoop() - } catch (e: Exception) { - LogUtil.e(AppConfig.TAG, "StartCore-Manager: Failed to stop V2Ray loop", e) - } - } - } + stopNativeCoreAsync(service, "stop") // Close existing browser dialer CoreNativeManager.reconcileBrowserDialer("") @@ -217,13 +230,107 @@ object CoreServiceManager { MessageHelper.sendMsg2UI(service, AppConfig.MSG_STATE_STOP_SUCCESS, "") NotificationManager.cancelNotification() + unregisterCoreReceivers(service) + + return true + } + + private fun registerCoreReceivers(service: Service) { + if (receiversRegistered) return + val coreFilter = IntentFilter(AppConfig.BROADCAST_ACTION_SERVICE).apply { + addAction(Intent.ACTION_SCREEN_ON) + addAction(Intent.ACTION_SCREEN_OFF) + addAction(Intent.ACTION_USER_PRESENT) + } + ContextCompat.registerReceiver(service, mMsgReceive, coreFilter, Utils.receiverFlags()) try { - service.unregisterReceiver(mMsgReceive) - } catch (e: Exception) { - LogUtil.e(AppConfig.TAG, "StartCore-Manager: Failed to unregister receiver", e) + ContextCompat.registerReceiver( + service, + tetheringMsgReceive, + IntentFilter(AppConfig.BROADCAST_ACTION_SERVICE), + Utils.receiverFlags(), + ) + receiversRegistered = true + } catch (error: Throwable) { + runCatching { service.unregisterReceiver(mMsgReceive) } + throw error } + } - return true + private fun unregisterCoreReceivers(service: Service) { + if (!receiversRegistered) return + receiversRegistered = false + listOf(mMsgReceive, tetheringMsgReceive).forEach { receiver -> + runCatching { service.unregisterReceiver(receiver) } + .onFailure { + LogUtil.e( + AppConfig.TAG, + "Core lifecycle failure: mode=${service.javaClass.simpleName} phase=stop " + + "profileId=$currentProfileId operation=unregister receiver", + it, + ) + } + } + } + + private fun cleanupFailedStart(service: Service) { + networkMonitor?.unregister() + networkMonitor = null + currentVpnInterface = null + stopNativeCoreAsync(service, "start-failure") + CoreNativeManager.reconcileBrowserDialer("") + runCatching { browserDialer?.stop() } + .onFailure { + LogUtil.e( + AppConfig.TAG, + "Core lifecycle failure: mode=${service.javaClass.simpleName} phase=start-failure " + + "profileId=$currentProfileId operation=stop browser dialer", + it, + ) + } + browserDialer = null + unregisterCoreReceivers(service) + } + + /** Runs native teardown in one operation-owned scope and coalesces repeated stop requests. */ + private fun stopNativeCoreAsync(service: Service, phase: String) { + synchronized(teardownLock) { + if (!shouldScheduleCoreTeardown(isRunning(), teardownExecutor != null)) return + val profileId = currentProfileId + val mode = service.javaClass.simpleName + val executor = Executors.newSingleThreadExecutor { command -> + Thread(command, "CoreTeardown").apply { isDaemon = true } + } + teardownExecutor = executor + try { + executor.execute { + try { + coreController.stopLoop() + } catch (error: Throwable) { + LogUtil.e( + AppConfig.TAG, + "Core lifecycle failure: mode=$mode phase=$phase profileId=$profileId " + + "operation=stop native core", + error, + ) + } finally { + synchronized(teardownLock) { + if (teardownExecutor === executor) teardownExecutor = null + } + executor.shutdown() + } + } + } catch (error: Throwable) { + teardownExecutor = null + executor.shutdownNow() + LogUtil.e( + AppConfig.TAG, + "Core lifecycle failure: mode=$mode phase=$phase profileId=$profileId " + + "operation=schedule native core stop", + error, + ) + } + } } /** @@ -264,6 +371,7 @@ object CoreServiceManager { connectionTestScope.coroutineContext.cancelChildren() LogUtil.i(AppConfig.TAG, "StartCore-Manager: Core reload start...") + TetheringCoreSync.onStopping(service) coreController.stopLoop() launchCore(service, tunFd, isReload = true) @@ -272,6 +380,7 @@ object CoreServiceManager { } catch (e: Exception) { val message = e.message?.takeUnless { it.isBlank() } ?: e.javaClass.simpleName LogUtil.e(AppConfig.TAG, "StartCore-Manager: Failed to reload core: $message", e) + TetheringCoreSync.onStartFailed(service, message) MessageHelper.sendMsg2UI(service, AppConfig.MSG_STATE_START_FAILURE, message) false } finally { @@ -536,4 +645,18 @@ object CoreServiceManager { } } } + + private class TetheringMessageHandler : BroadcastReceiver() { + override fun onReceive(context: Context?, intent: Intent?) { + val service = serviceControl?.get()?.getService() ?: return + when (intent?.getIntExtra("key", 0)) { + AppConfig.MSG_QUERY_HOTSPOT_CONFIG -> + TetheringCoreSync.sendCurrentSnapshot(service, coreController.isRunning) + AppConfig.MSG_SHIZUKU_APP_FOREGROUND -> TetheringCoreSync.onAppForegrounded(service) + } + } + } } + +internal fun shouldScheduleCoreTeardown(coreRunning: Boolean, teardownActive: Boolean): Boolean = + coreRunning && !teardownActive diff --git a/V2rayNG/app/src/main/java/com/v2ray/ang/dto/HotspotRoutingSnapshot.kt b/V2rayNG/app/src/main/java/com/v2ray/ang/dto/HotspotRoutingSnapshot.kt new file mode 100644 index 00000000000..8a0a2faafaa --- /dev/null +++ b/V2rayNG/app/src/main/java/com/v2ray/ang/dto/HotspotRoutingSnapshot.kt @@ -0,0 +1,37 @@ +package com.v2ray.ang.dto + +import java.io.Serializable + +/** + * Exact launch parameters captured by the running core process for Shizuku tethering. + * + * The normal core lives in a dedicated Android process. Sending this snapshot over the existing + * app-scoped broadcast channel avoids regenerating a configuration from settings that may have + * changed since that core was started. + */ +data class HotspotRoutingSnapshot( + val running: Boolean = false, + val vpnMode: Boolean = false, + val profileName: String = "", + val useHev: Boolean = false, + val ipv6Enabled: Boolean = false, + // This is the same IP-only list advertised by CoreVpnService. When local DNS is enabled, + // the generated core configuration intercepts its port-53 traffic and sends it to dns-out; + // otherwise the configured addresses remain ordinary routed DNS destinations. + val vpnDnsServers: List = emptyList(), + val socksPort: Int = 0, + val socksUsername: String? = null, + val socksPassword: String? = null, + val mtu: Int = 0, + val hevTcpTimeoutSeconds: Int = 0, + val hevUdpTimeoutSeconds: Int = 0, + val hevLogLevel: String = "warn", + // Unlike the tethering session token, this identity changes on every main-core launch. + // Nullable for broadcasts from an older app process during an APK update. Such snapshots + // cannot authorize a new engine; request fresh launch metadata instead. + val launchId: String? = null, +) : Serializable { + companion object { + private const val serialVersionUID = 5L + } +} diff --git a/V2rayNG/app/src/main/java/com/v2ray/ang/dto/HotspotRoutingSync.kt b/V2rayNG/app/src/main/java/com/v2ray/ang/dto/HotspotRoutingSync.kt new file mode 100644 index 00000000000..5e9649885c2 --- /dev/null +++ b/V2rayNG/app/src/main/java/com/v2ray/ang/dto/HotspotRoutingSync.kt @@ -0,0 +1,19 @@ +package com.v2ray.ang.dto + +import java.io.Serializable + +/** Authenticated native-core lifecycle update for the shell-owned tethering daemon. */ +data class HotspotRoutingSync( + val token: String, + val event: Int, + val snapshot: HotspotRoutingSnapshot? = null, + val detail: String = "", +) : Serializable { + companion object { + private const val serialVersionUID = 1L + + const val EVENT_CORE_STOPPING = 1 + const val EVENT_CORE_STARTED = 2 + const val EVENT_CORE_START_FAILED = 3 + } +} diff --git a/V2rayNG/app/src/main/java/com/v2ray/ang/service/HevTunnelConfig.kt b/V2rayNG/app/src/main/java/com/v2ray/ang/service/HevTunnelConfig.kt new file mode 100644 index 00000000000..ace4417b02e --- /dev/null +++ b/V2rayNG/app/src/main/java/com/v2ray/ang/service/HevTunnelConfig.kt @@ -0,0 +1,71 @@ +package com.v2ray.ang.service + +import com.v2ray.ang.AppConfig +import com.v2ray.ang.handler.MmkvManager + +internal data class HevTunnelSettings( + val tcpTimeoutSeconds: Int, + val udpTimeoutSeconds: Int, + val logLevel: String, +) { + companion object { + fun current(): HevTunnelSettings { + val timeouts = parseTimeouts( + MmkvManager.decodeSettingsString(AppConfig.PREF_HEV_TUNNEL_RW_TIMEOUT), + ) + return HevTunnelSettings( + tcpTimeoutSeconds = timeouts.first, + udpTimeoutSeconds = timeouts.second, + logLevel = MmkvManager.decodeSettingsString(AppConfig.PREF_HEV_TUNNEL_LOGLEVEL) + ?: AppConfig.DEFAULT_HEV_TUNNEL_LOGLEVEL, + ) + } + + internal fun parseTimeouts(value: String?): Pair { + val parts = (value ?: AppConfig.HEVTUN_RW_TIMEOUT).split(',') + .map { it.trim() } + .filter { it.isNotEmpty() } + return Pair( + parts.getOrNull(0)?.toIntOrNull() ?: DEFAULT_TCP_TIMEOUT_SECONDS, + parts.getOrNull(1)?.toIntOrNull() ?: DEFAULT_UDP_TIMEOUT_SECONDS, + ) + } + + private const val DEFAULT_TCP_TIMEOUT_SECONDS = 300 + private const val DEFAULT_UDP_TIMEOUT_SECONDS = 60 + } +} + +internal data class HevTunnelParameters( + val mtu: Int, + val ipv4: String, + val ipv6: String? = null, + val socksAddress: String, + val socksPort: Int, + val socksUsername: String? = null, + val socksPassword: String? = null, + val settings: HevTunnelSettings, +) + +internal object HevTunnelConfig { + fun build(parameters: HevTunnelParameters): String = buildString { + appendLine("tunnel:") + appendLine(" mtu: ${parameters.mtu}") + appendLine(" ipv4: '${parameters.ipv4.yamlSingleQuoted()}'") + parameters.ipv6?.let { appendLine(" ipv6: '${it.yamlSingleQuoted()}'") } + appendLine("socks5:") + appendLine(" port: ${parameters.socksPort}") + appendLine(" address: '${parameters.socksAddress.yamlSingleQuoted()}'") + appendLine(" udp: 'udp'") + if (parameters.socksUsername != null && parameters.socksPassword != null) { + appendLine(" username: '${parameters.socksUsername.yamlSingleQuoted()}'") + appendLine(" password: '${parameters.socksPassword.yamlSingleQuoted()}'") + } + appendLine("misc:") + appendLine(" tcp-read-write-timeout: ${parameters.settings.tcpTimeoutSeconds * 1000}") + appendLine(" udp-read-write-timeout: ${parameters.settings.udpTimeoutSeconds * 1000}") + appendLine(" log-level: '${parameters.settings.logLevel.yamlSingleQuoted()}'") + } + + private fun String.yamlSingleQuoted(): String = replace("'", "''") +} diff --git a/V2rayNG/app/src/main/java/com/v2ray/ang/service/TProxyService.kt b/V2rayNG/app/src/main/java/com/v2ray/ang/service/TProxyService.kt index a8b2da853b3..8c557a5c225 100644 --- a/V2rayNG/app/src/main/java/com/v2ray/ang/service/TProxyService.kt +++ b/V2rayNG/app/src/main/java/com/v2ray/ang/service/TProxyService.kt @@ -35,6 +35,21 @@ class TProxyService( @Suppress("FunctionName") private external fun TProxyGetStats(): LongArray? + /** + * Starts a second HEV instance from a dedicated process. + * + * The Shizuku tethering UserService runs in its own process, so HEV's process-global + * native state is independent from the instance serving the regular VpnService TUN. + */ + internal fun startExternalTunnel(configPath: String, fd: Int): Boolean = TProxyStartService(configPath, fd) + + internal fun isExternalTunnelRunning(): Boolean = TProxyIsRunning() + + /** Stops the HEV instance started in the current process. */ + internal fun stopExternalTunnel() { + TProxyStopService() + } + init { System.loadLibrary("hev-socks5-tunnel") } @@ -62,43 +77,21 @@ class TProxyService( } private fun buildConfig(): String { - val socksPort = SettingsManager.getSocksPort() - val socksUsername = SettingsManager.getSocksUsername() - val socksPassword = SettingsManager.getSocksPassword() val vpnConfig = SettingsManager.getCurrentVpnInterfaceAddressConfig() - val escapedSocksUsername = socksUsername?.replace("'", "''") - val escapedSocksPassword = socksPassword?.replace("'", "''") - return buildString { - appendLine("tunnel:") - appendLine(" mtu: ${SettingsManager.getVpnMtu()}") - appendLine(" ipv4: ${vpnConfig.ipv4Client}") - - if (MmkvManager.decodeSettingsBool(AppConfig.PREF_IPV6_ENABLED)) { - appendLine(" ipv6: '${vpnConfig.ipv6Client}'") - } - - appendLine("socks5:") - appendLine(" port: ${socksPort}") - appendLine(" address: ${AppConfig.LOOPBACK}") - appendLine(" udp: 'udp'") - if (escapedSocksUsername != null && escapedSocksPassword != null) { - appendLine(" username: '${escapedSocksUsername}'") - appendLine(" password: '${escapedSocksPassword}'") - } - - // Read-write timeout settings - val timeoutSetting = MmkvManager.decodeSettingsString(AppConfig.PREF_HEV_TUNNEL_RW_TIMEOUT) ?: AppConfig.HEVTUN_RW_TIMEOUT - val parts = timeoutSetting.split(",") - .map { it.trim() } - .filter { it.isNotEmpty() } - val tcpTimeout = parts.getOrNull(0)?.toIntOrNull() ?: 300 - val udpTimeout = parts.getOrNull(1)?.toIntOrNull() ?: 60 - - appendLine("misc:") - appendLine(" tcp-read-write-timeout: ${tcpTimeout * 1000}") - appendLine(" udp-read-write-timeout: ${udpTimeout * 1000}") - appendLine(" log-level: ${MmkvManager.decodeSettingsString(AppConfig.PREF_HEV_TUNNEL_LOGLEVEL, AppConfig.DEFAULT_HEV_TUNNEL_LOGLEVEL)}") - } + return HevTunnelConfig.build( + HevTunnelParameters( + mtu = SettingsManager.getVpnMtu(), + ipv4 = vpnConfig.ipv4Client, + ipv6 = vpnConfig.ipv6Client.takeIf { + MmkvManager.decodeSettingsBool(AppConfig.PREF_IPV6_ENABLED) + }, + socksAddress = AppConfig.LOOPBACK, + socksPort = SettingsManager.getSocksPort(), + socksUsername = SettingsManager.getSocksUsername(), + socksPassword = SettingsManager.getSocksPassword(), + settings = HevTunnelSettings.current(), + ), + ) } /** diff --git a/V2rayNG/app/src/main/java/com/v2ray/ang/shizuku/HotspotRoutingConfig.kt b/V2rayNG/app/src/main/java/com/v2ray/ang/shizuku/HotspotRoutingConfig.kt new file mode 100644 index 00000000000..57fcb90cbf0 --- /dev/null +++ b/V2rayNG/app/src/main/java/com/v2ray/ang/shizuku/HotspotRoutingConfig.kt @@ -0,0 +1,103 @@ +package com.v2ray.ang.shizuku + +import com.google.gson.JsonArray +import com.v2ray.ang.AppConfig +import com.v2ray.ang.dto.HotspotRoutingSnapshot +import com.v2ray.ang.service.HevTunnelConfig +import com.v2ray.ang.service.HevTunnelParameters +import com.v2ray.ang.service.HevTunnelSettings +import com.v2ray.ang.util.JsonUtil +import com.v2ray.ang.util.Utils + +internal data class HotspotRoutingEngineConfig( + val useHev: Boolean, + val profileName: String, + val content: String, +) + +internal data class HotspotRoutingLaunchConfig( + val engine: HotspotRoutingEngineConfig, + val dnsServers: List, + val ipv6Enabled: Boolean, + val xudpKey: String, +) + +internal data class HotspotRoutingParameters( + val launchId: String, + val useHev: Boolean, + val profileName: String, + val dnsServers: List, + val ipv6Enabled: Boolean, + val xudpKey: String, +) + +/** Builds the privileged datapath configuration from the exact running-core snapshot. */ +internal object HotspotRoutingConfig { + + fun parametersFromSnapshot(snapshot: HotspotRoutingSnapshot): HotspotRoutingParameters { + requireRoutableSnapshot(snapshot) + return HotspotRoutingParameters( + launchId = requireNotNull(snapshot.launchId) { "Core launch identity is unavailable" }, + useHev = snapshot.useHev, + profileName = snapshot.profileName, + dnsServers = snapshot.vpnDnsServers, + ipv6Enabled = snapshot.ipv6Enabled, + xudpKey = Utils.getDeviceIdForXUDPBaseKey(), + ) + } + + fun engineContentFromSnapshot(snapshot: HotspotRoutingSnapshot, coreConfig: String): String { + requireRoutableSnapshot(snapshot) + return if (snapshot.useHev) buildHevConfig(snapshot) else nativeTunOnlyConfig(coreConfig) + } + + private fun requireRoutableSnapshot(snapshot: HotspotRoutingSnapshot) { + require(snapshot.running) { "Start v2rayNG before enabling tethering routing" } + require(snapshot.vpnMode) { "v2rayNG must be running in VPN mode" } + } + + private fun nativeTunOnlyConfig(rawConfig: String): String { + val root = JsonUtil.parseString(rawConfig) + ?: error("The running Xray configuration is invalid") + val inbounds = root.get("inbounds") + ?.takeIf { it.isJsonArray } + ?.asJsonArray + ?: error("The running Xray configuration has no inbounds") + val tunInbounds = JsonArray() + inbounds.forEach { inbound -> + val protocol = inbound.takeIf { it.isJsonObject } + ?.asJsonObject + ?.get("protocol") + ?.takeIf { it.isJsonPrimitive } + ?.asString + if (protocol == "tun") tunInbounds.add(inbound.deepCopy()) + } + require(tunInbounds.size() > 0) { "The running Xray configuration has no TUN inbound" } + + // The normal core already owns its SOCKS/HTTP listener ports. The hotspot core only + // needs the TUN inbound; all outbounds, DNS, routing, balancing and observatory sections + // are intentionally preserved byte-for-byte at the JSON model level. + root.add("inbounds", tunInbounds) + return JsonUtil.toJsonPretty(root) ?: error("Unable to serialize the hotspot configuration") + } + + private fun buildHevConfig(snapshot: HotspotRoutingSnapshot): String { + return HevTunnelConfig.build( + HevTunnelParameters( + mtu = snapshot.mtu, + ipv4 = AppConfig.SHIZUKU_TUN_ADDR_V4.substringBefore('/'), + ipv6 = AppConfig.SHIZUKU_TUN_ADDR_V6.substringBefore('/') + .takeIf { snapshot.ipv6Enabled }, + socksAddress = AppConfig.LOOPBACK, + socksPort = snapshot.socksPort, + socksUsername = snapshot.socksUsername, + socksPassword = snapshot.socksPassword, + settings = HevTunnelSettings( + tcpTimeoutSeconds = snapshot.hevTcpTimeoutSeconds, + udpTimeoutSeconds = snapshot.hevUdpTimeoutSeconds, + logLevel = snapshot.hevLogLevel, + ), + ), + ) + } +} diff --git a/V2rayNG/app/src/main/java/com/v2ray/ang/shizuku/ShellContextCompat.kt b/V2rayNG/app/src/main/java/com/v2ray/ang/shizuku/ShellContextCompat.kt new file mode 100644 index 00000000000..b7167e85871 --- /dev/null +++ b/V2rayNG/app/src/main/java/com/v2ray/ang/shizuku/ShellContextCompat.kt @@ -0,0 +1,53 @@ +package com.v2ray.ang.shizuku + +import android.annotation.SuppressLint +import android.content.Context +import android.content.ContextWrapper + +/** Creates a context whose Binder attribution matches the Shizuku shell UID. */ +internal object ShellContextCompat { + + // Android has no public API for changing a Context's Binder attribution package. The + // UserService runs as UID 2000, so framework calls must identify com.android.shell. Remove this + // reflection only when Android or Shizuku supplies a public context factory whose op package is + // com.android.shell on every supported feature API; a plain UserService context is insufficient. + @SuppressLint("PrivateApi", "DiscouragedPrivateApi") + fun create(context: Context): Context { + val baseContext = (context as? ContextWrapper)?.baseContext ?: context + val contextImplClass = Class.forName("android.app.ContextImpl") + val activityThreadClass = Class.forName("android.app.ActivityThread") + val loadedApkClass = Class.forName("android.app.LoadedApk") + val mainThread = contextImplClass.getDeclaredField("mMainThread").run { + isAccessible = true + get(baseContext) + } + val systemContext = activityThreadClass.getDeclaredMethod("getSystemContext") + .invoke(mainThread) as Context + val packageContext = systemContext.createPackageContext( + SHELL_PACKAGE_NAME, + Context.CONTEXT_INCLUDE_CODE or Context.CONTEXT_IGNORE_SECURITY, + ) + val loadedApk = contextImplClass.getDeclaredField("mPackageInfo").run { + isAccessible = true + get(packageContext) + } + val createAppContext = contextImplClass.declaredMethods.firstOrNull { + it.name == "createAppContext" && it.parameterTypes.contentEquals( + arrayOf(activityThreadClass, loadedApkClass, String::class.java), + ) + } ?: contextImplClass.getDeclaredMethod( + "createAppContext", + activityThreadClass, + loadedApkClass, + ) + createAppContext.isAccessible = true + + return if (createAppContext.parameterCount == 3) { + createAppContext.invoke(null, mainThread, loadedApk, SHELL_PACKAGE_NAME) as Context + } else { + createAppContext.invoke(null, mainThread, loadedApk) as Context + } + } + + private const val SHELL_PACKAGE_NAME = "com.android.shell" +} diff --git a/V2rayNG/app/src/main/java/com/v2ray/ang/shizuku/ShizukuForegroundRecovery.kt b/V2rayNG/app/src/main/java/com/v2ray/ang/shizuku/ShizukuForegroundRecovery.kt new file mode 100644 index 00000000000..1d1a1a8b34e --- /dev/null +++ b/V2rayNG/app/src/main/java/com/v2ray/ang/shizuku/ShizukuForegroundRecovery.kt @@ -0,0 +1,35 @@ +package com.v2ray.ang.shizuku + +import android.app.Activity +import android.app.Application +import android.os.Build +import android.os.Bundle +import com.v2ray.ang.AppConfig +import com.v2ray.ang.R +import com.v2ray.ang.helper.MessageHelper + +/** Forwards app-foreground events needed to recover a replaced Shizuku Binder. */ +internal object ShizukuForegroundRecovery : Application.ActivityLifecycleCallbacks { + + fun register(application: Application) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.UPSIDE_DOWN_CAKE || + Application.getProcessName() != application.packageName || + !application.resources.getBoolean(R.bool.shizuku_tethering_enabled) + ) return + application.registerActivityLifecycleCallbacks(this) + } + + override fun onActivityResumed(activity: Activity) { + // Android 14+ can defer Shizuku's replacement-Binder notification while the app process is + // cached. Remove this foreground retry only when the minimum supported Shizuku release + // delivers that callback to cached non-provider processes on every supported Android API. + MessageHelper.sendMsg2Service(activity, AppConfig.MSG_SHIZUKU_APP_FOREGROUND, "") + } + + override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) = Unit + override fun onActivityStarted(activity: Activity) = Unit + override fun onActivityPaused(activity: Activity) = Unit + override fun onActivityStopped(activity: Activity) = Unit + override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) = Unit + override fun onActivityDestroyed(activity: Activity) = Unit +} diff --git a/V2rayNG/app/src/main/java/com/v2ray/ang/shizuku/ShizukuRoutingSyncReceiver.kt b/V2rayNG/app/src/main/java/com/v2ray/ang/shizuku/ShizukuRoutingSyncReceiver.kt new file mode 100644 index 00000000000..a0522ccccae --- /dev/null +++ b/V2rayNG/app/src/main/java/com/v2ray/ang/shizuku/ShizukuRoutingSyncReceiver.kt @@ -0,0 +1,169 @@ +package com.v2ray.ang.shizuku + +import android.content.BroadcastReceiver +import android.content.ComponentName +import android.content.Context +import android.content.Intent +import android.content.ServiceConnection +import android.content.pm.PackageManager +import android.os.DeadObjectException +import android.os.Handler +import android.os.IBinder +import android.os.Looper +import com.v2ray.ang.AppConfig +import com.v2ray.ang.dto.HotspotRoutingSync +import com.v2ray.ang.extension.serializable +import com.v2ray.ang.handler.MmkvManager +import com.v2ray.ang.util.LogUtil +import rikka.shizuku.Shizuku +import java.util.ArrayDeque +import java.util.concurrent.Executors + +private const val TAG = "ShizukuSyncReceiver" + +/** Relays app-core lifecycle updates to the shell-owned Shizuku UserService over Binder. */ +class ShizukuRoutingSyncReceiver : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + intent.setExtrasClassLoader(HotspotRoutingSync::class.java.classLoader) + val update = intent.serializable("content") ?: run { + LogUtil.w(TAG, "Ignoring malformed hotspot synchronization broadcast") + return + } + val pendingResult = goAsync() + ShizukuRoutingSyncDispatcher.enqueue(context.applicationContext, update, intent.coreTetheringLease()) { + pendingResult.finish() + } + } +} + +/** Keeps updates ordered across the normal core's stop/start process boundary. */ +private object ShizukuRoutingSyncDispatcher { + private const val BIND_TIMEOUT_MS = 5_000L + + private data class PendingUpdate( + val context: Context, + val update: HotspotRoutingSync, + val coreLease: ICoreTetheringLease?, + val finish: () -> Unit, + val retryAfterDisconnect: Boolean = true, + ) + + private val mainHandler = Handler(Looper.getMainLooper()) + private val worker = Executors.newSingleThreadExecutor() + private val queue = ArrayDeque() + private var service: IShizukuTetheringService? = null + private var binding = false + private var inFlight = false + private var bindGeneration = 0 + + private val connection = object : ServiceConnection { + override fun onServiceConnected(name: ComponentName, binder: IBinder) { + service = IShizukuTetheringService.Stub.asInterface(binder) + binding = false + pump() + } + + override fun onServiceDisconnected(name: ComponentName) { + service = null + binding = false + failAll("Shizuku tethering service disconnected") + } + } + + fun enqueue(context: Context, update: HotspotRoutingSync, coreLease: ICoreTetheringLease?, finish: () -> Unit) { + mainHandler.post { + queue.addLast(PendingUpdate(context, update, coreLease, finish)) + pump() + } + } + + private fun pump() { + if (inFlight || queue.isEmpty()) return + val currentService = service + if (currentService == null) { + bindIfNeeded() + return + } + + val pending = queue.removeFirst() + inFlight = true + worker.execute { + val result = runCatching { forward(currentService, pending) } + mainHandler.post { + if (result.exceptionOrNull() is DeadObjectException && pending.retryAfterDisconnect) { + // ServiceConnection may still hold the old proxy when the new Shizuku Binder arrives. + service = null + queue.addFirst(pending.copy(retryAfterDisconnect = false)) + } else { + result.onFailure { LogUtil.e(TAG, "Unable to forward hotspot synchronization", it) } + pending.finish() + } + inFlight = false + pump() + } + } + } + + private fun bindIfNeeded() { + if (binding) return + if (!Shizuku.pingBinder() || + Shizuku.checkSelfPermission() != PackageManager.PERMISSION_GRANTED + ) { + failAll("Shizuku is unavailable or permission is missing") + return + } + + binding = true + val generation = ++bindGeneration + runCatching { + Shizuku.bindUserService(ShizukuTetheringService.createUserServiceArgs(), connection) + } + .onFailure { + binding = false + failAll("Unable to bind Shizuku tethering service: ${it.message.orEmpty()}") + } + mainHandler.postDelayed({ + if (binding && generation == bindGeneration) { + binding = false + failAll("Timed out binding Shizuku tethering service") + } + }, BIND_TIMEOUT_MS) + } + + private fun forward(service: IShizukuTetheringService, pending: PendingUpdate) { + val update = pending.update + if (MmkvManager.decodeSettingsString(AppConfig.PREF_SHIZUKU_SYNC_TOKEN) != update.token) return + // These are one-way calls. The UserService owns the lengthy work; finish this broadcast + // after handoff rather than holding PendingResult across native startup and Android retries. + when (update.event) { + HotspotRoutingSync.EVENT_CORE_STOPPING -> service.notifyCoreStopping(update.token) + HotspotRoutingSync.EVENT_CORE_STARTED -> { + val snapshot = requireNotNull(update.snapshot) { "Core-start update has no snapshot" } + val coreLease = requireNotNull(pending.coreLease) { + "Core-start update has no protected-network lease" + } + val parameters = HotspotRoutingConfig.parametersFromSnapshot(snapshot) + service.synchronizeRouting( + update.token, + parameters.useHev, + parameters.profileName, + parameters.dnsServers.toTypedArray(), + parameters.ipv6Enabled, + parameters.xudpKey, + parameters.launchId, + coreLease, + ) + } + HotspotRoutingSync.EVENT_CORE_START_FAILED -> { + service.notifyCoreStartFailed(update.token, update.detail) + } + else -> error("Unknown hotspot synchronization event ${update.event}") + } + LogUtil.i(TAG, "Handed off hotspot sync event ${update.event}") + } + + private fun failAll(message: String) { + if (queue.isNotEmpty()) LogUtil.w(TAG, message) + while (queue.isNotEmpty()) queue.removeFirst().finish() + } +} diff --git a/V2rayNG/app/src/main/java/com/v2ray/ang/shizuku/ShizukuTetheringService.kt b/V2rayNG/app/src/main/java/com/v2ray/ang/shizuku/ShizukuTetheringService.kt new file mode 100644 index 00000000000..bdb079cbcbe --- /dev/null +++ b/V2rayNG/app/src/main/java/com/v2ray/ang/shizuku/ShizukuTetheringService.kt @@ -0,0 +1,1280 @@ +package com.v2ray.ang.shizuku + +import android.content.ComponentName +import android.content.Context +import android.net.ConnectivityManager +import android.net.IpPrefix +import android.net.LinkAddress +import android.net.LinkProperties +import android.net.Network +import android.os.Build +import android.os.IBinder +import android.os.ParcelFileDescriptor +import android.util.Log +import androidx.annotation.Keep +import androidx.annotation.RequiresApi +import com.v2ray.ang.AppConfig +import com.v2ray.ang.BuildConfig +import com.v2ray.ang.service.TProxyService +import go.Seq +import libv2ray.CoreCallbackHandler +import libv2ray.CoreController +import libv2ray.Libv2ray +import rikka.shizuku.Shizuku +import rikka.shizuku.SystemServiceHelper +import java.io.File +import java.net.Inet6Address +import java.net.InetAddress +import java.net.NetworkInterface +import java.util.concurrent.CountDownLatch +import java.util.concurrent.Executor +import java.util.concurrent.Executors +import java.util.concurrent.ScheduledFuture +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger +import java.util.concurrent.atomic.AtomicLong +import java.util.concurrent.atomic.AtomicReference + +/** + * Privileged Shizuku process that controls Android tethering and owns its proxy upstream. + * + * Android's TestNetworkManager creates a real kernel TUN without root when called by the shell + * UID. TetheringManager is then told to prefer test networks, so Android's Wi-Fi/USB DHCP, + * forwarding, NAT and DNS machinery sends client traffic into that TUN. A process-local HEV + * instance consumes the TUN through v2rayNG's SOCKS inbound, or a second Xray controller consumes + * it using a configuration derived from the running core. + * + * Selecting a preferred test network and starting a tethering downstream are separate Android + * operations. During that gap, especially while Wi-Fi changes from station to access-point mode, + * Tethering may briefly choose a physical default network. Every downstream start is therefore + * treated as provisional until Android reports only the owned test TUN as its actual upstream. + * Any other non-empty upstream is stopped immediately, keeping the feature fail-closed. + */ +@Keep +class ShizukuTetheringService(context: Context) : IShizukuTetheringService.Stub() { + + // The UserService runs as shell, and framework permission checks also require shell package + // attribution. The ordinary app context is retained only for the embedded Xray runtime. + private val executor = Executor { command -> command.run() } + private val appContext = context.applicationContext + private val shellContext = ShellContextCompat.create(context) + private val tetheringManager = if (usesPublicTetheringApi()) { + TetheringApi36.getManager(shellContext) + } else { + // API 33-35 do not expose the typed service lookup. Delete this string lookup together with + // TetheringPlatformCompat when the feature's minimum supported API becomes 36. + requireNotNull(shellContext.getSystemService(TETHERING_SERVICE)) { + "TetheringManager is unavailable" + } + } + private val connectivityManager = requireNotNull( + shellContext.getSystemService(ConnectivityManager::class.java) + ) { "ConnectivityManager is unavailable" } + // Serialize lifecycle work under one monitor so profile changes and user toggles cannot + // interleave. Only listener registration and emergency downstream stops bypass this lock. + // This state describes our routing engine, not whether Android's hotspot or USB is enabled. + // ACTIVE owns an engine and TUN; WAITING retains the TUN with the engine stopped so clients + // cannot fall back to a direct connection. STARTING/STOPPING may hold partial resources. + // ERROR does not imply cleanup: a failed downstream stop must retain its protected route. + // Resource ownership (routingSession/testTun), rather than ERROR alone, determines whether + // the UI must still offer Stop. DISABLED is reached after protected downstreams are stopped + // and our routing resources are released. + private var routingState = ROUTING_STATE_DISABLED + private var routingProfileName = "" + @Volatile private var routingSession: RoutingSession? = null + // Only a new process may recover a missing session; an explicit Stop must stay stopped. + private var freshUserService = true + @Volatile private var testNetworkHandle: TestNetworkHandle? = null + private val upstreamMonitor by lazy { createUpstreamMonitor() } + private val upstreamRejections = AtomicLong() + // Both lifecycle operations and emergency callbacks report warnings here. A successful retry + // clears only its downstream type, preserving failures for other restored downstreams. + private val wrongUpstreamWarningTypes = AtomicInteger() + // Lifecycle events belong to this privileged process, not a UI BroadcastReceiver's timeout. + private val coreUpdates = Executors.newSingleThreadScheduledExecutor { command -> + Thread(command, "TetheringCoreUpdates").apply { isDaemon = true } + } + private var engineHealthCheck: ScheduledFuture<*>? = null + private val statusListener = AtomicReference() + private var nativeController: CoreController? = null + private var hevConfigFile: File? = null + // Tethering callbacks can acknowledge a start before the downstream appears in the active + // type list. Retain that in-flight intent so concurrent shutdown and failed-start cleanup + // still issue stopTethering instead of mistaking the downstream for already stopped. + @Volatile private var requestedTetheringTypes = 0 + private var coreLease: ICoreTetheringLease? = null + private var coreLifetime: LifetimeWatch? = null + private var stagedAssetFingerprint = "" + + private val routingActive: Boolean + get() = routingState == ROUTING_STATE_ACTIVE_HEV || + routingState == ROUTING_STATE_ACTIVE_NATIVE + + private val testTun: ParcelFileDescriptor? + get() = testNetworkHandle?.tun + private val testInterfaceName: String? + get() = testNetworkHandle?.interfaceName + + private data class RoutingSession( + val token: String, + val xudpKey: String, + var dnsServers: List, + var ipv6Enabled: Boolean, + // What to restore after a core restart, not Android's current active-interface snapshot. + // requestedTetheringTypes separately covers starts Android has not yet published. + @Volatile var desiredTetheringTypes: Int, + // Distinguishes a paused session from a live profile switch, including failed restarts. + var coreRestartPending: Boolean = false, + ) + + private data class LifetimeWatch( + val binder: IBinder, + val recipient: IBinder.DeathRecipient, + ) { + fun unlink() { + runCatching { binder.unlinkToDeath(recipient, 0) } + } + } + + /** Owns the UserService side of one test-network TUN. */ + private class TestNetworkHandle( + val manager: Any, + // Keep TestNetworkInterface reachable; Android associates its lifetime with this object. + private val interfaceLifetime: Any, + val tun: ParcelFileDescriptor, + val interfaceName: String, + private val connectivityManager: ConnectivityManager, + val networkLifetimeToken: IBinder, + ) { + private val published = CountDownLatch(1) + var network: Network? = null + private set + + val callback = object : ConnectivityManager.NetworkCallback() { + private fun capture(network: Network, interfaceName: String?) { + if (interfaceName == this@TestNetworkHandle.interfaceName) { + this@TestNetworkHandle.network = network + published.countDown() + } + } + + override fun onAvailable(network: Network) { + capture(network, connectivityManager.getLinkProperties(network)?.interfaceName) + } + + override fun onLinkPropertiesChanged(network: Network, properties: LinkProperties) { + capture(network, properties.interfaceName) + } + } + + fun awaitPublished(): Boolean = + published.await(TEST_NETWORK_TIMEOUT_SECONDS, TimeUnit.SECONDS) + + fun release() { + runCatching { connectivityManager.unregisterNetworkCallback(callback) } + network?.let { publishedNetwork -> + runCatching { + manager.javaClass.getMethod("teardownTestNetwork", Network::class.java) + .invoke(manager, publishedNetwork) + }.onFailure { Log.w(TAG, "Unable to tear down test network", it) } + } + runCatching { tun.close() } + } + } + + @Synchronized + override fun setWifiHotspotEnabled(enabled: Boolean): Int { + if (enabled && Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) { + return RESULT_ROUTING_FAILED + } + val result = setTetheringEnabled(TETHERING_TYPE_WIFI, enabled) + if (result == RESULT_OK) { + val bit = tetheringTypeBit(TETHERING_TYPE_WIFI) + routingSession?.let { session -> + session.desiredTetheringTypes = if (enabled) { + session.desiredTetheringTypes or bit + } else { + session.desiredTetheringTypes and bit.inv() + } + } + } + notifyStatusChanged() + return result + } + + private fun getActiveTetheringTypes(): Int { + return try { + tetheringTypeMask(getTetheredInterfaces()) + } catch (error: Throwable) { + Log.e(TAG, "Unable to read tethering state", error) + TETHERING_TYPES_UNKNOWN + } + } + + private fun tetheringTypeMask(interfaces: List): Int { + return interfaces.fold(0) { mask, item -> mask or tetheringTypeBit(item.type) } + } + + private fun ipv6TetheringTypeMask(interfaces: List): Int { + return interfaces.fold(0) { mask, item -> + if (hasDelegatedIpv6Prefix(item.name)) mask or tetheringTypeBit(item.type) else mask + } + } + + private fun getTetheredInterfaces(): List { + // One registration serves status, lifecycle postconditions and emergency shutdown. + // Only the first read waits for Android's initial snapshot; later reads are in-memory. + return upstreamMonitor.awaitInterfaces(CALLBACK_TIMEOUT_SECONDS) + } + + /** + * Android assigns a local DNS address from the delegated upstream /64 to each downstream. + * Its presence on that real Wi-Fi or USB interface means Router Advertisement setup has + * completed; checking the test TUN itself would only prove that IPv6 was requested. + */ + private fun hasDelegatedIpv6Prefix(interfaceName: String): Boolean { + val prefix = TETHERING_IPV6_PREFIX ?: return false + val addresses = NetworkInterface.getByName(interfaceName)?.inetAddresses ?: return false + return addresses.asSequence().any(prefix::contains) + } + + private fun currentRoutingStateLocked(): Int { + if (routingActive && !isRoutingReadyLocked()) { + val engine = if (routingState == ROUTING_STATE_ACTIVE_HEV) "HEV" else "Native Xray" + setRoutingError("$engine tethering engine stopped unexpectedly") + } + return routingState + } + + private fun currentRoutingDetailLocked(): String { + // The shell process keeps platform diagnostics in English for logs. Expose only live + // interface/profile data; the app maps error states and result codes to localized text. + if (!routingActive && routingState != ROUTING_STATE_WAITING) return "" + val upstreamInterface = upstreamMonitor.currentInterfaceNames.orEmpty() + return formatRoutingDetail(upstreamInterface) + } + + private fun consumeWarningLocked(): Int { + return if (wrongUpstreamWarningTypes.getAndSet(0) == 0) { + RESULT_OK + } else { + RESULT_UNPROTECTED_UPSTREAM + } + } + + override fun getStatus(includeIpv6: Boolean): TetheringStatusSnapshot { + val interfaces = runCatching { getTetheredInterfaces() } + .onFailure { Log.e(TAG, "Unable to read tethering status", it) } + .getOrNull() + val activeTypes = interfaces?.let(::tetheringTypeMask) ?: TETHERING_TYPES_UNKNOWN + val ipv6Types = if (includeIpv6 && interfaces != null) { + runCatching { ipv6TetheringTypeMask(interfaces) } + .onFailure { Log.e(TAG, "Unable to read tethered IPv6 state", it) } + .getOrDefault(TETHERING_TYPES_UNKNOWN) + } else { + TETHERING_TYPES_UNKNOWN + } + return synchronized(this) { + TetheringStatusSnapshot( + routingState = currentRoutingStateLocked(), + routingDetail = currentRoutingDetailLocked(), + activeTetheringTypes = activeTypes, + ipv6TetheringTypes = ipv6Types, + warning = consumeWarningLocked(), + hasRoutingSession = routingSession != null || testTun != null, + ) + } + } + + override fun setStatusListener(listener: ITetheringStatusListener?) { + // Listener registration must never wait for the routing lifecycle monitor. The UI also + // unregisters through this one-way Binder call while its ViewModel is being cleared. + statusListener.set(listener) + } + + @Synchronized + override fun startRouting( + useHev: Boolean, + profileName: String, + dnsServers: Array, + ipv6Enabled: Boolean, + xudpKey: String, + syncToken: String, + launchId: String, + coreLease: ICoreTetheringLease, + ): Int { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return RESULT_ROUTING_FAILED + if (syncToken.isBlank()) { + Log.e(TAG, "Tethering synchronization token is empty") + return RESULT_INVALID_SESSION + } + // Reject duplicate starts before changing any resource owned by the existing session. + if (routingSession != null || testTun != null) return RESULT_ALREADY_ACTIVE + freshUserService = false + val activeTypes = getActiveTetheringTypes() + if (activeTypes < 0) { + setRoutingError("Unable to determine active tethering before enabling its protected route") + return RESULT_ROUTING_FAILED + } + val engineConfig = runCatching { readEngineConfig(coreLease, launchId) }.getOrElse { + setRoutingError(rootCauseMessage(it)) + return RESULT_ROUTING_FAILED + } + val launchConfig = HotspotRoutingLaunchConfig( + engine = HotspotRoutingEngineConfig(useHev, profileName, engineConfig), + dnsServers = dnsServers.toList(), + ipv6Enabled = ipv6Enabled, + xudpKey = xudpKey, + ) + val newSession = RoutingSession( + token = syncToken, + xudpKey = launchConfig.xudpKey, + dnsServers = launchConfig.dnsServers, + ipv6Enabled = launchConfig.ipv6Enabled, + desiredTetheringTypes = activeTypes, + ) + + try { + watchCoreLifetimeLocked(coreLease) + } catch (error: Throwable) { + clearCoreLifetimeWatchLocked() + setRoutingError(rootCauseMessage(error)) + return RESULT_ROUTING_FAILED + } + val result = startRoutingLocked(launchConfig, activeTypes) + if (result == RESULT_OK) { + routingSession = newSession + } else { + clearCoreLifetimeWatchLocked() + } + return result + } + + @RequiresApi(Build.VERSION_CODES.TIRAMISU) + private fun startRoutingLocked(config: HotspotRoutingLaunchConfig, activeTypes: Int): Int { + return try { + if (testTun == null) { + // A fresh UserService may be replacing one lost with Shizuku. Its core-side lease + // can still own the old protected network, but this process has no handle for it. + // Stop downstreams before cleanup releases that lease, then restore them only + // after the replacement network is ready. + check(stopActiveTetheringLocked(clearDesired = false) == RESULT_OK) { + "Unable to stop tethering before replacing its protected route" + } + createRoutingLocked(config) + val failedTypes = restoreTetheringTypesLocked(activeTypes) + reportTetheringRestoreFailuresLocked(failedTypes) + } else { + val failedTypes = rebuildRoutingLocked(config, activeTypes) + reportTetheringRestoreFailuresLocked(failedTypes) + } + RESULT_OK + } catch (error: Throwable) { + val detail = rootCauseMessage(error) + Log.e(TAG, "Unable to start v2rayNG tethering routing: $detail", error) + setRoutingError(detail) + RESULT_ROUTING_FAILED + } + } + + @RequiresApi(Build.VERSION_CODES.TIRAMISU) + private fun createRoutingLocked(config: HotspotRoutingLaunchConfig) { + cleanupRouting() + routingState = ROUTING_STATE_STARTING + Log.i(TAG, "Creating Android test-network TUN") + + try { + setPreferTestNetworks(true) + createTestNetwork(config.dnsServers, config.ipv6Enabled) + val tun = checkNotNull(testTun) { "Test TUN file descriptor is unavailable" } + startRoutingEngineLocked(config, tun.fd) + setRoutingActiveLocked(config) + } catch (error: Throwable) { + // A partially published test network is not useful for recovery. Release it here so + // callers always see either a complete protected route or no route at all. + cleanupRouting() + throw error + } + } + + @Synchronized + override fun stopRouting(): Int { + freshUserService = false + val result = shutdownRoutingLocked() + notifyStatusChanged() + return result + } + + private fun shutdownRoutingLocked(): Int { + val tetheringResult = stopActiveTetheringLocked(clearDesired = true) + if (tetheringResult != RESULT_OK) { + setRoutingError("Unable to disable tethering safely before removing its protected route") + return tetheringResult + } + routingSession = null + routingState = ROUTING_STATE_STOPPING + Log.i(TAG, "Stopping v2rayNG tethering routing") + cleanupRouting() + clearCoreLifetimeWatchLocked() + routingState = ROUTING_STATE_DISABLED + return RESULT_OK + } + + private fun stopActiveTetheringLocked( + clearDesired: Boolean, + activeTypes: Int = getActiveTetheringTypes(), + ): Int { + // Include accepted starts and the session's last desired state. This both covers Android's + // delayed active-state publication and provides a safe fallback if the state query fails. + val knownTypes = requestedTetheringTypes or (routingSession?.desiredTetheringTypes ?: 0) + if (activeTypes < 0 && knownTypes == 0) return RESULT_INTERNAL_ERROR + val typesToStop = activeTypes.coerceAtLeast(0) or knownTypes + if (clearDesired) routingSession?.desiredTetheringTypes = 0 + + var result = RESULT_OK + forEachTetheringType(typesToStop) { type, _ -> + val stopResult = stopTetheringTypeLocked(type) + if (stopResult != RESULT_OK && result == RESULT_OK) result = stopResult + } + return result + } + + /** + * Queues a pause of the secondary engine while retaining the test TUN and downstreams. + * Returning from this one-way call does not confirm completion. Once paused, clients remain + * on a dead TUN until [synchronizeRouting] supplies the replacement configuration. + */ + override fun notifyCoreStopping(token: String) = enqueueCoreUpdate { + findRoutingSession(token)?.let { pauseForCoreRestartLocked(it, "Main core stopping") } + } + + private fun pauseForCoreRestartLocked(session: RoutingSession, reason: String) { + val activeTypes = getActiveTetheringTypes() + if (activeTypes >= 0 && (routingActive || session.desiredTetheringTypes == 0)) { + session.desiredTetheringTypes = activeTypes + } + stopRoutingEngineLocked() + session.coreRestartPending = true + if (testTun != null) { + routingState = ROUTING_STATE_WAITING + Log.i( + TAG, + "$reason; tethering core stopped while preserving the protected test network " + + "and tethering types " + + "0x${session.desiredTetheringTypes.toString(16)}", + ) + } else { + val tetheringResult = stopActiveTetheringLocked(clearDesired = false) + setRoutingError("Protected test network is unavailable") + Log.e( + TAG, + "$reason without a protected test network; disabled tethering " + + "with result $tetheringResult", + ) + } + } + + override fun synchronizeRouting( + token: String, + useHev: Boolean, + profileName: String, + dnsServers: Array, + ipv6Enabled: Boolean, + xudpKey: String, + launchId: String, + coreLease: ICoreTetheringLease, + ) = enqueueCoreUpdate { + // The token identifies the user's enabled tethering session across core restarts; + // launchId identifies one main-core configuration. Both must match: a live session alone + // does not make a delayed configuration update current. + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU || !coreLease.isCurrentLaunch(launchId)) return@enqueueCoreUpdate + if (routingSession == null && freshUserService) { + startRouting(useHev, profileName, dnsServers, ipv6Enabled, xudpKey, token, launchId, coreLease) + return@enqueueCoreUpdate + } + // A missing session in an existing service means the user stopped it, not service death. + val session = findRoutingSession(token) ?: return@enqueueCoreUpdate + runCatching { + val launchConfig = HotspotRoutingLaunchConfig( + engine = HotspotRoutingEngineConfig(useHev, profileName, readEngineConfig(coreLease, launchId)), + dnsServers = dnsServers.toList(), + ipv6Enabled = ipv6Enabled, + xudpKey = session.xudpKey, + ) + watchCoreLifetimeLocked(coreLease) + applyRoutingConfigLocked(launchConfig, session) + }.onFailure { + // A newer launch/Stop will have its own queued event. Do not turn its stale predecessor + // into an error or accidentally apply a configuration from the wrong launch. + if (coreLease.isCurrentLaunch(launchId)) failRoutingSynchronizationLocked(it, session) + } + } + + override fun notifyCoreStartFailed(token: String, detail: String) = enqueueCoreUpdate { + val session = findRoutingSession(token) ?: return@enqueueCoreUpdate + failRoutingSynchronizationLocked( + IllegalStateException(detail.ifBlank { "v2rayNG failed to restart" }), + session, + ) + } + + private fun enqueueCoreUpdate(action: () -> Unit) { + // The queue orders core events; the monitor also excludes synchronous UI commands. + // Neither orders emergency stops, so start operations must check upstreamRejections too. + coreUpdates.execute { + synchronized(this) { + runCatching(action).onFailure { Log.e(TAG, "Unable to apply core lifecycle update", it) } + notifyStatusChanged() + } + } + } + + private fun findRoutingSession(token: String): RoutingSession? { + val session = routingSession + if (session == null || token.isBlank() || token != session.token) { + Log.w(TAG, "Ignoring hotspot update for an inactive or invalid session") + return null + } + return session + } + + /** + * Keep the network request and TUN open in both failure domains. If the app dies, this + * UserService retains them; if Shizuku dies, the main core retains the duplicates supplied + * through [coreLease]. The lease Binder also reports a main-core death when no event can be sent. + */ + private fun watchCoreLifetimeLocked(coreLease: ICoreTetheringLease) { + val binder = coreLease.asBinder() + if (coreLifetime?.binder === binder && binder.isBinderAlive) return + clearCoreLifetimeWatchLocked() + val recipient = IBinder.DeathRecipient { + synchronized(this) { + if (coreLifetime?.binder !== binder) return@synchronized + coreLifetime = null + this.coreLease = null + routingSession?.let { + Log.w(TAG, "Main core process died without a stop notification") + pauseForCoreRestartLocked(it, "Main core process died") + notifyStatusChanged() + } + } + } + this.coreLease = coreLease + coreLifetime = LifetimeWatch(binder, recipient) + try { + binder.linkToDeath(recipient, 0) + shareTestNetworkWithCoreLocked() + } catch (error: Throwable) { + this.coreLease = null + coreLifetime = null + throw IllegalStateException("Main core is no longer running", error) + } + } + + private fun shareTestNetworkWithCoreLocked() { + val lease = coreLease ?: return + val tun = testTun ?: return + ParcelFileDescriptor.dup(tun.fileDescriptor).use { + lease.holdTestNetwork(it) + } + } + + private fun clearCoreLifetimeWatchLocked() { + runCatching { coreLease?.releaseTestNetwork() } + coreLifetime?.unlink() + coreLease = null + coreLifetime = null + } + + @RequiresApi(Build.VERSION_CODES.TIRAMISU) + private fun applyRoutingConfigLocked( + launchConfig: HotspotRoutingLaunchConfig, + session: RoutingSession, + ) { + Log.i( + TAG, + "Synchronizing hotspot routing to profile ${launchConfig.engine.profileName.ifBlank { "" }}", + ) + val currentlyActive = getActiveTetheringTypes().coerceAtLeast(0) + val restoreTypes = if (session.coreRestartPending) { + session.desiredTetheringTypes or currentlyActive + } else { + currentlyActive + } + session.desiredTetheringTypes = restoreTypes + + val switchedInPlace = launchConfig.dnsServers == session.dnsServers && + launchConfig.ipv6Enabled == session.ipv6Enabled && + testTun != null && + (routingActive || routingState == ROUTING_STATE_WAITING) && + runCatching { + // Reusing the TUN avoids changing Android's selected tethering upstream during an + // ordinary profile switch. Rebuild only if the engine cannot reuse its descriptor. + restartRoutingEngineLocked(launchConfig) + }.onFailure { + Log.w(TAG, "In-place hotspot engine switch failed; rebuilding the test network", it) + }.isSuccess + + val failedTypes = if (switchedInPlace) { + restoreTetheringTypesLocked(restoreTypes) + } else { + rebuildRoutingLocked(launchConfig, restoreTypes) + } + session.dnsServers = launchConfig.dnsServers + session.ipv6Enabled = launchConfig.ipv6Enabled + session.coreRestartPending = false + reportTetheringRestoreFailuresLocked(failedTypes) + if (failedTypes == 0) { + Log.i( + TAG, + "Hotspot routing synchronized on ${testInterfaceName.orEmpty()}; tethering types 0x${restoreTypes.toString(16)}", + ) + } + } + + private fun restartRoutingEngineLocked(config: HotspotRoutingLaunchConfig) { + routingState = ROUTING_STATE_STARTING + Log.i(TAG, "Switching tethering to the new v2rayNG connection") + stopRoutingEngineLocked() + val tun = checkNotNull(testTun) { "Test TUN file descriptor is unavailable" } + startRoutingEngineLocked(config, tun.fd) + setRoutingActiveLocked(config) + } + + private fun restoreTetheringTypesLocked(types: Int): Int { + val activeTypes = getActiveTetheringTypes() + if (activeTypes < 0) return types + + var failedTypes = 0 + forEachTetheringType(types) { type, bit -> + val result = setTetheringEnabled(type, true, activeTypes) + if (result != RESULT_OK) failedTypes = failedTypes or bit + } + return failedTypes + } + + /** Visits exactly the tethering types represented in Android's non-negative bit mask. */ + private inline fun forEachTetheringType(types: Int, action: (type: Int, bit: Int) -> Unit) { + var remaining = types + while (remaining > 0) { + val bit = Integer.lowestOneBit(remaining) + action(Integer.numberOfTrailingZeros(bit), bit) + remaining = remaining xor bit + } + } + + private fun failRoutingSynchronizationLocked(error: Throwable, session: RoutingSession) { + val detail = rootCauseMessage(error) + Log.e(TAG, "Unable to synchronize hotspot routing: $detail", error) + stopRoutingEngineLocked() + session.coreRestartPending = true + if (testTun != null) { + routingState = ROUTING_STATE_WAITING + Log.w(TAG, "Tethering remains fail-closed on ${testInterfaceName.orEmpty()}") + } else { + val tetheringResult = stopActiveTetheringLocked(clearDesired = false) + if (tetheringResult == RESULT_OK) cleanupRouting() + setRoutingError(detail) + } + } + + override fun destroy() { + val safeToExit = synchronized(this) { + shutdownRoutingLocked() == RESULT_OK + } + if (!safeToExit) { + Log.e(TAG, "Refusing to destroy the UserService while tethering may still be active") + return + } + upstreamMonitor.close() + coreUpdates.shutdownNow() + System.exit(0) + } + + /** + * Changes one real Android tethering downstream while preserving the protected-upstream + * invariant. + * + * `setPreferTestNetworks(true)` influences Android's upstream choice, but it does not make the + * subsequent tethering start atomic. The callback can also arrive before the downstream and + * its selected upstream are visible. A successful start is consequently not returned to the + * app until the downstream is active and its actual upstream is exactly [testInterfaceName]. + */ + private fun setTetheringEnabled(type: Int, enabled: Boolean, activeTypes: Int = getActiveTetheringTypes()): Int { + val bit = tetheringTypeBit(type) + if (bit == 0) return RESULT_INTERNAL_ERROR + + val result = if (!enabled) { + val alreadyStopped = activeTypes >= 0 && activeTypes and bit == 0 && + requestedTetheringTypes and bit == 0 + if (alreadyStopped) RESULT_OK else stopTetheringTypeLocked(type) + } else { + startTetheringTypeLocked(type, activeTypes >= 0 && activeTypes and bit != 0) + } + if (enabled) { + when (result) { + RESULT_OK -> wrongUpstreamWarningTypes.getAndUpdate { it and bit.inv() } + RESULT_UNPROTECTED_UPSTREAM -> wrongUpstreamWarningTypes.getAndUpdate { it or bit } + } + } + return result + } + + private fun startTetheringTypeLocked(type: Int, alreadyEnabled: Boolean): Int { + val firstResult = startTetheringTypeAttemptLocked(type, alreadyEnabled) + if (firstResult != RESULT_UNPROTECTED_UPSTREAM) return firstResult + + // Some Android builds briefly select their physical upstream while applying the test- + // network preference. The failed attempt has already been stopped, so it is safe to give + // the framework a moment to settle and make one fresh attempt. Never loop indefinitely: + // a persistent wrong upstream must remain fail-closed and be reported to the user. + Log.w(TAG, "Waiting before retrying protected tethering type $type") + if (!sleepForUpstreamRetry()) return firstResult + return startTetheringTypeAttemptLocked(type, alreadyEnabled = false) + } + + private fun startTetheringTypeAttemptLocked(type: Int, alreadyEnabled: Boolean): Int { + val rejection = upstreamRejections.get() + val bit = tetheringTypeBit(type) + val expectedUpstream = testInterfaceName + if (!isRoutingReadyLocked() || testTun == null || expectedUpstream.isNullOrBlank()) { + Log.e(TAG, "Refusing to start tethering before protected routing is ready") + return RESULT_ROUTING_FAILED + } + + // Record the request before crossing into Android. From this point onward every error and + // every concurrent shutdown path must explicitly stop the possibly in-flight downstream. + requestedTetheringTypes = requestedTetheringTypes or bit + val preferenceReady = runCatching { setPreferTestNetworks(true) } + .onFailure { Log.e(TAG, "Unable to select the protected tethering upstream", it) } + .isSuccess + if (!preferenceReady) return stopAfterFailedStartLocked(type, RESULT_INTERNAL_ERROR) + + var needsStart = !alreadyEnabled + if (alreadyEnabled && !awaitProtectedUpstream(expectedUpstream)) { + // A downstream started outside this protected session may remain latched to its old + // physical upstream. Restart it so Android applies the test-network preference while + // making the new upstream selection. + Log.w(TAG, "Resetting tethering type $type before protected startup") + val stopResult = stopTetheringTypeLocked(type) + if (stopResult != RESULT_OK) return stopAfterFailedStartLocked(type, stopResult) + needsStart = true + } + + if (needsStart) { + val startResult = changeTetheringEnabled(type, true) + if (startResult != RESULT_OK) return stopAfterFailedStartLocked(type, startResult) + if (!awaitTetheringTypeState(type, enabled = true)) { + return stopAfterFailedStartLocked(type, RESULT_INTERNAL_ERROR) + } + } + + if (!awaitProtectedUpstream(expectedUpstream) || rejection != upstreamRejections.get()) { + // Do not wait for a non-empty physical upstream to hand over later: once Android has + // installed that forwarding path, tethered traffic may already bypass v2rayNG. + val actualUpstream = readUpstreamInterface() + Log.e( + TAG, + "Refusing tethering type $type on unprotected upstream " + + actualUpstream.ifBlank { "" }, + ) + val result = if (actualUpstream.isBlank()) { + RESULT_ROUTING_FAILED + } else { + RESULT_UNPROTECTED_UPSTREAM + } + return stopAfterFailedStartLocked(type, result) + } + + requestedTetheringTypes = requestedTetheringTypes and bit.inv() + return RESULT_OK + } + + private fun sleepForUpstreamRetry(): Boolean = try { + Thread.sleep(UPSTREAM_RETRY_DELAY_MILLIS) + true + } catch (_: InterruptedException) { + Thread.currentThread().interrupt() + false + } + + private fun readUpstreamInterface(): String = upstreamMonitor.currentInterfaceNames.orEmpty() + + private fun createUpstreamMonitor(): TetheringUpstreamMonitor { + return if (usesPublicTetheringApi()) { + TetheringApi36.observeUpstream( + tetheringManager, + connectivityManager, + executor, + ::onTetheringChanged, + ) + } else { + TetheringPlatformCompat.observeUpstreamLegacy( + tetheringManager, + connectivityManager, + executor, + ::onTetheringChanged, + ) + } + } + + private fun onTetheringChanged() { + stopUnprotectedDownstreams() + notifyStatusChanged() + } + + /** + * Safety must not queue behind the lifecycle monitor: native startup and the bounded retry + * can take seconds while another downstream is already carrying traffic. Read the callback's + * snapshot and dispatch all stops without waiting for any individual acknowledgement. + * Normal lifecycle operations still verify Android's final stopped state before releasing a + * TUN. The rejection counter also prevents an overlapping start from reporting success. + */ + private fun stopUnprotectedDownstreams() { + val expected = testInterfaceName ?: return + val actual = upstreamMonitor.currentInterfaceNames ?: return + if (actual.isBlank() || TetheringPlatformCompat.isProtectedUpstream(actual, expected)) return + + val activeTypes = upstreamMonitor.currentInterfaces?.let(::tetheringTypeMask) ?: 0 + val affectedTypes = activeTypes or requestedTetheringTypes or + (routingSession?.desiredTetheringTypes ?: 0) + if (affectedTypes == 0) return + + upstreamRejections.incrementAndGet() + wrongUpstreamWarningTypes.getAndUpdate { it or affectedTypes } + Log.e(TAG, "Android moved tethering to unprotected upstream $actual; stopping downstreams") + forEachTetheringType(affectedTypes) { type, _ -> + runCatching { + if (usesPublicTetheringApi()) { + TetheringApi36.requestStopTethering(tetheringManager, type, executor) { result -> + if (result != RESULT_OK) Log.e(TAG, "Emergency stop failed for tethering type $type: $result") + } + } else { + TetheringPlatformCompat.stopTethering(tetheringManager, type) + } + }.onFailure { Log.e(TAG, "Unable to request emergency stop for tethering type $type", it) } + } + } + + private fun notifyStatusChanged() { + val listener = statusListener.get() ?: return + runCatching { listener.onStatusChanged() } + .onFailure { statusListener.compareAndSet(listener, null) } + } + + private fun isRoutingReadyLocked(): Boolean { + return when (routingState) { + ROUTING_STATE_ACTIVE_NATIVE -> nativeController?.isRunning == true + ROUTING_STATE_ACTIVE_HEV -> TProxyService.isExternalTunnelRunning() + else -> false + } + } + + private fun stopAfterFailedStartLocked(type: Int, startResult: Int): Int { + // Cleanup is part of the safety contract. Prefer its failure when Android could not be + // observed stopping, because the original start error no longer describes the main risk. + val stopResult = stopTetheringTypeLocked(type) + return if (stopResult == RESULT_OK) startResult else stopResult + } + + private fun stopTetheringTypeLocked(type: Int): Int { + val bit = tetheringTypeBit(type) + val stopResult = changeTetheringEnabled(type, false) + if (awaitTetheringTypeState(type, enabled = false)) { + // Clear the in-flight marker only after Android confirms the downstream is absent. + requestedTetheringTypes = requestedTetheringTypes and bit.inv() + return RESULT_OK + } + Log.e(TAG, "Timed out waiting for tethering type $type to stop") + return if (stopResult == RESULT_OK) RESULT_INTERNAL_ERROR else stopResult + } + + private fun awaitTetheringTypeState(type: Int, enabled: Boolean): Boolean { + val bit = tetheringTypeBit(type) + return awaitResult(TETHERING_STATE_TIMEOUT_SECONDS) { + val activeTypes = getActiveTetheringTypes() + if (activeTypes >= 0 && (activeTypes and bit != 0) == enabled) true else null + } + } + + private fun awaitProtectedUpstream(expectedInterface: String) = awaitResult( + UPSTREAM_SELECTION_TIMEOUT_SECONDS, + ) { + val actualInterface = readUpstreamInterface() + when { + TetheringPlatformCompat.isProtectedUpstream(actualInterface, expectedInterface) -> true + // An empty value means upstream selection has not completed and is safe to poll. Any + // named, unexpected interface is already a usable forwarding path and must fail fast. + actualInterface.isNotBlank() -> false + else -> null + } + } + + /** Polls until Android reports success/failure, or returns false on timeout/interruption. */ + private inline fun awaitResult(timeoutSeconds: Long, poll: () -> Boolean?): Boolean { + val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(timeoutSeconds) + while (true) { + poll()?.let { return it } + if (System.nanoTime() >= deadline) return false + try { + Thread.sleep(TETHERING_STATE_POLL_MILLIS) + } catch (_: InterruptedException) { + Thread.currentThread().interrupt() + return false + } + } + } + + private fun changeTetheringEnabled(type: Int, enabled: Boolean): Int { + return runCatching { + when { + enabled && usesPublicTetheringApi() -> TetheringApi36.startTethering( + tetheringManager, + type, + executor, + CALLBACK_TIMEOUT_SECONDS, + ) + enabled -> TetheringPlatformCompat.startTethering( + tetheringManager, + type, + executor, + CALLBACK_TIMEOUT_SECONDS, + ) + usesPublicTetheringApi() -> + TetheringApi36.stopTethering( + tetheringManager, + type, + executor, + CALLBACK_TIMEOUT_SECONDS, + ) + else -> TetheringPlatformCompat.stopTethering( + tetheringManager, + type, + ) + } + }.onFailure { + Log.e(TAG, "Unable to set tethering type $type enabled=$enabled", it) + }.getOrDefault(RESULT_INTERNAL_ERROR) + } + + @RequiresApi(Build.VERSION_CODES.TIRAMISU) + private fun rebuildRoutingLocked(config: HotspotRoutingLaunchConfig, restoreTypes: Int): Int { + val stopResult = stopActiveTetheringLocked(clearDesired = false) + check(stopResult == RESULT_OK) { + "Unable to pause tethering safely before rebuilding its protected route" + } + createRoutingLocked(config) + return restoreTetheringTypesLocked(restoreTypes) + } + + private fun reportTetheringRestoreFailuresLocked(failedTypes: Int) { + if (failedTypes == 0) return + Log.w(TAG, "Unable to restore tethering types 0x${failedTypes.toString(16)}") + } + + @RequiresApi(Build.VERSION_CODES.Q) + private fun createTestNetwork(dnsServers: List, ipv6Enabled: Boolean) { + val manager = checkNotNull(shellContext.getSystemService(TEST_NETWORK_SERVICE)) { + "TestNetworkManager is unavailable on this Android build" + } + // TestNetworkManager installs a default route for every represented address family. + // Tethering can then delegate this synthetic /64 while Xray owns the shared TUN fd. + val addresses = buildList { + add(createLinkAddress(AppConfig.SHIZUKU_TUN_ADDR_V4)) + if (ipv6Enabled) add(createLinkAddress(AppConfig.SHIZUKU_TUN_ADDR_V6)) + } + val handle = createTestNetworkHandle(manager, addresses) + testNetworkHandle = handle + + // Register the duplicate request and TUN descriptor before publishing the network. From + // this point on, either the core process or this UserService can preserve the fail-closed + // upstream if the other process disappears. + shareTestNetworkWithCoreLocked() + connectivityManager.requestNetwork(TetheringPlatformCompat.testNetworkRequest(), handle.callback) + + val properties = LinkProperties().apply { + interfaceName = handle.interfaceName + setLinkAddresses(addresses) + // Mirror CoreVpnService instead of inventing tethering-specific resolvers. The core + // configuration decides whether port 53 is handled by v2rayNG's local DNS outbound. + val configuredDns = dnsServers.map(InetAddress::getByName) + setDnsServers(buildList { + addAll(configuredDns) + // Android requires an IPv6 DNS server before it will advertise an upstream /64. + // Most existing VPN DNS settings are IPv4-only, so append an internal ULA hint; + // it is not a hardcoded external resolver and configured servers remain first. + if (ipv6Enabled && configuredDns.none { it is Inet6Address }) { + add(InetAddress.getByName(AppConfig.SHIZUKU_TUN_DNS_HINT_V6)) + } + }) + } + val setupMethod = manager.javaClass.getMethod( + "setupTestNetwork", + LinkProperties::class.java, + java.lang.Boolean.TYPE, + IBinder::class.java, + ) + setupMethod.invoke(manager, properties, true, handle.networkLifetimeToken) + + check(handle.awaitPublished()) { "Android did not publish the test-network TUN" } + } + + /** + * TestNetworkManager is a module-library API, not an app API. Remove this reflection only when + * the public SDK exposes create/setup/teardown test-network calls with equivalent lifetime-token + * semantics and the feature no longer supports an older API without that public replacement. + */ + private fun createTestNetworkHandle( + manager: Any, + addresses: List, + ): TestNetworkHandle { + val addressArray = addresses.toTypedArray() + val testInterface = manager.javaClass + .getMethod("createTunInterface", addressArray.javaClass) + .invoke(manager, addressArray as Any) + ?: error("TestNetworkManager returned no TUN interface") + val tun = testInterface.javaClass.getMethod("getFileDescriptor") + .invoke(testInterface) as ParcelFileDescriptor + return try { + val interfaceName = testInterface.javaClass.getMethod("getInterfaceName") + .invoke(testInterface) as String + TestNetworkHandle( + manager = manager, + interfaceLifetime = testInterface, + tun = tun, + interfaceName = interfaceName, + connectivityManager = connectivityManager, + // The service and normal app are independent failure domains. Let system_server + // anchor the published test network so either process can disappear without + // Android immediately moving active tethering to a physical upstream. + networkLifetimeToken = checkNotNull(SystemServiceHelper.getSystemService(Context.CONNECTIVITY_SERVICE)) { + "Android connectivity service has no Binder" + }, + ) + } catch (error: Throwable) { + runCatching { tun.close() } + throw error + } + } + + private fun setPreferTestNetworks(prefer: Boolean) { + // This hidden API is the only way to make tethering consider TRANSPORT_TEST upstreams. + // Remove it only when a public API provides the same opt-in on every supported feature API, + // or when the design stops using a test network as the protected upstream. + tetheringManager.javaClass + .getMethod("setPreferTestNetworks", java.lang.Boolean.TYPE) + .invoke(tetheringManager, prefer) + } + + private fun startRoutingEngineLocked(config: HotspotRoutingLaunchConfig, fd: Int) { + val engine = config.engine + require(engine.content.isNotBlank()) { + "${if (engine.useHev) "HEV" else "Xray"} configuration is empty" + } + if (engine.useHev) { + startHev(engine.content, fd) + } else { + val lease = checkNotNull(coreLease) { "Core asset lease is unavailable" } + startNativeXray(engine.content, fd, stageNativeAssets(lease), config.xudpKey) + } + } + + /** + * The ordinary app now keeps geodata and user assets in app-private storage, which the shell + * UserService cannot traverse. Stream those files through the existing private core lease and + * cache them in the shell runtime directory. The fingerprint avoids recopying unchanged files + * during ordinary profile and network synchronization. + */ + private fun stageNativeAssets(coreLease: ICoreTetheringLease): String { + val directory = File(SHELL_RUNTIME_DIR, ASSET_DIRECTORY_NAME).apply { mkdirs() } + check(directory.isDirectory) { "Unable to create tethering asset directory" } + val names = coreLease.listAssetFiles().toList() + require(names.all { it.isNotBlank() && File(it).name == it }) { "Invalid core asset name" } + val fingerprint = coreLease.assetFingerprint() + if (fingerprint == stagedAssetFingerprint && names.all { File(directory, it).isFile }) { + return directory.absolutePath + } + + directory.listFiles()?.filter { it.isFile && it.name !in names }?.forEach { it.delete() } + names.forEach { name -> + val target = File(directory, name) + val temporary = File(directory, ".$name.tmp") + runCatching { + ParcelFileDescriptor.AutoCloseInputStream(coreLease.openAssetFile(name)).use { input -> + temporary.outputStream().use { output -> input.copyTo(output) } + } + check(!target.exists() || target.delete()) { "Unable to replace tethering asset $name" } + check(temporary.renameTo(target)) { "Unable to install tethering asset $name" } + }.onFailure { + temporary.delete() + throw it + } + } + stagedAssetFingerprint = fingerprint + return directory.absolutePath + } + + private fun readEngineConfig(coreLease: ICoreTetheringLease, launchId: String): String { + val descriptor = coreLease.openEngineConfig(launchId) + return ParcelFileDescriptor.AutoCloseInputStream(descriptor) + .bufferedReader(Charsets.UTF_8) + .use { it.readText() } + .also { require(it.isNotBlank()) { "Tethering engine configuration is empty" } } + } + + private fun setRoutingActiveLocked(config: HotspotRoutingLaunchConfig) { + routingProfileName = config.engine.profileName + routingState = if (config.engine.useHev) ROUTING_STATE_ACTIVE_HEV else ROUTING_STATE_ACTIVE_NATIVE + // HEV's JNI API has no exit callback. Observe the native worker while an engine is owned, + // rather than telling an idle screen that an exited worker is still routing traffic. + engineHealthCheck = coreUpdates.scheduleWithFixedDelay({ + synchronized(this) { + val previous = routingState + if (currentRoutingStateLocked() != previous) notifyStatusChanged() + if (routingState == ROUTING_STATE_ERROR) engineHealthCheck?.cancel(false) + } + }, 2, 2, TimeUnit.SECONDS) + } + + private fun setRoutingError(detail: String) { + routingState = ROUTING_STATE_ERROR + Log.e(TAG, detail) + } + + private fun formatRoutingDetail(interfaceName: String): String { + return listOf(interfaceName, routingProfileName) + .filter(String::isNotBlank) + .joinToString(" · ") + } + + private fun stopRoutingEngineLocked() { + engineHealthCheck?.cancel(false) + engineHealthCheck = null + runCatching { nativeController?.stopLoop() } + .onFailure { Log.w(TAG, "Unable to stop native hotspot core", it) } + nativeController = null + runCatching { if (hevConfigFile != null) TProxyService.stopExternalTunnel() } + .onFailure { Log.w(TAG, "Unable to stop hotspot HEV", it) } + hevConfigFile?.let { runCatching { it.delete() } } + hevConfigFile = null + } + + private fun startHev(config: String, fd: Int) { + val file = File(SHELL_RUNTIME_DIR, "v2rayng-hotspot-${android.os.Process.myPid()}.yaml") + file.writeText(config) + hevConfigFile = file + check(TProxyService.startExternalTunnel(file.absolutePath, fd)) { "Unable to start HEV tethering engine" } + } + + private fun startNativeXray( + config: String, + fd: Int, + assetPath: String, + xudpKey: String, + ) { + Seq.setContext(appContext) + Libv2ray.initCoreEnv(assetPath, xudpKey) + val controller = Libv2ray.newCoreController(object : CoreCallbackHandler { + override fun startup(): Long = 0 + override fun shutdown(): Long = 0 + override fun onEmitStatus(code: Long, status: String?): Long { + Log.i(TAG, "Hotspot Xray status $code: ${status.orEmpty()}") + return 0 + } + }) + try { + controller.startLoop(config, fd) + check(controller.isRunning) { "Native Xray hotspot core did not start" } + nativeController = controller + } catch (error: Throwable) { + runCatching { controller.stopLoop() } + throw error + } + } + + private fun cleanupRouting() { + // Callers stop real tethering first. Releasing the engine and TUN in this order then leaves + // no downstream that Android could silently move back to a physical upstream. + stopRoutingEngineLocked() + runCatching { coreLease?.releaseTestNetwork() } + + val handle = testNetworkHandle + testNetworkHandle = null + handle?.release() + routingProfileName = "" + + runCatching { setPreferTestNetworks(false) } + .onFailure { Log.w(TAG, "Unable to restore tethering upstream preference", it) } + } + + private fun createLinkAddress(cidr: String): LinkAddress { + // LinkAddress has no public app-SDK constructor through API 37. Replace this reflection only + // after the public SDK gains a CIDR-equivalent factory on every supported feature API. + return LinkAddress::class.java.getDeclaredConstructor(String::class.java).run { + isAccessible = true + newInstance(cidr) + } + } + + private fun rootCauseMessage(error: Throwable): String { + var current = error + while (current.cause != null && current.cause !== current) current = current.cause!! + return current.message?.takeIf { it.isNotBlank() } ?: current.javaClass.simpleName + } + + companion object { + private const val TAG = "ShizukuTethering" + // Shizuku UserServices can outlive an APK update. Bump this whenever the service + // implementation or its AIDL contract changes so an incompatible shell process is + // replaced even when a locally rebuilt APK keeps the same Android versionCode. + const val USER_SERVICE_VERSION = 20_260_765 + private const val TETHERING_SERVICE = "tethering" + private const val TEST_NETWORK_SERVICE = "test_network" + private val TETHERING_IPV6_PREFIX = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + AppConfig.SHIZUKU_TUN_ADDR_V6.let { cidr -> + IpPrefix( + InetAddress.getByName(cidr.substringBefore('/')), + cidr.substringAfter('/').toInt(), + ) + } + } else null + private const val SHELL_RUNTIME_DIR = "/data/local/tmp" + private const val ASSET_DIRECTORY_NAME = "v2rayng-tethering-assets" + private const val CALLBACK_TIMEOUT_SECONDS = 10L + private const val TEST_NETWORK_TIMEOUT_SECONDS = 15L + private const val TETHERING_STATE_TIMEOUT_SECONDS = 10L + private const val UPSTREAM_SELECTION_TIMEOUT_SECONDS = 5L + // Android can take several seconds to dismantle a rejected downstream and reconsider the + // preferred test network. Keep the delay type-agnostic so Wi-Fi, USB and other downstreams + // all use the same single bounded retry. + private const val UPSTREAM_RETRY_DELAY_MILLIS = 8_000L + private const val TETHERING_STATE_POLL_MILLIS = 200L + + const val TETHERING_TYPE_WIFI = 0 + const val TETHERING_TYPE_USB = 1 + const val TETHERING_TYPES_UNKNOWN = -1 + + const val ROUTING_STATE_DISABLED = 0 + const val ROUTING_STATE_STARTING = 1 + const val ROUTING_STATE_ACTIVE_HEV = 2 + const val ROUTING_STATE_ACTIVE_NATIVE = 3 + const val ROUTING_STATE_STOPPING = 4 + const val ROUTING_STATE_ERROR = 5 + const val ROUTING_STATE_WAITING = 6 + + const val RESULT_OK = 0 + const val RESULT_INTERNAL_ERROR = -1 + const val RESULT_ROUTING_FAILED = -2 + const val RESULT_INVALID_SESSION = -4 + const val RESULT_ALREADY_ACTIVE = -5 + const val RESULT_UNPROTECTED_UPSTREAM = -6 + + internal fun createUserServiceArgs() = Shizuku.UserServiceArgs( + ComponentName(BuildConfig.APPLICATION_ID, ShizukuTetheringService::class.java.name) + ) + .daemon(true) + .processNameSuffix("shizuku_tethering") + .debuggable(BuildConfig.DEBUG) + .version(USER_SERVICE_VERSION) + } +} diff --git a/V2rayNG/app/src/main/java/com/v2ray/ang/shizuku/TetheringApi36.kt b/V2rayNG/app/src/main/java/com/v2ray/ang/shizuku/TetheringApi36.kt new file mode 100644 index 00000000000..156c2dfc45d --- /dev/null +++ b/V2rayNG/app/src/main/java/com/v2ray/ang/shizuku/TetheringApi36.kt @@ -0,0 +1,146 @@ +package com.v2ray.ang.shizuku + +import android.content.Context +import android.net.ConnectivityManager +import android.net.Network +import android.net.TetheringInterface +import android.net.TetheringManager +import android.os.Build +import androidx.annotation.Keep +import androidx.annotation.RequiresApi +import java.util.concurrent.CountDownLatch +import java.util.concurrent.Executor +import java.util.concurrent.ExecutorService +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicReference + +/** Keeps API 36-only tethering types out of classes loaded on Android 13 through 15. */ +@RequiresApi(Build.VERSION_CODES.BAKLAVA) +internal object TetheringApi36 { + fun getManager(context: Context): TetheringManager = + requireNotNull(context.getSystemService(TetheringManager::class.java)) { + "TetheringManager is unavailable" + } + + fun observeUpstream( + service: Any, + connectivityManager: ConnectivityManager, + executor: Executor, + onChanged: () -> Unit, + ): TetheringUpstreamMonitor { + val manager = service as TetheringManager + val interfaceNames = AtomicReference(null) + val interfaces = AtomicReference?>(null) + val interfacesReceived = CountDownLatch(1) + val changeExecutor = newTetheringChangeExecutor() + val callback = UpstreamCallback(connectivityManager, interfaceNames, interfaces, interfacesReceived, changeExecutor, onChanged) + try { + manager.registerTetheringEventCallback(executor, callback) + } catch (error: Throwable) { + changeExecutor.shutdownNow() + throw error + } + return TetheringUpstreamMonitor(interfaceNames, interfaces, interfacesReceived) { + runCatching { manager.unregisterTetheringEventCallback(callback) } + changeExecutor.shutdownNow() + } + } + + fun startTethering( + service: Any, + type: Int, + executor: Executor, + timeoutSeconds: Long, + ): Int { + val manager = service as TetheringManager + var result = ShizukuTetheringService.RESULT_INTERNAL_ERROR + val callbackReceived = CountDownLatch(1) + manager.startTethering( + TetheringManager.TetheringRequest.Builder(type).build(), + executor, + object : TetheringManager.StartTetheringCallback { + override fun onTetheringStarted() { + result = ShizukuTetheringService.RESULT_OK + callbackReceived.countDown() + } + + override fun onTetheringFailed(error: Int) { + result = error + callbackReceived.countDown() + } + }, + ) + return if (callbackReceived.await(timeoutSeconds, TimeUnit.SECONDS)) { + result + } else { + ShizukuTetheringService.RESULT_INTERNAL_ERROR + } + } + + fun stopTethering( + service: Any, + type: Int, + executor: Executor, + timeoutSeconds: Long, + ): Int { + var result = ShizukuTetheringService.RESULT_INTERNAL_ERROR + val callbackReceived = CountDownLatch(1) + requestStopTethering(service, type, executor) { + result = it + callbackReceived.countDown() + } + return if (callbackReceived.await(timeoutSeconds, TimeUnit.SECONDS)) result else ShizukuTetheringService.RESULT_INTERNAL_ERROR + } + + /** Dispatch without waiting, so emergency shutdown can stop every downstream immediately. */ + fun requestStopTethering(service: Any, type: Int, executor: Executor, onResult: (Int) -> Unit) { + val manager = service as TetheringManager + val request = TetheringManager.TetheringRequest.Builder(type).build() + manager.stopTethering( + request, + executor, + object : TetheringManager.StopTetheringCallback { + override fun onStopTetheringSucceeded() { + onResult(ShizukuTetheringService.RESULT_OK) + } + + override fun onStopTetheringFailed(error: Int) { + onResult(error) + } + }, + ) + } + + private class UpstreamCallback( + private val connectivityManager: ConnectivityManager, + private val interfaceNames: AtomicReference, + private val tetheredInterfaces: AtomicReference?>, + private val interfacesReceived: CountDownLatch, + private val changeExecutor: ExecutorService, + private val onChanged: () -> Unit, + ) : TetheringManager.TetheringEventCallback { + override fun onTetheredInterfacesChanged(interfaces: Set) { + tetheredInterfaces.set(interfaces.map { ActiveTetheringInterface(it.type, it.`interface`) }) + interfacesReceived.countDown() + notifyChanged() + } + + /** + * API 36 made callback registration public, but kept this callback member @SystemApi. + * The framework invokes this same binary signature on the typed callback, so no reflection + * is needed. Replace it with a normal `override` only after the compile SDK exposes + * `onUpstreamChanged(Network?)`; remove it entirely only if upstream identity is no longer + * part of the fail-closed safety check. + */ + @Keep + @Suppress("unused") + fun onUpstreamChanged(network: Network?) { + interfaceNames.set(upstreamInterfaceNames(connectivityManager, network)) + notifyChanged() + } + + private fun notifyChanged() { + runCatching { changeExecutor.execute(onChanged) } + } + } +} diff --git a/V2rayNG/app/src/main/java/com/v2ray/ang/shizuku/TetheringCoreSync.kt b/V2rayNG/app/src/main/java/com/v2ray/ang/shizuku/TetheringCoreSync.kt new file mode 100644 index 00000000000..f8162d162d8 --- /dev/null +++ b/V2rayNG/app/src/main/java/com/v2ray/ang/shizuku/TetheringCoreSync.kt @@ -0,0 +1,400 @@ +package com.v2ray.ang.shizuku + +import android.app.Service +import android.content.Context +import android.content.Intent +import android.net.ConnectivityManager +import android.os.Build +import android.os.Bundle +import android.os.ParcelFileDescriptor +import com.v2ray.ang.AngApplication +import com.v2ray.ang.AppConfig +import com.v2ray.ang.R +import com.v2ray.ang.dto.HotspotRoutingSnapshot +import com.v2ray.ang.dto.HotspotRoutingSync +import com.v2ray.ang.handler.MmkvManager +import com.v2ray.ang.handler.SettingsManager +import com.v2ray.ang.service.CoreVpnService +import com.v2ray.ang.service.HevTunnelSettings +import com.v2ray.ang.util.LogUtil +import com.v2ray.ang.util.Utils +import rikka.shizuku.Shizuku +import rikka.shizuku.ShizukuProvider +import java.io.File + +/** Keeps the normal core's lifecycle and the privileged tethering core synchronized. */ +internal object TetheringCoreSync { + @Volatile + private var snapshot = HotspotRoutingSnapshot() + private val coreLease = CoreTetheringLease() + private var watchingShizuku = false + private val recoveryLock = Any() + private var recoveryState = TetheringRecoveryState() + private var activeProfileId = "" + + private val binderReceivedListener = Shizuku.OnBinderReceivedListener { + if (transitionRecovery(TetheringRecoveryState::onBinderReceived) != TetheringRecoveryAction.RECOVER) { + return@OnBinderReceivedListener + } + val currentSnapshot = snapshot.takeIf { it.running } ?: return@OnBinderReceivedListener + LogUtil.i(AppConfig.TAG, "Shizuku restarted; recovering protected tethering") + safely("recover", activeProfileId) { + send(AngApplication.application, HotspotRoutingSync.EVENT_CORE_STARTED, currentSnapshot) + } + } + + private val binderDeadListener = Shizuku.OnBinderDeadListener { + updateRecovery(TetheringRecoveryState::onBinderDied) + } + + fun onStarting() { + safely("start-preparation") { clearCoreState() } + } + + fun onStarted( + service: Service, + profileId: String, + profileName: String, + coreConfig: String, + useHev: Boolean, + ) { + safely("start", profileId) { + if (!service.resources.getBoolean(R.bool.shizuku_tethering_enabled)) return@safely + try { + val currentSnapshot = createSnapshot(service, profileName, useHev) + coreLease.attach(service, currentSnapshot, coreConfig) + snapshot = currentSnapshot + activeProfileId = profileId + updateRecovery(TetheringRecoveryState::onCoreStarted) + watchShizuku(service) + send(service, HotspotRoutingSync.EVENT_CORE_STARTED, snapshot) + } catch (error: Throwable) { + clearCoreState() + throw error + } + } + } + + fun onStartFailed(service: Service, detail: String) { + safely("start-failure") { + try { + send(service, HotspotRoutingSync.EVENT_CORE_START_FAILED, detail = detail) + } finally { + clearCoreState() + } + } + } + + fun onStopping(service: Service) { + safely("stop") { + try { + send(service, HotspotRoutingSync.EVENT_CORE_STOPPING) + } finally { + clearCoreState() + } + } + } + + fun clear() { + safely("clear") { clearCoreState() } + } + + fun onAppForegrounded(service: Service) { + val action = transitionRecovery { it.onAppForegrounded(Build.VERSION.SDK_INT) } + if (action != TetheringRecoveryAction.REQUEST_BINDER) return + + // Android 14+ queues Shizuku's cross-process Binder broadcast while the provider + // process is cached. Once the UI foregrounds that process, explicitly ask it for the + // replacement Binder so protected tethering can be restored without another user action. + // Remove this request with ShizukuForegroundRecovery under the condition documented there. + runCatching { ShizukuProvider.requestBinderForNonProviderProcess(service.applicationContext) } + .onFailure { + updateRecovery(TetheringRecoveryState::onForegroundRequestFailed) + logFailure("foreground-recovery", activeProfileId, it) + } + } + + private fun clearCoreState() { + snapshot = HotspotRoutingSnapshot() + coreLease.clearEngineConfig() + activeProfileId = "" + updateRecovery(TetheringRecoveryState::onCoreStopped) + } + + private fun watchShizuku(service: Service) { + if (!watchingShizuku) { + Shizuku.addBinderReceivedListener(binderReceivedListener) + try { + Shizuku.addBinderDeadListener(binderDeadListener) + } catch (error: Throwable) { + runCatching { Shizuku.removeBinderReceivedListener(binderReceivedListener) } + throw error + } + watchingShizuku = true + } + val binderAvailable = runCatching { Shizuku.pingBinder() } + .onFailure { logFailure("check-Shizuku", activeProfileId, it) } + .getOrDefault(false) + if (binderAvailable) return + + updateRecovery(TetheringRecoveryState::onBinderDied) + // The request owns a receiver until Shizuku answers. Tie it to the application rather + // than the short-lived core Service, and do not register another when its Binder is live. + runCatching { ShizukuProvider.requestBinderForNonProviderProcess(service.applicationContext) } + .onFailure { logFailure("request-Binder", activeProfileId, it) } + } + + fun sendCurrentSnapshot(service: Service, coreRunning: Boolean) { + safely("snapshot", activeProfileId) { + val currentSnapshot = snapshot.takeIf { coreRunning } ?: HotspotRoutingSnapshot() + service.sendBroadcast( + Intent(AppConfig.BROADCAST_ACTION_ACTIVITY) + .setPackage(AppConfig.ANG_PACKAGE) + .putExtra("key", AppConfig.MSG_HOTSPOT_CONFIG_RESPONSE) + .putExtra("content", currentSnapshot) + .withCoreLease(coreLease.takeIf { currentSnapshot.running }), + ) + } + } + + private fun createSnapshot( + service: Service, + profileName: String, + useHev: Boolean, + ): HotspotRoutingSnapshot { + val hevSettings = HevTunnelSettings.current() + + return HotspotRoutingSnapshot( + running = true, + vpnMode = service is CoreVpnService, + profileName = profileName, + useHev = useHev, + ipv6Enabled = MmkvManager.decodeSettingsBool(AppConfig.PREF_IPV6_ENABLED) == true, + vpnDnsServers = SettingsManager.getVpnDnsServers(), + socksPort = SettingsManager.getSocksPort(), + socksUsername = SettingsManager.getSocksUsername(), + socksPassword = SettingsManager.getSocksPassword(), + mtu = SettingsManager.getVpnMtu(), + hevTcpTimeoutSeconds = hevSettings.tcpTimeoutSeconds, + hevUdpTimeoutSeconds = hevSettings.udpTimeoutSeconds, + hevLogLevel = hevSettings.logLevel, + launchId = Utils.getUuid(), + ) + } + + private fun send( + context: Context, + event: Int, + snapshot: HotspotRoutingSnapshot? = null, + detail: String = "", + ) { + if (!context.resources.getBoolean(R.bool.shizuku_tethering_enabled)) return + val token = MmkvManager.decodeSettingsString(AppConfig.PREF_SHIZUKU_SYNC_TOKEN) + ?.takeIf { it.isNotBlank() } + ?: run { + LogUtil.i(AppConfig.TAG, "Tethering sync event $event skipped: no active Shizuku session") + return + } + LogUtil.i( + AppConfig.TAG, + "Sending tethering sync event $event${snapshot?.profileName?.let { " for $it" }.orEmpty()}", + ) + runCatching { + context.sendBroadcast( + Intent(context, ShizukuRoutingSyncReceiver::class.java) + .setPackage(AppConfig.ANG_PACKAGE) + .putExtra("content", HotspotRoutingSync(token, event, snapshot, detail)) + .withCoreLease(coreLease.takeIf { snapshot != null }), + ) + }.onFailure { LogUtil.e(AppConfig.TAG, "Unable to send tethering synchronization", it) } + } + + private fun updateRecovery(update: (TetheringRecoveryState) -> TetheringRecoveryState) { + synchronized(recoveryLock) { recoveryState = update(recoveryState) } + } + + private fun transitionRecovery( + update: (TetheringRecoveryState) -> TetheringRecoveryTransition, + ): TetheringRecoveryAction = synchronized(recoveryLock) { + val transition = update(recoveryState) + recoveryState = transition.state + transition.action + } + + private fun safely(phase: String, profileId: String = activeProfileId, action: () -> Unit) { + runCoreSyncHook(action) { error -> logFailure(phase, profileId, error) } + } + + private fun logFailure(phase: String, profileId: String, error: Throwable) { + runCatching { + LogUtil.e( + AppConfig.TAG, + "Tethering sync failed: mode=shared-core phase=$phase profileId=$profileId operation=Shizuku synchronization", + error, + ) + } + } +} + +private class CoreTetheringLease : ICoreTetheringLease.Stub() { + private var connectivityManager: ConnectivityManager? = null + private var networkCallback: ConnectivityManager.NetworkCallback? = null + private var tun: ParcelFileDescriptor? = null + private data class Launch(val snapshot: HotspotRoutingSnapshot, val config: String) + @Volatile private var launch: Launch? = null + private var assetDirectory: File? = null + private var configDirectory: File? = null + + @Synchronized + fun attach(service: Service, snapshot: HotspotRoutingSnapshot, coreConfig: String) { + connectivityManager = service.getSystemService(ConnectivityManager::class.java) + launch = Launch(snapshot, coreConfig) + assetDirectory = File(Utils.userAssetPath(service)) + configDirectory = service.cacheDir + } + + @Synchronized + fun clearEngineConfig() { + launch = null + assetDirectory = null + configDirectory = null + } + + override fun isCurrentLaunch(launchId: String): Boolean = launch?.snapshot?.launchId == launchId + + override fun openEngineConfig(launchId: String): ParcelFileDescriptor { + val (current, directory) = synchronized(this) { + val current = checkNotNull(launch) { "Core routing snapshot is unavailable" } + check(current.snapshot.launchId == launchId) { "Core launch was superseded" } + current to checkNotNull(configDirectory) { "Core cache directory is unavailable" } + } + // Capture one immutable launch, then do parsing/file I/O outside the lifecycle lock. + // A delayed Binder request must never combine old metadata with a newer configuration. + val temporary = File.createTempFile(ENGINE_CONFIG_FILE_PREFIX, null, directory) + try { + temporary.writeText( + HotspotRoutingConfig.engineContentFromSnapshot(current.snapshot, current.config), + Charsets.UTF_8, + ) + return ParcelFileDescriptor.open(temporary, ParcelFileDescriptor.MODE_READ_ONLY) + } finally { + // Unix keeps the opened inode alive for the Binder recipient while removing the + // credential-bearing configuration pathname immediately. + temporary.delete() + } + } + + @Synchronized + override fun assetFingerprint(): String = assetFiles().joinToString("|") { + "${it.name}:${it.length()}:${it.lastModified()}" + } + + @Synchronized + override fun listAssetFiles(): Array = assetFiles().map { it.name }.toTypedArray() + + @Synchronized + override fun openAssetFile(name: String): ParcelFileDescriptor { + require(name.isNotBlank() && File(name).name == name) { "Invalid asset name" } + val file = File(checkNotNull(assetDirectory) { "Core asset directory is unavailable" }, name) + require(file.isFile) { "Core asset is unavailable: $name" } + return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY) + } + + private fun assetFiles(): List = assetDirectory?.listFiles() + ?.filter { it.isFile } + ?.sortedBy { it.name } + .orEmpty() + + @Synchronized + override fun holdTestNetwork(tun: ParcelFileDescriptor) { + releaseTestNetwork() + val manager = checkNotNull(connectivityManager) { "Core network manager is unavailable" } + val callback = ConnectivityManager.NetworkCallback() + try { + manager.requestNetwork(TetheringPlatformCompat.testNetworkRequest(), callback) + networkCallback = callback + this.tun = tun + } catch (error: Throwable) { + runCatching { tun.close() } + throw error + } + } + + @Synchronized + override fun releaseTestNetwork() { + networkCallback?.let { callback -> + runCatching { connectivityManager?.unregisterNetworkCallback(callback) } + } + networkCallback = null + tun?.let { runCatching { it.close() } } + tun = null + } +} + +private const val EXTRA_CORE_LEASE = "core_tethering_lease" +private const val ENGINE_CONFIG_FILE_PREFIX = "v2rayng-tethering-config-" + +private fun Intent.withCoreLease(lease: ICoreTetheringLease?): Intent = apply { + lease ?: return@apply + putExtra(EXTRA_CORE_LEASE, Bundle().apply { putBinder(EXTRA_CORE_LEASE, lease.asBinder()) }) +} + +internal fun Intent.coreTetheringLease(): ICoreTetheringLease? = + getBundleExtra(EXTRA_CORE_LEASE)?.getBinder(EXTRA_CORE_LEASE) + ?.let(ICoreTetheringLease.Stub::asInterface) + +internal enum class TetheringRecoveryAction { + NONE, + RECOVER, + REQUEST_BINDER, +} + +internal data class TetheringRecoveryTransition( + val state: TetheringRecoveryState, + val action: TetheringRecoveryAction = TetheringRecoveryAction.NONE, +) + +internal data class TetheringRecoveryState( + val coreRunning: Boolean = false, + val recoverWhenShizukuReturns: Boolean = false, + val foregroundRequestPending: Boolean = false, +) { + fun onCoreStarted() = copy(coreRunning = true) + + fun onCoreStopped() = TetheringRecoveryState() + + fun onBinderDied() = copy( + recoverWhenShizukuReturns = coreRunning, + foregroundRequestPending = false, + ) + + fun onBinderReceived(): TetheringRecoveryTransition { + val recover = coreRunning && recoverWhenShizukuReturns + return TetheringRecoveryTransition( + state = copy( + recoverWhenShizukuReturns = false, + foregroundRequestPending = false, + ), + action = if (recover) TetheringRecoveryAction.RECOVER else TetheringRecoveryAction.NONE, + ) + } + + fun onAppForegrounded(sdkInt: Int): TetheringRecoveryTransition { + val requestBinder = sdkInt >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE && + recoverWhenShizukuReturns && !foregroundRequestPending + return TetheringRecoveryTransition( + state = if (requestBinder) copy(foregroundRequestPending = true) else this, + action = if (requestBinder) TetheringRecoveryAction.REQUEST_BINDER else TetheringRecoveryAction.NONE, + ) + } + + fun onForegroundRequestFailed() = copy(foregroundRequestPending = false) +} + +internal fun runCoreSyncHook(action: () -> Unit, onFailure: (Throwable) -> Unit): Boolean = try { + action() + true +} catch (error: Throwable) { + runCatching { onFailure(error) } + false +} diff --git a/V2rayNG/app/src/main/java/com/v2ray/ang/shizuku/TetheringPlatformCompat.kt b/V2rayNG/app/src/main/java/com/v2ray/ang/shizuku/TetheringPlatformCompat.kt new file mode 100644 index 00000000000..0cb6fbe2348 --- /dev/null +++ b/V2rayNG/app/src/main/java/com/v2ray/ang/shizuku/TetheringPlatformCompat.kt @@ -0,0 +1,230 @@ +package com.v2ray.ang.shizuku + +import android.annotation.SuppressLint +import android.net.ConnectivityManager +import android.net.Network +import android.net.NetworkCapabilities +import android.net.NetworkRequest +import android.os.Build +import android.util.Log +import androidx.annotation.ChecksSdkIntAtLeast +import java.lang.reflect.Proxy +import java.util.concurrent.CountDownLatch +import java.util.concurrent.Executor +import java.util.concurrent.ExecutorService +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicReference + +/** TetheringManager compatibility for Android 13 through 15. */ +internal object TetheringPlatformCompat { + + // Remove WrongConstant only when TRANSPORT_TEST enters the public SDK, or when the protected + // upstream stops being an Android test network and this request is deleted with it. + @SuppressLint("WrongConstant") + fun testNetworkRequest(): NetworkRequest = NetworkRequest.Builder() + .addTransportType(TRANSPORT_TEST) + .removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN) + .removeCapability(NetworkCapabilities.NET_CAPABILITY_TRUSTED) + .build() + + fun observeUpstreamLegacy( + service: Any, + connectivityManager: ConnectivityManager, + executor: Executor, + onChanged: () -> Unit, + ): TetheringUpstreamMonitor { + require(Build.VERSION.SDK_INT in Build.VERSION_CODES.TIRAMISU until Build.VERSION_CODES.BAKLAVA) + // API 33-35 hide this callback and the downstream-state APIs used below. Delete this + // reflection branch only when the feature's minimum supported API becomes 36; API 36 made + // the required TetheringManager types public, but that does not help older installations. + val callbackClass = Class.forName(TETHERING_EVENT_CALLBACK_CLASS) + check(callbackClass.isInterface) { "Tethering event callback is not an interface" } + val interfaceClass = Class.forName("android.net.TetheringInterface") + val getType = interfaceClass.getMethod("getType") + val getInterface = interfaceClass.getMethod("getInterface") + val interfaceNames = AtomicReference(null) + val interfaces = AtomicReference?>(null) + val interfacesReceived = CountDownLatch(1) + val changeExecutor = newTetheringChangeExecutor() + val callback = Proxy.newProxyInstance( + TetheringPlatformCompat::class.java.classLoader, + arrayOf(callbackClass), + ) { proxy, method, arguments -> + when (method.name) { + "onUpstreamChanged" -> { + val network = arguments?.firstOrNull() as? Network + interfaceNames.set(upstreamInterfaceNames(connectivityManager, network)) + runCatching { changeExecutor.execute(onChanged) } + null + } + "onTetheredInterfacesChanged" -> { + // API 33 already supplies Set; only its SDK visibility + // changes in API 36. Read that event, not getTetheredIfaces(): the manager's + // separate internal callback may not have updated its cache yet. + interfaces.set(runCatching { + val downstreams = arguments?.firstOrNull() as? Set<*> + ?: error("Tethering callback did not supply interface identities") + downstreams.map { downstream -> + ActiveTetheringInterface(getType.invoke(downstream) as Int, getInterface.invoke(downstream) as String) + } + } + .onFailure { Log.e("TetheringPlatformCompat", "Unable to identify active downstreams", it) } + .getOrNull()) + interfacesReceived.countDown() + runCatching { changeExecutor.execute(onChanged) } + null + } + "equals" -> proxy === arguments?.firstOrNull() + "hashCode" -> System.identityHashCode(proxy) + "toString" -> "v2rayNG tethering upstream callback" + else -> null + } + } + val register = service.javaClass.methods.firstOrNull { + it.name == "registerTetheringEventCallback" && + it.parameterTypes.contentEquals(arrayOf(Executor::class.java, callbackClass)) + } ?: error("TetheringManager.registerTetheringEventCallback is unavailable") + val unregister = service.javaClass.methods.firstOrNull { + it.name == "unregisterTetheringEventCallback" && + it.parameterTypes.contentEquals(arrayOf(callbackClass)) + } ?: error("TetheringManager.unregisterTetheringEventCallback is unavailable") + try { + register.invoke(service, executor, callback) + } catch (error: Throwable) { + changeExecutor.shutdownNow() + throw error + } + return TetheringUpstreamMonitor( + interfaceNames, + interfaces, + interfacesReceived, + ) { + runCatching { unregister.invoke(service, callback) } + changeExecutor.shutdownNow() + } + } + + internal fun isProtectedUpstream(actual: String, expected: String): Boolean { + if (expected.isBlank()) return false + // The callback reports the selected network's LinkProperties.interfaceName, not a list. + return actual == expected + } + + fun startTethering( + service: Any, + type: Int, + executor: Executor, + timeoutSeconds: Long, + ): Int { + require(Build.VERSION.SDK_INT in Build.VERSION_CODES.TIRAMISU until Build.VERSION_CODES.BAKLAVA) + // API 33-35 contain this callback API but keep all three participating types out of the + // public SDK. Reflection prevents those hidden types from leaking into the stable app + // contract. Delete this branch when the feature's minimum supported API becomes 36. + val requestClass = Class.forName(TETHERING_REQUEST_CLASS) + val requestBuilderClass = Class.forName(TETHERING_REQUEST_BUILDER_CLASS) + val callbackClass = Class.forName(START_TETHERING_CALLBACK_CLASS) + check(callbackClass.isInterface) { "Start tethering callback is not an interface" } + val request = requestBuilderClass.getConstructor(Integer.TYPE).newInstance(type).let { builder -> + requestBuilderClass.getMethod("build").invoke(builder) + } + var result = ShizukuTetheringService.RESULT_INTERNAL_ERROR + val callbackReceived = CountDownLatch(1) + val callback = Proxy.newProxyInstance( + TetheringPlatformCompat::class.java.classLoader, + arrayOf(callbackClass), + ) { proxy, method, arguments -> + when (method.name) { + "onTetheringStarted" -> { + result = ShizukuTetheringService.RESULT_OK + callbackReceived.countDown() + null + } + "onTetheringFailed" -> { + result = (arguments?.firstOrNull() as? Number)?.toInt() + ?: ShizukuTetheringService.RESULT_INTERNAL_ERROR + callbackReceived.countDown() + null + } + "equals" -> proxy === arguments?.firstOrNull() + "hashCode" -> System.identityHashCode(proxy) + "toString" -> "v2rayNG start tethering callback" + else -> null + } + } + val start = service.javaClass.methods.firstOrNull { + it.name == "startTethering" && it.parameterTypes.contentEquals( + arrayOf(requestClass, Executor::class.java, callbackClass), + ) + } ?: error("TetheringManager.startTethering is unavailable") + start.invoke(service, request, executor, callback) + return if (callbackReceived.await(timeoutSeconds, TimeUnit.SECONDS)) { + result + } else { + ShizukuTetheringService.RESULT_INTERNAL_ERROR + } + } + + // The service performs the shared postcondition check after this legacy API returns, so + // Android 13-15 follows the same single bounded wait as newer releases. + fun stopTethering(service: Any, type: Int): Int { + require(Build.VERSION.SDK_INT in Build.VERSION_CODES.TIRAMISU until Build.VERSION_CODES.BAKLAVA) + val method = service.javaClass.methods.firstOrNull { + it.name == "stopTethering" && + it.parameterTypes.contentEquals(arrayOf(Integer.TYPE)) + } ?: error("TetheringManager.stopTethering(int) is unavailable") + method.invoke(service, type) + return ShizukuTetheringService.RESULT_OK + } + + private const val TETHERING_EVENT_CALLBACK_CLASS = + "android.net.TetheringManager\$TetheringEventCallback" + private const val TETHERING_REQUEST_CLASS = "android.net.TetheringManager\$TetheringRequest" + private const val TETHERING_REQUEST_BUILDER_CLASS = + "android.net.TetheringManager\$TetheringRequest\$Builder" + private const val START_TETHERING_CALLBACK_CLASS = + "android.net.TetheringManager\$StartTetheringCallback" + private const val TRANSPORT_TEST = 7 +} + +internal class TetheringUpstreamMonitor( + private val interfaceNames: AtomicReference, + private val interfaces: AtomicReference?>, + private val interfacesReceived: CountDownLatch, + private val closeAction: () -> Unit, +) : AutoCloseable { + val currentInterfaceNames: String? + get() = interfaceNames.get() + + val currentInterfaces: List? + get() = interfaces.get() + + fun awaitInterfaces(timeoutSeconds: Long): List { + check(interfacesReceived.await(timeoutSeconds, TimeUnit.SECONDS)) { "Timed out reading tethered interfaces" } + return checkNotNull(currentInterfaces) { "Unable to identify active tethering interfaces" } + } + + override fun close() = closeAction() +} + +@ChecksSdkIntAtLeast(api = Build.VERSION_CODES.BAKLAVA) +internal fun usesPublicTetheringApi(): Boolean = isPublicTetheringApiLevel(Build.VERSION.SDK_INT) + +internal fun isPublicTetheringApiLevel(sdkInt: Int): Boolean = sdkInt >= Build.VERSION_CODES.BAKLAVA + +internal fun upstreamInterfaceNames(connectivityManager: ConnectivityManager, network: Network?): String { + val properties = network?.let(connectivityManager::getLinkProperties) ?: return "" + return properties.interfaceName.orEmpty() +} + +internal fun newTetheringChangeExecutor(): ExecutorService = + Executors.newSingleThreadExecutor { command -> + Thread(command, "TetheringUpstreamMonitor").apply { isDaemon = true } + } + +internal data class ActiveTetheringInterface( + val type: Int, + val name: String, +) + +internal fun tetheringTypeBit(type: Int): Int = if (type in 0..30) 1 shl type else 0 diff --git a/V2rayNG/app/src/main/java/com/v2ray/ang/shizuku/TetheringStatusSnapshot.kt b/V2rayNG/app/src/main/java/com/v2ray/ang/shizuku/TetheringStatusSnapshot.kt new file mode 100644 index 00000000000..cb92d791be1 --- /dev/null +++ b/V2rayNG/app/src/main/java/com/v2ray/ang/shizuku/TetheringStatusSnapshot.kt @@ -0,0 +1,40 @@ +package com.v2ray.ang.shizuku + +import android.os.Parcel +import android.os.Parcelable + +/** The shell-side tethering status returned to the UI in one Binder call. */ +data class TetheringStatusSnapshot( + val routingState: Int, + val routingDetail: String, + val activeTetheringTypes: Int, + val ipv6TetheringTypes: Int, + val warning: Int, + val hasRoutingSession: Boolean = false, +) : Parcelable { + private constructor(parcel: Parcel) : this( + routingState = parcel.readInt(), + routingDetail = parcel.readString().orEmpty(), + activeTetheringTypes = parcel.readInt(), + ipv6TetheringTypes = parcel.readInt(), + warning = parcel.readInt(), + hasRoutingSession = parcel.readInt() != 0, + ) + + override fun writeToParcel(parcel: Parcel, flags: Int) { + parcel.writeInt(routingState) + parcel.writeString(routingDetail) + parcel.writeInt(activeTetheringTypes) + parcel.writeInt(ipv6TetheringTypes) + parcel.writeInt(warning) + parcel.writeInt(if (hasRoutingSession) 1 else 0) + } + + override fun describeContents(): Int = 0 + + companion object CREATOR : Parcelable.Creator { + override fun createFromParcel(parcel: Parcel) = TetheringStatusSnapshot(parcel) + + override fun newArray(size: Int): Array = arrayOfNulls(size) + } +} diff --git a/V2rayNG/app/src/main/java/com/v2ray/ang/ui/ShizukuActivity.kt b/V2rayNG/app/src/main/java/com/v2ray/ang/ui/ShizukuActivity.kt new file mode 100644 index 00000000000..37fb7968064 --- /dev/null +++ b/V2rayNG/app/src/main/java/com/v2ray/ang/ui/ShizukuActivity.kt @@ -0,0 +1,26 @@ +package com.v2ray.ang.ui + +import androidx.activity.viewModels +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.v2ray.ang.ui.base.BaseComponentActivity + +class ShizukuActivity : BaseComponentActivity() { + private val viewModel: ShizukuViewModel by viewModels() + + @Composable + override fun ScreenContent() { + val state by viewModel.uiState.collectAsStateWithLifecycle() + TetheringScreen( + state = state, + onBackClick = { finish() }, + onAction = viewModel::onAction, + ) + } + + override fun onResume() { + super.onResume() + viewModel.onResume() + } +} diff --git a/V2rayNG/app/src/main/java/com/v2ray/ang/ui/ShizukuViewModel.kt b/V2rayNG/app/src/main/java/com/v2ray/ang/ui/ShizukuViewModel.kt new file mode 100644 index 00000000000..dcfee7f5159 --- /dev/null +++ b/V2rayNG/app/src/main/java/com/v2ray/ang/ui/ShizukuViewModel.kt @@ -0,0 +1,536 @@ +package com.v2ray.ang.ui + +import android.app.Application +import android.content.BroadcastReceiver +import android.content.ComponentName +import android.content.Context +import android.content.Intent +import android.content.IntentFilter +import android.content.ServiceConnection +import android.content.pm.PackageManager +import android.os.Build +import android.os.IBinder +import androidx.core.content.ContextCompat +import androidx.lifecycle.viewModelScope +import com.v2ray.ang.AppConfig +import com.v2ray.ang.R +import com.v2ray.ang.dto.HotspotRoutingSnapshot +import com.v2ray.ang.extension.serializable +import com.v2ray.ang.extension.toastInfo +import com.v2ray.ang.handler.MmkvManager +import com.v2ray.ang.helper.MessageHelper +import com.v2ray.ang.shizuku.HotspotRoutingConfig +import com.v2ray.ang.shizuku.ICoreTetheringLease +import com.v2ray.ang.shizuku.IShizukuTetheringService +import com.v2ray.ang.shizuku.ITetheringStatusListener +import com.v2ray.ang.shizuku.ShizukuTetheringService +import com.v2ray.ang.shizuku.TetheringStatusSnapshot +import com.v2ray.ang.shizuku.coreTetheringLease +import com.v2ray.ang.ui.base.BaseViewModel +import com.v2ray.ang.util.LogUtil +import com.v2ray.ang.util.Utils +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeoutOrNull +import rikka.shizuku.Shizuku +import rikka.shizuku.ShizukuProvider + +internal class ShizukuViewModel(application: Application) : BaseViewModel(application) { + private val _uiState = MutableStateFlow(TetheringUiState()) + val uiState: StateFlow = _uiState.asStateFlow() + + private var tetheringService: IShizukuTetheringService? = null + private var operationJob: Job? = null + private var operationGeneration = 0L + private var statusRefreshPending = false + private var snapshotWaiter: CompletableDeferred? = null + private var bindingTimeout: Job? = null + + private val userServiceArgs by lazy { + ShizukuTetheringService.createUserServiceArgs() + } + + private val userServiceConnection = object : ServiceConnection { + override fun onServiceConnected(name: ComponentName, binder: IBinder) { + viewModelScope.launch { + bindingTimeout?.cancel() + bindingTimeout = null + val service = IShizukuTetheringService.Stub.asInterface(binder) + tetheringService = service + _uiState.update { it.withServiceConnection(true) } + withContext(Dispatchers.IO) { + shizukuCall("register status listener", Unit) { service.setStatusListener(statusListener) } + } + refreshTetheringStatus() + } + } + + override fun onServiceDisconnected(name: ComponentName) { + viewModelScope.launch { clearServiceState() } + } + } + + private val statusListener = object : ITetheringStatusListener.Stub() { + override fun onStatusChanged() { + // Platform callbacks and core synchronization can change the shell-side state while + // this screen is idle. Refresh from that source of truth instead of polling it. + viewModelScope.launch { refreshTetheringStatus() } + } + } + + private val binderReceivedListener = Shizuku.OnBinderReceivedListener { + viewModelScope.launch { refreshShizukuStatus() } + } + private val binderDeadListener = Shizuku.OnBinderDeadListener { + viewModelScope.launch { + clearServiceState() + refreshShizukuStatus() + } + } + private val permissionResultListener = Shizuku.OnRequestPermissionResultListener { requestCode, grantResult -> + if (requestCode == SHIZUKU_PERMISSION_REQUEST_CODE) { + viewModelScope.launch { + if (grantResult == PackageManager.PERMISSION_GRANTED) { + toastSuccess(R.string.shizuku_permission_granted) + } else { + toastError(R.string.shizuku_permission_denied) + } + refreshShizukuStatus() + } + } + } + + private val coreStateReceiver = object : BroadcastReceiver() { + override fun onReceive(context: Context?, intent: Intent?) { + when (intent?.getIntExtra("key", 0)) { + AppConfig.MSG_STATE_RUNNING, + AppConfig.MSG_STATE_START_SUCCESS -> { + _uiState.update { it.withCoreRunning(true) } + requestCoreSnapshotAsync() + } + + AppConfig.MSG_STATE_NOT_RUNNING, + AppConfig.MSG_STATE_STOP_SUCCESS, + AppConfig.MSG_STATE_START_FAILURE -> _uiState.update { it.withCoreRunning(false) } + + AppConfig.MSG_HOTSPOT_CONFIG_RESPONSE -> { + val snapshot = intent.serializable("content") + ?: HotspotRoutingSnapshot() + _uiState.update { it.withCoreSnapshot(snapshot) } + snapshotWaiter?.takeIf { !it.isCompleted }?.complete( + CoreRoutingSnapshot(snapshot, intent.coreTetheringLease()), + ) + } + } + } + } + + init { + ContextCompat.registerReceiver( + app, + coreStateReceiver, + IntentFilter(AppConfig.BROADCAST_ACTION_ACTIVITY), + // The response carries the Binder that owns the protected test network. + ContextCompat.RECEIVER_NOT_EXPORTED, + ) + Shizuku.addBinderReceivedListenerSticky(binderReceivedListener) + Shizuku.addBinderDeadListener(binderDeadListener) + Shizuku.addRequestPermissionResultListener(permissionResultListener) + } + + fun onResume() { + queryCoreState() + viewModelScope.launch { refreshShizukuStatus() } + } + + fun onAction(action: ShizukuAction) { + when (action) { + ShizukuAction.RequestPermission -> requestShizukuPermission() + ShizukuAction.Refresh -> { + requestCoreSnapshotAsync() + viewModelScope.launch { refreshShizukuStatus() } + } + ShizukuAction.ToggleRouting -> toggleRouting() + ShizukuAction.ToggleHotspot -> toggleHotspot() + } + } + + private fun queryCoreState() { + MessageHelper.sendMsg2Service(app, AppConfig.MSG_REGISTER_CLIENT, "") + } + + private fun requestCoreSnapshotAsync() { + MessageHelper.sendMsg2Service(app, AppConfig.MSG_QUERY_HOTSPOT_CONFIG, "") + } + + private suspend fun refreshShizukuStatus() { + val status = getShizukuStatus() + _uiState.update { it.copy(shizukuStatus = status) } + if (status != ShizukuStatus.READY) { + clearServiceState() + return + } + if (tetheringService == null) bindUserService() else refreshTetheringStatus() + } + + private suspend fun getShizukuStatus(): ShizukuStatus = withContext(Dispatchers.IO) { + if (!shizukuCall("check Binder", false) { Shizuku.pingBinder() }) { + return@withContext if (isPackageInstalled(ShizukuProvider.MANAGER_APPLICATION_ID)) { + ShizukuStatus.NOT_RUNNING + } else { + ShizukuStatus.NOT_INSTALLED + } + } + if (shizukuCall("check server version", true) { Shizuku.isPreV11() }) { + return@withContext ShizukuStatus.UNSUPPORTED + } + val permissionGranted = shizukuCall("check permission", false) { + Shizuku.checkSelfPermission() == PackageManager.PERMISSION_GRANTED + } + if (permissionGranted) return@withContext ShizukuStatus.READY + + if (shizukuCall("check permission rationale", false) { + Shizuku.shouldShowRequestPermissionRationale() + }) { + ShizukuStatus.PERMISSION_DENIED + } else { + ShizukuStatus.PERMISSION_REQUIRED + } + } + + private fun requestShizukuPermission() { + viewModelScope.launch { + when (val status = getShizukuStatus()) { + ShizukuStatus.PERMISSION_REQUIRED -> runCatching { + Shizuku.requestPermission(SHIZUKU_PERMISSION_REQUEST_CODE) + }.onFailure { + logUiFailure("permission", "request permission", it) + toastError(R.string.shizuku_operation_failed) + refreshShizukuStatus() + } + + ShizukuStatus.READY -> refreshShizukuStatus() + else -> { + toastError(status.statusRes) + refreshShizukuStatus() + } + } + } + } + + private fun bindUserService() { + if (_uiState.value.operation == TetheringOperation.CONNECTING || tetheringService != null) return + _uiState.update { it.copy(operation = TetheringOperation.CONNECTING) } + + runCatching { + Shizuku.bindUserService(userServiceArgs, userServiceConnection) + bindingTimeout = viewModelScope.launch { + delay(USER_SERVICE_BIND_TIMEOUT_MS) + if (tetheringService == null) { + runCatching { Shizuku.unbindUserService(userServiceArgs, userServiceConnection, false) } + .onFailure { logUiFailure("connection", "unbind timed-out UserService", it) } + clearServiceState() + toastError(R.string.shizuku_operation_failed) + } + } + }.onFailure { + clearServiceState() + logUiFailure("connection", "bind UserService", it) + toastError(R.string.shizuku_operation_failed) + } + } + + private fun refreshTetheringStatus() { + if (_uiState.value.operation.isToggleInProgress) return + if (_uiState.value.operation == TetheringOperation.CHECKING) { + statusRefreshPending = true + return + } + val service = tetheringService ?: run { + clearServiceState() + return + } + statusRefreshPending = false + val generation = cancelCurrentOperation() + _uiState.update { it.copy(operation = TetheringOperation.CHECKING) } + operationJob = viewModelScope.launch { + val (ipv6Enabled, status) = withContext(Dispatchers.IO) { + val enabled = MmkvManager.decodeSettingsBool(AppConfig.PREF_IPV6_ENABLED) == true + enabled to try { + service.getStatus(enabled) + } catch (error: CancellationException) { + throw error + } catch (error: Throwable) { + logUiFailure("status", "read UserService status", error) + TetheringStatusSnapshot( + routingState = ShizukuTetheringService.ROUTING_STATE_ERROR, + routingDetail = "", + activeTetheringTypes = ShizukuTetheringService.TETHERING_TYPES_UNKNOWN, + ipv6TetheringTypes = ShizukuTetheringService.TETHERING_TYPES_UNKNOWN, + warning = ShizukuTetheringService.RESULT_OK, + ) + } + } + if (generation != operationGeneration) return@launch + _uiState.update { it.withTetheringStatus(status, ipv6Enabled) } + operationJob = null + if (status.warning == ShizukuTetheringService.RESULT_UNPROTECTED_UPSTREAM) { + localizedContext.toastInfo(R.string.shizuku_tethering_wrong_upstream) + } + if (statusRefreshPending) refreshTetheringStatus() + } + } + + private fun toggleRouting() { + val operation = _uiState.value.operationFor(ShizukuAction.ToggleRouting) ?: return + val enable = operation == TetheringOperation.STARTING_ROUTING + launchOperation(operation) { service -> + val result = if (enable) { + startRouting(service) + } else { + stopRouting(service) + } ?: return@launchOperation + if (result != ShizukuTetheringService.RESULT_OK) { + showRoutingError(result) + return@launchOperation + } + toastSuccess( + if (enable) R.string.shizuku_routing_enabled + else R.string.shizuku_routing_disabled + ) + } + } + + private fun toggleHotspot() { + val operation = _uiState.value.operationFor(ShizukuAction.ToggleHotspot) ?: return + val enable = operation == TetheringOperation.STARTING_HOTSPOT + launchOperation(operation) { service -> + var routingStartedHere = false + if (enable && !_uiState.value.routingActive) { + val routingResult = startRouting(service) ?: return@launchOperation + if (routingResult != ShizukuTetheringService.RESULT_OK) { + showRoutingError(routingResult) + return@launchOperation + } + routingStartedHere = true + } + + val result = callService("set Wi-Fi hotspot enabled=$enable") { + service.setWifiHotspotEnabled(enable) + } + if (result != ShizukuTetheringService.RESULT_OK) { + if (routingStartedHere) { + stopRouting(service) + } + if (result != ShizukuTetheringService.RESULT_UNPROTECTED_UPSTREAM) { + toastError(getString(R.string.shizuku_hotspot_operation_failed, result)) + } + return@launchOperation + } + + toastSuccess( + if (enable) R.string.shizuku_hotspot_enabled + else R.string.shizuku_hotspot_disabled + ) + } + } + + private fun launchOperation( + operation: TetheringOperation, + action: suspend (IShizukuTetheringService) -> Unit, + ) { + if (_uiState.value.operation.isToggleInProgress) return + val service = tetheringService ?: return + val generation = cancelCurrentOperation() + _uiState.update { it.copy(operation = operation) } + operationJob = viewModelScope.launch { + try { + action(service) + } catch (error: CancellationException) { + throw error + } catch (error: Throwable) { + logUiFailure("operation", operation.name, error) + toastError(R.string.shizuku_operation_failed) + } finally { + if (generation == operationGeneration) { + operationJob = null + _uiState.update { it.copy(operation = TetheringOperation.NONE) } + refreshTetheringStatus() + } + } + } + } + + private suspend fun callService(operation: String, action: () -> Int): Int = withContext(Dispatchers.IO) { + // A reopened screen must not overtake an old screen's pending remote operation and its + // token bookkeeping. This process-wide ordering never blocks the UI thread. + synchronized(serviceOperationLock) { + try { + action() + } catch (error: CancellationException) { + throw error + } catch (error: Throwable) { + logUiFailure("Binder", operation, error) + ShizukuTetheringService.RESULT_INTERNAL_ERROR + } + } + } + + // Null means the local failure was already reported; do not replace it with a generic error. + private suspend fun startRouting(service: IShizukuTetheringService): Int? { + val core = requestCoreSnapshot() ?: run { + toastError(R.string.shizuku_routing_snapshot_timeout) + return null + } + val snapshot = core.snapshot + if (!snapshot.running || !snapshot.vpnMode) { + toastError(R.string.shizuku_routing_status_start_v2ray) + return null + } + val parameters = try { + withContext(Dispatchers.Default) { + HotspotRoutingConfig.parametersFromSnapshot(snapshot) + } + } catch (error: CancellationException) { + throw error + } catch (error: Throwable) { + logUiFailure("configuration", "prepare tethering parameters", error) + toastError(R.string.shizuku_routing_snapshot_timeout) + return null + } + val coreLease = core.lease ?: run { + toastError(R.string.shizuku_operation_failed) + return null + } + + return callService("start routing") { + val previousToken = MmkvManager.decodeSettingsString(AppConfig.PREF_SHIZUKU_SYNC_TOKEN).orEmpty() + val token = Utils.getUuid() + MmkvManager.encodeSettings(AppConfig.PREF_SHIZUKU_SYNC_TOKEN, token) + var started = false + try { + service.startRouting( + parameters.useHev, parameters.profileName, parameters.dnsServers.toTypedArray(), + parameters.ipv6Enabled, parameters.xudpKey, token, parameters.launchId, coreLease, + ).also { started = it == ShizukuTetheringService.RESULT_OK } + } finally { + if (!started) { + MmkvManager.encodeSettings(AppConfig.PREF_SHIZUKU_SYNC_TOKEN, previousToken) + } + } + } + } + + private suspend fun stopRouting(service: IShizukuTetheringService): Int = callService("stop routing") { + // Binder calls cannot be cancelled once submitted. Commit their bookkeeping in the same + // IO block, before dispatching back to a ViewModel which may already have been cleared. + service.stopRouting().also { result -> + if (result == ShizukuTetheringService.RESULT_OK) MmkvManager.encodeSettings(AppConfig.PREF_SHIZUKU_SYNC_TOKEN, "") + } + } + + private suspend fun requestCoreSnapshot(): CoreRoutingSnapshot? { + val waiter = CompletableDeferred() + snapshotWaiter?.cancel() + snapshotWaiter = waiter + requestCoreSnapshotAsync() + return withTimeoutOrNull(CORE_SNAPSHOT_TIMEOUT_MS) { waiter.await() } + .also { if (snapshotWaiter === waiter) snapshotWaiter = null } + } + + private fun showRoutingError(result: Int) { + toastError( + getString( + R.string.shizuku_routing_operation_failed, + result, + getString(R.string.shizuku_operation_failed) + ) + ) + } + + private fun cancelCurrentOperation(): Long { + operationGeneration++ + operationJob?.cancel() + operationJob = null + return operationGeneration + } + + private fun clearServiceState() { + bindingTimeout?.cancel() + bindingTimeout = null + cancelCurrentOperation() + statusRefreshPending = false + tetheringService = null + _uiState.update { it.withServiceConnection(false) } + } + + private fun isPackageInstalled(packageName: String): Boolean = try { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return false + app.packageManager.getApplicationInfo(packageName, PackageManager.ApplicationInfoFlags.of(0)) + true + } catch (_: PackageManager.NameNotFoundException) { + false + } catch (error: Throwable) { + logUiFailure("status", "query Shizuku package", error) + false + } + + private fun shizukuCall(operation: String, default: T, action: () -> T): T = try { + action() + } catch (error: Throwable) { + logUiFailure("status", operation, error) + default + } + + private fun logUiFailure(phase: String, operation: String, error: Throwable) { + LogUtil.e( + AppConfig.TAG, + "Shizuku tethering failure: component=ui phase=$phase operation=$operation", + error, + ) + } + + override fun onCleared() { + cancelCurrentOperation() + snapshotWaiter?.cancel() + runCatching { app.unregisterReceiver(coreStateReceiver) } + .onFailure { logUiFailure("cleanup", "unregister core-state receiver", it) } + runCatching { Shizuku.removeBinderReceivedListener(binderReceivedListener) } + .onFailure { logUiFailure("cleanup", "remove Binder-received listener", it) } + runCatching { Shizuku.removeBinderDeadListener(binderDeadListener) } + .onFailure { logUiFailure("cleanup", "remove Binder-dead listener", it) } + runCatching { Shizuku.removeRequestPermissionResultListener(permissionResultListener) } + .onFailure { logUiFailure("cleanup", "remove permission listener", it) } + runCatching { tetheringService?.setStatusListener(null) } + .onFailure { logUiFailure("cleanup", "clear status listener", it) } + if (tetheringService != null || _uiState.value.operation == TetheringOperation.CONNECTING) { + runCatching { + // The service owns the live TUN and tethering upstream. Screen teardown must + // never destroy it; only the explicit Disable action may stop the datapath. + Shizuku.unbindUserService(userServiceArgs, userServiceConnection, false) + }.onFailure { logUiFailure("cleanup", "unbind UserService", it) } + } + tetheringService = null + } + + private data class CoreRoutingSnapshot( + val snapshot: HotspotRoutingSnapshot, + val lease: ICoreTetheringLease?, + ) + + companion object { + private val serviceOperationLock = Any() + private const val SHIZUKU_PERMISSION_REQUEST_CODE = 1001 + private const val CORE_SNAPSHOT_TIMEOUT_MS = 5_000L + private const val USER_SERVICE_BIND_TIMEOUT_MS = 5_000L + } +} diff --git a/V2rayNG/app/src/main/java/com/v2ray/ang/ui/TetheringScreen.kt b/V2rayNG/app/src/main/java/com/v2ray/ang/ui/TetheringScreen.kt new file mode 100644 index 00000000000..6e689c907d2 --- /dev/null +++ b/V2rayNG/app/src/main/java/com/v2ray/ang/ui/TetheringScreen.kt @@ -0,0 +1,457 @@ +package com.v2ray.ang.ui + +import androidx.compose.foundation.selection.toggleable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Scaffold +import androidx.compose.material3.ScaffoldDefaults +import androidx.compose.material3.Switch +import androidx.compose.material3.SwitchDefaults +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.scale +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import com.v2ray.ang.R +import com.v2ray.ang.dto.HotspotRoutingSnapshot +import com.v2ray.ang.shizuku.ShizukuTetheringService +import com.v2ray.ang.shizuku.TetheringStatusSnapshot +import com.v2ray.ang.shizuku.tetheringTypeBit +import com.v2ray.ang.ui.compose.AppTopBar + +internal enum class ShizukuStatus( + val statusRes: Int, + val detailsRes: Int?, +) { + CHECKING(R.string.shizuku_status_checking, null), + NOT_INSTALLED(R.string.shizuku_status_not_installed, R.string.shizuku_status_open_manager), + NOT_RUNNING(R.string.shizuku_status_not_running, R.string.shizuku_status_open_manager), + UNSUPPORTED(R.string.shizuku_status_unsupported, R.string.shizuku_status_update_required), + PERMISSION_REQUIRED( + R.string.shizuku_status_permission_required, + R.string.shizuku_status_permission_hint, + ), + PERMISSION_DENIED( + R.string.shizuku_status_permission_denied, + R.string.shizuku_status_permission_hint, + ), + READY(R.string.shizuku_status_ready, null); + + val canRequestPermission: Boolean + get() = this == PERMISSION_REQUIRED +} + +internal enum class TetheringOperation { + NONE, + CONNECTING, + CHECKING, + STARTING_ROUTING, + STOPPING_ROUTING, + STARTING_HOTSPOT, + STOPPING_HOTSPOT; + + val isToggleInProgress: Boolean + get() = this == STARTING_ROUTING || this == STOPPING_ROUTING || + this == STARTING_HOTSPOT || this == STOPPING_HOTSPOT +} + +internal data class TetheringUiState( + val shizukuStatus: ShizukuStatus = ShizukuStatus.CHECKING, + val operation: TetheringOperation = TetheringOperation.NONE, + val routingState: Int = ShizukuTetheringService.ROUTING_STATE_DISABLED, + val routingDetail: String = "", + val activeTetheringTypes: Int = ShizukuTetheringService.TETHERING_TYPES_UNKNOWN, + val ipv6TetheringTypes: Int = ShizukuTetheringService.TETHERING_TYPES_UNKNOWN, + val ipv6Enabled: Boolean = false, + val coreRunning: Boolean = false, + val coreVpnMode: Boolean = false, + val serviceConnected: Boolean = false, + val hasRoutingSession: Boolean = false, +) { + val vpnRunning: Boolean + get() = coreRunning && coreVpnMode + val routingActive: Boolean + get() = routingState == ShizukuTetheringService.ROUTING_STATE_ACTIVE_HEV || + routingState == ShizukuTetheringService.ROUTING_STATE_ACTIVE_NATIVE + val routingSessionEnabled: Boolean + get() = hasRoutingSession || routingActive || routingState == ShizukuTetheringService.ROUTING_STATE_WAITING + val hotspotEnabled: Boolean + get() = activeTetheringTypes >= 0 && + activeTetheringTypes and tetheringTypeBit(ShizukuTetheringService.TETHERING_TYPE_WIFI) != 0 + val tetheringStateKnown: Boolean + get() = activeTetheringTypes >= 0 +} + +internal sealed interface ShizukuAction { + data object RequestPermission : ShizukuAction + data object Refresh : ShizukuAction + data object ToggleRouting : ShizukuAction + data object ToggleHotspot : ShizukuAction +} + +internal fun TetheringUiState.withServiceConnection(connected: Boolean): TetheringUiState = + if (connected) { + copy(serviceConnected = true) + } else { + copy( + serviceConnected = false, + operation = TetheringOperation.NONE, + routingState = ShizukuTetheringService.ROUTING_STATE_DISABLED, + routingDetail = "", + hasRoutingSession = false, + activeTetheringTypes = ShizukuTetheringService.TETHERING_TYPES_UNKNOWN, + ipv6TetheringTypes = ShizukuTetheringService.TETHERING_TYPES_UNKNOWN, + ) + } + +internal fun TetheringUiState.withCoreRunning(running: Boolean): TetheringUiState = + copy(coreRunning = running, coreVpnMode = false) + +internal fun TetheringUiState.withCoreSnapshot(snapshot: HotspotRoutingSnapshot): TetheringUiState = + copy(coreRunning = snapshot.running, coreVpnMode = snapshot.vpnMode) + +internal fun TetheringUiState.withTetheringStatus( + status: TetheringStatusSnapshot, + ipv6Enabled: Boolean, +): TetheringUiState = copy( + operation = TetheringOperation.NONE, + routingState = status.routingState, + routingDetail = status.routingDetail, + activeTetheringTypes = status.activeTetheringTypes, + ipv6TetheringTypes = status.ipv6TetheringTypes, + ipv6Enabled = ipv6Enabled, + hasRoutingSession = status.hasRoutingSession, +) + +internal fun TetheringUiState.operationFor(action: ShizukuAction): TetheringOperation? = when (action) { + ShizukuAction.ToggleRouting -> if (routingSessionEnabled) { + TetheringOperation.STOPPING_ROUTING + } else { + TetheringOperation.STARTING_ROUTING + } + ShizukuAction.ToggleHotspot -> if (hotspotEnabled) { + TetheringOperation.STOPPING_HOTSPOT + } else { + TetheringOperation.STARTING_HOTSPOT + } + ShizukuAction.RequestPermission, + ShizukuAction.Refresh -> null +} + +internal enum class TetheringIpMode(val labelRes: Int) { + IPV4_ONLY(R.string.shizuku_tethering_ip_mode_ipv4), + DUAL_STACK(R.string.shizuku_tethering_ip_mode_dual_stack), + UNKNOWN(R.string.shizuku_tethering_ip_mode_unknown), +} + +internal fun TetheringUiState.ipMode(type: Int): TetheringIpMode? { + val bit = tetheringTypeBit(type) + if (!ipv6Enabled || activeTetheringTypes < 0 || activeTetheringTypes and bit == 0) return null + if (ipv6TetheringTypes < 0) return TetheringIpMode.UNKNOWN + return if (ipv6TetheringTypes and bit != 0) { + TetheringIpMode.DUAL_STACK + } else { + TetheringIpMode.IPV4_ONLY + } +} + +internal data class TetheringControlState( + val statusRes: Int, + val enabled: Boolean, +) + +internal fun routingAction( + state: TetheringUiState, +): TetheringControlState { + val statusRes = when { + state.operation == TetheringOperation.CONNECTING -> R.string.shizuku_routing_status_connecting + state.operation == TetheringOperation.CHECKING -> R.string.shizuku_routing_status_checking + state.operation == TetheringOperation.STARTING_ROUTING -> R.string.shizuku_routing_status_starting + state.operation == TetheringOperation.STOPPING_ROUTING -> R.string.shizuku_routing_status_stopping + !state.serviceConnected -> R.string.shizuku_routing_status_unavailable + state.routingState == ShizukuTetheringService.ROUTING_STATE_ACTIVE_HEV -> + R.string.shizuku_routing_status_hev + state.routingState == ShizukuTetheringService.ROUTING_STATE_ACTIVE_NATIVE -> + R.string.shizuku_routing_status_native + state.routingState == ShizukuTetheringService.ROUTING_STATE_STARTING -> + R.string.shizuku_routing_status_starting + state.routingState == ShizukuTetheringService.ROUTING_STATE_STOPPING -> + R.string.shizuku_routing_status_stopping + state.routingState == ShizukuTetheringService.ROUTING_STATE_WAITING -> + R.string.shizuku_routing_status_waiting + !state.routingSessionEnabled && !state.vpnRunning -> + R.string.shizuku_routing_status_start_v2ray + state.routingState == ShizukuTetheringService.ROUTING_STATE_ERROR -> + R.string.shizuku_routing_status_error + state.vpnRunning -> R.string.shizuku_routing_status_disabled + else -> R.string.shizuku_routing_status_start_v2ray + } + val enabled = state.serviceConnected && + state.operation == TetheringOperation.NONE && + when (state.routingState) { + ShizukuTetheringService.ROUTING_STATE_ACTIVE_HEV, + ShizukuTetheringService.ROUTING_STATE_ACTIVE_NATIVE, + ShizukuTetheringService.ROUTING_STATE_WAITING -> true + ShizukuTetheringService.ROUTING_STATE_ERROR, + ShizukuTetheringService.ROUTING_STATE_DISABLED -> state.routingSessionEnabled || state.vpnRunning + else -> false + } + return TetheringControlState( + statusRes = statusRes, + enabled = enabled, + ) +} + +internal fun hotspotAction( + state: TetheringUiState, +): TetheringControlState { + val statusRes = when { + state.operation == TetheringOperation.CONNECTING -> R.string.shizuku_hotspot_status_connecting + state.operation == TetheringOperation.CHECKING -> R.string.shizuku_hotspot_status_checking + state.operation == TetheringOperation.STARTING_HOTSPOT -> R.string.shizuku_hotspot_status_starting + state.operation == TetheringOperation.STOPPING_HOTSPOT -> R.string.shizuku_hotspot_status_stopping + !state.serviceConnected -> R.string.shizuku_hotspot_status_unavailable + state.hotspotEnabled && state.routingActive -> R.string.shizuku_hotspot_status_enabled + state.hotspotEnabled && state.routingState == ShizukuTetheringService.ROUTING_STATE_WAITING -> + R.string.shizuku_hotspot_status_waiting + state.hotspotEnabled -> R.string.shizuku_hotspot_status_enabled_direct + state.tetheringStateKnown && !state.routingActive && !state.vpnRunning -> + R.string.shizuku_routing_status_start_v2ray + state.tetheringStateKnown -> R.string.shizuku_hotspot_status_disabled + else -> R.string.shizuku_hotspot_status_unavailable + } + return TetheringControlState( + statusRes = statusRes, + enabled = state.serviceConnected && + state.operation == TetheringOperation.NONE && + (state.hotspotEnabled || + state.tetheringStateKnown && + (state.routingActive || state.vpnRunning)), + ) +} + +@Composable +internal fun TetheringScreen( + state: TetheringUiState, + onBackClick: () -> Unit, + onAction: (ShizukuAction) -> Unit, +) { + val routingAction = routingAction(state) + val hotspotAction = hotspotAction(state) + val routingSummary = stringResource(R.string.shizuku_routing_summary) + val usbStatus = stringResource(R.string.shizuku_usb_status_enabled) + val usbActive = state.activeTetheringTypes >= 0 && + state.activeTetheringTypes and tetheringTypeBit(ShizukuTetheringService.TETHERING_TYPE_USB) != 0 + val usbIpMode = state.ipMode(ShizukuTetheringService.TETHERING_TYPE_USB) + ?.let { stringResource(it.labelRes) } + val hotspotIpMode = state.ipMode(ShizukuTetheringService.TETHERING_TYPE_WIFI) + ?.let { stringResource(it.labelRes) } + val routingDetail = if (state.routingState == ShizukuTetheringService.ROUTING_STATE_ERROR) { + stringResource(R.string.shizuku_operation_failed) + } else { + state.routingDetail.ifBlank { routingSummary } + } + val routingDetails = buildString { + append(routingDetail) + if (usbActive) { + append("\n").append(usbStatus) + usbIpMode?.let { append(" · ").append(it) } + } + } + + Scaffold( + contentWindowInsets = ScaffoldDefaults.contentWindowInsets, + topBar = { + AppTopBar( + title = stringResource(R.string.title_tethering), + onBackClick = onBackClick, + isLoading = state.operation.isToggleInProgress, + ) + }, + ) { innerPadding -> + Column( + modifier = Modifier + .fillMaxSize() + .padding(innerPadding) + .verticalScroll(rememberScrollState()), + ) { + TetheringStatusSection( + iconRes = R.drawable.ic_device_hub_24dp, + title = stringResource(R.string.shizuku_status_title), + status = stringResource(state.shizukuStatus.statusRes), + details = state.shizukuStatus.detailsRes + ?.let { listOf(stringResource(it)) } + .orEmpty(), + ) + Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + TetheringActionButton( + text = stringResource(R.string.shizuku_request_permission), + enabled = state.shizukuStatus.canRequestPermission && + !state.operation.isToggleInProgress, + onClick = { onAction(ShizukuAction.RequestPermission) }, + modifier = Modifier.weight(1f), + ) + TetheringActionButton( + text = stringResource(R.string.shizuku_refresh_permission), + enabled = !state.operation.isToggleInProgress, + onClick = { onAction(ShizukuAction.Refresh) }, + modifier = Modifier.weight(1f), + ) + } + + Spacer(modifier = Modifier.height(8.dp)) + TetheringStatusSection( + iconRes = R.drawable.ic_routing_24dp, + title = stringResource(R.string.shizuku_routing_title), + status = stringResource(routingAction.statusRes), + details = listOf( + routingDetails, + stringResource(R.string.shizuku_routing_rules_disclaimer), + ), + checked = state.routingSessionEnabled, + toggleEnabled = routingAction.enabled, + onToggle = { onAction(ShizukuAction.ToggleRouting) }, + ) + + Spacer(modifier = Modifier.height(8.dp)) + TetheringStatusSection( + iconRes = R.drawable.ic_wifi_tethering_24dp, + title = stringResource(R.string.shizuku_hotspot_title), + status = stringResource(hotspotAction.statusRes), + details = listOfNotNull( + hotspotIpMode, + stringResource(R.string.shizuku_hotspot_summary), + ), + checked = state.hotspotEnabled, + toggleEnabled = hotspotAction.enabled, + onToggle = { onAction(ShizukuAction.ToggleHotspot) }, + ) + Spacer(modifier = Modifier.height(16.dp)) + } + } +} + +@Composable +private fun TetheringStatusSection( + iconRes: Int, + title: String, + status: String, + details: List, + checked: Boolean? = null, + toggleEnabled: Boolean = false, + onToggle: (() -> Unit)? = null, +) { + val toggleAction = onToggle?.takeIf { checked != null } + val toggleModifier = if (toggleAction != null && checked != null) { + Modifier + .toggleable( + value = checked, + enabled = toggleEnabled, + role = Role.Switch, + onValueChange = { toggleAction() }, + ) + .semantics(mergeDescendants = true) {} + } else { + Modifier + } + Column( + modifier = Modifier + .fillMaxWidth() + .then(toggleModifier) + .padding(16.dp), + ) { + Row(verticalAlignment = Alignment.CenterVertically) { + Icon( + painter = painterResource(iconRes), + contentDescription = null, + modifier = Modifier.size(24.dp), + tint = MaterialTheme.colorScheme.onSurface, + ) + Spacer(modifier = Modifier.width(16.dp)) + Text( + text = title, + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.weight(1f), + ) + if (checked != null && toggleAction != null) { + Switch( + checked = checked, + onCheckedChange = null, + modifier = Modifier + .scale(0.8f) + .clearAndSetSemantics {}, + colors = SwitchDefaults.colors( + checkedThumbColor = MaterialTheme.colorScheme.onSecondary, + checkedTrackColor = MaterialTheme.colorScheme.secondary, + ), + enabled = toggleEnabled, + ) + } + } + Column(modifier = Modifier.padding(start = 40.dp)) { + Spacer(modifier = Modifier.height(4.dp)) + Text( + text = status, + style = MaterialTheme.typography.bodyMedium, + fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.onSurface, + ) + details.forEach { detail -> + if (detail.isBlank()) return@forEach + Spacer(modifier = Modifier.height(4.dp)) + Text( + text = detail, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + } +} + +@Composable +private fun TetheringActionButton( + text: String, + enabled: Boolean, + onClick: () -> Unit, + modifier: Modifier = Modifier, +) { + OutlinedButton( + onClick = onClick, + enabled = enabled, + modifier = modifier.height(48.dp), + ) { + Text( + text = text, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } +} diff --git a/V2rayNG/app/src/main/java/com/v2ray/ang/ui/base/BaseComponentActivity.kt b/V2rayNG/app/src/main/java/com/v2ray/ang/ui/base/BaseComponentActivity.kt index 12e8c507372..541cc008e6c 100644 --- a/V2rayNG/app/src/main/java/com/v2ray/ang/ui/base/BaseComponentActivity.kt +++ b/V2rayNG/app/src/main/java/com/v2ray/ang/ui/base/BaseComponentActivity.kt @@ -23,4 +23,4 @@ abstract class BaseComponentActivity : AppCompatActivity() { @Composable protected abstract fun ScreenContent() -} \ No newline at end of file +} diff --git a/V2rayNG/app/src/main/java/com/v2ray/ang/ui/main/MainActivity.kt b/V2rayNG/app/src/main/java/com/v2ray/ang/ui/main/MainActivity.kt index 88cad8ded0f..e1a783791a2 100644 --- a/V2rayNG/app/src/main/java/com/v2ray/ang/ui/main/MainActivity.kt +++ b/V2rayNG/app/src/main/java/com/v2ray/ang/ui/main/MainActivity.kt @@ -26,6 +26,7 @@ import com.v2ray.ang.handler.SettingsChangeManager import com.v2ray.ang.handler.SettingsManager import com.v2ray.ang.handler.SubscriptionInfoParser import com.v2ray.ang.ui.AboutActivity +import com.v2ray.ang.ui.ShizukuActivity import com.v2ray.ang.ui.backup.BackupActivity import com.v2ray.ang.ui.base.HelperBaseComponentActivity import com.v2ray.ang.ui.checkupdate.CheckUpdateActivity @@ -155,6 +156,7 @@ class MainActivity : HelperBaseComponentActivity() { MainDestination.Logcat -> Intent(this, LogcatActivity::class.java) MainDestination.CheckUpdate -> Intent(this, CheckUpdateActivity::class.java) MainDestination.BackupRestore -> Intent(this, BackupActivity::class.java) + MainDestination.Tethering -> Intent(this, ShizukuActivity::class.java) MainDestination.About -> Intent(this, AboutActivity::class.java) MainDestination.Promotion -> { Utils.openUri( diff --git a/V2rayNG/app/src/main/java/com/v2ray/ang/ui/main/MainDrawer.kt b/V2rayNG/app/src/main/java/com/v2ray/ang/ui/main/MainDrawer.kt index 1bd2fadc6b0..a3d07546a9b 100644 --- a/V2rayNG/app/src/main/java/com/v2ray/ang/ui/main/MainDrawer.kt +++ b/V2rayNG/app/src/main/java/com/v2ray/ang/ui/main/MainDrawer.kt @@ -26,6 +26,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.BlendMode import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ColorFilter +import androidx.compose.ui.res.booleanResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp @@ -44,6 +45,7 @@ enum class MainDestination(@DrawableRes val iconRes: Int, @StringRes val labelRe Logcat(R.drawable.ic_logcat_24dp, R.string.title_logcat), CheckUpdate(R.drawable.ic_check_update_24dp, R.string.update_check_for_update), BackupRestore(R.drawable.ic_restore_24dp, R.string.title_configuration_backup_restore), + Tethering(R.drawable.ic_device_hub_24dp, R.string.title_tethering), About(R.drawable.ic_about_24dp, R.string.title_about) } @@ -60,12 +62,14 @@ private val drawerItems = primaryDrawerItems + listOf( MainDestination.Logcat, MainDestination.CheckUpdate, MainDestination.BackupRestore, + MainDestination.Tethering, MainDestination.About ) @Composable fun MainDrawerContent(drawerState: DrawerState, onNavigate: (MainDestination) -> Unit) { val drawerScrollState = rememberScrollState() + val tetheringEnabled = booleanResource(R.bool.shizuku_tethering_enabled) ModalDrawerSheet( drawerState = drawerState, @@ -107,16 +111,17 @@ fun MainDrawerContent(drawerState: DrawerState, onNavigate: (MainDestination) -> ) } } - drawerItems.forEachIndexed { index, item -> - if (index == primaryDrawerItems.size) AppDivider() - NavigationDrawerItem( - label = { Text(stringResource(item.labelRes)) }, - selected = false, - onClick = { onNavigate(item) }, - icon = { Icon(painterResource(item.iconRes), contentDescription = null) }, - modifier = Modifier.padding(NavigationDrawerItemDefaults.ItemPadding) - ) - } + drawerItems.filter { tetheringEnabled || it != MainDestination.Tethering } + .forEachIndexed { index, item -> + if (index == primaryDrawerItems.size) AppDivider() + NavigationDrawerItem( + label = { Text(stringResource(item.labelRes)) }, + selected = false, + onClick = { onNavigate(item) }, + icon = { Icon(painterResource(item.iconRes), contentDescription = null) }, + modifier = Modifier.padding(NavigationDrawerItemDefaults.ItemPadding) + ) + } } } } diff --git a/V2rayNG/app/src/main/res/drawable/ic_device_hub_24dp.xml b/V2rayNG/app/src/main/res/drawable/ic_device_hub_24dp.xml new file mode 100644 index 00000000000..ab7b76df83a --- /dev/null +++ b/V2rayNG/app/src/main/res/drawable/ic_device_hub_24dp.xml @@ -0,0 +1,9 @@ + + + diff --git a/V2rayNG/app/src/main/res/drawable/ic_wifi_tethering_24dp.xml b/V2rayNG/app/src/main/res/drawable/ic_wifi_tethering_24dp.xml new file mode 100644 index 00000000000..3187dbf8af9 --- /dev/null +++ b/V2rayNG/app/src/main/res/drawable/ic_wifi_tethering_24dp.xml @@ -0,0 +1,9 @@ + + + diff --git a/V2rayNG/app/src/main/res/values-ar/strings.xml b/V2rayNG/app/src/main/res/values-ar/strings.xml index 24c6d12414b..3e6a27f568f 100644 --- a/V2rayNG/app/src/main/res/values-ar/strings.xml +++ b/V2rayNG/app/src/main/res/values-ar/strings.xml @@ -469,6 +469,62 @@ النسخ الاحتياطي والاستعادة نسخ التكوين احتياطيًا استعادة التكوين + + + مشاركة الاتصال + حالة Shizuku + جارٍ التحقق… + Shizuku غير مثبّت + Shizuku لا يعمل + ثبّت Shizuku أو شغّله، ثم حدّث هذه الشاشة. + إصدار Shizuku غير مدعوم + حدّث Shizuku قبل استخدام هذه الميزة. + الإذن مطلوب + تم رفض الإذن + امنح v2rayNG إذن الوصول في مربع حوار أذونات Shizuku. + متصل ومصرّح له + طلب الإذن + تحديث + تم منح إذن Shizuku + تم رفض إذن Shizuku + فشلت عملية Shizuku + مشاركة الاتصال عبر v2rayNG + يوجّه نقطة اتصال Wi-Fi ومشاركة اتصال USB عبر VPN الذي يشغّله v2rayNG وقواعد توجيهه. يؤدي التعطيل إلى إيقاف مشاركة الاتصال المحمية أولًا لمنع تسرّب الاتصال المباشر. + ملاحظة: لا تُطبّق قواعد التوجيه حسب التطبيق أو العملية على الأجهزة المتصلة. + جارٍ التحقق من توجيه مشاركة الاتصال… + جارٍ إنشاء مسار الإرسال المحمي لمشاركة الاتصال… + التوجيه معطّل + جارٍ تشغيل مشاركة الاتصال عبر v2rayNG… + جارٍ إيقاف مشاركة الاتصال المحمية… + بانتظار تشغيل v2rayNG · حركة بيانات الأجهزة محجوبة + نشط · HEV TUN + نشط · Xray TUN الأصلي + خطأ في التوجيه + حالة التوجيه غير متاحة + شغّل v2rayNG في وضع VPN أولًا + تم تفعيل مشاركة الاتصال عبر v2rayNG + تم تعطيل مشاركة الاتصال عبر v2rayNG + فشل توجيه مشاركة الاتصال (الخطأ %1$d): %2$s + تعذرت قراءة إعدادات v2rayNG الحالية + مشاركة اتصال USB نشطة + IPv4 فقط + IPv4 وIPv6 + يتعذر تحديد إصدار IP + نقطة اتصال Wi-Fi + يؤدي تشغيل نقطة الاتصال من هنا إلى تفعيل مشاركة الاتصال عبر v2rayNG أولًا تلقائيًا. ويمكن لعنصر التحكم بالتوجيه أعلاه أيضًا حماية مشاركة اتصال USB التي تبدأها من إعدادات Android. + جارٍ التحقق من حالة نقطة الاتصال… + جارٍ الاتصال بالخدمة ذات الصلاحيات… + نقطة الاتصال مفعّلة · موجّهة عبر v2rayNG + نقطة الاتصال مفعّلة · توجيه v2rayNG متوقف + نقطة الاتصال مفعّلة · الإنترنت محجوب حتى إعادة تشغيل v2rayNG + نقطة الاتصال معطّلة + جارٍ تشغيل نقطة الاتصال… + جارٍ إيقاف نقطة الاتصال… + حالة نقطة الاتصال غير متاحة + تم تفعيل نقطة اتصال Wi-Fi + تم تعطيل نقطة اتصال Wi-Fi + فشلت عملية نقطة الاتصال (الخطأ %1$d) + أُلغي الربط أثناء تبديل Android للاتصال. انتظر قليلًا ثم حاول مرة أخرى. إصلاح بيانات ملفات التعريف حذف بيانات ملفات التعريف غير المستخدمة هل تريد حذف بيانات ملفات التعريف التي لم تعد مستخدمة في أي مجموعة؟ سيُحتفظ بملف التعريف المحدد وأي بيانات يتعذر التأكد من أنها غير مستخدمة. diff --git a/V2rayNG/app/src/main/res/values-az/strings.xml b/V2rayNG/app/src/main/res/values-az/strings.xml index 953a133830e..fbcbfcbe9b0 100644 --- a/V2rayNG/app/src/main/res/values-az/strings.xml +++ b/V2rayNG/app/src/main/res/values-az/strings.xml @@ -576,4 +576,59 @@ %1$s / %2$s Limitsiz + + İnternet paylaşımı + Shizuku vəziyyəti + Yoxlanılır… + Shizuku quraşdırılmayıb + Shizuku işləmir + Shizuku-nu quraşdırın və ya başladın, sonra bu ekranı yeniləyin. + Shizuku versiyası dəstəklənmir + Bu funksiyadan istifadə etməzdən əvvəl Shizuku-nu yeniləyin. + İcazə tələb olunur + İcazə rədd edildi + Shizuku icazə dialoqunda v2rayNG-yə giriş icazəsi verin. + Qoşulub və icazə verilib + İcazə istə + Yenilə + Shizuku icazəsi verildi + Shizuku icazəsi rədd edildi + Shizuku əməliyyatı uğursuz oldu + v2rayNG internet paylaşımı + Wi-Fi qaynar nöqtəsi və USB internet paylaşımını işləyən v2rayNG VPN-i və onun marşrutlaşdırma qaydaları vasitəsilə yönləndirir. Bunu söndürmək birbaşa bağlantı sızmasının qarşısını almaq üçün əvvəlcə qorunan internet paylaşımını dayandırır. + Qeyd: Qoşulmuş cihazlar üçün tətbiqə və prosesə əsaslanan marşrutlaşdırma qaydaları nəzərə alınmır. + İnternet paylaşımının marşrutlaşdırılması yoxlanılır… + İnternet paylaşımı üçün qorunan yuxarı bağlantı yaradılır… + Marşrutlaşdırma söndürülüb + v2rayNG internet paylaşımı başladılır… + Qorunan internet paylaşımı dayandırılır… + v2rayNG gözlənilir · cihazların trafiki bloklanıb + Aktiv · HEV TUN + Aktiv · Yerli Xray TUN + Marşrutlaşdırma xətası + Marşrutlaşdırma vəziyyəti əlçatan deyil + Əvvəlcə v2rayNG-ni VPN rejimində başladın + v2rayNG internet paylaşımı aktivləşdirildi + v2rayNG internet paylaşımı söndürüldü + İnternet paylaşımının marşrutlaşdırılması uğursuz oldu (xəta %1$d): %2$s + İşləyən v2rayNG konfiqurasiyasını oxumaq mümkün olmadı + USB internet paylaşımı aktivdir + Yalnız IPv4 + IPv4 + IPv6 + IP versiyası əlçatan deyil + Wi-Fi qaynar nöqtəsi + Qaynar nöqtəni buradan başlatmaq əvvəlcə v2rayNG internet paylaşımını avtomatik aktivləşdirir. Yuxarıdakı marşrutlaşdırma idarəsi Android parametrlərindən başladılan USB internet paylaşımını da qoruya bilər. + Qaynar nöqtənin vəziyyəti yoxlanılır… + İmtiyazlı xidmətə qoşulur… + Qaynar nöqtə aktivdir · v2rayNG vasitəsilə yönləndirilir + Qaynar nöqtə aktivdir · v2rayNG marşrutlaşdırması söndürülüb + Qaynar nöqtə aktivdir · v2rayNG yenidən başlayana qədər internet bloklanıb + Qaynar nöqtə söndürülüb + Qaynar nöqtə başladılır… + Qaynar nöqtə dayandırılır… + Qaynar nöqtənin vəziyyəti əlçatan deyil + Wi-Fi qaynar nöqtəsi aktivləşdirildi + Wi-Fi qaynar nöqtəsi söndürüldü + Qaynar nöqtə əməliyyatı uğursuz oldu (xəta %1$d) + Android bağlantıları dəyişdirərkən internet paylaşımı ləğv edildi. Bir az gözləyin, sonra yenidən cəhd edin. diff --git a/V2rayNG/app/src/main/res/values-bn/strings.xml b/V2rayNG/app/src/main/res/values-bn/strings.xml index 83ddd2ee21e..cbb82cf5e56 100644 --- a/V2rayNG/app/src/main/res/values-bn/strings.xml +++ b/V2rayNG/app/src/main/res/values-bn/strings.xml @@ -461,6 +461,62 @@ ব্যাকআপ ও পুনরুদ্ধার কনফিগারেশন ব্যাকআপ কনফিগারেশন পুনরুদ্ধার + + + ইন্টারনেট শেয়ারিং + Shizuku-এর অবস্থা + যাচাই করা হচ্ছে… + Shizuku ইনস্টল করা নেই + Shizuku চালু নেই + Shizuku ইনস্টল বা চালু করে এই স্ক্রিনটি রিফ্রেশ করুন। + Shizuku-এর এই সংস্করণ সমর্থিত নয় + ফিচারটি ব্যবহারের আগে Shizuku আপডেট করুন। + অনুমতি প্রয়োজন + অনুমতি প্রত্যাখ্যাত + Shizuku-এর অনুমতি ডায়ালগে v2rayNG-কে অ্যাক্সেস দিন। + সংযুক্ত এবং অনুমতিপ্রাপ্ত + অনুমতি চান + রিফ্রেশ + Shizuku-এর অনুমতি দেওয়া হয়েছে + Shizuku-এর অনুমতি প্রত্যাখ্যান করা হয়েছে + Shizuku অপারেশন ব্যর্থ হয়েছে + v2rayNG ইন্টারনেট শেয়ারিং + Wi-Fi হটস্পট ও USB টেথারিংয়ের ট্রাফিক চালু থাকা v2rayNG VPN এবং তার রাউটিং নিয়মের মধ্য দিয়ে পাঠায়। এটি বন্ধ করলে সরাসরি সংযোগ ফাঁস ঠেকাতে আগে সুরক্ষিত টেথারিং বন্ধ করা হয়। + দ্রষ্টব্য: সংযুক্ত ডিভাইসগুলোর ক্ষেত্রে অ্যাপভিত্তিক ও প্রসেসভিত্তিক রাউটিং নিয়ম প্রয়োগ হয় না। + টেথারিং রাউটিং যাচাই করা হচ্ছে… + সুরক্ষিত টেথারিং আপস্ট্রিম তৈরি করা হচ্ছে… + রাউটিং বন্ধ + v2rayNG টেথারিং চালু হচ্ছে… + সুরক্ষিত টেথারিং বন্ধ হচ্ছে… + v2rayNG চালুর অপেক্ষায় · ডিভাইসের ট্র্যাফিক বন্ধ + সক্রিয় · HEV TUN + সক্রিয় · নেটিভ Xray TUN + রাউটিং ত্রুটি + রাউটিংয়ের অবস্থা পাওয়া যাচ্ছে না + আগে VPN মোডে v2rayNG চালু করুন + v2rayNG টেথারিং চালু হয়েছে + v2rayNG টেথারিং বন্ধ হয়েছে + টেথারিং রাউটিং ব্যর্থ হয়েছে (ত্রুটি %1$d): %2$s + চালু থাকা v2rayNG-এর কনফিগারেশন পড়া যায়নি + USB টেথারিং সক্রিয় + শুধু IPv4 + IPv4 + IPv6 + IP সংস্করণ জানা যায়নি + Wi-Fi হটস্পট + এখান থেকে হটস্পট চালু করলে আগে স্বয়ংক্রিয়ভাবে v2rayNG টেথারিং চালু হয়। ওপরের রাউটিং নিয়ন্ত্রণ Android সেটিংস থেকে চালু করা USB টেথারিংকেও সুরক্ষিত করতে পারে। + হটস্পটের অবস্থা যাচাই করা হচ্ছে… + বিশেষ অনুমতিপ্রাপ্ত সার্ভিসে সংযোগ করা হচ্ছে… + হটস্পট চালু · v2rayNG-এর মাধ্যমে রাউট করা হচ্ছে + হটস্পট চালু · v2rayNG রাউটিং বন্ধ + হটস্পট চালু · v2rayNG আবার চালু না হওয়া পর্যন্ত ইন্টারনেট বন্ধ + হটস্পট বন্ধ + হটস্পট চালু হচ্ছে… + হটস্পট বন্ধ হচ্ছে… + হটস্পটের অবস্থা পাওয়া যাচ্ছে না + Wi-Fi হটস্পট চালু হয়েছে + Wi-Fi হটস্পট বন্ধ হয়েছে + হটস্পট অপারেশন ব্যর্থ হয়েছে (ত্রুটি %1$d) + Android সংযোগ পরিবর্তন করার সময় টেথারিং বাতিল হয়েছে। একটু অপেক্ষা করে আবার চেষ্টা করুন। প্রোফাইল স্টোরেজ মেরামত করুন অব্যবহৃত প্রোফাইল ডেটা মুছে ফেলুন কোনো গ্রুপে আর ব্যবহৃত হয় না এমন প্রোফাইল ডেটা মুছে ফেলবেন? নির্বাচিত প্রোফাইল এবং নিরাপদে অব্যবহৃত বলে নির্ধারণ করা যায় না এমন ডেটা রাখা হবে। diff --git a/V2rayNG/app/src/main/res/values-bqi-rIR/strings.xml b/V2rayNG/app/src/main/res/values-bqi-rIR/strings.xml index b2252d5b79a..780429ae8c9 100644 --- a/V2rayNG/app/src/main/res/values-bqi-rIR/strings.xml +++ b/V2rayNG/app/src/main/res/values-bqi-rIR/strings.xml @@ -461,6 +461,62 @@ لادراری گرؽڌن & وورگندن لادراری گرؽڌن ز کانفیگ وورگندن کانفیگ + + + تترینگ + وازیت Shizuku + من وارسۊوی… + Shizuku نئسب نوابیڌه + Shizuku کار نکونه + Shizuku ن نئسب یا راه بندازین، پس ای سفه ن ورۊ کۊنین. + ای ورژن Shizuku پشت‌یبۊوی نیابۊ + پؽش ز و کار گرؽڌن ای ویژیی، Shizuku ن ورۊ کۊنین. + موجوز لازمه + موجوز رت وابی + من پؽغام موجوز Shizuku، دسرسی v2rayNG ن بدین. + منپیز وابیڌه وو موجوز داره + گرؽڌن موجوز + ورۊ کردن + موجوز Shizuku گرؽڌه وابی + موجوز Shizuku رت وابی + کار Shizuku نامووفق وابی + تترینگ v2rayNG + ترافیک هات‌اسپات وای‌فای وو تترینگ USB ن ز VPN هیم سکو کارِ v2rayNG وو قانووای تور جوستن اوگذرونه. وا خاموش کردن، ٱول تترینگ ٱمن ن واداره تا ترافیک موستقیم نشت نکنه. + نکته: قانووای تور جوستن هر برنومه وو پردازش سی دسگایل منپیز وابیڌه و کار نرن. + من وارسۊوی تور جوستن تترینگ… + من درست کردن راه بالادسی ٱمن تترینگ… + تور جوستن خاموشه + تترینگ v2rayNG راه و افته… + تترینگ ٱمن واداره… + من وارستن راه افتادن v2rayNG · ترافیک دسگاها بسته‌س + کار کنه · HEV TUN + کار کنه · Xray TUN بۊمی + خوتا من تور جوستن + وازیت تور جوستن من دسرس نی + ٱول v2rayNG ن من هالت VPN راه بندازین + تترینگ v2rayNG راه و افتا + تترینگ v2rayNG واداشت وابی + تور جوستن تترینگ نامووفق وابی (خوتا %1$d): %2$s + کانفیگ v2rayNG هیم سکو کار خونڌه نوابی + تترینگ USB کار کنه + فقط IPv4 + IPv4 + IPv6 + نسخه IP دیار نی + هات‌اسپات وای‌فای + وا راه وندن هات‌اسپات ز ئیجا، ٱول تترینگ v2rayNG خوتکار راه و افته. کونترول تور جوستن بالا هنی تترینگ USB راه افتا ز سامووای Android ن ٱمن کنه. + من وارسۊوی وازیت هات‌اسپات… + من منپیز وابیڌن وا سرویس موجوزدار… + هات‌اسپات راه افتا · ز v2rayNG تور جۊری ابۊ + هات‌اسپات راه افتا · تور جوستن v2rayNG خاموشه + هات‌اسپات راه افتا · تا v2rayNG دوواره راه نیفته اینترنت بسته‌س + هات‌اسپات خاموشه + هات‌اسپات راه و افته… + هات‌اسپات واداره… + وازیت هات‌اسپات من دسرس نی + هات‌اسپات وای‌فای راه افتا + هات‌اسپات وای‌فای واداشت وابی + کار هات‌اسپات نامووفق وابی (خوتا %1$d) + وختی Android اتصال ن عوض اکرد، تترینگ لغو وابی. یه کم وارِسین و دوواره امتحان کنین. ترمیم جاگه زفت کردن پوروفایلا پاک کردن داده یل پوروفایلایی ک دی و کار گرؽڌه نؽبۊن داده یل پوروفایلایی ک دی من هیچ بونکۊیی و کار گرؽڌه نؽبۊن پاک ابۊن، هنی هم اخۊی پاکسووݩ کۊنی؟ پوروفایل پسند وابیڌه وو داده یلی ک نتری وا موتمعنی بفهمی دی و کار گرؽڌه نؽبۊن پاک نؽبۊن. @@ -575,4 +631,4 @@ واز کردن صفحه اطلاعات اشتراک بی‌حد - \ No newline at end of file + diff --git a/V2rayNG/app/src/main/res/values-fa/strings.xml b/V2rayNG/app/src/main/res/values-fa/strings.xml index dce046e9156..4022325bc18 100644 --- a/V2rayNG/app/src/main/res/values-fa/strings.xml +++ b/V2rayNG/app/src/main/res/values-fa/strings.xml @@ -461,6 +461,62 @@ پشتیبان‌گیری و بازیابی پشتیبان گیری از پیکربندی بازیابی پیکربندی + + + اشتراک‌گذاری اینترنت + وضعیت Shizuku + در حال بررسی… + Shizuku نصب نشده است + Shizuku در حال اجرا نیست + Shizuku را نصب یا اجرا کنید، سپس این صفحه را تازه‌سازی کنید. + نسخه Shizuku پشتیبانی نمی‌شود + پیش از استفاده از این قابلیت، Shizuku را به‌روزرسانی کنید. + مجوز لازم است + مجوز رد شده است + در پنجره مجوز Shizuku، دسترسی v2rayNG را تأیید کنید. + متصل و مجاز + درخواست مجوز + تازه‌سازی + مجوز Shizuku داده شد + مجوز Shizuku رد شد + عملیات Shizuku ناموفق بود + اشتراک‌گذاری اینترنت با v2rayNG + ترافیک نقطه اتصال Wi-Fi و اتصال اشتراکی USB را از VPN فعال v2rayNG و قوانین مسیریابی آن عبور می‌دهد. با غیرفعال کردن این گزینه، برای جلوگیری از نشت اتصال مستقیم ابتدا اشتراک‌گذاری محافظت‌شده متوقف می‌شود. + توجه: قوانین مسیریابی بر اساس برنامه یا فرایند برای دستگاه‌های متصل اعمال نمی‌شوند. + در حال بررسی مسیریابی اتصال اشتراکی… + در حال ساخت مسیر بالادستی محافظت‌شده… + مسیریابی غیرفعال است + در حال راه‌اندازی اشتراک‌گذاری v2rayNG… + در حال توقف اشتراک‌گذاری محافظت‌شده… + در انتظار راه‌اندازی v2rayNG · ترافیک دستگاه‌ها مسدود است + فعال · HEV TUN + فعال · Xray TUN بومی + خطای مسیریابی + وضعیت مسیریابی در دسترس نیست + ابتدا v2rayNG را در حالت VPN اجرا کنید + اشتراک‌گذاری v2rayNG فعال شد + اشتراک‌گذاری v2rayNG غیرفعال شد + مسیریابی اتصال اشتراکی ناموفق بود (خطای %1$d): %2$s + خواندن پیکربندی در حال اجرای v2rayNG ممکن نیست + اتصال اشتراکی USB فعال است + فقط IPv4 + IPv4 + IPv6 + نسخه IP قابل تشخیص نیست + نقطه اتصال Wi-Fi + با روشن کردن نقطه اتصال از اینجا، ابتدا اشتراک‌گذاری v2rayNG به‌طور خودکار فعال می‌شود. کنترل مسیریابی بالا می‌تواند از اتصال اشتراکی USB که در تنظیمات Android روشن شده نیز محافظت کند. + در حال بررسی وضعیت نقطه اتصال… + در حال اتصال به سرویس دارای دسترسی ویژه… + نقطه اتصال روشن است · مسیریابی از v2rayNG + نقطه اتصال روشن است · مسیریابی v2rayNG خاموش است + نقطه اتصال روشن است · تا راه‌اندازی مجدد v2rayNG اینترنت مسدود است + نقطه اتصال خاموش است + در حال روشن کردن نقطه اتصال… + در حال خاموش کردن نقطه اتصال… + وضعیت نقطه اتصال در دسترس نیست + نقطه اتصال Wi-Fi روشن شد + نقطه اتصال Wi-Fi خاموش شد + عملیات نقطه اتصال ناموفق بود (خطای %1$d) + هنگام تغییر اتصال توسط Android، تترینگ لغو شد. کمی صبر کنید و دوباره تلاش کنید. ترمیم فضای ذخیره‌سازی پروفایل‌ها حذف داده‌های پروفایل بلااستفاده داده‌های پروفایلی که دیگر در هیچ گروهی استفاده نمی‌شوند حذف شوند؟ پروفایل انتخاب‌شده و داده‌هایی که نمی‌توان با اطمینان بلااستفاده بودنشان را تشخیص داد حفظ خواهند شد. diff --git a/V2rayNG/app/src/main/res/values-ru/strings.xml b/V2rayNG/app/src/main/res/values-ru/strings.xml index ffe31f06d76..9dd03339dcf 100644 --- a/V2rayNG/app/src/main/res/values-ru/strings.xml +++ b/V2rayNG/app/src/main/res/values-ru/strings.xml @@ -465,6 +465,62 @@ Резервирование и восстановление Резервирование конфигурации Восстановление конфигурации + + + Раздача интернета + Состояние Shizuku + Проверка… + Shizuku не установлен + Shizuku не запущен + Установите или запустите Shizuku, затем обновите эту страницу. + Версия Shizuku не поддерживается + Обновите Shizuku перед использованием этой функции. + Требуется разрешение + В разрешении отказано + Предоставьте v2rayNG доступ в диалоге разрешений Shizuku. + Подключено, доступ разрешён + Запросить разрешение + Обновить + Разрешение Shizuku предоставлено + В разрешении Shizuku отказано + Операция Shizuku не выполнена + Раздача через v2rayNG + Направляет трафик точки доступа Wi-Fi и USB-модема через работающий VPN v2rayNG с учётом его правил маршрутизации. При отключении сначала прекращается защищённая раздача, чтобы исключить утечку трафика через прямое подключение. + Примечание: правила маршрутизации по приложениям и процессам не применяются к подключённым устройствам. + Проверка маршрутизации раздачи… + Создание защищённого исходящего канала для раздачи… + Маршрутизация отключена + Запуск раздачи через v2rayNG… + Остановка защищённой раздачи… + Ожидание запуска v2rayNG · трафик устройств заблокирован + Активно · HEV TUN + Активно · нативный Xray TUN + Ошибка маршрутизации + Состояние маршрутизации недоступно + Сначала запустите v2rayNG в режиме VPN + Раздача через v2rayNG включена + Раздача через v2rayNG отключена + Не удалось настроить маршрутизацию раздачи (ошибка %1$d): %2$s + Не удалось прочитать текущую конфигурацию v2rayNG + USB-модем активен + Только IPv4 + IPv4 + IPv6 + Версию IP определить не удалось + Точка доступа Wi-Fi + При включении точки доступа здесь сначала автоматически включается раздача через v2rayNG. Маршрутизация выше также защищает USB-модем, включённый в настройках Android. + Проверка состояния точки доступа… + Подключение к привилегированной службе… + Точка доступа включена · трафик идёт через v2rayNG + Точка доступа включена · маршрутизация v2rayNG отключена + Точка доступа включена · интернет заблокирован до запуска v2rayNG + Точка доступа отключена + Включение точки доступа… + Отключение точки доступа… + Состояние точки доступа недоступно + Точка доступа Wi-Fi включена + Точка доступа Wi-Fi отключена + Не удалось выполнить операцию с точкой доступа (ошибка %1$d) + Раздача была отменена, пока Android переключал подключение. Немного подождите и попробуйте ещё раз. Исправить хранилище профилей Удалить данные неиспользуемых профилей Удалить данные профилей, которые больше не используются ни в одной группе? Выбранный профиль и данные, которые нельзя с уверенностью отнести к неиспользуемым, будут сохранены. diff --git a/V2rayNG/app/src/main/res/values-v33/bools.xml b/V2rayNG/app/src/main/res/values-v33/bools.xml new file mode 100644 index 00000000000..5488d0feb96 --- /dev/null +++ b/V2rayNG/app/src/main/res/values-v33/bools.xml @@ -0,0 +1,4 @@ + + + true + diff --git a/V2rayNG/app/src/main/res/values-vi/strings.xml b/V2rayNG/app/src/main/res/values-vi/strings.xml index 1f88e683519..03df3641df2 100644 --- a/V2rayNG/app/src/main/res/values-vi/strings.xml +++ b/V2rayNG/app/src/main/res/values-vi/strings.xml @@ -459,6 +459,62 @@ Sao lưu & khôi phục Sao lưu cấu hình Khôi phục cấu hình + + + Chia sẻ kết nối + Trạng thái Shizuku + Đang kiểm tra… + Chưa cài đặt Shizuku + Shizuku chưa chạy + Hãy cài đặt hoặc khởi động Shizuku, rồi làm mới màn hình này. + Phiên bản Shizuku không được hỗ trợ + Hãy cập nhật Shizuku trước khi dùng tính năng này. + Cần cấp quyền + Quyền đã bị từ chối + Cho phép v2rayNG truy cập trong hộp thoại cấp quyền của Shizuku. + Đã kết nối và cấp quyền + Yêu cầu cấp quyền + Làm mới + Đã cấp quyền Shizuku + Đã từ chối quyền Shizuku + Thao tác Shizuku không thành công + Chia sẻ kết nối qua v2rayNG + Định tuyến điểm phát sóng Wi-Fi và chia sẻ kết nối qua USB thông qua VPN v2rayNG đang chạy cùng các quy tắc định tuyến của VPN. Khi tắt, kết nối chia sẻ được bảo vệ sẽ dừng trước để tránh rò rỉ qua kết nối trực tiếp. + Lưu ý: Các quy tắc định tuyến theo ứng dụng và theo tiến trình không áp dụng cho thiết bị được kết nối. + Đang kiểm tra định tuyến kết nối chia sẻ… + Đang tạo đường truyền nguồn được bảo vệ… + Định tuyến đang tắt + Đang bật chia sẻ kết nối qua v2rayNG… + Đang dừng kết nối chia sẻ được bảo vệ… + Đang chờ v2rayNG khởi động · lưu lượng từ thiết bị bị chặn + Đang hoạt động · HEV TUN + Đang hoạt động · Xray TUN gốc + Lỗi định tuyến + Không thể xác định trạng thái định tuyến + Hãy khởi động v2rayNG ở chế độ VPN trước + Đã bật chia sẻ kết nối qua v2rayNG + Đã tắt chia sẻ kết nối qua v2rayNG + Định tuyến kết nối chia sẻ không thành công (lỗi %1$d): %2$s + Không thể đọc cấu hình v2rayNG đang chạy + Chia sẻ kết nối qua USB đang hoạt động + Chỉ IPv4 + IPv4 + IPv6 + Không xác định được phiên bản IP + Điểm phát sóng Wi-Fi + Khi bật điểm phát sóng tại đây, chia sẻ kết nối qua v2rayNG sẽ tự động được bật trước. Tùy chọn định tuyến phía trên cũng có thể bảo vệ kết nối USB được bật trong phần cài đặt Android. + Đang kiểm tra trạng thái điểm phát sóng… + Đang kết nối với dịch vụ đặc quyền… + Điểm phát sóng đang bật · định tuyến qua v2rayNG + Điểm phát sóng đang bật · định tuyến v2rayNG đang tắt + Điểm phát sóng đang bật · Internet bị chặn cho đến khi v2rayNG khởi động lại + Điểm phát sóng đang tắt + Đang bật điểm phát sóng… + Đang tắt điểm phát sóng… + Không thể xác định trạng thái điểm phát sóng + Đã bật điểm phát sóng Wi-Fi + Đã tắt điểm phát sóng Wi-Fi + Thao tác với điểm phát sóng không thành công (lỗi %1$d) + Chia sẻ kết nối đã bị hủy trong lúc Android chuyển đổi kết nối. Hãy đợi một lát rồi thử lại. Sửa dữ liệu cấu hình Xóa dữ liệu cấu hình không còn được sử dụng Xóa dữ liệu cấu hình không còn được nhóm nào sử dụng? Cấu hình đang chọn và dữ liệu không thể xác định chắc chắn là không còn được sử dụng sẽ được giữ lại. diff --git a/V2rayNG/app/src/main/res/values-zh-rCN/strings.xml b/V2rayNG/app/src/main/res/values-zh-rCN/strings.xml index 19d20a05e55..502217d8318 100644 --- a/V2rayNG/app/src/main/res/values-zh-rCN/strings.xml +++ b/V2rayNG/app/src/main/res/values-zh-rCN/strings.xml @@ -459,6 +459,62 @@ 备份 & 还原 备份配置 还原配置 + + + 网络共享 + Shizuku 状态 + 正在检查… + 未安装 Shizuku + Shizuku 未运行 + 请安装或启动 Shizuku,然后刷新此页面。 + 不支持此 Shizuku 版本 + 请先更新 Shizuku,再使用此功能。 + 需要授权 + 授权已拒绝 + 请在 Shizuku 授权对话框中允许 v2rayNG 访问。 + 已连接并授权 + 请求授权 + 刷新 + 已授予 Shizuku 权限 + 已拒绝 Shizuku 权限 + Shizuku 操作失败 + v2rayNG 网络共享 + 将 Wi-Fi 热点和 USB 网络共享的流量转发至当前运行的 v2rayNG VPN,并应用其路由规则。关闭此功能时会先停止受保护的网络共享,以防流量通过直连泄漏。 + 注意:按应用和按进程的路由规则不适用于已连接的设备。 + 正在检查网络共享路由… + 正在创建受保护的网络共享上游… + 路由已关闭 + 正在启动 v2rayNG 网络共享… + 正在停止受保护的网络共享… + 等待 v2rayNG 启动 · 已阻止接入设备的流量 + 已启用 · HEV TUN + 已启用 · 原生 Xray TUN + 路由错误 + 无法获取路由状态 + 请先以 VPN 模式启动 v2rayNG + v2rayNG 网络共享已启用 + v2rayNG 网络共享已关闭 + 网络共享路由失败(错误 %1$d):%2$s + 无法读取当前运行的 v2rayNG 配置 + USB 网络共享已启用 + 仅 IPv4 + IPv4 + IPv6 + 无法确定 IP 版本 + Wi-Fi 热点 + 从此处开启热点时,会先自动启用 v2rayNG 网络共享。上方的路由控制也可以保护从 Android 设置中开启的 USB 网络共享。 + 正在检查热点状态… + 正在连接特权服务… + 热点已开启 · 流量经 v2rayNG 转发 + 热点已开启 · v2rayNG 路由已关闭 + 热点已开启 · v2rayNG 重启前禁止联网 + 热点已关闭 + 正在开启热点… + 正在关闭热点… + 无法获取热点状态 + Wi-Fi 热点已开启 + Wi-Fi 热点已关闭 + 热点操作失败(错误 %1$d) + Android 切换连接时已取消网络共享。请稍等片刻后重试。 修复配置存储 删除未使用的配置数据 要删除已不再被任何分组使用的配置数据吗?当前选中的配置以及无法安全判定为未使用的数据将会保留。 diff --git a/V2rayNG/app/src/main/res/values-zh-rTW/strings.xml b/V2rayNG/app/src/main/res/values-zh-rTW/strings.xml index 3bb3f41f969..9ce9a0acbdc 100644 --- a/V2rayNG/app/src/main/res/values-zh-rTW/strings.xml +++ b/V2rayNG/app/src/main/res/values-zh-rTW/strings.xml @@ -459,6 +459,62 @@ 備份與還原 備份設定 還原設定 + + + 網路共用 + Shizuku 狀態 + 正在檢查… + 尚未安裝 Shizuku + Shizuku 未執行 + 請安裝或啟動 Shizuku,然後重新整理此頁面。 + 不支援此 Shizuku 版本 + 請先更新 Shizuku,再使用此功能。 + 需要授權 + 授權遭拒 + 請在 Shizuku 授權對話框中允許 v2rayNG 存取。 + 已連線並授權 + 要求授權 + 重新整理 + 已授予 Shizuku 權限 + 已拒絕 Shizuku 權限 + Shizuku 操作失敗 + v2rayNG 網路共用 + 將 Wi-Fi 熱點和 USB 網路共用的流量轉送至目前執行中的 v2rayNG VPN,並套用其路由規則。關閉此功能時會先停止受保護的網路共用,以免流量透過直接連線洩漏。 + 注意:依應用程式和依處理程序的路由規則不適用於已連線的裝置。 + 正在檢查網路共用路由… + 正在建立受保護的網路共用上游… + 路由已關閉 + 正在啟動 v2rayNG 網路共用… + 正在停止受保護的網路共用… + 等待 v2rayNG 啟動 · 已阻止連線裝置的流量 + 已啟用 · HEV TUN + 已啟用 · 原生 Xray TUN + 路由錯誤 + 無法取得路由狀態 + 請先以 VPN 模式啟動 v2rayNG + v2rayNG 網路共用已啟用 + v2rayNG 網路共用已關閉 + 網路共用路由失敗(錯誤 %1$d):%2$s + 無法讀取目前執行中的 v2rayNG 設定 + USB 網路共用已啟用 + 僅 IPv4 + IPv4 + IPv6 + 無法判斷 IP 版本 + Wi-Fi 熱點 + 從這裡開啟熱點時,會先自動啟用 v2rayNG 網路共用。上方的路由控制也能保護從 Android 設定中開啟的 USB 網路共用。 + 正在檢查熱點狀態… + 正在連線至特殊權限服務… + 熱點已開啟 · 流量經 v2rayNG 轉送 + 熱點已開啟 · v2rayNG 路由已關閉 + 熱點已開啟 · v2rayNG 重新啟動前停止網路連線 + 熱點已關閉 + 正在開啟熱點… + 正在關閉熱點… + 無法取得熱點狀態 + Wi-Fi 熱點已開啟 + Wi-Fi 熱點已關閉 + 熱點操作失敗(錯誤 %1$d) + Android 切換連線時已取消網路共用。請稍候片刻再試。 修復設定檔儲存空間 刪除未使用的設定檔資料 要刪除已不再由任何群組使用的設定檔資料嗎?目前選取的設定檔,以及無法安全判定為未使用的資料,都會予以保留。 diff --git a/V2rayNG/app/src/main/res/values/bools.xml b/V2rayNG/app/src/main/res/values/bools.xml new file mode 100644 index 00000000000..92ef1685479 --- /dev/null +++ b/V2rayNG/app/src/main/res/values/bools.xml @@ -0,0 +1,4 @@ + + + false + diff --git a/V2rayNG/app/src/main/res/values/strings.xml b/V2rayNG/app/src/main/res/values/strings.xml index 99e8afd1849..f56ecfee2d7 100644 --- a/V2rayNG/app/src/main/res/values/strings.xml +++ b/V2rayNG/app/src/main/res/values/strings.xml @@ -461,6 +461,62 @@ Backup & Restore Backup config Restore config + + + Tethering + Shizuku status + Checking… + Shizuku is not installed + Shizuku is not running + Install or start Shizuku, then refresh this screen. + Unsupported Shizuku version + Update Shizuku before using this feature. + Permission required + Permission denied + Grant v2rayNG access in the Shizuku permission dialog. + Connected and permitted + Request permission + Refresh + Shizuku permission granted + Shizuku permission was denied + Shizuku operation failed + v2rayNG tethering + Routes Wi-Fi hotspot and USB tethering through the running v2rayNG VPN and its routing rules. Disabling this stops protected tethering first to prevent a direct-connection leak. + Note: Per-app and process-based routing rules are ignored for connected devices. + Checking tethering routing… + Creating the protected tethering upstream… + Routing disabled + Starting v2rayNG tethering… + Stopping protected tethering… + Waiting for v2rayNG · device traffic blocked + Active · HEV TUN + Active · Native Xray TUN + Routing error + Routing status unavailable + Start v2rayNG in VPN mode first + v2rayNG tethering enabled + v2rayNG tethering disabled + Tethering routing failed (error %1$d): %2$s + Unable to read the running v2rayNG configuration + USB tethering is active + IPv4 only + IPv4 + IPv6 + IP version unavailable + Wi-Fi hotspot + Starting the hotspot here automatically enables v2rayNG tethering first. The routing control above can also protect USB tethering started from Android settings. + Checking hotspot status… + Connecting to the privileged service… + Hotspot enabled · routed through v2rayNG + Hotspot enabled · v2rayNG routing is off + Hotspot enabled · Internet blocked until v2rayNG restarts + Hotspot disabled + Starting hotspot… + Stopping hotspot… + Hotspot status unavailable + Wi-Fi hotspot enabled + Wi-Fi hotspot disabled + Hotspot operation failed (error %1$d) + Tethering was cancelled while Android was switching connections. Wait a moment, then try again. Repair profile storage Remove unused profile data Delete profile data that is no longer used by any group? Selected profiles and data that cannot be safely classified will be kept. diff --git a/V2rayNG/app/src/test/java/com/v2ray/ang/service/CoreTeardownDecisionTest.kt b/V2rayNG/app/src/test/java/com/v2ray/ang/service/CoreTeardownDecisionTest.kt new file mode 100644 index 00000000000..d353982d195 --- /dev/null +++ b/V2rayNG/app/src/test/java/com/v2ray/ang/service/CoreTeardownDecisionTest.kt @@ -0,0 +1,16 @@ +package com.v2ray.ang.service + +import com.v2ray.ang.core.shouldScheduleCoreTeardown +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test + +class CoreTeardownDecisionTest { + + @Test + fun schedulesExactlyOneTeardownForARunningCore() { + assertFalse(shouldScheduleCoreTeardown(coreRunning = false, teardownActive = false)) + assertTrue(shouldScheduleCoreTeardown(coreRunning = true, teardownActive = false)) + assertFalse(shouldScheduleCoreTeardown(coreRunning = true, teardownActive = true)) + } +} diff --git a/V2rayNG/app/src/test/java/com/v2ray/ang/service/HevTunnelConfigTest.kt b/V2rayNG/app/src/test/java/com/v2ray/ang/service/HevTunnelConfigTest.kt new file mode 100644 index 00000000000..13007355e95 --- /dev/null +++ b/V2rayNG/app/src/test/java/com/v2ray/ang/service/HevTunnelConfigTest.kt @@ -0,0 +1,54 @@ +package com.v2ray.ang.service + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test + +class HevTunnelConfigTest { + + @Test + fun parsesNonBlankTimeoutsWithUpstreamDefaults() { + assertEquals(Pair(300, 60), HevTunnelSettings.parseTimeouts(null)) + assertEquals(Pair(5, 7), HevTunnelSettings.parseTimeouts("5, 7")) + assertEquals(Pair(300, 9), HevTunnelSettings.parseTimeouts("bad, 9")) + assertEquals(Pair(9, 60), HevTunnelSettings.parseTimeouts(", 9")) + assertEquals(Pair(300, 60), HevTunnelSettings.parseTimeouts(" , ")) + } + + @Test + fun buildsEscapedYamlForBothTunnelModes() { + val yaml = HevTunnelConfig.build( + HevTunnelParameters( + mtu = 1500, + ipv4 = "10.0.0.1", + ipv6 = "fc00::1", + socksAddress = "127.0.0.1", + socksPort = 10808, + socksUsername = "o'connor", + socksPassword = "p'ass", + settings = HevTunnelSettings(5, 7, "w'arn"), + ), + ) + + assertTrue(yaml.contains("ipv4: '10.0.0.1'")) + assertTrue(yaml.contains("ipv6: 'fc00::1'")) + assertTrue(yaml.contains("username: 'o''connor'")) + assertTrue(yaml.contains("password: 'p''ass'")) + assertTrue(yaml.contains("tcp-read-write-timeout: 5000")) + assertTrue(yaml.contains("udp-read-write-timeout: 7000")) + assertTrue(yaml.contains("log-level: 'w''arn'")) + + val ipv4Only = HevTunnelConfig.build( + HevTunnelParameters( + mtu = 1500, + ipv4 = "10.0.0.1", + socksAddress = "127.0.0.1", + socksPort = 10808, + settings = HevTunnelSettings(5, 7, "warn"), + ), + ) + assertFalse(ipv4Only.contains("ipv6:")) + assertFalse(ipv4Only.contains("username:")) + } +} diff --git a/V2rayNG/app/src/test/java/com/v2ray/ang/shizuku/HotspotRoutingConfigTest.kt b/V2rayNG/app/src/test/java/com/v2ray/ang/shizuku/HotspotRoutingConfigTest.kt new file mode 100644 index 00000000000..725f55af972 --- /dev/null +++ b/V2rayNG/app/src/test/java/com/v2ray/ang/shizuku/HotspotRoutingConfigTest.kt @@ -0,0 +1,99 @@ +package com.v2ray.ang.shizuku + +import com.google.gson.JsonParser +import com.v2ray.ang.AppConfig +import com.v2ray.ang.dto.HotspotRoutingSnapshot +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Test + +class HotspotRoutingConfigTest { + + @Test + fun oldSnapshotsWithoutLaunchIdentityCannotAuthorizeAnEngine() { + val snapshot = HotspotRoutingSnapshot(running = true, vpnMode = true) + assertThrows(IllegalArgumentException::class.java) { HotspotRoutingConfig.parametersFromSnapshot(snapshot) } + } + + @Test + fun nativeEngineKeepsOnlyTheTunInbound() { + val config = HotspotRoutingConfig.engineContentFromSnapshot( + HotspotRoutingSnapshot( + running = true, + vpnMode = true, + profileName = "Native", + ), + """ + { + "inbounds": [ + {"tag": "socks", "protocol": "socks"}, + {"tag": "tun", "protocol": "tun"} + ], + "outbounds": [{"tag": "proxy", "protocol": "freedom"}], + "dns": {"servers": [ + {"address": "192.0.2.53", "domains": ["domain:example.com"], "finalQuery": true}, + "https://dns.example/dns-query" + ]}, + "routing": {"domainStrategy": "AsIs"} + } + """.trimIndent(), + ) + + val root = JsonParser.parseString(config).asJsonObject + val inbounds = root.getAsJsonArray("inbounds") + assertEquals(1, inbounds.size()) + assertEquals("tun", inbounds[0].asJsonObject.get("protocol").asString) + val dnsServers = root.getAsJsonObject("dns").getAsJsonArray("servers") + assertEquals(2, dnsServers.size()) + assertEquals("192.0.2.53", dnsServers[0].asJsonObject.get("address").asString) + assertTrue(dnsServers[0].asJsonObject.get("finalQuery").asBoolean) + assertEquals("https://dns.example/dns-query", dnsServers[1].asString) + assertTrue(root.has("outbounds")) + assertTrue(root.has("routing")) + } + + @Test + fun hevEngineUsesTheRunningSnapshotSettings() { + val config = HotspotRoutingConfig.engineContentFromSnapshot( + HotspotRoutingSnapshot( + running = true, + vpnMode = true, + profileName = "HEV", + useHev = true, + socksPort = 10808, + socksUsername = "o'connor", + socksPassword = "p'ass", + mtu = 1500, + hevTcpTimeoutSeconds = 5, + hevUdpTimeoutSeconds = 7, + hevLogLevel = "w'arn", + ), + "not used by HEV", + ) + + assertTrue(config.contains("port: 10808")) + assertTrue(config.contains("username: 'o''connor'")) + assertTrue(config.contains("password: 'p''ass'")) + assertTrue(config.contains("tcp-read-write-timeout: 5000")) + assertTrue(config.contains("udp-read-write-timeout: 7000")) + assertTrue(config.contains("log-level: 'w''arn'")) + assertFalse(config.contains(" ipv6:")) + } + + @Test + fun hevEngineAddsIpv6OnlyWhenEnabled() { + val config = HotspotRoutingConfig.engineContentFromSnapshot( + HotspotRoutingSnapshot( + running = true, + vpnMode = true, + useHev = true, + ipv6Enabled = true, + ), + "not used by HEV", + ) + + assertTrue(config.contains(" ipv6: '${AppConfig.SHIZUKU_TUN_ADDR_V6.substringBefore('/')}'")) + } +} diff --git a/V2rayNG/app/src/test/java/com/v2ray/ang/shizuku/TetheringCoreSyncTest.kt b/V2rayNG/app/src/test/java/com/v2ray/ang/shizuku/TetheringCoreSyncTest.kt new file mode 100644 index 00000000000..2b7a5f404b1 --- /dev/null +++ b/V2rayNG/app/src/test/java/com/v2ray/ang/shizuku/TetheringCoreSyncTest.kt @@ -0,0 +1,54 @@ +package com.v2ray.ang.shizuku + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertSame +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test + +class TetheringCoreSyncTest { + + @Test + fun coreSyncHookNeverLeaksFeatureFailuresIntoThePrimaryCore() { + var failure: Throwable? = null + val expected = IllegalStateException("Shizuku unavailable") + + assertFalse(runCoreSyncHook({ throw expected }) { failure = it }) + assertSame(expected, failure) + assertTrue(runCoreSyncHook({}, {})) + assertFalse(runCoreSyncHook({ throw expected }) { throw IllegalStateException("logger failed") }) + } + + @Test + fun binderDeathRecoversOnlyAStillRunningCore() { + val stopped = TetheringRecoveryState().onBinderDied().onBinderReceived() + assertEquals(TetheringRecoveryAction.NONE, stopped.action) + + val running = TetheringRecoveryState().onCoreStarted().onBinderDied() + assertTrue(running.recoverWhenShizukuReturns) + val recovered = running.onBinderReceived() + assertEquals(TetheringRecoveryAction.RECOVER, recovered.action) + assertFalse(recovered.state.recoverWhenShizukuReturns) + assertEquals(TetheringRecoveryAction.NONE, recovered.state.onBinderReceived().action) + + assertEquals(TetheringRecoveryState(), running.onCoreStopped()) + } + + @Test + fun foregroundRecoveryIsApiBoundedAndCoalescedUntilItCompletes() { + val waiting = TetheringRecoveryState().onCoreStarted().onBinderDied() + assertEquals(TetheringRecoveryAction.NONE, waiting.onAppForegrounded(33).action) + + val requested = waiting.onAppForegrounded(34) + assertEquals(TetheringRecoveryAction.REQUEST_BINDER, requested.action) + assertTrue(requested.state.foregroundRequestPending) + assertEquals(TetheringRecoveryAction.NONE, requested.state.onAppForegrounded(37).action) + + val retry = requested.state.onForegroundRequestFailed().onAppForegrounded(37) + assertEquals(TetheringRecoveryAction.REQUEST_BINDER, retry.action) + + val received = retry.state.onBinderReceived() + assertEquals(TetheringRecoveryAction.RECOVER, received.action) + assertFalse(received.state.foregroundRequestPending) + } +} diff --git a/V2rayNG/app/src/test/java/com/v2ray/ang/shizuku/TetheringPlatformCompatTest.kt b/V2rayNG/app/src/test/java/com/v2ray/ang/shizuku/TetheringPlatformCompatTest.kt new file mode 100644 index 00000000000..ac8aa5e3541 --- /dev/null +++ b/V2rayNG/app/src/test/java/com/v2ray/ang/shizuku/TetheringPlatformCompatTest.kt @@ -0,0 +1,38 @@ +package com.v2ray.ang.shizuku + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test + +class TetheringPlatformCompatTest { + + @Test + fun usesPublicTetheringApiStartingAtApi36() { + assertEquals(false, isPublicTetheringApiLevel(33)) + assertEquals(false, isPublicTetheringApiLevel(35)) + assertEquals(true, isPublicTetheringApiLevel(36)) + assertEquals(true, isPublicTetheringApiLevel(37)) + } + + @Test + fun buildsOnlyValidTetheringTypeBits() { + assertEquals(1, tetheringTypeBit(0)) + assertEquals(1 shl 15, tetheringTypeBit(15)) + assertEquals(0, tetheringTypeBit(-1)) + assertEquals(0, tetheringTypeBit(31)) + } + + @Test + fun acceptsOnlyTheOwnedUpstreamInterface() { + assertEquals(true, TetheringPlatformCompat.isProtectedUpstream("testtun17", "testtun17")) + assertEquals( + false, + TetheringPlatformCompat.isProtectedUpstream("testtun17, testtun17", "testtun17"), + ) + assertEquals(false, TetheringPlatformCompat.isProtectedUpstream("", "testtun17")) + assertEquals(false, TetheringPlatformCompat.isProtectedUpstream("eth0", "testtun17")) + assertEquals( + false, + TetheringPlatformCompat.isProtectedUpstream("testtun17, eth0", "testtun17"), + ) + } +} diff --git a/V2rayNG/app/src/test/java/com/v2ray/ang/shizuku/TetheringUpstreamMonitorTest.kt b/V2rayNG/app/src/test/java/com/v2ray/ang/shizuku/TetheringUpstreamMonitorTest.kt new file mode 100644 index 00000000000..11f902d588e --- /dev/null +++ b/V2rayNG/app/src/test/java/com/v2ray/ang/shizuku/TetheringUpstreamMonitorTest.kt @@ -0,0 +1,31 @@ +package com.v2ray.ang.shizuku + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import java.util.concurrent.CountDownLatch +import java.util.concurrent.atomic.AtomicReference + +class TetheringUpstreamMonitorTest { + @Test + fun readsTheLatestCallbackSnapshotWithoutRegisteringAnotherCallback() { + val interfaces = AtomicReference?>(null) + val received = CountDownLatch(1) + var closed = false + val monitor = TetheringUpstreamMonitor(AtomicReference("testtun0"), interfaces, received) { closed = true } + assertThrows(IllegalStateException::class.java) { monitor.awaitInterfaces(0) } + + val usb = ActiveTetheringInterface(1, "usb0") + interfaces.set(listOf(usb)) + received.countDown() + assertEquals(listOf(usb), monitor.awaitInterfaces(0)) + interfaces.set(emptyList()) + assertTrue(monitor.awaitInterfaces(0).isEmpty()) + + interfaces.set(null) + assertThrows(IllegalStateException::class.java) { monitor.awaitInterfaces(0) } + monitor.close() + assertTrue(closed) + } +} diff --git a/V2rayNG/app/src/test/java/com/v2ray/ang/ui/TetheringUiStateTest.kt b/V2rayNG/app/src/test/java/com/v2ray/ang/ui/TetheringUiStateTest.kt new file mode 100644 index 00000000000..495d0c32ae3 --- /dev/null +++ b/V2rayNG/app/src/test/java/com/v2ray/ang/ui/TetheringUiStateTest.kt @@ -0,0 +1,240 @@ +package com.v2ray.ang.ui + +import com.v2ray.ang.R +import com.v2ray.ang.dto.HotspotRoutingSnapshot +import com.v2ray.ang.shizuku.ShizukuTetheringService +import com.v2ray.ang.shizuku.TetheringStatusSnapshot +import com.v2ray.ang.shizuku.tetheringTypeBit +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test + +class TetheringUiStateTest { + @Test + fun proxyOnlyOrRootCoreDoesNotEnableVpnOnlyStarts() { + val state = TetheringUiState(serviceConnected = true, activeTetheringTypes = 0) + .withCoreSnapshot(HotspotRoutingSnapshot(running = true, vpnMode = false)) + + assertTrue(state.coreRunning) + assertFalse(state.vpnRunning) + assertFalse(routingAction(state).enabled) + assertFalse(hotspotAction(state).enabled) + assertEquals(R.string.shizuku_routing_status_start_v2ray, routingAction(state).statusRes) + assertEquals(R.string.shizuku_routing_status_start_v2ray, hotspotAction(state).statusRes) + } + + @Test + fun vpnSnapshotEnablesStartsButRunningBroadcastDoesNotAssumeVpnMode() { + val state = TetheringUiState(serviceConnected = true, activeTetheringTypes = 0) + .withCoreSnapshot(HotspotRoutingSnapshot(running = true, vpnMode = true)) + + assertTrue(state.vpnRunning) + assertTrue(routingAction(state).enabled) + assertTrue(hotspotAction(state).enabled) + assertFalse(state.withCoreRunning(false).vpnRunning) + assertFalse(state.withCoreRunning(true).vpnRunning) + } + + @Test + fun unsupportedCoreModeStillAllowsStoppingOwnedRoutingAndHotspot() { + val state = TetheringUiState( + serviceConnected = true, + hasRoutingSession = true, + routingState = ShizukuTetheringService.ROUTING_STATE_ERROR, + activeTetheringTypes = tetheringTypeBit(ShizukuTetheringService.TETHERING_TYPE_WIFI), + ).withCoreSnapshot(HotspotRoutingSnapshot(running = true, vpnMode = false)) + + assertTrue(routingAction(state).enabled) + assertTrue(hotspotAction(state).enabled) + assertEquals(TetheringOperation.STOPPING_ROUTING, state.operationFor(ShizukuAction.ToggleRouting)) + assertEquals(TetheringOperation.STOPPING_HOTSPOT, state.operationFor(ShizukuAction.ToggleHotspot)) + } + + + @Test + fun failedShutdownRetainsStopEvenWhenMainCoreIsStopped() { + val state = TetheringUiState( + serviceConnected = true, + hasRoutingSession = true, + routingState = ShizukuTetheringService.ROUTING_STATE_ERROR, + coreRunning = false, + ) + assertTrue(state.routingSessionEnabled) + assertTrue(routingAction(state).enabled) + assertEquals(TetheringOperation.STOPPING_ROUTING, state.operationFor(ShizukuAction.ToggleRouting)) + assertFalse(state.withServiceConnection(false).hasRoutingSession) + } + + @Test + fun hotspotStateIsDerivedFromTheActiveTetheringMask() { + val unknown = TetheringUiState() + assertFalse(unknown.tetheringStateKnown) + assertFalse(unknown.hotspotEnabled) + + val disabled = TetheringUiState(activeTetheringTypes = 0) + assertTrue(disabled.tetheringStateKnown) + assertFalse(disabled.hotspotEnabled) + + val usbOnly = TetheringUiState( + activeTetheringTypes = 1 shl ShizukuTetheringService.TETHERING_TYPE_USB, + ) + assertFalse(usbOnly.hotspotEnabled) + + val wifi = TetheringUiState( + activeTetheringTypes = 1 shl ShizukuTetheringService.TETHERING_TYPE_WIFI, + ) + assertTrue(wifi.hotspotEnabled) + } + + @Test + fun actionMappingPreservesTransientAndFailClosedStates() { + val connecting = TetheringUiState(operation = TetheringOperation.CONNECTING) + assertEquals( + R.string.shizuku_routing_status_connecting, + routingAction(connecting).statusRes, + ) + assertEquals( + R.string.shizuku_hotspot_status_connecting, + hotspotAction(connecting).statusRes, + ) + + val waiting = TetheringUiState( + routingState = ShizukuTetheringService.ROUTING_STATE_WAITING, + activeTetheringTypes = 1 shl ShizukuTetheringService.TETHERING_TYPE_WIFI, + ) + val connectedWaiting = waiting.copy(serviceConnected = true) + val routing = routingAction(connectedWaiting) + assertEquals(R.string.shizuku_routing_status_waiting, routing.statusRes) + assertTrue(routing.enabled) + assertEquals( + R.string.shizuku_hotspot_status_waiting, + hotspotAction(connectedWaiting).statusRes, + ) + } + + @Test + fun viewModelStateStartsDisconnectedAndResetsShellStateOnDisconnect() { + val initial = TetheringUiState() + assertFalse(initial.serviceConnected) + + val connected = initial.withServiceConnection(true).copy( + operation = TetheringOperation.STARTING_ROUTING, + routingState = ShizukuTetheringService.ROUTING_STATE_ACTIVE_NATIVE, + routingDetail = "testtun0 · Lab", + activeTetheringTypes = tetheringTypeBit(ShizukuTetheringService.TETHERING_TYPE_WIFI), + ipv6TetheringTypes = 0, + coreRunning = true, + ) + val disconnected = connected.withServiceConnection(false) + + assertFalse(disconnected.serviceConnected) + assertEquals(TetheringOperation.NONE, disconnected.operation) + assertEquals(ShizukuTetheringService.ROUTING_STATE_DISABLED, disconnected.routingState) + assertEquals("", disconnected.routingDetail) + assertEquals(ShizukuTetheringService.TETHERING_TYPES_UNKNOWN, disconnected.activeTetheringTypes) + assertEquals(ShizukuTetheringService.TETHERING_TYPES_UNKNOWN, disconnected.ipv6TetheringTypes) + assertTrue(disconnected.coreRunning) + } + + @Test + fun viewModelStateMapsCoreAndUserServiceSnapshots() { + val coreRunning = TetheringUiState().withCoreRunning(true) + assertTrue(coreRunning.coreRunning) + assertFalse(coreRunning.withCoreSnapshot(HotspotRoutingSnapshot()).coreRunning) + + val status = TetheringStatusSnapshot( + routingState = ShizukuTetheringService.ROUTING_STATE_ACTIVE_HEV, + routingDetail = "testtun4 · Lab", + activeTetheringTypes = tetheringTypeBit(ShizukuTetheringService.TETHERING_TYPE_USB), + ipv6TetheringTypes = 0, + warning = ShizukuTetheringService.RESULT_OK, + ) + val loaded = coreRunning.copy(operation = TetheringOperation.CHECKING) + .withTetheringStatus(status, ipv6Enabled = true) + + assertEquals(TetheringOperation.NONE, loaded.operation) + assertEquals(status.routingState, loaded.routingState) + assertEquals(status.routingDetail, loaded.routingDetail) + assertEquals(status.activeTetheringTypes, loaded.activeTetheringTypes) + assertEquals(status.ipv6TetheringTypes, loaded.ipv6TetheringTypes) + assertTrue(loaded.ipv6Enabled) + } + + @Test + fun viewModelActionMappingCoversEveryActionAndToggleDirection() { + assertNull(TetheringUiState().operationFor(ShizukuAction.RequestPermission)) + assertNull(TetheringUiState().operationFor(ShizukuAction.Refresh)) + assertEquals( + TetheringOperation.STARTING_ROUTING, + TetheringUiState().operationFor(ShizukuAction.ToggleRouting), + ) + assertEquals( + TetheringOperation.STOPPING_ROUTING, + TetheringUiState( + routingState = ShizukuTetheringService.ROUTING_STATE_WAITING, + ).operationFor(ShizukuAction.ToggleRouting), + ) + assertEquals( + TetheringOperation.STARTING_HOTSPOT, + TetheringUiState(activeTetheringTypes = 0).operationFor(ShizukuAction.ToggleHotspot), + ) + assertEquals( + TetheringOperation.STOPPING_HOTSPOT, + TetheringUiState( + activeTetheringTypes = tetheringTypeBit(ShizukuTetheringService.TETHERING_TYPE_WIFI), + ).operationFor(ShizukuAction.ToggleHotspot), + ) + } + + @Test + fun reportsTheObservedIpModeForEachActiveDownstream() { + val wifi = tetheringTypeBit(ShizukuTetheringService.TETHERING_TYPE_WIFI) + val usb = tetheringTypeBit(ShizukuTetheringService.TETHERING_TYPE_USB) + val state = TetheringUiState( + activeTetheringTypes = wifi or usb, + ipv6TetheringTypes = wifi, + ipv6Enabled = true, + ) + + assertEquals( + TetheringIpMode.DUAL_STACK, + state.ipMode(ShizukuTetheringService.TETHERING_TYPE_WIFI), + ) + assertEquals( + TetheringIpMode.IPV4_ONLY, + state.ipMode(ShizukuTetheringService.TETHERING_TYPE_USB), + ) + } + + @Test + fun hidesTheIpModeWhenIpv6IsDisabledOrTheDownstreamIsInactive() { + val wifi = tetheringTypeBit(ShizukuTetheringService.TETHERING_TYPE_WIFI) + val disabled = TetheringUiState(activeTetheringTypes = wifi) + .ipMode(ShizukuTetheringService.TETHERING_TYPE_WIFI) + val inactive = TetheringUiState( + activeTetheringTypes = wifi, + ipv6TetheringTypes = wifi, + ipv6Enabled = true, + ).ipMode(ShizukuTetheringService.TETHERING_TYPE_USB) + + assertNull(disabled) + assertNull(inactive) + } + + @Test + fun doesNotMistakeAnUnavailableIpv6ProbeForIpv4Only() { + val wifi = tetheringTypeBit(ShizukuTetheringService.TETHERING_TYPE_WIFI) + val state = TetheringUiState( + activeTetheringTypes = wifi, + ipv6TetheringTypes = ShizukuTetheringService.TETHERING_TYPES_UNKNOWN, + ipv6Enabled = true, + ) + + assertEquals( + TetheringIpMode.UNKNOWN, + state.ipMode(ShizukuTetheringService.TETHERING_TYPE_WIFI), + ) + } +} diff --git a/V2rayNG/gradle/libs.versions.toml b/V2rayNG/gradle/libs.versions.toml index 5c01f8c9874..33c764b06c0 100644 --- a/V2rayNG/gradle/libs.versions.toml +++ b/V2rayNG/gradle/libs.versions.toml @@ -21,6 +21,7 @@ mockitoKotlin = "6.4.0" camerax = "1.6.2" composeBom = "2026.09.00" reorderable = "3.1.0" +shizuku = "13.1.5" coil = "3.6.3" [libraries] androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" } @@ -60,9 +61,11 @@ androidx-compose-ui = { group = "androidx.compose.ui", name = "ui" } androidx-compose-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling" } androidx-compose-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview" } lifecycle-runtime-compose = { module = "androidx.lifecycle:lifecycle-runtime-compose", version.ref = "lifecycleViewmodelKtx" } +shizuku-api = { module = "dev.rikka.shizuku:api", version.ref = "shizuku" } +shizuku-provider = { module = "dev.rikka.shizuku:provider", version.ref = "shizuku" } coil-compose = { module = "io.coil-kt.coil3:coil-compose", version.ref = "coil" } [plugins] android-application = { id = "com.android.application", version.ref = "agp" } android-library = { id = "com.android.library", version.ref = "agp" } kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" } -kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" } \ No newline at end of file +kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }