fix(proxy): сохранять ручной DNS при смене сети и чинить SOCKS5-раздачу
Хендовер подменял ручной список DNS оператора. SOCKS5: свой пул потоков, закрытие соединений на stop, таймаут рукопожатия, запрет loopback-целей.
This commit is contained in:
1 parent
8691c7685b
commit
88dc0d1038
4 files changed
+76
-35
No files matched your search
@@ -111,12 +111,7 @@ fun ClientConfig.toCoreJson(
|
|||||||
carrierDns: String? = null,
|
carrierDns: String? = null,
|
||||||
ownClientId: String = "",
|
ownClientId: String = "",
|
||||||
): String {
|
): String {
|
||||||
val manualDns = DnsList.normalize(customDns)
|
val dnsServers = coreDnsServers { carrierDns }
|
||||||
val dnsServers = when {
|
|
||||||
manualDns.isNotBlank() -> manualDns.split(",")
|
|
||||||
useCarrierDns -> carrierDns?.split(",").orEmpty()
|
|
||||||
else -> emptyList()
|
|
||||||
}.map { it.trim() }.filter { it.isNotEmpty() }
|
|
||||||
|
|
||||||
val obfOn = srv.obfEnabled && ObfProfile.isValidKey(srv.obfKey)
|
val obfOn = srv.obfEnabled && ObfProfile.isValidKey(srv.obfKey)
|
||||||
// Ядро поднимает встроенный туннель только поверх udp; UI тоже гасит выбор tcp.
|
// Ядро поднимает встроенный туннель только поверх udp; UI тоже гасит выбор tcp.
|
||||||
@@ -172,6 +167,15 @@ fun ClientConfig.toCoreJson(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun ClientConfig.coreDnsServers(carrierDns: () -> String?): List<String> {
|
||||||
|
val manualDns = DnsList.normalize(customDns)
|
||||||
|
return when {
|
||||||
|
manualDns.isNotBlank() -> manualDns.split(",")
|
||||||
|
useCarrierDns -> carrierDns()?.split(",").orEmpty()
|
||||||
|
else -> emptyList()
|
||||||
|
}.map { it.trim() }.filter { it.isNotEmpty() }
|
||||||
|
}
|
||||||
|
|
||||||
private fun KcpProfile.toCoreJson() = CoreConfigJson.Kcp(
|
private fun KcpProfile.toCoreJson() = CoreConfigJson.Kcp(
|
||||||
noDelay = noDelay,
|
noDelay = noDelay,
|
||||||
interval = interval,
|
interval = interval,
|
||||||
|
|||||||
@@ -1,13 +1,12 @@
|
|||||||
package com.freeturn.app.domain.proxy
|
package com.freeturn.app.domain.proxy
|
||||||
|
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.Dispatchers
|
|
||||||
import kotlinx.coroutines.Job
|
|
||||||
import kotlinx.coroutines.SupervisorJob
|
import kotlinx.coroutines.SupervisorJob
|
||||||
import kotlinx.coroutines.cancelChildren
|
import kotlinx.coroutines.asCoroutineDispatcher
|
||||||
|
import kotlinx.coroutines.cancel
|
||||||
|
import kotlinx.coroutines.coroutineScope
|
||||||
import kotlinx.coroutines.isActive
|
import kotlinx.coroutines.isActive
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.coroutines.withContext
|
|
||||||
import java.io.EOFException
|
import java.io.EOFException
|
||||||
import java.io.InputStream
|
import java.io.InputStream
|
||||||
import java.io.OutputStream
|
import java.io.OutputStream
|
||||||
@@ -20,6 +19,8 @@ import java.net.Socket
|
|||||||
import java.net.SocketTimeoutException
|
import java.net.SocketTimeoutException
|
||||||
import java.net.UnknownHostException
|
import java.net.UnknownHostException
|
||||||
import java.nio.charset.StandardCharsets
|
import java.nio.charset.StandardCharsets
|
||||||
|
import java.util.concurrent.ConcurrentHashMap
|
||||||
|
import java.util.concurrent.Executors
|
||||||
import kotlin.coroutines.coroutineContext
|
import kotlin.coroutines.coroutineContext
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -32,18 +33,21 @@ import kotlin.coroutines.coroutineContext
|
|||||||
* ([protect]), иначе ответы в локальную сеть уехали бы в туннель.
|
* ([protect]), иначе ответы в локальную сеть уехали бы в туннель.
|
||||||
*
|
*
|
||||||
* Слушает 0.0.0.0 без авторизации: открыт всей локальной сети, не только клиентам
|
* Слушает 0.0.0.0 без авторизации: открыт всей локальной сети, не только клиентам
|
||||||
* точки доступа.
|
* точки доступа. Цели на самом телефоне (loopback) закрыты.
|
||||||
|
*
|
||||||
|
* Одноразовый: после [stop] экземпляр не перезапускается.
|
||||||
*/
|
*/
|
||||||
class Socks5Server(
|
class Socks5Server(
|
||||||
private val protect: (Socket) -> Boolean,
|
private val protect: (Socket) -> Boolean,
|
||||||
private val port: Int = DEFAULT_PORT,
|
private val port: Int = DEFAULT_PORT,
|
||||||
) {
|
) {
|
||||||
private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
|
private val executor = Executors.newCachedThreadPool()
|
||||||
|
private val scope = CoroutineScope(executor.asCoroutineDispatcher() + SupervisorJob())
|
||||||
|
private val sockets = ConcurrentHashMap.newKeySet<Socket>()
|
||||||
|
|
||||||
// Слушающий сокет - под монитором: bind идёт на потоке вызывающего, чтобы
|
// Слушающий сокет - под монитором: bind идёт на потоке вызывающего, чтобы
|
||||||
// BindException был виден ему, а не утонул в корутине.
|
// BindException был виден ему, а не утонул в корутине.
|
||||||
private var serverSocket: ServerSocket? = null
|
@Volatile private var serverSocket: ServerSocket? = null
|
||||||
private var acceptJob: Job? = null
|
|
||||||
|
|
||||||
@Synchronized
|
@Synchronized
|
||||||
fun start() {
|
fun start() {
|
||||||
@@ -55,7 +59,7 @@ class Socks5Server(
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
serverSocket = socket
|
serverSocket = socket
|
||||||
acceptJob = scope.launch { acceptLoop(socket) }
|
scope.launch { acceptLoop(socket) }
|
||||||
ProxyStore.log("SOCKS5: раздача туннеля на $BIND_ADDRESS:$port (только TCP)")
|
ProxyStore.log("SOCKS5: раздача туннеля на $BIND_ADDRESS:$port (только TCP)")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -63,10 +67,11 @@ class Socks5Server(
|
|||||||
fun stop() {
|
fun stop() {
|
||||||
val socket = serverSocket ?: return
|
val socket = serverSocket ?: return
|
||||||
serverSocket = null
|
serverSocket = null
|
||||||
// Сокет закрываем до отмены: accept() блокирующий и на отмену корутины не смотрит.
|
socket.closeQuietly()
|
||||||
try { socket.close() } catch (_: Exception) {}
|
sockets.forEach { it.closeQuietly() }
|
||||||
acceptJob = null
|
sockets.clear()
|
||||||
scope.coroutineContext.cancelChildren()
|
scope.cancel()
|
||||||
|
executor.shutdown()
|
||||||
ProxyStore.log("SOCKS5: раздача остановлена")
|
ProxyStore.log("SOCKS5: раздача остановлена")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -85,44 +90,53 @@ class Socks5Server(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun handleClient(client: Socket) = withContext(Dispatchers.IO) {
|
private suspend fun handleClient(client: Socket) = coroutineScope {
|
||||||
var target: Socket? = null
|
var target: Socket? = null
|
||||||
|
track(client)
|
||||||
try {
|
try {
|
||||||
// Обратный канал - мимо туннеля: приложение теперь внутри tun, и ответы
|
// Обратный канал - мимо туннеля: приложение теперь внутри tun, и ответы
|
||||||
// клиенту в локальную сеть без этого ушли бы в туннель.
|
// клиенту в локальную сеть без этого ушли бы в туннель.
|
||||||
protect(client)
|
protect(client)
|
||||||
|
client.soTimeout = HANDSHAKE_TIMEOUT_MS
|
||||||
|
|
||||||
val input = client.getInputStream()
|
val input = client.getInputStream()
|
||||||
val output = client.getOutputStream()
|
val output = client.getOutputStream()
|
||||||
|
|
||||||
if (!negotiate(input, output)) return@withContext
|
if (!negotiate(input, output)) return@coroutineScope
|
||||||
|
|
||||||
if (input.readByte() != VERSION) return@withContext
|
if (input.readByte() != VERSION) return@coroutineScope
|
||||||
val command = input.readByte()
|
val command = input.readByte()
|
||||||
input.readByte() // RSV
|
input.readByte() // RSV
|
||||||
val addressType = input.readByte()
|
val addressType = input.readByte()
|
||||||
|
|
||||||
if (command != CMD_CONNECT) {
|
if (command != CMD_CONNECT) {
|
||||||
sendReply(output, REPLY_COMMAND_NOT_SUPPORTED)
|
sendReply(output, REPLY_COMMAND_NOT_SUPPORTED)
|
||||||
return@withContext
|
return@coroutineScope
|
||||||
}
|
}
|
||||||
// Длину неизвестного типа адреса не угадать - дочитать до порта нечем,
|
// Длину неизвестного типа адреса не угадать - дочитать до порта нечем,
|
||||||
// поэтому соединение после ответа закрывается.
|
// поэтому соединение после ответа закрывается.
|
||||||
val host = readHost(input, addressType) ?: run {
|
val host = readHost(input, addressType) ?: run {
|
||||||
sendReply(output, REPLY_ADDRESS_TYPE_NOT_SUPPORTED)
|
sendReply(output, REPLY_ADDRESS_TYPE_NOT_SUPPORTED)
|
||||||
return@withContext
|
return@coroutineScope
|
||||||
|
}
|
||||||
|
val address = InetSocketAddress(host, readPort(input))
|
||||||
|
val ip = address.address
|
||||||
|
if (ip != null && (ip.isLoopbackAddress || ip.isAnyLocalAddress)) {
|
||||||
|
sendReply(output, REPLY_NOT_ALLOWED)
|
||||||
|
return@coroutineScope
|
||||||
}
|
}
|
||||||
val targetPort = readPort(input)
|
|
||||||
|
|
||||||
val socket = Socket()
|
val socket = Socket()
|
||||||
target = socket
|
target = socket
|
||||||
|
track(socket)
|
||||||
try {
|
try {
|
||||||
socket.connect(InetSocketAddress(host, targetPort), CONNECT_TIMEOUT_MS)
|
socket.connect(address, CONNECT_TIMEOUT_MS)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
sendReply(output, replyFor(e))
|
sendReply(output, replyFor(e))
|
||||||
return@withContext
|
return@coroutineScope
|
||||||
}
|
}
|
||||||
sendReply(output, REPLY_SUCCESS)
|
sendReply(output, REPLY_SUCCESS)
|
||||||
|
client.soTimeout = 0
|
||||||
|
|
||||||
val upstream = launch { pipe(input, socket.getOutputStream(), socket) }
|
val upstream = launch { pipe(input, socket.getOutputStream(), socket) }
|
||||||
val downstream = launch { pipe(socket.getInputStream(), output, client) }
|
val downstream = launch { pipe(socket.getInputStream(), output, client) }
|
||||||
@@ -131,11 +145,18 @@ class Socks5Server(
|
|||||||
} catch (_: EOFException) {
|
} catch (_: EOFException) {
|
||||||
} catch (_: Exception) {
|
} catch (_: Exception) {
|
||||||
} finally {
|
} finally {
|
||||||
try { client.close() } catch (_: Exception) {}
|
client.closeQuietly()
|
||||||
try { target?.close() } catch (_: Exception) {}
|
target?.closeQuietly()
|
||||||
|
sockets.remove(client)
|
||||||
|
target?.let(sockets::remove)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun track(socket: Socket) {
|
||||||
|
sockets.add(socket)
|
||||||
|
if (serverSocket == null) socket.closeQuietly()
|
||||||
|
}
|
||||||
|
|
||||||
/** false - клиент не предложил "без авторизации" либо поздоровался не по протоколу. */
|
/** false - клиент не предложил "без авторизации" либо поздоровался не по протоколу. */
|
||||||
private fun negotiate(input: InputStream, output: OutputStream): Boolean {
|
private fun negotiate(input: InputStream, output: OutputStream): Boolean {
|
||||||
if (input.readByte() != VERSION) return false
|
if (input.readByte() != VERSION) return false
|
||||||
@@ -185,11 +206,7 @@ class Socks5Server(
|
|||||||
* встречная сторона держала бы соединение открытым, а обе `join` не возвращались бы
|
* встречная сторона держала бы соединение открытым, а обе `join` не возвращались бы
|
||||||
* до таймаута где-то в сети.
|
* до таймаута где-то в сети.
|
||||||
*/
|
*/
|
||||||
private suspend fun pipe(
|
private fun pipe(source: InputStream, destination: OutputStream, sink: Socket) {
|
||||||
source: InputStream,
|
|
||||||
destination: OutputStream,
|
|
||||||
sink: Socket,
|
|
||||||
) = withContext(Dispatchers.IO) {
|
|
||||||
val buffer = ByteArray(BUFFER_SIZE)
|
val buffer = ByteArray(BUFFER_SIZE)
|
||||||
try {
|
try {
|
||||||
while (true) {
|
while (true) {
|
||||||
@@ -211,6 +228,7 @@ class Socks5Server(
|
|||||||
private const val BACKLOG = 50
|
private const val BACKLOG = 50
|
||||||
private const val BUFFER_SIZE = 8192
|
private const val BUFFER_SIZE = 8192
|
||||||
private const val CONNECT_TIMEOUT_MS = 10_000
|
private const val CONNECT_TIMEOUT_MS = 10_000
|
||||||
|
private const val HANDSHAKE_TIMEOUT_MS = 15_000
|
||||||
|
|
||||||
private const val VERSION = 5
|
private const val VERSION = 5
|
||||||
private const val METHOD_NO_AUTH = 0x00
|
private const val METHOD_NO_AUTH = 0x00
|
||||||
@@ -222,6 +240,7 @@ class Socks5Server(
|
|||||||
|
|
||||||
private const val REPLY_SUCCESS = 0x00
|
private const val REPLY_SUCCESS = 0x00
|
||||||
private const val REPLY_GENERAL_FAILURE = 0x01
|
private const val REPLY_GENERAL_FAILURE = 0x01
|
||||||
|
private const val REPLY_NOT_ALLOWED = 0x02
|
||||||
private const val REPLY_HOST_UNREACHABLE = 0x04
|
private const val REPLY_HOST_UNREACHABLE = 0x04
|
||||||
private const val REPLY_CONNECTION_REFUSED = 0x05
|
private const val REPLY_CONNECTION_REFUSED = 0x05
|
||||||
private const val REPLY_COMMAND_NOT_SUPPORTED = 0x07
|
private const val REPLY_COMMAND_NOT_SUPPORTED = 0x07
|
||||||
@@ -229,6 +248,14 @@ class Socks5Server(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun Socket.closeQuietly() {
|
||||||
|
try { close() } catch (_: Exception) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun ServerSocket.closeQuietly() {
|
||||||
|
try { close() } catch (_: Exception) {}
|
||||||
|
}
|
||||||
|
|
||||||
private fun InputStream.readByte(): Int = read().also { if (it == -1) throw EOFException() }
|
private fun InputStream.readByte(): Int = read().also { if (it == -1) throw EOFException() }
|
||||||
|
|
||||||
private fun InputStream.readExactly(count: Int): ByteArray {
|
private fun InputStream.readExactly(count: Int): ByteArray {
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import com.freeturn.app.R
|
|||||||
import com.freeturn.app.data.AppPreferences
|
import com.freeturn.app.data.AppPreferences
|
||||||
import com.freeturn.app.data.CoreCommand
|
import com.freeturn.app.data.CoreCommand
|
||||||
import com.freeturn.app.data.config.ClientConfig
|
import com.freeturn.app.data.config.ClientConfig
|
||||||
|
import com.freeturn.app.data.config.coreDnsServers
|
||||||
import com.freeturn.app.data.config.toCoreJson
|
import com.freeturn.app.data.config.toCoreJson
|
||||||
import com.freeturn.app.domain.proxy.LogLevel
|
import com.freeturn.app.domain.proxy.LogLevel
|
||||||
import com.freeturn.app.domain.proxy.ProxyEngine
|
import com.freeturn.app.domain.proxy.ProxyEngine
|
||||||
@@ -304,7 +305,7 @@ class ProxyService : VpnService() {
|
|||||||
ProxyStore.log("Смена сети - переподключение (сон с прошлой проверки $slept c)")
|
ProxyStore.log("Смена сети - переподключение (сон с прошлой проверки $slept c)")
|
||||||
scope.launch {
|
scope.launch {
|
||||||
val cfg = prefs.clientConfigFlow.first()
|
val cfg = prefs.clientConfigFlow.first()
|
||||||
engine.reconnect(if (cfg.useCarrierDns) network.physicalDnsServers() else "")
|
engine.reconnect(cfg.coreDnsServers { network.physicalDnsServers() }.joinToString(","))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -148,6 +148,15 @@ class CoreConfigJsonTest {
|
|||||||
assertEquals("[]", off["dns"]!!.jsonObject["servers"].toString())
|
assertEquals("[]", off["dns"]!!.jsonObject["servers"].toString())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun handoverDnsKeepsManualList() {
|
||||||
|
val manual = base.copy(useCarrierDns = true, customDns = "1.1.1.1")
|
||||||
|
assertEquals(listOf("1.1.1.1"), manual.coreDnsServers { error("carrier queried") })
|
||||||
|
|
||||||
|
val carrier = base.copy(useCarrierDns = true)
|
||||||
|
assertEquals(listOf("10.0.0.1", "10.0.0.2"), carrier.coreDnsServers { "10.0.0.1, 10.0.0.2" })
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun obfNeedsValidKey() {
|
fun obfNeedsValidKey() {
|
||||||
val srv = ServerOpts(obfProfile = ObfProfile.RTPOPUS, obfKey = "short")
|
val srv = ServerOpts(obfProfile = ObfProfile.RTPOPUS, obfKey = "short")
|
||||||
|
|||||||
Reference in new issue
Block a user