lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README

connector.rs (4820B)


      1 use crate::{socket::NativeSocket, wire::MeteredIo};
      2 use core::{future::Future, pin::pin, task::Poll};
      3 use futures::StreamExt;
      4 use radroots_transport::host::websocket::{Admission, Connector, Error, IoFuture, Socket};
      5 use std::{net::SocketAddr, num::NonZeroUsize, sync::Arc, time::Duration};
      6 use tokio::net::TcpStream;
      7 use tokio_tungstenite::MaybeTlsStream;
      8 use url::Url;
      9 
     10 const MAX_RESOLVED_ADDRESSES: usize = 32;
     11 
     12 /// Inert native I/O provider. The shared session supplies its original
     13 /// destination authority, ingress generation, limits and connection deadline.
     14 #[derive(Clone, Copy, Debug, Default)]
     15 pub struct NativeConnector;
     16 
     17 impl Connector for NativeConnector {
     18     fn supports_ping(&self) -> bool {
     19         true
     20     }
     21 
     22     fn connect<'a>(
     23         &'a self,
     24         endpoint: &'a str,
     25         timeout: Duration,
     26         max_message_bytes: NonZeroUsize,
     27         admission: Arc<dyn Admission>,
     28     ) -> IoFuture<'a, Result<Arc<dyn Socket>, Error>> {
     29         Box::pin(async move {
     30             let parsed = Url::parse(endpoint).map_err(|_| Error::Policy)?;
     31             if !matches!(parsed.scheme(), "ws" | "wss")
     32                 || !parsed.username().is_empty()
     33                 || parsed.password().is_some()
     34                 || parsed.fragment().is_some()
     35             {
     36                 return Err(Error::Policy);
     37             }
     38             let host = parsed
     39                 .host_str()
     40                 .ok_or(Error::Policy)?
     41                 .trim_matches(['[', ']']);
     42             let port = parsed.port_or_known_default().ok_or(Error::Policy)?;
     43             let metering = Arc::clone(&admission);
     44             let connect = async {
     45                 let addresses = resolve_bounded(host, port).await?;
     46                 if addresses
     47                     .iter()
     48                     .any(|address| !admission.permits_address(address.ip()))
     49                 {
     50                     return Err(Error::Policy);
     51                 }
     52                 let tcp = connect_pinned(&addresses).await?;
     53                 let plaintext = if parsed.scheme() == "wss" {
     54                     let mut roots = rustls::RootCertStore::empty();
     55                     roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
     56                     let config = rustls::ClientConfig::builder()
     57                         .with_root_certificates(roots)
     58                         .with_no_client_auth();
     59                     let server_name = rustls::pki_types::ServerName::try_from(host.to_owned())
     60                         .map_err(|_| Error::Policy)?;
     61                     let tls = tokio_rustls::TlsConnector::from(Arc::new(config))
     62                         .connect(server_name, tcp)
     63                         .await
     64                         .map_err(|_| Error::Unavailable)?;
     65                     MaybeTlsStream::Rustls(tls)
     66                 } else {
     67                     MaybeTlsStream::Plain(tcp)
     68                 };
     69                 let metered = MeteredIo::new(plaintext, metering, max_message_bytes.get());
     70                 let config = tokio_tungstenite::tungstenite::protocol::WebSocketConfig::default()
     71                     .max_message_size(Some(max_message_bytes.get()))
     72                     .max_frame_size(Some(max_message_bytes.get()));
     73                 let (stream, _) =
     74                     tokio_tungstenite::client_async_with_config(endpoint, metered, Some(config))
     75                         .await
     76                         .map_err(|_| Error::Unavailable)?;
     77                 let (sink, stream) = stream.split();
     78                 Ok(
     79                     Arc::new(NativeSocket::new(sink, stream, max_message_bytes.get()))
     80                         as Arc<dyn Socket>,
     81                 )
     82             };
     83             let mut connect = pin!(connect);
     84             let admitted = futures::future::poll_fn(|context| {
     85                 if !admission.admitted_read(context) || !admission.admitted_write(context) {
     86                     return Poll::Ready(Err(Error::Policy));
     87                 }
     88                 connect.as_mut().poll(context)
     89             });
     90             tokio::time::timeout(timeout, admitted)
     91                 .await
     92                 .map_err(|_| Error::Timeout)?
     93         })
     94     }
     95 }
     96 
     97 async fn resolve_bounded(host: &str, port: u16) -> Result<Vec<SocketAddr>, Error> {
     98     let addresses = tokio::net::lookup_host((host, port))
     99         .await
    100         .map_err(|_| Error::Unavailable)?;
    101     let bounded = addresses
    102         .take(MAX_RESOLVED_ADDRESSES + 1)
    103         .collect::<Vec<_>>();
    104     if bounded.is_empty() || bounded.len() > MAX_RESOLVED_ADDRESSES {
    105         return Err(Error::Policy);
    106     }
    107     Ok(bounded)
    108 }
    109 
    110 async fn connect_pinned(addresses: &[SocketAddr]) -> Result<TcpStream, Error> {
    111     for address in addresses {
    112         if let Ok(stream) = TcpStream::connect(address).await {
    113             return Ok(stream);
    114         }
    115     }
    116     Err(Error::Unavailable)
    117 }