Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
43f0d42d65 | ||
|
|
2b0f842579 | ||
|
|
17ede339fa | ||
|
|
ac643caf03 | ||
|
|
0ceae2f557 | ||
|
|
df41b44302 | ||
|
|
4619292174 | ||
|
|
cff974851a | ||
|
|
d9080195ab | ||
|
|
026c2c9493 | ||
|
|
8907f4cf96 | ||
|
|
9aceaaa200 | ||
|
|
9e744b309e | ||
|
|
603e90dcca | ||
|
|
e7105b0245 | ||
|
|
25e359595b | ||
|
|
9f9c79cf2b | ||
|
|
447a309f69 | ||
|
|
8b975c77ce | ||
|
|
04ef7adb44 | ||
|
|
f236136919 | ||
|
|
a33a945477 | ||
|
|
8502860512 | ||
|
|
50f069731c | ||
|
|
37653792fd | ||
|
|
2cb3439efd | ||
|
|
8ac908e684 | ||
|
|
5a1bf79e4b | ||
|
|
5f56c471ce | ||
|
|
87feb7f483 | ||
|
|
a63184830d | ||
|
|
4e99ef1211 | ||
|
|
fa6398c40e | ||
|
|
778ce20f6e | ||
|
|
7da1a34495 | ||
|
|
bac4ccf26e | ||
|
|
e601b2dbaa | ||
|
|
8c6bb33527 | ||
|
|
43e57c9357 | ||
|
|
87d9afd55b | ||
|
|
7a2c7eccb3 | ||
|
|
dbc3454742 | ||
|
|
ad798f0a79 | ||
|
|
9604d07cea | ||
|
|
b13adc5340 | ||
|
|
5f2dbccebf | ||
|
|
bab6c754dc | ||
|
|
ddc219d01f | ||
|
|
275eb3ab0b | ||
|
|
62c941a07b |
@@ -9,6 +9,7 @@ title: "[Preset] "
|
|||||||
- URL:
|
- URL:
|
||||||
- Homepage or documentation:
|
- Homepage or documentation:
|
||||||
- Privacy policy (DoH servers) or license (blocklists):
|
- Privacy policy (DoH servers) or license (blocklists):
|
||||||
|
- Donation page (DoH servers, optional):
|
||||||
|
|
||||||
- [ ] DoH server: public and supports RFC 8484
|
- [ ] DoH server: public and supports RFC 8484
|
||||||
- [ ] Blocklist: public and actively maintained
|
- [ ] Blocklist: public and actively maintained
|
||||||
|
|||||||
@@ -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:
|
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.
|
- **Name** — how the server appears in the app, up to 40 characters.
|
||||||
- **DoH URL** — the full `https://` address of the DoH endpoint.
|
- **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.
|
- **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.
|
- **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:
|
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**.
|
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
|
## 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`.
|
1. Fork the repository and create a branch from `main`.
|
||||||
2. Keep one topic per pull request.
|
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.
|
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`).
|
5. Write short, plain commit messages in English (for example `Fix tunnel restart after server switch`).
|
||||||
6. Add screenshots for UI changes.
|
6. Add screenshots for UI changes.
|
||||||
|
|
||||||
|
|||||||
@@ -636,8 +636,7 @@ the "copyright" line and a pointer to where the full notice is found.
|
|||||||
|
|
||||||
This program is free software: you can redistribute it and/or modify
|
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
|
it under the terms of the GNU General Public License as published by
|
||||||
the Free Software Foundation, either version 3 of the License, or
|
the Free Software Foundation, version 3 of the License.
|
||||||
(at your option) any later version.
|
|
||||||
|
|
||||||
This program is distributed in the hope that it will be useful,
|
This program is distributed in the hope that it will be useful,
|
||||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
|||||||
@@ -1,23 +1,37 @@
|
|||||||
<p align="center">
|
<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>
|
</p>
|
||||||
|
|
||||||
<h1 align="center">SparkleDNS</h1>
|
<h1 align="center">SparkleDNS</h1>
|
||||||
|
|
||||||
<p align="center"><b>A lightweight DNS-over-HTTPS client for Android.</b></p>
|
|
||||||
|
|
||||||
<p align="center">
|
<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>
|
||||||
|
|
||||||
<p align="center">
|
<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+">
|
<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>
|
||||||
<img src="https://img.shields.io/badge/License-GPL--3.0--or--later-2e7d32?labelColor=1b1b1b" alt="GPL-3.0-or-later">
|
|
||||||
</p>
|
</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
|
- 🔌 **One-tap connect/disconnect**, with a Quick Settings tile
|
||||||
- 🔄 **Switch servers on the fly** — the tunnel restarts automatically
|
- 🔄 **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)
|
- 🚫 **Custom blocklists** — your own domains plus hosts/domain/AdBlock lists by URL (HaGeZi Pro++ and TIF presets)
|
||||||
- 🔓 **No analytics, no Google Play Services**
|
- 🔓 **No analytics, no Google Play Services**
|
||||||
|
|
||||||
## Screenshots
|
## <img src="assets/icon-install.png" width="32" alt=""> Installation
|
||||||
|
|
||||||
<p align="center">
|
- **[F-Droid](https://f-droid.org/packages/cc.skysparkle.sparkledns/)** — install and update through the F-Droid client.
|
||||||
<img src="assets/screenshots/1-your-dns-your-choice.png" width="200" alt="Your DNS, your choice">
|
- **[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.
|
||||||
<img src="assets/screenshots/2-protected.png" width="200" alt="Protected via SkySparkle">
|
- **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.
|
||||||
<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>
|
|
||||||
|
|
||||||
## Installation
|
## <img src="assets/icon-verify.png" width="32" alt=""> Verifying a download
|
||||||
|
|
||||||
<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">
|
|
||||||
|
|
||||||
Every official APK is signed with the same key. Check it before installing:
|
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`).
|
`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.
|
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`).
|
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`.
|
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.
|
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).
|
||||||
|
|||||||
@@ -13,8 +13,8 @@ android {
|
|||||||
targetSdk = 36
|
targetSdk = 36
|
||||||
// Single source of truth: the About screen reads these through BuildConfig.
|
// 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.
|
// Kept as plain literals so F-Droid can detect new versions. Code = major * 10000 + minor * 100 + patch.
|
||||||
versionCode = 10007
|
versionCode = 10010
|
||||||
versionName = "1.0.7"
|
versionName = "1.0.10"
|
||||||
}
|
}
|
||||||
|
|
||||||
buildTypes {
|
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 {
|
compileOptions {
|
||||||
sourceCompatibility = JavaVersion.VERSION_17
|
sourceCompatibility = JavaVersion.VERSION_17
|
||||||
targetCompatibility = JavaVersion.VERSION_17
|
targetCompatibility = JavaVersion.VERSION_17
|
||||||
@@ -42,6 +48,11 @@ android {
|
|||||||
includeInApk = false
|
includeInApk = false
|
||||||
includeInBundle = false
|
includeInBundle = false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
testOptions {
|
||||||
|
// android.util.Log and friends are no-ops in JVM unit tests
|
||||||
|
unitTests.isReturnDefaultValues = true
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
@@ -49,6 +60,13 @@ dependencies {
|
|||||||
implementation("androidx.activity:activity-compose:1.10.1")
|
implementation("androidx.activity:activity-compose:1.10.1")
|
||||||
implementation("androidx.compose.ui:ui")
|
implementation("androidx.compose.ui:ui")
|
||||||
implementation("androidx.compose.material3:material3")
|
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("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2")
|
||||||
implementation("com.squareup.okhttp3:okhttp:4.12.0")
|
implementation("com.squareup.okhttp3:okhttp:4.12.0")
|
||||||
|
|
||||||
|
// Debug builds only, never part of a release
|
||||||
|
debugImplementation("com.squareup.leakcanary:leakcanary-android:2.14")
|
||||||
|
|
||||||
|
testImplementation("junit:junit:4.13.2")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
# Readable stack traces in crash reports
|
# File names and line numbers stay in stack traces, names are obfuscated. To read a crash
|
||||||
|
# report, build the same release (builds are reproducible) and run
|
||||||
|
# retrace app/build/outputs/mapping/release/mapping.txt crash.txt
|
||||||
-keepattributes SourceFile,LineNumberTable
|
-keepattributes SourceFile,LineNumberTable
|
||||||
-dontobfuscate
|
|
||||||
|
|||||||
@@ -1,9 +1,12 @@
|
|||||||
package cc.skysparkle.sparkledns
|
package cc.skysparkle.sparkledns
|
||||||
|
|
||||||
|
import android.content.ActivityNotFoundException
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
|
import android.util.Log
|
||||||
|
import android.widget.Toast
|
||||||
import androidx.activity.compose.BackHandler
|
import androidx.activity.compose.BackHandler
|
||||||
import androidx.compose.animation.AnimatedContent
|
import androidx.compose.animation.AnimatedContent
|
||||||
import androidx.compose.animation.fadeIn
|
import androidx.compose.animation.fadeIn
|
||||||
@@ -264,7 +267,12 @@ private fun InfoRow(label: String, value: String) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
internal fun openUrl(context: Context, url: 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))
|
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.material3.TriStateCheckbox
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.LaunchedEffect
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
import androidx.compose.runtime.collectAsState
|
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.produceState
|
import androidx.compose.runtime.produceState
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.saveable.Saver
|
||||||
import androidx.compose.runtime.saveable.rememberSaveable
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.draw.clip
|
import androidx.compose.ui.draw.clip
|
||||||
import androidx.compose.ui.draw.rotate
|
|
||||||
import androidx.compose.ui.graphics.ImageBitmap
|
import androidx.compose.ui.graphics.ImageBitmap
|
||||||
import androidx.compose.ui.graphics.asImageBitmap
|
import androidx.compose.ui.graphics.asImageBitmap
|
||||||
|
import androidx.compose.ui.graphics.graphicsLayer
|
||||||
import androidx.compose.ui.platform.LocalContext
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.platform.LocalDensity
|
||||||
import androidx.compose.ui.res.painterResource
|
import androidx.compose.ui.res.painterResource
|
||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
import androidx.compose.ui.semantics.Role
|
import androidx.compose.ui.semantics.Role
|
||||||
import androidx.compose.ui.state.ToggleableState
|
import androidx.compose.ui.state.ToggleableState
|
||||||
import androidx.compose.ui.text.style.TextOverflow
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.withContext
|
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)
|
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
|
// Decoded icons survive scrolling and tab switches instead of being rendered again every time.
|
||||||
private val IconCache = LruCache<String, ImageBitmap>(256)
|
// 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
|
@Composable
|
||||||
fun AppsScreen(modifier: Modifier = Modifier) {
|
fun AppsScreen(modifier: Modifier = Modifier) {
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
val prefs = remember { Prefs(context) }
|
val prefs = remember { Prefs(context) }
|
||||||
val active by DohVpnService.active.collectAsState()
|
val active by DohVpnService.active.collectAsStateWithLifecycle()
|
||||||
val activeExcluded by DohVpnService.activeExcluded.collectAsState()
|
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 excluded by remember { mutableStateOf(prefs.excludedApps) }
|
||||||
var search by rememberSaveable { mutableStateOf("") }
|
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
|
val pending = active != null && excluded != activeExcluded
|
||||||
var showAppsHint by remember { mutableStateOf(!prefs.isHintDismissed(HINT_APPS)) }
|
var showAppsHint by remember { mutableStateOf(!prefs.isHintDismissed(HINT_APPS)) }
|
||||||
// Closing the "reconnect" card hides it until the selection changes again
|
// Closing the "reconnect" card hides it until the selection changes again
|
||||||
@@ -100,7 +111,7 @@ fun AppsScreen(modifier: Modifier = Modifier) {
|
|||||||
val searching = search.isNotBlank()
|
val searching = search.isNotBlank()
|
||||||
|
|
||||||
LaunchedEffect(Unit) {
|
LaunchedEffect(Unit) {
|
||||||
apps = withContext(Dispatchers.IO) { loadApps(context) }
|
apps = withContext(Dispatchers.IO) { loadApps(context) }.also { lastAppList = it }
|
||||||
}
|
}
|
||||||
|
|
||||||
val groups = remember(apps, search) {
|
val groups = remember(apps, search) {
|
||||||
@@ -188,7 +199,7 @@ fun AppsScreen(modifier: Modifier = Modifier) {
|
|||||||
|
|
||||||
groups.forEach { (group, items) ->
|
groups.forEach { (group, items) ->
|
||||||
val expanded = searching || group !in collapsed
|
val expanded = searching || group !in collapsed
|
||||||
item(key = "group:${group.name}") {
|
item(key = "group:${group.name}", contentType = "group") {
|
||||||
GroupHeader(
|
GroupHeader(
|
||||||
modifier = Modifier.animateItem(),
|
modifier = Modifier.animateItem(),
|
||||||
group = group,
|
group = group,
|
||||||
@@ -205,7 +216,7 @@ fun AppsScreen(modifier: Modifier = Modifier) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
if (expanded) {
|
if (expanded) {
|
||||||
itemsIndexed(items, key = { _, app -> app.packageName }) { index, app ->
|
itemsIndexed(items, key = { _, app -> app.packageName }, contentType = { _, _ -> "app" }) { index, app ->
|
||||||
AppRow(
|
AppRow(
|
||||||
modifier = Modifier.animateItem(),
|
modifier = Modifier.animateItem(),
|
||||||
app = app,
|
app = app,
|
||||||
@@ -237,7 +248,8 @@ private fun GroupHeader(
|
|||||||
else -> ToggleableState.Indeterminate
|
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(
|
Row(
|
||||||
modifier = modifier
|
modifier = modifier
|
||||||
@@ -267,7 +279,7 @@ private fun GroupHeader(
|
|||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.padding(end = 8.dp)
|
.padding(end = 8.dp)
|
||||||
.size(22.dp)
|
.size(22.dp)
|
||||||
.rotate(chevron),
|
.graphicsLayer { rotationZ = chevron.value },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -275,12 +287,15 @@ private fun GroupHeader(
|
|||||||
@Composable
|
@Composable
|
||||||
private fun AppRow(modifier: Modifier, app: AppItem, enabled: Boolean, last: Boolean, onToggle: (Boolean) -> Unit) {
|
private fun AppRow(modifier: Modifier, app: AppItem, enabled: Boolean, last: Boolean, onToggle: (Boolean) -> Unit) {
|
||||||
val context = LocalContext.current
|
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
|
if (value != null) return@produceState
|
||||||
value = withContext(Dispatchers.IO) {
|
value = withContext(Dispatchers.IO) {
|
||||||
runCatching { context.packageManager.getApplicationIcon(app.packageName).toImageBitmap(96) }
|
runCatching { context.packageManager.getApplicationIcon(app.packageName).toImageBitmap(iconPx) }
|
||||||
.getOrNull()
|
.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()
|
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"
|
private const val HINT_APPS = "apps"
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
package cc.skysparkle.sparkledns
|
package cc.skysparkle.sparkledns
|
||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
|
import android.content.SharedPreferences
|
||||||
|
import android.util.Log
|
||||||
|
import kotlinx.coroutines.CoroutineExceptionHandler
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.SupervisorJob
|
import kotlinx.coroutines.SupervisorJob
|
||||||
@@ -28,7 +31,9 @@ data class RemoteList(val url: String, val count: Int, val updated: Long)
|
|||||||
object Blocklist {
|
object Blocklist {
|
||||||
const val ALL_LISTS = "*"
|
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 lock = Any()
|
||||||
|
|
||||||
private val _enabled = MutableStateFlow(true)
|
private val _enabled = MutableStateFlow(true)
|
||||||
@@ -51,24 +56,16 @@ object Blocklist {
|
|||||||
private val _error = MutableStateFlow<String?>(null)
|
private val _error = MutableStateFlow<String?>(null)
|
||||||
val error: StateFlow<String?> = _error
|
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
|
@Volatile
|
||||||
private var hashes = LongArray(0)
|
|
||||||
private var listHashes = LongArray(0)
|
private var listHashes = LongArray(0)
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
private var customHashes = LongArray(0)
|
||||||
private var loaded = false
|
private var loaded = false
|
||||||
|
|
||||||
fun isBlocked(name: String): Boolean {
|
fun isBlocked(name: String): Boolean = _enabled.value && isBlockedIn(name, listHashes, customHashes)
|
||||||
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 reload(context: Context) = synchronized(lock) { load(BlocklistStore(context)) }
|
fun reload(context: Context) = synchronized(lock) { load(BlocklistStore(context)) }
|
||||||
|
|
||||||
@@ -84,7 +81,7 @@ object Blocklist {
|
|||||||
val updated = (_custom.value + domain).distinct().sorted()
|
val updated = (_custom.value + domain).distinct().sorted()
|
||||||
store.saveCustom(updated)
|
store.saveCustom(updated)
|
||||||
_custom.value = updated
|
_custom.value = updated
|
||||||
combine()
|
updateCustomHashes()
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -94,7 +91,7 @@ object Blocklist {
|
|||||||
val updated = _custom.value - domain
|
val updated = _custom.value - domain
|
||||||
store.saveCustom(updated)
|
store.saveCustom(updated)
|
||||||
_custom.value = updated
|
_custom.value = updated
|
||||||
combine()
|
updateCustomHashes()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun removeList(context: Context, url: String) = synchronized(lock) {
|
fun removeList(context: Context, url: String) = synchronized(lock) {
|
||||||
@@ -114,9 +111,10 @@ object Blocklist {
|
|||||||
if (target.isEmpty() || !_busy.compareAndSet(null, target)) return false
|
if (target.isEmpty() || !_busy.compareAndSet(null, target)) return false
|
||||||
_error.value = null
|
_error.value = null
|
||||||
val store = BlocklistStore(context.applicationContext)
|
val store = BlocklistStore(context.applicationContext)
|
||||||
|
val previous = _lists.value.firstOrNull { it.url == target }
|
||||||
scope.launch {
|
scope.launch {
|
||||||
try {
|
try {
|
||||||
val list = store.download(target)
|
val list = store.download(target, previous)
|
||||||
commit(store, listOf(list))
|
commit(store, listOf(list))
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
_error.value = e.message ?: e.javaClass.simpleName
|
_error.value = e.message ?: e.javaClass.simpleName
|
||||||
@@ -131,18 +129,20 @@ object Blocklist {
|
|||||||
if (_lists.value.isEmpty() || !_busy.compareAndSet(null, ALL_LISTS)) return false
|
if (_lists.value.isEmpty() || !_busy.compareAndSet(null, ALL_LISTS)) return false
|
||||||
_error.value = null
|
_error.value = null
|
||||||
val store = BlocklistStore(context.applicationContext)
|
val store = BlocklistStore(context.applicationContext)
|
||||||
val urls = _lists.value.map { it.url }
|
val current = _lists.value
|
||||||
scope.launch {
|
scope.launch {
|
||||||
try {
|
try {
|
||||||
val fresh = urls.mapNotNull { url ->
|
val fresh = current.mapNotNull { list ->
|
||||||
try {
|
try {
|
||||||
store.download(url)
|
store.download(list.url, list)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
if (_error.value == null) _error.value = e.message ?: e.javaClass.simpleName
|
if (_error.value == null) _error.value = e.message ?: e.javaClass.simpleName
|
||||||
null
|
null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
commit(store, fresh)
|
commit(store, fresh)
|
||||||
|
} catch (e: IOException) {
|
||||||
|
_error.value = e.message ?: e.javaClass.simpleName
|
||||||
} finally {
|
} finally {
|
||||||
_busy.value = null
|
_busy.value = null
|
||||||
}
|
}
|
||||||
@@ -169,35 +169,76 @@ object Blocklist {
|
|||||||
_enabled.value = store.enabled
|
_enabled.value = store.enabled
|
||||||
_custom.value = store.loadCustom()
|
_custom.value = store.loadCustom()
|
||||||
_lists.value = store.loadLists()
|
_lists.value = store.loadLists()
|
||||||
|
val custom = _custom.value
|
||||||
|
customHashes = LongArray(custom.size) { DomainHash.of(custom[it]) }.sortUnique()
|
||||||
reloadListHashes(store)
|
reloadListHashes(store)
|
||||||
loaded = true
|
loaded = true
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun reloadListHashes(store: BlocklistStore) {
|
private fun reloadListHashes(store: BlocklistStore) {
|
||||||
listHashes = merge(_lists.value.map { store.loadListHashes(it.url) })
|
listHashes = mergeSorted(_lists.value.map { store.loadListHashes(it.url) })
|
||||||
combine()
|
_total.value = unionSize(listHashes, customHashes)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun combine() {
|
private fun updateCustomHashes() {
|
||||||
val custom = _custom.value
|
val custom = _custom.value
|
||||||
hashes = if (custom.isEmpty()) {
|
customHashes = LongArray(custom.size) { DomainHash.of(custom[it]) }.sortUnique()
|
||||||
listHashes
|
_total.value = unionSize(listHashes, customHashes)
|
||||||
} else {
|
|
||||||
merge(listOf(listHashes, LongArray(custom.size) { DomainHash.of(custom[it]) }))
|
|
||||||
}
|
|
||||||
_total.value = hashes.size
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun merge(parts: List<LongArray>): LongArray {
|
// True when the name or one of its parent domains is in either sorted hash set
|
||||||
val nonEmpty = parts.filter { it.isNotEmpty() }
|
internal fun isBlockedIn(name: String, lists: LongArray, custom: LongArray): Boolean {
|
||||||
if (nonEmpty.size <= 1) return nonEmpty.firstOrNull() ?: LongArray(0) // stored lists are already sorted
|
if (lists.isEmpty() && custom.isEmpty()) return false
|
||||||
val all = LongArray(nonEmpty.sumOf { it.size })
|
val domain = name.trimEnd('.')
|
||||||
var pos = 0
|
var start = 0
|
||||||
nonEmpty.forEach { it.copyInto(all, pos); pos += it.size }
|
while (true) {
|
||||||
return all.sortUnique()
|
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 {
|
internal object DomainHash {
|
||||||
private const val FNV_OFFSET = -3750763034362895579L // 0xcbf29ce484222325
|
private const val FNV_OFFSET = -3750763034362895579L // 0xcbf29ce484222325
|
||||||
private const val FNV_PRIME = 1099511628211L
|
private const val FNV_PRIME = 1099511628211L
|
||||||
@@ -290,22 +331,38 @@ private class BlocklistStore(context: Context) {
|
|||||||
fun deleteListFile(url: String) {
|
fun deleteListFile(url: String) {
|
||||||
binFile(url).delete()
|
binFile(url).delete()
|
||||||
textFile(url).delete()
|
textFile(url).delete()
|
||||||
|
sp.edit().remove(etagKey(url)).remove(modifiedKey(url)).apply()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun download(url: String): RemoteList {
|
// With the list already on disk the server is asked for a changed one only, so updating
|
||||||
val request = runCatching { Request.Builder().url(url).build() }
|
// a list that did not change costs a few hundred bytes instead of megabytes
|
||||||
.getOrElse { throw IOException("Invalid URL") }
|
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}")
|
if (!response.isSuccessful) throw IOException("HTTP ${response.code}")
|
||||||
val body = response.body ?: throw IOException("Empty response")
|
val body = response.body ?: throw IOException("Empty response")
|
||||||
val parsed = LongList()
|
val parsed = LongList()
|
||||||
body.charStream().buffered().useLines { lines ->
|
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()
|
val result = parsed.toArray().sortUnique()
|
||||||
if (result.isEmpty()) throw IOException("No domains found")
|
if (result.isEmpty()) throw IOException("No domains found")
|
||||||
write(url, result)
|
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())
|
return RemoteList(url, result.size, System.currentTimeMillis())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -332,6 +389,12 @@ private class BlocklistStore(context: Context) {
|
|||||||
return result
|
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 binFile(url: String) = File(dir, "list_${hash(url)}.bin")
|
||||||
private fun textFile(url: String) = File(dir, "list_${hash(url)}.txt")
|
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) }
|
.take(8).joinToString("") { "%02x".format(it) }
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
|
const val MAX_LIST_DOMAINS = 4_000_000
|
||||||
|
|
||||||
val client: OkHttpClient by lazy {
|
val client: OkHttpClient by lazy {
|
||||||
OkHttpClient.Builder()
|
Http.client.newBuilder()
|
||||||
.connectTimeout(15, TimeUnit.SECONDS)
|
|
||||||
.readTimeout(60, TimeUnit.SECONDS)
|
.readTimeout(60, TimeUnit.SECONDS)
|
||||||
.build()
|
.build()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,15 @@
|
|||||||
package cc.skysparkle.sparkledns
|
package cc.skysparkle.sparkledns
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
|
import android.widget.Toast
|
||||||
import androidx.compose.animation.AnimatedVisibility
|
import androidx.compose.animation.AnimatedVisibility
|
||||||
import androidx.compose.animation.animateContentSize
|
import androidx.compose.animation.animateContentSize
|
||||||
|
import androidx.compose.foundation.background
|
||||||
import androidx.compose.foundation.horizontalScroll
|
import androidx.compose.foundation.horizontalScroll
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
import androidx.compose.foundation.layout.Column
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.PaddingValues
|
||||||
import androidx.compose.foundation.layout.Row
|
import androidx.compose.foundation.layout.Row
|
||||||
import androidx.compose.foundation.layout.Spacer
|
import androidx.compose.foundation.layout.Spacer
|
||||||
import androidx.compose.foundation.layout.fillMaxSize
|
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.padding
|
||||||
import androidx.compose.foundation.layout.size
|
import androidx.compose.foundation.layout.size
|
||||||
import androidx.compose.foundation.layout.width
|
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.rememberScrollState
|
||||||
|
import androidx.compose.foundation.shape.ZeroCornerSize
|
||||||
import androidx.compose.foundation.text.KeyboardActions
|
import androidx.compose.foundation.text.KeyboardActions
|
||||||
import androidx.compose.foundation.text.KeyboardOptions
|
import androidx.compose.foundation.text.KeyboardOptions
|
||||||
import androidx.compose.foundation.verticalScroll
|
|
||||||
import androidx.compose.material3.AssistChip
|
import androidx.compose.material3.AssistChip
|
||||||
import androidx.compose.material3.Card
|
import androidx.compose.material3.Card
|
||||||
|
import androidx.compose.material3.CardDefaults
|
||||||
import androidx.compose.material3.FilledTonalButton
|
import androidx.compose.material3.FilledTonalButton
|
||||||
import androidx.compose.material3.HorizontalDivider
|
import androidx.compose.material3.HorizontalDivider
|
||||||
import androidx.compose.material3.Icon
|
import androidx.compose.material3.Icon
|
||||||
@@ -30,7 +37,6 @@ import androidx.compose.material3.Switch
|
|||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
import androidx.compose.material3.TextButton
|
import androidx.compose.material3.TextButton
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.collectAsState
|
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
@@ -39,6 +45,7 @@ import androidx.compose.runtime.saveable.rememberSaveable
|
|||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.graphics.RectangleShape
|
||||||
import androidx.compose.ui.platform.LocalContext
|
import androidx.compose.ui.platform.LocalContext
|
||||||
import androidx.compose.ui.res.painterResource
|
import androidx.compose.ui.res.painterResource
|
||||||
import androidx.compose.ui.res.stringResource
|
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.input.KeyboardType
|
||||||
import androidx.compose.ui.text.style.TextOverflow
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
|
import java.io.IOException
|
||||||
import java.text.DateFormat
|
import java.text.DateFormat
|
||||||
import java.util.Date
|
import java.util.Date
|
||||||
|
|
||||||
@@ -65,17 +75,17 @@ fun BlocklistScreen(modifier: Modifier = Modifier) {
|
|||||||
val prefs = remember { Prefs(context) }
|
val prefs = remember { Prefs(context) }
|
||||||
var showNote by remember { mutableStateOf(!prefs.isHintDismissed(HINT_BLOCKLIST)) }
|
var showNote by remember { mutableStateOf(!prefs.isHintDismissed(HINT_BLOCKLIST)) }
|
||||||
|
|
||||||
val enabled by Blocklist.enabled.collectAsState()
|
val enabled by Blocklist.enabled.collectAsStateWithLifecycle()
|
||||||
val total by Blocklist.total.collectAsState()
|
val total by Blocklist.total.collectAsStateWithLifecycle()
|
||||||
val custom by Blocklist.custom.collectAsState()
|
val custom by Blocklist.custom.collectAsStateWithLifecycle()
|
||||||
val lists by Blocklist.lists.collectAsState()
|
val lists by Blocklist.lists.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
var domainInput by rememberSaveable { mutableStateOf("") }
|
var domainInput by rememberSaveable { mutableStateOf("") }
|
||||||
var domainError by remember { mutableStateOf(false) }
|
var domainError by remember { mutableStateOf(false) }
|
||||||
var urlInput by rememberSaveable { mutableStateOf("") }
|
var urlInput by rememberSaveable { mutableStateOf("") }
|
||||||
// Downloads live in Blocklist, so they keep running and stay visible across tab switches
|
// Downloads live in Blocklist, so they keep running and stay visible across tab switches
|
||||||
val busy by Blocklist.busy.collectAsState()
|
val busy by Blocklist.busy.collectAsStateWithLifecycle()
|
||||||
val error by Blocklist.error.collectAsState()
|
val error by Blocklist.error.collectAsStateWithLifecycle()
|
||||||
val lastError = remember { arrayOf("") } // kept while the card animates out
|
val lastError = remember { arrayOf("") } // kept while the card animates out
|
||||||
error?.let { lastError[0] = it }
|
error?.let { lastError[0] = it }
|
||||||
|
|
||||||
@@ -83,9 +93,11 @@ fun BlocklistScreen(modifier: Modifier = Modifier) {
|
|||||||
val input = domainInput
|
val input = domainInput
|
||||||
if (input.isBlank()) return
|
if (input.isBlank()) return
|
||||||
scope.launch {
|
scope.launch {
|
||||||
val ok = withContext(Dispatchers.IO) { Blocklist.addCustom(context, input) }
|
val result = withContext(Dispatchers.IO) { tryEdit { Blocklist.addCustom(context, input) } }
|
||||||
domainError = !ok
|
result.onSuccess { ok ->
|
||||||
if (ok) domainInput = ""
|
domainError = !ok
|
||||||
|
if (ok) domainInput = ""
|
||||||
|
}.onFailure { showEditError(context, it) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -94,56 +106,66 @@ fun BlocklistScreen(modifier: Modifier = Modifier) {
|
|||||||
if (url.isNotEmpty() && Blocklist.download(context, url)) urlInput = ""
|
if (url.isNotEmpty() && Blocklist.download(context, url)) urlInput = ""
|
||||||
}
|
}
|
||||||
|
|
||||||
Column(
|
// Own domains are lazy rows, so hundreds of them are not all composed when the tab opens.
|
||||||
modifier = modifier
|
// Together they look like the card they used to be in: same color and shape, split per row.
|
||||||
.fillMaxSize()
|
val cardColor = CardDefaults.cardColors().containerColor
|
||||||
.verticalScroll(rememberScrollState())
|
val cardShape = MaterialTheme.shapes.medium
|
||||||
.padding(16.dp),
|
val cardTop = cardShape.copy(bottomStart = ZeroCornerSize, bottomEnd = ZeroCornerSize)
|
||||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
val cardBottom = cardShape.copy(topStart = ZeroCornerSize, topEnd = ZeroCornerSize)
|
||||||
|
|
||||||
|
LazyColumn(
|
||||||
|
modifier = modifier.fillMaxSize(),
|
||||||
|
contentPadding = PaddingValues(16.dp),
|
||||||
) {
|
) {
|
||||||
Card(Modifier.fillMaxWidth()) {
|
item(key = "summary") {
|
||||||
Row(Modifier.padding(16.dp), verticalAlignment = Alignment.CenterVertically) {
|
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||||
IconBadge(
|
Card(Modifier.fillMaxWidth()) {
|
||||||
R.drawable.ic_tab_block,
|
Row(Modifier.padding(16.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||||
tint = if (enabled) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.outline,
|
IconBadge(
|
||||||
size = 52.dp,
|
R.drawable.ic_tab_block,
|
||||||
)
|
tint = if (enabled) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.outline,
|
||||||
Spacer(Modifier.width(16.dp))
|
size = 52.dp,
|
||||||
Column(Modifier.weight(1f)) {
|
)
|
||||||
Text(stringResource(R.string.bl_title), style = MaterialTheme.typography.titleMedium)
|
Spacer(Modifier.width(16.dp))
|
||||||
Text(
|
Column(Modifier.weight(1f)) {
|
||||||
formatCount(total.toLong()),
|
Text(stringResource(R.string.bl_title), style = MaterialTheme.typography.titleMedium)
|
||||||
style = MaterialTheme.typography.headlineSmall,
|
Text(
|
||||||
fontWeight = FontWeight.SemiBold,
|
formatCount(total.toLong()),
|
||||||
)
|
style = MaterialTheme.typography.headlineSmall,
|
||||||
Text(
|
fontWeight = FontWeight.SemiBold,
|
||||||
stringResource(R.string.bl_total_label),
|
)
|
||||||
style = MaterialTheme.typography.bodySmall,
|
Text(
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
stringResource(R.string.bl_total_label),
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Switch(checked = enabled, onCheckedChange = { Blocklist.setEnabled(context, it) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
AnimatedVisibility(visible = showNote, enter = Motion.expandIn, exit = Motion.collapseOut) {
|
||||||
|
HintCard(
|
||||||
|
stringResource(R.string.bl_note),
|
||||||
|
icon = R.drawable.ic_tab_info,
|
||||||
|
onDismiss = {
|
||||||
|
showNote = false
|
||||||
|
prefs.dismissHint(HINT_BLOCKLIST)
|
||||||
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
Switch(checked = enabled, onCheckedChange = { Blocklist.setEnabled(context, it) })
|
|
||||||
|
SectionHeader(stringResource(R.string.bl_my), icon = R.drawable.ic_tab_block)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
AnimatedVisibility(visible = showNote, enter = Motion.expandIn, exit = Motion.collapseOut) {
|
item(key = "custom") {
|
||||||
HintCard(
|
|
||||||
stringResource(R.string.bl_note),
|
|
||||||
icon = R.drawable.ic_tab_info,
|
|
||||||
onDismiss = {
|
|
||||||
showNote = false
|
|
||||||
prefs.dismissHint(HINT_BLOCKLIST)
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
SectionHeader(stringResource(R.string.bl_my), icon = R.drawable.ic_tab_block)
|
|
||||||
|
|
||||||
Card(Modifier.fillMaxWidth()) {
|
|
||||||
Column(
|
Column(
|
||||||
Modifier
|
Modifier
|
||||||
.animateContentSize(Motion.size)
|
.padding(top = 12.dp)
|
||||||
.padding(vertical = 8.dp)
|
.fillMaxWidth()
|
||||||
|
.background(cardColor, if (custom.isEmpty()) cardShape else cardTop)
|
||||||
|
.padding(top = 8.dp, bottom = if (custom.isEmpty()) 8.dp else 0.dp)
|
||||||
) {
|
) {
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),
|
modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),
|
||||||
@@ -182,117 +204,131 @@ fun BlocklistScreen(modifier: Modifier = Modifier) {
|
|||||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
|
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
custom.forEach { domain ->
|
}
|
||||||
InsetDivider(16)
|
}
|
||||||
Row(
|
|
||||||
modifier = Modifier.padding(start = 16.dp, end = 4.dp),
|
itemsIndexed(custom, key = { _, domain -> "domain:$domain" }, contentType = { _, _ -> "domain" }) { index, domain ->
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
val last = index == custom.lastIndex
|
||||||
|
Column(
|
||||||
|
Modifier
|
||||||
|
.animateItem()
|
||||||
|
.fillMaxWidth()
|
||||||
|
.background(cardColor, if (last) cardBottom else RectangleShape)
|
||||||
|
.padding(bottom = if (last) 8.dp else 0.dp)
|
||||||
|
) {
|
||||||
|
InsetDivider(16)
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.padding(start = 16.dp, end = 4.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
Text(domain, modifier = Modifier.weight(1f), maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||||
|
IconButton(onClick = { scope.editBlocklist(context) { Blocklist.removeCustom(context, domain) } }) {
|
||||||
|
Icon(painterResource(R.drawable.ic_delete), stringResource(R.string.delete), Modifier.size(20.dp))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
item(key = "lists") {
|
||||||
|
Column(Modifier.padding(top = 12.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||||
|
SectionHeader(
|
||||||
|
stringResource(R.string.bl_lists),
|
||||||
|
icon = R.drawable.ic_list,
|
||||||
|
action = {
|
||||||
|
TextButton(
|
||||||
|
onClick = { Blocklist.updateAll(context) },
|
||||||
|
enabled = lists.isNotEmpty() && busy == null,
|
||||||
|
) {
|
||||||
|
Icon(painterResource(R.drawable.ic_refresh), contentDescription = null, modifier = Modifier.size(18.dp))
|
||||||
|
Spacer(Modifier.width(6.dp))
|
||||||
|
Text(stringResource(if (busy == Blocklist.ALL_LISTS) R.string.bl_updating else R.string.bl_update_all))
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
Card(Modifier.fillMaxWidth()) {
|
||||||
|
Column(
|
||||||
|
Modifier
|
||||||
|
.animateContentSize(Motion.size)
|
||||||
|
.padding(vertical = 8.dp)
|
||||||
) {
|
) {
|
||||||
Text(domain, modifier = Modifier.weight(1f), maxLines = 1, overflow = TextOverflow.Ellipsis)
|
lists.forEachIndexed { index, list ->
|
||||||
IconButton(onClick = { scope.launch(Dispatchers.IO) { Blocklist.removeCustom(context, domain) } }) {
|
if (index > 0) InsetDivider(68)
|
||||||
Icon(painterResource(R.drawable.ic_delete), stringResource(R.string.delete), Modifier.size(20.dp))
|
ListRow(
|
||||||
|
list = list,
|
||||||
|
updating = busy == list.url || busy == Blocklist.ALL_LISTS,
|
||||||
|
actionsEnabled = busy == null,
|
||||||
|
onRefresh = { Blocklist.download(context, list.url) },
|
||||||
|
onDelete = { scope.editBlocklist(context) { Blocklist.removeList(context, list.url) } },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (lists.isNotEmpty()) InsetDivider(16)
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
OutlinedTextField(
|
||||||
|
value = urlInput,
|
||||||
|
onValueChange = { urlInput = it },
|
||||||
|
placeholder = { Text(stringResource(R.string.bl_list_url), maxLines = 1) },
|
||||||
|
singleLine = true,
|
||||||
|
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri, imeAction = ImeAction.Done),
|
||||||
|
keyboardActions = KeyboardActions(onDone = { if (busy == null) addList() }),
|
||||||
|
modifier = Modifier.weight(1f),
|
||||||
|
)
|
||||||
|
Spacer(Modifier.width(8.dp))
|
||||||
|
FilledTonalButton(
|
||||||
|
onClick = ::addList,
|
||||||
|
enabled = urlInput.isNotBlank() && busy == null,
|
||||||
|
) {
|
||||||
|
Icon(painterResource(R.drawable.ic_add), contentDescription = null, modifier = Modifier.size(18.dp))
|
||||||
|
Spacer(Modifier.width(6.dp))
|
||||||
|
Text(stringResource(R.string.add))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// A new list being added has no row yet, so its progress shows under the input
|
||||||
|
val addingNew = busy != null && busy != Blocklist.ALL_LISTS && lists.none { it.url == busy }
|
||||||
|
AnimatedVisibility(visible = addingNew, enter = Motion.expandIn, exit = Motion.collapseOut) {
|
||||||
|
LinearProgressIndicator(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(horizontal = 16.dp, vertical = 4.dp),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
SectionHeader(
|
val missingPresets = Presets.filter { (_, url) -> lists.none { it.url == url } }
|
||||||
stringResource(R.string.bl_lists),
|
AnimatedVisibility(visible = missingPresets.isNotEmpty(), enter = Motion.expandIn, exit = Motion.collapseOut) {
|
||||||
icon = R.drawable.ic_list,
|
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||||
action = {
|
SectionHeader(stringResource(R.string.bl_presets))
|
||||||
TextButton(
|
Row(
|
||||||
onClick = { Blocklist.updateAll(context) },
|
modifier = Modifier.horizontalScroll(rememberScrollState()),
|
||||||
enabled = lists.isNotEmpty() && busy == null,
|
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||||
) {
|
) {
|
||||||
Icon(painterResource(R.drawable.ic_refresh), contentDescription = null, modifier = Modifier.size(18.dp))
|
missingPresets.forEach { (name, url) ->
|
||||||
Spacer(Modifier.width(6.dp))
|
AssistChip(
|
||||||
Text(stringResource(if (busy == Blocklist.ALL_LISTS) R.string.bl_updating else R.string.bl_update_all))
|
onClick = { Blocklist.download(context, url) },
|
||||||
}
|
enabled = busy == null,
|
||||||
},
|
leadingIcon = {
|
||||||
)
|
Icon(painterResource(R.drawable.ic_add), contentDescription = null, modifier = Modifier.size(18.dp))
|
||||||
|
},
|
||||||
Card(Modifier.fillMaxWidth()) {
|
label = { Text(if (busy == url) stringResource(R.string.bl_updating) else name) },
|
||||||
Column(
|
)
|
||||||
Modifier
|
}
|
||||||
.animateContentSize(Motion.size)
|
}
|
||||||
.padding(vertical = 8.dp)
|
|
||||||
) {
|
|
||||||
lists.forEachIndexed { index, list ->
|
|
||||||
if (index > 0) InsetDivider(68)
|
|
||||||
ListRow(
|
|
||||||
list = list,
|
|
||||||
updating = busy == list.url || busy == Blocklist.ALL_LISTS,
|
|
||||||
actionsEnabled = busy == null,
|
|
||||||
onRefresh = { Blocklist.download(context, list.url) },
|
|
||||||
onDelete = { scope.launch(Dispatchers.IO) { Blocklist.removeList(context, list.url) } },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
if (lists.isNotEmpty()) InsetDivider(16)
|
|
||||||
Row(
|
|
||||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp),
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
) {
|
|
||||||
OutlinedTextField(
|
|
||||||
value = urlInput,
|
|
||||||
onValueChange = { urlInput = it },
|
|
||||||
placeholder = { Text(stringResource(R.string.bl_list_url), maxLines = 1) },
|
|
||||||
singleLine = true,
|
|
||||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri, imeAction = ImeAction.Done),
|
|
||||||
keyboardActions = KeyboardActions(onDone = { if (busy == null) addList() }),
|
|
||||||
modifier = Modifier.weight(1f),
|
|
||||||
)
|
|
||||||
Spacer(Modifier.width(8.dp))
|
|
||||||
FilledTonalButton(
|
|
||||||
onClick = ::addList,
|
|
||||||
enabled = urlInput.isNotBlank() && busy == null,
|
|
||||||
) {
|
|
||||||
Icon(painterResource(R.drawable.ic_add), contentDescription = null, modifier = Modifier.size(18.dp))
|
|
||||||
Spacer(Modifier.width(6.dp))
|
|
||||||
Text(stringResource(R.string.add))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// A new list being added has no row yet, so its progress shows under the input
|
|
||||||
val addingNew = busy != null && busy != Blocklist.ALL_LISTS && lists.none { it.url == busy }
|
AnimatedVisibility(visible = error != null, enter = Motion.expandIn, exit = Motion.collapseOut) {
|
||||||
AnimatedVisibility(visible = addingNew, enter = Motion.expandIn, exit = Motion.collapseOut) {
|
HintCard(
|
||||||
LinearProgressIndicator(
|
stringResource(R.string.bl_download_failed, lastError[0]),
|
||||||
modifier = Modifier
|
icon = R.drawable.ic_alert,
|
||||||
.fillMaxWidth()
|
tint = MaterialTheme.colorScheme.error,
|
||||||
.padding(horizontal = 16.dp, vertical = 4.dp),
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
val missingPresets = Presets.filter { (_, url) -> lists.none { it.url == url } }
|
|
||||||
AnimatedVisibility(visible = missingPresets.isNotEmpty(), enter = Motion.expandIn, exit = Motion.collapseOut) {
|
|
||||||
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
|
||||||
SectionHeader(stringResource(R.string.bl_presets))
|
|
||||||
Row(
|
|
||||||
modifier = Modifier.horizontalScroll(rememberScrollState()),
|
|
||||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
|
||||||
) {
|
|
||||||
missingPresets.forEach { (name, url) ->
|
|
||||||
AssistChip(
|
|
||||||
onClick = { Blocklist.download(context, url) },
|
|
||||||
enabled = busy == null,
|
|
||||||
leadingIcon = {
|
|
||||||
Icon(painterResource(R.drawable.ic_add), contentDescription = null, modifier = Modifier.size(18.dp))
|
|
||||||
},
|
|
||||||
label = { Text(if (busy == url) stringResource(R.string.bl_updating) else name) },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
AnimatedVisibility(visible = error != null, enter = Motion.expandIn, exit = Motion.collapseOut) {
|
|
||||||
HintCard(
|
|
||||||
stringResource(R.string.bl_download_failed, lastError[0]),
|
|
||||||
icon = R.drawable.ic_alert,
|
|
||||||
tint = MaterialTheme.colorScheme.error,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -358,4 +394,21 @@ private fun ListRow(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Blocklist edits write to storage, which can fail (a full disk, for one)
|
||||||
|
internal inline fun <T> tryEdit(action: () -> T): Result<T> =
|
||||||
|
try {
|
||||||
|
Result.success(action())
|
||||||
|
} catch (e: IOException) {
|
||||||
|
Result.failure(e)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun CoroutineScope.editBlocklist(context: Context, action: () -> Unit) = launch {
|
||||||
|
withContext(Dispatchers.IO) { tryEdit(action) }.onFailure { showEditError(context, it) }
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun showEditError(context: Context, error: Throwable) {
|
||||||
|
val reason = error.message ?: error.javaClass.simpleName
|
||||||
|
Toast.makeText(context, context.getString(R.string.test_fail, reason), Toast.LENGTH_LONG).show()
|
||||||
|
}
|
||||||
|
|
||||||
private const val HINT_BLOCKLIST = "blocklist"
|
private const val HINT_BLOCKLIST = "blocklist"
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ package cc.skysparkle.sparkledns
|
|||||||
import android.app.Application
|
import android.app.Application
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
|
import android.os.Process
|
||||||
|
import android.os.StrictMode
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.io.PrintWriter
|
import java.io.PrintWriter
|
||||||
import java.io.StringWriter
|
import java.io.StringWriter
|
||||||
@@ -10,8 +12,29 @@ import java.io.StringWriter
|
|||||||
class SparkleApp : Application() {
|
class SparkleApp : Application() {
|
||||||
override fun onCreate() {
|
override fun onCreate() {
|
||||||
super.onCreate()
|
super.onCreate()
|
||||||
|
if (BuildConfig.DEBUG) enableStrictMode()
|
||||||
CrashLog.install(this)
|
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? =
|
@Volatile
|
||||||
File(context.filesDir, FILE_NAME).takeIf { it.exists() }?.readText()
|
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) {
|
fun clear(context: Context) {
|
||||||
|
report = null
|
||||||
File(context.filesDir, FILE_NAME).delete()
|
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
|
import android.os.SystemClock
|
||||||
|
|
||||||
// TTL-aware LRU cache of DNS responses, keyed by the question section
|
// 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(
|
private class Entry(
|
||||||
val response: ByteArray,
|
val response: ByteArray,
|
||||||
@@ -19,7 +22,7 @@ class DnsCache(private val maxEntries: Int = 2000) {
|
|||||||
|
|
||||||
fun get(query: ByteArray): ByteArray? {
|
fun get(query: ByteArray): ByteArray? {
|
||||||
val key = keyOf(query) ?: return null
|
val key = keyOf(query) ?: return null
|
||||||
val now = SystemClock.elapsedRealtime()
|
val now = clock()
|
||||||
val entry = synchronized(map) {
|
val entry = synchronized(map) {
|
||||||
val e = map[key] ?: return null
|
val e = map[key] ?: return null
|
||||||
if (now >= e.expiresAt) {
|
if (now >= e.expiresAt) {
|
||||||
@@ -47,7 +50,7 @@ class DnsCache(private val maxEntries: Int = 2000) {
|
|||||||
val ttl = minOf(minTtl, MAX_TTL)
|
val ttl = minOf(minTtl, MAX_TTL)
|
||||||
if (ttl <= 0) return
|
if (ttl <= 0) return
|
||||||
|
|
||||||
val now = SystemClock.elapsedRealtime()
|
val now = clock()
|
||||||
val entry = Entry(response.copyOf(), records.first, records.second, now, now + ttl * 1000L)
|
val entry = Entry(response.copyOf(), records.first, records.second, now, now + ttl * 1000L)
|
||||||
synchronized(map) { map[key] = entry }
|
synchronized(map) { map[key] = entry }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,9 +11,11 @@ import android.service.quicksettings.Tile
|
|||||||
import android.service.quicksettings.TileService
|
import android.service.quicksettings.TileService
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.MainScope
|
import kotlinx.coroutines.MainScope
|
||||||
import kotlinx.coroutines.cancel
|
import kotlinx.coroutines.cancel
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
|
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
|
||||||
|
|
||||||
class DnsTileService : TileService() {
|
class DnsTileService : TileService() {
|
||||||
@@ -32,7 +34,12 @@ class DnsTileService : TileService() {
|
|||||||
override fun onStartListening() {
|
override fun onStartListening() {
|
||||||
listening?.cancel()
|
listening?.cancel()
|
||||||
listening = MainScope().also { scope ->
|
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 tile = qsTile ?: return
|
||||||
val active = DohVpnService.active.value
|
val active = DohVpnService.active.value
|
||||||
tile.state = if (active != null) Tile.STATE_ACTIVE else Tile.STATE_INACTIVE
|
tile.state = if (active != null) Tile.STATE_ACTIVE else Tile.STATE_INACTIVE
|
||||||
tile.label = getString(R.string.app_name)
|
tile.label = getString(R.string.app_name)
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
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()
|
tile.updateTile()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
package cc.skysparkle.sparkledns
|
package cc.skysparkle.sparkledns
|
||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
|
import android.net.ConnectivityManager
|
||||||
|
import android.net.Network
|
||||||
import android.net.http.HttpEngine
|
import android.net.http.HttpEngine
|
||||||
import android.net.http.HttpException
|
import android.net.http.HttpException
|
||||||
import android.net.http.UploadDataProvider
|
import android.net.http.UploadDataProvider
|
||||||
@@ -10,10 +12,10 @@ import android.net.http.UrlResponseInfo
|
|||||||
import android.os.Build
|
import android.os.Build
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
import androidx.annotation.RequiresApi
|
import androidx.annotation.RequiresApi
|
||||||
|
import okhttp3.ConnectionPool
|
||||||
import okhttp3.Dns
|
import okhttp3.Dns
|
||||||
import okhttp3.HttpUrl.Companion.toHttpUrl
|
import okhttp3.HttpUrl.Companion.toHttpUrl
|
||||||
import okhttp3.MediaType.Companion.toMediaType
|
import okhttp3.MediaType.Companion.toMediaType
|
||||||
import okhttp3.OkHttpClient
|
|
||||||
import okhttp3.Request
|
import okhttp3.Request
|
||||||
import okhttp3.RequestBody.Companion.toRequestBody
|
import okhttp3.RequestBody.Companion.toRequestBody
|
||||||
import java.io.ByteArrayOutputStream
|
import java.io.ByteArrayOutputStream
|
||||||
@@ -27,6 +29,7 @@ import java.util.concurrent.ExecutionException
|
|||||||
import java.util.concurrent.Executors
|
import java.util.concurrent.Executors
|
||||||
import java.util.concurrent.TimeUnit
|
import java.util.concurrent.TimeUnit
|
||||||
import java.util.concurrent.TimeoutException
|
import java.util.concurrent.TimeoutException
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean
|
||||||
|
|
||||||
private const val DNS_MESSAGE = "application/dns-message"
|
private const val DNS_MESSAGE = "application/dns-message"
|
||||||
private const val MAX_DNS_SIZE = 65535
|
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.
|
// everything else and older devices use OkHttp with HTTP/2.
|
||||||
class DohClient(context: Context, provider: DohProvider) {
|
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 {
|
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")
|
if (!DnsMessage.isResponse(body)) throw IOException("Invalid DNS response")
|
||||||
return body
|
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 {
|
private fun createTransport(context: Context, provider: DohProvider): Transport {
|
||||||
if (provider.http3 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
|
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)
|
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()
|
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 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))
|
.dns(BootstrapDns(provider.bootstrap))
|
||||||
.connectTimeout(5, TimeUnit.SECONDS)
|
.connectTimeout(5, TimeUnit.SECONDS)
|
||||||
.readTimeout(5, TimeUnit.SECONDS)
|
.readTimeout(5, TimeUnit.SECONDS)
|
||||||
.callTimeout(8, TimeUnit.SECONDS)
|
.callTimeout(8, TimeUnit.SECONDS)
|
||||||
.build()
|
.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
|
@Volatile
|
||||||
override var lastProtocol: String? = null
|
override var lastProtocol: String? = null
|
||||||
|
|
||||||
@@ -97,8 +145,8 @@ private class OkHttpTransport(private val provider: DohProvider) : Transport {
|
|||||||
}
|
}
|
||||||
|
|
||||||
override fun shutdown() {
|
override fun shutdown() {
|
||||||
client.dispatcher.executorService.shutdown()
|
if (watchingNetwork) runCatching { connectivity?.unregisterNetworkCallback(networkCallback) }
|
||||||
client.connectionPool.evictAll()
|
pool.evictAll()
|
||||||
}
|
}
|
||||||
|
|
||||||
private companion object {
|
private companion object {
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ import android.content.pm.ServiceInfo
|
|||||||
import android.graphics.drawable.Icon
|
import android.graphics.drawable.Icon
|
||||||
import android.net.VpnService
|
import android.net.VpnService
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
|
import android.os.Handler
|
||||||
|
import android.os.Looper
|
||||||
import android.os.ParcelFileDescriptor
|
import android.os.ParcelFileDescriptor
|
||||||
import android.os.SystemClock
|
import android.os.SystemClock
|
||||||
import android.system.ErrnoException
|
import android.system.ErrnoException
|
||||||
@@ -32,6 +34,14 @@ private const val WORKERS = 16
|
|||||||
private const val TAG = "SparkleDNS"
|
private const val TAG = "SparkleDNS"
|
||||||
private const val CHANNEL_ID = "vpn_status"
|
private const val CHANNEL_ID = "vpn_status"
|
||||||
private const val NOTIFICATION_ID = 1
|
private const val NOTIFICATION_ID = 1
|
||||||
|
private const val MAX_BAD_PACKETS = 100
|
||||||
|
|
||||||
|
// 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
|
// Local VPN that routes only the fake DNS address into the tunnel; all other traffic is untouched
|
||||||
class DohVpnService : VpnService() {
|
class DohVpnService : VpnService() {
|
||||||
@@ -50,6 +60,7 @@ class DohVpnService : VpnService() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private var session: Session? = null
|
private var session: Session? = null
|
||||||
|
private val mainHandler = Handler(Looper.getMainLooper())
|
||||||
|
|
||||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||||
if (intent?.action == ACTION_STOP) {
|
if (intent?.action == ACTION_STOP) {
|
||||||
@@ -97,18 +108,22 @@ class DohVpnService : VpnService() {
|
|||||||
.allowFamily(OsConstants.AF_INET6)
|
.allowFamily(OsConstants.AF_INET6)
|
||||||
// The app itself bypasses the VPN so it can resolve and reach the DoH server
|
// The app itself bypasses the VPN so it can resolve and reach the DoH server
|
||||||
runCatching { builder.addDisallowedApplication(packageName) }
|
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)
|
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
|
// 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
|
val previous = session
|
||||||
if (tun == null) {
|
if (tun == null) {
|
||||||
stopSession()
|
stopSession()
|
||||||
stopSelf()
|
stopSelf()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
session = Session(tun, DohClient(this, provider)).also { it.start() }
|
session = Session(tun, DohClient(this, provider), ::onSessionFailed).also { it.start() }
|
||||||
runCatching { previous?.stop() }
|
runCatching { previous?.stop() }
|
||||||
|
|
||||||
_active.value = provider
|
_active.value = provider
|
||||||
@@ -127,6 +142,17 @@ class DohVpnService : VpnService() {
|
|||||||
DnsTileService.refresh(this)
|
DnsTileService.refresh(this)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The tunnel reader died while the session should be running. Dropping the VPN lets Android
|
||||||
|
// fall back to normal DNS instead of sending every lookup on the device into a dead tunnel.
|
||||||
|
private fun onSessionFailed(failed: Session) {
|
||||||
|
mainHandler.post {
|
||||||
|
if (session !== failed) return@post
|
||||||
|
Log.e(TAG, "Tunnel stopped working, disconnecting")
|
||||||
|
stopSession()
|
||||||
|
stopSelf()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun showNotification(provider: DohProvider) {
|
private fun showNotification(provider: DohProvider) {
|
||||||
val manager = getSystemService(NotificationManager::class.java) ?: return
|
val manager = getSystemService(NotificationManager::class.java) ?: return
|
||||||
manager.createNotificationChannel(
|
manager.createNotificationChannel(
|
||||||
@@ -177,6 +203,7 @@ class DohVpnService : VpnService() {
|
|||||||
private class Session(
|
private class Session(
|
||||||
private val tun: ParcelFileDescriptor,
|
private val tun: ParcelFileDescriptor,
|
||||||
private val doh: DohClient,
|
private val doh: DohClient,
|
||||||
|
private val onFailure: (Session) -> Unit,
|
||||||
) {
|
) {
|
||||||
private val alive = AtomicBoolean(true)
|
private val alive = AtomicBoolean(true)
|
||||||
private val pool = Executors.newFixedThreadPool(WORKERS)
|
private val pool = Executors.newFixedThreadPool(WORKERS)
|
||||||
@@ -189,8 +216,14 @@ private class Session(
|
|||||||
fun stop() {
|
fun stop() {
|
||||||
if (!alive.getAndSet(false)) return
|
if (!alive.getAndSet(false)) return
|
||||||
pool.shutdownNow()
|
pool.shutdownNow()
|
||||||
doh.shutdown()
|
|
||||||
runCatching { tun.close() }
|
runCatching { tun.close() }
|
||||||
|
closer.execute {
|
||||||
|
try {
|
||||||
|
doh.shutdown()
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "DoH client shutdown failed", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun readLoop() {
|
private fun readLoop() {
|
||||||
@@ -201,26 +234,48 @@ private class Session(
|
|||||||
events = OsConstants.POLLIN.toShort()
|
events = OsConstants.POLLIN.toShort()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var badPackets = 0
|
||||||
|
|
||||||
while (alive.get()) {
|
while (alive.get()) {
|
||||||
try {
|
val n = try {
|
||||||
if (Os.poll(arrayOf(pollFd), 500) <= 0) continue
|
if (Os.poll(arrayOf(pollFd), 500) <= 0) continue
|
||||||
val n = input.read(buf)
|
input.read(buf)
|
||||||
if (n < 0) break
|
|
||||||
val query = Packet.parseDnsQuery(buf, n) ?: continue
|
|
||||||
dispatch(query)
|
|
||||||
} catch (e: ErrnoException) {
|
} catch (e: ErrnoException) {
|
||||||
if (e.errno != OsConstants.EINTR) break
|
if (e.errno == OsConstants.EINTR) continue
|
||||||
} catch (_: IOException) {
|
readerFailed(e)
|
||||||
break
|
return
|
||||||
} catch (_: RejectedExecutionException) {
|
} catch (e: IOException) {
|
||||||
break
|
readerFailed(e)
|
||||||
} catch (e: Exception) {
|
return
|
||||||
Log.e(TAG, "Tunnel reader failed", e)
|
}
|
||||||
break
|
if (n < 0) {
|
||||||
|
readerFailed(null)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
Packet.parseDnsQuery(buf, n)?.let(::dispatch)
|
||||||
|
badPackets = 0
|
||||||
|
} catch (e: RejectedExecutionException) {
|
||||||
|
readerFailed(e)
|
||||||
|
return
|
||||||
|
} catch (e: RuntimeException) {
|
||||||
|
// One packet the code cannot handle must not stop DNS for the whole device
|
||||||
|
Log.w(TAG, "Dropped a packet", e)
|
||||||
|
if (++badPackets >= MAX_BAD_PACKETS) {
|
||||||
|
readerFailed(e)
|
||||||
|
return
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// stop() closes the tunnel, which also ends the loop; only an unexpected end is a failure
|
||||||
|
private fun readerFailed(cause: Throwable?) {
|
||||||
|
if (!alive.get()) return
|
||||||
|
Log.e(TAG, "Tunnel reader stopped", cause)
|
||||||
|
onFailure(this)
|
||||||
|
}
|
||||||
|
|
||||||
// Blocklist and cache are answered right here; only real lookups go to the worker pool
|
// Blocklist and cache are answered right here; only real lookups go to the worker pool
|
||||||
private fun dispatch(query: UdpPacket) {
|
private fun dispatch(query: UdpPacket) {
|
||||||
val question = DnsMessage.question(query.payload)
|
val question = DnsMessage.question(query.payload)
|
||||||
@@ -235,12 +290,21 @@ private class Session(
|
|||||||
QueryLog.add(question, QueryStatus.CACHED, 0)
|
QueryLog.add(question, QueryStatus.CACHED, 0)
|
||||||
return
|
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 {
|
try {
|
||||||
val start = SystemClock.elapsedRealtime()
|
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
|
var status = QueryStatus.OK
|
||||||
val answer = try {
|
val answer = try {
|
||||||
doh.query(query.payload).also { cache.put(query.payload, it) }
|
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))
|
val packet = Packet.buildReply(query, DnsMessage.withId(payload, query.payload))
|
||||||
try {
|
try {
|
||||||
synchronized(output) { output.write(packet) }
|
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.Intent
|
||||||
import android.content.pm.PackageManager
|
import android.content.pm.PackageManager
|
||||||
import android.net.ConnectivityManager
|
import android.net.ConnectivityManager
|
||||||
|
import android.net.LinkProperties
|
||||||
|
import android.net.Network
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
import android.net.VpnService
|
import android.net.VpnService
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
@@ -66,11 +68,11 @@ import androidx.compose.material3.TextButton
|
|||||||
import androidx.compose.material3.darkColorScheme
|
import androidx.compose.material3.darkColorScheme
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.LaunchedEffect
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
import androidx.compose.runtime.collectAsState
|
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.produceState
|
|
||||||
import androidx.compose.runtime.remember
|
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.rememberCoroutineScope
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.ui.Alignment
|
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.input.KeyboardType
|
||||||
import androidx.compose.ui.text.style.TextOverflow
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.channels.awaitClose
|
||||||
import kotlinx.coroutines.delay
|
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.launch
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
|
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
|
||||||
@@ -114,38 +122,42 @@ private val ProtectedContainer = Color(0xFF16233A)
|
|||||||
|
|
||||||
private class TestResult(val ok: Boolean, val text: String)
|
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
|
@Composable
|
||||||
fun HomeScreen(modifier: Modifier = Modifier) {
|
fun HomeScreen(modifier: Modifier = Modifier) {
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
val prefs = remember { Prefs(context) }
|
val prefs = remember { Prefs(context) }
|
||||||
val active by DohVpnService.active.collectAsState()
|
val active by DohVpnService.active.collectAsStateWithLifecycle()
|
||||||
val running = active != null
|
val running = active != null
|
||||||
val scope = rememberCoroutineScope()
|
val scope = rememberCoroutineScope()
|
||||||
val stats = rememberLiveStats()
|
val stats = rememberLiveStats()
|
||||||
|
|
||||||
var selected by remember { mutableStateOf(prefs.providerId) }
|
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 syncing by remember { mutableStateOf(false) }
|
||||||
var syncResult by remember { mutableStateOf<TestResult?>(null) }
|
var syncResult by rememberSaveable(stateSaver = TestResultSaver) { mutableStateOf<TestResult?>(null) }
|
||||||
var shownSync by remember { mutableStateOf<TestResult?>(null) }
|
var shownSync by rememberSaveable(stateSaver = TestResultSaver) { mutableStateOf<TestResult?>(null) }
|
||||||
var customUrl by remember { mutableStateOf(prefs.customUrl) }
|
var customUrl by remember { mutableStateOf(prefs.customUrl) }
|
||||||
var customBootstrap by remember { mutableStateOf(prefs.customBootstrap) }
|
var customBootstrap by remember { mutableStateOf(prefs.customBootstrap) }
|
||||||
var customHttp3 by remember { mutableStateOf(prefs.customHttp3) }
|
var customHttp3 by remember { mutableStateOf(prefs.customHttp3) }
|
||||||
var testResult by remember { mutableStateOf<TestResult?>(null) }
|
var testResult by rememberSaveable(stateSaver = TestResultSaver) { mutableStateOf<TestResult?>(null) }
|
||||||
var shownResult by remember { mutableStateOf<TestResult?>(null) } // kept while the card animates out
|
var shownResult by rememberSaveable(stateSaver = TestResultSaver) { mutableStateOf<TestResult?>(null) } // kept while the card animates out
|
||||||
var testing by remember { mutableStateOf(false) }
|
var testing by remember { mutableStateOf(false) }
|
||||||
val crashReport = remember { CrashLog.read(context) }
|
val crashReport = remember { CrashLog.read(context) }
|
||||||
// Strict Private DNS makes Android ignore the VPN's DNS server; re-checked while Home is open
|
// Strict Private DNS makes Android ignore the VPN's DNS server; followed while Home is visible
|
||||||
val privateDnsHost by produceState<String?>(null) {
|
val privateDnsHost by remember { privateDnsHosts(context) }.collectAsStateWithLifecycle(initialValue = null)
|
||||||
while (true) {
|
|
||||||
value = readPrivateDnsHost(context)
|
|
||||||
delay(3000)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
var crashVisible by remember { mutableStateOf(crashReport != null) }
|
var crashVisible by remember { mutableStateOf(crashReport != null) }
|
||||||
|
|
||||||
val isCustom = selected == Providers.CUSTOM_ID
|
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 canConnect = !isCustom || customValid
|
||||||
val selectedProvider = remember(selected, customUrl, customBootstrap, customHttp3, servers) { prefs.resolve() }
|
val selectedProvider = remember(selected, customUrl, customBootstrap, customHttp3, servers) { prefs.resolve() }
|
||||||
val customName = stringResource(R.string.custom)
|
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
|
// Picking a server never touches a live connection; switching is an explicit action
|
||||||
val pendingSwitch = active?.let { it != selectedProvider && canConnect } == true
|
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(
|
val vpnPermission = rememberLauncherForActivityResult(
|
||||||
ActivityResultContracts.StartActivityForResult()
|
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() {
|
fun connectVpn() {
|
||||||
val permission = VpnService.prepare(context)
|
val permission = VpnService.prepare(context)
|
||||||
@@ -172,6 +198,8 @@ fun HomeScreen(modifier: Modifier = Modifier) {
|
|||||||
) { connectVpn() }
|
) { connectVpn() }
|
||||||
|
|
||||||
fun toggle() {
|
fun toggle() {
|
||||||
|
if (busy) return
|
||||||
|
busy = true
|
||||||
if (running) {
|
if (running) {
|
||||||
sendAction(context, DohVpnService.ACTION_STOP)
|
sendAction(context, DohVpnService.ACTION_STOP)
|
||||||
return
|
return
|
||||||
@@ -249,9 +277,15 @@ fun HomeScreen(modifier: Modifier = Modifier) {
|
|||||||
http3 = usesHttp3,
|
http3 = usesHttp3,
|
||||||
stats = stats,
|
stats = stats,
|
||||||
canConnect = canConnect,
|
canConnect = canConnect,
|
||||||
|
busy = busy,
|
||||||
switchTo = if (pendingSwitch) nameOf(selectedProvider) else null,
|
switchTo = if (pendingSwitch) nameOf(selectedProvider) else null,
|
||||||
onToggle = ::toggle,
|
onToggle = ::toggle,
|
||||||
onSwitch = { sendAction(context, DohVpnService.ACTION_START) },
|
onSwitch = {
|
||||||
|
if (!busy) {
|
||||||
|
busy = true
|
||||||
|
sendAction(context, DohVpnService.ACTION_START)
|
||||||
|
}
|
||||||
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
SectionHeader(stringResource(R.string.servers)) {
|
SectionHeader(stringResource(R.string.servers)) {
|
||||||
@@ -290,6 +324,7 @@ fun HomeScreen(modifier: Modifier = Modifier) {
|
|||||||
subtitle = hostOf(p.url),
|
subtitle = hostOf(p.url),
|
||||||
selected = selected == p.id,
|
selected = selected == p.id,
|
||||||
onPolicy = p.policy?.let { url -> { openUrl(context, url) } },
|
onPolicy = p.policy?.let { url -> { openUrl(context, url) } },
|
||||||
|
onDonate = p.donate?.let { url -> { openUrl(context, url) } },
|
||||||
) { select(p.id) }
|
) { select(p.id) }
|
||||||
}
|
}
|
||||||
RowDivider()
|
RowDivider()
|
||||||
@@ -404,6 +439,7 @@ private fun StatusHero(
|
|||||||
http3: Boolean,
|
http3: Boolean,
|
||||||
stats: QueryStats,
|
stats: QueryStats,
|
||||||
canConnect: Boolean,
|
canConnect: Boolean,
|
||||||
|
busy: Boolean,
|
||||||
switchTo: String?,
|
switchTo: String?,
|
||||||
onToggle: () -> Unit,
|
onToggle: () -> Unit,
|
||||||
onSwitch: () -> Unit,
|
onSwitch: () -> Unit,
|
||||||
@@ -489,7 +525,7 @@ private fun StatusHero(
|
|||||||
|
|
||||||
Button(
|
Button(
|
||||||
onClick = onToggle,
|
onClick = onToggle,
|
||||||
enabled = running || canConnect,
|
enabled = (running || canConnect) && !busy,
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.height(52.dp),
|
.height(52.dp),
|
||||||
@@ -505,7 +541,7 @@ private fun StatusHero(
|
|||||||
val lastSwitch = remember { arrayOf("") }
|
val lastSwitch = remember { arrayOf("") }
|
||||||
if (switchTo != null) lastSwitch[0] = switchTo
|
if (switchTo != null) lastSwitch[0] = switchTo
|
||||||
AnimatedVisibility(visible = switchTo != null, enter = Motion.expandIn, exit = Motion.collapseOut) {
|
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))
|
Icon(painterResource(R.drawable.ic_switch), contentDescription = null, modifier = Modifier.size(18.dp))
|
||||||
Spacer(Modifier.width(8.dp))
|
Spacer(Modifier.width(8.dp))
|
||||||
Text(stringResource(R.string.switch_to, lastSwitch[0]))
|
Text(stringResource(R.string.switch_to, lastSwitch[0]))
|
||||||
@@ -571,6 +607,7 @@ private fun ProviderRow(
|
|||||||
subtitle: String,
|
subtitle: String,
|
||||||
selected: Boolean,
|
selected: Boolean,
|
||||||
onPolicy: (() -> Unit)? = null,
|
onPolicy: (() -> Unit)? = null,
|
||||||
|
onDonate: (() -> Unit)? = null,
|
||||||
onClick: () -> Unit,
|
onClick: () -> Unit,
|
||||||
) {
|
) {
|
||||||
val highlight by animateColorAsState(
|
val highlight by animateColorAsState(
|
||||||
@@ -598,6 +635,16 @@ private fun ProviderRow(
|
|||||||
overflow = TextOverflow.Ellipsis,
|
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) {
|
if (onPolicy != null) {
|
||||||
IconButton(onClick = onPolicy, modifier = Modifier.size(40.dp)) {
|
IconButton(onClick = onPolicy, modifier = Modifier.size(40.dp)) {
|
||||||
Icon(
|
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
|
// 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? {
|
// Android reports the current state on registration and every change after it.
|
||||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) return null
|
private fun privateDnsHosts(context: Context): Flow<String?> {
|
||||||
val cm = context.getSystemService(ConnectivityManager::class.java) ?: return null
|
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) return flowOf(null)
|
||||||
return runCatching { cm.getLinkProperties(cm.activeNetwork)?.privateDnsServerName }.getOrNull()
|
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) {
|
private fun openNetworkSettings(context: Context) {
|
||||||
|
|||||||
@@ -28,8 +28,6 @@ import androidx.compose.material3.MaterialTheme
|
|||||||
import androidx.compose.material3.OutlinedTextField
|
import androidx.compose.material3.OutlinedTextField
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.LaunchedEffect
|
|
||||||
import androidx.compose.runtime.collectAsState
|
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.remember
|
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.TextAlign
|
||||||
import androidx.compose.ui.text.style.TextOverflow
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.delay
|
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
import java.text.SimpleDateFormat
|
import java.text.SimpleDateFormat
|
||||||
@@ -61,19 +59,17 @@ private val TimeFormat = SimpleDateFormat("HH:mm:ss", Locale.ROOT)
|
|||||||
fun MonitorScreen(modifier: Modifier = Modifier) {
|
fun MonitorScreen(modifier: Modifier = Modifier) {
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
val scope = rememberCoroutineScope()
|
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 entries by remember { mutableStateOf(QueryLog.snapshot()) }
|
||||||
var stats by remember { mutableStateOf(QueryLog.stats()) }
|
var stats by remember { mutableStateOf(QueryLog.stats()) }
|
||||||
var filter by rememberSaveable { mutableStateOf(MonitorFilter.ALL) }
|
var filter by rememberSaveable { mutableStateOf(MonitorFilter.ALL) }
|
||||||
var search by rememberSaveable { mutableStateOf("") }
|
var search by rememberSaveable { mutableStateOf("") }
|
||||||
|
|
||||||
LaunchedEffect(Unit) {
|
OnQueryLogChange {
|
||||||
while (true) {
|
entries = QueryLog.snapshot()
|
||||||
entries = QueryLog.snapshot()
|
stats = QueryLog.stats()
|
||||||
stats = QueryLog.stats()
|
|
||||||
delay(1000)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
val visible = remember(entries, filter, search) {
|
val visible = remember(entries, filter, search) {
|
||||||
@@ -90,14 +86,20 @@ fun MonitorScreen(modifier: Modifier = Modifier) {
|
|||||||
|
|
||||||
fun toggleBlock(domain: String, unblock: Boolean) {
|
fun toggleBlock(domain: String, unblock: Boolean) {
|
||||||
scope.launch {
|
scope.launch {
|
||||||
val ok = withContext(Dispatchers.IO) {
|
val result = withContext(Dispatchers.IO) {
|
||||||
if (unblock) {
|
tryEdit {
|
||||||
Blocklist.removeCustom(context, domain)
|
if (unblock) {
|
||||||
true
|
Blocklist.removeCustom(context, domain)
|
||||||
} else {
|
true
|
||||||
Blocklist.addCustom(context, domain)
|
} else {
|
||||||
|
Blocklist.addCustom(context, domain)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
val ok = result.getOrElse {
|
||||||
|
showEditError(context, it)
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
val message = when {
|
val message = when {
|
||||||
!ok -> context.getString(R.string.bl_invalid)
|
!ok -> context.getString(R.string.bl_invalid)
|
||||||
unblock -> context.getString(R.string.mon_unblocked, domain)
|
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 ->
|
itemsIndexed(visible, key = { _, e -> e.id }, contentType = { _, _ -> "query" }) { index, entry ->
|
||||||
val inCustom = entry.domain in custom
|
val inCustom = entry.domain in customSet
|
||||||
QueryRow(
|
QueryRow(
|
||||||
modifier = Modifier.animateItem(),
|
modifier = Modifier.animateItem(),
|
||||||
entry = entry,
|
entry = entry,
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import android.content.Context
|
|||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
|
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
|
||||||
import okhttp3.OkHttpClient
|
|
||||||
import okhttp3.Request
|
import okhttp3.Request
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.io.IOException
|
import java.io.IOException
|
||||||
@@ -17,6 +16,7 @@ data class DohProvider(
|
|||||||
val bootstrap: List<String> = emptyList(),
|
val bootstrap: List<String> = emptyList(),
|
||||||
val http3: Boolean = false,
|
val http3: Boolean = false,
|
||||||
val policy: String? = null,
|
val policy: String? = null,
|
||||||
|
val donate: String? = null,
|
||||||
)
|
)
|
||||||
|
|
||||||
object Providers {
|
object Providers {
|
||||||
@@ -32,11 +32,13 @@ object Providers {
|
|||||||
DohProvider(
|
DohProvider(
|
||||||
"quad9", "Quad9", "https://dns.quad9.net/dns-query", listOf("9.9.9.9", "149.112.112.112"),
|
"quad9", "Quad9", "https://dns.quad9.net/dns-query", listOf("9.9.9.9", "149.112.112.112"),
|
||||||
policy = "https://quad9.net/service/privacy/",
|
policy = "https://quad9.net/service/privacy/",
|
||||||
|
donate = "https://quad9.net/donate/",
|
||||||
),
|
),
|
||||||
DohProvider(
|
DohProvider(
|
||||||
"digitale-gesellschaft", "Digitale Gesellschaft", "https://dns.digitale-gesellschaft.ch/dns-query",
|
"digitale-gesellschaft", "Digitale Gesellschaft", "https://dns.digitale-gesellschaft.ch/dns-query",
|
||||||
listOf("185.95.218.42", "185.95.218.43"), http3 = true,
|
listOf("185.95.218.42", "185.95.218.43"), http3 = true,
|
||||||
policy = "https://www.digitale-gesellschaft.ch/dns/",
|
policy = "https://www.digitale-gesellschaft.ch/dns/",
|
||||||
|
donate = "https://www.digitale-gesellschaft.ch/uber-uns/unterstuetzer-werden/",
|
||||||
),
|
),
|
||||||
DohProvider(
|
DohProvider(
|
||||||
"uncensoreddns", "UncensoredDNS", "https://anycast.uncensoreddns.org/dns-query", listOf("91.239.100.100"),
|
"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",
|
"ffmuc", "Freifunk München", "https://doh.ffmuc.net/dns-query",
|
||||||
listOf("5.1.66.255", "185.150.99.255"), http3 = true,
|
listOf("5.1.66.255", "185.150.99.255"), http3 = true,
|
||||||
policy = "https://ffmuc.net/dns-privacy/",
|
policy = "https://ffmuc.net/dns-privacy/",
|
||||||
|
donate = "https://spende.ffmuc.net/",
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -70,8 +73,7 @@ object ServerList {
|
|||||||
@Volatile private var loaded = false
|
@Volatile private var loaded = false
|
||||||
|
|
||||||
private val client by lazy {
|
private val client by lazy {
|
||||||
OkHttpClient.Builder()
|
Http.client.newBuilder()
|
||||||
.connectTimeout(15, TimeUnit.SECONDS)
|
|
||||||
.readTimeout(30, TimeUnit.SECONDS)
|
.readTimeout(30, TimeUnit.SECONDS)
|
||||||
.build()
|
.build()
|
||||||
}
|
}
|
||||||
@@ -111,7 +113,8 @@ object ServerList {
|
|||||||
return parsed.size
|
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> {
|
fun parse(text: String): List<DohProvider> {
|
||||||
val builtInByHost = Providers.builtIn.associateBy { it.url.toHttpUrlOrNull()?.host }
|
val builtInByHost = Providers.builtIn.associateBy { it.url.toHttpUrlOrNull()?.host }
|
||||||
val seen = HashSet<String>()
|
val seen = HashSet<String>()
|
||||||
@@ -125,11 +128,14 @@ object ServerList {
|
|||||||
val url = cols[1].toHttpUrlOrNull()
|
val url = cols[1].toHttpUrlOrNull()
|
||||||
val policy = cols[2].takeIf { it.toHttpUrlOrNull()?.isHttps == true }
|
val policy = cols[2].takeIf { it.toHttpUrlOrNull()?.isHttps == true }
|
||||||
if (name.isEmpty() || url == null || !url.isHttps) continue
|
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 pinned = builtInByHost[url.host]
|
||||||
val server = pinned
|
val server = pinned
|
||||||
?: if (policy == null) continue
|
?: 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
|
if (!seen.add(server.id)) continue
|
||||||
result += server
|
result += server
|
||||||
if (result.size >= MAX_SERVERS) break
|
if (result.size >= MAX_SERVERS) break
|
||||||
|
|||||||
@@ -1,5 +1,10 @@
|
|||||||
package cc.skysparkle.sparkledns
|
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 }
|
enum class QueryStatus { OK, CACHED, BLOCKED, FAILED }
|
||||||
|
|
||||||
class QueryEntry(
|
class QueryEntry(
|
||||||
@@ -31,6 +36,14 @@ object QueryLog {
|
|||||||
private var failed = 0L
|
private var failed = 0L
|
||||||
private var latencySum = 0L
|
private var latencySum = 0L
|
||||||
private var latencyCount = 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) {
|
fun add(question: DnsMessage.Question?, status: QueryStatus, latencyMs: Int) {
|
||||||
if (question == null) return
|
if (question == null) return
|
||||||
@@ -46,6 +59,7 @@ object QueryLog {
|
|||||||
QueryStatus.BLOCKED -> blocked++
|
QueryStatus.BLOCKED -> blocked++
|
||||||
QueryStatus.FAILED -> failed++
|
QueryStatus.FAILED -> failed++
|
||||||
}
|
}
|
||||||
|
version.value++
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -67,5 +81,6 @@ object QueryLog {
|
|||||||
fun clear() {
|
fun clear() {
|
||||||
entries.clear()
|
entries.clear()
|
||||||
total = 0; cached = 0; blocked = 0; failed = 0; latencySum = 0; latencyCount = 0
|
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.getValue
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.rememberUpdatedState
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
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.text.style.TextOverflow
|
||||||
import androidx.compose.ui.unit.Dp
|
import androidx.compose.ui.unit.Dp
|
||||||
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.text.NumberFormat
|
||||||
|
import java.util.Locale
|
||||||
|
|
||||||
val CachedColor = Color(0xFF7FD1AE)
|
val CachedColor = Color(0xFF7FD1AE)
|
||||||
val WarningColor = Color(0xFFFFB86B)
|
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
|
@Composable
|
||||||
fun rememberLiveStats(): QueryStats {
|
fun rememberLiveStats(): QueryStats {
|
||||||
var stats by remember { mutableStateOf(QueryLog.stats()) }
|
var stats by remember { mutableStateOf(QueryLog.stats()) }
|
||||||
LaunchedEffect(Unit) {
|
OnQueryLogChange { stats = QueryLog.stats() }
|
||||||
while (true) {
|
|
||||||
stats = QueryLog.stats()
|
|
||||||
delay(1000)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return 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 =
|
fun cachePercent(stats: QueryStats): String =
|
||||||
"${if (stats.total == 0L) 0 else stats.cached * 100 / stats.total}%"
|
"${if (stats.total == 0L) 0 else stats.cached * 100 / stats.total}%"
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 184 KiB |
|
After Width: | Height: | Size: 124 KiB |
@@ -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>
|
||||||
|
Before Width: | Height: | Size: 19 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
Before Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 7.6 KiB |
|
Before Width: | Height: | Size: 29 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
Before Width: | Height: | Size: 54 KiB |
|
After Width: | Height: | Size: 40 KiB |
|
Before Width: | Height: | Size: 82 KiB |
|
After Width: | Height: | Size: 62 KiB |
@@ -84,6 +84,7 @@
|
|||||||
<string name="group_system">System</string>
|
<string name="group_system">System</string>
|
||||||
<string name="group_count">%1$d von %2$d über DNS</string>
|
<string name="group_count">%1$d von %2$d über DNS</string>
|
||||||
<string name="about_privacy_policy">Datenschutzerklärung</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_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_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>
|
<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_update">Serverliste aktualisieren</string>
|
||||||
<string name="servers_updated">Serverliste aktualisiert</string>
|
<string name="servers_updated">Serverliste aktualisiert</string>
|
||||||
<string name="servers_update_failed">Serverliste konnte nicht aktualisiert werden: %1$s</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>
|
</resources>
|
||||||
|
|||||||
@@ -84,6 +84,7 @@
|
|||||||
<string name="group_system">システム</string>
|
<string name="group_system">システム</string>
|
||||||
<string name="group_count">%2$d 件中 %1$d 件が DNS 経由</string>
|
<string name="group_count">%2$d 件中 %1$d 件が DNS 経由</string>
|
||||||
<string name="about_privacy_policy">プライバシーポリシー</string>
|
<string name="about_privacy_policy">プライバシーポリシー</string>
|
||||||
|
<string name="donate">寄付する</string>
|
||||||
<string name="licenses_title">オープンソースライセンス</string>
|
<string name="licenses_title">オープンソースライセンス</string>
|
||||||
<string name="licenses_hint">SparkleDNS は以下のオープンソースプロジェクトで作られています。タップするとプロジェクトのページを開きます。</string>
|
<string name="licenses_hint">SparkleDNS は以下のオープンソースプロジェクトで作られています。タップするとプロジェクトのページを開きます。</string>
|
||||||
<string name="licenses_data">ブロックリストのデータ(必要なときにダウンロード、同梱なし)</string>
|
<string name="licenses_data">ブロックリストのデータ(必要なときにダウンロード、同梱なし)</string>
|
||||||
@@ -97,4 +98,5 @@
|
|||||||
<string name="servers_update">サーバーリストを更新</string>
|
<string name="servers_update">サーバーリストを更新</string>
|
||||||
<string name="servers_updated">サーバーリストを更新しました</string>
|
<string name="servers_updated">サーバーリストを更新しました</string>
|
||||||
<string name="servers_update_failed">サーバーリストを更新できませんでした: %1$s</string>
|
<string name="servers_update_failed">サーバーリストを更新できませんでした: %1$s</string>
|
||||||
|
<string name="no_browser">このリンクを開けるアプリがありません</string>
|
||||||
</resources>
|
</resources>
|
||||||
|
|||||||
@@ -84,6 +84,7 @@
|
|||||||
<string name="group_system">Sistema</string>
|
<string name="group_system">Sistema</string>
|
||||||
<string name="group_count">%1$d iš %2$d per DNS</string>
|
<string name="group_count">%1$d iš %2$d per DNS</string>
|
||||||
<string name="about_privacy_policy">Privatumo politika</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_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_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>
|
<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_update">Atnaujinti serverių sąrašą</string>
|
||||||
<string name="servers_updated">Serverių sąrašas atnaujintas</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="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>
|
</resources>
|
||||||
|
|||||||
@@ -84,6 +84,7 @@
|
|||||||
<string name="group_system">Системные</string>
|
<string name="group_system">Системные</string>
|
||||||
<string name="group_count">%1$d из %2$d через DNS</string>
|
<string name="group_count">%1$d из %2$d через DNS</string>
|
||||||
<string name="about_privacy_policy">Политика конфиденциальности</string>
|
<string name="about_privacy_policy">Политика конфиденциальности</string>
|
||||||
|
<string name="donate">Пожертвовать</string>
|
||||||
<string name="licenses_title">Лицензии открытого ПО</string>
|
<string name="licenses_title">Лицензии открытого ПО</string>
|
||||||
<string name="licenses_hint">SparkleDNS построен на этих проектах с открытым кодом. Нажмите на проект, чтобы открыть его страницу.</string>
|
<string name="licenses_hint">SparkleDNS построен на этих проектах с открытым кодом. Нажмите на проект, чтобы открыть его страницу.</string>
|
||||||
<string name="licenses_data">Данные блоклистов (загружаются по запросу, не входят в приложение)</string>
|
<string name="licenses_data">Данные блоклистов (загружаются по запросу, не входят в приложение)</string>
|
||||||
@@ -97,4 +98,5 @@
|
|||||||
<string name="servers_update">Обновить список серверов</string>
|
<string name="servers_update">Обновить список серверов</string>
|
||||||
<string name="servers_updated">Список серверов обновлён</string>
|
<string name="servers_updated">Список серверов обновлён</string>
|
||||||
<string name="servers_update_failed">Не удалось обновить список серверов: %1$s</string>
|
<string name="servers_update_failed">Не удалось обновить список серверов: %1$s</string>
|
||||||
|
<string name="no_browser">Не найдено приложение, чтобы открыть ссылку</string>
|
||||||
</resources>
|
</resources>
|
||||||
|
|||||||
@@ -84,6 +84,7 @@
|
|||||||
<string name="group_system">系统</string>
|
<string name="group_system">系统</string>
|
||||||
<string name="group_count">%2$d 个中有 %1$d 个经过 DNS</string>
|
<string name="group_count">%2$d 个中有 %1$d 个经过 DNS</string>
|
||||||
<string name="about_privacy_policy">隐私政策</string>
|
<string name="about_privacy_policy">隐私政策</string>
|
||||||
|
<string name="donate">捐赠</string>
|
||||||
<string name="licenses_title">开源许可</string>
|
<string name="licenses_title">开源许可</string>
|
||||||
<string name="licenses_hint">SparkleDNS 使用了以下开源项目。点按项目可打开其页面。</string>
|
<string name="licenses_hint">SparkleDNS 使用了以下开源项目。点按项目可打开其页面。</string>
|
||||||
<string name="licenses_data">屏蔽列表数据(按需下载,未内置)</string>
|
<string name="licenses_data">屏蔽列表数据(按需下载,未内置)</string>
|
||||||
@@ -97,4 +98,5 @@
|
|||||||
<string name="servers_update">更新服务器列表</string>
|
<string name="servers_update">更新服务器列表</string>
|
||||||
<string name="servers_updated">服务器列表已更新</string>
|
<string name="servers_updated">服务器列表已更新</string>
|
||||||
<string name="servers_update_failed">无法更新服务器列表:%1$s</string>
|
<string name="servers_update_failed">无法更新服务器列表:%1$s</string>
|
||||||
|
<string name="no_browser">没有可以打开此链接的应用</string>
|
||||||
</resources>
|
</resources>
|
||||||
|
|||||||
@@ -85,6 +85,7 @@
|
|||||||
<string name="group_system">System</string>
|
<string name="group_system">System</string>
|
||||||
<string name="group_count">%1$d of %2$d via DNS</string>
|
<string name="group_count">%1$d of %2$d via DNS</string>
|
||||||
<string name="about_privacy_policy">Privacy policy</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_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_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>
|
<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_update">Update server list</string>
|
||||||
<string name="servers_updated">Server list updated</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="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>
|
</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)
|
||||||
|
}
|
||||||
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
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 与移动数据之间切换后以及网速较慢时,域名解析恢复更快
|
||||||
|
• 后台工作更少:不再刷新隐藏的界面
|
||||||
|
• 拦截列表仅在有变化时重新下载
|
||||||
|
• 应用图标更清晰,应用体积更小
|
||||||
|
• 连点“连接”不会再重复连接;存储空间已满时应用不再崩溃
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Records which classes and methods the app uses on startup and in each tab, in the text format
|
||||||
|
# of app/src/main/baseline-prof.txt. Needs a rooted Android 13+ device or emulator (no Play Store).
|
||||||
|
# Usage: scripts/baseline-profile.sh <non-minified release apk> <output file>
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
PKG=cc.skysparkle.sparkledns
|
||||||
|
ACT="$PKG/.MainActivity"
|
||||||
|
APK="$1"
|
||||||
|
OUT="$2"
|
||||||
|
|
||||||
|
adb root >/dev/null 2>&1 && sleep 3
|
||||||
|
adb wait-for-device
|
||||||
|
adb uninstall "$PKG" >/dev/null 2>&1 || true
|
||||||
|
adb install -g "$APK" >/dev/null
|
||||||
|
read -r W H < <(adb shell wm size | tr -d '\r' | awk -F'[ x]' '/Physical/ {print $3, $4}')
|
||||||
|
|
||||||
|
tap_text() {
|
||||||
|
local xy
|
||||||
|
for _ in 1 2 3 4 5; do
|
||||||
|
adb shell uiautomator dump /sdcard/ui.xml >/dev/null 2>&1 || true
|
||||||
|
xy="$(adb shell cat /sdcard/ui.xml | python3 -c '
|
||||||
|
import re, sys
|
||||||
|
xml, text = sys.stdin.read(), sys.argv[1]
|
||||||
|
for node in re.findall(r"<node [^>]*>", xml):
|
||||||
|
# Compose merges a clickable row into one node: "System, 3 of 5"
|
||||||
|
if re.search(r"(text|content-desc)=\"%s(\"|, )" % re.escape(text), node):
|
||||||
|
x1, y1, x2, y2 = map(int, re.search(r"bounds=\"\[(\d+),(\d+)\]\[(\d+),(\d+)\]\"", node).groups())
|
||||||
|
print((x1 + x2) // 2, (y1 + y2) // 2)
|
||||||
|
break
|
||||||
|
' "$1")"
|
||||||
|
if [[ -n "$xy" ]]; then
|
||||||
|
adb shell input tap $xy
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
# Lazy lists only show what is on screen; with "scroll", look further down
|
||||||
|
[[ "${2:-}" == scroll ]] && adb shell input swipe $((W / 2)) $((H * 2 / 3)) $((W / 2)) $((H / 3)) 300
|
||||||
|
sleep 1
|
||||||
|
done
|
||||||
|
echo "::warning::'$1' not found on screen"
|
||||||
|
}
|
||||||
|
|
||||||
|
swipe() {
|
||||||
|
adb shell input swipe $((W / 2)) $((H * 3 / 4)) $((W / 2)) $((H / 4)) 200
|
||||||
|
sleep 1
|
||||||
|
adb shell input swipe $((W / 2)) $((H / 4)) $((W / 2)) $((H * 3 / 4)) 200
|
||||||
|
sleep 1
|
||||||
|
}
|
||||||
|
|
||||||
|
for _ in 1 2 3; do
|
||||||
|
adb shell am force-stop "$PKG"
|
||||||
|
adb shell am start-activity -W -n "$ACT" >/dev/null
|
||||||
|
sleep 3
|
||||||
|
swipe
|
||||||
|
tap_text "Monitor"; sleep 2
|
||||||
|
tap_text "Apps"; sleep 3
|
||||||
|
tap_text "System" scroll; sleep 2
|
||||||
|
swipe
|
||||||
|
tap_text "Blocklist"; sleep 2
|
||||||
|
swipe
|
||||||
|
tap_text "About"; sleep 2
|
||||||
|
tap_text "Home"; sleep 2
|
||||||
|
# Makes ART write the profile now instead of on its own schedule
|
||||||
|
adb shell "kill -10 \$(pidof $PKG)"
|
||||||
|
sleep 5
|
||||||
|
done
|
||||||
|
|
||||||
|
adb shell pm dump-profiles --dump-classes-and-methods "$PKG"
|
||||||
|
sleep 2
|
||||||
|
adb pull "/data/misc/profman/$PKG-primary.prof.txt" "$OUT" >/dev/null
|
||||||
|
echo "Profile lines: $(wc -l < "$OUT")"
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Builds signed release APKs of two revisions for scripts/bench.sh.
|
||||||
|
# Usage: scripts/bench-build.sh <base-ref> <head-ref> <out-dir>
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
base="$(git rev-parse "$1")"
|
||||||
|
head="$(git rev-parse "$2")"
|
||||||
|
out="$(mkdir -p "$3" && cd "$3" && pwd)"
|
||||||
|
work="${RUNNER_TEMP:-/tmp}/bench-src"
|
||||||
|
|
||||||
|
keystore="$out/bench.jks"
|
||||||
|
[[ -f "$keystore" ]] || keytool -genkeypair -keystore "$keystore" -storepass benchpass -keypass benchpass \
|
||||||
|
-alias bench -keyalg RSA -keysize 2048 -validity 365 -dname "CN=bench" >/dev/null 2>&1
|
||||||
|
apksigner="$(ls -d "$ANDROID_HOME"/build-tools/*/ | sort -V | tail -n 1)apksigner"
|
||||||
|
|
||||||
|
build() {
|
||||||
|
local rev="$1" name="$2" dir="$work-$2" apk
|
||||||
|
rm -rf "$dir"
|
||||||
|
git worktree add -f --detach "$dir" "$rev" >/dev/null
|
||||||
|
(cd "$dir" && ./gradlew :app:assembleRelease -q)
|
||||||
|
apk="$(ls "$dir"/app/build/outputs/apk/release/*.apk | head -n 1)"
|
||||||
|
echo "$name,apk_bytes,$(stat -c %s "$apk")" >> "$out/sizes.csv"
|
||||||
|
echo "::notice title=APK size ($name ${rev:0:7})::$(stat -c %s "$apk") bytes"
|
||||||
|
"$apksigner" sign --ks "$keystore" --ks-pass pass:benchpass --out "$out/$name.apk" "$apk"
|
||||||
|
}
|
||||||
|
|
||||||
|
rm -f "$out/sizes.csv"
|
||||||
|
build "$base" base
|
||||||
|
build "$head" head
|
||||||
@@ -0,0 +1,222 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Benchmarks two APKs of SparkleDNS on one device or emulator and prints medians side by side:
|
||||||
|
# cold start, memory, CPU while in the background and scroll jank on the Apps tab.
|
||||||
|
# Rounds alternate the order of the APKs so device drift affects both alike.
|
||||||
|
# Needs a rooted device (an emulator image without Play Store) to drop the page cache.
|
||||||
|
# Usage: scripts/bench.sh <base.apk> <head.apk> [rounds]
|
||||||
|
set -uo pipefail
|
||||||
|
|
||||||
|
PKG=cc.skysparkle.sparkledns
|
||||||
|
ACT="$PKG/.MainActivity"
|
||||||
|
BASE_APK="$1"
|
||||||
|
HEAD_APK="$2"
|
||||||
|
ROUNDS="${3:-2}"
|
||||||
|
STARTS="${STARTS:-10}"
|
||||||
|
OUT="${OUT:-$(dirname "$BASE_APK")}"
|
||||||
|
RAW="$OUT/raw.csv"
|
||||||
|
: > "$RAW"
|
||||||
|
|
||||||
|
adb root >/dev/null 2>&1 && sleep 3
|
||||||
|
adb wait-for-device
|
||||||
|
read -r W H < <(adb shell wm size | tr -d '\r' | awk -F'[ x]' '/Physical/ {print $3, $4}')
|
||||||
|
|
||||||
|
record() { echo "$1,$2,$3" >> "$RAW"; } # name,metric,value
|
||||||
|
|
||||||
|
install() {
|
||||||
|
adb uninstall "$PKG" >/dev/null 2>&1
|
||||||
|
adb install -g "$1" >/dev/null
|
||||||
|
adb shell am start -W -n "$ACT" >/dev/null
|
||||||
|
sleep 2
|
||||||
|
adb shell am force-stop "$PKG"
|
||||||
|
# Compiles with the APK's baseline profile only, as the device does after an install,
|
||||||
|
# without what the JIT learned during the first run (same as Macrobenchmark's Partial mode)
|
||||||
|
adb shell cmd package compile --reset "$PKG" >/dev/null
|
||||||
|
adb shell am broadcast -f 0x20 -a androidx.profileinstaller.action.INSTALL_PROFILE \
|
||||||
|
"$PKG/androidx.profileinstaller.ProfileInstallReceiver" | tr -d '\r' | grep -o 'result=[0-9-]*'
|
||||||
|
sleep 2
|
||||||
|
adb shell cmd package compile -f -m speed-profile "$PKG" >/dev/null
|
||||||
|
}
|
||||||
|
|
||||||
|
launch() {
|
||||||
|
adb shell am start-activity -W -n "$ACT" | tr -d '\r'
|
||||||
|
}
|
||||||
|
|
||||||
|
cold_starts() {
|
||||||
|
local t
|
||||||
|
for _ in $(seq "$STARTS"); do
|
||||||
|
adb shell am force-stop "$PKG"
|
||||||
|
adb shell 'sync; echo 3 > /proc/sys/vm/drop_caches'
|
||||||
|
sleep 2
|
||||||
|
t="$(launch | awk '/TotalTime/ {print $2}')"
|
||||||
|
[[ -n "$t" ]] && record "$1" cold_start_ms "$t"
|
||||||
|
sleep 3
|
||||||
|
done
|
||||||
|
}
|
||||||
|
|
||||||
|
memory() {
|
||||||
|
local pss
|
||||||
|
for _ in 1 2 3; do
|
||||||
|
adb shell am force-stop "$PKG"
|
||||||
|
launch >/dev/null
|
||||||
|
sleep 10
|
||||||
|
pss="$(adb shell dumpsys meminfo "$PKG" | tr -d '\r' | awk '/TOTAL PSS:/ {print $3; exit}')"
|
||||||
|
[[ -n "$pss" ]] && record "$1" pss_kb "$pss"
|
||||||
|
done
|
||||||
|
}
|
||||||
|
|
||||||
|
# CPU time and scheduler wakeups of all app threads during 60 s on the home screen
|
||||||
|
background_cpu() {
|
||||||
|
local pid a b
|
||||||
|
adb shell am force-stop "$PKG"
|
||||||
|
launch >/dev/null
|
||||||
|
sleep 5
|
||||||
|
adb shell input keyevent 3
|
||||||
|
sleep 5
|
||||||
|
pid="$(adb shell pidof "$PKG" | tr -d '\r')"
|
||||||
|
[[ -z "$pid" ]] && return
|
||||||
|
a="$(adb shell "cat /proc/$pid/task/*/schedstat" | awk '{t += $1; n += $3} END {print t, n}')"
|
||||||
|
sleep 60
|
||||||
|
b="$(adb shell "cat /proc/$pid/task/*/schedstat" | awk '{t += $1; n += $3} END {print t, n}')"
|
||||||
|
read -r t1 n1 <<< "$a"
|
||||||
|
read -r t2 n2 <<< "$b"
|
||||||
|
record "$1" bg_cpu_ms_per_min "$(( (t2 - t1) / 1000000 ))"
|
||||||
|
record "$1" bg_wakeups_per_min "$(( n2 - n1 ))"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Memory still held 30 s after leaving the app from the Apps tab, with every icon loaded once
|
||||||
|
background_memory() {
|
||||||
|
local pss
|
||||||
|
adb shell am force-stop "$PKG"
|
||||||
|
launch >/dev/null
|
||||||
|
sleep 3
|
||||||
|
tap_text "Apps" || return
|
||||||
|
sleep 2
|
||||||
|
tap_text "System" scroll
|
||||||
|
sleep 2
|
||||||
|
for _ in 1 2 3 4; do
|
||||||
|
adb shell input swipe $((W / 2)) $((H * 3 / 4)) $((W / 2)) $((H / 4)) 200
|
||||||
|
sleep 1
|
||||||
|
done
|
||||||
|
sleep 3
|
||||||
|
adb shell input keyevent 3
|
||||||
|
sleep 30
|
||||||
|
pss="$(adb shell dumpsys meminfo "$PKG" | tr -d '\r' | awk '/TOTAL PSS:/ {print $3; exit}')"
|
||||||
|
[[ -n "$pss" ]] && record "$1" bg_pss_after_apps_kb "$pss"
|
||||||
|
}
|
||||||
|
|
||||||
|
tap_text() {
|
||||||
|
local xy
|
||||||
|
for _ in 1 2 3 4 5; do
|
||||||
|
adb shell uiautomator dump /sdcard/ui.xml >/dev/null 2>&1
|
||||||
|
xy="$(adb shell cat /sdcard/ui.xml | python3 -c '
|
||||||
|
import re, sys
|
||||||
|
xml, text = sys.stdin.read(), sys.argv[1]
|
||||||
|
for node in re.findall(r"<node [^>]*>", xml):
|
||||||
|
# Compose merges a clickable row into one node: "System, 3 of 5"
|
||||||
|
if re.search(r"(text|content-desc)=\"%s(\"|, )" % re.escape(text), node):
|
||||||
|
x1, y1, x2, y2 = map(int, re.search(r"bounds=\"\[(\d+),(\d+)\]\[(\d+),(\d+)\]\"", node).groups())
|
||||||
|
print((x1 + x2) // 2, (y1 + y2) // 2)
|
||||||
|
break
|
||||||
|
' "$1")"
|
||||||
|
if [[ -n "$xy" ]]; then
|
||||||
|
adb shell input tap $xy
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
# Lazy lists only show what is on screen; with "scroll", look further down
|
||||||
|
[[ "${2:-}" == scroll ]] && adb shell input swipe $((W / 2)) $((H * 2 / 3)) $((W / 2)) $((H / 3)) 300
|
||||||
|
sleep 1
|
||||||
|
done
|
||||||
|
echo "::warning::'$1' not found on screen"
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
jank() {
|
||||||
|
local g total janky
|
||||||
|
adb shell am force-stop "$PKG"
|
||||||
|
launch >/dev/null
|
||||||
|
sleep 3
|
||||||
|
tap_text "Apps" || return
|
||||||
|
sleep 2
|
||||||
|
tap_text "System" scroll # the only group collapsed by default, listed last
|
||||||
|
sleep 2
|
||||||
|
for _ in 1 2 3; do
|
||||||
|
adb shell input swipe $((W / 2)) $((H / 4)) $((W / 2)) $((H * 3 / 4)) 100
|
||||||
|
done
|
||||||
|
sleep 2
|
||||||
|
adb shell dumpsys gfxinfo "$PKG" reset >/dev/null
|
||||||
|
for dir in down down down down down up up up up up; do
|
||||||
|
if [[ $dir == down ]]; then
|
||||||
|
adb shell input swipe $((W / 2)) $((H * 3 / 4)) $((W / 2)) $((H / 4)) 200
|
||||||
|
else
|
||||||
|
adb shell input swipe $((W / 2)) $((H / 4)) $((W / 2)) $((H * 3 / 4)) 200
|
||||||
|
fi
|
||||||
|
sleep 1.2
|
||||||
|
done
|
||||||
|
g="$(adb shell dumpsys gfxinfo "$PKG" | tr -d '\r')"
|
||||||
|
total="$(awk -F': ' '/Total frames rendered/ {print $2; exit}' <<< "$g")"
|
||||||
|
janky="$(awk '/Janky frames:/ {print $3; exit}' <<< "$g")"
|
||||||
|
if [[ -n "$total" && "$total" -gt 0 ]]; then
|
||||||
|
record "$1" frames "$total"
|
||||||
|
record "$1" janky_pct "$(awk -v j="$janky" -v t="$total" 'BEGIN {printf "%.2f", j * 100 / t}')"
|
||||||
|
for p in 50 90 99; do
|
||||||
|
record "$1" "frame_p${p}_ms" "$(awk "/${p}th percentile/ {gsub(\"ms\", \"\", \$3); print \$3; exit}" <<< "$g")"
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
measure() {
|
||||||
|
echo "::group::$1"
|
||||||
|
install "$2"
|
||||||
|
cold_starts "$1"
|
||||||
|
memory "$1"
|
||||||
|
background_cpu "$1"
|
||||||
|
background_memory "$1"
|
||||||
|
jank "$1"
|
||||||
|
jank "$1"
|
||||||
|
echo "::endgroup::"
|
||||||
|
}
|
||||||
|
|
||||||
|
# The first launches after boot are far slower than later ones; warm up before measuring
|
||||||
|
echo "::group::warm-up"
|
||||||
|
install "$BASE_APK"
|
||||||
|
for _ in 1 2 3 4 5; do
|
||||||
|
adb shell am force-stop "$PKG"
|
||||||
|
launch >/dev/null
|
||||||
|
sleep 2
|
||||||
|
done
|
||||||
|
echo "::endgroup::"
|
||||||
|
|
||||||
|
for r in $(seq "$ROUNDS"); do
|
||||||
|
if (( r % 2 )); then
|
||||||
|
measure base "$BASE_APK"
|
||||||
|
measure head "$HEAD_APK"
|
||||||
|
else
|
||||||
|
measure head "$HEAD_APK"
|
||||||
|
measure base "$BASE_APK"
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
[[ -f "$OUT/sizes.csv" ]] && cat "$OUT/sizes.csv" >> "$RAW"
|
||||||
|
|
||||||
|
python3 - "$RAW" > "$OUT/results.md" <<'EOF'
|
||||||
|
import csv, statistics, sys
|
||||||
|
data = {}
|
||||||
|
for name, metric, value in csv.reader(open(sys.argv[1])):
|
||||||
|
if value:
|
||||||
|
data.setdefault(metric, {}).setdefault(name, []).append(float(value))
|
||||||
|
print("| Metric (median) | base | head | change | base min–max | head min–max | n |")
|
||||||
|
print("|---|---|---|---|---|---|---|")
|
||||||
|
for metric, by in data.items():
|
||||||
|
b, h = by.get("base", []), by.get("head", [])
|
||||||
|
mb = statistics.median(b) if b else None
|
||||||
|
mh = statistics.median(h) if h else None
|
||||||
|
change = f"{(mh - mb) / mb * 100:+.1f}%" if mb and mh is not None else "n/a"
|
||||||
|
fmt = lambda v: "n/a" if v is None else (f"{v:.0f}" if v >= 100 else f"{v:.2f}")
|
||||||
|
rng = lambda v: f"{fmt(min(v))}–{fmt(max(v))}" if v else "n/a"
|
||||||
|
print(f"| {metric} | {fmt(mb)} | {fmt(mh)} | {change} | {rng(b)} | {rng(h)} | {len(b)}/{len(h)} |")
|
||||||
|
EOF
|
||||||
|
|
||||||
|
cat "$OUT/results.md"
|
||||||
|
[[ -n "${GITHUB_STEP_SUMMARY:-}" ]] && cat "$OUT/results.md" >> "$GITHUB_STEP_SUMMARY"
|
||||||
|
msg="$(cat "$OUT/results.md")"
|
||||||
|
echo "::notice title=Benchmark::${msg//$'\n'/'%0A'}"
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
# SparkleDNS server list. How to add a server: see CONTRIBUTING.md
|
# 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
|
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/
|
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
|
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/
|
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/
|
||||||
|
|||||||