Выпуск WDTT Plus v15
This commit is contained in:
1 parent
3d2c277b06
commit
947551c176
65 files changed
+12788
-1338
No files matched your search
@@ -114,6 +114,86 @@ private val vkHttpsTargets = listOf(
|
||||
suspend fun collectClientNetworkDiagnostics(context: Context): ClientNetworkDiagnosticsReport =
|
||||
collectClientNetworkDiagnostics(context, retryOnNetworkChange = true)
|
||||
|
||||
internal suspend fun collectVpnDnsRuntimeDiagnostic(
|
||||
context: Context,
|
||||
settings: VpnDnsSettingsSnapshot,
|
||||
tunnelRunning: Boolean,
|
||||
runningProfile: Int?,
|
||||
): DeviceCheckItem? = withContext(Dispatchers.IO) {
|
||||
if (
|
||||
!tunnelRunning ||
|
||||
runningProfile != settings.profileIndex ||
|
||||
settings.selectionId == VPN_DNS_PROFILE_ID ||
|
||||
settings.configuredServers.isEmpty()
|
||||
) {
|
||||
return@withContext null
|
||||
}
|
||||
|
||||
val connectivityManager = context.getSystemService(ConnectivityManager::class.java)
|
||||
?: return@withContext null
|
||||
val network = runCatching { connectivityManager.activeNetwork }.getOrNull()
|
||||
val capabilities = network?.let {
|
||||
runCatching { connectivityManager.getNetworkCapabilities(it) }.getOrNull()
|
||||
}
|
||||
if (network == null || capabilities?.hasTransport(NetworkCapabilities.TRANSPORT_VPN) != true) {
|
||||
return@withContext DeviceCheckItem(
|
||||
title = "Доступность выбранного DNS внутри VPN",
|
||||
status = "VPN-сеть Android не найдена",
|
||||
details = "Туннель отмечен как запущенный, но Android не вернул активную VPN-сеть для безопасной проверки выбранного DNS.",
|
||||
recommendation = "Подождите несколько секунд и повторите проверку. Если интернет не работает, переподключите VPN.",
|
||||
severity = DeviceCheckSeverity.Warning,
|
||||
)
|
||||
}
|
||||
|
||||
val servers = settings.configuredServers.distinct()
|
||||
val results = coroutineScope {
|
||||
servers.flatMap { server ->
|
||||
listOf(
|
||||
async(Dispatchers.IO) {
|
||||
timedProbe("$server UDP") {
|
||||
directDnsQuery(network, server, useTcp = false, host = "example.com")
|
||||
}
|
||||
},
|
||||
async(Dispatchers.IO) {
|
||||
timedProbe("$server TCP") {
|
||||
directDnsQuery(network, server, useTcp = true, host = "example.com")
|
||||
}
|
||||
},
|
||||
)
|
||||
}.awaitAll()
|
||||
}
|
||||
val networkAfterProbe = runCatching { connectivityManager.activeNetwork }.getOrNull()
|
||||
if (networkAfterProbe != network) {
|
||||
return@withContext DeviceCheckItem(
|
||||
title = "Доступность выбранного DNS внутри VPN",
|
||||
status = "сеть изменилась во время проверки",
|
||||
details = "Результаты для прежней VPN-сети отброшены.",
|
||||
recommendation = "Дождитесь устойчивого подключения и повторите проверку устройства.",
|
||||
severity = DeviceCheckSeverity.Info,
|
||||
)
|
||||
}
|
||||
|
||||
val respondingServers = servers.count { server ->
|
||||
results.any { result -> result.success && result.label.startsWith("$server ") }
|
||||
}
|
||||
DeviceCheckItem(
|
||||
title = "Доступность выбранного DNS внутри VPN",
|
||||
status = "$respondingServers из ${servers.size} серверов отвечают",
|
||||
details = results.joinToString(". ") { it.display() } +
|
||||
". Проверка выполнена через активную VPN-сеть; достаточно ответа по UDP или TCP.",
|
||||
recommendation = if (respondingServers == servers.size) {
|
||||
""
|
||||
} else {
|
||||
"Выберите другой вариант в «Туннель → DNS внутри VPN» либо верните «Как в профиле» и повторите проверку."
|
||||
},
|
||||
severity = if (respondingServers == servers.size) {
|
||||
DeviceCheckSeverity.Ok
|
||||
} else {
|
||||
DeviceCheckSeverity.Warning
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
private suspend fun collectClientNetworkDiagnostics(
|
||||
context: Context,
|
||||
retryOnNetworkChange: Boolean
|
||||
@@ -464,9 +544,14 @@ private suspend fun probeClientDns(network: Network): List<NetworkProbeResult> =
|
||||
}.awaitAll()
|
||||
}
|
||||
|
||||
private fun directDnsQuery(network: Network, server: String, useTcp: Boolean): String {
|
||||
private fun directDnsQuery(
|
||||
network: Network,
|
||||
server: String,
|
||||
useTcp: Boolean,
|
||||
host: String = clientDnsProbeHost,
|
||||
): String {
|
||||
val queryId = (SystemClock.elapsedRealtimeNanos() and 0xffff).toInt()
|
||||
val query = buildDnsQuery(clientDnsProbeHost, queryId)
|
||||
val query = buildDnsQuery(host, queryId)
|
||||
val response = if (useTcp) {
|
||||
Socket().use { socket ->
|
||||
network.bindSocket(socket)
|
||||
|
||||
@@ -162,6 +162,288 @@ internal fun pageSizeCompatibilityItem(
|
||||
)
|
||||
}
|
||||
|
||||
internal fun tunnelHealthItem(
|
||||
running: Boolean,
|
||||
activeWorkers: Int,
|
||||
issue: ConnectionIssue?,
|
||||
confirmedNetworkFailure: Boolean,
|
||||
): DeviceCheckItem = when {
|
||||
!running -> DeviceCheckItem(
|
||||
title = "Текущее подключение VPN",
|
||||
status = "не активно",
|
||||
details = "VPN сейчас не подключён. Это не мешает проверке устройства; пункт фиксирует текущее состояние туннеля.",
|
||||
recommendation = issue?.let { "${it.title}: ${it.action}" }.orEmpty(),
|
||||
severity = DeviceCheckSeverity.Info,
|
||||
)
|
||||
confirmedNetworkFailure -> DeviceCheckItem(
|
||||
title = "Текущее подключение VPN",
|
||||
status = "нет ответа на пользовательский трафик",
|
||||
details = "VPN-интерфейс включён, активных каналов: $activeWorkers, но приложение подтвердило отсутствие ответов на переданный трафик.",
|
||||
recommendation = issue?.let { "${it.title}: ${it.action}" }
|
||||
?: "WDTT Plus автоматически проверит восстановление и при необходимости переподключит VPN.",
|
||||
severity = DeviceCheckSeverity.Warning,
|
||||
)
|
||||
issue != null -> DeviceCheckItem(
|
||||
title = "Текущее подключение VPN",
|
||||
status = "обнаружена проблема",
|
||||
details = "VPN-интерфейс включён, активных каналов: $activeWorkers. Приложение обнаружило состояние, требующее внимания.",
|
||||
recommendation = "${issue.title}: ${issue.action}",
|
||||
severity = DeviceCheckSeverity.Warning,
|
||||
)
|
||||
activeWorkers <= 0 -> DeviceCheckItem(
|
||||
title = "Текущее подключение VPN",
|
||||
status = "нет активных каналов",
|
||||
details = "VPN подключён, но сейчас нет активных транспортных каналов.",
|
||||
recommendation = "Подождите автоматического восстановления. Если каналы не появятся, переподключите VPN и приложите новый отчёт.",
|
||||
severity = DeviceCheckSeverity.Warning,
|
||||
)
|
||||
else -> DeviceCheckItem(
|
||||
title = "Текущее подключение VPN",
|
||||
status = "активно",
|
||||
details = "VPN подключён. Активных каналов: $activeWorkers.",
|
||||
severity = DeviceCheckSeverity.Ok,
|
||||
)
|
||||
}
|
||||
|
||||
internal fun sleepBatteryModeItem(
|
||||
enabled: Boolean,
|
||||
mode: SleepBatteryMode,
|
||||
pauseDelayMinutes: Int,
|
||||
resumeDelayMinutes: Int,
|
||||
runtime: SleepBatteryRuntimeState,
|
||||
notificationsGranted: Boolean,
|
||||
batteryOptimizationsIgnored: Boolean?,
|
||||
): DeviceCheckItem {
|
||||
if (!enabled) {
|
||||
return DeviceCheckItem(
|
||||
title = "Экономия батареи во сне",
|
||||
status = "выключена",
|
||||
details = "При выключенном экране WDTT Plus не будет намеренно останавливать VPN по сценарию сна.",
|
||||
severity = DeviceCheckSeverity.Info,
|
||||
)
|
||||
}
|
||||
|
||||
val normalizedPause = normalizeSleepPauseDelayMinutes(pauseDelayMinutes)
|
||||
val normalizedResume = normalizeSleepPauseDelayMinutes(resumeDelayMinutes)
|
||||
val status = when (mode) {
|
||||
SleepBatteryMode.DELAYED_PAUSE -> if (normalizedPause == 0) {
|
||||
"отключение сразу после выключения экрана"
|
||||
} else {
|
||||
"отключение через ${sleepDelayDescription(normalizedPause)}"
|
||||
}
|
||||
SleepBatteryMode.TIMED_PAUSE -> if (normalizedResume == 0) {
|
||||
"таймер 0 мин, VPN остаётся активным"
|
||||
} else {
|
||||
"пауза примерно на ${sleepDelayDescription(normalizedResume)}"
|
||||
}
|
||||
}
|
||||
val runtimeText = when (runtime.phase) {
|
||||
SleepBatteryRuntimePhase.IDLE -> "сценарий сейчас не выполняется"
|
||||
SleepBatteryRuntimePhase.WAITING_TO_PAUSE -> "идёт отсчёт до отключения VPN"
|
||||
SleepBatteryRuntimePhase.PAUSED_UNTIL_SCREEN_ON -> "VPN отключён до включения экрана"
|
||||
SleepBatteryRuntimePhase.WAITING_TO_RESUME -> "VPN отключён, ожидается таймер включения"
|
||||
SleepBatteryRuntimePhase.RESUMED_UNTIL_SCREEN_ON -> "VPN уже включён таймером"
|
||||
}
|
||||
val timedResumeNeedsAttention =
|
||||
mode == SleepBatteryMode.TIMED_PAUSE && normalizedResume > 0
|
||||
val severity = when {
|
||||
!notificationsGranted -> DeviceCheckSeverity.Warning
|
||||
timedResumeNeedsAttention && batteryOptimizationsIgnored == false -> DeviceCheckSeverity.Warning
|
||||
else -> DeviceCheckSeverity.Ok
|
||||
}
|
||||
val recommendation = when {
|
||||
!notificationsGranted ->
|
||||
"Разрешите уведомления WDTT Plus, чтобы видеть отсчёт и быстрые действия сценария сна."
|
||||
timedResumeNeedsAttention && batteryOptimizationsIgnored == false ->
|
||||
"Снимите ограничения батареи с WDTT Plus, если Android задерживает включение VPN по таймеру."
|
||||
else -> ""
|
||||
}
|
||||
val timerNote = if (timedResumeNeedsAttention) {
|
||||
" Android может немного отложить таймер в глубоком сне; включение экрана всегда завершает сценарий сразу."
|
||||
} else {
|
||||
" Включение экрана завершает текущий сценарий."
|
||||
}
|
||||
return DeviceCheckItem(
|
||||
title = "Экономия батареи во сне",
|
||||
status = status,
|
||||
details = "Текущее состояние: $runtimeText.$timerNote Во время паузы интернет телефона идёт напрямую, без VPN.",
|
||||
recommendation = recommendation,
|
||||
severity = severity,
|
||||
action = when {
|
||||
!notificationsGranted -> DeviceCheckAction.AppSettings
|
||||
timedResumeNeedsAttention && batteryOptimizationsIgnored == false ->
|
||||
DeviceCheckAction.BatterySettings
|
||||
else -> null
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
internal fun trustedWifiModeItem(
|
||||
enabled: Boolean,
|
||||
savedNetworkCount: Int,
|
||||
waiting: Boolean,
|
||||
waitingSsid: String,
|
||||
accessProblem: TrustedWifiAccessProblem?,
|
||||
): DeviceCheckItem {
|
||||
if (!enabled) {
|
||||
return DeviceCheckItem(
|
||||
title = "Доверенные Wi-Fi",
|
||||
status = "выключены",
|
||||
details = "VPN не будет автоматически останавливаться при подключении к сохранённым Wi-Fi сетям.",
|
||||
severity = DeviceCheckSeverity.Info,
|
||||
)
|
||||
}
|
||||
|
||||
val accessRecommendation = when (accessProblem) {
|
||||
TrustedWifiAccessProblem.ForegroundPermission ->
|
||||
"Разрешите WDTT Plus доступ к местоположению или ближайшим устройствам, чтобы Android возвращал имя Wi-Fi."
|
||||
TrustedWifiAccessProblem.BackgroundPermission ->
|
||||
"Разрешите фоновый доступ к местоположению, чтобы доверенная сеть определялась при закрытом приложении."
|
||||
TrustedWifiAccessProblem.LocationDisabled ->
|
||||
"Включите определение местоположения Android, иначе система скрывает имя текущей Wi-Fi сети."
|
||||
null -> ""
|
||||
}
|
||||
val accessAction = when (accessProblem) {
|
||||
TrustedWifiAccessProblem.LocationDisabled -> DeviceCheckAction.NetworkSettings
|
||||
TrustedWifiAccessProblem.ForegroundPermission,
|
||||
TrustedWifiAccessProblem.BackgroundPermission -> DeviceCheckAction.AppSettings
|
||||
null -> null
|
||||
}
|
||||
val cleanCount = savedNetworkCount.coerceAtLeast(0)
|
||||
val status = when {
|
||||
cleanCount == 0 -> "включены, сети не сохранены"
|
||||
accessProblem != null -> "включены, нет доступа к имени Wi-Fi"
|
||||
waiting -> "VPN ожидает выхода из доверенной сети"
|
||||
else -> "включены, сетей: $cleanCount"
|
||||
}
|
||||
val details = when {
|
||||
cleanCount == 0 ->
|
||||
"Автоматика включена, но без сохранённых сетей она не сможет приостанавливать VPN."
|
||||
accessProblem != null ->
|
||||
"Сохранено сетей: $cleanCount. Android не позволяет приложению надёжно определить текущую Wi-Fi сеть в нужном режиме."
|
||||
waiting -> {
|
||||
val network = waitingSsid.trim().takeIf(String::isNotEmpty)?.let { " «$it»" }.orEmpty()
|
||||
"VPN намеренно выключен в доверенной сети$network и восстановится после подтверждённого перехода на другую сеть."
|
||||
}
|
||||
else ->
|
||||
"Сохранено сетей: $cleanCount. VPN будет останавливаться только в них и восстанавливаться после выхода из доверенной сети."
|
||||
}
|
||||
return DeviceCheckItem(
|
||||
title = "Доверенные Wi-Fi",
|
||||
status = status,
|
||||
details = details,
|
||||
recommendation = when {
|
||||
cleanCount == 0 -> "Добавьте хотя бы одну сеть или выключите эту автоматику."
|
||||
accessProblem != null -> accessRecommendation
|
||||
else -> ""
|
||||
},
|
||||
severity = if (cleanCount == 0 || accessProblem != null) {
|
||||
DeviceCheckSeverity.Warning
|
||||
} else {
|
||||
DeviceCheckSeverity.Ok
|
||||
},
|
||||
action = accessAction,
|
||||
)
|
||||
}
|
||||
|
||||
internal fun vpnRoutingModeItem(
|
||||
snapshot: VpnRoutingSettingsSnapshot,
|
||||
installedPackages: Set<String>,
|
||||
ownPackageName: String,
|
||||
): DeviceCheckItem {
|
||||
val selectedPackages = decodeStoredVpnPackages(snapshot.appPackages)
|
||||
.filterNot { isAlwaysBypassedVpnPackage(it, ownPackageName) }
|
||||
val installedSelected = selectedPackages.filter { it in installedPackages }
|
||||
val missingPackages = selectedPackages.filterNot { it in installedPackages }
|
||||
val addressCount = snapshot.addressRules.size
|
||||
val domainCount = snapshot.addressRules.count { it.type == VpnAddressType.DOMAIN }
|
||||
val mode = if (snapshot.isWhitelist) "БС" else "ЧС"
|
||||
val counts = "приложений: ${selectedPackages.size}, адресов: $addressCount" +
|
||||
if (domainCount > 0) ", доменов: $domainCount" else ""
|
||||
|
||||
val warning = when {
|
||||
snapshot.isWhitelist && selectedPackages.isEmpty() && addressCount == 0 ->
|
||||
"Белый список пуст: при подключении профиль намеренно не пропускает трафик приложений через VPN."
|
||||
snapshot.isWhitelist && selectedPackages.isNotEmpty() && installedSelected.isEmpty() ->
|
||||
"Ни одно выбранное приложение сейчас не установлено: профиль не пропускает трафик приложений через VPN."
|
||||
missingPackages.isNotEmpty() ->
|
||||
"Часть выбранных приложений не установлена (${missingPackages.size}); их правила начнут действовать после установки."
|
||||
else -> null
|
||||
}
|
||||
val behavior = when {
|
||||
snapshot.isWhitelist && selectedPackages.isEmpty() && addressCount > 0 ->
|
||||
"Адресные правила применяются ко всем приложениям, кроме обязательных системных исключений WDTT Plus."
|
||||
snapshot.isWhitelist ->
|
||||
"Через VPN идут только выбранные установленные приложения и заданные адресные направления."
|
||||
selectedPackages.isEmpty() && addressCount == 0 ->
|
||||
"Пользовательских исключений нет; через VPN идёт весь поддерживаемый трафик, кроме обязательных исключений WDTT Plus."
|
||||
else ->
|
||||
"Выбранные приложения и адреса обходят VPN, остальной поддерживаемый трафик идёт через туннель."
|
||||
}
|
||||
return DeviceCheckItem(
|
||||
title = "Маршрутизация приложений и адресов",
|
||||
status = "профиль ${snapshot.profileIndex + 1}: $mode, $counts",
|
||||
details = listOfNotNull(behavior, warning).joinToString(" "),
|
||||
recommendation = if (warning != null) {
|
||||
"Проверьте активный профиль во вкладке «Исключения»; предупреждение не изменяет настройки автоматически."
|
||||
} else {
|
||||
""
|
||||
},
|
||||
severity = if (warning != null) DeviceCheckSeverity.Warning else DeviceCheckSeverity.Ok,
|
||||
)
|
||||
}
|
||||
|
||||
internal fun vpnDnsModeItem(
|
||||
settings: VpnDnsSettingsSnapshot,
|
||||
tunnelRunning: Boolean,
|
||||
runningProfile: Int?,
|
||||
profileName: String? = null,
|
||||
): DeviceCheckItem {
|
||||
val appliesNow = tunnelRunning && runningProfile == settings.profileIndex
|
||||
val customInvalid = settings.selectionId == VPN_DNS_CUSTOM_ID &&
|
||||
settings.customServers.isEmpty()
|
||||
val serverText = settings.configuredServers.joinToString(", ")
|
||||
val status = when {
|
||||
customInvalid -> "свой DNS не заполнен"
|
||||
settings.selectionId == VPN_DNS_PROFILE_ID -> "как в WireGuard-профиле"
|
||||
else -> "${settings.title}: $serverText"
|
||||
}
|
||||
val details = buildString {
|
||||
val displayName = profileName?.takeIf { it.isNotBlank() } ?: "Профиль ${settings.profileIndex + 1}"
|
||||
append("Настройка относится к «")
|
||||
append(displayName)
|
||||
append("» и управляет DNS внутри системного VPN-интерфейса Android. ")
|
||||
when {
|
||||
customInvalid -> append("При подключении безопасно сохранится DNS из WireGuard-профиля.")
|
||||
settings.selectionId == VPN_DNS_PROFILE_ID ->
|
||||
append("Фактические адреса предоставляет сервер вместе с WireGuard-конфигурацией.")
|
||||
settings.isSmartDns ->
|
||||
append("Это сторонний Smart DNS; отдельные сервисы могут направляться через его шлюзы.")
|
||||
else -> append("Выбранные адреса передаются Android VPN-интерфейсу.")
|
||||
}
|
||||
if (appliesNow) {
|
||||
append(" Сейчас запущен этот профиль.")
|
||||
} else if (tunnelRunning) {
|
||||
append(" Сейчас запущен другой профиль; настройка применится при запуске этого профиля.")
|
||||
}
|
||||
}
|
||||
return DeviceCheckItem(
|
||||
title = "DNS внутри VPN",
|
||||
status = status,
|
||||
details = details,
|
||||
recommendation = when {
|
||||
customInvalid -> "Откройте «Туннель → DNS внутри VPN» и укажите один или два IPv4-адреса либо выберите готовый вариант."
|
||||
settings.isSmartDns -> "Учитывайте политику конфиденциальности стороннего сервиса и проверяйте нужные сайты после его выбора."
|
||||
else -> ""
|
||||
},
|
||||
severity = when {
|
||||
customInvalid -> DeviceCheckSeverity.Warning
|
||||
settings.isSmartDns -> DeviceCheckSeverity.Info
|
||||
else -> DeviceCheckSeverity.Ok
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
object DeviceCompatibility {
|
||||
const val APP_VERSION_ITEM_TITLE = "Версия WDTT Plus"
|
||||
private const val MIN_RECOMMENDED_SDK = 29
|
||||
@@ -552,20 +834,18 @@ object DeviceCompatibility {
|
||||
severity = DeviceCheckSeverity.Ok
|
||||
)
|
||||
} else if (running) {
|
||||
DeviceCheckItem(
|
||||
title = "Текущее подключение VPN",
|
||||
status = "активно",
|
||||
details = "VPN подключён. Активных каналов: $activeWorkers.",
|
||||
recommendation = issue?.let { "${it.title}: ${it.action}" }.orEmpty(),
|
||||
severity = if (activeWorkers > 0) DeviceCheckSeverity.Ok else DeviceCheckSeverity.Warning
|
||||
tunnelHealthItem(
|
||||
running = true,
|
||||
activeWorkers = activeWorkers,
|
||||
issue = issue,
|
||||
confirmedNetworkFailure = TunnelManager.hasConfirmedNetworkFailureSince(0L),
|
||||
)
|
||||
} else {
|
||||
DeviceCheckItem(
|
||||
title = "Текущее подключение VPN",
|
||||
status = "не активно",
|
||||
details = "VPN сейчас не подключён. Это не мешает проверке устройства; пункт фиксирует текущее состояние туннеля.",
|
||||
recommendation = issue?.let { "${it.title}: ${it.action}" }.orEmpty(),
|
||||
severity = DeviceCheckSeverity.Info
|
||||
tunnelHealthItem(
|
||||
running = false,
|
||||
activeWorkers = activeWorkers,
|
||||
issue = issue,
|
||||
confirmedNetworkFailure = false,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -508,7 +508,8 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
link != null -> handleIncomingWdttLink(link)
|
||||
WdttTransferCodec.isAdminTransfer(value) -> pendingAdminTransfer = value.trim()
|
||||
WdttTransferCodec.documentFormat(value) == "wdtt-server-backup" -> {
|
||||
WdttTransferCodec.isEncryptedServerBackup(value) ||
|
||||
WdttTransferCodec.documentFormat(value) == "wdtt-server-backup" -> {
|
||||
wdttDeepLinkMessage = "Распознана резервная копия сервера. Она применяется к выбранному серверу во вкладке «Деплой» → «Перенос сервера» → «Импорт»."
|
||||
}
|
||||
WdttTransferCodec.documentFormat(value) == "wdtt-plus-admin-settings" -> {
|
||||
|
||||
@@ -26,12 +26,30 @@ data class ServerAdminProfileInfo(
|
||||
val listenPort: Int = 9000,
|
||||
val sni: String = "",
|
||||
val noDns: Boolean = false,
|
||||
val vpnDnsSelectionId: String = VPN_DNS_PROFILE_ID,
|
||||
val vpnDnsCustomServers: List<String> = emptyList(),
|
||||
val vpnDnsStored: Boolean = false,
|
||||
val ports: String = "56000,56001,9000",
|
||||
val deviceIds: List<String> = emptyList(),
|
||||
val updatedAt: Long = 0
|
||||
) {
|
||||
val hasSavedFields: Boolean
|
||||
get() = updatedAt > 0L || vkHashes.isNotBlank() || secondaryVkHash.isNotBlank() || vpnProfileRestorableName(profileName).isNotBlank()
|
||||
|
||||
val vpnDnsDisplayLabel: String
|
||||
get() {
|
||||
if (!vpnDnsStored) return "не сохранён"
|
||||
val settings = VpnDnsSettingsSnapshot(
|
||||
profileIndex = 0,
|
||||
selectionId = vpnDnsSelectionId,
|
||||
customServers = vpnDnsCustomServers,
|
||||
)
|
||||
return if (settings.configuredServers.isEmpty()) {
|
||||
settings.title
|
||||
} else {
|
||||
"${settings.title} (${settings.configuredServers.joinToString(", ")})"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data class ServerAdminState(
|
||||
@@ -289,7 +307,19 @@ object ServerAdminClient {
|
||||
suspend fun updateAdminProfileFromTunnel(
|
||||
target: ServerAdminTarget,
|
||||
profile: ServerAdminProfileInfo
|
||||
): ServerAdminActionResult = runArgsAction(target, buildAdminProfilePatchArgs(profile))
|
||||
): ServerAdminActionResult {
|
||||
return try {
|
||||
runArgsAction(target, buildAdminProfilePatchArgs(profile))
|
||||
} catch (error: IllegalStateException) {
|
||||
val legacyArgs = buildAdminProfilePatchArgs(profile, includeVpnDns = false)
|
||||
val dnsArgsWereAdded = legacyArgs != buildAdminProfilePatchArgs(profile)
|
||||
val oldServer = error.message.orEmpty().contains("сервер ещё не поддерживает", ignoreCase = true)
|
||||
if (!dnsArgsWereAdded || !oldServer) throw error
|
||||
runArgsAction(target, legacyArgs).copy(
|
||||
message = "Профиль обновлён, но DNS внутри VPN не сохранён: обновите серверную часть.",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun refreshPublicHost(target: ServerAdminTarget): ServerAdminActionResult =
|
||||
runArgsAction(target, listOf("refresh-public-ip"))
|
||||
@@ -436,6 +466,13 @@ object ServerAdminClient {
|
||||
listenPort = listenPort,
|
||||
sni = json?.optString("sni", "").orEmpty().trim(),
|
||||
noDns = json?.optBoolean("no_dns", false) ?: false,
|
||||
vpnDnsSelectionId = normalizeVpnDnsSelectionId(
|
||||
json?.optString("vpn_dns_selection", VPN_DNS_PROFILE_ID)
|
||||
),
|
||||
vpnDnsCustomServers = decodeStoredCustomVpnDnsServers(
|
||||
json?.optString("vpn_dns_custom", "").orEmpty()
|
||||
),
|
||||
vpnDnsStored = json?.has("vpn_dns_selection") == true,
|
||||
ports = ports,
|
||||
deviceIds = deviceIds,
|
||||
updatedAt = json?.optLong("updated_at", 0L) ?: 0L
|
||||
@@ -559,7 +596,10 @@ object ServerAdminClient {
|
||||
internal fun hasMeaningfulAdminProfileFields(profile: ServerAdminProfileInfo): Boolean =
|
||||
buildAdminProfilePatchArgs(profile).size > 1
|
||||
|
||||
internal fun buildAdminProfilePatchArgs(profile: ServerAdminProfileInfo): List<String> = buildList {
|
||||
internal fun buildAdminProfilePatchArgs(
|
||||
profile: ServerAdminProfileInfo,
|
||||
includeVpnDns: Boolean = true,
|
||||
): List<String> = buildList {
|
||||
add("update-admin-profile")
|
||||
profile.vkHashes.trim().takeIf { it.isNotBlank() }?.let {
|
||||
add("--vk-hashes")
|
||||
@@ -594,6 +634,12 @@ internal fun buildAdminProfilePatchArgs(profile: ServerAdminProfileInfo): List<S
|
||||
add(it)
|
||||
}
|
||||
if (profile.noDns) add("--no-dns")
|
||||
if (includeVpnDns && profile.vpnDnsStored) {
|
||||
add("--vpn-dns-selection")
|
||||
add(normalizeVpnDnsSelectionId(profile.vpnDnsSelectionId))
|
||||
add("--vpn-dns-custom")
|
||||
add(profile.vpnDnsCustomServers.joinToString(","))
|
||||
}
|
||||
}
|
||||
|
||||
private class AdminSshClient(private val session: Session, private val sudoPassword: String) {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
/** Версии приложения, для которых выпускалась новая обязательная серверная часть. */
|
||||
internal val SERVER_MIGRATION_LEVELS = intArrayOf(2, 3, 5, 6, 7, 12, 14)
|
||||
internal val SERVER_MIGRATION_LEVELS = intArrayOf(2, 3, 5, 6, 7, 12, 14, 15)
|
||||
|
||||
data class ServerMigrationState(
|
||||
val pendingLevel: Int,
|
||||
|
||||
@@ -32,6 +32,41 @@ import org.json.JSONObject
|
||||
import android.os.Build
|
||||
import java.util.UUID
|
||||
|
||||
internal const val DEFAULT_SLEEP_PAUSE_DELAY_MINUTES = 5
|
||||
internal const val MIN_SLEEP_PAUSE_DELAY_MINUTES = 0
|
||||
internal const val MAX_SLEEP_PAUSE_DELAY_MINUTES = 24 * 60
|
||||
|
||||
internal fun normalizeSleepPauseDelayMinutes(minutes: Int): Int =
|
||||
minutes.coerceIn(MIN_SLEEP_PAUSE_DELAY_MINUTES, MAX_SLEEP_PAUSE_DELAY_MINUTES)
|
||||
|
||||
enum class SleepBatteryMode(val storedValue: String) {
|
||||
DELAYED_PAUSE("delayed_pause"),
|
||||
TIMED_PAUSE("timed_pause");
|
||||
|
||||
companion object {
|
||||
fun fromStoredValue(value: String?): SleepBatteryMode =
|
||||
entries.firstOrNull { it.storedValue == value } ?: DELAYED_PAUSE
|
||||
}
|
||||
}
|
||||
|
||||
internal enum class SleepBatteryRuntimePhase(val storedValue: String) {
|
||||
IDLE("idle"),
|
||||
WAITING_TO_PAUSE("waiting_to_pause"),
|
||||
PAUSED_UNTIL_SCREEN_ON("paused_until_screen_on"),
|
||||
WAITING_TO_RESUME("waiting_to_resume"),
|
||||
RESUMED_UNTIL_SCREEN_ON("resumed_until_screen_on");
|
||||
|
||||
companion object {
|
||||
fun fromStoredValue(value: String?): SleepBatteryRuntimePhase =
|
||||
entries.firstOrNull { it.storedValue == value } ?: IDLE
|
||||
}
|
||||
}
|
||||
|
||||
internal data class SleepBatteryRuntimeState(
|
||||
val phase: SleepBatteryRuntimePhase = SleepBatteryRuntimePhase.IDLE,
|
||||
val deadlineMs: Long = 0L,
|
||||
)
|
||||
|
||||
data class VkHashInsertResult(
|
||||
val slot: Int,
|
||||
val hash: String,
|
||||
@@ -40,6 +75,21 @@ data class VkHashInsertResult(
|
||||
val hashes: List<String> = emptyList(),
|
||||
)
|
||||
|
||||
internal data class VpnRoutingImportResult(
|
||||
val blacklistAppCount: Int,
|
||||
val whitelistAppCount: Int,
|
||||
val blacklistAddressCount: Int,
|
||||
val whitelistAddressCount: Int,
|
||||
val isWhitelist: Boolean,
|
||||
)
|
||||
|
||||
internal data class VpnRoutingSettingsSnapshot(
|
||||
val profileIndex: Int,
|
||||
val isWhitelist: Boolean,
|
||||
val appPackages: String,
|
||||
val addressRules: List<VpnAddressRule>,
|
||||
)
|
||||
|
||||
data class WdttLinkParts(
|
||||
val host: String,
|
||||
val dtlsPort: Int,
|
||||
@@ -161,6 +211,8 @@ data class TunnelProfileSnapshot(
|
||||
val listenPort: Int,
|
||||
val sni: String,
|
||||
val protocol: String,
|
||||
val vpnDnsSelectionId: String = VPN_DNS_PROFILE_ID,
|
||||
val vpnDnsCustomServers: List<String> = emptyList(),
|
||||
val vkCallsPreflight: Boolean,
|
||||
val rtNetwork: Boolean = false,
|
||||
val rtMasque: Boolean = false,
|
||||
@@ -261,6 +313,8 @@ data class ActiveTunnelProfileUiSnapshot(
|
||||
val serverWgPort: Int,
|
||||
val listenPort: Int,
|
||||
val sni: String,
|
||||
val vpnDnsSelectionId: String,
|
||||
val vpnDnsCustomServers: List<String>,
|
||||
val captchaMode: String,
|
||||
val captchaSolveMethod: String,
|
||||
val fingerprint: String,
|
||||
@@ -522,6 +576,18 @@ class SettingsStore(context: Context) {
|
||||
private val TRUSTED_WIFI_WAITING = booleanPreferencesKey("trusted_wifi_waiting")
|
||||
private val TRUSTED_WIFI_WAITING_SSID = stringPreferencesKey("trusted_wifi_waiting_ssid")
|
||||
private val PAUSE_VPN_DURING_SLEEP = booleanPreferencesKey("pause_vpn_during_sleep")
|
||||
private val PAUSE_VPN_DURING_SLEEP_DELAY_MINUTES =
|
||||
intPreferencesKey("pause_vpn_during_sleep_delay_minutes")
|
||||
private val PAUSE_VPN_DURING_SLEEP_MODE =
|
||||
stringPreferencesKey("pause_vpn_during_sleep_mode")
|
||||
private val RESUME_VPN_DURING_SLEEP_DELAY_MINUTES =
|
||||
intPreferencesKey("resume_vpn_during_sleep_delay_minutes")
|
||||
private val SLEEP_BATTERY_SETTINGS_CONFIGURED =
|
||||
booleanPreferencesKey("sleep_battery_settings_configured")
|
||||
private val SLEEP_BATTERY_RUNTIME_PHASE =
|
||||
stringPreferencesKey("sleep_battery_runtime_phase")
|
||||
private val ACTIVE_TIMED_SLEEP_RESUME_DEADLINE_MS =
|
||||
longPreferencesKey("active_timed_sleep_resume_deadline_ms")
|
||||
private val WDTT_LINK = stringPreferencesKey("wdtt_link")
|
||||
private val WDTT_LINK_MODE = booleanPreferencesKey("wdtt_link_mode")
|
||||
private val CONNECTION_INPUT_METHOD = stringPreferencesKey("connection_input_method")
|
||||
@@ -599,6 +665,7 @@ class SettingsStore(context: Context) {
|
||||
private val ACCESS_ACTION_LAUNCHED_AT =
|
||||
longPreferencesKey("access_action_launched_at")
|
||||
private val PROFILE_MAX_WORKERS = intPreferencesKey("profile_max_workers")
|
||||
private val PROFILE_WORKER_LIMIT_SEEN = intPreferencesKey("profile_worker_limit_seen")
|
||||
private val VK_HASH_NEXT_SLOT = intPreferencesKey("vk_hash_next_slot")
|
||||
private val WORKERS_PER_HASH = intPreferencesKey("workers_per_hash")
|
||||
private val PROTOCOL = stringPreferencesKey("protocol")
|
||||
@@ -609,6 +676,8 @@ class SettingsStore(context: Context) {
|
||||
private val SNI = stringPreferencesKey("sni")
|
||||
private val NO_DTLS = booleanPreferencesKey("no_dtls")
|
||||
private val NO_DNS = booleanPreferencesKey("no_dns")
|
||||
private val VPN_DNS_SELECTION = stringPreferencesKey("vpn_dns_selection")
|
||||
private val VPN_DNS_CUSTOM = stringPreferencesKey("vpn_dns_custom")
|
||||
|
||||
private val USER_AGENT = stringPreferencesKey("user_agent")
|
||||
|
||||
@@ -662,6 +731,8 @@ class SettingsStore(context: Context) {
|
||||
private val IS_WHITELIST = booleanPreferencesKey("is_whitelist")
|
||||
private val BLACKLIST_APPS = stringPreferencesKey("blacklist_apps")
|
||||
private val WHITELIST_APPS = stringPreferencesKey("whitelist_apps")
|
||||
private val BLACKLIST_ADDRESSES = stringPreferencesKey("blacklist_addresses")
|
||||
private val WHITELIST_ADDRESSES = stringPreferencesKey("whitelist_addresses")
|
||||
|
||||
// ═══ Theme Mode ═══
|
||||
private val THEME_MODE = stringPreferencesKey("theme_mode") // "system", "light", "dark"
|
||||
@@ -749,6 +820,8 @@ class SettingsStore(context: Context) {
|
||||
ACCESS_LIFECYCLE_DISMISSED_SIGNATURE,
|
||||
PROTOCOL,
|
||||
SNI,
|
||||
VPN_DNS_SELECTION,
|
||||
VPN_DNS_CUSTOM,
|
||||
USER_AGENT,
|
||||
DEPLOY_IP,
|
||||
DEPLOY_LOGIN,
|
||||
@@ -770,6 +843,8 @@ class SettingsStore(context: Context) {
|
||||
EXCLUDED_APPS,
|
||||
BLACKLIST_APPS,
|
||||
WHITELIST_APPS,
|
||||
BLACKLIST_ADDRESSES,
|
||||
WHITELIST_ADDRESSES,
|
||||
CONNECTION_PASSWORD,
|
||||
CONNECTION_PASSWORD_ENCRYPTED,
|
||||
DEPLOY_MAIN_PASSWORD,
|
||||
@@ -795,6 +870,7 @@ class SettingsStore(context: Context) {
|
||||
private val PROFILE_INT_KEYS = listOf(
|
||||
WORKERS_PER_HASH,
|
||||
PROFILE_MAX_WORKERS,
|
||||
PROFILE_WORKER_LIMIT_SEEN,
|
||||
VK_HASH_NEXT_SLOT,
|
||||
LISTEN_PORT,
|
||||
SERVER_DTLS_PORT,
|
||||
@@ -895,6 +971,12 @@ class SettingsStore(context: Context) {
|
||||
serverWgPort = it[getProfileKey(SERVER_WG_PORT, profile)] ?: 56001,
|
||||
listenPort = it[getProfileKey(LISTEN_PORT, profile)] ?: 9000,
|
||||
sni = it[getProfileKey(SNI, profile)].orEmpty(),
|
||||
vpnDnsSelectionId = normalizeVpnDnsSelectionId(
|
||||
it[getProfileKey(VPN_DNS_SELECTION, profile)]
|
||||
),
|
||||
vpnDnsCustomServers = decodeStoredCustomVpnDnsServers(
|
||||
it[getProfileKey(VPN_DNS_CUSTOM, profile)].orEmpty()
|
||||
),
|
||||
captchaMode = it[getProfileKey(CAPTCHA_MODE, profile)] ?: "auto",
|
||||
captchaSolveMethod = it[getProfileKey(CAPTCHA_SOLVE_METHOD, profile)] ?: "auto",
|
||||
fingerprint = it[getProfileKey(SELECTED_FINGERPRINT, profile)] ?: "firefox",
|
||||
@@ -1038,6 +1120,41 @@ class SettingsStore(context: Context) {
|
||||
val pauseVpnDuringSleep: Flow<Boolean> = preferencesFlow.map {
|
||||
it[PAUSE_VPN_DURING_SLEEP] ?: false
|
||||
}
|
||||
val pauseVpnDuringSleepDelayMinutes: Flow<Int> = preferencesFlow.map {
|
||||
normalizeSleepPauseDelayMinutes(
|
||||
it[PAUSE_VPN_DURING_SLEEP_DELAY_MINUTES] ?: DEFAULT_SLEEP_PAUSE_DELAY_MINUTES
|
||||
)
|
||||
}
|
||||
val sleepBatteryMode: Flow<SleepBatteryMode> = preferencesFlow.map {
|
||||
SleepBatteryMode.fromStoredValue(it[PAUSE_VPN_DURING_SLEEP_MODE])
|
||||
}
|
||||
val resumeVpnDuringSleepDelayMinutes: Flow<Int> = preferencesFlow.map {
|
||||
normalizeSleepPauseDelayMinutes(
|
||||
it[RESUME_VPN_DURING_SLEEP_DELAY_MINUTES] ?: DEFAULT_SLEEP_PAUSE_DELAY_MINUTES
|
||||
)
|
||||
}
|
||||
val sleepBatterySettingsConfigured: Flow<Boolean> = preferencesFlow.map {
|
||||
it[SLEEP_BATTERY_SETTINGS_CONFIGURED]
|
||||
?: (
|
||||
it[PAUSE_VPN_DURING_SLEEP_DELAY_MINUTES] != null ||
|
||||
it[PAUSE_VPN_DURING_SLEEP_MODE] != null ||
|
||||
it[RESUME_VPN_DURING_SLEEP_DELAY_MINUTES] != null
|
||||
)
|
||||
}
|
||||
internal val sleepBatteryRuntimeState: Flow<SleepBatteryRuntimeState> = preferencesFlow.map { prefs ->
|
||||
val deadlineMs = (prefs[ACTIVE_TIMED_SLEEP_RESUME_DEADLINE_MS] ?: 0L).coerceAtLeast(0L)
|
||||
val storedPhase = prefs[SLEEP_BATTERY_RUNTIME_PHASE]
|
||||
SleepBatteryRuntimeState(
|
||||
phase = if (storedPhase == null && deadlineMs > 0L) {
|
||||
// Совместимость с локальными сборками, где сохранялся только
|
||||
// дедлайн второго режима.
|
||||
SleepBatteryRuntimePhase.WAITING_TO_RESUME
|
||||
} else {
|
||||
SleepBatteryRuntimePhase.fromStoredValue(storedPhase)
|
||||
},
|
||||
deadlineMs = deadlineMs,
|
||||
)
|
||||
}
|
||||
val wdttLink: Flow<String> = preferencesFlow.map { prefs ->
|
||||
val profile = prefs[ACTIVE_PROFILE] ?: 0
|
||||
prefs[getProfileKey(WDTT_LINK, profile)] ?: ""
|
||||
@@ -1174,15 +1291,87 @@ class SettingsStore(context: Context) {
|
||||
val profile = prefs[ACTIVE_PROFILE] ?: 0
|
||||
prefs[getProfileKey(DEPLOY_DNS2, profile)] ?: "1.0.0.1"
|
||||
}
|
||||
val vpnAppPackages: Flow<String> = preferencesFlow.map { prefs ->
|
||||
val profile = prefs[ACTIVE_PROFILE] ?: 0
|
||||
val baseKey = if (prefs[getProfileKey(IS_WHITELIST, profile)] == true) {
|
||||
|
||||
private fun vpnDnsSettingsSnapshot(
|
||||
prefs: Preferences,
|
||||
profileIndex: Int,
|
||||
): VpnDnsSettingsSnapshot {
|
||||
val profile = profileIndex.coerceIn(0, VPN_PROFILE_COUNT - 1)
|
||||
return VpnDnsSettingsSnapshot(
|
||||
profileIndex = profile,
|
||||
selectionId = normalizeVpnDnsSelectionId(
|
||||
prefs[getProfileKey(VPN_DNS_SELECTION, profile)]
|
||||
),
|
||||
customServers = decodeStoredCustomVpnDnsServers(
|
||||
prefs[getProfileKey(VPN_DNS_CUSTOM, profile)].orEmpty()
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
internal val vpnDnsSettings: Flow<VpnDnsSettingsSnapshot> = preferencesFlow.map { prefs ->
|
||||
vpnDnsSettingsSnapshot(
|
||||
prefs = prefs,
|
||||
profileIndex = prefs[ACTIVE_PROFILE] ?: 0,
|
||||
)
|
||||
}.distinctUntilChanged().flowOn(Dispatchers.IO)
|
||||
|
||||
internal suspend fun vpnDnsSettingsForProfile(
|
||||
profileIndex: Int,
|
||||
): VpnDnsSettingsSnapshot = vpnDnsSettingsSnapshot(
|
||||
prefs = preferencesFlow.first(),
|
||||
profileIndex = profileIndex,
|
||||
)
|
||||
|
||||
private fun vpnRoutingSettingsSnapshot(
|
||||
prefs: Preferences,
|
||||
profileIndex: Int,
|
||||
): VpnRoutingSettingsSnapshot {
|
||||
val profile = profileIndex.coerceIn(0, VPN_PROFILE_COUNT - 1)
|
||||
val whitelist = prefs[getProfileKey(IS_WHITELIST, profile)] == true
|
||||
val appKey = if (whitelist) {
|
||||
WHITELIST_APPS
|
||||
} else {
|
||||
BLACKLIST_APPS
|
||||
}
|
||||
prefs[getProfileKey(baseKey, profile)] ?: ""
|
||||
val addressKey = if (whitelist) {
|
||||
WHITELIST_ADDRESSES
|
||||
} else {
|
||||
BLACKLIST_ADDRESSES
|
||||
}
|
||||
return VpnRoutingSettingsSnapshot(
|
||||
profileIndex = profile,
|
||||
isWhitelist = whitelist,
|
||||
appPackages = sanitizeVpnRoutingPackages(
|
||||
decodeStoredVpnPackages(prefs[getProfileKey(appKey, profile)].orEmpty()),
|
||||
appContext.packageName,
|
||||
).joinToString(","),
|
||||
addressRules = decodeVpnAddressRules(
|
||||
prefs[getProfileKey(addressKey, profile)].orEmpty()
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
internal val vpnRoutingSettings: Flow<VpnRoutingSettingsSnapshot> = preferencesFlow.map { prefs ->
|
||||
vpnRoutingSettingsSnapshot(
|
||||
prefs = prefs,
|
||||
profileIndex = prefs[ACTIVE_PROFILE] ?: 0,
|
||||
)
|
||||
}.distinctUntilChanged().flowOn(Dispatchers.IO)
|
||||
|
||||
internal suspend fun vpnRoutingSettingsForProfile(
|
||||
profileIndex: Int,
|
||||
): VpnRoutingSettingsSnapshot = vpnRoutingSettingsSnapshot(
|
||||
prefs = preferencesFlow.first(),
|
||||
profileIndex = profileIndex,
|
||||
)
|
||||
|
||||
val vpnAppPackages: Flow<String> = vpnRoutingSettings
|
||||
.map { snapshot -> snapshot.appPackages }
|
||||
.distinctUntilChanged()
|
||||
|
||||
internal val vpnAddressRules: Flow<List<VpnAddressRule>> = vpnRoutingSettings
|
||||
.map { snapshot -> snapshot.addressRules }
|
||||
.distinctUntilChanged()
|
||||
|
||||
val detailedLogs: Flow<Boolean> = preferencesFlow.map { prefs ->
|
||||
val profile = prefs[ACTIVE_PROFILE] ?: 0
|
||||
@@ -1252,10 +1441,9 @@ class SettingsStore(context: Context) {
|
||||
}
|
||||
|
||||
// ═══ VPN Exclusions Mode ═══
|
||||
val isWhitelist: Flow<Boolean> = preferencesFlow.map { prefs ->
|
||||
val profile = prefs[ACTIVE_PROFILE] ?: 0
|
||||
prefs[getProfileKey(IS_WHITELIST, profile)] ?: false
|
||||
}
|
||||
val isWhitelist: Flow<Boolean> = vpnRoutingSettings
|
||||
.map { snapshot -> snapshot.isWhitelist }
|
||||
.distinctUntilChanged()
|
||||
|
||||
// ═══ Theme Mode ═══
|
||||
val themeMode: Flow<String> = preferencesFlow.map { it[THEME_MODE] ?: "system" }
|
||||
@@ -1655,8 +1843,11 @@ class SettingsStore(context: Context) {
|
||||
|
||||
suspend fun saveTrustedWifiEnabled(enabled: Boolean) {
|
||||
dataStore.edit { prefs ->
|
||||
prefs[TRUSTED_WIFI_ENABLED] = enabled
|
||||
if (!enabled) {
|
||||
val hasConfiguredNetworks =
|
||||
parseTrustedWifiSsids(prefs[TRUSTED_WIFI_SSIDS].orEmpty()).isNotEmpty()
|
||||
val effectiveEnabled = enabled && hasConfiguredNetworks
|
||||
prefs[TRUSTED_WIFI_ENABLED] = effectiveEnabled
|
||||
if (!effectiveEnabled) {
|
||||
prefs.remove(TRUSTED_WIFI_WAITING)
|
||||
prefs.remove(TRUSTED_WIFI_WAITING_SSID)
|
||||
}
|
||||
@@ -1683,8 +1874,14 @@ class SettingsStore(context: Context) {
|
||||
dataStore.edit { prefs ->
|
||||
val values = parseTrustedWifiSsids(prefs[TRUSTED_WIFI_SSIDS].orEmpty())
|
||||
.filterNot { it == clean }
|
||||
if (values.isEmpty()) prefs.remove(TRUSTED_WIFI_SSIDS)
|
||||
else prefs[TRUSTED_WIFI_SSIDS] = JSONArray(values).toString()
|
||||
if (values.isEmpty()) {
|
||||
prefs.remove(TRUSTED_WIFI_SSIDS)
|
||||
prefs[TRUSTED_WIFI_ENABLED] = false
|
||||
prefs.remove(TRUSTED_WIFI_WAITING)
|
||||
prefs.remove(TRUSTED_WIFI_WAITING_SSID)
|
||||
} else {
|
||||
prefs[TRUSTED_WIFI_SSIDS] = JSONArray(values).toString()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1706,6 +1903,41 @@ class SettingsStore(context: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun saveSleepBatteryMode(
|
||||
enabled: Boolean,
|
||||
mode: SleepBatteryMode,
|
||||
pauseDelayMinutes: Int,
|
||||
resumeDelayMinutes: Int,
|
||||
) {
|
||||
dataStore.edit { prefs ->
|
||||
prefs[PAUSE_VPN_DURING_SLEEP] = enabled
|
||||
prefs[PAUSE_VPN_DURING_SLEEP_DELAY_MINUTES] =
|
||||
normalizeSleepPauseDelayMinutes(pauseDelayMinutes)
|
||||
prefs[PAUSE_VPN_DURING_SLEEP_MODE] = mode.storedValue
|
||||
prefs[RESUME_VPN_DURING_SLEEP_DELAY_MINUTES] =
|
||||
normalizeSleepPauseDelayMinutes(resumeDelayMinutes)
|
||||
prefs[SLEEP_BATTERY_SETTINGS_CONFIGURED] = true
|
||||
}
|
||||
}
|
||||
|
||||
internal suspend fun saveSleepBatteryRuntimeState(
|
||||
phase: SleepBatteryRuntimePhase,
|
||||
deadlineMs: Long = 0L,
|
||||
) {
|
||||
dataStore.edit { prefs ->
|
||||
if (phase == SleepBatteryRuntimePhase.IDLE) {
|
||||
prefs.remove(SLEEP_BATTERY_RUNTIME_PHASE)
|
||||
} else {
|
||||
prefs[SLEEP_BATTERY_RUNTIME_PHASE] = phase.storedValue
|
||||
}
|
||||
if (deadlineMs > 0L) {
|
||||
prefs[ACTIVE_TIMED_SLEEP_RESUME_DEADLINE_MS] = deadlineMs
|
||||
} else {
|
||||
prefs.remove(ACTIVE_TIMED_SLEEP_RESUME_DEADLINE_MS)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun saveWdttLink(link: String) {
|
||||
dataStore.edit { prefs ->
|
||||
val profile = prefs[ACTIVE_PROFILE] ?: 0
|
||||
@@ -1776,6 +2008,12 @@ class SettingsStore(context: Context) {
|
||||
listenPort = prefs[getProfileKey(LISTEN_PORT, profile)] ?: 9000,
|
||||
sni = prefs[getProfileKey(SNI, profile)].orEmpty(),
|
||||
protocol = prefs[getProfileKey(PROTOCOL, profile)] ?: "udp",
|
||||
vpnDnsSelectionId = normalizeVpnDnsSelectionId(
|
||||
prefs[getProfileKey(VPN_DNS_SELECTION, profile)]
|
||||
),
|
||||
vpnDnsCustomServers = decodeStoredCustomVpnDnsServers(
|
||||
prefs[getProfileKey(VPN_DNS_CUSTOM, profile)].orEmpty()
|
||||
),
|
||||
vkCallsPreflight = prefs[getProfileKey(VKCALLS_PREFLIGHT, profile)] ?: true,
|
||||
rtNetwork = prefs[getProfileKey(RT_NETWORK, profile)] ?: false,
|
||||
rtMasque = prefs[getProfileKey(RT_MASQUE, profile)] ?: false,
|
||||
@@ -1979,6 +2217,18 @@ class SettingsStore(context: Context) {
|
||||
put("sni", prefs[getProfileKey(SNI, profile)].orEmpty())
|
||||
put("noDtls", prefs[getProfileKey(NO_DTLS, profile)] ?: false)
|
||||
put("noDns", prefs[getProfileKey(NO_DNS, profile)] ?: false)
|
||||
put(
|
||||
"vpnDnsSelection",
|
||||
normalizeVpnDnsSelectionId(
|
||||
prefs[getProfileKey(VPN_DNS_SELECTION, profile)]
|
||||
)
|
||||
)
|
||||
put(
|
||||
"vpnDnsCustom",
|
||||
decodeStoredCustomVpnDnsServers(
|
||||
prefs[getProfileKey(VPN_DNS_CUSTOM, profile)].orEmpty()
|
||||
).joinToString(",")
|
||||
)
|
||||
put("userAgent", prefs[getProfileKey(USER_AGENT, profile)].orEmpty())
|
||||
put("connectionPassword", readSecret(prefs, CONNECTION_PASSWORD_ENCRYPTED, CONNECTION_PASSWORD, profile))
|
||||
put("deployIp", prefs[getProfileKey(DEPLOY_IP, profile)].orEmpty())
|
||||
@@ -2007,6 +2257,8 @@ class SettingsStore(context: Context) {
|
||||
put("isWhitelist", prefs[getProfileKey(IS_WHITELIST, profile)] ?: false)
|
||||
put("blacklistApps", prefs[getProfileKey(BLACKLIST_APPS, profile)].orEmpty())
|
||||
put("whitelistApps", prefs[getProfileKey(WHITELIST_APPS, profile)].orEmpty())
|
||||
put("blacklistAddresses", prefs[getProfileKey(BLACKLIST_ADDRESSES, profile)].orEmpty())
|
||||
put("whitelistAddresses", prefs[getProfileKey(WHITELIST_ADDRESSES, profile)].orEmpty())
|
||||
put("detailedLogs", prefs[getProfileKey(DETAILED_LOGS, profile)] ?: false)
|
||||
put("selectedFingerprint", prefs[getProfileKey(SELECTED_FINGERPRINT, profile)] ?: "firefox")
|
||||
put("activeClientIds", prefs[getProfileKey(ACTIVE_CLIENT_IDS, profile)] ?: "6287487,8202606")
|
||||
@@ -2056,6 +2308,7 @@ class SettingsStore(context: Context) {
|
||||
prefs.remove(getProfileKey(REMOTE_ACTION_URL, profile))
|
||||
prefs.remove(getProfileKey(REMOTE_DOCUMENT_BINDING, profile))
|
||||
prefs.remove(getProfileKey(REMOTE_MANAGED_PROFILE, profile))
|
||||
prefs.remove(getProfileKey(PROFILE_WORKER_LIMIT_SEEN, profile))
|
||||
prefs.clearAccessLifecycle(profile)
|
||||
val importedLink = item.optString("wdttLink")
|
||||
val importedLinkMode = item.optBoolean("wdttLinkMode")
|
||||
@@ -2101,6 +2354,27 @@ class SettingsStore(context: Context) {
|
||||
prefs[getProfileKey(SNI, profile)] = item.optString("sni")
|
||||
prefs[getProfileKey(NO_DTLS, profile)] = item.optBoolean("noDtls")
|
||||
prefs[getProfileKey(NO_DNS, profile)] = item.optBoolean("noDns")
|
||||
val importedVpnDnsSelection = normalizeVpnDnsSelectionId(
|
||||
item.optString("vpnDnsSelection", VPN_DNS_PROFILE_ID)
|
||||
)
|
||||
val importedVpnDnsCustom = decodeStoredCustomVpnDnsServers(
|
||||
item.optString("vpnDnsCustom")
|
||||
)
|
||||
prefs[getProfileKey(VPN_DNS_SELECTION, profile)] =
|
||||
if (
|
||||
importedVpnDnsSelection == VPN_DNS_CUSTOM_ID &&
|
||||
importedVpnDnsCustom.isEmpty()
|
||||
) {
|
||||
VPN_DNS_PROFILE_ID
|
||||
} else {
|
||||
importedVpnDnsSelection
|
||||
}
|
||||
if (importedVpnDnsCustom.isEmpty()) {
|
||||
prefs.remove(getProfileKey(VPN_DNS_CUSTOM, profile))
|
||||
} else {
|
||||
prefs[getProfileKey(VPN_DNS_CUSTOM, profile)] =
|
||||
importedVpnDnsCustom.joinToString(",")
|
||||
}
|
||||
prefs[getProfileKey(USER_AGENT, profile)] = item.optString("userAgent")
|
||||
prefs.putSecret(
|
||||
CONNECTION_PASSWORD_ENCRYPTED,
|
||||
@@ -2137,8 +2411,18 @@ class SettingsStore(context: Context) {
|
||||
prefs[getProfileKey(CAPTCHA_SOLVE_METHOD, profile)] = item.optString("captchaSolveMethod", "auto")
|
||||
prefs[getProfileKey(CAPTCHA_WBV_SOLVE_METHOD, profile)] = item.optString("captchaWbvSolveMethod", "auto")
|
||||
prefs[getProfileKey(IS_WHITELIST, profile)] = item.optBoolean("isWhitelist")
|
||||
prefs[getProfileKey(BLACKLIST_APPS, profile)] = item.optString("blacklistApps")
|
||||
prefs[getProfileKey(WHITELIST_APPS, profile)] = item.optString("whitelistApps")
|
||||
prefs[getProfileKey(BLACKLIST_APPS, profile)] = sanitizeVpnRoutingPackages(
|
||||
decodeStoredVpnPackages(item.optString("blacklistApps")),
|
||||
appContext.packageName,
|
||||
).joinToString(",")
|
||||
prefs[getProfileKey(WHITELIST_APPS, profile)] = sanitizeVpnRoutingPackages(
|
||||
decodeStoredVpnPackages(item.optString("whitelistApps")),
|
||||
appContext.packageName,
|
||||
).joinToString(",")
|
||||
prefs[getProfileKey(BLACKLIST_ADDRESSES, profile)] =
|
||||
importedVpnAddressRules(item, "blacklistAddresses")
|
||||
prefs[getProfileKey(WHITELIST_ADDRESSES, profile)] =
|
||||
importedVpnAddressRules(item, "whitelistAddresses")
|
||||
prefs[getProfileKey(DETAILED_LOGS, profile)] = item.optBoolean("detailedLogs")
|
||||
prefs[getProfileKey(SELECTED_FINGERPRINT, profile)] = item.optString("selectedFingerprint", "firefox")
|
||||
prefs[getProfileKey(ACTIVE_CLIENT_IDS, profile)] = item.optString("activeClientIds", "6287487,8202606")
|
||||
@@ -2202,6 +2486,32 @@ class SettingsStore(context: Context) {
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun reconcileRemoteProfileWorkerLimit(profileIndex: Int? = null) {
|
||||
dataStore.edit { prefs ->
|
||||
val profile = (profileIndex ?: prefs[ACTIVE_PROFILE] ?: 0)
|
||||
.coerceIn(0, VPN_PROFILE_COUNT - 1)
|
||||
val seenKey = getProfileKey(PROFILE_WORKER_LIMIT_SEEN, profile)
|
||||
val remoteManaged = prefs[getProfileKey(REMOTE_MANAGED_PROFILE, profile)] == true
|
||||
val currentLimit = prefs[getProfileKey(PROFILE_MAX_WORKERS, profile)] ?: 0
|
||||
if (
|
||||
!remoteManaged ||
|
||||
currentLimit !in TUNNEL_WORKERS_PER_GROUP..APP_MAX_WORKERS ||
|
||||
currentLimit % TUNNEL_WORKERS_PER_GROUP != 0
|
||||
) {
|
||||
prefs.remove(seenKey)
|
||||
return@edit
|
||||
}
|
||||
val workersKey = getProfileKey(WORKERS_PER_HASH, profile)
|
||||
prefs[workersKey] = reconcileTunnelWorkerCountForProfileLimit(
|
||||
selectedWorkers = prefs[workersKey] ?: 18,
|
||||
previousProfileMaxWorkers = prefs[seenKey],
|
||||
currentProfileMaxWorkers = currentLimit,
|
||||
remoteManaged = true,
|
||||
)
|
||||
prefs[seenKey] = currentLimit
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a remote profile document as one DataStore transaction.
|
||||
*
|
||||
@@ -2408,24 +2718,45 @@ class SettingsStore(context: Context) {
|
||||
remove(getProfileKey(REMOTE_ACTION_URL, profile))
|
||||
remove(getProfileKey(REMOTE_DOCUMENT_BINDING, profile))
|
||||
remove(getProfileKey(REMOTE_MANAGED_PROFILE, profile))
|
||||
remove(getProfileKey(PROFILE_WORKER_LIMIT_SEEN, profile))
|
||||
clearAccessLifecycle(profile)
|
||||
}
|
||||
remoteManaged?.let { managed ->
|
||||
val key = getProfileKey(REMOTE_MANAGED_PROFILE, profile)
|
||||
if (managed) this[key] = true else remove(key)
|
||||
}
|
||||
if (!preserveConnectionSettings) {
|
||||
val requestedLimit = profileMaxWorkers
|
||||
?.takeIf { it >= TUNNEL_WORKERS_PER_GROUP }
|
||||
?: parts.maxWorkers
|
||||
val normalizedLimit = (requestedLimit / TUNNEL_WORKERS_PER_GROUP) *
|
||||
TUNNEL_WORKERS_PER_GROUP
|
||||
if (normalizedLimit >= TUNNEL_WORKERS_PER_GROUP) {
|
||||
this[getProfileKey(PROFILE_MAX_WORKERS, profile)] =
|
||||
normalizedLimit.coerceAtMost(APP_MAX_WORKERS)
|
||||
val maxWorkersKey = getProfileKey(PROFILE_MAX_WORKERS, profile)
|
||||
val seenLimitKey = getProfileKey(PROFILE_WORKER_LIMIT_SEEN, profile)
|
||||
val selectedWorkersKey = getProfileKey(WORKERS_PER_HASH, profile)
|
||||
val previousLimit = this[seenLimitKey] ?: this[maxWorkersKey]
|
||||
val requestedLimit = profileMaxWorkers
|
||||
?.takeIf { it >= TUNNEL_WORKERS_PER_GROUP }
|
||||
?: parts.maxWorkers
|
||||
val normalizedLimit = ((requestedLimit / TUNNEL_WORKERS_PER_GROUP) *
|
||||
TUNNEL_WORKERS_PER_GROUP).coerceAtMost(APP_MAX_WORKERS)
|
||||
if (normalizedLimit >= TUNNEL_WORKERS_PER_GROUP) {
|
||||
this[maxWorkersKey] = normalizedLimit
|
||||
val managed = this[getProfileKey(REMOTE_MANAGED_PROFILE, profile)] == true
|
||||
if (managed) {
|
||||
this[selectedWorkersKey] = if (remoteManaged == true) {
|
||||
normalizedLimit
|
||||
} else {
|
||||
reconcileTunnelWorkerCountForProfileLimit(
|
||||
selectedWorkers = this[selectedWorkersKey] ?: 18,
|
||||
previousProfileMaxWorkers = previousLimit,
|
||||
currentProfileMaxWorkers = normalizedLimit,
|
||||
remoteManaged = true,
|
||||
)
|
||||
}
|
||||
this[seenLimitKey] = normalizedLimit
|
||||
} else {
|
||||
remove(getProfileKey(PROFILE_MAX_WORKERS, profile))
|
||||
remove(seenLimitKey)
|
||||
}
|
||||
} else {
|
||||
remove(maxWorkersKey)
|
||||
remove(seenLimitKey)
|
||||
}
|
||||
if (!preserveConnectionSettings) {
|
||||
val importedProfileName = vpnProfileRestorableName(parts.profileName)
|
||||
if (importedProfileName.isNotBlank()) {
|
||||
this[getProfileKey(PROFILE_NAME, profile)] = importedProfileName
|
||||
@@ -2521,6 +2852,69 @@ class SettingsStore(context: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun applyImportedServerConnection(
|
||||
profileIndex: Int,
|
||||
host: String,
|
||||
connectionPassword: String,
|
||||
dtlsPort: Int,
|
||||
wgPort: Int,
|
||||
ownerProfile: ServerAdminProfileInfo
|
||||
) {
|
||||
val profile = profileIndex.coerceIn(0, VPN_PROFILE_COUNT - 1)
|
||||
require(host.isNotBlank()) { "Адрес импортированного сервера пустой." }
|
||||
require(connectionPassword.isNotBlank()) { "Главный пароль импортированного сервера пустой." }
|
||||
require(dtlsPort in 1..65535 && wgPort in 1..65535 && ownerProfile.listenPort in 1..65535) {
|
||||
"В импортированном профиле указаны некорректные порты."
|
||||
}
|
||||
val importedVpnDnsSelection = normalizeVpnDnsSelectionId(ownerProfile.vpnDnsSelectionId)
|
||||
val importedVpnDnsCustom = ownerProfile.vpnDnsCustomServers
|
||||
.joinToString(",")
|
||||
.let(::decodeStoredCustomVpnDnsServers)
|
||||
val effectiveVpnDnsSelection = if (
|
||||
importedVpnDnsSelection == VPN_DNS_CUSTOM_ID && importedVpnDnsCustom.isEmpty()
|
||||
) {
|
||||
VPN_DNS_PROFILE_ID
|
||||
} else {
|
||||
importedVpnDnsSelection
|
||||
}
|
||||
dataStore.edit { prefs ->
|
||||
prefs[getProfileKey(WDTT_LINK_MODE, profile)] = false
|
||||
prefs.remove(getProfileKey(WDTT_LINK, profile))
|
||||
prefs[getProfileKey(CONNECTION_INPUT_METHOD, profile)] = "manual"
|
||||
prefs[getProfileKey(PEER, profile)] = host.trim()
|
||||
prefs.putSecret(
|
||||
CONNECTION_PASSWORD_ENCRYPTED,
|
||||
CONNECTION_PASSWORD,
|
||||
connectionPassword,
|
||||
profile
|
||||
)
|
||||
prefs[getProfileKey(VK_HASHES, profile)] = ownerProfile.vkHashes.trim()
|
||||
prefs[getProfileKey(SECONDARY_VK_HASH, profile)] = ownerProfile.secondaryVkHash.trim()
|
||||
prefs[getProfileKey(WORKERS_PER_HASH, profile)] = ownerProfile.workersPerHash.coerceIn(1, 128)
|
||||
prefs[getProfileKey(PROTOCOL, profile)] =
|
||||
ownerProfile.protocol.trim().lowercase().takeIf { it == "udp" || it == "tcp" } ?: "udp"
|
||||
prefs[getProfileKey(LISTEN_PORT, profile)] = ownerProfile.listenPort
|
||||
prefs[getProfileKey(SERVER_DTLS_PORT, profile)] = dtlsPort
|
||||
prefs[getProfileKey(SERVER_WG_PORT, profile)] = wgPort
|
||||
prefs[getProfileKey(MANUAL_PORTS_ENABLED, profile)] =
|
||||
dtlsPort != 56000 || wgPort != 56001 || ownerProfile.listenPort != 9000
|
||||
prefs[getProfileKey(SNI, profile)] = ownerProfile.sni.trim()
|
||||
prefs[getProfileKey(NO_DNS, profile)] = ownerProfile.noDns
|
||||
if (ownerProfile.vpnDnsStored) {
|
||||
prefs[getProfileKey(VPN_DNS_SELECTION, profile)] = effectiveVpnDnsSelection
|
||||
if (importedVpnDnsCustom.isEmpty()) {
|
||||
prefs.remove(getProfileKey(VPN_DNS_CUSTOM, profile))
|
||||
} else {
|
||||
prefs[getProfileKey(VPN_DNS_CUSTOM, profile)] =
|
||||
importedVpnDnsCustom.joinToString(",")
|
||||
}
|
||||
}
|
||||
vpnProfileRestorableName(ownerProfile.profileName)
|
||||
.takeIf { it.isNotBlank() }
|
||||
?.let { prefs[getProfileKey(PROFILE_NAME, profile)] = it }
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun saveWorkersPerHash(workersPerHash: Int) {
|
||||
dataStore.edit { prefs ->
|
||||
val profile = prefs[ACTIVE_PROFILE] ?: 0
|
||||
@@ -2967,39 +3361,186 @@ class SettingsStore(context: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun toggleVpnAppSelected(packageName: String, whitelist: Boolean) {
|
||||
suspend fun toggleVpnAppSelected(
|
||||
packageName: String,
|
||||
whitelist: Boolean,
|
||||
profileIndex: Int? = null,
|
||||
) {
|
||||
val normalizedPackage = packageName.trim()
|
||||
require(
|
||||
normalizedPackage.isNotEmpty() &&
|
||||
',' !in normalizedPackage &&
|
||||
!isAlwaysBypassedVpnPackage(normalizedPackage, appContext.packageName)
|
||||
) { "Это приложение нельзя добавить в список маршрутизации." }
|
||||
dataStore.edit { prefs ->
|
||||
val profile = prefs[ACTIVE_PROFILE] ?: 0
|
||||
val profile = profileIndex?.coerceIn(0, VPN_PROFILE_COUNT - 1)
|
||||
?: (prefs[ACTIVE_PROFILE] ?: 0).coerceIn(0, VPN_PROFILE_COUNT - 1)
|
||||
val key = getProfileKey(if (whitelist) WHITELIST_APPS else BLACKLIST_APPS, profile)
|
||||
val packages = prefs[key]
|
||||
.orEmpty()
|
||||
.split(",")
|
||||
.map { it.trim() }
|
||||
.filter { it.isNotEmpty() }
|
||||
.toMutableSet()
|
||||
if (!packages.add(packageName)) packages.remove(packageName)
|
||||
val packages = sanitizeVpnRoutingPackages(
|
||||
decodeStoredVpnPackages(prefs[key].orEmpty()),
|
||||
appContext.packageName,
|
||||
).toMutableSet()
|
||||
if (!packages.add(normalizedPackage)) packages.remove(normalizedPackage)
|
||||
prefs[key] = packages.sorted().joinToString(",")
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun addBlacklistPackages(newPackages: Set<String>): Int {
|
||||
suspend fun addBlacklistPackages(
|
||||
newPackages: Set<String>,
|
||||
profileIndex: Int? = null,
|
||||
): Int {
|
||||
var addedCount = 0
|
||||
dataStore.edit { prefs ->
|
||||
val profile = prefs[ACTIVE_PROFILE] ?: 0
|
||||
val profile = profileIndex?.coerceIn(0, VPN_PROFILE_COUNT - 1)
|
||||
?: (prefs[ACTIVE_PROFILE] ?: 0).coerceIn(0, VPN_PROFILE_COUNT - 1)
|
||||
val key = getProfileKey(BLACKLIST_APPS, profile)
|
||||
val packages = prefs[key]
|
||||
.orEmpty()
|
||||
.split(",")
|
||||
.map { it.trim() }
|
||||
.filter { it.isNotEmpty() }
|
||||
.toMutableSet()
|
||||
val packages = sanitizeVpnRoutingPackages(
|
||||
decodeStoredVpnPackages(prefs[key].orEmpty()),
|
||||
appContext.packageName,
|
||||
).toMutableSet()
|
||||
val before = packages.size
|
||||
packages.addAll(newPackages)
|
||||
packages.addAll(sanitizeVpnRoutingPackages(newPackages, appContext.packageName))
|
||||
addedCount = packages.size - before
|
||||
prefs[key] = packages.sorted().joinToString(",")
|
||||
}
|
||||
return addedCount
|
||||
}
|
||||
|
||||
internal suspend fun addVpnAddressRules(
|
||||
rawValue: String,
|
||||
whitelist: Boolean,
|
||||
profileIndex: Int? = null,
|
||||
): List<VpnAddressRule> {
|
||||
val normalized = normalizeVpnAddressRules(rawValue)
|
||||
dataStore.edit { prefs ->
|
||||
val profile = profileIndex?.coerceIn(0, VPN_PROFILE_COUNT - 1)
|
||||
?: (prefs[ACTIVE_PROFILE] ?: 0).coerceIn(0, VPN_PROFILE_COUNT - 1)
|
||||
val key = getProfileKey(
|
||||
if (whitelist) WHITELIST_ADDRESSES else BLACKLIST_ADDRESSES,
|
||||
profile,
|
||||
)
|
||||
val rules = decodeVpnAddressRules(prefs[key].orEmpty()).toMutableList()
|
||||
val newRules = normalized.filterNot(rules::contains)
|
||||
if (newRules.isNotEmpty()) {
|
||||
require(rules.size + newRules.size <= MAX_VPN_ADDRESS_RULES) {
|
||||
"В одном списке может быть не больше $MAX_VPN_ADDRESS_RULES адресов."
|
||||
}
|
||||
rules += newRules
|
||||
prefs[key] = encodeVpnAddressRules(rules)
|
||||
}
|
||||
}
|
||||
return normalized
|
||||
}
|
||||
|
||||
internal suspend fun removeVpnAddressRule(
|
||||
rule: VpnAddressRule,
|
||||
whitelist: Boolean,
|
||||
profileIndex: Int? = null,
|
||||
) {
|
||||
dataStore.edit { prefs ->
|
||||
val profile = profileIndex?.coerceIn(0, VPN_PROFILE_COUNT - 1)
|
||||
?: (prefs[ACTIVE_PROFILE] ?: 0).coerceIn(0, VPN_PROFILE_COUNT - 1)
|
||||
val key = getProfileKey(
|
||||
if (whitelist) WHITELIST_ADDRESSES else BLACKLIST_ADDRESSES,
|
||||
profile,
|
||||
)
|
||||
val rules = decodeVpnAddressRules(prefs[key].orEmpty()).filterNot { it == rule }
|
||||
prefs[key] = encodeVpnAddressRules(rules)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun exportVpnRoutingSettings(profileIndex: Int? = null): String = preferencesFlow.map { prefs ->
|
||||
val profile = profileIndex?.coerceIn(0, VPN_PROFILE_COUNT - 1)
|
||||
?: (prefs[ACTIVE_PROFILE] ?: 0).coerceIn(0, VPN_PROFILE_COUNT - 1)
|
||||
encodeVpnRoutingDocument(
|
||||
VpnRoutingDocument(
|
||||
isWhitelist = prefs[getProfileKey(IS_WHITELIST, profile)] ?: false,
|
||||
blacklistApps = sanitizeVpnRoutingPackages(
|
||||
decodeStoredVpnPackages(prefs[getProfileKey(BLACKLIST_APPS, profile)].orEmpty()),
|
||||
appContext.packageName,
|
||||
),
|
||||
whitelistApps = sanitizeVpnRoutingPackages(
|
||||
decodeStoredVpnPackages(prefs[getProfileKey(WHITELIST_APPS, profile)].orEmpty()),
|
||||
appContext.packageName,
|
||||
),
|
||||
blacklistAddresses = decodeVpnAddressRules(
|
||||
prefs[getProfileKey(BLACKLIST_ADDRESSES, profile)].orEmpty()
|
||||
),
|
||||
whitelistAddresses = decodeVpnAddressRules(
|
||||
prefs[getProfileKey(WHITELIST_ADDRESSES, profile)].orEmpty()
|
||||
),
|
||||
)
|
||||
)
|
||||
}.first()
|
||||
|
||||
internal suspend fun importVpnRoutingSettings(
|
||||
settingsJson: String,
|
||||
profileIndex: Int? = null,
|
||||
): VpnRoutingImportResult {
|
||||
val imported = decodeVpnRoutingDocument(settingsJson)
|
||||
val document = imported.copy(
|
||||
blacklistApps = sanitizeVpnRoutingPackages(
|
||||
imported.blacklistApps,
|
||||
appContext.packageName,
|
||||
),
|
||||
whitelistApps = sanitizeVpnRoutingPackages(
|
||||
imported.whitelistApps,
|
||||
appContext.packageName,
|
||||
),
|
||||
)
|
||||
|
||||
dataStore.edit { prefs ->
|
||||
val profile = profileIndex?.coerceIn(0, VPN_PROFILE_COUNT - 1)
|
||||
?: (prefs[ACTIVE_PROFILE] ?: 0).coerceIn(0, VPN_PROFILE_COUNT - 1)
|
||||
prefs[getProfileKey(IS_WHITELIST, profile)] = document.isWhitelist
|
||||
prefs[getProfileKey(BLACKLIST_APPS, profile)] = document.blacklistApps.joinToString(",")
|
||||
prefs[getProfileKey(WHITELIST_APPS, profile)] = document.whitelistApps.joinToString(",")
|
||||
prefs[getProfileKey(BLACKLIST_ADDRESSES, profile)] =
|
||||
encodeVpnAddressRules(document.blacklistAddresses)
|
||||
prefs[getProfileKey(WHITELIST_ADDRESSES, profile)] =
|
||||
encodeVpnAddressRules(document.whitelistAddresses)
|
||||
}
|
||||
return VpnRoutingImportResult(
|
||||
blacklistAppCount = document.blacklistApps.size,
|
||||
whitelistAppCount = document.whitelistApps.size,
|
||||
blacklistAddressCount = document.blacklistAddresses.size,
|
||||
whitelistAddressCount = document.whitelistAddresses.size,
|
||||
isWhitelist = document.isWhitelist,
|
||||
)
|
||||
}
|
||||
|
||||
internal suspend fun saveVpnDnsSettings(
|
||||
selectionId: String,
|
||||
customServersRaw: String = "",
|
||||
profileIndex: Int? = null,
|
||||
): VpnDnsSettingsSnapshot {
|
||||
val selection = normalizeVpnDnsSelectionId(selectionId)
|
||||
require(selection == selectionId.trim().lowercase()) {
|
||||
"Неизвестный вариант DNS."
|
||||
}
|
||||
val customServers = if (selection == VPN_DNS_CUSTOM_ID) {
|
||||
normalizeCustomVpnDnsServers(customServersRaw)
|
||||
} else {
|
||||
decodeStoredCustomVpnDnsServers(customServersRaw)
|
||||
}
|
||||
var savedProfile = 0
|
||||
dataStore.edit { prefs ->
|
||||
savedProfile = profileIndex?.coerceIn(0, VPN_PROFILE_COUNT - 1)
|
||||
?: (prefs[ACTIVE_PROFILE] ?: 0).coerceIn(0, VPN_PROFILE_COUNT - 1)
|
||||
prefs[getProfileKey(VPN_DNS_SELECTION, savedProfile)] = selection
|
||||
if (customServers.isEmpty()) {
|
||||
prefs.remove(getProfileKey(VPN_DNS_CUSTOM, savedProfile))
|
||||
} else {
|
||||
prefs[getProfileKey(VPN_DNS_CUSTOM, savedProfile)] =
|
||||
customServers.joinToString(",")
|
||||
}
|
||||
}
|
||||
return VpnDnsSettingsSnapshot(
|
||||
profileIndex = savedProfile,
|
||||
selectionId = selection,
|
||||
customServers = customServers,
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun saveDetailedLogs(enabled: Boolean) {
|
||||
dataStore.edit { prefs ->
|
||||
@@ -3192,9 +3733,10 @@ class SettingsStore(context: Context) {
|
||||
}
|
||||
|
||||
// ═══ Сохранение режима списка (ЧС/БС) ═══
|
||||
suspend fun saveIsWhitelist(enabled: Boolean) {
|
||||
suspend fun saveIsWhitelist(enabled: Boolean, profileIndex: Int? = null) {
|
||||
dataStore.edit { prefs ->
|
||||
val profile = prefs[ACTIVE_PROFILE] ?: 0
|
||||
val profile = profileIndex?.coerceIn(0, VPN_PROFILE_COUNT - 1)
|
||||
?: (prefs[ACTIVE_PROFILE] ?: 0).coerceIn(0, VPN_PROFILE_COUNT - 1)
|
||||
prefs[getProfileKey(IS_WHITELIST, profile)] = enabled
|
||||
}
|
||||
}
|
||||
@@ -3242,18 +3784,31 @@ class SettingsStore(context: Context) {
|
||||
for (profile in 0 until VPN_PROFILE_COUNT) {
|
||||
val legacyKey = getProfileKey(EXCLUDED_APPS, profile)
|
||||
val legacyPackages = prefs[legacyKey].orEmpty()
|
||||
if (legacyPackages.isBlank()) continue
|
||||
if (legacyPackages.isNotBlank()) {
|
||||
val targetBaseKey = if (prefs[getProfileKey(IS_WHITELIST, profile)] == true) {
|
||||
WHITELIST_APPS
|
||||
} else {
|
||||
BLACKLIST_APPS
|
||||
}
|
||||
val targetKey = getProfileKey(targetBaseKey, profile)
|
||||
if (prefs[targetKey] == null) {
|
||||
prefs[targetKey] = sanitizeVpnRoutingPackages(
|
||||
decodeStoredVpnPackages(legacyPackages),
|
||||
appContext.packageName,
|
||||
).joinToString(",")
|
||||
}
|
||||
}
|
||||
|
||||
val targetBaseKey = if (prefs[getProfileKey(IS_WHITELIST, profile)] == true) {
|
||||
WHITELIST_APPS
|
||||
} else {
|
||||
BLACKLIST_APPS
|
||||
listOf(BLACKLIST_APPS, WHITELIST_APPS).forEach { baseKey ->
|
||||
val key = getProfileKey(baseKey, profile)
|
||||
val stored = prefs[key] ?: return@forEach
|
||||
val sanitized = sanitizeVpnRoutingPackages(
|
||||
decodeStoredVpnPackages(stored),
|
||||
appContext.packageName,
|
||||
).joinToString(",")
|
||||
if (stored != sanitized) prefs[key] = sanitized
|
||||
}
|
||||
val targetKey = getProfileKey(targetBaseKey, profile)
|
||||
if (prefs[targetKey] == null) {
|
||||
prefs[targetKey] = legacyPackages
|
||||
}
|
||||
prefs.remove(legacyKey)
|
||||
if (prefs[legacyKey] != null) prefs.remove(legacyKey)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3778,6 +4333,11 @@ class SettingsStore(context: Context) {
|
||||
|
||||
fun vpnProfileDefaultName(profile: Int): String = "VPN ${profile.coerceIn(0, 2) + 1}"
|
||||
|
||||
private fun importedVpnAddressRules(item: JSONObject, key: String): String {
|
||||
if (!item.has(key)) return encodeVpnAddressRules(emptyList())
|
||||
return encodeVpnAddressRules(decodeVpnAddressRulesStrict(item.optString(key)))
|
||||
}
|
||||
|
||||
private fun parseTrustedWifiSsids(raw: String): List<String> {
|
||||
if (raw.isBlank()) return emptyList()
|
||||
return runCatching {
|
||||
|
||||
@@ -19,9 +19,12 @@ import javax.crypto.spec.SecretKeySpec
|
||||
private const val TRANSFER_FORMAT = "wdtt-plus-transfer"
|
||||
private const val TRANSFER_VERSION = 1
|
||||
private const val ADMIN_KIND = "admin-settings"
|
||||
private const val SERVER_BACKUP_KIND = "server-backup"
|
||||
private const val PBKDF2_ITERATIONS = 210_000
|
||||
private const val KEY_BITS = 256
|
||||
private const val GCM_TAG_BITS = 128
|
||||
private const val MAX_TRANSFER_DOCUMENT_CHARS = 12_000_000
|
||||
private const val MAX_TRANSFER_PLAINTEXT_BYTES = 8_000_000
|
||||
|
||||
data class AdminTransferPreview(
|
||||
val createdAt: Long,
|
||||
@@ -100,20 +103,31 @@ object WdttTransferCodec {
|
||||
}
|
||||
|
||||
fun encryptAdminSettings(settingsJson: String, password: CharArray): String {
|
||||
return encryptDocument(settingsJson, password, ADMIN_KIND)
|
||||
}
|
||||
|
||||
fun encryptServerBackup(backupJson: String, password: CharArray): String {
|
||||
return encryptDocument(backupJson, password, SERVER_BACKUP_KIND)
|
||||
}
|
||||
|
||||
private fun encryptDocument(value: String, password: CharArray, kind: String): String {
|
||||
require(password.size >= 8) { "Пароль должен содержать не меньше 8 символов." }
|
||||
require(value.toByteArray(StandardCharsets.UTF_8).size <= MAX_TRANSFER_PLAINTEXT_BYTES) {
|
||||
"Данные для передачи слишком большие."
|
||||
}
|
||||
val salt = ByteArray(16).also(random::nextBytes)
|
||||
val iv = ByteArray(12).also(random::nextBytes)
|
||||
val key = deriveKey(password, salt, PBKDF2_ITERATIONS)
|
||||
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
|
||||
cipher.init(Cipher.ENCRYPT_MODE, key, GCMParameterSpec(GCM_TAG_BITS, iv))
|
||||
val compressed = gzip(settingsJson.toByteArray(StandardCharsets.UTF_8))
|
||||
val compressed = gzip(value.toByteArray(StandardCharsets.UTF_8))
|
||||
val encrypted = cipher.doFinal(compressed)
|
||||
key.encoded?.fill(0)
|
||||
|
||||
return JSONObject()
|
||||
.put("format", TRANSFER_FORMAT)
|
||||
.put("version", TRANSFER_VERSION)
|
||||
.put("kind", ADMIN_KIND)
|
||||
.put("kind", kind)
|
||||
.put("createdAt", System.currentTimeMillis())
|
||||
.put("sourceVersion", BuildConfig.VERSION_NAME)
|
||||
.put("kdf", "PBKDF2-HMAC-SHA256")
|
||||
@@ -125,10 +139,11 @@ object WdttTransferCodec {
|
||||
}
|
||||
|
||||
fun isAdminTransfer(value: String): Boolean = runCatching {
|
||||
val json = JSONObject(value.trim())
|
||||
json.optString("format") == TRANSFER_FORMAT &&
|
||||
json.optInt("version") == TRANSFER_VERSION &&
|
||||
json.optString("kind") == ADMIN_KIND
|
||||
hasEnvelopeKind(value, ADMIN_KIND)
|
||||
}.getOrDefault(false)
|
||||
|
||||
fun isEncryptedServerBackup(value: String): Boolean = runCatching {
|
||||
hasEnvelopeKind(value, SERVER_BACKUP_KIND)
|
||||
}.getOrDefault(false)
|
||||
|
||||
fun documentFormat(value: String): String? = runCatching {
|
||||
@@ -145,19 +160,33 @@ object WdttTransferCodec {
|
||||
}
|
||||
|
||||
fun decryptAdminSettings(value: String, password: CharArray): String {
|
||||
return decryptDocument(value, password, ADMIN_KIND)
|
||||
}
|
||||
|
||||
fun decryptServerBackup(value: String, password: CharArray): String {
|
||||
return decryptDocument(value, password, SERVER_BACKUP_KIND)
|
||||
}
|
||||
|
||||
private fun decryptDocument(value: String, password: CharArray, kind: String): String {
|
||||
require(password.isNotEmpty()) { "Введите пароль файла." }
|
||||
val json = requireAdminEnvelope(value)
|
||||
val json = requireEnvelope(value, kind)
|
||||
val iterations = json.optInt("iterations", 0)
|
||||
require(iterations in 100_000..1_000_000) { "Некорректные параметры защиты файла." }
|
||||
val salt = Base64.getDecoder().decode(json.getString("salt"))
|
||||
val iv = Base64.getDecoder().decode(json.getString("iv"))
|
||||
val encrypted = Base64.getDecoder().decode(json.getString("data"))
|
||||
val data = json.getString("data")
|
||||
require(data.length <= 10_700_000) { "Файл передачи слишком большой." }
|
||||
val salt = runCatching { Base64.getDecoder().decode(json.getString("salt")) }
|
||||
.getOrElse { throw IllegalArgumentException("Файл передачи повреждён.") }
|
||||
val iv = runCatching { Base64.getDecoder().decode(json.getString("iv")) }
|
||||
.getOrElse { throw IllegalArgumentException("Файл передачи повреждён.") }
|
||||
val encrypted = runCatching { Base64.getDecoder().decode(data) }
|
||||
.getOrElse { throw IllegalArgumentException("Файл передачи повреждён.") }
|
||||
require(salt.size == 16 && iv.size == 12) { "Файл передачи повреждён." }
|
||||
val key = deriveKey(password, salt, iterations)
|
||||
return try {
|
||||
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
|
||||
cipher.init(Cipher.DECRYPT_MODE, key, GCMParameterSpec(GCM_TAG_BITS, iv))
|
||||
ungzip(cipher.doFinal(encrypted)).toString(StandardCharsets.UTF_8)
|
||||
ungzip(cipher.doFinal(encrypted), MAX_TRANSFER_PLAINTEXT_BYTES)
|
||||
.toString(StandardCharsets.UTF_8)
|
||||
} catch (_: Exception) {
|
||||
throw IllegalArgumentException("Неверный пароль или файл повреждён.")
|
||||
} finally {
|
||||
@@ -166,11 +195,27 @@ object WdttTransferCodec {
|
||||
}
|
||||
|
||||
private fun requireAdminEnvelope(value: String): JSONObject {
|
||||
return requireEnvelope(value, ADMIN_KIND)
|
||||
}
|
||||
|
||||
private fun hasEnvelopeKind(value: String, kind: String): Boolean {
|
||||
if (value.length > MAX_TRANSFER_DOCUMENT_CHARS) return false
|
||||
val json = JSONObject(value.trim())
|
||||
return json.optString("format") == TRANSFER_FORMAT &&
|
||||
json.optInt("version") == TRANSFER_VERSION &&
|
||||
json.optString("kind") == kind
|
||||
}
|
||||
|
||||
private fun requireEnvelope(value: String, kind: String): JSONObject {
|
||||
require(value.length <= MAX_TRANSFER_DOCUMENT_CHARS) { "Файл передачи слишком большой." }
|
||||
val json = runCatching { JSONObject(value.trim()) }
|
||||
.getOrElse { throw IllegalArgumentException("Файл передачи повреждён или имеет неизвестный формат.") }
|
||||
require(json.optString("format") == TRANSFER_FORMAT) { "Это не файл передачи WDTT Plus." }
|
||||
require(json.optInt("version") == TRANSFER_VERSION) { "Версия файла пока не поддерживается." }
|
||||
require(json.optString("kind") == ADMIN_KIND) { "В файле нет настроек администратора." }
|
||||
require(json.optString("kind") == kind) {
|
||||
if (kind == ADMIN_KIND) "В файле нет настроек администратора."
|
||||
else "В файле нет резервной копии сервера."
|
||||
}
|
||||
return json
|
||||
}
|
||||
|
||||
@@ -189,8 +234,21 @@ object WdttTransferCodec {
|
||||
output.toByteArray()
|
||||
}
|
||||
|
||||
private fun ungzip(value: ByteArray): ByteArray =
|
||||
GZIPInputStream(ByteArrayInputStream(value)).use { it.readBytes() }
|
||||
private fun ungzip(value: ByteArray, maxBytes: Int): ByteArray =
|
||||
GZIPInputStream(ByteArrayInputStream(value)).use { input ->
|
||||
ByteArrayOutputStream().use { output ->
|
||||
val buffer = ByteArray(16 * 1024)
|
||||
var total = 0
|
||||
while (true) {
|
||||
val read = input.read(buffer)
|
||||
if (read < 0) break
|
||||
total += read
|
||||
require(total <= maxBytes) { "Распакованные данные слишком большие." }
|
||||
output.write(buffer, 0, read)
|
||||
}
|
||||
output.toByteArray()
|
||||
}
|
||||
}
|
||||
|
||||
private fun encode(value: String): String = URLEncoder.encode(value, StandardCharsets.UTF_8.name())
|
||||
.replace("+", "%20")
|
||||
|
||||
@@ -36,38 +36,65 @@ internal fun trustedWifiResumeRetryPlan(retryCount: Int): TrustedWifiResumeRetry
|
||||
TrustedWifiResumeRetryPlan(delayMs = 30_000L, keepCpuAwake = false)
|
||||
}
|
||||
|
||||
internal class TrustedWifiValidatedNetworkTracker<T : Any> {
|
||||
internal class TrustedWifiResumeNetworkTracker<T : Any> {
|
||||
private val validatedNetworks = ConcurrentHashMap.newKeySet<T>()
|
||||
private val limitedNonWifiNetworks = ConcurrentHashMap.newKeySet<T>()
|
||||
private val wifiNetworks = ConcurrentHashMap.newKeySet<T>()
|
||||
|
||||
@Synchronized
|
||||
fun update(network: T, validated: Boolean, wifi: Boolean) {
|
||||
if (validated) validatedNetworks.add(network) else validatedNetworks.remove(network)
|
||||
fun update(
|
||||
network: T,
|
||||
internetCapable: Boolean,
|
||||
validated: Boolean,
|
||||
wifi: Boolean,
|
||||
) {
|
||||
if (internetCapable && validated) {
|
||||
validatedNetworks.add(network)
|
||||
} else {
|
||||
validatedNetworks.remove(network)
|
||||
}
|
||||
if (internetCapable && !wifi) {
|
||||
limitedNonWifiNetworks.add(network)
|
||||
} else {
|
||||
limitedNonWifiNetworks.remove(network)
|
||||
}
|
||||
if (wifi) wifiNetworks.add(network) else wifiNetworks.remove(network)
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun lost(network: T) {
|
||||
validatedNetworks.remove(network)
|
||||
limitedNonWifiNetworks.remove(network)
|
||||
wifiNetworks.remove(network)
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun forgetWifi() {
|
||||
wifiNetworks.forEach { network -> validatedNetworks.remove(network) }
|
||||
wifiNetworks.forEach { network ->
|
||||
validatedNetworks.remove(network)
|
||||
limitedNonWifiNetworks.remove(network)
|
||||
}
|
||||
wifiNetworks.clear()
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun hasUsableNetwork(): Boolean = validatedNetworks.isNotEmpty()
|
||||
fun hasUsableNetwork(): Boolean =
|
||||
validatedNetworks.isNotEmpty() || limitedNonWifiNetworks.isNotEmpty()
|
||||
|
||||
@Synchronized
|
||||
fun clear() {
|
||||
validatedNetworks.clear()
|
||||
limitedNonWifiNetworks.clear()
|
||||
wifiNetworks.clear()
|
||||
}
|
||||
}
|
||||
|
||||
internal fun isUsableTrustedWifiResumeNetwork(
|
||||
internetCapable: Boolean,
|
||||
validated: Boolean,
|
||||
wifi: Boolean,
|
||||
): Boolean = internetCapable && (validated || !wifi)
|
||||
|
||||
object TrustedWifiManager {
|
||||
private val _state = MutableStateFlow(TrustedWifiRuntimeState())
|
||||
val state = _state.asStateFlow()
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,10 +1,33 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
import android.content.Context
|
||||
import java.util.Locale
|
||||
|
||||
private val tunnelTrafficPairRegex = Regex(
|
||||
"↓\\s*([0-9]+(?:[.,][0-9]+)?)\\s*МБ\\s*/\\s*↑\\s*([0-9]+(?:[.,][0-9]+)?)\\s*МБ"
|
||||
)
|
||||
private val tunnelTrafficValueMbRegex = Regex(
|
||||
"([↓↑])\\s*([0-9]+(?:[.,][0-9]+)?)\\s*МБ"
|
||||
)
|
||||
|
||||
internal fun formatTunnelTrafficForNotification(message: String): String =
|
||||
tunnelTrafficValueMbRegex.replace(message) { match ->
|
||||
val megabytes = match.groupValues[2].replace(',', '.').toDoubleOrNull()
|
||||
?: return@replace match.value
|
||||
if (megabytes < MEBIBYTES_PER_GIBIBYTE) {
|
||||
match.value
|
||||
} else {
|
||||
val gibibytes = megabytes / MEBIBYTES_PER_GIBIBYTE
|
||||
"${match.groupValues[1]}${String.format(Locale.US, "%.2f", gibibytes)} ГБ"
|
||||
}
|
||||
}
|
||||
|
||||
internal data class TunnelSessionTrafficSnapshot(
|
||||
val downloadOffsetMb: Double,
|
||||
val uploadOffsetMb: Double,
|
||||
val lastRawDownloadMb: Double?,
|
||||
val lastRawUploadMb: Double?,
|
||||
)
|
||||
|
||||
internal class TunnelSessionTrafficAccumulator {
|
||||
private var downloadOffsetMb = 0.0
|
||||
@@ -20,6 +43,24 @@ internal class TunnelSessionTrafficAccumulator {
|
||||
lastRawUploadMb = null
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun restore(snapshot: TunnelSessionTrafficSnapshot?) {
|
||||
reset()
|
||||
if (snapshot == null || !snapshot.isValid()) return
|
||||
downloadOffsetMb = snapshot.downloadOffsetMb
|
||||
uploadOffsetMb = snapshot.uploadOffsetMb
|
||||
lastRawDownloadMb = snapshot.lastRawDownloadMb
|
||||
lastRawUploadMb = snapshot.lastRawUploadMb
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun snapshot(): TunnelSessionTrafficSnapshot = TunnelSessionTrafficSnapshot(
|
||||
downloadOffsetMb = downloadOffsetMb,
|
||||
uploadOffsetMb = uploadOffsetMb,
|
||||
lastRawDownloadMb = lastRawDownloadMb,
|
||||
lastRawUploadMb = lastRawUploadMb,
|
||||
)
|
||||
|
||||
@Synchronized
|
||||
fun noteTransportRestart() {
|
||||
downloadOffsetMb += lastRawDownloadMb ?: 0.0
|
||||
@@ -61,3 +102,83 @@ internal class TunnelSessionTrafficAccumulator {
|
||||
const val TRAFFIC_RESET_TOLERANCE_MB = 0.005
|
||||
}
|
||||
}
|
||||
|
||||
private fun TunnelSessionTrafficSnapshot.isValid(): Boolean =
|
||||
downloadOffsetMb.isFinite() && downloadOffsetMb >= 0.0 &&
|
||||
uploadOffsetMb.isFinite() && uploadOffsetMb >= 0.0 &&
|
||||
lastRawDownloadMb.isValidTrafficValue() &&
|
||||
lastRawUploadMb.isValidTrafficValue()
|
||||
|
||||
private fun Double?.isValidTrafficValue(): Boolean =
|
||||
this == null || (isFinite() && this >= 0.0)
|
||||
|
||||
private const val MEBIBYTES_PER_GIBIBYTE = 1024.0
|
||||
|
||||
internal class TunnelSessionTrafficStore(context: Context) {
|
||||
private val appContext = context.applicationContext
|
||||
private val preferences = appContext.getSharedPreferences(
|
||||
PREFERENCES_NAME,
|
||||
Context.MODE_PRIVATE,
|
||||
)
|
||||
private val currentBootCount = runCatching {
|
||||
android.provider.Settings.Global.getInt(
|
||||
appContext.contentResolver,
|
||||
android.provider.Settings.Global.BOOT_COUNT,
|
||||
)
|
||||
}.getOrDefault(UNKNOWN_BOOT_COUNT)
|
||||
|
||||
fun load(): TunnelSessionTrafficSnapshot? {
|
||||
if (preferences.getInt(KEY_VERSION, 0) != SNAPSHOT_VERSION) return null
|
||||
val savedBootCount = preferences.getInt(KEY_BOOT_COUNT, UNKNOWN_BOOT_COUNT)
|
||||
if (
|
||||
currentBootCount != UNKNOWN_BOOT_COUNT &&
|
||||
savedBootCount != UNKNOWN_BOOT_COUNT &&
|
||||
currentBootCount != savedBootCount
|
||||
) return null
|
||||
return TunnelSessionTrafficSnapshot(
|
||||
downloadOffsetMb = preferences.getString(KEY_DOWNLOAD_OFFSET, null)?.toDoubleOrNull()
|
||||
?: return null,
|
||||
uploadOffsetMb = preferences.getString(KEY_UPLOAD_OFFSET, null)?.toDoubleOrNull()
|
||||
?: return null,
|
||||
lastRawDownloadMb = preferences.getString(KEY_LAST_RAW_DOWNLOAD, null)?.toDoubleOrNull(),
|
||||
lastRawUploadMb = preferences.getString(KEY_LAST_RAW_UPLOAD, null)?.toDoubleOrNull(),
|
||||
).takeIf(TunnelSessionTrafficSnapshot::isValid)
|
||||
}
|
||||
|
||||
fun save(snapshot: TunnelSessionTrafficSnapshot) {
|
||||
if (!snapshot.isValid()) return
|
||||
preferences.edit()
|
||||
.putInt(KEY_VERSION, SNAPSHOT_VERSION)
|
||||
.putInt(KEY_BOOT_COUNT, currentBootCount)
|
||||
.putString(KEY_DOWNLOAD_OFFSET, snapshot.downloadOffsetMb.toString())
|
||||
.putString(KEY_UPLOAD_OFFSET, snapshot.uploadOffsetMb.toString())
|
||||
.putNullableDouble(KEY_LAST_RAW_DOWNLOAD, snapshot.lastRawDownloadMb)
|
||||
.putNullableDouble(KEY_LAST_RAW_UPLOAD, snapshot.lastRawUploadMb)
|
||||
.apply()
|
||||
}
|
||||
|
||||
fun clear() {
|
||||
preferences.edit().clear().apply()
|
||||
}
|
||||
|
||||
private fun android.content.SharedPreferences.Editor.putNullableDouble(
|
||||
key: String,
|
||||
value: Double?,
|
||||
): android.content.SharedPreferences.Editor = if (value == null) {
|
||||
remove(key)
|
||||
} else {
|
||||
putString(key, value.toString())
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val PREFERENCES_NAME = "wdtt_tunnel_session_traffic"
|
||||
const val SNAPSHOT_VERSION = 1
|
||||
const val UNKNOWN_BOOT_COUNT = -1
|
||||
const val KEY_VERSION = "version"
|
||||
const val KEY_BOOT_COUNT = "boot_count"
|
||||
const val KEY_DOWNLOAD_OFFSET = "download_offset_mb"
|
||||
const val KEY_UPLOAD_OFFSET = "upload_offset_mb"
|
||||
const val KEY_LAST_RAW_DOWNLOAD = "last_raw_download_mb"
|
||||
const val KEY_LAST_RAW_UPLOAD = "last_raw_upload_mb"
|
||||
}
|
||||
}
|
||||
@@ -82,13 +82,16 @@ internal fun displayedTunnelProfile(
|
||||
internal fun shouldUseManagedConfigFirstStart(
|
||||
remoteManaged: Boolean,
|
||||
profileMaxWorkers: Int,
|
||||
): Boolean = remoteManaged && profileMaxWorkers == TUNNEL_WORKERS_PER_GROUP
|
||||
): Boolean = remoteManaged &&
|
||||
profileMaxWorkers in TUNNEL_WORKERS_PER_GROUP..APP_MAX_WORKERS &&
|
||||
profileMaxWorkers % TUNNEL_WORKERS_PER_GROUP == 0
|
||||
|
||||
suspend fun buildTunnelParamsFromSettings(
|
||||
context: Context,
|
||||
profileIndex: Int? = null,
|
||||
): TunnelParams? {
|
||||
val store = SettingsStore(context.applicationContext)
|
||||
store.reconcileRemoteProfileWorkerLimit(profileIndex)
|
||||
val saved = store.tunnelProfileSnapshot(profileIndex)
|
||||
return buildTunnelParams(saved)
|
||||
}
|
||||
|
||||
@@ -12,3 +12,35 @@ internal fun normalizeTunnelWorkerCount(requested: Int, profileMaxWorkers: Int =
|
||||
TUNNEL_WORKERS_PER_GROUP) * TUNNEL_WORKERS_PER_GROUP
|
||||
return rounded.coerceIn(TUNNEL_WORKERS_PER_GROUP, maximum)
|
||||
}
|
||||
|
||||
internal fun reconcileTunnelWorkerCountForProfileLimit(
|
||||
selectedWorkers: Int,
|
||||
previousProfileMaxWorkers: Int?,
|
||||
currentProfileMaxWorkers: Int,
|
||||
remoteManaged: Boolean,
|
||||
): Int {
|
||||
val normalizedCurrent = normalizeTunnelWorkerCount(
|
||||
selectedWorkers,
|
||||
currentProfileMaxWorkers,
|
||||
)
|
||||
if (!remoteManaged || currentProfileMaxWorkers !in TUNNEL_WORKERS_PER_GROUP..APP_MAX_WORKERS) {
|
||||
return normalizedCurrent
|
||||
}
|
||||
if (currentProfileMaxWorkers % TUNNEL_WORKERS_PER_GROUP != 0) return normalizedCurrent
|
||||
|
||||
val previousLimit = previousProfileMaxWorkers?.takeIf {
|
||||
it in TUNNEL_WORKERS_PER_GROUP..APP_MAX_WORKERS &&
|
||||
it % TUNNEL_WORKERS_PER_GROUP == 0
|
||||
}
|
||||
if (previousLimit == null) return currentProfileMaxWorkers
|
||||
|
||||
val selectedAtPreviousCeiling = normalizeTunnelWorkerCount(
|
||||
selectedWorkers,
|
||||
previousLimit,
|
||||
) == previousLimit
|
||||
return if (currentProfileMaxWorkers > previousLimit && selectedAtPreviousCeiling) {
|
||||
currentProfileMaxWorkers
|
||||
} else {
|
||||
normalizedCurrent
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,479 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.net.IDN
|
||||
|
||||
internal const val MAX_VPN_ADDRESS_RULES = 128
|
||||
internal const val MAX_VPN_ADDRESS_IMPORT_BYTES = 1024 * 1024
|
||||
private const val MAX_WIREGUARD_ALLOWED_IPS = 4096
|
||||
private const val MAX_EFFECTIVE_IPV4_PREFIXES = 128
|
||||
private const val IPV4_BITS = 32
|
||||
private const val IPV4_MAX = 0xffff_ffffL
|
||||
|
||||
internal enum class VpnAddressType(val storedValue: String) {
|
||||
DOMAIN("domain"),
|
||||
IP("ip"),
|
||||
SUBNET("subnet");
|
||||
|
||||
companion object {
|
||||
fun fromStoredValue(value: String): VpnAddressType? =
|
||||
entries.firstOrNull { it.storedValue == value }
|
||||
}
|
||||
}
|
||||
|
||||
internal data class VpnAddressRule(
|
||||
val type: VpnAddressType,
|
||||
val value: String,
|
||||
)
|
||||
|
||||
internal data class VpnAddressRoutingResult(
|
||||
val allowedIps: List<String>,
|
||||
val unresolvedDomains: List<String> = emptyList(),
|
||||
)
|
||||
|
||||
internal fun effectiveWireGuardAllowedIps(
|
||||
isWhitelist: Boolean,
|
||||
addressRulesConfigured: Boolean,
|
||||
addressRouting: VpnAddressRoutingResult,
|
||||
vpnDnsIpv4: List<String>,
|
||||
): List<String> = buildList {
|
||||
addAll(addressRouting.allowedIps)
|
||||
if (addressRulesConfigured) {
|
||||
// Android sends DNS to the addresses configured on the VPN interface.
|
||||
// Keep those exact destinations in the tunnel even if an address rule
|
||||
// would otherwise route them directly.
|
||||
vpnDnsIpv4.forEach { dns ->
|
||||
parseIpv4(dns)?.let { add("${formatIpv4(it)}/32") }
|
||||
}
|
||||
}
|
||||
if (
|
||||
!isWhitelist &&
|
||||
addressRulesConfigured &&
|
||||
"0.0.0.0/0" !in addressRouting.allowedIps
|
||||
) {
|
||||
// GoBackend включает общий kill-switch при любом /0. Поэтом ::/0
|
||||
// заблокировал бы и те IPv4-адреса, которые пользователь вынес в ЧС.
|
||||
// Два /1 закрывают всё IPv6 через VPN, но оставляют IPv4 split-route
|
||||
// рабочим: исключённые IPv4 продолжают идти напрямую.
|
||||
add("::/1")
|
||||
add("8000::/1")
|
||||
}
|
||||
}.distinct()
|
||||
|
||||
internal data class VpnRoutingDocument(
|
||||
val isWhitelist: Boolean,
|
||||
val blacklistApps: List<String>,
|
||||
val whitelistApps: List<String>,
|
||||
val blacklistAddresses: List<VpnAddressRule>,
|
||||
val whitelistAddresses: List<VpnAddressRule>,
|
||||
)
|
||||
|
||||
internal fun encodeVpnRoutingDocument(document: VpnRoutingDocument): String =
|
||||
JSONObject().apply {
|
||||
put("format", "wdtt-plus-routing")
|
||||
put("version", 1)
|
||||
put("isWhitelist", document.isWhitelist)
|
||||
put("blacklistApps", JSONArray(document.blacklistApps.distinct().sorted()))
|
||||
put("whitelistApps", JSONArray(document.whitelistApps.distinct().sorted()))
|
||||
put("blacklistAddresses", JSONArray(encodeVpnAddressRules(document.blacklistAddresses)))
|
||||
put("whitelistAddresses", JSONArray(encodeVpnAddressRules(document.whitelistAddresses)))
|
||||
}.toString(2)
|
||||
|
||||
internal fun decodeVpnRoutingDocument(raw: String): VpnRoutingDocument {
|
||||
require(raw.toByteArray(Charsets.UTF_8).size <= MAX_VPN_ADDRESS_IMPORT_BYTES) {
|
||||
"Файл маршрутизации слишком большой."
|
||||
}
|
||||
val root = runCatching { JSONObject(raw) }
|
||||
.getOrElse { throw IllegalArgumentException("Файл маршрутизации повреждён.") }
|
||||
require(root.optString("format") == "wdtt-plus-routing" && root.optInt("version") == 1) {
|
||||
"Это не поддерживаемый файл маршрутизации WDTT Plus."
|
||||
}
|
||||
require(root.opt("isWhitelist") is Boolean) { "В файле повреждён режим ЧС/БС." }
|
||||
return VpnRoutingDocument(
|
||||
isWhitelist = root.getBoolean("isWhitelist"),
|
||||
blacklistApps = parseVpnPackagesJson(root, "blacklistApps"),
|
||||
whitelistApps = parseVpnPackagesJson(root, "whitelistApps"),
|
||||
blacklistAddresses = parseVpnAddressRulesJson(root, "blacklistAddresses"),
|
||||
whitelistAddresses = parseVpnAddressRulesJson(root, "whitelistAddresses"),
|
||||
)
|
||||
}
|
||||
|
||||
internal fun decodeStoredVpnPackages(raw: String): List<String> =
|
||||
raw.split(',').map(String::trim).filter(String::isNotEmpty).distinct().sorted()
|
||||
|
||||
internal fun normalizeVpnAddressRule(
|
||||
rawValue: String,
|
||||
requestedType: VpnAddressType? = null,
|
||||
): VpnAddressRule {
|
||||
val clean = rawValue.trim()
|
||||
require(clean.isNotEmpty()) { "Введите домен, IPv4-адрес или подсеть." }
|
||||
require(clean.length <= 512) { "Адрес слишком длинный." }
|
||||
require('*' !in clean) {
|
||||
"Маска домена требует DNS-перехвата и пока не поддерживается. Добавьте нужные поддомены отдельными строками."
|
||||
}
|
||||
val extractedHost = extractHttpHost(clean) ?: extractBareHostWithPort(clean)
|
||||
|
||||
val type = requestedType ?: when {
|
||||
extractedHost != null && parseIpv4(extractedHost) != null -> VpnAddressType.IP
|
||||
extractedHost != null -> VpnAddressType.DOMAIN
|
||||
'/' in clean -> VpnAddressType.SUBNET
|
||||
parseIpv4(clean) != null -> VpnAddressType.IP
|
||||
else -> VpnAddressType.DOMAIN
|
||||
}
|
||||
|
||||
return when (type) {
|
||||
VpnAddressType.IP -> {
|
||||
require(extractedHost != null || ':' !in clean) {
|
||||
"IPv6 пока не поддерживается; укажите IPv4-адрес."
|
||||
}
|
||||
val address = parseIpv4(extractedHost ?: clean)
|
||||
?: throw IllegalArgumentException("Некорректный IPv4-адрес.")
|
||||
VpnAddressRule(type, formatIpv4(address))
|
||||
}
|
||||
|
||||
VpnAddressType.SUBNET -> {
|
||||
require(':' !in clean) { "IPv6-подсети пока не поддерживаются; укажите IPv4/CIDR." }
|
||||
val prefix = parseIpv4Prefix(clean)
|
||||
?: throw IllegalArgumentException("Некорректная IPv4-подсеть. Пример: 192.168.1.0/24.")
|
||||
VpnAddressRule(type, prefix.toCidr())
|
||||
}
|
||||
|
||||
VpnAddressType.DOMAIN -> {
|
||||
val domain = normalizeDomain(extractedHost ?: clean)
|
||||
VpnAddressRule(type, domain)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal fun normalizeVpnAddressRules(rawValue: String): List<VpnAddressRule> {
|
||||
val entries = rawValue.lineSequence()
|
||||
.map(String::trim)
|
||||
.filter(String::isNotEmpty)
|
||||
.toList()
|
||||
require(entries.isNotEmpty()) { "Введите хотя бы один адрес." }
|
||||
|
||||
val rules = buildList {
|
||||
entries.forEachIndexed { index, entry ->
|
||||
val range = parseIpv4Range(entry)
|
||||
val normalized = if (range == null) {
|
||||
listOf(normalizeVpnAddressRule(entry))
|
||||
} else if (range.first == range.last) {
|
||||
listOf(VpnAddressRule(VpnAddressType.IP, formatIpv4(range.first)))
|
||||
} else {
|
||||
ipv4RangeToPrefixes(range.first, range.last).map { prefix ->
|
||||
VpnAddressRule(VpnAddressType.SUBNET, prefix.toCidr())
|
||||
}
|
||||
}
|
||||
addAll(normalized)
|
||||
require(size <= MAX_VPN_ADDRESS_RULES) {
|
||||
"Адрес или диапазон в строке ${index + 1} создаёт слишком много правил; " +
|
||||
"в одном списке допускается не больше $MAX_VPN_ADDRESS_RULES."
|
||||
}
|
||||
}
|
||||
}
|
||||
return rules.distinct()
|
||||
}
|
||||
|
||||
internal fun encodeVpnAddressRules(rules: List<VpnAddressRule>): String =
|
||||
JSONArray().apply {
|
||||
rules.distinct().take(MAX_VPN_ADDRESS_RULES).forEach { rule ->
|
||||
put(
|
||||
JSONObject()
|
||||
.put("type", rule.type.storedValue)
|
||||
.put("value", rule.value)
|
||||
)
|
||||
}
|
||||
}.toString()
|
||||
|
||||
internal fun decodeVpnAddressRules(raw: String): List<VpnAddressRule> {
|
||||
if (raw.isBlank()) return emptyList()
|
||||
return runCatching {
|
||||
val array = JSONArray(raw)
|
||||
buildList {
|
||||
for (index in 0 until minOf(array.length(), MAX_VPN_ADDRESS_RULES)) {
|
||||
val item = array.optJSONObject(index) ?: continue
|
||||
val type = VpnAddressType.fromStoredValue(item.optString("type")) ?: continue
|
||||
runCatching {
|
||||
normalizeVpnAddressRule(item.optString("value"), type)
|
||||
}.getOrNull()?.let(::add)
|
||||
}
|
||||
}.distinct()
|
||||
}.getOrDefault(emptyList())
|
||||
}
|
||||
|
||||
internal fun decodeVpnAddressRulesStrict(raw: String): List<VpnAddressRule> {
|
||||
if (raw.isBlank()) return emptyList()
|
||||
val array = runCatching { JSONArray(raw) }
|
||||
.getOrElse { throw IllegalArgumentException("Список адресов повреждён.") }
|
||||
require(array.length() <= MAX_VPN_ADDRESS_RULES) {
|
||||
"В одном списке может быть не больше $MAX_VPN_ADDRESS_RULES адресов."
|
||||
}
|
||||
return buildList {
|
||||
for (index in 0 until array.length()) {
|
||||
val item = array.optJSONObject(index)
|
||||
?: throw IllegalArgumentException("Запись адреса №${index + 1} повреждена.")
|
||||
val type = VpnAddressType.fromStoredValue(item.optString("type"))
|
||||
?: throw IllegalArgumentException("Неизвестный тип адреса в записи №${index + 1}.")
|
||||
add(normalizeVpnAddressRule(item.optString("value"), type))
|
||||
}
|
||||
}.distinct()
|
||||
}
|
||||
|
||||
internal fun resolveVpnAddressRouting(
|
||||
isWhitelist: Boolean,
|
||||
rules: List<VpnAddressRule>,
|
||||
domainResolver: (String) -> List<String>,
|
||||
): VpnAddressRoutingResult {
|
||||
if (rules.isEmpty()) {
|
||||
return VpnAddressRoutingResult(allowedIps = listOf("0.0.0.0/0"))
|
||||
}
|
||||
|
||||
val prefixes = linkedSetOf<Ipv4Prefix>()
|
||||
val unresolvedDomains = mutableListOf<String>()
|
||||
rules.forEach { rule ->
|
||||
when (rule.type) {
|
||||
VpnAddressType.IP -> parseIpv4(rule.value)?.let {
|
||||
prefixes += Ipv4Prefix(it, IPV4_BITS)
|
||||
}
|
||||
|
||||
VpnAddressType.SUBNET -> parseIpv4Prefix(rule.value)?.let(prefixes::add)
|
||||
VpnAddressType.DOMAIN -> {
|
||||
val resolved = runCatching { domainResolver(rule.value) }
|
||||
.getOrDefault(emptyList())
|
||||
.mapNotNull(::parseIpv4)
|
||||
.distinct()
|
||||
if (resolved.isEmpty()) {
|
||||
unresolvedDomains += rule.value
|
||||
} else {
|
||||
resolved.forEach { prefixes += Ipv4Prefix(it, IPV4_BITS) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val compactPrefixes = collapseIpv4Prefixes(prefixes)
|
||||
require(compactPrefixes.size <= MAX_EFFECTIVE_IPV4_PREFIXES) {
|
||||
"Домены и адреса дали слишком много IPv4-маршрутов (${compactPrefixes.size}). " +
|
||||
"Сократите список или объедините адреса в подсети."
|
||||
}
|
||||
val allowed = if (isWhitelist) {
|
||||
compactPrefixes
|
||||
} else {
|
||||
subtractIpv4Prefixes(
|
||||
source = listOf(Ipv4Prefix(0L, 0)),
|
||||
excluded = compactPrefixes,
|
||||
)
|
||||
}
|
||||
require(allowed.size <= MAX_WIREGUARD_ALLOWED_IPS) {
|
||||
"Список адресов создаёт слишком много маршрутов (${allowed.size}). Объедините адреса в подсети."
|
||||
}
|
||||
return VpnAddressRoutingResult(
|
||||
allowedIps = allowed.sortedWith(compareBy<Ipv4Prefix> { it.network }.thenBy { it.length })
|
||||
.map(Ipv4Prefix::toCidr),
|
||||
unresolvedDomains = unresolvedDomains,
|
||||
)
|
||||
}
|
||||
|
||||
private fun normalizeDomain(rawValue: String): String {
|
||||
require(
|
||||
':' !in rawValue ||
|
||||
rawValue.startsWith("http://", true) ||
|
||||
rawValue.startsWith("https://", true)
|
||||
) {
|
||||
"Некорректный домен. Для IP используйте IPv4-адрес."
|
||||
}
|
||||
val candidate = if (rawValue.startsWith("http://", true) || rawValue.startsWith("https://", true)) {
|
||||
extractHttpHost(rawValue) ?: throw IllegalArgumentException("В ссылке не найден домен.")
|
||||
} else {
|
||||
require('/' !in rawValue && '?' !in rawValue && '#' !in rawValue && '@' !in rawValue) {
|
||||
"Укажите только домен либо вставьте полную ссылку http/https."
|
||||
}
|
||||
rawValue
|
||||
}
|
||||
val withoutTrailingDot = candidate.trim().trimEnd('.')
|
||||
val ascii = runCatching { IDN.toASCII(withoutTrailingDot, IDN.USE_STD3_ASCII_RULES) }
|
||||
.getOrElse { throw IllegalArgumentException("Некорректный домен.") }
|
||||
.lowercase()
|
||||
require(ascii.isNotEmpty() && ascii.length <= 253) { "Некорректная длина домена." }
|
||||
val labels = ascii.split('.')
|
||||
require(labels.all { label ->
|
||||
label.length in 1..63 &&
|
||||
label.first().isLetterOrDigit() &&
|
||||
label.last().isLetterOrDigit() &&
|
||||
label.all { it.isLetterOrDigit() || it == '-' }
|
||||
}) { "Некорректный домен." }
|
||||
require(labels.any { label -> label.any(Char::isLetter) }) { "Некорректный домен или IPv4-адрес." }
|
||||
return ascii
|
||||
}
|
||||
|
||||
private fun extractHttpHost(rawValue: String): String? {
|
||||
if (!rawValue.startsWith("http://", true) && !rawValue.startsWith("https://", true)) return null
|
||||
val authority = rawValue.substringAfter("://")
|
||||
.substringBefore('/')
|
||||
.substringBefore('?')
|
||||
.substringBefore('#')
|
||||
if (authority.isBlank() || '@' in authority) return null
|
||||
return authority.substringBefore(':').takeIf(String::isNotBlank)
|
||||
}
|
||||
|
||||
private fun extractBareHostWithPort(rawValue: String): String? {
|
||||
if (rawValue.count { it == ':' } != 1) return null
|
||||
val host = rawValue.substringBeforeLast(':').trim()
|
||||
val port = rawValue.substringAfterLast(':').toIntOrNull()
|
||||
if (host.isBlank() || port == null || port !in 1..65535) return null
|
||||
return host
|
||||
}
|
||||
|
||||
private fun parseVpnPackagesJson(root: JSONObject, key: String): List<String> {
|
||||
val array = root.optJSONArray(key)
|
||||
?: throw IllegalArgumentException("В файле нет списка $key.")
|
||||
require(array.length() <= 5_000) { "Список приложений в файле слишком большой." }
|
||||
// В Android встречается системный пакет `android` без точки, поэтому формат
|
||||
// должен принимать и его: файл, созданный самим приложением, обязан импортироваться.
|
||||
val packagePattern = Regex("[A-Za-z_][A-Za-z0-9_]*(?:\\.[A-Za-z0-9_]+)*")
|
||||
return buildList {
|
||||
for (index in 0 until array.length()) {
|
||||
val packageName = array.optString(index).trim()
|
||||
require(packageName.length in 1..255 && packagePattern.matches(packageName)) {
|
||||
"Некорректный пакет приложения в записи №${index + 1}."
|
||||
}
|
||||
add(packageName)
|
||||
}
|
||||
}.distinct().sorted()
|
||||
}
|
||||
|
||||
private fun parseVpnAddressRulesJson(root: JSONObject, key: String): List<VpnAddressRule> {
|
||||
val array = root.optJSONArray(key)
|
||||
?: throw IllegalArgumentException("В файле нет списка $key.")
|
||||
return decodeVpnAddressRulesStrict(array.toString())
|
||||
}
|
||||
|
||||
private data class Ipv4Prefix(
|
||||
val network: Long,
|
||||
val length: Int,
|
||||
) {
|
||||
init {
|
||||
require(length in 0..IPV4_BITS)
|
||||
require(network == (network and prefixMask(length)))
|
||||
}
|
||||
|
||||
fun contains(other: Ipv4Prefix): Boolean =
|
||||
length <= other.length && (other.network and prefixMask(length)) == network
|
||||
|
||||
fun toCidr(): String = "${formatIpv4(network)}/$length"
|
||||
}
|
||||
|
||||
private fun parseIpv4(value: String): Long? {
|
||||
val parts = value.trim().split('.')
|
||||
if (parts.size != 4) return null
|
||||
var result = 0L
|
||||
for (part in parts) {
|
||||
if (part.isEmpty() || part.length > 3 || part.any { !it.isDigit() }) return null
|
||||
if (part.length > 1 && part.startsWith('0')) return null
|
||||
val octet = part.toIntOrNull()?.takeIf { it in 0..255 } ?: return null
|
||||
result = (result shl 8) or octet.toLong()
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
private fun parseIpv4Prefix(value: String): Ipv4Prefix? {
|
||||
val separator = value.indexOf('/')
|
||||
if (separator <= 0 || separator != value.lastIndexOf('/')) return null
|
||||
val address = parseIpv4(value.substring(0, separator)) ?: return null
|
||||
val length = value.substring(separator + 1).toIntOrNull()?.takeIf { it in 0..IPV4_BITS }
|
||||
?: return null
|
||||
return Ipv4Prefix(address and prefixMask(length), length)
|
||||
}
|
||||
|
||||
private fun parseIpv4Range(value: String): LongRange? {
|
||||
val match = Regex("^\\s*([^\\s]+)\\s*[-–—]\\s*([^\\s]+)\\s*$").matchEntire(value)
|
||||
?: return null
|
||||
val first = parseIpv4(match.groupValues[1]) ?: return null
|
||||
val last = parseIpv4(match.groupValues[2]) ?: return null
|
||||
require(first <= last) { "Начало диапазона IPv4 должно быть не больше конца." }
|
||||
return first..last
|
||||
}
|
||||
|
||||
private fun ipv4RangeToPrefixes(first: Long, last: Long): List<Ipv4Prefix> {
|
||||
require(first in 0..IPV4_MAX && last in first..IPV4_MAX)
|
||||
val result = mutableListOf<Ipv4Prefix>()
|
||||
var current = first
|
||||
while (current <= last) {
|
||||
var prefixLength = IPV4_BITS
|
||||
while (prefixLength > 0) {
|
||||
val candidateLength = prefixLength - 1
|
||||
val candidateNetwork = current and prefixMask(candidateLength)
|
||||
if (candidateNetwork != current) break
|
||||
val blockSize = 1L shl (IPV4_BITS - candidateLength)
|
||||
val candidateLast = candidateNetwork + blockSize - 1L
|
||||
if (candidateLast > last) break
|
||||
prefixLength = candidateLength
|
||||
}
|
||||
val prefix = Ipv4Prefix(current, prefixLength)
|
||||
result += prefix
|
||||
current += 1L shl (IPV4_BITS - prefixLength)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
private fun prefixMask(length: Int): Long = when (length) {
|
||||
0 -> 0L
|
||||
IPV4_BITS -> IPV4_MAX
|
||||
else -> (IPV4_MAX shl (IPV4_BITS - length)) and IPV4_MAX
|
||||
}
|
||||
|
||||
private fun formatIpv4(value: Long): String =
|
||||
(3 downTo 0).joinToString(".") { shift -> ((value shr (shift * 8)) and 0xff).toString() }
|
||||
|
||||
private fun collapseIpv4Prefixes(values: Collection<Ipv4Prefix>): List<Ipv4Prefix> {
|
||||
val result = linkedSetOf<Ipv4Prefix>()
|
||||
values.sortedWith(compareBy<Ipv4Prefix> { it.length }.thenBy { it.network }).forEach { prefix ->
|
||||
if (result.none { it.contains(prefix) }) result += prefix
|
||||
}
|
||||
|
||||
for (length in IPV4_BITS downTo 1) {
|
||||
val atLength = result.filter { it.length == length }.mapTo(hashSetOf()) { it.network }
|
||||
val consumed = hashSetOf<Long>()
|
||||
atLength.sorted().forEach { network ->
|
||||
if (network in consumed) return@forEach
|
||||
val bit = 1L shl (IPV4_BITS - length)
|
||||
val sibling = network xor bit
|
||||
if (sibling in atLength) {
|
||||
result.remove(Ipv4Prefix(network, length))
|
||||
result.remove(Ipv4Prefix(sibling, length))
|
||||
result += Ipv4Prefix(network and prefixMask(length - 1), length - 1)
|
||||
consumed += network
|
||||
consumed += sibling
|
||||
}
|
||||
}
|
||||
}
|
||||
return result.toList()
|
||||
}
|
||||
|
||||
private fun subtractIpv4Prefixes(
|
||||
source: List<Ipv4Prefix>,
|
||||
excluded: List<Ipv4Prefix>,
|
||||
): List<Ipv4Prefix> {
|
||||
var remaining = source
|
||||
excluded.forEach { blocked ->
|
||||
remaining = remaining.flatMap { allowed -> subtractIpv4Prefix(allowed, blocked) }
|
||||
}
|
||||
return collapseIpv4Prefixes(remaining)
|
||||
}
|
||||
|
||||
private fun subtractIpv4Prefix(allowed: Ipv4Prefix, blocked: Ipv4Prefix): List<Ipv4Prefix> {
|
||||
if (!allowed.contains(blocked) && !blocked.contains(allowed)) return listOf(allowed)
|
||||
if (blocked.contains(allowed)) return emptyList()
|
||||
if (allowed.length == IPV4_BITS) return emptyList()
|
||||
|
||||
val childLength = allowed.length + 1
|
||||
val childBit = 1L shl (IPV4_BITS - childLength)
|
||||
val first = Ipv4Prefix(allowed.network, childLength)
|
||||
val second = Ipv4Prefix(allowed.network or childBit, childLength)
|
||||
return if (first.contains(blocked)) {
|
||||
subtractIpv4Prefix(first, blocked) + listOf(second)
|
||||
} else {
|
||||
listOf(first) + subtractIpv4Prefix(second, blocked)
|
||||
}
|
||||
}
|
||||
@@ -9,31 +9,60 @@ internal fun isAlwaysBypassedVpnPackage(packageName: String, ownPackageName: Str
|
||||
return packageName == ownPackageName || packageName in ALWAYS_BYPASSED_VPN_PACKAGES
|
||||
}
|
||||
|
||||
internal fun sanitizeVpnRoutingPackages(
|
||||
packageNames: Collection<String>,
|
||||
ownPackageName: String,
|
||||
): List<String> = packageNames
|
||||
.asSequence()
|
||||
.map(String::trim)
|
||||
.filter(String::isNotEmpty)
|
||||
.filterNot { isAlwaysBypassedVpnPackage(it, ownPackageName) }
|
||||
.distinct()
|
||||
.sorted()
|
||||
.toList()
|
||||
|
||||
internal data class VpnAppRouting(
|
||||
val included: Set<String> = emptySet(),
|
||||
val excluded: Set<String> = emptySet()
|
||||
val excluded: Set<String> = emptySet(),
|
||||
val blocksAllApps: Boolean = false,
|
||||
)
|
||||
|
||||
internal fun applyVpnAppRoutingToAllowedIps(
|
||||
routing: VpnAppRouting,
|
||||
allowedIps: List<String>,
|
||||
): List<String> = if (routing.blocksAllApps) emptyList() else allowedIps
|
||||
|
||||
internal fun resolveVpnAppRouting(
|
||||
isWhitelist: Boolean,
|
||||
selectedPackages: Set<String>,
|
||||
installedPackages: Set<String>,
|
||||
ownPackageName: String
|
||||
ownPackageName: String,
|
||||
addressWhitelistConfigured: Boolean = false,
|
||||
): VpnAppRouting {
|
||||
val alwaysBypassed = (ALWAYS_BYPASSED_VPN_PACKAGES + ownPackageName)
|
||||
.intersect(installedPackages)
|
||||
val selectedInstalled = selectedPackages
|
||||
.intersect(installedPackages)
|
||||
.minus(alwaysBypassed)
|
||||
val hasConfiguredSelectablePackages = selectedPackages.any {
|
||||
!isAlwaysBypassedVpnPackage(it, ownPackageName)
|
||||
}
|
||||
|
||||
if (!isWhitelist) {
|
||||
return VpnAppRouting(excluded = alwaysBypassed + selectedInstalled)
|
||||
}
|
||||
|
||||
// Пустой allowed-list в Android означает «ограничение не задано», то есть весь трафик.
|
||||
// Поэтому для пустого БС явно исключаем все установленные пакеты.
|
||||
// Если БС адресов заполнен, а приложений нет, адресные правила применяются ко всем
|
||||
// приложениям, кроме обязательных исключений. Если обе категории пусты, не разрешаем
|
||||
// Android трактовать пустой список приложений как «все приложения». В закрытом
|
||||
// состоянии не перечисляем установленные пакеты: список устареет после установки
|
||||
// нового приложения. Вместо этого вызывающий код оставляет peer без маршрутов.
|
||||
return if (selectedInstalled.isEmpty()) {
|
||||
VpnAppRouting(excluded = installedPackages)
|
||||
if (addressWhitelistConfigured && !hasConfiguredSelectablePackages) {
|
||||
VpnAppRouting(excluded = alwaysBypassed)
|
||||
} else {
|
||||
VpnAppRouting(blocksAllApps = true)
|
||||
}
|
||||
} else {
|
||||
VpnAppRouting(included = selectedInstalled)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
internal const val VPN_DNS_PROFILE_ID = "profile"
|
||||
internal const val VPN_DNS_CUSTOM_ID = "custom"
|
||||
internal const val MAX_CUSTOM_VPN_DNS_SERVERS = 2
|
||||
|
||||
internal enum class VpnDnsCategory {
|
||||
STANDARD,
|
||||
SMART,
|
||||
}
|
||||
|
||||
internal data class VpnDnsPreset(
|
||||
val id: String,
|
||||
val title: String,
|
||||
val servers: List<String>,
|
||||
val category: VpnDnsCategory,
|
||||
val description: String,
|
||||
)
|
||||
|
||||
internal val vpnDnsPresets = listOf(
|
||||
VpnDnsPreset(
|
||||
id = "cloudflare",
|
||||
title = "Cloudflare",
|
||||
servers = listOf("1.1.1.1", "1.0.0.1"),
|
||||
category = VpnDnsCategory.STANDARD,
|
||||
description = "Обычный DNS без фильтрации содержимого.",
|
||||
),
|
||||
VpnDnsPreset(
|
||||
id = "google",
|
||||
title = "Google DNS",
|
||||
servers = listOf("8.8.8.8", "8.8.4.4"),
|
||||
category = VpnDnsCategory.STANDARD,
|
||||
description = "Обычный публичный DNS без фильтрации содержимого.",
|
||||
),
|
||||
VpnDnsPreset(
|
||||
id = "quad9",
|
||||
title = "Quad9",
|
||||
servers = listOf("9.9.9.9", "149.112.112.112"),
|
||||
category = VpnDnsCategory.STANDARD,
|
||||
description = "Блокирует известные вредоносные домены.",
|
||||
),
|
||||
VpnDnsPreset(
|
||||
id = "adguard",
|
||||
title = "AdGuard DNS",
|
||||
servers = listOf("94.140.14.14", "94.140.15.15"),
|
||||
category = VpnDnsCategory.STANDARD,
|
||||
description = "Блокирует рекламу, трекеры и фишинговые домены.",
|
||||
),
|
||||
VpnDnsPreset(
|
||||
id = "xbox",
|
||||
title = "Xbox DNS",
|
||||
servers = listOf("111.88.96.50", "111.88.96.51"),
|
||||
category = VpnDnsCategory.SMART,
|
||||
description = "Сторонний Smart DNS для отдельных сервисов и игр.",
|
||||
),
|
||||
VpnDnsPreset(
|
||||
id = "comss",
|
||||
title = "Comss.one DNS",
|
||||
servers = listOf("83.220.169.155", "212.109.195.93"),
|
||||
category = VpnDnsCategory.SMART,
|
||||
description = "Сторонний Smart DNS для ИИ-сервисов с фильтрацией.",
|
||||
),
|
||||
)
|
||||
|
||||
internal data class VpnDnsSettingsSnapshot(
|
||||
val profileIndex: Int,
|
||||
val selectionId: String = VPN_DNS_PROFILE_ID,
|
||||
val customServers: List<String> = emptyList(),
|
||||
) {
|
||||
val preset: VpnDnsPreset?
|
||||
get() = vpnDnsPresets.firstOrNull { it.id == selectionId }
|
||||
|
||||
val isSmartDns: Boolean
|
||||
get() = preset?.category == VpnDnsCategory.SMART
|
||||
|
||||
val title: String
|
||||
get() = when (selectionId) {
|
||||
VPN_DNS_PROFILE_ID -> "Как в профиле"
|
||||
VPN_DNS_CUSTOM_ID -> "Свой DNS"
|
||||
else -> preset?.title ?: "Как в профиле"
|
||||
}
|
||||
|
||||
val configuredServers: List<String>
|
||||
get() = when (selectionId) {
|
||||
VPN_DNS_PROFILE_ID -> emptyList()
|
||||
VPN_DNS_CUSTOM_ID -> customServers
|
||||
else -> preset?.servers.orEmpty()
|
||||
}
|
||||
}
|
||||
|
||||
internal data class EffectiveVpnDns(
|
||||
val servers: List<String>,
|
||||
val selectionId: String,
|
||||
val title: String,
|
||||
val isSmartDns: Boolean,
|
||||
val fellBackToProfile: Boolean = false,
|
||||
)
|
||||
|
||||
internal fun vpnDnsAppliedLogMessage(
|
||||
profileName: String,
|
||||
effectiveDns: EffectiveVpnDns,
|
||||
): String = buildString {
|
||||
append('«')
|
||||
append(profileName.ifBlank { "Профиль" })
|
||||
append("»: ")
|
||||
val modeTitle = if (effectiveDns.selectionId == VPN_DNS_PROFILE_ID) {
|
||||
"DNS из WireGuard-профиля"
|
||||
} else {
|
||||
effectiveDns.title
|
||||
}
|
||||
append(modeTitle)
|
||||
if (effectiveDns.servers.isEmpty()) {
|
||||
append(" не задан; Android использует DNS основной сети.")
|
||||
} else {
|
||||
append(" используется внутри VPN: ")
|
||||
append(effectiveDns.servers.joinToString(", "))
|
||||
append('.')
|
||||
}
|
||||
if (effectiveDns.isSmartDns) {
|
||||
append(" Это сторонний Smart DNS: часть сервисов может идти через его шлюзы.")
|
||||
}
|
||||
if (effectiveDns.fellBackToProfile) {
|
||||
append(" Свой DNS был некорректен, поэтому безопасно включён DNS из WireGuard-профиля.")
|
||||
}
|
||||
}
|
||||
|
||||
internal fun normalizeVpnDnsSelectionId(value: String?): String {
|
||||
val normalized = value?.trim()?.lowercase().orEmpty()
|
||||
return when {
|
||||
normalized == VPN_DNS_PROFILE_ID -> VPN_DNS_PROFILE_ID
|
||||
normalized == VPN_DNS_CUSTOM_ID -> VPN_DNS_CUSTOM_ID
|
||||
vpnDnsPresets.any { it.id == normalized } -> normalized
|
||||
else -> VPN_DNS_PROFILE_ID
|
||||
}
|
||||
}
|
||||
|
||||
internal fun normalizeCustomVpnDnsServers(raw: String): List<String> {
|
||||
val values = raw
|
||||
.split(Regex("[,;\\s]+"))
|
||||
.map(String::trim)
|
||||
.filter(String::isNotEmpty)
|
||||
require(values.isNotEmpty()) { "Укажите хотя бы один IPv4-адрес DNS." }
|
||||
require(values.size <= MAX_CUSTOM_VPN_DNS_SERVERS) {
|
||||
"Можно указать не больше двух DNS-серверов."
|
||||
}
|
||||
return values.map(::normalizeVpnDnsIpv4).distinct().also { normalized ->
|
||||
require(normalized.isNotEmpty()) { "Укажите хотя бы один IPv4-адрес DNS." }
|
||||
}
|
||||
}
|
||||
|
||||
internal fun decodeStoredCustomVpnDnsServers(raw: String): List<String> =
|
||||
runCatching { normalizeCustomVpnDnsServers(raw) }.getOrDefault(emptyList())
|
||||
|
||||
internal fun isIpv4Literal(value: String): Boolean {
|
||||
val parts = value.split('.')
|
||||
return parts.size == 4 && parts.all { part ->
|
||||
part.isNotEmpty() &&
|
||||
part.length <= 3 &&
|
||||
part.all(Char::isDigit) &&
|
||||
(part.length == 1 || part.first() != '0') &&
|
||||
(part.toIntOrNull()?.let { it in 0..255 } == true)
|
||||
}
|
||||
}
|
||||
|
||||
internal fun resolveEffectiveVpnDns(
|
||||
settings: VpnDnsSettingsSnapshot,
|
||||
profileServers: List<String>,
|
||||
): EffectiveVpnDns {
|
||||
val normalizedSelection = normalizeVpnDnsSelectionId(settings.selectionId)
|
||||
val preset = vpnDnsPresets.firstOrNull { it.id == normalizedSelection }
|
||||
val selectedServers = when (normalizedSelection) {
|
||||
VPN_DNS_PROFILE_ID -> profileServers
|
||||
VPN_DNS_CUSTOM_ID -> settings.customServers
|
||||
else -> preset?.servers.orEmpty()
|
||||
}
|
||||
val customInvalid = normalizedSelection == VPN_DNS_CUSTOM_ID && selectedServers.isEmpty()
|
||||
return if (customInvalid) {
|
||||
EffectiveVpnDns(
|
||||
servers = profileServers,
|
||||
selectionId = VPN_DNS_PROFILE_ID,
|
||||
title = "Как в профиле",
|
||||
isSmartDns = false,
|
||||
fellBackToProfile = true,
|
||||
)
|
||||
} else {
|
||||
EffectiveVpnDns(
|
||||
servers = selectedServers.distinct(),
|
||||
selectionId = normalizedSelection,
|
||||
title = when (normalizedSelection) {
|
||||
VPN_DNS_PROFILE_ID -> "Как в профиле"
|
||||
VPN_DNS_CUSTOM_ID -> "Свой DNS"
|
||||
else -> preset?.title ?: "Как в профиле"
|
||||
},
|
||||
isSmartDns = preset?.category == VpnDnsCategory.SMART,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun normalizeVpnDnsIpv4(value: String): String {
|
||||
val parts = value.split('.')
|
||||
require(parts.size == 4) { "Некорректный IPv4-адрес DNS: $value" }
|
||||
val octets = parts.map { part ->
|
||||
require(part.isNotEmpty() && part.length <= 3 && part.all(Char::isDigit)) {
|
||||
"Некорректный IPv4-адрес DNS: $value"
|
||||
}
|
||||
require(part.length == 1 || part.first() != '0') {
|
||||
"Некорректный IPv4-адрес DNS: $value"
|
||||
}
|
||||
part.toInt().also { octet ->
|
||||
require(octet in 0..255) { "Некорректный IPv4-адрес DNS: $value" }
|
||||
}
|
||||
}
|
||||
require(octets != listOf(0, 0, 0, 0)) { "Адрес 0.0.0.0 нельзя использовать как DNS." }
|
||||
require(octets.first() != 127) { "Локальный адрес 127.0.0.0/8 нельзя использовать как DNS VPN." }
|
||||
require(octets.first() !in 224..239) { "Multicast-адрес нельзя использовать как DNS." }
|
||||
require(octets != listOf(255, 255, 255, 255)) { "Широковещательный адрес нельзя использовать как DNS." }
|
||||
return octets.joinToString(".")
|
||||
}
|
||||
@@ -10,13 +10,22 @@ import com.wireguard.config.Config
|
||||
import com.wireguard.config.Interface
|
||||
import com.wireguard.config.Peer
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.runInterruptible
|
||||
import kotlinx.coroutines.sync.Semaphore
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withPermit
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.ByteArrayInputStream
|
||||
import java.net.InetAddress
|
||||
import java.security.MessageDigest
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
class WireGuardHelper(context: Context) {
|
||||
private val appContext = context.applicationContext
|
||||
@@ -62,10 +71,6 @@ class WireGuardHelper(context: Context) {
|
||||
|
||||
val builder = Interface.Builder()
|
||||
.parseAddresses(parsedConfig.`interface`.addresses.joinToString(", ") { it.toString() })
|
||||
|
||||
if (parsedConfig.`interface`.dnsServers.isNotEmpty()) {
|
||||
builder.parseDnsServers(parsedConfig.`interface`.dnsServers.joinToString(", ") { it.hostAddress ?: "" })
|
||||
}
|
||||
if (parsedConfig.`interface`.listenPort.isPresent) {
|
||||
builder.parseListenPort(parsedConfig.`interface`.listenPort.get().toString())
|
||||
}
|
||||
@@ -81,12 +86,71 @@ class WireGuardHelper(context: Context) {
|
||||
// 1. Пакеты, которые всегда исключаются (наше приложение, ВК)
|
||||
// 2. Получаю настройки пользователя
|
||||
val settingsStore = SettingsStore(appContext)
|
||||
val selectedPackages = settingsStore.vpnAppPackages.first()
|
||||
val runningProfile = TunnelManager.activeTunnelProfile.value
|
||||
val routingSettings = if (runningProfile != null) {
|
||||
settingsStore.vpnRoutingSettingsForProfile(runningProfile)
|
||||
} else {
|
||||
settingsStore.vpnRoutingSettings.first()
|
||||
}
|
||||
val dnsSettings = if (runningProfile != null) {
|
||||
settingsStore.vpnDnsSettingsForProfile(runningProfile)
|
||||
} else {
|
||||
settingsStore.vpnDnsSettings.first()
|
||||
}
|
||||
val profileLabel = vpnProfileDisplayName(
|
||||
dnsSettings.profileIndex,
|
||||
settingsStore.profileNames.first(),
|
||||
)
|
||||
val profileDnsServers = parsedConfig.`interface`.dnsServers
|
||||
.mapNotNull { it.hostAddress }
|
||||
val effectiveDns = resolveEffectiveVpnDns(
|
||||
settings = dnsSettings,
|
||||
profileServers = profileDnsServers,
|
||||
)
|
||||
if (effectiveDns.servers.isNotEmpty()) {
|
||||
builder.parseDnsServers(effectiveDns.servers.joinToString(", "))
|
||||
}
|
||||
TunnelManager.noteVpnDnsEvent(
|
||||
key = "applied_${dnsSettings.profileIndex}_${effectiveDns.selectionId}",
|
||||
message = vpnDnsAppliedLogMessage(profileLabel, effectiveDns),
|
||||
warning = effectiveDns.fellBackToProfile,
|
||||
)
|
||||
val selectedPackages = routingSettings.appPackages
|
||||
.split(",")
|
||||
.map { it.trim() }
|
||||
.filter { it.isNotEmpty() }
|
||||
.toSet()
|
||||
val isWhitelist = settingsStore.isWhitelist.first()
|
||||
val isWhitelist = routingSettings.isWhitelist
|
||||
val addressRules = routingSettings.addressRules
|
||||
val resolvedDomains = resolveAddressRuleDomains(addressRules)
|
||||
val addressRouting = runCatching {
|
||||
resolveVpnAddressRouting(
|
||||
isWhitelist = isWhitelist,
|
||||
rules = addressRules,
|
||||
domainResolver = { domain -> resolvedDomains[domain].orEmpty() },
|
||||
)
|
||||
}.getOrElse { error ->
|
||||
Log.e("WG", "Address routing fallback: ${error.readableMessage()}")
|
||||
TunnelManager.noteAddressRoutingWarning(
|
||||
key = "fallback",
|
||||
message = if (isWhitelist) {
|
||||
"Правила адресов не применены: ${error.message ?: "ошибка списка"}. " +
|
||||
"БС адресов временно закрыт до исправления списка."
|
||||
} else {
|
||||
"Правила адресов не применены: ${error.message ?: "ошибка списка"}. " +
|
||||
"VPN продолжает работать без адресных исключений."
|
||||
},
|
||||
)
|
||||
VpnAddressRoutingResult(
|
||||
allowedIps = if (isWhitelist) emptyList() else listOf("0.0.0.0/0"),
|
||||
)
|
||||
}
|
||||
val effectiveAllowedIps = effectiveWireGuardAllowedIps(
|
||||
isWhitelist = isWhitelist,
|
||||
addressRulesConfigured = addressRules.isNotEmpty(),
|
||||
addressRouting = addressRouting,
|
||||
vpnDnsIpv4 = effectiveDns.servers.filter(::isIpv4Literal),
|
||||
)
|
||||
val installedPackages = appContext.packageManager
|
||||
.getInstalledApplications(0)
|
||||
.map { it.packageName }
|
||||
@@ -95,13 +159,18 @@ class WireGuardHelper(context: Context) {
|
||||
isWhitelist = isWhitelist,
|
||||
selectedPackages = selectedPackages,
|
||||
installedPackages = installedPackages,
|
||||
ownPackageName = appContext.packageName
|
||||
ownPackageName = appContext.packageName,
|
||||
addressWhitelistConfigured = isWhitelist && addressRules.isNotEmpty(),
|
||||
)
|
||||
if (routing.included.isNotEmpty()) {
|
||||
builder.includeApplications(routing.included)
|
||||
} else if (routing.excluded.isNotEmpty()) {
|
||||
builder.excludeApplications(routing.excluded)
|
||||
}
|
||||
val routedAllowedIps = applyVpnAppRoutingToAllowedIps(
|
||||
routing = routing,
|
||||
allowedIps = effectiveAllowedIps,
|
||||
)
|
||||
|
||||
val newInterface = builder.build()
|
||||
|
||||
@@ -114,8 +183,31 @@ class WireGuardHelper(context: Context) {
|
||||
if (peer.endpoint.isPresent) peerBuilder.parseEndpoint(peer.endpoint.get().toString())
|
||||
if (peer.persistentKeepalive.isPresent) peerBuilder.parsePersistentKeepalive(peer.persistentKeepalive.get().toString())
|
||||
}
|
||||
// Override AllowedIPs
|
||||
peerBuilder.parseAllowedIPs("0.0.0.0/0")
|
||||
// Android строит маршруты назначения из AllowedIPs. Пустой БС адресов
|
||||
// оставляет peer без маршрутов: VPN поднят, но пользовательский трафик в него
|
||||
// не попадёт. Для ЧС здесь уже рассчитано дополнение выбранных IPv4/CIDR.
|
||||
if (routedAllowedIps.isNotEmpty()) {
|
||||
peerBuilder.parseAllowedIPs(routedAllowedIps.joinToString(", "))
|
||||
}
|
||||
if (addressRouting.unresolvedDomains.isNotEmpty()) {
|
||||
val previewDomains = addressRouting.unresolvedDomains.take(3)
|
||||
val preview = previewDomains.joinToString(", ")
|
||||
val remaining = addressRouting.unresolvedDomains.size - previewDomains.size
|
||||
Log.w(
|
||||
"WG",
|
||||
"Address routing: unresolved domains=" +
|
||||
addressRouting.unresolvedDomains.joinToString(", "),
|
||||
)
|
||||
TunnelManager.noteAddressRoutingWarning(
|
||||
key = "unresolved_domains",
|
||||
message = buildString {
|
||||
append("Не удалось определить IPv4: ")
|
||||
append(preview)
|
||||
if (remaining > 0) append(" и ещё $remaining")
|
||||
append(". Эти домены не применены; переподключите VPN после восстановления DNS.")
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
val finalConfig = Config.Builder()
|
||||
.setInterface(newInterface)
|
||||
@@ -140,22 +232,27 @@ class WireGuardHelper(context: Context) {
|
||||
|
||||
ensureGoBackendServiceStarted()
|
||||
|
||||
sharedTunnel?.let { existingTunnel ->
|
||||
try {
|
||||
existingTunnel.suppressDownCallback = true
|
||||
backend.setState(existingTunnel, Tunnel.State.DOWN, null)
|
||||
} catch (e: Exception) {
|
||||
Log.w("WG", "Failed to stop previous tunnel before restart: ${e.readableMessage()}")
|
||||
}
|
||||
sharedTunnel = null
|
||||
sharedConfigFingerprint = null
|
||||
delay(150)
|
||||
}
|
||||
|
||||
// GoBackend умеет сам восстановить предыдущую конфигурацию, если новая не
|
||||
// поднимется. Не выключаем рабочий tunnel заранее, иначе этот rollback теряется.
|
||||
val previousTunnel = sharedTunnel
|
||||
val previousFingerprint = sharedConfigFingerprint
|
||||
previousTunnel?.suppressDownCallback = true
|
||||
val nextTunnel = WgTunnel {
|
||||
TunnelManager.onWireGuardInterfaceDropped()
|
||||
notifyWireGuardInterfaceDropped()
|
||||
}
|
||||
try {
|
||||
setTunnelUpWithRetry(nextTunnel, finalConfig)
|
||||
} catch (error: Exception) {
|
||||
previousTunnel?.suppressDownCallback = false
|
||||
val previousRestored = previousTunnel != null && runCatching {
|
||||
backend.getState(previousTunnel) == Tunnel.State.UP
|
||||
}.getOrDefault(false)
|
||||
if (previousRestored) {
|
||||
sharedTunnel = previousTunnel
|
||||
sharedConfigFingerprint = previousFingerprint
|
||||
}
|
||||
throw error
|
||||
}
|
||||
setTunnelUpWithRetry(nextTunnel, finalConfig)
|
||||
sharedTunnel = nextTunnel
|
||||
sharedConfigFingerprint = wireGuardConfigFingerprint(finalConfig)
|
||||
Log.d("WG", "WireGuard tunnel started successfully")
|
||||
@@ -169,22 +266,53 @@ class WireGuardHelper(context: Context) {
|
||||
|
||||
suspend fun reloadTunnel() = wgMutex.withLock {
|
||||
withContext(Dispatchers.IO) {
|
||||
val currentTunnel = sharedTunnel ?: return@withContext
|
||||
if (sharedTunnel == null) return@withContext
|
||||
try {
|
||||
val configFlow = TunnelManager.config.first() ?: return@withContext
|
||||
currentTunnel.suppressDownCallback = true
|
||||
backend.setState(currentTunnel, Tunnel.State.DOWN, null)
|
||||
sharedTunnel = null
|
||||
sharedConfigFingerprint = null
|
||||
delay(150)
|
||||
startTunnelLocked(configFlow)
|
||||
Log.d("WG", "WireGuard tunnel reloaded for new exceptions")
|
||||
Log.d("WG", "WireGuard tunnel reloaded for updated profile settings")
|
||||
} catch (e: Exception) {
|
||||
Log.e("WG", "Failed to reload WireGuard: ${e.readableMessage()}")
|
||||
TunnelManager.noteVpnInterfaceReloadWarning(
|
||||
message = "Новые настройки маршрутизации или DNS не применились: ${e.readableMessage()}. " +
|
||||
"Рабочая конфигурация сохранена, если Android смог её восстановить.",
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun resolveAddressRuleDomains(
|
||||
rules: List<VpnAddressRule>,
|
||||
): Map<String, List<String>> {
|
||||
val domains = rules.asSequence()
|
||||
.filter { it.type == VpnAddressType.DOMAIN }
|
||||
.map(VpnAddressRule::value)
|
||||
.distinct()
|
||||
.toList()
|
||||
if (domains.isEmpty()) return emptyMap()
|
||||
|
||||
val resolved = ConcurrentHashMap<String, List<String>>()
|
||||
val concurrency = Semaphore(16)
|
||||
withTimeoutOrNull(5_000L) {
|
||||
coroutineScope {
|
||||
domains.map { domain ->
|
||||
async(Dispatchers.IO) {
|
||||
concurrency.withPermit {
|
||||
val addresses = runCatching {
|
||||
runInterruptible {
|
||||
InetAddress.getAllByName(domain)
|
||||
.mapNotNull(InetAddress::getHostAddress)
|
||||
}
|
||||
}.getOrDefault(emptyList())
|
||||
resolved[domain] = addresses
|
||||
}
|
||||
}
|
||||
}.forEach { it.await() }
|
||||
}
|
||||
}
|
||||
return resolved
|
||||
}
|
||||
|
||||
suspend fun isTunnelUp(): Boolean = wgMutex.withLock {
|
||||
val current = sharedTunnel ?: return false
|
||||
return try {
|
||||
@@ -210,6 +338,51 @@ class WireGuardHelper(context: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
private fun notifyWireGuardInterfaceDropped() {
|
||||
val slotTransferred = isVpnSlotTransferred()
|
||||
TunnelManager.onWireGuardInterfaceDropped(slotTransferred)
|
||||
if (slotTransferred) {
|
||||
requestVpnSlotHandoverStop()
|
||||
return
|
||||
}
|
||||
|
||||
// При смене VPN Android может уничтожить старый VpnService чуть раньше,
|
||||
// чем обновит владельца разрешения. Несколько коротких проверок закрывают
|
||||
// эту гонку, не добавляя постоянного polling: ветка выполняется только
|
||||
// после внешнего DOWN-сигнала от WireGuard.
|
||||
TunnelManager.scope.launch {
|
||||
repeat(20) {
|
||||
delay(250L)
|
||||
if (isVpnSlotTransferred()) {
|
||||
TunnelManager.onWireGuardInterfaceDropped(vpnSlotTransferred = true)
|
||||
requestVpnSlotHandoverStop()
|
||||
return@launch
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Не полагаемся только на StateFlow: callback WireGuard приходит в момент,
|
||||
* когда Android уже передаёт единственный VPN-слот. Доставляем сигнал в
|
||||
* работающую foreground-службу сразу, чтобы она закрыла нативный клиент и
|
||||
* не смогла запустить WireGuard повторно в этой сессии.
|
||||
*/
|
||||
private fun requestVpnSlotHandoverStop() {
|
||||
runCatching {
|
||||
appContext.startService(
|
||||
Intent(appContext, TunnelService::class.java).apply {
|
||||
action = ACTION_VPN_SLOT_REVOKED
|
||||
}
|
||||
)
|
||||
}.onFailure {
|
||||
Log.w("WG", "Не удалось немедленно передать остановку VPN-службе: ${it.readableMessage()}")
|
||||
}
|
||||
}
|
||||
|
||||
private fun isVpnSlotTransferred(): Boolean =
|
||||
runCatching { VpnService.prepare(appContext) != null }.getOrDefault(false)
|
||||
|
||||
private suspend fun ensureGoBackendServiceStarted() {
|
||||
withContext(Dispatchers.Main) {
|
||||
runCatching {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,5 +1,6 @@
|
||||
package com.wdtt.plus.ui
|
||||
|
||||
import android.content.Intent
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.animateContentSize
|
||||
import androidx.compose.animation.core.Spring
|
||||
@@ -37,7 +38,9 @@ import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.wdtt.plus.SettingsStore
|
||||
import com.wdtt.plus.SleepBatteryMode
|
||||
import com.wdtt.plus.TunnelManager
|
||||
import com.wdtt.plus.TunnelService
|
||||
import com.wdtt.plus.TunnelStopCoordinator
|
||||
import com.wdtt.plus.TunnelStopResult
|
||||
import com.wdtt.plus.sanitizeVpnProfileNameInput
|
||||
@@ -97,6 +100,14 @@ fun FloatingToolbar(
|
||||
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 pauseVpnDuringSleepDelayMinutes by
|
||||
settingsStore.pauseVpnDuringSleepDelayMinutes.collectAsStateWithLifecycle(initialValue = 5)
|
||||
val sleepBatteryMode by
|
||||
settingsStore.sleepBatteryMode.collectAsStateWithLifecycle(initialValue = SleepBatteryMode.DELAYED_PAUSE)
|
||||
val resumeVpnDuringSleepDelayMinutes by
|
||||
settingsStore.resumeVpnDuringSleepDelayMinutes.collectAsStateWithLifecycle(initialValue = 5)
|
||||
val sleepBatterySettingsConfigured by
|
||||
settingsStore.sleepBatterySettingsConfigured.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(
|
||||
@@ -129,7 +140,9 @@ fun FloatingToolbar(
|
||||
var resetInProgress by remember { mutableStateOf(false) }
|
||||
var profileNameInput by rememberSaveable { mutableStateOf("") }
|
||||
var showTrustedWifiSettings by rememberSaveable { mutableStateOf(false) }
|
||||
var enableTrustedWifiAfterSetup by rememberSaveable { mutableStateOf(false) }
|
||||
var showVkClientSettings by rememberSaveable { mutableStateOf(false) }
|
||||
var showSleepTimerSettings by rememberSaveable { mutableStateOf(false) }
|
||||
|
||||
val tabWidthDp = 42.dp
|
||||
val tabHeightDp = 52.dp
|
||||
@@ -358,12 +371,19 @@ fun FloatingToolbar(
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable { showTrustedWifiSettings = true }
|
||||
.padding(horizontal = 4.dp, vertical = 4.dp),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f).padding(end = 10.dp)) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.weight(1f)
|
||||
.clickable {
|
||||
enableTrustedWifiAfterSetup = false
|
||||
showTrustedWifiSettings = true
|
||||
}
|
||||
.padding(end = 10.dp)
|
||||
) {
|
||||
Text(
|
||||
"Доверенные сети Wi‑Fi",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
@@ -373,9 +393,12 @@ fun FloatingToolbar(
|
||||
Text(
|
||||
when {
|
||||
trustedWifiRuntime.waiting -> "VPN ожидает выхода из сети"
|
||||
!trustedWifiEnabled -> "Выключено"
|
||||
trustedWifiSsids.isEmpty() -> "Сети не добавлены"
|
||||
else -> "Добавлено: ${trustedWifiSsids.size}"
|
||||
trustedWifiSsids.isEmpty() ->
|
||||
"Сети не настроены · нажмите для настройки"
|
||||
trustedWifiEnabled ->
|
||||
"Включено · сетей: ${trustedWifiSsids.size}"
|
||||
else ->
|
||||
"Выключено · сохранено сетей: ${trustedWifiSsids.size}"
|
||||
},
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
@@ -384,13 +407,34 @@ fun FloatingToolbar(
|
||||
}
|
||||
Switch(
|
||||
checked = trustedWifiEnabled,
|
||||
onCheckedChange = null,
|
||||
onCheckedChange = { enabled ->
|
||||
if (enabled && trustedWifiSsids.isEmpty()) {
|
||||
enableTrustedWifiAfterSetup = true
|
||||
showTrustedWifiSettings = true
|
||||
} else {
|
||||
scope.launch {
|
||||
settingsStore.saveTrustedWifiEnabled(enabled)
|
||||
if (TunnelManager.running.value || trustedWifiRuntime.waiting) {
|
||||
runCatching {
|
||||
context.startService(
|
||||
Intent(context, TunnelService::class.java).apply {
|
||||
action = "TRUSTED_WIFI_RECHECK"
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
modifier = Modifier.scale(0.85f)
|
||||
)
|
||||
}
|
||||
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 4.dp, vertical = 4.dp),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable { showSleepTimerSettings = true }
|
||||
.padding(horizontal = 4.dp, vertical = 4.dp),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
@@ -403,9 +447,39 @@ fun FloatingToolbar(
|
||||
)
|
||||
Text(
|
||||
if (pauseVpnDuringSleep) {
|
||||
"VPN выключается · интернет напрямую"
|
||||
when (sleepBatteryMode) {
|
||||
SleepBatteryMode.DELAYED_PAUSE ->
|
||||
if (pauseVpnDuringSleepDelayMinutes == 0) {
|
||||
"Отключение сразу после выключения экрана"
|
||||
} else {
|
||||
"Отключение через ${formatSleepTimerDuration(pauseVpnDuringSleepDelayMinutes)}"
|
||||
}
|
||||
SleepBatteryMode.TIMED_PAUSE ->
|
||||
if (resumeVpnDuringSleepDelayMinutes == 0) {
|
||||
"Таймер 0 мин · VPN останется активным"
|
||||
} else {
|
||||
"Сразу выключится · включение через ${formatSleepTimerDuration(resumeVpnDuringSleepDelayMinutes)}"
|
||||
}
|
||||
}
|
||||
} else {
|
||||
"VPN остаётся активным"
|
||||
if (sleepBatterySettingsConfigured) {
|
||||
when (sleepBatteryMode) {
|
||||
SleepBatteryMode.DELAYED_PAUSE ->
|
||||
if (pauseVpnDuringSleepDelayMinutes == 0) {
|
||||
"Выключено · сохранено немедленное отключение"
|
||||
} else {
|
||||
"Выключено · сохранено отключение через ${formatSleepTimerDuration(pauseVpnDuringSleepDelayMinutes)}"
|
||||
}
|
||||
SleepBatteryMode.TIMED_PAUSE ->
|
||||
if (resumeVpnDuringSleepDelayMinutes == 0) {
|
||||
"Выключено · сохранён таймер 0 мин"
|
||||
} else {
|
||||
"Выключено · сохранено включение через ${formatSleepTimerDuration(resumeVpnDuringSleepDelayMinutes)}"
|
||||
}
|
||||
}
|
||||
} else {
|
||||
"VPN остаётся активным · нажмите для настройки"
|
||||
}
|
||||
},
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
@@ -415,7 +489,27 @@ fun FloatingToolbar(
|
||||
Switch(
|
||||
checked = pauseVpnDuringSleep,
|
||||
onCheckedChange = { enabled ->
|
||||
scope.launch { settingsStore.savePauseVpnDuringSleep(enabled) }
|
||||
if (enabled) {
|
||||
if (sleepBatterySettingsConfigured) {
|
||||
scope.launch {
|
||||
settingsStore.savePauseVpnDuringSleep(true)
|
||||
TunnelManager.noteSleepBatteryEvent(
|
||||
"settings_enabled",
|
||||
"Экономия батареи во сне включена; сохранённый сценарий применится при следующем выключении экрана.",
|
||||
)
|
||||
}
|
||||
} else {
|
||||
showSleepTimerSettings = true
|
||||
}
|
||||
} else {
|
||||
scope.launch {
|
||||
settingsStore.savePauseVpnDuringSleep(false)
|
||||
TunnelManager.noteSleepBatteryEvent(
|
||||
"settings_disabled",
|
||||
"Экономия батареи во сне выключена.",
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
modifier = Modifier.scale(0.85f)
|
||||
)
|
||||
@@ -729,7 +823,11 @@ fun FloatingToolbar(
|
||||
if (showTrustedWifiSettings) {
|
||||
TrustedWifiSettingsDialog(
|
||||
settingsStore = settingsStore,
|
||||
onDismiss = { showTrustedWifiSettings = false }
|
||||
enableAfterFirstNetworkAdded = enableTrustedWifiAfterSetup,
|
||||
onDismiss = {
|
||||
enableTrustedWifiAfterSetup = false
|
||||
showTrustedWifiSettings = false
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
@@ -741,6 +839,39 @@ fun FloatingToolbar(
|
||||
onDismiss = { showVkClientSettings = false }
|
||||
)
|
||||
}
|
||||
|
||||
if (showSleepTimerSettings) {
|
||||
SleepTimerDialog(
|
||||
initialMode = sleepBatteryMode,
|
||||
initialPauseDelayMinutes = pauseVpnDuringSleepDelayMinutes,
|
||||
initialResumeDelayMinutes = resumeVpnDuringSleepDelayMinutes,
|
||||
onApply = { mode, pauseDelayMinutes, resumeDelayMinutes ->
|
||||
scope.launch {
|
||||
settingsStore.saveSleepBatteryMode(
|
||||
enabled = true,
|
||||
mode = mode,
|
||||
pauseDelayMinutes = pauseDelayMinutes,
|
||||
resumeDelayMinutes = resumeDelayMinutes,
|
||||
)
|
||||
val description = when (mode) {
|
||||
SleepBatteryMode.DELAYED_PAUSE ->
|
||||
"отключение VPN через ${formatSleepTimerDuration(pauseDelayMinutes)} после выключения экрана"
|
||||
SleepBatteryMode.TIMED_PAUSE -> if (resumeDelayMinutes == 0) {
|
||||
"VPN остаётся активным при таймере 0 мин"
|
||||
} else {
|
||||
"немедленное отключение VPN и включение примерно через ${formatSleepTimerDuration(resumeDelayMinutes)}"
|
||||
}
|
||||
}
|
||||
TunnelManager.noteSleepBatteryEvent(
|
||||
"settings_saved",
|
||||
"Настройки сохранены: $description.",
|
||||
)
|
||||
}
|
||||
showSleepTimerSettings = false
|
||||
},
|
||||
onDismiss = { showSleepTimerSettings = false },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -121,9 +121,17 @@ 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.SleepBatteryMode
|
||||
import com.wdtt.plus.SleepBatteryRuntimePhase
|
||||
import com.wdtt.plus.SleepBatteryRuntimeState
|
||||
import com.wdtt.plus.TunnelManager
|
||||
import com.wdtt.plus.TrustedWifiManager
|
||||
import com.wdtt.plus.decodeStoredVpnPackages
|
||||
import com.wdtt.plus.trustedWifiAccessProblem
|
||||
import com.wdtt.plus.sleepBatteryModeItem
|
||||
import com.wdtt.plus.trustedWifiModeItem
|
||||
import com.wdtt.plus.vpnRoutingModeItem
|
||||
import com.wdtt.plus.vpnProfileDisplayName
|
||||
import com.wdtt.plus.inspectRtMasqueEnrollment
|
||||
import com.wdtt.plus.UPDATE_DIALOG_ACTION_POSTPONED
|
||||
import com.wdtt.plus.UPDATE_DIALOG_ACTION_UPDATE
|
||||
@@ -359,8 +367,62 @@ fun InfoTab(
|
||||
releaseDate = releaseDate,
|
||||
latestRelease = latestRelease
|
||||
)
|
||||
val workers = runCatching { settingsStore.workersPerHash.first() }.getOrNull()
|
||||
val tunnelProfile = runCatching { settingsStore.tunnelProfileSnapshot() }.getOrNull()
|
||||
val selectedProfile = runCatching { settingsStore.activeProfile.first() }.getOrDefault(0)
|
||||
val savedTunnelProfile = runCatching { settingsStore.activeTunnelProfile.first() }.getOrNull()
|
||||
val diagnosticProfile = TunnelManager.activeTunnelProfile.value
|
||||
?: savedTunnelProfile
|
||||
?: selectedProfile
|
||||
val profileNames = runCatching { settingsStore.profileNames.first() }.getOrDefault(emptyList())
|
||||
val diagnosticProfileName = vpnProfileDisplayName(diagnosticProfile, profileNames)
|
||||
val tunnelProfile = runCatching {
|
||||
settingsStore.tunnelProfileSnapshot(diagnosticProfile)
|
||||
}.getOrNull()
|
||||
val workers = tunnelProfile?.workersPerHash
|
||||
?: runCatching { settingsStore.workersPerHash.first() }.getOrNull()
|
||||
val routingSnapshot = runCatching {
|
||||
settingsStore.vpnRoutingSettingsForProfile(diagnosticProfile)
|
||||
}.getOrNull()
|
||||
val vpnDnsSnapshot = runCatching {
|
||||
settingsStore.vpnDnsSettingsForProfile(diagnosticProfile)
|
||||
}.getOrNull()
|
||||
val installedPackages = withContext(Dispatchers.Default) {
|
||||
runCatching {
|
||||
@Suppress("DEPRECATION")
|
||||
context.packageManager.getInstalledApplications(0)
|
||||
.mapTo(linkedSetOf()) { it.packageName }
|
||||
}.getOrDefault(emptySet())
|
||||
}
|
||||
val trustedWifiEnabled = runCatching { settingsStore.trustedWifiEnabled.first() }.getOrDefault(false)
|
||||
val trustedWifiSsids = runCatching { settingsStore.trustedWifiSsids.first() }.getOrDefault(emptyList())
|
||||
val trustedWifiRuntime = TrustedWifiManager.state.value
|
||||
val trustedWifiWaiting = trustedWifiRuntime.waiting ||
|
||||
runCatching { settingsStore.trustedWifiWaiting.first() }.getOrDefault(false)
|
||||
val trustedWifiWaitingSsid = trustedWifiRuntime.ssid.ifBlank {
|
||||
runCatching { settingsStore.trustedWifiWaitingSsid.first() }.getOrDefault("")
|
||||
}
|
||||
val trustedWifiProblem = if (trustedWifiEnabled) {
|
||||
trustedWifiAccessProblem(context.applicationContext)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val sleepEnabled = runCatching { settingsStore.pauseVpnDuringSleep.first() }.getOrDefault(false)
|
||||
val sleepMode = runCatching { settingsStore.sleepBatteryMode.first() }
|
||||
.getOrDefault(SleepBatteryMode.DELAYED_PAUSE)
|
||||
val sleepPauseDelay = runCatching {
|
||||
settingsStore.pauseVpnDuringSleepDelayMinutes.first()
|
||||
}.getOrDefault(0)
|
||||
val sleepResumeDelay = runCatching {
|
||||
settingsStore.resumeVpnDuringSleepDelayMinutes.first()
|
||||
}.getOrDefault(0)
|
||||
val sleepRuntime = runCatching { settingsStore.sleepBatteryRuntimeState.first() }
|
||||
.getOrDefault(SleepBatteryRuntimeState())
|
||||
val notificationsGranted = Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU ||
|
||||
context.checkSelfPermission(android.Manifest.permission.POST_NOTIFICATIONS) ==
|
||||
PackageManager.PERMISSION_GRANTED
|
||||
val batteryOptimizationsIgnored = runCatching {
|
||||
context.getSystemService(PowerManager::class.java)
|
||||
?.isIgnoringBatteryOptimizations(context.packageName)
|
||||
}.getOrNull()
|
||||
val diagnosticsSummary = withContext(Dispatchers.Default) {
|
||||
buildSupportReportSummary(context.applicationContext, settingsStore)
|
||||
}
|
||||
@@ -383,6 +445,26 @@ fun InfoTab(
|
||||
)
|
||||
)
|
||||
}
|
||||
val vpnDnsRuntimeItem = vpnDnsSnapshot?.let { settings ->
|
||||
try {
|
||||
com.wdtt.plus.collectVpnDnsRuntimeDiagnostic(
|
||||
context = context.applicationContext,
|
||||
settings = settings,
|
||||
tunnelRunning = TunnelManager.running.value,
|
||||
runningProfile = TunnelManager.activeTunnelProfile.value,
|
||||
)
|
||||
} catch (error: CancellationException) {
|
||||
throw error
|
||||
} catch (error: Throwable) {
|
||||
com.wdtt.plus.DeviceCheckItem(
|
||||
title = "Доступность выбранного DNS внутри VPN",
|
||||
status = "проверка не выполнена",
|
||||
details = error.message?.take(180) ?: error.javaClass.simpleName,
|
||||
recommendation = "Повторите проверку при активном VPN этого профиля.",
|
||||
severity = com.wdtt.plus.DeviceCheckSeverity.Warning,
|
||||
)
|
||||
}
|
||||
}
|
||||
val report = withContext(Dispatchers.Default) {
|
||||
DeviceCompatibility.check(
|
||||
context = context.applicationContext,
|
||||
@@ -391,13 +473,46 @@ fun InfoTab(
|
||||
)
|
||||
}
|
||||
return report.copy(
|
||||
summaryLines = diagnosticsSummary + clientNetworkDiagnostics.summaryLines,
|
||||
summaryLines = diagnosticsSummary + clientNetworkDiagnostics.summaryLines +
|
||||
listOfNotNull(vpnDnsRuntimeItem?.let { "DNS внутри VPN: ${it.status}" }),
|
||||
items = listOf(versionItem) +
|
||||
report.items.filterNot {
|
||||
it.title == DeviceCompatibility.APP_VERSION_ITEM_TITLE ||
|
||||
it.title == "Сеть Android"
|
||||
} + listOfNotNull(
|
||||
tunnelProfile?.let { DeviceCompatibility.rtNetworkModeItem(context, it) }
|
||||
tunnelProfile?.let { DeviceCompatibility.rtNetworkModeItem(context, it) },
|
||||
sleepBatteryModeItem(
|
||||
enabled = sleepEnabled,
|
||||
mode = sleepMode,
|
||||
pauseDelayMinutes = sleepPauseDelay,
|
||||
resumeDelayMinutes = sleepResumeDelay,
|
||||
runtime = sleepRuntime,
|
||||
notificationsGranted = notificationsGranted,
|
||||
batteryOptimizationsIgnored = batteryOptimizationsIgnored,
|
||||
),
|
||||
trustedWifiModeItem(
|
||||
enabled = trustedWifiEnabled,
|
||||
savedNetworkCount = trustedWifiSsids.size,
|
||||
waiting = trustedWifiWaiting,
|
||||
waitingSsid = trustedWifiWaitingSsid,
|
||||
accessProblem = trustedWifiProblem,
|
||||
),
|
||||
routingSnapshot?.let {
|
||||
vpnRoutingModeItem(
|
||||
snapshot = it,
|
||||
installedPackages = installedPackages,
|
||||
ownPackageName = context.packageName,
|
||||
)
|
||||
},
|
||||
vpnDnsSnapshot?.let {
|
||||
com.wdtt.plus.vpnDnsModeItem(
|
||||
settings = it,
|
||||
tunnelRunning = TunnelManager.running.value,
|
||||
runningProfile = TunnelManager.activeTunnelProfile.value,
|
||||
profileName = diagnosticProfileName,
|
||||
)
|
||||
},
|
||||
vpnDnsRuntimeItem,
|
||||
) +
|
||||
clientNetworkDiagnostics.items
|
||||
)
|
||||
@@ -1904,6 +2019,29 @@ private fun diagnosticText(block: () -> Any?): String =
|
||||
|
||||
private fun formatMiB(bytes: Long): String = "${bytes.coerceAtLeast(0L) / (1024L * 1024L)} МБ"
|
||||
|
||||
internal fun sleepBatteryModeDiagnosticText(mode: SleepBatteryMode): String = when (mode) {
|
||||
SleepBatteryMode.DELAYED_PAUSE -> "отключить VPN после задержки до включения экрана"
|
||||
SleepBatteryMode.TIMED_PAUSE -> "отключить VPN сразу и включить по таймеру"
|
||||
}
|
||||
|
||||
internal fun sleepBatteryRuntimeDiagnosticText(
|
||||
runtime: SleepBatteryRuntimeState,
|
||||
nowMs: Long = System.currentTimeMillis(),
|
||||
): String {
|
||||
val phase = when (runtime.phase) {
|
||||
SleepBatteryRuntimePhase.IDLE -> "ожидание выключения экрана"
|
||||
SleepBatteryRuntimePhase.WAITING_TO_PAUSE -> "ожидание отключения VPN"
|
||||
SleepBatteryRuntimePhase.PAUSED_UNTIL_SCREEN_ON -> "VPN отключён до включения экрана"
|
||||
SleepBatteryRuntimePhase.WAITING_TO_RESUME -> "VPN отключён, ожидается включение по таймеру"
|
||||
SleepBatteryRuntimePhase.RESUMED_UNTIL_SCREEN_ON -> "VPN включён таймером до включения экрана"
|
||||
}
|
||||
if (runtime.deadlineMs <= 0L) return phase
|
||||
val remainingMs = (runtime.deadlineMs - nowMs).coerceAtLeast(0L)
|
||||
val remainingMinutes = remainingMs / 60_000L + if (remainingMs % 60_000L == 0L) 0L else 1L
|
||||
val boundedMinutes = remainingMinutes.coerceAtMost(Int.MAX_VALUE.toLong()).toInt()
|
||||
return "$phase, осталось ${formatSleepTimerDuration(boundedMinutes)}"
|
||||
}
|
||||
|
||||
private suspend fun buildSupportReportSummary(context: Context, settingsStore: SettingsStore): List<String> {
|
||||
val androidVersion = Build.VERSION.RELEASE ?: "?"
|
||||
val sdkInt = Build.VERSION.SDK_INT
|
||||
@@ -2025,7 +2163,20 @@ private suspend fun buildSupportReportSummary(context: Context, settingsStore: S
|
||||
"density=${displayMetrics.densityDpi} dpi, fontScale=${context.resources.configuration.fontScale}"
|
||||
}
|
||||
|
||||
val activeProfile = runCatching { settingsStore.activeProfile.first() + 1 }.getOrNull()
|
||||
val selectedProfileIndex = runCatching { settingsStore.activeProfile.first() }.getOrNull()
|
||||
val savedTunnelProfileIndex = runCatching { settingsStore.activeTunnelProfile.first() }.getOrNull()
|
||||
val diagnosticProfileIndex = TunnelManager.activeTunnelProfile.value
|
||||
?: savedTunnelProfileIndex
|
||||
?: selectedProfileIndex
|
||||
val activeProfile = diagnosticProfileIndex?.plus(1)
|
||||
val routingSettings = diagnosticProfileIndex?.let { profile ->
|
||||
runCatching { settingsStore.vpnRoutingSettingsForProfile(profile) }.getOrNull()
|
||||
}
|
||||
val vpnDnsSettings = diagnosticProfileIndex?.let { profile ->
|
||||
runCatching { settingsStore.vpnDnsSettingsForProfile(profile) }.getOrNull()
|
||||
}
|
||||
val routingPackages = routingSettings?.let { decodeStoredVpnPackages(it.appPackages) }.orEmpty()
|
||||
val routingDomains = routingSettings?.addressRules?.count { it.type == com.wdtt.plus.VpnAddressType.DOMAIN }
|
||||
val workers = runCatching { settingsStore.workersPerHash.first() }.getOrNull()
|
||||
val vkHashes = runCatching { settingsStore.vkHashes.first() }.getOrDefault("")
|
||||
val hashCount = vkHashes
|
||||
@@ -2060,6 +2211,13 @@ private suspend fun buildSupportReportSummary(context: Context, settingsStore: S
|
||||
val loggingEnabled = runCatching { settingsStore.loggingEnabled.first() }.getOrNull()
|
||||
val trustedWifiEnabled = runCatching { settingsStore.trustedWifiEnabled.first() }.getOrNull()
|
||||
val trustedWifiCount = runCatching { settingsStore.trustedWifiSsids.first().size }.getOrNull()
|
||||
val trustedWifiWaiting = TrustedWifiManager.state.value.waiting ||
|
||||
runCatching { settingsStore.trustedWifiWaiting.first() }.getOrDefault(false)
|
||||
val sleepBatteryEnabled = runCatching { settingsStore.pauseVpnDuringSleep.first() }.getOrNull()
|
||||
val sleepBatteryPauseDelay = runCatching { settingsStore.pauseVpnDuringSleepDelayMinutes.first() }.getOrNull()
|
||||
val sleepBatteryMode = runCatching { settingsStore.sleepBatteryMode.first() }.getOrNull()
|
||||
val sleepBatteryResumeDelay = runCatching { settingsStore.resumeVpnDuringSleepDelayMinutes.first() }.getOrNull()
|
||||
val sleepBatteryRuntime = runCatching { settingsStore.sleepBatteryRuntimeState.first() }.getOrNull()
|
||||
val trustedWifiAccess = if (trustedWifiEnabled == true) {
|
||||
when (trustedWifiAccessProblem(context)) {
|
||||
com.wdtt.plus.TrustedWifiAccessProblem.ForegroundPermission -> "нет доступа к имени Wi-Fi"
|
||||
@@ -2070,9 +2228,16 @@ private suspend fun buildSupportReportSummary(context: Context, settingsStore: S
|
||||
} else {
|
||||
"не требуется"
|
||||
}
|
||||
val confirmedNetworkFailure = TunnelManager.hasConfirmedNetworkFailureSince(0L)
|
||||
val tunnelIssue = TunnelManager.connectionIssue.value?.let { issue ->
|
||||
"${issue.title}: ${issue.action}"
|
||||
}.orEmpty().ifBlank { "нет" }
|
||||
}.orEmpty().ifBlank {
|
||||
if (confirmedNetworkFailure) {
|
||||
"пользовательский трафик передан, но ответы не получены"
|
||||
} else {
|
||||
"нет"
|
||||
}
|
||||
}
|
||||
|
||||
return buildString {
|
||||
appendLine("Версия приложения: ${BuildConfig.VERSION_NAME}")
|
||||
@@ -2112,13 +2277,31 @@ private suspend fun buildSupportReportSummary(context: Context, settingsStore: S
|
||||
appendLine("VPN-разрешение: $vpnPermission")
|
||||
appendLine(
|
||||
"Доверенные Wi-Fi: включено=${trustedWifiEnabled ?: "недоступно"}, " +
|
||||
"сетей=${trustedWifiCount ?: "недоступно"}, ожидание=${TrustedWifiManager.state.value.waiting}, доступ=$trustedWifiAccess"
|
||||
"сетей=${trustedWifiCount ?: "недоступно"}, ожидание=$trustedWifiWaiting, доступ=$trustedWifiAccess"
|
||||
)
|
||||
appendLine(
|
||||
"Экономия батареи во сне: включено=${sleepBatteryEnabled ?: "недоступно"}, " +
|
||||
"режим=${sleepBatteryMode?.let(::sleepBatteryModeDiagnosticText) ?: "недоступно"}, " +
|
||||
"отключение через=${sleepBatteryPauseDelay?.let(::formatSleepTimerDuration) ?: "недоступно"}, " +
|
||||
"включение через=${sleepBatteryResumeDelay?.let(::formatSleepTimerDuration) ?: "недоступно"}, " +
|
||||
"состояние=${sleepBatteryRuntime?.let(::sleepBatteryRuntimeDiagnosticText) ?: "недоступно"}"
|
||||
)
|
||||
appendLine("Локаль: ${diagnosticText { Locale.getDefault().toLanguageTag() }}")
|
||||
appendLine("Часовой пояс: ${diagnosticText { TimeZone.getDefault().id }}")
|
||||
appendLine("Туннель: запущен=${TunnelManager.running.value}, активных=${TunnelManager.activeWorkers.value}")
|
||||
appendLine("Последняя проблема: $tunnelIssue")
|
||||
appendLine("Профиль: ${activeProfile ?: "недоступно"}")
|
||||
appendLine(
|
||||
"Маршрутизация профиля: режим=${routingSettings?.let { if (it.isWhitelist) "БС" else "ЧС" } ?: "недоступно"}, " +
|
||||
"приложений=${routingSettings?.let { routingPackages.size } ?: "недоступно"}, " +
|
||||
"адресов=${routingSettings?.addressRules?.size ?: "недоступно"}, " +
|
||||
"доменов=${routingDomains ?: "недоступно"}"
|
||||
)
|
||||
appendLine(
|
||||
"DNS внутри VPN: ${vpnDnsSettings?.title ?: "недоступно"}, " +
|
||||
"адреса=${vpnDnsSettings?.configuredServers?.joinToString(", ")?.ifBlank { "из WireGuard-профиля" } ?: "недоступно"}, " +
|
||||
"smart=${vpnDnsSettings?.isSmartDns ?: "недоступно"}"
|
||||
)
|
||||
appendLine("Потоки: ${workers ?: "недоступно"}")
|
||||
appendLine("VK-хеши: заполнено $hashCount, запасной=${hasSecondaryHash ?: "недоступно"}")
|
||||
appendLine("Быстрый VKCalls: ${vkCallsEnabled ?: "недоступно"}")
|
||||
|
||||
@@ -41,6 +41,7 @@ internal class OutboundFormsStore(context: Context) {
|
||||
wireGuardExitPort = string(profile, WG_EXIT_PORT, "51820"),
|
||||
wireGuardExitDns = string(profile, WG_EXIT_DNS, "1.1.1.1,8.8.8.8"),
|
||||
importedWireGuardConfig = secret(profile, IMPORTED_WG_CONFIG),
|
||||
tunInterface = string(profile, TUN_INTERFACE, ""),
|
||||
),
|
||||
warpMtu = string(profile, WARP_MTU, "1280"),
|
||||
)
|
||||
@@ -60,6 +61,7 @@ internal class OutboundFormsStore(context: Context) {
|
||||
.putString(key(profile, WG_EXIT_USER), forms.wireGuardExitUser)
|
||||
.putString(key(profile, WG_EXIT_PORT), forms.wireGuardExitPort)
|
||||
.putString(key(profile, WG_EXIT_DNS), forms.wireGuardExitDns)
|
||||
.putString(key(profile, TUN_INTERFACE), forms.tunInterface)
|
||||
.putString(key(profile, WARP_MTU), warpMtu)
|
||||
|
||||
editor.putSecret(profile, LOCAL_PROXY_PASSWORD, forms.localProxyPassword)
|
||||
@@ -132,6 +134,7 @@ internal class OutboundFormsStore(context: Context) {
|
||||
private const val WG_EXIT_DNS = "wg_exit_dns"
|
||||
private const val WARP_MTU = "warp_mtu"
|
||||
private const val IMPORTED_WG_CONFIG = "imported_wg_config"
|
||||
private const val TUN_INTERFACE = "tun_interface"
|
||||
|
||||
private val NON_SECRET_NAMES = listOf(
|
||||
LOCAL_PROXY_PORT,
|
||||
@@ -146,6 +149,7 @@ internal class OutboundFormsStore(context: Context) {
|
||||
WG_EXIT_PORT,
|
||||
WG_EXIT_DNS,
|
||||
WARP_MTU,
|
||||
TUN_INTERFACE,
|
||||
)
|
||||
private val SECRET_NAMES = listOf(
|
||||
LOCAL_PROXY_PASSWORD,
|
||||
|
||||
@@ -2068,6 +2068,7 @@ private fun ServerToolsDialog(
|
||||
InfoLine("Протокол", state.adminProfile.protocol)
|
||||
InfoLine("SNI", state.adminProfile.sni.ifBlank { "не задан" })
|
||||
InfoLine("No DNS", if (state.adminProfile.noDns) "включено" else "выключено")
|
||||
InfoLine("DNS внутри VPN", state.adminProfile.vpnDnsDisplayLabel)
|
||||
HorizontalDivider()
|
||||
Text("Будет записано при установке", fontWeight = FontWeight.Bold)
|
||||
InfoLine("VK-хеши владельца", secretPresenceLabel(localAdminProfile.vkHashes))
|
||||
@@ -2077,6 +2078,7 @@ private fun ServerToolsDialog(
|
||||
InfoLine("Протокол", localAdminProfile.protocol)
|
||||
InfoLine("SNI", localAdminProfile.sni.ifBlank { "не задан" })
|
||||
InfoLine("No DNS", if (localAdminProfile.noDns) "включено" else "выключено")
|
||||
InfoLine("DNS внутри VPN", localAdminProfile.vpnDnsDisplayLabel)
|
||||
Text(
|
||||
"Это обзор без редактирования и отдельного сохранения. Чтобы изменить профиль владельца, заполните поля во вкладках «Туннель» и «Деплой», затем нажмите «Установить» и подтвердите установку с сохранением данных или с нуля.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,442 @@
|
||||
package com.wdtt.plus.ui
|
||||
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.foundation.gestures.detectDragGestures
|
||||
import androidx.compose.foundation.gestures.detectTapGestures
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.IntrinsicSize
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.SegmentedButton
|
||||
import androidx.compose.material3.SegmentedButtonDefaults
|
||||
import androidx.compose.material3.SingleChoiceSegmentedButtonRow
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.StrokeCap
|
||||
import androidx.compose.ui.graphics.drawscope.Stroke
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.ProgressBarRangeInfo
|
||||
import androidx.compose.ui.semantics.progressBarRangeInfo
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.semantics.setProgress
|
||||
import androidx.compose.ui.semantics.stateDescription
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import com.wdtt.plus.MAX_SLEEP_PAUSE_DELAY_MINUTES
|
||||
import com.wdtt.plus.SleepBatteryMode
|
||||
import com.wdtt.plus.normalizeSleepPauseDelayMinutes
|
||||
import com.wdtt.plus.sleepDelayDescription
|
||||
import kotlin.math.PI
|
||||
import kotlin.math.atan2
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.roundToInt
|
||||
import kotlin.math.sin
|
||||
|
||||
internal fun adjustSleepTimerHours(totalMinutes: Int, hoursDelta: Int): Int =
|
||||
normalizeSleepPauseDelayMinutes(totalMinutes + hoursDelta * 60)
|
||||
|
||||
internal fun replaceSleepTimerMinuteComponent(totalMinutes: Int, minute: Int): Int {
|
||||
val normalized = normalizeSleepPauseDelayMinutes(totalMinutes)
|
||||
val hours = (normalized / 60).coerceAtMost(23)
|
||||
return normalizeSleepPauseDelayMinutes(hours * 60 + minute.coerceIn(0, 59))
|
||||
}
|
||||
|
||||
internal fun updateSleepTimerFromDialDrag(
|
||||
totalMinutes: Int,
|
||||
previousMinute: Int,
|
||||
nextMinute: Int,
|
||||
): Int {
|
||||
val previous = previousMinute.coerceIn(0, 59)
|
||||
val next = nextMinute.coerceIn(0, 59)
|
||||
var minuteDelta = next - previous
|
||||
if (minuteDelta > 30) {
|
||||
minuteDelta -= 60
|
||||
} else if (minuteDelta < -30) {
|
||||
minuteDelta += 60
|
||||
}
|
||||
return normalizeSleepPauseDelayMinutes(totalMinutes + minuteDelta)
|
||||
}
|
||||
|
||||
internal fun formatSleepTimerDuration(totalMinutes: Int): String =
|
||||
sleepDelayDescription(totalMinutes)
|
||||
|
||||
@Composable
|
||||
internal fun SleepTimerDialog(
|
||||
initialMode: SleepBatteryMode,
|
||||
initialPauseDelayMinutes: Int,
|
||||
initialResumeDelayMinutes: Int,
|
||||
onApply: (SleepBatteryMode, Int, Int) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
var selectedModeName by rememberSaveable(initialMode) { mutableStateOf(initialMode.name) }
|
||||
var pauseDelayMinutes by rememberSaveable(initialPauseDelayMinutes) {
|
||||
mutableIntStateOf(normalizeSleepPauseDelayMinutes(initialPauseDelayMinutes))
|
||||
}
|
||||
var resumeDelayMinutes by rememberSaveable(initialResumeDelayMinutes) {
|
||||
mutableIntStateOf(normalizeSleepPauseDelayMinutes(initialResumeDelayMinutes))
|
||||
}
|
||||
val selectedMode = SleepBatteryMode.valueOf(selectedModeName)
|
||||
val totalMinutes = when (selectedMode) {
|
||||
SleepBatteryMode.DELAYED_PAUSE -> pauseDelayMinutes
|
||||
SleepBatteryMode.TIMED_PAUSE -> resumeDelayMinutes
|
||||
}
|
||||
val onTotalMinutesChange: (Int) -> Unit = { minutes ->
|
||||
when (selectedMode) {
|
||||
SleepBatteryMode.DELAYED_PAUSE -> pauseDelayMinutes = minutes
|
||||
SleepBatteryMode.TIMED_PAUSE -> resumeDelayMinutes = minutes
|
||||
}
|
||||
}
|
||||
|
||||
Dialog(
|
||||
onDismissRequest = onDismiss,
|
||||
properties = DialogProperties(usePlatformDefaultWidth = false),
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 20.dp),
|
||||
shape = RoundedCornerShape(28.dp),
|
||||
tonalElevation = 8.dp,
|
||||
shadowElevation = 12.dp,
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.padding(horizontal = 22.dp, vertical = 20.dp)
|
||||
.verticalScroll(rememberScrollState()),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(
|
||||
text = "Таймер сна",
|
||||
style = MaterialTheme.typography.titleLarge,
|
||||
fontWeight = FontWeight.Bold,
|
||||
)
|
||||
IconButton(
|
||||
onClick = onDismiss,
|
||||
modifier = Modifier.align(Alignment.CenterEnd),
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Close,
|
||||
contentDescription = "Закрыть таймер сна",
|
||||
)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.heightIn(min = 80.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(
|
||||
text = when (selectedMode) {
|
||||
SleepBatteryMode.DELAYED_PAUSE -> if (totalMinutes == 0) {
|
||||
"VPN отключится сразу после выключения экрана. Интернет будет работать напрямую до включения экрана"
|
||||
} else {
|
||||
"VPN отключится через выбранное время. После отключения интернет будет работать напрямую до включения экрана"
|
||||
}
|
||||
SleepBatteryMode.TIMED_PAUSE -> if (totalMinutes == 0) {
|
||||
"При значении 0 мин VPN останется активным после выключения экрана"
|
||||
} else {
|
||||
"VPN отключится сразу и включится примерно через выбранное время. Во время паузы интернет работает напрямую"
|
||||
}
|
||||
},
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(12.dp))
|
||||
|
||||
SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) {
|
||||
SleepBatteryMode.entries.forEachIndexed { index, mode ->
|
||||
SegmentedButton(
|
||||
selected = selectedMode == mode,
|
||||
onClick = { selectedModeName = mode.name },
|
||||
shape = SegmentedButtonDefaults.itemShape(
|
||||
index = index,
|
||||
count = SleepBatteryMode.entries.size,
|
||||
),
|
||||
icon = {
|
||||
StableSegmentedButtonIcon(selected = selectedMode == mode)
|
||||
},
|
||||
label = {
|
||||
Text(
|
||||
text = when (mode) {
|
||||
SleepBatteryMode.DELAYED_PAUSE -> "Отключить позже"
|
||||
SleepBatteryMode.TIMED_PAUSE -> "Включить позже"
|
||||
},
|
||||
modifier = Modifier.width(IntrinsicSize.Min),
|
||||
maxLines = 2,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(16.dp))
|
||||
|
||||
SleepTimerDial(
|
||||
totalMinutes = totalMinutes,
|
||||
mode = selectedMode,
|
||||
onTotalMinutesChange = onTotalMinutesChange,
|
||||
)
|
||||
|
||||
Spacer(Modifier.height(14.dp))
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.Center,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
OutlinedButton(
|
||||
onClick = { onTotalMinutesChange(adjustSleepTimerHours(totalMinutes, -1)) },
|
||||
enabled = totalMinutes > 0,
|
||||
shape = RoundedCornerShape(14.dp),
|
||||
) {
|
||||
Text("−1 ч", fontWeight = FontWeight.SemiBold)
|
||||
}
|
||||
Spacer(Modifier.width(12.dp))
|
||||
OutlinedButton(
|
||||
onClick = { onTotalMinutesChange(adjustSleepTimerHours(totalMinutes, 1)) },
|
||||
enabled = totalMinutes < MAX_SLEEP_PAUSE_DELAY_MINUTES,
|
||||
shape = RoundedCornerShape(14.dp),
|
||||
) {
|
||||
Text("+1 ч", fontWeight = FontWeight.SemiBold)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(18.dp))
|
||||
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.End,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Button(onClick = { onApply(selectedMode, pauseDelayMinutes, resumeDelayMinutes) }) {
|
||||
Text("Применить")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SleepTimerDial(
|
||||
totalMinutes: Int,
|
||||
mode: SleepBatteryMode,
|
||||
onTotalMinutesChange: (Int) -> Unit,
|
||||
) {
|
||||
val minute = totalMinutes % 60
|
||||
val currentTotalMinutes by rememberUpdatedState(totalMinutes)
|
||||
val currentOnTotalMinutesChange by rememberUpdatedState(onTotalMinutesChange)
|
||||
val primary = MaterialTheme.colorScheme.primary
|
||||
val primaryContainer = MaterialTheme.colorScheme.primaryContainer
|
||||
val knobBorder = MaterialTheme.colorScheme.onPrimary
|
||||
val outline = MaterialTheme.colorScheme.outlineVariant
|
||||
val labelColor = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
|
||||
fun positionToMinute(position: Offset, size: Int): Int {
|
||||
val center = size / 2f
|
||||
val angle = atan2(position.y - center, position.x - center) + PI / 2.0
|
||||
val normalizedAngle = (angle + PI * 2.0) % (PI * 2.0)
|
||||
return ((normalizedAngle / (PI * 2.0) * 60.0).roundToInt() % 60).coerceIn(0, 59)
|
||||
}
|
||||
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(238.dp)
|
||||
.semantics {
|
||||
contentDescription = when (mode) {
|
||||
SleepBatteryMode.DELAYED_PAUSE -> "Круговой таймер до отключения VPN"
|
||||
SleepBatteryMode.TIMED_PAUSE -> "Круговой таймер до включения VPN"
|
||||
}
|
||||
stateDescription = formatSleepTimerDuration(totalMinutes)
|
||||
progressBarRangeInfo = ProgressBarRangeInfo(
|
||||
current = totalMinutes.toFloat(),
|
||||
range = 0f..MAX_SLEEP_PAUSE_DELAY_MINUTES.toFloat(),
|
||||
steps = MAX_SLEEP_PAUSE_DELAY_MINUTES - 1,
|
||||
)
|
||||
setProgress { target ->
|
||||
currentOnTotalMinutesChange(normalizeSleepPauseDelayMinutes(target.roundToInt()))
|
||||
true
|
||||
}
|
||||
},
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Canvas(
|
||||
modifier = Modifier
|
||||
.matchParentSize()
|
||||
.pointerInput(Unit) {
|
||||
detectTapGestures { position ->
|
||||
currentOnTotalMinutesChange(
|
||||
replaceSleepTimerMinuteComponent(
|
||||
currentTotalMinutes,
|
||||
positionToMinute(position, size.width),
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
.pointerInput(Unit) {
|
||||
var previousMinute = currentTotalMinutes % 60
|
||||
var dragTotal = currentTotalMinutes
|
||||
detectDragGestures(
|
||||
onDragStart = { position ->
|
||||
dragTotal = currentTotalMinutes
|
||||
previousMinute = positionToMinute(position, size.width)
|
||||
},
|
||||
) { change, _ ->
|
||||
val nextMinute = positionToMinute(change.position, size.width)
|
||||
val nextTotal = updateSleepTimerFromDialDrag(
|
||||
totalMinutes = dragTotal,
|
||||
previousMinute = previousMinute,
|
||||
nextMinute = nextMinute,
|
||||
)
|
||||
previousMinute = nextMinute
|
||||
dragTotal = nextTotal
|
||||
currentOnTotalMinutesChange(nextTotal)
|
||||
}
|
||||
}
|
||||
) {
|
||||
val center = Offset(size.width / 2f, size.height / 2f)
|
||||
val radius = size.minDimension / 2f - 18.dp.toPx()
|
||||
val minuteAngle = minute / 60f * 360f - 90f
|
||||
val angleRadians = minuteAngle / 180f * PI
|
||||
val knob = Offset(
|
||||
x = center.x + cos(angleRadians).toFloat() * radius,
|
||||
y = center.y + sin(angleRadians).toFloat() * radius,
|
||||
)
|
||||
|
||||
drawCircle(
|
||||
color = primaryContainer.copy(alpha = 0.36f),
|
||||
radius = radius + 11.dp.toPx(),
|
||||
center = center,
|
||||
)
|
||||
drawCircle(
|
||||
color = outline,
|
||||
radius = radius,
|
||||
center = center,
|
||||
style = Stroke(width = 7.dp.toPx()),
|
||||
)
|
||||
repeat(60) { index ->
|
||||
val tickAngle = (index / 60f * 360f - 90f) / 180f * PI
|
||||
val major = index % 5 == 0
|
||||
val outer = radius - 7.dp.toPx()
|
||||
val inner = outer - if (major) 9.dp.toPx() else 4.dp.toPx()
|
||||
drawLine(
|
||||
color = if (major) labelColor.copy(alpha = 0.75f) else labelColor.copy(alpha = 0.3f),
|
||||
start = Offset(
|
||||
center.x + cos(tickAngle).toFloat() * inner,
|
||||
center.y + sin(tickAngle).toFloat() * inner,
|
||||
),
|
||||
end = Offset(
|
||||
center.x + cos(tickAngle).toFloat() * outer,
|
||||
center.y + sin(tickAngle).toFloat() * outer,
|
||||
),
|
||||
strokeWidth = if (major) 2.dp.toPx() else 1.dp.toPx(),
|
||||
cap = StrokeCap.Round,
|
||||
)
|
||||
}
|
||||
if (minute > 0) {
|
||||
drawArc(
|
||||
color = primary,
|
||||
startAngle = -90f,
|
||||
sweepAngle = minute / 60f * 360f,
|
||||
useCenter = false,
|
||||
topLeft = Offset(center.x - radius, center.y - radius),
|
||||
size = androidx.compose.ui.geometry.Size(radius * 2f, radius * 2f),
|
||||
style = Stroke(width = 7.dp.toPx(), cap = StrokeCap.Round),
|
||||
)
|
||||
}
|
||||
drawLine(
|
||||
color = primary.copy(alpha = 0.7f),
|
||||
start = center,
|
||||
end = knob,
|
||||
strokeWidth = 4.dp.toPx(),
|
||||
cap = StrokeCap.Round,
|
||||
)
|
||||
drawCircle(color = knobBorder, radius = 15.dp.toPx(), center = knob)
|
||||
drawCircle(color = primary, radius = 12.dp.toPx(), center = knob)
|
||||
drawCircle(
|
||||
color = Color.White.copy(alpha = 0.85f),
|
||||
radius = 3.dp.toPx(),
|
||||
center = knob + Offset(x = -4.dp.toPx(), y = -4.dp.toPx()),
|
||||
)
|
||||
}
|
||||
|
||||
Text("0", modifier = Modifier.align(Alignment.TopCenter).padding(top = 3.dp), color = labelColor, fontSize = 11.sp)
|
||||
Text("15", modifier = Modifier.align(Alignment.CenterEnd).padding(end = 1.dp), color = labelColor, fontSize = 11.sp)
|
||||
Text("30", modifier = Modifier.align(Alignment.BottomCenter).padding(bottom = 3.dp), color = labelColor, fontSize = 11.sp)
|
||||
Text("45", modifier = Modifier.align(Alignment.CenterStart).padding(start = 1.dp), color = labelColor, fontSize = 11.sp)
|
||||
|
||||
Surface(
|
||||
modifier = Modifier.size(122.dp),
|
||||
shape = CircleShape,
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
tonalElevation = 3.dp,
|
||||
shadowElevation = 2.dp,
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.padding(8.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Center,
|
||||
) {
|
||||
Text(
|
||||
text = formatSleepTimerDuration(totalMinutes),
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
Text(
|
||||
text = when (mode) {
|
||||
SleepBatteryMode.DELAYED_PAUSE -> "до отключения"
|
||||
SleepBatteryMode.TIMED_PAUSE ->
|
||||
if (totalMinutes == 0) "VPN активен" else "до включения"
|
||||
},
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -146,9 +146,7 @@ fun TransferCenterDialog(
|
||||
}
|
||||
Text("Получить профиль", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
Text(
|
||||
"Добавьте профиль через камеру, изображение или файл. "
|
||||
+ "Если сервис выдал обновление, приложение применит его "
|
||||
+ "к связанному профилю.",
|
||||
"Добавьте профиль через камеру, изображение или файл. Через эти же кнопки можно получить защищённые настройки администратора: предварительно включать админ-режим не нужно. После ввода пароля приложение покажет подтверждение, импортирует настройки и активирует режим администратора.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
@@ -218,7 +216,7 @@ fun TransferCenterDialog(
|
||||
HorizontalDivider()
|
||||
Text("Настройки администратора", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
Text(
|
||||
"Все три VPN-профиля, параметры деплоя, пароли, токен бота, исключения и настройки выхода. Данные шифруются указанным паролем.",
|
||||
"Все три VPN-профиля, параметры деплоя, пароли, токен бота, исключения и настройки выхода. Данные шифруются указанным паролем. Приватные SSH-ключи и конфигурации служб на VPS не передаются.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
@@ -353,7 +351,7 @@ fun AdminImportDialog(
|
||||
modifier = Modifier.fillMaxWidth().onFocusChanged { passwordFocused = it.isFocused }
|
||||
)
|
||||
} else {
|
||||
Text("Будут заменены все три VPN-профиля и локальные настройки администратора. Текущие данные приложения восстановить автоматически не получится.")
|
||||
Text("Будут заменены все три VPN-профиля и локальные настройки администратора. Текущие данные приложения восстановить автоматически не получится. Приватные SSH-ключи и конфигурации служб на VPS не входят в передачу: при необходимости добавьте их отдельно.")
|
||||
}
|
||||
error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
|
||||
}
|
||||
|
||||
@@ -15,7 +15,6 @@ import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
@@ -42,7 +41,6 @@ import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
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.runtime.LaunchedEffect
|
||||
@@ -89,20 +87,19 @@ private const val BACKGROUND_LOCATION_PERMISSION = "android.permission.ACCESS_BA
|
||||
@Composable
|
||||
fun TrustedWifiSettingsDialog(
|
||||
settingsStore: SettingsStore,
|
||||
enableAfterFirstNetworkAdded: Boolean = false,
|
||||
onDismiss: () -> Unit
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val configuration = LocalConfiguration.current
|
||||
val enabledState by remember(settingsStore) {
|
||||
settingsStore.trustedWifiEnabled.map { value: Boolean -> value as Boolean? }
|
||||
}.collectAsStateWithLifecycle(initialValue = null)
|
||||
val maxDialogHeight = (configuration.screenHeightDp.dp - 32.dp).coerceAtLeast(360.dp)
|
||||
val maxScrollableContentHeight = (maxDialogHeight - 112.dp).coerceAtLeast(220.dp)
|
||||
val trustedSsidsState by remember(settingsStore) {
|
||||
settingsStore.trustedWifiSsids.map { value: List<String> -> value as List<String>? }
|
||||
}.collectAsStateWithLifecycle(initialValue = null)
|
||||
val enabled = enabledState == true
|
||||
val trustedSsids = trustedSsidsState.orEmpty()
|
||||
val settingsReady = enabledState != null && trustedSsidsState != null
|
||||
val settingsReady = trustedSsidsState != null
|
||||
val runtimeState by TrustedWifiManager.state.collectAsStateWithLifecycle()
|
||||
var currentWifi by remember { mutableStateOf(ConnectedWifiState(connected = false)) }
|
||||
var pendingAction by remember { mutableStateOf<TrustedWifiUiAction?>(null) }
|
||||
@@ -130,6 +127,9 @@ fun TrustedWifiSettingsDialog(
|
||||
currentWifi = wifi
|
||||
if (wifi.ssidAvailable) {
|
||||
val added = settingsStore.addTrustedWifiSsid(wifi.ssid)
|
||||
if (enableAfterFirstNetworkAdded) {
|
||||
settingsStore.saveTrustedWifiEnabled(true)
|
||||
}
|
||||
val message = if (added) {
|
||||
"Сеть «${wifi.ssid}» добавлена"
|
||||
} else {
|
||||
@@ -199,14 +199,15 @@ fun TrustedWifiSettingsDialog(
|
||||
properties = DialogProperties(usePlatformDefaultWidth = false)
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(vertical = 16.dp),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth(0.92f)
|
||||
.fillMaxHeight(0.9f)
|
||||
.heightIn(max = (configuration.screenHeightDp.dp - 32.dp).coerceAtLeast(360.dp)),
|
||||
.heightIn(max = maxDialogHeight),
|
||||
shape = RoundedCornerShape(30.dp),
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
tonalElevation = 8.dp,
|
||||
@@ -215,7 +216,6 @@ fun TrustedWifiSettingsDialog(
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.verticalScroll(rememberScrollState())
|
||||
.padding(18.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(14.dp)
|
||||
) {
|
||||
@@ -249,43 +249,34 @@ fun TrustedWifiSettingsDialog(
|
||||
}
|
||||
}
|
||||
|
||||
if (!settingsReady) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(180.dp),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
CircularProgressIndicator()
|
||||
}
|
||||
} else {
|
||||
Surface(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = RoundedCornerShape(18.dp),
|
||||
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.55f)
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(14.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp)
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.heightIn(max = maxScrollableContentHeight)
|
||||
.verticalScroll(rememberScrollState()),
|
||||
verticalArrangement = Arrangement.spacedBy(14.dp),
|
||||
) {
|
||||
if (!settingsReady) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(180.dp),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
Text("Автоматическое ожидание", fontWeight = FontWeight.SemiBold)
|
||||
Text(
|
||||
"VPN выключается в выбранных сетях и восстанавливается после выхода из них.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
Switch(
|
||||
checked = enabled,
|
||||
onCheckedChange = { checked ->
|
||||
if (checked) requestAction(TrustedWifiUiAction.Enable)
|
||||
else scope.launch {
|
||||
settingsStore.saveTrustedWifiEnabled(false)
|
||||
recheckService()
|
||||
}
|
||||
}
|
||||
CircularProgressIndicator()
|
||||
}
|
||||
} else {
|
||||
if (enableAfterFirstNetworkAdded && trustedSsids.isEmpty()) {
|
||||
Surface(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = RoundedCornerShape(18.dp),
|
||||
color = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.6f),
|
||||
) {
|
||||
Text(
|
||||
"Добавьте хотя бы одну сеть — после этого режим включится автоматически.",
|
||||
modifier = Modifier.padding(14.dp),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onPrimaryContainer,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -387,6 +378,7 @@ fun TrustedWifiSettingsDialog(
|
||||
color = MaterialTheme.colorScheme.error
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -428,7 +420,11 @@ fun TrustedWifiSettingsDialog(
|
||||
Toast.makeText(context, "Сеть «$clean» добавлена", Toast.LENGTH_SHORT).show()
|
||||
manualInput = ""
|
||||
showManualInput = false
|
||||
recheckService()
|
||||
if (enableAfterFirstNetworkAdded) {
|
||||
requestAction(TrustedWifiUiAction.Enable)
|
||||
} else {
|
||||
recheckService()
|
||||
}
|
||||
} else {
|
||||
Toast.makeText(context, "Сеть «$clean» уже есть в списке", Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,342 @@
|
||||
package com.wdtt.plus.ui
|
||||
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
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.layout.width
|
||||
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.filled.ChevronRight
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.Dns
|
||||
import androidx.compose.material.icons.filled.WarningAmber
|
||||
import androidx.compose.material3.AlertDialogDefaults
|
||||
import androidx.compose.material3.Button
|
||||
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.RadioButton
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import com.wdtt.plus.VPN_DNS_CUSTOM_ID
|
||||
import com.wdtt.plus.VPN_DNS_PROFILE_ID
|
||||
import com.wdtt.plus.VpnDnsCategory
|
||||
import com.wdtt.plus.VpnDnsPreset
|
||||
import com.wdtt.plus.VpnDnsSettingsSnapshot
|
||||
import com.wdtt.plus.normalizeCustomVpnDnsServers
|
||||
import com.wdtt.plus.vpnDnsPresets
|
||||
|
||||
@Composable
|
||||
internal fun VpnDnsSettingsCard(
|
||||
settings: VpnDnsSettingsSnapshot,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
val subtitle = when (settings.selectionId) {
|
||||
VPN_DNS_PROFILE_ID -> "DNS из WireGuard-профиля"
|
||||
VPN_DNS_CUSTOM_ID -> settings.customServers.joinToString(", ").ifBlank { "Не настроен" }
|
||||
else -> settings.configuredServers.joinToString(", ")
|
||||
}
|
||||
AppSectionCard(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable(onClick = onClick),
|
||||
contentPadding = PaddingValues(horizontal = 16.dp, vertical = 14.dp),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Dns,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(22.dp),
|
||||
)
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = "DNS внутри VPN",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
)
|
||||
Text(
|
||||
text = "${settings.title} · $subtitle",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Icon(
|
||||
imageVector = Icons.Default.ChevronRight,
|
||||
contentDescription = "Открыть настройку DNS",
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun VpnDnsSettingsDialog(
|
||||
initialSettings: VpnDnsSettingsSnapshot,
|
||||
onApply: (selectionId: String, customServers: String) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
var selectionId by remember(initialSettings.profileIndex, initialSettings.selectionId) {
|
||||
mutableStateOf(initialSettings.selectionId)
|
||||
}
|
||||
var customInput by remember(initialSettings.profileIndex, initialSettings.customServers) {
|
||||
mutableStateOf(initialSettings.customServers.joinToString(", "))
|
||||
}
|
||||
var validationError by remember(initialSettings.profileIndex) { mutableStateOf<String?>(null) }
|
||||
val selectedPreset = vpnDnsPresets.firstOrNull { it.id == selectionId }
|
||||
|
||||
Dialog(
|
||||
onDismissRequest = onDismiss,
|
||||
properties = DialogProperties(usePlatformDefaultWidth = false),
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth(0.92f)
|
||||
.heightIn(max = 720.dp),
|
||||
shape = RoundedCornerShape(20.dp),
|
||||
color = AlertDialogDefaults.containerColor,
|
||||
tonalElevation = 6.dp,
|
||||
) {
|
||||
Column(modifier = Modifier.padding(horizontal = 20.dp, vertical = 16.dp)) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
text = "DNS внутри VPN",
|
||||
style = MaterialTheme.typography.titleLarge,
|
||||
fontWeight = FontWeight.Bold,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
IconButton(onClick = onDismiss) {
|
||||
Icon(Icons.Default.Close, contentDescription = "Закрыть")
|
||||
}
|
||||
}
|
||||
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.weight(1f, fill = false)
|
||||
.verticalScroll(rememberScrollState()),
|
||||
) {
|
||||
Text(
|
||||
text = "Текущий профиль",
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.padding(top = 4.dp, bottom = 4.dp),
|
||||
)
|
||||
VpnDnsOptionRow(
|
||||
title = "Как в профиле",
|
||||
subtitle = "Использовать DNS, полученный вместе с WireGuard-конфигурацией",
|
||||
selected = selectionId == VPN_DNS_PROFILE_ID,
|
||||
onClick = {
|
||||
selectionId = VPN_DNS_PROFILE_ID
|
||||
validationError = null
|
||||
},
|
||||
)
|
||||
|
||||
VpnDnsPresetSection(
|
||||
title = "Обычные DNS",
|
||||
presets = vpnDnsPresets.filter { it.category == VpnDnsCategory.STANDARD },
|
||||
selectionId = selectionId,
|
||||
onSelect = {
|
||||
selectionId = it
|
||||
validationError = null
|
||||
},
|
||||
)
|
||||
VpnDnsPresetSection(
|
||||
title = "Smart DNS",
|
||||
presets = vpnDnsPresets.filter { it.category == VpnDnsCategory.SMART },
|
||||
selectionId = selectionId,
|
||||
onSelect = {
|
||||
selectionId = it
|
||||
validationError = null
|
||||
},
|
||||
)
|
||||
|
||||
Text(
|
||||
text = "Свой DNS",
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.padding(top = 14.dp, bottom = 4.dp),
|
||||
)
|
||||
VpnDnsOptionRow(
|
||||
title = "Ввести вручную",
|
||||
subtitle = customInput.ifBlank { "Один или два IPv4-адреса" },
|
||||
selected = selectionId == VPN_DNS_CUSTOM_ID,
|
||||
onClick = {
|
||||
selectionId = VPN_DNS_CUSTOM_ID
|
||||
validationError = null
|
||||
},
|
||||
)
|
||||
if (selectionId == VPN_DNS_CUSTOM_ID) {
|
||||
OutlinedTextField(
|
||||
value = customInput,
|
||||
onValueChange = { value ->
|
||||
customInput = value.filter { character ->
|
||||
character.isDigit() || character in ".,; \n\t"
|
||||
}
|
||||
validationError = null
|
||||
},
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(top = 8.dp),
|
||||
label = { Text("IPv4-адреса DNS") },
|
||||
placeholder = { Text("1.1.1.1, 1.0.0.1") },
|
||||
supportingText = {
|
||||
Text(validationError ?: "Разделите адреса запятой или пробелом")
|
||||
},
|
||||
isError = validationError != null,
|
||||
minLines = 1,
|
||||
maxLines = 2,
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal),
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
)
|
||||
}
|
||||
|
||||
if (selectedPreset?.category == VpnDnsCategory.SMART) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(top = 12.dp),
|
||||
verticalAlignment = Alignment.Top,
|
||||
) {
|
||||
Icon(
|
||||
Icons.Default.WarningAmber,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.tertiary,
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
text = "Сторонний Smart DNS может направлять соединения с отдельными сервисами через собственные шлюзы.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
text = "Настройка действует на системный DNS приложений внутри VPN. Встроенный в приложение или браузер защищённый DNS может использовать собственный адрес.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(top = 12.dp, bottom = 4.dp),
|
||||
)
|
||||
}
|
||||
|
||||
Button(
|
||||
onClick = {
|
||||
if (selectionId == VPN_DNS_CUSTOM_ID) {
|
||||
val result = runCatching { normalizeCustomVpnDnsServers(customInput) }
|
||||
validationError = result.exceptionOrNull()?.message
|
||||
if (result.isFailure) return@Button
|
||||
customInput = result.getOrThrow().joinToString(", ")
|
||||
}
|
||||
onApply(selectionId, customInput)
|
||||
},
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(top = 14.dp),
|
||||
shape = RoundedCornerShape(14.dp),
|
||||
) {
|
||||
Text("Применить")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun VpnDnsPresetSection(
|
||||
title: String,
|
||||
presets: List<VpnDnsPreset>,
|
||||
selectionId: String,
|
||||
onSelect: (String) -> Unit,
|
||||
) {
|
||||
Text(
|
||||
text = title,
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.padding(top = 14.dp, bottom = 4.dp),
|
||||
)
|
||||
presets.forEach { preset ->
|
||||
VpnDnsOptionRow(
|
||||
title = preset.title,
|
||||
subtitle = "${preset.servers.joinToString(", ")} · ${preset.description}",
|
||||
selected = selectionId == preset.id,
|
||||
onClick = { onSelect(preset.id) },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun VpnDnsOptionRow(
|
||||
title: String,
|
||||
subtitle: String,
|
||||
selected: Boolean,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable(onClick = onClick),
|
||||
color = if (selected) {
|
||||
MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.55f)
|
||||
} else {
|
||||
MaterialTheme.colorScheme.surface
|
||||
},
|
||||
shape = RoundedCornerShape(8.dp),
|
||||
border = if (selected) {
|
||||
BorderStroke(1.dp, MaterialTheme.colorScheme.primary.copy(alpha = 0.65f))
|
||||
} else {
|
||||
null
|
||||
},
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.padding(horizontal = 8.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
RadioButton(selected = selected, onClick = onClick)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(text = title, style = MaterialTheme.typography.bodyMedium)
|
||||
Text(
|
||||
text = subtitle,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.35f))
|
||||
}
|
||||
Reference in new issue
Block a user