From 4d77ba6c911268ebc204e514819190d59c34bc92 Mon Sep 17 00:00:00 2001 From: zhy200308 <2258391712@qq.com> Date: Tue, 11 Aug 2026 09:08:37 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=96=B0=E5=A2=9E=20iPhone=20=E5=AE=A2?= =?UTF-8?q?=E6=88=B7=E7=AB=AF=EF=BC=8C=E5=90=AB=E9=9A=94=E7=A9=BA=E6=8A=95?= =?UTF-8?q?=E9=80=81=E5=BC=8F=E7=82=B9=E5=AF=B9=E7=82=B9=E4=BA=92=E4=BC=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 三条链路: - 电脑 → iPhone:扫 QFTSEND2 码下载,流式落盘 + 增量 SHA-256, 支持 Range 断点续传 - iPhone → 电脑:扫 QFTPAIR2 码后 init/chunk/finish 并行分块上传 - iPhone ↔ iPhone:QFTP2P1 扫码握手,Network.framework 开启 includePeerToPeer(AirDrop 同款 BLE 发现 + AWDL 点对点 Wi-Fi), 两台设备不需要连同一个 Wi-Fi,也不需要路由器 P2P 用 TLS-PSK 握手:32 字节预共享密钥由发送端随机生成并写进二维码, 扫码这个动作本身完成带外密钥交换与双向认证,无需证书体系与配对弹窗。 未扫到码的第三方连上来过不了握手。 核心层刻意不 import UIKit,可直接以 macOS 为目标编译测试, 不需要 Xcode 也不需要模拟器,已接入主自检套件,72 项全部通过: - 端点白名单 11 种拒绝用例(域名、公网、172.32 边界、 非规范八位组、IPv6、带凭据/路径/query) - CoreTests/MockPCServer.py 严格复刻 receiver.rs / sender.rs 的线上语义 (路径、header 名、JSON 字段、Range 行为、chunk 长度校验), 构成 Swift 与 Rust 两端的线格式契约测试,任一端改协议即会失败 - 真实 TLS-PSK 握手下的 P2P 端到端传输,含错误密钥必须被拒 iOS 平台限制(已在 ios/README.md 说明): NEHotspotConfiguration 需要付费账号 entitlement,故不实现 Direct AP 流程,与电脑互传要求同一局域网;AWDL 是苹果私有链路,Windows 无法参与。 上传块固定 4 MiB 而非 Android 的 4/8/16 MiB,因为 iOS 上 worker 数 × 块大小即内存峰值。 未验证部分:本机只有 Command Line Tools,无 Xcode 与 iOS SDK, UI 层(SwiftUI/UIKit/AVFoundation)未经编译;.xcodeproj 已通过 plutil 解析与引用完整性校验(42 个对象无悬空引用), 但未在 Xcode 中实际打开过。 --- .gitignore | 5 + ios/CoreTests/Helpers.swift | 24 + ios/CoreTests/MockPCServer.py | 241 +++++++++ ios/CoreTests/main.swift | 377 ++++++++++++++ ios/CoreTests/run.sh | 18 + ios/QFT.xcodeproj/project.pbxproj | 304 ++++++++++++ ios/QFT/App/HomeView.swift | 197 ++++++++ ios/QFT/App/QFTApp.swift | 10 + ios/QFT/App/ScannerView.swift | 137 +++++ ios/QFT/App/TransferModel.swift | 242 +++++++++ .../AccentColor.colorset/Contents.json | 4 + .../AppIcon.appiconset/Contents.json | 6 + ios/QFT/Assets.xcassets/Contents.json | 3 + ios/QFT/Core/Base64URL.swift | 46 ++ ios/QFT/Core/DownloadClient.swift | 210 ++++++++ ios/QFT/Core/HostDiscovery.swift | 271 ++++++++++ ios/QFT/Core/PairingProtocol.swift | 188 +++++++ ios/QFT/Core/PeerLink.swift | 469 ++++++++++++++++++ ios/QFT/Core/PeerPairing.swift | 94 ++++ ios/QFT/Core/UploadClient.swift | 189 +++++++ ios/QFT/Info.plist | 68 +++ ios/README.md | 118 +++++ ios/tools/generate_xcodeproj.py | 371 ++++++++++++++ scripts/ios_core_selftest.py | 40 ++ scripts/run_all_selftests.py | 1 + 25 files changed, 3633 insertions(+) create mode 100644 ios/CoreTests/Helpers.swift create mode 100644 ios/CoreTests/MockPCServer.py create mode 100644 ios/CoreTests/main.swift create mode 100755 ios/CoreTests/run.sh create mode 100644 ios/QFT.xcodeproj/project.pbxproj create mode 100644 ios/QFT/App/HomeView.swift create mode 100644 ios/QFT/App/QFTApp.swift create mode 100644 ios/QFT/App/ScannerView.swift create mode 100644 ios/QFT/App/TransferModel.swift create mode 100644 ios/QFT/Assets.xcassets/AccentColor.colorset/Contents.json create mode 100644 ios/QFT/Assets.xcassets/AppIcon.appiconset/Contents.json create mode 100644 ios/QFT/Assets.xcassets/Contents.json create mode 100644 ios/QFT/Core/Base64URL.swift create mode 100644 ios/QFT/Core/DownloadClient.swift create mode 100644 ios/QFT/Core/HostDiscovery.swift create mode 100644 ios/QFT/Core/PairingProtocol.swift create mode 100644 ios/QFT/Core/PeerLink.swift create mode 100644 ios/QFT/Core/PeerPairing.swift create mode 100644 ios/QFT/Core/UploadClient.swift create mode 100644 ios/QFT/Info.plist create mode 100644 ios/README.md create mode 100644 ios/tools/generate_xcodeproj.py create mode 100644 scripts/ios_core_selftest.py diff --git a/.gitignore b/.gitignore index 0b0c9e0..8dff8e0 100644 --- a/.gitignore +++ b/.gitignore @@ -12,3 +12,8 @@ local.properties Thumbs.db # 标定工具产物(wedge_gen.py 默认输出目录) /out +# Xcode +ios/**/xcuserdata/ +ios/**/*.xcworkspace/xcuserdata/ +ios/build/ +DerivedData/ diff --git a/ios/CoreTests/Helpers.swift b/ios/CoreTests/Helpers.swift new file mode 100644 index 0000000..0c7de41 --- /dev/null +++ b/ios/CoreTests/Helpers.swift @@ -0,0 +1,24 @@ +import Foundation +import CryptoKit + +func sha256Hex(_ data: Data) -> String { + SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() +} + +/// 从管道里读一行,带超时。用来等 MockPCServer 打印 `READY `。 +func readReadyLine(from handle: FileHandle, timeout: TimeInterval) -> String? { + let deadline = Date().addingTimeInterval(timeout) + var buffer = Data() + while Date() < deadline { + let available = handle.availableData + if available.isEmpty { + Thread.sleep(forTimeInterval: 0.02) + continue + } + buffer.append(available) + if let index = buffer.firstIndex(of: 0x0a) { + return String(data: buffer[buffer.startIndex.. --serve <文件> --save-dir <目录> --port 0 +启动后在 stdout 打印一行 `READY `,供测试脚本读取。 +""" + +import argparse +import base64 +import hashlib +import json +import os +import socket +import sys +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +STATE = {} + + +def b64url_decode(text): + padding = "=" * (-len(text) % 4) + return base64.urlsafe_b64decode(text + padding) + + +def b64url_encode(data): + return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=") + + +class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *_args): + pass + + # -------------------------------------------------- 工具 + + def _json(self, code, payload): + body = json.dumps(payload).encode("utf-8") + self.send_response(code) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.send_header("Connection", "close") + self.end_headers() + self.wfile.write(body) + + def _authorized(self): + if self.headers.get("X-QFT-Token") != STATE["token"]: + self.send_response(403) + self.send_header("Content-Length", "0") + self.send_header("Connection", "close") + self.end_headers() + return False + # 设备名必须是 base64url,解不出来说明客户端编码错了 + device = self.headers.get("X-QFT-Device") + if device is not None: + b64url_decode(device).decode("utf-8") + return True + + # -------------------------------------------------- GET + + def do_GET(self): + if not self._authorized(): + return + if self.path == "/qft/ping": + return self._json(200, {"ok": True, "protocol": 2, "parallel": True}) + if self.path == "/qft/download": + return self._download() + return self._json(404, {"ok": False}) + + def _download(self): + path = STATE["serve"] + size = os.path.getsize(path) + offset = 0 + header = self.headers.get("Range") + if header: + assert header.startswith("bytes="), "只支持 bytes= 形式的 Range" + assert header.endswith("-"), "sender.rs 只支持单段开区间 Range" + offset = int(header[len("bytes="):-1]) + assert 0 <= offset < size, "Range 越界" + remaining = size - offset + + self.send_response(206 if offset else 200) + self.send_header("Content-Type", "application/octet-stream") + self.send_header("Content-Length", str(remaining)) + self.send_header("Accept-Ranges", "bytes") + if offset: + self.send_header("Content-Range", "bytes %d-%d/%d" % (offset, size - 1, size)) + self.send_header("X-QFT-Filename", b64url_encode(os.path.basename(path).encode("utf-8"))) + self.send_header("Connection", "close") + self.end_headers() + with open(path, "rb") as fh: + fh.seek(offset) + while True: + block = fh.read(256 * 1024) + if not block: + break + self.wfile.write(block) + + # -------------------------------------------------- POST + + def do_POST(self): + if not self._authorized(): + return + if self.path == "/qft/upload/init": + return self._upload_init() + if self.path.startswith("/qft/upload/chunk/"): + return self._upload_chunk() + if self.path.startswith("/qft/upload/finish/"): + return self._upload_finish() + return self._json(404, {"ok": False}) + + def _upload_init(self): + name = b64url_decode(self.headers["X-QFT-Filename"]).decode("utf-8") + size = int(self.headers["X-QFT-Size"]) + chunk_size = int(self.headers.get("X-QFT-Chunk-Size", 8 * 1024 * 1024)) + chunk_size = max(1024 * 1024, min(16 * 1024 * 1024, chunk_size)) + total = 0 if size == 0 else (size + chunk_size - 1) // chunk_size + + upload_id = base64.urlsafe_b64encode(os.urandom(9)).decode("ascii").rstrip("=") + part = os.path.join(STATE["save_dir"], "%s.%s.qftpart" % (name, upload_id)) + with open(part, "wb") as fh: + fh.truncate(size) + STATE["uploads"][upload_id] = { + "name": name, "size": size, "chunk_size": chunk_size, + "total": total, "part": part, "received": [False] * total, + "lock": threading.Lock(), + } + return self._json(200, {"ok": True, "upload_id": upload_id, + "chunk_size": chunk_size, "total_chunks": total}) + + def _upload_chunk(self): + suffix = self.path[len("/qft/upload/chunk/"):] + upload_id, _, index_text = suffix.partition("/") + index = int(index_text) + session = STATE["uploads"].get(upload_id) + if session is None: + return self._json(500, {"ok": False, "error": "unknown upload"}) + + length = int(self.headers["Content-Length"]) + offset = index * session["chunk_size"] + expected = min(session["chunk_size"], session["size"] - offset) + assert length == expected, "chunk 长度不匹配:%d != %d" % (length, expected) + + body = b"" + while len(body) < length: + block = self.rfile.read(length - len(body)) + if not block: + break + body += block + assert len(body) == length, "chunk 体不完整" + + with session["lock"]: + if session["received"][index]: + return self._json(200, {"ok": True, "duplicate": True}) + with open(session["part"], "r+b") as fh: + fh.seek(offset) + fh.write(body) + session["received"][index] = True + return self._json(200, {"ok": True}) + + def _upload_finish(self): + upload_id = self.path[len("/qft/upload/finish/"):] + session = STATE["uploads"].get(upload_id) + if session is None: + return self._json(500, {"ok": False, "error": "unknown upload"}) + missing = session["received"].count(False) + if missing: + return self._json(409, {"ok": False, "missing": missing}) + + digest = hashlib.sha256() + with open(session["part"], "rb") as fh: + while True: + block = fh.read(1024 * 1024) + if not block: + break + digest.update(block) + final = os.path.join(STATE["save_dir"], session["name"]) + os.replace(session["part"], final) + del STATE["uploads"][upload_id] + return self._json(200, {"ok": True, "sha256": digest.hexdigest(), "size": session["size"]}) + + +def udp_responder(token, http_port, stop): + """QFTDISC2: → QFTHERE2::,对应 sender.rs 的发现线程。""" + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + try: + sock.bind(("0.0.0.0", 39392)) + except OSError: + return + sock.settimeout(0.25) + expected = ("QFTDISC2:%s" % token).encode("ascii") + reply = ("QFTHERE2:%s:%d" % (token, http_port)).encode("ascii") + while not stop.is_set(): + try: + data, peer = sock.recvfrom(512) + except socket.timeout: + continue + except OSError: + break + if data == expected: + sock.sendto(reply, peer) + sock.close() + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--token", required=True) + parser.add_argument("--serve", required=True, help="供 /qft/download 下发的文件") + parser.add_argument("--save-dir", required=True, help="接收上传的目录") + parser.add_argument("--port", type=int, default=0) + parser.add_argument("--udp", action="store_true", help="同时启动 UDP 发现应答") + args = parser.parse_args() + + STATE.update(token=args.token, serve=args.serve, save_dir=args.save_dir, uploads={}) + os.makedirs(args.save_dir, exist_ok=True) + + server = ThreadingHTTPServer(("127.0.0.1", args.port), Handler) + port = server.server_address[1] + + stop = threading.Event() + if args.udp: + threading.Thread(target=udp_responder, args=(args.token, port, stop), daemon=True).start() + + print("READY %d" % port, flush=True) + try: + server.serve_forever() + except KeyboardInterrupt: + pass + finally: + stop.set() + + +if __name__ == "__main__": + main() diff --git a/ios/CoreTests/main.swift b/ios/CoreTests/main.swift new file mode 100644 index 0000000..d8ec3e1 --- /dev/null +++ b/ios/CoreTests/main.swift @@ -0,0 +1,377 @@ +import Foundation + +// QFT iOS 核心层测试。刻意不依赖 XCTest:这样在只有 Command Line Tools、 +// 没有 Xcode 的机器上也能 `swiftc` 直接编译运行,CI 与本地一致。 +// +// 集成测试跑在 MockPCServer.py 上,该 mock 严格复刻 receiver.rs / sender.rs +// 的线上语义,因此这里通过 == 线格式与 Windows 端兼容。 + +var failures = 0 +var checks = 0 + +func check(_ condition: Bool, _ message: String) { + checks += 1 + if condition { + print(" ok \(message)") + } else { + failures += 1 + print(" FAIL \(message)") + } +} + +func checkEqual(_ actual: T, _ expected: T, _ message: String) { + check(actual == expected, "\(message)(实得 \(actual))") +} + +func section(_ title: String) { print("\n== \(title) ==") } + +// ---------------------------------------------------------------- Base64URL + +section("Base64URL") +checkEqual(Base64URL.encode("QFT"), "UUZU", "编码无填充") +checkEqual(Base64URL.decodeString("UUZU"), "QFT", "解码往返") +check(Base64URL.decode("a+b/c") == nil, "拒绝标准 Base64 字母表") +check(Base64URL.decode("A") == nil, "拒绝不可能的长度") +checkEqual(Base64URL.encode(Data([0xfb, 0xff])), "-_8", "- 与 _ 替换正确") +checkEqual(Base64URL.decode("-_8"), Data([0xfb, 0xff]), "- 与 _ 解码正确") +for _ in 0..<200 { + let raw = Data((0.. String { + let data = try! JSONSerialization.data(withJSONObject: object) + return prefix + Base64URL.encode(data) +} + +let session = "abcdefghijklmnopqrstuvwxyz012345" +let uploadText = makePairingText(prefix: "QFTPAIR2:", [ + "v": 2, "s": session, "n": "DESKTOP-QFT", "p": 39393, + "e": ["http://192.168.1.20:39393"], +]) +let upload = PairingProtocol.parse(uploadText) +check(upload != nil, "解析 QFTPAIR2") +checkEqual(upload?.direction, .uploadToPC, "方向为上传") +checkEqual(upload?.session, session, "会话令牌") +checkEqual(upload?.port, 39393, "端口") +checkEqual(upload?.pcName, "DESKTOP-QFT", "电脑名") +checkEqual(upload?.endpoints.count, 1, "端点数量") + +let downloadText = makePairingText(prefix: "QFTSEND2:", [ + "v": 2, "s": session, "n": "DESKTOP-QFT", "p": 39393, + "e": ["http://10.0.0.5:39393"], "d": "d", + "f": "报告.pdf", "z": 1_234_567, "h": String(repeating: "ab", count: 32), +]) +let download = PairingProtocol.parse(downloadText) +check(download != nil, "解析 QFTSEND2") +checkEqual(download?.direction, .downloadToPhone, "方向为下载") +checkEqual(download?.fileName, "报告.pdf", "文件名支持中文") +checkEqual(download?.fileSize, 1_234_567, "文件大小") + +check(PairingProtocol.parse("QFTPAIR2:" + Base64URL.encode( + try! JSONSerialization.data(withJSONObject: [ + "v": 2, "s": session, "p": 39393, "e": ["http://192.168.1.20:39393"], "d": "d", + ]))) == nil, "前缀与方向不符时拒绝") + +check(PairingProtocol.parse(makePairingText(prefix: "QFTSEND2:", [ + "v": 2, "s": session, "p": 39393, "e": ["http://10.0.0.5:39393"], "d": "d", + "f": "x.bin", "z": 1, "h": "not-a-hash", +])) == nil, "SHA-256 格式错误时拒绝") + +check(PairingProtocol.parse(makePairingText(prefix: "QFTPAIR2:", [ + "v": 1, "s": session, "p": 39393, "e": ["http://192.168.1.20:39393"], +])) == nil, "版本号不是 2 时拒绝") + +check(PairingProtocol.parse(makePairingText(prefix: "QFTPAIR2:", [ + "v": 2, "s": "short", "p": 39393, "e": ["http://192.168.1.20:39393"], +])) == nil, "会话令牌过短时拒绝") + +// ---------------------------------------------------------------- 端点白名单 + +section("端点白名单(二维码是不可信输入)") +let allowed = [ + "http://192.168.1.1:39393", "http://10.1.2.3:39393", + "http://172.16.0.1:39393", "http://172.31.255.254:39393", + "http://127.0.0.1:39393", "http://169.254.1.2:39393", +] +for endpoint in allowed { + check(PairingProtocol.isAllowedLocalHTTPEndpoint(endpoint, expectedPort: 39393), "接受 \(endpoint)") +} +let rejected = [ + "https://192.168.1.1:39393", // 只允许 http + "http://evil.com:39393", // 域名 + "http://8.8.8.8:39393", // 公网 + "http://172.32.0.1:39393", // 172 段边界外 + "http://192.168.1.1:1234", // 端口不符 + "http://user@192.168.1.1:39393", // 带凭据 + "http://192.168.1.1:39393/path", // 带路径 + "http://192.168.1.1:39393?a=b", // 带 query + "http://192.168.01.1:39393", // 非规范八位组 + "http://192.168.1:39393", // 段数不足 + "http://[::1]:39393", // IPv6 +] +for endpoint in rejected { + check(!PairingProtocol.isAllowedLocalHTTPEndpoint(endpoint, expectedPort: 39393), "拒绝 \(endpoint)") +} + +// ---------------------------------------------------------------- 本地网络 + +section("本机网络推导") +checkEqual(LocalNetwork.ipv4("192.168.1.20"), 0xC0A80114, "IPv4 转整数") +checkEqual(LocalNetwork.format(0xC0A80114), "192.168.1.20", "整数转 IPv4") +check(LocalNetwork.ipv4("192.168.1.256") == nil, "拒绝越界八位组") + +// ---------------------------------------------------------------- 集成测试 + +section("集成:与 MockPCServer 的完整传输") + +let root = URL(fileURLWithPath: CommandLine.arguments.count > 1 ? CommandLine.arguments[1] + : NSTemporaryDirectory()).appendingPathComponent("qft-ios-test", isDirectory: true) +try? FileManager.default.removeItem(at: root) +try! FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + +let mockScript = URL(fileURLWithPath: #filePath) + .deletingLastPathComponent().appendingPathComponent("MockPCServer.py") + +// 3 MiB + 一点零头,确保最后一块是不完整块 +let payloadSize = 3 * 1024 * 1024 + 4321 +var payload = Data(count: payloadSize) +payload.withUnsafeMutableBytes { buffer in + guard let base = buffer.bindMemory(to: UInt8.self).baseAddress else { return } + var state: UInt64 = 0x2026_0810 + for index in 0..> 33) & 0xff) + } +} +let sourceURL = root.appendingPathComponent("payload.bin") +try! payload.write(to: sourceURL) +let payloadHash = sha256Hex(payload) + +let saveDir = root.appendingPathComponent("received", isDirectory: true) +let downloadDir = root.appendingPathComponent("downloads", isDirectory: true) +try! FileManager.default.createDirectory(at: downloadDir, withIntermediateDirectories: true) +let token = "testsession0123456789abcdefghijk" + +let process = Process() +process.executableURL = URL(fileURLWithPath: "/usr/bin/env") +process.arguments = ["python3", mockScript.path, "--token", token, + "--serve", sourceURL.path, "--save-dir", saveDir.path, "--port", "0"] +let pipe = Pipe() +process.standardOutput = pipe +try! process.run() + +var port = 0 +let readyLine = readReadyLine(from: pipe.fileHandleForReading, timeout: 10) +if let readyLine, readyLine.hasPrefix("READY ") { + port = Int(readyLine.dropFirst("READY ".count).trimmingCharacters(in: .whitespaces)) ?? 0 +} +check(port > 0, "mock 电脑端已启动(端口 \(port))") + +if port > 0 { + let base = "http://127.0.0.1:\(port)" + let host = QFTHost(baseURL: base) + + let sendPairing = PairingPayload( + version: 2, session: token, pcName: "MOCK-PC", port: port, + endpoints: [base], wifi: nil, direction: .downloadToPhone, + fileName: "payload.bin", fileSize: UInt64(payloadSize), sha256: payloadHash) + + let semaphore = DispatchSemaphore(value: 0) + Task { + defer { semaphore.signal() } + + // --- 发现 --- + let discovery = HostDiscovery(pairing: sendPairing, deviceName: "iPhone 测试机") + let located = try? await discovery.locate() + check(located?.baseURL == base, "通过二维码端点定位到电脑") + + // --- 下载 --- + var lastFraction = 0.0 + let downloader = DownloadClient(host: host, pairing: sendPairing, + deviceName: "iPhone 测试机", + destinationDirectory: downloadDir) + do { + let saved = try await downloader.run { lastFraction = $0.fraction } + let received = try Data(contentsOf: saved) + checkEqual(received.count, payloadSize, "下载字节数一致") + checkEqual(sha256Hex(received), payloadHash, "下载内容 SHA-256 一致") + check(lastFraction > 0.99, "进度回调抵达 100%") + checkEqual(saved.lastPathComponent, "payload.bin", "落盘文件名正确") + check(!FileManager.default.fileExists(atPath: saved.path + ".qftpart"), "临时文件已清理") + } catch { + check(false, "下载失败:\(error.localizedDescription)") + } + + // --- 下载续传 --- + do { + let partURL = downloadDir.appendingPathComponent("payload.bin.qftpart") + try? FileManager.default.removeItem(at: partURL) + try payload.prefix(1_000_000).write(to: partURL) + let resumed = try await DownloadClient(host: host, pairing: sendPairing, + deviceName: "iPhone", + destinationDirectory: downloadDir).run { _ in } + let data = try Data(contentsOf: resumed) + checkEqual(sha256Hex(data), payloadHash, "从 1,000,000 字节处续传后内容仍正确") + try? FileManager.default.removeItem(at: resumed) + } catch { + check(false, "续传失败:\(error.localizedDescription)") + } + + // --- 上传 --- + let uploadPairing = PairingPayload( + version: 2, session: token, pcName: "MOCK-PC", port: port, + endpoints: [base], wifi: nil, direction: .uploadToPC, + fileName: nil, fileSize: nil, sha256: nil) + do { + var seen = 0.0 + let uploader = UploadClient(host: host, pairing: uploadPairing, deviceName: "iPhone 测试机") + let sha = try await uploader.run(fileURL: sourceURL) { seen = $0.fraction } + checkEqual(sha, payloadHash, "上传后电脑侧 SHA-256 与本地一致") + check(seen > 0.99, "上传进度回调抵达 100%") + let landed = saveDir.appendingPathComponent("payload.bin") + let data = try Data(contentsOf: landed) + checkEqual(data.count, payloadSize, "电脑侧落盘大小一致") + checkEqual(sha256Hex(data), payloadHash, "电脑侧落盘内容一致") + } catch { + check(false, "上传失败:\(error.localizedDescription)") + } + + // --- 错误令牌必须被拒 --- + let badPairing = PairingPayload( + version: 2, session: "wrongsession0123456789abcdefghij", pcName: "MOCK-PC", + port: port, endpoints: [base], wifi: nil, direction: .uploadToPC, + fileName: nil, fileSize: nil, sha256: nil) + do { + _ = try await UploadClient(host: host, pairing: badPairing, + deviceName: "iPhone").run(fileURL: sourceURL) { _ in } + check(false, "错误令牌本应失败") + } catch { + check(true, "错误令牌被拒绝:\(error.localizedDescription)") + } + } + semaphore.wait() +} + +process.terminate() + +// ---------------------------------------------------------------- P2P 配对码 + +section("隔空投送式配对码") + +let peerSample = PeerPairing( + version: 1, key: Data((0..<32).map { UInt8($0) }), instance: "qft-abcdefghijkl", + senderName: "我的 iPhone", fileName: "视频.mov", fileSize: 987_654_321, + sha256: String(repeating: "cd", count: 32)) +let peerRoundTrip = PeerPairing.parse(peerSample.encode()) +checkEqual(peerRoundTrip, peerSample, "QFTP2P1 编解码往返一致") +check(PeerPairing.isPeerText(peerSample.encode()), "前缀识别") +check(PairingProtocol.parse(peerSample.encode()) == nil, "P2P 码不会被误判为 QFTPAIR2") + +func mutatedPeer(_ change: (inout [String: Any]) -> Void) -> String? { + var object: [String: Any] = [ + "v": 1, "k": Base64URL.encode(Data(repeating: 7, count: 32)), + "i": "qft-abcdefghijkl", "n": "iPhone", "f": "a.bin", + "z": 10, "h": String(repeating: "ab", count: 32), + ] + change(&object) + let data = try! JSONSerialization.data(withJSONObject: object) + return PeerPairing.prefix + Base64URL.encode(data) +} +check(PeerPairing.parse(mutatedPeer { $0["k"] = Base64URL.encode(Data(repeating: 7, count: 16)) }!) == nil, + "密钥不足 32 字节时拒绝") +check(PeerPairing.parse(mutatedPeer { $0["i"] = "bad instance!" }!) == nil, "非法实例名时拒绝") +check(PeerPairing.parse(mutatedPeer { $0["f"] = "../../etc/passwd" }!) == nil, "文件名含路径分隔符时拒绝") +check(PeerPairing.parse(mutatedPeer { $0["h"] = "zz" }!) == nil, "摘要格式错误时拒绝") +check(PeerPairing.newKey().count == 32, "新密钥为 32 字节") +check(PeerPairing.isValidInstance(PeerPairing.newInstance()), "新实例名合法") +check(PeerPairing.newKey() != PeerPairing.newKey(), "密钥每次不同") + +// ---------------------------------------------------------------- P2P 传输 + +section("隔空投送式点对点传输(TLS-PSK 真实握手)") + +let peerDir = root.appendingPathComponent("peer", isDirectory: true) +try! FileManager.default.createDirectory(at: peerDir, withIntermediateDirectories: true) + +let peerSemaphore = DispatchSemaphore(value: 0) +Task { + defer { peerSemaphore.signal() } + let sender = PeerSender(fileURL: sourceURL, deviceName: "发送端 iPhone") + do { + let pairing = try sender.start() + checkEqual(pairing.fileSize, UInt64(payloadSize), "配对码里的文件大小") + checkEqual(pairing.sha256, payloadHash, "配对码里的 SHA-256 由发送端实算") + + let port = try await sender.listeningPort() + check(port > 0, "监听器就绪(端口 \(port))") + + // 二维码在真机上是扫出来的,这里模拟:编码 → 解码 → 用解出来的配对码连接 + guard let scanned = PeerPairing.parse(pairing.encode()) else { + check(false, "配对码无法解析"); return + } + + var receiver = PeerReceiver(pairing: scanned, destinationDirectory: peerDir) + receiver.directPort = port // 测试跳过 Bonjour,直连回环 + + async let sendSide: Void = sender.waitAndSend { _ in } + var peerFraction = 0.0 + let saved = try await receiver.run { peerFraction = $0.fraction } + try await sendSide + + let data = try Data(contentsOf: saved) + checkEqual(data.count, payloadSize, "P2P 收到字节数一致") + checkEqual(sha256Hex(data), payloadHash, "P2P 收到内容 SHA-256 一致") + check(peerFraction > 0.99, "P2P 进度回调抵达 100%") + check(!FileManager.default.fileExists(atPath: saved.path + ".qftpart"), "P2P 临时文件已清理") + } catch { + check(false, "P2P 传输失败:\(error.localizedDescription)") + } + sender.stop() +} +if peerSemaphore.wait(timeout: .now() + 60) == .timedOut { + check(false, "P2P 传输超时") +} + +// 错误密钥必须握手失败 +let wrongKeySemaphore = DispatchSemaphore(value: 0) +Task { + defer { wrongKeySemaphore.signal() } + let sender = PeerSender(fileURL: sourceURL, deviceName: "发送端") + do { + let pairing = try sender.start() + let port = try await sender.listeningPort() + let tampered = PeerPairing(version: 1, key: PeerPairing.newKey(), + instance: pairing.instance, senderName: pairing.senderName, + fileName: pairing.fileName, fileSize: pairing.fileSize, + sha256: pairing.sha256) + var receiver = PeerReceiver(pairing: tampered, destinationDirectory: peerDir) + receiver.directPort = port + _ = try await receiver.run { _ in } + check(false, "错误密钥本应握手失败") + } catch { + check(true, "错误密钥被 TLS-PSK 拒绝") + } + sender.stop() +} +if wrongKeySemaphore.wait(timeout: .now() + 30) == .timedOut { + check(false, "错误密钥用例超时(握手未在预期时间内失败)") +} + +// 测试全程只写 root 下的临时目录,不碰 Documents +try? FileManager.default.removeItem(at: root) + +print("\n检查 \(checks) 项,失败 \(failures) 项") +if failures > 0 { + print("IOS CORE TESTS FAILED") + exit(1) +} +print("IOS CORE TESTS PASSED") diff --git a/ios/CoreTests/run.sh b/ios/CoreTests/run.sh new file mode 100755 index 0000000..407e842 --- /dev/null +++ b/ios/CoreTests/run.sh @@ -0,0 +1,18 @@ +#!/bin/bash +# 在只有 Command Line Tools 的机器上编译并运行 iOS 核心层测试。 +# +# 核心层刻意不 import UIKit/AVFoundation,因此可以直接以 macOS 为目标编译, +# 在没有 Xcode / 没有模拟器的环境里也能验证协议、发现与传输逻辑。 +set -euo pipefail + +cd "$(dirname "$0")/.." +OUT="$(mktemp -d)" +trap 'rm -rf "$OUT"' EXIT + +echo "== 编译 ==" +swiftc -swift-version 5 -O \ + QFT/Core/*.swift CoreTests/*.swift \ + -o "$OUT/qft-core-tests" + +echo "== 运行 ==" +"$OUT/qft-core-tests" "$OUT" diff --git a/ios/QFT.xcodeproj/project.pbxproj b/ios/QFT.xcodeproj/project.pbxproj new file mode 100644 index 0000000..08f4a84 --- /dev/null +++ b/ios/QFT.xcodeproj/project.pbxproj @@ -0,0 +1,304 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 56; + objects = { + +/* Begin PBXBuildFile section */ + 554512A1FC8A6F66E2784787 /* QFTApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 453B172D654B3AEDE4E36D1E /* QFTApp.swift */; }; + 78FD5CF5E04D7E2483B90BAA /* HomeView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B6863D13BC7270D7FCE21E7 /* HomeView.swift */; }; + BDCF0D82F0BD0328770A8ABD /* ScannerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F3B15455554D7647B44D5038 /* ScannerView.swift */; }; + E26487D1146FDF6DD5F92D80 /* TransferModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3017489412A6FCAE8995B32E /* TransferModel.swift */; }; + EE5510DAC5BBB7F9D41A8F26 /* Base64URL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 848334DC6B2D30622C7E2A45 /* Base64URL.swift */; }; + 38E462342111ACFA8775D17B /* PairingProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5459D124A555B0E4121361E5 /* PairingProtocol.swift */; }; + 6B2EB3BCEDA4855168DB4ACE /* HostDiscovery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3776FFCC2817EF6BF3EEC4FD /* HostDiscovery.swift */; }; + 978F01FFFFF69591E44C8528 /* DownloadClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = EAA81C375609633BD8DB42F3 /* DownloadClient.swift */; }; + 0469B1106E6746B3BE56007D /* UploadClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = B8FB8A4A9482DB8F1234AE39 /* UploadClient.swift */; }; + 4D2B05655C76F69F32349834 /* PeerPairing.swift in Sources */ = {isa = PBXBuildFile; fileRef = 06E1A38EC22BBFED928C8EB6 /* PeerPairing.swift */; }; + A80B2E7BF8035E27D115EF59 /* PeerLink.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8DD16686BB19417EDC0B611A /* PeerLink.swift */; }; + C0C0B5440A627CE758643A9F /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = C628A05E9C83375781E165EB /* Assets.xcassets */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + 928818DCDA72C62B2D8288D5 /* QFT.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = QFT.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 453B172D654B3AEDE4E36D1E /* QFTApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QFTApp.swift; sourceTree = ""; }; + 0B6863D13BC7270D7FCE21E7 /* HomeView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeView.swift; sourceTree = ""; }; + F3B15455554D7647B44D5038 /* ScannerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScannerView.swift; sourceTree = ""; }; + 3017489412A6FCAE8995B32E /* TransferModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransferModel.swift; sourceTree = ""; }; + 848334DC6B2D30622C7E2A45 /* Base64URL.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Base64URL.swift; sourceTree = ""; }; + 5459D124A555B0E4121361E5 /* PairingProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PairingProtocol.swift; sourceTree = ""; }; + 3776FFCC2817EF6BF3EEC4FD /* HostDiscovery.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HostDiscovery.swift; sourceTree = ""; }; + EAA81C375609633BD8DB42F3 /* DownloadClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DownloadClient.swift; sourceTree = ""; }; + B8FB8A4A9482DB8F1234AE39 /* UploadClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UploadClient.swift; sourceTree = ""; }; + 06E1A38EC22BBFED928C8EB6 /* PeerPairing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PeerPairing.swift; sourceTree = ""; }; + 8DD16686BB19417EDC0B611A /* PeerLink.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PeerLink.swift; sourceTree = ""; }; + C628A05E9C83375781E165EB /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 7E4A60F8CA5D515103446ED3 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 019BAB185F97B56993A7087D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 32AAB6DFB51CD1888CC4883B /* App */ = { + isa = PBXGroup; + children = ( + 0B6863D13BC7270D7FCE21E7 /* HomeView.swift */, + 453B172D654B3AEDE4E36D1E /* QFTApp.swift */, + F3B15455554D7647B44D5038 /* ScannerView.swift */, + 3017489412A6FCAE8995B32E /* TransferModel.swift */, + ); + path = App; + sourceTree = ""; + }; + EC599E8CF455428A5E3179CE /* Core */ = { + isa = PBXGroup; + children = ( + 848334DC6B2D30622C7E2A45 /* Base64URL.swift */, + EAA81C375609633BD8DB42F3 /* DownloadClient.swift */, + 3776FFCC2817EF6BF3EEC4FD /* HostDiscovery.swift */, + 5459D124A555B0E4121361E5 /* PairingProtocol.swift */, + 8DD16686BB19417EDC0B611A /* PeerLink.swift */, + 06E1A38EC22BBFED928C8EB6 /* PeerPairing.swift */, + B8FB8A4A9482DB8F1234AE39 /* UploadClient.swift */, + ); + path = Core; + sourceTree = ""; + }; + 36EDFB66685EBD501D3910CE /* QFT */ = { + isa = PBXGroup; + children = ( + 32AAB6DFB51CD1888CC4883B /* App */, + C628A05E9C83375781E165EB /* Assets.xcassets */, + EC599E8CF455428A5E3179CE /* Core */, + 7E4A60F8CA5D515103446ED3 /* Info.plist */, + ); + path = QFT; + sourceTree = ""; + }; + 47C128B82C29A60341C3928E = { + isa = PBXGroup; + children = ( + 36EDFB66685EBD501D3910CE /* QFT */, + 83E44493474BECB586AAD962 /* Products */, + ); + sourceTree = ""; + }; + 83E44493474BECB586AAD962 /* Products */ = { + isa = PBXGroup; + children = ( + 928818DCDA72C62B2D8288D5 /* QFT.app */, + ); + name = Products; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 497CBF7ECF21FFA362230876 /* QFT */ = { + isa = PBXNativeTarget; + buildConfigurationList = A886B50DF087AEF7B87CDC65; + buildPhases = ( + C2511B36F0F0E810A9E46328 /* Sources */, + 019BAB185F97B56993A7087D /* Frameworks */, + C2112B99FC6905E49DE55430 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = QFT; + productName = QFT; + productReference = 928818DCDA72C62B2D8288D5 /* QFT.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 98F54143AB4E86B28C3AFEE0 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = 1; + LastSwiftUpdateCheck = 1600; + LastUpgradeCheck = 1600; + TargetAttributes = { + 497CBF7ECF21FFA362230876 = { + CreatedOnToolsVersion = 16.0; + }; + }; + }; + buildConfigurationList = 26E84C2B3712F7DFAC8AD93F; + compatibilityVersion = "Xcode 14.0"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + "zh-Hans", + ); + mainGroup = 47C128B82C29A60341C3928E; + productRefGroup = 83E44493474BECB586AAD962 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 497CBF7ECF21FFA362230876 /* QFT */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + C2112B99FC6905E49DE55430 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + C0C0B5440A627CE758643A9F /* Assets.xcassets in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + C2511B36F0F0E810A9E46328 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 554512A1FC8A6F66E2784787 /* QFTApp.swift in Sources */, + 78FD5CF5E04D7E2483B90BAA /* HomeView.swift in Sources */, + BDCF0D82F0BD0328770A8ABD /* ScannerView.swift in Sources */, + E26487D1146FDF6DD5F92D80 /* TransferModel.swift in Sources */, + EE5510DAC5BBB7F9D41A8F26 /* Base64URL.swift in Sources */, + 38E462342111ACFA8775D17B /* PairingProtocol.swift in Sources */, + 6B2EB3BCEDA4855168DB4ACE /* HostDiscovery.swift in Sources */, + 978F01FFFFF69591E44C8528 /* DownloadClient.swift in Sources */, + 0469B1106E6746B3BE56007D /* UploadClient.swift in Sources */, + 4D2B05655C76F69F32349834 /* PeerPairing.swift in Sources */, + A80B2E7BF8035E27D115EF59 /* PeerLink.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin XCBuildConfiguration section */ + 70DCC1EB255A5F3C8D9ED349 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = "DEBUG=1 $(inherited)"; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + DB189EBE9D4E38495C3C7EF5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + ENABLE_PREVIEWS = YES; + GENERATE_INFOPLIST_FILE = NO; + INFOPLIST_FILE = QFT/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + MARKETING_VERSION = 0.1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.qft.transfer; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_EMIT_LOC_STRINGS = NO; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + C3DCEEC1E0EB17A5583B8E94 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + SDKROOT = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_VERSION = 5.0; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 032222C0BAA33BC7119DFAF1 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + ENABLE_PREVIEWS = YES; + GENERATE_INFOPLIST_FILE = NO; + INFOPLIST_FILE = QFT/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + MARKETING_VERSION = 0.1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.qft.transfer; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_EMIT_LOC_STRINGS = NO; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 26E84C2B3712F7DFAC8AD93F = { + isa = XCConfigurationList; + buildConfigurations = ( + 70DCC1EB255A5F3C8D9ED349 /* Debug */, + C3DCEEC1E0EB17A5583B8E94 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + A886B50DF087AEF7B87CDC65 = { + isa = XCConfigurationList; + buildConfigurations = ( + DB189EBE9D4E38495C3C7EF5 /* Debug */, + 032222C0BAA33BC7119DFAF1 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 98F54143AB4E86B28C3AFEE0 /* Project object */; +} diff --git a/ios/QFT/App/HomeView.swift b/ios/QFT/App/HomeView.swift new file mode 100644 index 0000000..7f8aba4 --- /dev/null +++ b/ios/QFT/App/HomeView.swift @@ -0,0 +1,197 @@ +import SwiftUI +import UniformTypeIdentifiers + +struct HomeView: View { + + /// 同一个 view 上挂多个 .fileImporter 会互相覆盖,只能有一个, + /// 所以用这个枚举区分「选完文件之后要干什么」。 + private enum PickPurpose: Equatable { + case peerSend + case uploadToPC(PairingPayload) + } + + @StateObject private var model = TransferModel() + @State private var pickPurpose: PickPurpose? + + var body: some View { + NavigationStack { + content + .navigationTitle("QFT 快传") + .navigationBarTitleDisplayMode(.inline) + } + .fullScreenCover(isPresented: isScanning) { + ScannerView(onFound: { model.handleScanned($0) }, onCancel: { model.cancel() }) + .ignoresSafeArea() + } + .fileImporter(isPresented: isPicking, + allowedContentTypes: [UTType.item], allowsMultipleSelection: false) { result in + let purpose = pickPurpose + pickPurpose = nil + guard case .success(let urls) = result, let url = urls.first else { + model.reset() + return + } + switch purpose { + case .peerSend: model.startPeerSend(fileURL: url) + case .uploadToPC(let pairing): model.startUpload(pairing, fileURL: url) + case nil: break + } + } + .onAppear { model.refreshReceivedFiles() } + .onChange(of: model.stage) { _, stage in + // 扫到 QFTPAIR2 之后才知道要选文件,所以选择器由 stage 驱动 + if case .pickFileForUpload(let pairing) = stage { + pickPurpose = .uploadToPC(pairing) + } + } + } + + private var isScanning: Binding { + Binding(get: { model.stage == .scanning }, set: { if !$0 { model.cancel() } }) + } + + private var isPicking: Binding { + Binding(get: { pickPurpose != nil }, set: { if !$0 { pickPurpose = nil } }) + } + + @ViewBuilder + private var content: some View { + switch model.stage { + case .idle, .scanning, .pickFileForUpload: + landing + case .connecting(let message): + StatusCard(icon: "antenna.radiowaves.left.and.right", title: message) { + ProgressView() + Button("取消", role: .cancel) { model.cancel() } + } + case .running(let message): + StatusCard(icon: "arrow.left.arrow.right", title: message) { + if let progress = model.progress { + ProgressView(value: progress.fraction) + Text("\(progress.readableSize) · \(progress.readableRate)") + .font(.footnote.monospacedDigit()) + .foregroundStyle(.secondary) + } else { + ProgressView() + } + Button("取消", role: .cancel) { model.cancel() } + } + case .showingPeerCode(let pairing): + peerCode(pairing) + case .finished(let message, let url): + StatusCard(icon: "checkmark.circle.fill", title: message) { + if let url { + Text(url.lastPathComponent).font(.footnote).foregroundStyle(.secondary) + ShareLink(item: url) { Label("分享", systemImage: "square.and.arrow.up") } + } + Button("完成") { model.reset() }.buttonStyle(.borderedProminent) + } + case .failed(let message): + StatusCard(icon: "exclamationmark.triangle.fill", title: "传输失败") { + Text(message).font(.footnote).multilineTextAlignment(.center) + .foregroundStyle(.secondary) + Button("返回") { model.reset() }.buttonStyle(.borderedProminent) + } + } + } + + private var landing: some View { + List { + Section { + ActionRow(icon: "qrcode.viewfinder", title: "扫码", + detail: "扫电脑上的二维码收发文件,或扫另一台 iPhone 的码接收") { + model.beginScan() + } + ActionRow(icon: "iphone.gen3.radiowaves.left.and.right", title: "发给附近的 iPhone", + detail: "选文件后显示二维码,对方扫一下即可,无需连同一个 Wi-Fi") { + pickPurpose = .peerSend + } + } footer: { + Text("与电脑互传需要手机和电脑连在同一个 Wi-Fi。iPhone 之间使用点对点直连,不经过路由器。") + } + + if !model.receivedFiles.isEmpty { + Section("已接收") { + ForEach(model.receivedFiles, id: \.self) { url in + ShareLink(item: url) { + Label(url.lastPathComponent, systemImage: "doc") + .lineLimit(1) + } + } + } + } + } + } + + private func peerCode(_ pairing: PeerPairing) -> some View { + VStack(spacing: 20) { + Text("让对方用 QFT 扫这个码") + .font(.headline) + if let image = QRRenderer.image(from: pairing.encode()) { + Image(uiImage: image) + .interpolation(.none) + .resizable() + .scaledToFit() + .frame(maxWidth: 300) + .padding() + .background(.white) + .clipShape(RoundedRectangle(cornerRadius: 16)) + } + VStack(spacing: 4) { + Text(pairing.fileName).font(.subheadline).lineLimit(1) + Text(TransferProgress.readable(pairing.fileSize)) + .font(.footnote).foregroundStyle(.secondary) + } + if let progress = model.progress { + ProgressView(value: progress.fraction) + .padding(.horizontal, 40) + Text("\(progress.readableSize) · \(progress.readableRate)") + .font(.footnote.monospacedDigit()).foregroundStyle(.secondary) + } else { + Label("等待对方扫码…", systemImage: "hourglass") + .font(.footnote).foregroundStyle(.secondary) + } + Button("取消", role: .cancel) { model.cancel() } + } + .padding() + } +} + +private struct ActionRow: View { + let icon: String + let title: String + let detail: String + let action: () -> Void + + var body: some View { + Button(action: action) { + HStack(spacing: 14) { + Image(systemName: icon) + .font(.title2) + .frame(width: 34) + VStack(alignment: .leading, spacing: 3) { + Text(title).font(.body.weight(.medium)) + Text(detail).font(.caption).foregroundStyle(.secondary) + } + } + .padding(.vertical, 4) + } + .buttonStyle(.plain) + } +} + +private struct StatusCard: View { + let icon: String + let title: String + @ViewBuilder let content: Content + + var body: some View { + VStack(spacing: 18) { + Image(systemName: icon).font(.system(size: 44)) + Text(title).font(.headline).multilineTextAlignment(.center) + content + } + .padding(32) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } +} diff --git a/ios/QFT/App/QFTApp.swift b/ios/QFT/App/QFTApp.swift new file mode 100644 index 0000000..b4d405d --- /dev/null +++ b/ios/QFT/App/QFTApp.swift @@ -0,0 +1,10 @@ +import SwiftUI + +@main +struct QFTApp: App { + var body: some Scene { + WindowGroup { + HomeView() + } + } +} diff --git a/ios/QFT/App/ScannerView.swift b/ios/QFT/App/ScannerView.swift new file mode 100644 index 0000000..cd56856 --- /dev/null +++ b/ios/QFT/App/ScannerView.swift @@ -0,0 +1,137 @@ +import SwiftUI +import AVFoundation + +/// 二维码扫描。用 AVCaptureMetadataOutput 而不是 Vision: +/// 硬件解码路径延迟更低,而且这里只需要识别静态配对码, +/// 不需要 QFT2 光学链路那套 ROI 锁定与高频解码。 +struct ScannerView: UIViewControllerRepresentable { + + /// 只在识别到我们认识的前缀时回调,且只回调一次。 + let onFound: (String) -> Void + let onCancel: () -> Void + + func makeCoordinator() -> Coordinator { Coordinator(onFound: onFound) } + + func makeUIViewController(context: Context) -> ScannerController { + let controller = ScannerController() + controller.coordinator = context.coordinator + controller.onCancel = onCancel + return controller + } + + func updateUIViewController(_ controller: ScannerController, context: Context) {} + + final class Coordinator: NSObject, AVCaptureMetadataOutputObjectsDelegate { + private let onFound: (String) -> Void + private var consumed = false + + init(onFound: @escaping (String) -> Void) { self.onFound = onFound } + + func metadataOutput(_ output: AVCaptureMetadataOutput, + didOutput objects: [AVMetadataObject], + from connection: AVCaptureConnection) { + guard !consumed else { return } + for object in objects { + guard let readable = object as? AVMetadataMachineReadableCodeObject, + readable.type == .qr, let text = readable.stringValue else { continue } + guard PairingProtocol.isPairingText(text) || PeerPairing.isPeerText(text) else { continue } + consumed = true + UINotificationFeedbackGenerator().notificationOccurred(.success) + DispatchQueue.main.async { self.onFound(text) } + return + } + } + } +} + +final class ScannerController: UIViewController { + + var coordinator: ScannerView.Coordinator? + var onCancel: (() -> Void)? + + private let session = AVCaptureSession() + private var preview: AVCaptureVideoPreviewLayer? + private let hintLabel = UILabel() + + override func viewDidLoad() { + super.viewDidLoad() + view.backgroundColor = .black + configureSession() + configureOverlay() + } + + private func configureSession() { + guard let device = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back), + let input = try? AVCaptureDeviceInput(device: device), + session.canAddInput(input) else { + showFailure("无法打开相机") + return + } + session.addInput(input) + + let output = AVCaptureMetadataOutput() + guard session.canAddOutput(output) else { + showFailure("无法启动二维码识别") + return + } + session.addOutput(output) + output.setMetadataObjectsDelegate(coordinator, queue: .main) + output.metadataObjectTypes = [.qr] + + let layer = AVCaptureVideoPreviewLayer(session: session) + layer.videoGravity = .resizeAspectFill + layer.frame = view.bounds + view.layer.insertSublayer(layer, at: 0) + preview = layer + } + + private func configureOverlay() { + hintLabel.text = "对准电脑或另一台 iPhone 上的二维码" + hintLabel.textColor = .white + hintLabel.font = .systemFont(ofSize: 15, weight: .medium) + hintLabel.textAlignment = .center + hintLabel.numberOfLines = 0 + hintLabel.translatesAutoresizingMaskIntoConstraints = false + view.addSubview(hintLabel) + + let cancel = UIButton(type: .system) + cancel.setTitle("取消", for: .normal) + cancel.setTitleColor(.white, for: .normal) + cancel.titleLabel?.font = .systemFont(ofSize: 17, weight: .semibold) + cancel.addTarget(self, action: #selector(cancelTapped), for: .touchUpInside) + cancel.translatesAutoresizingMaskIntoConstraints = false + view.addSubview(cancel) + + NSLayoutConstraint.activate([ + hintLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 32), + hintLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -32), + hintLabel.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -96), + cancel.centerXAnchor.constraint(equalTo: view.centerXAnchor), + cancel.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -32), + ]) + } + + @objc private func cancelTapped() { onCancel?() } + + private func showFailure(_ message: String) { + hintLabel.text = message + } + + override func viewWillAppear(_ animated: Bool) { + super.viewWillAppear(animated) + guard !session.isRunning else { return } + // startRunning 会阻塞,必须离开主线程 + DispatchQueue.global(qos: .userInitiated).async { [session] in session.startRunning() } + } + + override func viewWillDisappear(_ animated: Bool) { + super.viewWillDisappear(animated) + guard session.isRunning else { return } + DispatchQueue.global(qos: .userInitiated).async { [session] in session.stopRunning() } + } + + override func viewDidLayoutSubviews() { + super.viewDidLayoutSubviews() + preview?.frame = view.bounds + } +} diff --git a/ios/QFT/App/TransferModel.swift b/ios/QFT/App/TransferModel.swift new file mode 100644 index 0000000..02ddb61 --- /dev/null +++ b/ios/QFT/App/TransferModel.swift @@ -0,0 +1,242 @@ +import SwiftUI +import CoreImage.CIFilterBuiltins + +@MainActor +final class TransferModel: ObservableObject { + + enum Stage: Equatable { + case idle + case scanning + /// 扫到 QFTPAIR2:需要用户挑一个文件传给电脑 + case pickFileForUpload(PairingPayload) + case connecting(String) + case running(String) + case showingPeerCode(PeerPairing) + case finished(String, URL?) + case failed(String) + } + + @Published private(set) var stage: Stage = .idle + @Published private(set) var progress: TransferProgress? + @Published private(set) var receivedFiles: [URL] = [] + + private var task: Task? + private var sender: PeerSender? + private var scopedURL: URL? + + private let deviceName = DeviceInfo.name + + // MARK: - 入口 + + func beginScan() { stage = .scanning } + + func cancel() { + task?.cancel() + task = nil + sender?.stop() + sender = nil + releaseScope() + progress = nil + stage = .idle + } + + func reset() { + progress = nil + stage = .idle + refreshReceivedFiles() + } + + /// 扫到码之后的统一分发 + func handleScanned(_ text: String) { + if let peer = PeerPairing.parse(text) { + startPeerReceive(peer) + return + } + guard let pairing = PairingProtocol.parse(text) else { + stage = .failed("这不是 QFT 的二维码,或二维码里的地址不是局域网地址。") + return + } + switch pairing.direction { + case .downloadToPhone: startDownload(pairing) + case .uploadToPC: stage = .pickFileForUpload(pairing) + } + } + + // MARK: - 电脑 → 手机 + + private func startDownload(_ pairing: PairingPayload) { + stage = .connecting("正在找 \(pairing.pcName)…") + task = Task { + do { + let host = try await HostDiscovery(pairing: pairing, deviceName: deviceName).locate() + guard !Task.isCancelled else { return } + stage = .running("正在从 \(pairing.pcName) 接收 \(pairing.fileName ?? "文件")") + let client = DownloadClient(host: host, pairing: pairing, deviceName: deviceName) + let saved = try await client.run { [weak self] value in + Task { @MainActor in self?.progress = value } + } + finish("已保存到「文件」App 的 QFT 文件夹", saved) + } catch { + fail(error) + } + } + } + + // MARK: - 手机 → 电脑 + + func startUpload(_ pairing: PairingPayload, fileURL: URL) { + guard claimScope(fileURL) else { + stage = .failed("没有权限读取这个文件,请换一个位置再试。") + return + } + stage = .connecting("正在找 \(pairing.pcName)…") + task = Task { + defer { releaseScope() } + do { + let host = try await HostDiscovery(pairing: pairing, deviceName: deviceName).locate() + guard !Task.isCancelled else { return } + stage = .running("正在发送 \(fileURL.lastPathComponent) 到 \(pairing.pcName)") + let client = UploadClient(host: host, pairing: pairing, deviceName: deviceName) + _ = try await client.run(fileURL: fileURL) { [weak self] value in + Task { @MainActor in self?.progress = value } + } + finish("已发送到 \(pairing.pcName)", nil) + } catch { + fail(error) + } + } + } + + // MARK: - iPhone ↔ iPhone(隔空投送式) + + func startPeerSend(fileURL: URL) { + guard claimScope(fileURL) else { + stage = .failed("没有权限读取这个文件,请换一个位置再试。") + return + } + stage = .connecting("正在准备…") + task = Task { + defer { releaseScope() } + do { + let sender = PeerSender(fileURL: fileURL, deviceName: deviceName) + // start() 里要完整读一遍文件算摘要,别卡住主线程 + let pairing = try await Task.detached { try sender.start() }.value + guard !Task.isCancelled else { sender.stop(); return } + self.sender = sender + stage = .showingPeerCode(pairing) + try await sender.waitAndSend { [weak self] value in + Task { @MainActor in self?.progress = value } + } + finish("已发送给对方", nil) + } catch { + fail(error) + } + sender?.stop() + sender = nil + } + } + + private func startPeerReceive(_ pairing: PeerPairing) { + stage = .connecting("正在连接 \(pairing.senderName)…") + task = Task { + do { + let directory = try DownloadClient.defaultDestinationDirectory() + let receiver = PeerReceiver(pairing: pairing, destinationDirectory: directory) + stage = .running("正在接收 \(pairing.fileName)") + let saved = try await receiver.run { [weak self] value in + Task { @MainActor in self?.progress = value } + } + finish("已保存到「文件」App 的 QFT 文件夹", saved) + } catch { + fail(error) + } + } + } + + // MARK: - 收尾 + + private func finish(_ message: String, _ url: URL?) { + progress = nil + stage = .finished(message, url) + refreshReceivedFiles() + } + + private func fail(_ error: Error) { + guard !(error is CancellationError) else { return } + progress = nil + stage = .failed(error.localizedDescription) + } + + func refreshReceivedFiles() { + guard let directory = try? DownloadClient.defaultDestinationDirectory(), + let entries = try? FileManager.default.contentsOfDirectory( + at: directory, includingPropertiesForKeys: [.contentModificationDateKey]) else { + receivedFiles = [] + return + } + receivedFiles = entries + .filter { $0.pathExtension != "qftpart" } + .sorted { lhs, rhs in + let l = (try? lhs.resourceValues(forKeys: [.contentModificationDateKey]))? + .contentModificationDate ?? .distantPast + let r = (try? rhs.resourceValues(forKeys: [.contentModificationDateKey]))? + .contentModificationDate ?? .distantPast + return l > r + } + } + + // MARK: - 安全作用域 + + /// 文件选择器给的 URL 属于其他进程的沙盒,读之前必须声明作用域, + /// 而且整个传输期间都要持有。 + private func claimScope(_ url: URL) -> Bool { + releaseScope() + guard url.startAccessingSecurityScopedResource() else { return false } + scopedURL = url + return true + } + + private func releaseScope() { + scopedURL?.stopAccessingSecurityScopedResource() + scopedURL = nil + } +} + +// MARK: - 二维码渲染 + +enum QRRenderer { + /// 配对码只有几百字节,用 M 级纠错换取更好的首次识别率。 + static func image(from text: String) -> UIImage? { + let filter = CIFilter.qrCodeGenerator() + filter.message = Data(text.utf8) + filter.correctionLevel = "M" + guard let output = filter.outputImage else { return nil } + // 放大用最近邻,避免插值把模块边缘糊掉 + let scaled = output.transformed(by: CGAffineTransform(scaleX: 12, y: 12)) + let context = CIContext() + guard let cgImage = context.createCGImage(scaled, from: scaled.extent) else { return nil } + return UIImage(cgImage: cgImage) + } +} + +extension TransferProgress { + var readableRate: String { + let units = ["B/s", "KB/s", "MB/s", "GB/s"] + var value = bytesPerSecond + var index = 0 + while value >= 1024, index < units.count - 1 { value /= 1024; index += 1 } + return String(format: "%.1f %@", value, units[index]) + } + + var readableSize: String { + Self.readable(completed) + " / " + Self.readable(total) + } + + static func readable(_ bytes: UInt64) -> String { + let units = ["B", "KB", "MB", "GB"] + var value = Double(bytes) + var index = 0 + while value >= 1024, index < units.count - 1 { value /= 1024; index += 1 } + return String(format: index == 0 ? "%.0f %@" : "%.1f %@", value, units[index]) + } +} diff --git a/ios/QFT/Assets.xcassets/AccentColor.colorset/Contents.json b/ios/QFT/Assets.xcassets/AccentColor.colorset/Contents.json new file mode 100644 index 0000000..3be300b --- /dev/null +++ b/ios/QFT/Assets.xcassets/AccentColor.colorset/Contents.json @@ -0,0 +1,4 @@ +{ + "colors" : [ { "idiom" : "universal" } ], + "info" : { "author" : "xcode", "version" : 1 } +} diff --git a/ios/QFT/Assets.xcassets/AppIcon.appiconset/Contents.json b/ios/QFT/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..07942c2 --- /dev/null +++ b/ios/QFT/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,6 @@ +{ + "images" : [ + { "idiom" : "universal", "platform" : "ios", "size" : "1024x1024" } + ], + "info" : { "author" : "xcode", "version" : 1 } +} diff --git a/ios/QFT/Assets.xcassets/Contents.json b/ios/QFT/Assets.xcassets/Contents.json new file mode 100644 index 0000000..d8b757a --- /dev/null +++ b/ios/QFT/Assets.xcassets/Contents.json @@ -0,0 +1,3 @@ +{ + "info" : { "author" : "xcode", "version" : 1 } +} diff --git a/ios/QFT/Core/Base64URL.swift b/ios/QFT/Core/Base64URL.swift new file mode 100644 index 0000000..480b526 --- /dev/null +++ b/ios/QFT/Core/Base64URL.swift @@ -0,0 +1,46 @@ +import Foundation + +/// RFC 4648 §5 的 URL-safe Base64,无填充。 +/// Windows 端用 `URL_SAFE_NO_PAD` 编码设备名、文件名与配对载荷, +/// Android 端对应 `Base64Url`,三端必须逐字节一致。 +enum Base64URL { + + static func encode(_ data: Data) -> String { + var text = data.base64EncodedString() + text = text.replacingOccurrences(of: "+", with: "-") + text = text.replacingOccurrences(of: "/", with: "_") + while text.hasSuffix("=") { text.removeLast() } + return text + } + + static func encode(_ text: String) -> String { + encode(Data(text.utf8)) + } + + static func decode(_ text: String) -> Data? { + // 只接受合法字母表,避免把任意输入喂给 Data(base64Encoded:) + // 后得到一个「解出来了但不是原意」的结果。 + guard !text.isEmpty else { return Data() } + for scalar in text.unicodeScalars { + switch scalar { + case "A"..."Z", "a"..."z", "0"..."9", "-", "_": + continue + default: + return nil + } + } + var padded = text.replacingOccurrences(of: "-", with: "+") + padded = padded.replacingOccurrences(of: "_", with: "/") + let remainder = padded.count % 4 + if remainder == 1 { return nil } // 不可能出现的长度 + if remainder != 0 { + padded.append(String(repeating: "=", count: 4 - remainder)) + } + return Data(base64Encoded: padded) + } + + static func decodeString(_ text: String) -> String? { + guard let data = decode(text) else { return nil } + return String(data: data, encoding: .utf8) + } +} diff --git a/ios/QFT/Core/DownloadClient.swift b/ios/QFT/Core/DownloadClient.swift new file mode 100644 index 0000000..2a25e9b --- /dev/null +++ b/ios/QFT/Core/DownloadClient.swift @@ -0,0 +1,210 @@ +import Foundation +import CryptoKit + +struct TransferProgress { + let completed: UInt64 + let total: UInt64 + let bytesPerSecond: Double + + var fraction: Double { + total == 0 ? 1 : min(1, Double(completed) / Double(total)) + } +} + +/// 电脑 → 手机下载(QFTSEND2)。 +/// +/// 边收边写盘、边算 SHA-256,中断后用 `Range: bytes=N-` 续传。 +/// Windows 端 `sender.rs` 只支持单段 Range,这里也只发单段。 +final class DownloadClient: NSObject { + + private let host: QFTHost + private let pairing: PairingPayload + private let deviceName: String + /// 落盘目录。默认 Documents/QFT(会出现在「文件」App 里); + /// 测试注入临时目录,避免碰到用户真实的文档目录。 + private let destinationDirectory: URL? + + private var fileHandle: FileHandle? + private var hasher = SHA256() + private var written: UInt64 = 0 + private var expectedTotal: UInt64 = 0 + private var startedAt = Date() + private var lastReport = Date.distantPast + private var onProgress: ((TransferProgress) -> Void)? + private var continuation: CheckedContinuation? + private var session: URLSession? + + init(host: QFTHost, pairing: PairingPayload, deviceName: String, + destinationDirectory: URL? = nil) { + self.host = host + self.pairing = pairing + self.deviceName = deviceName + self.destinationDirectory = destinationDirectory + super.init() + } + + /// 下载到目标目录,返回最终文件 URL。 + func run(onProgress: @escaping (TransferProgress) -> Void) async throws -> URL { + let name = pairing.fileName ?? "qft-download.bin" + let directory = try destinationDirectory ?? Self.defaultDestinationDirectory() + let partURL = directory.appendingPathComponent(name + ".qftpart") + + // 续传:已经落盘多少就从多少开始要 + var resumeFrom: UInt64 = 0 + if let attributes = try? FileManager.default.attributesOfItem(atPath: partURL.path), + let size = attributes[.size] as? NSNumber { + resumeFrom = UInt64(truncating: size) + } + if resumeFrom > 0, let declared = pairing.fileSize, resumeFrom >= declared { + // 断点比声明的文件还大,说明这个 .qftpart 不是本次会话的,丢弃重来 + try? FileManager.default.removeItem(at: partURL) + resumeFrom = 0 + } + if resumeFrom > 0 { + // 续传时无法复用之前的哈希中间态,重新扫一遍已落盘的部分 + hasher = SHA256() + let handle = try FileHandle(forReadingFrom: partURL) + defer { try? handle.close() } + while let block = try handle.read(upToCount: 4 * 1024 * 1024), !block.isEmpty { + hasher.update(data: block) + } + } else { + FileManager.default.createFile(atPath: partURL.path, contents: nil) + } + + self.written = resumeFrom + self.expectedTotal = pairing.fileSize ?? 0 + self.onProgress = onProgress + self.startedAt = Date() + self.fileHandle = try FileHandle(forWritingTo: partURL) + try fileHandle?.seekToEnd() + + guard let url = URL(string: host.baseURL + "/qft/download") else { + throw QFTError.malformedResponse("下载地址无效") + } + var request = URLRequest(url: url) + request.httpMethod = "GET" + request.timeoutInterval = 30 + request.setValue(pairing.session, forHTTPHeaderField: "X-QFT-Token") + request.setValue(Base64URL.encode(deviceName), forHTTPHeaderField: "X-QFT-Device") + if resumeFrom > 0 { + request.setValue("bytes=\(resumeFrom)-", forHTTPHeaderField: "Range") + } + + let configuration = URLSessionConfiguration.ephemeral + configuration.timeoutIntervalForRequest = 30 + configuration.timeoutIntervalForResource = 3600 + let urlSession = URLSession(configuration: configuration, delegate: self, delegateQueue: nil) + self.session = urlSession + defer { + try? fileHandle?.close() + fileHandle = nil + urlSession.invalidateAndCancel() + session = nil + } + + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + self.continuation = continuation + urlSession.dataTask(with: request).resume() + } + + if let declared = pairing.fileSize, written != declared { + throw QFTError.integrity("收到 \(written) 字节,电脑声明 \(declared) 字节") + } + if let expected = pairing.sha256 { + let actual = hasher.finalize().map { String(format: "%02x", $0) }.joined() + guard actual == expected else { + try? FileManager.default.removeItem(at: partURL) + throw QFTError.integrity("SHA-256 不匹配,文件已丢弃") + } + } + + let finalURL = Self.uniqueURL(in: directory, name: name) + try FileManager.default.moveItem(at: partURL, to: finalURL) + return finalURL + } + + // MARK: - 落盘目录 + + static func defaultDestinationDirectory() throws -> URL { + let documents = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, + appropriateFor: nil, create: true) + let directory = documents.appendingPathComponent("QFT", isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + return directory + } + + static func uniqueURL(in directory: URL, name: String) -> URL { + var candidate = directory.appendingPathComponent(name) + guard FileManager.default.fileExists(atPath: candidate.path) else { return candidate } + let stem = (name as NSString).deletingPathExtension + let ext = (name as NSString).pathExtension + var index = 1 + while FileManager.default.fileExists(atPath: candidate.path) { + let suffix = ext.isEmpty ? "\(stem) (\(index))" : "\(stem) (\(index)).\(ext)" + candidate = directory.appendingPathComponent(suffix) + index += 1 + } + return candidate + } +} + +extension DownloadClient: URLSessionDataDelegate { + + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, + didReceive response: URLResponse, + completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { + guard let http = response as? HTTPURLResponse else { + finish(with: QFTError.malformedResponse("非 HTTP 响应")) + completionHandler(.cancel) + return + } + guard http.statusCode == 200 || http.statusCode == 206 else { + finish(with: QFTError.httpStatus(http.statusCode, http.statusCode == 403 ? "会话已失效,请让电脑重新生成二维码" : "")) + completionHandler(.cancel) + return + } + if expectedTotal == 0 { + let length = http.expectedContentLength + if length > 0 { expectedTotal = written + UInt64(length) } + } + completionHandler(.allow) + } + + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + do { + try fileHandle?.write(contentsOf: data) + } catch { + finish(with: error) + dataTask.cancel() + return + } + hasher.update(data: data) + written &+= UInt64(data.count) + report() + } + + func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + if let error, (error as NSError).code != NSURLErrorCancelled { + finish(with: error) + } else { + report(force: true) + finish(with: nil) + } + } + + private func report(force: Bool = false) { + let now = Date() + guard force || now.timeIntervalSince(lastReport) > 0.1 else { return } + lastReport = now + let elapsed = max(0.001, now.timeIntervalSince(startedAt)) + onProgress?(TransferProgress(completed: written, total: expectedTotal, + bytesPerSecond: Double(written) / elapsed)) + } + + private func finish(with error: Error?) { + guard let continuation else { return } + self.continuation = nil + if let error { continuation.resume(throwing: error) } else { continuation.resume() } + } +} diff --git a/ios/QFT/Core/HostDiscovery.swift b/ios/QFT/Core/HostDiscovery.swift new file mode 100644 index 0000000..be908d8 --- /dev/null +++ b/ios/QFT/Core/HostDiscovery.swift @@ -0,0 +1,271 @@ +import Foundation + +#if canImport(UIKit) +import UIKit +#endif + +enum DeviceInfo { + static var name: String { + #if canImport(UIKit) + let raw = UIDevice.current.name + #else + let raw = Host.current().localizedName ?? "iPhone" + #endif + let cleaned = raw.filter { !$0.isNewline } + return cleaned.isEmpty ? "iPhone" : String(cleaned.prefix(64)) + } +} + +struct QFTHost: Equatable { + let baseURL: String // 形如 http://192.168.1.20:39393 +} + +enum QFTError: LocalizedError { + case hostNotFound + case httpStatus(Int, String) + case malformedResponse(String) + case integrity(String) + case cancelled + + var errorDescription: String? { + switch self { + case .hostNotFound: + return "找不到电脑。请确认手机和电脑连在同一个 Wi-Fi,并且电脑上的 QFT 正在等待连接。" + case .httpStatus(let code, let detail): + return "电脑返回 HTTP \(code)\(detail.isEmpty ? "" : ":\(detail)")" + case .malformedResponse(let detail): + return "电脑返回的数据无法解析:\(detail)" + case .integrity(let detail): + return "校验失败:\(detail)" + case .cancelled: + return "已取消" + } + } +} + +/// 在局域网里定位 Windows 端。 +/// +/// 顺序:二维码自带的 endpoint → UDP QFTDISC2 广播 → 当前子网有界扫描。 +/// 与 Android 端同一套策略,但去掉了 Direct-AP 相关的分支:iOS 连不上指定 AP。 +struct HostDiscovery { + + let pairing: PairingPayload + let deviceName: String + + static let discoveryPort: UInt16 = 39392 + + func locate() async throws -> QFTHost { + if let host = await probe(pairing.endpoints, timeout: 1.2) { + return host + } + if let hinted = await udpDiscover(timeout: 1.5), + let host = await probe([hinted], timeout: 1.5) { + return host + } + let candidates = LocalNetwork.subnetCandidates(port: pairing.port, limit: 254) + if !candidates.isEmpty, let host = await probe(candidates, timeout: 0.7) { + return host + } + throw QFTError.hostNotFound + } + + /// 并发 ping 全部候选,返回第一个应答的。 + func probe(_ endpoints: [String], timeout: TimeInterval) async -> QFTHost? { + guard !endpoints.isEmpty else { return nil } + return await withTaskGroup(of: QFTHost?.self) { group in + for endpoint in endpoints { + group.addTask { await Self.ping(endpoint, session: pairing.session, + deviceName: deviceName, timeout: timeout) } + } + for await result in group { + if let result { + group.cancelAll() + return result + } + } + return nil + } + } + + static func ping(_ baseURL: String, session: String, + deviceName: String, timeout: TimeInterval) async -> QFTHost? { + guard let url = URL(string: baseURL + "/qft/ping") else { return nil } + var request = URLRequest(url: url) + request.httpMethod = "GET" + request.timeoutInterval = timeout + request.setValue(session, forHTTPHeaderField: "X-QFT-Token") + request.setValue(Base64URL.encode(deviceName), forHTTPHeaderField: "X-QFT-Device") + + let configuration = URLSessionConfiguration.ephemeral + configuration.timeoutIntervalForRequest = timeout + configuration.waitsForConnectivity = false + let urlSession = URLSession(configuration: configuration) + defer { urlSession.finishTasksAndInvalidate() } + + guard let (data, response) = try? await urlSession.data(for: request), + let http = response as? HTTPURLResponse, http.statusCode == 200, + let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any], + (object["ok"] as? Bool) == true else { return nil } + return QFTHost(baseURL: baseURL) + } + + /// 向广播地址发 `QFTDISC2:`,等待 `QFTHERE2::`。 + /// 返回可用的 base URL;iOS 首次调用会触发「本地网络」权限弹窗。 + func udpDiscover(timeout: TimeInterval) async -> String? { + let expected = "QFTHERE2:\(pairing.session):" + let request = Data("QFTDISC2:\(pairing.session)".utf8) + + return await withCheckedContinuation { continuation in + DispatchQueue.global(qos: .userInitiated).async { + let result = Self.udpRoundTrip(request: request, + expectedPrefix: expected, + timeout: timeout) + continuation.resume(returning: result) + } + } + } + + private static func udpRoundTrip(request: Data, expectedPrefix: String, + timeout: TimeInterval) -> String? { + let fd = socket(AF_INET, SOCK_DGRAM, 0) + guard fd >= 0 else { return nil } + defer { close(fd) } + + var enable: Int32 = 1 + setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &enable, socklen_t(MemoryLayout.size)) + var tv = timeval(tv_sec: Int(timeout), tv_usec: Int32((timeout - floor(timeout)) * 1_000_000)) + setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, socklen_t(MemoryLayout.size)) + + var targets = ["255.255.255.255"] + if let broadcast = LocalNetwork.subnetBroadcastAddress() { targets.insert(broadcast, at: 0) } + + for target in targets { + var address = sockaddr_in() + address.sin_family = sa_family_t(AF_INET) + address.sin_port = discoveryPort.bigEndian + address.sin_addr.s_addr = inet_addr(target) + let sent = request.withUnsafeBytes { buffer -> Int in + withUnsafePointer(to: &address) { pointer in + pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { sockPointer in + sendto(fd, buffer.baseAddress, buffer.count, 0, + sockPointer, socklen_t(MemoryLayout.size)) + } + } + } + if sent < 0 { continue } + } + + let deadline = Date().addingTimeInterval(timeout) + var buffer = [UInt8](repeating: 0, count: 512) + while Date() < deadline { + var from = sockaddr_in() + var fromLength = socklen_t(MemoryLayout.size) + let received = withUnsafeMutablePointer(to: &from) { pointer -> Int in + pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { sockPointer in + recvfrom(fd, &buffer, buffer.count, 0, sockPointer, &fromLength) + } + } + if received <= 0 { break } + guard let text = String(bytes: buffer[0.. [Interface] { + var head: UnsafeMutablePointer? + guard getifaddrs(&head) == 0, let first = head else { return [] } + defer { freeifaddrs(head) } + + var result: [Interface] = [] + var cursor: UnsafeMutablePointer? = first + while let entry = cursor { + defer { cursor = entry.pointee.ifa_next } + guard let rawAddress = entry.pointee.ifa_addr, + rawAddress.pointee.sa_family == UInt8(AF_INET) else { continue } + let flags = Int32(entry.pointee.ifa_flags) + guard flags & IFF_UP != 0, flags & IFF_LOOPBACK == 0 else { continue } + + guard let address = describe(rawAddress), + let maskPointer = entry.pointee.ifa_netmask, + let netmask = describe(maskPointer) else { continue } + guard PairingProtocol.isPrivateIPv4(address) else { continue } + result.append(Interface(name: String(cString: entry.pointee.ifa_name), + address: address, netmask: netmask)) + } + // en0 是 iPhone 的 Wi-Fi 接口,优先于蜂窝/热点接口 + return result.sorted { lhs, _ in lhs.name == "en0" } + } + + private static func describe(_ address: UnsafeMutablePointer) -> String? { + var host = [CChar](repeating: 0, count: Int(NI_MAXHOST)) + let length = socklen_t(MemoryLayout.size) + guard getnameinfo(address, length, &host, socklen_t(host.count), + nil, 0, NI_NUMERICHOST) == 0 else { return nil } + return String(cString: host) + } + + static func subnetBroadcastAddress() -> String? { + guard let iface = activeInterfaces().first, + let ip = ipv4(iface.address), let mask = ipv4(iface.netmask) else { return nil } + return format(ip | ~mask) + } + + /// 当前子网内的候选地址。仅在 /24 或更小的子网上启用, + /// 避免在大网段里做无意义的上千次探测。 + static func subnetCandidates(port: Int, limit: Int) -> [String] { + guard let iface = activeInterfaces().first, + let ip = ipv4(iface.address), let mask = ipv4(iface.netmask) else { return [] } + let hostBits = (~mask).nonzeroBitCount + guard hostBits > 0, hostBits <= 8 else { return [] } + + let network = ip & mask + let broadcast = ip | ~mask + var result: [String] = [] + var candidate = network &+ 1 + while candidate < broadcast && result.count < limit { + if candidate != ip { result.append("http://\(format(candidate)):\(port)") } + candidate &+= 1 + } + // 网关通常是 .1,多半就是那台开热点/路由的机器,放最前面 + if let gatewayIndex = result.firstIndex(of: "http://\(format(network &+ 1)):\(port)") { + result.swapAt(0, gatewayIndex) + } + return result + } + + static func ipv4(_ text: String) -> UInt32? { + let parts = text.split(separator: ".", omittingEmptySubsequences: false) + guard parts.count == 4 else { return nil } + var value: UInt32 = 0 + for part in parts { + guard let octet = UInt32(part), octet <= 255 else { return nil } + value = (value << 8) | octet + } + return value + } + + static func format(_ value: UInt32) -> String { + "\((value >> 24) & 0xff).\((value >> 16) & 0xff).\((value >> 8) & 0xff).\(value & 0xff)" + } +} diff --git a/ios/QFT/Core/PairingProtocol.swift b/ios/QFT/Core/PairingProtocol.swift new file mode 100644 index 0000000..56d36ea --- /dev/null +++ b/ios/QFT/Core/PairingProtocol.swift @@ -0,0 +1,188 @@ +import Foundation + +enum TransferDirection: String { + case uploadToPC = "u" // QFTPAIR2:手机把文件传给电脑 + case downloadToPhone = "d" // QFTSEND2:电脑已选好文件,手机扫码后下载 +} + +struct WifiCredentials: Equatable { + let ssid: String + let passphrase: String +} + +struct PairingPayload: Equatable { + let version: Int + let session: String + let pcName: String + let port: Int + let endpoints: [String] + let wifi: WifiCredentials? + let direction: TransferDirection + let fileName: String? + let fileSize: UInt64? + let sha256: String? +} + +/// QFTPAIR2 / QFTSEND2 配对二维码解析。 +/// +/// 二维码是**不可信输入**:它决定了 App 接下来去连哪个地址。因此这里只接受 +/// 字面量私有 IPv4 + 二维码自称的端口,任何域名、公网地址、带 query/fragment +/// 的 URL 一律拒绝——与 Windows/Android 两端的校验保持一致。 +enum PairingProtocol { + + static let prefixUpload = "QFTPAIR2:" + static let prefixDownload = "QFTSEND2:" + + static func isPairingText(_ text: String) -> Bool { + text.hasPrefix(prefixUpload) || text.hasPrefix(prefixDownload) + } + + static func parse(_ text: String) -> PairingPayload? { + guard text.count <= 4096 else { return nil } + if text.hasPrefix(prefixUpload) { + return parseV2(String(text.dropFirst(prefixUpload.count)), expected: .uploadToPC) + } + if text.hasPrefix(prefixDownload) { + return parseV2(String(text.dropFirst(prefixDownload.count)), expected: .downloadToPhone) + } + return nil + } + + private static func parseV2(_ encoded: String, expected: TransferDirection) -> PairingPayload? { + guard let data = Base64URL.decode(encoded), data.count <= 2048 else { return nil } + guard let root = try? JSONSerialization.jsonObject(with: data), + let object = root as? [String: Any] else { return nil } + guard (object["v"] as? Int) == 2 else { return nil } + + // 缺省为 "u",与 Windows 端「上传 QR 不写 d 字段」的编码方式对应 + let rawDirection = (object["d"] as? String) ?? "u" + guard let direction = TransferDirection(rawValue: rawDirection), + direction == expected else { return nil } + + guard let session = object["s"] as? String, isValidSession(session) else { return nil } + guard let port = object["p"] as? Int, (1...65535).contains(port) else { return nil } + + var wifi: WifiCredentials? + if let array = object["w"] as? [Any], array.count >= 2, + let ssid = array[0] as? String, let passphrase = array[1] as? String { + guard isValidWifi(ssid: ssid, passphrase: passphrase) else { return nil } + wifi = WifiCredentials(ssid: ssid, passphrase: passphrase) + } + + var endpoints: [String] = [] + if let array = object["e"] as? [Any] { + for item in array { + guard let raw = item as? String else { continue } + var value = raw.trimmingCharacters(in: .whitespaces) + while value.hasSuffix("/") { value.removeLast() } + if isAllowedLocalHTTPEndpoint(value, expectedPort: port), !endpoints.contains(value) { + endpoints.append(value) + } + } + } + // iOS 无法用代码加入指定 Wi-Fi(NEHotspotConfiguration 需要付费账号的 + // entitlement),所以 Direct-AP 二维码在本端必须自带可用 endpoint。 + if endpoints.isEmpty { return nil } + + var fileName: String? + var fileSize: UInt64? + var sha256: String? + if direction == .downloadToPhone { + guard let name = (object["f"] as? String)?.trimmingCharacters(in: .whitespaces), + isValidFileName(name) else { return nil } + guard let size = object["z"] as? NSNumber, size.int64Value >= 0 else { return nil } + guard let hash = (object["h"] as? String)?.lowercased(), isValidSHA256(hash) else { return nil } + fileName = name + fileSize = UInt64(size.int64Value) + sha256 = hash + } + + let pcName = String(((object["n"] as? String) ?? "Windows-PC").prefix(80)) + return PairingPayload( + version: 2, + session: session, + pcName: pcName, + port: port, + endpoints: endpoints, + wifi: wifi, + direction: direction, + fileName: fileName, + fileSize: fileSize, + sha256: sha256 + ) + } + + // MARK: - 校验 + + static func isValidSession(_ value: String) -> Bool { + guard (20...64).contains(value.count) else { return false } + for scalar in value.unicodeScalars { + switch scalar { + case "A"..."Z", "a"..."z", "0"..."9", "-", "_": continue + default: return false + } + } + return true + } + + static func isValidWifi(ssid: String, passphrase: String) -> Bool { + !ssid.trimmingCharacters(in: .whitespaces).isEmpty + && Data(ssid.utf8).count <= 32 + && (8...63).contains(passphrase.count) + } + + static func isValidFileName(_ value: String) -> Bool { + guard !value.isEmpty, value.count <= 180 else { return false } + let forbidden: Set = ["\\", "/", ":", "*", "?", "\"", "<", ">", "|"] + for scalar in value.unicodeScalars { + if scalar.value <= 31 || scalar.value == 127 { return false } + if forbidden.contains(scalar) { return false } + } + return true + } + + static func isValidSHA256(_ value: String) -> Bool { + guard value.count == 64 else { return false } + for scalar in value.unicodeScalars { + switch scalar { + case "0"..."9", "a"..."f": continue + default: return false + } + } + return true + } + + /// 只允许 `http://<私有 IPv4 字面量>:<期望端口>`。 + /// 故意不使用 URL/URLComponents 的宽松解析:它会接受域名、IPv6、 + /// 带凭据的 URL 等本协议不该出现的形态。 + static func isAllowedLocalHTTPEndpoint(_ value: String, expectedPort: Int) -> Bool { + guard value.hasPrefix("http://") else { return false } + let rest = String(value.dropFirst("http://".count)) + guard !rest.contains("@"), !rest.contains("?"), !rest.contains("#"), + !rest.contains("/") else { return false } + let parts = rest.split(separator: ":", omittingEmptySubsequences: false) + guard parts.count == 2, let port = Int(parts[1]), port == expectedPort else { return false } + return isPrivateIPv4(String(parts[0])) + } + + static func isPrivateIPv4(_ host: String) -> Bool { + let octets = host.split(separator: ".", omittingEmptySubsequences: false) + guard octets.count == 4 else { return false } + var values: [Int] = [] + for octet in octets { + // 拒绝 "01"、"+1"、空段这类非规范写法 + guard !octet.isEmpty, octet.count <= 3, octet.allSatisfy({ $0.isASCII && $0.isNumber }), + let value = Int(octet), (0...255).contains(value), + octet.count == 1 || !octet.hasPrefix("0") else { return false } + values.append(value) + } + switch (values[0], values[1]) { + case (10, _): return true + case (127, _): return true + case (169, 254): return true + case (172, 16...31): return true + case (192, 168): return true + default: return false + } + } +} diff --git a/ios/QFT/Core/PeerLink.swift b/ios/QFT/Core/PeerLink.swift new file mode 100644 index 0000000..39735bd --- /dev/null +++ b/ios/QFT/Core/PeerLink.swift @@ -0,0 +1,469 @@ +import Foundation +import Network +import CryptoKit + +/// 点对点链路:Bonjour 发现 + TLS-PSK 加密 + 长度前缀分帧。 +/// +/// `includePeerToPeer = true` 让 Network.framework 在没有路由器时 +/// 自动使用 BLE 发现 + AWDL 点对点 Wi-Fi,也就是 AirDrop 用的同一条链路。 +/// 两台设备在同一个 Wi-Fi 下时它会优先走基础网络,速度同样很快。 +/// +/// AWDL 是苹果私有链路,Windows 无法参与——PC 方向仍走 HTTP 局域网路径。 +enum PeerLink { + + static let frameHeaderSize = 5 // 1 字节类型 + 4 字节 BE 长度 + static let chunkSize = 256 * 1024 + static let maxFrameSize = 4 * 1024 * 1024 + + enum FrameType: UInt8 { + case manifest = 1 + case data = 2 + case eof = 3 + case result = 4 + } + + enum PeerError: LocalizedError { + case handshake(String) + case protocolViolation(String) + case rejected(String) + case timeout + + var errorDescription: String? { + switch self { + case .handshake(let detail): return "建立加密连接失败:\(detail)" + case .protocolViolation(let detail): return "对方发来的数据不符合协议:\(detail)" + case .rejected(let detail): return "对方拒绝了传输:\(detail)" + case .timeout: return "等待对方超时" + } + } + } + + /// TLS-PSK 参数。密钥来自二维码,因此不需要任何证书体系, + /// 且扫码这个动作本身就完成了双向认证——中间人拿不到密钥就握不了手。 + static func parameters(key: Data, identity: String) -> NWParameters { + let tls = NWProtocolTLS.Options() + let keyData = key.withUnsafeBytes { DispatchData(bytes: $0) } + let identityData = Data(identity.utf8).withUnsafeBytes { DispatchData(bytes: $0) } + + sec_protocol_options_add_pre_shared_key( + tls.securityProtocolOptions, + keyData as __DispatchData, + identityData as __DispatchData) + if let suite = tls_ciphersuite_t(rawValue: UInt16(TLS_PSK_WITH_AES_128_GCM_SHA256)) { + sec_protocol_options_append_tls_ciphersuite(tls.securityProtocolOptions, suite) + } + + let tcp = NWProtocolTCP.Options() + tcp.noDelay = true + // 传输是一次性的,对端消失时不要长时间挂着 + tcp.connectionTimeout = 10 + tcp.enableKeepalive = true + tcp.keepaliveIdle = 5 + + let parameters = NWParameters(tls: tls, tcp: tcp) + parameters.includePeerToPeer = true + return parameters + } + + // MARK: - 分帧收发 + + static func send(_ connection: NWConnection, type: FrameType, payload: Data) async throws { + var header = Data([type.rawValue]) + var length = UInt32(payload.count).bigEndian + withUnsafeBytes(of: &length) { header.append(contentsOf: $0) } + + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + connection.send(content: header + payload, + completion: .contentProcessed { error in + if let error { continuation.resume(throwing: error) } else { continuation.resume() } + }) + } + } + + static func receiveFrame(_ connection: NWConnection) async throws -> (FrameType, Data) { + let header = try await receiveExactly(connection, count: frameHeaderSize) + guard let type = FrameType(rawValue: header[header.startIndex]) else { + throw PeerError.protocolViolation("未知帧类型 \(header[header.startIndex])") + } + let length = header[(header.startIndex + 1)...].withUnsafeBytes { + UInt32(bigEndian: $0.loadUnaligned(as: UInt32.self)) + } + guard length <= UInt32(maxFrameSize) else { + throw PeerError.protocolViolation("帧长度 \(length) 超出上限") + } + if length == 0 { return (type, Data()) } + return (type, try await receiveExactly(connection, count: Int(length))) + } + + static func receiveExactly(_ connection: NWConnection, count: Int) async throws -> Data { + var buffer = Data() + buffer.reserveCapacity(count) + while buffer.count < count { + let remaining = count - buffer.count + let block = try await withCheckedThrowingContinuation { + (continuation: CheckedContinuation) in + connection.receive(minimumIncompleteLength: 1, maximumLength: remaining) { + content, _, isComplete, error in + if let error { continuation.resume(throwing: error); return } + if let content, !content.isEmpty { continuation.resume(returning: content); return } + if isComplete { + continuation.resume(throwing: PeerError.protocolViolation("连接提前关闭")) + } else { + continuation.resume(returning: Data()) + } + } + } + buffer.append(block) + } + return buffer + } + + static func waitReady(_ connection: NWConnection, queue: DispatchQueue, + timeout: TimeInterval = 15) async throws { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + let resumed = Locked(false) + func finish(_ error: Error?) { + guard resumed.exchange(true) == false else { return } + if let error { continuation.resume(throwing: error) } else { continuation.resume() } + } + + connection.stateUpdateHandler = { state in + switch state { + case .ready: + finish(nil) + case .failed(let error): + finish(error) + case .waiting(let error): + // NWConnection 默认会在 .waiting 里无限重试。对一次性传输来说: + // TLS 类错误(密钥不匹配、对端拒绝)不可能自愈,立刻失败; + // 而链路层的暂时不可达在 AWDL/Bonjour 起来之前是正常现象,继续等。 + if case .tls = error { + finish(PeerError.handshake("预共享密钥不匹配,或对方已结束这次会话")) + } + case .cancelled: + finish(PeerError.handshake("连接被取消")) + default: + break + } + } + queue.asyncAfter(deadline: .now() + timeout) { finish(PeerError.timeout) } + connection.start(queue: queue) + } + } +} + +/// 极简互斥包装。continuation 只能 resume 一次,而 stateUpdateHandler +/// 可能在多个状态里触发,需要一个原子的「是否已 resume」。 +final class Locked { + private var value: Value + private let lock = NSLock() + + init(_ value: Value) { self.value = value } + + func exchange(_ newValue: Value) -> Value { + lock.lock(); defer { lock.unlock() } + let old = value + value = newValue + return old + } + + var current: Value { + lock.lock(); defer { lock.unlock() } + return value + } +} + +// MARK: - 发送端 + +/// 展示二维码的一方。持有文件,等待对方扫码后连入。 +final class PeerSender { + + /// 监听器的状态与排队中的连接。stateUpdateHandler / newConnectionHandler + /// 在任意线程触发,而等待方是 async,所以两边都要经过这把锁。 + private final class Box { + let lock = NSLock() + var readyPort: UInt16? + var failure: Error? + var pending: [NWConnection] = [] + var portWaiter: CheckedContinuation? + var connectionWaiter: CheckedContinuation? + + /// 同步方法:async 上下文里不允许直接调用 NSLock.lock() + func drainPending() -> [NWConnection] { + lock.lock(); defer { lock.unlock() } + let extras = pending + pending = [] + return extras + } + } + + private let fileURL: URL + private let deviceName: String + private let queue = DispatchQueue(label: "qft.peer.sender") + private let box = Box() + private var listener: NWListener? + private var pairing: PeerPairing? + + init(fileURL: URL, deviceName: String) { + self.fileURL = fileURL + self.deviceName = deviceName + } + + /// 等待监听就绪并返回实际端口。P2P 场景下对端靠 Bonjour 实例名找过来, + /// 端口只在测试直连时才需要。 + func listeningPort() async throws -> UInt16 { + try await withCheckedThrowingContinuation { continuation in + box.lock.lock() + if let port = box.readyPort { + box.lock.unlock(); continuation.resume(returning: port) + } else if let failure = box.failure { + box.lock.unlock(); continuation.resume(throwing: failure) + } else { + box.portWaiter = continuation + box.lock.unlock() + } + } + } + + /// 计算文件摘要、启动监听并广播 Bonjour 服务,返回要显示成二维码的配对码。 + func start() throws -> PeerPairing { + let attributes = try FileManager.default.attributesOfItem(atPath: fileURL.path) + let size = UInt64(truncating: (attributes[.size] as? NSNumber) ?? 0) + + var hasher = SHA256() + let handle = try FileHandle(forReadingFrom: fileURL) + while let block = try handle.read(upToCount: 4 * 1024 * 1024), !block.isEmpty { + hasher.update(data: block) + } + try handle.close() + let digest = hasher.finalize().map { String(format: "%02x", $0) }.joined() + + let pairing = PeerPairing( + version: 1, + key: PeerPairing.newKey(), + instance: PeerPairing.newInstance(), + senderName: deviceName, + fileName: fileURL.lastPathComponent, + fileSize: size, + sha256: digest) + + let parameters = PeerLink.parameters(key: pairing.key, identity: pairing.instance) + let listener = try NWListener(using: parameters) + listener.service = NWListener.Service(name: pairing.instance, + type: PeerPairing.serviceType) + + listener.stateUpdateHandler = { [box] state in + switch state { + case .ready: + box.lock.lock() + box.readyPort = listener.port?.rawValue + let waiter = box.portWaiter + box.portWaiter = nil + box.lock.unlock() + if let port = listener.port?.rawValue { waiter?.resume(returning: port) } + case .failed(let error): + box.lock.lock() + box.failure = error + let portWaiter = box.portWaiter + let connectionWaiter = box.connectionWaiter + box.portWaiter = nil + box.connectionWaiter = nil + box.lock.unlock() + portWaiter?.resume(throwing: error) + connectionWaiter?.resume(throwing: error) + default: + break + } + } + listener.newConnectionHandler = { [box] connection in + box.lock.lock() + if let waiter = box.connectionWaiter { + box.connectionWaiter = nil + box.lock.unlock() + waiter.resume(returning: connection) + } else { + box.pending.append(connection) + box.lock.unlock() + } + } + listener.start(queue: queue) + + self.listener = listener + self.pairing = pairing + return pairing + } + + /// 等待一个连接并把文件推过去。 + func waitAndSend(onProgress: @escaping (TransferProgress) -> Void) async throws { + guard let listener, let pairing else { + throw PeerLink.PeerError.handshake("尚未调用 start()") + } + + let connection = try await withCheckedThrowingContinuation { + (continuation: CheckedContinuation) in + box.lock.lock() + if !box.pending.isEmpty { + let first = box.pending.removeFirst() + box.lock.unlock() + continuation.resume(returning: first) + } else if let failure = box.failure { + box.lock.unlock() + continuation.resume(throwing: failure) + } else { + box.connectionWaiter = continuation + box.lock.unlock() + } + } + // 一次会话只服务一个对端,其余排队的连接直接断开 + box.drainPending().forEach { $0.cancel() } + + defer { connection.cancel(); listener.cancel() } + + try await PeerLink.waitReady(connection, queue: queue) + + let manifest: [String: Any] = [ + "name": pairing.fileName, + "size": NSNumber(value: pairing.fileSize), + "sha256": pairing.sha256, + "sender": pairing.senderName, + ] + try await PeerLink.send(connection, type: .manifest, + payload: try JSONSerialization.data(withJSONObject: manifest)) + + let handle = try FileHandle(forReadingFrom: fileURL) + defer { try? handle.close() } + var sent: UInt64 = 0 + let startedAt = Date() + var lastReport = Date.distantPast + + while let block = try handle.read(upToCount: PeerLink.chunkSize), !block.isEmpty { + try Task.checkCancellation() + try await PeerLink.send(connection, type: .data, payload: block) + sent &+= UInt64(block.count) + let now = Date() + if now.timeIntervalSince(lastReport) > 0.1 || sent >= pairing.fileSize { + lastReport = now + onProgress(TransferProgress( + completed: sent, total: pairing.fileSize, + bytesPerSecond: Double(sent) / max(0.001, now.timeIntervalSince(startedAt)))) + } + } + try await PeerLink.send(connection, type: .eof, payload: Data()) + + let (type, payload) = try await PeerLink.receiveFrame(connection) + guard type == .result, + let object = try? JSONSerialization.jsonObject(with: payload) as? [String: Any] else { + throw PeerLink.PeerError.protocolViolation("收尾帧无效") + } + if (object["ok"] as? Bool) != true { + throw PeerLink.PeerError.rejected((object["error"] as? String) ?? "对方未说明原因") + } + } + + func stop() { + listener?.cancel() + listener = nil + } +} + +// MARK: - 接收端 + +/// 扫码的一方。按实例名找到对端并接收文件。 +struct PeerReceiver { + + let pairing: PeerPairing + let destinationDirectory: URL + /// 测试用:跳过 Bonjour,直接连指定端口。 + var directPort: UInt16? + + func run(onProgress: @escaping (TransferProgress) -> Void) async throws -> URL { + let queue = DispatchQueue(label: "qft.peer.receiver") + let parameters = PeerLink.parameters(key: pairing.key, identity: pairing.instance) + + let endpoint: NWEndpoint + if let directPort { + endpoint = .hostPort(host: .ipv4(.loopback), port: .init(rawValue: directPort)!) + } else { + endpoint = .service(name: pairing.instance, type: PeerPairing.serviceType, + domain: "local", interface: nil) + } + + let connection = NWConnection(to: endpoint, using: parameters) + defer { connection.cancel() } + try await PeerLink.waitReady(connection, queue: queue) + + // --- 清单 --- + let (manifestType, manifestPayload) = try await PeerLink.receiveFrame(connection) + guard manifestType == .manifest, + let manifest = try? JSONSerialization.jsonObject(with: manifestPayload) as? [String: Any], + let declaredSize = (manifest["size"] as? NSNumber)?.uint64Value, + let declaredHash = manifest["sha256"] as? String else { + throw PeerLink.PeerError.protocolViolation("清单帧无效") + } + // 清单必须与二维码一致,否则说明连到的不是扫码时看到的那个文件 + guard declaredSize == pairing.fileSize, declaredHash == pairing.sha256 else { + try? await PeerLink.send(connection, type: .result, payload: Data( + #"{"ok":false,"error":"manifest mismatch"}"#.utf8)) + throw PeerLink.PeerError.protocolViolation("对方声明的文件与二维码不符") + } + + try FileManager.default.createDirectory(at: destinationDirectory, + withIntermediateDirectories: true) + let partURL = destinationDirectory.appendingPathComponent(pairing.fileName + ".qftpart") + try? FileManager.default.removeItem(at: partURL) + FileManager.default.createFile(atPath: partURL.path, contents: nil) + let handle = try FileHandle(forWritingTo: partURL) + + var hasher = SHA256() + var received: UInt64 = 0 + let startedAt = Date() + var lastReport = Date.distantPast + + // --- 数据 --- + do { + loop: while true { + try Task.checkCancellation() + let (type, payload) = try await PeerLink.receiveFrame(connection) + switch type { + case .data: + guard received &+ UInt64(payload.count) <= pairing.fileSize else { + throw PeerLink.PeerError.protocolViolation("收到的数据超出声明大小") + } + try handle.write(contentsOf: payload) + hasher.update(data: payload) + received &+= UInt64(payload.count) + let now = Date() + if now.timeIntervalSince(lastReport) > 0.1 || received >= pairing.fileSize { + lastReport = now + onProgress(TransferProgress( + completed: received, total: pairing.fileSize, + bytesPerSecond: Double(received) / max(0.001, now.timeIntervalSince(startedAt)))) + } + case .eof: + break loop + default: + throw PeerLink.PeerError.protocolViolation("数据阶段收到 \(type)") + } + } + try handle.close() + } catch { + try? handle.close() + try? FileManager.default.removeItem(at: partURL) + throw error + } + + // --- 校验 --- + let actual = hasher.finalize().map { String(format: "%02x", $0) }.joined() + guard received == pairing.fileSize, actual == pairing.sha256 else { + try? FileManager.default.removeItem(at: partURL) + try? await PeerLink.send(connection, type: .result, payload: Data( + #"{"ok":false,"error":"integrity"}"#.utf8)) + throw QFTError.integrity("收到 \(received)/\(pairing.fileSize) 字节,SHA-256 \(actual == pairing.sha256 ? "一致" : "不一致")") + } + + let finalURL = DownloadClient.uniqueURL(in: destinationDirectory, name: pairing.fileName) + try FileManager.default.moveItem(at: partURL, to: finalURL) + try await PeerLink.send(connection, type: .result, payload: Data(#"{"ok":true}"#.utf8)) + return finalURL + } +} diff --git a/ios/QFT/Core/PeerPairing.swift b/ios/QFT/Core/PeerPairing.swift new file mode 100644 index 0000000..19e7feb --- /dev/null +++ b/ios/QFT/Core/PeerPairing.swift @@ -0,0 +1,94 @@ +import Foundation +import Security + +/// 隔空投送式点对点配对码。 +/// +/// 与 QFTPAIR2/QFTSEND2 的关键区别:那两个是「连到某个 IP」, +/// 这个是「连到某个 Bonjour 服务实例,并用二维码里的预共享密钥做 TLS 认证」。 +/// 二维码在这里充当带外信道——和 AirDrop 用 BLE 交换身份是同一个作用, +/// 只是我们把身份交换搬到了用户可见的扫码动作上,不需要任何配对弹窗。 +struct PeerPairing: Equatable { + static let prefix = "QFTP2P1:" + + let version: Int + /// 32 字节预共享密钥。既是 TLS-PSK,也是服务实例的唯一凭据。 + let key: Data + /// Bonjour 服务实例名,由发送端随机生成 + let instance: String + let senderName: String + let fileName: String + let fileSize: UInt64 + let sha256: String + + static let serviceType = "_qft-p2p._tcp" + + func encode() -> String { + let object: [String: Any] = [ + "v": version, + "k": Base64URL.encode(key), + "i": instance, + "n": senderName, + "f": fileName, + "z": NSNumber(value: fileSize), + "h": sha256, + ] + let data = (try? JSONSerialization.data(withJSONObject: object)) ?? Data() + return Self.prefix + Base64URL.encode(data) + } + + static func isPeerText(_ text: String) -> Bool { text.hasPrefix(prefix) } + + static func parse(_ text: String) -> PeerPairing? { + guard text.hasPrefix(prefix), text.count <= 4096 else { return nil } + guard let data = Base64URL.decode(String(text.dropFirst(prefix.count))), + data.count <= 2048, + let object = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else { + return nil + } + guard (object["v"] as? Int) == 1 else { return nil } + guard let keyText = object["k"] as? String, + let key = Base64URL.decode(keyText), key.count == 32 else { return nil } + guard let instance = object["i"] as? String, isValidInstance(instance) else { return nil } + guard let fileName = (object["f"] as? String)?.trimmingCharacters(in: .whitespaces), + PairingProtocol.isValidFileName(fileName) else { return nil } + guard let size = object["z"] as? NSNumber, size.int64Value >= 0 else { return nil } + guard let hash = (object["h"] as? String)?.lowercased(), + PairingProtocol.isValidSHA256(hash) else { return nil } + + return PeerPairing( + version: 1, + key: key, + instance: instance, + senderName: String(((object["n"] as? String) ?? "iPhone").prefix(80)), + fileName: fileName, + fileSize: UInt64(size.int64Value), + sha256: hash + ) + } + + /// Bonjour 实例名:只允许我们自己生成的字符集,避免把任意字符串 + /// 交给 mDNS 解析。 + static func isValidInstance(_ value: String) -> Bool { + guard (8...48).contains(value.count) else { return false } + for scalar in value.unicodeScalars { + switch scalar { + case "A"..."Z", "a"..."z", "0"..."9", "-": continue + default: return false + } + } + return true + } + + static func newKey() -> Data { + var bytes = [UInt8](repeating: 0, count: 32) + _ = SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes) + return Data(bytes) + } + + static func newInstance() -> String { + let alphabet = Array("abcdefghijklmnopqrstuvwxyz0123456789") + var bytes = [UInt8](repeating: 0, count: 16) + _ = SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes) + return "qft-" + String(bytes.map { alphabet[Int($0) % alphabet.count] }) + } +} diff --git a/ios/QFT/Core/UploadClient.swift b/ios/QFT/Core/UploadClient.swift new file mode 100644 index 0000000..fab2b8e --- /dev/null +++ b/ios/QFT/Core/UploadClient.swift @@ -0,0 +1,189 @@ +import Foundation + +/// 手机 → 电脑并行上传(QFTPAIR2)。 +/// +/// 与 Android 端同一套 v2 流程:init → 并行 chunk → finish。 +/// Windows 端 `receiver.rs` 会预分配 `.qftpart`、按 offset 定位写入、 +/// 校验 SHA-256 后 rename,因此 chunk 之间没有顺序要求,重复 chunk 也是幂等的。 +/// +/// 与 Android 的唯一差异是**块大小固定 4 MiB**:Android 会按文件大小选 4/8/16 MiB, +/// 但 iOS 上 `workers × chunkSize` 就是内存峰值,16 MiB × 6 会在旧机型上触发 +/// jetsam。4 MiB × 6 = 24 MiB 峰值,在局域网速度下每块的往返开销可以忽略。 +struct UploadClient { + + let host: QFTHost + let pairing: PairingPayload + let deviceName: String + + static let chunkSize: UInt64 = 4 * 1024 * 1024 + static let maxWorkers = 6 + + struct Session { + let uploadID: String + let chunkSize: UInt64 + let totalChunks: Int + } + + func run(fileURL: URL, onProgress: @escaping (TransferProgress) -> Void) async throws -> String { + let attributes = try FileManager.default.attributesOfItem(atPath: fileURL.path) + let size = UInt64(truncating: (attributes[.size] as? NSNumber) ?? 0) + let name = fileURL.lastPathComponent + + let session = try await initUpload(name: name, size: size) + if session.totalChunks == 0 { + return try await finishUpload(session) + } + + let counter = ByteCounter(total: size, onProgress: onProgress) + let queue = IndexQueue(count: session.totalChunks) + + try await withThrowingTaskGroup(of: Void.self) { group in + let workers = min(session.totalChunks, Self.maxWorkers) + for _ in 0.. Session { + var request = try makeRequest(path: "/qft/upload/init") + request.setValue(Base64URL.encode(name), forHTTPHeaderField: "X-QFT-Filename") + request.setValue(String(size), forHTTPHeaderField: "X-QFT-Size") + request.setValue(String(Self.chunkSize), forHTTPHeaderField: "X-QFT-Chunk-Size") + request.setValue("0", forHTTPHeaderField: "Content-Length") + + let object = try await sendJSON(request, body: Data()) + guard let uploadID = object["upload_id"] as? String, !uploadID.isEmpty, + let chunkSize = (object["chunk_size"] as? NSNumber)?.uint64Value, chunkSize > 0, + let totalChunks = (object["total_chunks"] as? NSNumber)?.intValue, totalChunks >= 0 else { + throw QFTError.malformedResponse("init 响应缺少字段") + } + return Session(uploadID: uploadID, chunkSize: chunkSize, totalChunks: totalChunks) + } + + private func uploadChunk(_ session: Session, index: Int, body: Data) async throws { + var request = try makeRequest(path: "/qft/upload/chunk/\(session.uploadID)/\(index)") + request.setValue(String(body.count), forHTTPHeaderField: "Content-Length") + + // 重复的 chunk 在接收端是幂等的,因此重试是安全的。 + // Wi-Fi 漫游或 Windows 防火墙首次放行都可能吃掉第一次请求。 + var lastError: Error = QFTError.malformedResponse("未知错误") + for attempt in 0..<3 { + do { + _ = try await sendJSON(request, body: body) + return + } catch { + lastError = error + if case QFTError.httpStatus(let code, _) = error, code == 403 || code == 404 { throw error } + try? await Task.sleep(nanoseconds: UInt64(120_000_000 << attempt)) + } + } + throw lastError + } + + private func finishUpload(_ session: Session) async throws -> String { + var request = try makeRequest(path: "/qft/upload/finish/\(session.uploadID)") + request.setValue("0", forHTTPHeaderField: "Content-Length") + let object = try await sendJSON(request, body: Data()) + guard let sha = object["sha256"] as? String else { + throw QFTError.malformedResponse("finish 响应缺少 sha256") + } + return sha + } + + // MARK: - HTTP + + private func makeRequest(path: String) throws -> URLRequest { + guard let url = URL(string: host.baseURL + path) else { + throw QFTError.malformedResponse("上传地址无效:\(path)") + } + var request = URLRequest(url: url) + request.httpMethod = "POST" + request.timeoutInterval = 60 + request.setValue(pairing.session, forHTTPHeaderField: "X-QFT-Token") + request.setValue(Base64URL.encode(deviceName), forHTTPHeaderField: "X-QFT-Device") + request.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type") + return request + } + + private func sendJSON(_ request: URLRequest, body: Data) async throws -> [String: Any] { + let configuration = URLSessionConfiguration.ephemeral + configuration.timeoutIntervalForRequest = request.timeoutInterval + let urlSession = URLSession(configuration: configuration) + defer { urlSession.finishTasksAndInvalidate() } + + let (data, response) = try await urlSession.upload(for: request, from: body) + guard let http = response as? HTTPURLResponse else { + throw QFTError.malformedResponse("非 HTTP 响应") + } + guard http.statusCode == 200 else { + let detail = String(data: data.prefix(200), encoding: .utf8) ?? "" + throw QFTError.httpStatus(http.statusCode, detail) + } + guard let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { + throw QFTError.malformedResponse("响应不是 JSON") + } + if let ok = object["ok"] as? Bool, ok == false { + throw QFTError.malformedResponse("电脑拒绝了请求:\(object)") + } + return object + } +} + +/// 分发块序号。 +actor IndexQueue { + private var current = 0 + private let count: Int + + init(count: Int) { self.count = count } + + func next() -> Int? { + guard current < count else { return nil } + defer { current += 1 } + return current + } +} + +/// 汇总各 worker 的已传字节并限频回调。 +actor ByteCounter { + private var completed: UInt64 = 0 + private let total: UInt64 + private let startedAt = Date() + private var lastReport = Date.distantPast + private let onProgress: (TransferProgress) -> Void + + init(total: UInt64, onProgress: @escaping (TransferProgress) -> Void) { + self.total = total + self.onProgress = onProgress + } + + func add(_ bytes: UInt64) { + completed &+= bytes + let now = Date() + guard now.timeIntervalSince(lastReport) > 0.1 || completed >= total else { return } + lastReport = now + let elapsed = max(0.001, now.timeIntervalSince(startedAt)) + onProgress(TransferProgress(completed: completed, total: total, + bytesPerSecond: Double(completed) / elapsed)) + } +} diff --git a/ios/QFT/Info.plist b/ios/QFT/Info.plist new file mode 100644 index 0000000..35e4bd3 --- /dev/null +++ b/ios/QFT/Info.plist @@ -0,0 +1,68 @@ + + + + + CFBundleDevelopmentRegion + zh_CN + CFBundleDisplayName + QFT 快传 + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + $(MARKETING_VERSION) + CFBundleVersion + $(CURRENT_PROJECT_VERSION) + + + NSCameraUsageDescription + QFT 需要使用相机扫描电脑或另一台 iPhone 上的配对二维码。相机画面不会离开本机。 + + + NSLocalNetworkUsageDescription + QFT 需要在本地网络里找到你的电脑,才能直接传输文件。所有数据只在本地网络内传输,不经过互联网。 + + + NSBonjourServices + + _qft-p2p._tcp + + + + NSAppTransportSecurity + + NSAllowsLocalNetworking + + + + + UIFileSharingEnabled + + LSSupportsOpeningDocumentsInPlace + + + UILaunchScreen + + UIColorName + + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + + diff --git a/ios/README.md b/ios/README.md new file mode 100644 index 0000000..25a389e --- /dev/null +++ b/ios/README.md @@ -0,0 +1,118 @@ +# QFT iOS 客户端 v0.1.0 + +三种传输方式: + +| 方向 | 链路 | 说明 | +|---|---|---| +| 电脑 → iPhone | 局域网 HTTP | 扫 Windows 端的 `QFTSEND2` 码,自动下载,支持断点续传 | +| iPhone → 电脑 | 局域网 HTTP | 扫 `QFTPAIR2` 码,选文件后并行分块上传 | +| **iPhone ↔ iPhone** | **点对点直连** | 发送方显示二维码,接收方扫码,**不需要连同一个 Wi-Fi** | + +## 打开工程 + +```bash +open ios/QFT.xcodeproj +``` + +工程已提交到仓库,不需要 XcodeGen 之类的额外工具。首次构建前在 +Target → Signing & Capabilities 里选一下你自己的开发者账号(免费账号即可, +生成的描述文件 7 天有效)。 + +增删源文件后重新生成工程: + +```bash +python3 ios/tools/generate_xcodeproj.py +``` + +- 最低系统:iOS 17.0 +- Bundle ID:`com.qft.transfer`(按需改 `generate_xcodeproj.py` 里的常量) + +## 隔空投送式点对点传输 + +`PeerLink` 用 `Network.framework` 并打开 `includePeerToPeer`。底层就是 +AirDrop 用的那条链路——BLE 发现 + AWDL 点对点 Wi-Fi,两台设备不需要路由器, +也不需要连同一个 Wi-Fi。两端在同一个 Wi-Fi 下时它会自动优先走基础网络。 + +握手用 **TLS-PSK**:预共享密钥(32 字节)由发送端随机生成并写进二维码, +扫码这个动作本身就完成了带外密钥交换与双向认证。没扫到码的第三方 +连上来也过不了 TLS 握手,因此不需要任何证书体系,也不需要配对弹窗。 + +``` +发送方 接收方 +选文件 → 算 SHA-256 +启动 NWListener(Bonjour: _qft-p2p._tcp) +生成 32 字节 PSK +显示 QFTP2P1 二维码 ──────扫码────→ 解析出 PSK + 服务实例名 + NWBrowser 找到实例 + ←──────── TLS-PSK 握手 ────────→ +MANIFEST(JSON) ─────────────────────→ 校验与二维码是否一致 +DATA × N ─────────────────────→ 落盘 + 增量 SHA-256 +EOF ─────────────────────→ + ←──────── RESULT(JSON) ──────── 校验通过才 rename +``` + +**AWDL 是苹果私有链路,Windows 无法参与**,所以与电脑互传仍走局域网 HTTP。 +如果现场没有路由器,可行的替代是让 iPhone 开个人热点、电脑连上来。 + +## 已知的 iOS 平台限制 + +1. **无法用代码连接指定 Wi-Fi。** Android 端用 `WifiNetworkSpecifier` 自动加入 + Windows 的 QFT Direct AP,iOS 对应的 `NEHotspotConfiguration` 需要 + HotspotConfiguration entitlement,免费开发者账号拿不到。因此 iOS 端 + **不实现 Direct AP 流程**,`PairingProtocol` 在二维码不带可用 endpoint 时 + 会直接拒绝,而不是给用户一个连不上的假成功。 +2. **首次访问局域网会弹权限窗。** 已在 `Info.plist` 声明 + `NSLocalNetworkUsageDescription` 与 `NSBonjourServices`。 + 若用户误点了拒绝,需要去 设置 → 隐私与安全性 → 本地网络 里重新打开。 +3. **没有「下载」文件夹。** 收到的文件存在 App 的 Documents/QFT 下, + 通过 `UIFileSharingEnabled` + `LSSupportsOpeningDocumentsInPlace` + 暴露到「文件」App,也可以在 App 内直接分享出去。 +4. **上传块固定 4 MiB。** Android 端按文件大小选 4/8/16 MiB,但 iOS 上 + `worker 数 × 块大小` 就是内存峰值,16 MiB × 6 会在旧机型触发 jetsam。 + 4 MiB × 6 = 24 MiB 峰值,局域网速度下每块的往返开销可以忽略。 + +## 测试 + +核心层(协议、发现、上传、下载、P2P 链路)不依赖 UIKit, +可以直接以 macOS 为目标编译运行,**不需要 Xcode,也不需要模拟器**: + +```bash +./ios/CoreTests/run.sh +``` + +也已接入主自检套件(`python scripts/run_all_selftests.py`)。 + +测试内容: + +- `Base64URL` 与三端一致性(含 200 组随机字节往返) +- `QFTPAIR2` / `QFTSEND2` / `QFTP2P1` 解析,含各类畸形输入 +- **端点白名单**:二维码是不可信输入,只接受字面量私有 IPv4 + 声明端口。 + 已覆盖域名、公网地址、`172.32` 边界、非规范八位组、IPv6、带凭据/路径/query 等 11 种拒绝用例 +- **与 `MockPCServer.py` 的完整传输**:该 mock 严格复刻 `receiver.rs` / `sender.rs` + 的线上语义(路径、header 名、JSON 字段、Range 行为、chunk 长度校验), + 因此这组测试就是 Swift 端与 Rust 端的**线格式契约测试**——任何一边改了协议都会红 +- **真实 TLS-PSK 握手**下的 P2P 端到端传输,含错误密钥必须被拒 + +## 目录 + +``` +ios/ + QFT.xcodeproj/ 生成的工程(已提交) + QFT/ + Info.plist 权限声明、Bonjour 服务、ATS 本地网络例外 + App/ SwiftUI 界面 + 相机扫码(需要 Xcode 才能构建) + Core/ 纯 Foundation,可在 macOS 上编译测试 + Base64URL.swift + PairingProtocol.swift QFTPAIR2 / QFTSEND2 + 端点白名单 + HostDiscovery.swift endpoint 探测 → UDP 广播 → 子网扫描 + DownloadClient.swift 流式落盘 + 增量 SHA-256 + Range 续传 + UploadClient.swift init/chunk/finish 并行上传 + PeerPairing.swift QFTP2P1 配对码 + PeerLink.swift TLS-PSK + 分帧的点对点链路 + CoreTests/ + run.sh 编译并运行(swiftc,无需 Xcode) + main.swift 测试用例 + MockPCServer.py 复刻 Windows 端线上语义的假电脑 + tools/ + generate_xcodeproj.py 工程生成器 +``` diff --git a/ios/tools/generate_xcodeproj.py b/ios/tools/generate_xcodeproj.py new file mode 100644 index 0000000..fcf2d60 --- /dev/null +++ b/ios/tools/generate_xcodeproj.py @@ -0,0 +1,371 @@ +#!/usr/bin/env python3 +"""生成 ios/QFT.xcodeproj,不依赖 XcodeGen 等外部工具。 + +生成结果已提交到仓库,正常情况下双击 QFT.xcodeproj 即可。 +只有在**增删源文件**之后才需要重跑: + + python3 ios/tools/generate_xcodeproj.py + +对象 ID 由文件路径哈希得到,因此同样的文件集合总是产出同样的工程, +diff 干净,不会每次生成都全量变动。 +""" + +import hashlib +import os + +HERE = os.path.dirname(os.path.abspath(__file__)) +IOS_ROOT = os.path.dirname(HERE) + +APP_NAME = "QFT" +BUNDLE_ID = "com.qft.transfer" +DEPLOYMENT_TARGET = "17.0" +MARKETING_VERSION = "0.1.0" + +SOURCES = [ + "QFT/App/QFTApp.swift", + "QFT/App/HomeView.swift", + "QFT/App/ScannerView.swift", + "QFT/App/TransferModel.swift", + "QFT/Core/Base64URL.swift", + "QFT/Core/PairingProtocol.swift", + "QFT/Core/HostDiscovery.swift", + "QFT/Core/DownloadClient.swift", + "QFT/Core/UploadClient.swift", + "QFT/Core/PeerPairing.swift", + "QFT/Core/PeerLink.swift", +] +RESOURCES = ["QFT/Assets.xcassets"] +OTHER_FILES = ["QFT/Info.plist"] + + +def oid(*parts): + """由稳定字符串派生 24 位十六进制对象 ID。""" + digest = hashlib.sha1("::".join(parts).encode("utf-8")).hexdigest() + return digest[:24].upper() + + +def file_type(path): + if path.endswith(".swift"): + return "sourcecode.swift" + if path.endswith(".xcassets"): + return "folder.assetcatalog" + if path.endswith(".plist"): + return "text.plist.xml" + return "text" + + +def build_tree(paths): + """把扁平路径列表折成 {目录: {...}} 的嵌套结构。""" + tree = {} + for path in paths: + node = tree + segments = path.split("/") + for segment in segments[:-1]: + node = node.setdefault(segment, {}) + node[segments[-1]] = None + return tree + + +def emit_groups(tree, prefix, lines): + """深度优先输出 PBXGroup,返回本层 group 的 ID。""" + children = [] + for name in sorted(tree.keys()): + path = "%s/%s" % (prefix, name) if prefix else name + if tree[name] is None: + children.append((oid("file", path), name)) + else: + children.append((emit_groups(tree[name], path, lines), name)) + + group_id = oid("group", prefix or "") + lines.append("\t\t%s /* %s */ = {" % (group_id, prefix.split("/")[-1] if prefix else APP_NAME)) + lines.append("\t\t\tisa = PBXGroup;") + lines.append("\t\t\tchildren = (") + for child_id, child_name in children: + lines.append("\t\t\t\t%s /* %s */," % (child_id, child_name)) + lines.append("\t\t\t);") + if prefix: + lines.append("\t\t\tpath = %s;" % prefix.split("/")[-1]) + lines.append("\t\t\tsourceTree = \"\";") + lines.append("\t\t};") + return group_id + + +def generate(): + all_files = SOURCES + RESOURCES + OTHER_FILES + + project_id = oid("project") + target_id = oid("target", APP_NAME) + product_id = oid("product", APP_NAME) + products_group_id = oid("group", "") + sources_phase_id = oid("phase", "sources") + resources_phase_id = oid("phase", "resources") + frameworks_phase_id = oid("phase", "frameworks") + project_config_list = oid("configlist", "project") + target_config_list = oid("configlist", "target") + + lines = [] + add = lines.append + + add("// !$*UTF8*$!") + add("{") + add("\tarchiveVersion = 1;") + add("\tclasses = {") + add("\t};") + add("\tobjectVersion = 56;") + add("\tobjects = {") + + # ---------------- PBXBuildFile + add("") + add("/* Begin PBXBuildFile section */") + for path in SOURCES + RESOURCES: + name = path.split("/")[-1] + add("\t\t%s /* %s in %s */ = {isa = PBXBuildFile; fileRef = %s /* %s */; };" + % (oid("buildfile", path), name, + "Resources" if path in RESOURCES else "Sources", + oid("file", path), name)) + add("/* End PBXBuildFile section */") + + # ---------------- PBXFileReference + add("") + add("/* Begin PBXFileReference section */") + add("\t\t%s /* %s.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; " + "includeInIndex = 0; path = %s.app; sourceTree = BUILT_PRODUCTS_DIR; };" + % (product_id, APP_NAME, APP_NAME)) + for path in all_files: + name = path.split("/")[-1] + add("\t\t%s /* %s */ = {isa = PBXFileReference; lastKnownFileType = %s; path = %s; " + "sourceTree = \"\"; };" % (oid("file", path), name, file_type(path), name)) + add("/* End PBXFileReference section */") + + # ---------------- PBXFrameworksBuildPhase + add("") + add("/* Begin PBXFrameworksBuildPhase section */") + add("\t\t%s /* Frameworks */ = {" % frameworks_phase_id) + add("\t\t\tisa = PBXFrameworksBuildPhase;") + add("\t\t\tbuildActionMask = 2147483647;") + add("\t\t\tfiles = (") + add("\t\t\t);") + add("\t\t\trunOnlyForDeploymentPostprocessing = 0;") + add("\t\t};") + add("/* End PBXFrameworksBuildPhase section */") + + # ---------------- PBXGroup + add("") + add("/* Begin PBXGroup section */") + group_lines = [] + app_group_id = emit_groups(build_tree(all_files)[APP_NAME], APP_NAME, group_lines) + lines.extend(group_lines) + + root_group_id = oid("group", "") + add("\t\t%s = {" % root_group_id) + add("\t\t\tisa = PBXGroup;") + add("\t\t\tchildren = (") + add("\t\t\t\t%s /* %s */," % (app_group_id, APP_NAME)) + add("\t\t\t\t%s /* Products */," % products_group_id) + add("\t\t\t);") + add("\t\t\tsourceTree = \"\";") + add("\t\t};") + + add("\t\t%s /* Products */ = {" % products_group_id) + add("\t\t\tisa = PBXGroup;") + add("\t\t\tchildren = (") + add("\t\t\t\t%s /* %s.app */," % (product_id, APP_NAME)) + add("\t\t\t);") + add("\t\t\tname = Products;") + add("\t\t\tsourceTree = \"\";") + add("\t\t};") + add("/* End PBXGroup section */") + + # ---------------- PBXNativeTarget + add("") + add("/* Begin PBXNativeTarget section */") + add("\t\t%s /* %s */ = {" % (target_id, APP_NAME)) + add("\t\t\tisa = PBXNativeTarget;") + add("\t\t\tbuildConfigurationList = %s;" % target_config_list) + add("\t\t\tbuildPhases = (") + add("\t\t\t\t%s /* Sources */," % sources_phase_id) + add("\t\t\t\t%s /* Frameworks */," % frameworks_phase_id) + add("\t\t\t\t%s /* Resources */," % resources_phase_id) + add("\t\t\t);") + add("\t\t\tbuildRules = (") + add("\t\t\t);") + add("\t\t\tdependencies = (") + add("\t\t\t);") + add("\t\t\tname = %s;" % APP_NAME) + add("\t\t\tproductName = %s;" % APP_NAME) + add("\t\t\tproductReference = %s /* %s.app */;" % (product_id, APP_NAME)) + add("\t\t\tproductType = \"com.apple.product-type.application\";") + add("\t\t};") + add("/* End PBXNativeTarget section */") + + # ---------------- PBXProject + add("") + add("/* Begin PBXProject section */") + add("\t\t%s /* Project object */ = {" % project_id) + add("\t\t\tisa = PBXProject;") + add("\t\t\tattributes = {") + add("\t\t\t\tBuildIndependentTargetsInParallel = 1;") + add("\t\t\t\tLastSwiftUpdateCheck = 1600;") + add("\t\t\t\tLastUpgradeCheck = 1600;") + add("\t\t\t\tTargetAttributes = {") + add("\t\t\t\t\t%s = {" % target_id) + add("\t\t\t\t\t\tCreatedOnToolsVersion = 16.0;") + add("\t\t\t\t\t};") + add("\t\t\t\t};") + add("\t\t\t};") + add("\t\t\tbuildConfigurationList = %s;" % project_config_list) + add("\t\t\tcompatibilityVersion = \"Xcode 14.0\";") + add("\t\t\tdevelopmentRegion = en;") + add("\t\t\thasScannedForEncodings = 0;") + add("\t\t\tknownRegions = (") + add("\t\t\t\ten,") + add("\t\t\t\tBase,") + add("\t\t\t\t\"zh-Hans\",") + add("\t\t\t);") + add("\t\t\tmainGroup = %s;" % root_group_id) + add("\t\t\tproductRefGroup = %s /* Products */;" % products_group_id) + add("\t\t\tprojectDirPath = \"\";") + add("\t\t\tprojectRoot = \"\";") + add("\t\t\ttargets = (") + add("\t\t\t\t%s /* %s */," % (target_id, APP_NAME)) + add("\t\t\t);") + add("\t\t};") + add("/* End PBXProject section */") + + # ---------------- PBXResourcesBuildPhase + add("") + add("/* Begin PBXResourcesBuildPhase section */") + add("\t\t%s /* Resources */ = {" % resources_phase_id) + add("\t\t\tisa = PBXResourcesBuildPhase;") + add("\t\t\tbuildActionMask = 2147483647;") + add("\t\t\tfiles = (") + for path in RESOURCES: + add("\t\t\t\t%s /* %s in Resources */," % (oid("buildfile", path), path.split("/")[-1])) + add("\t\t\t);") + add("\t\t\trunOnlyForDeploymentPostprocessing = 0;") + add("\t\t};") + add("/* End PBXResourcesBuildPhase section */") + + # ---------------- PBXSourcesBuildPhase + add("") + add("/* Begin PBXSourcesBuildPhase section */") + add("\t\t%s /* Sources */ = {" % sources_phase_id) + add("\t\t\tisa = PBXSourcesBuildPhase;") + add("\t\t\tbuildActionMask = 2147483647;") + add("\t\t\tfiles = (") + for path in SOURCES: + add("\t\t\t\t%s /* %s in Sources */," % (oid("buildfile", path), path.split("/")[-1])) + add("\t\t\t);") + add("\t\t\trunOnlyForDeploymentPostprocessing = 0;") + add("\t\t};") + add("/* End PBXSourcesBuildPhase section */") + + # ---------------- XCBuildConfiguration + shared_project = [ + "ALWAYS_SEARCH_USER_PATHS = NO", + "CLANG_ANALYZER_NONNULL = YES", + "CLANG_ENABLE_MODULES = YES", + "CLANG_ENABLE_OBJC_ARC = YES", + "CLANG_WARN_DOCUMENTATION_COMMENTS = YES", + "CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE", + "COPY_PHASE_STRIP = NO", + "ENABLE_STRICT_OBJC_MSGSEND = YES", + "GCC_NO_COMMON_BLOCKS = YES", + "IPHONEOS_DEPLOYMENT_TARGET = %s" % DEPLOYMENT_TARGET, + "MTL_FAST_MATH = YES", + "SDKROOT = iphoneos", + "SWIFT_VERSION = 5.0", + ] + shared_target = [ + "ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon", + "ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor", + "CODE_SIGN_STYLE = Automatic", + "CURRENT_PROJECT_VERSION = 1", + "ENABLE_PREVIEWS = YES", + "GENERATE_INFOPLIST_FILE = NO", + "INFOPLIST_FILE = QFT/Info.plist", + "LD_RUNPATH_SEARCH_PATHS = \"$(inherited) @executable_path/Frameworks\"", + "MARKETING_VERSION = %s" % MARKETING_VERSION, + "PRODUCT_BUNDLE_IDENTIFIER = %s" % BUNDLE_ID, + "PRODUCT_NAME = \"$(TARGET_NAME)\"", + "SWIFT_EMIT_LOC_STRINGS = NO", + "TARGETED_DEVICE_FAMILY = \"1,2\"", + ] + variants = { + "Debug": { + "project": ["DEBUG_INFORMATION_FORMAT = dwarf", + "ENABLE_TESTABILITY = YES", + "GCC_OPTIMIZATION_LEVEL = 0", + "GCC_PREPROCESSOR_DEFINITIONS = \"DEBUG=1 $(inherited)\"", + "MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE", + "ONLY_ACTIVE_ARCH = YES", + "SWIFT_ACTIVE_COMPILATION_CONDITIONS = \"DEBUG $(inherited)\"", + "SWIFT_OPTIMIZATION_LEVEL = \"-Onone\""], + "target": [], + }, + "Release": { + "project": ["DEBUG_INFORMATION_FORMAT = \"dwarf-with-dsym\"", + "ENABLE_NS_ASSERTIONS = NO", + "MTL_ENABLE_DEBUG_INFO = NO", + "SWIFT_COMPILATION_MODE = wholemodule", + "VALIDATE_PRODUCT = YES"], + "target": [], + }, + } + + add("") + add("/* Begin XCBuildConfiguration section */") + for name, extra in variants.items(): + for scope, base in (("project", shared_project), ("target", shared_target)): + config_id = oid("config", scope, name) + add("\t\t%s /* %s */ = {" % (config_id, name)) + add("\t\t\tisa = XCBuildConfiguration;") + add("\t\t\tbuildSettings = {") + for setting in sorted(base + extra[scope]): + add("\t\t\t\t%s;" % setting) + add("\t\t\t};") + add("\t\t\tname = %s;" % name) + add("\t\t};") + add("/* End XCBuildConfiguration section */") + + # ---------------- XCConfigurationList + add("") + add("/* Begin XCConfigurationList section */") + for scope, list_id in (("project", project_config_list), ("target", target_config_list)): + add("\t\t%s = {" % list_id) + add("\t\t\tisa = XCConfigurationList;") + add("\t\t\tbuildConfigurations = (") + for name in variants: + add("\t\t\t\t%s /* %s */," % (oid("config", scope, name), name)) + add("\t\t\t);") + add("\t\t\tdefaultConfigurationIsVisible = 0;") + add("\t\t\tdefaultConfigurationName = Release;") + add("\t\t};") + add("/* End XCConfigurationList section */") + + add("\t};") + add("\trootObject = %s /* Project object */;" % project_id) + add("}") + return "\n".join(lines) + "\n" + + +def main(): + project_dir = os.path.join(IOS_ROOT, "%s.xcodeproj" % APP_NAME) + os.makedirs(project_dir, exist_ok=True) + target = os.path.join(project_dir, "project.pbxproj") + with open(target, "w", encoding="utf-8") as fh: + fh.write(generate()) + print("已生成 %s" % target) + + missing = [p for p in SOURCES + RESOURCES + OTHER_FILES + if not os.path.exists(os.path.join(IOS_ROOT, p))] + if missing: + print("警告:以下文件在工程里被引用但不存在:") + for path in missing: + print(" " + path) + return 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/ios_core_selftest.py b/scripts/ios_core_selftest.py new file mode 100644 index 0000000..24f2dde --- /dev/null +++ b/scripts/ios_core_selftest.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python3 +"""把 iOS 核心层测试接进主自检套件。 + +iOS 核心层(协议解析、局域网发现、上传/下载、P2P 链路)刻意不 import +UIKit/AVFoundation,因此可以直接以 macOS 为目标编译运行, +不需要 Xcode,也不需要模拟器。 + +非 macOS 主机或没有 swiftc 时跳过,不让整套自检失败。 +""" + +import platform +import shutil +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +RUNNER = ROOT / "ios" / "CoreTests" / "run.sh" + + +def main() -> int: + if platform.system() != "Darwin": + print("SKIP:iOS 核心层测试需要 macOS") + return 0 + if shutil.which("swiftc") is None: + print("SKIP:未找到 swiftc(安装 Xcode 或 Command Line Tools 后可运行)") + return 0 + if not RUNNER.exists(): + print("SKIP:%s 不存在" % RUNNER) + return 0 + + result = subprocess.run(["bash", str(RUNNER)], cwd=str(ROOT)) + if result.returncode != 0: + print("iOS 核心层测试失败") + return result.returncode + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/run_all_selftests.py b/scripts/run_all_selftests.py index a6ff795..a9de7c5 100644 --- a/scripts/run_all_selftests.py +++ b/scripts/run_all_selftests.py @@ -14,6 +14,7 @@ scripts = [ 'single_channel_guard_selftest.py', 'kotlin_host_smoke.py', 'wedge_selftest.py', + 'ios_core_selftest.py', ] for name in scripts: print(f'== {name} ==', flush=True)