Выпуск WDTT Plus v14
This commit is contained in:
1 parent
10bf9d6f25
commit
10c6939b2a
56 files changed
+7225
-813
No files matched your search
@@ -2,6 +2,34 @@
|
|||||||
|
|
||||||
Здесь фиксируются заметные пользовательские изменения WDTT Plus.
|
Здесь фиксируются заметные пользовательские изменения WDTT Plus.
|
||||||
|
|
||||||
|
## v14 — 03.08.2026
|
||||||
|
|
||||||
|
### Сеть РТ и MASQUE
|
||||||
|
|
||||||
|
- Добавлен отдельный режим «Сеть РТ» для мобильной сети Ростелекома с белыми списками. Он сначала пробует TURN/TLS с настраиваемым SNI, затем TURN/TCP ко всем адресам VK с разделением первого STUN-запроса и оставляет UDP последним резервом. Режим выключен по умолчанию и не меняет обычные подключения других операторов и Wi-Fi.
|
||||||
|
- Внутри «Сети РТ» доступен экспериментальный резерв MASQUE: WARP CONNECT-IP проверяется сначала по HTTP/2 через TCP/443, затем по HTTP/3 через QUIC/443. Регистрация WARP хранится в приватном каталоге приложения и повторно используется после перезапуска и выключения рубильников.
|
||||||
|
- Если прямой TLS к API Cloudflare недоступен, первую регистрацию WARP можно провести через SSH-сервер, указанный в разделе «Деплой». На сервер ничего не устанавливается, а обычный трафик WDTT, TURN и MASQUE через него не направляется; вероятнее всего, для этого нужен сервер за пределами РФ.
|
||||||
|
- Параметры SNI, MASQUE и регистрации через сервер перенесены в отдельное окно. Добавлены подробные инструкции, согласие с условиями Cloudflare, безопасный сброс сохранённой регистрации и поэтапные русские сообщения диагностики.
|
||||||
|
|
||||||
|
### VPN и энергопотребление
|
||||||
|
|
||||||
|
- В боковых настройках появилась необязательная «Экономия батареи во сне»: при выключенном экране VPN и системный VPN-интерфейс безопасно останавливаются, интернет идёт напрямую, а после пробуждения прежнее подключение обычно восстанавливается автоматически.
|
||||||
|
- Обычный режим стал устойчивее после сна и смены мобильной сети или Wi-Fi: краткая потеря статистики больше не вызывает преждевременное пересоздание VPN, а действительно пропавший системный интерфейс восстанавливается только после подтверждения на рабочей сети.
|
||||||
|
- Счётчики трафика текущей сессии больше не обнуляются в журнале после внутреннего перезапуска транспорта.
|
||||||
|
- Ожидание доверенной Wi-Fi теперь учитывает ещё не завершившийся запуск VPN и не позволяет службе преждевременно остановиться во время перехода.
|
||||||
|
|
||||||
|
### Диагностика и интерфейс
|
||||||
|
|
||||||
|
- Проверка устройства определяет оператора именно выбранной Android data-SIM. Если сеть или SIM меняется во время проверки, устаревшие результаты отбрасываются, а диагностика автоматически повторяется на новой сети.
|
||||||
|
- Отчёт поддержки дополнен состоянием «Сети РТ», MASQUE и локальной регистрации WARP; дублирующиеся сведения о сети убраны.
|
||||||
|
- Блок настроек туннеля стал компактнее: уменьшена высота «Мощности», «Быстрого VKCalls», «Авто капчи» и «Сети РТ».
|
||||||
|
|
||||||
|
### Совместимость
|
||||||
|
|
||||||
|
- Обновлены Android- и Go-компоненты WireGuard, а также сетевые зависимости нативного клиента.
|
||||||
|
- 64-битные нативные библиотеки собираются и проверяются с выравниванием для страниц памяти 16 КиБ. Это исправляет запуск на новых устройствах Android с таким размером страницы без повышения минимальной версии Android.
|
||||||
|
- При обновлении приложения до версии 14 вкладка «Деплой» напоминает обновить отличающуюся серверную часть с сохранением данных.
|
||||||
|
|
||||||
## v13 — 30.07.2026
|
## v13 — 30.07.2026
|
||||||
|
|
||||||
### Сервер
|
### Сервер
|
||||||
|
|||||||
+66
-6
@@ -46,7 +46,7 @@ plugins {
|
|||||||
id("org.jetbrains.kotlin.plugin.compose")
|
id("org.jetbrains.kotlin.plugin.compose")
|
||||||
}
|
}
|
||||||
|
|
||||||
val appVersionName = "13"
|
val appVersionName = "14"
|
||||||
val releaseApkBaseName = "WDTT-Plus"
|
val releaseApkBaseName = "WDTT-Plus"
|
||||||
|
|
||||||
val localProperties = Properties()
|
val localProperties = Properties()
|
||||||
@@ -90,9 +90,9 @@ android {
|
|||||||
applicationId = "com.wdtt.plus"
|
applicationId = "com.wdtt.plus"
|
||||||
minSdk = 28
|
minSdk = 28
|
||||||
targetSdk = 35
|
targetSdk = 35
|
||||||
versionCode = 13
|
versionCode = 14
|
||||||
versionName = appVersionName
|
versionName = appVersionName
|
||||||
buildConfigField("String", "MOD_RELEASE_DATE", "\"30.07.2026\"")
|
buildConfigField("String", "MOD_RELEASE_DATE", "\"03.08.2026\"")
|
||||||
buildConfigField("String", "WDTT_PLUS_DOMAIN", buildConfigString(wdttPlusDomain))
|
buildConfigField("String", "WDTT_PLUS_DOMAIN", buildConfigString(wdttPlusDomain))
|
||||||
manifestPlaceholders["wdttPlusDomain"] = wdttPlusDomain
|
manifestPlaceholders["wdttPlusDomain"] = wdttPlusDomain
|
||||||
manifestPlaceholders["appLabel"] = "WDTT Plus"
|
manifestPlaceholders["appLabel"] = "WDTT Plus"
|
||||||
@@ -249,11 +249,15 @@ tasks.register<Exec>("buildNativeClient") {
|
|||||||
mkdir -p "${'$'}jni_dir/${'$'}abi"
|
mkdir -p "${'$'}jni_dir/${'$'}abi"
|
||||||
if [ -n "${'$'}goarm" ]; then
|
if [ -n "${'$'}goarm" ]; then
|
||||||
env GOOS=android GOARCH="${'$'}goarch" GOARM="${'$'}goarm" CGO_ENABLED=1 CC="${'$'}ndk_bin/${'$'}cc" \
|
env GOOS=android GOARCH="${'$'}goarch" GOARM="${'$'}goarm" CGO_ENABLED=1 CC="${'$'}ndk_bin/${'$'}cc" \
|
||||||
go build -buildvcs=false -trimpath -ldflags="-s -w -checklinkname=0" -buildmode=pie \
|
go build -buildvcs=false -trimpath \
|
||||||
|
-ldflags="-s -w -checklinkname=0 -linkmode=external -extldflags=-Wl,-z,max-page-size=16384" \
|
||||||
|
-buildmode=pie \
|
||||||
-o "${'$'}jni_dir/${'$'}abi/libclient.so" .
|
-o "${'$'}jni_dir/${'$'}abi/libclient.so" .
|
||||||
else
|
else
|
||||||
env GOOS=android GOARCH="${'$'}goarch" CGO_ENABLED=1 CC="${'$'}ndk_bin/${'$'}cc" \
|
env GOOS=android GOARCH="${'$'}goarch" CGO_ENABLED=1 CC="${'$'}ndk_bin/${'$'}cc" \
|
||||||
go build -buildvcs=false -trimpath -ldflags="-s -w -checklinkname=0" -buildmode=pie \
|
go build -buildvcs=false -trimpath \
|
||||||
|
-ldflags="-s -w -checklinkname=0 -linkmode=external -extldflags=-Wl,-z,max-page-size=16384" \
|
||||||
|
-buildmode=pie \
|
||||||
-o "${'$'}jni_dir/${'$'}abi/libclient.so" .
|
-o "${'$'}jni_dir/${'$'}abi/libclient.so" .
|
||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
@@ -269,6 +273,62 @@ tasks.register<Exec>("buildNativeClient") {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
val verify16KbNativeLibraries = tasks.register<Exec>("verify16KbNativeLibraries") {
|
||||||
|
group = "verification"
|
||||||
|
description = "Verifies 16 KiB LOAD alignment for every 64-bit Android native library."
|
||||||
|
dependsOn("mergeReleaseNativeLibs")
|
||||||
|
|
||||||
|
val mergedNativeLibs = layout.buildDirectory.dir(
|
||||||
|
"intermediates/merged_native_libs/release/mergeReleaseNativeLibs/out/lib"
|
||||||
|
)
|
||||||
|
inputs.dir(mergedNativeLibs)
|
||||||
|
|
||||||
|
commandLine(
|
||||||
|
"bash",
|
||||||
|
"-lc",
|
||||||
|
"""
|
||||||
|
set -euo pipefail
|
||||||
|
lib_root="${'$'}1"
|
||||||
|
sdk_dir="${'$'}2"
|
||||||
|
readelf_bin="$(command -v readelf || true)"
|
||||||
|
if [ -z "${'$'}readelf_bin" ] && [ -n "${'$'}sdk_dir" ]; then
|
||||||
|
readelf_bin="$(ls -d "${'$'}sdk_dir"/ndk/*/toolchains/llvm/prebuilt/linux-x86_64/bin/llvm-readelf 2>/dev/null | sort -V | tail -n 1)"
|
||||||
|
fi
|
||||||
|
if [ -z "${'$'}readelf_bin" ] || [ ! -x "${'$'}readelf_bin" ]; then
|
||||||
|
echo "readelf is required to verify Android native page alignment." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
found=0
|
||||||
|
for abi in arm64-v8a x86_64; do
|
||||||
|
abi_dir="${'$'}lib_root/${'$'}abi"
|
||||||
|
[ -d "${'$'}abi_dir" ] || continue
|
||||||
|
while IFS= read -r -d '' library; do
|
||||||
|
found=1
|
||||||
|
while IFS= read -r alignment; do
|
||||||
|
value=${'$'}((alignment))
|
||||||
|
if [ "${'$'}value" -lt 16384 ]; then
|
||||||
|
echo "Native library is not compatible with 16 KiB pages: ${'$'}library (LOAD align=${'$'}alignment)" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
done < <("${'$'}readelf_bin" -lW "${'$'}library" | awk '${'$'}1 == "LOAD" { print ${'$'}NF }')
|
||||||
|
done < <(find "${'$'}abi_dir" -type f -name '*.so' -print0)
|
||||||
|
done
|
||||||
|
if [ "${'$'}found" -ne 1 ]; then
|
||||||
|
echo "No 64-bit Android native libraries found under ${'$'}lib_root." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "All 64-bit Android native libraries use 16 KiB-compatible LOAD alignment."
|
||||||
|
""".trimIndent(),
|
||||||
|
"bash",
|
||||||
|
mergedNativeLibs.get().asFile.absolutePath,
|
||||||
|
androidSdkDir.orEmpty(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
tasks.matching { it.name == "packageRelease" }.configureEach {
|
||||||
|
dependsOn(verify16KbNativeLibraries)
|
||||||
|
}
|
||||||
|
|
||||||
tasks.matching {
|
tasks.matching {
|
||||||
it.name.startsWith("merge") &&
|
it.name.startsWith("merge") &&
|
||||||
(it.name.endsWith("NativeLibs") || it.name.endsWith("JniLibFolders"))
|
(it.name.endsWith("NativeLibs") || it.name.endsWith("JniLibFolders"))
|
||||||
@@ -389,7 +449,7 @@ dependencies {
|
|||||||
implementation("androidx.lifecycle:lifecycle-runtime-compose:2.8.7")
|
implementation("androidx.lifecycle:lifecycle-runtime-compose:2.8.7")
|
||||||
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.8.7")
|
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.8.7")
|
||||||
implementation("androidx.datastore:datastore-preferences:1.1.1")
|
implementation("androidx.datastore:datastore-preferences:1.1.1")
|
||||||
implementation("com.wireguard.android:tunnel:1.0.20230706")
|
implementation("com.wireguard.android:tunnel:1.0.20260102")
|
||||||
implementation("com.github.mwiede:jsch:0.2.16")
|
implementation("com.github.mwiede:jsch:0.2.16")
|
||||||
implementation("org.bouncycastle:bcprov-jdk18on:1.79")
|
implementation("org.bouncycastle:bcprov-jdk18on:1.79")
|
||||||
implementation("com.journeyapps:zxing-android-embedded:4.3.0")
|
implementation("com.journeyapps:zxing-android-embedded:4.3.0")
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
Cloudflare WARP MASQUE interoperability code is adapted from
|
||||||
|
https://github.com/Diniboy1123/usque
|
||||||
|
commit 6aa03fc97d12848dce34eedbd187fb1077b5d1ea.
|
||||||
|
|
||||||
|
The MIT License (MIT)
|
||||||
|
|
||||||
|
Copyright © 2025, github.com/Diniboy1123
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||||
|
this software and associated documentation files (the “Software”), to deal in
|
||||||
|
the Software without restriction, including without limitation the rights to
|
||||||
|
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||||
|
the Software, and to permit persons to whom the Software is furnished to do so,
|
||||||
|
subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
@@ -98,6 +98,10 @@ data class AccessLifecycleStatus(
|
|||||||
val detailLabel: String = "",
|
val detailLabel: String = "",
|
||||||
val detailValue: String = "",
|
val detailValue: String = "",
|
||||||
val actionIcon: String = "",
|
val actionIcon: String = "",
|
||||||
|
val continuationAvailable: Boolean? = null,
|
||||||
|
val continuationExpiresAtSeconds: Long? = null,
|
||||||
|
val dismissible: Boolean? = null,
|
||||||
|
val dismissedMessage: String = "",
|
||||||
val severity: AccessLifecycleSeverity = AccessLifecycleSeverity.NORMAL,
|
val severity: AccessLifecycleSeverity = AccessLifecycleSeverity.NORMAL,
|
||||||
val checkedAtMillis: Long = System.currentTimeMillis(),
|
val checkedAtMillis: Long = System.currentTimeMillis(),
|
||||||
val profileRevision: Long = 0,
|
val profileRevision: Long = 0,
|
||||||
@@ -125,6 +129,10 @@ data class AccessLifecycleUiState(
|
|||||||
val detailLabel: String = "",
|
val detailLabel: String = "",
|
||||||
val detailValue: String = "",
|
val detailValue: String = "",
|
||||||
val actionIcon: String = "",
|
val actionIcon: String = "",
|
||||||
|
val continuationAvailable: Boolean? = null,
|
||||||
|
val continuationExpiresAtSeconds: Long? = null,
|
||||||
|
val dismissible: Boolean? = null,
|
||||||
|
val dismissedMessage: String = "",
|
||||||
val severity: AccessLifecycleSeverity,
|
val severity: AccessLifecycleSeverity,
|
||||||
val checkedAtMillis: Long,
|
val checkedAtMillis: Long,
|
||||||
) {
|
) {
|
||||||
@@ -140,6 +148,10 @@ data class AccessLifecycleUiState(
|
|||||||
detailLabel = "",
|
detailLabel = "",
|
||||||
detailValue = "",
|
detailValue = "",
|
||||||
actionIcon = "",
|
actionIcon = "",
|
||||||
|
continuationAvailable = null,
|
||||||
|
continuationExpiresAtSeconds = null,
|
||||||
|
dismissible = null,
|
||||||
|
dismissedMessage = "",
|
||||||
severity = AccessLifecycleSeverity.NORMAL,
|
severity = AccessLifecycleSeverity.NORMAL,
|
||||||
checkedAtMillis = 0,
|
checkedAtMillis = 0,
|
||||||
)
|
)
|
||||||
@@ -157,9 +169,29 @@ internal fun accessLifecycleDismissalSignature(
|
|||||||
lifecycle.message,
|
lifecycle.message,
|
||||||
lifecycle.detailLabel,
|
lifecycle.detailLabel,
|
||||||
lifecycle.detailValue,
|
lifecycle.detailValue,
|
||||||
|
lifecycle.continuationAvailable,
|
||||||
|
lifecycle.continuationExpiresAtSeconds,
|
||||||
|
lifecycle.dismissible,
|
||||||
|
lifecycle.dismissedMessage,
|
||||||
).joinToString("|")
|
).joinToString("|")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal fun accessLifecycleCanDismiss(lifecycle: AccessLifecycleUiState): Boolean =
|
||||||
|
lifecycle.dismissible ?: (
|
||||||
|
lifecycle.allowConnect && lifecycle.severity == AccessLifecycleSeverity.WARNING
|
||||||
|
)
|
||||||
|
|
||||||
|
internal fun boundContinuationAvailable(
|
||||||
|
hasCredential: Boolean,
|
||||||
|
hasEndpoint: Boolean,
|
||||||
|
remoteAvailability: Boolean?,
|
||||||
|
expiresAtSeconds: Long? = null,
|
||||||
|
nowSeconds: Long = System.currentTimeMillis() / 1_000L,
|
||||||
|
): Boolean = hasCredential &&
|
||||||
|
hasEndpoint &&
|
||||||
|
remoteAvailability != false &&
|
||||||
|
(expiresAtSeconds == null || expiresAtSeconds == 0L || expiresAtSeconds > nowSeconds)
|
||||||
|
|
||||||
internal fun StoredAccessLifecycle.toUiState(): AccessLifecycleUiState {
|
internal fun StoredAccessLifecycle.toUiState(): AccessLifecycleUiState {
|
||||||
val current = status
|
val current = status
|
||||||
return AccessLifecycleUiState(
|
return AccessLifecycleUiState(
|
||||||
@@ -173,6 +205,10 @@ internal fun StoredAccessLifecycle.toUiState(): AccessLifecycleUiState {
|
|||||||
detailLabel = current?.detailLabel.orEmpty(),
|
detailLabel = current?.detailLabel.orEmpty(),
|
||||||
detailValue = current?.detailValue.orEmpty(),
|
detailValue = current?.detailValue.orEmpty(),
|
||||||
actionIcon = current?.actionIcon.orEmpty(),
|
actionIcon = current?.actionIcon.orEmpty(),
|
||||||
|
continuationAvailable = current?.continuationAvailable,
|
||||||
|
continuationExpiresAtSeconds = current?.continuationExpiresAtSeconds,
|
||||||
|
dismissible = current?.dismissible,
|
||||||
|
dismissedMessage = current?.dismissedMessage.orEmpty(),
|
||||||
severity = current?.severity ?: AccessLifecycleSeverity.NORMAL,
|
severity = current?.severity ?: AccessLifecycleSeverity.NORMAL,
|
||||||
checkedAtMillis = current?.checkedAtMillis ?: 0,
|
checkedAtMillis = current?.checkedAtMillis ?: 0,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -3,12 +3,14 @@ package com.wdtt.plus
|
|||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
import kotlinx.coroutines.CancellationException
|
import kotlinx.coroutines.CancellationException
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
import kotlinx.coroutines.flow.asStateFlow
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
import kotlinx.coroutines.sync.Mutex
|
import kotlinx.coroutines.sync.Mutex
|
||||||
import kotlinx.coroutines.sync.withLock
|
import kotlinx.coroutines.sync.withLock
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
import java.util.TimeZone
|
import java.util.TimeZone
|
||||||
|
|
||||||
sealed interface AccessLifecycleRefreshResult {
|
sealed interface AccessLifecycleRefreshResult {
|
||||||
@@ -35,6 +37,14 @@ object AccessLifecycleCoordinator {
|
|||||||
context: Context,
|
context: Context,
|
||||||
profileIndex: Int,
|
profileIndex: Int,
|
||||||
force: Boolean = false,
|
force: Boolean = false,
|
||||||
|
): AccessLifecycleRefreshResult = withContext(Dispatchers.IO) {
|
||||||
|
refreshProfileOnWorker(context, profileIndex, force)
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun refreshProfileOnWorker(
|
||||||
|
context: Context,
|
||||||
|
profileIndex: Int,
|
||||||
|
force: Boolean = false,
|
||||||
): AccessLifecycleRefreshResult {
|
): AccessLifecycleRefreshResult {
|
||||||
val appContext = context.applicationContext
|
val appContext = context.applicationContext
|
||||||
val profile = profileIndex.coerceIn(0, 2)
|
val profile = profileIndex.coerceIn(0, 2)
|
||||||
@@ -60,7 +70,9 @@ object AccessLifecycleCoordinator {
|
|||||||
val current = store.accessLifecycleForProfile(profile)
|
val current = store.accessLifecycleForProfile(profile)
|
||||||
val currentNow = System.currentTimeMillis()
|
val currentNow = System.currentTimeMillis()
|
||||||
if (!current.capability.available) return@withLock AccessLifecycleRefreshResult.Unmanaged
|
if (!current.capability.available) return@withLock AccessLifecycleRefreshResult.Unmanaged
|
||||||
syncPendingProfileValues(store, profile, current.capability)
|
if (current.status?.continuationAvailable != false) {
|
||||||
|
syncPendingProfileValues(store, profile, current.capability)
|
||||||
|
}
|
||||||
if (
|
if (
|
||||||
!force &&
|
!force &&
|
||||||
current.status != null &&
|
current.status != null &&
|
||||||
@@ -104,6 +116,20 @@ object AccessLifecycleCoordinator {
|
|||||||
) {
|
) {
|
||||||
return@withLock AccessLifecycleRefreshResult.Unmanaged
|
return@withLock AccessLifecycleRefreshResult.Unmanaged
|
||||||
}
|
}
|
||||||
|
if (received.continuationAvailable != false) {
|
||||||
|
try {
|
||||||
|
syncPendingProfileValues(store, profile, effectiveCapability)
|
||||||
|
} catch (cancelled: CancellationException) {
|
||||||
|
throw cancelled
|
||||||
|
} catch (error: Exception) {
|
||||||
|
TunnelManager.noteAccessLifecycleEvent(
|
||||||
|
key = "profile_${profile}_values_sync_failed",
|
||||||
|
message = error.message
|
||||||
|
?: "Не удалось обновить сохранённые данные профиля",
|
||||||
|
warning = true,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
val profileUpdated = applyProfileUpdateIfNeeded(
|
val profileUpdated = applyProfileUpdateIfNeeded(
|
||||||
appContext = appContext,
|
appContext = appContext,
|
||||||
store = store,
|
store = store,
|
||||||
@@ -478,22 +504,17 @@ object AccessLifecycleCoordinator {
|
|||||||
require(binding.isNotBlank() && delivery.binding == binding) {
|
require(binding.isNotBlank() && delivery.binding == binding) {
|
||||||
"Обновление относится к другому профилю."
|
"Обновление относится к другому профилю."
|
||||||
}
|
}
|
||||||
val applied = store.applyWdttDeepLink(
|
val applied = store.applyRemoteDocumentDelivery(
|
||||||
plan = WdttDeepLinkApplyPlan(
|
plan = WdttDeepLinkApplyPlan(
|
||||||
link = delivery.document,
|
link = delivery.document,
|
||||||
targetProfile = profile,
|
targetProfile = profile,
|
||||||
requiresConfirmation = false,
|
requiresConfirmation = false,
|
||||||
storeAsLink = false,
|
storeAsLink = false,
|
||||||
),
|
),
|
||||||
resetRemoteContinuation = false,
|
delivery = delivery,
|
||||||
profileMaxWorkers = delivery.profileMaxWorkers,
|
isBoundUpdate = true,
|
||||||
remoteManaged = null,
|
|
||||||
preserveVkHashes = true,
|
|
||||||
)
|
)
|
||||||
require(applied != null) { "Не удалось применить обновление профиля." }
|
require(applied != null) { "Не удалось применить обновление профиля." }
|
||||||
if (delivery.access.available) {
|
|
||||||
store.saveRemoteAccessCapability(delivery.access, profile)
|
|
||||||
}
|
|
||||||
store.saveAppliedAccessProfileRevision(profile, update.revision)
|
store.saveAppliedAccessProfileRevision(profile, update.revision)
|
||||||
requestTunnelProfileRuntimeUpdate(profile)
|
requestTunnelProfileRuntimeUpdate(profile)
|
||||||
TunnelManager.noteAccessLifecycleEvent(
|
TunnelManager.noteAccessLifecycleEvent(
|
||||||
|
|||||||
@@ -246,6 +246,17 @@ object AccessLifecycleGateway {
|
|||||||
val actionIcon = action?.optString("icon").orEmpty().trim().take(32)
|
val actionIcon = action?.optString("icon").orEmpty().trim().take(32)
|
||||||
.takeIf { it == "update" }
|
.takeIf { it == "update" }
|
||||||
.orEmpty()
|
.orEmpty()
|
||||||
|
val continuationAvailable = root.optJSONObject("continuation")
|
||||||
|
?.takeIf { it.has("available") }
|
||||||
|
?.optBoolean("available", false)
|
||||||
|
val continuationExpiresAtSeconds = root.optJSONObject("continuation")
|
||||||
|
?.takeIf { it.has("expires") }
|
||||||
|
?.optLong("expires", 0L)
|
||||||
|
?.coerceAtLeast(0L)
|
||||||
|
val dismissible = root
|
||||||
|
.takeIf { it.has("dismissible") }
|
||||||
|
?.optBoolean("dismissible", false)
|
||||||
|
val dismissedMessage = root.optString("dismissed_message").trim().take(400)
|
||||||
val title = root.optString("title").trim().take(120)
|
val title = root.optString("title").trim().take(120)
|
||||||
val message = root.optString("message").trim().take(400)
|
val message = root.optString("message").trim().take(400)
|
||||||
val detail = root.optJSONObject("detail")
|
val detail = root.optJSONObject("detail")
|
||||||
@@ -281,6 +292,10 @@ object AccessLifecycleGateway {
|
|||||||
detailLabel = detailLabel,
|
detailLabel = detailLabel,
|
||||||
detailValue = detailValue,
|
detailValue = detailValue,
|
||||||
actionIcon = actionIcon,
|
actionIcon = actionIcon,
|
||||||
|
continuationAvailable = continuationAvailable,
|
||||||
|
continuationExpiresAtSeconds = continuationExpiresAtSeconds,
|
||||||
|
dismissible = dismissible,
|
||||||
|
dismissedMessage = dismissedMessage,
|
||||||
severity = severity,
|
severity = severity,
|
||||||
profileRevision = revision,
|
profileRevision = revision,
|
||||||
profileUpdate = update,
|
profileUpdate = update,
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import android.net.NetworkCapabilities
|
|||||||
import android.os.Build
|
import android.os.Build
|
||||||
import android.os.CancellationSignal
|
import android.os.CancellationSignal
|
||||||
import android.os.SystemClock
|
import android.os.SystemClock
|
||||||
|
import android.telephony.SubscriptionManager
|
||||||
import android.telephony.TelephonyManager
|
import android.telephony.TelephonyManager
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.CancellationException
|
import kotlinx.coroutines.CancellationException
|
||||||
@@ -111,6 +112,12 @@ private val vkHttpsTargets = listOf(
|
|||||||
)
|
)
|
||||||
|
|
||||||
suspend fun collectClientNetworkDiagnostics(context: Context): ClientNetworkDiagnosticsReport =
|
suspend fun collectClientNetworkDiagnostics(context: Context): ClientNetworkDiagnosticsReport =
|
||||||
|
collectClientNetworkDiagnostics(context, retryOnNetworkChange = true)
|
||||||
|
|
||||||
|
private suspend fun collectClientNetworkDiagnostics(
|
||||||
|
context: Context,
|
||||||
|
retryOnNetworkChange: Boolean
|
||||||
|
): ClientNetworkDiagnosticsReport =
|
||||||
withContext(Dispatchers.IO) {
|
withContext(Dispatchers.IO) {
|
||||||
val connectivityManager = context.getSystemService(ConnectivityManager::class.java)
|
val connectivityManager = context.getSystemService(ConnectivityManager::class.java)
|
||||||
val diagnosticNetwork = connectivityManager?.let { selectDiagnosticNetwork(context, it) }
|
val diagnosticNetwork = connectivityManager?.let { selectDiagnosticNetwork(context, it) }
|
||||||
@@ -138,6 +145,28 @@ suspend fun collectClientNetworkDiagnostics(context: Context): ClientNetworkDiag
|
|||||||
Triple(systemDns.await(), clientDns.await(), vkHttps.await())
|
Triple(systemDns.await(), clientDns.await(), vkHttps.await())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
val networkAfterProbes = selectDiagnosticNetwork(context, connectivityManager)
|
||||||
|
if (networkAfterProbes?.network != diagnosticNetwork.network) {
|
||||||
|
if (retryOnNetworkChange && networkAfterProbes != null) {
|
||||||
|
val retried = collectClientNetworkDiagnostics(
|
||||||
|
context,
|
||||||
|
retryOnNetworkChange = false
|
||||||
|
)
|
||||||
|
return@withContext retried.copy(
|
||||||
|
summaryLines = listOf(
|
||||||
|
"Сеть изменилась во время диагностики; проверки автоматически повторены на новой сети"
|
||||||
|
) + retried.summaryLines,
|
||||||
|
items = listOf(networkChangeItem(retried = true)) + retried.items
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return@withContext ClientNetworkDiagnosticsReport(
|
||||||
|
summaryLines = listOf(
|
||||||
|
"Сеть изменилась во время диагностики; результаты устаревшей сети отброшены"
|
||||||
|
),
|
||||||
|
items = listOf(networkChangeItem(retried = false))
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
val primaryDnsResults = dnsResults.filter { it.label in primaryVkDiagnosticHosts }
|
val primaryDnsResults = dnsResults.filter { it.label in primaryVkDiagnosticHosts }
|
||||||
val reserveDnsResults = dnsResults.filter { it.label in reserveVkDiagnosticHosts }
|
val reserveDnsResults = dnsResults.filter { it.label in reserveVkDiagnosticHosts }
|
||||||
val primaryDnsOk = primaryDnsResults.count { it.success }
|
val primaryDnsOk = primaryDnsResults.count { it.success }
|
||||||
@@ -287,18 +316,45 @@ private fun selectDiagnosticNetwork(context: Context, connectivityManager: Conne
|
|||||||
private fun mobileOperatorSummary(context: Context, capabilities: NetworkCapabilities): String {
|
private fun mobileOperatorSummary(context: Context, capabilities: NetworkCapabilities): String {
|
||||||
if (!capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) return "не применяется"
|
if (!capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) return "не применяется"
|
||||||
return runCatching {
|
return runCatching {
|
||||||
val telephonyManager = context.getSystemService(TelephonyManager::class.java)
|
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
|
||||||
val network = telephonyManager?.networkOperatorName.orEmpty().trim()
|
return@runCatching "не определён для выбранной сети на этой версии Android"
|
||||||
val sim = telephonyManager?.simOperatorName.orEmpty().trim()
|
}
|
||||||
val names = listOf(network, sim).filter(String::isNotBlank).distinct()
|
val dataSubscriptionId = SubscriptionManager.getDefaultDataSubscriptionId()
|
||||||
|
if (dataSubscriptionId < 0) {
|
||||||
|
return@runCatching "не определён для выбранной data-SIM"
|
||||||
|
}
|
||||||
|
val baseManager = context.getSystemService(TelephonyManager::class.java)
|
||||||
|
val manager = baseManager?.createForSubscriptionId(dataSubscriptionId)
|
||||||
|
?: return@runCatching "телефонная служба недоступна"
|
||||||
|
val names = listOf(manager.networkOperatorName, manager.simOperatorName)
|
||||||
|
.map(String::trim)
|
||||||
|
.filter(String::isNotBlank)
|
||||||
|
.distinct()
|
||||||
buildString {
|
buildString {
|
||||||
append(names.joinToString(" / ").ifBlank { "не определён" })
|
append(names.joinToString(" / ").ifBlank { "не определён" })
|
||||||
append(", roaming=")
|
append(", roaming=")
|
||||||
append(telephonyManager?.isNetworkRoaming ?: false)
|
append(manager.isNetworkRoaming)
|
||||||
|
append(", основная data-SIM")
|
||||||
}
|
}
|
||||||
}.getOrDefault("недоступен")
|
}.getOrDefault("недоступен")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun networkChangeItem(retried: Boolean): DeviceCheckItem = DeviceCheckItem(
|
||||||
|
title = "Смена сети во время диагностики",
|
||||||
|
status = if (retried) "проверки повторены" else "результаты отброшены",
|
||||||
|
details = if (retried) {
|
||||||
|
"Android сменил физическую сеть или мобильную data-SIM во время проверки. " +
|
||||||
|
"Результаты старой сети не использованы; пункты ниже относятся к новой сети."
|
||||||
|
} else {
|
||||||
|
"Android сменил физическую сеть или мобильную data-SIM, поэтому ошибки старого " +
|
||||||
|
"сетевого дескриптора (например ENONET/ENETUNREACH) не считаются отказом DNS или устройства."
|
||||||
|
},
|
||||||
|
recommendation = if (retried) "" else
|
||||||
|
"Дождитесь устойчивого подключения к нужной сети и повторите проверку устройства.",
|
||||||
|
severity = if (retried) DeviceCheckSeverity.Info else DeviceCheckSeverity.Warning,
|
||||||
|
action = if (retried) null else DeviceCheckAction.NetworkSettings
|
||||||
|
)
|
||||||
|
|
||||||
private fun buildNetworkPathItem(network: DiagnosticNetwork): DeviceCheckItem {
|
private fun buildNetworkPathItem(network: DiagnosticNetwork): DeviceCheckItem {
|
||||||
val capabilities = network.capabilities
|
val capabilities = network.capabilities
|
||||||
val validated = capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
|
val validated = capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
|
||||||
@@ -542,6 +598,8 @@ private fun buildRecentNetworkEventsItem(): DeviceCheckItem? {
|
|||||||
entry.key.startsWith("vk_credentials_") ||
|
entry.key.startsWith("vk_credentials_") ||
|
||||||
entry.key.startsWith("vk_legacy_") ||
|
entry.key.startsWith("vk_legacy_") ||
|
||||||
entry.key.startsWith("turn_") ||
|
entry.key.startsWith("turn_") ||
|
||||||
|
entry.key.startsWith("rt_") ||
|
||||||
|
entry.key.startsWith("masque_") ||
|
||||||
entry.key.startsWith("worker_turn_")
|
entry.key.startsWith("worker_turn_")
|
||||||
}
|
}
|
||||||
.take(12)
|
.take(12)
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import android.provider.Settings
|
|||||||
import android.system.Os
|
import android.system.Os
|
||||||
import android.system.OsConstants
|
import android.system.OsConstants
|
||||||
import android.webkit.WebView
|
import android.webkit.WebView
|
||||||
|
import org.json.JSONObject
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.text.SimpleDateFormat
|
import java.text.SimpleDateFormat
|
||||||
import java.util.Date
|
import java.util.Date
|
||||||
@@ -97,6 +98,70 @@ data class DeviceCompatibilityReport(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal enum class RtMasqueEnrollmentState {
|
||||||
|
Missing,
|
||||||
|
Ready,
|
||||||
|
Invalid,
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun inspectRtMasqueEnrollment(file: File): RtMasqueEnrollmentState {
|
||||||
|
if (!file.isFile) return RtMasqueEnrollmentState.Missing
|
||||||
|
if (file.length() !in 1L..128L * 1024L) return RtMasqueEnrollmentState.Invalid
|
||||||
|
return runCatching {
|
||||||
|
val json = JSONObject(file.readText(Charsets.UTF_8))
|
||||||
|
val requiredFields = listOf(
|
||||||
|
"private_key",
|
||||||
|
"endpoint_v4",
|
||||||
|
"endpoint_pub_key",
|
||||||
|
"ipv4",
|
||||||
|
)
|
||||||
|
if (
|
||||||
|
json.optInt("version", -1) != 1 ||
|
||||||
|
requiredFields.any { json.optString(it).isBlank() }
|
||||||
|
) {
|
||||||
|
RtMasqueEnrollmentState.Invalid
|
||||||
|
} else {
|
||||||
|
RtMasqueEnrollmentState.Ready
|
||||||
|
}
|
||||||
|
}.getOrDefault(RtMasqueEnrollmentState.Invalid)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun pageSizeCompatibilityItem(
|
||||||
|
pageSize: Long?,
|
||||||
|
processIs64Bit: Boolean,
|
||||||
|
): DeviceCheckItem = when {
|
||||||
|
pageSize == null || pageSize <= 0L -> DeviceCheckItem(
|
||||||
|
title = "Страница памяти",
|
||||||
|
status = "не удалось определить",
|
||||||
|
details = "Android не вернул размер страницы памяти.",
|
||||||
|
recommendation = "Если VPN не стартует на новом устройстве, скопируйте отчёт через «Проверить устройство».",
|
||||||
|
severity = DeviceCheckSeverity.Info,
|
||||||
|
firstLaunchRelevant = false,
|
||||||
|
)
|
||||||
|
pageSize == 16L * 1024L && processIs64Bit -> DeviceCheckItem(
|
||||||
|
title = "Страница памяти",
|
||||||
|
status = "16 КиБ · поддерживается",
|
||||||
|
details = "Устройство использует страницы памяти 16 КиБ. Все 64-битные нативные библиотеки release-сборки WDTT Plus проверяются на совместимое LOAD-выравнивание.",
|
||||||
|
severity = DeviceCheckSeverity.Ok,
|
||||||
|
firstLaunchRelevant = true,
|
||||||
|
)
|
||||||
|
pageSize > 4096L -> DeviceCheckItem(
|
||||||
|
title = "Страница памяти",
|
||||||
|
status = "$pageSize байт · требуется проверка",
|
||||||
|
details = "Android использует нестандартный для этой ABI размер страницы памяти, который нельзя подтвердить как штатный 16-КиБ режим текущей 64-битной сборки.",
|
||||||
|
recommendation = "Если туннель не стартует, установите подходящий APK и отправьте отчёт из «Проверить устройство».",
|
||||||
|
severity = DeviceCheckSeverity.Warning,
|
||||||
|
firstLaunchRelevant = true,
|
||||||
|
)
|
||||||
|
else -> DeviceCheckItem(
|
||||||
|
title = "Страница памяти",
|
||||||
|
status = "$pageSize байт",
|
||||||
|
details = "Размер страницы памяти поддерживается текущей нативной сборкой.",
|
||||||
|
severity = DeviceCheckSeverity.Ok,
|
||||||
|
firstLaunchRelevant = true,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
object DeviceCompatibility {
|
object DeviceCompatibility {
|
||||||
const val APP_VERSION_ITEM_TITLE = "Версия WDTT Plus"
|
const val APP_VERSION_ITEM_TITLE = "Версия WDTT Plus"
|
||||||
private const val MIN_RECOMMENDED_SDK = 29
|
private const val MIN_RECOMMENDED_SDK = 29
|
||||||
@@ -112,7 +177,7 @@ object DeviceCompatibility {
|
|||||||
val items = buildList {
|
val items = buildList {
|
||||||
add(androidVersionItem())
|
add(androidVersionItem())
|
||||||
add(abiItem())
|
add(abiItem())
|
||||||
add(nativeClientItem(appContext))
|
add(nativeComponentsItem(appContext))
|
||||||
nativeRuntimeSafetyItem()?.let(::add)
|
nativeRuntimeSafetyItem()?.let(::add)
|
||||||
add(pageSizeItem())
|
add(pageSizeItem())
|
||||||
add(memoryClassItem(appContext, workersPerHash))
|
add(memoryClassItem(appContext, workersPerHash))
|
||||||
@@ -231,30 +296,27 @@ object DeviceCompatibility {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun nativeClientItem(context: Context): DeviceCheckItem {
|
private fun nativeComponentsItem(context: Context): DeviceCheckItem {
|
||||||
val nativeLibraryDir = context.applicationInfo.nativeLibraryDir.orEmpty()
|
val nativeLibraryDir = context.applicationInfo.nativeLibraryDir.orEmpty()
|
||||||
val nativeClient = File(nativeLibraryDir, "libclient.so")
|
val nativeClient = File(nativeLibraryDir, "libclient.so")
|
||||||
|
val wireGuardBackend = File(nativeLibraryDir, "libwg-go.so")
|
||||||
|
val missing = buildList {
|
||||||
|
if (!nativeClient.isFile || nativeClient.length() <= 0L) add("libclient.so")
|
||||||
|
if (!wireGuardBackend.isFile || wireGuardBackend.length() <= 0L) add("libwg-go.so")
|
||||||
|
}
|
||||||
return when {
|
return when {
|
||||||
!nativeClient.isFile -> DeviceCheckItem(
|
missing.isNotEmpty() -> DeviceCheckItem(
|
||||||
title = "Нативный клиент",
|
title = "Нативные компоненты",
|
||||||
status = "libclient.so не найден",
|
status = "не найдены: ${missing.joinToString()}",
|
||||||
details = "Android-часть запустилась, но нативный Go-клиент, который поднимает TURN/DTLS транспорт, в установленном APK не найден.",
|
details = "В установленном APK отсутствует или повреждён нативный клиент TURN/DTLS либо WireGuard backend системного VPN.",
|
||||||
recommendation = "Переустановите APK нужной ABI или universal APK из официального релиза WDTT Plus.",
|
recommendation = "Переустановите APK нужной ABI или universal APK из официального релиза WDTT Plus.",
|
||||||
severity = DeviceCheckSeverity.Error,
|
severity = DeviceCheckSeverity.Error,
|
||||||
firstLaunchRelevant = true
|
firstLaunchRelevant = true
|
||||||
)
|
)
|
||||||
nativeClient.length() <= 0L -> DeviceCheckItem(
|
|
||||||
title = "Нативный клиент",
|
|
||||||
status = "libclient.so пустой",
|
|
||||||
details = "Файл нативного клиента найден, но его размер равен нулю.",
|
|
||||||
recommendation = "Переустановите APK; текущая установка выглядит повреждённой.",
|
|
||||||
severity = DeviceCheckSeverity.Error,
|
|
||||||
firstLaunchRelevant = true
|
|
||||||
)
|
|
||||||
else -> DeviceCheckItem(
|
else -> DeviceCheckItem(
|
||||||
title = "Нативный клиент",
|
title = "Нативные компоненты",
|
||||||
status = "найден",
|
status = "клиент и WireGuard найдены",
|
||||||
details = "libclient.so найден в установленном APK, размер: ${formatMiB(nativeClient.length())}.",
|
details = "libclient.so: ${formatMiB(nativeClient.length())}; libwg-go.so: ${formatMiB(wireGuardBackend.length())}.",
|
||||||
severity = DeviceCheckSeverity.Ok,
|
severity = DeviceCheckSeverity.Ok,
|
||||||
firstLaunchRelevant = true
|
firstLaunchRelevant = true
|
||||||
)
|
)
|
||||||
@@ -263,29 +325,56 @@ object DeviceCompatibility {
|
|||||||
|
|
||||||
private fun pageSizeItem(): DeviceCheckItem {
|
private fun pageSizeItem(): DeviceCheckItem {
|
||||||
val pageSize = runCatching { Os.sysconf(OsConstants._SC_PAGESIZE) }.getOrNull()
|
val pageSize = runCatching { Os.sysconf(OsConstants._SC_PAGESIZE) }.getOrNull()
|
||||||
|
return pageSizeCompatibilityItem(pageSize, android.os.Process.is64Bit())
|
||||||
|
}
|
||||||
|
|
||||||
|
fun rtNetworkModeItem(context: Context, profile: TunnelProfileSnapshot): DeviceCheckItem {
|
||||||
|
val enrollment = inspectRtMasqueEnrollment(
|
||||||
|
File(context.filesDir, RT_MASQUE_CONFIG_FILE_NAME)
|
||||||
|
)
|
||||||
return when {
|
return when {
|
||||||
pageSize == null || pageSize <= 0L -> DeviceCheckItem(
|
!profile.rtNetwork -> DeviceCheckItem(
|
||||||
title = "Страница памяти",
|
title = "Режим Сеть РТ",
|
||||||
status = "не удалось определить",
|
status = "выключен",
|
||||||
details = "Android не вернул размер страницы памяти.",
|
details = "Используется обычный порядок транспортов; настройки РТ этого профиля не влияют на подключение.",
|
||||||
recommendation = "Если VPN не стартует на новом устройстве, скопируйте отчёт через «Проверить устройство».",
|
|
||||||
severity = DeviceCheckSeverity.Info,
|
severity = DeviceCheckSeverity.Info,
|
||||||
firstLaunchRelevant = false
|
|
||||||
)
|
)
|
||||||
pageSize > 4096L -> DeviceCheckItem(
|
!profile.rtMasque -> DeviceCheckItem(
|
||||||
title = "Страница памяти",
|
title = "Режим Сеть РТ",
|
||||||
status = "$pageSize байт",
|
status = "TURN/TLS и TCP включены · MASQUE выключен",
|
||||||
details = "Устройство использует страницу памяти больше 4 KB. Для новых Android-устройств с 16 KB page size нужна отдельная проверка нативной библиотеки.",
|
details = "Для активного профиля включён только основной механизм Сети РТ. Регистрация WARP не требуется.",
|
||||||
recommendation = "Запуск не блокируется. Если туннель не стартует, отправьте отчёт из «Проверить устройство» — это важный сценарий для будущей совместимости.",
|
severity = DeviceCheckSeverity.Ok,
|
||||||
|
)
|
||||||
|
profile.rtMasqueServerBootstrap && !profile.rtMasqueServerAccessReady -> DeviceCheckItem(
|
||||||
|
title = "Режим Сеть РТ",
|
||||||
|
status = "«Через сервер» настроен не полностью",
|
||||||
|
details = "MASQUE включён, но в активном профиле нет полного SSH-доступа из раздела «Деплой».",
|
||||||
|
recommendation = "Заполните адрес и пароль либо приватный SSH-ключ в «Деплой» или выключите «Через сервер».",
|
||||||
severity = DeviceCheckSeverity.Warning,
|
severity = DeviceCheckSeverity.Warning,
|
||||||
firstLaunchRelevant = true
|
)
|
||||||
|
enrollment == RtMasqueEnrollmentState.Invalid -> DeviceCheckItem(
|
||||||
|
title = "Режим Сеть РТ",
|
||||||
|
status = "регистрация WARP повреждена",
|
||||||
|
details = "Локальный файл регистрации MASQUE не содержит корректной структуры версии 1. Секретные поля в отчёт не включены.",
|
||||||
|
recommendation = "Остановите VPN и выполните «Сбросить регистрацию WARP» в инструкции MASQUE.",
|
||||||
|
severity = DeviceCheckSeverity.Warning,
|
||||||
|
)
|
||||||
|
enrollment == RtMasqueEnrollmentState.Missing -> DeviceCheckItem(
|
||||||
|
title = "Режим Сеть РТ",
|
||||||
|
status = "MASQUE включён · регистрация ещё не создана",
|
||||||
|
details = "При следующем запуске VPN приложение попробует зарегистрировать отдельное устройство WARP. Прямые TURN-пути продолжат работать во время подготовки.",
|
||||||
|
recommendation = if (profile.rtMasqueServerBootstrap) {
|
||||||
|
"Если прямой TLS Cloudflare недоступен, приложение сможет использовать SSH-выход активного профиля."
|
||||||
|
} else {
|
||||||
|
"Если регистрация не выполняется, проверьте журнал MASQUE; при необходимости настройте «Через сервер»."
|
||||||
|
},
|
||||||
|
severity = DeviceCheckSeverity.Info,
|
||||||
)
|
)
|
||||||
else -> DeviceCheckItem(
|
else -> DeviceCheckItem(
|
||||||
title = "Страница памяти",
|
title = "Режим Сеть РТ",
|
||||||
status = "$pageSize байт",
|
status = "MASQUE готов",
|
||||||
details = "Обычный размер страницы памяти для текущей нативной сборки.",
|
details = "Структура сохранённой регистрации WARP корректна; при запуске её дополнительно проверит нативный клиент.",
|
||||||
severity = DeviceCheckSeverity.Ok,
|
severity = DeviceCheckSeverity.Ok,
|
||||||
firstLaunchRelevant = true
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -124,6 +124,11 @@ internal fun shouldHandleIncomingIntent(
|
|||||||
|
|
||||||
private sealed interface WdttConnectFlow {
|
private sealed interface WdttConnectFlow {
|
||||||
data class Progress(val message: String) : WdttConnectFlow
|
data class Progress(val message: String) : WdttConnectFlow
|
||||||
|
data class SelectAttachmentProfile(
|
||||||
|
val link: RemoteDocumentLink,
|
||||||
|
val candidates: List<RemoteAttachmentCandidate>,
|
||||||
|
val selectedProfile: Int,
|
||||||
|
) : WdttConnectFlow
|
||||||
data class SelectProfile(
|
data class SelectProfile(
|
||||||
val plan: WdttDeepLinkApplyPlan,
|
val plan: WdttDeepLinkApplyPlan,
|
||||||
val delivery: RemoteDocumentDelivery
|
val delivery: RemoteDocumentDelivery
|
||||||
@@ -264,7 +269,9 @@ class MainActivity : ComponentActivity() {
|
|||||||
wdttDeepLinkMessage = message
|
wdttDeepLinkMessage = message
|
||||||
},
|
},
|
||||||
onSelectWdttDeepLinkOverwriteProfile = { profile ->
|
onSelectWdttDeepLinkOverwriteProfile = { profile ->
|
||||||
pendingWdttDeepLinkPlan = pendingWdttDeepLinkPlan?.copy(targetProfile = profile)
|
pendingWdttDeepLinkPlan = pendingWdttDeepLinkPlan?.let { plan ->
|
||||||
|
if (profile in plan.blockedProfiles) plan else plan.copy(targetProfile = profile)
|
||||||
|
}
|
||||||
},
|
},
|
||||||
onConfirmWdttDeepLinkOverwrite = { plan ->
|
onConfirmWdttDeepLinkOverwrite = { plan ->
|
||||||
pendingWdttDeepLinkPlan = null
|
pendingWdttDeepLinkPlan = null
|
||||||
@@ -276,7 +283,31 @@ class MainActivity : ComponentActivity() {
|
|||||||
},
|
},
|
||||||
onSelectWdttConnectProfile = { profile ->
|
onSelectWdttConnectProfile = { profile ->
|
||||||
(wdttConnectFlow as? WdttConnectFlow.SelectProfile)?.let { flow ->
|
(wdttConnectFlow as? WdttConnectFlow.SelectProfile)?.let { flow ->
|
||||||
wdttConnectFlow = flow.copy(plan = flow.plan.copy(targetProfile = profile))
|
if (profile !in flow.plan.blockedProfiles) {
|
||||||
|
wdttConnectFlow = flow.copy(
|
||||||
|
plan = flow.plan.copy(targetProfile = profile)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onSelectWdttAttachmentProfile = { profile ->
|
||||||
|
(wdttConnectFlow as? WdttConnectFlow.SelectAttachmentProfile)?.let { flow ->
|
||||||
|
if (flow.candidates.any { it.profileIndex == profile }) {
|
||||||
|
wdttConnectFlow = flow.copy(selectedProfile = profile)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onConfirmWdttAttachmentProfile = {
|
||||||
|
(wdttConnectFlow as? WdttConnectFlow.SelectAttachmentProfile)?.let { flow ->
|
||||||
|
flow.candidates.firstOrNull {
|
||||||
|
it.profileIndex == flow.selectedProfile
|
||||||
|
}?.let { candidate ->
|
||||||
|
receiveRemoteDocument(
|
||||||
|
flow.link,
|
||||||
|
candidate.document,
|
||||||
|
candidate.profileIndex,
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
onConfirmWdttConnectProfile = { plan ->
|
onConfirmWdttConnectProfile = { plan ->
|
||||||
@@ -496,19 +527,106 @@ class MainActivity : ComponentActivity() {
|
|||||||
receiveRemoteDocument(link)
|
receiveRemoteDocument(link)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun receiveRemoteDocument(link: RemoteDocumentLink) {
|
private fun receiveRemoteDocument(
|
||||||
|
link: RemoteDocumentLink,
|
||||||
|
localDocument: String? = null,
|
||||||
|
attachmentProfile: Int? = null,
|
||||||
|
) {
|
||||||
if (!remoteDocumentRequests.add(link.url)) return
|
if (!remoteDocumentRequests.add(link.url)) return
|
||||||
lifecycleScope.launch {
|
lifecycleScope.launch {
|
||||||
try {
|
try {
|
||||||
|
var requestedAttachmentProfile = attachmentProfile
|
||||||
wdttConnectFlow = WdttConnectFlow.Progress("Проверяем ссылку и получаем доступ...")
|
wdttConnectFlow = WdttConnectFlow.Progress("Проверяем ссылку и получаем доступ...")
|
||||||
val delivery = RemoteDocumentGateway.receive(
|
suspend fun request(
|
||||||
link = link,
|
document: String?,
|
||||||
device = settingsStore.getOrCreateConnectDeviceId(),
|
profileAttachment: Boolean = false,
|
||||||
label = vkHashDeviceName(),
|
): RemoteDocumentDelivery =
|
||||||
client = BuildConfig.VERSION_NAME,
|
RemoteDocumentGateway.receive(
|
||||||
system = Build.VERSION.RELEASE.orEmpty(),
|
link = link,
|
||||||
localBindings = settingsStore.remoteDocumentBindings(),
|
device = settingsStore.getOrCreateConnectDeviceId(),
|
||||||
)
|
label = vkHashDeviceName(),
|
||||||
|
client = BuildConfig.VERSION_NAME,
|
||||||
|
system = Build.VERSION.RELEASE.orEmpty(),
|
||||||
|
localBindings = settingsStore.remoteDocumentBindings(),
|
||||||
|
localDocument = document,
|
||||||
|
profileAttachment = profileAttachment,
|
||||||
|
)
|
||||||
|
val delivery = try {
|
||||||
|
request(
|
||||||
|
localDocument,
|
||||||
|
profileAttachment = attachmentProfile != null,
|
||||||
|
)
|
||||||
|
} catch (error: RemoteDocumentFailure) {
|
||||||
|
if (!error.profileAttachmentRequired || localDocument != null) throw error
|
||||||
|
val candidates = settingsStore.remoteAttachmentCandidates()
|
||||||
|
val selection = resolveRemoteAttachmentCandidates(
|
||||||
|
candidates = candidates,
|
||||||
|
)
|
||||||
|
when {
|
||||||
|
candidates.isEmpty() -> {
|
||||||
|
wdttConnectFlow = WdttConnectFlow.Failed(
|
||||||
|
"Все локальные профили уже заняты действующими удалёнными " +
|
||||||
|
"разрешениями или готовыми профилями. Освободите обычный " +
|
||||||
|
"профиль и откройте ссылку снова."
|
||||||
|
)
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
|
else -> {
|
||||||
|
wdttConnectFlow = WdttConnectFlow.SelectAttachmentProfile(
|
||||||
|
link = link,
|
||||||
|
candidates = selection.choices,
|
||||||
|
selectedProfile = selection.choices.first().profileIndex,
|
||||||
|
)
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (delivery.kind == RemoteDocumentKind.ATTACHMENT) {
|
||||||
|
val profile = requestedAttachmentProfile
|
||||||
|
?: settingsStore.profileForRemoteBinding(delivery.binding)
|
||||||
|
if (
|
||||||
|
profile == null ||
|
||||||
|
!settingsStore.applyRemoteCapabilityAttachment(profile, delivery)
|
||||||
|
) {
|
||||||
|
wdttConnectFlow = WdttConnectFlow.Failed(
|
||||||
|
"Не удалось сохранить разрешение в выбранном профиле."
|
||||||
|
)
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
|
val confirmedStatus = when (
|
||||||
|
val confirmation = AccessLifecycleCoordinator.refreshProfile(
|
||||||
|
this@MainActivity,
|
||||||
|
profile,
|
||||||
|
force = true,
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
is AccessLifecycleRefreshResult.Success -> confirmation.status
|
||||||
|
is AccessLifecycleRefreshResult.Cached -> confirmation.status
|
||||||
|
else -> {
|
||||||
|
wdttConnectFlow = WdttConnectFlow.Failed(
|
||||||
|
"Разрешение сохранено в выбранном профиле, но сервер пока " +
|
||||||
|
"не подтвердил привязку. Проверьте интернет и обновите " +
|
||||||
|
"карточку профиля."
|
||||||
|
)
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val confirmedContinuation =
|
||||||
|
if (confirmedStatus?.continuationAvailable == false) {
|
||||||
|
RemoteContinuation(
|
||||||
|
available = false,
|
||||||
|
message = delivery.continuation.message,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
delivery.continuation
|
||||||
|
}
|
||||||
|
wdttConnectFlow = WdttConnectFlow.SelectHashes(
|
||||||
|
profile = profile,
|
||||||
|
continuation = confirmedContinuation,
|
||||||
|
access = delivery.access,
|
||||||
|
)
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
wdttConnectFlow = WdttConnectFlow.Progress("Доступ получен. Подготавливаем VPN-профиль...")
|
wdttConnectFlow = WdttConnectFlow.Progress("Доступ получен. Подготавливаем VPN-профиль...")
|
||||||
var boundProfile: Int? = null
|
var boundProfile: Int? = null
|
||||||
for (binding in listOf(delivery.binding, delivery.access.binding)) {
|
for (binding in listOf(delivery.binding, delivery.access.binding)) {
|
||||||
@@ -516,6 +634,13 @@ class MainActivity : ComponentActivity() {
|
|||||||
boundProfile = settingsStore.profileForRemoteBinding(binding)
|
boundProfile = settingsStore.profileForRemoteBinding(binding)
|
||||||
if (boundProfile != null) break
|
if (boundProfile != null) break
|
||||||
}
|
}
|
||||||
|
if (
|
||||||
|
boundProfile == null &&
|
||||||
|
delivery.kind == RemoteDocumentKind.BASE &&
|
||||||
|
requestedAttachmentProfile != null
|
||||||
|
) {
|
||||||
|
boundProfile = requestedAttachmentProfile
|
||||||
|
}
|
||||||
if (boundProfile == null && delivery.kind == RemoteDocumentKind.BASE) {
|
if (boundProfile == null && delivery.kind == RemoteDocumentKind.BASE) {
|
||||||
boundProfile = settingsStore.profileForConnectionDocument(delivery.document)
|
boundProfile = settingsStore.profileForConnectionDocument(delivery.document)
|
||||||
}
|
}
|
||||||
@@ -567,7 +692,10 @@ class MainActivity : ComponentActivity() {
|
|||||||
lifecycleScope.launch {
|
lifecycleScope.launch {
|
||||||
val store = SettingsStore(this@MainActivity)
|
val store = SettingsStore(this@MainActivity)
|
||||||
runCatching {
|
runCatching {
|
||||||
store.createWdttDeepLinkApplyPlan(link)
|
store.createWdttDeepLinkApplyPlan(
|
||||||
|
link,
|
||||||
|
allowOmittedConnection = delivery?.kind == RemoteDocumentKind.UPDATE,
|
||||||
|
)
|
||||||
}.onSuccess { basePlan ->
|
}.onSuccess { basePlan ->
|
||||||
val plan = basePlan?.let {
|
val plan = basePlan?.let {
|
||||||
if (preferredProfile == null) it else it.copy(
|
if (preferredProfile == null) it else it.copy(
|
||||||
@@ -684,24 +812,17 @@ class MainActivity : ComponentActivity() {
|
|||||||
}
|
}
|
||||||
if (fromRemoteDocument) {
|
if (fromRemoteDocument) {
|
||||||
val profile = result?.targetProfile ?: plan.targetProfile
|
val profile = result?.targetProfile ?: plan.targetProfile
|
||||||
if (delivery?.access?.available == true) {
|
if (delivery?.access?.available == true || isBoundUpdate) {
|
||||||
lifecycleScope.launch {
|
lifecycleScope.launch {
|
||||||
AccessLifecycleCoordinator.refreshProfile(
|
AccessLifecycleCoordinator.refreshProfile(
|
||||||
this@MainActivity,
|
this@MainActivity,
|
||||||
profile,
|
profile,
|
||||||
force = delivery.access.initialStatus == null,
|
force = isBoundUpdate || delivery?.access?.initialStatus == null,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (isBoundUpdate) {
|
if (shouldRestoreUiAfterBoundUpdate(isBoundUpdate)) {
|
||||||
val profileLabel = vpnProfileDisplayName(profile, store.profileNames.first())
|
wdttConnectFlow = null
|
||||||
wdttConnectFlow = WdttConnectFlow.Complete(
|
|
||||||
if (result?.alreadyApplied == true) {
|
|
||||||
"Обновление профиля $profileLabel уже применено."
|
|
||||||
} else {
|
|
||||||
"Профиль $profileLabel обновлён. Новые данные уже видны в настройках туннеля."
|
|
||||||
}
|
|
||||||
)
|
|
||||||
} else if (
|
} else if (
|
||||||
existingRemoteProfile &&
|
existingRemoteProfile &&
|
||||||
store.tunnelProfileSnapshot(profile).vkHashes.isNotBlank()
|
store.tunnelProfileSnapshot(profile).vkHashes.isNotBlank()
|
||||||
@@ -737,7 +858,13 @@ class MainActivity : ComponentActivity() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun startConnectAction(profile: Int, continuation: RemoteContinuation) {
|
private fun startConnectAction(profile: Int, continuation: RemoteContinuation) {
|
||||||
connectActionJob?.cancel()
|
// The dialog can deliver two taps before Compose has rendered the
|
||||||
|
// ExternalAction state. Do not cancel an already running preparation
|
||||||
|
// and start a second browser/login flow: VK treats those parallel
|
||||||
|
// attempts as repeated authentication requests and may answer with
|
||||||
|
// its flood-control error [9]. A fresh attempt is available through
|
||||||
|
// the explicit Back/Retry path after the current job finishes.
|
||||||
|
if (connectActionJob?.isActive == true) return
|
||||||
val access = (wdttConnectFlow as? WdttConnectFlow.SelectHashes)
|
val access = (wdttConnectFlow as? WdttConnectFlow.SelectHashes)
|
||||||
?.access
|
?.access
|
||||||
?: RemoteAccessCapability.Unavailable
|
?: RemoteAccessCapability.Unavailable
|
||||||
@@ -792,7 +919,8 @@ class MainActivity : ComponentActivity() {
|
|||||||
)
|
)
|
||||||
val target = RemoteContinuationLauncher.begin(
|
val target = RemoteContinuationLauncher.begin(
|
||||||
capability = continuation,
|
capability = continuation,
|
||||||
device = settingsStore.getOrCreateConnectDeviceId()
|
device = settingsStore.getOrCreateConnectDeviceId(),
|
||||||
|
localDocument = settingsStore.remoteActionProfileDocument(profile),
|
||||||
)
|
)
|
||||||
launchRemoteContinuation(target)
|
launchRemoteContinuation(target)
|
||||||
wdttConnectFlow = WdttConnectFlow.Complete(
|
wdttConnectFlow = WdttConnectFlow.Complete(
|
||||||
@@ -1251,6 +1379,8 @@ private fun MainScreen(
|
|||||||
onSelectWdttDeepLinkOverwriteProfile: (Int) -> Unit = {},
|
onSelectWdttDeepLinkOverwriteProfile: (Int) -> Unit = {},
|
||||||
onConfirmWdttDeepLinkOverwrite: (WdttDeepLinkApplyPlan) -> Unit = {},
|
onConfirmWdttDeepLinkOverwrite: (WdttDeepLinkApplyPlan) -> Unit = {},
|
||||||
onCancelWdttDeepLinkOverwrite: () -> Unit = {},
|
onCancelWdttDeepLinkOverwrite: () -> Unit = {},
|
||||||
|
onSelectWdttAttachmentProfile: (Int) -> Unit = {},
|
||||||
|
onConfirmWdttAttachmentProfile: () -> Unit = {},
|
||||||
onSelectWdttConnectProfile: (Int) -> Unit = {},
|
onSelectWdttConnectProfile: (Int) -> Unit = {},
|
||||||
onConfirmWdttConnectProfile: (WdttDeepLinkApplyPlan) -> Unit = {},
|
onConfirmWdttConnectProfile: (WdttDeepLinkApplyPlan) -> Unit = {},
|
||||||
onContinueLimitedWdttSetup: (WdttDeepLinkApplyPlan, RemoteDocumentDelivery) -> Unit = { _, _ -> },
|
onContinueLimitedWdttSetup: (WdttDeepLinkApplyPlan, RemoteDocumentDelivery) -> Unit = { _, _ -> },
|
||||||
@@ -1283,7 +1413,8 @@ private fun MainScreen(
|
|||||||
val scope = rememberCoroutineScope()
|
val scope = rememberCoroutineScope()
|
||||||
val updateCheckMutex = remember { Mutex() }
|
val updateCheckMutex = remember { Mutex() }
|
||||||
val settingsReady by settingsStore.settingsReady.collectAsStateWithLifecycle(initialValue = false)
|
val settingsReady by settingsStore.settingsReady.collectAsStateWithLifecycle(initialValue = false)
|
||||||
val startupSettings by settingsStore.activeTunnelProfileUiSnapshot.collectAsStateWithLifecycle()
|
val startupSettings by
|
||||||
|
settingsStore.activeTunnelProfileContentUiSnapshot.collectAsStateWithLifecycle()
|
||||||
if (!settingsReady || startupSettings == null) {
|
if (!settingsReady || startupSettings == null) {
|
||||||
Box(modifier = Modifier.fillMaxSize()) {
|
Box(modifier = Modifier.fillMaxSize()) {
|
||||||
AppBackdrop(modifier = Modifier.matchParentSize())
|
AppBackdrop(modifier = Modifier.matchParentSize())
|
||||||
@@ -1768,6 +1899,7 @@ private fun MainScreen(
|
|||||||
|
|
||||||
// Floating theme toolbar overlay
|
// Floating theme toolbar overlay
|
||||||
FloatingToolbar(
|
FloatingToolbar(
|
||||||
|
settingsStore = settingsStore,
|
||||||
activeProfile = activeProfile,
|
activeProfile = activeProfile,
|
||||||
profileNames = profileNames,
|
profileNames = profileNames,
|
||||||
onActiveProfileChange = { profile ->
|
onActiveProfileChange = { profile ->
|
||||||
@@ -1990,6 +2122,8 @@ private fun MainScreen(
|
|||||||
WdttConnectActivationDialog(
|
WdttConnectActivationDialog(
|
||||||
flow = flow,
|
flow = flow,
|
||||||
profileNames = profileNames,
|
profileNames = profileNames,
|
||||||
|
onSelectAttachmentProfile = onSelectWdttAttachmentProfile,
|
||||||
|
onConfirmAttachmentProfile = onConfirmWdttAttachmentProfile,
|
||||||
onSelectProfile = onSelectWdttConnectProfile,
|
onSelectProfile = onSelectWdttConnectProfile,
|
||||||
onConfirmProfile = onConfirmWdttConnectProfile,
|
onConfirmProfile = onConfirmWdttConnectProfile,
|
||||||
onContinueLimitedSetup = onContinueLimitedWdttSetup,
|
onContinueLimitedSetup = onContinueLimitedWdttSetup,
|
||||||
@@ -2032,16 +2166,24 @@ private fun MainScreen(
|
|||||||
repeat(3) { profile ->
|
repeat(3) { profile ->
|
||||||
FilterChip(
|
FilterChip(
|
||||||
selected = plan.targetProfile == profile,
|
selected = plan.targetProfile == profile,
|
||||||
|
enabled = profile !in plan.blockedProfiles,
|
||||||
onClick = { onSelectWdttDeepLinkOverwriteProfile(profile) },
|
onClick = { onSelectWdttDeepLinkOverwriteProfile(profile) },
|
||||||
label = { Text(vpnProfileDisplayName(profile, profileNames)) }
|
label = { Text(vpnProfileDisplayName(profile, profileNames)) }
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Text("Будет полностью заменено подключение в профиле $profileLabel.")
|
if (plan.blockedProfiles.size == 3) {
|
||||||
|
Text("Все профили защищены действующим удалённым доступом. Сначала освободите один из них.")
|
||||||
|
} else {
|
||||||
|
Text("Будет полностью заменено подключение в профиле $profileLabel.")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
confirmButton = {
|
confirmButton = {
|
||||||
TextButton(onClick = { onConfirmWdttDeepLinkOverwrite(plan) }) {
|
TextButton(
|
||||||
|
enabled = plan.targetProfile !in plan.blockedProfiles,
|
||||||
|
onClick = { onConfirmWdttDeepLinkOverwrite(plan) },
|
||||||
|
) {
|
||||||
Text("Да")
|
Text("Да")
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -2058,6 +2200,8 @@ private fun MainScreen(
|
|||||||
private fun WdttConnectActivationDialog(
|
private fun WdttConnectActivationDialog(
|
||||||
flow: WdttConnectFlow,
|
flow: WdttConnectFlow,
|
||||||
profileNames: List<String>,
|
profileNames: List<String>,
|
||||||
|
onSelectAttachmentProfile: (Int) -> Unit,
|
||||||
|
onConfirmAttachmentProfile: () -> Unit,
|
||||||
onSelectProfile: (Int) -> Unit,
|
onSelectProfile: (Int) -> Unit,
|
||||||
onConfirmProfile: (WdttDeepLinkApplyPlan) -> Unit,
|
onConfirmProfile: (WdttDeepLinkApplyPlan) -> Unit,
|
||||||
onContinueLimitedSetup: (WdttDeepLinkApplyPlan, RemoteDocumentDelivery) -> Unit,
|
onContinueLimitedSetup: (WdttDeepLinkApplyPlan, RemoteDocumentDelivery) -> Unit,
|
||||||
@@ -2073,7 +2217,8 @@ private fun WdttConnectActivationDialog(
|
|||||||
var selectedHashMethod by rememberSaveable { mutableStateOf<String?>(null) }
|
var selectedHashMethod by rememberSaveable { mutableStateOf<String?>(null) }
|
||||||
var helpMethod by rememberSaveable { mutableStateOf<String?>(null) }
|
var helpMethod by rememberSaveable { mutableStateOf<String?>(null) }
|
||||||
var unavailableAutoMessage by rememberSaveable { mutableStateOf<String?>(null) }
|
var unavailableAutoMessage by rememberSaveable { mutableStateOf<String?>(null) }
|
||||||
val canDismiss = flow is WdttConnectFlow.Complete ||
|
val canDismiss = flow is WdttConnectFlow.SelectAttachmentProfile ||
|
||||||
|
flow is WdttConnectFlow.Complete ||
|
||||||
flow is WdttConnectFlow.Failed
|
flow is WdttConnectFlow.Failed
|
||||||
AlertDialog(
|
AlertDialog(
|
||||||
onDismissRequest = {
|
onDismissRequest = {
|
||||||
@@ -2110,6 +2255,41 @@ private fun WdttConnectActivationDialog(
|
|||||||
Text(state.message)
|
Text(state.message)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
is WdttConnectFlow.SelectAttachmentProfile -> {
|
||||||
|
val selectedCandidate = state.candidates.first {
|
||||||
|
it.profileIndex == state.selectedProfile
|
||||||
|
}
|
||||||
|
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||||
|
Text(
|
||||||
|
"Найдено несколько изменённых обычных профилей. " +
|
||||||
|
"Выберите, к какому из них привязать разрешение. " +
|
||||||
|
"Готовые профили здесь недоступны."
|
||||||
|
)
|
||||||
|
state.candidates.forEach { candidate ->
|
||||||
|
FilterChip(
|
||||||
|
selected = state.selectedProfile == candidate.profileIndex,
|
||||||
|
onClick = {
|
||||||
|
onSelectAttachmentProfile(candidate.profileIndex)
|
||||||
|
},
|
||||||
|
label = {
|
||||||
|
Text("${candidate.displayName} · ${candidate.sourceLabel}")
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Text(
|
||||||
|
if (selectedCandidate.sourceLabel.contains("Деплой")) {
|
||||||
|
"Если подключение в «Деплое» заполнено полностью, при запуске " +
|
||||||
|
"будут использованы только адрес, порты и главный пароль. " +
|
||||||
|
"SSH-логин, SSH-пароль и ключи не передаются."
|
||||||
|
} else {
|
||||||
|
"Можно выбрать даже частично заполненный профиль и закончить " +
|
||||||
|
"его настройку позже. Подключение не заменяется."
|
||||||
|
},
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
is WdttConnectFlow.SelectProfile -> {
|
is WdttConnectFlow.SelectProfile -> {
|
||||||
val incomingName = WdttDeepLink.parse(
|
val incomingName = WdttDeepLink.parse(
|
||||||
state.plan.link,
|
state.plan.link,
|
||||||
@@ -2124,13 +2304,20 @@ private fun WdttConnectActivationDialog(
|
|||||||
repeat(3) { profile ->
|
repeat(3) { profile ->
|
||||||
FilterChip(
|
FilterChip(
|
||||||
selected = state.plan.targetProfile == profile,
|
selected = state.plan.targetProfile == profile,
|
||||||
|
enabled = profile !in state.plan.blockedProfiles,
|
||||||
onClick = { onSelectProfile(profile) },
|
onClick = { onSelectProfile(profile) },
|
||||||
label = { Text(vpnProfileDisplayName(profile, profileNames)) }
|
label = { Text(vpnProfileDisplayName(profile, profileNames)) }
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Text(
|
Text(
|
||||||
"Подключение в выбранном профиле будет полностью заменено.",
|
if (state.plan.blockedProfiles.size == 3) {
|
||||||
|
"Все профили защищены действующим готовым доступом. " +
|
||||||
|
"Ни один из них нельзя перезаписать."
|
||||||
|
} else {
|
||||||
|
"Подключение в выбранном профиле будет полностью заменено. " +
|
||||||
|
"Действующие готовые профили недоступны для выбора."
|
||||||
|
},
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
)
|
)
|
||||||
@@ -2141,7 +2328,7 @@ private fun WdttConnectActivationDialog(
|
|||||||
"Автоматическое получение VK-хешей сейчас недоступно."
|
"Автоматическое получение VK-хешей сейчас недоступно."
|
||||||
}
|
}
|
||||||
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||||
Text("Перед добавлением профиля обратите внимание:")
|
Text("Перед продолжением обратите внимание:")
|
||||||
Text(reason)
|
Text(reason)
|
||||||
Text(
|
Text(
|
||||||
"Это ограничение относится только к автоматическому получению " +
|
"Это ограничение относится только к автоматическому получению " +
|
||||||
@@ -2153,25 +2340,13 @@ private fun WdttConnectActivationDialog(
|
|||||||
}
|
}
|
||||||
is WdttConnectFlow.SelectHashes -> {
|
is WdttConnectFlow.SelectHashes -> {
|
||||||
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||||
Text("Выберите способ заполнения VK-хешей для нового профиля.")
|
Text("Выберите способ заполнения VK-хешей для профиля.")
|
||||||
if (state.access.exchange.actionAvailable) {
|
|
||||||
HashMethodRow(
|
|
||||||
title = state.access.exchange.label.ifBlank {
|
|
||||||
"Вернуть хеши"
|
|
||||||
},
|
|
||||||
body = state.access.exchange.message.ifBlank {
|
|
||||||
"Восстановить сохранённые хеши этого профиля"
|
|
||||||
},
|
|
||||||
onHelp = { helpMethod = "restore" },
|
|
||||||
onClick = {
|
|
||||||
onRestoreSavedHashes(state.profile, state.access)
|
|
||||||
}
|
|
||||||
)
|
|
||||||
}
|
|
||||||
HashMethodRow(
|
HashMethodRow(
|
||||||
title = "Получить автоматически",
|
title = "Получить автоматически",
|
||||||
body = if (state.continuation.available) {
|
body = if (state.continuation.available) {
|
||||||
"Войти в VK при необходимости и создать ссылки"
|
state.continuation.message.ifBlank {
|
||||||
|
"Войти в VK при необходимости и создать ссылки"
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
"Недоступно — нажмите, чтобы узнать, что делать"
|
"Недоступно — нажмите, чтобы узнать, что делать"
|
||||||
},
|
},
|
||||||
@@ -2192,6 +2367,20 @@ private fun WdttConnectActivationDialog(
|
|||||||
onHelp = { helpMethod = "manual" },
|
onHelp = { helpMethod = "manual" },
|
||||||
onClick = { selectedHashMethod = "manual" }
|
onClick = { selectedHashMethod = "manual" }
|
||||||
)
|
)
|
||||||
|
if (state.access.exchange.actionAvailable) {
|
||||||
|
HashMethodRow(
|
||||||
|
title = state.access.exchange.label.ifBlank {
|
||||||
|
"Вернуть хеши"
|
||||||
|
},
|
||||||
|
body = state.access.exchange.message.ifBlank {
|
||||||
|
"Восстановить сохранённые хеши этого профиля"
|
||||||
|
},
|
||||||
|
onHelp = { helpMethod = "restore" },
|
||||||
|
onClick = {
|
||||||
|
onRestoreSavedHashes(state.profile, state.access)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
if (selectedHashMethod == "manual") {
|
if (selectedHashMethod == "manual") {
|
||||||
OutlinedTextField(
|
OutlinedTextField(
|
||||||
value = manualHashes,
|
value = manualHashes,
|
||||||
@@ -2211,8 +2400,16 @@ private fun WdttConnectActivationDialog(
|
|||||||
},
|
},
|
||||||
confirmButton = {
|
confirmButton = {
|
||||||
when (flow) {
|
when (flow) {
|
||||||
|
is WdttConnectFlow.SelectAttachmentProfile -> {
|
||||||
|
TextButton(onClick = onConfirmAttachmentProfile) {
|
||||||
|
Text("Продолжить")
|
||||||
|
}
|
||||||
|
}
|
||||||
is WdttConnectFlow.SelectProfile -> {
|
is WdttConnectFlow.SelectProfile -> {
|
||||||
TextButton(onClick = { onConfirmProfile(flow.plan) }) {
|
TextButton(
|
||||||
|
enabled = flow.plan.targetProfile !in flow.plan.blockedProfiles,
|
||||||
|
onClick = { onConfirmProfile(flow.plan) },
|
||||||
|
) {
|
||||||
Text("Сохранить")
|
Text("Сохранить")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2256,6 +2453,11 @@ private fun WdttConnectActivationDialog(
|
|||||||
},
|
},
|
||||||
dismissButton = {
|
dismissButton = {
|
||||||
when (flow) {
|
when (flow) {
|
||||||
|
is WdttConnectFlow.SelectAttachmentProfile -> {
|
||||||
|
TextButton(onClick = onDismiss) {
|
||||||
|
Text("Отмена")
|
||||||
|
}
|
||||||
|
}
|
||||||
is WdttConnectFlow.SelectProfile -> {
|
is WdttConnectFlow.SelectProfile -> {
|
||||||
TextButton(onClick = onDismiss) {
|
TextButton(onClick = onDismiss) {
|
||||||
Text("Позже")
|
Text("Позже")
|
||||||
@@ -2310,7 +2512,7 @@ private fun WdttConnectActivationDialog(
|
|||||||
}
|
}
|
||||||
"restore" -> {
|
"restore" -> {
|
||||||
"WDTT Plus безопасно вернёт хеши, ранее сохранённые именно для " +
|
"WDTT Plus безопасно вернёт хеши, ранее сохранённые именно для " +
|
||||||
"этого готового профиля. Хеши других ваших профилей не используются."
|
"этого профиля. Значения других профилей не используются."
|
||||||
}
|
}
|
||||||
else -> {
|
else -> {
|
||||||
"Создайте или скопируйте до четырёх ссылок-приглашений VK Звонков, " +
|
"Создайте или скопируйте до четырёх ссылок-приглашений VK Звонков, " +
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ package com.wdtt.plus
|
|||||||
import android.content.Context
|
import android.content.Context
|
||||||
import kotlinx.coroutines.CancellationException
|
import kotlinx.coroutines.CancellationException
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.sync.Mutex
|
||||||
|
import kotlinx.coroutines.sync.withLock
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
import org.json.JSONObject
|
import org.json.JSONObject
|
||||||
import java.net.HttpURLConnection
|
import java.net.HttpURLConnection
|
||||||
@@ -81,6 +83,7 @@ object RemoteActionCatalogGateway {
|
|||||||
private const val CACHE_TTL_MS = 10 * 60 * 1000L
|
private const val CACHE_TTL_MS = 10 * 60 * 1000L
|
||||||
private const val MAX_RESPONSE_CHARS = 32 * 1024
|
private const val MAX_RESPONSE_CHARS = 32 * 1024
|
||||||
private val placements = setOf("tunnel", "profile", "about")
|
private val placements = setOf("tunnel", "profile", "about")
|
||||||
|
private val fetchMutex = Mutex()
|
||||||
|
|
||||||
@Volatile
|
@Volatile
|
||||||
private var cachedAt = 0L
|
private var cachedAt = 0L
|
||||||
@@ -91,21 +94,24 @@ object RemoteActionCatalogGateway {
|
|||||||
fun hasFreshCache(): Boolean =
|
fun hasFreshCache(): Boolean =
|
||||||
System.currentTimeMillis() - cachedAt in 0 until CACHE_TTL_MS
|
System.currentTimeMillis() - cachedAt in 0 until CACHE_TTL_MS
|
||||||
|
|
||||||
fun cached(): RemoteActionCatalog =
|
fun cached(): RemoteActionCatalog = cachedCatalog
|
||||||
if (hasFreshCache()) cachedCatalog else RemoteActionCatalog.Empty
|
|
||||||
|
|
||||||
suspend fun fetch(force: Boolean = false): RemoteActionCatalog {
|
suspend fun fetch(force: Boolean = false): RemoteActionCatalog {
|
||||||
val now = System.currentTimeMillis()
|
val now = System.currentTimeMillis()
|
||||||
if (!force && now - cachedAt in 0 until CACHE_TTL_MS) return cachedCatalog
|
if (!force && now - cachedAt in 0 until CACHE_TTL_MS) return cachedCatalog
|
||||||
return withContext(Dispatchers.IO) {
|
return withContext(Dispatchers.IO) {
|
||||||
val current = System.currentTimeMillis()
|
fetchMutex.withLock {
|
||||||
if (!force && current - cachedAt in 0 until CACHE_TTL_MS) {
|
val current = System.currentTimeMillis()
|
||||||
return@withContext cachedCatalog
|
if (!force && current - cachedAt in 0 until CACHE_TTL_MS) {
|
||||||
|
return@withLock cachedCatalog
|
||||||
|
}
|
||||||
|
runCatching { request() }
|
||||||
|
.onSuccess { received ->
|
||||||
|
cachedCatalog = received
|
||||||
|
cachedAt = current
|
||||||
|
}
|
||||||
|
cachedCatalog
|
||||||
}
|
}
|
||||||
val received = runCatching { request() }.getOrDefault(RemoteActionCatalog.Empty)
|
|
||||||
cachedCatalog = received
|
|
||||||
cachedAt = current
|
|
||||||
received
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -29,17 +29,25 @@ data class RemoteLaunchTarget(
|
|||||||
}
|
}
|
||||||
|
|
||||||
object RemoteContinuationLauncher {
|
object RemoteContinuationLauncher {
|
||||||
suspend fun begin(capability: RemoteContinuation, device: String): RemoteLaunchTarget {
|
suspend fun begin(
|
||||||
|
capability: RemoteContinuation,
|
||||||
|
device: String,
|
||||||
|
localDocument: String? = null,
|
||||||
|
): RemoteLaunchTarget {
|
||||||
require(capability.available && opaqueValue(capability.key)) {
|
require(capability.available && opaqueValue(capability.key)) {
|
||||||
"Автоматическое заполнение недоступно для этого профиля."
|
"Автоматическое заполнение недоступно для этого профиля."
|
||||||
}
|
}
|
||||||
require(safeServiceUrl(capability.url)) { "Автоматическое заполнение сейчас недоступно." }
|
require(safeServiceUrl(capability.url)) { "Автоматическое заполнение сейчас недоступно." }
|
||||||
require(validDevice(device)) { "Не удалось определить текущее устройство." }
|
require(validDevice(device)) { "Не удалось определить текущее устройство." }
|
||||||
return withContext(Dispatchers.IO) {
|
return withContext(Dispatchers.IO) {
|
||||||
val payload = JSONObject()
|
val request = JSONObject()
|
||||||
.put("key", capability.key.trim())
|
.put("key", capability.key.trim())
|
||||||
.put("device", device.trim())
|
.put("device", device.trim())
|
||||||
.put("return_transport", "auth_tab")
|
.put("return_transport", "auth_tab")
|
||||||
|
attachmentDocumentForRequest(localDocument)?.let { document ->
|
||||||
|
request.put("profile", document)
|
||||||
|
}
|
||||||
|
val payload = request
|
||||||
.toString()
|
.toString()
|
||||||
.toByteArray(Charsets.UTF_8)
|
.toByteArray(Charsets.UTF_8)
|
||||||
var connection: HttpURLConnection? = null
|
var connection: HttpURLConnection? = null
|
||||||
@@ -164,6 +172,11 @@ object RemoteContinuationLauncher {
|
|||||||
|
|
||||||
internal fun browserLaunchUrls(target: RemoteLaunchTarget): List<String> =
|
internal fun browserLaunchUrls(target: RemoteLaunchTarget): List<String> =
|
||||||
(
|
(
|
||||||
|
// The primary URL is for the preferred native VK handler. When
|
||||||
|
// that handler is unavailable, the backend-provided mobile login
|
||||||
|
// URL is the proven browser entry: it preserves the opaque `to`
|
||||||
|
// state through an unauthenticated VK login and immediately
|
||||||
|
// continues to the Mini App for an existing browser session.
|
||||||
if (target.handlerPackages().isNotEmpty() && target.fallbackUrl.isNotBlank()) {
|
if (target.handlerPackages().isNotEmpty() && target.fallbackUrl.isNotBlank()) {
|
||||||
listOf(target.fallbackUrl, target.primaryUrl)
|
listOf(target.fallbackUrl, target.primaryUrl)
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ data class RemoteDocumentFailureAction(
|
|||||||
class RemoteDocumentFailure(
|
class RemoteDocumentFailure(
|
||||||
message: String,
|
message: String,
|
||||||
val action: RemoteDocumentFailureAction? = null,
|
val action: RemoteDocumentFailureAction? = null,
|
||||||
|
val profileAttachmentRequired: Boolean = false,
|
||||||
) : IllegalStateException(message)
|
) : IllegalStateException(message)
|
||||||
|
|
||||||
data class RemoteContinuation(
|
data class RemoteContinuation(
|
||||||
@@ -33,7 +34,8 @@ data class RemoteContinuation(
|
|||||||
|
|
||||||
enum class RemoteDocumentKind {
|
enum class RemoteDocumentKind {
|
||||||
BASE,
|
BASE,
|
||||||
UPDATE
|
UPDATE,
|
||||||
|
ATTACHMENT,
|
||||||
}
|
}
|
||||||
|
|
||||||
data class RemoteDocumentDelivery(
|
data class RemoteDocumentDelivery(
|
||||||
@@ -49,7 +51,11 @@ data class RemoteDocumentDelivery(
|
|||||||
internal fun RemoteDocumentDelivery.shouldPreserveLocalVkHashes(
|
internal fun RemoteDocumentDelivery.shouldPreserveLocalVkHashes(
|
||||||
existingProfileRedelivery: Boolean = false,
|
existingProfileRedelivery: Boolean = false,
|
||||||
): Boolean {
|
): Boolean {
|
||||||
val deliveredHashes = WdttDeepLink.parse(document, allowMissingHashes = true)
|
val deliveredHashes = WdttDeepLink.parse(
|
||||||
|
document,
|
||||||
|
allowMissingHashes = true,
|
||||||
|
allowOmittedConnection = kind == RemoteDocumentKind.UPDATE,
|
||||||
|
)
|
||||||
?.hashes
|
?.hashes
|
||||||
.orEmpty()
|
.orEmpty()
|
||||||
return deliveredHashes.isBlank() &&
|
return deliveredHashes.isBlank() &&
|
||||||
@@ -64,7 +70,24 @@ internal fun RemoteDocumentDelivery.requiresInitialContinuationWarning(
|
|||||||
): Boolean =
|
): Boolean =
|
||||||
kind == RemoteDocumentKind.BASE &&
|
kind == RemoteDocumentKind.BASE &&
|
||||||
!continuation.available &&
|
!continuation.available &&
|
||||||
!existingProfileHasVkHashes
|
!existingProfileHasVkHashes
|
||||||
|
|
||||||
|
internal fun attachmentDocumentForRequest(localDocument: String?): String? =
|
||||||
|
localDocument
|
||||||
|
?.trim()
|
||||||
|
?.takeIf { document ->
|
||||||
|
document.length <= 4 * 1024 &&
|
||||||
|
document.startsWith("wdtt://connect?", ignoreCase = true) &&
|
||||||
|
WdttDeepLink.parse(document, allowMissingHashes = true)
|
||||||
|
?.let { it.hashes.isBlank() } == true
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun eligibleRemoteAttachmentDocument(
|
||||||
|
localDocument: String?,
|
||||||
|
alreadyManaged: Boolean,
|
||||||
|
): String? = if (alreadyManaged) null else attachmentDocumentForRequest(localDocument)
|
||||||
|
|
||||||
|
internal fun profileAttachmentRequired(value: String?): Boolean = value?.trim() == "1"
|
||||||
|
|
||||||
object RemoteDocumentGateway {
|
object RemoteDocumentGateway {
|
||||||
private const val MAX_RESPONSE_CHARS = 32 * 1024
|
private const val MAX_RESPONSE_CHARS = 32 * 1024
|
||||||
@@ -95,6 +118,8 @@ object RemoteDocumentGateway {
|
|||||||
client: String,
|
client: String,
|
||||||
system: String,
|
system: String,
|
||||||
localBindings: Collection<String>? = null,
|
localBindings: Collection<String>? = null,
|
||||||
|
localDocument: String? = null,
|
||||||
|
profileAttachment: Boolean = false,
|
||||||
): RemoteDocumentDelivery {
|
): RemoteDocumentDelivery {
|
||||||
require(extractLink(link.url) != null) { "Ссылка повреждена или неполна." }
|
require(extractLink(link.url) != null) { "Ссылка повреждена или неполна." }
|
||||||
require(validDevice(device)) { "Не удалось определить текущее устройство." }
|
require(validDevice(device)) { "Не удалось определить текущее устройство." }
|
||||||
@@ -113,6 +138,11 @@ object RemoteDocumentGateway {
|
|||||||
.take(6)
|
.take(6)
|
||||||
request.put("bindings", JSONArray(bindings))
|
request.put("bindings", JSONArray(bindings))
|
||||||
}
|
}
|
||||||
|
attachmentDocumentForRequest(localDocument)
|
||||||
|
?.let { request.put("profile", it) }
|
||||||
|
if (profileAttachment) {
|
||||||
|
request.put("attach", true)
|
||||||
|
}
|
||||||
val payload = request
|
val payload = request
|
||||||
.toString()
|
.toString()
|
||||||
.toByteArray(Charsets.UTF_8)
|
.toByteArray(Charsets.UTF_8)
|
||||||
@@ -135,6 +165,9 @@ object RemoteDocumentGateway {
|
|||||||
"Ссылка недоступна. Получите новую ссылку подключения."
|
"Ссылка недоступна. Получите новую ссылку подключения."
|
||||||
},
|
},
|
||||||
failure.second,
|
failure.second,
|
||||||
|
profileAttachmentRequired = profileAttachmentRequired(
|
||||||
|
connection.getHeaderField("X-WDTT-Profile-Required")
|
||||||
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
parse(body)
|
parse(body)
|
||||||
@@ -161,11 +194,20 @@ object RemoteDocumentGateway {
|
|||||||
val kind = when (root.optString("type").trim()) {
|
val kind = when (root.optString("type").trim()) {
|
||||||
"base" -> RemoteDocumentKind.BASE
|
"base" -> RemoteDocumentKind.BASE
|
||||||
"update" -> RemoteDocumentKind.UPDATE
|
"update" -> RemoteDocumentKind.UPDATE
|
||||||
|
"attachment" -> RemoteDocumentKind.ATTACHMENT
|
||||||
else -> throw IllegalStateException("WDTT Plus вернул неподдерживаемый тип данных.")
|
else -> throw IllegalStateException("WDTT Plus вернул неподдерживаемый тип данных.")
|
||||||
}
|
}
|
||||||
val document = root.optString("document").trim()
|
val document = root.optString("document").trim()
|
||||||
val documentParts = WdttDeepLink.parse(document, allowMissingHashes = true)
|
val documentParts = document
|
||||||
if (documentParts == null) {
|
.takeIf(String::isNotBlank)
|
||||||
|
?.let {
|
||||||
|
WdttDeepLink.parse(
|
||||||
|
it,
|
||||||
|
allowMissingHashes = true,
|
||||||
|
allowOmittedConnection = kind == RemoteDocumentKind.UPDATE,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (kind != RemoteDocumentKind.ATTACHMENT && documentParts == null) {
|
||||||
throw IllegalStateException("WDTT Plus вернул неполные данные подключения.")
|
throw IllegalStateException("WDTT Plus вернул неполные данные подключения.")
|
||||||
}
|
}
|
||||||
val binding = root.optString("binding").trim().takeIf(::opaqueValue).orEmpty()
|
val binding = root.optString("binding").trim().takeIf(::opaqueValue).orEmpty()
|
||||||
@@ -203,7 +245,7 @@ object RemoteDocumentGateway {
|
|||||||
}
|
}
|
||||||
when (kind) {
|
when (kind) {
|
||||||
RemoteDocumentKind.BASE -> {
|
RemoteDocumentKind.BASE -> {
|
||||||
if (documentParts.hashes.isNotBlank()) {
|
if (documentParts?.hashes?.isNotBlank() == true) {
|
||||||
throw IllegalStateException(
|
throw IllegalStateException(
|
||||||
"Ссылка подключения содержит лишние данные. Получите новую ссылку."
|
"Ссылка подключения содержит лишние данные. Получите новую ссылку."
|
||||||
)
|
)
|
||||||
@@ -219,6 +261,19 @@ object RemoteDocumentGateway {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
RemoteDocumentKind.ATTACHMENT -> {
|
||||||
|
if (
|
||||||
|
document.isNotBlank() ||
|
||||||
|
binding.isBlank() ||
|
||||||
|
!available ||
|
||||||
|
!accessAvailable ||
|
||||||
|
accessBinding != binding
|
||||||
|
) {
|
||||||
|
throw IllegalStateException(
|
||||||
|
"WDTT Plus вернул неполное разрешение для выбранного профиля."
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
val workers = root.optJSONObject("limits")?.optInt("workers", 0)
|
val workers = root.optJSONObject("limits")?.optInt("workers", 0)
|
||||||
?.takeIf {
|
?.takeIf {
|
||||||
|
|||||||
@@ -12,11 +12,6 @@ import javax.crypto.spec.GCMParameterSpec
|
|||||||
|
|
||||||
class SecureStringStore(context: Context) {
|
class SecureStringStore(context: Context) {
|
||||||
private val appContext = context.applicationContext
|
private val appContext = context.applicationContext
|
||||||
private val decryptedCache = object : LinkedHashMap<String, String>(32, 0.75f, true) {
|
|
||||||
override fun removeEldestEntry(
|
|
||||||
eldest: MutableMap.MutableEntry<String, String>?
|
|
||||||
): Boolean = size > 64
|
|
||||||
}
|
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
private const val KEY_ALIAS = "wdtt.settings.secrets"
|
private const val KEY_ALIAS = "wdtt.settings.secrets"
|
||||||
@@ -24,6 +19,11 @@ class SecureStringStore(context: Context) {
|
|||||||
private const val TRANSFORMATION = "AES/GCM/NoPadding"
|
private const val TRANSFORMATION = "AES/GCM/NoPadding"
|
||||||
private const val GCM_TAG_BITS = 128
|
private const val GCM_TAG_BITS = 128
|
||||||
private const val VERSION_PREFIX = "v1:"
|
private const val VERSION_PREFIX = "v1:"
|
||||||
|
private val decryptedCache = object : LinkedHashMap<String, String>(64, 0.75f, true) {
|
||||||
|
override fun removeEldestEntry(
|
||||||
|
eldest: MutableMap.MutableEntry<String, String>?
|
||||||
|
): Boolean = size > 128
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private val keyStore: KeyStore by lazy {
|
private val keyStore: KeyStore by lazy {
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
package com.wdtt.plus
|
package com.wdtt.plus
|
||||||
|
|
||||||
/** Версии приложения, для которых выпускалась новая обязательная серверная часть. */
|
/** Версии приложения, для которых выпускалась новая обязательная серверная часть. */
|
||||||
internal val SERVER_MIGRATION_LEVELS = intArrayOf(2, 3, 5, 6, 7, 12)
|
internal val SERVER_MIGRATION_LEVELS = intArrayOf(2, 3, 5, 6, 7, 12, 14)
|
||||||
|
|
||||||
data class ServerMigrationState(
|
data class ServerMigrationState(
|
||||||
val pendingLevel: Int,
|
val pendingLevel: Int,
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -31,6 +31,54 @@ data class SshCredentials(
|
|||||||
get() = allowPasswordAuthentication && password.isNotBlank()
|
get() = allowPasswordAuthentication && password.isNotBlank()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
data class SshProfileAccessStatus(
|
||||||
|
val available: Boolean,
|
||||||
|
val unavailableReason: String = "",
|
||||||
|
)
|
||||||
|
|
||||||
|
internal fun sshProfileAccessStatus(
|
||||||
|
host: String,
|
||||||
|
authMode: String,
|
||||||
|
password: String,
|
||||||
|
privateKey: String,
|
||||||
|
): SshProfileAccessStatus {
|
||||||
|
if (host.isBlank()) {
|
||||||
|
return SshProfileAccessStatus(
|
||||||
|
available = false,
|
||||||
|
unavailableReason = "укажите адрес сервера в разделе «Деплой»",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (authMode == "key") {
|
||||||
|
if (privateKey.isBlank()) {
|
||||||
|
return SshProfileAccessStatus(
|
||||||
|
available = false,
|
||||||
|
unavailableReason = "добавьте приватный SSH-ключ в разделе «Деплой»",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
sshPrivateKeyIssue(privateKey)?.let {
|
||||||
|
return SshProfileAccessStatus(
|
||||||
|
available = false,
|
||||||
|
unavailableReason = "исправьте приватный SSH-ключ в разделе «Деплой»: ${it.removeSuffix(".")}",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return SshProfileAccessStatus(available = true)
|
||||||
|
}
|
||||||
|
if (password.isBlank()) {
|
||||||
|
return SshProfileAccessStatus(
|
||||||
|
available = false,
|
||||||
|
unavailableReason = "укажите SSH-пароль в разделе «Деплой»",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return SshProfileAccessStatus(available = true)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal data class SshProfileConnection(
|
||||||
|
val host: String,
|
||||||
|
val user: String,
|
||||||
|
val credentials: SshCredentials,
|
||||||
|
val port: Int,
|
||||||
|
)
|
||||||
|
|
||||||
fun sshCredentialsForMode(
|
fun sshCredentialsForMode(
|
||||||
mode: String,
|
mode: String,
|
||||||
password: String,
|
password: String,
|
||||||
|
|||||||
@@ -127,10 +127,11 @@ internal fun decideTrustedWifiTransition(
|
|||||||
|
|
||||||
internal fun shouldKeepTunnelServiceAlive(
|
internal fun shouldKeepTunnelServiceAlive(
|
||||||
tunnelRunning: Boolean,
|
tunnelRunning: Boolean,
|
||||||
|
tunnelStarting: Boolean,
|
||||||
tunnelPaused: Boolean,
|
tunnelPaused: Boolean,
|
||||||
trustedWifiWaiting: Boolean,
|
trustedWifiWaiting: Boolean,
|
||||||
trustedWifiResumeInProgress: Boolean
|
trustedWifiResumeInProgress: Boolean
|
||||||
): Boolean = tunnelRunning || tunnelPaused || trustedWifiWaiting || trustedWifiResumeInProgress
|
): Boolean = tunnelRunning || tunnelStarting || tunnelPaused || trustedWifiWaiting || trustedWifiResumeInProgress
|
||||||
|
|
||||||
fun sanitizeTrustedWifiSsid(value: String): String {
|
fun sanitizeTrustedWifiSsid(value: String): String {
|
||||||
val clean = value
|
val clean = value
|
||||||
|
|||||||
@@ -59,16 +59,32 @@ internal val ConnectionIssue.isStandaloneUiIssue: Boolean
|
|||||||
|
|
||||||
enum class NetworkRecoveryAction {
|
enum class NetworkRecoveryAction {
|
||||||
SoftRestart,
|
SoftRestart,
|
||||||
RecreateVpn,
|
|
||||||
StopVpn
|
StopVpn
|
||||||
}
|
}
|
||||||
|
|
||||||
internal fun stableNetworkRecoveryAction(completedAttempts: Int): NetworkRecoveryAction = when {
|
internal fun stableNetworkRecoveryAction(@Suppress("UNUSED_PARAMETER") completedAttempts: Int): NetworkRecoveryAction =
|
||||||
completedAttempts <= 0 -> NetworkRecoveryAction.SoftRestart
|
NetworkRecoveryAction.SoftRestart
|
||||||
completedAttempts == 1 -> NetworkRecoveryAction.RecreateVpn
|
|
||||||
else -> NetworkRecoveryAction.StopVpn
|
internal fun hasFreshTransportHeartbeat(
|
||||||
|
running: Boolean,
|
||||||
|
activeWorkers: Int,
|
||||||
|
lastActiveAtMs: Long,
|
||||||
|
lastStatsAtMs: Long,
|
||||||
|
sinceMs: Long,
|
||||||
|
nowMs: Long,
|
||||||
|
freshnessMs: Long = 90_000L,
|
||||||
|
): Boolean {
|
||||||
|
if (!running || activeWorkers <= 0) return false
|
||||||
|
val freshActive = lastActiveAtMs >= sinceMs && nowMs - lastActiveAtMs < freshnessMs
|
||||||
|
val freshStats = lastStatsAtMs >= sinceMs && nowMs - lastStatsAtMs < freshnessMs
|
||||||
|
return freshActive || freshStats
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal fun shouldObserveTunnelHealth(
|
||||||
|
deviceInteractive: Boolean,
|
||||||
|
wakeRecoveryGraceActive: Boolean,
|
||||||
|
): Boolean = deviceInteractive && !wakeRecoveryGraceActive
|
||||||
|
|
||||||
enum class TunnelStopReason(val displayText: String) {
|
enum class TunnelStopReason(val displayText: String) {
|
||||||
User("отключено пользователем"),
|
User("отключено пользователем"),
|
||||||
VpnSlotTransferred("VPN-слот передан другому приложению"),
|
VpnSlotTransferred("VPN-слот передан другому приложению"),
|
||||||
@@ -150,6 +166,287 @@ internal fun isExpiredAccessAuthFailure(line: String): Boolean =
|
|||||||
|
|
||||||
internal const val WRAP_HANDSHAKE_RETRY_MESSAGE =
|
internal const val WRAP_HANDSHAKE_RETRY_MESSAGE =
|
||||||
"[WRAP] Отдельные каналы не ответили, выполняется повтор"
|
"[WRAP] Отдельные каналы не ответили, выполняется повтор"
|
||||||
|
internal const val RT_MASQUE_CONFIG_FILE_NAME = "rt-masque-v1.json"
|
||||||
|
|
||||||
|
internal fun shouldUseRtMasque(rtNetwork: Boolean, rtMasque: Boolean): Boolean =
|
||||||
|
rtNetwork && rtMasque
|
||||||
|
|
||||||
|
internal fun shouldUseRtMasqueServerBootstrap(
|
||||||
|
rtNetwork: Boolean,
|
||||||
|
rtMasque: Boolean,
|
||||||
|
serverBootstrap: Boolean,
|
||||||
|
): Boolean = rtNetwork && rtMasque && serverBootstrap
|
||||||
|
|
||||||
|
internal data class MasqueLogPresentation(
|
||||||
|
val key: String,
|
||||||
|
val message: String,
|
||||||
|
val warning: Boolean = false,
|
||||||
|
val startsDtls: Boolean = false,
|
||||||
|
)
|
||||||
|
|
||||||
|
internal fun classifyMasqueLog(line: String): MasqueLogPresentation? {
|
||||||
|
val hasTag = line.contains("[MASQUE]", ignoreCase = true)
|
||||||
|
val mentionsSelectedPath = line.contains("внутри MASQUE", ignoreCase = true)
|
||||||
|
val mentionsUdpFallback = line.contains("после MASQUE", ignoreCase = true)
|
||||||
|
if (!hasTag && !mentionsSelectedPath && !mentionsUdpFallback) return null
|
||||||
|
val text = if (hasTag) line.substringAfter("[MASQUE]", line).trim() else line.trim()
|
||||||
|
val h2 = text.contains("HTTP/2", ignoreCase = true)
|
||||||
|
val h3 = text.contains("HTTP/3", ignoreCase = true)
|
||||||
|
val registrationProblem =
|
||||||
|
text.contains("конфигурация WARP повреждена", ignoreCase = true) ||
|
||||||
|
text.contains("публичный ключ WARP endpoint не совпал", ignoreCase = true) ||
|
||||||
|
text.contains("access denied", ignoreCase = true)
|
||||||
|
val httpStatus = Regex("HTTP\\s+(\\d{3})", RegexOption.IGNORE_CASE)
|
||||||
|
.find(text)
|
||||||
|
?.groupValues
|
||||||
|
?.getOrNull(1)
|
||||||
|
?.toIntOrNull()
|
||||||
|
val apiCode = Regex("code=(\\d+)", RegexOption.IGNORE_CASE)
|
||||||
|
.find(text)
|
||||||
|
?.groupValues
|
||||||
|
?.getOrNull(1)
|
||||||
|
val enrollmentStage = when {
|
||||||
|
text.contains("этап 1/4", ignoreCase = true) ||
|
||||||
|
text.contains("регистрация WARP:", ignoreCase = true) ->
|
||||||
|
"создания устройства WARP (этап 1/4)"
|
||||||
|
text.contains("этап 2/4", ignoreCase = true) ||
|
||||||
|
text.contains("enrollment WARP", ignoreCase = true) ->
|
||||||
|
"включения MASQUE в Cloudflare (этап 2/4)"
|
||||||
|
text.contains("этап 3/4", ignoreCase = true) ||
|
||||||
|
text.contains("неполную конфигурацию", ignoreCase = true) ->
|
||||||
|
"проверки конфигурации MASQUE (этап 3/4)"
|
||||||
|
text.contains("этап 4/4", ignoreCase = true) ||
|
||||||
|
text.contains("сохранение регистрации", ignoreCase = true) ->
|
||||||
|
"сохранения регистрации на устройстве (этап 4/4)"
|
||||||
|
else -> "подготовки WARP"
|
||||||
|
}
|
||||||
|
val pathFailureReason = when {
|
||||||
|
text.contains("timeout", ignoreCase = true) ||
|
||||||
|
text.contains("deadline exceeded", ignoreCase = true) ||
|
||||||
|
text.contains("тайм-аут", ignoreCase = true) -> "таймаут"
|
||||||
|
text.contains("refused", ignoreCase = true) -> "соединение отклонено"
|
||||||
|
text.contains("unreachable", ignoreCase = true) ||
|
||||||
|
text.contains("no route", ignoreCase = true) -> "маршрут недоступен"
|
||||||
|
text.contains("lookup", ignoreCase = true) ||
|
||||||
|
text.contains("DNS", ignoreCase = true) -> "ошибка DNS внутри WARP"
|
||||||
|
text.contains("handshake", ignoreCase = true) -> "ошибка рукопожатия"
|
||||||
|
else -> "CONNECT-IP или TURN не ответил"
|
||||||
|
}
|
||||||
|
val enrollmentFailureReason = when {
|
||||||
|
httpStatus == 429 -> "Cloudflare ограничил частоту регистраций (HTTP 429)"
|
||||||
|
httpStatus == 403 -> "Cloudflare отклонил запрос (HTTP 403)"
|
||||||
|
httpStatus != null && httpStatus >= 500 -> "временная ошибка Cloudflare (HTTP $httpStatus)"
|
||||||
|
text.contains("тайм-аут TLS-рукопожатия", ignoreCase = true) ->
|
||||||
|
"TLS-рукопожатие с API Cloudflare не завершилось после успешного TCP/443"
|
||||||
|
text.contains("не прислал заголовки ответа", ignoreCase = true) ||
|
||||||
|
text.contains("не прислал ответ", ignoreCase = true) ->
|
||||||
|
"Cloudflare не ответил на уже отправленный HTTPS-запрос"
|
||||||
|
text.contains("тайм-аут подключения TCP/443", ignoreCase = true) ->
|
||||||
|
"не установилось TCP/443-соединение с API Cloudflare"
|
||||||
|
text.contains("тайм-аут системного DNS", ignoreCase = true) ->
|
||||||
|
"системный DNS Android не ответил для API Cloudflare"
|
||||||
|
text.contains("пустой ответ", ignoreCase = true) -> "Cloudflare вернул пустой ответ"
|
||||||
|
text.contains("не в формате JSON", ignoreCase = true) -> "Cloudflare вернул ответ не в формате JSON"
|
||||||
|
text.contains("структура JSON-ответа", ignoreCase = true) -> "формат ответа Cloudflare изменился"
|
||||||
|
text.contains("чтение ответа", ignoreCase = true) -> "ответ Cloudflare оборвался при чтении"
|
||||||
|
httpStatus != null -> "Cloudflare вернул HTTP $httpStatus"
|
||||||
|
text.contains("lookup", ignoreCase = true) ||
|
||||||
|
text.contains("DNS", ignoreCase = true) -> "не разрешился адрес API Cloudflare"
|
||||||
|
text.contains("timeout", ignoreCase = true) ||
|
||||||
|
text.contains("deadline exceeded", ignoreCase = true) ||
|
||||||
|
text.contains("тайм-аут", ignoreCase = true) -> "таймаут обращения к API Cloudflare"
|
||||||
|
text.contains("certificate", ignoreCase = true) ||
|
||||||
|
text.contains("x509", ignoreCase = true) -> "ошибка проверки TLS-сертификата API Cloudflare"
|
||||||
|
text.contains("connection refused", ignoreCase = true) -> "соединение с API Cloudflare отклонено"
|
||||||
|
text.contains("не вернула", ignoreCase = true) ||
|
||||||
|
text.contains("не вернул", ignoreCase = true) -> "Cloudflare вернул неполную конфигурацию"
|
||||||
|
else -> "запрос к API Cloudflare завершился ошибкой"
|
||||||
|
}
|
||||||
|
val rawEnrollmentFailure = text
|
||||||
|
.substringAfter("фоновая подготовка WARP пока не выполнена:", "")
|
||||||
|
.trim()
|
||||||
|
.replaceFirst(Regex("^этап\\s+\\d/4,[^:]{0,160}:\\s*", RegexOption.IGNORE_CASE), "")
|
||||||
|
.replace(Regex("(?i)Bearer\\s+\\S+"), "Bearer [скрыт]")
|
||||||
|
.replace(Regex("https?://\\S+", RegexOption.IGNORE_CASE), "[URL скрыт]")
|
||||||
|
.replace(Regex("[\\r\\n\\t]+"), " ")
|
||||||
|
.trim()
|
||||||
|
.take(260)
|
||||||
|
val enrollmentTechnicalDetail = buildList {
|
||||||
|
if (apiCode != null) add("код API $apiCode")
|
||||||
|
when {
|
||||||
|
text.contains("ошибка DNS для", ignoreCase = true) ->
|
||||||
|
add(text.substringAfter("ошибка DNS для", "").trim().take(180).let { "DNS: $it" })
|
||||||
|
text.contains("сетевая ошибка:", ignoreCase = true) ->
|
||||||
|
add(text.substringAfter("сетевая ошибка:", "").trim().take(180))
|
||||||
|
text.contains("не вернул ID или токен", ignoreCase = true) ->
|
||||||
|
add("в ответе отсутствует ID или токен")
|
||||||
|
text.contains("не вернул адрес MASQUE", ignoreCase = true) ->
|
||||||
|
add("в ответе отсутствует адрес MASQUE")
|
||||||
|
text.contains("неполная конфигурация", ignoreCase = true) ->
|
||||||
|
add("в ответе отсутствует обязательное поле")
|
||||||
|
}
|
||||||
|
if (rawEnrollmentFailure.isNotBlank()) add(rawEnrollmentFailure)
|
||||||
|
}.filter { it.isNotBlank() }.distinct().joinToString(", ")
|
||||||
|
.let { if (it.isBlank()) "" else "; подробность: $it" }
|
||||||
|
|
||||||
|
return when {
|
||||||
|
registrationProblem -> MasqueLogPresentation(
|
||||||
|
key = "masque_registration_invalid",
|
||||||
|
message = "[MASQUE] Регистрация WARP повреждена или отклонена. Остановите VPN и используйте «Сбросить регистрацию WARP» в справке MASQUE.",
|
||||||
|
warning = true,
|
||||||
|
)
|
||||||
|
text.contains("фоновая подготовка WARP пока не выполнена", ignoreCase = true) ->
|
||||||
|
MasqueLogPresentation(
|
||||||
|
key = "masque_enrollment_pending",
|
||||||
|
message = "[MASQUE] Ошибка на этапе $enrollmentStage: $enrollmentFailureReason$enrollmentTechnicalDetail. " +
|
||||||
|
"Регистрация не сохранена; прямые пути продолжают работу. Для новой попытки остановите и снова запустите VPN.",
|
||||||
|
warning = true,
|
||||||
|
)
|
||||||
|
text.contains("повторяем через TLS 1.2/HTTP 1.1", ignoreCase = true) &&
|
||||||
|
text.contains("разделённым ClientHello", ignoreCase = true) ->
|
||||||
|
MasqueLogPresentation(
|
||||||
|
"masque_api_tls_fallback",
|
||||||
|
"[MASQUE] API Cloudflare: обычный TLS не ответил; пробуем TLS 1.2/HTTP 1.1 с разделённым ClientHello...",
|
||||||
|
warning = true,
|
||||||
|
)
|
||||||
|
text.contains("данные устройства ещё не отправлялись", ignoreCase = true) ->
|
||||||
|
MasqueLogPresentation(
|
||||||
|
"masque_api_retry",
|
||||||
|
"[MASQUE] API Cloudflare не завершил соединение до отправки данных. Выполняем одну безопасную повторную попытку через системную сеть Android...",
|
||||||
|
warning = true,
|
||||||
|
)
|
||||||
|
text.contains("прямые HTTPS-пути недоступны", ignoreCase = true) &&
|
||||||
|
text.contains("выход через сервер профиля", ignoreCase = true) ->
|
||||||
|
MasqueLogPresentation(
|
||||||
|
"masque_api_server_retry",
|
||||||
|
"[MASQUE] Прямой API Cloudflare не ответил; пробуем регистрацию через сервер профиля...",
|
||||||
|
warning = true,
|
||||||
|
)
|
||||||
|
text.contains("выход через сервер профиля доступен", ignoreCase = true) ->
|
||||||
|
MasqueLogPresentation(
|
||||||
|
"masque_api_server_connected",
|
||||||
|
"[MASQUE] Защищённый выход через сервер профиля установлен ✓",
|
||||||
|
)
|
||||||
|
text.contains("выход через сервер профиля сработал", ignoreCase = true) ->
|
||||||
|
MasqueLogPresentation(
|
||||||
|
"masque_api_server_ok",
|
||||||
|
"[MASQUE] API Cloudflare доступен через сервер профиля ✓",
|
||||||
|
)
|
||||||
|
text.contains("локальный выход для регистрации WARP отклонён", ignoreCase = true) ->
|
||||||
|
MasqueLogPresentation(
|
||||||
|
"masque_api_server_invalid",
|
||||||
|
"[MASQUE] Локальный выход регистрации отклонён как небезопасный; продолжаем прямые попытки",
|
||||||
|
warning = true,
|
||||||
|
)
|
||||||
|
text.contains("системный DNS Android разрешил адрес", ignoreCase = true) ->
|
||||||
|
MasqueLogPresentation(
|
||||||
|
"masque_api_dns",
|
||||||
|
"[MASQUE] API Cloudflare: системный DNS Android разрешил адрес ✓",
|
||||||
|
)
|
||||||
|
text.contains("TCP/443 через системную сеть Android установлен", ignoreCase = true) ->
|
||||||
|
MasqueLogPresentation(
|
||||||
|
"masque_api_tcp",
|
||||||
|
"[MASQUE] API Cloudflare: TCP/443 через системную сеть Android установлен ✓",
|
||||||
|
)
|
||||||
|
text.contains("TLS-рукопожатие завершено", ignoreCase = true) &&
|
||||||
|
text.contains("HTTP/1.1", ignoreCase = true) ->
|
||||||
|
MasqueLogPresentation(
|
||||||
|
"masque_api_tls_fallback_ok",
|
||||||
|
"[MASQUE] API Cloudflare: резерв TLS 1.2/HTTP 1.1 установлен ✓",
|
||||||
|
)
|
||||||
|
text.contains("TLS-рукопожатие завершено", ignoreCase = true) ->
|
||||||
|
MasqueLogPresentation(
|
||||||
|
"masque_api_tls",
|
||||||
|
"[MASQUE] API Cloudflare: защищённое TLS-соединение установлено ✓",
|
||||||
|
)
|
||||||
|
text.contains("HTTP-запрос отправлен", ignoreCase = true) &&
|
||||||
|
text.contains("ожидаем ответ", ignoreCase = true) ->
|
||||||
|
MasqueLogPresentation(
|
||||||
|
"masque_api_request",
|
||||||
|
"[MASQUE] API Cloudflare: HTTPS-запрос отправлен, ожидаем ответ...",
|
||||||
|
)
|
||||||
|
text.contains("получен первый байт HTTP-ответа", ignoreCase = true) ->
|
||||||
|
MasqueLogPresentation(
|
||||||
|
"masque_api_response",
|
||||||
|
"[MASQUE] API Cloudflare: получен HTTP-ответ ✓",
|
||||||
|
)
|
||||||
|
text.contains("регистрация начата:", ignoreCase = true) ||
|
||||||
|
text.contains("первый запуск: регистрируем", ignoreCase = true) ->
|
||||||
|
MasqueLogPresentation(
|
||||||
|
"masque_enrollment_start",
|
||||||
|
"[MASQUE] Этап 1/4: создаём отдельное устройство WARP в Cloudflare...",
|
||||||
|
)
|
||||||
|
text.contains("этап 1/4 завершён", ignoreCase = true) ||
|
||||||
|
text.contains("базовая регистрация WARP создана", ignoreCase = true) ->
|
||||||
|
MasqueLogPresentation(
|
||||||
|
"masque_account_created",
|
||||||
|
"[MASQUE] Этап 1/4 завершён: устройство WARP создано. Этап 2/4: включаем для него MASQUE...",
|
||||||
|
)
|
||||||
|
text.contains("этап 2/4 завершён", ignoreCase = true) ||
|
||||||
|
text.contains("Cloudflare принял ключ MASQUE", ignoreCase = true) ->
|
||||||
|
MasqueLogPresentation(
|
||||||
|
"masque_key_accepted",
|
||||||
|
"[MASQUE] Этап 2/4 завершён: Cloudflare принял ключ MASQUE. Этап 3/4: проверяем адреса и ключ сервера...",
|
||||||
|
)
|
||||||
|
text.contains("этап 3/4 завершён", ignoreCase = true) ->
|
||||||
|
MasqueLogPresentation(
|
||||||
|
"masque_config_valid",
|
||||||
|
"[MASQUE] Этап 3/4 завершён: конфигурация MASQUE корректна ✓",
|
||||||
|
)
|
||||||
|
text.contains("этап 4/4 — сохраняем", ignoreCase = true) ->
|
||||||
|
MasqueLogPresentation(
|
||||||
|
"masque_enrollment_saving",
|
||||||
|
"[MASQUE] Этап 4/4: сохраняем регистрацию только в приватном хранилище приложения...",
|
||||||
|
)
|
||||||
|
text.contains("этап 4/4 завершён", ignoreCase = true) ||
|
||||||
|
text.contains("enrollment WARP сохранён", ignoreCase = true) ->
|
||||||
|
MasqueLogPresentation(
|
||||||
|
"masque_enrollment_saved",
|
||||||
|
"[MASQUE] Этап 4/4 завершён: регистрация WARP сохранена в приватном хранилище ✓",
|
||||||
|
)
|
||||||
|
text.contains("конфигурация WARP подготовлена", ignoreCase = true) ->
|
||||||
|
MasqueLogPresentation("masque_config_ready", "[MASQUE] Сохранённая регистрация WARP готова ✓")
|
||||||
|
text.contains("Включён резерв", ignoreCase = true) ->
|
||||||
|
MasqueLogPresentation("masque_enabled", "[MASQUE] Резерв включён: HTTP/2 (TCP/443), затем HTTP/3 (QUIC/443)")
|
||||||
|
text.contains("Прямые TCP/TLS-пути", ignoreCase = true) ->
|
||||||
|
MasqueLogPresentation("masque_fallback_start", "[MASQUE] Прямые TCP/TLS-пути РТ не ответили — запускаем CONNECT-IP до попытки UDP")
|
||||||
|
text.contains("Последний резерв после MASQUE", ignoreCase = true) ->
|
||||||
|
MasqueLogPresentation(
|
||||||
|
"masque_udp_fallback",
|
||||||
|
"[MASQUE] HTTP/2 и HTTP/3 не дали рабочий TURN — пробуем прямой UDP последним резервом",
|
||||||
|
warning = true,
|
||||||
|
)
|
||||||
|
text.contains("Relay:", ignoreCase = true) && h2 ->
|
||||||
|
MasqueLogPresentation("masque_selected", "[MASQUE] Выбран HTTP/2 через TCP/443 ✓", startsDtls = true)
|
||||||
|
text.contains("Relay:", ignoreCase = true) && h3 ->
|
||||||
|
MasqueLogPresentation("masque_selected", "[MASQUE] Выбран HTTP/3 через QUIC/443 ✓", startsDtls = true)
|
||||||
|
text.contains("CONNECT-IP HTTP/2 установлен", ignoreCase = true) ->
|
||||||
|
MasqueLogPresentation("masque_h2_connected", "[MASQUE] CONNECT-IP HTTP/2 через TCP/443 установлен ✓")
|
||||||
|
text.contains("CONNECT-IP HTTP/3 установлен", ignoreCase = true) ->
|
||||||
|
MasqueLogPresentation("masque_h3_connected", "[MASQUE] CONNECT-IP HTTP/3 через QUIC/443 установлен ✓")
|
||||||
|
text.contains("устанавливаем CONNECT-IP", ignoreCase = true) && h2 ->
|
||||||
|
MasqueLogPresentation("masque_h2_connecting", "[MASQUE] Подключаем CONNECT-IP HTTP/2 через TCP/443...")
|
||||||
|
text.contains("устанавливаем CONNECT-IP", ignoreCase = true) && h3 ->
|
||||||
|
MasqueLogPresentation("masque_h3_connecting", "[MASQUE] Подключаем CONNECT-IP HTTP/3 через QUIC/443...")
|
||||||
|
text.contains("Пробуем TURN", ignoreCase = true) && h2 ->
|
||||||
|
MasqueLogPresentation("masque_h2_turn", "[MASQUE] Проверяем TURN внутри HTTP/2...")
|
||||||
|
text.contains("Пробуем TURN", ignoreCase = true) && h3 ->
|
||||||
|
MasqueLogPresentation("masque_h3_turn", "[MASQUE] Проверяем TURN внутри HTTP/3...")
|
||||||
|
(text.contains("не сработал", ignoreCase = true) || text.contains("потерян", ignoreCase = true)) && h2 ->
|
||||||
|
MasqueLogPresentation(
|
||||||
|
"masque_h2_failed",
|
||||||
|
"[MASQUE] Путь HTTP/2/TCP/443 не сработал ($pathFailureReason); проверяем другие TURN-адреса и HTTP/3",
|
||||||
|
warning = true,
|
||||||
|
)
|
||||||
|
(text.contains("не сработал", ignoreCase = true) || text.contains("потерян", ignoreCase = true)) && h3 ->
|
||||||
|
MasqueLogPresentation(
|
||||||
|
"masque_h3_failed",
|
||||||
|
"[MASQUE] Путь HTTP/3/QUIC/443 не сработал ($pathFailureReason); проверяем другие TURN-адреса и прямой UDP",
|
||||||
|
warning = true,
|
||||||
|
)
|
||||||
|
else -> MasqueLogPresentation("masque_status", "[MASQUE] $text")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const val AMNEZIA_STYLE_RECOVERY = true
|
const val AMNEZIA_STYLE_RECOVERY = true
|
||||||
private const val RECOVERABLE_NETWORK_GRACE_MS = 90_000L
|
private const val RECOVERABLE_NETWORK_GRACE_MS = 90_000L
|
||||||
@@ -159,6 +456,7 @@ private const val STABLE_RECOVERY_GRACE_MS = 10 * 60_000L
|
|||||||
private const val STABLE_RECOVERY_RETRY_MS = 10 * 60_000L
|
private const val STABLE_RECOVERY_RETRY_MS = 10 * 60_000L
|
||||||
private const val STABLE_ZERO_WORKERS_GRACE_MS = 15 * 60_000L
|
private const val STABLE_ZERO_WORKERS_GRACE_MS = 15 * 60_000L
|
||||||
private const val STAGNANT_ACTIVE_TRAFFIC_MS = 20 * 60_000L
|
private const val STAGNANT_ACTIVE_TRAFFIC_MS = 20 * 60_000L
|
||||||
|
private const val WAKE_RECOVERY_GRACE_MS = 90_000L
|
||||||
|
|
||||||
object TunnelManager {
|
object TunnelManager {
|
||||||
// 100% защита от утечек: единый управляемый глобальный Scope
|
// 100% защита от утечек: единый управляемый глобальный Scope
|
||||||
@@ -168,6 +466,7 @@ object TunnelManager {
|
|||||||
private var readerJob: Job? = null
|
private var readerJob: Job? = null
|
||||||
private var watchdogJob: Job? = null
|
private var watchdogJob: Job? = null
|
||||||
private var wgHelper: WireGuardHelper? = null
|
private var wgHelper: WireGuardHelper? = null
|
||||||
|
private var warpApiSshRelay: WarpApiSshRelay? = null
|
||||||
|
|
||||||
private val startStopMutex = kotlinx.coroutines.sync.Mutex()
|
private val startStopMutex = kotlinx.coroutines.sync.Mutex()
|
||||||
|
|
||||||
@@ -198,8 +497,10 @@ object TunnelManager {
|
|||||||
private var lastSoftRestartAtMs = 0L
|
private var lastSoftRestartAtMs = 0L
|
||||||
private var lastUnderlyingNetworkChangeAtMs = 0L
|
private var lastUnderlyingNetworkChangeAtMs = 0L
|
||||||
private var networkTransitionGraceUntilMs = 0L
|
private var networkTransitionGraceUntilMs = 0L
|
||||||
|
private var wakeRecoveryGraceUntilMs = 0L
|
||||||
private var lastNetworkSettleRestartAtMs = 0L
|
private var lastNetworkSettleRestartAtMs = 0L
|
||||||
private var lastStableNetworkIssueLogAtMs = 0L
|
private var lastStableNetworkIssueLogAtMs = 0L
|
||||||
|
private val sessionTraffic = TunnelSessionTrafficAccumulator()
|
||||||
private val captchaSolveRequestId = AtomicLong(0)
|
private val captchaSolveRequestId = AtomicLong(0)
|
||||||
private val activeCaptchaSolveRequests = ConcurrentHashMap.newKeySet<Long>()
|
private val activeCaptchaSolveRequests = ConcurrentHashMap.newKeySet<Long>()
|
||||||
|
|
||||||
@@ -381,6 +682,7 @@ object TunnelManager {
|
|||||||
|
|
||||||
fun pollNetworkRecoveryAction(now: Long = System.currentTimeMillis()): NetworkRecoveryAction? {
|
fun pollNetworkRecoveryAction(now: Long = System.currentTimeMillis()): NetworkRecoveryAction? {
|
||||||
if (!running.value) return null
|
if (!running.value) return null
|
||||||
|
if (isWakeRecoveryGraceActive(now)) return null
|
||||||
if (AMNEZIA_STYLE_RECOVERY) {
|
if (AMNEZIA_STYLE_RECOVERY) {
|
||||||
return pollStableNetworkRecoveryAction(now)
|
return pollStableNetworkRecoveryAction(now)
|
||||||
}
|
}
|
||||||
@@ -495,13 +797,9 @@ object TunnelManager {
|
|||||||
"Восстанавливаю транспорт",
|
"Восстанавливаю транспорт",
|
||||||
"Сеть долго не подаёт признаков жизни. Выполняется тихая попытка без пересоздания VPN."
|
"Сеть долго не подаёт признаков жизни. Выполняется тихая попытка без пересоздания VPN."
|
||||||
)
|
)
|
||||||
NetworkRecoveryAction.RecreateVpn -> setConnectionIssue(
|
|
||||||
"Пересоздаю VPN",
|
|
||||||
"Тихое восстановление не помогло. Системный VPN-интерфейс будет пересоздан один раз."
|
|
||||||
)
|
|
||||||
NetworkRecoveryAction.StopVpn -> setConnectionIssue(
|
NetworkRecoveryAction.StopVpn -> setConnectionIssue(
|
||||||
"VPN остановлен, чтобы вернуть интернет",
|
"VPN остановлен, чтобы вернуть интернет",
|
||||||
"Пересоздание VPN не восстановило связь. WDTT Plus выключит VPN, чтобы телефон не остался без интернета."
|
"Повторные попытки не восстановили связь. WDTT Plus выключит VPN, чтобы телефон не остался без интернета."
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
return action
|
return action
|
||||||
@@ -660,6 +958,7 @@ object TunnelManager {
|
|||||||
if (!preserveLogs) clearLogs()
|
if (!preserveLogs) clearLogs()
|
||||||
config.value = null
|
config.value = null
|
||||||
stats.value = "Ожидание данных..."
|
stats.value = "Ожидание данных..."
|
||||||
|
sessionTraffic.reset()
|
||||||
floodCount = 0
|
floodCount = 0
|
||||||
mismatchCount = 0
|
mismatchCount = 0
|
||||||
refusedCount = 0
|
refusedCount = 0
|
||||||
@@ -671,6 +970,7 @@ object TunnelManager {
|
|||||||
resetStatsLivenessState()
|
resetStatsLivenessState()
|
||||||
lastUnderlyingNetworkChangeAtMs = 0L
|
lastUnderlyingNetworkChangeAtMs = 0L
|
||||||
networkTransitionGraceUntilMs = 0L
|
networkTransitionGraceUntilMs = 0L
|
||||||
|
wakeRecoveryGraceUntilMs = 0L
|
||||||
lastNetworkSettleRestartAtMs = 0L
|
lastNetworkSettleRestartAtMs = 0L
|
||||||
activeHashIndex = 0
|
activeHashIndex = 0
|
||||||
currentParams = params
|
currentParams = params
|
||||||
@@ -765,6 +1065,64 @@ object TunnelManager {
|
|||||||
// Go boolean flags must use -flag=value. A separate "false" value
|
// Go boolean flags must use -flag=value. A separate "false" value
|
||||||
// stops flag.Parse and silently drops every argument after it.
|
// stops flag.Parse and silently drops every argument after it.
|
||||||
cmd.add("-vkcalls-preflight=${params.vkCallsPreflight}")
|
cmd.add("-vkcalls-preflight=${params.vkCallsPreflight}")
|
||||||
|
cmd.add("-turn-stream-first=${params.rtNetwork}")
|
||||||
|
if (params.rtNetwork) {
|
||||||
|
val turnSni = normalizeRtTurnSni(params.rtTurnSni)
|
||||||
|
if (turnSni != null) {
|
||||||
|
cmd.add("-turn-sni")
|
||||||
|
cmd.add(turnSni)
|
||||||
|
} else if (params.rtTurnSni.isNotBlank()) {
|
||||||
|
updateWarningLog(
|
||||||
|
"rt_sni_invalid",
|
||||||
|
"[TURN] SNI режима «Сеть РТ» имеет неверный формат; запускаем TCP/TLS без подмены SNI",
|
||||||
|
20,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val useRtMasque = shouldUseRtMasque(params.rtNetwork, params.rtMasque)
|
||||||
|
cmd.add("-rt-masque=$useRtMasque")
|
||||||
|
if (useRtMasque) {
|
||||||
|
val masqueConfig = File(appContext.filesDir, RT_MASQUE_CONFIG_FILE_NAME)
|
||||||
|
cmd.add("-rt-masque-config")
|
||||||
|
cmd.add(masqueConfig.absolutePath)
|
||||||
|
cmd.add("-rt-masque-accept-tos=true")
|
||||||
|
if (
|
||||||
|
!masqueConfig.exists() &&
|
||||||
|
shouldUseRtMasqueServerBootstrap(
|
||||||
|
rtNetwork = params.rtNetwork,
|
||||||
|
rtMasque = params.rtMasque,
|
||||||
|
serverBootstrap = params.rtMasqueServerBootstrap,
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
closeWarpApiSshRelay()
|
||||||
|
when (val relayResult = WarpApiSshRelay.start(appContext, params.profileIndex)) {
|
||||||
|
is WarpApiSshRelayStartResult.Ready -> {
|
||||||
|
warpApiSshRelay = relayResult.relay
|
||||||
|
cmd.add("-warp-api-relay")
|
||||||
|
cmd.add(relayResult.relay.loopbackAddress)
|
||||||
|
updateLog(
|
||||||
|
"masque_server_bootstrap_ready",
|
||||||
|
"[MASQUE] Для первой регистрации подготовлен защищённый выход через сервер профиля ✓",
|
||||||
|
4,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
WarpApiSshRelayStartResult.MissingProfileAccess -> {
|
||||||
|
updateWarningLog(
|
||||||
|
"masque_server_bootstrap_missing",
|
||||||
|
"[MASQUE] «Через сервер» недоступен: в «Деплой» нет адреса сервера или выбранного SSH-доступа (пароль/приватный ключ); пробуем прямую регистрацию",
|
||||||
|
20,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
is WarpApiSshRelayStartResult.Failed -> {
|
||||||
|
updateWarningLog(
|
||||||
|
"masque_server_bootstrap_failed",
|
||||||
|
"[MASQUE] Выход через сервер не подготовлен: ${relayResult.message}; пробуем прямую регистрацию",
|
||||||
|
20,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
val androidId = SettingsStore(appContext).getOrCreateTunnelDeviceId()
|
val androidId = SettingsStore(appContext).getOrCreateTunnelDeviceId()
|
||||||
cmd.add("-device-id")
|
cmd.add("-device-id")
|
||||||
@@ -811,12 +1169,26 @@ object TunnelManager {
|
|||||||
startWatchdog(appContext, params)
|
startWatchdog(appContext, params)
|
||||||
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
|
closeWarpApiSshRelay()
|
||||||
val message = e.readableMessage()
|
val message = e.readableMessage()
|
||||||
updateLog("critical_start_error", "Критическая ошибка запуска: $message", 99, true)
|
updateLog("critical_start_error", "Критическая ошибка запуска: $message", 99, true)
|
||||||
setConnectionIssue("Не удалось запустить подключение", "Проверьте настройки туннеля и попробуйте подключиться снова. Причина: $message")
|
setConnectionIssue("Не удалось запустить подключение", "Проверьте настройки туннеля и попробуйте подключиться снова. Причина: $message")
|
||||||
e.printStackTrace()
|
e.printStackTrace()
|
||||||
running.value = false
|
if (isSwitching && currentParams != null) {
|
||||||
currentParams = null
|
// При автоматическом восстановлении не превращаем неудачную
|
||||||
|
// попытку в окончательную остановку: служба оставляет параметры
|
||||||
|
// сессии и сможет повторить восстановление позже.
|
||||||
|
running.value = true
|
||||||
|
processStartedAtMs = System.currentTimeMillis()
|
||||||
|
updateWarningLog(
|
||||||
|
"vpn_recovery_retry_pending",
|
||||||
|
"[VPN] Автоматическое восстановление пока не завершилось; сохраняем сессию и повторим попытку позже.",
|
||||||
|
50,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
running.value = false
|
||||||
|
currentParams = null
|
||||||
|
}
|
||||||
clearTransition()
|
clearTransition()
|
||||||
} finally {
|
} finally {
|
||||||
if (!isSwitching) clearTransition()
|
if (!isSwitching) clearTransition()
|
||||||
@@ -1089,7 +1461,8 @@ object TunnelManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (lineTrim.contains("[СТАТИСТИКА]")) {
|
if (lineTrim.contains("[СТАТИСТИКА]")) {
|
||||||
val msg = lineTrim.substringAfter("[СТАТИСТИКА]").trim()
|
val rawStats = lineTrim.substringAfter("[СТАТИСТИКА]").trim()
|
||||||
|
val msg = sessionTraffic.accumulate(rawStats)
|
||||||
stats.value = msg
|
stats.value = msg
|
||||||
lastStatsAtMs = now
|
lastStatsAtMs = now
|
||||||
|
|
||||||
@@ -1155,7 +1528,22 @@ object TunnelManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
val workerRetry = classifyRecoverableWorkerRetry(lineTrim, activeWorkers.value)
|
val workerRetry = classifyRecoverableWorkerRetry(lineTrim, activeWorkers.value)
|
||||||
|
val masquePresentation = classifyMasqueLog(lineTrim)
|
||||||
when {
|
when {
|
||||||
|
masquePresentation != null -> {
|
||||||
|
val presentation = masquePresentation
|
||||||
|
if (presentation.warning) {
|
||||||
|
updateWarningLog(presentation.key, presentation.message, 20)
|
||||||
|
} else {
|
||||||
|
updateLog(presentation.key, presentation.message, 2, false)
|
||||||
|
}
|
||||||
|
if (presentation.startsDtls) {
|
||||||
|
updateLog("dtls_start", "[DTLS] Рукопожатие (Handshake)...", 1, false)
|
||||||
|
}
|
||||||
|
if (presentation.key == "masque_enrollment_saved") {
|
||||||
|
closeWarpApiSshRelay()
|
||||||
|
}
|
||||||
|
}
|
||||||
workerRetry != null -> {
|
workerRetry != null -> {
|
||||||
if (activeWorkers.value <= 0) {
|
if (activeWorkers.value <= 0) {
|
||||||
when (workerRetry.first) {
|
when (workerRetry.first) {
|
||||||
@@ -1352,10 +1740,23 @@ object TunnelManager {
|
|||||||
lineTrim.contains("[TURN]") -> {
|
lineTrim.contains("[TURN]") -> {
|
||||||
val text = lineTrim.substringAfter("[TURN]").trim()
|
val text = lineTrim.substringAfter("[TURN]").trim()
|
||||||
when {
|
when {
|
||||||
|
text.contains("Креды уже заменены", true) ->
|
||||||
|
updateLog(
|
||||||
|
"turn_creds_current",
|
||||||
|
"[TURN] Используем уже обновлённые данные без повторного запроса к VK",
|
||||||
|
5,
|
||||||
|
false
|
||||||
|
)
|
||||||
text.contains("Креды обновлены", true) ->
|
text.contains("Креды обновлены", true) ->
|
||||||
updateLog("turn_creds_refreshed", "[TURN] Креды обновлены, продолжаем подключение", 2, false)
|
updateLog("turn_creds_refreshed", "[TURN] Креды обновлены, продолжаем подключение", 2, false)
|
||||||
text.contains("Креды уже обновлялись", true) ->
|
text.contains("Креды уже обновлялись", true) ->
|
||||||
updateLog("turn_creds_wait", "[TURN] Ждём перед повторным обновлением кредов", 2, false)
|
updateLog("turn_creds_wait", "[TURN] Ждём перед повторным обновлением кредов", 2, false)
|
||||||
|
text.contains("временно ограничил новые allocation", true) ->
|
||||||
|
updateWarningLog(
|
||||||
|
"turn_capacity_retry",
|
||||||
|
"[TURN] Узел временно ограничил новые каналы; повторяем без обновления данных VK",
|
||||||
|
20
|
||||||
|
)
|
||||||
text.contains("неполный ответ", true) ->
|
text.contains("неполный ответ", true) ->
|
||||||
updateWarningLog("turn_allocate_retry", "[TURN] Неполный Allocate-ответ, обновляем данные и повторяем", 20)
|
updateWarningLog("turn_allocate_retry", "[TURN] Неполный Allocate-ответ, обновляем данные и повторяем", 20)
|
||||||
text.contains("Ошибка allocation/кредов", true) ->
|
text.contains("Ошибка allocation/кредов", true) ->
|
||||||
@@ -1560,8 +1961,23 @@ object TunnelManager {
|
|||||||
watchdogJob = scope.launch {
|
watchdogJob = scope.launch {
|
||||||
var zeroWorkersSince = 0L
|
var zeroWorkersSince = 0L
|
||||||
var processDeadSince = 0L
|
var processDeadSince = 0L
|
||||||
|
val powerManager = context.getSystemService(Context.POWER_SERVICE) as? android.os.PowerManager
|
||||||
delay(10_000)
|
delay(10_000)
|
||||||
while (isActive && running.value) {
|
while (isActive && running.value) {
|
||||||
|
if (
|
||||||
|
!shouldObserveTunnelHealth(
|
||||||
|
deviceInteractive = powerManager?.isInteractive != false,
|
||||||
|
wakeRecoveryGraceActive = isWakeRecoveryGraceActive(),
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
// Сон и первые секунды после пробуждения не входят в длительность
|
||||||
|
// неисправности. Иначе старый таймер срабатывает сразу при включении
|
||||||
|
// экрана и без необходимости перезапускает транспорт.
|
||||||
|
zeroWorkersSince = 0L
|
||||||
|
processDeadSince = 0L
|
||||||
|
delay(10_000)
|
||||||
|
continue
|
||||||
|
}
|
||||||
val proc = process
|
val proc = process
|
||||||
if (proc == null || !proc.isAlive) {
|
if (proc == null || !proc.isAlive) {
|
||||||
val now = System.currentTimeMillis()
|
val now = System.currentTimeMillis()
|
||||||
@@ -1599,7 +2015,12 @@ object TunnelManager {
|
|||||||
lastActiveAtMs == 0L &&
|
lastActiveAtMs == 0L &&
|
||||||
!isCaptchaInProgress()
|
!isCaptchaInProgress()
|
||||||
) {
|
) {
|
||||||
handleCriticalError("\uD83D\uDD12 Неверный пароль подключения или несовместимый WRAP. Воркеры остановлены.")
|
val wrapStopMessage = if (currentParams?.rtNetwork == true) {
|
||||||
|
"\uD83C\uDF10 Через сеть РТ не получен ответ WRAP. Обычно сеть не пропустила выбранный TURN/SNI; реже причина в пароле или совместимости WRAP. Воркеры остановлены."
|
||||||
|
} else {
|
||||||
|
"\uD83D\uDD12 Неверный пароль подключения или несовместимый WRAP. Воркеры остановлены."
|
||||||
|
}
|
||||||
|
handleCriticalError(wrapStopMessage)
|
||||||
return@launch
|
return@launch
|
||||||
} else if (
|
} else if (
|
||||||
System.currentTimeMillis() - zeroWorkersSince > (if (AMNEZIA_STYLE_RECOVERY) STABLE_ZERO_WORKERS_GRACE_MS else 3 * 60_000L) &&
|
System.currentTimeMillis() - zeroWorkersSince > (if (AMNEZIA_STYLE_RECOVERY) STABLE_ZERO_WORKERS_GRACE_MS else 3 * 60_000L) &&
|
||||||
@@ -1655,6 +2076,7 @@ object TunnelManager {
|
|||||||
updateLog("network_restart", reason, 50, false)
|
updateLog("network_restart", reason, 50, false)
|
||||||
activeWorkers.value = 0
|
activeWorkers.value = 0
|
||||||
resetStatsLivenessState()
|
resetStatsLivenessState()
|
||||||
|
sessionTraffic.noteTransportRestart()
|
||||||
val restartDelayMs = transportRecoveryPolicy(
|
val restartDelayMs = transportRecoveryPolicy(
|
||||||
params.managedConfigFirstStart
|
params.managedConfigFirstStart
|
||||||
).processRestartDelayMs
|
).processRestartDelayMs
|
||||||
@@ -1715,6 +2137,7 @@ object TunnelManager {
|
|||||||
startStopMutex.lock()
|
startStopMutex.lock()
|
||||||
try {
|
try {
|
||||||
if (currentParams !== params || !running.value) return@launch
|
if (currentParams !== params || !running.value) return@launch
|
||||||
|
sessionTraffic.noteTransportRestart()
|
||||||
killProcess()
|
killProcess()
|
||||||
delay(250L)
|
delay(250L)
|
||||||
} finally {
|
} finally {
|
||||||
@@ -1761,6 +2184,30 @@ object TunnelManager {
|
|||||||
fun isNetworkTransitionGraceActive(now: Long = System.currentTimeMillis()): Boolean =
|
fun isNetworkTransitionGraceActive(now: Long = System.currentTimeMillis()): Boolean =
|
||||||
now < networkTransitionGraceUntilMs
|
now < networkTransitionGraceUntilMs
|
||||||
|
|
||||||
|
fun isWakeRecoveryGraceActive(now: Long = System.currentTimeMillis()): Boolean =
|
||||||
|
now < wakeRecoveryGraceUntilMs
|
||||||
|
|
||||||
|
fun noteDeviceSleepStarted() {
|
||||||
|
if (!running.value) return
|
||||||
|
// Ошибки, возникшие до или во время сна, нельзя переносить в решение о
|
||||||
|
// восстановлении после пробуждения: сеть и вывод статистики в этот период
|
||||||
|
// могут штатно приостанавливаться Android.
|
||||||
|
wakeRecoveryGraceUntilMs = 0L
|
||||||
|
}
|
||||||
|
|
||||||
|
fun noteDeviceWakeStarted(now: Long = System.currentTimeMillis()) {
|
||||||
|
if (!running.value) return
|
||||||
|
resetNetworkRecoveryState()
|
||||||
|
wakeRecoveryGraceUntilMs = now + WAKE_RECOVERY_GRACE_MS
|
||||||
|
networkTransitionGraceUntilMs = maxOf(networkTransitionGraceUntilMs, wakeRecoveryGraceUntilMs)
|
||||||
|
updateLog(
|
||||||
|
"wake_stabilization",
|
||||||
|
"[СОН] Устройство проснулось; даём текущему VPN восстановить активность без перезапуска.",
|
||||||
|
20,
|
||||||
|
false,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
fun connectionIssueTitleForNotification(now: Long = System.currentTimeMillis()): String? {
|
fun connectionIssueTitleForNotification(now: Long = System.currentTimeMillis()): String? {
|
||||||
val issue = connectionIssue.value ?: return null
|
val issue = connectionIssue.value ?: return null
|
||||||
if (!running.value) return null
|
if (!running.value) return null
|
||||||
@@ -1788,10 +2235,14 @@ object TunnelManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun hasFreshTunnelActivitySince(sinceMs: Long, now: Long = System.currentTimeMillis()): Boolean {
|
fun hasFreshTunnelActivitySince(sinceMs: Long, now: Long = System.currentTimeMillis()): Boolean {
|
||||||
if (!running.value || activeWorkers.value <= 0) return false
|
return hasFreshTransportHeartbeat(
|
||||||
val freshActive = lastActiveAtMs >= sinceMs && now - lastActiveAtMs < 90_000L
|
running = running.value,
|
||||||
val freshStats = lastStatsAtMs >= sinceMs && now - lastStatsAtMs < 90_000L
|
activeWorkers = activeWorkers.value,
|
||||||
return (freshActive || freshStats) && !isStatsTrafficStagnant(now)
|
lastActiveAtMs = lastActiveAtMs,
|
||||||
|
lastStatsAtMs = lastStatsAtMs,
|
||||||
|
sinceMs = sinceMs,
|
||||||
|
nowMs = now,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun noteWakeRescueStarted() {
|
fun noteWakeRescueStarted() {
|
||||||
@@ -1812,6 +2263,41 @@ object TunnelManager {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun noteWakeRescueDeferred() {
|
||||||
|
updateWarningLog(
|
||||||
|
"wake_rescue_deferred",
|
||||||
|
"[СОН] После пробуждения транспорт ещё не подал свежих признаков жизни. VPN-интерфейс оставлен активным; продолжаем наблюдение без аварийного отключения.",
|
||||||
|
50,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun noteSleepVpnPaused() {
|
||||||
|
updateLog(
|
||||||
|
"sleep_vpn_paused",
|
||||||
|
"[СОН] VPN временно отключён для экономии батареи; интернет телефона идёт напрямую.",
|
||||||
|
20,
|
||||||
|
false,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun noteSleepVpnPauseFailed() {
|
||||||
|
updateLog(
|
||||||
|
"sleep_vpn_pause_failed",
|
||||||
|
"[СОН] Режим экономии не применён: системный VPN-интерфейс не удалось безопасно остановить.",
|
||||||
|
50,
|
||||||
|
false,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun noteSleepVpnResumed() {
|
||||||
|
updateLog(
|
||||||
|
"sleep_vpn_resumed",
|
||||||
|
"[СОН] Экран включён; возобновляем VPN с сохранёнными настройками.",
|
||||||
|
20,
|
||||||
|
false,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
fun noteWakeRescueReconnect() {
|
fun noteWakeRescueReconnect() {
|
||||||
updateWarningLog(
|
updateWarningLog(
|
||||||
"wake_rescue_reconnect",
|
"wake_rescue_reconnect",
|
||||||
@@ -1837,15 +2323,16 @@ object TunnelManager {
|
|||||||
fun recreateVpnTunnel() {
|
fun recreateVpnTunnel() {
|
||||||
val params = currentParams ?: return
|
val params = currentParams ?: return
|
||||||
val context = lastContext ?: return
|
val context = lastContext ?: return
|
||||||
updateWarningLog("network_full_restart", "[СЕТЬ] Мягкие попытки не помогли, пересоздаём VPN", 50)
|
updateWarningLog("network_full_restart", "[VPN] Android потерял системный VPN-интерфейс, создаём его заново", 50)
|
||||||
scope.launch {
|
scope.launch {
|
||||||
withContext(Dispatchers.Main) {
|
withContext(Dispatchers.Main) {
|
||||||
wgHelper?.stopTunnel()
|
wgHelper?.stopTunnel()
|
||||||
}
|
}
|
||||||
|
sessionTraffic.noteTransportRestart()
|
||||||
killProcess()
|
killProcess()
|
||||||
activeWorkers.value = 0
|
activeWorkers.value = 0
|
||||||
delay(2500)
|
delay(2500)
|
||||||
if (currentParams != null) {
|
if (currentParams === params && running.value) {
|
||||||
start(context, params, isSwitching = true)
|
start(context, params, isSwitching = true)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1867,6 +2354,7 @@ object TunnelManager {
|
|||||||
|
|
||||||
fun pause() {
|
fun pause() {
|
||||||
if (!running.value) return
|
if (!running.value) return
|
||||||
|
sessionTraffic.noteTransportRestart()
|
||||||
killProcess()
|
killProcess()
|
||||||
activeWorkers.value = 0
|
activeWorkers.value = 0
|
||||||
resetStatsLivenessState()
|
resetStatsLivenessState()
|
||||||
@@ -1904,9 +2392,18 @@ object TunnelManager {
|
|||||||
try { proc.waitFor(1000, java.util.concurrent.TimeUnit.MILLISECONDS) } catch (_: Exception) {}
|
try { proc.waitFor(1000, java.util.concurrent.TimeUnit.MILLISECONDS) } catch (_: Exception) {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
closeWarpApiSshRelay()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
private fun closeWarpApiSshRelay() {
|
||||||
|
val relay = warpApiSshRelay
|
||||||
|
warpApiSshRelay = null
|
||||||
|
relay?.close()
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun stopOnlyProcess() {
|
private fun stopOnlyProcess() {
|
||||||
|
sessionTraffic.noteTransportRestart()
|
||||||
killProcess()
|
killProcess()
|
||||||
running.value = false
|
running.value = false
|
||||||
}
|
}
|
||||||
@@ -1918,29 +2415,13 @@ object TunnelManager {
|
|||||||
updateLog("stats", "[СТАТИСТИКА] $stoppedStats", 3, false)
|
updateLog("stats", "[СТАТИСТИКА] $stoppedStats", 3, false)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onWireGuardStoppedExternally() {
|
fun onWireGuardInterfaceDropped() {
|
||||||
noteStopRequested()
|
if (!running.value) return
|
||||||
scope.launch {
|
updateWarningLog(
|
||||||
startStopMutex.lock()
|
"vpn_interface_dropped",
|
||||||
try {
|
"[VPN] Android сообщил о потере системного VPN-интерфейса. Проверяем состояние перед восстановлением.",
|
||||||
if (!running.value) return@launch
|
50,
|
||||||
updateLog(
|
)
|
||||||
"vpn_released",
|
|
||||||
"[VPN] Android отключил WDTT Plus VPN или передал VPN другому приложению. Транспорт остановлен.",
|
|
||||||
50,
|
|
||||||
false
|
|
||||||
)
|
|
||||||
killProcess()
|
|
||||||
running.value = false
|
|
||||||
markLogSessionStopped(TunnelStopReason.VpnStoppedExternally)
|
|
||||||
resetStatsLivenessState()
|
|
||||||
currentParams = null
|
|
||||||
ManlCaptchaWebViewManager.cancelCaptcha()
|
|
||||||
} finally {
|
|
||||||
clearTransition()
|
|
||||||
startStopMutex.unlock()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun stop(reason: TunnelStopReason = TunnelStopReason.User) {
|
fun stop(reason: TunnelStopReason = TunnelStopReason.User) {
|
||||||
@@ -1958,6 +2439,7 @@ object TunnelManager {
|
|||||||
resetStatsLivenessState()
|
resetStatsLivenessState()
|
||||||
currentParams = null
|
currentParams = null
|
||||||
resetNetworkRecoveryState()
|
resetNetworkRecoveryState()
|
||||||
|
wakeRecoveryGraceUntilMs = 0L
|
||||||
ManlCaptchaWebViewManager.cancelCaptcha()
|
ManlCaptchaWebViewManager.cancelCaptcha()
|
||||||
} finally {
|
} finally {
|
||||||
if (reason == TunnelStopReason.User) {
|
if (reason == TunnelStopReason.User) {
|
||||||
@@ -1992,6 +2474,7 @@ object TunnelManager {
|
|||||||
resetStatsLivenessState()
|
resetStatsLivenessState()
|
||||||
currentParams = null
|
currentParams = null
|
||||||
resetNetworkRecoveryState()
|
resetNetworkRecoveryState()
|
||||||
|
wakeRecoveryGraceUntilMs = 0L
|
||||||
ManlCaptchaWebViewManager.cancelCaptcha()
|
ManlCaptchaWebViewManager.cancelCaptcha()
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
@@ -2173,6 +2656,10 @@ data class TunnelParams(
|
|||||||
val connectionPassword: String = "",
|
val connectionPassword: String = "",
|
||||||
val protocol: String = "udp",
|
val protocol: String = "udp",
|
||||||
val vkCallsPreflight: Boolean = true,
|
val vkCallsPreflight: Boolean = true,
|
||||||
|
val rtNetwork: Boolean = false,
|
||||||
|
val rtMasque: Boolean = false,
|
||||||
|
val rtMasqueServerBootstrap: Boolean = false,
|
||||||
|
val rtTurnSni: String = DEFAULT_RT_TURN_SNI,
|
||||||
val captchaMode: String = "auto",
|
val captchaMode: String = "auto",
|
||||||
val captchaSolveMethod: String = "auto",
|
val captchaSolveMethod: String = "auto",
|
||||||
val fingerprint: String = "firefox",
|
val fingerprint: String = "firefox",
|
||||||
|
|||||||
@@ -34,6 +34,7 @@ import kotlinx.coroutines.launch
|
|||||||
import kotlinx.coroutines.sync.Mutex
|
import kotlinx.coroutines.sync.Mutex
|
||||||
import kotlinx.coroutines.sync.withLock
|
import kotlinx.coroutines.sync.withLock
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
|
import kotlinx.coroutines.withTimeoutOrNull
|
||||||
import java.util.concurrent.ConcurrentHashMap
|
import java.util.concurrent.ConcurrentHashMap
|
||||||
|
|
||||||
private const val TUNNEL_NOTIFICATION_CHANNEL_ID = "wdtt_tunnel_v4"
|
private const val TUNNEL_NOTIFICATION_CHANNEL_ID = "wdtt_tunnel_v4"
|
||||||
@@ -44,14 +45,54 @@ private const val NETWORK_CHANGE_SETTLE_MS = 90_000L
|
|||||||
private const val NETWORK_RETURN_SETTLE_MS = 45_000L
|
private const val NETWORK_RETURN_SETTLE_MS = 45_000L
|
||||||
private const val NETWORK_LOSS_GRACE_MS = 2 * 60_000L
|
private const val NETWORK_LOSS_GRACE_MS = 2 * 60_000L
|
||||||
private const val WAKE_RESCUE_GRACE_MS = 60_000L
|
private const val WAKE_RESCUE_GRACE_MS = 60_000L
|
||||||
private const val WAKE_RESCUE_FAIL_OPEN_MS = 2 * 60_000L
|
|
||||||
private const val ACTIVE_PROFILE_REFRESH_INTERVAL_MS = 2 * 60_000L
|
private const val ACTIVE_PROFILE_REFRESH_INTERVAL_MS = 2 * 60_000L
|
||||||
private const val INITIAL_VPN_START_GRACE_MS = 90_000L
|
private const val INITIAL_VPN_START_GRACE_MS = 90_000L
|
||||||
|
private const val VPN_INTERFACE_MISSING_CONFIRM_MS = 90_000L
|
||||||
|
private const val VPN_INTERFACE_RECOVERY_RETRY_MS = 5 * 60_000L
|
||||||
private const val TRUSTED_WIFI_ENTER_DELAY_MS = 2_000L
|
private const val TRUSTED_WIFI_ENTER_DELAY_MS = 2_000L
|
||||||
private const val TRUSTED_WIFI_EXIT_DELAY_MS = 5_000L
|
private const val TRUSTED_WIFI_EXIT_DELAY_MS = 5_000L
|
||||||
private const val TRUSTED_WIFI_RESUME_START_TIMEOUT_MS = 30_000L
|
private const val TRUSTED_WIFI_RESUME_START_TIMEOUT_MS = 30_000L
|
||||||
private const val TRUSTED_WIFI_TRANSITION_WAKE_LOCK_TIMEOUT_MS = 75_000L
|
private const val TRUSTED_WIFI_TRANSITION_WAKE_LOCK_TIMEOUT_MS = 75_000L
|
||||||
|
|
||||||
|
internal fun shouldAttemptVpnInterfaceRecovery(
|
||||||
|
deviceInteractive: Boolean,
|
||||||
|
startupWindow: Boolean,
|
||||||
|
captchaActive: Boolean,
|
||||||
|
missingForMs: Long,
|
||||||
|
validatedNetworkAvailable: Boolean,
|
||||||
|
sinceLastAttemptMs: Long,
|
||||||
|
): Boolean =
|
||||||
|
deviceInteractive &&
|
||||||
|
!startupWindow &&
|
||||||
|
!captchaActive &&
|
||||||
|
missingForMs >= VPN_INTERFACE_MISSING_CONFIRM_MS &&
|
||||||
|
validatedNetworkAvailable &&
|
||||||
|
sinceLastAttemptMs >= VPN_INTERFACE_RECOVERY_RETRY_MS
|
||||||
|
|
||||||
|
internal fun shouldPauseVpnForSleep(
|
||||||
|
pauseEnabled: Boolean,
|
||||||
|
deviceInteractive: Boolean,
|
||||||
|
tunnelRunning: Boolean,
|
||||||
|
tunnelPaused: Boolean,
|
||||||
|
trustedWifiWaiting: Boolean,
|
||||||
|
): Boolean =
|
||||||
|
pauseEnabled &&
|
||||||
|
!deviceInteractive &&
|
||||||
|
tunnelRunning &&
|
||||||
|
!tunnelPaused &&
|
||||||
|
!trustedWifiWaiting
|
||||||
|
|
||||||
|
internal fun shouldResumeVpnAfterSleep(
|
||||||
|
sleepPausedByPolicy: Boolean,
|
||||||
|
tunnelRunning: Boolean,
|
||||||
|
tunnelPaused: Boolean,
|
||||||
|
trustedWifiWaiting: Boolean,
|
||||||
|
): Boolean =
|
||||||
|
sleepPausedByPolicy &&
|
||||||
|
tunnelRunning &&
|
||||||
|
tunnelPaused &&
|
||||||
|
!trustedWifiWaiting
|
||||||
|
|
||||||
class TunnelService : Service() {
|
class TunnelService : Service() {
|
||||||
private val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
|
private val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
|
||||||
private val startRequestGate = TunnelStartRequestGate()
|
private val startRequestGate = TunnelStartRequestGate()
|
||||||
@@ -83,9 +124,16 @@ class TunnelService : Service() {
|
|||||||
private var lastValidatedNetwork: Network? = null
|
private var lastValidatedNetwork: Network? = null
|
||||||
private var lastStableNetworkReconnectAt = 0L
|
private var lastStableNetworkReconnectAt = 0L
|
||||||
private var stableNetworkWasLost = false
|
private var stableNetworkWasLost = false
|
||||||
|
private var vpnInterfaceMissingSinceMs = 0L
|
||||||
|
private var lastVpnInterfaceRecoveryAttemptAtMs = 0L
|
||||||
private var screenStateReceiver: BroadcastReceiver? = null
|
private var screenStateReceiver: BroadcastReceiver? = null
|
||||||
private var trustedWifiStateReceiver: BroadcastReceiver? = null
|
private var trustedWifiStateReceiver: BroadcastReceiver? = null
|
||||||
private var wakeRescueJob: Job? = null
|
private var wakeRescueJob: Job? = null
|
||||||
|
private var sleepPauseJob: Job? = null
|
||||||
|
private val sleepTransitionMutex = Mutex()
|
||||||
|
private var lastKnownDeviceInteractive = true
|
||||||
|
@Volatile
|
||||||
|
private var sleepPausedByPolicy = false
|
||||||
private var trustedWifiNetworkCallback: ConnectivityManager.NetworkCallback? = null
|
private var trustedWifiNetworkCallback: ConnectivityManager.NetworkCallback? = null
|
||||||
private var trustedWifiSettingsJob: Job? = null
|
private var trustedWifiSettingsJob: Job? = null
|
||||||
private var trustedWifiEvaluationJob: Job? = null
|
private var trustedWifiEvaluationJob: Job? = null
|
||||||
@@ -107,6 +155,10 @@ class TunnelService : Service() {
|
|||||||
override fun onCreate() {
|
override fun onCreate() {
|
||||||
super.onCreate()
|
super.onCreate()
|
||||||
createNotificationChannel()
|
createNotificationChannel()
|
||||||
|
lastKnownDeviceInteractive = isDeviceInteractive()
|
||||||
|
if (!lastKnownDeviceInteractive) {
|
||||||
|
TunnelManager.noteDeviceSleepStarted()
|
||||||
|
}
|
||||||
// Сразу берем лок при создании
|
// Сразу берем лок при создании
|
||||||
acquireWakeLock()
|
acquireWakeLock()
|
||||||
setupNetworkCallback()
|
setupNetworkCallback()
|
||||||
@@ -121,6 +173,7 @@ class TunnelService : Service() {
|
|||||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||||
if (intent == null) {
|
if (intent == null) {
|
||||||
restoreTunnel()
|
restoreTunnel()
|
||||||
|
scheduleSleepPauseIfNeeded()
|
||||||
return START_STICKY
|
return START_STICKY
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -139,6 +192,11 @@ class TunnelService : Service() {
|
|||||||
connectionPassword = intent.getStringExtra("connection_password") ?: "",
|
connectionPassword = intent.getStringExtra("connection_password") ?: "",
|
||||||
protocol = intent.getStringExtra("protocol") ?: "udp",
|
protocol = intent.getStringExtra("protocol") ?: "udp",
|
||||||
vkCallsPreflight = intent.getBooleanExtra("vkcalls_preflight", true),
|
vkCallsPreflight = intent.getBooleanExtra("vkcalls_preflight", true),
|
||||||
|
rtNetwork = intent.getBooleanExtra("rt_network", false),
|
||||||
|
rtMasque = intent.getBooleanExtra("rt_masque", false),
|
||||||
|
rtMasqueServerBootstrap =
|
||||||
|
intent.getBooleanExtra("rt_masque_server_bootstrap", false),
|
||||||
|
rtTurnSni = intent.getStringExtra("rt_turn_sni") ?: DEFAULT_RT_TURN_SNI,
|
||||||
captchaMode = sanitizeCaptchaMode(intent.getStringExtra("captcha_mode")),
|
captchaMode = sanitizeCaptchaMode(intent.getStringExtra("captcha_mode")),
|
||||||
captchaSolveMethod = intent.getStringExtra("captcha_solve_method") ?: "auto",
|
captchaSolveMethod = intent.getStringExtra("captcha_solve_method") ?: "auto",
|
||||||
fingerprint = intent.getStringExtra("fingerprint") ?: "firefox",
|
fingerprint = intent.getStringExtra("fingerprint") ?: "firefox",
|
||||||
@@ -152,6 +210,7 @@ class TunnelService : Service() {
|
|||||||
profileIndex = intent.getIntExtra(TUNNEL_PROFILE_INDEX_EXTRA, 0).coerceIn(0, 2),
|
profileIndex = intent.getIntExtra(TUNNEL_PROFILE_INDEX_EXTRA, 0).coerceIn(0, 2),
|
||||||
)
|
)
|
||||||
requestTunnelStart(params)
|
requestTunnelStart(params)
|
||||||
|
scheduleSleepPauseIfNeeded()
|
||||||
}
|
}
|
||||||
"STOP" -> stopTunnel(TunnelStopReason.User)
|
"STOP" -> stopTunnel(TunnelStopReason.User)
|
||||||
"DEPLOY_START" -> {
|
"DEPLOY_START" -> {
|
||||||
@@ -359,6 +418,8 @@ class TunnelService : Service() {
|
|||||||
cancelTrustedWifiResumeRetry(resetCount = !fromTrustedWifiResume)
|
cancelTrustedWifiResumeRetry(resetCount = !fromTrustedWifiResume)
|
||||||
trustedWifiResumeInProgress = fromTrustedWifiResume
|
trustedWifiResumeInProgress = fromTrustedWifiResume
|
||||||
trustedWifiResumeStartedAt = if (fromTrustedWifiResume) System.currentTimeMillis() else 0L
|
trustedWifiResumeStartedAt = if (fromTrustedWifiResume) System.currentTimeMillis() else 0L
|
||||||
|
sleepPausedByPolicy = false
|
||||||
|
isTunnelPaused = false
|
||||||
trustedWifiWaiting = false
|
trustedWifiWaiting = false
|
||||||
trustedWifiWaitingSsid = ""
|
trustedWifiWaitingSsid = ""
|
||||||
lastStartParams = params
|
lastStartParams = params
|
||||||
@@ -386,11 +447,16 @@ class TunnelService : Service() {
|
|||||||
startNotificationProfileWatcher()
|
startNotificationProfileWatcher()
|
||||||
startStatsUpdater()
|
startStatsUpdater()
|
||||||
startActiveProfileRefresh(params.profileIndex)
|
startActiveProfileRefresh(params.profileIndex)
|
||||||
|
scheduleSleepPauseIfNeeded()
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun stopTunnel(reason: TunnelStopReason = TunnelStopReason.User) {
|
private fun stopTunnel(reason: TunnelStopReason = TunnelStopReason.User) {
|
||||||
TunnelManager.noteStopRequested()
|
TunnelManager.noteStopRequested()
|
||||||
if (stopSequenceJob?.isActive == true) return
|
if (stopSequenceJob?.isActive == true) return
|
||||||
|
sleepPausedByPolicy = false
|
||||||
|
sleepPauseJob?.cancel()
|
||||||
|
sleepPauseJob = null
|
||||||
|
isTunnelPaused = false
|
||||||
invalidatePendingStart()
|
invalidatePendingStart()
|
||||||
val effectiveReason = requestedStopReason ?: reason
|
val effectiveReason = requestedStopReason ?: reason
|
||||||
requestedStopReason = effectiveReason
|
requestedStopReason = effectiveReason
|
||||||
@@ -512,12 +578,16 @@ class TunnelService : Service() {
|
|||||||
override fun onReceive(context: Context?, intent: Intent?) {
|
override fun onReceive(context: Context?, intent: Intent?) {
|
||||||
when (intent?.action) {
|
when (intent?.action) {
|
||||||
Intent.ACTION_SCREEN_ON -> {
|
Intent.ACTION_SCREEN_ON -> {
|
||||||
|
observeDeviceInteractiveState(interactive = true)
|
||||||
|
resumeSleepPausedTunnelIfNeeded()
|
||||||
scheduleWakeRescueCheck()
|
scheduleWakeRescueCheck()
|
||||||
scheduleTrustedWifiEvaluation(delayMs = 0L)
|
scheduleTrustedWifiEvaluation(delayMs = 0L)
|
||||||
}
|
}
|
||||||
Intent.ACTION_SCREEN_OFF -> {
|
Intent.ACTION_SCREEN_OFF -> {
|
||||||
|
observeDeviceInteractiveState(interactive = false)
|
||||||
wakeRescueJob?.cancel()
|
wakeRescueJob?.cancel()
|
||||||
wakeRescueJob = null
|
wakeRescueJob = null
|
||||||
|
scheduleSleepPauseIfNeeded()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -534,6 +604,86 @@ class TunnelService : Service() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun scheduleSleepPauseIfNeeded() {
|
||||||
|
sleepPauseJob?.cancel()
|
||||||
|
sleepPauseJob = serviceScope.launch {
|
||||||
|
val pauseEnabled = SettingsStore(applicationContext).pauseVpnDuringSleep.first()
|
||||||
|
if (isDeviceInteractive() || !pauseEnabled) return@launch
|
||||||
|
|
||||||
|
val tunnelStarted = withTimeoutOrNull(15_000L) {
|
||||||
|
while (isActive && !TunnelManager.running.value) {
|
||||||
|
delay(250L)
|
||||||
|
}
|
||||||
|
TunnelManager.running.value
|
||||||
|
} ?: false
|
||||||
|
if (!tunnelStarted) return@launch
|
||||||
|
|
||||||
|
sleepTransitionMutex.withLock {
|
||||||
|
if (
|
||||||
|
!shouldPauseVpnForSleep(
|
||||||
|
pauseEnabled = pauseEnabled,
|
||||||
|
deviceInteractive = isDeviceInteractive(),
|
||||||
|
tunnelRunning = TunnelManager.running.value,
|
||||||
|
tunnelPaused = isTunnelPaused,
|
||||||
|
trustedWifiWaiting = trustedWifiWaiting,
|
||||||
|
)
|
||||||
|
) return@withLock
|
||||||
|
|
||||||
|
sleepPausedByPolicy = true
|
||||||
|
isTunnelPaused = true
|
||||||
|
val interfaceStopped = withContext(Dispatchers.IO) {
|
||||||
|
// Освобождаем и нативный транспорт, и системный VPN-интерфейс:
|
||||||
|
// иначе при паузе трафик остался бы внутри пустого туннеля.
|
||||||
|
TunnelManager.pause()
|
||||||
|
val helper = WireGuardHelper(applicationContext)
|
||||||
|
helper.stopTunnel()
|
||||||
|
!helper.isTunnelUp()
|
||||||
|
}
|
||||||
|
if (!interfaceStopped) {
|
||||||
|
// Не оставляем телефон без рабочего маршрута, если Android
|
||||||
|
// не подтвердил остановку системного VPN-интерфейса.
|
||||||
|
sleepPausedByPolicy = false
|
||||||
|
isTunnelPaused = false
|
||||||
|
acquireWakeLock()
|
||||||
|
acquireWifiLock()
|
||||||
|
TunnelManager.resume()
|
||||||
|
TunnelManager.noteSleepVpnPauseFailed()
|
||||||
|
updateNotification("VPN остаётся активным")
|
||||||
|
return@withLock
|
||||||
|
}
|
||||||
|
TunnelManager.noteSleepVpnPaused()
|
||||||
|
releaseWakeLock()
|
||||||
|
releaseWifiLock()
|
||||||
|
updateNotification("VPN выключен во сне · интернет напрямую")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun resumeSleepPausedTunnelIfNeeded() {
|
||||||
|
sleepPauseJob?.cancel()
|
||||||
|
sleepPauseJob = null
|
||||||
|
serviceScope.launch {
|
||||||
|
sleepTransitionMutex.withLock {
|
||||||
|
if (
|
||||||
|
!shouldResumeVpnAfterSleep(
|
||||||
|
sleepPausedByPolicy = sleepPausedByPolicy,
|
||||||
|
tunnelRunning = TunnelManager.running.value,
|
||||||
|
tunnelPaused = isTunnelPaused,
|
||||||
|
trustedWifiWaiting = trustedWifiWaiting,
|
||||||
|
)
|
||||||
|
) return@withLock
|
||||||
|
|
||||||
|
sleepPausedByPolicy = false
|
||||||
|
isTunnelPaused = false
|
||||||
|
acquireWakeLock()
|
||||||
|
acquireWifiLock()
|
||||||
|
updateNotification("Восстановление VPN...")
|
||||||
|
TunnelManager.noteSleepVpnResumed()
|
||||||
|
TunnelManager.resume()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun registerTrustedWifiStateReceiver() {
|
private fun registerTrustedWifiStateReceiver() {
|
||||||
if (trustedWifiStateReceiver != null) return
|
if (trustedWifiStateReceiver != null) return
|
||||||
trustedWifiStateReceiver = object : BroadcastReceiver() {
|
trustedWifiStateReceiver = object : BroadcastReceiver() {
|
||||||
@@ -586,52 +736,21 @@ class TunnelService : Service() {
|
|||||||
|
|
||||||
private fun scheduleWakeRescueCheck() {
|
private fun scheduleWakeRescueCheck() {
|
||||||
if (!AMNEZIA_STYLE_RECOVERY || !TunnelManager.running.value || isTunnelPaused || TunnelManager.isCaptchaInProgress()) return
|
if (!AMNEZIA_STYLE_RECOVERY || !TunnelManager.running.value || isTunnelPaused || TunnelManager.isCaptchaInProgress()) return
|
||||||
val wakeAt = System.currentTimeMillis()
|
|
||||||
TunnelManager.noteWakeRescueStarted()
|
TunnelManager.noteWakeRescueStarted()
|
||||||
updateNotification("Проверка VPN после сна...")
|
|
||||||
|
|
||||||
wakeRescueJob?.cancel()
|
wakeRescueJob?.cancel()
|
||||||
wakeRescueJob = TunnelManager.scope.launch(Dispatchers.Main) {
|
wakeRescueJob = TunnelManager.scope.launch(Dispatchers.Main) {
|
||||||
delay(WAKE_RESCUE_GRACE_MS)
|
delay(WAKE_RESCUE_GRACE_MS)
|
||||||
if (!TunnelManager.running.value || isTunnelPaused || TunnelManager.isCaptchaInProgress()) return@launch
|
if (!TunnelManager.running.value || isTunnelPaused || TunnelManager.isCaptchaInProgress()) return@launch
|
||||||
if (TunnelManager.hasFreshTunnelActivitySince(wakeAt)) {
|
if (TunnelManager.hasFreshTunnelActivitySince(System.currentTimeMillis() - WAKE_RESCUE_GRACE_MS)) {
|
||||||
TunnelManager.noteWakeRescueHealthy()
|
TunnelManager.noteWakeRescueHealthy()
|
||||||
updateNotification(buildTunnelNotificationText())
|
} else {
|
||||||
return@launch
|
// Выход из сна сам по себе не является доказательством поломки:
|
||||||
|
// Android и оператор могут на короткое время задержать вывод статистики.
|
||||||
|
// Не перезапускаем ни native-транспорт, ни системный VPN-интерфейс.
|
||||||
|
TunnelManager.noteWakeRescueDeferred()
|
||||||
}
|
}
|
||||||
|
updateNotification(buildTunnelNotificationText())
|
||||||
if (TunnelManager.isNetworkTransitionGraceActive()) {
|
|
||||||
updateNotification(buildTunnelNotificationText())
|
|
||||||
return@launch
|
|
||||||
}
|
|
||||||
val reconnectAt = System.currentTimeMillis()
|
|
||||||
val restarted = TunnelManager.restartTransport(
|
|
||||||
reason = "[СОН] После пробуждения VPN не подал признаков жизни. Мягко переподключаю транспорт.",
|
|
||||||
minIntervalMs = 60_000L
|
|
||||||
)
|
|
||||||
if (!restarted) {
|
|
||||||
// Другая ветка восстановления уже перезапускает транспорт либо ещё действует
|
|
||||||
// её защитный интервал. Не запускаем параллельный таймер, который мог бы
|
|
||||||
// ошибочно остановить уже восстанавливающийся VPN.
|
|
||||||
updateNotification(buildTunnelNotificationText())
|
|
||||||
return@launch
|
|
||||||
}
|
|
||||||
updateNotification("Восстановление VPN...")
|
|
||||||
|
|
||||||
delay(WAKE_RESCUE_FAIL_OPEN_MS)
|
|
||||||
if (!TunnelManager.running.value || isTunnelPaused || TunnelManager.isCaptchaInProgress()) return@launch
|
|
||||||
if (TunnelManager.hasFreshTunnelActivitySince(reconnectAt)) {
|
|
||||||
TunnelManager.noteWakeRescueHealthy()
|
|
||||||
updateNotification(buildTunnelNotificationText())
|
|
||||||
return@launch
|
|
||||||
}
|
|
||||||
|
|
||||||
TunnelManager.markStoppedAfterWakeRescue()
|
|
||||||
showTunnelAlertNotification(
|
|
||||||
"WDTT Plus остановил VPN",
|
|
||||||
"После пробуждения VPN не восстановился, поэтому приложение выключило VPN и вернуло прямой интернет."
|
|
||||||
)
|
|
||||||
stopTunnel(TunnelStopReason.WakeRecoveryFailed)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1147,6 +1266,7 @@ class TunnelService : Service() {
|
|||||||
|
|
||||||
private fun scheduleStableValidatedReconnect(reason: String) {
|
private fun scheduleStableValidatedReconnect(reason: String) {
|
||||||
val now = System.currentTimeMillis()
|
val now = System.currentTimeMillis()
|
||||||
|
val interactiveAtSchedule = isDeviceInteractive()
|
||||||
lastNetworkChangeTime = now
|
lastNetworkChangeTime = now
|
||||||
|
|
||||||
if (!TunnelManager.running.value || isTunnelPaused) return
|
if (!TunnelManager.running.value || isTunnelPaused) return
|
||||||
@@ -1163,6 +1283,18 @@ class TunnelService : Service() {
|
|||||||
Log.d("TunnelService", "$reason, ждём короткую стабилизацию перед reconnect")
|
Log.d("TunnelService", "$reason, ждём короткую стабилизацию перед reconnect")
|
||||||
delay(recoveryPolicy.networkSettleDelayMs)
|
delay(recoveryPolicy.networkSettleDelayMs)
|
||||||
if (lastNetworkChangeTime != now) return@launch
|
if (lastNetworkChangeTime != now) return@launch
|
||||||
|
// Смена underlying-сети во время сна часто является только
|
||||||
|
// восстановлением мобильного/Wi-Fi интерфейса Android. Не трогаем
|
||||||
|
// native-транспорт и VPN при таком событии ни во сне, ни если экран
|
||||||
|
// успел погаснуть до окончания стабилизации.
|
||||||
|
if (!interactiveAtSchedule || !isDeviceInteractive()) {
|
||||||
|
Log.d("TunnelService", "Пропускаем reconnect: событие сети пришло во время сна")
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
|
if (TunnelManager.isWakeRecoveryGraceActive()) {
|
||||||
|
Log.d("TunnelService", "Пропускаем reconnect: после пробуждения ещё действует стабилизация")
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
if (!TunnelManager.running.value || !hasAnyRealNetwork() || TunnelManager.isCaptchaInProgress()) return@launch
|
if (!TunnelManager.running.value || !hasAnyRealNetwork() || TunnelManager.isCaptchaInProgress()) return@launch
|
||||||
|
|
||||||
val sinceLastReconnect = System.currentTimeMillis() - lastStableNetworkReconnectAt
|
val sinceLastReconnect = System.currentTimeMillis() - lastStableNetworkReconnectAt
|
||||||
@@ -1170,6 +1302,10 @@ class TunnelService : Service() {
|
|||||||
Log.d("TunnelService", "Пропускаем reconnect: недавний reconnect уже был")
|
Log.d("TunnelService", "Пропускаем reconnect: недавний reconnect уже был")
|
||||||
return@launch
|
return@launch
|
||||||
}
|
}
|
||||||
|
if (TunnelManager.hasFreshTunnelActivitySince(now)) {
|
||||||
|
Log.d("TunnelService", "Пропускаем reconnect: транспорт уже активен на подтверждённой сети")
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
lastStableNetworkReconnectAt = System.currentTimeMillis()
|
lastStableNetworkReconnectAt = System.currentTimeMillis()
|
||||||
TunnelManager.restartTransport(
|
TunnelManager.restartTransport(
|
||||||
reason = "[СЕТЬ] Android подтвердил новую сеть. Мягко переподключаю транспорт.",
|
reason = "[СЕТЬ] Android подтвердил новую сеть. Мягко переподключаю транспорт.",
|
||||||
@@ -1190,6 +1326,30 @@ class TunnelService : Service() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
private fun hasValidatedRealNetwork(): Boolean {
|
||||||
|
val cm = connectivityManager ?: return false
|
||||||
|
return cm.allNetworks.any { network ->
|
||||||
|
val caps = cm.getNetworkCapabilities(network) ?: return@any false
|
||||||
|
caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) &&
|
||||||
|
caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN) &&
|
||||||
|
caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun isDeviceInteractive(): Boolean =
|
||||||
|
(getSystemService(POWER_SERVICE) as PowerManager).isInteractive
|
||||||
|
|
||||||
|
private fun observeDeviceInteractiveState(interactive: Boolean) {
|
||||||
|
if (lastKnownDeviceInteractive == interactive) return
|
||||||
|
lastKnownDeviceInteractive = interactive
|
||||||
|
if (interactive) {
|
||||||
|
TunnelManager.noteDeviceWakeStarted()
|
||||||
|
} else {
|
||||||
|
TunnelManager.noteDeviceSleepStarted()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Suppress("DEPRECATION")
|
@Suppress("DEPRECATION")
|
||||||
private fun hasUsableRealNetworkForTrustedWifiResume(): Boolean {
|
private fun hasUsableRealNetworkForTrustedWifiResume(): Boolean {
|
||||||
return trustedWifiValidatedNetworks.hasUsableNetwork()
|
return trustedWifiValidatedNetworks.hasUsableNetwork()
|
||||||
@@ -1385,6 +1545,15 @@ class TunnelService : Service() {
|
|||||||
if (
|
if (
|
||||||
!shouldKeepTunnelServiceAlive(
|
!shouldKeepTunnelServiceAlive(
|
||||||
tunnelRunning = TunnelManager.running.value,
|
tunnelRunning = TunnelManager.running.value,
|
||||||
|
tunnelStarting =
|
||||||
|
TunnelManager.transition.value == TunnelTransition.STARTING &&
|
||||||
|
lastStartParams?.let { params ->
|
||||||
|
shouldUseRtMasqueServerBootstrap(
|
||||||
|
rtNetwork = params.rtNetwork,
|
||||||
|
rtMasque = params.rtMasque,
|
||||||
|
serverBootstrap = params.rtMasqueServerBootstrap,
|
||||||
|
)
|
||||||
|
} == true,
|
||||||
tunnelPaused = isTunnelPaused,
|
tunnelPaused = isTunnelPaused,
|
||||||
trustedWifiWaiting = trustedWifiWaiting,
|
trustedWifiWaiting = trustedWifiWaiting,
|
||||||
trustedWifiResumeInProgress = trustedWifiResumeInProgress
|
trustedWifiResumeInProgress = trustedWifiResumeInProgress
|
||||||
@@ -1403,12 +1572,51 @@ class TunnelService : Service() {
|
|||||||
stopTunnel(TunnelStopReason.VpnSlotTransferred)
|
stopTunnel(TunnelStopReason.VpnSlotTransferred)
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
if (!startupWindow && !captchaActive && !helper.isTunnelUp()) {
|
val deviceInteractive = isDeviceInteractive()
|
||||||
Log.w("TunnelService", "Обнаружена пропажа или замена VPN-интерфейса! Экстренное выключение туннеля.")
|
// Не полагаемся только на broadcast: после глубокого сна первая
|
||||||
stopTunnel(TunnelStopReason.VpnInterfaceLost)
|
// итерация службы иногда выполняется раньше ACTION_SCREEN_ON.
|
||||||
break
|
observeDeviceInteractiveState(deviceInteractive)
|
||||||
|
val shouldInspectVpnInterface =
|
||||||
|
deviceInteractive && !startupWindow && !captchaActive
|
||||||
|
val vpnInterfaceUp = !shouldInspectVpnInterface || helper.isTunnelUp()
|
||||||
|
if (vpnInterfaceUp) {
|
||||||
|
vpnInterfaceMissingSinceMs = 0L
|
||||||
|
lastVpnInterfaceRecoveryAttemptAtMs = 0L
|
||||||
|
} else {
|
||||||
|
val now = System.currentTimeMillis()
|
||||||
|
if (vpnInterfaceMissingSinceMs == 0L) {
|
||||||
|
vpnInterfaceMissingSinceMs = now
|
||||||
|
Log.w(
|
||||||
|
"TunnelService",
|
||||||
|
"Системный VPN-интерфейс не найден. Подтверждаем состояние перед восстановлением."
|
||||||
|
)
|
||||||
|
}
|
||||||
|
val missingForMs = now - vpnInterfaceMissingSinceMs
|
||||||
|
val sinceLastAttemptMs = if (lastVpnInterfaceRecoveryAttemptAtMs == 0L) {
|
||||||
|
Long.MAX_VALUE
|
||||||
|
} else {
|
||||||
|
now - lastVpnInterfaceRecoveryAttemptAtMs
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
shouldAttemptVpnInterfaceRecovery(
|
||||||
|
deviceInteractive = deviceInteractive,
|
||||||
|
startupWindow = startupWindow,
|
||||||
|
captchaActive = captchaActive,
|
||||||
|
missingForMs = missingForMs,
|
||||||
|
validatedNetworkAvailable = hasValidatedRealNetwork(),
|
||||||
|
sinceLastAttemptMs = sinceLastAttemptMs,
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
lastVpnInterfaceRecoveryAttemptAtMs = now
|
||||||
|
Log.w(
|
||||||
|
"TunnelService",
|
||||||
|
"Потеря VPN-интерфейса подтверждена на рабочей сети. Создаём его заново."
|
||||||
|
)
|
||||||
|
updateNotification("Восстановление VPN...")
|
||||||
|
TunnelManager.recreateVpnTunnel()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (!startupWindow && !captchaActive) {
|
if (!startupWindow && !captchaActive && vpnInterfaceUp && deviceInteractive) {
|
||||||
when (TunnelManager.pollNetworkRecoveryAction()) {
|
when (TunnelManager.pollNetworkRecoveryAction()) {
|
||||||
NetworkRecoveryAction.SoftRestart -> {
|
NetworkRecoveryAction.SoftRestart -> {
|
||||||
Log.w("TunnelService", "Сетевая ошибка туннеля. Мягко перезапускаем транспорт.")
|
Log.w("TunnelService", "Сетевая ошибка туннеля. Мягко перезапускаем транспорт.")
|
||||||
@@ -1417,11 +1625,6 @@ class TunnelService : Service() {
|
|||||||
minIntervalMs = 20_000L
|
minIntervalMs = 20_000L
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
NetworkRecoveryAction.RecreateVpn -> {
|
|
||||||
Log.w("TunnelService", "Мягкие попытки не помогли. Пересоздаём VPN-туннель.")
|
|
||||||
updateNotification("Пересоздание VPN...")
|
|
||||||
TunnelManager.recreateVpnTunnel()
|
|
||||||
}
|
|
||||||
NetworkRecoveryAction.StopVpn -> {
|
NetworkRecoveryAction.StopVpn -> {
|
||||||
Log.w("TunnelService", "Автовосстановление не помогло. Останавливаем VPN, чтобы вернуть интернет.")
|
Log.w("TunnelService", "Автовосстановление не помогло. Останавливаем VPN, чтобы вернуть интернет.")
|
||||||
TunnelManager.markStoppedAfterFailedRecovery()
|
TunnelManager.markStoppedAfterFailedRecovery()
|
||||||
|
|||||||
@@ -0,0 +1,63 @@
|
|||||||
|
package com.wdtt.plus
|
||||||
|
|
||||||
|
import java.util.Locale
|
||||||
|
|
||||||
|
private val tunnelTrafficPairRegex = Regex(
|
||||||
|
"↓\\s*([0-9]+(?:[.,][0-9]+)?)\\s*МБ\\s*/\\s*↑\\s*([0-9]+(?:[.,][0-9]+)?)\\s*МБ"
|
||||||
|
)
|
||||||
|
|
||||||
|
internal class TunnelSessionTrafficAccumulator {
|
||||||
|
private var downloadOffsetMb = 0.0
|
||||||
|
private var uploadOffsetMb = 0.0
|
||||||
|
private var lastRawDownloadMb: Double? = null
|
||||||
|
private var lastRawUploadMb: Double? = null
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun reset() {
|
||||||
|
downloadOffsetMb = 0.0
|
||||||
|
uploadOffsetMb = 0.0
|
||||||
|
lastRawDownloadMb = null
|
||||||
|
lastRawUploadMb = null
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun noteTransportRestart() {
|
||||||
|
downloadOffsetMb += lastRawDownloadMb ?: 0.0
|
||||||
|
uploadOffsetMb += lastRawUploadMb ?: 0.0
|
||||||
|
lastRawDownloadMb = null
|
||||||
|
lastRawUploadMb = null
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun accumulate(message: String): String {
|
||||||
|
val match = tunnelTrafficPairRegex.find(message) ?: return message
|
||||||
|
val rawDownload = match.groupValues[1].toTrafficDouble() ?: return message
|
||||||
|
val rawUpload = match.groupValues[2].toTrafficDouble() ?: return message
|
||||||
|
|
||||||
|
val previousDownload = lastRawDownloadMb
|
||||||
|
val previousUpload = lastRawUploadMb
|
||||||
|
if (previousDownload != null && rawDownload + TRAFFIC_RESET_TOLERANCE_MB < previousDownload) {
|
||||||
|
downloadOffsetMb += previousDownload
|
||||||
|
}
|
||||||
|
if (previousUpload != null && rawUpload + TRAFFIC_RESET_TOLERANCE_MB < previousUpload) {
|
||||||
|
uploadOffsetMb += previousUpload
|
||||||
|
}
|
||||||
|
|
||||||
|
lastRawDownloadMb = rawDownload
|
||||||
|
lastRawUploadMb = rawUpload
|
||||||
|
|
||||||
|
val replacement = "↓${formatTrafficMb(downloadOffsetMb + rawDownload)} МБ / " +
|
||||||
|
"↑${formatTrafficMb(uploadOffsetMb + rawUpload)} МБ"
|
||||||
|
return message.replaceRange(match.range, replacement)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun String.toTrafficDouble(): Double? =
|
||||||
|
replace(',', '.').toDoubleOrNull()
|
||||||
|
|
||||||
|
private fun formatTrafficMb(value: Double): String =
|
||||||
|
String.format(Locale.US, "%.2f", value)
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val TRAFFIC_RESET_TOLERANCE_MB = 0.005
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,6 +5,33 @@ import android.content.Intent
|
|||||||
|
|
||||||
internal const val TUNNEL_PROFILE_INDEX_EXTRA = "profile_index"
|
internal const val TUNNEL_PROFILE_INDEX_EXTRA = "profile_index"
|
||||||
internal const val MANAGED_CONFIG_FIRST_START_EXTRA = "managed_config_first_start"
|
internal const val MANAGED_CONFIG_FIRST_START_EXTRA = "managed_config_first_start"
|
||||||
|
internal const val DEFAULT_RT_TURN_SNI = "ya.ru"
|
||||||
|
|
||||||
|
internal fun normalizeRtTurnSni(value: String): String? {
|
||||||
|
val host = value.trim().lowercase()
|
||||||
|
if (
|
||||||
|
host.isBlank() ||
|
||||||
|
host.length > 253 ||
|
||||||
|
host.startsWith(".") ||
|
||||||
|
host.endsWith(".") ||
|
||||||
|
host.contains("..")
|
||||||
|
) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
val labels = host.split('.')
|
||||||
|
if (labels.size < 2 || labels.all { it.toIntOrNull() != null }) return null
|
||||||
|
return host.takeIf {
|
||||||
|
labels.all { label ->
|
||||||
|
label.isNotBlank() &&
|
||||||
|
label.length <= 63 &&
|
||||||
|
!label.startsWith("-") &&
|
||||||
|
!label.endsWith("-") &&
|
||||||
|
label.all { char ->
|
||||||
|
char in 'a'..'z' || char in '0'..'9' || char == '-'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
internal data class TransportRecoveryPolicy(
|
internal data class TransportRecoveryPolicy(
|
||||||
val networkSettleDelayMs: Long,
|
val networkSettleDelayMs: Long,
|
||||||
@@ -15,18 +42,12 @@ internal data class TransportRecoveryPolicy(
|
|||||||
|
|
||||||
internal fun transportRecoveryPolicy(
|
internal fun transportRecoveryPolicy(
|
||||||
managedConfigFirstStart: Boolean,
|
managedConfigFirstStart: Boolean,
|
||||||
): TransportRecoveryPolicy = if (managedConfigFirstStart) {
|
): TransportRecoveryPolicy {
|
||||||
TransportRecoveryPolicy(
|
val processRestartDelayMs = if (managedConfigFirstStart) 250L else 2_500L
|
||||||
networkSettleDelayMs = 3_000L,
|
return TransportRecoveryPolicy(
|
||||||
reconnectMinIntervalMs = 8_000L,
|
|
||||||
processRestartDelayMs = 250L,
|
|
||||||
forceRestart = true,
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
TransportRecoveryPolicy(
|
|
||||||
networkSettleDelayMs = 15_000L,
|
networkSettleDelayMs = 15_000L,
|
||||||
reconnectMinIntervalMs = 2 * 60_000L,
|
reconnectMinIntervalMs = 2 * 60_000L,
|
||||||
processRestartDelayMs = 2_500L,
|
processRestartDelayMs = processRestartDelayMs,
|
||||||
forceRestart = false,
|
forceRestart = false,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -96,6 +117,11 @@ internal fun buildTunnelParams(saved: TunnelProfileSnapshot): TunnelParams? {
|
|||||||
connectionPassword = linkParts.password,
|
connectionPassword = linkParts.password,
|
||||||
protocol = saved.protocol,
|
protocol = saved.protocol,
|
||||||
vkCallsPreflight = saved.vkCallsPreflight,
|
vkCallsPreflight = saved.vkCallsPreflight,
|
||||||
|
rtNetwork = saved.rtNetwork,
|
||||||
|
rtMasque = saved.rtMasque,
|
||||||
|
rtMasqueServerBootstrap =
|
||||||
|
saved.rtMasqueServerBootstrap && saved.rtMasqueServerAccessReady,
|
||||||
|
rtTurnSni = saved.rtTurnSni,
|
||||||
captchaMode = sanitizeTunnelCaptchaMode(saved.captchaMode),
|
captchaMode = sanitizeTunnelCaptchaMode(saved.captchaMode),
|
||||||
captchaSolveMethod = saved.captchaSolveMethod,
|
captchaSolveMethod = saved.captchaSolveMethod,
|
||||||
fingerprint = saved.fingerprint,
|
fingerprint = saved.fingerprint,
|
||||||
@@ -127,6 +153,11 @@ internal fun buildTunnelParams(saved: TunnelProfileSnapshot): TunnelParams? {
|
|||||||
connectionPassword = password,
|
connectionPassword = password,
|
||||||
protocol = saved.protocol,
|
protocol = saved.protocol,
|
||||||
vkCallsPreflight = saved.vkCallsPreflight,
|
vkCallsPreflight = saved.vkCallsPreflight,
|
||||||
|
rtNetwork = saved.rtNetwork,
|
||||||
|
rtMasque = saved.rtMasque,
|
||||||
|
rtMasqueServerBootstrap =
|
||||||
|
saved.rtMasqueServerBootstrap && saved.rtMasqueServerAccessReady,
|
||||||
|
rtTurnSni = saved.rtTurnSni,
|
||||||
captchaMode = sanitizeTunnelCaptchaMode(saved.captchaMode),
|
captchaMode = sanitizeTunnelCaptchaMode(saved.captchaMode),
|
||||||
captchaSolveMethod = saved.captchaSolveMethod,
|
captchaSolveMethod = saved.captchaSolveMethod,
|
||||||
fingerprint = saved.fingerprint,
|
fingerprint = saved.fingerprint,
|
||||||
@@ -154,6 +185,10 @@ suspend fun buildTunnelStartIntentFromSettings(context: Context): Intent? {
|
|||||||
putExtra("connection_password", params.connectionPassword)
|
putExtra("connection_password", params.connectionPassword)
|
||||||
putExtra("protocol", params.protocol)
|
putExtra("protocol", params.protocol)
|
||||||
putExtra("vkcalls_preflight", params.vkCallsPreflight)
|
putExtra("vkcalls_preflight", params.vkCallsPreflight)
|
||||||
|
putExtra("rt_network", params.rtNetwork)
|
||||||
|
putExtra("rt_masque", params.rtMasque)
|
||||||
|
putExtra("rt_masque_server_bootstrap", params.rtMasqueServerBootstrap)
|
||||||
|
putExtra("rt_turn_sni", params.rtTurnSni)
|
||||||
putExtra("captcha_mode", params.captchaMode)
|
putExtra("captcha_mode", params.captchaMode)
|
||||||
putExtra("captcha_solve_method", params.captchaSolveMethod)
|
putExtra("captcha_solve_method", params.captchaSolveMethod)
|
||||||
putExtra("fingerprint", params.fingerprint)
|
putExtra("fingerprint", params.fingerprint)
|
||||||
|
|||||||
@@ -0,0 +1,94 @@
|
|||||||
|
package com.wdtt.plus
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import com.jcraft.jsch.Session
|
||||||
|
import java.io.Closeable
|
||||||
|
|
||||||
|
private const val WARP_API_RELAY_TARGET = "api.cloudflareclient.com"
|
||||||
|
private const val WARP_API_RELAY_TARGET_PORT = 443
|
||||||
|
|
||||||
|
internal sealed interface WarpApiSshRelayStartResult {
|
||||||
|
data class Ready(val relay: WarpApiSshRelay) : WarpApiSshRelayStartResult
|
||||||
|
data object MissingProfileAccess : WarpApiSshRelayStartResult
|
||||||
|
data class Failed(val message: String) : WarpApiSshRelayStartResult
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A short-lived loopback-only TCP relay backed by the SSH access already stored for the active
|
||||||
|
* Deploy profile. The forwarding target is fixed to Cloudflare's WARP enrollment API. No server
|
||||||
|
* endpoint, SSH username or credential is passed to the native process or written to logs.
|
||||||
|
*/
|
||||||
|
internal class WarpApiSshRelay private constructor(
|
||||||
|
private val session: Session,
|
||||||
|
val port: Int,
|
||||||
|
) : Closeable {
|
||||||
|
val loopbackAddress: String
|
||||||
|
get() = "127.0.0.1:$port"
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
private var closed = false
|
||||||
|
|
||||||
|
override fun close() {
|
||||||
|
if (closed) return
|
||||||
|
synchronized(this) {
|
||||||
|
if (closed) return
|
||||||
|
closed = true
|
||||||
|
runCatching { session.delPortForwardingL("127.0.0.1", port) }
|
||||||
|
runCatching { session.disconnect() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
suspend fun start(
|
||||||
|
context: Context,
|
||||||
|
profileIndex: Int,
|
||||||
|
): WarpApiSshRelayStartResult {
|
||||||
|
val profile = SettingsStore(context.applicationContext)
|
||||||
|
.sshConnectionForProfile(profileIndex)
|
||||||
|
?: return WarpApiSshRelayStartResult.MissingProfileAccess
|
||||||
|
|
||||||
|
var session: Session? = null
|
||||||
|
return try {
|
||||||
|
session = createSshSession(
|
||||||
|
host = profile.host,
|
||||||
|
user = profile.user,
|
||||||
|
credentials = profile.credentials,
|
||||||
|
port = profile.port,
|
||||||
|
)
|
||||||
|
val localPort = session.setPortForwardingL(
|
||||||
|
"127.0.0.1",
|
||||||
|
0,
|
||||||
|
WARP_API_RELAY_TARGET,
|
||||||
|
WARP_API_RELAY_TARGET_PORT,
|
||||||
|
)
|
||||||
|
if (localPort !in 1..65535) {
|
||||||
|
throw IllegalStateException("SSH не выделил локальный порт")
|
||||||
|
}
|
||||||
|
WarpApiSshRelayStartResult.Ready(
|
||||||
|
WarpApiSshRelay(session = session, port = localPort),
|
||||||
|
)
|
||||||
|
} catch (error: Exception) {
|
||||||
|
runCatching { session?.disconnect() }
|
||||||
|
WarpApiSshRelayStartResult.Failed(safeRelayError(error))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun safeRelayError(error: Throwable): String {
|
||||||
|
val detail = generateSequence(error) { it.cause }
|
||||||
|
.mapNotNull { it.message }
|
||||||
|
.joinToString(" ")
|
||||||
|
.lowercase()
|
||||||
|
return when {
|
||||||
|
"auth fail" in detail || "отклонил пароль" in detail || "отклонил приватный ключ" in detail ->
|
||||||
|
"SSH-сервер отклонил данные входа"
|
||||||
|
"timeout" in detail || "20 секунд" in detail ->
|
||||||
|
"SSH-сервер не ответил вовремя"
|
||||||
|
"refused" in detail || "порт отклонил" in detail ->
|
||||||
|
"SSH-порт отклонил подключение"
|
||||||
|
"administratively prohibited" in detail || "port forwarding" in detail ->
|
||||||
|
"SSH-сервер запретил TCP-переадресацию"
|
||||||
|
else -> "не удалось подготовить SSH-переадресацию"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,8 +9,12 @@ import kotlinx.coroutines.CoroutineScope
|
|||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.SupervisorJob
|
import kotlinx.coroutines.SupervisorJob
|
||||||
import kotlinx.coroutines.flow.combine
|
import kotlinx.coroutines.flow.combine
|
||||||
|
import kotlinx.coroutines.flow.first
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
|
internal fun shouldClearPhantomVpn(activeTunnelProfile: Int?): Boolean =
|
||||||
|
activeTunnelProfile == null
|
||||||
|
|
||||||
class WdttApplication : Application() {
|
class WdttApplication : Application() {
|
||||||
@Volatile
|
@Volatile
|
||||||
private var backendInstance: GoBackend? = null
|
private var backendInstance: GoBackend? = null
|
||||||
@@ -22,11 +26,18 @@ class WdttApplication : Application() {
|
|||||||
super.onCreate()
|
super.onCreate()
|
||||||
DeployManager.init(this)
|
DeployManager.init(this)
|
||||||
|
|
||||||
// Очищаем фантомный VPN при холодном старте приложения (например, после перезагрузки телефона).
|
val settingsStore = SettingsStore(this)
|
||||||
// Если телефон перезагрузился, система Android пытается сама восстановить VpnService,
|
|
||||||
// что приводит к фантомному ключу без интернета. Этот код мгновенно сбрасывает статус в DOWN.
|
// Очищаем только действительно бесхозный фантомный VPN. Если сохранён активный
|
||||||
|
// профиль, Android одновременно восстанавливает TunnelService: безусловный DOWN
|
||||||
|
// здесь мог опередить или оборвать штатное восстановление и затем вызвать новый UP.
|
||||||
CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {
|
CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {
|
||||||
runCatching {
|
runCatching {
|
||||||
|
val activeTunnelProfile = settingsStore.activeTunnelProfile.first()
|
||||||
|
if (!shouldClearPhantomVpn(activeTunnelProfile)) {
|
||||||
|
Log.d("WdttApp", "Ожидается восстановление активного VPN; очистка фантома пропущена")
|
||||||
|
return@runCatching
|
||||||
|
}
|
||||||
val backend = getBackend(this@WdttApplication)
|
val backend = getBackend(this@WdttApplication)
|
||||||
val tunnel = WireGuardHelper.WgTunnel()
|
val tunnel = WireGuardHelper.WgTunnel()
|
||||||
backend.setState(tunnel, Tunnel.State.DOWN, null)
|
backend.setState(tunnel, Tunnel.State.DOWN, null)
|
||||||
@@ -35,8 +46,6 @@ class WdttApplication : Application() {
|
|||||||
Log.w("WdttApp", "Не удалось очистить фантомный VPN: ${it.message}")
|
Log.w("WdttApp", "Не удалось очистить фантомный VPN: ${it.message}")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
val settingsStore = SettingsStore(this)
|
|
||||||
CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {
|
CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {
|
||||||
RemoteActionCatalogGateway.fetch(force = true)
|
RemoteActionCatalogGateway.fetch(force = true)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -153,7 +153,7 @@ class WireGuardHelper(context: Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
val nextTunnel = WgTunnel {
|
val nextTunnel = WgTunnel {
|
||||||
TunnelManager.onWireGuardStoppedExternally()
|
TunnelManager.onWireGuardInterfaceDropped()
|
||||||
}
|
}
|
||||||
setTunnelUpWithRetry(nextTunnel, finalConfig)
|
setTunnelUpWithRetry(nextTunnel, finalConfig)
|
||||||
sharedTunnel = nextTunnel
|
sharedTunnel = nextTunnel
|
||||||
|
|||||||
@@ -70,6 +70,7 @@ private const val PROFILE_RESET_TIMEOUT_MS = 10_000L
|
|||||||
@OptIn(ExperimentalLayoutApi::class, ExperimentalFoundationApi::class)
|
@OptIn(ExperimentalLayoutApi::class, ExperimentalFoundationApi::class)
|
||||||
@Composable
|
@Composable
|
||||||
fun FloatingToolbar(
|
fun FloatingToolbar(
|
||||||
|
settingsStore: SettingsStore,
|
||||||
activeProfile: Int,
|
activeProfile: Int,
|
||||||
profileNames: List<String>,
|
profileNames: List<String>,
|
||||||
onActiveProfileChange: (Int) -> Unit,
|
onActiveProfileChange: (Int) -> Unit,
|
||||||
@@ -92,10 +93,10 @@ fun FloatingToolbar(
|
|||||||
) {
|
) {
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
val scope = rememberCoroutineScope()
|
val scope = rememberCoroutineScope()
|
||||||
val settingsStore = remember { SettingsStore(context) }
|
|
||||||
val trustedWifiEnabled by settingsStore.trustedWifiEnabled.collectAsStateWithLifecycle(initialValue = false)
|
val trustedWifiEnabled by settingsStore.trustedWifiEnabled.collectAsStateWithLifecycle(initialValue = false)
|
||||||
val trustedWifiSsids by settingsStore.trustedWifiSsids.collectAsStateWithLifecycle(initialValue = emptyList())
|
val trustedWifiSsids by settingsStore.trustedWifiSsids.collectAsStateWithLifecycle(initialValue = emptyList())
|
||||||
val trustedWifiRuntime by com.wdtt.plus.TrustedWifiManager.state.collectAsStateWithLifecycle()
|
val trustedWifiRuntime by com.wdtt.plus.TrustedWifiManager.state.collectAsStateWithLifecycle()
|
||||||
|
val pauseVpnDuringSleep by settingsStore.pauseVpnDuringSleep.collectAsStateWithLifecycle(initialValue = false)
|
||||||
val customVkCredentialsEnabled by settingsStore.customVkCredentialsEnabled.collectAsStateWithLifecycle(initialValue = false)
|
val customVkCredentialsEnabled by settingsStore.customVkCredentialsEnabled.collectAsStateWithLifecycle(initialValue = false)
|
||||||
val customVkCredentialsComplete by settingsStore.customVkCredentialsComplete.collectAsStateWithLifecycle(initialValue = false)
|
val customVkCredentialsComplete by settingsStore.customVkCredentialsComplete.collectAsStateWithLifecycle(initialValue = false)
|
||||||
val savedToolbarYFraction by settingsStore.floatingToolbarYFraction.collectAsStateWithLifecycle(
|
val savedToolbarYFraction by settingsStore.floatingToolbarYFraction.collectAsStateWithLifecycle(
|
||||||
@@ -388,6 +389,38 @@ fun FloatingToolbar(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth().padding(horizontal = 4.dp, vertical = 4.dp),
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
verticalAlignment = Alignment.CenterVertically
|
||||||
|
) {
|
||||||
|
Column(modifier = Modifier.weight(1f).padding(end = 10.dp)) {
|
||||||
|
Text(
|
||||||
|
"Экономия батареи во сне",
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
fontWeight = FontWeight.SemiBold,
|
||||||
|
color = MaterialTheme.colorScheme.onSurface
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
if (pauseVpnDuringSleep) {
|
||||||
|
"VPN выключается · интернет напрямую"
|
||||||
|
} else {
|
||||||
|
"VPN остаётся активным"
|
||||||
|
},
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
lineHeight = 15.sp
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Switch(
|
||||||
|
checked = pauseVpnDuringSleep,
|
||||||
|
onCheckedChange = { enabled ->
|
||||||
|
scope.launch { settingsStore.savePauseVpnDuringSleep(enabled) }
|
||||||
|
},
|
||||||
|
modifier = Modifier.scale(0.85f)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
HorizontalDivider(
|
HorizontalDivider(
|
||||||
modifier = Modifier.padding(vertical = 4.dp),
|
modifier = Modifier.padding(vertical = 4.dp),
|
||||||
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f)
|
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f)
|
||||||
|
|||||||
@@ -8,8 +8,6 @@ import android.content.ClipboardManager
|
|||||||
import android.content.Context
|
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.NetworkCapabilities
|
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
import android.net.VpnService
|
import android.net.VpnService
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
@@ -23,7 +21,10 @@ import android.widget.Toast
|
|||||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
import androidx.activity.result.contract.ActivityResultContracts
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
import androidx.compose.animation.AnimatedVisibility
|
import androidx.compose.animation.AnimatedVisibility
|
||||||
|
import androidx.compose.animation.animateColorAsState
|
||||||
|
import androidx.compose.animation.core.animateDpAsState
|
||||||
import androidx.compose.animation.core.animateFloatAsState
|
import androidx.compose.animation.core.animateFloatAsState
|
||||||
|
import androidx.compose.animation.core.tween
|
||||||
import androidx.compose.animation.expandVertically
|
import androidx.compose.animation.expandVertically
|
||||||
import androidx.compose.animation.fadeIn
|
import androidx.compose.animation.fadeIn
|
||||||
import androidx.compose.animation.fadeOut
|
import androidx.compose.animation.fadeOut
|
||||||
@@ -117,10 +118,13 @@ import com.wdtt.plus.RemoteActionForm
|
|||||||
import com.wdtt.plus.RemoteContinuationLauncher
|
import com.wdtt.plus.RemoteContinuationLauncher
|
||||||
import com.wdtt.plus.RemoteUiAction
|
import com.wdtt.plus.RemoteUiAction
|
||||||
import com.wdtt.plus.RemoteUiActionLauncher
|
import com.wdtt.plus.RemoteUiActionLauncher
|
||||||
|
import com.wdtt.plus.RT_MASQUE_CONFIG_FILE_NAME
|
||||||
|
import com.wdtt.plus.RtMasqueEnrollmentState
|
||||||
import com.wdtt.plus.SettingsStore
|
import com.wdtt.plus.SettingsStore
|
||||||
import com.wdtt.plus.TunnelManager
|
import com.wdtt.plus.TunnelManager
|
||||||
import com.wdtt.plus.TrustedWifiManager
|
import com.wdtt.plus.TrustedWifiManager
|
||||||
import com.wdtt.plus.trustedWifiAccessProblem
|
import com.wdtt.plus.trustedWifiAccessProblem
|
||||||
|
import com.wdtt.plus.inspectRtMasqueEnrollment
|
||||||
import com.wdtt.plus.UPDATE_DIALOG_ACTION_POSTPONED
|
import com.wdtt.plus.UPDATE_DIALOG_ACTION_POSTPONED
|
||||||
import com.wdtt.plus.UPDATE_DIALOG_ACTION_UPDATE
|
import com.wdtt.plus.UPDATE_DIALOG_ACTION_UPDATE
|
||||||
import com.wdtt.plus.WDTTColors
|
import com.wdtt.plus.WDTTColors
|
||||||
@@ -139,6 +143,7 @@ import com.wdtt.plus.selectUpdateApkAsset
|
|||||||
import com.wdtt.plus.deviceCheckActionIntent
|
import com.wdtt.plus.deviceCheckActionIntent
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.CancellationException
|
import kotlinx.coroutines.CancellationException
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
import kotlinx.coroutines.flow.first
|
import kotlinx.coroutines.flow.first
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
@@ -260,6 +265,7 @@ fun InfoTab(
|
|||||||
var showHelpDialog by remember { mutableStateOf(false) }
|
var showHelpDialog by remember { mutableStateOf(false) }
|
||||||
var showQuestionDialog by remember { mutableStateOf(false) }
|
var showQuestionDialog by remember { mutableStateOf(false) }
|
||||||
var showSupportDialog by remember { mutableStateOf(false) }
|
var showSupportDialog by remember { mutableStateOf(false) }
|
||||||
|
var highlightNoServerBlock by remember { mutableStateOf(false) }
|
||||||
var pendingActionForm by remember { mutableStateOf<RemoteUiAction?>(null) }
|
var pendingActionForm by remember { mutableStateOf<RemoteUiAction?>(null) }
|
||||||
var actionCatalog by remember { mutableStateOf(RemoteActionCatalogGateway.cached()) }
|
var actionCatalog by remember { mutableStateOf(RemoteActionCatalogGateway.cached()) }
|
||||||
var questionAction by remember { mutableStateOf<RemoteUiAction?>(null) }
|
var questionAction by remember { mutableStateOf<RemoteUiAction?>(null) }
|
||||||
@@ -270,6 +276,7 @@ fun InfoTab(
|
|||||||
var projectExpanded by projectExpandedState
|
var projectExpanded by projectExpandedState
|
||||||
LaunchedEffect(projectSupportDialogRequest) {
|
LaunchedEffect(projectSupportDialogRequest) {
|
||||||
if (projectSupportDialogRequest > 0) {
|
if (projectSupportDialogRequest > 0) {
|
||||||
|
highlightNoServerBlock = true
|
||||||
showSupportDialog = true
|
showSupportDialog = true
|
||||||
onProjectSupportDialogRequestConsumed()
|
onProjectSupportDialogRequestConsumed()
|
||||||
}
|
}
|
||||||
@@ -353,6 +360,7 @@ fun InfoTab(
|
|||||||
latestRelease = latestRelease
|
latestRelease = latestRelease
|
||||||
)
|
)
|
||||||
val workers = runCatching { settingsStore.workersPerHash.first() }.getOrNull()
|
val workers = runCatching { settingsStore.workersPerHash.first() }.getOrNull()
|
||||||
|
val tunnelProfile = runCatching { settingsStore.tunnelProfileSnapshot() }.getOrNull()
|
||||||
val diagnosticsSummary = withContext(Dispatchers.Default) {
|
val diagnosticsSummary = withContext(Dispatchers.Default) {
|
||||||
buildSupportReportSummary(context.applicationContext, settingsStore)
|
buildSupportReportSummary(context.applicationContext, settingsStore)
|
||||||
}
|
}
|
||||||
@@ -385,7 +393,12 @@ fun InfoTab(
|
|||||||
return report.copy(
|
return report.copy(
|
||||||
summaryLines = diagnosticsSummary + clientNetworkDiagnostics.summaryLines,
|
summaryLines = diagnosticsSummary + clientNetworkDiagnostics.summaryLines,
|
||||||
items = listOf(versionItem) +
|
items = listOf(versionItem) +
|
||||||
report.items.filterNot { it.title == DeviceCompatibility.APP_VERSION_ITEM_TITLE } +
|
report.items.filterNot {
|
||||||
|
it.title == DeviceCompatibility.APP_VERSION_ITEM_TITLE ||
|
||||||
|
it.title == "Сеть Android"
|
||||||
|
} + listOfNotNull(
|
||||||
|
tunnelProfile?.let { DeviceCompatibility.rtNetworkModeItem(context, it) }
|
||||||
|
) +
|
||||||
clientNetworkDiagnostics.items
|
clientNetworkDiagnostics.items
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -415,6 +428,7 @@ fun InfoTab(
|
|||||||
currentVersion = currentVersion,
|
currentVersion = currentVersion,
|
||||||
releaseDate = releaseDate,
|
releaseDate = releaseDate,
|
||||||
onSupportClick = {
|
onSupportClick = {
|
||||||
|
highlightNoServerBlock = false
|
||||||
showSupportDialog = true
|
showSupportDialog = true
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
@@ -469,7 +483,7 @@ fun InfoTab(
|
|||||||
WideActionTile(
|
WideActionTile(
|
||||||
title = "Проверить устройство",
|
title = "Проверить устройство",
|
||||||
subtitle = if (isCheckingDevice) {
|
subtitle = if (isCheckingDevice) {
|
||||||
"Проверяем версию, Android, ABI, сеть и системные условия..."
|
"Проверяем Android, ABI, 16 КиБ, WireGuard, режим РТ и сеть..."
|
||||||
} else {
|
} else {
|
||||||
"Проверка совместимости и полный отчёт для диагностики"
|
"Проверка совместимости и полный отчёт для диагностики"
|
||||||
},
|
},
|
||||||
@@ -790,10 +804,16 @@ fun InfoTab(
|
|||||||
}
|
}
|
||||||
if (showSupportDialog) {
|
if (showSupportDialog) {
|
||||||
AdditionalActionsDialog(
|
AdditionalActionsDialog(
|
||||||
onDismiss = { showSupportDialog = false },
|
onDismiss = {
|
||||||
|
highlightNoServerBlock = false
|
||||||
|
showSupportDialog = false
|
||||||
|
},
|
||||||
primaryAction = actionCatalog.at("about"),
|
primaryAction = actionCatalog.at("about"),
|
||||||
secondaryAction = actionCatalog.at("tunnel"),
|
secondaryAction = actionCatalog.at("tunnel"),
|
||||||
|
highlightSecondaryAction = highlightNoServerBlock,
|
||||||
|
onSecondaryHighlightConsumed = { highlightNoServerBlock = false },
|
||||||
onActionClick = { action ->
|
onActionClick = { action ->
|
||||||
|
highlightNoServerBlock = false
|
||||||
if (action.form != null) {
|
if (action.form != null) {
|
||||||
showSupportDialog = false
|
showSupportDialog = false
|
||||||
pendingActionForm = action
|
pendingActionForm = action
|
||||||
@@ -811,10 +831,12 @@ fun InfoTab(
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
onProjectFallbackClick = {
|
onProjectFallbackClick = {
|
||||||
|
highlightNoServerBlock = false
|
||||||
showSupportDialog = false
|
showSupportDialog = false
|
||||||
openUrlInBrowser(context, ProjectDonateFallbackUrl)
|
openUrlInBrowser(context, ProjectDonateFallbackUrl)
|
||||||
},
|
},
|
||||||
onDonateOriginalClick = {
|
onDonateOriginalClick = {
|
||||||
|
highlightNoServerBlock = false
|
||||||
showSupportDialog = false
|
showSupportDialog = false
|
||||||
openUrlInBrowser(context, OriginalDonateUrl)
|
openUrlInBrowser(context, OriginalDonateUrl)
|
||||||
}
|
}
|
||||||
@@ -970,6 +992,8 @@ private fun AdditionalActionsDialog(
|
|||||||
onDismiss: () -> Unit,
|
onDismiss: () -> Unit,
|
||||||
primaryAction: RemoteUiAction?,
|
primaryAction: RemoteUiAction?,
|
||||||
secondaryAction: RemoteUiAction?,
|
secondaryAction: RemoteUiAction?,
|
||||||
|
highlightSecondaryAction: Boolean,
|
||||||
|
onSecondaryHighlightConsumed: () -> Unit,
|
||||||
onActionClick: (RemoteUiAction) -> Unit,
|
onActionClick: (RemoteUiAction) -> Unit,
|
||||||
onProjectFallbackClick: () -> Unit,
|
onProjectFallbackClick: () -> Unit,
|
||||||
onDonateOriginalClick: () -> Unit
|
onDonateOriginalClick: () -> Unit
|
||||||
@@ -1034,7 +1058,7 @@ private fun AdditionalActionsDialog(
|
|||||||
ExternalSupportBlock(
|
ExternalSupportBlock(
|
||||||
title = primaryAction.title,
|
title = primaryAction.title,
|
||||||
body = primaryAction.message,
|
body = primaryAction.message,
|
||||||
buttonText = primaryAction.label,
|
buttonText = "Поддержать проект",
|
||||||
onClick = { onActionClick(primaryAction) },
|
onClick = { onActionClick(primaryAction) },
|
||||||
emphasized = true,
|
emphasized = true,
|
||||||
)
|
)
|
||||||
@@ -1054,6 +1078,8 @@ private fun AdditionalActionsDialog(
|
|||||||
secondaryAction?.let { action ->
|
secondaryAction?.let { action ->
|
||||||
RemoteInfoActionBlock(
|
RemoteInfoActionBlock(
|
||||||
action = action,
|
action = action,
|
||||||
|
highlightRequested = highlightSecondaryAction,
|
||||||
|
onHighlightConsumed = onSecondaryHighlightConsumed,
|
||||||
onClick = { onActionClick(action) },
|
onClick = { onActionClick(action) },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1088,6 +1114,19 @@ private fun RemoteActionFormDialog(
|
|||||||
var fallbackAvailable by remember(form.token) { mutableStateOf(false) }
|
var fallbackAvailable by remember(form.token) { mutableStateOf(false) }
|
||||||
val numericValue = valueText.toLongOrNull()
|
val numericValue = valueText.toLongOrNull()
|
||||||
val valueValid = numericValue != null && numericValue in form.minimum..form.maximum
|
val valueValid = numericValue != null && numericValue in form.minimum..form.maximum
|
||||||
|
val supportAmount = valueText.trim()
|
||||||
|
val supportButtonLabel = if (supportAmount.isNotEmpty()) {
|
||||||
|
buildString {
|
||||||
|
append("Поддержать на ")
|
||||||
|
append(supportAmount)
|
||||||
|
if (form.inputSuffix.isNotBlank()) {
|
||||||
|
append(' ')
|
||||||
|
append(form.inputSuffix.trim())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
"Поддержать"
|
||||||
|
}
|
||||||
|
|
||||||
fun selectValue(value: String) {
|
fun selectValue(value: String) {
|
||||||
valueText = value
|
valueText = value
|
||||||
@@ -1268,7 +1307,7 @@ private fun RemoteActionFormDialog(
|
|||||||
Text(form.busyLabel, fontWeight = FontWeight.Bold)
|
Text(form.busyLabel, fontWeight = FontWeight.Bold)
|
||||||
} else {
|
} else {
|
||||||
Text(
|
Text(
|
||||||
form.submitLabel.replace("{value}", valueText),
|
supportButtonLabel,
|
||||||
fontWeight = FontWeight.Bold,
|
fontWeight = FontWeight.Bold,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1298,16 +1337,44 @@ private fun RemoteActionFormDialog(
|
|||||||
@Composable
|
@Composable
|
||||||
private fun RemoteInfoActionBlock(
|
private fun RemoteInfoActionBlock(
|
||||||
action: RemoteUiAction,
|
action: RemoteUiAction,
|
||||||
|
highlightRequested: Boolean = false,
|
||||||
|
onHighlightConsumed: () -> Unit = {},
|
||||||
onClick: () -> Unit,
|
onClick: () -> Unit,
|
||||||
) {
|
) {
|
||||||
|
var borderPulseActive by remember(highlightRequested) {
|
||||||
|
mutableStateOf(false)
|
||||||
|
}
|
||||||
|
LaunchedEffect(highlightRequested) {
|
||||||
|
if (highlightRequested) {
|
||||||
|
repeat(2) {
|
||||||
|
borderPulseActive = true
|
||||||
|
delay(380)
|
||||||
|
borderPulseActive = false
|
||||||
|
delay(280)
|
||||||
|
}
|
||||||
|
onHighlightConsumed()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val borderColor by animateColorAsState(
|
||||||
|
targetValue = if (borderPulseActive) {
|
||||||
|
MaterialTheme.colorScheme.primary
|
||||||
|
} else {
|
||||||
|
MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.45f)
|
||||||
|
},
|
||||||
|
animationSpec = tween(durationMillis = 240),
|
||||||
|
label = "no_server_highlight_border",
|
||||||
|
)
|
||||||
|
val borderWidth by animateDpAsState(
|
||||||
|
targetValue = if (borderPulseActive) 2.5.dp else 1.dp,
|
||||||
|
animationSpec = tween(durationMillis = 240),
|
||||||
|
label = "no_server_highlight_border_width",
|
||||||
|
)
|
||||||
|
|
||||||
Surface(
|
Surface(
|
||||||
shape = RoundedCornerShape(18.dp),
|
shape = RoundedCornerShape(18.dp),
|
||||||
color = MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.48f),
|
color = MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.48f),
|
||||||
contentColor = MaterialTheme.colorScheme.onSecondaryContainer,
|
contentColor = MaterialTheme.colorScheme.onSecondaryContainer,
|
||||||
border = BorderStroke(
|
border = BorderStroke(borderWidth, borderColor),
|
||||||
1.dp,
|
|
||||||
MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.45f)
|
|
||||||
)
|
|
||||||
) {
|
) {
|
||||||
Column(
|
Column(
|
||||||
modifier = Modifier.fillMaxWidth().padding(14.dp),
|
modifier = Modifier.fillMaxWidth().padding(14.dp),
|
||||||
@@ -1930,41 +1997,14 @@ private suspend fun buildSupportReportSummary(context: Context, settingsStore: S
|
|||||||
"без ограничений батареи=${powerManager?.isIgnoringBatteryOptimizations(context.packageName)}"
|
"без ограничений батареи=${powerManager?.isIgnoringBatteryOptimizations(context.packageName)}"
|
||||||
}
|
}
|
||||||
|
|
||||||
val connectivityManager = runCatching {
|
|
||||||
context.getSystemService(ConnectivityManager::class.java)
|
|
||||||
}.getOrNull()
|
|
||||||
val activeNetwork = runCatching { connectivityManager?.activeNetwork }.getOrNull()
|
|
||||||
val networkCapabilities = runCatching {
|
|
||||||
activeNetwork?.let { connectivityManager?.getNetworkCapabilities(it) }
|
|
||||||
}.getOrNull()
|
|
||||||
val networkTransports = buildList {
|
|
||||||
if (networkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true) add("Wi-Fi")
|
|
||||||
if (networkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) == true) add("мобильная")
|
|
||||||
if (networkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) == true) add("Ethernet")
|
|
||||||
if (networkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_VPN) == true) add("VPN")
|
|
||||||
}.joinToString().ifBlank { "не определён" }
|
|
||||||
val networkSummary = if (networkCapabilities != null) {
|
|
||||||
"$networkTransports, internet=${networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)}, " +
|
|
||||||
"validated=${networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)}, " +
|
|
||||||
"metered=${connectivityManager?.isActiveNetworkMetered}"
|
|
||||||
} else {
|
|
||||||
"недоступно"
|
|
||||||
}
|
|
||||||
val privateDns = diagnosticText {
|
|
||||||
val properties = activeNetwork?.let { connectivityManager?.getLinkProperties(it) }
|
|
||||||
properties?.isPrivateDnsActive
|
|
||||||
}
|
|
||||||
|
|
||||||
val webViewInfo = diagnosticText {
|
val webViewInfo = diagnosticText {
|
||||||
WebView.getCurrentWebViewPackage()?.let { "${it.packageName} ${it.versionName}" }
|
WebView.getCurrentWebViewPackage()?.let { "${it.packageName} ${it.versionName}" }
|
||||||
}
|
}
|
||||||
val nativeClientInfo = runCatching {
|
val nativeComponentsInfo = runCatching {
|
||||||
val nativeClient = File(appInfo?.nativeLibraryDir.orEmpty(), "libclient.so")
|
val nativeClient = File(appInfo?.nativeLibraryDir.orEmpty(), "libclient.so")
|
||||||
if (nativeClient.isFile) {
|
val wireGuardBackend = File(appInfo?.nativeLibraryDir.orEmpty(), "libwg-go.so")
|
||||||
"найден, ${formatMiB(nativeClient.length())}, executable=${nativeClient.canExecute()}"
|
"libclient.so=${if (nativeClient.isFile) formatMiB(nativeClient.length()) else "не найден"}, " +
|
||||||
} else {
|
"libwg-go.so=${if (wireGuardBackend.isFile) formatMiB(wireGuardBackend.length()) else "не найден"}"
|
||||||
"не найден"
|
|
||||||
}
|
|
||||||
}.getOrDefault("недоступно")
|
}.getOrDefault("недоступно")
|
||||||
|
|
||||||
val notificationPermission = diagnosticText {
|
val notificationPermission = diagnosticText {
|
||||||
@@ -1994,6 +2034,18 @@ private suspend fun buildSupportReportSummary(context: Context, settingsStore: S
|
|||||||
.coerceAtMost(4)
|
.coerceAtMost(4)
|
||||||
val hasSecondaryHash = runCatching { settingsStore.secondaryVkHash.first().isNotBlank() }.getOrNull()
|
val hasSecondaryHash = runCatching { settingsStore.secondaryVkHash.first().isNotBlank() }.getOrNull()
|
||||||
val vkCallsEnabled = runCatching { settingsStore.vkCallsPreflight.first() }.getOrNull()
|
val vkCallsEnabled = runCatching { settingsStore.vkCallsPreflight.first() }.getOrNull()
|
||||||
|
val rtNetworkEnabled = runCatching { settingsStore.rtNetwork.first() }.getOrNull()
|
||||||
|
val rtMasqueEnabled = runCatching { settingsStore.rtMasque.first() }.getOrNull()
|
||||||
|
val rtMasqueServerBootstrap =
|
||||||
|
runCatching { settingsStore.rtMasqueServerBootstrap.first() }.getOrNull()
|
||||||
|
val rtMasqueEnrollment = runCatching {
|
||||||
|
val config = File(context.filesDir, RT_MASQUE_CONFIG_FILE_NAME)
|
||||||
|
when (inspectRtMasqueEnrollment(config)) {
|
||||||
|
RtMasqueEnrollmentState.Missing -> "не создана"
|
||||||
|
RtMasqueEnrollmentState.Ready -> "сохранена и структурно корректна"
|
||||||
|
RtMasqueEnrollmentState.Invalid -> "повреждена"
|
||||||
|
}
|
||||||
|
}.getOrDefault("недоступно")
|
||||||
val customVkCredentialsEnabled = runCatching { settingsStore.customVkCredentialsEnabled.first() }.getOrNull()
|
val customVkCredentialsEnabled = runCatching { settingsStore.customVkCredentialsEnabled.first() }.getOrNull()
|
||||||
val customVkCredentialsComplete = runCatching { settingsStore.customVkCredentialsComplete.first() }.getOrNull()
|
val customVkCredentialsComplete = runCatching { settingsStore.customVkCredentialsComplete.first() }.getOrNull()
|
||||||
val builtInVkClientCount = runCatching {
|
val builtInVkClientCount = runCatching {
|
||||||
@@ -2052,10 +2104,8 @@ private suspend fun buildSupportReportSummary(context: Context, settingsStore: S
|
|||||||
appendLine("Low-RAM устройство: $lowRamDevice")
|
appendLine("Low-RAM устройство: $lowRamDevice")
|
||||||
appendLine("Хранилище приложения: $storageSummary")
|
appendLine("Хранилище приложения: $storageSummary")
|
||||||
appendLine("Питание: $powerSummary")
|
appendLine("Питание: $powerSummary")
|
||||||
appendLine("Сеть: $networkSummary")
|
|
||||||
appendLine("Private DNS: $privateDns")
|
|
||||||
appendLine("WebView: $webViewInfo")
|
appendLine("WebView: $webViewInfo")
|
||||||
appendLine("Нативный клиент: $nativeClientInfo")
|
appendLine("Нативные компоненты: $nativeComponentsInfo")
|
||||||
appendLine("Экран: $screenSummary")
|
appendLine("Экран: $screenSummary")
|
||||||
appendLine("Разрешение уведомлений: $notificationPermission")
|
appendLine("Разрешение уведомлений: $notificationPermission")
|
||||||
appendLine("Установка обновлений APK: $updateInstallPermission")
|
appendLine("Установка обновлений APK: $updateInstallPermission")
|
||||||
@@ -2072,6 +2122,12 @@ private suspend fun buildSupportReportSummary(context: Context, settingsStore: S
|
|||||||
appendLine("Потоки: ${workers ?: "недоступно"}")
|
appendLine("Потоки: ${workers ?: "недоступно"}")
|
||||||
appendLine("VK-хеши: заполнено $hashCount, запасной=${hasSecondaryHash ?: "недоступно"}")
|
appendLine("VK-хеши: заполнено $hashCount, запасной=${hasSecondaryHash ?: "недоступно"}")
|
||||||
appendLine("Быстрый VKCalls: ${vkCallsEnabled ?: "недоступно"}")
|
appendLine("Быстрый VKCalls: ${vkCallsEnabled ?: "недоступно"}")
|
||||||
|
appendLine("Сеть РТ (TURN stream-first): ${rtNetworkEnabled ?: "недоступно"}")
|
||||||
|
appendLine(
|
||||||
|
"MASQUE в Сети РТ (HTTP/2 → HTTP/3): ${rtMasqueEnabled ?: "недоступно"}, " +
|
||||||
|
"регистрация WARP=$rtMasqueEnrollment, " +
|
||||||
|
"первая регистрация через сервер=${rtMasqueServerBootstrap ?: "недоступно"}"
|
||||||
|
)
|
||||||
appendLine(
|
appendLine(
|
||||||
"Резерв VK: собственные=${customVkCredentialsEnabled ?: "недоступно"}, " +
|
"Резерв VK: собственные=${customVkCredentialsEnabled ?: "недоступно"}, " +
|
||||||
"заполнены=${customVkCredentialsComplete ?: "недоступно"}, встроенных=${builtInVkClientCount ?: "недоступно"}"
|
"заполнены=${customVkCredentialsComplete ?: "недоступно"}, встроенных=${builtInVkClientCount ?: "недоступно"}"
|
||||||
|
|||||||
@@ -0,0 +1,298 @@
|
|||||||
|
package com.wdtt.plus.ui
|
||||||
|
|
||||||
|
import androidx.compose.foundation.BorderStroke
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.heightIn
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.foundation.text.KeyboardOptions
|
||||||
|
import androidx.compose.foundation.verticalScroll
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.automirrored.filled.HelpOutline
|
||||||
|
import androidx.compose.material.icons.filled.Close
|
||||||
|
import androidx.compose.material.icons.filled.Cloud
|
||||||
|
import androidx.compose.material3.HorizontalDivider
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.IconButton
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.OutlinedTextField
|
||||||
|
import androidx.compose.material3.Surface
|
||||||
|
import androidx.compose.material3.Switch
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.platform.LocalConfiguration
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.text.input.KeyboardType
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.window.Dialog
|
||||||
|
import androidx.compose.ui.window.DialogProperties
|
||||||
|
import com.wdtt.plus.DEFAULT_RT_TURN_SNI
|
||||||
|
import com.wdtt.plus.SshProfileAccessStatus
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun RtNetworkSettingsDialog(
|
||||||
|
rtNetwork: Boolean,
|
||||||
|
turnSni: String,
|
||||||
|
turnSniValid: Boolean,
|
||||||
|
rtMasque: Boolean,
|
||||||
|
rtMasqueServerBootstrap: Boolean,
|
||||||
|
serverAccess: SshProfileAccessStatus,
|
||||||
|
tunnelRunning: Boolean,
|
||||||
|
onTurnSniChange: (String) -> Unit,
|
||||||
|
onRtMasqueChange: (Boolean) -> Unit,
|
||||||
|
onServerBootstrapChange: (Boolean) -> Unit,
|
||||||
|
onShowRtHelp: () -> Unit,
|
||||||
|
onShowMasqueHelp: () -> Unit,
|
||||||
|
onShowServerHelp: () -> Unit,
|
||||||
|
onDismiss: () -> Unit,
|
||||||
|
) {
|
||||||
|
val configuration = LocalConfiguration.current
|
||||||
|
val dialogMaxHeight = (configuration.screenHeightDp.dp - 32.dp).coerceAtLeast(360.dp)
|
||||||
|
val dialogMinHeight = 520.dp.coerceAtMost(dialogMaxHeight)
|
||||||
|
val controlsEnabled = rtNetwork && !tunnelRunning
|
||||||
|
val serverSupportingText = when {
|
||||||
|
!rtNetwork -> "Сначала включите «Сеть РТ»"
|
||||||
|
!rtMasque -> "Сначала включите MASQUE"
|
||||||
|
!serverAccess.available -> "Недоступно: ${serverAccess.unavailableReason}"
|
||||||
|
tunnelRunning -> "Остановите VPN, чтобы изменить настройку"
|
||||||
|
else -> "Только первая регистрация WARP · SSH из «Деплой»"
|
||||||
|
}
|
||||||
|
val serverTextIsError = rtNetwork && rtMasque && !serverAccess.available
|
||||||
|
|
||||||
|
Dialog(
|
||||||
|
onDismissRequest = onDismiss,
|
||||||
|
properties = DialogProperties(usePlatformDefaultWidth = false),
|
||||||
|
) {
|
||||||
|
Box(
|
||||||
|
modifier = Modifier.fillMaxSize(),
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
) {
|
||||||
|
Surface(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth(0.92f)
|
||||||
|
.heightIn(min = dialogMinHeight, max = dialogMaxHeight),
|
||||||
|
shape = RoundedCornerShape(30.dp),
|
||||||
|
color = MaterialTheme.colorScheme.surface,
|
||||||
|
tonalElevation = 8.dp,
|
||||||
|
shadowElevation = 8.dp,
|
||||||
|
) {
|
||||||
|
Column(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.verticalScroll(rememberScrollState())
|
||||||
|
.padding(18.dp),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(14.dp),
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||||
|
) {
|
||||||
|
Surface(
|
||||||
|
shape = RoundedCornerShape(16.dp),
|
||||||
|
color = MaterialTheme.colorScheme.primaryContainer,
|
||||||
|
) {
|
||||||
|
Box(
|
||||||
|
modifier = Modifier.size(48.dp),
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
Icons.Default.Cloud,
|
||||||
|
contentDescription = null,
|
||||||
|
modifier = Modifier.size(25.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Text(
|
||||||
|
"Сеть РТ",
|
||||||
|
modifier = Modifier.weight(1f),
|
||||||
|
style = MaterialTheme.typography.titleMedium,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
)
|
||||||
|
IconButton(onClick = onShowRtHelp) {
|
||||||
|
Icon(
|
||||||
|
Icons.AutoMirrored.Filled.HelpOutline,
|
||||||
|
contentDescription = "Инструкция по режиму Сеть РТ",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
IconButton(onClick = onDismiss) {
|
||||||
|
Icon(Icons.Default.Close, contentDescription = "Закрыть")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!rtNetwork || tunnelRunning) {
|
||||||
|
Surface(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
shape = RoundedCornerShape(16.dp),
|
||||||
|
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.55f),
|
||||||
|
border = BorderStroke(
|
||||||
|
1.dp,
|
||||||
|
MaterialTheme.colorScheme.outline.copy(alpha = 0.2f),
|
||||||
|
),
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
if (!rtNetwork) {
|
||||||
|
"Включите «Сеть РТ» в основном окне, чтобы изменить эти параметры."
|
||||||
|
} else {
|
||||||
|
"Остановите VPN, чтобы изменить параметры режима."
|
||||||
|
},
|
||||||
|
modifier = Modifier.padding(14.dp),
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Column(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||||
|
) {
|
||||||
|
OutlinedTextField(
|
||||||
|
value = turnSni,
|
||||||
|
onValueChange = onTurnSniChange,
|
||||||
|
label = { Text("SNI белого списка") },
|
||||||
|
placeholder = { Text(DEFAULT_RT_TURN_SNI) },
|
||||||
|
isError = !turnSniValid,
|
||||||
|
enabled = controlsEnabled,
|
||||||
|
singleLine = true,
|
||||||
|
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri),
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
shape = RoundedCornerShape(16.dp),
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = if (turnSniValid) {
|
||||||
|
"Только для TURN/TLS и MASQUE; в TURN/TCP и UDP SNI нет"
|
||||||
|
} else {
|
||||||
|
"Укажите домен латиницей, например $DEFAULT_RT_TURN_SNI"
|
||||||
|
},
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = if (turnSniValid) {
|
||||||
|
MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
|
} else {
|
||||||
|
MaterialTheme.colorScheme.error
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f))
|
||||||
|
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||||
|
) {
|
||||||
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Text("MASQUE", fontWeight = FontWeight.SemiBold)
|
||||||
|
IconButton(
|
||||||
|
onClick = onShowMasqueHelp,
|
||||||
|
modifier = Modifier.size(32.dp),
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
Icons.AutoMirrored.Filled.HelpOutline,
|
||||||
|
contentDescription = "Инструкция по MASQUE",
|
||||||
|
modifier = Modifier.size(19.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Text(
|
||||||
|
"Резерв после TURN/TLS и TCP: HTTP/2, затем HTTP/3",
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Switch(
|
||||||
|
checked = rtMasque,
|
||||||
|
enabled = controlsEnabled,
|
||||||
|
onCheckedChange = onRtMasqueChange,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f))
|
||||||
|
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||||
|
) {
|
||||||
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Text("Через сервер", fontWeight = FontWeight.SemiBold)
|
||||||
|
IconButton(
|
||||||
|
onClick = onShowServerHelp,
|
||||||
|
modifier = Modifier.size(32.dp),
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
Icons.AutoMirrored.Filled.HelpOutline,
|
||||||
|
contentDescription = "Инструкция по регистрации через сервер",
|
||||||
|
modifier = Modifier.size(19.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Text(
|
||||||
|
serverSupportingText,
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = if (serverTextIsError) {
|
||||||
|
MaterialTheme.colorScheme.error
|
||||||
|
} else {
|
||||||
|
MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Switch(
|
||||||
|
checked = rtMasqueServerBootstrap,
|
||||||
|
enabled = controlsEnabled && rtMasque && serverAccess.available,
|
||||||
|
onCheckedChange = onServerBootstrapChange,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
Surface(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
shape = RoundedCornerShape(16.dp),
|
||||||
|
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.55f),
|
||||||
|
border = BorderStroke(
|
||||||
|
1.dp,
|
||||||
|
MaterialTheme.colorScheme.outline.copy(alpha = 0.2f),
|
||||||
|
),
|
||||||
|
) {
|
||||||
|
Column(
|
||||||
|
modifier = Modifier.padding(14.dp),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(6.dp),
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
"Когда включать",
|
||||||
|
style = MaterialTheme.typography.labelLarge,
|
||||||
|
fontWeight = FontWeight.SemiBold,
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
"Сеть РТ — если в мобильной сети Ростелекома открываются разрешённые сайты, но WDTT Plus не подключается.",
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
"MASQUE — если одной «Сети РТ» недостаточно: это дополнительный резерв после TURN/TLS и TCP.",
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
"Через сервер — только если первая регистрация WARP для MASQUE не проходит напрямую; нужен настроенный иностранный SSH-сервер в «Деплой».",
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,53 @@
|
|||||||
|
package com.wdtt.plus
|
||||||
|
|
||||||
|
import java.nio.file.Files
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class DeviceCompatibilityTest {
|
||||||
|
@Test
|
||||||
|
fun sixteenKibPagesAreSupportedByThe64BitRelease() {
|
||||||
|
val item = pageSizeCompatibilityItem(16L * 1024L, processIs64Bit = true)
|
||||||
|
|
||||||
|
assertEquals(DeviceCheckSeverity.Ok, item.severity)
|
||||||
|
assertTrue(item.status.contains("поддерживается"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun nonStandardPageSizeStillWarnsWhenItIsNotThe64BitPath() {
|
||||||
|
val item = pageSizeCompatibilityItem(16L * 1024L, processIs64Bit = false)
|
||||||
|
|
||||||
|
assertEquals(DeviceCheckSeverity.Warning, item.severity)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun masqueEnrollmentInspectorRejectsIncompleteFiles() {
|
||||||
|
val directory = Files.createTempDirectory("wdtt-masque-check-").toFile()
|
||||||
|
val config = directory.resolve(RT_MASQUE_CONFIG_FILE_NAME)
|
||||||
|
try {
|
||||||
|
config.writeText("{\"version\":1,\"private_key\":\"secret\"}")
|
||||||
|
|
||||||
|
assertEquals(RtMasqueEnrollmentState.Invalid, inspectRtMasqueEnrollment(config))
|
||||||
|
} finally {
|
||||||
|
config.delete()
|
||||||
|
directory.delete()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun masqueEnrollmentInspectorAcceptsTheVersionOneShape() {
|
||||||
|
val directory = Files.createTempDirectory("wdtt-masque-check-").toFile()
|
||||||
|
val config = directory.resolve(RT_MASQUE_CONFIG_FILE_NAME)
|
||||||
|
try {
|
||||||
|
config.writeText(
|
||||||
|
"""{"version":1,"private_key":"private","endpoint_v4":"192.0.2.1","endpoint_pub_key":"public","ipv4":"172.16.0.2"}"""
|
||||||
|
)
|
||||||
|
|
||||||
|
assertEquals(RtMasqueEnrollmentState.Ready, inspectRtMasqueEnrollment(config))
|
||||||
|
} finally {
|
||||||
|
config.delete()
|
||||||
|
directory.delete()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,285 @@
|
|||||||
|
package com.wdtt.plus
|
||||||
|
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertNotNull
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class RtTurnSniTest {
|
||||||
|
@Test
|
||||||
|
fun allRtNetworkSettingsAreRegisteredAsProfilePreferences() {
|
||||||
|
val profilePreferenceNames = SettingsStore.resettableProfilePreferenceNames()
|
||||||
|
|
||||||
|
assertTrue(
|
||||||
|
profilePreferenceNames.containsAll(
|
||||||
|
setOf(
|
||||||
|
"rt_network",
|
||||||
|
"rt_masque",
|
||||||
|
"rt_masque_server_bootstrap",
|
||||||
|
"rt_turn_sni",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun masqueRequiresBothSwitches() {
|
||||||
|
assertFalse(shouldUseRtMasque(rtNetwork = false, rtMasque = false))
|
||||||
|
assertFalse(shouldUseRtMasque(rtNetwork = false, rtMasque = true))
|
||||||
|
assertFalse(shouldUseRtMasque(rtNetwork = true, rtMasque = false))
|
||||||
|
assertTrue(shouldUseRtMasque(rtNetwork = true, rtMasque = true))
|
||||||
|
assertFalse(
|
||||||
|
shouldUseRtMasqueServerBootstrap(
|
||||||
|
rtNetwork = false,
|
||||||
|
rtMasque = true,
|
||||||
|
serverBootstrap = true,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
assertFalse(
|
||||||
|
shouldUseRtMasqueServerBootstrap(
|
||||||
|
rtNetwork = true,
|
||||||
|
rtMasque = false,
|
||||||
|
serverBootstrap = true,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
assertTrue(
|
||||||
|
shouldUseRtMasqueServerBootstrap(
|
||||||
|
rtNetwork = true,
|
||||||
|
rtMasque = true,
|
||||||
|
serverBootstrap = true,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun masqueLogsExposeProtocolFallbackAndRegistrationRecovery() {
|
||||||
|
val h2 = classifyMasqueLog(
|
||||||
|
"[СЕССИЯ #1] [MASQUE] turns:443 через HTTP/2 не сработал: timeout"
|
||||||
|
)
|
||||||
|
assertEquals("masque_h2_failed", h2?.key)
|
||||||
|
assertTrue(h2?.warning == true)
|
||||||
|
assertTrue(h2?.message?.contains("таймаут") == true)
|
||||||
|
|
||||||
|
val selected = classifyMasqueLog(
|
||||||
|
"[СЕССИЯ #1] Relay: 1.2.3.4:5 через TURN TURNS внутри MASQUE HTTP/3 ✓"
|
||||||
|
)
|
||||||
|
assertEquals("masque_selected", selected?.key)
|
||||||
|
assertTrue(selected?.startsDtls == true)
|
||||||
|
|
||||||
|
val invalid = classifyMasqueLog(
|
||||||
|
"[MASQUE] фоновая подготовка WARP пока не выполнена: сохранённая конфигурация WARP повреждена"
|
||||||
|
)
|
||||||
|
assertEquals("masque_registration_invalid", invalid?.key)
|
||||||
|
assertTrue(invalid?.message?.contains("Сбросить регистрацию WARP") == true)
|
||||||
|
|
||||||
|
assertNull(classifyMasqueLog("[TURN] обычный режим"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun enrollmentLogKeepsSafeCloudflareFailureReason() {
|
||||||
|
val rateLimit = classifyMasqueLog(
|
||||||
|
"[MASQUE] фоновая подготовка WARP пока не выполнена: регистрация WARP: WARP API HTTP 429: code=1042"
|
||||||
|
)
|
||||||
|
assertEquals("masque_enrollment_pending", rateLimit?.key)
|
||||||
|
assertTrue(rateLimit?.message?.contains("HTTP 429") == true)
|
||||||
|
assertTrue(rateLimit?.message?.contains("этап 1/4") == true)
|
||||||
|
assertTrue(rateLimit?.message?.contains("код API 1042") == true)
|
||||||
|
|
||||||
|
val serverFailure = classifyMasqueLog(
|
||||||
|
"[MASQUE] фоновая подготовка WARP пока не выполнена: этап 2/4, включение MASQUE: WARP API HTTP 500"
|
||||||
|
)
|
||||||
|
assertTrue(serverFailure?.message?.contains("временная ошибка Cloudflare") == true)
|
||||||
|
assertTrue(serverFailure?.message?.contains("этап 2/4") == true)
|
||||||
|
|
||||||
|
val unexpectedBody = classifyMasqueLog(
|
||||||
|
"[MASQUE] фоновая подготовка WARP пока не выполнена: этап 1/4, создание устройства WARP: " +
|
||||||
|
"WARP API вернул ответ не в формате JSON: HTTP 200, Content-Type=text/html, размер=1240 байт"
|
||||||
|
)
|
||||||
|
assertTrue(unexpectedBody?.message?.contains("не в формате JSON") == true)
|
||||||
|
assertTrue(unexpectedBody?.message?.contains("Content-Type=text/html") == true)
|
||||||
|
|
||||||
|
val unknownFailure = classifyMasqueLog(
|
||||||
|
"[MASQUE] фоновая подготовка WARP пока не выполнена: этап 1/4, создание ключа устройства WARP: " +
|
||||||
|
"ошибка генератора случайных чисел"
|
||||||
|
)
|
||||||
|
assertTrue(unknownFailure?.message?.contains("ошибка генератора случайных чисел") == true)
|
||||||
|
|
||||||
|
val tlsTimeout = classifyMasqueLog(
|
||||||
|
"[MASQUE] фоновая подготовка WARP пока не выполнена: этап 1/4, создание устройства WARP: " +
|
||||||
|
"WARP API: тайм-аут TLS-рукопожатия (8 с) после успешного TCP/443"
|
||||||
|
)
|
||||||
|
assertTrue(tlsTimeout?.message?.contains("TLS-рукопожатие") == true)
|
||||||
|
assertTrue(tlsTimeout?.message?.contains("после успешного TCP/443") == true)
|
||||||
|
|
||||||
|
val responseTimeout = classifyMasqueLog(
|
||||||
|
"[MASQUE] фоновая подготовка WARP пока не выполнена: этап 1/4, создание устройства WARP: " +
|
||||||
|
"WARP API: HTTP-запрос отправлен, но Cloudflare не прислал ответ за 12 с"
|
||||||
|
)
|
||||||
|
assertTrue(responseTimeout?.message?.contains("уже отправленный HTTPS-запрос") == true)
|
||||||
|
|
||||||
|
val accountCreated = classifyMasqueLog(
|
||||||
|
"[MASQUE] этап 1/4 завершён: устройство WARP создано в Cloudflare; этап 2/4 — включаем для него MASQUE"
|
||||||
|
)
|
||||||
|
assertEquals("masque_account_created", accountCreated?.key)
|
||||||
|
assertTrue(accountCreated?.message?.contains("устройство WARP создано") == true)
|
||||||
|
|
||||||
|
val saved = classifyMasqueLog(
|
||||||
|
"[MASQUE] этап 4/4 завершён: регистрация WARP сохранена в приватном хранилище приложения ✓"
|
||||||
|
)
|
||||||
|
assertEquals("masque_enrollment_saved", saved?.key)
|
||||||
|
assertTrue(saved?.message?.contains("приватном хранилище") == true)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun cloudflareApiPhasesRemainSeparateInTheVisibleLog() {
|
||||||
|
assertEquals(
|
||||||
|
"masque_api_dns",
|
||||||
|
classifyMasqueLog("[MASQUE] API Cloudflare: системный DNS Android разрешил адрес ✓")?.key,
|
||||||
|
)
|
||||||
|
assertEquals(
|
||||||
|
"masque_api_tcp",
|
||||||
|
classifyMasqueLog("[MASQUE] API Cloudflare: TCP/443 через системную сеть Android установлен ✓")?.key,
|
||||||
|
)
|
||||||
|
assertEquals(
|
||||||
|
"masque_api_tls",
|
||||||
|
classifyMasqueLog("[MASQUE] API Cloudflare: TLS-рукопожатие завершено, согласован HTTP/2 ✓")?.key,
|
||||||
|
)
|
||||||
|
assertEquals(
|
||||||
|
"masque_api_request",
|
||||||
|
classifyMasqueLog("[MASQUE] API Cloudflare: HTTP-запрос отправлен, ожидаем ответ...")?.key,
|
||||||
|
)
|
||||||
|
assertEquals(
|
||||||
|
"masque_api_response",
|
||||||
|
classifyMasqueLog("[MASQUE] API Cloudflare: получен первый байт HTTP-ответа ✓")?.key,
|
||||||
|
)
|
||||||
|
assertEquals(
|
||||||
|
"masque_api_retry",
|
||||||
|
classifyMasqueLog(
|
||||||
|
"[MASQUE] API Cloudflare: TLS timeout; данные устройства ещё не отправлялись — " +
|
||||||
|
"выполняем одну безопасную повторную попытку"
|
||||||
|
)?.key,
|
||||||
|
)
|
||||||
|
assertEquals(
|
||||||
|
"masque_api_tls_fallback",
|
||||||
|
classifyMasqueLog(
|
||||||
|
"[MASQUE] API Cloudflare: обычный TLS не прошёл до отправки данных — " +
|
||||||
|
"повторяем через TLS 1.2/HTTP 1.1 с разделённым ClientHello"
|
||||||
|
)?.key,
|
||||||
|
)
|
||||||
|
assertEquals(
|
||||||
|
"masque_api_server_retry",
|
||||||
|
classifyMasqueLog(
|
||||||
|
"[MASQUE] API Cloudflare: прямые HTTPS-пути недоступны до отправки данных — " +
|
||||||
|
"пробуем защищённый выход через сервер профиля"
|
||||||
|
)?.key,
|
||||||
|
)
|
||||||
|
assertEquals(
|
||||||
|
"masque_api_server_connected",
|
||||||
|
classifyMasqueLog(
|
||||||
|
"[MASQUE] API Cloudflare: защищённый выход через сервер профиля доступен ✓"
|
||||||
|
)?.key,
|
||||||
|
)
|
||||||
|
assertEquals(
|
||||||
|
"masque_api_tls_fallback_ok",
|
||||||
|
classifyMasqueLog(
|
||||||
|
"[MASQUE] API Cloudflare: TLS-рукопожатие завершено, согласован HTTP/1.1 ✓"
|
||||||
|
)?.key,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun normalizesValidDomain() {
|
||||||
|
assertEquals("ya.ru", normalizeRtTurnSni(" Ya.RU "))
|
||||||
|
assertEquals("telemost.yandex.ru", normalizeRtTurnSni("telemost.yandex.ru"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun rejectsValuesThatCannotBeTlsSni() {
|
||||||
|
listOf("", "ya", "127.0.0.1", "я.рф", "-ya.ru", "ya..ru").forEach { value ->
|
||||||
|
assertNull(value, normalizeRtTurnSni(value))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun rtTurnSniDoesNotReplaceExistingServerSni() {
|
||||||
|
val params = buildTunnelParams(
|
||||||
|
TunnelProfileSnapshot(
|
||||||
|
profileIndex = 0,
|
||||||
|
remoteManaged = false,
|
||||||
|
linkMode = false,
|
||||||
|
link = "",
|
||||||
|
peer = "vpn.example",
|
||||||
|
vkHashes = "hash",
|
||||||
|
secondaryVkHash = "",
|
||||||
|
connectionPassword = "password",
|
||||||
|
workersPerHash = 18,
|
||||||
|
profileMaxWorkers = 0,
|
||||||
|
manualPortsEnabled = false,
|
||||||
|
serverDtlsPort = 56000,
|
||||||
|
listenPort = 9000,
|
||||||
|
sni = "server.example",
|
||||||
|
protocol = "udp",
|
||||||
|
vkCallsPreflight = true,
|
||||||
|
rtNetwork = true,
|
||||||
|
rtMasque = true,
|
||||||
|
rtMasqueServerBootstrap = true,
|
||||||
|
rtMasqueServerAccessReady = true,
|
||||||
|
rtTurnSni = "ya.ru",
|
||||||
|
captchaMode = "auto",
|
||||||
|
captchaSolveMethod = "auto",
|
||||||
|
fingerprint = "firefox",
|
||||||
|
clientIds = DEFAULT_VK_CLIENT_IDS,
|
||||||
|
customVkCredentialsEnabled = false,
|
||||||
|
customVkClientId = "",
|
||||||
|
customVkClientSecret = "",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
assertNotNull(params)
|
||||||
|
assertEquals("server.example", params?.sni)
|
||||||
|
assertEquals("ya.ru", params?.rtTurnSni)
|
||||||
|
assertEquals(true, params?.rtMasque)
|
||||||
|
assertEquals(true, params?.rtMasqueServerBootstrap)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun serverBootstrapIsNotStartedWithoutDeploySshAccess() {
|
||||||
|
val params = buildTunnelParams(
|
||||||
|
TunnelProfileSnapshot(
|
||||||
|
profileIndex = 0,
|
||||||
|
remoteManaged = false,
|
||||||
|
linkMode = false,
|
||||||
|
link = "",
|
||||||
|
peer = "vpn.example",
|
||||||
|
vkHashes = "hash",
|
||||||
|
secondaryVkHash = "",
|
||||||
|
connectionPassword = "password",
|
||||||
|
workersPerHash = 18,
|
||||||
|
profileMaxWorkers = 0,
|
||||||
|
manualPortsEnabled = false,
|
||||||
|
serverDtlsPort = 56000,
|
||||||
|
listenPort = 9000,
|
||||||
|
sni = "",
|
||||||
|
protocol = "udp",
|
||||||
|
vkCallsPreflight = true,
|
||||||
|
rtNetwork = true,
|
||||||
|
rtMasque = true,
|
||||||
|
rtMasqueServerBootstrap = true,
|
||||||
|
rtMasqueServerAccessReady = false,
|
||||||
|
rtTurnSni = "ya.ru",
|
||||||
|
captchaMode = "auto",
|
||||||
|
captchaSolveMethod = "auto",
|
||||||
|
fingerprint = "firefox",
|
||||||
|
clientIds = DEFAULT_VK_CLIENT_IDS,
|
||||||
|
customVkCredentialsEnabled = false,
|
||||||
|
customVkClientId = "",
|
||||||
|
customVkClientSecret = "",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
assertNotNull(params)
|
||||||
|
assertEquals(false, params?.rtMasqueServerBootstrap)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -66,6 +66,22 @@ class ServerMigrationTest {
|
|||||||
assertEquals(7, result.acknowledgedLevel)
|
assertEquals(7, result.acknowledgedLevel)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun updateFrom13To14RequiresServerMigration() {
|
||||||
|
val result = resolveServerMigrationInitialization(
|
||||||
|
currentVersionCode = 14,
|
||||||
|
isUpdatedInstall = true,
|
||||||
|
storedLastSeenAppVersionCode = 13,
|
||||||
|
storedPendingLevel = 12,
|
||||||
|
storedAcknowledgedLevel = 12,
|
||||||
|
legacyAcknowledgedLevel = 5
|
||||||
|
)
|
||||||
|
|
||||||
|
assertEquals(14, result.pendingLevel)
|
||||||
|
assertEquals(12, result.acknowledgedLevel)
|
||||||
|
assertEquals(14, latestServerMigrationLevel(14))
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun stateSeparatesReadNoticeFromCompletedDeployment() {
|
fun stateSeparatesReadNoticeFromCompletedDeployment() {
|
||||||
val state = ServerMigrationState(
|
val state = ServerMigrationState(
|
||||||
|
|||||||
@@ -50,6 +50,46 @@ class SshAuthenticationTest {
|
|||||||
assertFalse(keyMode.allowPasswordAuthentication)
|
assertFalse(keyMode.allowPasswordAuthentication)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun serverBootstrapAcceptsPasswordOrValidPrivateKeyFromDeploy() {
|
||||||
|
assertTrue(
|
||||||
|
sshProfileAccessStatus(
|
||||||
|
host = "server.example",
|
||||||
|
authMode = "password",
|
||||||
|
password = "secret",
|
||||||
|
privateKey = "",
|
||||||
|
).available
|
||||||
|
)
|
||||||
|
assertTrue(
|
||||||
|
sshProfileAccessStatus(
|
||||||
|
host = "server.example",
|
||||||
|
authMode = "key",
|
||||||
|
password = "",
|
||||||
|
privateKey = openSshKey,
|
||||||
|
).available
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun serverBootstrapExplainsMissingOrInvalidDeployAccess() {
|
||||||
|
val missingHost = sshProfileAccessStatus("", "password", "secret", "")
|
||||||
|
assertFalse(missingHost.available)
|
||||||
|
assertTrue(missingHost.unavailableReason.contains("адрес сервера"))
|
||||||
|
|
||||||
|
val missingPassword = sshProfileAccessStatus("server.example", "password", "", "")
|
||||||
|
assertFalse(missingPassword.available)
|
||||||
|
assertTrue(missingPassword.unavailableReason.contains("SSH-пароль"))
|
||||||
|
|
||||||
|
val invalidKey = sshProfileAccessStatus(
|
||||||
|
host = "server.example",
|
||||||
|
authMode = "key",
|
||||||
|
password = "",
|
||||||
|
privateKey = "ssh-ed25519 AAAA public-only",
|
||||||
|
)
|
||||||
|
assertFalse(invalidKey.available)
|
||||||
|
assertTrue(invalidKey.unavailableReason.contains("приватный SSH-ключ"))
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun ed25519UsesBundledAndroidCompatibleImplementation() {
|
fun ed25519UsesBundledAndroidCompatibleImplementation() {
|
||||||
configureJschEdDsaCompatibility()
|
configureJschEdDsaCompatibility()
|
||||||
|
|||||||
@@ -109,6 +109,7 @@ class TrustedWifiTest {
|
|||||||
assertTrue(
|
assertTrue(
|
||||||
shouldKeepTunnelServiceAlive(
|
shouldKeepTunnelServiceAlive(
|
||||||
tunnelRunning = false,
|
tunnelRunning = false,
|
||||||
|
tunnelStarting = false,
|
||||||
tunnelPaused = false,
|
tunnelPaused = false,
|
||||||
trustedWifiWaiting = false,
|
trustedWifiWaiting = false,
|
||||||
trustedWifiResumeInProgress = true
|
trustedWifiResumeInProgress = true
|
||||||
@@ -117,6 +118,20 @@ class TrustedWifiTest {
|
|||||||
assertFalse(
|
assertFalse(
|
||||||
shouldKeepTunnelServiceAlive(
|
shouldKeepTunnelServiceAlive(
|
||||||
tunnelRunning = false,
|
tunnelRunning = false,
|
||||||
|
tunnelStarting = false,
|
||||||
|
tunnelPaused = false,
|
||||||
|
trustedWifiWaiting = false,
|
||||||
|
trustedWifiResumeInProgress = false
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `service stays alive while tunnel process is starting`() {
|
||||||
|
assertTrue(
|
||||||
|
shouldKeepTunnelServiceAlive(
|
||||||
|
tunnelRunning = false,
|
||||||
|
tunnelStarting = true,
|
||||||
tunnelPaused = false,
|
tunnelPaused = false,
|
||||||
trustedWifiWaiting = false,
|
trustedWifiWaiting = false,
|
||||||
trustedWifiResumeInProgress = false
|
trustedWifiResumeInProgress = false
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ class TunnelProfilePresentationTest {
|
|||||||
assertEquals("link", resolveConnectionInputMethod("", false, false, true))
|
assertEquals("link", resolveConnectionInputMethod("", false, false, true))
|
||||||
assertEquals("manual", resolveConnectionInputMethod("", false, false, false))
|
assertEquals("manual", resolveConnectionInputMethod("", false, false, false))
|
||||||
assertEquals("manual", resolveConnectionInputMethod("", false, true, true))
|
assertEquals("manual", resolveConnectionInputMethod("", false, true, true))
|
||||||
assertEquals("link", resolveConnectionInputMethod("link", false, true, false))
|
assertEquals("manual", resolveConnectionInputMethod("link", false, true, false))
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -81,7 +81,7 @@ class TunnelProfilePresentationTest {
|
|||||||
manualValid = true,
|
manualValid = true,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
assertTrue(
|
assertFalse(
|
||||||
isSelectedCompactConnectionReady(
|
isSelectedCompactConnectionReady(
|
||||||
selectedMethod = "link",
|
selectedMethod = "link",
|
||||||
savedMethod = "link",
|
savedMethod = "link",
|
||||||
@@ -91,7 +91,7 @@ class TunnelProfilePresentationTest {
|
|||||||
manualValid = true,
|
manualValid = true,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
assertFalse(
|
assertTrue(
|
||||||
isSelectedCompactConnectionReady(
|
isSelectedCompactConnectionReady(
|
||||||
selectedMethod = "manual",
|
selectedMethod = "manual",
|
||||||
savedMethod = "link",
|
savedMethod = "link",
|
||||||
|
|||||||
@@ -13,22 +13,225 @@ class TunnelRecoveryPolicyTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun failedTransportRecoveryRecreatesVpnOnce() {
|
fun repeatedStableRecoveryRemainsTransportOnly() {
|
||||||
assertEquals(
|
assertEquals(
|
||||||
NetworkRecoveryAction.RecreateVpn,
|
NetworkRecoveryAction.SoftRestart,
|
||||||
stableNetworkRecoveryAction(completedAttempts = 1),
|
stableNetworkRecoveryAction(completedAttempts = 1),
|
||||||
)
|
)
|
||||||
|
assertEquals(
|
||||||
|
NetworkRecoveryAction.SoftRestart,
|
||||||
|
stableNetworkRecoveryAction(completedAttempts = 2),
|
||||||
|
)
|
||||||
|
assertEquals(
|
||||||
|
NetworkRecoveryAction.SoftRestart,
|
||||||
|
stableNetworkRecoveryAction(completedAttempts = 3),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun failedVpnRecreationStopsFailOpen() {
|
fun vpnInterfaceRecoveryRequiresAwakeDeviceAndValidatedNetwork() {
|
||||||
assertEquals(
|
assertEquals(
|
||||||
NetworkRecoveryAction.StopVpn,
|
false,
|
||||||
stableNetworkRecoveryAction(completedAttempts = 2),
|
shouldAttemptVpnInterfaceRecovery(
|
||||||
|
deviceInteractive = false,
|
||||||
|
startupWindow = false,
|
||||||
|
captchaActive = false,
|
||||||
|
missingForMs = 120_000L,
|
||||||
|
validatedNetworkAvailable = true,
|
||||||
|
sinceLastAttemptMs = Long.MAX_VALUE,
|
||||||
|
),
|
||||||
)
|
)
|
||||||
assertEquals(
|
assertEquals(
|
||||||
NetworkRecoveryAction.StopVpn,
|
false,
|
||||||
stableNetworkRecoveryAction(completedAttempts = 3),
|
shouldAttemptVpnInterfaceRecovery(
|
||||||
|
deviceInteractive = true,
|
||||||
|
startupWindow = false,
|
||||||
|
captchaActive = false,
|
||||||
|
missingForMs = 120_000L,
|
||||||
|
validatedNetworkAvailable = false,
|
||||||
|
sinceLastAttemptMs = Long.MAX_VALUE,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
assertEquals(
|
||||||
|
true,
|
||||||
|
shouldAttemptVpnInterfaceRecovery(
|
||||||
|
deviceInteractive = true,
|
||||||
|
startupWindow = false,
|
||||||
|
captchaActive = false,
|
||||||
|
missingForMs = 120_000L,
|
||||||
|
validatedNetworkAvailable = true,
|
||||||
|
sinceLastAttemptMs = Long.MAX_VALUE,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
assertEquals(
|
||||||
|
false,
|
||||||
|
shouldAttemptVpnInterfaceRecovery(
|
||||||
|
deviceInteractive = true,
|
||||||
|
startupWindow = false,
|
||||||
|
captchaActive = false,
|
||||||
|
missingForMs = 30_000L,
|
||||||
|
validatedNetworkAvailable = true,
|
||||||
|
sinceLastAttemptMs = Long.MAX_VALUE,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
assertEquals(
|
||||||
|
false,
|
||||||
|
shouldAttemptVpnInterfaceRecovery(
|
||||||
|
deviceInteractive = true,
|
||||||
|
startupWindow = false,
|
||||||
|
captchaActive = false,
|
||||||
|
missingForMs = 120_000L,
|
||||||
|
validatedNetworkAvailable = true,
|
||||||
|
sinceLastAttemptMs = 60_000L,
|
||||||
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun sleepBatteryModePausesOnlyAnActiveTunnel() {
|
||||||
|
assertEquals(
|
||||||
|
true,
|
||||||
|
shouldPauseVpnForSleep(
|
||||||
|
pauseEnabled = true,
|
||||||
|
deviceInteractive = false,
|
||||||
|
tunnelRunning = true,
|
||||||
|
tunnelPaused = false,
|
||||||
|
trustedWifiWaiting = false,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
assertEquals(
|
||||||
|
false,
|
||||||
|
shouldPauseVpnForSleep(
|
||||||
|
pauseEnabled = false,
|
||||||
|
deviceInteractive = false,
|
||||||
|
tunnelRunning = true,
|
||||||
|
tunnelPaused = false,
|
||||||
|
trustedWifiWaiting = false,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
assertEquals(
|
||||||
|
false,
|
||||||
|
shouldPauseVpnForSleep(
|
||||||
|
pauseEnabled = true,
|
||||||
|
deviceInteractive = true,
|
||||||
|
tunnelRunning = true,
|
||||||
|
tunnelPaused = false,
|
||||||
|
trustedWifiWaiting = false,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
assertEquals(
|
||||||
|
false,
|
||||||
|
shouldPauseVpnForSleep(
|
||||||
|
pauseEnabled = true,
|
||||||
|
deviceInteractive = false,
|
||||||
|
tunnelRunning = true,
|
||||||
|
tunnelPaused = true,
|
||||||
|
trustedWifiWaiting = false,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun sleepBatteryModeResumesOnlyItsOwnPause() {
|
||||||
|
assertEquals(
|
||||||
|
true,
|
||||||
|
shouldResumeVpnAfterSleep(
|
||||||
|
sleepPausedByPolicy = true,
|
||||||
|
tunnelRunning = true,
|
||||||
|
tunnelPaused = true,
|
||||||
|
trustedWifiWaiting = false,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
assertEquals(
|
||||||
|
false,
|
||||||
|
shouldResumeVpnAfterSleep(
|
||||||
|
sleepPausedByPolicy = false,
|
||||||
|
tunnelRunning = true,
|
||||||
|
tunnelPaused = true,
|
||||||
|
trustedWifiWaiting = false,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
assertEquals(
|
||||||
|
false,
|
||||||
|
shouldResumeVpnAfterSleep(
|
||||||
|
sleepPausedByPolicy = true,
|
||||||
|
tunnelRunning = true,
|
||||||
|
tunnelPaused = true,
|
||||||
|
trustedWifiWaiting = true,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun freshActiveHeartbeatDoesNotRequireTrafficGrowth() {
|
||||||
|
assertEquals(
|
||||||
|
true,
|
||||||
|
hasFreshTransportHeartbeat(
|
||||||
|
running = true,
|
||||||
|
activeWorkers = 9,
|
||||||
|
lastActiveAtMs = 120_000L,
|
||||||
|
lastStatsAtMs = 120_000L,
|
||||||
|
sinceMs = 100_000L,
|
||||||
|
nowMs = 130_000L,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun oldOrEmptyHeartbeatStillRequiresRecovery() {
|
||||||
|
assertEquals(
|
||||||
|
false,
|
||||||
|
hasFreshTransportHeartbeat(
|
||||||
|
running = true,
|
||||||
|
activeWorkers = 9,
|
||||||
|
lastActiveAtMs = 90_000L,
|
||||||
|
lastStatsAtMs = 90_000L,
|
||||||
|
sinceMs = 100_000L,
|
||||||
|
nowMs = 130_000L,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
assertEquals(
|
||||||
|
false,
|
||||||
|
hasFreshTransportHeartbeat(
|
||||||
|
running = true,
|
||||||
|
activeWorkers = 0,
|
||||||
|
lastActiveAtMs = 120_000L,
|
||||||
|
lastStatsAtMs = 120_000L,
|
||||||
|
sinceMs = 100_000L,
|
||||||
|
nowMs = 130_000L,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun tunnelHealthIsNotJudgedDuringSleepOrWakeStabilization() {
|
||||||
|
assertEquals(
|
||||||
|
false,
|
||||||
|
shouldObserveTunnelHealth(
|
||||||
|
deviceInteractive = false,
|
||||||
|
wakeRecoveryGraceActive = false,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
assertEquals(
|
||||||
|
false,
|
||||||
|
shouldObserveTunnelHealth(
|
||||||
|
deviceInteractive = true,
|
||||||
|
wakeRecoveryGraceActive = true,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
assertEquals(
|
||||||
|
true,
|
||||||
|
shouldObserveTunnelHealth(
|
||||||
|
deviceInteractive = true,
|
||||||
|
wakeRecoveryGraceActive = false,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun phantomVpnCleanupDoesNotRaceExpectedRestore() {
|
||||||
|
assertEquals(false, shouldClearPhantomVpn(activeTunnelProfile = 0))
|
||||||
|
assertEquals(false, shouldClearPhantomVpn(activeTunnelProfile = 2))
|
||||||
|
assertEquals(true, shouldClearPhantomVpn(activeTunnelProfile = null))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
package com.wdtt.plus
|
||||||
|
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class TunnelSessionTrafficTest {
|
||||||
|
@Test
|
||||||
|
fun trafficSurvivesAnIntentionalTransportRestart() {
|
||||||
|
val accumulator = TunnelSessionTrafficAccumulator()
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
"Активных: 9 | ↓12.50 МБ / ↑3.25 МБ",
|
||||||
|
accumulator.accumulate("Активных: 9 | ↓12.50 МБ / ↑3.25 МБ"),
|
||||||
|
)
|
||||||
|
|
||||||
|
accumulator.noteTransportRestart()
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
"Активных: 9 | ↓13.00 МБ / ↑3.35 МБ",
|
||||||
|
accumulator.accumulate("Активных: 9 | ↓0.50 МБ / ↑0.10 МБ"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun unexpectedCounterResetIsAccumulatedWithoutLosingSessionTotals() {
|
||||||
|
val accumulator = TunnelSessionTrafficAccumulator()
|
||||||
|
accumulator.accumulate("Активных: 9 | ↓4,00 МБ / ↑2,00 МБ")
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
"Активных: 9 | ↓4.25 МБ / ↑2.50 МБ",
|
||||||
|
accumulator.accumulate("Активных: 9 | ↓0,25 МБ / ↑0,50 МБ"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun newSessionStartsFromFreshCounters() {
|
||||||
|
val accumulator = TunnelSessionTrafficAccumulator()
|
||||||
|
accumulator.accumulate("Активных: 9 | ↓8.00 МБ / ↑1.00 МБ")
|
||||||
|
accumulator.noteTransportRestart()
|
||||||
|
accumulator.accumulate("Активных: 9 | ↓1.00 МБ / ↑0.50 МБ")
|
||||||
|
|
||||||
|
accumulator.reset()
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
"Активных: 9 | ↓0.25 МБ / ↑0.10 МБ",
|
||||||
|
accumulator.accumulate("Активных: 9 | ↓0.25 МБ / ↑0.10 МБ"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,7 +6,7 @@ require (
|
|||||||
github.com/pion/dtls/v3 v3.1.2
|
github.com/pion/dtls/v3 v3.1.2
|
||||||
github.com/pion/transport/v4 v4.0.1
|
github.com/pion/transport/v4 v4.0.1
|
||||||
golang.org/x/crypto v0.51.0
|
golang.org/x/crypto v0.51.0
|
||||||
golang.zx2c4.com/wireguard v0.0.0-20250521234502-f333402bd9cb
|
golang.zx2c4.com/wireguard v0.0.0-20260522210424-ecfc5a8d5446
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
|
|||||||
@@ -22,8 +22,8 @@ golang.org/x/time v0.10.0 h1:3usCWA8tQn0L8+hFJQNgzpWbd89begxN66o1Ojdn5L4=
|
|||||||
golang.org/x/time v0.10.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
|
golang.org/x/time v0.10.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
|
||||||
golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 h1:B82qJJgjvYKsXS9jeunTOisW56dUokqW/FOteYJJ/yg=
|
golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 h1:B82qJJgjvYKsXS9jeunTOisW56dUokqW/FOteYJJ/yg=
|
||||||
golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2/go.mod h1:deeaetjYA+DHMHg+sMSMI58GrEteJUUzzw7en6TJQcI=
|
golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2/go.mod h1:deeaetjYA+DHMHg+sMSMI58GrEteJUUzzw7en6TJQcI=
|
||||||
golang.zx2c4.com/wireguard v0.0.0-20250521234502-f333402bd9cb h1:whnFRlWMcXI9d+ZbWg+4sHnLp52d5yiIPUxMBSt4X9A=
|
golang.zx2c4.com/wireguard v0.0.0-20260522210424-ecfc5a8d5446 h1:cqHQ3AycTHvM2R7ikgyX57D+XvtcSnGylsLkOVhta/w=
|
||||||
golang.zx2c4.com/wireguard v0.0.0-20250521234502-f333402bd9cb/go.mod h1:rpwXGsirqLqN2L0JDJQlwOboGHmptD5ZD6T2VmcqhTw=
|
golang.zx2c4.com/wireguard v0.0.0-20260522210424-ecfc5a8d5446/go.mod h1:rpwXGsirqLqN2L0JDJQlwOboGHmptD5ZD6T2VmcqhTw=
|
||||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
gvisor.dev/gvisor v0.0.0-20250503011706-39ed1f5ac29c h1:m/r7OM+Y2Ty1sgBQ7Qb27VgIMBW8ZZhT4gLnUyDIhzI=
|
gvisor.dev/gvisor v0.0.0-20250503011706-39ed1f5ac29c h1:m/r7OM+Y2Ty1sgBQ7Qb27VgIMBW8ZZhT4gLnUyDIhzI=
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
# Third-party notices
|
||||||
|
|
||||||
|
The Cloudflare WARP MASQUE interoperability in `masque_warp.go` is adapted
|
||||||
|
from [Diniboy1123/usque](https://github.com/Diniboy1123/usque), commit
|
||||||
|
`6aa03fc97d12848dce34eedbd187fb1077b5d1ea`.
|
||||||
|
|
||||||
|
The MIT License (MIT)
|
||||||
|
|
||||||
|
Copyright © 2025, github.com/Diniboy1123
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||||
|
this software and associated documentation files (the “Software”), to deal in
|
||||||
|
the Software without restriction, including without limitation the rights to
|
||||||
|
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||||
|
the Software, and to permit persons to whom the Software is furnished to do so,
|
||||||
|
subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
+12
-2
@@ -234,9 +234,16 @@ func isAuthError(err error) bool {
|
|||||||
strings.Contains(errStr, "stale nonce")
|
strings.Contains(errStr, "stale nonce")
|
||||||
}
|
}
|
||||||
|
|
||||||
func handleAuthError(streamID int) bool {
|
func handleAuthError(streamID int, username, password string) bool {
|
||||||
cache := getStreamCache(streamID)
|
cache := getStreamCache(streamID)
|
||||||
cacheID := getCacheID(streamID)
|
cacheID := getCacheID(streamID)
|
||||||
|
cache.mutex.Lock()
|
||||||
|
defer cache.mutex.Unlock()
|
||||||
|
if cache.creds.Username == "" || cache.creds.Password == "" ||
|
||||||
|
cache.creds.Username != username || cache.creds.Password != password {
|
||||||
|
log.Printf("[STREAM %d] [TURN] Креды уже заменены; поздняя ошибка авторизации проигнорирована (cache=%d)", streamID, cacheID)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
now := time.Now().Unix()
|
now := time.Now().Unix()
|
||||||
|
|
||||||
@@ -251,7 +258,10 @@ func handleAuthError(streamID int) bool {
|
|||||||
|
|
||||||
if count >= maxCacheErrors {
|
if count >= maxCacheErrors {
|
||||||
log.Printf("[VK Auth] Multiple auth errors detected (%d), invalidating cache %d", count, cacheID)
|
log.Printf("[VK Auth] Multiple auth errors detected (%d), invalidating cache %d", count, cacheID)
|
||||||
cache.invalidate(streamID)
|
cache.creds = TurnCredentials{}
|
||||||
|
cache.errorCount.Store(0)
|
||||||
|
cache.lastErrorTime.Store(0)
|
||||||
|
log.Printf("[STREAM %d] [VK Auth] Credentials cache invalidated", streamID)
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
|
|||||||
@@ -79,3 +79,47 @@ func TestClassifyHashCheckErrorKeepsTerminalAndTransientStatusesSeparate(t *test
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestAuthErrorsFromSupersededCredentialsDoNotInvalidateFreshCache(t *testing.T) {
|
||||||
|
const streamID = 9876540
|
||||||
|
cacheID := getCacheID(streamID)
|
||||||
|
credentialsStore.mu.Lock()
|
||||||
|
delete(credentialsStore.caches, cacheID)
|
||||||
|
credentialsStore.mu.Unlock()
|
||||||
|
t.Cleanup(func() {
|
||||||
|
credentialsStore.mu.Lock()
|
||||||
|
delete(credentialsStore.caches, cacheID)
|
||||||
|
credentialsStore.mu.Unlock()
|
||||||
|
})
|
||||||
|
|
||||||
|
cache := getStreamCache(streamID)
|
||||||
|
cache.mutex.Lock()
|
||||||
|
cache.creds = TurnCredentials{
|
||||||
|
Username: "fresh-user",
|
||||||
|
Password: "fresh-pass",
|
||||||
|
ServerAddrs: []string{"turn:fresh.example:3478"},
|
||||||
|
Link: "fresh-link",
|
||||||
|
}
|
||||||
|
cache.mutex.Unlock()
|
||||||
|
|
||||||
|
for attempt := 0; attempt < maxCacheErrors+2; attempt++ {
|
||||||
|
if handleAuthError(streamID, "stale-user", "stale-pass") {
|
||||||
|
t.Fatal("superseded credentials invalidated the fresh cache")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if got := cache.errorCount.Load(); got != 0 {
|
||||||
|
t.Fatalf("superseded errors were counted: %d", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
for attempt := 1; attempt <= maxCacheErrors; attempt++ {
|
||||||
|
invalidated := handleAuthError(streamID, "fresh-user", "fresh-pass")
|
||||||
|
if invalidated != (attempt == maxCacheErrors) {
|
||||||
|
t.Fatalf("attempt %d invalidated=%v", attempt, invalidated)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cache.mutex.RLock()
|
||||||
|
defer cache.mutex.RUnlock()
|
||||||
|
if cache.creds.Username != "" || cache.creds.Password != "" {
|
||||||
|
t.Fatal("current credential failures did not invalidate the cache")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,6 +11,12 @@ import (
|
|||||||
|
|
||||||
const dnsProbeHost = "login.vk.ru"
|
const dnsProbeHost = "login.vk.ru"
|
||||||
|
|
||||||
|
// Keep Android's resolver before setupGlobalResolver optionally replaces the
|
||||||
|
// process-wide resolver with a direct DNS route optimized for VK. Some public
|
||||||
|
// resolvers return different Cloudflare WARP API edges, so MASQUE enrollment
|
||||||
|
// must be able to consult the device resolver independently.
|
||||||
|
var deviceSystemResolver = net.DefaultResolver
|
||||||
|
|
||||||
type dnsRoute struct {
|
type dnsRoute struct {
|
||||||
Label string
|
Label string
|
||||||
Network string
|
Network string
|
||||||
@@ -27,7 +33,7 @@ type directDNSProbe func(context.Context, dnsRoute, time.Duration) error
|
|||||||
type systemDNSProbe func(context.Context, *net.Resolver, time.Duration) error
|
type systemDNSProbe func(context.Context, *net.Resolver, time.Duration) error
|
||||||
|
|
||||||
func setupGlobalResolver() {
|
func setupGlobalResolver() {
|
||||||
systemResolver := net.DefaultResolver
|
systemResolver := deviceSystemResolver
|
||||||
route, probes := chooseDNSRoute(context.Background(), systemResolver)
|
route, probes := chooseDNSRoute(context.Background(), systemResolver)
|
||||||
if route.System {
|
if route.System {
|
||||||
logDNSSystemRoute(probes)
|
logDNSSystemRoute(probes)
|
||||||
|
|||||||
+13
-4
@@ -10,24 +10,33 @@ require (
|
|||||||
github.com/pion/dtls/v3 v3.1.2
|
github.com/pion/dtls/v3 v3.1.2
|
||||||
github.com/pion/logging v0.2.4
|
github.com/pion/logging v0.2.4
|
||||||
github.com/pion/turn/v5 v5.0.2
|
github.com/pion/turn/v5 v5.0.2
|
||||||
golang.org/x/crypto v0.46.0
|
golang.org/x/crypto v0.51.0
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
|
github.com/Diniboy1123/connect-ip-go v0.0.0-20260613064811-66cba32d7d33 // indirect
|
||||||
github.com/andybalholm/brotli v1.2.0 // indirect
|
github.com/andybalholm/brotli v1.2.0 // indirect
|
||||||
github.com/bdandy/go-errors v1.2.2 // indirect
|
github.com/bdandy/go-errors v1.2.2 // indirect
|
||||||
github.com/bdandy/go-socks4 v1.2.3 // indirect
|
github.com/bdandy/go-socks4 v1.2.3 // indirect
|
||||||
github.com/bogdanfinn/quic-go-utls v1.0.9-utls // indirect
|
github.com/bogdanfinn/quic-go-utls v1.0.9-utls // indirect
|
||||||
github.com/bogdanfinn/utls v1.7.7-barnius // indirect
|
github.com/bogdanfinn/utls v1.7.7-barnius // indirect
|
||||||
github.com/bogdanfinn/websocket v1.5.5-barnius // indirect
|
github.com/bogdanfinn/websocket v1.5.5-barnius // indirect
|
||||||
|
github.com/dunglas/httpsfv v1.0.2 // indirect
|
||||||
|
github.com/google/btree v1.1.2 // indirect
|
||||||
github.com/klauspost/compress v1.18.2 // indirect
|
github.com/klauspost/compress v1.18.2 // indirect
|
||||||
github.com/pion/randutil v0.1.0 // indirect
|
github.com/pion/randutil v0.1.0 // indirect
|
||||||
github.com/pion/stun/v3 v3.1.1 // indirect
|
github.com/pion/stun/v3 v3.1.1 // indirect
|
||||||
github.com/pion/transport/v4 v4.0.1 // indirect
|
github.com/pion/transport/v4 v4.0.1 // indirect
|
||||||
github.com/quic-go/qpack v0.6.0 // indirect
|
github.com/quic-go/qpack v0.6.0 // indirect
|
||||||
|
github.com/quic-go/quic-go v0.60.0 // indirect
|
||||||
github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5 // indirect
|
github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5 // indirect
|
||||||
github.com/wlynxg/anet v0.0.5 // indirect
|
github.com/wlynxg/anet v0.0.5 // indirect
|
||||||
golang.org/x/net v0.48.0 // indirect
|
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
|
||||||
golang.org/x/sys v0.39.0 // indirect
|
golang.org/x/net v0.55.0 // indirect
|
||||||
golang.org/x/text v0.36.0 // indirect
|
golang.org/x/sys v0.45.0 // indirect
|
||||||
|
golang.org/x/text v0.37.0 // indirect
|
||||||
|
golang.org/x/time v0.10.0 // indirect
|
||||||
|
golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 // indirect
|
||||||
|
golang.zx2c4.com/wireguard v0.0.0-20260522210424-ecfc5a8d5446 // indirect
|
||||||
|
gvisor.dev/gvisor v0.0.0-20250503011706-39ed1f5ac29c // indirect
|
||||||
)
|
)
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
github.com/Diniboy1123/connect-ip-go v0.0.0-20260613064811-66cba32d7d33 h1:HHEVWeNlF1ytUyi4xH+K0yVrkAwCOBAz2WvriKbs7HQ=
|
||||||
|
github.com/Diniboy1123/connect-ip-go v0.0.0-20260613064811-66cba32d7d33/go.mod h1:wi7UWeMy3b9dwZZeMcJjgZfjmmJn4z+ulsfdljz+Y/E=
|
||||||
github.com/andybalholm/brotli v1.2.0 h1:ukwgCxwYrmACq68yiUqwIWnGY0cTPox/M94sVwToPjQ=
|
github.com/andybalholm/brotli v1.2.0 h1:ukwgCxwYrmACq68yiUqwIWnGY0cTPox/M94sVwToPjQ=
|
||||||
github.com/andybalholm/brotli v1.2.0/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
|
github.com/andybalholm/brotli v1.2.0/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
|
||||||
github.com/bdandy/go-errors v1.2.2 h1:WdFv/oukjTJCLa79UfkGmwX7ZxONAihKu4V0mLIs11Q=
|
github.com/bdandy/go-errors v1.2.2 h1:WdFv/oukjTJCLa79UfkGmwX7ZxONAihKu4V0mLIs11Q=
|
||||||
@@ -18,6 +20,10 @@ github.com/cbeuw/connutil v1.0.1 h1:LWuNYjwm7JEDYG/ISAO1TfU4G+q2dA5NhR97eq2roCA=
|
|||||||
github.com/cbeuw/connutil v1.0.1/go.mod h1:lKofNtrW7Atmosgp1eNnTt2j2NjA2IkifapgLVI1QtA=
|
github.com/cbeuw/connutil v1.0.1/go.mod h1:lKofNtrW7Atmosgp1eNnTt2j2NjA2IkifapgLVI1QtA=
|
||||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/dunglas/httpsfv v1.0.2 h1:iERDp/YAfnojSDJ7PW3dj1AReJz4MrwbECSSE59JWL0=
|
||||||
|
github.com/dunglas/httpsfv v1.0.2/go.mod h1:zID2mqw9mFsnt7YC3vYQ9/cjq30q41W+1AnDwH8TiMg=
|
||||||
|
github.com/google/btree v1.1.2 h1:xf4v41cLI2Z6FxbKm+8Bu+m8ifhj15JuZ9sa0jZCMUU=
|
||||||
|
github.com/google/btree v1.1.2/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4=
|
||||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
github.com/klauspost/compress v1.18.2 h1:iiPHWW0YrcFgpBYhsA6D1+fqHssJscY/Tm/y2Uqnapk=
|
github.com/klauspost/compress v1.18.2 h1:iiPHWW0YrcFgpBYhsA6D1+fqHssJscY/Tm/y2Uqnapk=
|
||||||
@@ -38,6 +44,8 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb
|
|||||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
|
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
|
||||||
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
|
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
|
||||||
|
github.com/quic-go/quic-go v0.60.0 h1:xcQioE8OM66UQLeUMHltK1CCcOu3JbVB4JAQdDQSB+0=
|
||||||
|
github.com/quic-go/quic-go v0.60.0/go.mod h1:wpKpjmPpftl30sL6pFh7REVpjbcCVy4zt2vDyK1TuJk=
|
||||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||||
github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5 h1:YqAladjX7xpA6BM04leXMWAEjS0mTZ5kUU9KRBriQJc=
|
github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5 h1:YqAladjX7xpA6BM04leXMWAEjS0mTZ5kUU9KRBriQJc=
|
||||||
@@ -46,23 +54,39 @@ github.com/wlynxg/anet v0.0.5 h1:J3VJGi1gvo0JwZ/P1/Yc/8p63SoW98B5dHkYDmpgvvU=
|
|||||||
github.com/wlynxg/anet v0.0.5/go.mod h1:eay5PRQr7fIVAMbTbchTnO9gG65Hg/uYGdc7mguHxoA=
|
github.com/wlynxg/anet v0.0.5/go.mod h1:eay5PRQr7fIVAMbTbchTnO9gG65Hg/uYGdc7mguHxoA=
|
||||||
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
|
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
|
||||||
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
|
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
|
||||||
|
github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
|
||||||
|
github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
|
||||||
go.uber.org/mock v0.5.2 h1:LbtPTcP8A5k9WPXj54PPPbjcI4Y6lhyOZXn+VS7wNko=
|
go.uber.org/mock v0.5.2 h1:LbtPTcP8A5k9WPXj54PPPbjcI4Y6lhyOZXn+VS7wNko=
|
||||||
go.uber.org/mock v0.5.2/go.mod h1:wLlUxC2vVTPTaE3UD51E0BGOAElKrILxhVSDYQLld5o=
|
go.uber.org/mock v0.5.2/go.mod h1:wLlUxC2vVTPTaE3UD51E0BGOAElKrILxhVSDYQLld5o=
|
||||||
golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU=
|
golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU=
|
||||||
golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0=
|
golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0=
|
||||||
|
golang.org/x/crypto v0.51.0 h1:IBPXwPfKxY7cWQZ38ZCIRPI50YLeevDLlLnyC5wRGTI=
|
||||||
|
golang.org/x/crypto v0.51.0/go.mod h1:8AdwkbraGNABw2kOX6YFPs3WM22XqI4EXEd8g+x7Oc8=
|
||||||
golang.org/x/net v0.0.0-20211104170005-ce137452f963/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
golang.org/x/net v0.0.0-20211104170005-ce137452f963/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||||
golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=
|
golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=
|
||||||
golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=
|
golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=
|
||||||
|
golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8=
|
||||||
|
golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww=
|
||||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
|
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
|
||||||
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||||
|
golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY=
|
||||||
|
golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||||
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||||
golang.org/x/text v0.36.0 h1:JfKh3XmcRPqZPKevfXVpI1wXPTqbkE5f7JA92a55Yxg=
|
golang.org/x/text v0.36.0 h1:JfKh3XmcRPqZPKevfXVpI1wXPTqbkE5f7JA92a55Yxg=
|
||||||
golang.org/x/text v0.36.0/go.mod h1:NIdBknypM8iqVmPiuco0Dh6P5Jcdk8lJL0CUebqK164=
|
golang.org/x/text v0.36.0/go.mod h1:NIdBknypM8iqVmPiuco0Dh6P5Jcdk8lJL0CUebqK164=
|
||||||
|
golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=
|
||||||
|
golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=
|
||||||
golang.org/x/time v0.10.0 h1:3usCWA8tQn0L8+hFJQNgzpWbd89begxN66o1Ojdn5L4=
|
golang.org/x/time v0.10.0 h1:3usCWA8tQn0L8+hFJQNgzpWbd89begxN66o1Ojdn5L4=
|
||||||
golang.org/x/time v0.10.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
|
golang.org/x/time v0.10.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
|
||||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||||
|
golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 h1:B82qJJgjvYKsXS9jeunTOisW56dUokqW/FOteYJJ/yg=
|
||||||
|
golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2/go.mod h1:deeaetjYA+DHMHg+sMSMI58GrEteJUUzzw7en6TJQcI=
|
||||||
|
golang.zx2c4.com/wireguard v0.0.0-20260522210424-ecfc5a8d5446 h1:cqHQ3AycTHvM2R7ikgyX57D+XvtcSnGylsLkOVhta/w=
|
||||||
|
golang.zx2c4.com/wireguard v0.0.0-20260522210424-ecfc5a8d5446/go.mod h1:rpwXGsirqLqN2L0JDJQlwOboGHmptD5ZD6T2VmcqhTw=
|
||||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
gvisor.dev/gvisor v0.0.0-20250503011706-39ed1f5ac29c h1:m/r7OM+Y2Ty1sgBQ7Qb27VgIMBW8ZZhT4gLnUyDIhzI=
|
||||||
|
gvisor.dev/gvisor v0.0.0-20250503011706-39ed1f5ac29c/go.mod h1:3r5CMtNQMKIvBlrmM9xWUNamjKBYPOWyXOjmg5Kts3g=
|
||||||
+109
-36
@@ -12,14 +12,62 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
workersPerGroup = 9
|
workersPerGroup = 9
|
||||||
defaultCycleSecs = 36000
|
defaultCycleSecs = 36000
|
||||||
defaultWorkerRetryMin = 5 * time.Second
|
defaultWorkerRetryMin = 5 * time.Second
|
||||||
defaultWorkerRetryMax = 15 * time.Second
|
defaultWorkerRetryMax = 15 * time.Second
|
||||||
wrapHandshakeRetryMin = 1 * time.Second
|
wrapHandshakeRetryMin = 1 * time.Second
|
||||||
wrapHandshakeRetryMax = 3 * time.Second
|
wrapHandshakeRetryMax = 3 * time.Second
|
||||||
|
refreshedCredsRetryMin = 500 * time.Millisecond
|
||||||
|
refreshedCredsRetrySlot = 250 * time.Millisecond
|
||||||
|
refreshedCredsRetryJitterMax = 250 * time.Millisecond
|
||||||
)
|
)
|
||||||
|
|
||||||
|
type credentialRefreshResult uint8
|
||||||
|
|
||||||
|
const (
|
||||||
|
credentialRefreshNone credentialRefreshResult = iota
|
||||||
|
credentialRefreshApplied
|
||||||
|
credentialRefreshSuperseded
|
||||||
|
)
|
||||||
|
|
||||||
|
type groupCredentialsState struct {
|
||||||
|
mu sync.RWMutex
|
||||||
|
value Credentials
|
||||||
|
revision uint64
|
||||||
|
}
|
||||||
|
|
||||||
|
func newGroupCredentialsState(value Credentials) *groupCredentialsState {
|
||||||
|
value.TurnURLs = cloneStringSlice(value.TurnURLs)
|
||||||
|
return &groupCredentialsState{value: value, revision: 1}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (state *groupCredentialsState) snapshot() (Credentials, uint64) {
|
||||||
|
state.mu.RLock()
|
||||||
|
defer state.mu.RUnlock()
|
||||||
|
value := state.value
|
||||||
|
value.TurnURLs = cloneStringSlice(value.TurnURLs)
|
||||||
|
return value, state.revision
|
||||||
|
}
|
||||||
|
|
||||||
|
func (state *groupCredentialsState) isCurrent(revision uint64) bool {
|
||||||
|
state.mu.RLock()
|
||||||
|
defer state.mu.RUnlock()
|
||||||
|
return state.revision == revision
|
||||||
|
}
|
||||||
|
|
||||||
|
func (state *groupCredentialsState) replaceIfCurrent(revision uint64, value Credentials) bool {
|
||||||
|
state.mu.Lock()
|
||||||
|
defer state.mu.Unlock()
|
||||||
|
if state.revision != revision {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
value.TurnURLs = cloneStringSlice(value.TurnURLs)
|
||||||
|
state.value = value
|
||||||
|
state.revision++
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
func workerRetryDelayBounds(err error) (time.Duration, time.Duration) {
|
func workerRetryDelayBounds(err error) (time.Duration, time.Duration) {
|
||||||
if err != nil && strings.Contains(strings.ToUpper(err.Error()), "WRAP_AUTH_TIMEOUT") {
|
if err != nil && strings.Contains(strings.ToUpper(err.Error()), "WRAP_AUTH_TIMEOUT") {
|
||||||
return wrapHandshakeRetryMin, wrapHandshakeRetryMax
|
return wrapHandshakeRetryMin, wrapHandshakeRetryMax
|
||||||
@@ -33,6 +81,18 @@ func workerRetryDelay(err error) time.Duration {
|
|||||||
return minDelay + time.Duration(rand.Intn(steps))*time.Second
|
return minDelay + time.Duration(rand.Intn(steps))*time.Second
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func workerRetryDelayAfterCredentialRefresh(err error, result credentialRefreshResult, workerIndex int) time.Duration {
|
||||||
|
if result != credentialRefreshApplied && result != credentialRefreshSuperseded {
|
||||||
|
return workerRetryDelay(err)
|
||||||
|
}
|
||||||
|
if workerIndex < 0 {
|
||||||
|
workerIndex = 0
|
||||||
|
}
|
||||||
|
slot := workerIndex % workersPerGroup
|
||||||
|
jitter := time.Duration(rand.Int63n(int64(refreshedCredsRetryJitterMax) + 1))
|
||||||
|
return refreshedCredsRetryMin + time.Duration(slot)*refreshedCredsRetrySlot + jitter
|
||||||
|
}
|
||||||
|
|
||||||
type workerPolicyRetryGate struct {
|
type workerPolicyRetryGate struct {
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
blockedUntil time.Time
|
blockedUntil time.Time
|
||||||
@@ -140,6 +200,7 @@ func WorkerGroup(
|
|||||||
pauseFlag *int32,
|
pauseFlag *int32,
|
||||||
deviceID, password, deviceInfo, transportSession string,
|
deviceID, password, deviceInfo, transportSession string,
|
||||||
stats *Stats,
|
stats *Stats,
|
||||||
|
turnStreamFirst bool,
|
||||||
waitReady <-chan struct{},
|
waitReady <-chan struct{},
|
||||||
signalReady chan<- struct{},
|
signalReady chan<- struct{},
|
||||||
) {
|
) {
|
||||||
@@ -240,26 +301,35 @@ func WorkerGroup(
|
|||||||
user, pass, turnURLs, err = GetCreds(ctx, hash, credStreamID)
|
user, pass, turnURLs, err = GetCreds(ctx, hash, credStreamID)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
creds := &Credentials{User: user, Pass: pass, TurnURLs: turnURLs, CacheStreamID: credStreamID}
|
credsState := newGroupCredentialsState(Credentials{
|
||||||
|
User: user,
|
||||||
|
Pass: pass,
|
||||||
|
TurnURLs: turnURLs,
|
||||||
|
CacheStreamID: credStreamID,
|
||||||
|
})
|
||||||
|
|
||||||
log.Printf("[ГРУППА #%d] Креды OK, TURN: %v, %d воркеров", groupID, creds.TurnURLs, len(workerIDs))
|
initialCreds, _ := credsState.snapshot()
|
||||||
|
log.Printf("[ГРУППА #%d] Креды OK, TURN: %v, %d воркеров", groupID, initialCreds.TurnURLs, len(workerIDs))
|
||||||
|
|
||||||
var configRequestInFlight int32
|
var configRequestInFlight int32
|
||||||
var wg sync.WaitGroup
|
var wg sync.WaitGroup
|
||||||
var credsMu sync.RWMutex
|
|
||||||
var refreshMu sync.Mutex
|
var refreshMu sync.Mutex
|
||||||
var lastCredRefresh atomic.Int64
|
var lastCredRefresh atomic.Int64
|
||||||
var policyRetryGate workerPolicyRetryGate
|
var policyRetryGate workerPolicyRetryGate
|
||||||
|
|
||||||
refreshCreds := func(reason string) bool {
|
refreshCreds := func(reason string, failedRevision uint64) credentialRefreshResult {
|
||||||
refreshMu.Lock()
|
refreshMu.Lock()
|
||||||
defer refreshMu.Unlock()
|
defer refreshMu.Unlock()
|
||||||
|
if !credsState.isCurrent(failedRevision) {
|
||||||
|
log.Printf("[TURN] Креды уже заменены после этой попытки, используем актуальные (%s)", reason)
|
||||||
|
return credentialRefreshSuperseded
|
||||||
|
}
|
||||||
|
|
||||||
now := time.Now().Unix()
|
now := time.Now().Unix()
|
||||||
last := lastCredRefresh.Load()
|
last := lastCredRefresh.Load()
|
||||||
if last > 0 && now-last < 15 {
|
if last > 0 && now-last < 15 {
|
||||||
log.Printf("[TURN] Креды уже обновлялись %d сек назад, ждём следующий retry (%s)", now-last, reason)
|
log.Printf("[TURN] Креды уже обновлялись %d сек назад, ждём следующий retry (%s)", now-last, reason)
|
||||||
return true
|
return credentialRefreshNone
|
||||||
}
|
}
|
||||||
|
|
||||||
rotateForTurnFailure := hashFallback &&
|
rotateForTurnFailure := hashFallback &&
|
||||||
@@ -295,17 +365,24 @@ func WorkerGroup(
|
|||||||
}
|
}
|
||||||
if refreshErr != nil {
|
if refreshErr != nil {
|
||||||
log.Printf("[TURN] Не удалось обновить креды после %s: %v", reason, refreshErr)
|
log.Printf("[TURN] Не удалось обновить креды после %s: %v", reason, refreshErr)
|
||||||
return false
|
return credentialRefreshNone
|
||||||
}
|
}
|
||||||
selectedHash = nextHashIndex
|
selectedHash = nextHashIndex
|
||||||
hash = hashCandidates[selectedHash]
|
hash = hashCandidates[selectedHash]
|
||||||
|
|
||||||
credsMu.Lock()
|
replaced := credsState.replaceIfCurrent(failedRevision, Credentials{
|
||||||
creds = &Credentials{User: u, Pass: p, TurnURLs: urls, CacheStreamID: credStreamID}
|
User: u,
|
||||||
credsMu.Unlock()
|
Pass: p,
|
||||||
|
TurnURLs: urls,
|
||||||
|
CacheStreamID: credStreamID,
|
||||||
|
})
|
||||||
|
if !replaced {
|
||||||
|
log.Printf("[TURN] Креды уже заменены во время обновления, используем актуальные (%s)", reason)
|
||||||
|
return credentialRefreshSuperseded
|
||||||
|
}
|
||||||
lastCredRefresh.Store(time.Now().Unix())
|
lastCredRefresh.Store(time.Now().Unix())
|
||||||
log.Printf("[TURN] Креды обновлены после %s, TURN urls=%d", reason, len(urls))
|
log.Printf("[TURN] Креды обновлены после %s, TURN urls=%d", reason, len(urls))
|
||||||
return true
|
return credentialRefreshApplied
|
||||||
}
|
}
|
||||||
|
|
||||||
// Сигнализируем следующей группе, что мы успешно запустились (креды получены + 2 сек форы)
|
// Сигнализируем следующей группе, что мы успешно запустились (креды получены + 2 сек форы)
|
||||||
@@ -358,15 +435,13 @@ func WorkerGroup(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
credsMu.RLock()
|
credsSnapshot, credsRevision := credsState.snapshot()
|
||||||
credsSnapshot := *creds
|
|
||||||
credsSnapshot.TurnURLs = cloneStringSlice(creds.TurnURLs)
|
|
||||||
credsMu.RUnlock()
|
|
||||||
|
|
||||||
configDelivered, sessErr := RunSession(ctx, tp, peer, d, localPort,
|
configDelivered, sessErr := RunSession(ctx, tp, peer, d, localPort,
|
||||||
getConf, cc, requireConfig, onConfigDelivered, wid, &credsSnapshot,
|
getConf, cc, requireConfig, onConfigDelivered, wid, &credsSnapshot,
|
||||||
deviceID, password, deviceInfo,
|
deviceID, password, deviceInfo,
|
||||||
transportSession, stats)
|
transportSession, stats, turnStreamFirst)
|
||||||
|
refreshResult := credentialRefreshNone
|
||||||
|
|
||||||
if getConf {
|
if getConf {
|
||||||
if configDelivered {
|
if configDelivered {
|
||||||
@@ -406,14 +481,8 @@ func WorkerGroup(
|
|||||||
|
|
||||||
turnAllocAttrMissing := strings.Contains(errStrLower, "turn allocate") &&
|
turnAllocAttrMissing := strings.Contains(errStrLower, "turn allocate") &&
|
||||||
strings.Contains(errStrLower, "attribute not found")
|
strings.Contains(errStrLower, "attribute not found")
|
||||||
turnCredRefreshNeeded := turnAllocAttrMissing ||
|
turnCredRefreshNeeded := turnAllocAttrMissing || isCredentialTURNError(sessErr)
|
||||||
strings.Contains(errStrLower, "turn allocate auth") ||
|
turnCapacityLimited := isTURNCapacityError(sessErr)
|
||||||
strings.Contains(errStrLower, "invalid credential") ||
|
|
||||||
strings.Contains(errStrLower, "stale nonce") ||
|
|
||||||
strings.Contains(errStrLower, "allocation mismatch") ||
|
|
||||||
strings.Contains(errStrLower, "error 508") ||
|
|
||||||
strings.Contains(errStrLower, "turn квота") ||
|
|
||||||
strings.Contains(errStrLower, "quota")
|
|
||||||
|
|
||||||
if strings.Contains(errStrLower, "rate limit") ||
|
if strings.Contains(errStrLower, "rate limit") ||
|
||||||
strings.Contains(errStrLower, "flood control") ||
|
strings.Contains(errStrLower, "flood control") ||
|
||||||
@@ -431,10 +500,12 @@ func WorkerGroup(
|
|||||||
attempt++
|
attempt++
|
||||||
if turnAllocAttrMissing {
|
if turnAllocAttrMissing {
|
||||||
log.Printf("[ВОРКЕР #%d] [TURN] Allocate вернул неполный ответ, обновляем TURN-креды и повторяем (попытка %d): %s", wid, attempt, errStr)
|
log.Printf("[ВОРКЕР #%d] [TURN] Allocate вернул неполный ответ, обновляем TURN-креды и повторяем (попытка %d): %s", wid, attempt, errStr)
|
||||||
refreshCreds("TURN Allocate attribute-not-found")
|
refreshResult = refreshCreds("TURN Allocate attribute-not-found", credsRevision)
|
||||||
} else if turnCredRefreshNeeded {
|
} else if turnCredRefreshNeeded {
|
||||||
log.Printf("[ВОРКЕР #%d] [TURN] Ошибка allocation/кредов, обновляем TURN-креды и повторяем (попытка %d): %s", wid, attempt, errStr)
|
log.Printf("[ВОРКЕР #%d] [TURN] Ошибка allocation/кредов, обновляем TURN-креды и повторяем (попытка %d): %s", wid, attempt, errStr)
|
||||||
refreshCreds("TURN allocation error")
|
refreshResult = refreshCreds("TURN allocation error", credsRevision)
|
||||||
|
} else if turnCapacityLimited {
|
||||||
|
log.Printf("[ВОРКЕР #%d] [TURN] Узел временно ограничил новые allocation; сохраняем креды и повторяем другие TURN-пути (попытка %d): %s", wid, attempt, errStr)
|
||||||
} else {
|
} else {
|
||||||
log.Printf("[ВОРКЕР #%d] Ошибка (попытка %d): %s", wid, attempt, errStr)
|
log.Printf("[ВОРКЕР #%d] Ошибка (попытка %d): %s", wid, attempt, errStr)
|
||||||
}
|
}
|
||||||
@@ -453,7 +524,7 @@ func WorkerGroup(
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
retryDelay := workerRetryDelay(sessErr)
|
retryDelay := workerRetryDelayAfterCredentialRefresh(sessErr, refreshResult, workerIndex)
|
||||||
select {
|
select {
|
||||||
case <-time.After(retryDelay):
|
case <-time.After(retryDelay):
|
||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
@@ -554,10 +625,12 @@ func normalizeVKJoinHash(input string) string {
|
|||||||
|
|
||||||
// TurnParams — конфигурация TURN
|
// TurnParams — конфигурация TURN
|
||||||
type TurnParams struct {
|
type TurnParams struct {
|
||||||
Host string
|
Host string
|
||||||
Port string
|
Port string
|
||||||
Hashes []string
|
Hashes []string
|
||||||
WrapKey []byte // Password-derived WRAP key (32 bytes), nil = disabled
|
TLSFrontSNI string
|
||||||
|
Masque *warpMasqueManager
|
||||||
|
WrapKey []byte // Password-derived WRAP key (32 bytes), nil = disabled
|
||||||
}
|
}
|
||||||
|
|
||||||
// Credentials — учетные данные TURN
|
// Credentials — учетные данные TURN
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"reflect"
|
"reflect"
|
||||||
|
"sync"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
@@ -61,6 +62,127 @@ func TestWorkerPolicyRetryDelayIsBounded(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestGroupCredentialsStateRejectsStaleReplacement(t *testing.T) {
|
||||||
|
state := newGroupCredentialsState(Credentials{
|
||||||
|
User: "first-user",
|
||||||
|
Pass: "first-pass",
|
||||||
|
TurnURLs: []string{"turn:first.example:3478"},
|
||||||
|
})
|
||||||
|
|
||||||
|
first, revision := state.snapshot()
|
||||||
|
first.TurnURLs[0] = "mutated-outside-state"
|
||||||
|
unchanged, unchangedRevision := state.snapshot()
|
||||||
|
if unchanged.TurnURLs[0] != "turn:first.example:3478" {
|
||||||
|
t.Fatal("snapshot must not expose the stored TURN URL slice")
|
||||||
|
}
|
||||||
|
if unchangedRevision != revision {
|
||||||
|
t.Fatalf("initial revision changed: got %d, want %d", unchangedRevision, revision)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !state.replaceIfCurrent(revision, Credentials{
|
||||||
|
User: "fresh-user",
|
||||||
|
Pass: "fresh-pass",
|
||||||
|
TurnURLs: []string{"turn:fresh.example:3478"},
|
||||||
|
}) {
|
||||||
|
t.Fatal("current credential revision was not replaced")
|
||||||
|
}
|
||||||
|
if state.replaceIfCurrent(revision, first) {
|
||||||
|
t.Fatal("a stale worker replaced newer credentials")
|
||||||
|
}
|
||||||
|
fresh, freshRevision := state.snapshot()
|
||||||
|
if fresh.User != "fresh-user" || freshRevision != revision+1 {
|
||||||
|
t.Fatalf("fresh credentials = %#v at revision %d", fresh, freshRevision)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCredentialRefreshRetryUsesShortBoundedJitter(t *testing.T) {
|
||||||
|
for _, result := range []credentialRefreshResult{
|
||||||
|
credentialRefreshApplied,
|
||||||
|
credentialRefreshSuperseded,
|
||||||
|
} {
|
||||||
|
for workerIndex := 0; workerIndex < workersPerGroup; workerIndex++ {
|
||||||
|
minimum := refreshedCredsRetryMin + time.Duration(workerIndex)*refreshedCredsRetrySlot
|
||||||
|
maximum := minimum + refreshedCredsRetryJitterMax
|
||||||
|
for attempt := 0; attempt < 100; attempt++ {
|
||||||
|
delay := workerRetryDelayAfterCredentialRefresh(errors.New("TURN auth"), result, workerIndex)
|
||||||
|
if delay < minimum || delay > maximum {
|
||||||
|
t.Fatalf("worker %d short retry delay %v outside %v..%v", workerIndex, delay, minimum, maximum)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
delay := workerRetryDelayAfterCredentialRefresh(errors.New("TURN timeout"), credentialRefreshNone, 8)
|
||||||
|
if delay < defaultWorkerRetryMin || delay > defaultWorkerRetryMax {
|
||||||
|
t.Fatalf("ordinary retry delay %v outside %v..%v", delay, defaultWorkerRetryMin, defaultWorkerRetryMax)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCredentialRevisionsStayIndependentAtMaximumPower(t *testing.T) {
|
||||||
|
const groupCount = 108 / workersPerGroup
|
||||||
|
states := make([]*groupCredentialsState, groupCount)
|
||||||
|
for group := range states {
|
||||||
|
states[group] = newGroupCredentialsState(Credentials{
|
||||||
|
User: "initial",
|
||||||
|
TurnURLs: []string{"turn:initial.example:3478"},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
wins := make([]int, groupCount)
|
||||||
|
var winsMu sync.Mutex
|
||||||
|
for group, state := range states {
|
||||||
|
_, revision := state.snapshot()
|
||||||
|
for worker := 0; worker < workersPerGroup; worker++ {
|
||||||
|
wg.Add(1)
|
||||||
|
go func(group, worker int, state *groupCredentialsState, revision uint64) {
|
||||||
|
defer wg.Done()
|
||||||
|
if state.replaceIfCurrent(revision, Credentials{
|
||||||
|
User: "fresh",
|
||||||
|
TurnURLs: []string{"turn:fresh.example:3478"},
|
||||||
|
}) {
|
||||||
|
winsMu.Lock()
|
||||||
|
wins[group]++
|
||||||
|
winsMu.Unlock()
|
||||||
|
}
|
||||||
|
}(group, worker, state, revision)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
wg.Wait()
|
||||||
|
|
||||||
|
for group, state := range states {
|
||||||
|
if wins[group] != 1 {
|
||||||
|
t.Fatalf("group %d accepted %d replacements, want exactly one", group, wins[group])
|
||||||
|
}
|
||||||
|
credentials, revision := state.snapshot()
|
||||||
|
if credentials.User != "fresh" || revision != 2 {
|
||||||
|
t.Fatalf("group %d credentials = %#v at revision %d", group, credentials, revision)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTURNCapacityDoesNotInvalidateCredentials(t *testing.T) {
|
||||||
|
for _, message := range []string{"TURN квота: error 486", "TURN Allocate: error 508", "allocation quota reached"} {
|
||||||
|
err := errors.New(message)
|
||||||
|
if !isTURNCapacityError(err) {
|
||||||
|
t.Fatalf("%q must be classified as endpoint capacity", message)
|
||||||
|
}
|
||||||
|
if isCredentialTURNError(err) {
|
||||||
|
t.Fatalf("%q must not invalidate VK credentials", message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, message := range []string{"TURN Allocate: error 401 Unauthorized", "invalid credential", "stale nonce", "allocation mismatch"} {
|
||||||
|
err := errors.New(message)
|
||||||
|
if !isCredentialTURNError(err) {
|
||||||
|
t.Fatalf("%q must refresh credentials", message)
|
||||||
|
}
|
||||||
|
if isTURNCapacityError(err) {
|
||||||
|
t.Fatalf("%q must not be classified as endpoint capacity", message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestWrapHandshakeRetryUsesShortDedicatedWindow(t *testing.T) {
|
func TestWrapHandshakeRetryUsesShortDedicatedWindow(t *testing.T) {
|
||||||
minDelay, maxDelay := workerRetryDelayBounds(
|
minDelay, maxDelay := workerRetryDelayBounds(
|
||||||
errors.New("WRAP_AUTH_TIMEOUT: отдельный DTLS-канал не ответил вовремя"),
|
errors.New("WRAP_AUTH_TIMEOUT: отдельный DTLS-канал не ответил вовремя"),
|
||||||
|
|||||||
+72
-5
@@ -235,6 +235,9 @@ func enqueueCaptchaResult(result CaptchaResult) {
|
|||||||
func main() {
|
func main() {
|
||||||
log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds)
|
log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds)
|
||||||
os.Args = normalizeBooleanFlagArgs(os.Args, "-vkcalls-preflight")
|
os.Args = normalizeBooleanFlagArgs(os.Args, "-vkcalls-preflight")
|
||||||
|
os.Args = normalizeBooleanFlagArgs(os.Args, "-turn-stream-first")
|
||||||
|
os.Args = normalizeBooleanFlagArgs(os.Args, "-rt-masque")
|
||||||
|
os.Args = normalizeBooleanFlagArgs(os.Args, "-rt-masque-accept-tos")
|
||||||
|
|
||||||
setupGlobalResolver()
|
setupGlobalResolver()
|
||||||
|
|
||||||
@@ -322,6 +325,36 @@ func main() {
|
|||||||
connPassword := flag.String("password", "", "пароль подключения")
|
connPassword := flag.String("password", "", "пароль подключения")
|
||||||
captchaMode := flag.String("captcha-mode", "auto", "режим обхода капчи (auto/wv/rjs)")
|
captchaMode := flag.String("captcha-mode", "auto", "режим обхода капчи (auto/wv/rjs)")
|
||||||
vkCallsPreflight := flag.Bool("vkcalls-preflight", true, "пробовать VKCalls до captcha-цепочки")
|
vkCallsPreflight := flag.Bool("vkcalls-preflight", true, "пробовать VKCalls до captcha-цепочки")
|
||||||
|
turnStreamFirst := flag.Bool(
|
||||||
|
"turn-stream-first",
|
||||||
|
false,
|
||||||
|
"сначала пробовать TURN/TLS и TURN/TCP, сохраняя UDP как резерв",
|
||||||
|
)
|
||||||
|
turnSNI := flag.String(
|
||||||
|
"turn-sni",
|
||||||
|
"",
|
||||||
|
"SNI белого списка для TURN/TLS (используется только внешним TLS-соединением)",
|
||||||
|
)
|
||||||
|
rtMasque := flag.Bool(
|
||||||
|
"rt-masque",
|
||||||
|
false,
|
||||||
|
"после прямых путей Сети РТ пробовать WARP CONNECT-IP по HTTP/2 и HTTP/3",
|
||||||
|
)
|
||||||
|
rtMasqueConfig := flag.String(
|
||||||
|
"rt-masque-config",
|
||||||
|
"",
|
||||||
|
"путь к приватной конфигурации enrollment WARP MASQUE",
|
||||||
|
)
|
||||||
|
rtMasqueAcceptTOS := flag.Bool(
|
||||||
|
"rt-masque-accept-tos",
|
||||||
|
false,
|
||||||
|
"пользователь подтвердил условия Cloudflare для первой регистрации WARP",
|
||||||
|
)
|
||||||
|
warpAPIRelay := flag.String(
|
||||||
|
"warp-api-relay",
|
||||||
|
"",
|
||||||
|
"локальный loopback-выход только для регистрации WARP API",
|
||||||
|
)
|
||||||
fingerprint := flag.String("fingerprint", "firefox", "браузерный фингерпринт (firefox, chrome, safari, ios, android)")
|
fingerprint := flag.String("fingerprint", "firefox", "браузерный фингерпринт (firefox, chrome, safari, ios, android)")
|
||||||
clientIdsFlag := flag.String("client-ids", "", "ID клиентов VK через запятую")
|
clientIdsFlag := flag.String("client-ids", "", "ID клиентов VK через запятую")
|
||||||
|
|
||||||
@@ -332,6 +365,22 @@ func main() {
|
|||||||
}
|
}
|
||||||
activeCaptchaMode := setCaptchaMode(*captchaMode)
|
activeCaptchaMode := setCaptchaMode(*captchaMode)
|
||||||
setVKCallsPreflight(*vkCallsPreflight, *deviceID)
|
setVKCallsPreflight(*vkCallsPreflight, *deviceID)
|
||||||
|
var normalizedTurnSNI string
|
||||||
|
if *turnStreamFirst {
|
||||||
|
var turnSNIErr error
|
||||||
|
normalizedTurnSNI, turnSNIErr = normalizeTURNFrontSNI(*turnSNI)
|
||||||
|
if turnSNIErr != nil {
|
||||||
|
log.Fatalf("[КЛИЕНТ] Некорректный TURN SNI: %v", turnSNIErr)
|
||||||
|
}
|
||||||
|
if normalizedTurnSNI != "" {
|
||||||
|
log.Printf("[TURN] Режим «Сеть РТ»: TURN/TLS, затем TCP ко всем адресам VK с разделением первого STUN-запроса; UDP остаётся резервом; внешний TLS SNI=%s", normalizedTurnSNI)
|
||||||
|
} else {
|
||||||
|
log.Printf("[TURN] Режим «Сеть РТ»: TURN/TLS, затем TCP ко всем адресам VK с разделением первого STUN-запроса; UDP остаётся резервом")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if *rtMasque && !*turnStreamFirst {
|
||||||
|
log.Printf("[MASQUE] Проигнорирован: механизм доступен только вместе с режимом «Сеть РТ»")
|
||||||
|
}
|
||||||
|
|
||||||
if *vkHash == "" {
|
if *vkHash == "" {
|
||||||
log.Fatal("[КЛИЕНТ] Нужен -vk")
|
log.Fatal("[КЛИЕНТ] Нужен -vk")
|
||||||
@@ -404,11 +453,29 @@ func main() {
|
|||||||
useConfigFirstStart := *configFirstStart && *numW == workersPerGroup
|
useConfigFirstStart := *configFirstStart && *numW == workersPerGroup
|
||||||
useHashFallback := *hashFallback && *numW == workersPerGroup
|
useHashFallback := *hashFallback && *numW == workersPerGroup
|
||||||
|
|
||||||
|
var masqueManager *warpMasqueManager
|
||||||
|
if *turnStreamFirst && *rtMasque {
|
||||||
|
if err := configureWarpAPIRelay(*warpAPIRelay); err != nil {
|
||||||
|
log.Printf("[MASQUE] Локальный выход для регистрации WARP отклонён: %v; продолжаем прямые попытки", err)
|
||||||
|
}
|
||||||
|
masqueManager, err = newWarpMasqueManager(ctx, *rtMasqueConfig, normalizedTurnSNI, *rtMasqueAcceptTOS)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("[MASQUE] Не удалось включить новый механизм: %v; прямые пути «Сети РТ» остаются доступны", err)
|
||||||
|
masqueManager = nil
|
||||||
|
} else {
|
||||||
|
defer masqueManager.Close()
|
||||||
|
log.Printf("[MASQUE] Включён резерв после прямых путей: HTTP/2 (TCP/443), затем HTTP/3 (QUIC/443)")
|
||||||
|
go masqueManager.prewarmConfig()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
tp := &TurnParams{
|
tp := &TurnParams{
|
||||||
Host: *host,
|
Host: *host,
|
||||||
Port: *port,
|
Port: *port,
|
||||||
Hashes: hashes,
|
Hashes: hashes,
|
||||||
WrapKey: wrapKey,
|
TLSFrontSNI: normalizedTurnSNI,
|
||||||
|
Masque: masqueManager,
|
||||||
|
WrapKey: wrapKey,
|
||||||
}
|
}
|
||||||
|
|
||||||
// Слушаем локально с ожиданием (если старый процесс еще не убит Parent Watcher'ом)
|
// Слушаем локально с ожиданием (если старый процесс еще не убит Parent Watcher'ом)
|
||||||
@@ -555,7 +622,7 @@ func main() {
|
|||||||
defer wg.Done()
|
defer wg.Done()
|
||||||
WorkerGroup(ctx, cancel, groupID, startHashIndex, tp, peer, disp, localPort,
|
WorkerGroup(ctx, cancel, groupID, startHashIndex, tp, peer, disp, localPort,
|
||||||
isFirstGroup, configChan, workerIds, *numW, useConfigFirstStart, useHashFallback, &pauseFlag,
|
isFirstGroup, configChan, workerIds, *numW, useConfigFirstStart, useHashFallback, &pauseFlag,
|
||||||
*deviceID, *connPassword, *deviceInfo, transportSession, stats, waitR, sigR)
|
*deviceID, *connPassword, *deviceInfo, transportSession, stats, *turnStreamFirst, waitR, sigR)
|
||||||
}(gID, isFirst, cc, ids, g, myWaitReady, mySignalReady)
|
}(gID, isFirst, cc, ids, g, myWaitReady, mySignalReady)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,337 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"crypto/ecdsa"
|
||||||
|
"crypto/elliptic"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/tls"
|
||||||
|
"crypto/x509"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/pem"
|
||||||
|
"errors"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"net/http/httptrace"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func testWarpMasqueConfig(t *testing.T) *warpMasqueConfig {
|
||||||
|
t.Helper()
|
||||||
|
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
privateDER, err := x509.MarshalECPrivateKey(key)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
publicDER, err := x509.MarshalPKIXPublicKey(&key.PublicKey)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return &warpMasqueConfig{
|
||||||
|
Version: warpConfigVersion,
|
||||||
|
PrivateKey: base64.StdEncoding.EncodeToString(privateDER),
|
||||||
|
EndpointV4: "162.159.197.1",
|
||||||
|
EndpointH2V4: warpDefaultH2Endpoint,
|
||||||
|
EndpointPubKey: string(pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: publicDER})),
|
||||||
|
DeviceID: "device",
|
||||||
|
AccessToken: "token",
|
||||||
|
IPv4: "172.16.0.2",
|
||||||
|
IPv6: "2606:4700:110:8f1b::2",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWarpMasqueProtocolOrder(t *testing.T) {
|
||||||
|
if got, want := warpMasqueProtocolOrder(""), []warpMasqueProtocol{warpMasqueHTTP2, warpMasqueHTTP3}; !reflect.DeepEqual(got, want) {
|
||||||
|
t.Fatalf("default order = %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
if got, want := warpMasqueProtocolOrder(warpMasqueHTTP3), []warpMasqueProtocol{warpMasqueHTTP3, warpMasqueHTTP2}; !reflect.DeepEqual(got, want) {
|
||||||
|
t.Fatalf("remembered order = %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEndpointHost(t *testing.T) {
|
||||||
|
for input, want := range map[string]string{
|
||||||
|
"162.159.197.1:0": "162.159.197.1",
|
||||||
|
"[2606:4700::1]:0": "2606:4700::1",
|
||||||
|
"162.159.197.1": "162.159.197.1",
|
||||||
|
} {
|
||||||
|
got, err := endpointHost(input)
|
||||||
|
if err != nil || got != want {
|
||||||
|
t.Fatalf("endpointHost(%q) = %q, %v; want %q", input, got, err, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := endpointHost("warp.invalid:0"); err == nil {
|
||||||
|
t.Fatal("hostname endpoint must be rejected")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWarpMasqueConfigRoundTripIsPrivate(t *testing.T) {
|
||||||
|
path := filepath.Join(t.TempDir(), "nested", "warp.json")
|
||||||
|
want := testWarpMasqueConfig(t)
|
||||||
|
if err := saveWarpMasqueConfig(path, want); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
info, err := os.Stat(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got := info.Mode().Perm(); got != 0o600 {
|
||||||
|
t.Fatalf("config mode = %o, want 600", got)
|
||||||
|
}
|
||||||
|
got, err := loadWarpMasqueConfig(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(got, want) {
|
||||||
|
t.Fatalf("round trip mismatch:\n got %#v\nwant %#v", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWarpMasqueRequiresExplicitSNIAndConfigPath(t *testing.T) {
|
||||||
|
if _, err := newWarpMasqueManager(context.Background(), "", "ya.ru", true); err == nil {
|
||||||
|
t.Fatal("empty config path must be rejected")
|
||||||
|
}
|
||||||
|
if _, err := newWarpMasqueManager(context.Background(), "warp.json", "", true); err == nil {
|
||||||
|
t.Fatal("empty outer SNI must be rejected")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWarpAPIErrorMessageKeepsSafeStatusAndBackendCode(t *testing.T) {
|
||||||
|
got := warpAPIErrorMessage(429, []byte(`{"errors":[{"code":1042,"message":" rate limited "}]}`))
|
||||||
|
want := "WARP API HTTP 429: code=1042 rate limited"
|
||||||
|
if got != want {
|
||||||
|
t.Fatalf("warpAPIErrorMessage = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWarpAPINetworkErrorRemovesDeviceURL(t *testing.T) {
|
||||||
|
got := warpAPINetworkError(&url.Error{
|
||||||
|
Op: "Patch",
|
||||||
|
URL: "https://api.cloudflareclient.com/v0a4471/reg/secret-device-id",
|
||||||
|
Err: context.DeadlineExceeded,
|
||||||
|
}, warpAPIPhaseResponse).Error()
|
||||||
|
if strings.Contains(got, "secret-device-id") || strings.Contains(got, "https://") {
|
||||||
|
t.Fatalf("network error leaked request URL: %q", got)
|
||||||
|
}
|
||||||
|
if !strings.Contains(got, "HTTP-запрос отправлен") {
|
||||||
|
t.Fatalf("network error lacks Russian diagnosis: %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWarpAPINetworkErrorNamesExactHTTPSPhase(t *testing.T) {
|
||||||
|
tlsError := warpAPINetworkError(
|
||||||
|
errors.New("net/http: TLS handshake timeout"),
|
||||||
|
warpAPIPhaseTLS,
|
||||||
|
).Error()
|
||||||
|
if !strings.Contains(tlsError, "тайм-аут TLS-рукопожатия") ||
|
||||||
|
!strings.Contains(tlsError, "после успешного TCP/443") {
|
||||||
|
t.Fatalf("TLS diagnosis = %q", tlsError)
|
||||||
|
}
|
||||||
|
|
||||||
|
headerError := warpAPINetworkError(
|
||||||
|
errors.New("net/http: timeout awaiting response headers"),
|
||||||
|
warpAPIPhaseResponse,
|
||||||
|
).Error()
|
||||||
|
if !strings.Contains(headerError, "HTTP-запрос отправлен") ||
|
||||||
|
!strings.Contains(headerError, "не прислал заголовки ответа") {
|
||||||
|
t.Fatalf("response diagnosis = %q", headerError)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWarpAPIRelayErrorKeepsRussianPhaseWithoutEndpoint(t *testing.T) {
|
||||||
|
got := warpAPIRelayNetworkError(
|
||||||
|
&url.Error{
|
||||||
|
Op: "Post",
|
||||||
|
URL: "https://api.cloudflareclient.com/private-device-path",
|
||||||
|
Err: errors.New("net/http: TLS handshake timeout"),
|
||||||
|
},
|
||||||
|
warpAPIPhaseTLS,
|
||||||
|
).Error()
|
||||||
|
if !strings.Contains(got, "через сервер профиля") ||
|
||||||
|
!strings.Contains(got, "TLS-рукопожатие") {
|
||||||
|
t.Fatalf("relay diagnosis = %q", got)
|
||||||
|
}
|
||||||
|
if strings.Contains(got, "private-device-path") || strings.Contains(got, "https://") {
|
||||||
|
t.Fatalf("relay diagnosis leaked request URL: %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWarpAPITraceDistinguishesSafePreWriteFailure(t *testing.T) {
|
||||||
|
requestTrace := newWarpAPIRequestTrace()
|
||||||
|
clientTrace := requestTrace.clientTrace()
|
||||||
|
clientTrace.TLSHandshakeStart()
|
||||||
|
phase, written := requestTrace.snapshot()
|
||||||
|
if phase != warpAPIPhaseTLS || written {
|
||||||
|
t.Fatalf("before write: phase=%q written=%v", phase, written)
|
||||||
|
}
|
||||||
|
if !warpAPICanRetryBeforeWrite(&net.DNSError{Err: "timeout", IsTimeout: true}) {
|
||||||
|
t.Fatal("pre-write network timeout must allow one safe retry")
|
||||||
|
}
|
||||||
|
|
||||||
|
clientTrace.WroteRequest(httptrace.WroteRequestInfo{})
|
||||||
|
phase, written = requestTrace.snapshot()
|
||||||
|
if phase != warpAPIPhaseResponse || !written {
|
||||||
|
t.Fatalf("after write: phase=%q written=%v", phase, written)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWarpAPIFragmentConnOnlyFragmentsFirstTLSClientHello(t *testing.T) {
|
||||||
|
underlying := &recordingConn{}
|
||||||
|
connection := &warpAPIFragmentConn{
|
||||||
|
Conn: underlying,
|
||||||
|
chunkSize: 8,
|
||||||
|
}
|
||||||
|
|
||||||
|
proxyConnect := []byte("CONNECT api.cloudflareclient.com:443 HTTP/1.1\r\n\r\n")
|
||||||
|
if written, err := connection.Write(proxyConnect); err != nil || written != len(proxyConnect) {
|
||||||
|
t.Fatalf("proxy CONNECT write = %d, %v", written, err)
|
||||||
|
}
|
||||||
|
if len(underlying.writes) != 1 {
|
||||||
|
t.Fatalf("plain proxy request writes = %d, want 1", len(underlying.writes))
|
||||||
|
}
|
||||||
|
|
||||||
|
clientHello := append([]byte{0x16, 0x03, 0x01, 0x00, 0x18, 0x01, 0x00, 0x00, 0x14}, make([]byte, 20)...)
|
||||||
|
if written, err := connection.Write(clientHello); err != nil || written != len(clientHello) {
|
||||||
|
t.Fatalf("ClientHello write = %d, %v", written, err)
|
||||||
|
}
|
||||||
|
if got := len(underlying.writes); got != 1+4 {
|
||||||
|
t.Fatalf("writes after fragmented ClientHello = %d, want 5", got)
|
||||||
|
}
|
||||||
|
if reconstructed := bytes.Join(underlying.writes[1:], nil); !bytes.Equal(reconstructed, clientHello) {
|
||||||
|
t.Fatalf("fragmented ClientHello changed: %x", reconstructed)
|
||||||
|
}
|
||||||
|
|
||||||
|
applicationData := []byte{0x17, 0x03, 0x03, 0x00, 0x03, 1, 2, 3}
|
||||||
|
if _, err := connection.Write(applicationData); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got := len(underlying.writes); got != 6 {
|
||||||
|
t.Fatalf("later TLS record was fragmented: writes=%d, want 6", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWarpHTTPClientsKeepCertificateVerificationAndIsolateFallback(t *testing.T) {
|
||||||
|
normalTransport, ok := newWarpHTTPClient(false).Transport.(*http.Transport)
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("normal WARP client does not use net/http transport")
|
||||||
|
}
|
||||||
|
if !normalTransport.ForceAttemptHTTP2 || normalTransport.TLSClientConfig != nil {
|
||||||
|
t.Fatalf("normal WARP client changed: HTTP/2=%v TLS=%#v", normalTransport.ForceAttemptHTTP2, normalTransport.TLSClientConfig)
|
||||||
|
}
|
||||||
|
|
||||||
|
fallbackTransport, ok := newWarpHTTPClient(true).Transport.(*http.Transport)
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("fallback WARP client does not use net/http transport")
|
||||||
|
}
|
||||||
|
tlsConfig := fallbackTransport.TLSClientConfig
|
||||||
|
if tlsConfig == nil {
|
||||||
|
t.Fatal("fallback TLS configuration is missing")
|
||||||
|
}
|
||||||
|
if tlsConfig.MinVersion != tls.VersionTLS12 || tlsConfig.MaxVersion != tls.VersionTLS12 {
|
||||||
|
t.Fatalf("fallback TLS range = %x..%x, want TLS 1.2 only", tlsConfig.MinVersion, tlsConfig.MaxVersion)
|
||||||
|
}
|
||||||
|
if fallbackTransport.ForceAttemptHTTP2 || !reflect.DeepEqual(tlsConfig.NextProtos, []string{"http/1.1"}) {
|
||||||
|
t.Fatalf("fallback HTTP protocol = HTTP/2:%v ALPN:%v", fallbackTransport.ForceAttemptHTTP2, tlsConfig.NextProtos)
|
||||||
|
}
|
||||||
|
if tlsConfig.InsecureSkipVerify || tlsConfig.RootCAs != nil {
|
||||||
|
t.Fatal("fallback must retain system roots and full certificate verification")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWarpAPIRelayAcceptsOnlyLoopbackAndKeepsEndToEndTLS(t *testing.T) {
|
||||||
|
if _, err := normalizeWarpAPIRelayAddress("192.0.2.1:443"); err == nil {
|
||||||
|
t.Fatal("non-loopback relay must be rejected")
|
||||||
|
}
|
||||||
|
address, err := normalizeWarpAPIRelayAddress("127.0.0.1:19443")
|
||||||
|
if err != nil || address != "127.0.0.1:19443" {
|
||||||
|
t.Fatalf("loopback relay = %q, %v", address, err)
|
||||||
|
}
|
||||||
|
client, err := newWarpRelayHTTPClient(address)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
transport, ok := client.Transport.(*http.Transport)
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("relay client does not use net/http transport")
|
||||||
|
}
|
||||||
|
if transport.Proxy != nil || transport.TLSClientConfig != nil || !transport.ForceAttemptHTTP2 {
|
||||||
|
t.Fatalf(
|
||||||
|
"relay changed HTTPS security: proxySet=%v TLS=%#v HTTP/2=%v",
|
||||||
|
transport.Proxy != nil,
|
||||||
|
transport.TLSClientConfig,
|
||||||
|
transport.ForceAttemptHTTP2,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWarpAPIRecognizesOnlyTLSPhaseTimeoutForFragmentedRetry(t *testing.T) {
|
||||||
|
tlsTimeout := errors.New("net/http: TLS handshake timeout")
|
||||||
|
if !warpAPIIsTLSHandshakeTimeout(tlsTimeout, warpAPIPhaseTLS) {
|
||||||
|
t.Fatal("TLS handshake timeout must select the fragmented fallback")
|
||||||
|
}
|
||||||
|
if warpAPIIsTLSHandshakeTimeout(tlsTimeout, warpAPIPhaseTCP) {
|
||||||
|
t.Fatal("TCP-phase timeout must not select the TLS fallback")
|
||||||
|
}
|
||||||
|
if warpAPIIsTLSHandshakeTimeout(&net.DNSError{Err: "timeout", IsTimeout: true}, warpAPIPhaseDNS) {
|
||||||
|
t.Fatal("DNS timeout must not select the TLS fallback")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWarpAPIRequestDiagnosesUnexpectedSuccessfulResponse(t *testing.T) {
|
||||||
|
for name, body := range map[string]string{
|
||||||
|
"empty": "",
|
||||||
|
"html": "<html>challenge</html>",
|
||||||
|
} {
|
||||||
|
t.Run(name, func(t *testing.T) {
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||||
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
_, _ = w.Write([]byte(body))
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
|
||||||
|
var out warpAccountData
|
||||||
|
err := warpAPIRequest(context.Background(), http.MethodPost, server.URL, "", struct{}{}, &out)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("unexpected response must fail")
|
||||||
|
}
|
||||||
|
message := err.Error()
|
||||||
|
if !strings.Contains(message, "HTTP 200") || !strings.Contains(message, "Content-Type=text/html") {
|
||||||
|
t.Fatalf("diagnosis lacks status or content type: %q", message)
|
||||||
|
}
|
||||||
|
if strings.Contains(message, body) && body != "" {
|
||||||
|
t.Fatalf("diagnosis leaked response body: %q", message)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTurnCandidateStagesAreIsolatedBehindMasque(t *testing.T) {
|
||||||
|
candidates := []turnEndpoint{
|
||||||
|
{Host: "turns.example", Port: "443", Transport: turnTransportTLS},
|
||||||
|
{Host: "turn.example", Port: "443", Transport: turnTransportTCP},
|
||||||
|
{Host: "turn.example", Port: "3478", Transport: turnTransportUDP},
|
||||||
|
}
|
||||||
|
|
||||||
|
direct, masque, finalUDP := turnCandidateStages(candidates, false)
|
||||||
|
if !reflect.DeepEqual(direct, candidates) || masque != nil || finalUDP != nil {
|
||||||
|
t.Fatalf("ordinary stages changed: direct=%v masque=%v udp=%v", direct, masque, finalUDP)
|
||||||
|
}
|
||||||
|
|
||||||
|
direct, masque, finalUDP = turnCandidateStages(candidates, true)
|
||||||
|
wantStream := candidates[:2]
|
||||||
|
wantUDP := candidates[2:]
|
||||||
|
if !reflect.DeepEqual(direct, wantStream) || !reflect.DeepEqual(masque, wantStream) || !reflect.DeepEqual(finalUDP, wantUDP) {
|
||||||
|
t.Fatalf("MASQUE stages = direct=%v masque=%v udp=%v", direct, masque, finalUDP)
|
||||||
|
}
|
||||||
|
}
|
||||||
+262
-16
@@ -3,7 +3,10 @@ package main
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
|
"crypto/x509"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
"log"
|
"log"
|
||||||
"net"
|
"net"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -64,12 +67,136 @@ type connectedUDPConn struct{ *net.UDPConn }
|
|||||||
|
|
||||||
func (c *connectedUDPConn) WriteTo(p []byte, _ net.Addr) (int, error) { return c.Write(p) }
|
func (c *connectedUDPConn) WriteTo(p []byte, _ net.Addr) (int, error) { return c.Write(p) }
|
||||||
|
|
||||||
|
// splitFirstWriteConn fragments the first STUN request so its magic cookie
|
||||||
|
// crosses TCP segment boundaries. Some shallow DPI rules classify plain TURN
|
||||||
|
// by looking only at the first segment. This wrapper is enabled exclusively by
|
||||||
|
// the explicit «Сеть РТ» mode; ordinary operators keep the original writes.
|
||||||
|
type splitFirstWriteConn struct {
|
||||||
|
net.Conn
|
||||||
|
splitAt int
|
||||||
|
delay time.Duration
|
||||||
|
done atomic.Bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeFull(conn net.Conn, payload []byte) (int, error) {
|
||||||
|
total := 0
|
||||||
|
for len(payload) > 0 {
|
||||||
|
n, err := conn.Write(payload)
|
||||||
|
total += n
|
||||||
|
payload = payload[n:]
|
||||||
|
if err != nil {
|
||||||
|
return total, err
|
||||||
|
}
|
||||||
|
if n == 0 {
|
||||||
|
return total, io.ErrShortWrite
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return total, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (conn *splitFirstWriteConn) Write(payload []byte) (int, error) {
|
||||||
|
if !conn.done.CompareAndSwap(false, true) || len(payload) <= conn.splitAt {
|
||||||
|
return conn.Conn.Write(payload)
|
||||||
|
}
|
||||||
|
first, err := writeFull(conn.Conn, payload[:conn.splitAt])
|
||||||
|
if err != nil {
|
||||||
|
return first, err
|
||||||
|
}
|
||||||
|
if conn.delay > 0 {
|
||||||
|
time.Sleep(conn.delay)
|
||||||
|
}
|
||||||
|
second, err := writeFull(conn.Conn, payload[conn.splitAt:])
|
||||||
|
return first + second, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizeTURNFrontSNI(value string) (string, error) {
|
||||||
|
host := strings.ToLower(strings.TrimSpace(value))
|
||||||
|
if host == "" {
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
if len(host) > 253 || net.ParseIP(host) != nil || strings.HasPrefix(host, ".") ||
|
||||||
|
strings.HasSuffix(host, ".") || strings.Contains(host, "..") {
|
||||||
|
return "", fmt.Errorf("ожидалось доменное имя длиной до 253 символов")
|
||||||
|
}
|
||||||
|
labels := strings.Split(host, ".")
|
||||||
|
if len(labels) < 2 {
|
||||||
|
return "", fmt.Errorf("ожидалось доменное имя как ya.ru")
|
||||||
|
}
|
||||||
|
for _, label := range labels {
|
||||||
|
if label == "" || len(label) > 63 || label[0] == '-' || label[len(label)-1] == '-' {
|
||||||
|
return "", fmt.Errorf("некорректная метка домена")
|
||||||
|
}
|
||||||
|
for _, ch := range label {
|
||||||
|
if (ch < 'a' || ch > 'z') && (ch < '0' || ch > '9') && ch != '-' {
|
||||||
|
return "", fmt.Errorf("разрешены только латинские буквы, цифры, дефис и точки")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return host, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func verifyTURNCertificateChainWithoutHostname(state tls.ConnectionState) error {
|
||||||
|
if len(state.PeerCertificates) == 0 {
|
||||||
|
return fmt.Errorf("TURN TLS не прислал сертификат")
|
||||||
|
}
|
||||||
|
intermediates := x509.NewCertPool()
|
||||||
|
for _, cert := range state.PeerCertificates[1:] {
|
||||||
|
intermediates.AddCert(cert)
|
||||||
|
}
|
||||||
|
_, err := state.PeerCertificates[0].Verify(x509.VerifyOptions{
|
||||||
|
Intermediates: intermediates,
|
||||||
|
KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("проверка цепочки сертификата TURN TLS: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func turnTLSConfig(endpoint turnEndpoint, frontSNI string) *tls.Config {
|
||||||
|
config := &tls.Config{MinVersion: tls.VersionTLS12}
|
||||||
|
serverName := endpoint.Host
|
||||||
|
if frontSNI != "" {
|
||||||
|
serverName = frontSNI
|
||||||
|
}
|
||||||
|
if net.ParseIP(serverName) == nil {
|
||||||
|
config.ServerName = serverName
|
||||||
|
}
|
||||||
|
|
||||||
|
// При подмене SNI имя сертификата ожидаемо относится к TURN-узлу, а не к
|
||||||
|
// домену белого списка. Отключаем только сопоставление имени: публичная CA-
|
||||||
|
// цепочка всё равно проверяется в VerifyConnection.
|
||||||
|
if frontSNI != "" && !strings.EqualFold(frontSNI, endpoint.Host) {
|
||||||
|
config.InsecureSkipVerify = true // проверка перенесена в VerifyConnection
|
||||||
|
config.VerifyConnection = verifyTURNCertificateChainWithoutHostname
|
||||||
|
}
|
||||||
|
return config
|
||||||
|
}
|
||||||
|
|
||||||
|
func turnPathSNI(endpoint turnEndpoint, frontSNI string, rtMode bool) string {
|
||||||
|
if endpoint.Transport != turnTransportTLS {
|
||||||
|
if endpoint.Transport == turnTransportTCP && rtMode {
|
||||||
|
return "SNI не применяется, первый STUN-запрос разделён для DPI"
|
||||||
|
}
|
||||||
|
return "SNI не применяется"
|
||||||
|
}
|
||||||
|
if frontSNI != "" {
|
||||||
|
return "SNI=" + frontSNI
|
||||||
|
}
|
||||||
|
if net.ParseIP(endpoint.Host) == nil {
|
||||||
|
return "SNI=" + endpoint.Host
|
||||||
|
}
|
||||||
|
return "без SNI"
|
||||||
|
}
|
||||||
|
|
||||||
func openTURNAllocation(
|
func openTURNAllocation(
|
||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
endpoint turnEndpoint,
|
endpoint turnEndpoint,
|
||||||
peer *net.UDPAddr,
|
peer *net.UDPAddr,
|
||||||
creds *Credentials,
|
creds *Credentials,
|
||||||
sessionID int,
|
sessionID int,
|
||||||
|
frontSNI string,
|
||||||
|
splitTCPFirstWrite bool,
|
||||||
) (*turn.Client, net.PacketConn, error) {
|
) (*turn.Client, net.PacketConn, error) {
|
||||||
turnAddr := endpoint.address()
|
turnAddr := endpoint.address()
|
||||||
|
|
||||||
@@ -91,21 +218,21 @@ func openTURNAllocation(
|
|||||||
dialCtx, cancel := context.WithTimeout(ctx, 6*time.Second)
|
dialCtx, cancel := context.WithTimeout(ctx, 6*time.Second)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
dialer := &net.Dialer{Timeout: 6 * time.Second, KeepAlive: 30 * time.Second}
|
dialer := &net.Dialer{Timeout: 6 * time.Second, KeepAlive: 30 * time.Second}
|
||||||
conn, err := dialer.DialContext(dialCtx, "tcp", turnAddr)
|
rawConn, err := dialer.DialContext(dialCtx, "tcp", turnAddr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, nil, fmt.Errorf("TURN TCP подключение %s: %w", turnAddr, err)
|
return nil, nil, fmt.Errorf("TURN TCP подключение %s: %w", turnAddr, err)
|
||||||
}
|
}
|
||||||
|
var conn net.Conn = rawConn
|
||||||
|
if splitTCPFirstWrite {
|
||||||
|
conn = &splitFirstWriteConn{Conn: rawConn, splitAt: 6, delay: 20 * time.Millisecond}
|
||||||
|
}
|
||||||
turnConn = turn.NewSTUNConn(conn)
|
turnConn = turn.NewSTUNConn(conn)
|
||||||
case turnTransportTLS:
|
case turnTransportTLS:
|
||||||
dialCtx, cancel := context.WithTimeout(ctx, 8*time.Second)
|
dialCtx, cancel := context.WithTimeout(ctx, 8*time.Second)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
tlsConfig := &tls.Config{MinVersion: tls.VersionTLS12}
|
|
||||||
if net.ParseIP(endpoint.Host) == nil {
|
|
||||||
tlsConfig.ServerName = endpoint.Host
|
|
||||||
}
|
|
||||||
dialer := &tls.Dialer{
|
dialer := &tls.Dialer{
|
||||||
NetDialer: &net.Dialer{Timeout: 8 * time.Second, KeepAlive: 30 * time.Second},
|
NetDialer: &net.Dialer{Timeout: 8 * time.Second, KeepAlive: 30 * time.Second},
|
||||||
Config: tlsConfig,
|
Config: turnTLSConfig(endpoint, frontSNI),
|
||||||
}
|
}
|
||||||
conn, err := dialer.DialContext(dialCtx, "tcp", turnAddr)
|
conn, err := dialer.DialContext(dialCtx, "tcp", turnAddr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -116,6 +243,17 @@ func openTURNAllocation(
|
|||||||
return nil, nil, fmt.Errorf("неподдерживаемый TURN transport: %s", endpoint.Transport)
|
return nil, nil, fmt.Errorf("неподдерживаемый TURN transport: %s", endpoint.Transport)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return allocateTURNOnConn(endpoint, peer, creds, turnConn)
|
||||||
|
}
|
||||||
|
|
||||||
|
func allocateTURNOnConn(
|
||||||
|
endpoint turnEndpoint,
|
||||||
|
peer *net.UDPAddr,
|
||||||
|
creds *Credentials,
|
||||||
|
turnConn net.PacketConn,
|
||||||
|
) (*turn.Client, net.PacketConn, error) {
|
||||||
|
turnAddr := endpoint.address()
|
||||||
|
|
||||||
// RequestedAddressFamily
|
// RequestedAddressFamily
|
||||||
var addrFamily turn.RequestedAddressFamily
|
var addrFamily turn.RequestedAddressFamily
|
||||||
if peer.IP.To4() != nil {
|
if peer.IP.To4() != nil {
|
||||||
@@ -146,7 +284,7 @@ func openTURNAllocation(
|
|||||||
relay, err := tc.Allocate()
|
relay, err := tc.Allocate()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if isAuthError(err) {
|
if isAuthError(err) {
|
||||||
handleAuthError(creds.CacheStreamID)
|
handleAuthError(creds.CacheStreamID, creds.User, creds.Pass)
|
||||||
}
|
}
|
||||||
errStr := err.Error()
|
errStr := err.Error()
|
||||||
if strings.Contains(errStr, "Quota") || strings.Contains(errStr, "486") {
|
if strings.Contains(errStr, "Quota") || strings.Contains(errStr, "486") {
|
||||||
@@ -160,21 +298,78 @@ func openTURNAllocation(
|
|||||||
return tc, relay, nil
|
return tc, relay, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func openTURNAllocationOverMasque(
|
||||||
|
ctx context.Context,
|
||||||
|
endpoint turnEndpoint,
|
||||||
|
peer *net.UDPAddr,
|
||||||
|
creds *Credentials,
|
||||||
|
manager *warpMasqueManager,
|
||||||
|
protocol warpMasqueProtocol,
|
||||||
|
) (*turn.Client, net.PacketConn, error) {
|
||||||
|
if endpoint.Transport == turnTransportUDP {
|
||||||
|
return nil, nil, errors.New("TURN/UDP нельзя передать через TCP-поток CONNECT-IP")
|
||||||
|
}
|
||||||
|
|
||||||
|
rawConn, err := manager.dialProtocol(ctx, endpoint.address(), protocol)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, fmt.Errorf("MASQUE %s к %s: %w", protocol, endpoint.address(), err)
|
||||||
|
}
|
||||||
|
var conn net.Conn = rawConn
|
||||||
|
if endpoint.Transport == turnTransportTLS {
|
||||||
|
tlsConn := tls.Client(rawConn, turnTLSConfig(endpoint, ""))
|
||||||
|
handshakeCtx, cancel := context.WithTimeout(ctx, 8*time.Second)
|
||||||
|
err = tlsConn.HandshakeContext(handshakeCtx)
|
||||||
|
cancel()
|
||||||
|
if err != nil {
|
||||||
|
_ = rawConn.Close()
|
||||||
|
return nil, nil, fmt.Errorf("TURN TLS внутри MASQUE %s к %s: %w", protocol, endpoint.address(), err)
|
||||||
|
}
|
||||||
|
conn = tlsConn
|
||||||
|
}
|
||||||
|
|
||||||
|
return allocateTURNOnConn(endpoint, peer, creds, turn.NewSTUNConn(conn))
|
||||||
|
}
|
||||||
|
|
||||||
func isCredentialTURNError(err error) bool {
|
func isCredentialTURNError(err error) bool {
|
||||||
if err == nil {
|
if err == nil {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
text := strings.ToLower(err.Error())
|
text := strings.ToLower(err.Error())
|
||||||
return strings.Contains(text, "turn квота") ||
|
return strings.Contains(text, "turn allocate auth") ||
|
||||||
strings.Contains(text, "turn allocate auth") ||
|
strings.Contains(text, "unauthorized") ||
|
||||||
|
strings.Contains(text, "authentication") ||
|
||||||
|
strings.Contains(text, "error 401") ||
|
||||||
strings.Contains(text, "invalid credential") ||
|
strings.Contains(text, "invalid credential") ||
|
||||||
strings.Contains(text, "stale nonce") ||
|
strings.Contains(text, "stale nonce") ||
|
||||||
strings.Contains(text, "allocation mismatch") ||
|
strings.Contains(text, "allocation mismatch") ||
|
||||||
strings.Contains(text, "attribute not found") ||
|
strings.Contains(text, "attribute not found")
|
||||||
|
}
|
||||||
|
|
||||||
|
func isTURNCapacityError(err error) bool {
|
||||||
|
if err == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
text := strings.ToLower(err.Error())
|
||||||
|
return strings.Contains(text, "turn квота") ||
|
||||||
strings.Contains(text, "error 508") ||
|
strings.Contains(text, "error 508") ||
|
||||||
strings.Contains(text, "quota")
|
strings.Contains(text, "quota")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func turnCandidateStages(candidates []turnEndpoint, useMasque bool) (direct, masque, finalUDP []turnEndpoint) {
|
||||||
|
if !useMasque {
|
||||||
|
return candidates, nil, nil
|
||||||
|
}
|
||||||
|
for _, candidate := range candidates {
|
||||||
|
if candidate.Transport == turnTransportUDP {
|
||||||
|
finalUDP = append(finalUDP, candidate)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
direct = append(direct, candidate)
|
||||||
|
masque = append(masque, candidate)
|
||||||
|
}
|
||||||
|
return direct, masque, finalUDP
|
||||||
|
}
|
||||||
|
|
||||||
func RunSession(
|
func RunSession(
|
||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
tp *TurnParams,
|
tp *TurnParams,
|
||||||
@@ -189,30 +384,42 @@ func RunSession(
|
|||||||
creds *Credentials,
|
creds *Credentials,
|
||||||
deviceID, password, deviceInfo, transportSession string,
|
deviceID, password, deviceInfo, transportSession string,
|
||||||
stats *Stats,
|
stats *Stats,
|
||||||
|
preferTURNStream bool,
|
||||||
) (bool, error) {
|
) (bool, error) {
|
||||||
configDelivered := false
|
configDelivered := false
|
||||||
|
|
||||||
if len(creds.TurnURLs) == 0 {
|
if len(creds.TurnURLs) == 0 {
|
||||||
return false, fmt.Errorf("нет TURN URL в учетных данных")
|
return false, fmt.Errorf("нет TURN URL в учетных данных")
|
||||||
}
|
}
|
||||||
candidates := sessionTURNCandidates(creds.TurnURLs, sessionID, tp)
|
candidates := sessionTURNCandidatesWithPreference(
|
||||||
|
creds.TurnURLs,
|
||||||
|
sessionID,
|
||||||
|
tp,
|
||||||
|
preferTURNStream,
|
||||||
|
)
|
||||||
if len(candidates) == 0 {
|
if len(candidates) == 0 {
|
||||||
return false, fmt.Errorf("нет пригодных TURN URL в учетных данных")
|
return false, fmt.Errorf("нет пригодных TURN URL в учетных данных")
|
||||||
}
|
}
|
||||||
|
directCandidates, masqueCandidates, finalUDPCandidates := turnCandidateStages(candidates, tp.Masque != nil)
|
||||||
|
|
||||||
var tc *turn.Client
|
var tc *turn.Client
|
||||||
var relay net.PacketConn
|
var relay net.PacketConn
|
||||||
var selectedEndpoint turnEndpoint
|
var selectedEndpoint turnEndpoint
|
||||||
|
var selectedMasqueProtocol warpMasqueProtocol
|
||||||
var lastTURNErr error
|
var lastTURNErr error
|
||||||
var err error
|
var err error
|
||||||
for idx, candidate := range candidates {
|
for idx, candidate := range directCandidates {
|
||||||
if idx == 0 {
|
if !preferTURNStream && idx == 0 {
|
||||||
log.Printf("[СЕССИЯ #%d] TURN %s (%s)", sessionID, candidate.label(), candidate.address())
|
log.Printf("[СЕССИЯ #%d] TURN %s (%s)", sessionID, candidate.label(), candidate.address())
|
||||||
} else {
|
} else if !preferTURNStream {
|
||||||
log.Printf("[СЕССИЯ #%d] [TURN] Резервный путь %s (%s) после ошибки: %v", sessionID, candidate.label(), candidate.address(), lastTURNErr)
|
log.Printf("[СЕССИЯ #%d] [TURN] Резервный путь %s (%s) после ошибки: %v", sessionID, candidate.label(), candidate.address(), lastTURNErr)
|
||||||
|
} else if idx == 0 {
|
||||||
|
log.Printf("[СЕССИЯ #%d] [TURN] Путь %s (%s), %s", sessionID, candidate.label(), candidate.address(), turnPathSNI(candidate, tp.TLSFrontSNI, preferTURNStream))
|
||||||
|
} else {
|
||||||
|
log.Printf("[СЕССИЯ #%d] [TURN] Резервный путь %s (%s), %s, после ошибки: %v", sessionID, candidate.label(), candidate.address(), turnPathSNI(candidate, tp.TLSFrontSNI, preferTURNStream), lastTURNErr)
|
||||||
}
|
}
|
||||||
|
|
||||||
tc, relay, err = openTURNAllocation(ctx, candidate, peer, creds, sessionID)
|
tc, relay, err = openTURNAllocation(ctx, candidate, peer, creds, sessionID, tp.TLSFrontSNI, preferTURNStream)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
selectedEndpoint = candidate
|
selectedEndpoint = candidate
|
||||||
break
|
break
|
||||||
@@ -222,6 +429,41 @@ func RunSession(
|
|||||||
return false, err
|
return false, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if relay == nil && tp.Masque != nil {
|
||||||
|
log.Printf("[СЕССИЯ #%d] [MASQUE] Прямые TCP/TLS-пути «Сети РТ» не сработали; до UDP пробуем WARP CONNECT-IP: %v", sessionID, lastTURNErr)
|
||||||
|
masqueProtocols:
|
||||||
|
for _, protocol := range tp.Masque.protocolOrder() {
|
||||||
|
for _, candidate := range masqueCandidates {
|
||||||
|
log.Printf("[СЕССИЯ #%d] [MASQUE] Пробуем TURN %s (%s) внутри CONNECT-IP %s", sessionID, candidate.label(), candidate.address(), protocol)
|
||||||
|
tc, relay, err = openTURNAllocationOverMasque(ctx, candidate, peer, creds, tp.Masque, protocol)
|
||||||
|
if err == nil {
|
||||||
|
selectedEndpoint = candidate
|
||||||
|
selectedMasqueProtocol = protocol
|
||||||
|
tp.Masque.markPreferred(protocol)
|
||||||
|
break masqueProtocols
|
||||||
|
}
|
||||||
|
lastTURNErr = err
|
||||||
|
log.Printf("[СЕССИЯ #%d] [MASQUE] %s через %s не сработал: %v", sessionID, candidate.label(), protocol, err)
|
||||||
|
if isCredentialTURNError(err) {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if relay == nil && tp.Masque != nil {
|
||||||
|
for _, candidate := range finalUDPCandidates {
|
||||||
|
log.Printf("[СЕССИЯ #%d] [TURN] Последний резерв после MASQUE: %s (%s), после ошибки: %v", sessionID, candidate.label(), candidate.address(), lastTURNErr)
|
||||||
|
tc, relay, err = openTURNAllocation(ctx, candidate, peer, creds, sessionID, tp.TLSFrontSNI, preferTURNStream)
|
||||||
|
if err == nil {
|
||||||
|
selectedEndpoint = candidate
|
||||||
|
break
|
||||||
|
}
|
||||||
|
lastTURNErr = err
|
||||||
|
if isCredentialTURNError(err) {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
if lastTURNErr != nil && relay == nil {
|
if lastTURNErr != nil && relay == nil {
|
||||||
return false, lastTURNErr
|
return false, lastTURNErr
|
||||||
}
|
}
|
||||||
@@ -231,7 +473,11 @@ func RunSession(
|
|||||||
// Reset error count on successful allocation
|
// Reset error count on successful allocation
|
||||||
getStreamCache(creds.CacheStreamID).errorCount.Store(0)
|
getStreamCache(creds.CacheStreamID).errorCount.Store(0)
|
||||||
|
|
||||||
log.Printf("[СЕССИЯ #%d] Relay: %s через TURN %s", sessionID, relay.LocalAddr(), selectedEndpoint.label())
|
if selectedMasqueProtocol != "" {
|
||||||
|
log.Printf("[СЕССИЯ #%d] Relay: %s через TURN %s внутри MASQUE %s ✓", sessionID, relay.LocalAddr(), selectedEndpoint.label(), selectedMasqueProtocol)
|
||||||
|
} else {
|
||||||
|
log.Printf("[СЕССИЯ #%d] Relay: %s через TURN %s", sessionID, relay.LocalAddr(), selectedEndpoint.label())
|
||||||
|
}
|
||||||
|
|
||||||
// Pipe для DTLS ↔ TURN relay
|
// Pipe для DTLS ↔ TURN relay
|
||||||
pipeA, pipeB := connutil.AsyncPacketPipe()
|
pipeA, pipeB := connutil.AsyncPacketPipe()
|
||||||
|
|||||||
@@ -0,0 +1,96 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type recordingConn struct {
|
||||||
|
writes [][]byte
|
||||||
|
}
|
||||||
|
|
||||||
|
func (conn *recordingConn) Read(_ []byte) (int, error) { return 0, nil }
|
||||||
|
func (conn *recordingConn) Close() error { return nil }
|
||||||
|
func (conn *recordingConn) LocalAddr() net.Addr { return nil }
|
||||||
|
func (conn *recordingConn) RemoteAddr() net.Addr { return nil }
|
||||||
|
func (conn *recordingConn) SetDeadline(_ time.Time) error { return nil }
|
||||||
|
func (conn *recordingConn) SetReadDeadline(_ time.Time) error { return nil }
|
||||||
|
func (conn *recordingConn) SetWriteDeadline(_ time.Time) error { return nil }
|
||||||
|
|
||||||
|
func (conn *recordingConn) Write(payload []byte) (int, error) {
|
||||||
|
copyOfPayload := append([]byte(nil), payload...)
|
||||||
|
conn.writes = append(conn.writes, copyOfPayload)
|
||||||
|
return len(payload), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNormalizeTURNFrontSNI(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
input string
|
||||||
|
want string
|
||||||
|
ok bool
|
||||||
|
}{
|
||||||
|
{input: " Ya.RU ", want: "ya.ru", ok: true},
|
||||||
|
{input: "telemost.yandex.ru", want: "telemost.yandex.ru", ok: true},
|
||||||
|
{input: "", want: "", ok: true},
|
||||||
|
{input: "ya", ok: false},
|
||||||
|
{input: "127.0.0.1", ok: false},
|
||||||
|
{input: "я.рф", ok: false},
|
||||||
|
{input: "-ya.ru", ok: false},
|
||||||
|
{input: "ya..ru", ok: false},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.input, func(t *testing.T) {
|
||||||
|
got, err := normalizeTURNFrontSNI(tt.input)
|
||||||
|
if (err == nil) != tt.ok {
|
||||||
|
t.Fatalf("normalizeTURNFrontSNI(%q) error=%v", tt.input, err)
|
||||||
|
}
|
||||||
|
if got != tt.want {
|
||||||
|
t.Fatalf("normalizeTURNFrontSNI(%q)=%q, want %q", tt.input, got, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTurnTLSConfigUsesFrontSNIWithoutDisablingChainCheck(t *testing.T) {
|
||||||
|
endpoint := turnEndpoint{Host: "turn.example", Port: "443", Transport: turnTransportTLS}
|
||||||
|
config := turnTLSConfig(endpoint, "ya.ru")
|
||||||
|
if config.ServerName != "ya.ru" {
|
||||||
|
t.Fatalf("ServerName=%q, want ya.ru", config.ServerName)
|
||||||
|
}
|
||||||
|
if !config.InsecureSkipVerify || config.VerifyConnection == nil {
|
||||||
|
t.Fatal("front SNI must replace hostname matching with explicit CA-chain verification")
|
||||||
|
}
|
||||||
|
|
||||||
|
normal := turnTLSConfig(endpoint, "")
|
||||||
|
if normal.ServerName != "turn.example" || normal.InsecureSkipVerify || normal.VerifyConnection != nil {
|
||||||
|
t.Fatalf("normal TLS verification changed unexpectedly: %#v", normal)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSplitFirstWriteConnOnlySplitsFirstWrite(t *testing.T) {
|
||||||
|
underlying := &recordingConn{}
|
||||||
|
conn := &splitFirstWriteConn{Conn: underlying, splitAt: 6}
|
||||||
|
|
||||||
|
first := []byte("0123456789")
|
||||||
|
if n, err := conn.Write(first); err != nil || n != len(first) {
|
||||||
|
t.Fatalf("first Write() = (%d, %v), want (%d, nil)", n, err, len(first))
|
||||||
|
}
|
||||||
|
second := []byte("abcdef")
|
||||||
|
if n, err := conn.Write(second); err != nil || n != len(second) {
|
||||||
|
t.Fatalf("second Write() = (%d, %v), want (%d, nil)", n, err, len(second))
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(underlying.writes) != 3 {
|
||||||
|
t.Fatalf("underlying writes=%q, want three writes", underlying.writes)
|
||||||
|
}
|
||||||
|
if got := string(underlying.writes[0]); got != "012345" {
|
||||||
|
t.Fatalf("first fragment=%q, want %q", got, "012345")
|
||||||
|
}
|
||||||
|
if got := string(underlying.writes[1]); got != "6789" {
|
||||||
|
t.Fatalf("second fragment=%q, want %q", got, "6789")
|
||||||
|
}
|
||||||
|
if got := string(underlying.writes[2]); got != "abcdef" {
|
||||||
|
t.Fatalf("subsequent write=%q, want %q", got, "abcdef")
|
||||||
|
}
|
||||||
|
}
|
||||||
+76
-15
@@ -90,6 +90,19 @@ func legacyUDPEndpoint(raw string) (turnEndpoint, error) {
|
|||||||
return endpoint, nil
|
return endpoint, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// legacyTCPEndpoint preserves the behaviour of the original vk-turn-proxy
|
||||||
|
// client: VK may advertise an address as UDP even though the same TURN
|
||||||
|
// listener also accepts a TCP control connection.
|
||||||
|
func legacyTCPEndpoint(raw string) (turnEndpoint, error) {
|
||||||
|
endpoint, err := parseTURNEndpoint(raw)
|
||||||
|
if err != nil {
|
||||||
|
return turnEndpoint{}, err
|
||||||
|
}
|
||||||
|
endpoint.Transport = turnTransportTCP
|
||||||
|
endpoint.LegacyUDP = false
|
||||||
|
return endpoint, nil
|
||||||
|
}
|
||||||
|
|
||||||
func splitTURNHostPort(address string, transport turnTransport) (string, string, error) {
|
func splitTURNHostPort(address string, transport turnTransport) (string, string, error) {
|
||||||
host, port, err := net.SplitHostPort(address)
|
host, port, err := net.SplitHostPort(address)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
@@ -135,6 +148,19 @@ func (e turnEndpoint) label() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func sessionTURNCandidates(rawURLs []string, sessionID int, tp *TurnParams) []turnEndpoint {
|
func sessionTURNCandidates(rawURLs []string, sessionID int, tp *TurnParams) []turnEndpoint {
|
||||||
|
return sessionTURNCandidatesWithPreference(rawURLs, sessionID, tp, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
// sessionTURNCandidatesWithPreference keeps the historical UDP-first order
|
||||||
|
// unless the user explicitly enables the restricted-network mode. That mode
|
||||||
|
// prefers stream transports so a mobile network that silently drops relayed
|
||||||
|
// UDP is not retried forever.
|
||||||
|
func sessionTURNCandidatesWithPreference(
|
||||||
|
rawURLs []string,
|
||||||
|
sessionID int,
|
||||||
|
tp *TurnParams,
|
||||||
|
preferStream bool,
|
||||||
|
) []turnEndpoint {
|
||||||
if len(rawURLs) == 0 {
|
if len(rawURLs) == 0 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -165,27 +191,62 @@ func sessionTURNCandidates(rawURLs []string, sessionID int, tp *TurnParams) []tu
|
|||||||
result = append(result, endpoint)
|
result = append(result, endpoint)
|
||||||
}
|
}
|
||||||
|
|
||||||
if endpoint, err := legacyUDPEndpoint(rawURLs[selectedIndex]); err == nil {
|
addLegacyUDP := func() {
|
||||||
add(endpoint)
|
if endpoint, err := legacyUDPEndpoint(rawURLs[selectedIndex]); err == nil {
|
||||||
}
|
|
||||||
|
|
||||||
for offset := 1; offset < len(rawURLs); offset++ {
|
|
||||||
idx := (selectedIndex + offset) % len(rawURLs)
|
|
||||||
if endpoint, err := legacyUDPEndpoint(rawURLs[idx]); err == nil {
|
|
||||||
add(endpoint)
|
add(endpoint)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
for offset := 1; offset < len(rawURLs); offset++ {
|
||||||
|
idx := (selectedIndex + offset) % len(rawURLs)
|
||||||
|
if endpoint, err := legacyUDPEndpoint(rawURLs[idx]); err == nil {
|
||||||
|
add(endpoint)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for offset := 0; offset < len(rawURLs); offset++ {
|
addStreamCandidates := func(tlsFirst bool) {
|
||||||
idx := (selectedIndex + offset) % len(rawURLs)
|
if !tlsFirst {
|
||||||
endpoint, err := parseTURNEndpoint(rawURLs[idx])
|
for offset := 0; offset < len(rawURLs); offset++ {
|
||||||
if err != nil {
|
idx := (selectedIndex + offset) % len(rawURLs)
|
||||||
continue
|
endpoint, err := parseTURNEndpoint(rawURLs[idx])
|
||||||
|
if err != nil || endpoint.Transport == turnTransportUDP {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
add(endpoint)
|
||||||
|
}
|
||||||
|
return
|
||||||
}
|
}
|
||||||
if endpoint.Transport == turnTransportUDP {
|
|
||||||
continue
|
// A restricted allow-list is most likely to accept the TLS endpoint:
|
||||||
|
// it uses the real TURN hostname supplied by VK as outer SNI.
|
||||||
|
for _, transport := range []turnTransport{turnTransportTLS, turnTransportTCP} {
|
||||||
|
for offset := 0; offset < len(rawURLs); offset++ {
|
||||||
|
idx := (selectedIndex + offset) % len(rawURLs)
|
||||||
|
endpoint, err := parseTURNEndpoint(rawURLs[idx])
|
||||||
|
if err != nil || endpoint.Transport != transport {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
add(endpoint)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
add(endpoint)
|
|
||||||
|
// The upstream vk-turn-proxy uses TCP to the selected TURN address even
|
||||||
|
// when VK marks that URL as transport=udp. Keep this compatibility path
|
||||||
|
// behind stream preference so the normal UDP-first mode is untouched.
|
||||||
|
for offset := 0; offset < len(rawURLs); offset++ {
|
||||||
|
idx := (selectedIndex + offset) % len(rawURLs)
|
||||||
|
if endpoint, err := legacyTCPEndpoint(rawURLs[idx]); err == nil {
|
||||||
|
add(endpoint)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if preferStream {
|
||||||
|
addStreamCandidates(true)
|
||||||
|
addLegacyUDP()
|
||||||
|
} else {
|
||||||
|
addLegacyUDP()
|
||||||
|
addStreamCandidates(false)
|
||||||
}
|
}
|
||||||
|
|
||||||
return result
|
return result
|
||||||
|
|||||||
@@ -32,24 +32,78 @@ func TestSessionTURNCandidatesKeepLegacyUDPFirst(t *testing.T) {
|
|||||||
"turn:turn.example:3478?transport=tcp",
|
"turn:turn.example:3478?transport=tcp",
|
||||||
}
|
}
|
||||||
got := sessionTURNCandidates(raw, 0, nil)
|
got := sessionTURNCandidates(raw, 0, nil)
|
||||||
|
want := []struct {
|
||||||
|
host string
|
||||||
|
port string
|
||||||
|
transport turnTransport
|
||||||
|
legacyUDP bool
|
||||||
|
}{
|
||||||
|
{"turn.example", "443", turnTransportUDP, true},
|
||||||
|
{"1.2.3.4", "3478", turnTransportUDP, true},
|
||||||
|
{"turn.example", "3478", turnTransportUDP, true},
|
||||||
|
{"turn.example", "443", turnTransportTLS, false},
|
||||||
|
{"turn.example", "3478", turnTransportTCP, false},
|
||||||
|
}
|
||||||
|
if len(got) != len(want) {
|
||||||
|
t.Fatalf("normal-mode candidates=%#v, want %d entries", got, len(want))
|
||||||
|
}
|
||||||
|
for index, expected := range want {
|
||||||
|
actual := got[index]
|
||||||
|
if actual.Host != expected.host || actual.Port != expected.port ||
|
||||||
|
actual.Transport != expected.transport || actual.LegacyUDP != expected.legacyUDP {
|
||||||
|
t.Fatalf("normal-mode candidate[%d]=%#v, want %#v", index, actual, expected)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSessionTURNCandidatesPreferStreamForRtMode(t *testing.T) {
|
||||||
|
raw := []string{
|
||||||
|
"turn:turn.example:443?transport=tcp",
|
||||||
|
"turn:1.2.3.4:3478?transport=udp",
|
||||||
|
"turns:turn.example:443?transport=tcp",
|
||||||
|
}
|
||||||
|
got := sessionTURNCandidatesWithPreference(raw, 0, nil, true)
|
||||||
if len(got) < 3 {
|
if len(got) < 3 {
|
||||||
t.Fatalf("not enough candidates: %#v", got)
|
t.Fatalf("not enough candidates: %#v", got)
|
||||||
}
|
}
|
||||||
if got[0].Transport != turnTransportUDP || !got[0].LegacyUDP || got[0].Host != "turn.example" || got[0].Port != "443" {
|
if got[0].Transport != turnTransportTLS || got[0].LegacyUDP {
|
||||||
t.Fatalf("first candidate must preserve old UDP behavior, got %#v", got[0])
|
t.Fatalf("first candidate must be the real TLS transport, got %#v", got[0])
|
||||||
}
|
}
|
||||||
foundTLS := false
|
if got[1].Transport != turnTransportTCP || got[1].LegacyUDP {
|
||||||
foundTCP := false
|
t.Fatalf("second candidate must be the real TCP transport, got %#v", got[1])
|
||||||
for _, endpoint := range got[1:] {
|
|
||||||
if endpoint.Transport == turnTransportTLS {
|
|
||||||
foundTLS = true
|
|
||||||
}
|
|
||||||
if endpoint.Transport == turnTransportTCP {
|
|
||||||
foundTCP = true
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if !foundTLS || !foundTCP {
|
if got[len(got)-1].Transport != turnTransportUDP || !got[len(got)-1].LegacyUDP {
|
||||||
t.Fatalf("expected TCP/TLS fallbacks, got %#v", got)
|
t.Fatalf("legacy UDP candidates must remain as a final fallback, got %#v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSessionTURNCandidatesPreferStreamSynthesizesTCPFromUDPURL(t *testing.T) {
|
||||||
|
got := sessionTURNCandidatesWithPreference(
|
||||||
|
[]string{"turn:1.2.3.4:3478?transport=udp"},
|
||||||
|
0,
|
||||||
|
nil,
|
||||||
|
true,
|
||||||
|
)
|
||||||
|
if len(got) != 2 {
|
||||||
|
t.Fatalf("expected synthetic TCP plus UDP fallback, got %#v", got)
|
||||||
|
}
|
||||||
|
if got[0].Transport != turnTransportTCP || got[0].Host != "1.2.3.4" || got[0].Port != "3478" {
|
||||||
|
t.Fatalf("first candidate must be synthetic TCP to the VK TURN address, got %#v", got[0])
|
||||||
|
}
|
||||||
|
if got[1].Transport != turnTransportUDP || !got[1].LegacyUDP {
|
||||||
|
t.Fatalf("last candidate must preserve UDP fallback, got %#v", got[1])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSessionTURNCandidatesNormalModeDoesNotSynthesizeTCP(t *testing.T) {
|
||||||
|
got := sessionTURNCandidatesWithPreference(
|
||||||
|
[]string{"turn:1.2.3.4:3478?transport=udp"},
|
||||||
|
0,
|
||||||
|
nil,
|
||||||
|
false,
|
||||||
|
)
|
||||||
|
if len(got) != 1 || got[0].Transport != turnTransportUDP || !got[0].LegacyUDP {
|
||||||
|
t.Fatalf("normal mode must keep the historical UDP-only candidate, got %#v", got)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+5
-1
@@ -1,4 +1,8 @@
|
|||||||
org.gradle.jvmargs=-Xmx8G -Dfile.encoding=UTF-8 -XX:+UseParallelGC -XX:MaxMetaspaceSize=1024m
|
# Keep enough heap for release builds without allowing Gradle and Kotlin
|
||||||
|
# daemons to exhaust a typical development machine when the IDE is open.
|
||||||
|
org.gradle.jvmargs=-Xmx4G -Dfile.encoding=UTF-8 -XX:+UseParallelGC -XX:MaxMetaspaceSize=1024m
|
||||||
|
org.gradle.daemon.idletimeout=900000
|
||||||
|
kotlin.daemon.jvmargs=-Xmx2G -XX:MaxMetaspaceSize=768m
|
||||||
android.useAndroidX=true
|
android.useAndroidX=true
|
||||||
android.nonTransitiveRClass=true
|
android.nonTransitiveRClass=true
|
||||||
org.gradle.caching=true
|
org.gradle.caching=true
|
||||||
|
|||||||
@@ -115,6 +115,22 @@ case "$( uname )" in #(
|
|||||||
NONSTOP* ) nonstop=true ;;
|
NONSTOP* ) nonstop=true ;;
|
||||||
esac
|
esac
|
||||||
|
|
||||||
|
# Gradle starts another daemon when the compatible daemon is busy. On Linux,
|
||||||
|
# serialize wrapper invocations for this checkout so an accidental repeated
|
||||||
|
# command waits instead of running a second memory-heavy Android build. The
|
||||||
|
# lock descriptor stays in flock's parent process and is not inherited by the
|
||||||
|
# long-lived Gradle or Kotlin daemons.
|
||||||
|
if [ "${WDTT_GRADLE_LOCK_HELD:-0}" != 1 ] &&
|
||||||
|
! "$cygwin" && ! "$msys" && ! "$darwin" && ! "$nonstop" &&
|
||||||
|
command -v flock >/dev/null 2>&1
|
||||||
|
then
|
||||||
|
gradle_lock_dir=$APP_HOME/.gradle
|
||||||
|
mkdir -p "$gradle_lock_dir" || die "Could not create Gradle lock directory: $gradle_lock_dir"
|
||||||
|
WDTT_GRADLE_LOCK_HELD=1
|
||||||
|
export WDTT_GRADLE_LOCK_HELD
|
||||||
|
exec flock --exclusive --close "$gradle_lock_dir/wdtt-build.lock" "$0" "$@"
|
||||||
|
fi
|
||||||
|
|
||||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user