Terminal interface to find, download, and stream movies, TV shows, and live TV using local media players.
fix(core): harden proxy lifecycle, playback progress, and resource bounds
Samir Hossains6107d5a589c8
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a5dad7d..82f864b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,22 @@- Updated player resolution in `src/player.rs` to fall back to persisted configuration files (`config.json`) when custom player paths are not passed via environment variables (`MOVIEBOX_VLC_PATH`, `MOVIEBOX_MPV_PATH`, `MOVIEBOX_IINA_PATH`), allowing users to configure non-standard or portable player executables (e.g. `D:\PortableApps\VLC\vlc.exe`).- Added `clear_cached_player_executables` in `src/player.rs` to safely invalidate in-memory static player path caches when player configurations update.### Fixed+- **Proxy Sidecar Child Process Lifecycle & Zombie Prevention**:+ - Detached proxy sidecar `Child` handle via `std::mem::forget` upon successful loopback port acquisition in `src/proxy.rs`, preventing defunct zombie process leaks on Linux and Unix environments when sidecars exit cleanly.+- **Proxy HTTP Status Line Timing on Oversized Manifests**:+ - Deferred emitting the HTTP status line in `src/proxy.rs` until DASH manifest sizing is verified, returning `HTTP/1.1 502 Bad Gateway` on oversized manifests instead of a malformed `200 OK` error payload.+- **VLC Player Clean Exit Progress Tracking**:+ - Recorded elapsed watch progress for VLC when it exits with status code 1 and clean stderr in `src/tui/app/playback.rs`, ensuring normal VLC exits update watch history and continue watching rows identically to code 0 exits.+- **External Caption Sibling Query Isolation & Timeouts**:+ - Bound parallel sibling provider queries in `get_ext_captions` (`src/service.rs`) with individual 8-second `tokio::time::timeout` futures, preventing single uncommunicative sibling mirrors from delaying caption availability.+- **Overview Modal Persistence Across Screen Transitions**:+ - Reset `show_overview_modal` and `overview_modal_scroll` flags within `reset_transient_overlays` (`src/tui/app/tv.rs`), preventing overview backdrops from lingering across mode changes.+- **Details Pane Season & Episode Mouse Hitbox Scrolling Offsets**:+ - Factored `ListState::offset()` into row hitbox calculations in `src/tui/app/mouse.rs`, ensuring mouse clicks accurately select the intended season or episode row in scrolled lists.+- **Dynamic Application User-Agent Header**:+ - Configured `APP_HTTP_USER_AGENT` in `src/net.rs` to compile-time reference `CARGO_PKG_VERSION` dynamically rather than hardcoding a static version string.+- **Poster Fetch Memory Size Ceiling**:+ - Added a 5 MiB ceiling to `fetch_poster_bytes` in `src/service.rs` validating `Content-Length` and buffer length to protect against unbounded image memory consumption.- **Streams Table Column Alignment Under Modal Backdrops**:- Unified `pane_styles` highlight symbol to `""` during modal active states in `src/tui/screens/details.rs`, preventing Ratatui `Table` from reserving a 2-character highlight prefix column that shifted table headers and columns to the right whenever a popup (subtitles, player picker, help) opened.- **In-App Updater Streaming Timeout & Chunk Retry Recovery**:diff --git a/src/config.rs b/src/config.rsindex 955c915..da95026 100644--- a/src/config.rs+++ b/src/config.rs@@ -188,7 +188,13 @@ pub fn load() -> Config {};if path.exists() {if let Ok(content) = std::fs::read_to_string(&path) {- let mut val: serde_json::Value = serde_json::from_str(&content).unwrap_or_default();+ let mut val: serde_json::Value = match serde_json::from_str(&content) {+ Ok(v) => v,+ Err(e) => {+ log::warn!("config invalid JSON: {e}; resetting");+ serde_json::Value::default()+ }+ };let old_bdix = val.get("bdix_enabled").and_then(|v| v.as_bool())diff --git a/src/net.rs b/src/net.rsindex 50c24a7..2100e0a 100644--- a/src/net.rs+++ b/src/net.rs@@ -10,7 +10,7 @@ use reqwest::dns::{Addrs, Name, Resolve, Resolving};const FALLBACK_DNS_PORT: u16 = 53;pub const DEFAULT_BROWSER_USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";-pub const APP_HTTP_USER_AGENT: &str = "MovieBox-Tui/1.0";+pub const APP_HTTP_USER_AGENT: &str = concat!("MovieBox-Tui/", env!("CARGO_PKG_VERSION"));static GLOBAL_RESOLVER: std::sync::LazyLock<Arc<TokioResolver>> =std::sync::LazyLock::new(|| Arc::new(build_resolver()));diff --git a/src/proxy.rs b/src/proxy.rsindex d7d7d9c..ee1a52a 100644--- a/src/proxy.rs+++ b/src/proxy.rs@@ -93,6 +93,7 @@ pub fn spawn_sidecar(let _ = child.wait();format!("proxy sidecar returned unexpected output: {line:?}")})?;+ std::mem::forget(child);let proxy_path = if let Some(rest) = target_url.strip_prefix("https://") {format!("/https/{rest}")@@ -311,12 +312,6 @@ async fn handle_connection(};let status = upstream_res.status();- let status_line = format!(- "HTTP/1.1 {} {}\r\n",- status.as_u16(),- status.canonical_reason().unwrap_or("OK")- );- writer.write_all(status_line.as_bytes()).await?;let content_length = upstream_res.headers()@@ -341,7 +336,7 @@ async fn handle_connection(writer.write_all(format!(- "Content-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",+ "HTTP/1.1 502 Bad Gateway\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",body.len()).as_bytes(),@@ -354,7 +349,7 @@ async fn handle_connection(let rewritten_bytes = rewritten.as_bytes();let headers_out = format!(- "Content-Type: application/dash+xml\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",+ "HTTP/1.1 200 OK\r\nContent-Type: application/dash+xml\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",rewritten_bytes.len());writer.write_all(headers_out.as_bytes()).await?;@@ -363,6 +358,13 @@ async fn handle_connection(return Ok(());}+ let status_line = format!(+ "HTTP/1.1 {} {}\r\n",+ status.as_u16(),+ status.canonical_reason().unwrap_or("OK")+ );+ writer.write_all(status_line.as_bytes()).await?;+let headers_bytes = format_proxy_response_headers(upstream_res.headers(), &target_url);writer.write_all(&headers_bytes).await?;diff --git a/src/service.rs b/src/service.rsindex b4e3a53..e3e8615 100644--- a/src/service.rs+++ b/src/service.rs@@ -216,32 +216,36 @@ impl MovieBoxService {if !sib.is_empty() && sib != subject_id {let client = &self.client;sibling_futs.push(async move {- let page = if episode > 0 { (episode - 1) / 20 + 1 } else { 1 };- if let Ok((items, _)) = client.fetch_resource_page(sib, season, episode, 0, page).await {- let matched_item = find_matching_resource_item(&items, season, episode);- if let Some(item) = matched_item {- let item_rid = item- .get("resourceId")- .or_else(|| item.get("id"))- .and_then(|v| {- if let Some(n) = v.as_i64() {- Some(n.to_string())- } else if let Some(n) = v.as_u64() {- Some(n.to_string())- } else {- v.as_str().map(|s| s.to_string())+ tokio::time::timeout(std::time::Duration::from_secs(8), async move {+ let page = if episode > 0 { (episode - 1) / 20 + 1 } else { 1 };+ if let Ok((items, _)) = client.fetch_resource_page(sib, season, episode, 0, page).await {+ let matched_item = find_matching_resource_item(&items, season, episode);+ if let Some(item) = matched_item {+ let item_rid = item+ .get("resourceId")+ .or_else(|| item.get("id"))+ .and_then(|v| {+ if let Some(n) = v.as_i64() {+ Some(n.to_string())+ } else if let Some(n) = v.as_u64() {+ Some(n.to_string())+ } else {+ v.as_str().map(|s| s.to_string())+ }+ });+ if let Some(rid) = item_rid {+ if let Ok(res_payload) = client.get_ext_captions(sib, &rid).await {+ return crate::providers::moviebox::adapt::captions_json_to_options(+ &res_payload,+ );}- });- if let Some(rid) = item_rid {- if let Ok(res_payload) = client.get_ext_captions(sib, &rid).await {- return crate::providers::moviebox::adapt::captions_json_to_options(- &res_payload,- );}}}- }- Vec::new()+ Vec::new()+ })+ .await+ .unwrap_or_default()});}}@@ -289,6 +293,7 @@ impl MovieBoxService {}}pub async fn fetch_poster_bytes(&self, url: &str) -> Option<Vec<u8>> {+ const MAX_POSTER_BYTES: u64 = 5 * 1024 * 1024;let response = self.http_client.get(url)@@ -298,7 +303,22 @@ impl MovieBoxService {.ok()?.error_for_status().ok()?;- Some(response.bytes().await.ok()?.to_vec())+ if response+ .content_length()+ .is_some_and(|len| len > MAX_POSTER_BYTES)+ {+ log::warn!(+ "poster at {} exceeds size limit ({} bytes), skipping",+ crate::logging::sanitize_url(url),+ response.content_length().unwrap_or(0)+ );+ return None;+ }+ let bytes = response.bytes().await.ok()?;+ if bytes.len() as u64 > MAX_POSTER_BYTES {+ return None;+ }+ Some(bytes.to_vec())}pub async fn download_subtitle_file(diff --git a/src/tui/app/mouse.rs b/src/tui/app/mouse.rsindex d29075a..7f09081 100644--- a/src/tui/app/mouse.rs+++ b/src/tui/app/mouse.rs@@ -1131,12 +1131,14 @@ impl App {}DetailsPane::Seasons => {self.state.details_pane = DetailsPane::Seasons;- if clicked_row < self.state.available_seasons.len() {- self.state.season_list_state.select(Some(clicked_row));+ let offset = self.state.season_list_state.offset();+ let abs_row = offset + clicked_row;+ if abs_row < self.state.available_seasons.len() {+ self.state.season_list_state.select(Some(abs_row));self.state.selected_season = self.state.available_seasons- .get(clicked_row)+ .get(abs_row).map(|s| s.number).unwrap_or(1);self.state.episode_list_state.select(Some(0));@@ -1145,13 +1147,15 @@ impl App {}DetailsPane::Episodes => {self.state.details_pane = DetailsPane::Episodes;+ let offset = self.state.episode_list_state.offset();+ let abs_row = offset + clicked_row;let season_idx = self.state.season_list_state.selected().unwrap_or(0);if let Some(ep_numbers) =self.state.available_episode_numbers.get(season_idx){- if clicked_row < ep_numbers.len() {- self.state.episode_list_state.select(Some(clicked_row));- self.state.selected_episode = ep_numbers[clicked_row];+ if abs_row < ep_numbers.len() {+ self.state.episode_list_state.select(Some(abs_row));+ self.state.selected_episode = ep_numbers[abs_row];self.trigger_episode_fetch();}}diff --git a/src/tui/app/playback.rs b/src/tui/app/playback.rsindex b923f42..e5841fc 100644--- a/src/tui/app/playback.rs+++ b/src/tui/app/playback.rs@@ -578,6 +578,30 @@ impl App {kind,status.code());+ if let Some(item) = history_item {+ let elapsed = start_time.elapsed().as_secs();+ if elapsed >= 30 {+ let duration = item.duration_seconds;+ let start_pos = resume_seconds.unwrap_or(0);+ let total_pos = start_pos.saturating_add(elapsed);+ let progress = if let Some(d) = duration {+ total_pos.min(d)+ } else {+ total_pos+ };+ let completed = duration.is_some_and(|d| {+ d > 0 && progress >= (d as f64 * 0.90) as u64+ });+ sender+ .send(Action::UpdateProgress {+ item: Box::new(item),+ progress,+ duration,+ completed,+ })+ .ok();+ }+ }}Ok(status) => {let is_termux_socket_err = is_androiddiff --git a/src/tui/app/tv.rs b/src/tui/app/tv.rsindex 1fec79b..818571a 100644--- a/src/tui/app/tv.rs+++ b/src/tui/app/tv.rs@@ -24,6 +24,8 @@ impl App {self.state.tv_input_active = false;self.state.tv_input_buffer.clear();self.state.tv_input_is_file = false;+ self.state.show_overview_modal = false;+ self.state.overview_modal_scroll = 0;}pub(super) fn reset_mode_state(&mut self) {