fix: shell-инъекция в ServerScripts, вынос состояния из ProxyService, утечка scope

- ServerScripts.startServer(): санитизация listen/connect через shellSafe()
- ProxyService companion → ProxyServiceState (read-only публичный API)
- LocalProxyManager: добавлен destroy(), вызывается из ViewModel.onCleared()
This commit is contained in:
samosvalishe committed 2026-04-04 01:33:14 +03:00
1 parent bdad451722
commit c2efe5575d
6 files changed
+123 -71

No files matched your search

@@ -9,8 +9,8 @@ class ProxyReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) { override fun onReceive(context: Context, intent: Intent) {
when (intent.action) { when (intent.action) {
"com.freeturn.app.START_PROXY" -> { "com.freeturn.app.START_PROXY" -> {
ProxyService.clearLogs() ProxyServiceState.clearLogs()
ProxyService.startupResult.value = null ProxyServiceState.setStartupResult(null)
val serviceIntent = Intent(context, ProxyService::class.java) val serviceIntent = Intent(context, ProxyService::class.java)
context.startForegroundService(serviceIntent) context.startForegroundService(serviceIntent)
} }
@@ -25,10 +25,7 @@ import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
@@ -41,24 +38,6 @@ class ProxyService : Service() {
companion object { companion object {
const val MAX_RESTARTS = 8 const val MAX_RESTARTS = 8
private const val MAX_LOG_LINES = 200
val isRunning = MutableStateFlow(false)
val logs = MutableStateFlow<List<String>>(emptyList())
val proxyFailed = MutableSharedFlow<Unit>(extraBufferCapacity = 1)
val startupResult = MutableStateFlow<StartupResult?>(null)
fun addLog(msg: String) {
logs.update { current ->
val next = current + msg
if (next.size > MAX_LOG_LINES) next.drop(next.size - MAX_LOG_LINES) else next
}
}
fun clearLogs() {
logs.value = emptyList()
}
} }
private var wakeLock: PowerManager.WakeLock? = null private var wakeLock: PowerManager.WakeLock? = null
@@ -85,7 +64,7 @@ class ProxyService : Service() {
} }
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (isRunning.value) return START_STICKY if (ProxyServiceState.isRunning.value) return START_STICKY
openAppIntent = packageManager.getLaunchIntentForPackage(packageName)?.let { openAppIntent = packageManager.getLaunchIntentForPackage(packageName)?.let {
PendingIntent.getActivity(this, 0, it, PendingIntent.FLAG_IMMUTABLE) PendingIntent.getActivity(this, 0, it, PendingIntent.FLAG_IMMUTABLE)
@@ -99,7 +78,7 @@ class ProxyService : Service() {
.build() .build()
startForeground(1, notification) startForeground(1, notification)
isRunning.value = true ProxyServiceState.setRunning(true)
userStopped.set(false) userStopped.set(false)
restartCount = 0 restartCount = 0
@@ -109,7 +88,7 @@ class ProxyService : Service() {
registerNetworkCallback() registerNetworkCallback()
addLog("=== ЗАПУСК ПРОКСИ ===") ProxyServiceState.addLog("=== ЗАПУСК ПРОКСИ ===")
serviceScope.launch { startBinaryProcess() } serviceScope.launch { startBinaryProcess() }
return START_STICKY return START_STICKY
@@ -122,10 +101,10 @@ class ProxyService : Service() {
val customBin = File(filesDir, "custom_vkturn") val customBin = File(filesDir, "custom_vkturn")
val executable = if (customBin.exists()) { val executable = if (customBin.exists()) {
addLog("Используется кастомное ядро из памяти телефона") ProxyServiceState.addLog("Используется кастомное ядро из памяти телефона")
customBin.absolutePath customBin.absolutePath
} else { } else {
addLog("Используется стандартное ядро из APK") ProxyServiceState.addLog("Используется стандартное ядро из APK")
"${applicationInfo.nativeLibraryDir}/libvkturn.so" "${applicationInfo.nativeLibraryDir}/libvkturn.so"
} }
@@ -152,7 +131,7 @@ class ProxyService : Service() {
var startupEmitted = false var startupEmitted = false
var startupFailed = false var startupFailed = false
try { try {
addLog("Команда: ${cmdArgs.joinToString(" ")}") ProxyServiceState.addLog("Команда: ${cmdArgs.joinToString(" ")}")
val proc = withContext(Dispatchers.IO) { val proc = withContext(Dispatchers.IO) {
ProcessBuilder(cmdArgs) ProcessBuilder(cmdArgs)
@@ -165,17 +144,17 @@ class ProxyService : Service() {
var line: String? var line: String?
while (reader.readLine().also { line = it } != null) { while (reader.readLine().also { line = it } != null) {
val l = line ?: continue val l = line ?: continue
addLog(l) ProxyServiceState.addLog(l)
if (!startupEmitted) { if (!startupEmitted) {
val lower = l.lowercase() val lower = l.lowercase()
if (lower.contains("panic") || lower.contains("fatal") || if (lower.contains("panic") || lower.contains("fatal") ||
lower.contains("rate limit")) { lower.contains("rate limit")) {
startupResult.value = StartupResult.Failed(l) ProxyServiceState.setStartupResult(StartupResult.Failed(l))
updateNotification("VK TURN Proxy", "Ошибка подключения") updateNotification("VK TURN Proxy", "Ошибка подключения")
startupFailed = true startupFailed = true
} else { } else {
startupResult.value = StartupResult.Success ProxyServiceState.setStartupResult(StartupResult.Success)
updateNotification("VK TURN Proxy", "Прокси активен") updateNotification("VK TURN Proxy", "Прокси активен")
} }
startupEmitted = true startupEmitted = true
@@ -183,7 +162,7 @@ class ProxyService : Service() {
// compareAndSet гарантирует единственный postDelayed даже при параллельных quota-ошибках // compareAndSet гарантирует единственный postDelayed даже при параллельных quota-ошибках
if (isQuotaError(l) && sessionKillScheduled.compareAndSet(false, true)) { if (isQuotaError(l) && sessionKillScheduled.compareAndSet(false, true)) {
addLog(">>> QUOTA ERROR — сброс сессии через 2с") ProxyServiceState.addLog(">>> QUOTA ERROR — сброс сессии через 2с")
handler.postDelayed({ handler.postDelayed({
sessionKillScheduled.set(false) sessionKillScheduled.set(false)
if (!userStopped.get()) { if (!userStopped.get()) {
@@ -198,36 +177,36 @@ class ProxyService : Service() {
exitCode = if (withContext(Dispatchers.IO) { exitCode = if (withContext(Dispatchers.IO) {
proc.waitFor(5, TimeUnit.MINUTES) proc.waitFor(5, TimeUnit.MINUTES)
}) proc.exitValue() else -1 }) proc.exitValue() else -1
addLog("=== ПРОЦЕСС ОСТАНОВЛЕН (Код: $exitCode) ===") ProxyServiceState.addLog("=== ПРОЦЕСС ОСТАНОВЛЕН (Код: $exitCode) ===")
if (!startupEmitted) { if (!startupEmitted) {
startupResult.value = StartupResult.Failed( ProxyServiceState.setStartupResult(StartupResult.Failed(
"Процесс завершился без вывода (код: $exitCode)") "Процесс завершился без вывода (код: $exitCode)"))
startupFailed = true startupFailed = true
} }
} catch (e: Exception) { } catch (e: Exception) {
addLog("КРИТИЧЕСКАЯ ОШИБКА: ${e.message}") ProxyServiceState.addLog("КРИТИЧЕСКАЯ ОШИБКА: ${e.message}")
} finally { } finally {
process.set(null) process.set(null)
when { when {
userStopped.get() -> { userStopped.get() -> {
isRunning.value = false ProxyServiceState.setRunning(false)
stopSelf() stopSelf()
} }
startupFailed -> { startupFailed -> {
addLog("=== Ошибка при запуске, watchdog не активирован ===") ProxyServiceState.addLog("=== Ошибка при запуске, watchdog не активирован ===")
isRunning.value = false ProxyServiceState.setRunning(false)
// Убираем proxyFailed.tryEmit, так как startProxy и так обработает StartupResult.Failed // Убираем proxyFailed.tryEmit, так как startProxy и так обработает StartupResult.Failed
stopSelf() stopSelf()
} }
exitCode == 0 -> { exitCode == 0 -> {
val uptime = System.currentTimeMillis() - startedAt val uptime = System.currentTimeMillis() - startedAt
if (uptime < 5_000L) { if (uptime < 5_000L) {
addLog("=== Быстрый выход (${uptime}мс) — проверьте VK-ссылку и настройки ===") ProxyServiceState.addLog("=== Быстрый выход (${uptime}мс) — проверьте VK-ссылку и настройки ===")
} else { } else {
addLog("=== Сессия завершена нормально ===") ProxyServiceState.addLog("=== Сессия завершена нормально ===")
} }
isRunning.value = false ProxyServiceState.setRunning(false)
stopSelf() stopSelf()
} }
else -> scheduleWatchdogRestart() else -> scheduleWatchdogRestart()
@@ -240,16 +219,16 @@ class ProxyService : Service() {
private fun scheduleWatchdogRestart() { private fun scheduleWatchdogRestart() {
restartCount++ restartCount++
if (restartCount > MAX_RESTARTS) { if (restartCount > MAX_RESTARTS) {
addLog("=== WATCHDOG: превышен лимит попыток ($MAX_RESTARTS), остановка ===") ProxyServiceState.addLog("=== WATCHDOG: превышен лимит попыток ($MAX_RESTARTS), остановка ===")
isRunning.value = false ProxyServiceState.setRunning(false)
proxyFailed.tryEmit(Unit) ProxyServiceState.emitFailed()
stopSelf() stopSelf()
return return
} }
val baseDelay = minOf(1_000L * restartCount, 30_000L) val baseDelay = minOf(1_000L * restartCount, 30_000L)
val jitter = Random.nextLong(0, 500) val jitter = Random.nextLong(0, 500)
val delay = baseDelay + jitter val delay = baseDelay + jitter
addLog("=== WATCHDOG: перезапуск через ${delay}мс (попытка $restartCount/$MAX_RESTARTS) ===") ProxyServiceState.addLog("=== WATCHDOG: перезапуск через ${delay}мс (попытка $restartCount/$MAX_RESTARTS) ===")
updateNotification("VK TURN Proxy", "Переподключение ($restartCount/$MAX_RESTARTS)...") updateNotification("VK TURN Proxy", "Переподключение ($restartCount/$MAX_RESTARTS)...")
handler.postDelayed({ handler.postDelayed({
if (!userStopped.get()) serviceScope.launch { startBinaryProcess() } if (!userStopped.get()) serviceScope.launch { startBinaryProcess() }
@@ -275,7 +254,7 @@ class ProxyService : Service() {
networkDebounceJob = serviceScope.launch { networkDebounceJob = serviceScope.launch {
kotlinx.coroutines.delay(2000) kotlinx.coroutines.delay(2000)
if (!userStopped.get() && process.get() != null) { if (!userStopped.get() && process.get() != null) {
addLog("=== СМЕНА СЕТИ — ПЕРЕЗАПУСК ===") ProxyServiceState.addLog("=== СМЕНА СЕТИ — ПЕРЕЗАПУСК ===")
updateNotification("VK TURN Proxy", "Смена сети, переподключение...") updateNotification("VK TURN Proxy", "Смена сети, переподключение...")
restartCount = 0 restartCount = 0
val p = process.get() val p = process.get()
@@ -321,10 +300,10 @@ class ProxyService : Service() {
override fun onDestroy() { override fun onDestroy() {
super.onDestroy() super.onDestroy()
userStopped.set(true) userStopped.set(true)
isRunning.value = false ProxyServiceState.setRunning(false)
handler.removeCallbacksAndMessages(null) handler.removeCallbacksAndMessages(null)
unregisterNetworkCallback() unregisterNetworkCallback()
addLog("=== ОСТАНОВКА ИЗ ИНТЕРФЕЙСА ===") ProxyServiceState.addLog("=== ОСТАНОВКА ИЗ ИНТЕРФЕЙСА ===")
process.get()?.destroyForcibly() process.get()?.destroyForcibly()
serviceScope.cancel() serviceScope.cancel()
if (wakeLock?.isHeld == true) wakeLock?.release() if (wakeLock?.isHeld == true) wakeLock?.release()
@@ -0,0 +1,53 @@
package com.freeturn.app
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
/**
* Централизованное состояние прокси-сервиса.
* Публичный API — только read-only Flow, мутация через явные методы.
*/
object ProxyServiceState {
private const val MAX_LOG_LINES = 200
private val _isRunning = MutableStateFlow(false)
val isRunning: StateFlow<Boolean> = _isRunning.asStateFlow()
private val _logs = MutableStateFlow<List<String>>(emptyList())
val logs: StateFlow<List<String>> = _logs.asStateFlow()
private val _proxyFailed = MutableSharedFlow<Unit>(extraBufferCapacity = 1)
val proxyFailed: SharedFlow<Unit> = _proxyFailed.asSharedFlow()
private val _startupResult = MutableStateFlow<StartupResult?>(null)
val startupResult: StateFlow<StartupResult?> = _startupResult.asStateFlow()
fun setRunning(value: Boolean) {
_isRunning.value = value
}
fun setStartupResult(result: StartupResult?) {
_startupResult.value = result
}
fun emitFailed() {
_proxyFailed.tryEmit(Unit)
}
fun addLog(msg: String) {
_logs.update { current ->
val next = current + msg
if (next.size > MAX_LOG_LINES) next.drop(next.size - MAX_LOG_LINES) else next
}
}
fun clearLogs() {
_logs.value = emptyList()
}
}
@@ -4,6 +4,7 @@ import android.content.Context
import android.content.Intent import android.content.Intent
import android.net.Uri import android.net.Uri
import com.freeturn.app.ProxyService import com.freeturn.app.ProxyService
import com.freeturn.app.ProxyServiceState
import com.freeturn.app.StartupResult import com.freeturn.app.StartupResult
import com.freeturn.app.data.ClientConfig import com.freeturn.app.data.ClientConfig
import com.freeturn.app.viewmodel.ProxyState import com.freeturn.app.viewmodel.ProxyState
@@ -16,6 +17,7 @@ import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull import kotlinx.coroutines.withTimeoutOrNull
import kotlinx.coroutines.cancel
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
@@ -37,13 +39,13 @@ class LocalProxyManager(private val context: Context) {
} }
suspend fun observeProxyLifecycle() { suspend fun observeProxyLifecycle() {
ProxyService.proxyFailed.collect { ProxyServiceState.proxyFailed.collect {
setErrorWithAutoReset("Прокси упал ${ProxyService.MAX_RESTARTS} раз — проверьте настройки") setErrorWithAutoReset("Прокси упал ${ProxyService.MAX_RESTARTS} раз — проверьте настройки")
} }
} }
suspend fun observeProxyServiceStatus() { suspend fun observeProxyServiceStatus() {
ProxyService.isRunning.collect { running -> ProxyServiceState.isRunning.collect { running ->
if (running && _proxyState.value !is ProxyState.Running && _proxyState.value !is ProxyState.Starting) { if (running && _proxyState.value !is ProxyState.Running && _proxyState.value !is ProxyState.Starting) {
// Сервис запущен внешним источником (например, ProxyReceiver) // Сервис запущен внешним источником (например, ProxyReceiver)
_proxyState.value = ProxyState.Running _proxyState.value = ProxyState.Running
@@ -54,11 +56,11 @@ class LocalProxyManager(private val context: Context) {
} }
fun syncInitialState() { fun syncInitialState() {
if (ProxyService.isRunning.value) _proxyState.value = ProxyState.Running if (ProxyServiceState.isRunning.value) _proxyState.value = ProxyState.Running
} }
suspend fun startProxy(cfg: ClientConfig) { suspend fun startProxy(cfg: ClientConfig) {
if (ProxyService.isRunning.value) return if (ProxyServiceState.isRunning.value) return
if (_proxyState.value is ProxyState.Error) _proxyState.value = ProxyState.Idle if (_proxyState.value is ProxyState.Error) _proxyState.value = ProxyState.Idle
if (!cfg.isRawMode && (cfg.serverAddress.isBlank() || cfg.vkLink.isBlank())) { if (!cfg.isRawMode && (cfg.serverAddress.isBlank() || cfg.vkLink.isBlank())) {
@@ -72,12 +74,12 @@ class LocalProxyManager(private val context: Context) {
_proxyState.value = ProxyState.Starting _proxyState.value = ProxyState.Starting
ProxyService.clearLogs() ProxyServiceState.clearLogs()
ProxyService.startupResult.value = null ProxyServiceState.setStartupResult(null)
context.startForegroundService(Intent(context, ProxyService::class.java)) context.startForegroundService(Intent(context, ProxyService::class.java))
val result = withTimeoutOrNull(5_000L) { val result = withTimeoutOrNull(5_000L) {
ProxyService.startupResult.filterNotNull().first() ProxyServiceState.startupResult.filterNotNull().first()
} }
if (_proxyState.value is ProxyState.Error) return if (_proxyState.value is ProxyState.Error) return
@@ -114,20 +116,24 @@ class LocalProxyManager(private val context: Context) {
} }
dest.setExecutable(true) dest.setExecutable(true)
withContext(Dispatchers.Main) { _customKernelExists.value = true } withContext(Dispatchers.Main) { _customKernelExists.value = true }
ProxyService.addLog("Кастомное ядро установлено: ${dest.length() / 1024} KB") ProxyServiceState.addLog("Кастомное ядро установлено: ${dest.length() / 1024} KB")
} catch (e: Exception) { } catch (e: Exception) {
ProxyService.addLog("Ошибка установки ядра: ${e.message}") ProxyServiceState.addLog("Ошибка установки ядра: ${e.message}")
} }
} }
fun clearCustomKernel() { fun clearCustomKernel() {
File(context.filesDir, "custom_vkturn").delete() File(context.filesDir, "custom_vkturn").delete()
_customKernelExists.value = false _customKernelExists.value = false
ProxyService.addLog("Кастомное ядро удалено, используется встроенное") ProxyServiceState.addLog("Кастомное ядро удалено, используется встроенное")
} }
fun clearState() { fun clearState() {
_proxyState.value = ProxyState.Idle _proxyState.value = ProxyState.Idle
_customKernelExists.value = false _customKernelExists.value = false
} }
fun destroy() {
scope.cancel()
}
} }
@@ -2,6 +2,10 @@ package com.freeturn.app.domain
object ServerScripts { object ServerScripts {
/** Удаляет из строки всё, кроме допустимых символов host:port (защита от shell-инъекций) */
private fun shellSafe(value: String): String =
value.replace(Regex("[^a-zA-Z0-9._:\\-]"), "")
val checkServerState: String = """ val checkServerState: String = """
if ls /opt/vk-turn/server-linux-* >/dev/null 2>&1; then echo "INSTALLED:YES"; else echo "INSTALLED:NO"; fi 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"; else echo "RUNNING:NO"; fi if ps aux | grep -v grep | grep -q "server-linux-"; then echo "RUNNING:YES"; else echo "RUNNING:NO"; fi
@@ -54,13 +58,17 @@ object ServerScripts {
chmod +x "${'$'}BIN" && echo "DONE" chmod +x "${'$'}BIN" && echo "DONE"
""".trimIndent() """.trimIndent()
fun startServer(listen: String, connect: String): String = """ fun startServer(listen: String, connect: String): String {
cd /opt/vk-turn && val safeListen = shellSafe(listen)
ARCH=${'$'}(uname -m); val safeConnect = shellSafe(connect)
if [ "${'$'}ARCH" = "x86_64" ]; then BIN="server-linux-amd64"; else BIN="server-linux-arm64"; fi; return """
nohup ./${'$'}BIN -listen '${listen}' -connect '${connect}' > server.log 2>&1 & cd /opt/vk-turn &&
echo ${'$'}! > proxy.pid && echo "STARTED" ARCH=${'$'}(uname -m);
""".trimIndent() if [ "${'$'}ARCH" = "x86_64" ]; then BIN="server-linux-amd64"; else BIN="server-linux-arm64"; fi;
nohup ./${'$'}BIN -listen '${safeListen}' -connect '${safeConnect}' > server.log 2>&1 &
echo ${'$'}! > proxy.pid && echo "STARTED"
""".trimIndent()
}
val stopServer: String = """ val stopServer: String = """
cd /opt/vk-turn && cd /opt/vk-turn &&
@@ -7,6 +7,7 @@ import android.net.Uri
import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewModelScope
import com.freeturn.app.ProxyService import com.freeturn.app.ProxyService
import com.freeturn.app.ProxyServiceState
import com.freeturn.app.data.AppPreferences import com.freeturn.app.data.AppPreferences
import com.freeturn.app.data.ClientConfig import com.freeturn.app.data.ClientConfig
import com.freeturn.app.data.SshConfig import com.freeturn.app.data.SshConfig
@@ -34,7 +35,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
val sshLog: StateFlow<List<String>> = sshRepository.sshLog val sshLog: StateFlow<List<String>> = sshRepository.sshLog
val proxyState: StateFlow<ProxyState> = proxyManager.proxyState val proxyState: StateFlow<ProxyState> = proxyManager.proxyState
val logs: StateFlow<List<String>> = ProxyService.logs val logs: StateFlow<List<String>> = ProxyServiceState.logs
val customKernelExists: StateFlow<Boolean> = proxyManager.customKernelExists val customKernelExists: StateFlow<Boolean> = proxyManager.customKernelExists
private val _isInitialized = MutableStateFlow(false) private val _isInitialized = MutableStateFlow(false)
@@ -54,6 +55,11 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
proxyManager.syncInitialState() proxyManager.syncInitialState()
} }
override fun onCleared() {
super.onCleared()
proxyManager.destroy()
}
val sshConfig: StateFlow<SshConfig> = prefs.sshConfigFlow val sshConfig: StateFlow<SshConfig> = prefs.sshConfigFlow
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), SshConfig()) .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), SshConfig())
@@ -152,7 +158,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
} }
fun clearLogs() { fun clearLogs() {
ProxyService.clearLogs() ProxyServiceState.clearLogs()
} }
// ── Preferences ──────────────────────────────────────────────────────── // ── Preferences ────────────────────────────────────────────────────────
@@ -179,13 +185,13 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
fun resetAllSettings(context: Context) { fun resetAllSettings(context: Context) {
viewModelScope.launch { viewModelScope.launch {
if (ProxyService.isRunning.value) { if (ProxyServiceState.isRunning.value) {
context.stopService(Intent(context, ProxyService::class.java)) context.stopService(Intent(context, ProxyService::class.java))
} }
prefs.resetAll() prefs.resetAll()
sshRepository.resetAll() sshRepository.resetAll()
proxyManager.clearState() proxyManager.clearState()
ProxyService.clearLogs() ProxyServiceState.clearLogs()
val intent = (context as? android.app.Activity)?.intent val intent = (context as? android.app.Activity)?.intent
?: Intent(context, com.freeturn.app.MainActivity::class.java) ?: Intent(context, com.freeturn.app.MainActivity::class.java)