Skip to main content

medea_turn/transport/
mod.rs

1//! [STUN]/[TURN] transport definitions.
2//!
3//! [STUN]: https://en.wikipedia.org/wiki/STUN
4//! [TURN]: https://en.wikipedia.org/wiki/TURN
5
6mod tcp;
7
8use std::{borrow::Cow, io, net::SocketAddr};
9
10use async_trait::async_trait;
11use bytecodec::{DecodeExt as _, EncodeExt as _};
12use derive_more::with_trait::{Display, Error as StdError, From};
13use stun_codec::{Message, MessageDecoder, MessageEncoder};
14pub use tokio::net::UdpSocket;
15use tokio::net::{self, ToSocketAddrs};
16
17pub use self::tcp::Server as TcpServer;
18use crate::{
19    attr::{Attribute, PROTO_UDP},
20    chandata,
21    chandata::ChannelData,
22    server::INBOUND_MTU,
23};
24
25/// Parsed ingress [STUN]/[TURN] message.
26///
27/// [STUN]: https://en.wikipedia.org/wiki/STUN
28/// [TURN]: https://en.wikipedia.org/wiki/TURN
29#[derive(Debug)]
30pub enum Request {
31    /// [STUN Message].
32    ///
33    /// [STUN Message]: https://tools.ietf.org/html/rfc5389#section-6
34    Message(Message<Attribute>),
35
36    /// [TURN ChannelData Message][1].
37    ///
38    /// [1]: https://tools.ietf.org/html/rfc5766#section-11.4
39    ChannelData(ChannelData),
40}
41
42/// Abstraction of [STUN]/[TURN] transport implementation.
43///
44/// [STUN]: https://en.wikipedia.org/wiki/STUN
45/// [TURN]: https://en.wikipedia.org/wiki/TURN
46#[async_trait]
47pub trait Transport {
48    /// Receives a [`Request`] datagram message.
49    ///
50    /// # Errors
51    ///
52    /// See the [`Error`] for details.
53    async fn recv_from(&self) -> Result<(Request, SocketAddr), Error>;
54
55    /// Sends `data` to the provided [`SocketAddr`].
56    ///
57    /// # Errors
58    ///
59    /// See the [`Error`] for details.
60    async fn send_to(
61        &self,
62        data: Cow<'_, [u8]>,
63        target: SocketAddr,
64    ) -> Result<(), Error>;
65
66    /// Encodes and sends the provided [`Message`] to the provided
67    /// [`SocketAddr`] via the provided [`Transport`].
68    ///
69    /// # Errors
70    ///
71    /// See the [`Error`] for details.
72    async fn send_msg_to(
73        &self,
74        msg: Message<Attribute>,
75        dst: SocketAddr,
76    ) -> Result<(), Error> {
77        let bytes = MessageEncoder::new()
78            .encode_into_bytes(msg)
79            .map_err(|e| Error::Encode(*e.kind()))?;
80
81        self.send_to(Cow::Owned(bytes), dst).await
82    }
83
84    /// Returns the local [`SocketAddr`] of this [`Transport`].
85    fn local_addr(&self) -> SocketAddr;
86
87    /// Returns the protocol number of this [`Transport`] according to [IANA].
88    ///
89    /// [IANA]: https://tinyurl.com/iana-protocol-numbers
90    fn proto(&self) -> u8;
91}
92
93#[async_trait]
94impl Transport for UdpSocket {
95    async fn recv_from(&self) -> Result<(Request, SocketAddr), Error> {
96        let mut buf = vec![0u8; INBOUND_MTU];
97        let (n, addr) = self.recv_from(&mut buf).await?;
98
99        let msg = if ChannelData::is_channel_data(&buf[0..n]) {
100            buf.truncate(n);
101            let data = ChannelData::decode(buf)?;
102
103            Request::ChannelData(data)
104        } else {
105            let msg = MessageDecoder::<Attribute>::new()
106                .decode_from_bytes(&buf[0..n])
107                .map_err(|e| Error::Decode(*e.kind()))?
108                .map_err(|e| Error::Decode(*e.error().kind()))?;
109
110            Request::Message(msg)
111        };
112
113        Ok((msg, addr))
114    }
115
116    async fn send_to(
117        &self,
118        data: Cow<'_, [u8]>,
119        target: SocketAddr,
120    ) -> Result<(), Error> {
121        Ok(self.send_to(&data, target).await.map(|_| ())?)
122    }
123
124    fn local_addr(&self) -> SocketAddr {
125        #[expect( // intentional
126            clippy::unwrap_used,
127            reason = "called on the bound `UdpSocket` only"
128        )]
129        self.local_addr().unwrap()
130    }
131
132    fn proto(&self) -> u8 {
133        PROTO_UDP
134    }
135}
136
137/// Performs a DNS resolution of the provided `host`.
138///
139/// # Errors
140///
141/// If the provided `host` cannot be resolved to IP address.
142pub(crate) async fn lookup_host(
143    use_ipv4: bool,
144    host: impl ToSocketAddrs,
145) -> Result<SocketAddr, Error> {
146    for remote_addr in net::lookup_host(host).await? {
147        if (use_ipv4 && remote_addr.is_ipv4())
148            || (!use_ipv4 && remote_addr.is_ipv6())
149        {
150            return Ok(remote_addr);
151        }
152    }
153
154    Err(io::Error::other(format!(
155        "No available {} IP address found!",
156        if use_ipv4 { "ipv4" } else { "ipv6" },
157    ))
158    .into())
159}
160
161/// Possible errors of a [`Transport`].
162#[derive(Debug, Display, From, Eq, PartialEq, StdError)]
163#[expect( // false positive
164    variant_size_differences,
165    reason = "`io::Error` is pointer-sized"
166)]
167pub enum Error {
168    /// Tried to use a dead [`Transport`].
169    #[display("Underlying TCP/UDP transport is dead")]
170    TransportIsDead,
171
172    /// Failed to encode a [`Message`].
173    #[display("Failed to encode STUN/TURN message: {_0:?}")]
174    #[from(ignore)]
175    Encode(#[error(not(source))] bytecodec::ErrorKind),
176
177    /// Failed to decode message.
178    #[display("Failed to decode STUN/TURN message: {_0:?}")]
179    Decode(#[error(not(source))] bytecodec::ErrorKind),
180
181    /// [TURN ChannelData][1] format error.
182    ///
183    /// [1]: https://tools.ietf.org/html/rfc5766#section-11.4
184    #[from(chandata::FormatError)]
185    ChannelData(chandata::FormatError),
186
187    /// I/O error of the [`Transport`].
188    #[display("I/O error: {_0}")]
189    #[from(io::Error, IoError)]
190    Io(IoError),
191}
192
193/// [`io::Error`] implementing [`Eq`] and [`PartialEq`] by its [`kind`].
194///
195/// [`kind`]: io::Error::kind()
196#[derive(Debug, Display, From, StdError)]
197pub struct IoError(pub io::Error);
198
199impl Eq for IoError {}
200
201impl PartialEq for IoError {
202    fn eq(&self, other: &Self) -> bool {
203        self.0.kind() == other.0.kind()
204    }
205}
206
207#[cfg(test)]
208mod lookup_host_spec {
209    use super::lookup_host;
210
211    #[tokio::test]
212    async fn considers_ip_version() {
213        let stun_serv_addr = "stun1.l.google.com:19302";
214
215        if let Ok(ipv4_addr) = lookup_host(true, stun_serv_addr).await {
216            assert!(
217                ipv4_addr.is_ipv4(),
218                "expected ipv4 but got ipv6: {ipv4_addr}",
219            );
220        }
221
222        if let Ok(ipv6_addr) = lookup_host(false, stun_serv_addr).await {
223            assert!(
224                ipv6_addr.is_ipv6(),
225                "expected ipv6 but got ipv4: {ipv6_addr}",
226            );
227        }
228    }
229
230    #[tokio::test]
231    async fn resolves_localhost() {
232        let udp_addr = lookup_host(true, "localhost:1234").await.unwrap();
233
234        assert_eq!(udp_addr.ip().to_string(), "127.0.0.1");
235        assert_eq!(udp_addr.port(), 1234);
236
237        let res = lookup_host(false, "127.0.0.1:1234").await;
238
239        assert!(res.is_err(), "expected error, got: {res:?}");
240    }
241}