Files
QFT/ios/QFT/Core/PeerLink.swift
T
zhy200308 4d77ba6c91 feat: 新增 iPhone 客户端,含隔空投送式点对点互传
三条链路:
- 电脑 → 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 中实际打开过。
2026-08-11 09:08:37 +08:00

470 lines
19 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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<Void, Error>) 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<Data, Error>) 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<Void, Error>) 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<Value> {
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<UInt16, Error>?
var connectionWaiter: CheckedContinuation<NWConnection, Error>?
/// 同步方法: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<NWConnection, Error>) 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
}
}