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::{Checked, 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).map(Checked::Valid),
622 };
623 let valid = match checked {
624 Ok(Checked::Valid(valid)) => valid,
625 Ok(Checked::NeverReceived) => {
626 // RFC 8489 §9.2.5: an unsigned 400, or a response whose nonce cookie promises
627 // PASSWORD-ALGORITHMS it lacks. Not a response at all: the transaction and
628 // its retransmissions go on, over a reliable transport too, and it is not
629 // counted as discarded for its integrity (it ends in a timeout).
630 debug!("discarding {} as never received (RFC 8489 §9.2.5)", msg);
631 return Ok(());
632 }
633 Err(Rejection::IntegrityMissing | Rejection::IntegrityMismatch) => {
634 // A response to a signed request is believed only if it is signed with the
635 // same key (RFC 8489 §9.2.5). Over UDP it is dropped as if never received,
636 // so the transaction stays open and its retransmissions continue; over a
637 // reliable transport the transaction ends at once. Either way its failure
638 // is an integrity violation, not a timeout.
639 debug!("discarding {}: integrity attribute missing or wrong", msg);
640 if tr.is_reliable() {
641 if let Some(tr) = self.tr_map.delete(&msg.transaction_id) {
642 self.handle_transaction_failure(now, tr, Failure::IntegrityViolation);
643 }
644 } else if let Some(tr) = self.tr_map.get(&msg.transaction_id) {
645 tr.discarded = true;
646 }
647 return Ok(());
648 }
649 Err(Rejection::UnknownAttributes(unknown)) => {
650 // RFC 8489 §6.3.3, §6.3.4: the response is discarded and the transaction
651 // has failed.
652 debug!("discarding {}: unknown attributes {:?}", msg, unknown);
653 if let Some(tr) = self.tr_map.answered(&msg.transaction_id, now) {
654 self.handle_transaction_failure(now, tr, Failure::UnknownAttributes(unknown));
655 }
656 return Ok(());
657 }
658 Err(rejection) => {
659 debug!("discarding {}: {}", msg, rejection);
660 return Ok(());
661 }
662 };
663
664 let Some(tr) = self.tr_map.answered(&msg.transaction_id, now) else {
665 return Ok(());
666 };
667 let id = tr.transaction_id;
668 let res = Response {
669 msg: valid,
670 request: tr.raw,
671 };
672 match tr.transaction_type {
673 TransactionType::BindingRequest => {
674 if res.typ.class == CLASS_ERROR_RESPONSE {
675 let mut code = ErrorCodeAttribute::default();
676 let err = if code.get_from(&res).is_err() {
677 Error::Other(format!("{}", res.typ))
678 } else {
679 Error::Other(format!("{} (error {})", res.typ, code))
680 };
681 self.events.push_back(Event::BindingError(id, err));
682 } else {
683 let mut refl_addr = XorMappedAddress::default();
684 match refl_addr.get_from(&res) {
685 Ok(_) => {
686 self.events.push_back(Event::BindingResponse(
687 id,
688 ReflexiveAddr::new(refl_addr.ip, refl_addr.port),
689 ));
690 }
691 Err(err) => {
692 self.events.push_back(Event::BindingError(id, err));
693 }
694 }
695 }
696 }
697 TransactionType::AllocateAttempt(state) | TransactionType::AllocateRequest(state) => {
698 self.handle_allocate_response(now, res, *state)?;
699 }
700 // A release of an allocation the client did not keep: nothing to do.
701 TransactionType::OrphanRelease => {}
702 TransactionType::FamilyRelease(relayed_addr, family, retry) => {
703 let mut relay = Relay {
704 relayed_addr,
705 client: self,
706 };
707 relay.handle_family_release_response(now, res, family, retry)?;
708 }
709 TransactionType::CreatePermissionRequest(
710 relayed_addr,
711 peer_addr,
712 peer_addrs,
713 retry,
714 ) => {
715 let mut relay = Relay {
716 relayed_addr,
717 client: self,
718 };
719 relay.handle_create_permission_response(now, res, peer_addr, peer_addrs, retry)?;
720 }
721 TransactionType::RefreshRequest(relayed_addr, lifetime, retry) => {
722 let mut relay = Relay {
723 relayed_addr,
724 client: self,
725 };
726 relay.handle_refresh_response(now, res, lifetime, retry)?;
727 }
728 TransactionType::ConnectRequest(relayed_addr, peer_addr, retry) => {
729 let mut relay = Relay {
730 relayed_addr,
731 client: self,
732 };
733 relay.handle_connect_response(now, res, peer_addr, retry)?;
734 }
735 TransactionType::ChannelBindRequest(relayed_addr, bind_addr, retry) => {
736 let mut relay = Relay {
737 relayed_addr,
738 client: self,
739 };
740 relay.handle_channel_bind_response(now, res, bind_addr, retry)?;
741 }
742 }
743
744 Ok(())
745 }
746
747 /// Handles an indication from a server: the peer's data, the ICMP error a datagram to a
748 /// peer met, or a peer's connection to a TCP allocation.
749 fn handle_indication(
750 &mut self,
751 now: Instant,
752 msg: &Message,
753 from_turn_server: bool,
754 ) -> Result<()> {
755 // RFC 8489 §6.3.2: an indication with a wrong FINGERPRINT, or with an attribute the
756 // client has to but does not understand, is discarded. TURN indications are not
757 // signed (RFC 8656 §11); if one carries an integrity attribute all the same, what
758 // follows it is not read (RFC 8489 §9).
759 let msg = match validator().unauthenticated(msg) {
760 Ok(msg) => msg,
761 Err(rejection) => {
762 debug!("discarding {}: {}", msg, rejection);
763 return Ok(());
764 }
765 };
766
767 if msg.typ.method == METHOD_CONNECTION_ATTEMPT {
768 // Like relayed data, a peer's connection is announced by the server holding the
769 // allocation and by nobody else.
770 if !from_turn_server {
771 debug!("discarding ConnectionAttempt indication: not from the TURN server");
772 return Ok(());
773 }
774 let mut connection_id = ConnectionId::default();
775 connection_id.get_from(&msg)?;
776 let mut peer_addr = PeerAddress::default();
777 peer_addr.get_from(&msg)?;
778 let from = SocketAddr::new(peer_addr.ip, peer_addr.port);
779 // The server accepts connections only from peers the client installed a
780 // permission for (RFC 6062 §5.3), on a TCP allocation.
781 let Some(relayed) = self
782 .relays
783 .values()
784 .find(|relay| {
785 relay.transport == RelayTransport::Tcp
786 && relay.expects_data_from(&from.ip(), now)
787 })
788 .map(RelayState::name)
789 else {
790 debug!("discarding ConnectionAttempt from {from}: no permission");
791 return Ok(());
792 };
793 self.events
794 .push_back(Event::ConnectionAttempt(relayed, from, connection_id));
795 return Ok(());
796 }
797
798 // Only the TURN server holding the allocation relays peer data. The STUN server,
799 // when it is a different address, has no allocation and is not believed for it.
800 if msg.typ.method == METHOD_DATA && !from_turn_server {
801 debug!("discarding Data indication: not from the TURN server");
802 return Ok(());
803 }
804 if msg.typ.method == METHOD_DATA {
805 let mut peer_addr = PeerAddress::default();
806 peer_addr.get_from(&msg)?;
807 let from = SocketAddr::new(peer_addr.ip, peer_addr.port);
808
809 // A Data indication carries the peer's data, or the ICMP error a datagram
810 // relayed to that peer met (RFC 8656 §11.4, §11.6). One with neither is
811 // discarded.
812 let mut data = Data::default();
813 let mut icmp = Icmp::default();
814 let has_data = msg.contains(ATTR_DATA);
815 if has_data {
816 data.get_from(&msg)?;
817 } else {
818 icmp.get_from(&msg)?;
819 }
820
821 // The server relays only from addresses the client installed a permission
822 // for, so anything else is not what it claims to be (RFC 8656 §11.4, §11.6).
823 if !self
824 .relays
825 .values()
826 .any(|relay| relay.expects_data_from(&from.ip(), now))
827 {
828 debug!("discarding Data indication from {from}: no permission");
829 return Ok(());
830 }
831
832 if has_data {
833 debug!("data indication received from {}", from);
834 self.events.push_back(Event::DataIndicationOrChannelData(
835 None,
836 from,
837 BytesMut::from(&data.0[..]),
838 ))
839 } else {
840 debug!("{icmp} reported for {from}");
841 self.events.push_back(Event::IcmpError(from, icmp))
842 }
843 }
844
845 Ok(())
846 }
847
848 /// Deals with a transaction that ended without a response the client could act on.
849 ///
850 /// One that exhausted its retransmissions: a Refresh or ChannelBind is started once more
851 /// as a new transaction, so one lost burst does not let the allocation lapse or leave a
852 /// channel unbound for good. A ChannelBind that fails again returns its binding to idle,
853 /// so the next send binds it again. Anything not started again is reported as
854 /// [`Event::TransactionTimeout`], under the id its caller knows.
855 ///
856 /// One that failed for another reason (its responses were not authentic, or carried
857 /// attributes the client does not understand) is not started again, and is reported by
858 /// the error event of its kind.
859 fn handle_transaction_failure(&mut self, now: Instant, tr: Transaction, failure: Failure) {
860 // RFC 8489 §9.2.5: when every response that arrived was discarded, the failure is an
861 // integrity violation, not a timeout.
862 let failure = match failure {
863 Failure::Timeout if tr.discarded => Failure::IntegrityViolation,
864 other => other,
865 };
866 let timed_out = matches!(failure, Failure::Timeout);
867 let id = tr.transaction_type.report_id(tr.transaction_id);
868 match tr.transaction_type {
869 TransactionType::RefreshRequest(relayed_addr, lifetime, retry) => {
870 if timed_out
871 && !retry.timeout
872 && let Some(mut relay) = self.relay_by_key(relayed_addr)
873 && relay
874 .refresh_allocation_with(
875 now,
876 lifetime,
877 retry.after_timeout(tr.transaction_id),
878 )
879 .is_ok()
880 {
881 debug!("refresh timed out; sent again");
882 return;
883 }
884 let Some(mut relay) = self.relay_by_key(relayed_addr) else {
885 return;
886 };
887 let releasing = lifetime.is_zero();
888 relay.refresh_failed(now, lifetime, RequestError::Failed(failure.error()));
889 if releasing || !timed_out {
890 // The release is over, and reported as that; a failure that is not a
891 // timeout was reported as the refresh error it is.
892 return;
893 }
894 }
895 TransactionType::ChannelBindRequest(relayed_addr, bind_addr, retry) => {
896 if timed_out
897 && !retry.timeout
898 && let Some(mut relay) = self.relay_by_key(relayed_addr)
899 && relay
900 .rebind_channel(now, bind_addr, retry.after_timeout(tr.transaction_id))
901 .is_ok()
902 {
903 debug!("channel bind for {bind_addr} timed out; sent again");
904 return;
905 }
906 if let Some(mut relay) = self.relay_by_key(relayed_addr) {
907 if timed_out {
908 relay.channel_bind_timed_out(bind_addr);
909 } else {
910 relay.channel_bind_failed(
911 now,
912 bind_addr,
913 RequestError::Failed(failure.error()),
914 );
915 return;
916 }
917 }
918 }
919 TransactionType::FamilyRelease(relayed_addr, family, retry) => {
920 if timed_out
921 && !retry.timeout
922 && let Some(mut relay) = self.relay_by_key(relayed_addr)
923 && relay
924 .release_family_with(
925 now,
926 crate::proto::reqfamily::RequestedAddressFamily(family),
927 retry.after_timeout(tr.transaction_id),
928 )
929 .is_ok()
930 {
931 return;
932 }
933 // Nothing says the server deleted the address, so it is kept; the periodic
934 // Refresh keeps the whole allocation alive.
935 if let Some(relay) = self.relays.get(&relayed_addr) {
936 self.events.push_back(Event::RefreshError(
937 relay.name(),
938 RequestError::Failed(failure.error()),
939 ));
940 }
941 return;
942 }
943 TransactionType::ConnectRequest(relayed_addr, peer_addr, _) => {
944 // Nothing is outstanding for the peer any more.
945 if let Some(relay) = self.relays.get_mut(&relayed_addr) {
946 relay.connecting.remove(&peer_addr);
947 }
948 if !timed_out {
949 self.events.push_back(Event::ConnectError(
950 id,
951 peer_addr,
952 RequestError::Failed(failure.error()),
953 ));
954 return;
955 }
956 }
957 TransactionType::CreatePermissionRequest(relayed_addr, peer_addr, _, _) => {
958 if !timed_out {
959 // A permission the application asked for is not there; a refresh that
960 // failed this way leaves the permissions the time the server last
961 // granted, and they are asked for again.
962 if let Some(peer_addr) = peer_addr {
963 if let Some(relay) = self.relays.get_mut(&relayed_addr) {
964 relay.forget_unless_permitted(peer_addr.ip(), now);
965 }
966 self.events.push_back(Event::CreatePermissionError(
967 id,
968 RequestError::Failed(failure.error()),
969 ));
970 }
971 return;
972 }
973 }
974 TransactionType::AllocateAttempt(_) | TransactionType::AllocateRequest(_) => {
975 if !timed_out {
976 self.events.push_back(Event::AllocateError(
977 id,
978 RequestError::Failed(failure.error()),
979 ));
980 return;
981 }
982 }
983 TransactionType::BindingRequest => {
984 if !timed_out {
985 self.events
986 .push_back(Event::BindingError(id, failure.error()));
987 return;
988 }
989 }
990 TransactionType::OrphanRelease => return,
991 }
992 self.events.push_back(Event::TransactionTimeout(id));
993 }
994
995 fn handle_channel_data(&mut self, now: Instant, data: &[u8]) -> Result<()> {
996 let mut ch_data = ChannelData {
997 raw: data.to_vec(),
998 ..Default::default()
999 };
1000 ch_data.decode()?;
1001
1002 // A channel is the binding of one allocation; it is accepted from the moment its
1003 // ChannelBind is sent (RFC 8656 §12).
1004 let (relay, addr) = self
1005 .relays
1006 .values_mut()
1007 .find_map(|relay| {
1008 let addr = relay.binding_mgr.find_by_number(ch_data.number.0)?.addr;
1009 Some((relay, addr))
1010 })
1011 .ok_or(Error::ErrChannelBindNotFound)?;
1012
1013 // The server relays only from addresses the client holds a permission for
1014 // (RFC 8656 §12.6).
1015 if !relay.expects_data_from(&addr.ip(), now) {
1016 debug!(
1017 "discarding ChannelData from {addr} (ch={}): no permission",
1018 ch_data.number.0
1019 );
1020 return Ok(());
1021 }
1022 if let Some(b) = relay.binding_mgr.get_by_number(ch_data.number.0) {
1023 b.used = true;
1024 }
1025
1026 trace!(
1027 "channel data received from {} (ch={})",
1028 addr, ch_data.number.0
1029 );
1030
1031 self.events.push_back(Event::DataIndicationOrChannelData(
1032 Some(ch_data.number),
1033 addr,
1034 BytesMut::from(&ch_data.data[..]),
1035 ));
1036
1037 Ok(())
1038 }
1039
1040 /// Borrows the allocation for `relayed_addr` so data can be sent or permissions created.
1041 ///
1042 /// # Errors
1043 ///
1044 /// Fails if this client has no allocation for that address — it was never allocated, or has
1045 /// already been closed.
1046 pub fn relay(&mut self, relayed_addr: SocketAddr) -> Result<Relay<'_>> {
1047 // An allocation is kept under its first relayed address and found by any address it
1048 // has now: either of the two of a dual allocation.
1049 let key = self
1050 .relays
1051 .iter()
1052 .find(|(_, relay)| relay.addrs.contains(&relayed_addr))
1053 .map(|(key, _)| *key)
1054 .ok_or(Error::ErrStreamNotExisted)?;
1055 Ok(Relay {
1056 relayed_addr: key,
1057 client: self,
1058 })
1059 }
1060
1061 /// The allocation kept under `key`, whatever relayed addresses it has now.
1062 fn relay_by_key(&mut self, key: RelayedAddr) -> Option<Relay<'_>> {
1063 self.relays.contains_key(&key).then_some(Relay {
1064 relayed_addr: key,
1065 client: self,
1066 })
1067 }
1068
1069 /// Whether this client is waiting on a response for transaction `id`.
1070 ///
1071 /// A STUN response belongs to whoever sent the matching request — [RFC 5389 §7.3.3] matches
1072 /// them by transaction ID, and nothing else identifies the owner. That is only a question
1073 /// worth asking when several STUN users share one socket, which is exactly the situation a
1074 /// host is in when it points a STUN gatherer and this client at the same server address: both
1075 /// see every response, and the four-tuple is identical for both, so addresses cannot say whose
1076 /// a response is.
1077 ///
1078 /// Such a host calls this to route a response, rather than guessing from the peer address and
1079 /// handing it to a client that will silently discard it — [`handle_read`](sansio::Protocol::handle_read)
1080 /// drops a response with no matching transaction, as it must.
1081 ///
1082 /// Applies to responses only. TURN ChannelData carries no transaction ID at all, and
1083 /// indications are not transaction-matched; both are routed by address.
1084 ///
1085 /// [RFC 5389 §7.3.3]: https://www.rfc-editor.org/rfc/rfc5389#section-7.3.3
1086 #[must_use]
1087 pub fn has_transaction(&self, id: &TransactionId) -> bool {
1088 self.tr_map.find(id).is_some()
1089 }
1090
1091 /// send_binding_request_to sends a new STUN request to the given transport address
1092 /// return key to find out corresponding Event either BindingResponse or BindingRequestTimeout
1093 pub fn send_binding_request_to(
1094 &mut self,
1095 now: Instant,
1096 to: SocketAddr,
1097 ) -> Result<TransactionId> {
1098 let msg = {
1099 // RFC 8489 section 7: "When the FINGERPRINT extension is used, an agent includes
1100 // the FINGERPRINT attribute in messages it sends to another agent": the client
1101 // ends every other message with it, and this one shares their socket.
1102 let mut attrs: Vec<Box<dyn Setter + '_>> =
1103 vec![Box::new(TransactionId::new()), Box::new(BINDING_REQUEST)];
1104 if !self.software.text.is_empty() {
1105 attrs.push(Box::new(self.software.clone()));
1106 }
1107 attrs.push(Box::new(FINGERPRINT));
1108
1109 let mut msg = Message::new();
1110 msg.build(&attrs)?;
1111 msg
1112 };
1113
1114 debug!("client.SendBindingRequestTo call PerformTransaction 1");
1115 self.perform_transaction(now, &msg, to, TransactionType::BindingRequest, None)
1116 }
1117
1118 /// send_binding_request sends a new STUN request to the STUN server
1119 /// return key to find out corresponding Event either BindingResponse or BindingRequestTimeout
1120 pub fn send_binding_request(&mut self, now: Instant) -> Result<TransactionId> {
1121 if let Some(stun_serv_addr) = &self.stun_serv_addr {
1122 self.send_binding_request_to(now, *stun_serv_addr)
1123 } else {
1124 Err(Error::ErrStunserverAddressNotSet)
1125 }
1126 }
1127
1128 // stun_server_addr return the STUN server address
1129 fn stun_server_addr(&self) -> Option<SocketAddr> {
1130 self.stun_serv_addr
1131 }
1132
1133 /* https://datatracker.ietf.org/doc/html/rfc8656#section-20
1134 TURN TURN Peer Peer
1135 client server A B
1136 | | | |
1137 |--- Allocate request -------------->| | |
1138 | Transaction-Id=0xA56250D3F17ABE679422DE85 | |
1139 | SOFTWARE="Example client, version 1.03" | |
1140 | LIFETIME=3600 (1 hour) | | |
1141 | REQUESTED-TRANSPORT=17 (UDP) | | |
1142 | DONT-FRAGMENT | | |
1143 | | | |
1144 |<-- Allocate error response --------| | |
1145 | Transaction-Id=0xA56250D3F17ABE679422DE85 | |
1146 | SOFTWARE="Example server, version 1.17" | |
1147 | ERROR-CODE=401 (Unauthorized) | | |
1148 | REALM="example.com" | | |
1149 | NONCE="obMatJos2gAAAadl7W7PeDU4hKE72jda" | |
1150 | PASSWORD-ALGORITHMS=MD5 and SHA256 | |
1151 | | | |
1152 |--- Allocate request -------------->| | |
1153 | Transaction-Id=0xC271E932AD7446A32C234492 | |
1154 | SOFTWARE="Example client 1.03" | | |
1155 | LIFETIME=3600 (1 hour) | | |
1156 | REQUESTED-TRANSPORT=17 (UDP) | | |
1157 | DONT-FRAGMENT | | |
1158 | USERNAME="George" | | |
1159 | REALM="example.com" | | |
1160 | NONCE="obMatJos2gAAAadl7W7PeDU4hKE72jda" | |
1161 | PASSWORD-ALGORITHMS=MD5 and SHA256 | |
1162 | PASSWORD-ALGORITHM=SHA256 | | |
1163 | MESSAGE-INTEGRITY=... | | |
1164 | MESSAGE-INTEGRITY-SHA256=... | | |
1165 | | | |
1166 |<-- Allocate success response ------| | |
1167 | Transaction-Id=0xC271E932AD7446A32C234492 | |
1168 | SOFTWARE="Example server, version 1.17" | |
1169 | LIFETIME=1200 (20 minutes) | | |
1170 | XOR-RELAYED-ADDRESS=192.0.2.15:50000 | |
1171 | XOR-MAPPED-ADDRESS=192.0.2.1:7000 | |
1172 | MESSAGE-INTEGRITY-SHA256=... | | |
1173 */
1174 /// Replaces the long-term credential used to sign subsequent requests, **keeping any
1175 /// existing allocation**.
1176 ///
1177 /// This is for a new **password** for the same username. An allocation belongs to the
1178 /// username that created it: [RFC 8656 §5] has the server answer a request for it made
1179 /// under another username with **441 (Wrong Credentials)**. Giving up the allocation and
1180 /// allocating again is no way round a rotation either, since the server still holds the
1181 /// allocation for the 5-tuple and answers the new Allocate with 437 (Allocation Mismatch).
1182 /// So with a new password the existing allocation is re-signed, and its permissions and
1183 /// channel bindings survive.
1184 ///
1185 /// A new username takes effect for the next [`allocate`](Self::allocate) only: RFC 8656
1186 /// section 5 has every request about an allocation use the username that created it, so
1187 /// live allocations keep signing with theirs (and their password). To move to the new
1188 /// username, [`Relay::close`] an allocation, wait for [`Event::AllocationReleased`], and
1189 /// allocate again.
1190 ///
1191 /// The realm is *not* re-negotiated. It was learned from the server's 401 during the
1192 /// first `Allocate`, and a credential rotation keeps the same server, so it still
1193 /// applies. Follow this with [`Self::refresh_allocations`] so the server sees the new
1194 /// credential before the allocation would otherwise expire.
1195 ///
1196 /// [RFC 8656 §5]: https://datatracker.ietf.org/doc/html/rfc8656#section-5
1197 pub fn update_credentials(&mut self, username: String, password: String) -> Result<()> {
1198 // RFC 8656 section 5: an allocation's requests stay under the username that created
1199 // it; only a new password for that username re-keys it.
1200 let same_username = username == self.login.username;
1201 let login = Arc::new(Login {
1202 username,
1203 password,
1204 password_algorithms: self.login.password_algorithms.clone(),
1205 });
1206 if !same_username {
1207 self.login = login;
1208 return Ok(());
1209 }
1210
1211 // Each allocation carries the credential it will sign its own Refresh /
1212 // CreatePermission / ChannelBind with, so they have to be re-keyed too — otherwise
1213 // the next refresh would still present the retired credential. The realm, the nonce
1214 // and the password algorithm stay what the server last asked for. An allocation the
1215 // server gave without a credential stays unsigned until the server asks for one.
1216 let mut rekeyed = Vec::with_capacity(self.relays.len());
1217 for (key, relay) in &self.relays {
1218 rekeyed.push((
1219 *key,
1220 relay
1221 .credential
1222 .with_login(login.clone(), self.crypto_provider.crypto())?,
1223 ));
1224 }
1225 for (key, credential) in rekeyed {
1226 if let Some(relay) = self.relays.get_mut(&key) {
1227 relay.credential = Arc::new(credential);
1228 }
1229 }
1230 self.login = login;
1231
1232 Ok(())
1233 }
1234
1235 /// Refreshes every live allocation, re-signing each with the current credential.
1236 ///
1237 /// Each allocation is refreshed with its own current lifetime, so this extends rather
1238 /// than changes it. Intended to follow [`update_credentials`](Self::update_credentials).
1239 pub fn refresh_allocations(&mut self, now: Instant) -> Result<()> {
1240 let relays: Vec<(RelayedAddr, Duration)> = self
1241 .relays
1242 .iter()
1243 .filter(|(_, relay)| !relay.releasing)
1244 .map(|(addr, relay)| (*addr, relay.lifetime))
1245 .collect();
1246
1247 for (relayed_addr, lifetime) in relays {
1248 if let Some(mut relay) = self.relay_by_key(relayed_addr) {
1249 relay.refresh_allocation(now, lifetime)?;
1250 }
1251 }
1252
1253 Ok(())
1254 }
1255
1256 /// Builds a request about `relay`: `attrs`, then the allocation's credential when it has
1257 /// one, then FINGERPRINT.
1258 pub(crate) fn build_request(
1259 &self,
1260 method: Method,
1261 attrs: Vec<Box<dyn Setter>>,
1262 relay: &RelayState,
1263 ) -> Result<Message> {
1264 self.build_request_with(method, attrs, &relay.credential)
1265 }
1266
1267 /// Builds a request made with `credential`; without one until the server asked for it.
1268 pub(crate) fn build_request_with(
1269 &self,
1270 method: Method,
1271 attrs: Vec<Box<dyn Setter>>,
1272 credential: &Credential,
1273 ) -> Result<Message> {
1274 self.build_request_as(TransactionId::new(), method, attrs, credential)
1275 }
1276
1277 /// Builds the request `id`: `attrs`, SOFTWARE when the client has one (RFC 8656 §5: in
1278 /// every Allocate and Refresh, and allowed in any other request), what the long-term
1279 /// credential mechanism adds once the server asked for the credential (RFC 8489 §9.2.3,
1280 /// §9.2.5: USERNAME or USERHASH, REALM, NONCE, PASSWORD-ALGORITHMS and
1281 /// PASSWORD-ALGORITHM when the server offered algorithms, and MESSAGE-INTEGRITY-SHA256
1282 /// then, MESSAGE-INTEGRITY otherwise), and FINGERPRINT.
1283 pub(crate) fn build_request_as(
1284 &self,
1285 id: TransactionId,
1286 method: Method,
1287 attrs: Vec<Box<dyn Setter>>,
1288 credential: &Credential,
1289 ) -> Result<Message> {
1290 let mut setters: Vec<Box<dyn Setter + '_>> = vec![
1291 Box::new(id),
1292 Box::new(MessageType::new(method, CLASS_REQUEST)),
1293 ];
1294 setters.extend(attrs.into_iter().map(|a| a as Box<dyn Setter + '_>));
1295 if !self.software.text.is_empty() {
1296 setters.push(Box::new(self.software.clone()));
1297 }
1298 if let Some(authentication) = credential.setter(self.crypto_provider.crypto()) {
1299 setters.push(authentication);
1300 }
1301 setters.push(Box::new(FINGERPRINT));
1302
1303 let mut msg = Message::new();
1304 msg.build(&setters)?;
1305 Ok(msg)
1306 }
1307
1308 /// Deletes the allocation the server holds for this client's 5-tuple, with a Refresh of
1309 /// LIFETIME 0 (RFC 8656 §8), when the client keeps no copy of it. Nothing is reported.
1310 pub(crate) fn release_orphan(
1311 &mut self,
1312 now: Instant,
1313 credential: &Arc<Credential>,
1314 ) -> Result<()> {
1315 let msg = self.build_request_with(
1316 METHOD_REFRESH,
1317 vec![Box::new(Lifetime(Duration::ZERO))],
1318 credential,
1319 )?;
1320 let to = self.turn_server_addr_or_err()?;
1321 self.perform_transaction(
1322 now,
1323 &msg,
1324 to,
1325 TransactionType::OrphanRelease,
1326 Some(credential.clone()),
1327 )?;
1328 Ok(())
1329 }
1330
1331 /// Points the client at the alternate server of a 300 (Try Alternate), for an
1332 /// application that chooses to follow the redirection (RFC 8489 §10, RFC 8656 §7.4). The
1333 /// client never follows one by itself: the application owns the socket and the choice of
1334 /// server.
1335 ///
1336 /// `redirect` comes from [`ErrorResponse::try_alternate`], which is there only for a 300
1337 /// that was authenticated with the allocation's credential; RFC 8489 §14.8 has a client
1338 /// validate the response before it redirects itself. (An application that trusts the
1339 /// address of an unauthenticated 300, [`ErrorResponse::alternate_server`], makes the
1340 /// `TryAlternate` itself.) The server of the address family the client reached the old
1341 /// one over is taken, and becomes [`Client::turn_server_addr`]. The application then
1342 /// calls [`Client::allocate`] again: the request goes to the alternate server over the
1343 /// same transport protocol and with the same credentials. Over TLS or DTLS the
1344 /// application checks the new server's certificate against
1345 /// [`TryAlternate::domain`] when it is there, and against the name it used for the old
1346 /// server when it is not.
1347 ///
1348 /// # Errors
1349 ///
1350 /// Fails, and leaves the server as it is, when an Allocate was already sent to the
1351 /// alternate server within the last five minutes: the redirection is a loop and RFC 8489
1352 /// §10 has the client ignore it and take the transaction as failed. Fails as well while
1353 /// the client holds an allocation (its server cannot change), or when no TURN server is
1354 /// configured.
1355 pub fn follow_alternate(
1356 &mut self,
1357 now: Instant,
1358 redirect: &TryAlternate,
1359 ) -> Result<SocketAddr> {
1360 let current = self.turn_server_addr_or_err()?;
1361 if !self.relays.is_empty() {
1362 return Err(Error::Other(
1363 "the TURN server cannot change while the client holds an allocation".to_owned(),
1364 ));
1365 }
1366 let server = redirect
1367 .server_for(current.ip())
1368 .ok_or(Error::ErrAttributeNotFound)?;
1369 if !self.redirects.follow(server, now) {
1370 return Err(Error::Other(format!(
1371 "redirection loop: an Allocate was sent to {server} within the last five \
1372 minutes (RFC 8489 section 10)"
1373 )));
1374 }
1375 debug!("TURN server {current} redirects to {server}");
1376 self.turn_serv_addr = Some(server);
1377 Ok(server)
1378 }
1379
1380 /// The path MTU to the server, when the application knows it (RFC 8489 Section 6.1): a
1381 /// request over UDP larger than it allows is refused with `ErrPacketTooBig`. `None` (the
1382 /// default): unknown, 576 bytes for IPv4 and 1280 for IPv6.
1383 pub fn set_path_mtu(&mut self, mtu: Option<usize>) {
1384 self.path_mtu = mtu;
1385 }
1386
1387 /// Returns the TURN server address, if configured.
1388 pub fn turn_server_addr(&self) -> Option<SocketAddr> {
1389 self.turn_serv_addr
1390 }
1391
1392 /// Returns the TURN server address or an error if not configured.
1393 fn turn_server_addr_or_err(&self) -> Result<SocketAddr> {
1394 self.turn_serv_addr.ok_or(Error::ErrNilTurnSocket)
1395 }
1396
1397 /// Returns the local address this client is bound to.
1398 pub fn local_addr(&self) -> SocketAddr {
1399 self.local_addr
1400 }
1401
1402 /// WriteTo sends data to the specified destination using the base socket.
1403 fn write_to(&mut self, now: Instant, data: &[u8], remote: SocketAddr) {
1404 self.transmits.push_back(TransportMessage {
1405 now,
1406 transport: TransportContext {
1407 local_addr: self.local_addr,
1408 peer_addr: remote,
1409 transport_protocol: self.transport_protocol,
1410 ecn: None,
1411 },
1412 message: BytesMut::from(data),
1413 });
1414 }
1415
1416 // PerformTransaction performs STUN transaction
1417 fn perform_transaction(
1418 &mut self,
1419 now: Instant,
1420 msg: &Message,
1421 to: SocketAddr,
1422 transaction_type: TransactionType,
1423 credential: Option<Arc<Credential>>,
1424 ) -> Result<TransactionId> {
1425 // RFC 8489 Section 6.1: outside MTU probing, a request over UDP does not exceed the
1426 // path MTU (configured with `set_path_mtu`, else the RFC's 576 / 1280 bytes). Data
1427 // indications are not requests and are left to the path.
1428 if self.transport_protocol == TransportProtocol::UDP {
1429 let (unknown, overhead) = if to.is_ipv4() {
1430 (UNKNOWN_PATH_MTU_V4, IP_UDP_OVERHEAD_V4)
1431 } else {
1432 (UNKNOWN_PATH_MTU_V6, IP_UDP_OVERHEAD_V6)
1433 };
1434 let limit = self.path_mtu.unwrap_or(unknown).saturating_sub(overhead);
1435 if msg.raw.len() > limit {
1436 debug!(
1437 "{} request of {} bytes not sent: the path takes {limit}",
1438 msg.typ,
1439 msg.raw.len()
1440 );
1441 return Err(Error::ErrPacketTooBig);
1442 }
1443 }
1444 trace!(
1445 "start {} transaction {:?} to {}",
1446 msg.typ, msg.transaction_id, to
1447 );
1448 self.tr_map.start(
1449 now,
1450 TransactionConfig {
1451 transaction_id: msg.transaction_id,
1452 method: msg.typ.method,
1453 transaction_type,
1454 raw: BytesMut::from(&msg.raw[..]),
1455 local_addr: self.local_addr,
1456 peer_addr: to,
1457 transport_protocol: self.transport_protocol,
1458 credential,
1459 },
1460 );
1461 // In the order it was asked for, with whatever else the client sends.
1462 while let Some(transmit) = self.tr_map.poll_transmit() {
1463 self.transmits.push_back(transmit);
1464 }
1465
1466 Ok(msg.transaction_id)
1467 }
1468}