File: networkreplymodel.cpp

package info (click to toggle)
gammaray 3.3.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 21,612 kB
  • sloc: cpp: 94,643; ansic: 2,227; sh: 336; python: 164; yacc: 90; lex: 82; xml: 61; makefile: 26
file content (440 lines) | stat: -rw-r--r-- 16,727 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
/*
  networkreplymodel.cpp

  This file is part of GammaRay, the Qt application inspection and manipulation tool.

  SPDX-FileCopyrightText: 2019 Klarälvdalens Datakonsult AB, a KDAB Group company <info@kdab.com>
  Author: Volker Krause <volker.krause@kdab.com>

  SPDX-License-Identifier: GPL-2.0-or-later

  Contact KDAB at <info@kdab.com> for commercial licensing options.
*/

#include "networkreplymodel.h"

#include <core/util.h>
#include <common/objectid.h>

#include <QNetworkAccessManager>
#include <QNetworkReply>

// TODO: Should the network module import Qt Private headers? Or should this be somewhere else?
#include <private/qobject_p.h>
#include <private/qobject_p_p.h>

#include <iostream>
#include <limits>

using namespace GammaRay;

static const auto TopIndex = std::numeric_limits<quintptr>::max();

Q_DECLARE_METATYPE(GammaRay::NetworkReplyModel::ReplyNode)

namespace {
bool prioritizeLatestConnection(QObject *sender, const char *normalizedSignalName, QObject *receiver)
{
    const auto senderPrivate = QObjectPrivate::get(sender);
    const auto sigIndex = senderPrivate->signalIndex(normalizedSignalName);
    if (sigIndex < 0) {
        return false;
    }

    const auto connectionData = senderPrivate->connections.loadRelaxed();
    if (!connectionData) {
        return false;
    }

    auto signalsVector = connectionData->signalVector.loadRelaxed();
    if (!signalsVector) {
        return false;
    }

    QObjectPrivate::Connection *ourConn = nullptr;
    for (int i = 0; i < signalsVector->count(); ++i) {
        QObjectPrivate::Connection *conn = signalsVector->at(i).first;
        while (conn) {
            if (conn->signal_index == sigIndex && conn->receiver == receiver) {
                ourConn = conn;
                // We continue because we want to locate the latest connection,
                // i.e. the connection we just made
            }

            conn = conn->nextConnectionList;
        }

        // TODO: The whole thing needs to be atomic
        if (ourConn) {
            if (ourConn == signalsVector->at(i).first) {
                qDebug() << "We are already the first, nothing to do";
                return true;
            }

            qDebug() << "Swapping" << ourConn->receiver << "with"
                     << static_cast<QObjectPrivate::Connection *>(signalsVector->at(i).first)->receiver;
            ourConn->prevConnectionList->nextConnectionList.storeRelaxed(ourConn->nextConnectionList);
            ourConn->nextConnectionList.storeRelaxed(signalsVector->at(i).first);
            signalsVector->at(i).first.storeRelaxed(ourConn);
            return true;
        }
    }

    return false;
}

NetworkReply::ContentType contentType(const QVariant &v)
{
    if (v.toString().contains(QLatin1String("application/json"))) {
        return NetworkReply::Json;
    } else if (v.toString().contains(QLatin1String("application/xml"))) {
        return NetworkReply::Xml;
    } else if (v.toString().startsWith(QLatin1String("image/"))) {
        return NetworkReply::Image;
    }
    return NetworkReply::Unknown;
}

}

NetworkReplyModel::NetworkReplyModel(QObject *parent)
    : QAbstractItemModel(parent)
{
    m_time.start();

    qRegisterMetaType<QNetworkAccessManager *>();
    qRegisterMetaType<GammaRay::NetworkReplyModel::ReplyNode>();
}

NetworkReplyModel::~NetworkReplyModel() = default;

int NetworkReplyModel::columnCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    return NetworkReplyModelColumn::COLUMN_COUNT;
}

int NetworkReplyModel::rowCount(const QModelIndex &parent) const
{
    if (!parent.isValid()) {
        return m_nodes.size();
    }

    if (parent.internalId() == TopIndex) {
        return m_nodes[parent.row()].replies.size();
    }

    return 0;
}

QVariant NetworkReplyModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid()) {
        return {};
    }

    // top-level
    if (index.internalId() == TopIndex) {
        const auto &nam = m_nodes[index.row()];
        if (index.column() == NetworkReplyModelColumn::ObjectColumn && role == Qt::DisplayRole) {
            return nam.displayName;
        } else if (role == NetworkReplyModelRole::ObjectIdRole && index.column() == NetworkReplyModelColumn::ObjectColumn) {
            return QVariant::fromValue(ObjectId(nam.nam));
        }
        return {};
    }

    // reply level
    const auto &reply = m_nodes[index.internalId()].replies[index.row()];
    if (role == Qt::DisplayRole) {
        switch (index.column()) {
        case NetworkReplyModelColumn::ObjectColumn:
            return reply.displayName;
        case NetworkReplyModelColumn::OpColumn:
            return reply.op;
        case NetworkReplyModelColumn::SizeColumn:
            if (reply.duration == 0 && reply.size == 0) {
                return {}; // cached reply, we don't have proper data for that
            }
            return reply.size;
        case NetworkReplyModelColumn::TimeColumn:
            if (reply.state & NetworkReply::Finished) {
                return reply.duration;
            }
            return {};
        case NetworkReplyModelColumn::UrlColumn:
            return reply.url;
        }
    } else if (role == NetworkReplyModelRole::ReplyStateRole && index.column() == NetworkReplyModelColumn::ObjectColumn) {
        return reply.state;
    } else if (role == NetworkReplyModelRole::ReplyErrorRole && index.column() == NetworkReplyModelColumn::ObjectColumn) {
        return reply.errorMsgs;
    } else if (role == NetworkReplyModelRole::ObjectIdRole && index.column() == NetworkReplyModelColumn::ObjectColumn) {
        return QVariant::fromValue(ObjectId(reply.reply));
    } else if (role == NetworkReplyModelRole::ReplyResponseRole && index.column() == NetworkReplyModelColumn::ObjectColumn) {
        return reply.response;
    } else if (role == NetworkReplyModelRole::ReplyContentType && index.column() == NetworkReplyModelColumn::ObjectColumn) {
        return reply.contentType;
    }

    return {};
}

QModelIndex NetworkReplyModel::index(int row, int column, const QModelIndex &parent) const
{
    // top-level
    if (!parent.isValid()) {
        return createIndex(row, column, TopIndex);
    }

    return createIndex(row, column, parent.row());
}

QModelIndex NetworkReplyModel::parent(const QModelIndex &child) const
{
    if (child.internalId() == TopIndex) {
        return {};
    }

    return createIndex(child.internalId(), 0, TopIndex);
}

void NetworkReplyModel::objectCreated(QObject *obj)
{
    if (auto nam = qobject_cast<QNetworkAccessManager *>(obj)) {
        beginInsertRows({}, m_nodes.size(), m_nodes.size());
        NAMNode node;
        node.nam = nam;
        node.displayName = Util::displayString(nam);
        m_nodes.push_back(node);
        endInsertRows();

        connect(
            nam, &QNetworkAccessManager::finished, this, [this, nam](QNetworkReply *reply) { replyFinished(reply, nam); }, Qt::DirectConnection);
#ifndef QT_NO_SSL
        connect(
            nam, &QNetworkAccessManager::encrypted, this, [this, nam](QNetworkReply *reply) { replyEncrypted(reply, nam); }, Qt::DirectConnection);
        connect(nam, &QNetworkAccessManager::sslErrors, this, [this, nam](QNetworkReply *reply, const QList<QSslError> &errors) { replySslErrors(reply, errors, nam); });
#endif
    }

    if (auto reply = qobject_cast<QNetworkReply *>(obj)) {
        auto nam = reply->manager();
        auto namIt = std::find_if(m_nodes.begin(), m_nodes.end(), [nam](const NAMNode &node) {
            return node.nam == nam;
        });

        if (namIt == m_nodes.end()) {
            // TODO
            return;
        }

        ReplyNode replyNode;
        replyNode.reply = reply;
        replyNode.displayName = Util::displayString(reply);
        replyNode.op = reply->operation();
        replyNode.url = reply->url();
        if (reply->isFinished()) {
            replyNode.state |= NetworkReply::Finished;
            replyNode.duration = 0;
        } else {
            replyNode.duration = m_time.elapsed();
        }
        replyNode.contentType = contentType(reply->header(QNetworkRequest::ContentTypeHeader));
        updateReplyNode(nam, replyNode);

        if (m_captureResponse) {
            connect(
                reply, &QNetworkReply::downloadProgress, this, [this, reply, nam](qint64 received, qint64 total) { replyProgressSync(reply, received, total, nam); }, Qt::DirectConnection);
            if (!prioritizeLatestConnection(reply, QMetaObject::normalizedSignature("downloadProgress(qint64,qint64)"), this)) {
                qWarning() << "Failed to prioritize our slot, capturing network response might not work";
            }
        }

        // capture nam, as we cannot deref reply anymore when this triggers
        connect(reply, &QNetworkReply::downloadProgress, this, [this, reply, nam](qint64 received, qint64 total) { replyProgress(reply, received, total, nam); });
        connect(reply, &QNetworkReply::uploadProgress, this, [this, reply, nam](qint64 received, qint64 total) { replyProgress(reply, received, total, nam); });
        connect(reply, &QNetworkReply::destroyed, this, [this, reply, nam]() { replyDeleted(reply, nam); });
    }
}

QMap<int, QVariant> NetworkReplyModel::itemData(const QModelIndex &index) const
{
    auto m = QAbstractItemModel::itemData(index);
    if (index.column() == 0) {
        m.insert(NetworkReplyModelRole::ReplyStateRole, data(index, NetworkReplyModelRole::ReplyStateRole));
        m.insert(NetworkReplyModelRole::ReplyErrorRole, data(index, NetworkReplyModelRole::ReplyErrorRole));
        m.insert(NetworkReplyModelRole::ObjectIdRole, data(index, NetworkReplyModelRole::ObjectIdRole));
        m.insert(NetworkReplyModelRole::ReplyResponseRole, data(index, NetworkReplyModelRole::ReplyResponseRole));
        m.insert(NetworkReplyModelRole::ReplyContentType, data(index, NetworkReplyModelRole::ReplyContentType));
    }
    return m;
}

void NetworkReplyModel::replyFinished(QNetworkReply *reply, QNetworkAccessManager *nam)
{
    /// WARNING this runs in the thread of the reply, not the thread of this!
    ReplyNode node;
    node.reply = reply;
    node.displayName = Util::displayString(reply);
    node.url = reply->url();
    node.op = reply->operation();
    node.state |= NetworkReply::Finished;
    node.duration = m_time.elapsed() - node.duration;
    node.contentType = contentType(reply->header(QNetworkRequest::ContentTypeHeader));

    maybePeekResponse(node, reply);

    if (reply->error() != QNetworkReply::NoError) {
        node.state |= NetworkReply::Error;
        node.errorMsgs.push_back(reply->errorString());
    }

    // clang-format off
    QMetaObject::invokeMethod(this, "updateReplyNode", Qt::AutoConnection, Q_ARG(QNetworkAccessManager*, nam), Q_ARG(GammaRay::NetworkReplyModel::ReplyNode, node));
    // clang-format on

    if (reply->thread() != thread()) {
        connect(
            reply, &QNetworkReply::destroyed, this, [this, reply, nam]() { replyDeleted(reply, nam); }, Qt::DirectConnection);
    }
}

void NetworkReplyModel::replyProgress(QNetworkReply *reply, qint64 progress, qint64 total, QNetworkAccessManager *nam)
{
    ReplyNode node;
    node.reply = reply;
    node.size = std::max(progress, total);
    updateReplyNode(nam, node);
}

void NetworkReplyModel::replyProgressSync(QNetworkReply *reply, qint64 progress, qint64 total, QNetworkAccessManager *nam)
{
    /// WARNING this runs in the thread of the reply, not the thread of this!
    ReplyNode node;
    node.reply = reply;
    node.size = std::max(progress, total);
    maybePeekResponse(node, reply);

    // clang-format off
    QMetaObject::invokeMethod(this, "updateReplyNode", Qt::AutoConnection, Q_ARG(QNetworkAccessManager*, nam), Q_ARG(GammaRay::NetworkReplyModel::ReplyNode, node));
    // clang-format on
}

#ifndef QT_NO_SSL
void NetworkReplyModel::replyEncrypted(QNetworkReply *reply, QNetworkAccessManager *nam)
{
    /// WARNING this runs in the thread of the reply, not the thread of this!
    ReplyNode node;
    node.reply = reply;
    node.displayName = Util::displayString(reply);
    node.url = reply->url();
    node.op = reply->operation();
    node.state |= NetworkReply::Encrypted;
    // clang-format off
    QMetaObject::invokeMethod(this, "updateReplyNode", Qt::AutoConnection, Q_ARG(QNetworkAccessManager*, nam), Q_ARG(GammaRay::NetworkReplyModel::ReplyNode, node));
    // clang-format on
}

void NetworkReplyModel::replySslErrors(QNetworkReply *reply, const QList<QSslError> &errors, QNetworkAccessManager *nam)
{
    /// WARNING this runs in the thread of the reply, not the thread of this!
    ReplyNode node;
    node.reply = reply;
    node.displayName = Util::displayString(reply);
    node.url = reply->url();
    node.op = reply->operation();
    node.state |= NetworkReply::Error | NetworkReply::Unencrypted;
    for (const auto &err : errors) {
        node.errorMsgs.push_back(err.errorString());
    }

    // clang-format off
    QMetaObject::invokeMethod(this, "updateReplyNode", Qt::AutoConnection, Q_ARG(QNetworkAccessManager*, nam), Q_ARG(GammaRay::NetworkReplyModel::ReplyNode, node));
    // clang-format on
}
#endif

void NetworkReplyModel::replyDeleted(QNetworkReply *reply, QNetworkAccessManager *nam)
{
    /// WARNING this runs in the thread of the reply, not the thread of this!
    ReplyNode node;
    node.reply = reply;
    node.state |= NetworkReply::Deleted;
    // clang-format off
    QMetaObject::invokeMethod(this, "updateReplyNode", Qt::AutoConnection, Q_ARG(QNetworkAccessManager*, nam), Q_ARG(GammaRay::NetworkReplyModel::ReplyNode, node));
    // clang-format on
}

void NetworkReplyModel::maybePeekResponse(ReplyNode &node, QNetworkReply *reply) const
{
    if (m_captureResponse) {
        // TODO: Allow whitelisting a set of Content-Type values
        // TODO: Make the max size configurable
        const auto resp = reply->peek(5 * 1024 * 1024); // Read up to 5 MiB
        if (!resp.isEmpty())
            node.response = resp;
    }
}

void NetworkReplyModel::updateReplyNode(QNetworkAccessManager *nam, const NetworkReplyModel::ReplyNode &newNode)
{
    // WARNING reply is no longer safe to deref here!
    const auto namIt = std::find_if(m_nodes.begin(), m_nodes.end(), [nam](const NAMNode &node) {
        return node.nam == nam;
    });

    if (namIt == m_nodes.end()) {
        return;
    }

    auto replyIt = std::find_if((*namIt).replies.rbegin(), (*namIt).replies.rend(), [newNode](const ReplyNode &node) {
        // be careful with considering past deleted nodes, address can be reused
        return node.reply == newNode.reply && ((node.state & NetworkReply::Deleted) == 0 || newNode.state & NetworkReply::Deleted);
    });

    if (replyIt == (*namIt).replies.rend()) {
        const auto parentIdx = createIndex(std::distance(m_nodes.begin(), namIt), 0, TopIndex);
        beginInsertRows(parentIdx, (*namIt).replies.size(), (*namIt).replies.size());
        ReplyNode replyNode = newNode;
        if (replyNode.displayName.isEmpty()) {
            replyNode.displayName = Util::addressToString(newNode.reply);
        }
        (*namIt).replies.push_back(replyNode);
        endInsertRows();
        replyIt = (*namIt).replies.rbegin();
    } else {
        if (!newNode.displayName.isEmpty()) {
            (*replyIt).displayName = newNode.displayName;
        }
        (*replyIt).state |= newNode.state;
        if ((*replyIt).state & NetworkReply::Unencrypted) {
            (*replyIt).state &= ~NetworkReply::Encrypted;
        }
        if (!newNode.url.isEmpty()) {
            (*replyIt).url = newNode.url;
            (*replyIt).op = newNode.op;
        }
        if (!newNode.response.isEmpty()) {
            (*replyIt).response = newNode.response;
        }
        (*replyIt).errorMsgs += newNode.errorMsgs;
        if ((*replyIt).duration > 0 && newNode.duration > 0 && (newNode.state & NetworkReply::Finished)) {
            (*replyIt).duration = newNode.duration > (*replyIt).duration ? newNode.duration - (*replyIt).duration : 0;
        }
        (*replyIt).size = std::max((*replyIt).size, newNode.size);
        if (newNode.contentType != NetworkReply::Unknown)
            (*replyIt).contentType = newNode.contentType;

        const auto idx = createIndex(std::distance(replyIt, (*namIt).replies.rend()) - 1, 0, std::distance(m_nodes.begin(), namIt));
        emit dataChanged(idx, idx.sibling(idx.row(), columnCount() - 1));
    }
}

void NetworkReplyModel::setCaptureResponse(bool newCaptureResponse)
{
    if (m_captureResponse == newCaptureResponse)
        return;
    m_captureResponse = newCaptureResponse;
    emit captureResponseChanged();
}