use std::time::{Duration, Instant};
use sansio::Protocol;
use super::agent_rfc8445_test::*;
use super::*;
use crate::candidate::candidate_relay::CandidateRelayConfig;
const RELAY: &str = "203.0.113.9:6000";
const MAPPED: &str = "198.51.100.7:4000";
fn relay(at: &str) -> Candidate {
let at = addr(at);
let mapped = addr(MAPPED);
CandidateRelayConfig {
base_config: CandidateConfig {
network: "udp".to_owned(),
address: at.ip().to_string(),
port: at.port(),
component: 1,
..Default::default()
},
rel_addr: mapped.ip().to_string(),
rel_port: mapped.port(),
url: None,
}
.new_candidate_relay()
.unwrap()
}
struct Out {
local: SocketAddr,
to: SocketAddr,
message: Message,
}
fn run_peer(a: &mut Agent, from: Instant, until: Instant, mapped: Option<SocketAddr>) -> Vec<Out> {
let mut out = vec![];
let mut now = from;
loop {
a.handle_timeout(now).unwrap();
loop {
let mut batch = vec![];
while let Some(t) = a.poll_write() {
let mut m = Message {
raw: t.message.to_vec(),
..Message::default()
};
m.decode().unwrap();
batch.push(Out {
local: t.transport.local_addr,
to: t.transport.peer_addr,
message: m,
});
}
if batch.is_empty() {
break;
}
for o in &batch {
if o.message.typ != BINDING_REQUEST {
continue;
}
let response = peer_response(
BINDING_SUCCESS,
o.message.transaction_id,
mapped.unwrap_or(o.local),
None,
);
let _ = a.handle_read(TaggedBytesMut {
now,
transport: TransportContext {
local_addr: o.local,
peer_addr: o.to,
ecn: None,
transport_protocol: TransportProtocol::UDP,
},
message: BytesMut::from(&response.raw[..]),
});
}
out.extend(batch);
}
match a.poll_timeout() {
Some(next) if next <= until => now = next.max(now + Duration::from_micros(1)),
_ => return out,
}
}
}
fn states(a: &mut Agent) -> Vec<ConnectionState> {
let mut states = vec![];
while let Some(e) = a.poll_event() {
if let Event::ConnectionStateChange(s) = e.event {
states.push(s);
}
}
states
}
fn selected_local_type(a: &Agent) -> Option<CandidateType> {
a.get_selected_candidate_pair()
.map(|(local, _)| local.candidate_type())
}
fn from_peer(local: &str) -> TransportContext {
TransportContext {
local_addr: addr(local),
peer_addr: addr(REMOTE_A),
ecn: None,
transport_protocol: TransportProtocol::UDP,
}
}
fn connected_over_host() -> (Agent, Instant) {
let start = Instant::now();
let mut a = bare_agent(start, config(true));
assert!(a.add_local_candidate(relay(RELAY)).unwrap());
a.add_remote_candidate(host(addr(REMOTE_A))).unwrap();
a.start_connectivity_checks(start, true, REMOTE_UFRAG.to_owned(), REMOTE_PWD.to_owned())
.unwrap();
let now = start + Duration::from_secs(2);
run_peer(&mut a, start, now, None);
assert_eq!(a.state(), ConnectionState::Connected);
assert_eq!(
selected_local_type(&a),
Some(CandidateType::Host),
"the precondition: the host pair is selected"
);
assert_eq!(
a.media_path().map(|p| p.local_addr),
Some(addr(LOCAL)),
"the precondition: data runs on the host pair"
);
assert!(a.accepts_data(from_peer(LOCAL)));
states(&mut a);
(a, now)
}
fn new_generation_from_peer(a: &mut Agent) {
a.set_remote_credentials(REMOTE_UFRAG.to_owned(), REMOTE_PWD.to_owned())
.unwrap();
a.add_remote_candidate(host(addr(REMOTE_A))).unwrap();
}
#[test]
fn test_a_restart_into_the_relay_policy_does_not_keep_a_host_path() {
for keep_local_candidates in [true, false] {
let (mut a, now) = connected_over_host();
a.set_candidate_types(vec![CandidateType::Relay]);
a.restart(now, String::new(), String::new(), keep_local_candidates)
.unwrap();
assert_eq!(
a.media_path(),
None,
"keep={keep_local_candidates}: the host path is not kept across the restart"
);
assert!(!a.accepts_data(from_peer(LOCAL)));
assert_eq!(a.state(), ConnectionState::Checking);
assert_eq!(states(&mut a), vec![ConnectionState::Checking]);
assert!(
a.local_candidates
.iter()
.all(|c| c.candidate_type() == CandidateType::Relay),
"keep={keep_local_candidates}: the new generation has relayed candidates only"
);
let waiting = run_peer(&mut a, now, now + Duration::from_secs(10), None);
assert!(
waiting.iter().all(|o| o.local != addr(LOCAL)),
"keep={keep_local_candidates}: {} datagrams left on the host base while waiting",
waiting.iter().filter(|o| o.local == addr(LOCAL)).count()
);
assert_eq!(a.media_path(), None);
if !keep_local_candidates {
assert!(a.add_local_candidate(relay(RELAY)).unwrap());
}
assert!(
!a.add_local_candidate(host(addr(LOCAL))).unwrap(),
"a host candidate is refused under the relay policy"
);
new_generation_from_peer(&mut a);
let t = now + Duration::from_secs(10);
let after = run_peer(&mut a, t, t + Duration::from_secs(5), None);
assert!(
after.iter().all(|o| o.local != addr(LOCAL)),
"keep={keep_local_candidates}: nothing leaves on the host base after the restart"
);
assert!(
after.iter().any(|o| o.local == addr(RELAY)),
"the precondition: the relayed pair was checked"
);
assert_eq!(a.state(), ConnectionState::Connected);
assert_eq!(selected_local_type(&a), Some(CandidateType::Relay));
assert_eq!(a.media_path().map(|p| p.local_addr), Some(addr(RELAY)));
assert_eq!(a.retired_media_path(), None, "nor is the host path retired");
assert!(!a.accepts_data(from_peer(LOCAL)));
assert!(a.accepts_data(from_peer(RELAY)));
assert_eq!(states(&mut a), vec![ConnectionState::Connected]);
}
}
#[test]
fn test_a_second_restart_into_the_relay_policy_drops_the_path_the_first_kept() {
let (mut a, now) = connected_over_host();
a.restart(now, String::new(), String::new(), true).unwrap();
assert_eq!(
a.media_path().map(|p| p.local_addr),
Some(addr(LOCAL)),
"the precondition: the first restart keeps the host path (RFC 8445 Section 9)"
);
assert_eq!(a.state(), ConnectionState::Connected);
a.set_candidate_types(vec![CandidateType::Relay]);
a.restart(now, String::new(), String::new(), true).unwrap();
assert_eq!(a.media_path(), None);
assert_eq!(a.state(), ConnectionState::Checking);
let out = run_peer(&mut a, now, now + Duration::from_secs(10), None);
assert!(out.iter().all(|o| o.local != addr(LOCAL)));
}
#[test]
fn test_a_new_candidate_policy_without_a_restart_keeps_the_pair_in_use() {
let (mut a, now) = connected_over_host();
a.set_candidate_types(vec![CandidateType::Relay]);
let out = run_peer(&mut a, now, now + Duration::from_secs(20), None);
assert_eq!(a.state(), ConnectionState::Connected);
assert_eq!(selected_local_type(&a), Some(CandidateType::Host));
assert_eq!(a.media_path().map(|p| p.local_addr), Some(addr(LOCAL)));
assert!(a.accepts_data(from_peer(LOCAL)));
assert!(
out.iter()
.filter(|o| o.local == addr(LOCAL) && o.message.typ == BINDING_REQUEST)
.count()
>= 3,
"consent checks go on on the host pair"
);
assert!(
a.local_candidates
.iter()
.any(|c| c.candidate_type() == CandidateType::Host)
);
}
#[test]
fn test_a_restart_keeps_a_path_the_candidate_types_still_allow() {
for types in [
vec![],
vec![CandidateType::Host, CandidateType::Relay],
vec![CandidateType::Host],
] {
let (mut a, now) = connected_over_host();
a.set_candidate_types(types.clone());
a.restart(now, String::new(), String::new(), true).unwrap();
assert_eq!(
a.media_path().map(|p| p.local_addr),
Some(addr(LOCAL)),
"{types:?}"
);
assert_eq!(a.state(), ConnectionState::Connected, "{types:?}");
assert!(a.accepts_data(from_peer(LOCAL)), "{types:?}");
}
}
#[test]
fn test_a_relayed_path_through_a_learned_candidate_is_kept_across_the_restart() {
let start = Instant::now();
let mut a = Agent::new(
start,
Arc::new(AgentConfig {
candidate_types: vec![CandidateType::Relay],
..config(true)
}),
provider(),
)
.unwrap();
assert!(a.add_local_candidate(relay(RELAY)).unwrap());
a.add_remote_candidate(host(addr(REMOTE_A))).unwrap();
a.start_connectivity_checks(start, true, REMOTE_UFRAG.to_owned(), REMOTE_PWD.to_owned())
.unwrap();
let now = start + Duration::from_secs(5);
run_peer(&mut a, start, now, Some(addr("198.51.100.99:7777")));
assert_eq!(
a.state(),
ConnectionState::Connected,
"the precondition: connected before the restart"
);
assert_eq!(
selected_local_type(&a),
Some(CandidateType::PeerReflexive),
"the precondition: the selected pair's local candidate is a learned one"
);
assert_eq!(a.media_path().map(|p| p.local_addr), Some(addr(RELAY)));
a.restart(now, String::new(), String::new(), true).unwrap();
assert_eq!(
a.media_path().map(|p| p.local_addr),
Some(addr(RELAY)),
"a relayed path is kept across the restart"
);
assert_eq!(a.state(), ConnectionState::Connected);
}