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::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(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 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 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 type Rout = BytesMut;
336 type Wout = TaggedBytesMut;
338 type Eout = DataConnectionEvent;
339 type Error = Error;
340 type Time = Instant;
341
342 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 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}