Skip to main content

is/
lib.rs

1// Changed by Alakazam Labs for sew-str0m-is; the fork's patches are listed in its README.
2//! **This is sew-str0m-is, a fork of `is`, the ICE crate of
3//! [str0m](https://github.com/algesten/str0m)**, that Alakazam Labs publishes with sew-str0m for
4//! Sew, Alakazam Labs' chat and voice core. Depend on it as
5//! `is = { package = "sew-str0m-is", version = "0.12.3" }`; the library name stays `is`. It is
6//! used instead of upstream `is`; a build that also pulls in upstream `is` gets both, and their
7//! types do not mix. The crate's [README](https://crates.io/crates/sew-str0m-is) lists the
8//! patches and where to report problems. The rest of this page is upstream's documentation.
9//!
10//! # is -- ICE in Sans-IO style
11//!
12//! Standalone [ICE][rfc8445] agent extracted from the [str0m][str0m] WebRTC library.
13//!
14//! ICE is the protocol used to establish peer-to-peer connectivity across
15//! the internet. It coordinates STUN connectivity checks over every
16//! possible network path between two peers and picks the best one,
17//! handling NAT traversal along the way.
18//!
19//! This crate implements the ICE agent -- the state machine that drives
20//! candidate pairing, connectivity checks, and nomination -- without
21//! performing any I/O itself.
22//!
23//! # Sans-IO
24//!
25//! This is a [Sans-IO][sansio] implementation. The `IceAgent` never touches
26//! a socket. Instead you drive it in a loop:
27//!
28//! 1. `poll_timeout()` -- when to wake up next.
29//! 2. `handle_timeout(now)` -- advance timers.
30//! 3. `poll_transmit()` -- STUN packets to send.
31//! 4. `handle_packet(now, pkt)` -- feed incoming STUN.
32//! 5. `poll_event()` -- state changes and nominations.
33//!
34//! This makes the agent easy to embed in any async runtime, event loop, or
35//! test harness.
36//!
37//! # Quick start
38//!
39//! ```no_run
40//! use is::{IceAgent, IceCreds, Candidate};
41//!
42//! // Create an agent with random credentials.
43//! let mut agent = IceAgent::new(IceCreds::new());
44//!
45//! // Tell the agent about a local socket.
46//! let addr = "192.168.1.100:5000".parse().unwrap();
47//! agent.add_local_candidate(Candidate::host(addr, "udp").unwrap());
48//!
49//! // Exchange credentials and candidates with the remote peer via your
50//! // signalling channel, then run the loop above until
51//! // IceConnectionState::Connected.
52//! ```
53//!
54//! # Address discovery is external
55//!
56//! The agent does not enumerate network interfaces, query STUN servers, or
57//! allocate TURN relays. All of that is the caller's responsibility.
58//! Discovered addresses are fed in via `add_local_candidate()` at any time
59//! (trickle ICE).
60//!
61//! # Relationship to str0m
62//!
63//! This crate was extracted from [str0m][str0m] so the ICE agent can be
64//! reused outside the full WebRTC stack. str0m depends on this crate with
65//! default features disabled (it supplies its own HMAC provider through its
66//! pluggable crypto backend).
67//!
68//! When used standalone the default `sha1` feature provides
69//! `DefaultSha1HmacProvider` and a convenient `IceAgent::new()` constructor.
70//! Disable it if you want to supply your own provider via
71//! `IceAgent::with_hmac()`.
72//!
73//! # Design decisions
74//!
75//! The implementation makes several simplifying assumptions that suit
76//! WebRTC usage:
77//!
78//! - **STUN/TURN are external** -- see above.
79//! - **BUNDLE assumed** -- one agent, one data stream, one component (RTP).
80//! - **Trickle ICE only** -- candidates can arrive at any time.
81//! - **No frozen check state** -- single data stream means pairs go straight
82//!   to waiting.
83//! - **Nomination is not final** -- the agent can change its nominated pair
84//!   as network conditions shift, without an ICE restart.
85//! - **Ice-lite supported** -- the agent can act as a controlled ice-lite
86//!   endpoint for server-side use.
87//!
88//! For the full rationale and list of assumptions see the
89//! [design document][design].
90//!
91//! # Features
92//!
93//! | Feature | Default | Description |
94//! |---------|---------|-------------|
95//! | `sha1`  | yes     | Provides `DefaultSha1HmacProvider` and `IceAgent::new()` |
96//! | `pii`   | no      | Redacts IP addresses and other PII from log output |
97//!
98//! [rfc8445]: https://datatracker.ietf.org/doc/html/rfc8445
99//! [str0m]: https://crates.io/crates/str0m
100//! [sansio]: https://sans-io.readthedocs.io/
101//! [design]: https://github.com/algesten/str0m/blob/main/docs/ice.md
102
103// Avoid rewriting existing code: nested conditions are often more readable than long if-chains.
104#![forbid(unsafe_code)]
105#![allow(clippy::collapsible_if)]
106#![allow(clippy::new_without_default)]
107#![allow(clippy::bool_to_int_with_if)]
108
109#[macro_use]
110extern crate tracing;
111
112mod agent;
113pub use agent::{IceAgent, IceAgentEvent, IceConnectionState, IceCreds, LocalPreference};
114
115mod candidate;
116pub use candidate::{Candidate, CandidateBuilder, CandidateKind};
117
118mod pair;
119
120mod preference;
121pub use preference::default_local_preference;
122
123mod error;
124pub use error::IceError;
125pub use error::StunError;
126
127pub mod stun;
128
129mod parse;
130
131mod hmac_provider;
132#[cfg(feature = "sha1")]
133pub use hmac_provider::DefaultSha1HmacProvider;
134pub use str0m_proto::{Protocol, Sha1HmacProvider};
135
136#[cfg(test)]
137pub(crate) mod test {
138    use crate::agent::IceAgentStats;
139    use crate::stun::{StunMessage, StunPacket};
140    use crate::*;
141    use str0m_proto::Protocol;
142    use str0m_proto::Transmit;
143
144    use std::collections::HashMap;
145    use std::net::IpAddr;
146    use std::net::SocketAddr;
147    use std::ops::{Deref, DerefMut};
148    use std::time::{Duration, Instant};
149
150    use tracing::Span;
151    use tracing_subscriber::util::SubscriberInitExt;
152
153    #[test]
154    pub fn drop_host() {
155        let mut a1 = TestAgent::new(info_span!("L"));
156        let mut a2 = TestAgent::new(info_span!("R"));
157
158        // 9999 is just dropped by propagate
159        let c1 = a1.add_host_candidate("1.1.1.1:9999");
160        a2.add_remote_candidate(c1);
161
162        let c2 = a2.add_host_candidate("2.2.2.2:1000");
163        a1.add_remote_candidate(c2);
164
165        a1.set_controlling(true);
166        a2.set_controlling(false);
167
168        loop {
169            if a1.state().is_disconnected() && a2.state().is_disconnected() {
170                break;
171            }
172            progress(&mut a1, &mut a2);
173        }
174
175        assert_eq!(
176            a1.stats(),
177            IceAgentStats {
178                bind_request_sent: 9,
179                bind_success_recv: 0,
180                bind_request_recv: 0,
181                discovered_recv_count: 0,
182                nomination_send_count: 0,
183            }
184        );
185
186        assert_eq!(
187            a2.stats(),
188            IceAgentStats {
189                bind_request_sent: 9,
190                bind_success_recv: 0,
191                bind_request_recv: 0,
192                discovered_recv_count: 0,
193                nomination_send_count: 0,
194            }
195        );
196    }
197
198    #[test]
199    pub fn host_host_disconnect() {
200        let mut a1 = TestAgent::new(info_span!("L"));
201        let mut a2 = TestAgent::new(info_span!("R"));
202
203        let c1 = a1.add_host_candidate("1.1.1.1:1000");
204        a2.add_remote_candidate(c1);
205
206        let c2 = a2.add_host_candidate("2.2.2.2:1000");
207        a1.add_remote_candidate(c2);
208
209        a1.set_controlling(true);
210        a2.set_controlling(false);
211
212        loop {
213            if a1.state().is_connected() && a2.state().is_connected() {
214                break;
215            }
216            progress(&mut a1, &mut a2);
217        }
218
219        a1.drop_sent_packets = true;
220
221        loop {
222            if !a1.state().is_connected() && !a2.state().is_connected() {
223                break;
224            }
225            progress(&mut a1, &mut a2);
226        }
227
228        println!("{:?}", a1.events);
229        println!("{:?}", a2.events);
230
231        fn assert_last_event(d: &Duration, e: &IceAgentEvent, a: &IceAgent) {
232            assert_eq!(
233                *e,
234                IceAgentEvent::IceConnectionStateChange(IceConnectionState::Disconnected)
235            );
236            assert!(*d > a.ice_timeout());
237        }
238
239        let (d, e) = a1.events.last().unwrap();
240        assert_last_event(d, e, &a1);
241
242        let (d, e) = a2.events.last().unwrap();
243        assert_last_event(d, e, &a2);
244
245        assert_eq!(
246            a1.stats(),
247            IceAgentStats {
248                bind_request_sent: 11,
249                bind_success_recv: 2,
250                bind_request_recv: 11,
251                discovered_recv_count: 1,
252                nomination_send_count: 1,
253            }
254        );
255
256        assert_eq!(
257            a2.stats(),
258            IceAgentStats {
259                bind_request_sent: 11,
260                bind_success_recv: 2,
261                bind_request_recv: 2,
262                discovered_recv_count: 1,
263                nomination_send_count: 1,
264            }
265        );
266    }
267
268    #[test]
269    pub fn host_host() {
270        let mut a1 = TestAgent::new(info_span!("L"));
271        let mut a2 = TestAgent::new(info_span!("R"));
272
273        let c1 = a1.add_host_candidate("1.1.1.1:1000");
274        a2.add_remote_candidate(c1);
275
276        let c2 = a2.add_host_candidate("2.2.2.2:1000");
277        a1.add_remote_candidate(c2);
278
279        a1.set_controlling(true);
280        a2.set_controlling(false);
281
282        loop {
283            if a1.state().is_connected() && a2.state().is_connected() {
284                break;
285            }
286            progress(&mut a1, &mut a2);
287        }
288
289        assert_eq!(
290            a1.stats(),
291            IceAgentStats {
292                bind_request_sent: 2,
293                bind_success_recv: 2,
294                bind_request_recv: 2,
295                discovered_recv_count: 1,
296                nomination_send_count: 1,
297            }
298        );
299
300        assert_eq!(
301            a2.stats(),
302            IceAgentStats {
303                bind_request_sent: 3,
304                bind_success_recv: 2,
305                bind_request_recv: 2,
306                discovered_recv_count: 1,
307                nomination_send_count: 1,
308            }
309        );
310    }
311
312    // RFC 8445 §7.3.1.1: when both agents claim the controlling role, the
313    // role conflict is resolved deterministically by the tiebreaker — the
314    // higher-tiebreaker agent keeps the role, the other yields. Tiebreakers
315    // here are the random ones picked by the constructor, so we cannot
316    // predict which side wins; we only assert that the conflict resolves:
317    // the connection still establishes and exactly one side ends up
318    // controlled.
319    #[test]
320    pub fn role_conflict_resolves_to_one_controlled_side() {
321        let mut a1 = TestAgent::new(info_span!("L"));
322        let mut a2 = TestAgent::new(info_span!("R"));
323
324        let c1 = a1.add_host_candidate("1.1.1.1:1000");
325        a2.add_remote_candidate(c1);
326
327        let c2 = a2.add_host_candidate("2.2.2.2:1000");
328        a1.add_remote_candidate(c2);
329
330        a1.set_controlling(true);
331        a2.set_controlling(true);
332
333        loop {
334            if a1.state().is_connected() && a2.state().is_connected() {
335                break;
336            }
337            progress(&mut a1, &mut a2);
338        }
339
340        assert!(
341            a1.controlling() ^ a2.controlling(),
342            "role conflict must leave exactly one side controlling, got a1={} a2={}",
343            a1.controlling(),
344            a2.controlling(),
345        );
346        assert!(
347            a1.stats().nomination_send_count > 0 || a2.stats().nomination_send_count > 0,
348            "role conflict must not block nomination",
349        );
350    }
351
352    // str0m performs calculations on `now` internally
353    // To ensure that these never panic, we run a happy-path of `host-host` that uses a very early `Instant`.
354    #[test]
355    pub fn happy_path_very_early_timestamp() {
356        let early_now = find_earliest_now();
357
358        let mut a1 = TestAgent::new(info_span!("L"));
359        a1.time = early_now;
360        let mut a2 = TestAgent::new(info_span!("R"));
361        a2.time = early_now;
362
363        let c1 = a1.add_host_candidate("1.1.1.1:1000");
364        a2.add_remote_candidate(c1);
365
366        let c2 = a2.add_host_candidate("2.2.2.2:1000");
367        a1.add_remote_candidate(c2);
368
369        a1.set_controlling(true);
370        a2.set_controlling(false);
371
372        loop {
373            if a1.state().is_connected() && a2.state().is_connected() {
374                break;
375            }
376            progress(&mut a1, &mut a2);
377        }
378    }
379
380    #[test]
381    pub fn no_respond_to_stun_request_on_invalidated_candidate() {
382        let mut a1 = TestAgent::new(info_span!("L"));
383        let mut a2 = TestAgent::new(info_span!("R"));
384
385        let c1 = a1.add_host_candidate("1.1.1.1:1000");
386        a2.add_remote_candidate(c1.clone());
387
388        let c2 = a2.add_host_candidate("2.2.2.2:1000");
389        a1.add_remote_candidate(c2);
390
391        a1.set_controlling(true);
392        a2.set_controlling(false);
393
394        loop {
395            if a1.state().is_connected() && a2.state().is_connected() {
396                break;
397            }
398            progress(&mut a1, &mut a2);
399        }
400
401        a1.agent.invalidate_candidate(&c1);
402
403        let timeout = a2.poll_timeout().unwrap();
404        a2.handle_timeout(timeout);
405        let transmit = a2.poll_transmit().unwrap();
406
407        assert!(a1.poll_transmit().is_none());
408
409        a1.handle_packet(
410            Instant::now(),
411            StunPacket {
412                proto: Protocol::Udp,
413                source: sock("2.2.2.2:1000"),
414                destination: sock("1.1.1.1:1000"),
415                message: StunMessage::parse(&transmit.contents).unwrap(),
416            },
417        );
418
419        assert!(a1.poll_transmit().is_none());
420    }
421
422    #[test]
423    pub fn migrates_to_new_candidates_after_invalidation_without_timeout() {
424        let _guard = tracing_subscriber::fmt()
425            .with_env_filter("debug")
426            .with_test_writer()
427            .set_default();
428
429        let mut a1 = TestAgent::new(info_span!("L"));
430        let mut a2 = TestAgent::new(info_span!("R"));
431
432        let c1 = host("1.1.1.1:1000", "udp");
433        let c1 = a1.add_local_candidate(c1).unwrap().clone();
434        a2.add_remote_candidate(c1.clone());
435
436        let c2 = a2.add_host_candidate("2.2.2.2:1000");
437        a1.add_remote_candidate(c2);
438
439        a1.set_controlling(true);
440        a2.set_controlling(false);
441
442        loop {
443            if a1.state().is_connected() && a2.state().is_connected() {
444                break;
445            }
446            progress(&mut a1, &mut a2);
447        }
448
449        let a1_time = a1.time;
450        let a2_time = a2.time;
451        let new_sock = sock("8.8.8.8:1000");
452
453        let c3 = Candidate::host(new_sock, Protocol::Udp).unwrap();
454        let c3 = a1.add_local_candidate(c3).unwrap().clone();
455        a2.add_remote_candidate(c3);
456
457        a1.agent.invalidate_candidate(&c1);
458        a2.agent.invalidate_candidate(&c1);
459
460        loop {
461            let a1_nominated = a1.has_event(
462                |e| matches!(e, IceAgentEvent::NominatedSend { source, .. } if source == &new_sock),
463            );
464            let a2_nominated = a2.has_event(
465                |e| matches!(e, IceAgentEvent::NominatedSend { destination, .. } if destination == &new_sock)
466            );
467
468            if a1_nominated && a2_nominated {
469                break;
470            }
471
472            progress(&mut a1, &mut a2);
473        }
474
475        assert!(a1.time.duration_since(a1_time) < a1.ice_timeout());
476        assert!(a2.time.duration_since(a2_time) < a2.ice_timeout());
477    }
478
479    #[test]
480    pub fn re_adding_invalidated_local_candidate() {
481        let mut a1 = TestAgent::new(info_span!("L"));
482        let mut a2 = TestAgent::new(info_span!("R"));
483
484        let c1 = a1.add_host_candidate("1.1.1.1:1000");
485        a2.add_remote_candidate(c1.clone());
486
487        let c2 = a2.add_host_candidate("2.2.2.2:1000");
488        a1.add_remote_candidate(c2);
489
490        a1.set_controlling(true);
491        a2.set_controlling(false);
492
493        loop {
494            if a1.state().is_connected() && a2.state().is_connected() {
495                break;
496            }
497            progress(&mut a1, &mut a2);
498        }
499
500        a1.agent.invalidate_candidate(&c1);
501
502        // Let time pass until it disconnects.
503        loop {
504            if a1.state().is_disconnected() && a2.state().is_disconnected() {
505                break;
506            }
507            progress(&mut a1, &mut a2);
508        }
509
510        // Add back the invalidated candidate
511        a1.add_local_candidate(c1).unwrap();
512
513        // progress() fails after 100 number of polls.
514        a1.progress_count = 0;
515        a2.progress_count = 0;
516        loop {
517            if a1.state().is_connected() && a2.state().is_connected() {
518                break;
519            }
520            progress(&mut a1, &mut a2);
521        }
522    }
523
524    #[test]
525    pub fn re_adding_invalidated_remote_candidate() {
526        let mut a1 = TestAgent::new(info_span!("L"));
527        let mut a2 = TestAgent::new(info_span!("R"));
528
529        let c1 = a1.add_host_candidate("1.1.1.1:1000");
530        a2.add_remote_candidate(c1);
531
532        let c2 = a2.add_host_candidate("2.2.2.2:1000");
533        a1.add_remote_candidate(c2.clone());
534
535        a1.set_controlling(true);
536        a2.set_controlling(false);
537
538        loop {
539            if a1.state().is_connected() && a2.state().is_connected() {
540                break;
541            }
542            progress(&mut a1, &mut a2);
543        }
544
545        a1.agent.invalidate_candidate(&c2);
546
547        // Let time pass until it disconnects.
548        loop {
549            if a1.state().is_disconnected() && a2.state().is_disconnected() {
550                break;
551            }
552            progress(&mut a1, &mut a2);
553        }
554
555        // Add back the invalidated candidate
556        a1.add_remote_candidate(c2);
557
558        // progress() fails after 100 number of polls.
559        a1.progress_count = 0;
560        a2.progress_count = 0;
561        loop {
562            if a1.state().is_connected() && a2.state().is_connected() {
563                break;
564            }
565            progress(&mut a1, &mut a2);
566        }
567    }
568
569    #[test]
570    pub fn ice_lite_no_connection() {
571        let mut a1 = TestAgent::new(info_span!("L"));
572        let mut a2 = TestAgent::new(info_span!("R"));
573
574        // a1 acts as "server"
575        a1.agent.set_ice_lite(true);
576
577        // 9999 is just dropped by propagate
578        let c1 = a1.add_host_candidate("1.1.1.1:9999");
579        a2.add_remote_candidate(c1);
580
581        let c2 = a2.add_host_candidate("2.2.2.2:1000");
582        a1.add_remote_candidate(c2);
583
584        a1.set_controlling(true);
585        a2.set_controlling(false);
586
587        loop {
588            // The bug we try to avoid is that _both sides_ must reach a disconnected state eventually.
589            // The ice-lite (server side) should time out after roughly 8 seconds.
590            if a1.state().is_disconnected() && a2.state().is_disconnected() {
591                break;
592            }
593            progress(&mut a1, &mut a2);
594        }
595
596        assert!(a1.time - a1.start_time > Duration::from_secs(8));
597
598        assert_eq!(
599            a1.stats(),
600            IceAgentStats {
601                bind_request_sent: 0,
602                bind_success_recv: 0,
603                bind_request_recv: 0,
604                discovered_recv_count: 0,
605                nomination_send_count: 0,
606            }
607        );
608
609        assert_eq!(
610            a2.stats(),
611            IceAgentStats {
612                bind_request_sent: 9,
613                bind_success_recv: 0,
614                bind_request_recv: 0,
615                discovered_recv_count: 0,
616                nomination_send_count: 0,
617            }
618        );
619    }
620
621    /// Regression test: ice-lite agents should not disconnect immediately on first timeout.
622    #[test]
623    pub fn ice_lite_no_immediate_disconnect() {
624        let mut a1 = TestAgent::new(info_span!("L"));
625        a1.set_ice_lite(true);
626
627        a1.add_host_candidate("1.1.1.1:1000");
628        a1.add_remote_candidate(host("2.2.2.2:2000", "udp"));
629
630        a1.span.in_scope(|| a1.agent.handle_timeout(a1.time));
631
632        assert!(!a1.state().is_disconnected());
633    }
634
635    #[test]
636    pub fn prflx_host() {
637        let mut a1 = TestAgent::new(info_span!("L")).with_port_restricted_nat("4.4.4.4");
638        let mut a2 = TestAgent::new(info_span!("R"));
639
640        // will be rewritten to 4.4.4.4
641        let c1 = a1.add_host_candidate("3.3.3.3:1000");
642        a2.add_remote_candidate(c1);
643
644        let c2 = a2.add_host_candidate("2.2.2.2:1000");
645        a1.add_remote_candidate(c2);
646
647        a1.set_controlling(true);
648        a2.set_controlling(false);
649
650        loop {
651            if a1.state().is_connected() && a2.state().is_connected() {
652                break;
653            }
654            progress(&mut a1, &mut a2);
655        }
656
657        assert_eq!(
658            a1.stats(),
659            IceAgentStats {
660                bind_request_sent: 2,
661                bind_success_recv: 2,
662                bind_request_recv: 1,
663                discovered_recv_count: 1,
664                nomination_send_count: 1,
665            }
666        );
667
668        assert_eq!(
669            a2.stats(),
670            IceAgentStats {
671                bind_request_sent: 3,
672                bind_success_recv: 1,
673                bind_request_recv: 2,
674                discovered_recv_count: 1,
675                nomination_send_count: 1,
676            }
677        );
678    }
679
680    // pub fn init_log() {
681    //     use tracing_subscriber::{fmt, prelude::*, EnvFilter};
682
683    //     let env_filter =
684    //         EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("trace"));
685
686    //     tracing_subscriber::registry()
687    //         .with(fmt::layer())
688    //         .with(EnvFilter::from_default_env())
689    //         .init();
690    // }
691
692    #[test]
693    pub fn ice_lite_disconnect_reconnect() {
694        // init_log();
695
696        let mut a1 = TestAgent::new(info_span!("L"));
697        let mut a2 = TestAgent::new(info_span!("R"));
698
699        let c1 = a1.add_host_candidate("1.1.1.1:1000");
700        a2.add_remote_candidate(c1.clone());
701
702        let c2 = a2.add_host_candidate("2.2.2.2:1000");
703        a1.add_remote_candidate(c2.clone());
704
705        a1.set_controlling(true);
706        a2.set_controlling(false);
707        a2.set_ice_lite(true);
708
709        // Connect.
710        loop {
711            if a1.state().is_connected() && a2.state().is_connected() {
712                break;
713            }
714            progress(&mut a1, &mut a2);
715        }
716
717        // Disconnect
718        a1.drop_sent_packets = true;
719
720        loop {
721            if !a1.state().is_connected() && !a2.state().is_connected() {
722                break;
723            }
724            progress(&mut a1, &mut a2);
725        }
726
727        // Now reconnect after disconnecting.
728        a1.drop_sent_packets = false;
729
730        // Adding back the remote candidate will for new pairs to try.
731        // This makes a1 start sending new STUN requests.
732        // a2 in ice-lite mode will discover the pair from the STUN
733        // request and come out of disconnected.
734        a1.add_remote_candidate(c2);
735
736        loop {
737            if a1.state().is_connected() && a2.state().is_connected() {
738                break;
739            }
740            progress(&mut a1, &mut a2);
741        }
742    }
743
744    #[test]
745    pub fn trickle_host_host() {
746        let mut a1 = TestAgent::new(info_span!("L"));
747        let mut a2 = TestAgent::new(info_span!("R"));
748
749        // no traffic possible
750        let c1 = a1.add_host_candidate("3.3.3.3:9999");
751        a2.add_remote_candidate(c1);
752
753        let c2 = a2.add_host_candidate("2.2.2.2:1000");
754        a1.add_remote_candidate(c2);
755
756        a1.set_controlling(true);
757        a2.set_controlling(false);
758
759        // this will be going nowhere (tested in drop-host.rs).
760        for _ in 0..10 {
761            progress(&mut a1, &mut a2);
762        }
763
764        // "trickle" a possible candidate
765        a1.add_host_candidate("1.1.1.1:1000");
766
767        loop {
768            if a1.state().is_connected() && a2.state().is_connected() {
769                break;
770            }
771            progress(&mut a1, &mut a2);
772        }
773    }
774
775    #[test]
776    pub fn candidate_pair_of_same_kind_does_not_get_nominated() {
777        let mut a1 = TestAgent::new(info_span!("L"));
778        let mut a2 = TestAgent::new(info_span!("R")).with_port_restricted_nat("4.4.4.4");
779
780        let c1 = a1.add_relay_candidate("1.1.1.1:1000", "9.9.9.9:2000");
781        a2.add_remote_candidate(c1);
782
783        let c2 = a2.server_reflexive_candidate("8.8.8.8:3478", "3.3.3.3:1000");
784        let c2 = a2.add_local_candidate(c2).unwrap().clone();
785        a1.add_remote_candidate(c2);
786        let c3 = a2.add_host_candidate("3.3.3.3:1000");
787        a1.add_remote_candidate(c3);
788
789        a1.set_controlling(true);
790        a2.set_controlling(false);
791
792        // loop until we're connected.
793        loop {
794            if a1.state().is_connected() && a2.state().is_connected() {
795                break;
796            }
797            progress(&mut a1, &mut a2);
798        }
799
800        a2.add_remote_candidate(a1.add_relay_candidate("1.1.1.1:1001", "9.9.9.9:2000"));
801
802        loop {
803            if a2.has_event(|e| {
804                matches!(e, IceAgentEvent::DiscoveredRecv { source, .. } if source == &sock("1.1.1.1:1001"))
805            }) {
806                break;
807            }
808
809            progress(&mut a1, &mut a2);
810        }
811
812        assert!(!a1.has_event(|e| {
813            matches!(e, IceAgentEvent::NominatedSend { source, .. } if source == &sock("1.1.1.1:1001"))
814        }));
815        assert!(!a2.has_event(|e| {
816            matches!(e, IceAgentEvent::NominatedSend { destination, .. }
817                if destination == &sock("1.1.1.1:1001"))
818        }));
819    }
820
821    #[test]
822    pub fn no_disconnect_when_replacing_pflx_with_real_candidate() {
823        let mut a1 = TestAgent::new(info_span!("L"));
824        let mut a2 = TestAgent::new(info_span!("R"));
825
826        // We need a 2nd pair of candidates to make sure the agent doesn't go straight into `Completed`.
827
828        // Both agents know their local candidates
829        let c1 = a1.add_host_candidate("1.1.1.1:1000");
830        let c3 = a1.add_relay_candidate("2.2.2.2:1000", "9.9.9.9:2000");
831
832        let c2 = a2.add_host_candidate("1.1.1.1:1001");
833        let c4 = a2.add_relay_candidate("2.2.2.2:1001", "9.9.9.9:2000");
834
835        // Agent 1 also learns about the remote candidates but agent 2
836        // doesn't (imagine signalling layer being a bit slow)
837        a1.add_remote_candidate(c2);
838        a1.add_remote_candidate(c4);
839
840        a1.set_controlling(true);
841        a2.set_controlling(false);
842
843        // Wait until agent 2 is connected (based on a peer-reflexive candidate)
844        loop {
845            if a2.state().is_connected() {
846                break;
847            }
848            progress(&mut a1, &mut a2);
849        }
850        a2.events.clear();
851
852        // Candidates arrive via signalling layer
853        a2.add_remote_candidate(c1.clone());
854        a2.add_remote_candidate(c3.clone());
855
856        // Continue normal operation.
857        for _ in 0..50 {
858            progress(&mut a1, &mut a2);
859        }
860
861        // We expect to not disconnect as part of this, nor to go back to checking:
862        // the replacing pair keeps the validated path of the peer-reflexive one.
863        assert!(!a2.has_event(|e| matches!(
864            e,
865            IceAgentEvent::IceConnectionStateChange(
866                IceConnectionState::Disconnected | IceConnectionState::Checking
867            )
868        )));
869    }
870
871    #[test]
872    pub fn pair_replacement_in_attempt_window_stays_connected() {
873        let mut a1 = TestAgent::new(info_span!("L"));
874        let mut a2 = TestAgent::new(info_span!("R"));
875
876        let c1 = a1.add_host_candidate("1.1.1.1:1000");
877        let c2 = a2.add_host_candidate("2.2.2.2:1000");
878
879        // Only the controlling side initially knows the remote candidate. This makes
880        // the controlled side discover a peer-reflexive remote from inbound STUN.
881        a1.add_remote_candidate(c2);
882
883        a1.set_controlling(true);
884        a2.set_controlling(false);
885
886        // Exchange initial ICE credentials without consuming any binding requests.
887        progress_without_network(&mut a1, &mut a2);
888        progress_without_network(&mut a2, &mut a1);
889
890        a1.events.clear();
891        a2.events.clear();
892
893        // The controlling side starts checking the signalled host candidate.
894        progress_without_network(&mut a1, &mut a2);
895        let initial_request = progress_one_message(&mut a1, &mut a2);
896        assert!(initial_request.is_binding_request);
897        assert!(!initial_request.use_candidate);
898
899        let initial_reply = progress_one_message(&mut a2, &mut a1);
900        assert!(initial_reply.is_successful_binding_response);
901        assert!(a1.has_event(|e| matches!(e, IceAgentEvent::NominatedSend { .. })));
902
903        // Now the controlling side sends the nominated USE-CANDIDATE request.
904        progress_without_network(&mut a1, &mut a2);
905
906        let nominate_request = progress_one_message(&mut a1, &mut a2);
907        assert!(nominate_request.is_binding_request);
908        assert!(nominate_request.use_candidate);
909
910        // The controlled side answers that request and then sends a reverse binding
911        // request to confirm the nomination. The reply is queued when the request
912        // arrives, then the reverse binding request is queued on the next timeout.
913        // The nominated pair is not valid until that request is answered (RFC 8445
914        // §7.3.1.5), so the controlled side is not connected yet.
915        progress_without_network(&mut a2, &mut a1);
916        assert!(!a2.state().is_connected());
917
918        let nominate_reply = a2.poll_next_stun_message();
919        assert!(nominate_reply.is_successful_binding_response);
920        let reverse_request = a2.poll_next_stun_message();
921        assert!(reverse_request.is_binding_request);
922
923        // Before the reverse binding response arrives, the signalling layer delivers the
924        // controller's real remote candidate. This replaces the prflx pair during Attempt.
925        a2.add_remote_candidate(c1);
926        progress_without_network(&mut a2, &mut a1);
927
928        assert!(!a2.state().is_connected());
929        assert!(!a2.has_event(|e| matches!(
930            e,
931            IceAgentEvent::IceConnectionStateChange(IceConnectionState::Checking)
932        )));
933
934        // Finish the delayed round trip and ensure the controlled side stays connected.
935        deliver_transmit(&mut a2, &mut a1, &nominate_reply.transmit);
936        deliver_transmit(&mut a2, &mut a1, &reverse_request.transmit);
937
938        let reverse_reply = progress_one_message(&mut a1, &mut a2);
939        assert!(reverse_reply.is_successful_binding_response);
940
941        for _ in 0..20 {
942            if a1.state().is_connected() && a2.state().is_connected() {
943                break;
944            }
945            progress(&mut a1, &mut a2);
946        }
947
948        assert!(a1.state().is_connected());
949        assert!(a2.state().is_connected());
950        assert!(!a2.has_event(|e| matches!(
951            e,
952            IceAgentEvent::IceConnectionStateChange(IceConnectionState::Checking)
953        )));
954    }
955
956    #[test]
957    pub fn identical_host_and_server_reflexive_candidates_dont_create_new_pairs_on_inbound_stun_request()
958     {
959        let mut a1 = TestAgent::new(info_span!("L"));
960        let mut a2 = TestAgent::new(info_span!("R"));
961
962        let c1 = a1.add_host_candidate("1.1.1.1:1000");
963        a2.add_remote_candidate(c1);
964        let c2 = a2.server_reflexive_candidate("8.8.8.8:3478", "2.2.2.2:1000");
965        let c2 = a2.add_local_candidate(c2).unwrap().clone();
966        a1.add_remote_candidate(c2);
967        let c3 = a2.add_host_candidate("2.2.2.2:1000");
968        a1.add_remote_candidate(c3);
969
970        a1.set_controlling(true);
971        a2.set_controlling(false);
972
973        // loop until we're connected.
974        loop {
975            if a1.state().is_connected() && a2.state().is_connected() {
976                break;
977            }
978            progress(&mut a1, &mut a2);
979        }
980
981        // Each agent should only have a single candidate pair.
982        assert_eq!(a1.num_candidate_pairs(), 1);
983        assert_eq!(a2.num_candidate_pairs(), 1);
984    }
985
986    // In general, ICE prefers IPv6 over IPv4.
987    // However, in case our only IPv6 connectivity is via a relay that we are talking to over IPv4,
988    // we want to prefer the IPv4 code path.
989    #[test]
990    fn prefers_ipv4_ipv4_relay_candidate_over_ipv4_ipv6_controlling() {
991        let _guard = tracing_subscriber::fmt()
992            .with_env_filter("debug")
993            .with_test_writer()
994            .set_default();
995
996        let mut a1 = TestAgent::new(info_span!("L"));
997        let mut a2 = TestAgent::new(info_span!("R"));
998
999        a1.set_controlling(true);
1000        a2.set_controlling(false);
1001
1002        prefer_ipv4_candidate_over_ipv6_candidate(&mut a1, &mut a2);
1003    }
1004
1005    // In general, ICE prefers IPv6 over IPv4.
1006    // However, in case our only IPv6 connectivity is via a relay that we are talking to over IPv4,
1007    // we want to prefer the IPv4 code path.
1008    #[test]
1009    fn prefers_ipv4_ipv4_relay_candidate_over_ipv4_ipv6_controlled() {
1010        let _guard = tracing_subscriber::fmt()
1011            .with_env_filter("debug")
1012            .with_test_writer()
1013            .set_default();
1014
1015        let mut a1 = TestAgent::new(info_span!("L"));
1016        let mut a2 = TestAgent::new(info_span!("R"));
1017
1018        a1.set_controlling(false);
1019        a2.set_controlling(true);
1020
1021        prefer_ipv4_candidate_over_ipv6_candidate(&mut a1, &mut a2);
1022    }
1023
1024    fn prefer_ipv4_candidate_over_ipv6_candidate(a1: &mut TestAgent, a2: &mut TestAgent) {
1025        // Agent 1 only has IPv4 connectivity to a relay but allocates both IPv4 and IPv6 addresses.
1026        // Agent 2 has no relay but has full IPv4 and IPv6 connectivity.
1027        let relay_ipv4_ipv4 = a1.add_relay_candidate("7.7.7.7:5000", "1.1.1.1:5000");
1028        let relay_ipv6_ipv4 = a1.add_relay_candidate("[::7]:5000", "1.1.1.1:5000");
1029        a2.add_remote_candidate(relay_ipv4_ipv4);
1030        a2.add_remote_candidate(relay_ipv6_ipv4);
1031
1032        let host_ipv4 = a2.add_host_candidate("5.5.5.5:3000");
1033        let host_ipv6 = a2.add_host_candidate("[::2]:3000");
1034        a1.add_remote_candidate(host_ipv4);
1035        a1.add_remote_candidate(host_ipv6);
1036
1037        // loop until we're connected.
1038        loop {
1039            if a1.state().is_connected() && a2.state().is_connected() {
1040                break;
1041            }
1042            progress(a1, a2);
1043        }
1044
1045        assert!(a1.has_event(|e| {
1046            matches!(e, IceAgentEvent::NominatedSend { source, destination, .. }
1047                         if source == &sock("7.7.7.7:5000") && destination == &sock("5.5.5.5:3000"))
1048        }));
1049        assert!(a2.has_event(|e| {
1050            matches!(e, IceAgentEvent::NominatedSend { source, destination, .. }
1051                         if source == &sock("5.5.5.5:3000") && destination == &sock("7.7.7.7:5000"))
1052        }));
1053    }
1054
1055    #[test]
1056    fn changed_timing_config_takes_effect_immediately() {
1057        let _guard = tracing_subscriber::fmt()
1058            .with_env_filter("trace")
1059            .with_test_writer()
1060            .set_default();
1061
1062        const IDLE_RTO: Duration = Duration::from_secs(60);
1063        const NORMAL_RTO: Duration = Duration::from_secs(3);
1064
1065        let mut a1 = TestAgent::new(info_span!("L"));
1066        let mut a2 = TestAgent::new(info_span!("R"));
1067
1068        let c1 = host("1.1.1.1:1000", "udp");
1069        a1.add_local_candidate(c1.clone());
1070        a2.add_remote_candidate(c1);
1071
1072        let c2 = host("2.2.2.2:1000", "udp");
1073        a2.add_local_candidate(c2.clone());
1074        a1.add_remote_candidate(c2);
1075
1076        a1.set_controlling(true);
1077        a2.set_controlling(false);
1078
1079        // loop until we're connected.
1080        loop {
1081            if a1.state().is_connected() && a2.state().is_connected() {
1082                break;
1083            }
1084            progress(&mut a1, &mut a2);
1085        }
1086
1087        // Move to "idle" mode
1088        a1.set_initial_stun_rto(IDLE_RTO);
1089        a1.set_max_stun_rto(IDLE_RTO);
1090        a2.set_initial_stun_rto(IDLE_RTO);
1091        a2.set_max_stun_rto(IDLE_RTO);
1092
1093        // Spin for a bit
1094        for _ in 0..10 {
1095            progress(&mut a1, &mut a2);
1096        }
1097
1098        // This is a bit of a hack because we use "insider" knowledge here
1099        // that the next timeout is in fact `IDLE_RTO` away.
1100        let now = a1.poll_timeout().unwrap() - IDLE_RTO;
1101
1102        a1.set_initial_stun_rto(NORMAL_RTO);
1103        a1.set_max_stun_rto(NORMAL_RTO);
1104
1105        let timeout_after = a1.poll_timeout().unwrap();
1106
1107        // After applying the new timeout, it should only be `NORMAL_RTO` away.
1108        assert_eq!(timeout_after, now + NORMAL_RTO);
1109    }
1110
1111    #[test]
1112    fn new_candidates_after_disconnected_should_transition_to_checking() {
1113        let _guard = tracing_subscriber::fmt()
1114            .with_env_filter("trace")
1115            .with_test_writer()
1116            .set_default();
1117
1118        let mut a1 = TestAgent::new(info_span!("L"));
1119        let mut a2 = TestAgent::new(info_span!("R"));
1120
1121        let c1 = host("1.1.1.1:1000", "udp");
1122        a1.add_local_candidate(c1.clone());
1123        a2.add_remote_candidate(c1);
1124
1125        let c2 = host("2.2.2.2:1000", "udp");
1126        a2.add_local_candidate(c2.clone());
1127        a1.add_remote_candidate(c2);
1128
1129        a1.set_controlling(true);
1130        a2.set_controlling(false);
1131
1132        // loop until we're connected.
1133        loop {
1134            if a1.state().is_connected() && a2.state().is_connected() {
1135                break;
1136            }
1137            progress(&mut a1, &mut a2);
1138        }
1139
1140        // signal network outage
1141        a1.drop_sent_packets = true;
1142        a2.drop_sent_packets = true;
1143
1144        loop {
1145            if a1.state().is_disconnected() && a2.state().is_disconnected() {
1146                break;
1147            }
1148            progress(&mut a1, &mut a2);
1149        }
1150
1151        // Reconnect with new candidates
1152        a1.drop_sent_packets = false;
1153        a2.drop_sent_packets = false;
1154
1155        let c1 = host("5.5.5.5:1000", "udp");
1156        a1.add_local_candidate(c1.clone());
1157        a2.add_remote_candidate(c1);
1158
1159        let c2 = host("6.6.6.6:1000", "udp");
1160        a2.add_local_candidate(c2.clone());
1161        a1.add_remote_candidate(c2);
1162
1163        // Clear all existing events
1164        a1.events.clear();
1165        a2.events.clear();
1166
1167        // Reconnect
1168        loop {
1169            if a1.state().is_connected() && a2.state().is_connected() {
1170                break;
1171            }
1172            progress(&mut a1, &mut a2);
1173        }
1174
1175        assert!(a1.has_event(|e| matches!(
1176            e,
1177            IceAgentEvent::IceConnectionStateChange(IceConnectionState::Checking)
1178        )));
1179        assert!(a2.has_event(|e| matches!(
1180            e,
1181            IceAgentEvent::IceConnectionStateChange(IceConnectionState::Checking)
1182        )));
1183    }
1184
1185    #[test]
1186    pub fn symmetric_nat_both_sides() {
1187        let _guard = tracing_subscriber::fmt()
1188            .with_test_writer()
1189            .with_env_filter("trace")
1190            .set_default();
1191
1192        // Both agents are behind symmetric NAT
1193        let mut a1 = TestAgent::new(info_span!("L")).with_symmetric_nat("5.5.5.5");
1194        let mut a2 = TestAgent::new(info_span!("R")).with_symmetric_nat("6.6.6.6");
1195
1196        // Add host candidates. Those will fail behind NAT.
1197        a2.add_remote_candidate(a1.add_host_candidate("1.1.1.1:1000"));
1198        a1.add_remote_candidate(a2.add_host_candidate("2.2.2.2:1000"));
1199
1200        // Add server-reflexive candidates, those will also fail because the NAT is symmetric
1201        a2.add_remote_candidate(a1.server_reflexive_candidate("8.8.8.8:3478", "1.1.1.1:1000"));
1202        a1.add_remote_candidate(a2.server_reflexive_candidate("8.8.8.8:3478", "2.2.2.2:1000"));
1203
1204        // Add relay candidates, those will work
1205        a2.add_remote_candidate(a1.add_relay_candidate("3.3.3.3:1000", "1.1.1.1:1000"));
1206        a1.add_remote_candidate(a2.add_relay_candidate("4.4.4.4:1000", "2.2.2.2:1000"));
1207
1208        a1.set_controlling(true);
1209        a2.set_controlling(false);
1210
1211        loop {
1212            if a1.state().is_connected() && a2.state().is_connected() {
1213                break;
1214            }
1215            progress(&mut a1, &mut a2);
1216        }
1217
1218        // A1 sends from its host candidate with a random port getting assigned by the symmetric NAT.
1219        assert!(a1.has_event(|e| {
1220            matches!(e, IceAgentEvent::NominatedSend { source, destination, .. }
1221                         if source == &sock("1.1.1.1:1000") && destination == &sock("4.4.4.4:1000"))
1222        }));
1223        // A2 sends from its relay candidate, towards the public IP of A1.
1224        assert!(a2.has_event(|e| {
1225            matches!(e, IceAgentEvent::NominatedSend { source, destination, .. }
1226                         if source == &sock("4.4.4.4:1000") && destination.ip() == ip("5.5.5.5"))
1227        }));
1228    }
1229
1230    #[test]
1231    pub fn symmetric_nat_one_side() {
1232        let _guard = tracing_subscriber::fmt()
1233            .with_test_writer()
1234            .with_env_filter("trace")
1235            .set_default();
1236
1237        // Only one agent is behind symmetric NAT.
1238        let mut a1 = TestAgent::new(info_span!("L")).with_symmetric_nat("5.5.5.5");
1239        let mut a2 = TestAgent::new(info_span!("R")).with_port_restricted_nat("6.6.6.6");
1240
1241        // Add host candidates. Those will fail behind NAT.
1242        a2.add_remote_candidate(a1.add_host_candidate("1.1.1.1:1000"));
1243        a1.add_remote_candidate(a2.add_host_candidate("2.2.2.2:1000"));
1244
1245        // Add server-reflexive candidates, those will also fail due to A1's symmetric NAT.
1246        a2.add_remote_candidate(a1.server_reflexive_candidate("8.8.8.8:3478", "1.1.1.1:1000"));
1247        a1.add_remote_candidate(a2.server_reflexive_candidate("8.8.8.8:3478", "2.2.2.2:1000"));
1248
1249        // Add relay candidates, those will work.
1250        a2.add_remote_candidate(a1.add_relay_candidate("3.3.3.3:1000", "1.1.1.1:1000"));
1251        a1.add_remote_candidate(a2.add_relay_candidate("4.4.4.4:1000", "2.2.2.2:1000"));
1252
1253        a1.set_controlling(true);
1254        a2.set_controlling(false);
1255
1256        loop {
1257            if a1.state().is_connected() && a2.state().is_connected() {
1258                break;
1259            }
1260            progress(&mut a1, &mut a2);
1261        }
1262
1263        // A1 sends from its host candidate with a random port getting assigned by the symmetric NAT.
1264        assert!(a1.has_event(|e| {
1265            matches!(e, IceAgentEvent::NominatedSend { source, destination, .. }
1266                         if source == &sock("1.1.1.1:1000") && destination == &sock("4.4.4.4:1000"))
1267        }));
1268        // A2 sends from its relay candidate, towards the public IP of A1.
1269        assert!(a2.has_event(|e| {
1270            matches!(e, IceAgentEvent::NominatedSend { source, destination, .. }
1271                         if source == &sock("4.4.4.4:1000") && destination.ip() == ip("5.5.5.5"))
1272        }));
1273    }
1274
1275    #[test]
1276    fn server_reflexive_candidate_from_different_servers_have_different_ports_on_sym_nat() {
1277        let mut agent = TestAgent::new(info_span!("A")).with_symmetric_nat("4.4.4.4");
1278
1279        let c1 = agent.server_reflexive_candidate("8.8.8.8:3478", "1.1.1.1:1000");
1280        let c2 = agent.server_reflexive_candidate("9.9.9.9:3478", "1.1.1.1:1000");
1281
1282        assert_ne!(c1, c2);
1283    }
1284
1285    #[test]
1286    fn server_reflexive_candidate_from_different_servers_are_equal_on_restricted_nat() {
1287        let mut agent = TestAgent::new(info_span!("A")).with_port_restricted_nat("4.4.4.4");
1288
1289        let c1 = agent.server_reflexive_candidate("8.8.8.8:3478", "1.1.1.1:1000");
1290        let c2 = agent.server_reflexive_candidate("9.9.9.9:3478", "1.1.1.1:1000");
1291
1292        assert_eq!(c1, c2);
1293    }
1294
1295    pub struct TestStunMessage {
1296        transmit: Transmit,
1297        is_binding_request: bool,
1298        is_successful_binding_response: bool,
1299        use_candidate: bool,
1300    }
1301
1302    pub struct TestAgent {
1303        pub start_time: Instant,
1304        pub agent: IceAgent,
1305        pub span: Span,
1306        pub events: Vec<(Duration, IceAgentEvent)>,
1307        pub progress_count: u64,
1308        pub time: Instant,
1309        pub drop_sent_packets: bool,
1310        pub nat: Option<Nat>,
1311    }
1312
1313    impl TestAgent {
1314        pub fn new(span: Span) -> Self {
1315            let now = Instant::now();
1316            TestAgent {
1317                start_time: now,
1318                agent: IceAgent::new(IceCreds::new()),
1319                span,
1320                events: vec![],
1321                progress_count: 0,
1322                time: now,
1323                drop_sent_packets: false,
1324                nat: None,
1325            }
1326        }
1327
1328        pub fn with_symmetric_nat(mut self, external_ip: &str) -> Self {
1329            self.nat = Some(Nat::new_symmetric(external_ip));
1330            self
1331        }
1332
1333        pub fn with_port_restricted_nat(mut self, external_ip: &str) -> Self {
1334            self.nat = Some(Nat::new_port_restricted_cone(external_ip));
1335            self
1336        }
1337
1338        fn add_host_candidate(&mut self, addr: &str) -> Candidate {
1339            self.span.in_scope(|| {
1340                self.agent
1341                    .add_local_candidate(host(addr, "udp"))
1342                    .unwrap()
1343                    .clone()
1344            })
1345        }
1346
1347        fn add_relay_candidate(&mut self, addr: &str, local: &str) -> Candidate {
1348            let local = local.parse().unwrap();
1349            let addr = addr.parse().unwrap();
1350
1351            self.span.in_scope(|| {
1352                self.agent
1353                    .add_local_candidate(Candidate::relayed(addr, local, "udp").unwrap())
1354                    .unwrap()
1355                    .clone()
1356            })
1357        }
1358
1359        fn add_remote_candidate(&mut self, c: Candidate) {
1360            // Round-trip via SDP to simulate signalling protocol.
1361            let c = Candidate::from_sdp_string(&c.to_sdp_string()).unwrap();
1362
1363            self.span.in_scope(|| self.agent.add_remote_candidate(c))
1364        }
1365
1366        /// Simulate STUN to the given server and returned the server-reflexive candidate.
1367        ///
1368        /// Unlike [`TestAgent::add_host_candidate`] and [`TestAgent::add_relay_candidate`],
1369        /// this candidate is **not** added to the agent.
1370        /// Server-reflexive candidates are typically not added locally because one cannot
1371        /// directly send from them.
1372        /// The agent can only send from the base which is a host candidate.
1373        fn server_reflexive_candidate(&mut self, stun_server: &str, base: &str) -> Candidate {
1374            use NatType::*;
1375            let base = base.parse().unwrap();
1376            let stun_server = stun_server.parse().unwrap();
1377
1378            match self.nat.as_mut() {
1379                None => Candidate::server_reflexive(base, base, "udp"),
1380                Some(Nat {
1381                    nat_type: PortRestrictedCone { .. },
1382                    external_ip,
1383                }) => Candidate::server_reflexive(
1384                    SocketAddr::new(*external_ip, base.port()),
1385                    base,
1386                    "udp",
1387                ),
1388                Some(Nat {
1389                    nat_type: Symmetric { mappings },
1390                    external_ip,
1391                }) => {
1392                    let outside = symmetric_nat_lookup(base, stun_server, mappings);
1393
1394                    Candidate::server_reflexive(SocketAddr::new(*external_ip, outside), base, "udp")
1395                }
1396            }
1397            .unwrap()
1398        }
1399
1400        fn has_event(&self, predicate: impl Fn(&IceAgentEvent) -> bool) -> bool {
1401            self.events.iter().any(|(_, e)| predicate(e))
1402        }
1403
1404        fn advance_time(&mut self) {
1405            self.time = self
1406                .span
1407                .in_scope(|| self.agent.poll_timeout())
1408                .unwrap_or(self.time);
1409        }
1410
1411        fn poll_next_stun_message(&mut self) -> TestStunMessage {
1412            let transmit = self.poll_transmit().expect("agent should emit a transmit");
1413            let message =
1414                StunMessage::parse(&transmit.contents).expect("IceAgent to only emit StunMessages");
1415
1416            TestStunMessage {
1417                is_binding_request: message.is_binding_request(),
1418                is_successful_binding_response: message.is_successful_binding_response(),
1419                use_candidate: message.use_candidate(),
1420                transmit,
1421            }
1422        }
1423    }
1424
1425    pub fn progress(a1: &mut TestAgent, a2: &mut TestAgent) {
1426        let (f, t) = if a1.progress_count % 2 == a2.progress_count % 2 {
1427            (a2, a1)
1428        } else {
1429            (a1, a2)
1430        };
1431
1432        t.progress_count += 1;
1433        if t.progress_count > 100 {
1434            panic!("Test looped more than 100 times");
1435        }
1436
1437        if let Some(trans) = f.span.in_scope(|| f.agent.poll_transmit()) {
1438            let message =
1439                StunMessage::parse(&trans.contents).expect("IceAgent to only emit StunMessages");
1440
1441            // rewrite receive with test transforms, and potentially drop the packet.
1442            if let Some((source, destination)) = transform(trans.source, trans.destination, f, t) {
1443                if f.drop_sent_packets {
1444                    // drop packet
1445                    t.span.in_scope(|| t.agent.handle_timeout(t.time));
1446                } else {
1447                    if source != trans.source {
1448                        f.span.in_scope(|| {
1449                            tracing::trace!("Outbound NAT: {} => {}", trans.source, source)
1450                        });
1451                    }
1452
1453                    if destination != trans.destination {
1454                        t.span.in_scope(|| {
1455                            tracing::trace!("Inbound NAT: {} => {}", trans.destination, destination)
1456                        });
1457                    }
1458
1459                    let packet = StunPacket {
1460                        proto: trans.proto,
1461                        source,
1462                        destination,
1463                        message,
1464                    };
1465                    t.span.in_scope(|| t.agent.handle_packet(t.time, packet));
1466                }
1467            } else {
1468                tracing::debug!(from = %trans.source, to = %trans.destination, "NAT: Dropping packet");
1469
1470                // drop packet
1471                t.span.in_scope(|| t.agent.handle_timeout(t.time));
1472            }
1473        } else {
1474            t.span.in_scope(|| t.agent.handle_timeout(t.time));
1475        }
1476
1477        let time = t.time;
1478
1479        let tim_f = f.span.in_scope(|| f.agent.poll_timeout()).unwrap_or(f.time);
1480        f.time = tim_f;
1481
1482        let tim_t = t.span.in_scope(|| t.agent.poll_timeout()).unwrap_or(t.time);
1483        t.time = tim_t;
1484
1485        while let Some(v) = t.span.in_scope(|| t.agent.poll_event()) {
1486            println!("Polled event: {v:?}");
1487            use IceAgentEvent::*;
1488            f.span.in_scope(|| {
1489                if let IceRestart(v) = &v {
1490                    f.agent.set_remote_credentials(v.clone())
1491                }
1492            });
1493            t.events.push((time - t.start_time, v));
1494        }
1495    }
1496
1497    // These helpers intentionally bypass `progress()` so the regression test above
1498    // can hold specific STUN packets and inject the signalled host candidate in the
1499    // exact Attempt window being tested.
1500    fn progress_without_network(from: &mut TestAgent, to: &mut TestAgent) {
1501        let now = from.time;
1502        from.handle_timeout(now);
1503        drain_manual_test_events(to, from);
1504        from.advance_time();
1505        to.advance_time();
1506    }
1507
1508    fn drain_manual_test_events(from: &mut TestAgent, to: &mut TestAgent) {
1509        let time = to.time;
1510        while let Some(v) = to.span.in_scope(|| to.agent.poll_event()) {
1511            println!("Polled event: {v:?}");
1512            use IceAgentEvent::*;
1513            from.span.in_scope(|| {
1514                if let IceRestart(v) = &v {
1515                    from.agent.set_remote_credentials(v.clone())
1516                }
1517            });
1518            to.events.push((time - to.start_time, v));
1519        }
1520    }
1521
1522    fn progress_one_message(from: &mut TestAgent, to: &mut TestAgent) -> TestStunMessage {
1523        let msg = from.poll_next_stun_message();
1524
1525        deliver_transmit(from, to, &msg.transmit);
1526
1527        msg
1528    }
1529
1530    fn deliver_transmit(from: &mut TestAgent, to: &mut TestAgent, trans: &Transmit) {
1531        let message =
1532            StunMessage::parse(&trans.contents).expect("IceAgent to only emit StunMessages");
1533        let packet = StunPacket {
1534            proto: trans.proto,
1535            source: trans.source,
1536            destination: trans.destination,
1537            message,
1538        };
1539        to.span.in_scope(|| to.agent.handle_packet(to.time, packet));
1540        drain_manual_test_events(from, to);
1541        from.advance_time();
1542        to.advance_time();
1543    }
1544
1545    impl Deref for TestAgent {
1546        type Target = IceAgent;
1547
1548        fn deref(&self) -> &Self::Target {
1549            &self.agent
1550        }
1551    }
1552
1553    impl DerefMut for TestAgent {
1554        fn deref_mut(&mut self) -> &mut Self::Target {
1555            &mut self.agent
1556        }
1557    }
1558
1559    /// Performs a binary search for the earliest possible `Instant`.
1560    fn find_earliest_now() -> Instant {
1561        const ONE_YEAR: Duration = Duration::from_secs(60 * 60 * 24 * 365);
1562
1563        let mut now = Instant::now();
1564        let mut step = ONE_YEAR;
1565
1566        while step > Duration::from_secs(1) {
1567            match now.checked_sub(step) {
1568                Some(earlier) => {
1569                    now = earlier;
1570                    step *= 2; // Increase step-count to accelerate finding the earliest possible `Instant`.
1571                }
1572                None => {
1573                    step /= 2; // Decrease step-count to narrow down on the earliest possible `Instant`.
1574                }
1575            }
1576        }
1577
1578        now
1579    }
1580
1581    pub fn sock(s: impl Into<String>) -> SocketAddr {
1582        let s: String = s.into();
1583        s.parse().unwrap()
1584    }
1585
1586    pub fn ip(s: impl Into<String>) -> IpAddr {
1587        let s: String = s.into();
1588        s.parse().unwrap()
1589    }
1590
1591    pub fn host(s: impl Into<String>, proto: impl TryInto<Protocol>) -> Candidate {
1592        Candidate::host(sock(s), proto).unwrap()
1593    }
1594
1595    #[derive(Debug, Clone)]
1596    enum NatType {
1597        PortRestrictedCone {
1598            mappings: HashMap<(SocketAddr, SocketAddr), u16>,
1599        },
1600        Symmetric {
1601            mappings: HashMap<(SocketAddr, SocketAddr), u16>,
1602        },
1603    }
1604
1605    #[derive(Debug, Clone)]
1606    pub struct Nat {
1607        external_ip: IpAddr,
1608        nat_type: NatType,
1609    }
1610
1611    impl Nat {
1612        fn new_port_restricted_cone(external_ip: &str) -> Self {
1613            Self {
1614                external_ip: external_ip.parse().expect("Invalid IP address"),
1615                nat_type: NatType::PortRestrictedCone {
1616                    mappings: Default::default(),
1617                },
1618            }
1619        }
1620
1621        fn new_symmetric(external_ip: &str) -> Self {
1622            Self {
1623                external_ip: external_ip.parse().expect("Invalid IP address"),
1624                nat_type: NatType::Symmetric {
1625                    mappings: Default::default(),
1626                },
1627            }
1628        }
1629
1630        fn transform_outbound(
1631            &mut self,
1632            from: SocketAddr,
1633            to: SocketAddr,
1634        ) -> (SocketAddr, SocketAddr) {
1635            let external_port = match &mut self.nat_type {
1636                NatType::Symmetric { mappings } => {
1637                    // For symmetric NATs, the key is the 4-tuple of the connection.
1638
1639                    symmetric_nat_lookup(from, to, mappings)
1640                }
1641                NatType::PortRestrictedCone { mappings } => {
1642                    // For a port-restricted-cone NAT, the key is also the 4-tuple of the connection.
1643                    // Contrary to a symmetric NAT, the source port is preserved.
1644                    *mappings.entry((from, to)).or_insert(from.port())
1645                }
1646            };
1647
1648            (SocketAddr::new(self.external_ip, external_port), to)
1649        }
1650
1651        fn transform_inbound(
1652            &self,
1653            from: SocketAddr,
1654            to: SocketAddr,
1655        ) -> Option<(SocketAddr, SocketAddr)> {
1656            let internal_addr = match &self.nat_type {
1657                // For symmetric NAT, need exact source match of from == dst and only on the assigned port.
1658                NatType::Symmetric { mappings } => {
1659                    let ((src, _), _) = mappings
1660                        .iter()
1661                        .find(|((_, dst), outside)| from == *dst && **outside == to.port())?;
1662
1663                    *src
1664                }
1665                // For restricted-cone NAT, traffic on the outside assigned port is routed back
1666                // if we have previously contacted this IP + port combination.
1667                NatType::PortRestrictedCone { mappings } => {
1668                    let ((src, _), _) = mappings
1669                        .iter()
1670                        .find(|((_, dst), outside)| from == *dst && **outside == to.port())?;
1671
1672                    *src
1673                }
1674            };
1675
1676            Some((from, internal_addr))
1677        }
1678    }
1679
1680    fn symmetric_nat_lookup(
1681        src: SocketAddr,
1682        dst: SocketAddr,
1683        mappings: &mut HashMap<(SocketAddr, SocketAddr), u16>,
1684    ) -> u16 {
1685        let outside_port = loop {
1686            let port = str0m_proto::NonCryptographicRng::u16();
1687
1688            if mappings.values().any(|p| *p == port) {
1689                continue;
1690            }
1691
1692            break port;
1693        };
1694
1695        *mappings.entry((src, dst)).or_insert(outside_port)
1696    }
1697
1698    /// Transform function with flexible NAT support
1699    fn transform(
1700        from: SocketAddr,
1701        to: SocketAddr,
1702        from_agent: &mut TestAgent,
1703        to_agent: &mut TestAgent,
1704    ) -> Option<(SocketAddr, SocketAddr)> {
1705        if from.port() == 9999 || to.port() == 9999 {
1706            return None;
1707        }
1708
1709        let outgoing_is_from_relay = from_agent
1710            .local_candidates()
1711            .any(|c| c.addr() == from && c.kind() == CandidateKind::Relayed);
1712
1713        // If NAT is present on sending agent, apply it.
1714        let (from, to) = if let Some(nat) = &mut from_agent.nat {
1715            // If our traffic is "from" a relay candidate, the NAT does not apply.
1716            if outgoing_is_from_relay {
1717                (from, to)
1718            } else {
1719                nat.transform_outbound(from, to)
1720            }
1721        } else {
1722            (from, to)
1723        };
1724
1725        let incoming_is_from_relay = to_agent
1726            .local_candidates()
1727            .any(|c| c.addr() == to && c.kind() == CandidateKind::Relayed);
1728
1729        // If NAT is present on receiving agent, apply it.
1730        if let Some(nat) = &mut to_agent.nat {
1731            // If our traffic is "to" a relay candidate, the NAT does not apply.
1732            if incoming_is_from_relay {
1733                Some((from, to))
1734            } else {
1735                if nat.external_ip != to.ip() {
1736                    return None;
1737                }
1738
1739                nat.transform_inbound(from, to)
1740            }
1741        } else {
1742            Some((from, to))
1743        }
1744    }
1745}