50 Commits
Author SHA1 Message Date
kalarina 43f0d42d65 Release 1.0.10 2026-10-25 16:47:56 +02:00
kalarina 2b0f842579 Remove the GitHub Actions workflows 2026-10-25 14:54:42 +02:00
kalarina 17ede339fa Show own blocked domains as lazy list rows
All own domains were composed at once when the Blocklist tab opened.
The rows keep the look of the card they were in.
2026-10-25 14:50:49 +02:00
kalarina ac643caf03 Download blocklists again only when they changed
Updates send the stored ETag / Last-Modified, and a 304 answer keeps the
list on disk. Before, every update fetched every list in full.
2026-10-25 14:49:14 +02:00
kalarina 0ceae2f557 Read tile settings off the main thread
Opening the quick settings panel could start a fresh process whose
first tile update read SharedPreferences and servers.txt on the main
thread.
2026-10-25 14:48:46 +02:00
kalarina df41b44302 Tell the user when no app can open a link
Privacy policy, donation, source code and license links silently did
nothing on devices without a browser.
2026-10-25 14:48:16 +02:00
kalarina 4619292174 Ignore repeated taps on Connect, Disconnect and Switch
A quick double tap could start the connection twice, open the VPN
dialog twice, or turn the VPN back on right after switching it off.
The buttons are disabled until the VPN state changes (at most 5 s).
2026-10-25 14:47:57 +02:00
kalarina cff974851a Render app icons at their on-screen size
Icons were always drawn at 96 px: blurry on screens where 40 dp is
larger, wasted memory where it is smaller. The cache is now limited to
10 MB instead of 256 entries.
2026-10-25 14:47:28 +02:00
kalarina d9080195ab Let R8 obfuscate release builds
Shrinks the dex further. Crash reports keep file names and line
numbers; the mapping file restores the names and is kept with the CI
artifacts.
2026-10-25 14:46:33 +02:00
kalarina 026c2c9493 Package only the app's own languages
Library translations for other languages made up a large part of
resources.arsc while the app shows English in those languages anyway.
2026-10-25 14:46:22 +02:00
kalarina 8907f4cf96 Benchmark: warm the emulator up first and run three rounds by default
Two identical APKs differed by 9% in median cold start without it.
2026-10-25 13:39:11 +02:00
kalarina 9aceaaa200 CI: report the size of the packaged baseline profile 2026-10-25 13:39:11 +02:00
kalarina 9e744b309e Benchmark: compile with the baseline profile only, find off-screen rows
The app is now compiled the way Macrobenchmark's Partial mode does it,
so runs compare baseline profiles instead of what the JIT learned in a
warm-up run. Tapping a row scrolls the list when the row is off screen.
2026-10-25 12:35:23 +02:00
kalarina 603e90dcca Mention unit tests and the benchmark in CONTRIBUTING 2026-10-25 12:30:38 +02:00
kalarina e7105b0245 Benchmark: measure memory kept in the background after the Apps tab 2026-10-25 12:29:41 +02:00
kalarina 25e359595b Free decoded app icons once the UI is hidden
The VPN service keeps the process alive in the background, and with it
up to 256 icon bitmaps from the Apps tab.
2026-10-25 12:29:31 +02:00
kalarina 9f9c79cf2b Keep server test results and collapsed app groups across rotation 2026-10-25 12:28:49 +02:00
kalarina 447a309f69 Refuse blocklists with more than 4 million domains
A wrong URL pointing at a huge file could otherwise run the app out of
memory while parsing it.
2026-10-25 12:28:15 +02:00
kalarina 8b975c77ce Show the last app list at once when the Apps tab opens again
The list is still reloaded in the background on every visit; it no
longer starts from the loading placeholder each time.
2026-10-25 12:28:15 +02:00
kalarina 04ef7adb44 Trim Compose work in lists and frequent recompositions
contentType for lazy list items, a set for the own-domain lookup per
Monitor row, the group chevron animated in the draw phase, the custom
URL check remembered and the number format reused.
2026-10-25 12:27:50 +02:00
kalarina f236136919 Log VPN setup and tunnel write errors instead of dropping them silently 2026-10-25 12:27:24 +02:00
kalarina a33a945477 Store launcher icon and logo as lossless WebP
Pixel-identical to the PNGs, 108 KB smaller.
2026-10-25 12:27:01 +02:00
kalarina 8502860512 Add workflow that records a baseline profile on an emulator 2026-10-25 12:26:33 +02:00
kalarina 50f069731c Add LeakCanary to debug builds 2026-10-25 12:25:23 +02:00
kalarina 37653792fd Enable StrictMode in debug builds 2026-10-25 12:25:23 +02:00
kalarina 2cb3439efd Fail lookups that waited too long in the worker queue
With a slow server all 16 workers can be busy for up to 8 s each, and
queries kept piling up long after the asking app had retried or given
up, delaying every newer one.
2026-10-25 12:25:11 +02:00
kalarina 8ac908e684 Drop pooled DoH connections when the default network changes
After a switch between Wi-Fi and mobile data, HTTP/2 lookups could keep
using a connection of the old network until they timed out.
2026-10-25 12:24:09 +02:00
kalarina 5a1bf79e4b Derive all OkHttp clients from one shared base client
The DoH transport keeps its own connection pool and no longer creates
the dispatcher's thread pool only to shut it down.
2026-10-25 12:23:46 +02:00
kalarina 5f56c471ce Keep own blocked domains apart from downloaded lists
Adding or removing one own domain re-sorted the whole combined set,
allocating 8 bytes per entry of every list each time. Lists are now
merged in linear time and own domains are looked up in their own array.
2026-10-25 12:23:21 +02:00
kalarina 87feb7f483 Stop UI updates while the app is in the background
Home and Monitor polled the query log every second and Home queried
ConnectivityManager every 3 s, and kept doing so while the activity
was stopped. The log now signals changes (still at most once a second),
Private DNS comes from a network callback, and all flows are collected
with collectAsStateWithLifecycle.
2026-10-25 12:21:47 +02:00
kalarina a63184830d Run CI for every push instead of queueing them 2026-10-25 12:20:05 +02:00
kalarina 4e99ef1211 Load blocklists at background thread priority 2026-10-25 12:19:49 +02:00
kalarina fa6398c40e Load settings, server list and crash report off the main thread at startup
The first composition of Home read SharedPreferences, servers.txt and
last_crash.txt on the main thread.
2026-10-25 12:19:49 +02:00
kalarina 778ce20f6e Close DoH connections off the main thread when a session stops 2026-10-25 12:19:21 +02:00
kalarina 7da1a34495 Build the DoH transport on the first query instead of the main thread
Creating HttpEngine for HTTP/3 servers (the default one included) ran
inside onStartCommand on every connect and server switch.
2026-10-25 12:19:00 +02:00
kalarina bac4ccf26e Show an error instead of crashing when blocklist changes cannot be saved 2026-10-25 12:18:17 +02:00
kalarina e601b2dbaa Keep the tunnel reader alive on bad packets, disconnect if it dies
Before, any unexpected error ended the reader while the VPN stayed up,
so DNS stopped working for the whole device without any sign of it.
2026-10-25 12:18:17 +02:00
kalarina 8c6bb33527 Add unit tests for packet parsing, DNS cache, blocklist parser and server list
DnsCache takes its clock as a parameter so expiry can be tested.
2026-10-25 12:16:46 +02:00
kalarina 43e57c9357 Add emulator benchmark that compares two revisions 2026-10-25 12:13:31 +02:00
kalarina 87d9afd55b Add CI that builds and unit-tests every pushed commit 2026-10-25 12:00:26 +02:00
kalarina 7a2c7eccb3 Use GPL-3.0-only license wording 2026-10-21 14:50:38 +00:00
kalarina dbc3454742 Make star request platform-neutral 2026-10-20 13:06:24 +00:00
kalarina ad798f0a79 Add star request to README 2026-10-20 12:59:48 +00:00
kalarina 9604d07cea Changelog for 1.0.9 in all languages, mention donation links 2026-10-16 17:06:56 +00:00
kalarina b13adc5340 Add donation links to servers next to the privacy policy 2026-10-16 17:02:29 +00:00
kalarina 5f2dbccebf Point Obtainium links to Gitea 2026-10-16 11:59:23 +00:00
kalarina bab6c754dc Redesign README: store badges, release badge, install options 2026-10-16 11:51:04 +00:00
kalarina ddc219d01f Upload files to "assets" 2026-10-16 11:43:09 +00:00
kalarina 275eb3ab0b Upload files to "assets" 2026-10-16 11:40:39 +00:00
kalarina 62c941a07b Release 1.0.9 2026-10-15 13:43:22 +00:00
66 changed files with 1736 additions and 358 deletions
@@ -9,6 +9,7 @@ title: "[Preset] "
- URL:
- Homepage or documentation:
- Privacy policy (DoH servers) or license (blocklists):
- Donation page (DoH servers, optional):
- [ ] DoH server: public and supports RFC 8484
- [ ] Blocklist: public and actively maintained
+8 -5
View File
@@ -43,18 +43,21 @@ The server list lives in [`servers/servers.txt`](servers/servers.txt). The app d
To add a server, open the file on Gitea, click **Edit**, add one line at the end and send it as a pull request:
```
Name | DoH URL | Privacy policy | h3
Name | DoH URL | Privacy policy | h3 | Donation page
```
- **Name** — how the server appears in the app, up to 40 characters.
- **DoH URL** — the full `https://` address of the DoH endpoint.
- **Privacy policy** — an `https://` link to the operator's privacy policy. Lines without one are ignored.
- **h3** — optional. Add it only if the server supports HTTP/3.
- **Donation page** — optional. An `https://` link to the operator's own page for donations or support. The app shows it as a coin button next to the privacy policy. Only link to a page the operator runs or names on its website — no affiliate or third-party fundraising links.
Example:
Leave out any optional column you don't need; the app recognises them by their content. Examples:
```
Example DNS | https://dns.example.org/dns-query | https://example.org/privacy | h3
Example DNS | https://dns.example.org/dns-query | https://example.org/privacy | h3 | https://example.org/donate
Example DNS | https://dns.example.org/dns-query | https://example.org/privacy | https://example.org/donate
Example DNS | https://dns.example.org/dns-query | https://example.org/privacy
```
The server must:
@@ -66,7 +69,7 @@ The server must:
Before sending, check that it works: in the app choose **Custom server**, enter the URL and tap **Test server**.
Please don't change the lines of the servers that ship with the app (SkySparkle, Quad9, Digitale Gesellschaft, UncensoredDNS, Freifunk München): the app always keeps their built-in addresses. If you are unsure whether a server fits, open an issue with the *DoH server or blocklist* template instead.
Please don't change the lines of the servers that ship with the app (SkySparkle, Quad9, Digitale Gesellschaft, UncensoredDNS, Freifunk München): the app always keeps their built-in addresses and links. To fix one of their links, open an issue instead. If you are unsure whether a server fits, open an issue with the *DoH server or blocklist* template instead.
## Blocklists
@@ -86,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.
+1 -2
View File
@@ -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
+32 -32
View File
@@ -1,23 +1,37 @@
<p align="center">
<img src="assets/icon-rounded.png" width="128" alt="SparkleDNS icon">
<img src="assets/icon-rounded.png" width="112" alt="SparkleDNS icon">
</p>
<h1 align="center">SparkleDNS</h1>
<p align="center"><b>A lightweight DNS-over-HTTPS client for Android.</b></p>
<p align="center">
<a href="https://git.skysparkle.cc/kalarina/Sparkledns/releases"><img src="assets/get-it-on-gitea.png" height="60" alt="Get it on Gitea"></a>
<b>A lightweight DNS-over-HTTPS client for Android.</b><br>
A local VPN that captures only DNS traffic and sends every query to the DoH server you choose (RFC 8484). Everything else goes through your normal connection.
</p>
<p align="center">
<img src="https://img.shields.io/badge/Android-8.0%2B-2e7d32?logo=android&logoColor=white&labelColor=1b1b1b" alt="Android 8.0+">
<img src="https://img.shields.io/badge/License-GPL--3.0--or--later-2e7d32?labelColor=1b1b1b" alt="GPL-3.0-or-later">
<a href="https://github.com/kalarina-bit/Sparkledns/releases/latest"><img src="https://img.shields.io/github/v/release/kalarina-bit/Sparkledns?style=for-the-badge&label=release&labelColor=1b1b1b&color=2e7d32" alt="Latest release"></a>
</p>
SparkleDNS starts a local VPN that captures only DNS traffic and sends every query to the DoH server you choose (RFC 8484). Everything else goes through your normal connection.
<p align="center">
<a href="https://f-droid.org/packages/cc.skysparkle.sparkledns/"><img src="assets/get-it-on%20(1).png" height="56" alt="Get it on F-Droid"></a>
<a href="https://apps.obtainium.imranr.dev/redirect?r=obtainium://add/https://git.skysparkle.cc/kalarina/Sparkledns"><img src="assets/badge_obtainium.png" height="56" alt="Get it on Obtainium"></a>
<a href="https://github.com/kalarina-bit/Sparkledns/releases/latest"><img src="assets/get-it-on-github.png" height="56" alt="Get it on GitHub"></a>
<a href="https://git.skysparkle.cc/kalarina/Sparkledns/releases"><img src="assets/get-it-on-gitea.png" height="56" alt="Get it on Gitea"></a>
</p>
## Features
<p align="center">
<img src="assets/screenshots/1-your-dns-your-choice.png" width="160" alt="Your DNS, your choice">
<img src="assets/screenshots/2-protected.png" width="160" alt="Protected via SkySparkle">
<img src="assets/screenshots/3-stay-informed.png" width="160" alt="Stay informed">
<img src="assets/screenshots/4-block-your-way.png" width="160" alt="Block your way">
<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
- 🔄 **Switch servers on the fly** — the tunnel restarts automatically
@@ -27,27 +41,13 @@ SparkleDNS starts a local VPN that captures only DNS traffic and sends every que
- 🚫 **Custom blocklists** — your own domains plus hosts/domain/AdBlock lists by URL (HaGeZi Pro++ and TIF presets)
- 🔓 **No analytics, no Google Play Services**
## Screenshots
## <img src="assets/icon-install.png" width="32" alt=""> Installation
<p align="center">
<img src="assets/screenshots/1-your-dns-your-choice.png" width="200" alt="Your DNS, your choice">
<img src="assets/screenshots/2-protected.png" width="200" alt="Protected via SkySparkle">
<img src="assets/screenshots/3-stay-informed.png" width="200" alt="Stay informed">
<img src="assets/screenshots/4-block-your-way.png" width="200" alt="Block your way">
<img src="assets/screenshots/5-choose-your-own-route.png" width="200" alt="Choose your own route">
</p>
- **[F-Droid](https://f-droid.org/packages/cc.skysparkle.sparkledns/)** — install and update through the F-Droid client.
- **[Obtainium](https://apps.obtainium.imranr.dev/redirect?r=obtainium://add/https://git.skysparkle.cc/kalarina/Sparkledns)** — installs the APK straight from Gitea releases and keeps it up to date.
- **Manually** — download the latest APK from [GitHub](https://github.com/kalarina-bit/Sparkledns/releases/latest) or [Gitea](https://git.skysparkle.cc/kalarina/Sparkledns/releases), allow installs from unknown sources for the app you open it with (Settings → Apps → Special access → Install unknown apps), then open the `.apk` and confirm.
## Installation
<img src="assets/icon-install.png" width="36" align="left">
1. Download the latest APK from the [Releases page](https://git.skysparkle.cc/kalarina/Sparkledns/releases).
2. Allow installs from unknown sources for the app you open it with (Settings → Apps → Special access → Install unknown apps).
3. Open the `.apk` file and confirm the install.
## Verifying a download
<img src="assets/icon-verify.png" width="36" align="left">
## <img src="assets/icon-verify.png" width="32" alt=""> Verifying a download
Every official APK is signed with the same key. Check it before installing:
@@ -63,7 +63,7 @@ The SHA-256 fingerprint of the signing certificate must be:
`apksigner` prints the same value in lowercase without colons. On Android you can check it with [AppVerifier](https://github.com/soupslurpr/AppVerifier) (app ID `cc.skysparkle.sparkledns`).
## Building from source
## <img src="assets/icon-structure.png" width="32" alt=""> Building from source
Requires JDK 17+ and Android SDK 36.
@@ -75,12 +75,12 @@ Requires JDK 17+ and Android SDK 36.
1. Bump `versionName` and `versionCode` in `app/build.gradle.kts` (`versionCode = major * 10000 + minor * 100 + patch`).
2. Add `fastlane/metadata/android/<locale>/changelogs/<versionCode>.txt`.
3. Tag the commit as `v<versionName>` (for example `v1.0.6`) — F-Droid detects new releases from these tags.
3. Tag the commit as `v<versionName>` (for example `v1.0.9`) — F-Droid detects new releases from these tags, so upload the signed APK to the release right away.
## Contributing
## 🤝 Contributing
Bug reports, DoH server and blocklist suggestions, translation fixes and pull requests are welcome in the [issue tracker](https://git.skysparkle.cc/kalarina/Sparkledns/issues). Please read [CONTRIBUTING.md](CONTRIBUTING.md) first — it explains what fits the project and how to send changes. To open an issue or a pull request, [create an account](https://git.skysparkle.cc/user/sign_up) on this Gitea.
## License
## 📄 License
[GNU General Public License v3.0 or later](LICENSE).
[GNU General Public License v3.0 only](LICENSE).
+20 -2
View File
@@ -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 = 10007
versionName = "1.0.7"
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")
}
+3 -2
View File
@@ -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]) }))
customHashes = LongArray(custom.size) { DomainHash.of(custom[it]) }.sortUnique()
_total.value = unionSize(listHashes, customHashes)
}
_total.value = hashes.size
}
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) }
val result = withContext(Dispatchers.IO) { tryEdit { Blocklist.addCustom(context, input) } }
result.onSuccess { ok ->
domainError = !ok
if (ok) domainInput = ""
}.onFailure { showEditError(context, it) }
}
}
@@ -94,13 +106,19 @@ 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),
) {
item(key = "summary") {
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
Card(Modifier.fillMaxWidth()) {
Row(Modifier.padding(16.dp), verticalAlignment = Alignment.CenterVertically) {
IconBadge(
@@ -138,12 +156,16 @@ fun BlocklistScreen(modifier: Modifier = Modifier) {
}
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,21 +204,33 @@ fun BlocklistScreen(modifier: Modifier = Modifier) {
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
)
}
custom.forEach { domain ->
}
}
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.launch(Dispatchers.IO) { Blocklist.removeCustom(context, domain) } }) {
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,
@@ -225,7 +259,7 @@ fun BlocklistScreen(modifier: Modifier = Modifier) {
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) } },
onDelete = { scope.editBlocklist(context) { Blocklist.removeList(context, list.url) } },
)
}
if (lists.isNotEmpty()) InsetDivider(16)
@@ -295,6 +329,8 @@ fun BlocklistScreen(modifier: Modifier = Modifier) {
}
}
}
}
}
@Composable
private fun InsetDivider(start: Int) {
@@ -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,25 +234,47 @@ 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) {
@@ -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)) {
@@ -290,6 +324,7 @@ fun HomeScreen(modifier: Modifier = Modifier) {
subtitle = hostOf(p.url),
selected = selected == p.id,
onPolicy = p.policy?.let { url -> { openUrl(context, url) } },
onDonate = p.donate?.let { url -> { openUrl(context, url) } },
) { select(p.id) }
}
RowDivider()
@@ -404,6 +439,7 @@ private fun StatusHero(
http3: Boolean,
stats: QueryStats,
canConnect: Boolean,
busy: Boolean,
switchTo: String?,
onToggle: () -> Unit,
onSwitch: () -> Unit,
@@ -489,7 +525,7 @@ private fun StatusHero(
Button(
onClick = onToggle,
enabled = running || canConnect,
enabled = (running || canConnect) && !busy,
modifier = Modifier
.fillMaxWidth()
.height(52.dp),
@@ -505,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]))
@@ -571,6 +607,7 @@ private fun ProviderRow(
subtitle: String,
selected: Boolean,
onPolicy: (() -> Unit)? = null,
onDonate: (() -> Unit)? = null,
onClick: () -> Unit,
) {
val highlight by animateColorAsState(
@@ -598,6 +635,16 @@ private fun ProviderRow(
overflow = TextOverflow.Ellipsis,
)
}
if (onDonate != null) {
IconButton(onClick = onDonate, modifier = Modifier.size(40.dp)) {
Icon(
painterResource(R.drawable.ic_donate),
contentDescription = stringResource(R.string.donate),
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(18.dp),
)
}
}
if (onPolicy != null) {
IconButton(onClick = onPolicy, modifier = Modifier.size(40.dp)) {
Icon(
@@ -619,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) {
OnQueryLogChange {
entries = QueryLog.snapshot()
stats = QueryLog.stats()
delay(1000)
}
}
val visible = remember(entries, filter, search) {
@@ -90,7 +86,8 @@ fun MonitorScreen(modifier: Modifier = Modifier) {
fun toggleBlock(domain: String, unblock: Boolean) {
scope.launch {
val ok = withContext(Dispatchers.IO) {
val result = withContext(Dispatchers.IO) {
tryEdit {
if (unblock) {
Blocklist.removeCustom(context, domain)
true
@@ -98,6 +95,11 @@ fun MonitorScreen(modifier: Modifier = Modifier) {
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
@@ -17,6 +16,7 @@ data class DohProvider(
val bootstrap: List<String> = emptyList(),
val http3: Boolean = false,
val policy: String? = null,
val donate: String? = null,
)
object Providers {
@@ -32,11 +32,13 @@ object Providers {
DohProvider(
"quad9", "Quad9", "https://dns.quad9.net/dns-query", listOf("9.9.9.9", "149.112.112.112"),
policy = "https://quad9.net/service/privacy/",
donate = "https://quad9.net/donate/",
),
DohProvider(
"digitale-gesellschaft", "Digitale Gesellschaft", "https://dns.digitale-gesellschaft.ch/dns-query",
listOf("185.95.218.42", "185.95.218.43"), http3 = true,
policy = "https://www.digitale-gesellschaft.ch/dns/",
donate = "https://www.digitale-gesellschaft.ch/uber-uns/unterstuetzer-werden/",
),
DohProvider(
"uncensoreddns", "UncensoredDNS", "https://anycast.uncensoreddns.org/dns-query", listOf("91.239.100.100"),
@@ -46,6 +48,7 @@ object Providers {
"ffmuc", "Freifunk München", "https://doh.ffmuc.net/dns-query",
listOf("5.1.66.255", "185.150.99.255"), http3 = true,
policy = "https://ffmuc.net/dns-privacy/",
donate = "https://spende.ffmuc.net/",
),
)
@@ -70,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()
}
@@ -111,7 +113,8 @@ object ServerList {
return parsed.size
}
// Format per line: Name | DoH URL | privacy policy URL | h3 (optional). See CONTRIBUTING.md.
// Format per line: Name | DoH URL | privacy policy URL | h3 (optional) | donation URL (optional).
// The optional columns are recognised by content, so either can be left out. See CONTRIBUTING.md.
fun parse(text: String): List<DohProvider> {
val builtInByHost = Providers.builtIn.associateBy { it.url.toHttpUrlOrNull()?.host }
val seen = HashSet<String>()
@@ -125,11 +128,14 @@ object ServerList {
val url = cols[1].toHttpUrlOrNull()
val policy = cols[2].takeIf { it.toHttpUrlOrNull()?.isHttps == true }
if (name.isEmpty() || url == null || !url.isHttps) continue
// Shipped servers keep their address and id, so an edited list cannot redirect them
val extras = cols.drop(3)
val http3 = extras.any { it.equals("h3", ignoreCase = true) }
val donate = extras.firstOrNull { it.toHttpUrlOrNull()?.isHttps == true }
// Shipped servers keep their address, id and links, so an edited list cannot redirect them
val pinned = builtInByHost[url.host]
val server = pinned
?: if (policy == null) continue
else DohProvider(url.host, name, cols[1], http3 = cols.getOrElse(3) { "" }.equals("h3", ignoreCase = true), policy = policy)
else DohProvider(url.host, name, cols[1], http3 = http3, policy = policy, donate = donate)
if (!seen.add(server.id)) continue
result += server
if (result.size >= MAX_SERVERS) break
@@ -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}%"
Binary file not shown.

Before

Width:  |  Height:  |  Size: 184 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 124 KiB

+21
View File
@@ -0,0 +1,21 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="256"
android:viewportHeight="256">
<path
android:pathData="M128,38 A90,90 0 1,1 128,218 A90,90 0 1,1 128,38 Z"
android:strokeColor="#FFFFFFFF"
android:strokeWidth="11" />
<path
android:pathData="M156,99 C151,88 141,82 128,82 C112,82 100,91 100,105 C100,120 113,125 128,128 C144,131 158,137 158,153 C158,167 145,175 128,175 C113,175 101,168 97,156"
android:strokeColor="#FFFFFFFF"
android:strokeWidth="11"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M128,64 L128,82 M128,175 L128,193"
android:strokeColor="#FFFFFFFF"
android:strokeWidth="11"
android:strokeLineCap="round" />
</vector>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 82 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

+2
View File
@@ -84,6 +84,7 @@
<string name="group_system">System</string>
<string name="group_count">%1$d von %2$d über DNS</string>
<string name="about_privacy_policy">Datenschutzerklärung</string>
<string name="donate">Spenden</string>
<string name="licenses_title">Open-Source-Lizenzen</string>
<string name="licenses_hint">SparkleDNS basiert auf diesen Open-Source-Projekten. Tippe auf ein Projekt, um seine Seite zu öffnen.</string>
<string name="licenses_data">Sperrlisten-Daten (bei Bedarf geladen, nicht enthalten)</string>
@@ -97,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>
+2
View File
@@ -84,6 +84,7 @@
<string name="group_system">システム</string>
<string name="group_count">%2$d 件中 %1$d 件が DNS 経由</string>
<string name="about_privacy_policy">プライバシーポリシー</string>
<string name="donate">寄付する</string>
<string name="licenses_title">オープンソースライセンス</string>
<string name="licenses_hint">SparkleDNS は以下のオープンソースプロジェクトで作られています。タップするとプロジェクトのページを開きます。</string>
<string name="licenses_data">ブロックリストのデータ(必要なときにダウンロード、同梱なし)</string>
@@ -97,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>
+2
View File
@@ -84,6 +84,7 @@
<string name="group_system">Sistema</string>
<string name="group_count">%1$d iš %2$d per DNS</string>
<string name="about_privacy_policy">Privatumo politika</string>
<string name="donate">Paaukoti</string>
<string name="licenses_title">Atvirojo kodo licencijos</string>
<string name="licenses_hint">SparkleDNS sukurta naudojant šiuos atvirojo kodo projektus. Palieskite projektą, kad atidarytumėte jo puslapį.</string>
<string name="licenses_data">Blokavimo sąrašų duomenys (atsisiunčiami pagal poreikį, neįtraukti)</string>
@@ -97,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>
+2
View File
@@ -84,6 +84,7 @@
<string name="group_system">Системные</string>
<string name="group_count">%1$d из %2$d через DNS</string>
<string name="about_privacy_policy">Политика конфиденциальности</string>
<string name="donate">Пожертвовать</string>
<string name="licenses_title">Лицензии открытого ПО</string>
<string name="licenses_hint">SparkleDNS построен на этих проектах с открытым кодом. Нажмите на проект, чтобы открыть его страницу.</string>
<string name="licenses_data">Данные блоклистов (загружаются по запросу, не входят в приложение)</string>
@@ -97,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>
+2
View File
@@ -84,6 +84,7 @@
<string name="group_system">系统</string>
<string name="group_count">%2$d 个中有 %1$d 个经过 DNS</string>
<string name="about_privacy_policy">隐私政策</string>
<string name="donate">捐赠</string>
<string name="licenses_title">开源许可</string>
<string name="licenses_hint">SparkleDNS 使用了以下开源项目。点按项目可打开其页面。</string>
<string name="licenses_data">屏蔽列表数据(按需下载,未内置)</string>
@@ -97,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>
+2
View File
@@ -85,6 +85,7 @@
<string name="group_system">System</string>
<string name="group_count">%1$d of %2$d via DNS</string>
<string name="about_privacy_policy">Privacy policy</string>
<string name="donate">Donate</string>
<string name="licenses_title">Open-source licenses</string>
<string name="licenses_hint">SparkleDNS is built with these open-source projects. Tap a project to open its page.</string>
<string name="licenses_data">Blocklist data (downloaded on demand, not bundled)</string>
@@ -98,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)
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.3 KiB

@@ -0,0 +1,5 @@
• Spendenlinks neben der Datenschutzerklärung bei Servern, die Spenden annehmen
• Einfachere Serverliste
• Neues Symbol für die Datenschutzerklärung bei den Servern
• HTTP/3-Kennzeichnung aus der Serverliste entfernt
• Kürzere Beschreibung unter „Info“
@@ -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,5 @@
• Donation links next to the privacy policy for servers that accept donations
• Simpler server list
• New privacy policy icon on servers
• HTTP/3 badge removed from the server list
• Shorter About description
@@ -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,5 @@
• 寄付を受け付けているサーバーには、プライバシーポリシーの横に寄付リンクを表示
• サーバーリストをシンプルに
• サーバーのプライバシーポリシーアイコンを新しく
• サーバーリストから HTTP/3 の表示を削除
• 「情報」の説明を短く
@@ -0,0 +1,6 @@
• 想定外のパケットが届いても DNS は動作し続けます。トンネルが故障した場合は、DNS を黙って止めずに VPN をオフにします
• Wi-Fi とモバイルデータの切り替え後や遅いネットワークで、名前解決がより早く回復します
• バックグラウンドでの処理を削減:表示されていない画面は更新しません
• ブロックリストは変更があったときだけ再ダウンロードします
• アプリアイコンがより鮮明に、アプリサイズが小さく
• 「接続」をダブルタップしても二重に接続しません。ストレージがいっぱいでもアプリが落ちなくなりました
@@ -0,0 +1,5 @@
• Prie serverių, kurie priima aukas, šalia privatumo politikos – nuoroda aukoti
• Paprastesnis serverių sąrašas
• Nauja privatumo politikos piktograma prie serverių
• HTTP/3 žymė pašalinta iš serverių sąrašo
• Trumpesnis aprašymas skiltyje „Apie“
@@ -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,5 @@
• У серверов, которые принимают пожертвования, рядом с политикой конфиденциальности появилась ссылка на пожертвование
• Упрощённый список серверов
• Новый значок политики конфиденциальности у серверов
• Значок HTTP/3 убран из списка серверов
• Короче описание в «О программе»
@@ -0,0 +1,6 @@
• DNS продолжает работать, если пришёл неожиданный пакет; при сбое туннеля VPN отключается, а не блокирует DNS молча
• Запросы быстрее восстанавливаются после переключения между Wi-Fi и мобильной сетью и в медленных сетях
• Меньше работы в фоне: скрытые экраны больше не обновляются
• Блоклисты скачиваются заново, только если изменились
• Чётче значки приложений, меньше размер приложения
• Двойное нажатие «Подключить» больше не подключает дважды; переполненная память больше не роняет приложение
@@ -0,0 +1,5 @@
• 接受捐赠的服务器在隐私政策旁显示捐赠链接
• 服务器列表更简洁
• 服务器的隐私政策图标焕新
• 服务器列表中移除 HTTP/3 标识
• “关于”中的介绍更简短
@@ -0,0 +1,6 @@
• 收到意外的数据包时 DNS 仍可正常工作;隧道出错时会关闭 VPN,而不是悄悄阻断 DNS
• 在 Wi-Fi 与移动数据之间切换后以及网速较慢时,域名解析恢复更快
• 后台工作更少:不再刷新隐藏的界面
• 拦截列表仅在有变化时重新下载
• 应用图标更清晰,应用体积更小
• 连点“连接”不会再重复连接;存储空间已满时应用不再崩溃
+71
View File
@@ -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")"
+29
View File
@@ -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
+222
View File
@@ -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'}"
+4 -4
View File
@@ -1,8 +1,8 @@
# SparkleDNS server list. How to add a server: see CONTRIBUTING.md
# Name | DoH URL | Privacy policy | h3 (optional)
# Name | DoH URL | Privacy policy | h3 (optional) | Donation page (optional)
SkySparkle | https://blog.skysparkle.cc/dns-query | https://skysparkle.cc/privacy?lang=en | h3
Quad9 | https://dns.quad9.net/dns-query | https://quad9.net/service/privacy/
Digitale Gesellschaft | https://dns.digitale-gesellschaft.ch/dns-query | https://www.digitale-gesellschaft.ch/dns/ | h3
Quad9 | https://dns.quad9.net/dns-query | https://quad9.net/service/privacy/ | https://quad9.net/donate/
Digitale Gesellschaft | https://dns.digitale-gesellschaft.ch/dns-query | https://www.digitale-gesellschaft.ch/dns/ | h3 | https://www.digitale-gesellschaft.ch/uber-uns/unterstuetzer-werden/
UncensoredDNS | https://anycast.uncensoreddns.org/dns-query | https://blog.uncensoreddns.org/faq/
Freifunk München | https://doh.ffmuc.net/dns-query | https://ffmuc.net/dns-privacy/ | h3
Freifunk München | https://doh.ffmuc.net/dns-query | https://ffmuc.net/dns-privacy/ | h3 | https://spende.ffmuc.net/