runtime icon indicating copy to clipboard operation
runtime copied to clipboard

No non-blocking way to determine if you have data to read on SSLStream

Open ScotMac opened this issue 1 year ago • 33 comments

Description

SSLStream does not support a non-blocking way to determine if you currently have read data available. Here are the normal Network ways of determining this, and why they don't work for SSLStream:

  • Use read event (Poll): doesn't work for SSLStream, since it has the base TCP stream and the upper SSLStream, and a read event on the TCP stream does not mean there is necessarily data to read on the SSLStream (may just be meta data).
  • Call non-blocking Read or Peek on SSLStream: not supported on SSLStream.
  • Use very small timeout for timed SSLStream.Read: SSLStream will blow up (error out) the connection if it receives a timeout exception.

There is one way to get around this for Framework (doesn't work for Core). You can put a dummy stream on top of the low level TCP stream used with the SSLStream, and then set the TCP stream ReadTimeout to 1ms (smallest value). Then when the TCP stream throws a timeout exception, handle the exception and instead return 0 bytes, instead of the timeout exception that causes the SSLStream to blow up the connection.

This doesn't work for Core, because it interprets the stream 0 length receive as an EOF (like a zero length socket read). Framework instead just interprets it as zero bytes received and lets the SSLStream continue.

Reproduction Steps

Just create an SSLStream, which will have no non-blocking way to determine if you have read data.

Expected behavior

Have any non-blocking way of showing that the SSLStread has read data.

Actual behavior

No non-blocking way of determining if you have read data.

Regression?

No, i believe .NET has always has this problem.

Known Workarounds

One for framework (see the description).

Configuration

No response

Other information

No response

ScotMac avatar Aug 29 '25 22:08 ScotMac

I'm a bot. Here is a possible related and/or duplicate issue (I may be wrong):

  • https://github.com/dotnet/runtime/issues/22497

MihuBot avatar Aug 29 '25 22:08 MihuBot

Tagging subscribers to this area: @dotnet/ncl, @bartonjs, @vcsjones See info in area-owners.md if you want to be subscribed.

dotnet-policy-service avatar Aug 29 '25 22:08 dotnet-policy-service

What are you looking to do with the information?

A method that works with all streams is to have a pending read operation and check if it's already completed. With some streams (including SslStream), you can even do a zero-byte read.

MihaZupan avatar Aug 29 '25 22:08 MihaZupan

@MihaZupan, we are using blocking I/O for normal reads, not an async or threaded read. We are not looking to add a bunch of infrastructure around a threaded or async read.

Why would a zero-byte read be useful here? You mean to determine if the connection is still alive? We want to know if we have pending read data in a non-blocking manner, not whether we have "zero-bytes".

Basically, when a connection is checked into the connection pool, we need a non-blocking way to determine if their is pending read data.

ScotMac avatar Aug 30 '25 00:08 ScotMac

Why would a zero-byte read be useful here? You mean to determine if the connection is still alive?

No, the zero-byte read there means you don't need to keep another buffer around while waiting for data. The read itself will complete when a) there's any data available, or b) if you hit EOF. If the stream is just reading metadata internally, the zero-byte read won't complete. SocketsHttpHandler's HTTP/1.1 connection pool uses this to detect pending data on idle connections.

Unless you actually issue a full read on the stream, how would you know that there is any data available? E.g. if SslStream had a DataAvailable property, that would only tell you if there was leftover data available from the last time you've read anything in SslStream's buffers. If the underlying transport (e.g. network stream) had data available in kernel buffers, you wouldn't know unless the stream actually did a read.

MihaZupan avatar Aug 30 '25 00:08 MihaZupan

@MihaZupan, this is not a buffering issue. Nor are we looking for a zero-byte blocking read. We are instead looking for a non-blocking way to determine if we currently have pending data, like Poll.

ScotMac avatar Aug 30 '25 00:08 ScotMac

Note, it shouldn't be hard for the SSLStream combined with underlying (eg, TCP) stream to determine if there is pending data.

bool SSLStream.CheckForData()
{
  if ( <Can return data on SSLStream> ) return true;
  while ( stream.Poll(0, SelectMode.SelectRead) ) // non-blocking poll on internal stream
  {
     <Read once off the internal stream>
     <Process above read data>
     if ( <Can return data on SSLStream> ) return true;
  }
  return false;
}

And YES, we are fine w/ the check incurring a possible Read on the internal stream (see code), if necessary.

ScotMac avatar Aug 30 '25 00:08 ScotMac

Is the reason that this has not been done in the past because the internal stream isn't necessarily a tcp stream, and thus it might not be poll'able?

Probably 99% of the SSLStream's are associated with TCP streams. So, make the "CheckForData" only be supported for poll'able streams, like a TCP stream.

That way you fix the issue for 99% of the users of SSLStream.

ScotMac avatar Aug 30 '25 01:08 ScotMac

That way you fix the issue for 99% of the users of SSLStream.

99% of the users are likely using async code, because it is a TCP stream, thus network I/O, and thus inherently async.

That's if they're even doing it "manually", as opposed to any of the higher-level APIs that handle TCP as just part of whatever operation they're doing - in ASP.NET Core, or with things like HttpClient.PostAsJsonAsync(...). Because if you can abstract those details it makes your life way easier.

Clockwork-Muse avatar Aug 30 '25 05:08 Clockwork-Muse

This would be more of a feature request on the base Stream class. Since SslStream is just a wrapper around another stream (not necessarily NetworkStream) we cannot realiably implement this feature unless all streams expose the data available check.

I don't think we should implement new API on SslStream that would only work with one specific inner stream type. Maybe if there is sufficient demand, but you are the first to ask for such a feature in a long time.

The workaround suggested by mihazupan should work for you in the meantime. Keep pending zero-byte async read on the stream and check whether the task has completed (completed == data available, issue another zero-byte async read after you finish (synchronously) reading from the stream).

rzikm avatar Sep 01 '25 08:09 rzikm

I would tend to agree with @rzikm. This is somewhat more complicated as SslStream takes Stream as input and there is no Poll on that. And there may be data decrypted in inside buffers, there may be encrypted chunks that may or may not produce application data and there may be data in underlying stream or kernel buffer. To make this work reasonably well across different situations is going to be tricky.

I was proposing to have something that can combine networking and security functionality on https://github.com/dotnet/runtime/issues/63162 e.g. create something similar to Apple's Network Framework.

Aside from the specific ask, what problem are you trying to solve @ScotMac ? Understanding the use may help us to find some other way how to solve it.

wfurt avatar Sep 01 '25 20:09 wfurt

Hi Tomas (@wfurt), pretty much exactly what i specified in the description. ie, we are looking for a non-blocking way of checking if there is read data on the SSLStream (not the stream underlying the SSLStream, since as we all know, data on the underlying stream does not necessarily mean data on the top level SSLStream).

ie, something like a Poll(fReadEvent), but on the SSLStream.

ScotMac avatar Sep 02 '25 22:09 ScotMac

@ScotMac - That's not the underlying problem; you're describing the solution you've chosen to implement. The question is more along the lines of "why have you decided to attempt to manually check if there's data?". What larger picture (potentially completely non-technical) problem are you trying to solve that even necessitated this work?

  • Why aren't you just reading from the stream "normally" (async read to end) in the first place?
  • Why aren't you reading into a domain object, if you're dealing with discrete messages? (eg, GetAsJsonAsync(...))
  • If you're doing something like streaming, should you be using pipelines, which would handle at least some of this management for you. Which, if you really need to break things apart, could be used on each stream in the chain.

Clockwork-Muse avatar Sep 03 '25 03:09 Clockwork-Muse

Yes, this is NOT part of the normal reading on the stream, but is instead a CHECK if we got a notification from the server side of the connection while the connection is idle. These notifications are like meta data on TCP. This is typically done in the connection pool, where we are checking for this meta data on possibly hundreds of connections, hence the need to be a non-blocking way to check and not some type of thread per connection solution.

ScotMac avatar Sep 03 '25 23:09 ScotMac

It is key to note, that this type of CHECKING ON THE STREAM in a NON-BLOCKING manner is fairly standard in networking. Hence the need for Poll/Select and nonblocking read or peek that are ALL supported for normal TCP sockets, but i don't see anything of the sort for SSLStream.

ScotMac avatar Sep 03 '25 23:09 ScotMac

hence the need to be a non-blocking way to check and not some type of thread per connection solution.

So, async code in C# is non-blocking, and doesn't consume a thread per connection.

That said...

Yes, this is NOT part of the normal reading on the stream, but is instead a CHECK if we got a notification from the server side of the connection while the connection is idle.

.... And why is this important? What are you planning on doing with this information? This is still somewhat you describing your solution.

If your answer is "read data from a filled buffer", that's essentially what most of the streams will handle for you. Note that there are a lot of instrumented metrics for the built-in networking streams and other classes, which may be sufficient for you.

If you're writing a specialized server, the modern recommendation would probably be to use pipelines, as I mentioned earlier, just async reading/writing as required.

Clockwork-Muse avatar Sep 04 '25 04:09 Clockwork-Muse

We are not looking to add the non-trivial of amount of complexity required to switch from blocking IO to an async solution.

And why is this important? What are you planning on doing with this information? This is still somewhat you describing your solution

Not really, I described WHY we wanted to check if the connection/session/stream, in order to recieve non-payload meta data. Because this is not payload data, and because we are doing this check in the connection pool, where we can have hundreds of connections, we need to be able to do this check for non-payload meta data in a non-blocking manner.

But to further elaborate, the non-payload meta can be various things:

  • notification to shutdown the pooled session
  • notification that the server has a planned maintenance
  • notification that the server has migrated ...

ScotMac avatar Sep 05 '25 21:09 ScotMac

And, again, it is key to note, that this type of CHECKING ON THE STREAM in a NON-BLOCKING manner is fairly standard in networking. Hence the need for Poll/Select and nonblocking read or peek that are ALL supported for normal TCP sockets, but i don't see anything of the sort for SSLStream.

My point being, I am asking for something that is standard for a network connections, not something totally out of the ordinary.

ScotMac avatar Sep 05 '25 21:09 ScotMac

This has nothing to do with "instrumented metrics". This is a non-blocking check if the local endpoint of SSLStream currently has "read data" to be consumed.

As i mentioned, one solution is a SSLStream that is tied to a TCP Socket (instead of a generic stream), and thus easily able to check for data on the underlying socket, and process it, until Poll(Read), for exmple, says there is no more data, using a non-blocking Poll(). At which point, the SSLStream would return to the caller whether the handling of the data from the underlying TCP Socket resulted in payload data for the caller.

Their is various functionality not able to be supported, due to the fact that the underlying transport is a generic stream, whereas the huge majority of the users of SSL/TLS will be using it on top of TCP socket.

ScotMac avatar Sep 05 '25 21:09 ScotMac

As i said previously: We are not looking to add the non-trivial of amount of complexity required to switch from blocking IO to an async solution.

But to further expand on that, it makes no sense whatsoever for a connection pool to have hundreds of async operations pending on idle pool connections. We strongly believe that a non-blocking model is inherently a much better solution, where ONE THREAD can simple traverse the idle connections checking for any read data in a non-blocking manner. This one thread would, for the most part, not even be operating for possibly DAYS/WEEKS/MONTHS at a time. While the threads associated with the async operations would be sitting there continuously consuming memory/resources.

ScotMac avatar Sep 05 '25 21:09 ScotMac