Skip to content

An open-source cross-platform alternative to AirDrop

fix: fail the transfer when a file cannot be read instead of sending an empty body (#3450)

DropMind5db88c63d2f5
diff --git a/Cargo.lock b/Cargo.lock
index c9ca6d74..b284ff28 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2239,7 +2239,6 @@ dependencies = [
"serde",
"serde_json",
"tokio",
- "tokio-stream",
"tokio-util",
"toml",
"unicode-width",
diff --git a/app/assets/CHANGELOG.md b/app/assets/CHANGELOG.md
index 2305b2bc..bd1edf31 100644
--- a/app/assets/CHANGELOG.md
+++ b/app/assets/CHANGELOG.md
@@ -1,6 +1,7 @@
## Unreleased
- fix(macos): file sharing via Share Extension doesn't work in DMG builds (@ShlomoCode, @vdmkotai)
+- fix: show the real error when a file cannot be read while sending, instead of transferring it as an empty file (@leopalmieri-spec)
## 1.18.2 (2026-08-21)
diff --git a/cli/Cargo.toml b/cli/Cargo.toml
index bdc98cfd..2157f8e7 100644
--- a/cli/Cargo.toml
+++ b/cli/Cargo.toml
@@ -25,7 +25,6 @@ rcgen = "0.14"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
tokio = { version = "1", features = ["full"] }
-tokio-stream = "0.1"
tokio-util = { version = "0.7", features = ["rt"] }
toml = "1.1"
unicode-width = "0.2"
diff --git a/cli/src/send_task.rs b/cli/src/send_task.rs
index 8d9e429d..b119e21d 100644
--- a/cli/src/send_task.rs
+++ b/cli/src/send_task.rs
@@ -18,7 +18,6 @@ use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::Instant;
use tokio::sync::mpsc;
-use tokio_stream::wrappers::ReceiverStream;
use tokio_util::sync::CancellationToken;
/// Cancellation state of a send, shared between the app and the send task.
@@ -267,7 +266,8 @@ async fn send_inner(
/// with the cumulative number of bytes of this file as chunks are sent.
fn upload_body(content: FileContent, progress: impl Fn(u64) + Send + 'static) -> reqwest::Body {
let mut sent = 0u64;
- let stream = ReceiverStream::new(content.into_receiver()).map(move |chunk| {
+ let stream = content.into_stream().map(move |chunk| {
+ let chunk = chunk?;
sent += chunk.len() as u64;
progress(sent);
Ok::<Bytes, anyhow::Error>(chunk)
diff --git a/packages/core/src/http/client/mod.rs b/packages/core/src/http/client/mod.rs
index 6ef4c1a6..b1aed771 100644
--- a/packages/core/src/http/client/mod.rs
+++ b/packages/core/src/http/client/mod.rs
@@ -17,7 +17,6 @@ use rustls::pki_types::{CertificateDer, PrivateKeyDer};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use thiserror::Error;
-use tokio_stream::wrappers::ReceiverStream;
pub enum LsHttpClient {
V2(LsHttpClientV2),
@@ -175,12 +174,17 @@ impl LsHttpClient {
/// Builds a streaming request body from the file content, invoking `progress`
/// with the cumulative number of bytes read as each chunk is sent.
+///
+/// An I/O error while reading the file fails the body, which aborts the
+/// request. Ending the body early instead would send a complete but truncated
+/// upload that the receiver stores as a short (often empty) file.
pub(super) fn upload_body(
content: model::transfer::FileContent,
progress: impl Fn(u64) + Send + 'static,
) -> reqwest::Body {
let mut sent = 0_u64;
- let stream = ReceiverStream::new(content.into_receiver()).map(move |chunk| {
+ let stream = content.into_stream().map(move |chunk| {
+ let chunk = chunk?;
sent += chunk.len() as u64;
progress(sent);
Ok::<Bytes, anyhow::Error>(chunk)
diff --git a/packages/core/src/http/server/web.rs b/packages/core/src/http/server/web.rs
index 10bd8715..ffdc3c92 100644
--- a/packages/core/src/http/server/web.rs
+++ b/packages/core/src/http/server/web.rs
@@ -7,7 +7,6 @@ use crate::http::server::PeerIp;
use crate::http::server::{AppState, RequestClientInfo};
use crate::model::discovery::PROTOCOL_VERSION_V2;
use crate::model::transfer::{FileContent, FileDto};
-use bytes::Bytes;
use http_body_util::{BodyExt, StreamBody};
use hyper::body::{Frame, Incoming};
use hyper::{http, Request, Response, StatusCode};
@@ -19,7 +18,6 @@ use std::net::IpAddr;
use std::num::NonZeroUsize;
use std::sync::Arc;
use tokio::sync::{mpsc, oneshot, Mutex};
-use tokio_stream::wrappers::ReceiverStream;
use tokio_stream::StreamExt;
/// Events emitted by the web download (download API) endpoints that must be handled
@@ -447,7 +445,7 @@ pub(crate) async fn download(
.map_err(|_| AppError::Status(StatusCode::INTERNAL_SERVER_ERROR))?;
let size = file.size;
- let body = receiver_stream_body(content.into_receiver());
+ let body = file_content_body(content);
// The file name may be inside directories.
let file_name = file.file_name.replace('/', "-");
@@ -523,10 +521,13 @@ async fn file_list_response(
.into_response()
}
-/// Streams application-provided chunks as a response body.
-fn receiver_stream_body(binary_rx: mpsc::Receiver<Bytes>) -> BoxedBody {
- let stream = ReceiverStream::new(binary_rx)
- .map(|chunk| Ok::<_, std::io::Error>(Frame::data(Bytes::from(chunk))));
+/// Streams the file content as the response body.
+///
+/// An I/O error while reading fails the body. The response announces
+/// `Content-Length`, so ending it early instead would hand the browser a
+/// silently truncated file.
+fn file_content_body(content: FileContent) -> BoxedBody {
+ let stream = content.into_stream().map(|chunk| chunk.map(Frame::data));
StreamBody::new(stream).boxed()
}
diff --git a/packages/core/src/model/transfer.rs b/packages/core/src/model/transfer.rs
index 7b2f90d7..d54c704d 100644
--- a/packages/core/src/model/transfer.rs
+++ b/packages/core/src/model/transfer.rs
@@ -1,7 +1,10 @@
use bytes::Bytes;
+use futures_util::stream::{Stream, StreamExt};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
+use std::pin::Pin;
use tokio::sync::mpsc;
+use tokio_stream::wrappers::ReceiverStream;
/// Limit queued file read-ahead to 2 MiB per active stream.
const FILE_CHANNEL_CAPACITY: usize = 4;
@@ -9,6 +12,14 @@ const FILE_CHANNEL_CAPACITY: usize = 4;
/// Buffer size used when reading a file into chunks.
const READ_BUFFER_SIZE: usize = 512 * 1024;
+/// A file's content as a stream of chunks, ending with an [`Err`] item when the
+/// file could not be read.
+///
+/// `Sync` on top of `Send`, because the web download handler turns this stream
+/// into a boxed response body and `http_body_util::BodyExt::boxed` requires a
+/// `Sync` body.
+pub type FileStream = Pin<Box<dyn Stream<Item = Result<Bytes, std::io::Error>> + Send + Sync>>;
+
/// The binary content of a file provided by the application for a transfer.
///
/// Shared by the HTTP client (upload) and server (download API) so both can
@@ -31,14 +42,20 @@ pub enum FileContent {
impl FileContent {
/// Normalizes the content into a stream of binary chunks.
///
- /// [`FileContent::Stream`] is returned as-is. For [`FileContent::Path`] and
+ /// [`FileContent::Stream`] is forwarded as-is. For [`FileContent::Path`] and
/// [`FileContent::Fd`], a background task reads the file and forwards the
- /// chunks; the channel is closed on EOF or on an I/O error.
- pub fn into_receiver(self) -> mpsc::Receiver<Bytes> {
+ /// chunks; the stream ends after the last chunk on EOF.
+ ///
+ /// An I/O failure is yielded as a final [`Err`] item rather than ending the
+ /// stream early. The consumer builds a request or response body from this
+ /// stream, so a silent end would be indistinguishable from a complete file:
+ /// the peer would store a truncated (or empty) file and the transfer would
+ /// look successful on this side.
+ pub fn into_stream(self) -> FileStream {
match self {
FileContent::Stream(rx) => {
tracing::info!("Reading file content via byte stream from application");
- rx
+ Box::pin(ReceiverStream::new(rx).map(Ok))
}
FileContent::Path(path) => {
tracing::info!("Reading file content from path: {}", path.display());
@@ -48,10 +65,19 @@ impl FileContent {
Ok(file) => read_file_into_sender(file, tx).await,
Err(e) => {
tracing::error!("Failed to open {}: {e}", path.display());
+ // Re-wrapped with the path: this message is what the
+ // user gets to see, and the bare OS error does not
+ // say which file could not be read.
+ let _ = tx
+ .send(Err(std::io::Error::new(
+ e.kind(),
+ format!("Failed to open {}: {e}", path.display()),
+ )))
+ .await;
}
}
});
- rx
+ Box::pin(ReceiverStream::new(rx))
}
#[cfg(target_os = "android")]
FileContent::Fd(fd) => {
@@ -64,7 +90,7 @@ impl FileContent {
let std_file = unsafe { std::fs::File::from_raw_fd(fd) };
let file = tokio::fs::File::from_std(std_file);
tokio::spawn(read_file_into_sender(file, tx));
- rx
+ Box::pin(ReceiverStream::new(rx))
}
}
}
@@ -72,8 +98,13 @@ impl FileContent {
/// Reads `file` to EOF, forwarding chunks on `tx`.
///
-/// Stops early if the receiver is gone or a read error occurs.
-async fn read_file_into_sender(mut file: tokio::fs::File, tx: mpsc::Sender<Bytes>) {
+/// Stops early if the receiver is gone. A read error is forwarded as a final
+/// [`Err`] item, so the consumer aborts the transfer instead of treating the
+/// bytes read so far as the complete file.
+async fn read_file_into_sender(
+ mut file: tokio::fs::File,
+ tx: mpsc::Sender<Result<Bytes, std::io::Error>>,
+) {
use tokio::io::AsyncReadExt;
let mut buffer = bytes::BytesMut::new();
@@ -86,12 +117,13 @@ async fn read_file_into_sender(mut file: tokio::fs::File, tx: mpsc::Sender<Bytes
Ok(0) => break,
Ok(n) => {
total += n as u64;
- if tx.send(buffer.split().freeze()).await.is_err() {
+ if tx.send(Ok(buffer.split().freeze())).await.is_err() {
break;
}
}
Err(e) => {
tracing::error!("Failed to read file content: {e}");
+ let _ = tx.send(Err(e)).await;
break;
}
}
@@ -269,4 +301,36 @@ mod tests {
assert_eq!(metadata.modified_time(), None);
assert_eq!(metadata.accessed_time(), None);
}
+
+ /// A file that cannot be opened must fail the stream. Ending it silently
+ /// would be indistinguishable from an empty file, so the peer would store
+ /// a 0-byte file while this side reports a successful transfer.
+ #[tokio::test]
+ async fn unopenable_path_fails_the_stream() {
+ let missing =
+ std::env::temp_dir().join(format!("localsend-missing-{}", uuid::Uuid::new_v4()));
+ let chunks: Vec<_> = FileContent::Path(missing).into_stream().collect().await;
+
+ assert_eq!(chunks.len(), 1);
+ assert!(chunks[0].is_err());
+ }
+
+ /// The happy path still yields the file content and then ends.
+ #[tokio::test]
+ async fn readable_path_yields_the_content() {
+ let path = std::env::temp_dir().join(format!("localsend-content-{}", uuid::Uuid::new_v4()));
+ std::fs::write(&path, b"hello").unwrap();
+
+ let chunks: Vec<_> = FileContent::Path(path.clone())
+ .into_stream()
+ .collect()
+ .await;
+ std::fs::remove_file(&path).unwrap();
+
+ let mut content = Vec::new();
+ for chunk in chunks {
+ content.extend_from_slice(&chunk.expect("a readable file must not fail the stream"));
+ }
+ assert_eq!(content.as_slice(), b"hello");
+ }
}
diff --git a/packages/core/tests/v2_server.rs b/packages/core/tests/v2_server.rs
index aaf7f1dc..781044cc 100644
--- a/packages/core/tests/v2_server.rs
+++ b/packages/core/tests/v2_server.rs
@@ -3,7 +3,7 @@
use bytes::Bytes;
use futures_util::StreamExt;
use localsend::crypto::hash::sha256_hex;
-use localsend::http::client::{ClientError, LsHttpClientV2};
+use localsend::http::client::{ClientError, LsHttpClient, LsHttpClientV2};
use localsend::http::dto_v2::{PrepareUploadRequestDtoV2, RegisterDtoV2};
use localsend::http::server::common::save::FileUploadTarget;
use localsend::http::server::v2::{PrepareUploadDecisionV2, ServerEventV2, SessionEndReasonV2};
@@ -11,7 +11,7 @@ use localsend::http::server::web::WebConfig;
use localsend::http::server::{start_with_port, ServerConfigV2};
use localsend::http::state::ClientInfo;
use localsend::model::discovery::ProtocolType;
-use localsend::model::transfer::{FileDto, FileMetadata};
+use localsend::model::transfer::{FileContent, FileDto, FileMetadata};
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
@@ -793,6 +793,73 @@ async fn test_upload_saved_to_path_by_server() {
let _ = tokio::fs::remove_dir_all(&save_dir).await;
}
+/// A source file the sender cannot read must fail the upload instead of being
+/// sent as an empty body.
+///
+/// The receiver creates the destination before the first byte arrives, so an
+/// upload that silently ends without data leaves a 0-byte file behind while
+/// the sender streamed a well-formed, complete-looking request.
+#[tokio::test]
+async fn test_upload_of_unreadable_file_fails_instead_of_sending_an_empty_body() {
+ let save_dir = std::env::temp_dir().join(format!("localsend-test-{}", uuid::Uuid::new_v4()));
+ tokio::fs::create_dir_all(&save_dir).await.unwrap();
+
+ let server = start_test_server(None, true, Some(save_dir.clone())).await;
+ let client = LsHttpClientV2::try_new_without_cert().unwrap();
+
+ let file = file_dto("file-a", "a.bin", 5);
+ let result = client
+ .prepare_upload(
+ ProtocolType::Http,
+ "127.0.0.1",
+ server.port,
+ None,
+ prepare_upload_request(&[file]),
+ None,
+ CancellationToken::new(),
+ )
+ .await
+ .unwrap();
+ let response = result.response.unwrap();
+
+ // The source is gone by the time the upload starts, as an OS-managed
+ // temporary copy of a picked file can be.
+ let missing = save_dir.join("source-is-gone.bin");
+ let result = LsHttpClient::V2(LsHttpClientV2::try_new_without_cert().unwrap())
+ .upload(
+ ProtocolType::Http,
+ "127.0.0.1",
+ server.port,
+ None,
+ &response.session_id,
+ "file-a",
+ &response.files["file-a"],
+ FileContent::Path(missing),
+ |_| {},
+ CancellationToken::new(),
+ )
+ .await;
+
+ // The sender has to fail on its own. A status code here would mean the
+ // empty body was sent and only the receiver objected, which is exactly the
+ // behaviour this fixes - and it would still be an `Err`, so asserting
+ // `is_err()` alone would not catch a regression.
+ match result {
+ Err(ClientError::StatusCode(err)) => panic!(
+ "the empty body reached the receiver, which rejected it with {}; the sender should have failed before sending anything",
+ err.status
+ ),
+ Ok(()) => panic!("an unreadable source must not produce a successful upload"),
+ Err(_) => {}
+ }
+
+ // The receiver must not have stored the file as completely received.
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ assert!(!server.received.lock().await.contains_key("file-a"));
+
+ let _ = tokio::fs::remove_dir_all(&save_dir).await;
+}
+
#[tokio::test]
async fn test_upload_with_invalid_token() {
let server = start_test_server(None, true, None).await;