From b52a28b85f0bbeefb3d48598ecb83eb467a5d545 Mon Sep 17 00:00:00 2001 From: zarzet <42882290+zarzet@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:37:44 +0700 Subject: [PATCH] feat(link): serve songs the app lends to the Link server A catalog path that is a URI, such as an Android storage access document, opens through the app: the server forwards server/files/open without a device, duplicates the descriptor the app lends and forwards server/files/close when the response ends, the client goes away or any step fails. Lent files are bounded, opened one at a time, and serve streams with ranges, downloads, embedded covers and lyrics. Phones cannot send the server's own ops, and plain paths take the old route. --- rust_backend/crates/link/src/api.rs | 10 +- rust_backend/crates/link/src/lib.rs | 2 + rust_backend/crates/link/src/source.rs | 288 +++++++++++++++++ rust_backend/crates/link/src/subsonic.rs | 4 +- .../crates/link/src/subsonic/covers.rs | 112 +++++-- .../crates/link/src/subsonic/lyrics.rs | 56 +++- .../crates/link/src/subsonic/media.rs | 68 +++- .../crates/link/src/subsonic/objects.rs | 6 +- .../crates/link/src/subsonic/tests.rs | 19 +- .../crates/link/src/subsonic/tests/covers.rs | 2 +- .../crates/link/src/subsonic/tests/lent.rs | 302 ++++++++++++++++++ rust_backend/crates/link/src/types.rs | 2 + rust_backend/crates/link/src/ws/tests.rs | 1 + rust_backend/crates/link/tests/server.rs | 126 +++++++- 14 files changed, 936 insertions(+), 62 deletions(-) create mode 100644 rust_backend/crates/link/src/source.rs create mode 100644 rust_backend/crates/link/src/subsonic/tests/lent.rs diff --git a/rust_backend/crates/link/src/api.rs b/rust_backend/crates/link/src/api.rs index ffbeb1cbd..f104438a5 100644 --- a/rust_backend/crates/link/src/api.rs +++ b/rust_backend/crates/link/src/api.rs @@ -12,7 +12,7 @@ use crate::files::{self, ReceiveError}; use crate::pairing::{PAIRED, PairError}; use crate::server::{MAX_BODY, State}; use crate::types::{Device, HttpResponse, SubsonicRequest, json}; -use crate::{auth, subsonic, ws}; +use crate::{auth, source, subsonic, ws}; use bytes::Bytes; use http::{HeaderMap, Method, header}; use http_body_util::{BodyExt, LengthLimitError, Limited}; @@ -186,9 +186,11 @@ async fn forward(state: &Arc, op: &str, request: http::Request) let Some(record) = auth::bearer(&state.store, request.headers()) else { return unauthorized(); }; - if op - .split('/') - .any(|segment| segment.is_empty() || segment == "." || segment == "..") + // Only the server itself asks the app to lend it files. + if source::is_server_op(op) + || op + .split('/') + .any(|segment| segment.is_empty() || segment == "." || segment == "..") { return not_found(); } diff --git a/rust_backend/crates/link/src/lib.rs b/rust_backend/crates/link/src/lib.rs index 64773f14a..ec7a695aa 100644 --- a/rust_backend/crates/link/src/lib.rs +++ b/rust_backend/crates/link/src/lib.rs @@ -21,6 +21,7 @@ mod files; mod mdns; mod pairing; mod server; +mod source; mod store; mod tls; mod ws; @@ -105,6 +106,7 @@ impl LinkServer { timeout: tuning.request_timeout, }), catalog: RwLock::new(Arc::new(Catalog::empty())), + leases: Default::default(), }); let state = Arc::new(State { shared, diff --git a/rust_backend/crates/link/src/source.rs b/rust_backend/crates/link/src/source.rs new file mode 100644 index 000000000..cf4c03b70 --- /dev/null +++ b/rust_backend/crates/link/src/source.rs @@ -0,0 +1,288 @@ +//! Turns a catalog song's path into a file the server can read. A plain path +//! opens directly, as it always has. A URI (an Android storage access +//! `content://` document) only the app can open: the server forwards +//! [`OPEN_OP`] without a device, the app lends a path it may read, and the +//! server forwards [`CLOSE_OP`] once its response is finished, the client went +//! away, or anything failed on the way. The lease is named before the app is +//! asked, so even an open that times out or is abandoned is closed. + +use crate::types::{Host, Shared}; +use serde_json::{Value, json}; +use std::fs::Metadata; +use std::io::{self, Seek}; +use std::path::Path; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::Duration; +use tokio::sync::{Mutex, OwnedSemaphorePermit, Semaphore}; + +/// Asks the app to lend a file: `{"uri","lease"}`, answered `{"path"}`. +pub(crate) const OPEN_OP: &str = "server/files/open"; +/// Ends a lease: `{"lease"}`. +pub(crate) const CLOSE_OP: &str = "server/files/close"; +/// Files lent at once; more requests wait for one to be returned. +const MAX_LEASES: usize = 8; +/// How long a request waits for a lease before it gives up. +const LEASE_WAIT: Duration = Duration::from_secs(10); + +/// Lease names, unique for the process so a late close never meets a new +/// lease of the same name. +static NEXT_LEASE: AtomicU64 = AtomicU64::new(0); + +/// Whether `op` is one only the server itself forwards, which a phone may not +/// send. +pub(crate) fn is_server_op(op: &str) -> bool { + op == "server" || op.starts_with("server/") +} + +/// Whether only the app can open `path`: a URI rather than a file path. +pub(crate) fn needs_app(path: &Path) -> bool { + let Some((scheme, _)) = path.to_str().and_then(|text| text.split_once("://")) else { + return false; + }; + let mut chars = scheme.chars(); + chars + .next() + .is_some_and(|first| first.is_ascii_alphabetic()) + && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')) + && !scheme.eq_ignore_ascii_case("file") +} + +/// The name a song's file goes by: the last part of its path, a URI's decoded +/// document name, else its title and suffix. +pub(crate) fn file_name(path: &Path, title: &str, suffix: &str) -> String { + let fallback = || format!("{title}.{suffix}"); + if !needs_app(path) { + return path + .file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_else(fallback); + } + let text = path.to_string_lossy(); + let segment = text.rsplit('/').next().unwrap_or_default(); + let decoded = percent_decode(segment.split(['?', '#']).next().unwrap_or_default()); + // A document id such as `primary:Music/Artist/Song.flac`. + let name = decoded.rsplit(['/', ':']).next().unwrap_or_default().trim(); + match name.rfind('.') { + Some(dot) if dot > 0 && dot + 1 < name.len() => name.to_owned(), + _ => fallback(), + } +} + +fn percent_decode(text: &str) -> String { + let bytes = text.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut index = 0; + while index < bytes.len() { + let hex = |at: usize| bytes.get(at).and_then(|byte| (*byte as char).to_digit(16)); + match (bytes[index], hex(index + 1), hex(index + 2)) { + (b'%', Some(high), Some(low)) => { + out.push((high * 16 + low) as u8); + index += 3; + } + (byte, _, _) => { + out.push(byte); + index += 1; + } + } + } + String::from_utf8_lossy(&out).into_owned() +} + +/// The server's leases on files the app lends. +pub(crate) struct Leases { + permits: Arc, + wait: Duration, + /// Held from asking the app until the server holds its own copy of the + /// descriptor: the app gives up its oldest descriptor when it holds too + /// many, so one lent file is copied before the next is asked for. + opening: Mutex<()>, +} + +impl Leases { + /// At most `max` files lent at once; a request waits `wait` for one. + pub(crate) fn new(max: usize, wait: Duration) -> Self { + Self { + permits: Arc::new(Semaphore::new(max)), + wait, + opening: Mutex::new(()), + } + } +} + +impl Default for Leases { + fn default() -> Self { + Self::new(MAX_LEASES, LEASE_WAIT) + } +} + +/// The app's lease on one file. Dropping it forwards [`CLOSE_OP`] and frees +/// its place. +pub(crate) struct Lease { + host: Arc, + id: String, + _permit: OwnedSemaphorePermit, +} + +impl Drop for Lease { + fn drop(&mut self) { + // The host sends the request when called; awaiting the reply only + // lets it forget the request in good order. + let closed = self.host.request(CLOSE_OP, "", json!({ "lease": self.id })); + if let Ok(runtime) = tokio::runtime::Handle::try_current() { + drop(runtime.spawn(closed)); + } + } +} + +/// Why a file could not be opened. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum OpenError { + /// Not a readable file, or the app could not lend it. + Missing, + /// Every lease was taken and none was returned in time. + Busy, +} + +/// A song's file open for reading, and the lease that keeps a lent one +/// readable. Hold the lease until done reading. +pub(crate) struct Readable { + pub(crate) file: tokio::fs::File, + pub(crate) metadata: Metadata, + pub(crate) lease: Option, +} + +/// Opens the catalog file at `path`, directly or through the app. +pub(crate) async fn open(shared: &Shared, path: &Path) -> Result { + if !needs_app(path) { + let file = tokio::fs::File::open(path) + .await + .map_err(|_| OpenError::Missing)?; + let metadata = file.metadata().await.map_err(|_| OpenError::Missing)?; + return regular(file, metadata, None); + } + let uri = path.to_str().ok_or(OpenError::Missing)?; + let leases = &shared.leases; + let permit = tokio::time::timeout(leases.wait, Arc::clone(&leases.permits).acquire_owned()) + .await + .map_err(|_| OpenError::Busy)? + .map_err(|_| OpenError::Busy)?; + let lease = Lease { + host: Arc::clone(&shared.host), + id: (NEXT_LEASE.fetch_add(1, Ordering::Relaxed) + 1).to_string(), + _permit: permit, + }; + let file = { + let _opening = leases.opening.lock().await; + let reply = shared + .host + .request(OPEN_OP, "", json!({ "uri": uri, "lease": lease.id })) + .await + .map_err(|_| OpenError::Missing)?; + let lent = reply + .get("path") + .and_then(Value::as_str) + .ok_or(OpenError::Missing)?; + let mut file = duplicate(lent).map_err(|_| OpenError::Missing)?; + // A copy shares the descriptor's position; reading starts at the top. + file.rewind().map_err(|_| OpenError::Missing)?; + file + }; + let file = tokio::fs::File::from_std(file); + let metadata = file.metadata().await.map_err(|_| OpenError::Missing)?; + regular(file, metadata, Some(lease)) +} + +fn regular( + file: tokio::fs::File, + metadata: Metadata, + lease: Option, +) -> Result { + if !metadata.is_file() { + return Err(OpenError::Missing); + } + Ok(Readable { + file, + metadata, + lease, + }) +} + +/// The file behind the path the app lent. A descriptor path +/// (`/proc/self/fd/N`, `/dev/fd/N`) is duplicated: Android refuses to reopen +/// a proxied descriptor, and the copy stays readable whatever the app does +/// with its own. Any other path is opened. +fn duplicate(lent: &str) -> io::Result { + #[cfg(unix)] + if let Some(number) = lent + .strip_prefix("/proc/self/fd/") + .or_else(|| lent.strip_prefix("/dev/fd/")) + { + use std::os::fd::BorrowedFd; + let descriptor = number + .parse::() + .ok() + .filter(|descriptor| *descriptor >= 0) + .ok_or(io::ErrorKind::InvalidData)?; + // The app keeps the descriptor open until the lease closes, which + // is after this copy is made. + #[allow(unsafe_code)] + let owned = unsafe { BorrowedFd::borrow_raw(descriptor) }.try_clone_to_owned()?; + return Ok(std::fs::File::from(owned)); + } + std::fs::File::open(lent) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_uris_need_the_app() { + for path in [ + "content://com.example.documents/tree/a/document/a%3AMusic%2FSong.flac", + "content://media/external/audio/media/12", + ] { + assert!(needs_app(Path::new(path)), "{path}"); + } + for path in [ + "/music/Song.flac", + "/music/odd://name.flac", + "C:\\Music\\Song.flac", + "file:///music/Song.flac", + "relative/Song.flac", + ] { + assert!(!needs_app(Path::new(path)), "{path}"); + } + } + + #[test] + fn a_uri_is_named_by_its_document() { + let name = |path: &str| file_name(Path::new(path), "Title", "flac"); + assert_eq!( + name( + "content://com.example.documents/tree/a%3AMusic/document/a%3AMusic%2FBand%2FCaf%C3%A9.flac" + ), + "Café.flac" + ); + assert_eq!( + name("content://com.example.documents/document/a%3ASong.mp3"), + "Song.mp3" + ); + assert_eq!( + name("content://media/external/audio/media/12"), + "Title.flac" + ); + assert_eq!(name("/music/Band/Song.m4a"), "Song.m4a"); + assert_eq!(name("/"), "Title.flac"); + } + + #[test] + fn server_ops_are_told_apart() { + assert!(is_server_op(OPEN_OP)); + assert!(is_server_op(CLOSE_OP)); + assert!(is_server_op("server")); + assert!(!is_server_op("servers/x")); + assert!(!is_server_op("handoff/play")); + } +} diff --git a/rust_backend/crates/link/src/subsonic.rs b/rust_backend/crates/link/src/subsonic.rs index 78db6136d..33a43ffd0 100644 --- a/rust_backend/crates/link/src/subsonic.rs +++ b/rust_backend/crates/link/src/subsonic.rs @@ -105,7 +105,7 @@ pub async fn handle(shared: &Shared, request: SubsonicRequest) -> HttpResponse { let catalog = shared.catalog(); let binary = match request.method.as_str() { "stream" => media::stream(shared, &catalog, &request).await, - "download" => media::download(&catalog, &request).await, + "download" => media::download(shared, &catalog, &request).await, "getCoverArt" => covers::cover_art(shared, &catalog, &request).await, method => { let outcome = if forward::handles(method) { @@ -161,7 +161,7 @@ async fn dispatch( "getArtist" => browse::artist(catalog, request), "getAlbum" => browse::album(catalog, request), "getSong" => browse::song(catalog, request), - "getLyricsBySongId" => lyrics::by_song_id(catalog, request).await, + "getLyricsBySongId" => lyrics::by_song_id(shared, catalog, request).await, "getMusicDirectory" => browse::directory(catalog, request), "getAlbumList" => browse::album_list(shared, catalog, request, false).await, "getAlbumList2" => browse::album_list(shared, catalog, request, true).await, diff --git a/rust_backend/crates/link/src/subsonic/covers.rs b/rust_backend/crates/link/src/subsonic/covers.rs index b4dd963cb..ff9fde6b0 100644 --- a/rust_backend/crates/link/src/subsonic/covers.rs +++ b/rust_backend/crates/link/src/subsonic/covers.rs @@ -9,6 +9,7 @@ use super::media::file_response; use super::{Failure, number, required}; use crate::catalog::{Catalog, cover_format, hex}; +use crate::source::{self, Readable}; use crate::types::{HttpResponse, Shared, SubsonicRequest, full}; use http::header::{CACHE_CONTROL, ETAG, IF_NONE_MATCH}; use http::{HeaderMap, Response}; @@ -73,11 +74,12 @@ pub(super) async fn cover_art( let web: Vec = source.web.into_iter().map(Path::to_owned).collect(); let dir = shared.config.temp_dir.join(CACHE_DIR); let cache = dir.clone(); - let image = tokio::task::spawn_blocking(move || find_image(&cache, &files, &candidates, &web)) - .await - .ok() - .flatten() - .ok_or_else(not_found)?; + let image = if candidates.iter().any(|(audio, _)| source::needs_app(audio)) { + find_image_lent(shared, dir.clone(), files, candidates, web).await + } else { + blocking(move || find_image(&cache, &files, &candidates, &web)).await + } + .ok_or_else(not_found)?; let size = number::(request, "size") .filter(|size| *size > 0) .map(|size| u32::try_from(size.min(i64::from(MAX_EDGE))).unwrap_or(MAX_EDGE)); @@ -103,9 +105,22 @@ pub(super) async fn cover_art( { (target, content_type) = resized; } - file_response(&target, content_type, &request.headers, cache_headers) - .await - .map_err(|_| not_found()) + file_response( + shared, + &target, + content_type, + &request.headers, + cache_headers, + ) + .await + .map_err(|_| not_found()) +} + +/// `work` on the blocking pool. +async fn blocking( + work: impl FnOnce() -> Option + Send + 'static, +) -> Option { + tokio::task::spawn_blocking(work).await.ok().flatten() } /// The modification time in nanoseconds since the epoch, 0 when unknown. @@ -139,24 +154,67 @@ fn find_image( candidates: &[(PathBuf, &'static str)], web: &[PathBuf], ) -> Option { - let on_disk = |path: &PathBuf| { - let metadata = fs::metadata(path).ok().filter(fs::Metadata::is_file)?; - Some(Image { - path: path.clone(), - len: metadata.len(), - content_type: sniff(path), - stamp: version_stamp(path, &metadata), - }) - }; files .iter() - .find_map(on_disk) + .find_map(|path| on_disk(path)) .or_else(|| { candidates .iter() .find_map(|(audio, format)| extract_cached(dir, audio, format)) }) - .or_else(|| web.iter().find_map(on_disk)) + .or_else(|| web.iter().find_map(|path| on_disk(path))) +} + +/// [`find_image`] when an audio file is one the app lends: the same order, +/// each lent file borrowed only while its picture is looked for. A lent +/// file is borrowed even when its picture is cached, since its version +/// stamp comes from the open file. +async fn find_image_lent( + shared: &Shared, + dir: PathBuf, + files: Vec, + candidates: Vec<(PathBuf, &'static str)>, + web: Vec, +) -> Option { + if let Some(image) = blocking(move || files.iter().find_map(|path| on_disk(path))).await { + return Some(image); + } + for (audio, format) in candidates { + let dir = dir.clone(); + let image = if source::needs_app(&audio) { + let Ok(Readable { + file, + metadata, + lease, + }) = source::open(shared, &audio).await + else { + continue; + }; + let file = file.into_std().await; + blocking(move || { + let _lease = lease; + extract_into(&dir, &audio, format, &metadata, || Some(file)) + }) + .await + } else { + blocking(move || extract_cached(&dir, &audio, format)).await + }; + if image.is_some() { + return image; + } + } + blocking(move || web.iter().find_map(|path| on_disk(path))).await +} + +/// `path` as the image to serve, when it is a file. +fn on_disk(path: &Path) -> Option { + let metadata = fs::metadata(path).ok().filter(fs::Metadata::is_file)?; + Some(Image { + path: path.to_owned(), + len: metadata.len(), + content_type: sniff(path), + stamp: version_stamp(path, &metadata), + }) } /// Identifies one version of a file: its path, mtime and length. @@ -269,8 +327,20 @@ impl Seek for Watched { /// cache is unwritable. fn extract_cached(dir: &Path, audio: &Path, format: &str) -> Option { let metadata = fs::metadata(audio).ok().filter(fs::Metadata::is_file)?; + extract_into(dir, audio, format, &metadata, || fs::File::open(audio).ok()) +} + +/// [`extract_cached`] for the audio file `audio` with `metadata`, which +/// `open` opens only when its picture is not cached yet. +fn extract_into( + dir: &Path, + audio: &Path, + format: &str, + metadata: &fs::Metadata, + open: impl FnOnce() -> Option, +) -> Option { // The picture is a version of the audio file, whatever its cached copy. - let stamp = format!("embedded\0{}", version_stamp(audio, &metadata)); + let stamp = format!("embedded\0{}", version_stamp(audio, metadata)); let key = digest(&stamp); if without_picture().contains(&key) { return None; @@ -295,7 +365,7 @@ fn extract_cached(dir: &Path, audio: &Path, format: &str) -> Option { stamp, }); } - let cover = match read_picture(fs::File::open(audio).ok()?, format).ok()? { + let cover = match read_picture(open()?, format).ok()? { Some(cover) => cover, None => { remember_without_picture(key); diff --git a/rust_backend/crates/link/src/subsonic/lyrics.rs b/rust_backend/crates/link/src/subsonic/lyrics.rs index a2015c42b..9479499c3 100644 --- a/rust_backend/crates/link/src/subsonic/lyrics.rs +++ b/rust_backend/crates/link/src/subsonic/lyrics.rs @@ -6,11 +6,14 @@ use super::{Failure, Payload, payload, required}; use crate::catalog::Catalog; -use crate::types::SubsonicRequest; +use crate::source::{self, Readable}; +use crate::types::{Shared, SubsonicRequest}; use mornye_core::lyrics::{file, lrc}; use regex::Regex; use serde_json::{Value, json}; use std::fs::File; +use std::io::{Seek, SeekFrom}; +use std::path::Path; use std::sync::LazyLock; /// One or more leading `[mm:ss.xx]` stamps (a line sung more than once). @@ -27,22 +30,27 @@ static HEADER: LazyLock = /// A song without lyrics answers an empty `structuredLyrics`; an unknown id /// answers error 70. pub(super) async fn by_song_id( + shared: &Shared, catalog: &Catalog, request: &SubsonicRequest, ) -> Result { let id = required(request, "id")?; let song = catalog.song(id).ok_or_else(|| Failure::not_found("Song"))?; let path = song.path.to_string_lossy().into_owned(); - let raw = tokio::task::spawn_blocking(move || { - file::extract( - &path, - &|path| File::open(path).map_err(|error| error.to_string()), - &|| Ok(()), - ) - }) - .await - .ok() - .and_then(Result::ok) + let raw = if source::needs_app(&song.path) { + lent_lyrics(shared, &song.path, path).await + } else { + tokio::task::spawn_blocking(move || { + file::extract( + &path, + &|path| File::open(path).map_err(|error| error.to_string()), + &|| Ok(()), + ) + }) + .await + .ok() + .and_then(Result::ok) + } .unwrap_or_default(); let entries = if lrc::has_usable_content(&raw) { vec![structured(&song.artist, &song.title, raw)] @@ -55,6 +63,32 @@ pub(super) async fn by_song_id( )) } +/// The lyrics embedded in a file the app lends. A URI has no sidecar beside +/// it, so only the file itself is read. +async fn lent_lyrics(shared: &Shared, uri: &Path, path: String) -> Option { + let Readable { file, lease, .. } = source::open(shared, uri).await.ok()?; + let file = file.into_std().await; + tokio::task::spawn_blocking(move || { + let _lease = lease; + file::extract( + &path, + &|wanted| { + if wanted != path { + return Err("only the song itself is lent".to_owned()); + } + let mut copy = file.try_clone().map_err(|error| error.to_string())?; + copy.seek(SeekFrom::Start(0)) + .map_err(|error| error.to_string())?; + Ok(copy) + }, + &|| Ok(()), + ) + }) + .await + .ok() + .and_then(Result::ok) +} + fn structured(artist: &str, title: &str, raw: String) -> Value { let (synced, line): (bool, Vec) = match lrc::parse_synced(&raw) { Some(lines) => { diff --git a/rust_backend/crates/link/src/subsonic/media.rs b/rust_backend/crates/link/src/subsonic/media.rs index 3b9b7481a..539903c00 100644 --- a/rust_backend/crates/link/src/subsonic/media.rs +++ b/rust_backend/crates/link/src/subsonic/media.rs @@ -4,6 +4,7 @@ use super::objects::content_type; use super::{Failure, number, required}; use crate::catalog::{Catalog, Song}; +use crate::source::{self, Lease, OpenError, Readable}; use crate::types::{Body, HttpResponse, Shared, SubsonicRequest, full}; use bytes::Bytes; use futures_util::{Stream, StreamExt, TryStreamExt}; @@ -22,7 +23,7 @@ use std::process::Stdio; use std::sync::Mutex; use std::task::{Context, Poll}; use std::time::Duration; -use tokio::io::{AsyncRead, AsyncReadExt, AsyncSeekExt}; +use tokio::io::{AsyncRead, AsyncReadExt, AsyncSeekExt, ReadBuf}; use tokio::process::{Child, ChildStdout, Command}; use tokio_util::io::ReaderStream; @@ -48,12 +49,15 @@ pub(super) async fn stream( number::(request, "maxBitRate"), number::(request, "timeOffset"), ); + // ffmpeg opens the path itself, which it cannot do for a lent file. if let (Some(plan), Some(ffmpeg)) = (plan, &shared.config.ffmpeg_path) + && !source::needs_app(&song.path) && let Some(response) = transcode(ffmpeg, &song.path, &plan).await { return Ok(response); } file_response( + shared, &song.path, content_type(&song.suffix), &request.headers, @@ -63,17 +67,15 @@ pub(super) async fn stream( } pub(super) async fn download( + shared: &Shared, catalog: &Catalog, request: &SubsonicRequest, ) -> Result { let song = song(catalog, request)?; - let name = song - .path - .file_name() - .map(|name| name.to_string_lossy().into_owned()) - .unwrap_or_else(|| format!("{}.{}", song.title, song.suffix)); + let name = source::file_name(&song.path, &song.title, &song.suffix); let disposition = format!("attachment; filename*=UTF-8''{}", percent_encode(&name)); file_response( + shared, &song.path, content_type(&song.suffix), &request.headers, @@ -89,20 +91,29 @@ fn song<'a>(catalog: &'a Catalog, request: &SubsonicRequest) -> Result<&'a Song, .ok_or_else(|| Failure::not_found("Song").with_status(404)) } -/// Serves `path` with `Range` support. A missing file answers error 70 with -/// HTTP 404. +/// Serves `path` ([`source::open`]) with `Range` support; a lent file's lease +/// lasts as long as the body. A missing file answers error 70 with HTTP 404, +/// one the app could not lend in time HTTP 503. pub(super) async fn file_response( + shared: &Shared, path: &Path, content_type: &str, headers: &HeaderMap, extra: Vec<(HeaderName, String)>, ) -> Result { let missing = || Failure::not_found("File").with_status(404); - let mut file = tokio::fs::File::open(path).await.map_err(|_| missing())?; - let metadata = file.metadata().await.map_err(|_| missing())?; - if !metadata.is_file() { - return Err(missing()); - } + let Readable { + mut file, + metadata, + lease, + } = source::open(shared, path) + .await + .map_err(|error| match error { + OpenError::Missing => missing(), + OpenError::Busy => { + Failure::new(super::code::GENERIC, "Too many files are open").with_status(503) + } + })?; let len = metadata.len(); let range = headers .get(RANGE) @@ -118,7 +129,7 @@ pub(super) async fn file_response( ByteRange::Full => builder .status(200) .header(CONTENT_LENGTH, len) - .body(reader_body(file)), + .body(reader_body(file, lease)), ByteRange::Partial(start, end) => { file.seek(SeekFrom::Start(start)) .await @@ -127,7 +138,7 @@ pub(super) async fn file_response( .status(206) .header(CONTENT_LENGTH, end - start + 1) .header(CONTENT_RANGE, format!("bytes {start}-{end}/{len}")) - .body(reader_body(file.take(end - start + 1))) + .body(reader_body(file.take(end - start + 1), lease)) } ByteRange::Unsatisfiable => builder .status(416) @@ -137,12 +148,37 @@ pub(super) async fn file_response( response.map_err(|error| Failure::new(super::code::GENERIC, error.to_string())) } -fn reader_body(reader: impl AsyncRead + Send + Sync + 'static) -> Body { +fn reader_body( + reader: impl AsyncRead + Unpin + Send + Sync + 'static, + lease: Option, +) -> Body { + let reader = Leased { + reader, + _lease: lease, + }; BodyExt::boxed(StreamBody::new( ReaderStream::with_capacity(reader, CHUNK).map_ok(Frame::data), )) } +/// A body's reader and the lease keeping its file readable. The stream drops +/// it at the end or after an error, and hyper drops the stream when the +/// client goes away, so the lease ends with the response either way. +struct Leased { + reader: R, + _lease: Option, +} + +impl AsyncRead for Leased { + fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, + ) -> Poll> { + Pin::new(&mut self.get_mut().reader).poll_read(cx, buf) + } +} + /// The answer to a `Range` header for a `len`-byte file. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(super) enum ByteRange { diff --git a/rust_backend/crates/link/src/subsonic/objects.rs b/rust_backend/crates/link/src/subsonic/objects.rs index 73c48902b..943a3c064 100644 --- a/rust_backend/crates/link/src/subsonic/objects.rs +++ b/rust_backend/crates/link/src/subsonic/objects.rs @@ -172,11 +172,7 @@ fn album_created(catalog: &Catalog, index: usize) -> String { fn display_path(catalog: &Catalog, index: usize) -> String { let song = &catalog.songs()[index]; let album = &catalog.albums()[song.album]; - let file = song - .path - .file_name() - .map(|name| name.to_string_lossy().into_owned()) - .unwrap_or_else(|| format!("{}.{}", song.title, song.suffix)); + let file = crate::source::file_name(&song.path, &song.title, &song.suffix); format!( "{}/{}/{}", path_part(&album.artist_name), diff --git a/rust_backend/crates/link/src/subsonic/tests.rs b/rust_backend/crates/link/src/subsonic/tests.rs index fe7122d89..7699bb38a 100644 --- a/rust_backend/crates/link/src/subsonic/tests.rs +++ b/rust_backend/crates/link/src/subsonic/tests.rs @@ -5,6 +5,7 @@ mod browse; mod compat; mod covers; mod forward; +mod lent; mod lyrics; mod media; mod web_covers; @@ -26,11 +27,12 @@ pub(super) const DEVICE_ID: &str = "device-1"; pub(super) const APP_VERSION: &str = "9.9.9-test"; /// Records forwarded requests and answers with canned replies (`{}` when -/// none is set for an op). +/// none is set for an op); a held op never answers. #[derive(Default)] pub(super) struct FakeHost { requests: Mutex>, replies: Mutex>>, + held: Mutex>, } impl FakeHost { @@ -41,6 +43,11 @@ impl FakeHost { .insert(op.to_owned(), reply); } + /// Leaves every request for `op` unanswered. + pub(super) fn hold(&self, op: &str) { + self.held.lock().expect("held").push(op.to_owned()); + } + pub(super) fn requests(&self) -> Vec<(String, String, Value)> { self.requests.lock().expect("requests").clone() } @@ -66,6 +73,15 @@ impl Host for FakeHost { .lock() .expect("requests") .push((op.to_owned(), device_id.to_owned(), args)); + if self + .held + .lock() + .expect("held") + .iter() + .any(|held| held == op) + { + return Box::pin(std::future::pending()); + } let reply = self .replies .lock() @@ -129,6 +145,7 @@ impl Fixture { server_id: "server-1".to_owned(), host: Arc::clone(&host) as Arc, catalog: RwLock::new(Arc::new(catalog)), + leases: Default::default(), }; Self { _dir: dir, diff --git a/rust_backend/crates/link/src/subsonic/tests/covers.rs b/rust_backend/crates/link/src/subsonic/tests/covers.rs index a01653699..135a95907 100644 --- a/rust_backend/crates/link/src/subsonic/tests/covers.rs +++ b/rust_backend/crates/link/src/subsonic/tests/covers.rs @@ -178,7 +178,7 @@ async fn undecodable_covers_are_served_as_they_are() { /// A minimal FLAC file: STREAMINFO, then `block` as the last metadata block /// of type `kind`, then a frame sync code. -fn flac(kind: u8, block: &[u8]) -> Vec { +pub(super) fn flac(kind: u8, block: &[u8]) -> Vec { let mut bytes = b"fLaC".to_vec(); bytes.extend_from_slice(&[0, 0, 0, 34]); bytes.extend_from_slice(&[0; 34]); diff --git a/rust_backend/crates/link/src/subsonic/tests/lent.rs b/rust_backend/crates/link/src/subsonic/tests/lent.rs new file mode 100644 index 000000000..49940fbf9 --- /dev/null +++ b/rust_backend/crates/link/src/subsonic/tests/lent.rs @@ -0,0 +1,302 @@ +//! Songs only the app can open: the server borrows each file through +//! `server/files/open` and returns it through `server/files/close` once the +//! response is done with it, however the response ends. The test's open file +//! stands in for the descriptor the app holds. +#![cfg(unix)] + +use super::covers::{flac, flac_pair}; +use super::*; +use crate::source::{CLOSE_OP, Leases, OPEN_OP}; +use std::os::fd::AsRawFd; +use std::time::Duration; + +const URI: &str = + "content://com.example.documents/tree/a%3AMusic/document/a%3AMusic%2FBand%2FSong.flac"; + +/// A catalog whose one song `s` at `uri` the app lends from `bytes`. +fn lent_at(uri: &str, bytes: &[u8]) -> (Fixture, std::fs::File) { + let mut held = None; + let fixture = Fixture::new(|dir| { + let path = write_file(dir, "lent.flac", bytes); + held = Some(std::fs::File::open(path).expect("open")); + vec![json!({ + "id": "s", "title": "Song", "artist": "Band", "album": "Album", + "path": uri, "suffix": "flac", + })] + }); + let held = held.expect("held file"); + fixture.host.reply( + OPEN_OP, + Ok(json!({ "path": format!("/dev/fd/{}", held.as_raw_fd()) })), + ); + (fixture, held) +} + +fn lent(bytes: &[u8]) -> (Fixture, std::fs::File) { + lent_at(URI, bytes) +} + +fn audio(len: usize) -> Vec { + (0..len).map(|index| (index % 251) as u8).collect() +} + +/// The ops forwarded so far, each asserted to come from the server itself. +fn ops(fixture: &Fixture) -> Vec { + fixture + .host + .requests() + .into_iter() + .map(|(op, device, _)| { + assert_eq!(device, "", "{op} is the server's own request"); + op + }) + .collect() +} + +/// Asserts each open was followed by the close of the same lease. +fn returned(fixture: &Fixture, borrows: usize) { + let requests = fixture.host.requests(); + assert_eq!(requests.len(), borrows * 2, "{requests:?}"); + for pair in requests.chunks(2) { + assert_eq!(pair[0].0, OPEN_OP); + assert_eq!(pair[0].2["uri"], URI); + assert_eq!(pair[1].0, CLOSE_OP); + let lease = pair[0].2["lease"].as_str().expect("lease"); + assert!(!lease.is_empty()); + assert_eq!(pair[1].2["lease"], lease); + } +} + +#[tokio::test] +async fn a_lent_song_streams_whole_and_returns_its_lease() { + let bytes = audio(200_000); + let (fixture, _held) = lent(&bytes); + let reply = fixture + .raw("stream", &[("id", "s")], HeaderMap::new()) + .await; + assert_eq!(reply.status, 200); + assert_eq!(reply.header("content-type"), Some("audio/flac")); + assert_eq!(reply.header("content-length"), Some("200000")); + assert_eq!(reply.header("accept-ranges"), Some("bytes")); + assert_eq!(reply.body.as_ref(), bytes.as_slice()); + returned(&fixture, 1); +} + +#[tokio::test] +async fn ranges_seek_in_a_lent_song_and_each_response_borrows_its_own() { + let bytes = audio(200_000); + let (fixture, _held) = lent(&bytes); + for (range, start, end) in [ + ("bytes=150000-150099", 150_000, 150_099), + ("bytes=10-19", 10, 19), + ] { + let reply = fixture + .raw("stream", &[("id", "s")], headers(&[("range", range)])) + .await; + assert_eq!(reply.status, 206, "{range}"); + assert_eq!( + reply.header("content-range").map(str::to_owned), + Some(format!("bytes {start}-{end}/200000")) + ); + assert_eq!(reply.body.as_ref(), &bytes[start..=end]); + } + let whole = fixture + .raw("stream", &[("id", "s")], HeaderMap::new()) + .await; + assert_eq!(whole.body.as_ref(), bytes.as_slice(), "starts at the top"); + returned(&fixture, 3); +} + +#[tokio::test] +async fn a_response_dropped_midway_returns_its_lease() { + let (fixture, _held) = lent(&audio(1 << 20)); + let response = fixture + .response("stream", &[("id", "s")], HeaderMap::new()) + .await; + assert_eq!(response.status(), 200); + let mut body = response.into_body(); + let frame = body.frame().await.expect("a frame").expect("data"); + assert!(frame.data_ref().is_some_and(|data| !data.is_empty())); + assert_eq!(ops(&fixture), [OPEN_OP], "held while the client reads"); + drop(body); + returned(&fixture, 1); +} + +#[tokio::test] +async fn an_unsatisfiable_range_returns_its_lease() { + let (fixture, _held) = lent(&audio(100)); + let reply = fixture + .raw( + "stream", + &[("id", "s")], + headers(&[("range", "bytes=500-")]), + ) + .await; + assert_eq!(reply.status, 416); + returned(&fixture, 1); +} + +#[tokio::test] +async fn a_file_the_app_cannot_lend_answers_404_and_is_still_closed() { + let (fixture, _held) = lent(&audio(100)); + fixture + .host + .reply(OPEN_OP, Err(HostError::new("not_found", "Gone"))); + assert_eq!( + fixture + .raw("stream", &[("id", "s")], HeaderMap::new()) + .await + .status, + 404 + ); + // A lent path that is not a regular file. + let folder = fixture + .shared + .config + .temp_dir + .to_string_lossy() + .into_owned(); + fixture.host.reply(OPEN_OP, Ok(json!({ "path": folder }))); + assert_eq!( + fixture + .raw("download", &[("id", "s")], HeaderMap::new()) + .await + .status, + 404 + ); + fixture.host.reply(OPEN_OP, Ok(json!({}))); + assert_eq!( + fixture + .raw("stream", &[("id", "s")], HeaderMap::new()) + .await + .status, + 404 + ); + returned(&fixture, 3); +} + +#[tokio::test] +async fn an_open_abandoned_while_waiting_for_the_app_is_closed() { + let (fixture, _held) = lent(&audio(100)); + fixture.host.hold(OPEN_OP); + let waited = tokio::time::timeout( + Duration::from_millis(50), + fixture.response("stream", &[("id", "s")], HeaderMap::new()), + ) + .await; + assert!(waited.is_err(), "the app never answered"); + returned(&fixture, 1); +} + +#[tokio::test] +async fn lent_files_are_bounded_and_a_returned_one_frees_its_place() { + let bytes = audio(1 << 20); + let (mut fixture, _held) = lent(&bytes); + fixture.shared.leases = Leases::new(1, Duration::from_millis(50)); + let first = fixture + .response("stream", &[("id", "s")], HeaderMap::new()) + .await; + assert_eq!(first.status(), 200); + let busy = fixture + .raw("stream", &[("id", "s")], HeaderMap::new()) + .await; + assert_eq!(busy.status, 503); + assert_eq!( + ops(&fixture), + [OPEN_OP], + "a busy request never asks the app" + ); + drop(first); + let next = fixture + .raw("stream", &[("id", "s")], HeaderMap::new()) + .await; + assert_eq!(next.status, 200); + assert_eq!(next.body.as_ref(), bytes.as_slice()); + returned(&fixture, 2); +} + +#[tokio::test] +async fn a_lent_song_downloads_under_its_document_name() { + let bytes = audio(1000); + let (fixture, _held) = lent(&bytes); + let song = fixture.ok("getSong", &[("id", "s")], "song").await; + assert_eq!(song["path"], "Band/Album/Song.flac"); + assert!(ops(&fixture).is_empty(), "browsing opens nothing"); + let reply = fixture + .raw("download", &[("id", "s")], HeaderMap::new()) + .await; + assert_eq!(reply.status, 200); + assert_eq!( + reply.header("content-disposition"), + Some("attachment; filename*=UTF-8''Song.flac") + ); + assert_eq!(reply.body.as_ref(), bytes.as_slice()); + returned(&fixture, 1); +} + +#[tokio::test] +async fn a_picture_embedded_in_a_lent_song_is_its_cover() { + let image = png(12, 6); + let (with, _) = flac_pair(&image); + let uri = "content://com.example.documents/document/a%3ACovered.flac"; + let (fixture, _held) = lent_at(uri, &with); + for _ in 0..2 { + let reply = fixture + .raw("getCoverArt", &[("id", "s")], HeaderMap::new()) + .await; + assert_eq!(reply.status, 200); + assert_eq!(reply.header("content-type"), Some("image/png")); + assert_eq!(reply.body.as_ref(), image.as_slice()); + } + // The second is served from the cache, but its version comes from the + // lent file, which is borrowed again and returned. + let requests = fixture.host.requests(); + let ops: Vec<&str> = requests.iter().map(|(op, _, _)| op.as_str()).collect(); + assert_eq!(ops, [OPEN_OP, CLOSE_OP, OPEN_OP, CLOSE_OP]); + assert_eq!(requests[0].2["uri"], uri); +} + +/// A FLAC VORBIS_COMMENT block with `entries`. +fn vorbis_comment(entries: &[&str]) -> Vec { + let length = |len: usize| u32::try_from(len).expect("length").to_le_bytes(); + let mut block = length(4).to_vec(); + block.extend_from_slice(b"test"); + block.extend_from_slice(&length(entries.len())); + for entry in entries { + block.extend_from_slice(&length(entry.len())); + block.extend_from_slice(entry.as_bytes()); + } + block +} + +#[tokio::test] +async fn lyrics_embedded_in_a_lent_song_are_read() { + let song = flac( + 4, + &vorbis_comment(&["LYRICS=[00:01.00]Hello\n[00:02.00]World"]), + ); + let (fixture, _held) = lent(&song); + let list = fixture + .ok("getLyricsBySongId", &[("id", "s")], "lyricsList") + .await; + assert_eq!( + list["structuredLyrics"][0]["line"], + json!([ + { "start": 1000, "value": "Hello" }, + { "start": 2000, "value": "World" }, + ]), + "{list}" + ); + returned(&fixture, 1); +} + +#[tokio::test] +async fn a_plain_path_never_asks_the_app() { + let fixture = library(); + for method in ["stream", "download", "getCoverArt", "getLyricsBySongId"] { + fixture + .raw(method, &[("id", "l:2")], HeaderMap::new()) + .await; + } + assert!(fixture.host.requests().is_empty()); +} diff --git a/rust_backend/crates/link/src/types.rs b/rust_backend/crates/link/src/types.rs index 56c7f2ef2..23a4e807a 100644 --- a/rust_backend/crates/link/src/types.rs +++ b/rust_backend/crates/link/src/types.rs @@ -130,6 +130,8 @@ pub struct Shared { pub host: Arc, /// Replaced as a whole by `linkSetCatalog`. pub catalog: RwLock>, + /// The files the app lends for songs only it can open. + pub(crate) leases: crate::source::Leases, } impl Shared { diff --git a/rust_backend/crates/link/src/ws/tests.rs b/rust_backend/crates/link/src/ws/tests.rs index 4c24bcafb..57b6a1aee 100644 --- a/rust_backend/crates/link/src/ws/tests.rs +++ b/rust_backend/crates/link/src/ws/tests.rs @@ -55,6 +55,7 @@ impl Fixture { server_id: store.server_id(), host: Arc::new(NoopHost), catalog: RwLock::new(Arc::new(Catalog::empty())), + leases: Default::default(), }), store, pairing: Pairing::new(tuning.pairing_ttl, tuning.pair_interval), diff --git a/rust_backend/crates/link/tests/server.rs b/rust_backend/crates/link/tests/server.rs index f407dae08..9dfc545fa 100644 --- a/rust_backend/crates/link/tests/server.rs +++ b/rust_backend/crates/link/tests/server.rs @@ -34,12 +34,15 @@ type Socket = WebSocketStream>; const WAIT: Duration = Duration::from_secs(5); /// Records events and answers requests by `op`: `slow` never answers, -/// `missing` and `broken` fail, anything else echoes its arguments. +/// `missing` and `broken` fail, `server/files/open` lends `lent`, anything +/// else echoes its arguments. #[derive(Default)] struct FakeHost { events: Mutex>, requests: Mutex>, + lent: Mutex, changed: Condvar, + requested: Condvar, } impl Host for FakeHost { @@ -53,10 +56,12 @@ impl Host for FakeHost { .lock() .unwrap() .push((op.to_owned(), device_id.to_owned(), args.clone())); + self.requested.notify_all(); let reply = match op { "slow" => None, "missing" => Some(Err(HostError::new("not_found", "No such item"))), "broken" => Some(Err(HostError::new("weird", "Something broke"))), + "server/files/open" => Some(Ok(json!({"path": *self.lent.lock().unwrap()}))), _ => Some(Ok(json!({"op": op, "args": args}))), }; Box::pin(async move { @@ -74,6 +79,35 @@ impl Host for FakeHost { } impl FakeHost { + /// The arguments of the requests for `op` so far. + fn requests_for(&self, op: &str) -> Vec { + self.requests + .lock() + .unwrap() + .iter() + .filter(|(name, _, _)| name == op) + .map(|(_, _, args)| args.clone()) + .collect() + } + + /// Waits for the first request for `op`. + fn wait_request(&self, op: &str) -> Value { + let deadline = Instant::now() + WAIT; + let mut requests = self.requests.lock().unwrap(); + loop { + if let Some((_, _, args)) = requests.iter().find(|(name, _, _)| name == op) { + return args.clone(); + } + let now = Instant::now(); + assert!(now < deadline, "no {op} request: {requests:?}"); + requests = self + .requested + .wait_timeout(requests, deadline - now) + .unwrap() + .0; + } + } + fn events(&self, method: &str) -> Vec { self.events .lock() @@ -835,6 +869,96 @@ fn phones_upload_song_files_into_the_received_folder() { assert!(fixture.host.requests.lock().unwrap().is_empty()); } +#[test] +fn phones_cannot_send_the_servers_own_requests() { + let fixture = Fixture::new(); + let key = fixture.pair("phone-1"); + for path in [ + "/mornye/v1/server", + "/mornye/v1/server/files/open", + "/mornye/v1/server/files/close", + ] { + let response = fixture.post_json( + path, + Some(&key), + &json!({"uri": "content://com.example.documents/document/1", "lease": "1"}), + ); + assert_eq!(response.status, 404, "{path}"); + } + assert!(fixture.host.requests.lock().unwrap().is_empty()); +} + +#[cfg(unix)] +#[test] +fn a_dropped_connection_returns_the_file_the_app_lent() { + use std::os::fd::AsRawFd; + let fixture = Fixture::new(); + // Larger than the socket buffers, so the server is still sending. + let audio = fixture.dir.path().join("lent.flac"); + std::fs::write(&audio, vec![5u8; 16 << 20]).unwrap(); + let held = std::fs::File::open(&audio).unwrap(); + *fixture.host.lent.lock().unwrap() = format!("/dev/fd/{}", held.as_raw_fd()); + let catalog = fixture.dir.path().join("catalog.ndjson"); + let song = json!({ + "id": "s", "title": "Song", "artist": "Band", "suffix": "flac", + "path": "content://com.example.documents/document/a%3ASong.flac", + }); + std::fs::write( + &catalog, + format!("{}\n{song}\n", json!({"catalogVersion": 1, "count": 1})), + ) + .unwrap(); + fixture.server().set_catalog(&catalog).unwrap(); + let (_, key) = fixture.subsonic_key(); + let port = fixture.server().port(); + let fingerprint = fixture.server().fingerprint().to_owned(); + let host = Arc::clone(&fixture.host); + fixture.run(async move { + let tls = connect(port, &fingerprint).await; + let (mut sender, connection) = hyper::client::conn::http1::handshake(TokioIo::new(tls)) + .await + .unwrap(); + let connection = tokio::spawn(connection); + let request = http::Request::builder() + .uri(format!("/rest/stream?id=s&apiKey={key}")) + .header("host", "mornye.local") + .body(Full::new(Bytes::new())) + .unwrap(); + let response = sender.send_request(request).await.unwrap(); + assert_eq!(response.status(), 200); + let mut body = response.into_body(); + let frame = body.frame().await.unwrap().unwrap(); + assert!(frame.data_ref().is_some_and(|data| !data.is_empty())); + tokio::time::sleep(Duration::from_millis(100)).await; + assert!( + host.requests_for("server/files/close").is_empty(), + "the lease lasts while the song is sent" + ); + // The phone goes away mid-song. + drop(body); + drop(sender); + connection.abort(); + let _ = connection.await; + }); + let closed = fixture.host.wait_request("server/files/close"); + let opened = fixture.host.requests_for("server/files/open"); + assert_eq!(opened.len(), 1); + assert_eq!( + opened[0]["uri"], + "content://com.example.documents/document/a%3ASong.flac" + ); + assert_eq!(closed["lease"], opened[0]["lease"]); + let devices: Vec = fixture + .host + .requests + .lock() + .unwrap() + .iter() + .map(|(_, device, _)| device.clone()) + .collect(); + assert!(devices.iter().all(String::is_empty), "{devices:?}"); +} + #[test] fn subsonic_requests_authenticate_before_the_subsonic_layer() { let fixture = Fixture::new();