Repository navigation
Closed
Description
Background
Currently a single rustls connection owns several buffers:
- incoming TLS data, that has been read with
read_tls()but not yet processed byprocess_new_packets(). This is embedded intomsgs::MessageDeframerand is a contiguous buffer large enough to store the largest single TLS message that can appear on the wire (~18KB). At the moment we are following a strategy of keeping this buffer small, at the potential expense of extra allocator traffic and system calls. This buffer needs to be contiguous because we borrow it during message parsing. - outgoing TLS data, that has been produced by
process_new_packets(), but not yet written bywrite_tls(). This isCommonState::sendable_tls. - incoming application data, that has been decrypted by
process_new_packets(), but not yet read viareader(). This isCommonState::received_plaintext. - outgoing application data, that has been input with
writer()but is not yet sendable because the connection is not yet set up. This isCommonState::sendable_plaintext. It is automatically sent at completion of the TLS handshake, and not used thereafter -- use ofwriter()once the connection is set up encrypts the data immediately and puts the result inCommonState::sendable_tls.
This arrangement allows for the rustls IO API to be (relatively!) simple, and separates IO and processing concerns. But it is inefficient because:
- some of these buffers are short-lived: outgoing TLS is destined for the TCP send buffer, incoming application data is destined for the application.
- if the TCP send buffer is full, it may be necessary to keep outgoing TLS longer term. But buffering it in that case risks doing an end-run around TCP flow control. There is an attempt in rustls to quench the read-side if there is pending outgoing data (see
wants_read()). - for an application that deals with many connections simultaneously, these buffers could be shared (when not in use!) between many connections.
- if the TCP send buffer is full, it may be necessary to keep outgoing TLS longer term. But buffering it in that case risks doing an end-run around TCP flow control. There is an attempt in rustls to quench the read-side if there is pending outgoing data (see
- outgoing application data buffering is just a convenience for applications, and one they can arrange themselves if we choose to drop it as a feature in rustls.
Things to note
- The incoming TLS data buffer is longer-term, because TLS is a packetised protocol and we need a whole packet before we can process it. These packets are up to ~18KB, and their receipt can be split across any TCP packet boundaries. Any application that hopes to amortise buffer usage over many simultaneous connections needs to be sized such that all the connections can concurrently be in the state of receiving the largest possible message.
- Sending or receiving a TLS message can mean sending (a limited number of) additional control messages. Messages that are sent must retain their order (ie, it would not work to have a data path that deals only with application data and another that only deals with control messages, because the peer must see receive them in the original order).
- Outputting a TLS message into the "outgoing TLS data" buffer is not restartable, so an application-provided buffer for this must be big enough to contain it. We could have this be an error, of course, but that error would be permanent and irrecoverable for a given connection. rustls cannot reasonably become transactionally atomic over the ability to send a sequence of messages. However, it would be an option for rustls to become fully async, meaning a connection could be restarted once the write can complete.
- There are actually two "application data" paths in TLS1.3 which must be kept separated: "early data"/"0-RTT data" has different properties to normal, post-handshake data.
- We have two performance-critical data paths:
- sending application data, encrypting from a borrowed slice and putting the result into the "outgoing TLS data" buffer. This currently involves one (encrypting) copy plus one message-size allocation. Ideally we could remove that allocation.
- receiving application data, copying in via
std::io::Read, then decrypting into an allocated buffer. This currently involves two copies (one decryption) and one message-size allocation. Ideally we could remove the allocation and one copy.
Desirable outcomes
- applications using rustls can control the lifetime of the short-lived buffers listed above, depending on their IO needs.
- applications that want to buffer their outgoing/incoming data can do so themselves.
- rustls no longer needs to impl
std::io::Read/std::io::Writetraits, because it no longer owns the buffers that these used. - rustls connections have a lower and more predictable memory footprint when idle -- and less allocator traffic when in use -- allowing greater density and improving our C10k number.
- there is flexibility in the types used, so applications are not forced to (eg) repeatedly clear large regions of memory on every call into rustls.
Sketch
(Illustrative. Not intended to compile!)
enum Sink {
// slice, plus size used
Slice(&mut [u8], usize),
// appended to
Vec(&mut Vec<u8>>),
// slice, but avoid premature initialisation
BorrowedBuf(&mut std::io::BorrowedBuf),
}
enum Source {
Slice(&[u8]),
// unnecessary?
}
enum ReadablePartialUsed {
/// this many bytes are expected in addition to the data already provided.
MoreDataNeeded(usize),
/// this many bytes were consumed from the front of the buffer.
Consumed(usize),
}
struct BuffersUsed {
/// how many bytes read from the front of `send_appdata`.
send_appdata: usize,
/// how many bytes written to the front of `recv_appdata`.
recv_appdata: usize,
/// how many bytes written to the front of `send_tls`.
send_tls: usize,
/// how many bytes consumed from the front of `recv_tls`, or that additional data is required.
recv_tls: ReadablePartialUsed,
}
/// Reads TLS messages from `recv_tls`, processes them, and writes response
/// messages into `send_tls` and received application data into `recv_appdata`.
///
/// If the handshake has completed, reads application data to send from
/// `send_appdata`, encrypts it and writes the result into `send_tls`.
///
/// After this, the application should:
/// - Send any data added to `send_tls` on the underlying IO medium
/// - Process any data added to `recv_appdata`
/// - Advance over data read in `recv_tls` and `recv_appdata`. Note that
/// unprocessed data should be provided again at the next call.
fn process(
&mut self,
send_appdata: &mut Source,
recv_appdata: &mut Sink,
send_tls: &mut Sink,
recv_tls: &mut Source
) -> Result<BuffersUsed, Error>;
// nb, we need a second, separate function which deals with early data during handshaking.See also
https://docs.rs/pipebuf/latest/pipebuf/ - could be a component in improving this.
Reacted by Gustav Trede and Joshua Sleeper
Reacted by Joshua Sleeper
Reacted by Daniel McCarney
Metadata
Metadata
Assignees
Labels
No labels
Activity
djc commentedon Jul 18, 2023
To me the high-level goal here is to provide an API that doesn't have data-path buffering in the library, partly as a waypoint towards no_std operation. This would imply that all of these buffers are caller-allocated.
I think passed in received TLS would need to be a mutable slice so we can decrypt in place. Then we could also yield the received application data as a Vec of slices pointing into the received TLS data.
Initially it might be easiest to have the library write outgoing TLS into a Vec only (as opposed to a slice). This way we don't have to deal with yielding an error on an insufficiently sized buffer for the outgoing message(s), in which case we would have to be careful about not leaving the connection state in an inconsistent state (presuming we would not want this error to be fatal to the connection).
Implementation wise I think this means moving the ChunkVecBuffer fields from ConnectionState into ConnectionCommon, maybe we want to bundle them with the MessageDeframer in a new type, a mutable reference to which could be added to the Context types. Maybe the API could be shaped as a top-level
unbufferedmodule that exposes alternative ClientConnection and ServerConnection types?