376ffba96e
对应 V05_EXECUTION_PLAN 的 P1。核心改动是把「PC 只能当服务端」 这个写死的角色拆开——此前 TcpStream::connect 只出现在测试里, 桌面端根本无法主动连接另一台桌面端,PC↔PC 因此完全不可用。 跨平台 - windows/ → desktop/,crate 更名 qft-desktop - 新增 platform.rs 收敛全部平台差异:配置目录(LOCALAPPDATA / Application Support / XDG)、下载目录(含 Linux 本地化的 ~/下载)、 设备名、Direct AP 能力。约定:其余模块不得再出现 #[cfg(target_os)] - direct_ap.rs 的 Context 导入按平台条件化,非 Windows 上不再告警 - macOS 上已实测编译并链接出可执行文件(65 MB Mach-O arm64), 这是本仓库首次在非 Windows 平台构建成功 电脑 ↔ 电脑 - 新增 client.rs:桌面端发起侧。手写 HTTP,不引入客户端依赖—— 服务端本来就是手写的,两边同一套解析更容易与 Android/iOS 对齐。 含并发分块上传(自适应 4/8/16 MiB、最多 8 worker)与 Range 断点续传 - 新增 discovery.rs:UDP 广播 QFTBROWSE3 浏览局域网节点。 既有的 QFTDISC2 是「已知令牌找机器」,用于扫码之后; PC 没有摄像头,必须先能列出附近有谁 - receiver.rs 新增 POST /qft/pair:用 6 位配对码换会话令牌。 这是唯一不校验令牌的端点。6 位仅约 20 bit 熵,配严格失败计数兜底—— 错 5 次即作废,需重启接收;比较用定长实现,不做短路返回 - 新增「电脑 ↔ 电脑」界面:接收方显示配对码与本机地址; 发送方搜索/手动输入地址 → 输码连接 → 多选文件 → 带进度发送 验证(macOS,Rust 1.97.1) - cargo check 0 错误,cargo test 17/17 通过 - 新增端到端用例:真实起接收服务 → 配对(含错误码必须被拒)→ 9 MB 跨多分块并发上传 → 校验落盘内容逐字节一致且 SHA-256 与 接收端返回值相同。这就是 PC↔PC 的完整链路 - 11 项 Python 自检全部通过 顺带修复 - single_channel_guard_selftest 长期为红:它断言 DEFAULT_CHUNK_SIZE = 450,而代码早已改为 320。改名前即存在, 已用 git stash 验证与本次无关。改为范围检查(128~4096)并在 PASS 信息里打印实际值,既挡住"退回多通道小块"又不会因调参误报 已知限制 - UDP 广播只覆盖同一广播域。跨网段或 AP 隔离的 Wi-Fi 上搜索不到, 需手动输入对方 IP(界面已说明)。mDNS 留待后续 - 本阶段仍走 v2 明文 HTTP,加密随 QFT-Stream v3 一起做(见 P2)
243 lines
7.1 KiB
Rust
243 lines
7.1 KiB
Rust
use crate::base45;
|
|
use anyhow::{bail, Context, Result};
|
|
use crc32fast::hash as crc32;
|
|
use rand::RngCore;
|
|
use sha2::{Digest, Sha256};
|
|
use std::{
|
|
fs::File,
|
|
io::Read,
|
|
path::{Path, PathBuf},
|
|
};
|
|
|
|
pub const PREFIX: &str = "QFT2:";
|
|
pub const VERSION: u8 = 2;
|
|
|
|
#[derive(Clone, Copy, Debug)]
|
|
#[repr(u8)]
|
|
pub enum FrameKind {
|
|
Manifest = 1,
|
|
Data = 2,
|
|
End = 3,
|
|
}
|
|
|
|
#[derive(Clone, Debug)]
|
|
pub struct Manifest {
|
|
pub session_id: u64,
|
|
pub sender_device: String,
|
|
pub file_name: String,
|
|
pub file_size: u64,
|
|
pub chunk_size: u16,
|
|
pub total_chunks: u32,
|
|
pub sha256: [u8; 32],
|
|
}
|
|
|
|
pub struct TransferSource {
|
|
path: PathBuf,
|
|
file: File,
|
|
pub manifest: Manifest,
|
|
}
|
|
|
|
impl TransferSource {
|
|
pub fn open(path: impl AsRef<Path>, chunk_size: u16) -> Result<Self> {
|
|
if chunk_size == 0 {
|
|
bail!("chunk_size must be > 0");
|
|
}
|
|
let path = path.as_ref().to_path_buf();
|
|
let file = File::open(&path).context("open input file")?;
|
|
let file_size = file.metadata()?.len();
|
|
let total_chunks_u64 = if file_size == 0 {
|
|
0
|
|
} else {
|
|
(file_size + chunk_size as u64 - 1) / chunk_size as u64
|
|
};
|
|
if total_chunks_u64 > u32::MAX as u64 {
|
|
bail!("file requires too many chunks");
|
|
}
|
|
|
|
let sha256 = hash_file_streaming(&file)?;
|
|
let mut rng = rand::rng();
|
|
let session_id = rng.next_u64();
|
|
let file_name = path
|
|
.file_name()
|
|
.and_then(|s| s.to_str())
|
|
.unwrap_or("qft.bin")
|
|
.to_owned();
|
|
let sender_device = local_device_name();
|
|
|
|
Ok(Self {
|
|
path,
|
|
file,
|
|
manifest: Manifest {
|
|
session_id,
|
|
sender_device,
|
|
file_name,
|
|
file_size,
|
|
chunk_size,
|
|
total_chunks: total_chunks_u64 as u32,
|
|
sha256,
|
|
},
|
|
})
|
|
}
|
|
|
|
pub fn path(&self) -> &Path {
|
|
&self.path
|
|
}
|
|
|
|
pub fn total_playlist_frames(&self) -> u32 {
|
|
self.manifest.total_chunks.saturating_add(2)
|
|
}
|
|
|
|
/// playlist_index: 0=manifest, 1..=N=data, N+1=end
|
|
pub fn binary_frame(&self, playlist_index: u32) -> Result<Vec<u8>> {
|
|
let n = self.manifest.total_chunks;
|
|
if playlist_index == 0 {
|
|
return Ok(encode_manifest_binary(&self.manifest));
|
|
}
|
|
if playlist_index >= 1 && playlist_index <= n {
|
|
return self.encode_data_binary(playlist_index - 1);
|
|
}
|
|
if playlist_index == n + 1 {
|
|
return Ok(encode_frame_binary(
|
|
FrameKind::End,
|
|
self.manifest.session_id,
|
|
0,
|
|
n,
|
|
&[],
|
|
));
|
|
}
|
|
bail!("playlist index out of range")
|
|
}
|
|
|
|
/// QFT2 uses Base45 because the whole alphabet is legal in QR alphanumeric
|
|
/// mode. This is close to raw byte efficiency without relying on ZXing's
|
|
/// rawBytes interpretation, and Android can consume Result.text directly.
|
|
pub fn text_frame(&self, playlist_index: u32) -> Result<String> {
|
|
let binary = self.binary_frame(playlist_index)?;
|
|
Ok(format!("{PREFIX}{}", base45::encode(&binary)))
|
|
}
|
|
|
|
fn encode_data_binary(&self, seq: u32) -> Result<Vec<u8>> {
|
|
let offset = seq as u64 * self.manifest.chunk_size as u64;
|
|
let remaining = self.manifest.file_size.saturating_sub(offset);
|
|
let len = remaining.min(self.manifest.chunk_size as u64) as usize;
|
|
let mut payload = vec![0u8; len];
|
|
if len > 0 {
|
|
read_exact_at(&self.file, &mut payload, offset)?;
|
|
}
|
|
Ok(encode_frame_binary(
|
|
FrameKind::Data,
|
|
self.manifest.session_id,
|
|
seq,
|
|
self.manifest.total_chunks,
|
|
&payload,
|
|
))
|
|
}
|
|
}
|
|
|
|
fn encode_manifest_binary(m: &Manifest) -> Vec<u8> {
|
|
let name = m.file_name.as_bytes();
|
|
let name_len = name.len().min(u16::MAX as usize) as u16;
|
|
let device = m.sender_device.as_bytes();
|
|
let device_len = device.len().min(u16::MAX as usize) as u16;
|
|
let mut payload = Vec::with_capacity(
|
|
8 + 2 + 32 + 2 + name_len as usize + 2 + device_len as usize,
|
|
);
|
|
payload.extend_from_slice(&m.file_size.to_be_bytes());
|
|
payload.extend_from_slice(&m.chunk_size.to_be_bytes());
|
|
payload.extend_from_slice(&m.sha256);
|
|
payload.extend_from_slice(&name_len.to_be_bytes());
|
|
payload.extend_from_slice(&name[..name_len as usize]);
|
|
payload.extend_from_slice(&device_len.to_be_bytes());
|
|
payload.extend_from_slice(&device[..device_len as usize]);
|
|
encode_frame_binary(
|
|
FrameKind::Manifest,
|
|
m.session_id,
|
|
0,
|
|
m.total_chunks,
|
|
&payload,
|
|
)
|
|
}
|
|
|
|
pub fn encode_frame_binary(
|
|
kind: FrameKind,
|
|
session_id: u64,
|
|
seq: u32,
|
|
total_chunks: u32,
|
|
payload: &[u8],
|
|
) -> Vec<u8> {
|
|
assert!(payload.len() <= u16::MAX as usize);
|
|
let mut binary = Vec::with_capacity(28 + payload.len());
|
|
binary.extend_from_slice(b"QFT2");
|
|
binary.push(VERSION);
|
|
binary.push(kind as u8);
|
|
binary.extend_from_slice(&session_id.to_be_bytes());
|
|
binary.extend_from_slice(&seq.to_be_bytes());
|
|
binary.extend_from_slice(&total_chunks.to_be_bytes());
|
|
binary.extend_from_slice(&(payload.len() as u16).to_be_bytes());
|
|
binary.extend_from_slice(payload);
|
|
let crc = crc32(&binary);
|
|
binary.extend_from_slice(&crc.to_be_bytes());
|
|
binary
|
|
}
|
|
|
|
pub fn hex_sha256(bytes: &[u8; 32]) -> String {
|
|
const HEX: &[u8; 16] = b"0123456789abcdef";
|
|
let mut out = String::with_capacity(64);
|
|
for &b in bytes {
|
|
out.push(HEX[(b >> 4) as usize] as char);
|
|
out.push(HEX[(b & 0x0f) as usize] as char);
|
|
}
|
|
out
|
|
}
|
|
|
|
pub fn local_device_name() -> String {
|
|
crate::platform::device_name()
|
|
}
|
|
|
|
fn hash_file_streaming(file: &File) -> Result<[u8; 32]> {
|
|
let mut input = file.try_clone().context("clone input for sha256")?;
|
|
let mut hasher = Sha256::new();
|
|
let mut buf = vec![0u8; 4 * 1024 * 1024];
|
|
loop {
|
|
let n = input.read(&mut buf).context("read input for sha256")?;
|
|
if n == 0 {
|
|
break;
|
|
}
|
|
hasher.update(&buf[..n]);
|
|
}
|
|
Ok(hasher.finalize().into())
|
|
}
|
|
|
|
fn read_exact_at(file: &File, mut out: &mut [u8], mut offset: u64) -> Result<()> {
|
|
while !out.is_empty() {
|
|
let n = read_at_once(file, out, offset)?;
|
|
if n == 0 {
|
|
bail!("unexpected EOF at offset {offset}");
|
|
}
|
|
offset = offset.saturating_add(n as u64);
|
|
let (_, rest) = out.split_at_mut(n);
|
|
out = rest;
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
#[cfg(windows)]
|
|
fn read_at_once(file: &File, out: &mut [u8], offset: u64) -> std::io::Result<usize> {
|
|
use std::os::windows::fs::FileExt;
|
|
file.seek_read(out, offset)
|
|
}
|
|
|
|
#[cfg(unix)]
|
|
fn read_at_once(file: &File, out: &mut [u8], offset: u64) -> std::io::Result<usize> {
|
|
use std::os::unix::fs::FileExt;
|
|
file.read_at(out, offset)
|
|
}
|
|
|
|
#[cfg(not(any(windows, unix)))]
|
|
fn read_at_once(file: &File, out: &mut [u8], offset: u64) -> std::io::Result<usize> {
|
|
use std::io::{Seek, SeekFrom};
|
|
let mut cloned = file.try_clone()?;
|
|
cloned.seek(SeekFrom::Start(offset))?;
|
|
cloned.read(out)
|
|
}
|