feat: SOCKS5 Hotspot Proxy для раздачи Wi-Fi без root

Добавлен легковесный SOCKS5-сервер (Kotlin Coroutines) на 0.0.0.0:1080, позволяющий раздавать VPN-трафик через точку доступа без root-прав. Опция включается в Настройки -> Продвинутые.
This commit is contained in:
samosvalishe committed 2026-07-03 15:08:54 +03:00
1 parent ea19c091b2
commit 793ac904e7
7 files changed
+256 -1

No files matched your search

@@ -43,6 +43,7 @@ class AppPreferences(context: Context) {
val SERVERS_JSON = stringPreferencesKey("servers_json")
val ACTIVE_SERVER_ID = stringPreferencesKey("active_server_id")
val OWN_CLIENT_ID = stringPreferencesKey("own_client_id")
val HOTSPOT_PROXY_ENABLED = booleanPreferencesKey("hotspot_proxy_enabled")
}
/** DataStore-флоу: IOException (битый файл) -> дефолты, остальное пробрасываем. */
@@ -106,6 +107,9 @@ class AppPreferences(context: Context) {
// даже после "не ограничивать" - без флага диалог всплывал бы каждый запуск.
val batteryPromptShownFlow: Flow<Boolean> = prefFlow { prefs -> prefs[BATTERY_PROMPT_SHOWN] ?: false }
/** Разрешает запуск SOCKS5 сервера на 0.0.0.0:1080 для раздачи интернета. */
val hotspotProxyEnabledFlow: Flow<Boolean> = prefFlow { prefs -> prefs[HOTSPOT_PROXY_ENABLED] ?: false }
// --- CRUD серверов ---
// Каждая операция - одна транзакция dataStore.edit: атомарный read-modify-write,
// параллельные записи не теряются и не оставляют активный id без сервера.
@@ -234,7 +238,11 @@ class AppPreferences(context: Context) {
}
suspend fun setRestartServerOnSwitch(enabled: Boolean) {
context.dataStore.edit { prefs -> prefs[RESTART_SERVER_ON_SWITCH] = enabled }
context.dataStore.edit { it[RESTART_SERVER_ON_SWITCH] = enabled }
}
suspend fun setHotspotProxyEnabled(enabled: Boolean) {
context.dataStore.edit { it[HOTSPOT_PROXY_ENABLED] = enabled }
}
suspend fun setTgSubscribeShown() {
@@ -0,0 +1,198 @@
package com.freeturn.app.domain.proxy
import kotlinx.coroutines.*
import java.io.EOFException
import java.io.InputStream
import java.io.OutputStream
import java.net.InetAddress
import java.net.ServerSocket
import java.net.Socket
import java.util.concurrent.atomic.AtomicBoolean
/**
* Легковесный SOCKS5 прокси-сервер для раздачи Wi-Fi без root.
* Принимает подключения на 0.0.0.0 и проксирует трафик через себя.
* Поскольку он работает внутри приложения с включенным VpnService,
* его исходящий трафик автоматически маршрутизируется в туннель.
*/
class Socks5Server(private val port: Int = 1080) {
private var serverSocket: ServerSocket? = null
private var scope: CoroutineScope? = null
private val isRunning = AtomicBoolean(false)
companion object {
// SOCKS5 reply codes (RFC 1928)
private const val REPLY_SUCCESS: Byte = 0x00
private const val REPLY_GENERAL_FAILURE: Byte = 0x01
private const val REPLY_CONNECTION_REFUSED: Byte = 0x05
private const val REPLY_HOST_UNREACHABLE: Byte = 0x04
private const val REPLY_NETWORK_UNREACHABLE: Byte = 0x03
}
fun start() {
if (!isRunning.compareAndSet(false, true)) return
val newScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
scope = newScope
newScope.launch {
try {
serverSocket = ServerSocket(port, 50, InetAddress.getByName("0.0.0.0"))
ProxyServiceState.addLog("SOCKS5 Hotspot Proxy запущен на 0.0.0.0:$port")
while (isActive && isRunning.get()) {
val clientSocket = serverSocket?.accept() ?: break
launch { handleClient(clientSocket) }
}
} catch (e: Exception) {
if (e !is CancellationException && isRunning.get()) {
ProxyServiceState.addLog("SOCKS5 ошибка сервера: ${e.message}")
}
} finally {
stop()
}
}
}
fun stop() {
if (!isRunning.compareAndSet(true, false)) return
try {
serverSocket?.close()
serverSocket = null
} catch (_: Exception) {}
scope?.cancel()
scope = null
ProxyServiceState.addLog("SOCKS5 Hotspot Proxy остановлен")
}
private suspend fun handleClient(clientSocket: Socket) = withContext(Dispatchers.IO) {
var targetSocket: Socket? = null
try {
val input = clientSocket.getInputStream()
val output = clientSocket.getOutputStream()
// 1. Handshake
val version = input.readByte()
if (version != 5) return@withContext
val numMethods = input.readByte()
if (numMethods <= 0) return@withContext
val methods = ByteArray(numMethods)
input.readFully(methods)
// Отвечаем: 0x05 (SOCKS5), 0x00 (No authentication)
output.write(byteArrayOf(5, 0))
output.flush()
// 2. Request
val reqVersion = input.readByte()
val reqCmd = input.readByte()
input.readByte() // RSV (reserved, игнорируем)
val reqAtyp = input.readByte()
if (reqVersion != 5 || reqCmd != 1) { // Only CONNECT is supported
sendReply(output, REPLY_GENERAL_FAILURE)
return@withContext
}
val host: String
when (reqAtyp) {
1 -> { // IPv4
val hostBytes = ByteArray(4)
input.readFully(hostBytes)
host = InetAddress.getByAddress(hostBytes).hostAddress ?: ""
}
3 -> { // Domain name
val len = input.readByte()
if (len <= 0) return@withContext
val hostBytes = ByteArray(len)
input.readFully(hostBytes)
host = String(hostBytes)
}
4 -> { // IPv6
val hostBytes = ByteArray(16)
input.readFully(hostBytes)
host = InetAddress.getByAddress(hostBytes).hostAddress ?: ""
}
else -> {
sendReply(output, REPLY_GENERAL_FAILURE)
return@withContext
}
}
val portBytes = ByteArray(2)
input.readFully(portBytes)
val targetPort = ((portBytes[0].toInt() and 0xFF) shl 8) or (portBytes[1].toInt() and 0xFF)
// 3. Устанавливаем соединение с целью.
// Трафик этого сокета перехватит VpnService, так как мы внутри приложения.
try {
targetSocket = Socket(host, targetPort)
} catch (e: java.net.ConnectException) {
sendReply(output, REPLY_CONNECTION_REFUSED)
return@withContext
} catch (e: java.net.NoRouteToHostException) {
sendReply(output, REPLY_HOST_UNREACHABLE)
return@withContext
} catch (e: java.net.UnknownHostException) {
sendReply(output, REPLY_HOST_UNREACHABLE)
return@withContext
} catch (e: Exception) {
sendReply(output, REPLY_GENERAL_FAILURE)
return@withContext
}
sendReply(output, REPLY_SUCCESS)
// 4. Двунаправленное копирование
val clientToServer = launch { pipe(input, targetSocket.getOutputStream()) }
val serverToClient = launch { pipe(targetSocket.getInputStream(), output) }
clientToServer.join()
serverToClient.join()
} catch (_: EOFException) {
// Клиент разорвал соединение посреди handshake — штатная ситуация
} catch (_: Exception) {
// Игнорируем сетевые ошибки отдельных клиентов
} finally {
try { clientSocket.close() } catch (_: Exception) {}
try { targetSocket?.close() } catch (_: Exception) {}
}
}
/** Отправляет SOCKS5 reply с указанным кодом результата. */
private fun sendReply(output: OutputStream, replyCode: Byte) {
// VER(1) REP(1) RSV(1) ATYP(1)=IPv4 BND.ADDR(4) BND.PORT(2)
output.write(byteArrayOf(5, replyCode, 0, 1, 0, 0, 0, 0, 0, 0))
output.flush()
}
/**
* Читает один байт, бросает [EOFException] при EOF.
* Возвращает значение 0..255 как Int для удобства сравнений.
*/
private fun InputStream.readByte(): Int {
val b = this.read()
if (b == -1) throw EOFException()
return b
}
private fun InputStream.readFully(b: ByteArray) {
var offset = 0
while (offset < b.size) {
val read = this.read(b, offset, b.size - offset)
if (read == -1) throw EOFException()
offset += read
}
}
private suspend fun pipe(inputStream: InputStream, outputStream: OutputStream) = withContext(Dispatchers.IO) {
try {
val buffer = ByteArray(8192)
while (isActive) {
val bytesRead = inputStream.read(buffer)
if (bytesRead == -1) break
outputStream.write(buffer, 0, bytesRead)
outputStream.flush()
}
} catch (_: Exception) {
// Соединение закрыто другой стороной — штатное завершение pipe
}
}
}
@@ -1,5 +1,6 @@
package com.freeturn.app.service
import com.freeturn.app.domain.proxy.ProxyServiceState
import com.freeturn.app.domain.proxy.Socks5Server
import android.app.Service
import android.content.Intent
@@ -15,6 +16,7 @@ import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import org.koin.android.ext.android.inject
/**
@@ -32,6 +34,7 @@ class ProxyService : Service() {
private lateinit var speedMonitor: SpeedMonitor
private val prefs: AppPreferences by inject()
private var socks5Server: Socks5Server? = null
override fun onBind(intent: Intent?): IBinder? = null
@@ -56,6 +59,20 @@ class ProxyService : Service() {
isStopped = { controller.isUserStopped },
onSpeed = { notifier.setSpeed(it) },
)
serviceScope.launch {
prefs.hotspotProxyEnabledFlow.collect { enabled ->
if (enabled) {
if (socks5Server == null) {
socks5Server = Socks5Server()
socks5Server?.start()
}
} else {
socks5Server?.stop()
socks5Server = null
}
}
}
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
@@ -109,6 +126,8 @@ class ProxyService : Service() {
notifier.cancelCaptcha()
ProxyServiceState.addLog("Остановка")
controller.destroyProcessAndTunnel()
socks5Server?.stop()
socks5Server = null
serviceScope.cancel()
if (wakeLock?.isHeld == true) wakeLock?.release()
}
@@ -117,6 +117,7 @@ fun AdvancedScreen(
) {
val nerdMode by settingsViewModel.nerdMode.collectAsStateWithLifecycle()
val restartServerOnSwitch by settingsViewModel.restartServerOnSwitch.collectAsStateWithLifecycle()
val hotspotProxyEnabled by settingsViewModel.hotspotProxyEnabled.collectAsStateWithLifecycle()
val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior()
Scaffold(
@@ -154,6 +155,16 @@ fun AdvancedScreen(
)
}
SettingsCard {
SettingsSwitchRow(
title = stringResource(R.string.hotspot_proxy),
subtitle = stringResource(R.string.hotspot_proxy_desc),
iconRes = R.drawable.wifi_tethering_24px,
checked = hotspotProxyEnabled,
onCheckedChange = { settingsViewModel.setHotspotProxyEnabled(it) }
)
}
SettingsCard {
SettingsSwitchRow(
title = stringResource(R.string.restart_server_on_switch),
@@ -80,6 +80,9 @@ class SettingsViewModel(
val nerdMode: StateFlow<Boolean> = prefs.nerdModeFlow
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false)
val hotspotProxyEnabled: StateFlow<Boolean> = prefs.hotspotProxyEnabledFlow
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false)
val serversSnapshot: StateFlow<ServersSnapshot> = prefs.serversSnapshot
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ServersSnapshot())
@@ -147,6 +150,10 @@ class SettingsViewModel(
viewModelScope.launch { prefs.setNerdMode(enabled) }
}
fun setHotspotProxyEnabled(enabled: Boolean) {
viewModelScope.launch { prefs.setHotspotProxyEnabled(enabled) }
}
fun setTgSubscribeShown() {
viewModelScope.launch { prefs.setTgSubscribeShown() }
}
@@ -0,0 +1,10 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="960"
android:viewportHeight="960"
android:tint="?attr/colorControlNormal">
<path
android:fillColor="@android:color/white"
android:pathData="M204,810Q147,755 113.5,680.5Q80,606 80,520Q80,437 111.5,364Q143,291 197,237Q251,183 324,151.5Q397,120 480,120Q563,120 636,151.5Q709,183 763,237Q817,291 848.5,364Q880,437 880,520Q880,606 846.5,681Q813,756 756,810L700,754Q746,710 773,649.5Q800,589 800,520Q800,386 707,293Q614,200 480,200Q346,200 253,293Q160,386 160,520Q160,589 187,649Q214,709 261,753L204,810ZM317,697Q282,664 261,618.5Q240,573 240,520Q240,420 310,350Q380,280 480,280Q580,280 650,350Q720,420 720,520Q720,573 699,619Q678,665 643,697L586,640Q611,617 625.5,586Q640,555 640,520Q640,454 593,407Q546,360 480,360Q414,360 367,407Q320,454 320,520Q320,556 334.5,586.5Q349,617 374,640L317,697ZM423.5,576.5Q400,553 400,520Q400,487 423.5,463.5Q447,440 480,440Q513,440 536.5,463.5Q560,487 560,520Q560,553 536.5,576.5Q513,600 480,600Q447,600 423.5,576.5Z"/>
</vector>
+2
View File
@@ -397,6 +397,8 @@
<string name="settings_advanced_desc">Отладка и диагностика</string>
<string name="nerd_mode">Режим отладки</string>
<string name="nerd_mode_desc">Открывает отладочную информацию: состояние ядра, журнал сервера и подробные логи</string>
<string name="hotspot_proxy">SOCKS5 Hotspot</string>
<string name="hotspot_proxy_desc">Слушать на 0.0.0.0:1080 для раздачи VPN через точку доступа</string>
<string name="restart_server_on_switch">Перезапуск сервера при смене профиля</string>
<string name="restart_server_on_switch_desc">Перезапускать сервер под параметры нового профиля</string>
<string name="nerd_section_title">Отладочная информация</string>