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.
87 #[must_use]
88 pub fn server_for(&self, original: IpAddr) -> Option<SocketAddr> {
89 self.servers
90 .iter()
91 .find(|s| s.is_ipv4() == original.is_ipv4())
92 .or(self.servers.first())
93 .copied()
94 }
95
96 /// The ALTERNATE-SERVER attributes of this redirection, for a server (or a test) that
97 /// builds the 300 response.
98 #[must_use]
99 pub fn server_attributes(&self) -> Vec<AlternateServer> {
100 self.servers
101 .iter()
102 .map(|s| AlternateServer {
103 ip: s.ip(),
104 port: s.port(),
105 })
106 .collect()
107 }
108}
109
110/// Remembers which servers a request went to, so that a redirection back to one of them
111/// within five minutes is refused (RFC 8489 section 10: the client "MUST ignore the
112/// redirection and consider the transaction to have failed").
113///
114/// One guard per request that may be redirected. Time is the caller's.
115#[derive(Debug, Clone, Default)]
116pub struct RedirectGuard {
117 sent: Vec<(SocketAddr, Instant)>,
118}
119
120impl RedirectGuard {
121 /// A guard that has seen no server.
122 #[must_use]
123 pub fn new() -> Self {
124 Self::default()
125 }
126
127 /// Records that the request was sent to `server` at `now`: the original server first,
128 /// then each alternate that is followed.
129 pub fn sent_to(&mut self, server: SocketAddr, now: Instant) {
130 self.forget_before(now);
131 self.sent.retain(|(s, _)| *s != server);
132 self.sent.push((server, now));
133 }
134
135 /// Whether a redirection to `server` at `now` may be followed: not when the request was
136 /// sent there within the last five minutes.
137 #[must_use]
138 pub fn allows(&self, server: SocketAddr, now: Instant) -> bool {
139 !self.sent.iter().any(|(s, at)| {
140 *s == server && now.saturating_duration_since(*at) < REDIRECT_LOOP_WINDOW
141 })
142 }
143
144 /// Follows a redirection if the rule allows it: records `server` and returns `true`, or
145 /// returns `false` when it would be a loop.
146 pub fn follow(&mut self, server: SocketAddr, now: Instant) -> bool {
147 if !self.allows(server, now) {
148 return false;
149 }
150 self.sent_to(server, now);
151 true
152 }
153
154 fn forget_before(&mut self, now: Instant) {
155 self.sent
156 .retain(|(_, at)| now.saturating_duration_since(*at) < REDIRECT_LOOP_WINDOW);
157 }
158}