rtci_turn/client/mod.rs
1//! The Sans-I/O TURN client.
2//!
3//! Using a relay takes three steps: Allocate to obtain a public address, CreatePermission for
4//! each peer you intend to exchange data with, and then Send/Data indications (or a bound channel)
5//! to move bytes. Each step is a STUN transaction, so every [`Event`] carries the
6//! transaction id of the request it answers.
7//!
8//! The three address kinds are easy to confuse: [`RelayedAddr`] is what peers send to,
9//! [`ReflexiveAddr`] is how the server sees this client, and [`PeerAddr`] is the far end.
10#[cfg(test)]
11mod client_allocate_options_test;
12#[cfg(test)]
13mod client_allocate_test;
14#[cfg(test)]
15mod client_channel_test;
16#[cfg(test)]
17mod client_data_source_test;
18#[cfg(test)]
19mod client_lifecycle_test;
20#[cfg(test)]
21mod client_permission_refresh_test;
22#[cfg(test)]
23mod client_permission_test;
24#[cfg(test)]
25mod client_retry_test;
26#[cfg(test)]
27mod client_software_mtu_test;
28#[cfg(test)]
29mod client_stale_nonce_test;
30#[cfg(test)]
31mod client_stun8489_config_test;
32#[cfg(test)]
33mod client_stun8489_test;
34#[cfg(test)]
35mod client_tcp_allocation_test;
36#[cfg(test)]
37mod client_test;
38#[cfg(test)]
39mod test_server;
40
41mod allocation;
42/// Channel bindings, which replace the 36-byte Data indication header with a 4-byte one.
43pub mod binding;
44pub(crate) mod credential;
45/// The data connections of a TCP allocation (RFC 6062).
46pub mod data_connection;
47mod error;
48/// Per-peer send permissions, which a relay requires before it will forward to an address.
49pub mod permission;
50mod proto;
51/// A live allocation on the server, and sending or receiving through it.
52pub mod relay;
53/// Outstanding request tracking, with the RFC's retransmission schedule.
54pub mod transaction;
55
56use bytes::BytesMut;
57use crypto::RTCCryptoProvider;
58use log::{debug, trace};
59use std::collections::{HashMap, VecDeque};
60use std::net::{IpAddr, Ipv4Addr, SocketAddr, SocketAddrV4};
61use std::sync::Arc;
62use std::time::{Duration, Instant};
63
64use stun::alternate::RedirectGuard;
65/// The redirection of an authenticated 300 (Try Alternate): see
66/// [`ErrorResponse::try_alternate`] and [`Client::follow_alternate`].
67pub use stun::alternate::TryAlternate;
68use stun::attributes::*;
69#[cfg(test)]
70use stun::integrity::*;
71use stun::message::*;
72use stun::textattrs::*;
73use stun::timer::Schedule;
74use stun::validated::{Rejection, ValidatedMessage, Validator};
75use stun::xoraddr::*;
76
77use allocation::FamilyBlock;
78pub use allocation::{AllocateOptions, RelayTransport};
79use credential::{Credential, Login};
80pub use error::{ErrorResponse, RequestError};
81use transaction::*;
82
83use crate::client::relay::{Relay, RelayState};
84use crate::proto::chandata::*;
85use crate::proto::channum::ChannelNumber;
86use crate::proto::connid::ConnectionId;
87use crate::proto::data::*;
88use crate::proto::icmp::Icmp;
89use crate::proto::lifetime::Lifetime;
90use crate::proto::peeraddr::*;
91#[cfg(test)]
92use crate::proto::{PROTO_UDP, relayaddr::RelayedAddress, reqtrans::RequestedTransport};
93use shared::error::{Error, Result};
94use shared::util::lookup_host;
95use shared::{TransportContext, TransportMessage, TransportProtocol};
96use stun::error_code::ErrorCodeAttribute;
97use stun::fingerprint::FINGERPRINT;
98
99/// The comprehension-required attributes the TURN client understands in what it receives:
100/// those of STUN, of TURN (RFC 8656 §18) and of TCP allocations (RFC 6062 §6.2), and the three
101/// of RFC 3489 that old STUN servers still put in a Binding response. A message with any other
102/// is not processed (RFC 8489 §6.3.2 to §6.3.4).
103pub(crate) const KNOWN_ATTRIBUTES: &[AttrType] = &[
104 ATTR_MAPPED_ADDRESS,
105 ATTR_USERNAME,
106 ATTR_MESSAGE_INTEGRITY,
107 ATTR_ERROR_CODE,
108 ATTR_UNKNOWN_ATTRIBUTES,
109 ATTR_REALM,
110 ATTR_NONCE,
111 ATTR_MESSAGE_INTEGRITY_SHA256,
112 ATTR_PASSWORD_ALGORITHM,
113 ATTR_USER_HASH,
114 ATTR_XORMAPPED_ADDRESS,
115 ATTR_CHANNEL_NUMBER,
116 ATTR_LIFETIME,
117 ATTR_XOR_PEER_ADDRESS,
118 ATTR_DATA,
119 ATTR_XOR_RELAYED_ADDRESS,
120 ATTR_REQUESTED_ADDRESS_FAMILY,
121 ATTR_EVEN_PORT,
122 ATTR_REQUESTED_TRANSPORT,
123 ATTR_DONT_FRAGMENT,
124 ATTR_RESERVATION_TOKEN,
125 ATTR_CONNECTION_ID,
126 ATTR_SOURCE_ADDRESS,
127 ATTR_CHANGED_ADDRESS,
128 AttrType(0x000b),
129];
130
131/// The validator every received STUN message goes through.
132pub(crate) fn validator() -> Validator<'static> {
133 Validator::new().known_attributes(KNOWN_ATTRIBUTES)
134}
135
136/// A response that passed the checks, and the request it answers.
137pub(crate) struct Response {
138 /// The response, reduced to the attributes ahead of its integrity attribute: nothing
139 /// that follows it is read (RFC 8489 §9).
140 pub(crate) msg: ValidatedMessage,
141 /// The request as it was sent.
142 pub(crate) request: BytesMut,
143}
144
145impl Response {
146 /// The request the response answers, decoded.
147 pub(crate) fn request(&self) -> Message {
148 let mut request = Message::new();
149 request.raw = self.request.to_vec();
150 // What the client built decodes; if it does not, the request counts as unsigned.
151 let _ = request.decode();
152 request
153 }
154
155 /// The error of an error response.
156 pub(crate) fn error(&self) -> RequestError {
157 RequestError::of(&self.msg)
158 }
159
160 /// A response nothing checked, to a request without a credential: for tests that hand a
161 /// handler its response directly.
162 #[cfg(test)]
163 pub(crate) fn unchecked(msg: &Message) -> Self {
164 Self {
165 msg: Validator::new()
166 .unauthenticated(msg)
167 .expect("the response has no wrong FINGERPRINT"),
168 request: BytesMut::new(),
169 }
170 }
171}
172
173impl std::ops::Deref for Response {
174 type Target = Message;
175
176 fn deref(&self) -> &Message {
177 &self.msg
178 }
179}
180
181/// Why a transaction ended without a response the client could act on.
182pub(crate) enum Failure {
183 /// Nothing arrived in time.
184 Timeout,
185 /// Every response that arrived failed the integrity check, or, over a reliable
186 /// transport, one did (RFC 8489 §9.2.5).
187 IntegrityViolation,
188 /// The response carried comprehension-required attributes the client does not know
189 /// (RFC 8489 §6.3.3, §6.3.4).
190 UnknownAttributes(Vec<AttrType>),
191}
192
193impl Failure {
194 fn error(&self) -> Error {
195 match self {
196 Self::Timeout => Error::ErrTimeout,
197 Self::IntegrityViolation => Error::ErrIntegrityMismatch,
198 Self::UnknownAttributes(unknown) => {
199 Error::Other(Rejection::UnknownAttributes(unknown.clone()).to_string())
200 }
201 }
202 }
203}
204
205/// The retransmission timer of the client's requests (RFC 8489 §6.2), the one `rtci-stun` has
206/// ([`stun::timer`]). The default is the RFC's.
207///
208/// Over UDP a request is sent again after RTO, then after twice that, and so on, `rc` times in
209/// all, and its transaction fails `rm` x RTO after the last: with the defaults and an RTO of
210/// 500 ms, at 0, 0.5, 1.5, 3.5, 7.5, 15.5 and 31.5 s, failing at 39.5 s. Over TCP or TLS it is
211/// sent once and fails after `ti`. The initial RTO is [`ClientConfig::rto_in_ms`].
212#[derive(Debug, Clone, Copy, PartialEq, Eq)]
213pub struct RetransmissionConfig {
214 /// Rc: how many times a request is sent over UDP (RFC 8489 §6.2.1; 7). Values below 1
215 /// are 1.
216 pub rc: u32,
217 /// Rm: the transaction fails Rm x RTO after the last request (RFC 8489 §6.2.1; 16).
218 pub rm: u32,
219 /// Ti: how long a request waits over a reliable transport (RFC 8489 §6.2.2; 39.5 s).
220 pub ti: Duration,
221 /// Whether the RTO follows the server's round-trip times as RFC 6298 computes it, never
222 /// below the initial RTO, kept per server and dropped after ten minutes without a
223 /// transaction (RFC 8489 §6.2.1; on). Off: every transaction starts at the initial RTO.
224 pub rto_estimation: bool,
225 /// Most transactions outstanding to one server (RFC 8489 §6.2; 10). A request past the
226 /// limit is sent when one of them ends. `0` lifts the limit, for an application that
227 /// limits its rate some other way.
228 pub max_outstanding_transactions: usize,
229}
230
231impl Default for RetransmissionConfig {
232 fn default() -> Self {
233 let schedule = Schedule::default();
234 Self {
235 rc: schedule.rc,
236 rm: schedule.rm,
237 ti: schedule.ti,
238 rto_estimation: true,
239 max_outstanding_transactions: stun::timer::DEFAULT_MAX_OUTSTANDING,
240 }
241 }
242}
243const MAX_DATA_BUFFER_SIZE: usize = u16::MAX as usize; // message size limit for Chromium
244const MAX_READ_QUEUE_SIZE: usize = 1024;
245
246/// The public address the TURN server allocated on this client's behalf.
247///
248/// Peers send here; the server forwards to the client.
249pub type RelayedAddr = SocketAddr;
250/// The client's own address as seen by the server — its server-reflexive address.
251pub type ReflexiveAddr = SocketAddr;
252/// The address of a remote peer the client exchanges data with through the relay.
253pub type PeerAddr = SocketAddr;
254
255#[derive(Debug)]
256/// What the client produces in response to inbound datagrams and elapsed time.
257///
258/// A variant that answers a request the caller made carries the [`TransactionId`] that
259/// request returned, so responses can be matched to requests. A variant about an allocation
260/// as a whole (lost, released, a refresh or a channel bind the client made by itself) names
261/// the allocation by its relayed address instead.
262#[non_exhaustive]
263pub enum Event {
264 /// A request exhausted its retransmissions without a response.
265 ///
266 /// A request whose every response was discarded for its integrity, or whose response
267 /// carried attributes the client must but does not understand, does not end here: it is
268 /// reported by the error event of its kind ([`Event::AllocateError`],
269 /// [`Event::RefreshError`], ...) with [`RequestError::Failed`], an
270 /// `ErrIntegrityMismatch` in the first case (RFC 8489 §9.2.5: an integrity violation is
271 /// not a timeout).
272 TransactionTimeout(TransactionId),
273
274 /// A STUN Binding succeeded, reporting this client's server-reflexive address.
275 BindingResponse(TransactionId, ReflexiveAddr),
276 /// A STUN Binding failed.
277 BindingError(TransactionId, Error),
278
279 /// An Allocate succeeded; the relayed address is now usable.
280 AllocateResponse(TransactionId, RelayedAddr),
281 /// An Allocate failed — commonly authentication, or the server being out of ports. The
282 /// error carries the server's code (RFC 8656 §7.4 says what each one asks of the client).
283 AllocateError(TransactionId, RequestError),
284
285 /// A CreatePermission succeeded; the relay will now forward to and from this peer.
286 CreatePermissionResponse(TransactionId, PeerAddr),
287 /// A CreatePermission failed; there is no permission for the peer.
288 CreatePermissionError(TransactionId, RequestError),
289
290 /// The server no longer holds the allocation: it answered 437 (Allocation Mismatch) to a
291 /// request for it (RFC 8656 §5), or the allocation's lifetime ran out with no Refresh
292 /// answered. The client has dropped it, with its permissions and channel bindings;
293 /// [`Client::relay`] no longer finds it.
294 AllocationLost(RelayedAddr, RequestError),
295 /// An allocation the application released with [`Relay::close`] is done with: the server
296 /// confirmed, no longer had it, or never answered.
297 AllocationReleased(RelayedAddr),
298 /// A Refresh of the allocation failed. The allocation is kept and refreshed again while
299 /// its lifetime lasts; [`Event::AllocationLost`] follows if that runs out.
300 RefreshError(RelayedAddr, RequestError),
301 /// The server refused to refresh the permission for a peer's IP address. The client has
302 /// dropped it: nothing is sent to that address until a new permission is created.
303 PermissionLost(RelayedAddr, IpAddr, RequestError),
304 /// A Connect succeeded: the server has a TCP connection to the peer, named by the
305 /// CONNECTION-ID (RFC 6062 §4.3). The application now opens a new TCP connection to the
306 /// server and binds it with [`Relay::data_connection`]; the server gives it 30 seconds.
307 ConnectResponse(TransactionId, PeerAddr, ConnectionId),
308 /// A Connect failed. After a 447 (Connection Timeout or Failure) the same peer can be
309 /// tried again, ten seconds later at the earliest.
310 ConnectError(TransactionId, PeerAddr, RequestError),
311 /// A peer with a permission connected to the relayed address of a TCP allocation
312 /// (RFC 6062 §4.4). To accept, the application opens a new TCP connection to the server
313 /// and binds it with [`Relay::data_connection`] within 30 seconds; to refuse, it does
314 /// nothing.
315 ConnectionAttempt(RelayedAddr, PeerAddr, ConnectionId),
316 /// A datagram the server relayed to this peer was answered with an ICMP error, for
317 /// example "fragmentation needed" with the path MTU after a send with DONT-FRAGMENT
318 /// (RFC 8656 §11.6). The peer address tells whether the type and code are ICMPv4 or
319 /// ICMPv6.
320 IcmpError(PeerAddr, Icmp),
321 /// A ChannelBind for a peer failed. Data to it keeps going as Send indications, and the
322 /// bind is tried again later. After a 437, or a 400 (the channels of client and server are
323 /// out of step, RFC 8656 §12.3), [`Event::AllocationLost`] follows.
324 ChannelBindError(RelayedAddr, PeerAddr, RequestError),
325
326 /// Data arrived from a peer through the relay.
327 ///
328 /// The channel number is `Some` when it came as ChannelData and `None` when it came as a
329 /// Data indication.
330 DataIndicationOrChannelData(Option<ChannelNumber>, PeerAddr, BytesMut),
331}
332
333/// ClientConfig is a bag of config parameters for Client.
334pub struct ClientConfig {
335 /// The STUN server to use for Binding requests, as `host:port`. May be empty.
336 pub stun_serv_addr: String, // STUN server address (e.g. "stun.abc.com:3478")
337 /// The TURN server to allocate from, as `host:port`.
338 pub turn_serv_addr: String, // TURN server address (e.g. "turn.abc.com:3478")
339 /// The local address the client sends from.
340 pub local_addr: SocketAddr,
341 /// Whether to reach the server over UDP or TCP.
342 pub transport_protocol: TransportProtocol,
343 /// The long-term credential username for the TURN server. It is sent as USERNAME, or
344 /// hashed as USERHASH when the server's nonce says it supports that (RFC 8489 §9.2.5).
345 pub username: String,
346 /// The long-term credential password.
347 pub password: String,
348 /// Not used: the realm is the one the server names in its 401 (RFC 8489 §9.2.5).
349 pub realm: String,
350 /// The `SOFTWARE` attribute of every request (RFC 8489 Section 6.1: requests "SHOULD"
351 /// carry one; Section 16.1.2: its use "SHOULD" be configurable). The default is
352 /// [`DEFAULT_SOFTWARE`] (`rtci-turn` and its version); empty sends none, for an
353 /// application that would not tell its software to the path.
354 pub software: String,
355 /// Whether Send indications carry [`ClientConfig::software`] too (RFC 8489 Section 6.1:
356 /// "Indications MAY include a SOFTWARE attribute"). Off by default: Send indications are
357 /// the relayed data path, and the attribute would cost its bytes on every packet sent
358 /// before a channel is bound, for no effect on the protocol. Nothing is added when
359 /// `software` is empty.
360 pub software_in_indications: bool,
361 /// The initial retransmission timeout in milliseconds; each retransmission doubles the
362 /// wait. `0` selects the default, the 500 ms RFC 8489 §6.2.1 asks for at least.
363 pub rto_in_ms: u64,
364 /// The rest of the retransmission timer: Rc, Rm, Ti, the RTO estimate and the number of
365 /// outstanding transactions.
366 pub retransmission: RetransmissionConfig,
367 /// The password algorithms accepted from the server's PASSWORD-ALGORITHMS
368 /// (`stun::password_algorithm`), the first of the server's list that is in here being
369 /// used. Empty for all the client implements, SHA-256 and MD5. Without MD5, a server
370 /// that offers no list (RFC 5389) or MD5 alone is not authenticated to: RFC 8489
371 /// §18.5.1.1 keeps MD5 for such servers only.
372 pub password_algorithms: Vec<u16>,
373 /// Optional upper bound for the interval between allocation Refresh requests.
374 ///
375 /// By default, allocations are refreshed at half the lifetime advertised by the server.
376 /// A shorter cap can also keep the client-to-server NAT mapping active when an allocation
377 /// waits without carrying application traffic. Values below one second are rounded up.
378 pub allocation_refresh_interval_cap: Option<Duration>,
379}
380
381impl Default for ClientConfig {
382 fn default() -> Self {
383 Self {
384 stun_serv_addr: "".to_string(),
385 turn_serv_addr: "".to_string(),
386 local_addr: SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)),
387 transport_protocol: Default::default(),
388 username: "".to_string(),
389 password: "".to_string(),
390 realm: "".to_string(),
391 software: DEFAULT_SOFTWARE.to_string(),
392 software_in_indications: false,
393 rto_in_ms: 0,
394 retransmission: RetransmissionConfig::default(),
395 password_algorithms: vec![],
396 allocation_refresh_interval_cap: None,
397 }
398 }
399}
400
401/// The default `SOFTWARE` of the TURN client's requests ([`ClientConfig::software`]).
402pub const DEFAULT_SOFTWARE: &str = concat!("rtci-turn ", env!("CARGO_PKG_VERSION"));
403
404/// RFC 8489 Section 6.1: with the path MTU unknown, a STUN message over UDP is at most 576
405/// bytes of IPv4 datagram, 1280 of IPv6 (the IP and UDP headers taken off).
406const UNKNOWN_PATH_MTU_V4: usize = 576;
407const UNKNOWN_PATH_MTU_V6: usize = 1280;
408const IP_UDP_OVERHEAD_V4: usize = 28;
409const IP_UDP_OVERHEAD_V6: usize = 48;
410
411/// Client is a STUN client
412pub struct Client {
413 crypto_provider: Arc<dyn RTCCryptoProvider>,
414 stun_serv_addr: Option<SocketAddr>,
415 turn_serv_addr: Option<SocketAddr>,
416 local_addr: SocketAddr,
417 transport_protocol: TransportProtocol,
418 /// What the application authenticates with; each allocation has its own state of it.
419 login: Arc<Login>,
420 software: Software,
421 /// [`ClientConfig::software_in_indications`].
422 software_in_indications: bool,
423 /// The path MTU for requests over UDP ([`Client::set_path_mtu`]); `None`: unknown.
424 path_mtu: Option<usize>,
425 tr_map: TransactionMap,
426 /// The TURN servers an Allocate was sent to, against redirection loops (RFC 8489 §10).
427 redirects: RedirectGuard,
428 allocation_refresh_interval_cap: Option<Duration>,
429
430 /// Allocations, each under the first relayed address it was given.
431 relays: HashMap<RelayedAddr, RelayState>,
432 /// Address families the server refused, by `REQUESTED-ADDRESS-FAMILY` value less one.
433 family_blocks: [Option<FamilyBlock>; 2],
434 /// Whether the server answered an Allocate with a family that was not asked for.
435 family_mismatch: bool,
436 transmits: VecDeque<TransportMessage<BytesMut>>,
437 events: VecDeque<Event>,
438}
439
440impl Client {
441 /// Returns a new TURN client.
442 ///
443 /// The crypto provider is supplied by the caller; this crate never resolves a default.
444 pub fn new(config: ClientConfig, crypto_provider: Arc<dyn RTCCryptoProvider>) -> Result<Self> {
445 let stun_serv_addr = if config.stun_serv_addr.is_empty() {
446 None
447 } else {
448 Some(lookup_host(
449 config.local_addr.is_ipv4(),
450 config.stun_serv_addr.as_str(),
451 )?)
452 };
453
454 let turn_serv_addr = if config.turn_serv_addr.is_empty() {
455 None
456 } else {
457 Some(lookup_host(
458 config.local_addr.is_ipv4(),
459 config.turn_serv_addr.as_str(),
460 )?)
461 };
462
463 Ok(Client {
464 crypto_provider: crypto_provider.clone(),
465 stun_serv_addr,
466 turn_serv_addr,
467 local_addr: config.local_addr,
468 transport_protocol: config.transport_protocol,
469 login: Arc::new(Login {
470 username: config.username,
471 password: config.password,
472 password_algorithms: config.password_algorithms,
473 }),
474 software: Software::new(ATTR_SOFTWARE, config.software),
475 software_in_indications: config.software_in_indications,
476 path_mtu: None,
477 tr_map: TransactionMap::new(TimerSettings {
478 initial_rto: if config.rto_in_ms != 0 {
479 Duration::from_millis(config.rto_in_ms)
480 } else {
481 stun::timer::DEFAULT_RTO
482 },
483 schedule: Schedule {
484 rc: config.retransmission.rc.max(1),
485 rm: config.retransmission.rm,
486 ti: config.retransmission.ti,
487 },
488 estimate_rto: config.retransmission.rto_estimation,
489 max_outstanding: config.retransmission.max_outstanding_transactions,
490 }),
491 redirects: RedirectGuard::new(),
492 allocation_refresh_interval_cap: config.allocation_refresh_interval_cap,
493 relays: HashMap::new(),
494 family_blocks: [None, None],
495 family_mismatch: false,
496 transmits: VecDeque::new(),
497 events: VecDeque::new(),
498 })
499 }
500
501 // handle_inbound handles data received.
502 // This method handles incoming packet demultiplex it by the source address
503 // and the types of the message.
504 // This return Ok(handled or not) and if there was an error.
505 // Caller should check if the packet was handled by this client or not.
506 // If not handled, it is assumed that the packet is application data.
507 // If an error is returned, the caller should discard the packet regardless.
508 fn handle_inbound(&mut self, now: Instant, data: &[u8], from: SocketAddr) -> Result<()> {
509 // +-------------------+-------------------------------+
510 // | Return Values | |
511 // +-------------------+ Meaning / Action |
512 // | handled | error | |
513 // |=========+=========+===============================+
514 // | false | nil | Handle the packet as app data |
515 // |---------+---------+-------------------------------+
516 // | true | nil | Nothing to do |
517 // |---------+---------+-------------------------------+
518 // | false | error | (shouldn't happen) |
519 // |---------+---------+-------------------------------+
520 // | true | error | Error occurred while handling |
521 // +---------+---------+-------------------------------+
522 // Possible causes of the error:
523 // - Malformed packet (parse error)
524 // - STUN message was a request
525 // - Non-STUN message from the STUN server
526
527 // TURN and STUN messages are only ever sent to us by the servers we talk to. Anything
528 // else that looks like one — a spoofed Data indication, ChannelData or a forged
529 // response — is not from the server and must not be acted on or relayed as peer data.
530 let from_turn_server = self.turn_serv_addr == Some(from);
531 let from_a_server = from_turn_server || self.stun_serv_addr == Some(from);
532 if is_stun_message(data) {
533 // A response to a request sent to some other address (`send_binding_request_to`)
534 // is accepted from that address only.
535 if !from_a_server && !self.is_response_from_transaction_peer(data, from) {
536 debug!("discarding STUN message from {from}: not a configured server");
537 return Ok(());
538 }
539 self.handle_stun_message(now, data, from_turn_server)
540 } else if ChannelData::is_channel_data(data) {
541 if !from_turn_server {
542 debug!("discarding ChannelData from {from}: not the TURN server");
543 return Ok(());
544 }
545 self.handle_channel_data(now, data)
546 } else if self.stun_serv_addr.is_some() && &from == self.stun_serv_addr.as_ref().unwrap() {
547 // received from STUN server, but it is not a STUN message
548 Err(Error::ErrNonStunmessage)
549 } else {
550 // assume, this is an application data
551 trace!("non-STUN/TURN packet, unhandled");
552 Ok(())
553 }
554 }
555
556 /// Whether `data` is a STUN response to an outstanding transaction whose request went to
557 /// `from`.
558 fn is_response_from_transaction_peer(&self, data: &[u8], from: SocketAddr) -> bool {
559 let mut msg = Message::new();
560 msg.raw = data.to_vec();
561 if msg.decode().is_err() {
562 return false;
563 }
564 (msg.typ.class == CLASS_SUCCESS_RESPONSE || msg.typ.class == CLASS_ERROR_RESPONSE)
565 && self
566 .tr_map
567 .find(&msg.transaction_id)
568 .is_some_and(|tr| tr.peer_addr == from)
569 }
570
571 fn handle_stun_message(
572 &mut self,
573 now: Instant,
574 data: &[u8],
575 from_turn_server: bool,
576 ) -> Result<()> {
577 let mut msg = Message::new();
578 msg.raw = data.to_vec();
579 msg.decode()?;
580
581 if msg.typ.class == CLASS_REQUEST {
582 return Err(Error::Other(format!(
583 "{:?} : {}",
584 Error::ErrUnexpectedStunrequestMessage,
585 msg
586 )));
587 }
588
589 if msg.typ.class == CLASS_INDICATION {
590 return self.handle_indication(now, &msg, from_turn_server);
591 }
592
593 // This is a STUN response message (transactional)
594 // The type is either:
595 // - stun.ClassSuccessResponse
596 // - stun.ClassErrorResponse
597
598 let Some(tr) = self.tr_map.find(&msg.transaction_id) else {
599 // silently discard
600 debug!("no transaction for {}", msg);
601 return Ok(());
602 };
603
604 // Only a response of the request's method answers it (RFC 8489 §6.3). Anything else
605 // with its transaction id is not its response, and the transaction goes on.
606 if tr.method != msg.typ.method {
607 debug!(
608 "discarding {}: its transaction is a {} request",
609 msg, tr.method
610 );
611 return Ok(());
612 }
613
614 // One place for the checks of RFC 8489 §6.3, §9 and §9.2.5: FINGERPRINT, the
615 // integrity attribute the request's credential asks for, and no attribute the client
616 // has to but does not understand. What comes out holds the attributes ahead of the
617 // integrity attribute and nothing else.
618 let crypto = self.crypto_provider.crypto();
619 let checked = match &tr.credential {
620 Some(credential) => credential.check_response(&msg, &validator(), crypto),
621 None => validator().unauthenticated(&msg),
622 };
623 let valid = match checked {
624 Ok(valid) => valid,
625 Err(Rejection::IntegrityMissing | Rejection::IntegrityMismatch) => {
626 // A response to a signed request is believed only if it is signed with the
627 // same key (RFC 8489 §9.2.5). Over UDP it is dropped as if never received,
628 // so the transaction stays open and its retransmissions continue; over a
629 // reliable transport the transaction ends at once. Either way its failure
630 // is an integrity violation, not a timeout.
631 debug!("discarding {}: integrity attribute missing or wrong", msg);
632 if tr.is_reliable() {
633 if let Some(tr) = self.tr_map.delete(&msg.transaction_id) {
634 self.handle_transaction_failure(now, tr, Failure::IntegrityViolation);
635 }
636 } else if let Some(tr) = self.tr_map.get(&msg.transaction_id) {
637 tr.discarded = true;
638 }
639 return Ok(());
640 }
641 Err(Rejection::UnknownAttributes(unknown)) => {
642 // RFC 8489 §6.3.3, §6.3.4: the response is discarded and the transaction
643 // has failed.
644 debug!("discarding {}: unknown attributes {:?}", msg, unknown);
645 if let Some(tr) = self.tr_map.answered(&msg.transaction_id, now) {
646 self.handle_transaction_failure(now, tr, Failure::UnknownAttributes(unknown));
647 }
648 return Ok(());
649 }
650 Err(rejection) => {
651 debug!("discarding {}: {}", msg, rejection);
652 return Ok(());
653 }
654 };
655
656 let Some(tr) = self.tr_map.answered(&msg.transaction_id, now) else {
657 return Ok(());
658 };
659 let id = tr.transaction_id;
660 let res = Response {
661 msg: valid,
662 request: tr.raw,
663 };
664 match tr.transaction_type {
665 TransactionType::BindingRequest => {
666 if res.typ.class == CLASS_ERROR_RESPONSE {
667 let mut code = ErrorCodeAttribute::default();
668 let err = if code.get_from(&res).is_err() {
669 Error::Other(format!("{}", res.typ))
670 } else {
671 Error::Other(format!("{} (error {})", res.typ, code))
672 };
673 self.events.push_back(Event::BindingError(id, err));
674 } else {
675 let mut refl_addr = XorMappedAddress::default();
676 match refl_addr.get_from(&res) {
677 Ok(_) => {
678 self.events.push_back(Event::BindingResponse(
679 id,
680 ReflexiveAddr::new(refl_addr.ip, refl_addr.port),
681 ));
682 }
683 Err(err) => {
684 self.events.push_back(Event::BindingError(id, err));
685 }
686 }
687 }
688 }
689 TransactionType::AllocateAttempt(state) | TransactionType::AllocateRequest(state) => {
690 self.handle_allocate_response(now, res, *state)?;
691 }
692 // A release of an allocation the client did not keep: nothing to do.
693 TransactionType::OrphanRelease => {}
694 TransactionType::FamilyRelease(relayed_addr, family, retry) => {
695 let mut relay = Relay {
696 relayed_addr,
697 client: self,
698 };
699 relay.handle_family_release_response(now, res, family, retry)?;
700 }
701 TransactionType::CreatePermissionRequest(
702 relayed_addr,
703 peer_addr,
704 peer_addrs,
705 retry,
706 ) => {
707 let mut relay = Relay {
708 relayed_addr,
709 client: self,
710 };
711 relay.handle_create_permission_response(now, res, peer_addr, peer_addrs, retry)?;
712 }
713 TransactionType::RefreshRequest(relayed_addr, lifetime, retry) => {
714 let mut relay = Relay {
715 relayed_addr,
716 client: self,
717 };
718 relay.handle_refresh_response(now, res, lifetime, retry)?;
719 }
720 TransactionType::ConnectRequest(relayed_addr, peer_addr, retry) => {
721 let mut relay = Relay {
722 relayed_addr,
723 client: self,
724 };
725 relay.handle_connect_response(now, res, peer_addr, retry)?;
726 }
727 TransactionType::ChannelBindRequest(relayed_addr, bind_addr, retry) => {
728 let mut relay = Relay {
729 relayed_addr,
730 client: self,
731 };
732 relay.handle_channel_bind_response(now, res, bind_addr, retry)?;
733 }
734 }
735
736 Ok(())
737 }
738
739 /// Handles an indication from a server: the peer's data, the ICMP error a datagram to a
740 /// peer met, or a peer's connection to a TCP allocation.
741 fn handle_indication(
742 &mut self,
743 now: Instant,
744 msg: &Message,
745 from_turn_server: bool,
746 ) -> Result<()> {
747 // RFC 8489 §6.3.2: an indication with a wrong FINGERPRINT, or with an attribute the
748 // client has to but does not understand, is discarded. TURN indications are not
749 // signed (RFC 8656 §11); if one carries an integrity attribute all the same, what
750 // follows it is not read (RFC 8489 §9).
751 let msg = match validator().unauthenticated(msg) {
752 Ok(msg) => msg,
753 Err(rejection) => {
754 debug!("discarding {}: {}", msg, rejection);
755 return Ok(());
756 }
757 };
758
759 if msg.typ.method == METHOD_CONNECTION_ATTEMPT {
760 // Like relayed data, a peer's connection is announced by the server holding the
761 // allocation and by nobody else.
762 if !from_turn_server {
763 debug!("discarding ConnectionAttempt indication: not from the TURN server");
764 return Ok(());
765 }
766 let mut connection_id = ConnectionId::default();
767 connection_id.get_from(&msg)?;
768 let mut peer_addr = PeerAddress::default();
769 peer_addr.get_from(&msg)?;
770 let from = SocketAddr::new(peer_addr.ip, peer_addr.port);
771 // The server accepts connections only from peers the client installed a
772 // permission for (RFC 6062 §5.3), on a TCP allocation.
773 let Some(relayed) = self
774 .relays
775 .values()
776 .find(|relay| {
777 relay.transport == RelayTransport::Tcp
778 && relay.expects_data_from(&from.ip(), now)
779 })
780 .map(RelayState::name)
781 else {
782 debug!("discarding ConnectionAttempt from {from}: no permission");
783 return Ok(());
784 };
785 self.events
786 .push_back(Event::ConnectionAttempt(relayed, from, connection_id));
787 return Ok(());
788 }
789
790 // Only the TURN server holding the allocation relays peer data. The STUN server,
791 // when it is a different address, has no allocation and is not believed for it.
792 if msg.typ.method == METHOD_DATA && !from_turn_server {
793 debug!("discarding Data indication: not from the TURN server");
794 return Ok(());
795 }
796 if msg.typ.method == METHOD_DATA {
797 let mut peer_addr = PeerAddress::default();
798 peer_addr.get_from(&msg)?;
799 let from = SocketAddr::new(peer_addr.ip, peer_addr.port);
800
801 // A Data indication carries the peer's data, or the ICMP error a datagram
802 // relayed to that peer met (RFC 8656 §11.4, §11.6). One with neither is
803 // discarded.
804 let mut data = Data::default();
805 let mut icmp = Icmp::default();
806 let has_data = msg.contains(ATTR_DATA);
807 if has_data {
808 data.get_from(&msg)?;
809 } else {
810 icmp.get_from(&msg)?;
811 }
812
813 // The server relays only from addresses the client installed a permission
814 // for, so anything else is not what it claims to be (RFC 8656 §11.4, §11.6).
815 if !self
816 .relays
817 .values()
818 .any(|relay| relay.expects_data_from(&from.ip(), now))
819 {
820 debug!("discarding Data indication from {from}: no permission");
821 return Ok(());
822 }
823
824 if has_data {
825 debug!("data indication received from {}", from);
826 self.events.push_back(Event::DataIndicationOrChannelData(
827 None,
828 from,
829 BytesMut::from(&data.0[..]),
830 ))
831 } else {
832 debug!("{icmp} reported for {from}");
833 self.events.push_back(Event::IcmpError(from, icmp))
834 }
835 }
836
837 Ok(())
838 }
839
840 /// Deals with a transaction that ended without a response the client could act on.
841 ///
842 /// One that exhausted its retransmissions: a Refresh or ChannelBind is started once more
843 /// as a new transaction, so one lost burst does not let the allocation lapse or leave a
844 /// channel unbound for good. A ChannelBind that fails again returns its binding to idle,
845 /// so the next send binds it again. Anything not started again is reported as
846 /// [`Event::TransactionTimeout`], under the id its caller knows.
847 ///
848 /// One that failed for another reason (its responses were not authentic, or carried
849 /// attributes the client does not understand) is not started again, and is reported by
850 /// the error event of its kind.
851 fn handle_transaction_failure(&mut self, now: Instant, tr: Transaction, failure: Failure) {
852 // RFC 8489 §9.2.5: when every response that arrived was discarded, the failure is an
853 // integrity violation, not a timeout.
854 let failure = match failure {
855 Failure::Timeout if tr.discarded => Failure::IntegrityViolation,
856 other => other,
857 };
858 let timed_out = matches!(failure, Failure::Timeout);
859 let id = tr.transaction_type.report_id(tr.transaction_id);
860 match tr.transaction_type {
861 TransactionType::RefreshRequest(relayed_addr, lifetime, retry) => {
862 if timed_out
863 && !retry.timeout
864 && let Some(mut relay) = self.relay_by_key(relayed_addr)
865 && relay
866 .refresh_allocation_with(
867 now,
868 lifetime,
869 retry.after_timeout(tr.transaction_id),
870 )
871 .is_ok()
872 {
873 debug!("refresh timed out; sent again");
874 return;
875 }
876 let Some(mut relay) = self.relay_by_key(relayed_addr) else {
877 return;
878 };
879 let releasing = lifetime.is_zero();
880 relay.refresh_failed(now, lifetime, RequestError::Failed(failure.error()));
881 if releasing || !timed_out {
882 // The release is over, and reported as that; a failure that is not a
883 // timeout was reported as the refresh error it is.
884 return;
885 }
886 }
887 TransactionType::ChannelBindRequest(relayed_addr, bind_addr, retry) => {
888 if timed_out
889 && !retry.timeout
890 && let Some(mut relay) = self.relay_by_key(relayed_addr)
891 && relay
892 .rebind_channel(now, bind_addr, retry.after_timeout(tr.transaction_id))
893 .is_ok()
894 {
895 debug!("channel bind for {bind_addr} timed out; sent again");
896 return;
897 }
898 if let Some(mut relay) = self.relay_by_key(relayed_addr) {
899 if timed_out {
900 relay.channel_bind_timed_out(bind_addr);
901 } else {
902 relay.channel_bind_failed(
903 now,
904 bind_addr,
905 RequestError::Failed(failure.error()),
906 );
907 return;
908 }
909 }
910 }
911 TransactionType::FamilyRelease(relayed_addr, family, retry) => {
912 if timed_out
913 && !retry.timeout
914 && let Some(mut relay) = self.relay_by_key(relayed_addr)
915 && relay
916 .release_family_with(
917 now,
918 crate::proto::reqfamily::RequestedAddressFamily(family),
919 retry.after_timeout(tr.transaction_id),
920 )
921 .is_ok()
922 {
923 return;
924 }
925 // Nothing says the server deleted the address, so it is kept; the periodic
926 // Refresh keeps the whole allocation alive.
927 if let Some(relay) = self.relays.get(&relayed_addr) {
928 self.events.push_back(Event::RefreshError(
929 relay.name(),
930 RequestError::Failed(failure.error()),
931 ));
932 }
933 return;
934 }
935 TransactionType::ConnectRequest(relayed_addr, peer_addr, _) => {
936 // Nothing is outstanding for the peer any more.
937 if let Some(relay) = self.relays.get_mut(&relayed_addr) {
938 relay.connecting.remove(&peer_addr);
939 }
940 if !timed_out {
941 self.events.push_back(Event::ConnectError(
942 id,
943 peer_addr,
944 RequestError::Failed(failure.error()),
945 ));
946 return;
947 }
948 }
949 TransactionType::CreatePermissionRequest(relayed_addr, peer_addr, _, _) => {
950 if !timed_out {
951 // A permission the application asked for is not there; a refresh that
952 // failed this way leaves the permissions the time the server last
953 // granted, and they are asked for again.
954 if let Some(peer_addr) = peer_addr {
955 if let Some(relay) = self.relays.get_mut(&relayed_addr) {
956 relay.forget_unless_permitted(peer_addr.ip(), now);
957 }
958 self.events.push_back(Event::CreatePermissionError(
959 id,
960 RequestError::Failed(failure.error()),
961 ));
962 }
963 return;
964 }
965 }
966 TransactionType::AllocateAttempt(_) | TransactionType::AllocateRequest(_) => {
967 if !timed_out {
968 self.events.push_back(Event::AllocateError(
969 id,
970 RequestError::Failed(failure.error()),
971 ));
972 return;
973 }
974 }
975 TransactionType::BindingRequest => {
976 if !timed_out {
977 self.events
978 .push_back(Event::BindingError(id, failure.error()));
979 return;
980 }
981 }
982 TransactionType::OrphanRelease => return,
983 }
984 self.events.push_back(Event::TransactionTimeout(id));
985 }
986
987 fn handle_channel_data(&mut self, now: Instant, data: &[u8]) -> Result<()> {
988 let mut ch_data = ChannelData {
989 raw: data.to_vec(),
990 ..Default::default()
991 };
992 ch_data.decode()?;
993
994 // A channel is the binding of one allocation; it is accepted from the moment its
995 // ChannelBind is sent (RFC 8656 §12).
996 let (relay, addr) = self
997 .relays
998 .values_mut()
999 .find_map(|relay| {
1000 let addr = relay.binding_mgr.find_by_number(ch_data.number.0)?.addr;
1001 Some((relay, addr))
1002 })
1003 .ok_or(Error::ErrChannelBindNotFound)?;
1004
1005 // The server relays only from addresses the client holds a permission for
1006 // (RFC 8656 §12.6).
1007 if !relay.expects_data_from(&addr.ip(), now) {
1008 debug!(
1009 "discarding ChannelData from {addr} (ch={}): no permission",
1010 ch_data.number.0
1011 );
1012 return Ok(());
1013 }
1014 if let Some(b) = relay.binding_mgr.get_by_number(ch_data.number.0) {
1015 b.used = true;
1016 }
1017
1018 trace!(
1019 "channel data received from {} (ch={})",
1020 addr, ch_data.number.0
1021 );
1022
1023 self.events.push_back(Event::DataIndicationOrChannelData(
1024 Some(ch_data.number),
1025 addr,
1026 BytesMut::from(&ch_data.data[..]),
1027 ));
1028
1029 Ok(())
1030 }
1031
1032 /// Borrows the allocation for `relayed_addr` so data can be sent or permissions created.
1033 ///
1034 /// # Errors
1035 ///
1036 /// Fails if this client has no allocation for that address — it was never allocated, or has
1037 /// already been closed.
1038 pub fn relay(&mut self, relayed_addr: SocketAddr) -> Result<Relay<'_>> {
1039 // An allocation is kept under its first relayed address and found by any address it
1040 // has now: either of the two of a dual allocation.
1041 let key = self
1042 .relays
1043 .iter()
1044 .find(|(_, relay)| relay.addrs.contains(&relayed_addr))
1045 .map(|(key, _)| *key)
1046 .ok_or(Error::ErrStreamNotExisted)?;
1047 Ok(Relay {
1048 relayed_addr: key,
1049 client: self,
1050 })
1051 }
1052
1053 /// The allocation kept under `key`, whatever relayed addresses it has now.
1054 fn relay_by_key(&mut self, key: RelayedAddr) -> Option<Relay<'_>> {
1055 self.relays.contains_key(&key).then_some(Relay {
1056 relayed_addr: key,
1057 client: self,
1058 })
1059 }
1060
1061 /// Whether this client is waiting on a response for transaction `id`.
1062 ///
1063 /// A STUN response belongs to whoever sent the matching request — [RFC 5389 §7.3.3] matches
1064 /// them by transaction ID, and nothing else identifies the owner. That is only a question
1065 /// worth asking when several STUN users share one socket, which is exactly the situation a
1066 /// host is in when it points a STUN gatherer and this client at the same server address: both
1067 /// see every response, and the four-tuple is identical for both, so addresses cannot say whose
1068 /// a response is.
1069 ///
1070 /// Such a host calls this to route a response, rather than guessing from the peer address and
1071 /// handing it to a client that will silently discard it — [`handle_read`](sansio::Protocol::handle_read)
1072 /// drops a response with no matching transaction, as it must.
1073 ///
1074 /// Applies to responses only. TURN ChannelData carries no transaction ID at all, and
1075 /// indications are not transaction-matched; both are routed by address.
1076 ///
1077 /// [RFC 5389 §7.3.3]: https://www.rfc-editor.org/rfc/rfc5389#section-7.3.3
1078 #[must_use]
1079 pub fn has_transaction(&self, id: &TransactionId) -> bool {
1080 self.tr_map.find(id).is_some()
1081 }
1082
1083 /// send_binding_request_to sends a new STUN request to the given transport address
1084 /// return key to find out corresponding Event either BindingResponse or BindingRequestTimeout
1085 pub fn send_binding_request_to(
1086 &mut self,
1087 now: Instant,
1088 to: SocketAddr,
1089 ) -> Result<TransactionId> {
1090 let msg = {
1091 // RFC 8489 section 7: "When the FINGERPRINT extension is used, an agent includes
1092 // the FINGERPRINT attribute in messages it sends to another agent": the client
1093 // ends every other message with it, and this one shares their socket.
1094 let mut attrs: Vec<Box<dyn Setter + '_>> =
1095 vec![Box::new(TransactionId::new()), Box::new(BINDING_REQUEST)];
1096 if !self.software.text.is_empty() {
1097 attrs.push(Box::new(self.software.clone()));
1098 }
1099 attrs.push(Box::new(FINGERPRINT));
1100
1101 let mut msg = Message::new();
1102 msg.build(&attrs)?;
1103 msg
1104 };
1105
1106 debug!("client.SendBindingRequestTo call PerformTransaction 1");
1107 self.perform_transaction(now, &msg, to, TransactionType::BindingRequest, None)
1108 }
1109
1110 /// send_binding_request sends a new STUN request to the STUN server
1111 /// return key to find out corresponding Event either BindingResponse or BindingRequestTimeout
1112 pub fn send_binding_request(&mut self, now: Instant) -> Result<TransactionId> {
1113 if let Some(stun_serv_addr) = &self.stun_serv_addr {
1114 self.send_binding_request_to(now, *stun_serv_addr)
1115 } else {
1116 Err(Error::ErrStunserverAddressNotSet)
1117 }
1118 }
1119
1120 // stun_server_addr return the STUN server address
1121 fn stun_server_addr(&self) -> Option<SocketAddr> {
1122 self.stun_serv_addr
1123 }
1124
1125 /* https://datatracker.ietf.org/doc/html/rfc8656#section-20
1126 TURN TURN Peer Peer
1127 client server A B
1128 | | | |
1129 |--- Allocate request -------------->| | |
1130 | Transaction-Id=0xA56250D3F17ABE679422DE85 | |
1131 | SOFTWARE="Example client, version 1.03" | |
1132 | LIFETIME=3600 (1 hour) | | |
1133 | REQUESTED-TRANSPORT=17 (UDP) | | |
1134 | DONT-FRAGMENT | | |
1135 | | | |
1136 |<-- Allocate error response --------| | |
1137 | Transaction-Id=0xA56250D3F17ABE679422DE85 | |
1138 | SOFTWARE="Example server, version 1.17" | |
1139 | ERROR-CODE=401 (Unauthorized) | | |
1140 | REALM="example.com" | | |
1141 | NONCE="obMatJos2gAAAadl7W7PeDU4hKE72jda" | |
1142 | PASSWORD-ALGORITHMS=MD5 and SHA256 | |
1143 | | | |
1144 |--- Allocate request -------------->| | |
1145 | Transaction-Id=0xC271E932AD7446A32C234492 | |
1146 | SOFTWARE="Example client 1.03" | | |
1147 | LIFETIME=3600 (1 hour) | | |
1148 | REQUESTED-TRANSPORT=17 (UDP) | | |
1149 | DONT-FRAGMENT | | |
1150 | USERNAME="George" | | |
1151 | REALM="example.com" | | |
1152 | NONCE="obMatJos2gAAAadl7W7PeDU4hKE72jda" | |
1153 | PASSWORD-ALGORITHMS=MD5 and SHA256 | |
1154 | PASSWORD-ALGORITHM=SHA256 | | |
1155 | MESSAGE-INTEGRITY=... | | |
1156 | MESSAGE-INTEGRITY-SHA256=... | | |
1157 | | | |
1158 |<-- Allocate success response ------| | |
1159 | Transaction-Id=0xC271E932AD7446A32C234492 | |
1160 | SOFTWARE="Example server, version 1.17" | |
1161 | LIFETIME=1200 (20 minutes) | | |
1162 | XOR-RELAYED-ADDRESS=192.0.2.15:50000 | |
1163 | XOR-MAPPED-ADDRESS=192.0.2.1:7000 | |
1164 | MESSAGE-INTEGRITY-SHA256=... | | |
1165 */
1166 /// Replaces the long-term credential used to sign subsequent requests, **keeping any
1167 /// existing allocation**.
1168 ///
1169 /// This is for a new **password** for the same username. An allocation belongs to the
1170 /// username that created it: [RFC 8656 §5] has the server answer a request for it made
1171 /// under another username with **441 (Wrong Credentials)**. Giving up the allocation and
1172 /// allocating again is no way round a rotation either, since the server still holds the
1173 /// allocation for the 5-tuple and answers the new Allocate with 437 (Allocation Mismatch).
1174 /// So with a new password the existing allocation is re-signed, and its permissions and
1175 /// channel bindings survive.
1176 ///
1177 /// A new username takes effect for the next [`allocate`](Self::allocate) only: RFC 8656
1178 /// section 5 has every request about an allocation use the username that created it, so
1179 /// live allocations keep signing with theirs (and their password). To move to the new
1180 /// username, [`Relay::close`] an allocation, wait for [`Event::AllocationReleased`], and
1181 /// allocate again.
1182 ///
1183 /// The realm is *not* re-negotiated. It was learned from the server's 401 during the
1184 /// first `Allocate`, and a credential rotation keeps the same server, so it still
1185 /// applies. Follow this with [`Self::refresh_allocations`] so the server sees the new
1186 /// credential before the allocation would otherwise expire.
1187 ///
1188 /// [RFC 8656 §5]: https://datatracker.ietf.org/doc/html/rfc8656#section-5
1189 pub fn update_credentials(&mut self, username: String, password: String) -> Result<()> {
1190 // RFC 8656 section 5: an allocation's requests stay under the username that created
1191 // it; only a new password for that username re-keys it.
1192 let same_username = username == self.login.username;
1193 let login = Arc::new(Login {
1194 username,
1195 password,
1196 password_algorithms: self.login.password_algorithms.clone(),
1197 });
1198 if !same_username {
1199 self.login = login;
1200 return Ok(());
1201 }
1202
1203 // Each allocation carries the credential it will sign its own Refresh /
1204 // CreatePermission / ChannelBind with, so they have to be re-keyed too — otherwise
1205 // the next refresh would still present the retired credential. The realm, the nonce
1206 // and the password algorithm stay what the server last asked for. An allocation the
1207 // server gave without a credential stays unsigned until the server asks for one.
1208 let mut rekeyed = Vec::with_capacity(self.relays.len());
1209 for (key, relay) in &self.relays {
1210 rekeyed.push((
1211 *key,
1212 relay
1213 .credential
1214 .with_login(login.clone(), self.crypto_provider.crypto())?,
1215 ));
1216 }
1217 for (key, credential) in rekeyed {
1218 if let Some(relay) = self.relays.get_mut(&key) {
1219 relay.credential = Arc::new(credential);
1220 }
1221 }
1222 self.login = login;
1223
1224 Ok(())
1225 }
1226
1227 /// Refreshes every live allocation, re-signing each with the current credential.
1228 ///
1229 /// Each allocation is refreshed with its own current lifetime, so this extends rather
1230 /// than changes it. Intended to follow [`update_credentials`](Self::update_credentials).
1231 pub fn refresh_allocations(&mut self, now: Instant) -> Result<()> {
1232 let relays: Vec<(RelayedAddr, Duration)> = self
1233 .relays
1234 .iter()
1235 .filter(|(_, relay)| !relay.releasing)
1236 .map(|(addr, relay)| (*addr, relay.lifetime))
1237 .collect();
1238
1239 for (relayed_addr, lifetime) in relays {
1240 if let Some(mut relay) = self.relay_by_key(relayed_addr) {
1241 relay.refresh_allocation(now, lifetime)?;
1242 }
1243 }
1244
1245 Ok(())
1246 }
1247
1248 /// Builds a request about `relay`: `attrs`, then the allocation's credential when it has
1249 /// one, then FINGERPRINT.
1250 pub(crate) fn build_request(
1251 &self,
1252 method: Method,
1253 attrs: Vec<Box<dyn Setter>>,
1254 relay: &RelayState,
1255 ) -> Result<Message> {
1256 self.build_request_with(method, attrs, &relay.credential)
1257 }
1258
1259 /// Builds a request made with `credential`; without one until the server asked for it.
1260 pub(crate) fn build_request_with(
1261 &self,
1262 method: Method,
1263 attrs: Vec<Box<dyn Setter>>,
1264 credential: &Credential,
1265 ) -> Result<Message> {
1266 self.build_request_as(TransactionId::new(), method, attrs, credential)
1267 }
1268
1269 /// Builds the request `id`: `attrs`, SOFTWARE when the client has one (RFC 8656 §5: in
1270 /// every Allocate and Refresh, and allowed in any other request), what the long-term
1271 /// credential mechanism adds once the server asked for the credential (RFC 8489 §9.2.3,
1272 /// §9.2.5: USERNAME or USERHASH, REALM, NONCE, PASSWORD-ALGORITHMS and
1273 /// PASSWORD-ALGORITHM when the server offered algorithms, and MESSAGE-INTEGRITY-SHA256
1274 /// then, MESSAGE-INTEGRITY otherwise), and FINGERPRINT.
1275 pub(crate) fn build_request_as(
1276 &self,
1277 id: TransactionId,
1278 method: Method,
1279 attrs: Vec<Box<dyn Setter>>,
1280 credential: &Credential,
1281 ) -> Result<Message> {
1282 let mut setters: Vec<Box<dyn Setter + '_>> = vec![
1283 Box::new(id),
1284 Box::new(MessageType::new(method, CLASS_REQUEST)),
1285 ];
1286 setters.extend(attrs.into_iter().map(|a| a as Box<dyn Setter + '_>));
1287 if !self.software.text.is_empty() {
1288 setters.push(Box::new(self.software.clone()));
1289 }
1290 if let Some(authentication) = credential.setter(self.crypto_provider.crypto()) {
1291 setters.push(authentication);
1292 }
1293 setters.push(Box::new(FINGERPRINT));
1294
1295 let mut msg = Message::new();
1296 msg.build(&setters)?;
1297 Ok(msg)
1298 }
1299
1300 /// Deletes the allocation the server holds for this client's 5-tuple, with a Refresh of
1301 /// LIFETIME 0 (RFC 8656 §8), when the client keeps no copy of it. Nothing is reported.
1302 pub(crate) fn release_orphan(
1303 &mut self,
1304 now: Instant,
1305 credential: &Arc<Credential>,
1306 ) -> Result<()> {
1307 let msg = self.build_request_with(
1308 METHOD_REFRESH,
1309 vec![Box::new(Lifetime(Duration::ZERO))],
1310 credential,
1311 )?;
1312 let to = self.turn_server_addr_or_err()?;
1313 self.perform_transaction(
1314 now,
1315 &msg,
1316 to,
1317 TransactionType::OrphanRelease,
1318 Some(credential.clone()),
1319 )?;
1320 Ok(())
1321 }
1322
1323 /// Points the client at the alternate server of a 300 (Try Alternate), for an
1324 /// application that chooses to follow the redirection (RFC 8489 §10, RFC 8656 §7.4). The
1325 /// client never follows one by itself: the application owns the socket and the choice of
1326 /// server.
1327 ///
1328 /// `redirect` comes from [`ErrorResponse::try_alternate`], which is there only for a 300
1329 /// that was authenticated with the allocation's credential; RFC 8489 §14.8 has a client
1330 /// validate the response before it redirects itself. (An application that trusts the
1331 /// address of an unauthenticated 300, [`ErrorResponse::alternate_server`], makes the
1332 /// `TryAlternate` itself.) The server of the address family the client reached the old
1333 /// one over is taken, and becomes [`Client::turn_server_addr`]. The application then
1334 /// calls [`Client::allocate`] again: the request goes to the alternate server over the
1335 /// same transport protocol and with the same credentials. Over TLS or DTLS the
1336 /// application checks the new server's certificate against
1337 /// [`TryAlternate::domain`] when it is there, and against the name it used for the old
1338 /// server when it is not.
1339 ///
1340 /// # Errors
1341 ///
1342 /// Fails, and leaves the server as it is, when an Allocate was already sent to the
1343 /// alternate server within the last five minutes: the redirection is a loop and RFC 8489
1344 /// §10 has the client ignore it and take the transaction as failed. Fails as well while
1345 /// the client holds an allocation (its server cannot change), or when no TURN server is
1346 /// configured.
1347 pub fn follow_alternate(
1348 &mut self,
1349 now: Instant,
1350 redirect: &TryAlternate,
1351 ) -> Result<SocketAddr> {
1352 let current = self.turn_server_addr_or_err()?;
1353 if !self.relays.is_empty() {
1354 return Err(Error::Other(
1355 "the TURN server cannot change while the client holds an allocation".to_owned(),
1356 ));
1357 }
1358 let server = redirect
1359 .server_for(current.ip())
1360 .ok_or(Error::ErrAttributeNotFound)?;
1361 if !self.redirects.follow(server, now) {
1362 return Err(Error::Other(format!(
1363 "redirection loop: an Allocate was sent to {server} within the last five \
1364 minutes (RFC 8489 section 10)"
1365 )));
1366 }
1367 debug!("TURN server {current} redirects to {server}");
1368 self.turn_serv_addr = Some(server);
1369 Ok(server)
1370 }
1371
1372 /// The path MTU to the server, when the application knows it (RFC 8489 Section 6.1): a
1373 /// request over UDP larger than it allows is refused with `ErrPacketTooBig`. `None` (the
1374 /// default): unknown, 576 bytes for IPv4 and 1280 for IPv6.
1375 pub fn set_path_mtu(&mut self, mtu: Option<usize>) {
1376 self.path_mtu = mtu;
1377 }
1378
1379 /// Returns the TURN server address, if configured.
1380 pub fn turn_server_addr(&self) -> Option<SocketAddr> {
1381 self.turn_serv_addr
1382 }
1383
1384 /// Returns the TURN server address or an error if not configured.
1385 fn turn_server_addr_or_err(&self) -> Result<SocketAddr> {
1386 self.turn_serv_addr.ok_or(Error::ErrNilTurnSocket)
1387 }
1388
1389 /// Returns the local address this client is bound to.
1390 pub fn local_addr(&self) -> SocketAddr {
1391 self.local_addr
1392 }
1393
1394 /// WriteTo sends data to the specified destination using the base socket.
1395 fn write_to(&mut self, now: Instant, data: &[u8], remote: SocketAddr) {
1396 self.transmits.push_back(TransportMessage {
1397 now,
1398 transport: TransportContext {
1399 local_addr: self.local_addr,
1400 peer_addr: remote,
1401 transport_protocol: self.transport_protocol,
1402 ecn: None,
1403 },
1404 message: BytesMut::from(data),
1405 });
1406 }
1407
1408 // PerformTransaction performs STUN transaction
1409 fn perform_transaction(
1410 &mut self,
1411 now: Instant,
1412 msg: &Message,
1413 to: SocketAddr,
1414 transaction_type: TransactionType,
1415 credential: Option<Arc<Credential>>,
1416 ) -> Result<TransactionId> {
1417 // RFC 8489 Section 6.1: outside MTU probing, a request over UDP does not exceed the
1418 // path MTU (configured with `set_path_mtu`, else the RFC's 576 / 1280 bytes). Data
1419 // indications are not requests and are left to the path.
1420 if self.transport_protocol == TransportProtocol::UDP {
1421 let (unknown, overhead) = if to.is_ipv4() {
1422 (UNKNOWN_PATH_MTU_V4, IP_UDP_OVERHEAD_V4)
1423 } else {
1424 (UNKNOWN_PATH_MTU_V6, IP_UDP_OVERHEAD_V6)
1425 };
1426 let limit = self.path_mtu.unwrap_or(unknown).saturating_sub(overhead);
1427 if msg.raw.len() > limit {
1428 debug!(
1429 "{} request of {} bytes not sent: the path takes {limit}",
1430 msg.typ,
1431 msg.raw.len()
1432 );
1433 return Err(Error::ErrPacketTooBig);
1434 }
1435 }
1436 trace!(
1437 "start {} transaction {:?} to {}",
1438 msg.typ, msg.transaction_id, to
1439 );
1440 self.tr_map.start(
1441 now,
1442 TransactionConfig {
1443 transaction_id: msg.transaction_id,
1444 method: msg.typ.method,
1445 transaction_type,
1446 raw: BytesMut::from(&msg.raw[..]),
1447 local_addr: self.local_addr,
1448 peer_addr: to,
1449 transport_protocol: self.transport_protocol,
1450 credential,
1451 },
1452 );
1453 // In the order it was asked for, with whatever else the client sends.
1454 while let Some(transmit) = self.tr_map.poll_transmit() {
1455 self.transmits.push_back(transmit);
1456 }
1457
1458 Ok(msg.transaction_id)
1459 }
1460}