feat: SOCKS5 hotspot port, auth and UDP
Configurable port, username/password auth and optional UDP ASSOCIATE for the SOCKS5 hotspot
This commit is contained in:
1 parent
52030ecb30
commit
b76a386731
9 files changed
+350
-14
No files matched your search
@@ -1,5 +1,7 @@
|
|||||||
package com.freeturn.app.data
|
package com.freeturn.app.data
|
||||||
|
|
||||||
|
import com.freeturn.app.data.config.Socks5Config
|
||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import androidx.datastore.core.DataStore
|
import androidx.datastore.core.DataStore
|
||||||
import androidx.datastore.core.handlers.ReplaceFileCorruptionHandler
|
import androidx.datastore.core.handlers.ReplaceFileCorruptionHandler
|
||||||
@@ -53,6 +55,11 @@ class AppPreferences(context: Context) {
|
|||||||
val BATTERY_PROMPT_SHOWN = booleanPreferencesKey("battery_prompt_shown")
|
val BATTERY_PROMPT_SHOWN = booleanPreferencesKey("battery_prompt_shown")
|
||||||
val RESTART_SERVER_ON_SWITCH = booleanPreferencesKey("restart_server_on_switch")
|
val RESTART_SERVER_ON_SWITCH = booleanPreferencesKey("restart_server_on_switch")
|
||||||
val HOTSPOT_PROXY = booleanPreferencesKey("hotspot_proxy")
|
val HOTSPOT_PROXY = booleanPreferencesKey("hotspot_proxy")
|
||||||
|
val HOTSPOT_PORT =
|
||||||
|
androidx.datastore.preferences.core.intPreferencesKey("hotspot_port")
|
||||||
|
val HOTSPOT_USER = stringPreferencesKey("hotspot_user")
|
||||||
|
val HOTSPOT_PASS = stringPreferencesKey("hotspot_pass")
|
||||||
|
val HOTSPOT_UDP = booleanPreferencesKey("hotspot_udp")
|
||||||
val SERVERS_JSON = stringPreferencesKey("servers_json")
|
val SERVERS_JSON = stringPreferencesKey("servers_json")
|
||||||
val ACTIVE_SERVER_ID = stringPreferencesKey("active_server_id")
|
val ACTIVE_SERVER_ID = stringPreferencesKey("active_server_id")
|
||||||
val OWN_CLIENT_ID = stringPreferencesKey("own_client_id")
|
val OWN_CLIENT_ID = stringPreferencesKey("own_client_id")
|
||||||
@@ -166,6 +173,18 @@ class AppPreferences(context: Context) {
|
|||||||
// сервера уходят напрямую, и клиенты хотспота получили бы канал мимо туннеля.
|
// сервера уходят напрямую, и клиенты хотспота получили бы канал мимо туннеля.
|
||||||
val hotspotProxyEnabledFlow: Flow<Boolean> = prefFlow { prefs -> prefs[HOTSPOT_PROXY] ?: false }
|
val hotspotProxyEnabledFlow: Flow<Boolean> = prefFlow { prefs -> prefs[HOTSPOT_PROXY] ?: false }
|
||||||
|
|
||||||
|
val hotspotPortFlow: Flow<Int> = prefFlow { prefs -> prefs[HOTSPOT_PORT] ?: 1080 }
|
||||||
|
val hotspotUserFlow: Flow<String> = prefFlow { prefs -> prefs[HOTSPOT_USER] ?: "" }
|
||||||
|
val hotspotPassFlow: Flow<String> = prefFlow { prefs -> prefs[HOTSPOT_PASS] ?: "" }
|
||||||
|
val hotspotUdpFlow: Flow<Boolean> = prefFlow { prefs -> prefs[HOTSPOT_UDP] ?: false }
|
||||||
|
|
||||||
|
suspend fun hotspotConfig(): Socks5Config = Socks5Config(
|
||||||
|
port = hotspotPortFlow.first(),
|
||||||
|
user = hotspotUserFlow.first(),
|
||||||
|
pass = hotspotPassFlow.first(),
|
||||||
|
udp = hotspotUdpFlow.first(),
|
||||||
|
)
|
||||||
|
|
||||||
val tgSubscribeShownFlow: Flow<Boolean> = prefFlow { prefs -> prefs[TG_SUBSCRIBE_SHOWN] ?: false }
|
val tgSubscribeShownFlow: Flow<Boolean> = prefFlow { prefs -> prefs[TG_SUBSCRIBE_SHOWN] ?: false }
|
||||||
|
|
||||||
val suppressUpdatePromptFlow: Flow<Boolean> = prefFlow { prefs -> prefs[SUPPRESS_UPDATE_PROMPT] ?: false }
|
val suppressUpdatePromptFlow: Flow<Boolean> = prefFlow { prefs -> prefs[SUPPRESS_UPDATE_PROMPT] ?: false }
|
||||||
@@ -342,6 +361,21 @@ class AppPreferences(context: Context) {
|
|||||||
context.dataStore.edit { it[HOTSPOT_PROXY] = enabled }
|
context.dataStore.edit { it[HOTSPOT_PROXY] = enabled }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
suspend fun setHotspotPort(port: Int) {
|
||||||
|
context.dataStore.edit { it[HOTSPOT_PORT] = port }
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun setHotspotAuth(user: String, pass: String) {
|
||||||
|
context.dataStore.edit {
|
||||||
|
it[HOTSPOT_USER] = user
|
||||||
|
it[HOTSPOT_PASS] = pass
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun setHotspotUdp(enabled: Boolean) {
|
||||||
|
context.dataStore.edit { it[HOTSPOT_UDP] = enabled }
|
||||||
|
}
|
||||||
|
|
||||||
suspend fun setTgSubscribeShown() {
|
suspend fun setTgSubscribeShown() {
|
||||||
context.dataStore.edit { prefs -> prefs[TG_SUBSCRIBE_SHOWN] = true }
|
context.dataStore.edit { prefs -> prefs[TG_SUBSCRIBE_SHOWN] = true }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package com.freeturn.app.data.config
|
||||||
|
|
||||||
|
/** Параметры SOCKS5-раздачи. Пустой [user] - без авторизации. */
|
||||||
|
data class Socks5Config(
|
||||||
|
val port: Int = 1080,
|
||||||
|
val user: String = "",
|
||||||
|
val pass: String = "",
|
||||||
|
val udp: Boolean = false,
|
||||||
|
) {
|
||||||
|
val authEnabled: Boolean get() = user.isNotEmpty()
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.freeturn.app.domain.proxy
|
package com.freeturn.app.domain.proxy
|
||||||
|
|
||||||
|
import com.freeturn.app.data.config.Socks5Config
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.SupervisorJob
|
import kotlinx.coroutines.SupervisorJob
|
||||||
import kotlinx.coroutines.asCoroutineDispatcher
|
import kotlinx.coroutines.asCoroutineDispatcher
|
||||||
@@ -11,6 +12,8 @@ import java.io.EOFException
|
|||||||
import java.io.InputStream
|
import java.io.InputStream
|
||||||
import java.io.OutputStream
|
import java.io.OutputStream
|
||||||
import java.net.ConnectException
|
import java.net.ConnectException
|
||||||
|
import java.net.DatagramPacket
|
||||||
|
import java.net.DatagramSocket
|
||||||
import java.net.InetAddress
|
import java.net.InetAddress
|
||||||
import java.net.InetSocketAddress
|
import java.net.InetSocketAddress
|
||||||
import java.net.NoRouteToHostException
|
import java.net.NoRouteToHostException
|
||||||
@@ -19,6 +22,7 @@ import java.net.Socket
|
|||||||
import java.net.SocketTimeoutException
|
import java.net.SocketTimeoutException
|
||||||
import java.net.UnknownHostException
|
import java.net.UnknownHostException
|
||||||
import java.nio.charset.StandardCharsets
|
import java.nio.charset.StandardCharsets
|
||||||
|
import java.security.MessageDigest
|
||||||
import java.util.concurrent.ConcurrentHashMap
|
import java.util.concurrent.ConcurrentHashMap
|
||||||
import java.util.concurrent.Executors
|
import java.util.concurrent.Executors
|
||||||
import java.util.concurrent.atomic.AtomicInteger
|
import java.util.concurrent.atomic.AtomicInteger
|
||||||
@@ -26,14 +30,14 @@ import kotlin.coroutines.coroutineContext
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* SOCKS5 (RFC 1928) для раздачи туннеля наружу - через точку доступа или по локальной
|
* SOCKS5 (RFC 1928) для раздачи туннеля наружу - через точку доступа или по локальной
|
||||||
* сети. Только CONNECT: UDP ASSOCIATE не реализован, поэтому у клиентов нет QUIC и
|
* сети. CONNECT и (по настройке) UDP ASSOCIATE: без него у клиентов нет QUIC и
|
||||||
* UDP-DNS - им нужен remote DNS через сам прокси.
|
* UDP-DNS - им нужен remote DNS через сам прокси.
|
||||||
*
|
*
|
||||||
* Имеет смысл только в туннельном режиме. Сокеты к цели намеренно НЕ выводятся из
|
* Имеет смысл только в туннельном режиме. Сокеты к цели намеренно НЕ выводятся из
|
||||||
* VPN - именно они и должны уйти в tun; наружу выводится обратный канал к клиенту
|
* VPN - именно они и должны уйти в tun; наружу выводится обратный канал к клиенту
|
||||||
* ([protect]), иначе ответы в локальную сеть уехали бы в туннель.
|
* ([protect]), иначе ответы в локальную сеть уехали бы в туннель.
|
||||||
*
|
*
|
||||||
* Слушает 0.0.0.0 без авторизации: открыт всей локальной сети, не только клиентам
|
* Слушает 0.0.0.0, по умолчанию без авторизации: открыт всей локальной сети, не только клиентам
|
||||||
* точки доступа. Цели на самом телефоне (loopback) закрыты.
|
* точки доступа. Цели на самом телефоне (loopback) закрыты.
|
||||||
*
|
*
|
||||||
* Одноразовый: после [stop] экземпляр не перезапускается.
|
* Одноразовый: после [stop] экземпляр не перезапускается.
|
||||||
@@ -41,8 +45,14 @@ import kotlin.coroutines.coroutineContext
|
|||||||
class Socks5Server(
|
class Socks5Server(
|
||||||
private val protect: (Socket) -> Boolean,
|
private val protect: (Socket) -> Boolean,
|
||||||
private val log: ProxyLog,
|
private val log: ProxyLog,
|
||||||
private val port: Int = DEFAULT_PORT,
|
private val config: Socks5Config = Socks5Config(),
|
||||||
|
private val protectUdp: (DatagramSocket) -> Boolean = { true },
|
||||||
) {
|
) {
|
||||||
|
private val port = config.port
|
||||||
|
private val modeLabel: String
|
||||||
|
get() = (if (config.udp) "TCP+UDP" else "только TCP") +
|
||||||
|
(if (config.authEnabled) ", с паролем" else ", без пароля")
|
||||||
|
|
||||||
private val executor = Executors.newCachedThreadPool()
|
private val executor = Executors.newCachedThreadPool()
|
||||||
private val scope = CoroutineScope(executor.asCoroutineDispatcher() + SupervisorJob())
|
private val scope = CoroutineScope(executor.asCoroutineDispatcher() + SupervisorJob())
|
||||||
private val sockets = ConcurrentHashMap.newKeySet<Socket>()
|
private val sockets = ConcurrentHashMap.newKeySet<Socket>()
|
||||||
@@ -64,7 +74,7 @@ class Socks5Server(
|
|||||||
}
|
}
|
||||||
serverSocket = socket
|
serverSocket = socket
|
||||||
scope.launch { acceptLoop(socket) }
|
scope.launch { acceptLoop(socket) }
|
||||||
log.add("SOCKS5: раздача туннеля на $BIND_ADDRESS:$port (только TCP)")
|
log.add("SOCKS5: раздача туннеля на $BIND_ADDRESS:$port ($modeLabel)")
|
||||||
}
|
}
|
||||||
|
|
||||||
@Synchronized
|
@Synchronized
|
||||||
@@ -123,7 +133,8 @@ class Socks5Server(
|
|||||||
input.readByte() // RSV
|
input.readByte() // RSV
|
||||||
val addressType = input.readByte()
|
val addressType = input.readByte()
|
||||||
|
|
||||||
if (command != CMD_CONNECT) {
|
val isUdp = command == CMD_UDP_ASSOCIATE && config.udp
|
||||||
|
if (command != CMD_CONNECT && !isUdp) {
|
||||||
sendReply(output, REPLY_COMMAND_NOT_SUPPORTED)
|
sendReply(output, REPLY_COMMAND_NOT_SUPPORTED)
|
||||||
return@coroutineScope
|
return@coroutineScope
|
||||||
}
|
}
|
||||||
@@ -133,6 +144,11 @@ class Socks5Server(
|
|||||||
sendReply(output, REPLY_ADDRESS_TYPE_NOT_SUPPORTED)
|
sendReply(output, REPLY_ADDRESS_TYPE_NOT_SUPPORTED)
|
||||||
return@coroutineScope
|
return@coroutineScope
|
||||||
}
|
}
|
||||||
|
if (isUdp) {
|
||||||
|
readPort(input)
|
||||||
|
handleUdp(client, input, output)
|
||||||
|
return@coroutineScope
|
||||||
|
}
|
||||||
val address = InetSocketAddress(host, readPort(input))
|
val address = InetSocketAddress(host, readPort(input))
|
||||||
val ip = address.address
|
val ip = address.address
|
||||||
if (ip != null && (ip.isLoopbackAddress || ip.isAnyLocalAddress)) {
|
if (ip != null && (ip.isLoopbackAddress || ip.isAnyLocalAddress)) {
|
||||||
@@ -167,23 +183,128 @@ class Socks5Server(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* UDP ASSOCIATE (RFC 1928, п. 7). Релей живёт, пока открыто управляющее
|
||||||
|
* TCP-соединение. Датаграммы принимаются только с IP клиента, фрагменты
|
||||||
|
* отбрасываются. Сокет к клиенту выведен из туннеля ([protectUdp]), сокет к
|
||||||
|
* целям - нет: именно он должен уйти в tun.
|
||||||
|
*/
|
||||||
|
private suspend fun handleUdp(
|
||||||
|
client: Socket,
|
||||||
|
input: InputStream,
|
||||||
|
output: OutputStream,
|
||||||
|
) = coroutineScope {
|
||||||
|
val clientIp = client.inetAddress
|
||||||
|
val local = client.localAddress
|
||||||
|
val relay = DatagramSocket(InetSocketAddress(local, 0))
|
||||||
|
val outbound = DatagramSocket()
|
||||||
|
try {
|
||||||
|
if (!protectUdp(relay)) {
|
||||||
|
log.add("SOCKS5: protect UDP отклонён", LogLevel.Warning)
|
||||||
|
sendReply(output, REPLY_GENERAL_FAILURE)
|
||||||
|
return@coroutineScope
|
||||||
|
}
|
||||||
|
val reply = Socks5Udp.header(local, relay.localPort)
|
||||||
|
reply[0] = VERSION.toByte()
|
||||||
|
output.write(reply)
|
||||||
|
output.flush()
|
||||||
|
client.soTimeout = 0
|
||||||
|
val clientPort = AtomicInteger(0)
|
||||||
|
launch { relayUp(relay, outbound, clientIp, clientPort) }
|
||||||
|
launch { relayDown(relay, outbound, clientIp, clientPort) }
|
||||||
|
// Конец управляющего соединения закрывает ассоциацию.
|
||||||
|
while (input.read() != -1) {
|
||||||
|
// данные игнорируются
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
relay.close()
|
||||||
|
outbound.close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun relayUp(
|
||||||
|
relay: DatagramSocket,
|
||||||
|
outbound: DatagramSocket,
|
||||||
|
clientIp: InetAddress,
|
||||||
|
clientPort: AtomicInteger,
|
||||||
|
) {
|
||||||
|
val buf = ByteArray(UDP_BUFFER)
|
||||||
|
val packet = DatagramPacket(buf, buf.size)
|
||||||
|
try {
|
||||||
|
while (true) {
|
||||||
|
packet.length = buf.size
|
||||||
|
relay.receive(packet)
|
||||||
|
if (packet.address != clientIp) continue
|
||||||
|
clientPort.set(packet.port)
|
||||||
|
val head = Socks5Udp.parse(buf, packet.length) ?: continue
|
||||||
|
val ip = try {
|
||||||
|
InetAddress.getByName(head.host)
|
||||||
|
} catch (_: Exception) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if (ip.isLoopbackAddress || ip.isAnyLocalAddress) continue
|
||||||
|
val size = packet.length - head.dataOffset
|
||||||
|
outbound.send(DatagramPacket(buf, head.dataOffset, size, ip, head.port))
|
||||||
|
}
|
||||||
|
} catch (_: Exception) {
|
||||||
|
// сокет закрыт - штатный выход
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun relayDown(
|
||||||
|
relay: DatagramSocket,
|
||||||
|
outbound: DatagramSocket,
|
||||||
|
clientIp: InetAddress,
|
||||||
|
clientPort: AtomicInteger,
|
||||||
|
) {
|
||||||
|
val buf = ByteArray(UDP_BUFFER)
|
||||||
|
val packet = DatagramPacket(buf, buf.size)
|
||||||
|
try {
|
||||||
|
while (true) {
|
||||||
|
packet.length = buf.size
|
||||||
|
outbound.receive(packet)
|
||||||
|
val port = clientPort.get()
|
||||||
|
if (port == 0) continue
|
||||||
|
val head = Socks5Udp.header(packet.address, packet.port)
|
||||||
|
val out = head + buf.copyOfRange(0, packet.length)
|
||||||
|
relay.send(DatagramPacket(out, out.size, clientIp, port))
|
||||||
|
}
|
||||||
|
} catch (_: Exception) {
|
||||||
|
// сокет закрыт - штатный выход
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun track(socket: Socket) {
|
private fun track(socket: Socket) {
|
||||||
sockets.add(socket)
|
sockets.add(socket)
|
||||||
if (serverSocket == null) socket.closeQuietly()
|
if (serverSocket == null) socket.closeQuietly()
|
||||||
}
|
}
|
||||||
|
|
||||||
/** false - клиент не предложил "без авторизации" либо поздоровался не по протоколу. */
|
/** false - нет подходящего метода, неверный пароль либо не по протоколу. */
|
||||||
private fun negotiate(input: InputStream, output: OutputStream): Boolean {
|
private fun negotiate(input: InputStream, output: OutputStream): Boolean {
|
||||||
if (input.readByte() != VERSION) return false
|
if (input.readByte() != VERSION) return false
|
||||||
val methodCount = input.readByte()
|
val methodCount = input.readByte()
|
||||||
if (methodCount <= 0) return false
|
if (methodCount <= 0) return false
|
||||||
val methods = input.readExactly(methodCount)
|
val methods = input.readExactly(methodCount)
|
||||||
if (methods.none { it.toInt() and 0xFF == METHOD_NO_AUTH }) {
|
val wanted = if (config.authEnabled) METHOD_USER_PASS else METHOD_NO_AUTH
|
||||||
|
if (methods.none { it.toInt() and 0xFF == wanted }) {
|
||||||
output.writeBytes(VERSION, METHOD_NONE_ACCEPTABLE)
|
output.writeBytes(VERSION, METHOD_NONE_ACCEPTABLE)
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
output.writeBytes(VERSION, METHOD_NO_AUTH)
|
output.writeBytes(VERSION, wanted)
|
||||||
return true
|
return !config.authEnabled || authenticate(input, output)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** RFC 1929: VER=1, ULEN, UNAME, PLEN, PASSWD. Сравнение за постоянное время. */
|
||||||
|
private fun authenticate(input: InputStream, output: OutputStream): Boolean {
|
||||||
|
if (input.readByte() != AUTH_VERSION) return false
|
||||||
|
val user = input.readExactly(input.readByte())
|
||||||
|
val pass = input.readExactly(input.readByte())
|
||||||
|
val userOk = MessageDigest.isEqual(user, config.user.toByteArray(Charsets.UTF_8))
|
||||||
|
val passOk = MessageDigest.isEqual(pass, config.pass.toByteArray(Charsets.UTF_8))
|
||||||
|
val ok = userOk and passOk
|
||||||
|
output.writeBytes(AUTH_VERSION, if (ok) 0 else 1)
|
||||||
|
if (!ok) Thread.sleep(AUTH_FAIL_DELAY_MS)
|
||||||
|
return ok
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun readHost(input: InputStream, addressType: Int): String? = when (addressType) {
|
private fun readHost(input: InputStream, addressType: Int): String? = when (addressType) {
|
||||||
@@ -248,8 +369,13 @@ class Socks5Server(
|
|||||||
|
|
||||||
private const val VERSION = 5
|
private const val VERSION = 5
|
||||||
private const val METHOD_NO_AUTH = 0x00
|
private const val METHOD_NO_AUTH = 0x00
|
||||||
|
private const val METHOD_USER_PASS = 0x02
|
||||||
|
private const val AUTH_VERSION = 1
|
||||||
|
private const val AUTH_FAIL_DELAY_MS = 500L
|
||||||
|
private const val UDP_BUFFER = 65535
|
||||||
private const val METHOD_NONE_ACCEPTABLE = 0xFF
|
private const val METHOD_NONE_ACCEPTABLE = 0xFF
|
||||||
private const val CMD_CONNECT = 0x01
|
private const val CMD_CONNECT = 0x01
|
||||||
|
private const val CMD_UDP_ASSOCIATE = 0x03
|
||||||
private const val ATYP_IPV4 = 0x01
|
private const val ATYP_IPV4 = 0x01
|
||||||
private const val ATYP_DOMAIN = 0x03
|
private const val ATYP_DOMAIN = 0x03
|
||||||
private const val ATYP_IPV6 = 0x04
|
private const val ATYP_IPV6 = 0x04
|
||||||
@@ -289,3 +415,51 @@ private fun OutputStream.writeBytes(vararg values: Int) {
|
|||||||
write(ByteArray(values.size) { values[it].toByte() })
|
write(ByteArray(values.size) { values[it].toByte() })
|
||||||
flush()
|
flush()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Заголовок SOCKS5 UDP (RFC 1928, п. 7): RSV(2) FRAG ATYP ADDR PORT DATA. */
|
||||||
|
internal object Socks5Udp {
|
||||||
|
private const val ATYP_IPV4 = 1
|
||||||
|
private const val ATYP_DOMAIN = 3
|
||||||
|
private const val ATYP_IPV6 = 4
|
||||||
|
|
||||||
|
class Header(val host: String, val port: Int, val dataOffset: Int)
|
||||||
|
|
||||||
|
/** null - фрагмент, обрезанный пакет или неизвестный тип адреса. */
|
||||||
|
fun parse(buf: ByteArray, length: Int): Header? {
|
||||||
|
if (length < 4 || buf[2].toInt() != 0) return null
|
||||||
|
var pos = 4
|
||||||
|
val atyp = buf[3].toInt() and 0xFF
|
||||||
|
val host: String = when (atyp) {
|
||||||
|
ATYP_IPV4, ATYP_IPV6 -> {
|
||||||
|
val size = if (atyp == ATYP_IPV4) 4 else 16
|
||||||
|
if (length < pos + size + 2) return null
|
||||||
|
val addr = InetAddress.getByAddress(buf.copyOfRange(pos, pos + size))
|
||||||
|
pos += size
|
||||||
|
addr.hostAddress ?: return null
|
||||||
|
}
|
||||||
|
ATYP_DOMAIN -> {
|
||||||
|
if (length < pos + 1) return null
|
||||||
|
val n = buf[pos].toInt() and 0xFF
|
||||||
|
pos += 1
|
||||||
|
if (n == 0 || length < pos + n + 2) return null
|
||||||
|
val name = String(buf, pos, n, StandardCharsets.US_ASCII)
|
||||||
|
pos += n
|
||||||
|
name
|
||||||
|
}
|
||||||
|
else -> return null
|
||||||
|
}
|
||||||
|
val port = ((buf[pos].toInt() and 0xFF) shl 8) or (buf[pos + 1].toInt() and 0xFF)
|
||||||
|
return Header(host, port, pos + 2)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Заголовок ответа: 0 0 0 ATYP ADDR PORT (первый байт для TCP-ответа - версия). */
|
||||||
|
fun header(source: InetAddress, port: Int): ByteArray {
|
||||||
|
val addr = source.address
|
||||||
|
val out = ByteArray(6 + addr.size)
|
||||||
|
out[3] = (if (addr.size == 4) ATYP_IPV4 else ATYP_IPV6).toByte()
|
||||||
|
addr.copyInto(out, 4)
|
||||||
|
out[4 + addr.size] = (port shr 8).toByte()
|
||||||
|
out[5 + addr.size] = port.toByte()
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
package com.freeturn.app.service
|
package com.freeturn.app.service
|
||||||
|
|
||||||
|
import com.freeturn.app.data.config.Socks5Config
|
||||||
|
|
||||||
import android.content.BroadcastReceiver
|
import android.content.BroadcastReceiver
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
@@ -256,7 +258,7 @@ class ProxyService : VpnService() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
log.add("Сессия $session: запуск принят ядром")
|
log.add("Сессия $session: запуск принят ядром")
|
||||||
if (hotspot) startHotspot(session)
|
if (hotspot) startHotspot(session, prefs.hotspotConfig())
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -264,12 +266,17 @@ class ProxyService : VpnService() {
|
|||||||
* заявку, а пока оно поднималось, её могли отменить.
|
* заявку, а пока оно поднималось, её могли отменить.
|
||||||
*/
|
*/
|
||||||
@Synchronized
|
@Synchronized
|
||||||
private fun startHotspot(session: Long) {
|
private fun startHotspot(session: Long, cfg: Socks5Config) {
|
||||||
if (!isCurrent(session)) return
|
if (!isCurrent(session)) return
|
||||||
// Порт занимает ровно один сервер: потерянный тут экземпляр держал бы 1080 до
|
// Порт занимает ровно один сервер: потерянный тут экземпляр держал бы 1080 до
|
||||||
// смерти процесса.
|
// смерти процесса.
|
||||||
socks5?.stop()
|
socks5?.stop()
|
||||||
socks5 = Socks5Server(protect = { socket -> protect(socket) }, log = log).also { it.start() }
|
socks5 = Socks5Server(
|
||||||
|
protect = { socket -> protect(socket) },
|
||||||
|
log = log,
|
||||||
|
config = cfg,
|
||||||
|
protectUdp = { socket -> protect(socket) },
|
||||||
|
).also { it.start() }
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Исход попытки поднять tun. Судьбу сессии решает вызывающий, а не сама попытка. */
|
/** Исход попытки поднять tun. Судьбу сессии решает вызывающий, а не сама попытка. */
|
||||||
|
|||||||
@@ -0,0 +1,77 @@
|
|||||||
|
package com.freeturn.app.ui.screens.settings
|
||||||
|
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.produceState
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import com.freeturn.app.R
|
||||||
|
import com.freeturn.app.data.config.Socks5Config
|
||||||
|
import com.freeturn.app.ui.components.LabeledTextField
|
||||||
|
import com.freeturn.app.ui.components.SettingsCard
|
||||||
|
import com.freeturn.app.ui.components.SettingsSwitchRow
|
||||||
|
import com.freeturn.app.ui.theme.Spacing
|
||||||
|
import com.freeturn.app.viewmodel.settings.SettingsViewModel
|
||||||
|
|
||||||
|
/** Порт, логин/пароль и UDP для SOCKS5 Hotspot. Применяется со следующего запуска. */
|
||||||
|
@Composable
|
||||||
|
fun HotspotOptionsCard(vm: SettingsViewModel) {
|
||||||
|
val saved by produceState<Socks5Config?>(null) { value = vm.hotspotConfig() }
|
||||||
|
val cfg = saved ?: return
|
||||||
|
var portText by remember { mutableStateOf(cfg.port.toString()) }
|
||||||
|
var user by remember { mutableStateOf(cfg.user) }
|
||||||
|
var pass by remember { mutableStateOf(cfg.pass) }
|
||||||
|
var udp by remember { mutableStateOf(cfg.udp) }
|
||||||
|
val portOk = portText.toIntOrNull()?.let { it in 1024..65535 } == true
|
||||||
|
SettingsCard {
|
||||||
|
Column(
|
||||||
|
modifier = Modifier.padding(Spacing.md),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(Spacing.md)
|
||||||
|
) {
|
||||||
|
LabeledTextField(
|
||||||
|
value = portText,
|
||||||
|
onValueChange = { text ->
|
||||||
|
portText = text.filter { it.isDigit() }.take(5)
|
||||||
|
portText.toIntOrNull()
|
||||||
|
?.takeIf { it in 1024..65535 }
|
||||||
|
?.let { vm.setHotspotPort(it) }
|
||||||
|
},
|
||||||
|
labelRes = R.string.hotspot_port,
|
||||||
|
supportingRes = R.string.hotspot_port_hint,
|
||||||
|
isError = !portOk,
|
||||||
|
)
|
||||||
|
LabeledTextField(
|
||||||
|
value = user,
|
||||||
|
onValueChange = {
|
||||||
|
user = it
|
||||||
|
vm.setHotspotAuth(user, pass)
|
||||||
|
},
|
||||||
|
labelRes = R.string.hotspot_user,
|
||||||
|
supportingRes = R.string.hotspot_auth_hint,
|
||||||
|
)
|
||||||
|
LabeledTextField(
|
||||||
|
value = pass,
|
||||||
|
onValueChange = {
|
||||||
|
pass = it
|
||||||
|
vm.setHotspotAuth(user, pass)
|
||||||
|
},
|
||||||
|
labelRes = R.string.hotspot_pass,
|
||||||
|
)
|
||||||
|
SettingsSwitchRow(
|
||||||
|
title = stringResource(R.string.hotspot_udp),
|
||||||
|
subtitle = stringResource(R.string.hotspot_udp_desc),
|
||||||
|
checked = udp,
|
||||||
|
onCheckedChange = {
|
||||||
|
udp = it
|
||||||
|
vm.setHotspotUdp(it)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -168,6 +168,9 @@ fun AdvancedScreen(
|
|||||||
onCheckedChange = { settingsViewModel.setHotspotProxyEnabled(it) }
|
onCheckedChange = { settingsViewModel.setHotspotProxyEnabled(it) }
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
if (hotspotProxyEnabled) {
|
||||||
|
HotspotOptionsCard(settingsViewModel)
|
||||||
|
}
|
||||||
|
|
||||||
SettingsCard {
|
SettingsCard {
|
||||||
SettingsSwitchRow(
|
SettingsSwitchRow(
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
package com.freeturn.app.viewmodel.settings
|
package com.freeturn.app.viewmodel.settings
|
||||||
|
|
||||||
|
import com.freeturn.app.data.config.Socks5Config
|
||||||
|
|
||||||
import androidx.lifecycle.ViewModel
|
import androidx.lifecycle.ViewModel
|
||||||
import androidx.lifecycle.viewModelScope
|
import androidx.lifecycle.viewModelScope
|
||||||
import com.freeturn.app.data.AppPreferences
|
import com.freeturn.app.data.AppPreferences
|
||||||
@@ -92,6 +94,20 @@ class SettingsViewModel(
|
|||||||
viewModelScope.launch { prefs.setHotspotProxyEnabled(enabled) }
|
viewModelScope.launch { prefs.setHotspotProxyEnabled(enabled) }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
suspend fun hotspotConfig(): Socks5Config = prefs.hotspotConfig()
|
||||||
|
|
||||||
|
fun setHotspotPort(port: Int) {
|
||||||
|
viewModelScope.launch { prefs.setHotspotPort(port) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setHotspotAuth(user: String, pass: String) {
|
||||||
|
viewModelScope.launch { prefs.setHotspotAuth(user, pass) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setHotspotUdp(enabled: Boolean) {
|
||||||
|
viewModelScope.launch { prefs.setHotspotUdp(enabled) }
|
||||||
|
}
|
||||||
|
|
||||||
fun setDynamicTheme(enabled: Boolean) {
|
fun setDynamicTheme(enabled: Boolean) {
|
||||||
viewModelScope.launch { prefs.setDynamicTheme(enabled) }
|
viewModelScope.launch { prefs.setDynamicTheme(enabled) }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -387,10 +387,17 @@
|
|||||||
<string name="settings_advanced_desc">Debugging and diagnostics</string>
|
<string name="settings_advanced_desc">Debugging and diagnostics</string>
|
||||||
<string name="nerd_mode">Debug mode</string>
|
<string name="nerd_mode">Debug mode</string>
|
||||||
<string name="nerd_mode_desc">Shows debug info: core state, server journal and verbose logs</string>
|
<string name="nerd_mode_desc">Shows debug info: core state, server journal and verbose logs</string>
|
||||||
<string name="hotspot_proxy_desc">Listen on 0.0.0.0:1080 to share the WireGuard tunnel over a hotspot</string>
|
<string name="hotspot_proxy_desc">Listen on 0.0.0.0 to share the WireGuard tunnel over a hotspot</string>
|
||||||
<string name="restart_server_on_switch">Restart server on profile switch</string>
|
<string name="restart_server_on_switch">Restart server on profile switch</string>
|
||||||
<string name="restart_server_on_switch_desc">Restart the server with the new profile parameters</string>
|
<string name="restart_server_on_switch_desc">Restart the server with the new profile parameters</string>
|
||||||
<string name="external_control_hint">Turn on External control in settings, otherwise the shortcut will not work</string>
|
<string name="external_control_hint">Turn on External control in settings, otherwise the shortcut will not work</string>
|
||||||
|
<string name="hotspot_port">Port</string>
|
||||||
|
<string name="hotspot_port_hint">1024-65535, applied on next start</string>
|
||||||
|
<string name="hotspot_user">Username</string>
|
||||||
|
<string name="hotspot_pass">Password</string>
|
||||||
|
<string name="hotspot_auth_hint">Empty username - no authentication</string>
|
||||||
|
<string name="hotspot_udp">UDP over SOCKS5</string>
|
||||||
|
<string name="hotspot_udp_desc">UDP ASSOCIATE for QUIC and UDP DNS. Without a username and password, UDP is open to the whole local network</string>
|
||||||
<string name="external_control">External control</string>
|
<string name="external_control">External control</string>
|
||||||
<string name="external_control_desc">Let Tasker, MacroDroid and other apps start and stop the proxy. Enable only if you trust your installed apps</string>
|
<string name="external_control_desc">Let Tasker, MacroDroid and other apps start and stop the proxy. Enable only if you trust your installed apps</string>
|
||||||
<string name="nerd_section_title">Debug info</string>
|
<string name="nerd_section_title">Debug info</string>
|
||||||
|
|||||||
@@ -417,10 +417,17 @@
|
|||||||
<string name="nerd_mode">Режим отладки</string>
|
<string name="nerd_mode">Режим отладки</string>
|
||||||
<string name="nerd_mode_desc">Открывает отладочную информацию: состояние ядра, журнал сервера и подробные логи</string>
|
<string name="nerd_mode_desc">Открывает отладочную информацию: состояние ядра, журнал сервера и подробные логи</string>
|
||||||
<string name="hotspot_proxy" translatable="false">SOCKS5 Hotspot</string>
|
<string name="hotspot_proxy" translatable="false">SOCKS5 Hotspot</string>
|
||||||
<string name="hotspot_proxy_desc">Слушать на 0.0.0.0:1080 для раздачи WireGuard-туннеля через точку доступа</string>
|
<string name="hotspot_proxy_desc">Слушать на 0.0.0.0 для раздачи WireGuard-туннеля через точку доступа</string>
|
||||||
<string name="restart_server_on_switch">Перезапуск сервера при смене профиля</string>
|
<string name="restart_server_on_switch">Перезапуск сервера при смене профиля</string>
|
||||||
<string name="restart_server_on_switch_desc">Перезапускать сервер под параметры нового профиля</string>
|
<string name="restart_server_on_switch_desc">Перезапускать сервер под параметры нового профиля</string>
|
||||||
<string name="external_control_hint">Включите «Внешнее управление» в настройках, иначе ярлык не сработает</string>
|
<string name="external_control_hint">Включите «Внешнее управление» в настройках, иначе ярлык не сработает</string>
|
||||||
|
<string name="hotspot_port">Порт</string>
|
||||||
|
<string name="hotspot_port_hint">1024-65535, применится при следующем запуске</string>
|
||||||
|
<string name="hotspot_user">Логин</string>
|
||||||
|
<string name="hotspot_pass">Пароль</string>
|
||||||
|
<string name="hotspot_auth_hint">Пустой логин - без авторизации</string>
|
||||||
|
<string name="hotspot_udp">UDP через SOCKS5</string>
|
||||||
|
<string name="hotspot_udp_desc">UDP ASSOCIATE для QUIC и UDP-DNS. Без логина и пароля UDP открыт всей локальной сети</string>
|
||||||
<string name="external_control">Внешнее управление</string>
|
<string name="external_control">Внешнее управление</string>
|
||||||
<string name="external_control_desc">Разрешить Tasker, MacroDroid и другим приложениям запускать и останавливать прокси. Включайте, только если доверяете установленным приложениям</string>
|
<string name="external_control_desc">Разрешить Tasker, MacroDroid и другим приложениям запускать и останавливать прокси. Включайте, только если доверяете установленным приложениям</string>
|
||||||
<string name="nerd_section_title">Отладочная информация</string>
|
<string name="nerd_section_title">Отладочная информация</string>
|
||||||
|
|||||||
Reference in new issue
Block a user