Skip to main content

Connection

Struct Connection 

Source
pub struct Connection(/* private fields */);
Expand description

A QUIC connection.

Implementations§

Source§

impl Connection

Source

pub fn side(&self) -> Side

The side of the connection (client or server)

Source

pub fn local_ip(&self) -> Option<IpAddr>

The local IP address which was used when the peer established the connection.

This can be different from the address the endpoint is bound to, in case the endpoint is bound to a wildcard address like 0.0.0.0 or ::.

This will return None for clients, or when the platform does not expose this information.

Source

pub fn remote_address(&self) -> SocketAddr

The peer’s UDP address.

Will panic if called after poll has returned Ready.

Source

pub fn rtt(&self, path_id: PathId) -> Option<Duration>

Current best estimate of this connection’s latency (round-trip-time).

Source

pub fn stats(&self) -> ConnectionStats

Connection statistics.

Source

pub fn congestion_state(&self, path_id: PathId) -> Option<Box<dyn Controller>>

Current state of the congestion control algorithm. (For debugging purposes)

Source

pub fn peer_identity(&self) -> Option<Box<Vec<CertificateDer<'static>>>>

Cryptographic identity of the peer.

Source

pub fn stable_id(&self) -> usize

A stable identifier for this connection

Peer addresses and connection IDs can change, but this value will remain fixed for the lifetime of the connection.

Source

pub fn export_keying_material( &self, output: &mut [u8], label: &[u8], context: &[u8], ) -> Result<(), ExportKeyingMaterialError>

Derive keying material from this connection’s TLS session secrets.

When both peers call this method with the same label and context arguments and output buffers of equal length, they will get the same sequence of bytes in output. These bytes are cryptographically strong and pseudorandom, and are suitable for use as keying material.

This function fails if called with an empty output or called prior to the handshake completing.

See RFC5705 for more information.

Source

pub fn weak_handle(&self) -> WeakConnectionHandle

Returns a weak reference to the inner connection struct.

Source

pub fn on_closed(&self) -> OnClosed

Wait for the connection to be closed without keeping a strong reference to it.

Source

pub fn force_key_update(&self)

Update traffic keys spontaneously

This primarily exists for testing purposes.

Source

pub fn handshake_data(&mut self) -> Result<Box<HandshakeData>, ConnectionError>

Available on rustls only.

Parameters negotiated during the handshake.

Source

pub fn max_datagram_size(&self) -> Option<usize>

Compute the maximum size of datagrams that may be passed to send_datagram().

Returns None if datagrams are unsupported by the peer or disabled locally.

This may change over the lifetime of a connection according to variation in the path MTU estimate. The peer can also enforce an arbitrarily small fixed limit, but if the peer’s limit is large this is guaranteed to be a little over a kilobyte at minimum.

Not necessarily the maximum size of received datagrams.

Source

pub fn datagram_send_buffer_space(&self) -> usize

Bytes available in the outgoing datagram buffer.

When greater than zero, calling send_datagram() with a datagram of at most this size is guaranteed not to cause older datagrams to be dropped.

Source

pub fn set_max_concurrent_uni_streams(&self, count: VarInt)

Modify the number of remotely initiated unidirectional streams that may be concurrently open.

No streams may be opened by the peer unless fewer than count are already open. Large counts increase both minimum and worst-case memory consumption.

Source

pub fn set_send_window(&self, send_window: u64)

Source

pub fn set_receive_window(&self, receive_window: VarInt)

Source

pub fn set_max_concurrent_bi_streams(&self, count: VarInt)

Modify the number of remotely initiated bidirectional streams that may be concurrently open.

No streams may be opened by the peer unless fewer than count are already open. Large counts increase both minimum and worst-case memory consumption.

Source

pub fn close(&self, error_code: VarInt, reason: &[u8])

Close the connection immediately.

Pending operations will fail immediately with ConnectionError::LocallyClosed. No more data is sent to the peer and the peer may drop buffered data upon receiving the CONNECTION_CLOSE frame.

error_code and reason are not interpreted, and are provided directly to the peer.

reason will be truncated to fit in a single packet with overhead; to improve odds that it is preserved in full, it should be kept under 1KiB.

§Gracefully closing a connection

Only the peer last receiving application data can be certain that all data is delivered. The only reliable action it can then take is to close the connection, potentially with a custom error code. The delivery of the final CONNECTION_CLOSE frame is very likely if both endpoints stay online long enough, and Endpoint::shutdown() can be used to provide sufficient time. Otherwise, the remote peer will time out the connection, provided that the idle timeout is not disabled.

The sending side can not guarantee all stream data is delivered to the remote application. It only knows the data is delivered to the QUIC stack of the remote endpoint. Once the local side sends a CONNECTION_CLOSE frame in response to calling close() the remote endpoint may drop any data it received but is as yet undelivered to the application, including data that was acknowledged as received to the local endpoint.

Source

pub async fn handshake_confirmed(&self) -> Result<(), ConnectionError>

Wait for the handshake to be confirmed.

As a server, who must be authenticated by clients, this happens when the handshake completes upon receiving a TLS Finished message from the client. In return, the server send a HANDSHAKE_DONE frame.

As a client, this happens when receiving a HANDSHAKE_DONE frame. At this point, the server has either accepted our authentication, or, if client authentication is not required, accepted our lack of authentication.

Source

pub async fn closed(&self) -> ConnectionError

Wait for the connection to be closed for any reason.

Source

pub fn close_reason(&self) -> Option<ConnectionError>

If the connection is closed, the reason why.

Returns None if the connection is still open.

Source

pub fn open_path_ensure( &self, network_path: impl Into<FourTuple>, initial_status: PathStatus, ) -> OpenPath

Opens a new path if no path exists yet for network_path.

Source

pub fn open_path( &self, network_path: impl Into<FourTuple>, initial_status: PathStatus, ) -> OpenPath

Opens an additional path if multipath is negotiated.

Source

pub fn open_path_socket( &self, addr: SocketAddr, socket: UdpSocket, initial_status: PathStatus, ) -> Result<OpenPath, Error>

Opens an additional path using a new socket.

The socket should already be bound to a local address (e.g., via Android’s Network.bindSocket(fd)). local_ip is derived from the socket’s bound address. The socket is registered with the endpoint and a recv task is spawned automatically.

Source

pub fn path(&self, id: PathId) -> Option<Path>

Returns the path handle for an open path.

Source

pub fn path_events(&self) -> PathEvents

Subscribe to path events for this connection.

Source

pub fn paths(&self) -> Vec<Path>

Returns the path handles.

Source

pub fn all_path_stats(&self) -> HashMap<PathId, PathStats>

Returns all path stats.

Source

pub fn live_path_stats(&self) -> HashMap<PathId, PathStats>

Returns path statistics for paths that are still active in the QUIC stack.

Discarded paths are omitted; their last recorded statistics are still available from Self::path_stats (e.g. via a retained Path handle) and included in Self::all_path_stats.

Source

pub fn all_path_status(&self) -> HashMap<PathId, PathStatus>

Returns all path status.

Source

pub fn nat_traversal_updates(&self) -> NatTraversalUpdates

Subscribe to NAT traversal updates for this connection.

Source

pub fn observed_external_addr(&self) -> ObservedExternalAddr

The latest external address observed by the peer.

Source

pub fn path_stats(&self, path_id: PathId) -> Option<PathStats>

Statistics for a specific path.

Source

pub fn is_multipath_enabled(&self) -> bool

Whether the multipath extension was negotiated for this connection.

Source

pub fn add_nat_traversal_address( &self, address: SocketAddr, ) -> Result<(), Error>

Registers a local address for the NAT traversal extension.

Source

pub fn remove_nat_traversal_address( &self, address: SocketAddr, ) -> Result<(), Error>

Removes a local address from the NAT traversal extension set.

Source

pub fn get_local_nat_traversal_addresses( &self, ) -> Result<Vec<SocketAddr>, Error>

Returns the local NAT traversal addresses known to this connection.

Source

pub fn get_remote_nat_traversal_addresses( &self, ) -> Result<Vec<SocketAddr>, Error>

Returns the remote NAT traversal addresses known to this connection.

Source

pub fn initiate_nat_traversal_round(&self) -> Result<Vec<SocketAddr>, Error>

Initiates a NAT traversal round and returns the candidate addresses being probed.

Source

pub fn poll_recv_datagram( &self, cx: &mut Context<'_>, ) -> Poll<Result<Bytes, ConnectionError>>

Poll for an application datagram.

Returns Poll::Pending if no datagram is currently available, after registering cx’s waker to be notified when one arrives.

See read_datagram() for an async wrapper and try_recv_datagram() for a non-blocking alternative.

Source

pub fn try_recv_datagram(&self) -> Result<Option<Bytes>, ConnectionError>

Try to receive an application datagram. Returns None if no datagram is available.

Source

pub async fn read_datagram(&self) -> Result<Bytes, ConnectionError>

Receive an application datagram.

Source

pub fn send_datagram(&self, data: Bytes) -> Result<(), SendDatagramError>

Transmit data as an unreliable, unordered application datagram.

Application datagrams are a low-level primitive. They may be lost or delivered out of order, and data must both fit inside a single QUIC packet and be smaller than the maximum dictated by the peer.

Source

pub async fn send_datagram_wait( &self, data: Bytes, ) -> Result<(), SendDatagramError>

Transmit data as an unreliable, unordered application datagram.

Unlike send_datagram(), this method will wait for buffer space during congestion conditions, which effectively prioritizes old datagrams over new datagrams.

See send_datagram() for details.

Source

pub fn try_open_uni(&self) -> Result<SendStream, OpenStreamError>

Initiate a new outgoing unidirectional stream immediately.

Returns OpenStreamError::StreamsExhausted instead of waiting if stream ID flow control does not currently allow opening another stream.

Source

pub async fn open_uni(&self) -> Result<SendStream, ConnectionError>

Initiate a new outgoing unidirectional stream.

Source

pub fn try_open_bi(&self) -> Result<(SendStream, RecvStream), OpenStreamError>

Initiate a new outgoing bidirectional stream immediately.

Returns OpenStreamError::StreamsExhausted instead of waiting if stream ID flow control does not currently allow opening another stream.

Source

pub async fn open_bi(&self) -> Result<(SendStream, RecvStream), ConnectionError>

Initiate a new outgoing bidirectional stream.

Source

pub async fn accept_uni(&self) -> Result<RecvStream, ConnectionError>

Accept the next incoming uni-directional stream

Source

pub async fn accept_bi( &self, ) -> Result<(SendStream, RecvStream), ConnectionError>

Accept the next incoming bidirectional stream

Important Note: The Connection that calls open_bi() must write to its SendStream before the other Connection is able to accept_bi(). Calling open_bi() then waiting on the RecvStream without writing anything to SendStream will never succeed.

Trait Implementations§

Source§

impl Clone for Connection

Source§

fn clone(&self) -> Connection

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<B> Connection<B> for Connection
where B: Buf,

Available on crate feature h3 only.
Source§

type RecvStream = RecvStream

The type produced by poll_accept_recv()
Source§

type OpenStreams = OpenStreams

A producer of outgoing Unidirectional and Bidirectional streams.
Source§

fn poll_accept_recv( &mut self, cx: &mut Context<'_>, ) -> Poll<Result<Self::RecvStream, ConnectionErrorIncoming>>

Accept an incoming unidirectional stream Read more
Source§

fn poll_accept_bidi( &mut self, cx: &mut Context<'_>, ) -> Poll<Result<Self::BidiStream, ConnectionErrorIncoming>>

Accept an incoming bidirectional stream Read more
Source§

fn opener(&self) -> Self::OpenStreams

Get an object to open outgoing streams.
Source§

impl<B: Buf> DatagramConnectionExt<B> for Connection

Available on crate feature h3 only.
Source§

type SendDatagramHandler = Connection

The type of the Datagram send Handler
Source§

type RecvDatagramHandler = Connection

The type of the Datagram receive Handler
Source§

fn send_datagram_handler(&self) -> Self::SendDatagramHandler

Get the send datagram handler
Source§

fn recv_datagram_handler(&self) -> Self::RecvDatagramHandler

Get the receive datagram handler
Source§

impl Debug for Connection

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Drop for Connection

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more
Source§

impl Eq for Connection

Source§

impl<B> OpenStreams<B> for Connection
where B: Buf,

Available on crate feature h3 only.
Source§

type BidiStream = BidiStream<B>

The type produced by poll_open_bidi()
Source§

type SendStream = SendStream<B>

The type produced by poll_open_send()
Source§

fn poll_open_bidi( &mut self, cx: &mut Context<'_>, ) -> Poll<Result<Self::BidiStream, StreamErrorIncoming>>

Poll the connection to create a new bidirectional stream.
Source§

fn poll_open_send( &mut self, cx: &mut Context<'_>, ) -> Poll<Result<Self::SendStream, StreamErrorIncoming>>

Poll the connection to create a new unidirectional stream.
Source§

fn close(&mut self, code: Code, reason: &[u8])

Close the connection immediately
Source§

impl PartialEq for Connection

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl RecvDatagram for Connection

Available on crate feature h3 only.
Source§

type Buffer = Bytes

The buffer type
Source§

fn poll_incoming_datagram( &mut self, cx: &mut Context<'_>, ) -> Poll<Result<Self::Buffer, ConnectionErrorIncoming>>

Poll the connection for incoming datagrams.
Source§

impl<B> SendDatagram<B> for Connection
where B: Buf,

Available on crate feature h3 only.
Source§

fn send_datagram<T: Into<EncodedDatagram<B>>>( &mut self, data: T, ) -> Result<(), SendDatagramErrorIncoming>

Send a datagram

Auto Trait Implementations§

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

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

Source§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more