feat(wireguard): настраиваемый MTU туннеля
This commit is contained in:
1 parent
755602f90f
commit
a49a61ddec
11 files changed
+129
-8
No files matched your search
@@ -40,6 +40,8 @@ data class ClientConfig(
|
||||
val wireGuardConfig: String = "",
|
||||
/** Имя WG-туннеля для GoBackend. */
|
||||
val wireGuardTunnelName: String = TunnelTransport.DEFAULT_TUNNEL_NAME,
|
||||
/** MTU WG-интерфейса. Инжектится в [Interface] при подъёме (в сыром conf не хранится). */
|
||||
val wireGuardMtu: Int = DEFAULT_WG_MTU,
|
||||
/** Режим split-tunneling: all | include | exclude. */
|
||||
val splitTunnelMode: String = SplitTunnelMode.ALL,
|
||||
/** Список package-имён для include/exclude (разделители: запятая/пробел/перенос строки). */
|
||||
@@ -56,5 +58,10 @@ data class ClientConfig(
|
||||
companion object {
|
||||
const val DEFAULT_LOCAL_PORT = "127.0.0.1:9000"
|
||||
const val DEFAULT_STREAMS_PER_CRED = 6
|
||||
// TURN-релей добавляет overhead - 1280 (минимум IPv6) против фрагментации.
|
||||
const val DEFAULT_WG_MTU = 1280
|
||||
// Диапазон валидного MTU: 1280 = минимум IPv6, 1500 = потолок Ethernet.
|
||||
const val MIN_WG_MTU = 1280
|
||||
const val MAX_WG_MTU = 1500
|
||||
}
|
||||
}
|
||||
@@ -67,6 +67,7 @@ internal object ServerJson {
|
||||
put("tunnelTransport", p.client.tunnelTransport)
|
||||
put("wireGuardConfig", p.client.wireGuardConfig)
|
||||
put("wireGuardTunnelName", p.client.wireGuardTunnelName)
|
||||
put("wireGuardMtu", p.client.wireGuardMtu)
|
||||
put("splitTunnelMode", p.client.splitTunnelMode)
|
||||
put("splitTunnelApps", p.client.splitTunnelApps)
|
||||
put("logsEnabled", p.client.logsEnabled)
|
||||
@@ -130,6 +131,7 @@ internal object ServerJson {
|
||||
},
|
||||
wireGuardConfig = cliO.optString("wireGuardConfig"),
|
||||
wireGuardTunnelName = cliO.optString("wireGuardTunnelName").ifBlank { TunnelTransport.DEFAULT_TUNNEL_NAME },
|
||||
wireGuardMtu = cliO.optInt("wireGuardMtu", ClientConfig.DEFAULT_WG_MTU),
|
||||
splitTunnelMode = cliO.optString("splitTunnelMode", SplitTunnelMode.ALL).let {
|
||||
if (it in SplitTunnelMode.VALUES) it else SplitTunnelMode.ALL
|
||||
},
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.freeturn.app.data.share
|
||||
|
||||
import com.freeturn.app.data.config.ClientConfig
|
||||
import org.json.JSONObject
|
||||
import java.util.Base64
|
||||
|
||||
@@ -23,7 +24,8 @@ data class FreeturnLink(
|
||||
val dnsServers: String = "",
|
||||
val manualCaptcha: Boolean = false,
|
||||
val name: String = "",
|
||||
val wgConf: String = ""
|
||||
val wgConf: String = "",
|
||||
val mtu: Int = ClientConfig.DEFAULT_WG_MTU
|
||||
) {
|
||||
fun encode(): String {
|
||||
val sb = StringBuilder("{")
|
||||
@@ -45,6 +47,7 @@ data class FreeturnLink(
|
||||
if (dnsServers.isNotEmpty()) sb.field("dnss", jsonString(dnsServers))
|
||||
if (manualCaptcha) sb.field("mcap", "true")
|
||||
if (name.isNotEmpty()) sb.field("name", jsonString(name))
|
||||
if (mtu != ClientConfig.DEFAULT_WG_MTU) sb.field("mtu", mtu.toString())
|
||||
if (wgConf.isNotEmpty()) sb.field("wg", jsonString(wgConf))
|
||||
sb.append('}')
|
||||
return SCHEME + Base64.getUrlEncoder().withoutPadding()
|
||||
@@ -86,7 +89,8 @@ data class FreeturnLink(
|
||||
dnsServers = o.optString("dnss"),
|
||||
manualCaptcha = o.optBoolean("mcap", false),
|
||||
name = o.optString("name"),
|
||||
wgConf = o.optString("wg")
|
||||
wgConf = o.optString("wg"),
|
||||
mtu = o.optInt("mtu", ClientConfig.DEFAULT_WG_MTU)
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -29,14 +29,21 @@ object ShareLinkBuilder {
|
||||
obfKey = if (ObfProfile.isValidKey(obfKey)) obfKey else "",
|
||||
clientId = clientId.trim(),
|
||||
name = userName.trim(),
|
||||
wgConf = wgConf?.let(::normalizeConf).orEmpty()
|
||||
wgConf = wgConf?.let(::normalizeConf).orEmpty(),
|
||||
mtu = server.client.wireGuardMtu
|
||||
).encode()
|
||||
}
|
||||
|
||||
/** Срезает комментарии и пустые строки WG-conf - короче ссылка, плотнее QR. */
|
||||
/**
|
||||
* Срезает комментарии, пустые строки и MTU из WG-conf - короче ссылка, плотнее QR.
|
||||
* MTU едет отдельным полем ссылки (единственный источник), в conf не дублируется.
|
||||
*/
|
||||
internal fun normalizeConf(conf: String): String =
|
||||
conf.lineSequence()
|
||||
.map { it.trim() }
|
||||
.filter { it.isNotEmpty() && !it.startsWith("#") && !it.startsWith(";") }
|
||||
.filter {
|
||||
it.isNotEmpty() && !it.startsWith("#") && !it.startsWith(";") &&
|
||||
!(it.startsWith("MTU", ignoreCase = true) && it.contains("="))
|
||||
}
|
||||
.joinToString("\n")
|
||||
}
|
||||
@@ -38,6 +38,7 @@ class WireGuardTunnelManager(context: Context) {
|
||||
val endpoint = cfg.localPort.trim()
|
||||
val preparedConfig = rawConfig
|
||||
.withLocalEndpoint(endpoint)
|
||||
.withMtu(cfg.wireGuardMtu)
|
||||
.withSplitTunnel(
|
||||
appPackage = appContext.packageName,
|
||||
mode = cfg.splitTunnelMode,
|
||||
@@ -108,6 +109,27 @@ private fun String.withLocalEndpoint(endpoint: String): String {
|
||||
return lines.joinToString("\n")
|
||||
}
|
||||
|
||||
private fun String.withMtu(mtu: Int): String {
|
||||
if (mtu <= 0) return this
|
||||
var inInterface = false
|
||||
val lines = mutableListOf<String>()
|
||||
lineSequence().forEach { line ->
|
||||
val section = line.trim()
|
||||
if (section.startsWith("[") && section.endsWith("]")) {
|
||||
inInterface = section.equals("[Interface]", ignoreCase = true)
|
||||
}
|
||||
val isMtuLine = inInterface && section.startsWith("MTU", ignoreCase = true) &&
|
||||
section.contains("=")
|
||||
if (!isMtuLine) lines += line
|
||||
}
|
||||
val interfaceIndex = lines.indexOfFirst {
|
||||
it.trim().equals("[Interface]", ignoreCase = true)
|
||||
}
|
||||
if (interfaceIndex < 0) return lines.joinToString("\n")
|
||||
lines.add(interfaceIndex + 1, "MTU = $mtu")
|
||||
return lines.joinToString("\n")
|
||||
}
|
||||
|
||||
private fun String.withSplitTunnel(
|
||||
appPackage: String,
|
||||
mode: String,
|
||||
|
||||
+30
-2
@@ -99,6 +99,7 @@ fun ConnectionModeScreen(
|
||||
|
||||
var wgConfig by remember(saved.wireGuardConfig) { mutableStateOf(saved.wireGuardConfig) }
|
||||
var wgName by remember(saved.wireGuardTunnelName) { mutableStateOf(saved.wireGuardTunnelName) }
|
||||
var wgMtu by remember(saved.wireGuardMtu) { mutableStateOf(saved.wireGuardMtu.toString()) }
|
||||
|
||||
// Запись WG-настроек: транспорт всегда выставляется вместе с конфигом.
|
||||
fun persistWg(vpn: Boolean = isVpn) {
|
||||
@@ -106,7 +107,10 @@ fun ConnectionModeScreen(
|
||||
it.copy(
|
||||
tunnelTransport = if (vpn) TunnelTransport.WIREGUARD else TunnelTransport.NONE,
|
||||
wireGuardConfig = wgConfig.trim(),
|
||||
wireGuardTunnelName = wgName.trim().ifBlank { TunnelTransport.DEFAULT_TUNNEL_NAME }
|
||||
wireGuardTunnelName = wgName.trim().ifBlank { TunnelTransport.DEFAULT_TUNNEL_NAME },
|
||||
wireGuardMtu = wgMtu.toIntOrNull()
|
||||
?.coerceIn(ClientConfig.MIN_WG_MTU, ClientConfig.MAX_WG_MTU)
|
||||
?: ClientConfig.DEFAULT_WG_MTU
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -118,10 +122,15 @@ fun ConnectionModeScreen(
|
||||
// Дебаунс 600 мс для WG-полей.
|
||||
var wgDirty by remember(serverId) { mutableStateOf(false) }
|
||||
var pendingSave by remember(serverId) { mutableStateOf(false) }
|
||||
LaunchedEffect(wgConfig, wgName) {
|
||||
LaunchedEffect(wgConfig, wgName, wgMtu) {
|
||||
if (!wgDirty) { wgDirty = true; return@LaunchedEffect }
|
||||
pendingSave = true
|
||||
delay(600)
|
||||
// Пустой/вне диапазона MTU подтягиваем в поле к валидному - UI = сохранённое.
|
||||
val normalizedMtu = wgMtu.toIntOrNull()
|
||||
?.coerceIn(ClientConfig.MIN_WG_MTU, ClientConfig.MAX_WG_MTU)
|
||||
?: ClientConfig.DEFAULT_WG_MTU
|
||||
if (wgMtu != normalizedMtu.toString()) wgMtu = normalizedMtu.toString()
|
||||
persistWg()
|
||||
pendingSave = false
|
||||
}
|
||||
@@ -140,6 +149,8 @@ fun ConnectionModeScreen(
|
||||
}
|
||||
if (!text.isNullOrBlank()) {
|
||||
wgConfig = text
|
||||
// Префилл поля MTU из загруженного conf - поле = единственный источник.
|
||||
extractMtu(text)?.let { wgMtu = it.toString() }
|
||||
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
|
||||
}
|
||||
}
|
||||
@@ -216,6 +227,8 @@ fun ConnectionModeScreen(
|
||||
onWgConfig = { wgConfig = it },
|
||||
wgName = wgName,
|
||||
onWgName = { wgName = it },
|
||||
mtu = wgMtu,
|
||||
onMtu = { wgMtu = it },
|
||||
privacyMode = privacyMode,
|
||||
onLoadFile = { filePicker.launch("*/*") }
|
||||
)
|
||||
@@ -252,3 +265,18 @@ fun ConnectionModeScreen(
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Достаёт MTU из строки `[Interface]` загруженного conf; null - нет валидной строки. */
|
||||
private fun extractMtu(conf: String): Int? {
|
||||
var inInterface = false
|
||||
conf.lineSequence().forEach { line ->
|
||||
val section = line.trim()
|
||||
if (section.startsWith("[") && section.endsWith("]")) {
|
||||
inInterface = section.equals("[Interface]", ignoreCase = true)
|
||||
} else if (inInterface && section.startsWith("MTU", ignoreCase = true) &&
|
||||
section.contains("=")) {
|
||||
return section.substringAfter("=").trim().toIntOrNull()?.takeIf { it > 0 }
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -5,9 +5,11 @@ import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.freeturn.app.R
|
||||
import com.freeturn.app.ui.components.SectionLabel
|
||||
@@ -25,6 +27,8 @@ internal fun WireGuardConfigCard(
|
||||
onWgConfig: (String) -> Unit,
|
||||
wgName: String,
|
||||
onWgName: (String) -> Unit,
|
||||
mtu: String,
|
||||
onMtu: (String) -> Unit,
|
||||
privacyMode: Boolean,
|
||||
onLoadFile: () -> Unit
|
||||
) {
|
||||
@@ -62,6 +66,15 @@ internal fun WireGuardConfigCard(
|
||||
singleLine = true,
|
||||
readOnly = privacyMode
|
||||
)
|
||||
OutlinedTextField(
|
||||
value = mtu,
|
||||
onValueChange = { v -> onMtu(v.filter { it.isDigit() }) },
|
||||
label = { Text(stringResource(R.string.wireguard_mtu)) },
|
||||
supportingText = { Text(stringResource(R.string.wireguard_mtu_hint)) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -142,6 +142,7 @@ class ImportViewModel(
|
||||
tunnelTransport = if (wgConf.isNotEmpty()) TunnelTransport.WIREGUARD
|
||||
else TunnelTransport.NONE,
|
||||
wireGuardConfig = wgConf,
|
||||
wireGuardMtu = link.mtu,
|
||||
// cid из ссылки - владелец уже посадил его в allowlist сервера.
|
||||
clientId = link.clientId.trim()
|
||||
),
|
||||
|
||||
@@ -341,6 +341,8 @@
|
||||
|
||||
<!-- Туннельное приложение (WireGuard) -->
|
||||
<string name="wireguard_tunnel_name">Имя туннеля</string>
|
||||
<string name="wireguard_mtu">MTU</string>
|
||||
<string name="wireguard_mtu_hint">1280-1500</string>
|
||||
|
||||
<!-- Split tunneling -->
|
||||
<string name="split_tunnel_title">Раздельное туннелирование</string>
|
||||
|
||||
@@ -75,6 +75,21 @@ class FreeturnLinkTest {
|
||||
assertEquals(original, FreeturnLink.parse(original.encode()).getOrThrow())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `mtu round trips when non default`() {
|
||||
val original = FreeturnLink(provider = "vk", peer = "1.2.3.4:56000", mtu = 1400)
|
||||
assertEquals(1400, FreeturnLink.parse(original.encode()).getOrThrow().mtu)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `mtu omitted from json when default`() {
|
||||
val link = FreeturnLink(provider = "vk", peer = "1.2.3.4:56000")
|
||||
val payload = link.encode().removePrefix(FreeturnLink.SCHEME)
|
||||
val json = String(Base64.getUrlDecoder().decode(payload), Charsets.UTF_8)
|
||||
assertFalse(json.contains("mtu"))
|
||||
assertEquals(1280, FreeturnLink.parse(link.encode()).getOrThrow().mtu)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `obf none is omitted entirely`() {
|
||||
val link = FreeturnLink(provider = "vk", peer = "1.2.3.4:56000", obfProfile = "none", obfKey = "ff".repeat(32))
|
||||
|
||||
@@ -15,6 +15,7 @@ class ShareLinkBuilderTest {
|
||||
tcpForward: Boolean = false,
|
||||
bond: Boolean = false,
|
||||
useUdp: Boolean = false,
|
||||
mtu: Int = ClientConfig.DEFAULT_WG_MTU,
|
||||
opts: ServerOpts = ServerOpts()
|
||||
) = Server(
|
||||
name = "Мой сервер",
|
||||
@@ -22,7 +23,8 @@ class ShareLinkBuilderTest {
|
||||
serverAddress = "1.2.3.4:56000",
|
||||
tcpForward = tcpForward,
|
||||
bond = bond,
|
||||
useUdp = useUdp
|
||||
useUdp = useUdp,
|
||||
wireGuardMtu = mtu
|
||||
),
|
||||
opts = opts
|
||||
)
|
||||
@@ -66,6 +68,24 @@ class ShareLinkBuilderTest {
|
||||
assertEquals("[Interface]\nPrivateKey = abc=\n[Peer]\nPublicKey = def=", link.wgConf)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `mtu carried from client config`() {
|
||||
val link = FreeturnLink.parse(
|
||||
ShareLinkBuilder.build(server(mtu = 1380), ShareInfo(wgBackend = true), "u", null)
|
||||
).getOrThrow()
|
||||
assertEquals(1380, link.mtu)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `mtu line stripped from conf, field is source`() {
|
||||
val conf = "[Interface]\nPrivateKey = abc=\nMTU = 1500\n[Peer]\nPublicKey = def="
|
||||
val link = FreeturnLink.parse(
|
||||
ShareLinkBuilder.build(server(mtu = 1320), ShareInfo(wgBackend = true), "u", conf)
|
||||
).getOrThrow()
|
||||
assertEquals("[Interface]\nPrivateKey = abc=\n[Peer]\nPublicKey = def=", link.wgConf)
|
||||
assertEquals(1320, link.mtu)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `proxy share has no wg field`() {
|
||||
val raw = ShareLinkBuilder.build(server(), ShareInfo(mode = "tcp"), "u", null)
|
||||
|
||||
Reference in new issue
Block a user