Skip to main content

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::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}
165
166/// Most 401 responses one Allocate is sent again after: the one that asks for the
167/// credential, and one that names another realm for it. RFC 8489 §9.2.5 forbids the retry
168/// that changes nothing; this bounds the ones that do.
169const MAX_UNAUTHENTICATED_RETRIES: u8 = 2;
170
171#[cfg(test)]
172impl AllocateState {
173    /// A default Allocate that has reached its authenticated request, for tests that hand
174    /// the client a response directly.
175    pub(crate) fn authenticated() -> Self {
176        Self {
177            report_id: TransactionId::new(),
178            options: AllocateOptions::default(),
179            credential: Credential::established(),
180            unauthenticated_retries: 1,
181            stale_nonce_retried: false,
182        }
183    }
184}
185
186/// Why an address family is not asked for.
187#[derive(Clone, Copy)]
188pub(crate) enum FamilyBlock {
189    /// The server does not support it (440).
190    Unsupported,
191    /// The server had no capacity for it (508): not before this instant.
192    Until(Instant),
193}
194
195fn family_index(family: RequestedAddressFamily) -> usize {
196    usize::from(family == REQUESTED_FAMILY_IPV6)
197}
198
199/// Every address `m` carries in attributes of type `t`, XOR-decoded.
200fn xor_addresses(m: &Message, t: AttrType) -> Result<Vec<SocketAddr>> {
201    let mut out = vec![];
202    for attr in m.attributes.0.iter().filter(|a| a.typ == t) {
203        let mut one = Message::new();
204        one.transaction_id = m.transaction_id;
205        one.add(attr.typ, &attr.value);
206        let mut addr = XorMappedAddress::default();
207        addr.get_from_as(&one, t)?;
208        out.push(SocketAddr::new(addr.ip, addr.port));
209    }
210    Ok(out)
211}
212
213impl Client {
214    /// Sends an Allocate request for a UDP relayed address to the TURN server.
215    ///
216    /// Returns the id that [`Event::AllocateResponse`], [`Event::AllocateError`] or
217    /// [`Event::TransactionTimeout`] will name.
218    pub fn allocate(&mut self, now: Instant) -> Result<TransactionId> {
219        self.allocate_with(now, AllocateOptions::default())
220    }
221
222    /// Sends an Allocate request with `options` (RFC 8656 §7.1): an address family, a second
223    /// (IPv6) address, a lifetime, DONT-FRAGMENT, an even port, a reserved port.
224    ///
225    /// # Errors
226    ///
227    /// Fails, with nothing sent, if the RFC forbids the combination of options (see
228    /// [`AllocateOptions`]), or if the server has refused the address family and may not be
229    /// asked again: for good after a 440 (Address Family not Supported), for a minute after
230    /// it had no capacity for one of two families, and after it answered with an address of
231    /// a family that was not asked for (RFC 8656 §7.3, §7.4). An application that believes
232    /// the cause is gone calls [`Client::clear_allocate_restrictions`].
233    pub fn allocate_with(
234        &mut self,
235        now: Instant,
236        options: AllocateOptions,
237    ) -> Result<TransactionId> {
238        options.check()?;
239        // RFC 6062 §4.1: a TCP allocation cannot be had over a UDP association with the
240        // server.
241        if options.transport == RelayTransport::Tcp
242            && self.transport_protocol == TransportProtocol::UDP
243        {
244            return Err(Error::Other(
245                "a TCP allocation is asked for over TCP or TLS to the server, never over UDP"
246                    .to_owned(),
247            ));
248        }
249        if self.family_mismatch {
250            return Err(Error::Other(
251                "the server answered an Allocate with an address family that was not asked for"
252                    .to_owned(),
253            ));
254        }
255        if let Some(family) = options.refused_family() {
256            let mut families = vec![family];
257            if options.additional_ipv6 {
258                families.push(REQUESTED_FAMILY_IPV4);
259            }
260            for family in families {
261                match self.family_blocks[family_index(family)] {
262                    Some(FamilyBlock::Unsupported) => {
263                        return Err(Error::Other(format!(
264                            "the server does not support {family} relayed addresses (440)"
265                        )));
266                    }
267                    Some(FamilyBlock::Until(until)) if now < until => {
268                        return Err(Error::Other(format!(
269                            "the server had no capacity for a {family} relayed address (508)"
270                        )));
271                    }
272                    _ => {}
273                }
274            }
275        }
276
277        // The authenticated request that follows the 401 goes out under an id of its own,
278        // drawn here at random rather than derived from this request's (RFC 8489 §6.3.1:
279        // every new request takes a new transaction id). It is the one the caller is handed,
280        // because that request is the one that carries the allocation.
281        let allocation_id = TransactionId::new();
282        let state = AllocateState {
283            report_id: allocation_id,
284            options,
285            credential: Arc::new(Credential::new(self.login.clone())),
286            unauthenticated_retries: 0,
287            stale_nonce_retried: false,
288        };
289        // The servers this request went to, against a redirection back to one of them
290        // (RFC 8489 §10).
291        if let Some(server) = self.turn_serv_addr {
292            self.redirects.sent_to(server, now);
293        }
294        debug!("client.Allocate call PerformTransaction 1");
295        self.send_allocate(now, TransactionId::new(), state)?;
296        Ok(allocation_id)
297    }
298
299    /// Lets [`Client::allocate_with`] ask the server again for what it refused: an address
300    /// family it answered 440 or 508 for, or any allocation after it answered with a family
301    /// that was not asked for. RFC 8656 §7.3 and §7.4 forbid asking again until the client
302    /// "believes the mismatch has been fixed"; calling this says the application does.
303    pub fn clear_allocate_restrictions(&mut self) {
304        self.family_blocks = [None, None];
305        self.family_mismatch = false;
306    }
307
308    /// Sends the Allocate of `state` under `id`: with the credential once the server asked
309    /// for it, without before.
310    fn send_allocate(
311        &mut self,
312        now: Instant,
313        id: TransactionId,
314        state: AllocateState,
315    ) -> Result<()> {
316        let options = &state.options;
317        let mut attrs: Vec<Box<dyn Setter>> = vec![Box::new(RequestedTransport {
318            // REQUESTED-TRANSPORT names what the allocation relays, not the client-to-server
319            // transport (RFC 8656 §7.1): UDP, or TCP for a TCP allocation (RFC 6062 §4.1).
320            protocol: match options.transport {
321                RelayTransport::Udp => PROTO_UDP,
322                RelayTransport::Tcp => PROTO_TCP,
323            },
324        })];
325        if let Some(lifetime) = options.lifetime {
326            attrs.push(Box::new(Lifetime(lifetime)));
327        }
328        if let Some(family) = options.address_family {
329            attrs.push(Box::new(family));
330        }
331        if options.additional_ipv6 {
332            attrs.push(Box::new(AdditionalAddressFamily::default()));
333        }
334        if options.dont_fragment {
335            attrs.push(Box::new(DontFragmentAttr));
336        }
337        if let Some(even_port) = options.even_port {
338            attrs.push(Box::new(even_port));
339        }
340        if let Some(token) = &options.reservation_token {
341            attrs.push(Box::new(token.clone()));
342        }
343        let msg = self.build_request_as(id, METHOD_ALLOCATE, attrs, &state.credential)?;
344
345        let to = self.turn_server_addr_or_err()?;
346        let credential = state.credential.clone();
347        let transaction_type = if credential.is_established() {
348            TransactionType::AllocateRequest(Box::new(state))
349        } else {
350            TransactionType::AllocateAttempt(Box::new(state))
351        };
352        self.perform_transaction(now, &msg, to, transaction_type, Some(credential))?;
353        Ok(())
354    }
355
356    /// Handles the response to an Allocate.
357    pub(super) fn handle_allocate_response(
358        &mut self,
359        now: Instant,
360        response: Response,
361        mut state: AllocateState,
362    ) -> Result<()> {
363        // A server that wants no credential answers the first request with the allocation
364        // (RFC 8656 §7.2 step 1).
365        if response.typ.class != CLASS_ERROR_RESPONSE {
366            return self.handle_allocate_success(now, &response, state);
367        }
368        let id = state.report_id;
369        let err = response.error();
370        let authenticated = state.credential.is_established();
371
372        // 420 naming DONT-FRAGMENT: the server does not support it. The request is made
373        // again without it (RFC 8656 §7.4), and the allocation will not have it.
374        if state.options.dont_fragment
375            && matches!(&err, RequestError::Rejected(rejected)
376                if rejected.code == CODE_UNKNOWN_ATTRIBUTE
377                    && rejected.unknown_attributes.contains(&ATTR_DONT_FRAGMENT))
378        {
379            debug!("the server does not know DONT-FRAGMENT; allocating without it");
380            state.options.dont_fragment = false;
381            return self.send_allocate(now, TransactionId::new(), state);
382        }
383
384        // The long-term credential mechanism (RFC 8489 §9.2.5). A 401 (Unauthenticated) asks
385        // for the credential, or refuses the one the request carried; a 438 (Stale Nonce)
386        // gives an authenticated request a new nonce. To the first request only a 401 is a
387        // challenge; any other error is the answer to the Allocate, reported with its code
388        // under the id allocate() handed out.
389        let unauthenticated = err.is(CODE_UNAUTHORIZED);
390        let stale = err.is(CODE_STALE_NONCE) && authenticated;
391        if !unauthenticated && !stale {
392            self.allocate_failed(now, &state.options, id, err);
393            return Ok(());
394        }
395        // What the client may send again after, and how: the realm and nonce of the
396        // response, USERHASH when the nonce cookie says so, the first password algorithm of
397        // the server's list the client supports. Not after a bid-down (the cookie announces
398        // PASSWORD-ALGORITHMS and the response has none), not without a supported algorithm,
399        // and not after a 401 to the very credentials the request carried.
400        let challenged = state.credential.challenged(
401            &response.request(),
402            &response.msg,
403            self.crypto_provider.crypto(),
404        );
405        let credential = match challenged {
406            Ok(credential) => credential,
407            // The server refused the credential, or its response gives nothing to answer
408            // with (no realm, no nonce): the error is the answer.
409            Err(
410                ChallengeError::CredentialsRejected
411                | ChallengeError::Incomplete
412                | ChallengeError::NotAChallenge,
413            ) => {
414                self.allocate_failed(now, &state.options, id, err);
415                return Ok(());
416            }
417            // The client will not authenticate this way: a bid-down, no password algorithm
418            // it supports, or a user name or password it cannot use.
419            Err(refused) => {
420                debug!("Allocate: {err} is not answered: {refused}");
421                self.events.push_back(Event::AllocateError(
422                    id,
423                    RequestError::Failed(Error::Other(format!("{err}; not retried: {refused}"))),
424                ));
425                return Ok(());
426            }
427        };
428        let again = if unauthenticated {
429            state.unauthenticated_retries < MAX_UNAUTHENTICATED_RETRIES
430        } else {
431            !state.stale_nonce_retried
432        };
433        if !again {
434            self.allocate_failed(now, &state.options, id, err);
435            return Ok(());
436        }
437        if unauthenticated {
438            state.unauthenticated_retries += 1;
439        } else {
440            state.stale_nonce_retried = true;
441        }
442        state.credential = Arc::new(credential);
443
444        // The request that carries the credential the server first asked for goes out under
445        // the id allocate() returned, so the caller can match Event::AllocateResponse with
446        // it; every later one takes a new transaction id (RFC 8489 §9.2.5).
447        debug!("client.Allocate call PerformTransaction 2");
448        let next_id = if authenticated {
449            TransactionId::new()
450        } else {
451            id
452        };
453        self.send_allocate(now, next_id, state)
454    }
455
456    /// Reports an Allocate the server refused, and remembers what RFC 8656 §7.4 has the
457    /// client not ask again.
458    fn allocate_failed(
459        &mut self,
460        _now: Instant,
461        options: &AllocateOptions,
462        id: TransactionId,
463        err: RequestError,
464    ) {
465        // 440 (Address Family not Supported): "the client MUST NOT retry the request".
466        if err.is(CODE_ADDR_FAMILY_NOT_SUPPORTED)
467            && let Some(family) = options.refused_family()
468        {
469            self.family_blocks[family_index(family)] = Some(FamilyBlock::Unsupported);
470        }
471        self.events.push_back(Event::AllocateError(id, err));
472    }
473
474    /// Takes the allocation of an Allocate success response. `state.credential` is the
475    /// credential the request was made with: none when the server asked for none.
476    fn handle_allocate_success(
477        &mut self,
478        now: Instant,
479        response: &Message,
480        state: AllocateState,
481    ) -> Result<()> {
482        let id = state.report_id;
483
484        // The relayed address or addresses, the lifetime, and how the server sees us.
485        let mut lifetime = Lifetime::default();
486        let decoded = xor_addresses(response, ATTR_XOR_RELAYED_ADDRESS).and_then(|mut relayed| {
487            // An XOR-RELAYED-ADDRESS of the unspecified address and port 0 names no relayed
488            // transport address (RFC 8656 §7.3 has the attribute carry the one allocated).
489            // coturn 4.6 puts one beside the real address when the session was refused
490            // another family before; it is passed over, not taken for a second address.
491            relayed.retain(|addr| !(addr.ip().is_unspecified() && addr.port() == 0));
492            if relayed.is_empty() {
493                return Err(Error::ErrAttributeNotFound);
494            }
495            lifetime.get_from(response)?;
496            let mapped = if response.contains(ATTR_XORMAPPED_ADDRESS) {
497                xor_addresses(response, ATTR_XORMAPPED_ADDRESS)?
498                    .into_iter()
499                    .next()
500            } else {
501                None
502            };
503            Ok((relayed, mapped))
504        });
505        let (mut relayed, mapped) = match decoded {
506            Ok(decoded) => decoded,
507            Err(err) => {
508                // The server made an allocation this client cannot use: it is deleted, not
509                // left to hold the 5-tuple until it expires (RFC 8656 §7.3), and the caller
510                // is told.
511                let _ = self.release_orphan(now, &state.credential);
512                self.events
513                    .push_back(Event::AllocateError(id, RequestError::Failed(err)));
514                return Ok(());
515            }
516        };
517
518        // RFC 8656 §7.3: the addresses must be of families the client is prepared to handle,
519        // which are the ones it asked for: one address of the requested family (IPv4 when
520        // none was named), or with ADDITIONAL-ADDRESS-FAMILY at most one of each. If not,
521        // the allocation is deleted and no other is asked for until the cause is gone.
522        relayed.sort_by_key(SocketAddr::is_ipv6);
523        let max = if state.options.additional_ipv6 { 2 } else { 1 };
524        let one_per_family = relayed.len() == 1 || relayed[0].is_ipv6() != relayed[1].is_ipv6();
525        if relayed.len() > max
526            || !one_per_family
527            || !relayed.iter().all(|addr| state.options.expects(addr))
528        {
529            let _ = self.release_orphan(now, &state.credential);
530            self.family_mismatch = true;
531            self.events.push_back(Event::AllocateError(
532                id,
533                RequestError::Failed(Error::Other(format!(
534                    "the server allocated {relayed:?}, not the address family asked for"
535                ))),
536            ));
537            return Ok(());
538        }
539        let relayed_addr: RelayedAddr = relayed[0];
540
541        // A zero lifetime here is a protocol violation, not a degenerate allocation.
542        // RFC 8656 §7.2 has the server take `min(client proposed, server maximum)` and
543        // fall back to the *default* lifetime (600 s) whenever that computation does
544        // not exceed it — so the value returned by a successful Allocate is never
545        // below the default, and certainly never zero. Zero is meaningful only on the
546        // Refresh path (§8), where it means "allocation deleted".
547        //
548        // Accepting it would build a `RelayState` whose `refresh_alloc_timer` is
549        // `now.add(0)` — expired the instant it is created — for an allocation that is
550        // already gone. That relay then reports an expired refresh deadline forever,
551        // which is what a caller polling deadlines hot-loops on. See
552        // [webrtc#862](https://github.com/webrtc-rs/webrtc/issues/862).
553        if lifetime.0.is_zero() {
554            self.events.push_back(Event::AllocateError(
555                id,
556                RequestError::Failed(Error::Other(
557                    "Allocate success response carried LIFETIME=0; RFC 8656 §7.2 \
558                     requires at least the default lifetime"
559                        .to_owned(),
560                )),
561            ));
562            return Ok(());
563        }
564
565        // With two families asked for, the server says in ADDRESS-ERROR-CODE why one is
566        // missing: after 440 that family is not asked for again, after 508 not for a minute
567        // (RFC 8656 §7.3).
568        let mut address_error = AddressErrorCode::default();
569        let address_error = address_error
570            .get_from(response)
571            .is_ok()
572            .then_some(address_error);
573        if let Some(refused) = &address_error {
574            let block = if refused.code == CODE_ADDR_FAMILY_NOT_SUPPORTED {
575                Some(FamilyBlock::Unsupported)
576            } else if refused.code == CODE_INSUFFICIENT_CAPACITY {
577                Some(FamilyBlock::Until(now.add(INSUFFICIENT_CAPACITY_WAIT)))
578            } else {
579                None
580            };
581            if block.is_some() {
582                self.family_blocks[family_index(refused.family)] = block;
583            }
584        }
585
586        let mut token = ReservationToken::default();
587        let reservation_token = token.get_from(response).is_ok().then_some(token);
588
589        let mut relay = RelayState::new(
590            now,
591            relayed_addr,
592            state.credential,
593            lifetime.0,
594            self.allocation_refresh_interval_cap,
595        );
596        relay.addrs = relayed;
597        relay.mapped_addr = mapped;
598        relay.reservation_token = reservation_token;
599        relay.address_error = address_error;
600        // The server took the request with DONT-FRAGMENT in it, so it supports it.
601        relay.dont_fragment = state.options.dont_fragment;
602        relay.transport = state.options.transport;
603        self.relays.insert(relayed_addr, relay);
604        self.events
605            .push_back(Event::AllocateResponse(id, relayed_addr));
606        Ok(())
607    }
608}