SocketApi: Fix crash with readyRead() after disconnected() #7044
authorChristian Kamm <mail@ckamm.de>
Mon, 18 Feb 2019 09:53:41 +0000 (10:53 +0100)
committerKevin Ottens <kevin.ottens@nextcloud.com>
Tue, 15 Dec 2020 09:58:42 +0000 (10:58 +0100)
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

index 2a3947be1a52fd471b9883ee04271a264a7de1ae..427110b46fa76d7b3e4a9b3d25fb992459430621 100644 (file)
@@ -123,15 +123,20 @@ private:
 class SocketListener
 {
 public:
-    QIODevice *socket;
+    QPointer<QIODevice> 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<QIODevice *>(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