sbd_client/
lib.rs

1//! Sbd client library.
2#![deny(missing_docs)]
3
4use std::io::{Error, Result};
5use std::sync::Arc;
6
7/// defined by the sbd spec
8const MAX_MSG_SIZE: usize = 20_000;
9
10/// defined by ed25519 spec
11const PK_SIZE: usize = 32;
12
13/// defined by ed25519 spec
14const SIG_SIZE: usize = 64;
15
16/// sbd spec defines headers to be the same size as ed25519 pub keys
17const HDR_SIZE: usize = PK_SIZE;
18
19/// defined by sbd spec
20const NONCE_SIZE: usize = 32;
21
22/// defined by sbd spec
23const CMD_PREFIX: &[u8; 28] = &[0; 28];
24
25const F_LIMIT_BYTE_NANOS: &[u8] = b"lbrt";
26const F_LIMIT_IDLE_MILLIS: &[u8] = b"lidl";
27const F_AUTH_REQ: &[u8] = b"areq";
28const F_READY: &[u8] = b"srdy";
29
30#[cfg(feature = "raw_client")]
31pub mod raw_client;
32#[cfg(not(feature = "raw_client"))]
33mod raw_client;
34
35mod send_buf;
36
37/// Crypto to use. Note, the pair should be fresh for each new connection.
38pub trait Crypto {
39    /// The pubkey.
40    fn pub_key(&self) -> &[u8; PK_SIZE];
41
42    /// Sign the nonce.
43    fn sign(&self, nonce: &[u8]) -> Result<[u8; SIG_SIZE]>;
44}
45
46#[cfg(feature = "crypto")]
47mod default_crypto {
48    use super::*;
49
50    /// Default signer. Use a fresh one for every new connection.
51    pub struct DefaultCrypto([u8; PK_SIZE], ed25519_dalek::SigningKey);
52
53    impl Default for DefaultCrypto {
54        fn default() -> Self {
55            loop {
56                let k = ed25519_dalek::SigningKey::generate(
57                    &mut rand::thread_rng(),
58                );
59                let pk = k.verifying_key().to_bytes();
60                if &pk[..28] == CMD_PREFIX {
61                    continue;
62                } else {
63                    return Self(pk, k);
64                }
65            }
66        }
67    }
68
69    impl super::Crypto for DefaultCrypto {
70        fn pub_key(&self) -> &[u8; PK_SIZE] {
71            &self.0
72        }
73
74        fn sign(&self, nonce: &[u8]) -> std::io::Result<[u8; SIG_SIZE]> {
75            use ed25519_dalek::Signer;
76            Ok(self.1.sign(nonce).to_bytes())
77        }
78    }
79}
80#[cfg(feature = "crypto")]
81pub use default_crypto::*;
82
83/// Public key.
84#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
85pub struct PubKey(pub Arc<[u8; PK_SIZE]>);
86
87impl std::ops::Deref for PubKey {
88    type Target = [u8; 32];
89
90    fn deref(&self) -> &Self::Target {
91        &self.0
92    }
93}
94
95impl std::fmt::Debug for PubKey {
96    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
97        use base64::Engine;
98        let out = base64::engine::general_purpose::URL_SAFE_NO_PAD
99            .encode(&self.0[..]);
100        f.write_str(&out)
101    }
102}
103
104enum MsgType<'t> {
105    Msg {
106        #[allow(dead_code)]
107        pub_key: &'t [u8],
108        #[allow(dead_code)]
109        message: &'t [u8],
110    },
111    LimitByteNanos(i32),
112    LimitIdleMillis(i32),
113    AuthReq(&'t [u8]),
114    Ready,
115    Unknown,
116}
117
118/// A message received from a remote.
119/// This is just a single buffer. The first 32 bytes are the public key
120/// of the sender, or 28 `0`s followed by a 4 byte command. Any remaining bytes are the message. The buffer
121/// contained in this type is guaranteed to be at least 32 bytes long.
122pub struct Msg(pub Vec<u8>);
123
124impl Msg {
125    /// Get a reference to the slice containing the pubkey data.
126    pub fn pub_key_ref(&self) -> &[u8] {
127        &self.0[..PK_SIZE]
128    }
129
130    /// Extract a pubkey from the message.
131    pub fn pub_key(&self) -> PubKey {
132        PubKey(Arc::new(self.0[..PK_SIZE].try_into().unwrap()))
133    }
134
135    /// Get a reference to the slice containing the message data.
136    pub fn message(&self) -> &[u8] {
137        &self.0[PK_SIZE..]
138    }
139
140    // -- private -- //
141
142    fn parse(&self) -> Result<MsgType<'_>> {
143        if self.0.len() < PK_SIZE {
144            return Err(Error::other("invalid message length"));
145        }
146        if &self.0[..28] == CMD_PREFIX {
147            match &self.0[28..HDR_SIZE] {
148                F_LIMIT_BYTE_NANOS => {
149                    if self.0.len() != HDR_SIZE + 4 {
150                        return Err(Error::other("invalid lbrt length"));
151                    }
152                    Ok(MsgType::LimitByteNanos(i32::from_be_bytes(
153                        self.0[PK_SIZE..].try_into().unwrap(),
154                    )))
155                }
156                F_LIMIT_IDLE_MILLIS => {
157                    if self.0.len() != HDR_SIZE + 4 {
158                        return Err(Error::other("invalid lidl length"));
159                    }
160                    Ok(MsgType::LimitIdleMillis(i32::from_be_bytes(
161                        self.0[HDR_SIZE..].try_into().unwrap(),
162                    )))
163                }
164                F_AUTH_REQ => {
165                    if self.0.len() != HDR_SIZE + NONCE_SIZE {
166                        return Err(Error::other("invalid areq length"));
167                    }
168                    Ok(MsgType::AuthReq(&self.0[HDR_SIZE..]))
169                }
170                F_READY => Ok(MsgType::Ready),
171                _ => Ok(MsgType::Unknown),
172            }
173        } else {
174            Ok(MsgType::Msg {
175                pub_key: &self.0[..PK_SIZE],
176                message: &self.0[PK_SIZE..],
177            })
178        }
179    }
180}
181
182/// Handle to receive data from the sbd connection.
183pub struct MsgRecv(tokio::sync::mpsc::Receiver<Msg>);
184
185impl MsgRecv {
186    /// Receive data from the sbd connection.
187    pub async fn recv(&mut self) -> Option<Msg> {
188        self.0.recv().await
189    }
190}
191
192/// Configuration for connecting an SbdClient.
193#[derive(Clone)]
194pub struct SbdClientConfig {
195    /// Outgoing message buffer size.
196    pub out_buffer_size: usize,
197
198    /// Setting this to `true` allows `ws://` scheme.
199    pub allow_plain_text: bool,
200
201    /// Setting this to `true` disables certificate verification on `wss://`
202    /// scheme. WARNING: this is a dangerous configuration and should not
203    /// be used outside of testing (i.e. self-signed tls certificates).
204    pub danger_disable_certificate_check: bool,
205
206    /// Set any custom http headers to send with the websocket connect.
207    pub headers: Vec<(String, String)>,
208}
209
210impl Default for SbdClientConfig {
211    fn default() -> Self {
212        Self {
213            out_buffer_size: MAX_MSG_SIZE * 8,
214            allow_plain_text: false,
215            danger_disable_certificate_check: false,
216            headers: Vec::new(),
217        }
218    }
219}
220
221/// SbdClient represents a single connection to a single sbd server
222/// through which we can communicate with any number of peers on that server.
223pub struct SbdClient {
224    url: String,
225    pub_key: PubKey,
226    send_buf: Arc<tokio::sync::Mutex<send_buf::SendBuf>>,
227    read_task: tokio::task::JoinHandle<()>,
228    write_task: tokio::task::JoinHandle<()>,
229}
230
231impl Drop for SbdClient {
232    fn drop(&mut self) {
233        self.read_task.abort();
234        self.write_task.abort();
235    }
236}
237
238impl SbdClient {
239    /// Connect to the remote sbd server.
240    pub async fn connect<C: Crypto>(
241        url: &str,
242        crypto: &C,
243    ) -> Result<(Self, MsgRecv)> {
244        Self::connect_config(url, crypto, SbdClientConfig::default()).await
245    }
246
247    /// Connect to the remote sbd server.
248    pub async fn connect_config<C: Crypto>(
249        url: &str,
250        crypto: &C,
251        config: SbdClientConfig,
252    ) -> Result<(Self, MsgRecv)> {
253        use base64::Engine;
254        let full_url = format!(
255            "{url}/{}",
256            base64::engine::general_purpose::URL_SAFE_NO_PAD
257                .encode(crypto.pub_key())
258        );
259
260        let (mut send, mut recv) = raw_client::WsRawConnect {
261            full_url: full_url.clone(),
262            max_message_size: MAX_MSG_SIZE,
263            allow_plain_text: config.allow_plain_text,
264            danger_disable_certificate_check: config
265                .danger_disable_certificate_check,
266            headers: config.headers,
267        }
268        .connect()
269        .await?;
270
271        let raw_client::Handshake {
272            limit_byte_nanos,
273            limit_idle_millis,
274            bytes_sent,
275        } = raw_client::Handshake::handshake(&mut send, &mut recv, crypto)
276            .await?;
277
278        let send_buf = send_buf::SendBuf::new(
279            full_url.clone(),
280            send,
281            config.out_buffer_size,
282            (limit_byte_nanos as f64 * 1.1) as u64,
283            std::time::Duration::from_millis((limit_idle_millis / 2) as u64),
284            bytes_sent,
285        );
286        let send_buf = Arc::new(tokio::sync::Mutex::new(send_buf));
287
288        let send_buf2 = send_buf.clone();
289        let (recv_send, recv_recv) = tokio::sync::mpsc::channel(4);
290        let read_task = tokio::task::spawn(async move {
291            while let Ok(data) = recv.recv().await {
292                let data = Msg(data);
293
294                match match data.parse() {
295                    Ok(data) => data,
296                    Err(_) => break,
297                } {
298                    MsgType::Msg { .. } => {
299                        if recv_send.send(data).await.is_err() {
300                            break;
301                        }
302                    }
303                    MsgType::LimitByteNanos(rate) => {
304                        send_buf2
305                            .lock()
306                            .await
307                            .new_rate_limit((rate as f64 * 1.1) as u64);
308                    }
309                    MsgType::LimitIdleMillis(_) => break,
310                    MsgType::AuthReq(_) => break,
311                    MsgType::Ready => (),
312                    MsgType::Unknown => (),
313                }
314            }
315
316            send_buf2.lock().await.close().await;
317        });
318
319        let send_buf2 = send_buf.clone();
320        let write_task = tokio::task::spawn(async move {
321            loop {
322                if let Some(dur) = send_buf2.lock().await.next_step_dur() {
323                    tokio::time::sleep(dur).await;
324                }
325                match send_buf2.lock().await.write_next_queued().await {
326                    Err(_) => break,
327                    Ok(true) => (),
328                    Ok(false) => {
329                        tokio::time::sleep(std::time::Duration::from_millis(
330                            10,
331                        ))
332                        .await;
333                    }
334                }
335            }
336
337            send_buf2.lock().await.close().await;
338        });
339
340        let pub_key = PubKey(Arc::new(*crypto.pub_key()));
341
342        let this = Self {
343            url: full_url,
344            pub_key,
345            send_buf,
346            read_task,
347            write_task,
348        };
349
350        Ok((this, MsgRecv(recv_recv)))
351    }
352
353    /// The full url of this client.
354    pub fn url(&self) -> &str {
355        &self.url
356    }
357
358    /// The pub key of this client.
359    pub fn pub_key(&self) -> &PubKey {
360        &self.pub_key
361    }
362
363    /// Close the connection.
364    pub async fn close(&self) {
365        self.send_buf.lock().await.close().await;
366    }
367
368    /// Send a message to a peer.
369    pub async fn send(&self, peer: &PubKey, data: &[u8]) -> Result<()> {
370        self.send_buf.lock().await.send(peer, data).await
371    }
372}
373
374#[cfg(test)]
375mod test;