Wachu985 / flutter_wireguard_vpn

A Flutter package that allows connection through a VPN using WireGuard.
https://pub.dev/packages/wireguard_vpn
BSD 3-Clause "New" or "Revised" License
22 stars 9 forks source link

"Ghost" Tunnels #7

Open ByteSizedMarius opened 1 year ago

ByteSizedMarius commented 1 year ago

Hello, I've found a small problem and will propose a fix here, but since I am not comfortable with Kotlin, I'm opening this issue instead of a PR.

Basically, when a tunnel is running and the app is closed (swipe up, close), the tunnel will remain active in the background, as the app is not fully stopped (this is reproducible with the example app on api 34). Opening the app again, the WG backend has, to my knowledge, no way of retrieving the running tunnel from the old backend (statistics and getRunningTunnelNames return nothing). Reconnecting doesn't work either in my case, because the old tunnel is still active. The only solution I've found (other than changing the code), is force-stopping the app from the android settings, which closes the tunnel completely.

What I've done to remedy this, is to add a for-loop in onDetachedFromEngine, that closes currently running tunnels. This seems to prevent the issue at hand, as the method seems to be called whenever the app is closed in the way described.

override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
    scope.launch(Dispatchers.IO) {
        try {
            // get running tunnels
            val runningTunnels = futureBackend.await().runningTunnelNames
            // stop all tunnels
            runningTunnels.forEach {
                futureBackend.await().setState(tunnel(it), Tunnel.State.DOWN, null)
                Log.i(TAG, "Stopped tunnel $it")
            }
        } catch (e: Throwable) {
            Log.e(TAG, Log.getStackTraceString(e))
        }
    }

    channel.setMethodCallHandler(null)
}

Not sure if this is the correct place to do this (maybe kotlin offers a better native solution I am not aware of), but generally, I believe the tunnels should be shut down when the app closes to prevent active tunnels to become out of our control.

Thanks for your work on this, it's greatly appreciated.

chanhhoang99 commented 1 year ago

Thank @ByteSizedMarius for working on this. I also face the same issue and thank you for the fix, it works for me.

adarshaketh commented 3 months ago

Thank You