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