feat: replace arti-mobile-ex with custom-built Arti native library
The Guardian Project's arti-mobile-ex AAR has three problems: 1. No 16KB page-aligned binaries (required for Google Play) 2. ArtiProxy's stop()+start() causes state file lock conflicts (lock is tied to TorClient object lifetime, released only on GC) 3. ~140MB AAR size Replace with a custom JNI bridge built from Arti source, following BitChat's proven approach: Build tooling (tools/arti-build/): - build-arti.sh: Clones official Arti, compiles with cargo-ndk for ARM64 + x86_64, NDK 25+ for 16KB page alignment - Cargo.toml: Minimal deps with size-optimized release profile - src/lib.rs: Custom SOCKS5 proxy with proper lifecycle: - initialize() creates TorClient once (holds state lock forever) - startSocksProxy() binds port and accepts connections - stopSocksProxy() aborts listener only (TorClient stays alive) This cleanly separates "stop routing traffic" from "destroy client" Kotlin side: - ArtiNative.kt: JNI declarations + ArtiLogCallback interface - TorService.kt: Uses ArtiNative directly, start() initializes + starts proxy, stop() only stops proxy (no lock issues) - TorManager.kt: Restored stop() calls for OFF/EXTERNAL modes since our native stop is now safe Removed: arti-mobile-ex dependency from build.gradle and version catalog Native libraries must be built separately: cd tools/arti-build && ./build-arti.sh https://claude.ai/code/session_01BApgDd5udqBzMqysSRMpZu
This commit is contained in:
@@ -372,8 +372,6 @@ dependencies {
|
||||
// Kotlin serialization for the times where we need the Json tree and performance is not that important.
|
||||
implementation(libs.kotlinx.serialization.json)
|
||||
|
||||
implementation libs.arti.mobile.ex
|
||||
|
||||
testImplementation libs.junit
|
||||
testImplementation libs.mockk
|
||||
testImplementation libs.kotlinx.coroutines.test
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
/*
|
||||
* Copyright (c) 2025 Vitor Pamplona
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to use,
|
||||
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
|
||||
* Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
|
||||
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package com.vitorpamplona.amethyst.ui.tor
|
||||
|
||||
/**
|
||||
* JNI bridge to the custom-built Arti native library (libarti_android.so).
|
||||
*
|
||||
* The native TorClient is created once via [initialize] and persists for the
|
||||
* app's lifetime — its state file lock is never released until the process exits.
|
||||
*
|
||||
* The SOCKS proxy can be started and stopped independently via [startSocksProxy]
|
||||
* and [stopSocksProxy] without affecting the TorClient.
|
||||
*/
|
||||
object ArtiNative {
|
||||
init {
|
||||
System.loadLibrary("arti_android")
|
||||
}
|
||||
|
||||
external fun getVersion(): String
|
||||
|
||||
external fun setLogCallback(callback: ArtiLogCallback)
|
||||
|
||||
/**
|
||||
* Initialize the Arti runtime and bootstrap the Tor client.
|
||||
* @param dataDir Path to the app's private data directory for Arti state/cache.
|
||||
* @return 0 on success, negative on error.
|
||||
*/
|
||||
external fun initialize(dataDir: String): Int
|
||||
|
||||
/**
|
||||
* Start the SOCKS5 proxy on the given port.
|
||||
* Can be called multiple times — stops any existing listener first.
|
||||
* @return 0 on success, negative on error.
|
||||
*/
|
||||
external fun startSocksProxy(port: Int): Int
|
||||
|
||||
/**
|
||||
* Stop the SOCKS5 proxy listener and release the port.
|
||||
* The TorClient stays alive — no state file lock issues.
|
||||
* @return 0 on success.
|
||||
*/
|
||||
external fun stopSocksProxy(): Int
|
||||
}
|
||||
|
||||
/**
|
||||
* Callback interface for Arti log messages from the native layer.
|
||||
*/
|
||||
fun interface ArtiLogCallback {
|
||||
fun onLogLine(line: String)
|
||||
}
|
||||
@@ -63,10 +63,12 @@ class TorManager(
|
||||
}
|
||||
|
||||
TorType.OFF -> {
|
||||
service.stop()
|
||||
emit(TorServiceStatus.Off)
|
||||
}
|
||||
|
||||
TorType.EXTERNAL -> {
|
||||
service.stop()
|
||||
if (externalSocksPort > 0) {
|
||||
emit(TorServiceStatus.Active(externalSocksPort))
|
||||
} else {
|
||||
|
||||
@@ -22,95 +22,100 @@ package com.vitorpamplona.amethyst.ui.tor
|
||||
|
||||
import android.content.Context
|
||||
import com.vitorpamplona.quartz.utils.Log
|
||||
import info.guardianproject.arti.ArtiLogListener
|
||||
import info.guardianproject.arti.ArtiProxy
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
private const val DEFAULT_SOCKS_PORT = 19050
|
||||
|
||||
/**
|
||||
* Manages a single ArtiProxy instance for the app's lifetime.
|
||||
* Manages the Arti Tor client via custom JNI bindings.
|
||||
*
|
||||
* Arti's state file lock is tied to the TorClient object's lifetime —
|
||||
* it is only released when the object is garbage collected, not when
|
||||
* stop() is called. Calling stop()+start() on ArtiProxy creates a new
|
||||
* internal TorClient that conflicts with the old lock.
|
||||
*
|
||||
* Therefore, ArtiProxy is created and started once. It runs for the
|
||||
* entire process lifetime. When the user turns Tor "off", TorManager
|
||||
* simply stops emitting Active status — no traffic is routed through
|
||||
* the proxy, but the proxy itself stays alive. This is safe because
|
||||
* an idle Arti uses negligible resources and maintains no circuits
|
||||
* when no SOCKS connections are made.
|
||||
* The native TorClient is initialized once and persists for the app's
|
||||
* lifetime — its state file lock is never released until the process exits.
|
||||
* The SOCKS proxy can be started/stopped independently without affecting
|
||||
* the TorClient or its file locks.
|
||||
*/
|
||||
class TorService(
|
||||
val context: Context,
|
||||
) {
|
||||
private val socksPort = DEFAULT_SOCKS_PORT
|
||||
private val bootstrapped = AtomicBoolean(false)
|
||||
private val started = AtomicBoolean(false)
|
||||
private val initialized = AtomicBoolean(false)
|
||||
private val proxyRunning = AtomicBoolean(false)
|
||||
|
||||
private val _status = MutableStateFlow<TorServiceStatus>(TorServiceStatus.Off)
|
||||
val status: StateFlow<TorServiceStatus> = _status.asStateFlow()
|
||||
|
||||
private val logListener =
|
||||
ArtiLogListener { logLine ->
|
||||
val text = logLine ?: return@ArtiLogListener
|
||||
Log.d("TorService") { "Arti: $text" }
|
||||
init {
|
||||
ArtiNative.setLogCallback(
|
||||
ArtiLogCallback { text ->
|
||||
Log.d("TorService") { "Arti: $text" }
|
||||
|
||||
when {
|
||||
text.contains("Sufficiently bootstrapped", ignoreCase = true) ||
|
||||
text.contains("is usable", ignoreCase = true) -> {
|
||||
if (bootstrapped.compareAndSet(false, true)) {
|
||||
when {
|
||||
text.contains("Sufficiently bootstrapped", ignoreCase = true) -> {
|
||||
_status.value = TorServiceStatus.Active(socksPort)
|
||||
Log.d("TorService") { "Arti bootstrapped on port $socksPort" }
|
||||
Log.d("TorService") { "Arti SOCKS proxy active on port $socksPort" }
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
text.contains(
|
||||
"Another process has the lock",
|
||||
ignoreCase = true,
|
||||
) -> {
|
||||
Log.e("TorService") { "Arti state file lock conflict" }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private val artiProxy: ArtiProxy =
|
||||
ArtiProxy
|
||||
.Builder(context.applicationContext)
|
||||
.setSocksPort(socksPort)
|
||||
.setDnsPort(socksPort + 1)
|
||||
.setLogListener(logListener)
|
||||
.build()
|
||||
|
||||
/**
|
||||
* Initialize the TorClient (once) and start the SOCKS proxy.
|
||||
*/
|
||||
suspend fun start() {
|
||||
if (started.get()) {
|
||||
// Already started — just emit current state
|
||||
if (bootstrapped.get()) {
|
||||
_status.value = TorServiceStatus.Active(socksPort)
|
||||
} else {
|
||||
_status.value = TorServiceStatus.Connecting
|
||||
}
|
||||
if (proxyRunning.get()) {
|
||||
if (_status.value is TorServiceStatus.Active) return
|
||||
_status.value = TorServiceStatus.Connecting
|
||||
return
|
||||
}
|
||||
|
||||
_status.value = TorServiceStatus.Connecting
|
||||
|
||||
withContext(Dispatchers.IO) {
|
||||
try {
|
||||
artiProxy.start()
|
||||
started.set(true)
|
||||
Log.d("TorService") { "Arti started on port $socksPort" }
|
||||
} catch (e: Exception) {
|
||||
Log.e("TorService") { "Failed to start Arti: ${e.message}" }
|
||||
_status.value = TorServiceStatus.Off
|
||||
// Initialize TorClient once — this bootstraps the Tor network
|
||||
if (initialized.compareAndSet(false, true)) {
|
||||
val dataDir = File(context.filesDir, "arti").absolutePath
|
||||
Log.d("TorService") { "Initializing Arti with data dir: $dataDir" }
|
||||
|
||||
val initResult = ArtiNative.initialize(dataDir)
|
||||
if (initResult != 0) {
|
||||
Log.e("TorService") { "Failed to initialize Arti: error $initResult" }
|
||||
initialized.set(false)
|
||||
_status.value = TorServiceStatus.Off
|
||||
return@withContext
|
||||
}
|
||||
}
|
||||
|
||||
// Start the SOCKS proxy (can be called multiple times safely)
|
||||
val proxyResult = ArtiNative.startSocksProxy(socksPort)
|
||||
if (proxyResult != 0) {
|
||||
Log.e("TorService") { "Failed to start SOCKS proxy: error $proxyResult" }
|
||||
_status.value = TorServiceStatus.Off
|
||||
return@withContext
|
||||
}
|
||||
|
||||
proxyRunning.set(true)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop the SOCKS proxy and release the port.
|
||||
* The TorClient stays alive — no file lock issues on restart.
|
||||
*/
|
||||
suspend fun stop() {
|
||||
if (!proxyRunning.compareAndSet(true, false)) return
|
||||
|
||||
withContext(Dispatchers.IO) {
|
||||
ArtiNative.stopSocksProxy()
|
||||
Log.d("TorService") { "SOCKS proxy stopped" }
|
||||
}
|
||||
|
||||
_status.value = TorServiceStatus.Off
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user