sbd-server 0.4.0

simple websocket-based message relay server
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
//! Attempt to pre-allocate as much as possible, including our tokio tasks.
//! Ideally this would include a frame buffer that we could fill on ws
//! recv and use ase a reference for ws send, but alas, fastwebsockets
//! doesn't seem up to the task. tungstenite will willy-nilly allocate
//! buffers for us, but at least we should only be dealing with one at a
//! time per connection.

use super::*;
use std::collections::HashMap;
use std::sync::{Arc, Mutex, Weak};

static U: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);

enum TaskMsg {
    NewWs {
        uniq: u64,
        index: usize,
        ws: Arc<dyn SbdWebsocket>,
        ip: Arc<Ipv6Addr>,
        pk: PubKey,
        maybe_auth: Option<(Option<Arc<str>>, AuthTokenTracker)>,
    },
    Close,
}

struct SlotEntry {
    send: tokio::sync::mpsc::UnboundedSender<TaskMsg>,
}

struct SlabEntry {
    uniq: u64,
    handshake_complete: bool,
    weak_ws: Weak<dyn SbdWebsocket>,
}

struct CSlotInner {
    max_count: usize,
    slots: Vec<SlotEntry>,
    slab: slab::Slab<SlabEntry>,
    pk_to_index: HashMap<PubKey, usize>,
    ip_to_index: HashMap<Arc<Ipv6Addr>, Vec<usize>>,
    task_list: Vec<tokio::task::JoinHandle<()>>,
    open_connections: opentelemetry::metrics::UpDownCounter<i64>,
}

impl Drop for CSlotInner {
    fn drop(&mut self) {
        for task in self.task_list.iter() {
            task.abort();
        }
    }
}

/// A weak reference to a connection slot container.
#[derive(Clone)]
pub struct WeakCSlot(Weak<Mutex<CSlotInner>>);

impl WeakCSlot {
    /// Upgrade this weak reference to a strong reference.
    pub fn upgrade(&self) -> Option<CSlot> {
        self.0.upgrade().map(CSlot)
    }
}

/// A connection slot container.
///
/// Note this is not clone to ensure that when the single top-level handle
/// is dropped, that everything is shutdown properly.
pub struct CSlot(Arc<Mutex<CSlotInner>>);

impl CSlot {
    /// Create a new connection slot container.
    pub fn new(
        config: Arc<Config>,
        ip_rate: Arc<IpRate>,
        meter: opentelemetry::metrics::Meter,
    ) -> Self {
        let count = config.limit_clients as usize;

        let ip_rate_counter = meter
            .u64_counter("sbd.server.ip_rate_limited")
            .with_description("Total number of IP rate limited events")
            .with_unit("count")
            .build();

        Self(Arc::new_cyclic(|this| {
            let mut slots = Vec::with_capacity(count);
            let mut task_list = Vec::with_capacity(count);
            for _ in 0..count {
                let (send, recv) = tokio::sync::mpsc::unbounded_channel();
                slots.push(SlotEntry { send });
                task_list.push(tokio::task::spawn(top_task(
                    config.clone(),
                    ip_rate.clone(),
                    WeakCSlot(this.clone()),
                    recv,
                    ip_rate_counter.clone(),
                )));
            }

            let open_connections = meter
                .i64_up_down_counter("sbd.server.open_connections")
                .with_description("Number of open client connections")
                .build();

            Mutex::new(CSlotInner {
                max_count: count,
                slots,
                slab: slab::Slab::with_capacity(count),
                pk_to_index: HashMap::with_capacity(count),
                ip_to_index: HashMap::with_capacity(count),
                task_list,
                open_connections,
            })
        }))
    }

    /// Get a weak reference to this connection slot container.
    pub fn weak(&self) -> WeakCSlot {
        WeakCSlot(Arc::downgrade(&self.0))
    }

    /// Remove a websocket from its slot.
    fn remove(&self, uniq: u64, index: usize) {
        let mut lock = self.0.lock().unwrap();

        match lock.slab.get(index) {
            None => return,
            Some(s) => {
                if s.uniq != uniq {
                    return;
                }
            }
        }

        let _ = lock.slots.get(index).unwrap().send.send(TaskMsg::Close);
        lock.slab.remove(index);
        lock.pk_to_index.retain(|_, i| *i != index);
        lock.ip_to_index.retain(|_, v| {
            v.retain(|i| *i != index);
            !v.is_empty()
        });

        // Decrement the open connections metric
        lock.open_connections.add(-1, &[])
    }

    /// Inner helper for inserting a websocket into an available slot.
    // oi clippy, this is super straight forward...
    #[allow(clippy::type_complexity)]
    fn insert_and_get_rate_send_list(
        &self,
        ip: Arc<Ipv6Addr>,
        pk: PubKey,
        ws: Arc<dyn SbdWebsocket>,
        maybe_auth: Option<(Option<Arc<str>>, AuthTokenTracker)>,
    ) -> std::result::Result<
        Vec<(u64, usize, Weak<dyn SbdWebsocket>)>,
        Arc<dyn SbdWebsocket>,
    > {
        let mut lock = self.0.lock().unwrap();

        if lock.slab.len() >= lock.max_count {
            return Err(ws);
        }

        let weak_ws = Arc::downgrade(&ws);

        let uniq = U.fetch_add(1, std::sync::atomic::Ordering::Relaxed);

        let index = lock.slab.insert(SlabEntry {
            uniq,
            weak_ws,
            handshake_complete: false,
        });

        lock.pk_to_index.insert(pk.clone(), index);

        let rate_send_list = {
            let list = {
                // WARN - allocation here!
                // Also, do we want to limit the max connections from same ip?

                let e = lock
                    .ip_to_index
                    .entry(ip.clone())
                    .or_insert_with(|| Vec::with_capacity(1024));

                e.push(index);

                e.clone()
            };

            let mut rate_send_list = Vec::with_capacity(list.len());

            for index in list.iter() {
                if let Some(slab) = lock.slab.get(*index) {
                    rate_send_list.push((
                        slab.uniq,
                        *index,
                        slab.weak_ws.clone(),
                    ));
                }
            }

            rate_send_list
        };

        let send = lock.slots.get(index).unwrap().send.clone();
        let _ = send.send(TaskMsg::NewWs {
            uniq,
            index,
            ws,
            ip,
            pk,
            maybe_auth,
        });

        // Increment the open connections metric
        lock.open_connections.add(1, &[]);

        Ok(rate_send_list)
    }

    /// Insert a connection to be managed by this container.
    pub async fn insert(
        &self,
        config: &Config,
        ip: Arc<Ipv6Addr>,
        pk: PubKey,
        ws: Arc<impl SbdWebsocket>,
        maybe_auth: Option<(Option<Arc<str>>, AuthTokenTracker)>,
    ) {
        let rate_send_list =
            self.insert_and_get_rate_send_list(ip, pk, ws, maybe_auth);

        match rate_send_list {
            Ok(rate_send_list) => {
                let rate = if config.disable_rate_limiting {
                    1
                } else {
                    let mut rate = config.limit_ip_byte_nanos() as u64
                        * rate_send_list.len() as u64;
                    if rate > i32::MAX as u64 {
                        rate = i32::MAX as u64;
                    }
                    rate as i32
                };

                for (uniq, index, weak_ws) in rate_send_list {
                    if let Some(ws) = weak_ws.upgrade() {
                        if ws
                            .send(cmd::SbdCmd::limit_byte_nanos(rate))
                            .await
                            .is_err()
                        {
                            self.remove(uniq, index);
                        }
                    }
                }
            }
            Err(ws) => {
                ws.close().await;
                drop(ws);
            }
        }
    }

    /// Mark a slotted websocket as ready.
    fn mark_ready(&self, uniq: u64, index: usize) {
        let mut lock = self.0.lock().unwrap();
        if let Some(slab) = lock.slab.get_mut(index) {
            if slab.uniq == uniq {
                slab.handshake_complete = true;
            }
        }
    }

    /// Get a websocket from its slot.
    fn get_sender(
        &self,
        pk: &PubKey,
    ) -> Result<(u64, usize, Arc<dyn SbdWebsocket>)> {
        let lock = self.0.lock().unwrap();

        let index = match lock.pk_to_index.get(pk) {
            None => return Err(Error::other("no such peer")),
            Some(index) => *index,
        };

        let slab = lock.slab.get(index).unwrap();

        if !slab.handshake_complete {
            return Err(Error::other("no such peer"));
        }

        let uniq = slab.uniq;
        let ws = match slab.weak_ws.upgrade() {
            None => return Err(Error::other("no such peer")),
            Some(ws) => ws,
        };

        Ok((uniq, index, ws))
    }

    /// Send via a slotted websocket.
    async fn send(&self, pk: &PubKey, payload: Payload) -> Result<()> {
        let (uniq, index, ws) = self.get_sender(pk)?;

        match ws.send(payload).await {
            Err(err) => {
                self.remove(uniq, index);
                Err(err)
            }
            Ok(_) => Ok(()),
        }
    }
}

/// This top-task waits for incoming websockets, processes them until
/// completion, and then waits for a new incoming websocket.
async fn top_task(
    config: Arc<Config>,
    ip_rate: Arc<IpRate>,
    weak: WeakCSlot,
    mut recv: tokio::sync::mpsc::UnboundedReceiver<TaskMsg>,
    ip_rate_counter: opentelemetry::metrics::Counter<u64>,
) {
    let mut item = recv.recv().await;
    loop {
        let uitem = match item {
            None => break,
            Some(uitem) => uitem,
        };

        item = if let TaskMsg::NewWs {
            uniq,
            index,
            ws,
            ip,
            pk,
            maybe_auth,
        } = uitem
        {
            // we have a websocket! process to completion
            let next_i = tokio::select! {
                i = recv.recv() => Some(i),
                _ = ws_task(
                    &config,
                    &ip_rate,
                    &weak,
                    &ws,
                    ip,
                    pk,
                    uniq,
                    index,
                    maybe_auth,
                    &ip_rate_counter,
                ) => None,
            };

            // our websocket task ended, clean up
            ws.close().await;
            drop(ws);
            if let Some(cslot) = weak.upgrade() {
                cslot.remove(uniq, index);
            }

            match next_i {
                Some(i) => i,
                None => recv.recv().await,
            }
        } else {
            recv.recv().await
        };
    }
}

/// Process a single websocket until completion.
#[allow(clippy::too_many_arguments)]
async fn ws_task(
    config: &Arc<Config>,
    ip_rate: &IpRate,
    weak_cslot: &WeakCSlot,
    ws: &Arc<dyn SbdWebsocket>,
    ip: Arc<Ipv6Addr>,
    pk: PubKey,
    uniq: u64,
    index: usize,
    maybe_auth: Option<(Option<Arc<str>>, AuthTokenTracker)>,
    ip_rate_counter: &opentelemetry::metrics::Counter<u64>,
) {
    let pub_key =
        base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(*pk.0);
    let auth_res = tokio::time::timeout(config.idle_dur(), async {
        use rand::Rng;
        let mut nonce = [0xdb; 32];
        rand::thread_rng().fill(&mut nonce[..]);

        // send them a nonce to prove they can sign with private key
        ws.send(cmd::SbdCmd::auth_req(&nonce)).await?;

        loop {
            let auth_res = ws.recv().await?;

            if !ip_rate.is_ok(&ip, auth_res.as_ref().len()).await {
                ip_rate_counter.add(
                    1,
                    &[
                        opentelemetry::KeyValue::new(
                            "pub_key",
                            pub_key.clone(),
                        ),
                        opentelemetry::KeyValue::new("kind", "auth"),
                    ],
                );

                return Err(Error::other("ip rate limited"));
            }

            if let Some((token, token_tracker)) = &maybe_auth {
                // we already know they had a valid token
                // when they opened this connection.
                // just using this for side-effect marking token use time
                let _ =
                    token_tracker.check_is_token_valid(config, token.clone());
            }

            match cmd::SbdCmd::parse(auth_res)? {
                cmd::SbdCmd::AuthRes(sig) => {
                    if !pk.verify(&sig, &nonce) {
                        return Err(Error::other("invalid sig"));
                    }
                    break;
                }
                cmd::SbdCmd::Message(_) => {
                    return Err(Error::other(
                        "invalid forward before handshake",
                    ));
                }
                _ => continue,
            }
        }

        // NOTE: the byte_nanos limit is sent during the cslot insert

        ws.send(cmd::SbdCmd::limit_idle_millis(config.limit_idle_millis))
            .await?;

        if let Some(cslot) = weak_cslot.upgrade() {
            cslot.mark_ready(uniq, index);
        } else {
            return Err(Error::other("closed"));
        }

        ws.send(cmd::SbdCmd::ready()).await?;

        Ok(())
    })
    .await;

    if auth_res.is_err() {
        return;
    }

    // auth/init complete, now loop over incoming data

    while let Ok(Ok(payload)) =
        tokio::time::timeout(config.idle_dur(), ws.recv()).await
    {
        if !ip_rate.is_ok(&ip, payload.len()).await {
            ip_rate_counter.add(
                1,
                &[
                    opentelemetry::KeyValue::new("pub_key", pub_key),
                    opentelemetry::KeyValue::new("kind", "msg"),
                ],
            );

            break;
        }

        if let Some((token, token_tracker)) = &maybe_auth {
            // we already know they had a valid token
            // when they opened this connection.
            // just using this for side-effect marking token use time
            let _ = token_tracker.check_is_token_valid(config, token.clone());
        }

        let cmd = match cmd::SbdCmd::parse(payload) {
            Err(_) => break,
            Ok(cmd) => cmd,
        };

        match cmd {
            // don't need to do anything... we just get a new timeout above
            cmd::SbdCmd::Keepalive => (),
            // auth responses are invalid at this stage
            cmd::SbdCmd::AuthRes(_) => break,
            // ignore unknown messages
            cmd::SbdCmd::Unknown => (),
            // forward an actual message to a peer
            cmd::SbdCmd::Message(mut payload) => {
                let dest = {
                    let payload = payload.to_mut();

                    let mut dest = [0; 32];
                    dest.copy_from_slice(&payload[..32]);
                    let dest = PubKey(Arc::new(dest));

                    payload[..32].copy_from_slice(&pk.0[..]);

                    dest
                };

                if let Some(cslot) = weak_cslot.upgrade() {
                    let _ = cslot.send(&dest, payload).await;
                } else {
                    break;
                }
            }
        }
    }

    tracing::debug!("Closed connection for {ip}");
}