pub mod account;
pub mod command;
pub use teter_core::{e2e, history, sessions};
use std::io;
use std::path::Path;
use std::sync::Arc;
use futures_util::{Sink, SinkExt, Stream, StreamExt};
use teter_common::{Message, deserialize_message, serialize_message};
use tokio::io::{AsyncRead, AsyncWrite};
use tokio::net::TcpStream;
use tokio_rustls::TlsConnector;
use tokio_rustls::rustls;
use tokio_rustls::rustls::pki_types::pem::PemObject;
use tokio_rustls::rustls::pki_types::{CertificateDer, ServerName};
use tokio_tungstenite::WebSocketStream;
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
use tokio_tungstenite::tungstenite::http::Uri;
use tokio_tungstenite::tungstenite::{Error as WsError, Message as Frame};
pub trait Io: AsyncRead + AsyncWrite + Unpin + Send {}
impl<T: AsyncRead + AsyncWrite + Unpin + Send> Io for T {}
pub type Relay = WebSocketStream<Box<dyn Io>>;
pub async fn connect(url: &str, ca_cert: Option<&Path>) -> io::Result<Relay> {
let uri: Uri = url
.parse()
.map_err(|e| invalid(format!("relay URL {url}: {e}")))?;
let tls = match uri.scheme_str() {
Some("ws") => false,
Some("wss") => true,
_ => return Err(invalid(format!("relay URL {url}: not ws:// or wss://"))),
};
let host = uri
.host()
.ok_or_else(|| invalid(format!("relay URL {url}: no host")))?
.trim_start_matches('[')
.trim_end_matches(']')
.to_owned();
let port = uri.port_u16().unwrap_or(if tls { 443 } else { 80 });
let tcp = TcpStream::connect((host.as_str(), port)).await?;
tcp.set_nodelay(true)?;
let stream: Box<dyn Io> = if tls {
let connector = TlsConnector::from(Arc::new(client_config(ca_cert)?));
let name = ServerName::try_from(host.clone())
.map_err(|e| invalid(format!("relay host {host}: {e}")))?;
Box::new(connector.connect(name, tcp).await?)
} else {
Box::new(tcp)
};
let request = url.into_client_request().map_err(io::Error::other)?;
let (ws, _) = tokio_tungstenite::client_async(request, stream)
.await
.map_err(io::Error::other)?;
Ok(ws)
}
fn client_config(ca_cert: Option<&Path>) -> io::Result<rustls::ClientConfig> {
let mut roots = rustls::RootCertStore::empty();
match ca_cert {
Some(path) => {
for cert in CertificateDer::pem_file_iter(path)
.map_err(|e| invalid(format!("CA certificate {}: {e}", path.display())))?
{
let cert =
cert.map_err(|e| invalid(format!("CA certificate {}: {e}", path.display())))?;
roots
.add(cert)
.map_err(|e| invalid(format!("CA certificate {}: {e}", path.display())))?;
}
}
None => {
let found = rustls_native_certs::load_native_certs();
roots.add_parsable_certificates(found.certs);
}
}
let provider = Arc::new(rustls::crypto::ring::default_provider());
Ok(rustls::ClientConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()
.map_err(io::Error::other)?
.with_root_certificates(roots)
.with_no_client_auth())
}
fn invalid(message: String) -> io::Error {
io::Error::new(io::ErrorKind::InvalidInput, message)
}
pub async fn send<S>(sink: &mut S, msg: Message) -> io::Result<()>
where
S: Sink<Frame, Error = WsError> + Unpin,
{
let text = serialize_message(&msg).map_err(io::Error::other)?;
sink.send(Frame::text(text)).await.map_err(io::Error::other)
}
pub async fn recv<S>(stream: &mut S) -> io::Result<Option<Message>>
where
S: Stream<Item = Result<Frame, WsError>> + Unpin,
{
loop {
match stream.next().await {
Some(Ok(Frame::Text(text))) => {
return deserialize_message(&text)
.map(Some)
.map_err(io::Error::other);
}
Some(Ok(Frame::Close(_))) | None => return Ok(None),
Some(Ok(_)) => {}
Some(Err(e)) => return Err(io::Error::other(e)),
}
}
}