Skip to content

fix(android): tighten VPN session lifecycle reliability - #187

Merged
therealaleph merged 1 commit into
therealaleph:mainfrom
dazzling-no-more:fix/vpn-lifecycle-reliability
Apr 25, 2026
Merged

therealaleph merged 1 commit into
therealaleph:mainfrom
dazzling-no-more:fix/vpn-lifecycle-reliability

Conversation

@dazzling-no-more

Copy link
Copy Markdown
Contributor

What's fixed

1. Connect button could fire while previous Stop was still tearing down

The Compose Connect/Disconnect button was gated on a fixed 2s transitionCooldown timer. Worst-case teardown is around 9s (Tun2proxy.stop() + 4s tun2proxy join + 5s rt.shutdown_timeout), so users could tap Connect after the cooldown expired but before the previous Stop had released the listener socket. Native.startProxy then failed with "Address already in use" and the UI looked stuck.

The button now suspends on VpnState.isRunning until the service actually flips the flag, with a 12s withTimeoutOrNull backstop in case the service fails before flipping (e.g., establish() returned null). Side benefit: same gate also debounces the rapid-tap EGL renderer crash the old timer was guarding against.

2. Tun2proxy.stop() had no timeout

The teardown thread trusted the JNI call to return quickly. Wrapped it in a side thread with a 2s join(). If the native call hangs, we log and proceed — the bounded tun2proxy join + bounded rt.shutdown_timeout below it still release the listener port.

3. fd leak window between parcelFd.detachFd() and Thread.start()

Once detachFd() returned, ownership transferred to Tun2proxy.run's closeFdOnDrop. If Thread.start() threw (OOM under memory pressure), nobody owned the fd and it leaked for the life of the process. Now wrapped in try/catch; on failure we adopt the int fd into a fresh ParcelFileDescriptor purely so we can close() it, then the half-started service is torn down cleanly (stopProxy, stopForeground, stopSelf).

4. Misleading teardown doc-comment

The doc-block claimed step 2 ("close the TUN fd") forces tun2proxy's read() to return EBADF. That call has been a no-op since detachFd was added — the real exit mechanism is the cooperative Tun2proxy.stop() plus the bounded runtime shutdown. Rewrote the doc-block to call out the bound on each step, and corrected the inline step-2 comment so future debuggers don't chase a phantom safety net.

5. Recursive crash trap in MhrvApp's uncaught handler

The default-uncaught-exception handler called Log.e unguarded. If logging itself threw (logd dead, OOM in message format), we'd recurse into our own handler with a half-handled original exception. Wrapped the Log.e in try/catch so the previous handler still fires with the real failure.

Files touched

  • android/app/src/main/java/com/therealaleph/mhrv/MhrvApp.kt — guard Log.e in uncaught handler
  • android/app/src/main/java/com/therealaleph/mhrv/MhrvVpnService.kt — bounded Tun2proxy.stop(), fd-leak guard, rewritten teardown doc-block
  • android/app/src/main/java/com/therealaleph/mhrv/ui/HomeScreen.kt — awaitingRunning state-driven button gate

@therealaleph

Copy link
Copy Markdown
Owner

Reviewed locally — five clean reliability fixes, low blast radius (Android-only), good rationale on each. Merging.

Verified:

  • Test-merged against current main (post-v1.6.0 + UDP support) — clean auto-merge.
  • ./gradlew :app:compileReleaseKotlin = BUILD SUCCESSFUL.

Each fix makes sense:

  1. Connect button vs. teardown race — the 2s transitionCooldown was a guess; switching to a state-driven VpnState.isRunning gate with a 12s withTimeoutOrNull backstop is correct because the actual teardown ceiling (Tun2proxy + tun2proxy join + rt.shutdown_timeout = ~9s worst-case) is what we need to wait on. The same gate also gives us the EGL crash debounce as a side effect.

  2. Tun2proxy.stop() unbounded — wrapping in a 2s join() is the right shape; the native call is supposed to return fast but should never be allowed to hang the teardown thread. If it does hang, the bounded tun2proxy thread join + bounded rt.shutdown_timeout below still release the listener port. We accept the fd-leak as the cost of proceeding.

  3. fd leak between detachFd() and Thread.start() — this is a real correctness bug, not just defensive cleanup. Once detachFd returns, the ParcelFileDescriptor no longer owns the fd; if Thread.start throws (OOM under memory pressure is plausible on cheap Android devices), nobody closes it. Adopting the raw int back into a fresh ParcelFileDescriptor for the express purpose of closing it is a tidy idiom — Android FileDescriptor doesn't expose a portable close otherwise.

  4. Misleading doc comment — fair callout. The "step 2: close TUN fd to force EBADF on read" note has been factually wrong since detachFd landed; nobody noticed because the cooperative Tun2proxy.stop() has been doing the work. Worth fixing the comment so future debuggers don't waste time on the phantom path.

  5. Recursive crash trap in uncaught handler — small but real. If Log.e itself throws (logd dead, OOM during string format), the default handler never sees the original exception and we lose the actual crash signal. Guarding it with try/catch and falling through to the previous handler is the correct shape.

Releasing as v1.6.1 (patch — all fixes, no new behavior).


[reply via Anthropic Claude | reviewed by @therealaleph]

@therealaleph
therealaleph merged commit aa906e3 into therealaleph:main Apr 25, 2026
therealaleph added a commit that referenced this pull request Apr 25, 2026
Five small but real Android-only fixes:

1. Connect/Disconnect button gated on VpnState.isRunning state-flow
   with 12s backstop, replacing the fixed 2s transitionCooldown
   timer. Closes the race where a tap-after-Stop hit "Address already
   in use" because the previous teardown's listener-socket release
   wasn't done.

2. Tun2proxy.stop() wrapped in 2s join() — if the native call hangs,
   bounded teardown still releases the listener port instead of
   holding the teardown thread.

3. fd-leak fixed between parcelFd.detachFd() and Thread.start(): an
   OOM-thrown Thread.start used to orphan the detached fd. Now
   adopted into a fresh ParcelFileDescriptor purely so we can close()
   it.

4. Misleading teardown doc-comment rewritten — the "step 2 closes
   the TUN fd to force EBADF on read" claim has been factually
   wrong since detachFd landed.

5. Recursive crash trap: Log.e in MhrvApp's uncaught handler now
   wrapped in try/catch so a logd failure during exception logging
   falls through to the previous handler with the real exception.

No Rust changes; 98 lib + 22 tunnel-node tests still pass.

Local Android build verified, APK installed on mhrv_test emulator,
launches cleanly with v1.6.1 in title.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@dazzling-no-more
dazzling-no-more deleted the fix/vpn-lifecycle-reliability branch April 25, 2026 19:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants