summaryrefslogtreecommitdiffstats
path: root/src/network/access/qhttpthreaddelegate_p.h
blob: 38e9fb4d7829441a1c127f89bf78af2cc7e4429b (plain)
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
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

#ifndef QHTTPTHREADDELEGATE_H
#define QHTTPTHREADDELEGATE_H


//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API.  It exists for the convenience
// of the Network Access API.  This header file may change from
// version to version without notice, or even be removed.
//
// We mean it.
//

#include <QtNetwork/private/qtnetworkglobal_p.h>
#include <QObject>
#include <QThreadStorage>
#include <QNetworkProxy>
#include <QSslConfiguration>
#include <QSslError>
#include <QList>
#include <QNetworkReply>
#include "qhttpnetworkrequest_p.h"
#include "qhttpnetworkconnection_p.h"
#include "qhttp1configuration.h"
#include "qhttp2configuration.h"
#include <QSharedPointer>
#include <QScopedPointer>
#include "private/qnoncontiguousbytedevice_p.h"
#include "qnetworkaccessauthenticationmanager_p.h"
#include <QtNetwork/private/http2protocol_p.h>
#include <QtNetwork/qhttpheaders.h>

QT_REQUIRE_CONFIG(http);

QT_BEGIN_NAMESPACE

class QAuthenticator;
class QHttpNetworkReply;
class QEventLoop;
class QNetworkAccessCache;
class QNetworkAccessCachedHttpConnection;

class QHttpThreadDelegate : public QObject
{
    Q_OBJECT
public:
    explicit QHttpThreadDelegate(QObject *parent = nullptr);

    ~QHttpThreadDelegate();

    // incoming
    bool ssl;
#ifndef QT_NO_SSL
    QScopedPointer<QSslConfiguration> incomingSslConfiguration;
#endif
    QHttpNetworkRequest httpRequest;
    qint64 downloadBufferMaximumSize;
    qint64 readBufferMaxSize;
    qint64 bytesEmitted;
    // From backend, modified by us for signal compression
    std::shared_ptr<QAtomicInt> pendingDownloadData;
    std::shared_ptr<QAtomicInt> pendingDownloadProgress;
#ifndef QT_NO_NETWORKPROXY
    QNetworkProxy cacheProxy;
    QNetworkProxy transparentProxy;
#endif
    std::shared_ptr<QNetworkAccessAuthenticationManager> authenticationManager;
    bool synchronous;
    qint64 connectionCacheExpiryTimeoutSeconds;

    // outgoing, Retrieved in the synchronous HTTP case
    QByteArray synchronousDownloadData;
    QHttpHeaders incomingHeaders;
    int incomingStatusCode;
    QString incomingReasonPhrase;
    bool isPipeliningUsed;
    bool isHttp2Used;
    qint64 incomingContentLength;
    qint64 removedContentLength;
    QNetworkReply::NetworkError incomingErrorCode;
    QString incomingErrorDetail;
    QHttp1Configuration http1Parameters;
    QHttp2Configuration http2Parameters;

    bool isCompressed;

protected:
    // The zerocopy download buffer, if used:
    QSharedPointer<char> downloadBuffer;
    // The QHttpNetworkConnection that is used
    QNetworkAccessCachedHttpConnection *httpConnection;
    QByteArray cacheKey;
    QHttpNetworkReply *httpReply;

    // Used for implementing the synchronous HTTP, see startRequestSynchronously()
    QEventLoop *synchronousRequestLoop;

signals:
    void authenticationRequired(const QHttpNetworkRequest &request, QAuthenticator *);
#ifndef QT_NO_NETWORKPROXY
    void proxyAuthenticationRequired(const QNetworkProxy &, QAuthenticator *);
#endif
#ifndef QT_NO_SSL
    void encrypted();
    void sslErrors(const QList<QSslError> &, bool *, QList<QSslError> *);
    void sslConfigurationChanged(const QSslConfiguration &);
    void preSharedKeyAuthenticationRequired(QSslPreSharedKeyAuthenticator *);
#endif
    void socketStartedConnecting();
    void requestSent();
    void downloadMetaData(const QHttpHeaders &, int, const QString &, bool,
                          QSharedPointer<char>, qint64, qint64, bool, bool);
    void downloadProgress(qint64, qint64);
    void downloadData(const QByteArray &);
    void error(QNetworkReply::NetworkError, const QString &);
    void downloadFinished();
    void redirected(const QUrl &url, int httpStatus, int maxRedirectsRemainig);

public slots:
    // This are called via QueuedConnection from user thread
    void startRequest();
    void abortRequest();
    void readBufferSizeChanged(qint64 size);
    void readBufferFreed(qint64 size);

    // This is called with a BlockingQueuedConnection from user thread
    void startRequestSynchronously();
protected slots:
    // From QHttp*
    void readyReadSlot();
    void finishedSlot();
    void finishedWithErrorSlot(QNetworkReply::NetworkError errorCode, const QString &detail = QString());
    void synchronousFinishedSlot();
    void synchronousFinishedWithErrorSlot(QNetworkReply::NetworkError errorCode, const QString &detail = QString());
    void headerChangedSlot();
    void synchronousHeaderChangedSlot();
    void dataReadProgressSlot(qint64 done, qint64 total);
    void cacheCredentialsSlot(const QHttpNetworkRequest &request, QAuthenticator *authenticator);
#ifndef QT_NO_SSL
    void encryptedSlot();
    void sslErrorsSlot(const QList<QSslError> &errors);
    void preSharedKeyAuthenticationRequiredSlot(QSslPreSharedKeyAuthenticator *authenticator);
#endif

    void synchronousAuthenticationRequiredSlot(const QHttpNetworkRequest &request, QAuthenticator *);
#ifndef QT_NO_NETWORKPROXY
    void synchronousProxyAuthenticationRequiredSlot(const QNetworkProxy &, QAuthenticator *);
#endif

protected:
    // Cache for all the QHttpNetworkConnection objects.
    // This is per thread.
    static QThreadStorage<QNetworkAccessCache *> connections;

};

// This QNonContiguousByteDevice is connected to the QNetworkAccessHttpBackend
// and represents the PUT/POST data.
class QNonContiguousByteDeviceThreadForwardImpl : public QNonContiguousByteDevice
{
    Q_OBJECT
protected:
    bool wantDataPending = false;
    qint64 m_amount = 0;
    char *m_data = nullptr;
    QByteArray m_dataArray;
    bool m_atEnd = false;
    qint64 m_size = 0;
    qint64 m_pos = 0; // to match calls of haveDataSlot with the expected position
public:
    QNonContiguousByteDeviceThreadForwardImpl(bool aE, qint64 s)
        : QNonContiguousByteDevice(),
          m_atEnd(aE),
          m_size(s)
    {
    }

    ~QNonContiguousByteDeviceThreadForwardImpl()
    {
    }

    qint64 pos() const override
    {
        return m_pos;
    }

    const char* readPointer(qint64 maximumLength, qint64 &len) override
    {
        if (m_amount > 0) {
            len = m_amount;
            return m_data;
        }

        if (m_atEnd) {
            len = -1;
        } else if (!wantDataPending) {
            len = 0;
            wantDataPending = true;
            emit wantData(maximumLength);
        } else {
            // Do nothing, we already sent a wantData signal and wait for results
            len = 0;
        }
        return nullptr;
    }

    bool advanceReadPointer(qint64 a) override
    {
        if (m_data == nullptr)
            return false;

        m_amount -= a;
        m_data += a;
        m_pos += a;

        // To main thread to inform about our state. The m_pos will be sent as a sanity check.
        emit processedData(m_pos, a);

        return true;
    }

    bool atEnd() const override
    {
        if (m_amount > 0)
            return false;
        else
            return m_atEnd;
    }

    bool reset() override
    {
        m_amount = 0;
        m_data = nullptr;
        m_dataArray.clear();

        if (wantDataPending) {
            // had requested the user thread to send some data (only 1 in-flight at any moment)
            wantDataPending = false;
        }

        // Communicate as BlockingQueuedConnection
        bool b = false;
        emit resetData(&b);
        if (b) {
            // the reset succeeded, we're at pos 0 again
            m_pos = 0;
            m_atEnd = false;
            // the HTTP code will anyway abort the request if !b.
        }
        return b;
    }

    qint64 size() const override
    {
        return m_size;
    }

public slots:
    // From user thread:
    void haveDataSlot(qint64 pos, const QByteArray &dataArray, bool dataAtEnd, qint64 dataSize)
    {
        if (pos != m_pos) {
            // Sometimes when re-sending a request in the qhttpnetwork* layer there is a pending haveData from the
            // user thread on the way to us. We need to ignore it since it is the data for the wrong(later) chunk.
            return;
        }
        wantDataPending = false;

        m_dataArray = dataArray;
        m_data = const_cast<char*>(m_dataArray.constData());
        m_amount = dataArray.size();

        m_atEnd = dataAtEnd;
        m_size = dataSize;

        // This will tell the HTTP code (QHttpNetworkConnectionChannel) that we have data available now
        emit readyRead();
    }

signals:
    // void readyRead(); in parent class
    // void readProgress(qint64 current, qint64 total); happens in the main thread with the real bytedevice

    // to main thread:
    void wantData(qint64);
    void processedData(qint64 pos, qint64 amount);
    void resetData(bool *b);
};

QT_END_NAMESPACE

#endif // QHTTPTHREADDELEGATE_H