medea_turn/transport/
mod.rs1mod 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#[derive(Debug)]
30pub enum Request {
31 Message(Message<Attribute>),
35
36 ChannelData(ChannelData),
40}
41
42#[async_trait]
47pub trait Transport {
48 async fn recv_from(&self) -> Result<(Request, SocketAddr), Error>;
54
55 async fn send_to(
61 &self,
62 data: Cow<'_, [u8]>,
63 target: SocketAddr,
64 ) -> Result<(), Error>;
65
66 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 fn local_addr(&self) -> SocketAddr;
86
87 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( 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
137pub(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#[derive(Debug, Display, From, Eq, PartialEq, StdError)]
163#[expect( variant_size_differences,
165 reason = "`io::Error` is pointer-sized"
166)]
167pub enum Error {
168 #[display("Underlying TCP/UDP transport is dead")]
170 TransportIsDead,
171
172 #[display("Failed to encode STUN/TURN message: {_0:?}")]
174 #[from(ignore)]
175 Encode(#[error(not(source))] bytecodec::ErrorKind),
176
177 #[display("Failed to decode STUN/TURN message: {_0:?}")]
179 Decode(#[error(not(source))] bytecodec::ErrorKind),
180
181 #[from(chandata::FormatError)]
185 ChannelData(chandata::FormatError),
186
187 #[display("I/O error: {_0}")]
189 #[from(io::Error, IoError)]
190 Io(IoError),
191}
192
193#[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}