refactor(proxy): распилить ProxyService на focused-юниты в пакете proxy

Бог-класс (735 строк) разбит: CoreProcessController (процесс+watchdog),
NetworkHandoverMonitor (хендовер сети+DNS), ProxyNotifier, SpeedMonitor,
ProcessCompat, ProxyActions. Состояния StartupResult/CaptchaSession/
ConnectionStats перенесены в domain/AppStates. Строки статусов вынесены
в strings.xml, маркеры событий в логах с "===" на ключевые слова.
This commit is contained in:
samosvalishe committed 2026-06-13 21:37:23 +03:00
1 parent 85d7dc43b4
commit 5c4ca738bf
21 files changed
+928 -781

No files matched your search

+3 -3
View File
@@ -68,7 +68,7 @@
</activity>
<service
android:name=".ProxyService"
android:name=".proxy.ProxyService"
android:exported="false"
android:foregroundServiceType="specialUse"
tools:targetApi="29">
@@ -97,11 +97,11 @@
</provider>
<receiver
android:name=".ProxyReceiver"
android:name=".proxy.ProxyReceiver"
android:exported="false" />
<service
android:name=".ProxyTileService"
android:name=".proxy.ProxyTileService"
android:exported="true"
android:icon="@drawable/ic_qs_tile_nearby"
android:label="@string/tile_service_label"
@@ -1,735 +0,0 @@
package com.freeturn.app
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.content.pm.ServiceInfo
import android.os.PowerManager
import android.os.SystemClock
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.app.ServiceCompat
import com.freeturn.app.data.AppPreferences
import com.freeturn.app.data.CoreArgs
import com.freeturn.app.domain.CoreConnectionTracker
import com.freeturn.app.domain.CoreLogEvent
import com.freeturn.app.domain.CoreLogParser
import com.freeturn.app.domain.WireGuardTunnelManager
import java.io.BufferedReader
import java.io.File
import java.io.InputStreamReader
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicReference
import kotlin.random.Random
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import org.koin.android.ext.android.inject
sealed class StartupResult {
data object Success : StartupResult()
data class Failed(val message: String) : StartupResult()
}
class ProxyService : Service() {
companion object {
const val MAX_RESTARTS = 8
private const val CHANNEL_PROXY = "ProxyChannel"
private const val CHANNEL_CAPTCHA = "CaptchaChannel"
private const val NOTIF_ID_FG = 1
private const val NOTIF_ID_CAPTCHA = 2
// Даём TURN-туннелю «устаканиться» перед поднятием WireGuard поверх него.
private const val WIREGUARD_START_DELAY_MS = 2_000L
// Игнорируем сетевые события первые секунды после регистрации колбэка —
// иначе initial onAvailable/onCapabilitiesChanged триггерят ложный рестарт.
private const val NETWORK_CALLBACK_WARMUP_MS = 3_000L
}
private var wakeLock: PowerManager.WakeLock? = null
private var openAppIntent: PendingIntent? = null
private var currentBaseStatus = ""
private var currentSpeedText = ""
@Volatile private var speedLoopJob: kotlinx.coroutines.Job? = null
private val process = AtomicReference<Process?>(null)
private val userStopped = AtomicBoolean(false)
private val sessionKillScheduled = AtomicBoolean(false)
private val handler = Handler(Looper.getMainLooper())
private var networkCallback: ConnectivityManager.NetworkCallback? = null
@Volatile private var networkDebounceJob: kotlinx.coroutines.Job? = null
@Volatile private var lastPhysicalNetworkKey: String? = null
private val restartCount = AtomicInteger(0)
@Volatile private var captchaNotificationActive = false
private val prefs: AppPreferences by inject()
private lateinit var serviceScope: CoroutineScope
private lateinit var wireGuard: WireGuardTunnelManager
override fun onBind(intent: Intent?): IBinder? = null
override fun onCreate() {
super.onCreate()
serviceScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
wireGuard = WireGuardTunnelManager(applicationContext)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val nm = getSystemService(NotificationManager::class.java)
nm.createNotificationChannel(
NotificationChannel(
CHANNEL_PROXY,
getString(R.string.notif_channel_proxy),
NotificationManager.IMPORTANCE_LOW
)
)
nm.createNotificationChannel(
NotificationChannel(
CHANNEL_CAPTCHA,
getString(R.string.notif_channel_captcha),
NotificationManager.IMPORTANCE_HIGH
)
)
}
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
// ВАЖНО: startForeground вызываем ПЕРВЫМ делом и БЕЗУСЛОВНО — любой return
// до него даёт ForegroundServiceDidNotStartInTimeException через ~5с.
if (openAppIntent == null) {
openAppIntent = packageManager.getLaunchIntentForPackage(packageName)?.let {
PendingIntent.getActivity(this, 0, it, PendingIntent.FLAG_IMMUTABLE)
}
}
currentBaseStatus = getString(R.string.notif_proxy_connecting)
// Явно передаём FGS-тип (specialUse доступен с API 34; ниже — без типа).
// Оборачиваем в try/catch: ForegroundServiceStartNotAllowedException (API 31+
// при старте из фона) и InvalidForegroundServiceTypeException не должны
// ронять процесс.
val fgsType = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE else 0
try {
ServiceCompat.startForeground(this, NOTIF_ID_FG, createNotification(), fgsType)
} catch (e: Exception) {
ProxyServiceState.addLog("Не удалось запустить foreground-сервис: ${e.message}")
ProxyServiceState.setStartupResult(StartupResult.Failed(e.message ?: "FGS start failed"))
ProxyServiceState.setRunning(false)
stopSelf()
return START_NOT_STICKY
}
// Если процесс ядра ещё жив — это повторный onStartCommand (например,
// sticky-рестарт). Не запускаем второй процесс, но требование о
// startForeground выше уже выполнено.
if (process.get() != null) {
ProxyServiceState.setRunning(true)
return START_STICKY
}
ProxyServiceState.setRunning(true)
userStopped.set(false)
restartCount.set(0)
val powerManager = getSystemService(POWER_SERVICE) as PowerManager
// Освобождаем предыдущий wakelock перед созданием нового — иначе при
// повторном onStartCommand с уже мёртвым process старый объект остаётся
// held до GC (утечка wakelock).
if (wakeLock?.isHeld == true) wakeLock?.release()
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "VkTurn::BgLock")
wakeLock?.acquire(TimeUnit.HOURS.toMillis(24))
registerNetworkCallback()
ProxyServiceState.addLog("=== ЗАПУСК ПРОКСИ ===")
startSpeedMonitor()
serviceScope.launch { startBinaryProcess() }
return START_STICKY
}
private suspend fun startBinaryProcess() {
if (userStopped.get()) return
val cfg = prefs.clientConfigFlow.first()
ProxyServiceState.setLogsEnabled(cfg.logsEnabled)
// Obf-обфускация управляется на серверном экране, но должна передаваться
// и клиенту с тем же ключом, иначе DTLS-handshake не сойдётся. Источник
// истины — общий serverOpts.
val srv = prefs.serverOptsFlow.first()
// Имя ядра версионируется (libfreeturn-<ver>-android-arm64.so) и меняется
// между релизами — не хардкодим. Ищем в nativeLibraryDir libfreeturn*.so
// (Android извлекает туда только файлы вида lib*.so). При нескольких версиях
// берём лексикографически старшую.
val libDir = File(applicationInfo.nativeLibraryDir)
val executable = libDir.listFiles { f ->
f.name.startsWith("libfreeturn") && f.name.endsWith(".so")
}?.maxByOrNull { it.name }?.absolutePath
if (executable == null) {
ProxyServiceState.addLog(
"КРИТИЧЕСКАЯ ОШИБКА: ядро libfreeturn*.so не найдено в ${libDir.path}. " +
"Положите бинарник в jniLibs/arm64-v8a/ (имя обязано начинаться с lib и оканчиваться на .so)."
)
ProxyServiceState.setStartupResult(StartupResult.Failed("core binary not found"))
ProxyServiceState.setRunning(false)
stopSelf()
return
}
val cmdArgs = mutableListOf<String>()
if (cfg.isRawMode) {
val parts = cfg.rawCommand.trim().split("\\s+".toRegex()).filter { it.isNotEmpty() }
cmdArgs.add(executable)
cmdArgs.addAll(parts.drop(1))
} else {
cmdArgs.add(executable)
// argv строит общий с UI билдер ([CoreArgs.client]) — показанная команда не
// расходится с реально запускаемой. DNS оператора резолвим здесь (зависит от
// активной сети) и передаём в билдер.
val carrierDns = if (cfg.useCarrierDns) activeNetworkDnsServers() else null
cmdArgs.addAll(CoreArgs.client(cfg, srv, carrierDns, prefs.ownClientId()))
}
var exitCode = -1
val startedAt = System.currentTimeMillis()
var startupEmitted = false
var startupFailed = false
var wireGuardStarted = false
var captchaSessionCounter = 0L
// --- Трекинг активных соединений для индикации состояния в UI. ---
// UDP-релей (-mode udp): каждый поток логирует свой [STREAM N] Established/Closed
// парой (defer Closed ставится ДО логирования Established, см. client/main.go).
// Для UDP-релея целевое число потоков известно из конфига (-n). Если threads == 0,
// ядро запускает один поток, считаем total = 1.
val tracker = CoreConnectionTracker(
udpTotal = if (cfg.isRawMode) 0 else if (cfg.threads > 0) cfg.threads else 1,
tcpMode = cfg.tcpForward
)
fun publishStats() {
ProxyServiceState.setConnectionStats(ConnectionStats(tracker.active, tracker.total))
if (currentBaseStatus == getString(R.string.proxy_active)) {
buildAndShowNotification()
}
}
// Сброс на старте сессии (в том числе на watchdog-рестарте).
publishStats()
try {
ProxyServiceState.addLog("Команда: ${cmdArgs.joinToString(" ")}")
val proc = withContext(Dispatchers.IO) {
val pb = ProcessBuilder(cmdArgs).redirectErrorStream(true)
// Ядро по умолчанию пишет vk_profile.json в CWD (= /data/app/.../lib/<abi>/),
// а это read-only mount на Android. Перенаправляем в filesDir, где записать
// можно. См. client/profiles.go: profileFilePath() читает $VK_PROFILE_PATH
// в первую очередь.
pb.environment()["VK_PROFILE_PATH"] =
File(filesDir, "vk_profile.json").absolutePath
// CWD тоже подменяем на writeable dir — на случай если Go-код или его
// зависимости пишут что-то относительными путями (логи кеша tls-client и т.п.).
pb.directory(filesDir)
pb.start()
}
process.set(proc)
BufferedReader(InputStreamReader(proc.inputStream)).use { reader ->
var line: String?
while (true) {
line = try {
reader.readLine()
} catch (e: java.io.IOException) {
// При destroyCompat()/Process.destroy() с другого треда
// нативный pipe закрывается, и блокирующий readLine() бросает
// IOException("Stream closed" / "read interrupted by close()").
// Это нормальный путь остановки — выходим из цикла молча.
val msg = e.message.orEmpty()
val benign = userStopped.get() ||
msg.contains("interrupted by close", ignoreCase = true) ||
msg.contains("Stream closed", ignoreCase = true) ||
msg.contains("Bad file descriptor", ignoreCase = true)
if (!benign) {
ProxyServiceState.addLog("Чтение лога ядра прервано: ${e.message}")
}
null
}
if (line == null) break
val l = line
ProxyServiceState.addLog(l)
// Разбор строки — в CoreLogParser (чистая логика, под юнит-тестами);
// здесь только реакция на события.
val events = CoreLogParser.parse(l)
var statsChanged = false
for (event in events) when (event) {
// Детекция URL ручной капчи. Каждый раз выдаём новый sessionId,
// чтобы диалог пересоздавал WebView, даже если URL не поменялся
// (бинарник всегда использует http://localhost:8765).
is CoreLogEvent.CaptchaUrl -> {
captchaSessionCounter += 1
ProxyServiceState.setCaptchaSession(
CaptchaSession(event.url, captchaSessionCounter)
)
// Показываем нотификацию только если предыдущая капча уже закрыта.
// Бинарник может выдать несколько URL подряд за одну авторизацию —
// не плодим спам.
if (!captchaNotificationActive) {
showCaptchaNotification()
captchaNotificationActive = true
}
}
// Закрываем диалог — следующая капча-сессия откроет его заново
// через новый sessionId.
CoreLogEvent.CaptchaResolved -> {
if (ProxyServiceState.captchaSession.value != null) {
ProxyServiceState.setCaptchaSession(null)
cancelCaptchaNotification()
}
}
else -> if (tracker.apply(event)) statsChanged = true
}
if (statsChanged) publishStats()
// Startup: ядро упало с panic/fatal/окончательно не смогло
// получить creds ДО того, как удалось подключиться — считаем
// запуск неудачным. Первая строка без этих маркеров больше не
// трактуется как Success (ядро могло написать "Connecting..."
// и только потом упасть).
if (!startupEmitted) {
val hasFatal = events.any { it is CoreLogEvent.FatalStartup }
val hasConnection = tracker.hasConnection
when {
hasFatal -> {
ProxyServiceState.setStartupResult(StartupResult.Failed(l))
updateNotification("Ошибка подключения")
startupFailed = true
startupEmitted = true
}
hasConnection -> {
try {
if (cfg.wireGuardActive) {
ProxyServiceState.addLog(
"WireGuard: ждём ${WIREGUARD_START_DELAY_MS}мс после поднятия TURN-туннеля"
)
kotlinx.coroutines.delay(WIREGUARD_START_DELAY_MS)
if (userStopped.get() || process.get() !== proc) {
ProxyServiceState.addLog(
"WireGuard: старт отменён, прокси уже останавливается"
)
break
}
}
wireGuard.startAfterProxyReady(cfg)
wireGuardStarted = cfg.wireGuardActive
ProxyServiceState.setStartupResult(StartupResult.Success)
ProxyServiceState.markConnectedIfAbsent(SystemClock.elapsedRealtime())
updateNotification(
if (wireGuardStarted) getString(R.string.proxy_active_wireguard)
else getString(R.string.proxy_active)
)
} catch (e: Exception) {
val message = e.message ?: e.javaClass.simpleName
ProxyServiceState.addLog("WireGuard: ошибка запуска: $message")
ProxyServiceState.setStartupResult(
StartupResult.Failed("WireGuard не запустился: $message")
)
updateNotification("Ошибка WireGuard")
startupFailed = true
proc.destroyCompat()
}
startupEmitted = true
}
}
}
// compareAndSet гарантирует единственный postDelayed даже при параллельных quota-ошибках
if (events.any { it is CoreLogEvent.QuotaError } &&
sessionKillScheduled.compareAndSet(false, true)) {
ProxyServiceState.addLog(">>> QUOTA ERROR — сброс сессии через 2с")
handler.postDelayed({
sessionKillScheduled.set(false)
if (!userStopped.get()) {
restartCount.set(0)
process.get()?.destroyCompat()
}
}, 2_000)
}
}
}
exitCode = if (withContext(Dispatchers.IO) {
proc.waitForCompat(5, TimeUnit.MINUTES)
}) proc.exitValue() else -1
ProxyServiceState.addLog("=== ПРОЦЕСС ОСТАНОВЛЕН (Код: $exitCode) ===")
if (!startupEmitted) {
ProxyServiceState.setStartupResult(StartupResult.Failed(
"Процесс завершился без вывода (код: $exitCode)"))
}
} catch (e: CancellationException) {
// Остановка из UI отменяет корутину serviceScope → CancellationException
// ("Job was cancelled"). Это штатный путь остановки, не критическая ошибка.
// Пробрасываем дальше, чтобы не ломать семантику отмены; finally ниже
// обработает userStopped → stopSelf.
throw e
} catch (e: Exception) {
// Любое исключение во время пользовательской остановки — следствие
// destroy()/закрытия пайпов, а не реальная ошибка. Не шумим в логах.
if (userStopped.get()) {
startupFailed = false
} else {
val msg = e.message ?: ""
if (msg.contains("error=13") || msg.contains("Permission denied")) {
ProxyServiceState.addLog("КРИТИЧЕСКАЯ ОШИБКА: Отказано в запуске ядра — ваше устройство блокирует выполнение файлов из внутреннего хранилища (SELinux/noexec). Используйте встроенное ядро.")
ProxyServiceState.setStartupResult(StartupResult.Failed(msg))
startupFailed = true
} else {
ProxyServiceState.addLog("КРИТИЧЕСКАЯ ОШИБКА: ${e.message}")
}
}
} finally {
ProxyServiceState.setCaptchaSession(null)
cancelCaptchaNotification()
// WG-туннель живёт только поверх работающего прокси — гасим вместе с ядром.
if (wireGuardStarted) wireGuard.stop()
// Процесс мёртв — активных соединений нет. При watchdog-рестарте
// publishStats на новом старте снова выставит правильный target.
ProxyServiceState.setConnectionStats(ConnectionStats.IDLE)
process.set(null)
when {
userStopped.get() -> {
ProxyServiceState.setRunning(false)
stopSelf()
}
startupFailed -> {
ProxyServiceState.addLog("=== Ошибка при запуске, watchdog не активирован ===")
ProxyServiceState.setRunning(false)
// Убираем proxyFailed.tryEmit, так как startProxy и так обработает StartupResult.Failed
stopSelf()
}
exitCode == 0 -> {
val uptime = System.currentTimeMillis() - startedAt
if (uptime < 5_000L) {
ProxyServiceState.addLog("=== Быстрый выход (${uptime}мс) — проверьте VK-ссылку и настройки ===")
} else {
ProxyServiceState.addLog("=== Сессия завершена нормально ===")
}
ProxyServiceState.setRunning(false)
stopSelf()
}
else -> scheduleWatchdogRestart()
}
}
}
// Watchdog
private fun scheduleWatchdogRestart() {
val count = restartCount.incrementAndGet()
if (count > MAX_RESTARTS) {
ProxyServiceState.addLog("=== WATCHDOG: превышен лимит попыток ($MAX_RESTARTS), остановка ===")
ProxyServiceState.setRunning(false)
ProxyServiceState.emitFailed()
stopSelf()
return
}
val baseDelay = minOf(1_000L * count, 30_000L)
val jitter = Random.nextLong(0, 500)
val delay = baseDelay + jitter
ProxyServiceState.addLog("=== WATCHDOG: перезапуск через ${delay}мс (попытка $count/$MAX_RESTARTS) ===")
updateNotification("Переподключение ($count/$MAX_RESTARTS)...")
handler.postDelayed({
if (!userStopped.get()) serviceScope.launch { startBinaryProcess() }
}, delay)
}
// Network handover
private fun registerNetworkCallback() {
val cm = getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
val registeredAt = SystemClock.elapsedRealtime()
lastPhysicalNetworkKey = physicalNetworkKey(cm)
// Перезапуск только когда реально меняется ФИЗИЧЕСКАЯ сеть (Wi-Fi↔LTE и т.п.).
// WireGuard поднимает свой VPN-интерфейс — без фильтрации NOT_VPN его появление
// выглядело бы как смена сети и уводило прокси в бесконечный рестарт.
fun schedulePhysicalNetworkCheck(reason: String) {
if (SystemClock.elapsedRealtime() - registeredAt < NETWORK_CALLBACK_WARMUP_MS) {
return
}
networkDebounceJob?.cancel()
networkDebounceJob = serviceScope.launch {
kotlinx.coroutines.delay(2_000)
val oldKey = lastPhysicalNetworkKey
val newKey = physicalNetworkKey(cm)
// Ключ тот же — ожидаемый no-op. onCapabilitiesChanged сыплет
// десятки раз/мин (сигнал, link speed, валидация инета), не логаем.
if (oldKey == newKey) return@launch
lastPhysicalNetworkKey = newKey
if (newKey == null) {
ProxyServiceState.addLog("=== СЕТЬ: физическая сеть недоступна ($reason) ===")
return@launch
}
if (!userStopped.get() && process.get() != null) {
ProxyServiceState.addLog("=== СМЕНА СЕТИ — ПЕРЕЗАПУСК ===")
updateNotification("Смена сети, переподключение...")
restartCount.set(0)
process.get()?.destroyCompat()
}
}
}
val cb = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
val caps = cm.getNetworkCapabilities(network)
if (caps == null || caps.hasTransport(NetworkCapabilities.TRANSPORT_VPN) ||
!caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN)) {
ProxyServiceState.addLog("=== СЕТЬ: VPN-событие проигнорировано ===")
return
}
schedulePhysicalNetworkCheck("available")
}
override fun onLost(network: Network) {
schedulePhysicalNetworkCheck("lost")
}
override fun onCapabilitiesChanged(
network: Network,
networkCapabilities: NetworkCapabilities
) {
if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN) ||
!networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN)) {
return
}
schedulePhysicalNetworkCheck("capabilities")
}
}
networkCallback = cb
val request = NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN)
.build()
cm.registerNetworkCallback(request, cb)
}
/**
* Ключ ОДНОЙ приоритетной физсети (транспорт + iface). Берём приоритетную, а не
* весь allNetworks: при активном Wi-Fi cellular флапает в фоне, набор прыгал бы →
* ложная «смена сети» → лишний рестарт. link-адреса не в ключе — ротация
* IPv6/DHCP идёт на той же сети. Реальный хендовер меняет транспорт/iface.
*/
private fun physicalNetworkKey(cm: ConnectivityManager): String? {
// allNetworks deprecated с API 31, но это единственный синхронный способ
// снять полный снимок текущих сетей внутри колбэка. Подавляем осознанно.
@Suppress("DEPRECATION")
return cm.allNetworks.mapNotNull { network ->
val caps = cm.getNetworkCapabilities(network) ?: return@mapNotNull null
if (caps.hasTransport(NetworkCapabilities.TRANSPORT_VPN) ||
!caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) ||
!caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN)) {
return@mapNotNull null
}
// Приоритет = индекс, меньше важнее.
val (priority, transport) = when {
caps.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> 0 to "ethernet"
caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> 1 to "wifi"
caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> 2 to "cellular"
caps.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH) -> 3 to "bluetooth"
else -> return@mapNotNull null
}
val iface = cm.getLinkProperties(network)?.interfaceName.orEmpty()
// tie-break по iface — детерминированный выбор при равном приоритете.
Triple(priority, iface, "$transport|$iface")
}.minWithOrNull(compareBy({ it.first }, { it.second }))?.third
}
private fun unregisterNetworkCallback() {
networkCallback?.let { cb ->
try {
(getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager)
.unregisterNetworkCallback(cb)
} catch (_: Exception) {}
}
networkCallback = null
}
// Notification
private fun showCaptchaNotification() {
val notification = NotificationCompat.Builder(this, CHANNEL_CAPTCHA)
.setContentTitle(getString(R.string.notif_captcha_title))
.setContentText(getString(R.string.notif_captcha_text))
.setSmallIcon(R.drawable.ic_notification_captcha)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_REMINDER)
.setAutoCancel(true)
.setContentIntent(openAppIntent)
.build()
try {
NotificationManagerCompat.from(this).notify(NOTIF_ID_CAPTCHA, notification)
} catch (_: SecurityException) {
// POST_NOTIFICATIONS отозван юзером на API 33+ — молча игнорируем,
// диалог в UI всё равно откроется через captchaSession StateFlow.
}
}
private fun cancelCaptchaNotification() {
NotificationManagerCompat.from(this).cancel(NOTIF_ID_CAPTCHA)
captchaNotificationActive = false
}
private fun updateNotification(text: String) {
currentBaseStatus = text
buildAndShowNotification()
}
private fun formatSpeed(bytes: Long): String {
return when {
bytes < 1024 -> "$bytes B/s"
bytes < 1024 * 1024 -> "${bytes / 1024} KB/s"
else -> String.format(java.util.Locale.US, "%.1f MB/s", bytes / (1024f * 1024f))
}
}
private fun startSpeedMonitor() {
speedLoopJob?.cancel()
speedLoopJob = serviceScope.launch {
val uid = android.os.Process.myUid()
var lastRx = android.net.TrafficStats.getUidRxBytes(uid)
var lastTx = android.net.TrafficStats.getUidTxBytes(uid)
while (!userStopped.get()) {
kotlinx.coroutines.delay(3000)
val currentRx = android.net.TrafficStats.getUidRxBytes(uid)
val currentTx = android.net.TrafficStats.getUidTxBytes(uid)
if (currentRx != android.net.TrafficStats.UNSUPPORTED.toLong() && lastRx != android.net.TrafficStats.UNSUPPORTED.toLong()) {
val rxSpeed = maxOf(0, currentRx - lastRx)
val txSpeed = maxOf(0, currentTx - lastTx)
currentSpeedText = "↓ ${formatSpeed(rxSpeed)} ↑ ${formatSpeed(txSpeed)}"
lastRx = currentRx
lastTx = currentTx
if (currentBaseStatus == getString(R.string.proxy_active)) {
buildAndShowNotification()
}
}
}
}
}
private fun createNotification(): android.app.Notification {
var text = currentBaseStatus
val stats = ProxyServiceState.connectionStats.value
if (currentBaseStatus == getString(R.string.proxy_active)) {
if (stats.total > 0) {
text = String.format(
java.util.Locale.US,
getString(R.string.notif_proxy_status_format),
stats.active,
stats.total,
currentSpeedText
)
} else if (currentSpeedText.isNotEmpty()) {
text += " • $currentSpeedText"
}
}
val stopIntent = Intent(this, ProxyReceiver::class.java).apply {
action = "com.freeturn.app.STOP_PROXY"
}
val stopPendingIntent = PendingIntent.getBroadcast(
this, 0, stopIntent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
)
return NotificationCompat.Builder(this, CHANNEL_PROXY)
.setContentTitle(getString(R.string.notif_proxy_title))
.setContentText(text)
.setSmallIcon(android.R.drawable.ic_menu_preferences)
.setOngoing(true)
.setContentIntent(openAppIntent)
.addAction(0, getString(R.string.notif_proxy_stop_action), stopPendingIntent)
.build()
}
private fun buildAndShowNotification() {
try {
NotificationManagerCompat.from(this).notify(NOTIF_ID_FG, createNotification())
} catch (_: SecurityException) {}
}
// Helpers
/**
* DNS активной сети (оператор/Wi-Fi). Возвращает comma-separated список IP,
* пригодный для флага `-dns-servers` ядра. Пусто, если сеть недоступна или
* у linkProperties нет DNS (что норма на эмуляторе/некоторых VPN).
*/
private fun activeNetworkDnsServers(): String {
return try {
val cm = getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
val net = cm.activeNetwork ?: return ""
val lp = cm.getLinkProperties(net) ?: return ""
lp.dnsServers
.mapNotNull { it.hostAddress }
.filter { it.isNotBlank() }
.joinToString(",")
} catch (_: Exception) {
""
}
}
override fun onDestroy() {
super.onDestroy()
userStopped.set(true)
ProxyServiceState.setRunning(false)
ProxyServiceState.setConnectionStats(ConnectionStats.IDLE)
ProxyServiceState.clearConnectedSince()
handler.removeCallbacksAndMessages(null)
unregisterNetworkCallback()
cancelCaptchaNotification()
ProxyServiceState.addLog("=== ОСТАНОВКА ИЗ ИНТЕРФЕЙСА ===")
process.get()?.destroyCompat()
// WG-teardown — блокирующий JNI/IO; держать им main-поток нельзя (ANR).
// serviceScope гасим сразу, поэтому стоп туннеля уводим на отдельный поток
// без ожидания: туннель опустится сам, а если процесс прибьют — VpnService
// снимет ОС вместе с процессом.
val wg = wireGuard
Thread { runBlocking { wg.stop() } }.start()
serviceScope.cancel()
if (wakeLock?.isHeld == true) wakeLock?.release()
}
}
private fun Process.destroyCompat() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) destroyForcibly() else destroy()
}
private fun Process.waitForCompat(timeout: Long, unit: TimeUnit): Boolean {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) return waitFor(timeout, unit)
val deadline = System.currentTimeMillis() + unit.toMillis(timeout)
while (System.currentTimeMillis() < deadline) {
try { exitValue(); return true } catch (_: IllegalThreadStateException) { Thread.sleep(100) }
}
return try { exitValue(); true } catch (_: IllegalThreadStateException) { false }
}
@@ -2,7 +2,7 @@ package com.freeturn.app.data
/**
* Единый источник истины для argv клиентского ядра. Использует и движок
* ([com.freeturn.app.ProxyService] при запуске процесса), и UI (отладочная информация →
* ([com.freeturn.app.proxy.ProxyService] при запуске процесса), и UI (отладочная информация →
* параметры запуска), чтобы показанная команда не расходилась с реально запускаемой.
*
* Возвращает аргументы БЕЗ имени бинарника. DNS оператора ([carrierDns]) резолвится
@@ -40,6 +40,30 @@ sealed class ProxyState {
data class CaptchaRequired(val url: String, val sessionId: Long = 0L) : ProxyState()
}
// Результат старта прокси-сервиса (мост ProxyService → ProxyViewModel).
sealed class StartupResult {
data object Success : StartupResult()
data class Failed(val message: String) : StartupResult()
}
/**
* Сессия ручной капчи. sessionId позволяет диалогу различать соседние
* капча-сессии с одинаковым URL и пересоздавать WebView через `key(sessionId)`.
*/
data class CaptchaSession(val url: String, val sessionId: Long)
/**
* Агрегированная статистика подключений прокси-ядра.
*
* - [active] — число реально живых каналов (DTLS-потоков для udp-релея, smux-сессий для tcp-режима).
* - [total] — целевое число каналов. 0 означает «ещё неизвестно» (tcp-режим до первой waiting-строки).
*/
data class ConnectionStats(val active: Int, val total: Int) {
companion object {
val IDLE = ConnectionStats(0, 0)
}
}
// App update states
sealed class UpdateState {
object Idle : UpdateState()
@@ -3,11 +3,10 @@ package com.freeturn.app.domain
import android.content.Context
import android.content.Intent
import android.os.Build
import com.freeturn.app.ConnectionStats
import com.freeturn.app.ProxyService
import com.freeturn.app.ProxyServiceState
import com.freeturn.app.StartupResult
import com.freeturn.app.data.ClientConfig
import com.freeturn.app.proxy.CoreProcessController
import com.freeturn.app.proxy.ProxyService
import com.freeturn.app.proxy.ProxyServiceState
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
@@ -43,7 +42,7 @@ class LocalProxyManager(private val context: Context) {
private suspend fun observeProxyLifecycle() {
ProxyServiceState.proxyFailed.collect {
setErrorWithAutoReset("Прокси упал ${ProxyService.MAX_RESTARTS} раз — проверьте настройки")
setErrorWithAutoReset("Прокси упал ${CoreProcessController.MAX_RESTARTS} раз — проверьте настройки")
}
}
@@ -1,7 +1,7 @@
package com.freeturn.app.domain
import com.freeturn.app.ProxyServiceState
import com.freeturn.app.data.AppPreferences
import com.freeturn.app.proxy.ProxyServiceState
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withTimeoutOrNull
@@ -1,10 +1,10 @@
package com.freeturn.app.domain
import android.content.Context
import com.freeturn.app.ProxyServiceState
import com.freeturn.app.data.ClientConfig
import com.freeturn.app.data.SplitTunnelMode
import com.freeturn.app.data.TunnelTransport
import com.freeturn.app.proxy.ProxyServiceState
import com.wireguard.android.backend.GoBackend
import com.wireguard.android.backend.Tunnel
import com.wireguard.config.Config
@@ -0,0 +1,379 @@
package com.freeturn.app.proxy
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import com.freeturn.app.R
import com.freeturn.app.data.AppPreferences
import com.freeturn.app.data.CoreArgs
import com.freeturn.app.domain.CaptchaSession
import com.freeturn.app.domain.ConnectionStats
import com.freeturn.app.domain.CoreConnectionTracker
import com.freeturn.app.domain.CoreLogEvent
import com.freeturn.app.domain.CoreLogParser
import com.freeturn.app.domain.StartupResult
import com.freeturn.app.domain.WireGuardTunnelManager
import java.io.BufferedReader
import java.io.File
import java.io.InputStreamReader
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicReference
import kotlin.random.Random
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
/**
* Управляет нативным процессом ядра: запуск, чтение лога, реакция на события
* (капча / quota-error / startup / WireGuard) и watchdog-перезапуск с backoff.
* Живёт внутри [ProxyService]; о необходимости остановить сервис сообщает через
* [onStopRequested] (вместо прямого stopSelf).
*/
class CoreProcessController(
private val context: Context,
private val prefs: AppPreferences,
private val scope: CoroutineScope,
private val notifier: ProxyNotifier,
private val carrierDns: () -> String,
private val onStopRequested: () -> Unit,
) {
companion object {
const val MAX_RESTARTS = 8
// Даём TURN-туннелю «устаканиться» перед поднятием WireGuard поверх него.
private const val WIREGUARD_START_DELAY_MS = 2_000L
}
private val wireGuard = WireGuardTunnelManager(context)
private val handler = Handler(Looper.getMainLooper())
private val process = AtomicReference<Process?>(null)
private val userStopped = AtomicBoolean(false)
private val sessionKillScheduled = AtomicBoolean(false)
private val restartCount = AtomicInteger(0)
val isRunning: Boolean get() = process.get() != null
val isUserStopped: Boolean get() = userStopped.get()
fun start() {
userStopped.set(false)
restartCount.set(0)
scope.launch { startBinaryProcess() }
}
/** Сменилась физическая сеть — рвём процесс, watchdog поднимет на новой сети. */
fun onNetworkHandover() {
if (userStopped.get() || process.get() == null) return
ProxyServiceState.addLog("Смена сети — переподключение")
notifier.setStatus(context.getString(R.string.notif_proxy_network_change))
restartCount.set(0)
process.get()?.destroyCompat()
}
/** onDestroy, шаг 1: помечаем стоп и снимаем отложенные перезапуски/quota-kill. */
fun beginShutdown() {
userStopped.set(true)
handler.removeCallbacksAndMessages(null)
}
/**
* onDestroy, шаг 2: гасим процесс и WG-туннель. Teardown WG — блокирующий JNI/IO,
* держать им поток onDestroy нельзя (ANR); уводим на отдельный поток без ожидания.
*/
fun destroyProcessAndTunnel() {
process.get()?.destroyCompat()
val wg = wireGuard
Thread { runBlocking { wg.stop() } }.start()
}
private suspend fun startBinaryProcess() {
if (userStopped.get()) return
val cfg = prefs.clientConfigFlow.first()
ProxyServiceState.setLogsEnabled(cfg.logsEnabled)
// Obf-обфускация управляется на серверном экране, но должна передаваться и
// клиенту с тем же ключом, иначе DTLS-handshake не сойдётся. Источник истины —
// общий serverOpts.
val srv = prefs.serverOptsFlow.first()
// Имя ядра версионируется (libfreeturn-<ver>-android-arm64.so) и меняется между
// релизами — не хардкодим. Ищем в nativeLibraryDir libfreeturn*.so (Android
// извлекает туда только lib*.so). При нескольких версиях берём лексикографически
// старшую.
val libDir = File(context.applicationInfo.nativeLibraryDir)
val executable = libDir.listFiles { f ->
f.name.startsWith("libfreeturn") && f.name.endsWith(".so")
}?.maxByOrNull { it.name }?.absolutePath
if (executable == null) {
ProxyServiceState.addLog(
"Ядро libfreeturn*.so не найдено в ${libDir.path}. " +
"Положите бинарник в jniLibs/arm64-v8a/ (имя начинается с lib и оканчивается на .so)."
)
ProxyServiceState.setStartupResult(StartupResult.Failed("core binary not found"))
ProxyServiceState.setRunning(false)
onStopRequested()
return
}
val cmdArgs = mutableListOf<String>()
if (cfg.isRawMode) {
val parts = cfg.rawCommand.trim().split("\\s+".toRegex()).filter { it.isNotEmpty() }
cmdArgs.add(executable)
cmdArgs.addAll(parts.drop(1))
} else {
cmdArgs.add(executable)
// argv строит общий с UI билдер ([CoreArgs.client]) — показанная команда не
// расходится с реально запускаемой. DNS оператора резолвим здесь (зависит от
// активной сети) и передаём в билдер.
val carrierDnsValue = if (cfg.useCarrierDns) carrierDns() else null
cmdArgs.addAll(CoreArgs.client(cfg, srv, carrierDnsValue, prefs.ownClientId()))
}
var exitCode = -1
val startedAt = System.currentTimeMillis()
var startupEmitted = false
var startupFailed = false
var wireGuardStarted = false
var captchaSessionCounter = 0L
// --- Трекинг активных соединений для индикации состояния в UI. ---
// UDP-релей (-mode udp): каждый поток логирует свой [STREAM N] Established/Closed
// парой (defer Closed ставится ДО логирования Established, см. client/main.go).
// Для UDP-релея целевое число потоков известно из конфига (-n). Если threads == 0,
// ядро запускает один поток, считаем total = 1.
val tracker = CoreConnectionTracker(
udpTotal = if (cfg.isRawMode) 0 else if (cfg.threads > 0) cfg.threads else 1,
tcpMode = cfg.tcpForward
)
fun publishStats() {
ProxyServiceState.setConnectionStats(ConnectionStats(tracker.active, tracker.total))
notifier.refreshStats()
}
// Сброс на старте сессии (в том числе на watchdog-рестарте).
publishStats()
try {
ProxyServiceState.addLog("Команда: ${cmdArgs.joinToString(" ")}")
val proc = withContext(Dispatchers.IO) {
val pb = ProcessBuilder(cmdArgs).redirectErrorStream(true)
// Ядро по умолчанию пишет vk_profile.json в CWD (= /data/app/.../lib/<abi>/),
// а это read-only mount на Android. Перенаправляем в filesDir. См.
// client/profiles.go: profileFilePath() читает $VK_PROFILE_PATH первым.
pb.environment()["VK_PROFILE_PATH"] =
File(context.filesDir, "vk_profile.json").absolutePath
// CWD тоже подменяем на writeable dir — на случай если Go-код пишет
// относительными путями (логи кеша tls-client и т.п.).
pb.directory(context.filesDir)
pb.start()
}
process.set(proc)
BufferedReader(InputStreamReader(proc.inputStream)).use { reader ->
var line: String?
while (true) {
line = try {
reader.readLine()
} catch (e: java.io.IOException) {
// При destroyCompat()/Process.destroy() с другого треда нативный
// pipe закрывается, и блокирующий readLine() бросает IOException
// ("Stream closed" / "read interrupted by close()"). Это нормальный
// путь остановки — выходим из цикла молча.
val msg = e.message.orEmpty()
val benign = userStopped.get() ||
msg.contains("interrupted by close", ignoreCase = true) ||
msg.contains("Stream closed", ignoreCase = true) ||
msg.contains("Bad file descriptor", ignoreCase = true)
if (!benign) {
ProxyServiceState.addLog("Чтение лога ядра прервано: ${e.message}")
}
null
}
if (line == null) break
val l = line
ProxyServiceState.addLog(l)
// Разбор строки — в CoreLogParser (чистая логика, под юнит-тестами);
// здесь только реакция на события.
val events = CoreLogParser.parse(l)
var statsChanged = false
for (event in events) when (event) {
// Детекция URL ручной капчи. Каждый раз выдаём новый sessionId,
// чтобы диалог пересоздавал WebView, даже если URL не поменялся
// (бинарник всегда использует http://localhost:8765).
is CoreLogEvent.CaptchaUrl -> {
captchaSessionCounter += 1
ProxyServiceState.setCaptchaSession(
CaptchaSession(event.url, captchaSessionCounter)
)
notifier.showCaptcha()
}
// Закрываем диалог — следующая капча-сессия откроет его заново
// через новый sessionId.
CoreLogEvent.CaptchaResolved -> {
if (ProxyServiceState.captchaSession.value != null) {
ProxyServiceState.setCaptchaSession(null)
notifier.cancelCaptcha()
}
}
else -> if (tracker.apply(event)) statsChanged = true
}
if (statsChanged) publishStats()
// Startup: ядро упало с panic/fatal/окончательно не смогло получить
// creds ДО первого подключения — считаем запуск неудачным. Первая
// строка без этих маркеров больше не трактуется как Success (ядро
// могло написать "Connecting..." и только потом упасть).
if (!startupEmitted) {
val hasFatal = events.any { it is CoreLogEvent.FatalStartup }
val hasConnection = tracker.hasConnection
when {
hasFatal -> {
ProxyServiceState.setStartupResult(StartupResult.Failed(l))
notifier.setStatus(context.getString(R.string.notif_proxy_connect_error))
startupFailed = true
startupEmitted = true
}
hasConnection -> {
try {
if (cfg.wireGuardActive) {
ProxyServiceState.addLog(
"WireGuard: подъём через ${WIREGUARD_START_DELAY_MS} мс после старта TURN-туннеля"
)
delay(WIREGUARD_START_DELAY_MS)
if (userStopped.get() || process.get() !== proc) {
ProxyServiceState.addLog(
"WireGuard: старт отменён, прокси останавливается"
)
break
}
}
wireGuard.startAfterProxyReady(cfg)
wireGuardStarted = cfg.wireGuardActive
ProxyServiceState.setStartupResult(StartupResult.Success)
ProxyServiceState.markConnectedIfAbsent(SystemClock.elapsedRealtime())
notifier.setStatus(
if (wireGuardStarted) context.getString(R.string.proxy_active_wireguard)
else context.getString(R.string.proxy_active)
)
} catch (e: Exception) {
val message = e.message ?: e.javaClass.simpleName
ProxyServiceState.addLog("WireGuard: ошибка запуска — $message")
ProxyServiceState.setStartupResult(
StartupResult.Failed("WireGuard не запустился: $message")
)
notifier.setStatus(context.getString(R.string.notif_proxy_wireguard_error))
startupFailed = true
proc.destroyCompat()
}
startupEmitted = true
}
}
}
// compareAndSet гарантирует единственный postDelayed даже при параллельных quota-ошибках
if (events.any { it is CoreLogEvent.QuotaError } &&
sessionKillScheduled.compareAndSet(false, true)) {
ProxyServiceState.addLog("Превышена квота — сброс сессии через 2 с")
handler.postDelayed({
sessionKillScheduled.set(false)
if (!userStopped.get()) {
restartCount.set(0)
process.get()?.destroyCompat()
}
}, 2_000)
}
}
}
exitCode = if (withContext(Dispatchers.IO) {
proc.waitForCompat(5, TimeUnit.MINUTES)
}) proc.exitValue() else -1
ProxyServiceState.addLog("Процесс остановлен (код $exitCode)")
if (!startupEmitted) {
ProxyServiceState.setStartupResult(StartupResult.Failed(
"Процесс завершился без вывода (код: $exitCode)"))
}
} catch (e: CancellationException) {
// Остановка из UI отменяет корутину scope → CancellationException ("Job was
// cancelled"). Это штатный путь остановки. Пробрасываем дальше, чтобы не
// ломать семантику отмены; finally ниже обработает userStopped → стоп.
throw e
} catch (e: Exception) {
// Любое исключение во время пользовательской остановки — следствие
// destroy()/закрытия пайпов, а не реальная ошибка. Не шумим в логах.
if (userStopped.get()) {
startupFailed = false
} else {
val msg = e.message ?: ""
if (msg.contains("error=13") || msg.contains("Permission denied")) {
ProxyServiceState.addLog("Ошибка: устройство блокирует запуск файлов из внутреннего хранилища (SELinux/noexec). Используйте встроенное ядро.")
ProxyServiceState.setStartupResult(StartupResult.Failed(msg))
startupFailed = true
} else {
ProxyServiceState.addLog("Ошибка: ${e.message}")
}
}
} finally {
ProxyServiceState.setCaptchaSession(null)
notifier.cancelCaptcha()
// WG-туннель живёт только поверх работающего прокси — гасим вместе с ядром.
if (wireGuardStarted) wireGuard.stop()
// Процесс мёртв — активных соединений нет. При watchdog-рестарте publishStats
// на новом старте снова выставит правильный target.
ProxyServiceState.setConnectionStats(ConnectionStats.IDLE)
process.set(null)
when {
userStopped.get() -> {
ProxyServiceState.setRunning(false)
onStopRequested()
}
startupFailed -> {
ProxyServiceState.addLog("Ошибка при запуске, watchdog не активирован")
ProxyServiceState.setRunning(false)
onStopRequested()
}
exitCode == 0 -> {
val uptime = System.currentTimeMillis() - startedAt
if (uptime < 5_000L) {
ProxyServiceState.addLog("Быстрый выход (${uptime} мс) — проверьте ссылку и настройки")
} else {
ProxyServiceState.addLog("Сессия завершена")
}
ProxyServiceState.setRunning(false)
onStopRequested()
}
else -> scheduleWatchdogRestart()
}
}
}
private fun scheduleWatchdogRestart() {
val count = restartCount.incrementAndGet()
if (count > MAX_RESTARTS) {
ProxyServiceState.addLog("Watchdog: превышен лимит попыток ($MAX_RESTARTS), остановка")
ProxyServiceState.setRunning(false)
ProxyServiceState.emitFailed()
onStopRequested()
return
}
val baseDelay = minOf(1_000L * count, 30_000L)
val jitter = Random.nextLong(0, 500)
val delayMs = baseDelay + jitter
ProxyServiceState.addLog("Watchdog: перезапуск через ${delayMs} мс (попытка $count/$MAX_RESTARTS)")
notifier.setStatus(context.getString(R.string.notif_proxy_reconnecting, count, MAX_RESTARTS))
handler.postDelayed({
if (!userStopped.get()) scope.launch { startBinaryProcess() }
}, delayMs)
}
}
@@ -0,0 +1,146 @@
package com.freeturn.app.proxy
import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import android.os.SystemClock
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
/**
* Следит за сменой ФИЗИЧЕСКОЙ сети (Wi-Fi↔LTE и т.п.) и дёргает [onHandover].
* VPN-интерфейсы отфильтрованы: иначе старт WireGuard выглядел бы как смена сети
* и уводил прокси в бесконечный рестарт.
*/
class NetworkHandoverMonitor(
private val context: Context,
private val scope: CoroutineScope,
private val onHandover: () -> Unit,
) {
companion object {
// Игнорируем сетевые события первые секунды после регистрации — иначе
// initial onAvailable/onCapabilitiesChanged триггерят ложный рестарт.
private const val WARMUP_MS = 3_000L
}
private val cm get() = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
private var callback: ConnectivityManager.NetworkCallback? = null
@Volatile private var debounceJob: Job? = null
@Volatile private var lastKey: String? = null
fun register() {
val cm = cm
val registeredAt = SystemClock.elapsedRealtime()
lastKey = physicalNetworkKey(cm)
fun schedule(reason: String) {
if (SystemClock.elapsedRealtime() - registeredAt < WARMUP_MS) return
debounceJob?.cancel()
debounceJob = scope.launch {
delay(2_000)
val oldKey = lastKey
val newKey = physicalNetworkKey(cm)
// Ключ тот же — ожидаемый no-op. onCapabilitiesChanged сыплет
// десятки раз/мин (сигнал, link speed, валидация инета), не логаем.
if (oldKey == newKey) return@launch
lastKey = newKey
if (newKey == null) {
ProxyServiceState.addLog("Сеть: физическая сеть недоступна ($reason)")
return@launch
}
onHandover()
}
}
val cb = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
val caps = cm.getNetworkCapabilities(network)
if (caps == null || caps.hasTransport(NetworkCapabilities.TRANSPORT_VPN) ||
!caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN)) {
ProxyServiceState.addLog("Сеть: VPN-событие проигнорировано")
return
}
schedule("available")
}
override fun onLost(network: Network) {
schedule("lost")
}
override fun onCapabilitiesChanged(
network: Network,
networkCapabilities: NetworkCapabilities
) {
if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN) ||
!networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN)) {
return
}
schedule("capabilities")
}
}
callback = cb
val request = NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN)
.build()
cm.registerNetworkCallback(request, cb)
}
fun unregister() {
callback?.let { cb ->
try {
cm.unregisterNetworkCallback(cb)
} catch (_: Exception) {}
}
callback = null
}
/**
* DNS активной сети (оператор/Wi-Fi) для флага `-dns-servers` ядра.
* Пусто, если сеть недоступна или у linkProperties нет DNS (норма на эмуляторе).
*/
fun activeDnsServers(): String = try {
val net = cm.activeNetwork ?: return ""
val lp = cm.getLinkProperties(net) ?: return ""
lp.dnsServers
.mapNotNull { it.hostAddress }
.filter { it.isNotBlank() }
.joinToString(",")
} catch (_: Exception) {
""
}
/**
* Ключ ОДНОЙ приоритетной физсети (транспорт + iface). Берём приоритетную, а не
* весь allNetworks: при активном Wi-Fi cellular флапает в фоне, набор прыгал бы →
* ложная «смена сети». link-адреса не в ключе — ротация IPv6/DHCP идёт на той же
* сети; реальный хендовер меняет транспорт/iface.
*/
private fun physicalNetworkKey(cm: ConnectivityManager): String? {
// allNetworks deprecated с API 31, но это единственный синхронный способ снять
// полный снимок текущих сетей внутри колбэка. Подавляем осознанно.
@Suppress("DEPRECATION")
return cm.allNetworks.mapNotNull { network ->
val caps = cm.getNetworkCapabilities(network) ?: return@mapNotNull null
if (caps.hasTransport(NetworkCapabilities.TRANSPORT_VPN) ||
!caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) ||
!caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN)) {
return@mapNotNull null
}
val (priority, transport) = when {
caps.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> 0 to "ethernet"
caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> 1 to "wifi"
caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> 2 to "cellular"
caps.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH) -> 3 to "bluetooth"
else -> return@mapNotNull null
}
val iface = cm.getLinkProperties(network)?.interfaceName.orEmpty()
// tie-break по iface — детерминированный выбор при равном приоритете.
Triple(priority, iface, "$transport|$iface")
}.minWithOrNull(compareBy({ it.first }, { it.second }))?.third
}
}
@@ -0,0 +1,17 @@
package com.freeturn.app.proxy
import android.os.Build
import java.util.concurrent.TimeUnit
internal fun Process.destroyCompat() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) destroyForcibly() else destroy()
}
internal fun Process.waitForCompat(timeout: Long, unit: TimeUnit): Boolean {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) return waitFor(timeout, unit)
val deadline = System.currentTimeMillis() + unit.toMillis(timeout)
while (System.currentTimeMillis() < deadline) {
try { exitValue(); return true } catch (_: IllegalThreadStateException) { Thread.sleep(100) }
}
return try { exitValue(); true } catch (_: IllegalThreadStateException) { false }
}
@@ -0,0 +1,7 @@
package com.freeturn.app.proxy
/** Action-строки управления [ProxyService] через [ProxyReceiver] (тайл/нотификация). */
object ProxyActions {
const val START = "com.freeturn.app.START_PROXY"
const val STOP = "com.freeturn.app.STOP_PROXY"
}
@@ -0,0 +1,145 @@
package com.freeturn.app.proxy
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import com.freeturn.app.R
import java.util.Locale
/**
* Нотификации прокси-сервиса: foreground-статус (+скорость/число потоков) и
* отдельный алерт ручной капчи. Статус и скорость держит внутри, перерисовывает
* сам. Скорость/счётчик дописываются только когда статус == «активно» (без WG).
*/
class ProxyNotifier(private val service: Service) {
companion object {
const val NOTIF_ID_FG = 1
private const val NOTIF_ID_CAPTCHA = 2
private const val CHANNEL_PROXY = "ProxyChannel"
private const val CHANNEL_CAPTCHA = "CaptchaChannel"
}
private val openAppIntent: PendingIntent? by lazy {
service.packageManager.getLaunchIntentForPackage(service.packageName)?.let {
PendingIntent.getActivity(service, 0, it, PendingIntent.FLAG_IMMUTABLE)
}
}
private var baseStatus = ""
private var speedText = ""
private var captchaActive = false
private val isActive get() = baseStatus == service.getString(R.string.proxy_active)
fun createChannels() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
val nm = service.getSystemService(NotificationManager::class.java)
nm.createNotificationChannel(
NotificationChannel(
CHANNEL_PROXY,
service.getString(R.string.notif_channel_proxy),
NotificationManager.IMPORTANCE_LOW
)
)
nm.createNotificationChannel(
NotificationChannel(
CHANNEL_CAPTCHA,
service.getString(R.string.notif_channel_captcha),
NotificationManager.IMPORTANCE_HIGH
)
)
}
/** Базовый статус «Подключение…» для самого первого startForeground. */
fun prepareConnecting() {
baseStatus = service.getString(R.string.notif_proxy_connecting)
}
fun setStatus(text: String) {
baseStatus = text
show()
}
fun setSpeed(text: String) {
speedText = text
if (isActive) show()
}
/** Перерисовать (обновился счётчик потоков) — только если статус активен. */
fun refreshStats() {
if (isActive) show()
}
fun build(): Notification {
var text = baseStatus
val stats = ProxyServiceState.connectionStats.value
if (isActive) {
if (stats.total > 0) {
text = String.format(
Locale.US,
service.getString(R.string.notif_proxy_status_format),
stats.active,
stats.total,
speedText
)
} else if (speedText.isNotEmpty()) {
text += " • $speedText"
}
}
val stopIntent = Intent(service, ProxyReceiver::class.java).apply {
action = ProxyActions.STOP
}
val stopPending = PendingIntent.getBroadcast(
service, 0, stopIntent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
)
return NotificationCompat.Builder(service, CHANNEL_PROXY)
.setContentTitle(service.getString(R.string.notif_proxy_title))
.setContentText(text)
.setSmallIcon(android.R.drawable.ic_menu_preferences)
.setOngoing(true)
.setContentIntent(openAppIntent)
.addAction(0, service.getString(R.string.notif_proxy_stop_action), stopPending)
.build()
}
private fun show() {
try {
NotificationManagerCompat.from(service).notify(NOTIF_ID_FG, build())
} catch (_: SecurityException) {}
}
/** Показ алерта капчи. Дедуп: пока предыдущий не закрыт — повторно не шумим. */
fun showCaptcha() {
if (captchaActive) return
captchaActive = true
val notification = NotificationCompat.Builder(service, CHANNEL_CAPTCHA)
.setContentTitle(service.getString(R.string.notif_captcha_title))
.setContentText(service.getString(R.string.notif_captcha_text))
.setSmallIcon(R.drawable.ic_notification_captcha)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_REMINDER)
.setAutoCancel(true)
.setContentIntent(openAppIntent)
.build()
try {
NotificationManagerCompat.from(service).notify(NOTIF_ID_CAPTCHA, notification)
} catch (_: SecurityException) {
// POST_NOTIFICATIONS отозван на API 33+ — молча игнорируем, диалог в UI
// всё равно откроется через captchaSession StateFlow.
}
}
fun cancelCaptcha() {
NotificationManagerCompat.from(service).cancel(NOTIF_ID_CAPTCHA)
captchaActive = false
}
}
@@ -1,4 +1,4 @@
package com.freeturn.app
package com.freeturn.app.proxy
import android.content.BroadcastReceiver
import android.content.Context
@@ -9,7 +9,7 @@ class ProxyReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
when (intent.action) {
"com.freeturn.app.START_PROXY" -> {
ProxyActions.START -> {
ProxyServiceState.clearLogs()
ProxyServiceState.setStartupResult(null)
val serviceIntent = Intent(context, ProxyService::class.java)
@@ -19,7 +19,7 @@ class ProxyReceiver : BroadcastReceiver() {
context.startService(serviceIntent)
}
}
"com.freeturn.app.STOP_PROXY" -> {
ProxyActions.STOP -> {
val serviceIntent = Intent(context, ProxyService::class.java)
context.stopService(serviceIntent)
}
@@ -0,0 +1,121 @@
package com.freeturn.app.proxy
import android.app.Service
import android.content.Intent
import android.content.pm.ServiceInfo
import android.os.Build
import android.os.IBinder
import android.os.PowerManager
import androidx.core.app.ServiceCompat
import com.freeturn.app.data.AppPreferences
import com.freeturn.app.domain.ConnectionStats
import com.freeturn.app.domain.StartupResult
import java.util.concurrent.TimeUnit
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import org.koin.android.ext.android.inject
/**
* Foreground-сервис локального прокси (FGS-тип specialUse). Тонкий shell: держит
* lifecycle, wakelock и foreground-нотификацию, делегируя процесс/watchdog
* [CoreProcessController], нотификации [ProxyNotifier], хендовер сети
* [NetworkHandoverMonitor], скорость [SpeedMonitor].
*/
class ProxyService : Service() {
private var wakeLock: PowerManager.WakeLock? = null
private lateinit var serviceScope: CoroutineScope
private lateinit var notifier: ProxyNotifier
private lateinit var networkMonitor: NetworkHandoverMonitor
private lateinit var controller: CoreProcessController
private lateinit var speedMonitor: SpeedMonitor
private val prefs: AppPreferences by inject()
override fun onBind(intent: Intent?): IBinder? = null
override fun onCreate() {
super.onCreate()
serviceScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
notifier = ProxyNotifier(this)
notifier.createChannels()
networkMonitor = NetworkHandoverMonitor(applicationContext, serviceScope) {
controller.onNetworkHandover()
}
controller = CoreProcessController(
context = applicationContext,
prefs = prefs,
scope = serviceScope,
notifier = notifier,
carrierDns = { networkMonitor.activeDnsServers() },
onStopRequested = { stopSelf() },
)
speedMonitor = SpeedMonitor(
scope = serviceScope,
isStopped = { controller.isUserStopped },
onSpeed = { notifier.setSpeed(it) },
)
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
// ВАЖНО: startForeground вызываем ПЕРВЫМ делом и БЕЗУСЛОВНО — любой return до
// него даёт ForegroundServiceDidNotStartInTimeException через ~5с.
notifier.prepareConnecting()
// Явно передаём FGS-тип (specialUse доступен с API 34; ниже — без типа).
// try/catch: ForegroundServiceStartNotAllowedException (API 31+ при старте из
// фона) и InvalidForegroundServiceTypeException не должны ронять процесс.
val fgsType = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE else 0
try {
ServiceCompat.startForeground(this, ProxyNotifier.NOTIF_ID_FG, notifier.build(), fgsType)
} catch (e: Exception) {
ProxyServiceState.addLog("Не удалось запустить foreground-сервис: ${e.message}")
ProxyServiceState.setStartupResult(StartupResult.Failed(e.message ?: "FGS start failed"))
ProxyServiceState.setRunning(false)
stopSelf()
return START_NOT_STICKY
}
// Процесс ядра ещё жив — это повторный onStartCommand (sticky-рестарт). Второй
// процесс не плодим, требование startForeground выше уже выполнено.
if (controller.isRunning) {
ProxyServiceState.setRunning(true)
return START_STICKY
}
ProxyServiceState.setRunning(true)
acquireWakeLock()
networkMonitor.register()
ProxyServiceState.addLog("Запуск прокси")
speedMonitor.start()
controller.start()
return START_STICKY
}
private fun acquireWakeLock() {
val powerManager = getSystemService(POWER_SERVICE) as PowerManager
// Освобождаем предыдущий wakelock перед созданием нового — иначе при повторном
// onStartCommand с уже мёртвым процессом старый объект висит held до GC (утечка).
if (wakeLock?.isHeld == true) wakeLock?.release()
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "VkTurn::BgLock")
wakeLock?.acquire(TimeUnit.HOURS.toMillis(24))
}
override fun onDestroy() {
super.onDestroy()
controller.beginShutdown()
ProxyServiceState.setRunning(false)
ProxyServiceState.setConnectionStats(ConnectionStats.IDLE)
ProxyServiceState.clearConnectedSince()
networkMonitor.unregister()
notifier.cancelCaptcha()
ProxyServiceState.addLog("Остановка")
controller.destroyProcessAndTunnel()
serviceScope.cancel()
if (wakeLock?.isHeld == true) wakeLock?.release()
}
}
@@ -1,5 +1,8 @@
package com.freeturn.app
package com.freeturn.app.proxy
import com.freeturn.app.domain.CaptchaSession
import com.freeturn.app.domain.ConnectionStats
import com.freeturn.app.domain.StartupResult
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
@@ -8,24 +11,6 @@ import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
/**
* Сессия ручной капчи. sessionId позволяет диалогу различать соседние
* капча-сессии с одинаковым URL и пересоздавать WebView через `key(sessionId)`.
*/
data class CaptchaSession(val url: String, val sessionId: Long)
/**
* Агрегированная статистика подключений прокси-ядра.
*
* - [active] — число реально живых каналов (DTLS-потоков для udp-релея, smux-сессий для tcp-режима).
* - [total] — целевое число каналов. 0 означает «ещё неизвестно» (tcp-режим до первой waiting-строки).
*/
data class ConnectionStats(val active: Int, val total: Int) {
companion object {
val IDLE = ConnectionStats(0, 0)
}
}
/**
* Централизованное состояние прокси-сервиса.
* Публичный API — только read-only Flow, мутация через явные методы.
@@ -1,8 +1,9 @@
package com.freeturn.app
package com.freeturn.app.proxy
import android.content.Intent
import android.service.quicksettings.Tile
import android.service.quicksettings.TileService
import com.freeturn.app.R
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
@@ -34,12 +35,12 @@ class ProxyTileService : TileService() {
super.onClick()
if (isProxyRunning) {
val intent = Intent(this, ProxyReceiver::class.java).apply {
action = "com.freeturn.app.STOP_PROXY"
action = ProxyActions.STOP
}
sendBroadcast(intent)
} else {
val intent = Intent(this, ProxyReceiver::class.java).apply {
action = "com.freeturn.app.START_PROXY"
action = ProxyActions.START
}
sendBroadcast(intent)
}
@@ -0,0 +1,49 @@
package com.freeturn.app.proxy
import android.net.TrafficStats
import android.os.Process
import java.util.Locale
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
/**
* Опрашивает TrafficStats по UID раз в 3с и отдаёт строку «↓ rx ↑ tx» в [onSpeed].
* Цикл живёт пока [isStopped] не вернёт true (или scope не отменят).
*/
class SpeedMonitor(
private val scope: CoroutineScope,
private val isStopped: () -> Boolean,
private val onSpeed: (String) -> Unit,
) {
private var job: Job? = null
fun start() {
job?.cancel()
job = scope.launch {
val uid = Process.myUid()
var lastRx = TrafficStats.getUidRxBytes(uid)
var lastTx = TrafficStats.getUidTxBytes(uid)
while (!isStopped()) {
delay(3000)
val currentRx = TrafficStats.getUidRxBytes(uid)
val currentTx = TrafficStats.getUidTxBytes(uid)
if (currentRx != TrafficStats.UNSUPPORTED.toLong() &&
lastRx != TrafficStats.UNSUPPORTED.toLong()) {
val rxSpeed = maxOf(0, currentRx - lastRx)
val txSpeed = maxOf(0, currentTx - lastTx)
onSpeed("↓ ${format(rxSpeed)} ↑ ${format(txSpeed)}")
lastRx = currentRx
lastTx = currentTx
}
}
}
}
private fun format(bytes: Long): String = when {
bytes < 1024 -> "$bytes B/s"
bytes < 1024 * 1024 -> "${bytes / 1024} KB/s"
else -> String.format(Locale.US, "%.1f MB/s", bytes / (1024f * 1024f))
}
}
@@ -128,22 +128,27 @@ fun LogsScreen(proxyViewModel: ProxyViewModel) {
@Composable
private fun LogLine(line: String) {
val lower = line.lowercase()
val isHeader = line.startsWith("===")
val isError = lower.contains("ошибка") || lower.contains("error") ||
lower.contains("критическая") || lower.contains("failed") ||
lower.contains("fatal") || lower.contains("panic")
lower.contains("fatal") || lower.contains("panic") ||
lower.contains("не удалось")
val isWarning = lower.contains("watchdog") || lower.contains("перезапуск") ||
lower.contains("переподключение") || lower.contains("квота") ||
lower.contains("quota") || lower.contains("warn") ||
lower.contains(">>>")
lower.contains("недоступна")
val isSuccess = lower.contains("запущен") || lower.contains("подключен") ||
lower.contains("success") || lower.contains("started") ||
lower.contains("ok")
lower.contains("established")
// Ключевые события сессии — выделяем акцентом (прежде маркировались "===").
val isEvent = lower.contains("запуск прокси") || lower.contains("остановка") ||
lower.contains("процесс остановлен") || lower.contains("сессия завершена") ||
lower.contains("быстрый выход") || lower.startsWith("сеть:")
val textColor = when {
isError -> MaterialTheme.colorScheme.error
isWarning -> MaterialTheme.extendedColorScheme.warning
isSuccess -> MaterialTheme.extendedColorScheme.success
isHeader -> MaterialTheme.colorScheme.primary
isEvent -> MaterialTheme.colorScheme.primary
else -> MaterialTheme.colorScheme.onSurfaceVariant
}
Row(
@@ -152,7 +157,7 @@ private fun LogLine(line: String) {
.padding(horizontal = Spacing.lg, vertical = Spacing.xs),
verticalAlignment = Alignment.Top
) {
if (isHeader || isError || isWarning || isSuccess) {
if (isEvent || isError || isWarning || isSuccess) {
Box(
modifier = Modifier
.padding(top = Spacing.xs, end = Spacing.sm)
@@ -166,7 +171,7 @@ private fun LogLine(line: String) {
text = line,
style = MaterialTheme.typography.bodySmall.copy(
fontFamily = FontFamily.Monospace,
fontWeight = if (isHeader) FontWeight.SemiBold else FontWeight.Normal
fontWeight = if (isEvent) FontWeight.SemiBold else FontWeight.Normal
),
color = textColor
)
@@ -2,10 +2,10 @@ package com.freeturn.app.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.freeturn.app.ProxyServiceState
import com.freeturn.app.data.AppPreferences
import com.freeturn.app.domain.LocalProxyManager
import com.freeturn.app.domain.ProxyState
import com.freeturn.app.proxy.ProxyServiceState
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
@@ -4,8 +4,6 @@ import android.content.Context
import android.content.Intent
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.freeturn.app.ProxyService
import com.freeturn.app.ProxyServiceState
import com.freeturn.app.data.AppPreferences
import com.freeturn.app.data.ClientConfig
import com.freeturn.app.data.ObfProfile
@@ -16,6 +14,8 @@ import com.freeturn.app.domain.LocalProxyManager
import com.freeturn.app.domain.ProxyOrchestrator
import com.freeturn.app.domain.SshRepository
import com.freeturn.app.domain.UpdateState
import com.freeturn.app.proxy.ProxyService
import com.freeturn.app.proxy.ProxyServiceState
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.delay
+4
View File
@@ -315,6 +315,10 @@
<string name="notif_channel_captcha">Капча</string>
<string name="notif_captcha_title">Требуется прохождение капчи</string>
<string name="notif_captcha_text">Откройте приложение для проверки</string>
<string name="notif_proxy_connect_error">Ошибка подключения</string>
<string name="notif_proxy_wireguard_error">Ошибка WireGuard</string>
<string name="notif_proxy_network_change">Смена сети, переподключение…</string>
<string name="notif_proxy_reconnecting">Переподключение (%1$d/%2$d)…</string>
<!-- CaptchaWebViewDialog -->
<string name="captcha_title">Проверка VK</string>