Skip to content

An open-source cross-platform alternative to AirDrop

fix: let cancellation interrupt reading prepare-upload and upload responses (#3725)

Tien Nam Do84b17d4b6027
diff --git a/packages/core/src/http/client/mod.rs b/packages/core/src/http/client/mod.rs
index 0bc87cce..061041c5 100644
--- a/packages/core/src/http/client/mod.rs
+++ b/packages/core/src/http/client/mod.rs
@@ -362,3 +362,199 @@ impl ResponseExt for Response {
}))
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::model::discovery::ProtocolType;
+ use std::time::Duration;
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ use tokio::sync::oneshot;
+ use tokio::task::JoinHandle;
+ use tokio_util::sync::CancellationToken;
+
+ fn prepare_upload_payload() -> http::dto::PrepareUploadRequestDto {
+ http::dto::PrepareUploadRequestDto {
+ info: http::dto::RegisterDto {
+ alias: "Sender".to_string(),
+ version: "2.1".to_string(),
+ device_model: None,
+ device_type: None,
+ token: "FINGERPRINT".to_string(),
+ port: 53317,
+ protocol: ProtocolType::Http,
+ has_web_interface: false,
+ },
+ files: Default::default(),
+ }
+ }
+
+ /// Accepts one connection, reads the whole request to `path` (with a
+ /// `Content-Length` or chunked body) and answers with `response`. The
+ /// connection is never closed, so a body shorter than its `Content-Length`
+ /// keeps the client reading forever. The returned receiver fires once the
+ /// response has been written.
+ async fn stalling_peer(
+ path: &'static str,
+ response: &'static [u8],
+ ) -> (u16, oneshot::Receiver<()>, JoinHandle<()>) {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let port = listener.local_addr().unwrap().port();
+ let (written_tx, written_rx) = oneshot::channel();
+ let task = tokio::spawn(async move {
+ let (mut stream, _) = listener.accept().await.unwrap();
+ let mut request = Vec::new();
+ loop {
+ let mut chunk = [0u8; 4096];
+ let read = stream.read(&mut chunk).await.unwrap();
+ assert_ne!(read, 0, "client closed before sending the request");
+ request.extend_from_slice(&chunk[..read]);
+ let Some(end) = request.windows(4).position(|w| w == b"\r\n\r\n") else {
+ continue;
+ };
+ let head = std::str::from_utf8(&request[..end]).unwrap();
+ assert!(head.lines().next().unwrap().contains(path));
+ let length = head.lines().find_map(|line| {
+ let (name, value) = line.split_once(':')?;
+ name.eq_ignore_ascii_case("content-length")
+ .then(|| value.trim().parse::<usize>().unwrap())
+ });
+ let complete = match length {
+ Some(length) => request.len() >= end + 4 + length,
+ None => request.ends_with(b"0\r\n\r\n"),
+ };
+ if complete {
+ break;
+ }
+ }
+ stream.write_all(response).await.unwrap();
+ let _ = written_tx.send(());
+ std::future::pending::<()>().await;
+ });
+ (port, written_rx, task)
+ }
+
+ /// Cancelling must abort `prepare_upload` even after the response headers
+ /// arrived, while the (success or error) body is still being read.
+ #[tokio::test]
+ async fn prepare_upload_cancels_while_reading_response_body() {
+ let identity = crypto::cert::generate_self_signed().unwrap();
+ for version in [LsHttpClientVersion::V2, LsHttpClientVersion::V3] {
+ let client = LsHttpClient::new(
+ &identity.private_key_pem,
+ &identity.certificate_pem,
+ version,
+ None,
+ None,
+ )
+ .unwrap();
+ for response in [
+ b"HTTP/1.1 200 OK\r\nContent-Length: 1000\r\n\r\n{".as_slice(),
+ b"HTTP/1.1 403 Forbidden\r\nContent-Length: 1000\r\n\r\n{".as_slice(),
+ ] {
+ let (port, written, peer) = stalling_peer("/prepare-upload", response).await;
+ let cancel = CancellationToken::new();
+ let request = client.prepare_upload(
+ ProtocolType::Http,
+ "127.0.0.1",
+ port,
+ None,
+ prepare_upload_payload(),
+ None,
+ cancel.clone(),
+ );
+ tokio::pin!(request);
+
+ tokio::select! {
+ res = written => res.expect("peer failed before writing the response"),
+ _ = &mut request => panic!("request finished before the response was written"),
+ _ = tokio::time::sleep(Duration::from_secs(2)) => {
+ peer.abort();
+ panic!("the peer did not receive the whole request in time");
+ }
+ }
+ // Give the client time to parse the headers and start reading the body.
+ tokio::select! {
+ _ = tokio::time::sleep(Duration::from_millis(50)) => {}
+ _ = &mut request => panic!("request finished despite the incomplete body"),
+ }
+
+ cancel.cancel();
+ let result = tokio::time::timeout(Duration::from_secs(2), request).await;
+ peer.abort();
+ let result = result.expect("cancellation must interrupt reading the response body");
+ assert!(
+ matches!(result, Err(ClientError::Cancelled)),
+ "unexpected result: {:?}",
+ result.err()
+ );
+ }
+ }
+ }
+
+ /// Cancelling must abort `upload` even after the error response headers
+ /// arrived, while the error body is still being read.
+ #[tokio::test]
+ async fn upload_cancels_while_reading_error_body() {
+ let identity = crypto::cert::generate_self_signed().unwrap();
+ for version in [LsHttpClientVersion::V2, LsHttpClientVersion::V3] {
+ let client = LsHttpClient::new(
+ &identity.private_key_pem,
+ &identity.certificate_pem,
+ version,
+ None,
+ None,
+ )
+ .unwrap();
+ let (port, written, peer) = stalling_peer(
+ "/upload",
+ b"HTTP/1.1 403 Forbidden\r\nContent-Length: 1000\r\n\r\n{",
+ )
+ .await;
+ let (content_tx, content_rx) = tokio::sync::mpsc::channel(1);
+ content_tx
+ .send(bytes::Bytes::from_static(b"data"))
+ .await
+ .unwrap();
+ drop(content_tx);
+ let cancel = CancellationToken::new();
+ let request = client.upload(
+ ProtocolType::Http,
+ "127.0.0.1",
+ port,
+ None,
+ "session",
+ "file",
+ "token",
+ model::transfer::FileContent::Stream(content_rx),
+ |_| {},
+ cancel.clone(),
+ );
+ tokio::pin!(request);
+
+ tokio::select! {
+ res = written => res.expect("peer failed before writing the response"),
+ _ = &mut request => panic!("request finished before the response was written"),
+ _ = tokio::time::sleep(Duration::from_secs(2)) => {
+ peer.abort();
+ panic!("the peer did not receive the whole request in time");
+ }
+ }
+ // Give the client time to parse the headers and start reading the body.
+ tokio::select! {
+ _ = tokio::time::sleep(Duration::from_millis(50)) => {}
+ _ = &mut request => panic!("request finished despite the incomplete body"),
+ }
+
+ cancel.cancel();
+ let result = tokio::time::timeout(Duration::from_secs(2), request).await;
+ peer.abort();
+ let result = result.expect("cancellation must interrupt reading the error body");
+ assert!(
+ matches!(result, Err(ClientError::Cancelled)),
+ "unexpected result: {:?}",
+ result.err()
+ );
+ }
+ }
+}
diff --git a/packages/core/src/http/client/v2.rs b/packages/core/src/http/client/v2.rs
index 039d41cf..a92b23fa 100644
--- a/packages/core/src/http/client/v2.rs
+++ b/packages/core/src/http/client/v2.rs
@@ -170,41 +170,48 @@ impl LsHttpClientV2 {
}
.to_string();
- let send = self
- .client
- .post(&url)
- .header("Content-Type", "application/json")
- .body(serde_json::to_string(&payload)?)
- .send();
-
- let res = tokio::select! {
- res = send => res?,
- _ = cancel.cancelled() => return Err(ClientError::Cancelled),
+ // Cancellation must also cover reading the response body: a receiver
+ // that stalls after sending the headers would otherwise keep the
+ // cancelled request alive.
+ let response = async {
+ let res = self
+ .client
+ .post(&url)
+ .header("Content-Type", "application/json")
+ .body(serde_json::to_string(&payload)?)
+ .send()
+ .await?;
+
+ if protocol == ProtocolType::Https {
+ super::verify_cert_from_res(&res, public_key)?;
+ }
+
+ let status = res.status();
+
+ if status.as_u16() >= 400 {
+ return res.into_error().await;
+ }
+
+ if status == StatusCode::NO_CONTENT {
+ return Ok(PrepareUploadResultV2 {
+ status_code: status.as_u16(),
+ response: None,
+ });
+ }
+
+ let body = res.json::<PrepareUploadResponseDtoV2>().await?;
+
+ Ok(PrepareUploadResultV2 {
+ status_code: status.as_u16(),
+ response: Some(body),
+ })
};
- if protocol == ProtocolType::Https {
- super::verify_cert_from_res(&res, public_key)?;
- }
-
- let status = res.status();
-
- if status.as_u16() >= 400 {
- return res.into_error().await;
- }
-
- if status == StatusCode::NO_CONTENT {
- return Ok(PrepareUploadResultV2 {
- status_code: status.as_u16(),
- response: None,
- });
+ tokio::select! {
+ biased;
+ _ = cancel.cancelled() => Err(ClientError::Cancelled),
+ result = response => result,
}
-
- let body = res.json::<PrepareUploadResponseDtoV2>().await?;
-
- Ok(PrepareUploadResultV2 {
- status_code: status.as_u16(),
- response: Some(body),
- })
}
/// Uploads a file to the receiver.
@@ -256,20 +263,26 @@ impl LsHttpClientV2 {
}
.to_string();
- let res = tokio::select! {
- res = self.client.post(&url).body(body).send() => res?,
- _ = cancel.cancelled() => return Err(ClientError::Cancelled),
- };
+ // Cancellation must also cover reading an error body.
+ let response = async {
+ let res = self.client.post(&url).body(body).send().await?;
- if protocol == ProtocolType::Https {
- super::verify_cert_from_res(&res, public_key)?;
- }
+ if protocol == ProtocolType::Https {
+ super::verify_cert_from_res(&res, public_key)?;
+ }
- if res.status() != StatusCode::OK {
- return res.into_error().await;
- }
+ if res.status() != StatusCode::OK {
+ return res.into_error().await;
+ }
- Ok(())
+ Ok(())
+ };
+
+ tokio::select! {
+ biased;
+ _ = cancel.cancelled() => Err(ClientError::Cancelled),
+ result = response => result,
+ }
}
/// Cancels an ongoing file transfer session.
diff --git a/packages/core/src/http/client/v3.rs b/packages/core/src/http/client/v3.rs
index 8ebd46c9..6c55e13e 100644
--- a/packages/core/src/http/client/v3.rs
+++ b/packages/core/src/http/client/v3.rs
@@ -152,50 +152,57 @@ impl LsHttpClientV3 {
payload: http::dto::PrepareUploadRequestDto,
cancel: CancellationToken,
) -> Result<http::dto::PrepareUploadResult, ClientError> {
- let send = self
- .client
- .post(
- TargetUrl {
- version: ApiVersion::V3,
- protocol: protocol.as_str(),
- host: ip.to_string(),
- port,
- path: "/prepare-upload",
- params: &[],
- }
- .to_string(),
- )
- .body(serde_json::to_string(&payload)?)
- .send();
-
- let res = tokio::select! {
- res = send => res?,
- _ = cancel.cancelled() => return Err(ClientError::Cancelled),
+ // Cancellation must also cover reading the response body: a receiver
+ // that stalls after sending the headers would otherwise keep the
+ // cancelled request alive.
+ let response = async {
+ let res = self
+ .client
+ .post(
+ TargetUrl {
+ version: ApiVersion::V3,
+ protocol: protocol.as_str(),
+ host: ip.to_string(),
+ port,
+ path: "/prepare-upload",
+ params: &[],
+ }
+ .to_string(),
+ )
+ .body(serde_json::to_string(&payload)?)
+ .send()
+ .await?;
+
+ if protocol == ProtocolType::Https {
+ super::verify_cert_from_res(&res, public_key)?;
+ }
+
+ let status = res.status();
+
+ if status.as_u16() >= 400 {
+ return res.into_error().await;
+ }
+
+ if status == StatusCode::NO_CONTENT {
+ return Ok(http::dto::PrepareUploadResult {
+ status_code: status.as_u16(),
+ response: None,
+ });
+ }
+
+ let body = res.json::<http::dto::PrepareUploadResponseDto>().await?;
+
+ Ok(http::dto::PrepareUploadResult {
+ status_code: status.as_u16(),
+ response: Some(body),
+ })
};
- if protocol == ProtocolType::Https {
- super::verify_cert_from_res(&res, public_key)?;
- }
-
- let status = res.status();
-
- if status.as_u16() >= 400 {
- return res.into_error().await;
- }
-
- if status == StatusCode::NO_CONTENT {
- return Ok(http::dto::PrepareUploadResult {
- status_code: status.as_u16(),
- response: None,
- });
+ tokio::select! {
+ biased;
+ _ = cancel.cancelled() => Err(ClientError::Cancelled),
+ result = response => result,
}
-
- let body = res.json::<http::dto::PrepareUploadResponseDto>().await?;
-
- Ok(http::dto::PrepareUploadResult {
- status_code: status.as_u16(),
- response: Some(body),
- })
}
/// Uploads a file to the server.
@@ -216,40 +223,45 @@ impl LsHttpClientV3 {
body: reqwest::Body,
cancel: CancellationToken,
) -> Result<(), ClientError> {
- let send = self
- .client
- .post(
- TargetUrl {
- version: ApiVersion::V3,
- protocol: protocol.as_str(),
- host: ip.to_string(),
- port,
- path: "/upload",
- params: &[
- ("sessionId", &session_id),
- ("fileId", &file_id),
- ("token", &token),
- ],
- }
- .to_string(),
- )
- .body(body)
- .send();
-
- let res = tokio::select! {
- res = send => res?,
- _ = cancel.cancelled() => return Err(ClientError::Cancelled),
+ // Cancellation must also cover reading an error body.
+ let response = async {
+ let res = self
+ .client
+ .post(
+ TargetUrl {
+ version: ApiVersion::V3,
+ protocol: protocol.as_str(),
+ host: ip.to_string(),
+ port,
+ path: "/upload",
+ params: &[
+ ("sessionId", &session_id),
+ ("fileId", &file_id),
+ ("token", &token),
+ ],
+ }
+ .to_string(),
+ )
+ .body(body)
+ .send()
+ .await?;
+
+ if protocol == ProtocolType::Https {
+ super::verify_cert_from_res(&res, public_key)?;
+ }
+
+ if res.status() != StatusCode::OK {
+ return res.into_error().await;
+ }
+
+ Ok(())
};
- if protocol == ProtocolType::Https {
- super::verify_cert_from_res(&res, public_key)?;
- }
-
- if res.status() != StatusCode::OK {
- return res.into_error().await;
+ tokio::select! {
+ biased;
+ _ = cancel.cancelled() => Err(ClientError::Cancelled),
+ result = response => result,
}
-
- Ok(())
}
pub async fn cancel(