feat(proxy): режим проброса tcp с настраиваемым ARQ
This commit is contained in:
1 parent
29dc9a1999
commit
e7425a5ab8
39 files changed
+1013
-59
No files matched your search
@@ -23,13 +23,27 @@ data class CoreConfigJson(
|
|||||||
val obf: Obf,
|
val obf: Obf,
|
||||||
val dns: Dns,
|
val dns: Dns,
|
||||||
val log: Log,
|
val log: Log,
|
||||||
|
/** Только для `proxy.mode = tcp`: в udp ядро отвергает любое отличие от своего дефолта. */
|
||||||
|
val kcp: Kcp? = null,
|
||||||
val tunnel: Tunnel,
|
val tunnel: Tunnel,
|
||||||
) {
|
) {
|
||||||
@Serializable
|
@Serializable
|
||||||
data class Turn(val n: Int, val transport: String, val host: String, val port: String)
|
data class Turn(val n: Int, val transport: String, val host: String, val port: String)
|
||||||
|
|
||||||
@Serializable
|
@Serializable
|
||||||
data class Proxy(val listen: String)
|
data class Proxy(val mode: String, val listen: String)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class Kcp(
|
||||||
|
val noDelay: Int,
|
||||||
|
val interval: Int,
|
||||||
|
val resend: Int,
|
||||||
|
val nc: Int,
|
||||||
|
val sndWnd: Int,
|
||||||
|
val rcvWnd: Int,
|
||||||
|
val mtu: Int,
|
||||||
|
val ackNoDelay: Boolean,
|
||||||
|
)
|
||||||
|
|
||||||
@Serializable
|
@Serializable
|
||||||
data class Vk(
|
data class Vk(
|
||||||
@@ -52,11 +66,14 @@ data class CoreConfigJson(
|
|||||||
data class Tunnel(val mode: String, val config: String, val mtu: Int)
|
data class Tunnel(val mode: String, val config: String, val mtu: Int)
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
// Все поля явно: пропущенное ядро молча заменит своим дефолтом.
|
// Все поля явно: пропущенное ядро молча заменит своим дефолтом. Исключение -
|
||||||
private val json = Json { encodeDefaults = true }
|
// kcp: null не сериализуется, и дефолты ARQ остаются за ядром.
|
||||||
|
private val json = Json { encodeDefaults = true; explicitNulls = false }
|
||||||
|
|
||||||
const val TRANSPORT_TCP = "tcp"
|
const val TRANSPORT_TCP = "tcp"
|
||||||
const val TRANSPORT_UDP = "udp"
|
const val TRANSPORT_UDP = "udp"
|
||||||
|
const val PROXY_MODE_TCP = "tcp"
|
||||||
|
const val PROXY_MODE_UDP = "udp"
|
||||||
const val TUNNEL_MODE_NONE = "none"
|
const val TUNNEL_MODE_NONE = "none"
|
||||||
const val TUNNEL_MODE_WG = "wg"
|
const val TUNNEL_MODE_WG = "wg"
|
||||||
const val PLATFORM_MOBILE = "mobile"
|
const val PLATFORM_MOBILE = "mobile"
|
||||||
@@ -84,6 +101,8 @@ fun ClientConfig.toCoreJson(
|
|||||||
}.map { it.trim() }.filter { it.isNotEmpty() }
|
}.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.
|
||||||
|
val tcpMode = srv.tcpMode && !wireGuardActive
|
||||||
|
|
||||||
return CoreConfigJson.encode(
|
return CoreConfigJson.encode(
|
||||||
CoreConfigJson(
|
CoreConfigJson(
|
||||||
@@ -102,6 +121,7 @@ fun ClientConfig.toCoreJson(
|
|||||||
port = "",
|
port = "",
|
||||||
),
|
),
|
||||||
proxy = CoreConfigJson.Proxy(
|
proxy = CoreConfigJson.Proxy(
|
||||||
|
mode = if (tcpMode) CoreConfigJson.PROXY_MODE_TCP else CoreConfigJson.PROXY_MODE_UDP,
|
||||||
// В туннельном режиме порт не биндится (ядро берёт in-memory pipe),
|
// В туннельном режиме порт не биндится (ядро берёт in-memory pipe),
|
||||||
// но валидацию проходит и нужен прокси-режиму.
|
// но валидацию проходит и нужен прокси-режиму.
|
||||||
listen = localPort,
|
listen = localPort,
|
||||||
@@ -120,6 +140,7 @@ fun ClientConfig.toCoreJson(
|
|||||||
),
|
),
|
||||||
dns = CoreConfigJson.Dns(mode = dnsMode, servers = dnsServers),
|
dns = CoreConfigJson.Dns(mode = dnsMode, servers = dnsServers),
|
||||||
log = CoreConfigJson.Log(debug = debugMode),
|
log = CoreConfigJson.Log(debug = debugMode),
|
||||||
|
kcp = if (tcpMode) srv.kcp.toCoreJson() else null,
|
||||||
tunnel = CoreConfigJson.Tunnel(
|
tunnel = CoreConfigJson.Tunnel(
|
||||||
mode = if (wireGuardActive) CoreConfigJson.TUNNEL_MODE_WG
|
mode = if (wireGuardActive) CoreConfigJson.TUNNEL_MODE_WG
|
||||||
else CoreConfigJson.TUNNEL_MODE_NONE,
|
else CoreConfigJson.TUNNEL_MODE_NONE,
|
||||||
@@ -129,3 +150,14 @@ fun ClientConfig.toCoreJson(
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun KcpProfile.toCoreJson() = CoreConfigJson.Kcp(
|
||||||
|
noDelay = noDelay,
|
||||||
|
interval = interval,
|
||||||
|
resend = resend,
|
||||||
|
nc = nc,
|
||||||
|
sndWnd = sndWnd,
|
||||||
|
rcvWnd = rcvWnd,
|
||||||
|
mtu = mtu,
|
||||||
|
ackNoDelay = ackNoDelay,
|
||||||
|
)
|
||||||
@@ -46,6 +46,13 @@ object ClientId {
|
|||||||
ByteArray(16).also { SecureRandom().nextBytes(it) }.joinToString("") { "%02x".format(it) }
|
ByteArray(16).also { SecureRandom().nextBytes(it) }.joinToString("") { "%02x".format(it) }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Режим проброса (-mode): udp - датаграммы WireGuard, tcp - поток Xray/sing-box. */
|
||||||
|
object ProxyMode {
|
||||||
|
const val UDP = "udp"
|
||||||
|
const val TCP = "tcp"
|
||||||
|
val VALUES = listOf(UDP, TCP)
|
||||||
|
}
|
||||||
|
|
||||||
object TunnelTransport {
|
object TunnelTransport {
|
||||||
const val NONE = "none"
|
const val NONE = "none"
|
||||||
const val WIREGUARD = "wireguard"
|
const val WIREGUARD = "wireguard"
|
||||||
|
|||||||
@@ -0,0 +1,46 @@
|
|||||||
|
package com.freeturn.app.data.config
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Профиль ARQ-слоя tcp-режима: секция `kcp` конфига ядра и флаги `-kcp-*`.
|
||||||
|
*
|
||||||
|
* [DEFAULT] обязан совпадать с дефолтом ядра: в udp-режиме любое отличие ядро считает
|
||||||
|
* ошибкой запуска, поэтому в udp секция в конфиг не кладётся вовсе.
|
||||||
|
*/
|
||||||
|
data class KcpProfile(
|
||||||
|
val noDelay: Int = 1,
|
||||||
|
val interval: Int = 20,
|
||||||
|
val resend: Int = 2,
|
||||||
|
val nc: Int = 1,
|
||||||
|
val sndWnd: Int = 512,
|
||||||
|
val rcvWnd: Int = 512,
|
||||||
|
val mtu: Int = 1200,
|
||||||
|
val ackNoDelay: Boolean = true,
|
||||||
|
) {
|
||||||
|
val valid: Boolean
|
||||||
|
get() = noDelay in 0..1 && nc in 0..1 && interval > 0 && resend >= 0 &&
|
||||||
|
sndWnd > 0 && rcvWnd > 0 && mtu in MTU_MIN..MTU_MAX
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
val DEFAULT = KcpProfile()
|
||||||
|
|
||||||
|
/** Щадящий вариант для мобильной сети (docs/flags.md ядра). */
|
||||||
|
val MOBILE = KcpProfile(interval = 40, sndWnd = 256, rcvWnd = 256, ackNoDelay = false)
|
||||||
|
|
||||||
|
// Сегмент KCP едет внутри DTLS, obf-обёртки, TURN и IP/UDP - выше режется по пути.
|
||||||
|
const val MTU_MIN = 300
|
||||||
|
const val MTU_MAX = 1350
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
object KcpPreset {
|
||||||
|
const val STANDARD = "standard"
|
||||||
|
const val MOBILE = "mobile"
|
||||||
|
const val CUSTOM = "custom"
|
||||||
|
val VALUES = listOf(STANDARD, MOBILE, CUSTOM)
|
||||||
|
|
||||||
|
fun of(profile: KcpProfile): String = when (profile) {
|
||||||
|
KcpProfile.DEFAULT -> STANDARD
|
||||||
|
KcpProfile.MOBILE -> MOBILE
|
||||||
|
else -> CUSTOM
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,6 +14,7 @@ data class ProbeData(
|
|||||||
val version: String? = null,
|
val version: String? = null,
|
||||||
@SerialName("bin_sha256") val binSha256: String? = null,
|
@SerialName("bin_sha256") val binSha256: String? = null,
|
||||||
val running: Boolean = false,
|
val running: Boolean = false,
|
||||||
|
val mode: String? = null,
|
||||||
val obf: String? = null,
|
val obf: String? = null,
|
||||||
val runtime: String = "",
|
val runtime: String = "",
|
||||||
val euid: Int = -1,
|
val euid: Int = -1,
|
||||||
@@ -62,6 +63,7 @@ data class WgSetupInfo(
|
|||||||
@Serializable
|
@Serializable
|
||||||
data class ShareInfoData(
|
data class ShareInfoData(
|
||||||
@SerialName("wg_backend") val wgBackend: Boolean = false,
|
@SerialName("wg_backend") val wgBackend: Boolean = false,
|
||||||
|
val mode: String = "",
|
||||||
@SerialName("obf_profile") val obfProfile: String = "",
|
@SerialName("obf_profile") val obfProfile: String = "",
|
||||||
@SerialName("obf_key") val obfKey: String = "",
|
@SerialName("obf_key") val obfKey: String = "",
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -2,8 +2,10 @@ package com.freeturn.app.data.server
|
|||||||
|
|
||||||
import com.freeturn.app.data.config.ClientConfig
|
import com.freeturn.app.data.config.ClientConfig
|
||||||
import com.freeturn.app.data.config.DnsMode
|
import com.freeturn.app.data.config.DnsMode
|
||||||
|
import com.freeturn.app.data.config.KcpProfile
|
||||||
import com.freeturn.app.data.config.ObfProfile
|
import com.freeturn.app.data.config.ObfProfile
|
||||||
import com.freeturn.app.data.config.Provider
|
import com.freeturn.app.data.config.Provider
|
||||||
|
import com.freeturn.app.data.config.ProxyMode
|
||||||
import com.freeturn.app.data.config.SplitTunnelMode
|
import com.freeturn.app.data.config.SplitTunnelMode
|
||||||
import com.freeturn.app.data.config.SshConfig
|
import com.freeturn.app.data.config.SshConfig
|
||||||
import com.freeturn.app.data.config.TunnelTransport
|
import com.freeturn.app.data.config.TunnelTransport
|
||||||
@@ -72,6 +74,8 @@ internal object ServerJson {
|
|||||||
put("opts", JSONObject().apply {
|
put("opts", JSONObject().apply {
|
||||||
put("obfProfile", p.opts.obfProfile)
|
put("obfProfile", p.opts.obfProfile)
|
||||||
put("obfKey", p.opts.obfKey)
|
put("obfKey", p.opts.obfKey)
|
||||||
|
put("proxyMode", p.opts.proxyMode)
|
||||||
|
put("kcp", encodeKcp(p.opts.kcp))
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -132,8 +136,38 @@ internal object ServerJson {
|
|||||||
obfProfile = optsO.optString("obfProfile", ObfProfile.NONE).let {
|
obfProfile = optsO.optString("obfProfile", ObfProfile.NONE).let {
|
||||||
if (it in ObfProfile.VALUES) it else ObfProfile.NONE
|
if (it in ObfProfile.VALUES) it else ObfProfile.NONE
|
||||||
},
|
},
|
||||||
obfKey = optsO.optString("obfKey", "")
|
obfKey = optsO.optString("obfKey", ""),
|
||||||
|
proxyMode = optsO.optString("proxyMode", ProxyMode.UDP).let {
|
||||||
|
if (it in ProxyMode.VALUES) it else ProxyMode.UDP
|
||||||
|
},
|
||||||
|
kcp = decodeKcp(optsO.optJSONObject("kcp"))
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun encodeKcp(p: KcpProfile): JSONObject = JSONObject().apply {
|
||||||
|
put("noDelay", p.noDelay)
|
||||||
|
put("interval", p.interval)
|
||||||
|
put("resend", p.resend)
|
||||||
|
put("nc", p.nc)
|
||||||
|
put("sndWnd", p.sndWnd)
|
||||||
|
put("rcvWnd", p.rcvWnd)
|
||||||
|
put("mtu", p.mtu)
|
||||||
|
put("ackNoDelay", p.ackNoDelay)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun decodeKcp(o: JSONObject?): KcpProfile {
|
||||||
|
if (o == null) return KcpProfile.DEFAULT
|
||||||
|
val d = KcpProfile.DEFAULT
|
||||||
|
return KcpProfile(
|
||||||
|
noDelay = o.optInt("noDelay", d.noDelay),
|
||||||
|
interval = o.optInt("interval", d.interval),
|
||||||
|
resend = o.optInt("resend", d.resend),
|
||||||
|
nc = o.optInt("nc", d.nc),
|
||||||
|
sndWnd = o.optInt("sndWnd", d.sndWnd),
|
||||||
|
rcvWnd = o.optInt("rcvWnd", d.rcvWnd),
|
||||||
|
mtu = o.optInt("mtu", d.mtu),
|
||||||
|
ackNoDelay = o.optBoolean("ackNoDelay", d.ackNoDelay)
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,14 +1,22 @@
|
|||||||
package com.freeturn.app.data.server
|
package com.freeturn.app.data.server
|
||||||
|
|
||||||
|
import com.freeturn.app.data.config.KcpProfile
|
||||||
import com.freeturn.app.data.config.ObfProfile
|
import com.freeturn.app.data.config.ObfProfile
|
||||||
|
import com.freeturn.app.data.config.ProxyMode
|
||||||
|
|
||||||
/** Снимок серверных obf-опций. obfKey хранится в шифрованном хранилище AppPreferences. */
|
/** Снимок серверных опций. obfKey хранится в шифрованном хранилище AppPreferences. */
|
||||||
data class ServerOpts(
|
data class ServerOpts(
|
||||||
/** Wire-профиль обфускации: none | rtpopus | rtpopus2 | rtpopus3 (-obf-profile). */
|
/** Wire-профиль обфускации: none | rtpopus | rtpopus2 | rtpopus3 (-obf-profile). */
|
||||||
val obfProfile: String = ObfProfile.NONE,
|
val obfProfile: String = ObfProfile.NONE,
|
||||||
/** 64-hex obf-ключ (-obf-key). Должен совпадать на клиенте и сервере. */
|
/** 64-hex obf-ключ (-obf-key). Должен совпадать на клиенте и сервере. */
|
||||||
val obfKey: String = ""
|
val obfKey: String = "",
|
||||||
|
/** Режим проброса (-mode). Сервер отвергает сессию с другим режимом. */
|
||||||
|
val proxyMode: String = ProxyMode.UDP,
|
||||||
|
/** ARQ tcp-режима (-kcp-*); в udp не используется. */
|
||||||
|
val kcp: KcpProfile = KcpProfile.DEFAULT
|
||||||
) {
|
) {
|
||||||
/** Обфускация включена, когда выбран реальный профиль. */
|
/** Обфускация включена, когда выбран реальный профиль. */
|
||||||
val obfEnabled: Boolean get() = obfProfile != ObfProfile.NONE
|
val obfEnabled: Boolean get() = obfProfile != ObfProfile.NONE
|
||||||
|
|
||||||
|
val tcpMode: Boolean get() = proxyMode == ProxyMode.TCP
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.freeturn.app.data.share
|
package com.freeturn.app.data.share
|
||||||
|
|
||||||
|
import com.freeturn.app.data.config.KcpProfile
|
||||||
import org.json.JSONObject
|
import org.json.JSONObject
|
||||||
import java.util.Base64
|
import java.util.Base64
|
||||||
|
|
||||||
@@ -11,6 +12,7 @@ data class FreeturnLink(
|
|||||||
val provider: String,
|
val provider: String,
|
||||||
val peer: String,
|
val peer: String,
|
||||||
val transport: String = "",
|
val transport: String = "",
|
||||||
|
val mode: String = "",
|
||||||
val obfProfile: String = "",
|
val obfProfile: String = "",
|
||||||
val obfKey: String = "",
|
val obfKey: String = "",
|
||||||
val n: Int = 0,
|
val n: Int = 0,
|
||||||
@@ -20,6 +22,8 @@ data class FreeturnLink(
|
|||||||
val dnsMode: String = "",
|
val dnsMode: String = "",
|
||||||
val dnsServers: String = "",
|
val dnsServers: String = "",
|
||||||
val manualCaptcha: Boolean = false,
|
val manualCaptcha: Boolean = false,
|
||||||
|
/** ARQ tcp-режима; null - у получателя останется дефолт ядра. */
|
||||||
|
val kcp: KcpProfile? = null,
|
||||||
val name: String = "",
|
val name: String = "",
|
||||||
val wgConf: String = ""
|
val wgConf: String = ""
|
||||||
) {
|
) {
|
||||||
@@ -29,6 +33,7 @@ data class FreeturnLink(
|
|||||||
sb.field("provider", jsonString(provider))
|
sb.field("provider", jsonString(provider))
|
||||||
sb.field("peer", jsonString(peer))
|
sb.field("peer", jsonString(peer))
|
||||||
if (transport.isNotEmpty()) sb.field("transport", jsonString(transport))
|
if (transport.isNotEmpty()) sb.field("transport", jsonString(transport))
|
||||||
|
if (mode.isNotEmpty()) sb.field("mode", jsonString(mode))
|
||||||
if (obfProfile.isNotEmpty() && obfProfile != "none") {
|
if (obfProfile.isNotEmpty() && obfProfile != "none") {
|
||||||
sb.field("obf", jsonString(obfProfile))
|
sb.field("obf", jsonString(obfProfile))
|
||||||
sb.field("key", jsonString(obfKey))
|
sb.field("key", jsonString(obfKey))
|
||||||
@@ -40,6 +45,7 @@ data class FreeturnLink(
|
|||||||
if (dnsMode.isNotEmpty()) sb.field("dns", jsonString(dnsMode))
|
if (dnsMode.isNotEmpty()) sb.field("dns", jsonString(dnsMode))
|
||||||
if (dnsServers.isNotEmpty()) sb.field("dnss", jsonString(dnsServers))
|
if (dnsServers.isNotEmpty()) sb.field("dnss", jsonString(dnsServers))
|
||||||
if (manualCaptcha) sb.field("mcap", "true")
|
if (manualCaptcha) sb.field("mcap", "true")
|
||||||
|
if (kcp != null) sb.field("kcp", kcpJson(kcp))
|
||||||
if (name.isNotEmpty()) sb.field("name", jsonString(name))
|
if (name.isNotEmpty()) sb.field("name", jsonString(name))
|
||||||
if (wgConf.isNotEmpty()) sb.field("wg", jsonString(wgConf))
|
if (wgConf.isNotEmpty()) sb.field("wg", jsonString(wgConf))
|
||||||
sb.append('}')
|
sb.append('}')
|
||||||
@@ -70,6 +76,7 @@ data class FreeturnLink(
|
|||||||
provider = provider,
|
provider = provider,
|
||||||
peer = peer,
|
peer = peer,
|
||||||
transport = o.optString("transport"),
|
transport = o.optString("transport"),
|
||||||
|
mode = o.optString("mode"),
|
||||||
obfProfile = o.optString("obf"),
|
obfProfile = o.optString("obf"),
|
||||||
obfKey = o.optString("key"),
|
obfKey = o.optString("key"),
|
||||||
n = o.optInt("n", 0),
|
n = o.optInt("n", 0),
|
||||||
@@ -79,11 +86,32 @@ data class FreeturnLink(
|
|||||||
dnsMode = o.optString("dns"),
|
dnsMode = o.optString("dns"),
|
||||||
dnsServers = o.optString("dnss"),
|
dnsServers = o.optString("dnss"),
|
||||||
manualCaptcha = o.optBoolean("mcap", false),
|
manualCaptcha = o.optBoolean("mcap", false),
|
||||||
|
kcp = o.optJSONObject("kcp")?.let(::parseKcp),
|
||||||
name = o.optString("name"),
|
name = o.optString("name"),
|
||||||
wgConf = o.optString("wg")
|
wgConf = o.optString("wg")
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Ключи ARQ в ссылке - строчные (json-теги uri.KCP в ядре), а не camelCase конфига.
|
||||||
|
private fun parseKcp(o: JSONObject): KcpProfile {
|
||||||
|
val d = KcpProfile.DEFAULT
|
||||||
|
return KcpProfile(
|
||||||
|
noDelay = o.optInt("nodelay", d.noDelay),
|
||||||
|
interval = o.optInt("interval", d.interval),
|
||||||
|
resend = o.optInt("resend", d.resend),
|
||||||
|
nc = o.optInt("nc", d.nc),
|
||||||
|
sndWnd = o.optInt("sndwnd", d.sndWnd),
|
||||||
|
rcvWnd = o.optInt("rcvwnd", d.rcvWnd),
|
||||||
|
mtu = o.optInt("mtu", d.mtu),
|
||||||
|
ackNoDelay = o.optBoolean("acknodelay", d.ackNoDelay)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun kcpJson(p: KcpProfile): String =
|
||||||
|
"""{"nodelay":${p.noDelay},"interval":${p.interval},"resend":${p.resend},""" +
|
||||||
|
""""nc":${p.nc},"sndwnd":${p.sndWnd},"rcvwnd":${p.rcvWnd},""" +
|
||||||
|
""""mtu":${p.mtu},"acknodelay":${p.ackNoDelay}}"""
|
||||||
|
|
||||||
private fun StringBuilder.field(key: String, rawValue: String) {
|
private fun StringBuilder.field(key: String, rawValue: String) {
|
||||||
if (length > 1) append(',')
|
if (length > 1) append(',')
|
||||||
append('"').append(key).append("\":").append(rawValue)
|
append('"').append(key).append("\":").append(rawValue)
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
package com.freeturn.app.data.share
|
package com.freeturn.app.data.share
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Фактическое состояние сервера для построения share-ссылки (из `share-info`).
|
* Фактические параметры запущенного сервера (`share-info`).
|
||||||
* Используется вместо локального [com.freeturn.app.data.server.ServerOpts] для точности.
|
* Используется вместо локального [com.freeturn.app.data.server.ServerOpts] для точности.
|
||||||
*/
|
*/
|
||||||
data class ShareInfo(
|
data class ShareInfo(
|
||||||
|
/** Режим проброса живого сервера: "udp" | "tcp". */
|
||||||
|
val mode: String = "",
|
||||||
/** Пусто = сервер не запускался из приложения; при живых args хотя бы "none". */
|
/** Пусто = сервер не запускался из приложения; при живых args хотя бы "none". */
|
||||||
val obfProfile: String = "",
|
val obfProfile: String = "",
|
||||||
val obfKey: String = "",
|
val obfKey: String = "",
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
package com.freeturn.app.data.share
|
package com.freeturn.app.data.share
|
||||||
|
|
||||||
|
import com.freeturn.app.data.config.KcpProfile
|
||||||
import com.freeturn.app.data.config.ObfProfile
|
import com.freeturn.app.data.config.ObfProfile
|
||||||
|
import com.freeturn.app.data.config.ProxyMode
|
||||||
import com.freeturn.app.data.server.Server
|
import com.freeturn.app.data.server.Server
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -18,10 +20,14 @@ object ShareLinkBuilder {
|
|||||||
): String {
|
): String {
|
||||||
val obfProfile = if (info.hasRunArgs) info.obfProfile else server.opts.obfProfile
|
val obfProfile = if (info.hasRunArgs) info.obfProfile else server.opts.obfProfile
|
||||||
val obfKey = if (info.hasRunArgs) info.obfKey else server.opts.obfKey
|
val obfKey = if (info.hasRunArgs) info.obfKey else server.opts.obfKey
|
||||||
|
val tcpMode = if (info.hasRunArgs) info.mode == ProxyMode.TCP else server.opts.tcpMode
|
||||||
return FreeturnLink(
|
return FreeturnLink(
|
||||||
provider = server.client.provider,
|
provider = server.client.provider,
|
||||||
peer = server.client.serverAddress,
|
peer = server.client.serverAddress,
|
||||||
transport = if (server.client.useUdp) "udp" else "",
|
transport = if (server.client.useUdp) "udp" else "",
|
||||||
|
mode = if (tcpMode) ProxyMode.TCP else "",
|
||||||
|
// Профиль ARQ сервер не репортит: отдаём тот, что владелец ему и выставил.
|
||||||
|
kcp = server.opts.kcp.takeIf { tcpMode && it != KcpProfile.DEFAULT },
|
||||||
obfProfile = if (ObfProfile.isValidKey(obfKey)) obfProfile else "",
|
obfProfile = if (ObfProfile.isValidKey(obfKey)) obfProfile else "",
|
||||||
obfKey = if (ObfProfile.isValidKey(obfKey)) obfKey else "",
|
obfKey = if (ObfProfile.isValidKey(obfKey)) obfKey else "",
|
||||||
n = server.client.threads,
|
n = server.client.threads,
|
||||||
|
|||||||
@@ -13,6 +13,8 @@ sealed class ServerState {
|
|||||||
data class Known(
|
data class Known(
|
||||||
val installed: Boolean,
|
val installed: Boolean,
|
||||||
val running: Boolean,
|
val running: Boolean,
|
||||||
|
/** Режим живого сервера ("udp" | "tcp"); null - сервер не запущен. */
|
||||||
|
val mode: String? = null,
|
||||||
val obfProfile: String? = null,
|
val obfProfile: String? = null,
|
||||||
val version: String? = null
|
val version: String? = null
|
||||||
) : ServerState()
|
) : ServerState()
|
||||||
|
|||||||
@@ -42,6 +42,8 @@ class ProxyOrchestrator(
|
|||||||
sshRepository.stopServer()
|
sshRepository.stopServer()
|
||||||
sshRepository.startServer(
|
sshRepository.startServer(
|
||||||
listen = l, connect = c,
|
listen = l, connect = c,
|
||||||
|
proxyMode = opts.proxyMode,
|
||||||
|
kcp = opts.kcp,
|
||||||
obfProfile = if (opts.obfEnabled) opts.obfProfile else "none",
|
obfProfile = if (opts.obfEnabled) opts.obfProfile else "none",
|
||||||
obfKey = if (opts.obfEnabled) opts.obfKey else "",
|
obfKey = if (opts.obfEnabled) opts.obfKey else "",
|
||||||
clientId = prefs.ownClientId()
|
clientId = prefs.ownClientId()
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
package com.freeturn.app.domain.server
|
package com.freeturn.app.domain.server
|
||||||
|
|
||||||
|
import com.freeturn.app.data.config.KcpProfile
|
||||||
|
import com.freeturn.app.data.config.ProxyMode
|
||||||
|
|
||||||
sealed class ServerCommand {
|
sealed class ServerCommand {
|
||||||
data object Probe : ServerCommand()
|
data object Probe : ServerCommand()
|
||||||
data object Install : ServerCommand()
|
data object Install : ServerCommand()
|
||||||
@@ -49,6 +52,10 @@ sealed class ServerCommand {
|
|||||||
add("start")
|
add("start")
|
||||||
add("--listen=${opts.listen}")
|
add("--listen=${opts.listen}")
|
||||||
add("--connect=${opts.connect}")
|
add("--connect=${opts.connect}")
|
||||||
|
if (opts.proxyMode == ProxyMode.TCP) {
|
||||||
|
add("--mode=${ProxyMode.TCP}")
|
||||||
|
addAll(kcpArgs(opts.kcp))
|
||||||
|
}
|
||||||
if (opts.obfProfile != "none" && opts.obfKey.isNotBlank()) {
|
if (opts.obfProfile != "none" && opts.obfKey.isNotBlank()) {
|
||||||
add("--obf-profile=${opts.obfProfile}")
|
add("--obf-profile=${opts.obfProfile}")
|
||||||
add("--obf-key=${opts.obfKey}")
|
add("--obf-key=${opts.obfKey}")
|
||||||
@@ -85,7 +92,22 @@ sealed class ServerCommand {
|
|||||||
data class ServerStartOptions(
|
data class ServerStartOptions(
|
||||||
val listen: String,
|
val listen: String,
|
||||||
val connect: String,
|
val connect: String,
|
||||||
|
val proxyMode: String = ProxyMode.UDP,
|
||||||
|
val kcp: KcpProfile = KcpProfile.DEFAULT,
|
||||||
val obfProfile: String = "none",
|
val obfProfile: String = "none",
|
||||||
val obfKey: String = "",
|
val obfKey: String = "",
|
||||||
val clientId: String = ""
|
val clientId: String = ""
|
||||||
)
|
)
|
||||||
|
|
||||||
|
/** Только отличия от дефолта: остальное сервер возьмёт своё, как и клиент. */
|
||||||
|
private fun kcpArgs(p: KcpProfile): List<String> = buildList {
|
||||||
|
val d = KcpProfile.DEFAULT
|
||||||
|
if (p.noDelay != d.noDelay) add("--kcp-nodelay=${p.noDelay}")
|
||||||
|
if (p.interval != d.interval) add("--kcp-interval=${p.interval}")
|
||||||
|
if (p.resend != d.resend) add("--kcp-resend=${p.resend}")
|
||||||
|
if (p.nc != d.nc) add("--kcp-nc=${p.nc}")
|
||||||
|
if (p.sndWnd != d.sndWnd) add("--kcp-sndwnd=${p.sndWnd}")
|
||||||
|
if (p.rcvWnd != d.rcvWnd) add("--kcp-rcvwnd=${p.rcvWnd}")
|
||||||
|
if (p.mtu != d.mtu) add("--kcp-mtu=${p.mtu}")
|
||||||
|
if (p.ackNoDelay != d.ackNoDelay) add("--kcp-acknodelay=${p.ackNoDelay}")
|
||||||
|
}
|
||||||
@@ -31,7 +31,7 @@ class ShareRepository(context: Context, ssh: SSHManager) {
|
|||||||
suspend fun shareInfo(cfg: SshConfig): Result<ShareInfo> =
|
suspend fun shareInfo(cfg: SshConfig): Result<ShareInfo> =
|
||||||
control.run(cfg, ServerCommand.ShareInfo)
|
control.run(cfg, ServerCommand.ShareInfo)
|
||||||
.requireData<ShareInfoData>()
|
.requireData<ShareInfoData>()
|
||||||
.map { ShareInfo(it.obfProfile, it.obfKey, it.wgBackend) }
|
.map { ShareInfo(it.mode, it.obfProfile, it.obfKey, it.wgBackend) }
|
||||||
|
|
||||||
suspend fun addPeer(
|
suspend fun addPeer(
|
||||||
cfg: SshConfig,
|
cfg: SshConfig,
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
package com.freeturn.app.domain.ssh
|
package com.freeturn.app.domain.ssh
|
||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
|
import com.freeturn.app.data.config.KcpProfile
|
||||||
|
import com.freeturn.app.data.config.ProxyMode
|
||||||
import com.freeturn.app.data.config.SshConfig
|
import com.freeturn.app.data.config.SshConfig
|
||||||
import com.freeturn.app.data.control.ControlResponse
|
import com.freeturn.app.data.control.ControlResponse
|
||||||
import com.freeturn.app.data.control.InstallData
|
import com.freeturn.app.data.control.InstallData
|
||||||
@@ -149,6 +151,7 @@ class SshRepository(
|
|||||||
_serverState.value = ServerState.Known(
|
_serverState.value = ServerState.Known(
|
||||||
installed = d.installed,
|
installed = d.installed,
|
||||||
running = d.running,
|
running = d.running,
|
||||||
|
mode = if (d.running) d.mode ?: ProxyMode.UDP else null,
|
||||||
obfProfile = if (d.running) d.obf else null,
|
obfProfile = if (d.running) d.obf else null,
|
||||||
version = d.version
|
version = d.version
|
||||||
)
|
)
|
||||||
@@ -184,6 +187,8 @@ class SshRepository(
|
|||||||
suspend fun startServer(
|
suspend fun startServer(
|
||||||
listen: String,
|
listen: String,
|
||||||
connect: String,
|
connect: String,
|
||||||
|
proxyMode: String = ProxyMode.UDP,
|
||||||
|
kcp: KcpProfile = KcpProfile.DEFAULT,
|
||||||
obfProfile: String = "none",
|
obfProfile: String = "none",
|
||||||
obfKey: String = "",
|
obfKey: String = "",
|
||||||
clientId: String = ""
|
clientId: String = ""
|
||||||
@@ -198,6 +203,8 @@ class SshRepository(
|
|||||||
ServerStartOptions(
|
ServerStartOptions(
|
||||||
listen = listen,
|
listen = listen,
|
||||||
connect = connect,
|
connect = connect,
|
||||||
|
proxyMode = proxyMode,
|
||||||
|
kcp = kcp,
|
||||||
obfProfile = obfProfile,
|
obfProfile = obfProfile,
|
||||||
obfKey = obfKey,
|
obfKey = obfKey,
|
||||||
clientId = clientId
|
clientId = clientId
|
||||||
|
|||||||
@@ -0,0 +1,68 @@
|
|||||||
|
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3ExpressiveApi::class)
|
||||||
|
|
||||||
|
package com.freeturn.app.ui.components
|
||||||
|
|
||||||
|
import androidx.compose.animation.AnimatedVisibility
|
||||||
|
import androidx.compose.animation.EnterTransition
|
||||||
|
import androidx.compose.animation.ExitTransition
|
||||||
|
import androidx.compose.animation.fadeIn
|
||||||
|
import androidx.compose.animation.fadeOut
|
||||||
|
import androidx.compose.animation.scaleIn
|
||||||
|
import androidx.compose.animation.scaleOut
|
||||||
|
import androidx.compose.material3.ExtendedFloatingActionButton
|
||||||
|
import androidx.compose.material3.FloatingActionButtonDefaults
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.contentColorFor
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.res.painterResource
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.semantics.semantics
|
||||||
|
import androidx.compose.ui.semantics.stateDescription
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import com.freeturn.app.R
|
||||||
|
import com.freeturn.app.ui.theme.LocalReducedMotion
|
||||||
|
|
||||||
|
/** Запас под FAB в конце скролла: 56dp кнопки + 16dp отступа Scaffold + воздух. */
|
||||||
|
val FabClearance = 88.dp
|
||||||
|
|
||||||
|
/**
|
||||||
|
* FAB "Применить" для экранов с apply-моделью. Появляется, как только есть правки
|
||||||
|
* ([visible]), но при [blockedReason] остаётся на месте в disabled-виде: исчезнувшая
|
||||||
|
* кнопка не объясняет, почему применить нельзя.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
fun ApplyFab(visible: Boolean, blockedReason: String? = null, onApply: () -> Unit) {
|
||||||
|
val reducedMotion = LocalReducedMotion.current
|
||||||
|
val enabled = blockedReason == null
|
||||||
|
val container = if (enabled) FloatingActionButtonDefaults.containerColor
|
||||||
|
else MaterialTheme.colorScheme.surfaceContainerHighest
|
||||||
|
val onContainer = if (enabled) contentColorFor(container)
|
||||||
|
else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f)
|
||||||
|
|
||||||
|
AnimatedVisibility(
|
||||||
|
visible = visible,
|
||||||
|
enter = if (reducedMotion) EnterTransition.None else {
|
||||||
|
scaleIn(MaterialTheme.motionScheme.defaultSpatialSpec<Float>()) +
|
||||||
|
fadeIn(MaterialTheme.motionScheme.defaultEffectsSpec<Float>())
|
||||||
|
},
|
||||||
|
exit = if (reducedMotion) ExitTransition.None else {
|
||||||
|
scaleOut(MaterialTheme.motionScheme.fastSpatialSpec<Float>()) +
|
||||||
|
fadeOut(MaterialTheme.motionScheme.fastEffectsSpec<Float>())
|
||||||
|
}
|
||||||
|
) {
|
||||||
|
ExtendedFloatingActionButton(
|
||||||
|
onClick = { if (enabled) onApply() },
|
||||||
|
icon = { Icon(painterResource(R.drawable.check_circle_24px), contentDescription = null) },
|
||||||
|
text = { Text(stringResource(R.string.server_apply)) },
|
||||||
|
containerColor = container,
|
||||||
|
contentColor = onContainer,
|
||||||
|
// Тень у неактивной кнопки читалась бы как "нажми меня".
|
||||||
|
elevation = if (enabled) FloatingActionButtonDefaults.elevation()
|
||||||
|
else FloatingActionButtonDefaults.elevation(0.dp, 0.dp, 0.dp, 0.dp),
|
||||||
|
modifier = blockedReason?.let { r -> Modifier.semantics { stateDescription = r } } ?: Modifier
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
package com.freeturn.app.ui.components
|
||||||
|
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.Spacer
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.width
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Surface
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.res.painterResource
|
||||||
|
import com.freeturn.app.R
|
||||||
|
import com.freeturn.app.ui.theme.Spacing
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Тональная карточка предупреждения (tertiaryContainer): то, что надо учесть, но не ошибка.
|
||||||
|
* Отличима от соседних абзацев supporting-текста; для ошибок - [InlineErrorCard].
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
fun InlineNoticeCard(message: String, modifier: Modifier = Modifier) {
|
||||||
|
Surface(
|
||||||
|
shape = MaterialTheme.shapes.medium,
|
||||||
|
color = MaterialTheme.colorScheme.tertiaryContainer,
|
||||||
|
modifier = modifier.fillMaxWidth()
|
||||||
|
) {
|
||||||
|
Row(modifier = Modifier.padding(Spacing.md)) {
|
||||||
|
Icon(
|
||||||
|
painterResource(R.drawable.info_24px),
|
||||||
|
contentDescription = null,
|
||||||
|
tint = MaterialTheme.colorScheme.onTertiaryContainer
|
||||||
|
)
|
||||||
|
Spacer(Modifier.width(Spacing.md))
|
||||||
|
Text(
|
||||||
|
message,
|
||||||
|
color = MaterialTheme.colorScheme.onTertiaryContainer,
|
||||||
|
style = MaterialTheme.typography.bodyMedium
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
package com.freeturn.app.ui.components
|
||||||
|
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.SegmentedButton
|
||||||
|
import androidx.compose.material3.SegmentedButtonDefaults
|
||||||
|
import androidx.compose.material3.SingleChoiceSegmentedButtonRow
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.semantics.semantics
|
||||||
|
import androidx.compose.ui.semantics.stateDescription
|
||||||
|
import com.freeturn.app.R
|
||||||
|
import com.freeturn.app.data.HapticUtil
|
||||||
|
import com.freeturn.app.ui.theme.Spacing
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Выбор проброса UDP/TCP. [label] обязателен - без него сегменты озвучиваются как "1 из 2"
|
||||||
|
* без предмета выбора; [tcpDisabledReason] уходит и под группу, и в stateDescription.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
fun UdpTcpSegmented(
|
||||||
|
tcp: Boolean,
|
||||||
|
onTcp: (Boolean) -> Unit,
|
||||||
|
label: String,
|
||||||
|
modifier: Modifier = Modifier,
|
||||||
|
tcpDisabledReason: String? = null
|
||||||
|
) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
fun pick(value: Boolean) {
|
||||||
|
if (value == tcp) return
|
||||||
|
HapticUtil.perform(context, HapticUtil.Pattern.TOGGLE_ON)
|
||||||
|
onTcp(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
Column(modifier = modifier, verticalArrangement = Arrangement.spacedBy(Spacing.sm)) {
|
||||||
|
SettingsControlLabel(label)
|
||||||
|
SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) {
|
||||||
|
SegmentedButton(
|
||||||
|
selected = !tcp,
|
||||||
|
onClick = { pick(false) },
|
||||||
|
shape = SegmentedButtonDefaults.itemShape(index = 0, count = 2)
|
||||||
|
) { Text(stringResource(R.string.udp)) }
|
||||||
|
SegmentedButton(
|
||||||
|
selected = tcp,
|
||||||
|
onClick = { pick(true) },
|
||||||
|
enabled = tcpDisabledReason == null,
|
||||||
|
shape = SegmentedButtonDefaults.itemShape(index = 1, count = 2),
|
||||||
|
modifier = if (tcpDisabledReason == null) Modifier
|
||||||
|
else Modifier.semantics { stateDescription = tcpDisabledReason }
|
||||||
|
) { Text(stringResource(R.string.tcp)) }
|
||||||
|
}
|
||||||
|
if (tcpDisabledReason != null) {
|
||||||
|
Text(
|
||||||
|
tcpDisabledReason,
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+62
-3
@@ -45,16 +45,22 @@ import androidx.compose.ui.input.nestedscroll.nestedScroll
|
|||||||
import androidx.compose.ui.platform.LocalContext
|
import androidx.compose.ui.platform.LocalContext
|
||||||
import androidx.compose.ui.res.painterResource
|
import androidx.compose.ui.res.painterResource
|
||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
import androidx.compose.ui.unit.dp
|
|
||||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
import com.freeturn.app.R
|
import com.freeturn.app.R
|
||||||
import com.freeturn.app.data.config.ClientConfig
|
import com.freeturn.app.data.config.ClientConfig
|
||||||
|
import com.freeturn.app.data.config.ProxyMode
|
||||||
import com.freeturn.app.data.config.TunnelTransport
|
import com.freeturn.app.data.config.TunnelTransport
|
||||||
|
import com.freeturn.app.data.server.ServerOpts
|
||||||
import com.freeturn.app.data.HapticUtil
|
import com.freeturn.app.data.HapticUtil
|
||||||
|
import com.freeturn.app.ui.components.ApplyFab
|
||||||
|
import com.freeturn.app.ui.components.FabClearance
|
||||||
|
import com.freeturn.app.ui.components.InlineNoticeCard
|
||||||
import com.freeturn.app.ui.components.SectionLabel
|
import com.freeturn.app.ui.components.SectionLabel
|
||||||
import com.freeturn.app.ui.components.SettingsCard
|
import com.freeturn.app.ui.components.SettingsCard
|
||||||
import com.freeturn.app.ui.components.SettingsContentMaxWidth
|
import com.freeturn.app.ui.components.SettingsContentMaxWidth
|
||||||
import com.freeturn.app.ui.components.SettingsEntryRow
|
import com.freeturn.app.ui.components.SettingsEntryRow
|
||||||
|
import com.freeturn.app.ui.components.SettingsFieldSlot
|
||||||
|
import com.freeturn.app.ui.components.UdpTcpSegmented
|
||||||
import com.freeturn.app.ui.screens.splittunnel.SplitTunnelModal
|
import com.freeturn.app.ui.screens.splittunnel.SplitTunnelModal
|
||||||
import com.freeturn.app.ui.theme.Spacing
|
import com.freeturn.app.ui.theme.Spacing
|
||||||
import com.freeturn.app.viewmodel.proxy.ProxyViewModel
|
import com.freeturn.app.viewmodel.proxy.ProxyViewModel
|
||||||
@@ -78,6 +84,7 @@ fun ConnectionModeScreen(
|
|||||||
|
|
||||||
val server = serverId?.let { id -> snapshot.list.firstOrNull { it.id == id } }
|
val server = serverId?.let { id -> snapshot.list.firstOrNull { it.id == id } }
|
||||||
val saved = server?.client ?: activeClient
|
val saved = server?.client ?: activeClient
|
||||||
|
val savedOpts = server?.opts ?: snapshot.active?.opts ?: ServerOpts()
|
||||||
val isActive = serverId == null || serverId == snapshot.activeId
|
val isActive = serverId == null || serverId == snapshot.activeId
|
||||||
|
|
||||||
fun clientEdit(transform: (ClientConfig) -> ClientConfig) {
|
fun clientEdit(transform: (ClientConfig) -> ClientConfig) {
|
||||||
@@ -99,6 +106,23 @@ fun ConnectionModeScreen(
|
|||||||
var wgConfig by remember(fieldsKey) { mutableStateOf(saved.wireGuardConfig) }
|
var wgConfig by remember(fieldsKey) { mutableStateOf(saved.wireGuardConfig) }
|
||||||
var wgName by remember(fieldsKey) { mutableStateOf(saved.wireGuardTunnelName) }
|
var wgName by remember(fieldsKey) { mutableStateOf(saved.wireGuardTunnelName) }
|
||||||
|
|
||||||
|
// Проброс и 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
|
||||||
|
val forwardVisible = !isVpn && forwardDirty
|
||||||
|
val applyBlocked = if (isTcp && !kcpDraft.valid) stringResource(R.string.apply_blocked_arq) else null
|
||||||
|
|
||||||
|
fun applyForward() {
|
||||||
|
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
|
||||||
|
settingsViewModel.applyForwardConfig(
|
||||||
|
serverId,
|
||||||
|
if (isTcp) ProxyMode.TCP else ProxyMode.UDP,
|
||||||
|
kcpDraft
|
||||||
|
)
|
||||||
|
onBack?.invoke()
|
||||||
|
}
|
||||||
|
|
||||||
fun persistWg(vpn: Boolean = isVpn) {
|
fun persistWg(vpn: Boolean = isVpn) {
|
||||||
clientEdit {
|
clientEdit {
|
||||||
it.copy(
|
it.copy(
|
||||||
@@ -169,6 +193,9 @@ fun ConnectionModeScreen(
|
|||||||
scrollBehavior = scrollBehavior
|
scrollBehavior = scrollBehavior
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
|
floatingActionButton = {
|
||||||
|
ApplyFab(visible = forwardVisible, blockedReason = applyBlocked, onApply = { applyForward() })
|
||||||
|
},
|
||||||
contentWindowInsets = WindowInsets(0, 0, 0, 0)
|
contentWindowInsets = WindowInsets(0, 0, 0, 0)
|
||||||
) { padding ->
|
) { padding ->
|
||||||
Column(
|
Column(
|
||||||
@@ -202,6 +229,10 @@ fun ConnectionModeScreen(
|
|||||||
HapticUtil.perform(context, HapticUtil.Pattern.TOGGLE_ON)
|
HapticUtil.perform(context, HapticUtil.Pattern.TOGGLE_ON)
|
||||||
userPickedVpn = true
|
userPickedVpn = true
|
||||||
persistWg(vpn = true)
|
persistWg(vpn = true)
|
||||||
|
// Встроенный туннель живёт только поверх udp: иначе сервер
|
||||||
|
// остался бы поднят в tcp и отклонял бы наши сессии.
|
||||||
|
isTcp = false
|
||||||
|
if (savedOpts.tcpMode) settingsViewModel.setProxyMode(serverId, ProxyMode.UDP)
|
||||||
},
|
},
|
||||||
shape = SegmentedButtonDefaults.itemShape(index = 1, count = 2)
|
shape = SegmentedButtonDefaults.itemShape(index = 1, count = 2)
|
||||||
) { Text(stringResource(R.string.mode_vpn)) }
|
) { Text(stringResource(R.string.mode_vpn)) }
|
||||||
@@ -213,7 +244,35 @@ fun ConnectionModeScreen(
|
|||||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
)
|
)
|
||||||
|
|
||||||
if (isVpn) {
|
if (!isVpn) {
|
||||||
|
SectionLabel(stringResource(R.string.forward_section))
|
||||||
|
SettingsCard {
|
||||||
|
SettingsFieldSlot {
|
||||||
|
UdpTcpSegmented(
|
||||||
|
tcp = isTcp,
|
||||||
|
onTcp = { isTcp = it },
|
||||||
|
label = stringResource(R.string.tcp_forward_mode)
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
stringResource(
|
||||||
|
if (isTcp) R.string.forward_tcp_desc else R.string.forward_udp_desc
|
||||||
|
),
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
stringResource(R.string.forward_server_match),
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
|
)
|
||||||
|
if (isTcp) InlineNoticeCard(stringResource(R.string.forward_tcp_foreign_vpn))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isTcp) {
|
||||||
|
KcpCard(profile = kcpDraft, onProfile = { kcpDraft = it })
|
||||||
|
}
|
||||||
|
} else {
|
||||||
WireGuardConfigCard(
|
WireGuardConfigCard(
|
||||||
wgConfig = wgConfig,
|
wgConfig = wgConfig,
|
||||||
onWgConfig = { wgConfig = it; wgDirty = true },
|
onWgConfig = { wgConfig = it; wgDirty = true },
|
||||||
@@ -235,7 +294,7 @@ fun ConnectionModeScreen(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Spacer(Modifier.height(24.dp))
|
Spacer(Modifier.height(if (forwardVisible) FabClearance else Spacing.xxl))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,177 @@
|
|||||||
|
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||||
|
|
||||||
|
package com.freeturn.app.ui.screens.connectionmode
|
||||||
|
|
||||||
|
import androidx.annotation.StringRes
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.text.KeyboardOptions
|
||||||
|
import androidx.compose.material3.DropdownMenuItem
|
||||||
|
import androidx.compose.material3.ExposedDropdownMenu
|
||||||
|
import androidx.compose.material3.ExposedDropdownMenuAnchorType
|
||||||
|
import androidx.compose.material3.ExposedDropdownMenuBox
|
||||||
|
import androidx.compose.material3.ExposedDropdownMenuDefaults
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.OutlinedTextField
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.text.input.KeyboardType
|
||||||
|
import com.freeturn.app.R
|
||||||
|
import com.freeturn.app.data.config.KcpPreset
|
||||||
|
import com.freeturn.app.data.config.KcpProfile
|
||||||
|
import com.freeturn.app.ui.components.LabeledTextField
|
||||||
|
import com.freeturn.app.ui.components.SectionLabel
|
||||||
|
import com.freeturn.app.ui.components.SettingsCard
|
||||||
|
import com.freeturn.app.ui.components.SettingsFieldSlot
|
||||||
|
import com.freeturn.app.ui.components.SettingsRowDivider
|
||||||
|
import com.freeturn.app.ui.components.SettingsSwitchRow
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ARQ tcp-режима: пресет и, для "Свои", восемь параметров ядра.
|
||||||
|
* Значения уходят и клиенту, и серверу - настраиваются один раз на пару.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
internal fun KcpCard(profile: KcpProfile, onProfile: (KcpProfile) -> Unit) {
|
||||||
|
// Флаг, а не производный пресет: ручные значения, совпавшие с дефолтом, иначе
|
||||||
|
// схлопывали бы поля обратно прямо во время ввода.
|
||||||
|
var pinnedCustom by remember { mutableStateOf(KcpPreset.of(profile) == KcpPreset.CUSTOM) }
|
||||||
|
val preset = if (pinnedCustom) KcpPreset.CUSTOM else KcpPreset.of(profile)
|
||||||
|
|
||||||
|
SectionLabel(stringResource(R.string.kcp_section))
|
||||||
|
SettingsCard {
|
||||||
|
SettingsFieldSlot {
|
||||||
|
PresetDropdown(preset) { picked ->
|
||||||
|
pinnedCustom = picked == KcpPreset.CUSTOM
|
||||||
|
when (picked) {
|
||||||
|
KcpPreset.STANDARD -> onProfile(KcpProfile.DEFAULT)
|
||||||
|
KcpPreset.MOBILE -> onProfile(KcpProfile.MOBILE)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Text(
|
||||||
|
stringResource(presetDescRes(preset)),
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (preset == KcpPreset.CUSTOM) {
|
||||||
|
SettingsRowDivider()
|
||||||
|
SettingsFieldSlot {
|
||||||
|
NumberField(profile.interval, R.string.kcp_interval_label) { onProfile(profile.copy(interval = it)) }
|
||||||
|
NumberField(
|
||||||
|
profile.resend,
|
||||||
|
R.string.kcp_resend_label,
|
||||||
|
errorRes = R.string.kcp_value_nonneg,
|
||||||
|
valid = profile.resend >= 0
|
||||||
|
) {
|
||||||
|
onProfile(profile.copy(resend = it))
|
||||||
|
}
|
||||||
|
NumberField(profile.sndWnd, R.string.kcp_sndwnd_label) { onProfile(profile.copy(sndWnd = it)) }
|
||||||
|
NumberField(profile.rcvWnd, R.string.kcp_rcvwnd_label) { onProfile(profile.copy(rcvWnd = it)) }
|
||||||
|
NumberField(
|
||||||
|
profile.mtu,
|
||||||
|
R.string.kcp_mtu_label,
|
||||||
|
supportingRes = R.string.kcp_mtu_support,
|
||||||
|
errorRes = R.string.kcp_mtu_invalid,
|
||||||
|
valid = profile.mtu in KcpProfile.MTU_MIN..KcpProfile.MTU_MAX
|
||||||
|
) { onProfile(profile.copy(mtu = it)) }
|
||||||
|
}
|
||||||
|
SettingsRowDivider()
|
||||||
|
SettingsSwitchRow(
|
||||||
|
title = stringResource(R.string.kcp_nodelay_title),
|
||||||
|
subtitle = stringResource(R.string.kcp_nodelay_desc),
|
||||||
|
checked = profile.noDelay == 1,
|
||||||
|
onCheckedChange = { onProfile(profile.copy(noDelay = if (it) 1 else 0)) }
|
||||||
|
)
|
||||||
|
SettingsRowDivider()
|
||||||
|
SettingsSwitchRow(
|
||||||
|
title = stringResource(R.string.kcp_nc_title),
|
||||||
|
subtitle = stringResource(R.string.kcp_nc_desc),
|
||||||
|
checked = profile.nc == 1,
|
||||||
|
onCheckedChange = { onProfile(profile.copy(nc = if (it) 1 else 0)) }
|
||||||
|
)
|
||||||
|
SettingsRowDivider()
|
||||||
|
SettingsSwitchRow(
|
||||||
|
title = stringResource(R.string.kcp_acknodelay_title),
|
||||||
|
subtitle = stringResource(R.string.kcp_acknodelay_desc),
|
||||||
|
checked = profile.ackNoDelay,
|
||||||
|
onCheckedChange = { onProfile(profile.copy(ackNoDelay = it)) }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun PresetDropdown(preset: String, onPreset: (String) -> Unit) {
|
||||||
|
var expanded by remember { mutableStateOf(false) }
|
||||||
|
|
||||||
|
ExposedDropdownMenuBox(
|
||||||
|
expanded = expanded,
|
||||||
|
onExpandedChange = { expanded = !expanded }
|
||||||
|
) {
|
||||||
|
OutlinedTextField(
|
||||||
|
value = stringResource(presetLabelRes(preset)),
|
||||||
|
onValueChange = {},
|
||||||
|
readOnly = true,
|
||||||
|
label = { Text(stringResource(R.string.kcp_preset_label)) },
|
||||||
|
trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) },
|
||||||
|
modifier = Modifier
|
||||||
|
.menuAnchor(ExposedDropdownMenuAnchorType.PrimaryNotEditable, true)
|
||||||
|
.fillMaxWidth()
|
||||||
|
)
|
||||||
|
ExposedDropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) {
|
||||||
|
KcpPreset.VALUES.forEach { value ->
|
||||||
|
DropdownMenuItem(
|
||||||
|
text = { Text(stringResource(presetLabelRes(value))) },
|
||||||
|
onClick = {
|
||||||
|
expanded = false
|
||||||
|
onPreset(value)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@StringRes
|
||||||
|
private fun presetLabelRes(preset: String): Int = when (preset) {
|
||||||
|
KcpPreset.STANDARD -> R.string.kcp_preset_standard
|
||||||
|
KcpPreset.MOBILE -> R.string.kcp_preset_mobile
|
||||||
|
else -> R.string.kcp_preset_custom
|
||||||
|
}
|
||||||
|
|
||||||
|
@StringRes
|
||||||
|
private fun presetDescRes(preset: String): Int = when (preset) {
|
||||||
|
KcpPreset.STANDARD -> R.string.kcp_preset_standard_desc
|
||||||
|
KcpPreset.MOBILE -> R.string.kcp_preset_mobile_desc
|
||||||
|
else -> R.string.kcp_preset_custom_desc
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Пустое поле не пишется в профиль: значение остаётся прежним до валидного ввода. */
|
||||||
|
@Composable
|
||||||
|
private fun NumberField(
|
||||||
|
value: Int,
|
||||||
|
@StringRes labelRes: Int,
|
||||||
|
@StringRes supportingRes: Int? = null,
|
||||||
|
@StringRes errorRes: Int = R.string.kcp_value_positive,
|
||||||
|
valid: Boolean = value > 0,
|
||||||
|
onValue: (Int) -> Unit
|
||||||
|
) {
|
||||||
|
var text by remember(value) { mutableStateOf(value.toString()) }
|
||||||
|
LabeledTextField(
|
||||||
|
value = text,
|
||||||
|
onValueChange = { raw ->
|
||||||
|
text = raw.filter { it.isDigit() }.take(5)
|
||||||
|
text.toIntOrNull()?.let(onValue)
|
||||||
|
},
|
||||||
|
labelRes = labelRes,
|
||||||
|
supportingRes = supportingRes,
|
||||||
|
errorRes = errorRes,
|
||||||
|
isError = !valid || text.isEmpty(),
|
||||||
|
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
|
||||||
|
)
|
||||||
|
}
|
||||||
+22
-22
@@ -9,8 +9,6 @@ import androidx.compose.animation.AnimatedVisibility
|
|||||||
import androidx.compose.animation.expandVertically
|
import androidx.compose.animation.expandVertically
|
||||||
import androidx.compose.animation.fadeIn
|
import androidx.compose.animation.fadeIn
|
||||||
import androidx.compose.animation.fadeOut
|
import androidx.compose.animation.fadeOut
|
||||||
import androidx.compose.animation.scaleIn
|
|
||||||
import androidx.compose.animation.scaleOut
|
|
||||||
import androidx.compose.animation.shrinkVertically
|
import androidx.compose.animation.shrinkVertically
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
import androidx.compose.foundation.layout.Box
|
import androidx.compose.foundation.layout.Box
|
||||||
@@ -27,7 +25,6 @@ import androidx.compose.foundation.rememberScrollState
|
|||||||
import androidx.compose.foundation.verticalScroll
|
import androidx.compose.foundation.verticalScroll
|
||||||
import androidx.compose.material3.DropdownMenu
|
import androidx.compose.material3.DropdownMenu
|
||||||
import androidx.compose.material3.DropdownMenuItem
|
import androidx.compose.material3.DropdownMenuItem
|
||||||
import androidx.compose.material3.ExtendedFloatingActionButton
|
|
||||||
import androidx.compose.material3.Icon
|
import androidx.compose.material3.Icon
|
||||||
import androidx.compose.material3.IconButton
|
import androidx.compose.material3.IconButton
|
||||||
import androidx.compose.material3.LargeFlexibleTopAppBar
|
import androidx.compose.material3.LargeFlexibleTopAppBar
|
||||||
@@ -51,14 +48,16 @@ import androidx.compose.ui.input.nestedscroll.nestedScroll
|
|||||||
import androidx.compose.ui.platform.LocalContext
|
import androidx.compose.ui.platform.LocalContext
|
||||||
import androidx.compose.ui.res.painterResource
|
import androidx.compose.ui.res.painterResource
|
||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
import androidx.compose.ui.unit.dp
|
|
||||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
import com.freeturn.app.R
|
import com.freeturn.app.R
|
||||||
import com.freeturn.app.data.config.HostPort
|
import com.freeturn.app.data.config.HostPort
|
||||||
import com.freeturn.app.data.config.ObfProfile
|
import com.freeturn.app.data.config.ObfProfile
|
||||||
|
import com.freeturn.app.data.config.ProxyMode
|
||||||
import com.freeturn.app.domain.ServerState
|
import com.freeturn.app.domain.ServerState
|
||||||
import com.freeturn.app.domain.SshConnectionState
|
import com.freeturn.app.domain.SshConnectionState
|
||||||
import com.freeturn.app.data.HapticUtil
|
import com.freeturn.app.data.HapticUtil
|
||||||
|
import com.freeturn.app.ui.components.ApplyFab
|
||||||
|
import com.freeturn.app.ui.components.FabClearance
|
||||||
import com.freeturn.app.ui.components.SettingsContentMaxWidth
|
import com.freeturn.app.ui.components.SettingsContentMaxWidth
|
||||||
import com.freeturn.app.ui.theme.Spacing
|
import com.freeturn.app.ui.theme.Spacing
|
||||||
import com.freeturn.app.ui.util.copyToClipboard
|
import com.freeturn.app.ui.util.copyToClipboard
|
||||||
@@ -98,6 +97,7 @@ fun ServerManagementScreen(
|
|||||||
}
|
}
|
||||||
var proxyListenPort by rememberSaveable(savedListen) { mutableStateOf(savedListen.substringAfterLast(":", "56000")) }
|
var proxyListenPort by rememberSaveable(savedListen) { mutableStateOf(savedListen.substringAfterLast(":", "56000")) }
|
||||||
var proxyConnect by rememberSaveable(savedConnect) { mutableStateOf(savedConnect) }
|
var proxyConnect by rememberSaveable(savedConnect) { mutableStateOf(savedConnect) }
|
||||||
|
var tcpDraft by rememberSaveable(effServer.tcpMode) { mutableStateOf(effServer.tcpMode) }
|
||||||
var obfDraft by rememberSaveable(effServer.obfProfile) { mutableStateOf(effServer.obfProfile) }
|
var obfDraft by rememberSaveable(effServer.obfProfile) { mutableStateOf(effServer.obfProfile) }
|
||||||
var keyDraft by rememberSaveable(effServer.obfKey) { mutableStateOf(effServer.obfKey) }
|
var keyDraft by rememberSaveable(effServer.obfKey) { mutableStateOf(effServer.obfKey) }
|
||||||
|
|
||||||
@@ -113,22 +113,29 @@ fun ServerManagementScreen(
|
|||||||
val listenFull = "${proxyListenIp.ifBlank { "0.0.0.0" }}:$proxyListenPort"
|
val listenFull = "${proxyListenIp.ifBlank { "0.0.0.0" }}:$proxyListenPort"
|
||||||
val proxyDirty = listenFull != savedListen || proxyConnect != savedConnect
|
val proxyDirty = listenFull != savedListen || proxyConnect != savedConnect
|
||||||
val configDirty = proxyDirty ||
|
val configDirty = proxyDirty ||
|
||||||
|
tcpDraft != effServer.tcpMode ||
|
||||||
obfDraft != effServer.obfProfile ||
|
obfDraft != effServer.obfProfile ||
|
||||||
keyDraft != effServer.obfKey
|
keyDraft != effServer.obfKey
|
||||||
val keyOkForApply = obfDraft == ObfProfile.NONE || keyDraft.isBlank() ||
|
val keyOkForApply = obfDraft == ObfProfile.NONE || keyDraft.isBlank() ||
|
||||||
ObfProfile.isValidKey(keyDraft)
|
ObfProfile.isValidKey(keyDraft)
|
||||||
val addressesOk = HostPort.isValid(listenFull) && HostPort.isValid(proxyConnect)
|
val addressesOk = HostPort.isValid(listenFull) && HostPort.isValid(proxyConnect)
|
||||||
|
|
||||||
val canApply = serverSettingsAvailable(isConnected, syncOn) &&
|
val applyVisible = serverSettingsAvailable(isConnected, syncOn) && configDirty
|
||||||
configDirty && keyOkForApply && addressesOk && !isWorking
|
val applyBlocked = when {
|
||||||
|
isWorking -> stringResource(R.string.apply_blocked_busy)
|
||||||
|
!addressesOk -> stringResource(R.string.apply_blocked_address)
|
||||||
|
!keyOkForApply -> stringResource(R.string.apply_blocked_key)
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
fun applyConfig() {
|
fun applyConfig() {
|
||||||
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
|
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
|
||||||
// Активный - apply в живой рантайм (один рестарт). Неактивный - пишем только снимок сервера.
|
// Активный - apply в живой рантайм (один рестарт). Неактивный - пишем только снимок сервера.
|
||||||
|
val mode = if (tcpDraft) ProxyMode.TCP else ProxyMode.UDP
|
||||||
if (isActive) {
|
if (isActive) {
|
||||||
settingsViewModel.applyServerConfig(listenFull, proxyConnect, obfDraft, keyDraft)
|
settingsViewModel.applyServerConfig(listenFull, proxyConnect, mode, obfDraft, keyDraft)
|
||||||
} else {
|
} else {
|
||||||
// !isActive ⇒ serverId != null (см. isActive выше) - smart cast.
|
// !isActive ⇒ serverId != null (см. isActive выше) - smart cast.
|
||||||
settingsViewModel.updateServerConfig(serverId, listenFull, proxyConnect, obfDraft, keyDraft)
|
settingsViewModel.updateServerConfig(serverId, listenFull, proxyConnect, mode, obfDraft, keyDraft)
|
||||||
}
|
}
|
||||||
onBack()
|
onBack()
|
||||||
}
|
}
|
||||||
@@ -179,17 +186,7 @@ fun ServerManagementScreen(
|
|||||||
},
|
},
|
||||||
snackbarHost = { SnackbarHost(snackbarHostState) },
|
snackbarHost = { SnackbarHost(snackbarHostState) },
|
||||||
floatingActionButton = {
|
floatingActionButton = {
|
||||||
AnimatedVisibility(
|
ApplyFab(visible = applyVisible, blockedReason = applyBlocked, onApply = { applyConfig() })
|
||||||
visible = canApply,
|
|
||||||
enter = scaleIn() + fadeIn(),
|
|
||||||
exit = scaleOut() + fadeOut()
|
|
||||||
) {
|
|
||||||
ExtendedFloatingActionButton(
|
|
||||||
onClick = { applyConfig() },
|
|
||||||
icon = { Icon(painterResource(R.drawable.check_circle_24px), contentDescription = null) },
|
|
||||||
text = { Text(stringResource(R.string.server_apply)) }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
contentWindowInsets = WindowInsets(0, 0, 0, 0)
|
contentWindowInsets = WindowInsets(0, 0, 0, 0)
|
||||||
) { padding ->
|
) { padding ->
|
||||||
@@ -219,7 +216,7 @@ fun ServerManagementScreen(
|
|||||||
settingsViewModel.applyServer(serverId)
|
settingsViewModel.applyServer(serverId)
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
Spacer(Modifier.height(24.dp))
|
Spacer(Modifier.height(Spacing.xxl))
|
||||||
return@Column
|
return@Column
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -243,7 +240,7 @@ fun ServerManagementScreen(
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
Spacer(Modifier.height(24.dp))
|
Spacer(Modifier.height(Spacing.xxl))
|
||||||
return@Column
|
return@Column
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -280,6 +277,9 @@ fun ServerManagementScreen(
|
|||||||
// Гейт общий со входом в экран (ServerDetailScreen) - serverSettingsAvailable.
|
// Гейт общий со входом в экран (ServerDetailScreen) - serverSettingsAvailable.
|
||||||
if (serverSettingsAvailable(isConnected, syncOn)) {
|
if (serverSettingsAvailable(isConnected, syncOn)) {
|
||||||
ServerSyncCard(
|
ServerSyncCard(
|
||||||
|
tcp = tcpDraft,
|
||||||
|
onTcp = { tcpDraft = it },
|
||||||
|
tcpBlocked = effClient.wireGuardActive,
|
||||||
obfProfile = obfDraft,
|
obfProfile = obfDraft,
|
||||||
onObfProfile = { HapticUtil.perform(context, HapticUtil.Pattern.TOGGLE_ON); obfDraft = it },
|
onObfProfile = { HapticUtil.perform(context, HapticUtil.Pattern.TOGGLE_ON); obfDraft = it },
|
||||||
keyDraft = keyDraft,
|
keyDraft = keyDraft,
|
||||||
@@ -297,7 +297,7 @@ fun ServerManagementScreen(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
Spacer(Modifier.height(if (canApply) 88.dp else 24.dp))
|
Spacer(Modifier.height(if (applyVisible) FabClearance else Spacing.xxl))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,15 +29,19 @@ import com.freeturn.app.ui.components.SettingsCard
|
|||||||
import com.freeturn.app.ui.components.SettingsControlLabel
|
import com.freeturn.app.ui.components.SettingsControlLabel
|
||||||
import com.freeturn.app.ui.components.SettingsFieldSlot
|
import com.freeturn.app.ui.components.SettingsFieldSlot
|
||||||
import com.freeturn.app.ui.components.SettingsRowDivider
|
import com.freeturn.app.ui.components.SettingsRowDivider
|
||||||
|
import com.freeturn.app.ui.components.UdpTcpSegmented
|
||||||
import com.freeturn.app.ui.util.redact
|
import com.freeturn.app.ui.util.redact
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Синхронные серверные настройки (apply-модель): профиль обфускации и obf-ключ
|
* Синхронные серверные настройки (apply-модель): проброс UDP/TCP, профиль обфускации и
|
||||||
* (черновик). Регенерация/копирование ключа - через колбэки; рестарт случается
|
* obf-ключ (черновик). Регенерация/копирование ключа - через колбэки; рестарт случается
|
||||||
* по общей кнопке "Применить" на экране.
|
* по общей кнопке "Применить" на экране.
|
||||||
*/
|
*/
|
||||||
@Composable
|
@Composable
|
||||||
internal fun ServerSyncCard(
|
internal fun ServerSyncCard(
|
||||||
|
tcp: Boolean,
|
||||||
|
onTcp: (Boolean) -> Unit,
|
||||||
|
tcpBlocked: Boolean,
|
||||||
obfProfile: String,
|
obfProfile: String,
|
||||||
onObfProfile: (String) -> Unit,
|
onObfProfile: (String) -> Unit,
|
||||||
keyDraft: String,
|
keyDraft: String,
|
||||||
@@ -49,7 +53,16 @@ internal fun ServerSyncCard(
|
|||||||
) {
|
) {
|
||||||
SectionLabel(stringResource(R.string.server_sync_section))
|
SectionLabel(stringResource(R.string.server_sync_section))
|
||||||
SettingsCard {
|
SettingsCard {
|
||||||
// Профиль обфускации.
|
SettingsFieldSlot {
|
||||||
|
UdpTcpSegmented(
|
||||||
|
tcp = tcp,
|
||||||
|
onTcp = onTcp,
|
||||||
|
label = stringResource(R.string.tcp_forward_mode),
|
||||||
|
// Ядро поднимает туннель только поверх udp-проброса.
|
||||||
|
tcpDisabledReason = if (tcpBlocked) stringResource(R.string.tcp_blocked_by_tunnel) else null
|
||||||
|
)
|
||||||
|
}
|
||||||
|
SettingsRowDivider()
|
||||||
SettingsFieldSlot {
|
SettingsFieldSlot {
|
||||||
SettingsControlLabel(stringResource(R.string.obf_profile_title))
|
SettingsControlLabel(stringResource(R.string.obf_profile_title))
|
||||||
ObfProfileDropdown(obfProfile = obfProfile, onObfProfile = onObfProfile)
|
ObfProfileDropdown(obfProfile = obfProfile, onObfProfile = onObfProfile)
|
||||||
|
|||||||
@@ -209,6 +209,10 @@ private fun CoreStateCard(online: ServerHubState.Online, privacyMode: Boolean) {
|
|||||||
else -> R.string.nerd_state_running
|
else -> R.string.nerd_state_running
|
||||||
}
|
}
|
||||||
NerdStateRow(stringResource(R.string.nerd_state_label), stringResource(stateRes))
|
NerdStateRow(stringResource(R.string.nerd_state_label), stringResource(stateRes))
|
||||||
|
// Режим живого сервера: рассинхрон с клиентом сервер молча отклоняет.
|
||||||
|
online.mode?.takeIf { it.isNotBlank() }?.let {
|
||||||
|
NerdStateRow(stringResource(R.string.tcp_forward_mode), it.uppercase())
|
||||||
|
}
|
||||||
online.version?.takeIf { it.isNotBlank() }?.let {
|
online.version?.takeIf { it.isNotBlank() }?.let {
|
||||||
NerdStateRow(stringResource(R.string.nerd_version_label), versionLabel(it), mono = true)
|
NerdStateRow(stringResource(R.string.nerd_version_label), versionLabel(it), mono = true)
|
||||||
}
|
}
|
||||||
@@ -285,6 +289,8 @@ private fun serverCommandLine(server: Server, privacy: Boolean): String {
|
|||||||
val opts = ServerStartOptions(
|
val opts = ServerStartOptions(
|
||||||
listen = server.proxyListen,
|
listen = server.proxyListen,
|
||||||
connect = server.proxyConnect,
|
connect = server.proxyConnect,
|
||||||
|
proxyMode = server.opts.proxyMode,
|
||||||
|
kcp = server.opts.kcp,
|
||||||
obfProfile = if (server.opts.obfEnabled) server.opts.obfProfile else ObfProfile.NONE,
|
obfProfile = if (server.opts.obfEnabled) server.opts.obfProfile else ObfProfile.NONE,
|
||||||
obfKey = if (server.opts.obfEnabled) server.opts.obfKey else ""
|
obfKey = if (server.opts.obfEnabled) server.opts.obfKey else ""
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -49,6 +49,7 @@ import com.freeturn.app.ui.components.SettingsCard
|
|||||||
import com.freeturn.app.ui.components.SettingsEntryRow
|
import com.freeturn.app.ui.components.SettingsEntryRow
|
||||||
import com.freeturn.app.ui.components.SettingsFieldSlot
|
import com.freeturn.app.ui.components.SettingsFieldSlot
|
||||||
import com.freeturn.app.ui.components.SettingsRowDivider
|
import com.freeturn.app.ui.components.SettingsRowDivider
|
||||||
|
import com.freeturn.app.ui.components.UdpTcpSegmented
|
||||||
import com.freeturn.app.ui.theme.LocalReducedMotion
|
import com.freeturn.app.ui.theme.LocalReducedMotion
|
||||||
import com.freeturn.app.ui.theme.extendedColorScheme
|
import com.freeturn.app.ui.theme.extendedColorScheme
|
||||||
import com.freeturn.app.viewmodel.server.SetupConfigDraft
|
import com.freeturn.app.viewmodel.server.SetupConfigDraft
|
||||||
@@ -207,6 +208,16 @@ fun SetupConfigStep(
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
SettingsFieldSlot {
|
SettingsFieldSlot {
|
||||||
|
UdpTcpSegmented(
|
||||||
|
tcp = draft.backendTcp,
|
||||||
|
onTcp = { onDraftChange(draft.copy(backendTcp = it)) },
|
||||||
|
label = stringResource(R.string.setup_backend_protocol_label)
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
stringResource(R.string.setup_backend_protocol_desc),
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
|
)
|
||||||
BackendPortField(draft, showErrors, onDraftChange)
|
BackendPortField(draft, showErrors, onDraftChange)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ sealed interface ServerHubState {
|
|||||||
data class Online(
|
data class Online(
|
||||||
val running: Boolean,
|
val running: Boolean,
|
||||||
val installed: Boolean,
|
val installed: Boolean,
|
||||||
|
val mode: String?,
|
||||||
val obfProfile: String?,
|
val obfProfile: String?,
|
||||||
val version: String?,
|
val version: String?,
|
||||||
val sshIp: String
|
val sshIp: String
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import androidx.lifecycle.viewModelScope
|
|||||||
import com.freeturn.app.data.AppPreferences
|
import com.freeturn.app.data.AppPreferences
|
||||||
import com.freeturn.app.data.config.ClientConfig
|
import com.freeturn.app.data.config.ClientConfig
|
||||||
import com.freeturn.app.data.config.ObfProfile
|
import com.freeturn.app.data.config.ObfProfile
|
||||||
|
import com.freeturn.app.data.config.ProxyMode
|
||||||
import com.freeturn.app.data.server.Server
|
import com.freeturn.app.data.server.Server
|
||||||
import com.freeturn.app.data.server.ServerOpts
|
import com.freeturn.app.data.server.ServerOpts
|
||||||
import com.freeturn.app.data.config.SshConfig
|
import com.freeturn.app.data.config.SshConfig
|
||||||
@@ -69,6 +70,7 @@ data class SetupConfigDraft(
|
|||||||
val wgCustomConf: Boolean = false,
|
val wgCustomConf: Boolean = false,
|
||||||
val wgConfText: String = "",
|
val wgConfText: String = "",
|
||||||
val backendPort: String = "",
|
val backendPort: String = "",
|
||||||
|
val backendTcp: Boolean = false,
|
||||||
val vkLink: String = ""
|
val vkLink: String = ""
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -99,7 +101,10 @@ data class SetupUiState(
|
|||||||
val config: SetupConfigDraft = SetupConfigDraft(),
|
val config: SetupConfigDraft = SetupConfigDraft(),
|
||||||
val install: SetupInstallState? = null
|
val install: SetupInstallState? = null
|
||||||
) {
|
) {
|
||||||
/** Внешний порт совпал с портом бэкенда на том же хосте - оба бинда конфликтуют. */
|
/**
|
||||||
|
* Внешний порт совпал с UDP-портом бэкенда на том же хосте - оба бинда
|
||||||
|
* конфликтуют. TCP-бэкенд (Xray/sing-box) с UDP-listen не пересекается.
|
||||||
|
*/
|
||||||
val portsClash: Boolean
|
val portsClash: Boolean
|
||||||
get() {
|
get() {
|
||||||
val listen = config.listenPort.toIntOrNull() ?: return false
|
val listen = config.listenPort.toIntOrNull() ?: return false
|
||||||
@@ -107,7 +112,8 @@ data class SetupUiState(
|
|||||||
config.vpnMode && config.wgCustomConf -> config.backendPort.toIntOrNull()
|
config.vpnMode && config.wgCustomConf -> config.backendPort.toIntOrNull()
|
||||||
config.vpnMode && wgDetectedPort == null -> config.wgPort.toIntOrNull()
|
config.vpnMode && wgDetectedPort == null -> config.wgPort.toIntOrNull()
|
||||||
config.vpnMode -> wgDetectedPort
|
config.vpnMode -> wgDetectedPort
|
||||||
else -> config.backendPort.toIntOrNull()
|
!config.backendTcp -> config.backendPort.toIntOrNull()
|
||||||
|
else -> null
|
||||||
}
|
}
|
||||||
return backend != null && backend == listen
|
return backend != null && backend == listen
|
||||||
}
|
}
|
||||||
@@ -290,6 +296,7 @@ class ServerSetupViewModel(
|
|||||||
ServerStartOptions(
|
ServerStartOptions(
|
||||||
listen = "0.0.0.0:${c.listenPort}",
|
listen = "0.0.0.0:${c.listenPort}",
|
||||||
connect = "127.0.0.1:$backendPort",
|
connect = "127.0.0.1:$backendPort",
|
||||||
|
proxyMode = if (!c.vpnMode && c.backendTcp) ProxyMode.TCP else ProxyMode.UDP,
|
||||||
obfProfile = c.obfProfile,
|
obfProfile = c.obfProfile,
|
||||||
obfKey = if (obfOn) obfKey else "",
|
obfKey = if (obfOn) obfKey else "",
|
||||||
// Авторизация по allowlist с первого запуска: владелец сидится
|
// Авторизация по allowlist с первого запуска: владелец сидится
|
||||||
@@ -346,7 +353,8 @@ class ServerSetupViewModel(
|
|||||||
proxyConnect = "127.0.0.1:$backendPort",
|
proxyConnect = "127.0.0.1:$backendPort",
|
||||||
opts = ServerOpts(
|
opts = ServerOpts(
|
||||||
obfProfile = c.obfProfile,
|
obfProfile = c.obfProfile,
|
||||||
obfKey = if (c.obfProfile != ObfProfile.NONE) obfKey else ""
|
obfKey = if (c.obfProfile != ObfProfile.NONE) obfKey else "",
|
||||||
|
proxyMode = if (!c.vpnMode && c.backendTcp) ProxyMode.TCP else ProxyMode.UDP
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -52,6 +52,7 @@ class ServerViewModel(
|
|||||||
ServerHubState.Online(
|
ServerHubState.Online(
|
||||||
running = server.running,
|
running = server.running,
|
||||||
installed = server.installed,
|
installed = server.installed,
|
||||||
|
mode = server.mode,
|
||||||
obfProfile = server.obfProfile,
|
obfProfile = server.obfProfile,
|
||||||
version = server.version,
|
version = server.version,
|
||||||
sshIp = ssh.ip
|
sshIp = ssh.ip
|
||||||
@@ -116,6 +117,8 @@ class ServerViewModel(
|
|||||||
val opts = prefs.serverOptsFlow.first()
|
val opts = prefs.serverOptsFlow.first()
|
||||||
sshRepository.startServer(
|
sshRepository.startServer(
|
||||||
listen = l, connect = c,
|
listen = l, connect = c,
|
||||||
|
proxyMode = opts.proxyMode,
|
||||||
|
kcp = opts.kcp,
|
||||||
obfProfile = if (opts.obfEnabled) opts.obfProfile else "none",
|
obfProfile = if (opts.obfEnabled) opts.obfProfile else "none",
|
||||||
obfKey = if (opts.obfEnabled) opts.obfKey else "",
|
obfKey = if (opts.obfEnabled) opts.obfKey else "",
|
||||||
clientId = prefs.ownClientId()
|
clientId = prefs.ownClientId()
|
||||||
|
|||||||
@@ -8,9 +8,11 @@ import androidx.lifecycle.viewModelScope
|
|||||||
import com.freeturn.app.data.AppPreferences
|
import com.freeturn.app.data.AppPreferences
|
||||||
import com.freeturn.app.data.backup.BackupCrypto
|
import com.freeturn.app.data.backup.BackupCrypto
|
||||||
import com.freeturn.app.data.config.ClientConfig
|
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.ObfProfile
|
||||||
import com.freeturn.app.data.control.UninstallData
|
import com.freeturn.app.data.control.UninstallData
|
||||||
import com.freeturn.app.data.server.Server
|
import com.freeturn.app.data.server.Server
|
||||||
|
import com.freeturn.app.data.server.ServerOpts
|
||||||
import com.freeturn.app.data.server.ServersSnapshot
|
import com.freeturn.app.data.server.ServersSnapshot
|
||||||
import com.freeturn.app.domain.backup.BackupManager
|
import com.freeturn.app.domain.backup.BackupManager
|
||||||
import com.freeturn.app.domain.update.AppUpdater
|
import com.freeturn.app.domain.update.AppUpdater
|
||||||
@@ -287,25 +289,54 @@ class SettingsViewModel(
|
|||||||
it.copy(client = it.client.copy(syncServerSwitches = enabled))
|
it.copy(client = it.client.copy(syncServerSwitches = enabled))
|
||||||
}
|
}
|
||||||
if (!changed) return@launch
|
if (!changed) return@launch
|
||||||
// NonCancellable не даёт новому переключению оборвать SSH-команду на полпути.
|
scheduleServerSync()
|
||||||
syncSideEffectJob?.cancel()
|
}
|
||||||
syncSideEffectJob = viewModelScope.launch {
|
}
|
||||||
delay(syncSideEffectDebounceMs)
|
|
||||||
syncSideEffectMutex.withLock {
|
/** Отложенный рестарт пары сервер+клиент: правки летят пачками, SSH-команда - одна. */
|
||||||
if (!prefs.clientConfigFlow.first().syncServerSwitches) return@withLock
|
private fun scheduleServerSync() {
|
||||||
withContext(NonCancellable) {
|
// NonCancellable не даёт новому переключению оборвать SSH-команду на полпути.
|
||||||
orchestrator.restartServerIfRunning()
|
syncSideEffectJob?.cancel()
|
||||||
orchestrator.restartProxyIfRunning()
|
syncSideEffectJob = viewModelScope.launch {
|
||||||
}
|
delay(syncSideEffectDebounceMs)
|
||||||
|
syncSideEffectMutex.withLock {
|
||||||
|
if (!prefs.clientConfigFlow.first().syncServerSwitches) return@withLock
|
||||||
|
withContext(NonCancellable) {
|
||||||
|
orchestrator.restartServerIfRunning()
|
||||||
|
orchestrator.restartProxyIfRunning()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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) }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Режим и ARQ обязаны совпадать с сервером, поэтому правка активного сервера
|
||||||
|
* тянет за собой рестарт обеих сторон - как в apply-модели экрана сервера.
|
||||||
|
*/
|
||||||
|
private fun updateOpts(id: String?, transform: (ServerOpts) -> ServerOpts) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
val changed = if (id == null) {
|
||||||
|
prefs.updateActiveServer { it.copy(opts = transform(it.opts)) }
|
||||||
|
} else {
|
||||||
|
prefs.updateServer(id) { it.copy(opts = transform(it.opts)) }
|
||||||
|
}
|
||||||
|
if (!changed) return@launch
|
||||||
|
if (id != null && id != prefs.serversSnapshot.first().activeId) return@launch
|
||||||
|
scheduleServerSync()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Одна транзакция и один рестарт сохраняют атомарность apply-модели.
|
// Одна транзакция и один рестарт сохраняют атомарность apply-модели.
|
||||||
fun applyServerConfig(
|
fun applyServerConfig(
|
||||||
listen: String,
|
listen: String,
|
||||||
connect: String,
|
connect: String,
|
||||||
|
proxyMode: String,
|
||||||
obfProfile: String,
|
obfProfile: String,
|
||||||
obfKey: String
|
obfKey: String
|
||||||
) {
|
) {
|
||||||
@@ -321,7 +352,7 @@ class SettingsViewModel(
|
|||||||
s.copy(
|
s.copy(
|
||||||
proxyListen = listen,
|
proxyListen = listen,
|
||||||
proxyConnect = connect,
|
proxyConnect = connect,
|
||||||
opts = s.opts.copy(obfProfile = obfProfile, obfKey = effKey)
|
opts = s.opts.copy(proxyMode = proxyMode, obfProfile = obfProfile, obfKey = effKey)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
if (changed) {
|
if (changed) {
|
||||||
@@ -340,6 +371,7 @@ class SettingsViewModel(
|
|||||||
id: String,
|
id: String,
|
||||||
listen: String,
|
listen: String,
|
||||||
connect: String,
|
connect: String,
|
||||||
|
proxyMode: String,
|
||||||
obfProfile: String,
|
obfProfile: String,
|
||||||
obfKey: String
|
obfKey: String
|
||||||
) {
|
) {
|
||||||
@@ -353,7 +385,7 @@ class SettingsViewModel(
|
|||||||
target.copy(
|
target.copy(
|
||||||
proxyListen = listen,
|
proxyListen = listen,
|
||||||
proxyConnect = connect,
|
proxyConnect = connect,
|
||||||
opts = target.opts.copy(obfProfile = obfProfile, obfKey = effKey)
|
opts = target.opts.copy(proxyMode = proxyMode, obfProfile = obfProfile, obfKey = effKey)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,9 @@ import androidx.lifecycle.ViewModel
|
|||||||
import androidx.lifecycle.viewModelScope
|
import androidx.lifecycle.viewModelScope
|
||||||
import com.freeturn.app.data.AppPreferences
|
import com.freeturn.app.data.AppPreferences
|
||||||
import com.freeturn.app.data.config.ClientConfig
|
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.ObfProfile
|
||||||
|
import com.freeturn.app.data.config.ProxyMode
|
||||||
import com.freeturn.app.data.server.Server
|
import com.freeturn.app.data.server.Server
|
||||||
import com.freeturn.app.data.server.ServerOpts
|
import com.freeturn.app.data.server.ServerOpts
|
||||||
import com.freeturn.app.data.config.SshConfig
|
import com.freeturn.app.data.config.SshConfig
|
||||||
@@ -131,7 +133,9 @@ class ImportViewModel(
|
|||||||
),
|
),
|
||||||
opts = ServerOpts(
|
opts = ServerOpts(
|
||||||
obfProfile = link.obfProfile.ifBlank { ObfProfile.NONE },
|
obfProfile = link.obfProfile.ifBlank { ObfProfile.NONE },
|
||||||
obfKey = link.obfKey
|
obfKey = link.obfKey,
|
||||||
|
proxyMode = if (link.mode == ProxyMode.TCP) ProxyMode.TCP else ProxyMode.UDP,
|
||||||
|
kcp = link.kcp ?: KcpProfile.DEFAULT
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -114,7 +114,7 @@
|
|||||||
<string name="setup_checking_ssh_desc">Проверка окружения сервера</string>
|
<string name="setup_checking_ssh_desc">Проверка окружения сервера</string>
|
||||||
<string name="setup_mode_section">Режим работы</string>
|
<string name="setup_mode_section">Режим работы</string>
|
||||||
<string name="setup_mode_vpn_desc">Поднимем WireGuard на сервере - весь трафик устройства пойдёт через туннель.</string>
|
<string name="setup_mode_vpn_desc">Поднимем WireGuard на сервере - весь трафик устройства пойдёт через туннель.</string>
|
||||||
<string name="setup_mode_proxy_desc">Прокси перенаправляет трафик на ваш UDP-бэкенд на сервере: WireGuard или AmneziaWG.</string>
|
<string name="setup_mode_proxy_desc">Прокси перенаправляет трафик на ваш бэкенд на сервере: WireGuard или Xray.</string>
|
||||||
<string name="setup_wg_found">WireGuard найден</string>
|
<string name="setup_wg_found">WireGuard найден</string>
|
||||||
<string name="setup_wg_found_desc">Порт %1$d станет бэкендом. Для этого устройства добавится отдельный пир - конфиг подставится сам.</string>
|
<string name="setup_wg_found_desc">Порт %1$d станет бэкендом. Для этого устройства добавится отдельный пир - конфиг подставится сам.</string>
|
||||||
<string name="setup_wg_missing">WireGuard не найден</string>
|
<string name="setup_wg_missing">WireGuard не найден</string>
|
||||||
@@ -128,6 +128,8 @@
|
|||||||
<string name="setup_port_roll">Сгенерировать порт</string>
|
<string name="setup_port_roll">Сгенерировать порт</string>
|
||||||
<string name="setup_backend_port_label">Порт бэкенда</string>
|
<string name="setup_backend_port_label">Порт бэкенда</string>
|
||||||
<string name="setup_backend_port_desc">Локальный порт вашего VPN/бэкенда на сервере (127.0.0.1)</string>
|
<string name="setup_backend_port_desc">Локальный порт вашего VPN/бэкенда на сервере (127.0.0.1)</string>
|
||||||
|
<string name="setup_backend_protocol_label">Протокол бэкенда</string>
|
||||||
|
<string name="setup_backend_protocol_desc">UDP - WireGuard/AmneziaWG, TCP - Xray</string>
|
||||||
<string name="setup_turn_section">TURN-прокси</string>
|
<string name="setup_turn_section">TURN-прокси</string>
|
||||||
<string name="setup_listen_port_desc">Внешний UDP-порт сервера, случайный из диапазона 56000–56999</string>
|
<string name="setup_listen_port_desc">Внешний UDP-порт сервера, случайный из диапазона 56000–56999</string>
|
||||||
<string name="setup_obf_hint_rtpopus">Трафик маскируется под голосовой звонок. Ключ сгенерируется и подставится автоматически.</string>
|
<string name="setup_obf_hint_rtpopus">Трафик маскируется под голосовой звонок. Ключ сгенерируется и подставится автоматически.</string>
|
||||||
@@ -202,6 +204,8 @@
|
|||||||
<string name="streams_per_cred_recommendation">Сколько TURN-потоков обслуживает один VK-аккаунт</string>
|
<string name="streams_per_cred_recommendation">Сколько TURN-потоков обслуживает один VK-аккаунт</string>
|
||||||
<string name="streams_per_cred_format">Потоков на аккаунт: %1$d</string>
|
<string name="streams_per_cred_format">Потоков на аккаунт: %1$d</string>
|
||||||
|
|
||||||
|
<string name="tcp_forward_mode">Режим</string>
|
||||||
|
<string name="tcp_blocked_by_tunnel">Туннель работает только поверх UDP-проброса</string>
|
||||||
<string name="obf_profile_title">Обфускация</string>
|
<string name="obf_profile_title">Обфускация</string>
|
||||||
<string name="obf_none">Выкл</string>
|
<string name="obf_none">Выкл</string>
|
||||||
<string name="obf_rtpopus">rtpopus</string>
|
<string name="obf_rtpopus">rtpopus</string>
|
||||||
@@ -247,7 +251,7 @@
|
|||||||
<string name="listen_ip_desc">IP-адрес, который прослушивает сервер. 0.0.0.0 - все интерфейсы. Укажите конкретный WAN IP, если на хосте несколько адресов.</string>
|
<string name="listen_ip_desc">IP-адрес, который прослушивает сервер. 0.0.0.0 - все интерфейсы. Укажите конкретный WAN IP, если на хосте несколько адресов.</string>
|
||||||
<string name="turn_client_address">Адрес TURN-клиента</string>
|
<string name="turn_client_address">Адрес TURN-клиента</string>
|
||||||
<string name="turn_client_placeholder">127.0.0.1:40537</string>
|
<string name="turn_client_placeholder">127.0.0.1:40537</string>
|
||||||
<string name="turn_client_desc">Локальный WireGuard-бэкенд на стороне сервера</string>
|
<string name="turn_client_desc">Локальный WireGuard/Xray-бэкенд на стороне сервера</string>
|
||||||
<string name="server_install">Установить</string>
|
<string name="server_install">Установить</string>
|
||||||
<string name="server_update">Обновить</string>
|
<string name="server_update">Обновить</string>
|
||||||
<string name="server_obf_key_label">Obf-ключ (64 hex)</string>
|
<string name="server_obf_key_label">Obf-ключ (64 hex)</string>
|
||||||
@@ -463,6 +467,10 @@
|
|||||||
<string name="pill_offline">Сервер неактивен</string>
|
<string name="pill_offline">Сервер неактивен</string>
|
||||||
<string name="not_paired_hint">У сервера нет SSH-сопряжения: управление им из приложения недоступно, клиентские настройки работают.</string>
|
<string name="not_paired_hint">У сервера нет SSH-сопряжения: управление им из приложения недоступно, клиентские настройки работают.</string>
|
||||||
<string name="server_apply">Применить</string>
|
<string name="server_apply">Применить</string>
|
||||||
|
<string name="apply_blocked_arq">Исправьте значения ARQ</string>
|
||||||
|
<string name="apply_blocked_address">Проверьте адреса прослушивания и бэкенда</string>
|
||||||
|
<string name="apply_blocked_key">Проверьте obf-ключ</string>
|
||||||
|
<string name="apply_blocked_busy">Дождитесь операции на сервере</string>
|
||||||
<string name="server_inactive_title">Сервер не активен</string>
|
<string name="server_inactive_title">Сервер не активен</string>
|
||||||
<string name="server_inactive_desc">Чтобы управлять ядром и SSH-подключением, сделайте этот сервер активным.</string>
|
<string name="server_inactive_desc">Чтобы управлять ядром и SSH-подключением, сделайте этот сервер активным.</string>
|
||||||
<string name="make_active">Сделать активным</string>
|
<string name="make_active">Сделать активным</string>
|
||||||
@@ -481,6 +489,35 @@
|
|||||||
<string name="mode_vpn">VPN</string>
|
<string name="mode_vpn">VPN</string>
|
||||||
<string name="mode_proxy_desc">Трафик идёт через локальный прокси, без туннеля.</string>
|
<string name="mode_proxy_desc">Трафик идёт через локальный прокси, без туннеля.</string>
|
||||||
<string name="mode_vpn_desc">Весь трафик устройства туннелируется через WireGuard.</string>
|
<string name="mode_vpn_desc">Весь трафик устройства туннелируется через WireGuard.</string>
|
||||||
|
<string name="forward_section">Проброс</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>
|
||||||
|
<string name="forward_server_match">Сервер должен быть запущен в том же режиме, иначе он отклонит сессию.</string>
|
||||||
|
|
||||||
|
<string name="kcp_section">Профиль ARQ</string>
|
||||||
|
<string name="kcp_preset_label">Профиль</string>
|
||||||
|
<string name="kcp_preset_standard">Стандарт</string>
|
||||||
|
<string name="kcp_preset_mobile">Мобильный</string>
|
||||||
|
<string name="kcp_preset_custom">Свои</string>
|
||||||
|
<string name="kcp_preset_standard_desc">Дефолт ядра: минимальная задержка, больше служебного трафика.</string>
|
||||||
|
<string name="kcp_preset_mobile_desc">Щадящий для сотовой сети: реже опрос, окна меньше, ACK пачками.</string>
|
||||||
|
<string name="kcp_preset_custom_desc">Значения задаются вручную; применяются к клиенту и к серверу.</string>
|
||||||
|
<string name="kcp_interval_label">Интервал цикла, мс</string>
|
||||||
|
<string name="kcp_resend_label">Быстрый ресенд, дублей ACK</string>
|
||||||
|
<string name="kcp_sndwnd_label">Окно отправки, пакетов</string>
|
||||||
|
<string name="kcp_rcvwnd_label">Окно приёма, пакетов</string>
|
||||||
|
<string name="kcp_mtu_label">MTU сегмента, байт</string>
|
||||||
|
<string name="kcp_mtu_support">Допустимо 300–1350</string>
|
||||||
|
<string name="kcp_nodelay_title">Быстрый режим</string>
|
||||||
|
<string name="kcp_nodelay_desc">Отправка без задержки накопления</string>
|
||||||
|
<string name="kcp_nc_title">Без контроля перегрузки</string>
|
||||||
|
<string name="kcp_nc_desc">Не сбрасывать окно при потерях</string>
|
||||||
|
<string name="kcp_acknodelay_title">ACK сразу</string>
|
||||||
|
<string name="kcp_acknodelay_desc">Ниже задержка, выше служебный трафик</string>
|
||||||
|
<string name="kcp_value_positive">Нужно число больше нуля</string>
|
||||||
|
<string name="kcp_value_nonneg">Нужно 0 или больше</string>
|
||||||
|
<string name="kcp_mtu_invalid">Нужно значение от 300 до 1350</string>
|
||||||
<string name="load_wg_conf">Загрузить из файла</string>
|
<string name="load_wg_conf">Загрузить из файла</string>
|
||||||
<string name="connection_config_section">Конфигурация туннеля</string>
|
<string name="connection_config_section">Конфигурация туннеля</string>
|
||||||
<string name="change_server">Сменить сервер</string>
|
<string name="change_server">Сменить сервер</string>
|
||||||
@@ -528,6 +565,6 @@
|
|||||||
<!-- О проекте -->
|
<!-- О проекте -->
|
||||||
<string name="settings_about">О проекте</string>
|
<string name="settings_about">О проекте</string>
|
||||||
<string name="settings_about_desc">Версия, описание и ссылки</string>
|
<string name="settings_about_desc">Версия, описание и ссылки</string>
|
||||||
<string name="about_description">Free Turn проксирует WireGuard-трафик через публичные TURN-сервера. Открытый исходный код и никакой телеметрии: все настройки хранятся только на вашем устройстве.</string>
|
<string name="about_description">Free Turn проксирует WireGuard и Xray-трафик через публичные TURN-сервера. Открытый исходный код и никакой телеметрии: все настройки хранятся только на вашем устройстве.</string>
|
||||||
<string name="about_links">Ссылки</string>
|
<string name="about_links">Ссылки</string>
|
||||||
</resources>
|
</resources>
|
||||||
@@ -55,12 +55,41 @@ class CoreConfigJsonTest {
|
|||||||
|
|
||||||
// Лишний ключ в proxy валит старт ядра (DisallowUnknownFields), а не тест схемы.
|
// Лишний ключ в proxy валит старт ядра (DisallowUnknownFields), а не тест схемы.
|
||||||
@Test
|
@Test
|
||||||
fun proxyHasOnlyListen() {
|
fun proxyHasModeAndListen() {
|
||||||
val proxy = parse(base.copy(localPort = "127.0.0.1:9001"))["proxy"]!!.jsonObject
|
val proxy = parse(base.copy(localPort = "127.0.0.1:9001"))["proxy"]!!.jsonObject
|
||||||
assertEquals(setOf("listen"), proxy.keys)
|
assertEquals(setOf("mode", "listen"), proxy.keys)
|
||||||
|
assertEquals(ProxyMode.UDP, proxy["mode"]!!.jsonPrimitive.content)
|
||||||
assertEquals("127.0.0.1:9001", proxy["listen"]!!.jsonPrimitive.content)
|
assertEquals("127.0.0.1:9001", proxy["listen"]!!.jsonPrimitive.content)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// В udp ядро отвергает любое отличие ARQ от своего дефолта - секции быть не должно.
|
||||||
|
@Test
|
||||||
|
fun kcpOnlyInTcpMode() {
|
||||||
|
assertTrue(parse(base, ServerOpts(kcp = KcpProfile.MOBILE))["kcp"] == null)
|
||||||
|
|
||||||
|
val tcp = parse(base, ServerOpts(proxyMode = ProxyMode.TCP, kcp = KcpProfile.MOBILE))
|
||||||
|
assertEquals(ProxyMode.TCP, tcp["proxy"]!!.jsonObject["mode"]!!.jsonPrimitive.content)
|
||||||
|
val kcp = tcp["kcp"]!!.jsonObject
|
||||||
|
assertEquals(
|
||||||
|
setOf("noDelay", "interval", "resend", "nc", "sndWnd", "rcvWnd", "mtu", "ackNoDelay"),
|
||||||
|
kcp.keys
|
||||||
|
)
|
||||||
|
assertEquals(KcpProfile.MOBILE.interval, kcp["interval"]!!.jsonPrimitive.content.toInt())
|
||||||
|
assertEquals(KcpProfile.MOBILE.ackNoDelay, kcp["ackNoDelay"]!!.jsonPrimitive.content.toBoolean())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Встроенный туннель гонит датаграммы: tcp-режим при нём ядро бы отвергло.
|
||||||
|
@Test
|
||||||
|
fun tunnelForcesUdpMode() {
|
||||||
|
val wg = base.copy(
|
||||||
|
tunnelTransport = TunnelTransport.WIREGUARD,
|
||||||
|
wireGuardConfig = "[Interface]\nAddress = 10.8.0.2/32\n",
|
||||||
|
)
|
||||||
|
val o = parse(wg, ServerOpts(proxyMode = ProxyMode.TCP))
|
||||||
|
assertEquals(ProxyMode.UDP, o["proxy"]!!.jsonObject["mode"]!!.jsonPrimitive.content)
|
||||||
|
assertTrue(o["kcp"] == null)
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun manualDnsWinsOverCarrier() {
|
fun manualDnsWinsOverCarrier() {
|
||||||
val o = parse(base.copy(customDns = "1.1.1.1, 8.8.8.8"), carrierDns = "192.168.0.1")
|
val o = parse(base.copy(customDns = "1.1.1.1, 8.8.8.8"), carrierDns = "192.168.0.1")
|
||||||
|
|||||||
@@ -0,0 +1,37 @@
|
|||||||
|
package com.freeturn.app.data.server
|
||||||
|
|
||||||
|
import com.freeturn.app.data.config.KcpProfile
|
||||||
|
import com.freeturn.app.data.config.ProxyMode
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class ServerJsonTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `opts round trip keeps mode and arq`() {
|
||||||
|
val srv = Server(
|
||||||
|
name = "s",
|
||||||
|
opts = ServerOpts(
|
||||||
|
proxyMode = ProxyMode.TCP,
|
||||||
|
kcp = KcpProfile.MOBILE
|
||||||
|
)
|
||||||
|
)
|
||||||
|
val decoded = ServerJson.decodeList(ServerJson.encodeList(listOf(srv))).single()
|
||||||
|
assertEquals(ProxyMode.TCP, decoded.opts.proxyMode)
|
||||||
|
assertEquals(KcpProfile.MOBILE, decoded.opts.kcp)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `snapshot without mode and kcp falls back to defaults`() {
|
||||||
|
val raw = """[{"id":"1","name":"s","opts":{"obfProfile":"none","obfKey":""}}]"""
|
||||||
|
val decoded = ServerJson.decodeList(raw).single()
|
||||||
|
assertEquals(ProxyMode.UDP, decoded.opts.proxyMode)
|
||||||
|
assertEquals(KcpProfile.DEFAULT, decoded.opts.kcp)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `unknown mode falls back to udp`() {
|
||||||
|
val raw = """[{"id":"1","name":"s","opts":{"proxyMode":"quic"}}]"""
|
||||||
|
assertEquals(ProxyMode.UDP, ServerJson.decodeList(raw).single().opts.proxyMode)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.freeturn.app.data.share
|
package com.freeturn.app.data.share
|
||||||
|
|
||||||
|
import com.freeturn.app.data.config.KcpProfile
|
||||||
import org.junit.Assert.assertEquals
|
import org.junit.Assert.assertEquals
|
||||||
import org.junit.Assert.assertFalse
|
import org.junit.Assert.assertFalse
|
||||||
import org.junit.Assert.assertTrue
|
import org.junit.Assert.assertTrue
|
||||||
@@ -58,6 +59,8 @@ class FreeturnLinkTest {
|
|||||||
provider = "vk",
|
provider = "vk",
|
||||||
peer = "example.com:56000",
|
peer = "example.com:56000",
|
||||||
transport = "udp",
|
transport = "udp",
|
||||||
|
mode = "tcp",
|
||||||
|
kcp = KcpProfile.MOBILE,
|
||||||
obfProfile = "rtpopus",
|
obfProfile = "rtpopus",
|
||||||
obfKey = "00".repeat(32),
|
obfKey = "00".repeat(32),
|
||||||
n = 10,
|
n = 10,
|
||||||
@@ -81,6 +84,33 @@ class FreeturnLinkTest {
|
|||||||
assertEquals("", parsed.obfKey)
|
assertEquals("", parsed.obfKey)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Ключи ARQ в ссылке строчные (json-теги uri.KCP), а не camelCase конфига ядра.
|
||||||
|
@Test
|
||||||
|
fun `kcp uses go wire keys and sits before name`() {
|
||||||
|
val goldenJson = """{"v":1,"provider":"vk","peer":"1.2.3.4:56000","mode":"tcp",""" +
|
||||||
|
""""kcp":{"nodelay":1,"interval":40,"resend":2,"nc":1,"sndwnd":256,""" +
|
||||||
|
""""rcvwnd":256,"mtu":1200,"acknodelay":false},"name":"Papa"}"""
|
||||||
|
val golden = "freeturn://" + Base64.getUrlEncoder().withoutPadding()
|
||||||
|
.encodeToString(goldenJson.toByteArray(Charsets.UTF_8))
|
||||||
|
|
||||||
|
val link = FreeturnLink(
|
||||||
|
provider = "vk",
|
||||||
|
peer = "1.2.3.4:56000",
|
||||||
|
mode = "tcp",
|
||||||
|
kcp = KcpProfile.MOBILE,
|
||||||
|
name = "Papa"
|
||||||
|
)
|
||||||
|
assertEquals(golden, link.encode())
|
||||||
|
assertEquals(KcpProfile.MOBILE, FreeturnLink.parse(golden).getOrThrow().kcp)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `link without mode and kcp`() {
|
||||||
|
val parsed = FreeturnLink.parse(goldenMinimal).getOrThrow()
|
||||||
|
assertEquals("", parsed.mode)
|
||||||
|
assertEquals(null, parsed.kcp)
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun `unknown json fields are ignored`() {
|
fun `unknown json fields are ignored`() {
|
||||||
val json = """{"v":1,"provider":"vk","peer":"1.2.3.4:56000","future_field":"x"}"""
|
val json = """{"v":1,"provider":"vk","peer":"1.2.3.4:56000","future_field":"x"}"""
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
package com.freeturn.app.data.share
|
package com.freeturn.app.data.share
|
||||||
|
|
||||||
import com.freeturn.app.data.config.ClientConfig
|
import com.freeturn.app.data.config.ClientConfig
|
||||||
|
import com.freeturn.app.data.config.KcpProfile
|
||||||
|
import com.freeturn.app.data.config.ProxyMode
|
||||||
import com.freeturn.app.data.server.Server
|
import com.freeturn.app.data.server.Server
|
||||||
import com.freeturn.app.data.server.ServerOpts
|
import com.freeturn.app.data.server.ServerOpts
|
||||||
import org.junit.Assert.assertEquals
|
import org.junit.Assert.assertEquals
|
||||||
@@ -104,6 +106,32 @@ class ShareLinkBuilderTest {
|
|||||||
assertEquals(4, link.streamsPerCred)
|
assertEquals(4, link.streamsPerCred)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `tcp mode from live server wins over local opts`() {
|
||||||
|
val srv = server(opts = ServerOpts(proxyMode = ProxyMode.TCP, kcp = KcpProfile.MOBILE))
|
||||||
|
val info = ShareInfo(mode = ProxyMode.UDP, obfProfile = "none")
|
||||||
|
val link = FreeturnLink.parse(ShareLinkBuilder.build(srv, info, "u", null)).getOrThrow()
|
||||||
|
assertEquals("", link.mode)
|
||||||
|
assertEquals(null, link.kcp)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `tcp mode and non-default arq carried over`() {
|
||||||
|
val srv = server(opts = ServerOpts(proxyMode = ProxyMode.TCP, kcp = KcpProfile.MOBILE))
|
||||||
|
val link = FreeturnLink.parse(ShareLinkBuilder.build(srv, ShareInfo(), "u", null)).getOrThrow()
|
||||||
|
assertEquals(ProxyMode.TCP, link.mode)
|
||||||
|
assertEquals(KcpProfile.MOBILE, link.kcp)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Дефолтный ARQ у получателя и так дефолтный - в ссылке ему делать нечего.
|
||||||
|
@Test
|
||||||
|
fun `default arq is omitted`() {
|
||||||
|
val srv = server(opts = ServerOpts(proxyMode = ProxyMode.TCP))
|
||||||
|
val link = FreeturnLink.parse(ShareLinkBuilder.build(srv, ShareInfo(), "u", null)).getOrThrow()
|
||||||
|
assertEquals(ProxyMode.TCP, link.mode)
|
||||||
|
assertEquals(null, link.kcp)
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun `udp transport flag carried over`() {
|
fun `udp transport flag carried over`() {
|
||||||
val link = FreeturnLink.parse(
|
val link = FreeturnLink.parse(
|
||||||
|
|||||||
@@ -122,6 +122,11 @@ _write_args_file() {
|
|||||||
{
|
{
|
||||||
echo "-listen"; echo "$ARG_LISTEN"
|
echo "-listen"; echo "$ARG_LISTEN"
|
||||||
echo "-connect"; echo "$ARG_CONNECT"
|
echo "-connect"; echo "$ARG_CONNECT"
|
||||||
|
if [ "$ARG_MODE" = "tcp" ]; then
|
||||||
|
echo "-mode"; echo "tcp"
|
||||||
|
# Токены уже готовы (пары флаг/значение и -kcp-acknodelay=BOOL) - по строке на токен.
|
||||||
|
for tok in ${ARG_KCP[@]+"${ARG_KCP[@]}"}; do echo "$tok"; done
|
||||||
|
fi
|
||||||
if [ "$ARG_OBF_PROFILE" != "none" ] && [ -n "$ARG_OBF_KEY" ]; then
|
if [ "$ARG_OBF_PROFILE" != "none" ] && [ -n "$ARG_OBF_KEY" ]; then
|
||||||
echo "-obf-profile"; echo "$ARG_OBF_PROFILE"
|
echo "-obf-profile"; echo "$ARG_OBF_PROFILE"
|
||||||
echo "-obf-key"; echo "$ARG_OBF_KEY"
|
echo "-obf-key"; echo "$ARG_OBF_KEY"
|
||||||
@@ -182,6 +187,10 @@ _rt_start_nohup() {
|
|||||||
_write_env_file
|
_write_env_file
|
||||||
if [ -f "$ENVFILE" ]; then set -a; . "$ENVFILE"; set +a; fi
|
if [ -f "$ENVFILE" ]; then set -a; . "$ENVFILE"; set +a; fi
|
||||||
local args=(-listen "$ARG_LISTEN" -connect "$ARG_CONNECT")
|
local args=(-listen "$ARG_LISTEN" -connect "$ARG_CONNECT")
|
||||||
|
if [ "$ARG_MODE" = "tcp" ]; then
|
||||||
|
args+=(-mode tcp)
|
||||||
|
args+=(${ARG_KCP[@]+"${ARG_KCP[@]}"})
|
||||||
|
fi
|
||||||
[ -n "$ARG_CLIENT_ID" ] && args+=(-clients-file "$CLIENTSFILE")
|
[ -n "$ARG_CLIENT_ID" ] && args+=(-clients-file "$CLIENTSFILE")
|
||||||
if [ "$ARG_OBF_PROFILE" != "none" ] && [ -n "$ARG_OBF_KEY" ]; then
|
if [ "$ARG_OBF_PROFILE" != "none" ] && [ -n "$ARG_OBF_KEY" ]; then
|
||||||
( umask 077; printf '%s' "$ARG_OBF_KEY" > "$OBFFILE" ); chmod 600 "$OBFFILE"
|
( umask 077; printf '%s' "$ARG_OBF_KEY" > "$OBFFILE" ); chmod 600 "$OBFFILE"
|
||||||
|
|||||||
@@ -105,20 +105,23 @@ _peer_in_conf() { # CONF PUBKEY
|
|||||||
# obf_profile отдаётся всегда, когда параметры запуска нашлись (пусть и "none"):
|
# obf_profile отдаётся всегда, когда параметры запуска нашлись (пусть и "none"):
|
||||||
# по нему клиент отличает "сервер стартовал из приложения" от "данных нет".
|
# по нему клиент отличает "сервер стартовал из приложения" от "данных нет".
|
||||||
share_info_emit() {
|
share_info_emit() {
|
||||||
local backend=false obf="" key=""
|
local backend=false obf="" key="" mode=""
|
||||||
if wg_present && wg_is_ours; then backend=true; fi
|
if wg_present && wg_is_ours; then backend=true; fi
|
||||||
if [ -f "$ARGSFILE" ]; then
|
if [ -f "$ARGSFILE" ]; then
|
||||||
obf=$(awk 'prev=="-obf-profile"{print;exit}{prev=$0}' "$ARGSFILE"); obf=${obf:-none}
|
obf=$(awk 'prev=="-obf-profile"{print;exit}{prev=$0}' "$ARGSFILE"); obf=${obf:-none}
|
||||||
key=$(awk 'prev=="-obf-key"{print;exit}{prev=$0}' "$ARGSFILE")
|
key=$(awk 'prev=="-obf-key"{print;exit}{prev=$0}' "$ARGSFILE")
|
||||||
|
mode=$(awk 'prev=="-mode"{print;exit}{prev=$0}' "$ARGSFILE"); mode=${mode:-udp}
|
||||||
else
|
else
|
||||||
local cmdline
|
local cmdline
|
||||||
cmdline=$(current_cmdline)
|
cmdline=$(current_cmdline)
|
||||||
if [ -n "$cmdline" ]; then
|
if [ -n "$cmdline" ]; then
|
||||||
obf=$(printf '%s' "$cmdline" | sed -nE 's/.*-obf-profile[= ]+([a-z0-9]+).*/\1/p'); obf=${obf:-none}
|
obf=$(printf '%s' "$cmdline" | sed -nE 's/.*-obf-profile[= ]+([a-z0-9]+).*/\1/p'); obf=${obf:-none}
|
||||||
key=$(printf '%s' "$cmdline" | sed -nE 's/.*-obf-key[= ]+([0-9a-fA-F]{64}).*/\1/p')
|
key=$(printf '%s' "$cmdline" | sed -nE 's/.*-obf-key[= ]+([0-9a-fA-F]{64}).*/\1/p')
|
||||||
|
mode=$(printf '%s' "$cmdline" | sed -nE 's/.*-mode[= ]+(udp|tcp).*/\1/p'); mode=${mode:-udp}
|
||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
d_bool wg_backend "$backend"
|
d_bool wg_backend "$backend"
|
||||||
|
if [ -n "$mode" ]; then d_str mode "$mode"; fi
|
||||||
if [ -n "$obf" ]; then d_str obf_profile "$obf"; fi
|
if [ -n "$obf" ]; then d_str obf_profile "$obf"; fi
|
||||||
if [ -n "$key" ]; then d_str obf_key "$key"; fi
|
if [ -n "$key" ]; then d_str obf_key "$key"; fi
|
||||||
return 0
|
return 0
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
ARG_LISTEN=""
|
ARG_LISTEN=""
|
||||||
ARG_CONNECT=""
|
ARG_CONNECT=""
|
||||||
|
ARG_MODE="udp"
|
||||||
|
# Готовые argv-токены -kcp-*; пусто = сервер берёт свои дефолты, как и клиент.
|
||||||
|
ARG_KCP=()
|
||||||
ARG_OBF_PROFILE="none"
|
ARG_OBF_PROFILE="none"
|
||||||
ARG_OBF_KEY=""
|
ARG_OBF_KEY=""
|
||||||
ARG_TAIL=80
|
ARG_TAIL=80
|
||||||
@@ -13,6 +16,13 @@ ARG_DNS="1.1.1.1"
|
|||||||
ARG_WITH_WG_PKG=0
|
ARG_WITH_WG_PKG=0
|
||||||
ARG_DRY_RUN=0
|
ARG_DRY_RUN=0
|
||||||
|
|
||||||
|
# --kcp-foo=N -> argv-пара "-kcp-foo" "N"; диапазоны проверяет само ядро.
|
||||||
|
_kcp_num_arg() {
|
||||||
|
local flag=${1%%=*} value=${1#*=}
|
||||||
|
[[ "$value" =~ ^[0-9]+$ ]] || fail bad_arg "bad $flag (need number)"
|
||||||
|
ARG_KCP+=("-${flag#--}" "$value")
|
||||||
|
}
|
||||||
|
|
||||||
parse_args() {
|
parse_args() {
|
||||||
while [ $# -gt 0 ]; do
|
while [ $# -gt 0 ]; do
|
||||||
case "$1" in
|
case "$1" in
|
||||||
@@ -22,6 +32,14 @@ parse_args() {
|
|||||||
--connect=*)
|
--connect=*)
|
||||||
ARG_CONNECT="${1#*=}"
|
ARG_CONNECT="${1#*=}"
|
||||||
[[ "$ARG_CONNECT" =~ ^[a-zA-Z0-9.:_-]+$ ]] || fail bad_arg "bad --connect" ;;
|
[[ "$ARG_CONNECT" =~ ^[a-zA-Z0-9.:_-]+$ ]] || fail bad_arg "bad --connect" ;;
|
||||||
|
--mode=*)
|
||||||
|
ARG_MODE="${1#*=}"
|
||||||
|
[[ "$ARG_MODE" =~ ^(udp|tcp)$ ]] || fail bad_arg "bad --mode (udp|tcp)" ;;
|
||||||
|
--kcp-nodelay=*|--kcp-interval=*|--kcp-resend=*|--kcp-nc=*|--kcp-sndwnd=*|--kcp-rcvwnd=*|--kcp-mtu=*)
|
||||||
|
_kcp_num_arg "$1" ;;
|
||||||
|
--kcp-acknodelay=*)
|
||||||
|
[[ "${1#*=}" =~ ^(true|false)$ ]] || fail bad_arg "bad $1 (true|false)"
|
||||||
|
ARG_KCP+=("-kcp-acknodelay=${1#*=}") ;;
|
||||||
--obf-profile=*)
|
--obf-profile=*)
|
||||||
ARG_OBF_PROFILE="${1#*=}"
|
ARG_OBF_PROFILE="${1#*=}"
|
||||||
[[ "$ARG_OBF_PROFILE" =~ ^(none|rtpopus|rtpopus2|rtpopus3)$ ]] || fail bad_arg "bad --obf-profile" ;;
|
[[ "$ARG_OBF_PROFILE" =~ ^(none|rtpopus|rtpopus2|rtpopus3)$ ]] || fail bad_arg "bad --obf-profile" ;;
|
||||||
@@ -67,7 +85,7 @@ parse_args() {
|
|||||||
cmd_probe() {
|
cmd_probe() {
|
||||||
stage probe
|
stage probe
|
||||||
|
|
||||||
local arch bin="" installed=false running=false version="" sha="" obf=""
|
local arch bin="" installed=false running=false version="" sha="" obf="" mode=""
|
||||||
arch=$(detect_arch) || arch=""
|
arch=$(detect_arch) || arch=""
|
||||||
[ -n "$arch" ] && bin="$PREFIX/$arch"
|
[ -n "$arch" ] && bin="$PREFIX/$arch"
|
||||||
if [ -n "$bin" ] && [ -x "$bin" ]; then
|
if [ -n "$bin" ] && [ -x "$bin" ]; then
|
||||||
@@ -84,6 +102,9 @@ cmd_probe() {
|
|||||||
cmdline=$(current_cmdline)
|
cmdline=$(current_cmdline)
|
||||||
obf=$(printf '%s' "$cmdline" | sed -nE 's/.*-obf-profile[= ]+([a-z0-9]+).*/\1/p')
|
obf=$(printf '%s' "$cmdline" | sed -nE 's/.*-obf-profile[= ]+([a-z0-9]+).*/\1/p')
|
||||||
[ -z "$obf" ] && obf=none
|
[ -z "$obf" ] && obf=none
|
||||||
|
# -mode пишется только для tcp: без флага сервер работает в udp.
|
||||||
|
mode=$(printf '%s' "$cmdline" | sed -nE 's/.*-mode[= ]+(udp|tcp).*/\1/p')
|
||||||
|
[ -z "$mode" ] && mode=udp
|
||||||
fi
|
fi
|
||||||
|
|
||||||
local euid
|
local euid
|
||||||
@@ -109,6 +130,7 @@ cmd_probe() {
|
|||||||
[ -n "$sha" ] && d_str bin_sha256 "$sha"
|
[ -n "$sha" ] && d_str bin_sha256 "$sha"
|
||||||
d_bool running "$running"
|
d_bool running "$running"
|
||||||
if [ "$running" = true ]; then
|
if [ "$running" = true ]; then
|
||||||
|
d_str mode "$mode"
|
||||||
d_str obf "$obf"
|
d_str obf "$obf"
|
||||||
fi
|
fi
|
||||||
d_str runtime "$runtime"
|
d_str runtime "$runtime"
|
||||||
|
|||||||
@@ -71,6 +71,18 @@ run_script() { run bash "$SCRIPT" "$@"; }
|
|||||||
[[ "$output" == *'"code":"bad_arg"'* ]]
|
[[ "$output" == *'"code":"bad_arg"'* ]]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@test "невалидный --mode -> err bad_arg" {
|
||||||
|
run_script start --listen=0.0.0.0:56000 --connect=127.0.0.1:443 --mode=quic
|
||||||
|
[ "$status" -eq 1 ]
|
||||||
|
[[ "$output" == *'"code":"bad_arg"'* ]]
|
||||||
|
}
|
||||||
|
|
||||||
|
@test "нечисловой --kcp-interval -> err bad_arg" {
|
||||||
|
run_script start --listen=0.0.0.0:56000 --connect=127.0.0.1:443 --kcp-interval=fast
|
||||||
|
[ "$status" -eq 1 ]
|
||||||
|
[[ "$output" == *'"code":"bad_arg"'* ]]
|
||||||
|
}
|
||||||
|
|
||||||
@test "IPv6-endpoint принимается парсером (не bad_arg)" {
|
@test "IPv6-endpoint принимается парсером (не bad_arg)" {
|
||||||
# Под обычным юзером упрётся в needs_root - но parse_args уже принял [v6]:port.
|
# Под обычным юзером упрётся в needs_root - но parse_args уже принял [v6]:port.
|
||||||
run_script wg-setup --port=51820 "--endpoint=[2001:db8::1]:51820"
|
run_script wg-setup --port=51820 "--endpoint=[2001:db8::1]:51820"
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
#!/usr/bin/env bats
|
||||||
|
# White-box: сборка аргументов запуска сервера (run.args). Sandbox FT_*.
|
||||||
|
|
||||||
|
setup() {
|
||||||
|
SRC="$BATS_TEST_DIRNAME/../src"
|
||||||
|
LIB="$BATS_TEST_TMPDIR/lib.sh"
|
||||||
|
: > "$LIB"
|
||||||
|
for f in $(ls "$SRC"/*.sh | sort | grep -v '99-main'); do
|
||||||
|
cat "$f" >> "$LIB"; printf '\n' >> "$LIB"
|
||||||
|
done
|
||||||
|
export FT_PREFIX="$BATS_TEST_TMPDIR/prefix"
|
||||||
|
mkdir -p "$FT_PREFIX"
|
||||||
|
# shellcheck disable=SC1090
|
||||||
|
source "$LIB"
|
||||||
|
set +e; trap - EXIT
|
||||||
|
ARG_LISTEN="0.0.0.0:56000"
|
||||||
|
ARG_CONNECT="127.0.0.1:51820"
|
||||||
|
}
|
||||||
|
|
||||||
|
@test "run.args: udp-режим не пишет -mode и -kcp-*" {
|
||||||
|
_write_args_file
|
||||||
|
run cat "$ARGSFILE"
|
||||||
|
[[ "$output" != *"-mode"* ]]
|
||||||
|
[[ "$output" != *"-kcp-"* ]]
|
||||||
|
}
|
||||||
|
|
||||||
|
@test "run.args: tcp-режим с профилем ARQ" {
|
||||||
|
ARG_MODE="tcp"
|
||||||
|
ARG_KCP=(-kcp-interval 40 -kcp-sndwnd 256 -kcp-acknodelay=false)
|
||||||
|
_write_args_file
|
||||||
|
run cat "$ARGSFILE"
|
||||||
|
[[ "$output" == *$'-mode\ntcp'* ]]
|
||||||
|
[[ "$output" == *$'-kcp-interval\n40'* ]]
|
||||||
|
[[ "$output" == *$'-kcp-sndwnd\n256'* ]]
|
||||||
|
[[ "$output" == *'-kcp-acknodelay=false'* ]]
|
||||||
|
}
|
||||||
|
|
||||||
|
@test "parse_args: --kcp-interval -> argv-пара" {
|
||||||
|
parse_args --listen=0.0.0.0:56000 --connect=127.0.0.1:443 --mode=tcp --kcp-interval=40
|
||||||
|
[ "$ARG_MODE" = "tcp" ]
|
||||||
|
[ "${ARG_KCP[0]}" = "-kcp-interval" ]
|
||||||
|
[ "${ARG_KCP[1]}" = "40" ]
|
||||||
|
}
|
||||||
@@ -104,6 +104,22 @@ EOF
|
|||||||
[[ "$out" == *'"obf_profile":"none"'* ]]
|
[[ "$out" == *'"obf_profile":"none"'* ]]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@test "share_info_emit: режим из run.args" {
|
||||||
|
printf -- '-listen\n:8443\n-mode\ntcp\n-connect\n127.0.0.1:443\n' > "$FT_PREFIX/run.args"
|
||||||
|
_DATA=()
|
||||||
|
share_info_emit
|
||||||
|
out=$(IFS=,; printf '%s' "${_DATA[*]}")
|
||||||
|
[[ "$out" == *'"mode":"tcp"'* ]]
|
||||||
|
}
|
||||||
|
|
||||||
|
@test "share_info_emit: run.args без -mode -> udp" {
|
||||||
|
printf -- '-listen\n:8443\n-connect\n127.0.0.1:51820\n' > "$FT_PREFIX/run.args"
|
||||||
|
_DATA=()
|
||||||
|
share_info_emit
|
||||||
|
out=$(IFS=,; printf '%s' "${_DATA[*]}")
|
||||||
|
[[ "$out" == *'"mode":"udp"'* ]]
|
||||||
|
}
|
||||||
|
|
||||||
@test "clients_json: нет бинаря -> []" {
|
@test "clients_json: нет бинаря -> []" {
|
||||||
[ "$(clients_json)" = "[]" ]
|
[ "$(clients_json)" = "[]" ]
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user