Skip to content

Commit

Permalink
Handle race condition when HttpListener is stopped or closed (#63394)
Browse files Browse the repository at this point in the history
* Throw a HttpListenerException if the session is null

* Add similar check to BeginGetContext

* Address PR feedback

* Remove trailing spaces
  • Loading branch information
kevingosse authored Jan 5, 2022
1 parent 311ecfe commit ec5471c
Showing 1 changed file with 19 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -508,7 +508,14 @@ public HttpListenerContext GetContext()
uint size = 4096;
ulong requestId = 0;
memoryBlob = new SyncRequestContext((int)size);
HttpListenerSession session = _currentSession!;
HttpListenerSession? session = _currentSession;

// Because there is no synchronization, the listener can be stopped or closed while the method is executing,
// resulting in a null session
if (session == null)
{
throw new HttpListenerException((int)Interop.HttpApi.ERROR_INVALID_PARAMETER);
}

while (true)
{
Expand Down Expand Up @@ -617,10 +624,20 @@ public IAsyncResult BeginGetContext(AsyncCallback? callback, object? state)
{
throw new InvalidOperationException(SR.Format(SR.net_listener_mustcall, "Start()"));
}

HttpListenerSession? session = _currentSession;

// Because there is no synchronization, the listener can be stopped or closed while the method is executing,
// resulting in a null session
if (session == null)
{
throw new HttpListenerException((int)Interop.HttpApi.ERROR_INVALID_PARAMETER);
}

// prepare the ListenerAsyncResult object (this will have it's own
// event that the user can wait on for IO completion - which means we
// need to signal it when IO completes)
asyncResult = new ListenerAsyncResult(_currentSession!, state, callback);
asyncResult = new ListenerAsyncResult(session, state, callback);
uint statusCode = asyncResult.QueueBeginGetContext();
if (statusCode != Interop.HttpApi.ERROR_SUCCESS &&
statusCode != Interop.HttpApi.ERROR_IO_PENDING)
Expand Down

0 comments on commit ec5471c

Please sign in to comment.