1use 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
23pub const CONNECTION_BIND_TIMEOUT: Duration = Duration::from_secs(30);
26
27#[derive(Debug, PartialEq)]
29#[non_exhaustive]
30pub enum DataConnectionEvent {
31 Bound,
34 BindError(RequestError),
37}
38
39enum State {
40 Binding {
42 id: TransactionId,
43 deadline: Instant,
44 challenged: bool,
46 stale: bool,
47 },
48 Bound,
49 Failed,
50 Closed,
51}
52
53pub struct DataConnection {
77 crypto_provider: Arc<dyn RTCCryptoProvider>,
78 server_addr: SocketAddr,
79 local_addr: SocketAddr,
80 connection_id: ConnectionId,
81 software: Software,
82 credential: Arc<Credential>,
85 request: Message,
87 state: State,
88 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 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 #[must_use]
134 pub fn server_addr(&self) -> SocketAddr {
135 self.server_addr
136 }
137
138 #[must_use]
140 pub fn local_addr(&self) -> SocketAddr {
141 self.local_addr
142 }
143
144 #[must_use]
146 pub fn connection_id(&self) -> ConnectionId {
147 self.connection_id
148 }
149
150 #[must_use]
153 pub fn is_bound(&self) -> bool {
154 matches!(self.state, State::Bound)
155 }
156
157 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 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 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 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 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 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 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 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 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 type Rout = BytesMut;
345 type Wout = TaggedBytesMut;
347 type Eout = DataConnectionEvent;
348 type Error = Error;
349 type Time = Instant;
350
351 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 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}