From 2e11f14a6bfac32c25e305f65ac68a659cf01abb Mon Sep 17 00:00:00 2001 From: Christian Kamm Date: Mon, 18 Feb 2019 10:53:41 +0100 Subject: [PATCH] SocketApi: Fix crash with readyRead() after disconnected() #7044 With the recent bugfix to avoid sending messages on dead connections 0bfe7ac250c54f5415c0a794c7b271428e83c3cf the client now crashed if readyRead() was received after disconnected() for the socket as the listener for that connection was already removed. This code fixes it by still invoking the handler from readyRead() but passing a SocketListener that won't attempt to send messages. --- src/gui/socketapi.cpp | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/src/gui/socketapi.cpp b/src/gui/socketapi.cpp index 2a3947be1..427110b46 100644 --- a/src/gui/socketapi.cpp +++ b/src/gui/socketapi.cpp @@ -123,15 +123,20 @@ private: class SocketListener { public: - QIODevice *socket; + QPointer socket; - SocketListener(QIODevice *socket = nullptr) + explicit SocketListener(QIODevice *socket) : socket(socket) { } void sendMessage(const QString &message, bool doWait = false) const { + if (!socket) { + qCInfo(lcSocketApi) << "Not sending message to dead socket:" << message; + return; + } + qCInfo(lcSocketApi) << "Sending SocketAPI message -->" << message << "to" << socket; QString localMessage = message; if (!localMessage.endsWith(QLatin1Char('\n'))) { @@ -286,7 +291,19 @@ void SocketApi::slotReadSocket() { auto *socket = qobject_cast(sender()); ASSERT(socket); - SocketListener *listener = &*std::find_if(_listeners.begin(), _listeners.end(), ListenerHasSocketPred(socket)); + + // Find the SocketListener + // + // It's possible for the disconnected() signal to be triggered before + // the readyRead() signals are received - in that case there won't be a + // valid listener. We execute the handler anyway, but it will work with + // a SocketListener that doesn't send any messages. + static auto noListener = SocketListener(nullptr); + SocketListener *listener = &noListener; + auto listenerIt = std::find_if(_listeners.begin(), _listeners.end(), ListenerHasSocketPred(socket)); + if (listenerIt != _listeners.end()) { + listener = &*listenerIt; + } while (socket->canReadLine()) { // Make sure to normalize the input from the socket to