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, chunk_size: u16) -> Result { 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> { 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 { let binary = self.binary_frame(playlist_index)?; Ok(format!("{PREFIX}{}", base45::encode(&binary))) } fn encode_data_binary(&self, seq: u32) -> Result> { 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 { 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 { 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 { 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 { 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 { use std::io::{Seek, SeekFrom}; let mut cloned = file.try_clone()?; cloned.seek(SeekFrom::Start(offset))?; cloned.read(out) }