Keep the tunnel reader alive on bad packets, disconnect if it dies

Before, any unexpected error ended the reader while the VPN stayed up,
so DNS stopped working for the whole device without any sign of it.
This commit is contained in:
2026-10-25 12:18:17 +02:00
parent 8c6bb33527
commit e601b2dbaa
@@ -9,6 +9,8 @@ import android.content.pm.ServiceInfo
import android.graphics.drawable.Icon import android.graphics.drawable.Icon
import android.net.VpnService import android.net.VpnService
import android.os.Build import android.os.Build
import android.os.Handler
import android.os.Looper
import android.os.ParcelFileDescriptor import android.os.ParcelFileDescriptor
import android.os.SystemClock import android.os.SystemClock
import android.system.ErrnoException import android.system.ErrnoException
@@ -32,6 +34,7 @@ private const val WORKERS = 16
private const val TAG = "SparkleDNS" private const val TAG = "SparkleDNS"
private const val CHANNEL_ID = "vpn_status" private const val CHANNEL_ID = "vpn_status"
private const val NOTIFICATION_ID = 1 private const val NOTIFICATION_ID = 1
private const val MAX_BAD_PACKETS = 100
// Local VPN that routes only the fake DNS address into the tunnel; all other traffic is untouched // Local VPN that routes only the fake DNS address into the tunnel; all other traffic is untouched
class DohVpnService : VpnService() { class DohVpnService : VpnService() {
@@ -50,6 +53,7 @@ class DohVpnService : VpnService() {
} }
private var session: Session? = null private var session: Session? = null
private val mainHandler = Handler(Looper.getMainLooper())
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent?.action == ACTION_STOP) { if (intent?.action == ACTION_STOP) {
@@ -108,7 +112,7 @@ class DohVpnService : VpnService() {
stopSelf() stopSelf()
return return
} }
session = Session(tun, DohClient(this, provider)).also { it.start() } session = Session(tun, DohClient(this, provider), ::onSessionFailed).also { it.start() }
runCatching { previous?.stop() } runCatching { previous?.stop() }
_active.value = provider _active.value = provider
@@ -127,6 +131,17 @@ class DohVpnService : VpnService() {
DnsTileService.refresh(this) DnsTileService.refresh(this)
} }
// The tunnel reader died while the session should be running. Dropping the VPN lets Android
// fall back to normal DNS instead of sending every lookup on the device into a dead tunnel.
private fun onSessionFailed(failed: Session) {
mainHandler.post {
if (session !== failed) return@post
Log.e(TAG, "Tunnel stopped working, disconnecting")
stopSession()
stopSelf()
}
}
private fun showNotification(provider: DohProvider) { private fun showNotification(provider: DohProvider) {
val manager = getSystemService(NotificationManager::class.java) ?: return val manager = getSystemService(NotificationManager::class.java) ?: return
manager.createNotificationChannel( manager.createNotificationChannel(
@@ -177,6 +192,7 @@ class DohVpnService : VpnService() {
private class Session( private class Session(
private val tun: ParcelFileDescriptor, private val tun: ParcelFileDescriptor,
private val doh: DohClient, private val doh: DohClient,
private val onFailure: (Session) -> Unit,
) { ) {
private val alive = AtomicBoolean(true) private val alive = AtomicBoolean(true)
private val pool = Executors.newFixedThreadPool(WORKERS) private val pool = Executors.newFixedThreadPool(WORKERS)
@@ -201,26 +217,48 @@ private class Session(
events = OsConstants.POLLIN.toShort() events = OsConstants.POLLIN.toShort()
} }
var badPackets = 0
while (alive.get()) { while (alive.get()) {
try { val n = try {
if (Os.poll(arrayOf(pollFd), 500) <= 0) continue if (Os.poll(arrayOf(pollFd), 500) <= 0) continue
val n = input.read(buf) input.read(buf)
if (n < 0) break
val query = Packet.parseDnsQuery(buf, n) ?: continue
dispatch(query)
} catch (e: ErrnoException) { } catch (e: ErrnoException) {
if (e.errno != OsConstants.EINTR) break if (e.errno == OsConstants.EINTR) continue
} catch (_: IOException) { readerFailed(e)
break return
} catch (_: RejectedExecutionException) { } catch (e: IOException) {
break readerFailed(e)
} catch (e: Exception) { return
Log.e(TAG, "Tunnel reader failed", e) }
break if (n < 0) {
readerFailed(null)
return
}
try {
Packet.parseDnsQuery(buf, n)?.let(::dispatch)
badPackets = 0
} catch (e: RejectedExecutionException) {
readerFailed(e)
return
} catch (e: RuntimeException) {
// One packet the code cannot handle must not stop DNS for the whole device
Log.w(TAG, "Dropped a packet", e)
if (++badPackets >= MAX_BAD_PACKETS) {
readerFailed(e)
return
}
} }
} }
} }
// stop() closes the tunnel, which also ends the loop; only an unexpected end is a failure
private fun readerFailed(cause: Throwable?) {
if (!alive.get()) return
Log.e(TAG, "Tunnel reader stopped", cause)
onFailure(this)
}
// Blocklist and cache are answered right here; only real lookups go to the worker pool // Blocklist and cache are answered right here; only real lookups go to the worker pool
private fun dispatch(query: UdpPacket) { private fun dispatch(query: UdpPacket) {
val question = DnsMessage.question(query.payload) val question = DnsMessage.question(query.payload)