diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index f8ea863..84b4405 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -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" } diff --git a/android/app/src/main/java/com/qft/optical/EndpointRouting.kt b/android/app/src/main/java/com/qft/optical/EndpointRouting.kt index 660c924..1d2723e 100644 --- a/android/app/src/main/java/com/qft/optical/EndpointRouting.kt +++ b/android/app/src/main/java/com/qft/optical/EndpointRouting.kt @@ -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, + routedAdvertisedEndpoints: List, + ): List = 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, + advertisedEndpoints: List, + ): List { + val candidates = listOfNotNull(discoveredEndpoint) + gatewayEndpoints + return (candidates + if (dedicatedWifi) emptyList() else advertisedEndpoints).distinct() + } + fun onAnySubnet( endpoints: List, expectedPort: Int, diff --git a/android/app/src/main/java/com/qft/optical/MainActivity.kt b/android/app/src/main/java/com/qft/optical/MainActivity.kt index 518de9a..6486af4 100644 --- a/android/app/src/main/java/com/qft/optical/MainActivity.kt +++ b/android/app/src/main/java/com/qft/optical/MainActivity.kt @@ -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 = 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 { diff --git a/android/app/src/main/java/com/qft/optical/UploadClient.kt b/android/app/src/main/java/com/qft/optical/UploadClient.kt index bca0495..834fb50 100644 --- a/android/app/src/main/java/com/qft/optical/UploadClient.kt +++ b/android/app/src/main/java/com/qft/optical/UploadClient.kt @@ -144,18 +144,26 @@ object UploadClient { discoveredEndpoint: String? = null, subnetEndpoints: List = 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?, diff --git a/android/app/src/main/java/com/qft/optical/WifiConnector.kt b/android/app/src/main/java/com/qft/optical/WifiConnector.kt index 36332aa..58edd68 100644 --- a/android/app/src/main/java/com/qft/optical/WifiConnector.kt +++ b/android/app/src/main/java/com/qft/optical/WifiConnector.kt @@ -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) - /** * 回调经由这个可替换的收件人转发,而不是被 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, port: Int): EndpointCandidates? { - val network = bestWifiNetwork() ?: return null - return EndpointCandidates(network, endpointsOnNetwork(network, endpoints, port)) - } - fun endpointsOnNetwork(network: Network?, endpoints: List, port: Int): List { 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 { + 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 { val out = mutableListOf() if (network != null) { diff --git a/android/app/src/test/java/com/qft/optical/ProtocolTest.kt b/android/app/src/test/java/com/qft/optical/ProtocolTest.kt index b7bbfca..28bca37 100644 --- a/android/app/src/test/java/com/qft/optical/ProtocolTest.kt +++ b/android/app/src/test/java/com/qft/optical/ProtocolTest.kt @@ -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")) diff --git a/desktop/Cargo.lock b/desktop/Cargo.lock index 9c96cbb..d9556da 100644 --- a/desktop/Cargo.lock +++ b/desktop/Cargo.lock @@ -2587,7 +2587,7 @@ checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" [[package]] name = "qft-desktop" -version = "0.4.11" +version = "0.4.12" dependencies = [ "anyhow", "base64", diff --git a/desktop/Cargo.toml b/desktop/Cargo.toml index f807869..93eaccd 100644 --- a/desktop/Cargo.toml +++ b/desktop/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "qft-desktop" -version = "0.4.11" +version = "0.4.12" edition = "2024" rust-version = "1.95" diff --git a/desktop/src/main.rs b/desktop/src/main.rs index 9d656c5..fd4cb21 100644 --- a/desktop/src/main.rs +++ b/desktop/src/main.rs @@ -647,15 +647,19 @@ impl QftApp { ui.image((texture.id(), egui::vec2(side, side))); }); } - // 把二维码实际广播的地址摊开显示。手机报"找不到电脑"时, - // 第一件要确认的就是码里到底有没有它能到达的那个地址—— - // 在这里一眼可见,不必等手机端的诊断。 - ui.collapsing("二维码广播的地址", |ui| { - for endpoint in pairing::qr_endpoints(listen_port, self.receive.direct_ap.is_some()).iter().take(4) { - ui.monospace(endpoint); - } - ui.small("手机连上后会依次尝试这些地址;其中必须有一个与手机同网段。"); - }); + if self.receive.direct_ap.is_some() { + ui.collapsing("QFT 专用 Wi-Fi 路由", |ui| { + ui.label("二维码不广播电脑现有网卡地址。"); + ui.small("Android 先连接专用网络,再读取该连接的实际网关;只在专用子网内发现接收服务。"); + }); + } else { + ui.collapsing("二维码广播的地址", |ui| { + for endpoint in pairing::qr_endpoints(listen_port, false).iter().take(4) { + ui.monospace(endpoint); + } + ui.small("当前局域网备用模式:手机只尝试与自身同网段的地址。"); + }); + } if let Some(ap) = &self.receive.direct_ap { ui.label(format!("临时网络:{}", ap.ssid)); ui.small("网络身份会在这台电脑上复用以减少重复确认;每次接收仍会生成新的会话 Token。"); @@ -695,7 +699,11 @@ impl QftApp { ui.horizontal_wrapped(|ui| { ui.heading("电脑 → Android · 扫码自动直传"); 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( running, 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) { + 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.heading("直传控制"); ui.horizontal_wrapped(|ui| { @@ -838,46 +871,38 @@ impl QftApp { ui.label(&self.send.status); ui.small("拖动下方分隔条可为二维码腾出更多高度;也可切换到“专注二维码”。"); }); + } + 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 的虚拟网卡更是防火墙重灾区。 - // 面板必须放在运行态控制区里——直传启动后 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); - } + // 直传同样接受手机入站连接;Direct AP 虚拟网卡尤其需要明确放行。 + self.firewall_panel(ui, listen_port); } fn send_connection_panel(&mut self, ui: &mut egui::Ui, listen_port: u16) { ui.group(|ui| { - ui.collapsing("二维码广播的地址", |ui| { - for endpoint in - pairing::qr_endpoints(listen_port, self.send.direct_ap.is_some()).iter().take(4) - { - ui.monospace(endpoint); - } - ui.small("手机会依次尝试这些地址;其中必须有一个与手机同网段。"); - }); + if self.send.direct_ap.is_some() { + ui.collapsing("QFT 专用 Wi-Fi 路由", |ui| { + ui.label("二维码不广播电脑现有网卡地址。"); + ui.small("Android 会先连接下方专用网络,再读取该连接的实际网关并完成会话认证;只在这个专用子网内发现电脑。"); + }); + } else { + ui.collapsing("二维码广播的地址", |ui| { + for endpoint in pairing::qr_endpoints(listen_port, false).iter().take(4) { + ui.monospace(endpoint); + } + ui.small("当前局域网备用模式:手机只尝试与自身同网段的地址。"); + }); + } ui.label(format!("电脑:{}", self.local_device)); ui.label(format!("手机:{}", self.send.connected_device)); 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) { if ctx.input(|input| input.key_pressed(egui::Key::Escape)) { self.send.qr_focus = false; - self.receive.focus_qr = false; return; } @@ -2043,6 +2067,36 @@ mod font_tests { 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] 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] fn receive_running_page_renders_the_firewall_panel() { diff --git a/desktop/src/pairing.rs b/desktop/src/pairing.rs index ebcebbe..7d4b600 100644 --- a/desktop/src/pairing.rs +++ b/desktop/src/pairing.rs @@ -50,25 +50,17 @@ struct DirectApIdentity { } impl PairingPayload { - /// v2 intentionally uses short JSON keys. The Direct-AP QR no longer carries - /// a long transport string/security object and only keeps a small endpoint - /// fallback list. This materially lowers QR density and speeds phone scan. + /// v2 intentionally uses short JSON keys. A Direct-AP QR carries only the + /// dedicated Wi-Fi identity, session and port: Android must join that Wi-Fi + /// 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 { - // 开了 Direct AP 时,此前只放一个 AP 地址进二维码,手机因此**必须** - // 切到那张虚拟网卡才能连上。可两台设备本来常常已经在同一个局域网里, - // 切过去反而引入了 ICS 网卡、独立防火墙配置和几十秒的配网等待。 - // - // 现在无论是否开 Direct AP,都把常规局域网地址一并带上, - // 手机可以先在当前网络直连,连不上再切 AP。多两个短地址对 - // 二维码密度的影响可以忽略。 - // 取 4 个:Direct AP 场景要同时容纳 AP 网关地址与常规局域网地址, - // 只取 3 个时前者会被挤掉——手机于是连上了 AP 却找不到电脑。 - let endpoints: Vec<&str> = self - .endpoints - .iter() - .take(4) - .map(String::as_str) - .collect(); + let endpoints: Vec<&str> = if self.wifi.is_some() { + Vec::new() + } else { + self.endpoints.iter().take(4).map(String::as_str).collect() + }; let wifi = self.wifi.as_ref().map(|w| json!([w.ssid, w.passphrase])); let mut value = json!({ "v": 2, @@ -193,9 +185,10 @@ pub fn local_ipv4_addresses() -> Vec { } ips.sort_by_key(|ip| { let o = ip.octets(); + if is_likely_virtual(*ip) { + return 4; + } match (o[0], o[1]) { - // Windows 的 ICS / Wi-Fi Direct 固定网段,最可能是 QFT 自己拉起来的 - (192, 168) if o[2] == 137 || o[2] == 49 => 0, (192, 168) => 1, (10, _) => 2, (172, 16..=31) => 3, @@ -207,40 +200,14 @@ pub fn local_ipv4_addresses() -> Vec { /// 供二维码使用的端点列表。 /// -/// `direct_ap_active` 为真时,把 ICS/Wi-Fi Direct 的固定网关地址放在最前。 -/// 这一步不能省:二维码是在启动接收的瞬间生成的,而那块虚拟网卡往往 -/// **还没拿到 IP**,因此它不会出现在 get_if_addrs 的结果里。可手机连上 -/// AP 之后,网关恰恰就是这个地址——漏掉它,手机就会连上了 Wi-Fi 却 -/// 找不到电脑。 +/// Direct AP 模式不广播任何电脑现有网卡地址。手机必须先加入二维码中的 +/// 专用 Wi-Fi,再从 Android 为该连接提供的实际路由表读取网关。这样不会 +/// 猜测 192.168.137.1/49.1,也不会误连 LAN、VPN、WSL 或虚拟机网卡。 pub fn qr_endpoints(port: u16, direct_ap_active: bool) -> Vec { - let mut endpoints = local_ipv4_endpoints(port); if direct_ap_active { - // Direct AP 场景下二维码名额尤其紧张(只放得下 4 个),而手机此刻 - // 连的是 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); - } + return Vec::new(); } - 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::().ok()) - .is_some_and(is_likely_virtual) + local_ipv4_endpoints(port) } 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 { - let mut ips = Vec::::new(); - if let Ok(addrs) = if_addrs::get_if_addrs() { - for iface in addrs { - 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() + // 备用 LAN 模式也只广播系统中真实存在的私有地址,不再追加 + // 192.168.137.1/49.1 等猜测值。Android 随后还会按实际子网过滤。 + local_ipv4_addresses().into_iter() .map(|ip| format!("http://{ip}:{port}")) .collect() } @@ -329,34 +262,19 @@ mod tests { mod endpoint_order_tests { use super::*; - /// 二维码里的地址顺序直接决定手机先探测谁。真实网卡必须排在 - /// 猜测性兜底地址之前,否则手机会先去连两个根本不存在的地址。 #[test] - fn real_interfaces_come_before_guessed_fallbacks() { + fn current_lan_endpoints_are_all_real_private_interfaces() { let endpoints = local_ipv4_endpoints(39393); - assert!(!endpoints.is_empty(), "至少应有兜底地址"); - let real: Vec = local_ipv4_addresses(); - let guessed = ["http://192.168.137.1:39393", "http://192.168.49.1:39393"]; - for address in &real { - let endpoint = format!("http://{address}:39393"); - let Some(position) = endpoints.iter().position(|e| *e == endpoint) else { continue }; - for guess in guessed { - // 若某个兜底地址并非本机真实网卡,它必须排在真实网卡之后 - 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:?}" - ); - } - } - } + let expected: Vec = real + .iter() + .map(|address| format!("http://{address}:39393")) + .collect(); + assert_eq!(endpoints, expected); } #[test] - fn download_pairing_carries_lan_endpoints_even_with_direct_ap() { - // 开了 Direct AP 也要带上局域网地址,否则手机必须切网才能连 + fn direct_pairing_excludes_every_preexisting_computer_address() { let payload = PairingPayload { v: 2, session: "abcdefghijklmnopqrstuvwxyz012345".into(), @@ -383,8 +301,10 @@ mod endpoint_order_tests { .decode(text.trim_start_matches(PAIR_PREFIX)) .unwrap(), ).unwrap(); - assert!(json.contains("192.168.8.68"), "局域网地址必须进二维码:{json}"); - assert!(json.contains("192.168.137.1"), "Direct AP 地址也应保留:{json}"); + assert!(!json.contains("192.168.8.68"), "Direct 二维码不得携带 LAN 地址:{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 { use super::*; - /// Direct AP 的网关地址必须出现在二维码里,且排在最前。 - /// - /// 这是一个真实发生过的回退:把"猜测性兜底地址"挪到列表末尾后, - /// 二维码只取前 3 个,192.168.137.1 被挤了出去。手机连上了 AP、 - /// 拿到了 192.168.137.200/24,却在二维码里找不到 192.168.137.1, - /// 表现为"Wi-Fi 已连接但找不到电脑"——从现象几乎无法反推到这里。 #[test] - fn direct_ap_gateway_is_always_advertised_first() { + fn direct_ap_never_advertises_guessed_or_local_addresses() { let endpoints = qr_endpoints(39393, true); - assert_eq!( - 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:?}" - ); + assert!(endpoints.is_empty(), "Direct 模式只能由手机读取实际网关:{endpoints:?}"); } #[test] - fn direct_ap_addresses_survive_the_qr_length_cap() { - // 即使本机有很多张网卡,AP 地址也不能被截断掉 + fn direct_ap_encoding_stays_address_free_even_with_input_endpoints() { let payload = PairingPayload { v: 2, session: "abcdefghijklmnopqrstuvwxyz012345".into(), pc_name: "PC".into(), transport: "http-parallel-v2".into(), 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 { ssid: "QFT-PC-abc".into(), passphrase: "0123456789ab".into(), @@ -438,19 +346,21 @@ mod qr_endpoint_tests { .decode(text.trim_start_matches(PAIR_PREFIX)) .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] - 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); - // 没开 AP 时不该把两个猜测地址顶到前面去占位 - if endpoints.len() > 2 { - assert_ne!( - endpoints.first().map(String::as_str), - Some("http://192.168.137.1:39393"), - "未开 Direct AP 时不应优先猜测地址:{endpoints:?}" - ); + let real = local_ipv4_addresses(); + for guessed in ["192.168.137.1", "192.168.49.1"] { + if !real.iter().any(|ip| ip.to_string() == guessed) { + assert!( + !endpoints.iter().any(|endpoint| endpoint.contains(guessed)), + "不存在的地址不得加入二维码:{endpoints:?}" + ); + } } } } @@ -482,34 +392,3 @@ mod virtual_adapter_tests { 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("")); - } -}