xref: /webrtc/turn/src/allocation/mod.rs (revision 04f0bd9e)
1 #[cfg(test)]
2 mod allocation_test;
3 
4 pub mod allocation_manager;
5 pub mod channel_bind;
6 pub mod five_tuple;
7 pub mod permission;
8 
9 use crate::error::*;
10 use crate::proto::{chandata::*, channum::*, data::*, peeraddr::*, *};
11 use channel_bind::*;
12 use five_tuple::*;
13 use permission::*;
14 
15 use stun::agent::*;
16 use stun::message::*;
17 
18 use util::Conn;
19 
20 use std::collections::HashMap;
21 use std::marker::{Send, Sync};
22 use std::net::SocketAddr;
23 use std::sync::{atomic::AtomicBool, atomic::Ordering, Arc};
24 use tokio::sync::{mpsc, Mutex};
25 use tokio::time::{Duration, Instant};
26 
27 const RTP_MTU: usize = 1500;
28 
29 pub type AllocationMap = Arc<Mutex<HashMap<String, Arc<Mutex<Allocation>>>>>;
30 
31 // Allocation is tied to a FiveTuple and relays traffic
32 // use create_allocation and get_allocation to operate
33 pub struct Allocation {
34     protocol: Protocol,
35     turn_socket: Arc<dyn Conn + Send + Sync>,
36     pub(crate) relay_addr: SocketAddr,
37     pub(crate) relay_socket: Arc<dyn Conn + Send + Sync>,
38     five_tuple: FiveTuple,
39     permissions: Arc<Mutex<HashMap<String, Permission>>>,
40     channel_bindings: Arc<Mutex<HashMap<ChannelNumber, ChannelBind>>>,
41     pub(crate) allocations: Option<AllocationMap>,
42     reset_tx: Option<mpsc::Sender<Duration>>,
43     timer_expired: Arc<AtomicBool>,
44     closed: bool, // Option<mpsc::Receiver<()>>,
45 }
46 
47 fn addr2ipfingerprint(addr: &SocketAddr) -> String {
48     addr.ip().to_string()
49 }
50 
51 impl Allocation {
52     // creates a new instance of NewAllocation.
53     pub fn new(
54         turn_socket: Arc<dyn Conn + Send + Sync>,
55         relay_socket: Arc<dyn Conn + Send + Sync>,
56         relay_addr: SocketAddr,
57         five_tuple: FiveTuple,
58     ) -> Self {
59         Allocation {
60             protocol: PROTO_UDP,
61             turn_socket,
62             relay_addr,
63             relay_socket,
64             five_tuple,
65             permissions: Arc::new(Mutex::new(HashMap::new())),
66             channel_bindings: Arc::new(Mutex::new(HashMap::new())),
67             allocations: None,
68             reset_tx: None,
69             timer_expired: Arc::new(AtomicBool::new(false)),
70             closed: false,
71         }
72     }
73 
74     // has_permission gets the Permission from the allocation
75     pub async fn has_permission(&self, addr: &SocketAddr) -> bool {
76         let permissions = self.permissions.lock().await;
77         permissions.get(&addr2ipfingerprint(addr)).is_some()
78     }
79 
80     // add_permission adds a new permission to the allocation
81     pub async fn add_permission(&self, mut p: Permission) {
82         let fingerprint = addr2ipfingerprint(&p.addr);
83 
84         {
85             let permissions = self.permissions.lock().await;
86             if let Some(existed_permission) = permissions.get(&fingerprint) {
87                 existed_permission.refresh(PERMISSION_TIMEOUT).await;
88                 return;
89             }
90         }
91 
92         p.permissions = Some(Arc::clone(&self.permissions));
93         p.start(PERMISSION_TIMEOUT).await;
94 
95         {
96             let mut permissions = self.permissions.lock().await;
97             permissions.insert(fingerprint, p);
98         }
99     }
100 
101     // remove_permission removes the net.Addr's fingerprint from the allocation's permissions
102     pub async fn remove_permission(&self, addr: &SocketAddr) -> bool {
103         let mut permissions = self.permissions.lock().await;
104         permissions.remove(&addr2ipfingerprint(addr)).is_some()
105     }
106 
107     // add_channel_bind adds a new ChannelBind to the allocation, it also updates the
108     // permissions needed for this ChannelBind
109     pub async fn add_channel_bind(&self, mut c: ChannelBind, lifetime: Duration) -> Result<()> {
110         {
111             if let Some(addr) = self.get_channel_addr(&c.number).await {
112                 if addr != c.peer {
113                     return Err(Error::ErrSameChannelDifferentPeer);
114                 }
115             }
116 
117             if let Some(number) = self.get_channel_number(&c.peer).await {
118                 if number != c.number {
119                     return Err(Error::ErrSameChannelDifferentPeer);
120                 }
121             }
122         }
123 
124         {
125             let channel_bindings = self.channel_bindings.lock().await;
126             if let Some(cb) = channel_bindings.get(&c.number) {
127                 cb.refresh(lifetime).await;
128 
129                 // Channel binds also refresh permissions.
130                 self.add_permission(Permission::new(cb.peer)).await;
131 
132                 return Ok(());
133             }
134         }
135 
136         let peer = c.peer;
137 
138         // Add or refresh this channel.
139         c.channel_bindings = Some(Arc::clone(&self.channel_bindings));
140         c.start(lifetime).await;
141 
142         {
143             let mut channel_bindings = self.channel_bindings.lock().await;
144             channel_bindings.insert(c.number, c);
145         }
146 
147         // Channel binds also refresh permissions.
148         self.add_permission(Permission::new(peer)).await;
149 
150         Ok(())
151     }
152 
153     // remove_channel_bind removes the ChannelBind from this allocation by id
154     pub async fn remove_channel_bind(&self, number: ChannelNumber) -> bool {
155         let mut channel_bindings = self.channel_bindings.lock().await;
156         channel_bindings.remove(&number).is_some()
157     }
158 
159     // get_channel_addr gets the ChannelBind's addr
160     pub async fn get_channel_addr(&self, number: &ChannelNumber) -> Option<SocketAddr> {
161         let channel_bindings = self.channel_bindings.lock().await;
162         channel_bindings.get(number).map(|cb| cb.peer)
163     }
164 
165     // GetChannelByAddr gets the ChannelBind's number from this allocation by net.Addr
166     pub async fn get_channel_number(&self, addr: &SocketAddr) -> Option<ChannelNumber> {
167         let channel_bindings = self.channel_bindings.lock().await;
168         for cb in channel_bindings.values() {
169             if cb.peer == *addr {
170                 return Some(cb.number);
171             }
172         }
173         None
174     }
175 
176     // Close closes the allocation
177     pub async fn close(&mut self) -> Result<()> {
178         if self.closed {
179             return Err(Error::ErrClosed);
180         }
181 
182         self.closed = true;
183         self.stop();
184 
185         {
186             let mut permissions = self.permissions.lock().await;
187             for p in permissions.values_mut() {
188                 p.stop();
189             }
190         }
191 
192         {
193             let mut channel_bindings = self.channel_bindings.lock().await;
194             for c in channel_bindings.values_mut() {
195                 c.stop();
196             }
197         }
198 
199         log::trace!("allocation with {} closed!", self.five_tuple);
200 
201         let _ = self.turn_socket.close().await;
202         let _ = self.relay_socket.close().await;
203 
204         Ok(())
205     }
206 
207     pub async fn start(&mut self, lifetime: Duration) {
208         let (reset_tx, mut reset_rx) = mpsc::channel(1);
209         self.reset_tx = Some(reset_tx);
210 
211         let allocations = self.allocations.clone();
212         let five_tuple = self.five_tuple.clone();
213         let timer_expired = Arc::clone(&self.timer_expired);
214 
215         tokio::spawn(async move {
216             let timer = tokio::time::sleep(lifetime);
217             tokio::pin!(timer);
218             let mut done = false;
219 
220             while !done {
221                 tokio::select! {
222                     _ = &mut timer => {
223                         if let Some(allocs) = &allocations{
224                             let mut alls = allocs.lock().await;
225                             if let Some(a) = alls.remove(&five_tuple.fingerprint()) {
226                                 let mut a = a.lock().await;
227                                 let _ = a.close().await;
228                             }
229                         }
230                         done = true;
231                     },
232                     result = reset_rx.recv() => {
233                         if let Some(d) = result {
234                             timer.as_mut().reset(Instant::now() + d);
235                         } else {
236                             done = true;
237                         }
238                     },
239                 }
240             }
241 
242             timer_expired.store(true, Ordering::SeqCst);
243         });
244     }
245 
246     pub fn stop(&mut self) -> bool {
247         let expired = self.reset_tx.is_none() || self.timer_expired.load(Ordering::SeqCst);
248         self.reset_tx.take();
249         expired
250     }
251 
252     // Refresh updates the allocations lifetime
253     pub async fn refresh(&self, lifetime: Duration) {
254         if let Some(tx) = &self.reset_tx {
255             let _ = tx.send(lifetime).await;
256         }
257     }
258 
259     //  https://tools.ietf.org/html/rfc5766#section-10.3
260     //  When the server receives a UDP datagram at a currently allocated
261     //  relayed transport address, the server looks up the allocation
262     //  associated with the relayed transport address.  The server then
263     //  checks to see whether the set of permissions for the allocation allow
264     //  the relaying of the UDP datagram as described in Section 8.
265     //
266     //  If relaying is permitted, then the server checks if there is a
267     //  channel bound to the peer that sent the UDP datagram (see
268     //  Section 11).  If a channel is bound, then processing proceeds as
269     //  described in Section 11.7.
270     //
271     //  If relaying is permitted but no channel is bound to the peer, then
272     //  the server forms and sends a Data indication.  The Data indication
273     //  MUST contain both an XOR-PEER-ADDRESS and a DATA attribute.  The DATA
274     //  attribute is set to the value of the 'data octets' field from the
275     //  datagram, and the XOR-PEER-ADDRESS attribute is set to the source
276     //  transport address of the received UDP datagram.  The Data indication
277     //  is then sent on the 5-tuple associated with the allocation.
278     async fn packet_handler(&self) {
279         let five_tuple = self.five_tuple.clone();
280         let relay_addr = self.relay_addr;
281         let relay_socket = Arc::clone(&self.relay_socket);
282         let turn_socket = Arc::clone(&self.turn_socket);
283         let allocations = self.allocations.clone();
284         let channel_bindings = Arc::clone(&self.channel_bindings);
285         let permissions = Arc::clone(&self.permissions);
286 
287         tokio::spawn(async move {
288             let mut buffer = vec![0u8; RTP_MTU];
289 
290             loop {
291                 let (n, src_addr) = match relay_socket.recv_from(&mut buffer).await {
292                     Ok((n, src_addr)) => (n, src_addr),
293                     Err(_) => {
294                         if let Some(allocs) = &allocations {
295                             let mut alls = allocs.lock().await;
296                             alls.remove(&five_tuple.fingerprint());
297                         }
298                         break;
299                     }
300                 };
301 
302                 log::debug!(
303                     "relay socket {:?} received {} bytes from {}",
304                     relay_socket.local_addr().await,
305                     n,
306                     src_addr
307                 );
308 
309                 let cb_number = {
310                     let mut cb_number = None;
311                     let cbs = channel_bindings.lock().await;
312                     for cb in cbs.values() {
313                         if cb.peer == src_addr {
314                             cb_number = Some(cb.number);
315                             break;
316                         }
317                     }
318                     cb_number
319                 };
320 
321                 if let Some(number) = cb_number {
322                     let mut channel_data = ChannelData {
323                         data: buffer[..n].to_vec(),
324                         number,
325                         raw: vec![],
326                     };
327                     channel_data.encode();
328 
329                     if let Err(err) = turn_socket
330                         .send_to(&channel_data.raw, five_tuple.src_addr)
331                         .await
332                     {
333                         log::error!(
334                             "Failed to send ChannelData from allocation {} {}",
335                             src_addr,
336                             err
337                         );
338                     }
339                 } else {
340                     let exist = {
341                         let ps = permissions.lock().await;
342                         ps.get(&addr2ipfingerprint(&src_addr)).is_some()
343                     };
344 
345                     if exist {
346                         let msg = {
347                             let peer_address_attr = PeerAddress {
348                                 ip: src_addr.ip(),
349                                 port: src_addr.port(),
350                             };
351                             let data_attr = Data(buffer[..n].to_vec());
352 
353                             let mut msg = Message::new();
354                             if let Err(err) = msg.build(&[
355                                 Box::new(TransactionId::new()),
356                                 Box::new(MessageType::new(METHOD_DATA, CLASS_INDICATION)),
357                                 Box::new(peer_address_attr),
358                                 Box::new(data_attr),
359                             ]) {
360                                 log::error!(
361                                     "Failed to send DataIndication from allocation {} {}",
362                                     src_addr,
363                                     err
364                                 );
365                                 None
366                             } else {
367                                 Some(msg)
368                             }
369                         };
370 
371                         if let Some(msg) = msg {
372                             log::debug!(
373                                 "relaying message from {} to client at {}",
374                                 src_addr,
375                                 five_tuple.src_addr
376                             );
377                             if let Err(err) =
378                                 turn_socket.send_to(&msg.raw, five_tuple.src_addr).await
379                             {
380                                 log::error!(
381                                     "Failed to send DataIndication from allocation {} {}",
382                                     src_addr,
383                                     err
384                                 );
385                             }
386                         }
387                     } else {
388                         log::info!(
389                             "No Permission or Channel exists for {} on allocation {}",
390                             src_addr,
391                             relay_addr
392                         );
393                     }
394                 }
395             }
396         });
397     }
398 }
399