Skip to main content

rtci_turn/client/
mod.rs

1//! The Sans-I/O TURN client.
2//!
3//! Using a relay takes three steps: Allocate to obtain a public address, CreatePermission for
4//! each peer you intend to exchange data with, and then Send/Data indications (or a bound channel)
5//! to move bytes. Each step is a STUN transaction, so every [`Event`] carries the
6//! transaction id of the request it answers.
7//!
8//! The three address kinds are easy to confuse: [`RelayedAddr`] is what peers send to,
9//! [`ReflexiveAddr`] is how the server sees this client, and [`PeerAddr`] is the far end.
10#[cfg(test)]
11mod client_allocate_options_test;
12#[cfg(test)]
13mod client_allocate_test;
14#[cfg(test)]
15mod client_cached_credential_test;
16#[cfg(test)]
17mod client_channel_test;
18#[cfg(test)]
19mod client_data_source_test;
20#[cfg(test)]
21mod client_hardening_test;
22#[cfg(test)]
23mod client_lifecycle_test;
24#[cfg(test)]
25mod client_permission_refresh_test;
26#[cfg(test)]
27mod client_permission_test;
28#[cfg(test)]
29mod client_retry_test;
30#[cfg(test)]
31mod client_server_error_test;
32#[cfg(test)]
33mod client_software_mtu_test;
34#[cfg(test)]
35mod client_stale_nonce_test;
36#[cfg(test)]
37mod client_stun8489_config_test;
38#[cfg(test)]
39mod client_stun8489_test;
40#[cfg(test)]
41mod client_tcp_allocation_test;
42#[cfg(test)]
43mod client_test;
44#[cfg(test)]
45mod test_server;
46
47mod allocation;
48/// Channel bindings, which replace the 36-byte Data indication header with a 4-byte one.
49pub mod binding;
50pub(crate) mod credential;
51/// The data connections of a TCP allocation (RFC 6062).
52pub mod data_connection;
53mod error;
54/// Per-peer send permissions, which a relay requires before it will forward to an address.
55pub mod permission;
56mod proto;
57/// A live allocation on the server, and sending or receiving through it.
58pub mod relay;
59/// Outstanding request tracking, with the RFC's retransmission schedule.
60pub mod transaction;
61
62use bytes::BytesMut;
63use crypto::RTCCryptoProvider;
64use log::{debug, trace};
65use std::collections::{HashMap, VecDeque};
66use std::net::{IpAddr, Ipv4Addr, SocketAddr, SocketAddrV4};
67use std::sync::Arc;
68use std::time::{Duration, Instant};
69
70use stun::alternate::RedirectGuard;
71/// The redirection of an authenticated 300 (Try Alternate): see
72/// [`ErrorResponse::try_alternate`] and [`Client::follow_alternate`].
73pub use stun::alternate::TryAlternate;
74use stun::attributes::*;
75#[cfg(test)]
76use stun::integrity::*;
77use stun::message::*;
78use stun::textattrs::*;
79use stun::timer::Schedule;
80use stun::validated::{Rejection, ValidatedMessage, Validator};
81use stun::xoraddr::*;
82
83use allocation::FamilyBlock;
84pub use allocation::{AllocateOptions, RelayTransport};
85use credential::{Checked, Credential, Login};
86pub use error::{ErrorResponse, RequestError};
87use transaction::*;
88
89use crate::client::relay::{Relay, RelayState};
90use crate::proto::chandata::*;
91use crate::proto::channum::ChannelNumber;
92use crate::proto::connid::ConnectionId;
93use crate::proto::data::*;
94use crate::proto::icmp::Icmp;
95use crate::proto::lifetime::Lifetime;
96use crate::proto::peeraddr::*;
97#[cfg(test)]
98use crate::proto::{PROTO_UDP, relayaddr::RelayedAddress, reqtrans::RequestedTransport};
99use shared::error::{Error, Result};
100use shared::util::lookup_host;
101use shared::{TransportContext, TransportMessage, TransportProtocol};
102use stun::error_code::ErrorCodeAttribute;
103use stun::fingerprint::FINGERPRINT;
104
105/// The comprehension-required attributes the TURN client understands in what it receives:
106/// those of STUN, of TURN (RFC 8656 §18) and of TCP allocations (RFC 6062 §6.2), and the three
107/// of RFC 3489 that old STUN servers still put in a Binding response. A message with any other
108/// is not processed (RFC 8489 §6.3.2 to §6.3.4).
109pub(crate) const KNOWN_ATTRIBUTES: &[AttrType] = &[
110    ATTR_MAPPED_ADDRESS,
111    ATTR_USERNAME,
112    ATTR_MESSAGE_INTEGRITY,
113    ATTR_ERROR_CODE,
114    ATTR_UNKNOWN_ATTRIBUTES,
115    ATTR_REALM,
116    ATTR_NONCE,
117    ATTR_MESSAGE_INTEGRITY_SHA256,
118    ATTR_PASSWORD_ALGORITHM,
119    ATTR_USER_HASH,
120    ATTR_XORMAPPED_ADDRESS,
121    ATTR_CHANNEL_NUMBER,
122    ATTR_LIFETIME,
123    ATTR_XOR_PEER_ADDRESS,
124    ATTR_DATA,
125    ATTR_XOR_RELAYED_ADDRESS,
126    ATTR_REQUESTED_ADDRESS_FAMILY,
127    ATTR_EVEN_PORT,
128    ATTR_REQUESTED_TRANSPORT,
129    ATTR_DONT_FRAGMENT,
130    ATTR_RESERVATION_TOKEN,
131    ATTR_CONNECTION_ID,
132    ATTR_SOURCE_ADDRESS,
133    ATTR_CHANGED_ADDRESS,
134    AttrType(0x000b),
135];
136
137/// The validator every received STUN message goes through.
138pub(crate) fn validator() -> Validator<'static> {
139    Validator::new().known_attributes(KNOWN_ATTRIBUTES)
140}
141
142/// A response that passed the checks, and the request it answers.
143pub(crate) struct Response {
144    /// The response, reduced to the attributes ahead of its integrity attribute: nothing
145    /// that follows it is read (RFC 8489 §9).
146    pub(crate) msg: ValidatedMessage,
147    /// The request as it was sent.
148    pub(crate) request: BytesMut,
149}
150
151impl Response {
152    /// The request the response answers, decoded.
153    pub(crate) fn request(&self) -> Message {
154        let mut request = Message::new();
155        request.raw = self.request.to_vec();
156        // What the client built decodes; if it does not, the request counts as unsigned.
157        let _ = request.decode();
158        request
159    }
160
161    /// The error of an error response.
162    pub(crate) fn error(&self) -> RequestError {
163        RequestError::of(&self.msg)
164    }
165
166    /// A response nothing checked, to a request without a credential: for tests that hand a
167    /// handler its response directly.
168    #[cfg(test)]
169    pub(crate) fn unchecked(msg: &Message) -> Self {
170        Self {
171            msg: Validator::new()
172                .unauthenticated(msg)
173                .expect("the response has no wrong FINGERPRINT"),
174            request: BytesMut::new(),
175        }
176    }
177}
178
179impl std::ops::Deref for Response {
180    type Target = Message;
181
182    fn deref(&self) -> &Message {
183        &self.msg
184    }
185}
186
187/// Why a transaction ended without a response the client could act on.
188pub(crate) enum Failure {
189    /// Nothing arrived in time.
190    Timeout,
191    /// Every response that arrived failed the integrity check, or, over a reliable
192    /// transport, one did (RFC 8489 §9.2.5).
193    IntegrityViolation,
194    /// The response carried comprehension-required attributes the client does not know
195    /// (RFC 8489 §6.3.3, §6.3.4).
196    UnknownAttributes(Vec<AttrType>),
197}
198
199impl Failure {
200    fn error(&self) -> Error {
201        match self {
202            Self::Timeout => Error::ErrTimeout,
203            Self::IntegrityViolation => Error::ErrIntegrityMismatch,
204            Self::UnknownAttributes(unknown) => {
205                Error::Other(Rejection::UnknownAttributes(unknown.clone()).to_string())
206            }
207        }
208    }
209}
210
211/// The retransmission timer of the client's requests (RFC 8489 §6.2), the one `rtci-stun` has
212/// ([`stun::timer`]). The default is the RFC's.
213///
214/// Over UDP a request is sent again after RTO, then after twice that, and so on, `rc` times in
215/// all, and its transaction fails `rm` x RTO after the last: with the defaults and an RTO of
216/// 500 ms, at 0, 0.5, 1.5, 3.5, 7.5, 15.5 and 31.5 s, failing at 39.5 s. Over TCP or TLS it is
217/// sent once and fails after `ti`. The initial RTO is [`ClientConfig::rto_in_ms`].
218#[derive(Debug, Clone, Copy, PartialEq, Eq)]
219pub struct RetransmissionConfig {
220    /// Rc: how many times a request is sent over UDP (RFC 8489 §6.2.1; 7). Values below 1
221    /// are 1.
222    pub rc: u32,
223    /// Rm: the transaction fails Rm x RTO after the last request (RFC 8489 §6.2.1; 16).
224    pub rm: u32,
225    /// Ti: how long a request waits over a reliable transport (RFC 8489 §6.2.2; 39.5 s).
226    pub ti: Duration,
227    /// Whether the RTO follows the server's round-trip times as RFC 6298 computes it, never
228    /// below the initial RTO, kept per server and dropped after ten minutes without a
229    /// transaction (RFC 8489 §6.2.1; on). Off: every transaction starts at the initial RTO.
230    pub rto_estimation: bool,
231    /// Most transactions outstanding to one server (RFC 8489 §6.2; 10). A request past the
232    /// limit is sent when one of them ends. `0` lifts the limit, for an application that
233    /// limits its rate some other way.
234    pub max_outstanding_transactions: usize,
235}
236
237impl Default for RetransmissionConfig {
238    fn default() -> Self {
239        let schedule = Schedule::default();
240        Self {
241            rc: schedule.rc,
242            rm: schedule.rm,
243            ti: schedule.ti,
244            rto_estimation: true,
245            max_outstanding_transactions: stun::timer::DEFAULT_MAX_OUTSTANDING,
246        }
247    }
248}
249const MAX_DATA_BUFFER_SIZE: usize = u16::MAX as usize; // message size limit for Chromium
250const MAX_READ_QUEUE_SIZE: usize = 1024;
251
252/// The public address the TURN server allocated on this client's behalf.
253///
254/// Peers send here; the server forwards to the client.
255pub type RelayedAddr = SocketAddr;
256/// The client's own address as seen by the server — its server-reflexive address.
257pub type ReflexiveAddr = SocketAddr;
258/// The address of a remote peer the client exchanges data with through the relay.
259pub type PeerAddr = SocketAddr;
260
261#[derive(Debug)]
262/// What the client produces in response to inbound datagrams and elapsed time.
263///
264/// A variant that answers a request the caller made carries the [`TransactionId`] that
265/// request returned, so responses can be matched to requests. A variant about an allocation
266/// as a whole (lost, released, a refresh or a channel bind the client made by itself) names
267/// the allocation by its relayed address instead.
268#[non_exhaustive]
269pub enum Event {
270    /// A request exhausted its retransmissions without a response.
271    ///
272    /// A request whose every response was discarded for its integrity, or whose response
273    /// carried attributes the client must but does not understand, does not end here: it is
274    /// reported by the error event of its kind ([`Event::AllocateError`],
275    /// [`Event::RefreshError`], ...) with [`RequestError::Failed`], an
276    /// `ErrIntegrityMismatch` in the first case (RFC 8489 §9.2.5: an integrity violation is
277    /// not a timeout).
278    TransactionTimeout(TransactionId),
279
280    /// A STUN Binding succeeded, reporting this client's server-reflexive address.
281    BindingResponse(TransactionId, ReflexiveAddr),
282    /// A STUN Binding failed.
283    BindingError(TransactionId, Error),
284
285    /// An Allocate succeeded; the relayed address is now usable.
286    AllocateResponse(TransactionId, RelayedAddr),
287    /// An Allocate failed — commonly authentication, or the server being out of ports. The
288    /// error carries the server's code (RFC 8656 §7.4 says what each one asks of the client).
289    AllocateError(TransactionId, RequestError),
290
291    /// A CreatePermission succeeded; the relay will now forward to and from this peer.
292    CreatePermissionResponse(TransactionId, PeerAddr),
293    /// A CreatePermission failed; there is no permission for the peer.
294    CreatePermissionError(TransactionId, RequestError),
295
296    /// The server no longer holds the allocation: it answered 437 (Allocation Mismatch) to a
297    /// request for it (RFC 8656 §5), or the allocation's lifetime ran out with no Refresh
298    /// answered. The client has dropped it, with its permissions and channel bindings;
299    /// [`Client::relay`] no longer finds it.
300    AllocationLost(RelayedAddr, RequestError),
301    /// An allocation the application released with [`Relay::close`] is done with: the server
302    /// confirmed, no longer had it, or never answered.
303    AllocationReleased(RelayedAddr),
304    /// A Refresh of the allocation failed. The allocation is kept and refreshed again while
305    /// its lifetime lasts; [`Event::AllocationLost`] follows if that runs out.
306    RefreshError(RelayedAddr, RequestError),
307    /// The server refused to refresh the permission for a peer's IP address. The client has
308    /// dropped it: nothing is sent to that address until a new permission is created.
309    PermissionLost(RelayedAddr, IpAddr, RequestError),
310    /// A Connect succeeded: the server has a TCP connection to the peer, named by the
311    /// CONNECTION-ID (RFC 6062 §4.3). The application now opens a new TCP connection to the
312    /// server and binds it with [`Relay::data_connection`]; the server gives it 30 seconds.
313    ConnectResponse(TransactionId, PeerAddr, ConnectionId),
314    /// A Connect failed. After a 447 (Connection Timeout or Failure) the same peer can be
315    /// tried again, ten seconds later at the earliest.
316    ConnectError(TransactionId, PeerAddr, RequestError),
317    /// A peer with a permission connected to the relayed address of a TCP allocation
318    /// (RFC 6062 §4.4). To accept, the application opens a new TCP connection to the server
319    /// and binds it with [`Relay::data_connection`] within 30 seconds; to refuse, it does
320    /// nothing.
321    ConnectionAttempt(RelayedAddr, PeerAddr, ConnectionId),
322    /// A datagram the server relayed to this peer was answered with an ICMP error, for
323    /// example "fragmentation needed" with the path MTU after a send with DONT-FRAGMENT
324    /// (RFC 8656 §11.6). The peer address tells whether the type and code are ICMPv4 or
325    /// ICMPv6.
326    IcmpError(PeerAddr, Icmp),
327    /// A ChannelBind for a peer failed. Data to it keeps going as Send indications, and the
328    /// bind is tried again later. After a 437, or a 400 (the channels of client and server are
329    /// out of step, RFC 8656 §12.3), [`Event::AllocationLost`] follows.
330    ChannelBindError(RelayedAddr, PeerAddr, RequestError),
331
332    /// Data arrived from a peer through the relay.
333    ///
334    /// The channel number is `Some` when it came as ChannelData and `None` when it came as a
335    /// Data indication.
336    DataIndicationOrChannelData(Option<ChannelNumber>, PeerAddr, BytesMut),
337}
338
339/// ClientConfig is a bag of config parameters for Client.
340pub struct ClientConfig {
341    /// The STUN server to use for Binding requests, as `host:port`. May be empty.
342    pub stun_serv_addr: String, // STUN server address (e.g. "stun.abc.com:3478")
343    /// The TURN server to allocate from, as `host:port`.
344    pub turn_serv_addr: String, // TURN server address (e.g. "turn.abc.com:3478")
345    /// The local address the client sends from.
346    pub local_addr: SocketAddr,
347    /// Whether to reach the server over UDP or TCP.
348    pub transport_protocol: TransportProtocol,
349    /// The long-term credential username for the TURN server. It is sent as USERNAME, or
350    /// hashed as USERHASH when the server's nonce says it supports that (RFC 8489 §9.2.5).
351    pub username: String,
352    /// The long-term credential password.
353    pub password: String,
354    /// Not used: the realm is the one the server names in its 401 (RFC 8489 §9.2.5).
355    pub realm: String,
356    /// The `SOFTWARE` attribute of every request (RFC 8489 Section 6.1: requests "SHOULD"
357    /// carry one; Section 16.1.2: its use "SHOULD" be configurable). The default is
358    /// [`DEFAULT_SOFTWARE`] (`rtci-turn` and its version); empty sends none, for an
359    /// application that would not tell its software to the path.
360    pub software: String,
361    /// Whether Send indications carry [`ClientConfig::software`] too (RFC 8489 Section 6.1:
362    /// "Indications MAY include a SOFTWARE attribute"). Off by default: Send indications are
363    /// the relayed data path, and the attribute would cost its bytes on every packet sent
364    /// before a channel is bound, for no effect on the protocol. Nothing is added when
365    /// `software` is empty.
366    pub software_in_indications: bool,
367    /// The initial retransmission timeout in milliseconds; each retransmission doubles the
368    /// wait. `0` selects the default, the 500 ms RFC 8489 §6.2.1 asks for at least.
369    pub rto_in_ms: u64,
370    /// The rest of the retransmission timer: Rc, Rm, Ti, the RTO estimate and the number of
371    /// outstanding transactions.
372    pub retransmission: RetransmissionConfig,
373    /// The password algorithms accepted from the server's PASSWORD-ALGORITHMS
374    /// (`stun::password_algorithm`), the first of the server's list that is in here being
375    /// used. Empty for all the client implements, SHA-256 and MD5. Without MD5, a server
376    /// that offers no list (RFC 5389) or MD5 alone is not authenticated to: RFC 8489
377    /// §18.5.1.1 keeps MD5 for such servers only.
378    pub password_algorithms: Vec<u16>,
379    /// Optional upper bound for the interval between allocation Refresh requests.
380    ///
381    /// By default, allocations are refreshed at half the lifetime advertised by the server.
382    /// A shorter cap can also keep the client-to-server NAT mapping active when an allocation
383    /// waits without carrying application traffic. Values below one second are rounded up.
384    pub allocation_refresh_interval_cap: Option<Duration>,
385    /// The user name reveals the user and this connection to the server is not (D)TLS: it is
386    /// sent only as USERHASH, and a server that does not offer USERHASH gets no request with
387    /// the credential (RFC 8656 §21.1.6: "If the username reveals the identity of the user,
388    /// the client MUST use the USERHASH attribute ... or use (D)TLS").
389    pub username_anonymity_required: bool,
390}
391
392impl Default for ClientConfig {
393    fn default() -> Self {
394        Self {
395            stun_serv_addr: "".to_string(),
396            turn_serv_addr: "".to_string(),
397            local_addr: SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)),
398            transport_protocol: Default::default(),
399            username: "".to_string(),
400            password: "".to_string(),
401            realm: "".to_string(),
402            software: DEFAULT_SOFTWARE.to_string(),
403            software_in_indications: false,
404            rto_in_ms: 0,
405            retransmission: RetransmissionConfig::default(),
406            password_algorithms: vec![],
407            allocation_refresh_interval_cap: None,
408            username_anonymity_required: false,
409        }
410    }
411}
412
413/// The default `SOFTWARE` of the TURN client's requests ([`ClientConfig::software`]).
414pub const DEFAULT_SOFTWARE: &str = concat!("rtci-turn ", env!("CARGO_PKG_VERSION"));
415
416/// RFC 8489 Section 6.1: with the path MTU unknown, a STUN message over UDP is at most 576
417/// bytes of IPv4 datagram, 1280 of IPv6 (the IP and UDP headers taken off).
418const UNKNOWN_PATH_MTU_V4: usize = 576;
419const UNKNOWN_PATH_MTU_V6: usize = 1280;
420const IP_UDP_OVERHEAD_V4: usize = 28;
421const IP_UDP_OVERHEAD_V6: usize = 48;
422
423/// Client is a STUN client
424pub struct Client {
425    crypto_provider: Arc<dyn RTCCryptoProvider>,
426    stun_serv_addr: Option<SocketAddr>,
427    turn_serv_addr: Option<SocketAddr>,
428    local_addr: SocketAddr,
429    transport_protocol: TransportProtocol,
430    /// What the application authenticates with; each allocation has its own state of it.
431    login: Arc<Login>,
432    software: Software,
433    /// [`ClientConfig::software_in_indications`].
434    software_in_indications: bool,
435    /// The path MTU for requests over UDP ([`Client::set_path_mtu`]); `None`: unknown.
436    path_mtu: Option<usize>,
437    tr_map: TransactionMap,
438    /// The TURN servers an Allocate was sent to, against redirection loops (RFC 8489 §10).
439    redirects: RedirectGuard,
440    allocation_refresh_interval_cap: Option<Duration>,
441
442    /// Allocations, each under the first relayed address it was given.
443    relays: HashMap<RelayedAddr, RelayState>,
444    /// Address families the server refused, by `REQUESTED-ADDRESS-FAMILY` value less one.
445    family_blocks: [Option<FamilyBlock>; 2],
446    /// Whether the server answered an Allocate with a family that was not asked for.
447    family_mismatch: bool,
448    transmits: VecDeque<TransportMessage<BytesMut>>,
449    events: VecDeque<Event>,
450    /// Most times one request is sent again after a server error
451    /// ([`Client::set_server_error_resends`]).
452    server_error_resends: u32,
453    /// Requests answered with a server error, waiting to be sent again (RFC 8489 §6.3.4).
454    resends: Vec<Resend>,
455    /// [`Client::set_unauthenticated_allocations`].
456    unauthenticated_allocations: bool,
457    /// The credential of the last allocation the server granted with one
458    /// ([`Client::cached_credential`]).
459    accepted: Option<CachedCredential>,
460    /// The credential an Allocate starts with when it is not the first request to the server
461    /// ([`Client::use_cached_credential`]): `None`, the first request carries none.
462    start_with: Option<Arc<Credential>>,
463}
464
465/// The realm, nonce and password algorithm a TURN server accepted an authenticated request
466/// with, and the user name and password they were used with: what RFC 8489 §9.2.3.2 has a
467/// client cache "for subsequent communications with the server". A later client to the same
468/// server with the same login starts its Allocate with them
469/// ([`Client::use_cached_credential`]) instead of an unauthenticated request that draws a 401,
470/// one round trip less. It is taken only by a client of the same server address and login.
471#[derive(Clone)]
472pub struct CachedCredential {
473    server: SocketAddr,
474    credential: Arc<Credential>,
475}
476
477impl CachedCredential {
478    /// The server the credential was accepted by.
479    pub fn server(&self) -> SocketAddr {
480        self.server
481    }
482
483    /// Whether `other` is for the same server address and the same login, so that the later
484    /// of the two replaces the earlier in a cache.
485    pub fn is_for_same_server_and_login(&self, other: &CachedCredential) -> bool {
486        self.server == other.server && self.credential.has_login_of(&other.credential)
487    }
488}
489
490impl std::fmt::Debug for CachedCredential {
491    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
492        // The key and the password stay out of logs.
493        f.debug_struct("CachedCredential")
494            .field("server", &self.server)
495            .finish_non_exhaustive()
496    }
497}
498
499/// A request answered with a server error (500 to 599), to be sent again as a new
500/// transaction (RFC 8489 §6.3.4).
501pub(crate) struct Resend {
502    /// When it is sent.
503    pub(crate) due: Instant,
504    /// The server it goes to.
505    to: SocketAddr,
506    /// The id its caller was handed, which its events name.
507    report_id: TransactionId,
508    /// What is sent, with the resend counted.
509    kind: TransactionType,
510}
511
512impl Client {
513    /// Returns a new TURN client.
514    ///
515    /// The crypto provider is supplied by the caller; this crate never resolves a default.
516    pub fn new(config: ClientConfig, crypto_provider: Arc<dyn RTCCryptoProvider>) -> Result<Self> {
517        let stun_serv_addr = if config.stun_serv_addr.is_empty() {
518            None
519        } else {
520            Some(lookup_host(
521                config.local_addr.is_ipv4(),
522                config.stun_serv_addr.as_str(),
523            )?)
524        };
525
526        let turn_serv_addr = if config.turn_serv_addr.is_empty() {
527            None
528        } else {
529            Some(lookup_host(
530                config.local_addr.is_ipv4(),
531                config.turn_serv_addr.as_str(),
532            )?)
533        };
534
535        Ok(Client {
536            crypto_provider: crypto_provider.clone(),
537            stun_serv_addr,
538            turn_serv_addr,
539            local_addr: config.local_addr,
540            transport_protocol: config.transport_protocol,
541            login: Arc::new(Login {
542                username: config.username,
543                password: config.password,
544                password_algorithms: config.password_algorithms,
545                username_anonymity_required: config.username_anonymity_required,
546            }),
547            software: Software::new(ATTR_SOFTWARE, config.software),
548            software_in_indications: config.software_in_indications,
549            path_mtu: None,
550            tr_map: TransactionMap::new(TimerSettings {
551                initial_rto: if config.rto_in_ms != 0 {
552                    Duration::from_millis(config.rto_in_ms)
553                } else {
554                    stun::timer::DEFAULT_RTO
555                },
556                schedule: Schedule {
557                    rc: config.retransmission.rc.max(1),
558                    rm: config.retransmission.rm,
559                    ti: config.retransmission.ti,
560                },
561                estimate_rto: config.retransmission.rto_estimation,
562                max_outstanding: config.retransmission.max_outstanding_transactions,
563            }),
564            redirects: RedirectGuard::new(),
565            allocation_refresh_interval_cap: config.allocation_refresh_interval_cap,
566            relays: HashMap::new(),
567            family_blocks: [None, None],
568            family_mismatch: false,
569            transmits: VecDeque::new(),
570            events: VecDeque::new(),
571            server_error_resends: stun::timer::DEFAULT_SERVER_ERROR_RESENDS,
572            resends: Vec::new(),
573            unauthenticated_allocations: false,
574            accepted: None,
575            start_with: None,
576        })
577    }
578
579    /// The credential the server accepted the last allocation of this client with: its realm,
580    /// nonce and password algorithm, with this client's login (RFC 8489 §9.2.3.2). `None`
581    /// before an authenticated Allocate succeeded, and for an allocation the server granted
582    /// without a credential.
583    pub fn cached_credential(&self) -> Option<CachedCredential> {
584        self.accepted.clone()
585    }
586
587    /// Starts this client's Allocates with `cached`, the credential another client's
588    /// authenticated request to the same server succeeded with (RFC 8489 §9.2.3.2: "The
589    /// client SHOULD cache the username, password, realm, and nonce for subsequent
590    /// communications with the server. When the client sends a subsequent request, it MUST
591    /// include ... these cached values"): the first Allocate carries the credential, and the
592    /// 401 round trip of a first request (§9.2.3.1) is saved. Taken only when `cached` is of
593    /// this client's TURN server address and of the same user name, password and accepted
594    /// password algorithms; returns whether it was taken.
595    ///
596    /// A 438 (Stale Nonce) to such an Allocate is answered with the new nonce (§9.2.5). A 401
597    /// to it (the server no longer knows the realm or the nonce) sends the request again as
598    /// a request made after a first 401, so a cached credential costs at most the round trip
599    /// it was to save.
600    pub fn use_cached_credential(&mut self, cached: &CachedCredential) -> bool {
601        let same = self.turn_serv_addr == Some(cached.server)
602            && cached.credential.is_for(&self.login)
603            && cached.credential.is_established();
604        if same {
605            self.start_with = Some(cached.credential.clone());
606        }
607        same
608    }
609
610    /// How many times a request answered with a server error (500 to 599) is sent again
611    /// before the error is reported (RFC 8489 §6.3.4: the client "MAY resend the request;
612    /// clients that do so MUST limit the number of times they do this. Unless a specific
613    /// error code specifies a different value, the number of retransmissions SHOULD be
614    /// limited to 4"). The default is [`stun::timer::DEFAULT_SERVER_ERROR_RESENDS`], 4; 0
615    /// reports the first server error.
616    ///
617    /// Every request is resent this way: Binding, Allocate, Refresh (a release too),
618    /// CreatePermission, ChannelBind and Connect. Each resend is a new transaction under a new
619    /// transaction id, made again with the allocation's current credential, and waits after
620    /// the error as long as the retransmission of the same number would
621    /// ([`stun::timer::server_error_resend_delay`]: RTO, 2 RTO, 4 RTO, 8 RTO). The count
622    /// belongs to the one request: a new one (the next Refresh, another Allocate) starts from
623    /// none. Its events name the id its caller was handed, and the error event of its kind
624    /// ([`Event::AllocateError`], [`Event::RefreshError`], ...) comes only after the last
625    /// resend was answered with a server error too. A 508 (Insufficient Capacity) is not
626    /// resent: to an Allocate, RFC 8656 §7.4 has the client consider the operation failed and
627    /// wait at least a minute before it asks the server for another allocation, and the code
628    /// names a capacity limit for the other methods too (§19).
629    pub fn set_server_error_resends(&mut self, resends: u32) {
630        self.server_error_resends = resends;
631    }
632
633    /// Whether a client configured with a long-term credential
634    /// ([`ClientConfig::username`], [`ClientConfig::password`]) believes a success response
635    /// that carries no integrity attribute: one to the first Allocate, which goes without the
636    /// credential (RFC 8489 §9.2.3.1), and so to the requests of the allocation it makes. Off
637    /// by default.
638    ///
639    /// Off, such a response is discarded as one that fails its integrity check (RFC 8489
640    /// §9.2.5): over UDP as if it had never been received, the request being retransmitted,
641    /// over TCP or TLS ending the transaction at once, and either way reported as
642    /// [`RequestError::Failed`] with `ErrIntegrityMismatch` in the error event of its kind
643    /// ([`Event::AllocateError`], ...), not as a timeout. A 401 that arrives meanwhile is
644    /// answered as usual. RFC 8656 §21.1.5 relies on the integrity of responses to keep an
645    /// attacker from handing the client "a faked relayed address"; a success nothing signs
646    /// can come from anyone who sees the request, and the client has the credential to ask
647    /// for a signed one.
648    ///
649    /// On, a server that asks for no credential (RFC 8656 §7.2 step 1, the access-network
650    /// servers of RFC 8155 §9) can be used by a client that has one: its unsigned success is
651    /// an allocation, and the allocation's requests go without the credential until the server
652    /// asks for it with a 401. A client without a credential always takes such a success:
653    /// there is no key to check it with.
654    pub fn set_unauthenticated_allocations(&mut self, accept: bool) {
655        self.unauthenticated_allocations = accept;
656    }
657
658    // handle_inbound handles data received.
659    // This method handles incoming packet demultiplex it by the source address
660    // and the types of the message.
661    // This return Ok(handled or not) and if there was an error.
662    // Caller should check if the packet was handled by this client or not.
663    // If not handled, it is assumed that the packet is application data.
664    // If an error is returned, the caller should discard the packet regardless.
665    fn handle_inbound(&mut self, now: Instant, data: &[u8], from: SocketAddr) -> Result<()> {
666        // +-------------------+-------------------------------+
667        // |   Return Values   |                               |
668        // +-------------------+       Meaning / Action        |
669        // | handled |  error  |                               |
670        // |=========+=========+===============================+
671        // |  false  |   nil   | Handle the packet as app data |
672        // |---------+---------+-------------------------------+
673        // |  true   |   nil   |        Nothing to do          |
674        // |---------+---------+-------------------------------+
675        // |  false  |  error  |     (shouldn't happen)        |
676        // |---------+---------+-------------------------------+
677        // |  true   |  error  | Error occurred while handling |
678        // +---------+---------+-------------------------------+
679        // Possible causes of the error:
680        //  - Malformed packet (parse error)
681        //  - STUN message was a request
682        //  - Non-STUN message from the STUN server
683
684        // TURN and STUN messages are only ever sent to us by the servers we talk to. Anything
685        // else that looks like one — a spoofed Data indication, ChannelData or a forged
686        // response — is not from the server and must not be acted on or relayed as peer data.
687        let from_turn_server = self.turn_serv_addr == Some(from);
688        let from_a_server = from_turn_server || self.stun_serv_addr == Some(from);
689        if is_stun_message(data) {
690            // A response to a request sent to some other address (`send_binding_request_to`)
691            // is accepted from that address only.
692            if !from_a_server && !self.is_response_from_transaction_peer(data, from) {
693                debug!("discarding STUN message from {from}: not a configured server");
694                return Ok(());
695            }
696            self.handle_stun_message(now, data, from_turn_server)
697        } else if ChannelData::is_channel_data(data) {
698            if !from_turn_server {
699                debug!("discarding ChannelData from {from}: not the TURN server");
700                return Ok(());
701            }
702            self.handle_channel_data(now, data)
703        } else if self.stun_serv_addr.is_some() && &from == self.stun_serv_addr.as_ref().unwrap() {
704            // received from STUN server, but it is not a STUN message
705            Err(Error::ErrNonStunmessage)
706        } else {
707            // assume, this is an application data
708            trace!("non-STUN/TURN packet, unhandled");
709            Ok(())
710        }
711    }
712
713    /// Whether `data` is a STUN response to an outstanding transaction whose request went to
714    /// `from`.
715    fn is_response_from_transaction_peer(&self, data: &[u8], from: SocketAddr) -> bool {
716        let mut msg = Message::new();
717        msg.raw = data.to_vec();
718        if msg.decode().is_err() {
719            return false;
720        }
721        (msg.typ.class == CLASS_SUCCESS_RESPONSE || msg.typ.class == CLASS_ERROR_RESPONSE)
722            && self
723                .tr_map
724                .find(&msg.transaction_id)
725                .is_some_and(|tr| tr.peer_addr == from)
726    }
727
728    fn handle_stun_message(
729        &mut self,
730        now: Instant,
731        data: &[u8],
732        from_turn_server: bool,
733    ) -> Result<()> {
734        let mut msg = Message::new();
735        msg.raw = data.to_vec();
736        msg.decode()?;
737
738        if msg.typ.class == CLASS_REQUEST {
739            return Err(Error::Other(format!(
740                "{:?} : {}",
741                Error::ErrUnexpectedStunrequestMessage,
742                msg
743            )));
744        }
745
746        if msg.typ.class == CLASS_INDICATION {
747            return self.handle_indication(now, &msg, from_turn_server);
748        }
749
750        // This is a STUN response message (transactional)
751        // The type is either:
752        // - stun.ClassSuccessResponse
753        // - stun.ClassErrorResponse
754
755        let Some(tr) = self.tr_map.find(&msg.transaction_id) else {
756            // silently discard
757            debug!("no transaction for {}", msg);
758            return Ok(());
759        };
760
761        // Only a response of the request's method answers it (RFC 8489 §6.3). Anything else
762        // with its transaction id is not its response, and the transaction goes on.
763        if tr.method != msg.typ.method {
764            debug!(
765                "discarding {}: its transaction is a {} request",
766                msg, tr.method
767            );
768            return Ok(());
769        }
770
771        // One place for the checks of RFC 8489 §6.3, §9 and §9.2.5: FINGERPRINT, the
772        // integrity attribute the request's credential asks for, and no attribute the client
773        // has to but does not understand. What comes out holds the attributes ahead of the
774        // integrity attribute and nothing else.
775        let crypto = self.crypto_provider.crypto();
776        let checked = match &tr.credential {
777            Some(credential) => credential.check_response(&msg, &validator(), crypto),
778            None => validator().unauthenticated(&msg).map(Checked::Valid),
779        };
780        // A success that nothing signs, to a client that holds a credential, is taken as
781        // one whose integrity attribute is missing (RFC 8489 §9.2.5, RFC 8656 §21.1.5):
782        // see `set_unauthenticated_allocations`.
783        let checked = match checked {
784            Ok(Checked::Valid(valid))
785                if valid.typ.class == CLASS_SUCCESS_RESPONSE
786                    && !valid.is_authenticated()
787                    && !self.unauthenticated_allocations
788                    && tr.credential.as_ref().is_some_and(|c| c.has_login()) =>
789            {
790                Err(Rejection::IntegrityMissing)
791            }
792            other => other,
793        };
794        let valid = match checked {
795            Ok(Checked::Valid(valid)) => valid,
796            Ok(Checked::NeverReceived) => {
797                // RFC 8489 §9.2.5: an unsigned 400, or a response whose nonce cookie promises
798                // PASSWORD-ALGORITHMS it lacks. Not a response at all: the transaction and
799                // its retransmissions go on, over a reliable transport too, and it is not
800                // counted as discarded for its integrity (it ends in a timeout).
801                debug!("discarding {} as never received (RFC 8489 §9.2.5)", msg);
802                return Ok(());
803            }
804            Err(Rejection::IntegrityMissing | Rejection::IntegrityMismatch) => {
805                // A response to a signed request is believed only if it is signed with the
806                // same key (RFC 8489 §9.2.5). Over UDP it is dropped as if never received,
807                // so the transaction stays open and its retransmissions continue; over a
808                // reliable transport the transaction ends at once. Either way its failure
809                // is an integrity violation, not a timeout.
810                debug!("discarding {}: integrity attribute missing or wrong", msg);
811                if tr.is_reliable() {
812                    if let Some(tr) = self.tr_map.delete(&msg.transaction_id) {
813                        self.handle_transaction_failure(now, tr, Failure::IntegrityViolation);
814                    }
815                } else if let Some(tr) = self.tr_map.get(&msg.transaction_id) {
816                    tr.discarded = true;
817                }
818                return Ok(());
819            }
820            Err(Rejection::UnknownAttributes(unknown)) => {
821                // RFC 8489 §6.3.3, §6.3.4: the response is discarded and the transaction
822                // has failed.
823                debug!("discarding {}: unknown attributes {:?}", msg, unknown);
824                if let Some(tr) = self.tr_map.answered(&msg.transaction_id, now) {
825                    self.handle_transaction_failure(now, tr, Failure::UnknownAttributes(unknown));
826                }
827                return Ok(());
828            }
829            Err(rejection) => {
830                debug!("discarding {}: {}", msg, rejection);
831                return Ok(());
832            }
833        };
834
835        let Some(tr) = self.tr_map.answered(&msg.transaction_id, now) else {
836            return Ok(());
837        };
838        let Some(tr) = self.resend_after_server_error(now, &valid, tr) else {
839            return Ok(());
840        };
841        let id = tr.transaction_id;
842        let res = Response {
843            msg: valid,
844            request: tr.raw,
845        };
846        match tr.transaction_type {
847            TransactionType::BindingRequest(retry) => {
848                let id = retry.report_id(id);
849                if res.typ.class == CLASS_ERROR_RESPONSE {
850                    let mut code = ErrorCodeAttribute::default();
851                    let err = if code.get_from(&res).is_err() {
852                        Error::Other(format!("{}", res.typ))
853                    } else {
854                        Error::Other(format!("{} (error {})", res.typ, code))
855                    };
856                    self.events.push_back(Event::BindingError(id, err));
857                } else {
858                    let mut refl_addr = XorMappedAddress::default();
859                    match refl_addr.get_from(&res) {
860                        Ok(_)
861                            if !allocation::is_transport_address(&SocketAddr::new(
862                                refl_addr.ip,
863                                refl_addr.port,
864                            )) =>
865                        {
866                            // Port 0, unspecified, multicast or broadcast: no address the
867                            // server can have seen this client at.
868                            self.events.push_back(Event::BindingError(
869                                id,
870                                Error::Other(format!(
871                                    "XOR-MAPPED-ADDRESS {}:{} is no transport address",
872                                    refl_addr.ip, refl_addr.port
873                                )),
874                            ));
875                        }
876                        Ok(_) => {
877                            self.events.push_back(Event::BindingResponse(
878                                id,
879                                ReflexiveAddr::new(refl_addr.ip, refl_addr.port),
880                            ));
881                        }
882                        Err(err) => {
883                            self.events.push_back(Event::BindingError(id, err));
884                        }
885                    }
886                }
887            }
888            TransactionType::AllocateAttempt(state) | TransactionType::AllocateRequest(state) => {
889                self.handle_allocate_response(now, res, *state)?;
890            }
891            // A release of an allocation the client did not keep: nothing to do.
892            TransactionType::OrphanRelease => {}
893            TransactionType::FamilyRelease(relayed_addr, family, retry) => {
894                let mut relay = Relay {
895                    relayed_addr,
896                    client: self,
897                };
898                relay.handle_family_release_response(now, res, family, retry)?;
899            }
900            TransactionType::CreatePermissionRequest(
901                relayed_addr,
902                peer_addr,
903                peer_addrs,
904                retry,
905            ) => {
906                let mut relay = Relay {
907                    relayed_addr,
908                    client: self,
909                };
910                relay.handle_create_permission_response(now, res, peer_addr, peer_addrs, retry)?;
911            }
912            TransactionType::RefreshRequest(relayed_addr, lifetime, retry) => {
913                let mut relay = Relay {
914                    relayed_addr,
915                    client: self,
916                };
917                relay.handle_refresh_response(now, res, lifetime, retry)?;
918            }
919            TransactionType::ConnectRequest(relayed_addr, peer_addr, retry) => {
920                let mut relay = Relay {
921                    relayed_addr,
922                    client: self,
923                };
924                relay.handle_connect_response(now, res, peer_addr, retry)?;
925            }
926            TransactionType::ChannelBindRequest(relayed_addr, bind_addr, retry) => {
927                let mut relay = Relay {
928                    relayed_addr,
929                    client: self,
930                };
931                relay.handle_channel_bind_response(now, res, bind_addr, retry)?;
932            }
933        }
934
935        Ok(())
936    }
937
938    /// Handles an indication from a server: the peer's data, the ICMP error a datagram to a
939    /// peer met, or a peer's connection to a TCP allocation.
940    fn handle_indication(
941        &mut self,
942        now: Instant,
943        msg: &Message,
944        from_turn_server: bool,
945    ) -> Result<()> {
946        // RFC 8489 §6.3.2: an indication with a wrong FINGERPRINT, or with an attribute the
947        // client has to but does not understand, is discarded. TURN indications are not
948        // signed (RFC 8656 §11); if one carries an integrity attribute all the same, what
949        // follows it is not read (RFC 8489 §9).
950        let msg = match validator().unauthenticated(msg) {
951            Ok(msg) => msg,
952            Err(rejection) => {
953                debug!("discarding {}: {}", msg, rejection);
954                return Ok(());
955            }
956        };
957
958        if msg.typ.method == METHOD_CONNECTION_ATTEMPT {
959            // Like relayed data, a peer's connection is announced by the server holding the
960            // allocation and by nobody else.
961            if !from_turn_server {
962                debug!("discarding ConnectionAttempt indication: not from the TURN server");
963                return Ok(());
964            }
965            let mut connection_id = ConnectionId::default();
966            connection_id.get_from(&msg)?;
967            let mut peer_addr = PeerAddress::default();
968            peer_addr.get_from(&msg)?;
969            let from = SocketAddr::new(peer_addr.ip, peer_addr.port);
970            // The server accepts connections only from peers the client installed a
971            // permission for (RFC 6062 §5.3), on a TCP allocation.
972            let Some(relayed) = self
973                .relays
974                .values()
975                .find(|relay| {
976                    relay.transport == RelayTransport::Tcp
977                        && relay.expects_data_from(&from.ip(), now)
978                })
979                .map(RelayState::name)
980            else {
981                debug!("discarding ConnectionAttempt from {from}: no permission");
982                return Ok(());
983            };
984            self.events
985                .push_back(Event::ConnectionAttempt(relayed, from, connection_id));
986            return Ok(());
987        }
988
989        // Only the TURN server holding the allocation relays peer data. The STUN server,
990        // when it is a different address, has no allocation and is not believed for it.
991        if msg.typ.method == METHOD_DATA && !from_turn_server {
992            debug!("discarding Data indication: not from the TURN server");
993            return Ok(());
994        }
995        if msg.typ.method == METHOD_DATA {
996            let mut peer_addr = PeerAddress::default();
997            peer_addr.get_from(&msg)?;
998            let from = SocketAddr::new(peer_addr.ip, peer_addr.port);
999
1000            // A Data indication carries the peer's data, or the ICMP error a datagram
1001            // relayed to that peer met (RFC 8656 §11.4, §11.6). One with neither is
1002            // discarded.
1003            let mut data = Data::default();
1004            let mut icmp = Icmp::default();
1005            let has_data = msg.contains(ATTR_DATA);
1006            if has_data {
1007                data.get_from(&msg)?;
1008            } else {
1009                icmp.get_from(&msg)?;
1010            }
1011
1012            // The server relays only from addresses the client installed a permission
1013            // for, so anything else is not what it claims to be (RFC 8656 §11.4, §11.6).
1014            if !self
1015                .relays
1016                .values()
1017                .any(|relay| relay.expects_data_from(&from.ip(), now))
1018            {
1019                debug!("discarding Data indication from {from}: no permission");
1020                return Ok(());
1021            }
1022
1023            if has_data {
1024                debug!("data indication received from {}", from);
1025                self.events.push_back(Event::DataIndicationOrChannelData(
1026                    None,
1027                    from,
1028                    BytesMut::from(&data.0[..]),
1029                ))
1030            } else {
1031                debug!("{icmp} reported for {from}");
1032                self.events.push_back(Event::IcmpError(from, icmp))
1033            }
1034        }
1035
1036        Ok(())
1037    }
1038
1039    /// RFC 8489 §6.3.4: a request answered with a server error (500 to 599) is sent again
1040    /// later, as a new transaction, while it has resends left
1041    /// ([`Client::set_server_error_resends`]); then `None`. Otherwise the transaction is
1042    /// returned, for its response to be handled as it is.
1043    fn resend_after_server_error(
1044        &mut self,
1045        now: Instant,
1046        response: &Message,
1047        tr: Transaction,
1048    ) -> Option<Transaction> {
1049        if response.typ.class != CLASS_ERROR_RESPONSE {
1050            return Some(tr);
1051        }
1052        let mut code = ErrorCodeAttribute::default();
1053        if code.get_from(response).is_err() || !stun::timer::is_server_error(code.code.0) {
1054            return Some(tr);
1055        }
1056        // 508 (Insufficient Capacity) has a rule of its own: to an Allocate, "The client
1057        // considers the current operation as having failed" and waits at least a minute
1058        // before it asks again (RFC 8656 §7.4). The code is a capacity limit for every
1059        // method (§19), so a CreatePermission or ChannelBind is not resent after it either:
1060        // a ChannelBind refused that way is tried again a minute later.
1061        if code.code == stun::error_code::CODE_INSUFFICIENT_CAPACITY {
1062            return Some(tr);
1063        }
1064        let done = tr.transaction_type.server_errors()?;
1065        if done >= self.server_error_resends {
1066            return Some(tr);
1067        }
1068        let resend = done + 1;
1069        let wait = stun::timer::server_error_resend_delay(self.tr_map.rto(tr.peer_addr), resend);
1070        debug!(
1071            "{} answered {}: sent again in {wait:?} (resend {resend} of {})",
1072            tr.method, code.code.0, self.server_error_resends
1073        );
1074        let report_id = tr.transaction_type.report_id(tr.transaction_id);
1075        self.resends.push(Resend {
1076            due: stun::timer::after(now, wait),
1077            to: tr.peer_addr,
1078            report_id,
1079            kind: tr.transaction_type.after_server_error(tr.transaction_id),
1080        });
1081        None
1082    }
1083
1084    /// Sends the requests answered with a server error whose wait is over, as new
1085    /// transactions. One that cannot be made again (its allocation is gone, or the request
1086    /// cannot be built) is reported as the failure of its kind.
1087    fn send_due_resends(&mut self, now: Instant) {
1088        if !self.resends.iter().any(|r| r.due <= now) {
1089            return;
1090        }
1091        let (mut due, waiting): (Vec<Resend>, Vec<Resend>) = std::mem::take(&mut self.resends)
1092            .into_iter()
1093            .partition(|r| r.due <= now);
1094        self.resends = waiting;
1095        due.sort_by_key(|r| r.due);
1096        for resend in due {
1097            self.send_resend(now, resend);
1098        }
1099    }
1100
1101    fn send_resend(&mut self, now: Instant, resend: Resend) {
1102        let Resend {
1103            to,
1104            report_id: id,
1105            kind,
1106            ..
1107        } = resend;
1108        let failed = |err: Error| RequestError::Failed(err);
1109        match kind {
1110            TransactionType::BindingRequest(retry) => {
1111                if let Err(err) = self.binding_request_with(now, to, retry) {
1112                    self.events.push_back(Event::BindingError(id, err));
1113                }
1114            }
1115            TransactionType::AllocateAttempt(state) | TransactionType::AllocateRequest(state) => {
1116                if let Err(err) = self.send_allocate(now, TransactionId::new(), *state) {
1117                    self.events.push_back(Event::AllocateError(id, failed(err)));
1118                }
1119            }
1120            TransactionType::CreatePermissionRequest(
1121                relayed_addr,
1122                peer_addr,
1123                peer_addrs,
1124                retry,
1125            ) => {
1126                let Some(mut relay) = self.relay_by_key(relayed_addr) else {
1127                    return;
1128                };
1129                if let Err(err) = relay.create_permissions(now, &peer_addrs, peer_addr, retry)
1130                    && let Some(peer_addr) = peer_addr
1131                {
1132                    if let Some(relay) = self.relays.get_mut(&relayed_addr) {
1133                        relay.forget_unless_permitted(peer_addr.ip(), now);
1134                    }
1135                    self.events
1136                        .push_back(Event::CreatePermissionError(id, failed(err)));
1137                }
1138            }
1139            TransactionType::RefreshRequest(relayed_addr, lifetime, retry) => {
1140                let Some(mut relay) = self.relay_by_key(relayed_addr) else {
1141                    return;
1142                };
1143                if let Err(err) = relay.refresh_allocation_with(now, lifetime, retry) {
1144                    relay.refresh_failed(now, lifetime, failed(err));
1145                }
1146            }
1147            TransactionType::FamilyRelease(relayed_addr, family, retry) => {
1148                let Some(mut relay) = self.relay_by_key(relayed_addr) else {
1149                    return;
1150                };
1151                if let Err(err) = relay.release_family_with(
1152                    now,
1153                    crate::proto::reqfamily::RequestedAddressFamily(family),
1154                    retry,
1155                ) && let Some(relay) = self.relays.get(&relayed_addr)
1156                {
1157                    self.events
1158                        .push_back(Event::RefreshError(relay.name(), failed(err)));
1159                }
1160            }
1161            TransactionType::ConnectRequest(relayed_addr, peer_addr, retry) => {
1162                let Some(mut relay) = self.relay_by_key(relayed_addr) else {
1163                    return;
1164                };
1165                if let Err(err) = relay.connect_with(now, peer_addr, retry) {
1166                    if let Some(relay) = self.relays.get_mut(&relayed_addr) {
1167                        relay.connecting.remove(&peer_addr);
1168                    }
1169                    self.events
1170                        .push_back(Event::ConnectError(id, peer_addr, failed(err)));
1171                }
1172            }
1173            TransactionType::ChannelBindRequest(relayed_addr, bind_addr, retry) => {
1174                let Some(mut relay) = self.relay_by_key(relayed_addr) else {
1175                    return;
1176                };
1177                if let Err(err) = relay.rebind_channel(now, bind_addr, retry) {
1178                    relay.channel_bind_failed(now, bind_addr, failed(err));
1179                }
1180            }
1181            TransactionType::OrphanRelease => {}
1182        }
1183    }
1184
1185    /// Drops the resends waiting for the allocation `relayed_addr`, which no longer needs
1186    /// them.
1187    pub(crate) fn drop_resends_of(&mut self, relayed_addr: RelayedAddr) {
1188        self.resends
1189            .retain(|r| r.kind.relay() != Some(relayed_addr));
1190    }
1191
1192    /// When the earliest resend after a server error is due.
1193    pub(crate) fn resends_poll_timeout(&self) -> Option<Instant> {
1194        self.resends.iter().map(|r| r.due).min()
1195    }
1196
1197    /// Deals with a transaction that ended without a response the client could act on.
1198    ///
1199    /// One that exhausted its retransmissions: a Refresh or ChannelBind is started once more
1200    /// as a new transaction, so one lost burst does not let the allocation lapse or leave a
1201    /// channel unbound for good. A ChannelBind that fails again returns its binding to idle,
1202    /// so the next send binds it again. Anything not started again is reported as
1203    /// [`Event::TransactionTimeout`], under the id its caller knows.
1204    ///
1205    /// One that failed for another reason (its responses were not authentic, or carried
1206    /// attributes the client does not understand) is not started again, and is reported by
1207    /// the error event of its kind.
1208    fn handle_transaction_failure(&mut self, now: Instant, tr: Transaction, failure: Failure) {
1209        // RFC 8489 §9.2.5: when every response that arrived was discarded, the failure is an
1210        // integrity violation, not a timeout.
1211        let failure = match failure {
1212            Failure::Timeout if tr.discarded => Failure::IntegrityViolation,
1213            other => other,
1214        };
1215        let timed_out = matches!(failure, Failure::Timeout);
1216        let id = tr.transaction_type.report_id(tr.transaction_id);
1217        match tr.transaction_type {
1218            TransactionType::RefreshRequest(relayed_addr, lifetime, retry) => {
1219                if timed_out
1220                    && !retry.timeout
1221                    && let Some(mut relay) = self.relay_by_key(relayed_addr)
1222                    && relay
1223                        .refresh_allocation_with(
1224                            now,
1225                            lifetime,
1226                            retry.after_timeout(tr.transaction_id),
1227                        )
1228                        .is_ok()
1229                {
1230                    debug!("refresh timed out; sent again");
1231                    return;
1232                }
1233                let Some(mut relay) = self.relay_by_key(relayed_addr) else {
1234                    return;
1235                };
1236                let releasing = lifetime.is_zero();
1237                relay.refresh_failed(now, lifetime, RequestError::Failed(failure.error()));
1238                if releasing || !timed_out {
1239                    // The release is over, and reported as that; a failure that is not a
1240                    // timeout was reported as the refresh error it is.
1241                    return;
1242                }
1243            }
1244            TransactionType::ChannelBindRequest(relayed_addr, bind_addr, retry) => {
1245                if timed_out
1246                    && !retry.timeout
1247                    && let Some(mut relay) = self.relay_by_key(relayed_addr)
1248                    && relay
1249                        .rebind_channel(now, bind_addr, retry.after_timeout(tr.transaction_id))
1250                        .is_ok()
1251                {
1252                    debug!("channel bind for {bind_addr} timed out; sent again");
1253                    return;
1254                }
1255                if let Some(mut relay) = self.relay_by_key(relayed_addr) {
1256                    if timed_out {
1257                        relay.channel_bind_timed_out(bind_addr);
1258                    } else {
1259                        relay.channel_bind_failed(
1260                            now,
1261                            bind_addr,
1262                            RequestError::Failed(failure.error()),
1263                        );
1264                        return;
1265                    }
1266                }
1267            }
1268            TransactionType::FamilyRelease(relayed_addr, family, retry) => {
1269                if timed_out
1270                    && !retry.timeout
1271                    && let Some(mut relay) = self.relay_by_key(relayed_addr)
1272                    && relay
1273                        .release_family_with(
1274                            now,
1275                            crate::proto::reqfamily::RequestedAddressFamily(family),
1276                            retry.after_timeout(tr.transaction_id),
1277                        )
1278                        .is_ok()
1279                {
1280                    return;
1281                }
1282                // Nothing says the server deleted the address, so it is kept; the periodic
1283                // Refresh keeps the whole allocation alive.
1284                if let Some(relay) = self.relays.get(&relayed_addr) {
1285                    self.events.push_back(Event::RefreshError(
1286                        relay.name(),
1287                        RequestError::Failed(failure.error()),
1288                    ));
1289                }
1290                return;
1291            }
1292            TransactionType::ConnectRequest(relayed_addr, peer_addr, _) => {
1293                // Nothing is outstanding for the peer any more.
1294                if let Some(relay) = self.relays.get_mut(&relayed_addr) {
1295                    relay.connecting.remove(&peer_addr);
1296                }
1297                if !timed_out {
1298                    self.events.push_back(Event::ConnectError(
1299                        id,
1300                        peer_addr,
1301                        RequestError::Failed(failure.error()),
1302                    ));
1303                    return;
1304                }
1305            }
1306            TransactionType::CreatePermissionRequest(relayed_addr, peer_addr, _, _) => {
1307                if !timed_out {
1308                    // A permission the application asked for is not there; a refresh that
1309                    // failed this way leaves the permissions the time the server last
1310                    // granted, and they are asked for again.
1311                    if let Some(peer_addr) = peer_addr {
1312                        if let Some(relay) = self.relays.get_mut(&relayed_addr) {
1313                            relay.forget_unless_permitted(peer_addr.ip(), now);
1314                        }
1315                        self.events.push_back(Event::CreatePermissionError(
1316                            id,
1317                            RequestError::Failed(failure.error()),
1318                        ));
1319                    }
1320                    return;
1321                }
1322            }
1323            TransactionType::AllocateAttempt(_) | TransactionType::AllocateRequest(_) => {
1324                if !timed_out {
1325                    self.events.push_back(Event::AllocateError(
1326                        id,
1327                        RequestError::Failed(failure.error()),
1328                    ));
1329                    return;
1330                }
1331            }
1332            TransactionType::BindingRequest(_) => {
1333                if !timed_out {
1334                    self.events
1335                        .push_back(Event::BindingError(id, failure.error()));
1336                    return;
1337                }
1338            }
1339            TransactionType::OrphanRelease => return,
1340        }
1341        self.events.push_back(Event::TransactionTimeout(id));
1342    }
1343
1344    fn handle_channel_data(&mut self, now: Instant, data: &[u8]) -> Result<()> {
1345        let mut ch_data = ChannelData {
1346            raw: data.to_vec(),
1347            ..Default::default()
1348        };
1349        ch_data.decode()?;
1350
1351        // A channel is the binding of one allocation; it is accepted from the moment its
1352        // ChannelBind is sent (RFC 8656 §12).
1353        let (relay, addr) = self
1354            .relays
1355            .values_mut()
1356            .find_map(|relay| {
1357                let addr = relay.binding_mgr.find_by_number(ch_data.number.0)?.addr;
1358                Some((relay, addr))
1359            })
1360            .ok_or(Error::ErrChannelBindNotFound)?;
1361
1362        // The server relays only from addresses the client holds a permission for
1363        // (RFC 8656 §12.6).
1364        if !relay.expects_data_from(&addr.ip(), now) {
1365            debug!(
1366                "discarding ChannelData from {addr} (ch={}): no permission",
1367                ch_data.number.0
1368            );
1369            return Ok(());
1370        }
1371        if let Some(b) = relay.binding_mgr.get_by_number(ch_data.number.0) {
1372            b.used = true;
1373        }
1374
1375        trace!(
1376            "channel data received from {} (ch={})",
1377            addr, ch_data.number.0
1378        );
1379
1380        self.events.push_back(Event::DataIndicationOrChannelData(
1381            Some(ch_data.number),
1382            addr,
1383            BytesMut::from(&ch_data.data[..]),
1384        ));
1385
1386        Ok(())
1387    }
1388
1389    /// Borrows the allocation for `relayed_addr` so data can be sent or permissions created.
1390    ///
1391    /// # Errors
1392    ///
1393    /// Fails if this client has no allocation for that address — it was never allocated, or has
1394    /// already been closed.
1395    pub fn relay(&mut self, relayed_addr: SocketAddr) -> Result<Relay<'_>> {
1396        // An allocation is kept under its first relayed address and found by any address it
1397        // has now: either of the two of a dual allocation.
1398        let key = self
1399            .relays
1400            .iter()
1401            .find(|(_, relay)| relay.addrs.contains(&relayed_addr))
1402            .map(|(key, _)| *key)
1403            .ok_or(Error::ErrStreamNotExisted)?;
1404        Ok(Relay {
1405            relayed_addr: key,
1406            client: self,
1407        })
1408    }
1409
1410    /// The allocation kept under `key`, whatever relayed addresses it has now.
1411    fn relay_by_key(&mut self, key: RelayedAddr) -> Option<Relay<'_>> {
1412        self.relays.contains_key(&key).then_some(Relay {
1413            relayed_addr: key,
1414            client: self,
1415        })
1416    }
1417
1418    /// Whether this client is waiting on a response for transaction `id`.
1419    ///
1420    /// A STUN response belongs to whoever sent the matching request — [RFC 5389 §7.3.3] matches
1421    /// them by transaction ID, and nothing else identifies the owner. That is only a question
1422    /// worth asking when several STUN users share one socket, which is exactly the situation a
1423    /// host is in when it points a STUN gatherer and this client at the same server address: both
1424    /// see every response, and the four-tuple is identical for both, so addresses cannot say whose
1425    /// a response is.
1426    ///
1427    /// Such a host calls this to route a response, rather than guessing from the peer address and
1428    /// handing it to a client that will silently discard it — [`handle_read`](sansio::Protocol::handle_read)
1429    /// drops a response with no matching transaction, as it must.
1430    ///
1431    /// Applies to responses only. TURN ChannelData carries no transaction ID at all, and
1432    /// indications are not transaction-matched; both are routed by address.
1433    ///
1434    /// [RFC 5389 §7.3.3]: https://www.rfc-editor.org/rfc/rfc5389#section-7.3.3
1435    #[must_use]
1436    pub fn has_transaction(&self, id: &TransactionId) -> bool {
1437        self.tr_map.find(id).is_some()
1438    }
1439
1440    /// send_binding_request_to sends a new STUN request to the given transport address
1441    /// return key to find out corresponding Event either BindingResponse or BindingRequestTimeout
1442    pub fn send_binding_request_to(
1443        &mut self,
1444        now: Instant,
1445        to: SocketAddr,
1446    ) -> Result<TransactionId> {
1447        self.binding_request_with(now, to, Retry::default())
1448    }
1449
1450    /// Sends a Binding request to `to`, under a new transaction id, with `retry`'s state.
1451    fn binding_request_with(
1452        &mut self,
1453        now: Instant,
1454        to: SocketAddr,
1455        retry: Retry,
1456    ) -> Result<TransactionId> {
1457        let msg = {
1458            // RFC 8489 section 7: "When the FINGERPRINT extension is used, an agent includes
1459            // the FINGERPRINT attribute in messages it sends to another agent": the client
1460            // ends every other message with it, and this one shares their socket.
1461            let mut attrs: Vec<Box<dyn Setter + '_>> =
1462                vec![Box::new(TransactionId::new()), Box::new(BINDING_REQUEST)];
1463            if !self.software.text.is_empty() {
1464                attrs.push(Box::new(self.software.clone()));
1465            }
1466            attrs.push(Box::new(FINGERPRINT));
1467
1468            let mut msg = Message::new();
1469            msg.build(&attrs)?;
1470            msg
1471        };
1472
1473        debug!("client.SendBindingRequestTo call PerformTransaction 1");
1474        self.perform_transaction(now, &msg, to, TransactionType::BindingRequest(retry), None)
1475    }
1476
1477    /// send_binding_request sends a new STUN request to the STUN server
1478    /// return key to find out corresponding Event either BindingResponse or BindingRequestTimeout
1479    pub fn send_binding_request(&mut self, now: Instant) -> Result<TransactionId> {
1480        if let Some(stun_serv_addr) = &self.stun_serv_addr {
1481            self.send_binding_request_to(now, *stun_serv_addr)
1482        } else {
1483            Err(Error::ErrStunserverAddressNotSet)
1484        }
1485    }
1486
1487    // stun_server_addr return the STUN server address
1488    fn stun_server_addr(&self) -> Option<SocketAddr> {
1489        self.stun_serv_addr
1490    }
1491
1492    /* https://datatracker.ietf.org/doc/html/rfc8656#section-20
1493    TURN                                 TURN          Peer         Peer
1494    client                               server         A            B
1495      |                                    |            |            |
1496      |--- Allocate request -------------->|            |            |
1497      |    Transaction-Id=0xA56250D3F17ABE679422DE85    |            |
1498      |    SOFTWARE="Example client, version 1.03"      |            |
1499      |    LIFETIME=3600 (1 hour)          |            |            |
1500      |    REQUESTED-TRANSPORT=17 (UDP)    |            |            |
1501      |    DONT-FRAGMENT                   |            |            |
1502      |                                    |            |            |
1503      |<-- Allocate error response --------|            |            |
1504      |    Transaction-Id=0xA56250D3F17ABE679422DE85    |            |
1505      |    SOFTWARE="Example server, version 1.17"      |            |
1506      |    ERROR-CODE=401 (Unauthorized)   |            |            |
1507      |    REALM="example.com"             |            |            |
1508      |    NONCE="obMatJos2gAAAadl7W7PeDU4hKE72jda"     |            |
1509      |    PASSWORD-ALGORITHMS=MD5 and SHA256           |            |
1510      |                                    |            |            |
1511      |--- Allocate request -------------->|            |            |
1512      |    Transaction-Id=0xC271E932AD7446A32C234492    |            |
1513      |    SOFTWARE="Example client 1.03"  |            |            |
1514      |    LIFETIME=3600 (1 hour)          |            |            |
1515      |    REQUESTED-TRANSPORT=17 (UDP)    |            |            |
1516      |    DONT-FRAGMENT                   |            |            |
1517      |    USERNAME="George"               |            |            |
1518      |    REALM="example.com"             |            |            |
1519      |    NONCE="obMatJos2gAAAadl7W7PeDU4hKE72jda"     |            |
1520      |    PASSWORD-ALGORITHMS=MD5 and SHA256           |            |
1521      |    PASSWORD-ALGORITHM=SHA256       |            |            |
1522      |    MESSAGE-INTEGRITY=...           |            |            |
1523      |    MESSAGE-INTEGRITY-SHA256=...    |            |            |
1524      |                                    |            |            |
1525      |<-- Allocate success response ------|            |            |
1526      |    Transaction-Id=0xC271E932AD7446A32C234492    |            |
1527      |    SOFTWARE="Example server, version 1.17"      |            |
1528      |    LIFETIME=1200 (20 minutes)      |            |            |
1529      |    XOR-RELAYED-ADDRESS=192.0.2.15:50000         |            |
1530      |    XOR-MAPPED-ADDRESS=192.0.2.1:7000            |            |
1531      |    MESSAGE-INTEGRITY-SHA256=...    |            |            |
1532    */
1533    /// Replaces the long-term credential used to sign subsequent requests, **keeping any
1534    /// existing allocation**.
1535    ///
1536    /// This is for a new **password** for the same username. An allocation belongs to the
1537    /// username that created it: [RFC 8656 §5] has the server answer a request for it made
1538    /// under another username with **441 (Wrong Credentials)**. Giving up the allocation and
1539    /// allocating again is no way round a rotation either, since the server still holds the
1540    /// allocation for the 5-tuple and answers the new Allocate with 437 (Allocation Mismatch).
1541    /// So with a new password the existing allocation is re-signed, and its permissions and
1542    /// channel bindings survive.
1543    ///
1544    /// A new username takes effect for the next [`allocate`](Self::allocate) only: RFC 8656
1545    /// section 5 has every request about an allocation use the username that created it, so
1546    /// live allocations keep signing with theirs (and their password). To move to the new
1547    /// username, [`Relay::close`] an allocation, wait for [`Event::AllocationReleased`], and
1548    /// allocate again.
1549    ///
1550    /// The realm is *not* re-negotiated. It was learned from the server's 401 during the
1551    /// first `Allocate`, and a credential rotation keeps the same server, so it still
1552    /// applies. Follow this with [`Self::refresh_allocations`] so the server sees the new
1553    /// credential before the allocation would otherwise expire.
1554    ///
1555    /// [RFC 8656 §5]: https://datatracker.ietf.org/doc/html/rfc8656#section-5
1556    pub fn update_credentials(&mut self, username: String, password: String) -> Result<()> {
1557        // RFC 8656 section 5: an allocation's requests stay under the username that created
1558        // it; only a new password for that username re-keys it.
1559        let same_username = username == self.login.username;
1560        let login = Arc::new(Login {
1561            username,
1562            password,
1563            password_algorithms: self.login.password_algorithms.clone(),
1564            username_anonymity_required: self.login.username_anonymity_required,
1565        });
1566        if !same_username {
1567            self.login = login;
1568            return Ok(());
1569        }
1570
1571        // Each allocation carries the credential it will sign its own Refresh /
1572        // CreatePermission / ChannelBind with, so they have to be re-keyed too — otherwise
1573        // the next refresh would still present the retired credential. The realm, the nonce
1574        // and the password algorithm stay what the server last asked for. An allocation the
1575        // server gave without a credential stays unsigned until the server asks for one.
1576        let mut rekeyed = Vec::with_capacity(self.relays.len());
1577        for (key, relay) in &self.relays {
1578            rekeyed.push((
1579                *key,
1580                relay
1581                    .credential
1582                    .with_login(login.clone(), self.crypto_provider.crypto())?,
1583            ));
1584        }
1585        for (key, credential) in rekeyed {
1586            if let Some(relay) = self.relays.get_mut(&key) {
1587                relay.credential = Arc::new(credential);
1588            }
1589        }
1590        self.login = login;
1591
1592        Ok(())
1593    }
1594
1595    /// Refreshes every live allocation, re-signing each with the current credential.
1596    ///
1597    /// Each allocation is refreshed with its own current lifetime, so this extends rather
1598    /// than changes it. Intended to follow [`update_credentials`](Self::update_credentials).
1599    pub fn refresh_allocations(&mut self, now: Instant) -> Result<()> {
1600        let relays: Vec<(RelayedAddr, Duration)> = self
1601            .relays
1602            .iter()
1603            .filter(|(_, relay)| !relay.releasing)
1604            .map(|(addr, relay)| (*addr, relay.lifetime))
1605            .collect();
1606
1607        for (relayed_addr, lifetime) in relays {
1608            if let Some(mut relay) = self.relay_by_key(relayed_addr) {
1609                relay.refresh_allocation(now, lifetime)?;
1610            }
1611        }
1612
1613        Ok(())
1614    }
1615
1616    /// Builds a request about `relay`: `attrs`, then the allocation's credential when it has
1617    /// one, then FINGERPRINT.
1618    pub(crate) fn build_request(
1619        &self,
1620        method: Method,
1621        attrs: Vec<Box<dyn Setter>>,
1622        relay: &RelayState,
1623    ) -> Result<Message> {
1624        self.build_request_with(method, attrs, &relay.credential)
1625    }
1626
1627    /// Builds a request made with `credential`; without one until the server asked for it.
1628    pub(crate) fn build_request_with(
1629        &self,
1630        method: Method,
1631        attrs: Vec<Box<dyn Setter>>,
1632        credential: &Credential,
1633    ) -> Result<Message> {
1634        self.build_request_as(TransactionId::new(), method, attrs, credential)
1635    }
1636
1637    /// Builds the request `id`: `attrs`, SOFTWARE when the client has one (RFC 8656 §5: in
1638    /// every Allocate and Refresh, and allowed in any other request), what the long-term
1639    /// credential mechanism adds once the server asked for the credential (RFC 8489 §9.2.3,
1640    /// §9.2.5: USERNAME or USERHASH, REALM, NONCE, PASSWORD-ALGORITHMS and
1641    /// PASSWORD-ALGORITHM when the server offered algorithms, and MESSAGE-INTEGRITY-SHA256
1642    /// then, MESSAGE-INTEGRITY otherwise), and FINGERPRINT.
1643    pub(crate) fn build_request_as(
1644        &self,
1645        id: TransactionId,
1646        method: Method,
1647        attrs: Vec<Box<dyn Setter>>,
1648        credential: &Credential,
1649    ) -> Result<Message> {
1650        let mut setters: Vec<Box<dyn Setter + '_>> = vec![
1651            Box::new(id),
1652            Box::new(MessageType::new(method, CLASS_REQUEST)),
1653        ];
1654        setters.extend(attrs.into_iter().map(|a| a as Box<dyn Setter + '_>));
1655        if !self.software.text.is_empty() {
1656            setters.push(Box::new(self.software.clone()));
1657        }
1658        if let Some(authentication) = credential.setter(self.crypto_provider.crypto()) {
1659            setters.push(authentication);
1660        }
1661        setters.push(Box::new(FINGERPRINT));
1662
1663        let mut msg = Message::new();
1664        msg.build(&setters)?;
1665        Ok(msg)
1666    }
1667
1668    /// Deletes the allocation the server holds for this client's 5-tuple, with a Refresh of
1669    /// LIFETIME 0 (RFC 8656 §8), when the client keeps no copy of it. Nothing is reported.
1670    pub(crate) fn release_orphan(
1671        &mut self,
1672        now: Instant,
1673        credential: &Arc<Credential>,
1674    ) -> Result<()> {
1675        let msg = self.build_request_with(
1676            METHOD_REFRESH,
1677            vec![Box::new(Lifetime(Duration::ZERO))],
1678            credential,
1679        )?;
1680        let to = self.turn_server_addr_or_err()?;
1681        self.perform_transaction(
1682            now,
1683            &msg,
1684            to,
1685            TransactionType::OrphanRelease,
1686            Some(credential.clone()),
1687        )?;
1688        Ok(())
1689    }
1690
1691    /// Points the client at the alternate server of a 300 (Try Alternate), for an
1692    /// application that chooses to follow the redirection (RFC 8489 §10, RFC 8656 §7.4). The
1693    /// client never follows one by itself: the application owns the socket and the choice of
1694    /// server.
1695    ///
1696    /// `redirect` comes from [`ErrorResponse::try_alternate`], which is there only for a 300
1697    /// that was authenticated with the allocation's credential; RFC 8489 §14.8 has a client
1698    /// validate the response before it redirects itself. (An application that trusts the
1699    /// address of an unauthenticated 300, [`ErrorResponse::alternate_server`], makes the
1700    /// `TryAlternate` itself.) The server of the address family the client reached the old
1701    /// one over is taken, and becomes [`Client::turn_server_addr`]. The application then
1702    /// calls [`Client::allocate`] again: the request goes to the alternate server over the
1703    /// same transport protocol and with the same credentials. Over TLS or DTLS the
1704    /// application checks the new server's certificate against
1705    /// [`TryAlternate::domain`] when it is there, and against the name it used for the old
1706    /// server when it is not.
1707    ///
1708    /// # Errors
1709    ///
1710    /// Fails, and leaves the server as it is, when an Allocate was already sent to the
1711    /// alternate server within the last five minutes: the redirection is a loop and RFC 8489
1712    /// §10 has the client ignore it and take the transaction as failed. Fails the same way when
1713    /// the redirection names no usable server ([`stun::alternate::is_usable_alternate`]: port
1714    /// 0, an unspecified, multicast, broadcast or IPv4-mapped address, or a loopback address
1715    /// while the server is not on one). Fails as well while
1716    /// the client holds an allocation (its server cannot change), or when no TURN server is
1717    /// configured.
1718    pub fn follow_alternate(
1719        &mut self,
1720        now: Instant,
1721        redirect: &TryAlternate,
1722    ) -> Result<SocketAddr> {
1723        let current = self.turn_server_addr_or_err()?;
1724        if !self.relays.is_empty() {
1725            return Err(Error::Other(
1726                "the TURN server cannot change while the client holds an allocation".to_owned(),
1727            ));
1728        }
1729        let server = redirect.server_for(current.ip()).ok_or_else(|| {
1730            Error::Other(format!(
1731                "no usable alternate server in {:?} (RFC 8489 section 14.15)",
1732                redirect.servers
1733            ))
1734        })?;
1735        if !self.redirects.follow(server, now) {
1736            return Err(Error::Other(format!(
1737                "redirection loop: an Allocate was sent to {server} within the last five \
1738                 minutes (RFC 8489 section 10)"
1739            )));
1740        }
1741        debug!("TURN server {current} redirects to {server}");
1742        self.turn_serv_addr = Some(server);
1743        Ok(server)
1744    }
1745
1746    /// The path MTU to the server, when the application knows it (RFC 8489 Section 6.1): a
1747    /// request over UDP larger than it allows is refused with `ErrPacketTooBig`. `None` (the
1748    /// default): unknown, 576 bytes for IPv4 and 1280 for IPv6.
1749    pub fn set_path_mtu(&mut self, mtu: Option<usize>) {
1750        self.path_mtu = mtu;
1751    }
1752
1753    /// Returns the TURN server address, if configured.
1754    pub fn turn_server_addr(&self) -> Option<SocketAddr> {
1755        self.turn_serv_addr
1756    }
1757
1758    /// Returns the TURN server address or an error if not configured.
1759    fn turn_server_addr_or_err(&self) -> Result<SocketAddr> {
1760        self.turn_serv_addr.ok_or(Error::ErrNilTurnSocket)
1761    }
1762
1763    /// Returns the local address this client is bound to.
1764    pub fn local_addr(&self) -> SocketAddr {
1765        self.local_addr
1766    }
1767
1768    /// WriteTo sends data to the specified destination using the base socket.
1769    fn write_to(&mut self, now: Instant, data: &[u8], remote: SocketAddr) {
1770        self.transmits.push_back(TransportMessage {
1771            now,
1772            transport: TransportContext {
1773                local_addr: self.local_addr,
1774                peer_addr: remote,
1775                transport_protocol: self.transport_protocol,
1776                ecn: None,
1777            },
1778            message: BytesMut::from(data),
1779        });
1780    }
1781
1782    // PerformTransaction performs STUN transaction
1783    fn perform_transaction(
1784        &mut self,
1785        now: Instant,
1786        msg: &Message,
1787        to: SocketAddr,
1788        transaction_type: TransactionType,
1789        credential: Option<Arc<Credential>>,
1790    ) -> Result<TransactionId> {
1791        // RFC 8489 Section 6.1: outside MTU probing, a request over UDP does not exceed the
1792        // path MTU (configured with `set_path_mtu`, else the RFC's 576 / 1280 bytes). Data
1793        // indications are not requests and are left to the path.
1794        if self.transport_protocol == TransportProtocol::UDP {
1795            let (unknown, overhead) = if to.is_ipv4() {
1796                (UNKNOWN_PATH_MTU_V4, IP_UDP_OVERHEAD_V4)
1797            } else {
1798                (UNKNOWN_PATH_MTU_V6, IP_UDP_OVERHEAD_V6)
1799            };
1800            let limit = self.path_mtu.unwrap_or(unknown).saturating_sub(overhead);
1801            if msg.raw.len() > limit {
1802                debug!(
1803                    "{} request of {} bytes not sent: the path takes {limit}",
1804                    msg.typ,
1805                    msg.raw.len()
1806                );
1807                return Err(Error::ErrPacketTooBig);
1808            }
1809        }
1810        trace!(
1811            "start {} transaction {:?} to {}",
1812            msg.typ, msg.transaction_id, to
1813        );
1814        self.tr_map.start(
1815            now,
1816            TransactionConfig {
1817                transaction_id: msg.transaction_id,
1818                method: msg.typ.method,
1819                transaction_type,
1820                raw: BytesMut::from(&msg.raw[..]),
1821                local_addr: self.local_addr,
1822                peer_addr: to,
1823                transport_protocol: self.transport_protocol,
1824                credential,
1825            },
1826        );
1827        // In the order it was asked for, with whatever else the client sends.
1828        while let Some(transmit) = self.tr_map.poll_transmit() {
1829            self.transmits.push_back(transmit);
1830        }
1831
1832        Ok(msg.transaction_id)
1833    }
1834}