Skip to main content

Client

Struct Client 

Source
pub struct Client { /* private fields */ }
Expand description

Client is a STUN client

Implementations§

Source§

impl Client

Source

pub fn allocate(&mut self, now: Instant) -> Result<TransactionId>

Sends an Allocate request for a UDP relayed address to the TURN server.

Returns the id that Event::AllocateResponse, Event::AllocateError or Event::TransactionTimeout will name.

Source

pub fn allocate_with( &mut self, now: Instant, options: AllocateOptions, ) -> Result<TransactionId>

Sends an Allocate request with options (RFC 8656 §7.1): an address family, a second (IPv6) address, a lifetime, DONT-FRAGMENT, an even port, a reserved port.

§Errors

Fails, with nothing sent, if the RFC forbids the combination of options (see AllocateOptions), or if the server has refused the address family and may not be asked again: for good after a 440 (Address Family not Supported), for a minute after it had no capacity for one of two families, and after it answered with an address of a family that was not asked for (RFC 8656 §7.3, §7.4). An application that believes the cause is gone calls Client::clear_allocate_restrictions.

Source

pub fn clear_allocate_restrictions(&mut self)

Lets Client::allocate_with ask the server again for what it refused: an address family it answered 440 or 508 for, or any allocation after it answered with a family that was not asked for. RFC 8656 §7.3 and §7.4 forbid asking again until the client “believes the mismatch has been fixed”; calling this says the application does.

Source

pub fn answered_another_family(&self) -> bool

Whether the server answered an Allocate of this client with a relayed address of a family that was not asked for (RFC 8656 §7.3), so that Client::allocate_with refuses to ask it again until Client::clear_allocate_restrictions. A caller that replaces the client keeps that in mind for the server itself.

Source§

impl Client

Source

pub fn new( config: ClientConfig, crypto_provider: Arc<dyn RTCCryptoProvider>, ) -> Result<Self>

Returns a new TURN client.

The crypto provider is supplied by the caller; this crate never resolves a default.

Source

pub fn cached_credential(&self) -> Option<CachedCredential>

The credential the server accepted the last allocation of this client with: its realm, nonce and password algorithm, with this client’s login (RFC 8489 §9.2.3.2). None before an authenticated Allocate succeeded, and for an allocation the server granted without a credential.

Source

pub fn use_cached_credential(&mut self, cached: &CachedCredential) -> bool

Starts this client’s Allocates with cached, the credential another client’s authenticated request to the same server succeeded with (RFC 8489 §9.2.3.2: “The client SHOULD cache the username, password, realm, and nonce for subsequent communications with the server. When the client sends a subsequent request, it MUST include … these cached values”): the first Allocate carries the credential, and the 401 round trip of a first request (§9.2.3.1) is saved. Taken only when cached is of this client’s TURN server address and of the same user name, password and accepted password algorithms; returns whether it was taken.

A 438 (Stale Nonce) to such an Allocate is answered with the new nonce (§9.2.5). A 401 to it (the server no longer knows the realm or the nonce) sends the request again as a request made after a first 401, so a cached credential costs at most the round trip it was to save.

Source

pub fn set_server_error_resends(&mut self, resends: u32)

How many times a request answered with a server error (500 to 599) is sent again before the error is reported (RFC 8489 §6.3.4: the client “MAY resend the request; clients that do so MUST limit the number of times they do this. Unless a specific error code specifies a different value, the number of retransmissions SHOULD be limited to 4”). The default is stun::timer::DEFAULT_SERVER_ERROR_RESENDS, 4; 0 reports the first server error.

Every request is resent this way: Binding, Allocate, Refresh (a release too), CreatePermission, ChannelBind and Connect. Each resend is a new transaction under a new transaction id, made again with the allocation’s current credential, and waits after the error as long as the retransmission of the same number would (stun::timer::server_error_resend_delay: RTO, 2 RTO, 4 RTO, 8 RTO). The count belongs to the one request: a new one (the next Refresh, another Allocate) starts from none. Its events name the id its caller was handed, and the error event of its kind (Event::AllocateError, Event::RefreshError, …) comes only after the last resend was answered with a server error too. A 508 (Insufficient Capacity) is not resent: to an Allocate, RFC 8656 §7.4 has the client consider the operation failed and wait at least a minute before it asks the server for another allocation, and the code names a capacity limit for the other methods too (§19).

Source

pub fn set_unauthenticated_allocations(&mut self, accept: bool)

Whether a client configured with a long-term credential (ClientConfig::username, ClientConfig::password) believes a success response that carries no integrity attribute: one to the first Allocate, which goes without the credential (RFC 8489 §9.2.3.1), and so to the requests of the allocation it makes. Off by default.

Off, such a response is discarded as one that fails its integrity check (RFC 8489 §9.2.5): over UDP as if it had never been received, the request being retransmitted, over TCP or TLS ending the transaction at once, and either way reported as RequestError::Failed with ErrIntegrityMismatch in the error event of its kind (Event::AllocateError, …), not as a timeout. A 401 that arrives meanwhile is answered as usual. RFC 8656 §21.1.5 relies on the integrity of responses to keep an attacker from handing the client “a faked relayed address”; a success nothing signs can come from anyone who sees the request, and the client has the credential to ask for a signed one.

On, a server that asks for no credential (RFC 8656 §7.2 step 1, the access-network servers of RFC 8155 §9) can be used by a client that has one: its unsigned success is an allocation, and the allocation’s requests go without the credential until the server asks for it with a 401. A client without a credential always takes such a success: there is no key to check it with.

Source

pub fn relay(&mut self, relayed_addr: SocketAddr) -> Result<Relay<'_>>

Borrows the allocation for relayed_addr so data can be sent or permissions created.

§Errors

Fails if this client has no allocation for that address — it was never allocated, or has already been closed.

Source

pub fn has_transaction(&self, id: &TransactionId) -> bool

Whether this client is waiting on a response for transaction id.

A STUN response belongs to whoever sent the matching request — RFC 5389 §7.3.3 matches them by transaction ID, and nothing else identifies the owner. That is only a question worth asking when several STUN users share one socket, which is exactly the situation a host is in when it points a STUN gatherer and this client at the same server address: both see every response, and the four-tuple is identical for both, so addresses cannot say whose a response is.

Such a host calls this to route a response, rather than guessing from the peer address and handing it to a client that will silently discard it — handle_read drops a response with no matching transaction, as it must.

Applies to responses only. TURN ChannelData carries no transaction ID at all, and indications are not transaction-matched; both are routed by address.

Source

pub fn send_binding_request_to( &mut self, now: Instant, to: SocketAddr, ) -> Result<TransactionId>

send_binding_request_to sends a new STUN request to the given transport address return key to find out corresponding Event either BindingResponse or BindingRequestTimeout

Source

pub fn send_binding_request(&mut self, now: Instant) -> Result<TransactionId>

send_binding_request sends a new STUN request to the STUN server return key to find out corresponding Event either BindingResponse or BindingRequestTimeout

Source

pub fn update_credentials( &mut self, username: String, password: String, ) -> Result<()>

Replaces the long-term credential used to sign subsequent requests, keeping any existing allocation.

This is for a new password for the same username. An allocation belongs to the username that created it: RFC 8656 §5 has the server answer a request for it made under another username with 441 (Wrong Credentials). Giving up the allocation and allocating again is no way round a rotation either, since the server still holds the allocation for the 5-tuple and answers the new Allocate with 437 (Allocation Mismatch). So with a new password the existing allocation is re-signed, and its permissions and channel bindings survive.

A new username takes effect for the next allocate only: RFC 8656 section 5 has every request about an allocation use the username that created it, so live allocations keep signing with theirs (and their password). To move to the new username, Relay::close an allocation, wait for Event::AllocationReleased, and allocate again.

The realm is not re-negotiated. It was learned from the server’s 401 during the first Allocate, and a credential rotation keeps the same server, so it still applies. Follow this with Self::refresh_allocations so the server sees the new credential before the allocation would otherwise expire.

Source

pub fn refresh_allocations(&mut self, now: Instant) -> Result<()>

Refreshes every live allocation, re-signing each with the current credential.

Each allocation is refreshed with its own current lifetime, so this extends rather than changes it. Intended to follow update_credentials.

Source

pub fn follow_alternate( &mut self, now: Instant, redirect: &TryAlternate, ) -> Result<SocketAddr>

Points the client at the alternate server of a 300 (Try Alternate), for an application that chooses to follow the redirection (RFC 8489 §10, RFC 8656 §7.4). The client never follows one by itself: the application owns the socket and the choice of server.

redirect comes from ErrorResponse::try_alternate, which is there only for a 300 that was authenticated with the allocation’s credential; RFC 8489 §14.8 has a client validate the response before it redirects itself. (An application that trusts the address of an unauthenticated 300, ErrorResponse::alternate_server, makes the TryAlternate itself.) The server of the address family the client reached the old one over is taken, and becomes Client::turn_server_addr. The application then calls Client::allocate again: the request goes to the alternate server over the same transport protocol and with the same credentials. Over TLS or DTLS the application checks the new server’s certificate against TryAlternate::domain when it is there, and against the name it used for the old server when it is not.

§Errors

Fails, and leaves the server as it is, when an Allocate was already sent to the alternate server within the last five minutes: the redirection is a loop and RFC 8489 §10 has the client ignore it and take the transaction as failed. Fails the same way when the redirection names no usable server (stun::alternate::is_usable_alternate: port 0, an unspecified, multicast, broadcast or IPv4-mapped address, or a loopback address while the server is not on one). Fails as well while the client holds an allocation (its server cannot change), or when no TURN server is configured.

Source

pub fn set_path_mtu(&mut self, mtu: Option<usize>)

The path MTU to the server, when the application knows it (RFC 8489 Section 6.1): a request over UDP larger than it allows is refused with ErrPacketTooBig. None (the default): unknown, 576 bytes for IPv4 and 1280 for IPv6.

Source

pub fn turn_server_addr(&self) -> Option<SocketAddr>

Returns the TURN server address, if configured.

Source

pub fn local_addr(&self) -> SocketAddr

Returns the local address this client is bound to.

Trait Implementations§

Source§

impl Protocol<TransportMessage<BytesMut>, TransportMessage<BytesMut>, ()> for Client

Source§

type Rout = ()

Output read message type Read more
Source§

type Wout = TransportMessage<BytesMut>

Output write message type Read more
Source§

type Eout = Event

Output event type Read more
Source§

type Error = Error

Error type for protocol operations
Source§

type Time = Instant

Time/Instant type for timeout handling Read more
Source§

fn handle_read(&mut self, msg: TaggedBytesMut) -> Result<(), Self::Error>

Handle an incoming read message. Read more
Source§

fn poll_read(&mut self) -> Option<Self::Rout>

Poll for a processed read message. Read more
Source§

fn handle_write(&mut self, _msg: TaggedBytesMut) -> Result<(), Self::Error>

Handle an outgoing write message. Read more
Source§

fn poll_write(&mut self) -> Option<Self::Wout>

Poll for a processed write message. Read more
Source§

fn poll_event(&mut self) -> Option<Self::Eout>

Poll for a generated event. Read more
Source§

fn handle_timeout(&mut self, now: Instant) -> Result<(), Self::Error>

Handle a timeout event. Read more
Source§

fn poll_timeout(&mut self) -> Option<Instant>

Poll for the next timeout deadline. Read more
Source§

fn close(&mut self) -> Result<(), Self::Error>

Close the protocol. Read more
Source§

fn handle_event(&mut self, _evt: Ein) -> Result<(), Self::Error>

Handle a custom event. Read more

Auto Trait Implementations§

§

impl !RefUnwindSafe for Client

§

impl !UnwindSafe for Client

§

impl Forget for Client

§

impl Freeze for Client

§

impl Move for Client

§

impl Send for Client
where Arc<dyn RTCCryptoProvider>: Send, Arc<Login>: Send, RawVecInner: Send, RawTable<(TransactionId, Transaction)>: Send, RawTable<(SocketAddr, usize)>: Send, RawTable<(SocketAddr, RtoEstimator)>: Send, BytesMut: Send, RawTable<(SocketAddr, RelayState)>: Send, &'static str: Send, BoxRaw<Error>: Send, Repr: Send, BoxRaw<dyn Error + Sync + Send>: Send, BoxRaw<AllocateState>: Send, Arc<Credential>: Send,

§

impl Sync for Client
where Arc<dyn RTCCryptoProvider>: Sync, Arc<Login>: Sync, RawVecInner: Sync, RawTable<(TransactionId, Transaction)>: Sync, RawTable<(SocketAddr, usize)>: Sync, RawTable<(SocketAddr, RtoEstimator)>: Sync, BytesMut: Sync, RawTable<(SocketAddr, RelayState)>: Sync, BoxRaw<Error>: Sync, Repr: Sync, BoxRaw<dyn Error + Sync + Send>: Sync, BoxRaw<AllocateState>: Sync, Arc<Credential>: Sync,

§

impl Unpin for Client
where Arc<dyn RTCCryptoProvider>: Unpin, Arc<Login>: Unpin, *const u8 is !null: Unpin, Box<AllocateState>: Unpin, *mut Shared: Unpin, Arc<Credential>: Unpin, &'static str: Unpin, Box<Error>: Unpin, *const () is !null: Unpin, &'static SimpleMessage: Unpin, *const Custom is !null: Unpin, Box<dyn Error + Sync + Send>: Unpin,

§

impl UnsafeUnpin for Client

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.