pub mod account;
pub mod command;
pub use teter_core::{e2e, history, sessions};
use std::io;
use std::path::{Path, PathBuf};
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, PrivateKeyDer, 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>>;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Identity {
pub cert: PathBuf,
pub key: PathBuf,
}
pub const CLIENT_CERT_VAR: &str = "TETER_CLIENT_CERT";
pub const CLIENT_KEY_VAR: &str = "TETER_CLIENT_KEY";
impl Identity {
pub fn from_env() -> io::Result<Option<Self>> {
let var = |name| std::env::var_os(name).filter(|value| !value.is_empty());
Self::from_vars(var(CLIENT_CERT_VAR), var(CLIENT_KEY_VAR))
}
fn from_vars(
cert: Option<std::ffi::OsString>,
key: Option<std::ffi::OsString>,
) -> io::Result<Option<Self>> {
match (cert, key) {
(Some(cert), Some(key)) => Ok(Some(Self {
cert: cert.into(),
key: key.into(),
})),
(None, None) => Ok(None),
_ => Err(invalid(format!(
"a client certificate needs both {CLIENT_CERT_VAR} and {CLIENT_KEY_VAR}"
))),
}
}
}
pub async fn connect(url: &str, ca_cert: Option<&Path>) -> io::Result<Relay> {
connect_as(url, ca_cert, Identity::from_env()?.as_ref()).await
}
pub async fn connect_as(
url: &str,
ca_cert: Option<&Path>,
identity: Option<&Identity>,
) -> 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, identity)?));
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(|e| handshake_error(url, e))?;
Ok(ws)
}
fn handshake_error(url: &str, error: tokio_tungstenite::tungstenite::Error) -> io::Error {
let tokio_tungstenite::tungstenite::Error::Http(response) = &error else {
return io::Error::other(error);
};
if !response.status().is_redirection() {
return io::Error::other(error);
}
let location = response
.headers()
.get("location")
.and_then(|location| location.to_str().ok())
.unwrap_or("");
let secure = url
.strip_prefix("ws://")
.filter(|rest| {
location
.strip_prefix("https://")
.is_some_and(|to| host_of(to) == host_of(rest))
})
.map(|rest| format!("wss://{rest}"));
io::Error::other(match secure {
Some(secure) => format!(
"the relay at {url} redirects to https ({}): use {secure}",
response.status()
),
None if location.is_empty() => format!(
"the relay at {url} redirects ({}) without saying where",
response.status()
),
None => format!(
"the relay at {url} redirects ({}) to {location}: use that address, with ws:// or \
wss://",
response.status()
),
})
}
fn host_of(rest: &str) -> &str {
rest.split(['/', '?', '#']).next().unwrap_or("")
}
fn client_config(
ca_cert: Option<&Path>,
identity: Option<&Identity>,
) -> 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());
let builder = rustls::ClientConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()
.map_err(io::Error::other)?
.with_root_certificates(roots);
let Some(identity) = identity else {
return Ok(builder.with_no_client_auth());
};
let cert_error = |e: &dyn std::fmt::Display| {
invalid(format!(
"client certificate {}: {e}",
identity.cert.display()
))
};
let certs = CertificateDer::pem_file_iter(&identity.cert)
.and_then(|certs| certs.collect::<Result<Vec<_>, _>>())
.map_err(|e| cert_error(&e))?;
if certs.is_empty() {
return Err(cert_error(&"no certificate in the file"));
}
let key = PrivateKeyDer::from_pem_file(&identity.key).map_err(|e| {
invalid(format!(
"client certificate key {}: {e}",
identity.key.display()
))
})?;
builder.with_client_auth_cert(certs, key).map_err(|e| {
invalid(format!(
"client certificate {} with key {}: {e}",
identity.cert.display(),
identity.key.display()
))
})
}
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)),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_identity_needs_both_files_or_neither() {
assert_eq!(Identity::from_vars(None, None).unwrap(), None);
assert_eq!(
Identity::from_vars(Some("c.pem".into()), Some("k.pem".into())).unwrap(),
Some(Identity {
cert: "c.pem".into(),
key: "k.pem".into()
})
);
for (cert, key) in [(Some("c.pem".into()), None), (None, Some("k.pem".into()))] {
let err = Identity::from_vars(cert, key).unwrap_err();
assert!(err.to_string().contains(CLIENT_KEY_VAR), "{err}");
}
}
}