//! One bounded dispatcher-facing actor for WSS and HTTPS. Never reconnects or //! retries a permit internally; the owning journal/sync state machine does that. use crate::{ certificate_rotation::DeviceIdentity, https_channel::{self, HttpsChannel, WssFailure}, transport, }; use anyhow::{Context, Result, ensure}; use rmm_protocol::Envelope; use std::{net::SocketAddr, time::Duration}; use tokio::sync::mpsc; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Mode { Auto, Wss, Https, } impl Mode { pub fn parse(s: &str) -> Result { match s { "auto" => Ok(Self::Auto), "wss" => Ok(Self::Wss), "https" => Ok(Self::Https), _ => anyhow::bail!("RMM_TRANSPORT_INVALID"), } } } enum Channel { Wss(Box), Https(HttpsChannel), } enum Command { Send(Envelope), Poll(Envelope), } pub struct Handle { outgoing: mpsc::Sender, incoming: mpsc::Receiver>, task: tokio::task::JoinHandle<()>, https: bool, } impl Drop for Handle { fn drop(&mut self) { self.task.abort(); } } impl Handle { pub async fn send(&self, envelope: &Envelope) -> Result<()> { tokio::time::timeout( Duration::from_secs(2), self.outgoing.send(Command::Send(envelope.clone())), ) .await??; Ok(()) } pub fn uses_https(&self) -> bool { self.https } pub async fn poll(&self, heartbeat: Envelope) -> Result<()> { ensure!(self.https, "POLL_REQUIRES_HTTPS"); tokio::time::timeout( Duration::from_secs(2), self.outgoing.send(Command::Poll(heartbeat)), ) .await??; Ok(()) } pub async fn receive(&mut self) -> Result { self.incoming.recv().await.context("CHANNEL_CLOSED")? } } fn classify(error: &anyhow::Error) -> WssFailure { use tokio_tungstenite::tungstenite::Error; for cause in error.chain() { if let Some(error) = cause.downcast_ref::() { return match error { Error::Tls(_) => WssFailure::TlsOrIdentity, Error::Http(response) => match response.status().as_u16() { 401 | 403 => WssFailure::Authentication, 400 | 404 | 405 | 426 | 501 | 502 | 503 => WssFailure::UpgradeBlocked, _ => WssFailure::Other, }, _ => WssFailure::Other, }; } } WssFailure::Other } pub async fn connect( mode: Mode, address: SocketAddr, ca: &[u8], identity: &DeviceIdentity, hello: Envelope, ) -> Result { let channel = if mode == Mode::Https { None } else { match transport::connect( address, ca, &identity.certificate_pem, &identity.private_key_pem, ) .await { Ok(mut ws) => { transport::send(&mut ws, &hello).await?; Some(Channel::Wss(Box::new(ws))) } Err(error) if mode == Mode::Auto && classify(&error) == WssFailure::UpgradeBlocked => { match transport::connect( address, ca, &identity.certificate_pem, &identity.private_key_pem, ) .await { Ok(mut ws) => { transport::send(&mut ws, &hello).await?; Some(Channel::Wss(Box::new(ws))) } Err(second) => { ensure!( https_channel::allow_https_fallback(classify(&second), 2), "AUTO_FALLBACK_NOT_AUTHORIZED" ); None } } } Err(error) => return Err(error), } }; let channel = if let Some(channel) = channel { channel } else { let client = https_channel::mtls_client( address, ca, &identity.certificate_pem, &identity.private_key_pem, )?; let channel = HttpsChannel::connect(client, address, hello).await?; ensure!(channel.generation() > 0, "HTTPS_GENERATION"); Channel::Https(channel) }; let https = matches!(channel, Channel::Https(_)); let (outgoing, commands) = mpsc::channel(16); let (events, incoming) = mpsc::channel(32); let task = tokio::spawn(async move { let result = run(channel, commands, &events).await; if let Err(error) = result { let _ = events.send(Err(error)).await; } }); Ok(Handle { outgoing, incoming, task, https, }) } async fn run( mut channel: Channel, mut commands: mpsc::Receiver, events: &mpsc::Sender>, ) -> Result<()> { match &mut channel { Channel::Wss(ws) => loop { tokio::select! { incoming=transport::receive_live(ws)=>{events.send(Ok(incoming?)).await?;}, command=commands.recv()=>{let Some(Command::Send(command))=command else {return Ok(())};transport::send(ws,&command).await?;}, } }, Channel::Https(http) => { let mut pending = None; loop { while let Some(envelope) = http.receive() { events.send(Ok(envelope)).await?; } let command = match pending.take() { Some(command) => command, None => match commands.recv().await { Some(command) => command, None => { http.fence(); return Ok(()); } }, }; if let Command::Poll(command) = command { // Dropping a long poll loses no effect/start authority; the // next durable send or fresh heartbeat drives redelivery. tokio::select! { result=http.poll(command,25)=>result?, next=commands.recv()=>match next{Some(next)=>pending=Some(next),None=>{http.fence();return Ok(())}}, } } else if let Command::Send(command) = command { http.send(&command).await?; } } } } } #[cfg(test)] mod tests { use super::*; #[test] fn auto_fallback_classifies_upgrade_refusal_but_never_authentication() { for (status, expected) in [ (426, WssFailure::UpgradeBlocked), (401, WssFailure::Authentication), (403, WssFailure::Authentication), (500, WssFailure::Other), ] { let response = tokio_tungstenite::tungstenite::http::Response::builder() .status(status) .body(None::>) .unwrap(); let error = anyhow::Error::new(tokio_tungstenite::tungstenite::Error::Http(Box::new( response, ))); assert_eq!(classify(&error), expected); } assert_eq!( classify(&anyhow::anyhow!("ambiguous reset")), WssFailure::Other ); } #[test] fn explicit_transport_names_cannot_enable_verification_bypasses() { assert_eq!(Mode::parse("https").unwrap(), Mode::Https); assert_eq!(Mode::parse("auto").unwrap(), Mode::Auto); assert!(Mode::parse("https-insecure").is_err()); } }