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
use parking_lot::Mutex;
use std::collections::HashMap;
use std::io;
use std::net::SocketAddr;
use std::time::Duration;
use stun_types::parse::ParsedMessage;
use tokio::sync::oneshot;
use tokio::time::timeout;

pub mod auth;

pub trait TransportInfo {
    fn reliable(&self) -> bool;
}

pub struct Request<'r, T> {
    pub bytes: &'r [u8],
    pub tsx_id: u128,
    pub transport: &'r T,
}

pub struct IncomingMessage<T> {
    pub message: ParsedMessage,
    pub source: SocketAddr,
    pub transport: T,
}

/// Defines the "user" of a [`StunEndpoint`].
///
/// It is designed to be somewhat flexible and transport agnostic.
///
/// When using a [`StunEndpoint`] for multiple transports `UserData`
/// can be used to either pass the transport around directly or
/// have just be an identifying key.
#[async_trait::async_trait]
pub trait StunEndpointUser: Send + Sync {
    type Transport: TransportInfo + Send + Sync;

    /// Send the given `bytes` to `target` with the given `transport`.
    async fn send_to(
        &self,
        bytes: &[u8],
        target: SocketAddr,
        transport: &Self::Transport,
    ) -> io::Result<()>;

    /// Called by [`StunEndpoint::receive`] when it encounters a message
    /// without a matching transaction id.
    async fn receive(&self, message: IncomingMessage<Self::Transport>);
}

/// Transport agnostic endpoint. Uses [`StunEndpointUser`] to define
/// send/receive behavior.
pub struct StunEndpoint<U: StunEndpointUser> {
    user: U,
    transactions: Mutex<HashMap<u128, Transaction>>,
}

struct Transaction {
    sender: oneshot::Sender<ParsedMessage>,
}

impl<U: StunEndpointUser> StunEndpoint<U> {
    pub fn new(user: U) -> Self {
        Self {
            user,
            transactions: Default::default(),
        }
    }

    pub fn user(&self) -> &U {
        &self.user
    }

    pub fn user_mut(&mut self) -> &mut U {
        &mut self.user
    }

    pub async fn send_request(
        &self,
        request: Request<'_, U::Transport>,
        target: SocketAddr,
    ) -> io::Result<Option<ParsedMessage>> {
        struct DropGuard<'s, U>(&'s StunEndpoint<U>, u128)
        where
            U: StunEndpointUser;

        impl<U> Drop for DropGuard<'_, U>
        where
            U: StunEndpointUser,
        {
            fn drop(&mut self) {
                self.0.transactions.lock().remove(&self.1);
            }
        }

        let _guard = DropGuard(self, request.tsx_id);

        let (tx, mut rx) = oneshot::channel();
        self.transactions
            .lock()
            .insert(request.tsx_id, Transaction { sender: tx });

        let mut delta = Duration::from_millis(500);

        if request.transport.reliable() {
            match timeout(delta, &mut rx).await {
                Ok(Ok(response)) => Ok(Some(response)),
                Ok(Err(_)) => unreachable!(),
                Err(_) => Ok(None),
            }
        } else {
            for _ in 0..7 {
                self.user
                    .send_to(request.bytes, target, request.transport)
                    .await?;

                match timeout(delta, &mut rx).await {
                    Ok(Ok(response)) => return Ok(Some(response)),
                    Ok(Err(_)) => unreachable!(),
                    Err(_) => {
                        delta *= 2;
                    }
                }
            }

            Ok(None)
        }
    }

    /// Pass a received STUN message to the endpoint for further processing
    pub async fn receive(
        &self,
        message: ParsedMessage,
        source: SocketAddr,
        transport: U::Transport,
    ) {
        {
            let mut transactions = self.transactions.lock();
            if let Some(Transaction { sender }) = transactions.remove(&message.tsx_id) {
                let _ = sender.send(message);
                return;
            }
        }

        self.user
            .receive(IncomingMessage {
                source,
                message,
                transport,
            })
            .await;
    }
}