feat(server): install.sh из релиза ядра, apply вместо install/start (RPC proto 3)
Конфиг живёт в install.conf на сервере, приложение шлёт его целиком. Бэкенд - свой WG или готовый VPN, установка через docker/systemd; debug-сборка с local ставит свою сборку.
This commit is contained in:
1 parent
8abeeb70b3
commit
430416251c
55 files changed
+1164
-3548
No files matched your search
+108
-59
@@ -140,42 +140,10 @@ dependencies {
|
||||
testImplementation(libs.koin.test)
|
||||
}
|
||||
|
||||
abstract class AssembleControlScript : DefaultTask() {
|
||||
@get:InputDirectory
|
||||
abstract val srcDir: DirectoryProperty
|
||||
|
||||
@get:OutputDirectory
|
||||
abstract val outDir: DirectoryProperty
|
||||
|
||||
@TaskAction
|
||||
fun assemble() {
|
||||
val out = outDir.get().file("free-turn-control.sh").asFile
|
||||
out.parentFile.mkdirs()
|
||||
val parts = srcDir.get().asFile.listFiles { f -> f.isFile && f.extension == "sh" }
|
||||
?.sortedBy { it.name } ?: emptyList()
|
||||
require(parts.isNotEmpty()) { "no .sh modules in ${srcDir.get().asFile}" }
|
||||
out.writeText(parts.joinToString("\n") { it.readText().trimEnd('\n') } + "\n")
|
||||
}
|
||||
}
|
||||
|
||||
val assembleControlScript = tasks.register<AssembleControlScript>("assembleControlScript") {
|
||||
description = "Склеивает server-control/src/*.sh в free-turn-control.sh"
|
||||
group = "build"
|
||||
srcDir.set(rootProject.layout.projectDirectory.dir("server-control/src"))
|
||||
}
|
||||
|
||||
androidComponents {
|
||||
onVariants { variant ->
|
||||
variant.sources.assets?.addGeneratedSourceDirectory(
|
||||
assembleControlScript,
|
||||
AssembleControlScript::outDir
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Тянет `freeturn.aar` (ядро + gomobile-биндинг) из релизов free-turn-proxy
|
||||
* в app/libs. Версия `local` - брать уже лежащий файл и в сеть не ходить.
|
||||
* Тянет из релиза free-turn-proxy `freeturn.aar` (ядро + gomobile-биндинг) и `install.sh`
|
||||
* (серверный RPC, стримится по SSH) в app/libs. Версия общая: протокол скрипта - часть релиза.
|
||||
* `local` - брать уже лежащие app/libs/freeturn.aar и app/libs/install.sh, в сеть не ходить.
|
||||
*/
|
||||
abstract class FetchFreeturnAar : DefaultTask() {
|
||||
@get:Input
|
||||
@@ -196,15 +164,25 @@ abstract class FetchFreeturnAar : DefaultTask() {
|
||||
@get:OutputFile
|
||||
abstract val aarFile: RegularFileProperty
|
||||
|
||||
@get:OutputFile
|
||||
abstract val scriptFile: RegularFileProperty
|
||||
|
||||
/** Generated assets варианта; путь задаёт AGP. */
|
||||
@get:OutputDirectory
|
||||
abstract val assetsDir: DirectoryProperty
|
||||
|
||||
@TaskAction
|
||||
fun fetch() {
|
||||
val aar = aarFile.get().asFile
|
||||
val script = scriptFile.get().asFile
|
||||
val stamp = File(aar.parentFile, ".aar-version")
|
||||
val installed = if (stamp.isFile) stamp.readText().trim() else null
|
||||
|
||||
if (version.get().trim().equals("local", ignoreCase = true)) {
|
||||
if (!aar.isFile) throw GradleException("FreeTurn aar: freeturnAar=local, но ${aar.path} нет")
|
||||
didWork = false
|
||||
listOf(aar, script).firstOrNull { !it.isFile }?.let {
|
||||
throw GradleException("FreeTurn: freeturnAar=local, но ${it.path} нет")
|
||||
}
|
||||
publishScript(script)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -212,15 +190,16 @@ abstract class FetchFreeturnAar : DefaultTask() {
|
||||
resolveTag()
|
||||
} catch (e: Exception) {
|
||||
// Оффлайн со скачанным ядром - не повод ронять сборку
|
||||
if (aar.isFile && installed != null) {
|
||||
logger.warn("FreeTurn aar: не удалось узнать версию (${e.message}), оставляю $installed")
|
||||
if (aar.isFile && script.isFile && installed != null) {
|
||||
logger.warn("FreeTurn: не удалось узнать версию (${e.message}), оставляю $installed")
|
||||
publishScript(script)
|
||||
return
|
||||
}
|
||||
throw GradleException("FreeTurn aar: не удалось определить версию из ${repo.get()}: ${e.message}", e)
|
||||
throw GradleException("FreeTurn: не удалось определить версию из ${repo.get()}: ${e.message}", e)
|
||||
}
|
||||
|
||||
if (tag == installed && aar.isFile) {
|
||||
didWork = false
|
||||
if (tag == installed && aar.isFile && script.isFile) {
|
||||
publishScript(script)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -233,19 +212,26 @@ abstract class FetchFreeturnAar : DefaultTask() {
|
||||
if (p.size == 2) p[1].removePrefix("*") to p[0] else null
|
||||
}.toMap()
|
||||
|
||||
val src = cachedFile(File(cache, ASSET), "$base/$ASSET")
|
||||
val expected = sums[ASSET]
|
||||
?: throw GradleException("FreeTurn aar: $ASSET нет в checksums.txt релиза $tag")
|
||||
val actual = sha256(src)
|
||||
if (!actual.equals(expected, ignoreCase = true)) {
|
||||
src.delete()
|
||||
throw GradleException("FreeTurn aar: sha256 не сошёлся ($actual != $expected)")
|
||||
for ((asset, dest) in listOf(AAR to aar, SCRIPT to script)) {
|
||||
val src = cachedFile(File(cache, asset), "$base/$asset")
|
||||
val expected = sums[asset]
|
||||
?: throw GradleException("FreeTurn: $asset нет в checksums.txt релиза $tag")
|
||||
val actual = sha256(src)
|
||||
if (!actual.equals(expected, ignoreCase = true)) {
|
||||
src.delete()
|
||||
throw GradleException("FreeTurn: sha256 $asset не сошёлся ($actual != $expected)")
|
||||
}
|
||||
dest.parentFile.mkdirs()
|
||||
src.copyTo(dest, overwrite = true)
|
||||
}
|
||||
aar.parentFile.mkdirs()
|
||||
src.copyTo(aar, overwrite = true)
|
||||
|
||||
stamp.writeText(tag)
|
||||
logger.lifecycle("FreeTurn aar: $tag -> ${aar.path}")
|
||||
publishScript(script)
|
||||
logger.lifecycle("FreeTurn: $tag -> ${aar.parentFile.path}")
|
||||
}
|
||||
|
||||
private fun publishScript(script: File) {
|
||||
script.copyTo(assetsDir.get().file(SCRIPT).asFile, overwrite = true)
|
||||
}
|
||||
|
||||
private fun resolveTag(): String {
|
||||
@@ -313,22 +299,70 @@ abstract class FetchFreeturnAar : DefaultTask() {
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val ASSET = "freeturn.aar"
|
||||
const val AAR = "freeturn.aar"
|
||||
const val SCRIPT = "install.sh"
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `app/libs/server-linux-*` -> assets/server debug-сборки с `freeturnAar=local`: "Обновить"
|
||||
* в хабе сервера загружает их по SSH вместо релиза (отладка серверной части ядра).
|
||||
*/
|
||||
abstract class LocalServerBinaries : DefaultTask() {
|
||||
@get:InputFiles
|
||||
@get:PathSensitive(PathSensitivity.NAME_ONLY)
|
||||
abstract val binaries: ConfigurableFileCollection
|
||||
|
||||
@get:OutputDirectory
|
||||
abstract val assetsDir: DirectoryProperty
|
||||
|
||||
@TaskAction
|
||||
fun copy() {
|
||||
val out = assetsDir.get().dir("server").asFile
|
||||
out.deleteRecursively()
|
||||
out.mkdirs()
|
||||
for (f in binaries.files) {
|
||||
val asset = assetName(f.name)
|
||||
if (asset == null) {
|
||||
logger.warn("FreeTurn: ${f.name} - неизвестная архитектура, пропускаю")
|
||||
continue
|
||||
}
|
||||
f.copyTo(File(out, asset), overwrite = true)
|
||||
logger.lifecycle("FreeTurn: ${f.name} -> assets/server/$asset")
|
||||
}
|
||||
if (out.list().isNullOrEmpty()) {
|
||||
logger.warn("FreeTurn: в app/libs нет server-linux-* - \"Обновить\" поставит релиз")
|
||||
}
|
||||
}
|
||||
|
||||
// Имя ассета релиза (как server_asset в install.sh), в т.ч. из имён dist/ goreleaser:
|
||||
// server_linux_arm64_v8.0, server_linux_amd64_v1, server_linux_arm_7.
|
||||
private fun assetName(name: String): String? {
|
||||
val arch = Regex("^server[-_]linux[-_](.+)$").find(name)?.groupValues?.get(1) ?: return null
|
||||
return "server-linux-" + when {
|
||||
arch.startsWith("amd64") -> "amd64"
|
||||
arch.startsWith("arm64") -> "arm64"
|
||||
arch == "armv7" || arch.startsWith("arm_7") -> "armv7"
|
||||
arch.startsWith("386") -> "386"
|
||||
arch.startsWith("riscv64") -> "riscv64"
|
||||
else -> return null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val freeturnAarVersion: Provider<String> = providers.gradleProperty("freeturnAar")
|
||||
.orElse(providers.environmentVariable("FREETURN_AAR_VERSION"))
|
||||
.orElse("latest")
|
||||
|
||||
val fetchFreeturnAar = tasks.register<FetchFreeturnAar>("fetchFreeturnAar") {
|
||||
description = "Качает freeturn.aar из релизов free-turn-proxy в app/libs"
|
||||
description = "Качает freeturn.aar и install.sh из релизов free-turn-proxy в app/libs"
|
||||
group = "build"
|
||||
repo.set(providers.gradleProperty("freeturnAarRepo").orElse("samosvalishe/free-turn-proxy"))
|
||||
version.set(
|
||||
providers.gradleProperty("freeturnAar")
|
||||
.orElse(providers.environmentVariable("FREETURN_AAR_VERSION"))
|
||||
.orElse("latest")
|
||||
)
|
||||
version.set(freeturnAarVersion)
|
||||
token.set(providers.environmentVariable("GITHUB_TOKEN"))
|
||||
cacheDir.set(layout.dir(provider { File(gradle.gradleUserHomeDir, "caches/freeturn-core") }))
|
||||
aarFile.set(layout.projectDirectory.file("libs/freeturn.aar"))
|
||||
scriptFile.set(layout.projectDirectory.file("libs/install.sh"))
|
||||
// Версия резолвится в рантайме - актуальность решает stamp-файл внутри таски
|
||||
outputs.upToDateWhen { false }
|
||||
}
|
||||
@@ -336,3 +370,18 @@ val fetchFreeturnAar = tasks.register<FetchFreeturnAar>("fetchFreeturnAar") {
|
||||
// AAR нужен на компиляции, а не на упаковке - качаем в любой сборке.
|
||||
// matching, а не named - таски вариантов AGP создаёт позже конфигурации скрипта.
|
||||
tasks.matching { it.name == "preBuild" }.configureEach { dependsOn(fetchFreeturnAar) }
|
||||
|
||||
androidComponents {
|
||||
onVariants { variant ->
|
||||
variant.sources.assets?.addGeneratedSourceDirectory(
|
||||
fetchFreeturnAar,
|
||||
FetchFreeturnAar::assetsDir
|
||||
)
|
||||
if (variant.buildType == "debug" && freeturnAarVersion.get().trim().equals("local", ignoreCase = true)) {
|
||||
val bins = tasks.register<LocalServerBinaries>("${variant.name}LocalServerBinaries") {
|
||||
binaries.from(fileTree("libs") { include("server-linux*", "server_linux*") })
|
||||
}
|
||||
variant.sources.assets?.addGeneratedSourceDirectory(bins, LocalServerBinaries::assetsDir)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,8 @@ data class SshConfig(
|
||||
/** Пароль sudo для key-auth + SUDO_PASS. Пусто -> при password-auth берётся [password]. */
|
||||
val sudoPassword: String = ""
|
||||
) {
|
||||
fun sameHost(o: SshConfig): Boolean = ip.isNotBlank() && ip.equals(o.ip, ignoreCase = true) && port == o.port
|
||||
|
||||
companion object {
|
||||
// Значения authType - контракт хранения (ServerJson).
|
||||
const val AUTH_PASSWORD = "PASSWORD"
|
||||
|
||||
@@ -5,126 +5,85 @@ import kotlinx.serialization.Serializable
|
||||
|
||||
/**
|
||||
* Типизированные data-пейлоады команд (поле `data` в [ControlResponse]).
|
||||
* Контракт с server-control: имена полей = ключи JSON (см. 80-cmd.sh).
|
||||
* Контракт с install.sh (proto 3): имена полей = ключи JSON (см. cmd_* в скрипте).
|
||||
*/
|
||||
|
||||
@Serializable
|
||||
data class ProbeData(
|
||||
val installed: Boolean = false,
|
||||
val version: String? = null,
|
||||
@SerialName("bin_sha256") val binSha256: String? = null,
|
||||
val running: Boolean = false,
|
||||
val mode: String? = null,
|
||||
val obf: String? = null,
|
||||
val runtime: String = "",
|
||||
val euid: Int = -1,
|
||||
val wg: WgInfo = WgInfo(),
|
||||
val virt: String = "",
|
||||
@SerialName("wg_kernel") val wgKernel: Boolean = false,
|
||||
val conflicts: Conflicts = Conflicts(),
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class WgInfo(
|
||||
val present: Boolean = false,
|
||||
val port: Int? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class Conflicts(
|
||||
val warp: Boolean = false,
|
||||
val x3ui: Boolean = false,
|
||||
val wgeasy: Boolean = false,
|
||||
val tailscale: Boolean = false,
|
||||
@SerialName("other_ifaces") val otherIfaces: List<String> = emptyList(),
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class InstallData(
|
||||
val stage: String = "ok",
|
||||
val bin: String = "",
|
||||
val arch: String = "",
|
||||
val method: String? = null,
|
||||
val version: String? = null,
|
||||
val runtime: String = "",
|
||||
/** Нет install.conf - сервер не ставился этим установщиком (или старый, до proto 3). */
|
||||
val config: RemoteConfig? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class RemoteConfig(
|
||||
val method: String = "",
|
||||
val backend: String = "",
|
||||
val connect: String = "",
|
||||
val host: String = "",
|
||||
@SerialName("listen_port") val listenPort: Int = 0,
|
||||
@SerialName("wg_port") val wgPort: Int = 0,
|
||||
@SerialName("wg_net") val wgNet: String = "",
|
||||
val mode: String = "",
|
||||
@SerialName("obf_profile") val obfProfile: String = "",
|
||||
@SerialName("obf_key") val obfKey: String = "",
|
||||
val version: String = "",
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class ApplyData(
|
||||
val owner: OwnerDto = OwnerDto(),
|
||||
/** Ключ после apply: пустой в запросе -> сервер сгенерировал свой. */
|
||||
@SerialName("obf_key") val obfKey: String = "",
|
||||
@SerialName("needs_restart") val needsRestart: Boolean = false,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class WgSetupData(
|
||||
val wg: WgSetupInfo = WgSetupInfo(),
|
||||
@SerialName("client_conf_b64") val clientConfB64: String? = null,
|
||||
data class OwnerDto(
|
||||
@SerialName("client_id") val clientId: String = "",
|
||||
val pub: String = "",
|
||||
@SerialName("conf_b64") val confB64: String = "",
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class WgSetupInfo(
|
||||
data class ClientDto(
|
||||
val name: String = "",
|
||||
@SerialName("client_id") val clientId: String = "",
|
||||
val self: Boolean = false,
|
||||
/** ip/pub/hs - только при своём WG (backend=new). */
|
||||
val ip: String = "",
|
||||
val pub: String = "",
|
||||
val hs: Long = 0,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class ShareDto(
|
||||
val backend: String = "",
|
||||
val host: String = "",
|
||||
val port: Int = 0,
|
||||
val existed: Boolean = false,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class ShareInfoData(
|
||||
@SerialName("wg_backend") val wgBackend: Boolean = false,
|
||||
val mode: String = "",
|
||||
@SerialName("obf_profile") val obfProfile: String = "",
|
||||
@SerialName("obf_key") val obfKey: String = "",
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class ShareListData(
|
||||
val peers: List<PeerDto> = emptyList(),
|
||||
@SerialName("self_pub") val selfPub: String = "",
|
||||
data class ClientListData(
|
||||
val clients: List<ClientDto> = emptyList(),
|
||||
val share: ShareDto = ShareDto(),
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class PeerDto(
|
||||
val pub: String,
|
||||
@SerialName("name_b64") val nameB64: String? = null,
|
||||
val ip: String = "",
|
||||
val hs: Long? = null,
|
||||
@SerialName("has_conf") val hasConf: Boolean = false,
|
||||
data class ClientData(
|
||||
val client: ClientDto = ClientDto(),
|
||||
@SerialName("conf_b64") val confB64: String? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class ClientDto(
|
||||
val id: String,
|
||||
@SerialName("name_b64") val nameB64: String? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class PeerAddData(
|
||||
val peer: PeerRef = PeerRef(),
|
||||
@SerialName("client_id") val clientId: String = "",
|
||||
@SerialName("client_conf_b64") val clientConfB64: String = "",
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class PeerRef(
|
||||
val pub: String = "",
|
||||
val ip: String = "",
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class PeerConfData(
|
||||
@SerialName("client_id") val clientId: String = "",
|
||||
@SerialName("client_conf_b64") val clientConfB64: String = "",
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class UninstallData(
|
||||
@SerialName("dry_run") val dryRun: Boolean = false,
|
||||
val removed: UninstallRemoved = UninstallRemoved(),
|
||||
@SerialName("wg_pkg_removed") val wgPkgRemoved: Boolean = false,
|
||||
/** Что НЕ тронули (чужой WG, ip_forward, общий пакет) - для пояснения в UI. */
|
||||
val kept: List<String> = emptyList(),
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class UninstallRemoved(
|
||||
val binary: Boolean = false,
|
||||
val unit: Boolean = false,
|
||||
@SerialName("wg_iface") val wgIface: Boolean = false,
|
||||
val prefix: Boolean = false,
|
||||
val sysctl: Boolean = false,
|
||||
val ufw: Boolean = false,
|
||||
@SerialName("legacy_unit") val legacyUnit: Boolean = false,
|
||||
data class LogsData(
|
||||
val lines: List<String> = emptyList(),
|
||||
)
|
||||
@@ -8,7 +8,7 @@ import kotlinx.serialization.json.decodeFromJsonElement
|
||||
import java.util.Base64
|
||||
|
||||
/**
|
||||
* Envelope протокола v2 control-скрипта (см. server-control/src/10-proto.sh).
|
||||
* Envelope RPC install.sh (proto [PROTO_VERSION]).
|
||||
* Один JSON-объект на запуск: либо result=ok + data, либо result=err + code/msg.
|
||||
*/
|
||||
@Serializable
|
||||
@@ -22,6 +22,11 @@ data class ControlResponse(
|
||||
val logs: List<String> = emptyList(),
|
||||
) {
|
||||
val isOk: Boolean get() = result == "ok"
|
||||
|
||||
companion object {
|
||||
/** = PROTO_VERSION install.sh; другое значение - скрипт не той версии. */
|
||||
const val PROTO_VERSION = 3
|
||||
}
|
||||
}
|
||||
|
||||
/** Единый Json для протокола: незнакомые ключи игнорим (forward-compat). */
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
package com.freeturn.app.data.control
|
||||
|
||||
/** Парсит stdout control-команды в [ControlResponse] (один JSON-объект). */
|
||||
/** Парсит stdout RPC-команды в [ControlResponse] (один JSON-объект). */
|
||||
object ControlResponseParser {
|
||||
|
||||
fun parse(raw: String): ControlResponse {
|
||||
@@ -12,14 +12,19 @@ object ControlResponseParser {
|
||||
val jsonLine = text.lineSequence().lastOrNull { it.trimStart().startsWith("{") }
|
||||
?: return err(transportCode(text), text.take(300))
|
||||
|
||||
return runCatching {
|
||||
val r = runCatching {
|
||||
ControlJson.json.decodeFromString(ControlResponse.serializer(), jsonLine.trim())
|
||||
}.getOrElse {
|
||||
err("internal", "unparseable control output: ${jsonLine.take(200)}")
|
||||
return err("internal", "unparseable control output: ${jsonLine.take(200)}")
|
||||
}
|
||||
if (r.proto != ControlResponse.PROTO_VERSION) {
|
||||
return err(PROTO_MISMATCH, "server proto ${r.proto}, app ${ControlResponse.PROTO_VERSION}")
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
fun transportFailure(message: String): ControlResponse = err(transportCode(message), message)
|
||||
fun transportFailure(message: String, hostKeyChanged: Boolean = false): ControlResponse =
|
||||
err(if (hostKeyChanged) "host_key_changed" else transportCode(message), message)
|
||||
|
||||
private fun transportCode(msg: String): String = when {
|
||||
msg.contains("sudo", ignoreCase = true) && msg.contains("password", ignoreCase = true) -> "sudo_auth_failed"
|
||||
@@ -28,5 +33,7 @@ object ControlResponseParser {
|
||||
}
|
||||
|
||||
private fun err(code: String, msg: String) =
|
||||
ControlResponse(proto = 2, result = "err", code = code, msg = msg)
|
||||
ControlResponse(proto = ControlResponse.PROTO_VERSION, result = "err", code = code, msg = msg)
|
||||
|
||||
const val PROTO_MISMATCH = "proto_mismatch"
|
||||
}
|
||||
@@ -16,12 +16,7 @@ data class Server(
|
||||
val proxyListen: String = "0.0.0.0:56000",
|
||||
val proxyConnect: String = "127.0.0.1:40537",
|
||||
val opts: ServerOpts = ServerOpts()
|
||||
) {
|
||||
companion object {
|
||||
/** Имя-заглушка для записей без имени (data-слой, ресурсы недоступны). */
|
||||
const val FALLBACK_NAME = "Без названия"
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
data class ServersSnapshot(
|
||||
val list: List<Server> = emptyList(),
|
||||
|
||||
@@ -56,7 +56,7 @@ internal object ServerJson {
|
||||
})
|
||||
put("client", JSONObject().apply {
|
||||
put("serverAddress", p.client.serverAddress)
|
||||
put("vkLink", p.client.vkLink)
|
||||
put("callLink", p.client.callLink)
|
||||
put("provider", p.client.provider)
|
||||
put("threads", p.client.threads)
|
||||
put("streamsPerCred", p.client.streamsPerCred)
|
||||
@@ -86,6 +86,10 @@ internal object ServerJson {
|
||||
put("obfTimingMs", p.opts.obfTimingMs)
|
||||
put("proxyMode", p.opts.proxyMode)
|
||||
put("kcp", encodeKcp(p.opts.kcp))
|
||||
put("method", p.opts.method)
|
||||
put("backend", p.opts.backend)
|
||||
put("wgPort", p.opts.wgPort)
|
||||
put("wgNet", p.opts.wgNet)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -95,7 +99,7 @@ internal object ServerJson {
|
||||
val optsO = o.optJSONObject("opts") ?: JSONObject()
|
||||
return Server(
|
||||
id = o.optString("id").ifBlank { UUID.randomUUID().toString() },
|
||||
name = o.optString("name").ifBlank { Server.FALLBACK_NAME },
|
||||
name = o.optString("name"),
|
||||
ssh = SshConfig(
|
||||
ip = sshO.optString("ip"),
|
||||
port = sshO.optInt("port", 22),
|
||||
@@ -109,9 +113,9 @@ internal object ServerJson {
|
||||
),
|
||||
client = ClientConfig(
|
||||
serverAddress = cliO.optString("serverAddress"),
|
||||
vkLink = cliO.optString("vkLink"),
|
||||
provider = cliO.optString("provider", Provider.VK).let {
|
||||
if (it in Provider.VALUES) it else Provider.VK
|
||||
callLink = cliO.optString("callLink"),
|
||||
provider = cliO.optString("provider", Provider.RELAY).let {
|
||||
if (it in Provider.VALUES) it else Provider.RELAY
|
||||
},
|
||||
threads = cliO.optInt("threads", ClientConfig.DEFAULT_THREADS),
|
||||
streamsPerCred = cliO.optInt("streamsPerCred", ClientConfig.DEFAULT_STREAMS_PER_CRED),
|
||||
@@ -150,7 +154,15 @@ internal object ServerJson {
|
||||
proxyMode = optsO.optString("proxyMode", ProxyMode.UDP).let {
|
||||
if (it in ProxyMode.VALUES) it else ProxyMode.UDP
|
||||
},
|
||||
kcp = decodeKcp(optsO.optJSONObject("kcp"))
|
||||
kcp = decodeKcp(optsO.optJSONObject("kcp")),
|
||||
method = optsO.optString("method", ServerMethod.DOCKER).let {
|
||||
if (it in ServerMethod.VALUES) it else ServerMethod.DOCKER
|
||||
},
|
||||
backend = optsO.optString("backend", ServerBackend.NEW).let {
|
||||
if (it in ServerBackend.VALUES) it else ServerBackend.NEW
|
||||
},
|
||||
wgPort = optsO.optInt("wgPort", ServerBackend.DEFAULT_WG_PORT),
|
||||
wgNet = optsO.optString("wgNet").ifBlank { ServerBackend.DEFAULT_WG_NET }
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -13,15 +13,51 @@ data class ServerOpts(
|
||||
val obfProfile: String = ObfProfile.NONE,
|
||||
/** 64-hex obf-ключ (-obf-key). Должен совпадать на клиенте и сервере. */
|
||||
val obfKey: String = "",
|
||||
/** Межпакетная задержка мимикрии (-obf-timing), мс; 0 - выкл. Требует профиля. */
|
||||
/** Межпакетная задержка мимикрии клиента (-obf-timing), мс; 0 - выкл. Требует профиля. */
|
||||
val obfTimingMs: Int = 0,
|
||||
/** Режим проброса (-mode). Сервер отвергает сессию с другим режимом. */
|
||||
val proxyMode: String = ProxyMode.UDP,
|
||||
/** ARQ tcp-режима (-kcp-*); в udp не используется. */
|
||||
val kcp: KcpProfile = KcpProfile.DEFAULT
|
||||
val kcp: KcpProfile = KcpProfile.DEFAULT,
|
||||
val method: String = ServerMethod.DOCKER,
|
||||
val backend: String = ServerBackend.NEW,
|
||||
val wgPort: Int = ServerBackend.DEFAULT_WG_PORT,
|
||||
val wgNet: String = ServerBackend.DEFAULT_WG_NET
|
||||
) {
|
||||
/** Обфускация включена, когда выбран реальный профиль. */
|
||||
val obfEnabled: Boolean get() = obfProfile != ObfProfile.NONE
|
||||
|
||||
val tcpMode: Boolean get() = proxyMode == ProxyMode.TCP
|
||||
|
||||
val ownWg: Boolean get() = backend == ServerBackend.NEW
|
||||
}
|
||||
|
||||
/** Как install.sh запускает FreeTurn; WireGuard всегда на хосте. */
|
||||
object ServerMethod {
|
||||
const val DOCKER = "docker"
|
||||
const val SYSTEMD = "systemd"
|
||||
val VALUES = listOf(DOCKER, SYSTEMD)
|
||||
}
|
||||
|
||||
/** Куда сервер отдаёт трафик: свой WG ft-wg0 или чужой VPN по `-connect`. */
|
||||
object ServerBackend {
|
||||
const val NEW = "new"
|
||||
const val EXTERNAL = "external"
|
||||
val VALUES = listOf(NEW, EXTERNAL)
|
||||
|
||||
const val DEFAULT_WG_PORT = 51820
|
||||
const val DEFAULT_WG_NET = "10.13.13.0/24"
|
||||
|
||||
/** Та же проверка, что valid_net в install.sh: сетевой адрес, префикс /16../29. */
|
||||
fun isValidNet(net: String): Boolean {
|
||||
val m = NET.matchEntire(net.trim()) ?: return false
|
||||
val octets = m.groupValues[1].split('.').map { it.toIntOrNull() ?: return false }
|
||||
if (octets.any { it > 255 }) return false
|
||||
val prefix = m.groupValues[2].toInt()
|
||||
val ip = octets.fold(0L) { acc, o -> (acc shl 8) or o.toLong() }
|
||||
val hostMask = (1L shl (32 - prefix)) - 1
|
||||
return ip and hostMask == 0L
|
||||
}
|
||||
|
||||
private val NET = Regex("""^((?:(?:0|[1-9]\d{0,2})\.){3}(?:0|[1-9]\d{0,2}))/(1[6-9]|2[0-9])$""")
|
||||
}
|
||||
@@ -4,13 +4,16 @@ sealed class SshConnectionState {
|
||||
object Disconnected : SshConnectionState()
|
||||
object Connecting : SshConnectionState()
|
||||
data class Connected(val ip: String) : SshConnectionState()
|
||||
data class Error(val message: String) : SshConnectionState()
|
||||
data class Error(val message: String, val hostKeyChanged: Boolean = false) : SshConnectionState()
|
||||
}
|
||||
|
||||
enum class ServerOperation { APPLY, UPDATE, UPLOAD_BUILD, STOP }
|
||||
|
||||
sealed class ServerState {
|
||||
object Unknown : ServerState()
|
||||
object Checking : ServerState()
|
||||
data class Known(
|
||||
/** Стоит FreeTurn этим установщиком (есть install.conf); старая установка = false. */
|
||||
val installed: Boolean,
|
||||
val running: Boolean,
|
||||
/** Режим живого сервера ("udp" | "tcp"); null - сервер не запущен. */
|
||||
@@ -18,7 +21,7 @@ sealed class ServerState {
|
||||
val obfProfile: String? = null,
|
||||
val version: String? = null
|
||||
) : ServerState()
|
||||
data class Working(val action: String) : ServerState()
|
||||
data class Working(val operation: ServerOperation) : ServerState()
|
||||
data class Error(val message: String) : ServerState()
|
||||
}
|
||||
|
||||
@@ -29,5 +32,7 @@ sealed class UpdateState {
|
||||
object NoUpdate : UpdateState()
|
||||
data class Downloading(val progress: Int) : UpdateState()
|
||||
object ReadyToInstall : UpdateState()
|
||||
data class Error(val message: String) : UpdateState()
|
||||
data class Error(val reason: UpdateError) : UpdateState()
|
||||
}
|
||||
|
||||
enum class UpdateError { RELEASE_UNAVAILABLE, NO_APK, NETWORK, DOWNLOAD_FAILED, SIGNATURE_MISMATCH, FILE_MISSING }
|
||||
@@ -1,9 +1,10 @@
|
||||
package com.freeturn.app.domain.proxy
|
||||
|
||||
import com.freeturn.app.data.AppPreferences
|
||||
import com.freeturn.app.data.config.HostPort
|
||||
import com.freeturn.app.data.server.Server
|
||||
import com.freeturn.app.domain.ServerState
|
||||
import com.freeturn.app.domain.server.applyOptions
|
||||
import com.freeturn.app.domain.server.withApplied
|
||||
import com.freeturn.app.domain.ssh.SshRepository
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
@@ -97,23 +98,29 @@ class ProxyOrchestrator(
|
||||
sshRepository.logNote("рестарт сервера пропущен: $reason")
|
||||
return
|
||||
}
|
||||
val l = prefs.proxyListenFlow.first()
|
||||
val c = prefs.proxyConnectFlow.first()
|
||||
if (!HostPort.isValid(l) || !HostPort.isValid(c)) {
|
||||
sshRepository.logNote("рестарт сервера пропущен: некорректный listen/connect ($l -> $c)")
|
||||
return
|
||||
}
|
||||
val opts = prefs.serverOptsFlow.first()
|
||||
sshRepository.stopServer()
|
||||
sshRepository.startServer(
|
||||
listen = l, connect = c,
|
||||
proxyMode = opts.proxyMode,
|
||||
kcp = opts.kcp,
|
||||
obfProfile = if (opts.obfEnabled) opts.obfProfile else "none",
|
||||
obfKey = if (opts.obfEnabled) opts.obfKey else "",
|
||||
obfTimingMs = opts.obfTimingMs,
|
||||
clientId = prefs.ownClientId()
|
||||
)
|
||||
val server = prefs.serversSnapshot.first().active ?: return
|
||||
val applied = sshRepository.applyServer(server.applyOptions()) ?: return
|
||||
saveApplied(server.withApplied(applied))
|
||||
}
|
||||
|
||||
/**
|
||||
* Профили одного VPS (relay и direct из мастера) делят серверный конфиг: без синхронизации
|
||||
* второй остался бы со старым ключом/режимом и получил бы отлуп сервера.
|
||||
*/
|
||||
suspend fun saveApplied(server: Server) {
|
||||
prefs.serversSnapshot.first().list
|
||||
.filter { it.id == server.id || it.ssh.sameHost(server.ssh) }
|
||||
.forEach { s ->
|
||||
prefs.updateServer(s.id) {
|
||||
it.copy(
|
||||
proxyListen = server.proxyListen,
|
||||
proxyConnect = server.proxyConnect,
|
||||
// obf-timing - пейсинг клиента, серверу его не шлём.
|
||||
opts = server.opts.copy(obfTimingMs = it.opts.obfTimingMs),
|
||||
client = it.client.copy(clientId = server.client.clientId)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Команда START при живой сессии пересоздаёт её с новым конфигом. */
|
||||
|
||||
@@ -1,116 +1,122 @@
|
||||
package com.freeturn.app.domain.server
|
||||
|
||||
import com.freeturn.app.data.config.KcpProfile
|
||||
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.ServerBackend
|
||||
|
||||
/** RPC-команды install.sh (proto 3); argv - `<команда> --ключ=значение`. */
|
||||
sealed class ServerCommand {
|
||||
data object Probe : ServerCommand()
|
||||
data object Install : ServerCommand()
|
||||
|
||||
data class WgSetup(
|
||||
val port: Int,
|
||||
val endpoint: String
|
||||
/**
|
||||
* @param update переустановить сервер, даже если версия не менялась.
|
||||
* @param bin путь на сервере к загруженной локальной сборке - ставится вместо релиза.
|
||||
*/
|
||||
data class Apply(
|
||||
val opts: ApplyOptions,
|
||||
val update: Boolean = false,
|
||||
val bin: String = ""
|
||||
) : ServerCommand()
|
||||
data class Start(val opts: ServerStartOptions) : ServerCommand()
|
||||
data object Stop : ServerCommand()
|
||||
data class FetchLogs(val lines: Int = 80) : ServerCommand()
|
||||
|
||||
data class Uninstall(
|
||||
val withWgPkg: Boolean = false,
|
||||
val dryRun: Boolean = false
|
||||
) : ServerCommand()
|
||||
|
||||
data object ShareInfo : ServerCommand()
|
||||
|
||||
data class PeerAdd(
|
||||
val nameB64: String,
|
||||
val endpoint: String,
|
||||
val clientId: String
|
||||
) : ServerCommand()
|
||||
|
||||
data object ShareList : ServerCommand()
|
||||
|
||||
data class PeerConf(
|
||||
val pubkey: String,
|
||||
val clientId: String,
|
||||
val nameB64: String
|
||||
) : ServerCommand()
|
||||
data class PeerRemove(val pubkey: String) : ServerCommand()
|
||||
|
||||
data class ClientAdd(val nameB64: String, val clientId: String) : ServerCommand()
|
||||
data class ClientRemove(val clientId: String) : ServerCommand()
|
||||
data class Logs(val tail: Int = 80) : ServerCommand()
|
||||
data object ClientList : ServerCommand()
|
||||
data class ClientAdd(val name: String) : ServerCommand()
|
||||
data class ClientConf(val name: String) : ServerCommand()
|
||||
data class ClientRemove(val name: String) : ServerCommand()
|
||||
data object Uninstall : ServerCommand()
|
||||
|
||||
fun toArgv(): List<String> = when (this) {
|
||||
is Probe -> listOf("probe")
|
||||
is Install -> listOf("install")
|
||||
is WgSetup -> buildList {
|
||||
add("wg-setup")
|
||||
add("--port=$port")
|
||||
add("--endpoint=$endpoint")
|
||||
}
|
||||
is Start -> buildList {
|
||||
add("start")
|
||||
add("--listen=${opts.listen}")
|
||||
add("--connect=${opts.connect}")
|
||||
if (opts.proxyMode == ProxyMode.TCP) {
|
||||
add("--mode=${ProxyMode.TCP}")
|
||||
addAll(kcpArgs(opts.kcp))
|
||||
}
|
||||
if (opts.obfProfile != "none" && opts.obfKey.isNotBlank()) {
|
||||
add("--obf-profile=${opts.obfProfile}")
|
||||
add("--obf-key=${opts.obfKey}")
|
||||
// Пейсинг без профиля ядро отвергает - только внутри этой ветки.
|
||||
if (opts.obfTimingMs > 0) add("--obf-timing=${opts.obfTimingMs}ms")
|
||||
}
|
||||
if (opts.clientId.isNotBlank()) add("--client-id=${opts.clientId}")
|
||||
is Apply -> buildList {
|
||||
addAll(opts.toArgv())
|
||||
if (update) add("--update")
|
||||
if (bin.isNotEmpty()) add("--bin=$bin")
|
||||
}
|
||||
is Stop -> listOf("stop")
|
||||
is FetchLogs -> listOf("logs", "--tail=$lines")
|
||||
is ShareInfo -> listOf("share-info")
|
||||
is PeerAdd -> buildList {
|
||||
add("peer-add")
|
||||
add("--name-b64=$nameB64")
|
||||
add("--endpoint=$endpoint")
|
||||
if (clientId.isNotBlank()) add("--client-id=$clientId")
|
||||
}
|
||||
is ShareList -> listOf("share-list")
|
||||
is PeerConf -> buildList {
|
||||
add("peer-conf")
|
||||
add("--pubkey=$pubkey")
|
||||
if (clientId.isNotBlank()) add("--client-id=$clientId")
|
||||
if (nameB64.isNotBlank()) add("--name-b64=$nameB64")
|
||||
}
|
||||
is PeerRemove -> listOf("peer-remove", "--pubkey=$pubkey")
|
||||
is ClientAdd -> listOf("client-add", "--name-b64=$nameB64", "--client-id=$clientId")
|
||||
is ClientRemove -> listOf("client-remove", "--client-id=$clientId")
|
||||
is Uninstall -> buildList {
|
||||
add("uninstall")
|
||||
if (withWgPkg) add("--with-wg-pkg")
|
||||
if (dryRun) add("--dry-run")
|
||||
}
|
||||
is Logs -> listOf("logs", "--tail=$tail")
|
||||
is ClientList -> listOf("client-list")
|
||||
is ClientAdd -> listOf("client-add", "--name=$name")
|
||||
is ClientConf -> listOf("client-conf", "--name=$name")
|
||||
is ClientRemove -> listOf("client-remove", "--name=$name")
|
||||
// Снос целиком: приложение не ведёт серверы, где FreeTurn удалён, а WG оставлен.
|
||||
is Uninstall -> listOf("uninstall", "--target=all", "--purge")
|
||||
}
|
||||
}
|
||||
|
||||
data class ServerStartOptions(
|
||||
val listen: String,
|
||||
val connect: String,
|
||||
/**
|
||||
* Полный конфиг сервера для `apply`: скрипт хранит его в install.conf, поэтому шлём
|
||||
* всё, а не дельту - иначе на сервере осталось бы значение прошлой установки.
|
||||
*/
|
||||
data class ApplyOptions(
|
||||
val method: String,
|
||||
val backend: String,
|
||||
val listenPort: Int,
|
||||
/** host:port чужого VPN; только для [ServerBackend.EXTERNAL]. */
|
||||
val connect: String = "",
|
||||
val wgPort: Int = ServerBackend.DEFAULT_WG_PORT,
|
||||
val wgNet: String = ServerBackend.DEFAULT_WG_NET,
|
||||
val proxyMode: String = ProxyMode.UDP,
|
||||
val kcp: KcpProfile = KcpProfile.DEFAULT,
|
||||
val obfProfile: String = "none",
|
||||
val obfKey: String = "",
|
||||
val obfTimingMs: Int = 0,
|
||||
val clientId: String = ""
|
||||
val obfProfile: String = ObfProfile.NONE,
|
||||
/** Пусто при включённой обфускации - ключ сгенерирует сервер и вернёт в ответе. */
|
||||
val obfKey: String = ""
|
||||
) {
|
||||
fun toArgv(): List<String> = buildList {
|
||||
add("apply")
|
||||
add("--method=$method")
|
||||
add("--backend=$backend")
|
||||
add("--listen-port=$listenPort")
|
||||
if (backend == ServerBackend.EXTERNAL) {
|
||||
add("--connect=$connect")
|
||||
} else {
|
||||
add("--wg-port=$wgPort")
|
||||
add("--wg-net=$wgNet")
|
||||
}
|
||||
add("--mode=$proxyMode")
|
||||
add("--obf-profile=$obfProfile")
|
||||
if (obfProfile != ObfProfile.NONE && obfKey.isNotBlank()) add("--obf-key=$obfKey")
|
||||
if (proxyMode == ProxyMode.TCP) addAll(kcpArgs(kcp))
|
||||
}
|
||||
}
|
||||
|
||||
/** KCP_ARGS на сервере перезаписываются целиком: шлём весь профиль, не только отличия. */
|
||||
private fun kcpArgs(p: KcpProfile): List<String> = listOf(
|
||||
"--kcp-nodelay=${p.noDelay}",
|
||||
"--kcp-interval=${p.interval}",
|
||||
"--kcp-resend=${p.resend}",
|
||||
"--kcp-nc=${p.nc}",
|
||||
"--kcp-sndwnd=${p.sndWnd}",
|
||||
"--kcp-rcvwnd=${p.rcvWnd}",
|
||||
"--kcp-mtu=${p.mtu}",
|
||||
"--kcp-acknodelay=${p.ackNoDelay}"
|
||||
)
|
||||
|
||||
/** Только отличия от дефолта: остальное сервер возьмёт своё, как и клиент. */
|
||||
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}")
|
||||
}
|
||||
fun Server.applyOptions(): ApplyOptions = ApplyOptions(
|
||||
method = opts.method,
|
||||
backend = opts.backend,
|
||||
listenPort = proxyListen.substringAfterLast(':').toIntOrNull() ?: DEFAULT_LISTEN_PORT,
|
||||
connect = proxyConnect,
|
||||
wgPort = opts.wgPort,
|
||||
wgNet = opts.wgNet,
|
||||
proxyMode = opts.proxyMode,
|
||||
kcp = opts.kcp,
|
||||
obfProfile = opts.obfProfile,
|
||||
obfKey = opts.obfKey
|
||||
)
|
||||
|
||||
private const val DEFAULT_LISTEN_PORT = 56000
|
||||
|
||||
/** Итог `apply`: что сервер выдал сам и что надо положить в профиль. */
|
||||
data class ApplyResult(
|
||||
val ownerClientId: String,
|
||||
/** Клиентский WG-конфиг хозяина; пусто при чужом VPN. */
|
||||
val ownerConf: String,
|
||||
val obfKey: String
|
||||
)
|
||||
|
||||
/** Client ID хозяина и ключ после apply - иначе клиент не пройдёт allowlist или OBF. */
|
||||
fun Server.withApplied(r: ApplyResult): Server = copy(
|
||||
client = client.copy(clientId = r.ownerClientId.ifBlank { client.clientId }),
|
||||
opts = opts.copy(obfKey = r.obfKey)
|
||||
)
|
||||
@@ -9,16 +9,18 @@ import com.freeturn.app.domain.ssh.SshResult
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/** Запускает [ServerCommand] на удалённом хосте, стримя скрипт через SSH stdin. */
|
||||
/** Запускает [ServerCommand] на удалённом хосте, стримя install.sh через SSH stdin. */
|
||||
class ServerControl(
|
||||
context: Context,
|
||||
private val ssh: SSHManager
|
||||
) {
|
||||
private val appContext = context.applicationContext
|
||||
|
||||
// CR ломает bash построчно - на случай, если ассет прошёл через autocrlf.
|
||||
private val script: String by lazy {
|
||||
appContext.assets.open(SCRIPT_ASSET).bufferedReader(Charsets.UTF_8)
|
||||
.use { it.readText() }
|
||||
.replace("\r\n", "\n")
|
||||
}
|
||||
|
||||
/** Команда запуска скрипта с эскалацией по rootMode (скрипт идёт в stdin). */
|
||||
@@ -39,7 +41,7 @@ class ServerControl(
|
||||
|
||||
suspend fun run(cfg: SshConfig, cmd: ServerCommand): ControlResponse = withContext(Dispatchers.IO) {
|
||||
if (cfg.ip.isBlank()) {
|
||||
return@withContext ControlResponse(proto = 2, result = "err", code = "transport", msg = "no SSH config")
|
||||
return@withContext ControlResponseParser.transportFailure("no SSH config")
|
||||
}
|
||||
val stdin = if (cfg.rootMode == SshConfig.SUDO_PASS) {
|
||||
effectiveSudoPassword(cfg) + "\n" + script
|
||||
@@ -54,11 +56,14 @@ class ServerControl(
|
||||
command = remoteCmd(cmd.toArgv(), cfg),
|
||||
stdin = stdin,
|
||||
knownFingerprint = cfg.hostFingerprint.ifEmpty { null },
|
||||
sshKey = if (cfg.authType == SshConfig.AUTH_SSH_KEY) cfg.sshKey else ""
|
||||
sshKey = if (cfg.authType == SshConfig.AUTH_SSH_KEY) cfg.sshKey else "",
|
||||
// RPC молчит до конца команды, а read-timeout JSch считает тишину: get.docker.com
|
||||
// и docker pull в apply идут минутами.
|
||||
execTimeoutMs = if (cmd is ServerCommand.Apply) APPLY_TIMEOUT_MS else EXEC_TIMEOUT_MS
|
||||
)
|
||||
when (result) {
|
||||
is SshResult.Output -> ControlResponseParser.parse(result.text)
|
||||
is SshResult.Failure -> ControlResponseParser.transportFailure(result.message)
|
||||
is SshResult.Failure -> ControlResponseParser.transportFailure(result.message, result.hostKeyChanged)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,19 +81,85 @@ class ServerControl(
|
||||
(result as? SshResult.Output)?.let { classifyRootMode(it.text) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Заворачивает значение в одинарные кавычки для bash. Любая `'` внутри
|
||||
* заменяется на `'\''` - стандартный приём.
|
||||
*/
|
||||
/** Локальные сборки сервера вшиты только в debug с `freeturnAar=local` (отладка ядра). */
|
||||
val hasLocalBinaries: Boolean by lazy {
|
||||
appContext.assets.list(LOCAL_BIN_DIR).orEmpty().isNotEmpty()
|
||||
}
|
||||
|
||||
/** Загружает вшитую сборку под архитектуру хоста; успех - путь на сервере для `apply --bin`. */
|
||||
suspend fun uploadLocalBinary(cfg: SshConfig): Result<String> = withContext(Dispatchers.IO) {
|
||||
val knownFp = cfg.hostFingerprint.ifEmpty { null }
|
||||
val key = if (cfg.authType == SshConfig.AUTH_SSH_KEY) cfg.sshKey else ""
|
||||
val uname = when (val r = ssh.executeSilentCommand(
|
||||
cfg.ip, cfg.port, cfg.username, cfg.password, "uname -m",
|
||||
knownFingerprint = knownFp, sshKey = key
|
||||
)) {
|
||||
is SshResult.Output -> r.text.lines().lastOrNull { it.isNotBlank() }?.trim().orEmpty()
|
||||
is SshResult.Failure -> return@withContext uploadFailure(r.message, r.errorCode())
|
||||
}
|
||||
val asset = serverAsset(uname)
|
||||
?: return@withContext uploadFailure(
|
||||
"архитектура хоста \"$uname\" не поддерживается",
|
||||
ServerErrorCode.UNSUPPORTED_ARCH
|
||||
)
|
||||
val bytes = runCatching { appContext.assets.open("$LOCAL_BIN_DIR/$asset").use { it.readBytes() } }
|
||||
.getOrElse {
|
||||
return@withContext uploadFailure("в приложении нет сборки $asset", ServerErrorCode.UNSUPPORTED_ARCH)
|
||||
}
|
||||
|
||||
// Без sudo: /tmp доступен любому, в /opt кладёт уже скрипт под root.
|
||||
val r = ssh.executeWithBytes(
|
||||
cfg.ip, cfg.port, cfg.username, cfg.password,
|
||||
"f=\$(mktemp /tmp/freeturn-server.XXXXXX) && cat > \"\$f\" && echo \"$UPLOAD_MARK\$f\"",
|
||||
stdin = bytes,
|
||||
knownFingerprint = knownFp,
|
||||
sshKey = key,
|
||||
execTimeoutMs = APPLY_TIMEOUT_MS
|
||||
)
|
||||
when (r) {
|
||||
is SshResult.Output -> r.text.lines().map { it.trim() }
|
||||
.firstOrNull { it.startsWith(UPLOAD_MARK) }
|
||||
?.let { Result.success(it.removePrefix(UPLOAD_MARK)) }
|
||||
?: uploadFailure(
|
||||
"сервер не подтвердил загрузку $asset: ${r.text.ifBlank { "пустой ответ" }}",
|
||||
ServerErrorCode.TRANSPORT
|
||||
)
|
||||
is SshResult.Failure -> uploadFailure(r.message, r.errorCode())
|
||||
}
|
||||
}
|
||||
|
||||
private fun SshResult.Failure.errorCode(): ServerErrorCode =
|
||||
if (hostKeyChanged) ServerErrorCode.HOST_KEY_CHANGED else ServerErrorCode.TRANSPORT
|
||||
|
||||
private fun uploadFailure(message: String, code: ServerErrorCode): Result<Nothing> =
|
||||
Result.failure(ServerCommandException(message, code))
|
||||
|
||||
/** Одинарные кавычки для bash; `'` внутри - стандартный `'\''`. */
|
||||
private fun shellQuote(s: String): String {
|
||||
if (s.isEmpty()) return "''"
|
||||
// Если строка состоит только из безопасных символов - обходимся без кавычек.
|
||||
if (s.matches(Regex("^[A-Za-z0-9._:=\\-/]+$"))) return s
|
||||
return "'" + s.replace("'", "'\\''") + "'"
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val SCRIPT_ASSET = "free-turn-control.sh"
|
||||
const val SCRIPT_ASSET = "install.sh"
|
||||
private const val EXEC_TIMEOUT_MS = 180_000
|
||||
private const val APPLY_TIMEOUT_MS = 900_000
|
||||
private const val LOCAL_BIN_DIR = "server"
|
||||
private const val UPLOAD_MARK = "FT_BIN="
|
||||
|
||||
/**
|
||||
* `uname -m` -> имя ассета релиза, как server_asset в install.sh. mips не берём:
|
||||
* endianness видна только на самом хосте.
|
||||
*/
|
||||
fun serverAsset(uname: String): String? = when {
|
||||
uname == "x86_64" || uname == "amd64" -> "server-linux-amd64"
|
||||
uname == "aarch64" || uname == "arm64" -> "server-linux-arm64"
|
||||
uname.startsWith("armv7") -> "server-linux-armv7"
|
||||
uname.matches(Regex("i[3-6]86")) -> "server-linux-386"
|
||||
uname == "riscv64" -> "server-linux-riscv64"
|
||||
else -> null
|
||||
}
|
||||
|
||||
/** Классификация вывода preflight в [SshConfig].rootMode-константу. */
|
||||
fun classifyRootMode(output: String): String {
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
package com.freeturn.app.domain.server
|
||||
|
||||
import com.freeturn.app.data.control.ApplyData
|
||||
import com.freeturn.app.data.control.ControlJson
|
||||
import com.freeturn.app.data.control.ControlResponse
|
||||
import com.freeturn.app.data.control.decodeBase64
|
||||
|
||||
/** Машиночитаемый код ошибки control-скрипта (см. server-control ERR_CODE). */
|
||||
/** Код ошибки RPC install.sh (список - в шапке скрипта) плюс транспортные коды приложения. */
|
||||
enum class ServerErrorCode {
|
||||
BAD_ARG, NOT_WRITABLE, LOCK_FAILED, UNSUPPORTED_ARCH,
|
||||
NOT_INSTALLED, DOWNLOAD_FAILED, VERSION_RESOLVE_FAILED, NOT_ELF, TOO_SMALL, SHA_MISMATCH,
|
||||
WG_TOOLS_MISSING, WG_KERNEL_MISSING, WG_USERSPACE_MISSING, WG_UP_FAILED, WG_PORT_BUSY,
|
||||
NO_WG_BACKEND, PEER_ADD_FAILED, CONF_REWRITE_FAILED, NO_STORED_CONF, BASE64_MISSING,
|
||||
LISTEN_PORT_BUSY, START_FAILED, CLIENTS_CMD_FAILED,
|
||||
NEEDS_ROOT, SUDO_AUTH_FAILED, SUDO_REQUIRETTY, SUDO_UNAVAILABLE,
|
||||
BAD_ARG, NEEDS_ROOT, NOT_INSTALLED, UNSUPPORTED_ARCH, NO_SYSTEMD, DOCKER_FAILED,
|
||||
DOWNLOAD_FAILED, WG_UNSUPPORTED, WG_INSTALL_FAILED, WG_CONFLICT, BACKEND_LOCKED, PORT_BUSY,
|
||||
SUBNET_CONFLICT, SUBNET_FULL, HOST_UNKNOWN, EXISTS, NOT_FOUND, OWNER_PROTECTED, START_FAILED,
|
||||
SUDO_AUTH_FAILED, SUDO_REQUIRETTY, PROTO_MISMATCH, HOST_KEY_CHANGED,
|
||||
TRANSPORT, INTERNAL, UNKNOWN;
|
||||
|
||||
companion object {
|
||||
@@ -43,3 +43,8 @@ fun ControlResponse.asUnit(): Result<Unit> =
|
||||
/** ok -> декодируем data в [T]; err -> failure с кодом/текстом. */
|
||||
inline fun <reified T> ControlResponse.requireData(): Result<T> =
|
||||
if (isOk) runCatching { ControlJson.decode<T>(data) } else toFailure()
|
||||
|
||||
fun ControlResponse.applyResult(): Result<ApplyResult> =
|
||||
requireData<ApplyData>().map {
|
||||
ApplyResult(it.owner.clientId, decodeBase64(it.owner.confB64).orEmpty(), it.obfKey)
|
||||
}
|
||||
@@ -3,9 +3,6 @@ package com.freeturn.app.domain.server
|
||||
import android.content.Context
|
||||
import com.freeturn.app.data.config.SshConfig
|
||||
import com.freeturn.app.data.control.ProbeData
|
||||
import com.freeturn.app.data.control.UninstallData
|
||||
import com.freeturn.app.data.control.WgSetupData
|
||||
import com.freeturn.app.data.control.decodeBase64
|
||||
import com.freeturn.app.domain.ssh.SSHManager
|
||||
|
||||
class ServerSetupRepository(context: Context, private val ssh: SSHManager) {
|
||||
@@ -16,48 +13,13 @@ class ServerSetupRepository(context: Context, private val ssh: SSHManager) {
|
||||
|
||||
suspend fun detectRootMode(cfg: SshConfig): String? = control.detectRootMode(cfg)
|
||||
|
||||
data class ProbeResult(
|
||||
val wgPort: Int?
|
||||
)
|
||||
suspend fun probe(cfg: SshConfig): Result<ProbeData> =
|
||||
control.run(cfg, ServerCommand.Probe).requireData<ProbeData>()
|
||||
|
||||
data class WgSetupResult(
|
||||
val port: Int,
|
||||
val clientConf: String?,
|
||||
val existed: Boolean
|
||||
)
|
||||
suspend fun apply(cfg: SshConfig, opts: ApplyOptions): Result<ApplyResult> =
|
||||
control.run(cfg, ServerCommand.Apply(opts)).applyResult()
|
||||
|
||||
suspend fun probe(cfg: SshConfig): Result<ProbeResult> =
|
||||
control.run(cfg, ServerCommand.Probe)
|
||||
.requireData<ProbeData>()
|
||||
.map { ProbeResult(wgPort = it.wg.port) }
|
||||
|
||||
suspend fun install(cfg: SshConfig): Result<Unit> =
|
||||
control.run(cfg, ServerCommand.Install).asUnit()
|
||||
|
||||
suspend fun wgSetup(
|
||||
cfg: SshConfig,
|
||||
port: Int,
|
||||
endpoint: String
|
||||
): Result<WgSetupResult> =
|
||||
control.run(cfg, ServerCommand.WgSetup(port, endpoint))
|
||||
.requireData<WgSetupData>()
|
||||
.map {
|
||||
WgSetupResult(
|
||||
port = it.wg.port.takeIf { p -> p > 0 } ?: port,
|
||||
clientConf = decodeBase64(it.clientConfB64),
|
||||
existed = it.wg.existed
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun start(cfg: SshConfig, opts: ServerStartOptions): Result<Unit> =
|
||||
control.run(cfg, ServerCommand.Start(opts)).asUnit()
|
||||
|
||||
/**
|
||||
* Снос free-turn-proxy с сервера: бинарь, unit, НАШ ft-wg0, clients, PREFIX.
|
||||
* Чужой WG/общий ip_forward не трогаем (скрипт сам решает по маркерам).
|
||||
* [withWgPkg] - снести и пакет wireguard-tools, но лишь если ставили его мы.
|
||||
*/
|
||||
suspend fun uninstall(cfg: SshConfig, withWgPkg: Boolean = false): Result<UninstallData> =
|
||||
control.run(cfg, ServerCommand.Uninstall(withWgPkg = withWgPkg))
|
||||
.requireData<UninstallData>()
|
||||
/** Снос FreeTurn, нашего ft-wg0 и каталога установки; чужой WG скрипт не трогает. */
|
||||
suspend fun uninstall(cfg: SshConfig): Result<Unit> =
|
||||
control.run(cfg, ServerCommand.Uninstall).asUnit()
|
||||
}
|
||||
@@ -18,7 +18,8 @@ private const val CONNECT_TIMEOUT_MS = 5000
|
||||
sealed interface SshResult {
|
||||
/** stdout+stderr команды (`exec 2>&1`). */
|
||||
data class Output(val text: String) : SshResult
|
||||
data class Failure(val message: String) : SshResult
|
||||
/** [hostKeyChanged] - ключ хоста не совпал с сохранённым (возможна подмена). */
|
||||
data class Failure(val message: String, val hostKeyChanged: Boolean = false) : SshResult
|
||||
}
|
||||
|
||||
class SSHManager {
|
||||
@@ -39,11 +40,23 @@ class SSHManager {
|
||||
knownFingerprint: String? = null,
|
||||
sshKey: String = "",
|
||||
execTimeoutMs: Int = 180_000
|
||||
): SshResult = exec(
|
||||
ip, port, user, pass, command, stdin.toLf().toByteArray(Charsets.UTF_8),
|
||||
knownFingerprint, sshKey, execTimeoutMs
|
||||
)
|
||||
|
||||
/** Бинарный stdin как есть, без LF-нормализации. */
|
||||
suspend fun executeWithBytes(
|
||||
ip: String, port: Int, user: String, pass: String,
|
||||
command: String, stdin: ByteArray,
|
||||
knownFingerprint: String? = null,
|
||||
sshKey: String = "",
|
||||
execTimeoutMs: Int = 180_000
|
||||
): SshResult = exec(ip, port, user, pass, command, stdin, knownFingerprint, sshKey, execTimeoutMs)
|
||||
|
||||
private suspend fun exec(
|
||||
ip: String, port: Int, user: String, pass: String,
|
||||
command: String, stdin: String?,
|
||||
command: String, stdin: ByteArray?,
|
||||
knownFingerprint: String?, sshKey: String, execTimeoutMs: Int
|
||||
): SshResult = withContext(Dispatchers.IO) {
|
||||
val tofu = TofuHostKeyRepository(knownFingerprint)
|
||||
@@ -54,7 +67,7 @@ class SSHManager {
|
||||
session.timeout = execTimeoutMs
|
||||
SshResult.Output(runCommand(session, command, stdin, execTimeoutMs))
|
||||
} catch (e: Exception) {
|
||||
SshResult.Failure(failureMessage(e, tofu, knownFingerprint))
|
||||
failure(e, tofu, knownFingerprint)
|
||||
} finally {
|
||||
session?.disconnect()
|
||||
}
|
||||
@@ -67,7 +80,7 @@ class SSHManager {
|
||||
val jsch = JSch()
|
||||
if (sshKey.isNotBlank()) addKeyIdentity(jsch, sshKey, pass)
|
||||
val session = jsch.getSession(user, ip, port)
|
||||
if (sshKey.isBlank()) session.setPassword(pass)
|
||||
if (sshKey.isBlank()) session.setPassword(pass.toByteArray(Charsets.UTF_8))
|
||||
configureTofuHostKeyChecking(session, tofu)
|
||||
try {
|
||||
session.connect(CONNECT_TIMEOUT_MS)
|
||||
@@ -79,14 +92,12 @@ class SSHManager {
|
||||
}
|
||||
|
||||
private fun runCommand(
|
||||
session: Session, command: String, stdin: String?, execTimeoutMs: Int
|
||||
session: Session, command: String, stdin: ByteArray?, execTimeoutMs: Int
|
||||
): String {
|
||||
val channel = session.openChannel("exec") as ChannelExec
|
||||
// stderr объединяется с stdout для единого ответа управляющего скрипта.
|
||||
channel.setCommand("exec 2>&1\n${command.toLf()}")
|
||||
if (stdin != null) {
|
||||
channel.inputStream = ByteArrayInputStream(stdin.toLf().toByteArray(Charsets.UTF_8))
|
||||
}
|
||||
if (stdin != null) channel.inputStream = ByteArrayInputStream(stdin)
|
||||
|
||||
val inStream = channel.inputStream
|
||||
channel.connect(execTimeoutMs)
|
||||
@@ -102,16 +113,13 @@ class SSHManager {
|
||||
return output.trim()
|
||||
}
|
||||
|
||||
private fun failureMessage(e: Exception, tofu: TofuHostKeyRepository, knownFingerprint: String?): String {
|
||||
val isMitm = tofu.capturedFingerprint != null &&
|
||||
knownFingerprint != null &&
|
||||
tofu.capturedFingerprint != knownFingerprint
|
||||
return if (isMitm) {
|
||||
"Отпечаток сервера изменился - возможна MITM-атака\n" +
|
||||
"Ожидался: $knownFingerprint\n" +
|
||||
"Получен: ${tofu.capturedFingerprint}"
|
||||
private fun failure(e: Exception, tofu: TofuHostKeyRepository, knownFingerprint: String?): SshResult.Failure {
|
||||
val captured = tofu.capturedFingerprint
|
||||
// Отпечатки - в сообщение для журнала SSH; UI показывает свой текст по флагу.
|
||||
return if (captured != null && knownFingerprint != null && captured != knownFingerprint) {
|
||||
SshResult.Failure("host key изменился: ожидался $knownFingerprint, получен $captured", hostKeyChanged = true)
|
||||
} else {
|
||||
e.message ?: e.javaClass.simpleName
|
||||
SshResult.Failure(e.message ?: e.javaClass.simpleName)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -150,10 +158,10 @@ internal fun verifyConnectedFingerprint(
|
||||
capturedFingerprint: String?
|
||||
): String {
|
||||
val received = checkNotNull(capturedFingerprint) {
|
||||
"SSH-сервер не предоставил ключ для проверки"
|
||||
"сервер не предъявил host key"
|
||||
}
|
||||
check(knownFingerprint == null || knownFingerprint == received) {
|
||||
"Отпечаток SSH-сервера изменился"
|
||||
"host key не совпал с сохранённым"
|
||||
}
|
||||
return received
|
||||
}
|
||||
|
||||
@@ -1,20 +1,21 @@
|
||||
package com.freeturn.app.domain.ssh
|
||||
|
||||
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.control.ControlResponse
|
||||
import com.freeturn.app.data.control.InstallData
|
||||
import com.freeturn.app.data.control.LogsData
|
||||
import com.freeturn.app.data.control.ProbeData
|
||||
import com.freeturn.app.domain.ServerOperation
|
||||
import com.freeturn.app.domain.ServerState
|
||||
import com.freeturn.app.domain.SshConnectionState
|
||||
import com.freeturn.app.domain.server.ApplyOptions
|
||||
import com.freeturn.app.domain.server.ApplyResult
|
||||
import com.freeturn.app.domain.server.ServerCommand
|
||||
import com.freeturn.app.domain.server.ServerControl
|
||||
import com.freeturn.app.domain.server.ServerStartOptions
|
||||
import com.freeturn.app.domain.server.applyResult
|
||||
import com.freeturn.app.domain.server.errorText
|
||||
import com.freeturn.app.domain.server.requireData
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
@@ -72,10 +73,10 @@ class SshRepository(context: Context, private val sshManager: SSHManager) {
|
||||
val batch = buildList {
|
||||
addAll(result.logs)
|
||||
if (result.isOk) {
|
||||
// Примитивы - без кавычек JsonElement.toString (version=1.6.0, а не "1.6.0");
|
||||
// объекты/массивы (wg, conflicts) остаются компактным JSON.
|
||||
// Только примитивы: в объектах (config, owner) лежат obf-ключ и приватный WG-конфиг.
|
||||
result.data.forEach { (k, v) ->
|
||||
add(" $k=" + ((v as? JsonPrimitive)?.contentOrNull ?: v.toString()))
|
||||
val p = v as? JsonPrimitive ?: return@forEach
|
||||
if (k != "obf_key") add(" $k=" + (p.contentOrNull ?: p.toString()))
|
||||
}
|
||||
} else {
|
||||
add("ERROR: ${result.errorText()}")
|
||||
@@ -119,11 +120,10 @@ class SshRepository(context: Context, private val sshManager: SSHManager) {
|
||||
checkServerStateLocked(activeSshConfig, silent = false)
|
||||
true
|
||||
} else {
|
||||
val message = when (result) {
|
||||
is SshResult.Failure -> result.message
|
||||
is SshResult.Output -> result.text
|
||||
_sshState.value = when (result) {
|
||||
is SshResult.Failure -> SshConnectionState.Error(result.message, result.hostKeyChanged)
|
||||
is SshResult.Output -> SshConnectionState.Error(result.text)
|
||||
}
|
||||
_sshState.value = SshConnectionState.Error(message)
|
||||
false
|
||||
}
|
||||
}
|
||||
@@ -153,91 +153,52 @@ class SshRepository(context: Context, private val sshManager: SSHManager) {
|
||||
val r = runCmd(cfg, "Проверка состояния", ServerCommand.Probe)
|
||||
r.requireData<ProbeData>()
|
||||
.onSuccess { d ->
|
||||
val c = d.config
|
||||
_serverState.value = ServerState.Known(
|
||||
installed = d.installed,
|
||||
installed = d.installed && c != null,
|
||||
running = d.running,
|
||||
mode = if (d.running) d.mode ?: ProxyMode.UDP else null,
|
||||
obfProfile = if (d.running) d.obf else null,
|
||||
mode = if (d.running) c?.mode?.ifBlank { null } ?: ProxyMode.UDP else null,
|
||||
obfProfile = if (d.running) c?.obfProfile else null,
|
||||
version = d.version
|
||||
)
|
||||
}
|
||||
.onFailure { e -> _serverState.value = ServerState.Error(e.message ?: r.errorText()) }
|
||||
}
|
||||
|
||||
suspend fun installServer(): InstallResult = mutex.withLock {
|
||||
val cfg = activeSshConfig ?: return@withLock InstallResult.Failed("not connected")
|
||||
if (cfg.ip.isEmpty()) return@withLock InstallResult.Failed("no SSH config")
|
||||
_serverState.value = ServerState.Working("Установка free-turn-proxy...")
|
||||
|
||||
val result = runCmd(cfg, "Установка", ServerCommand.Install)
|
||||
result.requireData<InstallData>().fold(
|
||||
onSuccess = { d ->
|
||||
// Работающий процесс остаётся на старом бинарнике до перезапуска.
|
||||
if (d.needsRestart) {
|
||||
appendSshLog(" needs_restart -> авто-рестарт сервера")
|
||||
runCmd(cfg, "Авто-остановка перед рестартом", ServerCommand.Stop)
|
||||
}
|
||||
delay(300)
|
||||
checkServerStateLocked(cfg, silent = true)
|
||||
InstallResult.Success(stage = d.stage, version = d.version, needsRestart = d.needsRestart)
|
||||
},
|
||||
onFailure = { e ->
|
||||
val msg = e.message ?: result.errorText()
|
||||
suspend fun applyServer(opts: ApplyOptions, update: Boolean = false): ApplyResult? = mutex.withLock {
|
||||
val cfg = activeSshConfig ?: return@withLock null
|
||||
if (cfg.ip.isEmpty()) return@withLock null
|
||||
var bin = ""
|
||||
if (update && serverControl.hasLocalBinaries) {
|
||||
_serverState.value = ServerState.Working(ServerOperation.UPLOAD_BUILD)
|
||||
logHeader("Загрузка локальной сборки сервера", "${cfg.username}@${cfg.ip}:${cfg.port}")
|
||||
bin = serverControl.uploadLocalBinary(cfg).getOrElse { e ->
|
||||
val msg = e.message ?: e.toString()
|
||||
appendSshLog("ERROR: $msg")
|
||||
_serverState.value = ServerState.Error(msg)
|
||||
InstallResult.Failed(msg)
|
||||
return@withLock null
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun startServer(
|
||||
listen: String,
|
||||
connect: String,
|
||||
proxyMode: String = ProxyMode.UDP,
|
||||
kcp: KcpProfile = KcpProfile.DEFAULT,
|
||||
obfProfile: String = "none",
|
||||
obfKey: String = "",
|
||||
obfTimingMs: Int = 0,
|
||||
clientId: String = ""
|
||||
): Boolean = mutex.withLock {
|
||||
val cfg = activeSshConfig ?: return@withLock false
|
||||
if (cfg.ip.isEmpty()) return@withLock false
|
||||
|
||||
_serverState.value = ServerState.Working("Запуск сервера...")
|
||||
val result = runCmd(
|
||||
cfg, "Запуск",
|
||||
ServerCommand.Start(
|
||||
ServerStartOptions(
|
||||
listen = listen,
|
||||
connect = connect,
|
||||
proxyMode = proxyMode,
|
||||
kcp = kcp,
|
||||
obfProfile = obfProfile,
|
||||
obfKey = obfKey,
|
||||
obfTimingMs = obfTimingMs,
|
||||
clientId = clientId
|
||||
)
|
||||
)
|
||||
)
|
||||
if (!result.isOk) {
|
||||
_serverState.value = ServerState.Error(result.errorText())
|
||||
return@withLock false
|
||||
appendSshLog(" bin=$bin")
|
||||
}
|
||||
delay(1500)
|
||||
checkServerStateLocked(cfg, silent = true)
|
||||
true
|
||||
_serverState.value = ServerState.Working(
|
||||
if (update) ServerOperation.UPDATE else ServerOperation.APPLY
|
||||
)
|
||||
val result = runCmd(cfg, if (update) "Обновление" else "Применение", ServerCommand.Apply(opts, update, bin))
|
||||
result.applyResult()
|
||||
.onSuccess { checkServerStateLocked(cfg, silent = true) }
|
||||
.onFailure { _serverState.value = ServerState.Error(result.errorText()) }
|
||||
.getOrNull()
|
||||
}
|
||||
|
||||
suspend fun stopServer() = mutex.withLock {
|
||||
val cfg = activeSshConfig ?: return@withLock
|
||||
if (cfg.ip.isEmpty()) return@withLock
|
||||
_serverState.value = ServerState.Working("Остановка сервера...")
|
||||
|
||||
_serverState.value = ServerState.Working(ServerOperation.STOP)
|
||||
val result = runCmd(cfg, "Остановка", ServerCommand.Stop)
|
||||
if (!result.isOk) {
|
||||
_serverState.value = ServerState.Error(result.errorText())
|
||||
return@withLock
|
||||
}
|
||||
delay(1000)
|
||||
checkServerStateLocked(cfg, silent = true)
|
||||
}
|
||||
|
||||
@@ -246,7 +207,11 @@ class SshRepository(context: Context, private val sshManager: SSHManager) {
|
||||
if (cfg.ip.isEmpty()) return@withLock
|
||||
_logsLoading.value = true
|
||||
try {
|
||||
runCmd(cfg, "server.log", ServerCommand.FetchLogs(lines))
|
||||
logHeader("Журнал сервера", "${cfg.username}@${cfg.ip}:${cfg.port}")
|
||||
val result = serverControl.run(cfg, ServerCommand.Logs(lines))
|
||||
result.requireData<LogsData>()
|
||||
.onSuccess { appendSshLog(it.lines) }
|
||||
.onFailure { appendSshLog("ERROR: ${result.errorText()}") }
|
||||
} finally {
|
||||
_logsLoading.value = false
|
||||
}
|
||||
@@ -269,18 +234,4 @@ class SshRepository(context: Context, private val sshManager: SSHManager) {
|
||||
disconnect()
|
||||
_sshLog.value = emptyList()
|
||||
}
|
||||
|
||||
sealed class InstallResult {
|
||||
/**
|
||||
* stage: cached | downloaded; version - только если ядро вернуло.
|
||||
* needsRestart - true, если бинарь был переустановлен поверх работающего
|
||||
* процесса; перед использованием новой версии нужен start.
|
||||
*/
|
||||
data class Success(
|
||||
val stage: String,
|
||||
val version: String?,
|
||||
val needsRestart: Boolean = false
|
||||
) : InstallResult()
|
||||
data class Failed(val message: String) : InstallResult()
|
||||
}
|
||||
}
|
||||
@@ -20,7 +20,6 @@ import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import com.freeturn.app.R
|
||||
import com.freeturn.app.ui.util.HapticUtil
|
||||
import com.freeturn.app.data.control.UninstallData
|
||||
import com.freeturn.app.ui.components.BusyProgressIndicator
|
||||
import com.freeturn.app.ui.theme.Spacing
|
||||
import com.freeturn.app.viewmodel.server.ServerCleanupState
|
||||
@@ -39,6 +38,7 @@ internal fun DeleteServerDialog(
|
||||
text = { Text(stringResource(R.string.server_delete_confirm_desc, serverName)) },
|
||||
confirmButton = {
|
||||
TextButton(
|
||||
shapes = ButtonDefaults.shapes(),
|
||||
onClick = {
|
||||
HapticUtil.perform(context, HapticUtil.Pattern.ERROR)
|
||||
onConfirm()
|
||||
@@ -47,7 +47,7 @@ internal fun DeleteServerDialog(
|
||||
) { Text(stringResource(R.string.server_delete)) }
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }
|
||||
TextButton(shapes = ButtonDefaults.shapes(), onClick = onDismiss) { Text(stringResource(R.string.cancel)) }
|
||||
}
|
||||
)
|
||||
}
|
||||
@@ -76,12 +76,12 @@ internal fun ServerCleanupDialog(
|
||||
},
|
||||
confirmButton = {}
|
||||
)
|
||||
is ServerCleanupState.Done -> AlertDialog(
|
||||
ServerCleanupState.Done -> AlertDialog(
|
||||
onDismissRequest = {},
|
||||
title = { Text(stringResource(R.string.server_delete_done_title)) },
|
||||
text = { CleanupResult(state.data) },
|
||||
text = { Text(stringResource(R.string.server_delete_done_desc)) },
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
TextButton(shapes = ButtonDefaults.shapes(), onClick = {
|
||||
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
|
||||
onClose()
|
||||
}) { Text(stringResource(R.string.server_delete_done_confirm)) }
|
||||
@@ -107,6 +107,7 @@ internal fun ServerCleanupDialog(
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(
|
||||
shapes = ButtonDefaults.shapes(),
|
||||
onClick = {
|
||||
HapticUtil.perform(context, HapticUtil.Pattern.ERROR)
|
||||
onConfirm()
|
||||
@@ -117,7 +118,7 @@ internal fun ServerCleanupDialog(
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = onClose) { Text(stringResource(R.string.cancel)) }
|
||||
TextButton(shapes = ButtonDefaults.shapes(), onClick = onClose) { Text(stringResource(R.string.cancel)) }
|
||||
}
|
||||
)
|
||||
}
|
||||
@@ -146,6 +147,7 @@ internal fun RenameServerDialog(
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(
|
||||
shapes = ButtonDefaults.shapes(),
|
||||
onClick = {
|
||||
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
|
||||
onSave(newName)
|
||||
@@ -154,67 +156,7 @@ internal fun RenameServerDialog(
|
||||
) { Text(stringResource(R.string.save)) }
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }
|
||||
TextButton(shapes = ButtonDefaults.shapes(), onClick = onDismiss) { Text(stringResource(R.string.cancel)) }
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
/** Итог удалённой очистки: что снесли с сервера и что не тронули. */
|
||||
@Composable
|
||||
private fun CleanupResult(data: UninstallData) {
|
||||
Column {
|
||||
Text(
|
||||
stringResource(R.string.server_delete_done_desc),
|
||||
style = MaterialTheme.typography.bodyMedium
|
||||
)
|
||||
Spacer(Modifier.height(Spacing.md))
|
||||
|
||||
val r = data.removed
|
||||
val removed = buildList {
|
||||
if (r.binary) add(R.string.cleanup_item_binary)
|
||||
if (r.unit || r.legacyUnit) add(R.string.cleanup_item_service)
|
||||
if (r.wgIface) add(R.string.cleanup_item_wg)
|
||||
if (data.wgPkgRemoved) add(R.string.cleanup_item_wg_pkg)
|
||||
if (r.ufw) add(R.string.cleanup_item_firewall)
|
||||
if (r.prefix) add(R.string.cleanup_item_files)
|
||||
}
|
||||
if (removed.isEmpty()) {
|
||||
Text(
|
||||
stringResource(R.string.cleanup_nothing),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
} else {
|
||||
Text(
|
||||
stringResource(R.string.cleanup_removed_label),
|
||||
style = MaterialTheme.typography.labelLarge
|
||||
)
|
||||
removed.forEach {
|
||||
Text("• " + stringResource(it), style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
}
|
||||
|
||||
if (data.kept.isNotEmpty()) {
|
||||
Spacer(Modifier.height(Spacing.md))
|
||||
Text(
|
||||
stringResource(R.string.cleanup_kept_label),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
data.kept.forEach { token ->
|
||||
// kept-токены - контракт _kept_add (80-cmd.sh); незнакомый показываем как есть.
|
||||
val label = when (token) {
|
||||
"foreign_ft_wg0" -> stringResource(R.string.cleanup_kept_foreign_wg)
|
||||
"wireguard-tools" -> stringResource(R.string.cleanup_kept_wg_tools)
|
||||
"ip_forward" -> stringResource(R.string.cleanup_kept_ip_forward)
|
||||
else -> token
|
||||
}
|
||||
Text(
|
||||
"• $label",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -42,6 +42,7 @@ import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.freeturn.app.R
|
||||
import com.freeturn.app.data.config.Provider
|
||||
import com.freeturn.app.ui.util.HapticUtil
|
||||
import com.freeturn.app.domain.SshConnectionState
|
||||
import com.freeturn.app.ui.components.SectionLabel
|
||||
@@ -52,6 +53,7 @@ import com.freeturn.app.ui.components.SettingsEntryRow
|
||||
import com.freeturn.app.ui.components.SettingsGroup
|
||||
import com.freeturn.app.ui.components.SettingsGroupItem
|
||||
import com.freeturn.app.ui.components.SettingsSwitchRow
|
||||
import com.freeturn.app.ui.components.providerLabel
|
||||
import com.freeturn.app.ui.navigation.NAV_SLIDE_MS
|
||||
import com.freeturn.app.ui.theme.Spacing
|
||||
import com.freeturn.app.ui.util.redact
|
||||
@@ -140,6 +142,10 @@ fun ServerDetailScreen(
|
||||
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
|
||||
serverViewModel.installServer()
|
||||
},
|
||||
onUpdate = {
|
||||
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
|
||||
serverViewModel.updateServer()
|
||||
},
|
||||
onStart = {
|
||||
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
|
||||
serverViewModel.startServer()
|
||||
@@ -201,7 +207,7 @@ fun ServerDetailScreen(
|
||||
}
|
||||
}
|
||||
|
||||
SectionLabel(stringResource(R.string.provider_vk_calls))
|
||||
SectionLabel(providerLabel(server?.client?.provider ?: Provider.RELAY))
|
||||
// "Настройки сервера": при sync ON правки пушатся на сервер -> нужен живой
|
||||
// SSH; при sync OFF клиент-локальны -> вход доступен и оффлайн. Правило
|
||||
// общее с ServerManagementScreen - serverSettingsAvailable.
|
||||
@@ -334,6 +340,7 @@ fun ServerDetailScreen(
|
||||
private fun ServerHubActionsFab(
|
||||
online: ServerHubState.Online?,
|
||||
onInstall: () -> Unit,
|
||||
onUpdate: () -> Unit,
|
||||
onStart: () -> Unit,
|
||||
onStop: () -> Unit,
|
||||
onRename: () -> Unit,
|
||||
@@ -361,7 +368,7 @@ private fun ServerHubActionsFab(
|
||||
) {
|
||||
if (online != null) {
|
||||
FloatingActionButtonMenuItem(
|
||||
onClick = { expanded = false; onInstall() },
|
||||
onClick = { expanded = false; if (online.installed) onUpdate() else onInstall() },
|
||||
icon = { Icon(painterResource(R.drawable.cloud_download_24px), contentDescription = null) },
|
||||
text = {
|
||||
Text(stringResource(
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
|
||||
package com.freeturn.app.ui.screens.serverdetail
|
||||
|
||||
import androidx.annotation.StringRes
|
||||
import androidx.compose.animation.AnimatedContent
|
||||
import androidx.compose.animation.SizeTransform
|
||||
import androidx.compose.animation.animateColorAsState
|
||||
@@ -27,6 +28,7 @@ import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
@@ -44,6 +46,7 @@ import androidx.compose.ui.unit.IntSize
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.util.lerp
|
||||
import com.freeturn.app.R
|
||||
import com.freeturn.app.domain.ServerOperation
|
||||
import com.freeturn.app.ui.components.BusyProgressIndicator
|
||||
import com.freeturn.app.ui.theme.LocalReducedMotion
|
||||
import com.freeturn.app.ui.theme.extendedColorScheme
|
||||
@@ -93,7 +96,7 @@ internal fun ServerStatusCard(
|
||||
when (s) {
|
||||
is ServerHubState.Online -> OnlineContent(s)
|
||||
ServerHubState.Connecting -> BusyContent(stringResource(R.string.pill_connecting))
|
||||
is ServerHubState.Working -> BusyContent(s.action)
|
||||
is ServerHubState.Working -> BusyContent(stringResource(s.operation.labelRes()))
|
||||
ServerHubState.Failed -> FailedContent(onRetry)
|
||||
ServerHubState.Offline -> OfflineContent(onActivate)
|
||||
ServerHubState.NotPaired -> NotPairedContent()
|
||||
@@ -206,7 +209,7 @@ private fun FailedContent(onRetry: () -> Unit) {
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
title = stringResource(R.string.hub_connect_failed)
|
||||
)
|
||||
Button(onClick = onRetry, modifier = Modifier.fillMaxWidth(), shape = MaterialTheme.shapes.large) {
|
||||
Button(shapes = ButtonDefaults.shapes(), onClick = onRetry, modifier = Modifier.fillMaxWidth()) {
|
||||
Text(stringResource(R.string.reconnect))
|
||||
}
|
||||
}
|
||||
@@ -218,7 +221,7 @@ private fun OfflineContent(onActivate: () -> Unit) {
|
||||
title = stringResource(R.string.pill_offline),
|
||||
subtitle = stringResource(R.string.server_inactive_desc)
|
||||
)
|
||||
Button(onClick = onActivate, modifier = Modifier.fillMaxWidth(), shape = MaterialTheme.shapes.large) {
|
||||
Button(shapes = ButtonDefaults.shapes(), onClick = onActivate, modifier = Modifier.fillMaxWidth()) {
|
||||
Text(stringResource(R.string.make_active))
|
||||
}
|
||||
}
|
||||
@@ -231,3 +234,11 @@ private fun NotPairedContent() {
|
||||
subtitle = stringResource(R.string.not_paired_hint)
|
||||
)
|
||||
}
|
||||
|
||||
@StringRes
|
||||
private fun ServerOperation.labelRes(): Int = when (this) {
|
||||
ServerOperation.APPLY -> R.string.hub_op_apply
|
||||
ServerOperation.UPDATE -> R.string.hub_op_update
|
||||
ServerOperation.UPLOAD_BUILD -> R.string.hub_op_upload_build
|
||||
ServerOperation.STOP -> R.string.hub_op_stop
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
@@ -50,9 +51,9 @@ internal fun HeroCard(
|
||||
textAlign = TextAlign.Center
|
||||
)
|
||||
Button(
|
||||
shapes = ButtonDefaults.shapes(),
|
||||
onClick = onAction,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = MaterialTheme.shapes.large
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) { Text(actionLabel) }
|
||||
}
|
||||
}
|
||||
|
||||
+17
-25
@@ -11,29 +11,19 @@ import com.freeturn.app.ui.components.SettingsCard
|
||||
import com.freeturn.app.ui.components.SettingsFieldSlot
|
||||
import com.freeturn.app.ui.components.SettingsRowDivider
|
||||
|
||||
/** Серверный конфиг прокси: listen-IP/порт и TURN-адрес. SSH-only, показывается при живом подключении. */
|
||||
/**
|
||||
* Серверный конфиг прокси: внешний порт и адрес чужого VPN. SSH-only, при живом подключении.
|
||||
* [connect] null - свой WG, адрес бэкенда выводит сервер.
|
||||
*/
|
||||
@Composable
|
||||
internal fun ServerConfigCard(
|
||||
listenIp: String,
|
||||
onListenIp: (String) -> Unit,
|
||||
listenPort: String,
|
||||
onListenPort: (String) -> Unit,
|
||||
connect: String,
|
||||
connect: String?,
|
||||
onConnect: (String) -> Unit
|
||||
) {
|
||||
SectionLabel(stringResource(R.string.server_config))
|
||||
SettingsCard {
|
||||
SettingsFieldSlot {
|
||||
LabeledTextField(
|
||||
value = listenIp,
|
||||
onValueChange = { v -> onListenIp(v.filter { c -> c.isDigit() || c == '.' || c == ':' }) },
|
||||
labelRes = R.string.listen_ip,
|
||||
placeholderRes = R.string.listen_ip_placeholder,
|
||||
supportingRes = R.string.listen_ip_desc,
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri)
|
||||
)
|
||||
}
|
||||
SettingsRowDivider()
|
||||
SettingsFieldSlot {
|
||||
LabeledTextField(
|
||||
value = listenPort,
|
||||
@@ -44,16 +34,18 @@ internal fun ServerConfigCard(
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
|
||||
)
|
||||
}
|
||||
SettingsRowDivider()
|
||||
SettingsFieldSlot {
|
||||
LabeledTextField(
|
||||
value = connect,
|
||||
onValueChange = onConnect,
|
||||
labelRes = R.string.turn_client_address,
|
||||
placeholderRes = R.string.turn_client_placeholder,
|
||||
supportingRes = R.string.turn_client_desc,
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri)
|
||||
)
|
||||
if (connect != null) {
|
||||
SettingsRowDivider()
|
||||
SettingsFieldSlot {
|
||||
LabeledTextField(
|
||||
value = connect,
|
||||
onValueChange = onConnect,
|
||||
labelRes = R.string.setup_connect_label,
|
||||
placeholderRes = R.string.setup_connect_placeholder,
|
||||
supportingRes = R.string.setup_connect_desc,
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+12
-12
@@ -24,6 +24,8 @@ import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.IconButtonDefaults
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
@@ -95,9 +97,6 @@ fun ServerManagementScreen(
|
||||
val effClient = if (isActive) clientCfg else (server?.client ?: clientCfg)
|
||||
val effServer = if (isActive) serverOpts else (server?.opts ?: serverOpts)
|
||||
|
||||
var proxyListenIp by rememberSaveable(savedListen) {
|
||||
mutableStateOf(savedListen.substringBeforeLast(":", "0.0.0.0").ifBlank { "0.0.0.0" })
|
||||
}
|
||||
var proxyListenPort by rememberSaveable(savedListen) { mutableStateOf(savedListen.substringAfterLast(":", "56000")) }
|
||||
var proxyConnect by rememberSaveable(savedConnect) { mutableStateOf(savedConnect) }
|
||||
var tcpDraft by rememberSaveable(effServer.tcpMode) { mutableStateOf(effServer.tcpMode) }
|
||||
@@ -114,7 +113,8 @@ fun ServerManagementScreen(
|
||||
val isWorking = serverState is ServerState.Working || serverState is ServerState.Checking
|
||||
val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior()
|
||||
|
||||
val listenFull = "${proxyListenIp.ifBlank { "0.0.0.0" }}:$proxyListenPort"
|
||||
// install.sh слушает на всех интерфейсах: настраивается только порт.
|
||||
val listenFull = "0.0.0.0:$proxyListenPort"
|
||||
val proxyDirty = listenFull != savedListen || proxyConnect != savedConnect
|
||||
val configDirty = proxyDirty ||
|
||||
tcpDraft != effServer.tcpMode ||
|
||||
@@ -123,7 +123,8 @@ fun ServerManagementScreen(
|
||||
timingDraft != effServer.obfTimingMs
|
||||
val keyOkForApply = obfDraft == ObfProfile.NONE || keyDraft.isBlank() ||
|
||||
ObfProfile.isValidKey(keyDraft)
|
||||
val addressesOk = HostPort.isValid(listenFull) && HostPort.isValid(proxyConnect)
|
||||
// При своём WG connect выводит сервер (127.0.0.1:wg-port) - поле скрыто и не проверяется.
|
||||
val addressesOk = HostPort.isValid(listenFull) && (effServer.ownWg || HostPort.isValid(proxyConnect))
|
||||
|
||||
val applyVisible = serverSettingsAvailable(isConnected, syncOn) && configDirty
|
||||
val applyBlocked = when {
|
||||
@@ -153,7 +154,7 @@ fun ServerManagementScreen(
|
||||
LargeFlexibleTopAppBar(
|
||||
title = { Text(stringResource(R.string.provider_server_settings)) },
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onBack) {
|
||||
IconButton(shapes = IconButtonDefaults.shapes(), onClick = onBack) {
|
||||
Icon(
|
||||
painterResource(R.drawable.arrow_back_24px),
|
||||
contentDescription = stringResource(R.string.back)
|
||||
@@ -164,7 +165,7 @@ fun ServerManagementScreen(
|
||||
actions = {
|
||||
if (isActive && onEditConnection != null) {
|
||||
Box {
|
||||
IconButton(onClick = { showServerMenu = true }) {
|
||||
IconButton(shapes = IconButtonDefaults.shapes(), onClick = { showServerMenu = true }) {
|
||||
Icon(
|
||||
painterResource(R.drawable.more_vert_24px),
|
||||
contentDescription = stringResource(R.string.change_server)
|
||||
@@ -272,11 +273,9 @@ fun ServerManagementScreen(
|
||||
|
||||
if (isConnected) {
|
||||
ServerConfigCard(
|
||||
listenIp = proxyListenIp,
|
||||
onListenIp = { proxyListenIp = it },
|
||||
listenPort = proxyListenPort,
|
||||
onListenPort = { proxyListenPort = it },
|
||||
connect = proxyConnect,
|
||||
connect = proxyConnect.takeUnless { effServer.ownWg },
|
||||
onConnect = { proxyConnect = it }
|
||||
)
|
||||
}
|
||||
@@ -286,9 +285,10 @@ fun ServerManagementScreen(
|
||||
ServerSyncCard(
|
||||
tcp = tcpDraft,
|
||||
onTcp = { tcpDraft = it },
|
||||
tcpBlocked = effClient.wireGuardActive,
|
||||
// Свой WG на сервере живёт только в udp (install.sh отвергнет tcp).
|
||||
tcpBlocked = effClient.wireGuardActive || effServer.ownWg,
|
||||
obfProfile = obfDraft,
|
||||
onObfProfile = { HapticUtil.perform(context, HapticUtil.Pattern.TOGGLE_ON); obfDraft = it },
|
||||
onObfProfile = { obfDraft = it },
|
||||
keyDraft = keyDraft,
|
||||
onKeyDraft = { keyDraft = it },
|
||||
savedObfKey = effServer.obfKey,
|
||||
|
||||
@@ -3,28 +3,24 @@
|
||||
package com.freeturn.app.ui.screens.servermanagement
|
||||
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
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.Icon
|
||||
import androidx.compose.material3.IconButtonDefaults
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
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.painterResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import com.freeturn.app.R
|
||||
import com.freeturn.app.data.config.ObfProfile
|
||||
import com.freeturn.app.ui.components.ChoiceOption
|
||||
import com.freeturn.app.ui.components.OptionDropdown
|
||||
import com.freeturn.app.ui.components.SectionLabel
|
||||
import com.freeturn.app.ui.components.obfProfileLabel
|
||||
import com.freeturn.app.ui.components.SettingsCard
|
||||
import com.freeturn.app.ui.components.SettingsControlLabel
|
||||
import com.freeturn.app.ui.components.SettingsFieldSlot
|
||||
@@ -70,7 +66,12 @@ internal fun ServerSyncCard(
|
||||
SettingsRowDivider()
|
||||
SettingsFieldSlot {
|
||||
SettingsControlLabel(stringResource(R.string.obf_profile_title))
|
||||
ObfProfileDropdown(obfProfile = obfProfile, onObfProfile = onObfProfile)
|
||||
OptionDropdown(
|
||||
label = stringResource(R.string.obf_profile_title),
|
||||
options = ObfProfile.VALUES.map { ChoiceOption(it, obfProfileLabel(it)) },
|
||||
selected = obfProfile,
|
||||
onSelect = onObfProfile
|
||||
)
|
||||
}
|
||||
SettingsRowDivider()
|
||||
if (obfProfile != ObfProfile.NONE) {
|
||||
@@ -85,7 +86,7 @@ internal fun ServerSyncCard(
|
||||
isError = keyDraft.isNotBlank() && !ObfProfile.isValidKey(keyDraft),
|
||||
trailingIcon = {
|
||||
if (savedObfKey.isNotBlank() && !privacyMode) {
|
||||
IconButton(onClick = onCopyKey) {
|
||||
IconButton(shapes = IconButtonDefaults.shapes(), onClick = onCopyKey) {
|
||||
Icon(
|
||||
painterResource(R.drawable.content_copy_24px),
|
||||
contentDescription = stringResource(R.string.copy)
|
||||
@@ -105,6 +106,7 @@ internal fun ServerSyncCard(
|
||||
)
|
||||
if (!privacyMode) {
|
||||
TextButton(
|
||||
shapes = ButtonDefaults.shapes(),
|
||||
onClick = onRegenKey,
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
@@ -143,50 +145,3 @@ internal fun ServerSyncCard(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun obfProfileLabel(value: String): String = when (value) {
|
||||
ObfProfile.NONE -> stringResource(R.string.obf_none)
|
||||
ObfProfile.RTPOPUS -> stringResource(R.string.obf_rtpopus)
|
||||
ObfProfile.RTPOPUS2 -> stringResource(R.string.obf_rtpopus2)
|
||||
ObfProfile.RTPOPUS3 -> stringResource(R.string.obf_rtpopus3)
|
||||
else -> value
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ObfProfileDropdown(
|
||||
obfProfile: String,
|
||||
onObfProfile: (String) -> Unit,
|
||||
modifier: Modifier = Modifier
|
||||
) {
|
||||
var expanded by remember { mutableStateOf(false) }
|
||||
val current = obfProfileLabel(obfProfile)
|
||||
|
||||
ExposedDropdownMenuBox(
|
||||
expanded = expanded,
|
||||
onExpandedChange = { expanded = !expanded },
|
||||
modifier = modifier
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value = current,
|
||||
onValueChange = {},
|
||||
readOnly = true,
|
||||
label = { Text(stringResource(R.string.obf_profile_title)) },
|
||||
trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) },
|
||||
modifier = Modifier
|
||||
.menuAnchor(ExposedDropdownMenuAnchorType.PrimaryNotEditable, true)
|
||||
.fillMaxWidth()
|
||||
)
|
||||
ExposedDropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) {
|
||||
ObfProfile.VALUES.forEach { value ->
|
||||
DropdownMenuItem(
|
||||
text = { Text(obfProfileLabel(value)) },
|
||||
onClick = {
|
||||
expanded = false
|
||||
onObfProfile(value)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -38,12 +38,11 @@ import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.freeturn.app.R
|
||||
import com.freeturn.app.data.CoreCommand
|
||||
import com.freeturn.app.data.config.ObfProfile
|
||||
import com.freeturn.app.data.config.toCoreJson
|
||||
import com.freeturn.app.domain.proxy.ProxyEngine
|
||||
import com.freeturn.app.data.server.Server
|
||||
import com.freeturn.app.domain.server.ServerCommand
|
||||
import com.freeturn.app.domain.server.ServerStartOptions
|
||||
import com.freeturn.app.domain.server.applyOptions
|
||||
import com.freeturn.app.ui.util.HapticUtil
|
||||
import com.freeturn.app.ui.components.SettingsBackButton
|
||||
import com.freeturn.app.ui.components.SettingsContentMaxWidth
|
||||
@@ -288,23 +287,14 @@ private fun clientCommandLine(engine: ProxyEngine, server: Server, privacy: Bool
|
||||
)
|
||||
|
||||
private fun serverCommandLine(server: Server, privacy: Boolean): String {
|
||||
val opts = ServerStartOptions(
|
||||
listen = server.proxyListen,
|
||||
connect = server.proxyConnect,
|
||||
proxyMode = server.opts.proxyMode,
|
||||
kcp = server.opts.kcp,
|
||||
obfProfile = if (server.opts.obfEnabled) server.opts.obfProfile else ObfProfile.NONE,
|
||||
obfKey = if (server.opts.obfEnabled) server.opts.obfKey else "",
|
||||
obfTimingMs = server.opts.obfTimingMs
|
||||
)
|
||||
// Серверные флаги в форме --flag=value: маскируем хвост после '=' у секретов.
|
||||
val shown = ServerCommand.Start(opts).toArgv().joinToString(" ") { tok ->
|
||||
// Флаги в форме --flag=value: маскируем хвост после '=' у секретов.
|
||||
val shown = ServerCommand.Apply(server.applyOptions()).toArgv().joinToString(" ") { tok ->
|
||||
val eq = tok.indexOf('=')
|
||||
if (eq > 0 && tok.substring(0, eq) == "--obf-key")
|
||||
tok.substring(0, eq + 1) + tok.substring(eq + 1).redact(privacy)
|
||||
else tok
|
||||
}
|
||||
return "free-turn-control.sh $shown"
|
||||
return "install.sh $shown"
|
||||
}
|
||||
|
||||
@Composable
|
||||
|
||||
@@ -23,6 +23,8 @@ import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.FilledTonalButton
|
||||
import androidx.compose.material3.IconButtonDefaults
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.FilledTonalIconButton
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.LoadingIndicator
|
||||
@@ -96,6 +98,7 @@ internal fun SshLogCard(
|
||||
) {
|
||||
if (canFetchJournal) {
|
||||
FilledTonalButton(
|
||||
shapes = ButtonDefaults.shapes(),
|
||||
onClick = onFetchJournal,
|
||||
enabled = !logsLoading,
|
||||
modifier = Modifier.weight(1f)
|
||||
@@ -115,14 +118,14 @@ internal fun SshLogCard(
|
||||
}
|
||||
if (lines.isNotEmpty()) {
|
||||
if (canFetchJournal) {
|
||||
FilledTonalIconButton(onClick = onClear) {
|
||||
FilledTonalIconButton(shapes = IconButtonDefaults.shapes(), onClick = onClear) {
|
||||
Icon(
|
||||
painterResource(R.drawable.delete_24px),
|
||||
contentDescription = stringResource(R.string.clear)
|
||||
)
|
||||
}
|
||||
} else {
|
||||
FilledTonalButton(onClick = onClear, modifier = Modifier.weight(1f)) {
|
||||
FilledTonalButton(shapes = ButtonDefaults.shapes(), onClick = onClear, modifier = Modifier.weight(1f)) {
|
||||
Icon(
|
||||
painterResource(R.drawable.delete_24px),
|
||||
contentDescription = null,
|
||||
|
||||
@@ -6,8 +6,6 @@
|
||||
package com.freeturn.app.ui.screens.setup
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.animation.AnimatedContent
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.EnterTransition
|
||||
@@ -42,6 +40,7 @@ import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.ExtendedFloatingActionButton
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.LargeFlexibleTopAppBar
|
||||
@@ -55,7 +54,6 @@ import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
@@ -76,9 +74,6 @@ import com.freeturn.app.ui.components.SettingsContentMaxWidth
|
||||
import com.freeturn.app.ui.theme.LocalReducedMotion
|
||||
import com.freeturn.app.viewmodel.server.ServerSetupViewModel
|
||||
import com.freeturn.app.viewmodel.server.SetupStep
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.koin.androidx.compose.koinViewModel
|
||||
import com.freeturn.app.ui.theme.Spacing
|
||||
|
||||
@@ -114,37 +109,20 @@ fun ServerSetupScreen(
|
||||
title = { Text(stringResource(R.string.setup_abort_title)) },
|
||||
text = { Text(stringResource(R.string.setup_abort_text)) },
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
TextButton(shapes = ButtonDefaults.shapes(), onClick = {
|
||||
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
|
||||
showAbortDialog = false
|
||||
viewModel.backToConfig()
|
||||
}) { Text(stringResource(R.string.setup_abort_confirm)) }
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { showAbortDialog = false }) {
|
||||
TextButton(shapes = ButtonDefaults.shapes(), onClick = { showAbortDialog = false }) {
|
||||
Text(stringResource(R.string.setup_abort_stay))
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
val scope = rememberCoroutineScope()
|
||||
val wgFilePicker = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri ->
|
||||
if (uri != null) {
|
||||
scope.launch {
|
||||
val text = withContext(Dispatchers.IO) {
|
||||
runCatching {
|
||||
context.contentResolver.openInputStream(uri)?.bufferedReader()?.use { it.readText() }
|
||||
}.getOrNull()
|
||||
}
|
||||
if (!text.isNullOrBlank()) {
|
||||
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
|
||||
viewModel.setConfig(viewModel.uiState.value.config.copy(wgConfText = text))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val fab: SetupFab? = when {
|
||||
state.step == SetupStep.Ssh && !state.checkingSsh ->
|
||||
SetupFab(R.string.setup_continue, R.drawable.chevron_right_24px) {
|
||||
@@ -267,14 +245,12 @@ fun ServerSetupScreen(
|
||||
)
|
||||
SetupStep.Config -> SetupConfigStep(
|
||||
draft = state.config,
|
||||
wgDetectedPort = state.wgDetectedPort,
|
||||
reinstall = state.reinstall,
|
||||
duplicateHost = state.duplicateHost,
|
||||
portsClash = state.portsClash,
|
||||
showErrors = highlightErrors,
|
||||
onDraftChange = viewModel::setConfig,
|
||||
onRollListenPort = viewModel::rollListenPort,
|
||||
onRollWgPort = viewModel::rollWgPort,
|
||||
onLoadWgFile = { wgFilePicker.launch("*/*") }
|
||||
onRollListenPort = viewModel::rollListenPort
|
||||
)
|
||||
SetupStep.Install -> SetupInstallStep(
|
||||
install = state.install,
|
||||
|
||||
@@ -7,32 +7,20 @@ package com.freeturn.app.ui.screens.setup
|
||||
|
||||
import androidx.compose.animation.animateContentSize
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
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.Icon
|
||||
import androidx.compose.material3.IconButtonDefaults
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.SegmentedButton
|
||||
import androidx.compose.material3.SegmentedButtonDefaults
|
||||
import androidx.compose.material3.SingleChoiceSegmentedButtonRow
|
||||
import androidx.compose.material3.Surface
|
||||
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.platform.LocalContext
|
||||
import androidx.compose.ui.res.painterResource
|
||||
@@ -42,12 +30,18 @@ import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.unit.IntSize
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.freeturn.app.R
|
||||
import com.freeturn.app.data.config.AccessProtocol
|
||||
import com.freeturn.app.data.config.HostPort
|
||||
import com.freeturn.app.data.config.ObfProfile
|
||||
import com.freeturn.app.data.server.ServerBackend
|
||||
import com.freeturn.app.data.server.ServerMethod
|
||||
import com.freeturn.app.ui.util.HapticUtil
|
||||
import com.freeturn.app.ui.components.ChoiceOption
|
||||
import com.freeturn.app.ui.components.ConnectedChoiceRow
|
||||
import com.freeturn.app.ui.components.OptionDropdown
|
||||
import com.freeturn.app.ui.components.obfProfileLabel
|
||||
import com.freeturn.app.ui.components.SectionLabel
|
||||
import com.freeturn.app.ui.components.SettingsControlLabel
|
||||
import com.freeturn.app.ui.components.SettingsCard
|
||||
import com.freeturn.app.ui.components.SettingsEntryRow
|
||||
import com.freeturn.app.ui.components.SettingsFieldSlot
|
||||
import com.freeturn.app.ui.components.SettingsRowDivider
|
||||
import com.freeturn.app.ui.components.UdpTcpSegmented
|
||||
@@ -59,22 +53,22 @@ import com.freeturn.app.ui.theme.Spacing
|
||||
@Composable
|
||||
fun SetupConfigStep(
|
||||
draft: SetupConfigDraft,
|
||||
wgDetectedPort: Int?,
|
||||
reinstall: Boolean,
|
||||
duplicateHost: Boolean,
|
||||
portsClash: Boolean,
|
||||
showErrors: Boolean,
|
||||
onDraftChange: (SetupConfigDraft) -> Unit,
|
||||
onRollListenPort: () -> Unit,
|
||||
onRollWgPort: () -> Unit,
|
||||
onLoadWgFile: () -> Unit
|
||||
onRollListenPort: () -> Unit
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val reducedMotion = LocalReducedMotion.current
|
||||
val resizeSpec = MaterialTheme.motionScheme.defaultSpatialSpec<IntSize>()
|
||||
val cardModifier =
|
||||
if (reducedMotion) Modifier else Modifier.animateContentSize(resizeSpec)
|
||||
|
||||
if (duplicateHost) DuplicateHostPanel()
|
||||
when {
|
||||
reinstall -> InfoPanel(stringResource(R.string.setup_reinstall))
|
||||
duplicateHost -> InfoPanel(stringResource(R.string.setup_duplicate_host))
|
||||
}
|
||||
|
||||
SectionLabel(stringResource(R.string.server_name_label))
|
||||
SettingsCard {
|
||||
@@ -91,149 +85,102 @@ fun SetupConfigStep(
|
||||
}
|
||||
}
|
||||
|
||||
SectionLabel(stringResource(R.string.setup_mode_section))
|
||||
SectionLabel(stringResource(R.string.setup_backend_section))
|
||||
SettingsCard(modifier = cardModifier) {
|
||||
SettingsFieldSlot {
|
||||
SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) {
|
||||
SegmentedButton(
|
||||
selected = draft.vpnMode,
|
||||
onClick = {
|
||||
if (!draft.vpnMode) {
|
||||
HapticUtil.perform(context, HapticUtil.Pattern.TOGGLE_ON)
|
||||
onDraftChange(draft.copy(vpnMode = true))
|
||||
}
|
||||
},
|
||||
shape = SegmentedButtonDefaults.itemShape(index = 0, count = 2)
|
||||
) { Text(stringResource(R.string.mode_vpn)) }
|
||||
SegmentedButton(
|
||||
selected = !draft.vpnMode,
|
||||
onClick = {
|
||||
if (draft.vpnMode) {
|
||||
HapticUtil.perform(context, HapticUtil.Pattern.TOGGLE_ON)
|
||||
onDraftChange(draft.copy(vpnMode = false))
|
||||
}
|
||||
},
|
||||
shape = SegmentedButtonDefaults.itemShape(index = 1, count = 2)
|
||||
) { Text(stringResource(R.string.mode_proxy)) }
|
||||
}
|
||||
Text(
|
||||
stringResource(
|
||||
if (draft.vpnMode) R.string.setup_mode_vpn_desc
|
||||
else R.string.setup_mode_proxy_desc
|
||||
SettingsControlLabel(stringResource(R.string.setup_backend_label))
|
||||
ConnectedChoiceRow(
|
||||
options = listOf(
|
||||
ChoiceOption(ServerBackend.NEW, stringResource(R.string.setup_backend_new)),
|
||||
ChoiceOption(ServerBackend.EXTERNAL, stringResource(R.string.setup_backend_external))
|
||||
),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
selected = draft.backend,
|
||||
onSelect = { onDraftChange(draft.copy(backend = it)) }
|
||||
)
|
||||
Hint(stringResource(
|
||||
if (draft.ownWg) R.string.setup_backend_new_desc else R.string.setup_backend_external_desc
|
||||
))
|
||||
}
|
||||
SettingsRowDivider()
|
||||
if (draft.vpnMode) {
|
||||
SettingsFieldSlot {
|
||||
SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) {
|
||||
SegmentedButton(
|
||||
selected = !draft.wgCustomConf,
|
||||
onClick = {
|
||||
if (draft.wgCustomConf) {
|
||||
HapticUtil.perform(context, HapticUtil.Pattern.TOGGLE_ON)
|
||||
onDraftChange(draft.copy(wgCustomConf = false))
|
||||
}
|
||||
},
|
||||
shape = SegmentedButtonDefaults.itemShape(index = 0, count = 2)
|
||||
) { Text(stringResource(R.string.setup_wg_source_auto)) }
|
||||
SegmentedButton(
|
||||
selected = draft.wgCustomConf,
|
||||
onClick = {
|
||||
if (!draft.wgCustomConf) {
|
||||
HapticUtil.perform(context, HapticUtil.Pattern.TOGGLE_ON)
|
||||
onDraftChange(draft.copy(wgCustomConf = true))
|
||||
}
|
||||
},
|
||||
shape = SegmentedButtonDefaults.itemShape(index = 1, count = 2)
|
||||
) { Text(stringResource(R.string.setup_wg_source_custom)) }
|
||||
}
|
||||
if (draft.wgCustomConf) {
|
||||
Text(
|
||||
stringResource(R.string.setup_wg_custom_desc),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
} else if (wgDetectedPort != null) {
|
||||
WgStatusPanel(
|
||||
found = true,
|
||||
title = stringResource(R.string.setup_wg_found),
|
||||
desc = stringResource(R.string.setup_wg_found_desc, wgDetectedPort)
|
||||
)
|
||||
} else {
|
||||
WgStatusPanel(
|
||||
found = false,
|
||||
title = stringResource(R.string.setup_wg_missing),
|
||||
desc = stringResource(R.string.setup_wg_missing_desc)
|
||||
)
|
||||
PortField(
|
||||
value = draft.wgPort,
|
||||
onValueChange = { onDraftChange(draft.copy(wgPort = it)) },
|
||||
label = stringResource(R.string.setup_wg_port_label),
|
||||
onRoll = onRollWgPort,
|
||||
error = if (showErrors && !portOk(draft.wgPort)) {
|
||||
stringResource(R.string.setup_port_invalid)
|
||||
} else null
|
||||
)
|
||||
}
|
||||
}
|
||||
if (draft.wgCustomConf) {
|
||||
val hasConf = draft.wgConfText.isNotBlank()
|
||||
val protocol = remember(draft.wgConfText) { AccessProtocol.of(draft.wgConfText) }
|
||||
SettingsRowDivider()
|
||||
SettingsEntryRow(
|
||||
iconRes = R.drawable.cloud_download_24px,
|
||||
title = stringResource(R.string.load_wg_conf),
|
||||
subtitle = if (hasConf) {
|
||||
stringResource(
|
||||
if (protocol == AccessProtocol.AWG) R.string.protocol_awg
|
||||
else R.string.protocol_wg
|
||||
)
|
||||
} else null,
|
||||
trailingRes = if (hasConf) R.drawable.check_circle_24px else null,
|
||||
trailingTint = MaterialTheme.extendedColorScheme.success,
|
||||
onClick = onLoadWgFile
|
||||
SettingsFieldSlot {
|
||||
if (draft.ownWg) {
|
||||
val netInvalid = showErrors && !ServerBackend.isValidNet(draft.wgNet)
|
||||
OutlinedTextField(
|
||||
value = draft.wgNet,
|
||||
onValueChange = { v ->
|
||||
onDraftChange(draft.copy(wgNet = v.filter { it.isDigit() || it == '.' || it == '/' }))
|
||||
},
|
||||
label = { Text(stringResource(R.string.setup_wg_net_label)) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
isError = netInvalid,
|
||||
keyboardOptions = KeyboardOptions(
|
||||
keyboardType = KeyboardType.Uri,
|
||||
imeAction = ImeAction.Next
|
||||
),
|
||||
supportingText = {
|
||||
Text(stringResource(
|
||||
if (netInvalid) R.string.setup_wg_net_invalid else R.string.setup_wg_net_desc
|
||||
))
|
||||
}
|
||||
)
|
||||
PortField(
|
||||
value = draft.wgPort,
|
||||
onValueChange = { onDraftChange(draft.copy(wgPort = it)) },
|
||||
label = stringResource(R.string.setup_wg_port_label),
|
||||
error = when {
|
||||
portsClash -> stringResource(R.string.setup_ports_clash)
|
||||
showErrors && !portOk(draft.wgPort) -> stringResource(R.string.setup_port_invalid)
|
||||
else -> null
|
||||
}
|
||||
)
|
||||
} else {
|
||||
val connectInvalid = showErrors && !HostPort.isValid(draft.connect.trim())
|
||||
OutlinedTextField(
|
||||
value = draft.connect,
|
||||
onValueChange = { onDraftChange(draft.copy(connect = it.trim())) },
|
||||
label = { Text(stringResource(R.string.setup_connect_label)) },
|
||||
placeholder = { Text(stringResource(R.string.setup_connect_placeholder)) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
isError = connectInvalid,
|
||||
keyboardOptions = KeyboardOptions(
|
||||
keyboardType = KeyboardType.Uri,
|
||||
imeAction = ImeAction.Next
|
||||
),
|
||||
supportingText = {
|
||||
Text(stringResource(
|
||||
if (connectInvalid) R.string.setup_connect_invalid else R.string.setup_connect_desc
|
||||
))
|
||||
}
|
||||
)
|
||||
SettingsRowDivider()
|
||||
SettingsFieldSlot {
|
||||
OutlinedTextField(
|
||||
value = draft.wgConfText,
|
||||
onValueChange = { onDraftChange(draft.copy(wgConfText = it)) },
|
||||
label = { Text(stringResource(R.string.setup_wg_conf_label)) },
|
||||
placeholder = { Text(stringResource(R.string.setup_wg_conf_placeholder)) },
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.heightIn(min = 160.dp),
|
||||
isError = showErrors && draft.wgConfText.isBlank(),
|
||||
supportingText = if (showErrors && draft.wgConfText.isBlank()) {
|
||||
{ Text(stringResource(R.string.setup_field_required)) }
|
||||
} else null,
|
||||
maxLines = 10
|
||||
)
|
||||
BackendPortField(draft, showErrors, onDraftChange)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
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)
|
||||
Hint(stringResource(R.string.setup_backend_protocol_desc))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SectionLabel(stringResource(R.string.setup_turn_section))
|
||||
SectionLabel(stringResource(R.string.setup_server_section))
|
||||
SettingsCard {
|
||||
SettingsFieldSlot {
|
||||
ConnectedChoiceRow(
|
||||
options = listOf(
|
||||
ChoiceOption(ServerMethod.DOCKER, stringResource(R.string.setup_method_docker)),
|
||||
ChoiceOption(ServerMethod.SYSTEMD, stringResource(R.string.setup_method_systemd))
|
||||
),
|
||||
selected = draft.method,
|
||||
onSelect = { onDraftChange(draft.copy(method = it)) }
|
||||
)
|
||||
Hint(stringResource(
|
||||
if (draft.method == ServerMethod.DOCKER) R.string.setup_method_docker_desc
|
||||
else R.string.setup_method_systemd_desc
|
||||
))
|
||||
}
|
||||
SettingsRowDivider()
|
||||
SettingsFieldSlot {
|
||||
PortField(
|
||||
value = draft.listenPort,
|
||||
@@ -241,43 +188,34 @@ fun SetupConfigStep(
|
||||
label = stringResource(R.string.listen_port),
|
||||
supporting = stringResource(R.string.setup_listen_port_desc),
|
||||
onRoll = onRollListenPort,
|
||||
// Конфликт портов показываем сразу, формат - после тапа по submit.
|
||||
error = when {
|
||||
portsClash -> stringResource(R.string.setup_ports_clash)
|
||||
showErrors && !portOk(draft.listenPort) ->
|
||||
stringResource(R.string.setup_port_invalid)
|
||||
showErrors && !portOk(draft.listenPort) -> stringResource(R.string.setup_port_invalid)
|
||||
else -> null
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
SectionLabel(stringResource(R.string.obf_profile_title))
|
||||
SettingsCard {
|
||||
SettingsRowDivider()
|
||||
SettingsFieldSlot {
|
||||
ObfProfileDropdown(
|
||||
obfProfile = draft.obfProfile,
|
||||
onObfProfile = { value -> onDraftChange(draft.copy(obfProfile = value)) }
|
||||
)
|
||||
Text(
|
||||
stringResource(
|
||||
when (draft.obfProfile) {
|
||||
ObfProfile.NONE -> R.string.setup_obf_hint_none
|
||||
else -> R.string.setup_obf_hint_rtpopus
|
||||
}
|
||||
),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
OptionDropdown(
|
||||
label = stringResource(R.string.obf_profile_title),
|
||||
options = ObfProfile.VALUES.map { ChoiceOption(it, obfProfileLabel(it)) },
|
||||
selected = draft.obfProfile,
|
||||
onSelect = { onDraftChange(draft.copy(obfProfile = it)) }
|
||||
)
|
||||
Hint(stringResource(
|
||||
if (draft.obfProfile == ObfProfile.NONE) R.string.setup_obf_hint_none
|
||||
else R.string.setup_obf_hint_rtpopus
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
SectionLabel(stringResource(R.string.provider_vk_calls))
|
||||
SectionLabel(stringResource(R.string.provider_relay))
|
||||
SettingsCard {
|
||||
SettingsFieldSlot {
|
||||
OutlinedTextField(
|
||||
value = draft.vkLink,
|
||||
onValueChange = { onDraftChange(draft.copy(vkLink = it)) },
|
||||
value = draft.callLink,
|
||||
onValueChange = { onDraftChange(draft.copy(callLink = it)) },
|
||||
label = { Text(stringResource(R.string.call_link_label)) },
|
||||
placeholder = { Text(stringResource(R.string.call_link_placeholder)) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
@@ -292,36 +230,19 @@ fun SetupConfigStep(
|
||||
}
|
||||
}
|
||||
|
||||
private fun portOk(p: String): Boolean = p.toIntOrNull()?.let { it in 1..65535 } == true
|
||||
|
||||
@Composable
|
||||
private fun BackendPortField(
|
||||
draft: SetupConfigDraft,
|
||||
showErrors: Boolean,
|
||||
onDraftChange: (SetupConfigDraft) -> Unit
|
||||
) {
|
||||
val invalid = showErrors && !portOk(draft.backendPort)
|
||||
OutlinedTextField(
|
||||
value = draft.backendPort,
|
||||
onValueChange = { v -> onDraftChange(draft.copy(backendPort = v.filter { it.isDigit() })) },
|
||||
label = { Text(stringResource(R.string.setup_backend_port_label)) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
isError = invalid,
|
||||
keyboardOptions = KeyboardOptions(
|
||||
keyboardType = KeyboardType.Number,
|
||||
imeAction = ImeAction.Done
|
||||
),
|
||||
supportingText = {
|
||||
Text(stringResource(
|
||||
if (invalid) R.string.setup_port_invalid else R.string.setup_backend_port_desc
|
||||
))
|
||||
}
|
||||
private fun Hint(text: String) {
|
||||
Text(
|
||||
text,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
|
||||
private fun portOk(p: String): Boolean = p.toIntOrNull()?.let { it in 1..65535 } == true
|
||||
|
||||
@Composable
|
||||
private fun DuplicateHostPanel() {
|
||||
private fun InfoPanel(text: String) {
|
||||
Surface(
|
||||
shape = MaterialTheme.shapes.large,
|
||||
color = MaterialTheme.colorScheme.surfaceContainerLow,
|
||||
@@ -338,7 +259,7 @@ private fun DuplicateHostPanel() {
|
||||
modifier = Modifier.size(20.dp)
|
||||
)
|
||||
Text(
|
||||
stringResource(R.string.setup_duplicate_host),
|
||||
text,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
@@ -346,46 +267,12 @@ private fun DuplicateHostPanel() {
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun WgStatusPanel(found: Boolean, title: String, desc: String) {
|
||||
Surface(
|
||||
shape = MaterialTheme.shapes.medium,
|
||||
color = MaterialTheme.colorScheme.surfaceContainerHighest,
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.padding(Spacing.md),
|
||||
horizontalArrangement = Arrangement.spacedBy(Spacing.md)
|
||||
) {
|
||||
Icon(
|
||||
painterResource(if (found) R.drawable.check_circle_24px else R.drawable.cloud_download_24px),
|
||||
contentDescription = null,
|
||||
tint = if (found) MaterialTheme.extendedColorScheme.success
|
||||
else MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(20.dp)
|
||||
)
|
||||
Column(verticalArrangement = Arrangement.spacedBy(Spacing.xxs)) {
|
||||
Text(
|
||||
title,
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
color = MaterialTheme.colorScheme.onSurface
|
||||
)
|
||||
Text(
|
||||
desc,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PortField(
|
||||
value: String,
|
||||
onValueChange: (String) -> Unit,
|
||||
label: String,
|
||||
onRoll: () -> Unit,
|
||||
onRoll: (() -> Unit)? = null,
|
||||
supporting: String? = null,
|
||||
error: String? = null
|
||||
) {
|
||||
@@ -402,65 +289,18 @@ private fun PortField(
|
||||
imeAction = ImeAction.Done
|
||||
),
|
||||
supportingText = (error ?: supporting)?.let { { Text(it) } },
|
||||
trailingIcon = {
|
||||
IconButton(onClick = {
|
||||
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
|
||||
onRoll()
|
||||
}) {
|
||||
Icon(
|
||||
painterResource(R.drawable.refresh_24px),
|
||||
contentDescription = stringResource(R.string.setup_port_roll)
|
||||
)
|
||||
trailingIcon = onRoll?.let { roll ->
|
||||
{
|
||||
IconButton(shapes = IconButtonDefaults.shapes(), onClick = {
|
||||
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
|
||||
roll()
|
||||
}) {
|
||||
Icon(
|
||||
painterResource(R.drawable.refresh_24px),
|
||||
contentDescription = stringResource(R.string.setup_port_roll)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun obfProfileLabel(value: String): String = when (value) {
|
||||
ObfProfile.NONE -> stringResource(R.string.obf_none)
|
||||
ObfProfile.RTPOPUS -> stringResource(R.string.obf_rtpopus)
|
||||
ObfProfile.RTPOPUS2 -> stringResource(R.string.obf_rtpopus2)
|
||||
ObfProfile.RTPOPUS3 -> stringResource(R.string.obf_rtpopus3)
|
||||
else -> value
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ObfProfileDropdown(
|
||||
obfProfile: String,
|
||||
onObfProfile: (String) -> Unit,
|
||||
modifier: Modifier = Modifier
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
var expanded by remember { mutableStateOf(false) }
|
||||
val current = obfProfileLabel(obfProfile)
|
||||
|
||||
ExposedDropdownMenuBox(
|
||||
expanded = expanded,
|
||||
onExpandedChange = { expanded = !expanded },
|
||||
modifier = modifier
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value = current,
|
||||
onValueChange = {},
|
||||
readOnly = true,
|
||||
label = { Text(stringResource(R.string.obf_profile_title)) },
|
||||
trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) },
|
||||
modifier = Modifier
|
||||
.menuAnchor(ExposedDropdownMenuAnchorType.PrimaryNotEditable, true)
|
||||
.fillMaxWidth()
|
||||
)
|
||||
ExposedDropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) {
|
||||
ObfProfile.VALUES.forEach { value ->
|
||||
DropdownMenuItem(
|
||||
text = { Text(obfProfileLabel(value)) },
|
||||
onClick = {
|
||||
HapticUtil.perform(context, HapticUtil.Pattern.SELECTION)
|
||||
expanded = false
|
||||
onObfProfile(value)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,7 @@ import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.LoadingIndicator
|
||||
@@ -78,20 +79,20 @@ fun SetupInstallStep(
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
Button(
|
||||
shapes = ButtonDefaults.shapes(),
|
||||
onClick = {
|
||||
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
|
||||
onRetry()
|
||||
},
|
||||
modifier = Modifier.weight(1f),
|
||||
shape = MaterialTheme.shapes.large
|
||||
modifier = Modifier.weight(1f)
|
||||
) { Text(stringResource(R.string.setup_retry)) }
|
||||
TextButton(
|
||||
shapes = ButtonDefaults.shapes(),
|
||||
onClick = {
|
||||
HapticUtil.perform(context, HapticUtil.Pattern.SELECTION)
|
||||
onBackToConfig()
|
||||
},
|
||||
modifier = Modifier.weight(1f),
|
||||
shape = MaterialTheme.shapes.large
|
||||
modifier = Modifier.weight(1f)
|
||||
) { Text(stringResource(R.string.setup_back_to_config)) }
|
||||
}
|
||||
}
|
||||
@@ -254,8 +255,10 @@ private fun SetupDoneCard(summary: SetupSummary) {
|
||||
mono = true
|
||||
)
|
||||
SummaryRow(
|
||||
stringResource(R.string.setup_summary_mode),
|
||||
stringResource(if (summary.vpnMode) R.string.mode_vpn else R.string.mode_proxy)
|
||||
stringResource(R.string.setup_backend_section),
|
||||
stringResource(
|
||||
if (summary.ownWg) R.string.setup_backend_new else R.string.setup_backend_external
|
||||
)
|
||||
)
|
||||
SummaryRow(
|
||||
stringResource(R.string.setup_summary_obf),
|
||||
@@ -264,10 +267,10 @@ private fun SetupDoneCard(summary: SetupSummary) {
|
||||
)
|
||||
}
|
||||
|
||||
// VPN-режим: либо конфиг уже подставлен, либо нужен ручной импорт .conf.
|
||||
when {
|
||||
summary.wgConfImported -> SetupDoneHint(stringResource(R.string.setup_done_wg_imported))
|
||||
summary.usedExistingWg -> SetupDoneHint(stringResource(R.string.setup_done_wg_manual))
|
||||
// Чужой VPN: клиентский конфиг выдаёт его панель, не мы.
|
||||
!summary.ownWg -> SetupDoneHint(stringResource(R.string.setup_done_external))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -313,8 +316,6 @@ private fun SummaryRow(label: String, value: String, mono: Boolean = false) {
|
||||
}
|
||||
|
||||
private fun SetupTaskKind.labelRes(): Int = when (this) {
|
||||
SetupTaskKind.InstallCore -> R.string.setup_task_install
|
||||
SetupTaskKind.WireGuard -> R.string.setup_task_wireguard
|
||||
SetupTaskKind.StartServer -> R.string.setup_task_start
|
||||
SetupTaskKind.Apply -> R.string.setup_task_apply
|
||||
SetupTaskKind.Persist -> R.string.setup_task_persist
|
||||
}
|
||||
@@ -28,6 +28,8 @@ import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.ExtendedFloatingActionButton
|
||||
import androidx.compose.material3.IconButtonDefaults
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.LargeFlexibleTopAppBar
|
||||
@@ -120,7 +122,7 @@ fun SshSetupScreen(
|
||||
title = { Text(stringResource(R.string.connect_to_server)) },
|
||||
scrollBehavior = scrollBehavior,
|
||||
navigationIcon = {
|
||||
IconButton(onClick = {
|
||||
IconButton(shapes = IconButtonDefaults.shapes(), onClick = {
|
||||
HapticUtil.perform(context, HapticUtil.Pattern.SELECTION)
|
||||
onBack()
|
||||
}) {
|
||||
@@ -193,8 +195,11 @@ fun SshSetupScreen(
|
||||
onSudoPasswordChange = { sudoPassword = it },
|
||||
showSudoPassword = true
|
||||
)
|
||||
// Ошибка подключения - тональная карточка в тон ошибки.
|
||||
(sshState as? SshConnectionState.Error)?.let { InlineErrorCard(it.message) }
|
||||
(sshState as? SshConnectionState.Error)?.let {
|
||||
InlineErrorCard(
|
||||
if (it.hostKeyChanged) stringResource(R.string.error_ssh_host_key_changed) else it.message
|
||||
)
|
||||
}
|
||||
} else {
|
||||
ConnectionProgressCard(step = stringResource(R.string.ssh_connecting))
|
||||
}
|
||||
|
||||
@@ -2,7 +2,16 @@ package com.freeturn.app.viewmodel
|
||||
|
||||
import android.content.Context
|
||||
import com.freeturn.app.R
|
||||
import com.freeturn.app.domain.server.ServerCommandException
|
||||
import com.freeturn.app.domain.server.ServerErrorCode
|
||||
|
||||
/** Текст ошибки для UI: message исключения либо общий фоллбэк из ресурсов. */
|
||||
fun Throwable.uiError(context: Context): String =
|
||||
message?.takeIf { it.isNotBlank() } ?: context.getString(R.string.error_ssh_generic)
|
||||
/** Текст ошибки для UI: свой текст для известных кодов, иначе message исключения. */
|
||||
fun Throwable.uiError(context: Context): String {
|
||||
val res = when ((this as? ServerCommandException)?.code) {
|
||||
ServerErrorCode.PROTO_MISMATCH -> R.string.error_server_proto
|
||||
ServerErrorCode.HOST_KEY_CHANGED -> R.string.error_ssh_host_key_changed
|
||||
else -> null
|
||||
}
|
||||
if (res != null) return context.getString(res)
|
||||
return message?.takeIf { it.isNotBlank() } ?: context.getString(R.string.error_ssh_generic)
|
||||
}
|
||||
@@ -7,7 +7,6 @@ import com.freeturn.app.data.AppPreferences
|
||||
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.control.UninstallData
|
||||
import com.freeturn.app.data.server.Server
|
||||
import com.freeturn.app.data.server.ServerOpts
|
||||
import com.freeturn.app.data.server.ServersSnapshot
|
||||
@@ -25,7 +24,7 @@ import kotlinx.coroutines.launch
|
||||
sealed interface ServerCleanupState {
|
||||
data object Idle : ServerCleanupState
|
||||
data object Running : ServerCleanupState
|
||||
data class Done(val data: UninstallData) : ServerCleanupState
|
||||
data object Done : ServerCleanupState
|
||||
data class Error(val message: String) : ServerCleanupState
|
||||
}
|
||||
|
||||
@@ -96,8 +95,8 @@ class ServerConfigViewModel(
|
||||
_cleanupState.value = ServerCleanupState.Running
|
||||
// Перед удалением обновляем rootMode: сохранённое значение могло устареть.
|
||||
val mode = serverSetup.detectRootMode(cfg) ?: cfg.rootMode
|
||||
serverSetup.uninstall(cfg.copy(rootMode = mode), withWgPkg = true)
|
||||
.onSuccess { _cleanupState.value = ServerCleanupState.Done(it) }
|
||||
serverSetup.uninstall(cfg.copy(rootMode = mode))
|
||||
.onSuccess { _cleanupState.value = ServerCleanupState.Done }
|
||||
.onFailure { _cleanupState.value = ServerCleanupState.Error(it.uiError(appContext)) }
|
||||
}
|
||||
}
|
||||
@@ -114,7 +113,9 @@ class ServerConfigViewModel(
|
||||
}
|
||||
}
|
||||
|
||||
fun setActiveVkLink(link: String) = updateActiveClient { it.copy(vkLink = link.trim()) }
|
||||
fun setActiveCallLink(link: String) = updateActiveClient { it.copy(callLink = link.trim()) }
|
||||
|
||||
fun setActiveProvider(provider: String) = updateActiveClient { it.copy(provider = provider) }
|
||||
|
||||
fun setSplitTunnelMode(value: String) = updateActiveClient { it.copy(splitTunnelMode = value) }
|
||||
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
package com.freeturn.app.viewmodel.server
|
||||
|
||||
import com.freeturn.app.domain.ServerOperation
|
||||
|
||||
sealed interface ServerHubState {
|
||||
data object Offline : ServerHubState
|
||||
data object NotPaired : ServerHubState
|
||||
data object Connecting : ServerHubState
|
||||
data class Working(val action: String) : ServerHubState
|
||||
data class Working(val operation: ServerOperation) : ServerHubState
|
||||
data class Online(
|
||||
val running: Boolean,
|
||||
val installed: Boolean,
|
||||
|
||||
@@ -3,26 +3,32 @@ package com.freeturn.app.viewmodel.server
|
||||
import android.content.Context
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.freeturn.app.R
|
||||
import com.freeturn.app.data.AppPreferences
|
||||
import com.freeturn.app.data.config.ClientConfig
|
||||
import com.freeturn.app.data.config.HostPort
|
||||
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.ServerOpts
|
||||
import com.freeturn.app.data.config.SshConfig
|
||||
import com.freeturn.app.data.config.TunnelTransport
|
||||
import com.freeturn.app.data.control.RemoteConfig
|
||||
import com.freeturn.app.data.server.Server
|
||||
import com.freeturn.app.data.server.ServerBackend
|
||||
import com.freeturn.app.data.server.ServerMethod
|
||||
import com.freeturn.app.data.server.ServerOpts
|
||||
import com.freeturn.app.domain.proxy.ProxyOrchestrator
|
||||
import com.freeturn.app.domain.server.ApplyOptions
|
||||
import com.freeturn.app.domain.server.ApplyResult
|
||||
import com.freeturn.app.domain.server.ServerSetupRepository
|
||||
import com.freeturn.app.domain.server.ServerStartOptions
|
||||
import com.freeturn.app.viewmodel.HapticEvent
|
||||
import com.freeturn.app.viewmodel.Haptics
|
||||
import com.freeturn.app.viewmodel.uiError
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.NonCancellable
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
@@ -30,7 +36,7 @@ import kotlin.random.Random
|
||||
|
||||
enum class SetupStep { Ssh, Config, Install }
|
||||
|
||||
enum class SetupTaskKind { InstallCore, WireGuard, StartServer, Persist }
|
||||
enum class SetupTaskKind { Apply, Persist }
|
||||
|
||||
data class SetupSshDraft(
|
||||
val ip: String = "",
|
||||
@@ -64,16 +70,22 @@ data class SetupSshDraft(
|
||||
|
||||
data class SetupConfigDraft(
|
||||
val name: String = "",
|
||||
val vpnMode: Boolean = true,
|
||||
val obfProfile: String = ObfProfile.RTPOPUS,
|
||||
val listenPort: String = "",
|
||||
val wgPort: String = "",
|
||||
val wgCustomConf: Boolean = false,
|
||||
val wgConfText: String = "",
|
||||
val backendPort: String = "",
|
||||
val backend: String = ServerBackend.NEW,
|
||||
val wgNet: String = ServerBackend.DEFAULT_WG_NET,
|
||||
val wgPort: String = ServerBackend.DEFAULT_WG_PORT.toString(),
|
||||
/** Адрес своего VPN (host:port) для backend=external. */
|
||||
val connect: String = "",
|
||||
/** Мой VPN слушает TCP (Xray/sing-box) - проброс в tcp-режиме. */
|
||||
val backendTcp: Boolean = false,
|
||||
val vkLink: String = ""
|
||||
)
|
||||
val method: String = ServerMethod.DOCKER,
|
||||
val obfProfile: String = ObfProfile.RTPOPUS3,
|
||||
val listenPort: String = "",
|
||||
val callLink: String = ""
|
||||
) {
|
||||
val ownWg: Boolean get() = backend == ServerBackend.NEW
|
||||
|
||||
val proxyMode: String get() = if (!ownWg && backendTcp) ProxyMode.TCP else ProxyMode.UDP
|
||||
}
|
||||
|
||||
data class SetupInstallState(
|
||||
val tasks: List<SetupTaskKind>,
|
||||
@@ -86,10 +98,9 @@ data class SetupInstallState(
|
||||
data class SetupSummary(
|
||||
val serverName: String,
|
||||
val serverAddress: String,
|
||||
val vpnMode: Boolean,
|
||||
val ownWg: Boolean,
|
||||
val obfProfile: String,
|
||||
val wgConfImported: Boolean,
|
||||
val usedExistingWg: Boolean
|
||||
val wgConfImported: Boolean
|
||||
)
|
||||
|
||||
data class SetupUiState(
|
||||
@@ -97,43 +108,29 @@ data class SetupUiState(
|
||||
val ssh: SetupSshDraft = SetupSshDraft(),
|
||||
val checkingSsh: Boolean = false,
|
||||
val sshError: String? = null,
|
||||
val wgDetectedPort: Int? = null,
|
||||
/** На хосте уже есть установка: поля заполнены её конфигом. */
|
||||
val reinstall: Boolean = false,
|
||||
val duplicateHost: Boolean = false,
|
||||
val config: SetupConfigDraft = SetupConfigDraft(),
|
||||
val install: SetupInstallState? = null
|
||||
) {
|
||||
/**
|
||||
* Внешний порт совпал с UDP-портом бэкенда на том же хосте - оба бинда
|
||||
* конфликтуют. TCP-бэкенд (Xray/sing-box) с UDP-listen не пересекается.
|
||||
*/
|
||||
/** Свой WG и FreeTurn на одном UDP-порту хоста не уживутся. */
|
||||
val portsClash: Boolean
|
||||
get() {
|
||||
val listen = config.listenPort.toIntOrNull() ?: return false
|
||||
val backend = when {
|
||||
config.vpnMode && config.wgCustomConf -> config.backendPort.toIntOrNull()
|
||||
config.vpnMode && wgDetectedPort == null -> config.wgPort.toIntOrNull()
|
||||
config.vpnMode -> wgDetectedPort
|
||||
!config.backendTcp -> config.backendPort.toIntOrNull()
|
||||
else -> null
|
||||
}
|
||||
return backend != null && backend == listen
|
||||
}
|
||||
get() = config.ownWg && config.wgPort.isNotBlank() && config.wgPort == config.listenPort
|
||||
|
||||
val configValid: Boolean
|
||||
get() {
|
||||
fun ok(p: String) = p.toIntOrNull()?.let { it in 1..65535 } == true
|
||||
if (!ok(config.listenPort) || portsClash) return false
|
||||
return when {
|
||||
config.vpnMode && config.wgCustomConf ->
|
||||
config.wgConfText.isNotBlank() && ok(config.backendPort)
|
||||
config.vpnMode && wgDetectedPort == null -> ok(config.wgPort)
|
||||
!config.vpnMode -> ok(config.backendPort)
|
||||
else -> true
|
||||
return if (config.ownWg) {
|
||||
ok(config.wgPort) && ServerBackend.isValidNet(config.wgNet)
|
||||
} else {
|
||||
HostPort.isValid(config.connect.trim())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Сервер сохраняется только после успешного завершения удалённых шагов.
|
||||
// Сервер сохраняется только после успешного apply.
|
||||
class ServerSetupViewModel(
|
||||
private val repo: ServerSetupRepository,
|
||||
private val prefs: AppPreferences,
|
||||
@@ -145,23 +142,21 @@ class ServerSetupViewModel(
|
||||
private val appContext = context.applicationContext
|
||||
|
||||
private val _uiState = MutableStateFlow(
|
||||
SetupUiState(
|
||||
config = SetupConfigDraft(
|
||||
listenPort = randomListenPort(),
|
||||
wgPort = randomWgPort()
|
||||
)
|
||||
)
|
||||
SetupUiState(config = SetupConfigDraft(listenPort = randomListenPort()))
|
||||
)
|
||||
val uiState: StateFlow<SetupUiState> = _uiState.asStateFlow()
|
||||
|
||||
// Obf-ключ мастера: генерится один раз и уходит и в start, и в снимок сервера.
|
||||
private val obfKey: String = ObfProfile.generateKey()
|
||||
private var fingerprint: String = ""
|
||||
private var serverName: String = ""
|
||||
private var installJob: Job? = null
|
||||
// Apply прошёл, а профиль не сохранился: повтор не должен гонять apply заново.
|
||||
private var applied: ApplyResult? = null
|
||||
|
||||
fun setSsh(draft: SetupSshDraft) =
|
||||
_uiState.update { it.copy(ssh = draft, sshError = null) }
|
||||
_uiState.update {
|
||||
// Другой хост - его конфиг подтянет следующий probe.
|
||||
it.copy(ssh = draft, sshError = null, reinstall = it.reinstall && draft.ip == it.ssh.ip)
|
||||
}
|
||||
|
||||
fun setConfig(draft: SetupConfigDraft) =
|
||||
_uiState.update { it.copy(config = draft) }
|
||||
@@ -169,15 +164,13 @@ class ServerSetupViewModel(
|
||||
fun rollListenPort() =
|
||||
_uiState.update { it.copy(config = it.config.copy(listenPort = randomListenPort())) }
|
||||
|
||||
fun rollWgPort() =
|
||||
_uiState.update { it.copy(config = it.config.copy(wgPort = randomWgPort())) }
|
||||
|
||||
fun backToSsh() = _uiState.update { it.copy(step = SetupStep.Ssh) }
|
||||
|
||||
fun backToConfig() {
|
||||
// Гонка с диалогом прерывания: установка успела завершиться - не сбрасываем.
|
||||
if (_uiState.value.install?.done == true) return
|
||||
installJob?.cancel()
|
||||
applied = null
|
||||
_uiState.update { it.copy(step = SetupStep.Config, install = null) }
|
||||
}
|
||||
|
||||
@@ -198,18 +191,15 @@ class ServerSetupViewModel(
|
||||
val duplicate = prefs.serversSnapshot.first().list
|
||||
.any { it.ssh.ip.isNotBlank() && it.ssh.ip.equals(ip, ignoreCase = true) }
|
||||
haptics.perform(HapticEvent.SUCCESS)
|
||||
_uiState.update {
|
||||
it.copy(
|
||||
_uiState.update { st ->
|
||||
// Повторный probe не перетирает ручной ввод.
|
||||
val prefill = probe.config.takeUnless { st.reinstall }
|
||||
st.copy(
|
||||
checkingSsh = false,
|
||||
step = SetupStep.Config,
|
||||
wgDetectedPort = probe.wgPort,
|
||||
reinstall = st.reinstall || probe.config != null,
|
||||
duplicateHost = duplicate,
|
||||
// Повторный probe не перетирает ручной ввод.
|
||||
config = it.config.copy(
|
||||
backendPort = it.config.backendPort.ifBlank {
|
||||
(probe.wgPort ?: DEFAULT_WG_PORT).toString()
|
||||
}
|
||||
)
|
||||
config = prefill?.let { st.config.from(it) } ?: st.config
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -226,20 +216,20 @@ class ServerSetupViewModel(
|
||||
val s = _uiState.value
|
||||
if (s.step != SetupStep.Config || !s.configValid) return
|
||||
serverName = s.config.name.trim().ifBlank { fallbackName }
|
||||
val tasks = buildList {
|
||||
add(SetupTaskKind.InstallCore)
|
||||
if (s.config.vpnMode && !s.config.wgCustomConf) add(SetupTaskKind.WireGuard)
|
||||
add(SetupTaskKind.StartServer)
|
||||
add(SetupTaskKind.Persist)
|
||||
applied = null
|
||||
_uiState.update {
|
||||
it.copy(
|
||||
step = SetupStep.Install,
|
||||
install = SetupInstallState(listOf(SetupTaskKind.Apply, SetupTaskKind.Persist))
|
||||
)
|
||||
}
|
||||
_uiState.update { it.copy(step = SetupStep.Install, install = SetupInstallState(tasks)) }
|
||||
runInstall()
|
||||
}
|
||||
|
||||
fun retryInstall() {
|
||||
val st = _uiState.value.install ?: return
|
||||
if (st.error == null) return
|
||||
_uiState.update { it.copy(install = st.copy(current = 0, error = null)) }
|
||||
_uiState.update { it.copy(install = st.copy(error = null)) }
|
||||
runInstall()
|
||||
}
|
||||
|
||||
@@ -253,11 +243,9 @@ class ServerSetupViewModel(
|
||||
}
|
||||
}
|
||||
|
||||
private fun fail(message: String?) {
|
||||
private fun fail(message: String) {
|
||||
haptics.perform(HapticEvent.ERROR)
|
||||
_uiState.update { s ->
|
||||
s.copy(install = s.install?.copy(error = message ?: "unknown error"))
|
||||
}
|
||||
_uiState.update { s -> s.copy(install = s.install?.copy(error = message)) }
|
||||
}
|
||||
|
||||
private fun runInstall() {
|
||||
@@ -267,56 +255,18 @@ class ServerSetupViewModel(
|
||||
val cfg = s.ssh.toSshConfig().copy(hostFingerprint = fingerprint)
|
||||
val c = s.config
|
||||
|
||||
repo.install(cfg).onFailure { fail(it.message); return@launch }
|
||||
advance()
|
||||
|
||||
var wgClientConf: String? = null
|
||||
var backendPort = when {
|
||||
c.vpnMode && !c.wgCustomConf ->
|
||||
s.wgDetectedPort ?: c.wgPort.toIntOrNull() ?: DEFAULT_WG_PORT
|
||||
else -> c.backendPort.toIntOrNull() ?: DEFAULT_WG_PORT
|
||||
}
|
||||
if (c.vpnMode && c.wgCustomConf) {
|
||||
wgClientConf = c.wgConfText.trim()
|
||||
} else if (c.vpnMode) {
|
||||
// Endpoint клиентского конфига = локальный прокси устройства; рантайм
|
||||
// туннеля всё равно подменяет его при подъёме. wg-setup идемпотентно
|
||||
// поднимает НАШ ft-wg0 (создаёт или докручивает) и возвращает порт+conf.
|
||||
val wg = repo.wgSetup(
|
||||
cfg,
|
||||
port = backendPort,
|
||||
endpoint = ClientConfig.DEFAULT_LOCAL_PORT
|
||||
).getOrElse { fail(it.message); return@launch }
|
||||
wgClientConf = wg.clientConf
|
||||
backendPort = wg.port
|
||||
advance()
|
||||
}
|
||||
|
||||
val obfOn = c.obfProfile != ObfProfile.NONE
|
||||
repo.start(
|
||||
cfg,
|
||||
ServerStartOptions(
|
||||
listen = "0.0.0.0:${c.listenPort}",
|
||||
connect = "127.0.0.1:$backendPort",
|
||||
proxyMode = if (!c.vpnMode && c.backendTcp) ProxyMode.TCP else ProxyMode.UDP,
|
||||
obfProfile = c.obfProfile,
|
||||
obfKey = if (obfOn) obfKey else "",
|
||||
// Авторизация по allowlist с первого запуска: владелец сидится
|
||||
// в clients.json, сервер стартует с -clients-file.
|
||||
clientId = prefs.ownClientId()
|
||||
)
|
||||
).onFailure { fail(it.message); return@launch }
|
||||
advance()
|
||||
val result = applied ?: repo.apply(cfg, c.toApplyOptions())
|
||||
.getOrElse { fail(it.uiError(appContext)); return@launch }
|
||||
.also {
|
||||
applied = it
|
||||
advance()
|
||||
}
|
||||
|
||||
// NonCancellable: сервер уже настроен и запущен - уход с экрана не должен
|
||||
// оставить его без записи в приложении.
|
||||
val saved = withContext(NonCancellable) {
|
||||
val server = buildServer(cfg, c, backendPort, wgClientConf)
|
||||
prefs.addServer(server, activate = true)?.also { orchestrator.restartProxyIfRunning() }
|
||||
}
|
||||
|
||||
if (saved == null) {
|
||||
fail("Сервер запущен, но профиль не сохранён - список серверов повреждён")
|
||||
val saved = withContext(NonCancellable) { persist(cfg, c, result) }
|
||||
if (!saved) {
|
||||
fail(appContext.getString(R.string.setup_persist_failed))
|
||||
return@launch
|
||||
}
|
||||
advance()
|
||||
@@ -329,10 +279,9 @@ class ServerSetupViewModel(
|
||||
summary = SetupSummary(
|
||||
serverName = serverName,
|
||||
serverAddress = "${cfg.ip}:${c.listenPort}",
|
||||
vpnMode = c.vpnMode,
|
||||
ownWg = c.ownWg,
|
||||
obfProfile = c.obfProfile,
|
||||
wgConfImported = !c.wgCustomConf && wgClientConf != null,
|
||||
usedExistingWg = c.vpnMode && !c.wgCustomConf && s.wgDetectedPort != null
|
||||
wgConfImported = result.ownerConf.isNotBlank()
|
||||
)
|
||||
)
|
||||
)
|
||||
@@ -340,35 +289,61 @@ class ServerSetupViewModel(
|
||||
}
|
||||
}
|
||||
|
||||
private fun buildServer(
|
||||
cfg: SshConfig,
|
||||
c: SetupConfigDraft,
|
||||
backendPort: Int,
|
||||
wgClientConf: String?
|
||||
): Server = Server(
|
||||
// Провайдер (relay или direct) не выбирается тут: сервер один, переключатель - в листе серверов.
|
||||
private suspend fun persist(cfg: SshConfig, c: SetupConfigDraft, r: ApplyResult): Boolean {
|
||||
prefs.addServer(buildServer(cfg, c, r), activate = true) ?: return false
|
||||
orchestrator.restartProxyIfRunning()
|
||||
return true
|
||||
}
|
||||
|
||||
private fun buildServer(cfg: SshConfig, c: SetupConfigDraft, r: ApplyResult): Server = Server(
|
||||
name = serverName,
|
||||
ssh = cfg,
|
||||
client = ClientConfig(
|
||||
serverAddress = "${cfg.ip}:${c.listenPort}",
|
||||
vkLink = c.vkLink.trim(),
|
||||
tunnelTransport = if (c.vpnMode && !wgClientConf.isNullOrBlank())
|
||||
TunnelTransport.WIREGUARD else TunnelTransport.NONE,
|
||||
wireGuardConfig = wgClientConf.orEmpty()
|
||||
callLink = c.callLink.trim(),
|
||||
tunnelTransport = if (r.ownerConf.isNotBlank()) TunnelTransport.WIREGUARD
|
||||
else TunnelTransport.NONE,
|
||||
wireGuardConfig = r.ownerConf,
|
||||
clientId = r.ownerClientId
|
||||
),
|
||||
proxyListen = "0.0.0.0:${c.listenPort}",
|
||||
proxyConnect = "127.0.0.1:$backendPort",
|
||||
proxyConnect = if (c.ownWg) "127.0.0.1:${c.wgPort}" else c.connect.trim(),
|
||||
opts = ServerOpts(
|
||||
obfProfile = c.obfProfile,
|
||||
obfKey = if (c.obfProfile != ObfProfile.NONE) obfKey else "",
|
||||
proxyMode = if (!c.vpnMode && c.backendTcp) ProxyMode.TCP else ProxyMode.UDP
|
||||
obfKey = r.obfKey,
|
||||
proxyMode = c.proxyMode,
|
||||
method = c.method,
|
||||
backend = c.backend,
|
||||
wgPort = c.wgPort.toIntOrNull() ?: ServerBackend.DEFAULT_WG_PORT,
|
||||
wgNet = c.wgNet.trim()
|
||||
)
|
||||
)
|
||||
|
||||
private fun randomListenPort(): String = Random.nextInt(56000, 57000).toString()
|
||||
|
||||
private fun randomWgPort(): String = Random.nextInt(51000, 52000).toString()
|
||||
|
||||
companion object {
|
||||
private const val DEFAULT_WG_PORT = 51820
|
||||
}
|
||||
}
|
||||
|
||||
// Ключ не шлём: на чистом хосте его сгенерирует сервер, на переустановке оставит свой -
|
||||
// выданные гостям ссылки не протухнут.
|
||||
private fun SetupConfigDraft.toApplyOptions() = ApplyOptions(
|
||||
method = method,
|
||||
backend = backend,
|
||||
listenPort = listenPort.toInt(),
|
||||
connect = connect.trim(),
|
||||
wgPort = wgPort.toIntOrNull() ?: ServerBackend.DEFAULT_WG_PORT,
|
||||
wgNet = wgNet.trim(),
|
||||
proxyMode = proxyMode,
|
||||
obfProfile = obfProfile
|
||||
)
|
||||
|
||||
/** Черновик по конфигу прошлой установки: подсеть WG менять нельзя, остальное - как было. */
|
||||
private fun SetupConfigDraft.from(r: RemoteConfig) = copy(
|
||||
backend = r.backend.takeIf { it in ServerBackend.VALUES } ?: backend,
|
||||
wgNet = r.wgNet.ifBlank { wgNet },
|
||||
wgPort = r.wgPort.takeIf { it > 0 }?.toString() ?: wgPort,
|
||||
connect = r.connect.ifBlank { connect },
|
||||
backendTcp = r.mode == ProxyMode.TCP,
|
||||
method = r.method.takeIf { it in ServerMethod.VALUES } ?: method,
|
||||
obfProfile = r.obfProfile.takeIf { it in ObfProfile.VALUES } ?: obfProfile,
|
||||
listenPort = r.listenPort.takeIf { it > 0 }?.toString() ?: listenPort
|
||||
)
|
||||
@@ -3,13 +3,13 @@ package com.freeturn.app.viewmodel.server
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.freeturn.app.data.AppPreferences
|
||||
import com.freeturn.app.data.config.HostPort
|
||||
import com.freeturn.app.data.config.ObfProfile
|
||||
import com.freeturn.app.data.server.ServerOpts
|
||||
import com.freeturn.app.data.config.SshConfig
|
||||
import com.freeturn.app.domain.proxy.ProxyOrchestrator
|
||||
import com.freeturn.app.domain.ServerState
|
||||
import com.freeturn.app.domain.SshConnectionState
|
||||
import com.freeturn.app.domain.server.applyOptions
|
||||
import com.freeturn.app.domain.server.withApplied
|
||||
import com.freeturn.app.domain.ssh.SshRepository
|
||||
import com.freeturn.app.viewmodel.HapticEvent
|
||||
import com.freeturn.app.viewmodel.Haptics
|
||||
@@ -45,7 +45,7 @@ class ServerViewModel(
|
||||
when {
|
||||
ssh is SshConnectionState.Error -> ServerHubState.Failed
|
||||
server is ServerState.Error -> ServerHubState.Failed
|
||||
server is ServerState.Working -> ServerHubState.Working(server.action)
|
||||
server is ServerState.Working -> ServerHubState.Working(server.operation)
|
||||
ssh is SshConnectionState.Connected && server is ServerState.Known ->
|
||||
ServerHubState.Online(
|
||||
running = server.running,
|
||||
@@ -90,39 +90,20 @@ class ServerViewModel(
|
||||
}
|
||||
}
|
||||
|
||||
fun installServer() {
|
||||
viewModelScope.launch {
|
||||
val outcome = sshRepository.installServer()
|
||||
if (outcome is SshRepository.InstallResult.Success) {
|
||||
if (outcome.stage == "downloaded" && prefs.serverOptsFlow.first().obfKey.isBlank()) {
|
||||
prefs.updateActiveServer { it.copy(opts = it.opts.copy(obfKey = ObfProfile.generateKey())) }
|
||||
}
|
||||
if (outcome.needsRestart) {
|
||||
startServer()
|
||||
orchestrator.restartProxyIfRunning()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Установка и запуск - один apply: правки, сделанные пока сервер стоял, иначе
|
||||
// остались бы только в профиле, а сервер поднялся бы со старым install.conf.
|
||||
fun installServer() = applyActive()
|
||||
|
||||
fun startServer() {
|
||||
fun startServer() = applyActive()
|
||||
|
||||
fun updateServer() = applyActive(update = true)
|
||||
|
||||
private fun applyActive(update: Boolean = false) {
|
||||
viewModelScope.launch {
|
||||
val l = prefs.proxyListenFlow.first()
|
||||
val c = prefs.proxyConnectFlow.first()
|
||||
if (!HostPort.isValid(l) || !HostPort.isValid(c)) {
|
||||
sshRepository.updateServerState(ServerState.Error("Неверный формат адреса (ожидается host:port)"))
|
||||
return@launch
|
||||
}
|
||||
val opts = prefs.serverOptsFlow.first()
|
||||
sshRepository.startServer(
|
||||
listen = l, connect = c,
|
||||
proxyMode = opts.proxyMode,
|
||||
kcp = opts.kcp,
|
||||
obfProfile = if (opts.obfEnabled) opts.obfProfile else "none",
|
||||
obfKey = if (opts.obfEnabled) opts.obfKey else "",
|
||||
obfTimingMs = opts.obfTimingMs,
|
||||
clientId = prefs.ownClientId()
|
||||
)
|
||||
val server = prefs.serversSnapshot.first().active ?: return@launch
|
||||
val applied = sshRepository.applyServer(server.applyOptions(), update) ?: return@launch
|
||||
orchestrator.saveApplied(server.withApplied(applied))
|
||||
orchestrator.restartProxyIfRunning()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
<string name="share_tab_users">Пользователи</string>
|
||||
<string name="share_connection_desc">Предоставление доступа к VPN без прав управления сервером</string>
|
||||
<string name="share_user_name_label">Имя пользователя</string>
|
||||
<string name="share_user_name_hint">Латиница, цифры, . _ -</string>
|
||||
<string name="share_client_id_label">Client ID</string>
|
||||
<string name="share_client_id_hint">Нужен серверу, чтобы принять подключение (32 hex-символа)</string>
|
||||
<string name="share_client_id_invalid">Неверный формат: 32 hex-символа (0-9, a-f)</string>
|
||||
@@ -57,17 +58,19 @@
|
||||
<string name="share_revoke_title">Отозвать доступ?</string>
|
||||
<string name="share_revoke_desc">Пользователь \"%1$s\" будет удалён с сервера, его подключение перестанет работать. Действие необратимо.</string>
|
||||
<string name="share_revoke_confirm">Отозвать</string>
|
||||
<string name="share_include_vk_link">Вложить ссылку на звонок</string>
|
||||
<string name="share_include_vk_link_desc">Получателю не нужен свой аккаунт</string>
|
||||
<string name="share_include_call_link">Вложить ссылку на звонок</string>
|
||||
<string name="share_include_call_link_desc">Получателю не нужен свой аккаунт</string>
|
||||
<string name="share_no_address">У сервера не указан адрес - добавьте его в настройках сервера</string>
|
||||
<string name="error_ssh_generic">Ошибка SSH</string>
|
||||
<string name="error_server_proto">Скрипт управления сервером не той версии - обновите приложение.</string>
|
||||
<string name="error_ssh_host_key_changed">Ключ SSH-сервера не совпадает с сохранённым - возможна подмена сервера. Подключение прервано, подробности в журнале SSH.</string>
|
||||
|
||||
<!-- Импорт по ссылке (ImportSheet) -->
|
||||
<string name="import_title">Импорт подключения</string>
|
||||
<string name="import_default_name">Импортированный сервер</string>
|
||||
<string name="import_vk_link_label">Ссылка на звонок VK</string>
|
||||
<string name="import_vk_link_helper">Укажите ссылку на звонок VK для установки соединения</string>
|
||||
<string name="import_vk_link_from_owner">Ссылка пришла вместе с доступом - можно заменить своей</string>
|
||||
<string name="import_call_link_label">Ссылка на звонок</string>
|
||||
<string name="import_call_link_helper">Укажите ссылку на звонок для установки соединения</string>
|
||||
<string name="import_call_link_from_owner">Ссылка пришла вместе с доступом - можно заменить своей</string>
|
||||
<string name="import_duplicate_address">Сервер с данным адресом уже существует</string>
|
||||
<string name="import_duplicate_conf">Конфигурация уже импортирована</string>
|
||||
<string name="import_confirm">Импортировать</string>
|
||||
@@ -116,41 +119,45 @@
|
||||
<string name="setup_go_home">На главную</string>
|
||||
<string name="setup_checking_ssh">Проверка подключения…</string>
|
||||
<string name="setup_checking_ssh_desc">Проверка окружения сервера</string>
|
||||
<string name="setup_mode_section">Режим работы</string>
|
||||
<string name="setup_mode_vpn_desc">Поднимем WireGuard на сервере - весь трафик устройства пойдёт через туннель.</string>
|
||||
<string name="setup_mode_proxy_desc">Прокси перенаправляет трафик на ваш бэкенд на сервере: WireGuard или Xray.</string>
|
||||
<string name="setup_wg_found">WireGuard найден</string>
|
||||
<string name="setup_wg_found_desc">Порт %1$d станет бэкендом. Для этого устройства добавится отдельный пир - конфиг подставится сам.</string>
|
||||
<string name="setup_wg_missing">WireGuard не найден</string>
|
||||
<string name="setup_wg_missing_desc">Установим и настроим автоматически - клиентский конфиг подставится сам.</string>
|
||||
<string name="setup_wg_port_label">Порт WireGuard</string>
|
||||
<string name="setup_wg_source_auto">Автоматически</string>
|
||||
<string name="setup_wg_source_custom">Свой конфиг</string>
|
||||
<string name="setup_wg_custom_desc">WireGuard на сервере не настраивается - укажите порт и вставьте свой клиентский .conf.</string>
|
||||
<string name="setup_wg_conf_label">Клиентский конфиг (.conf)</string>
|
||||
<string name="setup_wg_conf_placeholder">[Interface]\n…</string>
|
||||
<string name="setup_port_roll">Сгенерировать порт</string>
|
||||
<string name="setup_backend_port_label">Порт бэкенда</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_label">Протокол VPN</string>
|
||||
<string name="setup_backend_protocol_desc">UDP - WireGuard/AmneziaWG, TCP - Xray</string>
|
||||
<string name="setup_turn_section">TURN-прокси</string>
|
||||
<string name="setup_listen_port_desc">Внешний UDP-порт сервера, случайный из диапазона 56000–56999</string>
|
||||
<string name="setup_obf_hint_rtpopus">Трафик маскируется под голосовой звонок. Ключ сгенерируется и подставится автоматически.</string>
|
||||
<string name="setup_obf_hint_none">Без маскировки трафика. Можно включить позже в настройках сервера.</string>
|
||||
<string name="setup_call_link_hint">Можно заполнить позже в настройках подключения</string>
|
||||
<string name="setup_task_install">Установка ядра</string>
|
||||
<string name="setup_task_wireguard">Настройка WireGuard</string>
|
||||
<string name="setup_task_start">Запуск сервера</string>
|
||||
<string name="setup_task_persist">Сохранение конфигурации</string>
|
||||
<string name="setup_task_apply">Установка и запуск</string>
|
||||
<string name="setup_persist_failed">Сервер настроен, но профиль не сохранён - список серверов повреждён</string>
|
||||
<string name="setup_reinstall">На сервере уже стоит FreeTurn - поля заполнены его настройками.</string>
|
||||
<string name="setup_backend_section">Куда идёт трафик</string>
|
||||
<string name="setup_backend_label">VPN на сервере</string>
|
||||
<string name="setup_backend_new">Новый WireGuard</string>
|
||||
<string name="setup_backend_external">Готовый VPN</string>
|
||||
<string name="setup_backend_new_desc">Установщик поставит на сервер WireGuard (интерфейс ft-wg0) и сам выпустит конфиги - для вас и для тех, с кем поделитесь.</string>
|
||||
<string name="setup_backend_external_desc">На сервере уже работает ваш VPN (Amnezia, wg-easy, 3x-ui). FreeTurn только передаёт в него трафик и сам VPN не трогает - клиентские конфиги берите в его панели.</string>
|
||||
<string name="setup_wg_net_label">Подсеть WireGuard</string>
|
||||
<string name="setup_wg_net_desc">Адреса клиентов, у сервера - .1. Не должна пересекаться с сетями сервера.</string>
|
||||
<string name="setup_wg_net_invalid">Сетевой адрес с префиксом /16-/29, например 10.13.13.0/24</string>
|
||||
<string name="setup_connect_label">Адрес VPN</string>
|
||||
<string name="setup_connect_placeholder">127.0.0.1:51820</string>
|
||||
<string name="setup_connect_desc">host:port вашего VPN, куда FreeTurn пересылает трафик</string>
|
||||
<string name="setup_connect_invalid">Нужен формат host:port</string>
|
||||
<string name="setup_server_section">Сервер</string>
|
||||
<string name="setup_method_docker">Docker</string>
|
||||
<string name="setup_method_systemd">systemd</string>
|
||||
<string name="setup_method_docker_desc">FreeTurn в контейнере. Docker поставится сам - первая установка может занять несколько минут.</string>
|
||||
<string name="setup_method_systemd_desc">FreeTurn - системная служба, без Docker.</string>
|
||||
<string name="setup_done_external">Клиентский конфиг VPN возьмите в своей панели и импортируйте в \"Режиме подключения\".</string>
|
||||
<string name="setup_retry">Повторить</string>
|
||||
<string name="setup_back_to_config">К настройкам</string>
|
||||
<string name="setup_done_hero">Сервер настроен и запущен</string>
|
||||
<string name="setup_done_active_hint">Сервер добавлен и сделан активным - запускайте с главного экрана.</string>
|
||||
<string name="setup_done_wg_imported">WireGuard-конфиг получен с сервера и подключён.</string>
|
||||
<string name="setup_done_wg_manual">Используется существующий WireGuard - импортируйте свой клиентский .conf в \"Режиме подключения\".</string>
|
||||
<string name="setup_summary_address">Адрес</string>
|
||||
<string name="setup_summary_mode">Режим</string>
|
||||
<string name="setup_summary_obf">Обфускация</string>
|
||||
<string name="setup_obf_off">Выключена</string>
|
||||
<string name="setup_abort_title">Прервать установку?</string>
|
||||
@@ -159,7 +166,7 @@
|
||||
<string name="setup_abort_stay">Остаться</string>
|
||||
<string name="setup_field_required">Обязательное поле</string>
|
||||
<string name="setup_port_invalid">Порт от 1 до 65535</string>
|
||||
<string name="setup_ports_clash">Совпадает с портом бэкенда</string>
|
||||
<string name="setup_ports_clash">Совпадает с портом WireGuard</string>
|
||||
<string name="setup_duplicate_host">Сервер с этим адресом уже есть в списке - добавится ещё одна запись.</string>
|
||||
<string name="setup_name_hint">Если не заполнять, назовем \"Новый сервер\".</string>
|
||||
<string name="setup_summary_name">Название</string>
|
||||
@@ -194,7 +201,6 @@
|
||||
<string name="call_link_label">Ссылка на звонок</string>
|
||||
<string name="call_link_placeholder">https://site.ru/call/…</string>
|
||||
<string name="call_link_support">Звонки -> Создать -> Скопировать ссылку (не нажимайте \"Завершить\")</string>
|
||||
<string name="call_link_edit">Изменить ссылку на звонок</string>
|
||||
<string name="call_link_empty_error">Введите ссылку на звонок</string>
|
||||
<string name="paste">Вставить</string>
|
||||
<string name="local_listen_address">Локальный адрес прослушивания</string>
|
||||
@@ -205,7 +211,7 @@
|
||||
<string name="client_section_advanced">Дополнительно</string>
|
||||
<string name="threads_format">Потоки: %1$d</string>
|
||||
<string name="threads_recommendation">Рекомендуется 8–12</string>
|
||||
<string name="streams_per_cred_recommendation">Сколько TURN-потоков обслуживает один VK-аккаунт</string>
|
||||
<string name="streams_per_cred_recommendation">Сколько TURN-потоков обслуживает один аккаунт</string>
|
||||
<string name="streams_per_cred_format">Потоков на аккаунт: %1$d</string>
|
||||
|
||||
<string name="tcp_forward_mode">Режим</string>
|
||||
@@ -218,7 +224,9 @@
|
||||
<string name="obf_rtpopus">rtpopus</string>
|
||||
<string name="obf_rtpopus2">rtpopus2</string>
|
||||
<string name="obf_rtpopus3">rtpopus3</string>
|
||||
<string name="provider_vk">VK Calls</string>
|
||||
<string name="provider_relay">Relay</string>
|
||||
<string name="provider_direct">Direct</string>
|
||||
<string name="provider_locked">Остановите подключение, чтобы сменить способ или ссылку</string>
|
||||
<string name="obf_key_empty_hint">Пусто - ключ сгенерируется при применении</string>
|
||||
<string name="obf_key_invalid_hint">Неверный формат - нужны 64 hex-символа</string>
|
||||
<string name="server_sync_section">Синхронные настройки сервера</string>
|
||||
@@ -253,12 +261,6 @@
|
||||
<string name="listen_port">Порт прослушивания</string>
|
||||
<string name="listen_port_placeholder">56000</string>
|
||||
<string name="listen_port_desc">Порт, на котором сервер принимает подключения от клиентов</string>
|
||||
<string name="listen_ip">IP прослушивания</string>
|
||||
<string name="listen_ip_placeholder">0.0.0.0</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_placeholder">127.0.0.1:40537</string>
|
||||
<string name="turn_client_desc">Локальный WireGuard/Xray-бэкенд на стороне сервера</string>
|
||||
<string name="server_install">Установить</string>
|
||||
<string name="server_update">Обновить</string>
|
||||
<string name="server_obf_key_label">Obf-ключ (64 hex)</string>
|
||||
@@ -306,7 +308,12 @@
|
||||
<string name="update_ready_desc_short">Готово к установке</string>
|
||||
<string name="update_install">Установить</string>
|
||||
<string name="update_no_update">Установлена последняя версия</string>
|
||||
<string name="update_error">Ошибка: %1$s</string>
|
||||
<string name="update_error_release">Не удалось получить информацию о релизе</string>
|
||||
<string name="update_error_no_apk">В релизе нет APK</string>
|
||||
<string name="update_error_network">Нет соединения с сервером</string>
|
||||
<string name="update_error_download">Не удалось скачать обновление</string>
|
||||
<string name="update_error_signature">Подпись обновления не совпадает - установка отменена</string>
|
||||
<string name="update_error_file">Файл обновления не найден</string>
|
||||
|
||||
<string name="debug_mode">Подробное логирование</string>
|
||||
<string name="debug_mode_desc">Детальный вывод ядра</string>
|
||||
@@ -334,9 +341,15 @@
|
||||
<string name="notif_proxy_wireguard_error">Ошибка WireGuard</string>
|
||||
<string name="notif_proxy_vpn_permission">Нужно разрешение VPN - откройте приложение</string>
|
||||
<string name="notif_proxy_vpn_denied">Разрешение VPN не выдано - прокси не запущен</string>
|
||||
<string name="proxy_error_service">Не удалось запустить сервис: %1$s</string>
|
||||
<string name="proxy_error_not_configured">Не заполнены настройки подключения</string>
|
||||
<string name="proxy_error_config_rejected">Ядро отклонило конфигурацию: %1$s</string>
|
||||
<string name="proxy_error_core_start">Ядро не запустилось: %1$s</string>
|
||||
<string name="proxy_error_tunnel_config">Не удалось разобрать конфиг WireGuard: %1$s</string>
|
||||
<string name="proxy_error_tunnel_iface">Не удалось поднять VPN-интерфейс: %1$s</string>
|
||||
|
||||
<!-- CaptchaWebViewDialog -->
|
||||
<string name="captcha_title">Проверка VK</string>
|
||||
<string name="captcha_title">Проверка на робота</string>
|
||||
<string name="captcha_subtitle">Пройдите проверку для продолжения</string>
|
||||
<string name="captcha_close">Закрыть</string>
|
||||
<string name="captcha_browser_hint">Капча открыта во внешнем браузере. После прохождения вернитесь в приложение.</string>
|
||||
@@ -352,6 +365,7 @@
|
||||
<!-- Servers -->
|
||||
<string name="server_delete">Удалить</string>
|
||||
<string name="server_unsaved_label">Не сохранено</string>
|
||||
<string name="server_unnamed">Без названия</string>
|
||||
|
||||
<!-- Notification & Tile -->
|
||||
<string name="notif_proxy_stop_action">Отключить</string>
|
||||
@@ -428,7 +442,6 @@
|
||||
<string name="settings_servers">Серверы</string>
|
||||
<string name="settings_servers_desc">Управление добавленными серверами и их настройками</string>
|
||||
<string name="settings_empty_servers">Нет добавленных серверов</string>
|
||||
<string name="provider_vk_calls">VK Звонки</string>
|
||||
<string name="server_delete_confirm_title">Удалить сервер?</string>
|
||||
<string name="server_delete_confirm_desc">Сервер \"%1$s\" и все его настройки будут удалены из приложения.</string>
|
||||
<!-- Раздел "Управление" в хабе сервера -->
|
||||
@@ -447,18 +460,6 @@
|
||||
<string name="server_delete_done_title">Сервер очищен</string>
|
||||
<string name="server_delete_done_desc">Компоненты FreeTurn удалены с сервера.</string>
|
||||
<string name="server_delete_done_confirm">Готово</string>
|
||||
<string name="cleanup_removed_label">Удалено с сервера:</string>
|
||||
<string name="cleanup_kept_label">Оставлено без изменений:</string>
|
||||
<string name="cleanup_nothing">Компоненты FreeTurn на сервере не найдены - удалять нечего.</string>
|
||||
<string name="cleanup_item_binary">Исполняемый файл free-turn-proxy</string>
|
||||
<string name="cleanup_item_service">Служба systemd</string>
|
||||
<string name="cleanup_item_wg">Интерфейс WireGuard (ft-wg0)</string>
|
||||
<string name="cleanup_item_wg_pkg">Пакет wireguard-tools</string>
|
||||
<string name="cleanup_item_firewall">Правило файрвола (ufw)</string>
|
||||
<string name="cleanup_item_files">Рабочие файлы и список пользователей</string>
|
||||
<string name="cleanup_kept_foreign_wg">Интерфейс ft-wg0 (создан не приложением)</string>
|
||||
<string name="cleanup_kept_wg_tools">Пакет wireguard-tools (установлен не приложением)</string>
|
||||
<string name="cleanup_kept_ip_forward">Системная настройка ip_forward</string>
|
||||
<string name="provider_connection_settings">Настройки подключения</string>
|
||||
<string name="provider_connection_settings_desc">Параметры клиента: адрес, потоки, DNS</string>
|
||||
<string name="provider_server_settings">Настройки сервера</string>
|
||||
@@ -469,6 +470,10 @@
|
||||
<string name="hub_connect_failed">Не удалось подключиться</string>
|
||||
<string name="hub_not_installed">Ядро не установлено</string>
|
||||
<string name="hub_sync_off">Синхронизация выключена</string>
|
||||
<string name="hub_op_apply">Применение настроек…</string>
|
||||
<string name="hub_op_update">Обновление сервера…</string>
|
||||
<string name="hub_op_upload_build">Загрузка локальной сборки…</string>
|
||||
<string name="hub_op_stop">Остановка сервера…</string>
|
||||
<!-- Заголовки фаз статуса (hero) -->
|
||||
<string name="pill_connecting">Подключение…</string>
|
||||
<string name="pill_not_paired">SSH не настроен</string>
|
||||
|
||||
@@ -10,38 +10,46 @@ class ControlResponseParserTest {
|
||||
|
||||
@Test
|
||||
fun `parses ok probe envelope`() {
|
||||
val raw = """{"proto":2,"result":"ok","data":{"installed":true,"running":false,"runtime":"systemd","euid":0,"wg":{"present":true,"port":51820},"virt":"kvm","wg_kernel":true,"conflicts":{"warp":true,"x3ui":false,"wgeasy":false,"tailscale":false,"other_ifaces":["CloudflareWARP"]}},"logs":[]}"""
|
||||
val raw = """{"proto":3,"result":"ok","data":{"installed":true,"running":true,"euid":0,"arch":"x86_64","method":"docker","version":"latest","config":{"method":"docker","backend":"new","connect":"","host":"203.0.113.7","listen_port":56000,"wg_port":51820,"wg_net":"10.13.13.0/24","mode":"udp","obf_profile":"rtpopus3","obf_key":"ab","version":"latest"}},"logs":[]}"""
|
||||
val r = ControlResponseParser.parse(raw)
|
||||
assertTrue(r.isOk)
|
||||
assertEquals(2, r.proto)
|
||||
val d = ControlJson.decode<ProbeData>(r.data)
|
||||
assertTrue(d.installed)
|
||||
assertEquals("systemd", d.runtime)
|
||||
assertEquals(51820, d.wg.port)
|
||||
assertTrue(d.conflicts.warp)
|
||||
assertEquals(listOf("CloudflareWARP"), d.conflicts.otherIfaces)
|
||||
assertEquals("docker", d.method)
|
||||
val c = d.config!!
|
||||
assertEquals("new", c.backend)
|
||||
assertEquals(56000, c.listenPort)
|
||||
assertEquals("10.13.13.0/24", c.wgNet)
|
||||
assertEquals("rtpopus3", c.obfProfile)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `wg port null decodes to null`() {
|
||||
val raw = """{"proto":2,"result":"ok","data":{"wg":{"present":false,"port":null}},"logs":[]}"""
|
||||
fun `probe without install conf has no config`() {
|
||||
val raw = """{"proto":3,"result":"ok","data":{"installed":false,"running":false,"euid":0,"arch":"aarch64"},"logs":[]}"""
|
||||
val d = ControlJson.decode<ProbeData>(ControlResponseParser.parse(raw).data)
|
||||
assertFalse(d.wg.present)
|
||||
assertNull(d.wg.port)
|
||||
assertFalse(d.installed)
|
||||
assertNull(d.config)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `parses err envelope with code`() {
|
||||
val raw = """{"proto":2,"result":"err","code":"wg_port_busy","msg":"udp 51820 busy","stage":"wg_setup","logs":["x"]}"""
|
||||
val raw = """{"proto":3,"result":"err","code":"port_busy","msg":"порт 51820/udp занят","stage":"apply","logs":["x"]}"""
|
||||
val r = ControlResponseParser.parse(raw)
|
||||
assertFalse(r.isOk)
|
||||
assertEquals("wg_port_busy", r.code)
|
||||
assertEquals("udp 51820 busy", r.msg)
|
||||
assertEquals("port_busy", r.code)
|
||||
assertEquals("порт 51820/udp занят", r.msg)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `other proto is proto_mismatch`() {
|
||||
val r = ControlResponseParser.parse("""{"proto":2,"result":"ok","data":{},"logs":[]}""")
|
||||
assertFalse(r.isOk)
|
||||
assertEquals(ControlResponseParser.PROTO_MISMATCH, r.code)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `banner before json is tolerated`() {
|
||||
val raw = "Welcome to Ubuntu\nLast login: ...\n{\"proto\":2,\"result\":\"ok\",\"data\":{},\"logs\":[]}"
|
||||
val raw = "Welcome to Ubuntu\nLast login: ...\n{\"proto\":3,\"result\":\"ok\",\"data\":{},\"logs\":[]}"
|
||||
assertTrue(ControlResponseParser.parse(raw).isOk)
|
||||
}
|
||||
|
||||
@@ -74,12 +82,23 @@ class ControlResponseParserTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `share-list arrays decode`() {
|
||||
val raw = """{"proto":2,"result":"ok","data":{"peers":[{"pub":"a=","ip":"10.0.0.2","has_conf":true}],"self_pub":"a=","clients":[{"id":"deadbeef"}]},"logs":[]}"""
|
||||
val d = ControlJson.decode<ShareListData>(ControlResponseParser.parse(raw).data)
|
||||
assertEquals(1, d.peers.size)
|
||||
assertEquals("a=", d.peers[0].pub)
|
||||
assertTrue(d.peers[0].hasConf)
|
||||
assertEquals("deadbeef", d.clients[0].id)
|
||||
fun `client-list decodes clients and share`() {
|
||||
val raw = """{"proto":3,"result":"ok","data":{"clients":[{"name":"owner","client_id":"aa","self":true,"ip":"10.13.13.2","pub":"p=","hs":1700000000},{"name":"phone","client_id":"bb","self":false}],"share":{"backend":"new","host":"203.0.113.7","port":56000,"mode":"udp","obf_profile":"rtpopus3","obf_key":"k"}},"logs":[]}"""
|
||||
val d = ControlJson.decode<ClientListData>(ControlResponseParser.parse(raw).data)
|
||||
assertEquals(2, d.clients.size)
|
||||
assertTrue(d.clients[0].self)
|
||||
assertEquals("p=", d.clients[0].pub)
|
||||
assertEquals("", d.clients[1].pub)
|
||||
assertEquals("new", d.share.backend)
|
||||
assertEquals(56000, d.share.port)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `apply decodes owner and key`() {
|
||||
val raw = """{"proto":3,"result":"ok","data":{"owner":{"client_id":"aa","pub":"p=","conf_b64":"W0ludGVyZmFjZV0=","link":"freeturn://x"},"obf_key":"kk","needs_restart":false},"logs":[]}"""
|
||||
val d = ControlJson.decode<ApplyData>(ControlResponseParser.parse(raw).data)
|
||||
assertEquals("aa", d.owner.clientId)
|
||||
assertEquals("[Interface]", decodeBase64(d.owner.confB64))
|
||||
assertEquals("kk", d.obfKey)
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,33 @@ class ServerJsonTest {
|
||||
assertEquals(KcpProfile.MOBILE, decoded.opts.kcp)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `install opts round trip`() {
|
||||
val srv = Server(
|
||||
name = "s",
|
||||
opts = ServerOpts(
|
||||
method = ServerMethod.SYSTEMD,
|
||||
backend = ServerBackend.EXTERNAL,
|
||||
wgPort = 51999,
|
||||
wgNet = "10.20.0.0/16"
|
||||
)
|
||||
)
|
||||
val o = ServerJson.decodeList(ServerJson.encodeList(listOf(srv))).single().opts
|
||||
assertEquals(ServerMethod.SYSTEMD, o.method)
|
||||
assertEquals(ServerBackend.EXTERNAL, o.backend)
|
||||
assertEquals(51999, o.wgPort)
|
||||
assertEquals("10.20.0.0/16", o.wgNet)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `snapshot without install opts falls back to defaults`() {
|
||||
val raw = """[{"id":"1","name":"s","opts":{"backend":"bogus"}}]"""
|
||||
val o = ServerJson.decodeList(raw).single().opts
|
||||
assertEquals(ServerMethod.DOCKER, o.method)
|
||||
assertEquals(ServerBackend.NEW, o.backend)
|
||||
assertEquals(ServerBackend.DEFAULT_WG_NET, o.wgNet)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `snapshot without mode and kcp falls back to defaults`() {
|
||||
val raw = """[{"id":"1","name":"s","opts":{"obfProfile":"none","obfKey":""}}]"""
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
package com.freeturn.app.domain.server
|
||||
|
||||
import com.freeturn.app.data.config.KcpProfile
|
||||
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.ServerBackend
|
||||
import com.freeturn.app.data.server.ServerMethod
|
||||
import com.freeturn.app.data.server.ServerOpts
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class ServerCommandTest {
|
||||
|
||||
@Test
|
||||
fun `apply new backend sends wg and omits connect`() {
|
||||
val argv = ServerCommand.Apply(
|
||||
ApplyOptions(
|
||||
method = ServerMethod.SYSTEMD,
|
||||
backend = ServerBackend.NEW,
|
||||
listenPort = 56001,
|
||||
connect = "ignored:1",
|
||||
obfProfile = ObfProfile.RTPOPUS3
|
||||
)
|
||||
).toArgv()
|
||||
assertEquals("apply", argv.first())
|
||||
assertTrue("--method=systemd" in argv)
|
||||
assertTrue("--listen-port=56001" in argv)
|
||||
assertTrue("--wg-net=${ServerBackend.DEFAULT_WG_NET}" in argv)
|
||||
assertFalse(argv.any { it.startsWith("--connect=") })
|
||||
// Пустой ключ не шлём - сервер оставит свой или сгенерирует.
|
||||
assertFalse(argv.any { it.startsWith("--obf-key=") })
|
||||
assertFalse(argv.any { it.startsWith("--kcp-") })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `apply external tcp sends connect and full kcp`() {
|
||||
val argv = ApplyOptions(
|
||||
method = ServerMethod.DOCKER,
|
||||
backend = ServerBackend.EXTERNAL,
|
||||
listenPort = 56000,
|
||||
connect = "127.0.0.1:443",
|
||||
proxyMode = ProxyMode.TCP,
|
||||
kcp = KcpProfile.DEFAULT,
|
||||
obfProfile = ObfProfile.NONE,
|
||||
obfKey = "k".repeat(64)
|
||||
).toArgv()
|
||||
assertTrue("--connect=127.0.0.1:443" in argv)
|
||||
assertFalse(argv.any { it.startsWith("--wg-") })
|
||||
assertFalse(argv.any { it.startsWith("--obf-key=") })
|
||||
assertEquals(8, argv.count { it.startsWith("--kcp-") })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `apply update flags go after config`() {
|
||||
val opts = ApplyOptions(method = ServerMethod.DOCKER, backend = ServerBackend.NEW, listenPort = 56000)
|
||||
assertEquals(opts.toArgv(), ServerCommand.Apply(opts).toArgv())
|
||||
assertEquals(
|
||||
opts.toArgv() + listOf("--update", "--bin=/tmp/freeturn-server.x"),
|
||||
ServerCommand.Apply(opts, update = true, bin = "/tmp/freeturn-server.x").toArgv()
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `uname maps to release asset`() {
|
||||
assertEquals("server-linux-amd64", ServerControl.serverAsset("x86_64"))
|
||||
assertEquals("server-linux-arm64", ServerControl.serverAsset("aarch64"))
|
||||
assertEquals("server-linux-armv7", ServerControl.serverAsset("armv7l"))
|
||||
assertEquals("server-linux-386", ServerControl.serverAsset("i686"))
|
||||
assertEquals(null, ServerControl.serverAsset("mips"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `server maps to apply options`() {
|
||||
val key = "a".repeat(64)
|
||||
val opts = Server(
|
||||
name = "s",
|
||||
proxyListen = "0.0.0.0:56123",
|
||||
proxyConnect = "10.0.0.1:51820",
|
||||
opts = ServerOpts(
|
||||
obfProfile = ObfProfile.RTPOPUS2,
|
||||
obfKey = key,
|
||||
backend = ServerBackend.EXTERNAL,
|
||||
method = ServerMethod.SYSTEMD
|
||||
)
|
||||
).applyOptions()
|
||||
assertEquals(56123, opts.listenPort)
|
||||
assertEquals("10.0.0.1:51820", opts.connect)
|
||||
assertEquals(key, opts.obfKey)
|
||||
assertEquals(ServerMethod.SYSTEMD, opts.method)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `client commands carry name`() {
|
||||
assertEquals(listOf("client-add", "--name=phone"), ServerCommand.ClientAdd("phone").toArgv())
|
||||
assertEquals(listOf("uninstall", "--target=all", "--purge"), ServerCommand.Uninstall.toArgv())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `wg net validation mirrors install sh`() {
|
||||
assertTrue(ServerBackend.isValidNet("10.13.13.0/24"))
|
||||
assertTrue(ServerBackend.isValidNet("172.16.0.0/16"))
|
||||
assertFalse(ServerBackend.isValidNet("10.13.13.1/24"))
|
||||
assertFalse(ServerBackend.isValidNet("10.13.13.0/30"))
|
||||
assertFalse(ServerBackend.isValidNet("10.0.0.0/8"))
|
||||
assertFalse(ServerBackend.isValidNet("256.0.0.0/24"))
|
||||
assertFalse(ServerBackend.isValidNet("010.0.0.0/24"))
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user