Skip to content

An open-source cross-platform alternative to AirDrop

feat: add web server

Tien Do Namd59c1e0a4b4e
diff --git a/core/Cargo.lock b/core/Cargo.lock
index 18943aa3..495a12cb 100644
--- a/core/Cargo.lock
+++ b/core/Cargo.lock
@@ -1249,6 +1249,7 @@ dependencies = [
"hyper-util",
"lru",
"pem",
+ "percent-encoding",
"rand 0.9.2",
"reqwest",
"rsa",
diff --git a/core/Cargo.toml b/core/Cargo.toml
index 11eb4fc4..5e4deb90 100644
--- a/core/Cargo.toml
+++ b/core/Cargo.toml
@@ -16,6 +16,7 @@ hyper = { version = "1.8.1", optional = true }
hyper-util = { version = "0.1.19", features = ["server"], optional = true }
lru = "0.16.3"
pem = { version = "3.0.6", optional = true }
+percent-encoding = { version = "2.3", optional = true }
reqwest = { version = "0.13.1", features = ["charset", "http2", "system-proxy", "json", "rustls-no-provider", "stream", "webpki-roots"], default-features = false, optional = true }
rand = "0.9.1"
rsa = { version = "0.9.8", optional = true }
@@ -39,7 +40,7 @@ x509-parser = { version = "0.18.0", features = ["verify"], optional = true }
[features]
default = []
crypto = ["ed25519-dalek", "rsa", "sha2"]
-http = ["crypto", "form_urlencoded", "http-body-util", "hyper", "hyper-util", "pem", "reqwest", "rustls", "socket2", "tokio-rustls", "x509-parser"]
+http = ["crypto", "form_urlencoded", "http-body-util", "hyper", "hyper-util", "pem", "percent-encoding", "reqwest", "rustls", "socket2", "tokio-rustls", "x509-parser"]
webrtc-signaling = ["tokio-tungstenite"]
webrtc = ["crypto", "flate2", "dep:webrtc", "webrtc-signaling", "x509-parser"]
full = ["crypto", "http", "webrtc"]
diff --git a/core/assets/web/error-403.html b/core/assets/web/error-403.html
new file mode 100644
index 00000000..69922bff
--- /dev/null
+++ b/core/assets/web/error-403.html
@@ -0,0 +1,11 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <meta charset="utf-8">
+ <title>LocalSend</title>
+</head>
+<body>
+ <h1>403 Forbidden</h1>
+ <p>You don't have permission to access this resource.</p>
+</body>
+</html>
diff --git a/core/assets/web/index.html b/core/assets/web/index.html
new file mode 100644
index 00000000..974ea94c
--- /dev/null
+++ b/core/assets/web/index.html
@@ -0,0 +1,98 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>LocalSend</title>
+ <style>
+ body {
+ font-family: sans-serif, system-ui;
+ margin: 0;
+ line-height: 1.5;
+ text-align: center;
+ }
+
+ a {
+ text-decoration: none;
+ color: #FFFFFF;
+ }
+
+ #file-list {
+ box-sizing: border-box;
+ width: 100%;
+ max-width: 1000px;
+ padding: 0 1em;
+ margin: 0 auto;
+ text-align: left;
+ }
+
+ .file-item {
+ display: table;
+ width: 100%;
+ padding: 0.5em 1em;
+ background-color: #00796B;
+ border-radius: 0.5em;
+ margin-bottom: 1em;
+ float: left;
+ box-sizing: border-box;
+ }
+
+ .file-item:hover {
+ background-color: #009688;
+ }
+
+ .file-name-cell, .file-size-cell, .file-index-cell {
+ display: table-cell;
+ vertical-align: middle;
+ }
+
+ .file-name-cell {
+ width: 100%;
+ padding: 0 0.5em;
+ }
+
+ .file-size-cell, .file-index-cell {
+ font-size: 0.8em;
+ white-space: nowrap;
+ color: #E0E0E0;
+ }
+
+ /* Two columns layout */
+ .file-item {
+ width: 100%;
+ }
+
+ @media screen and (min-width: 768px) {
+ #file-list.file-item {
+ width: 48%;
+ margin-right: 2%;
+ }
+ #file-list.file-item:nth-child(2n) {
+ margin-right: 0;
+ }
+ }
+
+ /* Single file mode */
+
+ #single-file {
+ box-sizing: border-box;
+ width: 100%;
+ text-align: left;
+ max-width: 400px;
+ padding: 0 1em;
+ margin: 0 auto;
+ }
+ </style>
+ <script src="main.js" defer></script>
+</head>
+<body>
+<noscript>
+ LocalSend requires JavaScript, which is currently disabled. Please enable it and try again.
+</noscript>
+
+<h1 style="padding: 0.5em">LocalSend</h1>
+<p id="status-text"></p>
+<div id="file-list"></div>
+<div id="single-file"></div>
+</body>
+</html>
diff --git a/core/assets/web/main.js b/core/assets/web/main.js
new file mode 100644
index 00000000..db5481dc
--- /dev/null
+++ b/core/assets/web/main.js
@@ -0,0 +1,178 @@
+// IMPORTANT: This script works in Internet Explorer 8!
+
+var BASE_URL = '/api/localsend/v2';
+
+var i18n = {};
+var sessionId = sessionStorage.getItem('sessionId');
+var queryParams = location.search.slice(1).split('&');
+var queryPin = null;
+
+// Parse query parameters manually for IE
+for (var i = 0; i < queryParams.length; i++) {
+ var pair = queryParams[i].split('=');
+ if (pair[0] === 'pin') {
+ queryPin = decodeURIComponent(pair[1]);
+ break;
+ }
+}
+
+function firstRequestFiles() {
+ document.getElementById('status-text').innerText = i18n.waiting;
+ var initialUrl = BASE_URL + '/prepare-download';
+
+ if (sessionId) {
+ initialUrl += '?sessionId=' + encodeURIComponent(sessionId);
+ if (queryPin) {
+ initialUrl += '&pin=' + encodeURIComponent(queryPin);
+ }
+ } else if (queryPin) {
+ initialUrl += '?pin=' + encodeURIComponent(queryPin);
+ }
+
+ makeRequest(initialUrl, 'POST', function (response) {
+ if (response.status === 401) {
+ pinRequestFiles(true);
+ return;
+ }
+
+ if (response.status === 403) {
+ document.getElementById('status-text').innerText = i18n.rejected;
+ return;
+ }
+
+ if (response.status === 429) {
+ document.getElementById('status-text').innerText = i18n.tooManyAttempts;
+ return;
+ }
+
+ if (response.status !== 200) {
+ document.getElementById('status-text').innerText = 'Error: ' + response.status;
+ return;
+ }
+
+ handleSuccess(response);
+ });
+}
+
+function pinRequestFiles(firstAttempt) {
+ var pin = prompt(i18n.enterPin + (firstAttempt ? '' : '\n' + i18n.invalidPin));
+ if (!pin) {
+ document.getElementById('status-text').innerText = i18n.invalidPin;
+ return;
+ }
+
+ makeRequest(BASE_URL + '/prepare-download?pin=' + encodeURIComponent(pin), 'POST', function (response) {
+ if (response.status === 401) {
+ pinRequestFiles(false);
+ return;
+ }
+
+ if (response.status === 403) {
+ document.getElementById('status-text').innerText = i18n.rejected;
+ return;
+ }
+
+ if (response.status === 429) {
+ document.getElementById('status-text').innerText = i18n.tooManyAttempts;
+ return;
+ }
+
+ if (response.status !== 200) {
+ document.getElementById('status-text').innerText = 'Error: ' + response.status;
+ return;
+ }
+
+ handleSuccess(response);
+ });
+}
+
+function makeRequest(url, method, callback) {
+ var xhr = new XMLHttpRequest();
+ xhr.open(method, url, true);
+ xhr.onreadystatechange = function () {
+ if (xhr.readyState === 4) {
+ callback(xhr);
+ }
+ };
+ xhr.send();
+}
+
+function fetchI18n(then) {
+ makeRequest('/i18n.json', 'GET', function (response) {
+ if (response.status === 200) {
+ i18n = JSON.parse(response.responseText);
+ then();
+ }
+ });
+}
+
+function init() {
+ fetchI18n(firstRequestFiles);
+}
+
+function handleSuccess(response) {
+ var data = JSON.parse(response.responseText);
+ var files = data.files;
+ sessionId = data.sessionId;
+ sessionStorage.setItem('sessionId', sessionId);
+
+ document.getElementById('status-text').innerText = i18n.files + ' (' + getKeys(data.files).length + ')';
+
+ // Handling file display
+ handleFilesDisplay(files, sessionId);
+}
+
+function handleFilesDisplay(files, sessionId) {
+ var html= '';
+ var fileKeys = getKeys(files);
+ for (var i = 0; i < fileKeys.length; i++) {
+ var file = files[fileKeys[i]];
+ html += '<a class="file-item" href="' + BASE_URL + '/download?sessionId=' + encodeURIComponent(sessionId) + '&fileId=' + encodeURIComponent(fileKeys[i]) + '">' +
+ '<div class="file-index-cell">' + (i + 1) + '</div>' +
+ '<div class="file-name-cell">' + escapeHtml(file.fileName) + '</div>' +
+ '<div class="file-size-cell">' + formatBytes(file.size) + '</div>' +
+ '</a>';
+ }
+
+ if (fileKeys.length === 1) {
+ document.getElementById('single-file').innerHTML = html;
+ } else {
+ document.getElementById('file-list').innerHTML = html;
+ }
+}
+
+function escapeHtml(text) {
+ if (text === null || text === undefined) {
+ return '';
+ }
+ var map = {
+ '&': '&amp;',
+ '<': '&lt;',
+ '>': '&gt;',
+ '"': '&quot;',
+ "'": '&#039;'
+ };
+ return String(text).replace(/[&<>"']/g, function(m) { return map[m]; });
+}
+
+function formatBytes(bytes) {
+ if (bytes < 1024) {
+ return bytes + ' B';
+ } else if (bytes < 1024 * 1024) {
+ return (bytes / 1024).toFixed(1) + ' KB';
+ } else if (bytes < 1024 * 1024 * 1024) {
+ return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
+ } else {
+ return (bytes / (1024 * 1024 * 1024)).toFixed(1) + ' GB';
+ }
+}
+
+function getKeys(obj) {
+ var keys = [];
+ for (var key in obj) {
+ keys.push(key);
+ }
+ return keys;
+}
+
+init();
diff --git a/core/src/http/server/controller/mod.rs b/core/src/http/server/controller/mod.rs
index f87961dc..f34074ee 100644
--- a/core/src/http/server/controller/mod.rs
+++ b/core/src/http/server/controller/mod.rs
@@ -1,3 +1,52 @@
pub(crate) mod v2;
pub(crate) mod v3;
pub(crate) mod web;
+
+use crate::http::server::error::AppError;
+use hyper::StatusCode;
+use lru::LruCache;
+use std::collections::HashMap;
+use std::net::IpAddr;
+use tokio::sync::Mutex;
+
+/// Maximum failed PIN attempts per IP before requests are blocked with 429.
+const MAX_PIN_ATTEMPTS: u32 = 3;
+
+/// Checks the `pin` query parameter against the required PIN (if any).
+pub(crate) async fn check_pin(
+ required_pin: Option<&str>,
+ pin_attempts: &Mutex<LruCache<IpAddr, u32>>,
+ query: &HashMap<String, String>,
+ ip: IpAddr,
+) -> Result<(), AppError> {
+ let Some(required_pin) = required_pin else {
+ return Ok(());
+ };
+
+ let mut attempts = pin_attempts.lock().await;
+ let count = attempts.get(&ip).copied().unwrap_or(0);
+ if count >= MAX_PIN_ATTEMPTS {
+ return Err(AppError::Message(
+ StatusCode::TOO_MANY_REQUESTS,
+ "Too many requests".to_string(),
+ ));
+ }
+
+ match query.get("pin") {
+ Some(pin) if pin == required_pin => {
+ attempts.pop(&ip);
+ Ok(())
+ }
+ Some(_) => {
+ attempts.put(ip, count + 1);
+ Err(AppError::Message(
+ StatusCode::UNAUTHORIZED,
+ "Invalid PIN".to_string(),
+ ))
+ }
+ None => Err(AppError::Message(
+ StatusCode::UNAUTHORIZED,
+ "PIN required".to_string(),
+ )),
+ }
+}
diff --git a/core/src/http/server/controller/v2.rs b/core/src/http/server/controller/v2.rs
index f32bc298..7dc681eb 100644
--- a/core/src/http/server/controller/v2.rs
+++ b/core/src/http/server/controller/v2.rs
@@ -3,14 +3,15 @@ use crate::http::dto_v2::{
RegisterResponseDtoV2, PROTOCOL_VERSION_V2,
};
use crate::http::server::collect_to_json::CollectToJson;
+use crate::http::server::controller::check_pin;
use crate::http::server::error::AppError;
use crate::http::server::event::{PrepareUploadDecisionV2, ServerEventV2, SessionEndReasonV2};
use crate::http::server::query::parse_query;
-use crate::http::server::response::JsonResponse;
+use crate::http::server::response::{empty_body, BoxedBody, JsonResponse};
use crate::http::server::session::{FileStatusV2, SessionFileV2, SessionStateV2, UploadSessionV2};
use crate::http::server::{AppState, RequestClientInfo, V2State};
use bytes::Bytes;
-use http_body_util::{BodyExt, Full};
+use http_body_util::BodyExt;
use hyper::body::Incoming;
use hyper::{Request, Response, StatusCode};
use std::collections::HashMap;
@@ -18,9 +19,6 @@ use std::sync::Arc;
use tokio::sync::{mpsc, oneshot};
use uuid::Uuid;
-/// Maximum failed PIN attempts per IP before requests are blocked with 429.
-const MAX_PIN_ATTEMPTS: u32 = 3;
-
/// Channel capacity for file upload chunks (provides backpressure).
const UPLOAD_CHANNEL_CAPACITY: usize = 16;
@@ -42,7 +40,7 @@ pub(crate) async fn register(
}
let info = state.info.lock().await.clone();
- let download = state.web.lock().await.is_some();
+ let download = state.web.is_some();
Ok(JsonResponse {
status: StatusCode::OK,
@@ -59,7 +57,7 @@ pub(crate) async fn register(
pub(crate) async fn info(state: AppState) -> Result<JsonResponse<InfoResponseDtoV2>, AppError> {
let info = state.info.lock().await.clone();
- let download = state.web.lock().await.is_some();
+ let download = state.web.is_some();
Ok(JsonResponse {
status: StatusCode::OK,
@@ -78,11 +76,11 @@ pub(crate) async fn prepare_upload(
req: Request<Incoming>,
state: AppState,
client_info: RequestClientInfo,
-) -> Result<Response<Full<Bytes>>, AppError> {
+) -> Result<Response<BoxedBody>, AppError> {
let v2 = require_v2(&state)?;
let query = parse_query(req.uri().query());
- check_pin(&v2, &query, &client_info).await?;
+ check_pin(v2.pin.as_deref(), &v2.pin_attempts, &query, client_info.ip).await?;
let payload = req
.into_body()
@@ -151,7 +149,7 @@ pub(crate) async fn prepare_upload(
if files.is_empty() {
// Nothing to transfer.
pending_guard.clear().await;
- let mut res = Response::new(Full::default());
+ let mut res = Response::new(empty_body());
*res.status_mut() = StatusCode::NO_CONTENT;
return Ok(res);
}
@@ -188,7 +186,7 @@ pub(crate) async fn upload(
req: Request<Incoming>,
state: AppState,
client_info: RequestClientInfo,
-) -> Result<Response<Full<Bytes>>, AppError> {
+) -> Result<Response<BoxedBody>, AppError> {
let v2 = require_v2(&state)?;
let query = parse_query(req.uri().query());
@@ -284,7 +282,7 @@ pub(crate) async fn upload(
upload_guard.finish(success).await;
match success {
- true => Ok(Response::new(Full::default())),
+ true => Ok(Response::new(empty_body())),
false => Err(AppError::Status(StatusCode::INTERNAL_SERVER_ERROR)),
}
}
@@ -292,7 +290,7 @@ pub(crate) async fn upload(
pub(crate) async fn cancel(
req: Request<Incoming>,
state: AppState,
-) -> Result<Response<Full<Bytes>>, AppError> {
+) -> Result<Response<BoxedBody>, AppError> {
let v2 = require_v2(&state)?;
let query = parse_query(req.uri().query());
@@ -320,7 +318,7 @@ pub(crate) async fn cancel(
}
}
- Ok(Response::new(Full::default()))
+ Ok(Response::new(empty_body()))
}
fn require_v2(state: &AppState) -> Result<Arc<V2State>, AppError> {
@@ -337,43 +335,6 @@ fn invalid_token_error() -> AppError {
)
}
-async fn check_pin(
- v2: &Arc<V2State>,
- query: &HashMap<String, String>,
- client_info: &RequestClientInfo,
-) -> Result<(), AppError> {
- let Some(required_pin) = &v2.pin else {
- return Ok(());
- };
-
- let mut attempts = v2.pin_attempts.lock().await;
- let count = attempts.get(&client_info.ip).copied().unwrap_or(0);
- if count >= MAX_PIN_ATTEMPTS {
- return Err(AppError::Message(
- StatusCode::TOO_MANY_REQUESTS,
- "Too many requests".to_string(),
- ));
- }
-
- match query.get("pin") {
- Some(pin) if pin == required_pin => {
- attempts.pop(&client_info.ip);
- Ok(())
- }
- Some(_) => {
- attempts.put(client_info.ip, count + 1);
- Err(AppError::Message(
- StatusCode::UNAUTHORIZED,
- "Invalid PIN".to_string(),
- ))
- }
- None => Err(AppError::Message(
- StatusCode::UNAUTHORIZED,
- "PIN required".to_string(),
- )),
- }
-}
-
/// Frees a claimed `Pending` session slot unless a session was created.
///
/// The cleanup also runs on drop so the slot is not leaked
diff --git a/core/src/http/server/controller/v3.rs b/core/src/http/server/controller/v3.rs
index a9e24dd6..cd9125cd 100644
--- a/core/src/http/server/controller/v3.rs
+++ b/core/src/http/server/controller/v3.rs
@@ -57,7 +57,7 @@ pub(crate) async fn register(
let payload = body.collect_to_json::<RegisterDto>().await?;
let info = state.info.lock().await.clone();
- let has_web_interface = state.web.lock().await.is_some();
+ let has_web_interface = state.web.is_some();
Ok(JsonResponse {
status: StatusCode::OK,
diff --git a/core/src/http/server/controller/web.rs b/core/src/http/server/controller/web.rs
index 1b524fdf..1adde69f 100644
--- a/core/src/http/server/controller/web.rs
+++ b/core/src/http/server/controller/web.rs
@@ -1,2 +1,476 @@
-#[derive(Clone, Debug)]
-pub struct WebPageState;
+use crate::http::dto_v2::{
+ InfoResponseDtoV2, PrepareDownloadResponseDtoV2, PROTOCOL_VERSION_V2,
+};
+use crate::http::server::controller::check_pin;
+use crate::http::server::error::AppError;
+use crate::http::server::event::ServerEventV2;
+use crate::http::server::query::parse_query;
+use crate::http::server::response::{full_body, BoxedBody, JsonResponse};
+use crate::http::server::{AppState, RequestClientInfo};
+use crate::model::transfer::FileDto;
+use bytes::Bytes;
+use http_body_util::{BodyExt, StreamBody};
+use hyper::body::{Frame, Incoming};
+use hyper::{http, Request, Response, StatusCode};
+use lru::LruCache;
+use percent_encoding::{utf8_percent_encode, AsciiSet, NON_ALPHANUMERIC};
+use serde::Serialize;
+use std::collections::HashMap;
+use std::net::IpAddr;
+use std::num::NonZeroUsize;
+use std::path::PathBuf;
+use std::sync::Arc;
+use tokio::io::AsyncReadExt;
+use tokio::sync::{mpsc, oneshot, Mutex};
+use tokio_stream::wrappers::ReceiverStream;
+
+const INDEX_HTML: &str = include_str!("../../../../assets/web/index.html");
+const MAIN_JS: &str = include_str!("../../../../assets/web/main.js");
+const ERROR_403_HTML: &str = include_str!("../../../../assets/web/error-403.html");
+
+/// Buffer size for reading files from disk during downloads.
+const DOWNLOAD_BUFFER_SIZE: usize = 64 * 1024;
+
+/// Channel capacity for file download chunks (provides backpressure).
+const DOWNLOAD_CHANNEL_CAPACITY: usize = 16;
+
+/// Characters that are percent-encoded in the content-disposition file name.
+/// Matches the component encoding of RFC 2396 (letters, digits and marks are kept).
+const FILE_NAME_ENCODE_SET: &AsciiSet = &NON_ALPHANUMERIC
+ .remove(b'-')
+ .remove(b'_')
+ .remove(b'.')
+ .remove(b'!')
+ .remove(b'~')
+ .remove(b'*')
+ .remove(b'\'')
+ .remove(b'(')
+ .remove(b')');
+
+/// Configuration for web send (download API): files offered for download by web browsers.
+pub struct WebSendConfig {
+ /// The files offered for download, mapped by file ID.
+ pub files: HashMap<String, WebSendFile>,
+
+ /// Optional PIN that web clients must provide via the `pin` query parameter.
+ pub pin: Option<String>,
+
+ /// Translations for the web page, served via `/i18n.json`.
+ pub i18n: WebSendI18n,
+}
+
+/// A file offered for download.
+pub struct WebSendFile {
+ /// The metadata of the file as presented to the web client.
+ pub dto: FileDto,
+
+ /// The content of the file.
+ pub content: WebSendFileContent,
+}
+
+/// The content source of a file offered for download.
+pub enum WebSendFileContent {
+ /// In-memory content (e.g. a text message or clipboard content).
+ Bytes(Bytes),
+
+ /// The content is read from the file system at download time.
+ Path(PathBuf),
+}
+
+/// Translations for the web page, served via `/i18n.json`.
+#[derive(Clone, Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct WebSendI18n {
+ pub waiting: String,
+ pub enter_pin: String,
+ pub invalid_pin: String,
+ pub too_many_attempts: String,
+ pub rejected: String,
+ pub files: String,
+ pub file_name: String,
+ pub size: String,
+}
+
+impl Default for WebSendI18n {
+ fn default() -> Self {
+ Self {
+ waiting: "Waiting for response…".to_string(),
+ enter_pin: "Enter PIN".to_string(),
+ invalid_pin: "Invalid PIN".to_string(),
+ too_many_attempts: "Too many attempts".to_string(),
+ rejected: "Rejected".to_string(),
+ files: "Files".to_string(),
+ file_name: "File name".to_string(),
+ size: "Size".to_string(),
+ }
+ }
+}
+
+/// Runtime state of the web send (download API) endpoints.
+pub(crate) struct WebPageState {
+ /// The files offered for download, mapped by file ID.
+ pub(crate) files: HashMap<String, WebSendFile>,
+
+ /// Optional PIN required for prepare-download requests.
+ pub(crate) pin: Option<String>,
+
+ /// Translations served via `/i18n.json`.
+ pub(crate) i18n: WebSendI18n,
+
+ /// Channel on which server events are emitted to the application.
+ pub(crate) event_tx: mpsc::Sender<ServerEventV2>,
+
+ /// Download sessions, keyed by session ID (the client's IP address).
+ pub(crate) sessions: Mutex<HashMap<String, WebSendSession>>,
+
+ /// Maps client IPs to the number of failed PIN attempts.
+ pub(crate) pin_attempts: Mutex<LruCache<IpAddr, u32>>,
+}
+
+impl WebPageState {
+ pub(crate) fn new(config: WebSendConfig, event_tx: mpsc::Sender<ServerEventV2>) -> Self {
+ Self {
+ files: config.files,
+ pin: config.pin,
+ i18n: config.i18n,
+ event_tx,
+ sessions: Mutex::new(HashMap::new()),
+ pin_attempts: Mutex::new(LruCache::new(NonZeroUsize::new(200).unwrap())),
+ }
+ }
+}
+
+/// A download session of a single web client.
+pub(crate) struct WebSendSession {
+ /// The IP address of the web client. Downloads are only allowed from this address.
+ ip: IpAddr,
+
+ /// `false` while the prepare-download request is waiting for the application's decision.
+ accepted: bool,
+}
+
+pub(crate) fn index(state: &AppState) -> Response<BoxedBody> {
+ match &state.web {
+ Some(_) => html_response(StatusCode::OK, INDEX_HTML, "text/html; charset=utf-8"),
+ None => error_403_page(),
+ }
+}
+
+pub(crate) fn main_js(state: &AppState) -> Response<BoxedBody> {
+ match &state.web {
+ Some(_) => html_response(StatusCode::OK, MAIN_JS, "text/javascript; charset=utf-8"),
+ None => error_403_page(),
+ }
+}
+
+pub(crate) fn i18n(state: &AppState) -> Result<Response<BoxedBody>, AppError> {
+ let web = require_web(state)?;
+
+ Ok(JsonResponse {
+ status: StatusCode::OK,
+ body: &web.i18n,
+ }
+ .into_response())
+}
+
+pub(crate) async fn prepare_download(
+ req: Request<Incoming>,
+ state: AppState,
+ client_info: RequestClientInfo,
+) -> Result<Response<BoxedBody>, AppError> {
+ let web = require_web(&state)?;
+ let query = parse_query(req.uri().query());
+
+ // An accepted client can re-fetch the file list (e.g. page reload).
+ if let Some(session_id) = query.get("sessionId") {
+ let sessions = web.sessions.lock().await;
+ let valid = sessions
+ .get(session_id)
+ .is_some_and(|session| session.accepted && session.ip == client_info.ip);
+ if valid {
+ drop(sessions);
+ return Ok(file_list_response(&state, &web, session_id.clone()).await);
+ }
+ }
+
+ check_pin(
+ web.pin.as_deref(),
+ &web.pin_attempts,
+ &query,
+ client_info.ip,
+ )
+ .await?;
+
+ let user_agent = req
+ .headers()
+ .get(http::header::USER_AGENT)
+ .and_then(|value| value.to_str().ok())
+ .map(str::to_string);
+
+ // One session per IP; a new request replaces any previous session of this client.
+ let session_id = client_info.ip.to_string();
+ {
+ let mut sessions = web.sessions.lock().await;
+ sessions.insert(
+ session_id.clone(),
+ WebSendSession {
+ ip: client_info.ip,
+ accepted: false,
+ },
+ );
+ }
+
+ // Removes the pending session again if this request is declined or aborted
+ // before the application accepted it.
+ let mut pending_guard = PendingWebSessionGuard::new(web.clone(), session_id.clone());
+
+ let (decision_tx, decision_rx) = oneshot::channel();
+ let event = ServerEventV2::PrepareDownload {
+ ip: client_info.ip,
+ session_id: session_id.clone(),
+ user_agent,
+ decision_tx,
+ };
+ if web.event_tx.send(event).await.is_err() {
+ return Err(AppError::Status(StatusCode::INTERNAL_SERVER_ERROR));
+ }
+
+ let accepted = decision_rx
+ .await
+ .map_err(|_| AppError::Status(StatusCode::INTERNAL_SERVER_ERROR))?;
+
+ if !accepted {
+ pending_guard.clear().await;
+ return Err(AppError::Message(
+ StatusCode::FORBIDDEN,
+ "File transfer rejected.".to_string(),
+ ));
+ }
+
+ {
+ let mut sessions = web.sessions.lock().await;
+ if let Some(session) = sessions.get_mut(&session_id) {
+ session.accepted = true;
+ }
+ }
+ pending_guard.disarm();
+
+ tracing::info!("Download session created: {session_id}");
+
+ Ok(file_list_response(&state, &web, session_id).await)
+}
+
+pub(crate) async fn download(
+ req: Request<Incoming>,
+ state: AppState,
+ client_info: RequestClientInfo,
+) -> Result<Response<BoxedBody>, AppError> {
+ let web = require_web(&state)?;
+ let query = parse_query(req.uri().query());
+
+ let Some(session_id) = query.get("sessionId") else {
+ return Err(AppError::BadRequest("Missing sessionId.".to_string()));
+ };
+
+ {
+ let sessions = web.sessions.lock().await;
+ let valid = sessions
+ .get(session_id)
+ .is_some_and(|session| session.accepted && session.ip == client_info.ip);
+ if !valid {
+ return Err(AppError::Message(
+ StatusCode::FORBIDDEN,
+ "Invalid sessionId.".to_string(),
+ ));
+ }
+ }
+
+ let Some(file_id) = query.get("fileId") else {
+ return Err(AppError::BadRequest("Missing fileId.".to_string()));
+ };
+
+ let Some(file) = web.files.get(file_id) else {
+ return Err(AppError::Message(
+ StatusCode::FORBIDDEN,
+ "Invalid fileId.".to_string(),
+ ));
+ };
+
+ let (size, body) = match &file.content {
+ WebSendFileContent::Bytes(bytes) => (bytes.len() as u64, full_body(bytes.clone())),
+ WebSendFileContent::Path(path) => {
+ let file = tokio::fs::File::open(path).await.map_err(|err| {
+ tracing::warn!("Failed to open file {path:?}: {err:#}");
+ AppError::Status(StatusCode::INTERNAL_SERVER_ERROR)
+ })?;
+
+ // Read the size at download time since the file
+ // could have changed since it was selected.
+ let size = file
+ .metadata()
+ .await
+ .map_err(|_| AppError::Status(StatusCode::INTERNAL_SERVER_ERROR))?
+ .len();
+
+ (size, file_stream_body(file))
+ }
+ };
+
+ // The file name may be inside directories.
+ let file_name = file.dto.file_name.replace('/', "-");
+ let encoded_file_name = utf8_percent_encode(&file_name, FILE_NAME_ENCODE_SET);
+
+ let mut response = Response::new(body);
+ let headers = response.headers_mut();
+ headers.insert(
+ http::header::CONTENT_TYPE,
+ http::HeaderValue::from_static("application/octet-stream"),
+ );
+ headers.insert(
+ http::header::CONTENT_DISPOSITION,
+ http::HeaderValue::from_str(&format!("attachment; filename=\"{encoded_file_name}\""))
+ .map_err(|_| AppError::Status(StatusCode::INTERNAL_SERVER_ERROR))?,
+ );
+ headers.insert(http::header::CONTENT_LENGTH, http::HeaderValue::from(size));
+
+ Ok(response)
+}
+
+fn require_web(state: &AppState) -> Result<Arc<WebPageState>, AppError> {
+ state.web.clone().ok_or(AppError::Message(
+ StatusCode::FORBIDDEN,
+ "Web send not initialized.".to_string(),
+ ))
+}
+
+fn html_response(
+ status: StatusCode,
+ content: &'static str,
+ content_type: &'static str,
+) -> Response<BoxedBody> {
+ let mut response = Response::new(full_body(content));
+ *response.status_mut() = status;
+ response.headers_mut().insert(
+ http::header::CONTENT_TYPE,
+ http::HeaderValue::from_static(content_type),
+ );
+ response
+}
+
+fn error_403_page() -> Response<BoxedBody> {
+ html_response(
+ StatusCode::FORBIDDEN,
+ ERROR_403_HTML,
+ "text/html; charset=utf-8",
+ )
+}
+
+async fn file_list_response(
+ state: &AppState,
+ web: &WebPageState,
+ session_id: String,
+) -> Response<BoxedBody> {
+ let info = state.info.lock().await.clone();
+
+ JsonResponse {
+ status: StatusCode::OK,
+ body: PrepareDownloadResponseDtoV2 {
+ info: InfoResponseDtoV2 {
+ alias: info.alias,
+ version: PROTOCOL_VERSION_V2.to_string(),
+ device_model: info.device_model,
+ device_type: info.device_type,
+ fingerprint: info.token,
+ download: true,
+ },
+ session_id,
+ files: web
+ .files
+ .iter()
+ .map(|(id, file)| (id.clone(), file.dto.clone()))
+ .collect(),
+ },
+ }
+ .into_response()
+}
+
+/// Streams a file from disk as a response body.
+fn file_stream_body(mut file: tokio::fs::File) -> BoxedBody {
+ let (tx, rx) = mpsc::channel::<Result<Frame<Bytes>, std::io::Error>>(DOWNLOAD_CHANNEL_CAPACITY);
+
+ tokio::spawn(async move {
+ let mut buffer = vec![0u8; DOWNLOAD_BUFFER_SIZE];
+ loop {
+ match file.read(&mut buffer).await {
+ Ok(0) => break, // EOF
+ Ok(bytes_read) => {
+ let chunk = Bytes::copy_from_slice(&buffer[..bytes_read]);
+ if tx.send(Ok(Frame::data(chunk))).await.is_err() {
+ break; // client disconnected
+ }
+ }
+ Err(err) => {
+ let _ = tx.send(Err(err)).await;
+ break;
+ }
+ }
+ }
+ });
+
+ StreamBody::new(ReceiverStream::new(rx)).boxed()
+}
+
+/// Removes a pending download session unless it was accepted.
+///
+/// The cleanup also runs on drop so the session is not leaked
+/// when the request future is cancelled (e.g. the web client disconnected
+/// while the application was still deciding).
+struct PendingWebSessionGuard {
+ web: Arc<WebPageState>,
+ session_id: String,
+ armed: bool,
+}
+
+impl PendingWebSessionGuard {
+ fn new(web: Arc<WebPageState>, session_id: String) -> Self {
+ Self {
+ web,
+ session_id,
+ armed: true,
+ }
+ }
+
+ /// Disarms the guard after the session was accepted.
+ fn disarm(&mut self) {
+ self.armed = false;
+ }
+
+ /// Removes the pending session immediately.
+ async fn clear(&mut self) {
+ self.armed = false;
+ clear_pending_session(&self.web, &self.session_id).await;
+ }
+}
+
+impl Drop for PendingWebSessionGuard {
+ fn drop(&mut self) {
+ if !self.armed {
+ return;
+ }
+ let web = self.web.clone();
+ let session_id = std::mem::take(&mut self.session_id);
+ tokio::spawn(async move {
+ clear_pending_session(&web, &session_id).await;
+ });
+ }
+}
+
+async fn clear_pending_session(web: &WebPageState, session_id: &str) {
+ let mut sessions = web.sessions.lock().await;
+ if sessions
+ .get(session_id)
+ .is_some_and(|session| !session.accepted)
+ {
+ sessions.remove(session_id);
+ }
+}
diff --git a/core/src/http/server/error.rs b/core/src/http/server/error.rs
index 28b5f723..18227d3d 100644
--- a/core/src/http/server/error.rs
+++ b/core/src/http/server/error.rs
@@ -1,7 +1,5 @@
use crate::http::dto::ErrorResponse;
-use crate::http::server::response::JsonResponse;
-use bytes::Bytes;
-use http_body_util::Full;
+use crate::http::server::response::{BoxedBody, JsonResponse};
use hyper::{Response, StatusCode};
#[derive(Debug, thiserror::Error)]
@@ -20,7 +18,7 @@ pub enum AppError {
}
impl AppError {
- pub(crate) fn to_response(self) -> Response<Full<Bytes>> {
+ pub(crate) fn to_response(self) -> Response<BoxedBody> {
let json = match self {
AppError::Hyper(_) => JsonResponse {
status: StatusCode::INTERNAL_SERVER_ERROR,
diff --git a/core/src/http/server/event.rs b/core/src/http/server/event.rs
index f6d696ac..b7aeb579 100644
--- a/core/src/http/server/event.rs
+++ b/core/src/http/server/event.rs
@@ -58,6 +58,25 @@ pub enum ServerEventV2 {
result_tx: oneshot::Sender<Result<(), String>>,
},
+ /// A web client requests to download the shared files
+ /// via `POST /api/localsend/v2/prepare-download`.
+ ///
+ /// The application must answer on `decision_tx`.
+ /// Dropping `decision_tx` results in a 500 response.
+ PrepareDownload {
+ /// The IP address of the web client.
+ ip: IpAddr,
+
+ /// The ID of the download session that is created when accepted.
+ session_id: String,
+
+ /// The `User-Agent` header of the web client.
+ user_agent: Option<String>,
+
+ /// Channel to send the decision (`true` to accept, `false` to decline).
+ decision_tx: oneshot::Sender<bool>,
+ },
+
/// An upload session ended.
SessionEnd {
/// The session ID of the ended session.
diff --git a/core/src/http/server/mod.rs b/core/src/http/server/mod.rs
index 8e42cd02..fb684ccd 100644
--- a/core/src/http/server/mod.rs
+++ b/core/src/http/server/mod.rs
@@ -7,15 +7,18 @@ mod query;
mod response;
mod session;
+pub use crate::http::server::controller::web::{
+ WebSendConfig, WebSendFile, WebSendFileContent, WebSendI18n,
+};
+
use crate::crypto::cert::public_key_from_cert_der;
use crate::http::server::client_cert_verifier::CustomClientCertVerifier;
use crate::http::server::controller::web::WebPageState;
use crate::http::server::error::AppError;
use crate::http::server::event::ServerEventV2;
+use crate::http::server::response::BoxedBody;
use crate::http::server::session::SessionStateV2;
use crate::http::state::ClientInfo;
-use bytes::Bytes;
-use http_body_util::Full;
use hyper::body::Incoming;
use hyper::{Method, Request, Response, StatusCode};
use hyper_util::rt::{TokioExecutor, TokioIo};
@@ -37,6 +40,10 @@ pub struct ServerConfigV2 {
/// Channel on which the server emits events that must be handled by the application.
pub event_tx: mpsc::Sender<ServerEventV2>,
+
+ /// Configuration for web send (download API).
+ /// `None` disables the web page and download routes.
+ pub web_send: Option<WebSendConfig>,
}
/// Runtime state of the v2 protocol endpoints.
@@ -60,7 +67,7 @@ struct AppState {
info: Arc<Mutex<ClientInfo>>,
/// State for serving web pages.
- web: Arc<Mutex<Option<WebPageState>>>,
+ web: Option<Arc<WebPageState>>,
/// Maps client identifiers to nonces that have been received from remote.
received_nonce_map: Arc<Mutex<LruCache<String, Vec<u8>>>>,
@@ -74,23 +81,31 @@ struct AppState {
impl AppState {
fn new(info: Arc<Mutex<ClientInfo>>, v2_config: Option<ServerConfigV2>) -> Self {
+ let (v2, web) = match v2_config {
+ Some(config) => (
+ Some(Arc::new(V2State {
+ pin: config.pin,
+ event_tx: config.event_tx.clone(),
+ session: Mutex::new(None),
+ pin_attempts: Mutex::new(LruCache::new(NonZeroUsize::new(200).unwrap())),
+ })),
+ config
+ .web_send
+ .map(|web_config| Arc::new(WebPageState::new(web_config, config.event_tx))),
+ ),
+ None => (None, None),
+ };
+
Self {
info,
- web: Arc::new(Mutex::new(None)),
+ web,
received_nonce_map: Arc::new(Mutex::new(LruCache::new(
NonZeroUsize::new(200).unwrap(),
))),
generated_nonce_map: Arc::new(Mutex::new(LruCache::new(
NonZeroUsize::new(200).unwrap(),
))),
- v2: v2_config.map(|config| {
- Arc::new(V2State {
- pin: config.pin,
- event_tx: config.event_tx,
- session: Mutex::new(None),
- pin_attempts: Mutex::new(LruCache::new(NonZeroUsize::new(200).unwrap())),
- })
- }),
+ v2,
}
}
}
@@ -294,7 +309,7 @@ impl RequestClientInfo {
}
}
-async fn handle_request(req: Request<Incoming>) -> Result<Response<Full<Bytes>>, hyper::Error> {
+async fn handle_request(req: Request<Incoming>) -> Result<Response<BoxedBody>, hyper::Error> {
Ok(handle_request_inner(req).await.unwrap_or_else(|err| {
tracing::error!("Error handling request: {err:?}");
err.to_response()
@@ -303,7 +318,7 @@ async fn handle_request(req: Request<Incoming>) -> Result<Response<Full<Bytes>>,
async fn handle_request_inner(
mut req: Request<Incoming>,
-) -> Result<Response<Full<Bytes>>, AppError> {
+) -> Result<Response<BoxedBody>, AppError> {
let Some(state) = req.extensions_mut().remove::<AppState>() else {
return Err(AppError::Status(StatusCode::INTERNAL_SERVER_ERROR));
};
@@ -315,6 +330,15 @@ async fn handle_request_inner(
let v2_enabled = state.v2.is_some();
match (req.method(), req.uri().path()) {
+ (&Method::GET, "/") => Ok(controller::web::index(&state)),
+ (&Method::GET, "/main.js") => Ok(controller::web::main_js(&state)),
+ (&Method::GET, "/i18n.json") => controller::web::i18n(&state),
+ (&Method::POST, "/api/localsend/v2/prepare-download") => {
+ controller::web::prepare_download(req, state, client_info).await
+ }
+ (&Method::GET, "/api/localsend/v2/download") => {
+ controller::web::download(req, state, client_info).await
+ }
(&Method::POST, "/api/localsend/v2/register") => {
if !v2_enabled {
return Err(AppError::Status(StatusCode::NOT_FOUND));
@@ -369,7 +393,7 @@ async fn handle_request_inner(
)
}
_ => {
- let mut res = Response::new(Full::default());
+ let mut res = Response::new(response::empty_body());
*res.status_mut() = StatusCode::NOT_FOUND;
Ok(res)
}
diff --git a/core/src/http/server/response.rs b/core/src/http/server/response.rs
index 0f8a968d..259d677e 100644
--- a/core/src/http/server/response.rs
+++ b/core/src/http/server/response.rs
@@ -1,16 +1,32 @@
use bytes::Bytes;
-use http_body_util::Full;
+use http_body_util::combinators::BoxBody;
+use http_body_util::{BodyExt, Full};
use hyper::{http, Response, StatusCode};
use serde::Serialize;
+/// Response body that is either fully buffered or streamed (e.g. file downloads).
+pub(crate) type BoxedBody = BoxBody<Bytes, std::io::Error>;
+
+/// Creates a fully buffered response body.
+pub(crate) fn full_body(bytes: impl Into<Bytes>) -> BoxedBody {
+ Full::new(bytes.into())
+ .map_err(std::io::Error::other)
+ .boxed()
+}
+
+/// Creates an empty response body.
+pub(crate) fn empty_body() -> BoxedBody {
+ full_body(Bytes::new())
+}
+
pub(crate) struct JsonResponse<T: Serialize> {
pub(crate) status: StatusCode,
pub(crate) body: T,
}
impl<T: Serialize> JsonResponse<T> {
- pub(crate) fn into_response(self) -> Response<Full<Bytes>> {
- let mut response = Response::new(Full::default());
+ pub(crate) fn into_response(self) -> Response<BoxedBody> {
+ let mut response = Response::new(empty_body());
*response.status_mut() = self.status;
response.headers_mut().insert(
@@ -18,9 +34,9 @@ impl<T: Serialize> JsonResponse<T> {
http::HeaderValue::from_static("application/json"),
);
- *response.body_mut() = Full::from(Bytes::from(
+ *response.body_mut() = full_body(
serde_json::to_string(&self.body).unwrap_or_else(|_| "{}".to_string()),
- ));
+ );
response
}
diff --git a/core/src/main.rs b/core/src/main.rs
index 99113945..4bf555fa 100644
--- a/core/src/main.rs
+++ b/core/src/main.rs
@@ -184,6 +184,15 @@ async fn server_test() -> Result<()> {
let _ = result_tx.send(Ok(()));
});
}
+ ServerEventV2::PrepareDownload {
+ ip,
+ session_id,
+ decision_tx,
+ ..
+ } => {
+ tracing::info!("Prepare download from {ip} (session {session_id})");
+ let _ = decision_tx.send(true);
+ }
ServerEventV2::SessionEnd { session_id, reason } => {
tracing::info!("Session {session_id} ended: {reason:?}");
}
@@ -201,6 +210,7 @@ async fn server_test() -> Result<()> {
Some(ServerConfigV2 {
pin: None,
event_tx,
+ web_send: None,
}),
stop_rx,
)
diff --git a/core/tests/v2_server.rs b/core/tests/v2_server.rs
index eb062929..78553306 100644
--- a/core/tests/v2_server.rs
+++ b/core/tests/v2_server.rs
@@ -68,6 +68,7 @@ async fn start_test_server(pin: Option<String>, accept: bool) -> TestServer {
ServerEventV2::SessionEnd { session_id, reason } => {
session_ends.lock().await.push((session_id, reason));
}
+ ServerEventV2::PrepareDownload { .. } => {}
}
}
}
@@ -85,7 +86,11 @@ async fn start_test_server(pin: Option<String>, accept: bool) -> TestServer {
device_type: None,
token: "server-fingerprint".to_string(),
},
- Some(ServerConfigV2 { pin, event_tx }),
+ Some(ServerConfigV2 {
+ pin,
+ event_tx,
+ web_send: None,
+ }),
stop_rx,
)
.await
diff --git a/core/tests/v2_web_send.rs b/core/tests/v2_web_send.rs
new file mode 100644
index 00000000..9fdb2f0f
--- /dev/null
+++ b/core/tests/v2_web_send.rs
@@ -0,0 +1,437 @@
+#![cfg(feature = "http")]
+
+use bytes::Bytes;
+use localsend::http::client::{ClientError, LsHttpClientV2};
+use localsend::http::dto::ProtocolType;
+use localsend::http::server::event::ServerEventV2;
+use localsend::http::server::{
+ start_with_port, ServerConfigV2, WebSendConfig, WebSendFile, WebSendFileContent, WebSendI18n,
+};
+use localsend::http::state::ClientInfo;
+use localsend::model::transfer::FileDto;
+use std::collections::HashMap;
+use std::net::IpAddr;
+use std::path::PathBuf;
+use std::sync::atomic::{AtomicU16, AtomicU32, Ordering};
+use std::sync::Arc;
+use std::time::Duration;
+use tokio::sync::oneshot;
+
+struct TestServer {
+ port: u16,
+ /// Number of `PrepareDownload` events received.
+ prepare_download_events: Arc<AtomicU32>,
+ _stop_tx: oneshot::Sender<()>,
+}
+
+async fn start_test_server(web_send: Option<WebSendConfig>, accept: bool) -> TestServer {
+ let _ = tracing_subscriber::fmt().with_test_writer().try_init();
+ let port = free_port();
+ let prepare_download_events = Arc::new(AtomicU32::new(0));
+
+ let (event_tx, mut event_rx) = tokio::sync::mpsc::channel::<ServerEventV2>(16);
+
+ tokio::spawn({
+ let prepare_download_events = prepare_download_events.clone();
+ async move {
+ while let Some(event) = event_rx.recv().await {
+ if let ServerEventV2::PrepareDownload { decision_tx, .. } = event {
+ prepare_download_events.fetch_add(1, Ordering::SeqCst);
+ let _ = decision_tx.send(accept);
+ }
+ }
+ }
+ });
+
+ let (stop_tx, stop_rx) = oneshot::channel::<()>();
+
+ start_with_port(
+ port,
+ None, // plain HTTP
+ ClientInfo {
+ alias: "Test Server".to_string(),
+ version: "2.1".to_string(),
+ device_model: Some("Rust".to_string()),
+ device_type: None,
+ token: "server-fingerprint".to_string(),
+ },
+ Some(ServerConfigV2 {
+ pin: None,
+ event_tx,
+ web_send,
+ }),
+ stop_rx,
+ )
+ .await
+ .expect("Failed to start server");
+
+ wait_until_reachable(port).await;
+
+ TestServer {
+ port,
+ prepare_download_events,
+ _stop_tx: stop_tx,
+ }
+}
+
+/// Returns a free port.
+///
+/// A counter is used instead of binding to port 0 because the OS may hand out
+/// the same just-freed ephemeral port to multiple tests running in parallel.
+fn free_port() -> u16 {
+ static PORT_COUNTER: AtomicU16 = AtomicU16::new(41551);
+
+ loop {
+ let port = PORT_COUNTER.fetch_add(1, Ordering::SeqCst);
+ if std::net::TcpListener::bind(("127.0.0.1", port)).is_ok() {
+ return port;
+ }
+ }
+}
+
+async fn wait_until_reachable(port: u16) {
+ for _ in 0..100 {
+ if tokio::net::TcpStream::connect(("127.0.0.1", port))
+ .await
+ .is_ok()
+ {
+ return;
+ }
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+ panic!("Server did not become reachable on port {port}");
+}
+
+fn file_dto(id: &str, name: &str, size: u64) -> FileDto {
+ FileDto {
+ id: id.to_string(),
+ file_name: name.to_string(),
+ size,
+ file_type: "application/octet-stream".to_string(),
+ sha256: None,
+ preview: None,
+ metadata: None,
+ }
+}
+
+/// Creates a web send config with an in-memory text file and a file on disk.
+///
+/// Returns the config and the path of the file on disk (the caller should delete it).
+fn web_send_config(pin: Option<String>) -> (WebSendConfig, PathBuf, Vec<u8>) {
+ let disk_content: Vec<u8> = (0..100_000u32).map(|i| i as u8).collect();
+ let disk_path = std::env::temp_dir().join(format!("localsend-web-send-{}", uuid::Uuid::new_v4()));
+ std::fs::write(&disk_path, &disk_content).expect("Failed to write test file");
+
+ let files = HashMap::from([
+ (
+ "file-text".to_string(),
+ WebSendFile {
+ dto: file_dto("file-text", "message.txt", 5),
+ content: WebSendFileContent::Bytes(Bytes::from_static(b"hello")),
+ },
+ ),
+ (
+ "file-disk".to_string(),
+ WebSendFile {
+ dto: file_dto("file-disk", "dir/data.bin", disk_content.len() as u64),
+ content: WebSendFileContent::Path(disk_path.clone()),
+ },
+ ),
+ ]);
+
+ (
+ WebSendConfig {
+ files,
+ pin,
+ i18n: WebSendI18n::default(),
+ },
+ disk_path,
+ disk_content,
+ )
+}
+
+fn assert_status(result: Result<impl Sized, ClientError>, expected_status: u16) {
+ match result {
+ Err(ClientError::StatusCode(err)) => assert_eq!(err.status, expected_status),
+ Err(err) => panic!("Expected status code {expected_status}, got error: {err:?}"),
+ Ok(_) => panic!("Expected status code {expected_status}, got success"),
+ }
+}
+
+#[tokio::test]
+async fn test_web_page() {
+ let (config, disk_path, _) = web_send_config(None);
+ let server = start_test_server(Some(config), true).await;
+ let client = localsend::reqwest::Client::new();
+ let base_url = format!("http://127.0.0.1:{}", server.port);
+
+ let response = client.get(&base_url).send().await.unwrap();
+ assert_eq!(response.status().as_u16(), 200);
+ assert!(response.text().await.unwrap().contains("LocalSend"));
+
+ let response = client
+ .get(format!("{base_url}/main.js"))
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(response.status().as_u16(), 200);
+ assert_eq!(
+ response.headers()["content-type"],
+ "text/javascript; charset=utf-8"
+ );
+
+ let response = client
+ .get(format!("{base_url}/i18n.json"))
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(response.status().as_u16(), 200);
+ let i18n = response
+ .json::<HashMap<String, String>>()
+ .await
+ .unwrap();
+ assert_eq!(i18n["enterPin"], "Enter PIN");
+ assert!(i18n.contains_key("waiting"));
+
+ // The register/info endpoints advertise the download API.
+ let info = LsHttpClientV2::try_new_without_cert()
+ .unwrap()
+ .info(ProtocolType::Http, "127.0.0.1", server.port)
+ .await
+ .unwrap();
+ assert!(info.download);
+
+ let _ = std::fs::remove_file(disk_path);
+}
+
+#[tokio::test]
+async fn test_web_page_disabled() {
+ let server = start_test_server(None, true).await;
+ let client = localsend::reqwest::Client::new();
+ let base_url = format!("http://127.0.0.1:{}", server.port);
+
+ let response = client.get(&base_url).send().await.unwrap();
+ assert_eq!(response.status().as_u16(), 403);
+
+ let response = client
+ .post(format!("{base_url}/api/localsend/v2/prepare-download"))
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(response.status().as_u16(), 403);
+
+ let info = LsHttpClientV2::try_new_without_cert()
+ .unwrap()
+ .info(ProtocolType::Http, "127.0.0.1", server.port)
+ .await
+ .unwrap();
+ assert!(!info.download);
+}
+
+#[tokio::test]
+async fn test_full_download_flow() {
+ let (config, disk_path, disk_content) = web_send_config(None);
+ let server = start_test_server(Some(config), true).await;
+ let client = LsHttpClientV2::try_new_without_cert().unwrap();
+
+ let response = client
+ .prepare_download(ProtocolType::Http, "127.0.0.1", server.port, None, None)
+ .await
+ .unwrap();
+
+ assert_eq!(response.info.alias, "Test Server");
+ assert_eq!(response.files.len(), 2);
+ assert_eq!(response.files["file-text"].file_name, "message.txt");
+ assert_eq!(server.prepare_download_events.load(Ordering::SeqCst), 1);
+
+ // Download the in-memory file.
+ let mut bytes = Vec::new();
+ client
+ .download_to_writer(
+ ProtocolType::Http,
+ "127.0.0.1",
+ server.port,
+ &response.session_id,
+ "file-text",
+ &mut bytes,
+ )
+ .await
+ .unwrap();
+ assert_eq!(bytes, b"hello");
+
+ // Download the file from disk (streamed).
+ let download_response = client
+ .download(
+ ProtocolType::Http,
+ "127.0.0.1",
+ server.port,
+ &response.session_id,
+ "file-disk",
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ download_response.headers()["content-length"],
+ disk_content.len().to_string().as_str()
+ );
+ assert_eq!(
+ download_response.headers()["content-disposition"],
+ "attachment; filename=\"dir-data.bin\""
+ );
+ assert_eq!(
+ download_response.bytes().await.unwrap().as_ref(),
+ disk_content.as_slice()
+ );
+
+ // The session can be reused without a new permission request (e.g. page reload).
+ let reused = client
+ .prepare_download(
+ ProtocolType::Http,
+ "127.0.0.1",
+ server.port,
+ Some(&response.session_id),
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(reused.session_id, response.session_id);
+ assert_eq!(server.prepare_download_events.load(Ordering::SeqCst), 1);
+
+ let _ = std::fs::remove_file(disk_path);
+}
+
+#[tokio::test]
+async fn test_prepare_download_rejected() {
+ let (config, disk_path, _) = web_send_config(None);
+ let server = start_test_server(Some(config), false).await;
+ let client = LsHttpClientV2::try_new_without_cert().unwrap();
+
+ let result = client
+ .prepare_download(ProtocolType::Http, "127.0.0.1", server.port, None, None)
+ .await;
+ assert_status(result, 403);
+
+ // The rejected session must not allow downloads.
+ let local_ip: IpAddr = "127.0.0.1".parse().unwrap();
+ let result = client
+ .download(
+ ProtocolType::Http,
+ "127.0.0.1",
+ server.port,
+ &local_ip.to_string(),
+ "file-text",
+ )
+ .await;
+ assert_status(result, 403);
+
+ let _ = std::fs::remove_file(disk_path);
+}
+
+#[tokio::test]
+async fn test_download_invalid_session() {
+ let (config, disk_path, _) = web_send_config(None);
+ let server = start_test_server(Some(config), true).await;
+ let client = LsHttpClientV2::try_new_without_cert().unwrap();
+
+ let result = client
+ .download(
+ ProtocolType::Http,
+ "127.0.0.1",
+ server.port,
+ "unknown-session",
+ "file-text",
+ )
+ .await;
+ assert_status(result, 403);
+
+ // Valid session but unknown file.
+ let response = client
+ .prepare_download(ProtocolType::Http, "127.0.0.1", server.port, None, None)
+ .await
+ .unwrap();
+ let result = client
+ .download(
+ ProtocolType::Http,
+ "127.0.0.1",
+ server.port,
+ &response.session_id,
+ "unknown-file",
+ )
+ .await;
+ assert_status(result, 403);
+
+ let _ = std::fs::remove_file(disk_path);
+}
+
+#[tokio::test]
+async fn test_pin() {
+ let (config, disk_path, _) = web_send_config(Some("123456".to_string()));
+ let server = start_test_server(Some(config), true).await;
+ let client = LsHttpClientV2::try_new_without_cert().unwrap();
+
+ // Missing PIN.
+ let result = client
+ .prepare_download(ProtocolType::Http, "127.0.0.1", server.port, None, None)
+ .await;
+ assert_status(result, 401);
+
+ // Wrong PIN.
+ let result = client
+ .prepare_download(
+ ProtocolType::Http,
+ "127.0.0.1",
+ server.port,
+ None,
+ Some("000000"),
+ )
+ .await;
+ assert_status(result, 401);
+
+ // Correct PIN.
+ client
+ .prepare_download(
+ ProtocolType::Http,
+ "127.0.0.1",
+ server.port,
+ None,
+ Some("123456"),
+ )
+ .await
+ .unwrap();
+
+ let _ = std::fs::remove_file(disk_path);
+}
+
+#[tokio::test]
+async fn test_pin_too_many_attempts() {
+ let (config, disk_path, _) = web_send_config(Some("123456".to_string()));
+ let server = start_test_server(Some(config), true).await;
+ let client = LsHttpClientV2::try_new_without_cert().unwrap();
+
+ for _ in 0..3 {
+ let result = client
+ .prepare_download(
+ ProtocolType::Http,
+ "127.0.0.1",
+ server.port,
+ None,
+ Some("000000"),
+ )
+ .await;
+ assert_status(result, 401);
+ }
+
+ // Blocked even with the correct PIN.
+ let result = client
+ .prepare_download(
+ ProtocolType::Http,
+ "127.0.0.1",
+ server.port,
+ None,
+ Some("123456"),
+ )
+ .await;
+ assert_status(result, 429);
+
+ let _ = std::fs::remove_file(disk_path);
+}