Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
43f0d42d65 | ||
|
|
2b0f842579 | ||
|
|
17ede339fa | ||
|
|
ac643caf03 | ||
|
|
0ceae2f557 | ||
|
|
df41b44302 | ||
|
|
4619292174 | ||
|
|
cff974851a | ||
|
|
d9080195ab | ||
|
|
026c2c9493 | ||
|
|
8907f4cf96 | ||
|
|
9aceaaa200 | ||
|
|
9e744b309e | ||
|
|
603e90dcca | ||
|
|
e7105b0245 | ||
|
|
25e359595b | ||
|
|
9f9c79cf2b | ||
|
|
447a309f69 | ||
|
|
8b975c77ce | ||
|
|
04ef7adb44 | ||
|
|
f236136919 | ||
|
|
a33a945477 | ||
|
|
8502860512 | ||
|
|
50f069731c | ||
|
|
37653792fd | ||
|
|
2cb3439efd | ||
|
|
8ac908e684 | ||
|
|
5a1bf79e4b | ||
|
|
5f56c471ce | ||
|
|
87feb7f483 | ||
|
|
a63184830d | ||
|
|
4e99ef1211 | ||
|
|
fa6398c40e | ||
|
|
778ce20f6e | ||
|
|
7da1a34495 | ||
|
|
bac4ccf26e | ||
|
|
e601b2dbaa | ||
|
|
8c6bb33527 | ||
|
|
43e57c9357 | ||
|
|
87d9afd55b | ||
|
|
7a2c7eccb3 | ||
|
|
dbc3454742 | ||
|
|
ad798f0a79 |
@@ -89,7 +89,7 @@ If your code adds new strings, add them to `values/strings.xml`. Translations fo
|
||||
1. Fork the repository and create a branch from `main`.
|
||||
2. Keep one topic per pull request.
|
||||
3. Follow the existing Kotlin and Jetpack Compose style; keep comments short and in English; don't reformat unrelated code.
|
||||
4. Make sure `./gradlew assembleDebug` builds, and test on a device or emulator.
|
||||
4. Make sure `./gradlew assembleDebug testDebugUnitTest` passes, and test on a device or emulator. For changes that may affect speed or memory, `scripts/bench.sh` compares two APKs on a rooted device or emulator (`scripts/bench-build.sh` builds them from two revisions).
|
||||
5. Write short, plain commit messages in English (for example `Fix tunnel restart after server switch`).
|
||||
6. Add screenshots for UI changes.
|
||||
|
||||
|
||||
@@ -636,8 +636,7 @@ the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
the Free Software Foundation, version 3 of the License.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
|
||||
@@ -28,6 +28,9 @@
|
||||
<img src="assets/screenshots/5-choose-your-own-route.png" width="160" alt="Choose your own route">
|
||||
</p>
|
||||
|
||||
> [!TIP]
|
||||
> If you find SparkleDNS useful, please consider giving it a ⭐ — it helps others discover the project.
|
||||
|
||||
## ✨ Features
|
||||
|
||||
- 🔌 **One-tap connect/disconnect**, with a Quick Settings tile
|
||||
@@ -80,4 +83,4 @@ Bug reports, DoH server and blocklist suggestions, translation fixes and pull re
|
||||
|
||||
## 📄 License
|
||||
|
||||
[GNU General Public License v3.0 or later](LICENSE).
|
||||
[GNU General Public License v3.0 only](LICENSE).
|
||||
|
||||
@@ -13,8 +13,8 @@ android {
|
||||
targetSdk = 36
|
||||
// Single source of truth: the About screen reads these through BuildConfig.
|
||||
// Kept as plain literals so F-Droid can detect new versions. Code = major * 10000 + minor * 100 + patch.
|
||||
versionCode = 10009
|
||||
versionName = "1.0.9"
|
||||
versionCode = 10010
|
||||
versionName = "1.0.10"
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
@@ -27,6 +27,12 @@ android {
|
||||
}
|
||||
}
|
||||
|
||||
androidResources {
|
||||
// Only the languages the app itself is translated to; library strings for other
|
||||
// languages were unused weight, as the app falls back to English there anyway
|
||||
localeFilters += listOf("en", "de", "ja", "lt", "ru", "zh")
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
@@ -42,6 +48,11 @@ android {
|
||||
includeInApk = false
|
||||
includeInBundle = false
|
||||
}
|
||||
|
||||
testOptions {
|
||||
// android.util.Log and friends are no-ops in JVM unit tests
|
||||
unitTests.isReturnDefaultValues = true
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
@@ -49,6 +60,13 @@ dependencies {
|
||||
implementation("androidx.activity:activity-compose:1.10.1")
|
||||
implementation("androidx.compose.ui:ui")
|
||||
implementation("androidx.compose.material3:material3")
|
||||
// Already pulled in by Compose at this version; declared because the app uses it directly
|
||||
implementation("androidx.lifecycle:lifecycle-runtime-compose:2.9.0")
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2")
|
||||
implementation("com.squareup.okhttp3:okhttp:4.12.0")
|
||||
|
||||
// Debug builds only, never part of a release
|
||||
debugImplementation("com.squareup.leakcanary:leakcanary-android:2.14")
|
||||
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# Readable stack traces in crash reports
|
||||
# File names and line numbers stay in stack traces, names are obfuscated. To read a crash
|
||||
# report, build the same release (builds are reproducible) and run
|
||||
# retrace app/build/outputs/mapping/release/mapping.txt crash.txt
|
||||
-keepattributes SourceFile,LineNumberTable
|
||||
-dontobfuscate
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
package cc.skysparkle.sparkledns
|
||||
|
||||
import android.content.ActivityNotFoundException
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.util.Log
|
||||
import android.widget.Toast
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.animation.AnimatedContent
|
||||
import androidx.compose.animation.fadeIn
|
||||
@@ -264,7 +267,12 @@ private fun InfoRow(label: String, value: String) {
|
||||
}
|
||||
|
||||
internal fun openUrl(context: Context, url: String) {
|
||||
runCatching {
|
||||
try {
|
||||
context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
} catch (_: ActivityNotFoundException) {
|
||||
// Without a browser the tap used to do nothing at all
|
||||
Toast.makeText(context, R.string.no_browser, Toast.LENGTH_SHORT).show()
|
||||
} catch (e: RuntimeException) {
|
||||
Log.w("SparkleDNS", "Cannot open $url", e)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,26 +39,28 @@ import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TriStateCheckbox
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.produceState
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.Saver
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.draw.rotate
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.state.ToggleableState
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
@@ -77,20 +79,29 @@ private enum class AppGroup(@StringRes val label: Int, @DrawableRes val icon: In
|
||||
|
||||
private class AppItem(val label: String, val packageName: String, val group: AppGroup)
|
||||
|
||||
// Decoded icons survive scrolling and tab switches instead of being rendered again every time
|
||||
private val IconCache = LruCache<String, ImageBitmap>(256)
|
||||
// Decoded icons survive scrolling and tab switches instead of being rendered again every time.
|
||||
// Limited by memory rather than count, since icon size now follows the screen density.
|
||||
private val IconCache = object : LruCache<String, ImageBitmap>(10 * 1024 * 1024) {
|
||||
override fun sizeOf(key: String, value: ImageBitmap) = value.width * value.height * 4
|
||||
}
|
||||
|
||||
internal fun clearAppIconCache() = IconCache.evictAll()
|
||||
|
||||
// Shown right away when the tab opens again, while the list is read anew in the background.
|
||||
// Only touched on the main thread.
|
||||
private var lastAppList: List<AppItem>? = null
|
||||
|
||||
@Composable
|
||||
fun AppsScreen(modifier: Modifier = Modifier) {
|
||||
val context = LocalContext.current
|
||||
val prefs = remember { Prefs(context) }
|
||||
val active by DohVpnService.active.collectAsState()
|
||||
val activeExcluded by DohVpnService.activeExcluded.collectAsState()
|
||||
val active by DohVpnService.active.collectAsStateWithLifecycle()
|
||||
val activeExcluded by DohVpnService.activeExcluded.collectAsStateWithLifecycle()
|
||||
|
||||
var apps by remember { mutableStateOf<List<AppItem>?>(null) }
|
||||
var apps by remember { mutableStateOf(lastAppList) }
|
||||
var excluded by remember { mutableStateOf(prefs.excludedApps) }
|
||||
var search by rememberSaveable { mutableStateOf("") }
|
||||
var collapsed by remember { mutableStateOf(setOf(AppGroup.SYSTEM)) }
|
||||
var collapsed by rememberSaveable(stateSaver = CollapsedSaver) { mutableStateOf(setOf(AppGroup.SYSTEM)) }
|
||||
val pending = active != null && excluded != activeExcluded
|
||||
var showAppsHint by remember { mutableStateOf(!prefs.isHintDismissed(HINT_APPS)) }
|
||||
// Closing the "reconnect" card hides it until the selection changes again
|
||||
@@ -100,7 +111,7 @@ fun AppsScreen(modifier: Modifier = Modifier) {
|
||||
val searching = search.isNotBlank()
|
||||
|
||||
LaunchedEffect(Unit) {
|
||||
apps = withContext(Dispatchers.IO) { loadApps(context) }
|
||||
apps = withContext(Dispatchers.IO) { loadApps(context) }.also { lastAppList = it }
|
||||
}
|
||||
|
||||
val groups = remember(apps, search) {
|
||||
@@ -188,7 +199,7 @@ fun AppsScreen(modifier: Modifier = Modifier) {
|
||||
|
||||
groups.forEach { (group, items) ->
|
||||
val expanded = searching || group !in collapsed
|
||||
item(key = "group:${group.name}") {
|
||||
item(key = "group:${group.name}", contentType = "group") {
|
||||
GroupHeader(
|
||||
modifier = Modifier.animateItem(),
|
||||
group = group,
|
||||
@@ -205,7 +216,7 @@ fun AppsScreen(modifier: Modifier = Modifier) {
|
||||
)
|
||||
}
|
||||
if (expanded) {
|
||||
itemsIndexed(items, key = { _, app -> app.packageName }) { index, app ->
|
||||
itemsIndexed(items, key = { _, app -> app.packageName }, contentType = { _, _ -> "app" }) { index, app ->
|
||||
AppRow(
|
||||
modifier = Modifier.animateItem(),
|
||||
app = app,
|
||||
@@ -237,7 +248,8 @@ private fun GroupHeader(
|
||||
else -> ToggleableState.Indeterminate
|
||||
}
|
||||
|
||||
val chevron by animateFloatAsState(if (expanded) 180f else 0f, Motion.rotation, label = "chevron")
|
||||
// Read only in the draw phase, so the animation does not recompose the header every frame
|
||||
val chevron = animateFloatAsState(if (expanded) 180f else 0f, Motion.rotation, label = "chevron")
|
||||
|
||||
Row(
|
||||
modifier = modifier
|
||||
@@ -267,7 +279,7 @@ private fun GroupHeader(
|
||||
modifier = Modifier
|
||||
.padding(end = 8.dp)
|
||||
.size(22.dp)
|
||||
.rotate(chevron),
|
||||
.graphicsLayer { rotationZ = chevron.value },
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -275,12 +287,15 @@ private fun GroupHeader(
|
||||
@Composable
|
||||
private fun AppRow(modifier: Modifier, app: AppItem, enabled: Boolean, last: Boolean, onToggle: (Boolean) -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val icon by produceState<ImageBitmap?>(IconCache.get(app.packageName), app.packageName) {
|
||||
// Rendered at the size it is shown (40 dp), so icons stay sharp on dense screens
|
||||
val iconPx = with(LocalDensity.current) { 40.dp.roundToPx() }
|
||||
val cacheKey = "${app.packageName}@$iconPx"
|
||||
val icon by produceState<ImageBitmap?>(IconCache.get(cacheKey), cacheKey) {
|
||||
if (value != null) return@produceState
|
||||
value = withContext(Dispatchers.IO) {
|
||||
runCatching { context.packageManager.getApplicationIcon(app.packageName).toImageBitmap(96) }
|
||||
runCatching { context.packageManager.getApplicationIcon(app.packageName).toImageBitmap(iconPx) }
|
||||
.getOrNull()
|
||||
?.also { IconCache.put(app.packageName, it) }
|
||||
?.also { IconCache.put(cacheKey, it) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -363,4 +378,10 @@ private fun Drawable.toImageBitmap(size: Int): ImageBitmap {
|
||||
return bitmap.asImageBitmap()
|
||||
}
|
||||
|
||||
// Collapsed groups survive rotation and process death
|
||||
private val CollapsedSaver = Saver<Set<AppGroup>, String>(
|
||||
save = { groups -> groups.joinToString(",") { it.name } },
|
||||
restore = { saved -> saved.split(',').mapNotNull { name -> AppGroup.entries.firstOrNull { it.name == name } }.toSet() },
|
||||
)
|
||||
|
||||
private const val HINT_APPS = "apps"
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package cc.skysparkle.sparkledns
|
||||
|
||||
import android.content.Context
|
||||
import android.content.SharedPreferences
|
||||
import android.util.Log
|
||||
import kotlinx.coroutines.CoroutineExceptionHandler
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
@@ -28,7 +31,9 @@ data class RemoteList(val url: String, val count: Int, val updated: Long)
|
||||
object Blocklist {
|
||||
const val ALL_LISTS = "*"
|
||||
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
private val scope = CoroutineScope(
|
||||
SupervisorJob() + Dispatchers.IO + CoroutineExceptionHandler { _, e -> Log.e("SparkleDNS", "Blocklist task failed", e) }
|
||||
)
|
||||
private val lock = Any()
|
||||
|
||||
private val _enabled = MutableStateFlow(true)
|
||||
@@ -51,24 +56,16 @@ object Blocklist {
|
||||
private val _error = MutableStateFlow<String?>(null)
|
||||
val error: StateFlow<String?> = _error
|
||||
|
||||
// Downloaded lists and own domains are kept apart, so editing a few own domains
|
||||
// does not rebuild a set that can hold millions of entries
|
||||
@Volatile
|
||||
private var hashes = LongArray(0)
|
||||
private var listHashes = LongArray(0)
|
||||
|
||||
@Volatile
|
||||
private var customHashes = LongArray(0)
|
||||
private var loaded = false
|
||||
|
||||
fun isBlocked(name: String): Boolean {
|
||||
if (!_enabled.value) return false
|
||||
val set = hashes
|
||||
if (set.isEmpty()) return false
|
||||
val domain = name.trimEnd('.')
|
||||
var start = 0
|
||||
while (true) {
|
||||
if (set.binarySearch(DomainHash.of(domain, start)) >= 0) return true
|
||||
val dot = domain.indexOf('.', start)
|
||||
if (dot < 0) return false
|
||||
start = dot + 1
|
||||
}
|
||||
}
|
||||
fun isBlocked(name: String): Boolean = _enabled.value && isBlockedIn(name, listHashes, customHashes)
|
||||
|
||||
fun reload(context: Context) = synchronized(lock) { load(BlocklistStore(context)) }
|
||||
|
||||
@@ -84,7 +81,7 @@ object Blocklist {
|
||||
val updated = (_custom.value + domain).distinct().sorted()
|
||||
store.saveCustom(updated)
|
||||
_custom.value = updated
|
||||
combine()
|
||||
updateCustomHashes()
|
||||
true
|
||||
}
|
||||
|
||||
@@ -94,7 +91,7 @@ object Blocklist {
|
||||
val updated = _custom.value - domain
|
||||
store.saveCustom(updated)
|
||||
_custom.value = updated
|
||||
combine()
|
||||
updateCustomHashes()
|
||||
}
|
||||
|
||||
fun removeList(context: Context, url: String) = synchronized(lock) {
|
||||
@@ -114,9 +111,10 @@ object Blocklist {
|
||||
if (target.isEmpty() || !_busy.compareAndSet(null, target)) return false
|
||||
_error.value = null
|
||||
val store = BlocklistStore(context.applicationContext)
|
||||
val previous = _lists.value.firstOrNull { it.url == target }
|
||||
scope.launch {
|
||||
try {
|
||||
val list = store.download(target)
|
||||
val list = store.download(target, previous)
|
||||
commit(store, listOf(list))
|
||||
} catch (e: Exception) {
|
||||
_error.value = e.message ?: e.javaClass.simpleName
|
||||
@@ -131,18 +129,20 @@ object Blocklist {
|
||||
if (_lists.value.isEmpty() || !_busy.compareAndSet(null, ALL_LISTS)) return false
|
||||
_error.value = null
|
||||
val store = BlocklistStore(context.applicationContext)
|
||||
val urls = _lists.value.map { it.url }
|
||||
val current = _lists.value
|
||||
scope.launch {
|
||||
try {
|
||||
val fresh = urls.mapNotNull { url ->
|
||||
val fresh = current.mapNotNull { list ->
|
||||
try {
|
||||
store.download(url)
|
||||
store.download(list.url, list)
|
||||
} catch (e: Exception) {
|
||||
if (_error.value == null) _error.value = e.message ?: e.javaClass.simpleName
|
||||
null
|
||||
}
|
||||
}
|
||||
commit(store, fresh)
|
||||
} catch (e: IOException) {
|
||||
_error.value = e.message ?: e.javaClass.simpleName
|
||||
} finally {
|
||||
_busy.value = null
|
||||
}
|
||||
@@ -169,35 +169,76 @@ object Blocklist {
|
||||
_enabled.value = store.enabled
|
||||
_custom.value = store.loadCustom()
|
||||
_lists.value = store.loadLists()
|
||||
val custom = _custom.value
|
||||
customHashes = LongArray(custom.size) { DomainHash.of(custom[it]) }.sortUnique()
|
||||
reloadListHashes(store)
|
||||
loaded = true
|
||||
}
|
||||
|
||||
private fun reloadListHashes(store: BlocklistStore) {
|
||||
listHashes = merge(_lists.value.map { store.loadListHashes(it.url) })
|
||||
combine()
|
||||
listHashes = mergeSorted(_lists.value.map { store.loadListHashes(it.url) })
|
||||
_total.value = unionSize(listHashes, customHashes)
|
||||
}
|
||||
|
||||
private fun combine() {
|
||||
private fun updateCustomHashes() {
|
||||
val custom = _custom.value
|
||||
hashes = if (custom.isEmpty()) {
|
||||
listHashes
|
||||
} else {
|
||||
merge(listOf(listHashes, LongArray(custom.size) { DomainHash.of(custom[it]) }))
|
||||
}
|
||||
_total.value = hashes.size
|
||||
customHashes = LongArray(custom.size) { DomainHash.of(custom[it]) }.sortUnique()
|
||||
_total.value = unionSize(listHashes, customHashes)
|
||||
}
|
||||
}
|
||||
|
||||
private fun merge(parts: List<LongArray>): LongArray {
|
||||
val nonEmpty = parts.filter { it.isNotEmpty() }
|
||||
if (nonEmpty.size <= 1) return nonEmpty.firstOrNull() ?: LongArray(0) // stored lists are already sorted
|
||||
val all = LongArray(nonEmpty.sumOf { it.size })
|
||||
var pos = 0
|
||||
nonEmpty.forEach { it.copyInto(all, pos); pos += it.size }
|
||||
return all.sortUnique()
|
||||
// True when the name or one of its parent domains is in either sorted hash set
|
||||
internal fun isBlockedIn(name: String, lists: LongArray, custom: LongArray): Boolean {
|
||||
if (lists.isEmpty() && custom.isEmpty()) return false
|
||||
val domain = name.trimEnd('.')
|
||||
var start = 0
|
||||
while (true) {
|
||||
val hash = DomainHash.of(domain, start)
|
||||
if (lists.binarySearch(hash) >= 0 || custom.binarySearch(hash) >= 0) return true
|
||||
val dot = domain.indexOf('.', start)
|
||||
if (dot < 0) return false
|
||||
start = dot + 1
|
||||
}
|
||||
}
|
||||
|
||||
// Number of distinct entries in both sorted sets; the custom set is small
|
||||
internal fun unionSize(lists: LongArray, custom: LongArray): Int =
|
||||
lists.size + custom.count { lists.binarySearch(it) < 0 }
|
||||
|
||||
// Merges sorted, duplicate-free arrays in linear time instead of sorting their concatenation
|
||||
internal fun mergeSorted(parts: List<LongArray>): LongArray {
|
||||
var arrays = parts.filter { it.isNotEmpty() }.map { if (it.isSortedUnique()) it else it.copyOf().sortUnique() }
|
||||
if (arrays.isEmpty()) return LongArray(0)
|
||||
while (arrays.size > 1) {
|
||||
arrays = arrays.chunked(2).map { if (it.size == 2) mergeTwo(it[0], it[1]) else it[0] }
|
||||
}
|
||||
return arrays[0]
|
||||
}
|
||||
|
||||
private fun mergeTwo(a: LongArray, b: LongArray): LongArray {
|
||||
val out = LongArray(a.size + b.size)
|
||||
var i = 0
|
||||
var j = 0
|
||||
var n = 0
|
||||
while (i < a.size && j < b.size) {
|
||||
val x = a[i]
|
||||
val y = b[j]
|
||||
when {
|
||||
x < y -> { out[n++] = x; i++ }
|
||||
x > y -> { out[n++] = y; j++ }
|
||||
else -> { out[n++] = x; i++; j++ }
|
||||
}
|
||||
}
|
||||
while (i < a.size) out[n++] = a[i++]
|
||||
while (j < b.size) out[n++] = b[j++]
|
||||
return if (n == out.size) out else out.copyOf(n)
|
||||
}
|
||||
|
||||
private fun LongArray.isSortedUnique(): Boolean {
|
||||
for (i in 1 until size) if (this[i - 1] >= this[i]) return false
|
||||
return true
|
||||
}
|
||||
|
||||
internal object DomainHash {
|
||||
private const val FNV_OFFSET = -3750763034362895579L // 0xcbf29ce484222325
|
||||
private const val FNV_PRIME = 1099511628211L
|
||||
@@ -290,22 +331,38 @@ private class BlocklistStore(context: Context) {
|
||||
fun deleteListFile(url: String) {
|
||||
binFile(url).delete()
|
||||
textFile(url).delete()
|
||||
sp.edit().remove(etagKey(url)).remove(modifiedKey(url)).apply()
|
||||
}
|
||||
|
||||
fun download(url: String): RemoteList {
|
||||
val request = runCatching { Request.Builder().url(url).build() }
|
||||
.getOrElse { throw IOException("Invalid URL") }
|
||||
// With the list already on disk the server is asked for a changed one only, so updating
|
||||
// a list that did not change costs a few hundred bytes instead of megabytes
|
||||
fun download(url: String, previous: RemoteList? = null): RemoteList {
|
||||
val builder = runCatching { Request.Builder().url(url) }.getOrElse { throw IOException("Invalid URL") }
|
||||
if (previous != null && binFile(url).exists()) {
|
||||
sp.getString(etagKey(url), null)?.let { builder.header("If-None-Match", it) }
|
||||
sp.getString(modifiedKey(url), null)?.let { builder.header("If-Modified-Since", it) }
|
||||
}
|
||||
|
||||
client.newCall(request).execute().use { response ->
|
||||
client.newCall(builder.build()).execute().use { response ->
|
||||
if (response.code == 304 && previous != null) return previous.copy(updated = System.currentTimeMillis())
|
||||
if (!response.isSuccessful) throw IOException("HTTP ${response.code}")
|
||||
val body = response.body ?: throw IOException("Empty response")
|
||||
val parsed = LongList()
|
||||
body.charStream().buffered().useLines { lines ->
|
||||
lines.forEach { line -> BlocklistParser.parseLine(line)?.let { parsed.add(DomainHash.of(it)) } }
|
||||
lines.forEach { line ->
|
||||
val domain = BlocklistParser.parseLine(line) ?: return@forEach
|
||||
// Far above the largest common lists; keeps a wrong URL from exhausting memory
|
||||
if (parsed.size >= MAX_LIST_DOMAINS) throw IOException("List too large")
|
||||
parsed.add(DomainHash.of(domain))
|
||||
}
|
||||
}
|
||||
val result = parsed.toArray().sortUnique()
|
||||
if (result.isEmpty()) throw IOException("No domains found")
|
||||
write(url, result)
|
||||
sp.edit()
|
||||
.putOrRemove(etagKey(url), response.header("ETag"))
|
||||
.putOrRemove(modifiedKey(url), response.header("Last-Modified"))
|
||||
.apply()
|
||||
return RemoteList(url, result.size, System.currentTimeMillis())
|
||||
}
|
||||
}
|
||||
@@ -332,6 +389,12 @@ private class BlocklistStore(context: Context) {
|
||||
return result
|
||||
}
|
||||
|
||||
private fun etagKey(url: String) = "etag_${hash(url)}"
|
||||
private fun modifiedKey(url: String) = "modified_${hash(url)}"
|
||||
|
||||
private fun SharedPreferences.Editor.putOrRemove(key: String, value: String?) =
|
||||
if (value == null) remove(key) else putString(key, value)
|
||||
|
||||
private fun binFile(url: String) = File(dir, "list_${hash(url)}.bin")
|
||||
private fun textFile(url: String) = File(dir, "list_${hash(url)}.txt")
|
||||
|
||||
@@ -339,9 +402,10 @@ private class BlocklistStore(context: Context) {
|
||||
.take(8).joinToString("") { "%02x".format(it) }
|
||||
|
||||
companion object {
|
||||
const val MAX_LIST_DOMAINS = 4_000_000
|
||||
|
||||
val client: OkHttpClient by lazy {
|
||||
OkHttpClient.Builder()
|
||||
.connectTimeout(15, TimeUnit.SECONDS)
|
||||
Http.client.newBuilder()
|
||||
.readTimeout(60, TimeUnit.SECONDS)
|
||||
.build()
|
||||
}
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
package cc.skysparkle.sparkledns
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.widget.Toast
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.animateContentSize
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
@@ -13,12 +17,15 @@ import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.itemsIndexed
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.ZeroCornerSize
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.AssistChip
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.FilledTonalButton
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
@@ -30,7 +37,6 @@ import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
@@ -39,6 +45,7 @@ import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.RectangleShape
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
@@ -47,9 +54,12 @@ import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.IOException
|
||||
import java.text.DateFormat
|
||||
import java.util.Date
|
||||
|
||||
@@ -65,17 +75,17 @@ fun BlocklistScreen(modifier: Modifier = Modifier) {
|
||||
val prefs = remember { Prefs(context) }
|
||||
var showNote by remember { mutableStateOf(!prefs.isHintDismissed(HINT_BLOCKLIST)) }
|
||||
|
||||
val enabled by Blocklist.enabled.collectAsState()
|
||||
val total by Blocklist.total.collectAsState()
|
||||
val custom by Blocklist.custom.collectAsState()
|
||||
val lists by Blocklist.lists.collectAsState()
|
||||
val enabled by Blocklist.enabled.collectAsStateWithLifecycle()
|
||||
val total by Blocklist.total.collectAsStateWithLifecycle()
|
||||
val custom by Blocklist.custom.collectAsStateWithLifecycle()
|
||||
val lists by Blocklist.lists.collectAsStateWithLifecycle()
|
||||
|
||||
var domainInput by rememberSaveable { mutableStateOf("") }
|
||||
var domainError by remember { mutableStateOf(false) }
|
||||
var urlInput by rememberSaveable { mutableStateOf("") }
|
||||
// Downloads live in Blocklist, so they keep running and stay visible across tab switches
|
||||
val busy by Blocklist.busy.collectAsState()
|
||||
val error by Blocklist.error.collectAsState()
|
||||
val busy by Blocklist.busy.collectAsStateWithLifecycle()
|
||||
val error by Blocklist.error.collectAsStateWithLifecycle()
|
||||
val lastError = remember { arrayOf("") } // kept while the card animates out
|
||||
error?.let { lastError[0] = it }
|
||||
|
||||
@@ -83,9 +93,11 @@ fun BlocklistScreen(modifier: Modifier = Modifier) {
|
||||
val input = domainInput
|
||||
if (input.isBlank()) return
|
||||
scope.launch {
|
||||
val ok = withContext(Dispatchers.IO) { Blocklist.addCustom(context, input) }
|
||||
domainError = !ok
|
||||
if (ok) domainInput = ""
|
||||
val result = withContext(Dispatchers.IO) { tryEdit { Blocklist.addCustom(context, input) } }
|
||||
result.onSuccess { ok ->
|
||||
domainError = !ok
|
||||
if (ok) domainInput = ""
|
||||
}.onFailure { showEditError(context, it) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,56 +106,66 @@ fun BlocklistScreen(modifier: Modifier = Modifier) {
|
||||
if (url.isNotEmpty() && Blocklist.download(context, url)) urlInput = ""
|
||||
}
|
||||
|
||||
Column(
|
||||
modifier = modifier
|
||||
.fillMaxSize()
|
||||
.verticalScroll(rememberScrollState())
|
||||
.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
// Own domains are lazy rows, so hundreds of them are not all composed when the tab opens.
|
||||
// Together they look like the card they used to be in: same color and shape, split per row.
|
||||
val cardColor = CardDefaults.cardColors().containerColor
|
||||
val cardShape = MaterialTheme.shapes.medium
|
||||
val cardTop = cardShape.copy(bottomStart = ZeroCornerSize, bottomEnd = ZeroCornerSize)
|
||||
val cardBottom = cardShape.copy(topStart = ZeroCornerSize, topEnd = ZeroCornerSize)
|
||||
|
||||
LazyColumn(
|
||||
modifier = modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
) {
|
||||
Card(Modifier.fillMaxWidth()) {
|
||||
Row(Modifier.padding(16.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
IconBadge(
|
||||
R.drawable.ic_tab_block,
|
||||
tint = if (enabled) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.outline,
|
||||
size = 52.dp,
|
||||
)
|
||||
Spacer(Modifier.width(16.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(stringResource(R.string.bl_title), style = MaterialTheme.typography.titleMedium)
|
||||
Text(
|
||||
formatCount(total.toLong()),
|
||||
style = MaterialTheme.typography.headlineSmall,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
)
|
||||
Text(
|
||||
stringResource(R.string.bl_total_label),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
item(key = "summary") {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Card(Modifier.fillMaxWidth()) {
|
||||
Row(Modifier.padding(16.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
IconBadge(
|
||||
R.drawable.ic_tab_block,
|
||||
tint = if (enabled) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.outline,
|
||||
size = 52.dp,
|
||||
)
|
||||
Spacer(Modifier.width(16.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(stringResource(R.string.bl_title), style = MaterialTheme.typography.titleMedium)
|
||||
Text(
|
||||
formatCount(total.toLong()),
|
||||
style = MaterialTheme.typography.headlineSmall,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
)
|
||||
Text(
|
||||
stringResource(R.string.bl_total_label),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
Switch(checked = enabled, onCheckedChange = { Blocklist.setEnabled(context, it) })
|
||||
}
|
||||
}
|
||||
|
||||
AnimatedVisibility(visible = showNote, enter = Motion.expandIn, exit = Motion.collapseOut) {
|
||||
HintCard(
|
||||
stringResource(R.string.bl_note),
|
||||
icon = R.drawable.ic_tab_info,
|
||||
onDismiss = {
|
||||
showNote = false
|
||||
prefs.dismissHint(HINT_BLOCKLIST)
|
||||
},
|
||||
)
|
||||
}
|
||||
Switch(checked = enabled, onCheckedChange = { Blocklist.setEnabled(context, it) })
|
||||
|
||||
SectionHeader(stringResource(R.string.bl_my), icon = R.drawable.ic_tab_block)
|
||||
}
|
||||
}
|
||||
|
||||
AnimatedVisibility(visible = showNote, enter = Motion.expandIn, exit = Motion.collapseOut) {
|
||||
HintCard(
|
||||
stringResource(R.string.bl_note),
|
||||
icon = R.drawable.ic_tab_info,
|
||||
onDismiss = {
|
||||
showNote = false
|
||||
prefs.dismissHint(HINT_BLOCKLIST)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
SectionHeader(stringResource(R.string.bl_my), icon = R.drawable.ic_tab_block)
|
||||
|
||||
Card(Modifier.fillMaxWidth()) {
|
||||
item(key = "custom") {
|
||||
Column(
|
||||
Modifier
|
||||
.animateContentSize(Motion.size)
|
||||
.padding(vertical = 8.dp)
|
||||
.padding(top = 12.dp)
|
||||
.fillMaxWidth()
|
||||
.background(cardColor, if (custom.isEmpty()) cardShape else cardTop)
|
||||
.padding(top = 8.dp, bottom = if (custom.isEmpty()) 8.dp else 0.dp)
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),
|
||||
@@ -182,117 +204,131 @@ fun BlocklistScreen(modifier: Modifier = Modifier) {
|
||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
)
|
||||
}
|
||||
custom.forEach { domain ->
|
||||
InsetDivider(16)
|
||||
Row(
|
||||
modifier = Modifier.padding(start = 16.dp, end = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
}
|
||||
}
|
||||
|
||||
itemsIndexed(custom, key = { _, domain -> "domain:$domain" }, contentType = { _, _ -> "domain" }) { index, domain ->
|
||||
val last = index == custom.lastIndex
|
||||
Column(
|
||||
Modifier
|
||||
.animateItem()
|
||||
.fillMaxWidth()
|
||||
.background(cardColor, if (last) cardBottom else RectangleShape)
|
||||
.padding(bottom = if (last) 8.dp else 0.dp)
|
||||
) {
|
||||
InsetDivider(16)
|
||||
Row(
|
||||
modifier = Modifier.padding(start = 16.dp, end = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(domain, modifier = Modifier.weight(1f), maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
IconButton(onClick = { scope.editBlocklist(context) { Blocklist.removeCustom(context, domain) } }) {
|
||||
Icon(painterResource(R.drawable.ic_delete), stringResource(R.string.delete), Modifier.size(20.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
item(key = "lists") {
|
||||
Column(Modifier.padding(top = 12.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
SectionHeader(
|
||||
stringResource(R.string.bl_lists),
|
||||
icon = R.drawable.ic_list,
|
||||
action = {
|
||||
TextButton(
|
||||
onClick = { Blocklist.updateAll(context) },
|
||||
enabled = lists.isNotEmpty() && busy == null,
|
||||
) {
|
||||
Icon(painterResource(R.drawable.ic_refresh), contentDescription = null, modifier = Modifier.size(18.dp))
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(stringResource(if (busy == Blocklist.ALL_LISTS) R.string.bl_updating else R.string.bl_update_all))
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
Card(Modifier.fillMaxWidth()) {
|
||||
Column(
|
||||
Modifier
|
||||
.animateContentSize(Motion.size)
|
||||
.padding(vertical = 8.dp)
|
||||
) {
|
||||
Text(domain, modifier = Modifier.weight(1f), maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
IconButton(onClick = { scope.launch(Dispatchers.IO) { Blocklist.removeCustom(context, domain) } }) {
|
||||
Icon(painterResource(R.drawable.ic_delete), stringResource(R.string.delete), Modifier.size(20.dp))
|
||||
lists.forEachIndexed { index, list ->
|
||||
if (index > 0) InsetDivider(68)
|
||||
ListRow(
|
||||
list = list,
|
||||
updating = busy == list.url || busy == Blocklist.ALL_LISTS,
|
||||
actionsEnabled = busy == null,
|
||||
onRefresh = { Blocklist.download(context, list.url) },
|
||||
onDelete = { scope.editBlocklist(context) { Blocklist.removeList(context, list.url) } },
|
||||
)
|
||||
}
|
||||
if (lists.isNotEmpty()) InsetDivider(16)
|
||||
Row(
|
||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value = urlInput,
|
||||
onValueChange = { urlInput = it },
|
||||
placeholder = { Text(stringResource(R.string.bl_list_url), maxLines = 1) },
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri, imeAction = ImeAction.Done),
|
||||
keyboardActions = KeyboardActions(onDone = { if (busy == null) addList() }),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
FilledTonalButton(
|
||||
onClick = ::addList,
|
||||
enabled = urlInput.isNotBlank() && busy == null,
|
||||
) {
|
||||
Icon(painterResource(R.drawable.ic_add), contentDescription = null, modifier = Modifier.size(18.dp))
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(stringResource(R.string.add))
|
||||
}
|
||||
}
|
||||
// A new list being added has no row yet, so its progress shows under the input
|
||||
val addingNew = busy != null && busy != Blocklist.ALL_LISTS && lists.none { it.url == busy }
|
||||
AnimatedVisibility(visible = addingNew, enter = Motion.expandIn, exit = Motion.collapseOut) {
|
||||
LinearProgressIndicator(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 4.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SectionHeader(
|
||||
stringResource(R.string.bl_lists),
|
||||
icon = R.drawable.ic_list,
|
||||
action = {
|
||||
TextButton(
|
||||
onClick = { Blocklist.updateAll(context) },
|
||||
enabled = lists.isNotEmpty() && busy == null,
|
||||
) {
|
||||
Icon(painterResource(R.drawable.ic_refresh), contentDescription = null, modifier = Modifier.size(18.dp))
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(stringResource(if (busy == Blocklist.ALL_LISTS) R.string.bl_updating else R.string.bl_update_all))
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
Card(Modifier.fillMaxWidth()) {
|
||||
Column(
|
||||
Modifier
|
||||
.animateContentSize(Motion.size)
|
||||
.padding(vertical = 8.dp)
|
||||
) {
|
||||
lists.forEachIndexed { index, list ->
|
||||
if (index > 0) InsetDivider(68)
|
||||
ListRow(
|
||||
list = list,
|
||||
updating = busy == list.url || busy == Blocklist.ALL_LISTS,
|
||||
actionsEnabled = busy == null,
|
||||
onRefresh = { Blocklist.download(context, list.url) },
|
||||
onDelete = { scope.launch(Dispatchers.IO) { Blocklist.removeList(context, list.url) } },
|
||||
)
|
||||
}
|
||||
if (lists.isNotEmpty()) InsetDivider(16)
|
||||
Row(
|
||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value = urlInput,
|
||||
onValueChange = { urlInput = it },
|
||||
placeholder = { Text(stringResource(R.string.bl_list_url), maxLines = 1) },
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri, imeAction = ImeAction.Done),
|
||||
keyboardActions = KeyboardActions(onDone = { if (busy == null) addList() }),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
FilledTonalButton(
|
||||
onClick = ::addList,
|
||||
enabled = urlInput.isNotBlank() && busy == null,
|
||||
) {
|
||||
Icon(painterResource(R.drawable.ic_add), contentDescription = null, modifier = Modifier.size(18.dp))
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(stringResource(R.string.add))
|
||||
val missingPresets = Presets.filter { (_, url) -> lists.none { it.url == url } }
|
||||
AnimatedVisibility(visible = missingPresets.isNotEmpty(), enter = Motion.expandIn, exit = Motion.collapseOut) {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
SectionHeader(stringResource(R.string.bl_presets))
|
||||
Row(
|
||||
modifier = Modifier.horizontalScroll(rememberScrollState()),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
missingPresets.forEach { (name, url) ->
|
||||
AssistChip(
|
||||
onClick = { Blocklist.download(context, url) },
|
||||
enabled = busy == null,
|
||||
leadingIcon = {
|
||||
Icon(painterResource(R.drawable.ic_add), contentDescription = null, modifier = Modifier.size(18.dp))
|
||||
},
|
||||
label = { Text(if (busy == url) stringResource(R.string.bl_updating) else name) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// A new list being added has no row yet, so its progress shows under the input
|
||||
val addingNew = busy != null && busy != Blocklist.ALL_LISTS && lists.none { it.url == busy }
|
||||
AnimatedVisibility(visible = addingNew, enter = Motion.expandIn, exit = Motion.collapseOut) {
|
||||
LinearProgressIndicator(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 4.dp),
|
||||
|
||||
AnimatedVisibility(visible = error != null, enter = Motion.expandIn, exit = Motion.collapseOut) {
|
||||
HintCard(
|
||||
stringResource(R.string.bl_download_failed, lastError[0]),
|
||||
icon = R.drawable.ic_alert,
|
||||
tint = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val missingPresets = Presets.filter { (_, url) -> lists.none { it.url == url } }
|
||||
AnimatedVisibility(visible = missingPresets.isNotEmpty(), enter = Motion.expandIn, exit = Motion.collapseOut) {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
SectionHeader(stringResource(R.string.bl_presets))
|
||||
Row(
|
||||
modifier = Modifier.horizontalScroll(rememberScrollState()),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
missingPresets.forEach { (name, url) ->
|
||||
AssistChip(
|
||||
onClick = { Blocklist.download(context, url) },
|
||||
enabled = busy == null,
|
||||
leadingIcon = {
|
||||
Icon(painterResource(R.drawable.ic_add), contentDescription = null, modifier = Modifier.size(18.dp))
|
||||
},
|
||||
label = { Text(if (busy == url) stringResource(R.string.bl_updating) else name) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
AnimatedVisibility(visible = error != null, enter = Motion.expandIn, exit = Motion.collapseOut) {
|
||||
HintCard(
|
||||
stringResource(R.string.bl_download_failed, lastError[0]),
|
||||
icon = R.drawable.ic_alert,
|
||||
tint = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -358,4 +394,21 @@ private fun ListRow(
|
||||
}
|
||||
}
|
||||
|
||||
// Blocklist edits write to storage, which can fail (a full disk, for one)
|
||||
internal inline fun <T> tryEdit(action: () -> T): Result<T> =
|
||||
try {
|
||||
Result.success(action())
|
||||
} catch (e: IOException) {
|
||||
Result.failure(e)
|
||||
}
|
||||
|
||||
internal fun CoroutineScope.editBlocklist(context: Context, action: () -> Unit) = launch {
|
||||
withContext(Dispatchers.IO) { tryEdit(action) }.onFailure { showEditError(context, it) }
|
||||
}
|
||||
|
||||
internal fun showEditError(context: Context, error: Throwable) {
|
||||
val reason = error.message ?: error.javaClass.simpleName
|
||||
Toast.makeText(context, context.getString(R.string.test_fail, reason), Toast.LENGTH_LONG).show()
|
||||
}
|
||||
|
||||
private const val HINT_BLOCKLIST = "blocklist"
|
||||
|
||||
@@ -3,6 +3,8 @@ package cc.skysparkle.sparkledns
|
||||
import android.app.Application
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import android.os.Process
|
||||
import android.os.StrictMode
|
||||
import java.io.File
|
||||
import java.io.PrintWriter
|
||||
import java.io.StringWriter
|
||||
@@ -10,8 +12,29 @@ import java.io.StringWriter
|
||||
class SparkleApp : Application() {
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
if (BuildConfig.DEBUG) enableStrictMode()
|
||||
CrashLog.install(this)
|
||||
Thread({ runCatching { Blocklist.reload(this) } }, "blocklist-load").start()
|
||||
Thread({
|
||||
// Reads what the first screen needs before it asks, so its first frame does not wait on storage
|
||||
Prefs(this).providerId
|
||||
CrashLog.preload(this)
|
||||
// Lists can hold millions of entries; loading them should not take CPU from the first frames
|
||||
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND)
|
||||
runCatching { Blocklist.reload(this) }
|
||||
}, "startup-load").start()
|
||||
}
|
||||
|
||||
// The VPN keeps the process running long after the screens are gone; decoded app icons
|
||||
// (up to 10 MB) can be rendered again the next time the Apps tab opens
|
||||
override fun onTrimMemory(level: Int) {
|
||||
super.onTrimMemory(level)
|
||||
if (level >= TRIM_MEMORY_UI_HIDDEN) clearAppIconCache()
|
||||
}
|
||||
|
||||
// Debug builds only: logs disk and network access on the main thread, leaked closeables and the like
|
||||
private fun enableStrictMode() {
|
||||
StrictMode.setThreadPolicy(StrictMode.ThreadPolicy.Builder().detectAll().penaltyLog().build())
|
||||
StrictMode.setVmPolicy(StrictMode.VmPolicy.Builder().detectAll().penaltyLog().build())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,10 +58,24 @@ object CrashLog {
|
||||
}
|
||||
}
|
||||
|
||||
fun read(context: Context): String? =
|
||||
File(context.filesDir, FILE_NAME).takeIf { it.exists() }?.readText()
|
||||
@Volatile
|
||||
private var preloaded = false
|
||||
|
||||
@Volatile
|
||||
private var report: String? = null
|
||||
|
||||
fun preload(context: Context) {
|
||||
report = load(context)
|
||||
preloaded = true
|
||||
}
|
||||
|
||||
fun read(context: Context): String? = if (preloaded) report else load(context)
|
||||
|
||||
fun clear(context: Context) {
|
||||
report = null
|
||||
File(context.filesDir, FILE_NAME).delete()
|
||||
}
|
||||
|
||||
private fun load(context: Context): String? =
|
||||
runCatching { File(context.filesDir, FILE_NAME).takeIf { it.exists() }?.readText() }.getOrNull()
|
||||
}
|
||||
|
||||
@@ -3,7 +3,10 @@ package cc.skysparkle.sparkledns
|
||||
import android.os.SystemClock
|
||||
|
||||
// TTL-aware LRU cache of DNS responses, keyed by the question section
|
||||
class DnsCache(private val maxEntries: Int = 2000) {
|
||||
class DnsCache(
|
||||
private val maxEntries: Int = 2000,
|
||||
private val clock: () -> Long = SystemClock::elapsedRealtime,
|
||||
) {
|
||||
|
||||
private class Entry(
|
||||
val response: ByteArray,
|
||||
@@ -19,7 +22,7 @@ class DnsCache(private val maxEntries: Int = 2000) {
|
||||
|
||||
fun get(query: ByteArray): ByteArray? {
|
||||
val key = keyOf(query) ?: return null
|
||||
val now = SystemClock.elapsedRealtime()
|
||||
val now = clock()
|
||||
val entry = synchronized(map) {
|
||||
val e = map[key] ?: return null
|
||||
if (now >= e.expiresAt) {
|
||||
@@ -47,7 +50,7 @@ class DnsCache(private val maxEntries: Int = 2000) {
|
||||
val ttl = minOf(minTtl, MAX_TTL)
|
||||
if (ttl <= 0) return
|
||||
|
||||
val now = SystemClock.elapsedRealtime()
|
||||
val now = clock()
|
||||
val entry = Entry(response.copyOf(), records.first, records.second, now, now + ttl * 1000L)
|
||||
synchronized(map) { map[key] = entry }
|
||||
}
|
||||
|
||||
@@ -11,9 +11,11 @@ import android.service.quicksettings.Tile
|
||||
import android.service.quicksettings.TileService
|
||||
import android.util.Log
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.MainScope
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
|
||||
|
||||
class DnsTileService : TileService() {
|
||||
@@ -32,7 +34,12 @@ class DnsTileService : TileService() {
|
||||
override fun onStartListening() {
|
||||
listening?.cancel()
|
||||
listening = MainScope().also { scope ->
|
||||
scope.launch { DohVpnService.active.collect { updateTile() } }
|
||||
scope.launch {
|
||||
// The tile can start a fresh process: read settings from storage off the main thread,
|
||||
// which also leaves them in memory for onClick
|
||||
val prefs = withContext(Dispatchers.IO) { Prefs(applicationContext).also { it.providerId } }
|
||||
DohVpnService.active.collect { updateTile(prefs) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,13 +68,13 @@ class DnsTileService : TileService() {
|
||||
}
|
||||
}
|
||||
|
||||
private fun updateTile() {
|
||||
private fun updateTile(prefs: Prefs) {
|
||||
val tile = qsTile ?: return
|
||||
val active = DohVpnService.active.value
|
||||
tile.state = if (active != null) Tile.STATE_ACTIVE else Tile.STATE_INACTIVE
|
||||
tile.label = getString(R.string.app_name)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
tile.subtitle = (active ?: Prefs(this).resolve()).displayName(this)
|
||||
tile.subtitle = (active ?: prefs.resolve()).displayName(this)
|
||||
}
|
||||
tile.updateTile()
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package cc.skysparkle.sparkledns
|
||||
|
||||
import android.content.Context
|
||||
import android.net.ConnectivityManager
|
||||
import android.net.Network
|
||||
import android.net.http.HttpEngine
|
||||
import android.net.http.HttpException
|
||||
import android.net.http.UploadDataProvider
|
||||
@@ -10,10 +12,10 @@ import android.net.http.UrlResponseInfo
|
||||
import android.os.Build
|
||||
import android.util.Log
|
||||
import androidx.annotation.RequiresApi
|
||||
import okhttp3.ConnectionPool
|
||||
import okhttp3.Dns
|
||||
import okhttp3.HttpUrl.Companion.toHttpUrl
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import java.io.ByteArrayOutputStream
|
||||
@@ -27,6 +29,7 @@ import java.util.concurrent.ExecutionException
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.TimeoutException
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
private const val DNS_MESSAGE = "application/dns-message"
|
||||
private const val MAX_DNS_SIZE = 65535
|
||||
@@ -36,17 +39,37 @@ private const val TAG = "SparkleDNS"
|
||||
// everything else and older devices use OkHttp with HTTP/2.
|
||||
class DohClient(context: Context, provider: DohProvider) {
|
||||
|
||||
private val transport: Transport = createTransport(context.applicationContext, provider)
|
||||
private val appContext = context.applicationContext
|
||||
|
||||
val lastProtocol: String? get() = transport.lastProtocol
|
||||
// Built on the first query, i.e. on a worker thread: setting up HttpEngine takes long enough
|
||||
// to stall the main thread, where the VPN service creates this client
|
||||
private val transport = lazy { createTransport(appContext, provider) }
|
||||
private val closed = AtomicBoolean(false)
|
||||
private val released = AtomicBoolean(false)
|
||||
|
||||
val lastProtocol: String? get() = if (transport.isInitialized()) transport.value.lastProtocol else null
|
||||
|
||||
fun query(message: ByteArray): ByteArray {
|
||||
val body = transport.query(message)
|
||||
if (closed.get()) throw IOException("Client closed")
|
||||
val active = transport.value
|
||||
// shutdown() may have run while the transport was being built
|
||||
if (closed.get()) {
|
||||
release()
|
||||
throw IOException("Client closed")
|
||||
}
|
||||
val body = active.query(message)
|
||||
if (!DnsMessage.isResponse(body)) throw IOException("Invalid DNS response")
|
||||
return body
|
||||
}
|
||||
|
||||
fun shutdown() = transport.shutdown()
|
||||
fun shutdown() {
|
||||
closed.set(true)
|
||||
if (transport.isInitialized()) release()
|
||||
}
|
||||
|
||||
private fun release() {
|
||||
if (released.compareAndSet(false, true)) transport.value.shutdown()
|
||||
}
|
||||
|
||||
private fun createTransport(context: Context, provider: DohProvider): Transport {
|
||||
if (provider.http3 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
|
||||
@@ -56,7 +79,7 @@ class DohClient(context: Context, provider: DohProvider) {
|
||||
Log.w(TAG, "HttpEngine unavailable, falling back to HTTP/2", e)
|
||||
}
|
||||
}
|
||||
return OkHttpTransport(provider)
|
||||
return OkHttpTransport(context, provider)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,17 +89,42 @@ private interface Transport {
|
||||
fun shutdown()
|
||||
}
|
||||
|
||||
private class OkHttpTransport(private val provider: DohProvider) : Transport {
|
||||
private class OkHttpTransport(context: Context, private val provider: DohProvider) : Transport {
|
||||
|
||||
private val url by lazy { provider.url.toHttpUrl() }
|
||||
|
||||
private val client = OkHttpClient.Builder()
|
||||
// Its own connection pool, so stopping a session drops only DoH connections
|
||||
private val pool = ConnectionPool()
|
||||
|
||||
private val client = Http.client.newBuilder()
|
||||
.connectionPool(pool)
|
||||
.dns(BootstrapDns(provider.bootstrap))
|
||||
.connectTimeout(5, TimeUnit.SECONDS)
|
||||
.readTimeout(5, TimeUnit.SECONDS)
|
||||
.callTimeout(8, TimeUnit.SECONDS)
|
||||
.build()
|
||||
|
||||
// Pooled connections still belong to the previous network after a switch between Wi-Fi and
|
||||
// mobile data, and lookups over them can hang until the timeout. Drop them whenever the default
|
||||
// network changes. (HttpEngine for HTTP/3 follows network changes on its own.)
|
||||
private val connectivity = context.getSystemService(ConnectivityManager::class.java)
|
||||
private val networkCallback = object : ConnectivityManager.NetworkCallback() {
|
||||
private var current: Network? = null
|
||||
|
||||
override fun onAvailable(network: Network) {
|
||||
if (current != null && current != network) pool.evictAll()
|
||||
current = network
|
||||
}
|
||||
|
||||
override fun onLost(network: Network) {
|
||||
if (network != current) return
|
||||
current = null
|
||||
pool.evictAll()
|
||||
}
|
||||
}
|
||||
private val watchingNetwork =
|
||||
connectivity != null && runCatching { connectivity.registerDefaultNetworkCallback(networkCallback) }.isSuccess
|
||||
|
||||
@Volatile
|
||||
override var lastProtocol: String? = null
|
||||
|
||||
@@ -97,8 +145,8 @@ private class OkHttpTransport(private val provider: DohProvider) : Transport {
|
||||
}
|
||||
|
||||
override fun shutdown() {
|
||||
client.dispatcher.executorService.shutdown()
|
||||
client.connectionPool.evictAll()
|
||||
if (watchingNetwork) runCatching { connectivity?.unregisterNetworkCallback(networkCallback) }
|
||||
pool.evictAll()
|
||||
}
|
||||
|
||||
private companion object {
|
||||
|
||||
@@ -9,6 +9,8 @@ import android.content.pm.ServiceInfo
|
||||
import android.graphics.drawable.Icon
|
||||
import android.net.VpnService
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.ParcelFileDescriptor
|
||||
import android.os.SystemClock
|
||||
import android.system.ErrnoException
|
||||
@@ -32,6 +34,14 @@ private const val WORKERS = 16
|
||||
private const val TAG = "SparkleDNS"
|
||||
private const val CHANNEL_ID = "vpn_status"
|
||||
private const val NOTIFICATION_ID = 1
|
||||
private const val MAX_BAD_PACKETS = 100
|
||||
|
||||
// Android's resolver retries after 5 s, so an older lookup no longer has anyone waiting for it
|
||||
private const val QUEUE_TIMEOUT_MS = 5000L
|
||||
|
||||
// Closing TLS connections writes to the network, so sessions release their DoH client here
|
||||
// rather than on the main thread, where the service stops them
|
||||
private val closer = Executors.newSingleThreadExecutor { r -> Thread(r, "doh-close").apply { isDaemon = true } }
|
||||
|
||||
// Local VPN that routes only the fake DNS address into the tunnel; all other traffic is untouched
|
||||
class DohVpnService : VpnService() {
|
||||
@@ -50,6 +60,7 @@ class DohVpnService : VpnService() {
|
||||
}
|
||||
|
||||
private var session: Session? = null
|
||||
private val mainHandler = Handler(Looper.getMainLooper())
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
if (intent?.action == ACTION_STOP) {
|
||||
@@ -97,18 +108,22 @@ class DohVpnService : VpnService() {
|
||||
.allowFamily(OsConstants.AF_INET6)
|
||||
// The app itself bypasses the VPN so it can resolve and reach the DoH server
|
||||
runCatching { builder.addDisallowedApplication(packageName) }
|
||||
excluded.forEach { runCatching { builder.addDisallowedApplication(it) } }
|
||||
.onFailure { Log.e(TAG, "Cannot exclude the app itself from the VPN", it) }
|
||||
// Apps uninstalled since they were picked are simply skipped
|
||||
excluded.forEach { app ->
|
||||
runCatching { builder.addDisallowedApplication(app) }.onFailure { Log.i(TAG, "Not excluding $app: $it") }
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) builder.setMetered(false)
|
||||
|
||||
// The new interface replaces the old one in place, so DNS never leaks during a server switch
|
||||
val tun = runCatching { builder.establish() }.getOrNull()
|
||||
val tun = runCatching { builder.establish() }.onFailure { Log.e(TAG, "Cannot establish the VPN", it) }.getOrNull()
|
||||
val previous = session
|
||||
if (tun == null) {
|
||||
stopSession()
|
||||
stopSelf()
|
||||
return
|
||||
}
|
||||
session = Session(tun, DohClient(this, provider)).also { it.start() }
|
||||
session = Session(tun, DohClient(this, provider), ::onSessionFailed).also { it.start() }
|
||||
runCatching { previous?.stop() }
|
||||
|
||||
_active.value = provider
|
||||
@@ -127,6 +142,17 @@ class DohVpnService : VpnService() {
|
||||
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) {
|
||||
val manager = getSystemService(NotificationManager::class.java) ?: return
|
||||
manager.createNotificationChannel(
|
||||
@@ -177,6 +203,7 @@ class DohVpnService : VpnService() {
|
||||
private class Session(
|
||||
private val tun: ParcelFileDescriptor,
|
||||
private val doh: DohClient,
|
||||
private val onFailure: (Session) -> Unit,
|
||||
) {
|
||||
private val alive = AtomicBoolean(true)
|
||||
private val pool = Executors.newFixedThreadPool(WORKERS)
|
||||
@@ -189,8 +216,14 @@ private class Session(
|
||||
fun stop() {
|
||||
if (!alive.getAndSet(false)) return
|
||||
pool.shutdownNow()
|
||||
doh.shutdown()
|
||||
runCatching { tun.close() }
|
||||
closer.execute {
|
||||
try {
|
||||
doh.shutdown()
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "DoH client shutdown failed", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun readLoop() {
|
||||
@@ -201,26 +234,48 @@ private class Session(
|
||||
events = OsConstants.POLLIN.toShort()
|
||||
}
|
||||
|
||||
var badPackets = 0
|
||||
|
||||
while (alive.get()) {
|
||||
try {
|
||||
val n = try {
|
||||
if (Os.poll(arrayOf(pollFd), 500) <= 0) continue
|
||||
val n = input.read(buf)
|
||||
if (n < 0) break
|
||||
val query = Packet.parseDnsQuery(buf, n) ?: continue
|
||||
dispatch(query)
|
||||
input.read(buf)
|
||||
} catch (e: ErrnoException) {
|
||||
if (e.errno != OsConstants.EINTR) break
|
||||
} catch (_: IOException) {
|
||||
break
|
||||
} catch (_: RejectedExecutionException) {
|
||||
break
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Tunnel reader failed", e)
|
||||
break
|
||||
if (e.errno == OsConstants.EINTR) continue
|
||||
readerFailed(e)
|
||||
return
|
||||
} catch (e: IOException) {
|
||||
readerFailed(e)
|
||||
return
|
||||
}
|
||||
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
|
||||
private fun dispatch(query: UdpPacket) {
|
||||
val question = DnsMessage.question(query.payload)
|
||||
@@ -235,12 +290,21 @@ private class Session(
|
||||
QueryLog.add(question, QueryStatus.CACHED, 0)
|
||||
return
|
||||
}
|
||||
pool.execute { handle(query, question) }
|
||||
val queued = SystemClock.elapsedRealtime()
|
||||
pool.execute { handle(query, question, queued) }
|
||||
}
|
||||
|
||||
private fun handle(query: UdpPacket, question: DnsMessage.Question?) {
|
||||
private fun handle(query: UdpPacket, question: DnsMessage.Question?, queued: Long) {
|
||||
try {
|
||||
val start = SystemClock.elapsedRealtime()
|
||||
// On a slow network lookups pile up behind the workers. Answer the stale ones with
|
||||
// SERVFAIL at once instead of spending a worker on them, so the queue drains.
|
||||
if (start - queued > QUEUE_TIMEOUT_MS) {
|
||||
if (!alive.get()) return
|
||||
QueryLog.add(question, QueryStatus.FAILED, (start - queued).toInt())
|
||||
DnsMessage.servfail(query.payload)?.let { write(query, it) }
|
||||
return
|
||||
}
|
||||
var status = QueryStatus.OK
|
||||
val answer = try {
|
||||
doh.query(query.payload).also { cache.put(query.payload, it) }
|
||||
@@ -263,7 +327,9 @@ private class Session(
|
||||
val packet = Packet.buildReply(query, DnsMessage.withId(payload, query.payload))
|
||||
try {
|
||||
synchronized(output) { output.write(packet) }
|
||||
} catch (_: IOException) {
|
||||
} catch (e: IOException) {
|
||||
// Expected while the session is being stopped
|
||||
if (alive.get()) Log.w(TAG, "Cannot write an answer to the tunnel", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
package cc.skysparkle.sparkledns
|
||||
|
||||
import okhttp3.OkHttpClient
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
// Base for every OkHttp client in the app. Clients made with newBuilder() share its dispatcher
|
||||
// and thread pools, and its connection pool unless they bring their own.
|
||||
internal object Http {
|
||||
val client: OkHttpClient by lazy {
|
||||
OkHttpClient.Builder()
|
||||
.connectTimeout(15, TimeUnit.SECONDS)
|
||||
.build()
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,8 @@ import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.ConnectivityManager
|
||||
import android.net.LinkProperties
|
||||
import android.net.Network
|
||||
import android.net.Uri
|
||||
import android.net.VpnService
|
||||
import android.os.Build
|
||||
@@ -66,11 +68,11 @@ import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.darkColorScheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.produceState
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.Saver
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
@@ -87,8 +89,14 @@ import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.channels.awaitClose
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.callbackFlow
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.flowOf
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
|
||||
@@ -114,38 +122,42 @@ private val ProtectedContainer = Color(0xFF16233A)
|
||||
|
||||
private class TestResult(val ok: Boolean, val text: String)
|
||||
|
||||
// How long a tap on Connect, Disconnect or Switch blocks further taps if the VPN state never changes
|
||||
private const val BUSY_TIMEOUT_MS = 5000L
|
||||
|
||||
// Keeps test and sync results across rotation and process death
|
||||
private val TestResultSaver = Saver<TestResult?, String>(
|
||||
save = { result -> result?.let { (if (it.ok) "1" else "0") + it.text } },
|
||||
restore = { saved -> TestResult(saved.startsWith("1"), saved.drop(1)) },
|
||||
)
|
||||
|
||||
@Composable
|
||||
fun HomeScreen(modifier: Modifier = Modifier) {
|
||||
val context = LocalContext.current
|
||||
val prefs = remember { Prefs(context) }
|
||||
val active by DohVpnService.active.collectAsState()
|
||||
val active by DohVpnService.active.collectAsStateWithLifecycle()
|
||||
val running = active != null
|
||||
val scope = rememberCoroutineScope()
|
||||
val stats = rememberLiveStats()
|
||||
|
||||
var selected by remember { mutableStateOf(prefs.providerId) }
|
||||
val servers by ServerList.servers.collectAsState()
|
||||
val servers by ServerList.servers.collectAsStateWithLifecycle()
|
||||
var syncing by remember { mutableStateOf(false) }
|
||||
var syncResult by remember { mutableStateOf<TestResult?>(null) }
|
||||
var shownSync by remember { mutableStateOf<TestResult?>(null) }
|
||||
var syncResult by rememberSaveable(stateSaver = TestResultSaver) { mutableStateOf<TestResult?>(null) }
|
||||
var shownSync by rememberSaveable(stateSaver = TestResultSaver) { mutableStateOf<TestResult?>(null) }
|
||||
var customUrl by remember { mutableStateOf(prefs.customUrl) }
|
||||
var customBootstrap by remember { mutableStateOf(prefs.customBootstrap) }
|
||||
var customHttp3 by remember { mutableStateOf(prefs.customHttp3) }
|
||||
var testResult by remember { mutableStateOf<TestResult?>(null) }
|
||||
var shownResult by remember { mutableStateOf<TestResult?>(null) } // kept while the card animates out
|
||||
var testResult by rememberSaveable(stateSaver = TestResultSaver) { mutableStateOf<TestResult?>(null) }
|
||||
var shownResult by rememberSaveable(stateSaver = TestResultSaver) { mutableStateOf<TestResult?>(null) } // kept while the card animates out
|
||||
var testing by remember { mutableStateOf(false) }
|
||||
val crashReport = remember { CrashLog.read(context) }
|
||||
// Strict Private DNS makes Android ignore the VPN's DNS server; re-checked while Home is open
|
||||
val privateDnsHost by produceState<String?>(null) {
|
||||
while (true) {
|
||||
value = readPrivateDnsHost(context)
|
||||
delay(3000)
|
||||
}
|
||||
}
|
||||
// Strict Private DNS makes Android ignore the VPN's DNS server; followed while Home is visible
|
||||
val privateDnsHost by remember { privateDnsHosts(context) }.collectAsStateWithLifecycle(initialValue = null)
|
||||
var crashVisible by remember { mutableStateOf(crashReport != null) }
|
||||
|
||||
val isCustom = selected == Providers.CUSTOM_ID
|
||||
val customValid = customUrl.trim().toHttpUrlOrNull()?.isHttps == true
|
||||
val customValid = remember(customUrl) { customUrl.trim().toHttpUrlOrNull()?.isHttps == true }
|
||||
val canConnect = !isCustom || customValid
|
||||
val selectedProvider = remember(selected, customUrl, customBootstrap, customHttp3, servers) { prefs.resolve() }
|
||||
val customName = stringResource(R.string.custom)
|
||||
@@ -156,9 +168,23 @@ fun HomeScreen(modifier: Modifier = Modifier) {
|
||||
// Picking a server never touches a live connection; switching is an explicit action
|
||||
val pendingSwitch = active?.let { it != selectedProvider && canConnect } == true
|
||||
|
||||
// Set by a tap until the VPN state changes or the attempt gives up, so a double tap neither
|
||||
// starts two connections nor switches the VPN back on right after turning it off
|
||||
var busy by remember { mutableStateOf(false) }
|
||||
LaunchedEffect(active) { busy = false }
|
||||
LaunchedEffect(busy) {
|
||||
if (busy) {
|
||||
delay(BUSY_TIMEOUT_MS)
|
||||
busy = false
|
||||
}
|
||||
}
|
||||
|
||||
val vpnPermission = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.StartActivityForResult()
|
||||
) { if (it.resultCode == Activity.RESULT_OK) sendAction(context, DohVpnService.ACTION_START) }
|
||||
) {
|
||||
if (it.resultCode == Activity.RESULT_OK) sendAction(context, DohVpnService.ACTION_START)
|
||||
else busy = false
|
||||
}
|
||||
|
||||
fun connectVpn() {
|
||||
val permission = VpnService.prepare(context)
|
||||
@@ -172,6 +198,8 @@ fun HomeScreen(modifier: Modifier = Modifier) {
|
||||
) { connectVpn() }
|
||||
|
||||
fun toggle() {
|
||||
if (busy) return
|
||||
busy = true
|
||||
if (running) {
|
||||
sendAction(context, DohVpnService.ACTION_STOP)
|
||||
return
|
||||
@@ -249,9 +277,15 @@ fun HomeScreen(modifier: Modifier = Modifier) {
|
||||
http3 = usesHttp3,
|
||||
stats = stats,
|
||||
canConnect = canConnect,
|
||||
busy = busy,
|
||||
switchTo = if (pendingSwitch) nameOf(selectedProvider) else null,
|
||||
onToggle = ::toggle,
|
||||
onSwitch = { sendAction(context, DohVpnService.ACTION_START) },
|
||||
onSwitch = {
|
||||
if (!busy) {
|
||||
busy = true
|
||||
sendAction(context, DohVpnService.ACTION_START)
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
SectionHeader(stringResource(R.string.servers)) {
|
||||
@@ -405,6 +439,7 @@ private fun StatusHero(
|
||||
http3: Boolean,
|
||||
stats: QueryStats,
|
||||
canConnect: Boolean,
|
||||
busy: Boolean,
|
||||
switchTo: String?,
|
||||
onToggle: () -> Unit,
|
||||
onSwitch: () -> Unit,
|
||||
@@ -490,7 +525,7 @@ private fun StatusHero(
|
||||
|
||||
Button(
|
||||
onClick = onToggle,
|
||||
enabled = running || canConnect,
|
||||
enabled = (running || canConnect) && !busy,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(52.dp),
|
||||
@@ -506,7 +541,7 @@ private fun StatusHero(
|
||||
val lastSwitch = remember { arrayOf("") }
|
||||
if (switchTo != null) lastSwitch[0] = switchTo
|
||||
AnimatedVisibility(visible = switchTo != null, enter = Motion.expandIn, exit = Motion.collapseOut) {
|
||||
OutlinedButton(onClick = onSwitch, modifier = Modifier.fillMaxWidth()) {
|
||||
OutlinedButton(onClick = onSwitch, enabled = !busy, modifier = Modifier.fillMaxWidth()) {
|
||||
Icon(painterResource(R.drawable.ic_switch), contentDescription = null, modifier = Modifier.size(18.dp))
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(stringResource(R.string.switch_to, lastSwitch[0]))
|
||||
@@ -631,11 +666,24 @@ private fun RowDivider() {
|
||||
)
|
||||
}
|
||||
|
||||
// Hostname of strict Private DNS (DNS-over-TLS) on the current network, null when it is Automatic or Off
|
||||
private fun readPrivateDnsHost(context: Context): String? {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) return null
|
||||
val cm = context.getSystemService(ConnectivityManager::class.java) ?: return null
|
||||
return runCatching { cm.getLinkProperties(cm.activeNetwork)?.privateDnsServerName }.getOrNull()
|
||||
// Hostname of strict Private DNS (DNS-over-TLS) on the current network, null when it is Automatic or Off.
|
||||
// Android reports the current state on registration and every change after it.
|
||||
private fun privateDnsHosts(context: Context): Flow<String?> {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) return flowOf(null)
|
||||
val cm = context.applicationContext.getSystemService(ConnectivityManager::class.java) ?: return flowOf(null)
|
||||
return callbackFlow {
|
||||
val callback = object : ConnectivityManager.NetworkCallback() {
|
||||
override fun onLinkPropertiesChanged(network: Network, linkProperties: LinkProperties) {
|
||||
trySend(linkProperties.privateDnsServerName)
|
||||
}
|
||||
|
||||
override fun onLost(network: Network) {
|
||||
trySend(null)
|
||||
}
|
||||
}
|
||||
val registered = runCatching { cm.registerDefaultNetworkCallback(callback) }.isSuccess
|
||||
awaitClose { if (registered) runCatching { cm.unregisterNetworkCallback(callback) } }
|
||||
}.distinctUntilChanged()
|
||||
}
|
||||
|
||||
private fun openNetworkSettings(context: Context) {
|
||||
|
||||
@@ -28,8 +28,6 @@ import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
@@ -45,8 +43,8 @@ import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.text.SimpleDateFormat
|
||||
@@ -61,19 +59,17 @@ private val TimeFormat = SimpleDateFormat("HH:mm:ss", Locale.ROOT)
|
||||
fun MonitorScreen(modifier: Modifier = Modifier) {
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val custom by Blocklist.custom.collectAsState()
|
||||
val custom by Blocklist.custom.collectAsStateWithLifecycle()
|
||||
val customSet = remember(custom) { custom.toHashSet() }
|
||||
|
||||
var entries by remember { mutableStateOf(QueryLog.snapshot()) }
|
||||
var stats by remember { mutableStateOf(QueryLog.stats()) }
|
||||
var filter by rememberSaveable { mutableStateOf(MonitorFilter.ALL) }
|
||||
var search by rememberSaveable { mutableStateOf("") }
|
||||
|
||||
LaunchedEffect(Unit) {
|
||||
while (true) {
|
||||
entries = QueryLog.snapshot()
|
||||
stats = QueryLog.stats()
|
||||
delay(1000)
|
||||
}
|
||||
OnQueryLogChange {
|
||||
entries = QueryLog.snapshot()
|
||||
stats = QueryLog.stats()
|
||||
}
|
||||
|
||||
val visible = remember(entries, filter, search) {
|
||||
@@ -90,14 +86,20 @@ fun MonitorScreen(modifier: Modifier = Modifier) {
|
||||
|
||||
fun toggleBlock(domain: String, unblock: Boolean) {
|
||||
scope.launch {
|
||||
val ok = withContext(Dispatchers.IO) {
|
||||
if (unblock) {
|
||||
Blocklist.removeCustom(context, domain)
|
||||
true
|
||||
} else {
|
||||
Blocklist.addCustom(context, domain)
|
||||
val result = withContext(Dispatchers.IO) {
|
||||
tryEdit {
|
||||
if (unblock) {
|
||||
Blocklist.removeCustom(context, domain)
|
||||
true
|
||||
} else {
|
||||
Blocklist.addCustom(context, domain)
|
||||
}
|
||||
}
|
||||
}
|
||||
val ok = result.getOrElse {
|
||||
showEditError(context, it)
|
||||
return@launch
|
||||
}
|
||||
val message = when {
|
||||
!ok -> context.getString(R.string.bl_invalid)
|
||||
unblock -> context.getString(R.string.mon_unblocked, domain)
|
||||
@@ -196,8 +198,8 @@ fun MonitorScreen(modifier: Modifier = Modifier) {
|
||||
}
|
||||
}
|
||||
|
||||
itemsIndexed(visible, key = { _, e -> e.id }) { index, entry ->
|
||||
val inCustom = entry.domain in custom
|
||||
itemsIndexed(visible, key = { _, e -> e.id }, contentType = { _, _ -> "query" }) { index, entry ->
|
||||
val inCustom = entry.domain in customSet
|
||||
QueryRow(
|
||||
modifier = Modifier.animateItem(),
|
||||
entry = entry,
|
||||
|
||||
@@ -4,7 +4,6 @@ import android.content.Context
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
@@ -74,8 +73,7 @@ object ServerList {
|
||||
@Volatile private var loaded = false
|
||||
|
||||
private val client by lazy {
|
||||
OkHttpClient.Builder()
|
||||
.connectTimeout(15, TimeUnit.SECONDS)
|
||||
Http.client.newBuilder()
|
||||
.readTimeout(30, TimeUnit.SECONDS)
|
||||
.build()
|
||||
}
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
package cc.skysparkle.sparkledns
|
||||
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.transform
|
||||
|
||||
enum class QueryStatus { OK, CACHED, BLOCKED, FAILED }
|
||||
|
||||
class QueryEntry(
|
||||
@@ -31,6 +36,14 @@ object QueryLog {
|
||||
private var failed = 0L
|
||||
private var latencySum = 0L
|
||||
private var latencyCount = 0L
|
||||
private val version = MutableStateFlow(0L)
|
||||
|
||||
// Fires right away, then at most once a second while queries keep coming: a busy log refreshes
|
||||
// the screen no more often than the old one-second polling did, and an idle one not at all
|
||||
fun changes(): Flow<Long> = version.transform {
|
||||
emit(it)
|
||||
delay(1000)
|
||||
}
|
||||
|
||||
fun add(question: DnsMessage.Question?, status: QueryStatus, latencyMs: Int) {
|
||||
if (question == null) return
|
||||
@@ -46,6 +59,7 @@ object QueryLog {
|
||||
QueryStatus.BLOCKED -> blocked++
|
||||
QueryStatus.FAILED -> failed++
|
||||
}
|
||||
version.value++
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,5 +81,6 @@ object QueryLog {
|
||||
fun clear() {
|
||||
entries.clear()
|
||||
total = 0; cached = 0; blocked = 0; failed = 0; latencySum = 0; latencyCount = 0
|
||||
version.value++
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,6 +30,7 @@ import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
@@ -42,8 +43,11 @@ import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import kotlinx.coroutines.delay
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.compose.LocalLifecycleOwner
|
||||
import androidx.lifecycle.repeatOnLifecycle
|
||||
import java.text.NumberFormat
|
||||
import java.util.Locale
|
||||
|
||||
val CachedColor = Color(0xFF7FD1AE)
|
||||
val WarningColor = Color(0xFFFFB86B)
|
||||
@@ -191,20 +195,35 @@ fun StatDivider() {
|
||||
)
|
||||
}
|
||||
|
||||
// Polls the in-memory query log once a second while the screen is visible
|
||||
// Runs [onChange] when the query log changes, at most once a second and only while the screen
|
||||
// is started: nothing runs while the app sits in the background
|
||||
@Composable
|
||||
fun OnQueryLogChange(onChange: () -> Unit) {
|
||||
val lifecycle = LocalLifecycleOwner.current.lifecycle
|
||||
val current by rememberUpdatedState(onChange)
|
||||
LaunchedEffect(lifecycle) {
|
||||
lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||
QueryLog.changes().collect { current() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun rememberLiveStats(): QueryStats {
|
||||
var stats by remember { mutableStateOf(QueryLog.stats()) }
|
||||
LaunchedEffect(Unit) {
|
||||
while (true) {
|
||||
stats = QueryLog.stats()
|
||||
delay(1000)
|
||||
}
|
||||
}
|
||||
OnQueryLogChange { stats = QueryLog.stats() }
|
||||
return stats
|
||||
}
|
||||
|
||||
fun formatCount(value: Long): String = NumberFormat.getIntegerInstance().format(value)
|
||||
// Called from composition only, i.e. on the main thread; rebuilt when the locale changes
|
||||
private var countFormat: Pair<Locale, NumberFormat>? = null
|
||||
|
||||
fun formatCount(value: Long): String {
|
||||
val locale = Locale.getDefault()
|
||||
val format = countFormat?.takeIf { it.first == locale }?.second
|
||||
?: NumberFormat.getIntegerInstance(locale).also { countFormat = locale to it }
|
||||
return format.format(value)
|
||||
}
|
||||
|
||||
fun cachePercent(stats: QueryStats): String =
|
||||
"${if (stats.total == 0L) 0 else stats.cached * 100 / stats.total}%"
|
||||
|
||||
|
Before Width: | Height: | Size: 184 KiB |
|
After Width: | Height: | Size: 124 KiB |
|
Before Width: | Height: | Size: 19 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
Before Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 7.6 KiB |
|
Before Width: | Height: | Size: 29 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
Before Width: | Height: | Size: 54 KiB |
|
After Width: | Height: | Size: 40 KiB |
|
Before Width: | Height: | Size: 82 KiB |
|
After Width: | Height: | Size: 62 KiB |
@@ -98,4 +98,5 @@
|
||||
<string name="servers_update">Serverliste aktualisieren</string>
|
||||
<string name="servers_updated">Serverliste aktualisiert</string>
|
||||
<string name="servers_update_failed">Serverliste konnte nicht aktualisiert werden: %1$s</string>
|
||||
<string name="no_browser">Keine App zum Öffnen dieses Links gefunden</string>
|
||||
</resources>
|
||||
|
||||
@@ -98,4 +98,5 @@
|
||||
<string name="servers_update">サーバーリストを更新</string>
|
||||
<string name="servers_updated">サーバーリストを更新しました</string>
|
||||
<string name="servers_update_failed">サーバーリストを更新できませんでした: %1$s</string>
|
||||
<string name="no_browser">このリンクを開けるアプリがありません</string>
|
||||
</resources>
|
||||
|
||||
@@ -98,4 +98,5 @@
|
||||
<string name="servers_update">Atnaujinti serverių sąrašą</string>
|
||||
<string name="servers_updated">Serverių sąrašas atnaujintas</string>
|
||||
<string name="servers_update_failed">Nepavyko atnaujinti serverių sąrašo: %1$s</string>
|
||||
<string name="no_browser">Nerasta programėlės šiai nuorodai atidaryti</string>
|
||||
</resources>
|
||||
|
||||
@@ -98,4 +98,5 @@
|
||||
<string name="servers_update">Обновить список серверов</string>
|
||||
<string name="servers_updated">Список серверов обновлён</string>
|
||||
<string name="servers_update_failed">Не удалось обновить список серверов: %1$s</string>
|
||||
<string name="no_browser">Не найдено приложение, чтобы открыть ссылку</string>
|
||||
</resources>
|
||||
|
||||
@@ -98,4 +98,5 @@
|
||||
<string name="servers_update">更新服务器列表</string>
|
||||
<string name="servers_updated">服务器列表已更新</string>
|
||||
<string name="servers_update_failed">无法更新服务器列表:%1$s</string>
|
||||
<string name="no_browser">没有可以打开此链接的应用</string>
|
||||
</resources>
|
||||
|
||||
@@ -99,4 +99,5 @@
|
||||
<string name="servers_update">Update server list</string>
|
||||
<string name="servers_updated">Server list updated</string>
|
||||
<string name="servers_update_failed">Couldn\'t update the server list: %1$s</string>
|
||||
<string name="no_browser">No app found to open this link</string>
|
||||
</resources>
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package cc.skysparkle.sparkledns
|
||||
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class BlocklistMatchTest {
|
||||
|
||||
private fun set(vararg domains: String) = domains.map { DomainHash.of(it) }.sorted().toLongArray()
|
||||
|
||||
@Test
|
||||
fun blocksDomainsAndTheirSubdomains() {
|
||||
val lists = set("ads.example.com")
|
||||
val custom = set("tracker.net")
|
||||
|
||||
assertTrue(isBlockedIn("ads.example.com", lists, custom))
|
||||
assertTrue(isBlockedIn("a.b.ads.example.com.", lists, custom))
|
||||
assertTrue(isBlockedIn("cdn.tracker.net", lists, custom))
|
||||
assertFalse(isBlockedIn("example.com", lists, custom))
|
||||
assertFalse(isBlockedIn("badads.example.com", lists, custom))
|
||||
assertFalse(isBlockedIn("tracker.network", lists, custom))
|
||||
assertFalse(isBlockedIn("ads.example.com", LongArray(0), LongArray(0)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun mergesSortedListsWithoutDuplicates() {
|
||||
val a = longArrayOf(-5, 1, 4, 9)
|
||||
val b = longArrayOf(1, 2, 9, 12)
|
||||
val c = longArrayOf(3)
|
||||
|
||||
assertArrayEquals(longArrayOf(-5, 1, 2, 3, 4, 9, 12), mergeSorted(listOf(a, b, c, LongArray(0))))
|
||||
assertArrayEquals(LongArray(0), mergeSorted(emptyList()))
|
||||
assertArrayEquals(a, mergeSorted(listOf(a)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun sortsInputsThatAreNotSorted() {
|
||||
assertArrayEquals(longArrayOf(1, 2, 3, 7), mergeSorted(listOf(longArrayOf(3, 1, 3), longArrayOf(7, 2))))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun countsEntriesInBothSetsOnce() {
|
||||
assertEquals(5, unionSize(longArrayOf(1, 2, 3, 4), longArrayOf(2, 5)))
|
||||
assertEquals(2, unionSize(LongArray(0), longArrayOf(2, 5)))
|
||||
assertEquals(4, unionSize(longArrayOf(1, 2, 3, 4), LongArray(0)))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package cc.skysparkle.sparkledns
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
|
||||
class BlocklistParserTest {
|
||||
|
||||
@Test
|
||||
fun understandsCommonListFormats() {
|
||||
assertEquals("ads.example.com", BlocklistParser.parseLine("0.0.0.0 ads.example.com"))
|
||||
assertEquals("ads.example.com", BlocklistParser.parseLine("127.0.0.1\tads.example.com # tracker"))
|
||||
assertEquals("ads.example.com", BlocklistParser.parseLine("ads.example.com"))
|
||||
assertEquals("tracker.example", BlocklistParser.parseLine("||tracker.example^"))
|
||||
assertEquals("tracker.example", BlocklistParser.parseLine("||tracker.example^\$third-party"))
|
||||
assertEquals("bad.example", BlocklistParser.parseLine("address=/bad.example/0.0.0.0"))
|
||||
assertEquals("bad.example", BlocklistParser.parseLine("server=/bad.example/"))
|
||||
assertEquals("bad.example", BlocklistParser.parseLine("local-zone: \"bad.example\" always_nxdomain"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun skipsCommentsRulesAndLocalNames() {
|
||||
assertNull(BlocklistParser.parseLine(""))
|
||||
assertNull(BlocklistParser.parseLine("# comment"))
|
||||
assertNull(BlocklistParser.parseLine("! adblock comment"))
|
||||
assertNull(BlocklistParser.parseLine("[Adblock Plus 2.0]"))
|
||||
assertNull(BlocklistParser.parseLine("@@||allowed.example^"))
|
||||
assertNull(BlocklistParser.parseLine("example.com##.banner"))
|
||||
assertNull(BlocklistParser.parseLine("127.0.0.1 localhost"))
|
||||
assertNull(BlocklistParser.parseLine("0.0.0.0 0.0.0.0"))
|
||||
assertNull(BlocklistParser.parseLine("::1 ip6-localhost"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun normalizesUserInput() {
|
||||
assertEquals("example.com", BlocklistParser.normalize(" HTTPS://Example.COM/path?q=1 "))
|
||||
assertEquals("example.com", BlocklistParser.normalize("*.example.com"))
|
||||
assertEquals("example.com", BlocklistParser.normalize("example.com."))
|
||||
assertEquals("example.com", BlocklistParser.normalize("example.com:8080"))
|
||||
assertNull(BlocklistParser.normalize("localhost"))
|
||||
assertNull(BlocklistParser.normalize("bad..example"))
|
||||
assertNull(BlocklistParser.normalize("-bad.example"))
|
||||
assertNull(BlocklistParser.normalize("exa mple.com"))
|
||||
assertNull(BlocklistParser.normalize("192.168.0.1"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun parentHashMatchesHashOfTheSuffix() {
|
||||
val name = "a.b.example.com"
|
||||
assertEquals(DomainHash.of("example.com"), DomainHash.of(name, name.indexOf("example")))
|
||||
assertEquals(DomainHash.of(name), DomainHash.of(name, 0))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package cc.skysparkle.sparkledns
|
||||
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
|
||||
class DnsCacheTest {
|
||||
|
||||
private var now = 1_000_000L
|
||||
private val cache = DnsCache(clock = { now })
|
||||
|
||||
@Test
|
||||
fun answersWithTheNewQueryIdAndAgedTtl() {
|
||||
val first = DnsMessage.buildQuery("example.com")
|
||||
cache.put(first, dnsResponse(first, ttls = listOf(300)))
|
||||
now += 10_000
|
||||
|
||||
val second = DnsMessage.buildQuery("EXAMPLE.com")
|
||||
val hit = requireNotNull(cache.get(second))
|
||||
|
||||
assertEquals(second[0], hit[0])
|
||||
assertEquals(second[1], hit[1])
|
||||
assertEquals(290L, answerTtl(hit))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun expiresWithTheShortestTtl() {
|
||||
val query = DnsMessage.buildQuery("example.com")
|
||||
cache.put(query, dnsResponse(query, ttls = listOf(300, 60)))
|
||||
|
||||
now += 59_000
|
||||
val hit = requireNotNull(cache.get(query))
|
||||
assertEquals(241L, answerTtl(hit, 0))
|
||||
assertEquals(1L, answerTtl(hit, 1))
|
||||
|
||||
now += 1_000
|
||||
assertNull(cache.get(query))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun capsTtlAtOneHour() {
|
||||
val query = DnsMessage.buildQuery("example.com")
|
||||
cache.put(query, dnsResponse(query, ttls = listOf(86_400)))
|
||||
|
||||
now += 3_599_000
|
||||
assertNotNull(cache.get(query))
|
||||
now += 1_000
|
||||
assertNull(cache.get(query))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun keepsEmptyNxdomainForThirtySeconds() {
|
||||
val query = DnsMessage.buildQuery("nothing.example")
|
||||
cache.put(query, dnsResponse(query, rcode = 3, ttls = emptyList()))
|
||||
|
||||
now += 29_000
|
||||
assertEquals(3, DnsMessage.rcode(requireNotNull(cache.get(query))))
|
||||
now += 1_000
|
||||
assertNull(cache.get(query))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun skipsFailuresTruncatedAndZeroTtlAnswers() {
|
||||
val failed = DnsMessage.buildQuery("a.example")
|
||||
val truncated = DnsMessage.buildQuery("b.example")
|
||||
val zero = DnsMessage.buildQuery("c.example")
|
||||
|
||||
cache.put(failed, dnsResponse(failed, rcode = 2))
|
||||
cache.put(truncated, dnsResponse(truncated, truncated = true))
|
||||
cache.put(zero, dnsResponse(zero, ttls = listOf(0)))
|
||||
|
||||
assertNull(cache.get(failed))
|
||||
assertNull(cache.get(truncated))
|
||||
assertNull(cache.get(zero))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun leavesTheOptRecordAlone() {
|
||||
val query = DnsMessage.buildQuery("example.com")
|
||||
val response = dnsResponse(query, withOpt = true)
|
||||
cache.put(query, response)
|
||||
now += 10_000
|
||||
|
||||
val hit = requireNotNull(cache.get(query))
|
||||
|
||||
assertArrayEquals(response.copyOfRange(response.size - 11, response.size), hit.copyOfRange(hit.size - 11, hit.size))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun separatesRecordTypes() {
|
||||
val a = DnsMessage.buildQuery("example.com", type = 1)
|
||||
val aaaa = DnsMessage.buildQuery("example.com", type = 28)
|
||||
cache.put(a, dnsResponse(a))
|
||||
|
||||
assertNull(cache.get(aaaa))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun evictsTheLeastRecentlyUsedEntry() {
|
||||
val small = DnsCache(maxEntries = 2, clock = { now })
|
||||
val a = DnsMessage.buildQuery("a.example")
|
||||
val b = DnsMessage.buildQuery("b.example")
|
||||
val c = DnsMessage.buildQuery("c.example")
|
||||
small.put(a, dnsResponse(a))
|
||||
small.put(b, dnsResponse(b))
|
||||
small.get(a)
|
||||
small.put(c, dnsResponse(c))
|
||||
|
||||
assertNotNull(small.get(a))
|
||||
assertNull(small.get(b))
|
||||
assertNotNull(small.get(c))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package cc.skysparkle.sparkledns
|
||||
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertSame
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class DnsMessageTest {
|
||||
|
||||
@Test
|
||||
fun questionIsReadBackLowercase() {
|
||||
val question = requireNotNull(DnsMessage.question(DnsMessage.buildQuery("WWW.Example.COM.", type = 28)))
|
||||
|
||||
assertEquals("www.example.com", question.name)
|
||||
assertEquals(28, question.type)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun questionRejectsCompressedOrCutNames() {
|
||||
val query = DnsMessage.buildQuery("example.com")
|
||||
val compressed = query.copyOf(12) + byteArrayOf(0xC0.toByte(), 0x0C, 0, 1, 0, 1)
|
||||
|
||||
assertNull(DnsMessage.question(compressed))
|
||||
assertNull(DnsMessage.question(query.copyOf(16)))
|
||||
assertNull(DnsMessage.question(query.copyOf(11)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun withIdCopiesTheQueryId() {
|
||||
val query = DnsMessage.buildQuery("example.com")
|
||||
val response = dnsResponse(query)
|
||||
response[0] = (query[0] + 1).toByte()
|
||||
|
||||
val fixed = DnsMessage.withId(response, query)
|
||||
|
||||
assertEquals(query[0], fixed[0])
|
||||
assertEquals(query[1], fixed[1])
|
||||
assertSame(fixed, DnsMessage.withId(fixed, query))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun errorReplyKeepsOnlyTheQuestion() {
|
||||
val query = DnsMessage.buildQuery("example.com")
|
||||
// An EDNS OPT record in the additional section must not be echoed back
|
||||
val withOpt = query.copyOf().also { it[11] = 1 } + byteArrayOf(0, 0, 41, 0x10, 0, 0, 0, 0, 0, 0, 0)
|
||||
|
||||
val reply = requireNotNull(DnsMessage.errorReply(withOpt, DnsMessage.RCODE_NXDOMAIN))
|
||||
|
||||
assertEquals(query.size, reply.size)
|
||||
assertTrue(DnsMessage.isResponse(reply))
|
||||
assertEquals(DnsMessage.RCODE_NXDOMAIN, DnsMessage.rcode(reply))
|
||||
assertEquals(1, u16(reply, 4))
|
||||
assertArrayEquals(ByteArray(6), reply.copyOfRange(6, 12))
|
||||
assertArrayEquals(query.copyOfRange(12, query.size), reply.copyOfRange(12, reply.size))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun servfailAndResponseFlags() {
|
||||
val query = DnsMessage.buildQuery("example.com")
|
||||
|
||||
assertFalse(DnsMessage.isResponse(query))
|
||||
assertEquals(DnsMessage.RCODE_SERVFAIL, DnsMessage.rcode(requireNotNull(DnsMessage.servfail(query))))
|
||||
assertNull(DnsMessage.servfail(ByteArray(5)))
|
||||
assertEquals(-1, DnsMessage.rcode(ByteArray(2)))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package cc.skysparkle.sparkledns
|
||||
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
|
||||
class PacketTest {
|
||||
|
||||
private val client = byteArrayOf(10, 111, 222.toByte(), 1)
|
||||
private val server = byteArrayOf(10, 111, 222.toByte(), 2)
|
||||
|
||||
@Test
|
||||
fun parsesDnsQuery() {
|
||||
val query = DnsMessage.buildQuery("example.com")
|
||||
val packet = ipv4Udp(client, server, 40000, 53, query)
|
||||
|
||||
val parsed = requireNotNull(Packet.parseDnsQuery(packet, packet.size))
|
||||
|
||||
assertArrayEquals(query, parsed.payload)
|
||||
assertArrayEquals(client, parsed.srcIp)
|
||||
assertArrayEquals(server, parsed.dstIp)
|
||||
assertEquals(40000, parsed.srcPort)
|
||||
assertEquals(53, parsed.dstPort)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun usesOnlyTheBytesThatWereRead() {
|
||||
val query = DnsMessage.buildQuery("example.com")
|
||||
val packet = ipv4Udp(client, server, 40000, 53, query)
|
||||
val buffer = packet + ByteArray(100) { 0x55 }
|
||||
|
||||
val parsed = requireNotNull(Packet.parseDnsQuery(buffer, packet.size))
|
||||
|
||||
assertArrayEquals(query, parsed.payload)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun ignoresEverythingThatIsNotADnsQuery() {
|
||||
val query = DnsMessage.buildQuery("example.com")
|
||||
val otherPort = ipv4Udp(client, server, 40000, 443, query)
|
||||
val tcp = ipv4Udp(client, server, 40000, 53, query, protocol = 6)
|
||||
val fragment = ipv4Udp(client, server, 40000, 53, query, flagsAndOffset = 0x2000)
|
||||
val ipv6 = ipv4Udp(client, server, 40000, 53, query).also { it[0] = 0x60 }
|
||||
|
||||
assertNull(Packet.parseDnsQuery(otherPort, otherPort.size))
|
||||
assertNull(Packet.parseDnsQuery(tcp, tcp.size))
|
||||
assertNull(Packet.parseDnsQuery(fragment, fragment.size))
|
||||
assertNull(Packet.parseDnsQuery(ipv6, ipv6.size))
|
||||
assertNull(Packet.parseDnsQuery(otherPort, 27))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun replySwapsEndpointsAndHasValidChecksums() {
|
||||
val query = DnsMessage.buildQuery("example.com")
|
||||
val packet = ipv4Udp(client, server, 40000, 53, query)
|
||||
val parsed = requireNotNull(Packet.parseDnsQuery(packet, packet.size))
|
||||
// Odd length exercises the checksum padding
|
||||
val answer = dnsResponse(query) + byteArrayOf(7)
|
||||
|
||||
val reply = Packet.buildReply(parsed, answer)
|
||||
|
||||
assertEquals(28 + answer.size, reply.size)
|
||||
assertEquals(0x45, reply[0].toInt())
|
||||
assertEquals(reply.size, u16(reply, 2))
|
||||
assertArrayEquals(server, reply.copyOfRange(12, 16))
|
||||
assertArrayEquals(client, reply.copyOfRange(16, 20))
|
||||
assertEquals(53, u16(reply, 20))
|
||||
assertEquals(40000, u16(reply, 22))
|
||||
assertArrayEquals(answer, reply.copyOfRange(28, reply.size))
|
||||
assertEquals(0xFFFF, onesSum(reply.copyOfRange(0, 20)))
|
||||
|
||||
val udp = reply.copyOfRange(20, reply.size)
|
||||
val pseudo = reply.copyOfRange(12, 20) + byteArrayOf(0, 17) + byteArrayOf((udp.size shr 8).toByte(), udp.size.toByte())
|
||||
assertEquals(0xFFFF, onesSum(pseudo, udp))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package cc.skysparkle.sparkledns
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertSame
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class ServerListTest {
|
||||
|
||||
@Test
|
||||
fun readsAllColumns() {
|
||||
val list = ServerList.parse(
|
||||
"""
|
||||
# Name | URL | policy | h3 | donate
|
||||
Example DNS | https://dns.example.org/dns-query | https://example.org/privacy | h3 | https://example.org/donate
|
||||
Other | https://doh.other.net/q | https://other.net/policy | https://other.net/give
|
||||
""".trimIndent()
|
||||
)
|
||||
|
||||
assertEquals(2, list.size)
|
||||
val first = list[0]
|
||||
assertEquals("dns.example.org", first.id)
|
||||
assertEquals("Example DNS", first.name)
|
||||
assertEquals("https://dns.example.org/dns-query", first.url)
|
||||
assertEquals("https://example.org/privacy", first.policy)
|
||||
assertEquals("https://example.org/donate", first.donate)
|
||||
assertTrue(first.http3)
|
||||
|
||||
val second = list[1]
|
||||
assertFalse(second.http3)
|
||||
assertEquals("https://other.net/give", second.donate)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun skipsServersWithoutHttpsOrPolicy() {
|
||||
val list = ServerList.parse(
|
||||
"""
|
||||
Plain | http://dns.example.org/dns-query | https://example.org/privacy
|
||||
No policy | https://dns.example.org/dns-query | not a url
|
||||
Too short | https://dns.example.org/dns-query
|
||||
""".trimIndent()
|
||||
)
|
||||
|
||||
assertTrue(list.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun shippedServersCannotBeRedirected() {
|
||||
val quad9 = Providers.builtIn.first { it.id == "quad9" }
|
||||
|
||||
val list = ServerList.parse("Fake | https://dns.quad9.net/elsewhere | https://evil.example/policy")
|
||||
|
||||
assertSame(quad9, list.single())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun dropsDuplicatesTrimsNamesAndCapsTheList() {
|
||||
val long = "N".repeat(60)
|
||||
val lines = (1..60).joinToString("\n") { "$long | https://dns$it.example/q | https://example.org/p" } +
|
||||
"\nDuplicate | https://dns1.example/q | https://example.org/p"
|
||||
|
||||
val list = ServerList.parse(lines)
|
||||
|
||||
assertEquals(50, list.size)
|
||||
assertEquals(40, list[0].name.length)
|
||||
assertEquals(list.size, list.map { it.id }.toSet().size)
|
||||
assertNull(list.firstOrNull { it.name == "Duplicate" })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package cc.skysparkle.sparkledns
|
||||
|
||||
import java.io.ByteArrayOutputStream
|
||||
|
||||
// Hand-built DNS messages and IPv4/UDP packets for the tests
|
||||
|
||||
internal fun dnsResponse(
|
||||
query: ByteArray,
|
||||
rcode: Int = 0,
|
||||
ttls: List<Int> = listOf(300),
|
||||
withOpt: Boolean = false,
|
||||
truncated: Boolean = false,
|
||||
): ByteArray {
|
||||
val questionEnd = requireNotNull(skipName(query, 12)) + 4
|
||||
val out = ByteArrayOutputStream()
|
||||
out.write(query, 0, 2)
|
||||
out.write(0x81 or if (truncated) 0x02 else 0) // QR + RD (+ TC)
|
||||
out.write(0x80 or rcode) // RA + RCODE
|
||||
out.write(byteArrayOf(0, 1, 0, ttls.size.toByte(), 0, 0, 0, (if (withOpt) 1 else 0).toByte()))
|
||||
out.write(query, 12, questionEnd - 12)
|
||||
for (ttl in ttls) {
|
||||
out.write(byteArrayOf(0xC0.toByte(), 0x0C, 0, 1, 0, 1))
|
||||
out.write(be32(ttl))
|
||||
out.write(byteArrayOf(0, 4, 93, 184.toByte(), 216.toByte(), 34))
|
||||
}
|
||||
if (withOpt) {
|
||||
// Root name, type OPT, UDP size 4096, extended flags with the DO bit, no data
|
||||
out.write(byteArrayOf(0, 0, 41, 0x10, 0, 0, 0, 0x80.toByte(), 0, 0, 0))
|
||||
}
|
||||
return out.toByteArray()
|
||||
}
|
||||
|
||||
internal fun ipv4Udp(
|
||||
src: ByteArray,
|
||||
dst: ByteArray,
|
||||
srcPort: Int,
|
||||
dstPort: Int,
|
||||
payload: ByteArray,
|
||||
protocol: Int = 17,
|
||||
flagsAndOffset: Int = 0,
|
||||
): ByteArray {
|
||||
val p = ByteArray(28 + payload.size)
|
||||
p[0] = 0x45
|
||||
put16(p, 2, p.size)
|
||||
put16(p, 6, flagsAndOffset)
|
||||
p[8] = 64
|
||||
p[9] = protocol.toByte()
|
||||
src.copyInto(p, 12)
|
||||
dst.copyInto(p, 16)
|
||||
put16(p, 20, srcPort)
|
||||
put16(p, 22, dstPort)
|
||||
put16(p, 24, 8 + payload.size)
|
||||
payload.copyInto(p, 28)
|
||||
return p
|
||||
}
|
||||
|
||||
// One's complement sum of 16-bit words; a correct checksum makes it 0xFFFF
|
||||
internal fun onesSum(vararg parts: ByteArray): Int {
|
||||
var sum = 0L
|
||||
for (part in parts) {
|
||||
var i = 0
|
||||
while (i + 1 < part.size) {
|
||||
sum += u16(part, i)
|
||||
i += 2
|
||||
}
|
||||
if (i < part.size) sum += (part[i].toInt() and 0xFF) shl 8
|
||||
}
|
||||
while (sum shr 16 != 0L) sum = (sum and 0xFFFF) + (sum shr 16)
|
||||
return sum.toInt()
|
||||
}
|
||||
|
||||
internal fun be32(value: Int) = ByteArray(4).also { put32(it, 0, value) }
|
||||
|
||||
// TTL field of the n-th answer of a message built by dnsResponse
|
||||
internal fun answerTtl(message: ByteArray, index: Int = 0): Long {
|
||||
val first = requireNotNull(skipName(message, 12)) + 4
|
||||
return u32(message, first + index * 16 + 6)
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
• DNS funktioniert weiter, wenn ein unerwartetes Paket ankommt; fällt der Tunnel aus, schaltet sich das VPN ab, statt DNS still zu blockieren
|
||||
• Anfragen erholen sich schneller nach einem Wechsel zwischen WLAN und Mobilfunk und in langsamen Netzen
|
||||
• Weniger Arbeit im Hintergrund: ausgeblendete Bildschirme werden nicht mehr aktualisiert
|
||||
• Blocklisten werden nur noch erneut geladen, wenn sie sich geändert haben
|
||||
• Schärfere App-Symbole, kleinere App
|
||||
• Ein Doppeltipp auf „Verbinden“ verbindet nicht mehr doppelt; voller Speicher lässt die App nicht mehr abstürzen
|
||||
@@ -0,0 +1,6 @@
|
||||
• DNS keeps working when an unexpected packet arrives; if the tunnel fails, the VPN turns off instead of silently blocking DNS
|
||||
• Lookups recover faster after switching between Wi-Fi and mobile data and on slow networks
|
||||
• Less work in the background: hidden screens are no longer refreshed
|
||||
• Blocklists are downloaded again only when they changed
|
||||
• Sharper app icons, smaller app
|
||||
• A double tap on Connect no longer connects twice; a full storage no longer crashes the app
|
||||
@@ -0,0 +1,6 @@
|
||||
• 想定外のパケットが届いても DNS は動作し続けます。トンネルが故障した場合は、DNS を黙って止めずに VPN をオフにします
|
||||
• Wi-Fi とモバイルデータの切り替え後や遅いネットワークで、名前解決がより早く回復します
|
||||
• バックグラウンドでの処理を削減:表示されていない画面は更新しません
|
||||
• ブロックリストは変更があったときだけ再ダウンロードします
|
||||
• アプリアイコンがより鮮明に、アプリサイズが小さく
|
||||
• 「接続」をダブルタップしても二重に接続しません。ストレージがいっぱいでもアプリが落ちなくなりました
|
||||
@@ -0,0 +1,6 @@
|
||||
• DNS veikia toliau, net jei atkeliauja netikėtas paketas; sugedus tuneliui VPN išsijungia, užuot tyliai blokavęs DNS
|
||||
• Užklausos greičiau atsigauna perjungus „Wi-Fi“ ir mobiliuosius duomenis bei lėtuose tinkluose
|
||||
• Mažiau darbo fone: paslėpti ekranai nebeatnaujinami
|
||||
• Blokavimo sąrašai atsisiunčiami iš naujo tik pasikeitus
|
||||
• Ryškesnės programėlių piktogramos, mažesnė programėlė
|
||||
• Dvigubas paspaudimas „Prisijungti“ nebejungia dukart; dėl pilnos atminties programėlė nebeužsidaro
|
||||
@@ -0,0 +1,6 @@
|
||||
• DNS продолжает работать, если пришёл неожиданный пакет; при сбое туннеля VPN отключается, а не блокирует DNS молча
|
||||
• Запросы быстрее восстанавливаются после переключения между Wi-Fi и мобильной сетью и в медленных сетях
|
||||
• Меньше работы в фоне: скрытые экраны больше не обновляются
|
||||
• Блоклисты скачиваются заново, только если изменились
|
||||
• Чётче значки приложений, меньше размер приложения
|
||||
• Двойное нажатие «Подключить» больше не подключает дважды; переполненная память больше не роняет приложение
|
||||
@@ -0,0 +1,6 @@
|
||||
• 收到意外的数据包时 DNS 仍可正常工作;隧道出错时会关闭 VPN,而不是悄悄阻断 DNS
|
||||
• 在 Wi-Fi 与移动数据之间切换后以及网速较慢时,域名解析恢复更快
|
||||
• 后台工作更少:不再刷新隐藏的界面
|
||||
• 拦截列表仅在有变化时重新下载
|
||||
• 应用图标更清晰,应用体积更小
|
||||
• 连点“连接”不会再重复连接;存储空间已满时应用不再崩溃
|
||||
@@ -0,0 +1,71 @@
|
||||
#!/usr/bin/env bash
|
||||
# Records which classes and methods the app uses on startup and in each tab, in the text format
|
||||
# of app/src/main/baseline-prof.txt. Needs a rooted Android 13+ device or emulator (no Play Store).
|
||||
# Usage: scripts/baseline-profile.sh <non-minified release apk> <output file>
|
||||
set -euo pipefail
|
||||
|
||||
PKG=cc.skysparkle.sparkledns
|
||||
ACT="$PKG/.MainActivity"
|
||||
APK="$1"
|
||||
OUT="$2"
|
||||
|
||||
adb root >/dev/null 2>&1 && sleep 3
|
||||
adb wait-for-device
|
||||
adb uninstall "$PKG" >/dev/null 2>&1 || true
|
||||
adb install -g "$APK" >/dev/null
|
||||
read -r W H < <(adb shell wm size | tr -d '\r' | awk -F'[ x]' '/Physical/ {print $3, $4}')
|
||||
|
||||
tap_text() {
|
||||
local xy
|
||||
for _ in 1 2 3 4 5; do
|
||||
adb shell uiautomator dump /sdcard/ui.xml >/dev/null 2>&1 || true
|
||||
xy="$(adb shell cat /sdcard/ui.xml | python3 -c '
|
||||
import re, sys
|
||||
xml, text = sys.stdin.read(), sys.argv[1]
|
||||
for node in re.findall(r"<node [^>]*>", xml):
|
||||
# Compose merges a clickable row into one node: "System, 3 of 5"
|
||||
if re.search(r"(text|content-desc)=\"%s(\"|, )" % re.escape(text), node):
|
||||
x1, y1, x2, y2 = map(int, re.search(r"bounds=\"\[(\d+),(\d+)\]\[(\d+),(\d+)\]\"", node).groups())
|
||||
print((x1 + x2) // 2, (y1 + y2) // 2)
|
||||
break
|
||||
' "$1")"
|
||||
if [[ -n "$xy" ]]; then
|
||||
adb shell input tap $xy
|
||||
return 0
|
||||
fi
|
||||
# Lazy lists only show what is on screen; with "scroll", look further down
|
||||
[[ "${2:-}" == scroll ]] && adb shell input swipe $((W / 2)) $((H * 2 / 3)) $((W / 2)) $((H / 3)) 300
|
||||
sleep 1
|
||||
done
|
||||
echo "::warning::'$1' not found on screen"
|
||||
}
|
||||
|
||||
swipe() {
|
||||
adb shell input swipe $((W / 2)) $((H * 3 / 4)) $((W / 2)) $((H / 4)) 200
|
||||
sleep 1
|
||||
adb shell input swipe $((W / 2)) $((H / 4)) $((W / 2)) $((H * 3 / 4)) 200
|
||||
sleep 1
|
||||
}
|
||||
|
||||
for _ in 1 2 3; do
|
||||
adb shell am force-stop "$PKG"
|
||||
adb shell am start-activity -W -n "$ACT" >/dev/null
|
||||
sleep 3
|
||||
swipe
|
||||
tap_text "Monitor"; sleep 2
|
||||
tap_text "Apps"; sleep 3
|
||||
tap_text "System" scroll; sleep 2
|
||||
swipe
|
||||
tap_text "Blocklist"; sleep 2
|
||||
swipe
|
||||
tap_text "About"; sleep 2
|
||||
tap_text "Home"; sleep 2
|
||||
# Makes ART write the profile now instead of on its own schedule
|
||||
adb shell "kill -10 \$(pidof $PKG)"
|
||||
sleep 5
|
||||
done
|
||||
|
||||
adb shell pm dump-profiles --dump-classes-and-methods "$PKG"
|
||||
sleep 2
|
||||
adb pull "/data/misc/profman/$PKG-primary.prof.txt" "$OUT" >/dev/null
|
||||
echo "Profile lines: $(wc -l < "$OUT")"
|
||||
@@ -0,0 +1,29 @@
|
||||
#!/usr/bin/env bash
|
||||
# Builds signed release APKs of two revisions for scripts/bench.sh.
|
||||
# Usage: scripts/bench-build.sh <base-ref> <head-ref> <out-dir>
|
||||
set -euo pipefail
|
||||
|
||||
base="$(git rev-parse "$1")"
|
||||
head="$(git rev-parse "$2")"
|
||||
out="$(mkdir -p "$3" && cd "$3" && pwd)"
|
||||
work="${RUNNER_TEMP:-/tmp}/bench-src"
|
||||
|
||||
keystore="$out/bench.jks"
|
||||
[[ -f "$keystore" ]] || keytool -genkeypair -keystore "$keystore" -storepass benchpass -keypass benchpass \
|
||||
-alias bench -keyalg RSA -keysize 2048 -validity 365 -dname "CN=bench" >/dev/null 2>&1
|
||||
apksigner="$(ls -d "$ANDROID_HOME"/build-tools/*/ | sort -V | tail -n 1)apksigner"
|
||||
|
||||
build() {
|
||||
local rev="$1" name="$2" dir="$work-$2" apk
|
||||
rm -rf "$dir"
|
||||
git worktree add -f --detach "$dir" "$rev" >/dev/null
|
||||
(cd "$dir" && ./gradlew :app:assembleRelease -q)
|
||||
apk="$(ls "$dir"/app/build/outputs/apk/release/*.apk | head -n 1)"
|
||||
echo "$name,apk_bytes,$(stat -c %s "$apk")" >> "$out/sizes.csv"
|
||||
echo "::notice title=APK size ($name ${rev:0:7})::$(stat -c %s "$apk") bytes"
|
||||
"$apksigner" sign --ks "$keystore" --ks-pass pass:benchpass --out "$out/$name.apk" "$apk"
|
||||
}
|
||||
|
||||
rm -f "$out/sizes.csv"
|
||||
build "$base" base
|
||||
build "$head" head
|
||||
@@ -0,0 +1,222 @@
|
||||
#!/usr/bin/env bash
|
||||
# Benchmarks two APKs of SparkleDNS on one device or emulator and prints medians side by side:
|
||||
# cold start, memory, CPU while in the background and scroll jank on the Apps tab.
|
||||
# Rounds alternate the order of the APKs so device drift affects both alike.
|
||||
# Needs a rooted device (an emulator image without Play Store) to drop the page cache.
|
||||
# Usage: scripts/bench.sh <base.apk> <head.apk> [rounds]
|
||||
set -uo pipefail
|
||||
|
||||
PKG=cc.skysparkle.sparkledns
|
||||
ACT="$PKG/.MainActivity"
|
||||
BASE_APK="$1"
|
||||
HEAD_APK="$2"
|
||||
ROUNDS="${3:-2}"
|
||||
STARTS="${STARTS:-10}"
|
||||
OUT="${OUT:-$(dirname "$BASE_APK")}"
|
||||
RAW="$OUT/raw.csv"
|
||||
: > "$RAW"
|
||||
|
||||
adb root >/dev/null 2>&1 && sleep 3
|
||||
adb wait-for-device
|
||||
read -r W H < <(adb shell wm size | tr -d '\r' | awk -F'[ x]' '/Physical/ {print $3, $4}')
|
||||
|
||||
record() { echo "$1,$2,$3" >> "$RAW"; } # name,metric,value
|
||||
|
||||
install() {
|
||||
adb uninstall "$PKG" >/dev/null 2>&1
|
||||
adb install -g "$1" >/dev/null
|
||||
adb shell am start -W -n "$ACT" >/dev/null
|
||||
sleep 2
|
||||
adb shell am force-stop "$PKG"
|
||||
# Compiles with the APK's baseline profile only, as the device does after an install,
|
||||
# without what the JIT learned during the first run (same as Macrobenchmark's Partial mode)
|
||||
adb shell cmd package compile --reset "$PKG" >/dev/null
|
||||
adb shell am broadcast -f 0x20 -a androidx.profileinstaller.action.INSTALL_PROFILE \
|
||||
"$PKG/androidx.profileinstaller.ProfileInstallReceiver" | tr -d '\r' | grep -o 'result=[0-9-]*'
|
||||
sleep 2
|
||||
adb shell cmd package compile -f -m speed-profile "$PKG" >/dev/null
|
||||
}
|
||||
|
||||
launch() {
|
||||
adb shell am start-activity -W -n "$ACT" | tr -d '\r'
|
||||
}
|
||||
|
||||
cold_starts() {
|
||||
local t
|
||||
for _ in $(seq "$STARTS"); do
|
||||
adb shell am force-stop "$PKG"
|
||||
adb shell 'sync; echo 3 > /proc/sys/vm/drop_caches'
|
||||
sleep 2
|
||||
t="$(launch | awk '/TotalTime/ {print $2}')"
|
||||
[[ -n "$t" ]] && record "$1" cold_start_ms "$t"
|
||||
sleep 3
|
||||
done
|
||||
}
|
||||
|
||||
memory() {
|
||||
local pss
|
||||
for _ in 1 2 3; do
|
||||
adb shell am force-stop "$PKG"
|
||||
launch >/dev/null
|
||||
sleep 10
|
||||
pss="$(adb shell dumpsys meminfo "$PKG" | tr -d '\r' | awk '/TOTAL PSS:/ {print $3; exit}')"
|
||||
[[ -n "$pss" ]] && record "$1" pss_kb "$pss"
|
||||
done
|
||||
}
|
||||
|
||||
# CPU time and scheduler wakeups of all app threads during 60 s on the home screen
|
||||
background_cpu() {
|
||||
local pid a b
|
||||
adb shell am force-stop "$PKG"
|
||||
launch >/dev/null
|
||||
sleep 5
|
||||
adb shell input keyevent 3
|
||||
sleep 5
|
||||
pid="$(adb shell pidof "$PKG" | tr -d '\r')"
|
||||
[[ -z "$pid" ]] && return
|
||||
a="$(adb shell "cat /proc/$pid/task/*/schedstat" | awk '{t += $1; n += $3} END {print t, n}')"
|
||||
sleep 60
|
||||
b="$(adb shell "cat /proc/$pid/task/*/schedstat" | awk '{t += $1; n += $3} END {print t, n}')"
|
||||
read -r t1 n1 <<< "$a"
|
||||
read -r t2 n2 <<< "$b"
|
||||
record "$1" bg_cpu_ms_per_min "$(( (t2 - t1) / 1000000 ))"
|
||||
record "$1" bg_wakeups_per_min "$(( n2 - n1 ))"
|
||||
}
|
||||
|
||||
# Memory still held 30 s after leaving the app from the Apps tab, with every icon loaded once
|
||||
background_memory() {
|
||||
local pss
|
||||
adb shell am force-stop "$PKG"
|
||||
launch >/dev/null
|
||||
sleep 3
|
||||
tap_text "Apps" || return
|
||||
sleep 2
|
||||
tap_text "System" scroll
|
||||
sleep 2
|
||||
for _ in 1 2 3 4; do
|
||||
adb shell input swipe $((W / 2)) $((H * 3 / 4)) $((W / 2)) $((H / 4)) 200
|
||||
sleep 1
|
||||
done
|
||||
sleep 3
|
||||
adb shell input keyevent 3
|
||||
sleep 30
|
||||
pss="$(adb shell dumpsys meminfo "$PKG" | tr -d '\r' | awk '/TOTAL PSS:/ {print $3; exit}')"
|
||||
[[ -n "$pss" ]] && record "$1" bg_pss_after_apps_kb "$pss"
|
||||
}
|
||||
|
||||
tap_text() {
|
||||
local xy
|
||||
for _ in 1 2 3 4 5; do
|
||||
adb shell uiautomator dump /sdcard/ui.xml >/dev/null 2>&1
|
||||
xy="$(adb shell cat /sdcard/ui.xml | python3 -c '
|
||||
import re, sys
|
||||
xml, text = sys.stdin.read(), sys.argv[1]
|
||||
for node in re.findall(r"<node [^>]*>", xml):
|
||||
# Compose merges a clickable row into one node: "System, 3 of 5"
|
||||
if re.search(r"(text|content-desc)=\"%s(\"|, )" % re.escape(text), node):
|
||||
x1, y1, x2, y2 = map(int, re.search(r"bounds=\"\[(\d+),(\d+)\]\[(\d+),(\d+)\]\"", node).groups())
|
||||
print((x1 + x2) // 2, (y1 + y2) // 2)
|
||||
break
|
||||
' "$1")"
|
||||
if [[ -n "$xy" ]]; then
|
||||
adb shell input tap $xy
|
||||
return 0
|
||||
fi
|
||||
# Lazy lists only show what is on screen; with "scroll", look further down
|
||||
[[ "${2:-}" == scroll ]] && adb shell input swipe $((W / 2)) $((H * 2 / 3)) $((W / 2)) $((H / 3)) 300
|
||||
sleep 1
|
||||
done
|
||||
echo "::warning::'$1' not found on screen"
|
||||
return 1
|
||||
}
|
||||
|
||||
jank() {
|
||||
local g total janky
|
||||
adb shell am force-stop "$PKG"
|
||||
launch >/dev/null
|
||||
sleep 3
|
||||
tap_text "Apps" || return
|
||||
sleep 2
|
||||
tap_text "System" scroll # the only group collapsed by default, listed last
|
||||
sleep 2
|
||||
for _ in 1 2 3; do
|
||||
adb shell input swipe $((W / 2)) $((H / 4)) $((W / 2)) $((H * 3 / 4)) 100
|
||||
done
|
||||
sleep 2
|
||||
adb shell dumpsys gfxinfo "$PKG" reset >/dev/null
|
||||
for dir in down down down down down up up up up up; do
|
||||
if [[ $dir == down ]]; then
|
||||
adb shell input swipe $((W / 2)) $((H * 3 / 4)) $((W / 2)) $((H / 4)) 200
|
||||
else
|
||||
adb shell input swipe $((W / 2)) $((H / 4)) $((W / 2)) $((H * 3 / 4)) 200
|
||||
fi
|
||||
sleep 1.2
|
||||
done
|
||||
g="$(adb shell dumpsys gfxinfo "$PKG" | tr -d '\r')"
|
||||
total="$(awk -F': ' '/Total frames rendered/ {print $2; exit}' <<< "$g")"
|
||||
janky="$(awk '/Janky frames:/ {print $3; exit}' <<< "$g")"
|
||||
if [[ -n "$total" && "$total" -gt 0 ]]; then
|
||||
record "$1" frames "$total"
|
||||
record "$1" janky_pct "$(awk -v j="$janky" -v t="$total" 'BEGIN {printf "%.2f", j * 100 / t}')"
|
||||
for p in 50 90 99; do
|
||||
record "$1" "frame_p${p}_ms" "$(awk "/${p}th percentile/ {gsub(\"ms\", \"\", \$3); print \$3; exit}" <<< "$g")"
|
||||
done
|
||||
fi
|
||||
}
|
||||
|
||||
measure() {
|
||||
echo "::group::$1"
|
||||
install "$2"
|
||||
cold_starts "$1"
|
||||
memory "$1"
|
||||
background_cpu "$1"
|
||||
background_memory "$1"
|
||||
jank "$1"
|
||||
jank "$1"
|
||||
echo "::endgroup::"
|
||||
}
|
||||
|
||||
# The first launches after boot are far slower than later ones; warm up before measuring
|
||||
echo "::group::warm-up"
|
||||
install "$BASE_APK"
|
||||
for _ in 1 2 3 4 5; do
|
||||
adb shell am force-stop "$PKG"
|
||||
launch >/dev/null
|
||||
sleep 2
|
||||
done
|
||||
echo "::endgroup::"
|
||||
|
||||
for r in $(seq "$ROUNDS"); do
|
||||
if (( r % 2 )); then
|
||||
measure base "$BASE_APK"
|
||||
measure head "$HEAD_APK"
|
||||
else
|
||||
measure head "$HEAD_APK"
|
||||
measure base "$BASE_APK"
|
||||
fi
|
||||
done
|
||||
|
||||
[[ -f "$OUT/sizes.csv" ]] && cat "$OUT/sizes.csv" >> "$RAW"
|
||||
|
||||
python3 - "$RAW" > "$OUT/results.md" <<'EOF'
|
||||
import csv, statistics, sys
|
||||
data = {}
|
||||
for name, metric, value in csv.reader(open(sys.argv[1])):
|
||||
if value:
|
||||
data.setdefault(metric, {}).setdefault(name, []).append(float(value))
|
||||
print("| Metric (median) | base | head | change | base min–max | head min–max | n |")
|
||||
print("|---|---|---|---|---|---|---|")
|
||||
for metric, by in data.items():
|
||||
b, h = by.get("base", []), by.get("head", [])
|
||||
mb = statistics.median(b) if b else None
|
||||
mh = statistics.median(h) if h else None
|
||||
change = f"{(mh - mb) / mb * 100:+.1f}%" if mb and mh is not None else "n/a"
|
||||
fmt = lambda v: "n/a" if v is None else (f"{v:.0f}" if v >= 100 else f"{v:.2f}")
|
||||
rng = lambda v: f"{fmt(min(v))}–{fmt(max(v))}" if v else "n/a"
|
||||
print(f"| {metric} | {fmt(mb)} | {fmt(mh)} | {change} | {rng(b)} | {rng(h)} | {len(b)}/{len(h)} |")
|
||||
EOF
|
||||
|
||||
cat "$OUT/results.md"
|
||||
[[ -n "${GITHUB_STEP_SUMMARY:-}" ]] && cat "$OUT/results.md" >> "$GITHUB_STEP_SUMMARY"
|
||||
msg="$(cat "$OUT/results.md")"
|
||||
echo "::notice title=Benchmark::${msg//$'\n'/'%0A'}"
|
||||