Archive Android 1.0.7 GPL candidate source; full production acceptance false (2026-11-07)

This commit is contained in:
2026-11-07 03:47:07 +00:00
parent 261dde435b
commit 35f2d3b4e7
54 changed files with 68608 additions and 466 deletions
+2 -2
View File
@@ -13,8 +13,8 @@ android {
applicationId = "cn.toplc.zonghengjia"
minSdk = 24
targetSdk = 37
versionCode = 10002
versionName = "1.0.2"
versionCode = 10007
versionName = "1.0.7"
multiDexEnabled = true
val abiFilterList = (properties["ABI_FILTERS"] as? String)?.split(';')
@@ -11,13 +11,22 @@ import com.v2ray.ang.handler.MmkvManager
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
/** Run only in the dedicated disposable Android acceptance emulator. No production accounts. */
@RunWith(AndroidJUnit4::class)
class UpgradeSmokeTest {
private fun requireEmulator() {
val descriptor = InstrumentationRegistry.getInstrumentation().uiAutomation.executeShellCommand("getprop ro.kernel.qemu")
val value = android.os.ParcelFileDescriptor.AutoCloseInputStream(descriptor).bufferedReader().use { it.readText().trim() }
assertEquals("Never change a physical device's account fixture", "1", value)
}
@Test fun seedUpgrade() {
requireEmulator()
val context = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("1.0.0", context.packageManager.getPackageInfo(context.packageName, 0).versionName)
assertEquals(InstrumentationRegistry.getArguments().getString("oldVersion") ?: "1.0.2",
context.packageManager.getPackageInfo(context.packageName, 0).versionName)
UcvlSecureStore.saveToken("ucvl-upgrade-fixture-not-a-real-token")
UcvlSecureStore.saveLastLogin("ucvl-upgrade-fixture")
MmkvManager.encodeSettings("ucvl_test_expected_device_id", UcvlSecureStore.deviceId())
@@ -25,8 +34,10 @@ class UpgradeSmokeTest {
}
@Test fun verifyUpgrade() {
requireEmulator()
val context = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("1.0.1", context.packageManager.getPackageInfo(context.packageName, 0).versionName)
assertEquals(InstrumentationRegistry.getArguments().getString("newVersion") ?: "1.0.3",
context.packageManager.getPackageInfo(context.packageName, 0).versionName)
assertEquals("ucvl-upgrade-fixture", UcvlSecureStore.lastLogin())
assertEquals(MmkvManager.decodeSettingsString("ucvl_test_expected_device_id"), UcvlSecureStore.deviceId())
assertEquals("ucvl-upgrade-fixture-not-a-real-token", UcvlSecureStore.loadToken())
@@ -35,6 +46,7 @@ class UpgradeSmokeTest {
}
@Test fun loginVisibleAndEmptyFormIsSafe() {
requireEmulator()
UcvlSecureStore.clearToken()
val inst = InstrumentationRegistry.getInstrumentation()
val activity = inst.startActivitySync(Intent(inst.targetContext, UcvlMainActivity::class.java)
@@ -48,10 +60,35 @@ class UpgradeSmokeTest {
assertTrue(activity.findViewById<TextView>(R.id.loginError).text.contains("请输入"))
}
inst.waitForIdleSync()
inst.uiAutomation.takeScreenshot().useBitmap { bitmap ->
// isShown/idle alone can precede the first rendered frame (white screenshot).
val rendered = CountDownLatch(1)
inst.runOnMainSync {
activity.window.decorView.postOnAnimation {
activity.window.decorView.postOnAnimation { rendered.countDown() }
}
}
assertTrue("Login did not render two frames", rendered.await(5, TimeUnit.SECONDS))
// SurfaceFlinger may still be displaying the launch surface after app
// frames are queued. Poll a bounded visual condition, retaining failure evidence.
fun painted(bitmap: Bitmap): Boolean {
// Sample empty right-hand background, not the white title glyphs
// at the header centre (which caused a false blank-frame result).
val header = bitmap.getPixel(bitmap.width * 9 / 10, bitmap.height / 8)
val page = bitmap.getPixel(bitmap.width * 9 / 10, bitmap.height / 2)
return android.graphics.Color.red(page) - android.graphics.Color.red(header) > 80
}
var screenshot = inst.uiAutomation.takeScreenshot()
val deadline = android.os.SystemClock.elapsedRealtime() + 10_000
while (!painted(screenshot) && android.os.SystemClock.elapsedRealtime() < deadline) {
screenshot.recycle()
android.os.SystemClock.sleep(200)
screenshot = inst.uiAutomation.takeScreenshot()
}
screenshot.useBitmap { bitmap ->
java.io.File(inst.targetContext.filesDir, "acceptance-login.png").outputStream().use {
bitmap.compress(Bitmap.CompressFormat.PNG, 100, it)
}
assertTrue("Login frame is still blank after rendering deadline", painted(bitmap))
}
inst.runOnMainSync { activity.finish() }
}
@@ -19,6 +19,18 @@ interface ServiceControl {
*/
fun stopService()
/** Proxy-only services have no Android VPN lease and retain their old behavior. */
fun sessionEpoch(): Long = 0L
fun isSessionValid(epoch: Long): Boolean = true
/** Report success only while the service still owns the session being started. */
fun reportIfSessionValid(epoch: Long, report: () -> Unit): Boolean {
if (!isSessionValid(epoch)) return false
report()
return true
}
/**
* Protects the VPN socket.
* @param socket The socket to protect.
@@ -38,6 +38,7 @@ import libv2ray.CoreController
import libv2ray.ProcessFinder
import java.lang.ref.SoftReference
import java.net.InetSocketAddress
import java.util.concurrent.atomic.AtomicLong
object CoreServiceManager {
@@ -46,6 +47,8 @@ object CoreServiceManager {
private var currentConfig: ProfileItem? = null
private var processFinder: XrayProcessFinder? = null
private var browserDialer: IDialerService? = null
private val coreLifecycleLock = Any()
private val coreGeneration = AtomicLong(0)
var serviceControl: SoftReference<ServiceControl>? = null
set(value) {
@@ -111,7 +114,10 @@ object CoreServiceManager {
* Checks if the V2Ray service is running.
* @return True if the service is running, false otherwise.
*/
fun isRunning() = coreController.isRunning
fun isRunning(): Boolean {
val control = serviceControl?.get() ?: return false
return coreController.isRunning && control.isSessionValid(control.sessionEpoch())
}
/**
* Gets the name of the currently running server.
@@ -202,26 +208,35 @@ object CoreServiceManager {
return false
}
val service = getService()
if (service == null) {
val control = serviceControl?.get()
if (control == null) {
LogUtil.e(AppConfig.TAG, "StartCore-Manager: Service is null")
return false
}
val service = control.getService()
val epoch = control.sessionEpoch()
try {
doStartCoreLoop(service, vpnInterface)
requireSession(control, epoch)
doStartCoreLoop(service, vpnInterface, control, epoch)
return true
} catch (e: Exception) {
val message = e.message?.takeUnless { it.isBlank() } ?: e.javaClass.simpleName
LogUtil.e(AppConfig.TAG, "StartCore-Manager: $message", e)
MessageUtil.sendMsg2UI(service, AppConfig.MSG_STATE_START_FAILURE, message)
NotificationManager.cancelNotification()
if (serviceControl?.get() === control) stopCoreLoop()
return false
}
}
private fun requireSession(control: ServiceControl, epoch: Long) {
check(serviceControl?.get() === control && control.isSessionValid(epoch)) {
"VPN permission or startup session was revoked"
}
}
@Throws(Exception::class)
private fun doStartCoreLoop(service: Service, vpnInterface: ParcelFileDescriptor?) {
private fun doStartCoreLoop(service: Service, vpnInterface: ParcelFileDescriptor?, control: ServiceControl, epoch: Long) {
val guid = MmkvManager.getSelectServer() ?: error("No server selected")
val config = MmkvManager.decodeServerConfig(guid) ?: error("Failed to decode server config")
@@ -231,6 +246,7 @@ object CoreServiceManager {
if (!result.status) {
error(result.errorMessage.ifBlank { "Failed to get V2Ray config" })
}
requireSession(control, epoch)
val mFilter = IntentFilter(AppConfig.BROADCAST_ACTION_SERVICE)
mFilter.addAction(Intent.ACTION_SCREEN_ON)
@@ -251,7 +267,14 @@ object CoreServiceManager {
NotificationManager.showNotification(currentConfig)
CoreNativeManager.reconcileBrowserDialer(dialerAddr)
coreController.startLoop(result.content, tunFd)
// Do not hold a VPN lease lock while entering native code: its callbacks
// may arrive on another thread. A revoke invalidates that lease at once.
synchronized(coreLifecycleLock) {
requireSession(control, epoch)
coreGeneration.incrementAndGet()
coreController.startLoop(result.content, tunFd)
}
requireSession(control, epoch)
if (!coreController.isRunning) {
error("Core failed to start")
@@ -269,8 +292,11 @@ object CoreServiceManager {
browserDialer!!.start(service, dialerAddr)
}
MessageUtil.sendMsg2UI(service, AppConfig.MSG_STATE_START_SUCCESS, "")
NotificationManager.startSpeedNotification()
requireSession(control, epoch)
check(control.reportIfSessionValid(epoch) {
MessageUtil.sendMsg2UI(service, AppConfig.MSG_STATE_START_SUCCESS, "")
}) { "VPN session was revoked before startup could be reported" }
if (isRunning()) NotificationManager.startSpeedNotification()
LogUtil.i(AppConfig.TAG, "StartCore-Manager: Core started successfully")
}
@@ -282,12 +308,17 @@ object CoreServiceManager {
fun stopCoreLoop(): Boolean {
val service = getService() ?: return false
if (coreController.isRunning) {
CoroutineScope(Dispatchers.IO).launch {
try {
coreController.stopLoop()
} catch (e: Exception) {
LogUtil.e(AppConfig.TAG, "StartCore-Manager: Failed to stop V2Ray loop", e)
val generation = coreGeneration.get()
// Always schedule stop, even when revoke preceded native startup. The
// serialized generation check also prevents an old stop killing a new core.
CoroutineScope(Dispatchers.IO).launch {
synchronized(coreLifecycleLock) {
if (coreGeneration.get() == generation) {
try {
coreController.stopLoop()
} catch (e: Exception) {
LogUtil.e(AppConfig.TAG, "StartCore-Manager: Failed to stop V2Ray loop", e)
}
}
}
}
@@ -485,9 +516,10 @@ object CoreServiceManager {
val serviceControl = serviceControl?.get() ?: return
when (intent?.getIntExtra("key", 0)) {
AppConfig.MSG_REGISTER_CLIENT -> {
if (coreController.isRunning) {
MessageUtil.sendMsg2UI(serviceControl.getService(), AppConfig.MSG_STATE_RUNNING, "")
} else {
val epoch = serviceControl.sessionEpoch()
if (!coreController.isRunning || !serviceControl.reportIfSessionValid(epoch) {
MessageUtil.sendMsg2UI(serviceControl.getService(), AppConfig.MSG_STATE_RUNNING, "")
}) {
MessageUtil.sendMsg2UI(serviceControl.getService(), AppConfig.MSG_STATE_NOT_RUNNING, "")
}
}
@@ -525,9 +557,9 @@ object CoreServiceManager {
Intent.ACTION_SCREEN_ON -> {
LogUtil.i(AppConfig.TAG, "StartCore-Manager: Screen on")
NotificationManager.startSpeedNotification()
if (isRunning()) NotificationManager.startSpeedNotification()
}
}
}
}
}
}
@@ -12,6 +12,8 @@ import android.net.NetworkRequest
import android.net.ProxyInfo
import android.net.VpnService
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.os.ParcelFileDescriptor
import android.os.StrictMode
import androidx.annotation.RequiresApi
@@ -25,12 +27,14 @@ import com.v2ray.ang.handler.MmkvManager
import com.v2ray.ang.handler.NotificationManager
import com.v2ray.ang.handler.SettingsManager
import com.v2ray.ang.util.LogUtil
import com.v2ray.ang.util.MessageUtil
import com.v2ray.ang.util.MyContextWrapper
import com.v2ray.ang.util.Utils
import java.lang.ref.SoftReference
import com.v2ray.ang.ucvl.UcvlApiClient
import com.v2ray.ang.ucvl.UcvlAuthorizationGuard
import com.v2ray.ang.ucvl.UcvlSecureStore
import com.v2ray.ang.ucvl.UcvlVpnStartupLease
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
@@ -40,8 +44,12 @@ import kotlinx.coroutines.launch
@SuppressLint("VpnServicePolicy")
class CoreVpnService : VpnService(), ServiceControl {
private lateinit var mInterface: ParcelFileDescriptor
private var isRunning = false
@Volatile private var mInterface: ParcelFileDescriptor? = null
@Volatile private var isRunning = false
@Volatile private var permissionRevoked = false
@Volatile private var startupEpoch = 0L
private val startupLease = UcvlVpnStartupLease()
private val mainHandler = Handler(Looper.getMainLooper())
private var tun2SocksService: Tun2SocksControl? = null
private val authorizationScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
private var authorizationJob: Job? = null
@@ -94,6 +102,9 @@ class CoreVpnService : VpnService(), ServiceControl {
override fun onRevoke() {
LogUtil.w(AppConfig.TAG, "StartCore-VPN: Permission revoked")
// onRevoke may arrive on Binder while establish/startLoop blocks main.
// Invalidate first; cleanup must not race those main-thread operations.
permissionRevoked = true
stopAllService()
}
@@ -103,48 +114,54 @@ class CoreVpnService : VpnService(), ServiceControl {
// }
override fun onDestroy() {
startupLease.invalidate()
stopAllServiceOnMain(false)
authorizationScope.cancel()
super.onDestroy()
LogUtil.i(AppConfig.TAG, "StartCore-VPN: Service destroyed")
// Ensure VPN interface is properly closed when the service is destroyed without
// going through stopAllService() (e.g. when killed unexpectedly). isRunning is
// set to false at the start of stopAllService(), so this guard prevents a double-close.
if (isRunning) {
try {
if (::mInterface.isInitialized) {
mInterface.close()
LogUtil.i(AppConfig.TAG, "StartCore-VPN: VPN interface closed in onDestroy")
}
} catch (e: Exception) {
LogUtil.e(AppConfig.TAG, "StartCore-VPN: Failed to close interface in onDestroy", e)
}
}
NotificationManager.cancelNotification()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (isRunning) return START_NOT_STICKY
if (isSessionValid(startupEpoch)) return START_NOT_STICKY
if (permissionRevoked) {
stopSelf()
return START_NOT_STICKY
}
val token = UcvlSecureStore.loadToken()
if (token.isNullOrBlank()) {
stopSelf()
return START_NOT_STICKY
}
LogUtil.i(AppConfig.TAG, "StartCore-VPN: Service command received")
startupEpoch = startupLease.begin()
NotificationManager.showNotification(null)
setupVpnService()
val configured = try {
setupVpnService(startupEpoch)
} catch (e: Exception) {
LogUtil.e(AppConfig.TAG, "StartCore-VPN: VPN setup failed", e)
false
}
if (!configured) {
MessageUtil.sendMsg2UI(this, AppConfig.MSG_STATE_START_FAILURE,
"VPN permission or interface is no longer available")
stopAllService()
return START_NOT_STICKY
}
startService()
if (isRunning) {
if (isSessionValid(startupEpoch)) {
authorizationJob?.cancel()
authorizationJob = authorizationScope.launch {
UcvlApiClient().use { api ->
UcvlAuthorizationGuard.watch(token, UcvlSecureStore::loadToken,
{ api.profile(it) }, {
if (UcvlSecureStore.loadToken() == token) UcvlSecureStore.clearToken()
sendBroadcast(Intent(UcvlAuthorizationGuard.ACTION_REVOKED).setPackage(packageName))
if (UcvlSecureStore.loadToken() == token) {
UcvlSecureStore.clearToken()
sendBroadcast(Intent(UcvlAuthorizationGuard.ACTION_REVOKED).setPackage(packageName))
}
stopAllService()
})
}, sessionChanged = { stopAllService() })
}
}
}
@@ -157,11 +174,13 @@ class CoreVpnService : VpnService(), ServiceControl {
}
override fun startService() {
if (!::mInterface.isInitialized) {
LogUtil.e(AppConfig.TAG, "StartCore-VPN: Interface not initialized")
val vpnInterface = mInterface
if (vpnInterface == null || !isSessionValid(startupEpoch)) {
LogUtil.e(AppConfig.TAG, "StartCore-VPN: Interface or VPN session no longer valid")
stopAllService()
return
}
if (!CoreServiceManager.startCoreLoop(mInterface)) {
if (!CoreServiceManager.startCoreLoop(vpnInterface)) {
LogUtil.e(AppConfig.TAG, "StartCore-VPN: Failed to start core loop")
stopAllService()
return
@@ -172,6 +191,20 @@ class CoreVpnService : VpnService(), ServiceControl {
stopAllService(true)
}
override fun sessionEpoch(): Long = startupEpoch
override fun isSessionValid(epoch: Long): Boolean {
if (!startupLease.isValid(epoch) || !isRunning ||
mInterface?.fileDescriptor?.valid() != true) return false
val prepared = try { prepare(this) == null } catch (_: Exception) { false }
return prepared && startupLease.isValid(epoch) && !permissionRevoked
}
override fun reportIfSessionValid(epoch: Long, report: () -> Unit): Boolean {
if (!isSessionValid(epoch)) return false
return startupLease.reportIfValid(epoch, report)
}
override fun vpnProtect(socket: Int): Boolean {
return protect(socket)
}
@@ -187,28 +220,29 @@ class CoreVpnService : VpnService(), ServiceControl {
* Sets up the VPN service.
* Prepares the VPN and configures it if preparation is successful.
*/
private fun setupVpnService() {
private fun setupVpnService(epoch: Long): Boolean {
if (!startupLease.isValid(epoch) || permissionRevoked) return false
val prepare = prepare(this)
if (prepare != null) {
LogUtil.e(AppConfig.TAG, "StartCore-VPN: Permission not granted")
stopSelf()
return
return false
}
if (configureVpnService() != true) {
if (!configureVpnService(epoch)) {
LogUtil.e(AppConfig.TAG, "StartCore-VPN: Configuration failed")
stopSelf()
return
return false
}
if (!isSessionValid(epoch)) return false
runTun2socks()
return isSessionValid(epoch)
}
/**
* Configures the VPN service.
* @return True if the VPN service was configured successfully, false otherwise.
*/
private fun configureVpnService(): Boolean {
private fun configureVpnService(epoch: Long): Boolean {
val builder = Builder()
// Configure network settings (addresses, routing and DNS)
@@ -219,9 +253,8 @@ class CoreVpnService : VpnService(), ServiceControl {
// Close the old interface since the parameters have been changed
try {
if (::mInterface.isInitialized) {
mInterface.close()
}
mInterface?.close()
mInterface = null
} catch (e: Exception) {
LogUtil.w(AppConfig.TAG, "Failed to close old interface", e)
}
@@ -231,9 +264,18 @@ class CoreVpnService : VpnService(), ServiceControl {
// Create a new interface using the builder and save the parameters
try {
mInterface = builder.establish()!!
if (!startupLease.isValid(epoch) || prepare(this) != null) return false
val established = builder.establish() ?: return false
// Keep ownership even if a subsequent permission check throws, so
// the common failure cleanup always closes the newly created fd.
mInterface = established
if (!startupLease.isValid(epoch) || permissionRevoked || prepare(this) != null) {
established.close()
mInterface = null
return false
}
isRunning = true
return true
return isSessionValid(epoch)
} catch (e: Exception) {
LogUtil.e(AppConfig.TAG, "Failed to establish VPN interface", e)
stopAllService()
@@ -363,12 +405,15 @@ class CoreVpnService : VpnService(), ServiceControl {
* Starts the tun2socks process with the appropriate parameters.
*/
private fun runTun2socks() {
val epoch = startupEpoch
val vpnInterface = mInterface ?: return
if (!isSessionValid(epoch)) return
if (SettingsManager.isUsingHevTun()) {
tun2SocksService = TProxyService(
context = applicationContext,
vpnInterface = mInterface,
isRunningProvider = { isRunning },
restartCallback = { runTun2socks() }
vpnInterface = vpnInterface,
isRunningProvider = { isSessionValid(epoch) },
restartCallback = { mainHandler.post { if (isSessionValid(epoch)) runTun2socks() } }
)
} else {
tun2SocksService = null
@@ -378,6 +423,19 @@ class CoreVpnService : VpnService(), ServiceControl {
}
private fun stopAllService(isForced: Boolean = true) {
val epoch = startupEpoch
startupLease.invalidate()
if (Looper.myLooper() == Looper.getMainLooper()) {
stopAllServiceOnMain(isForced)
} else {
mainHandler.post {
// A cleanup posted by an older session must not stop a later one.
if (startupEpoch == epoch) stopAllServiceOnMain(isForced)
}
}
}
private fun stopAllServiceOnMain(isForced: Boolean) {
authorizationJob?.cancel()
authorizationJob = null
// val configName = defaultDPreference.getPrefString(PREF_CURR_CONFIG_GUID, "")
@@ -405,24 +463,14 @@ class CoreVpnService : VpnService(), ServiceControl {
//in a row for several times. You will find that later created v2ray core report port in use
//which means the first v2ray core somehow failed to stop and release the port.
stopSelf()
// Add a small delay to allow the async core stop operation to complete
// before closing the VPN interface, preventing a race condition that can
// leave the VPN icon in the status bar after stopping the service.
try {
Thread.sleep(100)
} catch (e: InterruptedException) {
LogUtil.w(AppConfig.TAG, "StartCore-VPN: Sleep interrupted", e)
}
try {
if (::mInterface.isInitialized) {
mInterface.close()
LogUtil.i(AppConfig.TAG, "StartCore-VPN: VPN interface closed")
}
} catch (e: Exception) {
LogUtil.e(AppConfig.TAG, "StartCore-VPN: Failed to close interface", e)
}
}
// Close on every failure/destruction, including revoke before native start.
val vpnInterface = mInterface
mInterface = null
try {
vpnInterface?.close()
} catch (e: Exception) {
LogUtil.e(AppConfig.TAG, "StartCore-VPN: Failed to close interface", e)
}
}
}
@@ -4,6 +4,7 @@ import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.delay
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.isActive
import kotlinx.coroutines.ensureActive
/** Runs in the VPN service, so closing the activity cannot bypass revocation. */
object UcvlAuthorizationGuard {
@@ -14,23 +15,34 @@ object UcvlAuthorizationGuard {
loadToken: () -> String?,
check: suspend (String) -> Unit,
revoke: () -> Unit,
sessionChanged: () -> Unit,
intervalMillis: Long = 60_000,
) {
fun stopIfSessionChanged(): Boolean {
if (loadToken() == token) return false
// Stop the old tunnel, but do not revoke or hide a replacement login.
sessionChanged()
return true
}
while (currentCoroutineContext().isActive) {
if (loadToken() != token) { revoke(); return }
if (stopIfSessionChanged()) return
try {
check(token)
} catch (cancelled: CancellationException) {
throw cancelled
} catch (error: UcvlApiException) {
currentCoroutineContext().ensureActive()
if (error.statusCode == 401 || error.statusCode == 403) {
// A late reply for an old login must never erase a newer login.
if (loadToken() == token) revoke()
if (!stopIfSessionChanged()) revoke()
return
}
} catch (_: Exception) {
// Transient loss of connectivity is not evidence that an account was revoked.
}
currentCoroutineContext().ensureActive()
// Recheck immediately even after success/temporary failure, not 60 seconds later.
if (stopIfSessionChanged()) return
delay(intervalMillis)
}
}
@@ -12,6 +12,7 @@ import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import android.view.inputmethod.EditorInfo
import android.widget.ArrayAdapter
import android.widget.Button
@@ -27,6 +28,7 @@ import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowCompat
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.Lifecycle
import com.v2ray.ang.AppConfig
import com.v2ray.ang.R
import com.v2ray.ang.BuildConfig
@@ -44,6 +46,10 @@ import java.util.Locale
class UcvlMainActivity : AppCompatActivity() {
private val api = UcvlApiClient()
private val releases = UcvlReleaseChecker()
private var checkingUpdates = false
private var availableUpdate: UcvlUpdateOffer? = null
private var promptedUpdateVersion: String? = null
private val mainViewModel: MainViewModel by viewModels()
private var profile: UcvlProfile? = null
private var busy = false
@@ -81,6 +87,7 @@ class UcvlMainActivity : AppCompatActivity() {
} else {
pendingStart = false
setConnectionState(false, "未连接", "需要允许系统 VPN 连接请求")
availableUpdate?.let { showUpdateOffer(it, automatic = true) }
}
}
@@ -96,7 +103,7 @@ class UcvlMainActivity : AppCompatActivity() {
if (intent?.action != UcvlTraffic.ACTION) return
val up = intent.getLongExtra("up_speed", 0)
val down = intent.getLongExtra("down_speed", 0)
proxySpeed.text = "↑ ${formatBytes(up)}/s ↓ ${formatBytes(down)}/s"
proxySpeed.text = "↑ ${UcvlTrafficFormat.speed(up)} ↓ ${UcvlTrafficFormat.speed(down)}"
proxyTotal.text = "本次代理 ${formatBytes(intent.getLongExtra("total", 0))} · 仅统计 proxy 出站"
speedPoints.addLast(up to down)
while (speedPoints.size > 40) speedPoints.removeFirst()
@@ -104,8 +111,22 @@ class UcvlMainActivity : AppCompatActivity() {
}
}
@Suppress("DEPRECATION")
private fun prepareScenicWindow() {
WindowCompat.setDecorFitsSystemWindows(window, false)
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
if (Build.VERSION.SDK_INT < 35) {
// Older releases keep the theme's opaque bars, including its night colors.
val surface = ContextCompat.getColor(this, R.color.ucvl_surface)
window.statusBarColor = surface
window.navigationBarColor = surface
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
promptedUpdateVersion = savedInstanceState?.getString("ucvl.promptedUpdateVersion")
prepareScenicWindow()
setContentView(R.layout.activity_ucvl_main)
val root = findViewById<View>(R.id.ucvlRoot)
ViewCompat.setOnApplyWindowInsetsListener(root) { view, insets ->
@@ -115,6 +136,7 @@ class UcvlMainActivity : AppCompatActivity() {
insets
}
WindowCompat.getInsetsController(window, root).isAppearanceLightStatusBars = true
WindowCompat.getInsetsController(window, root).isAppearanceLightNavigationBars = true
bindViews()
setupActions()
setupCoreState()
@@ -131,6 +153,17 @@ class UcvlMainActivity : AppCompatActivity() {
showDashboardLoading()
refreshProfile(token, initial = true)
}
checkUpdates(manual = false)
}
override fun onResume() {
super.onResume()
availableUpdate?.let { showUpdateOffer(it, automatic = true) }
}
override fun onSaveInstanceState(outState: Bundle) {
outState.putString("ucvl.promptedUpdateVersion", promptedUpdateVersion)
super.onSaveInstanceState(outState)
}
private fun bindViews() {
@@ -161,6 +194,11 @@ class UcvlMainActivity : AppCompatActivity() {
}
private fun setupActions() {
findViewById<Button>(R.id.checkUpdatesButton).setOnClickListener {
val offer = availableUpdate
if (offer == null) checkUpdates(manual = true)
else showUpdateOffer(offer, automatic = false)
}
findViewById<View>(R.id.registerButton).setOnClickListener {
openWeb("https://vpn.toplc.cn/register/")
}
@@ -401,7 +439,7 @@ class UcvlMainActivity : AppCompatActivity() {
val identity = if (value.identityType == "employee") "内部员工" else "外部联系人"
accountText.text = "${value.email} · $identity"
routeSpinner.adapter = ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, value.routeModes)
routeSpinner.adapter = ArrayAdapter(this, R.layout.ucvl_spinner_item, value.routeModes)
val lastRoute = MmkvManager.decodeSettingsString(LAST_ROUTE_KEY, "smart").orEmpty()
value.routeModes.indexOfFirst { it.id == lastRoute }.takeIf { it >= 0 }?.let(routeSpinner::setSelection)
usageChart.setPoints(value.usageHistory.orEmpty().map { it.uploadBytes to it.downloadBytes })
@@ -460,6 +498,7 @@ class UcvlMainActivity : AppCompatActivity() {
statusDetail.text = message
}
loginButton.text = if (value && loginPanel.visibility == View.VISIBLE) "请稍候…" else "安全登录"
if (!value) availableUpdate?.let { showUpdateOffer(it, automatic = true) }
}
private fun friendlyError(exception: Exception): String = when (exception) {
@@ -468,6 +507,41 @@ class UcvlMainActivity : AppCompatActivity() {
else -> exception.message?.takeIf { it.isNotBlank() } ?: "网络连接失败,请检查当前网络。"
}
private fun checkUpdates(manual: Boolean) {
if (checkingUpdates) return
checkingUpdates = true
val button = findViewById<Button>(R.id.checkUpdatesButton)
val status = findViewById<TextView>(R.id.updateStatus)
button.isEnabled = false
if (manual) status.text = "正在检查公司 Git…"
lifecycleScope.launch {
try {
availableUpdate = releases.latest(BuildConfig.VERSION_NAME)
val offer = availableUpdate
button.text = offer?.let { "下载新版本 ${it.version}" } ?: "检查软件更新"
status.text = if (offer != null) "新版本已发布,可覆盖升级保留配置" else if (manual) "暂无更新的 Android 正式版" else ""
if (offer != null && !manual) showUpdateOffer(offer, automatic = true)
} catch (cancelled: kotlinx.coroutines.CancellationException) {
throw cancelled
} catch (_: Exception) {
if (manual) status.text = "暂未取得版本信息,VPN 连接不受影响"
} finally {
checkingUpdates = false
button.isEnabled = true
}
}
}
private fun showUpdateOffer(offer: UcvlUpdateOffer, automatic: Boolean) {
if (isFinishing || isDestroyed || !lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) return
if (automatic && (busy || pendingStart || promptedUpdateVersion == offer.version)) return
promptedUpdateVersion = offer.version
MaterialAlertDialogBuilder(this).setTitle("发现新版本 ${offer.version}")
.setMessage("从公司 Git 下载并使用系统安装器覆盖升级,保留账号和配置。不要先卸载旧版本。Android 要求的安装授权仍需本人确认。")
.setPositiveButton("前往下载") { _, _ -> openWeb(offer.url) }
.setNegativeButton("暂不更新", null).show()
}
private fun openWeb(url: String) {
try { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url))) }
catch (_: android.content.ActivityNotFoundException) {
@@ -491,6 +565,7 @@ class UcvlMainActivity : AppCompatActivity() {
override fun onDestroy() {
unregisterReceiver(trafficReceiver)
api.close()
releases.close()
super.onDestroy()
}
@@ -0,0 +1,134 @@
package com.v2ray.ang.ucvl
import com.google.gson.JsonArray
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.Closeable
import java.io.IOException
import java.net.Proxy
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
data class UcvlUpdateOffer(val version: String, val url: String, val size: Long)
/** Anonymous Git lookups never share platform credentials or control the VPN. */
class UcvlReleaseChecker : Closeable {
private val client = OkHttpClient.Builder().proxy(Proxy.NO_PROXY)
.followRedirects(false).followSslRedirects(false)
.connectTimeout(10, TimeUnit.SECONDS).callTimeout(20, TimeUnit.SECONDS).build()
suspend fun latest(current: String): UcvlUpdateOffer? = withContext(Dispatchers.IO) {
// One deadline covers every page; a shared cross-platform repository can
// place Android releases beyond the first page after many Windows releases.
val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(20)
lookup(current) { page ->
val call = client.newCall(Request.Builder().url("$RELEASE_API&page=$page")
.header("Accept", "application/json").get().build())
call.timeout().deadlineNanoTime(deadline)
call.execute().use { response ->
if (!response.isSuccessful) throw IOException("暂时无法读取公司 Git 版本列表。")
val body = response.body
if (body.contentLength() > MAX_METADATA) throw IOException("版本列表过大。")
// Bound decoded body size as well, including chunked/gzip responses.
val source = body.source()
source.request(MAX_METADATA + 1)
if (source.buffer.size > MAX_METADATA) throw IOException("版本列表过大。")
source.readUtf8()
}
}
}
override fun close() {
client.dispatcher.cancelAll()
cleanup.execute {
client.connectionPool.evictAll()
client.dispatcher.executorService.shutdown()
}
}
companion object {
const val RELEASE_API = "https://pro.ucvl.cn/api/v1/repos/admin/ucvl-software-downloads/releases?limit=50"
private const val DOWNLOAD_ROOT = "https://pro.ucvl.cn/admin/ucvl-software-downloads/releases/download/"
private const val MAX_METADATA = 1024L * 1024
private const val MAX_TOTAL_METADATA = 4L * MAX_METADATA
private const val PAGE_SIZE = 50
private const val MAX_PAGES = 10
private val tagPattern = Regex("^android-v(\\d+\\.\\d+\\.\\d+)$")
private val versionPattern = Regex("^(\\d+)\\.(\\d+)\\.(\\d+)$")
private val cleanup = Executors.newSingleThreadExecutor { work ->
Thread(work, "UCVL-release-cleanup").apply { isDaemon = true }
}
private fun parts(version: String): List<Int> = versionPattern.matchEntire(version)?.groupValues
?.drop(1)?.map { it.toIntOrNull() ?: throw IOException("无效版本号。") }
?: throw IOException("无效版本号。")
private fun compare(left: List<Int>, right: List<Int>): Int {
for (index in 0..2) if (left[index] != right[index]) return left[index].compareTo(right[index])
return 0
}
internal fun select(json: String, current: String): UcvlUpdateOffer? {
return select(array(json), current)
}
internal suspend fun lookup(current: String, loadPage: suspend (Int) -> String): UcvlUpdateOffer? {
val releases = JsonArray()
var bytes = 0L
for (page in 1..MAX_PAGES) {
val text = loadPage(page)
val size = text.toByteArray(Charsets.UTF_8).size.toLong()
bytes += size
if (size > MAX_METADATA || bytes > MAX_TOTAL_METADATA) throw IOException("版本列表过大。")
val rows = array(text)
releases.addAll(rows)
if (rows.size() < PAGE_SIZE) return select(releases, current)
}
throw IOException("版本列表分页过多,请稍后重试或从公司发布页下载。")
}
private fun array(text: String): JsonArray = try {
JsonParser.parseString(text).asJsonArray
} catch (error: RuntimeException) {
throw IOException("版本列表格式异常。", error)
}
private fun select(rows: JsonArray, current: String): UcvlUpdateOffer? {
val installed = parts(current.substringBefore('-').substringBefore('+'))
val releases = rows.filter { it.isJsonObject }.map { it.asJsonObject }
.mapNotNull { release ->
// Malformed records for other products must not hide valid
// Android updates. Missing flags remain ineligible.
val tag = release.get("tag_name")?.takeIf { it.isJsonPrimitive && it.asJsonPrimitive.isString }
?.asString.orEmpty()
val match = tagPattern.matchEntire(tag) ?: return@mapNotNull null
if (!release.isFalse("draft") || !release.isFalse("prerelease")) return@mapNotNull null
val version = match.groupValues[1]
val parsed = try { parts(version) } catch (_: IOException) { return@mapNotNull null }
Triple(release, version, parsed)
}
val selected = releases.maxWithOrNull { left, right -> compare(left.third, right.third) } ?: return null
if (compare(selected.third, installed) <= 0) return null
val version = selected.second
val filename = "UCVL-Zonghengjia-$version-android-universal.apk"
// Universal is an explicit cross-ABI package; never offer an arbitrary
// first attachment, a Windows EXE, or a different publisher's APK.
val assets = selected.first.get("assets")?.takeIf { it.isJsonArray }?.asJsonArray
?.filter { it.isJsonObject }?.map { it.asJsonObject }
?.filter { it.get("name")?.takeIf { value -> value.isJsonPrimitive }?.asString == filename }
?: throw IOException("正式版本缺少 Android 安装包列表。")
if (assets.size != 1) throw IOException("正式版本缺少唯一的 Android 通用安装包。")
val size = assets.single().get("size")?.asLong ?: 0
if (size <= 0 || size > 250L * 1024 * 1024) throw IOException("安装包大小异常。")
return UcvlUpdateOffer(version, "$DOWNLOAD_ROOT${selected.first.get("tag_name").asString}/$filename", size)
}
private fun JsonObject.isFalse(name: String): Boolean = get(name)?.let {
it.isJsonPrimitive && it.asJsonPrimitive.isBoolean && !it.asBoolean
} == true
}
}
@@ -0,0 +1,16 @@
package com.v2ray.ang.ucvl
import java.util.Locale
/** Proxy speed uses KB/s or larger units, including idle and very small samples. */
object UcvlTrafficFormat {
fun speed(bytesPerSecond: Long): String {
if (bytesPerSecond <= 0) return "0.0 KB/s"
var amount = bytesPerSecond.toDouble() / 1024
if (amount < 0.1) return "<0.1 KB/s"
val units = arrayOf("KB/s", "MB/s", "GB/s", "TB/s")
var unit = 0
while (amount >= 1024 && unit < units.lastIndex) { amount /= 1024; unit++ }
return String.format(Locale.US, "%.1f %s", amount, units[unit])
}
}
@@ -0,0 +1,33 @@
package com.v2ray.ang.ucvl
import java.util.concurrent.atomic.AtomicLong
/**
* A startup owns one epoch. Android can revoke it on a Binder thread while the
* main thread is still establishing the TUN or starting native code.
*
* Never hold [reportLock] around Android permission calls, native start/stop, or
* cleanup. It only orders invalidation with short, final state reports.
*/
class UcvlVpnStartupLease {
private val state = AtomicLong(0)
private val reportLock = Any()
fun begin(): Long = synchronized(reportLock) {
val next = (state.get() and -2L) + 3L
state.set(next)
next
}
fun invalidate() = synchronized(reportLock) {
state.set(state.get() and -2L)
}
fun isValid(epoch: Long): Boolean = epoch and 1L == 1L && state.get() == epoch
fun reportIfValid(epoch: Long, report: () -> Unit): Boolean = synchronized(reportLock) {
if (!isValid(epoch)) return@synchronized false
report()
true
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 MiB

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="@color/ucvl_glass_white" />
<corners android:radius="18dp" />
<stroke android:width="1dp" android:color="@color/ucvl_glass_border" />
</shape>
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<gradient
android:angle="270"
android:startColor="#D9F3F7FC"
android:centerColor="#26F3F7FC"
android:endColor="#D9F3F7FC" />
</shape>
@@ -1,390 +1,482 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/ucvlRoot"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/ucvl_surface"
android:fillViewport="true">
android:background="@color/ucvl_surface">
<LinearLayout
<!-- The original desktop artwork stays separate from every native control. -->
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
android:layout_height="match_parent"
android:alpha="0.86"
android:contentDescription="@null"
android:importantForAccessibility="no"
android:scaleType="centerCrop"
android:src="@drawable/ucvl_landscape_header_v1" />
<View
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/ucvl_scenic_mist"
android:importantForAccessibility="no" />
<androidx.core.widget.NestedScrollView
android:id="@+id/ucvlRoot"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="true"
android:fillViewport="true"
android:overScrollMode="never">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/ucvl_navy"
android:gravity="center_vertical"
android:orientation="horizontal"
android:paddingStart="22dp"
android:paddingTop="22dp"
android:paddingEnd="22dp"
android:orientation="vertical"
android:paddingStart="18dp"
android:paddingEnd="18dp"
android:paddingBottom="22dp">
<ImageView
android:layout_width="72dp"
android:layout_height="72dp"
android:contentDescription="@string/app_name"
android:src="@drawable/zonghengjia_logo" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal"
android:paddingTop="26dp"
android:paddingBottom="24dp">
<ImageView
android:layout_width="60dp"
android:layout_height="60dp"
android:contentDescription="@string/app_name"
android:src="@drawable/zonghengjia_logo" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="纵横家"
android:textColor="@color/ucvl_text"
android:textSize="28sp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:text="智能安全网络 · Android"
android:textColor="@color/ucvl_muted"
android:textSize="13sp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:id="@+id/loginPanel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_weight="1"
android:orientation="vertical">
android:background="@drawable/ucvl_glass_card"
android:orientation="vertical"
android:padding="20dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="优创⁺纵横家"
android:textColor="@android:color/white"
android:textSize="24sp"
android:text="登录纵横家"
android:textColor="@color/ucvl_text"
android:textSize="25sp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:text="Powered by 优创未来 · Android"
android:textColor="#B8DAF4"
android:layout_marginTop="6dp"
android:text="使用公司分配的用户名或邮箱登录"
android:textColor="@color/ucvl_muted"
android:textSize="14sp" />
<EditText
android:id="@+id/loginInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="28dp"
android:minHeight="56dp"
android:autofillHints="username"
android:background="@drawable/ucvl_input"
android:hint="用户名 / 邮箱"
android:inputType="textEmailAddress"
android:imeOptions="actionNext"
android:singleLine="true"
android:maxLines="1"
android:textColor="@color/ucvl_text"
android:textColorHint="@color/ucvl_muted" />
<EditText
android:id="@+id/passwordInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="14dp"
android:minHeight="56dp"
android:autofillHints="password"
android:background="@drawable/ucvl_input"
android:hint="密码"
android:imeOptions="actionDone"
android:inputType="textPassword"
android:singleLine="true"
android:maxLines="1"
android:textColor="@color/ucvl_text"
android:textColorHint="@color/ucvl_muted" />
<TextView
android:id="@+id/loginError"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:textColor="@color/ucvl_danger"
android:textSize="13sp" />
<com.google.android.material.button.MaterialButton
android:id="@+id/loginButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="14dp"
android:minHeight="54dp"
android:text="安全登录"
android:textColor="@android:color/white"
android:textSize="16sp"
app:backgroundTint="@color/ucvl_royal"
app:cornerRadius="12dp" />
<com.google.android.material.button.MaterialButton
android:id="@+id/registerButton"
style="@style/Widget.MaterialComponents.Button.TextButton"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:minHeight="48dp"
android:text="注册新用户 · 审核后使用"
android:maxLines="2"
android:singleLine="false"
android:textColor="@color/ucvl_royal" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:gravity="center"
android:text="账号停用后,设备授权与线路会自动失效"
android:textColor="@color/ucvl_muted"
android:textSize="12sp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="@+id/loginPanel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="24dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="登录优创⁺纵横家"
android:textColor="@color/ucvl_text"
android:textSize="25sp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="6dp"
android:text="使用公司分配的用户名或邮箱登录"
android:textColor="@color/ucvl_muted"
android:textSize="14sp" />
<EditText
android:id="@+id/loginInput"
android:layout_width="match_parent"
android:layout_height="56dp"
android:layout_marginTop="28dp"
android:autofillHints="username"
android:background="@drawable/ucvl_input"
android:hint="用户名 / 邮箱"
android:inputType="textEmailAddress"
android:maxLines="1"
android:textColor="@color/ucvl_text"
android:textColorHint="@color/ucvl_muted" />
<EditText
android:id="@+id/passwordInput"
android:layout_width="match_parent"
android:layout_height="56dp"
android:layout_marginTop="14dp"
android:autofillHints="password"
android:background="@drawable/ucvl_input"
android:hint="密码"
android:imeOptions="actionDone"
android:inputType="textPassword"
android:maxLines="1"
android:textColor="@color/ucvl_text"
android:textColorHint="@color/ucvl_muted" />
<TextView
android:id="@+id/loginError"
<LinearLayout
android:id="@+id/dashboardPanel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:textColor="@color/ucvl_danger"
android:textSize="13sp" />
<com.google.android.material.button.MaterialButton
android:id="@+id/loginButton"
android:layout_width="match_parent"
android:layout_height="54dp"
android:layout_marginTop="14dp"
android:text="安全登录"
android:textSize="16sp"
app:backgroundTint="@color/ucvl_royal"
app:cornerRadius="12dp" />
<com.google.android.material.button.MaterialButton
android:id="@+id/registerButton"
style="@style/Widget.MaterialComponents.Button.TextButton"
android:layout_width="match_parent" android:layout_height="48dp"
android:text="注册新用户 · 审核后使用" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:gravity="center"
android:text="账号停用后,设备授权与线路会自动失效"
android:textColor="@color/ucvl_muted"
android:textSize="12sp" />
</LinearLayout>
<LinearLayout
android:id="@+id/dashboardPanel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="18dp"
android:visibility="gone">
<TextView
android:id="@+id/welcomeText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/ucvl_text"
android:textSize="23sp"
android:textStyle="bold" />
<TextView
android:id="@+id/accountText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:textColor="@color/ucvl_muted"
android:textSize="13sp" />
<com.google.android.material.card.MaterialCardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="18dp"
app:cardBackgroundColor="@android:color/white"
app:cardCornerRadius="18dp"
app:strokeColor="@color/ucvl_border"
app:strokeWidth="1dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal"
android:padding="20dp">
<TextView
android:id="@+id/statusDot"
android:layout_width="36dp"
android:layout_height="wrap_content"
android:gravity="center"
android:text="●"
android:textColor="@color/ucvl_muted"
android:textSize="24sp" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="@+id/statusTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="未连接"
android:textColor="@color/ucvl_text"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="@+id/statusDetail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:text="点击连接,由平台自动选择节点"
android:textColor="@color/ucvl_muted"
android:textSize="13sp" />
</LinearLayout>
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
<com.google.android.material.card.MaterialCardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="14dp"
app:cardBackgroundColor="@android:color/white"
app:cardCornerRadius="18dp"
app:strokeColor="@color/ucvl_border"
app:strokeWidth="1dp">
android:orientation="vertical"
android:visibility="gone">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/ucvl_glass_card"
android:orientation="vertical"
android:padding="18dp">
<TextView
android:layout_width="wrap_content"
android:id="@+id/welcomeText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="当前工作节点"
android:textColor="@color/ucvl_text"
android:textSize="23sp"
android:textStyle="bold" />
<TextView
android:id="@+id/currentNode"
android:id="@+id/accountText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="6dp"
android:text="连接后显示实际工作节点"
android:textColor="@color/ucvl_royal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="代理模式"
android:textColor="@color/ucvl_text"
android:textStyle="bold" />
<Spinner
android:id="@+id/routeSpinner"
android:layout_width="match_parent"
android:layout_height="52dp"
android:layout_marginTop="6dp"
android:background="@drawable/ucvl_input" />
<com.google.android.material.button.MaterialButton
android:id="@+id/connectButton"
android:layout_width="match_parent"
android:layout_height="56dp"
android:layout_marginTop="20dp"
android:text="连接"
android:textSize="17sp"
app:backgroundTint="@color/ucvl_royal"
app:cornerRadius="14dp" />
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
<com.google.android.material.card.MaterialCardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="14dp"
app:cardBackgroundColor="@android:color/white"
app:cardCornerRadius="18dp"
app:strokeColor="@color/ucvl_border"
app:strokeWidth="1dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="18dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="本期流量"
android:textColor="@color/ucvl_text"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="@+id/usageText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:textColor="@color/ucvl_royal"
android:textSize="17sp"
android:textStyle="bold" />
<ProgressBar
android:id="@+id/usageProgress"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="10dp"
android:layout_marginTop="10dp"
android:max="100"
android:progressTint="@color/ucvl_blue" />
<TextView
android:id="@+id/planText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginTop="4dp"
android:textColor="@color/ucvl_muted"
android:textSize="13sp" />
<TextView android:id="@+id/proxySpeed" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_marginTop="14dp"
android:text="↑ 0 B/s ↓ 0 B/s" android:textColor="@color/ucvl_royal" />
<com.v2ray.ang.ucvl.UcvlTrafficChart android:id="@+id/speedChart"
android:layout_width="match_parent" android:layout_height="56dp"
android:contentDescription="近期代理上传蓝线、下载青线速率,每三秒采样" />
<TextView android:id="@+id/proxyTotal" android:layout_width="match_parent"
android:layout_height="wrap_content" android:text="本次代理 0 B · 仅统计 proxy 出站"
android:textColor="@color/ucvl_muted" android:textSize="12sp" />
<TextView android:layout_width="match_parent" android:layout_height="wrap_content"
android:layout_marginTop="10dp" android:text="近 7 天代理用量 · 蓝色上传 / 青色下载"
android:textColor="@color/ucvl_muted" android:textSize="12sp" />
<com.v2ray.ang.ucvl.UcvlTrafficChart android:id="@+id/usageChart"
android:layout_width="match_parent" android:layout_height="56dp"
android:contentDescription="近七天代理上传和下载用量" />
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
<com.google.android.material.card.MaterialCardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="18dp"
app:cardBackgroundColor="@color/ucvl_glass_white"
app:cardCornerRadius="18dp"
app:cardElevation="0dp"
app:strokeColor="@color/ucvl_glass_border"
app:strokeWidth="1dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal"
android:padding="20dp">
<TextView
android:id="@+id/statusDot"
android:layout_width="36dp"
android:layout_height="wrap_content"
android:gravity="center"
android:text="●"
android:textColor="@color/ucvl_muted"
android:textSize="24sp" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="@+id/statusTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="未连接"
android:textColor="@color/ucvl_text"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="@+id/statusDetail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:text="点击连接,由平台自动选择节点"
android:textColor="@color/ucvl_muted"
android:textSize="13sp" />
</LinearLayout>
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
<com.google.android.material.card.MaterialCardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="14dp"
app:cardBackgroundColor="@color/ucvl_glass_white"
app:cardCornerRadius="18dp"
app:cardElevation="0dp"
app:strokeColor="@color/ucvl_glass_border"
app:strokeWidth="1dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="18dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="当前工作节点"
android:textColor="@color/ucvl_text"
android:textStyle="bold" />
<TextView
android:id="@+id/currentNode"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="6dp"
android:text="连接后显示实际工作节点"
android:textColor="@color/ucvl_royal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="代理模式"
android:textColor="@color/ucvl_text"
android:textStyle="bold" />
<Spinner
android:id="@+id/routeSpinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="6dp"
android:minHeight="52dp"
android:popupBackground="@android:color/white"
android:background="@drawable/ucvl_input" />
<com.google.android.material.button.MaterialButton
android:id="@+id/connectButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:minHeight="56dp"
android:text="连接"
android:textColor="@android:color/white"
android:textSize="17sp"
app:backgroundTint="@color/ucvl_royal"
app:cornerRadius="14dp" />
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
<com.google.android.material.card.MaterialCardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="14dp"
app:cardBackgroundColor="@color/ucvl_glass_white"
app:cardCornerRadius="18dp"
app:cardElevation="0dp"
app:strokeColor="@color/ucvl_glass_border"
app:strokeWidth="1dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="18dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="本期流量"
android:textColor="@color/ucvl_text"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="@+id/usageText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:textColor="@color/ucvl_royal"
android:textSize="17sp"
android:textStyle="bold" />
<ProgressBar
android:id="@+id/usageProgress"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="10dp"
android:layout_marginTop="10dp"
android:max="100"
android:progressTint="@color/ucvl_blue" />
<TextView
android:id="@+id/planText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:textColor="@color/ucvl_muted"
android:textSize="13sp" />
<TextView android:id="@+id/proxySpeed" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_marginTop="14dp"
android:text="↑ 0.0 KB/s ↓ 0.0 KB/s" android:textColor="@color/ucvl_royal" />
<com.v2ray.ang.ucvl.UcvlTrafficChart android:id="@+id/speedChart"
android:layout_width="match_parent" android:layout_height="56dp"
android:contentDescription="近期代理上传蓝线、下载青线速率,每三秒采样" />
<TextView android:id="@+id/proxyTotal" android:layout_width="match_parent"
android:layout_height="wrap_content" android:text="本次代理 0 B · 仅统计 proxy 出站"
android:textColor="@color/ucvl_muted" android:textSize="12sp" />
<TextView android:layout_width="match_parent" android:layout_height="wrap_content"
android:layout_marginTop="10dp" android:text="近 7 天代理用量 · 蓝色上传 / 青色下载"
android:textColor="@color/ucvl_muted" android:textSize="12sp" />
<com.v2ray.ang.ucvl.UcvlTrafficChart android:id="@+id/usageChart"
android:layout_width="match_parent" android:layout_height="56dp"
android:contentDescription="近七天代理上传和下载用量" />
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:orientation="horizontal">
<com.google.android.material.button.MaterialButton
android:id="@+id/refreshButton"
style="@style/Widget.MaterialComponents.Button.OutlinedButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:minHeight="48dp"
android:text="刷新"
android:maxLines="2"
android:singleLine="false"
android:textColor="@color/ucvl_royal"
app:backgroundTint="@color/ucvl_glass_white"
app:strokeColor="@color/ucvl_border" />
<com.google.android.material.button.MaterialButton
android:id="@+id/logoutButton"
style="@style/Widget.MaterialComponents.Button.OutlinedButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_weight="1"
android:minHeight="48dp"
android:text="退出账号"
android:maxLines="2"
android:singleLine="false"
android:textColor="@color/ucvl_royal"
app:backgroundTint="@color/ucvl_glass_white"
app:strokeColor="@color/ucvl_border" />
</LinearLayout>
<com.google.android.material.button.MaterialButton
android:id="@+id/exitButton"
style="@style/Widget.MaterialComponents.Button.TextButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:minHeight="48dp"
android:text="断开并退出应用"
android:maxLines="2"
android:singleLine="false"
android:textColor="@color/ucvl_danger" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:gravity="center"
android:text="公司策略 · 代理流量统计\nvpn.toplc.cn · © 2026 UCVL"
android:textColor="@color/ucvl_muted"
android:textSize="12sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:orientation="horizontal">
android:layout_marginTop="18dp"
android:background="@drawable/ucvl_glass_card"
android:orientation="vertical"
android:padding="8dp">
<TextView
android:id="@+id/updateStatus"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:gravity="center" android:textSize="12sp" android:paddingHorizontal="20dp"
android:textColor="@color/ucvl_muted" />
<com.google.android.material.button.MaterialButton
android:id="@+id/refreshButton"
style="@style/Widget.MaterialComponents.Button.OutlinedButton"
android:layout_width="0dp"
android:layout_height="48dp"
android:layout_weight="1"
android:text="刷新" />
android:id="@+id/checkUpdatesButton"
style="@style/Widget.MaterialComponents.Button.TextButton"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:minHeight="48dp"
android:text="检查软件更新"
android:maxLines="2"
android:singleLine="false"
android:textColor="@color/ucvl_royal" />
<com.google.android.material.button.MaterialButton
android:id="@+id/logoutButton"
style="@style/Widget.MaterialComponents.Button.OutlinedButton"
android:layout_width="0dp"
android:layout_height="48dp"
android:layout_marginStart="10dp"
android:layout_weight="1"
android:text="退出账号" />
android:id="@+id/openSourceButton"
style="@style/Widget.MaterialComponents.Button.TextButton"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:minHeight="48dp"
android:text="版本与开源许可"
android:maxLines="2"
android:singleLine="false"
android:textColor="@color/ucvl_royal" />
</LinearLayout>
<com.google.android.material.button.MaterialButton
android:id="@+id/exitButton"
style="@style/Widget.MaterialComponents.Button.TextButton"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_marginTop="4dp"
android:text="断开并退出应用"
android:textColor="@color/ucvl_danger" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:gravity="center"
android:text="公司策略 · 代理流量统计\nvpn.toplc.cn · © 2026 UCVL"
android:textColor="@color/ucvl_muted"
android:textSize="12sp" />
</LinearLayout>
<com.google.android.material.button.MaterialButton
android:id="@+id/openSourceButton"
style="@style/Widget.MaterialComponents.Button.TextButton"
android:layout_width="match_parent" android:layout_height="48dp"
android:text="版本与开源许可" />
</LinearLayout>
</androidx.core.widget.NestedScrollView>
</androidx.core.widget.NestedScrollView>
</FrameLayout>
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:minHeight="48dp"
android:paddingStart="8dp"
android:paddingTop="10dp"
android:paddingEnd="8dp"
android:paddingBottom="10dp"
android:textColor="@color/ucvl_text"
android:textSize="15sp" />
@@ -5,8 +5,10 @@
<color name="ucvl_royal">#1167D8</color>
<color name="ucvl_surface">#F3F7FC</color>
<color name="ucvl_text">#0B284D</color>
<color name="ucvl_muted">#7186A1</color>
<color name="ucvl_muted">#435F7B</color>
<color name="ucvl_success">#15966A</color>
<color name="ucvl_danger">#C63F45</color>
<color name="ucvl_border">#D8E4F0</color>
<color name="ucvl_glass_white">#80FFFFFF</color>
<color name="ucvl_glass_border">#B3FFFFFF</color>
</resources>
@@ -1,13 +1,15 @@
package com.v2ray.ang.ucvl
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.withTimeout
import org.junit.Assert.*
import org.junit.Test
class UcvlAuthorizationGuardTest {
@Test fun revokedLoginStops() = runBlocking {
var stopped = false
UcvlAuthorizationGuard.watch("old", { "old" }, { throw UcvlApiException(401, "revoked") }, { stopped = true }, 1)
UcvlAuthorizationGuard.watch("old", { "old" }, { throw UcvlApiException(401, "revoked") }, { stopped = true }, { fail("Unchanged session") }, 1)
assertTrue(stopped)
}
@Test fun transientFailureDoesNotRevoke() = runBlocking {
@@ -18,18 +20,93 @@ class UcvlAuthorizationGuardTest {
if (calls == 1) throw java.io.IOException("offline")
assertFalse(stopped)
throw UcvlApiException(403, "revoked")
}, { stopped = true }, 1)
}, { stopped = true }, { fail("Unchanged session") }, 1)
assertEquals(2, calls)
assertTrue(stopped)
}
@Test fun staleResponseCannotClearNewLogin() = runBlocking {
var token = "old"
var stopped = false
var oldTunnelStopped = false
UcvlAuthorizationGuard.watch("old", { token }, {
token = "new"
throw UcvlApiException(401, "old response")
}, { stopped = true }, 1)
}, { stopped = true }, { oldTunnelStopped = true }, 1)
assertFalse(stopped)
assertTrue(oldTunnelStopped)
assertEquals("new", token)
}
@Test fun lateSuccessMustNotRevokeNewLogin() = runBlocking {
var token = "old"
var revoked = false
var oldTunnelStopped = false
withTimeout(1_000) {
UcvlAuthorizationGuard.watch("old", { token }, {
token = "new"
}, { revoked = true }, { oldTunnelStopped = true }, 60_000)
}
assertFalse("An old successful request must not revoke a replacement login", revoked)
assertTrue("Old tunnel must stop without waiting for the next poll", oldTunnelStopped)
assertEquals("new", token)
}
@Test fun replacementBeforeRequestStopsOnlyOldTunnel() = runBlocking {
var changes = 0
UcvlAuthorizationGuard.watch("old", { "new" }, { fail("Must not query old token") },
{ fail("Must not revoke new login") }, { changes++ })
assertEquals(1, changes)
}
@Test fun removedLoginStopsOldTunnelWithoutFalseRevocation() = runBlocking {
var changes = 0
UcvlAuthorizationGuard.watch("old", { null }, { fail("Already logged out") },
{ fail("No current login to revoke") }, { changes++ })
assertEquals(1, changes)
}
@Test fun lateTransientErrorStopsChangedSessionImmediately() = runBlocking {
var token = "old"
var changes = 0
withTimeout(1_000) {
UcvlAuthorizationGuard.watch("old", { token }, {
token = "new"
throw java.io.IOException("offline")
}, { fail("Network errors must not revoke a new login") }, { changes++ }, 60_000)
}
assertEquals(1, changes)
assertEquals("new", token)
}
@Test fun cancelledRequestDoesNotRevokeOrStopAnotherSession() = runBlocking {
var cancellationPropagated = false
try {
UcvlAuthorizationGuard.watch("old", { "old" }, { throw CancellationException("service stopped") },
{ fail("Cancelled watcher must not revoke") }, { fail("Cancelled watcher must not stop") })
} catch (_: CancellationException) { cancellationPropagated = true }
assertTrue(cancellationPropagated)
}
@Test fun sameLoginSuccessKeepsWatchingUntilActuallyRevoked() = runBlocking {
var calls = 0
var revocations = 0
UcvlAuthorizationGuard.watch("old", { "old" }, {
calls++
if (calls == 2) throw UcvlApiException(403, "revoked")
assertEquals(0, revocations)
}, { revocations++ }, { fail("Same session") }, 1)
assertEquals(2, calls)
assertEquals(1, revocations)
}
@Test fun lateForbiddenMustNotRevokeNewLogin() = runBlocking {
var token = "old"
var changes = 0
UcvlAuthorizationGuard.watch("old", { token }, {
token = "new"
throw UcvlApiException(403, "old forbidden response")
}, { fail("New login must survive") }, { changes++ }, 1)
assertEquals(1, changes)
assertEquals("new", token)
}
}
@@ -0,0 +1,42 @@
package com.v2ray.ang.ucvl
import org.junit.Assert.*
import org.junit.Test
class UcvlReleaseCheckerTest {
private fun fixture(version: String = "1.0.3", tag: String = "android-v$version", draft: Boolean = false,
preview: Boolean = false, size: Long = 30000000, file: String = "UCVL-Zonghengjia-$version-android-universal.apk") =
"""[{"tag_name":"$tag","draft":$draft,"prerelease":$preview,"assets":[
{"name":"$file","size":$size,"browser_download_url":"https://example.invalid/unsafe.apk"}]}]"""
@Test fun usesOnlyCompanyGitCanonicalDownloadAndUniversalApk() {
val offer = UcvlReleaseChecker.select(fixture(), "1.0.2")!!
assertEquals("1.0.3", offer.version)
assertEquals("https://pro.ucvl.cn/admin/ucvl-software-downloads/releases/download/android-v1.0.3/UCVL-Zonghengjia-1.0.3-android-universal.apk", offer.url)
assertEquals(30000000L, offer.size)
}
@Test fun skipsDraftAndPreviewAndOtherPlatforms() {
assertNull(UcvlReleaseChecker.select(fixture(draft = true), "1.0.2"))
assertNull(UcvlReleaseChecker.select(fixture(preview = true), "1.0.2"))
assertNull(UcvlReleaseChecker.select(fixture(tag = "windows-v9.0.0"), "1.0.2"))
}
@Test fun comparesVersionsNumericallyWithoutDowngrades() {
assertNull(UcvlReleaseChecker.select(fixture(), "1.0.3"))
assertNull(UcvlReleaseChecker.select(fixture(), "1.0.4"))
assertNotNull(UcvlReleaseChecker.select(fixture(version = "1.0.10"), "1.0.9"))
assertNotNull(UcvlReleaseChecker.select(fixture(), "1.0.2+debug"))
assertNull(UcvlReleaseChecker.select("[]", "1.0.2"))
}
@Test(expected = java.io.IOException::class) fun rejectsMissingUniversal() {
UcvlReleaseChecker.select(fixture(file = "UCVL-Zonghengjia-1.0.3-android-arm64-v8a.apk"), "1.0.2")
}
@Test(expected = java.io.IOException::class) fun rejectsOversizedPackage() {
UcvlReleaseChecker.select(fixture(size = 251L * 1024 * 1024), "1.0.2")
}
@Test(expected = java.io.IOException::class) fun rejectsEmptyPackage() {
UcvlReleaseChecker.select(fixture(size = 0), "1.0.2")
}
@Test(expected = java.io.IOException::class) fun rejectsTraversalAttachment() {
UcvlReleaseChecker.select(fixture(file = "../unsafe.apk"), "1.0.2")
}
}
@@ -0,0 +1,74 @@
package com.v2ray.ang.ucvl
import kotlinx.coroutines.runBlocking
import org.junit.Assert.*
import org.junit.Test
import java.io.IOException
class UcvlUpgradeReliabilityTest {
private fun android(version: String) = """{"tag_name":"android-v$version","draft":false,"prerelease":false,"assets":[{"name":"UCVL-Zonghengjia-$version-android-universal.apk","size":66000000}]}"""
private fun fullPage() = "[" + (1..50).joinToString(",") {
"""{"tag_name":"windows-v0.3.$it","draft":false,"prerelease":false,"assets":[]}"""
} + "]"
@Test fun findsAndroidAfterFullPageOfWindowsReleases() = runBlocking {
val pages = mutableListOf<Int>()
val offer = UcvlReleaseChecker.lookup("1.0.6") { page ->
pages.add(page)
if (page == 1) fullPage() else "[${android("1.0.7")}]"
}
assertEquals(listOf(1, 2), pages)
assertEquals("1.0.7", offer?.version)
}
@Test fun checksAllPagesBeforeChoosingNumericallyNewest() = runBlocking {
val first = fullPage().dropLast(1) + ",${android("1.0.7")}]"
val offer = UcvlReleaseChecker.lookup("1.0.6") { page ->
if (page == 1) first else "[${android("1.0.10")}]"
}
assertEquals("1.0.10", offer?.version)
}
@Test fun ignoresMalformedUnrelatedAndOverflowingVersionRecords() {
val json = """[null,17,{}, {"tag_name":"windows-v9","draft":"broken"},
{"tag_name":"android-v99999999999999.0.0","draft":false,"prerelease":false}, ${android("1.0.7")}]"""
assertEquals("1.0.7", UcvlReleaseChecker.select(json, "1.0.6")?.version)
}
@Test fun duplicateUniversalApksFailClosed() {
val release = android("1.0.7").replace("\"size\":66000000}]", "\"size\":66000000},{\"name\":\"UCVL-Zonghengjia-1.0.7-android-universal.apk\",\"size\":66000000}]")
assertThrows(IOException::class.java) { UcvlReleaseChecker.select("[$release]", "1.0.6") }
}
@Test fun refusesUnboundedPagination() = runBlocking {
var calls = 0
try {
UcvlReleaseChecker.lookup("1.0.6") { calls++; fullPage() }
fail("Unbounded release list must fail with a retryable error")
} catch (_: IOException) {
assertEquals(10, calls)
}
}
@Test fun rejectsOversizedDecodedPageBeforeParsing() = runBlocking {
try {
UcvlReleaseChecker.lookup("1.0.6") { " ".repeat(1024 * 1024 + 1) }
fail("Decoded page must remain bounded")
} catch (_: IOException) { }
}
@Test fun emptyPageEndsLookupWithoutDowngrade() = runBlocking {
var calls = 0
assertNull(UcvlReleaseChecker.lookup("1.0.7") { calls++; "[]" })
assertEquals(1, calls)
}
@Test fun speedUsesKilobytesMinimumWithoutOverstatingTinyTransfers() {
assertEquals("0.0 KB/s", UcvlTrafficFormat.speed(0))
assertEquals("0.0 KB/s", UcvlTrafficFormat.speed(-10))
assertEquals("<0.1 KB/s", UcvlTrafficFormat.speed(1))
assertEquals("0.1 KB/s", UcvlTrafficFormat.speed(103))
assertEquals("1.0 KB/s", UcvlTrafficFormat.speed(1024))
assertEquals("1.5 MB/s", UcvlTrafficFormat.speed(1572864))
}
}
@@ -0,0 +1,131 @@
package com.v2ray.ang.ucvl
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import org.junit.Assert.*
import org.junit.Test
class UcvlVpnStartupLeaseTest {
@Test fun initialSessionCannotReportRunning() {
val lease = UcvlVpnStartupLease()
assertFalse(lease.isValid(0))
assertFalse(lease.reportIfValid(0) { fail("No startup owns the service") })
}
@Test fun beginCreatesValidSession() {
val lease = UcvlVpnStartupLease()
assertTrue(lease.isValid(lease.begin()))
}
@Test fun replacementInvalidatesOlderStartup() {
val lease = UcvlVpnStartupLease()
val old = lease.begin()
val replacement = lease.begin()
assertNotEquals(old, replacement)
assertFalse(lease.isValid(old))
assertTrue(lease.isValid(replacement))
}
@Test fun revokeBeforeEstablishPreventsStartup() = revokeAt(Phase.BEFORE_ESTABLISH)
@Test fun revokeDuringEstablishClosesInterfaceAndSkipsNative() = revokeAt(Phase.ESTABLISHED)
@Test fun revokeDuringNativeStartStopsNativeWithoutSuccess() = revokeAt(Phase.NATIVE_STARTED)
@Test fun revokeBeforeSuccessBroadcastPreventsGreenState() = revokeAt(Phase.BEFORE_REPORT)
@Test fun lateSuccessAfterStopCannotReportRunning() {
val lease = UcvlVpnStartupLease()
val epoch = lease.begin()
lease.invalidate()
assertFalse(lease.reportIfValid(epoch) { fail("Stopped startup cannot revive") })
}
@Test fun oldStartupCannotReportSuccessForReplacementSession() {
val lease = UcvlVpnStartupLease()
val old = lease.begin()
val replacement = lease.begin()
assertFalse(lease.reportIfValid(old) { fail("Stale startup") })
assertTrue(lease.reportIfValid(replacement) {})
}
@Test fun registrationAfterRevokeCannotReportRunning() {
val lease = UcvlVpnStartupLease()
val epoch = lease.begin()
lease.invalidate()
assertFalse(lease.reportIfValid(epoch) { fail("Native-running alone is insufficient") })
}
@Test fun repeatedInvalidationCannotResurrectSession() {
val lease = UcvlVpnStartupLease()
val epoch = lease.begin()
repeat(3) { lease.invalidate() }
assertFalse(lease.isValid(epoch))
val next = lease.begin()
assertNotEquals(epoch, next)
assertTrue(lease.isValid(next))
}
@Test fun binderCanInvalidateWhileNativeStartBlocksMain() {
val lease = UcvlVpnStartupLease()
val epoch = lease.begin()
val starting = CountDownLatch(1)
val allowReturn = CountDownLatch(1)
val finished = CountDownLatch(1)
val success = AtomicBoolean(false)
val main = Thread {
starting.countDown()
try {
check(allowReturn.await(2, TimeUnit.SECONDS))
success.set(lease.reportIfValid(epoch) {})
} finally { finished.countDown() }
}
main.start()
assertTrue(starting.await(2, TimeUnit.SECONDS))
// No lock spans simulated establish/native code: Binder never waits for main.
lease.invalidate()
assertFalse(lease.isValid(epoch))
allowReturn.countDown()
assertTrue(finished.await(2, TimeUnit.SECONDS))
assertFalse(success.get())
main.join(2_000)
}
@Test fun healthySessionReportsSuccessExactlyOnceWhenRequested() {
val lease = UcvlVpnStartupLease()
val epoch = lease.begin()
var reports = 0
assertTrue(lease.reportIfValid(epoch) { reports++ })
assertEquals(1, reports)
}
private enum class Phase { BEFORE_ESTABLISH, ESTABLISHED, NATIVE_STARTED, BEFORE_REPORT }
/** Fake Android/native boundaries exercise the same lease checks as the service. */
private fun revokeAt(phase: Phase) {
val lease = UcvlVpnStartupLease()
val epoch = lease.begin()
var interfaceOpen = false
var nativeRunning = false
var success = false
fun boundary(at: Phase): Boolean {
if (phase == at) lease.invalidate()
return lease.isValid(epoch)
}
try {
if (!boundary(Phase.BEFORE_ESTABLISH)) return
interfaceOpen = true
if (!boundary(Phase.ESTABLISHED)) return
nativeRunning = true
if (!boundary(Phase.NATIVE_STARTED)) return
if (!boundary(Phase.BEFORE_REPORT)) return
success = lease.reportIfValid(epoch) {}
} finally {
if (!lease.isValid(epoch)) {
interfaceOpen = false
nativeRunning = false
}
assertFalse("Revoked TUN must close", interfaceOpen)
assertFalse("Late native start must stop", nativeRunning)
assertFalse("Revoked startup cannot show connected", success)
}
}
}