feat: sync серверных опций с клиентом + новое ядро
- Серверные настройки (VLESS bonding, WRAP-обфускация, wrap-key) синхронизируются между клиентом и сервером, чтобы DTLS-handshake не разъезжался. - Управление сервером переехало на единый bash-скрипт vk-turn-control.sh, стримящийся через SSH stdin (probe/install/start/ stop/logs/gen-wrap-key). KEY=VALUE протокол + RESULT-маркер. - Авто-обработка NEEDS_RESTART после update: клиент сам перезапускает сервер с актуальными опциями. - Socket-таймауты на SSH I/O (30s обычные команды, 180s install) — больше не висим при потере соединения. - Скрипт удаляет резервный .bak после успешного старта. - .claude/ в .gitignore. Клиентское ядро: - Удалена поддержка кастомного ядра (linker hack под SELinux). - Новые флаги: -streams-per-cred (вместо -allocs-per-stream), -captcha-solver v1/v2, -dns-servers (DNS оператора), -wrap/-wrap-key, -vless-bond. Удалены устаревшие -dns / -port 443. - Расширен CAPTCHA URL regex под новый формат manual_captcha.go. - Smart-wait стартапа клиента: до 5 минут, завершается по фактическому startupResult или остановке сервиса (не рубим watchdog раньше времени).
This commit is contained in:
1 parent
b694c61159
commit
61ca5f267c
19 files changed
+1183
-478
No files matched your search
@@ -17,3 +17,6 @@ local.properties
|
||||
# Build outputs
|
||||
**/build/
|
||||
**/release/
|
||||
|
||||
# Claude Code
|
||||
.claude/
|
||||
@@ -0,0 +1,293 @@
|
||||
#!/bin/bash
|
||||
# vk-turn-proxy server control script.
|
||||
# Streamed via SSH stdin from Android (bash -s -- <subcmd> <args>).
|
||||
# Output protocol: KEY=VALUE lines, "LOG: ..." for free text, final RESULT=ok|err.
|
||||
|
||||
set -eu
|
||||
|
||||
PREFIX="/opt/vk-turn"
|
||||
PIDFILE="$PREFIX/proxy.pid"
|
||||
WRAPFILE="$PREFIX/wrap.key"
|
||||
LOGFILE="$PREFIX/server.log"
|
||||
VERFILE="$PREFIX/version"
|
||||
BASE_URL="https://github.com/Moroka8/vk-turn-proxy/releases/latest/download"
|
||||
|
||||
log() { echo "LOG: $*"; }
|
||||
emit() { echo "$1=$2"; }
|
||||
die() { echo "ERR=$*"; echo "RESULT=err"; exit 1; }
|
||||
|
||||
trap 'rc=$?; if [ $rc -ne 0 ]; then echo "ERR=script exit $rc"; echo "RESULT=err"; fi' EXIT
|
||||
|
||||
detect_arch() {
|
||||
local m
|
||||
m=$(uname -m)
|
||||
case "$m" in
|
||||
x86_64|amd64) echo "server-linux-amd64" ;;
|
||||
aarch64|arm64) echo "server-linux-arm64" ;;
|
||||
*) die "unsupported arch: $m" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
binpath() { echo "$PREFIX/$(detect_arch)"; }
|
||||
|
||||
is_running() {
|
||||
if [ -f "$PIDFILE" ]; then
|
||||
local pid
|
||||
pid=$(cat "$PIDFILE" 2>/dev/null || echo "")
|
||||
if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then
|
||||
return 0
|
||||
fi
|
||||
rm -f "$PIDFILE"
|
||||
fi
|
||||
if pgrep -f "^$PREFIX/server-linux-" >/dev/null 2>&1; then
|
||||
return 0
|
||||
fi
|
||||
return 1
|
||||
}
|
||||
|
||||
cmd_probe() {
|
||||
local bin
|
||||
bin=$(binpath)
|
||||
if [ -x "$bin" ]; then
|
||||
emit INSTALLED yes
|
||||
local sha
|
||||
sha=$(sha256sum "$bin" 2>/dev/null | awk '{print $1}')
|
||||
[ -n "$sha" ] && emit BIN_SHA256 "$sha"
|
||||
if [ -f "$VERFILE" ]; then
|
||||
emit VERSION "$(cat "$VERFILE")"
|
||||
fi
|
||||
else
|
||||
emit INSTALLED no
|
||||
fi
|
||||
if is_running; then
|
||||
emit RUNNING yes
|
||||
local cmdline
|
||||
cmdline=$(pgrep -af "^$PREFIX/server-linux-" | head -n1 || true)
|
||||
if echo "$cmdline" | grep -q -- "-vless"; then emit VLESS yes; else emit VLESS no; fi
|
||||
if echo "$cmdline" | grep -q -- "-vless-bond"; then emit VLESS_BOND yes; else emit VLESS_BOND no; fi
|
||||
if echo "$cmdline" | grep -q -- "-wrap"; then emit WRAP yes; else emit WRAP no; fi
|
||||
else
|
||||
emit RUNNING no
|
||||
fi
|
||||
echo "RESULT=ok"
|
||||
trap - EXIT
|
||||
}
|
||||
|
||||
_dl() {
|
||||
local url=$1 out=$2
|
||||
if command -v curl >/dev/null 2>&1; then
|
||||
curl -sSL --fail -o "$out" "$url"
|
||||
elif command -v wget >/dev/null 2>&1; then
|
||||
wget -q -O "$out" "$url"
|
||||
else
|
||||
die "neither curl nor wget present"
|
||||
fi
|
||||
}
|
||||
|
||||
_resolve_version() {
|
||||
# GitHub `latest/download/<asset>` отвечает 302 с Location, содержащим тег
|
||||
# вида .../releases/download/vX.Y.Z/<asset>. Берём из URL.
|
||||
local url="$1" loc=""
|
||||
if command -v curl >/dev/null 2>&1; then
|
||||
loc=$(curl -sI "$url" 2>/dev/null | awk -F': ' 'tolower($1)=="location"{print $2}' | tr -d '\r' | head -n1)
|
||||
elif command -v wget >/dev/null 2>&1; then
|
||||
loc=$(wget --spider --server-response "$url" 2>&1 | awk '/[Ll]ocation:/{print $2}' | tr -d '\r' | head -n1)
|
||||
fi
|
||||
echo "$loc" | sed -nE 's#.*/releases/download/([^/]+)/.*#\1#p'
|
||||
}
|
||||
|
||||
cmd_install() {
|
||||
mkdir -p "$PREFIX" || die "cannot create $PREFIX"
|
||||
[ -w "$PREFIX" ] || die "$PREFIX not writable"
|
||||
local bin name asset_url tmp ver curver
|
||||
name=$(detect_arch)
|
||||
bin="$PREFIX/$name"
|
||||
tmp="$bin.new"
|
||||
asset_url="$BASE_URL/$name"
|
||||
|
||||
log "resolving latest version"
|
||||
ver=$(_resolve_version "$asset_url")
|
||||
if [ -z "$ver" ]; then
|
||||
die "cannot resolve latest version (no Location header from $BASE_URL)"
|
||||
fi
|
||||
curver=""
|
||||
[ -f "$VERFILE" ] && curver=$(cat "$VERFILE")
|
||||
|
||||
if [ -x "$bin" ] && [ "$ver" = "$curver" ]; then
|
||||
emit STAGE cached
|
||||
emit BIN "$name"
|
||||
emit VERSION "$ver"
|
||||
echo "RESULT=ok"
|
||||
trap - EXIT
|
||||
return 0
|
||||
fi
|
||||
|
||||
log "downloading $name @ $ver"
|
||||
if ! _dl "$asset_url" "$tmp"; then
|
||||
rm -f "$tmp"
|
||||
die "binary download failed"
|
||||
fi
|
||||
# sanity-check: GitHub отдаёт HTML-404 при отсутствии ассета.
|
||||
local size
|
||||
size=$(wc -c < "$tmp" 2>/dev/null || echo 0)
|
||||
if [ "$size" -lt 100000 ]; then
|
||||
rm -f "$tmp"
|
||||
die "downloaded file too small ($size bytes)"
|
||||
fi
|
||||
|
||||
chmod +x "$tmp"
|
||||
if [ -f "$bin" ]; then
|
||||
cp -f "$bin" "$bin.bak" 2>/dev/null || true
|
||||
fi
|
||||
mv -f "$tmp" "$bin"
|
||||
echo "$ver" > "$VERFILE"
|
||||
|
||||
emit STAGE downloaded
|
||||
emit BIN "$name"
|
||||
emit VERSION "$ver"
|
||||
if is_running; then
|
||||
emit NEEDS_RESTART yes
|
||||
fi
|
||||
echo "RESULT=ok"
|
||||
trap - EXIT
|
||||
}
|
||||
|
||||
# parse --key=value args into globals
|
||||
ARG_LISTEN=""
|
||||
ARG_CONNECT=""
|
||||
ARG_VLESS=""
|
||||
ARG_VLESS_BOND=""
|
||||
ARG_WRAP_KEY=""
|
||||
ARG_TAIL=80
|
||||
|
||||
parse_args() {
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--listen=*)
|
||||
ARG_LISTEN="${1#*=}"
|
||||
[[ "$ARG_LISTEN" =~ ^[a-zA-Z0-9.:_-]+$ ]] || die "bad --listen"
|
||||
;;
|
||||
--connect=*)
|
||||
ARG_CONNECT="${1#*=}"
|
||||
[[ "$ARG_CONNECT" =~ ^[a-zA-Z0-9.:_-]+$ ]] || die "bad --connect"
|
||||
;;
|
||||
--vless) ARG_VLESS=1 ;;
|
||||
--vless-bond) ARG_VLESS_BOND=1 ;;
|
||||
--wrap-key=*)
|
||||
ARG_WRAP_KEY="${1#*=}"
|
||||
[[ "$ARG_WRAP_KEY" =~ ^[0-9a-fA-F]{64}$ ]] || die "bad --wrap-key (need 64 hex)"
|
||||
;;
|
||||
--tail=*)
|
||||
ARG_TAIL="${1#*=}"
|
||||
[[ "$ARG_TAIL" =~ ^[0-9]+$ ]] || die "bad --tail"
|
||||
;;
|
||||
*) die "unknown arg: $1" ;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
}
|
||||
|
||||
cmd_start() {
|
||||
parse_args "$@"
|
||||
[ -n "$ARG_LISTEN" ] || die "--listen required"
|
||||
[ -n "$ARG_CONNECT" ] || die "--connect required"
|
||||
local bin
|
||||
bin=$(binpath)
|
||||
[ -x "$bin" ] || die "server binary not installed; run install first"
|
||||
|
||||
if is_running; then
|
||||
log "already running, stopping first"
|
||||
cmd_stop_inner
|
||||
fi
|
||||
|
||||
cd "$PREFIX"
|
||||
local args=(-listen "$ARG_LISTEN" -connect "$ARG_CONNECT")
|
||||
[ -n "$ARG_VLESS" ] && args+=(-vless)
|
||||
[ -n "$ARG_VLESS_BOND" ] && args+=(-vless-bond)
|
||||
if [ -n "$ARG_WRAP_KEY" ]; then
|
||||
umask 077
|
||||
printf '%s' "$ARG_WRAP_KEY" > "$WRAPFILE"
|
||||
chmod 600 "$WRAPFILE"
|
||||
args+=(-wrap -wrap-key "$(cat "$WRAPFILE")")
|
||||
fi
|
||||
|
||||
nohup "$bin" "${args[@]}" >"$LOGFILE" 2>&1 &
|
||||
local pid=$!
|
||||
echo "$pid" > "$PIDFILE"
|
||||
sleep 1
|
||||
if ! kill -0 "$pid" 2>/dev/null; then
|
||||
if [ -f "$bin.bak" ]; then
|
||||
log "process died; rolling back .bak"
|
||||
mv -f "$bin.bak" "$bin"
|
||||
fi
|
||||
rm -f "$PIDFILE"
|
||||
die "server failed to start; see logs"
|
||||
fi
|
||||
# Старт удался — резервная копия больше не нужна, чтобы не копились тушки
|
||||
# после нескольких циклов update.
|
||||
rm -f "$bin.bak"
|
||||
emit PID "$pid"
|
||||
echo "RESULT=ok"
|
||||
trap - EXIT
|
||||
}
|
||||
|
||||
cmd_stop_inner() {
|
||||
if [ -f "$PIDFILE" ]; then
|
||||
local pid
|
||||
pid=$(cat "$PIDFILE" 2>/dev/null || echo "")
|
||||
if [ -n "$pid" ]; then
|
||||
kill "$pid" 2>/dev/null || true
|
||||
sleep 1
|
||||
kill -9 "$pid" 2>/dev/null || true
|
||||
fi
|
||||
rm -f "$PIDFILE"
|
||||
fi
|
||||
pkill -9 -f "^$PREFIX/server-linux-" 2>/dev/null || true
|
||||
rm -f "$WRAPFILE"
|
||||
}
|
||||
|
||||
cmd_stop() {
|
||||
cmd_stop_inner
|
||||
emit STOPPED yes
|
||||
echo "RESULT=ok"
|
||||
trap - EXIT
|
||||
}
|
||||
|
||||
cmd_logs() {
|
||||
parse_args "$@"
|
||||
if [ -f "$LOGFILE" ]; then
|
||||
tail -n "$ARG_TAIL" "$LOGFILE" | sed 's/^/LOG: /'
|
||||
else
|
||||
log "(log empty)"
|
||||
fi
|
||||
echo "RESULT=ok"
|
||||
trap - EXIT
|
||||
}
|
||||
|
||||
cmd_gen_wrap_key() {
|
||||
local bin key
|
||||
bin=$(binpath)
|
||||
[ -x "$bin" ] || die "server binary not installed"
|
||||
key=$("$bin" -gen-wrap-key 2>/dev/null | grep -oE '[0-9a-fA-F]{64}' | head -n1)
|
||||
[ -n "$key" ] || die "binary did not return wrap-key"
|
||||
emit WRAPKEY "$key"
|
||||
echo "RESULT=ok"
|
||||
trap - EXIT
|
||||
}
|
||||
|
||||
main() {
|
||||
[ $# -ge 1 ] || die "no subcommand"
|
||||
local sub=$1
|
||||
shift
|
||||
case "$sub" in
|
||||
probe) cmd_probe ;;
|
||||
install) cmd_install "$@" ;;
|
||||
start) cmd_start "$@" ;;
|
||||
stop) cmd_stop ;;
|
||||
logs) cmd_logs "$@" ;;
|
||||
gen-wrap-key) cmd_gen_wrap_key ;;
|
||||
*) die "unknown subcommand: $sub" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
main "$@"
|
||||
@@ -18,7 +18,6 @@ import android.os.SystemClock
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.app.NotificationManagerCompat
|
||||
import com.freeturn.app.data.AppPreferences
|
||||
import com.freeturn.app.data.DnsMode
|
||||
import java.io.BufferedReader
|
||||
import java.io.File
|
||||
import java.io.InputStreamReader
|
||||
@@ -51,8 +50,11 @@ class ProxyService : Service() {
|
||||
private const val NOTIF_ID_CAPTCHA = 2
|
||||
// Жёстко привязываемся к строке-объявлению капчи в бинарнике, чтобы
|
||||
// случайные localhost-URL в других логах не открывали диалог.
|
||||
// Новое ядро (manual_captcha.go) пишет "manually open this URL: <url>".
|
||||
// Старое — "Open this URL in your browser: <url>". Поддерживаем оба, чтобы
|
||||
// приложение работало с кастомным ядром, оставшимся у пользователя.
|
||||
private val CAPTCHA_URL_REGEX =
|
||||
Pattern.compile("""Open this URL in your browser:\s*(https?://\S+)""")
|
||||
Pattern.compile("""(?:manually open this URL|Open this URL in your browser):\s*(https?://\S+)""")
|
||||
|
||||
// События жизненного цикла соединений, публикуемые ядром (client/main.go).
|
||||
// Не-VLESS: несколько потоков со своим [STREAM N], у каждого свой Established/Closed.
|
||||
@@ -145,16 +147,12 @@ class ProxyService : Service() {
|
||||
if (userStopped.get()) return
|
||||
|
||||
val cfg = prefs.clientConfigFlow.first()
|
||||
// Wrap-обфускация и VLESS bonding управляются на серверном экране, но
|
||||
// должны передаваться и клиенту с тем же ключом, иначе DTLS-handshake
|
||||
// не сойдётся. Источник истины — общий serverOpts.
|
||||
val srv = prefs.serverOptsFlow.first()
|
||||
|
||||
val customBin = File(filesDir, "custom_vkturn")
|
||||
val useCustom = customBin.exists()
|
||||
val executable = if (useCustom) {
|
||||
ProxyServiceState.addLog("Используется кастомное ядро из памяти телефона")
|
||||
customBin.absolutePath
|
||||
} else {
|
||||
ProxyServiceState.addLog("Используется стандартное ядро из APK")
|
||||
"${applicationInfo.nativeLibraryDir}/libvkturn.so"
|
||||
}
|
||||
val executable = "${applicationInfo.nativeLibraryDir}/libvkturn.so"
|
||||
|
||||
val cmdArgs = mutableListOf<String>()
|
||||
|
||||
@@ -170,30 +168,34 @@ class ProxyService : Service() {
|
||||
cmdArgs.add(cfg.vkLink)
|
||||
cmdArgs.add("-listen"); cmdArgs.add(cfg.localPort)
|
||||
if (cfg.threads > 0) { cmdArgs.add("-n"); cmdArgs.add(cfg.threads.toString()) }
|
||||
if (cfg.allocsPerStream > 1) { cmdArgs.add("-allocs-per-stream"); cmdArgs.add(cfg.allocsPerStream.toString()) }
|
||||
// -streams-per-cred передаём только если пользователь поменял дефолт.
|
||||
if (cfg.streamsPerCred > 0 && cfg.streamsPerCred != 10) {
|
||||
cmdArgs.add("-streams-per-cred"); cmdArgs.add(cfg.streamsPerCred.toString())
|
||||
}
|
||||
if (cfg.vlessMode) cmdArgs.add("-vless")
|
||||
else if (cfg.useUdp) cmdArgs.add("-udp")
|
||||
// VLESS bonding имеет смысл только в VLESS-режиме.
|
||||
if (cfg.vlessMode && srv.vlessBond) cmdArgs.add("-vless-bond")
|
||||
// WRAP: тот же ключ, что и у сервера (хранится в EncryptedSharedPreferences).
|
||||
// Без 64-hex ключа флаг не передаём — ядро упадёт.
|
||||
if (srv.wrapEnabled &&
|
||||
srv.wrapKey.length == 64 &&
|
||||
srv.wrapKey.matches(Regex("^[0-9a-fA-F]+$"))
|
||||
) {
|
||||
cmdArgs.add("-wrap")
|
||||
cmdArgs.add("-wrap-key"); cmdArgs.add(srv.wrapKey)
|
||||
}
|
||||
if (cfg.manualCaptcha) cmdArgs.add("--manual-captcha")
|
||||
// -dns передаём только если пользователь выбрал не-дефолт: ядро по
|
||||
// умолчанию уже использует auto (UDP/53 с sticky-fallback на DoH).
|
||||
if (cfg.dnsMode in DnsMode.ALL && cfg.dnsMode != DnsMode.AUTO) {
|
||||
cmdArgs.add("-dns"); cmdArgs.add(cfg.dnsMode)
|
||||
if (cfg.captchaSolver != "v2") {
|
||||
cmdArgs.add("-captcha-solver"); cmdArgs.add(cfg.captchaSolver)
|
||||
}
|
||||
if (cfg.forcePort443) { cmdArgs.add("-port"); cmdArgs.add("443") }
|
||||
if (cfg.debugMode) cmdArgs.add("-debug")
|
||||
}
|
||||
|
||||
// Кастомное ядро лежит в filesDir, откуда SELinux (untrusted_app) запрещает execve.
|
||||
// Запускаем через системный линкер: /system/bin/linker* — ему execve разрешён,
|
||||
// а целевой ELF мапится как данные. Работает для PIE-бинарников
|
||||
// (Go-сборки android/arm64 PIE по умолчанию).
|
||||
if (useCustom) {
|
||||
val linker = if (Build.SUPPORTED_ABIS.firstOrNull()?.contains("64") == true) {
|
||||
"/system/bin/linker64"
|
||||
} else {
|
||||
"/system/bin/linker"
|
||||
if (cfg.useCarrierDns) {
|
||||
val dns = activeNetworkDnsServers()
|
||||
if (dns.isNotBlank()) {
|
||||
cmdArgs.add("-dns-servers"); cmdArgs.add(dns)
|
||||
}
|
||||
}
|
||||
cmdArgs.add(0, linker)
|
||||
}
|
||||
|
||||
var exitCode = -1
|
||||
@@ -543,6 +545,25 @@ class ProxyService : Service() {
|
||||
private fun isQuotaError(line: String): Boolean =
|
||||
line.lowercase().contains("quota")
|
||||
|
||||
/**
|
||||
* DNS активной сети (оператор/Wi-Fi). Возвращает comma-separated список IP,
|
||||
* пригодный для флага `-dns-servers` ядра. Пусто, если сеть недоступна или
|
||||
* у linkProperties нет DNS (что норма на эмуляторе/некоторых VPN).
|
||||
*/
|
||||
private fun activeNetworkDnsServers(): String {
|
||||
return try {
|
||||
val cm = getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
|
||||
val net = cm.activeNetwork ?: return ""
|
||||
val lp = cm.getLinkProperties(net) ?: return ""
|
||||
lp.dnsServers
|
||||
.mapNotNull { it.hostAddress }
|
||||
.filter { it.isNotBlank() }
|
||||
.joinToString(",")
|
||||
} catch (_: Exception) {
|
||||
""
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
super.onDestroy()
|
||||
userStopped.set(true)
|
||||
|
||||
@@ -8,6 +8,7 @@ import com.jcraft.jsch.Session
|
||||
import com.jcraft.jsch.UserInfo
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.ByteArrayInputStream
|
||||
import java.security.MessageDigest
|
||||
import java.util.Base64
|
||||
import java.util.Properties
|
||||
@@ -30,7 +31,12 @@ class SSHManager {
|
||||
suspend fun executeSilentCommand(
|
||||
ip: String, port: Int, user: String, pass: String, command: String,
|
||||
knownFingerprint: String? = null,
|
||||
sshKey: String = ""
|
||||
sshKey: String = "",
|
||||
/**
|
||||
* Таймаут на чтение из канала (мс). Защита от зависания, когда
|
||||
* соединение установлено, но удалённый процесс молчит.
|
||||
*/
|
||||
execTimeoutMs: Int = 30_000
|
||||
): String = withContext(Dispatchers.IO) {
|
||||
val tofu = TofuHostKeyRepository(knownFingerprint)
|
||||
var tempSession: Session? = null
|
||||
@@ -52,6 +58,9 @@ class SSHManager {
|
||||
config["StrictHostKeyChecking"] = "no"
|
||||
tempSession.setConfig(config)
|
||||
tempSession.connect(5000)
|
||||
// Socket-таймаут на I/O: если за execTimeoutMs не пришло ни байта,
|
||||
// read() бросит SocketTimeoutException вместо вечного ожидания.
|
||||
tempSession.timeout = execTimeoutMs
|
||||
|
||||
lastSeenFingerprint = tofu.capturedFingerprint
|
||||
|
||||
@@ -65,7 +74,7 @@ class SSHManager {
|
||||
|
||||
// Получаем stdout-поток ДО connect() — после уже нельзя
|
||||
val inStream = channel.inputStream
|
||||
channel.connect()
|
||||
channel.connect(execTimeoutMs)
|
||||
|
||||
val output = inStream.bufferedReader().use { reader ->
|
||||
buildString {
|
||||
@@ -94,6 +103,76 @@ class SSHManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Выполняет команду по SSH, передавая [stdin] через стандартный ввод процесса.
|
||||
* Используется для стрима asset-скрипта (`bash -s -- args`) без записи на сервер.
|
||||
* Возвращает stdout+stderr команды (CRLF→LF).
|
||||
*/
|
||||
suspend fun executeWithStdin(
|
||||
ip: String, port: Int, user: String, pass: String,
|
||||
command: String, stdin: String,
|
||||
knownFingerprint: String? = null,
|
||||
sshKey: String = "",
|
||||
/**
|
||||
* Таймаут на чтение из канала (мс). Дефолт > чем у обычного exec,
|
||||
* потому что серверный install качает бинарь с GitHub.
|
||||
*/
|
||||
execTimeoutMs: Int = 180_000
|
||||
): String = withContext(Dispatchers.IO) {
|
||||
val tofu = TofuHostKeyRepository(knownFingerprint)
|
||||
var tempSession: Session? = null
|
||||
try {
|
||||
val jsch = JSch()
|
||||
if (sshKey.isNotBlank()) {
|
||||
jsch.addIdentity("identity", sshKey.toByteArray(Charsets.UTF_8), null, null)
|
||||
}
|
||||
tempSession = jsch.getSession(user, ip, port)
|
||||
if (sshKey.isBlank()) tempSession.setPassword(pass)
|
||||
tempSession.hostKeyRepository = tofu
|
||||
val config = Properties()
|
||||
config["StrictHostKeyChecking"] = "no"
|
||||
tempSession.setConfig(config)
|
||||
tempSession.connect(5000)
|
||||
tempSession.timeout = execTimeoutMs
|
||||
|
||||
lastSeenFingerprint = tofu.capturedFingerprint
|
||||
|
||||
val channel = tempSession.openChannel("exec") as ChannelExec
|
||||
val sanitized = command.replace("\r\n", "\n").replace("\r", "\n")
|
||||
channel.setCommand("exec 2>&1\n$sanitized")
|
||||
// Нормализуем переносы строк stdin: Kotlin source может содержать
|
||||
// CRLF, что ломает bash heredoc/parser.
|
||||
val stdinLf = stdin.replace("\r\n", "\n").replace("\r", "\n")
|
||||
channel.setInputStream(ByteArrayInputStream(stdinLf.toByteArray(Charsets.UTF_8)))
|
||||
|
||||
val inStream = channel.inputStream
|
||||
channel.connect(execTimeoutMs)
|
||||
|
||||
val output = inStream.bufferedReader().use { reader ->
|
||||
buildString {
|
||||
var line: String?
|
||||
while (reader.readLine().also { line = it } != null) {
|
||||
append(line).append("\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
channel.disconnect()
|
||||
output.trim()
|
||||
} catch (e: Exception) {
|
||||
val isMitm = tofu.capturedFingerprint != null
|
||||
&& knownFingerprint != null
|
||||
&& tofu.capturedFingerprint != knownFingerprint
|
||||
if (isMitm) {
|
||||
"ERROR: Отпечаток сервера изменился — возможна MITM-атака\n" +
|
||||
"Ожидался: $knownFingerprint\n" +
|
||||
"Получен: ${tofu.capturedFingerprint}"
|
||||
} else {
|
||||
"ERROR: ${e.message}"
|
||||
}
|
||||
} finally {
|
||||
tempSession?.disconnect()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -34,28 +34,22 @@ data class ClientConfig(
|
||||
val serverAddress: String = "",
|
||||
val vkLink: String = "",
|
||||
val threads: Int = 4,
|
||||
val allocsPerStream: Int = 1,
|
||||
/** Соответствует флагу `-streams-per-cred` ядра. Дефолт ядра = 10. */
|
||||
val streamsPerCred: Int = 10,
|
||||
val useUdp: Boolean = true,
|
||||
val manualCaptcha: Boolean = false,
|
||||
val localPort: String = "127.0.0.1:9000",
|
||||
val isRawMode: Boolean = false,
|
||||
val rawCommand: String = "",
|
||||
val vlessMode: Boolean = false,
|
||||
// "auto" | "udp" | "doh" — соответствует флагу -dns ядра.
|
||||
val dnsMode: String = DnsMode.AUTO,
|
||||
// Если true — в argv ядра добавляется -port 443, переопределяя порт TURN-сервера VK.
|
||||
val forcePort443: Boolean = false,
|
||||
/** "v1" | "v2" — соответствует флагу -captcha-solver ядра. Дефолт = v2. */
|
||||
val captchaSolver: String = "v2",
|
||||
// Если true — добавляется флаг -debug для расширенного вывода в логах.
|
||||
val debugMode: Boolean = false
|
||||
val debugMode: Boolean = false,
|
||||
// Если true — в argv передаётся -dns-servers с DNS активной сети (оператор связи).
|
||||
val useCarrierDns: Boolean = false
|
||||
)
|
||||
|
||||
object DnsMode {
|
||||
const val AUTO = "auto"
|
||||
const val UDP = "udp"
|
||||
const val DOH = "doh"
|
||||
val ALL = listOf(AUTO, UDP, DOH)
|
||||
}
|
||||
|
||||
class AppPreferences(context: Context) {
|
||||
private val context = context.applicationContext
|
||||
|
||||
@@ -71,23 +65,34 @@ class AppPreferences(context: Context) {
|
||||
// Устаревший ключ из мультиссылочной фичи — используется для очистки.
|
||||
private val CLIENT_VK_LINKS_LEGACY = stringPreferencesKey("client_vk_links")
|
||||
val CLIENT_THREADS = intPreferencesKey("client_threads")
|
||||
val CLIENT_ALLOCS_PER_STREAM = intPreferencesKey("client_allocs_per_stream")
|
||||
val CLIENT_STREAMS_PER_CRED = intPreferencesKey("client_streams_per_cred")
|
||||
val CLIENT_UDP = booleanPreferencesKey("client_udp")
|
||||
val CLIENT_MANUAL_CAPTCHA = booleanPreferencesKey("client_manual_captcha")
|
||||
val CLIENT_LOCAL_PORT = stringPreferencesKey("client_local_port")
|
||||
val CLIENT_IS_RAW = booleanPreferencesKey("client_is_raw")
|
||||
val CLIENT_RAW_CMD = stringPreferencesKey("client_raw_cmd")
|
||||
val CLIENT_VLESS = booleanPreferencesKey("client_vless")
|
||||
val CLIENT_DNS_MODE = stringPreferencesKey("client_dns_mode")
|
||||
val CLIENT_FORCE_PORT_443 = booleanPreferencesKey("client_turn_port_443")
|
||||
val CLIENT_CAPTCHA_SOLVER = stringPreferencesKey("client_captcha_solver")
|
||||
val CLIENT_DEBUG = booleanPreferencesKey("client_debug")
|
||||
val CLIENT_USE_CARRIER_DNS = booleanPreferencesKey("client_use_carrier_dns")
|
||||
// Устаревшие ключи — не пишутся, но молча удаляются при saveClientConfig.
|
||||
private val CLIENT_DNS_MODE_LEGACY = stringPreferencesKey("client_dns_mode")
|
||||
private val CLIENT_ALLOCS_PER_STREAM_LEGACY = intPreferencesKey("client_allocs_per_stream")
|
||||
|
||||
// Устаревший ключ — читается только для миграции (true → "doh").
|
||||
// Ключ "client_force_port_443" не переиспользуется под новую семантику, чтобы
|
||||
// у старых пользователей не включился неожиданно -port 443.
|
||||
// Устаревший ключ из старой -port 443 фичи (обе семантики удалены).
|
||||
private val CLIENT_FORCE_PORT_443_LEGACY = booleanPreferencesKey("client_force_port_443")
|
||||
private val CLIENT_TURN_PORT_443_LEGACY = booleanPreferencesKey("client_turn_port_443")
|
||||
val PROXY_LISTEN = stringPreferencesKey("proxy_listen")
|
||||
val PROXY_CONNECT = stringPreferencesKey("proxy_connect")
|
||||
// Серверные параметры (управляются на ServerManagementScreen).
|
||||
val SERVER_VLESS_BOND = booleanPreferencesKey("server_vless_bond")
|
||||
val SERVER_WRAP_ENABLED = booleanPreferencesKey("server_wrap_enabled")
|
||||
// Ревизия — инкрементится при saveServerOpts. Нужна, чтобы Flow эмитил
|
||||
// обновление, когда меняется только wrap-key в EncryptedSharedPreferences
|
||||
// (DataStore сам по себе не видит этого изменения).
|
||||
val SERVER_OPTS_REV = intPreferencesKey("server_opts_rev")
|
||||
// Wrap-ключ хранится в EncryptedSharedPreferences (key: "server_wrap_key"),
|
||||
// не в DataStore. См. encryptedPrefs ниже.
|
||||
val DYNAMIC_THEME = booleanPreferencesKey("dynamic_theme")
|
||||
val TG_SUBSCRIBE_SHOWN = booleanPreferencesKey("tg_subscribe_shown")
|
||||
val PROFILES_JSON = stringPreferencesKey("profiles_json")
|
||||
@@ -138,17 +143,18 @@ class AppPreferences(context: Context) {
|
||||
serverAddress = prefs[CLIENT_SERVER_ADDR] ?: "",
|
||||
vkLink = prefs[CLIENT_VK_LINK] ?: "",
|
||||
threads = prefs[CLIENT_THREADS] ?: 4,
|
||||
allocsPerStream = prefs[CLIENT_ALLOCS_PER_STREAM] ?: 1,
|
||||
streamsPerCred = prefs[CLIENT_STREAMS_PER_CRED] ?: 10,
|
||||
useUdp = prefs[CLIENT_UDP] ?: true,
|
||||
manualCaptcha = prefs[CLIENT_MANUAL_CAPTCHA] ?: false,
|
||||
localPort = prefs[CLIENT_LOCAL_PORT] ?: "127.0.0.1:9000",
|
||||
isRawMode = prefs[CLIENT_IS_RAW] ?: false,
|
||||
rawCommand = prefs[CLIENT_RAW_CMD] ?: "",
|
||||
vlessMode = prefs[CLIENT_VLESS] ?: false,
|
||||
dnsMode = prefs[CLIENT_DNS_MODE]
|
||||
?: if (prefs[CLIENT_FORCE_PORT_443_LEGACY] == true) DnsMode.DOH else DnsMode.AUTO,
|
||||
forcePort443 = prefs[CLIENT_FORCE_PORT_443] ?: false,
|
||||
debugMode = prefs[CLIENT_DEBUG] ?: false
|
||||
captchaSolver = (prefs[CLIENT_CAPTCHA_SOLVER] ?: "v2").let {
|
||||
if (it == "v1" || it == "v2") it else "v2"
|
||||
},
|
||||
debugMode = prefs[CLIENT_DEBUG] ?: false,
|
||||
useCarrierDns = prefs[CLIENT_USE_CARRIER_DNS] ?: false
|
||||
)
|
||||
}
|
||||
|
||||
@@ -164,6 +170,34 @@ class AppPreferences(context: Context) {
|
||||
.catch { if (it is IOException) emit(emptyPreferences()) else throw it }
|
||||
.map { prefs -> prefs[PROXY_CONNECT] ?: "127.0.0.1:40537" }
|
||||
|
||||
/** Снимок серверных опций. wrapKey читается из шифрованного хранилища. */
|
||||
data class ServerOpts(
|
||||
val vlessBond: Boolean = false,
|
||||
val wrapEnabled: Boolean = false,
|
||||
val wrapKey: String = ""
|
||||
)
|
||||
|
||||
val serverOptsFlow: Flow<ServerOpts> = context.dataStore.data
|
||||
.catch { if (it is IOException) emit(emptyPreferences()) else throw it }
|
||||
.map { prefs ->
|
||||
ServerOpts(
|
||||
vlessBond = prefs[SERVER_VLESS_BOND] ?: false,
|
||||
wrapEnabled = prefs[SERVER_WRAP_ENABLED] ?: false,
|
||||
wrapKey = encryptedPrefs.getString("server_wrap_key", null) ?: ""
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun saveServerOpts(opts: ServerOpts) {
|
||||
withContext(Dispatchers.IO) {
|
||||
encryptedPrefs.edit { putString("server_wrap_key", opts.wrapKey) }
|
||||
}
|
||||
context.dataStore.edit { prefs ->
|
||||
prefs[SERVER_VLESS_BOND] = opts.vlessBond
|
||||
prefs[SERVER_WRAP_ENABLED] = opts.wrapEnabled
|
||||
prefs[SERVER_OPTS_REV] = (prefs[SERVER_OPTS_REV] ?: 0) + 1
|
||||
}
|
||||
}
|
||||
|
||||
val dynamicThemeFlow: Flow<Boolean> = context.dataStore.data
|
||||
.catch { if (it is IOException) emit(emptyPreferences()) else throw it }
|
||||
.map { prefs -> prefs[DYNAMIC_THEME] ?: true }
|
||||
@@ -224,7 +258,7 @@ class AppPreferences(context: Context) {
|
||||
prefs[CLIENT_VK_LINK] = config.vkLink
|
||||
prefs.remove(CLIENT_VK_LINKS_LEGACY)
|
||||
prefs[CLIENT_THREADS] = config.threads
|
||||
prefs[CLIENT_ALLOCS_PER_STREAM] = config.allocsPerStream
|
||||
prefs[CLIENT_STREAMS_PER_CRED] = config.streamsPerCred
|
||||
prefs[CLIENT_UDP] = config.useUdp
|
||||
prefs[CLIENT_MANUAL_CAPTCHA] = config.manualCaptcha
|
||||
// Мигрируем старый ключ: noDtls удалён из приложения.
|
||||
@@ -233,12 +267,14 @@ class AppPreferences(context: Context) {
|
||||
prefs[CLIENT_IS_RAW] = config.isRawMode
|
||||
prefs[CLIENT_RAW_CMD] = config.rawCommand
|
||||
prefs[CLIENT_VLESS] = config.vlessMode
|
||||
prefs[CLIENT_DNS_MODE] = if (config.dnsMode in DnsMode.ALL) config.dnsMode else DnsMode.AUTO
|
||||
prefs[CLIENT_FORCE_PORT_443] = config.forcePort443
|
||||
prefs[CLIENT_CAPTCHA_SOLVER] = config.captchaSolver
|
||||
prefs[CLIENT_DEBUG] = config.debugMode
|
||||
// Зачищаем устаревший ключ после успешной миграции, чтобы он не всплывал
|
||||
// при следующей загрузке, если пользователь переключит режим обратно.
|
||||
prefs[CLIENT_USE_CARRIER_DNS] = config.useCarrierDns
|
||||
// Удаляем устаревшие ключи, которые больше не использует ядро.
|
||||
prefs.remove(CLIENT_FORCE_PORT_443_LEGACY)
|
||||
prefs.remove(CLIENT_TURN_PORT_443_LEGACY)
|
||||
prefs.remove(CLIENT_DNS_MODE_LEGACY)
|
||||
prefs.remove(CLIENT_ALLOCS_PER_STREAM_LEGACY)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -274,11 +310,12 @@ class AppPreferences(context: Context) {
|
||||
)
|
||||
}
|
||||
|
||||
/** Полный сброс: DataStore + EncryptedSharedPreferences + кастомный бинарник */
|
||||
/** Полный сброс: DataStore + EncryptedSharedPreferences. */
|
||||
suspend fun resetAll() {
|
||||
context.dataStore.edit { it.clear() }
|
||||
withContext(Dispatchers.IO) {
|
||||
encryptedPrefs.edit { clear() }
|
||||
// Чистим следы старого кастомного ядра, если оставались.
|
||||
File(context.filesDir, "custom_vkturn").delete()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,16 +60,16 @@ internal object ProfileJson {
|
||||
put("serverAddress", p.client.serverAddress)
|
||||
put("vkLink", p.client.vkLink)
|
||||
put("threads", p.client.threads)
|
||||
put("allocsPerStream", p.client.allocsPerStream)
|
||||
put("streamsPerCred", p.client.streamsPerCred)
|
||||
put("useUdp", p.client.useUdp)
|
||||
put("manualCaptcha", p.client.manualCaptcha)
|
||||
put("localPort", p.client.localPort)
|
||||
put("isRawMode", p.client.isRawMode)
|
||||
put("rawCommand", p.client.rawCommand)
|
||||
put("vlessMode", p.client.vlessMode)
|
||||
put("dnsMode", p.client.dnsMode)
|
||||
put("forcePort443", p.client.forcePort443)
|
||||
put("captchaSolver", p.client.captchaSolver)
|
||||
put("debugMode", p.client.debugMode)
|
||||
put("useCarrierDns", p.client.useCarrierDns)
|
||||
})
|
||||
put("proxyListen", p.proxyListen)
|
||||
put("proxyConnect", p.proxyConnect)
|
||||
@@ -94,18 +94,18 @@ internal object ProfileJson {
|
||||
serverAddress = cliO.optString("serverAddress"),
|
||||
vkLink = cliO.optString("vkLink"),
|
||||
threads = cliO.optInt("threads", 4),
|
||||
allocsPerStream = cliO.optInt("allocsPerStream", 1),
|
||||
streamsPerCred = cliO.optInt("streamsPerCred", 10),
|
||||
useUdp = cliO.optBoolean("useUdp", true),
|
||||
manualCaptcha = cliO.optBoolean("manualCaptcha", false),
|
||||
localPort = cliO.optString("localPort", "127.0.0.1:9000"),
|
||||
isRawMode = cliO.optBoolean("isRawMode", false),
|
||||
rawCommand = cliO.optString("rawCommand"),
|
||||
vlessMode = cliO.optBoolean("vlessMode", false),
|
||||
dnsMode = cliO.optString("dnsMode", DnsMode.AUTO).let {
|
||||
if (it in DnsMode.ALL) it else DnsMode.AUTO
|
||||
captchaSolver = cliO.optString("captchaSolver", "v2").let {
|
||||
if (it == "v1" || it == "v2") it else "v2"
|
||||
},
|
||||
forcePort443 = cliO.optBoolean("forcePort443", false),
|
||||
debugMode = cliO.optBoolean("debugMode", false)
|
||||
debugMode = cliO.optBoolean("debugMode", false),
|
||||
useCarrierDns = cliO.optBoolean("useCarrierDns", false)
|
||||
),
|
||||
proxyListen = o.optString("proxyListen").ifBlank { "0.0.0.0:56000" },
|
||||
proxyConnect = o.optString("proxyConnect").ifBlank { "127.0.0.1:40537" }
|
||||
|
||||
@@ -2,7 +2,6 @@ package com.freeturn.app.domain
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import com.freeturn.app.ConnectionStats
|
||||
import com.freeturn.app.ProxyService
|
||||
@@ -15,31 +14,22 @@ import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.filterNotNull
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.launch
|
||||
import java.io.File
|
||||
|
||||
class LocalProxyManager(private val context: Context) {
|
||||
|
||||
private val _proxyState = MutableStateFlow<ProxyState>(ProxyState.Idle)
|
||||
val proxyState: StateFlow<ProxyState> = _proxyState.asStateFlow()
|
||||
|
||||
private val _customKernelExists = MutableStateFlow(false)
|
||||
val customKernelExists: StateFlow<Boolean> = _customKernelExists.asStateFlow()
|
||||
|
||||
private val scope = CoroutineScope(Dispatchers.Main + SupervisorJob())
|
||||
private var resetJob: kotlinx.coroutines.Job? = null
|
||||
|
||||
init {
|
||||
_customKernelExists.value = File(context.filesDir, "custom_vkturn").exists()
|
||||
}
|
||||
|
||||
suspend fun observeProxyLifecycle() {
|
||||
ProxyServiceState.proxyFailed.collect {
|
||||
setErrorWithAutoReset("Прокси упал ${ProxyService.MAX_RESTARTS} раз — проверьте настройки")
|
||||
@@ -143,8 +133,21 @@ class LocalProxyManager(private val context: Context) {
|
||||
context.startService(intent)
|
||||
}
|
||||
|
||||
val result = withTimeoutOrNull(20_000L) {
|
||||
ProxyServiceState.startupResult.filterNotNull().first()
|
||||
// Умное ожидание стартапа. Watchdog внутри сервиса делает до MAX_RESTARTS
|
||||
// попыток с backoff до 30с — фиксированный таймаут (20с) обрывал UI ещё
|
||||
// на первой-второй ретрай-итерации. Теперь ждём пока:
|
||||
// • сервис не отдаст StartupResult (Success/Failed), ИЛИ
|
||||
// • сервис не остановится сам (watchdog исчерпал лимит → isRunning=false).
|
||||
// Верхняя граница в 5 минут — страховка от подвисшего сервиса.
|
||||
val result = withTimeoutOrNull(5 * 60_000L) {
|
||||
// Дождаться, что сервис фактически поднялся (onStartCommand).
|
||||
ProxyServiceState.isRunning.first { it }
|
||||
combine(
|
||||
ProxyServiceState.startupResult,
|
||||
ProxyServiceState.isRunning
|
||||
) { sr, running -> sr to running }
|
||||
.first { (sr, running) -> sr != null || !running }
|
||||
.first
|
||||
}
|
||||
|
||||
if (_proxyState.value is ProxyState.Error) return
|
||||
@@ -195,66 +198,8 @@ class LocalProxyManager(private val context: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun setCustomKernel(uri: Uri): String? = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val MAX_SIZE = 100L * 1024 * 1024 // 100 MB
|
||||
val ELF_MAGIC = byteArrayOf(0x7F, 0x45, 0x4C, 0x46) // \x7FELF
|
||||
val dest = File(context.filesDir, "custom_vkturn")
|
||||
val inputStream = context.contentResolver.openInputStream(uri)
|
||||
?: return@withContext "Не удалось открыть файл"
|
||||
|
||||
val error: String? = inputStream.use { input ->
|
||||
val header = ByteArray(4)
|
||||
if (input.read(header) < 4 || !header.contentEquals(ELF_MAGIC)) {
|
||||
return@use "Файл не является ELF-бинарником. Убедитесь, что загружаете правильное ядро"
|
||||
}
|
||||
|
||||
var totalBytes = header.size.toLong()
|
||||
dest.outputStream().use { output ->
|
||||
output.write(header)
|
||||
val buf = ByteArray(65_536)
|
||||
var n: Int
|
||||
while (input.read(buf).also { n = it } != -1) {
|
||||
totalBytes += n
|
||||
if (totalBytes > MAX_SIZE) {
|
||||
return@use "Файл слишком большой (максимум 100 МБ)"
|
||||
}
|
||||
output.write(buf, 0, n)
|
||||
}
|
||||
}
|
||||
|
||||
if (totalBytes <= 4L) return@use "Файл пустой"
|
||||
null
|
||||
}
|
||||
|
||||
if (error != null) {
|
||||
dest.delete()
|
||||
return@withContext error
|
||||
}
|
||||
|
||||
dest.setExecutable(true, false)
|
||||
try {
|
||||
Runtime.getRuntime().exec(arrayOf("chmod", "755", dest.absolutePath)).waitFor()
|
||||
} catch (_: Exception) {}
|
||||
withContext(Dispatchers.Main) { _customKernelExists.value = true }
|
||||
ProxyServiceState.addLog("Кастомное ядро установлено: ${dest.length() / 1024} КБ")
|
||||
null
|
||||
} catch (e: Exception) {
|
||||
ProxyServiceState.addLog("Ошибка установки ядра: ${e.message}")
|
||||
"Ошибка: ${e.message}"
|
||||
}
|
||||
}
|
||||
|
||||
fun clearCustomKernel() {
|
||||
File(context.filesDir, "custom_vkturn").delete()
|
||||
_customKernelExists.value = false
|
||||
ProxyServiceState.addLog("Кастомное ядро удалено, используется встроенное")
|
||||
}
|
||||
|
||||
fun clearState() {
|
||||
_proxyState.value = ProxyState.Idle
|
||||
File(context.filesDir, "custom_vkturn").delete()
|
||||
_customKernelExists.value = false
|
||||
}
|
||||
|
||||
fun destroy() {
|
||||
|
||||
@@ -1,83 +0,0 @@
|
||||
package com.freeturn.app.domain
|
||||
|
||||
object ServerScripts {
|
||||
|
||||
/** Удаляет из строки всё, кроме допустимых символов host:port (защита от shell-инъекций) */
|
||||
private fun shellSafe(value: String): String =
|
||||
value.replace(Regex("[^a-zA-Z0-9._:\\-]"), "")
|
||||
|
||||
val checkServerState: String = """
|
||||
if ls /opt/vk-turn/server-linux-* >/dev/null 2>&1; then echo "INSTALLED:YES"; else echo "INSTALLED:NO"; fi
|
||||
if ps aux | grep -v grep | grep -q "server-linux-"; then
|
||||
echo "RUNNING:YES"
|
||||
if ps aux | grep -v grep | grep "server-linux-" | grep -q "\-vless"; then echo "VLESS:YES"; else echo "VLESS:NO"; fi
|
||||
else
|
||||
echo "RUNNING:NO"
|
||||
fi
|
||||
""".trimIndent()
|
||||
|
||||
val installServer: String = """
|
||||
mkdir -p /opt/vk-turn || { echo "ERROR: не удалось создать /opt/vk-turn (нет прав)"; exit 1; }
|
||||
cd /opt/vk-turn || { echo "ERROR: не удалось войти в /opt/vk-turn"; exit 1; }
|
||||
if [ ! -w /opt/vk-turn ]; then echo "ERROR: /opt/vk-turn не доступен для записи"; exit 1; fi
|
||||
if [ -f /opt/vk-turn/proxy.pid ]; then kill -9 ${'$'}(cat /opt/vk-turn/proxy.pid) 2>/dev/null; rm -f /opt/vk-turn/proxy.pid; fi
|
||||
ARCH=${'$'}(uname -m)
|
||||
if [ "${'$'}ARCH" = "x86_64" ]; then BIN="server-linux-amd64"; else BIN="server-linux-arm64"; fi
|
||||
BASE_URL="https://github.com/cacggghp/vk-turn-proxy/releases/latest/download"
|
||||
BINPATH="/opt/vk-turn/${'$'}BIN"
|
||||
echo "Arch: ${'$'}ARCH | Binary: ${'$'}BIN"
|
||||
_dl() { URL=${'$'}1; OUT=${'$'}2
|
||||
if command -v curl >/dev/null 2>&1; then
|
||||
curl -sSL -o "${'$'}OUT" "${'$'}URL" 2>&1
|
||||
elif command -v wget >/dev/null 2>&1; then
|
||||
wget -q -O "${'$'}OUT" "${'$'}URL" 2>&1
|
||||
else
|
||||
echo "ERROR: curl и wget не найдены"; return 1
|
||||
fi
|
||||
}
|
||||
_dl "${'$'}BASE_URL/${'$'}BIN" "${'$'}BINPATH" || { echo "ERROR: скачивание бинарника не удалось"; exit 1; }
|
||||
SIZE=${'$'}(wc -c < "${'$'}BINPATH" 2>/dev/null || echo 0)
|
||||
echo "Size: ${'$'}SIZE bytes"
|
||||
if [ "${'$'}SIZE" -lt 100000 ]; then echo "ERROR: файл слишком мал (${'$'}SIZE байт)"; cat "${'$'}BINPATH" 2>/dev/null; exit 1; fi
|
||||
if _dl "${'$'}BASE_URL/checksums.txt" /opt/vk-turn/checksums.txt && [ -s /opt/vk-turn/checksums.txt ]; then
|
||||
EXPECTED=${'$'}(grep "${'$'}BIN" /opt/vk-turn/checksums.txt | awk '{print ${'$'}1}')
|
||||
if [ -n "${'$'}EXPECTED" ]; then
|
||||
ACTUAL=${'$'}(sha256sum "${'$'}BINPATH" | awk '{print ${'$'}1}')
|
||||
if [ "${'$'}EXPECTED" = "${'$'}ACTUAL" ]; then
|
||||
echo "SHA256: OK"
|
||||
else
|
||||
echo "ERROR: SHA256 не совпадает — ожидался ${'$'}EXPECTED, получен ${'$'}ACTUAL"
|
||||
rm -f "${'$'}BINPATH" /opt/vk-turn/checksums.txt; exit 1
|
||||
fi
|
||||
else
|
||||
echo "WARN: ${'$'}BIN не найден в checksums.txt, SHA256 пропущен"
|
||||
fi
|
||||
rm -f /opt/vk-turn/checksums.txt
|
||||
else
|
||||
echo "WARN: checksums.txt недоступен, SHA256 не проверен"
|
||||
fi
|
||||
chmod +x "${'$'}BINPATH" && echo "DONE"
|
||||
""".trimIndent()
|
||||
|
||||
fun startServer(listen: String, connect: String, vlessMode: Boolean = false): String {
|
||||
val safeListen = shellSafe(listen)
|
||||
val safeConnect = shellSafe(connect)
|
||||
val vlessFlag = if (vlessMode) " -vless" else ""
|
||||
return """
|
||||
cd /opt/vk-turn &&
|
||||
ARCH=${'$'}(uname -m);
|
||||
if [ "${'$'}ARCH" = "x86_64" ]; then BIN="server-linux-amd64"; else BIN="server-linux-arm64"; fi;
|
||||
nohup ./${'$'}BIN -listen '${safeListen}' -connect '${safeConnect}'${vlessFlag} > server.log 2>&1 &
|
||||
echo ${'$'}! > proxy.pid && echo "STARTED"
|
||||
""".trimIndent()
|
||||
}
|
||||
|
||||
val stopServer: String = """
|
||||
cd /opt/vk-turn &&
|
||||
if [ -f proxy.pid ]; then kill -9 ${'$'}(cat proxy.pid) 2>/dev/null; rm -f proxy.pid; fi;
|
||||
pkill -9 -f "[s]erver-linux-" 2>/dev/null;
|
||||
echo "STOPPED"
|
||||
""".trimIndent()
|
||||
|
||||
val fetchServerLogs: String = "tail -n 80 /opt/vk-turn/server.log 2>/dev/null || echo '(лог пуст)'"
|
||||
}
|
||||
@@ -1,7 +1,12 @@
|
||||
package com.freeturn.app.domain
|
||||
|
||||
import android.content.Context
|
||||
import com.freeturn.app.SSHManager
|
||||
import com.freeturn.app.data.SshConfig
|
||||
import com.freeturn.app.domain.server.CmdResult
|
||||
import com.freeturn.app.domain.server.ServerCommand
|
||||
import com.freeturn.app.domain.server.ServerControl
|
||||
import com.freeturn.app.domain.server.ServerOptions
|
||||
import com.freeturn.app.viewmodel.ServerState
|
||||
import com.freeturn.app.viewmodel.SshConnectionState
|
||||
import kotlinx.coroutines.delay
|
||||
@@ -12,7 +17,11 @@ import kotlinx.coroutines.flow.update
|
||||
import java.time.LocalTime
|
||||
import java.time.format.DateTimeFormatter
|
||||
|
||||
class SshRepository(private val sshManager: SSHManager = SSHManager()) {
|
||||
class SshRepository(
|
||||
context: Context,
|
||||
private val sshManager: SSHManager = SSHManager(),
|
||||
private val serverControl: ServerControl = ServerControl(context, sshManager)
|
||||
) {
|
||||
|
||||
var activeSshConfig: SshConfig? = null
|
||||
private set
|
||||
@@ -40,19 +49,34 @@ class SshRepository(private val sshManager: SSHManager = SSHManager()) {
|
||||
}
|
||||
}
|
||||
|
||||
private fun logCommand(target: String) {
|
||||
appendSshLog(" ssh $target")
|
||||
private fun logHeader(label: String, target: String) {
|
||||
appendSshLog("", "=== $label [${timestamp()}] ===", " ssh $target")
|
||||
}
|
||||
|
||||
private val SshConfig.fp get() = hostFingerprint.ifEmpty { null }
|
||||
private val SshConfig.key get() = if (authType == "SSH_KEY") sshKey else ""
|
||||
private fun logCmdResult(result: CmdResult) {
|
||||
result.logs.forEach { appendSshLog(it) }
|
||||
when (result) {
|
||||
is CmdResult.Ok ->
|
||||
result.kv.forEach { (k, v) -> appendSshLog(" $k=$v") }
|
||||
is CmdResult.Err ->
|
||||
appendSshLog("ERROR: ${result.message}")
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun runSshCommand(cfg: SshConfig, label: String, cmd: String): String {
|
||||
appendSshLog("", "=== $label [${timestamp()}] ===")
|
||||
logCommand("${cfg.username}@${cfg.ip}:${cfg.port}")
|
||||
private suspend fun runCmd(cfg: SshConfig, label: String, cmd: ServerCommand): CmdResult {
|
||||
logHeader(label, "${cfg.username}@${cfg.ip}:${cfg.port}")
|
||||
val result = serverControl.run(cfg, cmd)
|
||||
logCmdResult(result)
|
||||
return result
|
||||
}
|
||||
|
||||
/** Простая SSH-команда (используется только для healthcheck при подключении). */
|
||||
private suspend fun runEcho(cfg: SshConfig): String {
|
||||
logHeader("Подключение", "${cfg.username}@${cfg.ip}:${cfg.port}")
|
||||
val result = sshManager.executeSilentCommand(
|
||||
cfg.ip, cfg.port, cfg.username, cfg.password, cmd,
|
||||
knownFingerprint = cfg.fp, sshKey = cfg.key
|
||||
cfg.ip, cfg.port, cfg.username, cfg.password, "echo OK",
|
||||
knownFingerprint = cfg.hostFingerprint.ifEmpty { null },
|
||||
sshKey = if (cfg.authType == "SSH_KEY") cfg.sshKey else ""
|
||||
)
|
||||
result.lines().filter { it.isNotBlank() }.forEach { appendSshLog(it) }
|
||||
return result
|
||||
@@ -60,7 +84,7 @@ class SshRepository(private val sshManager: SSHManager = SSHManager()) {
|
||||
|
||||
suspend fun connectSsh(config: SshConfig): Pair<Boolean, String?> {
|
||||
_sshState.value = SshConnectionState.Connecting
|
||||
val result = runSshCommand(config, "Подключение", "echo OK")
|
||||
val result = runEcho(config)
|
||||
return if (result.trim() == "OK") {
|
||||
val fp = sshManager.lastSeenFingerprint ?: config.hostFingerprint
|
||||
activeSshConfig = config.copy(hostFingerprint = fp)
|
||||
@@ -87,47 +111,92 @@ class SshRepository(private val sshManager: SSHManager = SSHManager()) {
|
||||
}
|
||||
_serverState.value = ServerState.Checking
|
||||
|
||||
val result = runSshCommand(cfg, "Проверка состояния", ServerScripts.checkServerState)
|
||||
_serverState.value = if (result.startsWith("ERROR")) {
|
||||
ServerState.Error(result.removePrefix("ERROR: "))
|
||||
} else {
|
||||
val running = result.contains("RUNNING:YES")
|
||||
val vlessMode = if (running) result.contains("VLESS:YES") else null
|
||||
val known = ServerState.Known(
|
||||
installed = result.contains("INSTALLED:YES"),
|
||||
running = running,
|
||||
vlessMode = vlessMode
|
||||
)
|
||||
known
|
||||
when (val r = runCmd(cfg, "Проверка состояния", ServerCommand.Probe)) {
|
||||
is CmdResult.Err -> _serverState.value = ServerState.Error(r.message)
|
||||
is CmdResult.Ok -> {
|
||||
val running = r.kv["RUNNING"] == "yes"
|
||||
val installed = r.kv["INSTALLED"] == "yes"
|
||||
val vlessMode = if (running) r.kv["VLESS"] == "yes" else null
|
||||
val vlessBond = if (running) r.kv["VLESS_BOND"] == "yes" else null
|
||||
val wrap = if (running) r.kv["WRAP"] == "yes" else null
|
||||
val version = r.kv["VERSION"]
|
||||
_serverState.value = ServerState.Known(
|
||||
installed = installed,
|
||||
running = running,
|
||||
vlessMode = vlessMode,
|
||||
vlessBond = vlessBond,
|
||||
wrap = wrap,
|
||||
version = version
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun installServer() {
|
||||
val cfg = activeSshConfig ?: return
|
||||
if (cfg.ip.isEmpty()) return
|
||||
/**
|
||||
* Идемпотентная установка: скрипт сам решает, скачивать или нет (по sha256).
|
||||
* После downloaded автоматически генерим wrap-ключ — он понадобится при
|
||||
* первом start с включённым WRAP. Возвращаемое значение — true при успехе.
|
||||
*/
|
||||
suspend fun installServer(): InstallOutcome {
|
||||
val cfg = activeSshConfig ?: return InstallOutcome.Failed("not connected")
|
||||
if (cfg.ip.isEmpty()) return InstallOutcome.Failed("no SSH config")
|
||||
_serverState.value = ServerState.Working("Установка vk-turn-proxy...")
|
||||
|
||||
val result = runSshCommand(cfg, "Установка", ServerScripts.installServer)
|
||||
if (!result.contains("DONE")) {
|
||||
val errorMsg = result.lines()
|
||||
.filter { it.isNotBlank() }
|
||||
.takeLast(4)
|
||||
.joinToString("\n")
|
||||
.ifBlank { "Нет вывода от команды — см. SSH-лог" }
|
||||
_serverState.value = ServerState.Error(errorMsg)
|
||||
} else {
|
||||
delay(500)
|
||||
checkServerState(cfg)
|
||||
val result = runCmd(cfg, "Установка", ServerCommand.Install)
|
||||
return when (result) {
|
||||
is CmdResult.Err -> {
|
||||
_serverState.value = ServerState.Error(result.message)
|
||||
InstallOutcome.Failed(result.message)
|
||||
}
|
||||
is CmdResult.Ok -> {
|
||||
val stage = result.kv["STAGE"] ?: "ok"
|
||||
val version = result.kv["VERSION"]
|
||||
val needsRestart = result.kv["NEEDS_RESTART"] == "yes"
|
||||
// Если при update сервер был запущен, скрипт перезаписал бинарь,
|
||||
// но процесс всё ещё крутит старую версию. Перезапускаем сами,
|
||||
// иначе пользователь думает что обновился, а live-running старый.
|
||||
if (needsRestart) {
|
||||
appendSshLog(" NEEDS_RESTART=yes → авто-рестарт сервера")
|
||||
runCmd(cfg, "Авто-остановка перед рестартом", ServerCommand.Stop)
|
||||
// start вызвать без аргументов нельзя — нужны listen/connect.
|
||||
// Их знает только VM. Сигнализируем через отдельный outcome,
|
||||
// VM решает, как стартовать (с актуальными prefs).
|
||||
}
|
||||
delay(300)
|
||||
checkServerState(cfg)
|
||||
InstallOutcome.Success(stage = stage, version = version, needsRestart = needsRestart)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun startServer(listen: String, connect: String, vlessMode: Boolean = false): Boolean {
|
||||
suspend fun startServer(
|
||||
listen: String,
|
||||
connect: String,
|
||||
vlessMode: Boolean = false,
|
||||
vlessBond: Boolean = false,
|
||||
wrapKey: String = ""
|
||||
): Boolean {
|
||||
val cfg = activeSshConfig ?: return false
|
||||
if (cfg.ip.isEmpty()) return false
|
||||
|
||||
_serverState.value = ServerState.Working("Запуск сервера...")
|
||||
runSshCommand(cfg, "Запуск", ServerScripts.startServer(listen, connect, vlessMode))
|
||||
delay(2000)
|
||||
val result = runCmd(
|
||||
cfg, "Запуск",
|
||||
ServerCommand.Start(
|
||||
ServerOptions(
|
||||
listen = listen,
|
||||
connect = connect,
|
||||
vless = vlessMode,
|
||||
vlessBond = vlessBond && vlessMode,
|
||||
wrapKey = wrapKey
|
||||
)
|
||||
)
|
||||
)
|
||||
if (result is CmdResult.Err) {
|
||||
_serverState.value = ServerState.Error(result.message)
|
||||
return false
|
||||
}
|
||||
delay(1500)
|
||||
checkServerState(cfg)
|
||||
return true
|
||||
}
|
||||
@@ -137,8 +206,12 @@ class SshRepository(private val sshManager: SSHManager = SSHManager()) {
|
||||
if (cfg.ip.isEmpty()) return
|
||||
_serverState.value = ServerState.Working("Остановка сервера...")
|
||||
|
||||
runSshCommand(cfg, "Остановка", ServerScripts.stopServer)
|
||||
delay(2000)
|
||||
val result = runCmd(cfg, "Остановка", ServerCommand.Stop)
|
||||
if (result is CmdResult.Err) {
|
||||
_serverState.value = ServerState.Error(result.message)
|
||||
return
|
||||
}
|
||||
delay(1000)
|
||||
checkServerState(cfg)
|
||||
}
|
||||
|
||||
@@ -146,8 +219,23 @@ class SshRepository(private val sshManager: SSHManager = SSHManager()) {
|
||||
val cfg = activeSshConfig ?: return
|
||||
if (cfg.ip.isEmpty()) return
|
||||
_serverLogs.value = "…"
|
||||
val out = runSshCommand(cfg, "server.log", ServerScripts.fetchServerLogs)
|
||||
_serverLogs.value = out.trim().ifEmpty { "(лог пуст)" }
|
||||
when (val r = runCmd(cfg, "server.log", ServerCommand.FetchLogs())) {
|
||||
is CmdResult.Err -> _serverLogs.value = "ERROR: ${r.message}"
|
||||
is CmdResult.Ok ->
|
||||
_serverLogs.value = r.logs.joinToString("\n").ifEmpty { "(лог пуст)" }
|
||||
}
|
||||
}
|
||||
|
||||
/** Просит сервер сгенерировать новый wrap-key. Возвращает hex или null. */
|
||||
suspend fun generateWrapKey(): String? {
|
||||
val cfg = activeSshConfig ?: return null
|
||||
if (cfg.ip.isEmpty()) return null
|
||||
return when (val r = runCmd(cfg, "Генерация wrap-key", ServerCommand.GenWrapKey)) {
|
||||
is CmdResult.Err -> null
|
||||
is CmdResult.Ok -> r.kv["WRAPKEY"]?.takeIf {
|
||||
it.matches(Regex("^[0-9a-fA-F]{64}$"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun updateServerState(state: ServerState) {
|
||||
@@ -160,3 +248,17 @@ class SshRepository(private val sshManager: SSHManager = SSHManager()) {
|
||||
_sshLog.value = emptyList()
|
||||
}
|
||||
}
|
||||
|
||||
sealed class InstallOutcome {
|
||||
/**
|
||||
* stage: cached | downloaded; version — только если ядро вернуло.
|
||||
* needsRestart — true, если бинарь был переустановлен поверх работающего
|
||||
* процесса; перед использованием новой версии нужен start.
|
||||
*/
|
||||
data class Success(
|
||||
val stage: String,
|
||||
val version: String?,
|
||||
val needsRestart: Boolean = false
|
||||
) : InstallOutcome()
|
||||
data class Failed(val message: String) : InstallOutcome()
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.freeturn.app.domain.server
|
||||
|
||||
/**
|
||||
* Команды управления сервером, которые транслируются в подкоманды
|
||||
* `vk-turn-control.sh`. Скрипт стримится через SSH stdin (см. [ServerControl]).
|
||||
*/
|
||||
sealed class ServerCommand {
|
||||
data object Probe : ServerCommand()
|
||||
data object Install : ServerCommand()
|
||||
data class Start(val opts: ServerOptions) : ServerCommand()
|
||||
data object Stop : ServerCommand()
|
||||
data object GenWrapKey : ServerCommand()
|
||||
data class FetchLogs(val lines: Int = 80) : ServerCommand()
|
||||
|
||||
fun toArgv(): List<String> = when (this) {
|
||||
is Probe -> listOf("probe")
|
||||
is Install -> listOf("install")
|
||||
is Start -> buildList {
|
||||
add("start")
|
||||
add("--listen=${opts.listen}")
|
||||
add("--connect=${opts.connect}")
|
||||
if (opts.vless) add("--vless")
|
||||
if (opts.vlessBond) add("--vless-bond")
|
||||
if (opts.wrapKey.isNotBlank()) add("--wrap-key=${opts.wrapKey}")
|
||||
}
|
||||
is Stop -> listOf("stop")
|
||||
is GenWrapKey -> listOf("gen-wrap-key")
|
||||
is FetchLogs -> listOf("logs", "--tail=$lines")
|
||||
}
|
||||
}
|
||||
|
||||
data class ServerOptions(
|
||||
val listen: String,
|
||||
val connect: String,
|
||||
val vless: Boolean = false,
|
||||
val vlessBond: Boolean = false,
|
||||
/** 64-hex wrap-ключ. Пустая строка → передача без -wrap. */
|
||||
val wrapKey: String = ""
|
||||
)
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.freeturn.app.domain.server
|
||||
|
||||
import android.content.Context
|
||||
import com.freeturn.app.SSHManager
|
||||
import com.freeturn.app.data.SshConfig
|
||||
|
||||
/**
|
||||
* Запускает [ServerCommand] на удалённом хосте, стримя `vk-turn-control.sh`
|
||||
* (asset) через SSH stdin. Скрипт грузится один раз, дальше он будет
|
||||
* передаваться в bash при каждом вызове — это даёт простоту (нет sync-проблемы
|
||||
* с серверной копией) и идемпотентность (скрипт сам решает install/cached).
|
||||
*/
|
||||
class ServerControl(
|
||||
context: Context,
|
||||
private val ssh: SSHManager
|
||||
) {
|
||||
private val appContext = context.applicationContext
|
||||
|
||||
private val script: String by lazy {
|
||||
appContext.assets.open(SCRIPT_ASSET).bufferedReader(Charsets.UTF_8)
|
||||
.use { it.readText() }
|
||||
}
|
||||
|
||||
/** Сырая команда, которую запускаем на сервере (без скрипта — он идёт через stdin). */
|
||||
private fun remoteCmd(argv: List<String>): String {
|
||||
val quoted = argv.joinToString(" ") { shellQuote(it) }
|
||||
return "bash -s -- $quoted"
|
||||
}
|
||||
|
||||
suspend fun run(cfg: SshConfig, cmd: ServerCommand): CmdResult {
|
||||
if (cfg.ip.isBlank()) return CmdResult.Err("no SSH config", emptyList())
|
||||
val output = ssh.executeWithStdin(
|
||||
ip = cfg.ip,
|
||||
port = cfg.port,
|
||||
user = cfg.username,
|
||||
pass = cfg.password,
|
||||
command = remoteCmd(cmd.toArgv()),
|
||||
stdin = script,
|
||||
knownFingerprint = cfg.hostFingerprint.ifEmpty { null },
|
||||
sshKey = if (cfg.authType == "SSH_KEY") cfg.sshKey else ""
|
||||
)
|
||||
return ServerOutputParser.parse(output)
|
||||
}
|
||||
|
||||
/**
|
||||
* Заворачивает значение в одинарные кавычки для 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 = "vk-turn-control.sh"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.freeturn.app.domain.server
|
||||
|
||||
/**
|
||||
* Результат выполнения серверной команды. Парсится из stdout `vk-turn-control.sh`.
|
||||
*
|
||||
* Контракт скрипта:
|
||||
* - Каждая строка вида `KEY=VALUE` идёт в [Ok.kv].
|
||||
* - Префикс `LOG: ` — свободный текст, попадает в [Ok.logs] / [Err.logs] без префикса.
|
||||
* - Прочие непустые строки трактуются как лог.
|
||||
* - Финальная строка обязана быть `RESULT=ok` или `RESULT=err`. При `err`
|
||||
* ожидается `ERR=<message>` ранее в выводе.
|
||||
*
|
||||
* Если на верхнем уровне `SSHManager` вернул `ERROR: ...` (сетевая/MITM ошибка) —
|
||||
* это перехватывается до парсера: [parse] также трактует такой случай как [Err].
|
||||
*/
|
||||
sealed class CmdResult {
|
||||
abstract val logs: List<String>
|
||||
data class Ok(val kv: Map<String, String>, override val logs: List<String>) : CmdResult()
|
||||
data class Err(val message: String, override val logs: List<String>) : CmdResult()
|
||||
}
|
||||
|
||||
object ServerOutputParser {
|
||||
fun parse(raw: String): CmdResult {
|
||||
// SSHManager сигнализирует транспортные ошибки префиксом "ERROR: ".
|
||||
// Не пытаемся разбирать как k=v — отдаём наверх как есть.
|
||||
if (raw.startsWith("ERROR:")) {
|
||||
return CmdResult.Err(raw.removePrefix("ERROR:").trim(), emptyList())
|
||||
}
|
||||
val kv = LinkedHashMap<String, String>()
|
||||
val logs = mutableListOf<String>()
|
||||
raw.lines().forEach { rawLine ->
|
||||
val line = rawLine.trimEnd('\r')
|
||||
when {
|
||||
line.isEmpty() -> { /* skip */ }
|
||||
line.startsWith("LOG: ") -> logs += line.removePrefix("LOG: ")
|
||||
// k=v: ключ — только [A-Z0-9_], всё остальное считаем логом.
|
||||
line.contains('=') && line.substringBefore('=').matches(Regex("[A-Z][A-Z0-9_]*")) -> {
|
||||
val k = line.substringBefore('=')
|
||||
val v = line.substringAfter('=')
|
||||
kv[k] = v
|
||||
}
|
||||
else -> logs += line
|
||||
}
|
||||
}
|
||||
return when (kv["RESULT"]) {
|
||||
"ok" -> CmdResult.Ok(kv, logs)
|
||||
"err" -> CmdResult.Err(kv["ERR"] ?: "unknown error", logs)
|
||||
else -> CmdResult.Err(
|
||||
"no RESULT marker (output truncated?)",
|
||||
logs
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,33 +1,33 @@
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
@file:OptIn(
|
||||
androidx.compose.material3.ExperimentalMaterial3Api::class,
|
||||
androidx.compose.material3.ExperimentalMaterial3ExpressiveApi::class
|
||||
)
|
||||
|
||||
package com.freeturn.app.ui.screens
|
||||
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.WindowInsets
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.imePadding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.FilledTonalButton
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.DividerDefaults
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.SegmentedButton
|
||||
import androidx.compose.material3.SegmentedButtonDefaults
|
||||
@@ -47,15 +47,14 @@ import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.freeturn.app.R
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.freeturn.app.data.ClientConfig
|
||||
import com.freeturn.app.data.DnsMode
|
||||
import com.freeturn.app.ui.HapticUtil
|
||||
import com.freeturn.app.viewmodel.MainViewModel
|
||||
import com.freeturn.app.viewmodel.SshConnectionState
|
||||
import kotlin.math.roundToInt
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
@@ -72,28 +71,35 @@ fun ClientSetupScreen(
|
||||
) {
|
||||
val saved by viewModel.clientConfig.collectAsStateWithLifecycle()
|
||||
val sshConfig by viewModel.sshConfig.collectAsStateWithLifecycle()
|
||||
val sshState by viewModel.sshState.collectAsStateWithLifecycle()
|
||||
val serverState by viewModel.serverState.collectAsStateWithLifecycle()
|
||||
val serverOpts by viewModel.serverOpts.collectAsStateWithLifecycle()
|
||||
val proxyListen by viewModel.proxyListen.collectAsStateWithLifecycle()
|
||||
val customKernelExists by viewModel.customKernelExists.collectAsStateWithLifecycle()
|
||||
val kernelError by viewModel.kernelError.collectAsStateWithLifecycle()
|
||||
val privacyMode by viewModel.privacyMode.collectAsStateWithLifecycle()
|
||||
val isRegeneratingWrapKey by viewModel.isRegeneratingWrapKey.collectAsStateWithLifecycle()
|
||||
|
||||
val isSshConnected = sshState is SshConnectionState.Connected
|
||||
val serverKnown = serverState as? com.freeturn.app.viewmodel.ServerState.Known
|
||||
// Эффективное значение sync-флага: если сервер запущен — реальное состояние
|
||||
// из probe; иначе — последнее сохранённое (frozen).
|
||||
val effectiveVlessMode = serverKnown?.vlessMode ?: saved.vlessMode
|
||||
val effectiveVlessBond = serverKnown?.vlessBond ?: serverOpts.vlessBond
|
||||
val effectiveWrap = serverKnown?.wrap ?: serverOpts.wrapEnabled
|
||||
|
||||
val context = LocalContext.current
|
||||
|
||||
val kernelPickerLauncher = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.OpenDocument()
|
||||
) { uri -> uri?.let { viewModel.setCustomKernel(it) } }
|
||||
|
||||
var serverAddress by rememberSaveable(saved.serverAddress) { mutableStateOf(saved.serverAddress) }
|
||||
var vkLink by rememberSaveable(saved.vkLink) { mutableStateOf(saved.vkLink) }
|
||||
var threads by rememberSaveable(saved.threads) { mutableFloatStateOf(saved.threads.toFloat()) }
|
||||
var allocsPerStream by rememberSaveable(saved.allocsPerStream) { mutableIntStateOf(saved.allocsPerStream) }
|
||||
var streamsPerCred by rememberSaveable(saved.streamsPerCred) { mutableFloatStateOf(saved.streamsPerCred.toFloat()) }
|
||||
var useUdp by rememberSaveable(saved.useUdp) { mutableStateOf(saved.useUdp) }
|
||||
var manualCaptcha by rememberSaveable(saved.manualCaptcha) { mutableStateOf(saved.manualCaptcha) }
|
||||
var useCarrierDns by rememberSaveable(saved.useCarrierDns) { mutableStateOf(saved.useCarrierDns) }
|
||||
var localPort by rememberSaveable(saved.localPort) { mutableStateOf(saved.localPort) }
|
||||
var dnsMode by rememberSaveable(saved.dnsMode) { mutableStateOf(saved.dnsMode) }
|
||||
var forcePort443 by rememberSaveable(saved.forcePort443) { mutableStateOf(saved.forcePort443) }
|
||||
var captchaSolver by rememberSaveable(saved.captchaSolver) { mutableStateOf(saved.captchaSolver) }
|
||||
var debugMode by rememberSaveable(saved.debugMode) { mutableStateOf(saved.debugMode) }
|
||||
var lastSliderInt by rememberSaveable { mutableIntStateOf(saved.threads) }
|
||||
var lastStreamsInt by rememberSaveable { mutableIntStateOf(saved.streamsPerCred) }
|
||||
|
||||
// Автозаполнение адреса сервера из SSH-конфига если поле пустое
|
||||
LaunchedEffect(sshConfig.ip, proxyListen) {
|
||||
@@ -105,21 +111,21 @@ fun ClientSetupScreen(
|
||||
|
||||
// Авто-сохранение с дебаунсом 600 мс на каждое изменение поля.
|
||||
// vlessMode исключён — сохраняется через setVlessMode с автоперезапуском сервера.
|
||||
LaunchedEffect(serverAddress, vkLink, threads, allocsPerStream, useUdp, manualCaptcha, localPort, dnsMode, forcePort443, debugMode) {
|
||||
LaunchedEffect(serverAddress, vkLink, threads, streamsPerCred, useUdp, manualCaptcha, useCarrierDns, localPort, captchaSolver, debugMode) {
|
||||
delay(600)
|
||||
viewModel.saveClientConfig(
|
||||
ClientConfig(
|
||||
serverAddress = serverAddress.trim(),
|
||||
vkLink = vkLink.trim(),
|
||||
threads = threads.roundToInt(),
|
||||
allocsPerStream = allocsPerStream,
|
||||
streamsPerCred = streamsPerCred.roundToInt(),
|
||||
useUdp = useUdp,
|
||||
manualCaptcha = manualCaptcha,
|
||||
localPort = localPort.trim(),
|
||||
vlessMode = saved.vlessMode,
|
||||
dnsMode = dnsMode,
|
||||
forcePort443 = forcePort443,
|
||||
debugMode = debugMode
|
||||
captchaSolver = captchaSolver,
|
||||
debugMode = debugMode,
|
||||
useCarrierDns = useCarrierDns
|
||||
)
|
||||
)
|
||||
}
|
||||
@@ -220,58 +226,31 @@ fun ClientSetupScreen(
|
||||
|
||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text(
|
||||
stringResource(R.string.allocs_per_stream_label),
|
||||
stringResource(R.string.streams_per_cred_format, streamsPerCred.roundToInt()),
|
||||
style = MaterialTheme.typography.bodyMedium
|
||||
)
|
||||
Text(
|
||||
stringResource(R.string.allocs_per_stream_recommendation),
|
||||
stringResource(R.string.streams_per_cred_recommendation),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
val allocsOptions = listOf(1, 2, 3)
|
||||
SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) {
|
||||
allocsOptions.forEachIndexed { idx, value ->
|
||||
SegmentedButton(
|
||||
selected = allocsPerStream == value,
|
||||
onClick = {
|
||||
HapticUtil.perform(context, HapticUtil.Pattern.TOGGLE_ON)
|
||||
allocsPerStream = value
|
||||
},
|
||||
shape = SegmentedButtonDefaults.itemShape(index = idx, count = allocsOptions.size)
|
||||
) { Text(value.toString()) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Column {
|
||||
Text(stringResource(R.string.dns_mode_title), style = MaterialTheme.typography.bodyMedium)
|
||||
Text(
|
||||
stringResource(R.string.dns_mode_desc),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
val dnsOptions = listOf(
|
||||
DnsMode.AUTO to stringResource(R.string.dns_mode_auto),
|
||||
DnsMode.UDP to stringResource(R.string.dns_mode_udp),
|
||||
DnsMode.DOH to stringResource(R.string.dns_mode_doh)
|
||||
Slider(
|
||||
value = streamsPerCred,
|
||||
onValueChange = {
|
||||
val v = it.roundToInt()
|
||||
if (v != lastStreamsInt) {
|
||||
HapticUtil.perform(context, HapticUtil.Pattern.SELECTION)
|
||||
lastStreamsInt = v
|
||||
}
|
||||
streamsPerCred = it
|
||||
},
|
||||
valueRange = 1f..50f,
|
||||
steps = 0,
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
)
|
||||
SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) {
|
||||
dnsOptions.forEachIndexed { idx, (value, label) ->
|
||||
SegmentedButton(
|
||||
selected = dnsMode == value,
|
||||
onClick = {
|
||||
HapticUtil.perform(context, HapticUtil.Pattern.TOGGLE_ON)
|
||||
dnsMode = value
|
||||
},
|
||||
shape = SegmentedButtonDefaults.itemShape(index = idx, count = dnsOptions.size)
|
||||
) { Text(label) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!saved.vlessMode) {
|
||||
if (!effectiveVlessMode) {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Column {
|
||||
Text(stringResource(R.string.transport_protocol), style = MaterialTheme.typography.bodyMedium)
|
||||
@@ -300,18 +279,31 @@ fun ClientSetupScreen(
|
||||
) { Text(stringResource(R.string.udp)) }
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
SwitchRow(
|
||||
label = stringResource(R.string.vless_mode),
|
||||
description = stringResource(R.string.vless_mode_desc),
|
||||
checked = saved.vlessMode,
|
||||
onCheckedChange = {
|
||||
HapticUtil.perform(context, if (it) HapticUtil.Pattern.TOGGLE_ON else HapticUtil.Pattern.TOGGLE_OFF)
|
||||
viewModel.setVlessMode(it)
|
||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Column {
|
||||
Text(stringResource(R.string.captcha_solver_title), style = MaterialTheme.typography.bodyMedium)
|
||||
Text(
|
||||
stringResource(R.string.captcha_solver_desc),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
)
|
||||
val solverOptions = listOf("v2", "v1")
|
||||
SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) {
|
||||
solverOptions.forEachIndexed { idx, value ->
|
||||
SegmentedButton(
|
||||
selected = captchaSolver == value,
|
||||
onClick = {
|
||||
HapticUtil.perform(context, HapticUtil.Pattern.TOGGLE_ON)
|
||||
captchaSolver = value
|
||||
},
|
||||
shape = SegmentedButtonDefaults.itemShape(index = idx, count = solverOptions.size)
|
||||
) { Text(value) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SwitchRow(
|
||||
label = stringResource(R.string.manual_captcha),
|
||||
@@ -324,12 +316,12 @@ fun ClientSetupScreen(
|
||||
)
|
||||
|
||||
SwitchRow(
|
||||
label = stringResource(R.string.force_port_443),
|
||||
description = stringResource(R.string.force_port_443_desc),
|
||||
checked = forcePort443,
|
||||
label = stringResource(R.string.use_carrier_dns),
|
||||
description = stringResource(R.string.use_carrier_dns_desc),
|
||||
checked = useCarrierDns,
|
||||
onCheckedChange = {
|
||||
HapticUtil.perform(context, if (it) HapticUtil.Pattern.TOGGLE_ON else HapticUtil.Pattern.TOGGLE_OFF)
|
||||
forcePort443 = it
|
||||
useCarrierDns = it
|
||||
}
|
||||
)
|
||||
|
||||
@@ -345,94 +337,109 @@ fun ClientSetupScreen(
|
||||
|
||||
HorizontalDivider(Modifier, DividerDefaults.Thickness, DividerDefaults.color)
|
||||
|
||||
// Ядро
|
||||
Text(stringResource(R.string.core_title), style = MaterialTheme.typography.titleMedium)
|
||||
Text(
|
||||
stringResource(R.string.server_sync_section),
|
||||
style = MaterialTheme.typography.titleMedium
|
||||
)
|
||||
|
||||
Card(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = if (customKernelExists)
|
||||
MaterialTheme.colorScheme.secondaryContainer
|
||||
else
|
||||
MaterialTheme.colorScheme.surfaceVariant
|
||||
)
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 14.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceBetween
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
modifier = Modifier.weight(1f)
|
||||
) {
|
||||
Icon(
|
||||
painter = painterResource(
|
||||
if (customKernelExists) R.drawable.check_circle_24px
|
||||
else R.drawable.memory_24px
|
||||
),
|
||||
contentDescription = null,
|
||||
tint = if (customKernelExists)
|
||||
MaterialTheme.colorScheme.primary
|
||||
else
|
||||
MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||
Text(
|
||||
if (customKernelExists) stringResource(R.string.custom_core)
|
||||
else stringResource(R.string.builtin_core),
|
||||
style = MaterialTheme.typography.bodyMedium
|
||||
)
|
||||
Text(
|
||||
if (customKernelExists) stringResource(R.string.loaded_from_memory)
|
||||
else stringResource(R.string.from_apk),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
}
|
||||
if (customKernelExists) {
|
||||
IconButton(onClick = {
|
||||
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
|
||||
viewModel.clearCustomKernel()
|
||||
}) {
|
||||
Icon(
|
||||
painter = painterResource(R.drawable.delete_24px),
|
||||
contentDescription = stringResource(R.string.reset),
|
||||
tint = MaterialTheme.colorScheme.error
|
||||
)
|
||||
}
|
||||
} else {
|
||||
FilledTonalButton(onClick = {
|
||||
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
|
||||
viewModel.clearKernelError()
|
||||
kernelPickerLauncher.launch(arrayOf("*/*"))
|
||||
}) {
|
||||
Text(stringResource(R.string.btn_load))
|
||||
}
|
||||
}
|
||||
// VLESS-режим — sync с сервером (-vless на обеих сторонах).
|
||||
// Без SSH-подключения замораживается на последнем известном значении.
|
||||
SwitchRow(
|
||||
label = stringResource(R.string.vless_mode),
|
||||
description = if (isSshConnected)
|
||||
stringResource(R.string.vless_mode_desc)
|
||||
else
|
||||
stringResource(R.string.locked_disconnect_hint),
|
||||
checked = effectiveVlessMode,
|
||||
enabled = isSshConnected,
|
||||
onCheckedChange = {
|
||||
HapticUtil.perform(context, if (it) HapticUtil.Pattern.TOGGLE_ON else HapticUtil.Pattern.TOGGLE_OFF)
|
||||
viewModel.setVlessMode(it)
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
if (kernelError != null) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
Icon(
|
||||
painter = painterResource(R.drawable.error_24px),
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.error,
|
||||
modifier = Modifier.size(16.dp)
|
||||
)
|
||||
Text(
|
||||
kernelError!!,
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.error
|
||||
)
|
||||
SwitchRow(
|
||||
label = stringResource(R.string.client_vless_bond),
|
||||
description = if (isSshConnected)
|
||||
stringResource(R.string.client_vless_bond_desc)
|
||||
else
|
||||
stringResource(R.string.locked_disconnect_hint),
|
||||
checked = effectiveVlessBond,
|
||||
enabled = isSshConnected && effectiveVlessMode,
|
||||
onCheckedChange = {
|
||||
HapticUtil.perform(context, if (it) HapticUtil.Pattern.TOGGLE_ON else HapticUtil.Pattern.TOGGLE_OFF)
|
||||
viewModel.setServerVlessBond(it)
|
||||
}
|
||||
)
|
||||
|
||||
SwitchRow(
|
||||
label = stringResource(R.string.client_wrap_enabled),
|
||||
description = if (isSshConnected)
|
||||
stringResource(R.string.client_wrap_desc)
|
||||
else
|
||||
stringResource(R.string.locked_disconnect_hint),
|
||||
checked = effectiveWrap,
|
||||
enabled = isSshConnected,
|
||||
onCheckedChange = {
|
||||
HapticUtil.perform(context, if (it) HapticUtil.Pattern.TOGGLE_ON else HapticUtil.Pattern.TOGGLE_OFF)
|
||||
viewModel.setServerWrapEnabled(it)
|
||||
}
|
||||
)
|
||||
|
||||
if (effectiveWrap) {
|
||||
OutlinedTextField(
|
||||
value = serverOpts.wrapKey.redact(privacyMode),
|
||||
onValueChange = { /* read-only */ },
|
||||
label = { Text(stringResource(R.string.server_wrap_key_label)) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
readOnly = true,
|
||||
singleLine = true,
|
||||
trailingIcon = {
|
||||
if (serverOpts.wrapKey.isNotBlank() && !privacyMode) {
|
||||
IconButton(onClick = {
|
||||
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
|
||||
val cm = context.getSystemService(android.content.ClipboardManager::class.java)
|
||||
cm?.setPrimaryClip(
|
||||
android.content.ClipData.newPlainText("wrap-key", serverOpts.wrapKey)
|
||||
)
|
||||
}) {
|
||||
Icon(
|
||||
painter = painterResource(R.drawable.content_copy_24px),
|
||||
contentDescription = stringResource(R.string.copy)
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
supportingText = {
|
||||
if (serverOpts.wrapKey.isBlank()) {
|
||||
Text(
|
||||
stringResource(R.string.wrap_key_empty_hint),
|
||||
color = MaterialTheme.colorScheme.error
|
||||
)
|
||||
}
|
||||
}
|
||||
)
|
||||
if (isSshConnected) {
|
||||
Box(modifier = Modifier.fillMaxWidth()) {
|
||||
androidx.compose.material3.TextButton(
|
||||
onClick = {
|
||||
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
|
||||
viewModel.regenerateWrapKey()
|
||||
},
|
||||
enabled = !isRegeneratingWrapKey,
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
if (isRegeneratingWrapKey) {
|
||||
androidx.compose.material3.CircularWavyProgressIndicator(
|
||||
modifier = Modifier.size(20.dp)
|
||||
)
|
||||
Spacer(Modifier.size(8.dp))
|
||||
Text(stringResource(R.string.server_wrap_regen_in_progress))
|
||||
} else {
|
||||
Text(stringResource(R.string.server_wrap_regen))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -460,6 +467,7 @@ private fun SwitchRow(
|
||||
label: String,
|
||||
description: String,
|
||||
checked: Boolean,
|
||||
enabled: Boolean = true,
|
||||
onCheckedChange: (Boolean) -> Unit
|
||||
) {
|
||||
Row(
|
||||
@@ -468,13 +476,18 @@ private fun SwitchRow(
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(label, style = MaterialTheme.typography.bodyMedium)
|
||||
Text(
|
||||
label,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = if (enabled) MaterialTheme.colorScheme.onSurface
|
||||
else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.5f)
|
||||
)
|
||||
Text(
|
||||
description,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
Switch(checked = checked, onCheckedChange = onCheckedChange)
|
||||
Switch(checked = checked, enabled = enabled, onCheckedChange = onCheckedChange)
|
||||
}
|
||||
}
|
||||
@@ -254,7 +254,7 @@ fun HomeScreen(
|
||||
Spacer(Modifier.height(12.dp))
|
||||
ConfigRow(stringResource(R.string.server), clientConfig.serverAddress.redact(privacyMode))
|
||||
ConfigRow(stringResource(R.string.threads), "${clientConfig.threads}")
|
||||
ConfigRow(stringResource(R.string.allocs_per_stream_label), "${clientConfig.allocsPerStream}")
|
||||
ConfigRow(stringResource(R.string.streams_per_cred_label), "${clientConfig.streamsPerCred}")
|
||||
ConfigRow(
|
||||
stringResource(R.string.transport_protocol),
|
||||
if (clientConfig.vlessMode) "VLESS"
|
||||
|
||||
@@ -78,6 +78,7 @@ fun ServerManagementScreen(
|
||||
val savedConnect by viewModel.proxyConnect.collectAsStateWithLifecycle()
|
||||
val sshLog by viewModel.sshLog.collectAsStateWithLifecycle()
|
||||
val privacyMode by viewModel.privacyMode.collectAsStateWithLifecycle()
|
||||
val installStage by viewModel.serverInstallStage.collectAsStateWithLifecycle()
|
||||
|
||||
var proxyListenPort by rememberSaveable(savedListen) { mutableStateOf(savedListen.substringAfterLast(":", "56000")) }
|
||||
var proxyConnect by rememberSaveable(savedConnect) { mutableStateOf(savedConnect) }
|
||||
@@ -139,6 +140,28 @@ fun ServerManagementScreen(
|
||||
Spacer(Modifier.height(10.dp))
|
||||
StatusRow(stringResource(R.string.vk_turn_proxy), serverKnown?.running == true)
|
||||
|
||||
if (serverKnown?.installed == true && !serverKnown.version.isNullOrBlank()) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(
|
||||
stringResource(R.string.server_version_label, serverKnown.version),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
|
||||
installStage?.let { stage ->
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(
|
||||
when (stage) {
|
||||
"cached" -> stringResource(R.string.server_install_cached)
|
||||
"downloaded" -> stringResource(R.string.server_install_downloaded)
|
||||
else -> stage
|
||||
},
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.extendedColorScheme.info
|
||||
)
|
||||
}
|
||||
|
||||
when (serverState) {
|
||||
is ServerState.Checking -> {
|
||||
Spacer(Modifier.height(12.dp))
|
||||
@@ -200,6 +223,9 @@ fun ServerManagementScreen(
|
||||
)
|
||||
}
|
||||
|
||||
// VLESS bonding / WRAP управляются на клиентском экране — общий source.
|
||||
// Здесь не дублируем, чтобы не путать пользователя двумя точками контроля.
|
||||
|
||||
// Action buttons
|
||||
FilledTonalButton(
|
||||
onClick = {
|
||||
@@ -213,7 +239,7 @@ fun ServerManagementScreen(
|
||||
) {
|
||||
Icon(painterResource(R.drawable.cloud_download_24px), null)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(if (serverKnown?.installed == true) stringResource(R.string.update) else stringResource(R.string.install))
|
||||
Text(stringResource(R.string.install))
|
||||
}
|
||||
|
||||
Button(
|
||||
|
||||
@@ -12,7 +12,14 @@ sealed class SshConnectionState {
|
||||
sealed class ServerState {
|
||||
object Unknown : ServerState()
|
||||
object Checking : ServerState()
|
||||
data class Known(val installed: Boolean, val running: Boolean, val vlessMode: Boolean? = null) : ServerState()
|
||||
data class Known(
|
||||
val installed: Boolean,
|
||||
val running: Boolean,
|
||||
val vlessMode: Boolean? = null,
|
||||
val vlessBond: Boolean? = null,
|
||||
val wrap: Boolean? = null,
|
||||
val version: String? = null
|
||||
) : ServerState()
|
||||
data class Working(val action: String) : ServerState()
|
||||
data class Error(val message: String) : ServerState()
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ package com.freeturn.app.viewmodel
|
||||
import android.app.Application
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import androidx.lifecycle.AndroidViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.freeturn.app.ProxyService
|
||||
@@ -30,7 +29,7 @@ import kotlinx.coroutines.withTimeoutOrNull
|
||||
class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
|
||||
private val prefs = AppPreferences(application)
|
||||
private val sshRepository = SshRepository()
|
||||
private val sshRepository = SshRepository(application)
|
||||
private val proxyManager = LocalProxyManager(application)
|
||||
private val appUpdater = AppUpdater(application)
|
||||
|
||||
@@ -41,7 +40,6 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
val proxyState: StateFlow<ProxyState> = proxyManager.proxyState
|
||||
val connectedSince: StateFlow<Long?> = ProxyServiceState.connectedSince
|
||||
val logs: StateFlow<List<String>> = ProxyServiceState.logs
|
||||
val customKernelExists: StateFlow<Boolean> = proxyManager.customKernelExists
|
||||
val updateState: StateFlow<UpdateState> = appUpdater.state
|
||||
|
||||
private val _isInitialized = MutableStateFlow(false)
|
||||
@@ -279,10 +277,46 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
}
|
||||
|
||||
// Server management
|
||||
val serverOpts: StateFlow<AppPreferences.ServerOpts> = prefs.serverOptsFlow
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), AppPreferences.ServerOpts())
|
||||
|
||||
private val _serverInstallStage = MutableStateFlow<String?>(null)
|
||||
/** Последний результат install: "cached" | "downloaded" | null. */
|
||||
val serverInstallStage: StateFlow<String?> = _serverInstallStage.asStateFlow()
|
||||
|
||||
private val _isRegeneratingWrapKey = MutableStateFlow(false)
|
||||
/** true — пока крутится gen-wrap-key + последующий рестарт сервера/клиента. */
|
||||
val isRegeneratingWrapKey: StateFlow<Boolean> = _isRegeneratingWrapKey.asStateFlow()
|
||||
|
||||
fun installServer() {
|
||||
viewModelScope.launch { sshRepository.installServer() }
|
||||
viewModelScope.launch {
|
||||
_serverInstallStage.value = null
|
||||
val outcome = sshRepository.installServer()
|
||||
if (outcome is com.freeturn.app.domain.InstallOutcome.Success) {
|
||||
_serverInstallStage.value = outcome.stage
|
||||
// Авто-генерация wrap-key после первого скачивания, если ещё нет.
|
||||
if (outcome.stage == "downloaded") {
|
||||
val current = prefs.serverOptsFlow.first()
|
||||
if (current.wrapKey.isBlank()) {
|
||||
val key = sshRepository.generateWrapKey()
|
||||
if (!key.isNullOrBlank()) {
|
||||
prefs.saveServerOpts(current.copy(wrapKey = key))
|
||||
}
|
||||
}
|
||||
}
|
||||
// Скрипт переустановил бинарь поверх работающего процесса —
|
||||
// SshRepository уже вызвал stop, осталось стартануть с актуальными
|
||||
// listen/connect и serverOpts (их знает только VM).
|
||||
if (outcome.needsRestart) {
|
||||
startServer()
|
||||
restartProxyIfRunning()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun consumeInstallStage() { _serverInstallStage.value = null }
|
||||
|
||||
fun startServer() {
|
||||
val l = proxyListen.value
|
||||
val c = proxyConnect.value
|
||||
@@ -291,7 +325,92 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
return
|
||||
}
|
||||
val vless = clientConfig.value.vlessMode
|
||||
viewModelScope.launch { sshRepository.startServer(l, c, vless) }
|
||||
val opts = serverOpts.value
|
||||
val wrapKey = if (opts.wrapEnabled) opts.wrapKey else ""
|
||||
viewModelScope.launch {
|
||||
sshRepository.startServer(
|
||||
listen = l, connect = c,
|
||||
vlessMode = vless,
|
||||
vlessBond = opts.vlessBond,
|
||||
wrapKey = wrapKey
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun setServerVlessBond(enabled: Boolean) {
|
||||
viewModelScope.launch {
|
||||
val current = prefs.serverOptsFlow.first()
|
||||
if (current.vlessBond == enabled) return@launch
|
||||
prefs.saveServerOpts(current.copy(vlessBond = enabled))
|
||||
restartServerIfRunning()
|
||||
restartProxyIfRunning()
|
||||
}
|
||||
}
|
||||
|
||||
fun setServerWrapEnabled(enabled: Boolean) {
|
||||
viewModelScope.launch {
|
||||
val current = prefs.serverOptsFlow.first()
|
||||
if (current.wrapEnabled == enabled) return@launch
|
||||
// При первом включении wrap, если ключа ещё нет — пробуем взять с сервера.
|
||||
var next = current.copy(wrapEnabled = enabled)
|
||||
if (enabled && next.wrapKey.isBlank()) {
|
||||
val key = sshRepository.generateWrapKey()
|
||||
if (!key.isNullOrBlank()) next = next.copy(wrapKey = key)
|
||||
}
|
||||
prefs.saveServerOpts(next)
|
||||
restartServerIfRunning()
|
||||
restartProxyIfRunning()
|
||||
}
|
||||
}
|
||||
|
||||
fun regenerateWrapKey() {
|
||||
viewModelScope.launch {
|
||||
if (_isRegeneratingWrapKey.value) return@launch
|
||||
_isRegeneratingWrapKey.value = true
|
||||
try {
|
||||
val key = sshRepository.generateWrapKey() ?: return@launch
|
||||
val current = prefs.serverOptsFlow.first()
|
||||
prefs.saveServerOpts(current.copy(wrapKey = key))
|
||||
restartServerIfRunning()
|
||||
restartProxyIfRunning()
|
||||
} finally {
|
||||
_isRegeneratingWrapKey.value = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Перезапускает сервер с актуальными опциями, если он сейчас запущен. */
|
||||
private suspend fun restartServerIfRunning() {
|
||||
val running = (serverState.value as? ServerState.Known)?.running == true
|
||||
if (!running) return
|
||||
val l = proxyListen.value
|
||||
val c = proxyConnect.value
|
||||
if (!l.matches(Regex("""^[\w.\-]+:\d{1,5}$""")) ||
|
||||
!c.matches(Regex("""^[\w.\-]+:\d{1,5}$"""))) return
|
||||
val opts = prefs.serverOptsFlow.first()
|
||||
val vless = clientConfig.value.vlessMode
|
||||
sshRepository.stopServer()
|
||||
sshRepository.startServer(
|
||||
listen = l, connect = c,
|
||||
vlessMode = vless,
|
||||
vlessBond = opts.vlessBond,
|
||||
wrapKey = if (opts.wrapEnabled) opts.wrapKey else ""
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Перезапускает локальный клиент с актуальным ClientConfig + serverOpts,
|
||||
* если он сейчас работает. Используется после изменения sync-флагов
|
||||
* (vlessMode/vlessBond/wrap*), чтобы клиент и сервер не разъехались по
|
||||
* параметрам после отдельного рестарта сервера.
|
||||
*/
|
||||
private suspend fun restartProxyIfRunning() {
|
||||
if (!ProxyServiceState.isRunning.value) return
|
||||
proxyManager.stopProxy()
|
||||
withTimeoutOrNull(2_000) {
|
||||
ProxyServiceState.isRunning.first { !it }
|
||||
}
|
||||
proxyManager.startProxy(clientConfig.value)
|
||||
}
|
||||
|
||||
fun stopServer() {
|
||||
@@ -310,6 +429,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
sshRepository.stopServer()
|
||||
startServer()
|
||||
}
|
||||
restartProxyIfRunning()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -351,24 +471,6 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
viewModelScope.launch { prefs.setOnboardingDone(true) }
|
||||
}
|
||||
|
||||
// Custom kernel
|
||||
private val _kernelError = MutableStateFlow<String?>(null)
|
||||
val kernelError: StateFlow<String?> = _kernelError.asStateFlow()
|
||||
|
||||
fun setCustomKernel(uri: Uri) {
|
||||
viewModelScope.launch {
|
||||
_kernelError.value = proxyManager.setCustomKernel(uri)
|
||||
}
|
||||
}
|
||||
|
||||
fun clearCustomKernel() {
|
||||
proxyManager.clearCustomKernel()
|
||||
}
|
||||
|
||||
fun clearKernelError() {
|
||||
_kernelError.value = null
|
||||
}
|
||||
|
||||
// App update
|
||||
fun checkForUpdate() {
|
||||
viewModelScope.launch { appUpdater.checkForUpdate(silent = false) }
|
||||
|
||||
Binary file not shown.
@@ -12,7 +12,7 @@
|
||||
<string name="current_settings">Текущие настройки</string>
|
||||
<string name="server">Сервер</string>
|
||||
<string name="threads">Потоки</string>
|
||||
<string name="allocs_per_stream_label">TURN-аллокаций на поток</string>
|
||||
<string name="streams_per_cred_label">Потоков на пару кредов</string>
|
||||
<string name="tcp">TCP</string>
|
||||
<string name="udp">UDP</string>
|
||||
<string name="local_port">Локальный порт</string>
|
||||
@@ -53,24 +53,24 @@
|
||||
<string name="parameters_title">Параметры</string>
|
||||
<string name="threads_format">Потоки: %1$d</string>
|
||||
<string name="threads_recommendation">Рекомендуется 4–8</string>
|
||||
<string name="allocs_per_stream_recommendation">Открывает несколько TURN-аллокаций под одной парой кредов. Максимум 3.</string>
|
||||
<string name="streams_per_cred_recommendation">Сколько TURN-потоков обслуживает одна пара VK-кредов. По умолчанию 10.</string>
|
||||
<string name="streams_per_cred_format">Потоков на кред: %1$d</string>
|
||||
<string name="captcha_solver_title">Решатель капчи</string>
|
||||
<string name="captcha_solver_desc">v2 — нейросетевой (быстрее), v1 — legacy fallback</string>
|
||||
<string name="client_vless_bond">VLESS bonding</string>
|
||||
<string name="client_vless_bond_desc">Должен совпадать с настройкой сервера. Только для VLESS-режима.</string>
|
||||
<string name="client_wrap_enabled">WRAP-обфускация</string>
|
||||
<string name="client_wrap_desc">Должна совпадать с настройкой сервера. Ключ берётся с сервера.</string>
|
||||
<string name="locked_disconnect_hint">Подключитесь к серверу, чтобы изменить</string>
|
||||
<string name="wrap_key_empty_hint">Ключ не сгенерирован — нажмите кнопку ниже</string>
|
||||
<string name="server_wrap_regen_in_progress">Генерация ключа…</string>
|
||||
<string name="server_sync_section">Синхронные настройки сервера</string>
|
||||
<string name="transport_protocol">Транспорт</string>
|
||||
<string name="transport_protocol_desc">UDP снижает задержки, TCP — стабильнее</string>
|
||||
<string name="manual_captcha">Ручной ввод капчи</string>
|
||||
<string name="manual_captcha_desc">Решать капчу вручную вместо автоматического распознавания</string>
|
||||
<string name="force_port_443">TURN на порту 443</string>
|
||||
<string name="force_port_443_desc">Помогает, если оператор режет нестандартные порты</string>
|
||||
<string name="dns_mode_title">DNS-резолвер</string>
|
||||
<string name="dns_mode_desc">Авто — пробует системный DNS, переключается на DNS-over-HTTPS при блокировке</string>
|
||||
<string name="dns_mode_auto">Авто</string>
|
||||
<string name="dns_mode_udp">UDP/53</string>
|
||||
<string name="dns_mode_doh">DoH</string>
|
||||
<string name="core_title">Ядро</string>
|
||||
<string name="custom_core">Кастомное ядро</string>
|
||||
<string name="builtin_core">Встроенное ядро</string>
|
||||
<string name="loaded_from_memory">Загружено из памяти устройства</string>
|
||||
<string name="from_apk">Из APK</string>
|
||||
<string name="btn_load">Загрузить</string>
|
||||
<string name="use_carrier_dns">DNS оператора связи</string>
|
||||
<string name="use_carrier_dns_desc">Использовать DNS текущей сети вместо системного резолвера</string>
|
||||
<string name="finish_setup">Завершить настройку</string>
|
||||
|
||||
<!-- LogsScreen -->
|
||||
@@ -91,8 +91,16 @@
|
||||
<string name="turn_client_address">Адрес TURN‑клиента</string>
|
||||
<string name="turn_client_placeholder">127.0.0.1:40537</string>
|
||||
<string name="turn_client_desc">Локальный WireGuard/Hysteria-клиент на стороне сервера</string>
|
||||
<string name="update">Обновить</string>
|
||||
<string name="install">Установить</string>
|
||||
<string name="install">Установить / обновить</string>
|
||||
<string name="server_install_cached">Актуально</string>
|
||||
<string name="server_install_downloaded">Обновлено</string>
|
||||
<string name="server_version_label">Версия: %1$s</string>
|
||||
<string name="server_vless_bond">VLESS bonding</string>
|
||||
<string name="server_vless_bond_desc">Объединение нескольких VLESS-сессий в один туннель</string>
|
||||
<string name="server_wrap_enabled">WRAP-обфускация</string>
|
||||
<string name="server_wrap_desc">Маскирует DTLS-трафик ChaCha20-XOR (одинаковый ключ на сервере и клиенте)</string>
|
||||
<string name="server_wrap_key_label">Wrap-ключ (64 hex)</string>
|
||||
<string name="server_wrap_regen">Сгенерировать новый ключ на сервере</string>
|
||||
<string name="start_server">Запустить сервер</string>
|
||||
<string name="stop_server">Остановить сервер</string>
|
||||
<string name="continue_client_setup">Продолжить настройку клиента</string>
|
||||
|
||||
Reference in new issue
Block a user