Skip to main content

teter_client/
lib.rs

1//! A client's connection to the teter relay, over `ws://` or `wss://`, and
2//! the protocol messages sent and received on it. Shared by the backend and
3//! the frontend.
4
5pub mod account;
6pub mod command;
7pub use teter_core::{e2e, sessions};
8
9use std::io;
10use std::path::Path;
11use std::sync::Arc;
12
13use futures_util::{Sink, SinkExt, Stream, StreamExt};
14use teter_common::{Message, deserialize_message, serialize_message};
15use tokio::io::{AsyncRead, AsyncWrite};
16use tokio::net::TcpStream;
17use tokio_rustls::TlsConnector;
18use tokio_rustls::rustls;
19use tokio_rustls::rustls::pki_types::pem::PemObject;
20use tokio_rustls::rustls::pki_types::{CertificateDer, ServerName};
21use tokio_tungstenite::WebSocketStream;
22use tokio_tungstenite::tungstenite::client::IntoClientRequest;
23use tokio_tungstenite::tungstenite::http::Uri;
24use tokio_tungstenite::tungstenite::{Error as WsError, Message as Frame};
25
26/// A byte stream: plain TCP, or TLS over TCP.
27pub trait Io: AsyncRead + AsyncWrite + Unpin + Send {}
28impl<T: AsyncRead + AsyncWrite + Unpin + Send> Io for T {}
29
30/// A WebSocket connection to the relay.
31pub type Relay = WebSocketStream<Box<dyn Io>>;
32
33/// Connect to `url` (`ws://host:port/path` or `wss://...`). For `wss://`,
34/// the relay's certificate must chain to the system's roots, or to
35/// `ca_cert` (a PEM file) when given.
36pub async fn connect(url: &str, ca_cert: Option<&Path>) -> io::Result<Relay> {
37    let uri: Uri = url
38        .parse()
39        .map_err(|e| invalid(format!("relay URL {url}: {e}")))?;
40    let tls = match uri.scheme_str() {
41        Some("ws") => false,
42        Some("wss") => true,
43        _ => return Err(invalid(format!("relay URL {url}: not ws:// or wss://"))),
44    };
45    let host = uri
46        .host()
47        .ok_or_else(|| invalid(format!("relay URL {url}: no host")))?
48        .trim_start_matches('[')
49        .trim_end_matches(']')
50        .to_owned();
51    let port = uri.port_u16().unwrap_or(if tls { 443 } else { 80 });
52
53    let tcp = TcpStream::connect((host.as_str(), port)).await?;
54    tcp.set_nodelay(true)?;
55    let stream: Box<dyn Io> = if tls {
56        let connector = TlsConnector::from(Arc::new(client_config(ca_cert)?));
57        let name = ServerName::try_from(host.clone())
58            .map_err(|e| invalid(format!("relay host {host}: {e}")))?;
59        Box::new(connector.connect(name, tcp).await?)
60    } else {
61        Box::new(tcp)
62    };
63    let request = url.into_client_request().map_err(io::Error::other)?;
64    let (ws, _) = tokio_tungstenite::client_async(request, stream)
65        .await
66        .map_err(io::Error::other)?;
67    Ok(ws)
68}
69
70fn client_config(ca_cert: Option<&Path>) -> io::Result<rustls::ClientConfig> {
71    let mut roots = rustls::RootCertStore::empty();
72    match ca_cert {
73        Some(path) => {
74            for cert in CertificateDer::pem_file_iter(path)
75                .map_err(|e| invalid(format!("CA certificate {}: {e}", path.display())))?
76            {
77                let cert =
78                    cert.map_err(|e| invalid(format!("CA certificate {}: {e}", path.display())))?;
79                roots
80                    .add(cert)
81                    .map_err(|e| invalid(format!("CA certificate {}: {e}", path.display())))?;
82            }
83        }
84        None => {
85            let found = rustls_native_certs::load_native_certs();
86            roots.add_parsable_certificates(found.certs);
87        }
88    }
89    let provider = Arc::new(rustls::crypto::ring::default_provider());
90    Ok(rustls::ClientConfig::builder_with_provider(provider)
91        .with_safe_default_protocol_versions()
92        .map_err(io::Error::other)?
93        .with_root_certificates(roots)
94        .with_no_client_auth())
95}
96
97fn invalid(message: String) -> io::Error {
98    io::Error::new(io::ErrorKind::InvalidInput, message)
99}
100
101/// Send one protocol message on `sink` (a [`Relay`], or its sending half).
102pub async fn send<S>(sink: &mut S, msg: Message) -> io::Result<()>
103where
104    S: Sink<Frame, Error = WsError> + Unpin,
105{
106    let text = serialize_message(&msg).map_err(io::Error::other)?;
107    sink.send(Frame::text(text)).await.map_err(io::Error::other)
108}
109
110/// The next protocol message on `stream` (a [`Relay`], or its receiving
111/// half), or `None` once the relay closed the connection.
112pub async fn recv<S>(stream: &mut S) -> io::Result<Option<Message>>
113where
114    S: Stream<Item = Result<Frame, WsError>> + Unpin,
115{
116    loop {
117        match stream.next().await {
118            Some(Ok(Frame::Text(text))) => {
119                return deserialize_message(&text)
120                    .map(Some)
121                    .map_err(io::Error::other);
122            }
123            Some(Ok(Frame::Close(_))) | None => return Ok(None),
124            Some(Ok(_)) => {}
125            Some(Err(e)) => return Err(io::Error::other(e)),
126        }
127    }
128}