Выпуск WDTT Plus v14
This commit is contained in:
1 parent
10bf9d6f25
commit
10c6939b2a
56 files changed
+7226
-814
No files matched your search
@@ -98,6 +98,10 @@ data class AccessLifecycleStatus(
|
||||
val detailLabel: String = "",
|
||||
val detailValue: 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 checkedAtMillis: Long = System.currentTimeMillis(),
|
||||
val profileRevision: Long = 0,
|
||||
@@ -125,6 +129,10 @@ data class AccessLifecycleUiState(
|
||||
val detailLabel: String = "",
|
||||
val detailValue: String = "",
|
||||
val actionIcon: String = "",
|
||||
val continuationAvailable: Boolean? = null,
|
||||
val continuationExpiresAtSeconds: Long? = null,
|
||||
val dismissible: Boolean? = null,
|
||||
val dismissedMessage: String = "",
|
||||
val severity: AccessLifecycleSeverity,
|
||||
val checkedAtMillis: Long,
|
||||
) {
|
||||
@@ -140,6 +148,10 @@ data class AccessLifecycleUiState(
|
||||
detailLabel = "",
|
||||
detailValue = "",
|
||||
actionIcon = "",
|
||||
continuationAvailable = null,
|
||||
continuationExpiresAtSeconds = null,
|
||||
dismissible = null,
|
||||
dismissedMessage = "",
|
||||
severity = AccessLifecycleSeverity.NORMAL,
|
||||
checkedAtMillis = 0,
|
||||
)
|
||||
@@ -157,9 +169,29 @@ internal fun accessLifecycleDismissalSignature(
|
||||
lifecycle.message,
|
||||
lifecycle.detailLabel,
|
||||
lifecycle.detailValue,
|
||||
lifecycle.continuationAvailable,
|
||||
lifecycle.continuationExpiresAtSeconds,
|
||||
lifecycle.dismissible,
|
||||
lifecycle.dismissedMessage,
|
||||
).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 {
|
||||
val current = status
|
||||
return AccessLifecycleUiState(
|
||||
@@ -173,6 +205,10 @@ internal fun StoredAccessLifecycle.toUiState(): AccessLifecycleUiState {
|
||||
detailLabel = current?.detailLabel.orEmpty(),
|
||||
detailValue = current?.detailValue.orEmpty(),
|
||||
actionIcon = current?.actionIcon.orEmpty(),
|
||||
continuationAvailable = current?.continuationAvailable,
|
||||
continuationExpiresAtSeconds = current?.continuationExpiresAtSeconds,
|
||||
dismissible = current?.dismissible,
|
||||
dismissedMessage = current?.dismissedMessage.orEmpty(),
|
||||
severity = current?.severity ?: AccessLifecycleSeverity.NORMAL,
|
||||
checkedAtMillis = current?.checkedAtMillis ?: 0,
|
||||
)
|
||||
|
||||
@@ -3,12 +3,14 @@ package com.wdtt.plus
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.util.TimeZone
|
||||
|
||||
sealed interface AccessLifecycleRefreshResult {
|
||||
@@ -35,6 +37,14 @@ object AccessLifecycleCoordinator {
|
||||
context: Context,
|
||||
profileIndex: Int,
|
||||
force: Boolean = false,
|
||||
): AccessLifecycleRefreshResult = withContext(Dispatchers.IO) {
|
||||
refreshProfileOnWorker(context, profileIndex, force)
|
||||
}
|
||||
|
||||
private suspend fun refreshProfileOnWorker(
|
||||
context: Context,
|
||||
profileIndex: Int,
|
||||
force: Boolean = false,
|
||||
): AccessLifecycleRefreshResult {
|
||||
val appContext = context.applicationContext
|
||||
val profile = profileIndex.coerceIn(0, 2)
|
||||
@@ -60,7 +70,9 @@ object AccessLifecycleCoordinator {
|
||||
val current = store.accessLifecycleForProfile(profile)
|
||||
val currentNow = System.currentTimeMillis()
|
||||
if (!current.capability.available) return@withLock AccessLifecycleRefreshResult.Unmanaged
|
||||
syncPendingProfileValues(store, profile, current.capability)
|
||||
if (current.status?.continuationAvailable != false) {
|
||||
syncPendingProfileValues(store, profile, current.capability)
|
||||
}
|
||||
if (
|
||||
!force &&
|
||||
current.status != null &&
|
||||
@@ -104,6 +116,20 @@ object AccessLifecycleCoordinator {
|
||||
) {
|
||||
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(
|
||||
appContext = appContext,
|
||||
store = store,
|
||||
@@ -478,22 +504,17 @@ object AccessLifecycleCoordinator {
|
||||
require(binding.isNotBlank() && delivery.binding == binding) {
|
||||
"Обновление относится к другому профилю."
|
||||
}
|
||||
val applied = store.applyWdttDeepLink(
|
||||
val applied = store.applyRemoteDocumentDelivery(
|
||||
plan = WdttDeepLinkApplyPlan(
|
||||
link = delivery.document,
|
||||
targetProfile = profile,
|
||||
requiresConfirmation = false,
|
||||
storeAsLink = false,
|
||||
),
|
||||
resetRemoteContinuation = false,
|
||||
profileMaxWorkers = delivery.profileMaxWorkers,
|
||||
remoteManaged = null,
|
||||
preserveVkHashes = true,
|
||||
delivery = delivery,
|
||||
isBoundUpdate = true,
|
||||
)
|
||||
require(applied != null) { "Не удалось применить обновление профиля." }
|
||||
if (delivery.access.available) {
|
||||
store.saveRemoteAccessCapability(delivery.access, profile)
|
||||
}
|
||||
store.saveAppliedAccessProfileRevision(profile, update.revision)
|
||||
requestTunnelProfileRuntimeUpdate(profile)
|
||||
TunnelManager.noteAccessLifecycleEvent(
|
||||
|
||||
@@ -246,6 +246,17 @@ object AccessLifecycleGateway {
|
||||
val actionIcon = action?.optString("icon").orEmpty().trim().take(32)
|
||||
.takeIf { it == "update" }
|
||||
.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 message = root.optString("message").trim().take(400)
|
||||
val detail = root.optJSONObject("detail")
|
||||
@@ -281,6 +292,10 @@ object AccessLifecycleGateway {
|
||||
detailLabel = detailLabel,
|
||||
detailValue = detailValue,
|
||||
actionIcon = actionIcon,
|
||||
continuationAvailable = continuationAvailable,
|
||||
continuationExpiresAtSeconds = continuationExpiresAtSeconds,
|
||||
dismissible = dismissible,
|
||||
dismissedMessage = dismissedMessage,
|
||||
severity = severity,
|
||||
profileRevision = revision,
|
||||
profileUpdate = update,
|
||||
|
||||
@@ -9,6 +9,7 @@ import android.net.NetworkCapabilities
|
||||
import android.os.Build
|
||||
import android.os.CancellationSignal
|
||||
import android.os.SystemClock
|
||||
import android.telephony.SubscriptionManager
|
||||
import android.telephony.TelephonyManager
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.CancellationException
|
||||
@@ -111,6 +112,12 @@ private val vkHttpsTargets = listOf(
|
||||
)
|
||||
|
||||
suspend fun collectClientNetworkDiagnostics(context: Context): ClientNetworkDiagnosticsReport =
|
||||
collectClientNetworkDiagnostics(context, retryOnNetworkChange = true)
|
||||
|
||||
private suspend fun collectClientNetworkDiagnostics(
|
||||
context: Context,
|
||||
retryOnNetworkChange: Boolean
|
||||
): ClientNetworkDiagnosticsReport =
|
||||
withContext(Dispatchers.IO) {
|
||||
val connectivityManager = context.getSystemService(ConnectivityManager::class.java)
|
||||
val diagnosticNetwork = connectivityManager?.let { selectDiagnosticNetwork(context, it) }
|
||||
@@ -138,6 +145,28 @@ suspend fun collectClientNetworkDiagnostics(context: Context): ClientNetworkDiag
|
||||
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 reserveDnsResults = dnsResults.filter { it.label in reserveVkDiagnosticHosts }
|
||||
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 {
|
||||
if (!capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) return "не применяется"
|
||||
return runCatching {
|
||||
val telephonyManager = context.getSystemService(TelephonyManager::class.java)
|
||||
val network = telephonyManager?.networkOperatorName.orEmpty().trim()
|
||||
val sim = telephonyManager?.simOperatorName.orEmpty().trim()
|
||||
val names = listOf(network, sim).filter(String::isNotBlank).distinct()
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
|
||||
return@runCatching "не определён для выбранной сети на этой версии Android"
|
||||
}
|
||||
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 {
|
||||
append(names.joinToString(" / ").ifBlank { "не определён" })
|
||||
append(", roaming=")
|
||||
append(telephonyManager?.isNetworkRoaming ?: false)
|
||||
append(manager.isNetworkRoaming)
|
||||
append(", основная data-SIM")
|
||||
}
|
||||
}.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 {
|
||||
val capabilities = network.capabilities
|
||||
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_legacy_") ||
|
||||
entry.key.startsWith("turn_") ||
|
||||
entry.key.startsWith("rt_") ||
|
||||
entry.key.startsWith("masque_") ||
|
||||
entry.key.startsWith("worker_turn_")
|
||||
}
|
||||
.take(12)
|
||||
|
||||
@@ -16,6 +16,7 @@ import android.provider.Settings
|
||||
import android.system.Os
|
||||
import android.system.OsConstants
|
||||
import android.webkit.WebView
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.text.SimpleDateFormat
|
||||
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 {
|
||||
const val APP_VERSION_ITEM_TITLE = "Версия WDTT Plus"
|
||||
private const val MIN_RECOMMENDED_SDK = 29
|
||||
@@ -112,7 +177,7 @@ object DeviceCompatibility {
|
||||
val items = buildList {
|
||||
add(androidVersionItem())
|
||||
add(abiItem())
|
||||
add(nativeClientItem(appContext))
|
||||
add(nativeComponentsItem(appContext))
|
||||
nativeRuntimeSafetyItem()?.let(::add)
|
||||
add(pageSizeItem())
|
||||
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 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 {
|
||||
!nativeClient.isFile -> DeviceCheckItem(
|
||||
title = "Нативный клиент",
|
||||
status = "libclient.so не найден",
|
||||
details = "Android-часть запустилась, но нативный Go-клиент, который поднимает TURN/DTLS транспорт, в установленном APK не найден.",
|
||||
missing.isNotEmpty() -> DeviceCheckItem(
|
||||
title = "Нативные компоненты",
|
||||
status = "не найдены: ${missing.joinToString()}",
|
||||
details = "В установленном APK отсутствует или повреждён нативный клиент TURN/DTLS либо WireGuard backend системного VPN.",
|
||||
recommendation = "Переустановите APK нужной ABI или universal APK из официального релиза WDTT Plus.",
|
||||
severity = DeviceCheckSeverity.Error,
|
||||
firstLaunchRelevant = true
|
||||
)
|
||||
nativeClient.length() <= 0L -> DeviceCheckItem(
|
||||
title = "Нативный клиент",
|
||||
status = "libclient.so пустой",
|
||||
details = "Файл нативного клиента найден, но его размер равен нулю.",
|
||||
recommendation = "Переустановите APK; текущая установка выглядит повреждённой.",
|
||||
severity = DeviceCheckSeverity.Error,
|
||||
firstLaunchRelevant = true
|
||||
)
|
||||
else -> DeviceCheckItem(
|
||||
title = "Нативный клиент",
|
||||
status = "найден",
|
||||
details = "libclient.so найден в установленном APK, размер: ${formatMiB(nativeClient.length())}.",
|
||||
title = "Нативные компоненты",
|
||||
status = "клиент и WireGuard найдены",
|
||||
details = "libclient.so: ${formatMiB(nativeClient.length())}; libwg-go.so: ${formatMiB(wireGuardBackend.length())}.",
|
||||
severity = DeviceCheckSeverity.Ok,
|
||||
firstLaunchRelevant = true
|
||||
)
|
||||
@@ -263,29 +325,56 @@ object DeviceCompatibility {
|
||||
|
||||
private fun pageSizeItem(): DeviceCheckItem {
|
||||
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 {
|
||||
pageSize == null || pageSize <= 0L -> DeviceCheckItem(
|
||||
title = "Страница памяти",
|
||||
status = "не удалось определить",
|
||||
details = "Android не вернул размер страницы памяти.",
|
||||
recommendation = "Если VPN не стартует на новом устройстве, скопируйте отчёт через «Проверить устройство».",
|
||||
!profile.rtNetwork -> DeviceCheckItem(
|
||||
title = "Режим Сеть РТ",
|
||||
status = "выключен",
|
||||
details = "Используется обычный порядок транспортов; настройки РТ этого профиля не влияют на подключение.",
|
||||
severity = DeviceCheckSeverity.Info,
|
||||
firstLaunchRelevant = false
|
||||
)
|
||||
pageSize > 4096L -> DeviceCheckItem(
|
||||
title = "Страница памяти",
|
||||
status = "$pageSize байт",
|
||||
details = "Устройство использует страницу памяти больше 4 KB. Для новых Android-устройств с 16 KB page size нужна отдельная проверка нативной библиотеки.",
|
||||
recommendation = "Запуск не блокируется. Если туннель не стартует, отправьте отчёт из «Проверить устройство» — это важный сценарий для будущей совместимости.",
|
||||
!profile.rtMasque -> DeviceCheckItem(
|
||||
title = "Режим Сеть РТ",
|
||||
status = "TURN/TLS и TCP включены · MASQUE выключен",
|
||||
details = "Для активного профиля включён только основной механизм Сети РТ. Регистрация WARP не требуется.",
|
||||
severity = DeviceCheckSeverity.Ok,
|
||||
)
|
||||
profile.rtMasqueServerBootstrap && !profile.rtMasqueServerAccessReady -> DeviceCheckItem(
|
||||
title = "Режим Сеть РТ",
|
||||
status = "«Через сервер» настроен не полностью",
|
||||
details = "MASQUE включён, но в активном профиле нет полного SSH-доступа из раздела «Деплой».",
|
||||
recommendation = "Заполните адрес и пароль либо приватный SSH-ключ в «Деплой» или выключите «Через сервер».",
|
||||
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(
|
||||
title = "Страница памяти",
|
||||
status = "$pageSize байт",
|
||||
details = "Обычный размер страницы памяти для текущей нативной сборки.",
|
||||
title = "Режим Сеть РТ",
|
||||
status = "MASQUE готов",
|
||||
details = "Структура сохранённой регистрации WARP корректна; при запуске её дополнительно проверит нативный клиент.",
|
||||
severity = DeviceCheckSeverity.Ok,
|
||||
firstLaunchRelevant = true
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -124,6 +124,11 @@ internal fun shouldHandleIncomingIntent(
|
||||
|
||||
private sealed interface 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(
|
||||
val plan: WdttDeepLinkApplyPlan,
|
||||
val delivery: RemoteDocumentDelivery
|
||||
@@ -264,7 +269,9 @@ class MainActivity : ComponentActivity() {
|
||||
wdttDeepLinkMessage = message
|
||||
},
|
||||
onSelectWdttDeepLinkOverwriteProfile = { profile ->
|
||||
pendingWdttDeepLinkPlan = pendingWdttDeepLinkPlan?.copy(targetProfile = profile)
|
||||
pendingWdttDeepLinkPlan = pendingWdttDeepLinkPlan?.let { plan ->
|
||||
if (profile in plan.blockedProfiles) plan else plan.copy(targetProfile = profile)
|
||||
}
|
||||
},
|
||||
onConfirmWdttDeepLinkOverwrite = { plan ->
|
||||
pendingWdttDeepLinkPlan = null
|
||||
@@ -276,7 +283,31 @@ class MainActivity : ComponentActivity() {
|
||||
},
|
||||
onSelectWdttConnectProfile = { profile ->
|
||||
(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 ->
|
||||
@@ -496,19 +527,106 @@ class MainActivity : ComponentActivity() {
|
||||
receiveRemoteDocument(link)
|
||||
}
|
||||
|
||||
private fun receiveRemoteDocument(link: RemoteDocumentLink) {
|
||||
private fun receiveRemoteDocument(
|
||||
link: RemoteDocumentLink,
|
||||
localDocument: String? = null,
|
||||
attachmentProfile: Int? = null,
|
||||
) {
|
||||
if (!remoteDocumentRequests.add(link.url)) return
|
||||
lifecycleScope.launch {
|
||||
try {
|
||||
var requestedAttachmentProfile = attachmentProfile
|
||||
wdttConnectFlow = WdttConnectFlow.Progress("Проверяем ссылку и получаем доступ...")
|
||||
val delivery = RemoteDocumentGateway.receive(
|
||||
link = link,
|
||||
device = settingsStore.getOrCreateConnectDeviceId(),
|
||||
label = vkHashDeviceName(),
|
||||
client = BuildConfig.VERSION_NAME,
|
||||
system = Build.VERSION.RELEASE.orEmpty(),
|
||||
localBindings = settingsStore.remoteDocumentBindings(),
|
||||
)
|
||||
suspend fun request(
|
||||
document: String?,
|
||||
profileAttachment: Boolean = false,
|
||||
): RemoteDocumentDelivery =
|
||||
RemoteDocumentGateway.receive(
|
||||
link = link,
|
||||
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-профиль...")
|
||||
var boundProfile: Int? = null
|
||||
for (binding in listOf(delivery.binding, delivery.access.binding)) {
|
||||
@@ -516,6 +634,13 @@ class MainActivity : ComponentActivity() {
|
||||
boundProfile = settingsStore.profileForRemoteBinding(binding)
|
||||
if (boundProfile != null) break
|
||||
}
|
||||
if (
|
||||
boundProfile == null &&
|
||||
delivery.kind == RemoteDocumentKind.BASE &&
|
||||
requestedAttachmentProfile != null
|
||||
) {
|
||||
boundProfile = requestedAttachmentProfile
|
||||
}
|
||||
if (boundProfile == null && delivery.kind == RemoteDocumentKind.BASE) {
|
||||
boundProfile = settingsStore.profileForConnectionDocument(delivery.document)
|
||||
}
|
||||
@@ -567,7 +692,10 @@ class MainActivity : ComponentActivity() {
|
||||
lifecycleScope.launch {
|
||||
val store = SettingsStore(this@MainActivity)
|
||||
runCatching {
|
||||
store.createWdttDeepLinkApplyPlan(link)
|
||||
store.createWdttDeepLinkApplyPlan(
|
||||
link,
|
||||
allowOmittedConnection = delivery?.kind == RemoteDocumentKind.UPDATE,
|
||||
)
|
||||
}.onSuccess { basePlan ->
|
||||
val plan = basePlan?.let {
|
||||
if (preferredProfile == null) it else it.copy(
|
||||
@@ -684,24 +812,17 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
if (fromRemoteDocument) {
|
||||
val profile = result?.targetProfile ?: plan.targetProfile
|
||||
if (delivery?.access?.available == true) {
|
||||
if (delivery?.access?.available == true || isBoundUpdate) {
|
||||
lifecycleScope.launch {
|
||||
AccessLifecycleCoordinator.refreshProfile(
|
||||
this@MainActivity,
|
||||
profile,
|
||||
force = delivery.access.initialStatus == null,
|
||||
force = isBoundUpdate || delivery?.access?.initialStatus == null,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (isBoundUpdate) {
|
||||
val profileLabel = vpnProfileDisplayName(profile, store.profileNames.first())
|
||||
wdttConnectFlow = WdttConnectFlow.Complete(
|
||||
if (result?.alreadyApplied == true) {
|
||||
"Обновление профиля $profileLabel уже применено."
|
||||
} else {
|
||||
"Профиль $profileLabel обновлён. Новые данные уже видны в настройках туннеля."
|
||||
}
|
||||
)
|
||||
if (shouldRestoreUiAfterBoundUpdate(isBoundUpdate)) {
|
||||
wdttConnectFlow = null
|
||||
} else if (
|
||||
existingRemoteProfile &&
|
||||
store.tunnelProfileSnapshot(profile).vkHashes.isNotBlank()
|
||||
@@ -737,7 +858,13 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
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)
|
||||
?.access
|
||||
?: RemoteAccessCapability.Unavailable
|
||||
@@ -792,7 +919,8 @@ class MainActivity : ComponentActivity() {
|
||||
)
|
||||
val target = RemoteContinuationLauncher.begin(
|
||||
capability = continuation,
|
||||
device = settingsStore.getOrCreateConnectDeviceId()
|
||||
device = settingsStore.getOrCreateConnectDeviceId(),
|
||||
localDocument = settingsStore.remoteActionProfileDocument(profile),
|
||||
)
|
||||
launchRemoteContinuation(target)
|
||||
wdttConnectFlow = WdttConnectFlow.Complete(
|
||||
@@ -1251,6 +1379,8 @@ private fun MainScreen(
|
||||
onSelectWdttDeepLinkOverwriteProfile: (Int) -> Unit = {},
|
||||
onConfirmWdttDeepLinkOverwrite: (WdttDeepLinkApplyPlan) -> Unit = {},
|
||||
onCancelWdttDeepLinkOverwrite: () -> Unit = {},
|
||||
onSelectWdttAttachmentProfile: (Int) -> Unit = {},
|
||||
onConfirmWdttAttachmentProfile: () -> Unit = {},
|
||||
onSelectWdttConnectProfile: (Int) -> Unit = {},
|
||||
onConfirmWdttConnectProfile: (WdttDeepLinkApplyPlan) -> Unit = {},
|
||||
onContinueLimitedWdttSetup: (WdttDeepLinkApplyPlan, RemoteDocumentDelivery) -> Unit = { _, _ -> },
|
||||
@@ -1283,7 +1413,8 @@ private fun MainScreen(
|
||||
val scope = rememberCoroutineScope()
|
||||
val updateCheckMutex = remember { Mutex() }
|
||||
val settingsReady by settingsStore.settingsReady.collectAsStateWithLifecycle(initialValue = false)
|
||||
val startupSettings by settingsStore.activeTunnelProfileUiSnapshot.collectAsStateWithLifecycle()
|
||||
val startupSettings by
|
||||
settingsStore.activeTunnelProfileContentUiSnapshot.collectAsStateWithLifecycle()
|
||||
if (!settingsReady || startupSettings == null) {
|
||||
Box(modifier = Modifier.fillMaxSize()) {
|
||||
AppBackdrop(modifier = Modifier.matchParentSize())
|
||||
@@ -1768,6 +1899,7 @@ private fun MainScreen(
|
||||
|
||||
// Floating theme toolbar overlay
|
||||
FloatingToolbar(
|
||||
settingsStore = settingsStore,
|
||||
activeProfile = activeProfile,
|
||||
profileNames = profileNames,
|
||||
onActiveProfileChange = { profile ->
|
||||
@@ -1990,6 +2122,8 @@ private fun MainScreen(
|
||||
WdttConnectActivationDialog(
|
||||
flow = flow,
|
||||
profileNames = profileNames,
|
||||
onSelectAttachmentProfile = onSelectWdttAttachmentProfile,
|
||||
onConfirmAttachmentProfile = onConfirmWdttAttachmentProfile,
|
||||
onSelectProfile = onSelectWdttConnectProfile,
|
||||
onConfirmProfile = onConfirmWdttConnectProfile,
|
||||
onContinueLimitedSetup = onContinueLimitedWdttSetup,
|
||||
@@ -2032,16 +2166,24 @@ private fun MainScreen(
|
||||
repeat(3) { profile ->
|
||||
FilterChip(
|
||||
selected = plan.targetProfile == profile,
|
||||
enabled = profile !in plan.blockedProfiles,
|
||||
onClick = { onSelectWdttDeepLinkOverwriteProfile(profile) },
|
||||
label = { Text(vpnProfileDisplayName(profile, profileNames)) }
|
||||
)
|
||||
}
|
||||
}
|
||||
Text("Будет полностью заменено подключение в профиле $profileLabel.")
|
||||
if (plan.blockedProfiles.size == 3) {
|
||||
Text("Все профили защищены действующим удалённым доступом. Сначала освободите один из них.")
|
||||
} else {
|
||||
Text("Будет полностью заменено подключение в профиле $profileLabel.")
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = { onConfirmWdttDeepLinkOverwrite(plan) }) {
|
||||
TextButton(
|
||||
enabled = plan.targetProfile !in plan.blockedProfiles,
|
||||
onClick = { onConfirmWdttDeepLinkOverwrite(plan) },
|
||||
) {
|
||||
Text("Да")
|
||||
}
|
||||
},
|
||||
@@ -2058,6 +2200,8 @@ private fun MainScreen(
|
||||
private fun WdttConnectActivationDialog(
|
||||
flow: WdttConnectFlow,
|
||||
profileNames: List<String>,
|
||||
onSelectAttachmentProfile: (Int) -> Unit,
|
||||
onConfirmAttachmentProfile: () -> Unit,
|
||||
onSelectProfile: (Int) -> Unit,
|
||||
onConfirmProfile: (WdttDeepLinkApplyPlan) -> Unit,
|
||||
onContinueLimitedSetup: (WdttDeepLinkApplyPlan, RemoteDocumentDelivery) -> Unit,
|
||||
@@ -2073,7 +2217,8 @@ private fun WdttConnectActivationDialog(
|
||||
var selectedHashMethod by rememberSaveable { mutableStateOf<String?>(null) }
|
||||
var helpMethod 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
|
||||
AlertDialog(
|
||||
onDismissRequest = {
|
||||
@@ -2110,6 +2255,41 @@ private fun WdttConnectActivationDialog(
|
||||
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 -> {
|
||||
val incomingName = WdttDeepLink.parse(
|
||||
state.plan.link,
|
||||
@@ -2124,13 +2304,20 @@ private fun WdttConnectActivationDialog(
|
||||
repeat(3) { profile ->
|
||||
FilterChip(
|
||||
selected = state.plan.targetProfile == profile,
|
||||
enabled = profile !in state.plan.blockedProfiles,
|
||||
onClick = { onSelectProfile(profile) },
|
||||
label = { Text(vpnProfileDisplayName(profile, profileNames)) }
|
||||
)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
"Подключение в выбранном профиле будет полностью заменено.",
|
||||
if (state.plan.blockedProfiles.size == 3) {
|
||||
"Все профили защищены действующим готовым доступом. " +
|
||||
"Ни один из них нельзя перезаписать."
|
||||
} else {
|
||||
"Подключение в выбранном профиле будет полностью заменено. " +
|
||||
"Действующие готовые профили недоступны для выбора."
|
||||
},
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
@@ -2141,7 +2328,7 @@ private fun WdttConnectActivationDialog(
|
||||
"Автоматическое получение VK-хешей сейчас недоступно."
|
||||
}
|
||||
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Text("Перед добавлением профиля обратите внимание:")
|
||||
Text("Перед продолжением обратите внимание:")
|
||||
Text(reason)
|
||||
Text(
|
||||
"Это ограничение относится только к автоматическому получению " +
|
||||
@@ -2153,25 +2340,13 @@ private fun WdttConnectActivationDialog(
|
||||
}
|
||||
is WdttConnectFlow.SelectHashes -> {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
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)
|
||||
}
|
||||
)
|
||||
}
|
||||
Text("Выберите способ заполнения VK-хешей для профиля.")
|
||||
HashMethodRow(
|
||||
title = "Получить автоматически",
|
||||
body = if (state.continuation.available) {
|
||||
"Войти в VK при необходимости и создать ссылки"
|
||||
state.continuation.message.ifBlank {
|
||||
"Войти в VK при необходимости и создать ссылки"
|
||||
}
|
||||
} else {
|
||||
"Недоступно — нажмите, чтобы узнать, что делать"
|
||||
},
|
||||
@@ -2192,6 +2367,20 @@ private fun WdttConnectActivationDialog(
|
||||
onHelp = { helpMethod = "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") {
|
||||
OutlinedTextField(
|
||||
value = manualHashes,
|
||||
@@ -2211,8 +2400,16 @@ private fun WdttConnectActivationDialog(
|
||||
},
|
||||
confirmButton = {
|
||||
when (flow) {
|
||||
is WdttConnectFlow.SelectAttachmentProfile -> {
|
||||
TextButton(onClick = onConfirmAttachmentProfile) {
|
||||
Text("Продолжить")
|
||||
}
|
||||
}
|
||||
is WdttConnectFlow.SelectProfile -> {
|
||||
TextButton(onClick = { onConfirmProfile(flow.plan) }) {
|
||||
TextButton(
|
||||
enabled = flow.plan.targetProfile !in flow.plan.blockedProfiles,
|
||||
onClick = { onConfirmProfile(flow.plan) },
|
||||
) {
|
||||
Text("Сохранить")
|
||||
}
|
||||
}
|
||||
@@ -2256,6 +2453,11 @@ private fun WdttConnectActivationDialog(
|
||||
},
|
||||
dismissButton = {
|
||||
when (flow) {
|
||||
is WdttConnectFlow.SelectAttachmentProfile -> {
|
||||
TextButton(onClick = onDismiss) {
|
||||
Text("Отмена")
|
||||
}
|
||||
}
|
||||
is WdttConnectFlow.SelectProfile -> {
|
||||
TextButton(onClick = onDismiss) {
|
||||
Text("Позже")
|
||||
@@ -2310,7 +2512,7 @@ private fun WdttConnectActivationDialog(
|
||||
}
|
||||
"restore" -> {
|
||||
"WDTT Plus безопасно вернёт хеши, ранее сохранённые именно для " +
|
||||
"этого готового профиля. Хеши других ваших профилей не используются."
|
||||
"этого профиля. Значения других профилей не используются."
|
||||
}
|
||||
else -> {
|
||||
"Создайте или скопируйте до четырёх ссылок-приглашений VK Звонков, " +
|
||||
|
||||
@@ -3,6 +3,8 @@ package com.wdtt.plus
|
||||
import android.content.Context
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.json.JSONObject
|
||||
import java.net.HttpURLConnection
|
||||
@@ -81,6 +83,7 @@ object RemoteActionCatalogGateway {
|
||||
private const val CACHE_TTL_MS = 10 * 60 * 1000L
|
||||
private const val MAX_RESPONSE_CHARS = 32 * 1024
|
||||
private val placements = setOf("tunnel", "profile", "about")
|
||||
private val fetchMutex = Mutex()
|
||||
|
||||
@Volatile
|
||||
private var cachedAt = 0L
|
||||
@@ -91,21 +94,24 @@ object RemoteActionCatalogGateway {
|
||||
fun hasFreshCache(): Boolean =
|
||||
System.currentTimeMillis() - cachedAt in 0 until CACHE_TTL_MS
|
||||
|
||||
fun cached(): RemoteActionCatalog =
|
||||
if (hasFreshCache()) cachedCatalog else RemoteActionCatalog.Empty
|
||||
fun cached(): RemoteActionCatalog = cachedCatalog
|
||||
|
||||
suspend fun fetch(force: Boolean = false): RemoteActionCatalog {
|
||||
val now = System.currentTimeMillis()
|
||||
if (!force && now - cachedAt in 0 until CACHE_TTL_MS) return cachedCatalog
|
||||
return withContext(Dispatchers.IO) {
|
||||
val current = System.currentTimeMillis()
|
||||
if (!force && current - cachedAt in 0 until CACHE_TTL_MS) {
|
||||
return@withContext cachedCatalog
|
||||
fetchMutex.withLock {
|
||||
val current = System.currentTimeMillis()
|
||||
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 {
|
||||
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(safeServiceUrl(capability.url)) { "Автоматическое заполнение сейчас недоступно." }
|
||||
require(validDevice(device)) { "Не удалось определить текущее устройство." }
|
||||
return withContext(Dispatchers.IO) {
|
||||
val payload = JSONObject()
|
||||
val request = JSONObject()
|
||||
.put("key", capability.key.trim())
|
||||
.put("device", device.trim())
|
||||
.put("return_transport", "auth_tab")
|
||||
attachmentDocumentForRequest(localDocument)?.let { document ->
|
||||
request.put("profile", document)
|
||||
}
|
||||
val payload = request
|
||||
.toString()
|
||||
.toByteArray(Charsets.UTF_8)
|
||||
var connection: HttpURLConnection? = null
|
||||
@@ -164,6 +172,11 @@ object RemoteContinuationLauncher {
|
||||
|
||||
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()) {
|
||||
listOf(target.fallbackUrl, target.primaryUrl)
|
||||
} else {
|
||||
|
||||
@@ -21,6 +21,7 @@ data class RemoteDocumentFailureAction(
|
||||
class RemoteDocumentFailure(
|
||||
message: String,
|
||||
val action: RemoteDocumentFailureAction? = null,
|
||||
val profileAttachmentRequired: Boolean = false,
|
||||
) : IllegalStateException(message)
|
||||
|
||||
data class RemoteContinuation(
|
||||
@@ -33,7 +34,8 @@ data class RemoteContinuation(
|
||||
|
||||
enum class RemoteDocumentKind {
|
||||
BASE,
|
||||
UPDATE
|
||||
UPDATE,
|
||||
ATTACHMENT,
|
||||
}
|
||||
|
||||
data class RemoteDocumentDelivery(
|
||||
@@ -49,7 +51,11 @@ data class RemoteDocumentDelivery(
|
||||
internal fun RemoteDocumentDelivery.shouldPreserveLocalVkHashes(
|
||||
existingProfileRedelivery: Boolean = false,
|
||||
): Boolean {
|
||||
val deliveredHashes = WdttDeepLink.parse(document, allowMissingHashes = true)
|
||||
val deliveredHashes = WdttDeepLink.parse(
|
||||
document,
|
||||
allowMissingHashes = true,
|
||||
allowOmittedConnection = kind == RemoteDocumentKind.UPDATE,
|
||||
)
|
||||
?.hashes
|
||||
.orEmpty()
|
||||
return deliveredHashes.isBlank() &&
|
||||
@@ -64,7 +70,24 @@ internal fun RemoteDocumentDelivery.requiresInitialContinuationWarning(
|
||||
): Boolean =
|
||||
kind == RemoteDocumentKind.BASE &&
|
||||
!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 {
|
||||
private const val MAX_RESPONSE_CHARS = 32 * 1024
|
||||
@@ -95,6 +118,8 @@ object RemoteDocumentGateway {
|
||||
client: String,
|
||||
system: String,
|
||||
localBindings: Collection<String>? = null,
|
||||
localDocument: String? = null,
|
||||
profileAttachment: Boolean = false,
|
||||
): RemoteDocumentDelivery {
|
||||
require(extractLink(link.url) != null) { "Ссылка повреждена или неполна." }
|
||||
require(validDevice(device)) { "Не удалось определить текущее устройство." }
|
||||
@@ -113,6 +138,11 @@ object RemoteDocumentGateway {
|
||||
.take(6)
|
||||
request.put("bindings", JSONArray(bindings))
|
||||
}
|
||||
attachmentDocumentForRequest(localDocument)
|
||||
?.let { request.put("profile", it) }
|
||||
if (profileAttachment) {
|
||||
request.put("attach", true)
|
||||
}
|
||||
val payload = request
|
||||
.toString()
|
||||
.toByteArray(Charsets.UTF_8)
|
||||
@@ -135,6 +165,9 @@ object RemoteDocumentGateway {
|
||||
"Ссылка недоступна. Получите новую ссылку подключения."
|
||||
},
|
||||
failure.second,
|
||||
profileAttachmentRequired = profileAttachmentRequired(
|
||||
connection.getHeaderField("X-WDTT-Profile-Required")
|
||||
),
|
||||
)
|
||||
}
|
||||
parse(body)
|
||||
@@ -161,11 +194,20 @@ object RemoteDocumentGateway {
|
||||
val kind = when (root.optString("type").trim()) {
|
||||
"base" -> RemoteDocumentKind.BASE
|
||||
"update" -> RemoteDocumentKind.UPDATE
|
||||
"attachment" -> RemoteDocumentKind.ATTACHMENT
|
||||
else -> throw IllegalStateException("WDTT Plus вернул неподдерживаемый тип данных.")
|
||||
}
|
||||
val document = root.optString("document").trim()
|
||||
val documentParts = WdttDeepLink.parse(document, allowMissingHashes = true)
|
||||
if (documentParts == null) {
|
||||
val documentParts = document
|
||||
.takeIf(String::isNotBlank)
|
||||
?.let {
|
||||
WdttDeepLink.parse(
|
||||
it,
|
||||
allowMissingHashes = true,
|
||||
allowOmittedConnection = kind == RemoteDocumentKind.UPDATE,
|
||||
)
|
||||
}
|
||||
if (kind != RemoteDocumentKind.ATTACHMENT && documentParts == null) {
|
||||
throw IllegalStateException("WDTT Plus вернул неполные данные подключения.")
|
||||
}
|
||||
val binding = root.optString("binding").trim().takeIf(::opaqueValue).orEmpty()
|
||||
@@ -203,7 +245,7 @@ object RemoteDocumentGateway {
|
||||
}
|
||||
when (kind) {
|
||||
RemoteDocumentKind.BASE -> {
|
||||
if (documentParts.hashes.isNotBlank()) {
|
||||
if (documentParts?.hashes?.isNotBlank() == true) {
|
||||
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)
|
||||
?.takeIf {
|
||||
|
||||
@@ -12,11 +12,6 @@ import javax.crypto.spec.GCMParameterSpec
|
||||
|
||||
class SecureStringStore(context: Context) {
|
||||
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 {
|
||||
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 GCM_TAG_BITS = 128
|
||||
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 {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
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(
|
||||
val pendingLevel: Int,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -31,6 +31,54 @@ data class SshCredentials(
|
||||
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(
|
||||
mode: String,
|
||||
password: String,
|
||||
|
||||
@@ -127,10 +127,11 @@ internal fun decideTrustedWifiTransition(
|
||||
|
||||
internal fun shouldKeepTunnelServiceAlive(
|
||||
tunnelRunning: Boolean,
|
||||
tunnelStarting: Boolean,
|
||||
tunnelPaused: Boolean,
|
||||
trustedWifiWaiting: Boolean,
|
||||
trustedWifiResumeInProgress: Boolean
|
||||
): Boolean = tunnelRunning || tunnelPaused || trustedWifiWaiting || trustedWifiResumeInProgress
|
||||
): Boolean = tunnelRunning || tunnelStarting || tunnelPaused || trustedWifiWaiting || trustedWifiResumeInProgress
|
||||
|
||||
fun sanitizeTrustedWifiSsid(value: String): String {
|
||||
val clean = value
|
||||
|
||||
@@ -59,16 +59,32 @@ internal val ConnectionIssue.isStandaloneUiIssue: Boolean
|
||||
|
||||
enum class NetworkRecoveryAction {
|
||||
SoftRestart,
|
||||
RecreateVpn,
|
||||
StopVpn
|
||||
}
|
||||
|
||||
internal fun stableNetworkRecoveryAction(completedAttempts: Int): NetworkRecoveryAction = when {
|
||||
completedAttempts <= 0 -> NetworkRecoveryAction.SoftRestart
|
||||
completedAttempts == 1 -> NetworkRecoveryAction.RecreateVpn
|
||||
else -> NetworkRecoveryAction.StopVpn
|
||||
internal fun stableNetworkRecoveryAction(@Suppress("UNUSED_PARAMETER") completedAttempts: Int): NetworkRecoveryAction =
|
||||
NetworkRecoveryAction.SoftRestart
|
||||
|
||||
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) {
|
||||
User("отключено пользователем"),
|
||||
VpnSlotTransferred("VPN-слот передан другому приложению"),
|
||||
@@ -150,6 +166,287 @@ internal fun isExpiredAccessAuthFailure(line: String): Boolean =
|
||||
|
||||
internal const val WRAP_HANDSHAKE_RETRY_MESSAGE =
|
||||
"[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
|
||||
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_ZERO_WORKERS_GRACE_MS = 15 * 60_000L
|
||||
private const val STAGNANT_ACTIVE_TRAFFIC_MS = 20 * 60_000L
|
||||
private const val WAKE_RECOVERY_GRACE_MS = 90_000L
|
||||
|
||||
object TunnelManager {
|
||||
// 100% защита от утечек: единый управляемый глобальный Scope
|
||||
@@ -168,6 +466,7 @@ object TunnelManager {
|
||||
private var readerJob: Job? = null
|
||||
private var watchdogJob: Job? = null
|
||||
private var wgHelper: WireGuardHelper? = null
|
||||
private var warpApiSshRelay: WarpApiSshRelay? = null
|
||||
|
||||
private val startStopMutex = kotlinx.coroutines.sync.Mutex()
|
||||
|
||||
@@ -198,8 +497,10 @@ object TunnelManager {
|
||||
private var lastSoftRestartAtMs = 0L
|
||||
private var lastUnderlyingNetworkChangeAtMs = 0L
|
||||
private var networkTransitionGraceUntilMs = 0L
|
||||
private var wakeRecoveryGraceUntilMs = 0L
|
||||
private var lastNetworkSettleRestartAtMs = 0L
|
||||
private var lastStableNetworkIssueLogAtMs = 0L
|
||||
private val sessionTraffic = TunnelSessionTrafficAccumulator()
|
||||
private val captchaSolveRequestId = AtomicLong(0)
|
||||
private val activeCaptchaSolveRequests = ConcurrentHashMap.newKeySet<Long>()
|
||||
|
||||
@@ -381,6 +682,7 @@ object TunnelManager {
|
||||
|
||||
fun pollNetworkRecoveryAction(now: Long = System.currentTimeMillis()): NetworkRecoveryAction? {
|
||||
if (!running.value) return null
|
||||
if (isWakeRecoveryGraceActive(now)) return null
|
||||
if (AMNEZIA_STYLE_RECOVERY) {
|
||||
return pollStableNetworkRecoveryAction(now)
|
||||
}
|
||||
@@ -495,13 +797,9 @@ object TunnelManager {
|
||||
"Восстанавливаю транспорт",
|
||||
"Сеть долго не подаёт признаков жизни. Выполняется тихая попытка без пересоздания VPN."
|
||||
)
|
||||
NetworkRecoveryAction.RecreateVpn -> setConnectionIssue(
|
||||
"Пересоздаю VPN",
|
||||
"Тихое восстановление не помогло. Системный VPN-интерфейс будет пересоздан один раз."
|
||||
)
|
||||
NetworkRecoveryAction.StopVpn -> setConnectionIssue(
|
||||
"VPN остановлен, чтобы вернуть интернет",
|
||||
"Пересоздание VPN не восстановило связь. WDTT Plus выключит VPN, чтобы телефон не остался без интернета."
|
||||
"Повторные попытки не восстановили связь. WDTT Plus выключит VPN, чтобы телефон не остался без интернета."
|
||||
)
|
||||
}
|
||||
return action
|
||||
@@ -660,6 +958,7 @@ object TunnelManager {
|
||||
if (!preserveLogs) clearLogs()
|
||||
config.value = null
|
||||
stats.value = "Ожидание данных..."
|
||||
sessionTraffic.reset()
|
||||
floodCount = 0
|
||||
mismatchCount = 0
|
||||
refusedCount = 0
|
||||
@@ -671,6 +970,7 @@ object TunnelManager {
|
||||
resetStatsLivenessState()
|
||||
lastUnderlyingNetworkChangeAtMs = 0L
|
||||
networkTransitionGraceUntilMs = 0L
|
||||
wakeRecoveryGraceUntilMs = 0L
|
||||
lastNetworkSettleRestartAtMs = 0L
|
||||
activeHashIndex = 0
|
||||
currentParams = params
|
||||
@@ -765,6 +1065,64 @@ object TunnelManager {
|
||||
// Go boolean flags must use -flag=value. A separate "false" value
|
||||
// stops flag.Parse and silently drops every argument after it.
|
||||
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()
|
||||
cmd.add("-device-id")
|
||||
@@ -811,12 +1169,26 @@ object TunnelManager {
|
||||
startWatchdog(appContext, params)
|
||||
|
||||
} catch (e: Exception) {
|
||||
closeWarpApiSshRelay()
|
||||
val message = e.readableMessage()
|
||||
updateLog("critical_start_error", "Критическая ошибка запуска: $message", 99, true)
|
||||
setConnectionIssue("Не удалось запустить подключение", "Проверьте настройки туннеля и попробуйте подключиться снова. Причина: $message")
|
||||
e.printStackTrace()
|
||||
running.value = false
|
||||
currentParams = null
|
||||
if (isSwitching && currentParams != null) {
|
||||
// При автоматическом восстановлении не превращаем неудачную
|
||||
// попытку в окончательную остановку: служба оставляет параметры
|
||||
// сессии и сможет повторить восстановление позже.
|
||||
running.value = true
|
||||
processStartedAtMs = System.currentTimeMillis()
|
||||
updateWarningLog(
|
||||
"vpn_recovery_retry_pending",
|
||||
"[VPN] Автоматическое восстановление пока не завершилось; сохраняем сессию и повторим попытку позже.",
|
||||
50,
|
||||
)
|
||||
} else {
|
||||
running.value = false
|
||||
currentParams = null
|
||||
}
|
||||
clearTransition()
|
||||
} finally {
|
||||
if (!isSwitching) clearTransition()
|
||||
@@ -1089,7 +1461,8 @@ object TunnelManager {
|
||||
}
|
||||
|
||||
if (lineTrim.contains("[СТАТИСТИКА]")) {
|
||||
val msg = lineTrim.substringAfter("[СТАТИСТИКА]").trim()
|
||||
val rawStats = lineTrim.substringAfter("[СТАТИСТИКА]").trim()
|
||||
val msg = sessionTraffic.accumulate(rawStats)
|
||||
stats.value = msg
|
||||
lastStatsAtMs = now
|
||||
|
||||
@@ -1155,7 +1528,22 @@ object TunnelManager {
|
||||
}
|
||||
|
||||
val workerRetry = classifyRecoverableWorkerRetry(lineTrim, activeWorkers.value)
|
||||
val masquePresentation = classifyMasqueLog(lineTrim)
|
||||
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 -> {
|
||||
if (activeWorkers.value <= 0) {
|
||||
when (workerRetry.first) {
|
||||
@@ -1352,10 +1740,23 @@ object TunnelManager {
|
||||
lineTrim.contains("[TURN]") -> {
|
||||
val text = lineTrim.substringAfter("[TURN]").trim()
|
||||
when {
|
||||
text.contains("Креды уже заменены", true) ->
|
||||
updateLog(
|
||||
"turn_creds_current",
|
||||
"[TURN] Используем уже обновлённые данные без повторного запроса к VK",
|
||||
5,
|
||||
false
|
||||
)
|
||||
text.contains("Креды обновлены", true) ->
|
||||
updateLog("turn_creds_refreshed", "[TURN] Креды обновлены, продолжаем подключение", 2, false)
|
||||
text.contains("Креды уже обновлялись", true) ->
|
||||
updateLog("turn_creds_wait", "[TURN] Ждём перед повторным обновлением кредов", 2, false)
|
||||
text.contains("временно ограничил новые allocation", true) ->
|
||||
updateWarningLog(
|
||||
"turn_capacity_retry",
|
||||
"[TURN] Узел временно ограничил новые каналы; повторяем без обновления данных VK",
|
||||
20
|
||||
)
|
||||
text.contains("неполный ответ", true) ->
|
||||
updateWarningLog("turn_allocate_retry", "[TURN] Неполный Allocate-ответ, обновляем данные и повторяем", 20)
|
||||
text.contains("Ошибка allocation/кредов", true) ->
|
||||
@@ -1560,8 +1961,23 @@ object TunnelManager {
|
||||
watchdogJob = scope.launch {
|
||||
var zeroWorkersSince = 0L
|
||||
var processDeadSince = 0L
|
||||
val powerManager = context.getSystemService(Context.POWER_SERVICE) as? android.os.PowerManager
|
||||
delay(10_000)
|
||||
while (isActive && running.value) {
|
||||
if (
|
||||
!shouldObserveTunnelHealth(
|
||||
deviceInteractive = powerManager?.isInteractive != false,
|
||||
wakeRecoveryGraceActive = isWakeRecoveryGraceActive(),
|
||||
)
|
||||
) {
|
||||
// Сон и первые секунды после пробуждения не входят в длительность
|
||||
// неисправности. Иначе старый таймер срабатывает сразу при включении
|
||||
// экрана и без необходимости перезапускает транспорт.
|
||||
zeroWorkersSince = 0L
|
||||
processDeadSince = 0L
|
||||
delay(10_000)
|
||||
continue
|
||||
}
|
||||
val proc = process
|
||||
if (proc == null || !proc.isAlive) {
|
||||
val now = System.currentTimeMillis()
|
||||
@@ -1599,7 +2015,12 @@ object TunnelManager {
|
||||
lastActiveAtMs == 0L &&
|
||||
!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
|
||||
} else if (
|
||||
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)
|
||||
activeWorkers.value = 0
|
||||
resetStatsLivenessState()
|
||||
sessionTraffic.noteTransportRestart()
|
||||
val restartDelayMs = transportRecoveryPolicy(
|
||||
params.managedConfigFirstStart
|
||||
).processRestartDelayMs
|
||||
@@ -1715,6 +2137,7 @@ object TunnelManager {
|
||||
startStopMutex.lock()
|
||||
try {
|
||||
if (currentParams !== params || !running.value) return@launch
|
||||
sessionTraffic.noteTransportRestart()
|
||||
killProcess()
|
||||
delay(250L)
|
||||
} finally {
|
||||
@@ -1761,6 +2184,30 @@ object TunnelManager {
|
||||
fun isNetworkTransitionGraceActive(now: Long = System.currentTimeMillis()): Boolean =
|
||||
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? {
|
||||
val issue = connectionIssue.value ?: return null
|
||||
if (!running.value) return null
|
||||
@@ -1788,10 +2235,14 @@ object TunnelManager {
|
||||
}
|
||||
|
||||
fun hasFreshTunnelActivitySince(sinceMs: Long, now: Long = System.currentTimeMillis()): Boolean {
|
||||
if (!running.value || activeWorkers.value <= 0) return false
|
||||
val freshActive = lastActiveAtMs >= sinceMs && now - lastActiveAtMs < 90_000L
|
||||
val freshStats = lastStatsAtMs >= sinceMs && now - lastStatsAtMs < 90_000L
|
||||
return (freshActive || freshStats) && !isStatsTrafficStagnant(now)
|
||||
return hasFreshTransportHeartbeat(
|
||||
running = running.value,
|
||||
activeWorkers = activeWorkers.value,
|
||||
lastActiveAtMs = lastActiveAtMs,
|
||||
lastStatsAtMs = lastStatsAtMs,
|
||||
sinceMs = sinceMs,
|
||||
nowMs = now,
|
||||
)
|
||||
}
|
||||
|
||||
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() {
|
||||
updateWarningLog(
|
||||
"wake_rescue_reconnect",
|
||||
@@ -1837,15 +2323,16 @@ object TunnelManager {
|
||||
fun recreateVpnTunnel() {
|
||||
val params = currentParams ?: return
|
||||
val context = lastContext ?: return
|
||||
updateWarningLog("network_full_restart", "[СЕТЬ] Мягкие попытки не помогли, пересоздаём VPN", 50)
|
||||
updateWarningLog("network_full_restart", "[VPN] Android потерял системный VPN-интерфейс, создаём его заново", 50)
|
||||
scope.launch {
|
||||
withContext(Dispatchers.Main) {
|
||||
wgHelper?.stopTunnel()
|
||||
}
|
||||
sessionTraffic.noteTransportRestart()
|
||||
killProcess()
|
||||
activeWorkers.value = 0
|
||||
delay(2500)
|
||||
if (currentParams != null) {
|
||||
if (currentParams === params && running.value) {
|
||||
start(context, params, isSwitching = true)
|
||||
}
|
||||
}
|
||||
@@ -1867,6 +2354,7 @@ object TunnelManager {
|
||||
|
||||
fun pause() {
|
||||
if (!running.value) return
|
||||
sessionTraffic.noteTransportRestart()
|
||||
killProcess()
|
||||
activeWorkers.value = 0
|
||||
resetStatsLivenessState()
|
||||
@@ -1904,9 +2392,18 @@ object TunnelManager {
|
||||
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() {
|
||||
sessionTraffic.noteTransportRestart()
|
||||
killProcess()
|
||||
running.value = false
|
||||
}
|
||||
@@ -1918,29 +2415,13 @@ object TunnelManager {
|
||||
updateLog("stats", "[СТАТИСТИКА] $stoppedStats", 3, false)
|
||||
}
|
||||
|
||||
fun onWireGuardStoppedExternally() {
|
||||
noteStopRequested()
|
||||
scope.launch {
|
||||
startStopMutex.lock()
|
||||
try {
|
||||
if (!running.value) return@launch
|
||||
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 onWireGuardInterfaceDropped() {
|
||||
if (!running.value) return
|
||||
updateWarningLog(
|
||||
"vpn_interface_dropped",
|
||||
"[VPN] Android сообщил о потере системного VPN-интерфейса. Проверяем состояние перед восстановлением.",
|
||||
50,
|
||||
)
|
||||
}
|
||||
|
||||
fun stop(reason: TunnelStopReason = TunnelStopReason.User) {
|
||||
@@ -1958,6 +2439,7 @@ object TunnelManager {
|
||||
resetStatsLivenessState()
|
||||
currentParams = null
|
||||
resetNetworkRecoveryState()
|
||||
wakeRecoveryGraceUntilMs = 0L
|
||||
ManlCaptchaWebViewManager.cancelCaptcha()
|
||||
} finally {
|
||||
if (reason == TunnelStopReason.User) {
|
||||
@@ -1992,6 +2474,7 @@ object TunnelManager {
|
||||
resetStatsLivenessState()
|
||||
currentParams = null
|
||||
resetNetworkRecoveryState()
|
||||
wakeRecoveryGraceUntilMs = 0L
|
||||
ManlCaptchaWebViewManager.cancelCaptcha()
|
||||
}
|
||||
} finally {
|
||||
@@ -2173,6 +2656,10 @@ data class TunnelParams(
|
||||
val connectionPassword: String = "",
|
||||
val protocol: String = "udp",
|
||||
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 captchaSolveMethod: String = "auto",
|
||||
val fingerprint: String = "firefox",
|
||||
|
||||
@@ -34,6 +34,7 @@ import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
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_LOSS_GRACE_MS = 2 * 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 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_EXIT_DELAY_MS = 5_000L
|
||||
private const val TRUSTED_WIFI_RESUME_START_TIMEOUT_MS = 30_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() {
|
||||
private val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
|
||||
private val startRequestGate = TunnelStartRequestGate()
|
||||
@@ -83,9 +124,16 @@ class TunnelService : Service() {
|
||||
private var lastValidatedNetwork: Network? = null
|
||||
private var lastStableNetworkReconnectAt = 0L
|
||||
private var stableNetworkWasLost = false
|
||||
private var vpnInterfaceMissingSinceMs = 0L
|
||||
private var lastVpnInterfaceRecoveryAttemptAtMs = 0L
|
||||
private var screenStateReceiver: BroadcastReceiver? = null
|
||||
private var trustedWifiStateReceiver: BroadcastReceiver? = 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 trustedWifiSettingsJob: Job? = null
|
||||
private var trustedWifiEvaluationJob: Job? = null
|
||||
@@ -107,6 +155,10 @@ class TunnelService : Service() {
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
createNotificationChannel()
|
||||
lastKnownDeviceInteractive = isDeviceInteractive()
|
||||
if (!lastKnownDeviceInteractive) {
|
||||
TunnelManager.noteDeviceSleepStarted()
|
||||
}
|
||||
// Сразу берем лок при создании
|
||||
acquireWakeLock()
|
||||
setupNetworkCallback()
|
||||
@@ -121,6 +173,7 @@ class TunnelService : Service() {
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
if (intent == null) {
|
||||
restoreTunnel()
|
||||
scheduleSleepPauseIfNeeded()
|
||||
return START_STICKY
|
||||
}
|
||||
|
||||
@@ -139,6 +192,11 @@ class TunnelService : Service() {
|
||||
connectionPassword = intent.getStringExtra("connection_password") ?: "",
|
||||
protocol = intent.getStringExtra("protocol") ?: "udp",
|
||||
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")),
|
||||
captchaSolveMethod = intent.getStringExtra("captcha_solve_method") ?: "auto",
|
||||
fingerprint = intent.getStringExtra("fingerprint") ?: "firefox",
|
||||
@@ -152,6 +210,7 @@ class TunnelService : Service() {
|
||||
profileIndex = intent.getIntExtra(TUNNEL_PROFILE_INDEX_EXTRA, 0).coerceIn(0, 2),
|
||||
)
|
||||
requestTunnelStart(params)
|
||||
scheduleSleepPauseIfNeeded()
|
||||
}
|
||||
"STOP" -> stopTunnel(TunnelStopReason.User)
|
||||
"DEPLOY_START" -> {
|
||||
@@ -359,6 +418,8 @@ class TunnelService : Service() {
|
||||
cancelTrustedWifiResumeRetry(resetCount = !fromTrustedWifiResume)
|
||||
trustedWifiResumeInProgress = fromTrustedWifiResume
|
||||
trustedWifiResumeStartedAt = if (fromTrustedWifiResume) System.currentTimeMillis() else 0L
|
||||
sleepPausedByPolicy = false
|
||||
isTunnelPaused = false
|
||||
trustedWifiWaiting = false
|
||||
trustedWifiWaitingSsid = ""
|
||||
lastStartParams = params
|
||||
@@ -386,11 +447,16 @@ class TunnelService : Service() {
|
||||
startNotificationProfileWatcher()
|
||||
startStatsUpdater()
|
||||
startActiveProfileRefresh(params.profileIndex)
|
||||
scheduleSleepPauseIfNeeded()
|
||||
}
|
||||
|
||||
private fun stopTunnel(reason: TunnelStopReason = TunnelStopReason.User) {
|
||||
TunnelManager.noteStopRequested()
|
||||
if (stopSequenceJob?.isActive == true) return
|
||||
sleepPausedByPolicy = false
|
||||
sleepPauseJob?.cancel()
|
||||
sleepPauseJob = null
|
||||
isTunnelPaused = false
|
||||
invalidatePendingStart()
|
||||
val effectiveReason = requestedStopReason ?: reason
|
||||
requestedStopReason = effectiveReason
|
||||
@@ -512,12 +578,16 @@ class TunnelService : Service() {
|
||||
override fun onReceive(context: Context?, intent: Intent?) {
|
||||
when (intent?.action) {
|
||||
Intent.ACTION_SCREEN_ON -> {
|
||||
observeDeviceInteractiveState(interactive = true)
|
||||
resumeSleepPausedTunnelIfNeeded()
|
||||
scheduleWakeRescueCheck()
|
||||
scheduleTrustedWifiEvaluation(delayMs = 0L)
|
||||
}
|
||||
Intent.ACTION_SCREEN_OFF -> {
|
||||
observeDeviceInteractiveState(interactive = false)
|
||||
wakeRescueJob?.cancel()
|
||||
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() {
|
||||
if (trustedWifiStateReceiver != null) return
|
||||
trustedWifiStateReceiver = object : BroadcastReceiver() {
|
||||
@@ -586,52 +736,21 @@ class TunnelService : Service() {
|
||||
|
||||
private fun scheduleWakeRescueCheck() {
|
||||
if (!AMNEZIA_STYLE_RECOVERY || !TunnelManager.running.value || isTunnelPaused || TunnelManager.isCaptchaInProgress()) return
|
||||
val wakeAt = System.currentTimeMillis()
|
||||
TunnelManager.noteWakeRescueStarted()
|
||||
updateNotification("Проверка VPN после сна...")
|
||||
|
||||
wakeRescueJob?.cancel()
|
||||
wakeRescueJob = TunnelManager.scope.launch(Dispatchers.Main) {
|
||||
delay(WAKE_RESCUE_GRACE_MS)
|
||||
if (!TunnelManager.running.value || isTunnelPaused || TunnelManager.isCaptchaInProgress()) return@launch
|
||||
if (TunnelManager.hasFreshTunnelActivitySince(wakeAt)) {
|
||||
if (TunnelManager.hasFreshTunnelActivitySince(System.currentTimeMillis() - WAKE_RESCUE_GRACE_MS)) {
|
||||
TunnelManager.noteWakeRescueHealthy()
|
||||
updateNotification(buildTunnelNotificationText())
|
||||
return@launch
|
||||
} else {
|
||||
// Выход из сна сам по себе не является доказательством поломки:
|
||||
// Android и оператор могут на короткое время задержать вывод статистики.
|
||||
// Не перезапускаем ни native-транспорт, ни системный VPN-интерфейс.
|
||||
TunnelManager.noteWakeRescueDeferred()
|
||||
}
|
||||
|
||||
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)
|
||||
updateNotification(buildTunnelNotificationText())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1147,6 +1266,7 @@ class TunnelService : Service() {
|
||||
|
||||
private fun scheduleStableValidatedReconnect(reason: String) {
|
||||
val now = System.currentTimeMillis()
|
||||
val interactiveAtSchedule = isDeviceInteractive()
|
||||
lastNetworkChangeTime = now
|
||||
|
||||
if (!TunnelManager.running.value || isTunnelPaused) return
|
||||
@@ -1163,6 +1283,18 @@ class TunnelService : Service() {
|
||||
Log.d("TunnelService", "$reason, ждём короткую стабилизацию перед reconnect")
|
||||
delay(recoveryPolicy.networkSettleDelayMs)
|
||||
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
|
||||
|
||||
val sinceLastReconnect = System.currentTimeMillis() - lastStableNetworkReconnectAt
|
||||
@@ -1170,6 +1302,10 @@ class TunnelService : Service() {
|
||||
Log.d("TunnelService", "Пропускаем reconnect: недавний reconnect уже был")
|
||||
return@launch
|
||||
}
|
||||
if (TunnelManager.hasFreshTunnelActivitySince(now)) {
|
||||
Log.d("TunnelService", "Пропускаем reconnect: транспорт уже активен на подтверждённой сети")
|
||||
return@launch
|
||||
}
|
||||
lastStableNetworkReconnectAt = System.currentTimeMillis()
|
||||
TunnelManager.restartTransport(
|
||||
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")
|
||||
private fun hasUsableRealNetworkForTrustedWifiResume(): Boolean {
|
||||
return trustedWifiValidatedNetworks.hasUsableNetwork()
|
||||
@@ -1385,6 +1545,15 @@ class TunnelService : Service() {
|
||||
if (
|
||||
!shouldKeepTunnelServiceAlive(
|
||||
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,
|
||||
trustedWifiWaiting = trustedWifiWaiting,
|
||||
trustedWifiResumeInProgress = trustedWifiResumeInProgress
|
||||
@@ -1403,12 +1572,51 @@ class TunnelService : Service() {
|
||||
stopTunnel(TunnelStopReason.VpnSlotTransferred)
|
||||
break
|
||||
}
|
||||
if (!startupWindow && !captchaActive && !helper.isTunnelUp()) {
|
||||
Log.w("TunnelService", "Обнаружена пропажа или замена VPN-интерфейса! Экстренное выключение туннеля.")
|
||||
stopTunnel(TunnelStopReason.VpnInterfaceLost)
|
||||
break
|
||||
val deviceInteractive = isDeviceInteractive()
|
||||
// Не полагаемся только на broadcast: после глубокого сна первая
|
||||
// итерация службы иногда выполняется раньше ACTION_SCREEN_ON.
|
||||
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()) {
|
||||
NetworkRecoveryAction.SoftRestart -> {
|
||||
Log.w("TunnelService", "Сетевая ошибка туннеля. Мягко перезапускаем транспорт.")
|
||||
@@ -1417,11 +1625,6 @@ class TunnelService : Service() {
|
||||
minIntervalMs = 20_000L
|
||||
)
|
||||
}
|
||||
NetworkRecoveryAction.RecreateVpn -> {
|
||||
Log.w("TunnelService", "Мягкие попытки не помогли. Пересоздаём VPN-туннель.")
|
||||
updateNotification("Пересоздание VPN...")
|
||||
TunnelManager.recreateVpnTunnel()
|
||||
}
|
||||
NetworkRecoveryAction.StopVpn -> {
|
||||
Log.w("TunnelService", "Автовосстановление не помогло. Останавливаем VPN, чтобы вернуть интернет.")
|
||||
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 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(
|
||||
val networkSettleDelayMs: Long,
|
||||
@@ -15,18 +42,12 @@ internal data class TransportRecoveryPolicy(
|
||||
|
||||
internal fun transportRecoveryPolicy(
|
||||
managedConfigFirstStart: Boolean,
|
||||
): TransportRecoveryPolicy = if (managedConfigFirstStart) {
|
||||
TransportRecoveryPolicy(
|
||||
networkSettleDelayMs = 3_000L,
|
||||
reconnectMinIntervalMs = 8_000L,
|
||||
processRestartDelayMs = 250L,
|
||||
forceRestart = true,
|
||||
)
|
||||
} else {
|
||||
TransportRecoveryPolicy(
|
||||
): TransportRecoveryPolicy {
|
||||
val processRestartDelayMs = if (managedConfigFirstStart) 250L else 2_500L
|
||||
return TransportRecoveryPolicy(
|
||||
networkSettleDelayMs = 15_000L,
|
||||
reconnectMinIntervalMs = 2 * 60_000L,
|
||||
processRestartDelayMs = 2_500L,
|
||||
processRestartDelayMs = processRestartDelayMs,
|
||||
forceRestart = false,
|
||||
)
|
||||
}
|
||||
@@ -96,6 +117,11 @@ internal fun buildTunnelParams(saved: TunnelProfileSnapshot): TunnelParams? {
|
||||
connectionPassword = linkParts.password,
|
||||
protocol = saved.protocol,
|
||||
vkCallsPreflight = saved.vkCallsPreflight,
|
||||
rtNetwork = saved.rtNetwork,
|
||||
rtMasque = saved.rtMasque,
|
||||
rtMasqueServerBootstrap =
|
||||
saved.rtMasqueServerBootstrap && saved.rtMasqueServerAccessReady,
|
||||
rtTurnSni = saved.rtTurnSni,
|
||||
captchaMode = sanitizeTunnelCaptchaMode(saved.captchaMode),
|
||||
captchaSolveMethod = saved.captchaSolveMethod,
|
||||
fingerprint = saved.fingerprint,
|
||||
@@ -127,6 +153,11 @@ internal fun buildTunnelParams(saved: TunnelProfileSnapshot): TunnelParams? {
|
||||
connectionPassword = password,
|
||||
protocol = saved.protocol,
|
||||
vkCallsPreflight = saved.vkCallsPreflight,
|
||||
rtNetwork = saved.rtNetwork,
|
||||
rtMasque = saved.rtMasque,
|
||||
rtMasqueServerBootstrap =
|
||||
saved.rtMasqueServerBootstrap && saved.rtMasqueServerAccessReady,
|
||||
rtTurnSni = saved.rtTurnSni,
|
||||
captchaMode = sanitizeTunnelCaptchaMode(saved.captchaMode),
|
||||
captchaSolveMethod = saved.captchaSolveMethod,
|
||||
fingerprint = saved.fingerprint,
|
||||
@@ -154,6 +185,10 @@ suspend fun buildTunnelStartIntentFromSettings(context: Context): Intent? {
|
||||
putExtra("connection_password", params.connectionPassword)
|
||||
putExtra("protocol", params.protocol)
|
||||
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_solve_method", params.captchaSolveMethod)
|
||||
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.SupervisorJob
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
internal fun shouldClearPhantomVpn(activeTunnelProfile: Int?): Boolean =
|
||||
activeTunnelProfile == null
|
||||
|
||||
class WdttApplication : Application() {
|
||||
@Volatile
|
||||
private var backendInstance: GoBackend? = null
|
||||
@@ -21,12 +25,19 @@ class WdttApplication : Application() {
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
DeployManager.init(this)
|
||||
|
||||
// Очищаем фантомный VPN при холодном старте приложения (например, после перезагрузки телефона).
|
||||
// Если телефон перезагрузился, система Android пытается сама восстановить VpnService,
|
||||
// что приводит к фантомному ключу без интернета. Этот код мгновенно сбрасывает статус в DOWN.
|
||||
|
||||
val settingsStore = SettingsStore(this)
|
||||
|
||||
// Очищаем только действительно бесхозный фантомный VPN. Если сохранён активный
|
||||
// профиль, Android одновременно восстанавливает TunnelService: безусловный DOWN
|
||||
// здесь мог опередить или оборвать штатное восстановление и затем вызвать новый UP.
|
||||
CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {
|
||||
runCatching {
|
||||
val activeTunnelProfile = settingsStore.activeTunnelProfile.first()
|
||||
if (!shouldClearPhantomVpn(activeTunnelProfile)) {
|
||||
Log.d("WdttApp", "Ожидается восстановление активного VPN; очистка фантома пропущена")
|
||||
return@runCatching
|
||||
}
|
||||
val backend = getBackend(this@WdttApplication)
|
||||
val tunnel = WireGuardHelper.WgTunnel()
|
||||
backend.setState(tunnel, Tunnel.State.DOWN, null)
|
||||
@@ -35,8 +46,6 @@ class WdttApplication : Application() {
|
||||
Log.w("WdttApp", "Не удалось очистить фантомный VPN: ${it.message}")
|
||||
}
|
||||
}
|
||||
|
||||
val settingsStore = SettingsStore(this)
|
||||
CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {
|
||||
RemoteActionCatalogGateway.fetch(force = true)
|
||||
}
|
||||
|
||||
@@ -153,7 +153,7 @@ class WireGuardHelper(context: Context) {
|
||||
}
|
||||
|
||||
val nextTunnel = WgTunnel {
|
||||
TunnelManager.onWireGuardStoppedExternally()
|
||||
TunnelManager.onWireGuardInterfaceDropped()
|
||||
}
|
||||
setTunnelUpWithRetry(nextTunnel, finalConfig)
|
||||
sharedTunnel = nextTunnel
|
||||
|
||||
@@ -70,6 +70,7 @@ private const val PROFILE_RESET_TIMEOUT_MS = 10_000L
|
||||
@OptIn(ExperimentalLayoutApi::class, ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
fun FloatingToolbar(
|
||||
settingsStore: SettingsStore,
|
||||
activeProfile: Int,
|
||||
profileNames: List<String>,
|
||||
onActiveProfileChange: (Int) -> Unit,
|
||||
@@ -92,10 +93,10 @@ fun FloatingToolbar(
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val settingsStore = remember { SettingsStore(context) }
|
||||
val trustedWifiEnabled by settingsStore.trustedWifiEnabled.collectAsStateWithLifecycle(initialValue = false)
|
||||
val trustedWifiSsids by settingsStore.trustedWifiSsids.collectAsStateWithLifecycle(initialValue = emptyList())
|
||||
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 customVkCredentialsComplete by settingsStore.customVkCredentialsComplete.collectAsStateWithLifecycle(initialValue = false)
|
||||
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(
|
||||
modifier = Modifier.padding(vertical = 4.dp),
|
||||
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f)
|
||||
|
||||
@@ -8,8 +8,6 @@ import android.content.ClipboardManager
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.ConnectivityManager
|
||||
import android.net.NetworkCapabilities
|
||||
import android.net.Uri
|
||||
import android.net.VpnService
|
||||
import android.os.Build
|
||||
@@ -23,7 +21,10 @@ import android.widget.Toast
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
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.tween
|
||||
import androidx.compose.animation.expandVertically
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
@@ -117,10 +118,13 @@ import com.wdtt.plus.RemoteActionForm
|
||||
import com.wdtt.plus.RemoteContinuationLauncher
|
||||
import com.wdtt.plus.RemoteUiAction
|
||||
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.TunnelManager
|
||||
import com.wdtt.plus.TrustedWifiManager
|
||||
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_UPDATE
|
||||
import com.wdtt.plus.WDTTColors
|
||||
@@ -139,6 +143,7 @@ import com.wdtt.plus.selectUpdateApkAsset
|
||||
import com.wdtt.plus.deviceCheckActionIntent
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
@@ -260,6 +265,7 @@ fun InfoTab(
|
||||
var showHelpDialog by remember { mutableStateOf(false) }
|
||||
var showQuestionDialog by remember { mutableStateOf(false) }
|
||||
var showSupportDialog by remember { mutableStateOf(false) }
|
||||
var highlightNoServerBlock by remember { mutableStateOf(false) }
|
||||
var pendingActionForm by remember { mutableStateOf<RemoteUiAction?>(null) }
|
||||
var actionCatalog by remember { mutableStateOf(RemoteActionCatalogGateway.cached()) }
|
||||
var questionAction by remember { mutableStateOf<RemoteUiAction?>(null) }
|
||||
@@ -270,6 +276,7 @@ fun InfoTab(
|
||||
var projectExpanded by projectExpandedState
|
||||
LaunchedEffect(projectSupportDialogRequest) {
|
||||
if (projectSupportDialogRequest > 0) {
|
||||
highlightNoServerBlock = true
|
||||
showSupportDialog = true
|
||||
onProjectSupportDialogRequestConsumed()
|
||||
}
|
||||
@@ -353,6 +360,7 @@ fun InfoTab(
|
||||
latestRelease = latestRelease
|
||||
)
|
||||
val workers = runCatching { settingsStore.workersPerHash.first() }.getOrNull()
|
||||
val tunnelProfile = runCatching { settingsStore.tunnelProfileSnapshot() }.getOrNull()
|
||||
val diagnosticsSummary = withContext(Dispatchers.Default) {
|
||||
buildSupportReportSummary(context.applicationContext, settingsStore)
|
||||
}
|
||||
@@ -385,7 +393,12 @@ fun InfoTab(
|
||||
return report.copy(
|
||||
summaryLines = diagnosticsSummary + clientNetworkDiagnostics.summaryLines,
|
||||
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
|
||||
)
|
||||
}
|
||||
@@ -415,6 +428,7 @@ fun InfoTab(
|
||||
currentVersion = currentVersion,
|
||||
releaseDate = releaseDate,
|
||||
onSupportClick = {
|
||||
highlightNoServerBlock = false
|
||||
showSupportDialog = true
|
||||
}
|
||||
)
|
||||
@@ -469,7 +483,7 @@ fun InfoTab(
|
||||
WideActionTile(
|
||||
title = "Проверить устройство",
|
||||
subtitle = if (isCheckingDevice) {
|
||||
"Проверяем версию, Android, ABI, сеть и системные условия..."
|
||||
"Проверяем Android, ABI, 16 КиБ, WireGuard, режим РТ и сеть..."
|
||||
} else {
|
||||
"Проверка совместимости и полный отчёт для диагностики"
|
||||
},
|
||||
@@ -790,10 +804,16 @@ fun InfoTab(
|
||||
}
|
||||
if (showSupportDialog) {
|
||||
AdditionalActionsDialog(
|
||||
onDismiss = { showSupportDialog = false },
|
||||
onDismiss = {
|
||||
highlightNoServerBlock = false
|
||||
showSupportDialog = false
|
||||
},
|
||||
primaryAction = actionCatalog.at("about"),
|
||||
secondaryAction = actionCatalog.at("tunnel"),
|
||||
highlightSecondaryAction = highlightNoServerBlock,
|
||||
onSecondaryHighlightConsumed = { highlightNoServerBlock = false },
|
||||
onActionClick = { action ->
|
||||
highlightNoServerBlock = false
|
||||
if (action.form != null) {
|
||||
showSupportDialog = false
|
||||
pendingActionForm = action
|
||||
@@ -811,10 +831,12 @@ fun InfoTab(
|
||||
}
|
||||
},
|
||||
onProjectFallbackClick = {
|
||||
highlightNoServerBlock = false
|
||||
showSupportDialog = false
|
||||
openUrlInBrowser(context, ProjectDonateFallbackUrl)
|
||||
},
|
||||
onDonateOriginalClick = {
|
||||
highlightNoServerBlock = false
|
||||
showSupportDialog = false
|
||||
openUrlInBrowser(context, OriginalDonateUrl)
|
||||
}
|
||||
@@ -970,6 +992,8 @@ private fun AdditionalActionsDialog(
|
||||
onDismiss: () -> Unit,
|
||||
primaryAction: RemoteUiAction?,
|
||||
secondaryAction: RemoteUiAction?,
|
||||
highlightSecondaryAction: Boolean,
|
||||
onSecondaryHighlightConsumed: () -> Unit,
|
||||
onActionClick: (RemoteUiAction) -> Unit,
|
||||
onProjectFallbackClick: () -> Unit,
|
||||
onDonateOriginalClick: () -> Unit
|
||||
@@ -1034,7 +1058,7 @@ private fun AdditionalActionsDialog(
|
||||
ExternalSupportBlock(
|
||||
title = primaryAction.title,
|
||||
body = primaryAction.message,
|
||||
buttonText = primaryAction.label,
|
||||
buttonText = "Поддержать проект",
|
||||
onClick = { onActionClick(primaryAction) },
|
||||
emphasized = true,
|
||||
)
|
||||
@@ -1054,6 +1078,8 @@ private fun AdditionalActionsDialog(
|
||||
secondaryAction?.let { action ->
|
||||
RemoteInfoActionBlock(
|
||||
action = action,
|
||||
highlightRequested = highlightSecondaryAction,
|
||||
onHighlightConsumed = onSecondaryHighlightConsumed,
|
||||
onClick = { onActionClick(action) },
|
||||
)
|
||||
}
|
||||
@@ -1088,6 +1114,19 @@ private fun RemoteActionFormDialog(
|
||||
var fallbackAvailable by remember(form.token) { mutableStateOf(false) }
|
||||
val numericValue = valueText.toLongOrNull()
|
||||
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) {
|
||||
valueText = value
|
||||
@@ -1268,7 +1307,7 @@ private fun RemoteActionFormDialog(
|
||||
Text(form.busyLabel, fontWeight = FontWeight.Bold)
|
||||
} else {
|
||||
Text(
|
||||
form.submitLabel.replace("{value}", valueText),
|
||||
supportButtonLabel,
|
||||
fontWeight = FontWeight.Bold,
|
||||
)
|
||||
}
|
||||
@@ -1298,16 +1337,44 @@ private fun RemoteActionFormDialog(
|
||||
@Composable
|
||||
private fun RemoteInfoActionBlock(
|
||||
action: RemoteUiAction,
|
||||
highlightRequested: Boolean = false,
|
||||
onHighlightConsumed: () -> 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(
|
||||
shape = RoundedCornerShape(18.dp),
|
||||
color = MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.48f),
|
||||
contentColor = MaterialTheme.colorScheme.onSecondaryContainer,
|
||||
border = BorderStroke(
|
||||
1.dp,
|
||||
MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.45f)
|
||||
)
|
||||
border = BorderStroke(borderWidth, borderColor),
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().padding(14.dp),
|
||||
@@ -1930,41 +1997,14 @@ private suspend fun buildSupportReportSummary(context: Context, settingsStore: S
|
||||
"без ограничений батареи=${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 {
|
||||
WebView.getCurrentWebViewPackage()?.let { "${it.packageName} ${it.versionName}" }
|
||||
}
|
||||
val nativeClientInfo = runCatching {
|
||||
val nativeComponentsInfo = runCatching {
|
||||
val nativeClient = File(appInfo?.nativeLibraryDir.orEmpty(), "libclient.so")
|
||||
if (nativeClient.isFile) {
|
||||
"найден, ${formatMiB(nativeClient.length())}, executable=${nativeClient.canExecute()}"
|
||||
} else {
|
||||
"не найден"
|
||||
}
|
||||
val wireGuardBackend = File(appInfo?.nativeLibraryDir.orEmpty(), "libwg-go.so")
|
||||
"libclient.so=${if (nativeClient.isFile) formatMiB(nativeClient.length()) else "не найден"}, " +
|
||||
"libwg-go.so=${if (wireGuardBackend.isFile) formatMiB(wireGuardBackend.length()) else "не найден"}"
|
||||
}.getOrDefault("недоступно")
|
||||
|
||||
val notificationPermission = diagnosticText {
|
||||
@@ -1994,6 +2034,18 @@ private suspend fun buildSupportReportSummary(context: Context, settingsStore: S
|
||||
.coerceAtMost(4)
|
||||
val hasSecondaryHash = runCatching { settingsStore.secondaryVkHash.first().isNotBlank() }.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 customVkCredentialsComplete = runCatching { settingsStore.customVkCredentialsComplete.first() }.getOrNull()
|
||||
val builtInVkClientCount = runCatching {
|
||||
@@ -2052,10 +2104,8 @@ private suspend fun buildSupportReportSummary(context: Context, settingsStore: S
|
||||
appendLine("Low-RAM устройство: $lowRamDevice")
|
||||
appendLine("Хранилище приложения: $storageSummary")
|
||||
appendLine("Питание: $powerSummary")
|
||||
appendLine("Сеть: $networkSummary")
|
||||
appendLine("Private DNS: $privateDns")
|
||||
appendLine("WebView: $webViewInfo")
|
||||
appendLine("Нативный клиент: $nativeClientInfo")
|
||||
appendLine("Нативные компоненты: $nativeComponentsInfo")
|
||||
appendLine("Экран: $screenSummary")
|
||||
appendLine("Разрешение уведомлений: $notificationPermission")
|
||||
appendLine("Установка обновлений APK: $updateInstallPermission")
|
||||
@@ -2072,6 +2122,12 @@ private suspend fun buildSupportReportSummary(context: Context, settingsStore: S
|
||||
appendLine("Потоки: ${workers ?: "недоступно"}")
|
||||
appendLine("VK-хеши: заполнено $hashCount, запасной=${hasSecondaryHash ?: "недоступно"}")
|
||||
appendLine("Быстрый VKCalls: ${vkCallsEnabled ?: "недоступно"}")
|
||||
appendLine("Сеть РТ (TURN stream-first): ${rtNetworkEnabled ?: "недоступно"}")
|
||||
appendLine(
|
||||
"MASQUE в Сети РТ (HTTP/2 → HTTP/3): ${rtMasqueEnabled ?: "недоступно"}, " +
|
||||
"регистрация WARP=$rtMasqueEnrollment, " +
|
||||
"первая регистрация через сервер=${rtMasqueServerBootstrap ?: "недоступно"}"
|
||||
)
|
||||
appendLine(
|
||||
"Резерв VK: собственные=${customVkCredentialsEnabled ?: "недоступно"}, " +
|
||||
"заполнены=${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
Reference in new issue
Block a user