Skip to main content

rtci_turn/client/
relay.rs

1use log::{debug, warn};
2use std::collections::{HashMap, HashSet};
3use std::net::{IpAddr, SocketAddr};
4use std::ops::Add;
5use std::time::{Duration, Instant};
6use stun::error_code::*;
7use stun::fingerprint::*;
8use stun::message::*;
9
10use super::permission::*;
11use super::transaction::*;
12use crate::proto;
13
14use crate::client::binding::{BINDING_REFRESH_AGE, BindingManager, BindingState};
15use crate::client::credential::Credential;
16use crate::client::data_connection::{DataConnection, DataConnectionConfig};
17use crate::client::error::RequestError;
18use crate::client::{Client, Event, RelayTransport, RelayedAddr, Response};
19use crate::proto::connid::ConnectionId;
20use shared::error::{Error, Result};
21use std::sync::Arc;
22
23const PERM_REFRESH_INTERVAL: Duration = Duration::from_secs(120);
24// https://datatracker.ietf.org/doc/html/rfc8656#name-permissions-2
25// The Permission Lifetime MUST be 300 seconds (= 5 minutes).
26const PERM_LIFETIME: Duration = Duration::from_secs(300);
27const MAX_RETRY_ATTEMPTS: u16 = 3;
28/// How often the bindings of an allocation are looked over for ones to rebind.
29const BINDING_SWEEP_INTERVAL: Duration = Duration::from_secs(60);
30/// How long a ChannelBind the server refused is not sent again. The data goes as Send
31/// indications meanwhile, so this only bounds how often a server that keeps refusing is asked.
32const CHANNEL_BIND_RETRY_INTERVAL: Duration = Duration::from_secs(60);
33/// Most peer addresses one CreatePermission names. A refresh of more permissions is split into
34/// several requests, which keeps each well inside one UDP datagram (an IPv6 XOR-PEER-ADDRESS is
35/// 24 bytes) and far from the 64 KiB a STUN length field can describe.
36pub(crate) const MAX_PEERS_PER_CREATE_PERMISSION: usize = 16;
37/// Smallest step the allocation-refresh timer may advance by.
38///
39/// The timer advances by a fixed cadence from its own previous value, which keeps the refresh
40/// schedule drift-free. That only works while the step is positive. `lifetime` is assigned
41/// straight from the server's LIFETIME attribute, and a refresh carrying `LIFETIME=0` — how
42/// RFC 8656 §8 deallocates, and what [`Relay::close`] sends — makes `lifetime / 2` zero. The timer
43/// then freezes on an already-expired instant and `poll_timeout` reports that same instant
44/// forever. A caller that treats an expired deadline as "handle it and go round again" spins
45/// on it without ever reaching its socket reads, which is
46/// [webrtc#862](https://github.com/webrtc-rs/webrtc/issues/862).
47const MIN_ALLOC_REFRESH_INTERVAL: Duration = Duration::from_secs(1);
48
49fn allocation_refresh_interval(lifetime: Duration, interval_cap: Option<Duration>) -> Duration {
50    let half_lifetime = lifetime / 2;
51    interval_cap
52        .map_or(half_lifetime, |cap| half_lifetime.min(cap))
53        .max(MIN_ALLOC_REFRESH_INTERVAL)
54}
55
56// RelayState is a set of params use by Relay
57pub(crate) struct RelayState {
58    /// The address the allocation is kept under: the first relayed address it was given.
59    pub(crate) relayed_addr: RelayedAddr,
60    /// The relayed addresses the allocation has now: one, or an IPv4 and an IPv6 one after
61    /// ADDITIONAL-ADDRESS-FAMILY (RFC 8656 §7.1), IPv4 first.
62    pub(crate) addrs: Vec<RelayedAddr>,
63    /// The XOR-MAPPED-ADDRESS of the Allocate success response: the client's
64    /// server-reflexive address.
65    pub(crate) mapped_addr: Option<SocketAddr>,
66    /// The RESERVATION-TOKEN of the Allocate success response.
67    pub(crate) reservation_token: Option<proto::rsrvtoken::ReservationToken>,
68    /// Why the server did not allocate one of the two families asked for.
69    pub(crate) address_error: Option<proto::addrerror::AddressErrorCode>,
70    /// Whether the server took an Allocate with DONT-FRAGMENT, so supports it.
71    pub(crate) dont_fragment: bool,
72    /// What the allocation relays: UDP datagrams, or TCP connections (RFC 6062).
73    pub(crate) transport: RelayTransport,
74    /// Peers a Connect request is outstanding for: never two for one peer address
75    /// (RFC 6062 §4.3).
76    pub(crate) connecting: HashSet<SocketAddr>,
77    /// Peers the server could not connect to (447), and when each may be tried again.
78    connect_hold: HashMap<SocketAddr, Instant>,
79    /// The long-term credential requests for the allocation are made with, as the server's
80    /// last challenge left it: none for an allocation a server gave without asking for one.
81    pub(crate) credential: Arc<Credential>,
82    pub(crate) lifetime: Duration,
83    /// When the server deletes the allocation unless a Refresh reaches it first: the lifetime
84    /// it last returned, counted from that response.
85    pub(crate) expires_at: Instant,
86    /// Whether the application released the allocation ([`Relay::close`]). Nothing is sent
87    /// for it any more but the Refresh with LIFETIME 0 and its retries.
88    pub(crate) releasing: bool,
89    allocation_refresh_interval_cap: Option<Duration>,
90    /// Permissions by peer IP address: a permission covers every port on that address
91    /// (RFC 8656 §9).
92    pub(crate) perm_map: HashMap<IpAddr, Permission>,
93    /// The allocation's channel bindings. They are the allocation's own and end with it
94    /// (RFC 8656 §12).
95    pub(crate) binding_mgr: BindingManager,
96    refresh_alloc_timer: Instant,
97    refresh_perms_timer: Instant,
98    /// When the bindings are next looked over; `None` while no binding is live.
99    bindings_timer: Option<Instant>,
100}
101
102impl RelayState {
103    pub(super) fn new(
104        now: Instant,
105        relayed_addr: RelayedAddr,
106        credential: Arc<Credential>,
107        lifetime: Duration,
108        allocation_refresh_interval_cap: Option<Duration>,
109    ) -> Self {
110        debug!("initial lifetime: {} seconds", lifetime.as_secs());
111
112        Self {
113            relayed_addr,
114            addrs: vec![relayed_addr],
115            mapped_addr: None,
116            reservation_token: None,
117            address_error: None,
118            dont_fragment: false,
119            transport: RelayTransport::Udp,
120            connecting: HashSet::new(),
121            connect_hold: HashMap::new(),
122            credential,
123            lifetime,
124            expires_at: now.add(lifetime),
125            releasing: false,
126            allocation_refresh_interval_cap,
127            perm_map: HashMap::new(),
128            binding_mgr: BindingManager::new(),
129            refresh_alloc_timer: now.add(allocation_refresh_interval(
130                lifetime,
131                allocation_refresh_interval_cap,
132            )),
133            refresh_perms_timer: now.add(PERM_REFRESH_INTERVAL),
134            bindings_timer: None,
135        }
136    }
137
138    /// Whether requests for this allocation are signed. An allocation a server gave without
139    /// asking for a credential (RFC 8656 §7.2 step 1) has none.
140    pub(crate) fn is_signed(&self) -> bool {
141        self.credential.is_established()
142    }
143
144    /// Whether the allocation has a relayed address of `peer`'s family. A peer of another
145    /// family cannot be reached through it: the server answers 443 (RFC 8656 §10.2, §12.2).
146    pub(crate) fn relays_family_of(&self, peer: &IpAddr) -> bool {
147        self.addrs
148            .iter()
149            .any(|addr| addr.is_ipv4() == peer.is_ipv4())
150    }
151
152    /// The address events name the allocation by: its first relayed address.
153    pub(crate) fn name(&self) -> RelayedAddr {
154        self.addrs.first().copied().unwrap_or(self.relayed_addr)
155    }
156
157    /// Whether the client holds a permission for `ip`, asked for or installed, that has not
158    /// run out at `now`: data from an address without one is not relayed by the server
159    /// (RFC 8656 §11.4, §12.6).
160    pub(crate) fn expects_data_from(&self, ip: &IpAddr, now: Instant) -> bool {
161        self.perm_map
162            .get(ip)
163            .is_some_and(|perm| perm.state() == PermState::Idle || perm.is_permitted(now))
164    }
165
166    /// Drops the permission for `ip` after a CreatePermission the application asked for failed,
167    /// unless the server installed it meanwhile: a permission is per IP address (RFC 8656 §9),
168    /// so another request for the same address (another port) may have been granted while this
169    /// one was outstanding, and the refusal of one request takes nothing from the other.
170    pub(crate) fn forget_unless_permitted(&mut self, ip: IpAddr, now: Instant) {
171        if self
172            .perm_map
173            .get(&ip)
174            .is_some_and(|perm| !perm.is_permitted(now))
175        {
176            self.perm_map.remove(&ip);
177        }
178    }
179}
180
181/// A borrowed handle to one live allocation on the TURN server.
182///
183/// Obtained from [`Client::relay`](crate::client::Client::relay). Sending to a peer requires
184/// a permission for it first — see [`Self::create_permission`].
185pub struct Relay<'a> {
186    pub(crate) relayed_addr: RelayedAddr,
187    pub(crate) client: &'a mut Client,
188}
189
190impl Relay<'_> {
191    /// Asks the server to permit traffic to and from `peer_addr`.
192    ///
193    /// The relay silently drops data for peers with no permission, and permissions expire after
194    /// five minutes unless refreshed. A permission is for the peer's IP address, whatever the
195    /// port (RFC 8656 §9), so one covers every port on that address. Returns the transaction id
196    /// to match against the resulting [`Event`], or `None` if a permission is already in place.
197    ///
198    /// # Errors
199    ///
200    /// Fails if the allocation no longer exists or was released, if `peer_addr` is not of
201    /// the family of a relayed address of the allocation (RFC 8656 §10.1), or if the request
202    /// cannot be encoded.
203    pub fn create_permission(
204        &mut self,
205        now: Instant,
206        peer_addr: SocketAddr,
207    ) -> Result<Option<TransactionId>> {
208        if let Some(relay) = self.client.relays.get_mut(&self.relayed_addr) {
209            if relay.releasing {
210                return Err(Error::ErrConnClosed);
211            }
212            if !relay.relays_family_of(&peer_addr.ip()) {
213                return Err(peer_family_mismatch(peer_addr));
214            }
215            relay
216                .perm_map
217                .entry(peer_addr.ip())
218                .or_insert_with(Permission::default);
219            if let Some(perm) = relay.perm_map.get(&peer_addr.ip())
220                && !perm.is_permitted(now)
221            {
222                return Ok(Some(self.create_permissions(
223                    now,
224                    &[peer_addr],
225                    Some(peer_addr),
226                    Retry::default(),
227                )?));
228            }
229            Ok(None)
230        } else {
231            Err(Error::ErrConnClosed)
232        }
233    }
234
235    pub(crate) fn poll_timeout(&self) -> Option<Instant> {
236        let relay = self.client.relays.get(&self.relayed_addr)?;
237        if relay.releasing {
238            // Only the release is outstanding, and its transaction has its own deadline.
239            return None;
240        }
241        let mut deadline = relay.refresh_alloc_timer.min(relay.refresh_perms_timer);
242        if let Some(bindings_timer) = relay.bindings_timer {
243            deadline = deadline.min(bindings_timer);
244        }
245        Some(deadline)
246    }
247
248    pub(crate) fn handle_timeout(&mut self, now: Instant) {
249        let Some(relay) = self.client.relays.get_mut(&self.relayed_addr) else {
250            return;
251        };
252        if relay.releasing {
253            return;
254        }
255
256        let refresh_alloc = if relay.refresh_alloc_timer <= now {
257            // Floored so the timer always moves. A zero step would leave it pinned to an
258            // instant already in the past — see `MIN_ALLOC_REFRESH_INTERVAL`.
259            let step =
260                allocation_refresh_interval(relay.lifetime, relay.allocation_refresh_interval_cap);
261            relay.refresh_alloc_timer = now.add(step);
262            Some(relay.lifetime)
263        } else {
264            None
265        };
266
267        let refresh_perms = if relay.refresh_perms_timer <= now {
268            relay.refresh_perms_timer = now.add(PERM_REFRESH_INTERVAL);
269            true
270        } else {
271            false
272        };
273
274        // A binding lasts 10 minutes from its last ChannelBind (RFC 8656 §12). One that
275        // carried data since then is rebound before a send would do it, so a channel the
276        // client only receives on does not run out.
277        let mut rebind = vec![];
278        if relay.bindings_timer.is_some_and(|at| at <= now) {
279            let mut any_live = false;
280            for b in relay.binding_mgr.iter_mut() {
281                if !b.is_live(now) {
282                    continue;
283                }
284                any_live = true;
285                if b.state() == BindingState::Ready
286                    && b.used
287                    && now.saturating_duration_since(b.refreshed_at()) + BINDING_SWEEP_INTERVAL
288                        >= BINDING_REFRESH_AGE
289                {
290                    b.set_state(BindingState::Refresh);
291                    rebind.push(b.addr);
292                }
293            }
294            relay.bindings_timer = any_live.then(|| now.add(BINDING_SWEEP_INTERVAL));
295        }
296
297        if let Some(lifetime) = refresh_alloc {
298            let _ = self.refresh_allocation(now, lifetime);
299        }
300        if refresh_perms {
301            let _ = self.refresh_permissions(now);
302        }
303        for bind_addr in rebind {
304            if self
305                .rebind_channel(now, bind_addr, Retry::default())
306                .is_err()
307                && let Some(relay) = self.client.relays.get_mut(&self.relayed_addr)
308                && let Some(b) = relay.binding_mgr.get_by_addr(&bind_addr)
309            {
310                b.set_state(BindingState::Ready);
311            }
312        }
313    }
314
315    /// Sends `p` to `peer_addr` through the relay.
316    ///
317    /// Uses ChannelData framing once a channel is bound for that peer, and a Send indication
318    /// until then. A channel is bound for every peer address sent to, as long as channel
319    /// numbers are free; without one the data keeps going as Send indications.
320    ///
321    /// # Errors
322    ///
323    /// Fails if the allocation is gone or was released, if no permission is in place for
324    /// `peer_addr` (none was created, the server refused it, or its 300 s ran out without a
325    /// refresh), or if `p` is longer than the message that would carry it can say (65 535
326    /// bytes of ChannelData).
327    pub fn send_to(&mut self, now: Instant, p: &[u8], peer_addr: SocketAddr) -> Result<()> {
328        let Some(relay) = self.client.relays.get(&self.relayed_addr) else {
329            return Err(Error::ErrConnClosed);
330        };
331        if relay.releasing {
332            return Err(Error::ErrConnClosed);
333        }
334        if relay.transport == RelayTransport::Tcp {
335            return Err(not_a_udp_allocation());
336        }
337        // check if we have a permission for the destination IP addr
338        if !relay
339            .perm_map
340            .get(&peer_addr.ip())
341            .is_some_and(|perm| perm.is_permitted(now))
342        {
343            return Err(Error::ErrNoPermission);
344        }
345        // The peer of a channel binding is of the relayed address's family (RFC 8656 §12.1).
346        if !relay.relays_family_of(&peer_addr.ip()) {
347            return Err(peer_family_mismatch(peer_addr));
348        }
349
350        self.send(now, p, peer_addr)
351    }
352
353    /// Whether a channel to `peer_addr` is bound and live on the server, so that
354    /// [`Self::send_to`] sends ChannelData.
355    #[must_use]
356    pub fn channel_ready(&mut self, now: Instant, peer_addr: SocketAddr) -> bool {
357        let Some(relay) = self.client.relays.get_mut(&self.relayed_addr) else {
358            return false;
359        };
360        relay.binding_mgr.get_by_addr(&peer_addr).is_some_and(|b| {
361            matches!(b.state(), BindingState::Ready | BindingState::Refresh) && b.is_live(now)
362        })
363    }
364
365    /// Asks the server for a channel to `peer_addr` (RFC 8656 §12) without sending data: a
366    /// ChannelBind when none is bound, under way or refused for the moment. A permission for
367    /// the peer must be in place, as for [`Self::send_to`].
368    ///
369    /// # Errors
370    ///
371    /// As [`Self::send_to`]'s, but for the length.
372    pub fn bind_channel(&mut self, now: Instant, peer_addr: SocketAddr) -> Result<()> {
373        let Some(relay) = self.client.relays.get_mut(&self.relayed_addr) else {
374            return Err(Error::ErrConnClosed);
375        };
376        if relay.releasing {
377            return Err(Error::ErrConnClosed);
378        }
379        if relay.transport == RelayTransport::Tcp {
380            return Err(not_a_udp_allocation());
381        }
382        if !relay
383            .perm_map
384            .get(&peer_addr.ip())
385            .is_some_and(|perm| perm.is_permitted(now))
386        {
387            return Err(Error::ErrNoPermission);
388        }
389        if !relay.relays_family_of(&peer_addr.ip()) {
390            return Err(peer_family_mismatch(peer_addr));
391        }
392        if relay.binding_mgr.find_by_addr(&peer_addr).is_none() {
393            let _ = relay.binding_mgr.create(now, peer_addr);
394        }
395        let mut bind = None;
396        if let Some(b) = relay.binding_mgr.get_by_addr(&peer_addr) {
397            if b.state() == BindingState::Failed && b.retry_at.is_none_or(|at| at <= now) {
398                b.set_state(BindingState::Idle);
399            }
400            let stale = matches!(b.state(), BindingState::Ready) && !b.is_live(now);
401            if b.state() == BindingState::Idle || stale {
402                b.set_state(BindingState::Request);
403                bind = Some(b.number);
404            }
405        }
406        if let Some(number) = bind {
407            let credential = relay.credential.clone();
408            self.channel_bind(
409                now,
410                self.relayed_addr,
411                peer_addr,
412                number,
413                credential,
414                Retry::default(),
415            )?;
416        }
417        Ok(())
418    }
419
420    /// Sends `p` to `peer_addr` in a Send indication (RFC 8656 §11.1), never as ChannelData,
421    /// and binds no channel for the peer. For a caller that defers channels, as RFC 8445
422    /// §7.2.1 recommends an ICE agent do "until ICE completes": its connectivity checks go
423    /// this way, and [`Self::send_to`] (which binds a channel to the peer) once a pair through
424    /// the allocation is selected. A channel already bound to the peer is left as it is.
425    ///
426    /// # Errors
427    ///
428    /// As [`Self::send_to`].
429    pub fn send_indication_to(
430        &mut self,
431        now: Instant,
432        p: &[u8],
433        peer_addr: SocketAddr,
434    ) -> Result<()> {
435        let Some(relay) = self.client.relays.get(&self.relayed_addr) else {
436            return Err(Error::ErrConnClosed);
437        };
438        if relay.releasing {
439            return Err(Error::ErrConnClosed);
440        }
441        if relay.transport == RelayTransport::Tcp {
442            return Err(not_a_udp_allocation());
443        }
444        if !relay
445            .perm_map
446            .get(&peer_addr.ip())
447            .is_some_and(|perm| perm.is_permitted(now))
448        {
449            return Err(Error::ErrNoPermission);
450        }
451        if !relay.relays_family_of(&peer_addr.ip()) {
452            return Err(peer_family_mismatch(peer_addr));
453        }
454        self.send_indication(now, p, peer_addr, false)
455    }
456
457    /// Sends `p` to `peer_addr` in a Send indication carrying DONT-FRAGMENT, which asks the
458    /// server to set the DF bit on the datagram it sends the peer (RFC 8656 §11.1). The data
459    /// never goes as ChannelData, which cannot say so.
460    ///
461    /// # Errors
462    ///
463    /// As [`Self::send_to`]; and if the allocation was not made with
464    /// [`AllocateOptions::dont_fragment`](crate::client::AllocateOptions), or the server
465    /// answered that request with 420: the server is not known to support the attribute
466    /// (RFC 8656 §7.1).
467    pub fn send_to_dont_fragment(
468        &mut self,
469        now: Instant,
470        p: &[u8],
471        peer_addr: SocketAddr,
472    ) -> Result<()> {
473        let Some(relay) = self.client.relays.get(&self.relayed_addr) else {
474            return Err(Error::ErrConnClosed);
475        };
476        if relay.releasing {
477            return Err(Error::ErrConnClosed);
478        }
479        if relay.transport == RelayTransport::Tcp {
480            return Err(not_a_udp_allocation());
481        }
482        if !relay.dont_fragment {
483            return Err(Error::Other(
484                "DONT-FRAGMENT is not known to be supported for this allocation".to_owned(),
485            ));
486        }
487        if !relay
488            .perm_map
489            .get(&peer_addr.ip())
490            .is_some_and(|perm| perm.is_permitted(now))
491        {
492            return Err(Error::ErrNoPermission);
493        }
494        if !relay.relays_family_of(&peer_addr.ip()) {
495            return Err(peer_family_mismatch(peer_addr));
496        }
497        self.send_indication(now, p, peer_addr, true)
498    }
499
500    /// The relayed addresses of the allocation: one, or an IPv4 and an IPv6 address when it
501    /// was made with [`AllocateOptions::additional_ipv6`](crate::client::AllocateOptions)
502    /// and the server gave both. Peers of either family can then be reached through it.
503    #[must_use]
504    pub fn relayed_addrs(&self) -> Vec<RelayedAddr> {
505        self.state()
506            .map_or_else(Vec::new, |relay| relay.addrs.clone())
507    }
508
509    /// The client's address as the server saw the Allocate request arrive from: its
510    /// server-reflexive address (RFC 8656 §7.3), from the response's XOR-MAPPED-ADDRESS.
511    #[must_use]
512    pub fn mapped_addr(&self) -> Option<SocketAddr> {
513        self.state()?.mapped_addr
514    }
515
516    /// The lifetime the server last granted the allocation.
517    #[must_use]
518    pub fn lifetime(&self) -> Option<Duration> {
519        self.state().map(|relay| relay.lifetime)
520    }
521
522    /// The RESERVATION-TOKEN of the Allocate success response: the port the server holds for
523    /// a later allocation, after an EVEN-PORT that asked for it (RFC 8656 §7.1).
524    #[must_use]
525    pub fn reservation_token(&self) -> Option<proto::rsrvtoken::ReservationToken> {
526        self.state()?.reservation_token.clone()
527    }
528
529    /// Whether the server supports DONT-FRAGMENT: the allocation was made with it and the
530    /// server took it.
531    #[must_use]
532    pub fn dont_fragment(&self) -> bool {
533        self.state().is_some_and(|relay| relay.dont_fragment)
534    }
535
536    /// The ADDRESS-ERROR-CODE of the Allocate success response: which of the two address
537    /// families asked for the server did not allocate, and why (RFC 8656 §7.3).
538    #[must_use]
539    pub fn address_error(&self) -> Option<proto::addrerror::AddressErrorCode> {
540        self.state()?.address_error.clone()
541    }
542
543    /// What the allocation relays: UDP datagrams, or TCP connections (RFC 6062).
544    #[must_use]
545    pub fn transport(&self) -> RelayTransport {
546        self.state()
547            .map_or(RelayTransport::Udp, |relay| relay.transport)
548    }
549
550    /// Asks the server to open a TCP connection from the relayed address to `peer_addr`
551    /// (RFC 6062 §4.3), with a Connect request on the control connection. Returns the id that
552    /// [`Event::ConnectResponse`], [`Event::ConnectError`] or [`Event::TransactionTimeout`]
553    /// will name. The server answers when the peer accepted, or after it gave up (about 30
554    /// seconds).
555    ///
556    /// Connect requests to different peers can be outstanding together.
557    ///
558    /// # Errors
559    ///
560    /// Fails, with nothing sent, if the allocation is gone, was released, or relays UDP; if
561    /// `peer_addr` is not of the family of its relayed address; if a Connect to `peer_addr`
562    /// is still outstanding (RFC 6062 §4.3: never two for one peer address); or if the server
563    /// answered 447 for `peer_addr` less than ten seconds ago.
564    pub fn connect(&mut self, now: Instant, peer_addr: SocketAddr) -> Result<TransactionId> {
565        let Some(relay) = self.client.relays.get_mut(&self.relayed_addr) else {
566            return Err(Error::ErrConnClosed);
567        };
568        if relay.releasing {
569            return Err(Error::ErrConnClosed);
570        }
571        if relay.transport != RelayTransport::Tcp {
572            return Err(Error::Other(
573                "Connect is for a TCP allocation (RFC 6062); this one relays UDP".to_owned(),
574            ));
575        }
576        if !relay.relays_family_of(&peer_addr.ip()) {
577            return Err(peer_family_mismatch(peer_addr));
578        }
579        if relay.connecting.contains(&peer_addr) {
580            return Err(Error::Other(format!(
581                "a Connect to {peer_addr} is already outstanding"
582            )));
583        }
584        if let Some(until) = relay.connect_hold.get(&peer_addr) {
585            if now < *until {
586                return Err(Error::Other(format!(
587                    "the server could not connect to {peer_addr}; not again within {}s",
588                    CONNECT_RETRY_WAIT.as_secs()
589                )));
590            }
591            relay.connect_hold.remove(&peer_addr);
592        }
593        relay.connecting.insert(peer_addr);
594        match self.connect_with(now, peer_addr, Retry::default()) {
595            Ok(id) => Ok(id),
596            Err(err) => {
597                if let Some(relay) = self.client.relays.get_mut(&self.relayed_addr) {
598                    relay.connecting.remove(&peer_addr);
599                }
600                Err(err)
601            }
602        }
603    }
604
605    pub(super) fn connect_with(
606        &mut self,
607        now: Instant,
608        peer_addr: SocketAddr,
609        retry: Retry,
610    ) -> Result<TransactionId> {
611        let Some(relay) = self.client.relays.get(&self.relayed_addr) else {
612            return Err(Error::ErrConnClosed);
613        };
614        let msg = self.client.build_request(
615            METHOD_CONNECT,
616            vec![Box::new(proto::peeraddr::PeerAddress {
617                ip: peer_addr.ip(),
618                port: peer_addr.port(),
619            })],
620            relay,
621        )?;
622        let credential = Some(relay.credential.clone());
623        self.client.perform_transaction(
624            now,
625            &msg,
626            self.client.turn_server_addr_or_err()?,
627            TransactionType::ConnectRequest(self.relayed_addr, peer_addr, retry),
628            credential,
629        )
630    }
631
632    pub(super) fn handle_connect_response(
633        &mut self,
634        now: Instant,
635        res: Response,
636        peer_addr: SocketAddr,
637        retry: Retry,
638    ) -> Result<()> {
639        if !self.client.relays.contains_key(&self.relayed_addr) {
640            return Ok(());
641        }
642        let id = retry.report_id(res.transaction_id);
643
644        let err = if res.typ.class == CLASS_ERROR_RESPONSE {
645            let mut err = res.error();
646            if self.take_challenge(&res) {
647                if !retry.stale_nonce
648                    && self
649                        .connect_with(now, peer_addr, retry.after_stale_nonce(res.transaction_id))
650                        .is_ok()
651                {
652                    // The same peer again, with the new nonce and a new transaction id.
653                    return Ok(());
654                }
655                err = RequestError::Failed(Error::ErrTryAgain);
656            }
657            err
658        } else {
659            let mut connection_id = ConnectionId::default();
660            match connection_id.get_from(&res) {
661                Ok(()) => {
662                    if let Some(relay) = self.client.relays.get_mut(&self.relayed_addr) {
663                        relay.connecting.remove(&peer_addr);
664                    }
665                    self.client.events.push_back(Event::ConnectResponse(
666                        id,
667                        peer_addr,
668                        connection_id,
669                    ));
670                    return Ok(());
671                }
672                Err(err) => RequestError::Failed(err),
673            }
674        };
675
676        if let Some(relay) = self.client.relays.get_mut(&self.relayed_addr) {
677            relay.connecting.remove(&peer_addr);
678            // 447 (Connection Timeout or Failure): the peer may be tried again, but not
679            // within ten seconds (RFC 6062 §4.3).
680            if err.is(CODE_CONN_TIMEOUT_OR_FAILURE) {
681                relay
682                    .connect_hold
683                    .insert(peer_addr, now.add(CONNECT_RETRY_WAIT));
684            }
685        }
686        // 437: the allocation no longer exists (RFC 8656 §5).
687        let allocation_gone = err.is(CODE_ALLOC_MISMATCH);
688        self.client
689            .events
690            .push_back(Event::ConnectError(id, peer_addr, err));
691        if allocation_gone {
692            self.lose(res.error());
693        }
694        Ok(())
695    }
696
697    /// The protocol side of a new TCP connection to the server that is to carry the peer
698    /// connection `connection_id`: from [`Event::ConnectResponse`] for a connection this
699    /// client asked for, from [`Event::ConnectionAttempt`] for one a peer made (RFC 6062
700    /// §4.3, §4.4).
701    ///
702    /// The application opens the connection itself, to the server address the control
703    /// connection goes to ([`DataConnection::server_addr`]) and from `local_addr`, which must
704    /// not be the control connection's local address. The returned [`DataConnection`] has the
705    /// ConnectionBind request queued, with the CONNECTION-ID and the credential of the
706    /// control connection; the server waits 30 seconds for it.
707    ///
708    /// # Errors
709    ///
710    /// Fails if the allocation is gone, was released, or relays UDP, or if `local_addr` is
711    /// the control connection's.
712    pub fn data_connection(
713        &mut self,
714        now: Instant,
715        connection_id: ConnectionId,
716        local_addr: SocketAddr,
717    ) -> Result<DataConnection> {
718        let Some(relay) = self.client.relays.get(&self.relayed_addr) else {
719            return Err(Error::ErrConnClosed);
720        };
721        if relay.releasing {
722            return Err(Error::ErrConnClosed);
723        }
724        if relay.transport != RelayTransport::Tcp {
725            return Err(Error::Other(
726                "a data connection is for a TCP allocation (RFC 6062); this one relays UDP"
727                    .to_owned(),
728            ));
729        }
730        if local_addr == self.client.local_addr {
731            return Err(Error::Other(
732                "a data connection is made from another local address than the control \
733                 connection's (RFC 6062 section 4.3)"
734                    .to_owned(),
735            ));
736        }
737        DataConnection::new(
738            now,
739            DataConnectionConfig {
740                crypto_provider: self.client.crypto_provider.clone(),
741                server_addr: self.client.turn_server_addr_or_err()?,
742                local_addr,
743                connection_id,
744                software: self.client.software.clone(),
745                credential: relay.credential.clone(),
746            },
747        )
748    }
749
750    fn state(&self) -> Option<&RelayState> {
751        self.client.relays.get(&self.relayed_addr)
752    }
753
754    /// The address events name this allocation by.
755    fn name(&self) -> RelayedAddr {
756        self.state().map_or(self.relayed_addr, RelayState::name)
757    }
758
759    /// Deletes the relayed address of one family from an allocation that has two, with a
760    /// Refresh of LIFETIME 0 naming the family (RFC 8656 §8.1). The other address, with its
761    /// permissions and channel bindings, stays. [`Event::AllocationReleased`] names the
762    /// address when the server confirms. For an allocation with one address this is
763    /// [`Self::close`].
764    ///
765    /// # Errors
766    ///
767    /// Fails if the allocation is gone or was released, or has no relayed address of
768    /// `family`: REQUESTED-ADDRESS-FAMILY may only name a family the allocation holds.
769    pub fn release_family(
770        &mut self,
771        now: Instant,
772        family: proto::reqfamily::RequestedAddressFamily,
773    ) -> Result<()> {
774        let Some(relay) = self.client.relays.get(&self.relayed_addr) else {
775            return Err(Error::ErrConnClosed);
776        };
777        if relay.releasing {
778            return Err(Error::ErrConnClosed);
779        }
780        let ipv6 = family == proto::reqfamily::REQUESTED_FAMILY_IPV6;
781        if (family != proto::reqfamily::REQUESTED_FAMILY_IPV4 && !ipv6)
782            || !relay.addrs.iter().any(|addr| addr.is_ipv6() == ipv6)
783        {
784            return Err(Error::Other(format!(
785                "the allocation has no {family} relayed address"
786            )));
787        }
788        if relay.addrs.len() == 1 {
789            return self.close(now);
790        }
791        self.release_family_with(now, family, Retry::default())
792    }
793
794    pub(super) fn release_family_with(
795        &mut self,
796        now: Instant,
797        family: proto::reqfamily::RequestedAddressFamily,
798        retry: Retry,
799    ) -> Result<()> {
800        let Some(relay) = self.client.relays.get(&self.relayed_addr) else {
801            return Err(Error::ErrConnClosed);
802        };
803        let msg = self.client.build_request(
804            METHOD_REFRESH,
805            vec![
806                Box::new(proto::lifetime::Lifetime(Duration::ZERO)),
807                Box::new(family),
808            ],
809            relay,
810        )?;
811        let credential = Some(relay.credential.clone());
812        let _ = self.client.perform_transaction(
813            now,
814            &msg,
815            self.client.turn_server_addr_or_err()?,
816            TransactionType::FamilyRelease(self.relayed_addr, family.0, retry),
817            credential,
818        );
819        Ok(())
820    }
821
822    /// Handles the response to the Refresh that deletes the relayed address of `family`.
823    pub(super) fn handle_family_release_response(
824        &mut self,
825        now: Instant,
826        res: Response,
827        family: u8,
828        retry: Retry,
829    ) -> Result<()> {
830        let family = proto::reqfamily::RequestedAddressFamily(family);
831        let ipv6 = family == proto::reqfamily::REQUESTED_FAMILY_IPV6;
832        if res.typ.class == CLASS_ERROR_RESPONSE {
833            let mut err = res.error();
834            if self.take_challenge(&res) {
835                if !retry.stale_nonce {
836                    return self.release_family_with(
837                        now,
838                        family,
839                        retry.after_stale_nonce(res.transaction_id),
840                    );
841                }
842                err = RequestError::Failed(Error::ErrTryAgain);
843            }
844            if err.is(CODE_ALLOC_MISMATCH) {
845                self.lose(err);
846                return Ok(());
847            }
848            // 443 (Peer Address Family Mismatch): the server holds no address of that
849            // family (RFC 8656 §8.2), so there is none to keep here. Anything else leaves
850            // the address where it was.
851            if !err.is(CODE_PEER_ADDR_FAMILY_MISMATCH) {
852                let name = self.name();
853                self.client.events.push_back(Event::RefreshError(name, err));
854                return Ok(());
855            }
856        }
857
858        let Some(relay) = self.client.relays.get_mut(&self.relayed_addr) else {
859            return Ok(());
860        };
861        // The other family's address, permissions and channel bindings are untouched.
862        let gone: Vec<RelayedAddr> = relay
863            .addrs
864            .iter()
865            .copied()
866            .filter(|addr| addr.is_ipv6() == ipv6)
867            .collect();
868        relay.addrs.retain(|addr| addr.is_ipv6() != ipv6);
869        relay.perm_map.retain(|ip, _| ip.is_ipv6() != ipv6);
870        let bound: Vec<SocketAddr> = relay
871            .binding_mgr
872            .iter()
873            .map(|b| b.addr)
874            .filter(|addr| addr.is_ipv6() == ipv6)
875            .collect();
876        for addr in bound {
877            relay.binding_mgr.delete_by_addr(&addr);
878        }
879        if relay.addrs.is_empty() {
880            self.released();
881            return Ok(());
882        }
883        for addr in gone {
884            self.client
885                .events
886                .push_back(Event::AllocationReleased(addr));
887        }
888        Ok(())
889    }
890
891    fn send(&mut self, now: Instant, p: &[u8], peer_addr: SocketAddr) -> Result<()> {
892        let Some(relay) = self.client.relays.get_mut(&self.relayed_addr) else {
893            return Err(Error::ErrConnClosed);
894        };
895
896        // What to do about the channel for this peer: bind it, rebind it, or neither; and
897        // whether the data can go on it.
898        let mut bind = None;
899        let mut channel = None;
900        if relay.binding_mgr.find_by_addr(&peer_addr).is_none() {
901            // Out of channel numbers: binding is optional (RFC 8656 §12), the data goes as a
902            // Send indication.
903            let _ = relay.binding_mgr.create(now, peer_addr);
904        }
905        if let Some(b) = relay.binding_mgr.get_by_addr(&peer_addr) {
906            if b.state() == BindingState::Failed && b.retry_at.is_none_or(|at| at <= now) {
907                b.set_state(BindingState::Idle);
908            }
909            match b.state() {
910                BindingState::Idle => {
911                    b.set_state(BindingState::Request);
912                    bind = Some(b.number);
913                }
914                BindingState::Request | BindingState::Failed => {}
915                BindingState::Ready | BindingState::Refresh => {
916                    if !b.is_live(now) {
917                        // The binding ran out on the server, which now drops ChannelData on
918                        // that number: bind it again, the same number to the same peer.
919                        if b.state() == BindingState::Ready {
920                            b.set_state(BindingState::Request);
921                            bind = Some(b.number);
922                        }
923                    } else {
924                        if b.state() == BindingState::Ready
925                            && now.saturating_duration_since(b.refreshed_at()) > BINDING_REFRESH_AGE
926                        {
927                            b.set_state(BindingState::Refresh);
928                            bind = Some(b.number);
929                        }
930                        channel = Some(b.number);
931                    }
932                }
933            }
934        }
935
936        if let Some(channel_number) = channel
937            && p.len() > usize::from(u16::MAX)
938        {
939            // Refused before anything is sent for it, the rebind included.
940            if bind.is_some()
941                && let Some(b) = relay.binding_mgr.get_by_addr(&peer_addr)
942            {
943                b.set_state(BindingState::Ready);
944            }
945            debug!(
946                "{} bytes do not fit ChannelData on {channel_number}",
947                p.len()
948            );
949            return Err(Error::ErrBadChannelDataLength);
950        }
951
952        if let Some(bind_number) = bind {
953            let credential = relay.credential.clone();
954            self.channel_bind(
955                now,
956                self.relayed_addr,
957                peer_addr,
958                bind_number,
959                credential,
960                Retry::default(),
961            )?;
962        }
963
964        match channel {
965            Some(channel_number) => {
966                if let Some(relay) = self.client.relays.get_mut(&self.relayed_addr)
967                    && let Some(b) = relay.binding_mgr.get_by_addr(&peer_addr)
968                {
969                    b.used = true;
970                }
971                self.send_channel_data(now, p, channel_number)
972            }
973            None => self.send_indication(now, p, peer_addr, false),
974        }
975    }
976
977    /// Sends `p` to `peer_addr` in a Send indication (RFC 8656 §11.1).
978    fn send_indication(
979        &mut self,
980        now: Instant,
981        p: &[u8],
982        peer_addr: SocketAddr,
983        dont_fragment: bool,
984    ) -> Result<()> {
985        let mut setters: Vec<Box<dyn Setter>> = vec![
986            Box::new(TransactionId::new()),
987            Box::new(MessageType::new(METHOD_SEND, CLASS_INDICATION)),
988            Box::new(proto::data::Data(p.to_vec())),
989            Box::new(proto::peeraddr::PeerAddress {
990                ip: peer_addr.ip(),
991                port: peer_addr.port(),
992            }),
993        ];
994        if dont_fragment {
995            setters.push(Box::new(proto::dontfrag::DontFragmentAttr));
996        }
997        // RFC 8489 Section 6.1: "Indications MAY include a SOFTWARE attribute"; only when the
998        // application asked for it (`ClientConfig::software_in_indications`).
999        if self.client.software_in_indications && !self.client.software.text.is_empty() {
1000            setters.push(Box::new(self.client.software.clone()));
1001        }
1002        setters.push(Box::new(FINGERPRINT));
1003        let mut msg = Message::new();
1004        msg.build(&setters)?;
1005
1006        // indication has no transaction (fire-and-forget)
1007        self.client
1008            .write_to(now, &msg.raw, self.client.turn_server_addr_or_err()?);
1009        Ok(())
1010    }
1011
1012    // Close closes the connection.
1013    // Any blocked ReadFrom or write_to operations will be unblocked and return errors.
1014    /// Releases the allocation by refreshing it with a zero lifetime (RFC 8656 §8).
1015    ///
1016    /// From here on the allocation is not refreshed and nothing can be sent through it,
1017    /// whatever becomes of the request. [`Event::AllocationReleased`] follows when the server
1018    /// confirms, answers 437 (it no longer had the allocation), or never answers; in that last
1019    /// case the server drops the allocation when its lifetime runs out.
1020    ///
1021    /// # Re-allocating on the same socket after a release
1022    ///
1023    /// An allocation is its 5-tuple's (RFC 8656 §2.2): an [`allocate`](Client::allocate) from
1024    /// the same local address to the same server before [`Event::AllocationReleased`] can be
1025    /// refused with 437 (Allocation Mismatch, §7.2). On a 437 the client "SHOULD pick another
1026    /// client transport address and retry", tries three, and then "SHOULD NOT try to create
1027    /// another allocation on the server for 2 minutes" (§7.4): never retry on the refused
1028    /// 5-tuple. RFC 8656 §8.2 has the server delete the allocation when it answers; coturn
1029    /// keeps it for one second more and answers 437 meanwhile, so wait about two seconds after
1030    /// [`Event::AllocationReleased`] (or use another socket) before allocating there again.
1031    ///
1032    /// # Errors
1033    ///
1034    /// Fails if the refresh request cannot be sent.
1035    pub fn close(&mut self, now: Instant) -> Result<()> {
1036        let Some(relay) = self.client.relays.get_mut(&self.relayed_addr) else {
1037            return Err(Error::ErrConnClosed);
1038        };
1039        if relay.releasing {
1040            return Ok(());
1041        }
1042        relay.releasing = true;
1043        // Whatever else is under way for the allocation no longer matters.
1044        let relayed_addr = self.relayed_addr;
1045        self.client
1046            .tr_map
1047            .delete_where(|tr| tr.relay() == Some(relayed_addr));
1048        self.client.drop_resends_of(relayed_addr);
1049        self.refresh_allocation(now, Duration::from_secs(0))
1050    }
1051
1052    /// Forgets the allocation and everything under way for it.
1053    fn forget(&mut self) {
1054        let relayed_addr = self.relayed_addr;
1055        self.client.relays.remove(&relayed_addr);
1056        self.client
1057            .tr_map
1058            .delete_where(|tr| tr.relay() == Some(relayed_addr));
1059        self.client.drop_resends_of(relayed_addr);
1060    }
1061
1062    /// The server no longer holds the allocation: the client drops its copy, with its
1063    /// permissions and channel bindings, and says so.
1064    pub(super) fn lose(&mut self, err: RequestError) {
1065        let name = self.name();
1066        debug!("allocation {name} lost: {err}");
1067        self.forget();
1068        self.client
1069            .events
1070            .push_back(Event::AllocationLost(name, err));
1071    }
1072
1073    /// The allocation the application released is done with.
1074    pub(super) fn released(&mut self) {
1075        let name = self.name();
1076        debug!("allocation released; relay {name} dropped");
1077        self.forget();
1078        self.client
1079            .events
1080            .push_back(Event::AllocationReleased(name));
1081    }
1082
1083    pub(super) fn create_permissions(
1084        &mut self,
1085        now: Instant,
1086        peer_addrs: &[SocketAddr],
1087        peer_addr_opt: Option<SocketAddr>,
1088        retry: Retry,
1089    ) -> Result<TransactionId> {
1090        let Some(relay) = self.client.relays.get(&self.relayed_addr) else {
1091            return Err(Error::ErrConnClosed);
1092        };
1093        let attrs: Vec<Box<dyn Setter>> = peer_addrs
1094            .iter()
1095            .map(|addr| {
1096                Box::new(proto::peeraddr::PeerAddress {
1097                    ip: addr.ip(),
1098                    port: addr.port(),
1099                }) as Box<dyn Setter>
1100            })
1101            .collect();
1102        let msg = self
1103            .client
1104            .build_request(METHOD_CREATE_PERMISSION, attrs, relay)?;
1105        let credential = Some(relay.credential.clone());
1106        self.client.perform_transaction(
1107            now,
1108            &msg,
1109            self.client.turn_server_addr_or_err()?,
1110            TransactionType::CreatePermissionRequest(
1111                self.relayed_addr,
1112                peer_addr_opt,
1113                peer_addrs.to_vec(),
1114                retry,
1115            ),
1116            credential,
1117        )
1118    }
1119
1120    /// Whether the error response `res` is one the request can be sent again after, and takes
1121    /// what that needs from it (RFC 8489 §9.2.5, RFC 8656 §4.4): the nonce of a 438 (Stale
1122    /// Nonce), with its realm, password algorithms and user name form, or the same of a 401
1123    /// (Unauthenticated) to a request that carried no credential because the server had not
1124    /// asked for one when it made the allocation, or that names another realm.
1125    ///
1126    /// Not after a response whose nonce cookie announces PASSWORD-ALGORITHMS when it has none
1127    /// (a bid-down), not when none of the offered algorithms is supported, and not after a
1128    /// 401 to the very credentials the request carried.
1129    fn take_challenge(&mut self, res: &Response) -> bool {
1130        let mut code = ErrorCodeAttribute::default();
1131        if code.get_from(res).is_err()
1132            || (code.code != CODE_STALE_NONCE && code.code != CODE_UNAUTHORIZED)
1133        {
1134            return false;
1135        }
1136        let Some(relay) = self.client.relays.get_mut(&self.relayed_addr) else {
1137            return false;
1138        };
1139        match relay.credential.challenged(
1140            &res.request(),
1141            &res.msg,
1142            self.client.crypto_provider.crypto(),
1143        ) {
1144            Ok(credential) => {
1145                relay.credential = Arc::new(credential);
1146                debug!("{}: took the server's realm and nonce", code.code.0);
1147                true
1148            }
1149            Err(refused) => {
1150                warn!("{} is not answered: {refused}", code.code.0);
1151                false
1152            }
1153        }
1154    }
1155
1156    pub(super) fn handle_create_permission_response(
1157        &mut self,
1158        now: Instant,
1159        res: Response,
1160        peer_addr_opt: Option<SocketAddr>,
1161        peer_addrs: Vec<SocketAddr>,
1162        retry: Retry,
1163    ) -> Result<()> {
1164        if !self.client.relays.contains_key(&self.relayed_addr) {
1165            return Ok(());
1166        }
1167        let id = retry.report_id(res.transaction_id);
1168
1169        if res.typ.class != CLASS_ERROR_RESPONSE {
1170            let Some(relay) = self.client.relays.get_mut(&self.relayed_addr) else {
1171                return Ok(());
1172            };
1173            // The server installed or refreshed every permission the request named, for 300 s
1174            // from now (RFC 8656 §9, §10.3).
1175            let until = now.add(PERM_LIFETIME);
1176            if let Some(peer_addr) = peer_addr_opt {
1177                if let Some(perm) = relay.perm_map.get_mut(&peer_addr.ip()) {
1178                    perm.permit_until(until);
1179                    self.client
1180                        .events
1181                        .push_back(Event::CreatePermissionResponse(id, peer_addr));
1182                }
1183            } else {
1184                for peer_addr in &peer_addrs {
1185                    if let Some(perm) = relay.perm_map.get_mut(&peer_addr.ip())
1186                        && perm.state() == PermState::Permitted
1187                    {
1188                        perm.permit_until(until);
1189                    }
1190                }
1191            }
1192            return Ok(());
1193        }
1194
1195        let mut err = res.error();
1196        if self.take_challenge(&res) {
1197            if !retry.stale_nonce {
1198                // The same peers again, with the new nonce and a new transaction id.
1199                self.create_permissions(
1200                    now,
1201                    &peer_addrs,
1202                    peer_addr_opt,
1203                    retry.after_stale_nonce(res.transaction_id),
1204                )?;
1205                return Ok(());
1206            }
1207            err = RequestError::Failed(Error::ErrTryAgain);
1208        }
1209
1210        // 437 (Allocation Mismatch) to anything but an Allocate: the allocation no longer
1211        // exists (RFC 8656 §5).
1212        let allocation_gone = err.is(CODE_ALLOC_MISMATCH);
1213        if let Some(peer_addr) = peer_addr_opt {
1214            if let Some(relay) = self.client.relays.get_mut(&self.relayed_addr) {
1215                relay.forget_unless_permitted(peer_addr.ip(), now);
1216            }
1217            self.client
1218                .events
1219                .push_back(Event::CreatePermissionError(id, err));
1220            if allocation_gone {
1221                self.lose(res.error());
1222            }
1223        } else if allocation_gone {
1224            self.lose(err);
1225        } else if !res.msg.is_authenticated()
1226            && self
1227                .client
1228                .relays
1229                .get(&self.relayed_addr)
1230                .is_some_and(RelayState::is_signed)
1231        {
1232            // An unsigned 401 or 438 is all a server can say about a credential or nonce it
1233            // does not accept, and all anyone else can forge. It ends this refresh, not the
1234            // permissions: they last what the server last granted, and are asked for again.
1235            debug!("permission refresh failed ({err}); the permissions keep their time");
1236        } else if peer_addrs.len() > 1 {
1237            // The server refuses a request for one address it will not permit, and with it
1238            // the refresh of every other address the request named. Each is asked for on its
1239            // own, so only the refused ones end.
1240            debug!("permission refresh refused ({err}); refreshing each address on its own");
1241            for peer_addr in &peer_addrs {
1242                self.create_permissions(now, &[*peer_addr], None, Retry::default())?;
1243            }
1244        } else if let Some(peer_addr) = peer_addrs.first() {
1245            // The permission is not refreshed: it ends on the server within 300 s of its last
1246            // refresh, and here now, so nothing more is sent to a peer the server will drop.
1247            if let Some(relay) = self.client.relays.get_mut(&self.relayed_addr) {
1248                relay.perm_map.remove(&peer_addr.ip());
1249            }
1250            let name = self.name();
1251            self.client
1252                .events
1253                .push_back(Event::PermissionLost(name, peer_addr.ip(), err));
1254        }
1255
1256        Ok(())
1257    }
1258
1259    pub(super) fn refresh_allocation(&mut self, now: Instant, lifetime: Duration) -> Result<()> {
1260        self.refresh_allocation_with(now, lifetime, Retry::default())
1261    }
1262
1263    pub(super) fn refresh_allocation_with(
1264        &mut self,
1265        now: Instant,
1266        lifetime: Duration,
1267        retry: Retry,
1268    ) -> Result<()> {
1269        let Some(relay) = self.client.relays.get(&self.relayed_addr) else {
1270            return Err(Error::ErrConnClosed);
1271        };
1272        let msg = self.client.build_request(
1273            METHOD_REFRESH,
1274            vec![Box::new(proto::lifetime::Lifetime(lifetime))],
1275            relay,
1276        )?;
1277        let credential = Some(relay.credential.clone());
1278        let _ = self.client.perform_transaction(
1279            now,
1280            &msg,
1281            self.client.turn_server_addr_or_err()?,
1282            TransactionType::RefreshRequest(self.relayed_addr, lifetime, retry),
1283            credential,
1284        );
1285        Ok(())
1286    }
1287
1288    /// Handles a Refresh response as if it answered a first request for the current lifetime.
1289    #[cfg(test)]
1290    pub(super) fn handle_refresh_allocation_response(
1291        &mut self,
1292        now: Instant,
1293        res: Message,
1294    ) -> Result<()> {
1295        let lifetime = self
1296            .client
1297            .relays
1298            .get(&self.relayed_addr)
1299            .map_or(Duration::ZERO, |relay| relay.lifetime);
1300        self.handle_refresh_response(now, Response::unchecked(&res), lifetime, Retry::default())
1301    }
1302
1303    /// Handles the response to a Refresh that asked for `lifetime`.
1304    pub(super) fn handle_refresh_response(
1305        &mut self,
1306        now: Instant,
1307        res: Response,
1308        lifetime: Duration,
1309        retry: Retry,
1310    ) -> Result<()> {
1311        if !self.client.relays.contains_key(&self.relayed_addr) {
1312            return Ok(());
1313        }
1314
1315        if res.typ.class == CLASS_ERROR_RESPONSE {
1316            let mut err = res.error();
1317            if self.take_challenge(&res) {
1318                if !retry.stale_nonce {
1319                    // The same LIFETIME again (zero for a release), with the new nonce and a
1320                    // new transaction id.
1321                    return self.refresh_allocation_with(
1322                        now,
1323                        lifetime,
1324                        retry.after_stale_nonce(res.transaction_id),
1325                    );
1326                }
1327                err = RequestError::Failed(Error::ErrTryAgain);
1328            }
1329            self.refresh_failed(now, lifetime, err);
1330            return Ok(());
1331        }
1332
1333        // Getting lifetime from response
1334        let mut updated_lifetime = proto::lifetime::Lifetime::default();
1335        if let Err(err) = updated_lifetime.get_from(&res) {
1336            // A success that does not say for how long: nothing to extend the allocation by.
1337            self.refresh_failed(now, lifetime, RequestError::Failed(err));
1338            return Ok(());
1339        }
1340
1341        // A zero lifetime is the server confirming deallocation — the reply to the refresh
1342        // `close()` sends. The allocation no longer exists, so neither should the relay:
1343        // leaving it in the map means it keeps reporting refresh deadlines for something that
1344        // is gone, and keeps trying to refresh it.
1345        if updated_lifetime.0.is_zero() {
1346            if lifetime.is_zero() {
1347                self.released();
1348            } else {
1349                self.lose(RequestError::Failed(Error::ErrFailedToRefreshAllocation));
1350            }
1351            return Ok(());
1352        }
1353
1354        if let Some(relay) = self.client.relays.get_mut(&self.relayed_addr) {
1355            relay.lifetime = updated_lifetime.0;
1356            relay.expires_at = now.add(relay.lifetime);
1357            relay.refresh_alloc_timer = now.add(allocation_refresh_interval(
1358                relay.lifetime,
1359                relay.allocation_refresh_interval_cap,
1360            ));
1361            debug!("updated lifetime: {} seconds", relay.lifetime.as_secs());
1362        }
1363
1364        Ok(())
1365    }
1366
1367    /// A Refresh that asked for `lifetime` got no usable answer, or an error other than a
1368    /// challenge it could be sent again after.
1369    pub(super) fn refresh_failed(&mut self, now: Instant, lifetime: Duration, err: RequestError) {
1370        let Some(relay) = self.client.relays.get_mut(&self.relayed_addr) else {
1371            return;
1372        };
1373
1374        if lifetime.is_zero() || relay.releasing {
1375            // The application released the allocation, so it is not refreshed again whatever
1376            // the server said: a 437 means it was gone already (RFC 8656 §8.3), and after
1377            // anything else, or silence, the server drops it when its lifetime runs out.
1378            if matches!(err, RequestError::Rejected(_)) && !err.is(CODE_ALLOC_MISMATCH) {
1379                let name = relay.name();
1380                self.client.events.push_back(Event::RefreshError(name, err));
1381            }
1382            self.released();
1383            return;
1384        }
1385
1386        // 437 (Allocation Mismatch): the allocation no longer exists (RFC 8656 §5, §8.3). So
1387        // it does, for the client, once its lifetime ran out with no Refresh answered.
1388        if err.is(CODE_ALLOC_MISMATCH) || now >= relay.expires_at {
1389            self.lose(err);
1390            return;
1391        }
1392
1393        // The allocation still has time: the next Refresh does not wait for the usual
1394        // interval, which may end at the expiry itself.
1395        let remaining = relay.expires_at.saturating_duration_since(now);
1396        let sooner = now.add((remaining / 2).max(MIN_ALLOC_REFRESH_INTERVAL));
1397        if sooner < relay.refresh_alloc_timer {
1398            relay.refresh_alloc_timer = sooner;
1399        }
1400        let name = relay.name();
1401        self.client.events.push_back(Event::RefreshError(name, err));
1402    }
1403
1404    pub(super) fn refresh_permissions(&mut self, now: Instant) -> Result<()> {
1405        if let Some(relay) = self.client.relays.get_mut(&self.relayed_addr) {
1406            // The port of an XOR-PEER-ADDRESS in a CreatePermission is ignored (RFC 8656 §9.1).
1407            let addrs: Vec<SocketAddr> = relay
1408                .perm_map
1409                .keys()
1410                .map(|ip| SocketAddr::new(*ip, 0))
1411                .collect();
1412            if addrs.is_empty() {
1413                debug!("no permission to refresh");
1414                return Ok(());
1415            }
1416            for peers in addrs.chunks(MAX_PEERS_PER_CREATE_PERMISSION) {
1417                let _ = self.create_permissions(now, peers, None, Retry::default())?;
1418            }
1419            Ok(())
1420        } else {
1421            Err(Error::ErrConnClosed)
1422        }
1423    }
1424
1425    #[allow(clippy::too_many_arguments)] // the retry state rides with the request it repeats
1426    fn channel_bind(
1427        &mut self,
1428        now: Instant,
1429        relayed_addr: RelayedAddr,
1430        bind_addr: SocketAddr,
1431        bind_number: u16,
1432        credential: Arc<Credential>,
1433        retry: Retry,
1434    ) -> Result<()> {
1435        let msg = self.client.build_request_with(
1436            METHOD_CHANNEL_BIND,
1437            vec![
1438                Box::new(proto::peeraddr::PeerAddress {
1439                    ip: bind_addr.ip(),
1440                    port: bind_addr.port(),
1441                }),
1442                Box::new(proto::channum::ChannelNumber(bind_number)),
1443            ],
1444            &credential,
1445        )?;
1446        let turn_server_addr = self.client.turn_server_addr_or_err()?;
1447
1448        if let Some(relay) = self.client.relays.get_mut(&relayed_addr)
1449            && let Some(b) = relay.binding_mgr.get_by_addr(&bind_addr)
1450        {
1451            // From here on the server may hold the binding, whatever comes back.
1452            b.last_request_at = Some(now);
1453        }
1454
1455        debug!("UDPConn.bind call PerformTransaction 1");
1456        let _ = self.client.perform_transaction(
1457            now,
1458            &msg,
1459            turn_server_addr,
1460            TransactionType::ChannelBindRequest(relayed_addr, bind_addr, retry),
1461            Some(credential),
1462        );
1463
1464        Ok(())
1465    }
1466
1467    /// Sends the ChannelBind for `bind_addr` again, on the channel number it already has and
1468    /// with the allocation's current nonce and key.
1469    pub(super) fn rebind_channel(
1470        &mut self,
1471        now: Instant,
1472        bind_addr: SocketAddr,
1473        retry: Retry,
1474    ) -> Result<()> {
1475        let relay = self
1476            .client
1477            .relays
1478            .get(&self.relayed_addr)
1479            .ok_or(Error::ErrConnClosed)?;
1480        let bind_number = relay
1481            .binding_mgr
1482            .find_by_addr(&bind_addr)
1483            .map(|b| b.number)
1484            .ok_or(Error::ErrChannelBindNotFound)?;
1485        let credential = relay.credential.clone();
1486        self.channel_bind(
1487            now,
1488            self.relayed_addr,
1489            bind_addr,
1490            bind_number,
1491            credential,
1492            retry,
1493        )
1494    }
1495
1496    pub(super) fn handle_channel_bind_response(
1497        &mut self,
1498        now: Instant,
1499        res: Response,
1500        bind_addr: SocketAddr,
1501        retry: Retry,
1502    ) -> Result<()> {
1503        if !self.client.relays.contains_key(&self.relayed_addr) {
1504            return Ok(());
1505        }
1506
1507        if res.typ.class != CLASS_ERROR_RESPONSE {
1508            let Some(relay) = self.client.relays.get_mut(&self.relayed_addr) else {
1509                return Ok(());
1510            };
1511            if let Some(b) = relay.binding_mgr.get_by_addr(&bind_addr) {
1512                b.set_refreshed_at(now);
1513                b.set_state(BindingState::Ready);
1514                b.bound = true;
1515                b.used = false;
1516                b.retry_at = None;
1517                debug!("channel binding successful: {}", bind_addr);
1518                if relay.bindings_timer.is_none() {
1519                    relay.bindings_timer = Some(now.add(BINDING_SWEEP_INTERVAL));
1520                }
1521            }
1522            // A ChannelBind also installs or refreshes the permission for the peer's address
1523            // (RFC 8656 §12.3).
1524            if let Some(perm) = relay.perm_map.get_mut(&bind_addr.ip()) {
1525                perm.permit_until(now.add(PERM_LIFETIME));
1526            }
1527            return Ok(());
1528        }
1529
1530        let mut err = res.error();
1531        if self.take_challenge(&res) {
1532            if !retry.stale_nonce
1533                && self
1534                    .rebind_channel(now, bind_addr, retry.after_stale_nonce(res.transaction_id))
1535                    .is_ok()
1536            {
1537                // Sent again with the new nonce; the binding keeps waiting on it.
1538                return Ok(());
1539            }
1540            err = RequestError::Failed(Error::ErrTryAgain);
1541        }
1542        self.channel_bind_failed(now, bind_addr, err);
1543        Ok(())
1544    }
1545
1546    /// A ChannelBind for `bind_addr` failed with `err`: an error response, or responses the
1547    /// client could not accept.
1548    pub(super) fn channel_bind_failed(
1549        &mut self,
1550        now: Instant,
1551        bind_addr: SocketAddr,
1552        err: RequestError,
1553    ) {
1554        warn!("ChannelBind for {bind_addr} failed: {err}");
1555
1556        // The data keeps going as Send indications, and the ChannelBind is not sent again
1557        // with every one of them.
1558        if let Some(relay) = self.client.relays.get_mut(&self.relayed_addr)
1559            && let Some(b) = relay.binding_mgr.get_by_addr(&bind_addr)
1560        {
1561            b.set_state(BindingState::Failed);
1562            b.retry_at = Some(now.add(CHANNEL_BIND_RETRY_INTERVAL));
1563        }
1564
1565        // 437: the allocation no longer exists (RFC 8656 §5). 400: the client's channels and
1566        // the server's are out of step, and RFC 8656 §12.3 recommends deleting the allocation
1567        // and starting afresh.
1568        let allocation_gone = err.is(CODE_ALLOC_MISMATCH);
1569        let out_of_step = err.is(CODE_BAD_REQUEST);
1570        let again = match &err {
1571            RequestError::Rejected(response) => RequestError::Rejected(response.clone()),
1572            RequestError::Failed(_) => RequestError::Failed(Error::ErrTryAgain),
1573        };
1574        let name = self.name();
1575        self.client
1576            .events
1577            .push_back(Event::ChannelBindError(name, bind_addr, err));
1578        if allocation_gone {
1579            self.lose(again);
1580        } else if out_of_step {
1581            // Released on the server and dropped here at once: its state cannot be trusted.
1582            let credential = self
1583                .client
1584                .relays
1585                .get(&self.relayed_addr)
1586                .map(|relay| relay.credential.clone());
1587            if let Some(credential) = credential {
1588                let _ = self.client.release_orphan(now, &credential);
1589            }
1590            self.lose(again);
1591        }
1592    }
1593
1594    /// A ChannelBind for `bind_addr` and the one sent after it both went unanswered: the next
1595    /// send to that peer binds it again.
1596    pub(super) fn channel_bind_timed_out(&mut self, bind_addr: SocketAddr) {
1597        if let Some(relay) = self.client.relays.get_mut(&self.relayed_addr)
1598            && let Some(b) = relay.binding_mgr.get_by_addr(&bind_addr)
1599        {
1600            b.set_state(BindingState::Idle);
1601        }
1602    }
1603
1604    fn send_channel_data(&mut self, now: Instant, data: &[u8], channel_number: u16) -> Result<()> {
1605        let mut ch_data = proto::chandata::ChannelData {
1606            data: data.to_vec(),
1607            number: proto::channum::ChannelNumber(channel_number),
1608            ..Default::default()
1609        };
1610        ch_data.encode()?;
1611
1612        self.client
1613            .write_to(now, &ch_data.raw, self.client.turn_server_addr_or_err()?);
1614
1615        Ok(())
1616    }
1617}
1618
1619/// How long after a 447 the same peer is not connected to again (RFC 6062 §4.3: "at least 10
1620/// seconds").
1621const CONNECT_RETRY_WAIT: Duration = Duration::from_secs(10);
1622
1623/// The error for datagram sends on a TCP allocation, whose data goes over data connections.
1624fn not_a_udp_allocation() -> Error {
1625    Error::Other(
1626        "this is a TCP allocation (RFC 6062): data goes over a data connection per peer".to_owned(),
1627    )
1628}
1629
1630/// The error for a peer no relayed address of the allocation can reach.
1631fn peer_family_mismatch(peer_addr: SocketAddr) -> Error {
1632    Error::Other(format!(
1633        "{peer_addr} is not of the address family of a relayed address of the allocation"
1634    ))
1635}