use super::super::budget::SESSION_BYTES;
use super::stun_binding_request;
use super::*;
use crate::stream_wire::{encode_request, StreamRequest};
use crate::tunnel::{self, encode_ws, read_ws, WsFrame};
use crate::types::{IngressSocket, WireSocket};
use crate::wire;
use serde_json::json;
use std::sync::Arc;
use std::time::{Duration, Instant};
use str0m::change::SdpAnswer;
use str0m::net::{Protocol, Receive};
use str0m::{Candidate, Event, Input, Output, Rtc};
use tokio::io::DuplexStream;
use tokio::net::{UdpSocket, UnixListener};
use tokio::sync::mpsc;
use tokio::task::JoinSet;
fn empty_ingress() -> Arc<IngressSocket> {
Arc::new(IngressSocket::default())
}
fn empty_wire() -> Arc<WireSocket> {
Arc::new(WireSocket::default())
}
#[test]
fn full_ice_answerer_punches_two_port_restricted_nats() {
let base: [SocketAddr; 2] = [
"10.1.0.2:4000".parse().unwrap(),
"10.2.0.2:5000".parse().unwrap(),
];
let public: [SocketAddr; 2] = [
"203.0.113.1:14000".parse().unwrap(),
"203.0.113.2:15000".parse().unwrap(),
];
let mut peers = [rtc(), rtc()];
for i in 0..2 {
peers[i].add_local_candidate(Candidate::host(base[i], "udp").unwrap());
peers[i]
.add_local_candidate(Candidate::server_reflexive(public[i], base[i], "udp").unwrap());
}
let mut changes = peers[0].sdp_api();
changes.add_channel("http.request/1".into());
let (offer, pending) = changes.apply().unwrap();
let sdp = offer
.to_sdp_string()
.lines()
.filter(|line| !line.starts_with("a=candidate:"))
.collect::<Vec<_>>()
.join("\r\n")
+ "\r\n";
let mut binding = Binding {
nonce: None,
candidates: 0,
};
let answer = binding.signal(&mut peers[1], json!({"type":"offer", "version":1,
"offer_nonce":"0123456789abcdef", "dtls_fingerprint":fingerprint(&sdp).unwrap(), "sdp":sdp})).unwrap().unwrap();
let answer_sdp = answer["sdp"].as_str().unwrap();
assert!(!answer_sdp.contains("a=ice-lite"));
assert!(answer_sdp.contains("203.0.113.2 15000 typ srflx"));
peers[0]
.sdp_api()
.accept_answer(pending, SdpAnswer::from_sdp_string(answer_sdp).unwrap())
.unwrap();
for candidate in [
"candidate:1 1 udp 2113937151 test.local 4000 typ host".to_owned(),
Candidate::host(base[0], "udp").unwrap().to_sdp_string(),
format!("candidate:2 1 udp 1677729535 {} {} typ srflx raddr 0.0.0.0 rport 0 generation 0 network-cost 999", public[0].ip(), public[0].port()),
] {
binding.signal(&mut peers[1], json!({"type":"candidate", "offer_nonce":"0123456789abcdef", "candidate":candidate})).unwrap();
}
let start = Instant::now();
let mut opened = [false; 2];
let mut connected = [false; 2];
let mut checked = std::collections::HashSet::new();
for tick in 0..2000 {
let now = start + Duration::from_millis(tick * 10);
for i in 0..2 {
peers[i].handle_input(Input::Timeout(now)).unwrap();
loop {
match peers[i].poll_output().unwrap() {
Output::Timeout(_) => break,
Output::Event(Event::ChannelOpen(_, _)) => connected[i] = true,
Output::Transmit(t) => {
assert_eq!(
t.source, base[i],
"srflx traffic must use its bound base socket"
);
if i == 1 && t.contents[..2] == [0, 1] {
checked.insert(t.destination);
}
let other = 1 - i;
if t.destination != public[other] {
continue;
}
opened[i] = true;
if !opened[other] {
continue;
}
let contents = (&*t.contents).try_into().unwrap();
let input = Input::Receive(
now,
Receive {
proto: Protocol::Udp,
source: public[i],
destination: base[other],
contents,
},
);
assert!(peers[other].accepts(&input));
peers[other].handle_input(input).unwrap();
}
_ => {}
}
}
}
if connected == [true; 2] {
break;
}
}
assert!(
checked.contains(&base[0]),
"answerer never checked host candidate"
);
assert!(
checked.contains(&public[0]),
"answerer never checked trickled srflx candidate"
);
assert_eq!(opened, [true; 2]);
assert_eq!(
connected, [true; 2],
"DataChannel must connect through translated addresses"
);
}
#[tokio::test]
async fn answerer_checks_trickled_candidates_from_the_stun_gathering_socket() {
let stun = UdpSocket::bind("127.0.0.1:0").await.unwrap();
let stun_address = stun.local_addr().unwrap();
let responder = tokio::spawn(async move {
let mut request = [0; 20];
let (_, peer) = stun.recv_from(&mut request).await.unwrap();
let mut reply = request.to_vec();
reply[..4].copy_from_slice(&[1, 1, 0, 12]);
reply.extend_from_slice(&[0, 0x20, 0, 8, 0, 1]);
reply.extend_from_slice(&(peer.port() ^ 0x2112).to_be_bytes());
reply.extend_from_slice(&(u32::from_be_bytes([203, 0, 113, 5]) ^ 0x2112a442).to_be_bytes());
stun.send_to(&reply, peer).await.unwrap();
peer
});
let mut offerer = rtc();
let mut changes = offerer.sdp_api();
changes.add_media(
str0m::media::MediaKind::Audio,
str0m::media::Direction::SendRecv,
None,
None,
None,
);
changes.add_channel("http.request/1".into());
let (offer, _) = changes.apply().unwrap();
let sdp = offer.to_sdp_string();
let (mut signal, server) = tokio::io::duplex(65536);
let handle = WebRtcHandle::new();
let cancel = handle.clone();
let task = tokio::spawn(async move {
let (read, write) = tokio::io::split(server);
serve(
read,
write,
empty_ingress(),
cancel,
vec![stun_address],
Some("127.0.0.1:0".parse().unwrap()),
)
.await
});
write_signal(&mut signal, &json!({"type":"offer", "version":1,
"offer_nonce":"0123456789abcdef", "dtls_fingerprint":fingerprint(&sdp).unwrap(), "sdp":sdp})).await.unwrap();
let answer = tokio::time::timeout(Duration::from_secs(3), read_signal(&mut signal))
.await
.unwrap()
.unwrap();
let bound = responder.await.unwrap();
let answer_sdp = answer["sdp"].as_str().unwrap();
assert!(!answer_sdp.contains("a=ice-lite"));
assert!(answer_sdp.contains(&format!("203.0.113.5 {} typ srflx", bound.port())));
let mut trickled = false;
for _ in 0..answer_sdp
.lines()
.filter(|line| line.starts_with("a=candidate:"))
.count()
{
let msg = read_signal(&mut signal).await.unwrap();
assert_eq!(msg["offer_nonce"], "0123456789abcdef");
assert_eq!(msg["sdp_mline_index"], 1);
trickled |= msg["candidate"].as_str().unwrap().contains("typ srflx");
}
assert!(trickled);
let host = UdpSocket::bind("127.0.0.1:0").await.unwrap();
let reflexive = UdpSocket::bind("127.0.0.1:0").await.unwrap();
for candidate in [
"candidate:1 1 udp 2113937151 test.local 4000 typ host".to_owned(),
Candidate::host(host.local_addr().unwrap(), "udp").unwrap().to_sdp_string(),
format!("candidate:2 1 udp 1677729535 127.0.0.1 {} typ srflx raddr 0.0.0.0 rport 0 generation 0 network-cost 999", reflexive.local_addr().unwrap().port()),
] {
write_signal(&mut signal, &json!({"type":"candidate", "offer_nonce":"0123456789abcdef", "candidate":candidate})).await.unwrap();
}
for remote in [&host, &reflexive] {
let mut packet = [0; 1500];
let (n, source) =
tokio::time::timeout(Duration::from_secs(2), remote.recv_from(&mut packet))
.await
.unwrap()
.unwrap();
assert!(n > 20);
assert_eq!(&packet[..2], &[0, 1]);
assert_eq!(source, bound);
}
handle.close();
task.await.unwrap().unwrap();
}
pub(crate) struct Browser {
rtc: Rtc,
socket: UdpSocket,
signal: DuplexStream,
channel: str0m::channel::ChannelId,
handle: WebRtcHandle,
task: tokio::task::JoinHandle<Result<(), String>>,
partial: Vec<u8>,
}
impl Drop for Browser {
fn drop(&mut self) {
self.handle.close();
self.task.abort();
}
}
impl Browser {
async fn new(method: &str, ingress: Arc<IngressSocket>) -> Self {
Self::with_stun(method, ingress, vec![]).await
}
async fn with_stun(method: &str, ingress: Arc<IngressSocket>, stun: Vec<SocketAddr>) -> Self {
Self::with_connection(method, ingress, stun).await
}
async fn with_connection(
method: &str,
ingress: Arc<IngressSocket>,
stun: Vec<SocketAddr>,
) -> Self {
let socket = UdpSocket::bind("127.0.0.1:0").await.unwrap();
let mut rtc = Rtc::builder()
.set_sctp_max_buffered_amount(FRAME)
.build(Instant::now());
rtc.add_local_candidate(Candidate::host(socket.local_addr().unwrap(), "udp").unwrap());
let mut changes = rtc.sdp_api();
let channel = changes.add_channel(method.into());
let (offer, pending) = changes.apply().unwrap();
let sdp = offer.to_sdp_string();
let (mut signal, server) = tokio::io::duplex(65536);
let handle = WebRtcHandle::new();
let server_handle = handle.clone();
let gathered = !stun.is_empty();
let task = tokio::spawn(async move {
let (read, write) = tokio::io::split(server);
serve(
read,
write,
ingress,
server_handle,
stun,
Some("127.0.0.1:0".parse().unwrap()),
)
.await
});
write_signal(&mut signal, &serde_json::json!({"type":"offer", "version":1,
"offer_nonce":"0123456789abcdef", "dtls_fingerprint":fingerprint(&sdp).unwrap(), "sdp":sdp})).await.unwrap();
let answer = tokio::time::timeout(Duration::from_secs(5), read_signal(&mut signal))
.await
.unwrap()
.unwrap();
if gathered {
assert!(answer["sdp"].as_str().unwrap().contains("typ srflx"));
}
assert_eq!(answer["offer_nonce"], "0123456789abcdef");
assert_eq!(
answer["dtls_fingerprint"],
fingerprint(answer["sdp"].as_str().unwrap()).unwrap()
);
let candidate = tokio::time::timeout(Duration::from_secs(2), read_signal(&mut signal))
.await
.unwrap()
.unwrap();
assert_eq!(candidate["type"], "candidate");
assert_eq!(candidate["offer_nonce"], "0123456789abcdef");
Candidate::from_sdp_string(candidate["candidate"].as_str().unwrap()).unwrap();
rtc.sdp_api()
.accept_answer(
pending,
SdpAnswer::from_sdp_string(answer["sdp"].as_str().unwrap()).unwrap(),
)
.unwrap();
let mut browser = Self {
rtc,
socket,
signal,
channel,
handle,
task,
partial: vec![],
};
tokio::time::timeout(Duration::from_secs(5), async {
loop {
if matches!(browser.step().await, Some(Event::ChannelOpen(_, _))) {
break;
}
}
})
.await
.unwrap();
browser
}
async fn step(&mut self) -> Option<Event> {
let deadline = loop {
match self.rtc.poll_output().unwrap() {
Output::Timeout(t) => break t,
Output::Transmit(t) => {
let _ = self.socket.send_to(&t.contents, t.destination).await;
}
Output::Event(e) => return Some(e),
}
};
let wait = deadline
.saturating_duration_since(Instant::now())
.min(Duration::from_millis(100));
let mut buf = [0; 65536];
tokio::select! {
_ = tokio::time::sleep(wait) => { self.rtc.handle_input(Input::Timeout(Instant::now())).unwrap(); }
received = self.socket.recv_from(&mut buf) => {
let (n, source) = received.unwrap();
if let Ok(contents) = (&buf[..n]).try_into() {
self.rtc.handle_input(Input::Receive(Instant::now(), Receive { proto: Protocol::Udp, source,
destination:self.socket.local_addr().unwrap(), contents })).unwrap();
}
}
}
None
}
fn send(&mut self, bytes: &[u8]) {
for chunk in segment(bytes) {
assert!(self
.rtc
.channel(self.channel)
.unwrap()
.write(true, &chunk)
.unwrap());
}
}
async fn receive(&mut self) -> Vec<u8> {
tokio::time::timeout(Duration::from_secs(5), async {
loop {
if let Some(Event::ChannelData(data)) = self.step().await {
assert!(data.binary);
assert!(data.data.len() <= 16384);
self.partial.extend_from_slice(&data.data[1..]);
if data.data[0] & 1 == 0 {
return std::mem::take(&mut self.partial);
}
}
}
})
.await
.unwrap()
}
pub(crate) async fn expect_close(&mut self) {
tokio::time::timeout(Duration::from_secs(10), async {
loop {
match self.step().await {
Some(Event::ChannelClose(_)) | Some(Event::Closed) => break,
_ => {}
}
}
})
.await
.unwrap();
}
fn method(&mut self, method: &str) {
self.send(&wire::encode_request(method, &[]).unwrap());
}
}
#[tokio::test]
async fn wire_channel_splices_to_wire_socket() {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let dir = tempfile::tempdir().unwrap();
let sock = dir.path().join("wire.sock");
let listener = UnixListener::bind(&sock).unwrap();
let server = tokio::spawn(async move {
let (mut stream, _) = listener.accept().await.unwrap();
let mut line = Vec::new();
loop {
let mut byte = [0u8; 1];
stream.read_exact(&mut byte).await.unwrap();
line.push(byte[0]);
if byte[0] == b'\n' {
break;
}
}
assert_eq!(
line.as_slice(),
br#"{"v":1,"carrier":"webrtc","origin":""}
"#
);
let mut buf = [0u8; 32];
let n = stream.read(&mut buf).await.unwrap();
assert_eq!(&buf[..n], b"ping-wire");
stream.write_all(b"pong-wire").await.unwrap();
let _ = stream.shutdown().await;
});
let mut tasks = JoinSet::new();
let (output, mut outgoing) = mpsc::channel(16);
let mut rtc = rtc();
let id = rtc.sdp_api().add_channel("wire/1".into());
let wire = Arc::new(WireSocket { path: Some(sock) });
let channel = open_channel(
id,
"wire/1".into(),
empty_ingress(),
wire,
&mut tasks,
output,
ByteBudget::default(),
);
assert!(channel
.input
.push(wire::encode_request("wire/1", &[]).unwrap()));
assert!(channel.input.push(b"ping-wire".to_vec()));
let finished = tokio::time::timeout(Duration::from_secs(5), async {
loop {
match outgoing.recv().await {
Some(Out::Finished(finished)) if finished == id => break,
Some(_) => {}
None => panic!("channel output closed before Finished"),
}
}
})
.await;
assert!(finished.is_ok(), "wire channel splice timed out");
server.await.unwrap();
tasks.join_next().await.unwrap().unwrap();
}
#[tokio::test]
async fn offer_answer_establishes_datachannel() {
let mut b = Browser::new("http.request/1", empty_ingress()).await;
write_signal(
&mut b.signal,
&serde_json::json!({"type":"close","offer_nonce":"0123456789abcdef"}),
)
.await
.unwrap();
tokio::time::timeout(Duration::from_secs(2), &mut b.task)
.await
.unwrap()
.unwrap()
.unwrap();
assert!(b.handle.is_closed());
}
#[tokio::test]
async fn datachannel_http_request_round_trip() {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let dir = tempfile::tempdir().unwrap();
let sock = dir.path().join("http.sock");
let listener = UnixListener::bind(&sock).unwrap();
let server = tokio::spawn(async move {
let (mut stream, _) = listener.accept().await.unwrap();
let mut buf = vec![0u8; 8 * 1024 * 1024];
let mut collected = Vec::new();
loop {
let n = stream.read(&mut buf).await.unwrap();
if n == 0 {
break;
}
collected.extend_from_slice(&buf[..n]);
if let Some(split) = collected.windows(4).position(|w| w == b"\r\n\r\n") {
let head = std::str::from_utf8(&collected[..split]).unwrap();
let content_length = head
.lines()
.find_map(|l| {
l.strip_prefix("content-length: ")
.or_else(|| l.strip_prefix("Content-Length: "))
})
.and_then(|v| v.trim().parse::<usize>().ok())
.unwrap_or(0);
if collected.len() >= split + 4 + content_length {
let body = collected[split + 4..split + 4 + content_length].to_vec();
let response = format!(
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
body.len()
);
stream.write_all(response.as_bytes()).await.unwrap();
stream.write_all(&body).await.unwrap();
return;
}
}
}
});
let ingress = Arc::new(IngressSocket { path: Some(sock) });
let mut b = Browser::new("http.request/1", ingress).await;
use base64::Engine;
let body = vec![42; 64 * 1024];
let request = encode_request(&StreamRequest {
method: "PUT".into(),
path: "/api/echo".into(),
headers: Default::default(),
body_b64: base64::engine::general_purpose::STANDARD.encode(&body),
})
.unwrap();
let method = "http.request/1";
let mut frame = (method.len() as u16).to_be_bytes().to_vec();
frame.extend_from_slice(method.as_bytes());
frame.extend(request);
b.send(&frame);
let mut response = vec![];
loop {
let frame = b.receive().await;
let end = frame[0] == 3;
response.extend(frame);
if end {
break;
}
}
let mut decoder = crate::stream_wire::StreamDecoder::new(response.as_slice());
assert!(
matches!(decoder.next_frame().await.unwrap(), Some(crate::stream_wire::StreamFrame::Head(h)) if h.status == 200)
);
let mut received = vec![];
while let Some(frame) = decoder.next_frame().await.unwrap() {
if let crate::stream_wire::StreamFrame::Data(bytes) = frame {
received.extend(bytes);
}
}
assert_eq!(received, body);
b.expect_close().await;
server.abort();
}
#[tokio::test]
async fn datachannel_ws_stream_round_trip() {
use futures_util::{SinkExt, StreamExt};
let dir = tempfile::tempdir().unwrap();
let sock = dir.path().join("ws.sock");
let listener = UnixListener::bind(&sock).unwrap();
let server = tokio::spawn(async move {
let (stream, _) = listener.accept().await.unwrap();
let mut ws = tokio_tungstenite::accept_async(stream).await.unwrap();
while let Some(Ok(message)) = ws.next().await {
ws.send(message).await.unwrap();
}
});
let ingress = Arc::new(IngressSocket { path: Some(sock) });
let mut b = Browser::new("ws.stream/1", ingress).await;
b.method("ws.stream/1");
b.send(
&encode_ws(&WsFrame::Open {
path: "/api/ws".into(),
headers: Default::default(),
})
.unwrap(),
);
let bytes = b.receive().await;
assert!(matches!(
read_ws(&mut bytes.as_slice()).await.unwrap(),
WsFrame::Open { .. }
));
b.send(&encode_ws(&WsFrame::Text("hello".into())).unwrap());
let bytes = b.receive().await;
assert_eq!(
read_ws(&mut bytes.as_slice()).await.unwrap(),
WsFrame::Text("hello".into())
);
server.abort();
}
#[tokio::test]
async fn cancellation_closes_bound_datachannel() {
let mut b = Browser::new("http.request/1", empty_ingress()).await;
b.handle.close();
tokio::time::timeout(Duration::from_secs(2), &mut b.task)
.await
.unwrap()
.unwrap()
.unwrap();
assert!(b.handle.is_closed());
}
#[test]
fn signaling_rejects_unbound_fingerprints_and_restarts() {
let mut rtc = rtc();
let mut binding = Binding {
nonce: None,
candidates: 0,
};
for message in [
json!({"type":"offer","version":1,"offer_nonce":"0123456789abcdef","sdp":"v=0\r\na=fingerprint:sha-256 AA\r\n","dtls_fingerprint":"sha-256 BB"}),
json!({"type":"restart","version":1,"offer_nonce":"0123456789abcdef","previous_offer_nonce":"other0123456789abcdef"}),
] {
assert!(binding.signal(&mut rtc, message).is_err());
}
}
#[tokio::test]
async fn signaling_frame_bound_precedes_allocation() {
let (mut client, mut server) = tokio::io::duplex(4);
use tokio::io::AsyncWriteExt;
client.write_u32((SIGNAL + 1) as u32).await.unwrap();
assert!(read_signal(&mut server)
.await
.unwrap_err()
.contains("bound"));
}
#[tokio::test]
async fn method_prefix_must_match_channel_label() {
let mut b = Browser::new("http.request/1", empty_ingress()).await;
b.method("ws.stream/1");
b.expect_close().await;
assert!(!b.handle.is_closed());
}
#[tokio::test]
async fn ice_restart_keeps_the_existing_datachannel() {
let mut b = Browser::new("http.request/1", empty_ingress()).await;
let mut changes = b.rtc.sdp_api();
changes.ice_restart(true);
let (offer, pending) = changes.apply().unwrap();
let sdp = offer.to_sdp_string();
write_signal(
&mut b.signal,
&json!({"type":"restart", "version":1,
"offer_nonce":"fedcba9876543210", "previous_offer_nonce":"0123456789abcdef",
"dtls_fingerprint":fingerprint(&sdp).unwrap(), "sdp":sdp}),
)
.await
.unwrap();
let answer = tokio::time::timeout(Duration::from_secs(2), async {
loop {
let message = read_signal(&mut b.signal).await.unwrap();
if message["type"] == "answer" {
break message;
}
assert_eq!(message["type"], "candidate");
}
})
.await
.unwrap();
assert_eq!(answer["offer_nonce"], "fedcba9876543210");
b.rtc
.sdp_api()
.accept_answer(
pending,
SdpAnswer::from_sdp_string(answer["sdp"].as_str().unwrap()).unwrap(),
)
.unwrap();
b.method("http.request/1");
b.send(
&encode_request(&StreamRequest {
method: "GET".into(),
path: "/private".into(),
headers: Default::default(),
body_b64: String::new(),
})
.unwrap(),
);
let bytes = b.receive().await;
let mut decoder = crate::stream_wire::StreamDecoder::new(bytes.as_slice());
assert!(
matches!(decoder.next_frame().await.unwrap(), Some(crate::stream_wire::StreamFrame::Head(h)) if h.status == 403)
);
}
#[tokio::test]
async fn advertised_stun_candidate_is_in_the_answer() {
let stun = UdpSocket::bind("127.0.0.1:0").await.unwrap();
let address = stun.local_addr().unwrap();
let responder = tokio::spawn(async move {
let mut request = [0; 20];
let (n, peer) = stun.recv_from(&mut request).await.unwrap();
assert_eq!(n, 20);
assert_eq!(&request[..2], &[0, 1]);
let mut reply = request.to_vec();
reply[..4].copy_from_slice(&[1, 1, 0, 12]);
reply.extend_from_slice(&[0, 0x20, 0, 8, 0, 1]);
reply.extend_from_slice(&(45678u16 ^ 0x2112).to_be_bytes());
reply.extend_from_slice(&(u32::from_be_bytes([203, 0, 113, 5]) ^ 0x2112a442).to_be_bytes());
stun.send_to(&reply, peer).await.unwrap();
});
let _b = Browser::with_stun("http.request/1", empty_ingress(), vec![address]).await;
responder.await.unwrap();
}
#[tokio::test]
async fn signaling_eof_closes_the_remote_datachannel() {
let mut b = Browser::new("http.request/1", empty_ingress()).await;
b.signal.shutdown().await.unwrap();
let _ = tokio::time::timeout(Duration::from_secs(2), &mut b.task)
.await
.unwrap()
.unwrap();
assert!(b.handle.is_closed());
}
fn segment(bytes: &[u8]) -> Vec<Vec<u8>> {
if bytes.is_empty() {
return vec![vec![0]];
}
let count = bytes.len().div_ceil(CHUNK - 1);
bytes
.chunks(CHUNK - 1)
.enumerate()
.map(|(i, data)| {
let mut chunk = Vec::with_capacity(data.len() + 1);
chunk.push(u8::from(i + 1 < count));
chunk.extend_from_slice(data);
chunk
})
.collect()
}
#[tokio::test]
async fn mdns_and_stale_candidates_keep_channel_open() {
let mut b = Browser::new("http.request/1", empty_ingress()).await;
for offer_nonce in ["0123456789abcdef", "fedcba9876543210"] {
write_signal(&mut b.signal, &json!({"type":"candidate", "offer_nonce":offer_nonce,
"candidate":"candidate:1 1 udp 2113937151 0b1c1234-5678-9abc-def0-123456789abc.local 54321 typ host"})).await.unwrap();
}
b.method("http.request/1");
b.send(
&encode_request(&StreamRequest {
method: "GET".into(),
path: "/private".into(),
headers: Default::default(),
body_b64: String::new(),
})
.unwrap(),
);
let bytes = b.receive().await;
let mut decoder = crate::stream_wire::StreamDecoder::new(bytes.as_slice());
assert!(
matches!(decoder.next_frame().await.unwrap(), Some(crate::stream_wire::StreamFrame::Head(h)) if h.status == 403)
);
assert!(!b.handle.is_closed());
}
#[test]
fn unparseable_candidates_count_toward_cap() {
let mut rtc = rtc();
let mut binding = Binding {
nonce: Some("0123456789abcdef".into()),
candidates: 0,
};
for _ in 0..32 {
assert!(binding.signal(&mut rtc, json!({"type":"candidate", "offer_nonce":"0123456789abcdef", "candidate":"candidate:bad"})).is_ok());
}
assert_eq!(binding.candidates, 32);
assert!(binding.signal(&mut rtc, json!({"type":"candidate", "offer_nonce":"0123456789abcdef", "candidate":"candidate:bad"})).is_err());
}
#[tokio::test(start_paused = true)]
async fn idle_method_prefix_releases_channel_slot() {
let mut tasks = JoinSet::new();
let (output, mut outgoing) = mpsc::channel(16);
let mut rtc = rtc();
let id = rtc.sdp_api().add_channel("http.request/1".into());
let _channel = open_channel(
id,
"http.request/1".into(),
empty_ingress(),
empty_wire(),
&mut tasks,
output,
ByteBudget::default(),
);
tokio::task::yield_now().await;
tokio::time::advance(DEVICE_CALL_READ_DEADLINE).await;
assert!(matches!(outgoing.recv().await, Some(Out::Finished(finished)) if finished == id));
tasks.join_next().await.unwrap().unwrap();
}
#[test]
fn channel_input_is_bounded_by_bytes_instead_of_message_count() {
let input = ChannelInput::default();
for _ in 0..FRAME / (CHUNK - 1) {
assert!(input.push(vec![42; CHUNK - 1]));
}
let remaining = FRAME % (CHUNK - 1);
assert!(input.push(vec![42; remaining]));
assert_eq!(input.queue.lock().1, FRAME);
assert!(!input.push(vec![42]));
}
#[tokio::test]
async fn sixteen_prepared_channels_are_admitted() {
let mut b = Browser::new("http.request/1", empty_ingress()).await;
assert_eq!(MAX_SESSION_STREAMS, 16);
for _ in 1..MAX_SESSION_STREAMS {
let id = b
.rtc
.direct_api()
.create_data_channel(str0m::channel::ChannelConfig {
label: "http.request/1".into(),
..Default::default()
});
b.channel = id;
tokio::time::timeout(Duration::from_secs(2), async {
loop {
match b.step().await {
Some(Event::ChannelOpen(opened, _)) if opened == id => break,
Some(Event::ChannelClose(_)) => {
panic!("prepared channel closed below the limit")
}
_ => {}
}
}
})
.await
.unwrap();
}
let extra = b
.rtc
.direct_api()
.create_data_channel(str0m::channel::ChannelConfig {
label: "http.request/1".into(),
..Default::default()
});
tokio::time::timeout(Duration::from_secs(2), async {
loop {
if matches!(b.step().await, Some(Event::ChannelClose(id)) if id == extra) {
break;
}
}
})
.await
.unwrap();
b.method("http.request/1");
b.send(
&encode_request(&StreamRequest {
method: "GET".into(),
path: "/private".into(),
headers: Default::default(),
body_b64: String::new(),
})
.unwrap(),
);
let bytes = b.receive().await;
let mut decoder = crate::stream_wire::StreamDecoder::new(bytes.as_slice());
assert!(
matches!(decoder.next_frame().await.unwrap(), Some(crate::stream_wire::StreamFrame::Head(h)) if h.status == 403)
);
assert!(!b.handle.is_closed());
}
#[tokio::test]
async fn ipv6_only_stun_list_still_answers_with_ipv4_host() {
let mut offerer = rtc();
let mut changes = offerer.sdp_api();
changes.add_channel("http.request/1".into());
let (offer, _) = changes.apply().unwrap();
let sdp = offer.to_sdp_string();
let (mut signal, server) = tokio::io::duplex(65536);
let handle = WebRtcHandle::new();
let server_handle = handle.clone();
let task = tokio::spawn(async move {
let (read, write) = tokio::io::split(server);
serve(
read,
write,
empty_ingress(),
server_handle,
vec!["[::1]:3478".parse().unwrap()],
None,
)
.await
});
write_signal(&mut signal, &json!({"type":"offer", "version":1,
"offer_nonce":"0123456789abcdef", "dtls_fingerprint":fingerprint(&sdp).unwrap(), "sdp":sdp})).await.unwrap();
let answer = tokio::time::timeout(Duration::from_secs(2), read_signal(&mut signal))
.await
.unwrap()
.unwrap();
assert_eq!(answer["type"], "answer");
assert!(answer["sdp"]
.as_str()
.unwrap()
.lines()
.filter_map(|line| line.strip_prefix("a="))
.filter_map(|line| Candidate::from_sdp_string(line).ok())
.any(|candidate| candidate.addr().is_ipv4()));
handle.close();
task.await.unwrap().unwrap();
}
#[tokio::test]
async fn session_budget_is_shared_by_dc_queues_and_http_bodies_and_released() {
let budget = ByteBudget::default();
let inputs: Vec<_> = (0..4)
.map(|_| ChannelInput {
budget: budget.clone(),
..Default::default()
})
.collect();
for input in &inputs {
assert!(input.push(vec![0; FRAME]));
}
assert!(budget.reserve(1).is_none());
let mut refusal = vec![];
tunnel::refuse(&mut refusal, "http.request/1", "too_busy")
.await
.unwrap();
assert_eq!(refusal[0], 1); drop(inputs);
assert!(budget.reserve(SESSION_BYTES).is_some());
}
#[test]
fn logical_frame_accepts_six_mib_and_rejects_one_more_byte() {
assert_eq!(FRAME, 6 * 1024 * 1024);
let input = ChannelInput::default();
assert!(input.push(vec![0; FRAME]));
assert!(!input.push(vec![0]));
}
#[tokio::test]
async fn dc_websocket_remains_open_beyond_one_hour() {
use futures_util::{SinkExt, StreamExt};
let dir = tempfile::tempdir().unwrap();
let sock = dir.path().join("ws.sock");
let listener = UnixListener::bind(&sock).unwrap();
let server = tokio::spawn(async move {
let (stream, _) = listener.accept().await.unwrap();
let mut ws = tokio_tungstenite::accept_async(stream).await.unwrap();
while let Some(Ok(message)) = ws.next().await {
ws.send(message).await.unwrap();
}
});
let ingress = Arc::new(IngressSocket { path: Some(sock) });
let mut rtc = rtc();
let id = rtc.sdp_api().add_channel("ws.stream/1".into());
let mut tasks = JoinSet::new();
let (output, mut outgoing) = mpsc::channel(16);
let channel = open_channel(
id,
"ws.stream/1".into(),
ingress,
empty_wire(),
&mut tasks,
output,
ByteBudget::default(),
);
assert!(channel.input.push(
wire::encode_request(
"ws.stream/1",
&encode_ws(&WsFrame::Open {
path: "/api/ws".into(),
headers: Default::default()
})
.unwrap()
)
.unwrap()
));
assert!(matches!(outgoing.recv().await, Some(Out::Bytes(_, _))));
tokio::time::pause();
tokio::time::advance(Duration::from_secs(3601)).await;
tokio::task::yield_now().await;
assert!(channel
.input
.push(encode_ws(&WsFrame::Text("still live".into())).unwrap()));
tokio::time::resume();
let Some(Out::Bytes(_, bytes)) = tokio::time::timeout(Duration::from_secs(3), outgoing.recv())
.await
.unwrap()
else {
panic!("websocket ended at one hour");
};
assert_eq!(
read_ws(&mut &bytes[1..]).await.unwrap(),
WsFrame::Text("still live".into())
);
tasks.abort_all();
server.abort();
}
#[tokio::test]
async fn late_stun_reply_is_trickled_after_answer() {
let stun = UdpSocket::bind("127.0.0.1:0").await.unwrap();
let address = stun.local_addr().unwrap();
let mut offerer = rtc();
let mut changes = offerer.sdp_api();
changes.add_media(
str0m::media::MediaKind::Audio,
str0m::media::Direction::SendRecv,
None,
None,
None,
);
changes.add_channel("http.request/1".into());
let (offer, _) = changes.apply().unwrap();
let sdp = offer.to_sdp_string();
let (mut signal, server) = tokio::io::duplex(65536);
let handle = WebRtcHandle::new();
let cancel = handle.clone();
let task = tokio::spawn(async move {
let (read, write) = tokio::io::split(server);
serve(
read,
write,
empty_ingress(),
cancel,
vec![address],
Some("127.0.0.1:0".parse().unwrap()),
)
.await
});
write_signal(&mut signal, &json!({"type":"offer", "version":1,
"offer_nonce":"0123456789abcdef", "dtls_fingerprint":fingerprint(&sdp).unwrap(), "sdp":sdp})).await.unwrap();
let mut request = [0; 20];
let (_, peer) = stun.recv_from(&mut request).await.unwrap();
let answer = tokio::time::timeout(Duration::from_secs(2), read_signal(&mut signal))
.await
.unwrap()
.unwrap();
assert_eq!(answer["type"], "answer");
assert!(!answer["sdp"].as_str().unwrap().contains("typ srflx"));
let mut reply = request.to_vec();
reply[..4].copy_from_slice(&[1, 1, 0, 12]);
reply.extend_from_slice(&[0, 0x20, 0, 8, 0, 1]);
reply.extend_from_slice(&(45678u16 ^ 0x2112).to_be_bytes());
reply.extend_from_slice(&(u32::from_be_bytes([203, 0, 113, 5]) ^ 0x2112a442).to_be_bytes());
stun.send_to(&reply, peer).await.unwrap();
let candidate = tokio::time::timeout(Duration::from_secs(2), async {
loop {
let msg = read_signal(&mut signal).await.unwrap();
assert_eq!(msg["type"], "candidate");
if msg["candidate"].as_str().unwrap().contains("typ srflx") {
break msg;
}
}
})
.await
.unwrap();
assert_eq!(candidate["offer_nonce"], "0123456789abcdef");
assert_eq!(candidate["sdp_mline_index"], 1);
stun.send_to(&reply, peer).await.unwrap();
assert!(
tokio::time::timeout(Duration::from_millis(100), read_signal(&mut signal))
.await
.is_err()
);
handle.close();
task.await.unwrap().unwrap();
}
fn answer_with_hosts(addresses: &[SocketAddr]) -> String {
let mut offerer = rtc();
let mut changes = offerer.sdp_api();
changes.add_channel("http.request/1".into());
let (offer, _) = changes.apply().unwrap();
let sdp = offer.to_sdp_string();
let mut answerer = rtc();
LocalCandidates::hosts(&mut answerer, addresses.iter().copied()).unwrap();
let mut binding = Binding {
nonce: None,
candidates: 0,
};
binding.signal(&mut answerer, json!({"type":"offer", "version":1,
"offer_nonce":"0123456789abcdef", "dtls_fingerprint":fingerprint(&sdp).unwrap(), "sdp":sdp}))
.unwrap().unwrap()["sdp"].as_str().unwrap().to_owned()
}
#[test]
fn answer_advertises_one_host_per_available_family() {
let v4 = "192.0.2.1:12000".parse().unwrap();
let v6 = "[fd00::1]:13000".parse().unwrap();
let answer = answer_with_hosts(&[v4, v6]);
assert!(answer.contains("192.0.2.1 12000 typ host"));
assert!(answer.contains("fd00::1 13000 typ host"));
assert_eq!(
answer
.lines()
.filter(|line| line.starts_with("a=candidate:"))
.count(),
2
);
}
#[tokio::test]
async fn ipv6_bind_failure_keeps_ipv4_answer() {
let sockets = session_sockets(Some("127.0.0.1:0".parse().unwrap()), &[], |_| {
Err(std::io::Error::new(
std::io::ErrorKind::AddrNotAvailable,
"injected IPv6 bind failure",
))
})
.unwrap();
assert_eq!(sockets.len(), 1);
let local = sockets[0].local;
let answer = answer_with_hosts(&[local]);
assert!(answer.contains(&format!("127.0.0.1 {} typ host", local.port())));
let peer = UdpSocket::bind("127.0.0.1:0").await.unwrap();
peer.send_to(b"still usable", local).await.unwrap();
let mut buf = [0; 64];
let (index, n, _) = recv_packet(&sockets, &mut buf).await.unwrap();
assert_eq!(index, 0);
assert_eq!(&buf[..n], b"still usable");
}
#[test]
fn ipv6_host_scope_policy() {
for ip in [
"::",
"::1",
"fe80::1",
"febf::1",
"ff02::1",
"::ffff:192.0.2.1",
"fec0::1",
"::2",
] {
assert!(!usable_ipv6(ip.parse().unwrap()), "{ip}");
}
for ip in ["2001:db8::1", "fd00::1", "fc00::1"] {
assert!(usable_ipv6(ip.parse().unwrap()), "{ip}");
}
}
#[test]
fn ipv6_stun_mapping_checks_transaction_and_candidate_bounds() {
let txid = [42; 12];
let mut reply = stun_binding_request(&txid).to_vec();
reply[..4].copy_from_slice(&[1, 1, 0, 24]);
reply.extend_from_slice(&[0, 0x20, 0, 20, 0, 2]);
reply.extend_from_slice(&(45678u16 ^ 0x2112).to_be_bytes());
let ip: Ipv6Addr = "2001:db8::1234".parse().unwrap();
let encoded: Vec<_> = ip
.octets()
.iter()
.zip(reply[4..20].iter())
.map(|(a, b)| a ^ b)
.collect();
reply.extend_from_slice(&encoded);
let mapped = SocketAddr::new(ip.into(), 45678);
assert_eq!(stun_mapped(&reply, &txid), Some(mapped));
assert_eq!(stun_mapped(&reply, &[0; 12]), None);
for n in 0..reply.len() {
assert_eq!(stun_mapped(&reply[..n], &txid), None);
}
let mut rtc = rtc();
let local = "[fd00::1]:10000".parse().unwrap();
let mut candidates = LocalCandidates::hosts(&mut rtc, [local].into_iter()).unwrap();
assert!(candidates
.mapped(&mut rtc, mapped, local)
.unwrap()
.is_some());
assert!(candidates
.mapped(&mut rtc, mapped, local)
.unwrap()
.is_none());
for port in 1..8 {
assert!(candidates
.mapped(&mut rtc, SocketAddr::new(ip.into(), port), local)
.unwrap()
.is_some());
}
assert!(candidates
.mapped(&mut rtc, SocketAddr::new(ip.into(), 8), local)
.unwrap()
.is_none());
assert!(candidates
.mapped(
&mut rtc,
"203.0.113.1:45678".parse().unwrap(),
"192.0.2.1:10000".parse().unwrap()
)
.unwrap()
.is_some());
}