76 Commits
Author SHA1 Message Date
kalarina 43f0d42d65 Release 1.0.10 2026-10-25 16:47:56 +02:00
kalarina 2b0f842579 Remove the GitHub Actions workflows 2026-10-25 14:54:42 +02:00
kalarina 17ede339fa Show own blocked domains as lazy list rows
All own domains were composed at once when the Blocklist tab opened.
The rows keep the look of the card they were in.
2026-10-25 14:50:49 +02:00
kalarina ac643caf03 Download blocklists again only when they changed
Updates send the stored ETag / Last-Modified, and a 304 answer keeps the
list on disk. Before, every update fetched every list in full.
2026-10-25 14:49:14 +02:00
kalarina 0ceae2f557 Read tile settings off the main thread
Opening the quick settings panel could start a fresh process whose
first tile update read SharedPreferences and servers.txt on the main
thread.
2026-10-25 14:48:46 +02:00
kalarina df41b44302 Tell the user when no app can open a link
Privacy policy, donation, source code and license links silently did
nothing on devices without a browser.
2026-10-25 14:48:16 +02:00
kalarina 4619292174 Ignore repeated taps on Connect, Disconnect and Switch
A quick double tap could start the connection twice, open the VPN
dialog twice, or turn the VPN back on right after switching it off.
The buttons are disabled until the VPN state changes (at most 5 s).
2026-10-25 14:47:57 +02:00
kalarina cff974851a Render app icons at their on-screen size
Icons were always drawn at 96 px: blurry on screens where 40 dp is
larger, wasted memory where it is smaller. The cache is now limited to
10 MB instead of 256 entries.
2026-10-25 14:47:28 +02:00
kalarina d9080195ab Let R8 obfuscate release builds
Shrinks the dex further. Crash reports keep file names and line
numbers; the mapping file restores the names and is kept with the CI
artifacts.
2026-10-25 14:46:33 +02:00
kalarina 026c2c9493 Package only the app's own languages
Library translations for other languages made up a large part of
resources.arsc while the app shows English in those languages anyway.
2026-10-25 14:46:22 +02:00
kalarina 8907f4cf96 Benchmark: warm the emulator up first and run three rounds by default
Two identical APKs differed by 9% in median cold start without it.
2026-10-25 13:39:11 +02:00
kalarina 9aceaaa200 CI: report the size of the packaged baseline profile 2026-10-25 13:39:11 +02:00
kalarina 9e744b309e Benchmark: compile with the baseline profile only, find off-screen rows
The app is now compiled the way Macrobenchmark's Partial mode does it,
so runs compare baseline profiles instead of what the JIT learned in a
warm-up run. Tapping a row scrolls the list when the row is off screen.
2026-10-25 12:35:23 +02:00
kalarina 603e90dcca Mention unit tests and the benchmark in CONTRIBUTING 2026-10-25 12:30:38 +02:00
kalarina e7105b0245 Benchmark: measure memory kept in the background after the Apps tab 2026-10-25 12:29:41 +02:00
kalarina 25e359595b Free decoded app icons once the UI is hidden
The VPN service keeps the process alive in the background, and with it
up to 256 icon bitmaps from the Apps tab.
2026-10-25 12:29:31 +02:00
kalarina 9f9c79cf2b Keep server test results and collapsed app groups across rotation 2026-10-25 12:28:49 +02:00
kalarina 447a309f69 Refuse blocklists with more than 4 million domains
A wrong URL pointing at a huge file could otherwise run the app out of
memory while parsing it.
2026-10-25 12:28:15 +02:00
kalarina 8b975c77ce Show the last app list at once when the Apps tab opens again
The list is still reloaded in the background on every visit; it no
longer starts from the loading placeholder each time.
2026-10-25 12:28:15 +02:00
kalarina 04ef7adb44 Trim Compose work in lists and frequent recompositions
contentType for lazy list items, a set for the own-domain lookup per
Monitor row, the group chevron animated in the draw phase, the custom
URL check remembered and the number format reused.
2026-10-25 12:27:50 +02:00
kalarina f236136919 Log VPN setup and tunnel write errors instead of dropping them silently 2026-10-25 12:27:24 +02:00
kalarina a33a945477 Store launcher icon and logo as lossless WebP
Pixel-identical to the PNGs, 108 KB smaller.
2026-10-25 12:27:01 +02:00
kalarina 8502860512 Add workflow that records a baseline profile on an emulator 2026-10-25 12:26:33 +02:00
kalarina 50f069731c Add LeakCanary to debug builds 2026-10-25 12:25:23 +02:00
kalarina 37653792fd Enable StrictMode in debug builds 2026-10-25 12:25:23 +02:00
kalarina 2cb3439efd Fail lookups that waited too long in the worker queue
With a slow server all 16 workers can be busy for up to 8 s each, and
queries kept piling up long after the asking app had retried or given
up, delaying every newer one.
2026-10-25 12:25:11 +02:00
kalarina 8ac908e684 Drop pooled DoH connections when the default network changes
After a switch between Wi-Fi and mobile data, HTTP/2 lookups could keep
using a connection of the old network until they timed out.
2026-10-25 12:24:09 +02:00
kalarina 5a1bf79e4b Derive all OkHttp clients from one shared base client
The DoH transport keeps its own connection pool and no longer creates
the dispatcher's thread pool only to shut it down.
2026-10-25 12:23:46 +02:00
kalarina 5f56c471ce Keep own blocked domains apart from downloaded lists
Adding or removing one own domain re-sorted the whole combined set,
allocating 8 bytes per entry of every list each time. Lists are now
merged in linear time and own domains are looked up in their own array.
2026-10-25 12:23:21 +02:00
kalarina 87feb7f483 Stop UI updates while the app is in the background
Home and Monitor polled the query log every second and Home queried
ConnectivityManager every 3 s, and kept doing so while the activity
was stopped. The log now signals changes (still at most once a second),
Private DNS comes from a network callback, and all flows are collected
with collectAsStateWithLifecycle.
2026-10-25 12:21:47 +02:00
kalarina a63184830d Run CI for every push instead of queueing them 2026-10-25 12:20:05 +02:00
kalarina 4e99ef1211 Load blocklists at background thread priority 2026-10-25 12:19:49 +02:00
kalarina fa6398c40e Load settings, server list and crash report off the main thread at startup
The first composition of Home read SharedPreferences, servers.txt and
last_crash.txt on the main thread.
2026-10-25 12:19:49 +02:00
kalarina 778ce20f6e Close DoH connections off the main thread when a session stops 2026-10-25 12:19:21 +02:00
kalarina 7da1a34495 Build the DoH transport on the first query instead of the main thread
Creating HttpEngine for HTTP/3 servers (the default one included) ran
inside onStartCommand on every connect and server switch.
2026-10-25 12:19:00 +02:00
kalarina bac4ccf26e Show an error instead of crashing when blocklist changes cannot be saved 2026-10-25 12:18:17 +02:00
kalarina e601b2dbaa Keep the tunnel reader alive on bad packets, disconnect if it dies
Before, any unexpected error ended the reader while the VPN stayed up,
so DNS stopped working for the whole device without any sign of it.
2026-10-25 12:18:17 +02:00
kalarina 8c6bb33527 Add unit tests for packet parsing, DNS cache, blocklist parser and server list
DnsCache takes its clock as a parameter so expiry can be tested.
2026-10-25 12:16:46 +02:00
kalarina 43e57c9357 Add emulator benchmark that compares two revisions 2026-10-25 12:13:31 +02:00
kalarina 87d9afd55b Add CI that builds and unit-tests every pushed commit 2026-10-25 12:00:26 +02:00
kalarina 7a2c7eccb3 Use GPL-3.0-only license wording 2026-10-21 14:50:38 +00:00
kalarina dbc3454742 Make star request platform-neutral 2026-10-20 13:06:24 +00:00
kalarina ad798f0a79 Add star request to README 2026-10-20 12:59:48 +00:00
kalarina 9604d07cea Changelog for 1.0.9 in all languages, mention donation links 2026-10-16 17:06:56 +00:00
kalarina b13adc5340 Add donation links to servers next to the privacy policy 2026-10-16 17:02:29 +00:00
kalarina 5f2dbccebf Point Obtainium links to Gitea 2026-10-16 11:59:23 +00:00
kalarina bab6c754dc Redesign README: store badges, release badge, install options 2026-10-16 11:51:04 +00:00
kalarina ddc219d01f Upload files to "assets" 2026-10-16 11:43:09 +00:00
kalarina 275eb3ab0b Upload files to "assets" 2026-10-16 11:40:39 +00:00
kalarina 62c941a07b Release 1.0.9 2026-10-15 13:43:22 +00:00
kalarina e039ab0d46 Remove HTTP/3 badge from the server list 2026-10-14 13:35:32 +00:00
kalarina 032a49f1f8 New privacy policy icon on servers, shorter About description 2026-10-14 12:12:17 +00:00
kalarina 9ca55a4d40 Simpler server list format, document adding servers in CONTRIBUTING 2026-10-14 11:03:35 +00:00
kalarina 00e30cb858 Mention new servers in the 1.0.7 changelog 2026-10-14 10:56:09 +00:00
kalarina 41a8f94f65 Update server list button and privacy policy links on Home 2026-10-14 10:55:35 +00:00
kalarina 6bd72d3583 Independent DoH servers and a server list synced from the repository 2026-10-14 10:55:04 +00:00
kalarina 59194a7914 Remove VirusTotal workflow 2026-10-14 10:42:10 +00:00
kalarina 0f8bb8dc9d Read VirusTotal key from secret 2026-10-14 10:20:55 +00:00
kalarina 8bccbe597c Update .gitea/workflows/virustotal.yml 2026-10-14 10:11:07 +00:00
kalarina 73959b16b2 Scan release APKs with VirusTotal 2026-10-14 09:23:23 +00:00
kalarina 838507ec63 Release 1.0.7 2026-10-13 17:01:47 +00:00
kalarina 3de0f84aab Update CONTRIBUTING for six languages 2026-10-13 16:52:03 +00:00
kalarina 9b40f7e7af Add missing blocklist hint key 2026-10-13 15:53:37 +00:00
kalarina eda2353cf4 Add German, Japanese, Lithuanian and Chinese translations 2026-10-13 15:52:34 +00:00
kalarina 728dbba49b Add German, Japanese, Lithuanian and Chinese UI, closable hint cards, drop license row from About 2026-10-13 15:50:05 +00:00
kalarina 91f7d99508 Update store descriptions in six languages 2026-10-13 14:51:40 +00:00
kalarina 442aad40ac Remove duplicate account note from CONTRIBUTING 2026-10-12 13:37:30 +00:00
kalarina 6dbe67e5c0 Update README 2026-10-12 13:35:33 +00:00
kalarina d036bbe93a Update README 2026-10-12 13:34:15 +00:00
kalarina 42326e0933 Use Gitea as the only contribution channel 2026-10-11 14:11:14 +00:00
kalarina 9dda504172 Add contributing guide and issue/PR templates 2026-10-11 14:01:49 +00:00
kalarina 44790eb68f Restructure README 2026-10-11 13:46:53 +00:00
kalarina 149d08b082 Add minimum Android version to README 2026-10-11 13:41:08 +00:00
kalarina 25b6dc7d6c Normalize line endings via .gitattributes 2026-10-11 12:52:58 +03:00
kalarina 00d15bac74 Remove fdroid recipe, state GPL-3.0-or-later, format key fingerprint
The build recipe now lives in fdroiddata, so the outdated copy in
fdroid/ is removed. README states the license as GPL-3.0-or-later to
match the F-Droid metadata and shows the signing certificate
fingerprint in colon-separated form.
2026-10-10 15:25:26 +00:00
kalarina f438d44e03 Verify downloads by signing key and fix app name in README
README now tells users to verify the APK signing certificate instead
of a checksum from the Releases page, uses the real APK file name and
spells the app name as SparkleDNS.
2026-10-10 15:19:37 +00:00
98 changed files with 2865 additions and 551 deletions
+2
View File
@@ -0,0 +1,2 @@
* text=auto eol=lf
*.bat text eol=crlf
+28
View File
@@ -0,0 +1,28 @@
---
name: Bug report
about: Something doesn't work as expected
title: "[Bug] "
---
**What happened**
**Steps to reproduce**
1.
2.
3.
**What you expected**
**Environment**
- App version:
- Installed from: Gitea / F-Droid
- Device and Android version:
- DoH server in use:
- Network: Wi-Fi / mobile data
**Screenshots or logs** (optional — please remove domains you don't want to share)
@@ -0,0 +1,15 @@
---
name: DoH server or blocklist
about: Suggest a DoH server or blocklist preset
title: "[Preset] "
---
- Type: DoH server / blocklist
- Name:
- URL:
- Homepage or documentation:
- Privacy policy (DoH servers) or license (blocklists):
- Donation page (DoH servers, optional):
- [ ] DoH server: public and supports RFC 8484
- [ ] Blocklist: public and actively maintained
+18
View File
@@ -0,0 +1,18 @@
---
name: Feature request
about: Suggest an idea that fits the app
title: "[Feature] "
---
<!-- Please check the "Out of scope" list in CONTRIBUTING.md before opening this. -->
**What problem does this solve**
**Proposed solution**
**Alternatives you considered**
- [ ] I'd like to implement this myself
+12
View File
@@ -0,0 +1,12 @@
---
name: Translation fix
about: Report a wrong or awkward translation
title: "[Translation] "
---
<!-- Currently supported: English, Russian. For a new language, open a feature request first. -->
- Language:
- Screen or place in the app:
- Current text:
- Suggested text:
+17
View File
@@ -0,0 +1,17 @@
## What does this change
## Related issue
Closes #
## Checklist
- [ ] Discussed in an issue first (not needed for small fixes)
- [ ] `./gradlew assembleDebug` builds
- [ ] Tested on a device or emulator (Android version: )
- [ ] DNS queries only go to the selected DoH server
- [ ] No ads, analytics, trackers or Google Play Services / Firebase dependencies
- [ ] New strings added to `values/strings.xml` (missing translations noted below)
- [ ] Screenshots added for UI changes
- [ ] I agree that my contribution is licensed under GPL-3.0-or-later
+102
View File
@@ -0,0 +1,102 @@
# Contributing to SparkleDNS
Thanks for wanting to help! This guide explains where to contribute, what fits the project and how to send changes.
## Where to contribute
Issues and pull requests go to the repository on [Gitea](https://git.skysparkle.cc/kalarina/Sparkledns).
## Ways to help
- **Report a bug** — use the *Bug report* template.
- **Add a DoH server** — add one line to [`servers/servers.txt`](servers/servers.txt), see [Adding a DoH server](#adding-a-doh-server).
- **Suggest a blocklist** — use the *DoH server or blocklist* template.
- **Suggest a feature** — use the *Feature request* template; check [Out of scope](#out-of-scope) first.
- **Fix a translation** — use the *Translation fix* template or send a pull request.
- **Write code** — see [Pull requests](#pull-requests).
## Before you start
- **Small changes** (typos, obvious bugs, translation fixes): send a pull request directly.
- **Anything bigger** (new features, UI changes, new dependencies): open an issue first and wait for a go-ahead, so your work isn't wasted.
## Ground rules
- No ads, analytics, telemetry, trackers or accounts.
- DNS queries may only go to the DoH server the user selected — never anywhere else.
- No Google Play Services, Firebase or other proprietary libraries — the app must stay buildable for F-Droid.
- New dependencies must be open source and justified in the pull request.
- Be respectful in issues and reviews.
## Out of scope
These will not be accepted:
- Changing the default DoH server.
- Logging, uploading or sharing users' DNS queries.
- Features that require Google Play Services or a proprietary SDK.
## Adding a DoH server
The server list lives in [`servers/servers.txt`](servers/servers.txt). The app downloads it when the user taps **Update server list**, so a new server reaches users without a new release.
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 | Donation page
```
- **Name** — how the server appears in the app, up to 40 characters.
- **DoH URL** — the full `https://` address of the DoH endpoint.
- **Privacy policy** — an `https://` link to the operator's privacy policy. Lines without one are ignored.
- **h3** — optional. Add it only if the server supports HTTP/3.
- **Donation page** — optional. An `https://` link to the operator's own page for donations or support. The app shows it as a coin button next to the privacy policy. Only link to a page the operator runs or names on its website — no affiliate or third-party fundraising links.
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 | 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:
- be public and free, without an account;
- support RFC 8484;
- publish what it logs, and not sell or share query data;
- be run by a non-profit, a community or an individual rather than a large company.
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 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
Blocklist presets must be public, actively maintained and licensed for this kind of use. Use the *DoH server or blocklist* template and include a link to the list's homepage.
## Translations
SparkleDNS is available in exactly six languages: English, Russian, German, Japanese, Lithuanian and Chinese. Fixes to these are welcome; new languages are not accepted.
- App strings: `app/src/main/res/values-<lang>/strings.xml` (English is `values/`).
- Store listing: `fastlane/metadata/android/<locale>/`.
If your code adds new strings, add them to `values/strings.xml`. Translations for the other languages are welcome but not required — mention missing ones in the pull request.
## Pull requests
1. Fork the repository and create a branch from `main`.
2. Keep one topic per pull request.
3. Follow the existing Kotlin and Jetpack Compose style; keep comments short and in English; don't reformat unrelated code.
4. Make sure `./gradlew assembleDebug testDebugUnitTest` passes, and test on a device or emulator. For changes that may affect speed or memory, `scripts/bench.sh` compares two APKs on a rooted device or emulator (`scripts/bench-build.sh` builds them from two revisions).
5. Write short, plain commit messages in English (for example `Fix tunnel restart after server switch`).
6. Add screenshots for UI changes.
## Security
Please don't post details of security issues publicly. Open a short issue titled "Security contact" without any details, and the maintainer will reach out privately.
## License
By contributing, you agree that your contribution is licensed under the [GNU General Public License v3.0 or later](LICENSE), the same as the rest of the project.
+1 -2
View File
@@ -636,8 +636,7 @@ the "copyright" line and a pointer to where the full notice is found.
This program is free software: you can redistribute it and/or modify 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
+48 -49
View File
@@ -1,22 +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"> <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/github/downloads/kalarina-bit/Sparkledns/latest/total?label=downloads&color=2e7d32&labelColor=1b1b1b" alt="downloads counter"> <a href="https://github.com/kalarina-bit/Sparkledns/releases/latest"><img src="https://img.shields.io/github/v/release/kalarina-bit/Sparkledns?style=for-the-badge&label=release&labelColor=1b1b1b&color=2e7d32" alt="Latest release"></a>
</p> </p>
**Lightweight DNS-over-HTTPS client for Android** (Kotlin, Jetpack Compose). <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>
The app starts a local VPN that captures only DNS traffic and forwards every query to the selected DoH server (RFC 8484) — everything else goes through your normal connection. <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>
## Features > [!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
@@ -26,62 +41,46 @@ The app starts a local VPN that captures only DNS traffic and forwards 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"> Every official APK is signed with the same key. Check it before installing:
1. Download the APK for the version you want from the [Releases page](https://github.com/kalarina-bit/Sparkledns/releases).
2. On your Android device, allow installs from unknown sources for the app you use to open the file (Settings → Apps → Special access → Install unknown apps).
3. Open the downloaded `.apk` file and confirm the install.
## Verifying a download
<img src="assets/icon-verify.png" width="36" align="left">
Compare the SHA-256 checksum of the downloaded APK against the value shown for that version on the [Releases page](https://github.com/kalarina-bit/Sparkledns/releases):
```sh ```sh
sha256sum Sparkledns-vX.X.X.apk apksigner verify --print-certs SparkleDNS-v<version>.apk
``` ```
## Building from source The SHA-256 fingerprint of the signing certificate must be:
```
42:F6:30:63:4B:D0:F8:7F:49:17:85:A8:84:87:70:E4:45:96:7B:36:F1:02:8E:FD:16:F8:F9:52:01:27:3A:29
```
`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`).
## <img src="assets/icon-structure.png" width="32" alt=""> Building from source
Requires JDK 17+ and Android SDK 36.
```sh ```sh
./gradlew assembleRelease ./gradlew assembleRelease
``` ```
Or open the project in Android Studio and run the `app` configuration. Requires Android 8.0 (API 26) or newer; HTTP/3 requires Android 14. ### Releasing
The version lives in `app/build.gradle.kts` (`versionName`, `versionCode = major * 10000 + minor * 100 + patch`). For every release, add `fastlane/metadata/android/<locale>/changelogs/<versionCode>.txt` and tag the commit as `v<versionName>` (for example `v1.0.6`) — F-Droid detects new releases from these tags. 1. Bump `versionName` and `versionCode` in `app/build.gradle.kts` (`versionCode = major * 10000 + minor * 100 + patch`).
2. Add `fastlane/metadata/android/<locale>/changelogs/<versionCode>.txt`.
3. Tag the commit as `v<versionName>` (for example `v1.0.9`) — F-Droid detects new releases from these tags, so upload the signed APK to the release right away.
## Repository structure ## 🤝 Contributing
<img src="assets/icon-structure.png" width="36" align="left"> 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
.
├── app/ # Android app source (Kotlin, Jetpack Compose)
├── assets/ # README images
│ └── screenshots/ # App screenshots
├── fastlane/ # F-Droid store listing, screenshots and changelogs
├── fdroid/ # Build recipe for fdroiddata
├── gradle/ # Gradle wrapper
├── LICENSE # GNU GPLv3
└── README.md
```
APK builds are published as assets on the [Releases page](https://github.com/kalarina-bit/Sparkledns/releases), not stored in this repository. [GNU General Public License v3.0 only](LICENSE).
## License
This project is licensed under the **GNU General Public License v3.0** — see the [LICENSE](LICENSE) file for details.
+20 -2
View File
@@ -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 = 10006 versionCode = 10010
versionName = "1.0.6" 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")
} }
+3 -2
View File
@@ -1,3 +1,4 @@
# Readable stack traces in crash reports # File names and line numbers stay in stack traces, names are obfuscated. To read a crash
# report, build the same release (builds are reproducible) and run
# retrace app/build/outputs/mapping/release/mapping.txt crash.txt
-keepattributes SourceFile,LineNumberTable -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
@@ -50,7 +53,6 @@ import androidx.compose.ui.unit.dp
private const val PRIVACY_POLICY = "https://skysparkle.cc/privacy?lang=en" private const val PRIVACY_POLICY = "https://skysparkle.cc/privacy?lang=en"
private const val SOURCE_CODE = "https://git.skysparkle.cc/kalarina/Sparkledns" private const val SOURCE_CODE = "https://git.skysparkle.cc/kalarina/Sparkledns"
private const val APP_LICENSE = "GPL-3.0-or-later"
private const val APACHE_2 = "Apache License 2.0" private const val APACHE_2 = "Apache License 2.0"
private const val APACHE_2_URL = "https://www.apache.org/licenses/LICENSE-2.0" private const val APACHE_2_URL = "https://www.apache.org/licenses/LICENSE-2.0"
@@ -149,7 +151,6 @@ private fun AboutContent(modifier: Modifier, onOpenLicenses: () -> Unit) {
InfoRow(stringResource(R.string.about_version), BuildConfig.VERSION_NAME) InfoRow(stringResource(R.string.about_version), BuildConfig.VERSION_NAME)
InfoRow(stringResource(R.string.about_protocol), "DNS-over-HTTPS (RFC 8484)") InfoRow(stringResource(R.string.about_protocol), "DNS-over-HTTPS (RFC 8484)")
InfoRow("HTTP/3", http3) InfoRow("HTTP/3", http3)
InfoRow(stringResource(R.string.about_license), APP_LICENSE)
} }
} }
@@ -265,8 +266,13 @@ private fun InfoRow(label: String, value: String) {
} }
} }
private 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,27 +79,39 @@ 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)) }
// Closing the "reconnect" card hides it until the selection changes again
var pendingDismissedFor by remember { mutableStateOf<Set<String>?>(null) }
// Uninstalled apps may still be in the saved set; count only the ones on the device // Uninstalled apps may still be in the saved set; count only the ones on the device
val excludedCount = apps?.count { it.packageName in excluded } ?: excluded.size val excludedCount = apps?.count { it.packageName in excluded } ?: excluded.size
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) {
@@ -122,8 +136,21 @@ fun AppsScreen(modifier: Modifier = Modifier) {
) { ) {
item { item {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
HintCard(stringResource(R.string.apps_hint), icon = R.drawable.ic_tab_info) AnimatedVisibility(visible = showAppsHint, enter = Motion.expandIn, exit = Motion.collapseOut) {
AnimatedVisibility(visible = pending, enter = Motion.expandIn, exit = Motion.collapseOut) { HintCard(
stringResource(R.string.apps_hint),
icon = R.drawable.ic_tab_info,
onDismiss = {
showAppsHint = false
prefs.dismissHint(HINT_APPS)
},
)
}
AnimatedVisibility(
visible = pending && excluded != pendingDismissedFor,
enter = Motion.expandIn,
exit = Motion.collapseOut,
) {
HintCard( HintCard(
text = stringResource(R.string.apps_pending), text = stringResource(R.string.apps_pending),
icon = R.drawable.ic_refresh, icon = R.drawable.ic_refresh,
@@ -133,6 +160,7 @@ fun AppsScreen(modifier: Modifier = Modifier) {
Text(stringResource(R.string.reconnect)) Text(stringResource(R.string.reconnect))
} }
}, },
onDismiss = { pendingDismissedFor = excluded },
) )
} }
} }
@@ -171,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,
@@ -188,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,
@@ -220,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
@@ -250,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 },
) )
} }
} }
@@ -258,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) }
} }
} }
@@ -345,3 +377,11 @@ private fun Drawable.toImageBitmap(size: Int): ImageBitmap {
draw(canvas) draw(canvas)
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"
@@ -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
@@ -62,18 +72,20 @@ private val Presets = listOf(
fun BlocklistScreen(modifier: Modifier = Modifier) { fun BlocklistScreen(modifier: Modifier = Modifier) {
val context = LocalContext.current val context = LocalContext.current
val scope = rememberCoroutineScope() val scope = rememberCoroutineScope()
val prefs = remember { Prefs(context) }
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 }
@@ -81,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) } }
result.onSuccess { ok ->
domainError = !ok domainError = !ok
if (ok) domainInput = "" if (ok) domainInput = ""
}.onFailure { showEditError(context, it) }
} }
} }
@@ -92,13 +106,19 @@ 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),
) { ) {
item(key = "summary") {
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
Card(Modifier.fillMaxWidth()) { Card(Modifier.fillMaxWidth()) {
Row(Modifier.padding(16.dp), verticalAlignment = Alignment.CenterVertically) { Row(Modifier.padding(16.dp), verticalAlignment = Alignment.CenterVertically) {
IconBadge( IconBadge(
@@ -124,15 +144,28 @@ fun BlocklistScreen(modifier: Modifier = Modifier) {
} }
} }
HintCard(stringResource(R.string.bl_note), icon = R.drawable.ic_tab_info) AnimatedVisibility(visible = showNote, enter = Motion.expandIn, exit = Motion.collapseOut) {
HintCard(
stringResource(R.string.bl_note),
icon = R.drawable.ic_tab_info,
onDismiss = {
showNote = false
prefs.dismissHint(HINT_BLOCKLIST)
},
)
}
SectionHeader(stringResource(R.string.bl_my), icon = R.drawable.ic_tab_block) SectionHeader(stringResource(R.string.bl_my), icon = R.drawable.ic_tab_block)
}
}
Card(Modifier.fillMaxWidth()) { item(key = "custom") {
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),
@@ -171,21 +204,33 @@ 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 -> }
}
itemsIndexed(custom, key = { _, domain -> "domain:$domain" }, contentType = { _, _ -> "domain" }) { index, domain ->
val last = index == custom.lastIndex
Column(
Modifier
.animateItem()
.fillMaxWidth()
.background(cardColor, if (last) cardBottom else RectangleShape)
.padding(bottom = if (last) 8.dp else 0.dp)
) {
InsetDivider(16) InsetDivider(16)
Row( Row(
modifier = Modifier.padding(start = 16.dp, end = 4.dp), modifier = Modifier.padding(start = 16.dp, end = 4.dp),
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
) { ) {
Text(domain, modifier = Modifier.weight(1f), maxLines = 1, overflow = TextOverflow.Ellipsis) Text(domain, modifier = Modifier.weight(1f), maxLines = 1, overflow = TextOverflow.Ellipsis)
IconButton(onClick = { scope.launch(Dispatchers.IO) { Blocklist.removeCustom(context, domain) } }) { IconButton(onClick = { scope.editBlocklist(context) { Blocklist.removeCustom(context, domain) } }) {
Icon(painterResource(R.drawable.ic_delete), stringResource(R.string.delete), Modifier.size(20.dp)) 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( SectionHeader(
stringResource(R.string.bl_lists), stringResource(R.string.bl_lists),
icon = R.drawable.ic_list, icon = R.drawable.ic_list,
@@ -214,7 +259,7 @@ fun BlocklistScreen(modifier: Modifier = Modifier) {
updating = busy == list.url || busy == Blocklist.ALL_LISTS, updating = busy == list.url || busy == Blocklist.ALL_LISTS,
actionsEnabled = busy == null, actionsEnabled = busy == null,
onRefresh = { Blocklist.download(context, list.url) }, onRefresh = { Blocklist.download(context, list.url) },
onDelete = { scope.launch(Dispatchers.IO) { Blocklist.removeList(context, list.url) } }, onDelete = { scope.editBlocklist(context) { Blocklist.removeList(context, list.url) } },
) )
} }
if (lists.isNotEmpty()) InsetDivider(16) if (lists.isNotEmpty()) InsetDivider(16)
@@ -284,6 +329,8 @@ fun BlocklistScreen(modifier: Modifier = Modifier) {
} }
} }
} }
}
}
@Composable @Composable
private fun InsetDivider(start: Int) { private fun InsetDivider(start: Int) {
@@ -346,3 +393,22 @@ private fun ListRow(
} }
} }
} }
// Blocklist edits write to storage, which can fail (a full disk, for one)
internal inline fun <T> tryEdit(action: () -> T): Result<T> =
try {
Result.success(action())
} catch (e: IOException) {
Result.failure(e)
}
internal fun CoroutineScope.editBlocklist(context: Context, action: () -> Unit) = launch {
withContext(Dispatchers.IO) { tryEdit(action) }.onFailure { showEditError(context, it) }
}
internal fun showEditError(context: Context, error: Throwable) {
val reason = error.message ?: error.javaClass.simpleName
Toast.makeText(context, context.getString(R.string.test_fail, reason), Toast.LENGTH_LONG).show()
}
private const val HINT_BLOCKLIST = "blocklist"
@@ -3,6 +3,8 @@ package cc.skysparkle.sparkledns
import android.app.Application import android.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,25 +234,47 @@ 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) {
@@ -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
@@ -53,7 +55,9 @@ import androidx.compose.material3.Button
import androidx.compose.material3.Card import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults import androidx.compose.material3.CardDefaults
import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.OutlinedTextField
@@ -63,11 +67,12 @@ import androidx.compose.material3.Text
import androidx.compose.material3.TextButton 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.collectAsState 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.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
@@ -84,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
@@ -111,36 +122,44 @@ 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.collectAsStateWithLifecycle()
var syncing by remember { mutableStateOf(false) }
var syncResult by rememberSaveable(stateSaver = TestResultSaver) { mutableStateOf<TestResult?>(null) }
var shownSync by rememberSaveable(stateSaver = TestResultSaver) { mutableStateOf<TestResult?>(null) }
var customUrl by remember { mutableStateOf(prefs.customUrl) } var 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) { prefs.resolve() } val selectedProvider = remember(selected, customUrl, customBootstrap, customHttp3, servers) { prefs.resolve() }
val customName = stringResource(R.string.custom) val customName = stringResource(R.string.custom)
fun nameOf(p: DohProvider) = if (p.id == Providers.CUSTOM_ID) customName else p.name fun nameOf(p: DohProvider) = if (p.id == Providers.CUSTOM_ID) customName else p.name
val shownProvider = active ?: selectedProvider val shownProvider = active ?: selectedProvider
@@ -149,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)
@@ -165,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
@@ -181,6 +216,30 @@ fun HomeScreen(modifier: Modifier = Modifier) {
testResult = null testResult = null
} }
// A server removed from the list falls back to the default one
LaunchedEffect(servers) {
if (selected != Providers.CUSTOM_ID && servers.none { it.id == selected }) select(Providers.default.id)
}
val syncOk = stringResource(R.string.servers_updated)
val syncFail = stringResource(R.string.servers_update_failed)
fun syncServers() {
syncing = true
syncResult = null
scope.launch {
val result = withContext(Dispatchers.IO) {
runCatching { ServerList.sync(context) }
.fold(
onSuccess = { TestResult(true, syncOk) },
onFailure = { TestResult(false, syncFail.format(it.message ?: it.javaClass.simpleName)) },
)
}
shownSync = result
syncResult = result
syncing = false
}
}
fun runTest() { fun runTest() {
val provider = prefs.resolve() val provider = prefs.resolve()
testing = true testing = true
@@ -218,24 +277,60 @@ 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)) {
if (syncing) {
Box(Modifier.size(48.dp), contentAlignment = Alignment.Center) {
CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp)
}
} else {
IconButton(onClick = ::syncServers) {
Icon(
painterResource(R.drawable.ic_refresh),
contentDescription = stringResource(R.string.servers_update),
modifier = Modifier.size(20.dp),
)
}
}
}
AnimatedVisibility(visible = syncResult != null, enter = Motion.expandIn, exit = Motion.collapseOut) {
shownSync?.let { result ->
HintCard(
text = result.text,
icon = if (result.ok) R.drawable.ic_check else R.drawable.ic_alert,
tint = if (result.ok) CachedColor else MaterialTheme.colorScheme.error,
onDismiss = { syncResult = null },
)
}
}
Card(Modifier.fillMaxWidth()) { Card(Modifier.fillMaxWidth()) {
Column(Modifier.padding(vertical = 6.dp)) { Column(Modifier.padding(vertical = 6.dp)) {
Providers.list.forEachIndexed { index, p -> servers.forEachIndexed { index, p ->
if (index > 0) RowDivider() if (index > 0) RowDivider()
ProviderRow(p.name, hostOf(p.url), p.http3, selected == p.id) { select(p.id) } ProviderRow(
title = p.name,
subtitle = hostOf(p.url),
selected = selected == p.id,
onPolicy = p.policy?.let { url -> { openUrl(context, url) } },
onDonate = p.donate?.let { url -> { openUrl(context, url) } },
) { select(p.id) }
} }
RowDivider() RowDivider()
ProviderRow( ProviderRow(
title = stringResource(R.string.custom), title = stringResource(R.string.custom),
subtitle = hostOf(customUrl), subtitle = hostOf(customUrl),
http3 = customHttp3,
selected = isCustom, selected = isCustom,
) { select(Providers.CUSTOM_ID) } ) { select(Providers.CUSTOM_ID) }
} }
@@ -308,13 +403,19 @@ fun HomeScreen(modifier: Modifier = Modifier) {
text = result.text, text = result.text,
icon = if (result.ok) R.drawable.ic_check else R.drawable.ic_alert, icon = if (result.ok) R.drawable.ic_check else R.drawable.ic_alert,
tint = if (result.ok) CachedColor else MaterialTheme.colorScheme.error, tint = if (result.ok) CachedColor else MaterialTheme.colorScheme.error,
onDismiss = { testResult = null },
) )
} }
} }
val lastHost = remember { arrayOf("") } val lastHost = remember { arrayOf("") }
privateDnsHost?.let { lastHost[0] = it } privateDnsHost?.let { lastHost[0] = it }
AnimatedVisibility(visible = privateDnsHost != null, enter = Motion.expandIn, exit = Motion.collapseOut) { var dismissedDnsHost by remember { mutableStateOf(prefs.dismissedPrivateDns) }
AnimatedVisibility(
visible = privateDnsHost != null && privateDnsHost != dismissedDnsHost,
enter = Motion.expandIn,
exit = Motion.collapseOut,
) {
HintCard( HintCard(
text = stringResource(R.string.hint, lastHost[0]), text = stringResource(R.string.hint, lastHost[0]),
icon = R.drawable.ic_alert, icon = R.drawable.ic_alert,
@@ -322,6 +423,10 @@ fun HomeScreen(modifier: Modifier = Modifier) {
action = { action = {
TextButton(onClick = { openNetworkSettings(context) }) { Text(stringResource(R.string.open_settings)) } TextButton(onClick = { openNetworkSettings(context) }) { Text(stringResource(R.string.open_settings)) }
}, },
onDismiss = {
dismissedDnsHost = lastHost[0]
prefs.dismissedPrivateDns = lastHost[0]
},
) )
} }
} }
@@ -334,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,
@@ -419,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),
@@ -435,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]))
@@ -496,7 +602,14 @@ private fun CrashCard(report: String, onCopy: () -> Unit, onDismiss: () -> Unit)
} }
@Composable @Composable
private fun ProviderRow(title: String, subtitle: String, http3: Boolean, selected: Boolean, onClick: () -> Unit) { private fun ProviderRow(
title: String,
subtitle: String,
selected: Boolean,
onPolicy: (() -> Unit)? = null,
onDonate: (() -> Unit)? = null,
onClick: () -> Unit,
) {
val highlight by animateColorAsState( val highlight by animateColorAsState(
if (selected) MaterialTheme.colorScheme.primary.copy(alpha = 0.08f) else Color.Transparent, if (selected) MaterialTheme.colorScheme.primary.copy(alpha = 0.08f) else Color.Transparent,
animationSpec = Motion.color, animationSpec = Motion.color,
@@ -522,9 +635,25 @@ private fun ProviderRow(title: String, subtitle: String, http3: Boolean, selecte
overflow = TextOverflow.Ellipsis, overflow = TextOverflow.Ellipsis,
) )
} }
if (http3) { if (onDonate != null) {
Spacer(Modifier.width(8.dp)) IconButton(onClick = onDonate, modifier = Modifier.size(40.dp)) {
Pill("HTTP/3", MaterialTheme.colorScheme.primary) Icon(
painterResource(R.drawable.ic_donate),
contentDescription = stringResource(R.string.donate),
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(18.dp),
)
}
}
if (onPolicy != null) {
IconButton(onClick = onPolicy, modifier = Modifier.size(40.dp)) {
Icon(
painterResource(R.drawable.ic_policy),
contentDescription = stringResource(R.string.about_privacy_policy),
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(18.dp),
)
}
} }
} }
} }
@@ -537,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,7 +86,8 @@ 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) {
tryEdit {
if (unblock) { if (unblock) {
Blocklist.removeCustom(context, domain) Blocklist.removeCustom(context, domain)
true true
@@ -98,6 +95,11 @@ fun MonitorScreen(modifier: Modifier = Modifier) {
Blocklist.addCustom(context, domain) 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,
@@ -5,6 +5,10 @@ import android.content.Context
class Prefs(context: Context) { class Prefs(context: Context) {
private val sp = context.applicationContext.getSharedPreferences("doh", Context.MODE_PRIVATE) private val sp = context.applicationContext.getSharedPreferences("doh", Context.MODE_PRIVATE)
init {
ServerList.ensureLoaded(context.applicationContext)
}
var providerId: String var providerId: String
get() = sp.getString(KEY_PROVIDER, null) ?: Providers.default.id get() = sp.getString(KEY_PROVIDER, null) ?: Providers.default.id
set(value) = sp.edit().putString(KEY_PROVIDER, value).apply() set(value) = sp.edit().putString(KEY_PROVIDER, value).apply()
@@ -25,6 +29,20 @@ class Prefs(context: Context) {
get() = sp.getStringSet(KEY_EXCLUDED, null)?.toSet() ?: emptySet() get() = sp.getStringSet(KEY_EXCLUDED, null)?.toSet() ?: emptySet()
set(value) = sp.edit().putStringSet(KEY_EXCLUDED, value).apply() set(value) = sp.edit().putStringSet(KEY_EXCLUDED, value).apply()
// Hint cards the user closed with the X
fun isHintDismissed(key: String): Boolean =
sp.getStringSet(KEY_HINTS, null)?.contains(key) == true
fun dismissHint(key: String) {
val current = sp.getStringSet(KEY_HINTS, null)?.toSet() ?: emptySet()
sp.edit().putStringSet(KEY_HINTS, current + key).apply()
}
// The Private DNS warning stays closed until the hostname changes
var dismissedPrivateDns: String
get() = sp.getString(KEY_PRIVATE_DNS, null) ?: ""
set(value) = sp.edit().putString(KEY_PRIVATE_DNS, value).apply()
fun resolve(): DohProvider = fun resolve(): DohProvider =
if (providerId == Providers.CUSTOM_ID) { if (providerId == Providers.CUSTOM_ID) {
DohProvider(Providers.CUSTOM_ID, "Custom", customUrl.trim(), parseIps(customBootstrap), customHttp3) DohProvider(Providers.CUSTOM_ID, "Custom", customUrl.trim(), parseIps(customBootstrap), customHttp3)
@@ -38,5 +56,7 @@ class Prefs(context: Context) {
const val KEY_BOOTSTRAP = "custom_bootstrap" const val KEY_BOOTSTRAP = "custom_bootstrap"
const val KEY_HTTP3 = "custom_http3" const val KEY_HTTP3 = "custom_http3"
const val KEY_EXCLUDED = "excluded_apps" const val KEY_EXCLUDED = "excluded_apps"
const val KEY_HINTS = "dismissed_hints"
const val KEY_PRIVATE_DNS = "dismissed_private_dns"
} }
} }
@@ -1,6 +1,13 @@
package cc.skysparkle.sparkledns package cc.skysparkle.sparkledns
import android.content.Context import android.content.Context
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.Request
import java.io.File
import java.io.IOException
import java.util.concurrent.TimeUnit
data class DohProvider( data class DohProvider(
val id: String, val id: String,
@@ -8,25 +15,148 @@ data class DohProvider(
val url: String, val url: String,
val bootstrap: List<String> = emptyList(), val bootstrap: List<String> = emptyList(),
val http3: Boolean = false, val http3: Boolean = false,
val policy: String? = null,
val donate: String? = null,
) )
object Providers { object Providers {
const val CUSTOM_ID = "custom" const val CUSTOM_ID = "custom"
const val DEFAULT_ID = "skysparkle"
val list = listOf( // Shipped with the app and used until the list from the repository is downloaded
DohProvider("skysparkle", "SkySparkle", "https://blog.skysparkle.cc/dns-query", http3 = true), val builtIn = listOf(
DohProvider("cloudflare", "Cloudflare", "https://cloudflare-dns.com/dns-query", listOf("1.1.1.1", "1.0.0.1")), DohProvider(
DohProvider("google", "Google", "https://dns.google/dns-query", listOf("8.8.8.8", "8.8.4.4")), "skysparkle", "SkySparkle", "https://blog.skysparkle.cc/dns-query",
DohProvider("quad9", "Quad9", "https://dns.quad9.net/dns-query", listOf("9.9.9.9", "149.112.112.112")), http3 = true, policy = "https://skysparkle.cc/privacy?lang=en",
DohProvider("adguard", "AdGuard", "https://dns.adguard-dns.com/dns-query", listOf("94.140.14.14", "94.140.15.15")), ),
DohProvider("mullvad", "Mullvad", "https://dns.mullvad.net/dns-query", listOf("194.242.2.2")), DohProvider(
"quad9", "Quad9", "https://dns.quad9.net/dns-query", listOf("9.9.9.9", "149.112.112.112"),
policy = "https://quad9.net/service/privacy/",
donate = "https://quad9.net/donate/",
),
DohProvider(
"digitale-gesellschaft", "Digitale Gesellschaft", "https://dns.digitale-gesellschaft.ch/dns-query",
listOf("185.95.218.42", "185.95.218.43"), http3 = true,
policy = "https://www.digitale-gesellschaft.ch/dns/",
donate = "https://www.digitale-gesellschaft.ch/uber-uns/unterstuetzer-werden/",
),
DohProvider(
"uncensoreddns", "UncensoredDNS", "https://anycast.uncensoreddns.org/dns-query", listOf("91.239.100.100"),
policy = "https://blog.uncensoreddns.org/faq/",
),
DohProvider(
"ffmuc", "Freifunk München", "https://doh.ffmuc.net/dns-query",
listOf("5.1.66.255", "185.150.99.255"), http3 = true,
policy = "https://ffmuc.net/dns-privacy/",
donate = "https://spende.ffmuc.net/",
),
) )
val default: DohProvider get() = list.first() val list: List<DohProvider> get() = ServerList.servers.value
// The project's own server stays the default whatever order the list uses
val default: DohProvider get() = list.firstOrNull { it.id == DEFAULT_ID } ?: list.first()
fun byId(id: String): DohProvider = list.firstOrNull { it.id == id } ?: default fun byId(id: String): DohProvider = list.firstOrNull { it.id == id } ?: default
} }
// The server list kept in the project repository, so servers can change without an app update
object ServerList {
const val SOURCE = "https://git.skysparkle.cc/kalarina/Sparkledns/raw/branch/main/servers/servers.txt"
private const val FILE = "servers.txt"
private const val MAX_BYTES = 64 * 1024
private const val MAX_SERVERS = 50
private val _servers = MutableStateFlow(Providers.builtIn)
val servers: StateFlow<List<DohProvider>> = _servers
@Volatile private var loaded = false
private val client by lazy {
Http.client.newBuilder()
.readTimeout(30, TimeUnit.SECONDS)
.build()
}
fun ensureLoaded(context: Context) {
if (loaded) return
synchronized(this) {
if (loaded) return
val cached = runCatching { File(context.filesDir, FILE).readText() }.getOrNull()
cached?.let(::parse)?.takeIf { it.isNotEmpty() }?.let { _servers.value = it }
loaded = true
}
}
// Blocking: call off the main thread. Returns the number of servers in the new list.
fun sync(context: Context): Int {
val request = Request.Builder().url(SOURCE).build()
val text = client.newCall(request).execute().use { response ->
if (!response.isSuccessful) throw IOException("HTTP ${response.code}")
val body = response.body ?: throw IOException("Empty response")
if (body.contentLength() > MAX_BYTES) throw IOException("List too large")
val bytes = body.byteStream().readNBytesCompat(MAX_BYTES + 1)
if (bytes.size > MAX_BYTES) throw IOException("List too large")
String(bytes, Charsets.UTF_8)
}
val parsed = parse(text)
if (parsed.isEmpty()) throw IOException("No servers found")
val file = File(context.filesDir, FILE)
val tmp = File(context.filesDir, "$FILE.tmp")
tmp.writeText(text)
if (!tmp.renameTo(file)) {
tmp.delete()
throw IOException("Cannot save list")
}
_servers.value = parsed
loaded = true
return parsed.size
}
// Format per line: Name | DoH URL | privacy policy URL | h3 (optional) | donation URL (optional).
// The optional columns are recognised by content, so either can be left out. See CONTRIBUTING.md.
fun parse(text: String): List<DohProvider> {
val builtInByHost = Providers.builtIn.associateBy { it.url.toHttpUrlOrNull()?.host }
val seen = HashSet<String>()
val result = ArrayList<DohProvider>()
for (raw in text.lineSequence()) {
val line = raw.trim()
if (line.isEmpty() || line.startsWith("#")) continue
val cols = line.split('|').map { it.trim() }
if (cols.size < 3) continue
val name = cols[0].take(40)
val url = cols[1].toHttpUrlOrNull()
val policy = cols[2].takeIf { it.toHttpUrlOrNull()?.isHttps == true }
if (name.isEmpty() || url == null || !url.isHttps) continue
val extras = cols.drop(3)
val http3 = extras.any { it.equals("h3", ignoreCase = true) }
val donate = extras.firstOrNull { it.toHttpUrlOrNull()?.isHttps == true }
// Shipped servers keep their address, id and links, so an edited list cannot redirect them
val pinned = builtInByHost[url.host]
val server = pinned
?: if (policy == null) continue
else DohProvider(url.host, name, cols[1], http3 = http3, policy = policy, donate = donate)
if (!seen.add(server.id)) continue
result += server
if (result.size >= MAX_SERVERS) break
}
return result
}
}
private fun java.io.InputStream.readNBytesCompat(limit: Int): ByteArray {
val out = java.io.ByteArrayOutputStream()
val buffer = ByteArray(8192)
var total = 0
while (total < limit) {
val read = read(buffer, 0, minOf(buffer.size, limit - total))
if (read < 0) break
out.write(buffer, 0, read)
total += read
}
return out.toByteArray()
}
fun parseIps(raw: String): List<String> = fun parseIps(raw: String): List<String> =
raw.split(',', ';', ' ').map { it.trim() }.filter { it.isNotEmpty() } raw.split(',', ';', ' ').map { it.trim() }.filter { it.isNotEmpty() }
@@ -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++
} }
} }
@@ -22,6 +22,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
@@ -29,19 +30,24 @@ 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
import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
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.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)
@@ -112,13 +118,23 @@ fun HintCard(
@DrawableRes icon: Int = R.drawable.ic_tab_info, @DrawableRes icon: Int = R.drawable.ic_tab_info,
tint: Color = MaterialTheme.colorScheme.onSurfaceVariant, tint: Color = MaterialTheme.colorScheme.onSurfaceVariant,
action: (@Composable () -> Unit)? = null, action: (@Composable () -> Unit)? = null,
onDismiss: (() -> Unit)? = null,
) { ) {
Card( Card(
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
colors = CardDefaults.cardColors(containerColor = tint.copy(alpha = 0.10f)), colors = CardDefaults.cardColors(containerColor = tint.copy(alpha = 0.10f)),
) { ) {
Row( Row(
modifier = Modifier.padding(start = 14.dp, end = if (action != null) 6.dp else 14.dp, top = 12.dp, bottom = 12.dp), modifier = Modifier.padding(
start = 14.dp,
end = when {
onDismiss != null -> 4.dp
action != null -> 6.dp
else -> 14.dp
},
top = if (onDismiss != null) 6.dp else 12.dp,
bottom = if (onDismiss != null) 6.dp else 12.dp,
),
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
) { ) {
Icon(painterResource(icon), contentDescription = null, tint = tint, modifier = Modifier.size(20.dp)) Icon(painterResource(icon), contentDescription = null, tint = tint, modifier = Modifier.size(20.dp))
@@ -130,6 +146,16 @@ fun HintCard(
modifier = Modifier.weight(1f), modifier = Modifier.weight(1f),
) )
action?.invoke() action?.invoke()
if (onDismiss != null) {
IconButton(onClick = onDismiss, modifier = Modifier.size(40.dp)) {
Icon(
painterResource(R.drawable.ic_close),
contentDescription = stringResource(R.string.dismiss),
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(18.dp),
)
}
}
} }
} }
} }
@@ -169,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}%"
Binary file not shown.

Before

Width:  |  Height:  |  Size: 184 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 124 KiB

+10
View File
@@ -0,0 +1,10 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="256"
android:viewportHeight="256">
<path
android:strokeColor="#FFFFFFFF"
android:strokeWidth="14"
android:pathData="M64,64L192,192M192,64L64,192" />
</vector>
+21
View File
@@ -0,0 +1,21 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="256"
android:viewportHeight="256">
<path
android:pathData="M128,38 A90,90 0 1,1 128,218 A90,90 0 1,1 128,38 Z"
android:strokeColor="#FFFFFFFF"
android:strokeWidth="11" />
<path
android:pathData="M156,99 C151,88 141,82 128,82 C112,82 100,91 100,105 C100,120 113,125 128,128 C144,131 158,137 158,153 C158,167 145,175 128,175 C113,175 101,168 97,156"
android:strokeColor="#FFFFFFFF"
android:strokeWidth="11"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M128,64 L128,82 M128,175 L128,193"
android:strokeColor="#FFFFFFFF"
android:strokeWidth="11"
android:strokeLineCap="round" />
</vector>
+14
View File
@@ -0,0 +1,14 @@
<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 L58,67 L58,120 C58,165 90,200 128,217 C166,200 198,165 198,120 L198,67 Z"
android:strokeColor="#FFFFFFFF"
android:strokeWidth="11"
android:strokeLineJoin="round" />
<path
android:fillColor="#FFFFFFFF"
android:pathData="M127.5,86.0 L135.8,111.6 L162.7,111.6 L140.9,127.4 L149.2,152.9 L127.5,137.1 L105.8,152.9 L114.1,127.4 L92.3,111.6 L119.2,111.6 Z" />
</vector>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 82 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

+102
View File
@@ -0,0 +1,102 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="status_on">Geschützt</string>
<string name="status_off">Getrennt</string>
<string name="via">über %1$s</string>
<string name="connect">Verbinden</string>
<string name="disconnect">Trennen</string>
<string name="servers">DNS-over-HTTPS-Server</string>
<string name="custom">Eigener Server</string>
<string name="custom_url">DoH-URL</string>
<string name="custom_bootstrap">Bootstrap-IP (optional, durch Kommas getrennt)</string>
<string name="invalid_url">Die URL muss mit https:// beginnen</string>
<string name="switch_to">Zu %1$s wechseln</string>
<string name="test">Server testen</string>
<string name="testing">Wird getestet…</string>
<string name="test_ok">Funktioniert über %1$s – erste Anfrage %2$d ms, Wiederholung %3$d ms</string>
<string name="http3">HTTP/3 (QUIC)</string>
<string name="http3_note">Android 14+. Mit HTTP/3 werden keine Bootstrap-IPs verwendet</string>
<string name="test_rcode">Server antwortete mit Fehlercode %1$d</string>
<string name="test_fail">Fehler: %1$s</string>
<string name="crash_title">Die App ist beim letzten Mal abgestürzt</string>
<string name="copy">Kopieren</string>
<string name="dismiss">Schließen</string>
<string name="hint">„Privates DNS“ ist in den Android-Einstellungen auf %1$s gesetzt. DNS geht deshalb dorthin und umgeht SparkleDNS. Stelle es auf „Automatisch“ oder „Aus“.</string>
<string name="notif_channel">VPN-Status</string>
<string name="notif_title">Geschützt über %1$s</string>
<string name="notif_text">DNS über HTTPS ist aktiv</string>
<string name="tab_home">Start</string>
<string name="tab_monitor">Monitor</string>
<string name="tab_apps">Apps</string>
<string name="tab_blocklist">Sperrliste</string>
<string name="tab_about">Info</string>
<string name="mon_queries">Anfragen</string>
<string name="mon_cached">Aus dem Cache</string>
<string name="mon_blocked">Blockiert</string>
<string name="mon_latency">Ø Latenz</string>
<string name="mon_ms">%1$d ms</string>
<string name="mon_all">Alle</string>
<string name="mon_errors">Fehler</string>
<string name="mon_search">Domain suchen</string>
<string name="mon_clear">Leeren</string>
<string name="mon_empty">Noch keine Anfragen. Verbinde dich und öffne eine beliebige Website.</string>
<string name="status_cached">Cache</string>
<string name="status_blocked">Blockiert</string>
<string name="status_failed">Fehler</string>
<string name="mon_block">Blockieren</string>
<string name="mon_unblock">Freigeben</string>
<string name="mon_blocked_added">%1$s zur Sperrliste hinzugefügt</string>
<string name="mon_unblocked">%1$s von der Sperrliste entfernt</string>
<string name="apps_hint">Ausgeschaltete Apps umgehen SparkleDNS und nutzen das normale DNS des Netzwerks.</string>
<string name="apps_search">Apps suchen</string>
<string name="apps_pending">Änderungen gelten nach dem erneuten Verbinden</string>
<string name="reconnect">Neu verbinden</string>
<string name="apps_loading">Wird geladen…</string>
<string name="apps_count">DNS umgehen: %1$d</string>
<string name="bl_note">Subdomains werden ebenfalls blockiert. Hosts-, reine Domain-, AdBlock- und dnsmasq-Listen werden unterstützt. Änderungen gelten sofort.</string>
<string name="bl_my">Meine Domains</string>
<string name="bl_domain_hint">example.com</string>
<string name="add">Hinzufügen</string>
<string name="bl_invalid">Ungültige Domain</string>
<string name="bl_empty_custom">Noch keine Domains</string>
<string name="delete">Löschen</string>
<string name="bl_lists">Listen</string>
<string name="bl_update_all">Alle aktualisieren</string>
<string name="bl_updating">Wird aktualisiert…</string>
<string name="bl_list_url">Listen-URL</string>
<string name="bl_list_info">%1$s Domains · %2$s</string>
<string name="bl_presets">Beliebte Listen</string>
<string name="bl_download_failed">Download fehlgeschlagen: %1$s</string>
<string name="about_desc">DNS-Anfragen verschlüsseln, ohne den gesamten Verkehr über ein VPN zu leiten.</string>
<string name="about_version">Version</string>
<string name="about_protocol">Protokoll</string>
<string name="about_http3_yes">Auf diesem Gerät unterstützt</string>
<string name="about_http3_no">Benötigt Android 14+, HTTP/2 wird verwendet</string>
<string name="group_social">Soziale Netzwerke &amp; Messenger</string>
<string name="group_video">Video</string>
<string name="group_audio">Musik &amp; Audio</string>
<string name="group_games">Spiele</string>
<string name="group_images">Fotos &amp; Bilder</string>
<string name="group_news">Nachrichten</string>
<string name="group_maps">Karten &amp; Navigation</string>
<string name="group_productivity">Produktivität</string>
<string name="group_other">Sonstiges</string>
<string name="group_system">System</string>
<string name="group_count">%1$d von %2$d über DNS</string>
<string name="about_privacy_policy">Datenschutzerklärung</string>
<string name="donate">Spenden</string>
<string name="licenses_title">Open-Source-Lizenzen</string>
<string name="licenses_hint">SparkleDNS basiert auf diesen Open-Source-Projekten. Tippe auf ein Projekt, um seine Seite zu öffnen.</string>
<string name="licenses_data">Sperrlisten-Daten (bei Bedarf geladen, nicht enthalten)</string>
<string name="license_view">Lizenz ansehen</string>
<string name="back">Zurück</string>
<string name="bl_total_label">Domains blockiert</string>
<string name="about_source">Quellcode</string>
<string name="open_settings">Einstellungen</string>
<string name="mon_no_match">Nichts passt zum Filter</string>
<string name="bl_title">Blockierung</string>
<string name="servers_update">Serverliste aktualisieren</string>
<string name="servers_updated">Serverliste aktualisiert</string>
<string name="servers_update_failed">Serverliste konnte nicht aktualisiert werden: %1$s</string>
<string name="no_browser">Keine App zum Öffnen dieses Links gefunden</string>
</resources>
+102
View File
@@ -0,0 +1,102 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="status_on">保護中</string>
<string name="status_off">未接続</string>
<string name="via">%1$s 経由</string>
<string name="connect">接続</string>
<string name="disconnect">切断</string>
<string name="servers">DNS-over-HTTPS サーバー</string>
<string name="custom">カスタムサーバー</string>
<string name="custom_url">DoH URL</string>
<string name="custom_bootstrap">ブートストラップ IP(任意、カンマ区切り)</string>
<string name="invalid_url">URL は https:// で始まる必要があります</string>
<string name="switch_to">%1$s に切り替え</string>
<string name="test">サーバーをテスト</string>
<string name="testing">テスト中…</string>
<string name="test_ok">%1$s で動作中 — 初回 %2$d ms、2回目 %3$d ms</string>
<string name="http3">HTTP/3 (QUIC)</string>
<string name="http3_note">Android 14 以降。HTTP/3 ではブートストラップ IP は使われません</string>
<string name="test_rcode">サーバーがエラーコード %1$d を返しました</string>
<string name="test_fail">エラー: %1$s</string>
<string name="crash_title">前回アプリがクラッシュしました</string>
<string name="copy">コピー</string>
<string name="dismiss">閉じる</string>
<string name="hint">Android の設定で「プライベート DNS」が %1$s に設定されているため、DNS はそちらへ送られ SparkleDNS を経由しません。「自動」または「OFF」に切り替えてください。</string>
<string name="notif_channel">VPN の状態</string>
<string name="notif_title">%1$s 経由で保護中</string>
<string name="notif_text">DNS over HTTPS が有効です</string>
<string name="tab_home">ホーム</string>
<string name="tab_monitor">モニター</string>
<string name="tab_apps">アプリ</string>
<string name="tab_blocklist">ブロックリスト</string>
<string name="tab_about">情報</string>
<string name="mon_queries">クエリ</string>
<string name="mon_cached">キャッシュから</string>
<string name="mon_blocked">ブロック済み</string>
<string name="mon_latency">平均遅延</string>
<string name="mon_ms">%1$d ms</string>
<string name="mon_all">すべて</string>
<string name="mon_errors">エラー</string>
<string name="mon_search">ドメインを検索</string>
<string name="mon_clear">クリア</string>
<string name="mon_empty">まだクエリはありません。接続して、任意のウェブサイトを開いてください。</string>
<string name="status_cached">キャッシュ</string>
<string name="status_blocked">ブロック</string>
<string name="status_failed">エラー</string>
<string name="mon_block">ブロック</string>
<string name="mon_unblock">ブロック解除</string>
<string name="mon_blocked_added">%1$s をブロックリストに追加しました</string>
<string name="mon_unblocked">%1$s をブロックリストから削除しました</string>
<string name="apps_hint">オフにしたアプリは SparkleDNS を経由せず、ネットワークの通常の DNS を使います。</string>
<string name="apps_search">アプリを検索</string>
<string name="apps_pending">変更は再接続後に反映されます</string>
<string name="reconnect">再接続</string>
<string name="apps_loading">読み込み中…</string>
<string name="apps_count">DNS をバイパス: %1$d</string>
<string name="bl_note">サブドメインもブロックされます。hosts、ドメインのみ、AdBlock、dnsmasq 形式のリストに対応しています。変更はすぐに反映されます。</string>
<string name="bl_my">マイドメイン</string>
<string name="bl_domain_hint">example.com</string>
<string name="add">追加</string>
<string name="bl_invalid">無効なドメイン</string>
<string name="bl_empty_custom">まだドメインはありません</string>
<string name="delete">削除</string>
<string name="bl_lists">リスト</string>
<string name="bl_update_all">すべて更新</string>
<string name="bl_updating">更新中…</string>
<string name="bl_list_url">リストの URL</string>
<string name="bl_list_info">%1$s ドメイン · %2$s</string>
<string name="bl_presets">人気のリスト</string>
<string name="bl_download_failed">ダウンロードに失敗しました: %1$s</string>
<string name="about_desc">すべての通信をVPNに通さずに、DNSリクエストを暗号化します。</string>
<string name="about_version">バージョン</string>
<string name="about_protocol">プロトコル</string>
<string name="about_http3_yes">この端末で対応しています</string>
<string name="about_http3_no">Android 14 以降が必要です。HTTP/2 を使用します</string>
<string name="group_social">SNS とメッセージ</string>
<string name="group_video">動画</string>
<string name="group_audio">音楽とオーディオ</string>
<string name="group_games">ゲーム</string>
<string name="group_images">写真と画像</string>
<string name="group_news">ニュース</string>
<string name="group_maps">地図とナビ</string>
<string name="group_productivity">仕事効率化</string>
<string name="group_other">その他</string>
<string name="group_system">システム</string>
<string name="group_count">%2$d 件中 %1$d 件が DNS 経由</string>
<string name="about_privacy_policy">プライバシーポリシー</string>
<string name="donate">寄付する</string>
<string name="licenses_title">オープンソースライセンス</string>
<string name="licenses_hint">SparkleDNS は以下のオープンソースプロジェクトで作られています。タップするとプロジェクトのページを開きます。</string>
<string name="licenses_data">ブロックリストのデータ(必要なときにダウンロード、同梱なし)</string>
<string name="license_view">ライセンスを見る</string>
<string name="back">戻る</string>
<string name="bl_total_label">件のドメインをブロック</string>
<string name="about_source">ソースコード</string>
<string name="open_settings">設定</string>
<string name="mon_no_match">フィルターに一致するものはありません</string>
<string name="bl_title">ブロック</string>
<string name="servers_update">サーバーリストを更新</string>
<string name="servers_updated">サーバーリストを更新しました</string>
<string name="servers_update_failed">サーバーリストを更新できませんでした: %1$s</string>
<string name="no_browser">このリンクを開けるアプリがありません</string>
</resources>
+102
View File
@@ -0,0 +1,102 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="status_on">Apsaugota</string>
<string name="status_off">Atsijungta</string>
<string name="via">per %1$s</string>
<string name="connect">Prisijungti</string>
<string name="disconnect">Atsijungti</string>
<string name="servers">DNS-over-HTTPS serveris</string>
<string name="custom">Savas serveris</string>
<string name="custom_url">DoH URL</string>
<string name="custom_bootstrap">Bootstrap IP (neprivaloma, atskirti kableliais)</string>
<string name="invalid_url">URL turi prasidėti https://</string>
<string name="switch_to">Perjungti į %1$s</string>
<string name="test">Tikrinti serverį</string>
<string name="testing">Tikrinama…</string>
<string name="test_ok">Veikia per %1$s – pirma užklausa %2$d ms, pakartotinė %3$d ms</string>
<string name="http3">HTTP/3 (QUIC)</string>
<string name="http3_note">Android 14+. Su HTTP/3 bootstrap IP nenaudojami</string>
<string name="test_rcode">Serveris grąžino klaidos kodą %1$d</string>
<string name="test_fail">Klaida: %1$s</string>
<string name="crash_title">Praėjusį kartą programėlė užstrigo</string>
<string name="copy">Kopijuoti</string>
<string name="dismiss">Uždaryti</string>
<string name="hint">Android nustatymuose „Privatus DNS“ nustatytas į %1$s, todėl DNS siunčiamas ten ir apeina SparkleDNS. Perjunkite į „Automatinis“ arba „Išjungta“.</string>
<string name="notif_channel">VPN būsena</string>
<string name="notif_title">Apsaugota per %1$s</string>
<string name="notif_text">DNS per HTTPS įjungtas</string>
<string name="tab_home">Pradžia</string>
<string name="tab_monitor">Stebėjimas</string>
<string name="tab_apps">Programėlės</string>
<string name="tab_blocklist">Blokavimo sąrašas</string>
<string name="tab_about">Apie</string>
<string name="mon_queries">Užklausos</string>
<string name="mon_cached">Iš talpyklos</string>
<string name="mon_blocked">Užblokuota</string>
<string name="mon_latency">Vid. delsa</string>
<string name="mon_ms">%1$d ms</string>
<string name="mon_all">Visos</string>
<string name="mon_errors">Klaidos</string>
<string name="mon_search">Ieškoti domeno</string>
<string name="mon_clear">Išvalyti</string>
<string name="mon_empty">Užklausų dar nėra. Prisijunkite ir atidarykite bet kurią svetainę.</string>
<string name="status_cached">Talpykla</string>
<string name="status_blocked">Užblokuota</string>
<string name="status_failed">Klaida</string>
<string name="mon_block">Blokuoti</string>
<string name="mon_unblock">Atblokuoti</string>
<string name="mon_blocked_added">%1$s pridėtas į blokavimo sąrašą</string>
<string name="mon_unblocked">%1$s pašalintas iš blokavimo sąrašo</string>
<string name="apps_hint">Išjungtos programėlės apeina SparkleDNS ir naudoja įprastą tinklo DNS.</string>
<string name="apps_search">Ieškoti programėlių</string>
<string name="apps_pending">Pakeitimai įsigalios prisijungus iš naujo</string>
<string name="reconnect">Prisijungti iš naujo</string>
<string name="apps_loading">Įkeliama…</string>
<string name="apps_count">Apeina DNS: %1$d</string>
<string name="bl_note">Blokuojami ir subdomenai. Palaikomi hosts, paprastų domenų, AdBlock ir dnsmasq sąrašai. Pakeitimai įsigalioja iš karto.</string>
<string name="bl_my">Mano domenai</string>
<string name="bl_domain_hint">example.com</string>
<string name="add">Pridėti</string>
<string name="bl_invalid">Netinkamas domenas</string>
<string name="bl_empty_custom">Domenų dar nėra</string>
<string name="delete">Ištrinti</string>
<string name="bl_lists">Sąrašai</string>
<string name="bl_update_all">Atnaujinti visus</string>
<string name="bl_updating">Atnaujinama…</string>
<string name="bl_list_url">Sąrašo URL</string>
<string name="bl_list_info">%1$s domenų · %2$s</string>
<string name="bl_presets">Populiarūs sąrašai</string>
<string name="bl_download_failed">Atsisiųsti nepavyko: %1$s</string>
<string name="about_desc">Šifruokite DNS užklausas, nenukreipdami viso srauto per VPN.</string>
<string name="about_version">Versija</string>
<string name="about_protocol">Protokolas</string>
<string name="about_http3_yes">Palaikoma šiame įrenginyje</string>
<string name="about_http3_no">Reikia Android 14+, naudojamas HTTP/2</string>
<string name="group_social">Socialiniai tinklai ir žinutės</string>
<string name="group_video">Vaizdo įrašai</string>
<string name="group_audio">Muzika ir garsas</string>
<string name="group_games">Žaidimai</string>
<string name="group_images">Nuotraukos ir vaizdai</string>
<string name="group_news">Naujienos</string>
<string name="group_maps">Žemėlapiai ir navigacija</string>
<string name="group_productivity">Produktyvumas</string>
<string name="group_other">Kita</string>
<string name="group_system">Sistema</string>
<string name="group_count">%1$d iš %2$d per DNS</string>
<string name="about_privacy_policy">Privatumo politika</string>
<string name="donate">Paaukoti</string>
<string name="licenses_title">Atvirojo kodo licencijos</string>
<string name="licenses_hint">SparkleDNS sukurta naudojant šiuos atvirojo kodo projektus. Palieskite projektą, kad atidarytumėte jo puslapį.</string>
<string name="licenses_data">Blokavimo sąrašų duomenys (atsisiunčiami pagal poreikį, neįtraukti)</string>
<string name="license_view">Peržiūrėti licenciją</string>
<string name="back">Atgal</string>
<string name="bl_total_label">užblokuotų domenų</string>
<string name="about_source">Šaltinio kodas</string>
<string name="open_settings">Nustatymai</string>
<string name="mon_no_match">Filtro neatitinka niekas</string>
<string name="bl_title">Blokavimas</string>
<string name="servers_update">Atnaujinti serverių sąrašą</string>
<string name="servers_updated">Serverių sąrašas atnaujintas</string>
<string name="servers_update_failed">Nepavyko atnaujinti serverių sąrašo: %1$s</string>
<string name="no_browser">Nerasta programėlės šiai nuorodai atidaryti</string>
</resources>
+6 -2
View File
@@ -67,7 +67,7 @@
<string name="bl_list_info">%1$s доменов · %2$s</string> <string name="bl_list_info">%1$s доменов · %2$s</string>
<string name="bl_presets">Популярные списки</string> <string name="bl_presets">Популярные списки</string>
<string name="bl_download_failed">Ошибка загрузки: %1$s</string> <string name="bl_download_failed">Ошибка загрузки: %1$s</string>
<string name="about_desc">Шифрованный DNS через HTTPS и HTTP/3 для всего устройства. Через локальный VPN идёт только DNS, остальной трафик не затрагивается.</string> <string name="about_desc">Шифруйте DNS-запросы, не пропуская весь трафик через VPN.</string>
<string name="about_version">Версия</string> <string name="about_version">Версия</string>
<string name="about_protocol">Протокол</string> <string name="about_protocol">Протокол</string>
<string name="about_http3_yes">Поддерживается на этом устройстве</string> <string name="about_http3_yes">Поддерживается на этом устройстве</string>
@@ -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>
@@ -94,5 +95,8 @@
<string name="open_settings">Настройки</string> <string name="open_settings">Настройки</string>
<string name="mon_no_match">Ничего не найдено</string> <string name="mon_no_match">Ничего не найдено</string>
<string name="bl_title">Блокировка</string> <string name="bl_title">Блокировка</string>
<string name="about_license">Лицензия</string> <string name="servers_update">Обновить список серверов</string>
<string name="servers_updated">Список серверов обновлён</string>
<string name="servers_update_failed">Не удалось обновить список серверов: %1$s</string>
<string name="no_browser">Не найдено приложение, чтобы открыть ссылку</string>
</resources> </resources>
+102
View File
@@ -0,0 +1,102 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="status_on">已保护</string>
<string name="status_off">未连接</string>
<string name="via">通过 %1$s</string>
<string name="connect">连接</string>
<string name="disconnect">断开</string>
<string name="servers">DNS-over-HTTPS 服务器</string>
<string name="custom">自定义服务器</string>
<string name="custom_url">DoH URL</string>
<string name="custom_bootstrap">引导 IP(可选,用逗号分隔)</string>
<string name="invalid_url">URL 必须以 https:// 开头</string>
<string name="switch_to">切换到 %1$s</string>
<string name="test">测试服务器</string>
<string name="testing">正在测试…</string>
<string name="test_ok">可通过 %1$s 使用——首次请求 %2$d 毫秒,重复请求 %3$d 毫秒</string>
<string name="http3">HTTP/3 (QUIC)</string>
<string name="http3_note">需要 Android 14 及以上。使用 HTTP/3 时不使用引导 IP</string>
<string name="test_rcode">服务器返回错误代码 %1$d</string>
<string name="test_fail">错误:%1$s</string>
<string name="crash_title">应用上次崩溃了</string>
<string name="copy">复制</string>
<string name="dismiss">关闭</string>
<string name="hint">Android 设置中的“私人 DNS”被设为 %1$s,因此 DNS 会发往那里并绕过 SparkleDNS。请将其切换为“自动”或“关闭”。</string>
<string name="notif_channel">VPN 状态</string>
<string name="notif_title">已通过 %1$s 保护</string>
<string name="notif_text">DNS over HTTPS 已启用</string>
<string name="tab_home">首页</string>
<string name="tab_monitor">监控</string>
<string name="tab_apps">应用</string>
<string name="tab_blocklist">屏蔽列表</string>
<string name="tab_about">关于</string>
<string name="mon_queries">查询</string>
<string name="mon_cached">来自缓存</string>
<string name="mon_blocked">已屏蔽</string>
<string name="mon_latency">平均延迟</string>
<string name="mon_ms">%1$d 毫秒</string>
<string name="mon_all">全部</string>
<string name="mon_errors">错误</string>
<string name="mon_search">搜索域名</string>
<string name="mon_clear">清除</string>
<string name="mon_empty">还没有查询。连接后打开任意网站即可。</string>
<string name="status_cached">缓存</string>
<string name="status_blocked">已屏蔽</string>
<string name="status_failed">错误</string>
<string name="mon_block">屏蔽</string>
<string name="mon_unblock">取消屏蔽</string>
<string name="mon_blocked_added">已将 %1$s 加入屏蔽列表</string>
<string name="mon_unblocked">已将 %1$s 从屏蔽列表移除</string>
<string name="apps_hint">关闭的应用会绕过 SparkleDNS,使用网络的常规 DNS。</string>
<string name="apps_search">搜索应用</string>
<string name="apps_pending">更改将在重新连接后生效</string>
<string name="reconnect">重新连接</string>
<string name="apps_loading">正在加载…</string>
<string name="apps_count">绕过 DNS:%1$d</string>
<string name="bl_note">子域名也会被屏蔽。支持 hosts、纯域名、AdBlock 和 dnsmasq 格式的列表。更改立即生效。</string>
<string name="bl_my">我的域名</string>
<string name="bl_domain_hint">example.com</string>
<string name="add">添加</string>
<string name="bl_invalid">域名无效</string>
<string name="bl_empty_custom">还没有域名</string>
<string name="delete">删除</string>
<string name="bl_lists">列表</string>
<string name="bl_update_all">全部更新</string>
<string name="bl_updating">正在更新…</string>
<string name="bl_list_url">列表 URL</string>
<string name="bl_list_info">%1$s 个域名 · %2$s</string>
<string name="bl_presets">热门列表</string>
<string name="bl_download_failed">下载失败:%1$s</string>
<string name="about_desc">加密 DNS 请求,无需让全部流量经过 VPN。</string>
<string name="about_version">版本</string>
<string name="about_protocol">协议</string>
<string name="about_http3_yes">此设备支持</string>
<string name="about_http3_no">需要 Android 14 及以上,当前使用 HTTP/2</string>
<string name="group_social">社交与通讯</string>
<string name="group_video">视频</string>
<string name="group_audio">音乐与音频</string>
<string name="group_games">游戏</string>
<string name="group_images">照片与图片</string>
<string name="group_news">新闻</string>
<string name="group_maps">地图与导航</string>
<string name="group_productivity">效率</string>
<string name="group_other">其他</string>
<string name="group_system">系统</string>
<string name="group_count">%2$d 个中有 %1$d 个经过 DNS</string>
<string name="about_privacy_policy">隐私政策</string>
<string name="donate">捐赠</string>
<string name="licenses_title">开源许可</string>
<string name="licenses_hint">SparkleDNS 使用了以下开源项目。点按项目可打开其页面。</string>
<string name="licenses_data">屏蔽列表数据(按需下载,未内置)</string>
<string name="license_view">查看许可</string>
<string name="back">返回</string>
<string name="bl_total_label">个域名已屏蔽</string>
<string name="about_source">源代码</string>
<string name="open_settings">设置</string>
<string name="mon_no_match">没有符合筛选条件的内容</string>
<string name="bl_title">屏蔽</string>
<string name="servers_update">更新服务器列表</string>
<string name="servers_updated">服务器列表已更新</string>
<string name="servers_update_failed">无法更新服务器列表:%1$s</string>
<string name="no_browser">没有可以打开此链接的应用</string>
</resources>
+6 -2
View File
@@ -68,7 +68,7 @@
<string name="bl_list_info">%1$s domains · %2$s</string> <string name="bl_list_info">%1$s domains · %2$s</string>
<string name="bl_presets">Popular lists</string> <string name="bl_presets">Popular lists</string>
<string name="bl_download_failed">Download failed: %1$s</string> <string name="bl_download_failed">Download failed: %1$s</string>
<string name="about_desc">Encrypted DNS over HTTPS and HTTP/3 for the whole device. Only DNS goes through the local VPN, all other traffic is untouched.</string> <string name="about_desc">Encrypt DNS requests without routing all your traffic through a VPN.</string>
<string name="about_version">Version</string> <string name="about_version">Version</string>
<string name="about_protocol">Protocol</string> <string name="about_protocol">Protocol</string>
<string name="about_http3_yes">Supported on this device</string> <string name="about_http3_yes">Supported on this device</string>
@@ -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>
@@ -95,5 +96,8 @@
<string name="open_settings">Settings</string> <string name="open_settings">Settings</string>
<string name="mon_no_match">Nothing matches the filter</string> <string name="mon_no_match">Nothing matches the filter</string>
<string name="bl_title">Blocking</string> <string name="bl_title">Blocking</string>
<string name="about_license">License</string> <string name="servers_update">Update server list</string>
<string name="servers_updated">Server list updated</string>
<string name="servers_update_failed">Couldn\'t update the server list: %1$s</string>
<string name="no_browser">No app found to open this link</string>
</resources> </resources>
@@ -0,0 +1,49 @@
package cc.skysparkle.sparkledns
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class BlocklistMatchTest {
private fun set(vararg domains: String) = domains.map { DomainHash.of(it) }.sorted().toLongArray()
@Test
fun blocksDomainsAndTheirSubdomains() {
val lists = set("ads.example.com")
val custom = set("tracker.net")
assertTrue(isBlockedIn("ads.example.com", lists, custom))
assertTrue(isBlockedIn("a.b.ads.example.com.", lists, custom))
assertTrue(isBlockedIn("cdn.tracker.net", lists, custom))
assertFalse(isBlockedIn("example.com", lists, custom))
assertFalse(isBlockedIn("badads.example.com", lists, custom))
assertFalse(isBlockedIn("tracker.network", lists, custom))
assertFalse(isBlockedIn("ads.example.com", LongArray(0), LongArray(0)))
}
@Test
fun mergesSortedListsWithoutDuplicates() {
val a = longArrayOf(-5, 1, 4, 9)
val b = longArrayOf(1, 2, 9, 12)
val c = longArrayOf(3)
assertArrayEquals(longArrayOf(-5, 1, 2, 3, 4, 9, 12), mergeSorted(listOf(a, b, c, LongArray(0))))
assertArrayEquals(LongArray(0), mergeSorted(emptyList()))
assertArrayEquals(a, mergeSorted(listOf(a)))
}
@Test
fun sortsInputsThatAreNotSorted() {
assertArrayEquals(longArrayOf(1, 2, 3, 7), mergeSorted(listOf(longArrayOf(3, 1, 3), longArrayOf(7, 2))))
}
@Test
fun countsEntriesInBothSetsOnce() {
assertEquals(5, unionSize(longArrayOf(1, 2, 3, 4), longArrayOf(2, 5)))
assertEquals(2, unionSize(LongArray(0), longArrayOf(2, 5)))
assertEquals(4, unionSize(longArrayOf(1, 2, 3, 4), LongArray(0)))
}
}
@@ -0,0 +1,53 @@
package cc.skysparkle.sparkledns
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
class BlocklistParserTest {
@Test
fun understandsCommonListFormats() {
assertEquals("ads.example.com", BlocklistParser.parseLine("0.0.0.0 ads.example.com"))
assertEquals("ads.example.com", BlocklistParser.parseLine("127.0.0.1\tads.example.com # tracker"))
assertEquals("ads.example.com", BlocklistParser.parseLine("ads.example.com"))
assertEquals("tracker.example", BlocklistParser.parseLine("||tracker.example^"))
assertEquals("tracker.example", BlocklistParser.parseLine("||tracker.example^\$third-party"))
assertEquals("bad.example", BlocklistParser.parseLine("address=/bad.example/0.0.0.0"))
assertEquals("bad.example", BlocklistParser.parseLine("server=/bad.example/"))
assertEquals("bad.example", BlocklistParser.parseLine("local-zone: \"bad.example\" always_nxdomain"))
}
@Test
fun skipsCommentsRulesAndLocalNames() {
assertNull(BlocklistParser.parseLine(""))
assertNull(BlocklistParser.parseLine("# comment"))
assertNull(BlocklistParser.parseLine("! adblock comment"))
assertNull(BlocklistParser.parseLine("[Adblock Plus 2.0]"))
assertNull(BlocklistParser.parseLine("@@||allowed.example^"))
assertNull(BlocklistParser.parseLine("example.com##.banner"))
assertNull(BlocklistParser.parseLine("127.0.0.1 localhost"))
assertNull(BlocklistParser.parseLine("0.0.0.0 0.0.0.0"))
assertNull(BlocklistParser.parseLine("::1 ip6-localhost"))
}
@Test
fun normalizesUserInput() {
assertEquals("example.com", BlocklistParser.normalize(" HTTPS://Example.COM/path?q=1 "))
assertEquals("example.com", BlocklistParser.normalize("*.example.com"))
assertEquals("example.com", BlocklistParser.normalize("example.com."))
assertEquals("example.com", BlocklistParser.normalize("example.com:8080"))
assertNull(BlocklistParser.normalize("localhost"))
assertNull(BlocklistParser.normalize("bad..example"))
assertNull(BlocklistParser.normalize("-bad.example"))
assertNull(BlocklistParser.normalize("exa mple.com"))
assertNull(BlocklistParser.normalize("192.168.0.1"))
}
@Test
fun parentHashMatchesHashOfTheSuffix() {
val name = "a.b.example.com"
assertEquals(DomainHash.of("example.com"), DomainHash.of(name, name.indexOf("example")))
assertEquals(DomainHash.of(name), DomainHash.of(name, 0))
}
}
@@ -0,0 +1,115 @@
package cc.skysparkle.sparkledns
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Test
class DnsCacheTest {
private var now = 1_000_000L
private val cache = DnsCache(clock = { now })
@Test
fun answersWithTheNewQueryIdAndAgedTtl() {
val first = DnsMessage.buildQuery("example.com")
cache.put(first, dnsResponse(first, ttls = listOf(300)))
now += 10_000
val second = DnsMessage.buildQuery("EXAMPLE.com")
val hit = requireNotNull(cache.get(second))
assertEquals(second[0], hit[0])
assertEquals(second[1], hit[1])
assertEquals(290L, answerTtl(hit))
}
@Test
fun expiresWithTheShortestTtl() {
val query = DnsMessage.buildQuery("example.com")
cache.put(query, dnsResponse(query, ttls = listOf(300, 60)))
now += 59_000
val hit = requireNotNull(cache.get(query))
assertEquals(241L, answerTtl(hit, 0))
assertEquals(1L, answerTtl(hit, 1))
now += 1_000
assertNull(cache.get(query))
}
@Test
fun capsTtlAtOneHour() {
val query = DnsMessage.buildQuery("example.com")
cache.put(query, dnsResponse(query, ttls = listOf(86_400)))
now += 3_599_000
assertNotNull(cache.get(query))
now += 1_000
assertNull(cache.get(query))
}
@Test
fun keepsEmptyNxdomainForThirtySeconds() {
val query = DnsMessage.buildQuery("nothing.example")
cache.put(query, dnsResponse(query, rcode = 3, ttls = emptyList()))
now += 29_000
assertEquals(3, DnsMessage.rcode(requireNotNull(cache.get(query))))
now += 1_000
assertNull(cache.get(query))
}
@Test
fun skipsFailuresTruncatedAndZeroTtlAnswers() {
val failed = DnsMessage.buildQuery("a.example")
val truncated = DnsMessage.buildQuery("b.example")
val zero = DnsMessage.buildQuery("c.example")
cache.put(failed, dnsResponse(failed, rcode = 2))
cache.put(truncated, dnsResponse(truncated, truncated = true))
cache.put(zero, dnsResponse(zero, ttls = listOf(0)))
assertNull(cache.get(failed))
assertNull(cache.get(truncated))
assertNull(cache.get(zero))
}
@Test
fun leavesTheOptRecordAlone() {
val query = DnsMessage.buildQuery("example.com")
val response = dnsResponse(query, withOpt = true)
cache.put(query, response)
now += 10_000
val hit = requireNotNull(cache.get(query))
assertArrayEquals(response.copyOfRange(response.size - 11, response.size), hit.copyOfRange(hit.size - 11, hit.size))
}
@Test
fun separatesRecordTypes() {
val a = DnsMessage.buildQuery("example.com", type = 1)
val aaaa = DnsMessage.buildQuery("example.com", type = 28)
cache.put(a, dnsResponse(a))
assertNull(cache.get(aaaa))
}
@Test
fun evictsTheLeastRecentlyUsedEntry() {
val small = DnsCache(maxEntries = 2, clock = { now })
val a = DnsMessage.buildQuery("a.example")
val b = DnsMessage.buildQuery("b.example")
val c = DnsMessage.buildQuery("c.example")
small.put(a, dnsResponse(a))
small.put(b, dnsResponse(b))
small.get(a)
small.put(c, dnsResponse(c))
assertNotNull(small.get(a))
assertNull(small.get(b))
assertNotNull(small.get(c))
}
}
@@ -0,0 +1,69 @@
package cc.skysparkle.sparkledns
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Test
class DnsMessageTest {
@Test
fun questionIsReadBackLowercase() {
val question = requireNotNull(DnsMessage.question(DnsMessage.buildQuery("WWW.Example.COM.", type = 28)))
assertEquals("www.example.com", question.name)
assertEquals(28, question.type)
}
@Test
fun questionRejectsCompressedOrCutNames() {
val query = DnsMessage.buildQuery("example.com")
val compressed = query.copyOf(12) + byteArrayOf(0xC0.toByte(), 0x0C, 0, 1, 0, 1)
assertNull(DnsMessage.question(compressed))
assertNull(DnsMessage.question(query.copyOf(16)))
assertNull(DnsMessage.question(query.copyOf(11)))
}
@Test
fun withIdCopiesTheQueryId() {
val query = DnsMessage.buildQuery("example.com")
val response = dnsResponse(query)
response[0] = (query[0] + 1).toByte()
val fixed = DnsMessage.withId(response, query)
assertEquals(query[0], fixed[0])
assertEquals(query[1], fixed[1])
assertSame(fixed, DnsMessage.withId(fixed, query))
}
@Test
fun errorReplyKeepsOnlyTheQuestion() {
val query = DnsMessage.buildQuery("example.com")
// An EDNS OPT record in the additional section must not be echoed back
val withOpt = query.copyOf().also { it[11] = 1 } + byteArrayOf(0, 0, 41, 0x10, 0, 0, 0, 0, 0, 0, 0)
val reply = requireNotNull(DnsMessage.errorReply(withOpt, DnsMessage.RCODE_NXDOMAIN))
assertEquals(query.size, reply.size)
assertTrue(DnsMessage.isResponse(reply))
assertEquals(DnsMessage.RCODE_NXDOMAIN, DnsMessage.rcode(reply))
assertEquals(1, u16(reply, 4))
assertArrayEquals(ByteArray(6), reply.copyOfRange(6, 12))
assertArrayEquals(query.copyOfRange(12, query.size), reply.copyOfRange(12, reply.size))
}
@Test
fun servfailAndResponseFlags() {
val query = DnsMessage.buildQuery("example.com")
assertFalse(DnsMessage.isResponse(query))
assertEquals(DnsMessage.RCODE_SERVFAIL, DnsMessage.rcode(requireNotNull(DnsMessage.servfail(query))))
assertNull(DnsMessage.servfail(ByteArray(5)))
assertEquals(-1, DnsMessage.rcode(ByteArray(2)))
}
}
@@ -0,0 +1,77 @@
package cc.skysparkle.sparkledns
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
class PacketTest {
private val client = byteArrayOf(10, 111, 222.toByte(), 1)
private val server = byteArrayOf(10, 111, 222.toByte(), 2)
@Test
fun parsesDnsQuery() {
val query = DnsMessage.buildQuery("example.com")
val packet = ipv4Udp(client, server, 40000, 53, query)
val parsed = requireNotNull(Packet.parseDnsQuery(packet, packet.size))
assertArrayEquals(query, parsed.payload)
assertArrayEquals(client, parsed.srcIp)
assertArrayEquals(server, parsed.dstIp)
assertEquals(40000, parsed.srcPort)
assertEquals(53, parsed.dstPort)
}
@Test
fun usesOnlyTheBytesThatWereRead() {
val query = DnsMessage.buildQuery("example.com")
val packet = ipv4Udp(client, server, 40000, 53, query)
val buffer = packet + ByteArray(100) { 0x55 }
val parsed = requireNotNull(Packet.parseDnsQuery(buffer, packet.size))
assertArrayEquals(query, parsed.payload)
}
@Test
fun ignoresEverythingThatIsNotADnsQuery() {
val query = DnsMessage.buildQuery("example.com")
val otherPort = ipv4Udp(client, server, 40000, 443, query)
val tcp = ipv4Udp(client, server, 40000, 53, query, protocol = 6)
val fragment = ipv4Udp(client, server, 40000, 53, query, flagsAndOffset = 0x2000)
val ipv6 = ipv4Udp(client, server, 40000, 53, query).also { it[0] = 0x60 }
assertNull(Packet.parseDnsQuery(otherPort, otherPort.size))
assertNull(Packet.parseDnsQuery(tcp, tcp.size))
assertNull(Packet.parseDnsQuery(fragment, fragment.size))
assertNull(Packet.parseDnsQuery(ipv6, ipv6.size))
assertNull(Packet.parseDnsQuery(otherPort, 27))
}
@Test
fun replySwapsEndpointsAndHasValidChecksums() {
val query = DnsMessage.buildQuery("example.com")
val packet = ipv4Udp(client, server, 40000, 53, query)
val parsed = requireNotNull(Packet.parseDnsQuery(packet, packet.size))
// Odd length exercises the checksum padding
val answer = dnsResponse(query) + byteArrayOf(7)
val reply = Packet.buildReply(parsed, answer)
assertEquals(28 + answer.size, reply.size)
assertEquals(0x45, reply[0].toInt())
assertEquals(reply.size, u16(reply, 2))
assertArrayEquals(server, reply.copyOfRange(12, 16))
assertArrayEquals(client, reply.copyOfRange(16, 20))
assertEquals(53, u16(reply, 20))
assertEquals(40000, u16(reply, 22))
assertArrayEquals(answer, reply.copyOfRange(28, reply.size))
assertEquals(0xFFFF, onesSum(reply.copyOfRange(0, 20)))
val udp = reply.copyOfRange(20, reply.size)
val pseudo = reply.copyOfRange(12, 20) + byteArrayOf(0, 17) + byteArrayOf((udp.size shr 8).toByte(), udp.size.toByte())
assertEquals(0xFFFF, onesSum(pseudo, udp))
}
}
@@ -0,0 +1,71 @@
package cc.skysparkle.sparkledns
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Test
class ServerListTest {
@Test
fun readsAllColumns() {
val list = ServerList.parse(
"""
# Name | URL | policy | h3 | donate
Example DNS | https://dns.example.org/dns-query | https://example.org/privacy | h3 | https://example.org/donate
Other | https://doh.other.net/q | https://other.net/policy | https://other.net/give
""".trimIndent()
)
assertEquals(2, list.size)
val first = list[0]
assertEquals("dns.example.org", first.id)
assertEquals("Example DNS", first.name)
assertEquals("https://dns.example.org/dns-query", first.url)
assertEquals("https://example.org/privacy", first.policy)
assertEquals("https://example.org/donate", first.donate)
assertTrue(first.http3)
val second = list[1]
assertFalse(second.http3)
assertEquals("https://other.net/give", second.donate)
}
@Test
fun skipsServersWithoutHttpsOrPolicy() {
val list = ServerList.parse(
"""
Plain | http://dns.example.org/dns-query | https://example.org/privacy
No policy | https://dns.example.org/dns-query | not a url
Too short | https://dns.example.org/dns-query
""".trimIndent()
)
assertTrue(list.isEmpty())
}
@Test
fun shippedServersCannotBeRedirected() {
val quad9 = Providers.builtIn.first { it.id == "quad9" }
val list = ServerList.parse("Fake | https://dns.quad9.net/elsewhere | https://evil.example/policy")
assertSame(quad9, list.single())
}
@Test
fun dropsDuplicatesTrimsNamesAndCapsTheList() {
val long = "N".repeat(60)
val lines = (1..60).joinToString("\n") { "$long | https://dns$it.example/q | https://example.org/p" } +
"\nDuplicate | https://dns1.example/q | https://example.org/p"
val list = ServerList.parse(lines)
assertEquals(50, list.size)
assertEquals(40, list[0].name.length)
assertEquals(list.size, list.map { it.id }.toSet().size)
assertNull(list.firstOrNull { it.name == "Duplicate" })
}
}
@@ -0,0 +1,78 @@
package cc.skysparkle.sparkledns
import java.io.ByteArrayOutputStream
// Hand-built DNS messages and IPv4/UDP packets for the tests
internal fun dnsResponse(
query: ByteArray,
rcode: Int = 0,
ttls: List<Int> = listOf(300),
withOpt: Boolean = false,
truncated: Boolean = false,
): ByteArray {
val questionEnd = requireNotNull(skipName(query, 12)) + 4
val out = ByteArrayOutputStream()
out.write(query, 0, 2)
out.write(0x81 or if (truncated) 0x02 else 0) // QR + RD (+ TC)
out.write(0x80 or rcode) // RA + RCODE
out.write(byteArrayOf(0, 1, 0, ttls.size.toByte(), 0, 0, 0, (if (withOpt) 1 else 0).toByte()))
out.write(query, 12, questionEnd - 12)
for (ttl in ttls) {
out.write(byteArrayOf(0xC0.toByte(), 0x0C, 0, 1, 0, 1))
out.write(be32(ttl))
out.write(byteArrayOf(0, 4, 93, 184.toByte(), 216.toByte(), 34))
}
if (withOpt) {
// Root name, type OPT, UDP size 4096, extended flags with the DO bit, no data
out.write(byteArrayOf(0, 0, 41, 0x10, 0, 0, 0, 0x80.toByte(), 0, 0, 0))
}
return out.toByteArray()
}
internal fun ipv4Udp(
src: ByteArray,
dst: ByteArray,
srcPort: Int,
dstPort: Int,
payload: ByteArray,
protocol: Int = 17,
flagsAndOffset: Int = 0,
): ByteArray {
val p = ByteArray(28 + payload.size)
p[0] = 0x45
put16(p, 2, p.size)
put16(p, 6, flagsAndOffset)
p[8] = 64
p[9] = protocol.toByte()
src.copyInto(p, 12)
dst.copyInto(p, 16)
put16(p, 20, srcPort)
put16(p, 22, dstPort)
put16(p, 24, 8 + payload.size)
payload.copyInto(p, 28)
return p
}
// One's complement sum of 16-bit words; a correct checksum makes it 0xFFFF
internal fun onesSum(vararg parts: ByteArray): Int {
var sum = 0L
for (part in parts) {
var i = 0
while (i + 1 < part.size) {
sum += u16(part, i)
i += 2
}
if (i < part.size) sum += (part[i].toInt() and 0xFF) shl 8
}
while (sum shr 16 != 0L) sum = (sum and 0xFFFF) + (sum shr 16)
return sum.toInt()
}
internal fun be32(value: Int) = ByteArray(4).also { put32(it, 0, value) }
// TTL field of the n-th answer of a message built by dnsResponse
internal fun answerTtl(message: ByteArray, index: Int = 0): Long {
val first = requireNotNull(skipName(message, 12)) + 4
return u32(message, first + index * 16 + 6)
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.3 KiB

@@ -0,0 +1,5 @@
• Jetzt auch auf Deutsch, Japanisch, Litauisch und Chinesisch
• Unabhängige Server: Digitale Gesellschaft, UncensoredDNS, Freifunk München. Cloudflare, Google, AdGuard und Mullvad entfernt
• Serverliste lässt sich aus dem Projekt-Repository aktualisieren, jeder Server verlinkt seine Datenschutzerklärung
• Hinweise und Warnungen lassen sich mit ✕ schließen
• Aufgeräumter Info-Bildschirm
@@ -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,14 @@
<p>Schütze deine DNS-Anfragen mit verschlüsseltem DNS-over-HTTPS, während dein übriger Internetverkehr über die normale Verbindung läuft. SparkleDNS gibt dir die Kontrolle über DNS, ohne dein ganzes Gerät über einen VPN-Server zu leiten.</p>
<ul>
<li>Sende DNS-Anfragen per RFC 8484 an den DoH-Server deiner Wahl.</li>
<li>Prüfe Protokoll und Latenz eines Servers, bevor du dich verbindest.</li>
<li>Sieh Anfragen und Statistiken live, filtere die Aktivität und blockiere Domains mit einem Tippen.</li>
<li>Füge eigene Domainregeln oder Blocklisten per URL hinzu, inklusive der Vorlagen HaGeZi Pro++ und TIF.</li>
<li>Lass ausgewählte Apps den DNS-Tunnel umgehen.</li>
<li>Verbinde oder trenne mit einem Tippen oder über die Kachel in den Schnelleinstellungen.</li>
</ul>
<p>SparkleDNS erstellt einen lokalen VPN-Tunnel, der nur den DNS-Verkehr erfasst. DNS-Anfragen gehen an den gewählten DoH-Server, alles andere nutzt deine normale Verbindung. Wechselst du den Server während der Verbindung, startet der Tunnel automatisch neu. Keine Analysedienste und keine Google-Play-Dienste.</p>
<p>SparkleDNS ist ein schlanker DNS-Client für Android mit klarer Kontrolle über verschlüsseltes DNS und Domain-Blockierung. Installiere SparkleDNS und behalte deine DNS-Anfragen im Griff.</p>
@@ -0,0 +1 @@
DNS-Anfragen verschlüsseln, ohne den gesamten Verkehr über ein VPN zu leiten.
@@ -0,0 +1 @@
SparkleDNS
@@ -0,0 +1,5 @@
• Now in German, Japanese, Lithuanian and Chinese
• Independent servers: Digitale Gesellschaft, UncensoredDNS, Freifunk München. Cloudflare, Google, AdGuard and Mullvad removed
• Update the server list from the project repository; each server links to its privacy policy
• Hints and warnings can be closed with ✕
• Cleaner About screen
@@ -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
@@ -1,31 +1,14 @@
SparkleDNS encrypts every DNS lookup on your device with DNS-over-HTTPS (RFC 8484) and HTTP/3. It uses Android's VPN API only locally: just DNS requests go into the tunnel, all other traffic takes your normal connection, so speed and battery stay the same. <p>Protect your DNS requests with encrypted DNS-over-HTTPS, while your other internet traffic stays on its normal connection. SparkleDNS gives you control over DNS without routing your whole device through a VPN server.</p>
<b>Servers</b>
<ul> <ul>
<li>SkySparkle (default) with HTTP/3, run by the developer</li> <li>Send DNS queries to your chosen DoH server using RFC 8484.</li>
<li>Cloudflare, Google, Quad9, AdGuard, Mullvad</li> <li>Check server protocol and latency before you connect.</li>
<li>Any custom DoH server, with optional bootstrap IPs and HTTP/3</li> <li>See live queries and stats, filter activity, and block domains with a tap.</li>
<li>Add custom domain rules or blocklists by URL, including HaGeZi Pro++ and TIF presets.</li>
<li>Let selected apps bypass the DNS tunnel.</li>
<li>Connect or disconnect in one tap, or use the Quick Settings tile.</li>
</ul> </ul>
<b>Features</b> <p>SparkleDNS creates a local VPN tunnel to capture DNS traffic only. DNS requests go to your selected DoH server; everything else uses your regular connection. Switch servers while connected and the tunnel restarts automatically. No analytics or Google Play Services are included.</p>
<ul>
<li>One-tap connect, Quick Settings tile, Always-on VPN support</li>
<li>Live monitor: every query with its status and latency, filters, search and one-tap blocking</li>
<li>Per-app rules: apps grouped by category, chosen ones bypass SparkleDNS</li>
<li>Blocklists: your own domains plus hosts, plain domain, AdBlock and dnsmasq lists by URL, HaGeZi Pro++ and TIF one tap away. Subdomains are blocked too, changes apply instantly</li>
<li>Local DNS cache that honours TTLs</li>
<li>Server test showing the protocol (h3 or h2) and latency</li>
</ul>
<b>Privacy</b> <p>Choose SparkleDNS for a lightweight Android DNS client with clear controls over encrypted DNS and domain blocking. Install SparkleDNS and take control of your DNS requests.</p>
No analytics, no ads, no Google Play Services. The query log lives only in memory and never leaves the device. DNS requests go to the server you choose. The default SkySparkle server is run by the developer under this privacy policy: https://skysparkle.cc/privacy?lang=en
<b>Permissions</b>
<ul>
<li>VPN: a local tunnel that carries DNS only, nothing is routed to a remote VPN</li>
<li>Notifications: connection status with a Disconnect button</li>
<li>Network state: needed by Android's HTTP/3 engine and to detect Private DNS</li>
<li>Installed apps (launcher entries only): to list apps for per-app rules</li>
</ul>
HTTP/3 needs Android 14 or newer; older versions use HTTP/2. If Private DNS in Android settings is set to a specific hostname, Android sends DNS there instead; SparkleDNS shows a warning when that happens.
@@ -1 +1 @@
Encrypted DNS over HTTPS and HTTP/3 with blocklists and per-app rules Encrypt DNS requests without routing all your traffic through a VPN.
@@ -0,0 +1,5 @@
• ドイツ語・日本語・リトアニア語・中国語に対応
• 独立系サーバー:Digitale Gesellschaft、UncensoredDNS、Freifunk München。Cloudflare、Google、AdGuard、Mullvad を削除
• サーバーリストをプロジェクトのリポジトリから更新できるように。各サーバーにプライバシーポリシーのリンク
• ヒントと警告を ✕ で閉じられるように
• 「情報」画面を整理
@@ -0,0 +1,5 @@
• 寄付を受け付けているサーバーには、プライバシーポリシーの横に寄付リンクを表示
• サーバーリストをシンプルに
• サーバーのプライバシーポリシーアイコンを新しく
• サーバーリストから HTTP/3 の表示を削除
• 「情報」の説明を短く
@@ -0,0 +1,6 @@
• 想定外のパケットが届いても DNS は動作し続けます。トンネルが故障した場合は、DNS を黙って止めずに VPN をオフにします
• Wi-Fi とモバイルデータの切り替え後や遅いネットワークで、名前解決がより早く回復します
• バックグラウンドでの処理を削減:表示されていない画面は更新しません
• ブロックリストは変更があったときだけ再ダウンロードします
• アプリアイコンがより鮮明に、アプリサイズが小さく
• 「接続」をダブルタップしても二重に接続しません。ストレージがいっぱいでもアプリが落ちなくなりました
@@ -0,0 +1,14 @@
<p>暗号化されたDNS-over-HTTPSでDNSリクエストを保護し、その他のインターネット通信は通常の接続のまま。SparkleDNSなら、端末全体をVPNサーバー経由にすることなくDNSをコントロールできます。</p>
<ul>
<li>選んだDoHサーバーへRFC 8484でDNSクエリを送信。</li>
<li>接続前にサーバーのプロトコルと遅延を確認。</li>
<li>クエリと統計をリアルタイムで表示し、アクティビティを絞り込み、ワンタップでドメインをブロック。</li>
<li>独自のドメインルールやURL指定のブロックリストを追加。HaGeZi Pro++やTIFのプリセットも利用可能。</li>
<li>選んだアプリだけDNSトンネルを経由しないよう設定。</li>
<li>ワンタップ、またはクイック設定タイルで接続・切断。</li>
</ul>
<p>SparkleDNSはローカルVPNトンネルを作成し、DNS通信だけを取り込みます。DNSリクエストは選んだDoHサーバーへ送られ、それ以外の通信は通常の接続を使います。接続中にサーバーを切り替えると、トンネルは自動で再起動します。アナリティクスやGoogle Playサービスは含まれていません。</p>
<p>暗号化DNSとドメインブロックをわかりやすく管理できる、軽量なAndroid向けDNSクライアントならSparkleDNS。インストールして、DNSリクエストを自分の手でコントロールしましょう。</p>
@@ -0,0 +1 @@
すべての通信をVPNに通さずに、DNSリクエストを暗号化します。
@@ -0,0 +1 @@
SparkleDNS
@@ -0,0 +1,5 @@
• Dabar ir vokiečių, japonų, lietuvių bei kinų kalbomis
• Nepriklausomi serveriai: Digitale Gesellschaft, UncensoredDNS, Freifunk München. Cloudflare, Google, AdGuard ir Mullvad pašalinti
• Serverių sąrašą galima atnaujinti iš projekto saugyklos, prie kiekvieno serverio – nuoroda į privatumo politiką
• Patarimus ir įspėjimus galima uždaryti ✕
• Tvarkingesnis ekranas „Apie“
@@ -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,14 @@
<p>Apsaugokite savo DNS užklausas šifruotu DNS-over-HTTPS, o likęs interneto srautas tegul eina įprastu ryšiu. SparkleDNS leidžia valdyti DNS, nenukreipiant viso įrenginio per VPN serverį.</p>
<ul>
<li>Siųskite DNS užklausas pasirinktam DoH serveriui pagal RFC 8484.</li>
<li>Prieš jungdamiesi patikrinkite serverio protokolą ir delsą.</li>
<li>Stebėkite užklausas ir statistiką realiuoju laiku, filtruokite veiklą ir blokuokite domenus vienu palietimu.</li>
<li>Pridėkite savo domenų taisykles arba blokavimo sąrašus pagal URL, įskaitant HaGeZi Pro++ ir TIF šablonus.</li>
<li>Leiskite pasirinktoms programėlėms apeiti DNS tunelį.</li>
<li>Prisijunkite ar atsijunkite vienu palietimu arba per sparčiųjų nustatymų plytelę.</li>
</ul>
<p>SparkleDNS sukuria vietinį VPN tunelį, kuris perima tik DNS srautą. DNS užklausos keliauja į pasirinktą DoH serverį, visa kita naudoja įprastą ryšį. Pakeitus serverį prisijungus, tunelis automatiškai paleidžiamas iš naujo. Jokios analitikos ir jokių Google Play paslaugų.</p>
<p>SparkleDNS – lengvas DNS klientas Android įrenginiams su aiškiu šifruoto DNS ir domenų blokavimo valdymu. Įdiekite SparkleDNS ir perimkite savo DNS užklausų kontrolę.</p>
@@ -0,0 +1 @@
Šifruokite DNS užklausas, nenukreipdami viso srauto per VPN.
+1
View File
@@ -0,0 +1 @@
SparkleDNS
@@ -0,0 +1,5 @@
• Теперь на немецком, японском, литовском и китайском
• Независимые серверы: Digitale Gesellschaft, UncensoredDNS, Freifunk München. Cloudflare, Google, AdGuard и Mullvad убраны
• Список серверов обновляется из репозитория проекта, у каждого сервера есть ссылка на политику конфиденциальности
• Подсказки и предупреждения закрываются крестиком
• Обновлён экран «О приложении»
@@ -0,0 +1,5 @@
• У серверов, которые принимают пожертвования, рядом с политикой конфиденциальности появилась ссылка на пожертвование
• Упрощённый список серверов
• Новый значок политики конфиденциальности у серверов
• Значок HTTP/3 убран из списка серверов
• Короче описание в «О программе»
@@ -0,0 +1,6 @@
• DNS продолжает работать, если пришёл неожиданный пакет; при сбое туннеля VPN отключается, а не блокирует DNS молча
• Запросы быстрее восстанавливаются после переключения между Wi-Fi и мобильной сетью и в медленных сетях
• Меньше работы в фоне: скрытые экраны больше не обновляются
• Блоклисты скачиваются заново, только если изменились
• Чётче значки приложений, меньше размер приложения
• Двойное нажатие «Подключить» больше не подключает дважды; переполненная память больше не роняет приложение
@@ -1,31 +1,14 @@
SparkleDNS шифрует каждый DNS-запрос на устройстве с помощью DNS-over-HTTPS (RFC 8484) и HTTP/3. VPN Android используется только локально: в туннель попадают лишь DNS-запросы, весь остальной трафик идёт обычным путём, поэтому скорость и батарея не страдают. <p>Защитите свои DNS-запросы с помощью зашифрованного DNS-over-HTTPS, а остальной интернет-трафик пусть идёт по обычному соединению. SparkleDNS даёт контроль над DNS, не пропуская всё устройство через VPN-сервер.</p>
<b>Серверы</b>
<ul> <ul>
<li>SkySparkle (по умолчанию) с HTTP/3, работает у разработчика</li> <li>Отправляйте DNS-запросы на выбранный DoH-сервер по RFC 8484.</li>
<li>Cloudflare, Google, Quad9, AdGuard, Mullvad</li> <li>Проверяйте протокол и задержку сервера перед подключением.</li>
<li>Любой свой DoH-сервер, с bootstrap IP и HTTP/3 по желанию</li> <li>Смотрите запросы и статистику в реальном времени, фильтруйте активность и блокируйте домены одним касанием.</li>
<li>Добавляйте свои правила для доменов или блок-листы по URL, включая пресеты HaGeZi Pro++ и TIF.</li>
<li>Разрешайте выбранным приложениям обходить DNS-туннель.</li>
<li>Подключайтесь и отключайтесь одним касанием или через плитку быстрых настроек.</li>
</ul> </ul>
<b>Возможности</b> <p>SparkleDNS создаёт локальный VPN-туннель, который перехватывает только DNS-трафик. DNS-запросы уходят на выбранный DoH-сервер, всё остальное идёт по обычному соединению. Если сменить сервер во время подключения, туннель перезапустится автоматически. Никакой аналитики и сервисов Google Play.</p>
<ul>
<li>Подключение одним касанием, плитка в шторке, поддержка постоянного VPN</li>
<li>Монитор: каждый запрос со статусом и задержкой, фильтры, поиск и блокировка одним касанием</li>
<li>Правила для приложений: группы по категориям, выбранные приложения идут мимо SparkleDNS</li>
<li>Блоклисты: свои домены и списки hosts, доменов, AdBlock и dnsmasq по ссылке, HaGeZi Pro++ и TIF в одно касание. Поддомены блокируются тоже, изменения применяются сразу</li>
<li>Локальный DNS-кэш с учётом TTL</li>
<li>Проверка сервера с протоколом (h3 или h2) и задержкой</li>
</ul>
<b>Приватность</b> <p>SparkleDNS — лёгкий DNS-клиент для Android с понятным управлением зашифрованным DNS и блокировкой доменов. Установите SparkleDNS и возьмите свои DNS-запросы под контроль.</p>
Никакой аналитики, рекламы и сервисов Google Play. Журнал запросов хранится только в памяти и никуда не отправляется. DNS-запросы уходят на выбранный вами сервер. Сервер SkySparkle по умолчанию работает у разработчика по этой политике конфиденциальности: https://skysparkle.cc/privacy?lang=en
<b>Разрешения</b>
<ul>
<li>VPN: локальный туннель только для DNS, ничего не уходит на удалённый VPN</li>
<li>Уведомления: статус подключения и кнопка «Отключить»</li>
<li>Состояние сети: нужно движку HTTP/3 Android и для проверки частного DNS</li>
<li>Установленные приложения (только ярлыки лаунчера): для правил по приложениям</li>
</ul>
Для HTTP/3 нужен Android 14 или новее, на более старых используется HTTP/2. Если в настройках Android «Частный DNS» задан конкретным хостом, Android отправляет DNS туда; SparkleDNS предупреждает об этом.
@@ -1 +1 @@
Шифрованный DNS через HTTPS и HTTP/3 с блоклистами и правилами для приложений Шифруйте DNS-запросы, не пропуская весь трафик через VPN.
@@ -0,0 +1,5 @@
• 新增德语、日语、立陶宛语和中文
• 独立服务器:Digitale Gesellschaft、UncensoredDNS、Freifunk München;移除 Cloudflare、Google、AdGuard 和 Mullvad
• 可从项目仓库更新服务器列表,每个服务器都附有隐私政策链接
• 提示和警告可点 ✕ 关闭
• “关于”页面更简洁
@@ -0,0 +1,5 @@
• 接受捐赠的服务器在隐私政策旁显示捐赠链接
• 服务器列表更简洁
• 服务器的隐私政策图标焕新
• 服务器列表中移除 HTTP/3 标识
• “关于”中的介绍更简短
@@ -0,0 +1,6 @@
• 收到意外的数据包时 DNS 仍可正常工作;隧道出错时会关闭 VPN,而不是悄悄阻断 DNS
• 在 Wi-Fi 与移动数据之间切换后以及网速较慢时,域名解析恢复更快
• 后台工作更少:不再刷新隐藏的界面
• 拦截列表仅在有变化时重新下载
• 应用图标更清晰,应用体积更小
• 连点“连接”不会再重复连接;存储空间已满时应用不再崩溃
@@ -0,0 +1,14 @@
<p>使用加密的 DNS-over-HTTPS 保护你的 DNS 请求,其他网络流量仍走普通连接。SparkleDNS 让你掌控 DNS,而无需让整台设备经过 VPN 服务器。</p>
<ul>
<li>按照 RFC 8484 将 DNS 查询发送到你选择的 DoH 服务器。</li>
<li>连接前检查服务器的协议和延迟。</li>
<li>实时查看查询和统计信息,筛选活动,一键屏蔽域名。</li>
<li>添加自定义域名规则,或通过 URL 添加屏蔽列表,包括 HaGeZi Pro++ 和 TIF 预设。</li>
<li>允许指定应用绕过 DNS 隧道。</li>
<li>一键连接或断开,也可使用快捷设置磁贴。</li>
</ul>
<p>SparkleDNS 创建本地 VPN 隧道,仅捕获 DNS 流量。DNS 请求发送到你选择的 DoH 服务器,其他流量使用常规连接。连接时切换服务器,隧道会自动重启。不含任何分析服务或 Google Play 服务。</p>
<p>SparkleDNS 是一款轻量的 Android DNS 客户端,让你清晰掌控加密 DNS 与域名屏蔽。安装 SparkleDNS,掌控你的 DNS 请求。</p>
@@ -0,0 +1 @@
加密 DNS 请求,无需让全部流量经过 VPN。
@@ -0,0 +1 @@
SparkleDNS
-27
View File
@@ -1,27 +0,0 @@
# Build recipe for the F-Droid main repository.
# Submit it as metadata/cc.skysparkle.sparkledns.yml in a merge request to https://gitlab.com/fdroid/fdroiddata
Categories:
- Connectivity
- Security
License: GPL-3.0-or-later
WebSite: https://skysparkle.cc
SourceCode: https://git.skysparkle.cc/kalarina/Sparkledns
IssueTracker: https://git.skysparkle.cc/kalarina/Sparkledns/issues
AutoName: SparkleDNS
RepoType: git
Repo: https://git.skysparkle.cc/kalarina/Sparkledns.git
Builds:
- versionName: 1.0.6
versionCode: 10006
commit: v1.0.6
subdir: app
gradle:
- yes
AutoUpdateMode: Version
UpdateCheckMode: Tags ^v[0-9.]+$
CurrentVersion: 1.0.6
CurrentVersionCode: 10006
+71
View File
@@ -0,0 +1,71 @@
#!/usr/bin/env bash
# Records which classes and methods the app uses on startup and in each tab, in the text format
# of app/src/main/baseline-prof.txt. Needs a rooted Android 13+ device or emulator (no Play Store).
# Usage: scripts/baseline-profile.sh <non-minified release apk> <output file>
set -euo pipefail
PKG=cc.skysparkle.sparkledns
ACT="$PKG/.MainActivity"
APK="$1"
OUT="$2"
adb root >/dev/null 2>&1 && sleep 3
adb wait-for-device
adb uninstall "$PKG" >/dev/null 2>&1 || true
adb install -g "$APK" >/dev/null
read -r W H < <(adb shell wm size | tr -d '\r' | awk -F'[ x]' '/Physical/ {print $3, $4}')
tap_text() {
local xy
for _ in 1 2 3 4 5; do
adb shell uiautomator dump /sdcard/ui.xml >/dev/null 2>&1 || true
xy="$(adb shell cat /sdcard/ui.xml | python3 -c '
import re, sys
xml, text = sys.stdin.read(), sys.argv[1]
for node in re.findall(r"<node [^>]*>", xml):
# Compose merges a clickable row into one node: "System, 3 of 5"
if re.search(r"(text|content-desc)=\"%s(\"|, )" % re.escape(text), node):
x1, y1, x2, y2 = map(int, re.search(r"bounds=\"\[(\d+),(\d+)\]\[(\d+),(\d+)\]\"", node).groups())
print((x1 + x2) // 2, (y1 + y2) // 2)
break
' "$1")"
if [[ -n "$xy" ]]; then
adb shell input tap $xy
return 0
fi
# Lazy lists only show what is on screen; with "scroll", look further down
[[ "${2:-}" == scroll ]] && adb shell input swipe $((W / 2)) $((H * 2 / 3)) $((W / 2)) $((H / 3)) 300
sleep 1
done
echo "::warning::'$1' not found on screen"
}
swipe() {
adb shell input swipe $((W / 2)) $((H * 3 / 4)) $((W / 2)) $((H / 4)) 200
sleep 1
adb shell input swipe $((W / 2)) $((H / 4)) $((W / 2)) $((H * 3 / 4)) 200
sleep 1
}
for _ in 1 2 3; do
adb shell am force-stop "$PKG"
adb shell am start-activity -W -n "$ACT" >/dev/null
sleep 3
swipe
tap_text "Monitor"; sleep 2
tap_text "Apps"; sleep 3
tap_text "System" scroll; sleep 2
swipe
tap_text "Blocklist"; sleep 2
swipe
tap_text "About"; sleep 2
tap_text "Home"; sleep 2
# Makes ART write the profile now instead of on its own schedule
adb shell "kill -10 \$(pidof $PKG)"
sleep 5
done
adb shell pm dump-profiles --dump-classes-and-methods "$PKG"
sleep 2
adb pull "/data/misc/profman/$PKG-primary.prof.txt" "$OUT" >/dev/null
echo "Profile lines: $(wc -l < "$OUT")"
+29
View File
@@ -0,0 +1,29 @@
#!/usr/bin/env bash
# Builds signed release APKs of two revisions for scripts/bench.sh.
# Usage: scripts/bench-build.sh <base-ref> <head-ref> <out-dir>
set -euo pipefail
base="$(git rev-parse "$1")"
head="$(git rev-parse "$2")"
out="$(mkdir -p "$3" && cd "$3" && pwd)"
work="${RUNNER_TEMP:-/tmp}/bench-src"
keystore="$out/bench.jks"
[[ -f "$keystore" ]] || keytool -genkeypair -keystore "$keystore" -storepass benchpass -keypass benchpass \
-alias bench -keyalg RSA -keysize 2048 -validity 365 -dname "CN=bench" >/dev/null 2>&1
apksigner="$(ls -d "$ANDROID_HOME"/build-tools/*/ | sort -V | tail -n 1)apksigner"
build() {
local rev="$1" name="$2" dir="$work-$2" apk
rm -rf "$dir"
git worktree add -f --detach "$dir" "$rev" >/dev/null
(cd "$dir" && ./gradlew :app:assembleRelease -q)
apk="$(ls "$dir"/app/build/outputs/apk/release/*.apk | head -n 1)"
echo "$name,apk_bytes,$(stat -c %s "$apk")" >> "$out/sizes.csv"
echo "::notice title=APK size ($name ${rev:0:7})::$(stat -c %s "$apk") bytes"
"$apksigner" sign --ks "$keystore" --ks-pass pass:benchpass --out "$out/$name.apk" "$apk"
}
rm -f "$out/sizes.csv"
build "$base" base
build "$head" head
+222
View File
@@ -0,0 +1,222 @@
#!/usr/bin/env bash
# Benchmarks two APKs of SparkleDNS on one device or emulator and prints medians side by side:
# cold start, memory, CPU while in the background and scroll jank on the Apps tab.
# Rounds alternate the order of the APKs so device drift affects both alike.
# Needs a rooted device (an emulator image without Play Store) to drop the page cache.
# Usage: scripts/bench.sh <base.apk> <head.apk> [rounds]
set -uo pipefail
PKG=cc.skysparkle.sparkledns
ACT="$PKG/.MainActivity"
BASE_APK="$1"
HEAD_APK="$2"
ROUNDS="${3:-2}"
STARTS="${STARTS:-10}"
OUT="${OUT:-$(dirname "$BASE_APK")}"
RAW="$OUT/raw.csv"
: > "$RAW"
adb root >/dev/null 2>&1 && sleep 3
adb wait-for-device
read -r W H < <(adb shell wm size | tr -d '\r' | awk -F'[ x]' '/Physical/ {print $3, $4}')
record() { echo "$1,$2,$3" >> "$RAW"; } # name,metric,value
install() {
adb uninstall "$PKG" >/dev/null 2>&1
adb install -g "$1" >/dev/null
adb shell am start -W -n "$ACT" >/dev/null
sleep 2
adb shell am force-stop "$PKG"
# Compiles with the APK's baseline profile only, as the device does after an install,
# without what the JIT learned during the first run (same as Macrobenchmark's Partial mode)
adb shell cmd package compile --reset "$PKG" >/dev/null
adb shell am broadcast -f 0x20 -a androidx.profileinstaller.action.INSTALL_PROFILE \
"$PKG/androidx.profileinstaller.ProfileInstallReceiver" | tr -d '\r' | grep -o 'result=[0-9-]*'
sleep 2
adb shell cmd package compile -f -m speed-profile "$PKG" >/dev/null
}
launch() {
adb shell am start-activity -W -n "$ACT" | tr -d '\r'
}
cold_starts() {
local t
for _ in $(seq "$STARTS"); do
adb shell am force-stop "$PKG"
adb shell 'sync; echo 3 > /proc/sys/vm/drop_caches'
sleep 2
t="$(launch | awk '/TotalTime/ {print $2}')"
[[ -n "$t" ]] && record "$1" cold_start_ms "$t"
sleep 3
done
}
memory() {
local pss
for _ in 1 2 3; do
adb shell am force-stop "$PKG"
launch >/dev/null
sleep 10
pss="$(adb shell dumpsys meminfo "$PKG" | tr -d '\r' | awk '/TOTAL PSS:/ {print $3; exit}')"
[[ -n "$pss" ]] && record "$1" pss_kb "$pss"
done
}
# CPU time and scheduler wakeups of all app threads during 60 s on the home screen
background_cpu() {
local pid a b
adb shell am force-stop "$PKG"
launch >/dev/null
sleep 5
adb shell input keyevent 3
sleep 5
pid="$(adb shell pidof "$PKG" | tr -d '\r')"
[[ -z "$pid" ]] && return
a="$(adb shell "cat /proc/$pid/task/*/schedstat" | awk '{t += $1; n += $3} END {print t, n}')"
sleep 60
b="$(adb shell "cat /proc/$pid/task/*/schedstat" | awk '{t += $1; n += $3} END {print t, n}')"
read -r t1 n1 <<< "$a"
read -r t2 n2 <<< "$b"
record "$1" bg_cpu_ms_per_min "$(( (t2 - t1) / 1000000 ))"
record "$1" bg_wakeups_per_min "$(( n2 - n1 ))"
}
# Memory still held 30 s after leaving the app from the Apps tab, with every icon loaded once
background_memory() {
local pss
adb shell am force-stop "$PKG"
launch >/dev/null
sleep 3
tap_text "Apps" || return
sleep 2
tap_text "System" scroll
sleep 2
for _ in 1 2 3 4; do
adb shell input swipe $((W / 2)) $((H * 3 / 4)) $((W / 2)) $((H / 4)) 200
sleep 1
done
sleep 3
adb shell input keyevent 3
sleep 30
pss="$(adb shell dumpsys meminfo "$PKG" | tr -d '\r' | awk '/TOTAL PSS:/ {print $3; exit}')"
[[ -n "$pss" ]] && record "$1" bg_pss_after_apps_kb "$pss"
}
tap_text() {
local xy
for _ in 1 2 3 4 5; do
adb shell uiautomator dump /sdcard/ui.xml >/dev/null 2>&1
xy="$(adb shell cat /sdcard/ui.xml | python3 -c '
import re, sys
xml, text = sys.stdin.read(), sys.argv[1]
for node in re.findall(r"<node [^>]*>", xml):
# Compose merges a clickable row into one node: "System, 3 of 5"
if re.search(r"(text|content-desc)=\"%s(\"|, )" % re.escape(text), node):
x1, y1, x2, y2 = map(int, re.search(r"bounds=\"\[(\d+),(\d+)\]\[(\d+),(\d+)\]\"", node).groups())
print((x1 + x2) // 2, (y1 + y2) // 2)
break
' "$1")"
if [[ -n "$xy" ]]; then
adb shell input tap $xy
return 0
fi
# Lazy lists only show what is on screen; with "scroll", look further down
[[ "${2:-}" == scroll ]] && adb shell input swipe $((W / 2)) $((H * 2 / 3)) $((W / 2)) $((H / 3)) 300
sleep 1
done
echo "::warning::'$1' not found on screen"
return 1
}
jank() {
local g total janky
adb shell am force-stop "$PKG"
launch >/dev/null
sleep 3
tap_text "Apps" || return
sleep 2
tap_text "System" scroll # the only group collapsed by default, listed last
sleep 2
for _ in 1 2 3; do
adb shell input swipe $((W / 2)) $((H / 4)) $((W / 2)) $((H * 3 / 4)) 100
done
sleep 2
adb shell dumpsys gfxinfo "$PKG" reset >/dev/null
for dir in down down down down down up up up up up; do
if [[ $dir == down ]]; then
adb shell input swipe $((W / 2)) $((H * 3 / 4)) $((W / 2)) $((H / 4)) 200
else
adb shell input swipe $((W / 2)) $((H / 4)) $((W / 2)) $((H * 3 / 4)) 200
fi
sleep 1.2
done
g="$(adb shell dumpsys gfxinfo "$PKG" | tr -d '\r')"
total="$(awk -F': ' '/Total frames rendered/ {print $2; exit}' <<< "$g")"
janky="$(awk '/Janky frames:/ {print $3; exit}' <<< "$g")"
if [[ -n "$total" && "$total" -gt 0 ]]; then
record "$1" frames "$total"
record "$1" janky_pct "$(awk -v j="$janky" -v t="$total" 'BEGIN {printf "%.2f", j * 100 / t}')"
for p in 50 90 99; do
record "$1" "frame_p${p}_ms" "$(awk "/${p}th percentile/ {gsub(\"ms\", \"\", \$3); print \$3; exit}" <<< "$g")"
done
fi
}
measure() {
echo "::group::$1"
install "$2"
cold_starts "$1"
memory "$1"
background_cpu "$1"
background_memory "$1"
jank "$1"
jank "$1"
echo "::endgroup::"
}
# The first launches after boot are far slower than later ones; warm up before measuring
echo "::group::warm-up"
install "$BASE_APK"
for _ in 1 2 3 4 5; do
adb shell am force-stop "$PKG"
launch >/dev/null
sleep 2
done
echo "::endgroup::"
for r in $(seq "$ROUNDS"); do
if (( r % 2 )); then
measure base "$BASE_APK"
measure head "$HEAD_APK"
else
measure head "$HEAD_APK"
measure base "$BASE_APK"
fi
done
[[ -f "$OUT/sizes.csv" ]] && cat "$OUT/sizes.csv" >> "$RAW"
python3 - "$RAW" > "$OUT/results.md" <<'EOF'
import csv, statistics, sys
data = {}
for name, metric, value in csv.reader(open(sys.argv[1])):
if value:
data.setdefault(metric, {}).setdefault(name, []).append(float(value))
print("| Metric (median) | base | head | change | base min–max | head min–max | n |")
print("|---|---|---|---|---|---|---|")
for metric, by in data.items():
b, h = by.get("base", []), by.get("head", [])
mb = statistics.median(b) if b else None
mh = statistics.median(h) if h else None
change = f"{(mh - mb) / mb * 100:+.1f}%" if mb and mh is not None else "n/a"
fmt = lambda v: "n/a" if v is None else (f"{v:.0f}" if v >= 100 else f"{v:.2f}")
rng = lambda v: f"{fmt(min(v))}–{fmt(max(v))}" if v else "n/a"
print(f"| {metric} | {fmt(mb)} | {fmt(mh)} | {change} | {rng(b)} | {rng(h)} | {len(b)}/{len(h)} |")
EOF
cat "$OUT/results.md"
[[ -n "${GITHUB_STEP_SUMMARY:-}" ]] && cat "$OUT/results.md" >> "$GITHUB_STEP_SUMMARY"
msg="$(cat "$OUT/results.md")"
echo "::notice title=Benchmark::${msg//$'\n'/'%0A'}"
+8
View File
@@ -0,0 +1,8 @@
# SparkleDNS server list. How to add a server: see CONTRIBUTING.md
# Name | DoH URL | Privacy policy | h3 (optional) | Donation page (optional)
SkySparkle | https://blog.skysparkle.cc/dns-query | https://skysparkle.cc/privacy?lang=en | h3
Quad9 | https://dns.quad9.net/dns-query | https://quad9.net/service/privacy/ | https://quad9.net/donate/
Digitale Gesellschaft | https://dns.digitale-gesellschaft.ch/dns-query | https://www.digitale-gesellschaft.ch/dns/ | h3 | https://www.digitale-gesellschaft.ch/uber-uns/unterstuetzer-werden/
UncensoredDNS | https://anycast.uncensoreddns.org/dns-query | https://blog.uncensoreddns.org/faq/
Freifunk München | https://doh.ffmuc.net/dns-query | https://ffmuc.net/dns-privacy/ | h3 | https://spende.ffmuc.net/