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::{Checked, 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(Checked::Valid(valid)) => valid,
267                Ok(Checked::NeverReceived) => {
268                    // RFC 8489 §9.2.5: an unsigned 400 is discarded as if it had never
269                    // arrived; the bind waits on, until its deadline.
270                    debug!(
271                        "data connection {}: {msg}: discarded as never received",
272                        self.connection_id
273                    );
274                    continue;
275                }
276                Err(Rejection::IntegrityMissing | Rejection::IntegrityMismatch) => {
277                    debug!(
278                        "data connection {}: {msg}: integrity attribute missing or wrong",
279                        self.connection_id
280                    );
281                    self.fail(RequestError::Failed(Error::ErrIntegrityMismatch));
282                    return Ok(());
283                }
284                Err(rejection) => {
285                    self.fail(RequestError::Failed(Error::Other(rejection.to_string())));
286                    return Ok(());
287                }
288            };
289
290            if msg.typ.class == CLASS_SUCCESS_RESPONSE {
291                self.state = State::Bound;
292                self.events.push_back(DataConnectionEvent::Bound);
293                // Whatever follows the response is the peer's.
294                if !self.inbound.is_empty() {
295                    let rest = self.inbound.split();
296                    self.reads.push_back(rest);
297                }
298                return Ok(());
299            }
300
301            let err = RequestError::of(&msg);
302            // The server's nonces may be the connection's own: a 401 or 438 is answered once
303            // each with the same request and what the response asks for, by the rules of the
304            // control connection (RFC 8489 §9.2.5).
305            let again = if err.is(CODE_UNAUTHORIZED) && !challenged {
306                Some((true, stale))
307            } else if err.is(CODE_STALE_NONCE) && !stale {
308                Some((challenged, true))
309            } else {
310                None
311            };
312            if let Some((challenged, stale)) = again {
313                match self
314                    .credential
315                    .challenged(&self.request, &msg, self.crypto_provider.crypto())
316                {
317                    Ok(credential) => {
318                        self.credential = Arc::new(credential);
319                        let id = self.send_bind(now)?;
320                        self.state = State::Binding {
321                            id,
322                            deadline,
323                            challenged,
324                            stale,
325                        };
326                        continue;
327                    }
328                    Err(refused) => {
329                        debug!(
330                            "data connection {}: {err} is not answered: {refused}",
331                            self.connection_id
332                        );
333                    }
334                }
335            }
336            self.fail(err);
337            return Ok(());
338        }
339    }
340}
341
342impl sansio::Protocol<TaggedBytesMut, TaggedBytesMut, ()> for DataConnection {
343    /// The peer's bytes.
344    type Rout = BytesMut;
345    /// Bytes for the TCP connection to the server.
346    type Wout = TaggedBytesMut;
347    type Eout = DataConnectionEvent;
348    type Error = Error;
349    type Time = Instant;
350
351    /// Takes the next chunk read from the TCP connection, whatever its boundaries.
352    fn handle_read(&mut self, msg: TaggedBytesMut) -> Result<()> {
353        match self.state {
354            State::Bound => {
355                if !msg.message.is_empty() {
356                    self.reads.push_back(msg.message);
357                }
358                Ok(())
359            }
360            State::Binding { .. } => {
361                self.inbound.extend_from_slice(&msg.message);
362                self.read_response(msg.now)
363            }
364            State::Failed | State::Closed => Ok(()),
365        }
366    }
367
368    fn poll_read(&mut self) -> Option<Self::Rout> {
369        self.reads.pop_front()
370    }
371
372    /// Queues `msg.message` for the peer, as it is. `msg.transport` is not looked at.
373    fn handle_write(&mut self, msg: TaggedBytesMut) -> Result<()> {
374        self.send(msg.now, &msg.message)
375    }
376
377    fn poll_write(&mut self) -> Option<Self::Wout> {
378        self.transmits.pop_front()
379    }
380
381    fn poll_event(&mut self) -> Option<Self::Eout> {
382        self.events.pop_front()
383    }
384
385    fn handle_timeout(&mut self, now: Instant) -> Result<()> {
386        if let State::Binding { deadline, .. } = self.state
387            && deadline <= now
388        {
389            self.fail(RequestError::Failed(Error::ErrTimeout));
390        }
391        Ok(())
392    }
393
394    fn poll_timeout(&mut self) -> Option<Instant> {
395        match self.state {
396            State::Binding { deadline, .. } => Some(deadline),
397            _ => None,
398        }
399    }
400
401    fn close(&mut self) -> Result<()> {
402        self.state = State::Closed;
403        self.inbound.clear();
404        self.transmits.clear();
405        Ok(())
406    }
407}