mirror of
https://github.com/permissionlesstech/bitchat-android.git
synced 2026-11-29 08:27:15 +00:00
Merge pull request #1039 from permissionlesstech/claude/fix-tor-bind-retry-port-8c836b
Rebuild Arti proxy when the SOCKS port changes
This commit is contained in:
2 files changed
+166
-20
No files matched your search
@@ -33,7 +33,17 @@ import java.util.concurrent.atomic.AtomicLong
|
||||
*
|
||||
* Based on the original TorManager implementation.
|
||||
*/
|
||||
class ArtiTorManager private constructor() {
|
||||
class ArtiTorManager internal constructor(
|
||||
private val appScope: CoroutineScope = CoroutineScope(Dispatchers.IO + SupervisorJob()),
|
||||
private val proxyFactory: (Application, Int, ArtiLogListener) -> ArtiProxy =
|
||||
{ application, socksPort, logListener ->
|
||||
ArtiProxy.Builder(application)
|
||||
.setSocksPort(socksPort)
|
||||
.setDnsPort(socksPort + 1)
|
||||
.setLogListener(logListener)
|
||||
.build()
|
||||
}
|
||||
) {
|
||||
enum class TorState {
|
||||
OFF,
|
||||
STARTING,
|
||||
@@ -69,8 +79,6 @@ class ArtiTorManager private constructor() {
|
||||
}
|
||||
}
|
||||
|
||||
private val appScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
|
||||
|
||||
@Volatile
|
||||
private var initialized = false
|
||||
@Volatile
|
||||
@@ -78,6 +86,8 @@ class ArtiTorManager private constructor() {
|
||||
@Volatile
|
||||
private var artiProxy: ArtiProxy? = null
|
||||
@Volatile
|
||||
private var artiProxyPort: Int = DEFAULT_SOCKS_PORT
|
||||
@Volatile
|
||||
private var lastMode: TorMode = TorMode.OFF
|
||||
private val applyMutex = Mutex()
|
||||
@Volatile
|
||||
@@ -113,6 +123,17 @@ class ArtiTorManager private constructor() {
|
||||
|
||||
private val stateChangeDeferred = AtomicReference<CompletableDeferred<TorState>?>(null)
|
||||
|
||||
private val artiLogListener = ArtiLogListener { logLine ->
|
||||
val text = logLine ?: return@ArtiLogListener
|
||||
val s = text
|
||||
lastLogTime.set(System.currentTimeMillis())
|
||||
_statusFlow.update { it.copy(lastLogLine = s) }
|
||||
handleArtiLogLine(s)
|
||||
if (_statusFlow.value.bootstrapPercent < 100) {
|
||||
armBootstrapInactivityWatchdog()
|
||||
}
|
||||
}
|
||||
|
||||
fun isProxyEnabled(): Boolean {
|
||||
val s = _statusFlow.value
|
||||
return s.mode != TorMode.OFF && s.running && s.bootstrapPercent >= 100 &&
|
||||
@@ -127,22 +148,7 @@ class ArtiTorManager private constructor() {
|
||||
currentApplication = application
|
||||
TorPreferenceManager.init(application)
|
||||
|
||||
val logListener = ArtiLogListener { logLine ->
|
||||
val text = logLine ?: return@ArtiLogListener
|
||||
val s = text
|
||||
lastLogTime.set(System.currentTimeMillis())
|
||||
_statusFlow.update { it.copy(lastLogLine = s) }
|
||||
handleArtiLogLine(s)
|
||||
if (_statusFlow.value.bootstrapPercent < 100) {
|
||||
armBootstrapInactivityWatchdog()
|
||||
}
|
||||
}
|
||||
|
||||
artiProxy = ArtiProxy.Builder(application)
|
||||
.setSocksPort(currentSocksPort)
|
||||
.setDnsPort(currentSocksPort + 1)
|
||||
.setLogListener(logListener)
|
||||
.build()
|
||||
artiProxy = buildArtiProxy(application)
|
||||
|
||||
val savedMode = TorPreferenceManager.get(application)
|
||||
if (savedMode == TorMode.ON) {
|
||||
@@ -266,7 +272,7 @@ class ArtiTorManager private constructor() {
|
||||
delay(RESTART_DELAY_MS)
|
||||
}
|
||||
|
||||
val proxy = artiProxy ?: run {
|
||||
val proxy = proxyForCurrentPort(application) ?: run {
|
||||
Log.e(TAG, "ArtiProxy not initialized! This should not happen.")
|
||||
_statusFlow.update { it.copy(state = TorState.ERROR) }
|
||||
return
|
||||
@@ -313,6 +319,23 @@ class ArtiTorManager private constructor() {
|
||||
}
|
||||
}
|
||||
|
||||
private fun buildArtiProxy(application: Application): ArtiProxy {
|
||||
val port = currentSocksPort
|
||||
return proxyFactory(application, port, artiLogListener).also { artiProxyPort = port }
|
||||
}
|
||||
|
||||
/**
|
||||
* ArtiProxy fixes its ports at construction, so it must be rebuilt whenever
|
||||
* [currentSocksPort] moves or Tor would bind a different port than [socksAddr].
|
||||
* Call only after the previous proxy has been stopped.
|
||||
*/
|
||||
private fun proxyForCurrentPort(application: Application): ArtiProxy? {
|
||||
if (artiProxy != null && artiProxyPort != currentSocksPort) {
|
||||
artiProxy = buildArtiProxy(application)
|
||||
}
|
||||
return artiProxy
|
||||
}
|
||||
|
||||
private fun isBindError(exception: Exception): Boolean {
|
||||
val message = exception.message?.lowercase() ?: ""
|
||||
return message.contains("bind") ||
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
package com.bitchat.android.net
|
||||
|
||||
import android.app.Application
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import com.bitchat.android.util.AppConstants
|
||||
import info.guardianproject.arti.ArtiException
|
||||
import info.guardianproject.arti.ArtiProxy
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.test.TestScope
|
||||
import kotlinx.coroutines.test.advanceTimeBy
|
||||
import kotlinx.coroutines.test.runCurrent
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.mockito.kotlin.doAnswer
|
||||
import org.mockito.kotlin.mock
|
||||
import org.mockito.kotlin.whenever
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
class ArtiTorManagerBindRetryRobolectricTest {
|
||||
|
||||
private companion object {
|
||||
const val DEFAULT_PORT = AppConstants.Tor.DEFAULT_SOCKS_PORT
|
||||
const val MAX_BIND_RETRIES = AppConstants.Tor.MAX_RETRY_ATTEMPTS
|
||||
|
||||
// init() applies the saved mode twice and each OFF waits out the stop timeout.
|
||||
const val INIT_SETTLE_MS = 2 * AppConstants.Tor.STOP_TIMEOUT_MS + 1
|
||||
}
|
||||
|
||||
private val application: Application = ApplicationProvider.getApplicationContext()
|
||||
private val occupiedPorts = mutableSetOf<Int>()
|
||||
private val startAttempts = mutableListOf<Int>()
|
||||
private var listeningPort: Int? = null
|
||||
|
||||
@Before
|
||||
fun startWithTorOff() {
|
||||
TorPreferenceManager.set(application, TorMode.OFF)
|
||||
}
|
||||
|
||||
@After
|
||||
fun restoreDefaultTorMode() {
|
||||
TorPreferenceManager.set(application, TorMode.ON)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `bind failure moves the listener onto the advertised SOCKS port`() = runTest {
|
||||
occupiedPorts += DEFAULT_PORT
|
||||
|
||||
val manager = managerWithTorOn()
|
||||
|
||||
assertEquals(listOf(DEFAULT_PORT, DEFAULT_PORT + 1), startAttempts)
|
||||
assertEquals(DEFAULT_PORT + 1, listeningPort)
|
||||
assertEquals(listeningPort, manager.currentSocksAddress()?.port)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `tor off and on after a bind failure listens on the advertised default port`() = runTest {
|
||||
occupiedPorts += DEFAULT_PORT
|
||||
val manager = managerWithTorOn()
|
||||
occupiedPorts.clear()
|
||||
|
||||
manager.applyMode(application, TorMode.OFF)
|
||||
assertNull(manager.currentSocksAddress())
|
||||
manager.applyMode(application, TorMode.ON)
|
||||
|
||||
assertEquals(DEFAULT_PORT, listeningPort)
|
||||
assertEquals(DEFAULT_PORT, manager.currentSocksAddress()?.port)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `exhausted bind retries stay fail closed after trying each port once`() = runTest {
|
||||
val triedPorts = (DEFAULT_PORT..DEFAULT_PORT + MAX_BIND_RETRIES).toList()
|
||||
occupiedPorts += triedPorts
|
||||
|
||||
val manager = managerWithTorOn()
|
||||
|
||||
assertEquals(triedPorts, startAttempts)
|
||||
assertNull(listeningPort)
|
||||
assertEquals(ArtiTorManager.TorState.ERROR, manager.statusFlow.value.state)
|
||||
assertFalse(manager.statusFlow.value.running)
|
||||
assertFalse(manager.isProxyEnabled())
|
||||
// A published SOCKS address keeps HTTP clients on the dead proxy instead of going direct.
|
||||
assertNotNull(manager.currentSocksAddress())
|
||||
}
|
||||
|
||||
private suspend fun TestScope.managerWithTorOn(): ArtiTorManager {
|
||||
val manager = ArtiTorManager(
|
||||
appScope = backgroundScope,
|
||||
proxyFactory = { _, socksPort, _ -> fakeProxy(socksPort) }
|
||||
)
|
||||
manager.init(application)
|
||||
advanceTimeBy(INIT_SETTLE_MS)
|
||||
runCurrent()
|
||||
manager.applyMode(application, TorMode.ON)
|
||||
return manager
|
||||
}
|
||||
|
||||
/** Behaves like ArtiProxy: the port is fixed at construction and bound by start(). */
|
||||
private fun fakeProxy(port: Int): ArtiProxy {
|
||||
val proxy = mock<ArtiProxy>()
|
||||
doAnswer {
|
||||
startAttempts += port
|
||||
if (port in occupiedPorts) {
|
||||
throw ArtiException("Failed to bind SOCKS proxy to port $port (port already in use)")
|
||||
}
|
||||
listeningPort = port
|
||||
null
|
||||
}.whenever(proxy).start()
|
||||
doAnswer {
|
||||
if (listeningPort == port) listeningPort = null
|
||||
null
|
||||
}.whenever(proxy).stop()
|
||||
return proxy
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user