Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 99 additions & 0 deletions crates/host/src/lib.rs
Original file line number Diff line number Diff line change
@@ -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<IpAddr> {
let mut ips: Vec<IpAddr> = 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<dyn platform::Platform>,
/// 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<timing::TimingLog>,
pub pairing_store: PathBuf,
/// Show or hide the pairing code.
pub notify: Box<dyn Fn(pairing::Notice) + Send + Sync>,
}

/// A running host. Signaling serves on its own thread.
pub struct Host {
pub shared: Arc<session::SharedHandle>,
pub pairing: Arc<pairing::Pairing>,
/// 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<Host> {
let lan: Vec<String> = 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 })
}
113 changes: 39 additions & 74 deletions crates/host/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -159,7 +153,7 @@
result
}

fn run(args: Args, app: Option<AppPaths>) -> Result<()> {

Check failure on line 156 in crates/host/src/main.rs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this function to reduce its Cognitive Complexity from 37 to the 30 allowed.

See more on https://sonarcloud.io/project/issues?id=th3r-dev_mullion&issues=AaHMAi9Tr3jilQPuovcH&open=AaHMAi9Tr3jilQPuovcH&pullRequest=23
// Env fills the defaults; explicit flags win.
let mut sw = config::Switches::from_env();
if let Some(v) = args.port { sw.port = v; }
Expand Down Expand Up @@ -222,19 +216,7 @@
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<IpAddr> = 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,
Expand All @@ -246,69 +228,54 @@
..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::<mullion_host::PortInUse>().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();
Expand All @@ -318,11 +285,9 @@
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"");
Expand Down
24 changes: 16 additions & 8 deletions crates/host/src/signaling.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,8 @@ pub struct Signaling {
web: Option<Server>,
handler: Arc<dyn OfferHandler>,
host_name: String,
/// What receivers are told this host is: "Mac", "tablet".
kind: &'static str,
config: serde_json::Value,
lan_ips: Vec<String>,
pairing: Option<Arc<Pairing>>,
Expand Down Expand Up @@ -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`.
Expand Down Expand Up @@ -246,10 +254,10 @@ impl Signaling {
sealed: Sealed,
}
let Ok(so) = serde_json::from_slice::<SealedOffer>(&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)),
Expand Down Expand Up @@ -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 {
Expand All @@ -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"),
Expand Down Expand Up @@ -351,15 +359,15 @@ 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());
req.respond(with_cors(resp)).context("respond")
}
("/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)
Expand All @@ -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::<LayoutRequest>(&body) else {
return respond_status(req, 400, "Body must be JSON {\"cells\":[{\"display_id\":7,\"col\":1,\"row\":0}]}");
Expand Down
Loading