1use std::fmt;
4#[cfg(any(
5 all(feature = "dummy", not(target_family = "wasm")),
6 all(feature = "native-webrtc", not(target_family = "wasm")),
7 all(feature = "web-sys-webrtc", target_family = "wasm")
8))]
9use std::sync::Arc;
10
11use crate::core::transport::SharedTransport;
12
13#[derive(Clone, Copy, Debug, Eq, PartialEq)]
22pub struct UdpPortRange {
23 min: u16,
25 max: u16,
27}
28
29impl UdpPortRange {
30 pub const fn new(min: u16, max: u16) -> Result<Self, UdpPortRangeError> {
37 if min == 0 || max == 0 {
38 return Err(UdpPortRangeError::ZeroBound { min, max });
39 }
40 if min > max {
41 return Err(UdpPortRangeError::Inverted { min, max });
42 }
43
44 Ok(Self { min, max })
45 }
46
47 pub const fn from_optional_bounds(
56 min: Option<u16>,
57 max: Option<u16>,
58 ) -> Result<Option<Self>, UdpPortRangeError> {
59 match (min, max) {
60 (None, None) => Ok(None),
61 (Some(min), Some(max)) => match Self::new(min, max) {
62 Ok(range) => Ok(Some(range)),
63 Err(err) => Err(err),
64 },
65 (min, max) => Err(UdpPortRangeError::IncompleteBounds { min, max }),
66 }
67 }
68
69 pub const fn min(self) -> u16 {
71 self.min
72 }
73
74 pub const fn max(self) -> u16 {
76 self.max
77 }
78}
79
80#[derive(Clone, Copy, Debug, Eq, PartialEq)]
82pub enum UdpPortRangeError {
83 ZeroBound {
85 min: u16,
87 max: u16,
89 },
90 Inverted {
92 min: u16,
94 max: u16,
96 },
97 IncompleteBounds {
99 min: Option<u16>,
101 max: Option<u16>,
103 },
104}
105
106impl fmt::Display for UdpPortRangeError {
107 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108 match self {
109 Self::ZeroBound { min, max } => write!(
110 f,
111 "UDP port range bounds must be non-zero: min={min}, max={max}"
112 ),
113 Self::Inverted { min, max } => {
114 write!(f, "UDP port range min must be <= max: min={min}, max={max}")
115 }
116 Self::IncompleteBounds { min, max } => write!(
117 f,
118 "Both UDP port range bounds must be set together: min={min:?}, max={max:?}"
119 ),
120 }
121 }
122}
123
124impl std::error::Error for UdpPortRangeError {}
125
126#[derive(Clone, Debug, Default, Eq, PartialEq)]
132pub struct TransportNetworkConfig {
133 traversal_servers: String,
135 endpoint_hint: Option<String>,
137 udp_port_range: Option<UdpPortRange>,
139}
140
141impl TransportNetworkConfig {
142 pub fn new(
145 traversal_servers: impl Into<String>,
146 endpoint_hint: Option<String>,
147 udp_port_range: Option<UdpPortRange>,
148 ) -> Self {
149 Self {
150 traversal_servers: traversal_servers.into(),
151 endpoint_hint,
152 udp_port_range,
153 }
154 }
155
156 pub fn with_endpoint_hint(mut self, endpoint_hint: Option<String>) -> Self {
158 self.endpoint_hint = endpoint_hint;
159 self
160 }
161
162 pub const fn with_udp_port_range(mut self, udp_port_range: Option<UdpPortRange>) -> Self {
164 self.udp_port_range = udp_port_range;
165 self
166 }
167
168 pub fn endpoint_hint(&self) -> Option<&str> {
170 self.endpoint_hint.as_deref()
171 }
172
173 pub const fn udp_port_range(&self) -> Option<UdpPortRange> {
175 self.udp_port_range
176 }
177
178 pub fn traversal_servers(&self) -> &str {
180 &self.traversal_servers
181 }
182
183 #[cfg(any(
191 all(
192 not(target_family = "wasm"),
193 any(feature = "native-webrtc", feature = "dummy")
194 ),
195 all(target_family = "wasm", feature = "web-sys-webrtc")
196 ))]
197 pub fn build_shared_transport(
198 &self,
199 initial_session_credential: Option<&str>,
200 ) -> SharedTransport {
201 let credentials = initial_session_credential.unwrap_or(&self.traversal_servers);
202 #[cfg(all(feature = "native-webrtc", not(target_family = "wasm")))]
203 {
204 Arc::new(crate::connections::WebrtcTransport::new(
205 credentials,
206 self.endpoint_hint.clone(),
207 self.udp_port_range,
208 ))
209 }
210 #[cfg(all(
211 feature = "dummy",
212 not(feature = "native-webrtc"),
213 not(target_family = "wasm")
214 ))]
215 {
216 Arc::new(crate::connections::DummyTransport::new(
217 credentials,
218 self.endpoint_hint.clone(),
219 self.udp_port_range,
220 ))
221 }
222 #[cfg(all(feature = "web-sys-webrtc", target_family = "wasm"))]
223 {
224 #[allow(clippy::arc_with_non_send_sync)]
227 Arc::new(crate::connections::WebSysWebrtcTransport::new(
228 credentials,
229 self.endpoint_hint.clone(),
230 self.udp_port_range,
231 ))
232 }
233 }
234
235 #[cfg(any(
239 all(
240 not(target_family = "wasm"),
241 any(feature = "native-webrtc", feature = "dummy")
242 ),
243 all(target_family = "wasm", feature = "web-sys-webrtc")
244 ))]
245 pub fn try_build_shared_transport(
246 &self,
247 initial_session_credential: Option<&str>,
248 ) -> crate::error::Result<SharedTransport> {
249 let credentials = initial_session_credential.unwrap_or(&self.traversal_servers);
250 #[cfg(all(feature = "native-webrtc", not(target_family = "wasm")))]
251 {
252 Ok(Arc::new(crate::connections::WebrtcTransport::new_strict(
253 credentials,
254 self.endpoint_hint.clone(),
255 self.udp_port_range,
256 )?))
257 }
258 #[cfg(all(
259 feature = "dummy",
260 not(feature = "native-webrtc"),
261 not(target_family = "wasm")
262 ))]
263 {
264 Ok(Arc::new(crate::connections::DummyTransport::new_strict(
265 credentials,
266 self.endpoint_hint.clone(),
267 self.udp_port_range,
268 )?))
269 }
270 #[cfg(all(feature = "web-sys-webrtc", target_family = "wasm"))]
271 {
272 #[allow(clippy::arc_with_non_send_sync)]
273 let transport = Arc::new(crate::connections::WebSysWebrtcTransport::new_strict(
274 credentials,
275 self.endpoint_hint.clone(),
276 self.udp_port_range,
277 )?);
278 Ok(transport)
279 }
280 }
281
282 #[cfg(all(feature = "dummy", not(target_family = "wasm")))]
285 pub fn build_dummy_transport(
286 &self,
287 initial_session_credential: Option<&str>,
288 ) -> SharedTransport {
289 let credentials = initial_session_credential.unwrap_or(&self.traversal_servers);
290 Arc::new(crate::connections::DummyTransport::new(
291 credentials,
292 self.endpoint_hint.clone(),
293 self.udp_port_range,
294 ))
295 }
296
297 #[cfg(all(feature = "dummy", not(target_family = "wasm")))]
301 pub fn try_build_dummy_transport(
302 &self,
303 initial_session_credential: Option<&str>,
304 ) -> crate::error::Result<SharedTransport> {
305 let credentials = initial_session_credential.unwrap_or(&self.traversal_servers);
306 Ok(Arc::new(crate::connections::DummyTransport::new_strict(
307 credentials,
308 self.endpoint_hint.clone(),
309 self.udp_port_range,
310 )?))
311 }
312
313 pub fn session_credentials_of(transport: &SharedTransport) -> Option<String> {
317 let any = transport.as_any();
318 #[cfg(all(feature = "native-webrtc", not(target_family = "wasm")))]
319 if let Some(webrtc) = any.downcast_ref::<crate::connections::WebrtcTransport>() {
320 return Some(webrtc.session_credentials());
321 }
322 #[cfg(all(feature = "dummy", not(target_family = "wasm")))]
323 if let Some(dummy) = any.downcast_ref::<crate::connections::DummyTransport>() {
324 return Some(dummy.session_credentials());
325 }
326 #[cfg(all(feature = "web-sys-webrtc", target_family = "wasm"))]
327 if let Some(web_sys) = any.downcast_ref::<crate::connections::WebSysWebrtcTransport>() {
328 return Some(web_sys.session_credentials());
329 }
330 let _ = any;
331 None
332 }
333
334 pub fn prepare_ice_server_rotation(
339 transport: &SharedTransport,
340 credentials: String,
341 ) -> crate::error::Result<Box<dyn FnOnce()>> {
342 let parsed = crate::ice_server::parse_ice_servers_strict(&credentials)?;
343 let any = transport.as_any();
344 #[cfg(all(feature = "native-webrtc", not(target_family = "wasm")))]
345 if any.is::<crate::connections::WebrtcTransport>() {
346 let handle = Arc::clone(transport);
347 return Ok(Box::new(move || {
348 if let Some(webrtc) = handle
349 .as_any()
350 .downcast_ref::<crate::connections::WebrtcTransport>()
351 {
352 webrtc.commit_prepared_ice_servers(credentials, parsed);
353 }
354 }));
355 }
356 #[cfg(all(feature = "dummy", not(target_family = "wasm")))]
357 if any.is::<crate::connections::DummyTransport>() {
358 let handle = Arc::clone(transport);
359 return Ok(Box::new(move || {
360 if let Some(dummy) = handle
361 .as_any()
362 .downcast_ref::<crate::connections::DummyTransport>()
363 {
364 dummy.commit_prepared_ice_servers(credentials, parsed);
365 }
366 }));
367 }
368 #[cfg(all(feature = "web-sys-webrtc", target_family = "wasm"))]
369 if any.is::<crate::connections::WebSysWebrtcTransport>() {
370 let handle = Arc::clone(transport);
371 return Ok(Box::new(move || {
372 if let Some(web_sys) = handle
373 .as_any()
374 .downcast_ref::<crate::connections::WebSysWebrtcTransport>()
375 {
376 web_sys.commit_prepared_ice_servers(credentials, parsed);
377 }
378 }));
379 }
380 let _ = (any, parsed);
381 Err(crate::error::Error::UnsupportedOperation(
382 "transport backend does not support ICE server credential rotation".to_string(),
383 ))
384 }
385}
386
387#[cfg(test)]
388mod tests {
389 use super::*;
390
391 #[test]
392 fn test_udp_port_range_preserves_valid_bounds() {
393 let range = UdpPortRange::new(49160, 49200);
394
395 assert_eq!(
396 range,
397 Ok(UdpPortRange {
398 min: 49160,
399 max: 49200
400 })
401 );
402 }
403
404 #[test]
405 fn test_udp_port_range_rejects_zero_bound() {
406 let range = UdpPortRange::new(0, 49200);
407
408 assert_eq!(
409 range,
410 Err(UdpPortRangeError::ZeroBound { min: 0, max: 49200 })
411 );
412 }
413
414 #[test]
415 fn test_udp_port_range_rejects_inverted_bounds() {
416 let range = UdpPortRange::new(49200, 49160);
417
418 assert_eq!(
419 range,
420 Err(UdpPortRangeError::Inverted {
421 min: 49200,
422 max: 49160
423 })
424 );
425 }
426
427 #[test]
428 fn test_udp_port_range_rejects_incomplete_optional_bounds() {
429 assert_eq!(
430 UdpPortRange::from_optional_bounds(Some(49160), None),
431 Err(UdpPortRangeError::IncompleteBounds {
432 min: Some(49160),
433 max: None,
434 })
435 );
436 assert_eq!(UdpPortRange::from_optional_bounds(None, None), Ok(None));
437 }
438}