1pub mod account;
6pub mod command;
7pub use teter_core::{e2e, history, sessions};
8
9use std::io;
10use std::path::{Path, PathBuf};
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, PrivateKeyDer, 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
26pub trait Io: AsyncRead + AsyncWrite + Unpin + Send {}
28impl<T: AsyncRead + AsyncWrite + Unpin + Send> Io for T {}
29
30pub type Relay = WebSocketStream<Box<dyn Io>>;
32
33#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct Identity {
37 pub cert: PathBuf,
39 pub key: PathBuf,
41}
42
43pub const CLIENT_CERT_VAR: &str = "TETER_CLIENT_CERT";
45pub const CLIENT_KEY_VAR: &str = "TETER_CLIENT_KEY";
47
48impl Identity {
49 pub fn from_env() -> io::Result<Option<Self>> {
56 let var = |name| std::env::var_os(name).filter(|value| !value.is_empty());
57 Self::from_vars(var(CLIENT_CERT_VAR), var(CLIENT_KEY_VAR))
58 }
59
60 fn from_vars(
61 cert: Option<std::ffi::OsString>,
62 key: Option<std::ffi::OsString>,
63 ) -> io::Result<Option<Self>> {
64 match (cert, key) {
65 (Some(cert), Some(key)) => Ok(Some(Self {
66 cert: cert.into(),
67 key: key.into(),
68 })),
69 (None, None) => Ok(None),
70 _ => Err(invalid(format!(
71 "a client certificate needs both {CLIENT_CERT_VAR} and {CLIENT_KEY_VAR}"
72 ))),
73 }
74 }
75}
76
77pub async fn connect(url: &str, ca_cert: Option<&Path>) -> io::Result<Relay> {
82 connect_as(url, ca_cert, Identity::from_env()?.as_ref()).await
83}
84
85pub async fn connect_as(
88 url: &str,
89 ca_cert: Option<&Path>,
90 identity: Option<&Identity>,
91) -> io::Result<Relay> {
92 let uri: Uri = url
93 .parse()
94 .map_err(|e| invalid(format!("relay URL {url}: {e}")))?;
95 let tls = match uri.scheme_str() {
96 Some("ws") => false,
97 Some("wss") => true,
98 _ => return Err(invalid(format!("relay URL {url}: not ws:// or wss://"))),
99 };
100 let host = uri
101 .host()
102 .ok_or_else(|| invalid(format!("relay URL {url}: no host")))?
103 .trim_start_matches('[')
104 .trim_end_matches(']')
105 .to_owned();
106 let port = uri.port_u16().unwrap_or(if tls { 443 } else { 80 });
107
108 let tcp = TcpStream::connect((host.as_str(), port)).await?;
109 tcp.set_nodelay(true)?;
110 let stream: Box<dyn Io> = if tls {
111 let connector = TlsConnector::from(Arc::new(client_config(ca_cert, identity)?));
112 let name = ServerName::try_from(host.clone())
113 .map_err(|e| invalid(format!("relay host {host}: {e}")))?;
114 Box::new(connector.connect(name, tcp).await?)
115 } else {
116 Box::new(tcp)
117 };
118 let request = url.into_client_request().map_err(io::Error::other)?;
119 let (ws, _) = tokio_tungstenite::client_async(request, stream)
120 .await
121 .map_err(io::Error::other)?;
122 Ok(ws)
123}
124
125fn client_config(
126 ca_cert: Option<&Path>,
127 identity: Option<&Identity>,
128) -> io::Result<rustls::ClientConfig> {
129 let mut roots = rustls::RootCertStore::empty();
130 match ca_cert {
131 Some(path) => {
132 for cert in CertificateDer::pem_file_iter(path)
133 .map_err(|e| invalid(format!("CA certificate {}: {e}", path.display())))?
134 {
135 let cert =
136 cert.map_err(|e| invalid(format!("CA certificate {}: {e}", path.display())))?;
137 roots
138 .add(cert)
139 .map_err(|e| invalid(format!("CA certificate {}: {e}", path.display())))?;
140 }
141 }
142 None => {
143 let found = rustls_native_certs::load_native_certs();
144 roots.add_parsable_certificates(found.certs);
145 }
146 }
147 let provider = Arc::new(rustls::crypto::ring::default_provider());
148 let builder = rustls::ClientConfig::builder_with_provider(provider)
149 .with_safe_default_protocol_versions()
150 .map_err(io::Error::other)?
151 .with_root_certificates(roots);
152 let Some(identity) = identity else {
153 return Ok(builder.with_no_client_auth());
154 };
155 let cert_error = |e: &dyn std::fmt::Display| {
156 invalid(format!(
157 "client certificate {}: {e}",
158 identity.cert.display()
159 ))
160 };
161 let certs = CertificateDer::pem_file_iter(&identity.cert)
162 .and_then(|certs| certs.collect::<Result<Vec<_>, _>>())
163 .map_err(|e| cert_error(&e))?;
164 if certs.is_empty() {
165 return Err(cert_error(&"no certificate in the file"));
166 }
167 let key = PrivateKeyDer::from_pem_file(&identity.key).map_err(|e| {
168 invalid(format!(
169 "client certificate key {}: {e}",
170 identity.key.display()
171 ))
172 })?;
173 builder.with_client_auth_cert(certs, key).map_err(|e| {
174 invalid(format!(
175 "client certificate {} with key {}: {e}",
176 identity.cert.display(),
177 identity.key.display()
178 ))
179 })
180}
181
182fn invalid(message: String) -> io::Error {
183 io::Error::new(io::ErrorKind::InvalidInput, message)
184}
185
186pub async fn send<S>(sink: &mut S, msg: Message) -> io::Result<()>
188where
189 S: Sink<Frame, Error = WsError> + Unpin,
190{
191 let text = serialize_message(&msg).map_err(io::Error::other)?;
192 sink.send(Frame::text(text)).await.map_err(io::Error::other)
193}
194
195pub async fn recv<S>(stream: &mut S) -> io::Result<Option<Message>>
198where
199 S: Stream<Item = Result<Frame, WsError>> + Unpin,
200{
201 loop {
202 match stream.next().await {
203 Some(Ok(Frame::Text(text))) => {
204 return deserialize_message(&text)
205 .map(Some)
206 .map_err(io::Error::other);
207 }
208 Some(Ok(Frame::Close(_))) | None => return Ok(None),
209 Some(Ok(_)) => {}
210 Some(Err(e)) => return Err(io::Error::other(e)),
211 }
212 }
213}
214
215#[cfg(test)]
216mod tests {
217
218 use super::*;
219
220 #[test]
221 fn an_identity_needs_both_files_or_neither() {
222 assert_eq!(Identity::from_vars(None, None).unwrap(), None);
223 assert_eq!(
224 Identity::from_vars(Some("c.pem".into()), Some("k.pem".into())).unwrap(),
225 Some(Identity {
226 cert: "c.pem".into(),
227 key: "k.pem".into()
228 })
229 );
230 for (cert, key) in [(Some("c.pem".into()), None), (None, Some("k.pem".into()))] {
231 let err = Identity::from_vars(cert, key).unwrap_err();
232 assert!(err.to_string().contains(CLIENT_KEY_VAR), "{err}");
233 }
234 }
235}