Skip to main content

rtci_turn/client/
data_connection.rs

1//! The client data connection of a TCP allocation (RFC 6062 §4.3 to §4.5).
2use std::collections::VecDeque;
3use std::net::SocketAddr;
4use std::ops::Add;
5use std::sync::Arc;
6use std::time::{Duration, Instant};
7
8use bytes::BytesMut;
9use crypto::RTCCryptoProvider;
10use log::debug;
11use stun::error_code::*;
12use stun::fingerprint::FINGERPRINT;
13use stun::message::*;
14use stun::textattrs::*;
15use stun::validated::Rejection;
16
17use super::credential::Credential;
18use super::{RequestError, validator};
19use crate::proto::connid::ConnectionId;
20use shared::error::{Error, Result};
21use shared::{TaggedBytesMut, TransportContext, TransportMessage, TransportProtocol};
22
23/// How long the ConnectionBind may go unanswered. The server gives a new peer connection 30
24/// seconds to be bound and then closes it (RFC 6062 §5.2, §5.3), so nothing can answer later.
25pub const CONNECTION_BIND_TIMEOUT: Duration = Duration::from_secs(30);
26
27/// What a [`DataConnection`] reports.
28#[derive(Debug, PartialEq)]
29#[non_exhaustive]
30pub enum DataConnectionEvent {
31    /// The server accepted the ConnectionBind: the connection now carries the peer's bytes
32    /// and nothing else, both ways (RFC 6062 §4.5).
33    Bound,
34    /// The ConnectionBind failed, or went unanswered for [`CONNECTION_BIND_TIMEOUT`]. The
35    /// connection is of no use; the application closes it.
36    BindError(RequestError),
37}
38
39enum State {
40    /// The ConnectionBind `id` is out.
41    Binding {
42        id: TransactionId,
43        deadline: Instant,
44        /// Whether it was already sent again after a 401 / after a 438.
45        challenged: bool,
46        stale: bool,
47    },
48    Bound,
49    Failed,
50    Closed,
51}
52
53/// One client data connection of a TCP allocation: a second TCP (or TLS) connection to the
54/// TURN server that, once bound, carries one peer's byte stream as it is (RFC 6062 §4.3 to
55/// §4.5).
56///
57/// Made by [`Relay::data_connection`](super::relay::Relay::data_connection) with the
58/// CONNECTION-ID of a Connect success response ([`Event::ConnectResponse`](super::Event)) or
59/// of a ConnectionAttempt indication ([`Event::ConnectionAttempt`](super::Event)). Sans-I/O:
60/// the application opens the connection, to [`Self::server_addr`] and from a local port of
61/// its own, and then
62///
63/// - sends what [`poll_write`](sansio::Protocol::poll_write) gives, the ConnectionBind
64///   request first;
65/// - hands every chunk it reads to [`handle_read`](sansio::Protocol::handle_read) (the
66///   stream as it comes: no framing is expected of the application);
67/// - calls [`handle_timeout`](sansio::Protocol::handle_timeout) when
68///   [`poll_timeout`](sansio::Protocol::poll_timeout) says;
69/// - after [`DataConnectionEvent::Bound`], writes to the peer with
70///   [`handle_write`](sansio::Protocol::handle_write) or [`Self::send`], and takes the
71///   peer's bytes from [`poll_read`](sansio::Protocol::poll_read).
72///
73/// Closing the TCP connection ends the peer's connection too (RFC 6062 §4.6). The allocation
74/// must be kept refreshed for as long as the data connection is wanted, which the
75/// [`Client`](super::Client) that made it does on its control connection.
76pub struct DataConnection {
77    crypto_provider: Arc<dyn RTCCryptoProvider>,
78    server_addr: SocketAddr,
79    local_addr: SocketAddr,
80    connection_id: ConnectionId,
81    software: Software,
82    /// The long-term credential of the control connection, as the server's last challenge
83    /// on either connection left it; none when the server asked for no credential there.
84    credential: Arc<Credential>,
85    /// The ConnectionBind that is out, as it was sent.
86    request: Message,
87    state: State,
88    /// The stream so far, until the ConnectionBind response is whole.
89    inbound: BytesMut,
90    transmits: VecDeque<TaggedBytesMut>,
91    reads: VecDeque<BytesMut>,
92    events: VecDeque<DataConnectionEvent>,
93}
94
95pub(crate) struct DataConnectionConfig {
96    pub(crate) crypto_provider: Arc<dyn RTCCryptoProvider>,
97    pub(crate) server_addr: SocketAddr,
98    pub(crate) local_addr: SocketAddr,
99    pub(crate) connection_id: ConnectionId,
100    pub(crate) software: Software,
101    pub(crate) credential: Arc<Credential>,
102}
103
104impl DataConnection {
105    /// A data connection that has its ConnectionBind queued.
106    pub(crate) fn new(now: Instant, config: DataConnectionConfig) -> Result<Self> {
107        let mut connection = DataConnection {
108            crypto_provider: config.crypto_provider,
109            server_addr: config.server_addr,
110            local_addr: config.local_addr,
111            connection_id: config.connection_id,
112            software: config.software,
113            credential: config.credential,
114            request: Message::new(),
115            state: State::Closed,
116            inbound: BytesMut::new(),
117            transmits: VecDeque::new(),
118            reads: VecDeque::new(),
119            events: VecDeque::new(),
120        };
121        let id = connection.send_bind(now)?;
122        connection.state = State::Binding {
123            id,
124            deadline: now.add(CONNECTION_BIND_TIMEOUT),
125            challenged: false,
126            stale: false,
127        };
128        Ok(connection)
129    }
130
131    /// The server's transport address: where the application opens this connection to, the
132    /// same one the control connection goes to (RFC 6062 §4.3).
133    #[must_use]
134    pub fn server_addr(&self) -> SocketAddr {
135        self.server_addr
136    }
137
138    /// The local address the application said this connection is made from.
139    #[must_use]
140    pub fn local_addr(&self) -> SocketAddr {
141        self.local_addr
142    }
143
144    /// The CONNECTION-ID this connection binds.
145    #[must_use]
146    pub fn connection_id(&self) -> ConnectionId {
147        self.connection_id
148    }
149
150    /// Whether the server accepted the ConnectionBind, so the connection carries the peer's
151    /// bytes.
152    #[must_use]
153    pub fn is_bound(&self) -> bool {
154        matches!(self.state, State::Bound)
155    }
156
157    /// Queues `data` for the peer, as it is.
158    ///
159    /// # Errors
160    ///
161    /// Fails until the connection is bound, and after it failed or was closed.
162    pub fn send(&mut self, now: Instant, data: &[u8]) -> Result<()> {
163        if !self.is_bound() {
164            return Err(Error::ErrConnClosed);
165        }
166        self.transmit(now, data);
167        Ok(())
168    }
169
170    fn transmit(&mut self, now: Instant, data: &[u8]) {
171        self.transmits.push_back(TransportMessage {
172            now,
173            transport: TransportContext {
174                local_addr: self.local_addr,
175                peer_addr: self.server_addr,
176                transport_protocol: TransportProtocol::TCP,
177                ecn: None,
178            },
179            message: BytesMut::from(data),
180        });
181    }
182
183    /// Queues the ConnectionBind request: the CONNECTION-ID and the credential of the control
184    /// connection (RFC 6062 §4.3, §4.4).
185    fn send_bind(&mut self, now: Instant) -> Result<TransactionId> {
186        let id = TransactionId::new();
187        let mut setters: Vec<Box<dyn Setter + '_>> = vec![
188            Box::new(id),
189            Box::new(MessageType::new(METHOD_CONNECTION_BIND, CLASS_REQUEST)),
190            Box::new(self.connection_id),
191        ];
192        if !self.software.text.is_empty() {
193            setters.push(Box::new(self.software.clone()));
194        }
195        if let Some(authentication) = self.credential.setter(self.crypto_provider.crypto()) {
196            setters.push(authentication);
197        }
198        setters.push(Box::new(FINGERPRINT));
199        let mut msg = Message::new();
200        msg.build(&setters)?;
201        drop(setters);
202        self.transmit(now, &msg.raw);
203        self.request = msg;
204        Ok(id)
205    }
206
207    fn fail(&mut self, err: RequestError) {
208        debug!("data connection {}: {err}", self.connection_id);
209        self.state = State::Failed;
210        self.inbound.clear();
211        self.events.push_back(DataConnectionEvent::BindError(err));
212    }
213
214    /// Takes the ConnectionBind response off the front of the stream, once it is whole.
215    fn read_response(&mut self, now: Instant) -> Result<()> {
216        loop {
217            let State::Binding {
218                id,
219                deadline,
220                challenged,
221                stale,
222            } = self.state
223            else {
224                return Ok(());
225            };
226            if self.inbound.len() < MESSAGE_HEADER_SIZE {
227                return Ok(());
228            }
229            // Until the bind is answered the server sends STUN and nothing else.
230            if self.inbound[0] & 0xc0 != 0 || !is_stun_message(&self.inbound) {
231                self.fail(RequestError::Failed(Error::ErrNonStunmessage));
232                return Err(Error::ErrNonStunmessage);
233            }
234            let length = usize::from(u16::from_be_bytes([self.inbound[2], self.inbound[3]]));
235            let total = MESSAGE_HEADER_SIZE + length;
236            if self.inbound.len() < total {
237                return Ok(());
238            }
239            let raw = self.inbound.split_to(total);
240            let mut msg = Message::new();
241            msg.raw = raw.to_vec();
242            if let Err(err) = msg.decode() {
243                self.fail(RequestError::Failed(Error::Other(err.to_string())));
244                return Err(err);
245            }
246            // Only the answer to the request that is out counts; a response to one that was
247            // sent again, or anything else, is passed over.
248            if msg.transaction_id != id
249                || msg.typ.method != METHOD_CONNECTION_BIND
250                || (msg.typ.class != CLASS_SUCCESS_RESPONSE
251                    && msg.typ.class != CLASS_ERROR_RESPONSE)
252            {
253                debug!("data connection {}: ignoring {msg}", self.connection_id);
254                continue;
255            }
256            // As on the control connection (RFC 8489 §6.3, §9, §9.2.5): the response to a
257            // signed request is signed with the same key, and nothing after its integrity
258            // attribute is read. This is a reliable transport, so a response that is not
259            // authentic ends the transaction at once, as an integrity violation; so does one
260            // with an attribute the client has to but does not understand.
261            let msg = match self.credential.check_response(
262                &msg,
263                &validator(),
264                self.crypto_provider.crypto(),
265            ) {
266                Ok(valid) => valid,
267                Err(Rejection::IntegrityMissing | Rejection::IntegrityMismatch) => {
268                    debug!(
269                        "data connection {}: {msg}: integrity attribute missing or wrong",
270                        self.connection_id
271                    );
272                    self.fail(RequestError::Failed(Error::ErrIntegrityMismatch));
273                    return Ok(());
274                }
275                Err(rejection) => {
276                    self.fail(RequestError::Failed(Error::Other(rejection.to_string())));
277                    return Ok(());
278                }
279            };
280
281            if msg.typ.class == CLASS_SUCCESS_RESPONSE {
282                self.state = State::Bound;
283                self.events.push_back(DataConnectionEvent::Bound);
284                // Whatever follows the response is the peer's.
285                if !self.inbound.is_empty() {
286                    let rest = self.inbound.split();
287                    self.reads.push_back(rest);
288                }
289                return Ok(());
290            }
291
292            let err = RequestError::of(&msg);
293            // The server's nonces may be the connection's own: a 401 or 438 is answered once
294            // each with the same request and what the response asks for, by the rules of the
295            // control connection (RFC 8489 §9.2.5).
296            let again = if err.is(CODE_UNAUTHORIZED) && !challenged {
297                Some((true, stale))
298            } else if err.is(CODE_STALE_NONCE) && !stale {
299                Some((challenged, true))
300            } else {
301                None
302            };
303            if let Some((challenged, stale)) = again {
304                match self
305                    .credential
306                    .challenged(&self.request, &msg, self.crypto_provider.crypto())
307                {
308                    Ok(credential) => {
309                        self.credential = Arc::new(credential);
310                        let id = self.send_bind(now)?;
311                        self.state = State::Binding {
312                            id,
313                            deadline,
314                            challenged,
315                            stale,
316                        };
317                        continue;
318                    }
319                    Err(refused) => {
320                        debug!(
321                            "data connection {}: {err} is not answered: {refused}",
322                            self.connection_id
323                        );
324                    }
325                }
326            }
327            self.fail(err);
328            return Ok(());
329        }
330    }
331}
332
333impl sansio::Protocol<TaggedBytesMut, TaggedBytesMut, ()> for DataConnection {
334    /// The peer's bytes.
335    type Rout = BytesMut;
336    /// Bytes for the TCP connection to the server.
337    type Wout = TaggedBytesMut;
338    type Eout = DataConnectionEvent;
339    type Error = Error;
340    type Time = Instant;
341
342    /// Takes the next chunk read from the TCP connection, whatever its boundaries.
343    fn handle_read(&mut self, msg: TaggedBytesMut) -> Result<()> {
344        match self.state {
345            State::Bound => {
346                if !msg.message.is_empty() {
347                    self.reads.push_back(msg.message);
348                }
349                Ok(())
350            }
351            State::Binding { .. } => {
352                self.inbound.extend_from_slice(&msg.message);
353                self.read_response(msg.now)
354            }
355            State::Failed | State::Closed => Ok(()),
356        }
357    }
358
359    fn poll_read(&mut self) -> Option<Self::Rout> {
360        self.reads.pop_front()
361    }
362
363    /// Queues `msg.message` for the peer, as it is. `msg.transport` is not looked at.
364    fn handle_write(&mut self, msg: TaggedBytesMut) -> Result<()> {
365        self.send(msg.now, &msg.message)
366    }
367
368    fn poll_write(&mut self) -> Option<Self::Wout> {
369        self.transmits.pop_front()
370    }
371
372    fn poll_event(&mut self) -> Option<Self::Eout> {
373        self.events.pop_front()
374    }
375
376    fn handle_timeout(&mut self, now: Instant) -> Result<()> {
377        if let State::Binding { deadline, .. } = self.state
378            && deadline <= now
379        {
380            self.fail(RequestError::Failed(Error::ErrTimeout));
381        }
382        Ok(())
383    }
384
385    fn poll_timeout(&mut self) -> Option<Instant> {
386        match self.state {
387            State::Binding { deadline, .. } => Some(deadline),
388            _ => None,
389        }
390    }
391
392    fn close(&mut self) -> Result<()> {
393        self.state = State::Closed;
394        self.inbound.clear();
395        self.transmits.clear();
396        Ok(())
397    }
398}