Skip to content

Commit

Permalink
Sockets: Properly handle POLLHUP events
Browse files Browse the repository at this point in the history
Stops client socket leaking.
  • Loading branch information
stenzek committed Jul 21, 2024
1 parent 6b78364 commit 7880087
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 4 deletions.
36 changes: 32 additions & 4 deletions src/util/sockets.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -486,10 +486,17 @@ bool SocketMultiplexer::PollEventsWithTimeout(u32 milliseconds)
PendingSocketPair& psp = triggered_sockets[i];

// fire events
if (psp.second & (POLLIN | POLLHUP | POLLERR))
psp.first->OnReadEvent();
if (psp.second & POLLOUT)
psp.first->OnWriteEvent();
if (psp.second & (POLLHUP | POLLERR))
{
psp.first->OnHangupEvent();
}
else
{
if (psp.second & POLLIN)
psp.first->OnReadEvent();
if (psp.second & POLLOUT)
psp.first->OnWriteEvent();
}

psp.first.~shared_ptr();
}
Expand Down Expand Up @@ -558,6 +565,12 @@ void ListenSocket::OnReadEvent()

void ListenSocket::OnWriteEvent()
{
ERROR_LOG("Unexpected OnWriteEvent() in ListenSocket {}", m_local_address.ToString());
}

void ListenSocket::OnHangupEvent()
{
ERROR_LOG("Unexpected OnHangupEvent() in ListenSocket {}", m_local_address.ToString());
}

StreamSocket::StreamSocket(SocketMultiplexer& multiplexer, SocketDescriptor descriptor)
Expand Down Expand Up @@ -770,6 +783,21 @@ void StreamSocket::OnWriteEvent()
// shouldn't be called
}

void StreamSocket::OnHangupEvent()
{
std::unique_lock lock(m_lock);
if (!m_connected)
return;

m_multiplexer.SetNotificationMask(this, m_descriptor, 0);
m_multiplexer.RemoveClientSocket(this);
closesocket(m_descriptor);
m_descriptor = INVALID_SOCKET;
m_connected = false;

OnDisconnected(Error::CreateString("Connection closed by peer."));
}

BufferedStreamSocket::BufferedStreamSocket(SocketMultiplexer& multiplexer, SocketDescriptor descriptor,
size_t receive_buffer_size /* = 16384 */,
size_t send_buffer_size /* = 16384 */)
Expand Down
3 changes: 3 additions & 0 deletions src/util/sockets.h
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ class BaseSocket : public std::enable_shared_from_this<BaseSocket>
protected:
virtual void OnReadEvent() = 0;
virtual void OnWriteEvent() = 0;
virtual void OnHangupEvent() = 0;

SocketMultiplexer& m_multiplexer;
SocketDescriptor m_descriptor;
Expand Down Expand Up @@ -194,6 +195,7 @@ class ListenSocket final : public BaseSocket
protected:
void OnReadEvent() override final;
void OnWriteEvent() override final;
void OnHangupEvent() override final;

private:
SocketMultiplexer::CreateStreamSocketCallback m_accept_callback;
Expand Down Expand Up @@ -231,6 +233,7 @@ class StreamSocket : public BaseSocket

virtual void OnReadEvent() override;
virtual void OnWriteEvent() override;
virtual void OnHangupEvent() override;

void CloseWithError();

Expand Down

0 comments on commit 7880087

Please sign in to comment.