Skip to content

Read impl on Session #563

Closed
Closed

Description

@jsha

Related to #562

For Session, the Read trait is a somewhat awkward fit. https://doc.rust-lang.org/std/io/trait.Read.html#tymethod.read

If n is 0, then it can indicate one of two scenarios:
This reader has reached its "end of file" and will likely no longer be able to produce bytes. Note that this does not mean that the reader will always no longer be able to produce bytes.

Currently, Session::read() takes advantage of the wiggle room in "likely." Returning Ok(0) from Session::read() means "no more plaintext bytes available in buffer, but that can change in the future." Returning Err(io::ErrorKind::ConnectionAborted) from Session::read() means "successful EOF for the overall connection."

That's a bit confusing to deal with because it inverts the usual way Read impls work:

This function does not provide any guarantees about whether it blocks waiting for data, but if an object needs to block for a read and cannot, it will typically signal this via an Err return value.

And also it means you can't, for instance, stack a Session with something else that requires a Read, like a gzip decoder.

We could switch these: Session::read would return an error (e.g. io::ErrorKind::WouldBlock) when there are temporarily no bytes available, and return Ok(0) upon close_notify.

Another approach would be: remove the Read impl on Session. Instead, process_new_packets would return Result<PartialReader, TLSError>, where PartialReader would impl Read, and would read however many bytes are available in the buffer and then return Ok(0).

Activity

  1. djc commented on Mar 15, 2021

    @djc
    Member

    It would be nice if we can align with the std semantics, but I'm a bit worried about the compatibility situation -- seems likely we would break a bunch of downstream users, and there's not really a way to make this obvious at compile time? I guess we could add a new method with the changed semantics, and deprecate the old one.

  2. jsha commented on Mar 15, 2021

    @jsha
    ContributorAuthor

    Agreed that changing the semantics without notice at compile time would be an issue. I think probably the best would be as you say, to deprecate the read method (and in general the impl Read for Session). The replacement could either be a differently-named method with new semantics, or a PartialReader returned from process_new_packets.

    In the scenario above, Stream and StreamOwned would still impl Read. Worth noting, however, that they have similarly awkward semantics: they're return an error if they receive a close_notify, when we'd really like that to be treated as an EOF with no errors.And if they receive a TCP close without a close_notify first, that should be treated as an error.

  3. briansmith commented on Mar 31, 2021

    @briansmith
    Contributor

    It seems to me that the caller of process_new_packets() needs to be able to recognize many different states:

    1. No error and some data is available. More data may be available later. Data can be sent.
    2. No error and no data is available. Data might be available later. Data can be sent.
    3. Close notify was received. No more data will become available. We need to soon stop sending data.
    4. The read side of the connection was closed without a "close notify". No more data is available and "close notify" will never be received. Some applications (e.g. a web browser) might treat this the same as (3). Other applications that are more strict may treat this as an error since this isn't a "secure close."
    5. An error occurred and nothing more may be done.

    I saw the PR that proposes to add a is_close_notify. However, That seems to imply that the lack of a close_notify is no big deal; otherwise, it wouldn't be an optional extra check. However, the "correct" way to do TLS, when feasible, is to insist on receiving a close_notify and consider it an error to not receive one. And so it seems to me like the API design should be biased towards forcing the user to recognize the difference between receiving and not receiving one, and this should be reflected in the type of process_new_packets.

  4. jsha commented on Apr 1, 2021

    @jsha
    ContributorAuthor

    Agreed that an improved API would be ideal here. #605 is a sort of stopgap / fallback approach, if we don't wind up rewriting the process_new_packets interface, or if it takes a while.

    1. The read side of the connection was closed without a "close notify".

    Note that because it does no I/O, process_new_packets will never learn that the read side of the connection was closed, unless we add a new method "read_side_was_closed()".

    There's a related set of problems to solve for StreamOwned, which does do I/O. I think for StreamOwned it makes sense to:

    • return an error by default for "read side closed without close_notify", and
    • make that error typed so the user can ignore it if they choose to be lax, and
    • return a clean close on receiving close_notify.
  5. jsha commented on Apr 2, 2021

    @jsha
    ContributorAuthor

    It would also be useful to capture these semantics about extracting plaintext:

    • It never returns an io::Error
    • It will always extract as many bytes as are available, up to the limit of the destination slice.

    And as an extra little bonus, maybe we could save some copies and some allocations? Here's a concrete proposal for Session (ignoring StreamOwned for now):

    /// If there are any bytes in the session's plaintext buffer, writes them to dst.
    /// If dst is not yet full, processes any new packets read by a previous call
    /// to read_tls and write the plaintext to dst, storing any excess in the session's
    /// plaintext buffer. Errors from this function relate to TLS protocol errors, and
    /// are fatal to the session. Future calls after an error will do no new work
    /// and will return the same error.
    ///
    /// Ok(n, Eof) means n plaintext bytes were written to dst and a close_notify
    ///   alert was received.
    ///
    /// Ok(n, Open) means that n plaintext bytes were written to dst. If
    ///   n < dst.len(), it also means there are no more plaintext bytes available until
    ///   additional TLS bytes are read with read_tls()).
    fn process_new_packets(dst: &mut [u8]) -> Result<(usize, Status), TLSError>
    
    enum Status {
      Open,
      Eof
    }
    
  6. briansmith commented on Apr 9, 2021

    @briansmith
    Contributor

    Future calls after an error will do no new work
    /// and will return the same error.

    What will happen if the function is called again after Eof has been returned once?

  7. jsha commented on Apr 9, 2021

    @jsha
    ContributorAuthor

    Good point, the proposed documentation should also say:

    /// Calls after Eof is returned will do no work and return Ok((0, Eof))

  8. briansmith commented on Apr 9, 2021

    @briansmith
    Contributor
    fn process_new_packets(dst: &mut [u8]) -> Result<(usize, Status), TLSError>
    

    Might I suggest:

    fn process_new_packets<'a>(dst: &'a mut [MaybeUninit<u8>]) -> Result<(&'a mut [u8], &'a mut [MaybeUninit<u8>], Status), TLSError>
    

    The first slice in the tuple would be the plaintext of the new data received, if any, a subslice at the beginning of dst. Change all the documentation to talk about the length of this slice instead of len. The second slice in the tuple would be the rest of dst. Using &mut [MaybeUninit<T>] is the right way to indicate an output buffer that doesn't (necessarily) have anything valid to read.

  9. briansmith commented on Apr 9, 2021

    @briansmith
    Contributor

    Also, I think we should use a named struct with named fields instead of a tuple.

  10. jsha commented on Apr 9, 2021

    @jsha
    ContributorAuthor

    I definitely like the idea of using MaybeUninit here. It solves a problem for crustls: right now the crustls docs have to specify that calling code must initialize even output-only memory, upon pain of UB. It would be better to remove that requirement, because it would be easy to disregard or forget.

    I also like the idea of returning a &'a mut [u8] slice that indicates "this memory has been written to and is now usable." What do you anticipate people using the leftover &'a mut [MaybeUninit<u8>] for?

    Agreed that a named struct is appropriate, particularly if we have three fields in the Ok variant.

  11. briansmith commented on Apr 9, 2021

    @briansmith
    Contributor

    What do you anticipate people using the leftover &'a mut [MaybeUninit<u8>] for?

    I don't know, but it seems natural to include it since this function is basically a split() of dst.

  12. ctz commented on Apr 10, 2021

    @ctz
    Member

    My plan for this is:

    • returning a small struct from process_new_packets that contains the peer half-closure state, and amount of data available to read and write. We can add to this in the future data that is useful to callers prior to doing any IO (but not, I suggest, behaviours).
    • remove the existing std::io::Read implementation from Connection
    • add a trivial reader() method instead, which returns a object that implements std::io::Read, but also is a place we could put other read-related methods (like the MaybeUninit interface suggested above, and a no-std interface in the future). Likewise writer() for consistency.
    • the semantics of std::io::Read::read are changed so that:
      • Ok(0) means clean EOF, only after receipt of a close_notify
      • "no data" is signalled with Err(io::ErrorKind::WouldBlock.into()), like a non-blocking socket. But this situation is entirely avoidable given the data available from process_new_packets

    The reader() change is primarily to avoid quietly changing read() semantics, though it'll be very easy for a downstream caller to just change rustls_session.read(...) to rustls_session.reader().read(...) and end up with something that doesn't work, but eh.

    Things I thought about but rejected:

    • totally removing std::io traits implementation -- this feels like a step too far, even if it is ossified and too loosely defined.
    • gluing the ability to read to the return value of process_new_packets: at least in the example programs process_new_packets happens distant to read() -- we say in the docs that process_new_packets should happen after read_tls makes progress, but that's not always a convenient time to read plaintext. It's of course always possible to call process_new_packets() again, or save the returned object, but these options seem messy or fraught with lifetime-hell respectively.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions