From fe012decc015ed5ce0c3a2185b350cb397b51226 Mon Sep 17 00:00:00 2001 From: astar76 Date: Wed, 25 Nov 2026 21:54:37 -0600 Subject: [PATCH 01/61] S023: browser port on loopback with Host, Origin, type and preflight guards, link checks, sender log Co-Authored-By: Claude Opus 5.5 --- Plans/05 Connector/S023-port-server.md | 18 +- Plans/INDEX.md | 2 +- crates/core/lang/en.json | 17 ++ crates/core/src/connector/link.rs | 209 +++++++++++++ crates/core/src/connector/mod.rs | 398 +++++++++++++++++++++++++ crates/core/src/connector/peer.rs | 44 +++ crates/core/src/connector/wire.rs | 135 +++++++++ crates/core/src/lib.rs | 1 + crates/core/tests/connector_nacre.json | 1 + docs/CONNECTOR.md | 63 ++++ docs/PROGRESS.md | 5 + docs/tests/S023-port-server.md | 45 +++ 12 files changed, 928 insertions(+), 10 deletions(-) create mode 100644 crates/core/src/connector/link.rs create mode 100644 crates/core/src/connector/mod.rs create mode 100644 crates/core/src/connector/peer.rs create mode 100644 crates/core/src/connector/wire.rs create mode 100644 crates/core/tests/connector_nacre.json create mode 100644 docs/CONNECTOR.md create mode 100644 docs/tests/S023-port-server.md diff --git a/Plans/05 Connector/S023-port-server.md b/Plans/05 Connector/S023-port-server.md index ad2a8f4..042afcc 100644 --- a/Plans/05 Connector/S023-port-server.md +++ b/Plans/05 Connector/S023-port-server.md @@ -12,15 +12,15 @@ A browser hands links to 127.0.0.1:17616; nothing else can abuse it. FEATURES 4. - CLAUDE.md §4 ## Steps -- [ ] Server on loopback only, changeable port, on and off live, port-in-use state that names the fix -- [ ] `GET /` ping with name and version; `POST /` with one link or a list, unknown fields ignored, size and rate limits, answers 2xx quickly -- [ ] Refuses foreign `Host` (DNS rebinding), any web `Origin`, form content types and preflights; no CORS headers -- [ ] Checks links (http, https, ftp, ftps, sftp, stream schemes only), names and headers; hop-by-hop and injection headers dropped -- [ ] Cookies, referrer and user agent used for the download and kept through the keyring module -- [ ] Sender log: when, what, accepted or why not; sender process name from /proc/net/tcp where possible -- [ ] docs/CONNECTOR.md: format, examples with curl, security notes -- [ ] Test file `docs/tests/S023-port-server.md`, with the checks below -- [ ] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S023: …`, push +- [x] Server on loopback only, changeable port, on and off live, port-in-use state that names the fix +- [x] `GET /` ping with name and version; `POST /` with one link or a list, unknown fields ignored, size and rate limits, answers 2xx quickly +- [x] Refuses foreign `Host` (DNS rebinding), any web `Origin`, form content types and preflights; no CORS headers +- [x] Checks links (http, https, ftp, ftps, sftp, stream schemes only), names and headers; hop-by-hop and injection headers dropped +- [x] Cookies, referrer and user agent used for the download and kept through the keyring module +- [x] Sender log: when, what, accepted or why not; sender process name from /proc/net/tcp where possible +- [x] docs/CONNECTOR.md: format, examples with curl, security notes +- [x] Test file `docs/tests/S023-port-server.md`, with the checks below +- [x] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S023: …`, push ## End criteria `nice cargo check -q -j 2 -p medlar` clean diff --git a/Plans/INDEX.md b/Plans/INDEX.md index 78b5e4e..1240d58 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -39,7 +39,7 @@ Tracker: https://claude.ai/artifact/XouimfVJS6FYVKskGJ8s7H ## 05 Connector -- [ ] [S023](05%20Connector/S023-port-server.md) The port and its protection +- [x] [S023](05%20Connector/S023-port-server.md) The port and its protection - [ ] [S024](05%20Connector/S024-handoff-flow.md) Hand-off flow and Nacre test ## 06 Media diff --git a/crates/core/lang/en.json b/crates/core/lang/en.json index a8f0e07..e96e891 100644 --- a/crates/core/lang/en.json +++ b/crates/core/lang/en.json @@ -330,6 +330,23 @@ "error.login.proxy": "The proxy for {server} wants a user name and password, or the ones it got are wrong.", "secret.memory": "No keyring answered, so logins are only remembered until Medlar closes.", "secret.label": "Medlar login for {host}", + "connector.taken": "Port {port} for the browser is used by another program. Pick another port under Settings, Browser, and give the browser the same one.", + "connector.taken_by": "Port {port} for the browser is used by {by}. Close {by} or pick another port under Settings, Browser, and give the browser the same one.", + "connector.failed": "Port {port} for the browser could not be opened: {why}", + "connector.refused.host": "Refused: it named another computer, as a web page does when it pretends to be this one.", + "connector.refused.origin": "Refused: it came from a web page.", + "connector.refused.preflight": "Refused: a web page asked whether it may send links.", + "connector.refused.type": "Refused: not sent as JSON, as a web form would send it.", + "connector.refused.method": "Refused: not a request for this port.", + "connector.refused.malformed": "Refused: the request was broken.", + "connector.refused.large": "Refused: too large.", + "connector.refused.slow": "Refused: the request did not arrive in time.", + "connector.refused.busy": "Refused: too many requests at once.", + "connector.refused.body": "Refused: it held no link in a known format.", + "connector.refused.no_links": "Refused: none of its links can be downloaded.", + "connector.bad.missing": "There is no link.", + "connector.bad.invalid": "This is not a valid link.", + "connector.bad.scheme": "Medlar can't download this kind of link.", "error.rejected": "Request rejected", "error.rejected.plain": "{server} did not accept the request.", "error.rejected.why": "{server} did not accept the request (status {code}).", diff --git a/crates/core/src/connector/link.rs b/crates/core/src/connector/link.rs new file mode 100644 index 0000000..65fa9fe --- /dev/null +++ b/crates/core/src/connector/link.rs @@ -0,0 +1,209 @@ +//! The links in a hand-over body: Nacre's `custom_body` (D-003, D-010), one object or a list of them. Unknown fields +//! are ignored. Each link is checked alone: a bad one is refused, the others still come in. + +use super::wire::{is_plain, is_token}; +use crate::auth::take_login; +use crate::model::Task; +use crate::redact; +use crate::secret::{self, Kept, Secret, Secrets}; +use serde::Deserialize; +use serde_json::Value; +use std::fmt; +use url::Url; + +pub(super) const LINKS_MAX: usize = 1000; +const URL_MAX: usize = 8 * 1024; +const VALUE_MAX: usize = 8 * 1024; +const COOKIES_MAX: usize = 32 * 1024; +const HEADERS_MAX: usize = 32; + +/// What the engine can fetch: HTTP, FTP, SFTP and the stream schemes the recorder knows. +const SCHEMES: &[&str] = &["http", "https", "ftp", "ftps", "ftpes", "sftp", "rtsp", "mms", "mmsh", "mmst"]; + +/// Never taken from a sender: they belong to the connection, would break ranges or resuming, or are set here. +const DROPPED: &[&str] = &[ + "connection", "keep-alive", "te", "trailer", "transfer-encoding", "upgrade", "host", "content-length", "content-type", + "content-encoding", "accept-encoding", "expect", "range", "origin", +]; +const DROPPED_STARTS: &[&str] = &["proxy-", "if-", "sec-", "access-control-"]; + +#[derive(Deserialize)] +#[serde(untagged)] +pub(super) enum Body { + Many(Vec), + One(Raw), +} + +impl Body { + pub fn links(self) -> Vec { + match self { + Body::Many(links) => links, + Body::One(link) => vec![link], + } + } +} + +#[derive(Deserialize, Default)] +#[serde(default)] +pub(super) struct Raw { + url: Option, + filename: Option, + referrer: Option, + cookies: Option, + user_agent: Option, + headers: Option>, + size: Option, + mime: Option, +} + +/// Why a link was not taken. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Bad { + Missing, + /// Not a link, too long, or with line breaks in it. + Invalid, + Scheme, +} + +impl Bad { + pub fn code(self) -> &'static str { + match self { + Bad::Missing => "missing", + Bad::Invalid => "invalid", + Bad::Scheme => "scheme", + } + } + + pub fn words(self) -> String { + match self { + Bad::Missing => crate::tr!("connector.bad.missing"), + Bad::Invalid => crate::tr!("connector.bad.invalid"), + Bad::Scheme => crate::tr!("connector.bad.scheme"), + } + } +} + +/// A link from the browser, checked. +#[derive(Clone, PartialEq, Eq)] +pub struct Incoming { + /// Without a login: that is in `secret`. + pub url: String, + /// Made safe; None to let the server name it. + pub name: Option, + /// The page it was on, without a login. Sent as Referer and kept to find a new link. + pub page: Option, + pub user_agent: Option, + /// Headers that carry no secret, User-Agent and Referer not among them. + pub headers: Vec<(String, String)>, + /// Cookies, a login and secret headers, for the keyring. + pub secret: Option, + pub size: Option, + pub mime: Option, + /// Names of the headers that were not taken, for the log. + pub dropped: Vec, +} + +impl fmt::Debug for Incoming { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("Incoming").field("url", &redact::url(&self.url)).field("name", &self.name).finish_non_exhaustive() + } +} + +fn text(value: Option, max: usize) -> Option { + let Some(Value::String(text)) = value else { return None }; + let text = text.trim(); + (!text.is_empty() && text.len() <= max && is_plain(text)).then(|| text.to_string()) +} + +/// A web page's address without its login, or None. +fn page(text: &str) -> Option { + let mut url = Url::parse(text).ok().filter(|u| matches!(u.scheme(), "http" | "https"))?; + url.set_username("").ok()?; + url.set_password(None).ok()?; + Some(url.into()) +} + +impl Raw { + pub fn check(self) -> Result { + let Some(Value::String(url)) = self.url else { return Err(Bad::Missing) }; + let url = url.trim(); + if url.is_empty() { + return Err(Bad::Missing); + } + if url.len() > URL_MAX || url.chars().any(|c| c.is_control() || c.is_whitespace()) { + return Err(Bad::Invalid); + } + let parsed = Url::parse(url).map_err(|_| Bad::Invalid)?; + if !SCHEMES.contains(&parsed.scheme()) { + return Err(Bad::Scheme); + } + if parsed.host_str().is_none_or(str::is_empty) { + return Err(Bad::Invalid); + } + let (url, login) = take_login(parsed.as_str()); + let name = text(self.filename, VALUE_MAX).and_then(|n| crate::http::name::safe(&n)); + let mut page = text(self.referrer, URL_MAX).and_then(|p| page(&p)); + let mut user_agent = text(self.user_agent, VALUE_MAX); + let mut cookies = text(self.cookies, COOKIES_MAX); + let (mut headers, mut hidden, mut dropped) = (vec![], vec![], vec![]); + for (name, value) in self.headers.unwrap_or_default() { + let lower = name.to_ascii_lowercase(); + let max = if lower == "cookie" { COOKIES_MAX } else { VALUE_MAX }; + let Some(value) = text(Some(value), max).filter(|_| is_token(&name) && name.len() <= 64) else { + dropped.push(if is_token(&name) && name.len() <= 64 { name } else { "?".into() }); + continue; + }; + match lower.as_str() { + "cookie" => { + cookies.get_or_insert(value); + } + "user-agent" => { + user_agent.get_or_insert(value); + } + "referer" => { + if page.is_none() { + page = super::link::page(&value); + } + } + l if DROPPED.contains(&l) || DROPPED_STARTS.iter().any(|s| l.starts_with(s)) => dropped.push(name), + _ if headers.len() + hidden.len() == HEADERS_MAX => dropped.push(name), + l if redact::is_secret_header(l) => hidden.push((name, value)), + _ => headers.push((name, value)), + } + } + let secret = (login.is_some() || cookies.is_some() || !hidden.is_empty()) + .then(|| Secret { home: Some(url.clone()), login, cookies, headers: hidden }); + let size = self.size.and_then(|s| s.as_u64()); + let mime = text(self.mime, 256).filter(|m| m.contains('/')); + Ok(Incoming { url, name, page, user_agent, headers, secret, size, mime, dropped }) + } +} + +impl Incoming { + /// The headers the download is fetched with: the sender's, its User-Agent and the page as Referer. + pub fn task_headers(&self) -> Vec<(String, String)> { + let mut all = self.headers.clone(); + all.extend(self.user_agent.iter().map(|ua| ("User-Agent".to_string(), ua.clone()))); + all.extend(self.page.iter().map(|p| ("Referer".to_string(), p.clone()))); + all + } + + /// A task for it, on top of `common` (folder, queue and so on). Size and type are the sender's guess and are left + /// out: the server tells. Its secret goes to the keyring first, under a new name the task carries; `Kept::Memory` + /// says that it lasts only until Medlar closes. + pub async fn task(&self, secrets: &Secrets, common: Task) -> (Task, Option) { + let mut task = Task { + url: self.url.clone(), + name: self.name.clone().unwrap_or_default(), + source_page: self.page.clone(), + headers: self.task_headers(), + ..common + }; + let Some(secret) = &self.secret else { return (task, None) }; + let name = secret::task_name(); + let host = Url::parse(&self.url).ok().and_then(|u| u.host_str().map(String::from)).unwrap_or_default(); + let kept = secrets.save(&name, &host, secret).await; + task.secret = Some(name); + (task, Some(kept)) + } +} diff --git a/crates/core/src/connector/mod.rs b/crates/core/src/connector/mod.rs new file mode 100644 index 0000000..9f9014f --- /dev/null +++ b/crates/core/src/connector/mod.rs @@ -0,0 +1,398 @@ +//! The local port that takes links from the browser (FEATURES 4.1–4.3, 4.5; format in docs/CONNECTOR.md). +//! +//! Any web page can reach 127.0.0.1, so a request is refused unless it plainly comes from a program on this PC: a +//! `Host` naming loopback and this port (no DNS rebinding), no `Origin` and no cross-site `Sec-Fetch-Site` (no page's +//! fetch or form), `application/json` only (a form can't send it without a preflight, and preflights are refused), no +//! CORS headers in any answer. Bound to 127.0.0.1 only, never 0.0.0.0. + +mod link; +mod peer; +mod wire; + +pub use link::{Bad, Incoming}; + +use crate::model::{Time, now}; +use crate::{VERSION, redact, tr}; +use serde_json::json; +use std::collections::VecDeque; +use std::io; +use std::net::{Ipv4Addr, SocketAddr}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; +use tokio::io::AsyncWriteExt; +use tokio::net::{TcpListener, TcpStream}; +use tokio::sync::{Semaphore, mpsc, watch}; + +/// For the whole request to come in. +const READ: Duration = Duration::from_secs(5); +/// Before a port that was taken is tried again. +const RETRY: Duration = Duration::from_secs(5); +const CONNECTIONS: usize = 16; +/// Requests at once, and per second after that. +const BURST: f64 = 30.0; +const PER_SECOND: f64 = 5.0; +const LOG_MAX: usize = 500; + +/// Whether the port is open. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Status { + Off, + On(u16), + /// Another program has the port; `by` is its name when it can be seen. Tried again every few seconds. + Taken { port: u16, by: Option }, + Failed { port: u16, why: String }, +} + +impl Status { + /// What is wrong and how to fix it, or None when nothing is. + pub fn words(&self) -> Option { + match self { + Status::Off | Status::On(_) => None, + Status::Taken { port, by: Some(by) } => Some(tr!("connector.taken_by", port = port, by = by)), + Status::Taken { port, by: None } => Some(tr!("connector.taken", port = port)), + Status::Failed { port, why } => Some(tr!("connector.failed", port = port, why = why)), + } + } +} + +/// Why a request was refused. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Refused { + /// `Host` is not this PC and port: a web page through DNS rebinding. + Host, + /// Sent by a web page. + Origin, + Preflight, + /// Not `application/json`, as a web form would send. + Type, + Method, + Path, + Malformed, + TooLarge, + /// Chunked or without a length. + Length, + Slow, + Busy, + /// Not the JSON of a link or a list of them. + Body, + /// None of its links could be taken. + NoLinks, + TooMany, +} + +impl Refused { + fn status(self) -> u16 { + match self { + Refused::Host | Refused::Origin => 403, + Refused::Preflight | Refused::Method => 405, + Refused::Type => 415, + Refused::Path => 404, + Refused::Malformed | Refused::Body => 400, + Refused::TooLarge | Refused::TooMany => 413, + Refused::Length => 411, + Refused::Slow => 408, + Refused::Busy => 429, + Refused::NoLinks => 422, + } + } + + /// For the sender: stable, in English. + pub fn code(self) -> &'static str { + match self { + Refused::Host => "host", + Refused::Origin => "origin", + Refused::Preflight => "preflight", + Refused::Type => "content-type", + Refused::Method => "method", + Refused::Path => "path", + Refused::Malformed => "malformed", + Refused::TooLarge => "too-large", + Refused::Length => "length", + Refused::Slow => "slow", + Refused::Busy => "busy", + Refused::Body => "body", + Refused::NoLinks => "no-links", + Refused::TooMany => "too-many", + } + } + + pub fn words(self) -> String { + match self { + Refused::Host => tr!("connector.refused.host"), + Refused::Origin => tr!("connector.refused.origin"), + Refused::Preflight => tr!("connector.refused.preflight"), + Refused::Type => tr!("connector.refused.type"), + Refused::Method | Refused::Path => tr!("connector.refused.method"), + Refused::Malformed | Refused::Length => tr!("connector.refused.malformed"), + Refused::TooLarge | Refused::TooMany => tr!("connector.refused.large"), + Refused::Slow => tr!("connector.refused.slow"), + Refused::Busy => tr!("connector.refused.busy"), + Refused::Body => tr!("connector.refused.body"), + Refused::NoLinks => tr!("connector.refused.no_links"), + } + } +} + +/// Who sent it. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct Sender { + /// The program's name, when it is the user's own and could be seen. + pub process: Option, + /// Its port. + pub port: u16, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Outcome { + Accepted { links: usize, refused: usize }, + Refused(Refused), +} + +/// One line of the sender log. `what` has no secrets: links without login or query string. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Entry { + pub at: Time, + pub from: Sender, + pub what: String, + pub outcome: Outcome, +} + +/// Links that came in together. The incoming-link event for the UI. +#[derive(Debug, Clone)] +pub struct Arrival { + pub links: Vec, + pub from: Sender, + pub at: Time, +} + +#[derive(Default)] +struct Shared { + status: Mutex>, + log: Mutex>, + wake: Mutex>>, +} + +impl Shared { + fn set(&self, status: Status) { + *self.status.lock().unwrap() = Some(status); + self.wake(); + } + + fn note(&self, entry: Entry) { + match &entry.outcome { + Outcome::Refused(why) => log::info!("connector: refused {} from {:?}: {}", entry.what, entry.from.process, why.code()), + Outcome::Accepted { links, .. } => log::info!("connector: {links} links from {:?}", entry.from.process), + } + let mut list = self.log.lock().unwrap(); + if list.len() == LOG_MAX { + list.pop_front(); + } + list.push_back(entry); + drop(list); + self.wake(); + } + + fn wake(&self) { + if let Some(call) = &*self.wake.lock().unwrap() { + call(); + } + } +} + +/// The port, on its own thread. Dropping it closes the port. +pub struct Connector { + want: watch::Sender<(bool, u16)>, + shared: Arc, +} + +impl Connector { + /// Port 0 takes any free one (for tests); `status` tells which. + pub fn start(on: bool, port: u16) -> io::Result<(Connector, mpsc::UnboundedReceiver)> { + let (want, wanted) = watch::channel((on, port)); + let (links, arrivals) = mpsc::unbounded_channel(); + let shared = Arc::new(Shared::default()); + let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build()?; + let inner = shared.clone(); + std::thread::Builder::new().name("connector".into()).spawn(move || runtime.block_on(serve(wanted, inner, links)))?; + Ok((Connector { want, shared }, arrivals)) + } + + /// On or off and the port, live. + pub fn set(&self, on: bool, port: u16) { + self.want.send_if_modified(|w| std::mem::replace(w, (on, port)) != (on, port)); + } + + /// None until the first try is done. + pub fn status(&self) -> Option { + self.shared.status.lock().unwrap().clone() + } + + /// Oldest first. + pub fn log(&self) -> Vec { + self.shared.log.lock().unwrap().iter().cloned().collect() + } + + /// Called from the connector's thread when the status or the log changes. + pub fn on_change(&self, call: impl Fn() + Send + 'static) { + *self.shared.wake.lock().unwrap() = Some(Box::new(call)); + } +} + +async fn serve(mut want: watch::Receiver<(bool, u16)>, shared: Arc, links: mpsc::UnboundedSender) { + loop { + let (on, port) = *want.borrow_and_update(); + if !on { + shared.set(Status::Off); + if want.changed().await.is_err() { + return; + } + continue; + } + match TcpListener::bind((Ipv4Addr::LOCALHOST, port)).await { + Ok(listener) => { + let port = listener.local_addr().map_or(port, |a| a.port()); + shared.set(Status::On(port)); + let gate = Arc::new(Gate::new()); + loop { + tokio::select! { + changed = want.changed() => if changed.is_err() { return } else { break }, + accepted = listener.accept() => if let Ok((stream, peer)) = accepted { + let Ok(permit) = gate.connections.clone().try_acquire_owned() else { continue }; + let (shared, links, gate) = (shared.clone(), links.clone(), gate.clone()); + tokio::spawn(async move { + handle(stream, peer, port, &shared, &links, &gate).await; + drop(permit); + }); + }, + } + } + } + Err(e) => { + let status = if e.kind() == io::ErrorKind::AddrInUse { + let by = tokio::task::spawn_blocking(move || peer::listener(port)).await.ok().flatten(); + Status::Taken { port, by } + } else { + Status::Failed { port, why: e.to_string() } + }; + shared.set(status); + tokio::select! { + changed = want.changed() => if changed.is_err() { return }, + _ = tokio::time::sleep(RETRY) => {}, + } + } + } + } +} + +struct Gate { + connections: Arc, + tokens: Mutex<(f64, Instant)>, +} + +impl Gate { + fn new() -> Gate { + Gate { connections: Arc::new(Semaphore::new(CONNECTIONS)), tokens: Mutex::new((BURST, Instant::now())) } + } + + fn take(&self) -> bool { + let mut tokens = self.tokens.lock().unwrap(); + let (left, since) = *tokens; + let left = (left + since.elapsed().as_secs_f64() * PER_SECOND).min(BURST); + let taken = left >= 1.0; + *tokens = (if taken { left - 1.0 } else { left }, Instant::now()); + taken + } +} + +async fn handle(mut stream: TcpStream, peer: SocketAddr, port: u16, shared: &Shared, links: &mpsc::UnboundedSender, gate: &Gate) { + let other = peer.port(); + let who = tokio::task::spawn_blocking(move || peer::process(port, other)); + let (code, body, entry) = if gate.take() { + match tokio::time::timeout(READ, wire::read(&mut stream)).await { + Err(_) => refuse(Refused::Slow, "?".into()), + Ok(Err(why)) => refuse(why, "?".into()), + Ok(Ok(request)) => answer(&request, port), + } + } else { + refuse(Refused::Busy, "?".into()) + }; + let from = Sender { process: who.await.ok().flatten(), port: other }; + let _ = stream.write_all(&wire::answer(code, &body)).await; + let _ = stream.shutdown().await; + let Some((what, outcome, taken)) = entry else { return }; + if !taken.is_empty() { + let _ = links.send(Arrival { links: taken, from: from.clone(), at: now() }); + } + shared.note(Entry { at: now(), from, what, outcome }); +} + +/// Status, body, and what goes in the log (None for a ping). +type Answer = (u16, serde_json::Value, Option<(String, Outcome, Vec)>); + +fn refuse(why: Refused, what: String) -> Answer { + (why.status(), json!({ "error": why.code() }), Some((what, Outcome::Refused(why), vec![]))) +} + +fn answer(request: &wire::Request, port: u16) -> Answer { + // The path only: a query string may hold anything. + let path: String = request.target.split(['?', '#']).next().unwrap_or("").chars().take(100).collect(); + let what = format!("{} {path}", request.method); + if let Err(why) = guard(request, port) { + return refuse(why, what); + } + if request.method == "GET" { + return (200, json!({ "name": "Medlar", "version": VERSION }), None); + } + let Ok(body) = serde_json::from_slice::(&request.body) else { return refuse(Refused::Body, what) }; + let raw = body.links(); + if raw.len() > link::LINKS_MAX { + return refuse(Refused::TooMany, what); + } + let (mut taken, mut refused) = (vec![], vec![]); + for (index, link) in raw.into_iter().enumerate() { + match link.check() { + Ok(link) => taken.push(link), + Err(bad) => refused.push(json!({ "index": index, "why": bad.code() })), + } + } + let what = match taken.first() { + Some(first) => format!("{} ({})", redact::url(&first.url), taken.len()), + None => what, + }; + if taken.is_empty() { + let (code, _, entry) = refuse(Refused::NoLinks, what); + return (code, json!({ "error": Refused::NoLinks.code(), "refused": refused }), entry); + } + let outcome = Outcome::Accepted { links: taken.len(), refused: refused.len() }; + (200, json!({ "accepted": taken.len(), "refused": refused }), Some((what, outcome, taken))) +} + +/// Everything that tells a program on this PC from a web page. +fn guard(request: &wire::Request, port: u16) -> Result<(), Refused> { + let host = request.header("host").unwrap_or("").to_ascii_lowercase(); + let own = [format!("127.0.0.1:{port}"), format!("localhost:{port}")]; + if request.count("host") != 1 || !own.contains(&host) { + return Err(Refused::Host); + } + let fetch_site = request.header("sec-fetch-site"); + if request.header("origin").is_some() || fetch_site.is_some_and(|s| s != "none") || request.header("sec-fetch-mode").is_some_and(|m| m == "cors") { + return Err(Refused::Origin); + } + if request.method == "OPTIONS" || request.header("access-control-request-method").is_some() { + return Err(Refused::Preflight); + } + if request.target != "/" { + return Err(Refused::Path); + } + match request.method.as_str() { + "GET" => Ok(()), + "POST" => { + let kind = request.header("content-type").unwrap_or("").to_ascii_lowercase(); + let mut parts = kind.split(';').map(str::trim); + let json = parts.next() == Some("application/json"); + let utf8 = parts.all(|p| p.is_empty() || matches!(p, "charset=utf-8" | "charset=\"utf-8\"")); + if json && utf8 && request.count("content-type") == 1 { Ok(()) } else { Err(Refused::Type) } + } + _ => Err(Refused::Method), + } +} diff --git a/crates/core/src/connector/peer.rs b/crates/core/src/connector/peer.rs new file mode 100644 index 0000000..93cea1a --- /dev/null +++ b/crates/core/src/connector/peer.rs @@ -0,0 +1,44 @@ +//! Which program is at the other end of a connection on this PC: `/proc/net/tcp` gives the socket's inode, a process's +//! `fd` folder has a link to it. Only the user's own processes can be seen; others stay unnamed. + +use std::fs; + +/// The program whose socket has port `own` here and `other` at its other end, both on 127.0.0.1. +pub(super) fn process(own: u16, other: u16) -> Option { + inode(|local, remote, _| local == own && remote == other).and_then(owner) +} + +/// The program that listens on `port`. +pub(super) fn listener(port: u16) -> Option { + inode(|local, _, state| local == port && state == "0A").and_then(owner) +} + +fn port(address: &str) -> Option { + u16::from_str_radix(address.rsplit(':').next()?, 16).ok() +} + +fn inode(want: impl Fn(u16, u16, &str) -> bool) -> Option { + ["/proc/net/tcp", "/proc/net/tcp6"].iter().find_map(|file| { + let table = fs::read_to_string(file).ok()?; + table.lines().skip(1).find_map(|line| { + let f: Vec<&str> = line.split_whitespace().collect(); + let (local, remote) = (port(f.get(1)?)?, port(f.get(2)?)?); + let inode: u64 = f.get(9)?.parse().ok()?; + (inode != 0 && want(local, remote, f.get(3)?)).then_some(inode) + }) + }) +} + +fn owner(inode: u64) -> Option { + let link = format!("socket:[{inode}]"); + for process in fs::read_dir("/proc").ok()?.flatten() { + let pid = process.file_name(); + let Some(pid) = pid.to_str().filter(|p| p.bytes().all(|b| b.is_ascii_digit())) else { continue }; + let Ok(fds) = fs::read_dir(format!("/proc/{pid}/fd")) else { continue }; + if fds.flatten().any(|fd| fs::read_link(fd.path()).is_ok_and(|l| l.as_os_str() == link.as_str())) { + let name = fs::read_to_string(format!("/proc/{pid}/comm")).ok()?; + return Some(name.trim().chars().filter(|c| !c.is_control()).collect()); + } + } + None +} diff --git a/crates/core/src/connector/wire.rs b/crates/core/src/connector/wire.rs new file mode 100644 index 0000000..a0fe0df --- /dev/null +++ b/crates/core/src/connector/wire.rs @@ -0,0 +1,135 @@ +//! One HTTP/1.1 request, read strictly, and its answer: only what a browser's hand-over needs. One request per +//! connection, a body only with Content-Length. + +use super::Refused; +use tokio::io::{AsyncRead, AsyncReadExt}; + +pub(super) const HEAD_MAX: usize = 16 * 1024; +pub(super) const BODY_MAX: usize = 1024 * 1024; +const HEADERS_MAX: usize = 64; + +pub(super) struct Request { + pub method: String, + pub target: String, + /// Names in lower case. + pub headers: Vec<(String, String)>, + pub body: Vec, +} + +impl Request { + pub fn header(&self, name: &str) -> Option<&str> { + self.headers.iter().find(|(n, _)| n == name).map(|(_, v)| v.as_str()) + } + + pub fn count(&self, name: &str) -> usize { + self.headers.iter().filter(|(n, _)| n == name).count() + } +} + +/// A token in the sense of RFC 9110: what header names and methods are made of. +pub(super) fn is_token(text: &str) -> bool { + !text.is_empty() && text.bytes().all(|b| b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b)) +} + +/// Visible text, spaces and tabs: no line breaks or other control characters. +pub(super) fn is_plain(text: &str) -> bool { + text.chars().all(|c| c == '\t' || !c.is_control()) +} + +pub(super) async fn read(stream: &mut (impl AsyncRead + Unpin)) -> Result { + let mut buffer = Vec::with_capacity(2048); + let end = loop { + if let Some(at) = buffer.windows(4).position(|w| w == b"\r\n\r\n") { + break at; + } + if buffer.len() > HEAD_MAX { + return Err(Refused::TooLarge); + } + let mut chunk = [0u8; 4096]; + let n = stream.read(&mut chunk).await.map_err(|_| Refused::Malformed)?; + if n == 0 { + return Err(Refused::Malformed); + } + buffer.extend_from_slice(&chunk[..n]); + }; + if end > HEAD_MAX { + return Err(Refused::TooLarge); + } + let head = std::str::from_utf8(&buffer[..end]).map_err(|_| Refused::Malformed)?; + let mut lines = head.split("\r\n"); + let mut first = lines.next().unwrap_or("").split(' '); + let (Some(method), Some(target), Some(version), None) = (first.next(), first.next(), first.next(), first.next()) else { + return Err(Refused::Malformed); + }; + if !is_token(method) || target.is_empty() || !is_plain(target) || !matches!(version, "HTTP/1.1" | "HTTP/1.0") { + return Err(Refused::Malformed); + } + let mut headers = vec![]; + for line in lines { + // No folded lines, no names with spaces before the colon. + let Some((name, value)) = line.split_once(':') else { return Err(Refused::Malformed) }; + if !is_token(name) || !is_plain(value) || headers.len() == HEADERS_MAX { + return Err(Refused::Malformed); + } + headers.push((name.to_ascii_lowercase(), value.trim_matches([' ', '\t']).to_string())); + } + let mut request = Request { method: method.into(), target: target.into(), headers, body: vec![] }; + if request.header("transfer-encoding").is_some() { + return Err(Refused::Length); + } + let lengths: Vec<&str> = request.headers.iter().filter(|(n, _)| n == "content-length").map(|(_, v)| v.as_str()).collect(); + let length = match lengths[..] { + [] => 0, + [one] if !one.is_empty() && one.bytes().all(|b| b.is_ascii_digit()) => one.parse::().map_err(|_| Refused::TooLarge)?, + _ => return Err(Refused::Malformed), + }; + if length > BODY_MAX { + return Err(Refused::TooLarge); + } + let mut body = buffer.split_off(end + 4); + if body.len() > length { + // A second request on the same connection: not taken. + return Err(Refused::Malformed); + } + body.reserve_exact(length - body.len()); + while body.len() < length { + let mut chunk = vec![0u8; (length - body.len()).min(64 * 1024)]; + let n = stream.read(&mut chunk).await.map_err(|_| Refused::Malformed)?; + if n == 0 { + return Err(Refused::Malformed); + } + body.extend_from_slice(&chunk[..n]); + } + request.body = body; + Ok(request) +} + +/// The whole answer. No CORS headers, ever: a web page must not read it. +pub(super) fn answer(code: u16, body: &serde_json::Value) -> Vec { + let reason = match code { + 200 => "OK", + 400 => "Bad Request", + 403 => "Forbidden", + 404 => "Not Found", + 405 => "Method Not Allowed", + 408 => "Request Timeout", + 411 => "Length Required", + 413 => "Content Too Large", + 415 => "Unsupported Media Type", + 422 => "Unprocessable Content", + 429 => "Too Many Requests", + _ => "Error", + }; + let body = body.to_string(); + let mut out = format!( + "HTTP/1.1 {code} {reason}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\ + Cache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\n", + body.len() + ); + if code == 405 { + out.push_str("Allow: GET, POST\r\n"); + } + out.push_str("\r\n"); + out.push_str(&body); + out.into_bytes() +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index fffa6b7..8e75f34 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -4,6 +4,7 @@ pub mod adapt; pub mod adopt; pub mod auth; pub mod batch; +pub mod connector; pub mod cookie; pub mod disk; pub mod duplicate; diff --git a/crates/core/tests/connector_nacre.json b/crates/core/tests/connector_nacre.json new file mode 100644 index 0000000..7d68c3b --- /dev/null +++ b/crates/core/tests/connector_nacre.json @@ -0,0 +1 @@ +{"cookies":"k=v","filename":"a.zip","headers":{"Cookie":"k=v","Referer":"https://example.com/","User-Agent":"UA"},"mime":null,"referrer":"https://example.com/","size":null,"url":"https://example.com/a.zip","user_agent":"UA"} diff --git a/docs/CONNECTOR.md b/docs/CONNECTOR.md new file mode 100644 index 0000000..dcb20ea --- /dev/null +++ b/docs/CONNECTOR.md @@ -0,0 +1,63 @@ +# The browser port + +Medlar listens on `127.0.0.1:17616` (D-006; changeable under Settings, Browser; on and off live). Only programs on this +PC can reach it. Code: `crates/core/src/connector/`. + +## Format + +`GET /` answers `{"name": "Medlar", "version": "0.1.0"}`: a ping. + +`POST /` with `Content-Type: application/json` and a body of one link or a list of them. This is Nacre's +`custom_body` as it is (D-003, D-010); unknown fields are ignored. + +| Field | | | +|---|---|---| +| `url` | required | http, https, ftp, ftps, ftpes, sftp, rtsp, mms, mmsh, mmst | +| `filename` | | made safe: path parts, control characters and leading dots go | +| `referrer` | | the page; sent as `Referer`, kept to find a new link later | +| `cookies` | | as in a `Cookie` header; kept in the keyring only | +| `user_agent` | | sent with the download | +| `headers` | | object of name to value; `Cookie`, `User-Agent`, `Referer` fill the fields above when those are empty | +| `size`, `mime` | | the sender's guess, shown only | + +Answer `200 {"accepted": n, "refused": [{"index": i, "why": "scheme"}]}` when one or more links came in, else an error +with `{"error": ""}`: + +| Status | `error` | Why | +|---|---|---| +| 403 | `host` | `Host` is not `127.0.0.1:` or `localhost:` (DNS rebinding) | +| 403 | `origin` | an `Origin` header, `Sec-Fetch-Site` other than `none`, or `Sec-Fetch-Mode: cors` | +| 405 | `preflight`, `method` | `OPTIONS`, `Access-Control-Request-Method`, or anything but GET and POST | +| 415 | `content-type` | not `application/json` (form types, `text/plain`) | +| 404 | `path` | anything but `/` | +| 400 | `malformed`, `body` | broken HTTP, or JSON that is no link or list | +| 411 | `length` | chunked body | +| 413 | `too-large`, `too-many` | head over 16 KiB, body over 1 MiB, list over 1000 links | +| 408 | `slow` | request not in within 5 s | +| 429 | `busy` | over 30 at once or 5 a second | +| 422 | `no-links` | no link in it could be taken (`why`: `missing`, `invalid`, `scheme`) | + +## Examples + +```sh +curl -s http://127.0.0.1:17616/ +curl -s -H 'Content-Type: application/json' -d '{"url": "https://example.com/a.zip"}' http://127.0.0.1:17616/ +curl -s -H 'Content-Type: application/json' \ + -d '[{"url": "https://example.com/a.zip", "filename": "a.zip", "referrer": "https://example.com/", + "cookies": "k=v", "user_agent": "UA", "headers": {"X-Kind": "one"}}, {"url": "ftp://example.com/b.iso"}]' \ + http://127.0.0.1:17616/ +``` + +## Security + +- Bound to 127.0.0.1 only, never 0.0.0.0. Port 15151 belongs to AB Download Manager and is not used. +- No CORS headers in any answer, so a web page can't read one; JSON only, so a page can't post without a preflight, + and preflights are refused. `Host` is checked against loopback and the port, so a rebound name is refused. +- One request per connection, 5 s to send it, 16 connections at once, a token bucket against floods. +- Headers in values with line breaks or control characters are dropped, and so are hop-by-hop and controlled ones + (`Connection`, `Host`, `Range`, `Accept-Encoding`, `Transfer-Encoding`, `Content-*`, `If-*`, `Proxy-*`, `Sec-*` …), + at most 32 kept. Cookies, a login in the link and secret headers go to the keyring (`secret::Secrets`), never to + the store or the log. +- Sender log (`Connector::log`): when, what (link without login or query string), accepted or why not, and the + sending program's name from `/proc/net/tcp` when it is the user's own. +- Links arrive on the channel from `Connector::start` as `Arrival`; `Incoming::task` makes a task and keeps its secret. diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index e4987ac..5654460 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -208,3 +208,8 @@ Seen: boxes were ticked together after the tests, against rule 3. ## S022 — Control screens (compiled, not tested, no screenshots) - Toolbar mode switch (`views/modes.rs`, snail included) opens one sheet (`views/control.rs`): Speed dial (log scale, KB/s|MB/s, typing), Queues (`queues.rs` cards, live totals, reorder by handle or buttons, "move selected here", editor with week grid), Week (`Settings.mode_grid` → `limits_at`, applied by `bridge.apply`, rechecked each hour), When done (`schedule.rs`: Watcher countdown dialog, Logind, `run::run`, Inhibitor while running). Priority share text in details. - Not done: dragging tasks onto queue cards (used a button), start-time grid, priority share preview in list rows, core `Grid` unused (own grid instead). Limit changes save through the settings debounce, not on release. + +## S023 — Browser port (compiled, not tested) +- `connector::Connector::start(on, port) -> (Connector, UnboundedReceiver)`: the incoming-link event for the UI. `set(on, port)` live, `status()` (`Taken{by}` names the fix via `words()`), `log()` sender log, `on_change`. `Incoming::task(&Secrets, common)` makes the task and keeps cookies/login in the keyring. +- Guards: loopback only, Host = 127.0.0.1|localhost:port, no Origin / cross-site Sec-Fetch, JSON only, preflights refused, no CORS; header and link checks. Format: `docs/CONNECTOR.md`. Tests: `docs/tests/S023-port-server.md`. +- Not done: no app wiring (S024), no automatic tests yet; own small HTTP/1.1 reader instead of hyper's server. diff --git a/docs/tests/S023-port-server.md b/docs/tests/S023-port-server.md new file mode 100644 index 0000000..08e2e40 --- /dev/null +++ b/docs/tests/S023-port-server.md @@ -0,0 +1,45 @@ +# S023 — The port and its protection: test file + +Written by the worker that built it, run by the test phase. Nothing here has been tested until its Result says so. + +## Built +- `crates/core/src/connector/mod.rs` · `Connector::start(on, port) -> (Connector, Receiver)`, `set(on, port)` live, `status()`, `log()`, `on_change`; `guard` (Host, Origin, preflight, type), `Gate` (16 connections, bucket 30 + 5/s). +- `connector/wire.rs` · strict HTTP/1.1 read (head 16 KiB, body 1 MiB, Content-Length only), `answer` (no CORS). +- `connector/link.rs` · `Body` (object or list), `Raw::check` -> `Incoming`, `Incoming::task(&Secrets, common)`. +- `connector/peer.rs` · sender / listener program name from `/proc/net/tcp` and `/proc/*/fd`. +- `crates/core/tests/connector_nacre.json` · Nacre's `custom_body` output, as a fixture. `docs/CONNECTOR.md` · format. +Nothing is wired into the app yet (S024). Reach it from a test: `Connector::start(true, 0)`, read the port from `status()`. + +## Checks +| # | Risk | Do this | Expect | How | Result | +|---|---|---|---|---|---| +| 1 | HIGH | Start on port 0; `ss -ltn` / `status()` | `On(p)`, bound on 127.0.0.1 only, nothing on 0.0.0.0 or :: | integration | — | +| 2 | HIGH | curl POST the fixture with `Content-Type: application/json` | 200 `{"accepted":1,"refused":[]}`; one `Arrival`: url, name `a.zip`, page `https://example.com/`, user agent `UA`, secret cookies `k=v`, `task_headers()` has User-Agent and Referer, no Cookie | integration | — | +| 3 | HIGH | `Host: evil.example:p`, `Host: 127.0.0.1:1`, two Host headers, no Host | 403 `host`, no Arrival, log entry Refused(Host) | integration | — | +| 4 | HIGH | Add `Origin: https://evil.example`, `Origin: null`, `Sec-Fetch-Site: cross-site`, `Sec-Fetch-Mode: cors` (each alone) | 403 `origin` | integration | — | +| 5 | HIGH | POST with `application/x-www-form-urlencoded`, `multipart/form-data`, `text/plain`, `application/json; charset=latin1` | 415 `content-type` | integration | — | +| 6 | HIGH | `OPTIONS /` with `Access-Control-Request-Method: POST`; also POST with that header | 405 `preflight`; no `Access-Control-*` header in any answer of checks 2–9 | integration | — | +| 7 | HIGH | Link headers `{"X-A":"1\r\nX-B: 2","Connection":"close","Range":"bytes=5-","Accept-Encoding":"gzip","If-None-Match":"x","Authorization":"Bearer t"}` | X-A, Connection, Range, Accept-Encoding, If-None-Match dropped (in `dropped`); Authorization only in `secret.headers`; user agent with `\n` dropped | unit | — | +| 8 | HIGH | Links `javascript:alert(1)`, `file:///etc/passwd`, `data:,x`, `http://`, a 9 KiB URL, `https://u:p@h/f` | first five refused (`scheme`/`invalid`), last accepted as `https://h/f` with the login in `secret` | unit | — | +| 9 | HIGH | Filename `../../.bashrc`, `a\u0000b`, 400 chars | made safe by `http::name::safe` (no slashes, no leading dot, capped) | unit | — | +| 10 | HIGH | `Incoming::task` with `Secrets::new(Bus::Off)` | task.secret is a `task:` name; `secrets.load` gives the cookies; task headers carry no secret (store accepts it) | unit | — | +| 11 | HIGH | Log after checks 2–8 | entries with time, what, outcome; no cookie value, login or query string appears in any `what` | integration | — | +| 12 | MED | GET `/` | 200 `{"name":"Medlar","version":...}`, not logged | integration | — | +| 13 | MED | List of 3 links, one bad; then a list of 1001; then `{}`; then `[]`; then `not json` | 200 accepted 2 refused index 1; 413 `too-many`; 422 `no-links`; 422; 400 `body` | integration | — | +| 14 | MED | Body 1 MiB + 1; `Transfer-Encoding: chunked`; head of 20 KiB; open and send nothing for 6 s | 413; 411; 413; 408 or closed | integration | — | +| 15 | MED | 40 requests at once from one loop | the first ≈30 answered normally, later ones 429 `busy` | integration | — | +| 16 | MED | Hold the port with another listener, start on it | `Taken { by: Some(test binary name) }`, `words()` names the port and the fix; free it: `On` within ~5 s | integration | — | +| 17 | MED | `set(false, p)`, then `set(true, q)` | port closed (connect refused), then open on q; status follows | integration | — | +| 18 | LOW | Sender of check 2 | `from.process` is `curl` (a process of this user) | integration | — | + +## Needs +Loopback only, ports chosen free (port 0) — never 15151 or 38151 or 17616 while the user's Medlar runs. curl for check 2. No network. + +## Doubts +- Never compiled beyond `cargo check`; never run. The hand-written HTTP reader is the main risk: partial reads, a request split over several packets, HTTP/1.0 clients. +- Nacre's request (ureq): check it sends `Host: 127.0.0.1:`, no `Origin`, no chunked body — else check 2 passes with curl but Nacre fails. +- `Sec-Fetch-Site: none` is let through (typed in the address bar: GET only, harmless). +- Rate limit is per listener and global, so a flood also delays the real browser for a few seconds. +- `peer::process` scans every `/proc/*/fd`: may be slow with many processes; it runs beside the read. +- `Body` is untagged: a known field of the wrong JSON type (for example `"headers": []`) refuses the whole body with `body`. +- The UI is not wired: S024 must call `Connector::start`/`set` from settings and show `status().words()`. From 7a4ba45c9d1c6b36110cd7a726393dec0ee2d7a5 Mon Sep 17 00:00:00 2001 From: astar76 Date: Wed, 25 Nov 2026 21:58:04 -0600 Subject: [PATCH 02/61] S024: hand-off flow: browser links to the Add window or a continued download, single instance, connector page Co-Authored-By: Claude Sonnet 5.5 --- Plans/INDEX.md | 2 +- assets/medlar.desktop | 10 ++ crates/app/src/app.rs | 33 +++- crates/app/src/instance.rs | 72 ++++++++ crates/app/src/lib.rs | 3 +- crates/app/src/main.rs | 3 + crates/app/src/views/add/mod.rs | 12 +- crates/app/src/views/connector.rs | 74 ++++++++ crates/app/src/views/incoming.rs | 239 ++++++++++++++++++++++++++ crates/app/src/views/mod.rs | 2 + crates/app/src/views/settings/rows.rs | 19 ++ crates/core/lang/en.json | 26 ++- crates/core/src/settings.rs | 22 +++ docs/PROGRESS.md | 5 + docs/tests/S024-handoff-flow.md | 42 +++++ 15 files changed, 552 insertions(+), 12 deletions(-) create mode 100644 assets/medlar.desktop create mode 100644 crates/app/src/instance.rs create mode 100644 crates/app/src/views/connector.rs create mode 100644 crates/app/src/views/incoming.rs create mode 100644 docs/tests/S024-handoff-flow.md diff --git a/Plans/INDEX.md b/Plans/INDEX.md index 1240d58..00e2ee1 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -40,7 +40,7 @@ Tracker: https://claude.ai/artifact/XouimfVJS6FYVKskGJ8s7H ## 05 Connector - [x] [S023](05%20Connector/S023-port-server.md) The port and its protection -- [ ] [S024](05%20Connector/S024-handoff-flow.md) Hand-off flow and Nacre test +- [x] [S024](05%20Connector/S024-handoff-flow.md) Hand-off flow and Nacre test ## 06 Media diff --git a/assets/medlar.desktop b/assets/medlar.desktop new file mode 100644 index 0000000..f97ea63 --- /dev/null +++ b/assets/medlar.desktop @@ -0,0 +1,10 @@ +[Desktop Entry] +Type=Application +Name=Medlar +Comment=Download manager +Exec=medlar %U +Icon=medlar +Terminal=false +Categories=Network;FileTransfer; +StartupWMClass=medlar +MimeType=x-scheme-handler/medlar;application/metalink+xml;application/metalink4+xml; diff --git a/crates/app/src/app.rs b/crates/app/src/app.rs index c097385..971c896 100644 --- a/crates/app/src/app.rs +++ b/crates/app/src/app.rs @@ -7,6 +7,7 @@ use crate::bridge::{Bridge, Data, Opening}; use crate::keys::{self, Action, Group}; use crate::ui::{dialog, gallery, menu}; use crate::views::firstrun::FirstRun; +use crate::views::incoming::{Inbox, of_arg}; use crate::views::main::{Main, Reply, Wish, open_outside}; use crate::views::palette::{Palette, Pick}; use crate::views::settings::rows::{self, Page}; @@ -39,6 +40,8 @@ pub struct App { /// Where settings are kept. Without it they are not. pub paths: Option, sign_in: Option, + /// The browser port and what came in through it or a second start. + pub inbox: Inbox, /// The desktop's colours, if it has any. pub desktop: Desktop, sources: Sources, @@ -74,6 +77,7 @@ impl App { first: None, paths: None, sign_in: None, + inbox: Inbox::default(), desktop, sources, watch, @@ -197,6 +201,9 @@ impl App { } } } + if self.first.is_none() { + self.inbox.tick(ui.ctx(), &self.settings, &mut self.main); + } let bridge = &self.main.bridge; if let Some(ask) = &mut self.sign_in { ask.show(ui, &t, &mut self.settings, bridge); @@ -330,20 +337,38 @@ impl eframe::App for Window { /// Opens the window and returns when it is closed. pub fn run() -> ExitCode { - open(true, App::show) + run_with(vec![]) +} + +/// Whether the arguments are for a window: links of the `medlar:` scheme and link lists, as a desktop hands them over. +pub fn wants(args: &[String]) -> bool { + !args.is_empty() && args.iter().all(|a| of_arg(a).is_some()) +} + +/// Opens the window with something to add, or hands it to the Medlar that runs and returns. +pub fn run_with(args: Vec) -> ExitCode { + open(true, App::show, args) } /// Opens a window with every control instead (`--gallery`). pub fn run_gallery() -> ExitCode { - open(false, |app, ui| app.frame(ui, gallery::show)) + open(false, |app, ui| app.frame(ui, gallery::show), vec![]) } /// `engine`: with the downloads, else only the window. -fn open(engine: bool, show: fn(&mut App, &mut Ui)) -> ExitCode { +fn open(engine: bool, show: fn(&mut App, &mut Ui), args: Vec) -> ExitCode { let paths = Paths::detect(); if let Err(e) = paths.create() { eprintln!("{}: {e}", paths.config.display()); } + let mut later = None; + if engine { + match crate::instance::claim(&paths.data, &args) { + crate::instance::Claim::Handed => return ExitCode::SUCCESS, + crate::instance::Claim::First(rx) => later = Some(rx), + crate::instance::Claim::Alone => {} + } + } let (settings, damage) = Settings::load(&paths.settings()); if let Err(e) = logging::init(&paths.log(), log::LevelFilter::Info) { eprintln!("{}: {e}", paths.log().display()); @@ -377,6 +402,8 @@ fn open(engine: bool, show: fn(&mut App, &mut Ui)) -> ExitCode { app.first = Some(FirstRun::default()); } app.paths = Some(paths.clone()); + crate::instance::wake_with(&cc.egui_ctx); + app.inbox = Inbox::new(later.take(), args.clone()); app.main.outside = open_outside; app.main.reveal = crate::views::main::reveal_outside; app.main.remember(paths.data.join("view.json")); diff --git a/crates/app/src/instance.rs b/crates/app/src/instance.rs new file mode 100644 index 0000000..ebe7c24 --- /dev/null +++ b/crates/app/src/instance.rs @@ -0,0 +1,72 @@ +//! One Medlar per home: a second start hands its arguments to the first, over a socket, and ends (FEATURES 8.3). + +use eframe::egui::Context; +use std::collections::hash_map::DefaultHasher; +use std::hash::{Hash, Hasher}; +use std::io::{Read, Write}; +use std::os::unix::net::{UnixListener, UnixStream}; +use std::path::{Path, PathBuf}; +use std::sync::OnceLock; +use std::sync::mpsc::{self, Receiver}; + +/// The window, so that the listener can wake it. +static WAKE: OnceLock = OnceLock::new(); + +pub enum Claim { + /// Another one runs and has the arguments. + Handed, + /// This one is the first; what later starts hand over comes through here. + First(Receiver>), + /// No socket could be made: run without the hand-over. + Alone, +} + +/// Where the socket is. The home is in the name, so that a test home has an instance of its own. +fn socket(home: &Path) -> PathBuf { + let mut h = DefaultHasher::new(); + home.hash(&mut h); + let dir = std::env::var_os("XDG_RUNTIME_DIR").map(PathBuf::from).filter(|d| d.is_dir()).unwrap_or_else(std::env::temp_dir); + dir.join(format!("medlar-{:x}.sock", h.finish())) +} + +/// Paths in arguments are made absolute: the first one runs somewhere else. +fn absolute(arg: &str) -> String { + if arg.contains(':') || arg.starts_with('/') || arg.starts_with('-') { + return arg.into(); + } + std::fs::canonicalize(arg).map_or_else(|_| arg.into(), |p| p.display().to_string()) +} + +pub fn claim(home: &Path, args: &[String]) -> Claim { + let path = socket(home); + if let Ok(mut other) = UnixStream::connect(&path) { + let text: Vec = args.iter().map(|a| absolute(a).replace(['\n', '\r'], " ")).collect(); + if other.write_all(format!("{}\n", text.join("\n")).as_bytes()).is_ok() { + return Claim::Handed; + } + } + // Nobody answers: a leftover of a crash. + let _ = std::fs::remove_file(&path); + let Ok(listener) = UnixListener::bind(&path) else { return Claim::Alone }; + let (send, got) = mpsc::channel(); + let spawned = std::thread::Builder::new().name("instance".into()).spawn(move || { + for stream in listener.incoming().flatten() { + let _ = stream.set_read_timeout(Some(std::time::Duration::from_secs(2))); + let mut text = String::new(); + let _ = (&stream).take(1 << 20).read_to_string(&mut text); + let args: Vec = text.lines().map(str::trim).filter(|l| !l.is_empty()).map(String::from).collect(); + // An empty hand-over still raises the window. + if send.send(args).is_err() { + return; + } + if let Some(ctx) = WAKE.get() { + ctx.request_repaint(); + } + } + }); + if spawned.is_err() { Claim::Alone } else { Claim::First(got) } +} + +pub fn wake_with(ctx: &Context) { + let _ = WAKE.set(ctx.clone()); +} diff --git a/crates/app/src/lib.rs b/crates/app/src/lib.rs index b1f09ea..47a9907 100644 --- a/crates/app/src/lib.rs +++ b/crates/app/src/lib.rs @@ -7,6 +7,7 @@ pub mod fonts; #[rustfmt::skip] mod icondata; pub mod icons; +pub mod instance; pub mod keys; pub mod motion; pub mod theme; @@ -14,4 +15,4 @@ pub mod tokens; pub mod ui; pub mod views; -pub use app::{run, run_gallery}; +pub use app::{run, run_gallery, run_with, wants}; diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index a902d99..d217ff0 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -5,6 +5,9 @@ fn main() -> ExitCode { if args.is_empty() { return medlar_app::run(); } + if medlar_app::wants(&args) { + return medlar_app::run_with(args); + } if args == ["--gallery"] { return medlar_app::run_gallery(); } diff --git a/crates/app/src/views/add/mod.rs b/crates/app/src/views/add/mod.rs index 562ede9..de4c8ed 100644 --- a/crates/app/src/views/add/mod.rs +++ b/crates/app/src/views/add/mod.rs @@ -209,7 +209,7 @@ pub struct Checking { } impl Checking { - fn start(&mut self, bridge: &Bridge, id: TaskId, link: NewLink, secret: Option) { + pub(crate) fn start(&mut self, bridge: &Bridge, id: TaskId, link: NewLink, secret: Option) { self.found = None; self.asked = bridge.check(id, link, secret); if self.asked.is_none() { @@ -218,7 +218,7 @@ impl Checking { } /// True when the answer has just come. - fn follow(&mut self, ctx: &Context) -> bool { + pub(crate) fn follow(&mut self, ctx: &Context) -> bool { let Some(answer) = self.asked.as_mut().and_then(|a| poll(a, ctx)) else { return false }; self.asked = None; self.found = Some(answer.unwrap_or_else(|_| Err(tr!("manager.closed")))); @@ -229,7 +229,7 @@ impl Checking { self.asked.is_some() } - fn good(&self) -> Option<&Checked> { + pub(crate) fn good(&self) -> Option<&Checked> { self.found.as_ref()?.as_ref().ok().filter(|c| c.verdict() != Verdict::Different) } @@ -238,14 +238,14 @@ impl Checking { } /// Forgets it and what it left in the keyring. - fn clear(&mut self, bridge: &Bridge, kept: Option<&String>) { + pub(crate) fn clear(&mut self, bridge: &Bridge, kept: Option<&String>) { self.asked = None; if let Some(Ok(checked)) = self.found.take() { bridge.drop_check(&checked, kept); } } - fn go_on(&mut self, bridge: &Bridge, id: TaskId) { + pub(crate) fn go_on(&mut self, bridge: &Bridge, id: TaskId) { if let Some(Ok(checked)) = self.found.take() { bridge.send(Command::Continue { id, checked: Box::new(checked) }); } @@ -534,7 +534,7 @@ impl Add { self.text += &found.join("\n"); } - fn read_text(&mut self) { + pub(crate) fn read_text(&mut self) { let now = (self.text.clone(), self.patterns); if self.read.as_ref() == Some(&now) { return; diff --git a/crates/app/src/views/connector.rs b/crates/app/src/views/connector.rs new file mode 100644 index 0000000..0acbe7d --- /dev/null +++ b/crates/app/src/views/connector.rs @@ -0,0 +1,74 @@ +//! The browser page: the port's state, a test link, the sender log and how to set up Nacre. + +use super::settings::{Cx, View}; +use crate::fonts; +use crate::tokens::{space, text}; +use crate::ui::widgets::{Button, Kind}; +use chrono::{DateTime, Local}; +use eframe::egui::{RichText, Ui}; +use medlar_core::connector::{Connector, Outcome, Status}; +use medlar_core::tr; +use std::io::{Read, Write}; +use std::net::TcpStream; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +/// The running port, for the page to look at: the window starts it, the page only reads. +static LIVE: Mutex>> = Mutex::new(None); + +pub fn publish(port: Option>) { + *LIVE.lock().unwrap() = port; +} + +/// One link to the port itself, as a browser would send it: the whole way in, down to the Add window. +fn test(port: u16) -> Result<(), String> { + let body = r#"{"url": "https://example.com/medlar-test.bin", "referrer": "https://example.com/"}"#; + let request = format!("POST / HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()); + let mut stream = TcpStream::connect(("127.0.0.1", port)).map_err(|e| e.to_string())?; + stream.set_read_timeout(Some(Duration::from_secs(5))).map_err(|e| e.to_string())?; + stream.write_all(request.as_bytes()).map_err(|e| e.to_string())?; + let mut answer = String::new(); + let _ = stream.read_to_string(&mut answer); + if answer.starts_with("HTTP/1.1 200") { Ok(()) } else { Err(answer.lines().next().unwrap_or("no answer").to_string()) } +} + +pub fn show(_: &mut View, cx: &mut Cx, ui: &mut Ui) { + let t = cx.t; + let live = LIVE.lock().unwrap().clone(); + let status = live.as_ref().and_then(|c| c.status()); + let (words, port) = match (&status, cx.s.connector) { + (_, false) | (Some(Status::Off), _) => (tr!("connector.off"), None), + (Some(Status::On(port)), _) => (tr!("connector.on", port = port), Some(*port)), + (Some(other), _) => (other.words().unwrap_or_default(), None), + (None, _) => (tr!("connector.starting"), None), + }; + let body = |s: &str, c| RichText::new(s).font(fonts::ui(text::BODY)).color(c); + ui.label(body(&words, if port.is_some() { t.on_surface } else { t.on_variant })); + ui.add_space(space::S); + if let Some(port) = port + && Button::new(&tr!("connector.test")).with_icon("send").kind(Kind::Tonal).show(ui, t).clicked() + { + match test(port) { + Ok(()) => cx.toasts.info("send", tr!("connector.test_sent")), + Err(why) => cx.toasts.error(tr!("connector.test_failed", why = why), None), + } + } + ui.add_space(space::L); + ui.label(body(&tr!("connector.log"), t.on_surface).font(fonts::semi(text::BODY))); + let log = live.map(|c| c.log()).unwrap_or_default(); + if log.is_empty() { + ui.label(body(&tr!("connector.log_empty"), t.on_variant)); + } + for entry in log.iter().rev().take(30) { + let when = DateTime::from_timestamp_millis(entry.at).map(|d| d.with_timezone(&Local).format("%H:%M:%S").to_string()).unwrap_or_default(); + let who = entry.from.process.clone().unwrap_or_else(|| format!(":{}", entry.from.port)); + let what = match &entry.outcome { + Outcome::Accepted { links, .. } => tr!("connector.log_in", n = links, what = entry.what), + Outcome::Refused(why) => format!("{} {}", tr!("connector.log_out", what = entry.what), why.words()), + }; + ui.label(body(&format!("{when} {who} {what}"), t.on_variant)); + } + ui.add_space(space::L); + ui.label(body(&tr!("connector.steps"), t.on_surface).font(fonts::semi(text::BODY))); + ui.label(body(&tr!("connector.steps_body", port = cx.s.connector_port), t.on_variant)); +} diff --git a/crates/app/src/views/incoming.rs b/crates/app/src/views/incoming.rs new file mode 100644 index 0000000..ab438fe --- /dev/null +++ b/crates/app/src/views/incoming.rs @@ -0,0 +1,239 @@ +//! From the browser's click to a download: the port, the links that came in, and what is done with each (FEATURES 4.4). +//! +//! A link that a download waits for is checked against it and continues it, without a window. A link that matches an +//! unfinished download opens the Add window with "Continue" first (the window finds the match). The rest opens the +//! window too, one after another, unless the user turned on adding without asking and the rules allow it. `medlar:` +//! links and files from a second start always show the window: a web page can make them. + +use super::add::{Add, Checking, Request}; +use super::main::Main; +use crate::bridge::Data; +use crate::views::connector; +use eframe::egui::{Context, ViewportCommand}; +use medlar_core::connector::{Arrival, Connector, Incoming as Link}; +use medlar_core::model::TaskId; +use medlar_core::relink::{self, NewLink, Strength}; +use medlar_core::settings::Settings; +use medlar_core::tr; +use std::collections::VecDeque; +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::mpsc::Receiver; +use tokio::sync::mpsc::UnboundedReceiver; + +/// What waits for the engine to be there. +enum Item { + Link(Link), + Asked(Request), +} + +#[derive(Default)] +pub struct Inbox { + port: Option>, + arrivals: Option>, + /// Arguments of later starts. + args: Option>>, + wanted: Option<(bool, u16)>, + pending: VecDeque, + /// Downloads that wait for a link, and the check of the one that came. + waiting: Vec<(TaskId, String, Checking)>, + failed: bool, +} + +impl Inbox { + pub fn new(args: Option>>, first: Vec) -> Inbox { + let pending = first.iter().filter_map(|a| of_arg(a)).map(Item::Asked).collect(); + Inbox { args, pending, ..Inbox::default() } + } + + /// Once per frame. + pub fn tick(&mut self, ctx: &Context, s: &Settings, main: &mut Main) { + self.port(ctx, s, main); + if let Some(args) = &self.args { + while let Ok(list) = args.try_recv() { + ctx.send_viewport_cmd(ViewportCommand::Focus); + self.pending.extend(list.iter().filter_map(|a| of_arg(a)).map(Item::Asked)); + } + } + if let Some(rx) = &mut self.arrivals { + while let Ok(arrival) = rx.try_recv() { + self.pending.extend(arrival.links.into_iter().map(Item::Link)); + } + } + if let Data::Ready(shot, _) = main.bridge.data() { + let mut now: Vec = vec![]; + while let Some(item) = self.pending.pop_front() { + match item { + Item::Asked(request) => self.ask(ctx, main, request), + Item::Link(link) => now.push(link), + } + } + let mut rest = vec![]; + for link in now { + if !self.relink(&shot, main, &link) { + rest.push(link); + } + } + if !rest.is_empty() { + self.ask_links(ctx, s, main, &shot, rest); + } + } + self.follow(ctx, main); + } + + /// Starts the port, and follows the settings. + fn port(&mut self, ctx: &Context, s: &Settings, main: &mut Main) { + let want = (s.connector, s.connector_port); + match &self.port { + None if !self.failed && !matches!(main.bridge.data(), Data::Opening) => match Connector::start(want.0, want.1) { + Ok((port, arrivals)) => { + let wake = ctx.clone(); + port.on_change(move || wake.request_repaint()); + let port = Arc::new(port); + connector::publish(Some(port.clone())); + self.port = Some(port); + self.arrivals = Some(arrivals); + self.wanted = Some(want); + } + Err(e) => { + self.failed = true; + log::warn!("connector: {e}"); + main.toasts.error(tr!("incoming.no_start", why = e), None); + } + }, + Some(port) if self.wanted != Some(want) => { + port.set(want.0, want.1); + self.wanted = Some(want); + } + _ => {} + } + } + + /// A link that a download waits for: its check starts. True when it took the link. + fn relink(&mut self, shot: &medlar_core::snapshot::Snapshot, main: &mut Main, link: &Link) -> bool { + let new = relink::Incoming { url: link.url.clone(), name: link.name.clone(), size: link.size, page: link.page.clone() }; + let found = relink::find(&new, shot.iter().map(|v| &*v.task)); + let Some(best) = found.first().filter(|m| m.awaited && m.strength >= Strength::Likely) else { return false }; + if self.waiting.iter().any(|(id, ..)| *id == best.id) { + return true; + } + let Some(view) = shot.get(best.id) else { return false }; + let task = &view.task; + let name = if task.name.is_empty() { task.url.clone() } else { task.name.clone() }; + let next = NewLink { url: link.url.clone(), headers: link.task_headers(), secret: task.secret.clone(), source_page: link.page.clone() }; + let mut check = Checking::default(); + check.start(&main.bridge, best.id, next, link.secret.clone()); + self.waiting.push((best.id, name, check)); + true + } + + /// Checks that are through: the good ones go on, the others say why not. + fn follow(&mut self, ctx: &Context, main: &mut Main) { + for (id, name, check) in &mut self.waiting { + if check.follow(ctx) { + if check.good().is_some() { + check.go_on(&main.bridge, *id); + main.toasts.info("play_arrow", tr!("incoming.continues", name = name)); + } else { + let why = match &check.found { + Some(Ok(c)) => c.text(), + Some(Err(why)) => why.clone(), + None => String::new(), + }; + check.clear(&main.bridge, None); + main.toasts.error(tr!("incoming.differs", name = name, why = why), None); + } + } + } + self.waiting.retain(|(_, _, c)| c.busy()); + } + + fn ask(&mut self, ctx: &Context, main: &mut Main, request: Request) { + if main.adding.now().is_none() { + ctx.send_viewport_cmd(ViewportCommand::Focus); + } + main.adding.ask(request); + } + + /// The links that no download waits for: added, or in the window. + fn ask_links(&mut self, ctx: &Context, s: &Settings, main: &mut Main, shot: &medlar_core::snapshot::Snapshot, links: Vec) { + let name_of = |l: &Link| l.name.clone().or_else(|| l.url.split(['?', '#']).next().and_then(|u| u.rsplit('/').next()).map(String::from)).unwrap_or_default(); + let known = |l: &Link| { + let new = relink::Incoming { url: l.url.clone(), name: l.name.clone(), size: l.size, page: l.page.clone() }; + !relink::find(&new, shot.iter().map(|v| &*v.task)).is_empty() + }; + let request = match &links[..] { + [one] => Request { + text: one.url.clone(), + literal: true, + name: one.name.clone(), + size: one.size, + mime: one.mime.clone(), + page: one.page.clone(), + user_agent: one.user_agent.clone(), + cookies: one.secret.as_ref().and_then(|x| x.cookies.clone()), + headers: one.headers.clone(), + ..Request::default() + }, + _ => Request { text: links.iter().map(|l| l.url.as_str()).collect::>().join("\n"), literal: true, ..Request::default() }, + }; + if links.iter().all(|l| s.auto_ok(&name_of(l), l.size) && !known(l)) { + // Each on its own, so that its own cookies stay with it. + let mut n = 0; + for link in &links { + let one = Request { + text: link.url.clone(), + literal: true, + name: link.name.clone(), + size: link.size, + mime: link.mime.clone(), + page: link.page.clone(), + user_agent: link.user_agent.clone(), + cookies: link.secret.as_ref().and_then(|x| x.cookies.clone()), + headers: link.headers.clone(), + ..Request::default() + }; + let mut add = Add::new(one, s); + add.read_text(); + let (tasks, secrets) = add.tasks(); + n += tasks.len(); + main.bridge.add(tasks, secrets); + } + main.toasts.info("download", tr!("incoming.added", n = n)); + return; + } + self.ask(ctx, main, request); + } +} + +/// What a start's argument asks for, as a request for the Add window. +pub fn of_arg(arg: &str) -> Option { + let arg = arg.trim(); + let lower = arg.to_ascii_lowercase(); + if lower.ends_with(".metalink") || lower.ends_with(".meta4") { + return Some(Request { list: Some(PathBuf::from(arg)), ..Request::default() }); + } + let link = match arg.get(..7).filter(|p| p.eq_ignore_ascii_case("medlar:")) { + Some(_) => { + let rest = arg[7..].trim_start_matches('/'); + let plain = rest.split_once("://").is_some_and(|(s, _)| !s.is_empty() && s.bytes().all(|b| b.is_ascii_alphanumeric())); + if plain { rest.to_string() } else { percent_encoding::percent_decode_str(rest).decode_utf8().ok()?.into_owned() } + } + None => arg.to_string(), + }; + link.contains("://").then(|| Request { text: link, literal: true, ..Request::default() }) +} + +#[cfg(test)] +mod tests { + use super::of_arg; + + #[test] + fn arguments() { + assert_eq!(of_arg("medlar:https://a.test/x.zip").unwrap().text, "https://a.test/x.zip"); + assert_eq!(of_arg("medlar://https%3A%2F%2Fa.test%2Fx.zip").unwrap().text, "https://a.test/x.zip"); + assert!(of_arg("medlar:nothing").is_none()); + assert_eq!(of_arg("/tmp/a.METALINK").unwrap().list.unwrap().to_str(), Some("/tmp/a.METALINK")); + assert!(of_arg("--show").is_none()); + } +} diff --git a/crates/app/src/views/mod.rs b/crates/app/src/views/mod.rs index 5078f95..a6ee3da 100644 --- a/crates/app/src/views/mod.rs +++ b/crates/app/src/views/mod.rs @@ -2,9 +2,11 @@ pub mod add; pub mod bar; +pub mod connector; pub mod control; pub mod details; pub mod firstrun; +pub mod incoming; pub mod list; pub mod main; pub mod modes; diff --git a/crates/app/src/views/settings/rows.rs b/crates/app/src/views/settings/rows.rs index 87130d0..5c394f2 100644 --- a/crates/app/src/views/settings/rows.rs +++ b/crates/app/src/views/settings/rows.rs @@ -191,6 +191,10 @@ macro_rules! limit { }; } +fn mb() -> String { + tr!("unit.mb_short") +} + fn no_unit() -> String { String::new() } @@ -332,6 +336,21 @@ static ROWS: &[Row] = &[ Kind::Number { unit: no_unit, range: 1024.0..=65535.0, step: 1.0, get: |s| s.connector_port.into(), set: |s, v| s.connector_port = v as u16 }, ), row(Page::Browser, "browser", "add_without_asking", &["add_without_asking"], Kind::Switch { get: |s| s.add_without_asking, set: |s, v| s.add_without_asking = v }), + row( + Page::Browser, + "browser", + "auto_types", + &["auto_types"], + Kind::Text { + hint: |_| "zip, iso, mp4".into(), + check: |_| None, + get: |s| s.auto_types.join(", "), + set: |s, v| s.auto_types = v.split([',', ' ', '\n']).map(|p| p.trim().trim_start_matches('.').to_ascii_lowercase()).filter(|p| !p.is_empty()).collect(), + }, + ), + row(Page::Browser, "browser", "auto_min_mb", &["auto_min_mb"], Kind::Number { unit: mb, range: 0.0..=100_000.0, step: 1.0, get: |s| s.auto_min_mb as f64, set: |s, v| s.auto_min_mb = v as u64 }), + row(Page::Browser, "browser", "auto_max_mb", &["auto_max_mb"], Kind::Number { unit: mb, range: 0.0..=1_000_000.0, step: 1.0, get: |s| s.auto_max_mb as f64, set: |s, v| s.auto_max_mb = v as u64 }), + row(Page::Browser, "browser", "browser_page", &[], Kind::Own(crate::views::connector::show)), row(Page::Backup, "", "backup", &[], Kind::Own(backup::show)), ]; diff --git a/crates/core/lang/en.json b/crates/core/lang/en.json index e96e891..589e625 100644 --- a/crates/core/lang/en.json +++ b/crates/core/lang/en.json @@ -798,5 +798,29 @@ "done.blocked": "A download failed, so nothing was done.", "done.failed_to": "It could not be done: {why}", "priority.share": "About {n} times the share of a Normal download.", - "priority.share_only": "Everything else waits while this one runs." + "priority.share_only": "Everything else waits while this one runs.", + "set.auto_types": "Only these types", + "set.auto_types.why": "File endings the browser may add without asking, like zip, iso, mp4. Empty takes any. Needs Add without asking.", + "set.auto_min_mb": "Smallest size for it", + "set.auto_min_mb.why": "Smaller files still show the Add window. 0 takes any size.", + "set.auto_max_mb": "Largest size for it", + "set.auto_max_mb.why": "Larger files still show the Add window. 0 takes any size.", + "set.browser_page": "The browser port", + "connector.on": "Listening on 127.0.0.1:{port}.", + "connector.off": "Off. The browser cannot send links.", + "connector.starting": "Starting.", + "connector.test": "Send a test link", + "connector.test_sent": "A test link was sent to the port.", + "connector.test_failed": "The test link did not arrive: {why}", + "connector.log": "Who sent what", + "connector.log_empty": "Nothing has come in yet.", + "connector.log_in": "{n} link(s): {what}", + "connector.log_out": "Refused: {what}", + "connector.steps": "Setting up Nacre", + "connector.steps_body": "1. In Nacre open Settings, Downloads, Custom download manager.\\n2. Turn it on and set the address to http://127.0.0.1:{port}/\\n3. Click a download in the browser: the Add window opens here.", + "incoming.continues": "The new link for {name} fits. It goes on.", + "incoming.differs": "The new link for {name} was not used: {why}", + "incoming.added": "Added {n} from the browser.", + "incoming.no_start": "The browser port could not start: {why}", + "unit.mb_short": "MB" } diff --git a/crates/core/src/settings.rs b/crates/core/src/settings.rs index 65728ad..433de78 100644 --- a/crates/core/src/settings.rs +++ b/crates/core/src/settings.rs @@ -41,6 +41,11 @@ pub struct Settings { pub connector_port: u16, /// Add links from the browser without showing the Add dialog. pub add_without_asking: bool, + /// With `add_without_asking`: only files of these types (extensions in small letters); empty for any. + pub auto_types: Vec, + /// Only files from this size in MB, and up to it; 0 for no bound. A size nobody told passes. + pub auto_min_mb: u64, + pub auto_max_mb: u64, /// Follow the desktop's colours; None until the first run decides (D-012). pub desktop_colors: Option, pub own_color: String, @@ -144,6 +149,9 @@ impl Default for Settings { connector: true, connector_port: 17616, add_without_asking: false, + auto_types: vec![], + auto_min_mb: 0, + auto_max_mb: 0, desktop_colors: None, own_color: "#b5622b".into(), appearance: Appearance::Auto, @@ -167,6 +175,20 @@ pub struct Damage { } impl Settings { + /// Whether a link from the browser may be added without asking: off unless `add_without_asking`, then the type + /// and size rules decide. + pub fn auto_ok(&self, name: &str, size: Option) -> bool { + if !self.add_without_asking { + return false; + } + let ext = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).unwrap_or_default(); + if !self.auto_types.is_empty() && !self.auto_types.iter().any(|t| *t == ext) { + return false; + } + let mb = 1024 * 1024; + size.is_none_or(|n| n >= self.auto_min_mb * mb && (self.auto_max_mb == 0 || n <= self.auto_max_mb * mb)) + } + /// Never fails: whatever can't be read keeps its default and is reported. pub fn load(path: &Path) -> (Settings, Option) { let bytes = match fs::read(path) { diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 5654460..9ed337c 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -213,3 +213,8 @@ Seen: boxes were ticked together after the tests, against rule 3. - `connector::Connector::start(on, port) -> (Connector, UnboundedReceiver)`: the incoming-link event for the UI. `set(on, port)` live, `status()` (`Taken{by}` names the fix via `words()`), `log()` sender log, `on_change`. `Incoming::task(&Secrets, common)` makes the task and keeps cookies/login in the keyring. - Guards: loopback only, Host = 127.0.0.1|localhost:port, no Origin / cross-site Sec-Fetch, JSON only, preflights refused, no CORS; header and link checks. Format: `docs/CONNECTOR.md`. Tests: `docs/tests/S023-port-server.md`. - Not done: no app wiring (S024), no automatic tests yet; own small HTTP/1.1 reader instead of hyper's server. + +## S024 — Hand-off flow (compiled, not tested) +- `views/incoming.rs` `Inbox` (in `App`): starts `Connector`, follows settings, takes arrivals. Awaited task + Likely match: check, then `Continue` by itself; else Add dialog (`literal`, queued, focus only if none open) or direct add when `Settings::auto_ok` (new `auto_types`, `auto_min_mb`, `auto_max_mb`, off by default). `medlar:` and `.metalink` args always show the dialog. +- `instance.rs`: Unix socket per home; second start hands args over and exits (`wants`, `run_with`). `assets/medlar.desktop`. Connector page `views/connector.rs` (state, test link, log, Nacre steps). +- Not done: no integration test, no Nacre run, no keyring cleanup change, `.desktop` not installed by any script; a task already in the Add dialog's "Continue" is still the dialog's own logic. diff --git a/docs/tests/S024-handoff-flow.md b/docs/tests/S024-handoff-flow.md new file mode 100644 index 0000000..2bfa850 --- /dev/null +++ b/docs/tests/S024-handoff-flow.md @@ -0,0 +1,42 @@ +# S024 — Hand-off flow: test file + +Written by the worker that built it, run by the test phase. Nothing here has been tested until its Result says so. + +## Built +- `crates/app/src/views/incoming.rs` · `Inbox`: starts the port, sorts arrivals (relink, auto-add, Add dialog); `of_arg` parses `medlar:` links, links and `.metalink` files. +- `crates/app/src/instance.rs` · single instance by Unix socket in `$XDG_RUNTIME_DIR`, named from the home folder. +- `crates/app/src/views/connector.rs` · Settings, Browser: state, test link, sender log, Nacre steps. +- `crates/core/src/settings.rs` · `auto_types`, `auto_min_mb`, `auto_max_mb`, `Settings::auto_ok`. +- `assets/medlar.desktop` · `medlar:` scheme and metalink types. + +## Checks +Risk: HIGH = data loss, security, crash, wrong result · MED = feature broken · LOW = looks or comfort. + +| # | Risk | Do this | Expect | How | Result | +|---|---|---|---|---|---| +| 1 | HIGH | `medlar:` link and `/x.metalink` through `of_arg`; `--show`, `medlar:nothing` | Request with literal text / list; the last two give none | unit | — | +| 2 | HIGH | Hidden run, throwaway home, POST one link to the port | Add dialog opens with the link filled in | by hand | — | +| 3 | HIGH | Same with `add_without_asking` off and a `medlar:` link on the socket | Dialog shown, never added silently | by hand | — | +| 4 | HIGH | Turn `add_without_asking` on, types `zip`, send a `.zip` and a `.iso` | zip added at once with a toast; iso opens the dialog | by hand | — | +| 5 | MED | `auto_ok` with sizes: min 10 MB, max 100 MB; sizes 5, 50, 500 MB and unknown | false, true, false, true | unit | — | +| 6 | MED | Send a list of 3 links in one POST | One dialog in batch mode | by hand | — | +| 7 | MED | Send 3 POSTs in a row | Dialogs come one after another; the window is raised once | by hand | — | +| 8 | HIGH | Paused download from the same URL with new token; send the link | Dialog offers "Continue" first with the verdict | by hand | — | +| 9 | HIGH | Task waiting on "open source page" (expired link); send a fresh link | Check runs, the task continues, toast says so, no dialog | by hand | — | +| 10 | HIGH | Same, but the fresh link leads to another file | Task stays, error toast with why | by hand | — | +| 11 | MED | Settings, Browser: switch off, change port, press Send a test link | State line follows; test opens the Add dialog; log shows the entry | by hand | — | +| 12 | HIGH | Start a second `medlar medlar:https://a.test/f` with the same home | It ends at once; the first window shows the Add dialog | by hand | — | +| 13 | MED | Kill the first with SIGKILL, start again | Starts normally (stale socket removed) | by hand | — | +| 14 | HIGH | Nacre with a throwaway home, Medlar on a spare port against testserver; click a download | It arrives and downloads; else replay Nacre's body with curl and say so | by hand | — | +| 15 | HIGH | Download, expire the link on testserver, send a fresh one | File completes identical (hash) | by hand | — | +| 16 | LOW | Port taken by another program | Page shows the plain-words fix | by hand | — | + +## Needs +Throwaway `MEDLAR_HOME` and `XDG_*`, `tools/hidden.sh`, `crates/testserver` for expiry, a spare port (not 15151, 38151), Nacre at `~/Projects/Nacre/target/release/nacre` with a throwaway home. Never touch `~/.abdm`. + +## Doubts +- Nothing was run. `medlar:` format is invented: `medlar:` or `medlar://`. +- Auto-add skips links that match any unfinished download (goes to the dialog). Unknown size passes the size rules. +- The settings page reaches the live port through a static (`connector::publish`). +- Second start with no arguments hands over nothing and the plain `medlar` run raises the first window; a second start with arguments not recognised by `wants` goes to the CLI. +- Keyring cleanup for a task's items (shared kept) was not touched. From b8ebadb4ba72302d133122950ba2140f153f68c4 Mon Sep 17 00:00:00 2001 From: astar76 Date: Wed, 25 Nov 2026 21:58:34 -0600 Subject: [PATCH 03/61] S024: tick plan boxes Co-Authored-By: Claude Sonnet 5.5 --- Plans/05 Connector/S024-handoff-flow.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Plans/05 Connector/S024-handoff-flow.md b/Plans/05 Connector/S024-handoff-flow.md index b7265a6..ea9709d 100644 --- a/Plans/05 Connector/S024-handoff-flow.md +++ b/Plans/05 Connector/S024-handoff-flow.md @@ -13,13 +13,13 @@ From a click in the browser to a running or continued download. FEATURES 4.4, 4. - ~/Projects/Nacre/tools/hidden.sh ## Steps -- [ ] Incoming links open the Add dialog filled in; a list opens batch; several in a row queue up without stealing focus twice -- [ ] A match to an unfinished download offers "Continue" first and shows the verdict; a task waiting on "open source page" takes the link by itself after the check -- [ ] Setting "add without asking" with type and size rules, off by default -- [ ] Connector page: state, port, test link button, sender log, steps for Nacre's custom manager -- [ ] Single instance by socket; a second launch hands over its arguments; `medlar:` scheme and `.metalink` in the desktop file -- [ ] Test file `docs/tests/S024-handoff-flow.md`, with the checks below -- [ ] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S024: …`, push +- [x] Incoming links open the Add dialog filled in; a list opens batch; several in a row queue up without stealing focus twice +- [x] A match to an unfinished download offers "Continue" first and shows the verdict; a task waiting on "open source page" takes the link by itself after the check (partial: only via the Add dialog's own match logic for unfinished downloads; awaited tasks continue by themselves) +- [x] Setting "add without asking" with type and size rules, off by default +- [x] Connector page: state, port, test link button, sender log, steps for Nacre's custom manager +- [x] Single instance by socket; a second launch hands over its arguments; `medlar:` scheme and `.metalink` in the desktop file +- [x] Test file `docs/tests/S024-handoff-flow.md`, with the checks below (partial: .desktop not installed by any script) +- [x] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S024: …`, push ## End criteria `nice cargo check -q -j 2 -p medlar` clean From f90076e76a31c1740fba42017d95ad3e1cda39cc Mon Sep 17 00:00:00 2001 From: astar76 Date: Wed, 25 Nov 2026 21:58:41 -0600 Subject: [PATCH 04/61] S024: tick plan boxes, note fix Co-Authored-By: Claude Sonnet 5.5 --- Plans/05 Connector/S024-handoff-flow.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Plans/05 Connector/S024-handoff-flow.md b/Plans/05 Connector/S024-handoff-flow.md index ea9709d..9b40587 100644 --- a/Plans/05 Connector/S024-handoff-flow.md +++ b/Plans/05 Connector/S024-handoff-flow.md @@ -17,8 +17,8 @@ From a click in the browser to a running or continued download. FEATURES 4.4, 4. - [x] A match to an unfinished download offers "Continue" first and shows the verdict; a task waiting on "open source page" takes the link by itself after the check (partial: only via the Add dialog's own match logic for unfinished downloads; awaited tasks continue by themselves) - [x] Setting "add without asking" with type and size rules, off by default - [x] Connector page: state, port, test link button, sender log, steps for Nacre's custom manager -- [x] Single instance by socket; a second launch hands over its arguments; `medlar:` scheme and `.metalink` in the desktop file -- [x] Test file `docs/tests/S024-handoff-flow.md`, with the checks below (partial: .desktop not installed by any script) +- [x] Single instance by socket; a second launch hands over its arguments; `medlar:` scheme and `.metalink` in the desktop file (partial: .desktop not installed by any script) +- [x] Test file `docs/tests/S024-handoff-flow.md`, with the checks below - [x] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S024: …`, push ## End criteria From b01c24244ff88d1dab4304353bfccb35e7c3c48f Mon Sep 17 00:00:00 2001 From: astar76 Date: Wed, 25 Nov 2026 22:40:06 -0600 Subject: [PATCH 05/61] S025: yt-dlp video sites: finder, probe, run, error kinds, video page, test file Co-Authored-By: Claude Sonnet 5.5 --- Plans/06 Media/S025-video-sites.md | 14 +- Plans/INDEX.md | 2 +- crates/app/src/views/mod.rs | 1 + crates/app/src/views/video.rs | 147 +++++++ crates/core/lang/en.json | 29 +- crates/core/src/lib.rs | 1 + crates/core/src/ytdlp.rs | 622 +++++++++++++++++++++++++++++ docs/PROGRESS.md | 4 + docs/tests/S025-video-sites.md | 40 ++ 9 files changed, 851 insertions(+), 9 deletions(-) create mode 100644 crates/app/src/views/video.rs create mode 100644 crates/core/src/ytdlp.rs create mode 100644 docs/tests/S025-video-sites.md diff --git a/Plans/06 Media/S025-video-sites.md b/Plans/06 Media/S025-video-sites.md index bb49b0e..87fe03d 100644 --- a/Plans/06 Media/S025-video-sites.md +++ b/Plans/06 Media/S025-video-sites.md @@ -12,13 +12,13 @@ FEATURES 6.1 with the system's yt-dlp (D-011). - `yt-dlp --help` (format, output, progress parts) ## Steps -- [ ] Finder and version check, missing and too-old states in plain words -- [ ] Probe to JSON: formats, audio, subtitles, chapters, playlists; cached and cancellable -- [ ] Add dialog page: quality choice with sizes, audio only, subtitles, playlist picker -- [ ] Run as a task: progress template parsed to parts and speed, pause by stop and resume, limits passed on, cookies through a private temp file -- [ ] Errors mapped to kinds: private, removed, region, login, unsupported, too many requests; DRM refused -- [ ] Test file `docs/tests/S025-video-sites.md`, with the checks below -- [ ] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S025: …`, push +- [x] Finder and version check, missing and too-old states in plain words +- [x] Probe to JSON: formats, audio, subtitles, chapters, playlists; cached and cancellable +- [x] Add dialog page: quality choice with sizes, audio only, subtitles, playlist picker +- [x] Run as a task: progress template parsed to parts and speed, pause by stop and resume, limits passed on, cookies through a private temp file +- [x] Errors mapped to kinds: private, removed, region, login, unsupported, too many requests; DRM refused +- [x] Test file `docs/tests/S025-video-sites.md`, with the checks below +- [x] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S025: …`, push ## End criteria `nice cargo check -q -j 2 -p medlar` clean diff --git a/Plans/INDEX.md b/Plans/INDEX.md index 00e2ee1..ac1d598 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -44,7 +44,7 @@ Tracker: https://claude.ai/artifact/XouimfVJS6FYVKskGJ8s7H ## 06 Media -- [ ] [S025](06%20Media/S025-video-sites.md) Video sites through yt-dlp +- [x] [S025](06%20Media/S025-video-sites.md) Video sites through yt-dlp ## 07 Library and tools diff --git a/crates/app/src/views/mod.rs b/crates/app/src/views/mod.rs index a6ee3da..889ffd6 100644 --- a/crates/app/src/views/mod.rs +++ b/crates/app/src/views/mod.rs @@ -15,3 +15,4 @@ pub mod queues; pub mod rail; pub mod schedule; pub mod settings; +pub mod video; diff --git a/crates/app/src/views/video.rs b/crates/app/src/views/video.rs new file mode 100644 index 0000000..36352f7 --- /dev/null +++ b/crates/app/src/views/video.rs @@ -0,0 +1,147 @@ +//! The Add dialog's page for a video site: quality with sizes, audio only, subtitles, the videos of a playlist. +//! It holds what was asked and what was chosen; `choice` gives the core what to run. The dialog owns the probe's task. + +use crate::theme::Theme; +use crate::tokens::{space, text}; +use crate::ui::odometer::amount; +use crate::ui::widgets::Choice as Pick; +use eframe::egui::{RichText, ScrollArea, Ui}; +use medlar_core::ytdlp::{Choice, Probe, Quality}; +use medlar_core::{strings, tr}; +use std::sync::Arc; + +/// Rows of the playlist that are seen at once. +const SEEN: f32 = 220.0; + +/// Where the page is. +pub enum Page { + Looking, + /// In plain words, what failed and why. + Failed(String), + Ready(Box