fix(proxy): сериализовать подъём/остановку WG и откатывать туннель при провале

This commit is contained in:
samosvalishe committed 2026-06-14 11:40:15 +03:00
1 parent ede1a4cac6
commit 393f74125a
1 file changed
+17 -3
@@ -10,6 +10,8 @@ import com.wireguard.config.Config
import java.io.ByteArrayInputStream import java.io.ByteArrayInputStream
import java.nio.charset.StandardCharsets import java.nio.charset.StandardCharsets
import java.util.concurrent.atomic.AtomicReference import java.util.concurrent.atomic.AtomicReference
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
/** /**
* Поднимает WireGuard-туннель поверх локального прокси. * Поднимает WireGuard-туннель поверх локального прокси.
@@ -20,6 +22,8 @@ class WireGuardTunnelManager(context: Context) {
private val appContext = context.applicationContext private val appContext = context.applicationContext
private val backend by lazy { GoBackend(appContext) } private val backend by lazy { GoBackend(appContext) }
private val tunnelRef = AtomicReference<NamedTunnel?>(null) private val tunnelRef = AtomicReference<NamedTunnel?>(null)
// Без сериализации stop во время старта оставлял туннель поднятым (no-op до tunnelRef.set).
private val mutex = Mutex()
/** Поднять туннель после того как прокси-ядро установило соединение. No-op без WG-конфига. */ /** Поднять туннель после того как прокси-ядро установило соединение. No-op без WG-конфига. */
suspend fun startAfterProxyReady(cfg: ClientConfig) { suspend fun startAfterProxyReady(cfg: ClientConfig) {
@@ -43,14 +47,24 @@ class WireGuardTunnelManager(context: Context) {
ByteArrayInputStream(preparedConfig.toByteArray(StandardCharsets.UTF_8)) ByteArrayInputStream(preparedConfig.toByteArray(StandardCharsets.UTF_8))
) )
stop() mutex.withLock {
stopLocked()
val tunnel = NamedTunnel(name) val tunnel = NamedTunnel(name)
backend.setState(tunnel, Tunnel.State.UP, config) // Ссылка ДО setState: при провале откат/stop опустит частично поднятый туннель.
tunnelRef.set(tunnel) tunnelRef.set(tunnel)
try {
backend.setState(tunnel, Tunnel.State.UP, config)
} catch (e: Exception) {
stopLocked()
throw e
}
ProxyServiceState.addLog("WireGuard: туннель $name поднят через $endpoint") ProxyServiceState.addLog("WireGuard: туннель $name поднят через $endpoint")
} }
}
fun stop() { suspend fun stop() = mutex.withLock { stopLocked() }
private fun stopLocked() {
val tunnel = tunnelRef.getAndSet(null) ?: return val tunnel = tunnelRef.getAndSet(null) ?: return
try { try {
backend.setState(tunnel, Tunnel.State.DOWN, null) backend.setState(tunnel, Tunnel.State.DOWN, null)