Branch data Line data Source code
1 : : #pragma once
2 : :
3 : : #include <QNetworkReply>
4 : : #include <QNetworkRequest>
5 : : #include <QTimer>
6 : :
7 : : namespace DavNetworkLimits {
8 : :
9 : : inline constexpr qint64 MaxResponseBytes = 10 * 1024 * 1024;
10 : : inline constexpr int RequestTimeoutMs = 30000;
11 : : inline constexpr const char *FailureProperty = "mailjdDavNetworkFailure";
12 : :
13 : 5 : inline QString responseTooLargeMessage(qint64 bytes) {
14 : 10 : return QStringLiteral("DAV response too large (%1 bytes, limit %2 bytes)")
15 [ + - ]: 15 : .arg(bytes)
16 [ + - ]: 10 : .arg(MaxResponseBytes);
17 : : }
18 : :
19 : 8 : inline void failReply(QNetworkReply *reply, const QString &error) {
20 [ + + + - : 8 : if (!reply || reply->property(FailureProperty).isValid())
+ - + + +
+ + + -
- ]
21 : 2 : return;
22 [ + - ]: 6 : reply->setProperty(FailureProperty, error);
23 : 6 : reply->abort();
24 : : }
25 : :
26 : 120 : inline void checkResponseSize(QNetworkReply *reply) {
27 [ + + + - : 120 : if (!reply || reply->property(FailureProperty).isValid())
+ - + + +
+ + + -
- ]
28 : 15 : return;
29 : :
30 : : const QVariant contentLength =
31 [ + - ]: 107 : reply->header(QNetworkRequest::ContentLengthHeader);
32 [ + - + + ]: 107 : if (contentLength.isValid()) {
33 : 3 : bool ok = false;
34 [ + - ]: 3 : const qint64 declaredSize = contentLength.toLongLong(&ok);
35 [ + - + + ]: 3 : if (ok && declaredSize > MaxResponseBytes) {
36 [ + - + - ]: 2 : failReply(reply, responseTooLargeMessage(declaredSize));
37 : 2 : return;
38 : : }
39 : : }
40 : :
41 [ + - ]: 105 : const qint64 buffered = reply->bytesAvailable();
42 [ + + ]: 105 : if (buffered > MaxResponseBytes)
43 [ + - + - ]: 2 : failReply(reply, responseTooLargeMessage(buffered));
44 [ + + ]: 107 : }
45 : :
46 : 110 : inline void apply(QNetworkReply *reply) {
47 [ + + ]: 110 : if (!reply)
48 : 1 : return;
49 : :
50 [ + - - + : 109 : auto *timer = new QTimer(reply);
- - ]
51 : 109 : timer->setSingleShot(true);
52 [ + - ]: 109 : QObject::connect(timer, &QTimer::timeout, reply, [reply]() {
53 [ # # ]: 0 : failReply(reply, QStringLiteral("DAV request timed out"));
54 : 0 : });
55 [ + - ]: 109 : QObject::connect(reply, &QNetworkReply::finished, timer, &QTimer::stop);
56 : 109 : timer->start(RequestTimeoutMs);
57 : :
58 : 109 : QObject::connect(reply, &QNetworkReply::metaDataChanged, reply,
59 [ + - ]: 112 : [reply]() { checkResponseSize(reply); });
60 : 109 : QObject::connect(reply, &QNetworkReply::readyRead, reply,
61 [ + - ]: 111 : [reply]() { checkResponseSize(reply); });
62 [ + - ]: 218 : QTimer::singleShot(0, reply, [reply]() { checkResponseSize(reply); });
63 : : }
64 : :
65 : 111 : inline QString failureReason(QNetworkReply *reply) {
66 [ + + + - : 222 : return reply ? reply->property(FailureProperty).toString() : QString();
+ - + + -
- ]
67 : : }
68 : :
69 : : } // namespace DavNetworkLimits
|