turn/relay/
relay_static.rs

1use std::net::IpAddr;
2
3use async_trait::async_trait;
4use util::vnet::net::*;
5
6use super::*;
7use crate::error::*;
8
9/// `RelayAddressGeneratorStatic` can be used to return static IP address each time a relay is created.
10/// This can be used when you have a single static IP address that you want to use.
11pub struct RelayAddressGeneratorStatic {
12    /// `relay_address` is the IP returned to the user when the relay is created.
13    pub relay_address: IpAddr,
14
15    /// `address` is passed to Listen/ListenPacket when creating the Relay.
16    pub address: String,
17
18    pub net: Arc<Net>,
19}
20
21#[async_trait]
22impl RelayAddressGenerator for RelayAddressGeneratorStatic {
23    fn validate(&self) -> Result<()> {
24        if self.address.is_empty() {
25            Err(Error::ErrListeningAddressInvalid)
26        } else {
27            Ok(())
28        }
29    }
30
31    async fn allocate_conn(
32        &self,
33        use_ipv4: bool,
34        requested_port: u16,
35    ) -> Result<(Arc<dyn Conn + Send + Sync>, SocketAddr)> {
36        let addr = self
37            .net
38            .resolve_addr(use_ipv4, &format!("{}:{}", self.address, requested_port))
39            .await?;
40        let conn = self.net.bind(addr).await?;
41        let mut relay_addr = conn.local_addr()?;
42        relay_addr.set_ip(self.relay_address);
43        return Ok((conn, relay_addr));
44    }
45}