rtci_turn/client/allocation.rs
1//! Allocate: what the request asks for, the exchange that authenticates it, and what the
2//! client takes from the success response (RFC 8656 §7).
3use std::net::{IpAddr, SocketAddr};
4use std::ops::Add;
5use std::time::{Duration, Instant};
6
7use log::debug;
8use stun::attributes::*;
9use stun::error_code::*;
10use stun::long_term::ChallengeError;
11use stun::message::*;
12use stun::xoraddr::XorMappedAddress;
13
14use super::credential::Credential;
15use super::relay::RelayState;
16use super::transaction::TransactionType;
17use super::{Client, Event, RelayedAddr, RequestError, Response};
18use crate::proto::addfamily::AdditionalAddressFamily;
19use crate::proto::addrerror::AddressErrorCode;
20use crate::proto::dontfrag::DontFragmentAttr;
21use crate::proto::evenport::EvenPort;
22use crate::proto::lifetime::Lifetime;
23use crate::proto::reqfamily::{
24 REQUESTED_FAMILY_IPV4, REQUESTED_FAMILY_IPV6, RequestedAddressFamily,
25};
26use crate::proto::reqtrans::RequestedTransport;
27use crate::proto::rsrvtoken::ReservationToken;
28use crate::proto::{PROTO_TCP, PROTO_UDP};
29use shared::TransportProtocol;
30use shared::error::{Error, Result};
31use std::sync::Arc;
32
33/// What an allocation relays to and from peers: the REQUESTED-TRANSPORT of its Allocate.
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
35#[non_exhaustive]
36pub enum RelayTransport {
37 /// UDP datagrams (RFC 8656): permissions, Send and Data indications, channels.
38 #[default]
39 Udp,
40 /// TCP connections (RFC 6062): the client connects to peers with
41 /// [`Relay::connect`](super::relay::Relay::connect) and accepts their connections from
42 /// [`Event::ConnectionAttempt`], each over a
43 /// [`DataConnection`](super::data_connection::DataConnection) of its own. The client must
44 /// reach the server over TCP or TLS.
45 Tcp,
46}
47
48/// How long an address family the server had no capacity for is not asked for again
49/// (RFC 8656 §7.3: "at least 1 minute").
50const INSUFFICIENT_CAPACITY_WAIT: Duration = Duration::from_secs(60);
51
52/// What an Allocate request asks for beyond a UDP relayed address (RFC 8656 §7.1).
53///
54/// The default asks for nothing more: one relayed address, IPv4 unless the server decides
55/// otherwise, for the server's default lifetime.
56///
57/// The RFC forbids some combinations, and [`Client::allocate_with`] refuses them before
58/// anything is sent: `address_family` with `additional_ipv6` or `reservation_token`;
59/// `additional_ipv6` with `reservation_token` or with an `even_port` that reserves the next
60/// port; `reservation_token` with `even_port`.
61///
62/// A TCP allocation ([`RelayTransport::Tcp`], RFC 6062 §4.1) takes none of `dont_fragment`,
63/// `even_port` and `reservation_token`, and cannot be asked for over UDP.
64#[derive(Debug, Clone, Default, PartialEq, Eq)]
65pub struct AllocateOptions {
66 /// REQUESTED-TRANSPORT: what the allocation relays, UDP datagrams by default.
67 pub transport: RelayTransport,
68 /// REQUESTED-ADDRESS-FAMILY: the family of the one relayed address, for example
69 /// [`REQUESTED_FAMILY_IPV6`] for an IPv6 relayed address.
70 pub address_family: Option<RequestedAddressFamily>,
71 /// ADDITIONAL-ADDRESS-FAMILY: an IPv6 relayed address beside the IPv4 one. The server
72 /// may give only one of the two; [`Relay::address_error`](super::relay::Relay) then says
73 /// why.
74 pub additional_ipv6: bool,
75 /// LIFETIME: how long the allocation should last without a refresh. A hint; the server
76 /// answers with what it grants, which the client then goes by.
77 pub lifetime: Option<Duration>,
78 /// DONT-FRAGMENT, to find out whether the server supports it and so whether
79 /// [`Relay::send_to_dont_fragment`](super::relay::Relay::send_to_dont_fragment) can be
80 /// used. A server that does not know the attribute answers 420; the client then makes
81 /// the request again without it.
82 pub dont_fragment: bool,
83 /// EVEN-PORT: an even relayed port, and with `reserve_port` the next port held for a
84 /// later allocation, which the response's RESERVATION-TOKEN names.
85 pub even_port: Option<EvenPort>,
86 /// RESERVATION-TOKEN: use the port a previous allocation reserved.
87 pub reservation_token: Option<ReservationToken>,
88}
89
90impl AllocateOptions {
91 /// Whether RFC 8656 §7.1 lets these go into one request.
92 fn check(&self) -> Result<()> {
93 let refuse = |why: &str| Err(Error::Other(format!("Allocate options: {why}")));
94 if let Some(family) = self.address_family
95 && family != REQUESTED_FAMILY_IPV4
96 && family != REQUESTED_FAMILY_IPV6
97 {
98 return Err(Error::ErrInvalidRequestedFamilyValue);
99 }
100 if self.address_family.is_some() && self.additional_ipv6 {
101 return refuse(
102 "REQUESTED-ADDRESS-FAMILY and ADDITIONAL-ADDRESS-FAMILY exclude each other",
103 );
104 }
105 if self.address_family.is_some() && self.reservation_token.is_some() {
106 return refuse("REQUESTED-ADDRESS-FAMILY cannot go with RESERVATION-TOKEN");
107 }
108 if self.additional_ipv6 && self.reservation_token.is_some() {
109 return refuse("ADDITIONAL-ADDRESS-FAMILY cannot go with RESERVATION-TOKEN");
110 }
111 if self.additional_ipv6 && self.even_port.is_some_and(|even| even.reserve_port) {
112 return refuse("ADDITIONAL-ADDRESS-FAMILY cannot go with EVEN-PORT reserving a port");
113 }
114 if self.reservation_token.is_some() && self.even_port.is_some() {
115 return refuse("EVEN-PORT is left out with RESERVATION-TOKEN");
116 }
117 // RFC 6062 §4.1: these are UDP's and never go into the Allocate of a TCP allocation.
118 if self.transport == RelayTransport::Tcp
119 && (self.dont_fragment || self.even_port.is_some() || self.reservation_token.is_some())
120 {
121 return refuse(
122 "a TCP allocation takes no DONT-FRAGMENT, EVEN-PORT or RESERVATION-TOKEN",
123 );
124 }
125 Ok(())
126 }
127
128 /// The address family a refusal of this request is about: the one it asked for, IPv6 for
129 /// the additional address, IPv4 when it named none. `None` with a reservation token,
130 /// which fixes the address.
131 fn refused_family(&self) -> Option<RequestedAddressFamily> {
132 if self.reservation_token.is_some() {
133 None
134 } else if self.additional_ipv6 {
135 Some(REQUESTED_FAMILY_IPV6)
136 } else {
137 Some(self.address_family.unwrap_or(REQUESTED_FAMILY_IPV4))
138 }
139 }
140
141 /// Whether the server may answer this request with a relayed address `addr`.
142 fn expects(&self, addr: &SocketAddr) -> bool {
143 if self.reservation_token.is_some() || self.additional_ipv6 {
144 return true;
145 }
146 let ipv6 = self.address_family == Some(REQUESTED_FAMILY_IPV6);
147 addr.is_ipv6() == ipv6
148 }
149}
150
151/// An Allocate under way: what it asks for and how far its exchange has come.
152pub(crate) struct AllocateState {
153 /// The id [`Client::allocate`] handed to its caller, which everything said about the
154 /// allocation names.
155 pub(crate) report_id: TransactionId,
156 pub(crate) options: AllocateOptions,
157 /// The credential the request is made with: none until the server asked for it with a
158 /// 401 (RFC 8489 §9.2.3.1).
159 pub(crate) credential: Arc<Credential>,
160 /// How many times the request was sent again after a 401 (Unauthenticated).
161 unauthenticated_retries: u8,
162 /// Whether the request was already sent again after a 438 (Stale Nonce).
163 stale_nonce_retried: bool,
164 /// How many times the request was sent again after a server error (RFC 8489 §6.3.4).
165 pub(crate) server_errors: u32,
166 /// The request carries a credential cached from an earlier allocation on the server
167 /// (RFC 8489 §9.2.3.2, [`Client::use_cached_credential`]), not one this request's own 401
168 /// asked for.
169 pub(crate) cached: bool,
170}
171
172/// Most 401 responses one Allocate is sent again after: the one that asks for the
173/// credential, and one that names another realm for it. RFC 8489 §9.2.5 forbids the retry
174/// that changes nothing; this bounds the ones that do.
175const MAX_UNAUTHENTICATED_RETRIES: u8 = 2;
176
177#[cfg(test)]
178impl AllocateState {
179 /// A default Allocate that has reached its authenticated request, for tests that hand
180 /// the client a response directly.
181 pub(crate) fn authenticated() -> Self {
182 Self {
183 report_id: TransactionId::new(),
184 options: AllocateOptions::default(),
185 credential: Credential::established(),
186 unauthenticated_retries: 1,
187 stale_nonce_retried: false,
188 server_errors: 0,
189 cached: false,
190 }
191 }
192}
193
194/// Why an address family is not asked for.
195#[derive(Clone, Copy)]
196pub(crate) enum FamilyBlock {
197 /// The server does not support it (440).
198 Unsupported,
199 /// The server had no capacity for it (508): not before this instant.
200 Until(Instant),
201}
202
203fn family_index(family: RequestedAddressFamily) -> usize {
204 usize::from(family == REQUESTED_FAMILY_IPV6)
205}
206
207/// Whether `addr`, read from an XOR-RELAYED-ADDRESS or XOR-MAPPED-ADDRESS, is a transport
208/// address a datagram can be sent to: not port 0, not the unspecified address, not a multicast
209/// address, not the IPv4 broadcast address. A relayed address is where peers send (RFC 8656
210/// §7.3); a mapped one is a server-reflexive candidate for ICE.
211pub(super) fn is_transport_address(addr: &SocketAddr) -> bool {
212 let ip = addr.ip();
213 let broadcast = matches!(ip, IpAddr::V4(v4) if v4.is_broadcast());
214 addr.port() != 0 && !ip.is_unspecified() && !ip.is_multicast() && !broadcast
215}
216
217/// Every address `m` carries in attributes of type `t`, XOR-decoded.
218fn xor_addresses(m: &Message, t: AttrType) -> Result<Vec<SocketAddr>> {
219 let mut out = vec![];
220 for attr in m.attributes.0.iter().filter(|a| a.typ == t) {
221 let mut one = Message::new();
222 one.transaction_id = m.transaction_id;
223 one.add(attr.typ, &attr.value);
224 let mut addr = XorMappedAddress::default();
225 addr.get_from_as(&one, t)?;
226 out.push(SocketAddr::new(addr.ip, addr.port));
227 }
228 Ok(out)
229}
230
231impl Client {
232 /// Sends an Allocate request for a UDP relayed address to the TURN server.
233 ///
234 /// Returns the id that [`Event::AllocateResponse`], [`Event::AllocateError`] or
235 /// [`Event::TransactionTimeout`] will name.
236 pub fn allocate(&mut self, now: Instant) -> Result<TransactionId> {
237 self.allocate_with(now, AllocateOptions::default())
238 }
239
240 /// Sends an Allocate request with `options` (RFC 8656 §7.1): an address family, a second
241 /// (IPv6) address, a lifetime, DONT-FRAGMENT, an even port, a reserved port.
242 ///
243 /// # Errors
244 ///
245 /// Fails, with nothing sent, if the RFC forbids the combination of options (see
246 /// [`AllocateOptions`]), or if the server has refused the address family and may not be
247 /// asked again: for good after a 440 (Address Family not Supported), for a minute after
248 /// it had no capacity for one of two families, and after it answered with an address of
249 /// a family that was not asked for (RFC 8656 §7.3, §7.4). An application that believes
250 /// the cause is gone calls [`Client::clear_allocate_restrictions`].
251 pub fn allocate_with(
252 &mut self,
253 now: Instant,
254 options: AllocateOptions,
255 ) -> Result<TransactionId> {
256 options.check()?;
257 // RFC 6062 §4.1: a TCP allocation cannot be had over a UDP association with the
258 // server.
259 if options.transport == RelayTransport::Tcp
260 && self.transport_protocol == TransportProtocol::UDP
261 {
262 return Err(Error::Other(
263 "a TCP allocation is asked for over TCP or TLS to the server, never over UDP"
264 .to_owned(),
265 ));
266 }
267 if self.family_mismatch {
268 return Err(Error::Other(
269 "the server answered an Allocate with an address family that was not asked for"
270 .to_owned(),
271 ));
272 }
273 if let Some(family) = options.refused_family() {
274 let mut families = vec![family];
275 if options.additional_ipv6 {
276 families.push(REQUESTED_FAMILY_IPV4);
277 }
278 for family in families {
279 match self.family_blocks[family_index(family)] {
280 Some(FamilyBlock::Unsupported) => {
281 return Err(Error::Other(format!(
282 "the server does not support {family} relayed addresses (440)"
283 )));
284 }
285 Some(FamilyBlock::Until(until)) if now < until => {
286 return Err(Error::Other(format!(
287 "the server had no capacity for a {family} relayed address (508)"
288 )));
289 }
290 _ => {}
291 }
292 }
293 }
294
295 // The authenticated request that follows the 401 goes out under an id of its own,
296 // drawn here at random rather than derived from this request's (RFC 8489 §6.3.1:
297 // every new request takes a new transaction id). It is the one the caller is handed,
298 // because that request is the one that carries the allocation.
299 let allocation_id = TransactionId::new();
300 // RFC 8489 §9.2.3: a request to a server the client has completed a successful
301 // transaction with is a subsequent request (§9.2.3.2) and carries the cached
302 // credential; only the first request to the server goes without (§9.2.3.1).
303 let cached = self.start_with.clone();
304 let state = AllocateState {
305 report_id: allocation_id,
306 options,
307 cached: cached.is_some(),
308 credential: cached.unwrap_or_else(|| Arc::new(Credential::new(self.login.clone()))),
309 unauthenticated_retries: 0,
310 stale_nonce_retried: false,
311 server_errors: 0,
312 };
313 // The servers this request went to, against a redirection back to one of them
314 // (RFC 8489 §10).
315 if let Some(server) = self.turn_serv_addr {
316 self.redirects.sent_to(server, now);
317 }
318 debug!("client.Allocate call PerformTransaction 1");
319 self.send_allocate(now, TransactionId::new(), state)?;
320 Ok(allocation_id)
321 }
322
323 /// Lets [`Client::allocate_with`] ask the server again for what it refused: an address
324 /// family it answered 440 or 508 for, or any allocation after it answered with a family
325 /// that was not asked for. RFC 8656 §7.3 and §7.4 forbid asking again until the client
326 /// "believes the mismatch has been fixed"; calling this says the application does.
327 pub fn clear_allocate_restrictions(&mut self) {
328 self.family_blocks = [None, None];
329 self.family_mismatch = false;
330 }
331
332 /// Whether the server answered an Allocate of this client with a relayed address of a
333 /// family that was not asked for (RFC 8656 §7.3), so that [`Client::allocate_with`]
334 /// refuses to ask it again until [`Client::clear_allocate_restrictions`]. A caller that
335 /// replaces the client keeps that in mind for the server itself.
336 #[must_use]
337 pub fn answered_another_family(&self) -> bool {
338 self.family_mismatch
339 }
340
341 /// Sends the Allocate of `state` under `id`: with the credential once the server asked
342 /// for it, without before.
343 pub(super) fn send_allocate(
344 &mut self,
345 now: Instant,
346 id: TransactionId,
347 state: AllocateState,
348 ) -> Result<()> {
349 let options = &state.options;
350 let mut attrs: Vec<Box<dyn Setter>> = vec![Box::new(RequestedTransport {
351 // REQUESTED-TRANSPORT names what the allocation relays, not the client-to-server
352 // transport (RFC 8656 §7.1): UDP, or TCP for a TCP allocation (RFC 6062 §4.1).
353 protocol: match options.transport {
354 RelayTransport::Udp => PROTO_UDP,
355 RelayTransport::Tcp => PROTO_TCP,
356 },
357 })];
358 if let Some(lifetime) = options.lifetime {
359 attrs.push(Box::new(Lifetime(lifetime)));
360 }
361 if let Some(family) = options.address_family {
362 attrs.push(Box::new(family));
363 }
364 if options.additional_ipv6 {
365 attrs.push(Box::new(AdditionalAddressFamily::default()));
366 }
367 if options.dont_fragment {
368 attrs.push(Box::new(DontFragmentAttr));
369 }
370 if let Some(even_port) = options.even_port {
371 attrs.push(Box::new(even_port));
372 }
373 if let Some(token) = &options.reservation_token {
374 attrs.push(Box::new(token.clone()));
375 }
376 let msg = self.build_request_as(id, METHOD_ALLOCATE, attrs, &state.credential)?;
377
378 let to = self.turn_server_addr_or_err()?;
379 let credential = state.credential.clone();
380 let transaction_type = if credential.is_established() {
381 TransactionType::AllocateRequest(Box::new(state))
382 } else {
383 TransactionType::AllocateAttempt(Box::new(state))
384 };
385 self.perform_transaction(now, &msg, to, transaction_type, Some(credential))?;
386 Ok(())
387 }
388
389 /// Handles the response to an Allocate.
390 pub(super) fn handle_allocate_response(
391 &mut self,
392 now: Instant,
393 response: Response,
394 mut state: AllocateState,
395 ) -> Result<()> {
396 // A server that wants no credential answers the first request with the allocation
397 // (RFC 8656 §7.2 step 1). One that nothing signs reaches here only when the client
398 // has no credential or was told to take it (`Client::set_unauthenticated_allocations`).
399 if response.typ.class != CLASS_ERROR_RESPONSE {
400 return self.handle_allocate_success(now, &response, state);
401 }
402 let id = state.report_id;
403 let err = response.error();
404 let authenticated = state.credential.is_established();
405
406 // 420 naming DONT-FRAGMENT: the server does not support it. The request is made
407 // again without it (RFC 8656 §7.4), and the allocation will not have it.
408 if state.options.dont_fragment
409 && matches!(&err, RequestError::Rejected(rejected)
410 if rejected.code == CODE_UNKNOWN_ATTRIBUTE
411 && rejected.unknown_attributes.contains(&ATTR_DONT_FRAGMENT))
412 {
413 debug!("the server does not know DONT-FRAGMENT; allocating without it");
414 state.options.dont_fragment = false;
415 return self.send_allocate(now, TransactionId::new(), state);
416 }
417
418 // The long-term credential mechanism (RFC 8489 §9.2.5). A 401 (Unauthenticated) asks
419 // for the credential, or refuses the one the request carried; a 438 (Stale Nonce)
420 // gives an authenticated request a new nonce. To the first request only a 401 is a
421 // challenge; any other error is the answer to the Allocate, reported with its code
422 // under the id allocate() handed out.
423 let unauthenticated = err.is(CODE_UNAUTHORIZED);
424 let stale = err.is(CODE_STALE_NONCE) && authenticated;
425 if !unauthenticated && !stale {
426 self.allocate_failed(now, &state.options, id, err);
427 return Ok(());
428 }
429 // A 401 to a request that carried a cached credential: the server does not take that
430 // realm or nonce any more (its state was lost, say). The request is made again as the
431 // one after a first request's 401, from this response alone, and the cache is not
432 // used again by this client.
433 if unauthenticated && state.cached {
434 debug!("Allocate: the cached credential drew a 401; authenticating anew");
435 state.cached = false;
436 state.credential = Arc::new(Credential::new(self.login.clone()));
437 self.start_with = None;
438 }
439 // What the client may send again after, and how: the realm and nonce of the
440 // response, USERHASH when the nonce cookie says so, the first password algorithm of
441 // the server's list the client supports. Not after a bid-down (the cookie announces
442 // PASSWORD-ALGORITHMS and the response has none), not without a supported algorithm,
443 // and not after a 401 to the very credentials the request carried.
444 let challenged = state.credential.challenged(
445 &response.request(),
446 &response.msg,
447 self.crypto_provider.crypto(),
448 );
449 let credential = match challenged {
450 Ok(credential) => credential,
451 // The server refused the credential, or its response gives nothing to answer
452 // with (no realm, no nonce): the error is the answer.
453 Err(
454 ChallengeError::CredentialsRejected
455 | ChallengeError::Incomplete
456 | ChallengeError::NotAChallenge,
457 ) => {
458 self.allocate_failed(now, &state.options, id, err);
459 return Ok(());
460 }
461 // The client will not authenticate this way: a bid-down, no password algorithm
462 // it supports, or a user name or password it cannot use.
463 Err(refused) => {
464 debug!("Allocate: {err} is not answered: {refused}");
465 self.events.push_back(Event::AllocateError(
466 id,
467 RequestError::Failed(Error::Other(format!("{err}; not retried: {refused}"))),
468 ));
469 return Ok(());
470 }
471 };
472 let again = if unauthenticated {
473 state.unauthenticated_retries < MAX_UNAUTHENTICATED_RETRIES
474 } else {
475 !state.stale_nonce_retried
476 };
477 if !again {
478 self.allocate_failed(now, &state.options, id, err);
479 return Ok(());
480 }
481 if unauthenticated {
482 state.unauthenticated_retries += 1;
483 } else {
484 state.stale_nonce_retried = true;
485 }
486 state.credential = Arc::new(credential);
487
488 // The request that carries the credential the server first asked for goes out under
489 // the id allocate() returned, so the caller can match Event::AllocateResponse with
490 // it; every later one takes a new transaction id (RFC 8489 §9.2.5).
491 debug!("client.Allocate call PerformTransaction 2");
492 let next_id = if authenticated {
493 TransactionId::new()
494 } else {
495 id
496 };
497 self.send_allocate(now, next_id, state)
498 }
499
500 /// Reports an Allocate the server refused, and remembers what RFC 8656 §7.4 has the
501 /// client not ask again.
502 fn allocate_failed(
503 &mut self,
504 _now: Instant,
505 options: &AllocateOptions,
506 id: TransactionId,
507 err: RequestError,
508 ) {
509 // 440 (Address Family not Supported): "the client MUST NOT retry the request".
510 if err.is(CODE_ADDR_FAMILY_NOT_SUPPORTED)
511 && let Some(family) = options.refused_family()
512 {
513 self.family_blocks[family_index(family)] = Some(FamilyBlock::Unsupported);
514 }
515 self.events.push_back(Event::AllocateError(id, err));
516 }
517
518 /// Takes the allocation of an Allocate success response. `state.credential` is the
519 /// credential the request was made with: none when the server asked for none.
520 fn handle_allocate_success(
521 &mut self,
522 now: Instant,
523 response: &Message,
524 state: AllocateState,
525 ) -> Result<()> {
526 let id = state.report_id;
527
528 // The relayed address or addresses, the lifetime, and how the server sees us.
529 let mut lifetime = Lifetime::default();
530 let decoded = xor_addresses(response, ATTR_XOR_RELAYED_ADDRESS).and_then(|mut relayed| {
531 // An XOR-RELAYED-ADDRESS of the unspecified address and port 0 names no relayed
532 // transport address (RFC 8656 §7.3 has the attribute carry the one allocated).
533 // coturn 4.6 puts one beside the real address when the session was refused
534 // another family before; it is passed over, not taken for a second address.
535 relayed.retain(|addr| !(addr.ip().is_unspecified() && addr.port() == 0));
536 if relayed.is_empty() {
537 return Err(Error::ErrAttributeNotFound);
538 }
539 // Any other address peers could not send to (port 0, unspecified, multicast,
540 // broadcast) is an allocation the client cannot use.
541 if let Some(unusable) = relayed.iter().find(|addr| !is_transport_address(addr)) {
542 return Err(Error::Other(format!(
543 "XOR-RELAYED-ADDRESS {unusable} is no address a peer can send to"
544 )));
545 }
546 lifetime.get_from(response)?;
547 // A mapped address that is no transport address is not passed on as one.
548 let mapped = if response.contains(ATTR_XORMAPPED_ADDRESS) {
549 xor_addresses(response, ATTR_XORMAPPED_ADDRESS)?
550 .into_iter()
551 .next()
552 .filter(is_transport_address)
553 } else {
554 None
555 };
556 Ok((relayed, mapped))
557 });
558 let (mut relayed, mapped) = match decoded {
559 Ok(decoded) => decoded,
560 Err(err) => {
561 // The server made an allocation this client cannot use: it is deleted, not
562 // left to hold the 5-tuple until it expires (RFC 8656 §7.3), and the caller
563 // is told.
564 let _ = self.release_orphan(now, &state.credential);
565 self.events
566 .push_back(Event::AllocateError(id, RequestError::Failed(err)));
567 return Ok(());
568 }
569 };
570
571 // RFC 8656 §7.3: the addresses must be of families the client is prepared to handle,
572 // which are the ones it asked for: one address of the requested family (IPv4 when
573 // none was named), or with ADDITIONAL-ADDRESS-FAMILY at most one of each. If not,
574 // the allocation is deleted and no other is asked for until the cause is gone.
575 relayed.sort_by_key(SocketAddr::is_ipv6);
576 let max = if state.options.additional_ipv6 { 2 } else { 1 };
577 let one_per_family = relayed.len() == 1 || relayed[0].is_ipv6() != relayed[1].is_ipv6();
578 if relayed.len() > max
579 || !one_per_family
580 || !relayed.iter().all(|addr| state.options.expects(addr))
581 {
582 let _ = self.release_orphan(now, &state.credential);
583 self.family_mismatch = true;
584 self.events.push_back(Event::AllocateError(
585 id,
586 RequestError::Failed(Error::Other(format!(
587 "the server allocated {relayed:?}, not the address family asked for"
588 ))),
589 ));
590 return Ok(());
591 }
592 let relayed_addr: RelayedAddr = relayed[0];
593
594 // A zero lifetime here is a protocol violation, not a degenerate allocation.
595 // RFC 8656 §7.2 has the server take `min(client proposed, server maximum)` and
596 // fall back to the *default* lifetime (600 s) whenever that computation does
597 // not exceed it — so the value returned by a successful Allocate is never
598 // below the default, and certainly never zero. Zero is meaningful only on the
599 // Refresh path (§8), where it means "allocation deleted".
600 //
601 // Accepting it would build a `RelayState` whose `refresh_alloc_timer` is
602 // `now.add(0)` — expired the instant it is created — for an allocation that is
603 // already gone. That relay then reports an expired refresh deadline forever,
604 // which is what a caller polling deadlines hot-loops on. See
605 // [webrtc#862](https://github.com/webrtc-rs/webrtc/issues/862).
606 if lifetime.0.is_zero() {
607 self.events.push_back(Event::AllocateError(
608 id,
609 RequestError::Failed(Error::Other(
610 "Allocate success response carried LIFETIME=0; RFC 8656 §7.2 \
611 requires at least the default lifetime"
612 .to_owned(),
613 )),
614 ));
615 return Ok(());
616 }
617
618 // With two families asked for, the server says in ADDRESS-ERROR-CODE why one is
619 // missing: after 440 that family is not asked for again, after 508 not for a minute
620 // (RFC 8656 §7.3).
621 let mut address_error = AddressErrorCode::default();
622 let address_error = address_error
623 .get_from(response)
624 .is_ok()
625 .then_some(address_error);
626 if let Some(refused) = &address_error {
627 let block = if refused.code == CODE_ADDR_FAMILY_NOT_SUPPORTED {
628 Some(FamilyBlock::Unsupported)
629 } else if refused.code == CODE_INSUFFICIENT_CAPACITY {
630 Some(FamilyBlock::Until(now.add(INSUFFICIENT_CAPACITY_WAIT)))
631 } else {
632 None
633 };
634 if block.is_some() {
635 self.family_blocks[family_index(refused.family)] = block;
636 }
637 }
638
639 let mut token = ReservationToken::default();
640 let reservation_token = token.get_from(response).is_ok().then_some(token);
641
642 // RFC 8489 §9.2.3.2: the realm, nonce and password algorithm the server accepted are
643 // cached for later requests to it (`Client::cached_credential`).
644 if state.credential.is_established()
645 && let Some(server) = self.turn_serv_addr
646 {
647 self.accepted = Some(super::CachedCredential {
648 server,
649 credential: state.credential.clone(),
650 });
651 }
652
653 let mut relay = RelayState::new(
654 now,
655 relayed_addr,
656 state.credential,
657 lifetime.0,
658 self.allocation_refresh_interval_cap,
659 );
660 relay.addrs = relayed;
661 relay.mapped_addr = mapped;
662 relay.reservation_token = reservation_token;
663 relay.address_error = address_error;
664 // The server took the request with DONT-FRAGMENT in it, so it supports it.
665 relay.dont_fragment = state.options.dont_fragment;
666 relay.transport = state.options.transport;
667 self.relays.insert(relayed_addr, relay);
668 self.events
669 .push_back(Event::AllocateResponse(id, relayed_addr));
670 Ok(())
671 }
672}