Attempting to close SSL sockets through ASIOSession::end() is not multi-thread safe. Here is a possible scenario where we can have a read after write data-race:
- Thread 1 is running SSL handshake, and attempts to emplace the established SSL socket into _sslSocket (see here). This is done while holding the session lock.
- Thread 2 calls into ASIOSession::end(), which will attempt to get the underlying socket object by inquiring _sslSocket multiple times (here). All these accesses are done without holding the lock.
We can serialize accesses to _sslSocket by threads calling into ASIOSession::end() and ASIOSession::handshakeSSLForEgressWithLock() using a mutex. This should ensure the socket is not altered while running ASIOSession::end().