1 #[cfg(test)]
2 mod request_test;
3
4 use crate::allocation::allocation_manager::*;
5 use crate::allocation::channel_bind::ChannelBind;
6 use crate::allocation::five_tuple::*;
7 use crate::allocation::permission::Permission;
8 use crate::auth::*;
9 use crate::error::*;
10 use crate::proto::chandata::ChannelData;
11 use crate::proto::channum::ChannelNumber;
12 use crate::proto::data::Data;
13 use crate::proto::evenport::EvenPort;
14 use crate::proto::lifetime::*;
15 use crate::proto::peeraddr::PeerAddress;
16 use crate::proto::relayaddr::RelayedAddress;
17 use crate::proto::reqtrans::RequestedTransport;
18 use crate::proto::rsrvtoken::ReservationToken;
19 use crate::proto::*;
20
21 use stun::agent::*;
22 use stun::attributes::*;
23 use stun::error_code::*;
24 use stun::fingerprint::*;
25 use stun::integrity::*;
26 use stun::message::*;
27 use stun::textattrs::*;
28 use stun::uattrs::*;
29 use stun::xoraddr::*;
30
31 use util::Conn;
32
33 use std::collections::HashMap;
34 use std::marker::{Send, Sync};
35 use std::net::SocketAddr;
36 #[cfg(feature = "metrics")]
37 use std::sync::atomic::Ordering;
38 use std::sync::Arc;
39 use std::time::SystemTime;
40 use tokio::sync::Mutex;
41 use tokio::time::{Duration, Instant};
42
43 use md5::{Digest, Md5};
44
45 pub(crate) const MAXIMUM_ALLOCATION_LIFETIME: Duration = Duration::from_secs(3600); // https://tools.ietf.org/html/rfc5766#section-6.2 defines 3600 seconds recommendation
46 pub(crate) const NONCE_LIFETIME: Duration = Duration::from_secs(3600); // https://tools.ietf.org/html/rfc5766#section-4
47
48 // Request contains all the state needed to process a single incoming datagram
49 pub struct Request {
50 // Current Request State
51 pub conn: Arc<dyn Conn + Send + Sync>,
52 pub src_addr: SocketAddr,
53 pub buff: Vec<u8>,
54
55 // Server State
56 pub allocation_manager: Arc<Manager>,
57 pub nonces: Arc<Mutex<HashMap<String, Instant>>>,
58
59 // User Configuration
60 pub auth_handler: Arc<dyn AuthHandler + Send + Sync>,
61 pub realm: String,
62 pub channel_bind_timeout: Duration,
63 }
64
65 impl Request {
new( conn: Arc<dyn Conn + Send + Sync>, src_addr: SocketAddr, allocation_manager: Arc<Manager>, auth_handler: Arc<dyn AuthHandler + Send + Sync>, ) -> Self66 pub fn new(
67 conn: Arc<dyn Conn + Send + Sync>,
68 src_addr: SocketAddr,
69 allocation_manager: Arc<Manager>,
70 auth_handler: Arc<dyn AuthHandler + Send + Sync>,
71 ) -> Self {
72 Request {
73 conn,
74 src_addr,
75 buff: vec![],
76 allocation_manager,
77 nonces: Arc::new(Mutex::new(HashMap::new())),
78 auth_handler,
79 realm: String::new(),
80 channel_bind_timeout: Duration::from_secs(0),
81 }
82 }
83
84 // handle_request processes the give Request
handle_request(&mut self) -> Result<()>85 pub async fn handle_request(&mut self) -> Result<()> {
86 /*log::debug!(
87 "received {} bytes of udp from {} on {}",
88 self.buff.len(),
89 self.src_addr,
90 self.conn.local_addr().await?
91 );*/
92
93 if ChannelData::is_channel_data(&self.buff) {
94 self.handle_data_packet().await
95 } else {
96 self.handle_turn_packet().await
97 }
98 }
99
handle_data_packet(&mut self) -> Result<()>100 async fn handle_data_packet(&mut self) -> Result<()> {
101 log::debug!("received DataPacket from {}", self.src_addr);
102 let mut c = ChannelData {
103 raw: self.buff.clone(),
104 ..Default::default()
105 };
106 c.decode()?;
107 self.handle_channel_data(&c).await
108 }
109
handle_turn_packet(&mut self) -> Result<()>110 async fn handle_turn_packet(&mut self) -> Result<()> {
111 log::debug!("handle_turn_packet");
112 let mut m = Message {
113 raw: self.buff.clone(),
114 ..Default::default()
115 };
116 m.decode()?;
117
118 self.process_message_handler(&m).await
119 }
120
process_message_handler(&mut self, m: &Message) -> Result<()>121 async fn process_message_handler(&mut self, m: &Message) -> Result<()> {
122 if m.typ.class == CLASS_INDICATION {
123 match m.typ.method {
124 METHOD_SEND => self.handle_send_indication(m).await,
125 _ => Err(Error::ErrUnexpectedClass),
126 }
127 } else if m.typ.class == CLASS_REQUEST {
128 match m.typ.method {
129 METHOD_ALLOCATE => self.handle_allocate_request(m).await,
130 METHOD_REFRESH => self.handle_refresh_request(m).await,
131 METHOD_CREATE_PERMISSION => self.handle_create_permission_request(m).await,
132 METHOD_CHANNEL_BIND => self.handle_channel_bind_request(m).await,
133 METHOD_BINDING => self.handle_binding_request(m).await,
134 _ => Err(Error::ErrUnexpectedClass),
135 }
136 } else {
137 Err(Error::ErrUnexpectedClass)
138 }
139 }
140
authenticate_request( &mut self, m: &Message, calling_method: Method, ) -> Result<Option<(Username, MessageIntegrity)>>141 pub(crate) async fn authenticate_request(
142 &mut self,
143 m: &Message,
144 calling_method: Method,
145 ) -> Result<Option<(Username, MessageIntegrity)>> {
146 if !m.contains(ATTR_MESSAGE_INTEGRITY) {
147 self.respond_with_nonce(m, calling_method, CODE_UNAUTHORIZED)
148 .await?;
149 return Ok(None);
150 }
151
152 let mut nonce_attr = Nonce::new(ATTR_NONCE, String::new());
153 let mut username_attr = Username::new(ATTR_USERNAME, String::new());
154 let mut realm_attr = Realm::new(ATTR_REALM, String::new());
155 let bad_request_msg = build_msg(
156 m.transaction_id,
157 MessageType::new(calling_method, CLASS_ERROR_RESPONSE),
158 vec![Box::new(ErrorCodeAttribute {
159 code: CODE_BAD_REQUEST,
160 reason: vec![],
161 })],
162 )?;
163
164 if let Err(err) = nonce_attr.get_from(m) {
165 build_and_send_err(&self.conn, self.src_addr, bad_request_msg, err.into()).await?;
166 return Ok(None);
167 }
168
169 let to_be_deleted = {
170 // Assert Nonce exists and is not expired
171 let mut nonces = self.nonces.lock().await;
172
173 let to_be_deleted = if let Some(nonce_creation_time) = nonces.get(&nonce_attr.text) {
174 Instant::now()
175 .checked_duration_since(*nonce_creation_time)
176 .unwrap_or_else(|| Duration::from_secs(0))
177 >= NONCE_LIFETIME
178 } else {
179 true
180 };
181
182 if to_be_deleted {
183 nonces.remove(&nonce_attr.text);
184 }
185 to_be_deleted
186 };
187
188 if to_be_deleted {
189 self.respond_with_nonce(m, calling_method, CODE_STALE_NONCE)
190 .await?;
191 return Ok(None);
192 }
193
194 if let Err(err) = realm_attr.get_from(m) {
195 build_and_send_err(&self.conn, self.src_addr, bad_request_msg, err.into()).await?;
196 return Ok(None);
197 }
198 if let Err(err) = username_attr.get_from(m) {
199 build_and_send_err(&self.conn, self.src_addr, bad_request_msg, err.into()).await?;
200 return Ok(None);
201 }
202
203 let our_key = match self.auth_handler.auth_handle(
204 &username_attr.to_string(),
205 &realm_attr.to_string(),
206 self.src_addr,
207 ) {
208 Ok(key) => key,
209 Err(_) => {
210 build_and_send_err(
211 &self.conn,
212 self.src_addr,
213 bad_request_msg,
214 Error::ErrNoSuchUser,
215 )
216 .await?;
217 return Ok(None);
218 }
219 };
220
221 let mi = MessageIntegrity(our_key);
222 if let Err(err) = mi.check(&mut m.clone()) {
223 build_and_send_err(&self.conn, self.src_addr, bad_request_msg, err.into()).await?;
224 Ok(None)
225 } else {
226 Ok(Some((username_attr, mi)))
227 }
228 }
229
respond_with_nonce( &mut self, m: &Message, calling_method: Method, response_code: ErrorCode, ) -> Result<()>230 async fn respond_with_nonce(
231 &mut self,
232 m: &Message,
233 calling_method: Method,
234 response_code: ErrorCode,
235 ) -> Result<()> {
236 let nonce = build_nonce()?;
237
238 {
239 // Nonce has already been taken
240 let mut nonces = self.nonces.lock().await;
241 if nonces.contains_key(&nonce) {
242 return Err(Error::ErrDuplicatedNonce);
243 }
244 nonces.insert(nonce.clone(), Instant::now());
245 }
246
247 let msg = build_msg(
248 m.transaction_id,
249 MessageType::new(calling_method, CLASS_ERROR_RESPONSE),
250 vec![
251 Box::new(ErrorCodeAttribute {
252 code: response_code,
253 reason: vec![],
254 }),
255 Box::new(Nonce::new(ATTR_NONCE, nonce)),
256 Box::new(Realm::new(ATTR_REALM, self.realm.clone())),
257 ],
258 )?;
259
260 build_and_send(&self.conn, self.src_addr, msg).await
261 }
262
handle_binding_request(&mut self, m: &Message) -> Result<()>263 pub(crate) async fn handle_binding_request(&mut self, m: &Message) -> Result<()> {
264 log::debug!("received BindingRequest from {}", self.src_addr);
265
266 let (ip, port) = (self.src_addr.ip(), self.src_addr.port());
267
268 let msg = build_msg(
269 m.transaction_id,
270 BINDING_SUCCESS,
271 vec![
272 Box::new(XorMappedAddress { ip, port }),
273 Box::new(FINGERPRINT),
274 ],
275 )?;
276
277 build_and_send(&self.conn, self.src_addr, msg).await
278 }
279
280 // // https://tools.ietf.org/html/rfc5766#section-6.2
handle_allocate_request(&mut self, m: &Message) -> Result<()>281 pub(crate) async fn handle_allocate_request(&mut self, m: &Message) -> Result<()> {
282 log::debug!("received AllocateRequest from {}", self.src_addr);
283
284 // 1. The server MUST require that the request be authenticated. This
285 // authentication MUST be done using the long-term credential
286 // mechanism of [https://tools.ietf.org/html/rfc5389#section-10.2.2]
287 // unless the client and server agree to use another mechanism through
288 // some procedure outside the scope of this document.
289 let (username, message_integrity) =
290 if let Some(mi) = self.authenticate_request(m, METHOD_ALLOCATE).await? {
291 mi
292 } else {
293 log::debug!("no MessageIntegrity");
294 return Ok(());
295 };
296
297 let five_tuple = FiveTuple {
298 src_addr: self.src_addr,
299 dst_addr: self.conn.local_addr()?,
300 protocol: PROTO_UDP,
301 };
302 let mut requested_port = 0;
303 let mut reservation_token = "".to_owned();
304
305 // 2. The server checks if the 5-tuple is currently in use by an
306 // existing allocation. If yes, the server rejects the request with
307 // a 437 (Allocation Mismatch) error.
308 if self
309 .allocation_manager
310 .get_allocation(&five_tuple)
311 .await
312 .is_some()
313 {
314 let msg = build_msg(
315 m.transaction_id,
316 MessageType::new(METHOD_ALLOCATE, CLASS_ERROR_RESPONSE),
317 vec![Box::new(ErrorCodeAttribute {
318 code: CODE_ALLOC_MISMATCH,
319 reason: vec![],
320 })],
321 )?;
322 return build_and_send_err(
323 &self.conn,
324 self.src_addr,
325 msg,
326 Error::ErrRelayAlreadyAllocatedForFiveTuple,
327 )
328 .await;
329 }
330
331 // 3. The server checks if the request contains a REQUESTED-TRANSPORT
332 // attribute. If the REQUESTED-TRANSPORT attribute is not included
333 // or is malformed, the server rejects the request with a 400 (Bad
334 // Request) error. Otherwise, if the attribute is included but
335 // specifies a protocol other that UDP, the server rejects the
336 // request with a 442 (Unsupported Transport Protocol) error.
337 let mut requested_transport = RequestedTransport::default();
338 if let Err(err) = requested_transport.get_from(m) {
339 let bad_request_msg = build_msg(
340 m.transaction_id,
341 MessageType::new(METHOD_ALLOCATE, CLASS_ERROR_RESPONSE),
342 vec![Box::new(ErrorCodeAttribute {
343 code: CODE_BAD_REQUEST,
344 reason: vec![],
345 })],
346 )?;
347 return build_and_send_err(&self.conn, self.src_addr, bad_request_msg, err.into())
348 .await;
349 } else if requested_transport.protocol != PROTO_UDP {
350 let msg = build_msg(
351 m.transaction_id,
352 MessageType::new(METHOD_ALLOCATE, CLASS_ERROR_RESPONSE),
353 vec![Box::new(ErrorCodeAttribute {
354 code: CODE_UNSUPPORTED_TRANS_PROTO,
355 reason: vec![],
356 })],
357 )?;
358 return build_and_send_err(
359 &self.conn,
360 self.src_addr,
361 msg,
362 Error::ErrRequestedTransportMustBeUdp,
363 )
364 .await;
365 }
366
367 // 4. The request may contain a DONT-FRAGMENT attribute. If it does,
368 // but the server does not support sending UDP datagrams with the DF
369 // bit set to 1 (see Section 12), then the server treats the DONT-
370 // FRAGMENT attribute in the Allocate request as an unknown
371 // comprehension-required attribute.
372 if m.contains(ATTR_DONT_FRAGMENT) {
373 let msg = build_msg(
374 m.transaction_id,
375 MessageType::new(METHOD_ALLOCATE, CLASS_ERROR_RESPONSE),
376 vec![
377 Box::new(ErrorCodeAttribute {
378 code: CODE_UNKNOWN_ATTRIBUTE,
379 reason: vec![],
380 }),
381 Box::new(UnknownAttributes(vec![ATTR_DONT_FRAGMENT])),
382 ],
383 )?;
384 return build_and_send_err(
385 &self.conn,
386 self.src_addr,
387 msg,
388 Error::ErrNoDontFragmentSupport,
389 )
390 .await;
391 }
392
393 // 5. The server checks if the request contains a RESERVATION-TOKEN
394 // attribute. If yes, and the request also contains an EVEN-PORT
395 // attribute, then the server rejects the request with a 400 (Bad
396 // Request) error. Otherwise, it checks to see if the token is
397 // valid (i.e., the token is in range and has not expired and the
398 // corresponding relayed transport address is still available). If
399 // the token is not valid for some reason, the server rejects the
400 // request with a 508 (Insufficient Capacity) error.
401 let mut reservation_token_attr = ReservationToken::default();
402 if reservation_token_attr.get_from(m).is_ok() {
403 let mut even_port = EvenPort::default();
404 if even_port.get_from(m).is_ok() {
405 let bad_request_msg = build_msg(
406 m.transaction_id,
407 MessageType::new(METHOD_ALLOCATE, CLASS_ERROR_RESPONSE),
408 vec![Box::new(ErrorCodeAttribute {
409 code: CODE_BAD_REQUEST,
410 reason: vec![],
411 })],
412 )?;
413 return build_and_send_err(
414 &self.conn,
415 self.src_addr,
416 bad_request_msg,
417 Error::ErrRequestWithReservationTokenAndEvenPort,
418 )
419 .await;
420 }
421 }
422
423 // 6. The server checks if the request contains an EVEN-PORT attribute.
424 // If yes, then the server checks that it can satisfy the request
425 // (i.e., can allocate a relayed transport address as described
426 // below). If the server cannot satisfy the request, then the
427 // server rejects the request with a 508 (Insufficient Capacity)
428 // error.
429 let mut even_port = EvenPort::default();
430 if even_port.get_from(m).is_ok() {
431 let mut random_port = 1;
432
433 while random_port % 2 != 0 {
434 random_port = match self.allocation_manager.get_random_even_port().await {
435 Ok(port) => port,
436 Err(err) => {
437 let insufficent_capacity_msg = build_msg(
438 m.transaction_id,
439 MessageType::new(METHOD_ALLOCATE, CLASS_ERROR_RESPONSE),
440 vec![Box::new(ErrorCodeAttribute {
441 code: CODE_INSUFFICIENT_CAPACITY,
442 reason: vec![],
443 })],
444 )?;
445 return build_and_send_err(
446 &self.conn,
447 self.src_addr,
448 insufficent_capacity_msg,
449 err,
450 )
451 .await;
452 }
453 };
454 }
455
456 requested_port = random_port;
457 reservation_token = rand_seq(8);
458 }
459
460 // 7. At any point, the server MAY choose to reject the request with a
461 // 486 (Allocation Quota Reached) error if it feels the client is
462 // trying to exceed some locally defined allocation quota. The
463 // server is free to define this allocation quota any way it wishes,
464 // but SHOULD define it based on the username used to authenticate
465 // the request, and not on the client's transport address.
466
467 // 8. Also at any point, the server MAY choose to reject the request
468 // with a 300 (Try Alternate) error if it wishes to redirect the
469 // client to a different server. The use of this error code and
470 // attribute follow the specification in [RFC5389].
471 let lifetime_duration = allocation_lifetime(m);
472 let a = match self
473 .allocation_manager
474 .create_allocation(
475 five_tuple,
476 Arc::clone(&self.conn),
477 requested_port,
478 lifetime_duration,
479 username,
480 )
481 .await
482 {
483 Ok(a) => a,
484 Err(err) => {
485 let insufficent_capacity_msg = build_msg(
486 m.transaction_id,
487 MessageType::new(METHOD_ALLOCATE, CLASS_ERROR_RESPONSE),
488 vec![Box::new(ErrorCodeAttribute {
489 code: CODE_INSUFFICIENT_CAPACITY,
490 reason: vec![],
491 })],
492 )?;
493 return build_and_send_err(
494 &self.conn,
495 self.src_addr,
496 insufficent_capacity_msg,
497 err,
498 )
499 .await;
500 }
501 };
502
503 // Once the allocation is created, the server replies with a success
504 // response. The success response contains:
505 // * An XOR-RELAYED-ADDRESS attribute containing the relayed transport
506 // address.
507 // * A LIFETIME attribute containing the current value of the time-to-
508 // expiry timer.
509 // * A RESERVATION-TOKEN attribute (if a second relayed transport
510 // address was reserved).
511 // * An XOR-MAPPED-ADDRESS attribute containing the client's IP address
512 // and port (from the 5-tuple).
513
514 let (src_ip, src_port) = (self.src_addr.ip(), self.src_addr.port());
515 let relay_ip = a.relay_addr.ip();
516 let relay_port = a.relay_addr.port();
517
518 let msg = {
519 if !reservation_token.is_empty() {
520 self.allocation_manager
521 .create_reservation(reservation_token.clone(), relay_port)
522 .await;
523 }
524
525 let mut response_attrs: Vec<Box<dyn Setter>> = vec![
526 Box::new(RelayedAddress {
527 ip: relay_ip,
528 port: relay_port,
529 }),
530 Box::new(Lifetime(lifetime_duration)),
531 Box::new(XorMappedAddress {
532 ip: src_ip,
533 port: src_port,
534 }),
535 ];
536
537 if !reservation_token.is_empty() {
538 response_attrs.push(Box::new(ReservationToken(
539 reservation_token.as_bytes().to_vec(),
540 )));
541 }
542
543 response_attrs.push(Box::new(message_integrity));
544 build_msg(
545 m.transaction_id,
546 MessageType::new(METHOD_ALLOCATE, CLASS_SUCCESS_RESPONSE),
547 response_attrs,
548 )?
549 };
550
551 build_and_send(&self.conn, self.src_addr, msg).await
552 }
553
handle_refresh_request(&mut self, m: &Message) -> Result<()>554 pub(crate) async fn handle_refresh_request(&mut self, m: &Message) -> Result<()> {
555 log::debug!("received RefreshRequest from {}", self.src_addr);
556
557 let (_, message_integrity) =
558 if let Some(mi) = self.authenticate_request(m, METHOD_REFRESH).await? {
559 mi
560 } else {
561 log::debug!("no MessageIntegrity");
562 return Ok(());
563 };
564
565 let lifetime_duration = allocation_lifetime(m);
566 let five_tuple = FiveTuple {
567 src_addr: self.src_addr,
568 dst_addr: self.conn.local_addr()?,
569 protocol: PROTO_UDP,
570 };
571
572 if lifetime_duration != Duration::from_secs(0) {
573 let a = self.allocation_manager.get_allocation(&five_tuple).await;
574 if let Some(a) = a {
575 a.refresh(lifetime_duration).await;
576 } else {
577 return Err(Error::ErrNoAllocationFound);
578 }
579 } else {
580 self.allocation_manager.delete_allocation(&five_tuple).await;
581 }
582
583 let msg = build_msg(
584 m.transaction_id,
585 MessageType::new(METHOD_REFRESH, CLASS_SUCCESS_RESPONSE),
586 vec![
587 Box::new(Lifetime(lifetime_duration)),
588 Box::new(message_integrity),
589 ],
590 )?;
591
592 build_and_send(&self.conn, self.src_addr, msg).await
593 }
594
handle_create_permission_request(&mut self, m: &Message) -> Result<()>595 pub(crate) async fn handle_create_permission_request(&mut self, m: &Message) -> Result<()> {
596 log::debug!("received CreatePermission from {}", self.src_addr);
597
598 let a = self
599 .allocation_manager
600 .get_allocation(&FiveTuple {
601 src_addr: self.src_addr,
602 dst_addr: self.conn.local_addr()?,
603 protocol: PROTO_UDP,
604 })
605 .await;
606
607 if let Some(a) = a {
608 let (_, message_integrity) = if let Some(mi) = self
609 .authenticate_request(m, METHOD_CREATE_PERMISSION)
610 .await?
611 {
612 mi
613 } else {
614 log::debug!("no MessageIntegrity");
615 return Ok(());
616 };
617 let mut add_count = 0;
618
619 {
620 for attr in &m.attributes.0 {
621 if attr.typ != ATTR_XOR_PEER_ADDRESS {
622 continue;
623 }
624
625 let mut peer_address = PeerAddress::default();
626 if peer_address.get_from(m).is_err() {
627 add_count = 0;
628 break;
629 }
630
631 log::debug!(
632 "adding permission for {}",
633 format!("{}:{}", peer_address.ip, peer_address.port)
634 );
635
636 a.add_permission(Permission::new(SocketAddr::new(
637 peer_address.ip,
638 peer_address.port,
639 )))
640 .await;
641 add_count += 1;
642 }
643 }
644
645 let mut resp_class = CLASS_SUCCESS_RESPONSE;
646 if add_count == 0 {
647 resp_class = CLASS_ERROR_RESPONSE;
648 }
649
650 let msg = build_msg(
651 m.transaction_id,
652 MessageType::new(METHOD_CREATE_PERMISSION, resp_class),
653 vec![Box::new(message_integrity)],
654 )?;
655
656 build_and_send(&self.conn, self.src_addr, msg).await
657 } else {
658 Err(Error::ErrNoAllocationFound)
659 }
660 }
661
handle_send_indication(&mut self, m: &Message) -> Result<()>662 pub(crate) async fn handle_send_indication(&mut self, m: &Message) -> Result<()> {
663 log::debug!("received SendIndication from {}", self.src_addr);
664
665 let a = self
666 .allocation_manager
667 .get_allocation(&FiveTuple {
668 src_addr: self.src_addr,
669 dst_addr: self.conn.local_addr()?,
670 protocol: PROTO_UDP,
671 })
672 .await;
673
674 if let Some(a) = a {
675 let mut data_attr = Data::default();
676 data_attr.get_from(m)?;
677
678 let mut peer_address = PeerAddress::default();
679 peer_address.get_from(m)?;
680
681 let msg_dst = SocketAddr::new(peer_address.ip, peer_address.port);
682
683 let has_perm = a.has_permission(&msg_dst).await;
684 if !has_perm {
685 return Err(Error::ErrNoPermission);
686 }
687
688 let l = a.relay_socket.send_to(&data_attr.0, msg_dst).await?;
689 if l != data_attr.0.len() {
690 Err(Error::ErrShortWrite)
691 } else {
692 #[cfg(feature = "metrics")]
693 a.relayed_bytes
694 .fetch_add(data_attr.0.len(), Ordering::AcqRel);
695
696 Ok(())
697 }
698 } else {
699 Err(Error::ErrNoAllocationFound)
700 }
701 }
702
handle_channel_bind_request(&mut self, m: &Message) -> Result<()>703 pub(crate) async fn handle_channel_bind_request(&mut self, m: &Message) -> Result<()> {
704 log::debug!("received ChannelBindRequest from {}", self.src_addr);
705
706 let a = self
707 .allocation_manager
708 .get_allocation(&FiveTuple {
709 src_addr: self.src_addr,
710 dst_addr: self.conn.local_addr()?,
711 protocol: PROTO_UDP,
712 })
713 .await;
714
715 if let Some(a) = a {
716 let bad_request_msg = build_msg(
717 m.transaction_id,
718 MessageType::new(METHOD_CHANNEL_BIND, CLASS_ERROR_RESPONSE),
719 vec![Box::new(ErrorCodeAttribute {
720 code: CODE_BAD_REQUEST,
721 reason: vec![],
722 })],
723 )?;
724
725 let (_, message_integrity) =
726 if let Some(mi) = self.authenticate_request(m, METHOD_CHANNEL_BIND).await? {
727 mi
728 } else {
729 log::debug!("no MessageIntegrity");
730 return Ok(());
731 };
732 let mut channel = ChannelNumber::default();
733 if let Err(err) = channel.get_from(m) {
734 return build_and_send_err(&self.conn, self.src_addr, bad_request_msg, err.into())
735 .await;
736 }
737
738 let mut peer_addr = PeerAddress::default();
739 if let Err(err) = peer_addr.get_from(m) {
740 return build_and_send_err(&self.conn, self.src_addr, bad_request_msg, err.into())
741 .await;
742 }
743
744 log::debug!(
745 "binding channel {} to {}",
746 channel,
747 format!("{}:{}", peer_addr.ip, peer_addr.port)
748 );
749
750 let result = {
751 a.add_channel_bind(
752 ChannelBind::new(channel, SocketAddr::new(peer_addr.ip, peer_addr.port)),
753 self.channel_bind_timeout,
754 )
755 .await
756 };
757 if let Err(err) = result {
758 return build_and_send_err(&self.conn, self.src_addr, bad_request_msg, err).await;
759 }
760
761 let msg = build_msg(
762 m.transaction_id,
763 MessageType::new(METHOD_CHANNEL_BIND, CLASS_SUCCESS_RESPONSE),
764 vec![Box::new(message_integrity)],
765 )?;
766 build_and_send(&self.conn, self.src_addr, msg).await
767 } else {
768 Err(Error::ErrNoAllocationFound)
769 }
770 }
771
handle_channel_data(&mut self, c: &ChannelData) -> Result<()>772 pub(crate) async fn handle_channel_data(&mut self, c: &ChannelData) -> Result<()> {
773 log::debug!("received ChannelData from {}", self.src_addr);
774
775 let a = self
776 .allocation_manager
777 .get_allocation(&FiveTuple {
778 src_addr: self.src_addr,
779 dst_addr: self.conn.local_addr()?,
780 protocol: PROTO_UDP,
781 })
782 .await;
783
784 if let Some(a) = a {
785 let channel = a.get_channel_addr(&c.number).await;
786 if let Some(peer) = channel {
787 let l = a.relay_socket.send_to(&c.data, peer).await?;
788 if l != c.data.len() {
789 Err(Error::ErrShortWrite)
790 } else {
791 #[cfg(feature = "metrics")]
792 a.relayed_bytes.fetch_add(c.data.len(), Ordering::AcqRel);
793
794 Ok(())
795 }
796 } else {
797 Err(Error::ErrNoSuchChannelBind)
798 }
799 } else {
800 Err(Error::ErrNoAllocationFound)
801 }
802 }
803 }
804
rand_seq(n: usize) -> String805 pub(crate) fn rand_seq(n: usize) -> String {
806 let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".as_bytes();
807 let mut buf = vec![0u8; n];
808 for b in &mut buf {
809 *b = letters[rand::random::<usize>() % letters.len()];
810 }
811 if let Ok(s) = String::from_utf8(buf) {
812 s
813 } else {
814 String::new()
815 }
816 }
817
build_nonce() -> Result<String>818 pub(crate) fn build_nonce() -> Result<String> {
819 /* #nosec */
820 let mut s = String::new();
821 s.push_str(
822 format!(
823 "{}",
824 SystemTime::now()
825 .duration_since(SystemTime::UNIX_EPOCH)?
826 .as_nanos()
827 )
828 .as_str(),
829 );
830 s.push_str(format!("{}", rand::random::<u64>()).as_str());
831
832 let mut h = Md5::new();
833 h.update(s.as_bytes());
834 Ok(format!("{:x}", h.finalize()))
835 }
836
build_and_send( conn: &Arc<dyn Conn + Send + Sync>, dst: SocketAddr, msg: Message, ) -> Result<()>837 pub(crate) async fn build_and_send(
838 conn: &Arc<dyn Conn + Send + Sync>,
839 dst: SocketAddr,
840 msg: Message,
841 ) -> Result<()> {
842 let _ = conn.send_to(&msg.raw, dst).await?;
843 Ok(())
844 }
845
846 // Send a STUN packet and return the original error to the caller
build_and_send_err( conn: &Arc<dyn Conn + Send + Sync>, dst: SocketAddr, msg: Message, err: Error, ) -> Result<()>847 pub(crate) async fn build_and_send_err(
848 conn: &Arc<dyn Conn + Send + Sync>,
849 dst: SocketAddr,
850 msg: Message,
851 err: Error,
852 ) -> Result<()> {
853 build_and_send(conn, dst, msg).await?;
854
855 Err(err)
856 }
857
build_msg( transaction_id: TransactionId, msg_type: MessageType, mut additional: Vec<Box<dyn Setter>>, ) -> Result<Message>858 pub(crate) fn build_msg(
859 transaction_id: TransactionId,
860 msg_type: MessageType,
861 mut additional: Vec<Box<dyn Setter>>,
862 ) -> Result<Message> {
863 let mut attrs: Vec<Box<dyn Setter>> = vec![
864 Box::new(Message {
865 transaction_id,
866 ..Default::default()
867 }),
868 Box::new(msg_type),
869 ];
870
871 attrs.append(&mut additional);
872
873 let mut msg = Message::new();
874 msg.build(&attrs)?;
875 Ok(msg)
876 }
877
allocation_lifetime(m: &Message) -> Duration878 pub(crate) fn allocation_lifetime(m: &Message) -> Duration {
879 let mut lifetime_duration = DEFAULT_LIFETIME;
880
881 let mut lifetime = Lifetime::default();
882 if lifetime.get_from(m).is_ok() && lifetime.0 < MAXIMUM_ALLOCATION_LIFETIME {
883 lifetime_duration = lifetime.0;
884 }
885
886 lifetime_duration
887 }
888