enforce dedicated Wi-Fi for direct QR pairing

This commit is contained in:
zhy200308
2026-08-12 11:46:59 +08:00
parent eccd93266e
commit 65223dafe4
10 changed files with 345 additions and 306 deletions
+2 -2
View File
@@ -12,8 +12,8 @@ android {
applicationId = "com.qft.optical"
minSdk = 24
targetSdk = 35
versionCode = 19
versionName = "0.4.7"
versionCode = 20
versionName = "0.4.8"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
@@ -4,6 +4,32 @@ import java.net.URI
/** Pure IPv4 routing helpers kept Android-free so candidate selection is testable. */
object EndpointRouting {
/**
* A dedicated QFT Wi-Fi must never reuse QR/LAN adapter addresses. Its only
* direct candidates are gateways supplied by Android for that exact Network.
* Current-LAN fallback mode may additionally use advertised same-subnet IPs.
*/
fun afterConnection(
dedicatedWifi: Boolean,
gatewayEndpoints: List<String>,
routedAdvertisedEndpoints: List<String>,
): List<String> = if (dedicatedWifi) {
gatewayEndpoints.distinct()
} else {
(gatewayEndpoints + routedAdvertisedEndpoints).distinct()
}
/** Same isolation rule for retry/recovery after the first gateway probe. */
fun forRecovery(
dedicatedWifi: Boolean,
discoveredEndpoint: String?,
gatewayEndpoints: List<String>,
advertisedEndpoints: List<String>,
): List<String> {
val candidates = listOfNotNull(discoveredEndpoint) + gatewayEndpoints
return (candidates + if (dedicatedWifi) emptyList() else advertisedEndpoints).distinct()
}
fun onAnySubnet(
endpoints: List<String>,
expectedPort: Int,
@@ -195,7 +195,7 @@ class MainActivity : ComponentActivity() {
) { showReceivedFiles() })
root.addView(space(22))
root.addView(text("本机设备:$receiverDeviceLabel", 13f, MUTED))
root.addView(text("QFT v0.4.7 · Android 7+ 到最新", 12f, MUTED))
root.addView(text("QFT v${BuildConfig.VERSION_NAME} · Android 7+ 到最新", 12f, MUTED))
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
}
@@ -605,49 +605,10 @@ class MainActivity : ComponentActivity() {
private fun connectPair(pair: PairingPayload) {
val attempt = ++pairConnectionAttempt
transferAbortReason = null
// 先在**当前网络**上试一把二维码给出的地址。
//
// 两台设备常常本来就在同一个局域网里,此时切到 Direct AP 是纯粹的
// 倒退:要等系统配网弹窗、要走 ICS 虚拟网卡、还得让那块网卡的防火墙
// 配置也放行,实测能耗掉一两分钟。只有当前网络确实够不着电脑时,
// 才值得付出切网的代价。
val currentCandidates = if (pair.wifi != null) {
wifiConnector.currentWifiCandidates(pair.endpoints, pair.port)
} else null
if (currentCandidates != null && currentCandidates.endpoints.isNotEmpty()) {
showConnecting(pair, "正在当前网络上尝试直连…")
transferExecutor.execute {
val direct = UploadClient.probeEndpoints(
network = currentCandidates.network,
pairing = pair,
deviceName = receiverDeviceLabel,
endpoints = currentCandidates.endpoints,
connectMs = 320,
readMs = 450,
)
runOnUiThread {
if (attempt != pairConnectionAttempt) return@runOnUiThread
if (direct != null) {
// The probe was explicitly bound to this Wi-Fi handle;
// keep subsequent upload/download requests on the same
// route instead of assuming Android made it the default.
connectedNetwork = currentCandidates.network
connectedBaseUrl = direct
updateConnectingStatus("当前网络已直连到电脑,无需切换 Wi-Fi。")
if (pair.direction == TransferDirection.DOWNLOAD_TO_PHONE) {
startDownloadFromPc(pair, direct)
} else {
showSendReady(pair, direct)
}
} else {
// 当前网络够不着,才切 Direct AP
connectViaWifi(pair, attempt)
}
}
}
return
}
connectedBaseUrl = null
// 携带 Wi-Fi 身份的 QFT Direct 会无条件先连接那张专用网络。
// 不再尝试二维码/电脑当前 LAN 地址;“当前局域网”仍是桌面端用户
// 明确选择的独立备用模式(wifi == null)。
connectViaWifi(pair, attempt)
}
@@ -667,32 +628,49 @@ class MainActivity : ComponentActivity() {
if (connectedBaseUrl != null) return@available
transferExecutor.execute {
if (attempt != pairConnectionAttempt) return@execute
val gateways = wifiConnector.gatewayEndpoints(network, pair.port)
val routedEndpoints = wifiConnector.endpointsOnNetwork(
network,
pair.endpoints,
pair.port,
val dedicatedWifi = pair.wifi != null
val gateways = if (dedicatedWifi) {
runOnUiThread { updateConnectingStatus("专用 Wi-Fi 已连接 · 正在读取实际网关…") }
wifiConnector.awaitGatewayEndpoints(network, pair.port, timeoutMs = 3_500L)
} else {
wifiConnector.gatewayEndpoints(network, pair.port)
}
val routedEndpoints = if (dedicatedWifi) emptyList() else {
wifiConnector.endpointsOnNetwork(network, pair.endpoints, pair.port)
}
val directCandidates = EndpointRouting.afterConnection(
dedicatedWifi = dedicatedWifi,
gatewayEndpoints = gateways,
routedAdvertisedEndpoints = routedEndpoints,
)
// 先直接打网关。Direct AP 场景下网关**必然**就是那台电脑
// (手机的 IP 是电脑的 DHCP 发的),根本不需要先做发现。
// 此前把阻塞式 UDP 发现排在最前,白白等掉一两秒才开始
// 真正能成功的那一步。
runOnUiThread { updateConnectingStatus("网络已就绪 · 正在直连网关…") }
// Direct AP 的网关由这次专用连接的 LinkProperties 给出,
// 不使用二维码地址,也不猜测 192.168.137/49 网段。
runOnUiThread {
updateConnectingStatus(
if (dedicatedWifi) "已取得专用网络网关 · 正在认证电脑…"
else "网络已就绪 · 正在连接同网段电脑…"
)
}
val direct = UploadClient.probeEndpoints(
network = network,
pairing = pair,
deviceName = receiverDeviceLabel,
endpoints = (gateways + routedEndpoints).distinct(),
connectMs = 400,
readMs = 600,
endpoints = directCandidates,
connectMs = if (dedicatedWifi) 650 else 400,
readMs = if (dedicatedWifi) 850 else 600,
)
// 直连不通才退回发现流程:UDP 广播 → 子网扫描
var discovered: String? = null
var subnet: List<String> = emptyList()
if (direct == null) {
runOnUiThread { updateConnectingStatus("网关未应答 · 正在 UDP 快速发现电脑…") }
runOnUiThread {
updateConnectingStatus(
if (dedicatedWifi) "专用网关正在初始化 · 仅在 QFT 子网内自动发现…"
else "同网段地址未应答 · 正在 UDP 快速发现电脑…"
)
}
discovered = UploadClient.discoverUdp(
network = network,
pairing = pair,
@@ -702,7 +680,7 @@ class MainActivity : ComponentActivity() {
runOnUiThread {
updateConnectingStatus(
if (discovered != null) "已通过 UDP 找到电脑 · 正在验证接收服务…"
else "正在并行探测网关;必要时自动扫描当前 QFT 子网…"
else "仅在当前连接的 QFT 子网内并行查找电脑…"
)
}
}
@@ -717,20 +695,29 @@ class MainActivity : ComponentActivity() {
)
runOnUiThread {
if (attempt != pairConnectionAttempt) return@runOnUiThread
// 如果 Wi-Fi 波动后系统已交付了新的 Network,旧探测结果
// 不得覆盖新连接或短暂显示失败页。
if (connectedNetwork != network) return@runOnUiThread
if (base == null) {
// 把手机实际所处的网络写进报错。否则"找不到"这三个字
// 无法区分:手机在别的网段?没拿到网关?还是对端真的没开。
val diagnosis = buildString {
append("Wi-Fi 已连接,但快速发现、网关探测和当前子网扫描都未找到 QFT 接收服务。\n\n")
append(
if (dedicatedWifi) {
"QFT 专用 Wi-Fi 已连接,但在该专用网络的实际网关和子网内未找到服务。\n\n"
} else {
"Wi-Fi 已连接,但在当前局域网内未找到 QFT 服务。\n\n"
}
)
append("手机侧:").append(wifiConnector.describeNetwork(network)).append("\n")
append("二维码给出的地址:")
append(pair.endpoints.joinToString("、").ifEmpty { "(无,仅靠发现)" })
append("连接模式:")
append(if (dedicatedWifi) "QFT 专用 Wi-Fi(不使用二维码/电脑本地网卡地址)" else "当前局域网备用模式")
append("\n探测过的网关地址:")
append(gateways.joinToString("、").ifEmpty { "(无)" })
append("\n子网扫描范围:").append(subnet.size).append(" 个地址\n\n")
append("请对照检查:① 手机与电脑是否在同一网段;")
append("② Windows 上是否在「Android → 电脑」页并已点「启动接收」;")
append("③ Windows 防火墙是否放行了 qft-desktop.exe(Profile 必须含当前网络类型)。")
append("请对照检查:① Windows 上 QFT Direct 是否仍显示已就绪;")
append("② 防火墙是否放行 qft-desktop.exe 的当前专用网络类型;")
append("③ 手机是否仍连接二维码内的 QFT 专用网络。")
}
showPairError(pair, diagnosis)
} else {
@@ -144,18 +144,26 @@ object UploadClient {
discoveredEndpoint: String? = null,
subnetEndpoints: List<String> = emptyList(),
): String? {
val common = listOf(
"http://192.168.137.1:${pairing.port}",
"http://192.168.49.1:${pairing.port}",
val dedicatedWifi = pairing.wifi != null
// Direct mode must use only facts obtained from the dedicated Network:
// its actual gateway and an authenticated UDP reply. Never inject LAN,
// VPN or guessed Windows ICS addresses into this candidate list.
val fast = EndpointRouting.forRecovery(
dedicatedWifi = dedicatedWifi,
discoveredEndpoint = discoveredEndpoint,
gatewayEndpoints = preferredEndpoints,
advertisedEndpoints = pairing.endpoints,
)
val fast = (listOfNotNull(discoveredEndpoint) + preferredEndpoints + pairing.endpoints + common)
.map { it.trim().removeSuffix("/") }
.filter { PairingProtocol.isAllowedLocalHttpEndpoint(it, pairing.port) }
.distinct()
// Stage 1: QR-carried endpoints and actual gateway. This is the normal
// path and must complete well inside the 10-second pairing budget.
val fastDeadline = android.os.SystemClock.elapsedRealtime() + 1_050
// Give a newly associated Direct network enough time for ARP, the group
// owner route and Windows' new-network firewall profile to settle. A
// successful candidate still returns immediately, so this extends only
// the failure/recovery path.
val fastWindowMs = if (dedicatedWifi) 4_000L else 1_050L
val fastDeadline = android.os.SystemClock.elapsedRealtime() + fastWindowMs
while (fast.isNotEmpty() && android.os.SystemClock.elapsedRealtime() < fastDeadline) {
probeCandidatesParallel(network, pairing, deviceName, fast, workers = 12, connectMs = 220, readMs = 260)
?.let { return it }
@@ -175,9 +183,9 @@ object UploadClient {
?.let { return it }
}
// One short final pass covers a just-finished ARP/Windows firewall
// transition without adding the former two-second tail latency.
val deadline = android.os.SystemClock.elapsedRealtime() + 500
// One final pass covers a route/firewall transition that completed while
// the actual connected subnet fallback was running.
val deadline = android.os.SystemClock.elapsedRealtime() + if (dedicatedWifi) 1_200L else 500L
while (fast.isNotEmpty() && android.os.SystemClock.elapsedRealtime() < deadline) {
probeCandidatesParallel(network, pairing, deviceName, fast, workers = 12, connectMs = 240, readMs = 260)
?.let { return it }
@@ -190,8 +198,8 @@ object UploadClient {
* 在指定网络(`network` 为 null 表示系统默认网络)上并发探测一组地址,
* 返回第一个应答的。
*
* 供「切换 Wi-Fi 之前先试当前网络」这一步使用:两台设备本来就在同一个
* 局域网时,这一下就成功了,不必再走配网弹窗与虚拟网卡。
* Direct 模式只传入专用网络的实际网关;当前局域网备用模式传入经过
* 同网段过滤的二维码地址。调用方必须显式绑定对应的 Network。
*/
fun probeEndpoints(
network: Network?,
@@ -35,8 +35,6 @@ class WifiConnector(context: Context) {
private var legacyPreviousNetworkId: Int? = null
private var legacyTargetNetworkId: Int? = null
data class EndpointCandidates(val network: Network, val endpoints: List<String>)
/**
* 回调经由这个可替换的收件人转发,而不是被 NetworkCallback 闭包捕获。
* 这样「用户点重试」时可以直接换掉 UI 回调、继续复用那个还挂着的
@@ -318,16 +316,6 @@ class WifiConnector(context: Context) {
private fun hasIpv4(props: LinkProperties?): Boolean = props?.linkAddresses?.any { it.address is Inet4Address } == true
/**
* Only probe QR endpoints that can actually be routed over the phone's
* current Wi-Fi. This avoids spending a full TCP timeout on Direct-AP and
* stale LAN addresses before Android has even started switching networks.
*/
fun currentWifiCandidates(endpoints: List<String>, port: Int): EndpointCandidates? {
val network = bestWifiNetwork() ?: return null
return EndpointCandidates(network, endpointsOnNetwork(network, endpoints, port))
}
fun endpointsOnNetwork(network: Network?, endpoints: List<String>, port: Int): List<String> {
if (network == null) return emptyList()
val links = connectivity.getLinkProperties(network)?.linkAddresses
@@ -435,6 +423,26 @@ class WifiConnector(context: Context) {
.toList()
}
/**
* WifiNetworkSpecifier may report IPv4 a few callbacks before DHCP routes
* include the group-owner gateway. Wait on the transfer worker for the route
* belonging to this exact Network instead of guessing Windows ICS ranges.
*/
fun awaitGatewayEndpoints(network: Network?, port: Int, timeoutMs: Long): List<String> {
val deadline = SystemClock.elapsedRealtime() + timeoutMs.coerceAtLeast(0L)
do {
gatewayEndpoints(network, port).takeIf { it.isNotEmpty() }?.let { return it }
if (SystemClock.elapsedRealtime() >= deadline || Thread.currentThread().isInterrupted) break
try {
Thread.sleep(100)
} catch (_: InterruptedException) {
Thread.currentThread().interrupt()
break
}
} while (true)
return gatewayEndpoints(network, port)
}
fun discoveryHosts(network: Network?): List<InetAddress> {
val out = mutableListOf<InetAddress>()
if (network != null) {
@@ -10,6 +10,49 @@ import java.util.concurrent.Executors
import java.util.zip.CRC32
class ProtocolTest {
@Test
fun dedicatedWifiNeverProbesQrOrComputerLanAddresses() {
assertEquals(
listOf("http://192.168.137.1:39393"),
EndpointRouting.afterConnection(
dedicatedWifi = true,
gatewayEndpoints = listOf("http://192.168.137.1:39393"),
routedAdvertisedEndpoints = listOf(
"http://192.168.8.162:39393",
"http://192.168.49.1:39393",
),
),
)
}
@Test
fun dedicatedWifiRecoveryStillRejectsAdvertisedAndGuessedAddresses() {
assertEquals(
listOf("http://192.168.137.1:39393"),
EndpointRouting.forRecovery(
dedicatedWifi = true,
discoveredEndpoint = null,
gatewayEndpoints = listOf("http://192.168.137.1:39393"),
advertisedEndpoints = listOf(
"http://192.168.8.162:39393",
"http://192.168.49.1:39393",
),
),
)
}
@Test
fun currentLanModeCanUseSameSubnetAdvertisedAddresses() {
assertEquals(
listOf("http://192.168.8.1:39393", "http://192.168.8.162:39393"),
EndpointRouting.afterConnection(
dedicatedWifi = false,
gatewayEndpoints = listOf("http://192.168.8.1:39393"),
routedAdvertisedEndpoints = listOf("http://192.168.8.162:39393"),
),
)
}
@Test
fun probeCompletionWaitsForARealResultInsteadOfConsumingAnEmptyPoll() {
val pool = Executors.newSingleThreadExecutor()
@@ -91,6 +134,18 @@ class ProtocolTest {
assertEquals(42L, payload.fileSize)
}
@Test
fun parsesDedicatedWifiPairingWithoutAdvertisedComputerAddresses() {
val json = """{"v":2,"s":"abcdefghijklmnopqrstuvwxyz012345","n":"DESKTOP-QFT","p":39393,"e":[],"w":["QFT-DESKTOP-abc123","0123456789abcdef"]}"""
val payload = PairingProtocol.parse(
PairingProtocol.PREFIX_V2 + Base64Url.encode(json.toByteArray()),
)!!
assertNotNull(payload.wifi)
assertEquals("QFT-DESKTOP-abc123", payload.wifi?.ssid)
assertTrue(payload.endpoints.isEmpty())
}
@Test
fun base45KnownVectors() {
assertArrayEquals("AB".toByteArray(), Base45.decode("BB8"))