mirror of
https://github.com/kalarina-bit/Sparkledns.git
synced 2026-11-22 15:46:09 +00:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
399fc5ea36 | ||
|
|
83789c8510 | ||
|
|
64728e5fcd | ||
|
|
2578af2bed |
@@ -4,3 +4,6 @@ local.properties
|
|||||||
.idea/
|
.idea/
|
||||||
*.iml
|
*.iml
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
# Signing keys must never be committed
|
||||||
|
*.jks
|
||||||
|
*.keystore
|
||||||
|
|||||||
+15
-14
@@ -1,11 +1,12 @@
|
|||||||
plugins {
|
plugins {
|
||||||
id("com.android.application")
|
alias(libs.plugins.android.application)
|
||||||
id("org.jetbrains.kotlin.plugin.compose")
|
alias(libs.plugins.kotlin.compose)
|
||||||
}
|
}
|
||||||
|
|
||||||
android {
|
android {
|
||||||
namespace = "cc.skysparkle.sparkledns"
|
namespace = "cc.skysparkle.sparkledns"
|
||||||
compileSdk = 36
|
// The current AndroidX libraries require it
|
||||||
|
compileSdk = 37
|
||||||
|
|
||||||
defaultConfig {
|
defaultConfig {
|
||||||
applicationId = "cc.skysparkle.sparkledns"
|
applicationId = "cc.skysparkle.sparkledns"
|
||||||
@@ -13,8 +14,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 = 10103
|
versionCode = 10104
|
||||||
versionName = "1.1.3"
|
versionName = "1.1.4"
|
||||||
}
|
}
|
||||||
|
|
||||||
buildTypes {
|
buildTypes {
|
||||||
@@ -71,17 +72,17 @@ android {
|
|||||||
}
|
}
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
implementation(platform("androidx.compose:compose-bom:2025.09.00"))
|
implementation(platform(libs.androidx.compose.bom))
|
||||||
implementation("androidx.activity:activity-compose:1.10.1")
|
implementation(libs.androidx.activity.compose)
|
||||||
implementation("androidx.compose.ui:ui")
|
implementation(libs.androidx.compose.ui)
|
||||||
implementation("androidx.compose.material3:material3")
|
implementation(libs.androidx.compose.material3)
|
||||||
// Already pulled in by Compose at this version; declared because the app uses it directly
|
// 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(libs.androidx.lifecycle.runtime.compose)
|
||||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2")
|
implementation(libs.kotlinx.coroutines.android)
|
||||||
implementation("com.squareup.okhttp3:okhttp:4.12.0")
|
implementation(libs.okhttp)
|
||||||
|
|
||||||
// Debug builds only, never part of a release
|
// Debug builds only, never part of a release
|
||||||
debugImplementation("com.squareup.leakcanary:leakcanary-android:2.14")
|
debugImplementation(libs.leakcanary.android)
|
||||||
|
|
||||||
testImplementation("junit:junit:4.13.2")
|
testImplementation(libs.junit)
|
||||||
}
|
}
|
||||||
@@ -6,7 +6,7 @@
|
|||||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SYSTEM_EXEMPTED" />
|
||||||
<!-- Keeps the scheduled blocklist update after a reboot -->
|
<!-- Keeps the scheduled blocklist update after a reboot -->
|
||||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||||
|
|
||||||
@@ -21,6 +21,8 @@
|
|||||||
<application
|
<application
|
||||||
android:name=".SparkleApp"
|
android:name=".SparkleApp"
|
||||||
android:allowBackup="false"
|
android:allowBackup="false"
|
||||||
|
android:dataExtractionRules="@xml/data_extraction_rules"
|
||||||
|
android:localeConfig="@xml/locales_config"
|
||||||
android:icon="@mipmap/ic_launcher"
|
android:icon="@mipmap/ic_launcher"
|
||||||
android:roundIcon="@mipmap/ic_launcher_round"
|
android:roundIcon="@mipmap/ic_launcher_round"
|
||||||
android:label="@string/app_name"
|
android:label="@string/app_name"
|
||||||
@@ -40,7 +42,7 @@
|
|||||||
<service
|
<service
|
||||||
android:name=".DohVpnService"
|
android:name=".DohVpnService"
|
||||||
android:exported="false"
|
android:exported="false"
|
||||||
android:foregroundServiceType="specialUse"
|
android:foregroundServiceType="systemExempted"
|
||||||
android:permission="android.permission.BIND_VPN_SERVICE">
|
android:permission="android.permission.BIND_VPN_SERVICE">
|
||||||
<intent-filter>
|
<intent-filter>
|
||||||
<action android:name="android.net.VpnService" />
|
<action android:name="android.net.VpnService" />
|
||||||
@@ -48,9 +50,6 @@
|
|||||||
<meta-data
|
<meta-data
|
||||||
android:name="android.net.VpnService.SUPPORTS_ALWAYS_ON"
|
android:name="android.net.VpnService.SUPPORTS_ALWAYS_ON"
|
||||||
android:value="true" />
|
android:value="true" />
|
||||||
<property
|
|
||||||
android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
|
|
||||||
android:value="Local DNS-over-HTTPS VPN that keeps encrypted DNS active while the user has it enabled" />
|
|
||||||
</service>
|
</service>
|
||||||
|
|
||||||
<service
|
<service
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import kotlinx.coroutines.flow.StateFlow
|
|||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import okhttp3.OkHttpClient
|
import okhttp3.OkHttpClient
|
||||||
import okhttp3.Request
|
import okhttp3.Request
|
||||||
|
import okio.BufferedSource
|
||||||
import org.json.JSONArray
|
import org.json.JSONArray
|
||||||
import org.json.JSONObject
|
import org.json.JSONObject
|
||||||
import java.io.BufferedOutputStream
|
import java.io.BufferedOutputStream
|
||||||
@@ -475,13 +476,11 @@ private class BlocklistStore(context: Context) {
|
|||||||
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 ->
|
BlocklistParser.readLimitedLines(body.source()) { line ->
|
||||||
lines.forEach { line ->
|
val domain = BlocklistParser.parseLine(line) ?: return@readLimitedLines
|
||||||
val domain = BlocklistParser.parseLine(line) ?: return@forEach
|
// Far above the largest common lists; keeps a wrong URL from exhausting memory
|
||||||
// Far above the largest common lists; keeps a wrong URL from exhausting memory
|
if (parsed.size >= MAX_LIST_DOMAINS) throw IOException("List too large")
|
||||||
if (parsed.size >= MAX_LIST_DOMAINS) throw IOException("List too large")
|
parsed.add(DomainHash.of(domain))
|
||||||
parsed.add(DomainHash.of(domain))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
// Sorted inside the download buffer: a list with millions of entries is never copied
|
// Sorted inside the download buffer: a list with millions of entries is never copied
|
||||||
val count = parsed.sortUnique()
|
val count = parsed.sortUnique()
|
||||||
@@ -521,6 +520,7 @@ private class BlocklistStore(context: Context) {
|
|||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
const val MAX_LIST_DOMAINS = 4_000_000
|
const val MAX_LIST_DOMAINS = 4_000_000
|
||||||
|
|
||||||
private const val MERGED_KEY = "merged"
|
private const val MERGED_KEY = "merged"
|
||||||
|
|
||||||
val client: OkHttpClient by lazy {
|
val client: OkHttpClient by lazy {
|
||||||
@@ -533,6 +533,59 @@ private class BlocklistStore(context: Context) {
|
|||||||
|
|
||||||
// Understands hosts files, plain domain lists, AdBlock rules (||domain^) and dnsmasq / unbound syntax
|
// Understands hosts files, plain domain lists, AdBlock rules (||domain^) and dnsmasq / unbound syntax
|
||||||
object BlocklistParser {
|
object BlocklistParser {
|
||||||
|
/** A list larger than this is refused; the biggest common lists are well below it. */
|
||||||
|
const val MAX_LIST_BYTES = 256L * 1024 * 1024
|
||||||
|
|
||||||
|
/** Longer lines (no blocklist entry is that long) are skipped, not read into memory. */
|
||||||
|
const val MAX_LINE_BYTES = 4096L
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reads [source] line by line within [MAX_LIST_BYTES] in total and [MAX_LINE_BYTES] per
|
||||||
|
* line, so a wrong URL (a binary file, a page with no line breaks) cannot fill the memory.
|
||||||
|
*/
|
||||||
|
fun readLimitedLines(source: BufferedSource, onLine: (String) -> Unit) {
|
||||||
|
var total = 0L
|
||||||
|
fun consumed(bytes: Long) {
|
||||||
|
total += bytes
|
||||||
|
if (total > MAX_LIST_BYTES) throw IOException("List too large")
|
||||||
|
}
|
||||||
|
while (true) {
|
||||||
|
val newline = source.indexOf('\n'.code.toByte(), 0, MAX_LINE_BYTES + 1)
|
||||||
|
when {
|
||||||
|
newline >= 0 -> {
|
||||||
|
onLine(source.readUtf8(newline))
|
||||||
|
source.skip(1)
|
||||||
|
consumed(newline + 1)
|
||||||
|
}
|
||||||
|
source.exhausted() -> return
|
||||||
|
source.request(MAX_LINE_BYTES + 1) -> {
|
||||||
|
// Overlong line: drop it piece by piece up to its end
|
||||||
|
while (true) {
|
||||||
|
// Only what is already buffered: the next line may start right after the break
|
||||||
|
val end = source.buffer.indexOf('\n'.code.toByte())
|
||||||
|
if (end >= 0) {
|
||||||
|
source.skip(end + 1)
|
||||||
|
consumed(end + 1)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
val chunk = source.buffer.size
|
||||||
|
if (chunk == 0L) return
|
||||||
|
source.skip(chunk)
|
||||||
|
consumed(chunk)
|
||||||
|
if (!source.request(1)) return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else -> {
|
||||||
|
// Last line without a line break
|
||||||
|
val rest = source.buffer.size
|
||||||
|
onLine(source.readUtf8())
|
||||||
|
consumed(rest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private val WHITESPACE = Regex("\\s+")
|
private val WHITESPACE = Regex("\\s+")
|
||||||
private val IGNORED = setOf(
|
private val IGNORED = setOf(
|
||||||
"localhost", "localhost.localdomain", "local", "broadcasthost",
|
"localhost", "localhost.localdomain", "local", "broadcasthost",
|
||||||
@@ -548,6 +601,8 @@ object BlocklistParser {
|
|||||||
// Fast path for AdBlock-style lists such as HaGeZi: ||domain^
|
// Fast path for AdBlock-style lists such as HaGeZi: ||domain^
|
||||||
if (line.startsWith("||")) {
|
if (line.startsWith("||")) {
|
||||||
val end = line.indexOfAny(charArrayOf('^', '$', '/'), 2)
|
val end = line.indexOfAny(charArrayOf('^', '$', '/'), 2)
|
||||||
|
// ||example.com/ads/ blocks one path in a browser; as DNS it would block the whole site
|
||||||
|
if (end >= 0 && line[end] == '/' && hasPath(line.substring(end))) return null
|
||||||
return normalize(if (end >= 0) line.substring(2, end) else line.substring(2))
|
return normalize(if (end >= 0) line.substring(2, end) else line.substring(2))
|
||||||
}
|
}
|
||||||
if (DNSMASQ.any { line.startsWith(it) }) return normalize(line.substringAfter("=/").substringBefore('/'))
|
if (DNSMASQ.any { line.startsWith(it) }) return normalize(line.substringAfter("=/").substringBefore('/'))
|
||||||
@@ -557,9 +612,17 @@ object BlocklistParser {
|
|||||||
val parts = line.substringBefore('#').trim().split(WHITESPACE)
|
val parts = line.substringBefore('#').trim().split(WHITESPACE)
|
||||||
val candidate = if (parts.size >= 2 && looksLikeIp(parts[0])) parts[1] else parts[0]
|
val candidate = if (parts.size >= 2 && looksLikeIp(parts[0])) parts[1] else parts[0]
|
||||||
if (candidate.lowercase() in IGNORED) return null
|
if (candidate.lowercase() in IGNORED) return null
|
||||||
|
// A URL with a path (|http://example.com/x|) stands for one page, not for the domain
|
||||||
|
val afterScheme = candidate.substringAfter("://")
|
||||||
|
val slash = afterScheme.indexOf('/')
|
||||||
|
if (slash >= 0 && hasPath(afterScheme.substring(slash))) return null
|
||||||
return normalize(candidate)
|
return normalize(candidate)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// "/", "/^" or "/|" only end the host; anything longer is a path
|
||||||
|
private fun hasPath(fromSlash: String): Boolean =
|
||||||
|
fromSlash.trimEnd('^', '|').length > 1
|
||||||
|
|
||||||
fun normalize(input: String): String? {
|
fun normalize(input: String): String? {
|
||||||
var s = input.trim().lowercase()
|
var s = input.trim().lowercase()
|
||||||
s = s.substringAfter("://")
|
s = s.substringAfter("://")
|
||||||
|
|||||||
@@ -59,6 +59,15 @@ class DnsTileService : TileService() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// Turning protection off needs an unlocked phone, like other security toggles
|
||||||
|
if (running && isLocked) {
|
||||||
|
unlockAndRun { toggle(running) }
|
||||||
|
return
|
||||||
|
}
|
||||||
|
toggle(running)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun toggle(running: Boolean) {
|
||||||
val action = if (running) DohVpnService.ACTION_STOP else DohVpnService.ACTION_START
|
val action = if (running) DohVpnService.ACTION_STOP else DohVpnService.ACTION_START
|
||||||
try {
|
try {
|
||||||
startService(Intent(this, DohVpnService::class.java).setAction(action))
|
startService(Intent(this, DohVpnService::class.java).setAction(action))
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import android.net.ConnectivityManager
|
|||||||
import android.net.Network
|
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.NetworkException
|
||||||
import android.net.http.UploadDataProvider
|
import android.net.http.UploadDataProvider
|
||||||
import android.net.http.UploadDataSink
|
import android.net.http.UploadDataSink
|
||||||
import android.net.http.UrlRequest
|
import android.net.http.UrlRequest
|
||||||
@@ -74,7 +75,10 @@ class DohClient(context: Context, provider: DohProvider) {
|
|||||||
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) {
|
||||||
try {
|
try {
|
||||||
return Http3Transport(context, provider)
|
val http3 = Http3Transport(context, provider)
|
||||||
|
// HttpEngine resolves the host with system DNS and cannot use fixed addresses
|
||||||
|
return if (provider.bootstrap.isEmpty()) http3
|
||||||
|
else BootstrapFallbackTransport(http3) { OkHttpTransport(context, provider) }
|
||||||
} catch (e: Throwable) {
|
} catch (e: Throwable) {
|
||||||
Log.w(TAG, "HttpEngine unavailable, falling back to HTTP/2", e)
|
Log.w(TAG, "HttpEngine unavailable, falling back to HTTP/2", e)
|
||||||
}
|
}
|
||||||
@@ -89,6 +93,38 @@ private interface Transport {
|
|||||||
fun shutdown()
|
fun shutdown()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private class UnresolvedHostException(cause: Throwable) : IOException("Host not resolved", cause)
|
||||||
|
|
||||||
|
// HTTP/3 first; once the network fails to resolve the server's name, the rest of the session
|
||||||
|
// goes over OkHttp, which connects to the bootstrap addresses instead
|
||||||
|
private class BootstrapFallbackTransport(
|
||||||
|
private val http3: Transport,
|
||||||
|
createFallback: () -> Transport,
|
||||||
|
) : Transport {
|
||||||
|
private val fallback = lazy(createFallback)
|
||||||
|
@Volatile private var useFallback = false
|
||||||
|
|
||||||
|
override val lastProtocol: String?
|
||||||
|
get() = if (useFallback) fallback.value.lastProtocol else http3.lastProtocol
|
||||||
|
|
||||||
|
override fun query(message: ByteArray): ByteArray {
|
||||||
|
if (!useFallback) {
|
||||||
|
try {
|
||||||
|
return http3.query(message)
|
||||||
|
} catch (e: UnresolvedHostException) {
|
||||||
|
Log.w(TAG, "Server name not resolved over HTTP/3, using bootstrap addresses")
|
||||||
|
useFallback = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fallback.value.query(message)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun shutdown() {
|
||||||
|
http3.shutdown()
|
||||||
|
if (fallback.isInitialized()) fallback.value.shutdown()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private class OkHttpTransport(context: Context, 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() }
|
||||||
@@ -140,7 +176,11 @@ private class OkHttpTransport(context: Context, private val provider: DohProvide
|
|||||||
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")
|
||||||
if (body.contentLength() > MAX_DNS_SIZE) throw IOException("Response too large")
|
if (body.contentLength() > MAX_DNS_SIZE) throw IOException("Response too large")
|
||||||
return body.bytes()
|
// Without Content-Length the size is only known while reading: stop one byte past the limit
|
||||||
|
val source = body.source()
|
||||||
|
source.request(MAX_DNS_SIZE + 1L)
|
||||||
|
if (source.buffer.size > MAX_DNS_SIZE) throw IOException("Response too large")
|
||||||
|
return source.buffer.readByteArray()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -220,7 +260,11 @@ private class Http3Transport(context: Context, private val provider: DohProvider
|
|||||||
}
|
}
|
||||||
|
|
||||||
override fun onFailed(request: UrlRequest, info: UrlResponseInfo?, error: HttpException) {
|
override fun onFailed(request: UrlRequest, info: UrlResponseInfo?, error: HttpException) {
|
||||||
result.completeExceptionally(IOException(error.message, error))
|
val unresolved = error is NetworkException &&
|
||||||
|
error.errorCode == NetworkException.ERROR_HOSTNAME_NOT_RESOLVED
|
||||||
|
result.completeExceptionally(
|
||||||
|
if (unresolved) UnresolvedHostException(error) else IOException(error.message, error)
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onCanceled(request: UrlRequest, info: UrlResponseInfo?) {
|
override fun onCanceled(request: UrlRequest, info: UrlResponseInfo?) {
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ import android.system.StructPollfd
|
|||||||
import android.util.Log
|
import android.util.Log
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
|
||||||
import java.io.FileInputStream
|
import java.io.FileInputStream
|
||||||
import java.io.FileOutputStream
|
import java.io.FileOutputStream
|
||||||
import java.io.IOException
|
import java.io.IOException
|
||||||
@@ -34,7 +35,11 @@ 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
|
||||||
|
// Separate channel with normal importance: losing protection must not go unnoticed
|
||||||
|
private const val ALERT_CHANNEL_ID = "vpn_alerts"
|
||||||
|
private const val ALERT_NOTIFICATION_ID = 2
|
||||||
private const val MAX_BAD_PACKETS = 100
|
private const val MAX_BAD_PACKETS = 100
|
||||||
|
private const val READER_JOIN_MS = 1000L
|
||||||
|
|
||||||
// Android's resolver retries after 5 s, so an older lookup no longer has anyone waiting for it
|
// 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
|
private const val QUEUE_TIMEOUT_MS = 5000L
|
||||||
@@ -96,6 +101,16 @@ class DohVpnService : VpnService() {
|
|||||||
val provider = prefs.resolve()
|
val provider = prefs.resolve()
|
||||||
val excluded = prefs.excludedApps
|
val excluded = prefs.excludedApps
|
||||||
|
|
||||||
|
// The app checks the address before connecting, but always-on VPN and a restart by the
|
||||||
|
// system start the service directly. A tunnel with a broken URL would fail every lookup.
|
||||||
|
if (provider.url.toHttpUrlOrNull()?.isHttps != true) {
|
||||||
|
Log.e(TAG, "Server address is not a valid HTTPS URL, not starting")
|
||||||
|
stopSession()
|
||||||
|
showAlert(R.string.alert_bad_url_title, R.string.alert_bad_url_text)
|
||||||
|
stopSelf()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
val builder = Builder()
|
val builder = Builder()
|
||||||
.setSession(provider.displayName(this))
|
.setSession(provider.displayName(this))
|
||||||
.addAddress(TUN_ADDRESS, 32)
|
.addAddress(TUN_ADDRESS, 32)
|
||||||
@@ -138,6 +153,14 @@ class DohVpnService : VpnService() {
|
|||||||
_activeExcluded.value = excluded
|
_activeExcluded.value = excluded
|
||||||
showNotification(provider)
|
showNotification(provider)
|
||||||
DnsTileService.refresh(this)
|
DnsTileService.refresh(this)
|
||||||
|
getSystemService(NotificationManager::class.java)?.cancel(ALERT_NOTIFICATION_ID)
|
||||||
|
|
||||||
|
// With "Block connections without VPN" the app, excluded from its own tunnel, cannot reach
|
||||||
|
// the DoH server, so every lookup would fail
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && isLockdownEnabled) {
|
||||||
|
Log.w(TAG, "Lockdown mode is on, the DoH server is not reachable")
|
||||||
|
showAlert(R.string.alert_lockdown_title, R.string.alert_lockdown_text)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun stopSession() {
|
private fun stopSession() {
|
||||||
@@ -157,10 +180,34 @@ class DohVpnService : VpnService() {
|
|||||||
if (session !== failed) return@post
|
if (session !== failed) return@post
|
||||||
Log.e(TAG, "Tunnel stopped working, disconnecting")
|
Log.e(TAG, "Tunnel stopped working, disconnecting")
|
||||||
stopSession()
|
stopSession()
|
||||||
|
// DNS goes unencrypted from here on; the user has to know
|
||||||
|
showAlert(R.string.alert_stopped_title, R.string.alert_stopped_text)
|
||||||
stopSelf()
|
stopSelf()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun showAlert(titleRes: Int, textRes: Int) {
|
||||||
|
val manager = getSystemService(NotificationManager::class.java) ?: return
|
||||||
|
manager.createNotificationChannel(
|
||||||
|
NotificationChannel(ALERT_CHANNEL_ID, getString(R.string.alert_channel), NotificationManager.IMPORTANCE_DEFAULT)
|
||||||
|
)
|
||||||
|
val openApp = PendingIntent.getActivity(
|
||||||
|
this, 2,
|
||||||
|
Intent(this, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),
|
||||||
|
PendingIntent.FLAG_IMMUTABLE,
|
||||||
|
)
|
||||||
|
val text = getString(textRes)
|
||||||
|
val notification = Notification.Builder(this, ALERT_CHANNEL_ID)
|
||||||
|
.setSmallIcon(R.drawable.ic_notification)
|
||||||
|
.setContentTitle(getString(titleRes))
|
||||||
|
.setContentText(text)
|
||||||
|
.setStyle(Notification.BigTextStyle().bigText(text))
|
||||||
|
.setContentIntent(openApp)
|
||||||
|
.setAutoCancel(true)
|
||||||
|
.build()
|
||||||
|
runCatching { manager.notify(ALERT_NOTIFICATION_ID, notification) }
|
||||||
|
}
|
||||||
|
|
||||||
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(
|
||||||
@@ -196,7 +243,7 @@ class DohVpnService : VpnService() {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
|
||||||
startForeground(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE)
|
startForeground(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_SYSTEM_EXEMPTED)
|
||||||
} else {
|
} else {
|
||||||
startForeground(NOTIFICATION_ID, notification)
|
startForeground(NOTIFICATION_ID, notification)
|
||||||
}
|
}
|
||||||
@@ -229,6 +276,9 @@ private class Session(
|
|||||||
if (!alive.getAndSet(false)) return
|
if (!alive.getAndSet(false)) return
|
||||||
pool.shutdownNow()
|
pool.shutdownNow()
|
||||||
runCatching { wakeup[1].close() }
|
runCatching { wakeup[1].close() }
|
||||||
|
// The pipe wakes the reader at once; let it leave before its descriptor is closed and
|
||||||
|
// possibly reused by something else
|
||||||
|
if (Thread.currentThread() !== reader) runCatching { reader.join(READER_JOIN_MS) }
|
||||||
runCatching { tun.close() }
|
runCatching { tun.close() }
|
||||||
closer.execute {
|
closer.execute {
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -131,4 +131,11 @@
|
|||||||
<string name="turn_on">Einschalten</string>
|
<string name="turn_on">Einschalten</string>
|
||||||
<string name="downloading">Wird geladen…</string>
|
<string name="downloading">Wird geladen…</string>
|
||||||
<string name="change_server">Server wechseln</string>
|
<string name="change_server">Server wechseln</string>
|
||||||
|
<string name="alert_channel">Schutzwarnungen</string>
|
||||||
|
<string name="alert_stopped_title">DNS-Schutz beendet</string>
|
||||||
|
<string name="alert_stopped_text">Der Tunnel funktioniert nicht mehr, DNS ist nicht mehr verschlüsselt. Öffne SparkleDNS, um dich erneut zu verbinden.</string>
|
||||||
|
<string name="alert_bad_url_title">DNS-Schutz nicht gestartet</string>
|
||||||
|
<string name="alert_bad_url_text">Die Serveradresse ist keine gültige HTTPS-URL. Öffne SparkleDNS und prüfe den Server.</string>
|
||||||
|
<string name="alert_lockdown_title">DNS-Server nicht erreichbar</string>
|
||||||
|
<string name="alert_lockdown_text">„Verbindungen ohne VPN blockieren“ ist aktiv, daher erreicht SparkleDNS den DNS-Server nicht und Anfragen schlagen fehl. Schalte es in den VPN-Einstellungen von Android aus.</string>
|
||||||
</resources>
|
</resources>
|
||||||
|
|||||||
@@ -131,4 +131,11 @@
|
|||||||
<string name="turn_on">オンにする</string>
|
<string name="turn_on">オンにする</string>
|
||||||
<string name="downloading">ダウンロード中…</string>
|
<string name="downloading">ダウンロード中…</string>
|
||||||
<string name="change_server">サーバーを変更</string>
|
<string name="change_server">サーバーを変更</string>
|
||||||
|
<string name="alert_channel">保護に関する警告</string>
|
||||||
|
<string name="alert_stopped_title">DNS 保護が停止しました</string>
|
||||||
|
<string name="alert_stopped_text">トンネルが動作しなくなったため、DNS は暗号化されていません。SparkleDNS を開いて再接続してください。</string>
|
||||||
|
<string name="alert_bad_url_title">DNS 保護を開始できません</string>
|
||||||
|
<string name="alert_bad_url_text">サーバーのアドレスが有効な HTTPS URL ではありません。SparkleDNS を開いてサーバーを確認してください。</string>
|
||||||
|
<string name="alert_lockdown_title">DNS サーバーに接続できません</string>
|
||||||
|
<string name="alert_lockdown_text">「VPN なしの接続をブロック」がオンのため、SparkleDNS は DNS サーバーに接続できず、名前解決に失敗します。Android の VPN 設定でオフにしてください。</string>
|
||||||
</resources>
|
</resources>
|
||||||
|
|||||||
@@ -131,4 +131,11 @@
|
|||||||
<string name="turn_on">Įjungti</string>
|
<string name="turn_on">Įjungti</string>
|
||||||
<string name="downloading">Atsisiunčiama…</string>
|
<string name="downloading">Atsisiunčiama…</string>
|
||||||
<string name="change_server">Keisti serverį</string>
|
<string name="change_server">Keisti serverį</string>
|
||||||
|
<string name="alert_channel">Apsaugos įspėjimai</string>
|
||||||
|
<string name="alert_stopped_title">DNS apsauga išjungta</string>
|
||||||
|
<string name="alert_stopped_text">Tunelis nustojo veikti, DNS nebešifruojamas. Atidarykite SparkleDNS, kad prisijungtumėte iš naujo.</string>
|
||||||
|
<string name="alert_bad_url_title">DNS apsauga nepaleista</string>
|
||||||
|
<string name="alert_bad_url_text">Serverio adresas nėra tinkamas HTTPS adresas. Atidarykite SparkleDNS ir patikrinkite serverį.</string>
|
||||||
|
<string name="alert_lockdown_title">DNS serveris nepasiekiamas</string>
|
||||||
|
<string name="alert_lockdown_text">Įjungta „Blokuoti ryšius be VPN“, todėl SparkleDNS negali pasiekti DNS serverio ir užklausos nepavyksta. Išjunkite tai Android VPN nustatymuose.</string>
|
||||||
</resources>
|
</resources>
|
||||||
|
|||||||
@@ -131,4 +131,11 @@
|
|||||||
<string name="turn_on">Включить</string>
|
<string name="turn_on">Включить</string>
|
||||||
<string name="downloading">Загрузка…</string>
|
<string name="downloading">Загрузка…</string>
|
||||||
<string name="change_server">Сменить сервер</string>
|
<string name="change_server">Сменить сервер</string>
|
||||||
|
<string name="alert_channel">Предупреждения о защите</string>
|
||||||
|
<string name="alert_stopped_title">Защита DNS отключена</string>
|
||||||
|
<string name="alert_stopped_text">Туннель перестал работать, DNS больше не шифруется. Откройте SparkleDNS, чтобы подключиться снова.</string>
|
||||||
|
<string name="alert_bad_url_title">Защита DNS не запущена</string>
|
||||||
|
<string name="alert_bad_url_text">Адрес сервера не является корректным HTTPS-адресом. Откройте SparkleDNS и проверьте сервер.</string>
|
||||||
|
<string name="alert_lockdown_title">DNS-сервер недоступен</string>
|
||||||
|
<string name="alert_lockdown_text">Включено «Блокировать соединения без VPN», поэтому SparkleDNS не может связаться с DNS-сервером и запросы не проходят. Отключите это в настройках VPN Android.</string>
|
||||||
</resources>
|
</resources>
|
||||||
|
|||||||
@@ -131,4 +131,11 @@
|
|||||||
<string name="turn_on">开启</string>
|
<string name="turn_on">开启</string>
|
||||||
<string name="downloading">正在下载…</string>
|
<string name="downloading">正在下载…</string>
|
||||||
<string name="change_server">更换服务器</string>
|
<string name="change_server">更换服务器</string>
|
||||||
|
<string name="alert_channel">保护警告</string>
|
||||||
|
<string name="alert_stopped_title">DNS 保护已停止</string>
|
||||||
|
<string name="alert_stopped_text">隧道已停止工作,DNS 不再加密。请打开 SparkleDNS 重新连接。</string>
|
||||||
|
<string name="alert_bad_url_title">DNS 保护未启动</string>
|
||||||
|
<string name="alert_bad_url_text">服务器地址不是有效的 HTTPS 网址。请打开 SparkleDNS 检查服务器。</string>
|
||||||
|
<string name="alert_lockdown_title">无法连接 DNS 服务器</string>
|
||||||
|
<string name="alert_lockdown_text">已开启“屏蔽未使用 VPN 的连接”,SparkleDNS 无法连接 DNS 服务器,解析会失败。请在 Android 的 VPN 设置中关闭该选项。</string>
|
||||||
</resources>
|
</resources>
|
||||||
|
|||||||
@@ -132,4 +132,11 @@
|
|||||||
<string name="turn_on">Turn on</string>
|
<string name="turn_on">Turn on</string>
|
||||||
<string name="downloading">Downloading…</string>
|
<string name="downloading">Downloading…</string>
|
||||||
<string name="change_server">Change server</string>
|
<string name="change_server">Change server</string>
|
||||||
|
<string name="alert_channel">Protection alerts</string>
|
||||||
|
<string name="alert_stopped_title">DNS protection stopped</string>
|
||||||
|
<string name="alert_stopped_text">The tunnel stopped working, so DNS is no longer encrypted. Open SparkleDNS to connect again.</string>
|
||||||
|
<string name="alert_bad_url_title">DNS protection not started</string>
|
||||||
|
<string name="alert_bad_url_text">The server address is not a valid HTTPS URL. Open SparkleDNS and check the server.</string>
|
||||||
|
<string name="alert_lockdown_title">DNS server unreachable</string>
|
||||||
|
<string name="alert_lockdown_text">\"Block connections without VPN\" is on, so SparkleDNS cannot reach the DNS server and lookups fail. Turn it off in Android VPN settings.</string>
|
||||||
</resources>
|
</resources>
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<data-extraction-rules>
|
||||||
|
<cloud-backup>
|
||||||
|
<exclude domain="root" />
|
||||||
|
<exclude domain="database" />
|
||||||
|
<exclude domain="sharedpref" />
|
||||||
|
<exclude domain="file" />
|
||||||
|
</cloud-backup>
|
||||||
|
<device-transfer>
|
||||||
|
<exclude domain="root" />
|
||||||
|
<exclude domain="database" />
|
||||||
|
<exclude domain="sharedpref" />
|
||||||
|
<exclude domain="file" />
|
||||||
|
</device-transfer>
|
||||||
|
</data-extraction-rules>
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<locale-config xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<locale android:name="en" />
|
||||||
|
<locale android:name="de" />
|
||||||
|
<locale android:name="ja" />
|
||||||
|
<locale android:name="lt" />
|
||||||
|
<locale android:name="ru" />
|
||||||
|
<locale android:name="zh" />
|
||||||
|
</locale-config>
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
package cc.skysparkle.sparkledns
|
package cc.skysparkle.sparkledns
|
||||||
|
|
||||||
|
import okio.Buffer
|
||||||
import org.junit.Assert.assertEquals
|
import org.junit.Assert.assertEquals
|
||||||
import org.junit.Assert.assertNull
|
import org.junit.Assert.assertNull
|
||||||
import org.junit.Test
|
import org.junit.Test
|
||||||
@@ -51,4 +52,22 @@ class BlocklistParserTest {
|
|||||||
assertEquals(DomainHash.of(name), DomainHash.of(name, 0))
|
assertEquals(DomainHash.of(name), DomainHash.of(name, 0))
|
||||||
assertEquals(DomainHash.of("b.example"), DomainHash.of(name, 2, name.indexOf(".com")))
|
assertEquals(DomainHash.of("b.example"), DomainHash.of(name, 2, name.indexOf(".com")))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun rulesWithAPathAreSkippedNotTurnedIntoTheWholeDomain() {
|
||||||
|
assertNull(BlocklistParser.parseLine("||example.com/ads/"))
|
||||||
|
assertNull(BlocklistParser.parseLine("|http://example.com/x|"))
|
||||||
|
assertNull(BlocklistParser.parseLine("https://example.com/banner.js"))
|
||||||
|
assertEquals("example.com", BlocklistParser.parseLine("||example.com/^"))
|
||||||
|
assertEquals("example.com", BlocklistParser.parseLine("https://example.com/"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun overlongLinesAreSkippedAndTheRestIsRead() {
|
||||||
|
val long = "x".repeat(BlocklistParser.MAX_LINE_BYTES.toInt() * 3)
|
||||||
|
val source = Buffer().writeUtf8("a.example\r\n$long\nb.example\nc.example")
|
||||||
|
val lines = mutableListOf<String>()
|
||||||
|
BlocklistParser.readLimitedLines(source) { lines += it.trim() }
|
||||||
|
assertEquals(listOf("a.example", "b.example", "c.example"), lines)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-3
@@ -1,6 +1,6 @@
|
|||||||
plugins {
|
plugins {
|
||||||
id("com.android.application") version "9.2.1" apply false
|
alias(libs.plugins.android.application) apply false
|
||||||
// Not applied to modules: only pins the Kotlin version used by AGP's built-in Kotlin
|
// Not applied to modules: only pins the Kotlin version used by AGP's built-in Kotlin
|
||||||
id("org.jetbrains.kotlin.android") version "2.4.0" apply false
|
alias(libs.plugins.kotlin.android) apply false
|
||||||
id("org.jetbrains.kotlin.plugin.compose") version "2.4.0" apply false
|
alias(libs.plugins.kotlin.compose) apply false
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
• Eine Benachrichtigung meldet, wenn der Schutz endet, die Serveradresse ungültig ist oder „Verbindungen ohne VPN blockieren“ den Server unerreichbar macht
|
||||||
|
• Bootstrap-Adressen funktionieren jetzt auch über HTTP/3
|
||||||
|
• Blocklistenregeln mit Pfad sperren nicht mehr ganze Websites
|
||||||
|
• Ausschalten über die Schnelleinstellung nur bei entsperrtem Handy
|
||||||
|
• App-Sprache in den Android-Einstellungen wählbar
|
||||||
|
• Aktualisierte Bibliotheken
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
• A notification tells you when protection stops, when the server address is invalid or when "Block connections without VPN" keeps the server unreachable
|
||||||
|
• Bootstrap addresses now also work over HTTP/3
|
||||||
|
• Blocklist rules with a path no longer block whole sites
|
||||||
|
• Turning protection off from the quick settings tile needs an unlocked phone
|
||||||
|
• App language can be set in Android settings
|
||||||
|
• Updated libraries
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
• 保護が停止したとき、サーバーのアドレスが無効なとき、「VPN なしの接続をブロック」でサーバーに届かないときに通知
|
||||||
|
• Bootstrap アドレスが HTTP/3 でも使えるように
|
||||||
|
• パス付きのブロックリストのルールでサイト全体がブロックされなくなりました
|
||||||
|
• クイック設定タイルから保護をオフにするにはロック解除が必要に
|
||||||
|
• Android の設定でアプリの言語を選択可能に
|
||||||
|
• ライブラリを更新
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
• Pranešimas, kai apsauga išsijungia, serverio adresas netinkamas arba „Blokuoti ryšius be VPN“ neleidžia pasiekti serverio
|
||||||
|
• Bootstrap adresai dabar veikia ir per HTTP/3
|
||||||
|
• Blokavimo sąrašų taisyklės su keliu nebeblokuoja visų svetainių
|
||||||
|
• Išjungti apsaugą iš sparčiųjų nustatymų galima tik atrakinus telefoną
|
||||||
|
• Programėlės kalbą galima pasirinkti Android nustatymuose
|
||||||
|
• Atnaujintos bibliotekos
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
• Уведомление, если защита отключилась, адрес сервера неверный или «Блокировать соединения без VPN» не пускает к серверу
|
||||||
|
• Bootstrap-адреса теперь работают и по HTTP/3
|
||||||
|
• Правила блоклистов с путём больше не блокируют сайты целиком
|
||||||
|
• Выключить защиту с плитки можно только на разблокированном телефоне
|
||||||
|
• Язык приложения можно выбрать в настройках Android
|
||||||
|
• Обновлены библиотеки
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
• 保护停止、服务器地址无效或“屏蔽未使用 VPN 的连接”导致无法连接服务器时会发出通知
|
||||||
|
• Bootstrap 地址现在也适用于 HTTP/3
|
||||||
|
• 带路径的拦截列表规则不再拦截整个网站
|
||||||
|
• 从快捷设置磁贴关闭保护需要先解锁手机
|
||||||
|
• 可在 Android 设置中选择应用语言
|
||||||
|
• 更新了依赖库
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
[versions]
|
||||||
|
agp = "9.2.1"
|
||||||
|
kotlin = "2.4.20"
|
||||||
|
composeBom = "2026.09.00"
|
||||||
|
activityCompose = "1.13.0"
|
||||||
|
lifecycleRuntimeCompose = "2.11.0"
|
||||||
|
kotlinxCoroutines = "1.11.0"
|
||||||
|
okhttp = "5.4.0"
|
||||||
|
leakcanary = "2.14"
|
||||||
|
junit = "4.13.2"
|
||||||
|
|
||||||
|
[libraries]
|
||||||
|
androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" }
|
||||||
|
androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" }
|
||||||
|
androidx-compose-ui = { group = "androidx.compose.ui", name = "ui" }
|
||||||
|
androidx-compose-material3 = { group = "androidx.compose.material3", name = "material3" }
|
||||||
|
androidx-lifecycle-runtime-compose = { group = "androidx.lifecycle", name = "lifecycle-runtime-compose", version.ref = "lifecycleRuntimeCompose" }
|
||||||
|
kotlinx-coroutines-android = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-android", version.ref = "kotlinxCoroutines" }
|
||||||
|
okhttp = { group = "com.squareup.okhttp3", name = "okhttp", version.ref = "okhttp" }
|
||||||
|
leakcanary-android = { group = "com.squareup.leakcanary", name = "leakcanary-android", version.ref = "leakcanary" }
|
||||||
|
junit = { group = "junit", name = "junit", version.ref = "junit" }
|
||||||
|
|
||||||
|
[plugins]
|
||||||
|
android-application = { id = "com.android.application", version.ref = "agp" }
|
||||||
|
kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
|
||||||
|
kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
|
||||||
Reference in New Issue
Block a user