Replace address-only trust and pushed peer state with installation identities, SPKI-pinned QUIC, candidate-only discovery, and bounded responder-owned protocol-8 pulls. The runtime now owns each network generation and all admitted work through shutdown. Add exact bundled content identities, reproducible manifest publishing, capability-confined downloads, streaming BLAKE3 verification, quarantine and retry, and crash-recoverable download and install transactions. Ship generated fixture catalogs and fail closed when production manifests are absent. The Tauri backend exposes durable sharing policy, redacted identity state, and attempt-keyed transfer snapshots. Frontend consumption follows in the next commit. Repository-wide test certificates and protocol-7 paths are removed. BREAKING CHANGE: peers must use protocol 8 and exact catalog content artifacts; protocol-7 frames and shared-certificate identities are no longer accepted. Test Plan: - `just test` -- passed on the completed stack (708 workspace tests) - `just clippy` -- passed on the completed stack - `just build` -- passed with fixture catalogs on the completed stack - `just catalog-check-production` -- failed closed because the external production manifest corpus is absent - `git diff --cached --check` -- passed
517 lines
16 KiB
Rust
517 lines
16 KiB
Rust
use std::{
|
|
convert::TryInto,
|
|
fs::File,
|
|
io::{self, Read, SeekFrom},
|
|
path::Path,
|
|
};
|
|
|
|
use bytes::Bytes;
|
|
use lanspread_utils::maybe_addr;
|
|
use s2n_quic::{
|
|
application,
|
|
connection,
|
|
stream::{Error as StreamError, SendStream},
|
|
};
|
|
use tokio::time::Instant;
|
|
|
|
use crate::{config::FILE_TRANSFER_BUFFER_SIZE, scoped_blocking::scoped_blocking};
|
|
|
|
const RAW_CHUNK_SEND_TIMEOUT: std::time::Duration = std::time::Duration::from_mins(10);
|
|
|
|
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
|
enum ChunkCloseOutcome {
|
|
Closed,
|
|
CleanRemoteClose,
|
|
}
|
|
|
|
trait RawChunkSend {
|
|
async fn send_chunk(&mut self, bytes: Bytes) -> Result<(), String>;
|
|
async fn close_chunk(&mut self) -> Result<ChunkCloseOutcome, String>;
|
|
fn reset_chunk(&mut self) -> Result<(), String>;
|
|
}
|
|
|
|
impl RawChunkSend for SendStream {
|
|
async fn send_chunk(&mut self, bytes: Bytes) -> Result<(), String> {
|
|
self.send(bytes).await.map_err(|error| error.to_string())
|
|
}
|
|
|
|
async fn close_chunk(&mut self) -> Result<ChunkCloseOutcome, String> {
|
|
match self.close().await {
|
|
Ok(()) => Ok(ChunkCloseOutcome::Closed),
|
|
Err(error) if is_clean_remote_close(&error) => Ok(ChunkCloseOutcome::CleanRemoteClose),
|
|
Err(error) => Err(error.to_string()),
|
|
}
|
|
}
|
|
|
|
fn reset_chunk(&mut self) -> Result<(), String> {
|
|
self.reset(application::Error::UNKNOWN)
|
|
.map_err(|error| error.to_string())
|
|
}
|
|
}
|
|
|
|
fn cancel_send_stream(tx: &mut impl RawChunkSend, remote_addr: &str, path: &Path) {
|
|
// Reset instead of finishing so truncated whole-file transfers cannot look like EOF.
|
|
if let Err(err) = tx.reset_chunk() {
|
|
log::debug!(
|
|
"{remote_addr} failed to reset cancelled transfer for {}: {err}",
|
|
path.display()
|
|
);
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Eq, PartialEq)]
|
|
pub(crate) enum FileReadOutcome {
|
|
BytesRead(usize),
|
|
Cancelled,
|
|
}
|
|
|
|
/// Completes one bounded read in the caller's task so cancellation cannot
|
|
/// detach filesystem work onto Tokio's blocking pool.
|
|
pub(crate) fn read_file_bytes_scoped(
|
|
cancel_token: &tokio_util::sync::CancellationToken,
|
|
reader: &mut impl Read,
|
|
buffer: &mut [u8],
|
|
) -> io::Result<FileReadOutcome> {
|
|
if cancel_token.is_cancelled() {
|
|
return Ok(FileReadOutcome::Cancelled);
|
|
}
|
|
|
|
let result = scoped_blocking(|| reader.read(buffer));
|
|
|
|
if cancel_token.is_cancelled() {
|
|
Ok(FileReadOutcome::Cancelled)
|
|
} else {
|
|
result.map(FileReadOutcome::BytesRead)
|
|
}
|
|
}
|
|
|
|
fn seek_file_scoped(file: &mut impl io::Seek, offset: u64) -> io::Result<()> {
|
|
scoped_blocking(|| io::Seek::seek(file, SeekFrom::Start(offset)).map(|_| ()))
|
|
}
|
|
|
|
#[allow(clippy::too_many_lines)]
|
|
async fn stream_file_bytes(
|
|
tx: &mut SendStream,
|
|
file: File,
|
|
display_path: &Path,
|
|
offset: u64,
|
|
length: u64,
|
|
cancel_token: tokio_util::sync::CancellationToken,
|
|
) -> eyre::Result<()> {
|
|
let remote_addr = format!("{}", maybe_addr!(tx.connection().remote_addr()));
|
|
stream_file_bytes_with_timeout(
|
|
tx,
|
|
file,
|
|
display_path,
|
|
offset,
|
|
length,
|
|
cancel_token,
|
|
&remote_addr,
|
|
RAW_CHUNK_SEND_TIMEOUT,
|
|
)
|
|
.await
|
|
}
|
|
|
|
#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
|
|
async fn stream_file_bytes_with_timeout(
|
|
tx: &mut impl RawChunkSend,
|
|
mut file: impl Read + io::Seek,
|
|
display_path: &Path,
|
|
offset: u64,
|
|
length: u64,
|
|
cancel_token: tokio_util::sync::CancellationToken,
|
|
remote_addr: &str,
|
|
send_timeout: std::time::Duration,
|
|
) -> eyre::Result<()> {
|
|
log::debug!(
|
|
"{remote_addr} streaming file bytes for peer: {}, offset: {offset}, length: {length}",
|
|
display_path.display()
|
|
);
|
|
|
|
if offset > 0
|
|
&& let Err(error) = seek_file_scoped(&mut file, offset)
|
|
{
|
|
cancel_send_stream(tx, remote_addr, display_path);
|
|
return Err(error.into());
|
|
}
|
|
|
|
let mut remaining = length;
|
|
let mut total_bytes = 0u64;
|
|
let mut last_total_bytes = 0u64;
|
|
let started = Instant::now();
|
|
let mut timestamp = Instant::now();
|
|
let mut buf = vec![0u8; FILE_TRANSFER_BUFFER_SIZE];
|
|
|
|
while remaining > 0 {
|
|
if cancel_token.is_cancelled() {
|
|
log::info!(
|
|
"{remote_addr} transfer cancelled for {}",
|
|
display_path.display()
|
|
);
|
|
cancel_send_stream(tx, remote_addr, display_path);
|
|
return Err(eyre::eyre!("File transfer cancelled by user"));
|
|
}
|
|
|
|
let read_len = std::cmp::min(remaining, buf.len() as u64);
|
|
let read_len: usize = read_len.try_into().unwrap_or(usize::MAX);
|
|
if read_len == 0 {
|
|
break;
|
|
}
|
|
|
|
let bytes_read =
|
|
match read_file_bytes_scoped(&cancel_token, &mut file, &mut buf[..read_len]) {
|
|
Err(error) => {
|
|
cancel_send_stream(tx, remote_addr, display_path);
|
|
return Err(error.into());
|
|
}
|
|
Ok(outcome) => match outcome {
|
|
FileReadOutcome::Cancelled => {
|
|
log::info!(
|
|
"{remote_addr} transfer cancelled for {}",
|
|
display_path.display()
|
|
);
|
|
cancel_send_stream(tx, remote_addr, display_path);
|
|
return Err(eyre::eyre!("File transfer cancelled by user"));
|
|
}
|
|
FileReadOutcome::BytesRead(bytes_read) => bytes_read,
|
|
},
|
|
};
|
|
if bytes_read == 0 {
|
|
cancel_send_stream(tx, remote_addr, display_path);
|
|
return Err(eyre::eyre!(
|
|
"catalog file became shorter while streaming {}: {remaining} bytes missing",
|
|
display_path.display()
|
|
));
|
|
}
|
|
|
|
tokio::select! {
|
|
() = cancel_token.cancelled() => {
|
|
log::info!(
|
|
"{remote_addr} transfer cancelled for {}",
|
|
display_path.display()
|
|
);
|
|
cancel_send_stream(tx, remote_addr, display_path);
|
|
return Err(eyre::eyre!("File transfer cancelled by user"));
|
|
}
|
|
() = tokio::time::sleep(send_timeout) => {
|
|
cancel_send_stream(tx, remote_addr, display_path);
|
|
return Err(eyre::eyre!(
|
|
"catalog chunk send timed out after {send_timeout:?} for {}",
|
|
display_path.display()
|
|
));
|
|
}
|
|
res = tx.send_chunk(Bytes::copy_from_slice(&buf[..bytes_read])) => {
|
|
if let Err(error) = res {
|
|
cancel_send_stream(tx, remote_addr, display_path);
|
|
return Err(eyre::eyre!(error));
|
|
}
|
|
}
|
|
}
|
|
remaining = remaining.saturating_sub(bytes_read as u64);
|
|
total_bytes += bytes_read as u64;
|
|
|
|
if remaining == 0 {
|
|
break;
|
|
}
|
|
|
|
if last_total_bytes + 10_000_000 < total_bytes {
|
|
let elapsed = timestamp.elapsed();
|
|
let diff_bytes = total_bytes - last_total_bytes;
|
|
|
|
if elapsed.as_secs_f64() >= 1.0 {
|
|
#[allow(clippy::cast_precision_loss)]
|
|
let mb_per_s = (diff_bytes as f64) / (elapsed.as_secs_f64() * 1_000_000.0);
|
|
log::debug!(
|
|
"{remote_addr} sending file data: {}, MB/s: {mb_per_s:.2}",
|
|
display_path.display()
|
|
);
|
|
last_total_bytes = total_bytes;
|
|
timestamp = Instant::now();
|
|
}
|
|
}
|
|
}
|
|
|
|
let elapsed = started.elapsed();
|
|
#[allow(clippy::cast_precision_loss)]
|
|
let mib_per_s = if elapsed.as_secs_f64() > 0.0 {
|
|
total_bytes as f64 / elapsed.as_secs_f64() / (1024.0 * 1024.0)
|
|
} else {
|
|
0.0
|
|
};
|
|
log::info!(
|
|
"{remote_addr} finished streaming file bytes: {}, total_bytes: {total_bytes}, MiB/s: {mib_per_s:.2}",
|
|
display_path.display()
|
|
);
|
|
|
|
tokio::select! {
|
|
() = cancel_token.cancelled() => {
|
|
log::info!("{remote_addr} transfer cancelled while closing stream");
|
|
cancel_send_stream(tx, remote_addr, display_path);
|
|
return Err(eyre::eyre!("File transfer cancelled by user"));
|
|
}
|
|
() = tokio::time::sleep(send_timeout) => {
|
|
cancel_send_stream(tx, remote_addr, display_path);
|
|
return Err(eyre::eyre!(
|
|
"catalog chunk close timed out after {send_timeout:?} for {}",
|
|
display_path.display()
|
|
));
|
|
}
|
|
res = tx.close_chunk() => {
|
|
match res {
|
|
Ok(ChunkCloseOutcome::Closed) => {}
|
|
Ok(ChunkCloseOutcome::CleanRemoteClose) => {
|
|
log::debug!("{remote_addr} closed stream after transfer completion");
|
|
}
|
|
Err(err) => {
|
|
cancel_send_stream(tx, remote_addr, display_path);
|
|
return Err(eyre::eyre!(err));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn is_clean_remote_close(err: &StreamError) -> bool {
|
|
matches!(
|
|
err,
|
|
StreamError::ConnectionError {
|
|
error: connection::Error::Closed { .. },
|
|
..
|
|
}
|
|
)
|
|
}
|
|
|
|
pub async fn send_game_file_chunk(
|
|
relative_path: &str,
|
|
offset: u64,
|
|
length: u64,
|
|
file: File,
|
|
tx: &mut SendStream,
|
|
cancel_token: tokio_util::sync::CancellationToken,
|
|
) -> eyre::Result<()> {
|
|
let result = stream_file_bytes(
|
|
tx,
|
|
file,
|
|
Path::new(relative_path),
|
|
offset,
|
|
length,
|
|
cancel_token,
|
|
)
|
|
.await;
|
|
if let Err(e) = &result {
|
|
let remote_addr = maybe_addr!(tx.connection().remote_addr());
|
|
log::error!(
|
|
"{remote_addr} failed to stream chunk {relative_path} offset {offset} length {length}: {e}"
|
|
);
|
|
}
|
|
result
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use std::{future::pending, io::Cursor, time::Duration};
|
|
|
|
use tokio_util::sync::CancellationToken;
|
|
|
|
use super::*;
|
|
|
|
#[derive(Clone, Copy)]
|
|
enum ControlledIo {
|
|
Ready,
|
|
Fail,
|
|
Pending,
|
|
}
|
|
|
|
struct ControlledSender {
|
|
send: ControlledIo,
|
|
close: ControlledIo,
|
|
reset_count: usize,
|
|
}
|
|
|
|
impl ControlledSender {
|
|
const fn new(send: ControlledIo, close: ControlledIo) -> Self {
|
|
Self {
|
|
send,
|
|
close,
|
|
reset_count: 0,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl RawChunkSend for ControlledSender {
|
|
async fn send_chunk(&mut self, _bytes: Bytes) -> Result<(), String> {
|
|
match self.send {
|
|
ControlledIo::Ready => Ok(()),
|
|
ControlledIo::Fail => Err("controlled send failure".to_string()),
|
|
ControlledIo::Pending => pending().await,
|
|
}
|
|
}
|
|
|
|
async fn close_chunk(&mut self) -> Result<ChunkCloseOutcome, String> {
|
|
match self.close {
|
|
ControlledIo::Ready => Ok(ChunkCloseOutcome::Closed),
|
|
ControlledIo::Fail => Err("controlled close failure".to_string()),
|
|
ControlledIo::Pending => pending().await,
|
|
}
|
|
}
|
|
|
|
fn reset_chunk(&mut self) -> Result<(), String> {
|
|
self.reset_count += 1;
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
struct ControlledReader {
|
|
bytes: Cursor<Vec<u8>>,
|
|
fail_read: bool,
|
|
fail_seek: bool,
|
|
}
|
|
|
|
impl ControlledReader {
|
|
fn bytes(bytes: &[u8]) -> Self {
|
|
Self {
|
|
bytes: Cursor::new(bytes.to_vec()),
|
|
fail_read: false,
|
|
fail_seek: false,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Read for ControlledReader {
|
|
fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
|
|
if self.fail_read {
|
|
return Err(io::Error::other("controlled read failure"));
|
|
}
|
|
Read::read(&mut self.bytes, buffer)
|
|
}
|
|
}
|
|
|
|
impl io::Seek for ControlledReader {
|
|
fn seek(&mut self, position: SeekFrom) -> io::Result<u64> {
|
|
if self.fail_seek {
|
|
return Err(io::Error::other("controlled seek failure"));
|
|
}
|
|
io::Seek::seek(&mut self.bytes, position)
|
|
}
|
|
}
|
|
|
|
async fn controlled_stream(
|
|
sender: &mut ControlledSender,
|
|
reader: ControlledReader,
|
|
offset: u64,
|
|
length: u64,
|
|
timeout: Duration,
|
|
) -> eyre::Result<()> {
|
|
stream_file_bytes_with_timeout(
|
|
sender,
|
|
reader,
|
|
Path::new("payload.bin"),
|
|
offset,
|
|
length,
|
|
CancellationToken::new(),
|
|
"controlled-peer",
|
|
timeout,
|
|
)
|
|
.await
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn seek_read_and_send_failures_reset_the_admitted_chunk() {
|
|
let mut seek_sender = ControlledSender::new(ControlledIo::Ready, ControlledIo::Ready);
|
|
let mut seek_reader = ControlledReader::bytes(b"payload");
|
|
seek_reader.fail_seek = true;
|
|
assert!(
|
|
controlled_stream(&mut seek_sender, seek_reader, 1, 1, Duration::from_secs(1))
|
|
.await
|
|
.is_err()
|
|
);
|
|
assert_eq!(seek_sender.reset_count, 1);
|
|
|
|
let mut read_sender = ControlledSender::new(ControlledIo::Ready, ControlledIo::Ready);
|
|
let mut read_reader = ControlledReader::bytes(b"payload");
|
|
read_reader.fail_read = true;
|
|
assert!(
|
|
controlled_stream(&mut read_sender, read_reader, 0, 1, Duration::from_secs(1))
|
|
.await
|
|
.is_err()
|
|
);
|
|
assert_eq!(read_sender.reset_count, 1);
|
|
|
|
let mut send_sender = ControlledSender::new(ControlledIo::Fail, ControlledIo::Ready);
|
|
assert!(
|
|
controlled_stream(
|
|
&mut send_sender,
|
|
ControlledReader::bytes(b"payload"),
|
|
0,
|
|
1,
|
|
Duration::from_secs(1)
|
|
)
|
|
.await
|
|
.is_err()
|
|
);
|
|
assert_eq!(send_sender.reset_count, 1);
|
|
}
|
|
|
|
#[tokio::test(start_paused = true)]
|
|
async fn blocked_send_and_close_hit_the_application_deadline_and_reset() {
|
|
let timeout = Duration::from_secs(30);
|
|
let mut send_sender = ControlledSender::new(ControlledIo::Pending, ControlledIo::Ready);
|
|
let send_error = controlled_stream(
|
|
&mut send_sender,
|
|
ControlledReader::bytes(b"payload"),
|
|
0,
|
|
1,
|
|
timeout,
|
|
)
|
|
.await
|
|
.expect_err("blocked send should time out");
|
|
assert!(send_error.to_string().contains("send timed out"));
|
|
assert_eq!(send_sender.reset_count, 1);
|
|
|
|
let mut close_sender = ControlledSender::new(ControlledIo::Ready, ControlledIo::Pending);
|
|
let close_error = controlled_stream(
|
|
&mut close_sender,
|
|
ControlledReader::bytes(&[]),
|
|
0,
|
|
0,
|
|
timeout,
|
|
)
|
|
.await
|
|
.expect_err("blocked close should time out");
|
|
assert!(close_error.to_string().contains("close timed out"));
|
|
assert_eq!(close_sender.reset_count, 1);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn short_file_and_close_failure_reset_instead_of_finishing() {
|
|
let mut short_sender = ControlledSender::new(ControlledIo::Ready, ControlledIo::Ready);
|
|
assert!(
|
|
controlled_stream(
|
|
&mut short_sender,
|
|
ControlledReader::bytes(&[]),
|
|
0,
|
|
1,
|
|
Duration::from_secs(1)
|
|
)
|
|
.await
|
|
.is_err()
|
|
);
|
|
assert_eq!(short_sender.reset_count, 1);
|
|
|
|
let mut close_sender = ControlledSender::new(ControlledIo::Ready, ControlledIo::Fail);
|
|
assert!(
|
|
controlled_stream(
|
|
&mut close_sender,
|
|
ControlledReader::bytes(&[]),
|
|
0,
|
|
0,
|
|
Duration::from_secs(1)
|
|
)
|
|
.await
|
|
.is_err()
|
|
);
|
|
assert_eq!(close_sender.reset_count, 1);
|
|
}
|
|
}
|