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" applicationId = "com.qft.optical"
minSdk = 24 minSdk = 24
targetSdk = 35 targetSdk = 35
versionCode = 19 versionCode = 20
versionName = "0.4.7" versionName = "0.4.8"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" 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. */ /** Pure IPv4 routing helpers kept Android-free so candidate selection is testable. */
object EndpointRouting { 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( fun onAnySubnet(
endpoints: List<String>, endpoints: List<String>,
expectedPort: Int, expectedPort: Int,
@@ -195,7 +195,7 @@ class MainActivity : ComponentActivity() {
) { showReceivedFiles() }) ) { showReceivedFiles() })
root.addView(space(22)) root.addView(space(22))
root.addView(text("本机设备:$receiverDeviceLabel", 13f, MUTED)) 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) }) setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
} }
@@ -605,49 +605,10 @@ class MainActivity : ComponentActivity() {
private fun connectPair(pair: PairingPayload) { private fun connectPair(pair: PairingPayload) {
val attempt = ++pairConnectionAttempt val attempt = ++pairConnectionAttempt
transferAbortReason = null transferAbortReason = null
connectedBaseUrl = null
// 先在**当前网络**上试一把二维码给出的地址。 // 携带 Wi-Fi 身份的 QFT Direct 会无条件先连接那张专用网络。
// // 不再尝试二维码/电脑当前 LAN 地址;“当前局域网”仍是桌面端用户
// 两台设备常常本来就在同一个局域网里,此时切到 Direct AP 是纯粹的 // 明确选择的独立备用模式(wifi == null)。
// 倒退:要等系统配网弹窗、要走 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
}
connectViaWifi(pair, attempt) connectViaWifi(pair, attempt)
} }
@@ -667,32 +628,49 @@ class MainActivity : ComponentActivity() {
if (connectedBaseUrl != null) return@available if (connectedBaseUrl != null) return@available
transferExecutor.execute { transferExecutor.execute {
if (attempt != pairConnectionAttempt) return@execute if (attempt != pairConnectionAttempt) return@execute
val gateways = wifiConnector.gatewayEndpoints(network, pair.port) val dedicatedWifi = pair.wifi != null
val routedEndpoints = wifiConnector.endpointsOnNetwork( val gateways = if (dedicatedWifi) {
network, runOnUiThread { updateConnectingStatus("专用 Wi-Fi 已连接 · 正在读取实际网关…") }
pair.endpoints, wifiConnector.awaitGatewayEndpoints(network, pair.port, timeoutMs = 3_500L)
pair.port, } 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 场景下网关**必然**就是那台电脑 // Direct AP 的网关由这次专用连接的 LinkProperties 给出,
// (手机的 IP 是电脑的 DHCP 发的),根本不需要先做发现。 // 不使用二维码地址,也不猜测 192.168.137/49 网段。
// 此前把阻塞式 UDP 发现排在最前,白白等掉一两秒才开始 runOnUiThread {
// 真正能成功的那一步。 updateConnectingStatus(
runOnUiThread { updateConnectingStatus("网络已就绪 · 正在直连网关…") } if (dedicatedWifi) "已取得专用网络网关 · 正在认证电脑…"
else "网络已就绪 · 正在连接同网段电脑…"
)
}
val direct = UploadClient.probeEndpoints( val direct = UploadClient.probeEndpoints(
network = network, network = network,
pairing = pair, pairing = pair,
deviceName = receiverDeviceLabel, deviceName = receiverDeviceLabel,
endpoints = (gateways + routedEndpoints).distinct(), endpoints = directCandidates,
connectMs = 400, connectMs = if (dedicatedWifi) 650 else 400,
readMs = 600, readMs = if (dedicatedWifi) 850 else 600,
) )
// 直连不通才退回发现流程:UDP 广播 → 子网扫描 // 直连不通才退回发现流程:UDP 广播 → 子网扫描
var discovered: String? = null var discovered: String? = null
var subnet: List<String> = emptyList() var subnet: List<String> = emptyList()
if (direct == null) { if (direct == null) {
runOnUiThread { updateConnectingStatus("网关未应答 · 正在 UDP 快速发现电脑…") } runOnUiThread {
updateConnectingStatus(
if (dedicatedWifi) "专用网关正在初始化 · 仅在 QFT 子网内自动发现…"
else "同网段地址未应答 · 正在 UDP 快速发现电脑…"
)
}
discovered = UploadClient.discoverUdp( discovered = UploadClient.discoverUdp(
network = network, network = network,
pairing = pair, pairing = pair,
@@ -702,7 +680,7 @@ class MainActivity : ComponentActivity() {
runOnUiThread { runOnUiThread {
updateConnectingStatus( updateConnectingStatus(
if (discovered != null) "已通过 UDP 找到电脑 · 正在验证接收服务…" if (discovered != null) "已通过 UDP 找到电脑 · 正在验证接收服务…"
else "正在并行探测网关;必要时自动扫描当前 QFT 子网…" else "仅在当前连接的 QFT 子网内并行查找电脑…"
) )
} }
} }
@@ -717,20 +695,29 @@ class MainActivity : ComponentActivity() {
) )
runOnUiThread { runOnUiThread {
if (attempt != pairConnectionAttempt) return@runOnUiThread if (attempt != pairConnectionAttempt) return@runOnUiThread
// 如果 Wi-Fi 波动后系统已交付了新的 Network,旧探测结果
// 不得覆盖新连接或短暂显示失败页。
if (connectedNetwork != network) return@runOnUiThread
if (base == null) { if (base == null) {
// 把手机实际所处的网络写进报错。否则"找不到"这三个字 // 把手机实际所处的网络写进报错。否则"找不到"这三个字
// 无法区分:手机在别的网段?没拿到网关?还是对端真的没开。 // 无法区分:手机在别的网段?没拿到网关?还是对端真的没开。
val diagnosis = buildString { 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(wifiConnector.describeNetwork(network)).append("\n")
append("二维码给出的地址:") append("连接模式:")
append(pair.endpoints.joinToString("、").ifEmpty { "(无,仅靠发现)" }) append(if (dedicatedWifi) "QFT 专用 Wi-Fi(不使用二维码/电脑本地网卡地址)" else "当前局域网备用模式")
append("\n探测过的网关地址:") append("\n探测过的网关地址:")
append(gateways.joinToString("、").ifEmpty { "(无)" }) append(gateways.joinToString("、").ifEmpty { "(无)" })
append("\n子网扫描范围:").append(subnet.size).append(" 个地址\n\n") append("\n子网扫描范围:").append(subnet.size).append(" 个地址\n\n")
append("请对照检查:① 手机与电脑是否在同一网段;") append("请对照检查:① Windows 上 QFT Direct 是否仍显示已就绪;")
append("② Windows 上是否在「Android → 电脑」页并已点「启动接收」;") append("② 防火墙是否放行 qft-desktop.exe 的当前专用网络类型;")
append("③ Windows 防火墙是否放行了 qft-desktop.exe(Profile 必须含当前网络类型)。") append("③ 手机是否仍连接二维码内的 QFT 专用网络。")
} }
showPairError(pair, diagnosis) showPairError(pair, diagnosis)
} else { } else {
@@ -144,18 +144,26 @@ object UploadClient {
discoveredEndpoint: String? = null, discoveredEndpoint: String? = null,
subnetEndpoints: List<String> = emptyList(), subnetEndpoints: List<String> = emptyList(),
): String? { ): String? {
val common = listOf( val dedicatedWifi = pairing.wifi != null
"http://192.168.137.1:${pairing.port}", // Direct mode must use only facts obtained from the dedicated Network:
"http://192.168.49.1:${pairing.port}", // 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("/") } .map { it.trim().removeSuffix("/") }
.filter { PairingProtocol.isAllowedLocalHttpEndpoint(it, pairing.port) } .filter { PairingProtocol.isAllowedLocalHttpEndpoint(it, pairing.port) }
.distinct() .distinct()
// Stage 1: QR-carried endpoints and actual gateway. This is the normal // Give a newly associated Direct network enough time for ARP, the group
// path and must complete well inside the 10-second pairing budget. // owner route and Windows' new-network firewall profile to settle. A
val fastDeadline = android.os.SystemClock.elapsedRealtime() + 1_050 // 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) { while (fast.isNotEmpty() && android.os.SystemClock.elapsedRealtime() < fastDeadline) {
probeCandidatesParallel(network, pairing, deviceName, fast, workers = 12, connectMs = 220, readMs = 260) probeCandidatesParallel(network, pairing, deviceName, fast, workers = 12, connectMs = 220, readMs = 260)
?.let { return it } ?.let { return it }
@@ -175,9 +183,9 @@ object UploadClient {
?.let { return it } ?.let { return it }
} }
// One short final pass covers a just-finished ARP/Windows firewall // One final pass covers a route/firewall transition that completed while
// transition without adding the former two-second tail latency. // the actual connected subnet fallback was running.
val deadline = android.os.SystemClock.elapsedRealtime() + 500 val deadline = android.os.SystemClock.elapsedRealtime() + if (dedicatedWifi) 1_200L else 500L
while (fast.isNotEmpty() && android.os.SystemClock.elapsedRealtime() < deadline) { while (fast.isNotEmpty() && android.os.SystemClock.elapsedRealtime() < deadline) {
probeCandidatesParallel(network, pairing, deviceName, fast, workers = 12, connectMs = 240, readMs = 260) probeCandidatesParallel(network, pairing, deviceName, fast, workers = 12, connectMs = 240, readMs = 260)
?.let { return it } ?.let { return it }
@@ -190,8 +198,8 @@ object UploadClient {
* 在指定网络(`network` 为 null 表示系统默认网络)上并发探测一组地址, * 在指定网络(`network` 为 null 表示系统默认网络)上并发探测一组地址,
* 返回第一个应答的。 * 返回第一个应答的。
* *
* 供「切换 Wi-Fi 之前先试当前网络」这一步使用:两台设备本来就在同一个 * Direct 模式只传入专用网络的实际网关;当前局域网备用模式传入经过
* 局域网时,这一下就成功了,不必再走配网弹窗与虚拟网卡。 * 同网段过滤的二维码地址。调用方必须显式绑定对应的 Network。
*/ */
fun probeEndpoints( fun probeEndpoints(
network: Network?, network: Network?,
@@ -35,8 +35,6 @@ class WifiConnector(context: Context) {
private var legacyPreviousNetworkId: Int? = null private var legacyPreviousNetworkId: Int? = null
private var legacyTargetNetworkId: Int? = null private var legacyTargetNetworkId: Int? = null
data class EndpointCandidates(val network: Network, val endpoints: List<String>)
/** /**
* 回调经由这个可替换的收件人转发,而不是被 NetworkCallback 闭包捕获。 * 回调经由这个可替换的收件人转发,而不是被 NetworkCallback 闭包捕获。
* 这样「用户点重试」时可以直接换掉 UI 回调、继续复用那个还挂着的 * 这样「用户点重试」时可以直接换掉 UI 回调、继续复用那个还挂着的
@@ -318,16 +316,6 @@ class WifiConnector(context: Context) {
private fun hasIpv4(props: LinkProperties?): Boolean = props?.linkAddresses?.any { it.address is Inet4Address } == true 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> { fun endpointsOnNetwork(network: Network?, endpoints: List<String>, port: Int): List<String> {
if (network == null) return emptyList() if (network == null) return emptyList()
val links = connectivity.getLinkProperties(network)?.linkAddresses val links = connectivity.getLinkProperties(network)?.linkAddresses
@@ -435,6 +423,26 @@ class WifiConnector(context: Context) {
.toList() .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> { fun discoveryHosts(network: Network?): List<InetAddress> {
val out = mutableListOf<InetAddress>() val out = mutableListOf<InetAddress>()
if (network != null) { if (network != null) {
@@ -10,6 +10,49 @@ import java.util.concurrent.Executors
import java.util.zip.CRC32 import java.util.zip.CRC32
class ProtocolTest { 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 @Test
fun probeCompletionWaitsForARealResultInsteadOfConsumingAnEmptyPoll() { fun probeCompletionWaitsForARealResultInsteadOfConsumingAnEmptyPoll() {
val pool = Executors.newSingleThreadExecutor() val pool = Executors.newSingleThreadExecutor()
@@ -91,6 +134,18 @@ class ProtocolTest {
assertEquals(42L, payload.fileSize) 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 @Test
fun base45KnownVectors() { fun base45KnownVectors() {
assertArrayEquals("AB".toByteArray(), Base45.decode("BB8")) assertArrayEquals("AB".toByteArray(), Base45.decode("BB8"))
+1 -1
View File
@@ -2587,7 +2587,7 @@ checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
[[package]] [[package]]
name = "qft-desktop" name = "qft-desktop"
version = "0.4.11" version = "0.4.12"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"base64", "base64",
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "qft-desktop" name = "qft-desktop"
version = "0.4.11" version = "0.4.12"
edition = "2024" edition = "2024"
rust-version = "1.95" rust-version = "1.95"
+111 -35
View File
@@ -647,15 +647,19 @@ impl QftApp {
ui.image((texture.id(), egui::vec2(side, side))); ui.image((texture.id(), egui::vec2(side, side)));
}); });
} }
// 把二维码实际广播的地址摊开显示。手机报"找不到电脑"时, if self.receive.direct_ap.is_some() {
// 第一件要确认的就是码里到底有没有它能到达的那个地址—— ui.collapsing("QFT 专用 Wi-Fi 路由", |ui| {
// 在这里一眼可见,不必等手机端的诊断。 ui.label("二维码不广播电脑现有网卡地址。");
ui.small("Android 先连接专用网络,再读取该连接的实际网关;只在专用子网内发现接收服务。");
});
} else {
ui.collapsing("二维码广播的地址", |ui| { ui.collapsing("二维码广播的地址", |ui| {
for endpoint in pairing::qr_endpoints(listen_port, self.receive.direct_ap.is_some()).iter().take(4) { for endpoint in pairing::qr_endpoints(listen_port, false).iter().take(4) {
ui.monospace(endpoint); ui.monospace(endpoint);
} }
ui.small("手机连上后会依次尝试这些地址;其中必须有一个与手机同网段。"); ui.small("当前局域网备用模式:手机只尝试与自身同网段的地址。");
}); });
}
if let Some(ap) = &self.receive.direct_ap { if let Some(ap) = &self.receive.direct_ap {
ui.label(format!("临时网络:{}", ap.ssid)); ui.label(format!("临时网络:{}", ap.ssid));
ui.small("网络身份会在这台电脑上复用以减少重复确认;每次接收仍会生成新的会话 Token。"); ui.small("网络身份会在这台电脑上复用以减少重复确认;每次接收仍会生成新的会话 Token。");
@@ -695,7 +699,11 @@ impl QftApp {
ui.horizontal_wrapped(|ui| { ui.horizontal_wrapped(|ui| {
ui.heading("电脑 → Android · 扫码自动直传"); ui.heading("电脑 → Android · 扫码自动直传");
ui.separator(); ui.separator();
ui.label("QFTSEND2 · 自动连接本地 Wi-Fi · 扫码后立即下载"); ui.label(if self.send.use_direct_ap {
"QFTSEND2 · 自动连接 QFT 专用 Wi-Fi · 扫码后立即下载"
} else {
"QFTSEND2 · 当前局域网备用模式 · 扫码后立即下载"
});
if ui.add_enabled( if ui.add_enabled(
running, running,
egui::Button::new(if self.send.qr_focus { "退出专注二维码" } else { "专注二维码" }), egui::Button::new(if self.send.qr_focus { "退出专注二维码" } else { "专注二维码" }),
@@ -823,6 +831,31 @@ impl QftApp {
} }
fn pc_to_phone_running_controls(&mut self, ui: &mut egui::Ui) { fn pc_to_phone_running_controls(&mut self, ui: &mut egui::Ui) {
let listen_port = self
.send
.server
.as_ref()
.map(|server| server.port)
.unwrap_or(sender::PREFERRED_PORT);
// 宽屏时让连接信息从控制区顶部开始,而不是先走完整个左侧控制区
// 后才进入第二行 columns。此前右侧面板因此被整体推低,形成截图中
// “广播地址上面一大片空白”的布局。
if ui.available_width() >= 860.0 {
ui.columns(2, |cols| {
self.send_control_and_firewall_column(&mut cols[0], listen_port);
self.send_connection_panel(&mut cols[1], listen_port);
});
} else {
self.send_control_panel(ui);
ui.add_space(6.0);
self.send_connection_panel(ui, listen_port);
ui.add_space(6.0);
self.firewall_panel(ui, listen_port);
}
}
fn send_control_panel(&mut self, ui: &mut egui::Ui) {
ui.group(|ui| { ui.group(|ui| {
ui.heading("直传控制"); ui.heading("直传控制");
ui.horizontal_wrapped(|ui| { ui.horizontal_wrapped(|ui| {
@@ -838,46 +871,38 @@ impl QftApp {
ui.label(&self.send.status); ui.label(&self.send.status);
ui.small("拖动下方分隔条可为二维码腾出更多高度;也可切换到“专注二维码”。"); ui.small("拖动下方分隔条可为二维码腾出更多高度;也可切换到“专注二维码”。");
}); });
ui.add_space(6.0);
// 这条路同样要接受手机的入站连接,Direct AP 的虚拟网卡更是防火墙重灾区。
// 面板必须放在运行态控制区里——直传启动后 pc_to_phone_ui 已经提前 return,
// 那个函数尾部的任何 UI 都画不出来。
let listen_port = self
.send
.server
.as_ref()
.map(|server| server.port)
.unwrap_or(sender::PREFERRED_PORT);
// 宽屏下把连接信息放到防火墙右侧:这两块都是扫码失败时要一起核对的
// 诊断信息,并排后不必在控制区里上下寻找。最小窗口下仍改回纵向,
// 给防火墙按钮和较长的 endpoint 留出足够宽度。
if ui.available_width() >= 860.0 {
ui.columns(2, |cols| {
self.firewall_panel(&mut cols[0], listen_port);
self.send_connection_panel(&mut cols[1], listen_port);
});
} else {
self.firewall_panel(ui, listen_port);
ui.add_space(6.0);
self.send_connection_panel(ui, listen_port);
} }
fn send_control_and_firewall_column(&mut self, ui: &mut egui::Ui, listen_port: u16) {
self.send_control_panel(ui);
ui.add_space(6.0);
// 直传同样接受手机入站连接;Direct AP 虚拟网卡尤其需要明确放行。
self.firewall_panel(ui, listen_port);
} }
fn send_connection_panel(&mut self, ui: &mut egui::Ui, listen_port: u16) { fn send_connection_panel(&mut self, ui: &mut egui::Ui, listen_port: u16) {
ui.group(|ui| { ui.group(|ui| {
if self.send.direct_ap.is_some() {
ui.collapsing("QFT 专用 Wi-Fi 路由", |ui| {
ui.label("二维码不广播电脑现有网卡地址。");
ui.small("Android 会先连接下方专用网络,再读取该连接的实际网关并完成会话认证;只在这个专用子网内发现电脑。");
});
} else {
ui.collapsing("二维码广播的地址", |ui| { ui.collapsing("二维码广播的地址", |ui| {
for endpoint in for endpoint in pairing::qr_endpoints(listen_port, false).iter().take(4) {
pairing::qr_endpoints(listen_port, self.send.direct_ap.is_some()).iter().take(4)
{
ui.monospace(endpoint); ui.monospace(endpoint);
} }
ui.small("手机会依次尝试这些地址;其中必须有一个与手机同网段。"); ui.small("当前局域网备用模式:手机只尝试与自身同网段的地址。");
}); });
}
ui.label(format!("电脑:{}", self.local_device)); ui.label(format!("电脑:{}", self.local_device));
ui.label(format!("手机:{}", self.send.connected_device)); ui.label(format!("手机:{}", self.send.connected_device));
if let Some(ap) = &self.send.direct_ap { if let Some(ap) = &self.send.direct_ap {
ui.label(format!("临时网络:{}", ap.ssid)); ui.label(format!("专用网络:{}", ap.ssid));
if !self.send.session_token.is_empty() {
let short = &self.send.session_token[..10.min(self.send.session_token.len())];
ui.small(format!("专用 Wi-Fi + 临时会话 {short}… · 停止直传后失效"));
}
} }
}); });
} }
@@ -885,7 +910,6 @@ impl QftApp {
fn pc_to_phone_qr_focus_ui(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) { fn pc_to_phone_qr_focus_ui(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) {
if ctx.input(|input| input.key_pressed(egui::Key::Escape)) { if ctx.input(|input| input.key_pressed(egui::Key::Escape)) {
self.send.qr_focus = false; self.send.qr_focus = false;
self.receive.focus_qr = false;
return; return;
} }
@@ -2043,6 +2067,36 @@ mod font_tests {
text text
} }
fn rendered_text_positions(build: impl Fn(&mut egui::Ui)) -> Vec<(String, f32)> {
fn collect(shape: &egui::epaint::Shape, out: &mut Vec<(String, f32)>) {
match shape {
egui::epaint::Shape::Text(text) => {
out.push((text.galley.text().to_owned(), text.pos.y));
}
egui::epaint::Shape::Vec(shapes) => {
for shape in shapes {
collect(shape, out);
}
}
_ => {}
}
}
let ctx = egui::Context::default();
let mut positions = Vec::new();
for _ in 0..2 {
positions.clear();
let output = ctx.run_ui(egui::RawInput::default(), |ui| {
ui.set_width(1_200.0);
build(ui);
});
for clipped in &output.shapes {
collect(&clipped.shape, &mut positions);
}
}
positions
}
/// 直传运行态的控制区必须包含防火墙放行入口。 /// 直传运行态的控制区必须包含防火墙放行入口。
#[test] #[test]
fn running_send_controls_render_the_firewall_panel() { fn running_send_controls_render_the_firewall_panel() {
@@ -2062,6 +2116,28 @@ mod font_tests {
); );
} }
#[test]
fn running_send_connection_panel_starts_beside_the_top_controls() {
let positions = rendered_text_positions(|ui| {
let mut app = QftApp::bare(String::new());
app.pc_to_phone_running_controls(ui);
});
let control_y = positions
.iter()
.find(|(text, _)| text.contains("直传控制"))
.map(|(_, y)| *y)
.expect("应绘制直传控制标题");
let connection_y = positions
.iter()
.find(|(text, _)| text.contains("二维码广播的地址"))
.map(|(_, y)| *y)
.expect("应绘制连接信息标题");
assert!(
(control_y - connection_y).abs() <= 8.0,
"连接信息应与顶部控制区并排,实际 y={connection_y},控制区 y={control_y}"
);
}
/// 接收页运行态(非专注模式)同样必须有防火墙入口。 /// 接收页运行态(非专注模式)同样必须有防火墙入口。
#[test] #[test]
fn receive_running_page_renders_the_firewall_panel() { fn receive_running_page_renders_the_firewall_panel() {
+49 -170
View File
@@ -50,25 +50,17 @@ struct DirectApIdentity {
} }
impl PairingPayload { impl PairingPayload {
/// v2 intentionally uses short JSON keys. The Direct-AP QR no longer carries /// v2 intentionally uses short JSON keys. A Direct-AP QR carries only the
/// a long transport string/security object and only keeps a small endpoint /// dedicated Wi-Fi identity, session and port: Android must join that Wi-Fi
/// fallback list. This materially lowers QR density and speeds phone scan. /// and obtain the desktop gateway from the resulting route table. Existing
/// LAN/virtual-adapter addresses are deliberately excluded so they cannot
/// bypass or delay dedicated pairing.
pub fn encode_text(&self) -> Result<String> { pub fn encode_text(&self) -> Result<String> {
// 开了 Direct AP 时,此前只放一个 AP 地址进二维码,手机因此**必须** let endpoints: Vec<&str> = if self.wifi.is_some() {
// 切到那张虚拟网卡才能连上。可两台设备本来常常已经在同一个局域网里, Vec::new()
// 切过去反而引入了 ICS 网卡、独立防火墙配置和几十秒的配网等待。 } else {
// self.endpoints.iter().take(4).map(String::as_str).collect()
// 现在无论是否开 Direct AP,都把常规局域网地址一并带上, };
// 手机可以先在当前网络直连,连不上再切 AP。多两个短地址对
// 二维码密度的影响可以忽略。
// 取 4 个:Direct AP 场景要同时容纳 AP 网关地址与常规局域网地址,
// 只取 3 个时前者会被挤掉——手机于是连上了 AP 却找不到电脑。
let endpoints: Vec<&str> = self
.endpoints
.iter()
.take(4)
.map(String::as_str)
.collect();
let wifi = self.wifi.as_ref().map(|w| json!([w.ssid, w.passphrase])); let wifi = self.wifi.as_ref().map(|w| json!([w.ssid, w.passphrase]));
let mut value = json!({ let mut value = json!({
"v": 2, "v": 2,
@@ -193,9 +185,10 @@ pub fn local_ipv4_addresses() -> Vec<Ipv4Addr> {
} }
ips.sort_by_key(|ip| { ips.sort_by_key(|ip| {
let o = ip.octets(); let o = ip.octets();
if is_likely_virtual(*ip) {
return 4;
}
match (o[0], o[1]) { match (o[0], o[1]) {
// Windows 的 ICS / Wi-Fi Direct 固定网段,最可能是 QFT 自己拉起来的
(192, 168) if o[2] == 137 || o[2] == 49 => 0,
(192, 168) => 1, (192, 168) => 1,
(10, _) => 2, (10, _) => 2,
(172, 16..=31) => 3, (172, 16..=31) => 3,
@@ -207,40 +200,14 @@ pub fn local_ipv4_addresses() -> Vec<Ipv4Addr> {
/// 供二维码使用的端点列表。 /// 供二维码使用的端点列表。
/// ///
/// `direct_ap_active` 为真时,把 ICS/Wi-Fi Direct 的固定网关地址放在最前。 /// Direct AP 模式不广播任何电脑现有网卡地址。手机必须先加入二维码中的
/// 这一步不能省:二维码是在启动接收的瞬间生成的,而那块虚拟网卡往往 /// 专用 Wi-Fi,再从 Android 为该连接提供的实际路由表读取网关。这样不会
/// **还没拿到 IP**,因此它不会出现在 get_if_addrs 的结果里。可手机连上 /// 猜测 192.168.137.1/49.1,也不会误连 LAN、VPN、WSL 或虚拟机网卡。
/// AP 之后,网关恰恰就是这个地址——漏掉它,手机就会连上了 Wi-Fi 却
/// 找不到电脑。
pub fn qr_endpoints(port: u16, direct_ap_active: bool) -> Vec<String> { pub fn qr_endpoints(port: u16, direct_ap_active: bool) -> Vec<String> {
let mut endpoints = local_ipv4_endpoints(port);
if direct_ap_active { if direct_ap_active {
// Direct AP 场景下二维码名额尤其紧张(只放得下 4 个),而手机此刻 return Vec::new();
// 连的是 AP 网段,虚拟网卡地址永远到不了,却会挤掉真正可用的地址。
// 这里直接剔除而不只是降权——降权在名额少时救不了场。
endpoints.retain(|endpoint| !is_virtual_endpoint(endpoint));
for ap in [
format!("http://192.168.137.1:{port}"),
format!("http://192.168.49.1:{port}"),
].into_iter().rev() {
endpoints.retain(|e| *e != ap);
endpoints.insert(0, ap);
} }
} local_ipv4_endpoints(port)
endpoints
}
/// 判断地址是否多半来自虚拟网卡。
///
/// 依据的是各家虚拟化产品的默认网段,且都以 `.1` 结尾(宿主机在虚拟网络里
/// 通常是网关)。这只是启发式,因此调用方只降权、不丢弃。
/// 判断 `http://IP:port` 形式的端点是否指向虚拟网卡。
fn is_virtual_endpoint(endpoint: &str) -> bool {
endpoint
.strip_prefix("http://")
.and_then(|rest| rest.split(':').next())
.and_then(|host| host.parse::<Ipv4Addr>().ok())
.is_some_and(is_likely_virtual)
} }
fn is_likely_virtual(ip: Ipv4Addr) -> bool { fn is_likely_virtual(ip: Ipv4Addr) -> bool {
@@ -259,43 +226,9 @@ fn is_likely_virtual(ip: Ipv4Addr) -> bool {
} }
pub fn local_ipv4_endpoints(port: u16) -> Vec<String> { pub fn local_ipv4_endpoints(port: u16) -> Vec<String> {
let mut ips = Vec::<Ipv4Addr>::new(); // 备用 LAN 模式也只广播系统中真实存在的私有地址,不再追加
if let Ok(addrs) = if_addrs::get_if_addrs() { // 192.168.137.1/49.1 等猜测值。Android 随后还会按实际子网过滤。
for iface in addrs { local_ipv4_addresses().into_iter()
let IpAddr::V4(ip) = iface.ip() else { continue };
if ip.is_loopback() || ip.is_unspecified() || ip.is_link_local() {
continue;
}
if !ips.contains(&ip) {
ips.push(ip);
}
}
}
// 真实存在的网卡地址排在前面,其中 Direct AP 常用的两个网段优先;
// 随后才补上猜测性的兜底地址。此前无条件把 192.168.137.1 / 49.1 排在
// 最前,即使本机根本没有这两块网卡——手机于是先去探测两个不存在的
// 地址,真正可用的局域网地址反而被挤到后面。
ips.sort_by_key(|ip| {
if *ip == Ipv4Addr::new(192, 168, 137, 1) { 0 }
else if *ip == Ipv4Addr::new(192, 168, 49, 1) { 1 }
// 虚拟网卡(VMware / Hyper-V / WSL / Docker)的地址手机永远到不了,
// 却会占满二维码里有限的名额,把真正可达的地址挤出去——实测中
// 192.168.30.1、192.168.31.1、172.21.96.1 就是这样把 AP 网关顶掉的。
// 不删除,只降权:万一某台机器真用这些网段做局域网,仍能兜底。
else if is_likely_virtual(*ip) { 4 }
else if ip.is_private() { 2 }
else { 3 }
});
for fallback in [
Ipv4Addr::new(192, 168, 137, 1),
Ipv4Addr::new(192, 168, 49, 1),
] {
if !ips.contains(&fallback) {
ips.push(fallback);
}
}
ips.into_iter()
.map(|ip| format!("http://{ip}:{port}")) .map(|ip| format!("http://{ip}:{port}"))
.collect() .collect()
} }
@@ -329,34 +262,19 @@ mod tests {
mod endpoint_order_tests { mod endpoint_order_tests {
use super::*; use super::*;
/// 二维码里的地址顺序直接决定手机先探测谁。真实网卡必须排在
/// 猜测性兜底地址之前,否则手机会先去连两个根本不存在的地址。
#[test] #[test]
fn real_interfaces_come_before_guessed_fallbacks() { fn current_lan_endpoints_are_all_real_private_interfaces() {
let endpoints = local_ipv4_endpoints(39393); let endpoints = local_ipv4_endpoints(39393);
assert!(!endpoints.is_empty(), "至少应有兜底地址");
let real: Vec<Ipv4Addr> = local_ipv4_addresses(); let real: Vec<Ipv4Addr> = local_ipv4_addresses();
let guessed = ["http://192.168.137.1:39393", "http://192.168.49.1:39393"]; let expected: Vec<String> = real
for address in &real { .iter()
let endpoint = format!("http://{address}:39393"); .map(|address| format!("http://{address}:39393"))
let Some(position) = endpoints.iter().position(|e| *e == endpoint) else { continue }; .collect();
for guess in guessed { assert_eq!(endpoints, expected);
// 若某个兜底地址并非本机真实网卡,它必须排在真实网卡之后
if real.iter().any(|ip| format!("http://{ip}:39393") == guess) { continue }
if let Some(guess_position) = endpoints.iter().position(|e| e == guess) {
assert!(
position < guess_position,
"真实地址 {endpoint} 应排在猜测地址 {guess} 之前:{endpoints:?}"
);
}
}
}
} }
#[test] #[test]
fn download_pairing_carries_lan_endpoints_even_with_direct_ap() { fn direct_pairing_excludes_every_preexisting_computer_address() {
// 开了 Direct AP 也要带上局域网地址,否则手机必须切网才能连
let payload = PairingPayload { let payload = PairingPayload {
v: 2, v: 2,
session: "abcdefghijklmnopqrstuvwxyz012345".into(), session: "abcdefghijklmnopqrstuvwxyz012345".into(),
@@ -383,8 +301,10 @@ mod endpoint_order_tests {
.decode(text.trim_start_matches(PAIR_PREFIX)) .decode(text.trim_start_matches(PAIR_PREFIX))
.unwrap(), .unwrap(),
).unwrap(); ).unwrap();
assert!(json.contains("192.168.8.68"), "局域网地址必须进二维码:{json}"); assert!(!json.contains("192.168.8.68"), "Direct 二维码不得携带 LAN 地址:{json}");
assert!(json.contains("192.168.137.1"), "Direct AP 地址也应保留:{json}"); assert!(!json.contains("192.168.137.1"), "Direct 二维码不得猜测 AP 网关:{json}");
assert!(json.contains("\"e\":[]"), "Direct 二维码端点必须为空:{json}");
assert!(json.contains("QFT-PC-abc"), "专用 Wi-Fi 身份必须保留:{json}");
} }
} }
@@ -392,36 +312,24 @@ mod endpoint_order_tests {
mod qr_endpoint_tests { mod qr_endpoint_tests {
use super::*; use super::*;
/// Direct AP 的网关地址必须出现在二维码里,且排在最前。
///
/// 这是一个真实发生过的回退:把"猜测性兜底地址"挪到列表末尾后,
/// 二维码只取前 3 个,192.168.137.1 被挤了出去。手机连上了 AP、
/// 拿到了 192.168.137.200/24,却在二维码里找不到 192.168.137.1,
/// 表现为"Wi-Fi 已连接但找不到电脑"——从现象几乎无法反推到这里。
#[test] #[test]
fn direct_ap_gateway_is_always_advertised_first() { fn direct_ap_never_advertises_guessed_or_local_addresses() {
let endpoints = qr_endpoints(39393, true); let endpoints = qr_endpoints(39393, true);
assert_eq!( assert!(endpoints.is_empty(), "Direct 模式只能由手机读取实际网关:{endpoints:?}");
endpoints.first().map(String::as_str),
Some("http://192.168.137.1:39393"),
"Direct AP 网关必须排第一:{endpoints:?}"
);
assert!(
endpoints.iter().any(|e| e == "http://192.168.49.1:39393"),
"Wi-Fi Direct 的另一个常用网段也应保留:{endpoints:?}"
);
} }
#[test] #[test]
fn direct_ap_addresses_survive_the_qr_length_cap() { fn direct_ap_encoding_stays_address_free_even_with_input_endpoints() {
// 即使本机有很多张网卡,AP 地址也不能被截断掉
let payload = PairingPayload { let payload = PairingPayload {
v: 2, v: 2,
session: "abcdefghijklmnopqrstuvwxyz012345".into(), session: "abcdefghijklmnopqrstuvwxyz012345".into(),
pc_name: "PC".into(), pc_name: "PC".into(),
transport: "http-parallel-v2".into(), transport: "http-parallel-v2".into(),
port: 39393, port: 39393,
endpoints: qr_endpoints(39393, true), endpoints: vec![
"http://192.168.137.1:39393".into(),
"http://10.20.30.40:39393".into(),
],
wifi: Some(WifiCredentials { wifi: Some(WifiCredentials {
ssid: "QFT-PC-abc".into(), ssid: "QFT-PC-abc".into(),
passphrase: "0123456789ab".into(), passphrase: "0123456789ab".into(),
@@ -438,21 +346,23 @@ mod qr_endpoint_tests {
.decode(text.trim_start_matches(PAIR_PREFIX)) .decode(text.trim_start_matches(PAIR_PREFIX))
.unwrap(), .unwrap(),
).unwrap(); ).unwrap();
assert!(json.contains("192.168.137.1"), "AP 网关必须进二维码:{json}"); assert!(!json.contains("192.168.137.1"), "不得携带猜测网关:{json}");
assert!(!json.contains("10.20.30.40"), "不得携带本地网卡:{json}");
} }
#[test] #[test]
fn without_direct_ap_the_guessed_addresses_stay_at_the_back() { fn without_direct_ap_no_guessed_addresses_are_added() {
let endpoints = qr_endpoints(39393, false); let endpoints = qr_endpoints(39393, false);
// 没开 AP 时不该把两个猜测地址顶到前面去占位 let real = local_ipv4_addresses();
if endpoints.len() > 2 { for guessed in ["192.168.137.1", "192.168.49.1"] {
assert_ne!( if !real.iter().any(|ip| ip.to_string() == guessed) {
endpoints.first().map(String::as_str), assert!(
Some("http://192.168.137.1:39393"), !endpoints.iter().any(|endpoint| endpoint.contains(guessed)),
"未开 Direct AP 时不应优先猜测地址:{endpoints:?}" "不存在的地址不得加入二维码:{endpoints:?}"
); );
} }
} }
}
} }
#[cfg(test)] #[cfg(test)]
@@ -482,34 +392,3 @@ mod virtual_adapter_tests {
assert!(!is_likely_virtual("172.21.96.200".parse().unwrap())); assert!(!is_likely_virtual("172.21.96.200".parse().unwrap()));
} }
} }
#[cfg(test)]
mod direct_ap_filter_tests {
use super::*;
#[test]
fn virtual_endpoints_are_dropped_when_direct_ap_is_on() {
let endpoints = qr_endpoints(39393, true);
for endpoint in &endpoints {
assert!(
!is_virtual_endpoint(endpoint),
"Direct AP 下不应出现虚拟网卡端点:{endpoint}(完整列表 {endpoints:?})"
);
}
// 剔除之后 AP 网关仍须在最前
assert_eq!(
endpoints.first().map(String::as_str),
Some("http://192.168.137.1:39393")
);
}
#[test]
fn endpoint_parser_handles_malformed_input() {
assert!(is_virtual_endpoint("http://192.168.30.1:39393"));
assert!(!is_virtual_endpoint("http://192.168.8.68:39393"));
// 解析不了的一律不当作虚拟网卡,避免误删真实地址
assert!(!is_virtual_endpoint("garbage"));
assert!(!is_virtual_endpoint("http://:39393"));
assert!(!is_virtual_endpoint(""));
}
}