Skip to main content

Client

Struct Client 

Source
pub struct Client<B: Buffer, C: CryptoProvider> { /* private fields */ }
Expand description

A sans-IO TLS 1.3 client state machine.

The client progresses through the handshake phases:

PhaseWhat happens
ClientHelloWaiting for start_handshake to write the ClientHello
ServerHello / ServerFlightProcessing the server’s response
ClientFinishedSending the client Finished, then app keys are installed
ApplicationDataConnection is established; use encrypt / decrypt
ClosedConnection has been terminated

The caller is responsible for all network I/O. Use receive_buffer and commit_received to feed data in, and outgoing_data to extract data to send.

§Panics

Methods that dereference suite (e.g. encrypt, decrypt) will panic if called before the handshake completes.

Implementations§

Source§

impl<B: Buffer, C: CryptoProvider> Client<B, C>

Source

pub fn new(config: ClientConfig<C>, receive_buffer: B, send_buffer: B) -> Self

Create a new TLS 1.3 client.

receive_buffer and send_buffer are scratch buffers the client uses to hold incoming and outgoing TLS records. Each must be at least [MAX_RECORD_SIZE] bytes long.

Owned types such as Vec<u8> may be passed directly. Borrowed slices (&mut [u8]) are also accepted — they must outlive the Client.

Source

pub fn receive_buffer(&mut self) -> &mut [u8]

Return the tail of the receive buffer where the caller should write incoming network data.

Source

pub fn commit_received(&mut self, n: usize)

Inform the client that n bytes have been written into the buffer returned by receive_buffer.

Source

pub fn accept_certificate(&mut self, result: Result<(), Error>)

Provide the result of certificate validation to the handshake.

Must be called after receiving VerifyServerCertificate. The handshake will then proceed to verify the server’s CertificateVerify signature and Finished message.

If result is Err, the handshake is aborted with that error when continue_handshake is next called.

This is a no-op if the handshake is not currently waiting for certificate verification.

Source

pub fn server_certificate( &self, ) -> Option<(ReceivedCertificate<'_>, Option<&str>)>

Return the server’s certificate and server name for validation.

Should be called after receiving VerifyServerCertificate. Returns None if the handshake is not in the certificate verification phase.

Source

pub fn start_handshake( &mut self, server_name: Option<&str>, alpn_protocols: &[&[u8]], ) -> Result<ClientHandshakeEvent<'_>, Error>

Begin the TLS 1.3 handshake by writing a ClientHello into the send buffer.

server_name is the SNI host name (optional). alpn_protocols lists application-layer protocol identifiers to negotiate (e.g. b"h2", b"http/1.1").

On success returns Send — the caller should transmit outgoing_data over the network and then call continue_handshake.

§Errors

Returns Error::CryptoError if key-pair generation fails, or Error::EncodeError if the ClientHello cannot be encoded.

Source

pub fn continue_handshake(&mut self) -> Result<ClientHandshakeEvent<'_>, Error>

Advance the handshake state machine.

Must be called after each Send or Receive event produced by the previous call. The caller should:

  1. Inspect the returned event.
  2. If Send: transmit outgoing_data over the network.
  3. If Receive: read data from the network into receive_buffer, then call commit_received.
  4. Call continue_handshake again.

When Done is returned the connection is established and application data may be exchanged with encrypt / decrypt.

§Errors

Returns an error if the server’s messages are malformed, the certificate chain is invalid, the signature verification fails, or the transcript hash does not match the expected Finished verify_data.

Source

pub fn outgoing_data(&self) -> &[u8]

Return the data that should be sent over the network.

Used during both the handshake and application-data phases. After encrypt or after Send from the handshake, this returns the contents of the send buffer.

Source

pub fn commit_sent(&mut self, n: usize)

Advance the sent position within the send buffer.

Call this after transmitting n bytes from the slice returned by outgoing_data. The send buffer is reset automatically once all bytes have been sent.

§Panics

Panics if n exceeds the remaining unsent length.

Source

pub fn encrypt(&mut self, data: &[u8]) -> Result<usize, Error>

Encrypt application data and write the resulting TLS record into the send buffer.

Returns the number of plaintext bytes written (always equal to data.len()). The encrypted record is available via outgoing_data.

§Panics

Panics if called before the handshake has completed (i.e. before Done is returned).

§Errors

Returns Error::InsufficientBuffer if the send buffer is too small for the encrypted record.

Source

pub fn decrypt(&mut self) -> Result<ClientApplicationDataEvent, Error>

Decrypt one or more TLS records from the receive buffer.

Processes records in a loop until it runs out of complete records, encounters application data, receives a NewSessionTicket, or receives a close_notify alert.

§Panics

Panics if called before the handshake has completed.

§Errors

Returns Error::ConnectionClosed when the peer sends a close_notify alert. Returns Error::AeadError if record decryption fails.

Source

pub fn received_app_data(&self) -> &[u8]

Get the last decrypted application data (after decrypt returned AppData).

Returns only the unconsumed portion of the data. Advance the consumed position with commit_app_data so that subsequent calls return the remainder.

Source

pub fn commit_app_data(&mut self, n: usize)

Advance the consumed position within the last decrypted record.

Call this after reading n bytes from the slice returned by received_app_data. The next call to decrypt will not process new records until all data from the current record has been consumed (i.e. the total consumed equals the record length).

§Panics

Panics if n exceeds the remaining unconsumed length.

Source

pub fn outgoing_key_update_data(&self) -> &[u8]

Return the unsent portion of the pending KeyUpdate response, if any.

The caller should transmit this data over the network and then call commit_key_update_data with the number of bytes successfully sent.

Source

pub fn commit_key_update_data(&mut self, n: usize)

Advance the sent position within the pending KeyUpdate response.

Call this after transmitting n bytes from the slice returned by outgoing_key_update_data. The response is cleared automatically once all bytes have been sent.

§Panics

Panics if n exceeds the remaining unsent length.

Source

pub fn received_ticket_data(&self) -> &[u8]

Get the raw ticket bytes from the last NewSessionTicket (after decrypt returned Ticket).

Source

pub fn close(&mut self) -> Result<&[u8], Error>

Send a close_notify alert to the peer.

The encrypted alert is returned.

Source

pub fn is_established(&self) -> bool

Auto Trait Implementations§

§

impl<B, C> Freeze for Client<B, C>

§

impl<B, C> RefUnwindSafe for Client<B, C>

§

impl<B, C> Send for Client<B, C>
where B: Send, <C as CryptoProvider>::Hasher: Send, <C as CryptoProvider>::AeadKey: Send,

§

impl<B, C> Sync for Client<B, C>
where B: Sync, <C as CryptoProvider>::Hasher: Sync, <C as CryptoProvider>::AeadKey: Sync,

§

impl<B, C> Unpin for Client<B, C>
where B: Unpin, C: Unpin,

§

impl<B, C> UnsafeUnpin for Client<B, C>

§

impl<B, C> UnwindSafe for Client<B, C>

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, 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.