tx5_connection/
conn.rs

1use super::*;
2use std::sync::atomic::Ordering;
3
4pub(crate) enum ConnCmd {
5    SigRecv(tx5_signal::SignalMessage),
6    WebrtcRecv(webrtc::WebrtcEvt),
7    SendMessage(Vec<u8>),
8    WebrtcTimeoutCheck,
9    WebrtcClosed,
10}
11
12/// Receive messages from a tx5 connection.
13pub struct ConnRecv(CloseRecv<Vec<u8>>);
14
15impl ConnRecv {
16    /// Receive up to 16KiB of message data.
17    pub async fn recv(&mut self) -> Option<Vec<u8>> {
18        self.0.recv().await
19    }
20}
21
22/// A tx5 connection.
23pub struct Conn {
24    ready: Arc<tokio::sync::Semaphore>,
25    pub_key: PubKey,
26    cmd_send: CloseSend<ConnCmd>,
27    conn_task: tokio::task::JoinHandle<()>,
28    keepalive_task: tokio::task::JoinHandle<()>,
29    is_webrtc: Arc<std::sync::atomic::AtomicBool>,
30    send_msg_count: Arc<std::sync::atomic::AtomicU64>,
31    send_byte_count: Arc<std::sync::atomic::AtomicU64>,
32    recv_msg_count: Arc<std::sync::atomic::AtomicU64>,
33    recv_byte_count: Arc<std::sync::atomic::AtomicU64>,
34    hub_cmd_send: tokio::sync::mpsc::Sender<HubCmd>,
35}
36
37macro_rules! netaudit {
38    ($lvl:ident, $($all:tt)*) => {
39        ::tracing::event!(
40            target: "NETAUDIT",
41            ::tracing::Level::$lvl,
42            m = "tx5-connection",
43            $($all)*
44        );
45    };
46}
47
48impl Drop for Conn {
49    fn drop(&mut self) {
50        netaudit!(DEBUG, pub_key = ?self.pub_key, a = "drop");
51
52        self.conn_task.abort();
53        self.keepalive_task.abort();
54
55        let hub_cmd_send = self.hub_cmd_send.clone();
56        let pub_key = self.pub_key.clone();
57        tokio::task::spawn(async move {
58            let _ = hub_cmd_send.send(HubCmd::Disconnect(pub_key)).await;
59        });
60    }
61}
62
63impl Conn {
64    #[cfg(test)]
65    pub(crate) fn test_kill_keepalive_task(&self) {
66        self.keepalive_task.abort();
67    }
68
69    pub(crate) fn priv_new(
70        webrtc_config: WebRtcConfig,
71        is_polite: bool,
72        pub_key: PubKey,
73        client: Weak<tx5_signal::SignalConnection>,
74        config: Arc<HubConfig>,
75        hub_cmd_send: tokio::sync::mpsc::Sender<HubCmd>,
76    ) -> (Arc<Self>, ConnRecv, CloseSend<ConnCmd>) {
77        netaudit!(DEBUG, ?webrtc_config, ?pub_key, ?is_polite, a = "open",);
78
79        let is_webrtc = Arc::new(std::sync::atomic::AtomicBool::new(false));
80        let send_msg_count = Arc::new(std::sync::atomic::AtomicU64::new(0));
81        let send_byte_count = Arc::new(std::sync::atomic::AtomicU64::new(0));
82        let recv_msg_count = Arc::new(std::sync::atomic::AtomicU64::new(0));
83        let recv_byte_count = Arc::new(std::sync::atomic::AtomicU64::new(0));
84
85        // zero len semaphore.. we actually just wait for the close
86        let ready = Arc::new(tokio::sync::Semaphore::new(0));
87
88        let (mut msg_send, msg_recv) = CloseSend::sized_channel(1024);
89        let (cmd_send, cmd_recv) = CloseSend::sized_channel(1024);
90
91        let keepalive_dur = config.signal_config.max_idle / 2;
92        let client2 = client.clone();
93        let pub_key2 = pub_key.clone();
94        let keepalive_task = tokio::task::spawn(async move {
95            loop {
96                tokio::time::sleep(keepalive_dur).await;
97
98                if let Some(client) = client2.upgrade() {
99                    if client.send_keepalive(&pub_key2).await.is_err() {
100                        break;
101                    }
102                } else {
103                    break;
104                }
105            }
106        });
107
108        msg_send.set_close_on_drop(true);
109
110        let con_task_fut = con_task(
111            is_polite,
112            webrtc_config,
113            TaskCore {
114                client,
115                config,
116                pub_key: pub_key.clone(),
117                cmd_send: cmd_send.clone(),
118                cmd_recv,
119                send_msg_count: send_msg_count.clone(),
120                send_byte_count: send_byte_count.clone(),
121                recv_msg_count: recv_msg_count.clone(),
122                recv_byte_count: recv_byte_count.clone(),
123                msg_send,
124                ready: ready.clone(),
125                is_webrtc: is_webrtc.clone(),
126            },
127        );
128        let conn_task = tokio::task::spawn(con_task_fut);
129
130        let mut cmd_send2 = cmd_send.clone();
131        cmd_send2.set_close_on_drop(true);
132        let this = Self {
133            ready,
134            pub_key,
135            cmd_send: cmd_send2,
136            conn_task,
137            keepalive_task,
138            is_webrtc,
139            send_msg_count,
140            send_byte_count,
141            recv_msg_count,
142            recv_byte_count,
143            hub_cmd_send,
144        };
145
146        (Arc::new(this), ConnRecv(msg_recv), cmd_send)
147    }
148
149    /// Wait until this connection is ready to send / receive data.
150    pub async fn ready(&self) {
151        // this will error when we close the semaphore waking up the task
152        let _ = self.ready.acquire().await;
153    }
154
155    /// Returns `true` if we sucessfully connected over webrtc.
156    pub fn is_using_webrtc(&self) -> bool {
157        self.is_webrtc.load(Ordering::SeqCst)
158    }
159
160    /// The pub key of the remote peer this is connected to.
161    pub fn pub_key(&self) -> &PubKey {
162        &self.pub_key
163    }
164
165    /// Send up to 16KiB of message data.
166    pub async fn send(&self, msg: Vec<u8>) -> Result<()> {
167        self.cmd_send.send(ConnCmd::SendMessage(msg)).await
168    }
169
170    /// Get connection statistics.
171    pub fn get_stats(&self) -> ConnStats {
172        ConnStats {
173            send_msg_count: self.send_msg_count.load(Ordering::Relaxed),
174            send_byte_count: self.send_byte_count.load(Ordering::Relaxed),
175            recv_msg_count: self.recv_msg_count.load(Ordering::Relaxed),
176            recv_byte_count: self.recv_byte_count.load(Ordering::Relaxed),
177        }
178    }
179}
180
181/// Connection statistics.
182#[derive(Default)]
183pub struct ConnStats {
184    /// message count sent.
185    pub send_msg_count: u64,
186
187    /// byte count sent.
188    pub send_byte_count: u64,
189
190    /// message count received.
191    pub recv_msg_count: u64,
192
193    /// byte count received.
194    pub recv_byte_count: u64,
195}
196
197struct TaskCore {
198    config: Arc<HubConfig>,
199    client: Weak<tx5_signal::SignalConnection>,
200    pub_key: PubKey,
201    cmd_send: CloseSend<ConnCmd>,
202    cmd_recv: CloseRecv<ConnCmd>,
203    msg_send: CloseSend<Vec<u8>>,
204    ready: Arc<tokio::sync::Semaphore>,
205    is_webrtc: Arc<std::sync::atomic::AtomicBool>,
206    send_msg_count: Arc<std::sync::atomic::AtomicU64>,
207    send_byte_count: Arc<std::sync::atomic::AtomicU64>,
208    recv_msg_count: Arc<std::sync::atomic::AtomicU64>,
209    recv_byte_count: Arc<std::sync::atomic::AtomicU64>,
210}
211
212impl TaskCore {
213    async fn handle_recv_msg(
214        &self,
215        msg: Vec<u8>,
216    ) -> std::result::Result<(), ()> {
217        self.recv_msg_count.fetch_add(1, Ordering::Relaxed);
218        self.recv_byte_count
219            .fetch_add(msg.len() as u64, Ordering::Relaxed);
220        if self.msg_send.send(msg).await.is_err() {
221            netaudit!(
222                DEBUG,
223                pub_key = ?self.pub_key,
224                a = "close: msg_send closed",
225            );
226            Err(())
227        } else {
228            Ok(())
229        }
230    }
231
232    fn track_send_msg(&self, len: usize) {
233        self.send_msg_count.fetch_add(1, Ordering::Relaxed);
234        self.send_byte_count
235            .fetch_add(len as u64, Ordering::Relaxed);
236    }
237}
238
239async fn con_task(
240    is_polite: bool,
241    webrtc_config: WebRtcConfig,
242    mut task_core: TaskCore,
243) {
244    // first process the handshake
245    if let Some(client) = task_core.client.upgrade() {
246        let handshake_fut = async {
247            let nonce = client.send_handshake_req(&task_core.pub_key).await?;
248
249            let mut got_peer_res = false;
250            let mut sent_our_res = false;
251
252            while let Some(cmd) = task_core.cmd_recv.recv().await {
253                match cmd {
254                    ConnCmd::SigRecv(sig) => {
255                        use tx5_signal::SignalMessage::*;
256                        match sig {
257                            HandshakeReq(oth_nonce) => {
258                                client
259                                    .send_handshake_res(
260                                        &task_core.pub_key,
261                                        oth_nonce,
262                                    )
263                                    .await?;
264                                sent_our_res = true;
265                            }
266                            HandshakeRes(res_nonce) => {
267                                if res_nonce != nonce {
268                                    return Err(Error::other("nonce mismatch"));
269                                }
270                                got_peer_res = true;
271                            }
272                            // Ignore all other message types...
273                            // they may be from previous sessions
274                            _ => (),
275                        }
276                    }
277                    ConnCmd::SendMessage(_) => {
278                        return Err(Error::other("send before ready"));
279                    }
280                    ConnCmd::WebrtcTimeoutCheck
281                    | ConnCmd::WebrtcRecv(_)
282                    | ConnCmd::WebrtcClosed => {
283                        // only emitted by the webrtc module
284                        // which at this point hasn't yet been initialized
285                        unreachable!()
286                    }
287                }
288                if got_peer_res && sent_our_res {
289                    break;
290                }
291            }
292
293            Result::Ok(())
294        };
295
296        match tokio::time::timeout(
297            task_core.config.signal_config.max_idle,
298            handshake_fut,
299        )
300        .await
301        {
302            Err(_) | Ok(Err(_)) => {
303                client.close_peer(&task_core.pub_key).await;
304                return;
305            }
306            Ok(Ok(_)) => (),
307        }
308    } else {
309        return;
310    }
311
312    // next, attempt webrtc
313    let task_core = match con_task_attempt_webrtc(
314        is_polite,
315        webrtc_config,
316        task_core,
317    )
318    .await
319    {
320        AttemptWebrtcResult::Abort => return,
321        AttemptWebrtcResult::Fallback(task_core) => task_core,
322    };
323
324    task_core.is_webrtc.store(false, Ordering::SeqCst);
325
326    // if webrtc failed in a way that allows us to fall back to sbd,
327    // use the fallback sbd messaging system
328    con_task_fallback_use_signal(task_core).await;
329}
330
331async fn recv_cmd(task_core: &mut TaskCore) -> Option<ConnCmd> {
332    match tokio::time::timeout(
333        task_core.config.signal_config.max_idle,
334        task_core.cmd_recv.recv(),
335    )
336    .await
337    {
338        Err(_) => {
339            netaudit!(
340                DEBUG,
341                pub_key = ?task_core.pub_key,
342                a = "close: connection idle",
343            );
344            None
345        }
346        Ok(None) => {
347            netaudit!(
348                DEBUG,
349                pub_key = ?task_core.pub_key,
350                a = "close: cmd_recv stream complete",
351            );
352            None
353        }
354        Ok(Some(cmd)) => Some(cmd),
355    }
356}
357
358async fn webrtc_task(
359    mut webrtc_recv: CloseRecv<webrtc::WebrtcEvt>,
360    cmd_send: CloseSend<ConnCmd>,
361) {
362    while let Some(evt) = webrtc_recv.recv().await {
363        if cmd_send.send(ConnCmd::WebrtcRecv(evt)).await.is_err() {
364            break;
365        }
366    }
367    netaudit!(DEBUG, a = "webrtc task closed, sending WebrtcClosed",);
368    let _ = cmd_send.send(ConnCmd::WebrtcClosed).await;
369}
370
371enum AttemptWebrtcResult {
372    Abort,
373    Fallback(TaskCore),
374}
375
376async fn con_task_attempt_webrtc(
377    is_polite: bool,
378    webrtc_config: WebRtcConfig,
379    mut task_core: TaskCore,
380) -> AttemptWebrtcResult {
381    use AttemptWebrtcResult::*;
382
383    let timeout_dur = task_core.config.signal_config.max_idle;
384    let timeout_cmd_send = task_core.cmd_send.clone();
385    tokio::task::spawn(async move {
386        tokio::time::sleep(timeout_dur).await;
387        let _ = timeout_cmd_send.send(ConnCmd::WebrtcTimeoutCheck).await;
388    });
389
390    let (webrtc, webrtc_recv) = webrtc::new_backend_module(
391        task_core.config.backend_module,
392        is_polite,
393        webrtc_config,
394        // MAYBE - make this configurable
395        4096,
396    );
397
398    struct AbortWebrtc(tokio::task::AbortHandle);
399
400    impl Drop for AbortWebrtc {
401        fn drop(&mut self) {
402            self.0.abort();
403        }
404    }
405
406    // ensure if we exit this loop that the tokio task is stopped
407    let _abort_webrtc = AbortWebrtc(
408        tokio::task::spawn(webrtc_task(
409            webrtc_recv,
410            task_core.cmd_send.clone(),
411        ))
412        .abort_handle(),
413    );
414
415    let mut is_ready = false;
416
417    #[cfg(test)]
418    if task_core.config.test_fail_webrtc {
419        netaudit!(
420            WARN,
421            pub_key = ?task_core.pub_key,
422            a = "webrtc fallback: test",
423        );
424        return Fallback(task_core);
425    }
426
427    while let Some(cmd) = recv_cmd(&mut task_core).await {
428        use tx5_signal::SignalMessage::*;
429        use webrtc::WebrtcEvt::*;
430        use ConnCmd::*;
431        match cmd {
432            SigRecv(HandshakeReq(_)) | SigRecv(HandshakeRes(_)) => {
433                netaudit!(
434                    DEBUG,
435                    pub_key = ?task_core.pub_key,
436                    a = "close: unexpected handshake msg",
437                );
438                break;
439            }
440            SigRecv(tx5_signal::SignalMessage::Message(msg)) => {
441                if task_core.handle_recv_msg(msg).await.is_err() {
442                    break;
443                }
444                netaudit!(
445                    WARN,
446                    pub_key = ?task_core.pub_key,
447                    a = "webrtc fallback: remote sent us an sbd message",
448                );
449                // if we get a message from the remote, we have to assume
450                // they are switching to fallback mode, and thus we cannot
451                // use webrtc ourselves.
452                return Fallback(task_core);
453            }
454            SigRecv(Offer(offer)) => {
455                netaudit!(
456                    TRACE,
457                    pub_key = ?task_core.pub_key,
458                    offer = String::from_utf8_lossy(&offer).to_string(),
459                    a = "recv_offer",
460                );
461                if let Err(err) = webrtc.in_offer(offer).await {
462                    netaudit!(
463                        WARN,
464                        pub_key = ?task_core.pub_key,
465                        ?err,
466                        a = "webrtc fallback: failed to parse received offer",
467                    );
468                    return Fallback(task_core);
469                }
470            }
471            SigRecv(Answer(answer)) => {
472                netaudit!(
473                    TRACE,
474                    pub_key = ?task_core.pub_key,
475                    offer = String::from_utf8_lossy(&answer).to_string(),
476                    a = "recv_answer",
477                );
478                if let Err(err) = webrtc.in_answer(answer).await {
479                    netaudit!(
480                        WARN,
481                        pub_key = ?task_core.pub_key,
482                        ?err,
483                        a = "webrtc fallback: failed to parse received answer",
484                    );
485                    return Fallback(task_core);
486                }
487            }
488            SigRecv(Ice(ice)) => {
489                netaudit!(
490                    TRACE,
491                    pub_key = ?task_core.pub_key,
492                    offer = String::from_utf8_lossy(&ice).to_string(),
493                    a = "recv_ice",
494                );
495                if let Err(err) = webrtc.in_ice(ice).await {
496                    netaudit!(
497                        DEBUG,
498                        pub_key = ?task_core.pub_key,
499                        ?err,
500                        a = "ignoring webrtc in_ice error",
501                    );
502                    // ice errors are often benign... just ignore it
503                }
504            }
505            SigRecv(Keepalive) | SigRecv(Unknown) => {
506                // these are no-ops
507            }
508            WebrtcRecv(GeneratedOffer(offer)) => {
509                netaudit!(
510                    TRACE,
511                    pub_key = ?task_core.pub_key,
512                    offer = String::from_utf8_lossy(&offer).to_string(),
513                    a = "send_offer",
514                );
515                if let Some(client) = task_core.client.upgrade() {
516                    if let Err(err) =
517                        client.send_offer(&task_core.pub_key, offer).await
518                    {
519                        netaudit!(
520                            DEBUG,
521                            pub_key = ?task_core.pub_key,
522                            ?err,
523                            a = "webrtc send_offer error",
524                        );
525                        break;
526                    }
527                } else {
528                    break;
529                }
530            }
531            WebrtcRecv(GeneratedAnswer(answer)) => {
532                netaudit!(
533                    TRACE,
534                    pub_key = ?task_core.pub_key,
535                    offer = String::from_utf8_lossy(&answer).to_string(),
536                    a = "send_answer",
537                );
538                if let Some(client) = task_core.client.upgrade() {
539                    if let Err(err) =
540                        client.send_answer(&task_core.pub_key, answer).await
541                    {
542                        netaudit!(
543                            DEBUG,
544                            pub_key = ?task_core.pub_key,
545                            ?err,
546                            a = "webrtc send_answer error",
547                        );
548                        break;
549                    }
550                } else {
551                    break;
552                }
553            }
554            WebrtcRecv(GeneratedIce(ice)) => {
555                netaudit!(
556                    TRACE,
557                    pub_key = ?task_core.pub_key,
558                    offer = String::from_utf8_lossy(&ice).to_string(),
559                    a = "send_ice",
560                );
561                if let Some(client) = task_core.client.upgrade() {
562                    if let Err(err) =
563                        client.send_ice(&task_core.pub_key, ice).await
564                    {
565                        netaudit!(
566                            DEBUG,
567                            pub_key = ?task_core.pub_key,
568                            ?err,
569                            a = "webrtc send_ice error",
570                        );
571                        break;
572                    }
573                } else {
574                    break;
575                }
576            }
577            WebrtcRecv(webrtc::WebrtcEvt::Message(msg)) => {
578                if task_core.handle_recv_msg(msg).await.is_err() {
579                    break;
580                }
581            }
582            WebrtcRecv(Ready) => {
583                is_ready = true;
584                task_core.is_webrtc.store(true, Ordering::SeqCst);
585                task_core.ready.close();
586            }
587            SendMessage(msg) => {
588                let len = msg.len();
589
590                netaudit!(
591                    TRACE,
592                    pub_key = ?task_core.pub_key,
593                    byte_len = len,
594                    a = "queue msg for backend send",
595                );
596                if let Err(err) = webrtc.message(msg).await {
597                    netaudit!(
598                        WARN,
599                        pub_key = ?task_core.pub_key,
600                        ?err,
601                        a = "webrtc fallback: failed to send message",
602                    );
603                    return Fallback(task_core);
604                }
605
606                task_core.track_send_msg(len);
607            }
608            WebrtcTimeoutCheck => {
609                if !is_ready {
610                    netaudit!(
611                        WARN,
612                        pub_key = ?task_core.pub_key,
613                        a = "webrtc fallback: failed to ready within timeout",
614                    );
615                    return Fallback(task_core);
616                }
617            }
618            WebrtcClosed => {
619                netaudit!(
620                    WARN,
621                    pub_key = ?task_core.pub_key,
622                    a = "webrtc processing task closed",
623                );
624                break;
625            }
626        }
627    }
628
629    Abort
630}
631
632async fn con_task_fallback_use_signal(mut task_core: TaskCore) {
633    // closing the semaphore causes all the acquire awaits to end
634    task_core.ready.close();
635
636    while let Some(cmd) = recv_cmd(&mut task_core).await {
637        match cmd {
638            ConnCmd::SigRecv(tx5_signal::SignalMessage::Message(msg)) => {
639                if task_core.handle_recv_msg(msg).await.is_err() {
640                    break;
641                }
642            }
643            ConnCmd::SendMessage(msg) => match task_core.client.upgrade() {
644                Some(client) => {
645                    let len = msg.len();
646                    if let Err(err) =
647                        client.send_message(&task_core.pub_key, msg).await
648                    {
649                        netaudit!(
650                            DEBUG,
651                            pub_key = ?task_core.pub_key,
652                            ?err,
653                            a = "close: sbd client send error",
654                        );
655                        break;
656                    }
657                    task_core.track_send_msg(len);
658                }
659                None => {
660                    netaudit!(
661                        DEBUG,
662                        pub_key = ?task_core.pub_key,
663                        a = "close: sbd client closed",
664                    );
665                    break;
666                }
667            },
668            _ => (),
669        }
670    }
671}