mirror of
https://github.com/ratspeak/rsReticulum
synced 2026-11-22 23:10:33 +00:00
resource: receive large transfers as a file; rncp takes any file size
An application that takes transfers only as bytes keeps its in-memory limit.
This commit is contained in:
1 parent
a91e5577d9
commit
4bfd0fa0fb
12 files changed
+1272
-144
No files matched your search
@@ -205,6 +205,27 @@ matches these errors exhaustively needs the new arms.
|
||||
- `ResourceError::DecompressedTooLarge`, `TransferAction` and
|
||||
`ResourceFlags::app_flag` are new. `InboundTransfer`, `OutboundTransfer` and
|
||||
`MultiSegmentInbound` gain public fields.
|
||||
- An inbound Resource can be received as a file of any size, not bound by the
|
||||
in-memory limit (`inbound_reassembly_limit`, 128 MiB - 1 by default). Each
|
||||
verified segment is appended to the file before its proof is sent, as
|
||||
`Resource.assemble` writes it (`RNS/Resource.py`), and a transfer that
|
||||
fails, is cancelled or cannot be written leaves no file behind. Additions,
|
||||
none of which changes a caller that takes bytes:
|
||||
- `LinkManager::set_resource_file_channel(dir, min_size, tx)` and
|
||||
`DestinationHandle::receive_resource_files(dir, min_size, capacity)`
|
||||
deliver `ResourceFileCompletion { path, size, .. }` for ordinary Resources
|
||||
that advertise `min_size` bytes or more. Without them a Resource above the
|
||||
in-memory limit is refused, as before.
|
||||
- `LinkSessionResourceOffer::accept_to_file(dir)` assembles the offer into
|
||||
a file and returns its path in `LinkSessionReceivedResource::file`.
|
||||
- A session now offers a Resource above its limit to the application
|
||||
instead of refusing it unseen. `accept` on such an offer rejects it with
|
||||
`LinkSessionResourceError::TooLarge`.
|
||||
|
||||
The receiver owns a delivered file and moves or removes it. Use the
|
||||
runtime's `storage/resources` directory (`StoragePaths::resource_dir`),
|
||||
where upstream keeps them; the cache job removes a spool left there by a
|
||||
crash after one day.
|
||||
|
||||
## Crypto
|
||||
|
||||
@@ -235,6 +256,12 @@ matches these errors exhaustively needs the new arms.
|
||||
for `--phy-rates` (`RNS/Utilities/rncp.py:331`).
|
||||
- `RncpError` gains `Interrupted`, `NotFound`, `RemoteError`, `RequestFailed`
|
||||
and `Stamp`.
|
||||
- `spawn_rncp_listener_with_resource_dir` and
|
||||
`rncp_fetch_file_with_resource_dir` name the directory a received or fetched
|
||||
file is assembled in before it is moved to the save directory, as rncp moves
|
||||
`resource.data` (`RNS/Utilities/rncp.py`). `rncp-rs` passes
|
||||
`storage/resources`; the functions without the argument use the system
|
||||
temporary directory. Neither holds the file in memory.
|
||||
- `rnsh::RnshError` is `#[non_exhaustive]`. `Denied` carries the remote
|
||||
message, `Denied(String)`, and the enum gains `ClientException`, `LinkClosed`,
|
||||
`ProtocolError`, `StampFailure` and `Terminated`
|
||||
|
||||
@@ -865,10 +865,9 @@ pub enum ResourceError {
|
||||
pub const MAX_RESOURCE_SIZE: usize = 134_217_727;
|
||||
|
||||
/// Default bound on the advertised total size of an inbound Resource that is
|
||||
/// reassembled in memory (128 MiB - 1). Local difference from upstream, which
|
||||
/// assembles every inbound Resource to storage and has no such bound
|
||||
/// (Resource.py). Streaming inbound reassembly to the
|
||||
/// consumer would remove the need for it.
|
||||
/// reassembled in memory (128 MiB - 1). Upstream assembles every inbound
|
||||
/// Resource into a file and has no such bound (Resource.py); a receiver that
|
||||
/// takes larger Resources as files is not bound by it either.
|
||||
pub const DEFAULT_INBOUND_REASSEMBLY_LIMIT: usize = MAX_RESOURCE_SIZE;
|
||||
|
||||
/// Former split-resource segment cap. The Resource protocol has no segment
|
||||
|
||||
@@ -48,7 +48,7 @@ below follow the `--`; networked examples also accept `--config DIRECTORY`.
|
||||
| `channel` | `server`, or `client HASH [MESSAGE]`. Exchanges a custom Channel message. |
|
||||
| `buffer` | `server`, or `client HASH [MESSAGE]`. Exchanges a short UTF-8 string using Buffer/stream frames and interoperates with upstream `Examples/Buffer.py`. Use the default short message; the server replies `I received "<text>" over the buffer` per received frame and is not an arbitrary-length echo protocol. |
|
||||
| `resource` | `server`, or `client HASH [MESSAGE]`. Transfers a Resource with progress reporting. |
|
||||
| `filetransfer` | `server NEW_OUTPUT_FILE`, or `client HASH INPUT_FILE`. Writes the first completed Resource to a new file and refuses to replace an existing file. |
|
||||
| `filetransfer` | `server NEW_OUTPUT_FILE`, or `client HASH INPUT_FILE`. Writes the first completed Resource to a new file and refuses to replace an existing file. A Resource of 1 MiB or more is received as a file of any size. |
|
||||
| `speedtest` | `server`, or `client HASH [BYTE_COUNT]`. Queues Link packets; the default is 2 MiB. |
|
||||
| `ratchets` | `IDENTITY_FILE RATCHET_FILE [MESSAGE]`. Local key persistence and encrypt/decrypt composition; it does not start a network runtime. |
|
||||
|
||||
|
||||
@@ -42,22 +42,48 @@ async fn server(args: ExampleArgs) -> ExampleResult {
|
||||
.await?;
|
||||
println!("The first completed transfer will be written to {output_path}");
|
||||
|
||||
let completed = tokio::select! {
|
||||
_ = runtime.shutdown.wait() => None,
|
||||
completed = destination.events.resource_completions.recv() => completed,
|
||||
};
|
||||
if let Some(completed) = completed {
|
||||
let mut output = OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&output_path)?;
|
||||
output.write_all(&completed.data)?;
|
||||
output.sync_all()?;
|
||||
println!(
|
||||
"Wrote {} bytes to {} without replacing an existing file",
|
||||
completed.data.len(),
|
||||
output_path,
|
||||
);
|
||||
// A Resource of 1 MiB or more arrives as a file of any size, assembled
|
||||
// where Reticulum keeps its Resources; a smaller one arrives as bytes.
|
||||
let resource_dir =
|
||||
rns_runtime::platform::StoragePaths::from_config_dir(&runtime.handle.config_dir)
|
||||
.resource_dir;
|
||||
let mut files = destination
|
||||
.handle
|
||||
.receive_resource_files(resource_dir, 1 << 20, 4)
|
||||
.await?;
|
||||
|
||||
tokio::select! {
|
||||
_ = runtime.shutdown.wait() => {}
|
||||
Some(completed) = destination.events.resource_completions.recv() => {
|
||||
let mut output = OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&output_path)?;
|
||||
output.write_all(&completed.data)?;
|
||||
output.sync_all()?;
|
||||
println!(
|
||||
"Wrote {} bytes to {} without replacing an existing file",
|
||||
completed.data.len(),
|
||||
output_path,
|
||||
);
|
||||
}
|
||||
Some(completed) = files.recv() => {
|
||||
// The received file is ours: copy it into place, then remove it.
|
||||
let copied = OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&output_path)
|
||||
.and_then(|mut output| {
|
||||
std::io::copy(&mut File::open(&completed.path)?, &mut output)?;
|
||||
output.sync_all()
|
||||
});
|
||||
std::fs::remove_file(&completed.path)?;
|
||||
copied?;
|
||||
println!(
|
||||
"Wrote {} bytes to {} without replacing an existing file",
|
||||
completed.size, output_path,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
destination.close().await?;
|
||||
|
||||
@@ -24,7 +24,7 @@ use crate::link_manager::{
|
||||
DestinationAnnounceOptions, DestinationControlError, DestinationRequest, LinkChannelMessage,
|
||||
LinkManager, LinkManagerCommand, LinkPacketProof, LinkPacketSendReceipt,
|
||||
LinkPayloadSendReceipt, LinkResourceEvent, LinkResourceProof, LinkResourceSendReceipt,
|
||||
LinkSendError, RequestOutcome, ResourceCompletion,
|
||||
LinkSendError, RequestOutcome, ResourceCompletion, ResourceFileCompletion,
|
||||
};
|
||||
|
||||
const DEFAULT_EVENT_CAPACITY: usize = 128;
|
||||
@@ -52,8 +52,10 @@ pub struct DestinationRuntimeOptions {
|
||||
pub stamp_value: Option<f64>,
|
||||
/// Announced link-request cost (Python `Destination.set_link_cost`).
|
||||
pub link_cost: Option<f64>,
|
||||
/// Largest advertised total size of an inbound Resource, which the
|
||||
/// destination reassembles in memory; `None` accepts any size. See
|
||||
/// Largest advertised total size of an inbound Resource the destination
|
||||
/// reassembles in memory; `None` reassembles any size. A larger Resource
|
||||
/// is refused unless [`DestinationHandle::receive_resource_files`] takes
|
||||
/// it as a file. See
|
||||
/// [`rns_protocol::resource::DEFAULT_INBOUND_REASSEMBLY_LIMIT`].
|
||||
pub inbound_reassembly_limit: Option<usize>,
|
||||
/// Exact endpoint dispatch from the same runtime
|
||||
@@ -403,6 +405,41 @@ impl DestinationHandle {
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)
|
||||
}
|
||||
|
||||
/// Receive ordinary inbound Resources that advertise `min_size` bytes or
|
||||
/// more as files in `dir`, whatever their size; they are not bound by
|
||||
/// [`DestinationRuntimeOptions::inbound_reassembly_limit`]. Smaller ones
|
||||
/// still arrive on [`DestinationEvents::resource_completions`]. Use the
|
||||
/// runtime's `storage/resources` directory (`StoragePaths::resource_dir`),
|
||||
/// where upstream assembles Resources, unless the application has its own.
|
||||
/// See
|
||||
/// [`LinkManager::set_resource_file_channel`](crate::link_manager::LinkManager::set_resource_file_channel).
|
||||
/// Drain the receiver: each file belongs to whoever receives it.
|
||||
pub async fn receive_resource_files(
|
||||
&self,
|
||||
dir: impl Into<PathBuf>,
|
||||
min_size: usize,
|
||||
capacity: usize,
|
||||
) -> Result<mpsc::Receiver<ResourceFileCompletion>, DestinationRuntimeError> {
|
||||
if capacity == 0 {
|
||||
return Err(DestinationRuntimeError::InvalidEventCapacity);
|
||||
}
|
||||
let (files_tx, files_rx) = mpsc::channel(capacity);
|
||||
let (result_tx, result_rx) = oneshot::channel();
|
||||
self.command_tx
|
||||
.send(LinkManagerCommand::SetResourceFileChannel {
|
||||
dir: dir.into(),
|
||||
min_size,
|
||||
files_tx,
|
||||
result_tx: Some(result_tx),
|
||||
})
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)?;
|
||||
result_rx
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)?;
|
||||
Ok(files_rx)
|
||||
}
|
||||
|
||||
pub async fn deregister_request_handler(
|
||||
&self,
|
||||
path: impl Into<String>,
|
||||
|
||||
@@ -22,6 +22,7 @@ pub mod platform;
|
||||
pub mod probe;
|
||||
pub mod remote_management;
|
||||
pub mod resource_source;
|
||||
mod resource_spool;
|
||||
pub mod reticulum;
|
||||
pub mod rncp;
|
||||
pub mod rnsh;
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -37,6 +37,7 @@ use crate::resource_source::{
|
||||
PreparedResourceSegment, PreparedResourceSource, ResourceOptions, ResourceSource,
|
||||
ResourceSourceError,
|
||||
};
|
||||
use crate::resource_spool::{ResourceSpool, spool_dir};
|
||||
|
||||
const COMMAND_BUFFER: usize = 64;
|
||||
const EVENT_BUFFER: usize = 256;
|
||||
@@ -67,12 +68,14 @@ pub struct LinkSessionConfig {
|
||||
/// is an OUT destination, which Python leaves at `PROVE_NONE`; `ProveApp`
|
||||
/// has no callback here and proves nothing.
|
||||
pub proof_strategy: ProofStrategy,
|
||||
/// Where file responses are spooled by default, as Reticulum.resourcepath;
|
||||
/// the system temp dir when unset.
|
||||
/// Where file responses and Resources accepted to a file are written by
|
||||
/// default, as Reticulum.resourcepath; the system temp dir when unset.
|
||||
pub resource_dir: Option<PathBuf>,
|
||||
/// Largest advertised total size of an inbound Resource the session
|
||||
/// reassembles in memory; `None` accepts any size. Spooled responses are
|
||||
/// not bounded by it. See [`DEFAULT_INBOUND_REASSEMBLY_LIMIT`].
|
||||
/// reassembles in memory; `None` reassembles any size. Spooled responses
|
||||
/// and Resources accepted with
|
||||
/// [`LinkSessionResourceOffer::accept_to_file`] are not bounded by it. See
|
||||
/// [`DEFAULT_INBOUND_REASSEMBLY_LIMIT`].
|
||||
pub inbound_reassembly_limit: Option<usize>,
|
||||
}
|
||||
|
||||
@@ -296,7 +299,10 @@ pub struct LinkSessionReceivedResource {
|
||||
pub link_id: [u8; 16],
|
||||
pub resource_id: [u8; 32],
|
||||
pub data: Vec<u8>,
|
||||
/// Set instead of `data` when a request response was spooled to disk.
|
||||
/// Set instead of `data` when a request response was spooled to disk or
|
||||
/// the offer was accepted with
|
||||
/// [`LinkSessionResourceOffer::accept_to_file`]. The receiver owns the
|
||||
/// file: move it or remove it.
|
||||
pub file: Option<PathBuf>,
|
||||
pub metadata: Option<Vec<u8>>,
|
||||
pub total_segments: usize,
|
||||
@@ -313,8 +319,9 @@ pub struct LinkSessionReceivedResource {
|
||||
/// Dropping an offer leaves this expiry in force and does not accept data.
|
||||
/// Acceptance covers the logical transfer and valid follow-up segments.
|
||||
/// Response Resources for pending requests are accepted internally, without an
|
||||
/// offer. Inspect advertised size before accepting; completed inbound data is
|
||||
/// assembled in memory.
|
||||
/// offer. Inspect the advertised size before accepting: `accept` assembles the
|
||||
/// data in memory, up to the session's in-memory limit, and `accept_to_file`
|
||||
/// assembles any size into a file.
|
||||
pub struct LinkSessionResourceOffer {
|
||||
link_id: [u8; 16],
|
||||
resource_id: [u8; 32],
|
||||
@@ -361,8 +368,32 @@ impl LinkSessionResourceOffer {
|
||||
self.is_response
|
||||
}
|
||||
|
||||
/// Accept the Resource and receive its data in memory. An offer above
|
||||
/// [`LinkSessionConfig::inbound_reassembly_limit`] is rejected with
|
||||
/// [`LinkSessionResourceError::TooLarge`]; use [`Self::accept_to_file`].
|
||||
pub async fn accept(
|
||||
self,
|
||||
) -> Result<LinkSessionInboundResourceHandle, LinkSessionResourceError> {
|
||||
self.accept_with(None).await
|
||||
}
|
||||
|
||||
/// Accept the Resource into a file, whatever its size, as upstream
|
||||
/// assembles every Resource under `Reticulum.resourcepath` (Resource.py).
|
||||
/// The file is written in `dir`, or in the session's resource directory.
|
||||
/// Each verified segment is appended before its proof is sent, so one
|
||||
/// segment at a time is held in memory. `concluded` returns the path in
|
||||
/// [`LinkSessionReceivedResource::file`] with empty `data`; a transfer
|
||||
/// that fails, is cancelled or cannot be written leaves no file behind.
|
||||
pub async fn accept_to_file(
|
||||
self,
|
||||
dir: Option<PathBuf>,
|
||||
) -> Result<LinkSessionInboundResourceHandle, LinkSessionResourceError> {
|
||||
self.accept_with(Some(dir)).await
|
||||
}
|
||||
|
||||
async fn accept_with(
|
||||
self,
|
||||
file_dir: Option<Option<PathBuf>>,
|
||||
) -> Result<LinkSessionInboundResourceHandle, LinkSessionResourceError> {
|
||||
let (progress_tx, progress_rx) = watch::channel(0.0);
|
||||
let (conclusion_tx, conclusion_rx) = oneshot::channel();
|
||||
@@ -371,6 +402,7 @@ impl LinkSessionResourceOffer {
|
||||
.send(LinkSessionCommand::Resource(
|
||||
LinkSessionResourceCommand::AcceptInbound {
|
||||
segment_hash: self.segment_hash,
|
||||
file_dir,
|
||||
progress_tx,
|
||||
conclusion_tx,
|
||||
result_tx,
|
||||
@@ -410,8 +442,8 @@ impl LinkSessionResourceOffer {
|
||||
}
|
||||
|
||||
/// Lifecycle handle for an accepted inbound Resource. `concluded` returns the
|
||||
/// complete in-memory payload after assembly and local proof admission; the
|
||||
/// application still owns processing and persistence. Dropping this handle
|
||||
/// complete payload, in memory or as a file, after assembly and local proof
|
||||
/// admission; the application still owns processing and persistence. Dropping this handle
|
||||
/// does not cancel reception. `cancel` returns whether a live logical transfer
|
||||
/// was removed locally, not an acknowledgment from its sender. Progress is a
|
||||
/// coalescing estimate; only `concluded` establishes success.
|
||||
@@ -626,6 +658,8 @@ enum LinkSessionResourceCommand {
|
||||
},
|
||||
AcceptInbound {
|
||||
segment_hash: [u8; 32],
|
||||
/// `Some` assembles into a file, in the given or the default directory.
|
||||
file_dir: Option<Option<PathBuf>>,
|
||||
progress_tx: watch::Sender<f64>,
|
||||
conclusion_tx:
|
||||
oneshot::Sender<Result<LinkSessionReceivedResource, LinkSessionResourceError>>,
|
||||
@@ -765,6 +799,9 @@ struct SessionInboundLogical {
|
||||
reported_bytes: usize,
|
||||
reported_progress: f64,
|
||||
spool: Option<ResponseSpool>,
|
||||
/// The file of a Resource accepted to a file. Dropping it unfinished
|
||||
/// removes the partial file.
|
||||
file: Option<ResourceSpool>,
|
||||
/// Payload bytes assembled so far.
|
||||
received_bytes: usize,
|
||||
/// RequestReceipt.max_response_size, enforced on received bytes too.
|
||||
@@ -781,6 +818,8 @@ struct InboundResourceLifecycle {
|
||||
progress_tx: watch::Sender<f64>,
|
||||
conclusion_tx: oneshot::Sender<Result<LinkSessionReceivedResource, LinkSessionResourceError>>,
|
||||
spool: Option<ResponseSpool>,
|
||||
/// Directory of a Resource accepted to a file.
|
||||
file_dir: Option<PathBuf>,
|
||||
max_bytes: Option<usize>,
|
||||
segment_gap_timeout: Option<Duration>,
|
||||
}
|
||||
@@ -1978,10 +2017,13 @@ async fn handle_resource_command(
|
||||
}
|
||||
LinkSessionResourceCommand::AcceptInbound {
|
||||
segment_hash,
|
||||
file_dir,
|
||||
progress_tx,
|
||||
conclusion_tx,
|
||||
result_tx,
|
||||
} => {
|
||||
let file_dir = file_dir
|
||||
.map(|dir| dir.unwrap_or_else(|| spool_dir(resources.resource_dir.as_deref())));
|
||||
let result = accept_inbound_offer(
|
||||
transport_tx,
|
||||
attached_interface,
|
||||
@@ -1993,6 +2035,7 @@ async fn handle_resource_command(
|
||||
progress_tx,
|
||||
conclusion_tx,
|
||||
spool: None,
|
||||
file_dir,
|
||||
max_bytes: None,
|
||||
segment_gap_timeout: None,
|
||||
},
|
||||
@@ -2685,6 +2728,27 @@ async fn accept_inbound_offer(
|
||||
if advertisement.segment_index != 1 || resources.inbound_logicals.contains_key(&resource_id) {
|
||||
return Err(LinkSessionResourceError::OfferExpired);
|
||||
}
|
||||
// Only a file can take a Resource above the in-memory limit.
|
||||
if lifecycle.spool.is_none()
|
||||
&& lifecycle.file_dir.is_none()
|
||||
&& let Some(max) = resources.inbound_reassembly_limit
|
||||
&& advertisement.data_size > max
|
||||
{
|
||||
send_resource_action(
|
||||
transport_tx,
|
||||
attached_interface,
|
||||
link,
|
||||
TransferAction::SendCancel(CancelType::Rcl, segment_hash),
|
||||
)
|
||||
.await?;
|
||||
resources
|
||||
.rejected_inbound
|
||||
.insert(resource_id, Instant::now());
|
||||
return Err(LinkSessionResourceError::TooLarge {
|
||||
size: advertisement.data_size as u64,
|
||||
max,
|
||||
});
|
||||
}
|
||||
|
||||
let mut transfer =
|
||||
inbound_transfer_from_advertisement(&advertisement, link, resources.last_inbound)?;
|
||||
@@ -2707,9 +2771,13 @@ async fn accept_inbound_offer(
|
||||
let coordinator = (advertisement.total_segments > 1).then(|| {
|
||||
MultiSegmentInbound::new(advertisement.total_segments, advertisement.original_hash)
|
||||
});
|
||||
let in_memory_limit = match lifecycle.spool {
|
||||
Some(_) => None,
|
||||
None => resources.inbound_reassembly_limit,
|
||||
let file = lifecycle
|
||||
.file_dir
|
||||
.as_deref()
|
||||
.map(|dir| ResourceSpool::new(dir, &resource_id));
|
||||
let in_memory_limit = match (&lifecycle.spool, &file) {
|
||||
(None, None) => resources.inbound_reassembly_limit,
|
||||
_ => None,
|
||||
};
|
||||
let size_bound = advertisement
|
||||
.data_size
|
||||
@@ -2729,6 +2797,7 @@ async fn accept_inbound_offer(
|
||||
reported_bytes: 0,
|
||||
reported_progress: 0.0,
|
||||
spool: lifecycle.spool,
|
||||
file,
|
||||
received_bytes: 0,
|
||||
max_bytes: lifecycle.max_bytes,
|
||||
segment_gap_since: None,
|
||||
@@ -2805,9 +2874,15 @@ fn conclude_inbound_resource(
|
||||
let Some(logical) = resources.inbound_logicals.remove(&resource_id) else {
|
||||
return;
|
||||
};
|
||||
// A failed spool is removed by its writer's owner once the writer ends.
|
||||
// A failed spool is removed by its writer's owner once the writer ends;
|
||||
// a failed file is removed when `logical` drops.
|
||||
let succeeded = result.is_ok();
|
||||
let _ = logical.conclusion_tx.send(result);
|
||||
if let Err(Ok(received)) = logical.conclusion_tx.send(result)
|
||||
&& let Some(path) = received.file
|
||||
{
|
||||
// The handle is gone, so nobody else can remove the file.
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
let _ = event_tx.try_send(LinkSessionEvent::ResourceConcluded {
|
||||
resource_id,
|
||||
direction: LinkSessionResourceDirection::Inbound,
|
||||
@@ -3101,7 +3176,7 @@ async fn process_inbound_resource_advertisement(
|
||||
advertisement
|
||||
.flags
|
||||
.has_metadata
|
||||
.then(|| default_spool_dir(resources.resource_dir.as_deref()))
|
||||
.then(|| spool_dir(resources.resource_dir.as_deref()))
|
||||
})
|
||||
.and_then(|dir| open_response_spool(&dir, &resource_id));
|
||||
let (spool, writer) = match spool {
|
||||
@@ -3160,6 +3235,7 @@ async fn process_inbound_resource_advertisement(
|
||||
progress_tx,
|
||||
conclusion_tx,
|
||||
spool,
|
||||
file_dir: None,
|
||||
max_bytes,
|
||||
segment_gap_timeout,
|
||||
},
|
||||
@@ -3181,12 +3257,11 @@ async fn process_inbound_resource_advertisement(
|
||||
return matches!(result, Err(LinkSessionResourceError::TransportUnavailable));
|
||||
}
|
||||
|
||||
// An offer above the in-memory limit still reaches the application,
|
||||
// which can take it as a file.
|
||||
if advertisement.segment_index != 1
|
||||
|| has_pending_logical
|
||||
|| resources.pending_inbound.len() >= MAX_PENDING_RESOURCE_OFFERS
|
||||
|| resources
|
||||
.inbound_reassembly_limit
|
||||
.is_some_and(|limit| advertisement.data_size > limit)
|
||||
{
|
||||
return matches!(
|
||||
send_resource_action(
|
||||
@@ -3390,6 +3465,32 @@ async fn complete_inbound_segment(
|
||||
fail_inbound_logical(link, resources, event_tx, resource_id, error);
|
||||
return transport_failed;
|
||||
}
|
||||
// Resource.assemble writes the segment before Resource.prove: a failed
|
||||
// write sends neither a proof nor a cancel, and the Link stays up.
|
||||
let segment_len = data.len();
|
||||
let data = match resources
|
||||
.inbound_logicals
|
||||
.get_mut(&resource_id)
|
||||
.and_then(|logical| logical.file.as_mut())
|
||||
{
|
||||
Some(file) => {
|
||||
if let Err(error) = file.append(&data) {
|
||||
tracing::error!(%error, "could not write received Resource data");
|
||||
fail_inbound_logical(
|
||||
link,
|
||||
resources,
|
||||
event_tx,
|
||||
resource_id,
|
||||
LinkSessionResourceError::Failed(format!(
|
||||
"could not write Resource data: {error}"
|
||||
)),
|
||||
);
|
||||
return false;
|
||||
}
|
||||
Vec::new()
|
||||
}
|
||||
None => data,
|
||||
};
|
||||
if let Err(error) = send_resource_action(
|
||||
transport_tx,
|
||||
attached_interface,
|
||||
@@ -3416,7 +3517,7 @@ async fn complete_inbound_segment(
|
||||
logical.current_segment = None;
|
||||
logical.received_bytes = logical
|
||||
.received_bytes
|
||||
.saturating_add(data.len())
|
||||
.saturating_add(segment_len)
|
||||
.saturating_add(metadata_size);
|
||||
if let Some(max) = logical.max_bytes
|
||||
&& logical.received_bytes > max
|
||||
@@ -3480,10 +3581,13 @@ async fn complete_inbound_segment(
|
||||
let Some(data) = complete_data else {
|
||||
return false;
|
||||
};
|
||||
let Some(logical) = resources.inbound_logicals.get(&resource_id) else {
|
||||
let Some(logical) = resources.inbound_logicals.get_mut(&resource_id) else {
|
||||
return false;
|
||||
};
|
||||
let file = logical.spool.as_ref().map(|spool| spool.path.clone());
|
||||
let file = match logical.file.take() {
|
||||
Some(file) => Some(file.finish().0),
|
||||
None => logical.spool.as_ref().map(|spool| spool.path.clone()),
|
||||
};
|
||||
let received = LinkSessionReceivedResource {
|
||||
link_id: link.link_id,
|
||||
resource_id,
|
||||
@@ -4238,15 +4342,6 @@ fn deliver_session_response(
|
||||
|
||||
type SpoolWriter = oneshot::Receiver<std::io::Result<()>>;
|
||||
|
||||
/// Resource.storagepath's directory: the runtime's `storage/resources`,
|
||||
/// or the system temporary directory without a runtime.
|
||||
fn default_spool_dir(resource_dir: Option<&std::path::Path>) -> PathBuf {
|
||||
resource_dir
|
||||
.filter(|dir| dir.is_dir())
|
||||
.map(std::path::Path::to_path_buf)
|
||||
.unwrap_or_else(std::env::temp_dir)
|
||||
}
|
||||
|
||||
fn open_response_spool(
|
||||
dir: &std::path::Path,
|
||||
resource_id: &[u8; 32],
|
||||
@@ -5063,11 +5158,13 @@ mod tests {
|
||||
|
||||
/// An ordinary inbound Resource of `data` advertising `advertised` bytes,
|
||||
/// offered to a session with the given reassembly limit and accepted when
|
||||
/// offered. Returns the control packet contexts sent and the conclusion.
|
||||
/// offered, into a file when `file_dir` is given. Returns the control
|
||||
/// packet contexts sent and the conclusion, or why it was not accepted.
|
||||
async fn drive_session_inbound(
|
||||
data: Vec<u8>,
|
||||
advertised: usize,
|
||||
limit: Option<usize>,
|
||||
file_dir: Option<PathBuf>,
|
||||
) -> (
|
||||
Vec<rns_wire::context::PacketContext>,
|
||||
Option<Result<LinkSessionReceivedResource, LinkSessionResourceError>>,
|
||||
@@ -5124,7 +5221,7 @@ mod tests {
|
||||
if offer_rx.try_recv().is_ok() {
|
||||
let (progress_tx, _progress_rx) = watch::channel(0.0);
|
||||
let (conclusion_tx, mut conclusion_rx) = oneshot::channel();
|
||||
accept_inbound_offer(
|
||||
let accepted = accept_inbound_offer(
|
||||
&transport_tx,
|
||||
1,
|
||||
&mut initiator,
|
||||
@@ -5135,24 +5232,29 @@ mod tests {
|
||||
progress_tx,
|
||||
conclusion_tx,
|
||||
spool: None,
|
||||
file_dir,
|
||||
max_bytes: None,
|
||||
segment_gap_timeout: None,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
for part in sender.resource.parts.clone() {
|
||||
handle_inbound_resource_part(
|
||||
&transport_tx,
|
||||
1,
|
||||
&mut initiator,
|
||||
&mut resources,
|
||||
&event_tx,
|
||||
&part,
|
||||
)
|
||||
.await;
|
||||
.await;
|
||||
match accepted {
|
||||
Ok(()) => {
|
||||
for part in sender.resource.parts.clone() {
|
||||
handle_inbound_resource_part(
|
||||
&transport_tx,
|
||||
1,
|
||||
&mut initiator,
|
||||
&mut resources,
|
||||
&event_tx,
|
||||
&part,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
conclusion = conclusion_rx.try_recv().ok();
|
||||
}
|
||||
Err(error) => conclusion = Some(Err(error)),
|
||||
}
|
||||
conclusion = conclusion_rx.try_recv().ok();
|
||||
}
|
||||
drop(transport_tx);
|
||||
let mut contexts = Vec::new();
|
||||
@@ -5189,24 +5291,134 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn inbound_resource_above_session_reassembly_limit_is_refused() {
|
||||
async fn inbound_resource_above_session_reassembly_limit_needs_a_file() {
|
||||
let data = vec![0x5C; 4000];
|
||||
let limit = Some(data.len() - 1);
|
||||
let (contexts, conclusion) =
|
||||
drive_session_inbound(data.clone(), data.len(), Some(data.len() - 1)).await;
|
||||
drive_session_inbound(data.clone(), data.len(), limit, None).await;
|
||||
assert_eq!(
|
||||
contexts,
|
||||
vec![rns_wire::context::PacketContext::ResourceRcl]
|
||||
);
|
||||
assert!(conclusion.is_none(), "a refused Resource is never offered");
|
||||
assert!(
|
||||
matches!(
|
||||
conclusion,
|
||||
Some(Err(LinkSessionResourceError::TooLarge {
|
||||
size: 4000,
|
||||
max: 3999
|
||||
}))
|
||||
),
|
||||
"accepting into memory above the limit is refused: {conclusion:?}"
|
||||
);
|
||||
|
||||
let (_, conclusion) = drive_session_inbound(data.clone(), data.len(), None).await;
|
||||
let (_, conclusion) = drive_session_inbound(data.clone(), data.len(), None, None).await;
|
||||
assert_eq!(conclusion.unwrap().unwrap().data, data);
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (contexts, conclusion) =
|
||||
drive_session_inbound(data.clone(), data.len(), limit, Some(dir.path().into())).await;
|
||||
assert_eq!(
|
||||
contexts.last(),
|
||||
Some(&rns_wire::context::PacketContext::ResourcePrf)
|
||||
);
|
||||
let received = conclusion.unwrap().unwrap();
|
||||
assert!(received.data.is_empty());
|
||||
let path = received
|
||||
.file
|
||||
.expect("the Resource is handed over as a file");
|
||||
assert!(path.starts_with(dir.path()));
|
||||
assert!(std::fs::read(&path).unwrap() == data);
|
||||
assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn inbound_resource_accepted_to_a_file_leaves_nothing_behind_on_failure() {
|
||||
let data = vec![0x5E; 4000];
|
||||
|
||||
// More data than advertised: cancelled, not proved.
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (contexts, conclusion) =
|
||||
drive_session_inbound(data.clone(), 3999, Some(0), Some(dir.path().into())).await;
|
||||
assert!(matches!(
|
||||
conclusion,
|
||||
Some(Err(LinkSessionResourceError::Failed(_)))
|
||||
));
|
||||
assert!(!contexts.contains(&rns_wire::context::PacketContext::ResourcePrf));
|
||||
assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0);
|
||||
|
||||
// A directory that cannot be written: Resource.assemble marks the
|
||||
// Resource corrupt, which sends neither a proof nor a cancel.
|
||||
let missing = dir.path().join("absent");
|
||||
let (contexts, conclusion) =
|
||||
drive_session_inbound(data.clone(), data.len(), Some(0), Some(missing)).await;
|
||||
assert!(matches!(
|
||||
conclusion,
|
||||
Some(Err(LinkSessionResourceError::Failed(_)))
|
||||
));
|
||||
assert!(
|
||||
contexts
|
||||
.iter()
|
||||
.all(|context| *context == rns_wire::context::PacketContext::ResourceReq),
|
||||
"only part requests are sent: {contexts:?}"
|
||||
);
|
||||
assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0);
|
||||
|
||||
// The handle is gone before the transfer ends: nobody can take the file.
|
||||
let (progress_tx, _progress_rx) = watch::channel(0.0);
|
||||
let (conclusion_tx, conclusion_rx) = oneshot::channel();
|
||||
drop(conclusion_rx);
|
||||
let mut file = ResourceSpool::new(dir.path(), &[9; 32]);
|
||||
file.append(&data).unwrap();
|
||||
let path = file.finish().0;
|
||||
let mut resources = SessionResources::default();
|
||||
resources.inbound_logicals.insert(
|
||||
[9; 32],
|
||||
SessionInboundLogical {
|
||||
data_size: data.len(),
|
||||
total_segments: 1,
|
||||
request_id: None,
|
||||
is_request: false,
|
||||
is_response: false,
|
||||
progress_tx,
|
||||
conclusion_tx,
|
||||
coordinator: None,
|
||||
current_segment: None,
|
||||
reported_bytes: 0,
|
||||
reported_progress: 0.0,
|
||||
spool: None,
|
||||
file: None,
|
||||
received_bytes: 0,
|
||||
max_bytes: None,
|
||||
segment_gap_since: None,
|
||||
segment_gap_timeout: None,
|
||||
size_bound: data.len(),
|
||||
},
|
||||
);
|
||||
let (event_tx, _event_rx) = mpsc::channel(4);
|
||||
conclude_inbound_resource(
|
||||
&mut resources,
|
||||
&event_tx,
|
||||
[9; 32],
|
||||
Ok(LinkSessionReceivedResource {
|
||||
link_id: [0; 16],
|
||||
resource_id: [9; 32],
|
||||
data: Vec::new(),
|
||||
file: Some(path.clone()),
|
||||
metadata: None,
|
||||
total_segments: 1,
|
||||
request_id: None,
|
||||
is_request: false,
|
||||
is_response: false,
|
||||
}),
|
||||
);
|
||||
assert!(!path.exists());
|
||||
assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn inbound_resource_sending_more_than_advertised_is_cut_off() {
|
||||
let data = vec![0x5D; 4000];
|
||||
let (contexts, conclusion) = drive_session_inbound(data, 3999, None).await;
|
||||
let (contexts, conclusion) = drive_session_inbound(data, 3999, None, None).await;
|
||||
assert!(matches!(
|
||||
conclusion,
|
||||
Some(Err(LinkSessionResourceError::Failed(_)))
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
//! An inbound Resource assembled into a file, as `Resource.assemble` appends
|
||||
//! each verified segment to `Resource.storagepath` (Resource.py).
|
||||
|
||||
use std::fs::File;
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
const NONCE_LEN: usize = 8;
|
||||
const HASH_HEX_LEN: usize = 64;
|
||||
|
||||
/// The file one inbound Resource is assembled into. Dropping it removes the
|
||||
/// file unless [`ResourceSpool::finish`] handed it over.
|
||||
pub(crate) struct ResourceSpool {
|
||||
path: PathBuf,
|
||||
file: Option<File>,
|
||||
len: u64,
|
||||
keep: bool,
|
||||
}
|
||||
|
||||
impl ResourceSpool {
|
||||
/// Name a spool for `resource_id` in `dir`. The file is created by the
|
||||
/// first [`Self::append`], as upstream opens it when a segment is assembled.
|
||||
pub(crate) fn new(dir: &Path, resource_id: &[u8; 32]) -> Self {
|
||||
// The id is chosen by the peer and the directory may be shared: the
|
||||
// suffix keeps two transfers of one Resource in separate files.
|
||||
let nonce = rns_crypto::random::random_bytes(NONCE_LEN);
|
||||
Self {
|
||||
path: dir.join(format!(
|
||||
"{}-{}",
|
||||
hex::encode(resource_id),
|
||||
hex::encode(nonce)
|
||||
)),
|
||||
file: None,
|
||||
len: 0,
|
||||
keep: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Append one verified segment. An error leaves the spool unusable; the
|
||||
/// owner drops it, which removes the partial file.
|
||||
pub(crate) fn append(&mut self, data: &[u8]) -> std::io::Result<()> {
|
||||
if self.file.is_none() {
|
||||
let mut options = std::fs::OpenOptions::new();
|
||||
// Never reuse or follow an existing entry.
|
||||
options.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
|
||||
self.file = Some(options.open(&self.path)?);
|
||||
}
|
||||
let file = self.file.as_mut().expect("spool file was just opened");
|
||||
file.write_all(data)?;
|
||||
self.len = self.len.saturating_add(data.len() as u64);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Payload bytes written so far.
|
||||
pub(crate) fn len(&self) -> u64 {
|
||||
self.len
|
||||
}
|
||||
|
||||
/// Close the file and hand it to the caller, who then owns and removes it.
|
||||
pub(crate) fn finish(mut self) -> (PathBuf, u64) {
|
||||
self.keep = true;
|
||||
self.file = None;
|
||||
(std::mem::take(&mut self.path), self.len)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ResourceSpool {
|
||||
fn drop(&mut self) {
|
||||
if self.keep {
|
||||
return;
|
||||
}
|
||||
// Close before removing: an open file cannot be removed on Windows.
|
||||
if self.file.take().is_some() {
|
||||
let _ = std::fs::remove_file(&self.path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `Reticulum.resourcepath` when it exists, else the system temporary
|
||||
/// directory (a session or manager used without a runtime).
|
||||
pub(crate) fn spool_dir(resource_dir: Option<&Path>) -> PathBuf {
|
||||
resource_dir
|
||||
.filter(|dir| dir.is_dir())
|
||||
.map(Path::to_path_buf)
|
||||
.unwrap_or_else(std::env::temp_dir)
|
||||
}
|
||||
|
||||
/// Whether `name` is a spool file name, `<64 hex>-<16 hex>`. The cache cleaner
|
||||
/// removes stale ones a crash left behind, as it does upstream's hash-named
|
||||
/// files.
|
||||
pub(crate) fn is_spool_name(name: &[u8]) -> bool {
|
||||
let hex = |bytes: &[u8]| bytes.iter().all(u8::is_ascii_hexdigit);
|
||||
name.len() == HASH_HEX_LEN + 1 + NONCE_LEN * 2
|
||||
&& name[HASH_HEX_LEN] == b'-'
|
||||
&& hex(&name[..HASH_HEX_LEN])
|
||||
&& hex(&name[HASH_HEX_LEN + 1..])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn entries(dir: &Path) -> usize {
|
||||
std::fs::read_dir(dir).unwrap().count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finished_spool_holds_the_segments_in_order_and_is_kept() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut spool = ResourceSpool::new(dir.path(), &[7; 32]);
|
||||
assert_eq!(
|
||||
entries(dir.path()),
|
||||
0,
|
||||
"nothing is created before a segment"
|
||||
);
|
||||
spool.append(b"first ").unwrap();
|
||||
spool.append(b"second").unwrap();
|
||||
assert_eq!(spool.len(), 12);
|
||||
let (path, len) = spool.finish();
|
||||
assert_eq!(len, 12);
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"first second");
|
||||
assert!(is_spool_name(path.file_name().unwrap().as_encoded_bytes()));
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let mode = std::fs::metadata(&path).unwrap().permissions().mode();
|
||||
assert_eq!(mode & 0o777, 0o600);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dropped_spool_leaves_no_file() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut spool = ResourceSpool::new(dir.path(), &[7; 32]);
|
||||
spool.append(&[1; 4096]).unwrap();
|
||||
assert_eq!(entries(dir.path()), 1);
|
||||
drop(spool);
|
||||
assert_eq!(entries(dir.path()), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_directory_fails_the_first_segment_and_leaves_nothing() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let missing = dir.path().join("absent");
|
||||
let mut spool = ResourceSpool::new(&missing, &[7; 32]);
|
||||
assert!(spool.append(b"data").is_err());
|
||||
drop(spool);
|
||||
assert_eq!(entries(dir.path()), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_spools_for_one_resource_use_separate_files() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut first = ResourceSpool::new(dir.path(), &[7; 32]);
|
||||
let mut second = ResourceSpool::new(dir.path(), &[7; 32]);
|
||||
first.append(b"a").unwrap();
|
||||
second.append(b"b").unwrap();
|
||||
assert_eq!(entries(dir.path()), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spool_names_are_recognised_and_other_names_are_not() {
|
||||
let name = format!("{}-{}", "ab".repeat(32), "cd".repeat(8));
|
||||
assert!(is_spool_name(name.as_bytes()));
|
||||
assert!(!is_spool_name("ab".repeat(32).as_bytes()));
|
||||
assert!(!is_spool_name(
|
||||
format!("{}.{}", "ab".repeat(32), "cd".repeat(8)).as_bytes()
|
||||
));
|
||||
assert!(!is_spool_name(
|
||||
format!("{}-{}", "zz".repeat(32), "cd".repeat(8)).as_bytes()
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -1143,7 +1143,8 @@ pub struct LinkConnectOptions {
|
||||
/// Retain RSSI, SNR and quality measurements reported by interfaces.
|
||||
pub track_phy_stats: bool,
|
||||
/// Largest advertised total size of an inbound Resource the session
|
||||
/// reassembles in memory; `None` accepts any size. See
|
||||
/// reassembles in memory; `None` reassembles any size. A Resource
|
||||
/// accepted to a file is not bound by it. See
|
||||
/// [`rns_protocol::resource::DEFAULT_INBOUND_REASSEMBLY_LIMIT`].
|
||||
pub inbound_reassembly_limit: Option<usize>,
|
||||
}
|
||||
@@ -11031,7 +11032,9 @@ fn clean_cache_dir_at(cache_dir: &Path, ttl: std::time::Duration, now: std::time
|
||||
for entry in entries.flatten() {
|
||||
let file_name = entry.file_name();
|
||||
// Python matches names of full-hash hex length, (HASHLENGTH//8)*2.
|
||||
if file_name.as_encoded_bytes().len() != 64 {
|
||||
// A Resource spool a crash left behind is cleaned the same way.
|
||||
let name = file_name.as_encoded_bytes();
|
||||
if name.len() != 64 && !crate::resource_spool::is_spool_name(name) {
|
||||
continue;
|
||||
}
|
||||
if let Ok(metadata) = entry.metadata()
|
||||
@@ -18872,6 +18875,8 @@ port = 37428
|
||||
let packet_path = cache_dir.join(hash_name);
|
||||
let resource_path = resource_dir.join(hash_name);
|
||||
let unrelated_path = resource_dir.join("unrelated");
|
||||
let spool_path = resource_dir.join(format!("{hash_name}-0123456789abcdef"));
|
||||
fs::write(&spool_path, b"spool").unwrap();
|
||||
fs::write(&packet_path, b"packet").unwrap();
|
||||
fs::write(&resource_path, b"resource").unwrap();
|
||||
fs::write(&unrelated_path, b"keep").unwrap();
|
||||
@@ -18889,6 +18894,10 @@ port = 37428
|
||||
after_resource_ttl,
|
||||
);
|
||||
assert!(!resource_path.exists(), "Resources expire after one day");
|
||||
assert!(
|
||||
!spool_path.exists(),
|
||||
"an abandoned Resource spool expires after one day"
|
||||
);
|
||||
assert!(
|
||||
packet_path.exists(),
|
||||
"packet cache entries live for seven days"
|
||||
|
||||
+132
-39
@@ -25,8 +25,11 @@ use rns_transport::messages::{
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
use crate::lifecycle::ShutdownSignal;
|
||||
use crate::link_manager::{DestinationRequest, LinkManager, RequestOutcome, ResourceCompletion};
|
||||
use crate::link_manager::{
|
||||
DestinationRequest, LinkManager, RequestOutcome, ResourceFileCompletion,
|
||||
};
|
||||
use crate::resource_source::{PreparedResourceSource, ResourceOptions, ResourceSource};
|
||||
use crate::resource_spool::ResourceSpool;
|
||||
use rns_identity::destination::AllowPolicy;
|
||||
use rns_link::link::ResourceStrategy;
|
||||
|
||||
@@ -407,10 +410,26 @@ impl RncpListenerHandle {
|
||||
///
|
||||
/// Keep the handle and read [`RncpListenerHandle::shutdown`] before embedding this
|
||||
/// listener in a longer-lived runtime.
|
||||
///
|
||||
/// Received files are assembled in the system temporary directory; use
|
||||
/// [`spawn_rncp_listener_with_resource_dir`] to name the directory.
|
||||
pub async fn spawn_rncp_listener(
|
||||
transport_tx: mpsc::Sender<TransportMessage>,
|
||||
cfg: RncpListenerConfig,
|
||||
events_tx: mpsc::Sender<RncpEvent>,
|
||||
) -> Result<RncpListenerHandle, RncpError> {
|
||||
spawn_rncp_listener_with_resource_dir(transport_tx, cfg, events_tx, &std::env::temp_dir()).await
|
||||
}
|
||||
|
||||
/// [`spawn_rncp_listener`], assembling each received file in `resource_dir`
|
||||
/// before it is moved to the save directory, as rncp moves the file Reticulum
|
||||
/// assembled under `Reticulum.resourcepath` (rncp.py). Pass the runtime's
|
||||
/// `storage/resources` directory. A received file has no size limit.
|
||||
pub async fn spawn_rncp_listener_with_resource_dir(
|
||||
transport_tx: mpsc::Sender<TransportMessage>,
|
||||
cfg: RncpListenerConfig,
|
||||
events_tx: mpsc::Sender<RncpEvent>,
|
||||
resource_dir: &Path,
|
||||
) -> Result<RncpListenerHandle, RncpError> {
|
||||
let signing_key = cfg
|
||||
.identity
|
||||
@@ -443,8 +462,11 @@ pub async fn spawn_rncp_listener(
|
||||
Some(signing_key),
|
||||
);
|
||||
|
||||
let (completion_tx, mut completion_rx) = mpsc::channel::<ResourceCompletion>(64);
|
||||
link_mgr.set_resource_completion_channel(completion_tx);
|
||||
// Every received file is assembled on disk, whatever its size; a fetch
|
||||
// request sent as a Resource is unpacked in memory, as upstream does.
|
||||
let (file_tx, mut file_rx) = mpsc::channel::<ResourceFileCompletion>(64);
|
||||
link_mgr.set_resource_file_channel(resource_dir, 0, file_tx);
|
||||
link_mgr.set_inbound_reassembly_limit(None);
|
||||
|
||||
let allowed_set: Arc<std::collections::HashSet<[u8; 16]>> =
|
||||
Arc::new(cfg.allowed.iter().copied().collect());
|
||||
@@ -454,8 +476,6 @@ pub async fn spawn_rncp_listener(
|
||||
let (identified_tx, mut identified_rx) = mpsc::channel::<([u8; 16], [u8; 16])>(64);
|
||||
link_mgr.set_link_identified_channel(identified_tx);
|
||||
link_mgr.set_resource_strategy(ResourceStrategy::AcceptApp);
|
||||
// Received files are handed to storage, as upstream rncp moves its file.
|
||||
link_mgr.set_inbound_reassembly_limit(None);
|
||||
let link_identities = link_mgr.link_identities_handle();
|
||||
let push_allowed = Arc::clone(&allowed_set);
|
||||
link_mgr.set_resource_accept_handler(move |link_id, _adv| {
|
||||
@@ -530,9 +550,10 @@ pub async fn spawn_rncp_listener(
|
||||
.await;
|
||||
}
|
||||
}
|
||||
completion = completion_rx.recv() => {
|
||||
completion = file_rx.recv() => {
|
||||
let Some(evt) = completion else { break };
|
||||
if denied_links.contains(&evt.link_id) {
|
||||
let _ = std::fs::remove_file(&evt.path);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -541,17 +562,18 @@ pub async fn spawn_rncp_listener(
|
||||
link_id = hex::encode(evt.link_id),
|
||||
"Invalid data received, ignoring resource"
|
||||
);
|
||||
let _ = std::fs::remove_file(&evt.path);
|
||||
continue;
|
||||
};
|
||||
|
||||
match save_payload(&save_dir, &file_name, &evt.data, overwrite).await {
|
||||
match save_received_file(&save_dir, &file_name, evt.path, overwrite).await {
|
||||
Ok(path) => {
|
||||
let _ = events_tx_cb
|
||||
.send(RncpEvent::Completed {
|
||||
link_id: evt.link_id,
|
||||
file_name,
|
||||
saved_path: path,
|
||||
bytes: evt.data.len(),
|
||||
bytes: usize::try_from(evt.size).unwrap_or(usize::MAX),
|
||||
})
|
||||
.await;
|
||||
}
|
||||
@@ -656,21 +678,36 @@ fn extract_filename(metadata: Option<&[u8]>) -> Option<String> {
|
||||
None
|
||||
}
|
||||
|
||||
async fn save_payload(
|
||||
/// Move a received file from its spool to `save_dir`, as rncp moves the file
|
||||
/// Reticulum assembled (rncp.py). The spool is removed on every outcome.
|
||||
async fn save_received_file(
|
||||
save_dir: &Path,
|
||||
file_name: &str,
|
||||
data: &[u8],
|
||||
spooled: PathBuf,
|
||||
overwrite: bool,
|
||||
) -> Result<PathBuf, String> {
|
||||
let save_dir = save_dir.to_path_buf();
|
||||
let file_name = file_name.to_string();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let saved = save_path_for(&save_dir, &file_name, overwrite)
|
||||
.and_then(|path| move_into_place(&spooled, &path).map(|()| path));
|
||||
if saved.is_err() {
|
||||
let _ = std::fs::remove_file(&spooled);
|
||||
}
|
||||
saved
|
||||
})
|
||||
.await
|
||||
.unwrap_or_else(|error| Err(format!("save task failed: {error}")))
|
||||
}
|
||||
|
||||
fn save_path_for(save_dir: &Path, file_name: &str, overwrite: bool) -> Result<PathBuf, String> {
|
||||
// rncp.py: the basename must name an entry directly in save_dir.
|
||||
let basename = basename(file_name).to_string();
|
||||
if basename.is_empty() || basename == "." || basename == ".." {
|
||||
return Err(format!("invalid save path for {file_name:?}"));
|
||||
}
|
||||
|
||||
tokio::fs::create_dir_all(save_dir)
|
||||
.await
|
||||
.map_err(|e| format!("create save_dir: {e}"))?;
|
||||
std::fs::create_dir_all(save_dir).map_err(|e| format!("create save_dir: {e}"))?;
|
||||
let mut path = save_dir.join(&basename);
|
||||
if !overwrite && path.exists() {
|
||||
let mut i = 1;
|
||||
@@ -683,12 +720,37 @@ async fn save_payload(
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
tokio::fs::write(&path, data)
|
||||
.await
|
||||
.map_err(|e| format!("write {}: {e}", path.display()))?;
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
fn move_into_place(spooled: &Path, path: &Path) -> Result<(), String> {
|
||||
let describe = |e: std::io::Error| format!("write {}: {e}", path.display());
|
||||
// The spool is private; the saved file takes the permissions a file
|
||||
// written in place would have.
|
||||
let permissions = std::fs::File::create(path)
|
||||
.and_then(|placeholder| placeholder.metadata())
|
||||
.map_err(describe)?
|
||||
.permissions();
|
||||
if std::fs::rename(spooled, path).is_ok() {
|
||||
return std::fs::set_permissions(path, permissions).map_err(describe);
|
||||
}
|
||||
// Another filesystem: copy, as shutil.move does.
|
||||
let copied = std::fs::File::open(spooled).and_then(|mut from| {
|
||||
let mut to = std::fs::File::create(path)?;
|
||||
std::io::copy(&mut from, &mut to)
|
||||
});
|
||||
match copied {
|
||||
Ok(_) => {
|
||||
let _ = std::fs::remove_file(spooled);
|
||||
Ok(())
|
||||
}
|
||||
Err(error) => {
|
||||
let _ = std::fs::remove_file(path);
|
||||
Err(describe(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn build_link_close(link: &mut Link) -> Option<Bytes> {
|
||||
let link_id = link.link_id;
|
||||
let teardown_data = link.teardown(CloseReason::InitiatorClosed)?;
|
||||
@@ -1486,10 +1548,23 @@ pub struct RncpFetchRequest<'a> {
|
||||
/// ([`RncpError::RemoteError`]) or 240 ([`RncpError::Denied`]). No answer
|
||||
/// within the request timeout gives [`RncpError::RequestFailed`].
|
||||
///
|
||||
/// Success means the assembled file was written under `save_dir`; the Resource
|
||||
/// proof is sent before this local write. Filename collision handling follows
|
||||
/// [`RncpListenerConfig`].
|
||||
/// Success means the assembled file was moved under `save_dir`; each Resource
|
||||
/// proof is sent after its segment is written to the spool and before this
|
||||
/// move. Filename collision handling follows [`RncpListenerConfig`]. The file
|
||||
/// is assembled in the system temporary directory; use
|
||||
/// [`rncp_fetch_file_with_resource_dir`] to name the directory.
|
||||
pub async fn rncp_fetch_file(request: RncpFetchRequest<'_>) -> Result<RncpFetchOutcome, RncpError> {
|
||||
rncp_fetch_file_with_resource_dir(request, &std::env::temp_dir()).await
|
||||
}
|
||||
|
||||
/// [`rncp_fetch_file`], assembling the fetched file in `resource_dir` before
|
||||
/// it is moved to the save directory, as rncp moves the file Reticulum
|
||||
/// assembled under `Reticulum.resourcepath` (rncp.py). Pass the runtime's
|
||||
/// `storage/resources` directory. A fetched file has no size limit.
|
||||
pub async fn rncp_fetch_file_with_resource_dir(
|
||||
request: RncpFetchRequest<'_>,
|
||||
resource_dir: &Path,
|
||||
) -> Result<RncpFetchOutcome, RncpError> {
|
||||
use rns_protocol::resource::{InboundTransfer, MultiSegmentInbound, TransferAction};
|
||||
|
||||
let RncpFetchRequest {
|
||||
@@ -1558,11 +1633,14 @@ pub async fn rncp_fetch_file(request: RncpFetchRequest<'_>) -> Result<RncpFetchO
|
||||
std::collections::HashMap::new();
|
||||
let mut split_resources: std::collections::HashMap<[u8; 32], MultiSegmentInbound> =
|
||||
std::collections::HashMap::new();
|
||||
// The fetched file, appended one verified segment at a time. Dropped
|
||||
// unfinished, it removes the partial file.
|
||||
let mut spool: Option<ResourceSpool> = None;
|
||||
let mut segment_routes: std::collections::HashMap<[u8; 32], ([u8; 32], usize)> =
|
||||
std::collections::HashMap::new();
|
||||
|
||||
let fetch_loop = async {
|
||||
let result: Result<(String, Vec<u8>), RncpError> = loop {
|
||||
let result: Result<(String, ResourceSpool), RncpError> = loop {
|
||||
if !ack_seen && Instant::now() >= request_deadline {
|
||||
break Err(RncpError::RequestFailed);
|
||||
}
|
||||
@@ -1688,7 +1766,6 @@ pub async fn rncp_fetch_file(request: RncpFetchRequest<'_>) -> Result<RncpFetchO
|
||||
}
|
||||
let coord = split_resources.entry(adv.original_hash).or_insert_with(|| {
|
||||
MultiSegmentInbound::new(adv.total_segments, adv.original_hash)
|
||||
.with_size_bound(adv.data_size)
|
||||
});
|
||||
if coord.total_segments != adv.total_segments {
|
||||
break Err(RncpError::ResourceFailed(
|
||||
@@ -1781,11 +1858,14 @@ pub async fn rncp_fetch_file(request: RncpFetchRequest<'_>) -> Result<RncpFetchO
|
||||
}
|
||||
|
||||
if let Some(rh) = completed_rh {
|
||||
let (payload, proof, metadata) = match transfers.get_mut(&rh) {
|
||||
let (payload, proof, metadata, advertised) = match transfers.get_mut(&rh) {
|
||||
Some(t) => match t.complete(Some(&decrypt_fn)) {
|
||||
Ok((payload, proof)) => {
|
||||
(payload, proof, t.resource.metadata.clone())
|
||||
}
|
||||
Ok((payload, proof)) => (
|
||||
payload,
|
||||
proof,
|
||||
t.resource.metadata.clone(),
|
||||
t.resource.data_size as u64,
|
||||
),
|
||||
Err(e) => {
|
||||
break Err(RncpError::ResourceFailed(format!(
|
||||
"resource assemble/proof failed: {e:?}; parts={}/{} map_hashes={} total_size={} data_size={} flags={:?}",
|
||||
@@ -1804,6 +1884,21 @@ pub async fn rncp_fetch_file(request: RncpFetchRequest<'_>) -> Result<RncpFetchO
|
||||
));
|
||||
}
|
||||
};
|
||||
// Resource.assemble writes the segment before
|
||||
// Resource.prove: no proof for an unwritten segment.
|
||||
let logical_id = segment_routes.get(&rh).map_or(rh, |route| route.0);
|
||||
let file = spool
|
||||
.get_or_insert_with(|| ResourceSpool::new(resource_dir, &logical_id));
|
||||
if file.len().saturating_add(payload.len() as u64) > advertised {
|
||||
break Err(RncpError::ResourceFailed(
|
||||
"received more data than advertised".into(),
|
||||
));
|
||||
}
|
||||
if let Err(error) = file.append(&payload) {
|
||||
break Err(RncpError::Io(format!(
|
||||
"could not write received data: {error}"
|
||||
)));
|
||||
}
|
||||
let prf_raw = build_resource_proof_packet(link_id, &proof);
|
||||
// The received file is not locally concluded until its
|
||||
// Resource proof has been admitted on the exact Link
|
||||
@@ -1823,7 +1918,7 @@ pub async fn rncp_fetch_file(request: RncpFetchRequest<'_>) -> Result<RncpFetchO
|
||||
if let Some(meta) = metadata {
|
||||
coord.set_metadata(meta);
|
||||
}
|
||||
if let Err(e) = coord.set_segment_data(segment_index, payload) {
|
||||
if let Err(e) = coord.set_segment_data(segment_index, Vec::new()) {
|
||||
break Err(RncpError::ResourceFailed(format!(
|
||||
"split segment rejected: {e:?}"
|
||||
)));
|
||||
@@ -1838,14 +1933,6 @@ pub async fn rncp_fetch_file(request: RncpFetchRequest<'_>) -> Result<RncpFetchO
|
||||
continue;
|
||||
}
|
||||
|
||||
let payload = match coord.reassemble() {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
break Err(RncpError::ResourceFailed(format!(
|
||||
"split reassemble: {e:?}"
|
||||
)));
|
||||
}
|
||||
};
|
||||
let meta_bytes = coord.metadata.clone();
|
||||
let Some(file_name) = extract_filename(meta_bytes.as_deref()) else {
|
||||
break Err(RncpError::ResourceFailed(
|
||||
@@ -1859,7 +1946,9 @@ pub async fn rncp_fetch_file(request: RncpFetchRequest<'_>) -> Result<RncpFetchO
|
||||
phy_bytes: last_phy_bytes,
|
||||
});
|
||||
}
|
||||
break Ok((file_name, payload));
|
||||
break spool.take().map(|file| (file_name, file)).ok_or_else(|| {
|
||||
RncpError::ResourceFailed("no data received".into())
|
||||
});
|
||||
}
|
||||
|
||||
let Some(file_name) = extract_filename(metadata.as_deref()) else {
|
||||
@@ -1871,7 +1960,10 @@ pub async fn rncp_fetch_file(request: RncpFetchRequest<'_>) -> Result<RncpFetchO
|
||||
phy_bytes: last_phy_bytes,
|
||||
});
|
||||
}
|
||||
break Ok((file_name, payload));
|
||||
break spool
|
||||
.take()
|
||||
.map(|file| (file_name, file))
|
||||
.ok_or_else(|| RncpError::ResourceFailed("no data received".into()));
|
||||
}
|
||||
}
|
||||
rns_wire::context::PacketContext::ResourceHmu => {
|
||||
@@ -1922,9 +2014,10 @@ pub async fn rncp_fetch_file(request: RncpFetchRequest<'_>) -> Result<RncpFetchO
|
||||
};
|
||||
close_link(rl, &transport_tx, &result).await;
|
||||
|
||||
let (file_name, payload) = result?;
|
||||
let bytes = payload.len();
|
||||
let saved_path = save_payload(save_dir, &file_name, &payload, overwrite)
|
||||
let (file_name, file) = result?;
|
||||
let (spooled, bytes) = file.finish();
|
||||
let bytes = usize::try_from(bytes).unwrap_or(usize::MAX);
|
||||
let saved_path = save_received_file(save_dir, &file_name, spooled, overwrite)
|
||||
.await
|
||||
.map_err(RncpError::Io)?;
|
||||
|
||||
|
||||
@@ -42,8 +42,8 @@ use rns_runtime::platform::StoragePaths;
|
||||
use rns_runtime::reticulum::ReticulumHandle;
|
||||
use rns_runtime::rncp::{
|
||||
DEFAULT_RNCP_APP_NAME, RncpError, RncpEvent, RncpFetchRequest, RncpListenerConfig,
|
||||
RncpProgress, RncpSendRequest, default_rncp_app_name, rncp_fetch_file, rncp_send_file,
|
||||
spawn_rncp_listener,
|
||||
RncpProgress, RncpSendRequest, default_rncp_app_name, rncp_fetch_file_with_resource_dir,
|
||||
rncp_send_file, spawn_rncp_listener_with_resource_dir,
|
||||
};
|
||||
|
||||
const DEFAULT_TIMEOUT_SECS: f64 = 15.0;
|
||||
@@ -625,17 +625,20 @@ async fn run_fetch(args: Args) -> ! {
|
||||
})
|
||||
};
|
||||
|
||||
let result = rncp_fetch_file(RncpFetchRequest {
|
||||
transport_tx: handle.transport_tx.clone(),
|
||||
identity,
|
||||
dest_hash,
|
||||
remote_path: path_arg,
|
||||
save_dir: &save_dir,
|
||||
overwrite: args.overwrite,
|
||||
path_timeout: link_wait,
|
||||
progress_tx: Some(progress_tx),
|
||||
shutdown: Some(interrupt.clone()),
|
||||
})
|
||||
let result = rncp_fetch_file_with_resource_dir(
|
||||
RncpFetchRequest {
|
||||
transport_tx: handle.transport_tx.clone(),
|
||||
identity,
|
||||
dest_hash,
|
||||
remote_path: path_arg,
|
||||
save_dir: &save_dir,
|
||||
overwrite: args.overwrite,
|
||||
path_timeout: link_wait,
|
||||
progress_tx: Some(progress_tx),
|
||||
shutdown: Some(interrupt.clone()),
|
||||
},
|
||||
&paths.resource_dir,
|
||||
)
|
||||
.await;
|
||||
|
||||
let _ = progress_task.await;
|
||||
@@ -987,7 +990,14 @@ async fn run_listen(args: Args) -> ! {
|
||||
fetch_jail,
|
||||
fetch_auto_compress: !args.no_compress,
|
||||
};
|
||||
let listener = match spawn_rncp_listener(handle.transport_tx.clone(), cfg, event_tx).await {
|
||||
let listener = match spawn_rncp_listener_with_resource_dir(
|
||||
handle.transport_tx.clone(),
|
||||
cfg,
|
||||
event_tx,
|
||||
&paths.resource_dir,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(h) => h,
|
||||
Err(e) => {
|
||||
tracing::error!("rncp-rs: failed to start listener: {e}");
|
||||
|
||||
Reference in new issue
Block a user