rtci_stun/client.rs
1//! A Sans-I/O STUN client.
2//!
3//! Sends requests to one server and matches the responses, with the retransmission timer of
4//! RFC 8489 section 6.2: over UDP a request is sent again at RTO, 2 RTO, 4 RTO and so on, Rc
5//! times in all, and the transaction fails Rm x RTO after the last one; over TCP it is sent
6//! once and fails after Ti. The RTO starts at a configurable value (500 ms) and then follows
7//! the round-trip times the server shows (RFC 6298). Build one with
8//! [`ClientBuilder`](crate::client::ClientBuilder); drive it with datagrams and time.
9//!
10//! What counts as the response is checked as section 6.3 says: it comes from the server, is a
11//! success or error response of the request's method, has a valid FINGERPRINT if it has one,
12//! and carries no comprehension-required attribute the client does not know.
13use bytes::BytesMut;
14use shared::error::*;
15use std::collections::{HashMap, VecDeque};
16use std::net::SocketAddr;
17use std::sync::Arc;
18use std::time::{Duration, Instant};
19
20use crate::agent::*;
21use crate::attributes::*;
22use crate::error_code::ErrorCodeAttribute;
23use crate::message::*;
24use crate::timer::{
25 DEFAULT_MAX_OUTSTANDING, DEFAULT_RC, DEFAULT_RM, DEFAULT_RTO, DEFAULT_TI, RtoEstimator,
26 Schedule,
27};
28use crate::validated::{Rejection, Validator};
29use crypto::{RTCCryptoProvider, SecretVec};
30use shared::{TaggedBytesMut, TransportContext, TransportMessage, TransportProtocol};
31
32const DEFAULT_TIMEOUT_RATE: Duration = Duration::from_millis(5);
33const DEFAULT_MAX_BUFFER_SIZE: usize = 8;
34/// RFC 8489 section 6.1: with an unknown path MTU, the IP packet of a STUN message over UDP is
35/// at most 576 bytes for IPv4 and 1280 bytes for IPv6.
36const UNKNOWN_PATH_MTU_V4: usize = 576;
37const UNKNOWN_PATH_MTU_V6: usize = 1280;
38/// IP and UDP headers: 20 + 8 bytes for IPv4, 40 + 8 for IPv6.
39const IP_UDP_OVERHEAD_V4: usize = 28;
40const IP_UDP_OVERHEAD_V6: usize = 48;
41
42/// A [`Message`] together with the instant the caller is sending it at.
43///
44/// `Rin` is a [`TaggedBytesMut`], which carries a timestamp; without this the write channel
45/// would not, and `handle_write` would have to ask the clock for one. A STUN client's first
46/// action is typically a write before any read, so a retained instant is not an option here —
47/// it would still be the construction seed.
48pub struct TaggedMessage {
49 /// When the caller is sending this message.
50 pub now: Instant,
51 /// The STUN message to send.
52 pub message: Message,
53}
54
55/// ClientTransaction represents transaction in progress.
56/// If transaction is succeed or failed, f will be called
57/// provided by event.
58/// Concurrent access is invalid.
59#[derive(Debug, Clone)]
60pub struct ClientTransaction {
61 id: TransactionId,
62 method: Method,
63 /// How many times the request has been sent.
64 sent: u32,
65 start: Instant,
66 /// The RTO this transaction started with; each retransmission waits twice as long as the
67 /// one before it.
68 rto: Duration,
69 /// When the request is sent again or, after the last one, the transaction fails.
70 deadline: Instant,
71 /// A response was discarded because its integrity did not hold.
72 discarded: bool,
73 raw: Vec<u8>,
74}
75
76struct ClientSettings {
77 buffer_size: usize,
78 rto: Duration,
79 rto_rate: Duration,
80 rc: u32,
81 rm: u32,
82 ti: Duration,
83 estimate_rto: bool,
84 max_outstanding: usize,
85 path_mtu: Option<usize>,
86 known_attributes: Vec<AttrType>,
87 integrity: Option<(SecretVec, Arc<dyn RTCCryptoProvider>)>,
88 closed: bool,
89}
90
91impl Default for ClientSettings {
92 fn default() -> Self {
93 ClientSettings {
94 buffer_size: DEFAULT_MAX_BUFFER_SIZE,
95 rto: DEFAULT_RTO,
96 rto_rate: DEFAULT_TIMEOUT_RATE,
97 rc: DEFAULT_RC,
98 rm: DEFAULT_RM,
99 ti: DEFAULT_TI,
100 estimate_rto: true,
101 max_outstanding: DEFAULT_MAX_OUTSTANDING,
102 path_mtu: None,
103 known_attributes: default_known_attributes(),
104 integrity: None,
105 closed: false,
106 }
107 }
108}
109
110/// The comprehension-required attributes a Binding client understands: those of RFC 8489,
111/// and the three of RFC 3489 that servers of that generation still put in a Binding response
112/// (SOURCE-ADDRESS, CHANGED-ADDRESS, REFLECTED-FROM), which are read past.
113fn default_known_attributes() -> Vec<AttrType> {
114 let mut known = STUN_ATTRIBUTES.to_vec();
115 known.extend_from_slice(&[ATTR_SOURCE_ADDRESS, ATTR_CHANGED_ADDRESS, AttrType(0x000b)]);
116 known
117}
118
119#[derive(Default)]
120/// Builds a [`Client`] with a chosen transaction timeout, retransmission schedule and
121/// handler.
122pub struct ClientBuilder {
123 settings: ClientSettings,
124}
125
126impl ClientBuilder {
127 /// Sets the initial RTO (RFC 8489 section 6.2.1; 500 ms by default, and the RFC asks for
128 /// no less unless something else bounds the rate, as ICE's pacing does).
129 ///
130 /// It is the RTO of the first transaction and the floor of every later one: the RTO then
131 /// follows the server's round-trip time upwards (see
132 /// [`with_rto_estimation`](Self::with_rto_estimation)).
133 pub fn with_rto(mut self, rto: Duration) -> Self {
134 self.settings.rto = rto;
135 self
136 }
137
138 /// Sets Rc, how many times a request is sent before the transaction fails (RFC 8489
139 /// section 6.2.1; 7 by default). Values below 1 are 1.
140 pub fn with_rc(mut self, rc: u32) -> Self {
141 self.settings.rc = rc.max(1);
142 self
143 }
144
145 /// Sets Rm: the transaction fails Rm x RTO after the last request (RFC 8489 section
146 /// 6.2.1; 16 by default).
147 pub fn with_rm(mut self, rm: u32) -> Self {
148 self.settings.rm = rm;
149 self
150 }
151
152 /// Sets Ti, how long a request waits for its response over a reliable transport, where it
153 /// is never retransmitted (RFC 8489 section 6.2.2; 39.5 s by default).
154 pub fn with_ti(mut self, ti: Duration) -> Self {
155 self.settings.ti = ti;
156 self
157 }
158
159 /// Turns the RFC 6298 computation of the RTO on or off (on by default).
160 ///
161 /// On: a request answered without a retransmission gives a round-trip sample, and the RTO
162 /// of the next transaction is `SRTT + 4 x RTTVAR`, to 1 ms, never below the initial RTO.
163 /// It is kept for the server and dropped after ten minutes without a transaction.
164 /// Off: every transaction starts at the initial RTO.
165 pub fn with_rto_estimation(mut self, on: bool) -> Self {
166 self.settings.estimate_rto = on;
167 self
168 }
169
170 /// Sets how many transactions may be outstanding at once (RFC 8489 section 6.2; 10 by
171 /// default). A request past the limit is refused by `handle_write`. `0` lifts the limit,
172 /// for a caller that limits its rate some other way.
173 pub fn with_max_outstanding_transactions(mut self, max: usize) -> Self {
174 self.settings.max_outstanding = max;
175 self
176 }
177
178 /// Sets the path MTU to the server, when the caller knows it: a message over UDP then has
179 /// to fit an IP packet of that size (RFC 8489 section 6.1).
180 ///
181 /// Without it the RFC's sizes for an unknown path MTU apply: an IP packet of 576 bytes
182 /// for IPv4 and 1280 bytes for IPv6, which is a STUN message of 548 or 1232 bytes.
183 /// `handle_write` refuses a larger one, so that it is never fragmented on the way. A
184 /// message that probes the path MTU is the one case where the RFC lets the rule go: set
185 /// `usize::MAX` for the client that sends it.
186 pub fn with_path_mtu(mut self, mtu: usize) -> Self {
187 self.settings.path_mtu = Some(mtu);
188 self
189 }
190
191 /// Sets the comprehension-required attributes the usage understands in a response:
192 /// [`STUN_ATTRIBUTES`] plus its own. A response that carries any other fails its
193 /// transaction with [`TransactionFailure::UnknownAttributes`] (RFC 8489 sections 6.3.3 and
194 /// 6.3.4).
195 ///
196 /// The default is `STUN_ATTRIBUTES` and RFC 3489's SOURCE-ADDRESS, CHANGED-ADDRESS and
197 /// REFLECTED-FROM, which old servers still send in a Binding response.
198 pub fn with_known_attributes(mut self, known: &[AttrType]) -> Self {
199 self.settings.known_attributes = known.to_vec();
200 self
201 }
202
203 /// Requires every response to be authenticated with `key` (the short-term credential
204 /// mechanism, RFC 8489 section 9.1.4).
205 ///
206 /// A response whose integrity attribute is absent or wrong is discarded as if it had
207 /// never arrived, so retransmissions continue; if the transaction then ends without an
208 /// authentic response, it ends with [`TransactionFailure::IntegrityViolation`] rather than
209 /// a timeout. Over a reliable transport such a response ends the transaction at once.
210 /// The message of [`StunEvent::Message`] then holds the authenticated attributes only.
211 ///
212 /// The long-term mechanism has responses that are valid unsigned (401, 438): its caller
213 /// leaves this off and uses
214 /// [`LongTermCredentials::check_response`](crate::long_term::LongTermCredentials::check_response).
215 pub fn with_response_integrity(
216 mut self,
217 key: impl Into<Vec<u8>>,
218 provider: Arc<dyn RTCCryptoProvider>,
219 ) -> Self {
220 self.settings.integrity = Some((SecretVec::new(key.into()), provider));
221 self
222 }
223
224 /// with_timeout_rate sets RTO timer minimum resolution.
225 #[deprecated(
226 note = "has no effect: a sans-I/O client has no timer of its own, the caller's \
227 `handle_timeout` calls set the resolution"
228 )]
229 pub fn with_timeout_rate(mut self, d: Duration) -> Self {
230 self.settings.rto_rate = d;
231 self
232 }
233
234 /// with_buffer_size sets buffer size.
235 #[deprecated(note = "has no effect: the client buffers nothing of a fixed size")]
236 pub fn with_buffer_size(mut self, buffer_size: usize) -> Self {
237 self.settings.buffer_size = buffer_size;
238 self
239 }
240
241 /// Disables retransmissions: each request is sent once (Rc = 1) and its transaction fails
242 /// Rm x RTO later.
243 ///
244 /// A client built for [`TransportProtocol::TCP`] never retransmits and waits Ti, with or
245 /// without this (RFC 8489 section 6.2.2).
246 pub fn with_no_retransmit(mut self) -> Self {
247 self.settings.rc = 1;
248 self
249 }
250
251 /// A builder with the RFC's default timings.
252 pub fn new() -> Self {
253 ClientBuilder {
254 settings: ClientSettings::default(),
255 }
256 }
257
258 /// Builds the client for the given local and remote addresses.
259 ///
260 /// # Errors
261 ///
262 /// Fails if the configured timings are inconsistent.
263 pub fn build(
264 self,
265 now: Instant,
266 local: SocketAddr,
267 remote: SocketAddr,
268 protocol: TransportProtocol,
269 ) -> Result<Client> {
270 Ok(Client::new(now, local, remote, protocol, self.settings))
271 }
272}
273
274/// Client simulates "connection" to STUN server.
275pub struct Client {
276 local: SocketAddr,
277 remote: SocketAddr,
278 transport_protocol: TransportProtocol,
279 settings: ClientSettings,
280 rto: RtoEstimator,
281 transactions: HashMap<TransactionId, ClientTransaction>,
282 transmits: VecDeque<TransportMessage<BytesMut>>,
283 events: VecDeque<StunEvent>,
284
285 /// The newest instant a caller has supplied, seeded at construction.
286 now: Instant,
287}
288
289impl Client {
290 fn new(
291 now: Instant,
292 local: SocketAddr,
293 remote: SocketAddr,
294 transport_protocol: TransportProtocol,
295 settings: ClientSettings,
296 ) -> Self {
297 Self {
298 local,
299 remote,
300 transport_protocol,
301 rto: RtoEstimator::new(settings.rto, settings.estimate_rto),
302 settings,
303 transactions: HashMap::new(),
304 transmits: VecDeque::new(),
305 events: VecDeque::new(),
306 now,
307 }
308 }
309
310 /// Records the newest instant a caller has supplied.
311 ///
312 /// `max` rather than assignment: an outbound message carries the instant of the input that
313 /// caused it, so a caller can legitimately present an older one than the newest seen.
314 fn observe(&mut self, now: Instant) {
315 self.now = now.max(self.now);
316 }
317
318 /// The address this client sends from.
319 pub fn local_addr(&self) -> SocketAddr {
320 self.local
321 }
322
323 /// The STUN server this client talks to.
324 pub fn peer_addr(&self) -> SocketAddr {
325 self.remote
326 }
327
328 /// The RTO the next transaction starts with: the initial RTO, or what the server's
329 /// round-trip times have made of it.
330 pub fn rto(&self) -> Duration {
331 self.rto.rto()
332 }
333
334 /// How many transactions are waiting for their response.
335 pub fn outstanding_transactions(&self) -> usize {
336 self.transactions.len()
337 }
338
339 /// The largest STUN message this client sends: unbounded over a reliable transport, and
340 /// over UDP what fits the path MTU, known or assumed (RFC 8489 section 6.1).
341 pub fn max_message_size(&self) -> usize {
342 if self.is_reliable() {
343 return usize::MAX;
344 }
345 let (unknown, overhead) = if self.remote.is_ipv4() {
346 (UNKNOWN_PATH_MTU_V4, IP_UDP_OVERHEAD_V4)
347 } else {
348 (UNKNOWN_PATH_MTU_V6, IP_UDP_OVERHEAD_V6)
349 };
350 self.settings
351 .path_mtu
352 .unwrap_or(unknown)
353 .saturating_sub(overhead)
354 }
355
356 /// RFC 8489 section 6.2.2: a reliable transport retransmits for the client.
357 fn is_reliable(&self) -> bool {
358 self.transport_protocol == TransportProtocol::TCP
359 }
360
361 fn transmit(&mut self, now: Instant, raw: &[u8]) {
362 self.transmits.push_back(TransportMessage {
363 now,
364 transport: TransportContext {
365 local_addr: self.local,
366 peer_addr: self.remote,
367 ecn: None,
368 transport_protocol: self.transport_protocol,
369 },
370 message: BytesMut::from(raw),
371 });
372 }
373
374 /// When the request of `ct`, just sent at `now` for the `ct.sent`-th time, is due again
375 /// (RFC 8489 sections 6.2.1 and 6.2.2).
376 fn next_deadline(&self, ct: &ClientTransaction, now: Instant) -> Instant {
377 Schedule {
378 rc: self.settings.rc,
379 rm: self.settings.rm,
380 ti: self.settings.ti,
381 }
382 .next_deadline(self.is_reliable(), ct.start, ct.rto, ct.sent, now)
383 }
384
385 /// Ends a transaction with `event`.
386 fn finish(&mut self, id: TransactionId, event: StunEvent) {
387 self.transactions.remove(&id);
388 self.events.push_back(event);
389 }
390
391 /// The transactions whose deadline has come, in the order of their deadlines.
392 fn due(&self, now: Instant) -> Vec<TransactionId> {
393 let mut due: Vec<(Instant, TransactionId)> = self
394 .transactions
395 .values()
396 .filter(|ct| ct.deadline <= now)
397 .map(|ct| (ct.deadline, ct.id))
398 .collect();
399 due.sort_by_key(|(deadline, id)| (*deadline, id.0));
400 due.into_iter().map(|(_, id)| id).collect()
401 }
402}
403
404impl sansio::Protocol<TaggedBytesMut, TaggedMessage, ()> for Client {
405 type Rout = ();
406 type Wout = TaggedBytesMut;
407 type Eout = StunEvent;
408 type Error = Error;
409 type Time = Instant;
410
411 /// Takes a datagram (or one framed message of a stream) from the network.
412 ///
413 /// What is not the response to an outstanding request is dropped without an event (RFC
414 /// 8489 section 6.3): a message from another address than the server's, a request or an
415 /// indication, a response with an unknown transaction id or of another method, and a
416 /// message whose FINGERPRINT does not match.
417 ///
418 /// # Errors
419 ///
420 /// Fails when the server's datagram is not a STUN message.
421 fn handle_read(&mut self, msg: TaggedBytesMut) -> Result<()> {
422 self.observe(msg.now);
423 if msg.transport.peer_addr != self.remote {
424 return Ok(());
425 }
426 let mut stun_msg = Message::new();
427 stun_msg.unmarshal_binary(&msg.message)?;
428
429 let class = stun_msg.typ.class;
430 if class != CLASS_SUCCESS_RESPONSE && class != CLASS_ERROR_RESPONSE {
431 return Ok(());
432 }
433 let id = stun_msg.transaction_id;
434 let Some(ct) = self.transactions.get(&id) else {
435 return Ok(());
436 };
437 if ct.method != stun_msg.typ.method {
438 return Ok(());
439 }
440 let (sent, start) = (ct.sent, ct.start);
441
442 let validator = Validator::new().known_attributes(&self.settings.known_attributes);
443 let checked = match &self.settings.integrity {
444 Some((key, provider)) => {
445 validator.authenticate(&stun_msg, key.as_ref(), provider.crypto())
446 }
447 None => validator.unauthenticated(&stun_msg),
448 };
449 let valid = match checked {
450 Ok(valid) => valid,
451 Err(Rejection::FingerprintMissing | Rejection::FingerprintMismatch) => return Ok(()),
452 Err(Rejection::IntegrityMissing | Rejection::IntegrityMismatch) => {
453 if self.is_reliable() {
454 // RFC 8489 section 9.1.4: over a reliable transport the transaction ends
455 // at once.
456 self.finish(
457 id,
458 StunEvent::TransactionFailed {
459 id,
460 reason: TransactionFailure::IntegrityViolation,
461 },
462 );
463 } else if let Some(ct) = self.transactions.get_mut(&id) {
464 // Discarded as if it had never arrived; retransmissions continue.
465 ct.discarded = true;
466 }
467 return Ok(());
468 }
469 Err(Rejection::UnknownAttributes(unknown)) => {
470 self.finish(
471 id,
472 StunEvent::TransactionFailed {
473 id,
474 reason: TransactionFailure::UnknownAttributes(unknown),
475 },
476 );
477 return Ok(());
478 }
479 Err(Rejection::Crypto(error)) => return Err(Error::Crypto(error)),
480 };
481
482 // Karn's algorithm: only a request that was sent once gives a round-trip time.
483 if sent == 1 {
484 self.rto
485 .sample(msg.now.saturating_duration_since(start), msg.now);
486 }
487
488 // RFC 8489 section 6.3.4: an error response without ERROR-CODE fails the transaction.
489 if class == CLASS_ERROR_RESPONSE && ErrorCodeAttribute::default().get_from(&valid).is_err()
490 {
491 self.finish(
492 id,
493 StunEvent::TransactionFailed {
494 id,
495 reason: TransactionFailure::MissingErrorCode,
496 },
497 );
498 return Ok(());
499 }
500
501 let message = if self.settings.integrity.is_some() {
502 valid.into_message()
503 } else {
504 stun_msg
505 };
506 self.finish(id, StunEvent::Message(message));
507 Ok(())
508 }
509
510 fn poll_read(&mut self) -> Option<Self::Rout> {
511 None
512 }
513
514 /// Sends a message to the server.
515 ///
516 /// A request starts a transaction, which ends with one event: the response, a timeout or
517 /// a failure. An indication is sent and forgotten: it has no response and no timeout (RFC
518 /// 8489 section 6.3.2).
519 ///
520 /// # Errors
521 ///
522 /// Fails when the client is closed, when the message is larger than the path MTU allows
523 /// over UDP (`ErrPacketTooBig`; RFC 8489 section 6.1,
524 /// [`with_path_mtu`](ClientBuilder::with_path_mtu)), when a request reuses the
525 /// transaction id of an outstanding one, and when the limit of outstanding transactions
526 /// is reached (RFC 8489 section 6.2;
527 /// [`with_max_outstanding_transactions`](ClientBuilder::with_max_outstanding_transactions)).
528 fn handle_write(&mut self, msg: TaggedMessage) -> Result<()> {
529 if self.settings.closed {
530 return Err(Error::ErrClientClosed);
531 }
532
533 let now = msg.now;
534 self.observe(now);
535 let m = msg.message;
536
537 if m.raw.len() > self.max_message_size() {
538 return Err(Error::ErrPacketTooBig);
539 }
540 if m.typ.class != CLASS_REQUEST {
541 self.transmit(now, &m.raw);
542 return Ok(());
543 }
544 if self.transactions.contains_key(&m.transaction_id) {
545 return Err(Error::ErrTransactionExists);
546 }
547 if self.settings.max_outstanding != 0
548 && self.transactions.len() >= self.settings.max_outstanding
549 {
550 return Err(Error::Other(format!(
551 "{} transactions are outstanding to {}, the limit of RFC 8489 section 6.2",
552 self.transactions.len(),
553 self.remote
554 )));
555 }
556
557 let mut ct = ClientTransaction {
558 id: m.transaction_id,
559 method: m.typ.method,
560 sent: 1,
561 start: now,
562 rto: self.rto.start(now),
563 deadline: now,
564 discarded: false,
565 raw: m.raw,
566 };
567 ct.deadline = self.next_deadline(&ct, now);
568 self.transmit(now, &ct.raw);
569 self.transactions.insert(ct.id, ct);
570
571 Ok(())
572 }
573
574 /// Returns packets to transmit
575 ///
576 /// It should be polled for transmit after:
577 /// - the application performed some I/O
578 /// - a call was made to `handle_read`
579 /// - a call was made to `handle_write`
580 /// - a call was made to `handle_timeout`
581 fn poll_write(&mut self) -> Option<Self::Wout> {
582 self.transmits.pop_front()
583 }
584
585 fn poll_event(&mut self) -> Option<Self::Eout> {
586 self.events.pop_front()
587 }
588
589 /// When `handle_timeout` is next due: the earliest retransmission or transaction end.
590 fn poll_timeout(&mut self) -> Option<Self::Time> {
591 self.transactions.values().map(|ct| ct.deadline).min()
592 }
593
594 /// Advances time: every request whose interval has passed (`deadline <= now`) is sent
595 /// again, or, after its last transmission, its transaction ends with
596 /// [`StunEvent::TransactionTimeOut`].
597 fn handle_timeout(&mut self, now: Instant) -> Result<()> {
598 if self.settings.closed {
599 return Err(Error::ErrClientClosed);
600 }
601 self.observe(now);
602 for id in self.due(now) {
603 let Some(mut ct) = self.transactions.remove(&id) else {
604 continue;
605 };
606 if self.is_reliable() || ct.sent >= self.settings.rc {
607 // RFC 8489 section 9.1.4: when every response was discarded, the failure is an
608 // integrity violation, not a timeout.
609 self.events.push_back(if ct.discarded {
610 StunEvent::TransactionFailed {
611 id,
612 reason: TransactionFailure::IntegrityViolation,
613 }
614 } else {
615 StunEvent::TransactionTimeOut
616 });
617 continue;
618 }
619 ct.sent += 1;
620 ct.deadline = self.next_deadline(&ct, now);
621 self.transmit(now, &ct.raw);
622 self.transactions.insert(id, ct);
623 }
624 Ok(())
625 }
626
627 fn close(&mut self) -> Result<()> {
628 if self.settings.closed {
629 return Err(Error::ErrClientClosed);
630 }
631 self.settings.closed = true;
632 let mut ids: Vec<TransactionId> = self.transactions.keys().copied().collect();
633 ids.sort_by_key(|id| id.0);
634 for _ in ids {
635 self.events.push_back(StunEvent::AgentClosed);
636 }
637 self.transactions.clear();
638 Ok(())
639 }
640}
641
642#[cfg(test)]
643mod client_conformance_test;
644
645#[cfg(test)]
646mod client_test {
647 use super::*;
648 use sansio::Protocol;
649
650 fn addrs() -> (SocketAddr, SocketAddr) {
651 (
652 "127.0.0.1:5000".parse().unwrap(),
653 "127.0.0.1:3478".parse().unwrap(),
654 )
655 }
656
657 fn binding_request() -> Message {
658 let mut msg = Message::new();
659 msg.build(&[Box::<TransactionId>::default(), Box::new(BINDING_REQUEST)])
660 .expect("a binding request encodes");
661 msg
662 }
663
664 /// The transaction deadline is computed from the instant the caller supplied to
665 /// `handle_write`, not from an ambient reading, so a retransmission can be observed by
666 /// arithmetic on a base instant with no wall-clock time passing and no sleeping.
667 #[test]
668 fn test_transaction_retransmits_on_injected_time() -> Result<()> {
669 let base = Instant::now();
670 let t = |millis| base + Duration::from_millis(millis);
671
672 let (local, remote) = addrs();
673 let mut client = ClientBuilder::new()
674 .with_rto(Duration::from_millis(100))
675 .build(t(0), local, remote, TransportProtocol::UDP)?;
676
677 // The write is stamped at t(10), so the first attempt's deadline is t(10) + 1 * rto.
678 client.handle_write(TaggedMessage {
679 now: t(10),
680 message: binding_request(),
681 })?;
682
683 let transmit = client.poll_write().expect("the request is queued");
684 assert_eq!(
685 transmit.now,
686 t(10),
687 "the request carries the caller's instant, not an ambient reading"
688 );
689 assert!(client.poll_write().is_none());
690
691 assert_eq!(
692 client.poll_timeout(),
693 Some(t(110)),
694 "the deadline is one RTO after the instant the caller wrote at"
695 );
696
697 // Before the deadline nothing is retransmitted.
698 client.handle_timeout(t(109))?;
699 while client.poll_event().is_some() {}
700 assert!(
701 client.poll_write().is_none(),
702 "the deadline is not yet reached one millisecond before it"
703 );
704
705 // At the deadline the request goes out again, stamped with that same instant: a
706 // driver that sleeps until `poll_timeout` and then calls `handle_timeout` makes
707 // progress.
708 client.handle_timeout(t(110))?;
709 while client.poll_event().is_some() {}
710 let retransmit = client.poll_write().expect("the request is retransmitted");
711 assert_eq!(retransmit.now, t(110));
712 assert_eq!(
713 retransmit.message, transmit.message,
714 "a retransmission repeats the original request verbatim"
715 );
716
717 // The second interval is twice the first, from the instant it was scheduled at.
718 assert_eq!(client.poll_timeout(), Some(t(310)));
719
720 client.close()
721 }
722}