Skip to content

Closing a connection can dispose the ping/receive wait handles while another thread is using them #13

Open

Description

@andreion1ca

Summary

WebSocket.releaseCommonResources() calls Close() on _pongReceived and _receivingExited while other threads may still be inside Reset/Set/WaitOne on those same handles. That is a use-after-dispose of an OS wait handle, and it can take the whole process down.

Where the window opens

On the server side the sweep timer is what makes this reachable in normal operation:

WebSocketSessionManager.Sweep() -> InactiveIDs -> broadping() -> WebSocket.Ping()

Ping() does received.Reset() … received.WaitOne(_waitTime) on _pongReceived. If the connection is torn down at that moment, close() -> releaseResources() -> releaseCommonResources() closes that handle underneath the ping. Connections that are accepted and then immediately refused by the application are the worst case, because they are closed right after the receive loop has already started.

Evidence

Reported downstream as alttester/AltTester-Server#206: the server dies with

Fatal error. System.AccessViolationException: Attempted to read or write protected memory.
   at System.Collections.Generic.Dictionary`2[...]..ctor()
   at AltServerWebSocketSharp.Server.WebSocketSessionManager.broadping(Byte[])
   at AltServerWebSocketSharp.Server.WebSocketSessionManager+<get_InactiveIDs>d__21.MoveNext()
   at AltServerWebSocketSharp.Server.WebSocketSessionManager.Sweep()

Both occurrences in the attached log land on the first sweep tick, exactly 60s after startup, each shortly after a connection was accepted and then refused. Reproducibility was 3/10.

Related problems in the same area

  • Three readers test the field and then use it without snapshotting, so they can NRE when the field is nulled in between: client closeHandshake, processPongFrame (which carries a catch (NullReferenceException) that hides it), and server closeHandshake (reads _receivingExited twice — null check, then wait).
  • Sweep() clears _sweeping in its last statement rather than a finally. Anything thrown out of the loop leaves the flag stuck at true, and every later tick returns at the "already in progress" guard — the sweep is then silently dead for the rest of the process's life.

Affected

Both legs. The server hits it via the sweep; a client that calls Ping() while the connection is closing has the same shape.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions