use anyhow::{Context, Result, ensure}; use futures_util::{SinkExt, StreamExt}; use prost::Message; use rmm_protocol::Envelope; use rustls::{ClientConfig, RootCertStore}; use std::{io::BufReader, net::SocketAddr, sync::Arc, time::Duration}; use tokio::{net::TcpStream, time::timeout}; use tokio_tungstenite::{ Connector, MaybeTlsStream, WebSocketStream, tungstenite::{Message as WsMessage, protocol::WebSocketConfig}, }; pub type Channel = WebSocketStream>; pub async fn connect( address: SocketAddr, ca: &[u8], certificate: &[u8], private_key: &[u8], ) -> Result { ensure!( address.port() != 0 && !address.ip().is_unspecified() && !address.ip().is_multicast(), "INVALID_CONNECT_ADDRESS" ); let mut roots = RootCertStore::empty(); for cert in rustls_pemfile::certs(&mut BufReader::new(ca)) { roots.add(cert?)?; } let certs = rustls_pemfile::certs(&mut BufReader::new(certificate)) .collect::>>()?; let key = rustls_pemfile::private_key(&mut BufReader::new(private_key))? .context("device key missing")?; let config = ClientConfig::builder() .with_root_certificates(roots) .with_client_auth_cert(certs, key)?; let tcp = timeout(Duration::from_secs(10), TcpStream::connect(address)).await??; let ws = WebSocketConfig::default() .max_message_size(Some(rmm_domain::MAX_MESSAGE)) .max_frame_size(Some(rmm_domain::MAX_MESSAGE)); // URL controls TLS SNI and hostname validation; address overrides TCP only. let (channel, _) = timeout( Duration::from_secs(10), tokio_tungstenite::client_async_tls_with_config( format!( "wss://{}:{}/agent/v1/connect", crate::https_channel::server_name()?, address.port() ), tcp, Some(ws), Some(Connector::Rustls(Arc::new(config))), ), ) .await??; Ok(channel) } pub async fn send(ws: &mut Channel, e: &Envelope) -> Result<()> { timeout( Duration::from_secs(10), ws.send(WsMessage::Binary(e.encode_to_vec().into())), ) .await??; Ok(()) } pub async fn receive_live(ws: &mut Channel) -> Result { loop { match ws.next().await.context("channel closed")?? { WsMessage::Binary(bytes) => { ensure!(bytes.len() <= rmm_domain::MAX_MESSAGE, "message limit"); return Ok(Envelope::decode(bytes)?); } WsMessage::Ping(_) => ws.flush().await?, WsMessage::Pong(_) => {} WsMessage::Close(_) => anyhow::bail!("channel closed"), _ => anyhow::bail!("binary envelope required"), } } }