1 /****************************************************************************
3 ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/legal
6 ** This file is part of the QtWebSockets module of the Qt Toolkit.
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.
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.
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.
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.
40 ****************************************************************************/
42 #include "qwebsocket.h"
43 #include "qwebsocket_p.h"
44 #include "qwebsocketprotocol_p.h"
45 #include "qwebsockethandshakerequest_p.h"
46 #include "qwebsockethandshakeresponse_p.h"
48 #include <QtCore/QUrl>
49 #include <QtNetwork/QAuthenticator>
50 #include <QtNetwork/QTcpSocket>
51 #include <QtCore/QByteArray>
52 #include <QtCore/QtEndian>
53 #include <QtCore/QCryptographicHash>
54 #include <QtCore/QRegularExpression>
55 #include <QtCore/QStringList>
56 #include <QtNetwork/QHostAddress>
57 #include <QtCore/QStringBuilder> //for more efficient string concatenation
58 #ifndef QT_NONETWORKPROXY
59 #include <QtNetwork/QNetworkProxy>
62 #include <QtNetwork/QSslConfiguration>
63 #include <QtNetwork/QSslError>
66 #include <QtCore/QDebug>
72 const quint64 FRAME_SIZE_IN_BYTES = 512 * 512 * 2; //maximum size of a frame when sending a message
74 QWebSocketConfiguration::QWebSocketConfiguration() :
76 m_sslConfiguration(QSslConfiguration::defaultConfiguration()),
78 m_ignoreSslErrors(false),
80 #ifndef QT_NONETWORKPROXY
81 m_proxy(QNetworkProxy::DefaultProxy)
89 QWebSocketPrivate::QWebSocketPrivate(const QString &origin, QWebSocketProtocol::Version version,
90 QWebSocket *pWebSocket, QObject *parent) :
94 m_errorString(QWebSocket::tr("Unknown error")),
101 m_socketState(QAbstractSocket::UnconnectedState),
102 m_pauseMode(QAbstractSocket::PauseNever),
106 m_isClosingHandshakeSent(false),
107 m_isClosingHandshakeReceived(false),
108 m_closeCode(QWebSocketProtocol::CloseCodeNormal),
120 QWebSocketPrivate::QWebSocketPrivate(QTcpSocket *pTcpSocket, QWebSocketProtocol::Version version,
121 QWebSocket *pWebSocket, QObject *parent) :
124 m_pSocket(pTcpSocket),
125 m_errorString(pTcpSocket->errorString()),
132 m_socketState(pTcpSocket->state()),
133 m_pauseMode(pTcpSocket->pauseMode()),
134 m_readBufferSize(pTcpSocket->readBufferSize()),
137 m_isClosingHandshakeSent(false),
138 m_isClosingHandshakeReceived(false),
139 m_closeCode(QWebSocketProtocol::CloseCodeNormal),
146 makeConnections(m_pSocket.data());
152 void QWebSocketPrivate::init()
155 //TODO: need a better randomizer
156 qsrand(static_cast<uint>(QDateTime::currentMSecsSinceEpoch()));
162 QWebSocketPrivate::~QWebSocketPrivate()
166 if (state() == QAbstractSocket::ConnectedState)
167 close(QWebSocketProtocol::CloseCodeGoingAway, tr("Connection closed"));
168 releaseConnections(m_pSocket.data());
174 void QWebSocketPrivate::abort()
183 QAbstractSocket::SocketError QWebSocketPrivate::error() const
185 QAbstractSocket::SocketError err = QAbstractSocket::UnknownSocketError;
186 if (Q_LIKELY(m_pSocket))
187 err = m_pSocket->error();
194 QString QWebSocketPrivate::errorString() const
197 if (!m_errorString.isEmpty())
198 errMsg = m_errorString;
200 errMsg = m_pSocket->errorString();
207 bool QWebSocketPrivate::flush()
210 if (Q_LIKELY(m_pSocket))
211 result = m_pSocket->flush();
218 qint64 QWebSocketPrivate::sendTextMessage(const QString &message)
220 return doWriteFrames(message.toUtf8(), false);
226 qint64 QWebSocketPrivate::sendBinaryMessage(const QByteArray &data)
228 return doWriteFrames(data, true);
235 void QWebSocketPrivate::setSslConfiguration(const QSslConfiguration &sslConfiguration)
237 m_configuration.m_sslConfiguration = sslConfiguration;
243 QSslConfiguration QWebSocketPrivate::sslConfiguration() const
245 return m_configuration.m_sslConfiguration;
251 void QWebSocketPrivate::ignoreSslErrors(const QList<QSslError> &errors)
253 m_configuration.m_ignoredSslErrors = errors;
259 void QWebSocketPrivate::ignoreSslErrors()
261 m_configuration.m_ignoreSslErrors = true;
262 if (Q_LIKELY(m_pSocket)) {
263 QSslSocket *pSslSocket = qobject_cast<QSslSocket *>(m_pSocket.data());
264 if (Q_LIKELY(pSslSocket))
265 pSslSocket->ignoreSslErrors();
272 Called from QWebSocketServer
275 QWebSocket *QWebSocketPrivate::upgradeFrom(QTcpSocket *pTcpSocket,
276 const QWebSocketHandshakeRequest &request,
277 const QWebSocketHandshakeResponse &response,
280 QWebSocket *pWebSocket = new QWebSocket(pTcpSocket, response.acceptedVersion(), parent);
281 if (Q_LIKELY(pWebSocket)) {
282 pWebSocket->d_func()->setExtension(response.acceptedExtension());
283 pWebSocket->d_func()->setOrigin(request.origin());
284 pWebSocket->d_func()->setRequestUrl(request.requestUrl());
285 pWebSocket->d_func()->setProtocol(response.acceptedProtocol());
286 pWebSocket->d_func()->setResourceName(request.requestUrl().toString(QUrl::RemoveUserInfo));
287 //a server should not send masked frames
288 pWebSocket->d_func()->enableMasking(false);
297 void QWebSocketPrivate::close(QWebSocketProtocol::CloseCode closeCode, QString reason)
299 if (Q_UNLIKELY(!m_pSocket))
301 if (!m_isClosingHandshakeSent) {
303 const quint16 code = qToBigEndian<quint16>(closeCode);
305 payload.append(static_cast<const char *>(static_cast<const void *>(&code)), 2);
306 if (!reason.isEmpty())
307 payload.append(reason.toUtf8());
308 quint32 maskingKey = 0;
310 maskingKey = generateMaskingKey();
311 QWebSocketProtocol::mask(payload.data(), payload.size(), maskingKey);
313 QByteArray frame = getFrameHeader(QWebSocketProtocol::OpCodeClose,
314 payload.size(), maskingKey, true);
315 frame.append(payload);
316 m_pSocket->write(frame);
319 m_isClosingHandshakeSent = true;
321 Q_EMIT q->aboutToClose();
329 void QWebSocketPrivate::open(const QUrl &url, bool mask)
331 //just delete the old socket for the moment;
332 //later, we can add more 'intelligent' handling by looking at the url
334 QTcpSocket *pTcpSocket = m_pSocket.take();
336 releaseConnections(pTcpSocket);
337 pTcpSocket->deleteLater();
340 if (Q_LIKELY(!m_pSocket)) {
343 m_dataProcessor.clear();
344 m_isClosingHandshakeReceived = false;
345 m_isClosingHandshakeSent = false;
348 QString resourceName = url.path();
349 if (!url.query().isEmpty()) {
350 if (!resourceName.endsWith(QChar::fromLatin1('?'))) {
351 resourceName.append(QChar::fromLatin1('?'));
353 resourceName.append(url.query());
355 if (resourceName.isEmpty())
356 resourceName = QStringLiteral("/");
357 setResourceName(resourceName);
361 if (url.scheme() == QStringLiteral("wss")) {
362 if (!QSslSocket::supportsSsl()) {
363 const QString message = tr("SSL Sockets are not supported on this platform.");
364 setErrorString(message);
365 Q_EMIT q->error(QAbstractSocket::UnsupportedSocketOperationError);
367 QSslSocket *sslSocket = new QSslSocket(this);
368 m_pSocket.reset(sslSocket);
369 if (Q_LIKELY(m_pSocket)) {
370 m_pSocket->setSocketOption(QAbstractSocket::LowDelayOption, 1);
371 m_pSocket->setSocketOption(QAbstractSocket::KeepAliveOption, 1);
372 m_pSocket->setReadBufferSize(m_readBufferSize);
373 m_pSocket->setPauseMode(m_pauseMode);
375 makeConnections(m_pSocket.data());
376 connect(sslSocket, &QSslSocket::encryptedBytesWritten, q,
377 &QWebSocket::bytesWritten);
378 setSocketState(QAbstractSocket::ConnectingState);
380 sslSocket->setSslConfiguration(m_configuration.m_sslConfiguration);
381 if (Q_UNLIKELY(m_configuration.m_ignoreSslErrors))
382 sslSocket->ignoreSslErrors();
384 sslSocket->ignoreSslErrors(m_configuration.m_ignoredSslErrors);
385 #ifndef QT_NO_NETWORKPROXY
386 sslSocket->setProxy(m_configuration.m_proxy);
388 sslSocket->connectToHostEncrypted(url.host(), url.port(443));
390 const QString message = tr("Out of memory.");
391 setErrorString(message);
392 Q_EMIT q->error(QAbstractSocket::SocketResourceError);
397 if (url.scheme() == QStringLiteral("ws")) {
398 m_pSocket.reset(new QTcpSocket(this));
399 if (Q_LIKELY(m_pSocket)) {
400 m_pSocket->setSocketOption(QAbstractSocket::LowDelayOption, 1);
401 m_pSocket->setSocketOption(QAbstractSocket::KeepAliveOption, 1);
402 m_pSocket->setReadBufferSize(m_readBufferSize);
403 m_pSocket->setPauseMode(m_pauseMode);
405 makeConnections(m_pSocket.data());
406 connect(m_pSocket.data(), &QAbstractSocket::bytesWritten, q,
407 &QWebSocket::bytesWritten);
408 setSocketState(QAbstractSocket::ConnectingState);
409 #ifndef QT_NO_NETWORKPROXY
410 m_pSocket->setProxy(m_configuration.m_proxy);
412 m_pSocket->connectToHost(url.host(), url.port(80));
414 const QString message = tr("Out of memory.");
415 setErrorString(message);
416 Q_EMIT q->error(QAbstractSocket::SocketResourceError);
419 const QString message = tr("Unsupported websockets scheme: %1").arg(url.scheme());
420 setErrorString(message);
421 Q_EMIT q->error(QAbstractSocket::UnsupportedSocketOperationError);
429 void QWebSocketPrivate::ping(const QByteArray &payload)
431 QByteArray payloadTruncated = payload.left(125);
432 m_pingTimer.restart();
433 QByteArray pingFrame = getFrameHeader(QWebSocketProtocol::OpCodePing, payloadTruncated.size(),
434 0 /*do not mask*/, true);
435 pingFrame.append(payloadTruncated);
436 qint64 ret = writeFrame(pingFrame);
442 Sets the version to use for the websocket protocol;
443 this must be set before the socket is opened.
445 void QWebSocketPrivate::setVersion(QWebSocketProtocol::Version version)
447 if (m_version != version)
453 Sets the resource name of the connection; must be set before the socket is openend
455 void QWebSocketPrivate::setResourceName(const QString &resourceName)
457 if (m_resourceName != resourceName)
458 m_resourceName = resourceName;
464 void QWebSocketPrivate::setRequestUrl(const QUrl &requestUrl)
466 if (m_requestUrl != requestUrl)
467 m_requestUrl = requestUrl;
473 void QWebSocketPrivate::setOrigin(const QString &origin)
475 if (m_origin != origin)
482 void QWebSocketPrivate::setProtocol(const QString &protocol)
484 if (m_protocol != protocol)
485 m_protocol = protocol;
491 void QWebSocketPrivate::setExtension(const QString &extension)
493 if (m_extension != extension)
494 m_extension = extension;
500 void QWebSocketPrivate::enableMasking(bool enable)
502 if (m_mustMask != enable)
509 void QWebSocketPrivate::makeConnections(const QTcpSocket *pTcpSocket)
511 Q_ASSERT(pTcpSocket);
514 if (Q_LIKELY(pTcpSocket)) {
515 //pass through signals
516 typedef void (QAbstractSocket:: *ASErrorSignal)(QAbstractSocket::SocketError);
517 typedef void (QWebSocket:: *WSErrorSignal)(QAbstractSocket::SocketError);
519 static_cast<ASErrorSignal>(&QAbstractSocket::error),
520 q, static_cast<WSErrorSignal>(&QWebSocket::error));
521 connect(pTcpSocket, &QAbstractSocket::proxyAuthenticationRequired, q,
522 &QWebSocket::proxyAuthenticationRequired);
523 connect(pTcpSocket, &QAbstractSocket::readChannelFinished, q,
524 &QWebSocket::readChannelFinished);
525 connect(pTcpSocket, &QAbstractSocket::aboutToClose, q, &QWebSocket::aboutToClose);
528 connect(pTcpSocket, &QAbstractSocket::stateChanged, this,
529 &QWebSocketPrivate::processStateChanged);
530 //!!!important to use a QueuedConnection here;
531 //with QTcpSocket there is no problem, but with QSslSocket the processing hangs
532 connect(pTcpSocket, &QAbstractSocket::readyRead, this,
533 &QWebSocketPrivate::processData, Qt::QueuedConnection);
536 connect(&m_dataProcessor, &QWebSocketDataProcessor::textFrameReceived, q,
537 &QWebSocket::textFrameReceived);
538 connect(&m_dataProcessor, &QWebSocketDataProcessor::binaryFrameReceived, q,
539 &QWebSocket::binaryFrameReceived);
540 connect(&m_dataProcessor, &QWebSocketDataProcessor::binaryMessageReceived, q,
541 &QWebSocket::binaryMessageReceived);
542 connect(&m_dataProcessor, &QWebSocketDataProcessor::textMessageReceived, q,
543 &QWebSocket::textMessageReceived);
544 connect(&m_dataProcessor, &QWebSocketDataProcessor::errorEncountered, this,
545 &QWebSocketPrivate::close);
546 connect(&m_dataProcessor, &QWebSocketDataProcessor::pingReceived, this,
547 &QWebSocketPrivate::processPing);
548 connect(&m_dataProcessor, &QWebSocketDataProcessor::pongReceived, this,
549 &QWebSocketPrivate::processPong);
550 connect(&m_dataProcessor, &QWebSocketDataProcessor::closeReceived, this,
551 &QWebSocketPrivate::processClose);
557 void QWebSocketPrivate::releaseConnections(const QTcpSocket *pTcpSocket)
559 if (Q_LIKELY(pTcpSocket))
560 disconnect(pTcpSocket);
561 disconnect(&m_dataProcessor);
567 QWebSocketProtocol::Version QWebSocketPrivate::version() const
575 QString QWebSocketPrivate::resourceName() const
577 return m_resourceName;
583 QUrl QWebSocketPrivate::requestUrl() const
591 QString QWebSocketPrivate::origin() const
599 QString QWebSocketPrivate::protocol() const
607 QString QWebSocketPrivate::extension() const
615 QWebSocketProtocol::CloseCode QWebSocketPrivate::closeCode() const
623 QString QWebSocketPrivate::closeReason() const
625 return m_closeReason;
631 QByteArray QWebSocketPrivate::getFrameHeader(QWebSocketProtocol::OpCode opCode,
632 quint64 payloadLength, quint32 maskingKey,
637 bool ok = payloadLength <= 0x7FFFFFFFFFFFFFFFULL;
640 //FIN, RSV1-3, opcode (RSV-1, RSV-2 and RSV-3 are zero)
641 byte = static_cast<quint8>((opCode & 0x0F) | (lastFrame ? 0x80 : 0x00));
642 header.append(static_cast<char>(byte));
647 if (payloadLength <= 125) {
648 byte |= static_cast<quint8>(payloadLength);
649 header.append(static_cast<char>(byte));
650 } else if (payloadLength <= 0xFFFFU) {
652 header.append(static_cast<char>(byte));
653 quint16 swapped = qToBigEndian<quint16>(static_cast<quint16>(payloadLength));
654 header.append(static_cast<const char *>(static_cast<const void *>(&swapped)), 2);
655 } else if (payloadLength <= 0x7FFFFFFFFFFFFFFFULL) {
657 header.append(static_cast<char>(byte));
658 quint64 swapped = qToBigEndian<quint64>(payloadLength);
659 header.append(static_cast<const char *>(static_cast<const void *>(&swapped)), 8);
662 if (maskingKey != 0) {
663 const quint32 mask = qToBigEndian<quint32>(maskingKey);
664 header.append(static_cast<const char *>(static_cast<const void *>(&mask)),
668 setErrorString(QStringLiteral("WebSocket::getHeader: payload too big!"));
669 Q_EMIT q_ptr->error(QAbstractSocket::DatagramTooLargeError);
678 qint64 QWebSocketPrivate::doWriteFrames(const QByteArray &data, bool isBinary)
680 qint64 payloadWritten = 0;
681 if (Q_UNLIKELY(!m_pSocket) || (state() != QAbstractSocket::ConnectedState))
682 return payloadWritten;
685 const QWebSocketProtocol::OpCode firstOpCode = isBinary ?
686 QWebSocketProtocol::OpCodeBinary : QWebSocketProtocol::OpCodeText;
688 int numFrames = data.size() / FRAME_SIZE_IN_BYTES;
689 QByteArray tmpData(data);
691 char *payload = tmpData.data();
692 quint64 sizeLeft = quint64(data.size()) % FRAME_SIZE_IN_BYTES;
693 if (Q_LIKELY(sizeLeft))
696 //catch the case where the payload is zero bytes;
697 //in this case, we still need to send a frame
698 if (Q_UNLIKELY(numFrames == 0))
700 quint64 currentPosition = 0;
701 qint64 bytesWritten = 0;
702 quint64 bytesLeft = data.size();
704 for (int i = 0; i < numFrames; ++i) {
705 quint32 maskingKey = 0;
707 maskingKey = generateMaskingKey();
709 const bool isLastFrame = (i == (numFrames - 1));
710 const bool isFirstFrame = (i == 0);
712 const quint64 size = qMin(bytesLeft, FRAME_SIZE_IN_BYTES);
713 const QWebSocketProtocol::OpCode opcode = isFirstFrame ? firstOpCode
714 : QWebSocketProtocol::OpCodeContinue;
717 bytesWritten += m_pSocket->write(getFrameHeader(opcode, size, maskingKey, isLastFrame));
720 if (Q_LIKELY(size > 0)) {
721 char *currentData = payload + currentPosition;
723 QWebSocketProtocol::mask(currentData, size, maskingKey);
724 qint64 written = m_pSocket->write(currentData, static_cast<qint64>(size));
725 if (Q_LIKELY(written > 0)) {
726 bytesWritten += written;
727 payloadWritten += written;
730 setErrorString(tr("Error writing bytes to socket: %1.")
731 .arg(m_pSocket->errorString()));
732 Q_EMIT q->error(QAbstractSocket::NetworkError);
736 currentPosition += size;
739 if (Q_UNLIKELY(payloadWritten != data.size())) {
740 setErrorString(tr("Bytes written %1 != %2.").arg(payloadWritten).arg(data.size()));
741 Q_EMIT q->error(QAbstractSocket::NetworkError);
743 return payloadWritten;
749 quint32 QWebSocketPrivate::generateRandomNumber() const
751 //TODO: need a better randomizer
752 return quint32((double(qrand()) / RAND_MAX) * std::numeric_limits<quint32>::max());
758 quint32 QWebSocketPrivate::generateMaskingKey() const
760 return generateRandomNumber();
766 QByteArray QWebSocketPrivate::generateKey() const
770 for (int i = 0; i < 4; ++i) {
771 const quint32 tmp = generateRandomNumber();
772 key.append(static_cast<const char *>(static_cast<const void *>(&tmp)), sizeof(quint32));
775 return key.toBase64();
782 QString QWebSocketPrivate::calculateAcceptKey(const QByteArray &key) const
784 const QByteArray tmpKey = key + QByteArrayLiteral("258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
785 const QByteArray hash = QCryptographicHash::hash(tmpKey, QCryptographicHash::Sha1).toBase64();
786 return QString::fromLatin1(hash);
792 qint64 QWebSocketPrivate::writeFrames(const QList<QByteArray> &frames)
795 if (Q_LIKELY(m_pSocket)) {
796 QList<QByteArray>::const_iterator it;
797 for (it = frames.cbegin(); it < frames.cend(); ++it)
798 written += writeFrame(*it);
806 qint64 QWebSocketPrivate::writeFrame(const QByteArray &frame)
809 if (Q_LIKELY(m_pSocket))
810 written = m_pSocket->write(frame);
817 QString readLine(QTcpSocket *pSocket)
822 while (pSocket->getChar(&c)) {
823 if (c == char('\r')) {
824 pSocket->getChar(&c);
827 line.append(QChar::fromLatin1(c));
833 //called on the client for a server handshake response
837 void QWebSocketPrivate::processHandshake(QTcpSocket *pSocket)
840 if (Q_UNLIKELY(!pSocket))
844 QString errorDescription;
846 const QString regExpStatusLine(QStringLiteral("^(HTTP/[0-9]+\\.[0-9]+)\\s([0-9]+)\\s(.*)"));
847 const QRegularExpression regExp(regExpStatusLine);
848 const QString statusLine = readLine(pSocket);
849 QString httpProtocol;
851 QString httpStatusMessage;
852 const QRegularExpressionMatch match = regExp.match(statusLine);
853 if (Q_LIKELY(match.hasMatch())) {
854 QStringList tokens = match.capturedTexts();
855 tokens.removeFirst(); //remove the search string
856 if (tokens.length() == 3) {
857 httpProtocol = tokens[0];
858 httpStatusCode = tokens[1].toInt();
859 httpStatusMessage = tokens[2].trimmed();
863 if (Q_UNLIKELY(!ok)) {
864 errorDescription = tr("Invalid statusline in response: %1.").arg(statusLine);
866 QString headerLine = readLine(pSocket);
867 QMap<QString, QString> headers;
868 while (!headerLine.isEmpty()) {
869 const QStringList headerField = headerLine.split(QStringLiteral(": "),
870 QString::SkipEmptyParts);
871 headers.insertMulti(headerField[0], headerField[1]);
872 headerLine = readLine(pSocket);
875 const QString acceptKey = headers.value(QStringLiteral("Sec-WebSocket-Accept"),
877 const QString upgrade = headers.value(QStringLiteral("Upgrade"), QString());
878 const QString connection = headers.value(QStringLiteral("Connection"), QString());
879 // unused for the moment
880 // const QString extensions = headers.value(QStringLiteral("Sec-WebSocket-Extensions"),
882 // const QString protocol = headers.value(QStringLiteral("Sec-WebSocket-Protocol"),
884 const QString version = headers.value(QStringLiteral("Sec-WebSocket-Version"),
887 if (Q_LIKELY(httpStatusCode == 101)) {
888 //HTTP/x.y 101 Switching Protocols
889 bool conversionOk = false;
890 const float version = httpProtocol.midRef(5).toFloat(&conversionOk);
891 //TODO: do not check the httpStatusText right now
892 ok = !(acceptKey.isEmpty() ||
893 (!conversionOk || (version < 1.1f)) ||
894 (upgrade.toLower() != QStringLiteral("websocket")) ||
895 (connection.toLower() != QStringLiteral("upgrade")));
897 const QString accept = calculateAcceptKey(m_key);
898 ok = (accept == acceptKey);
901 tr("Accept-Key received from server %1 does not match the client key %2.")
902 .arg(acceptKey).arg(accept);
905 tr("QWebSocketPrivate::processHandshake: Invalid statusline in response: %1.")
908 } else if (httpStatusCode == 400) {
909 //HTTP/1.1 400 Bad Request
910 if (!version.isEmpty()) {
911 const QStringList versions = version.split(QStringLiteral(", "),
912 QString::SkipEmptyParts);
913 if (!versions.contains(QString::number(QWebSocketProtocol::currentVersion()))) {
914 //if needed to switch protocol version, then we are finished here
915 //because we cannot handle other protocols than the RFC one (v13)
917 tr("Handshake: Server requests a version that we don't support: %1.")
918 .arg(versions.join(QStringLiteral(", ")));
921 //we tried v13, but something different went wrong
923 tr("QWebSocketPrivate::processHandshake: Unknown error condition " \
924 "encountered. Aborting connection.");
930 tr("QWebSocketPrivate::processHandshake: Unhandled http status code: %1 (%2).")
931 .arg(httpStatusCode).arg(httpStatusMessage);
936 setErrorString(errorDescription);
937 Q_EMIT q->error(QAbstractSocket::ConnectionRefusedError);
939 //handshake succeeded
940 setSocketState(QAbstractSocket::ConnectedState);
941 Q_EMIT q->connected();
949 void QWebSocketPrivate::processStateChanged(QAbstractSocket::SocketState socketState)
953 QAbstractSocket::SocketState webSocketState = this->state();
954 switch (socketState) {
955 case QAbstractSocket::ConnectedState:
956 if (webSocketState == QAbstractSocket::ConnectingState) {
957 m_key = generateKey();
958 const QString handshake =
959 createHandShakeRequest(m_resourceName,
961 % QStringLiteral(":")
962 % QString::number(m_requestUrl.port(80)),
967 m_pSocket->write(handshake.toLatin1());
971 case QAbstractSocket::ClosingState:
972 if (webSocketState == QAbstractSocket::ConnectedState)
973 setSocketState(QAbstractSocket::ClosingState);
976 case QAbstractSocket::UnconnectedState:
977 if (webSocketState != QAbstractSocket::UnconnectedState) {
978 setSocketState(QAbstractSocket::UnconnectedState);
979 Q_EMIT q->disconnected();
983 case QAbstractSocket::HostLookupState:
984 case QAbstractSocket::ConnectingState:
985 case QAbstractSocket::BoundState:
986 case QAbstractSocket::ListeningState:
988 //to make C++ compiler happy;
998 void QWebSocketPrivate::processData()
1000 Q_ASSERT(m_pSocket);
1001 while (m_pSocket->bytesAvailable()) {
1002 if (state() == QAbstractSocket::ConnectingState)
1003 processHandshake(m_pSocket.data());
1005 m_dataProcessor.process(m_pSocket.data());
1012 void QWebSocketPrivate::processPing(const QByteArray &data)
1014 Q_ASSERT(m_pSocket);
1015 quint32 maskingKey = 0;
1017 maskingKey = generateMaskingKey();
1018 m_pSocket->write(getFrameHeader(QWebSocketProtocol::OpCodePong, data.size(), maskingKey, true));
1019 if (data.size() > 0) {
1020 QByteArray maskedData = data;
1022 QWebSocketProtocol::mask(&maskedData, maskingKey);
1023 m_pSocket->write(maskedData);
1030 void QWebSocketPrivate::processPong(const QByteArray &data)
1033 Q_EMIT q->pong(static_cast<quint64>(m_pingTimer.elapsed()), data);
1039 void QWebSocketPrivate::processClose(QWebSocketProtocol::CloseCode closeCode, QString closeReason)
1041 m_isClosingHandshakeReceived = true;
1042 close(closeCode, closeReason);
1048 QString QWebSocketPrivate::createHandShakeRequest(QString resourceName,
1055 QStringList handshakeRequest;
1057 handshakeRequest << QStringLiteral("GET ") % resourceName % QStringLiteral(" HTTP/1.1") <<
1058 QStringLiteral("Host: ") % host <<
1059 QStringLiteral("Upgrade: websocket") <<
1060 QStringLiteral("Connection: Upgrade") <<
1061 QStringLiteral("Sec-WebSocket-Key: ") % QString::fromLatin1(key);
1062 if (!origin.isEmpty())
1063 handshakeRequest << QStringLiteral("Origin: ") % origin;
1064 handshakeRequest << QStringLiteral("Sec-WebSocket-Version: ")
1065 % QString::number(QWebSocketProtocol::currentVersion());
1066 if (extensions.length() > 0)
1067 handshakeRequest << QStringLiteral("Sec-WebSocket-Extensions: ") % extensions;
1068 if (protocols.length() > 0)
1069 handshakeRequest << QStringLiteral("Sec-WebSocket-Protocol: ") % protocols;
1070 handshakeRequest << QStringLiteral("\r\n");
1072 return handshakeRequest.join(QStringLiteral("\r\n"));
1078 QAbstractSocket::SocketState QWebSocketPrivate::state() const
1080 return m_socketState;
1086 void QWebSocketPrivate::setSocketState(QAbstractSocket::SocketState state)
1089 if (m_socketState != state) {
1090 m_socketState = state;
1091 Q_EMIT q->stateChanged(m_socketState);
1098 void QWebSocketPrivate::setErrorString(const QString &errorString)
1100 if (m_errorString != errorString)
1101 m_errorString = errorString;
1107 QHostAddress QWebSocketPrivate::localAddress() const
1109 QHostAddress address;
1110 if (Q_LIKELY(m_pSocket))
1111 address = m_pSocket->localAddress();
1118 quint16 QWebSocketPrivate::localPort() const
1121 if (Q_LIKELY(m_pSocket))
1122 port = m_pSocket->localPort();
1129 QAbstractSocket::PauseModes QWebSocketPrivate::pauseMode() const
1137 QHostAddress QWebSocketPrivate::peerAddress() const
1139 QHostAddress address;
1140 if (Q_LIKELY(m_pSocket))
1141 address = m_pSocket->peerAddress();
1148 QString QWebSocketPrivate::peerName() const
1151 if (Q_LIKELY(m_pSocket))
1152 name = m_pSocket->peerName();
1159 quint16 QWebSocketPrivate::peerPort() const
1162 if (Q_LIKELY(m_pSocket))
1163 port = m_pSocket->peerPort();
1167 #ifndef QT_NO_NETWORKPROXY
1171 QNetworkProxy QWebSocketPrivate::proxy() const
1173 return m_configuration.m_proxy;
1179 void QWebSocketPrivate::setProxy(const QNetworkProxy &networkProxy)
1181 if (networkProxy != networkProxy)
1182 m_configuration.m_proxy = networkProxy;
1184 #endif //QT_NO_NETWORKPROXY
1189 qint64 QWebSocketPrivate::readBufferSize() const
1191 return m_readBufferSize;
1197 void QWebSocketPrivate::resume()
1199 if (Q_LIKELY(m_pSocket))
1200 m_pSocket->resume();
1206 void QWebSocketPrivate::setPauseMode(QAbstractSocket::PauseModes pauseMode)
1208 m_pauseMode = pauseMode;
1209 if (Q_LIKELY(m_pSocket))
1210 m_pSocket->setPauseMode(m_pauseMode);
1216 void QWebSocketPrivate::setReadBufferSize(qint64 size)
1218 m_readBufferSize = size;
1219 if (Q_LIKELY(m_pSocket))
1220 m_pSocket->setReadBufferSize(m_readBufferSize);
1226 bool QWebSocketPrivate::isValid() const
1228 return (m_pSocket && m_pSocket->isValid() &&
1229 (m_socketState == QAbstractSocket::ConnectedState));