Skip to main content

rtci_stun/
alternate.rs

1//! The client side of the ALTERNATE-SERVER mechanism (RFC 8489 section 10): reading a 300
2//! (Try Alternate) error response, and refusing a redirection loop.
3//!
4//! This crate performs no I/O, so it does not dial the alternate server. It gives the caller
5//! what the redirection says ([`TryAlternate`](crate::alternate::TryAlternate)) and the rule that stops a loop
6//! ([`RedirectGuard`](crate::alternate::RedirectGuard)); the caller sends the same request, with the same credentials, to the
7//! new address over the same transport protocol. Over (D)TLS the caller validates the
8//! server's certificate against [`TryAlternate::domain`](crate::alternate::TryAlternate::domain) when it is there, and against the
9//! original domain when it is not.
10
11#[cfg(test)]
12mod alternate_test;
13
14use crate::addr::{AlternateServer, MappedAddress};
15use crate::attributes::*;
16use crate::error_code::{CODE_TRY_ALTERNATE, ErrorCodeAttribute};
17use crate::message::*;
18use crate::textattrs::TextAttribute;
19use crate::validated::ValidatedMessage;
20use shared::error::*;
21
22use std::net::{IpAddr, SocketAddr};
23use std::time::{Duration, Instant};
24
25/// How long a server counts as already tried (RFC 8489 section 10: "within the last five
26/// minutes").
27pub const REDIRECT_LOOP_WINDOW: Duration = Duration::from_secs(300);
28
29/// What a 300 (Try Alternate) error response says.
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct TryAlternate {
32    /// The ALTERNATE-SERVER attributes, in the order the server sent them: the first has the
33    /// address family the request was sent to, a second one, if any, the other family.
34    pub servers: Vec<SocketAddr>,
35    /// ALTERNATE-DOMAIN: the name the alternate server's certificate is checked against when
36    /// the transport is TLS or DTLS. `None`: the domain of the original request applies.
37    pub domain: Option<String>,
38}
39
40impl TryAlternate {
41    /// Reads the redirection out of `response`.
42    ///
43    /// `Ok(None)` when the response is not a 300 error response, when it has no
44    /// ALTERNATE-SERVER, or when it is not authenticated: RFC 8489 section 14.8 lets a client
45    /// follow a 300 only after validating its integrity attribute (a forged one would point
46    /// the client's requests, credentials included, at a victim), and a
47    /// [`ValidatedMessage`] shows only the attributes that integrity covers. The transaction
48    /// has failed in each of those cases, as with any other error response.
49    ///
50    /// # Errors
51    ///
52    /// Fails when an ALTERNATE-SERVER or the ALTERNATE-DOMAIN is malformed.
53    pub fn from_response(response: &ValidatedMessage) -> Result<Option<Self>> {
54        if response.typ.class != CLASS_ERROR_RESPONSE || !response.is_authenticated() {
55            return Ok(None);
56        }
57        let mut code = ErrorCodeAttribute::default();
58        if code.get_from(response).is_err() || code.code != CODE_TRY_ALTERNATE {
59            return Ok(None);
60        }
61        let mut servers = vec![];
62        for attribute in &response.attributes.0 {
63            if attribute.typ != ATTR_ALTERNATE_SERVER {
64                continue;
65            }
66            // Each ALTERNATE-SERVER is decoded on its own: `Message::get` finds the first.
67            let mut one = Message::new();
68            one.write_header();
69            one.add(ATTR_ALTERNATE_SERVER, &attribute.value);
70            let mut server = MappedAddress::default();
71            server.get_from_as(&one, ATTR_ALTERNATE_SERVER)?;
72            servers.push(SocketAddr::new(server.ip, server.port));
73        }
74        if servers.is_empty() {
75            return Ok(None);
76        }
77        let domain = match TextAttribute::get_from_as(response, ATTR_ALTERNATE_DOMAIN) {
78            Ok(domain) => Some(domain.text),
79            Err(Error::ErrAttributeNotFound) => None,
80            Err(error) => return Err(error),
81        };
82        Ok(Some(Self { servers, domain }))
83    }
84
85    /// The alternate server of the address family of `original`, the server the request was
86    /// sent to; the first alternate of any family when there is none. Only an alternate that
87    /// [`is_usable_alternate`] is taken: `None` when the response names no other.
88    #[must_use]
89    pub fn server_for(&self, original: IpAddr) -> Option<SocketAddr> {
90        let mut usable = self
91            .servers
92            .iter()
93            .filter(|s| is_usable_alternate(**s, original));
94        let first = usable.clone().next();
95        usable
96            .find(|s| s.is_ipv4() == original.is_ipv4())
97            .or(first)
98            .copied()
99    }
100
101    /// The ALTERNATE-SERVER attributes of this redirection, for a server (or a test) that
102    /// builds the 300 response.
103    #[must_use]
104    pub fn server_attributes(&self) -> Vec<AlternateServer> {
105        self.servers
106            .iter()
107            .map(|s| AlternateServer {
108                ip: s.ip(),
109                port: s.port(),
110            })
111            .collect()
112    }
113}
114
115/// Whether `server`, read from an ALTERNATE-SERVER, can name "a different STUN server that the
116/// STUN client should try" (RFC 8489 section 14.15) for a client that reached the redirecting
117/// server at `original`.
118///
119/// Not when it is no destination at all: port 0, the unspecified address (or any of
120/// 0.0.0.0/8, "this network"), a multicast address, the IPv4 broadcast address, or an
121/// IPv4-mapped IPv6 address (an IPv4 address in the attribute's IPv6 family, which RFC 8489
122/// section 14.1 does not provide for). Not a loopback address either, unless `original` is
123/// one too: a server elsewhere cannot run on this host, and following it would send the
124/// client's requests, with its credential, to whatever listens locally.
125#[must_use]
126pub fn is_usable_alternate(server: SocketAddr, original: IpAddr) -> bool {
127    if server.port() == 0 {
128        return false;
129    }
130    let ip = server.ip();
131    let no_destination = match ip {
132        IpAddr::V4(v4) => v4.octets()[0] == 0 || v4.is_multicast() || v4.is_broadcast(),
133        IpAddr::V6(v6) => v6.is_unspecified() || v6.is_multicast() || v6.to_ipv4_mapped().is_some(),
134    };
135    !no_destination && (!ip.is_loopback() || original.is_loopback())
136}
137
138/// Remembers which servers a request went to, so that a redirection back to one of them
139/// within five minutes is refused (RFC 8489 section 10: the client "MUST ignore the
140/// redirection and consider the transaction to have failed").
141///
142/// One guard per request that may be redirected. Time is the caller's.
143#[derive(Debug, Clone, Default)]
144pub struct RedirectGuard {
145    sent: Vec<(SocketAddr, Instant)>,
146}
147
148impl RedirectGuard {
149    /// A guard that has seen no server.
150    #[must_use]
151    pub fn new() -> Self {
152        Self::default()
153    }
154
155    /// Records that the request was sent to `server` at `now`: the original server first,
156    /// then each alternate that is followed.
157    pub fn sent_to(&mut self, server: SocketAddr, now: Instant) {
158        self.forget_before(now);
159        self.sent.retain(|(s, _)| *s != server);
160        self.sent.push((server, now));
161    }
162
163    /// Whether a redirection to `server` at `now` may be followed: not when the request was
164    /// sent there within the last five minutes.
165    #[must_use]
166    pub fn allows(&self, server: SocketAddr, now: Instant) -> bool {
167        !self.sent.iter().any(|(s, at)| {
168            *s == server && now.saturating_duration_since(*at) < REDIRECT_LOOP_WINDOW
169        })
170    }
171
172    /// Follows a redirection if the rule allows it: records `server` and returns `true`, or
173    /// returns `false` when it would be a loop.
174    pub fn follow(&mut self, server: SocketAddr, now: Instant) -> bool {
175        if !self.allows(server, now) {
176            return false;
177        }
178        self.sent_to(server, now);
179        true
180    }
181
182    fn forget_before(&mut self, now: Instant) {
183        self.sent
184            .retain(|(_, at)| now.saturating_duration_since(*at) < REDIRECT_LOOP_WINDOW);
185    }
186}