1 /****************************************************************************
3 ** Copyright (C) 2014 Kurt Pattyn <pattyn.kurt@gmail.com>.
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:LGPL21$
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 or version 3 as published by the Free
20 ** Software Foundation and appearing in the file LICENSE.LGPLv21 and
21 ** LICENSE.LGPLv3 included in the packaging of this file. Please review the
22 ** following information to ensure the GNU Lesser General Public License
23 ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
24 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
26 ** In addition, as a special exception, Digia gives you certain additional
27 ** rights. These rights are described in the Digia Qt LGPL Exception
28 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
32 ****************************************************************************/
34 #include "qwebsocket.h"
35 #include "qwebsocket_p.h"
36 #include "qwebsocketprotocol_p.h"
37 #include "qwebsockethandshakerequest_p.h"
38 #include "qwebsockethandshakeresponse_p.h"
39 #include "qdefaultmaskgenerator_p.h"
41 #include <QtCore/QUrl>
42 #include <QtNetwork/QAuthenticator>
43 #include <QtNetwork/QTcpSocket>
44 #include <QtCore/QByteArray>
45 #include <QtCore/QtEndian>
46 #include <QtCore/QCryptographicHash>
47 #include <QtCore/QRegularExpression>
48 #include <QtCore/QStringList>
49 #include <QtNetwork/QHostAddress>
50 #include <QtCore/QStringBuilder> //for more efficient string concatenation
51 #ifndef QT_NONETWORKPROXY
52 #include <QtNetwork/QNetworkProxy>
55 #include <QtNetwork/QSslConfiguration>
56 #include <QtNetwork/QSslError>
59 #include <QtCore/QDebug>
65 const quint64 FRAME_SIZE_IN_BYTES = 512 * 512 * 2; //maximum size of a frame when sending a message
67 QWebSocketConfiguration::QWebSocketConfiguration() :
69 m_sslConfiguration(QSslConfiguration::defaultConfiguration()),
71 m_ignoreSslErrors(false),
73 #ifndef QT_NO_NETWORKPROXY
74 m_proxy(QNetworkProxy::DefaultProxy),
83 QWebSocketPrivate::QWebSocketPrivate(const QString &origin, QWebSocketProtocol::Version version,
84 QWebSocket *pWebSocket) :
95 m_socketState(QAbstractSocket::UnconnectedState),
96 m_pauseMode(QAbstractSocket::PauseNever),
100 m_isClosingHandshakeSent(false),
101 m_isClosingHandshakeReceived(false),
102 m_closeCode(QWebSocketProtocol::CloseCodeNormal),
107 m_pMaskGenerator(&m_defaultMaskGenerator),
108 m_defaultMaskGenerator()
115 QWebSocketPrivate::QWebSocketPrivate(QTcpSocket *pTcpSocket, QWebSocketProtocol::Version version,
116 QWebSocket *pWebSocket) :
119 m_pSocket(pTcpSocket),
120 m_errorString(pTcpSocket->errorString()),
127 m_socketState(pTcpSocket->state()),
128 m_pauseMode(pTcpSocket->pauseMode()),
129 m_readBufferSize(pTcpSocket->readBufferSize()),
132 m_isClosingHandshakeSent(false),
133 m_isClosingHandshakeReceived(false),
134 m_closeCode(QWebSocketProtocol::CloseCodeNormal),
139 m_pMaskGenerator(&m_defaultMaskGenerator),
140 m_defaultMaskGenerator()
147 void QWebSocketPrivate::init()
150 Q_ASSERT(m_pMaskGenerator);
152 m_pMaskGenerator->seed();
155 makeConnections(m_pSocket.data());
162 QWebSocketPrivate::~QWebSocketPrivate()
166 if (state() == QAbstractSocket::ConnectedState)
167 close(QWebSocketProtocol::CloseCodeGoingAway, QWebSocket::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
335 if (!url.isValid() || url.toString().contains(QStringLiteral("\r\n"))) {
336 setErrorString(QWebSocket::tr("Invalid URL."));
337 Q_EMIT q->error(QAbstractSocket::ConnectionRefusedError);
340 QTcpSocket *pTcpSocket = m_pSocket.take();
342 releaseConnections(pTcpSocket);
343 pTcpSocket->deleteLater();
346 if (Q_LIKELY(!m_pSocket)) {
347 m_dataProcessor.clear();
348 m_isClosingHandshakeReceived = false;
349 m_isClosingHandshakeSent = false;
352 QString resourceName = url.path();
353 if (resourceName.contains(QStringLiteral("\r\n"))) {
354 setRequestUrl(QUrl()); //clear requestUrl
355 setErrorString(QWebSocket::tr("Invalid resource name."));
356 Q_EMIT q->error(QAbstractSocket::ConnectionRefusedError);
359 if (!url.query().isEmpty()) {
360 if (!resourceName.endsWith(QChar::fromLatin1('?'))) {
361 resourceName.append(QChar::fromLatin1('?'));
363 resourceName.append(url.query());
365 if (resourceName.isEmpty())
366 resourceName = QStringLiteral("/");
367 setResourceName(resourceName);
371 if (url.scheme() == QStringLiteral("wss")) {
372 if (!QSslSocket::supportsSsl()) {
373 const QString message =
374 QWebSocket::tr("SSL Sockets are not supported on this platform.");
375 setErrorString(message);
376 Q_EMIT q->error(QAbstractSocket::UnsupportedSocketOperationError);
378 QSslSocket *sslSocket = new QSslSocket;
379 m_pSocket.reset(sslSocket);
380 if (Q_LIKELY(m_pSocket)) {
381 m_pSocket->setSocketOption(QAbstractSocket::LowDelayOption, 1);
382 m_pSocket->setSocketOption(QAbstractSocket::KeepAliveOption, 1);
383 m_pSocket->setReadBufferSize(m_readBufferSize);
384 m_pSocket->setPauseMode(m_pauseMode);
386 makeConnections(m_pSocket.data());
387 QObject::connect(sslSocket, &QSslSocket::encryptedBytesWritten, q,
388 &QWebSocket::bytesWritten);
389 typedef void (QSslSocket:: *sslErrorSignalType)(const QList<QSslError> &);
390 QObject::connect(sslSocket,
391 static_cast<sslErrorSignalType>(&QSslSocket::sslErrors),
392 q, &QWebSocket::sslErrors);
393 setSocketState(QAbstractSocket::ConnectingState);
395 sslSocket->setSslConfiguration(m_configuration.m_sslConfiguration);
396 if (Q_UNLIKELY(m_configuration.m_ignoreSslErrors))
397 sslSocket->ignoreSslErrors();
399 sslSocket->ignoreSslErrors(m_configuration.m_ignoredSslErrors);
400 #ifndef QT_NO_NETWORKPROXY
401 sslSocket->setProxy(m_configuration.m_proxy);
403 sslSocket->connectToHostEncrypted(url.host(), url.port(443));
405 const QString message = QWebSocket::tr("Out of memory.");
406 setErrorString(message);
407 Q_EMIT q->error(QAbstractSocket::SocketResourceError);
412 if (url.scheme() == QStringLiteral("ws")) {
413 m_pSocket.reset(new QTcpSocket);
414 if (Q_LIKELY(m_pSocket)) {
415 m_pSocket->setSocketOption(QAbstractSocket::LowDelayOption, 1);
416 m_pSocket->setSocketOption(QAbstractSocket::KeepAliveOption, 1);
417 m_pSocket->setReadBufferSize(m_readBufferSize);
418 m_pSocket->setPauseMode(m_pauseMode);
420 makeConnections(m_pSocket.data());
421 QObject::connect(m_pSocket.data(), &QAbstractSocket::bytesWritten, q,
422 &QWebSocket::bytesWritten);
423 setSocketState(QAbstractSocket::ConnectingState);
424 #ifndef QT_NO_NETWORKPROXY
425 m_pSocket->setProxy(m_configuration.m_proxy);
427 m_pSocket->connectToHost(url.host(), url.port(80));
429 const QString message = QWebSocket::tr("Out of memory.");
430 setErrorString(message);
431 Q_EMIT q->error(QAbstractSocket::SocketResourceError);
434 const QString message =
435 QWebSocket::tr("Unsupported WebSocket scheme: %1").arg(url.scheme());
436 setErrorString(message);
437 Q_EMIT q->error(QAbstractSocket::UnsupportedSocketOperationError);
445 void QWebSocketPrivate::ping(const QByteArray &payload)
447 QByteArray payloadTruncated = payload.left(125);
448 m_pingTimer.restart();
449 QByteArray pingFrame = getFrameHeader(QWebSocketProtocol::OpCodePing, payloadTruncated.size(),
450 0 /*do not mask*/, true);
451 pingFrame.append(payloadTruncated);
452 qint64 ret = writeFrame(pingFrame);
458 Sets the version to use for the WebSocket protocol;
459 this must be set before the socket is opened.
461 void QWebSocketPrivate::setVersion(QWebSocketProtocol::Version version)
463 if (m_version != version)
469 Sets the resource name of the connection; must be set before the socket is openend
471 void QWebSocketPrivate::setResourceName(const QString &resourceName)
473 if (m_resourceName != resourceName)
474 m_resourceName = resourceName;
480 void QWebSocketPrivate::setRequestUrl(const QUrl &requestUrl)
482 if (m_requestUrl != requestUrl)
483 m_requestUrl = requestUrl;
489 void QWebSocketPrivate::setOrigin(const QString &origin)
491 if (m_origin != origin)
498 void QWebSocketPrivate::setProtocol(const QString &protocol)
500 if (m_protocol != protocol)
501 m_protocol = protocol;
507 void QWebSocketPrivate::setExtension(const QString &extension)
509 if (m_extension != extension)
510 m_extension = extension;
516 void QWebSocketPrivate::enableMasking(bool enable)
518 if (m_mustMask != enable)
525 void QWebSocketPrivate::makeConnections(const QTcpSocket *pTcpSocket)
527 Q_ASSERT(pTcpSocket);
530 if (Q_LIKELY(pTcpSocket)) {
531 //pass through signals
532 typedef void (QAbstractSocket:: *ASErrorSignal)(QAbstractSocket::SocketError);
533 typedef void (QWebSocket:: *WSErrorSignal)(QAbstractSocket::SocketError);
534 QObject::connect(pTcpSocket,
535 static_cast<ASErrorSignal>(&QAbstractSocket::error),
536 q, static_cast<WSErrorSignal>(&QWebSocket::error));
537 #ifndef QT_NO_NETWORKPROXY
538 QObject::connect(pTcpSocket, &QAbstractSocket::proxyAuthenticationRequired, q,
539 &QWebSocket::proxyAuthenticationRequired);
541 QObject::connect(pTcpSocket, &QAbstractSocket::readChannelFinished, q,
542 &QWebSocket::readChannelFinished);
543 QObject::connect(pTcpSocket, &QAbstractSocket::aboutToClose, q, &QWebSocket::aboutToClose);
546 QObjectPrivate::connect(pTcpSocket, &QAbstractSocket::stateChanged, this,
547 &QWebSocketPrivate::processStateChanged);
548 //!!!important to use a QueuedConnection here;
549 //with QTcpSocket there is no problem, but with QSslSocket the processing hangs
550 QObjectPrivate::connect(pTcpSocket, &QAbstractSocket::readyRead, this,
551 &QWebSocketPrivate::processData, Qt::QueuedConnection);
554 QObject::connect(&m_dataProcessor, &QWebSocketDataProcessor::textFrameReceived, q,
555 &QWebSocket::textFrameReceived);
556 QObject::connect(&m_dataProcessor, &QWebSocketDataProcessor::binaryFrameReceived, q,
557 &QWebSocket::binaryFrameReceived);
558 QObject::connect(&m_dataProcessor, &QWebSocketDataProcessor::binaryMessageReceived, q,
559 &QWebSocket::binaryMessageReceived);
560 QObject::connect(&m_dataProcessor, &QWebSocketDataProcessor::textMessageReceived, q,
561 &QWebSocket::textMessageReceived);
562 QObjectPrivate::connect(&m_dataProcessor, &QWebSocketDataProcessor::errorEncountered, this,
563 &QWebSocketPrivate::close);
564 QObjectPrivate::connect(&m_dataProcessor, &QWebSocketDataProcessor::pingReceived, this,
565 &QWebSocketPrivate::processPing);
566 QObjectPrivate::connect(&m_dataProcessor, &QWebSocketDataProcessor::pongReceived, this,
567 &QWebSocketPrivate::processPong);
568 QObjectPrivate::connect(&m_dataProcessor, &QWebSocketDataProcessor::closeReceived, this,
569 &QWebSocketPrivate::processClose);
575 void QWebSocketPrivate::releaseConnections(const QTcpSocket *pTcpSocket)
577 if (Q_LIKELY(pTcpSocket))
578 pTcpSocket->disconnect(pTcpSocket);
579 m_dataProcessor.disconnect();
585 QWebSocketProtocol::Version QWebSocketPrivate::version() const
593 QString QWebSocketPrivate::resourceName() const
595 return m_resourceName;
601 QUrl QWebSocketPrivate::requestUrl() const
609 QString QWebSocketPrivate::origin() const
617 QString QWebSocketPrivate::protocol() const
625 QString QWebSocketPrivate::extension() const
633 QWebSocketProtocol::CloseCode QWebSocketPrivate::closeCode() const
641 QString QWebSocketPrivate::closeReason() const
643 return m_closeReason;
649 QByteArray QWebSocketPrivate::getFrameHeader(QWebSocketProtocol::OpCode opCode,
650 quint64 payloadLength, quint32 maskingKey,
655 bool ok = payloadLength <= 0x7FFFFFFFFFFFFFFFULL;
658 //FIN, RSV1-3, opcode (RSV-1, RSV-2 and RSV-3 are zero)
659 byte = static_cast<quint8>((opCode & 0x0F) | (lastFrame ? 0x80 : 0x00));
660 header.append(static_cast<char>(byte));
665 if (payloadLength <= 125) {
666 byte |= static_cast<quint8>(payloadLength);
667 header.append(static_cast<char>(byte));
668 } else if (payloadLength <= 0xFFFFU) {
670 header.append(static_cast<char>(byte));
671 quint16 swapped = qToBigEndian<quint16>(static_cast<quint16>(payloadLength));
672 header.append(static_cast<const char *>(static_cast<const void *>(&swapped)), 2);
673 } else if (payloadLength <= 0x7FFFFFFFFFFFFFFFULL) {
675 header.append(static_cast<char>(byte));
676 quint64 swapped = qToBigEndian<quint64>(payloadLength);
677 header.append(static_cast<const char *>(static_cast<const void *>(&swapped)), 8);
680 if (maskingKey != 0) {
681 const quint32 mask = qToBigEndian<quint32>(maskingKey);
682 header.append(static_cast<const char *>(static_cast<const void *>(&mask)),
686 setErrorString(QStringLiteral("WebSocket::getHeader: payload too big!"));
687 Q_EMIT q_ptr->error(QAbstractSocket::DatagramTooLargeError);
696 qint64 QWebSocketPrivate::doWriteFrames(const QByteArray &data, bool isBinary)
698 qint64 payloadWritten = 0;
699 if (Q_UNLIKELY(!m_pSocket) || (state() != QAbstractSocket::ConnectedState))
700 return payloadWritten;
703 const QWebSocketProtocol::OpCode firstOpCode = isBinary ?
704 QWebSocketProtocol::OpCodeBinary : QWebSocketProtocol::OpCodeText;
706 int numFrames = data.size() / FRAME_SIZE_IN_BYTES;
707 QByteArray tmpData(data);
709 char *payload = tmpData.data();
710 quint64 sizeLeft = quint64(data.size()) % FRAME_SIZE_IN_BYTES;
711 if (Q_LIKELY(sizeLeft))
714 //catch the case where the payload is zero bytes;
715 //in this case, we still need to send a frame
716 if (Q_UNLIKELY(numFrames == 0))
718 quint64 currentPosition = 0;
719 qint64 bytesWritten = 0;
720 quint64 bytesLeft = data.size();
722 for (int i = 0; i < numFrames; ++i) {
723 quint32 maskingKey = 0;
725 maskingKey = generateMaskingKey();
727 const bool isLastFrame = (i == (numFrames - 1));
728 const bool isFirstFrame = (i == 0);
730 const quint64 size = qMin(bytesLeft, FRAME_SIZE_IN_BYTES);
731 const QWebSocketProtocol::OpCode opcode = isFirstFrame ? firstOpCode
732 : QWebSocketProtocol::OpCodeContinue;
735 bytesWritten += m_pSocket->write(getFrameHeader(opcode, size, maskingKey, isLastFrame));
738 if (Q_LIKELY(size > 0)) {
739 char *currentData = payload + currentPosition;
741 QWebSocketProtocol::mask(currentData, size, maskingKey);
742 qint64 written = m_pSocket->write(currentData, static_cast<qint64>(size));
743 if (Q_LIKELY(written > 0)) {
744 bytesWritten += written;
745 payloadWritten += written;
748 setErrorString(QWebSocket::tr("Error writing bytes to socket: %1.")
749 .arg(m_pSocket->errorString()));
750 Q_EMIT q->error(QAbstractSocket::NetworkError);
754 currentPosition += size;
757 if (Q_UNLIKELY(payloadWritten != data.size())) {
758 setErrorString(QWebSocket::tr("Bytes written %1 != %2.")
759 .arg(payloadWritten).arg(data.size()));
760 Q_EMIT q->error(QAbstractSocket::NetworkError);
762 return payloadWritten;
768 quint32 QWebSocketPrivate::generateMaskingKey() const
770 return m_pMaskGenerator->nextMask();
776 QByteArray QWebSocketPrivate::generateKey() const
780 for (int i = 0; i < 4; ++i) {
781 const quint32 tmp = m_pMaskGenerator->nextMask();
782 key.append(static_cast<const char *>(static_cast<const void *>(&tmp)), sizeof(quint32));
785 return key.toBase64();
792 QString QWebSocketPrivate::calculateAcceptKey(const QByteArray &key) const
794 const QByteArray tmpKey = key + QByteArrayLiteral("258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
795 const QByteArray hash = QCryptographicHash::hash(tmpKey, QCryptographicHash::Sha1).toBase64();
796 return QString::fromLatin1(hash);
802 qint64 QWebSocketPrivate::writeFrames(const QList<QByteArray> &frames)
805 if (Q_LIKELY(m_pSocket)) {
806 QList<QByteArray>::const_iterator it;
807 for (it = frames.cbegin(); it < frames.cend(); ++it)
808 written += writeFrame(*it);
816 qint64 QWebSocketPrivate::writeFrame(const QByteArray &frame)
819 if (Q_LIKELY(m_pSocket))
820 written = m_pSocket->write(frame);
827 QString readLine(QTcpSocket *pSocket)
832 while (pSocket->getChar(&c)) {
833 if (c == char('\r')) {
834 pSocket->getChar(&c);
837 line.append(QChar::fromLatin1(c));
843 // this function is a copy of QHttpNetworkReplyPrivate::parseStatus
844 static bool parseStatusLine(const QByteArray &status, int *majorVersion, int *minorVersion,
845 int *statusCode, QString *reasonPhrase)
848 // Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF
849 // HTTP-Version = "HTTP" "/" 1*DIGIT "." 1*DIGIT
850 // that makes: 'HTTP/n.n xxx Message'
851 // byte count: 0123456789012
853 static const int minLength = 11;
854 static const int dotPos = 6;
855 static const int spacePos = 8;
856 static const char httpMagic[] = "HTTP/";
858 if (status.length() < minLength
859 || !status.startsWith(httpMagic)
860 || status.at(dotPos) != '.'
861 || status.at(spacePos) != ' ') {
862 // I don't know how to parse this status line
866 // optimize for the valid case: defer checking until the end
867 *majorVersion = status.at(dotPos - 1) - '0';
868 *minorVersion = status.at(dotPos + 1) - '0';
871 int j = status.indexOf(' ', i + 1); // j == -1 || at(j) == ' ' so j+1 == 0 && j+1 <= length()
872 const QByteArray code = status.mid(i + 1, j - i - 1);
875 *statusCode = code.toInt(&ok);
876 *reasonPhrase = QString::fromLatin1(status.constData() + j + 1);
878 return ok && uint(*majorVersion) <= 9 && uint(* minorVersion) <= 9;
882 //called on the client for a server handshake response
886 void QWebSocketPrivate::processHandshake(QTcpSocket *pSocket)
889 if (Q_UNLIKELY(!pSocket))
893 QString errorDescription;
895 const QByteArray statusLine = pSocket->readLine();
896 int httpMajorVersion, httpMinorVersion;
898 QString httpStatusMessage;
899 if (Q_UNLIKELY(!parseStatusLine(statusLine, &httpMajorVersion, &httpMinorVersion,
900 &httpStatusCode, &httpStatusMessage))) {
901 errorDescription = QWebSocket::tr("Invalid statusline in response: %1.").arg(QString::fromLatin1(statusLine));
903 QString headerLine = readLine(pSocket);
904 QMap<QString, QString> headers;
905 while (!headerLine.isEmpty()) {
906 const QStringList headerField = headerLine.split(QStringLiteral(": "),
907 QString::SkipEmptyParts);
908 if (headerField.size() == 2) {
909 headers.insertMulti(headerField[0].toLower(), headerField[1]);
911 headerLine = readLine(pSocket);
914 const QString acceptKey = headers.value(QStringLiteral("sec-websocket-accept"),
916 const QString upgrade = headers.value(QStringLiteral("upgrade"), QString());
917 const QString connection = headers.value(QStringLiteral("connection"), QString());
918 // unused for the moment
919 // const QString extensions = headers.value(QStringLiteral("sec-websocket-extensions"),
921 // const QString protocol = headers.value(QStringLiteral("sec-websocket-protocol"),
923 const QString version = headers.value(QStringLiteral("sec-websocket-version"),
926 if (Q_LIKELY(httpStatusCode == 101)) {
927 //HTTP/x.y 101 Switching Protocols
928 //TODO: do not check the httpStatusText right now
929 ok = !(acceptKey.isEmpty() ||
930 (httpMajorVersion < 1 || httpMinorVersion < 1) ||
931 (upgrade.toLower() != QStringLiteral("websocket")) ||
932 (connection.toLower() != QStringLiteral("upgrade")));
934 const QString accept = calculateAcceptKey(m_key);
935 ok = (accept == acceptKey);
938 QWebSocket::tr("Accept-Key received from server %1 does not match the client key %2.")
939 .arg(acceptKey).arg(accept);
942 QWebSocket::tr("QWebSocketPrivate::processHandshake: Invalid statusline in response: %1.")
943 .arg(QString::fromLatin1(statusLine));
945 } else if (httpStatusCode == 400) {
946 //HTTP/1.1 400 Bad Request
947 if (!version.isEmpty()) {
948 const QStringList versions = version.split(QStringLiteral(", "),
949 QString::SkipEmptyParts);
950 if (!versions.contains(QString::number(QWebSocketProtocol::currentVersion()))) {
951 //if needed to switch protocol version, then we are finished here
952 //because we cannot handle other protocols than the RFC one (v13)
954 QWebSocket::tr("Handshake: Server requests a version that we don't support: %1.")
955 .arg(versions.join(QStringLiteral(", ")));
958 //we tried v13, but something different went wrong
960 QWebSocket::tr("QWebSocketPrivate::processHandshake: Unknown error condition encountered. Aborting connection.");
966 QWebSocket::tr("QWebSocketPrivate::processHandshake: Unhandled http status code: %1 (%2).")
967 .arg(httpStatusCode).arg(httpStatusMessage);
972 setErrorString(errorDescription);
973 Q_EMIT q->error(QAbstractSocket::ConnectionRefusedError);
975 //handshake succeeded
976 setSocketState(QAbstractSocket::ConnectedState);
977 Q_EMIT q->connected();
985 void QWebSocketPrivate::processStateChanged(QAbstractSocket::SocketState socketState)
989 QAbstractSocket::SocketState webSocketState = this->state();
990 switch (socketState) {
991 case QAbstractSocket::ConnectedState:
992 if (webSocketState == QAbstractSocket::ConnectingState) {
993 m_key = generateKey();
994 const QString handshake =
995 createHandShakeRequest(m_resourceName,
997 % QStringLiteral(":")
998 % QString::number(m_requestUrl.port(80)),
1003 if (handshake.isEmpty()) {
1005 Q_EMIT q->error(QAbstractSocket::ConnectionRefusedError);
1008 m_pSocket->write(handshake.toLatin1());
1012 case QAbstractSocket::ClosingState:
1013 if (webSocketState == QAbstractSocket::ConnectedState)
1014 setSocketState(QAbstractSocket::ClosingState);
1017 case QAbstractSocket::UnconnectedState:
1018 if (webSocketState != QAbstractSocket::UnconnectedState) {
1019 setSocketState(QAbstractSocket::UnconnectedState);
1020 Q_EMIT q->disconnected();
1024 case QAbstractSocket::HostLookupState:
1025 case QAbstractSocket::ConnectingState:
1026 case QAbstractSocket::BoundState:
1027 case QAbstractSocket::ListeningState:
1029 //to make C++ compiler happy;
1039 void QWebSocketPrivate::processData()
1041 Q_ASSERT(m_pSocket);
1042 while (m_pSocket->bytesAvailable()) {
1043 if (state() == QAbstractSocket::ConnectingState)
1044 processHandshake(m_pSocket.data());
1046 m_dataProcessor.process(m_pSocket.data());
1053 void QWebSocketPrivate::processPing(const QByteArray &data)
1055 Q_ASSERT(m_pSocket);
1056 quint32 maskingKey = 0;
1058 maskingKey = generateMaskingKey();
1059 m_pSocket->write(getFrameHeader(QWebSocketProtocol::OpCodePong, data.size(), maskingKey, true));
1060 if (data.size() > 0) {
1061 QByteArray maskedData = data;
1063 QWebSocketProtocol::mask(&maskedData, maskingKey);
1064 m_pSocket->write(maskedData);
1071 void QWebSocketPrivate::processPong(const QByteArray &data)
1074 Q_EMIT q->pong(static_cast<quint64>(m_pingTimer.elapsed()), data);
1080 void QWebSocketPrivate::processClose(QWebSocketProtocol::CloseCode closeCode, QString closeReason)
1082 m_isClosingHandshakeReceived = true;
1083 close(closeCode, closeReason);
1089 QString QWebSocketPrivate::createHandShakeRequest(QString resourceName,
1096 QStringList handshakeRequest;
1097 if (resourceName.contains(QStringLiteral("\r\n"))) {
1098 setErrorString(QWebSocket::tr("The resource name contains newlines. " \
1099 "Possible attack detected."));
1102 if (host.contains(QStringLiteral("\r\n"))) {
1103 setErrorString(QWebSocket::tr("The hostname contains newlines. " \
1104 "Possible attack detected."));
1107 if (origin.contains(QStringLiteral("\r\n"))) {
1108 setErrorString(QWebSocket::tr("The origin contains newlines. " \
1109 "Possible attack detected."));
1112 if (extensions.contains(QStringLiteral("\r\n"))) {
1113 setErrorString(QWebSocket::tr("The extensions attribute contains newlines. " \
1114 "Possible attack detected."));
1117 if (protocols.contains(QStringLiteral("\r\n"))) {
1118 setErrorString(QWebSocket::tr("The protocols attribute contains newlines. " \
1119 "Possible attack detected."));
1123 handshakeRequest << QStringLiteral("GET ") % resourceName % QStringLiteral(" HTTP/1.1") <<
1124 QStringLiteral("Host: ") % host <<
1125 QStringLiteral("Upgrade: websocket") <<
1126 QStringLiteral("Connection: Upgrade") <<
1127 QStringLiteral("Sec-WebSocket-Key: ") % QString::fromLatin1(key);
1128 if (!origin.isEmpty())
1129 handshakeRequest << QStringLiteral("Origin: ") % origin;
1130 handshakeRequest << QStringLiteral("Sec-WebSocket-Version: ")
1131 % QString::number(QWebSocketProtocol::currentVersion());
1132 if (extensions.length() > 0)
1133 handshakeRequest << QStringLiteral("Sec-WebSocket-Extensions: ") % extensions;
1134 if (protocols.length() > 0)
1135 handshakeRequest << QStringLiteral("Sec-WebSocket-Protocol: ") % protocols;
1136 handshakeRequest << QStringLiteral("\r\n");
1138 return handshakeRequest.join(QStringLiteral("\r\n"));
1144 QAbstractSocket::SocketState QWebSocketPrivate::state() const
1146 return m_socketState;
1152 void QWebSocketPrivate::setSocketState(QAbstractSocket::SocketState state)
1155 if (m_socketState != state) {
1156 m_socketState = state;
1157 Q_EMIT q->stateChanged(m_socketState);
1164 void QWebSocketPrivate::setErrorString(const QString &errorString)
1166 if (m_errorString != errorString)
1167 m_errorString = errorString;
1173 QHostAddress QWebSocketPrivate::localAddress() const
1175 QHostAddress address;
1176 if (Q_LIKELY(m_pSocket))
1177 address = m_pSocket->localAddress();
1184 quint16 QWebSocketPrivate::localPort() const
1187 if (Q_LIKELY(m_pSocket))
1188 port = m_pSocket->localPort();
1195 QAbstractSocket::PauseModes QWebSocketPrivate::pauseMode() const
1203 QHostAddress QWebSocketPrivate::peerAddress() const
1205 QHostAddress address;
1206 if (Q_LIKELY(m_pSocket))
1207 address = m_pSocket->peerAddress();
1214 QString QWebSocketPrivate::peerName() const
1217 if (Q_LIKELY(m_pSocket))
1218 name = m_pSocket->peerName();
1225 quint16 QWebSocketPrivate::peerPort() const
1228 if (Q_LIKELY(m_pSocket))
1229 port = m_pSocket->peerPort();
1233 #ifndef QT_NO_NETWORKPROXY
1237 QNetworkProxy QWebSocketPrivate::proxy() const
1239 return m_configuration.m_proxy;
1245 void QWebSocketPrivate::setProxy(const QNetworkProxy &networkProxy)
1247 if (m_configuration.m_proxy != networkProxy)
1248 m_configuration.m_proxy = networkProxy;
1250 #endif //QT_NO_NETWORKPROXY
1255 void QWebSocketPrivate::setMaskGenerator(const QMaskGenerator *maskGenerator)
1258 m_pMaskGenerator = &m_defaultMaskGenerator;
1259 else if (maskGenerator != m_pMaskGenerator)
1260 m_pMaskGenerator = const_cast<QMaskGenerator *>(maskGenerator);
1266 const QMaskGenerator *QWebSocketPrivate::maskGenerator() const
1268 Q_ASSERT(m_pMaskGenerator);
1269 return m_pMaskGenerator;
1275 qint64 QWebSocketPrivate::readBufferSize() const
1277 return m_readBufferSize;
1283 void QWebSocketPrivate::resume()
1285 if (Q_LIKELY(m_pSocket))
1286 m_pSocket->resume();
1292 void QWebSocketPrivate::setPauseMode(QAbstractSocket::PauseModes pauseMode)
1294 m_pauseMode = pauseMode;
1295 if (Q_LIKELY(m_pSocket))
1296 m_pSocket->setPauseMode(m_pauseMode);
1302 void QWebSocketPrivate::setReadBufferSize(qint64 size)
1304 m_readBufferSize = size;
1305 if (Q_LIKELY(m_pSocket))
1306 m_pSocket->setReadBufferSize(m_readBufferSize);
1312 bool QWebSocketPrivate::isValid() const
1314 return (m_pSocket && m_pSocket->isValid() &&
1315 (m_socketState == QAbstractSocket::ConnectedState));