use bytes::BytesMut;
use shared::error::*;
use std::collections::{HashMap, VecDeque};
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::{Duration, Instant};
use crate::agent::*;
use crate::attributes::*;
use crate::error_code::ErrorCodeAttribute;
use crate::message::*;
use crate::timer::{
DEFAULT_MAX_OUTSTANDING, DEFAULT_RC, DEFAULT_RM, DEFAULT_RTO, DEFAULT_TI, RtoEstimator,
Schedule,
};
use crate::validated::{Rejection, Validator};
use crypto::{RTCCryptoProvider, SecretVec};
use shared::{TaggedBytesMut, TransportContext, TransportMessage, TransportProtocol};
const DEFAULT_TIMEOUT_RATE: Duration = Duration::from_millis(5);
const DEFAULT_MAX_BUFFER_SIZE: usize = 8;
const UNKNOWN_PATH_MTU_V4: usize = 576;
const UNKNOWN_PATH_MTU_V6: usize = 1280;
const IP_UDP_OVERHEAD_V4: usize = 28;
const IP_UDP_OVERHEAD_V6: usize = 48;
pub struct TaggedMessage {
pub now: Instant,
pub message: Message,
}
#[derive(Debug, Clone)]
pub struct ClientTransaction {
id: TransactionId,
method: Method,
sent: u32,
start: Instant,
rto: Duration,
deadline: Instant,
discarded: bool,
raw: Vec<u8>,
}
struct ClientSettings {
buffer_size: usize,
rto: Duration,
rto_rate: Duration,
rc: u32,
rm: u32,
ti: Duration,
estimate_rto: bool,
max_outstanding: usize,
path_mtu: Option<usize>,
known_attributes: Vec<AttrType>,
integrity: Option<(SecretVec, Arc<dyn RTCCryptoProvider>)>,
closed: bool,
}
impl Default for ClientSettings {
fn default() -> Self {
ClientSettings {
buffer_size: DEFAULT_MAX_BUFFER_SIZE,
rto: DEFAULT_RTO,
rto_rate: DEFAULT_TIMEOUT_RATE,
rc: DEFAULT_RC,
rm: DEFAULT_RM,
ti: DEFAULT_TI,
estimate_rto: true,
max_outstanding: DEFAULT_MAX_OUTSTANDING,
path_mtu: None,
known_attributes: default_known_attributes(),
integrity: None,
closed: false,
}
}
}
fn default_known_attributes() -> Vec<AttrType> {
let mut known = STUN_ATTRIBUTES.to_vec();
known.extend_from_slice(&[ATTR_SOURCE_ADDRESS, ATTR_CHANGED_ADDRESS, AttrType(0x000b)]);
known
}
#[derive(Default)]
pub struct ClientBuilder {
settings: ClientSettings,
}
impl ClientBuilder {
pub fn with_rto(mut self, rto: Duration) -> Self {
self.settings.rto = rto;
self
}
pub fn with_rc(mut self, rc: u32) -> Self {
self.settings.rc = rc.max(1);
self
}
pub fn with_rm(mut self, rm: u32) -> Self {
self.settings.rm = rm;
self
}
pub fn with_ti(mut self, ti: Duration) -> Self {
self.settings.ti = ti;
self
}
pub fn with_rto_estimation(mut self, on: bool) -> Self {
self.settings.estimate_rto = on;
self
}
pub fn with_max_outstanding_transactions(mut self, max: usize) -> Self {
self.settings.max_outstanding = max;
self
}
pub fn with_path_mtu(mut self, mtu: usize) -> Self {
self.settings.path_mtu = Some(mtu);
self
}
pub fn with_known_attributes(mut self, known: &[AttrType]) -> Self {
self.settings.known_attributes = known.to_vec();
self
}
pub fn with_response_integrity(
mut self,
key: impl Into<Vec<u8>>,
provider: Arc<dyn RTCCryptoProvider>,
) -> Self {
self.settings.integrity = Some((SecretVec::new(key.into()), provider));
self
}
#[deprecated(
note = "has no effect: a sans-I/O client has no timer of its own, the caller's \
`handle_timeout` calls set the resolution"
)]
pub fn with_timeout_rate(mut self, d: Duration) -> Self {
self.settings.rto_rate = d;
self
}
#[deprecated(note = "has no effect: the client buffers nothing of a fixed size")]
pub fn with_buffer_size(mut self, buffer_size: usize) -> Self {
self.settings.buffer_size = buffer_size;
self
}
pub fn with_no_retransmit(mut self) -> Self {
self.settings.rc = 1;
self
}
pub fn new() -> Self {
ClientBuilder {
settings: ClientSettings::default(),
}
}
pub fn build(
self,
now: Instant,
local: SocketAddr,
remote: SocketAddr,
protocol: TransportProtocol,
) -> Result<Client> {
Ok(Client::new(now, local, remote, protocol, self.settings))
}
}
pub struct Client {
local: SocketAddr,
remote: SocketAddr,
transport_protocol: TransportProtocol,
settings: ClientSettings,
rto: RtoEstimator,
transactions: HashMap<TransactionId, ClientTransaction>,
transmits: VecDeque<TransportMessage<BytesMut>>,
events: VecDeque<StunEvent>,
now: Instant,
}
impl Client {
fn new(
now: Instant,
local: SocketAddr,
remote: SocketAddr,
transport_protocol: TransportProtocol,
settings: ClientSettings,
) -> Self {
Self {
local,
remote,
transport_protocol,
rto: RtoEstimator::new(settings.rto, settings.estimate_rto),
settings,
transactions: HashMap::new(),
transmits: VecDeque::new(),
events: VecDeque::new(),
now,
}
}
fn observe(&mut self, now: Instant) {
self.now = now.max(self.now);
}
pub fn local_addr(&self) -> SocketAddr {
self.local
}
pub fn peer_addr(&self) -> SocketAddr {
self.remote
}
pub fn rto(&self) -> Duration {
self.rto.rto()
}
pub fn outstanding_transactions(&self) -> usize {
self.transactions.len()
}
pub fn max_message_size(&self) -> usize {
if self.is_reliable() {
return usize::MAX;
}
let (unknown, overhead) = if self.remote.is_ipv4() {
(UNKNOWN_PATH_MTU_V4, IP_UDP_OVERHEAD_V4)
} else {
(UNKNOWN_PATH_MTU_V6, IP_UDP_OVERHEAD_V6)
};
self.settings
.path_mtu
.unwrap_or(unknown)
.saturating_sub(overhead)
}
fn is_reliable(&self) -> bool {
self.transport_protocol == TransportProtocol::TCP
}
fn transmit(&mut self, now: Instant, raw: &[u8]) {
self.transmits.push_back(TransportMessage {
now,
transport: TransportContext {
local_addr: self.local,
peer_addr: self.remote,
ecn: None,
transport_protocol: self.transport_protocol,
},
message: BytesMut::from(raw),
});
}
fn next_deadline(&self, ct: &ClientTransaction, now: Instant) -> Instant {
Schedule {
rc: self.settings.rc,
rm: self.settings.rm,
ti: self.settings.ti,
}
.next_deadline(self.is_reliable(), ct.start, ct.rto, ct.sent, now)
}
fn finish(&mut self, id: TransactionId, event: StunEvent) {
self.transactions.remove(&id);
self.events.push_back(event);
}
fn due(&self, now: Instant) -> Vec<TransactionId> {
let mut due: Vec<(Instant, TransactionId)> = self
.transactions
.values()
.filter(|ct| ct.deadline <= now)
.map(|ct| (ct.deadline, ct.id))
.collect();
due.sort_by_key(|(deadline, id)| (*deadline, id.0));
due.into_iter().map(|(_, id)| id).collect()
}
}
impl sansio::Protocol<TaggedBytesMut, TaggedMessage, ()> for Client {
type Rout = ();
type Wout = TaggedBytesMut;
type Eout = StunEvent;
type Error = Error;
type Time = Instant;
fn handle_read(&mut self, msg: TaggedBytesMut) -> Result<()> {
self.observe(msg.now);
if msg.transport.peer_addr != self.remote {
return Ok(());
}
let mut stun_msg = Message::new();
stun_msg.unmarshal_binary(&msg.message)?;
let class = stun_msg.typ.class;
if class != CLASS_SUCCESS_RESPONSE && class != CLASS_ERROR_RESPONSE {
return Ok(());
}
let id = stun_msg.transaction_id;
let Some(ct) = self.transactions.get(&id) else {
return Ok(());
};
if ct.method != stun_msg.typ.method {
return Ok(());
}
let (sent, start) = (ct.sent, ct.start);
let validator = Validator::new().known_attributes(&self.settings.known_attributes);
let checked = match &self.settings.integrity {
Some((key, provider)) => {
validator.authenticate(&stun_msg, key.as_ref(), provider.crypto())
}
None => validator.unauthenticated(&stun_msg),
};
let valid = match checked {
Ok(valid) => valid,
Err(Rejection::FingerprintMissing | Rejection::FingerprintMismatch) => return Ok(()),
Err(Rejection::IntegrityMissing | Rejection::IntegrityMismatch) => {
if self.is_reliable() {
self.finish(
id,
StunEvent::TransactionFailed {
id,
reason: TransactionFailure::IntegrityViolation,
},
);
} else if let Some(ct) = self.transactions.get_mut(&id) {
ct.discarded = true;
}
return Ok(());
}
Err(Rejection::UnknownAttributes(unknown)) => {
self.finish(
id,
StunEvent::TransactionFailed {
id,
reason: TransactionFailure::UnknownAttributes(unknown),
},
);
return Ok(());
}
Err(Rejection::Crypto(error)) => return Err(Error::Crypto(error)),
};
if sent == 1 {
self.rto
.sample(msg.now.saturating_duration_since(start), msg.now);
}
if class == CLASS_ERROR_RESPONSE && ErrorCodeAttribute::default().get_from(&valid).is_err()
{
self.finish(
id,
StunEvent::TransactionFailed {
id,
reason: TransactionFailure::MissingErrorCode,
},
);
return Ok(());
}
let message = if self.settings.integrity.is_some() {
valid.into_message()
} else {
stun_msg
};
self.finish(id, StunEvent::Message(message));
Ok(())
}
fn poll_read(&mut self) -> Option<Self::Rout> {
None
}
fn handle_write(&mut self, msg: TaggedMessage) -> Result<()> {
if self.settings.closed {
return Err(Error::ErrClientClosed);
}
let now = msg.now;
self.observe(now);
let m = msg.message;
if m.raw.len() > self.max_message_size() {
return Err(Error::ErrPacketTooBig);
}
if m.typ.class != CLASS_REQUEST {
self.transmit(now, &m.raw);
return Ok(());
}
if self.transactions.contains_key(&m.transaction_id) {
return Err(Error::ErrTransactionExists);
}
if self.settings.max_outstanding != 0
&& self.transactions.len() >= self.settings.max_outstanding
{
return Err(Error::Other(format!(
"{} transactions are outstanding to {}, the limit of RFC 8489 section 6.2",
self.transactions.len(),
self.remote
)));
}
let mut ct = ClientTransaction {
id: m.transaction_id,
method: m.typ.method,
sent: 1,
start: now,
rto: self.rto.start(now),
deadline: now,
discarded: false,
raw: m.raw,
};
ct.deadline = self.next_deadline(&ct, now);
self.transmit(now, &ct.raw);
self.transactions.insert(ct.id, ct);
Ok(())
}
fn poll_write(&mut self) -> Option<Self::Wout> {
self.transmits.pop_front()
}
fn poll_event(&mut self) -> Option<Self::Eout> {
self.events.pop_front()
}
fn poll_timeout(&mut self) -> Option<Self::Time> {
self.transactions.values().map(|ct| ct.deadline).min()
}
fn handle_timeout(&mut self, now: Instant) -> Result<()> {
if self.settings.closed {
return Err(Error::ErrClientClosed);
}
self.observe(now);
for id in self.due(now) {
let Some(mut ct) = self.transactions.remove(&id) else {
continue;
};
if self.is_reliable() || ct.sent >= self.settings.rc {
self.events.push_back(if ct.discarded {
StunEvent::TransactionFailed {
id,
reason: TransactionFailure::IntegrityViolation,
}
} else {
StunEvent::TransactionTimeOut
});
continue;
}
ct.sent += 1;
ct.deadline = self.next_deadline(&ct, now);
self.transmit(now, &ct.raw);
self.transactions.insert(id, ct);
}
Ok(())
}
fn close(&mut self) -> Result<()> {
if self.settings.closed {
return Err(Error::ErrClientClosed);
}
self.settings.closed = true;
let mut ids: Vec<TransactionId> = self.transactions.keys().copied().collect();
ids.sort_by_key(|id| id.0);
for _ in ids {
self.events.push_back(StunEvent::AgentClosed);
}
self.transactions.clear();
Ok(())
}
}
#[cfg(test)]
mod client_conformance_test;
#[cfg(test)]
mod client_test {
use super::*;
use sansio::Protocol;
fn addrs() -> (SocketAddr, SocketAddr) {
(
"127.0.0.1:5000".parse().unwrap(),
"127.0.0.1:3478".parse().unwrap(),
)
}
fn binding_request() -> Message {
let mut msg = Message::new();
msg.build(&[Box::<TransactionId>::default(), Box::new(BINDING_REQUEST)])
.expect("a binding request encodes");
msg
}
#[test]
fn test_transaction_retransmits_on_injected_time() -> Result<()> {
let base = Instant::now();
let t = |millis| base + Duration::from_millis(millis);
let (local, remote) = addrs();
let mut client = ClientBuilder::new()
.with_rto(Duration::from_millis(100))
.build(t(0), local, remote, TransportProtocol::UDP)?;
client.handle_write(TaggedMessage {
now: t(10),
message: binding_request(),
})?;
let transmit = client.poll_write().expect("the request is queued");
assert_eq!(
transmit.now,
t(10),
"the request carries the caller's instant, not an ambient reading"
);
assert!(client.poll_write().is_none());
assert_eq!(
client.poll_timeout(),
Some(t(110)),
"the deadline is one RTO after the instant the caller wrote at"
);
client.handle_timeout(t(109))?;
while client.poll_event().is_some() {}
assert!(
client.poll_write().is_none(),
"the deadline is not yet reached one millisecond before it"
);
client.handle_timeout(t(110))?;
while client.poll_event().is_some() {}
let retransmit = client.poll_write().expect("the request is retransmitted");
assert_eq!(retransmit.now, t(110));
assert_eq!(
retransmit.message, transmit.message,
"a retransmission repeats the original request verbatim"
);
assert_eq!(client.poll_timeout(), Some(t(310)));
client.close()
}
}