feat(tcp): вернуть настройку bond
This commit is contained in:
1 parent
e747be0807
commit
6e8cbc952f
14 files changed
+94
-8
No files matched your search
@@ -7,6 +7,7 @@ data class ClientConfig(
|
||||
val threads: Int = DEFAULT_THREADS,
|
||||
val streamsPerCred: Int = DEFAULT_STREAMS_PER_CRED,
|
||||
val useUdp: Boolean = false,
|
||||
val bond: Boolean = false,
|
||||
val manualCaptcha: Boolean = false,
|
||||
val localPort: String = DEFAULT_LOCAL_PORT,
|
||||
val debugMode: Boolean = false,
|
||||
|
||||
@@ -32,7 +32,7 @@ data class CoreConfigJson(
|
||||
data class Turn(val n: Int, val transport: String, val host: String, val port: String)
|
||||
|
||||
@Serializable
|
||||
data class Proxy(val mode: String, val listen: String)
|
||||
data class Proxy(val mode: String, val listen: String, val bond: Boolean? = null)
|
||||
|
||||
@Serializable
|
||||
data class Kcp(
|
||||
@@ -67,8 +67,7 @@ data class CoreConfigJson(
|
||||
data class Tunnel(val mode: String, val config: String, val mtu: Int)
|
||||
|
||||
companion object {
|
||||
// Все поля явно: пропущенное ядро молча заменит своим дефолтом. Исключение -
|
||||
// kcp: null не сериализуется, и дефолты ARQ остаются за ядром.
|
||||
// null в kcp/bond опускается ради дефолтов ядра и совместимости со старыми AAR.
|
||||
private val json = Json { encodeDefaults = true; explicitNulls = false }
|
||||
|
||||
const val TRANSPORT_TCP = "tcp"
|
||||
@@ -140,6 +139,8 @@ fun ClientConfig.toCoreJson(
|
||||
// В туннельном режиме порт не биндится (ядро берёт in-memory pipe),
|
||||
// но валидацию проходит и нужен прокси-режиму.
|
||||
listen = localPort,
|
||||
// Выключенный bond не отправляем: старые AAR отвергают незнакомые поля.
|
||||
bond = if (tcpMode && bond) true else null,
|
||||
),
|
||||
relay = CoreConfigJson.Relay(
|
||||
links = listOf(callLink),
|
||||
|
||||
@@ -61,6 +61,7 @@ internal object ServerJson {
|
||||
put("threads", p.client.threads)
|
||||
put("streamsPerCred", p.client.streamsPerCred)
|
||||
put("useUdp", p.client.useUdp)
|
||||
put("bond", p.client.bond)
|
||||
put("manualCaptcha", p.client.manualCaptcha)
|
||||
put("localPort", p.client.localPort)
|
||||
put("debugMode", p.client.debugMode)
|
||||
@@ -120,6 +121,7 @@ internal object ServerJson {
|
||||
threads = cliO.optInt("threads", ClientConfig.DEFAULT_THREADS),
|
||||
streamsPerCred = cliO.optInt("streamsPerCred", ClientConfig.DEFAULT_STREAMS_PER_CRED),
|
||||
useUdp = cliO.optBoolean("useUdp", false),
|
||||
bond = cliO.optBoolean("bond", false),
|
||||
manualCaptcha = cliO.optBoolean("manualCaptcha", false),
|
||||
localPort = cliO.optString("localPort", ClientConfig.DEFAULT_LOCAL_PORT),
|
||||
debugMode = cliO.optBoolean("debugMode", false),
|
||||
|
||||
@@ -13,6 +13,7 @@ data class FreeturnLink(
|
||||
val peer: String,
|
||||
val transport: String = "",
|
||||
val mode: String = "",
|
||||
val bond: Boolean = false,
|
||||
val obfProfile: String = "",
|
||||
val obfKey: String = "",
|
||||
val obfTimingMs: Int = 0,
|
||||
@@ -37,6 +38,7 @@ data class FreeturnLink(
|
||||
sb.field("peer", jsonString(peer))
|
||||
if (transport.isNotEmpty()) sb.field("transport", jsonString(transport))
|
||||
if (mode.isNotEmpty()) sb.field("mode", jsonString(mode))
|
||||
if (bond) sb.field("bond", "true")
|
||||
if (obfProfile.isNotEmpty() && obfProfile != "none") {
|
||||
sb.field("obf", jsonString(obfProfile))
|
||||
sb.field("key", jsonString(obfKey))
|
||||
@@ -82,6 +84,7 @@ data class FreeturnLink(
|
||||
peer = peer,
|
||||
transport = o.optString("transport"),
|
||||
mode = o.optString("mode"),
|
||||
bond = o.optBoolean("bond", false),
|
||||
obfProfile = o.optString("obf"),
|
||||
obfKey = o.optString("key"),
|
||||
obfTimingMs = o.optInt("timing", 0),
|
||||
|
||||
@@ -28,6 +28,7 @@ object ShareLinkBuilder {
|
||||
peer = server.client.serverAddress,
|
||||
transport = if (server.client.useUdp) "udp" else "",
|
||||
mode = if (tcpMode) ProxyMode.TCP else "",
|
||||
bond = tcpMode && server.client.bond && wgConf.isNullOrBlank(),
|
||||
// Профиль ARQ сервер не репортит: отдаём тот, что владелец ему и выставил.
|
||||
kcp = server.opts.kcp.takeIf { tcpMode && it != KcpProfile.DEFAULT },
|
||||
obfProfile = if (ObfProfile.isValidKey(obfKey)) obfProfile else "",
|
||||
|
||||
+13
-2
@@ -61,6 +61,7 @@ import com.freeturn.app.ui.components.SettingsCard
|
||||
import com.freeturn.app.ui.components.SettingsContentMaxWidth
|
||||
import com.freeturn.app.ui.components.SettingsEntryRow
|
||||
import com.freeturn.app.ui.components.SettingsFieldSlot
|
||||
import com.freeturn.app.ui.components.SettingsSwitchRow
|
||||
import com.freeturn.app.ui.components.UdpTcpSegmented
|
||||
import com.freeturn.app.ui.screens.splittunnel.SplitTunnelModal
|
||||
import com.freeturn.app.ui.theme.Spacing
|
||||
@@ -109,7 +110,8 @@ fun ConnectionModeScreen(
|
||||
// Проброс и ARQ - черновики: рестарт пары клиент+сервер идёт по "Применить".
|
||||
var isTcp by remember(fieldsKey, savedOpts.proxyMode) { mutableStateOf(savedOpts.tcpMode) }
|
||||
var kcpDraft by remember(fieldsKey, savedOpts.kcp) { mutableStateOf(savedOpts.kcp) }
|
||||
val forwardDirty = isTcp != savedOpts.tcpMode || kcpDraft != savedOpts.kcp
|
||||
var bondDraft by remember(fieldsKey, saved.bond) { mutableStateOf(saved.bond) }
|
||||
val forwardDirty = isTcp != savedOpts.tcpMode || kcpDraft != savedOpts.kcp || bondDraft != saved.bond
|
||||
val forwardVisible = !isVpn && forwardDirty
|
||||
val applyBlocked = if (isTcp && !kcpDraft.valid) stringResource(R.string.apply_blocked_arq) else null
|
||||
|
||||
@@ -118,7 +120,8 @@ fun ConnectionModeScreen(
|
||||
serverConfigViewModel.applyForwardConfig(
|
||||
serverId,
|
||||
if (isTcp) ProxyMode.TCP else ProxyMode.UDP,
|
||||
kcpDraft
|
||||
kcpDraft,
|
||||
bondDraft
|
||||
)
|
||||
onBack?.invoke()
|
||||
}
|
||||
@@ -263,6 +266,14 @@ fun ConnectionModeScreen(
|
||||
}
|
||||
|
||||
if (isTcp) {
|
||||
SettingsCard {
|
||||
SettingsSwitchRow(
|
||||
title = stringResource(R.string.bond_title),
|
||||
subtitle = stringResource(R.string.bond_desc),
|
||||
checked = bondDraft,
|
||||
onCheckedChange = { bondDraft = it }
|
||||
)
|
||||
}
|
||||
KcpCard(profile = kcpDraft, onProfile = { kcpDraft = it })
|
||||
}
|
||||
} else {
|
||||
|
||||
@@ -133,9 +133,23 @@ class ServerConfigViewModel(
|
||||
|
||||
fun setProxyMode(id: String?, mode: String) = updateOpts(id) { it.copy(proxyMode = mode) }
|
||||
|
||||
/** Режим и ARQ одной транзакцией: рестарт пары идёт один раз на "Применить". */
|
||||
fun applyForwardConfig(id: String?, mode: String, kcp: KcpProfile) =
|
||||
updateOpts(id) { it.copy(proxyMode = mode, kcp = kcp) }
|
||||
/** Bond меняет только клиент; режим и ARQ требуют синхронизации сервера. */
|
||||
fun applyForwardConfig(id: String?, mode: String, kcp: KcpProfile, bond: Boolean) {
|
||||
viewModelScope.launch {
|
||||
var serverChanged = false
|
||||
val transform: (Server) -> Server = {
|
||||
val opts = it.opts.copy(proxyMode = mode, kcp = kcp)
|
||||
serverChanged = opts != it.opts
|
||||
it.copy(opts = opts, client = it.client.copy(bond = bond))
|
||||
}
|
||||
val changed = if (id == null) prefs.updateActiveServer(transform)
|
||||
else prefs.updateServer(id, transform)
|
||||
if (!changed) return@launch
|
||||
if (id != null && id != prefs.serversSnapshot.first().activeId) return@launch
|
||||
if (serverChanged) orchestrator.scheduleSync()
|
||||
else orchestrator.restartProxyIfRunning()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Режим и ARQ обязаны совпадать с сервером, поэтому правка активного сервера
|
||||
|
||||
@@ -124,6 +124,7 @@ class ImportViewModel(
|
||||
// стартовал бы с конфигом, который отвергнет ядро или сервер.
|
||||
private fun requireUsable(link: FreeturnLink) {
|
||||
require(link.provider in Provider.VALUES) { "unknown provider" }
|
||||
require(!link.bond || (link.mode == ProxyMode.TCP && link.wgConf.isBlank())) { "bond requires TCP proxy" }
|
||||
if (link.obfProfile.isBlank() || link.obfProfile == ObfProfile.NONE) return
|
||||
require(link.obfProfile in ObfProfile.VALUES) { "unknown obf profile" }
|
||||
require(ObfProfile.isValidKey(link.obfKey)) { "bad obf key" }
|
||||
@@ -139,6 +140,7 @@ class ImportViewModel(
|
||||
callLink = st.callLink.trim(),
|
||||
provider = link.provider,
|
||||
useUdp = link.transport == "udp",
|
||||
bond = link.bond,
|
||||
threads = link.n.takeIf { it > 0 } ?: ClientConfig.DEFAULT_THREADS,
|
||||
streamsPerCred = link.streamsPerCred.takeIf { it > 0 }
|
||||
?: ClientConfig.DEFAULT_STREAMS_PER_CRED,
|
||||
|
||||
@@ -471,6 +471,8 @@
|
||||
<string name="mode_proxy_desc">Traffic goes through a local proxy, without a tunnel.</string>
|
||||
<string name="mode_vpn_desc">All device traffic is tunneled through WireGuard.</string>
|
||||
<string name="forward_section">Forwarding</string>
|
||||
<string name="bond_title">Combine channels (bond)</string>
|
||||
<string name="bond_desc">Use several channels for one TCP connection. Requires a server with bond support. If a channel fails, Xray will need to reconnect.</string>
|
||||
<string name="forward_udp_desc">UDP relay: the local port accepts WireGuard/AmneziaWG traffic.</string>
|
||||
<string name="forward_tcp_desc">TCP forwarder: the local port is used by Xray or sing-box, no own tunnel is brought up.</string>
|
||||
<string name="forward_tcp_foreign_vpn">If another app holds the VPN on the device, exclude FreeTurn from its tunnel - otherwise traffic will loop.</string>
|
||||
|
||||
@@ -502,6 +502,8 @@
|
||||
<string name="mode_proxy_desc">Трафик идёт через локальный прокси, без туннеля.</string>
|
||||
<string name="mode_vpn_desc">Весь трафик устройства туннелируется через WireGuard.</string>
|
||||
<string name="forward_section">Проброс</string>
|
||||
<string name="bond_title">Объединять каналы (bond)</string>
|
||||
<string name="bond_desc">Одно TCP-соединение использует несколько каналов. Нужен сервер с поддержкой bond. При обрыве канала Xray потребуется переподключиться.</string>
|
||||
<string name="forward_udp_desc">UDP-релей: локальный порт принимает трафик WireGuard/AmneziaWG.</string>
|
||||
<string name="forward_tcp_desc">TCP-форвардер: локальный порт слушает Xray или sing-box, свой туннель не поднимается.</string>
|
||||
<string name="forward_tcp_foreign_vpn">Если VPN на устройстве держит другое приложение, исключите FreeTurn из его туннеля - иначе трафик зациклится.</string>
|
||||
|
||||
@@ -15,6 +15,21 @@ import org.junit.Test
|
||||
*/
|
||||
class CoreConfigJsonTest {
|
||||
|
||||
@Test
|
||||
fun bondIsSentOnlyWhenEnabledForTcpProxy() {
|
||||
val client = ClientConfig(bond = true)
|
||||
val tcp = ServerOpts(proxyMode = ProxyMode.TCP)
|
||||
val proxy = parse(client, tcp)["proxy"]!!.jsonObject
|
||||
assertEquals("true", proxy["bond"]!!.jsonPrimitive.content)
|
||||
assertFalse(parse(client)["proxy"]!!.jsonObject.containsKey("bond"))
|
||||
assertFalse(parse(client.copy(bond = false), tcp)["proxy"]!!.jsonObject.containsKey("bond"))
|
||||
val wg = client.copy(
|
||||
tunnelTransport = TunnelTransport.WIREGUARD,
|
||||
wireGuardConfig = "[Interface]\nAddress = 10.8.0.2/32\n"
|
||||
)
|
||||
assertFalse(parse(wg, tcp)["proxy"]!!.jsonObject.containsKey("bond"))
|
||||
}
|
||||
|
||||
private val base = ClientConfig(
|
||||
serverAddress = "1.2.3.4:56000",
|
||||
callLink = "https://call.example/x",
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.freeturn.app.data.server
|
||||
|
||||
import com.freeturn.app.data.config.ClientConfig
|
||||
import com.freeturn.app.data.config.KcpProfile
|
||||
import com.freeturn.app.data.config.ObfProfile
|
||||
import com.freeturn.app.data.config.ProxyMode
|
||||
@@ -9,6 +10,14 @@ import org.junit.Test
|
||||
|
||||
class ServerJsonTest {
|
||||
|
||||
@Test
|
||||
fun `bond persists and old profiles keep it disabled`() {
|
||||
val server = Server(name = "bond", client = ClientConfig(bond = true))
|
||||
val decoded = ServerJson.decodeList(ServerJson.encodeList(listOf(server))).single()
|
||||
assertEquals(true, decoded.client.bond)
|
||||
assertEquals(false, ServerJson.decodeList("""[{"id":"old","client":{}}]""").single().client.bond)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `opts round trip keeps mode and arq`() {
|
||||
val srv = Server(
|
||||
|
||||
@@ -9,6 +9,15 @@ import java.util.Base64
|
||||
|
||||
class FreeturnLinkTest {
|
||||
|
||||
@Test
|
||||
fun `bond round trip matches Go wire fields`() {
|
||||
val link = FreeturnLink(provider = "vk", peer = "1.2.3.4:56000", mode = "tcp", bond = true)
|
||||
val json = String(Base64.getUrlDecoder().decode(link.encode().removePrefix("freeturn://")), Charsets.UTF_8)
|
||||
assertEquals("""{"v":1,"provider":"vk","peer":"1.2.3.4:56000","mode":"tcp","bond":true}""", json)
|
||||
assertEquals(link, FreeturnLink.parse(link.encode()).getOrThrow())
|
||||
assertFalse(FreeturnLink.parse(goldenMinimal).getOrThrow().bond)
|
||||
}
|
||||
|
||||
/** Ссылка из docs/uri.md Go-репо: {"v":1,"provider":"vk","peer":"1.2.3.4:56000"}. */
|
||||
private val goldenMinimal = "freeturn://eyJ2IjoxLCJwcm92aWRlciI6InZrIiwicGVlciI6IjEuMi4zLjQ6NTYwMDAifQ"
|
||||
|
||||
|
||||
@@ -10,6 +10,20 @@ import org.junit.Test
|
||||
|
||||
class ShareLinkBuilderTest {
|
||||
|
||||
@Test
|
||||
fun `bond is shared only for TCP without a WG config`() {
|
||||
val srv = Server(
|
||||
name = "bond",
|
||||
client = ClientConfig(serverAddress = "1.2.3.4:56000", bond = true),
|
||||
opts = ServerOpts(proxyMode = ProxyMode.TCP)
|
||||
)
|
||||
fun shared(server: Server, wg: String? = null) =
|
||||
FreeturnLink.parse(ShareLinkBuilder.build(server, ShareInfo(), "guest", wg)).getOrThrow()
|
||||
assertEquals(true, shared(srv).bond)
|
||||
assertEquals(false, shared(srv.copy(opts = ServerOpts())).bond)
|
||||
assertEquals(false, shared(srv, "[Interface]\nAddress=10.8.0.2/32").bond)
|
||||
}
|
||||
|
||||
private val key = "ab".repeat(32)
|
||||
|
||||
private fun server(
|
||||
|
||||
Reference in new issue
Block a user