From 16e2d21aa39c0f3b118a390b6762ea49ea07d4ed Mon Sep 17 00:00:00 2001 From: Emiel Bruijntjes Date: Wed, 26 Apr 2017 15:33:17 +0200 Subject: [PATCH] fixed issue that a tcp connection could crash if the user space code deconstructed a handler in a onClosed() handler --- src/tcpconnected.h | 27 +++++++++++++++++++++++++++ src/tcpstate.h | 2 +- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/tcpconnected.h b/src/tcpconnected.h index df5e5b9..85bc377 100644 --- a/src/tcpconnected.h +++ b/src/tcpconnected.h @@ -133,6 +133,9 @@ public: */ virtual ~TcpConnected() noexcept { + // skip if handler is already forgotten + if (_handler == nullptr) return; + // we no longer have to monitor the socket _handler->monitor(_connection, _socket, 0); @@ -263,6 +266,30 @@ public: // pass to base return TcpState::reportNegotiate(heartbeat); } + + /** + * Report to the handler that the connection was nicely closed + */ + virtual void reportClosed() override + { + // we no longer have to monitor the socket + _handler->monitor(_connection, _socket, 0); + + // close the socket + close(_socket); + + // socket is closed now + _socket = -1; + + // copy the handler (if might destruct this object) + auto *handler = _handler; + + // reset member before the handler can make a mess of it + _handler = nullptr; + + // notify to handler + handler->onClosed(_connection); + } }; /** diff --git a/src/tcpstate.h b/src/tcpstate.h index 11aa75d..bdedcf2 100644 --- a/src/tcpstate.h +++ b/src/tcpstate.h @@ -127,7 +127,7 @@ public: /** * Report to the handler that the connection was nicely closed */ - void reportClosed() + virtual void reportClosed() { // pass to handler _handler->onClosed(_connection);