复用连接

This commit is contained in:
2026-10-28 13:51:20 +08:00
parent 0851713876
commit 5739f7f8e7
15 changed files with 581 additions and 376 deletions
+2 -2
View File
@@ -18,8 +18,8 @@ android {
applicationId = "net.bluemangoo.indpjsk"
minSdk = appMinSdk
targetSdk = 37
versionCode = 3
versionName = "1.2"
versionCode = 4
versionName = "1.3"
}
@@ -25,10 +25,11 @@ import net.bluemangoo.indpjsk.ui.CaptureScreen
import net.bluemangoo.indpjsk.ui.CaptureViewModel
import net.bluemangoo.indpjsk.ui.CapturedFilesScreen
import net.bluemangoo.indpjsk.ui.ProxySettingsScreen
import net.bluemangoo.indpjsk.ui.UploadSettingsScreen
import net.bluemangoo.indpjsk.ui.theme.IndPjskTheme
import java.io.File
enum class AppScreen { MAIN, PROXY, APP_SELECTION, FILES, ABOUT }
enum class AppScreen { MAIN, PROXY, UPLOAD, APP_SELECTION, FILES, ABOUT }
class MainActivity : ComponentActivity() {
@@ -73,10 +74,15 @@ class MainActivity : ComponentActivity() {
onStartCapture = { requestVpnAndStart() },
onStopCapture = { viewModel.stopCapture(this) },
onOpenProxySettings = { screen = AppScreen.PROXY },
onOpenUploadSettings = { screen = AppScreen.UPLOAD },
onOpenFiles = { screen = AppScreen.FILES },
onOpenAbout = { screen = AppScreen.ABOUT },
)
AppScreen.UPLOAD -> UploadSettingsScreen(
onBack = { screen = AppScreen.MAIN },
)
AppScreen.PROXY -> ProxySettingsScreen(
bypassPackages = bypassPackages,
onBypassChange = { newSet ->
@@ -3,7 +3,7 @@ package net.bluemangoo.indpjsk.data
import net.bluemangoo.indpjsk.upload.Uploader
object PredefinedProfiles {
private const val SUITE_PATH = "/api/suite/user/(\\d+)(\\?isLogin=true)?\$"
private const val SUITE_PATH = "/api/suite/user/(\\d+)(\\?isLogin=true)?$"
private const val MYSEKAI_PATH =
"/api/user/(\\d+)/mysekai\\?isForceAllReloadOnlyMysekai=True"
@@ -40,7 +40,10 @@ object PredefinedProfiles {
}
)
private val CN_HOSTS = listOf("mkcn-prod-public-60001-1.dailygn.com")
private val CN_HOSTS = listOf(
"mkcn-prod-public-60001-1.dailygn.com",
"mkcn-prod-public-60001-2.dailygn.com"
)
private val JP_HOSTS = listOf("production-game-api.sekai.colorfulpalette.org")
private val EN_HOSTS = listOf("n-production-game-api.sekai-en.com")
private val TW_HOSTS = listOf(
@@ -3,19 +3,19 @@ package net.bluemangoo.indpjsk.data
import android.content.Context
import androidx.core.content.edit
/** 全局配置持久化:上传码、上游代理、忽略的应用、选中的配置 */
object SettingsStore {
private const val PREFS = "settings"
private const val KEY_UPLOAD_CODE = "upload_code"
private const val KEY_USE_UPLOAD = "use_upload"
private const val KEY_PROXY = "upstream_proxy"
private const val KEY_USE_PROXY = "use_proxy"
private const val KEY_BYPASS = "bypass_packages"
private const val KEY_PROFILE = "selected_profile"
private fun prefs(context: Context) =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
// ---- 上传码 ----
fun loadUploadCode(context: Context): String =
prefs(context).getString(KEY_UPLOAD_CODE, "").orEmpty()
@@ -23,7 +23,15 @@ object SettingsStore {
prefs(context).edit { putString(KEY_UPLOAD_CODE, code) }
}
// ---- 上游代理(空 = 直连) ----
fun loadUseUpload(context: Context): Boolean {
return loadUploadCode(context).isNotBlank() && prefs(context).getBoolean(KEY_USE_UPLOAD, true)
}
fun saveUseUpload(context: Context, enabled: Boolean) {
prefs(context).edit { putBoolean(KEY_USE_UPLOAD, enabled) }
}
fun loadProxy(context: Context): String =
prefs(context).getString(KEY_PROXY, "").orEmpty()
@@ -31,7 +39,15 @@ object SettingsStore {
prefs(context).edit { putString(KEY_PROXY, proxy.trim()) }
}
// ---- 不走 VPN 的应用(包名) ----
fun loadUseProxy(context: Context): Boolean {
return loadProxy(context).isNotBlank() && prefs(context).getBoolean(KEY_USE_PROXY, true)
}
fun saveUseProxy(context: Context, enabled: Boolean) {
prefs(context).edit { putBoolean(KEY_USE_PROXY, enabled) }
}
fun loadBypassPackages(context: Context): Set<String> =
prefs(context).getStringSet(KEY_BYPASS, emptySet())?.toSet() ?: emptySet()
@@ -39,7 +55,7 @@ object SettingsStore {
prefs(context).edit { putStringSet(KEY_BYPASS, packages) }
}
// ---- 当前选中的配置 ----
fun loadSelectedProfileId(context: Context): String? =
prefs(context).getString(KEY_PROFILE, null)
@@ -15,14 +15,12 @@ import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import net.bluemangoo.indpjsk.R
import net.bluemangoo.indpjsk.data.CaptureProfile
import net.bluemangoo.indpjsk.data.CaptureProfileStep
import net.bluemangoo.indpjsk.data.SettingsStore
import net.bluemangoo.indpjsk.data.StepSelectionStore
import net.bluemangoo.indpjsk.state.CaptureStatus
import net.bluemangoo.indpjsk.vpn.LogEntry
@@ -36,6 +34,7 @@ fun CaptureScreen(
onStartCapture: () -> Unit,
onStopCapture: () -> Unit,
onOpenProxySettings: () -> Unit,
onOpenUploadSettings: () -> Unit,
onOpenFiles: () -> Unit,
onOpenAbout: () -> Unit,
) {
@@ -46,7 +45,6 @@ fun CaptureScreen(
var enabledMap by remember { mutableStateOf(StepSelectionStore.loadAll(context) as Map<String, Boolean>) }
var menuExpanded by remember { mutableStateOf(false) }
var profileExpanded by remember { mutableStateOf(false) }
var showUploadCodeDialog by remember { mutableStateOf(false) }
val isRunning = state.status == CaptureStatus.RUNNING
val isCaptured = state.status == CaptureStatus.CAPTURED
@@ -69,10 +67,10 @@ fun CaptureScreen(
onDismissRequest = { menuExpanded = false }
) {
DropdownMenuItem(
text = { Text("上传码") },
text = { Text("上传设置") },
onClick = {
menuExpanded = false
showUploadCodeDialog = true
onOpenUploadSettings()
}
)
DropdownMenuItem(
@@ -215,48 +213,6 @@ fun CaptureScreen(
}
}
}
if (showUploadCodeDialog) {
UploadCodeDialog(onDismiss = { showUploadCodeDialog = false })
}
}
@Composable
private fun UploadCodeDialog(onDismiss: () -> Unit) {
val context = LocalContext.current
var text by remember { mutableStateOf(SettingsStore.loadUploadCode(context)) }
AlertDialog(
onDismissRequest = onDismiss,
title = { Text("上传码") },
text = {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
OutlinedTextField(
value = text,
onValueChange = { text = it.trim() },
modifier = Modifier.fillMaxWidth(),
singleLine = true,
label = { Text("Haruki 上传码") },
visualTransformation = PasswordVisualTransformation(),
textStyle = MaterialTheme.typography.bodyMedium
)
Text(
text = "从 Haruki 工具箱 - 数据上传 - iOS 获取。",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
},
confirmButton = {
TextButton(onClick = {
SettingsStore.saveUploadCode(context, text)
onDismiss()
}) { Text("保存") }
},
dismissButton = {
TextButton(onClick = onDismiss) { Text("取消") }
}
)
}
@Composable
@@ -29,6 +29,7 @@ fun ProxySettingsScreen(
) {
val context = LocalContext.current
var proxy by remember { mutableStateOf(SettingsStore.loadProxy(context)) }
var useProxy by remember { mutableStateOf(SettingsStore.loadUseProxy(context)) }
var pendingRemove by remember { mutableStateOf<AppEntry?>(null) }
val entries = remember(bypassPackages) {
@@ -37,6 +38,7 @@ fun ProxySettingsScreen(
val looksValid = proxy.isBlank() ||
((proxy.startsWith("http://") || proxy.startsWith("https://")) && proxy.contains(":"))
val canUseProxy = proxy.isNotBlank() && looksValid
Scaffold(
topBar = {
@@ -66,11 +68,35 @@ fun ProxySettingsScreen(
) {
Text("上游代理", style = MaterialTheme.typography.labelLarge)
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
Checkbox(
checked = useProxy && canUseProxy,
onCheckedChange = {
useProxy = it
SettingsStore.saveUseProxy(context, it)
},
enabled = canUseProxy
)
Text(
text = "使用上游代理",
style = MaterialTheme.typography.bodyMedium
)
}
OutlinedTextField(
value = proxy,
onValueChange = {
proxy = it
SettingsStore.saveProxy(context, it)
// 地址被清空时不允许再勾着;顺手把偏好也清掉,避免重新填写时自动勾上
if (it.isBlank() && useProxy) {
useProxy = false
SettingsStore.saveUseProxy(context, false)
}
},
modifier = Modifier.fillMaxWidth(),
singleLine = true,
@@ -79,10 +105,10 @@ fun ProxySettingsScreen(
isError = !looksValid,
supportingText = {
Text(
text = if (looksValid) {
"留空以忽略;只支持 http / https 代理"
} else {
"格式示例:http://127.0.0.1:7890"
text = when {
proxy.isBlank() -> "填写地址后才能勾选启用;只支持 http / https 代理"
!looksValid -> "格式示例:http://127.0.0.1:7890"
else -> "只支持 http / https 代理"
}
)
}
@@ -0,0 +1,95 @@
package net.bluemangoo.indpjsk.ui
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.dp
import net.bluemangoo.indpjsk.R
import net.bluemangoo.indpjsk.data.SettingsStore
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun UploadSettingsScreen(onBack: () -> Unit) {
val context = LocalContext.current
var code by remember { mutableStateOf(SettingsStore.loadUploadCode(context)) }
var useUpload by remember { mutableStateOf(SettingsStore.loadUseUpload(context)) }
var showCode by remember { mutableStateOf(false) }
val canUpload = code.isNotBlank()
Scaffold(
topBar = {
TopAppBar(
title = { Text("上传设置") },
navigationIcon = {
IconButton(onClick = onBack) {
Icon(
painter = painterResource(R.drawable.arrow_back_24px),
contentDescription = "返回"
)
}
}
)
}
) { padding ->
Column(
modifier = Modifier
.padding(padding)
.verticalScroll(rememberScrollState())
.padding(horizontal = 16.dp, vertical = 12.dp),
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
OutlinedTextField(
value = code,
onValueChange = {
code = it.trim()
SettingsStore.saveUploadCode(context, code)
if (code.isBlank() && useUpload) {
useUpload = false
SettingsStore.saveUseUpload(context, false)
}
},
modifier = Modifier.fillMaxWidth(),
singleLine = true,
label = { Text("Haruki 上传码") },
placeholder = { Text("从 Haruki 工具箱 - 数据上传 - iOS 获取") },
visualTransformation = if (showCode) {
VisualTransformation.None
} else {
PasswordVisualTransformation()
},
trailingIcon = {
TextButton(onClick = { showCode = !showCode }) {
Text(if (showCode) "隐藏" else "显示")
}
}
)
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
Checkbox(
checked = useUpload && canUpload,
onCheckedChange = {
useUpload = it
SettingsStore.saveUseUpload(context, it)
},
enabled = canUpload
)
Text(
text = "上传到 Haruki",
style = MaterialTheme.typography.bodyMedium
)
}
}
}
}
@@ -59,12 +59,17 @@ object Uploader {
}
suspend fun tryUpload(result: CaptureResult) {
val uploadCode = SettingsStore.loadUploadCode(App.appContext).trim()
if (uploadCode.isNotEmpty()) {
VpnLog.info("${result.profile.name}${result.step.name} 开始上传")
upload(uploadCode, result.url, result.file)
VpnLog.success("${result.profile.name}${result.step.name} 上传完成")
val context = App.appContext
// 复选框没勾就不传(没填上传码时复选框本身不可用)
if (!SettingsStore.loadUseUpload(context)) return
val uploadCode = SettingsStore.loadUploadCode(context).trim()
if (uploadCode.isEmpty()) {
VpnLog.warn("未填写上传码,跳过上传")
return
}
VpnLog.info("${result.profile.name}${result.step.name} 开始上传")
upload(uploadCode, result.url, result.file)
VpnLog.success("${result.profile.name}${result.step.name} 上传完成")
}
private fun postChunk(
@@ -7,7 +7,11 @@ import android.os.ParcelFileDescriptor
import kotlinx.coroutines.*
import net.bluemangoo.indpjsk.data.*
import net.bluemangoo.indpjsk.state.CaptureStateHolder
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.CountDownLatch
@SuppressLint("VpnServicePolicy")
class CaptureVpnService : VpnService() {
@@ -23,9 +27,7 @@ class CaptureVpnService : VpnService() {
private val postScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
fun captureFile(
filesDir: File,
profile: CaptureProfile,
step: CaptureProfileStep
filesDir: File, profile: CaptureProfile, step: CaptureProfileStep
): File = File(File(File(filesDir, "captures"), profile.id), step.fileName)
}
@@ -38,6 +40,16 @@ class CaptureVpnService : VpnService() {
@Volatile
private var stopRequested = false
private val stepResults = ConcurrentHashMap<String, String>()
private val finishedSteps = ConcurrentHashMap.newKeySet<String>()
@Volatile
private var allDone: CountDownLatch? = null
@Volatile
private var lastCaptured: File? = null
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
when (intent?.action) {
@@ -49,11 +61,13 @@ class CaptureVpnService : VpnService() {
ACTION_STOP -> {
stopRequested = true
VpnLog.warn("手动停止…")
VpnBridge.requestStop()
closeActivePfd()
VpnBridge.stopSession()
allDone?.countDown()
CaptureStateHolder.setIdle()
stopSelf()
if (captureThread?.isAlive != true) {
closeActivePfd()
stopSelf()
}
}
else -> return START_NOT_STICKY
@@ -66,7 +80,6 @@ class CaptureVpnService : VpnService() {
activePfd = null
try {
pfd?.close()
VpnBridge.requestStop()
} catch (t: Throwable) {
VpnLog.warn("关闭代理失败: ${t.message}")
}
@@ -88,22 +101,47 @@ class CaptureVpnService : VpnService() {
return
}
val proxy = SettingsStore.loadProxy(this).trim()
val proxy: String? = if (SettingsStore.loadUseProxy(this)) {
SettingsStore.loadProxy(this).trim().takeIf { it.isNotEmpty() }
} else {
null
}
val bypassPackages = SettingsStore.loadBypassPackages(this)
if (proxy.isNotEmpty()) VpnLog.info("上游代理: $proxy")
if (proxy != null) {
VpnLog.info("上游代理: $proxy")
} else {
VpnLog.info("未启用上游代理")
}
if (bypassPackages.isNotEmpty()) {
VpnLog.info("忽略的应用: ${bypassPackages.joinToString(", ")}")
}
stopRequested = false
stepResults.clear()
finishedSteps.clear()
lastCaptured = null
val latch = CountDownLatch(1)
allDone = latch
VpnLog.info("==== 开始抓包 ====")
VpnLog.info("配置: ${profile.name}")
VpnLog.info("步骤: ${enabledSteps.joinToString(" -> ") { it.name }}")
VpnLog.info("步骤(并行): ${enabledSteps.joinToString(" / ") { it.name }}")
VpnBridge.stepListener = { stepId, url ->
val step = enabledSteps.firstOrNull { it.id == stepId }
if (step == null) {
VpnLog.warn("收到未知步骤的结果: $stepId")
} else {
handleStepResult(profile, step, url)
finishedSteps.add(step.id)
if (finishedSteps.size >= enabledSteps.size) {
latch.countDown()
}
}
}
captureThread = Thread({
var pfd: ParcelFileDescriptor?
var lastFile: File? = null
var completed = 0
var errorMsg: String? = null
try {
@@ -111,159 +149,131 @@ class CaptureVpnService : VpnService() {
throw IllegalStateException("Rust 动态库 core_vpn 未加载")
}
val builder = Builder()
.setSession("Capture-${profile.id}")
.addAddress(VPN_ADDRESS, VPN_PREFIX)
.addDisallowedApplication(packageName)
.addRoute("1.0.0.0", 8)
val builder = Builder().setSession("Capture-${profile.id}").addAddress(VPN_ADDRESS, VPN_PREFIX)
.addDisallowedApplication(packageName).addRoute("1.0.0.0", 8)
.addRoute("2.0.0.0", 7)
.addRoute("4.0.0.0", 6)
.addRoute("8.0.0.0", 7)
.addRoute("2.0.0.0", 7).addRoute("4.0.0.0", 6).addRoute("8.0.0.0", 7)
.addRoute("11.0.0.0", 8)
.addRoute("12.0.0.0", 6)
.addRoute("16.0.0.0", 4)
.addRoute("32.0.0.0", 3)
.addRoute("64.0.0.0", 5)
.addRoute("96.0.0.0", 10)
.addRoute("11.0.0.0", 8).addRoute("12.0.0.0", 6).addRoute("16.0.0.0", 4).addRoute("32.0.0.0", 3)
.addRoute("64.0.0.0", 5).addRoute("96.0.0.0", 10)
.addRoute("100.128.0.0", 9)
.addRoute("101.0.0.0", 8)
.addRoute("102.0.0.0", 7)
.addRoute("104.0.0.0", 5)
.addRoute("112.0.0.0", 4)
.addRoute("100.128.0.0", 9).addRoute("101.0.0.0", 8).addRoute("102.0.0.0", 7)
.addRoute("104.0.0.0", 5).addRoute("112.0.0.0", 4)
.addRoute("128.0.0.0", 3)
.addRoute("160.0.0.0", 5)
.addRoute("168.0.0.0", 6)
.addRoute("169.0.0.0", 9)
.addRoute("169.128.0.0", 10)
.addRoute("169.192.0.0", 11)
.addRoute("169.224.0.0", 12)
.addRoute("169.240.0.0", 13)
.addRoute("169.248.0.0", 14)
.addRoute("169.252.0.0", 15)
.addRoute("128.0.0.0", 3).addRoute("160.0.0.0", 5).addRoute("168.0.0.0", 6).addRoute("169.0.0.0", 9)
.addRoute("169.128.0.0", 10).addRoute("169.192.0.0", 11).addRoute("169.224.0.0", 12)
.addRoute("169.240.0.0", 13).addRoute("169.248.0.0", 14).addRoute("169.252.0.0", 15)
.addRoute("169.255.0.0", 16)
.addRoute("170.0.0.0", 7)
.addRoute("172.0.0.0", 12)
.addRoute("169.255.0.0", 16).addRoute("170.0.0.0", 7).addRoute("172.0.0.0", 12)
.addRoute("172.32.0.0", 11)
.addRoute("172.64.0.0", 10)
.addRoute("172.128.0.0", 9)
.addRoute("173.0.0.0", 8)
.addRoute("174.0.0.0", 7)
.addRoute("176.0.0.0", 4)
.addRoute("192.0.0.0", 9)
.addRoute("192.128.0.0", 11)
.addRoute("192.160.0.0", 13)
.addRoute("192.169.0.0", 16)
.addRoute("192.170.0.0", 15)
.addRoute("192.172.0.0", 14)
.addRoute("192.176.0.0", 12)
.addRoute("172.32.0.0", 11).addRoute("172.64.0.0", 10).addRoute("172.128.0.0", 9)
.addRoute("173.0.0.0", 8).addRoute("174.0.0.0", 7).addRoute("176.0.0.0", 4).addRoute("192.0.0.0", 9)
.addRoute("192.128.0.0", 11).addRoute("192.160.0.0", 13).addRoute("192.169.0.0", 16)
.addRoute("192.170.0.0", 15).addRoute("192.172.0.0", 14).addRoute("192.176.0.0", 12)
.addRoute("192.192.0.0", 10)
.addRoute("193.0.0.0", 8)
.addRoute("194.0.0.0", 7)
.addRoute("196.0.0.0", 6)
.addRoute("200.0.0.0", 5)
.addRoute("208.0.0.0", 4)
.addRoute("::", 0)
.addDnsServer("8.8.8.8")
.addDnsServer("114.114.114.114")
.addRoute("193.0.0.0", 8).addRoute("194.0.0.0", 7).addRoute("196.0.0.0", 6).addRoute("200.0.0.0", 5)
.addRoute("208.0.0.0", 4).addRoute("::", 0).addDnsServer("8.8.8.8").addDnsServer("114.114.114.114")
for (pkg in bypassPackages) {
if (pkg == packageName) continue
runCatching { builder.addDisallowedApplication(pkg) }
.onFailure { VpnLog.warn("忽略应用 $pkg 失败: ${it.message}") }
runCatching { builder.addDisallowedApplication(pkg) }.onFailure { VpnLog.warn("忽略应用 $pkg 失败: ${it.message}") }
}
pfd = builder.establish()
?: throw IllegalStateException("VpnService.establish() 返回 null")
pfd = builder.establish() ?: throw IllegalStateException("VpnService.establish() 返回 null")
activePfd = pfd
val fd = pfd.fd
VpnLog.info("网络代理已连接")
for ((index, step) in enabledSteps.withIndex()) {
if (stopRequested) {
VpnLog.warn("用户停止,终止后续步骤")
break
val stepsJson = JSONArray().apply {
enabledSteps.forEach { step ->
put(JSONObject().apply {
put("id", step.id)
put("hosts", JSONArray(step.hosts))
put("path", step.path)
put("savePath", captureFile(filesDir, profile, step).absolutePath)
})
}
}.toString()
val label = "[${index + 1}/${enabledSteps.size}] ${step.name}"
val target = captureFile(filesDir, profile, step)
target.parentFile?.mkdirs()
if (target.exists()) target.delete()
if (!VpnBridge.boot(fd, stepsJson, proxy)) {
throw IllegalStateException("tun core 启动失败")
}
VpnLog.info("VPN 已建立")
val capturedUrl = VpnBridge.runCapture(
fd,
step.hosts.joinToString(","),
step.path,
target.absolutePath,
proxy
)
latch.await()
if (capturedUrl == null) {
if (stopRequested) {
VpnLog.warn("$label 被用户停止")
break
}
errorMsg = "$label 未抓到目标请求"
VpnLog.error(errorMsg)
break
}
VpnLog.info("$label 抓到目标请求: $capturedUrl")
if (!target.exists() || target.length() == 0L) {
errorMsg = "$label 返回了 URL 但文件为空"
VpnLog.error(errorMsg)
break
}
lastFile = target
completed++
VpnLog.success("$label 抓取成功")
val result = CaptureResult(profile, step, capturedUrl, target)
postScope.launch {
try {
step.postAction(result)
} catch (c: CancellationException) {
VpnLog.warn("$label 后处理被取消: ${c.message}")
throw c
} catch (t: Throwable) {
VpnLog.error("$label 后处理失败: ${t.message}")
}
}
if (stopRequested) {
VpnLog.warn("用户停止,已抓到 ${stepResults.size}/${enabledSteps.size} 步")
} else if (stepResults.size < enabledSteps.size) {
errorMsg = "只抓到 ${stepResults.size}/${enabledSteps.size} 步"
VpnLog.error(errorMsg)
}
} catch (t: Throwable) {
errorMsg = t.message ?: "抓包异常"
VpnLog.error("抓包异常: ${t.message}")
} finally {
VpnBridge.stepListener = null
VpnBridge.stopSession()
VpnBridge.shutdownSession()
closeActivePfd()
VpnLog.info("==== 抓包结束($completed/${enabledSteps.size} 步完成)====")
VpnLog.info("==== 抓包结束(${stepResults.size}/${enabledSteps.size} 步完成)====")
if (errorMsg != null) {
CaptureStateHolder.setError(errorMsg)
} else if (completed == enabledSteps.size && lastFile != null) {
CaptureStateHolder.setCaptured(lastFile)
} else if (stepResults.size == enabledSteps.size && lastCaptured != null) {
CaptureStateHolder.setCaptured(lastCaptured!!)
} else {
CaptureStateHolder.setIdle()
}
allDone = null
stopSelf()
}
}, "capture-blocking-worker").apply { start() }
}
private fun handleStepResult(
profile: CaptureProfile,
step: CaptureProfileStep,
url: String?,
) {
val target = captureFile(filesDir, profile, step)
if (url == null || !target.exists() || target.length() == 0L) {
VpnLog.error("${step.name} 抓取失败")
return
}
stepResults[step.id] = url
lastCaptured = target
VpnLog.success("${step.name} 抓到目标请求")
val result = CaptureResult(profile, step, url, target)
VpnLog.info("${step.name} 立即执行后处理(不等其他步骤)")
postScope.launch {
try {
step.postAction(result)
} catch (c: CancellationException) {
VpnLog.warn("${step.name} 后处理被取消: ${c.message}")
throw c
} catch (t: Throwable) {
VpnLog.error("${step.name} 后处理失败: ${t.message}")
}
}
}
override fun onRevoke() {
stopRequested = true
VpnLog.warn("VPN 权限被撤销")
closeActivePfd()
VpnBridge.stopSession()
allDone?.countDown()
super.onRevoke()
}
override fun onDestroy() {
closeActivePfd()
if (captureThread?.isAlive != true) {
VpnBridge.stopSession()
VpnBridge.shutdownSession()
closeActivePfd()
}
captureThread = null
super.onDestroy()
}
@@ -2,30 +2,14 @@ package net.bluemangoo.indpjsk.vpn
import android.util.Log
/**
* Rust core_vpn 的 JNI 桥。
*
* 契约(由 Rust lib.rs 实现):
* runCapture(jint tunFd, jstring targetHosts, jstring path, jstring savePath, jstring proxy) -> String?
* - 阻塞直到抓包结束
* - tunFd 的所有权【仍在 Kotlin 侧】,Rust 内部用 BorrowedAsyncDevice 借用,不得 close()
* - targetHosts 是逗号分隔的域名白名单(一个步骤可能对应多个上游域名)
* - proxy 可为 null / 空串(直连),否则必须是 http(s)://host:port 形式,Rust 侧会再校验一次
* - 返回非 null = 抓到目标请求,值是命中的原始完整 URL(https://host/path?query),文件已写入 savePath
* - 返回 null = 失败 / 被 requestStop 打断 / 未匹配
*
* requestStop() -> void
* - 立即返回,仅设置原子停止标志,使阻塞中的 runCapture 尽快返回 false
*
* nativeLog(String)(Kotlin -> Rust 回调的落地端)
* - Rust 通过 JNIEnv.call_static_method(".../VpnBridge", "nativeLog", ...) 调用
* - 用于把 TLS 握手 / 匹配结果等关键日志写进 UI 日志框
*/
object VpnBridge {
private const val TAG = "VpnBridge"
private var loaded = false
@Volatile
var stepListener: ((String, String?) -> Unit)? = null
init {
loaded = try {
System.loadLibrary("core_vpn")
@@ -39,19 +23,19 @@ object VpnBridge {
fun isAvailable(): Boolean = loaded
@JvmStatic
external fun runCapture(
tunFd: Int,
targetHosts: String,
targetPath: String,
savePath: String,
proxy: String?
): String?
external fun boot(tunFd: Int, stepsJson: String, proxy: String?): Boolean
@JvmStatic
external fun requestStop()
external fun stopSession()
@JvmStatic
external fun shutdownSession()
@JvmStatic
fun nativeStepResult(stepId: String, url: String?) {
stepListener?.invoke(stepId, url)
}
/** 供 Rust JNI 回调写入日志框;Rust 侧通过 call_static_method 调用本方法 */
@Suppress("unused")
@JvmStatic
fun nativeLog(level: String, msg: String) {
when (level) {
@@ -61,4 +45,4 @@ object VpnBridge {
else -> VpnLog.info(msg)
}
}
}
}