use anyhow::{Context, Result}; use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _}; use rand::RngCore; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use std::{ fs, net::{IpAddr, Ipv4Addr}, path::PathBuf, }; pub const PAIR_PREFIX: &str = "QFTPAIR2:"; pub const SEND_PREFIX: &str = "QFTSEND2:"; #[derive(Clone, Debug)] pub struct PairingPayload { pub v: u8, pub session: String, pub pc_name: String, pub transport: String, pub port: u16, pub endpoints: Vec, pub wifi: Option, /// `upload` means Android uploads to this PC. `download` means the PC has /// selected a file and Android downloads it immediately after pairing. pub direction: PairingDirection, pub file_name: Option, pub file_size: Option, pub sha256: Option, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum PairingDirection { Upload, Download, } #[derive(Clone, Debug)] pub struct WifiCredentials { pub ssid: String, pub passphrase: String, pub security: String, } #[derive(Clone, Debug, Serialize, Deserialize)] struct DirectApIdentity { version: u8, ssid: String, passphrase: String, } impl PairingPayload { /// 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 { 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, "s": self.session, "n": self.pc_name, "p": self.port, "e": endpoints, "w": wifi, }); // Keep the common Android → PC QR as small as before. File metadata is // needed only for the new PC → Android automatic-download QR. if self.direction == PairingDirection::Download { let object = value.as_object_mut().expect("pairing JSON object"); object.insert("d".into(), Value::String("d".into())); object.insert("f".into(), serde_json::to_value(&self.file_name)?); object.insert("z".into(), serde_json::to_value(self.file_size)?); object.insert("h".into(), serde_json::to_value(&self.sha256)?); } let json = serde_json::to_vec(&value).context("serialize pairing payload")?; let prefix = match self.direction { PairingDirection::Upload => PAIR_PREFIX, PairingDirection::Download => SEND_PREFIX, }; Ok(format!("{prefix}{}", URL_SAFE_NO_PAD.encode(json))) } } pub fn new_session_token() -> String { let mut bytes = [0u8; 16]; rand::rng().fill_bytes(&mut bytes); URL_SAFE_NO_PAD.encode(bytes) } /// Decode an authenticated Direct discovery datagram. `Some(None)` preserves /// compatibility with older Android builds that did not include a device name. pub fn discovery_device(text: &str, session: &str) -> Option> { let prefix = format!("QFTDISC2:{session}"); if text == prefix { return Some(None); } let encoded = text.strip_prefix(&(prefix + ":"))?; let bytes = URL_SAFE_NO_PAD.decode(encoded).ok()?; let name = String::from_utf8(bytes).ok()?; let clean: String = name .chars() .filter(|c| !c.is_control()) .take(80) .collect(); (!clean.trim().is_empty()).then_some(Some(clean)) } /// Keep one random AP identity per Windows device so Android can remember the /// user's approval for that exact local-only network. The AP itself is only /// active while QFT receive mode is running; the file-transfer session token is /// regenerated every time receive mode starts. pub fn load_or_create_direct_ap_credentials(pc_name: &str) -> Result<(String, String)> { let path = direct_ap_identity_path(); if let Ok(bytes) = fs::read(&path) { if let Ok(identity) = serde_json::from_slice::(&bytes) { if identity.version == 1 && !identity.ssid.trim().is_empty() && (8..=63).contains(&identity.passphrase.len()) { return Ok((identity.ssid, identity.passphrase)); } } } let (ssid, passphrase) = new_direct_ap_credentials(pc_name); let identity = DirectApIdentity { version: 1, ssid: ssid.clone(), passphrase: passphrase.clone(), }; if let Some(parent) = path.parent() { fs::create_dir_all(parent) .with_context(|| format!("创建 QFT 配置目录 {} 失败", parent.display()))?; } let tmp = path.with_extension("json.tmp"); let json = serde_json::to_vec_pretty(&identity)?; fs::write(&tmp, json) .with_context(|| format!("保存 QFT Direct 身份 {} 失败", tmp.display()))?; if path.exists() { let _ = fs::remove_file(&path); } fs::rename(&tmp, &path) .with_context(|| format!("完成 QFT Direct 身份保存 {} 失败", path.display()))?; Ok((ssid, passphrase)) } pub fn reset_direct_ap_credentials() -> Result<()> { let path = direct_ap_identity_path(); if path.exists() { fs::remove_file(&path) .with_context(|| format!("删除 QFT Direct 身份 {} 失败", path.display()))?; } Ok(()) } fn direct_ap_identity_path() -> PathBuf { crate::platform::config_dir().join("direct-ap.json") } fn new_direct_ap_credentials(pc_name: &str) -> (String, String) { let suffix = new_session_token(); let suffix = &suffix[..6.min(suffix.len())]; let base: String = pc_name .chars() .filter(|c| c.is_ascii_alphanumeric()) .take(10) .collect(); let base = if base.is_empty() { "PC" } else { &base }; let ssid = format!("QFT-{base}-{suffix}"); let mut random = [0u8; 12]; rand::rng().fill_bytes(&mut random); let password = URL_SAFE_NO_PAD.encode(random); (ssid, password[..16.min(password.len())].to_owned()) } /// 本机可用的私有 IPv4 地址,按「最可能是对方看得到的那一个」排序。 /// /// 连接码把地址编进码里,所以这里的排序直接决定了用户第一眼看到的那串码 /// 是否好用。虚拟网卡(Docker/VPN/虚拟机桥接)会排到后面。 pub fn local_ipv4_addresses() -> 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 !ip.is_private() { continue; } if !ips.contains(&ip) { ips.push(ip); } } } ips.sort_by_key(|ip| { let o = ip.octets(); if is_likely_virtual(*ip) { return 4; } match (o[0], o[1]) { (192, 168) => 1, (10, _) => 2, (172, 16..=31) => 3, _ => 4, } }); ips } /// 供二维码使用的端点列表。 /// /// 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 { if direct_ap_active { return Vec::new(); } local_ipv4_endpoints(port) } fn is_likely_virtual(ip: Ipv4Addr) -> bool { let o = ip.octets(); if o[3] != 1 { return false; } match (o[0], o[1]) { // VMware Workstation 常用 192.168.(1..=254).1 里的高位段; // 这里只挑实测遇到的与常见默认值,避免误伤家用 192.168.0/1.1 (192, 168) => matches!(o[2], 30 | 31 | 56 | 99 | 100 | 152 | 174 | 226), // WSL2 / Hyper-V 默认在 172.16-31 段 (172, 16..=31) => true, _ => false, } } pub fn local_ipv4_endpoints(port: u16) -> Vec { // 备用 LAN 模式也只广播系统中真实存在的私有地址,不再追加 // 192.168.137.1/49.1 等猜测值。Android 随后还会按实际子网过滤。 local_ipv4_addresses().into_iter() .map(|ip| format!("http://{ip}:{port}")) .collect() } #[cfg(test)] mod tests { use super::*; #[test] fn discovery_request_reports_android_name_and_accepts_legacy_format() { let session = "abcdefghijklmnopqrstuvwxyz012345"; let name = URL_SAFE_NO_PAD.encode("HUAWEI CDY-AN90".as_bytes()); assert_eq!( discovery_device(&format!("QFTDISC2:{session}:{name}"), session), Some(Some("HUAWEI CDY-AN90".into())) ); assert_eq!(discovery_device(&format!("QFTDISC2:{session}"), session), Some(None)); assert_eq!(discovery_device("QFTDISC2:wrong", session), None); } #[test] fn download_pairing_uses_dedicated_short_prefix() { let payload = PairingPayload { v: 2, session: "abcdefghijklmnopqrstuvwxyz012345".into(), pc_name: "DESKTOP-QFT".into(), transport: "http-download-v2".into(), port: 39393, endpoints: vec!["http://192.168.49.1:39393".into()], wifi: None, direction: PairingDirection::Download, file_name: Some("sample.bin".into()), file_size: Some(42), sha256: Some("00".repeat(32)), }; let text = payload.encode_text().unwrap(); assert!(text.starts_with(SEND_PREFIX)); assert!(text.len() < 800); } } #[cfg(test)] mod endpoint_order_tests { use super::*; #[test] fn current_lan_endpoints_are_all_real_private_interfaces() { let endpoints = local_ipv4_endpoints(39393); let real: Vec = local_ipv4_addresses(); let expected: Vec = real .iter() .map(|address| format!("http://{address}:39393")) .collect(); assert_eq!(endpoints, expected); } #[test] fn direct_pairing_excludes_every_preexisting_computer_address() { let payload = PairingPayload { v: 2, session: "abcdefghijklmnopqrstuvwxyz012345".into(), pc_name: "PC".into(), transport: "http-parallel-v2".into(), port: 39393, endpoints: vec![ "http://192.168.137.1:39393".into(), "http://192.168.8.68:39393".into(), ], wifi: Some(WifiCredentials { ssid: "QFT-PC-abc".into(), passphrase: "0123456789ab".into(), security: "WPA2".into(), }), direction: PairingDirection::Upload, file_name: None, file_size: None, sha256: None, }; let text = payload.encode_text().unwrap(); let json = String::from_utf8( base64::engine::general_purpose::URL_SAFE_NO_PAD .decode(text.trim_start_matches(PAIR_PREFIX)) .unwrap(), ).unwrap(); 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}"); } } #[cfg(test)] mod qr_endpoint_tests { use super::*; #[test] fn direct_ap_never_advertises_guessed_or_local_addresses() { let endpoints = qr_endpoints(39393, true); assert!(endpoints.is_empty(), "Direct 模式只能由手机读取实际网关:{endpoints:?}"); } #[test] 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: 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(), security: "WPA2".into(), }), direction: PairingDirection::Upload, file_name: None, file_size: None, sha256: None, }; let text = payload.encode_text().unwrap(); let json = String::from_utf8( base64::engine::general_purpose::URL_SAFE_NO_PAD .decode(text.trim_start_matches(PAIR_PREFIX)) .unwrap(), ).unwrap(); assert!(!json.contains("192.168.137.1"), "不得携带猜测网关:{json}"); assert!(!json.contains("10.20.30.40"), "不得携带本地网卡:{json}"); } #[test] fn without_direct_ap_no_guessed_addresses_are_added() { let endpoints = qr_endpoints(39393, false); 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:?}" ); } } } } #[cfg(test)] mod virtual_adapter_tests { use super::*; /// 实测中这三个虚拟网卡地址把 Direct AP 网关挤出了二维码。 #[test] fn known_virtual_ranges_are_recognised() { for ip in ["192.168.30.1", "192.168.31.1", "172.21.96.1", "172.17.0.1"] { assert!(is_likely_virtual(ip.parse().unwrap()), "{ip} 应被识别为虚拟网卡"); } } /// 家用路由器最常见的网关不能被误伤,否则真实局域网地址反被降权。 #[test] fn common_home_gateways_are_not_treated_as_virtual() { for ip in ["192.168.0.1", "192.168.1.1", "192.168.8.1", "10.0.0.1"] { assert!(!is_likely_virtual(ip.parse().unwrap()), "{ip} 不应被当作虚拟网卡"); } } /// 只有 .1 结尾才可能是虚拟网关;普通主机地址一律不降权。 #[test] fn only_gateway_addresses_are_considered() { assert!(!is_likely_virtual("192.168.30.55".parse().unwrap())); assert!(!is_likely_virtual("172.21.96.200".parse().unwrap())); } }