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 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