3
0
Fork 0

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.
This commit is contained in:
John Maguire 2021-05-03 14:58:09 -04:00 committed by GitHub
parent 1d044a1e36
commit 3194028a78
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 21 additions and 12 deletions

View File

@ -39,6 +39,7 @@ class NebulaVpnService : VpnService() {
private var nebula: mobileNebula.Nebula? = null private var nebula: mobileNebula.Nebula? = null
private var vpnInterface: ParcelFileDescriptor? = null private var vpnInterface: ParcelFileDescriptor? = null
private var didSleep = false private var didSleep = false
private var networkCallback: NetworkCallback = NetworkCallback();
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent?.getStringExtra("COMMAND") == "STOP") { if (intent?.getStringExtra("COMMAND") == "STOP") {
@ -128,20 +129,27 @@ class NebulaVpnService : VpnService() {
val builder = NetworkRequest.Builder() val builder = NetworkRequest.Builder()
builder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) builder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
connectivityManager.registerNetworkCallback(builder.build(), connectivityManager.registerNetworkCallback(builder.build(), networkCallback)
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")
}
})
} }
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() { private fun registerSleep() {
val receiver: BroadcastReceiver = object : BroadcastReceiver() { val receiver: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent?) { override fun onReceive(context: Context, intent: Intent?) {
@ -163,6 +171,7 @@ class NebulaVpnService : VpnService() {
} }
private fun stopVpn() { private fun stopVpn() {
unregisterNetworkCallback()
nebula?.stop() nebula?.stop()
vpnInterface?.close() vpnInterface?.close()
running = false running = false