From b993812f4002ed409e72c97496b17a24ddb87cf8 Mon Sep 17 00:00:00 2001 From: th33raphat Date: Thu, 12 Nov 2026 02:07:06 +0700 Subject: [PATCH] refactor(host): the streaming core is a library too The Android app will share its own screen (a Mac shows it), so it needs the host's sessions, signaling and pairing. crates/host is now lib + bin: lib.rs exports session, signaling, pairing, screens, timing, probe_page, config and platform, plus start(HostOptions) -> Host with the wiring main.rs did inline (session thread, pairing store, signaling listener and web port, the address to show). main.rs keeps what is the Mac's: flags, AppPaths, the menu bar, the code dialog, the updater and the viewer. Signaling's messages to receivers name the host's kind ("Pair this device with the Mac first") from HostOptions.kind instead of a fixed "Mac". No behaviour change on the Mac. A taken port is still the "already running" dialog: start() marks that error with PortInUse. Checked: 72 tests pass; the lib builds for aarch64-linux-android; the binary serves /hello and refuses an unpaired device as before. --- crates/host/src/lib.rs | 99 ++++++++++++++++++++++++++++++ crates/host/src/main.rs | 113 ++++++++++++----------------------- crates/host/src/signaling.rs | 24 +++++--- 3 files changed, 154 insertions(+), 82 deletions(-) create mode 100644 crates/host/src/lib.rs diff --git a/crates/host/src/lib.rs b/crates/host/src/lib.rs new file mode 100644 index 0000000..f33bc10 --- /dev/null +++ b/crates/host/src/lib.rs @@ -0,0 +1,99 @@ +//! The host's streaming core, shared by the Mac menu bar app (`main.rs`) and +//! the Android app's "Share this screen": WebRTC sessions, signaling, pairing +//! and the layout map. A frontend brings its own `Platform` (capture and +//! encode) and its own way to show the pairing code, then calls [`start`]. + +pub mod config; +pub mod pairing; +pub mod platform; +pub mod probe_page; +pub mod screens; +pub mod session; +pub mod signaling; +pub mod timing; + +use std::net::{IpAddr, SocketAddr}; +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; + +use anyhow::Result; + +/// Every usable local IPv4 address, the main one first, loopback last, so +/// loopback and LAN receivers both connect. +pub fn lan_ips() -> Vec { + let mut ips: Vec = vec![]; + if let Ok(ip) = local_ip_address::local_ip() { + ips.push(ip); + } + if let Ok(list) = local_ip_address::list_afinet_netifas() { + for (_, ip) in list { + if ip.is_ipv4() && !ips.contains(&ip) && !ip.is_loopback() && !ip.is_unspecified() { + ips.push(ip); + } + } + } + ips.push(IpAddr::from([127, 0, 0, 1])); + ips +} + +/// What a frontend decides; [`start`] does the rest. +pub struct HostOptions { + pub platform: Arc, + /// Signaling listener. + pub addr: SocketAddr, + /// Second port for the receiver page (80 on the Mac), 0 = none. + pub web_port: u16, + pub host_name: String, + /// What receivers are told this host is ("Mac", "tablet"). + pub kind: &'static str, + /// `advertise_ips` usually from [`lan_ips`]. + pub session: session::SessionConfig, + /// Effective switches, served at `/config`. + pub config: serde_json::Value, + pub log: Arc, + pub pairing_store: PathBuf, + /// Show or hide the pairing code. + pub notify: Box, +} + +/// A running host. Signaling serves on its own thread. +pub struct Host { + pub shared: Arc, + pub pairing: Arc, + /// What to type in a browser: the bare address when port 80 is ours, + /// otherwise address:port. + pub address: String, + pub session_thread: std::thread::JoinHandle<()>, +} + +/// The signaling port could not be had: most likely another Mullion has it. +#[derive(Debug)] +pub struct PortInUse(pub u16); + +impl std::fmt::Display for PortInUse { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "port {} is in use", self.0) + } +} + +pub fn start(o: HostOptions) -> Result { + let lan: Vec = o.session.advertise_ips.iter().filter(|ip| !ip.is_loopback()).map(|ip| ip.to_string()).collect(); + let (handle, session_thread) = session::start(o.session, o.platform, o.log)?; + let pairing = Arc::new(pairing::Pairing::load(Some(o.pairing_store), o.notify)); + let shared = Arc::new(session::SharedHandle(Mutex::new(handle))); + let signaling = signaling::Signaling::bind(o.addr, shared.clone(), o.host_name) + .map_err(|e| e.context(PortInUse(o.addr.port())))? + .with_kind(o.kind) + .with_config(o.config) + .with_lan_ips(lan.clone()) + .with_pairing(pairing.clone()) + .with_web_port(o.web_port); + let ip = lan.first().cloned().unwrap_or_else(|| "127.0.0.1".into()); + let address = match signaling.web_port() { + Some(80) => ip, + Some(p) => format!("{ip}:{p}"), + None => format!("{ip}:{}", o.addr.port()), + }; + std::thread::spawn(move || signaling.run()); + Ok(Host { shared, pairing, address, session_thread }) +} diff --git a/crates/host/src/main.rs b/crates/host/src/main.rs index cd39f4b..04c4418 100644 --- a/crates/host/src/main.rs +++ b/crates/host/src/main.rs @@ -6,21 +6,15 @@ //! `~/Library/Logs/Mullion`, settings from //! `~/Library/Application Support/Mullion/mullion.env`). -mod config; #[cfg(target_os = "macos")] mod menubar; -mod platform; -mod probe_page; -mod pairing; -mod screens; -mod session; -mod signaling; -mod timing; #[cfg(target_os = "macos")] mod update; #[cfg(target_os = "macos")] mod viewer; +use mullion_host::{config, pairing, platform, session, timing}; + use std::net::{IpAddr, SocketAddr}; use std::path::PathBuf; use std::sync::{Arc, Mutex}; @@ -222,19 +216,7 @@ fn run(args: Args, app: Option) -> Result<()> { let log = Arc::new(timing::TimingLog::new(Some(&log_path))?); info!("timing log: {}", log_path.display()); - // Advertise every usable local IP so loopback and LAN receivers both connect. - let mut ips: Vec = vec![]; - if let Ok(ip) = local_ip_address::local_ip() { - ips.push(ip); - } - if let Ok(list) = local_ip_address::list_afinet_netifas() { - for (_, ip) in list { - if ip.is_ipv4() && !ips.contains(&ip) && !ip.is_loopback() && !ip.is_unspecified() { - ips.push(ip); - } - } - } - ips.push("127.0.0.1".parse().unwrap()); + let ips = mullion_host::lan_ips(); let pipeline = platform::PipelineConfig { width: sw.width, @@ -246,69 +228,54 @@ fn run(args: Args, app: Option) -> Result<()> { ..Default::default() }; platform::set_arrange_enabled(sw.arrange); - let (handle, session_thread) = - session::start( - session::SessionConfig { - advertise_ips: ips.clone(), - pipeline, - extend: sw.extend, - display_grace: sw.display_grace(), - multi_session: sw.multi_session, - }, - platform, - log.clone(), - )?; // Pairing: receivers must be let in with a code shown here. Kept with the // app's other files, also when run from a terminal. - let pairing = Arc::new(pairing::Pairing::load( - Some(AppPaths::new().support.join("paired.json")), - Box::new({ - let in_app = app.is_some(); - move |n| match n { - pairing::Notice::Code { name, code } => { - println!("Pairing code for {name}: {} {}", &code[..3], &code[3..]); - #[cfg(target_os = "macos")] - if in_app { - let p = PAIRING.get().cloned(); - menubar::show_pair_code(name, code, Box::new(move || if let Some(p) = &p { p.cancel() })); - } + let in_app = app.is_some(); + let started = mullion_host::start(mullion_host::HostOptions { + platform, + addr: SocketAddr::new(args.bind, sw.port), + web_port: sw.web_port, + host_name: host_name.clone(), + kind: "Mac", + session: session::SessionConfig { + advertise_ips: ips, + pipeline, + extend: sw.extend, + display_grace: sw.display_grace(), + multi_session: sw.multi_session, + }, + config: serde_json::to_value(&sw)?, + log: log.clone(), + pairing_store: AppPaths::new().support.join("paired.json"), + notify: Box::new(move |n| match n { + pairing::Notice::Code { name, code } => { + println!("Pairing code for {name}: {} {}", &code[..3], &code[3..]); + #[cfg(target_os = "macos")] + if in_app { + let p = PAIRING.get().cloned(); + menubar::show_pair_code(name, code, Box::new(move || if let Some(p) = &p { p.cancel() })); } - pairing::Notice::Closed => { - #[cfg(target_os = "macos")] - if in_app { - menubar::close_pair_code(); - } + } + pairing::Notice::Closed => { + #[cfg(target_os = "macos")] + if in_app { + menubar::close_pair_code(); } } }), - )); - let _ = PAIRING.set(pairing.clone()); - - let addr = SocketAddr::new(args.bind, sw.port); - let shared = Arc::new(session::SharedHandle(Mutex::new(handle))); - let signaling = match signaling::Signaling::bind(addr, shared.clone(), host_name.clone()) { - Ok(s) => s, + }); + let mullion_host::Host { shared, pairing, address, session_thread } = match started { + Ok(h) => h, #[cfg(target_os = "macos")] - Err(e) if app.is_some() => menubar::fatal( + Err(e) if in_app && e.downcast_ref::().is_some() => menubar::fatal( "Mullion is already running", &format!("Port {} is in use, most likely by another Mullion (the app or tools/run-host.sh). Quit that one, then open Mullion again.\n\n{e:#}", sw.port), ), Err(e) => return Err(e), - } - .with_config(serde_json::to_value(&sw)?) - .with_lan_ips(ips.iter().filter(|ip| !ip.is_loopback()).map(|ip| ip.to_string()).collect()) - .with_pairing(pairing.clone()) - .with_web_port(sw.web_port); - let lan = ips.first().map(|ip| ip.to_string()).unwrap_or_else(|| "127.0.0.1".into()); - // What to type in a browser: the bare address when port 80 is ours, - // otherwise address:port, so whatever is shown or copied opens Mullion. - let address = match signaling.web_port() { - Some(80) => lan.clone(), - Some(p) => format!("{lan}:{p}"), - None => format!("{lan}:{}", sw.port), }; - info!("signaling on http://{lan}:{}/offer receiver: http://{address}/ config: /config", sw.port); + let _ = PAIRING.set(pairing.clone()); + info!("signaling on port {} receiver: http://{address}/ config: /config", sw.port); println!("Mullion host {host_name}: open http://{address} on the tablet."); let log_for_exit = log.clone(); @@ -318,11 +285,9 @@ fn run(args: Args, app: Option) -> Result<()> { std::process::exit(0); }); - std::thread::spawn(move || signaling.run()); - #[cfg(target_os = "macos")] if let Some(a) = &app { - use signaling::OfferHandler; + use mullion_host::signaling::OfferHandler; let first_launch = !a.support.join("welcomed").exists(); let _ = std::fs::create_dir_all(&a.support); let _ = std::fs::write(a.support.join("welcomed"), b""); diff --git a/crates/host/src/signaling.rs b/crates/host/src/signaling.rs index 92c9a23..8df5460 100644 --- a/crates/host/src/signaling.rs +++ b/crates/host/src/signaling.rs @@ -84,6 +84,8 @@ pub struct Signaling { web: Option, handler: Arc, host_name: String, + /// What receivers are told this host is: "Mac", "tablet". + kind: &'static str, config: serde_json::Value, lan_ips: Vec, pairing: Option>, @@ -126,7 +128,13 @@ impl Signaling { let server = Server::http(addr).map_err(|e| { anyhow!("Can't listen on port {}: {}. Pick another with --port.", addr.port(), e) })?; - Ok(Self { server, web: None, handler, host_name, config: serde_json::Value::Null, lan_ips: Vec::new(), pairing: None }) + Ok(Self { server, web: None, handler, host_name, kind: "Mac", config: serde_json::Value::Null, lan_ips: Vec::new(), pairing: None }) + } + + /// What receivers are told this host is ("Mac" by default). + pub fn with_kind(mut self, kind: &'static str) -> Self { + self.kind = kind; + self } /// Effective switches, served at `/config`. @@ -246,10 +254,10 @@ impl Signaling { sealed: Sealed, } let Ok(so) = serde_json::from_slice::(&body) else { - return respond_json(req, 401, &serde_json::json!({"pair": true, "error": "Pair this device with the Mac first."})); + return respond_json(req, 401, &serde_json::json!({"pair": true, "error": format!("Pair this device with the {} first.", self.kind)})); }; if !p.is_paired(&so.device) { - return respond_json(req, 401, &serde_json::json!({"pair": true, "error": "This Mac no longer knows this device. Pair again."})); + return respond_json(req, 401, &serde_json::json!({"pair": true, "error": format!("This {} no longer knows this device. Pair again.", self.kind)})); } match p.open_offer(&so.device, &so.sealed) { Ok((plain, ctx)) => (plain, Some(ctx)), @@ -313,7 +321,7 @@ impl Signaling { "/pair/confirm" => p.confirm(&field("pairing"), &field("mac"), &self.host_name).map(|c| serde_json::to_value(c).unwrap_or_default()), _ => match p.challenge(&field("device")) { Some(nonce) => Ok(serde_json::json!({ "nonce": nonce })), - None => return respond_json(req, 401, &serde_json::json!({"pair": true, "error": "Pair this device with the Mac first."})), + None => return respond_json(req, 401, &serde_json::json!({"pair": true, "error": format!("Pair this device with the {} first.", self.kind)})), }, }; match out { @@ -322,7 +330,7 @@ impl Signaling { Err(PairError::Gone) => respond_json(req, 410, &serde_json::json!({ "error": "No pairing in progress, or it expired." })), Err(PairError::Busy) => respond_json(req, 429, &serde_json::json!({ "error": "Another device is pairing. Try again in a few seconds." })), Err(PairError::WrongCode { left }) => respond_json(req, 403, &serde_json::json!({ "error": "Wrong code.", "left": left })), - Err(PairError::Full) => respond_json(req, 507, &serde_json::json!({ "error": "Too many paired devices. Forget some on the Mac." })), + Err(PairError::Full) => respond_json(req, 507, &serde_json::json!({ "error": format!("Too many paired devices. Forget some on the {}.", self.kind) })), } } ("/offer", _) => respond_status(req, 405, "Use POST"), @@ -351,7 +359,7 @@ impl Signaling { } ("/devices", Method::Get) => { if !self.allowed(&req, peer, &path, b"") { - return respond_status(req, 401, "Pair this device with the Mac first"); + return respond_status(req, 401, &format!("Pair this device with the {} first", self.kind)); } let body = serde_json::to_vec(&self.handler.devices())?; let resp = Response::from_data(body).with_header(Header::from_bytes("Content-Type", "application/json").unwrap()); @@ -359,7 +367,7 @@ impl Signaling { } ("/screens", Method::Get) => { if !self.allowed(&req, peer, &path, b"") { - return respond_status(req, 401, "Pair this device with the Mac first"); + return respond_status(req, 401, &format!("Pair this device with the {} first", self.kind)); } let view = self.handler.screens(); self.respond_screens(req, view) @@ -372,7 +380,7 @@ impl Signaling { return respond_status(req, 413, "Layout too large"); } if !self.allowed(&req, peer, &path, &body) { - return respond_status(req, 401, "Pair this device with the Mac first"); + return respond_status(req, 401, &format!("Pair this device with the {} first", self.kind)); } let Ok(layout) = serde_json::from_slice::(&body) else { return respond_status(req, 400, "Body must be JSON {\"cells\":[{\"display_id\":7,\"col\":1,\"row\":0}]}");