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