Verify Android proxy egress before reporting connected

This commit is contained in:
UCVL Software Automation
2026-11-15 22:08:40 +08:00
parent 35f2d3b4e7
commit 9c122a8913
12 changed files with 249 additions and 25 deletions
+3 -1
View File
@@ -1,6 +1,8 @@
# 纵横家 Android 客户端 # 纵横家 Android 客户端
版本 `1.0.7`;包名 `cn.toplc.zonghengjia`。这是公司 Android 客户端的 GPL-3.0 衍生源码,不包含服务器端、账号、节点凭据或公司签名私钥。发布状态以公司安装包仓库的同版正式 Release 为准。 版本 `1.0.8`;包名 `cn.toplc.zonghengjia`。这是公司 Android 客户端的 GPL-3.0 衍生源码,不包含服务器端、账号、节点凭据或公司签名私钥。发布状态以公司安装包仓库的同版正式 Release 为准。
1.0.8 启动 Android VPN 后,先通过已授权的代理出口完成 HTTPS 验证,再显示已连接。第一个检查站点失败时改用独立站点。验证中可取消,刷新账号信息时可断开。连接验证与普通应用流量分别使用各自的路由规则。Android 继续使用平台为手机分配的代理入口和系统 VPN。
1.0.7 修复共享安装包仓库分页后漏检 Android 版本,以及无关版本记录格式异常导致整个更新检查失败的问题。自动检查有统一20秒网络截止时间、分页及响应大小上限;发现新版本后提示从公司仓库覆盖安装,保留账号和配置,安装仍需 Android 系统确认。代理速度最低使用 KB/s;极小正样本显示 `<0.1 KB/s`。保留1.0.6的启动租约、授权隔离和电脑同款山水/半透明界面。本版验证包括离线 JVM 回归、五种 APK 的编译与同证书签名核验及 GPL 编译输入绑定;没有切换生产手机上的夜猫,也未把旧版手机验收记到本包。 1.0.7 修复共享安装包仓库分页后漏检 Android 版本,以及无关版本记录格式异常导致整个更新检查失败的问题。自动检查有统一20秒网络截止时间、分页及响应大小上限;发现新版本后提示从公司仓库覆盖安装,保留账号和配置,安装仍需 Android 系统确认。代理速度最低使用 KB/s;极小正样本显示 `<0.1 KB/s`。保留1.0.6的启动租约、授权隔离和电脑同款山水/半透明界面。本版验证包括离线 JVM 回归、五种 APK 的编译与同证书签名核验及 GPL 编译输入绑定;没有切换生产手机上的夜猫,也未把旧版手机验收记到本包。
+2 -2
View File
@@ -13,8 +13,8 @@ android {
applicationId = "cn.toplc.zonghengjia" applicationId = "cn.toplc.zonghengjia"
minSdk = 24 minSdk = 24
targetSdk = 37 targetSdk = 37
versionCode = 10007 versionCode = 10008
versionName = "1.0.7" versionName = "1.0.8"
multiDexEnabled = true multiDexEnabled = true
val abiFilterList = (properties["ABI_FILTERS"] as? String)?.split(';') val abiFilterList = (properties["ABI_FILTERS"] as? String)?.split(';')
@@ -0,0 +1,76 @@
package com.v2ray.ang.ucvl
import android.os.ParcelFileDescriptor
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import java.net.InetAddress
import java.net.InetSocketAddress
import java.net.ServerSocket
import java.net.Socket
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.TimeUnit
import kotlin.concurrent.thread
@RunWith(AndroidJUnit4::class)
class UcvlEgressProbeTest {
@Test fun rejectsWhenBothExplicitProxyChecksFail() {
exerciseProxy(acceptCloudflare = false)
}
@Test fun independentlyVerifiesSecondTlsTargetWhenFirstFails() {
exerciseProxy(acceptCloudflare = true)
}
private fun exerciseProxy(acceptCloudflare: Boolean) {
val automation = InstrumentationRegistry.getInstrumentation().uiAutomation
val device = ParcelFileDescriptor.AutoCloseInputStream(automation.executeShellCommand("getprop ro.kernel.qemu"))
assertEquals("1", device.bufferedReader().use { it.readText().trim() })
val received = LinkedBlockingQueue<String>()
ServerSocket(0, 4, InetAddress.getByName("127.0.0.1")).use { listener ->
listener.soTimeout = 15_000
val proxy = thread(isDaemon = true, name = "isolated-http-test-proxy") {
repeat(2) {
listener.accept().use { incoming ->
incoming.soTimeout = 10_000
val input = incoming.getInputStream().buffered()
val header = StringBuilder()
while (header.length < 4096 && !header.endsWith("\r\n\r\n")) {
val next = input.read()
if (next == -1) break
header.append(next.toChar())
}
val verb = header.lineSequence().firstOrNull().orEmpty()
received.put(verb)
val output = incoming.getOutputStream()
if (acceptCloudflare && verb == "CONNECT cp.cloudflare.com:443 HTTP/1.1") {
Socket().use { upstream ->
upstream.connect(InetSocketAddress("cp.cloudflare.com", 443), 5_000)
upstream.soTimeout = 10_000
output.write("HTTP/1.1 200 Connection established\r\n\r\n".toByteArray())
output.flush()
thread(isDaemon = true, name = "isolated-http-test-upload") {
runCatching { input.copyTo(upstream.getOutputStream()) }
}
runCatching { upstream.getInputStream().copyTo(output) }
}
} else {
output.write("HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".toByteArray())
output.flush()
}
}
}
}
val verified = runBlocking { UcvlEgressProbe.succeeds(listener.localPort) }
if (acceptCloudflare) assertTrue("Second proxy tunnel must return HTTPS 204", verified) else assertFalse(verified)
assertEquals("CONNECT www.gstatic.com:443 HTTP/1.1", received.poll(2, TimeUnit.SECONDS))
assertEquals("CONNECT cp.cloudflare.com:443 HTTP/1.1", received.poll(2, TimeUnit.SECONDS))
proxy.join(300)
}
}
}
@@ -68,14 +68,21 @@ class UpgradeSmokeTest {
} }
} }
assertTrue("Login did not render two frames", rendered.await(5, TimeUnit.SECONDS)) assertTrue("Login did not render two frames", rendered.await(5, TimeUnit.SECONDS))
// SurfaceFlinger may still be displaying the launch surface after app val buttonCenter = IntArray(2)
// frames are queued. Poll a bounded visual condition, retaining failure evidence. inst.runOnMainSync {
val button = activity.findViewById<android.view.View>(R.id.loginButton)
button.getLocationOnScreen(buttonCenter)
// Sample the colored button away from its rounded corners and centered label.
buttonCenter[0] += button.width / 6
buttonCenter[1] += button.height / 2
}
// The scenery can contain a pale header and pale page at the same time.
// A filled blue action button distinguishes a rendered frame from the splash.
fun painted(bitmap: Bitmap): Boolean { fun painted(bitmap: Bitmap): Boolean {
// Sample empty right-hand background, not the white title glyphs val (x, y) = buttonCenter
// at the header centre (which caused a false blank-frame result). if (x !in 0 until bitmap.width || y !in 0 until bitmap.height) return false
val header = bitmap.getPixel(bitmap.width * 9 / 10, bitmap.height / 8) val pixel = bitmap.getPixel(x, y)
val page = bitmap.getPixel(bitmap.width * 9 / 10, bitmap.height / 2) return android.graphics.Color.blue(pixel) - android.graphics.Color.red(pixel) > 80
return android.graphics.Color.red(page) - android.graphics.Color.red(header) > 80
} }
var screenshot = inst.uiAutomation.takeScreenshot() var screenshot = inst.uiAutomation.takeScreenshot()
val deadline = android.os.SystemClock.elapsedRealtime() + 10_000 val deadline = android.os.SystemClock.elapsedRealtime() + 10_000
@@ -161,6 +161,8 @@ object AppConfig {
const val MSG_STATE_START = 3 const val MSG_STATE_START = 3
const val MSG_STATE_START_SUCCESS = 31 const val MSG_STATE_START_SUCCESS = 31
const val MSG_STATE_START_FAILURE = 32 const val MSG_STATE_START_FAILURE = 32
const val MSG_STATE_VERIFYING = 33
const val PREF_UCVL_MANAGED_PROFILE = "ucvl_managed_profile"
const val MSG_STATE_STOP = 4 const val MSG_STATE_STOP = 4
const val MSG_STATE_STOP_SUCCESS = 41 const val MSG_STATE_STOP_SUCCESS = 41
const val MSG_STATE_RESTART = 5 const val MSG_STATE_RESTART = 5
@@ -49,6 +49,7 @@ object CoreServiceManager {
private var browserDialer: IDialerService? = null private var browserDialer: IDialerService? = null
private val coreLifecycleLock = Any() private val coreLifecycleLock = Any()
private val coreGeneration = AtomicLong(0) private val coreGeneration = AtomicLong(0)
private val verifiedGeneration = AtomicLong(-1)
var serviceControl: SoftReference<ServiceControl>? = null var serviceControl: SoftReference<ServiceControl>? = null
set(value) { set(value) {
@@ -293,11 +294,31 @@ object CoreServiceManager {
} }
requireSession(control, epoch) requireSession(control, epoch)
check(control.reportIfSessionValid(epoch) { val generation = coreGeneration.get()
if (service is CoreVpnService && guid == MmkvManager.decodeSettingsString(AppConfig.PREF_UCVL_MANAGED_PROFILE)) {
MessageUtil.sendMsg2UI(service, AppConfig.MSG_STATE_VERIFYING, "")
service.verifyEgress(epoch) { ready ->
if (ready) {
reportConnected(service, control, epoch, generation)
} else if (coreGeneration.get() == generation && control.reportIfSessionValid(epoch) {
MessageUtil.sendMsg2UI(service, AppConfig.MSG_STATE_START_FAILURE, "代理出口验证失败,请稍后重连。")
}) {
control.stopService()
}
}
} else {
check(reportConnected(service, control, epoch, generation)) { "VPN session was revoked before startup could be reported" }
}
}
private fun reportConnected(service: Service, control: ServiceControl, epoch: Long, generation: Long): Boolean {
if (serviceControl?.get() !== control || coreGeneration.get() != generation || !coreController.isRunning) return false
val reported = control.reportIfSessionValid(epoch) {
verifiedGeneration.set(generation)
MessageUtil.sendMsg2UI(service, AppConfig.MSG_STATE_START_SUCCESS, "") MessageUtil.sendMsg2UI(service, AppConfig.MSG_STATE_START_SUCCESS, "")
}) { "VPN session was revoked before startup could be reported" } }
if (isRunning()) NotificationManager.startSpeedNotification() if (reported && isRunning()) NotificationManager.startSpeedNotification()
LogUtil.i(AppConfig.TAG, "StartCore-Manager: Core started successfully") return reported
} }
/** /**
@@ -518,7 +539,12 @@ object CoreServiceManager {
AppConfig.MSG_REGISTER_CLIENT -> { AppConfig.MSG_REGISTER_CLIENT -> {
val epoch = serviceControl.sessionEpoch() val epoch = serviceControl.sessionEpoch()
if (!coreController.isRunning || !serviceControl.reportIfSessionValid(epoch) { if (!coreController.isRunning || !serviceControl.reportIfSessionValid(epoch) {
MessageUtil.sendMsg2UI(serviceControl.getService(), AppConfig.MSG_STATE_RUNNING, "") val state = if (verifiedGeneration.get() == coreGeneration.get()) {
AppConfig.MSG_STATE_RUNNING
} else {
AppConfig.MSG_STATE_VERIFYING
}
MessageUtil.sendMsg2UI(serviceControl.getService(), state, "")
}) { }) {
MessageUtil.sendMsg2UI(serviceControl.getService(), AppConfig.MSG_STATE_NOT_RUNNING, "") MessageUtil.sendMsg2UI(serviceControl.getService(), AppConfig.MSG_STATE_NOT_RUNNING, "")
} }
@@ -33,6 +33,7 @@ import com.v2ray.ang.util.Utils
import java.lang.ref.SoftReference import java.lang.ref.SoftReference
import com.v2ray.ang.ucvl.UcvlApiClient import com.v2ray.ang.ucvl.UcvlApiClient
import com.v2ray.ang.ucvl.UcvlAuthorizationGuard import com.v2ray.ang.ucvl.UcvlAuthorizationGuard
import com.v2ray.ang.ucvl.UcvlEgressProbe
import com.v2ray.ang.ucvl.UcvlSecureStore import com.v2ray.ang.ucvl.UcvlSecureStore
import com.v2ray.ang.ucvl.UcvlVpnStartupLease import com.v2ray.ang.ucvl.UcvlVpnStartupLease
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
@@ -53,6 +54,7 @@ class CoreVpnService : VpnService(), ServiceControl {
private var tun2SocksService: Tun2SocksControl? = null private var tun2SocksService: Tun2SocksControl? = null
private val authorizationScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) private val authorizationScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
private var authorizationJob: Job? = null private var authorizationJob: Job? = null
private var egressJob: Job? = null
/**destroy /**destroy
* Unfortunately registerDefaultNetworkCallback is going to return our VPN interface: https://android.googlesource.com/platform/frameworks/base/+/dda156ab0c5d66ad82bdcf76cda07cbc0a9c8a2e * Unfortunately registerDefaultNetworkCallback is going to return our VPN interface: https://android.googlesource.com/platform/frameworks/base/+/dda156ab0c5d66ad82bdcf76cda07cbc0a9c8a2e
@@ -191,6 +193,15 @@ class CoreVpnService : VpnService(), ServiceControl {
stopAllService(true) stopAllService(true)
} }
fun verifyEgress(epoch: Long, report: (Boolean) -> Unit) {
egressJob?.cancel()
egressJob = authorizationScope.launch {
// The managed runtime uses its fixed SOCKS port plus one for HTTP.
val ready = UcvlEgressProbe.succeeds(SettingsManager.getSocksPort() + 1)
if (isSessionValid(epoch)) report(ready)
}
}
override fun sessionEpoch(): Long = startupEpoch override fun sessionEpoch(): Long = startupEpoch
override fun isSessionValid(epoch: Long): Boolean { override fun isSessionValid(epoch: Long): Boolean {
@@ -436,6 +447,8 @@ class CoreVpnService : VpnService(), ServiceControl {
} }
private fun stopAllServiceOnMain(isForced: Boolean) { private fun stopAllServiceOnMain(isForced: Boolean) {
egressJob?.cancel()
egressJob = null
authorizationJob?.cancel() authorizationJob?.cancel()
authorizationJob = null authorizationJob = null
// val configName = defaultDPreference.getPrefString(PREF_CURR_CONFIG_GUID, "") // val configName = defaultDPreference.getPrefString(PREF_CURR_CONFIG_GUID, "")
@@ -54,6 +54,16 @@ object UcvlConfigBridge {
val rules = JsonArray() val rules = JsonArray()
rules.add(JsonParser.parseString("""{"type":"field","inboundTag":["socks-in","http-in"],"port":"53","outboundTag":"ucvl-dns-out"}""")) rules.add(JsonParser.parseString("""{"type":"field","inboundTag":["socks-in","http-in"],"port":"53","outboundTag":"ucvl-dns-out"}"""))
rules.add(JsonParser.parseString("""{"type":"field","inboundTag":["ucvl-dns"],"outboundTag":"proxy"}""")) rules.add(JsonParser.parseString("""{"type":"field","inboundTag":["ucvl-dns"],"outboundTag":"proxy"}"""))
// The app uses the loopback HTTP port for its HTTPS startup checks.
// Regular VPN traffic arrives over SOCKS and keeps the platform rules.
rules.add(JsonObject().apply {
addProperty("type", "field")
add("inboundTag", JsonArray().apply { add("http-in") })
add("domain", JsonArray().apply {
UcvlEgressProbe.targets.forEach { add("full:${it.host}") }
})
addProperty("outboundTag", "proxy")
})
originalRules.forEach { rules.add(it.deepCopy()) } originalRules.forEach { rules.add(it.deepCopy()) }
routing.add("rules", rules) routing.add("rules", rules)
return result return result
@@ -0,0 +1,50 @@
package com.v2ray.ang.ucvl
import kotlinx.coroutines.suspendCancellableCoroutine
import okhttp3.Call
import okhttp3.Callback
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException
import java.net.InetSocketAddress
import java.net.Proxy
import java.util.concurrent.TimeUnit
import kotlin.coroutines.resume
internal object UcvlEgressProbe {
val targets = listOf(
"https://www.gstatic.com/generate_204".toHttpUrl(),
"https://cp.cloudflare.com/generate_204".toHttpUrl(),
)
suspend fun succeeds(port: Int): Boolean {
val client = OkHttpClient.Builder()
.proxy(Proxy(Proxy.Type.HTTP, InetSocketAddress("127.0.0.1", port)))
.followRedirects(false)
.followSslRedirects(false)
.retryOnConnectionFailure(false)
.callTimeout(6, TimeUnit.SECONDS)
.build()
try {
return targets.any { target ->
val request = Request.Builder().url(target).build()
suspendCancellableCoroutine { continuation ->
val call = client.newCall(request)
continuation.invokeOnCancellation { call.cancel() }
call.enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) = continuation.resume(false)
override fun onResponse(call: Call, response: Response) {
response.use { continuation.resume(it.code == 204) }
}
})
}
}
} finally {
client.connectionPool.evictAll()
client.dispatcher.executorService.shutdown()
}
}
}
@@ -248,6 +248,9 @@ class UcvlMainActivity : AppCompatActivity() {
mainViewModel.isRunning.observe(this) { running -> mainViewModel.isRunning.observe(this) { running ->
applyRunningState(running == true) applyRunningState(running == true)
} }
mainViewModel.isStarting.observe(this) {
applyRunningState(mainViewModel.isRunning.value == true)
}
mainViewModel.updateTestResultAction.observe(this) { result -> mainViewModel.updateTestResultAction.observe(this) { result ->
if (!result.isNullOrBlank() && mainViewModel.isRunning.value == true) { if (!result.isNullOrBlank() && mainViewModel.isRunning.value == true) {
statusDetail.text = result statusDetail.text = result
@@ -312,12 +315,12 @@ class UcvlMainActivity : AppCompatActivity() {
} }
private fun toggleConnection() { private fun toggleConnection() {
if (busy) return if (mainViewModel.isRunning.value == true || mainViewModel.isStarting.value == true) {
if (mainViewModel.isRunning.value == true) {
CoreServiceManager.stopVService(this) CoreServiceManager.stopVService(this)
setConnectionState(false, "正在断开", "系统将自动恢复原网络") setConnectionState(false, "正在断开", "系统将自动恢复原网络")
return return
} }
if (busy) return
val currentProfile = profile ?: return val currentProfile = profile ?: return
val route = currentProfile.routeModes.getOrNull(routeSpinner.selectedItemPosition) val route = currentProfile.routeModes.getOrNull(routeSpinner.selectedItemPosition)
if (currentProfile.nodes.isEmpty() || route == null) { if (currentProfile.nodes.isEmpty() || route == null) {
@@ -353,10 +356,10 @@ class UcvlMainActivity : AppCompatActivity() {
val raw = UcvlConfigBridge.buildRuntime(response.config, response.node.name, port, port + 1, val raw = UcvlConfigBridge.buildRuntime(response.config, response.node.name, port, port + 1,
SettingsManager.getSocksUsername(), SettingsManager.getSocksPassword(), SettingsManager.getSocksUsername(), SettingsManager.getSocksPassword(),
response.gateway?.preferredAddress()).toString() response.gateway?.preferredAddress()).toString()
val ownedGuid = MmkvManager.decodeSettingsString(OWNED_PROFILE_KEY).orEmpty() val ownedGuid = MmkvManager.decodeSettingsString(AppConfig.PREF_UCVL_MANAGED_PROFILE).orEmpty()
val selected = MmkvManager.encodeServerConfig(ownedGuid, CustomFmt.parse(raw)) val selected = MmkvManager.encodeServerConfig(ownedGuid, CustomFmt.parse(raw))
MmkvManager.encodeServerRaw(selected, raw) MmkvManager.encodeServerRaw(selected, raw)
MmkvManager.encodeSettings(OWNED_PROFILE_KEY, selected) MmkvManager.encodeSettings(AppConfig.PREF_UCVL_MANAGED_PROFILE, selected)
MmkvManager.setSelectServer(selected) MmkvManager.setSelectServer(selected)
} }
MmkvManager.encodeSettings(LAST_NODE_KEY, response.node.slug) MmkvManager.encodeSettings(LAST_NODE_KEY, response.node.slug)
@@ -468,13 +471,26 @@ class UcvlMainActivity : AppCompatActivity() {
val route = profile?.routeModes?.getOrNull(routeSpinner.selectedItemPosition) val route = profile?.routeModes?.getOrNull(routeSpinner.selectedItemPosition)
currentNode.text = "$nodeName · 平台自动调度" currentNode.text = "$nodeName · 平台自动调度"
setConnectionState(true, "已安全连接", listOfNotNull(nodeName, route?.name).joinToString(" · ")) setConnectionState(true, "已安全连接", listOfNotNull(nodeName, route?.name).joinToString(" · "))
} else if (mainViewModel.isStarting.value == true) {
setConnectionState(false, "正在验证连接", "通过 VPN 检查 HTTPS 是否可用")
} else if (statusTitle.text != "连接失败" && statusTitle.text != "本地直连") { } else if (statusTitle.text != "连接失败" && statusTitle.text != "本地直连") {
currentNode.text = "连接后显示实际工作节点" currentNode.text = "连接后显示实际工作节点"
proxySpeed.text = "↑ 0 B/s ↓ 0 B/s" proxySpeed.text = "↑ 0 B/s ↓ 0 B/s"
setConnectionState(false, "未连接", "点击连接,由平台策略自动选择节点") setConnectionState(false, "未连接", "点击连接,由平台策略自动选择节点")
} }
connectButton.text = if (running) "断开" else "连接" updateConnectControls()
routeSpinner.isEnabled = !running && !busy }
private fun updateConnectControls() {
val running = mainViewModel.isRunning.value == true
val verifying = mainViewModel.isStarting.value == true
connectButton.text = when {
running -> "断开"
verifying -> "取消"
else -> "连接"
}
connectButton.isEnabled = running || verifying || (!busy && profile?.nodes?.isNotEmpty() == true)
routeSpinner.isEnabled = !busy && !running && !verifying
} }
private fun setConnectionState(connected: Boolean, title: String, detail: String) { private fun setConnectionState(connected: Boolean, title: String, detail: String) {
@@ -489,11 +505,10 @@ class UcvlMainActivity : AppCompatActivity() {
private fun setBusy(value: Boolean, message: String = "") { private fun setBusy(value: Boolean, message: String = "") {
busy = value busy = value
loginButton.isEnabled = !value loginButton.isEnabled = !value
connectButton.isEnabled = !value && profile?.nodes?.isNotEmpty() == true updateConnectControls()
refreshButton.isEnabled = !value refreshButton.isEnabled = !value
logoutButton.isEnabled = !value logoutButton.isEnabled = !value
exitButton.isEnabled = !value exitButton.isEnabled = !value
routeSpinner.isEnabled = !value && mainViewModel.isRunning.value != true
if (value && dashboardPanel.visibility == View.VISIBLE && message.isNotBlank()) { if (value && dashboardPanel.visibility == View.VISIBLE && message.isNotBlank()) {
statusDetail.text = message statusDetail.text = message
} }
@@ -573,7 +588,6 @@ class UcvlMainActivity : AppCompatActivity() {
private const val SOURCE_URL = "https://pro.ucvl.cn/admin/ucvl-zonghengjia-android" private const val SOURCE_URL = "https://pro.ucvl.cn/admin/ucvl-zonghengjia-android"
private const val LAST_NODE_KEY = "ucvl_last_node" private const val LAST_NODE_KEY = "ucvl_last_node"
private const val LAST_NODE_NAME_KEY = "ucvl_last_node_name" private const val LAST_NODE_NAME_KEY = "ucvl_last_node_name"
private const val OWNED_PROFILE_KEY = "ucvl_managed_profile"
private const val LAST_ROUTE_KEY = "ucvl_last_route" private const val LAST_ROUTE_KEY = "ucvl_last_route"
} }
} }
@@ -44,6 +44,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
var keywordFilter = "" var keywordFilter = ""
val serversCache = mutableListOf<ServersCache>() val serversCache = mutableListOf<ServersCache>()
val isRunning by lazy { MutableLiveData<Boolean>() } val isRunning by lazy { MutableLiveData<Boolean>() }
val isStarting by lazy { MutableLiveData(false) }
val updateListAction by lazy { MutableLiveData<Int>() } val updateListAction by lazy { MutableLiveData<Int>() }
val updateTestResultAction by lazy { MutableLiveData<String>() } val updateTestResultAction by lazy { MutableLiveData<String>() }
private val tcpingTestScope by lazy { CoroutineScope(Dispatchers.IO) } private val tcpingTestScope by lazy { CoroutineScope(Dispatchers.IO) }
@@ -457,15 +458,22 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
when (intent?.getIntExtra("key", 0)) { when (intent?.getIntExtra("key", 0)) {
AppConfig.MSG_STATE_RUNNING -> { AppConfig.MSG_STATE_RUNNING -> {
isRunning.value = true isRunning.value = true
isStarting.value = false
} }
AppConfig.MSG_STATE_NOT_RUNNING -> { AppConfig.MSG_STATE_NOT_RUNNING -> {
isRunning.value = false isRunning.value = false
isStarting.value = false
}
AppConfig.MSG_STATE_VERIFYING -> {
isStarting.value = true
} }
AppConfig.MSG_STATE_START_SUCCESS -> { AppConfig.MSG_STATE_START_SUCCESS -> {
getApplication<AngApplication>().toastSuccess(R.string.toast_services_success) getApplication<AngApplication>().toastSuccess(R.string.toast_services_success)
isRunning.value = true isRunning.value = true
isStarting.value = false
} }
AppConfig.MSG_STATE_START_FAILURE -> { AppConfig.MSG_STATE_START_FAILURE -> {
@@ -476,10 +484,12 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
getApplication<AngApplication>().toastError(R.string.toast_services_failure) getApplication<AngApplication>().toastError(R.string.toast_services_failure)
} }
isRunning.value = false isRunning.value = false
isStarting.value = false
} }
AppConfig.MSG_STATE_STOP_SUCCESS -> { AppConfig.MSG_STATE_STOP_SUCCESS -> {
isRunning.value = false isRunning.value = false
isStarting.value = false
} }
AppConfig.MSG_MEASURE_DELAY_SUCCESS -> { AppConfig.MSG_MEASURE_DELAY_SUCCESS -> {
@@ -26,7 +26,7 @@ class UcvlConfigBridgeTest {
assertEquals(before, source.toString()) assertEquals(before, source.toString())
assertEquals(source.getAsJsonArray("outbounds")[0], runtime.getAsJsonArray("outbounds")[0]) assertEquals(source.getAsJsonArray("outbounds")[0], runtime.getAsJsonArray("outbounds")[0])
assertEquals(source.getAsJsonObject("routing").getAsJsonArray("rules")[0], assertEquals(source.getAsJsonObject("routing").getAsJsonArray("rules")[0],
runtime.getAsJsonObject("routing").getAsJsonArray("rules")[2]) runtime.getAsJsonObject("routing").getAsJsonArray("rules")[3])
assertFalse(runtime.has("api")) assertFalse(runtime.has("api"))
assertTrue(runtime.getAsJsonArray("inbounds").all { it.asJsonObject.get("listen").asString == "127.0.0.1" }) assertTrue(runtime.getAsJsonArray("inbounds").all { it.asJsonObject.get("listen").asString == "127.0.0.1" })
assertTrue(runtime.getAsJsonObject("policy").getAsJsonObject("system").get("statsOutboundUplink").asBoolean) assertTrue(runtime.getAsJsonObject("policy").getAsJsonObject("system").get("statsOutboundUplink").asBoolean)
@@ -41,6 +41,20 @@ class UcvlConfigBridgeTest {
assertFalse(rules.any { it.asJsonObject.get("network")?.asString == "tcp,udp" }) assertFalse(rules.any { it.asJsonObject.get("network")?.asString == "tcp,udp" })
} }
@Test fun forcesOnlyLoopbackHttpConnectivityChecksThroughTheProxy() {
val source = fixture()
val rules = UcvlConfigBridge.buildRuntime(source, "VPN002", 10808, 10809)
.getAsJsonObject("routing").getAsJsonArray("rules")
val probe = rules.firstOrNull { rule ->
rule.asJsonObject.getAsJsonArray("inboundTag")?.map { it.asString } == listOf("http-in") &&
rule.asJsonObject.has("domain")
}?.asJsonObject ?: throw AssertionError("HTTPS startup checks can be routed directly")
assertEquals("proxy", probe.get("outboundTag").asString)
assertEquals(listOf("full:cp.cloudflare.com", "full:www.gstatic.com"),
probe.getAsJsonArray("domain").map { it.asString }.sorted())
assertTrue(rules.indexOf(probe) < rules.indexOf(source.getAsJsonObject("routing").getAsJsonArray("rules")[0]))
}
@Test fun usesUnifiedNpmGatewayWithoutChangingPortOrRealitySni() { @Test fun usesUnifiedNpmGatewayWithoutChangingPortOrRealitySni() {
val runtime = UcvlConfigBridge.buildRuntime( val runtime = UcvlConfigBridge.buildRuntime(
fixture(), "VPN002", 10808, 10809, gatewayAddress = "59.110.91.17") fixture(), "VPN002", 10808, 10809, gatewayAddress = "59.110.91.17")