Coverage Report

Created: 2026-02-26 07:48

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/qtbase/src/network/socket/qhttpsocketengine.cpp
Line
Count
Source
1
// Copyright (C) 2016 The Qt Company Ltd.
2
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3
// Qt-Security score:critical reason:network-protocol
4
5
#include "qhttpsocketengine_p.h"
6
#include "qtcpsocket.h"
7
#include "qhostaddress.h"
8
#include "qurl.h"
9
#include "private/qhttpnetworkreply_p.h"
10
#include "private/qiodevice_p.h"
11
#include "qdeadlinetimer.h"
12
#include "qnetworkinterface.h"
13
14
#if !defined(QT_NO_NETWORKPROXY)
15
#include <qdebug.h>
16
17
QT_BEGIN_NAMESPACE
18
19
using namespace Qt::StringLiterals;
20
21
#define DEBUG
22
23
QHttpSocketEngine::QHttpSocketEngine(QObject *parent)
24
0
    : QAbstractSocketEngine(*new QHttpSocketEnginePrivate, parent)
25
0
{
26
0
}
27
28
QHttpSocketEngine::~QHttpSocketEngine()
29
0
{
30
0
}
31
32
bool QHttpSocketEngine::initialize(QAbstractSocket::SocketType type, QAbstractSocket::NetworkLayerProtocol protocol)
33
0
{
34
0
    Q_D(QHttpSocketEngine);
35
0
    if (type != QAbstractSocket::TcpSocket)
36
0
        return false;
37
38
0
    setProtocol(protocol);
39
0
    setSocketType(type);
40
0
    d->socket = new QTcpSocket(this);
41
0
    d->reply = new QHttpNetworkReply(QUrl(), this);
42
43
    // Explicitly disable proxying on the proxy socket itself to avoid
44
    // unwanted recursion.
45
0
    d->socket->setProxy(QNetworkProxy::NoProxy);
46
47
    // Intercept all the signals.
48
0
    connect(d->socket, SIGNAL(connected()),
49
0
            this, SLOT(slotSocketConnected()),
50
0
            Qt::DirectConnection);
51
0
    connect(d->socket, SIGNAL(disconnected()),
52
0
            this, SLOT(slotSocketDisconnected()),
53
0
            Qt::DirectConnection);
54
0
    connect(d->socket, SIGNAL(readyRead()),
55
0
            this, SLOT(slotSocketReadNotification()),
56
0
            Qt::DirectConnection);
57
0
    connect(d->socket, SIGNAL(bytesWritten(qint64)),
58
0
            this, SLOT(slotSocketBytesWritten()),
59
0
            Qt::DirectConnection);
60
0
    connect(d->socket, SIGNAL(errorOccurred(QAbstractSocket::SocketError)),
61
0
            this, SLOT(slotSocketError(QAbstractSocket::SocketError)),
62
0
            Qt::DirectConnection);
63
0
    connect(d->socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)),
64
0
            this, SLOT(slotSocketStateChanged(QAbstractSocket::SocketState)),
65
0
            Qt::DirectConnection);
66
67
0
    return true;
68
0
}
69
70
bool QHttpSocketEngine::initialize(qintptr, QAbstractSocket::SocketState)
71
0
{
72
0
    return false;
73
0
}
74
75
void QHttpSocketEngine::setProxy(const QNetworkProxy &proxy)
76
0
{
77
0
    Q_D(QHttpSocketEngine);
78
0
    d->proxy = proxy;
79
0
    QString user = proxy.user();
80
0
    if (!user.isEmpty())
81
0
        d->authenticator.setUser(user);
82
0
    QString password = proxy.password();
83
0
    if (!password.isEmpty())
84
0
        d->authenticator.setPassword(password);
85
0
}
86
87
qintptr QHttpSocketEngine::socketDescriptor() const
88
0
{
89
0
    Q_D(const QHttpSocketEngine);
90
0
    return d->socket ? d->socket->socketDescriptor() : -1;
91
0
}
92
93
bool QHttpSocketEngine::isValid() const
94
0
{
95
0
    Q_D(const QHttpSocketEngine);
96
0
    return d->socket;
97
0
}
98
99
bool QHttpSocketEngine::connectInternal()
100
0
{
101
0
    Q_D(QHttpSocketEngine);
102
103
0
    d->credentialsSent = false;
104
105
    // If the handshake is done, enter ConnectedState state and return true.
106
0
    if (d->state == Connected) {
107
0
        qWarning("QHttpSocketEngine::connectToHost: called when already connected");
108
0
        setState(QAbstractSocket::ConnectedState);
109
0
        return true;
110
0
    }
111
112
0
    if (d->state == ConnectSent && d->socketState != QAbstractSocket::ConnectedState)
113
0
        setState(QAbstractSocket::UnconnectedState);
114
115
    // Handshake isn't done. If unconnected, start connecting.
116
0
    if (d->state == None && d->socket->state() == QAbstractSocket::UnconnectedState) {
117
0
        setState(QAbstractSocket::ConnectingState);
118
        //limit buffer in internal socket, data is buffered in the external socket under application control
119
0
        d->socket->setReadBufferSize(65536);
120
0
        d->socket->connectToHost(d->proxy.hostName(), d->proxy.port());
121
0
    }
122
123
    // If connected (might happen right away, at least for localhost services
124
    // on some BSD systems), there might already be bytes available.
125
0
    if (bytesAvailable())
126
0
        slotSocketReadNotification();
127
128
0
    return d->socketState == QAbstractSocket::ConnectedState;
129
0
}
130
131
bool QHttpSocketEngine::connectToHost(const QHostAddress &address, quint16 port)
132
0
{
133
0
    Q_D(QHttpSocketEngine);
134
135
0
    setPeerAddress(address);
136
0
    setPeerPort(port);
137
0
    d->peerName.clear();
138
139
0
    return connectInternal();
140
0
}
141
142
bool QHttpSocketEngine::connectToHostByName(const QString &hostname, quint16 port)
143
0
{
144
0
    Q_D(QHttpSocketEngine);
145
146
0
    setPeerAddress(QHostAddress());
147
0
    setPeerPort(port);
148
0
    d->peerName = hostname;
149
150
0
    return connectInternal();
151
0
}
152
153
bool QHttpSocketEngine::bind(const QHostAddress &, quint16)
154
0
{
155
0
    qWarning("Operation is not supported");
156
0
    setError(QAbstractSocket::UnsupportedSocketOperationError, "Unsupported socket operation"_L1);
157
0
    return false;
158
0
}
159
160
bool QHttpSocketEngine::listen(int backlog)
161
0
{
162
0
    Q_UNUSED(backlog);
163
0
    qWarning("Operation is not supported");
164
0
    setError(QAbstractSocket::UnsupportedSocketOperationError, "Unsupported socket operation"_L1);
165
0
    return false;
166
0
}
167
168
qintptr QHttpSocketEngine::accept()
169
0
{
170
0
    qWarning("Operation is not supported");
171
0
    setError(QAbstractSocket::UnsupportedSocketOperationError, "Unsupported socket operation"_L1);
172
0
    return -1;
173
0
}
174
175
void QHttpSocketEngine::close()
176
0
{
177
0
    Q_D(QHttpSocketEngine);
178
0
    if (d->socket) {
179
0
        d->socket->close();
180
0
        delete d->socket;
181
0
        d->socket = nullptr;
182
0
    }
183
0
}
184
185
qint64 QHttpSocketEngine::bytesAvailable() const
186
0
{
187
0
    Q_D(const QHttpSocketEngine);
188
0
    return d->socket ? d->socket->bytesAvailable() : 0;
189
0
}
190
191
qint64 QHttpSocketEngine::read(char *data, qint64 maxlen)
192
0
{
193
0
    Q_D(QHttpSocketEngine);
194
0
    qint64 bytesRead = d->socket->read(data, maxlen);
195
196
0
    if (d->socket->state() == QAbstractSocket::UnconnectedState
197
0
        && d->socket->bytesAvailable() == 0) {
198
0
        emitReadNotification();
199
0
    }
200
201
0
    if (bytesRead == -1) {
202
        // If nothing has been read so far, and the direct socket read
203
        // failed, return the socket's error. Otherwise, fall through and
204
        // return as much as we read so far.
205
0
        close();
206
0
        setError(QAbstractSocket::RemoteHostClosedError, "Remote host closed"_L1);
207
0
        setState(QAbstractSocket::UnconnectedState);
208
0
        return -1;
209
0
    }
210
0
    return bytesRead;
211
0
}
212
213
qint64 QHttpSocketEngine::write(const char *data, qint64 len)
214
0
{
215
0
    Q_D(QHttpSocketEngine);
216
0
    return d->socket->write(data, len);
217
0
}
218
219
#ifndef QT_NO_UDPSOCKET
220
#ifndef QT_NO_NETWORKINTERFACE
221
bool QHttpSocketEngine::joinMulticastGroup(const QHostAddress &,
222
                                           const QNetworkInterface &)
223
0
{
224
0
    qWarning("Operation is not supported");
225
0
    setError(QAbstractSocket::UnsupportedSocketOperationError, "Unsupported socket operation"_L1);
226
0
    return false;
227
0
}
228
229
bool QHttpSocketEngine::leaveMulticastGroup(const QHostAddress &,
230
                                            const QNetworkInterface &)
231
0
{
232
0
    qWarning("Operation is not supported");
233
0
    setError(QAbstractSocket::UnsupportedSocketOperationError, "Unsupported socket operation"_L1);
234
0
    return false;
235
0
}
236
237
QNetworkInterface QHttpSocketEngine::multicastInterface() const
238
0
{
239
0
    return QNetworkInterface();
240
0
}
241
242
bool QHttpSocketEngine::setMulticastInterface(const QNetworkInterface &)
243
0
{
244
0
    qWarning("Operation is not supported");
245
0
    setError(QAbstractSocket::UnsupportedSocketOperationError, "Unsupported socket operation"_L1);
246
0
    return false;
247
0
}
248
#endif // QT_NO_NETWORKINTERFACE
249
250
bool QHttpSocketEngine::hasPendingDatagrams() const
251
0
{
252
0
    qWarning("Operation is not supported");
253
0
    return false;
254
0
}
255
256
qint64 QHttpSocketEngine::pendingDatagramSize() const
257
0
{
258
0
    qWarning("Operation is not supported");
259
0
    return -1;
260
0
}
261
#endif // QT_NO_UDPSOCKET
262
263
qint64 QHttpSocketEngine::readDatagram(char *, qint64, QIpPacketHeader *, PacketHeaderOptions)
264
0
{
265
0
    qWarning("Operation is not supported");
266
0
    setError(QAbstractSocket::UnsupportedSocketOperationError, "Unsupported socket operation"_L1);
267
0
    return -1;
268
0
}
269
270
qint64 QHttpSocketEngine::writeDatagram(const char *, qint64, const QIpPacketHeader &)
271
0
{
272
0
    qWarning("Operation is not supported");
273
0
    setError(QAbstractSocket::UnsupportedSocketOperationError, "Unsupported socket operation"_L1);
274
0
    return -1;
275
0
}
276
277
qint64 QHttpSocketEngine::bytesToWrite() const
278
0
{
279
0
    Q_D(const QHttpSocketEngine);
280
0
    if (d->socket) {
281
0
        return d->socket->bytesToWrite();
282
0
    } else {
283
0
        return 0;
284
0
    }
285
0
}
286
287
int QHttpSocketEngine::option(SocketOption option) const
288
0
{
289
0
    Q_D(const QHttpSocketEngine);
290
0
    if (d->socket) {
291
        // convert the enum and call the real socket
292
0
        if (option == QAbstractSocketEngine::LowDelayOption)
293
0
            return d->socket->socketOption(QAbstractSocket::LowDelayOption).toInt();
294
0
        if (option == QAbstractSocketEngine::KeepAliveOption)
295
0
            return d->socket->socketOption(QAbstractSocket::KeepAliveOption).toInt();
296
0
    }
297
0
    return -1;
298
0
}
299
300
bool QHttpSocketEngine::setOption(SocketOption option, int value)
301
0
{
302
0
    Q_D(QHttpSocketEngine);
303
0
    if (d->socket) {
304
        // convert the enum and call the real socket
305
0
        if (option == QAbstractSocketEngine::LowDelayOption)
306
0
            d->socket->setSocketOption(QAbstractSocket::LowDelayOption, value);
307
0
        if (option == QAbstractSocketEngine::KeepAliveOption)
308
0
            d->socket->setSocketOption(QAbstractSocket::KeepAliveOption, value);
309
0
        return true;
310
0
    }
311
0
    return false;
312
0
}
313
314
bool QHttpSocketEngine::waitForRead(QDeadlineTimer deadline, bool *timedOut)
315
0
{
316
0
    Q_D(const QHttpSocketEngine);
317
318
0
    if (!d->socket || d->socket->state() == QAbstractSocket::UnconnectedState)
319
0
        return false;
320
321
    // Wait for more data if nothing is available.
322
0
    if (!d->socket->bytesAvailable()) {
323
0
        if (!d->socket->waitForReadyRead(deadline.remainingTime())) {
324
0
            if (d->socket->state() == QAbstractSocket::UnconnectedState)
325
0
                return true;
326
0
            setError(d->socket->error(), d->socket->errorString());
327
0
            if (timedOut && d->socket->error() == QAbstractSocket::SocketTimeoutError)
328
0
                *timedOut = true;
329
0
            return false;
330
0
        }
331
0
    }
332
333
0
    waitForProtocolHandshake(deadline);
334
335
    // Report any error that may occur.
336
0
    if (d->state != Connected) {
337
0
        setError(d->socket->error(), d->socket->errorString());
338
0
        if (timedOut && d->socket->error() == QAbstractSocket::SocketTimeoutError)
339
0
            *timedOut = true;
340
0
        return false;
341
0
    }
342
0
    return true;
343
0
}
344
345
bool QHttpSocketEngine::waitForWrite(QDeadlineTimer deadline, bool *timedOut)
346
0
{
347
0
    Q_D(const QHttpSocketEngine);
348
349
    // If we're connected, just forward the call.
350
0
    if (d->state == Connected) {
351
0
        if (d->socket->bytesToWrite()) {
352
0
            if (!d->socket->waitForBytesWritten(deadline.remainingTime())) {
353
0
                if (d->socket->error() == QAbstractSocket::SocketTimeoutError && timedOut)
354
0
                    *timedOut = true;
355
0
                return false;
356
0
            }
357
0
        }
358
0
        return true;
359
0
    }
360
361
0
    waitForProtocolHandshake(deadline);
362
363
    // Report any error that may occur.
364
0
    if (d->state != Connected) {
365
//        setError(d->socket->error(), d->socket->errorString());
366
0
        if (timedOut && d->socket->error() == QAbstractSocket::SocketTimeoutError)
367
0
            *timedOut = true;
368
0
    }
369
370
0
    return true;
371
0
}
372
373
bool QHttpSocketEngine::waitForReadOrWrite(bool *readyToRead, bool *readyToWrite,
374
                                           bool checkRead, bool checkWrite,
375
                                           QDeadlineTimer deadline, bool *timedOut)
376
0
{
377
0
    Q_UNUSED(checkRead);
378
379
0
    if (!checkWrite) {
380
        // Not interested in writing? Then we wait for read notifications.
381
0
        bool canRead = waitForRead(deadline, timedOut);
382
0
        if (readyToRead)
383
0
            *readyToRead = canRead;
384
0
        return canRead;
385
0
    }
386
387
    // Interested in writing? Then we wait for write notifications.
388
0
    bool canWrite = waitForWrite(deadline, timedOut);
389
0
    if (readyToWrite)
390
0
        *readyToWrite = canWrite;
391
0
    return canWrite;
392
0
}
393
394
void QHttpSocketEngine::waitForProtocolHandshake(QDeadlineTimer deadline) const
395
0
{
396
0
    Q_D(const QHttpSocketEngine);
397
398
    // If we're not connected yet, wait until we are (and until bytes have
399
    // been received, i.e. the socket has connected, we have sent the
400
    // greeting, and then received the response), or until an error occurs.
401
0
    while (d->state != Connected && d->socket->waitForReadyRead(deadline.remainingTime())) {
402
        // Loop while the protocol handshake is taking place.
403
0
    }
404
0
}
405
406
bool QHttpSocketEngine::isReadNotificationEnabled() const
407
0
{
408
0
    Q_D(const QHttpSocketEngine);
409
0
    return d->readNotificationEnabled;
410
0
}
411
412
void QHttpSocketEngine::setReadNotificationEnabled(bool enable)
413
0
{
414
0
    Q_D(QHttpSocketEngine);
415
0
    if (d->readNotificationEnabled == enable)
416
0
        return;
417
418
0
    d->readNotificationEnabled = enable;
419
0
    if (enable) {
420
        // Enabling read notification can trigger a notification.
421
0
        if (bytesAvailable()) {
422
0
            slotSocketReadNotification();
423
0
        } else if (d->socket && d->socket->state() == QAbstractSocket::UnconnectedState) {
424
0
            emitReadNotification();
425
0
        }
426
0
    }
427
0
}
428
429
bool QHttpSocketEngine::isWriteNotificationEnabled() const
430
0
{
431
0
    Q_D(const QHttpSocketEngine);
432
0
    return d->writeNotificationEnabled;
433
0
}
434
435
void QHttpSocketEngine::setWriteNotificationEnabled(bool enable)
436
0
{
437
0
    Q_D(QHttpSocketEngine);
438
0
    d->writeNotificationEnabled = enable;
439
0
    if (enable && d->state == Connected && d->socket->state() == QAbstractSocket::ConnectedState)
440
0
        QMetaObject::invokeMethod(this, "writeNotification", Qt::QueuedConnection);
441
0
}
442
443
bool QHttpSocketEngine::isExceptionNotificationEnabled() const
444
0
{
445
0
    Q_D(const QHttpSocketEngine);
446
0
    return d->exceptNotificationEnabled;
447
0
}
448
449
void QHttpSocketEngine::setExceptionNotificationEnabled(bool enable)
450
0
{
451
0
    Q_D(QHttpSocketEngine);
452
0
    d->exceptNotificationEnabled = enable;
453
0
}
454
455
void QHttpSocketEngine::slotSocketConnected()
456
0
{
457
0
    Q_D(QHttpSocketEngine);
458
459
    // Send the greeting.
460
0
    const char method[] = "CONNECT";
461
0
    QByteArray peerAddress = d->peerName.isEmpty() ?
462
0
                             d->peerAddress.toString().toLatin1() :
463
0
                             QUrl::toAce(d->peerName);
464
0
    QByteArray path = peerAddress + ':' + QByteArray::number(d->peerPort);
465
0
    QByteArray data = method;
466
0
    data += ' ';
467
0
    data += path;
468
0
    data += " HTTP/1.1\r\n";
469
0
    data += "Proxy-Connection: keep-alive\r\n";
470
0
    data += "Host: " + peerAddress + "\r\n";
471
0
    const auto headers = d->proxy.headers();
472
0
    if (!headers.contains(QHttpHeaders::WellKnownHeader::UserAgent))
473
0
        data += "User-Agent: Mozilla/5.0\r\n";
474
0
    for (qsizetype i = 0; i < headers.size(); ++i) {
475
0
        const auto name = headers.nameAt(i);
476
0
        data += QByteArrayView(name.data(), name.size()) + ": "
477
0
                + headers.valueAt(i) + "\r\n";
478
0
    }
479
0
    QAuthenticatorPrivate *priv = QAuthenticatorPrivate::getPrivate(d->authenticator);
480
    //qDebug() << "slotSocketConnected: priv=" << priv << (priv ? (int)priv->method : -1);
481
0
    if (priv && priv->method != QAuthenticatorPrivate::None) {
482
0
        d->credentialsSent = true;
483
0
        data += "Proxy-Authorization: " + priv->calculateResponse(method, path, d->proxy.hostName());
484
0
        data += "\r\n";
485
0
    }
486
0
    data += "\r\n";
487
//     qDebug() << ">>>>>>>> sending request" << this;
488
//     qDebug() << data;
489
//     qDebug(">>>>>>>");
490
0
    d->socket->write(data);
491
0
    d->state = ConnectSent;
492
0
}
493
494
void QHttpSocketEngine::slotSocketDisconnected()
495
0
{
496
0
}
497
498
void QHttpSocketEngine::slotSocketReadNotification()
499
0
{
500
0
    Q_D(QHttpSocketEngine);
501
0
    if (d->state != Connected && d->socket->bytesAvailable() == 0)
502
0
        return;
503
504
0
    if (d->state == Connected) {
505
        // Forward as a read notification.
506
0
        if (d->readNotificationEnabled)
507
0
            emitReadNotification();
508
0
        return;
509
0
    }
510
511
0
    if (d->state == ConnectSent) {
512
0
        d->reply->d_func()->state = QHttpNetworkReplyPrivate::NothingDoneState;
513
0
        d->state = ReadResponseHeader;
514
0
    }
515
516
0
    if (d->state == ReadResponseHeader) {
517
0
        bool ok = readHttpHeader();
518
0
        if (!ok) {
519
            // protocol error, this isn't HTTP
520
0
            d->socket->close();
521
0
            setState(QAbstractSocket::UnconnectedState);
522
0
            setError(QAbstractSocket::ProxyProtocolError, tr("Did not receive HTTP response from proxy"));
523
0
            emitConnectionNotification();
524
0
            return;
525
0
        }
526
0
        if (d->state == ReadResponseHeader)
527
0
            return; // readHttpHeader() was not done yet, need to wait for more header data
528
0
    }
529
530
0
    if (d->state == ReadResponseContent) {
531
0
        qint64 skipped = d->socket->skip(d->pendingResponseData);
532
0
        if (skipped == -1) {
533
0
            d->socket->disconnectFromHost();
534
0
            emitWriteNotification();
535
0
            return;
536
0
        }
537
0
        d->pendingResponseData -= uint(skipped);
538
0
        if (d->pendingResponseData > 0)
539
0
            return;
540
0
        if (d->reply->statusCode() == 407)
541
0
            d->state = SendAuthentication;
542
0
    }
543
544
0
    int statusCode = d->reply->statusCode();
545
0
    QAuthenticatorPrivate *priv = nullptr;
546
0
    if (statusCode == 200) {
547
0
        d->state = Connected;
548
0
        setLocalAddress(d->socket->localAddress());
549
0
        setLocalPort(d->socket->localPort());
550
0
        d->inboundStreamCount = d->outboundStreamCount = 1;
551
0
        setState(QAbstractSocket::ConnectedState);
552
0
        d->authenticator.detach();
553
0
        priv = QAuthenticatorPrivate::getPrivate(d->authenticator);
554
0
        priv->hasFailed = false;
555
0
    } else if (statusCode == 407) {
556
0
        if (d->authenticator.isNull())
557
0
            d->authenticator.detach();
558
0
        priv = QAuthenticatorPrivate::getPrivate(d->authenticator);
559
560
0
        const auto headers = d->reply->header();
561
0
        priv->parseHttpResponse(headers, true, d->proxy.hostName());
562
563
0
        if (priv->phase == QAuthenticatorPrivate::Invalid) {
564
            // problem parsing the reply
565
0
            d->socket->close();
566
0
            setState(QAbstractSocket::UnconnectedState);
567
0
            setError(QAbstractSocket::ProxyProtocolError, tr("Error parsing authentication request from proxy"));
568
0
            emitConnectionNotification();
569
0
            return;
570
0
        }
571
572
0
        if (priv->phase == QAuthenticatorPrivate::Done
573
0
            || (priv->phase == QAuthenticatorPrivate::Start
574
0
                && (priv->method == QAuthenticatorPrivate::Ntlm
575
0
                    || priv->method == QAuthenticatorPrivate::Negotiate))) {
576
0
            if (priv->phase == QAuthenticatorPrivate::Start)
577
0
                priv->phase = QAuthenticatorPrivate::Phase1;
578
0
            bool credentialsWasSent = d->credentialsSent;
579
0
            if (d->credentialsSent) {
580
                // Remember that (e.g.) NTLM is two-phase, so only reset when the authentication is
581
                // not currently in progress. 407 response again means the provided
582
                // username/password were invalid.
583
0
                d->authenticator.detach();
584
0
                priv = QAuthenticatorPrivate::getPrivate(d->authenticator);
585
0
                priv->hasFailed = true;
586
0
                d->credentialsSent = false;
587
0
                priv->phase = QAuthenticatorPrivate::Done;
588
0
            }
589
0
            if ((priv->method != QAuthenticatorPrivate::Ntlm
590
0
                 && priv->method != QAuthenticatorPrivate::Negotiate)
591
0
                || credentialsWasSent)
592
0
                proxyAuthenticationRequired(d->proxy, &d->authenticator);
593
0
        }
594
595
0
        bool willClose;
596
0
        QByteArray proxyConnectionHeader = d->reply->headerField("Proxy-Connection");
597
        // Although most proxies use the unofficial Proxy-Connection header, the Connection header
598
        // from http spec is also allowed.
599
0
        if (proxyConnectionHeader.isEmpty())
600
0
            proxyConnectionHeader = d->reply->headerField("Connection");
601
0
        if (proxyConnectionHeader.compare("close", Qt::CaseInsensitive) == 0) {
602
0
            willClose = true;
603
0
        } else if (proxyConnectionHeader.compare("keep-alive", Qt::CaseInsensitive) == 0) {
604
0
            willClose = false;
605
0
        } else {
606
            // no Proxy-Connection header, so use the default
607
            // HTTP 1.1's default behaviour is to keep persistent connections
608
            // HTTP 1.0 or earlier, so we expect the server to close
609
0
            willClose = (d->reply->majorVersion() * 0x100 + d->reply->minorVersion()) <= 0x0100;
610
0
        }
611
612
0
        if (willClose) {
613
            // the server will disconnect, so let's avoid receiving an error
614
            // especially since the signal below may trigger a new event loop
615
0
            d->socket->disconnectFromHost();
616
0
            d->socket->readAll();
617
            //We're done with the reply and need to reset it for the next connection
618
0
            delete d->reply;
619
0
            d->reply = new QHttpNetworkReply(QUrl(), this);
620
0
        }
621
622
0
        if (priv->phase == QAuthenticatorPrivate::Done) {
623
0
            d->authenticator = QAuthenticator();
624
0
            setError(QAbstractSocket::ProxyAuthenticationRequiredError, tr("Authentication required"));
625
0
            d->socket->disconnectFromHost();
626
0
        } else {
627
            // close the connection if it isn't already and reconnect using the chosen authentication method
628
0
            d->state = SendAuthentication;
629
0
            if (willClose) {
630
0
                d->socket->connectToHost(d->proxy.hostName(), d->proxy.port());
631
0
            } else {
632
                // send the HTTP CONNECT again
633
0
                slotSocketConnected();
634
0
            }
635
0
            return;
636
0
        }
637
0
    } else {
638
0
        d->socket->close();
639
0
        setState(QAbstractSocket::UnconnectedState);
640
0
        if (statusCode == 403 || statusCode == 405) {
641
            // 403 Forbidden
642
            // 405 Method Not Allowed
643
0
            setError(QAbstractSocket::SocketAccessError, tr("Proxy denied connection"));
644
0
        } else if (statusCode == 404) {
645
            // 404 Not Found: host lookup error
646
0
            setError(QAbstractSocket::HostNotFoundError, QAbstractSocket::tr("Host not found"));
647
0
        } else if (statusCode == 503) {
648
            // 503 Service Unavailable: Connection Refused
649
0
            setError(QAbstractSocket::ConnectionRefusedError, QAbstractSocket::tr("Connection refused"));
650
0
        } else {
651
            // Some other reply
652
            //qWarning("UNEXPECTED RESPONSE: [%s]", responseHeader.toString().toLatin1().data());
653
0
            setError(QAbstractSocket::ProxyProtocolError, tr("Error communicating with HTTP proxy"));
654
0
        }
655
0
    }
656
657
    // The handshake is done; notify that we're connected (or failed to connect)
658
0
    emitConnectionNotification();
659
0
}
660
661
bool QHttpSocketEngine::readHttpHeader()
662
0
{
663
0
    Q_D(QHttpSocketEngine);
664
665
0
    if (d->state != ReadResponseHeader)
666
0
        return false;
667
668
0
    bool ok = true;
669
0
    if (d->reply->d_func()->state == QHttpNetworkReplyPrivate::NothingDoneState) {
670
        // do not keep old content sizes, status etc. around
671
0
        d->reply->d_func()->clearHttpLayerInformation();
672
0
        d->reply->d_func()->state = QHttpNetworkReplyPrivate::ReadingStatusState;
673
0
    }
674
0
    if (d->reply->d_func()->state == QHttpNetworkReplyPrivate::ReadingStatusState) {
675
0
        ok = d->reply->d_func()->readStatus(d->socket) != -1;
676
0
        if (ok && d->reply->d_func()->state == QHttpNetworkReplyPrivate::ReadingStatusState)
677
0
            return true; //Not done parsing headers yet, wait for more data
678
0
    }
679
0
    if (ok && d->reply->d_func()->state == QHttpNetworkReplyPrivate::ReadingHeaderState) {
680
0
        ok = d->reply->d_func()->readHeader(d->socket) != -1;
681
0
        if (ok && d->reply->d_func()->state == QHttpNetworkReplyPrivate::ReadingHeaderState)
682
0
            return true; //Not done parsing headers yet, wait for more data
683
0
    }
684
0
    if (ok) {
685
0
        bool contentLengthOk;
686
0
        int contentLength = d->reply->headerField("Content-Length").toInt(&contentLengthOk);
687
0
        if (contentLengthOk && contentLength > 0)
688
0
            d->pendingResponseData = contentLength;
689
0
        d->state = ReadResponseContent; // we are done reading the header
690
0
    }
691
0
    return ok;
692
0
}
693
694
void QHttpSocketEngine::slotSocketBytesWritten()
695
0
{
696
0
    Q_D(QHttpSocketEngine);
697
0
    if (d->state == Connected && d->writeNotificationEnabled)
698
0
        emitWriteNotification();
699
0
}
700
701
void QHttpSocketEngine::slotSocketError(QAbstractSocket::SocketError error)
702
0
{
703
0
    Q_D(QHttpSocketEngine);
704
705
0
    if (d->state != Connected) {
706
        // we are in proxy handshaking stages
707
0
        if (error == QAbstractSocket::HostNotFoundError)
708
0
            setError(QAbstractSocket::ProxyNotFoundError, tr("Proxy server not found"));
709
0
        else if (error == QAbstractSocket::ConnectionRefusedError)
710
0
            setError(QAbstractSocket::ProxyConnectionRefusedError, tr("Proxy connection refused"));
711
0
        else if (error == QAbstractSocket::SocketTimeoutError)
712
0
            setError(QAbstractSocket::ProxyConnectionTimeoutError, tr("Proxy server connection timed out"));
713
0
        else if (error == QAbstractSocket::RemoteHostClosedError)
714
0
            setError(QAbstractSocket::ProxyConnectionClosedError, tr("Proxy connection closed prematurely"));
715
0
        else
716
0
            setError(error, d->socket->errorString());
717
0
        emitConnectionNotification();
718
0
        return;
719
0
    }
720
721
    // We're connected
722
0
    if (error == QAbstractSocket::SocketTimeoutError)
723
0
        return;                 // ignore this error
724
725
0
    d->state = None;
726
0
    setError(error, d->socket->errorString());
727
0
    if (error != QAbstractSocket::RemoteHostClosedError)
728
0
        qDebug() << "QHttpSocketEngine::slotSocketError: got weird error =" << error;
729
    //read notification needs to always be emitted, otherwise the higher layer doesn't get the disconnected signal
730
0
    emitReadNotification();
731
0
}
732
733
void QHttpSocketEngine::slotSocketStateChanged(QAbstractSocket::SocketState state)
734
0
{
735
0
    Q_UNUSED(state);
736
0
}
737
738
void QHttpSocketEngine::emitPendingReadNotification()
739
0
{
740
0
    Q_D(QHttpSocketEngine);
741
0
    d->readNotificationPending = false;
742
0
    if (d->readNotificationEnabled)
743
0
        readNotification();
744
0
}
745
746
void QHttpSocketEngine::emitPendingWriteNotification()
747
0
{
748
0
    Q_D(QHttpSocketEngine);
749
0
    d->writeNotificationPending = false;
750
0
    if (d->writeNotificationEnabled)
751
0
        writeNotification();
752
0
}
753
754
void QHttpSocketEngine::emitPendingConnectionNotification()
755
0
{
756
0
    Q_D(QHttpSocketEngine);
757
0
    d->connectionNotificationPending = false;
758
0
    connectionNotification();
759
0
}
760
761
void QHttpSocketEngine::emitReadNotification()
762
0
{
763
0
    Q_D(QHttpSocketEngine);
764
    // if there is a connection notification pending we have to emit the readNotification
765
    // in case there is connection error. This is only needed for Windows, but it does not
766
    // hurt in other cases.
767
0
    if ((d->readNotificationEnabled && !d->readNotificationPending) || d->connectionNotificationPending) {
768
0
        d->readNotificationPending = true;
769
0
        QMetaObject::invokeMethod(this, "emitPendingReadNotification", Qt::QueuedConnection);
770
0
    }
771
0
}
772
773
void QHttpSocketEngine::emitWriteNotification()
774
0
{
775
0
    Q_D(QHttpSocketEngine);
776
0
    if (d->writeNotificationEnabled && !d->writeNotificationPending) {
777
0
        d->writeNotificationPending = true;
778
0
        QMetaObject::invokeMethod(this, "emitPendingWriteNotification", Qt::QueuedConnection);
779
0
    }
780
0
}
781
782
void QHttpSocketEngine::emitConnectionNotification()
783
0
{
784
0
    Q_D(QHttpSocketEngine);
785
0
    if (!d->connectionNotificationPending) {
786
0
        d->connectionNotificationPending = true;
787
0
        QMetaObject::invokeMethod(this, "emitPendingConnectionNotification", Qt::QueuedConnection);
788
0
    }
789
0
}
790
791
QHttpSocketEnginePrivate::QHttpSocketEnginePrivate()
792
0
    : readNotificationEnabled(false)
793
0
    , writeNotificationEnabled(false)
794
0
    , exceptNotificationEnabled(false)
795
0
    , readNotificationPending(false)
796
0
    , writeNotificationPending(false)
797
0
    , connectionNotificationPending(false)
798
0
    , credentialsSent(false)
799
0
    , pendingResponseData(0)
800
0
{
801
0
    socket = nullptr;
802
0
    reply = nullptr;
803
0
    state = QHttpSocketEngine::None;
804
0
}
805
806
QHttpSocketEnginePrivate::~QHttpSocketEnginePrivate()
807
0
{
808
0
}
809
810
QAbstractSocketEngine *QHttpSocketEngineHandler::createSocketEngine(QAbstractSocket::SocketType socketType,
811
                                                                    const QNetworkProxy &proxy,
812
                                                                    QObject *parent)
813
0
{
814
0
    if (socketType != QAbstractSocket::TcpSocket)
815
0
        return nullptr;
816
817
    // proxy type must have been resolved by now
818
0
    if (proxy.type() != QNetworkProxy::HttpProxy)
819
0
        return nullptr;
820
821
    // we only accept active sockets
822
0
    if (!qobject_cast<QAbstractSocket *>(parent))
823
0
        return nullptr;
824
825
0
    QHttpSocketEngine *engine = new QHttpSocketEngine(parent);
826
0
    engine->setProxy(proxy);
827
0
    return engine;
828
0
}
829
830
QAbstractSocketEngine *QHttpSocketEngineHandler::createSocketEngine(qintptr, QObject *)
831
0
{
832
0
    return nullptr;
833
0
}
834
835
QT_END_NAMESPACE
836
837
#endif // !QT_NO_NETWORKPROXY
838
839
#include "moc_qhttpsocketengine_p.cpp"