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
mod obfs_tls;
mod obfs_udp;
use std::{ops::Deref, sync::Arc};

use async_trait::async_trait;
use bytes::Bytes;
pub use obfs_tls::*;
pub use obfs_udp::*;

use smol::future::FutureExt;

/// Abstracts over any "pipe" that can carry datagrams along one particular path. This should almost always be used in conjunction with [crate::Multiplex].
#[async_trait]
pub trait Pipe: Send + Sync + 'static {
    /// Sends a datagram to the other side. Should never block; if the datagram cannot be sent quickly it should simply be dropped.
    ///
    /// Datagrams of at least 65535 bytes must be accepted, but larger datagrams might not be.
    async fn send(&self, to_send: Bytes);

    /// Receives the next datagram from the other side. If the pipe has failed, this must return an error promptly.
    async fn recv(&self) -> std::io::Result<Bytes>;

    /// Return a static string slice that identifies the protocol.
    fn protocol(&self) -> &str;

    /// Return a static string slice that contains arbitrary metadata, set by the peer.
    fn peer_metadata(&self) -> &str;

    /// Return a protocol-specific address identifying the other side.
    fn peer_addr(&self) -> String;
}

#[async_trait]
impl<P: Pipe + ?Sized, T: Deref<Target = P> + Send + Sync + 'static> Pipe for T {
    async fn send(&self, to_send: Bytes) {
        self.deref().send(to_send).await
    }

    async fn recv(&self) -> std::io::Result<Bytes> {
        self.deref().recv().await
    }

    fn protocol(&self) -> &str {
        self.deref().protocol()
    }

    fn peer_metadata(&self) -> &str {
        self.deref().peer_metadata()
    }

    fn peer_addr(&self) -> String {
        self.deref().peer_addr()
    }
}

/// Abstracts over any "listener" that can receive [Pipe]s.
///
/// To avoid "viral generics", trait objects are returned.
#[async_trait]
pub trait PipeListener: Sized + Send + Sync {
    /// Accepts the next pipe at this listener.
    async fn accept_pipe(&self) -> std::io::Result<Arc<dyn Pipe>>;

    /// Combines this PipeListener with another PipeListener.
    fn or<T: PipeListener>(self, other: T) -> OrPipeListener<Self, T> {
        OrPipeListener {
            left: self,
            right: other,
        }
    }
}

pub struct OrPipeListener<T: PipeListener + Sized, U: PipeListener + Sized> {
    left: T,
    right: U,
}

#[async_trait]
impl<T: PipeListener, U: PipeListener> PipeListener for OrPipeListener<T, U> {
    async fn accept_pipe(&self) -> std::io::Result<Arc<dyn Pipe>> {
        self.left.accept_pipe().or(self.right.accept_pipe()).await
    }
}