From 3194028a78815e3ff43cfa20f7e95125be9cbbaa Mon Sep 17 00:00:00 2001 From: John Maguire Date: Mon, 3 May 2021 14:58:09 -0400 Subject: [PATCH] Unregister network callback on stop (Android) (#34) Previously when `stopVpn()` was called, it was possible for the network change callback to fire while we were in the middle of shutting down. This commit unregisters the network change callback before telling Nebula to shutdown. --- .../defined/mobile_nebula/NebulaVpnService.kt | 33 ++++++++++++------- 1 file changed, 21 insertions(+), 12 deletions(-) diff --git a/android/app/src/main/kotlin/net/defined/mobile_nebula/NebulaVpnService.kt b/android/app/src/main/kotlin/net/defined/mobile_nebula/NebulaVpnService.kt index cef46da..2261c96 100644 --- a/android/app/src/main/kotlin/net/defined/mobile_nebula/NebulaVpnService.kt +++ b/android/app/src/main/kotlin/net/defined/mobile_nebula/NebulaVpnService.kt @@ -39,6 +39,7 @@ class NebulaVpnService : VpnService() { private var nebula: mobileNebula.Nebula? = null private var vpnInterface: ParcelFileDescriptor? = null private var didSleep = false + private var networkCallback: NetworkCallback = NetworkCallback(); override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { if (intent?.getStringExtra("COMMAND") == "STOP") { @@ -128,20 +129,27 @@ class NebulaVpnService : VpnService() { val builder = NetworkRequest.Builder() builder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) - connectivityManager.registerNetworkCallback(builder.build(), - object : ConnectivityManager.NetworkCallback () { - override fun onAvailable(network: Network?) { - super.onAvailable(network) - nebula!!.rebind("network change") - } - - override fun onLost(network: Network?) { - super.onLost(network) - nebula!!.rebind("network change") - } - }) + connectivityManager.registerNetworkCallback(builder.build(), networkCallback) } + private fun unregisterNetworkCallback() { + val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager + connectivityManager.unregisterNetworkCallback(networkCallback) + } + + inner class NetworkCallback() : ConnectivityManager.NetworkCallback () { + override fun onAvailable(network: Network?) { + super.onAvailable(network) + nebula!!.rebind("network change") + } + + override fun onLost(network: Network?) { + super.onLost(network) + nebula!!.rebind("network change") + } + } + + private fun registerSleep() { val receiver: BroadcastReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent?) { @@ -163,6 +171,7 @@ class NebulaVpnService : VpnService() { } private fun stopVpn() { + unregisterNetworkCallback() nebula?.stop() vpnInterface?.close() running = false